{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n var ans = 1e9.toInt + 10\n var ansT = -1\n REP(100, 1) { t =>\n var cost = 0\n REP(N) { i =>\n if (abs(A(i) - t) > 1) {\n cost += abs(A(i) - t) - 1\n }\n }\n if (cost < ans) {\n ans = cost\n ansT = t\n }\n }\n out.println(s\"$ansT $ans\")\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject SalemsGame {\n\n\n def step(l: List[Int], sum: Long, n: Int): (Int, Long) =\n if (absSum(l) >= sum) (n - 1, sum)\n else step(l.map(_ - 1), absSum(l), n + 1)\n\n def absSum(l: List[Int]): Long = l.toStream\n .filter(Math.abs(_) > 1)\n .map(Math.abs)\n .map(_ - 1)\n .sum\n\n def main(args: Array[String]): Unit = {\n val skip = StdIn.readLine()\n val res = StdIn.readLine().split(\" \").map(_.toInt).toList\n val (a, b) = step(res.map(_ - 1), Long.MaxValue, 1)\n println(s\"$a $b\")\n }\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject SalemsGame {\n\n\n def step(l: List[Int], sum: Long, n: Int): (Int, Long) =\n if (absSum(l) >= sum) (n - 1, sum)\n else step(l.map(_ - 1), absSum(l), n + 1)\n\n def absSum(l: List[Int]): Long = l.toStream\n .filter(Math.abs(_) > 1)\n .map(Math.abs)\n .map(_ - 1)\n .sum\n\n def main(args: Array[String]): Unit = {\n val skip = StdIn.readLine()\n val res = StdIn.readLine().split(\" \").map(_.toInt).toList\n val (a, b) = step(res, Long.MaxValue, 1)\n println(s\"$a $b\")\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject SalemsGame {\n\n\n def step(l: List[Int], sum: Long, n: Int): (Int, Long) =\n if (absSum(l) >= sum) (n - 1, sum)\n else step(l.map(_ - 1), absSum(l), n + 1)\n\n def absSum(l: List[Int]): Long = l.toStream\n .filter(Math.abs(_) > 1)\n .map(Math.abs)\n .map(_ - 1)\n .sum\n\n def main(args: Array[String]): Unit = {\n val skip = StdIn.readLine()\n val res = StdIn.readLine().split(\" \").map(_.toInt).toList\n val (a, b) = step(res, Long.MaxValue, 0)\n println(s\"$a $b\")\n }\n}"}], "src_uid": "bce9ebad1dc8bd5aae516c4ca9e551c0"} {"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val qs = Array.fill(n){ readLine.toInt }\n\n val res = for {\n q <- qs\n r1 = if (q >= 9 && (q - 9) % 4 == 0) 1 + (q - 9) / 4 else -1\n r2 = if (q >= 6 && (q - 6) % 4 == 0) 1 + (q - 6) / 4 else -1\n r3 = if (q >= 15 && (q - 15) % 4 == 0) 2 + (q - 15) / 4 else -1\n r4 = if (q % 4 == 0) q / 4 else -1\n } yield Seq(r1, r2, r3, r4).max\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\"\\n\"))\n\n Console.flush\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\nimport scala.math.pow\nimport scala.collection.mutable._\n\nobject Main {\n implicit def bool2int(b: Boolean): Int = { if(b) 1 else 0 }\n\n def main(args: Array[String]): Unit = {\n val memoized = memoizedSolution\n (1 to readInt).foreach { _ => println(memoized(readInt)) }\n }\n\n def memoizedSolution: Int => Int = {\n def querySolution(i: Int) = {\n i match {\n case i if i % 4 == 0 => i / 4\n case i if i >= 6 && (i - 6) % 4 == 0 => (i - 6) / 4 + 1\n case i if i >= 9 && (i - 9) % 4 == 0 => (i - 9) / 4 + 1\n case i if i >= 15 && (i - 15) % 4 == 0 => (i - 15) / 4 + 2\n case _ => -1\n }\n }\n\n val map = Map[Int, Int]()\n\n i => map.getOrElse(i, {\n val solution = querySolution(i)\n map.put(i, solution)\n solution\n })\n }\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.math.pow\nimport scala.collection.mutable._\n\nobject Main {\n implicit def bool2int(b: Boolean): Int = { if(b) 1 else 0 }\n\n def main(args: Array[String]): Unit = {\n (1 to readInt).foreach { _ => println(querySolution(readInt)) }\n }\n\n def querySolution(i: Int): Int = {\n i match {\n case i if i % 4 == 0 => i / 4\n case i if i >= 6 && (i - 6) % 4 == 0 => (i - 6) / 4 + 1\n case i if i >= 9 && (i - 9) % 4 == 0 => (i - 9) / 4 + 1\n case i if i >= 15 && (i - 15) % 4 == 0 => (i - 15) / 4 + 2\n case _ => -1\n }\n }\n}\n"}], "negative_code": [], "src_uid": "0c2550b2df0849a62969edf5b73e0ac5"} {"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject B {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(2 * n).zipWithIndex\n\n val (even, odd) = as.partition(_._1 % 2 == 0)\n\n val evenQ = mutable.Queue(even: _*)\n val oddQ = mutable.Queue(odd: _*)\n\n val res = ArrayBuffer.empty[String]\n while (oddQ.size > 2) {\n val a, b = oddQ.dequeue()\n res += s\"${a._2 + 1} ${b._2 + 1}\"\n }\n\n val lim = if (odd.isEmpty) 2 else 1\n while (evenQ.size > lim) {\n val a, b = evenQ.dequeue()\n res += s\"${a._2 + 1} ${b._2 + 1}\"\n }\n\n out.println(res.mkString(\"\\n\"))\n\n out.flush()\n }\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "\nobject B extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n import scala.collection.mutable\n import scala.collection.mutable.ArrayBuffer\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n// val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val n = in.nextInt()\n\n n.times {\n val m = in.nextInt()\n\n var oddIndex = mutable.ArrayBuffer[Int]()\n var evenIndex = mutable.ArrayBuffer[Int]()\n\n 1.to(m * 2)\n .foreach(i => {\n val d = in.nextInt()\n if (d % 2 == 0) {\n evenIndex :+= i\n } else {\n oddIndex :+= i\n }\n })\n\n if (oddIndex.size % 2 == 1 && evenIndex.size % 2 == 1) {\n printGrouped(oddIndex.drop(1))\n printGrouped(evenIndex.drop(1))\n } else {\n if (oddIndex.size >= 2) {\n printGrouped(oddIndex.drop(2))\n printGrouped(evenIndex)\n } else {\n printGrouped(evenIndex.drop(2))\n printGrouped(oddIndex)\n }\n }\n }\n\n def printGrouped(list: ArrayBuffer[Int]) = {\n if (list.nonEmpty) {\n for (x <- list.grouped(2)) {\n println(s\"${x(0)} ${x(1)}\")\n }\n }\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val t = readInt\n (0 until t).foreach { i =>\n val n = readInt\n val arrWithIndex = readLine.split(\" \").map(_.toInt).zipWithIndex.toList\n val even = arrWithIndex.filter(x => (x._1 % 2) == 0)\n val evenG = even.grouped(2).toList\n val odd = arrWithIndex.filter(x => (x._1 % 2) != 0)\n val oddG = odd.grouped(2).toList\n val evenPairs = (if ((even.size % 2) != 0) evenG.dropRight(1) else evenG) map { case List((x1, x2), (y1, y2)) => (x2, y2) }\n val oddPairs = (if ((odd.size % 2) != 0) oddG.dropRight(1) else oddG) map { case List((x1, x2), (y1, y2)) => (x2, y2) }\n val result = evenPairs ++ oddPairs\n val finalResult = if (result.size > n - 1) result.dropRight(1) else result\n finalResult foreach { k => println(s\"${k._1 + 1} ${k._2 + 1}\") }\n }\n }\n}\n"}], "negative_code": [{"source_code": "\nobject B extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n import scala.collection.mutable\n import scala.collection.mutable.ArrayBuffer\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n// val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val n = in.nextInt()\n\n n.times {\n val m = in.nextInt()\n\n var oddIndex = mutable.ArrayBuffer[Int]()\n var evenIndex = mutable.ArrayBuffer[Int]()\n\n 1.to(m * 2)\n .foreach(i => {\n val d = in.nextInt()\n if (d % 2 == 0) {\n evenIndex :+= i\n }\n if (d % 2 == 1) {\n oddIndex :+= i\n }\n })\n\n if (oddIndex.size % 2 == 1 && evenIndex.size % 2 == 1) {\n printGrouped(oddIndex.take(oddIndex.size - 1))\n printGrouped(evenIndex.take(evenIndex.size - 1))\n } else {\n if (oddIndex.size >= 2) {\n printGrouped(oddIndex.take(oddIndex.size - 2))\n printGrouped(evenIndex)\n } else {\n printGrouped(evenIndex.take(oddIndex.size - 2))\n printGrouped(oddIndex)\n }\n }\n }\n\n def printGrouped(list: ArrayBuffer[Int]) = {\n for (x <- list.grouped(2)) {\n println(s\"${x(0)} ${x(1)}\")\n }\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}], "src_uid": "96fac9f9377bf03e144067bf93716d3d"} {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.Ordering.Implicits._\nimport scala.collection.immutable.Queue\nimport scala.collection.mutable.ArrayBuffer\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def lowerBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (!(array(mid) < value)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def solve(): Unit = {\n val n = nextInt\n val position = new Array[Int](n)\n val height = new Array[Int](n)\n val dp = Array.ofDim[Int](n, 2)\n\n for (i <- 0 until n) {\n position(i) = nextInt\n height(i) = nextInt\n }\n dp(0)(0) = 1\n if (n != 1 && position(0) + height(0) < position(1)) {\n dp(0)(1) = 1\n }\n for (i <- 1 until n) {\n if (position(i - 1) + height(i - 1) + height(i) < position(i)) {\n dp(i)(0) = math.max(dp(i)(0), dp(i - 1)(1) + 1)\n }\n if (position(i - 1) + height(i) < position(i)) {\n dp(i)(0) = math.max(dp(i)(0), dp(i - 1)(0) + 1)\n }\n if (i + 1 >= n ||\n position(i) + height(i) < position(i + 1)) {\n dp(i)(1) = math.max(dp(i - 1)(0), dp(i - 1)(1)) + 1\n }\n dp(i)(0) = math.max(dp(i - 1)(0), dp(i)(0))\n dp(i)(0) = math.max(dp(i - 1)(1), dp(i)(0))\n }\n\n println(dp(n - 1).max)\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve()\n out.close\n }\n}\n", "positive_code": [{"source_code": "object C545 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n case class Tree(x: Long, h: Long)\n val input = new Array[Tree](n)\n for(i <- 0 until n) {\n val Array(x, h) = readLongs(2)\n input(i) = Tree(x, h)\n }\n var ret = if(input.length > 1) 2 else 1\n for(i <- 1 until n-1) {\n if(input(i).x - input(i).h > input(i-1).x){\n ret +=1\n } else if (input(i).x + input(i).h < input(i+1).x) {\n input(i) = Tree(input(i).x + input(i).h, input(i).h)\n ret += 1\n }\n }\n println(ret)\n }\n}"}, {"source_code": "object _545C extends CodeForcesApp {\n import scala.collection.mutable\n\n override type Input = IndexedSeq[(Long, Long)]\n override type Output = Int\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n IndexedSeq.fill(nextInt)((nextLong, nextLong))\n }\n\n override def solve(input: Input) = {\n var count = 0\n var curX = -2e9\n\n def chop(from: Long, to: Long) = {\n //debug(\"Chopped\", from, to)\n curX = to\n count += 1\n }\n\n for {\n ((x, h), i) <- input.zipWithIndex\n } {\n if(curX < x - h) {\n chop(x-h, x)\n } else {\n if (i == input.length - 1) {\n chop(x, x+h)\n } else {\n val (nextX, _) = input(i+1)\n if (x+h < nextX) {\n chop(x, x+h)\n } else {\n curX = x\n }\n }\n }\n }\n\n count\n }\n\n override def format(result: Output) = super.format(result)\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp extends App {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /********************************[ lib ]************************************/\n import scala.collection.mutable\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type m_=>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None\n /******************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n def timeLimitSecond = 1\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n case class Tree (x:Int, h:Int) {\n def x_left = x - h;\n def x_centre = x;\n def x_right = x + h;\n\n var dp_left = 0;\n var dp_center = 0;\n var dp_right = 0;\n }\n\n def main(args: Array[String]) {\n val trees : Array[Tree] =\n (1 to StdIn.readInt()).map(_ =>\n StdIn.readLine.split(\" \").map(Integer.parseInt) match {\n case Array(f, s) => new Tree(f, s)\n }).toArray;\n\n trees(0).dp_left = 1;\n \n def handle_trees = (tr1 : Tree, tr2 : Tree) =>\n Seq((tr1.x_centre, tr1.dp_left), (tr1.x_centre, tr1.dp_center), (tr1.x_right, tr1.dp_right)) map {\n case (x, dp) =>\n if(x < tr2.x_left)\n tr2.dp_left = math.max(dp + 1, tr2.dp_left);\n else if(x < tr2.x_centre) {\n tr2.dp_center = math.max(dp, tr2.dp_center);\n tr2.dp_right = math.max(dp + 1, tr2.dp_right);\n }\n }\n \n for(i <- trees.indices.tail) {\n handle_trees(trees(i-1), trees(i));\n }\n\n println(math.max(trees.last.dp_left, trees.last.dp_right));\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n val Trees = new Array[(Int, Int)](n)\n\n for (i <- 0 until n) {\n val line = readLine().split(\" \").map(_.toInt)\n Trees(i) = (line(0), line(1))\n }\n\n def solve(): Int = {\n var result = 0\n var lastOccupied = 0\n for (i <- 0 until n) {\n if (i == 0) {\n result += 1\n lastOccupied = Trees(0)._1\n }\n else if (i == n - 1) result += 1\n else {\n val (x, h) = Trees(i)\n if (lastOccupied < x - h) {\n// println(s\"left fall $i\")\n result += 1\n lastOccupied = x\n } else if (x + h < Trees(i + 1)._1) {\n// println(s\"fall $i\")\n result += 1\n lastOccupied = x + h\n } else {\n lastOccupied = x\n }\n\n }\n }\n result\n }\n\n println(solve())\n}\n"}, {"source_code": "object C{\n def main(args: Array[String]){\n val in=io.Source.stdin.getLines()\n val n=in.next().toInt\n var x= new Array[Int](n)\n var h=new Array[Int](n)\n for(i <- 0 until n){\n val t=in.next().split(\" \")\n x(i) = t(0).toInt\n\n h(i) = t(1).toInt\n\n }\n var (nl,nr)=(1,1)\n \n if(n>1){\n nl=1\n nr=if(x(0)+h(0)x(i-1)){\n nl=nl0+1\n }\n else{\n nl=nl0\n }\n if(nr0>nl){\n nl=nr0\n }\n if(x(i)-h(i)>x(i-1)+h(i-1)){\n if(nr0+1>nl){\n nl=nr0+1\n }\n }\n if(i==n-1||x(i)+h(i)nr0){\n nr=nl0+1\n }\n else{\n nr=nr0+1\n }\n }\n }\n println(nr)\n }\n}\n"}], "negative_code": [{"source_code": "object C545 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n case class Tree(x: Long, h: Long)\n val input = new Array[Tree](n)\n for(i <- 0 until n) {\n val Array(x, h) = readLongs(2)\n input(i) = Tree(x, h)\n }\n var ret = 2\n for(i <- 1 until n-1) {\n if((input(i).x - input(i).h > input(i-1).x) || (input(i).x + input(i).h < input(i+1).x)) {\n ret += 1\n }\n }\n println(ret)\n }\n}"}, {"source_code": "object C545 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n case class Tree(x: Long, h: Long)\n val input = new Array[Tree](n)\n for(i <- 0 until n) {\n val Array(x, h) = readLongs(2)\n input(i) = Tree(x, h)\n }\n var ret = 2\n for(i <- 1 until n-1) {\n if(input(i).x - input(i).h > input(i-1).x){\n ret +=1\n } else if (input(i).x + input(i).h < input(i+1).x) {\n input(i) = Tree(input(i).x + input(i).h, input(i).h)\n ret += 1\n }\n }\n println(ret)\n }\n}"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.Ordering.Implicits._\nimport scala.collection.immutable.Queue\nimport scala.collection.mutable.ArrayBuffer\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def lowerBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (!(array(mid) < value)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def solve(): Unit = {\n val n = nextInt\n val position = new Array[Int](n)\n val height = new Array[Int](n)\n val dp = Array.ofDim[Int](n, 2)\n\n for (i <- 0 until n) {\n position(i) = nextInt\n height(i) = nextInt\n }\n dp(0)(0) = 1\n if (position(0) + height(0) < position(1)) {\n dp(0)(1) = 1\n }\n for (i <- 1 until n) {\n if (position(i - 1) + height(i - 1) + height(i) < position(i)) {\n dp(i)(0) = math.max(dp(i)(0), dp(i - 1)(1) + 1)\n }\n if (position(i - 1) + height(i) < position(i)) {\n dp(i)(0) = math.max(dp(i)(0), dp(i - 1)(0) + 1)\n }\n if (i + 1 < n) {\n if (position(i) + height(i) < position(i + 1)) {\n dp(i)(1) = math.max(dp(i - 1)(0), dp(i - 1)(1)) + 1\n }\n } else {\n dp(i)(1) = math.max(dp(i - 1)(0), dp(i - 1)(1)) + 1\n }\n dp(i)(0) = math.max(dp(i - 1)(0), dp(i)(0))\n dp(i)(1) = math.max(dp(i - 1)(1), dp(i)(1))\n }\n println(dp(n - 1).max)\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve()\n out.close\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n val Trees = new Array[(Int, Int)](n)\n\n for (i <- 0 until n) {\n val line = readLine().split(\" \").map(_.toInt)\n Trees(i) = (line(0), line(1))\n }\n\n def solve(): Int = {\n var result = 0\n var lastOccupied = 0\n for (i <- 0 until n) {\n if (i == 0) {\n result += 1\n lastOccupied = Trees(0)._1\n }\n else if (i == n - 1) result += 1\n else {\n val (x, h) = Trees(i)\n if (lastOccupied < x - h) {\n println(s\"left fall $i\")\n result += 1\n lastOccupied = x\n } else if (x + h < Trees(i + 1)._1) {\n println(s\"fall $i\")\n result += 1\n lastOccupied = x + h\n } else {\n lastOccupied = x\n }\n\n }\n }\n result\n }\n\n println(solve())\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n val Trees = new Array[(Int, Int)](n)\n\n for (i <- 0 until n) {\n val line = readLine().split(\" \").map(_.toInt)\n Trees(i) = (line(0), line(1))\n }\n\n def solve(): Int = {\n var result = 0\n var last = 0\n for (i <- 0 until n) {\n if (i == 0) result += 1\n else if (i == n - 1) result +=1\n else {\n val (x, h) = Trees(i)\n if (last < x - h) {\n result += 1\n last = x\n } else if (x + h < Trees(i + 1)._1) {\n result += 1\n last = x + h\n }\n\n }\n }\n result\n }\n\n println(solve())\n}\n"}], "src_uid": "a850dd88a67a6295823e70e2c5c857c9"} {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\nimport scala.annotation.tailrec\n//import java.math.BigDecimal\n\nobject Bitz_G { \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.t6.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n \n println(comb(n, 5) * comb(n, 3))\n \n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n def comb(n: Int, m: Int) = { \n factLast(n+m-1, m) / fact(m)\n }\n \n def fact(v: Long): Long = v match {\n case 1 => 1\n case x => x * fact(x - 1)\n }\n\n def factLast(v:Int, k:Int):BigDecimal = {\n var res = BigDecimal(1);\n for (i <- (v-k+1) to v) {\n res *= i\n// db(res)\n }\n res\n }\n \n \n //---------------------------- service code ----------------------------------\n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n321\n\"\"\"//66715035255088\n \nval t6 = \"\"\"\n624\n\"\"\"//7147161340917624\n\n}\n\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Main {\n\n def sqr(x: Long) = x * x\n\n def powmod(x: Long, n: Long, p: Long): Long = {\n if (n == 1) x\n else if (n % 2 == 1) (powmod(x, n - 1, p) * x) % p\n else sqr(powmod(x, n / 2, p)) % p\n }\n\n def C(n: Long, k: Long) = {\n var res = BigInt(1)\n for (i <- n - k + 1 to n) {\n res = res * i\n }\n for (i <- 1 to k.toInt) {\n res = res / i\n }\n res\n }\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n\n val n = in.nextInt()\n\n println(C(n - 1 + 3, 3) * C(n - 1 + 5, 5))\n }\n}\n"}], "negative_code": [], "src_uid": "d41aebacfd5d16046db7c5d339478115"} {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n import scala.util.control.Breaks.{break, breakable}\n \n\n var io = new FastIO(\"in.txt\")\n var T, A, K = 0\n def main(args: Array[String]): Unit = {\n T = io.nextInt\n while({T-=1; T >= 0}){\n A = io.nextInt\n K = io.nextInt\n if(A < K){\n io.println(K - A)\n }else if(A > K){\n var ans = {\n (A - K) % 2 match {\n case 0 => 0\n case 1 => 1\n }\n }\n\n io.println(ans)\n\n\n }else{\n io.println(0)\n }\n }\n io.flush()\n }\n\n class FastIO {\n var sb: StringBuilder = new StringBuilder()\n var br: BufferedReader = null;\n var st: StringTokenizer = null;\n var ps: PrintStream = new PrintStream(System.out)\n\n def this(fname: String) {\n this()\n try {\n var input = new File(fname)\n if(input.exists()){\n System.setIn(new FileInputStream(fname))\n }\n }\n catch {\n case e: Exception => {\n e.printStackTrace()\n }\n }\n\n br = new BufferedReader(new InputStreamReader(System.in))\n }\n\n def next: String = {\n while ( {\n st == null || !st.hasMoreElements\n }) try st = new StringTokenizer(br.readLine)\n catch {\n case e: IOException =>\n e.printStackTrace()\n }\n st.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n def nextLong: Long = next.toLong\n\n def nextDouble: Double = next.toDouble\n\n def flush(): Unit = {\n ps.print(sb.toString())\n sb.setLength(0)\n }\n\n def print(o: Any): Unit = {\n sb.append(o)\n }\n\n def println(o: Any): Unit = {\n sb.append(o)\n sb.append('\\n')\n }\n\n def nextLine: String = {\n var str = \"\"\n try str = br.readLine\n catch {\n case e: IOException =>\n e.printStackTrace()\n }\n str\n }\n }\n}\n", "positive_code": [{"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n\n val ans =\n if (n <= k) k - n\n else (n % 2 - k % 2).abs\n\n println(ans)\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n\n val ans =\n if (n <= k) k - n\n else 2 * math.ceil((n + k) / 2.0).toInt - k - n\n\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n var io = new FastIO(\"in.txt\")\n var T, A, K = 0\n def main(args: Array[String]): Unit = {\n T = io.nextInt\n while({T-=1; T >= 0}){\n A = io.nextInt\n K = io.nextInt\n if(A < K){\n io.println(K - A)\n }else if(A > K){\n var ans = {\n (A - K) % 2 match {\n case 0 => 0\n case 1 => 1\n }\n }\n\n io.println(ans)\n\n\n }else{\n io.println(0)\n }\n }\n io.flush()\n }\n}\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.control.Breaks.{break, breakable}\nclass FastIO {\n var sb: StringBuilder = new StringBuilder()\n var br: BufferedReader = null;\n var st: StringTokenizer = null;\n var ps: PrintStream = new PrintStream(System.out)\n\n def this(fname: String) {\n this()\n try {\n var input = new File(fname)\n if(input.exists()){\n System.setIn(new FileInputStream(fname))\n }\n }\n catch {\n case e: Exception => {\n e.printStackTrace()\n }\n }\n\n br = new BufferedReader(new InputStreamReader(System.in))\n }\n\n def next: String = {\n while ( {\n st == null || !st.hasMoreElements\n }) try st = new StringTokenizer(br.readLine)\n catch {\n case e: IOException =>\n e.printStackTrace()\n }\n st.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n def nextLong: Long = next.toLong\n\n def nextDouble: Double = next.toDouble\n\n def flush(): Unit = {\n ps.print(sb.toString())\n sb.setLength(0)\n }\n\n def print(o: Any): Unit = {\n sb.append(o)\n }\n\n def println(o: Any): Unit = {\n sb.append(o)\n sb.append('\\n')\n }\n\n def nextLine: String = {\n var str = \"\"\n try str = br.readLine\n catch {\n case e: IOException =>\n e.printStackTrace()\n }\n str\n }\n}"}, {"source_code": "object DistanceAxis {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn._\n val input = readInt()\n var i = 0\n while(i < input) {\n val line = readLine().split(\" \")\n val A = line(0).toInt\n val diff = line(1).toInt\n if(diff < A) {\n val result = (A - diff) % 2\n println(result)\n } else {\n println(math.abs(A-diff))\n }\n i += 1\n }\n }\n}\n"}, {"source_code": "\nobject A extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val a = in.nextInt()\n val k = in.nextInt()\n\n val sol1 = {\n if ((a + k) % 2 == 0) 0 else 1\n }\n val sol1B = (a + k + sol1) / 2\n\n val result1 = if (math.abs(sol1B - math.abs((a + sol1) - sol1B)) == k) sol1 else 100000000\n\n val sol2 = {\n if ((a - k) < 0) (a - k) * -1\n else {\n if (((a - k)) % 2 == 0) 0 else 1\n }\n }\n\n val sol2B = (a - k + sol2) / 2\n\n val result2 = if (math.abs(sol2B - math.abs((a + sol2) - sol2B)) == k) sol2 else 100000000\n\n println(math.min(result1, result2))\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}], "negative_code": [], "src_uid": "f98d1d426f68241bad437eb221f617f4"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n REP(N) { i =>\n if (A(i) % 2 == 0) {\n A(i) -= 1\n }\n }\n out.println(A.mkString(\" \"))\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object CF498A extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n val array = (new Array[Int](in.nextInt)).map(_ => in.nextInt)\n val result = array.map(x => {\n if (x%2 == 0) x-1 else x\n })\n out.println(result.mkString(\" \"))\n }\n\n solve\n out.flush\n out.close\n}"}, {"source_code": "import scala.io.StdIn\n\nobject AdjacentReplacements {\n\n def main(args: Array[String]): Unit = {\n StdIn.readLine()\n val numbers = StdIn.readLine().split(\" \").map(_.toInt)\n println(solve(numbers).mkString(\" \"))\n }\n\n def solve(numbers: Seq[Int]): Seq[Int] = {\n numbers.map(n => if (n % 2 == 0) n - 1 else n)\n }\n}\n"}, {"source_code": "/**\n * @author ShankarShastri\n * Algorithm: ProblemA\n */\n\nimport scala.io.StdIn._\nimport scala.annotation.tailrec\n\nobject ProblemA {\n def main(args: Array[String]): Unit = {\n val _ = readInt\n val arrList = readLine().split(\" \").map(_.toInt).toList\n val res = arrList.map(x => {\n if(x%2 ==0) x-1\n else x\n })\n println(res.mkString(\" \"))\n }\n}\n"}, {"source_code": "object _1006A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val nums = io.read[Vector[Int]]\n val ans = nums.map(i => if(i%2 == 0) i-1 else i)\n io.writeAll(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Main2 extends App {\n\n import java.io._\n import java.util.{StringTokenizer}\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n val a = in.nextLine.split(' ').map(_.toInt).map(x => (x - 1) / 2 * 2 + 1)\n out.print(a.mkString(\" \"))\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}"}], "negative_code": [], "src_uid": "d00696cb27c679dda6e2e29314a8432b"} {"source_code": "//package codeforces.contests._1426\n\nobject FloorNumber {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(n, x) = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val result = {\n if (n <= 2) 1\n else {\n 1 + (n - 2) / x + (if ((n - 2) % x != 0) 1 else 0)\n }\n }\n println(result)\n }\n }\n}\n", "positive_code": [{"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, x) = readLine().split(\" \").map(_.toInt)\n val ans = 0.max(n - 2 + x - 1) / x + 1\n\n println(ans)\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject tasks extends App {\n for (str <- Source.stdin.getLines().drop(1)){\n val ln: List[String] = str.split(\" \").toList\n val aptnm: Int = ln.head.toInt\n val aptflr: Int = ln(1).toInt\n val floor = {\n if (aptnm < 3)\n 1\n else\n ((aptnm.toDouble - 2) / aptflr).ceil.toInt + 1\n }\n println(s\"$floor\")\n }\n}"}], "negative_code": [{"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, x) = readLine().split(\" \").map(_.toInt)\n val ans = (n - 2 + x - 1) / x + 1\n\n println(ans)\n }\n}\n"}], "src_uid": "8b50a0eb2e1c425455b132683d3e6047"} {"source_code": "import scala.io.StdIn._\nimport scala.collection.mutable.Set\nimport scala.collection.mutable.ArrayBuffer\n\nobject Main extends App {\n val Array(n, q) = readLine.split(\" \").map(_.toInt)\n val qs = (1 to q)\n .map(_ => {\n val Array(a, b) = readLine.split(\" \")\n (a.toInt - 1, b.toInt - 1)\n })\n\n val cells = Array.fill(2, n) { Cell.empty }\n var totalBlock = 0\n \n val results = ArrayBuffer[Boolean]()\n\n qs.foreach {\n case (a, b) => {\n val neighbor = (math.max(0, b - 1) to math.min(n - 1, b + 1))\n .map((1 - a, _))\n val curCell = cells(a)(b)\n\n if (curCell.blocked) { // remove the block\n curCell.blocked = false\n curCell.links.clear\n neighbor.foreach {\n case (c, d) =>\n if (cells(c)(d).links.contains(a -> b)) {\n cells(c)(d).links -= (a -> b)\n totalBlock -= 1\n }\n }\n\n } else { // add the block\n curCell.blocked = true\n neighbor.foreach {\n case (c, d) =>\n if (cells(c)(d).blocked) {\n curCell.links += c -> d\n cells(c)(d).links += a -> b\n totalBlock += 1\n }\n }\n }\n\n /* for (i <- 0 to 1) {\n for (j <- 0 until n)\n print(if (cells(i)(j).blocked) \"1 \" else \"0 \")\n println\n }\n\n for (i <- 0 to 1) {\n cells(i).foreach(x => print(x.links))\n println\n }\n\n println(totalBlock) */\n\n if (totalBlock == 0)\n results += true\n else\n results += false\n }\n }\n \n results.foreach(x => println(if (x) \"YES\" else \"NO\"))\n}\n\nclass Cell(var blocked: Boolean, var links: ArrayBuffer[(Int, Int)])\n\nobject Cell {\n def empty = {\n new Cell(false, ArrayBuffer())\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val Array(n, q) = stdin.next().split(' ').map(_.toInt)\n val blocks: mutable.Set[((Int, Int), (Int, Int))] = mutable.Set.empty[((Int, Int), (Int, Int))]\n val arr = Array.ofDim[Boolean](2, n)\n val an = stdin.take(q).map(line => line.split(\" \").map(_.toInt).map(_ - 1)).foldLeft(List.empty[String]) {\n case (result, Array(r, c)) if arr(r)(c) => {\n arr(r)(c) = false\n blocks.remove((0, c), (1, c))\n if (r == 0) {\n blocks.remove((0, c), (1, c - 1))\n blocks.remove((0, c), (1, c + 1))\n }\n else {\n blocks.remove((0, c - 1), (1, c))\n blocks.remove((0, c + 1), (1, c))\n }\n val res = if (blocks.isEmpty) \"YES\" else \"NO\"\n res :: result\n }\n case (result, Array(r, c)) => {\n arr(r)(c) = true\n if (r == 0) {\n if (arr(1)(c))\n blocks.add((0, c), (1, c))\n if (c > 0 && arr(1)(c - 1))\n blocks.add((0, c), (1, c - 1))\n if (c < n - 1 && arr(1)(c + 1))\n blocks.add((0, c), (1, c + 1))\n }\n else {\n if (arr(0)(c))\n blocks.add((0, c), (1, c))\n if (c > 0 && arr(0)(c - 1))\n blocks.add((0, c - 1), (1, c))\n if (c < n - 1 && arr(0)(c + 1))\n blocks.add((0, c + 1), (1, c))\n }\n val res = if (blocks.isEmpty) \"YES\" else \"NO\"\n res :: result\n }\n }\n println(an.reverse.mkString(\"\\n\"))\n}\n\n\n// 5 11 2\n// 2 3 4 5 7\n\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val Array(n, q) = stdin.next().split(' ').map(_.toInt)\n val blocks: mutable.Set[((Int, Int), (Int, Int))] = mutable.Set.empty[((Int, Int), (Int, Int))]\n val arr = Array.ofDim[Boolean](2, q)\n val an = stdin.take(q).map(line => line.split(\" \").map(_.toInt).map(_ - 1)).foldLeft(List.empty[String]) {\n case (result, Array(r, c)) if arr(r)(c) => {\n arr(r)(c) = false\n blocks.remove((0, c), (1, c))\n if (r == 0) {\n blocks.remove((0, c), (1, c - 1))\n blocks.remove((0, c), (1, c + 1))\n }\n else {\n blocks.remove((0, c - 1), (1, c))\n blocks.remove((0, c + 1), (1, c))\n }\n val res = if (blocks.isEmpty) \"YES\" else \"NO\"\n res :: result\n }\n case (result, Array(r, c)) => {\n arr(r)(c) = true\n if (r == 0) {\n if (arr(1)(c))\n blocks.add((0, c), (1, c))\n if (c > 0 && arr(1)(c - 1))\n blocks.add((0, c), (1, c - 1))\n if (c < q - 1 && arr(1)(c + 1))\n blocks.add((0, c), (1, c + 1))\n }\n else {\n if (arr(0)(c))\n blocks.add((0, c), (1, c))\n if (c > 0 && arr(0)(c - 1))\n blocks.add((0, c - 1), (1, c))\n if (c < q - 1 && arr(0)(c + 1))\n blocks.add((0, c + 1), (1, c))\n }\n val res = if (blocks.isEmpty) \"YES\" else \"NO\"\n res :: result\n }\n }\n println(an.mkString(\"\\n\"))\n}\n\n\n// 5 11 2\n// 2 3 4 5 7\n\n"}], "src_uid": "af036416721694d1843368988ca78e8e"} {"source_code": "object NewPassword extends App {\n val firstinput = Console.in.readLine().split(\" \").map( _.toInt).toList\n // Length of the Password\n val n = firstinput(0) // 2 <= n <= 100\n // Number of distinct symbols\n val k = firstinput(1) // 2 <= k <= min(n, 26)\n\n val setOfChars = (1 to k).map( _ + 64).map( _.toChar.toLower )\n\n val isLengthValid: String => Boolean = { pw => pw.length == n }\n val isConsistencyValid: String => Boolean = { pw => pw.matches(\"^([a-z]+)\")}\n val isIntegrityValid: String => Boolean = { pw => pw.distinct.length == k }\n val isConsecutiveValid: String => Boolean = { pw => pw.sliding(2).forall( s => s.reverse != s) }\n val isValidPassword: String => Boolean = { pw =>\n isLengthValid(pw) &&\n isConsistencyValid(pw) &&\n isIntegrityValid(pw) &&\n isConsecutiveValid(pw)\n }\n\n def createNewPassword(pw: String = \"\", idx: Int = 0): String =\n if(isValidPassword(pw)) pw\n else if(idx < k) createNewPassword(pw + setOfChars(idx), idx + 1)\n else createNewPassword(pw)\n\n println(createNewPassword())\n}", "positive_code": [{"source_code": "object NewPassword extends App {\n val firstinput = Console.in.readLine().split(\" \").map( _.toInt).toList\n // Length of the Password\n val n = firstinput(0) // 2 <= n <= 100\n // Number of distinct symbols\n val k = firstinput(1) // 2 <= k <= min(n, 26)\n\n val setOfChars = (1 to k).map( _ + 64).map( _.toChar.toLower )\n\n val isLengthValid: String => Boolean = { pw => pw.length == n }\n val isConsistencyValid: String => Boolean = { pw => pw.matches(\"^([a-z]+)\")}\n val isIntegrityValid: String => Boolean = { pw => pw.distinct.length == k }\n val isConsecutiveValid: String => Boolean = { pw => pw.sliding(2).forall( s => s.reverse != s) }\n val isValidPassword: String => Boolean = { pw =>\n isLengthValid(pw) &&\n isConsistencyValid(pw) &&\n isIntegrityValid(pw) &&\n isConsecutiveValid(pw)\n }\n\n\n def createNewPassword(pw: String = \"\", idx: Int = 0): String =\n if(isValidPassword(pw)) pw\n else {\n if(idx < k) createNewPassword(pw + setOfChars(idx), idx + 1)\n else createNewPassword(pw)\n }\n\n println(createNewPassword())\n}"}, {"source_code": "\n/**\n * Created by ruslan on 3/12/17.\n */\nobject ProblebA extends App {\n\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n var st: StringTokenizer = null\n val out = new PrintWriter(System.out)\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) st =\n new StringTokenizer(br.readLine)\n st.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n val n = nextInt\n val k = nextInt\n\n val s = new StringBuilder\n\n for (i <- 0 until n) {\n s.append(((i % k) + 'a').toChar)\n }\n\n println(s.toString)\n\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CVK2A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CVK2A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val k = ni()\n var c = 0\n REP(n) { _ =>\n out.print(('a'+c).toChar)\n c = ( c + 1 ) % k\n }\n }\n}\n"}], "negative_code": [], "src_uid": "39f5e934bf293053246bd3faa8061c3b"} {"source_code": "import java.io._\nimport java.util.Scanner\n\nimport scala.annotation.tailrec\n\nobject Main {\n def main(args: Array[String]) {\n val scan = new Scanner(new BufferedInputStream(System.in))\n val n = scan.nextInt()\n val inArr = new Array[Int](n+1) //没有new时,是初始化值\n for( i <- 1 to n){\n val inX = scan.nextInt()\n inArr(inX) = i\n }\n scan.close()\n val ans = Process(inArr,2,0)\n println(ans)\n }\n\n @tailrec\n def Process(inArr: Array[Int],i: Int, ans: Long): Long={\n if(i>=inArr.length){\n ans\n }else{\n val d = math.abs(inArr(i)-inArr(i-1))\n Process(inArr,i+1,ans+d)\n }\n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n import scala.math \n val n = Console.readLine.toLong\n val seq = Console.readLine.split(\" \").map(_.toLong).zip(0 until n.toInt).toMap\n val r = seq.flatMap(kv => seq.get(kv._1 + 1).map(x => math.abs(kv._2 - x))).map(_.toLong).sum\n println(r)\n}"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by Buffalo on 16/1/1.\n */\nobject cf_612b {\n\n def main(args : Array[String]): Unit = {\n val n : Int = StdIn readInt()\n val l = StdIn.readLine().split(' ').map(_.toInt).zipWithIndex.sortWith(_._1 < _._1)\n println(0.to(l.size - 2).map(i => Math.abs(l(i)._2.toLong - l(i+1)._2)).sum)\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n import scala.math \n val n = readLine.toLong\n val seq = readLine.split(\" \").map(_.toLong).zip(0 until n.toInt).toMap\n val r = seq.flatMap(kv => seq.get(kv._1 + 1).map(x => math.abs(kv._2 - x))).map(_.toLong).sum\n println(r)\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt - 1)\n val positions = Array.ofDim[Int](n)\n data.indices.foreach { i =>\n positions(data(i)) = i\n }\n println(positions.tail.foldLeft((0l, positions.head)) {\n case ((sum, prev), el) => (sum + Math.abs(prev - el), el)\n }._1)\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n import scala.math \n val n = Console.readLine.toLong\n val seq = Console.readLine.split(\" \").map(_.toLong).zip(0 until n.toInt).toMap\n val r = seq.flatMap(kv => seq.get(kv._1 + 1).map(x => math.abs(kv._2 - x))).sum\n println(r)\n}"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by Buffalo on 16/1/1.\n */\nobject cf_612b {\n\n def main(args : Array[String]): Unit = {\n val n : Int = StdIn readInt()\n val l = StdIn.readLine().split(' ').map(_.toInt).zipWithIndex.sortWith(_._1 < _._1)\n println(0.to(l.size - 2).map(i => Math.abs(l(i)._2 - l(i+1)._2)).sum)\n }\n\n}"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by Buffalo on 16/1/1.\n */\nobject cf_612b {\n\n def main(args : Array[String]): Unit = {\n val n : Long = StdIn readInt()\n val l = StdIn.readLine().split(' ').map(_.toInt).zipWithIndex.sortWith(_._1 < _._1)\n println(0.to(l.size - 2).map(i => Math.abs(l(i)._2 - l(i+1)._2)).sum)\n }\n\n}"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by Buffalo on 16/1/1.\n */\nobject cf_612b {\n\n def main(args : Array[String]): Unit = {\n val n : Int = StdIn readInt()\n val l = StdIn.readLine().split(' ').map(_.toLong).zipWithIndex.sortWith(_._1 < _._1)\n println(0.to(l.size - 2).map(i => Math.abs(l(i)._2 - l(i+1)._2)).sum)\n }\n\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt - 1)\n val positions = Array.ofDim[Int](n)\n data.indices.foreach { i =>\n positions(data(i)) = i\n }\n println(positions.tail.foldLeft((0, positions.head)) {\n case ((sum, prev), el) => (sum + Math.abs(prev - el), el)\n }._1)\n}"}, {"source_code": "import java.io._\nimport java.util.Scanner\n\nimport scala.annotation.tailrec\n\nobject Main {\n def main(args: Array[String]) {\n val scan = new Scanner(new BufferedInputStream(System.in))\n val n = scan.nextInt()\n val inArr = new Array[Int](n+1) //没有new时,是初始化值\n for( i <- 1 to n){\n val inX = scan.nextInt()\n inArr(inX) = i\n }\n scan.close()\n val ans = Process(inArr,2,0)\n println(ans)\n }\n\n @tailrec\n def Process(inArr: Array[Int],i: Int, ans: Int): Int={\n if(i>=inArr.length){\n ans\n }else{\n val d = math.abs(inArr(i)-inArr(i-1))\n Process(inArr,i+1,ans+d)\n }\n }\n}"}], "src_uid": "54e2b6bea0dc6ee68366405945af50c6"} {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject D0 extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n val Array(n, t) = readInts(2)\n val problems0 = Array.tabulate(n)(identity)\n val as, ts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val Array(a, t) = readInts(2)\n as(i) = a\n ts(i) = t\n }\n\n val problems = problems0.sortBy(ts)\n\n def can(limit: Int): Boolean = {\n var i = 0\n var time = 0L\n var s = 0\n while (i < n && time < t) {\n val p = problems(i)\n if (as(p) >= limit && time + ts(p) <= t) {\n s += 1\n time += ts(p)\n }\n i += 1\n }\n s >= limit\n }\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (can(mid)) binSearch(mid + 1, hi)\n else binSearch(low, mid - 1)\n }\n }\n\n val max = binSearch(0, n) - 1\n\n val res = ArrayBuffer.empty[Int]\n for (p <- problems) {\n if (as(p) >= max && res.size < max) res += p + 1\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(max)\n println(res.size)\n println(res.mkString(\" \"))\n\n Console.flush\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\nobject D {\n def canGetXPoints(a: Array[(Int, Int, Int)], x: Int, T: Int, out: Output): Boolean = {\n val n = a.length\n var i = 0\n var sum = 0\n var count = 0\n if (out != null) {\n out.println(x)\n out.println(x)\n }\n while (i < n && count < x && sum <= T) {\n if (a(i)._2 >= x) {\n sum += a(i)._3\n count += 1\n if (out != null) {\n out.print(s\"${a(i)._1 + 1} \")\n }\n }\n i += 1\n }\n count == x && sum <= T\n }\n\n def findMaxPoints(a: Array[(Int, Int, Int)], T: Int, left: Int, right: Int): Int = {\n if (left + 1 == right) left else {\n val mid = (left + right) >>> 1\n if (canGetXPoints(a, mid, T, null)) {\n findMaxPoints(a, T, mid, right)\n } else {\n findMaxPoints(a, T, left, mid)\n }\n }\n }\n\n def solve(in: Input, out: Output): Unit = {\n val n, T = in.nextInt()\n val A = Array.tabulate(n)(i => (i, in.nextInt(), in.nextInt())).sortBy(_._3)\n val result = findMaxPoints(A, T, 0, n + 1)\n canGetXPoints(A, result, T, out)\n }\n\n class Input(in: InputStream) extends Closeable {\n private[this] val br = new BufferedReader(new InputStreamReader(in))\n private[this] var st = new StringTokenizer(br.readLine())\n\n override def close(): Unit = br.close()\n\n @tailrec\n final def next(): String = if (st.hasMoreTokens) st.nextToken() else {\n st = new StringTokenizer(br.readLine())\n next()\n }\n\n final def nextInt(): Int = next().toInt\n final def nextLong(): Long = next().toLong\n final def nextDouble(): Double = next().toDouble\n }\n\n final type Output = PrintWriter\n\n def main(args: Array[String]): Unit = {\n val in = new Input(System.in)\n val out = new Output(System.out)\n solve(in, out)\n out.close()\n in.close()\n }\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\nobject D {\n def canGetXPoints(a: Array[(Int, Int, Int)], x: Int, T: Int, out: Output): Boolean = {\n val n = a.length\n var i = 0\n var sum = 0\n var count = 0\n if (out != null) {\n out.println(x)\n out.println(x)\n }\n while (i < n && count < x && sum <= T) {\n if (a(i)._2 >= x) {\n sum += a(i)._3\n count += 1\n if (out != null) {\n out.print(s\"${a(i)._1 + 1} \")\n }\n }\n i += 1\n }\n sum <= T\n }\n\n def findMaxPoints(a: Array[(Int, Int, Int)], T: Int, left: Int, right: Int): Int = {\n if (left + 1 == right) left else {\n val mid = (left + right) >>> 1\n if (canGetXPoints(a, mid, T, null)) {\n findMaxPoints(a, T, mid, right)\n } else {\n findMaxPoints(a, T, left, mid)\n }\n }\n }\n\n def solve(in: Input, out: Output): Unit = {\n val n, T = in.nextInt()\n val A = Array.tabulate(n)(i => (i, in.nextInt(), in.nextInt())).sortBy(_._3)\n val result = findMaxPoints(A, T, 0, n + 1)\n canGetXPoints(A, result, T, out)\n }\n\n class Input(in: InputStream) extends Closeable {\n private[this] val br = new BufferedReader(new InputStreamReader(in))\n private[this] var st = new StringTokenizer(br.readLine())\n\n override def close(): Unit = br.close()\n\n @tailrec\n final def next(): String = if (st.hasMoreTokens) st.nextToken() else {\n st = new StringTokenizer(br.readLine())\n next()\n }\n\n final def nextInt(): Int = next().toInt\n final def nextLong(): Long = next().toLong\n final def nextDouble(): Double = next().toDouble\n }\n\n final type Output = PrintWriter\n\n def main(args: Array[String]): Unit = {\n val in = new Input(System.in)\n val out = new Output(System.out)\n solve(in, out)\n out.close()\n in.close()\n }\n}\n"}, {"source_code": "import java.util\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n\n val Array(n, t) = readInts(2)\n val problems0 = Array.tabulate(n)(identity)\n val as, ts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val Array(a, t) = readInts(2)\n as(i) = a\n ts(i) = t\n }\n\n val problems = problems0.sortBy(p => (-as(p), ts(p)))\n val MAXT = ts.max\n\n val pq = Array.fill(MAXT + 1)(0)\n\n var max = 0L\n var time = 0L\n var count = 0\n\n def take(p: Int) = {\n takeTT(ts(p))\n }\n\n def takeTT(tt: Int) = {\n count += 1\n pq(tt) += 1\n time += tt\n }\n\n def remove(tt: Int) = {\n count -= 1\n pq(tt) -= 1\n time -= tt\n removed += tt\n }\n\n val removed = ArrayBuffer.empty[Int]\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n removed.clear()\n while (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0 && tt > ts(p)) {\n tt -= 1\n }\n if (tt > ts(p)) remove(tt)\n }\n if (count < as(p) && time + ts(p) <= t) {\n take(p)\n } else {\n for (r <- removed) {\n takeTT(r)\n }\n }\n }\n if (count > max) {\n max = count\n }\n }\n\n println(max)\n time = 0L\n count = 0\n util.Arrays.fill(pq, 0)\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n removed.clear()\n while (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0 && tt > ts(p)) {\n tt -= 1\n }\n if (tt > ts(p)) remove(tt)\n }\n if (count < as(p) && time + ts(p) <= t) {\n take(p)\n } else {\n for (r <- removed) {\n takeTT(r)\n }\n }\n }\n if (count == max) {\n print()\n }\n }\n\n def print() = {\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(max)\n val res = ArrayBuffer.empty[Int]\n for (p <- problems) {\n if (pq(ts(p)) > 0) {\n res += p + 1\n pq(ts(p)) -= 1\n }\n }\n println(res.mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n\n}\n"}, {"source_code": "import java.util\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n\n val Array(n, t) = readInts(2)\n val problems0 = Array.tabulate(n)(identity)\n val as, ts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val Array(a, t) = readInts(2)\n as(i) = a\n ts(i) = t\n }\n\n val problems = problems0.sortBy(p => (-as(p), ts(p)))\n val MAXT = ts.max\n\n val pq = Array.fill(MAXT + 1)(0)\n\n var max = 0L\n var time = 0L\n var count = 0\n\n def take(p: Int) = {\n takeTT(ts(p))\n }\n\n def takeTT(tt: Int) = {\n count += 1\n pq(tt) += 1\n time += tt\n }\n\n def remove(tt: Int) = {\n count -= 1\n pq(tt) -= 1\n time -= tt\n //removed += tt\n }\n\n val removed = ArrayBuffer.empty[Int]\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n removed.clear()\n while (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0 && tt > ts(p)) {\n tt -= 1\n }\n if (tt > ts(p) && pq(tt) > 0) remove(tt)\n }\n if (count < as(p) && time + ts(p) <= t) {\n take(p)\n } else {\n for (r <- removed) {\n takeTT(r)\n }\n }\n }\n if (count > max) {\n max = count\n }\n }\n\n println(max)\n time = 0L\n count = 0\n util.Arrays.fill(pq, 0)\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n removed.clear()\n while (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0 && tt > ts(p)) {\n tt -= 1\n }\n if (tt > ts(p) && pq(tt) > 0) remove(tt)\n }\n if (count < as(p) && time + ts(p) <= t) {\n take(p)\n } else {\n for (r <- removed) {\n takeTT(r)\n }\n }\n }\n if (count == max) {\n print()\n }\n }\n\n def print() = {\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(max)\n val res = ArrayBuffer.empty[Int]\n for (p <- problems) {\n if (pq(ts(p)) > 0) {\n res += p + 1\n pq(ts(p)) -= 1\n }\n }\n println(res.mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n\n}\n"}, {"source_code": "import java.util\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n\n val Array(n, t) = readInts(2)\n val problems0 = Array.tabulate(n)(identity)\n val as, ts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val Array(a, t) = readInts(2)\n as(i) = a\n ts(i) = t\n }\n\n val problems = problems0.sortBy(p => (-as(p), ts(p)))\n val MAXT = ts.max\n\n val pq = Array.fill(MAXT + 1)(0)//new mutable.PriorityQueue[Int]()(Ordering.by(p => ts(p)))\n\n var max = 0L\n var time = 0L\n var count = 0\n\n def take(p: Int) = {\n count += 1\n pq(ts(p)) += 1\n time += ts(p)\n }\n\n def remove(tt: Int) = {\n count -= 1\n pq(tt) -= 1\n time -= tt\n }\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n while (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0) {\n tt -= 1\n }\n if (tt > ts(p)) remove(tt)\n }\n if (count < as(p) && time + ts(p) <= t) {\n take(p)\n }\n }\n if (count > max) {\n max = count\n }\n //println(pq.mkString(\" \"))\n }\n\nprintln(max)\n time = 0L\n count = 0\n util.Arrays.fill(pq, 0)\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n while (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0) {\n tt -= 1\n }\n if (tt > ts(p)) remove(tt)\n }\n if (count < as(p) && time + ts(p) <= t) {\n take(p)\n }\n }\n if (count == max) {\n print()\n }\n }\n\n def print() = {\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(max)\n val res = ArrayBuffer.empty[Int]\n for (p <- problems) {\n if (pq(ts(p)) > 0) {\n res += p + 1\n pq(ts(p)) -= 1\n }\n }\n println(res.mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n\n}\n"}, {"source_code": "import java.util\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n\n val Array(n, t) = readInts(2)\n val problems0 = Array.tabulate(n)(identity)\n val as, ts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val Array(a, t) = readInts(2)\n as(i) = a\n ts(i) = t\n }\n\n val problems = problems0.sortBy(p => (-as(p), ts(p)))\n val MAXT = ts.max\n\n val pq = Array.fill(MAXT + 1)(0)\n\n var max = 0L\n var time = 0L\n var count = 0\n\n def take(p: Int) = {\n count += 1\n pq(ts(p)) += 1\n time += ts(p)\n }\n\n def remove(tt: Int) = {\n count -= 1\n pq(tt) -= 1\n time -= tt\n }\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n while (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0 && tt > ts(p)) {\n tt -= 1\n }\n if (tt > ts(p)) remove(tt)\n }\n if (count < as(p) && time + ts(p) <= t) {\n take(p)\n }\n }\n if (count > max) {\n max = count\n }\n }\n\n println(max)\n time = 0L\n count = 0\n util.Arrays.fill(pq, 0)\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n while (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0 && tt > ts(p)) {\n tt -= 1\n }\n if (tt > ts(p)) remove(tt)\n }\n if (count < as(p) && time + ts(p) <= t) {\n take(p)\n }\n }\n if (count == max) {\n print()\n }\n }\n\n def print() = {\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(max)\n val res = ArrayBuffer.empty[Int]\n for (p <- problems) {\n if (pq(ts(p)) > 0) {\n res += p + 1\n pq(ts(p)) -= 1\n }\n }\n println(res.mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n\n}\n"}, {"source_code": "import java.util\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n\n val Array(n, t) = readInts(2)\n val problems0 = Array.tabulate(n)(identity)\n val as, ts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val Array(a, t) = readInts(2)\n as(i) = a\n ts(i) = t\n }\n\n val problems = problems0.sortBy(p => (-as(p), ts(p)))\n val MAXT = ts.max\n\n val pq = Array.fill(MAXT + 1)(0)\n\n var max = 0L\n var time = 0L\n var count = 0\n\n def take(p: Int) = {\n takeTT(ts(p))\n }\n\n def takeTT(tt: Int) = {\n count += 1\n pq(tt) += 1\n time += tt\n }\n\n def remove(tt: Int) = {\n count -= 1\n pq(tt) -= 1\n if (pq(tt) < 0) throw new RuntimeException(\"\")\n time -= tt\n removed += tt\n }\n\n val removed = ArrayBuffer.empty[Int]\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n removed.clear()\n while (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0 && tt > ts(p)) {\n tt -= 1\n }\n if (tt > ts(p) && pq(tt) > 0) remove(tt)\n }\n if (count < as(p) && time + ts(p) <= t) {\n take(p)\n } else {\n for (r <- removed) {\n takeTT(r)\n }\n }\n }\n if (count > max) {\n max = count\n }\n }\n\n println(max)\n time = 0L\n count = 0\n util.Arrays.fill(pq, 0)\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n removed.clear()\n while (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0 && tt > ts(p)) {\n tt -= 1\n }\n if (tt > ts(p) && pq(tt) > 0) remove(tt)\n }\n if (count < as(p) && time + ts(p) <= t) {\n take(p)\n } else {\n for (r <- removed) {\n takeTT(r)\n }\n }\n }\n if (count == max) {\n print()\n }\n }\n\n def print() = {\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(max)\n val res = ArrayBuffer.empty[Int]\n for (p <- problems) {\n if (pq(ts(p)) > 0) {\n res += p + 1\n pq(ts(p)) -= 1\n }\n }\n println(res.mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n val Array(n, t) = readInts(2)\n val problems0 = Array.tabulate(n)(identity)\n val as, ts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val Array(a, t) = readInts(2)\n as(i) = a\n ts(i) = t\n }\n\n val problems = problems0.sortBy(p => (-as(p), ts(p)))\n\n val pq = new mutable.PriorityQueue[Int]()(Ordering.by(p => ts(p)))\n\n var max = 0L\n var time = 0L\n\n for (p <- problems) {\n if (time + ts(p) <= t && pq.size < as(p)) {\n pq += p\n time += ts(p)\n } else {\n while (pq.size >= as(p)) {\n val rem = pq.dequeue()\n time -= ts(rem)\n }\n if (time + ts(p) <= t) {\n pq += p\n time += ts(p)\n }\n }\n if (pq.size > max) max = pq.size\n }\n\n time = 0L\n pq.clear()\n for (p <- problems) {\n if (time + ts(p) <= t && pq.size < as(p)) {\n pq += p\n time += ts(p)\n } else {\n while (pq.size >= as(p)) {\n val rem = pq.dequeue()\n time -= ts(rem)\n }\n if (time + ts(p) <= t) {\n pq += p\n time += ts(p)\n }\n }\n if (pq.size == max) print()\n }\n\n def print() = {\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(max)\n println(max)\n println(pq.toArray.map(_ + 1).mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n\n}\n"}, {"source_code": "import java.util\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n\n val Array(n, t) = readInts(2)\n val problems0 = Array.tabulate(n)(identity)\n val as, ts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val Array(a, t) = readInts(2)\n as(i) = a\n ts(i) = t\n }\n\n val problems = problems0.sortBy(p => (-as(p), ts(p)))\n val MAXT = ts.max\n\n val pq = Array.fill(MAXT + 1)(0)\n\n var max = 0L\n var time = 0L\n var count = 0\n\n def take(p: Int) = {\n takeTT(ts(p))\n }\n\n def takeTT(tt: Int) = {\n count += 1\n pq(tt) += 1\n time += tt\n }\n\n def remove(tt: Int) = {\n count -= 1\n pq(tt) -= 1\n time -= tt\n removed += tt\n }\n\n val removed = ArrayBuffer.empty[Int]\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n removed.clear()\n if (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0 && tt > ts(p)) {\n tt -= 1\n }\n if (tt > ts(p) && pq(tt) > 0) remove(tt)\n }\n if (count < as(p) && time + ts(p) <= t) {\n take(p)\n } else {\n for (r <- removed) {\n takeTT(r)\n }\n }\n }\n if (count > max) {\n max = count\n }\n }\n\n println(max)\n time = 0L\n count = 0\n util.Arrays.fill(pq, 0)\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n removed.clear()\n if (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0 && tt > ts(p)) {\n tt -= 1\n }\n if (tt > ts(p) && pq(tt) > 0) remove(tt)\n }\n if (count < as(p) && time + ts(p) <= t) {\n take(p)\n } else {\n for (r <- removed) {\n takeTT(r)\n }\n }\n }\n if (count == max) {\n print()\n }\n }\n\n def print() = {\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(max)\n val res = ArrayBuffer.empty[Int]\n for (p <- problems) {\n if (pq(ts(p)) > 0) {\n res += p + 1\n pq(ts(p)) -= 1\n }\n }\n println(res.mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n val Array(n, t) = readInts(2)\n val problems0 = Array.tabulate(n)(identity)\n val as, ts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val Array(a, t) = readInts(2)\n as(i) = a\n ts(i) = t\n }\n\n val problems = problems0.sortBy(p => (-as(p), ts(p)))\n\n val pq = new mutable.PriorityQueue[Int]()(Ordering.by(p => ts(p)))\n\n var max = 0L\n var time = 0L\n\n for (p <- problems) {\n if (time + ts(p) <= t && pq.size < as(p)) {\n pq += p\n time += ts(p)\n } else {\n while (pq.size >= as(p) && ts(pq.head) > ts(p)) {\n val rem = pq.dequeue()\n time -= ts(rem)\n }\n if (time + ts(p) <= t) {\n pq += p\n time += ts(p)\n }\n }\n if (pq.size > max) max = pq.size\n }\n\n time = 0L\n pq.clear()\n for (p <- problems) {\n if (time + ts(p) <= t && pq.size < as(p)) {\n pq += p\n time += ts(p)\n } else {\n while (pq.size >= as(p) && ts(pq.head) > ts(p)) {\n val rem = pq.dequeue()\n time -= ts(rem)\n }\n if (time + ts(p) <= t) {\n pq += p\n time += ts(p)\n }\n }\n if (pq.size == max) print()\n }\n\n def print() = {\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(max)\n println(max)\n println(pq.toArray.map(_ + 1).mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n\n}\n"}, {"source_code": "import java.util\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n\n val Array(n, t) = readInts(2)\n val problems0 = Array.tabulate(n)(identity)\n val as, ts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val Array(a, t) = readInts(2)\n as(i) = a\n ts(i) = t\n }\n\n val problems = problems0.sortBy(p => (-as(p), ts(p)))\n val MAXT = ts.max\n\n val pq = Array.fill(MAXT + 1)(0)//new mutable.PriorityQueue[Int]()(Ordering.by(p => ts(p)))\n\n var max = 0L\n var time = 0L\n var count = 0\n\n def take(p: Int) = {\n count += 1\n pq(ts(p)) += 1\n time += ts(p)\n }\n\n def remove(tt: Int) = {\n count -= 1\n pq(tt) -= 1\n time -= tt\n }\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n while (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0) {\n tt -= 1\n }\n if (tt > ts(p)) remove(tt)\n }\n if (time + ts(p) <= t) {\n take(p)\n }\n }\n if (count > max) {\n max = count\n }\n //println(pq.mkString(\" \"))\n }\n\nprintln(max)\n time = 0L\n count = 0\n util.Arrays.fill(pq, 0)\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n while (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0) {\n tt -= 1\n }\n if (tt > ts(p)) remove(tt)\n }\n if (time + ts(p) <= t) {\n take(p)\n }\n }\n if (count == max) {\n print()\n }\n }\n\n def print() = {\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(max)\n val res = ArrayBuffer.empty[Int]\n for (p <- problems) {\n if (pq(ts(p)) > 0) {\n res += p + 1\n pq(ts(p)) -= 1\n }\n }\n println(res.mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n\n}\n"}, {"source_code": "import java.util\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n\n val Array(n, t) = readInts(2)\n val problems0 = Array.tabulate(n)(identity)\n val as, ts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val Array(a, t) = readInts(2)\n as(i) = a\n ts(i) = t\n }\n\n val problems = problems0.sortBy(p => (-as(p), ts(p)))\n val MAXT = ts.max\n\n val pq = Array.fill(MAXT + 1)(0)\n\n var max = 0L\n var time = 0L\n var count = 0\n\n def take(p: Int) = {\n takeTT(ts(p))\n }\n\n def takeTT(tt: Int) = {\n count += 1\n pq(tt) += 1\n time += tt\n }\n\n def remove(tt: Int) = {\n count -= 1\n pq(tt) -= 1\n time -= tt\n removed += tt\n }\n\n val removed = ArrayBuffer.empty[Int]\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n removed.clear()\n while (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0 && tt > ts(p)) {\n tt -= 1\n }\n if (tt > ts(p) && pq(tt) > 0) remove(tt)\n }\n if (count < as(p) && time + ts(p) <= t) {\n take(p)\n } else {\n for (r <- removed) {\n takeTT(r)\n }\n }\n }\n if (count > max) {\n max = count\n }\n }\n\n println(max)\n time = 0L\n count = 0\n util.Arrays.fill(pq, 0)\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n removed.clear()\n while (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0 && tt > ts(p)) {\n tt -= 1\n }\n if (tt > ts(p) && pq(tt) > 0) remove(tt)\n }\n if (count < as(p) && time + ts(p) <= t) {\n take(p)\n } else {\n for (r <- removed) {\n takeTT(r)\n }\n }\n }\n if (count == max) {\n print()\n }\n }\n\n def print() = {\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(max)\n val res = ArrayBuffer.empty[Int]\n for (p <- problems) {\n if (pq(ts(p)) > 0) {\n res += p + 1\n pq(ts(p)) -= 1\n }\n }\n println(res.mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, t) = readInts(2)\n val problems0 = Array.tabulate(n)(identity)\n val as, ts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val Array(a, t) = readInts(2)\n as(i) = a\n ts(i) = t\n }\n\n val problems = problems0.sortBy(p => (-as(p), ts(p)))\n\n val pq = new mutable.PriorityQueue[Int]()(Ordering.by(p => ts(p)))\n\n var max = 0L\n var time = 0L\n\n for (p <- problems) {\n if (time + ts(p) <= t) {\n pq += p\n time += ts(p)\n } else {\n while (pq.size >= as(p)) {\n val rem = pq.dequeue()\n time -= ts(rem)\n }\n if (time + ts(p) <= t) {\n pq += p\n time += ts(p)\n }\n }\n if (pq.size > max) max = pq.size\n }\n\n time = 0L\n pq.clear()\n for (p <- problems) {\n if (time + ts(p) <= t) {\n pq += p\n time += ts(p)\n } else {\n while (pq.size >= as(p)) {\n val rem = pq.dequeue()\n time -= ts(rem)\n }\n if (time + ts(p) <= t) {\n pq += p\n time += ts(p)\n }\n }\n if (pq.size == max) {\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(max)\n println(max)\n println(pq.toArray.map(_ + 1).mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n }\n}\n"}, {"source_code": "import java.util\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n\n val Array(n, t) = readInts(2)\n val problems0 = Array.tabulate(n)(identity)\n val as, ts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val Array(a, t) = readInts(2)\n as(i) = a\n ts(i) = t\n }\n\n val problems = problems0.sortBy(p => (-as(p), ts(p)))\n val MAXT = ts.max\n\n val pq = Array.fill(MAXT + 1)(0)\n\n var max = 0L\n var time = 0L\n var count = 0\n\n def take(p: Int) = {\n count += 1\n pq(ts(p)) += 1\n time += ts(p)\n }\n\n def remove(tt: Int) = {\n count -= 1\n pq(tt) -= 1\n time -= tt\n }\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n while (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0 && tt > 0) {\n tt -= 1\n }\n if (tt > ts(p)) remove(tt)\n }\n if (count < as(p) && time + ts(p) <= t) {\n take(p)\n }\n }\n if (count > max) {\n max = count\n }\n }\n\n println(max)\n time = 0L\n count = 0\n util.Arrays.fill(pq, 0)\n\n for (p <- problems) {\n if (time + ts(p) <= t && count < as(p)) {\n take(p)\n } else {\n var tt = MAXT\n while (count >= as(p) && tt > ts(p)) {\n while (pq(tt) == 0 && tt > 0) {\n tt -= 1\n }\n if (tt > ts(p)) remove(tt)\n }\n if (count < as(p) && time + ts(p) <= t) {\n take(p)\n }\n }\n if (count == max) {\n print()\n }\n }\n\n def print() = {\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(max)\n val res = ArrayBuffer.empty[Int]\n for (p <- problems) {\n if (pq(ts(p)) > 0) {\n res += p + 1\n pq(ts(p)) -= 1\n }\n }\n println(res.mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n\n}\n"}], "src_uid": "5294cad0d35a6c8ed40a8322ba5fd7b1"} {"source_code": "import scala.+:\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable._\r\nimport scala.collection.immutable._\r\nimport scala.util.Sorting.quickSort\r\nimport scala.math._\r\nimport scala.io.StdIn\r\n\r\nobject Main extends App {\r\n\r\n val arr = StdIn.readLine.split(\" \").map(_.toInt)\r\n val n = arr(0)\r\n val q = arr(1)\r\n val s = StdIn.readLine()\r\n val c = new Array[Char](n + 1)\r\n var cnt = 0\r\n for (i <- s.indices) {\r\n c(i + 1) = s(i)\r\n }\r\n for (i <- 3 to n) {\r\n if (c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a') {\r\n cnt += 1\r\n }\r\n }\r\n def ok(i: Int): Int = {\r\n if (i >= 2 && c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a')\r\n return 1\r\n if (\r\n i >= 1 && i + 1 <= n && c(i + 1) == 'c' && c(i) == 'b' && c(i - 1) == 'a'\r\n )\r\n return 1\r\n if (i + 2 <= n && c(i + 2) == 'c' && c(i + 1) == 'b' && c(i) == 'a')\r\n return 1\r\n return 0\r\n }\r\n var po = 0\r\n var r = \"\"\r\n for (j <- 1 to q) {\r\n val query = StdIn.readLine.split(\" \")\r\n po = query(0).toInt\r\n r = query(1)\r\n cnt -= ok(po)\r\n c(po) = r(0)\r\n cnt += ok(po)\r\n println(cnt)\r\n }\r\n\r\n def check(kk: Int): Boolean = {\r\n return true\r\n }\r\n def bs(st: Int, en: Int): Int = {\r\n if (en - st <= 1) {\r\n if (check(en))\r\n return en\r\n else\r\n return st\r\n }\r\n val mid = (st + en) / 2\r\n if (check(mid))\r\n return bs(mid, en)\r\n else\r\n return bs(st, mid)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.+:\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable._\r\nimport scala.collection.immutable._\r\nimport scala.util.Sorting.quickSort\r\nimport scala.math._\r\nimport scala.io.StdIn\r\n\r\nobject Main extends App {\r\n\r\n val arr = StdIn.readLine.split(\" \").map(_.toInt)\r\n val n = arr(0)\r\n val q = arr(1)\r\n val s = StdIn.readLine()\r\n val c = new Array[Char](n + 1)\r\n var cnt = 0\r\n for (i <- s.indices) {\r\n c(i + 1) = s(i)\r\n }\r\n for (i <- 3 to n) {\r\n if (c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a') {\r\n cnt += 1\r\n }\r\n }\r\n def ok(i: Int): Int = {\r\n if (i >= 2 && c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a')\r\n return 1\r\n if (\r\n i >= 1 && i + 1 <= n && c(i + 1) == 'c' && c(i) == 'b' && c(i - 1) == 'a'\r\n )\r\n return 1\r\n if (i + 2 <= n && c(i + 2) == 'c' && c(i + 1) == 'b' && c(i) == 'a')\r\n return 1\r\n return 0\r\n }\r\n var po = 0\r\n var r = \"\"\r\n for (j <- 1 to q) {\r\n val (poa: String, ra: String) = StdIn.readf2(\"{0} {1}\")\r\n po = poa.toInt\r\n r = ra\r\n cnt -= ok(po)\r\n c(po) = r(0)\r\n cnt += ok(po)\r\n println(cnt)\r\n }\r\n\r\n def check(kk: Int): Boolean = {\r\n return true\r\n }\r\n def bs(st: Int, en: Int): Int = {\r\n if (en - st <= 1) {\r\n if (check(en))\r\n return en\r\n else\r\n return st\r\n }\r\n val mid = (st + en) / 2\r\n if (check(mid))\r\n return bs(mid, en)\r\n else\r\n return bs(st, mid)\r\n }\r\n}\r\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(val a: Int, val b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return -1 * a.compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mp = mutable.Map[Char, Int]()\n\n val t = 1//readInt()\n\n\n for (tt <- 1 to t) {\n val n = readInt()\n val c = new Array[Char](n+1)\n val q = readInt()\n val s = readString()\n var cnt = 0\n for (i <- s.indices) {\n c(i+1) = s(i)\n }\n for (i <- 3 to n) {\n if (c(i) == 'c' && c(i-1) == 'b' && c(i-2) == 'a') {\n cnt += 1\n }\n }\n def ok(i: Int): Int = {\n if (i >= 2 && c(i) == 'c' && c(i-1) == 'b' && c(i-2) == 'a')\n return 1\n if (i >= 1 && i+1 <= n && c(i + 1) == 'c' && c(i) == 'b' && c(i-1) == 'a')\n return 1\n if (i+2 <= n && c(i + 2) == 'c' && c(i+1) == 'b' && c(i) == 'a')\n return 1\n return 0\n }\n var po = 0\n var r = \"\"\n for (j <- 1 to q) {\n po = readInt()\n r = readString()\n cnt -= ok(po)\n c(po) = r(0)\n cnt += ok(po)\n writer.println(cnt)\n }\n \n def check(kk: Int): Boolean = {\n return true\n }\n def bs(st:Int, en:Int): Int = {\n if (en - st <= 1) {\n if (check(en))\n return en\n else\n return st\n }\n val mid = (st + en) / 2\n if (check(mid))\n return bs(mid, en)\n else\n return bs(st, mid)\n }\n }\n writer.flush()\n}\n"}, {"source_code": "import scala.+:\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable._\r\nimport scala.collection.immutable._\r\nimport scala.util.Sorting.quickSort\r\nimport scala.math._\r\nimport scala.io.StdIn\r\nimport java.io.PrintWriter\r\n\r\nobject Main extends App {\r\n val writer = new PrintWriter(System.out, false)\r\n val arr = StdIn.readLine.split(\" \").map(_.toInt)\r\n val n = arr(0)\r\n val q = arr(1)\r\n var s = StdIn.readLine()\r\n val c = new Array[Char](n + 1)\r\n for (i <- s.indices) {\r\n c(i + 1) = s(i)\r\n }\r\n var num = 0\r\n c.indices\r\n .foreach(i => {\r\n if (c(i) == 'a' && i <= n - 2) {\r\n if (c(i + 1) == 'b' && c(i + 2) == 'c') {\r\n num += 1\r\n }\r\n }\r\n })\r\n\r\n (0 until q).foreach { i =>\r\n val (pos, char) = StdIn.readLine().split(\" \") match {\r\n case Array(a, b) => (a.toInt, b.charAt(0))\r\n }\r\n if (char == c(pos)) {\r\n writer.println(num)\r\n } else {\r\n def ok(i: Int): Boolean = {\r\n if (i >= 2 && c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a')\r\n return true\r\n else if (\r\n i >= 1 && i + 1 <= n && c(i + 1) == 'c' && c(i) == 'b' && c(\r\n i - 1\r\n ) == 'a'\r\n )\r\n return true\r\n else if (\r\n i + 2 <= n && c(i + 2) == 'c' && c(i + 1) == 'b' && c(i) == 'a'\r\n )\r\n return true\r\n return false\r\n }\r\n val f1 = ok(pos)\r\n c(pos) = char\r\n val f2 = ok(pos)\r\n if (f1 && !f2) {\r\n num -= 1\r\n } else if (!f1 && f2) {\r\n num += 1\r\n }\r\n\r\n writer.println(num)\r\n }\r\n }\r\n writer.flush()\r\n}\r\n"}, {"source_code": "import scala.+:\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable._\r\nimport scala.collection.immutable._\r\nimport scala.util.Sorting.quickSort\r\nimport scala.math._\r\nimport scala.io.StdIn\r\nimport java.io.PrintWriter\r\n\r\nobject Main extends App {\r\n val writer = new PrintWriter(System.out, false)\r\n val arr = StdIn.readLine.split(\" \").map(_.toInt)\r\n val n = arr(0)\r\n val q = arr(1)\r\n var s = StdIn.readLine()\r\n val c = new Array[Char](n + 1)\r\n for (i <- s.indices) {\r\n c(i + 1) = s(i)\r\n }\r\n var num = 0\r\n c.indices\r\n .foreach(i => {\r\n if (c(i) == 'a' && i <= n - 2) {\r\n if (c(i + 1) == 'b' && c(i + 2) == 'c') {\r\n num += 1\r\n }\r\n }\r\n })\r\n\r\n (0 until q).foreach { i =>\r\n val (pos, char) = StdIn.readLine().split(\" \") match {\r\n case Array(a, b) => (a.toInt, b.charAt(0))\r\n }\r\n if (char == c(pos)) {\r\n writer.println(num)\r\n } else {\r\n def testChar(char: Char) = char match {\r\n case 'a' => {\r\n if (pos <= n - 2) {\r\n c(pos + 1) == 'b' && c(pos + 2) == 'c'\r\n } else {\r\n false\r\n }\r\n }\r\n case 'b' => {\r\n if (pos <= n - 1 && pos >= 2) {\r\n c(pos - 1) == 'a' && c(pos + 1) == 'c'\r\n } else {\r\n false\r\n }\r\n }\r\n case 'c' => {\r\n if (pos >= 3) {\r\n c(pos - 1) == 'b' && c(pos - 2) == 'a'\r\n } else {\r\n false\r\n }\r\n }\r\n }\r\n val f1 = testChar(c(pos))\r\n val f2 = testChar(char)\r\n if (f1 && !f2) {\r\n num -= 1\r\n } else if (!f1 && f2) {\r\n num += 1\r\n }\r\n c(pos) = char\r\n writer.println(num)\r\n }\r\n }\r\n writer.flush()\r\n}\r\n"}, {"source_code": "import scala.+:\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable._\r\nimport scala.collection.immutable._\r\nimport scala.util.Sorting.quickSort\r\nimport scala.math._\r\nimport scala.io.StdIn\r\nimport java.io.PrintWriter\r\n\r\nobject Main extends App {\r\n val writer = new PrintWriter(System.out, false)\r\n val arr = StdIn.readLine.split(\" \").map(_.toInt)\r\n val n = arr(0)\r\n val q = arr(1)\r\n var s = StdIn.readLine()\r\n val c = new Array[Char](n + 1)\r\n for (i <- s.indices) {\r\n c(i + 1) = s(i)\r\n }\r\n var num = c.indices\r\n .map(i => {\r\n if (c(i) == 'a' && i <= n - 2) {\r\n if (c(i + 1) == 'b' && c(i + 2) == 'c') {\r\n 1\r\n } else {\r\n 0\r\n }\r\n } else {\r\n 0\r\n }\r\n })\r\n .sum\r\n (0 until q).foreach { i =>\r\n val (pos, char) = StdIn.readLine().split(\" \") match {\r\n case Array(a, b) => (a.toInt, b.charAt(0))\r\n }\r\n if (char == c(pos)) {\r\n writer.println(num)\r\n } else {\r\n def testChar(char: Char) = char match {\r\n case 'a' => {\r\n if (pos <= n - 2) {\r\n c(pos + 1) == 'b' && c(pos + 2) == 'c'\r\n } else {\r\n false\r\n }\r\n }\r\n case 'b' => {\r\n if (pos <= n - 1 && pos >= 2) {\r\n c(pos - 1) == 'a' && c(pos + 1) == 'c'\r\n } else {\r\n false\r\n }\r\n }\r\n case 'c' => {\r\n if (pos >= 3) {\r\n c(pos - 1) == 'b' && c(pos - 2) == 'a'\r\n } else {\r\n false\r\n }\r\n }\r\n }\r\n val f1 = testChar(c(pos))\r\n val f2 = testChar(char)\r\n if (f1 && !f2) {\r\n num -= 1\r\n } else if (!f1 && f2) {\r\n num += 1\r\n }\r\n c(pos) = char\r\n writer.println(num)\r\n }\r\n }\r\n writer.flush()\r\n}\r\n"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.+:\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable._\r\nimport scala.collection.immutable._\r\nimport scala.util.Sorting.quickSort\r\nimport scala.math._\r\n\r\nobject Main extends App {\r\n val writer = new PrintWriter(System.out, false)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {\r\n while (!st.hasMoreTokens) { st = new StringTokenizer(reader.readLine()) };\r\n st.nextToken()\r\n }\r\n def readInt(): Int = next().toInt\r\n def readLong(): Long = next().toLong\r\n def readString(): String = next()\r\n case class fenwick(n: Int) {\r\n val tree = new Array[Long](n + 1)\r\n def query(ind: Int): Long = {\r\n var idx = ind\r\n var ans = 0L\r\n while (idx > 0) {\r\n ans += tree(idx)\r\n idx -= (idx & -idx)\r\n }\r\n return ans\r\n }\r\n def update(ind: Int, value: Long): Unit = {\r\n var idx = ind\r\n while (idx <= n) {\r\n tree(idx) += value\r\n idx += (idx & -idx)\r\n }\r\n }\r\n }\r\n case class pair(val a: Int, val b: Int) extends Ordered[pair] {\r\n override def compare(that: pair): Int = {\r\n return -1 * a.compareTo(that.a)\r\n }\r\n }\r\n def gcd(a: Int, b: Int): Int = b match {\r\n case 0 => a\r\n case n => gcd(b, a % b)\r\n }\r\n val rem = 1000000007\r\n val maxn = 200010\r\n val mp = mutable.Map[Char, Int]()\r\n val t = 1 //readInt()\r\n for (tt <- 1 to t) {\r\n val n = readInt()\r\n val c = new Array[Char](n + 1)\r\n val q = readInt()\r\n val s = readString()\r\n var cnt = 0\r\n for (i <- s.indices) {\r\n c(i + 1) = s(i)\r\n }\r\n for (i <- 3 to n) {\r\n if (c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a') {\r\n cnt += 1\r\n }\r\n }\r\n def ok(i: Int): Int = {\r\n if (i >= 2 && c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a')\r\n return 1\r\n if (\r\n i >= 1 && i + 1 <= n && c(i + 1) == 'c' && c(i) == 'b' && c(\r\n i - 1\r\n ) == 'a'\r\n )\r\n return 1\r\n if (i + 2 <= n && c(i + 2) == 'c' && c(i + 1) == 'b' && c(i) == 'a')\r\n return 1\r\n return 0\r\n }\r\n var po = 0\r\n var r = \"\"\r\n for (j <- 1 to q) {\r\n po = readInt()\r\n r = readString()\r\n cnt -= ok(po)\r\n c(po) = r(0)\r\n cnt += ok(po)\r\n println(cnt)\r\n }\r\n\r\n def check(kk: Int): Boolean = {\r\n return true\r\n }\r\n def bs(st: Int, en: Int): Int = {\r\n if (en - st <= 1) {\r\n if (check(en))\r\n return en\r\n else\r\n return st\r\n }\r\n val mid = (st + en) / 2\r\n if (check(mid))\r\n return bs(mid, en)\r\n else\r\n return bs(st, mid)\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.+:\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable._\r\nimport scala.collection.immutable._\r\nimport scala.util.Sorting.quickSort\r\nimport scala.math._\r\n\r\nobject Main extends App {\r\n val writer = new PrintWriter(System.out, false)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {\r\n while (!st.hasMoreTokens) { st = new StringTokenizer(reader.readLine()) };\r\n st.nextToken()\r\n }\r\n def readInt(): Int = next().toInt\r\n def readLong(): Long = next().toLong\r\n def readString(): String = next()\r\n case class fenwick(n: Int) {\r\n val tree = new Array[Long](n + 1)\r\n def query(ind: Int): Long = {\r\n var idx = ind\r\n var ans = 0L\r\n while (idx > 0) {\r\n ans += tree(idx)\r\n idx -= (idx & -idx)\r\n }\r\n return ans\r\n }\r\n def update(ind: Int, value: Long): Unit = {\r\n var idx = ind\r\n while (idx <= n) {\r\n tree(idx) += value\r\n idx += (idx & -idx)\r\n }\r\n }\r\n }\r\n case class pair(val a: Int, val b: Int) extends Ordered[pair] {\r\n override def compare(that: pair): Int = {\r\n return -1 * a.compareTo(that.a)\r\n }\r\n }\r\n def gcd(a: Int, b: Int): Int = b match {\r\n case 0 => a\r\n case n => gcd(b, a % b)\r\n }\r\n val rem = 1000000007\r\n val maxn = 200010\r\n val mp = mutable.Map[Char, Int]()\r\n val t = 1 //readInt()\r\n for (tt <- 1 to t) {\r\n val n = readInt()\r\n val c = new Array[Char](n + 1)\r\n val q = readInt()\r\n val s = readString()\r\n var cnt = 0\r\n for (i <- s.indices) {\r\n c(i + 1) = s(i)\r\n }\r\n for (i <- 3 to n) {\r\n if (c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a') {\r\n cnt += 1\r\n }\r\n }\r\n def ok(i: Int): Int = {\r\n if (i >= 2 && c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a')\r\n return 1\r\n if (\r\n i >= 1 && i + 1 <= n && c(i + 1) == 'c' && c(i) == 'b' && c(\r\n i - 1\r\n ) == 'a'\r\n )\r\n return 1\r\n if (i + 2 <= n && c(i + 2) == 'c' && c(i + 1) == 'b' && c(i) == 'a')\r\n return 1\r\n return 0\r\n }\r\n var po = 0\r\n var r = \"\"\r\n for (j <- 1 to q) {\r\n po = readInt()\r\n r = readString()\r\n cnt -= ok(po)\r\n c(po) = r(0)\r\n cnt += ok(po)\r\n writer.println(cnt)\r\n }\r\n\r\n def check(kk: Int): Boolean = {\r\n return true\r\n }\r\n def bs(st: Int, en: Int): Int = {\r\n if (en - st <= 1) {\r\n if (check(en))\r\n return en\r\n else\r\n return st\r\n }\r\n val mid = (st + en) / 2\r\n if (check(mid))\r\n return bs(mid, en)\r\n else\r\n return bs(st, mid)\r\n }\r\n }\r\n writer.flush()\r\n}\r\n"}], "negative_code": [{"source_code": "import scala.+:\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable._\r\nimport scala.collection.immutable._\r\nimport scala.util.Sorting.quickSort\r\nimport scala.math._\r\nimport scala.io.StdIn\r\nimport java.io.PrintWriter\r\n\r\nobject Main extends App {\r\n val writer = new PrintWriter(System.out, false)\r\n val arr = StdIn.readLine.split(\" \").map(_.toInt)\r\n val n = arr(0)\r\n val q = arr(1)\r\n var s = StdIn.readLine()\r\n var num = s.indices\r\n .map(i => {\r\n if (s(i) == 'a' && i < n - 2) {\r\n if (s(i + 1) == 'b' && s(i + 2) == 'c') {\r\n 1\r\n } else {\r\n 0\r\n }\r\n } else {\r\n 0\r\n }\r\n })\r\n .sum\r\n (0 until q).foreach { i =>\r\n val (pos, c) = StdIn.readLine().split(\" \") match {\r\n case Array(a, b) => (a.toInt, b.charAt(0))\r\n }\r\n if (c == s(pos - 1)) {\r\n println(num)\r\n } else {\r\n def testChar(c: Char) = c match {\r\n case 'a' => {\r\n if (pos <= n - 2) {\r\n s(pos) == 'b' && s(pos + 1) == 'c'\r\n } else {\r\n false\r\n }\r\n }\r\n case 'b' => {\r\n if (pos <= n - 1 && pos >= 2) {\r\n s(pos - 2) == 'a' && s(pos) == 'c'\r\n } else {\r\n false\r\n }\r\n }\r\n case 'c' => {\r\n if (pos >= 3) {\r\n s(pos - 2) == 'b' && s(pos - 3) == 'a'\r\n } else {\r\n false\r\n }\r\n }\r\n }\r\n val f1 = testChar(s(pos - 1))\r\n val f2 = testChar(c)\r\n if (f1 && !f2) {\r\n num -= 1\r\n } else if (!f1 && f2) {\r\n num += 1\r\n }\r\n s = s.updated(pos - 1, c)\r\n writer.println(num)\r\n }\r\n }\r\n writer.flush()\r\n}"}], "src_uid": "db473ad780a93983667d12b1357c6e2f"} {"source_code": "import java.util.PriorityQueue\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject CE976B extends App {\n val nums = readLine().split(\" \")\n val n = nums(0).toInt;\n val k = nums(1).toInt;\n var hotelCounts = 0;\n if (k % 2 == 1 && n % 2 == 0) {\n println(\"NO\")\n }\n else {\n println(\"YES\")\n var ans = Array.ofDim[Char](4, n)\n for (i <- 0 to 3) {\n\n for (j <- 0 until n) ans(i)(j) = '.'\n }\n if (k % 2 == 1) {\n if (k > n - 2) {\n ans = fillRow(ans, 1, n, n - 2)\n ans = fillRow(ans, 2, n, k - n + 2)\n } else {\n ans = fillRow(ans, 1, n, k)\n }\n } else {\n val dis = k / 2;\n for (i <- 1 to 2)\n for (j <- 1 until n - 1) {\n if (j <= dis) ans(i)(j) = '#'\n }\n }\n\n for (i <- 0 to 3) {\n for (j <- 0 to n - 1) {\n print(ans(i)(j))\n }\n println()\n }\n\n }\n\n\n def fillRow(ans: Array[Array[Char]], row: Int, n: Int, k: Int): Array[Array[Char]] = {\n var ret = ans\n val dis = (n - k) / 2;\n for (i <- 0 until n) {\n if (i >= dis && i < n - dis)\n ret(row)(i) = '#'\n }\n if (k % 2 == 0)\n ret(row)(n / 2) = '.'\n return ret\n }\n\n}\n", "positive_code": [{"source_code": "object B extends App {\n // 3 <= n <= 99\n // 0 <= k <= 2 * (n - 2)\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n if (k % 2 == 0) {\n println(\"YES\")\n println(\".\" * n)\n val r = k / 2\n println(\".\" + \"#\" * r + \".\" * (n - 1 - r))\n println(\".\" + \"#\" * r + \".\" * (n - 1 - r))\n println(\".\" * n)\n } else if (k == n - 2) {\n println(\"YES\")\n println(\".\" * n)\n println(\".\" + \"#\" * (n - 2) + \".\")\n println(\".\" * n)\n println(\".\" * n)\n } else if (k > n - 2) {\n println(\"YES\")\n println(\".\" * n)\n println(\".\" + \"#\" * (n - 2) + \".\")\n val r = k - n + 2\n println(\".#\" + \"#\" * (r - 2) + \".\" * (n - r - 2) + \"#.\")\n println(\".\" * n)\n } else {\n println(\"YES\")\n println(\".\" * n)\n val t = (n - k) / 2\n println(\".\" * t + \"#\" * k + \".\" * t)\n println(\".\" * n)\n println(\".\" * n)\n }\n}\n"}, {"source_code": "import scala.io.StdIn;\n\nobject Necklace {\n def main(args: Array[String]): Unit = {\n val n :: k :: Nil = readLine split(\" \") map (_.toInt) toList;\n val mid = n >> 1;\n def getCount (x: Int): Int = Math.min(x, n - x - 1) * 2\n def getPlacement(x: Int, y: Int): Char =\n if (y == 0 || y == n - 1) '.'\n else if (k == 2 * (n - 2)) '#'\n else if (y == mid) (if ((k % 2) == 1 && (x == 0)) '#' else '.') \n else if (x == 0) (if (getCount(y) <= k) '#' else '.')\n else if (getCount(y) <= (k - n + 3)) '#' else '.'\n println(\"YES\");\n println(\".\" * n);\n val lines = for (i <- 0 to 1) yield\n (for (j <- 0 to n - 1) yield getPlacement(i, j)).mkString(\"\")\n println(lines.mkString(\"\\n\"));\n println(\".\" * n);\n }\n} \n"}], "negative_code": [{"source_code": "import java.util.PriorityQueue\n\nimport scala.collection.mutable\n\nobject CE976B extends App {\n val nums = readLine().split(\" \")\n val n = nums(0).toInt;\n val k = nums(1).toInt;\n var hotelCounts = 0;\n println(\"YES\")\n for (i <- 1 to 4) {\n for (j <- 1 to n) {\n if (i > 1 && i < 4 && j > 1 && j < n && hotelCounts < k) {\n print('#')\n hotelCounts += 1\n }\n else {\n print(\".\")\n }\n }\n println()\n }\n\n\n}\n"}, {"source_code": "object B extends App {\n // 3 <= n <= 99\n // 0 <= k <= 2 * (n - 2)\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n if (k % 2 == 0) {\n println(\"YES\")\n println(\".\" * n)\n val r = k / 2\n println(\".\" + \"#\" * r + \".\" * (n - 1 - r))\n println(\".\" + \"#\" * r + \".\" * (n - 1 - r))\n println(\".\" * n)\n } else if (k == n - 2) {\n println(\"YES\")\n println(\".\" * n)\n println(\".\" + \"#\" * (n - 2) + \".\")\n println(\".\" * n)\n println(\".\" * n)\n } else if (k > n - 2) {\n println(\"YES\")\n println(\".\" * n)\n println(\".\" + \"#\" * (n - 2) + \".\")\n val r = k - n + 2\n println(\".#\" + \"#\" * (r - 2) + \".\" * (n - r - 2) + \"#.\")\n println(\".\" * n)\n } else {\n println(\"NO\")\n }\n}\n"}, {"source_code": "object B extends App {\n // 3 <= n <= 99\n // 0 <= k <= 2 * (n - 2)\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n if (k % 2 == 0) {\n println(\"YES\")\n println(\".\" * n)\n val r = k / 2\n println(\".\" + \"#\" * r + \".\" * (n - 1 - r))\n println(\".\" + \"#\" * r + \".\" * (n - 1 - r))\n println(\".\" * n)\n } else if (k == n - 2) {\n println(\"YES\")\n println(\".\" * n)\n println(\".\" + \"#\" * (n - 2) + \".\")\n println(\".\" * n)\n println(\".\" * n)\n } else if (k >= n - 4) {\n println(\"YES\")\n println(\".\" * n)\n println(\".\" + \"#\" * (n - 2) + \".\")\n val r = k - n\n println(\".#\" + \".\" * (n - 4 - r) + \"#\" * (r - 1) + \"#.\")\n println(\".\" * n)\n } else {\n println(\"NO\")\n }\n}\n"}, {"source_code": "object B extends App {\n // 3 <= n <= 99\n // 0 <= k <= 2 * (n - 2)\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n if (k >= n - 2) {\n println(\"YES\")\n println(\".\" * n)\n println(\".\" + \"#\" * (n - 2) + \".\")\n val r = k - n + 2\n println(\".\" + \".\" * (n - 2 - r) + \"#\" * r + \".\")\n println(\".\" * n)\n } else if (k % 2 == 0) {\n println(\"YES\")\n println(\".\" * n)\n val r = k / 2\n println(\".\" + \"#\" * r + \".\" * (n - 1 - r) )\n println(\".\" + \"#\" * r + \".\" * (n - 1 - r) )\n println(\".\" * n)\n } else {\n println(\"NO\")\n }\n}\n"}, {"source_code": "object B extends App {\n // 3 <= n <= 99\n // 0 <= k <= 2 * (n - 2)\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n if (k % 2 == 0) {\n println(\"YES\")\n println(\".\" * n)\n val r = k / 2\n println(\".\" + \"#\" * r + \".\" * (n - 1 - r) )\n println(\".\" + \"#\" * r + \".\" * (n - 1 - r) )\n println(\".\" * n)\n } else if (k >= n - 2) {\n println(\"YES\")\n println(\".\" * n)\n println(\".\" + \"#\" * (n - 2) + \".\")\n val r = k - n + 2\n println(\".\" + \".\" * (n - 2 - r) + \"#\" * r + \".\")\n println(\".\" * n)\n } else if (k > 1) {\n println(\"YES\")\n println(\".\" * n)\n println(\".\" + \"#\" * (k - 1) + \".\" * (n - k))\n println(\".\" + \".\" * (k - 2) + \"#\" + \".\" * (n - k))\n println(\".\" * n)\n } else {\n println(\"NO\")\n }\n}\n"}, {"source_code": "import scala.io.StdIn;\n\nobject Necklace {\n def main(args: Array[String]): Unit = {\n val n :: k :: Nil = readLine split(\" \") map (_.toInt) toList;\n val mid = n >> 1;\n def getCount (x: Int): Int = Math.min(x, n - x - 1) * 2\n def getPlacement(x: Int, y: Int): Char =\n if (y == 0 || y == n - 1) '.'\n else if (k == 2 * (n - 2)) '#'\n else if (y == mid) (if ((k % 2) == 1 && (x == 0)) '#' else '.') \n else if (x == 0) (if (getCount(y) <= k) '#' else '.')\n else if (getCount(y) <= (k - n + 2)) '#' else '.'\n println(\"YES\");\n println(\".\" * n);\n val lines = for (i <- 0 to 1) yield\n (for (j <- 0 to n - 1) yield getPlacement(i, j)).mkString(\"\")\n println(lines.mkString(\"\\n\"));\n println(\".\" * n);\n }\n} \n"}], "src_uid": "2669feb8200769869c4b2c29012059ed"} {"source_code": "import scala.collection.mutable\n\n//package e\n\nobject E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k) = readInts(2)\n val us = readInts(2 * k).map(_ - 1).toSet\n\n val adjBuilders = Array.fill(n){new mutable.ArrayBuilder.ofInt}\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n\n def dfs(parent: Int, u: Int): (Int, Long) = {\n// var cables = cables0\n var resBelow = 0L\n var uCountBelow = 0\n\n if (us(u)) {\n uCountBelow += 1\n }\n\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v != parent) {\n val (uBel, resBel) = dfs(u, v)\n resBelow += resBel\n uCountBelow += uBel\n }\n i += 1\n }\n//println(u, (uCountBelow, resBelow + Math.min(2 * k - uCountBelow, uCountBelow)))\n (uCountBelow, resBelow + Math.min(2 * k - uCountBelow, uCountBelow))\n }\n\n val res = dfs(-1, 0)\n\n println(res._2)\n}\n", "positive_code": [{"source_code": "import scala.collection.immutable.BitSet\nimport scala.collection.mutable\n\nobject E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val us = BitSet.empty ++ readInts(2 * k).map(_ - 1)\n\n val adjBuilders = Array.fill(n){new mutable.ArrayBuilder.ofInt}\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n\n def dfs(parent: Int, u: Int): (Int, Long) = {\n\n var resBelow = 0L\n var uCountBelow = 0\n\n if (us(u)) {\n uCountBelow += 1\n }\n\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v != parent) {\n val (uBel, resBel) = dfs(u, v)\n resBelow += resBel\n uCountBelow += uBel\n }\n i += 1\n }\n\n (uCountBelow, resBelow + Math.min(2 * k - uCountBelow, uCountBelow))\n }\n\n val (_, res) = dfs(-1, 0)\n\n println(res)\n}\n"}, {"source_code": "import scala.collection.mutable.BitSet\nimport scala.collection.mutable\n\nobject E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val us = new BitSet(n)\n us ++= readInts(2 * k).map(_ - 1)\n\n val adjBuilders = Array.fill(n){new mutable.ArrayBuilder.ofInt}\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n\n def dfs(parent: Int, u: Int): (Int, Long) = {\n\n var resBelow = 0L\n var uCountBelow = 0\n\n if (us(u)) {\n uCountBelow += 1\n }\n\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v != parent) {\n val (uBel, resBel) = dfs(u, v)\n resBelow += resBel\n uCountBelow += uBel\n }\n i += 1\n }\n\n (uCountBelow, resBelow + Math.min(2 * k - uCountBelow, uCountBelow))\n }\n\n val (_, res) = dfs(-1, 0)\n\n println(res)\n}\n"}, {"source_code": "import scala.collection.mutable\n\n//package e\n\nobject E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k) = readInts(2)\n val us = readInts(2 * k).map(_ - 1).toSet\n\n val adjBuilders = Array.fill(n){new mutable.ArrayBuilder.ofInt}\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n\n def dfs(parent: Int, u: Int, cables0: Int): (Int, Long) = {\n// var cables = cables0\n var resBelow = 0L\n var uCountBelow = 0\n\n if (us(u)) {\n uCountBelow += 1\n// if (uCount <= k) cables += 1\n// else cables -= 1\n }\n\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v != parent) {\n val (uBel, resBel) = dfs(u, v, cables0)\n resBelow += resBel\n uCountBelow += uBel\n }\n i += 1\n }\n//println(u, (uCountBelow, resBelow + Math.min(2 * k - uCountBelow, uCountBelow)))\n (uCountBelow, resBelow + Math.min(2 * k - uCountBelow, uCountBelow))\n }\n\n val res = dfs(-1, 0, 0)\n\n println(res._2)\n}\n"}], "negative_code": [], "src_uid": "ca22cf92727a38fbb3c085b9362602db"} {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, _, b) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val s = (0 until n).map(i => ('a' + i % b).toChar).mkString(\"\")\n\n println(s)\n }\n}", "positive_code": [{"source_code": "object B extends App {\n case class Sub(n: Int, a: Int, b: Int)\n\n private def construct(s: Sub): String =\n (Range('a', 'z' + 1).take(s.b).map(_.toChar).mkString(\"\") * (1 + s.n / s.b))\n .take(s.n)\n\n val t = scala.io.StdIn.readInt()\n\n val input = (0 until t)\n .foldLeft(List.empty[Sub]) { (acc, _) =>\n val Array(n, a, b) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n Sub(n, a, b) :: acc\n }\n .reverse\n\n val output = input.map(construct)\n\n output.foreach(println)\n}"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, _, b) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val s = (('a' to 'z').take(b).mkString(\"\") * (1 + n / b)).take(n)\n\n println(s)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Solution_B extends App {\n val T = StdIn.readInt()\n for (t <- 1 to T) {\n val input = StdIn.readLine().split(\" \").map{_.toInt}\n val N = input(0)\n val A = input(1)\n val B = input(2)\n val result = new StringBuilder()\n val pattern = Array.fill[Char](A)('a')\n for (c <- A - B + 1 until A) {\n pattern(c) = (pattern(c - 1) + 1).toChar\n }\n var offset = 0\n for (c <- 0 until N) {\n result.append(pattern(offset))\n offset += 1\n offset %= A\n }\n println(result.toString())\n }\n}\n"}, {"source_code": "\nobject Main extends App {\n import scala.io.StdIn._\n val t = readInt\n val alphabets = ('a' to 'z').mkString\n for(_ <- 0 until t) {\n val Array(n, a, b) = readLine.trim.split(' ').map(_.toInt)\n println(((alphabets.take(b) + \"a\" * (a - b)) * ((n + a - 1) / a)).take(n))\n }\n}\n"}], "negative_code": [{"source_code": "object B extends App {\n case class Sub(n: Int, a: Int, b: Int)\n\n private def construct(s: Sub): String =\n (Range('a', 'z').take(s.b).map(_.toChar).mkString(\"\") * (s.n / s.b + 1))\n .take(s.n)\n\n val t = scala.io.StdIn.readInt()\n\n val input = (0 until t)\n .foldLeft(List.empty[Sub]) { (acc, _) =>\n val Array(n, a, b) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n Sub(n, a, b) :: acc\n }\n .reverse\n\n val output = input.map(construct)\n\n output.foreach(println)\n}"}], "src_uid": "a82f15c1b0ddcacc1de966be20cfc5a2"} {"source_code": "import scala.collection.JavaConversions._\nimport scala.collection.mutable._\n\n\nobject Codeforces546B {\n def main(args: Array[String]) {\n val n = scala.io.StdIn.readLine().toInt\n val ar = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n var coins = 0\n for (i <- 1 until n) {\n if (ar(i) <= ar(i-1)) {\n coins += (ar(i-1) + 1 - ar(i))\n ar(i) = ar(i-1) + 1\n }\n }\n println(coins)\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args:Array[String]) {\n val sc = new java.util.Scanner(System.in)\n var pre, ans = 0\n Array.fill(sc.nextInt)(sc.nextInt).sorted.foreach { cur =>\n val up = Seq(cur - pre - 1, 0).min.abs\n ans += up\n pre = cur + up\n }\n println(ans)\n }\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _546B extends App {\n var token = new StringTokenizer(\"\")\n\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt)\n val cnt = Array.fill(2 * n + 10)(0)\n a.foreach(i => cnt(i) += 1)\n\n def doit(i: Int, acc: Int): Int = {\n// println(cnt.toList)\n if (i == cnt.length) acc\n else {\n val delta = (cnt(i) - 1) max 0\n cnt(i) -= delta\n if (i + 1 < cnt.length) cnt(i + 1) += delta\n doit(i + 1, acc + delta)\n }\n }\n\n println(doit(0, 0))\n}\n"}, {"source_code": "/**\n * Created by r on 5/23/15.\n */\nobject badge {\n def main (args: Array[String]) {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt //最初の整数が読み込まれる\n var ar = new Array[Int](n)\n for (i <- 0 to n-1)\n ar(i) = sc.nextInt\n scala.util.Sorting.quickSort(ar)\n var coin = 0\n var flg = false\n do {\n flg = false\n for (i <- 0 to n-2) {\n if (ar(i) >= ar(i + 1)) {\n ar(i + 1) = ar(i + 1) + 1\n coin = coin + 1\n flg = true\n }\n }\n } while(flg == true)\n\n println(coin)\n }\n}\n"}, {"source_code": "object R304_SoldierAndBadges extends App {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextLine().toInt\n val a = sc.nextLine().split(\" \").map(_.toInt).sorted\n\n var ans = 0\n var bef = a(0)\n (1 to a.length - 1).foreach { i =>\n var tmp = 0\n while (bef >= a(i) + tmp) {\n tmp += 1\n ans += 1\n }\n bef = a(i) + tmp\n }\n println(ans)\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\nobject _546B extends CodeForcesApp {\n import scala.collection.mutable\n\n override type Input = List[Int]\n override type Output = Int\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n List.fill(nextInt)(nextInt)\n }\n\n override def solve(input: Input) = {\n val used = mutable.Set.empty[Int]\n @tailrec\n def f(badges: List[Int], acc: Int): Int = badges match {\n case Nil => acc\n case x :: xs if used contains x =>\n val y = (Stream.from(x+1) find {i => !(used contains i)}).head\n f(y :: xs, (y - x) + acc)\n case x :: xs =>\n used += x\n f(xs, acc)\n }\n f(input, 0)\n }\n\n override def format(result: Output) = super.format(result)\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp extends App {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /********************************[ lib ]************************************/\n import scala.collection.mutable\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type m_=>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None\n /******************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n def timeLimitSecond = 1\n}\n"}, {"source_code": "object _546B extends CodeForcesApp {\n import scala.collection.mutable\n\n override type Input = List[Int]\n override type Output = Int\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n List.fill(nextInt)(nextInt)\n }\n\n override def solve(input: Input) = {\n val used = mutable.Set.empty[Int]\n\n def f(badges: List[Int]): Int = badges match {\n case Nil => 0\n case (x :: xs) if used contains x =>\n val y = ((x+1 to 10000) find (i => !(used contains i))).get\n used += y\n (y - x) + f(xs)\n case (x :: xs) =>\n used += x\n f(xs)\n }\n f(input)\n }\n\n override def format(result: Output) = super.format(result)\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp extends App {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /********************************[ lib ]************************************/\n import scala.collection.mutable\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type m_=>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None\n /******************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n def timeLimitSecond = 1\n}\n"}, {"source_code": "object _546B extends CodeForcesApp {\n import scala.collection.mutable\n\n override type Input = List[Int]\n override type Output = Int\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n List.fill(nextInt)(nextInt)\n }\n\n override def solve(input: Input) = {\n val used = mutable.Set.empty[Int]\n\n def f(badges: List[Int]): Int = badges match {\n case Nil => 0\n case x :: xs if used contains x =>\n val y = (Stream.from(x+1) find {i => !(used contains i)}).head\n (y - x) + f(y :: xs)\n case x :: xs =>\n used += x\n f(xs)\n }\n f(input)\n }\n\n override def format(result: Output) = super.format(result)\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp extends App {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /********************************[ lib ]************************************/\n import scala.collection.mutable\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type m_=>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None\n /******************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n def timeLimitSecond = 1\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n val a = Array.fill(6001)(0);\n var r = 0;\n\n def main(args: Array[String]): Unit = {\n StdIn.readLine(); // ignore\n StdIn.readLine().split(\" \").map(Integer.parseInt).foreach(a(_)+=1);\n\n for(i <- 0 to 6000) {\n if ( a(i) > 1 ) {\n val d = a(i) - 1;\n a(i+1) += d;\n r += d;\n }\n }\n\n println(r);\n }\n}"}, {"source_code": "import scala.io.StdIn\nimport scala.collection.SeqView\n\nobject Main {\n val a = Array.fill(6001)(0);\n var r = 0;\n\n def main(args: Array[String]): Unit = {\n StdIn.readLine(); // ignore\n StdIn.readLine().split(\" \").map(Integer.parseInt).foreach(a(_)+=1);\n\n for(i <- (0 to 6000).view if (a(i) > 1); d = a(i) - 1) {\n a(i+1) += d;\n r += d;\n }\n\n println(r);\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n readInt()\n val input = readLine().split(\" \").map(_.toInt).sorted\n val counter = new Array[Boolean](3000 * 3000 + 1)\n\n def solve() = {\n var answer = 0\n for (i <- input) {\n if (!counter(i)) counter(i) = true\n else {\n var find = i\n while (counter(find)) {\n answer += 1\n find += 1\n }\n counter(find) = true\n }\n }\n answer\n }\n\n println(solve())\n}\n"}, {"source_code": "import scala.io.StdIn._\n\n/**\n * Created by przemek on 23.05.15.\n */\nobject Badges {\n def main(args: Array[String]) = {\n val N = readInt()\n val badges = readLine().split(\" \").map(_.toInt).sortWith(_ < _)\n solve(N, badges)\n }\n\n\n def solve(N: Int, badges: Array[Int]) {\n var c = 0\n for (i <- 1 to N - 1) {\n if (badges(i) <= badges(i-1)) {\n c += badges(i-1) + 1 - badges(i)\n badges(i) = badges(i-1) + 1\n }\n }\n println(c)\n }\n}\n"}, {"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val n =nextInt\n val a=Array.fill(n)(0)\n for(i<-0 until n){a(i)=nextInt}\n scala.util.Sorting.quickSort(a)\n var sum=0\n for(i<-0 until n-1){\n var l=1+i\n while(l next.toInt)\n\n def doit(a: List[Int], acc: Int): Int =\n if (a == Nil) acc\n else if (a.count(i => i == a.head) > 1) doit(a.head + 1 :: a.tail, acc + 1)\n else doit(a.tail, acc)\n\n println(doit(a.toList, 0))\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _546B extends App {\n var token = new StringTokenizer(\"\")\n\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt).sorted\n\n def doit(a: List[Int], acc: Int): Int = {\n if (a == Nil) acc\n else if (a.count(i => i == a.head) > 1) doit(a.head + 1 :: a.tail, acc + 1)\n else doit(a.tail, acc)\n }\n\n println(doit(a.toList, 0))\n}\n"}, {"source_code": "object _546B extends CodeForcesApp {\n import scala.collection.mutable\n\n override type Input = List[Int]\n override type Output = Int\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n List.fill(nextInt)(nextInt)\n }\n\n override def solve(input: Input) = {\n def f(badges: List[Int]): Int = badges match {\n case Nil => 0\n case (x :: xs) if xs contains x =>\n val y = ((x+1 to 10000) find (i => !(xs contains i))).get\n (y - x) + f(y :: xs)\n case (x :: xs) => f(xs)\n }\n f(input)\n }\n\n override def format(result: Output) = super.format(result)\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp extends App {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /********************************[ lib ]************************************/\n import scala.collection.mutable\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type m_=>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None\n /******************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n def timeLimitSecond = 1\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n val a = Array.fill(6001)(0);\n var r = 0;\n\n def main(args: Array[String]): Unit = {\n StdIn.readLine(); // ignore\n StdIn.readLine().split(\" \").map(Integer.parseInt).foreach(a(_)+=1);\n\n for(i <- 0 to 6000 if a(i) > 1) {\n a(i+1) += 1;\n r += 1;\n }\n\n println(r);\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n val a = Array.fill(6001)(0);\n var r = 0;\n\n def main(args: Array[String]): Unit = {\n StdIn.readLine(); // ignore\n StdIn.readLine().split(\" \").map(Integer.parseInt).foreach(a(_)+=1);\n\n for(i <- 0 to 6000 if a(i) > 1; d = a(i) - 1) {\n a(i+1) += d;\n r += d;\n }\n\n println(r);\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\n/**\n * Created by przemek on 23.05.15.\n */\nobject Badges {\n def main(args: Array[String]) = {\n val N = readInt()\n val badges = readLine().split(\" \").map(_.toInt).sortWith(_ < _)\n println(badges.mkString(\" \"))\n solve(N, badges)\n }\n\n\n def solve(N: Int, badges: Array[Int]) {\n var c = 0\n for (i <- 1 to N - 1) {\n if (badges(i) <= badges(i-1)) {\n c += badges(i-1) + 1 - badges(i)\n badges(i) = badges(i-1) + 1\n }\n }\n println(c)\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\n/**\n * Created by przemek on 23.05.15.\n */\nobject Badges {\n def main(args: Array[String]) = {\n val N = readInt()\n val badges = readLine().split(\" \").map(_.toInt).sortWith(_ < _)\n\n var prev = 0\n var c = 0\n for (i <- 0 to N - 1) {\n if (badges(i) == prev) {\n badges(i) += 1\n c += 1\n }\n prev = badges(i)\n }\n println(c)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\n/**\n * Created by przemek on 23.05.15.\n */\nobject Badges {\n def main(args: Array[String]) = {\n val N = readInt()\n val badges = readLine().split(\" \").map(_.toInt).sortWith(_ < _)\n\n var prev = 0\n var c = 0\n for (i <- 0 to N - 1) {\n if (badges(i) <= prev) {\n badges(i) = prev +1\n c += badges(i) - prev\n }\n prev = badges(i)\n }\n println(c)\n }\n\n}\n"}], "src_uid": "53ae714f04fd29721b8bbf77576b7ccf"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(a, b, c, d) = in.next().split(' ').map(_.toDouble)\n val ab = a / b\n val cd = c / d * (1 - ab)\n println(ab / (ab + cd))\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(a, b, c, d) = readLine().split(\" \").map(_.toDouble)\n val p1 = a / b\n val p2 = c / d\n println(p1 / (1 - (1 - p1) * (1 - p2)))\n }\n}"}, {"source_code": "object P312B extends App {\n var str = readLine();\n var data_str = str.split(\" \");\n var datas = new Array[Integer](4);\n for (i <- 0 to 3) {\n datas.update(i, data_str(i).toInt);\n }\n var p = Array(1.0 * datas(0) / datas(1),1.0 * datas(2) / datas(3));\n //無限等比数列でした。。\n var answer =p(0)/(1-(1-p(0))*(1-p(1)))\n print(answer);\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(a, b, c, d) = readLine().split(\" \").map(_.toInt)\n val p1 = a.toFloat / b.toFloat\n val p2 = c.toFloat / d.toFloat\n println(p1 / (1 - (1 - p1) * (1 - p2)))\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(a, b, c, d) = readLine().split(\" \").map(_.toInt)\n val p1 = a.toFloat / b.toFloat\n val p2 = c.toFloat / d.toFloat\n println(p1 / (1 - p1 * p2))\n }\n}"}], "src_uid": "7b932b2d3ab65a353b18d81cf533a54e"} {"source_code": "import java.util\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.control.Breaks._\n\nobject Main {\n def main(args: Array[String]) {\n val max = 1e7.toInt\n val cnt, sum = Array.ofDim[Int](max + 1)\n val (primes, fact) = getPrimes(max)\n\n val n = readToken().toInt\n for (i <- readLine.split(\" \")) {\n var x = i.toInt\n var prev = -1\n while (x != 1) {\n val t = fact(x)\n if (t != prev) {\n cnt(t) += 1\n prev = t\n }\n x /= t\n }\n }\n\n (2 to max).foreach(i => sum(i) = sum(i - 1) + cnt(i))\n\n val m = readToken().toInt\n (0 until m).foreach(i => {\n val t = readLine.split(\" \").map(_.toInt)\n val l = t(0).min(max + 1)\n val r = t(1).min(max)\n println(sum(r) - sum(l - 1))\n })\n }\n\n\n def getPrimes(n: Int): (Array[Int], Array[Int]) = {\n val primes = ArrayBuffer.empty[Int]\n val maxFact = Array.ofDim[Int](n + 1)\n\n for (i <- 2 to n; if maxFact(i) == 0) {\n (i to n by i).foreach(maxFact(_) = i)\n primes += i\n }\n\n (primes.toArray, maxFact)\n }\n\n var st = new util.StringTokenizer(\"\")\n\n def readToken() = {\n while (!st.hasMoreTokens) st = new java.util.StringTokenizer(readLine)\n st.nextToken\n }\n}\n", "positive_code": [{"source_code": "import java.util\nimport scala.collection.mutable.ArrayBuffer\n\nobject Main {\n def main(args: Array[String]) {\n val max = 1e7.toInt\n val cnt, sum = Array.fill(max + 1)(0)\n val (primes, fact) = getPrimes(max)\n\n val n = readToken().toInt\n for (i <- 0 until n) {\n var x = readToken().toInt\n var prev = -1\n while (x != 1) {\n if (fact(x) != prev) {\n cnt(fact(x)) += 1\n prev = fact(x)\n }\n x /= fact(x)\n }\n }\n\n (2 to max).foreach(i => sum(i) = sum(i - 1) + cnt(i))\n\n val m = readToken().toInt\n for (i <- 0 until m) {\n val t = readLine.split(\" \").map(_.toInt)\n val l = t(0).min(max + 1)\n val r = t(1).min(max)\n println(sum(r) - sum(l - 1))\n }\n }\n\n def getPrimes(n: Int): (Array[Int], Array[Int]) = {\n val primes = ArrayBuffer.empty[Int]\n val maxFact = Array.fill(n + 1)(1)\n\n for (i <- 2 to n; if maxFact(i) == 1) {\n (i to n by i).foreach(maxFact(_) = i)\n primes += i\n }\n\n (primes.toArray, maxFact)\n }\n\n var st = new util.StringTokenizer(\"\")\n\n def readToken() = {\n while (!st.hasMoreTokens) st = new java.util.StringTokenizer(readLine)\n st.nextToken\n }\n}"}], "negative_code": [], "src_uid": "fe42c7f0222497ce3fff51b3676f42d1"} {"source_code": "object B741 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m, w) = readInts(3)\n val wi = readInts(n)\n val bi = readInts(n)\n val G = {\n val _G = Array.fill(n)(cu.ArrayBuffer.empty[Int])\n (1 to m).foreach{ _ =>\n val Array(a, b) = readInts(2).map(_-1)\n _G(a).append(b)\n _G(b).append(a)\n }\n _G.map(_.toArray)\n }\n // All connected groups\n val groups = {\n val _groups = cu.ArrayBuffer.empty[Array[Int]]\n val vis = Array.fill(n)(false)\n\n def dfs(i: Int): cu.ArrayBuffer[Int] = {\n val ret = cu.ArrayBuffer.empty[Int]\n if (!vis(i)) {\n vis(i) = true\n\n ret.append(i)\n for (a <- G(i))\n ret.appendAll(dfs(a))\n }\n ret\n }\n\n for (i <- 0 until n if !vis(i)) {\n val g = dfs(i).toArray\n _groups.append(g)\n }\n _groups\n }\n val gW = groups.map(_.map(wi).sum)\n val gB = groups.map(_.map(bi).sum)\n //knapsack\n val dp = Array.ofDim[Int](groups.length, w+1)\n for(i <- groups.indices; j <- 0 to w)\n dp(i)(j) = -1\n def solve(pos: Int, wLeft: Int): Int = {\n if(pos >= groups.length)\n 0\n else if (dp(pos)(wLeft) != -1)\n dp(pos)(wLeft)\n else {\n var res = 0\n for(a <- groups(pos)) {\n if(wi(a) <= wLeft) {\n res = math.max(res, solve(pos+1, wLeft-wi(a)) + bi(a))\n }\n }\n if(gW(pos) <= wLeft) {\n res = math.max(res, solve(pos+1, wLeft-gW(pos)) + gB(pos))\n }\n res = math.max(res, solve(pos+1, wLeft))\n dp(pos)(wLeft) = res\n res\n }\n }\n println(solve(0, w))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "object B741 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m, w) = readInts(3)\n val wi = readInts(n)\n val bi = readInts(n)\n val G = {\n val _G = Array.fill(n)(cu.ArrayBuffer.empty[Int])\n (1 to m).foreach{ _ =>\n val Array(a, b) = readInts(2).map(_-1)\n _G(a).append(b)\n _G(b).append(a)\n }\n _G.map(_.toArray)\n }\n // All connected groups\n val groups = {\n val _groups = cu.ArrayBuffer.empty[Array[Int]]\n val vis = Array.fill(n)(false)\n\n def dfs(i: Int): cu.ArrayBuffer[Int] = {\n val ret = cu.ArrayBuffer.empty[Int]\n if (!vis(i)) {\n vis(i) = true\n\n ret.append(i)\n for (a <- G(i))\n ret.appendAll(dfs(a))\n }\n ret\n }\n\n for (i <- 0 until n if !vis(i)) {\n val g = dfs(i).toArray\n _groups.append(g)\n }\n _groups.map(_.map(i => (wi(i), bi(i)))).map{ arr =>\n arr ++ Array((arr.map(_._1).sum, arr.map(_._2).sum))\n }.toArray\n }\n //knapsack\n val dp = Array.ofDim[Int](groups.length, w+1)\n for(i <- groups.indices; j <- 0 to w)\n dp(i)(j) = -1\n def solve(pos: Int, wLeft: Int): Int = {\n if(pos >= groups.length)\n 0\n else if (dp(pos)(wLeft) != -1)\n dp(pos)(wLeft)\n else {\n var res = 0\n res = math.max(res, solve(pos+1, wLeft))\n for((w, b) <- groups(pos)) {\n if(w <= wLeft) {\n res = math.max(res, solve(pos+1, wLeft-w) + b)\n }\n }\n dp(pos)(wLeft) = res\n res\n }\n }\n println(solve(0, w))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object B741 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m, w) = readInts(3)\n val wi = readInts(n)\n val bi = readInts(n)\n val G = {\n val _G = Array.fill(n)(cu.ArrayBuffer.empty[Int])\n (1 to m).foreach{ _ =>\n val Array(a, b) = readInts(2).map(_-1)\n _G(a).append(b)\n _G(b).append(a)\n }\n _G.map(_.toArray)\n }\n // All connected groups\n val groups = {\n val _groups = cu.ArrayBuffer.empty[Array[Int]]\n val vis = Array.fill(n)(false)\n\n def dfs(i: Int): cu.ArrayBuffer[Int] = {\n val ret = cu.ArrayBuffer.empty[Int]\n if (!vis(i)) {\n vis(i) = true\n\n ret.append(i)\n for (a <- G(i))\n ret.appendAll(dfs(a))\n }\n ret\n }\n\n for (i <- 0 until n if !vis(i)) {\n val g = dfs(i).toArray\n _groups.append(g)\n }\n _groups\n }\n val gW = groups.map(_.map(wi).sum)\n val gB = groups.map(_.map(bi).sum)\n //knapsack\n val dp = Array.ofDim[Int](groups.length, w+1)\n for(i <- groups.indices; j <- 0 to w)\n dp(i)(j) = -1\n def solve(pos: Int, wLeft: Int): Int = {\n if(pos >= groups.length)\n 0\n else if (dp(pos)(wLeft) != -1)\n dp(pos)(wLeft)\n else {\n var res = 0\n res = math.max(res, solve(pos+1, wLeft))\n for(a <- groups(pos)) {\n if(wi(a) <= wLeft) {\n res = math.max(res, solve(pos+1, wLeft-wi(a)) + bi(a))\n }\n }\n if(gW(pos) <= wLeft) {\n res = math.max(res, solve(pos+1, wLeft-gW(pos)) + gB(pos))\n }\n dp(pos)(wLeft) = res\n res\n }\n }\n println(solve(0, w))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [], "src_uid": "7c96bc1aa4dcabf7560d915823ba22f1"} {"source_code": "import scala.collection.mutable\n\nobject D344 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val input = scala.io.StdIn.readLine\n val stack = mutable.Stack[Char]()\n for(i <- input.indices) {\n if(stack.nonEmpty && stack.top == input(i)) {\n stack.pop()\n } else {\n stack.push(input(i))\n }\n }\n if(stack.isEmpty) {\n println(\"Yes\")\n } else {\n println(\"No\")\n }\n }\n}", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n val stack = mutable.Stack(line.head)\n\n line.tail.foreach { i =>\n if (stack.isEmpty)\n stack.push(i)\n else if (stack.top != i) {\n stack.push(i)\n } else {\n stack.pop()\n }\n }\n\n if (stack.isEmpty)\n println(\"Yes\")\n else\n println(\"No\")\n\n}\n\n"}, {"source_code": "object D extends App {\n \n var prev = ' '\n var cnt = 0\n \n for (c <- Console.readLine)\n if (cnt == 0) {\n prev = c\n cnt = 1\n } else {\n if (c == prev) cnt -= 1 else cnt += 1\n prev = if (prev == '-') '+' else '-'\n }\n\n println(if (cnt == 0) \"Yes\" else \"No\")\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n def readString = Console.readLine\n\n val s = readString\n \n val st = mutable.Stack[Char]()\n \n for (c <- s) {\n if (st.nonEmpty && st.head == c) {\n st.pop\n } else {\n st.push(c)\n }\n }\n\n println(if (st.isEmpty) \"Yes\" else \"No\")\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n if (line.length % 2 == 1 || (0 until line.length / 2).exists(i => line(i) != line(line.length - 1 - i)))\n println(\"No\")\n else\n println(\"Yes\")\n\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n val stack = mutable.Stack(line.head)\n\n line.tail.foreach { i =>\n if (stack.nonEmpty && stack.top != i) {\n val top = stack.pop()\n if (stack.nonEmpty && stack.top == top) {\n while (stack.nonEmpty && stack.top == top) {\n stack.pop()\n }\n } else {\n stack.push(top)\n }\n }\n stack.push(i)\n }\n\n if (stack.nonEmpty) {\n val top = stack.pop()\n if (stack.nonEmpty && stack.top == top) {\n while (stack.nonEmpty && stack.top == top) {\n stack.pop()\n }\n } else {\n stack.push(top)\n }\n }\n\n\n if (stack.isEmpty)\n println(\"Yes\")\n else\n println(\"No\")\n\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n if (line.length == 1 || (0 until line.length / 2).exists(i => line(i) != line(line.length - 1 - i)))\n println(\"No\")\n else\n println(\"Yes\")\n\n}\n"}], "src_uid": "89b4a7b4a6160ce784c588409b6ce935"} {"source_code": "import scala.:+\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Solution extends App {\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n readInt()\n val numbers = readInts()\n val (a, b) = numbers.zipWithIndex.partition { case (value, _) => value == numbers(0)}\n val answer = 1 + (if (a.length == 1) a(0)._2 else b(0)._2)\n println(answer)\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\r\nimport scala.io.StdIn._\r\n\r\nobject A1512 {\r\n def main(args: Array[String]){\r\n val t = readInt()\r\n\r\n for(i <- 1 to t) {\r\n val n = readInt()\r\n var arr = readLine.split(\" \").map(_.toInt)\r\n println(if(arr.count(_ == arr.min) > arr.count(_ == arr.max)) arr.indexOf(arr.max) + 1\r\n else arr.indexOf(arr.min) + 1)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.annotation.tailrec\r\nimport scala.io.StdIn.readLine\r\n\r\nobject CodeForces extends App {\r\n val t = readLine.toInt\r\n for( _ <- (1 to t)){\r\n val n = readLine.toInt\r\n val list = readLine.split(' ').map(x => x.toInt).toList.zipWithIndex\r\n val a = list(0)._1\r\n val b = list(1)._1\r\n val c = list(2)._1\r\n val mode = if (a == b) a else (if (a == c) a else b)\r\n val spy = list.find(x => x._1 != mode)\r\n println(spy.get._2 + 1)\r\n }\r\n\r\n}\r\n"}, {"source_code": "import scala.util.control._\r\nobject Main{\r\n def main(args : Array[String]):Unit = {\r\n var t = scala.io.StdIn.readInt()\r\n val outloop = new Breaks;\r\n val inloop = new Breaks;\r\n outloop.breakable{\r\n for (i<-1 to t){\r\n var n = scala.io.StdIn.readInt()\r\n var arr = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\r\n inloop.breakable{\r\n if ((arr(0)!=arr(1))&&(arr(0)!=arr(2))){\r\n println(1)\r\n }\r\n else if((arr(n-1)!=arr(n-2)) && (arr(n-1)!=arr(n-3))){\r\n println(n)\r\n }\r\n else{\r\n for (j<-1 to (n-2)){\r\n if((arr(j)!=arr(j-1)) && (arr(j)!=arr(j+1))){\r\n println(j+1)\r\n inloop.break\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}"}, {"source_code": "import scala.io.StdIn\r\n\r\nobject Main {\r\n def test(): Unit = {\r\n val n = StdIn.readLine().toInt\r\n val arr = StdIn.readLine().split(\" \").map(_.toInt).zipWithIndex\r\n val a = arr(0)\r\n lazy val b = arr.find { _._1 != a._1 }.toRight()\r\n if (arr.count(_._1 == a._1) > 1)\r\n System.out.println(b.getOrElse((0, 0))._2 + 1)\r\n else\r\n System.out.println(a._2 + 1)\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val t = StdIn.readLine().toInt\r\n (1 to t) foreach {\r\n _ => test()\r\n }\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\r\nimport scala.io.StdIn._\r\n\r\nobject A1512 {\r\n def main(args: Array[String]){\r\n val t = readInt()\r\n\r\n for(i <- 1 to t) {\r\n val n = readInt()\r\n var arr = readLine.split(\" \").map(_.toInt)\r\n println(if(arr.count(_ == arr.min) > arr.count(_ == arr.max)) arr.indexOf(arr.min) + 1\r\n else arr.indexOf(arr.max) - 1)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\r\nimport scala.io.StdIn._\r\n\r\nobject A1512 {\r\n def main(args: Array[String]){\r\n val t = readInt()\r\n\r\n for(i <- 1 to t) {\r\n val n = readInt()\r\n var arr = readLine.split(\" \").map(_.toInt)\r\n println(if(arr.count(_ == arr.min) > arr.count(_ == arr.max)) arr.min\r\n else arr.max)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.annotation.tailrec\r\nimport scala.io.StdIn.readLine\r\n\r\nobject CodeForces extends App {\r\n val t = readLine.toInt\r\n for( _ <- (1 to t)){\r\n val n = readLine.toInt\r\n val list = readLine.split(' ').map(x => x.toInt).toList.zipWithIndex\r\n println(list)\r\n val a = list(0)._1\r\n val b = list(1)._1\r\n val c = list(2)._1\r\n val mode = if (a == b) a else (if (a == c) a else b)\r\n val spy = list.find(x => x._1 != mode)\r\n println(spy.get._2 + 1)\r\n }\r\n\r\n}\r\n"}, {"source_code": "import scala.io.StdIn.readLine\r\n\r\nobject CodeForces extends App {\r\n val t = readLine.toInt\r\n for( _ <- (1 to t)){\r\n val n = readLine.toInt\r\n val list = readLine.split(' ').map(x => x.toInt).toList\r\n val a = list(0)\r\n val b = list(1)\r\n val c = list(2)\r\n val mode = if (a == b) a else (if (a == c) a else b)\r\n val spy = list.find(x => x != mode)\r\n println(spy.get)\r\n }\r\n \r\n}\r\n"}, {"source_code": "import scala.annotation.tailrec\r\nimport scala.io.StdIn.readLine\r\n\r\nobject CodeForces extends App {\r\n val t = readLine.toInt\r\n for( _ <- (1 to t)){\r\n val n = readLine.toInt\r\n val list = readLine.split(' ').map(x => x.toInt).toList\r\n val a = list(0)\r\n val b = list(1)\r\n val c = list(2)\r\n val mode = if (a == b) a else c\r\n val spy = list.find(x => x != mode)\r\n println(spy.get)\r\n }\r\n \r\n}\r\n"}], "src_uid": "224a0b09547ec1441474efbd8e06353b"} {"source_code": "import java.util._\nimport java.io._\nimport java.util\n\nobject D {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val mod = (1e9 + 7).toInt\n val t = nextInt\n val k = nextInt\n val dp = new Array[Int](1e5.toInt + 1)\n dp(0) = 1\n for (i <- 1 until dp.length) {\n if (i == k) {\n dp(i) = 2\n }\n else if (i > k) {\n dp(i) = (dp(i - 1) % mod + dp(i - k) % mod) % mod\n } else {\n dp(i) = 1\n }\n }\n val prefixSum = new Array[Int](1e5.toInt + 1)\n prefixSum(0) = dp(0)\n for (i <- 1 until prefixSum.length) {\n prefixSum(i) = (dp(i) % mod + prefixSum(i - 1) % mod) % mod\n }\n for (i <- 0 until t) {\n val a = nextInt\n val b = nextInt\n out.println((prefixSum(b) - prefixSum(a - 1) + mod) % mod)\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.Scanner\nimport scala.language.implicitConversions\n\nobject Main{\n\n class Lazy[A](x: => A) {\n lazy val value = x\n override def toString(): String = value.toString()\n }\n\n object Lazy {\n def apply[A](x: => A) = new Lazy(x)\n implicit def fromLazy[A](z: Lazy[A]): A = z.value\n implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)\n }\n\n import Lazy._\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val T = sc.nextInt\n val K = sc.nextInt\n val MAXN = 100005\n val MOD: Int = 1000000007\n\n lazy val DP: Array[Lazy[Int]] = Array.tabulate(MAXN)(x => if (x < K) 1 else (DP(x - K) + DP(x - 1)) % MOD)\n lazy val P: Array[Lazy[Int]] = Array.tabulate(MAXN)(x => if (x == 0) DP(0) else (DP(x) + P(x - 1)) % MOD)\n\n val ranges = for (i <- 0.until(T)) yield (sc.nextInt, sc.nextInt)\n ranges.map{case (s, e) =>\n { \n val startValue: Int = if (s == 0) 0 else P(s - 1);\n (P(e) - startValue + MOD) % MOD\n }\n }.foreach(println)\n }\n}"}, {"source_code": "object D474 {\n\n import IO._\n import collection.{mutable => cu}\n val MOD = 1000000007L\n def main(args: Array[String]): Unit = {\n val Array(t, k) = readInts(2)\n val dp = Array(0L) ++ Array.fill(k-1)(1L) ++ Array(2L) ++ Array.fill(100010-k)(0L)\n for(i <- k+1 until 100010) {\n dp(i) = (dp(i-1) + dp(i-k))%MOD\n }\n for(i <- 1 until 100010) {\n dp(i) = (dp(i) + dp(i-1))%MOD\n }\n for(_ <- 1 to t) {\n val Array(a, b) = readInts(2)\n println((dp(b) - dp(a-1) + 2*MOD)%MOD)\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(t, k) = in.next().split(' ').map(_.toInt)\n val ans = (1 to t).map{_ =>\n val data = in.next().split(' ').map(_.toInt)\n (data.head, data.last)\n }\n val maxB = ans.maxBy(_._2)._2\n val cache = Array.ofDim[Long](maxB + 1)\n val sumCache = Array.ofDim[Long](maxB + 1)\n (1 until k).foreach(i => cache(i) = 1)\n cache(k) = 2\n (k + 1 to maxB).foreach{\n i => cache(i) = (cache(i - 1) + cache(i - k)) % 1000000007\n }\n (1 to maxB).foreach { i =>\n sumCache(i) = (sumCache(i - 1) + cache(i)) % 1000000007\n }\n\n val res = ans.map {\n case(0, b) => sumCache(b)\n case(a, b) => (1000000007l + sumCache(b) - sumCache(a - 1)) % 1000000007\n }\n println(res.mkString(\"\\n\"))\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(t, k) = in.next().split(' ').map(_.toInt)\n val ans = (1 to t).map{_ =>\n val data = in.next().split(' ').map(_.toInt)\n (data.head, data.last)\n }\n val maxB = ans.maxBy(_._2)._2\n val cache = Array.ofDim[Long](maxB + 1)\n val sumCache = Array.ofDim[Long](maxB + 1)\n (1 until k).foreach(i => cache(i) = 1)\n cache(k) = 2\n (k + 1 to maxB).foreach{\n i => cache(i) = (cache(i - 1) + (if (i % k == 0) 2 else 1)) % 1000000007\n }\n (1 to maxB).foreach { i =>\n sumCache(i) = (sumCache(i - 1) + cache(i)) % 1000000007\n }\n\n val res = ans.map {\n case(0, b) => sumCache(b)\n case(a, b) => (1000000007l + sumCache(b) - sumCache(a - 1)) % 1000000007\n }\n println(res.mkString(\"\\n\"))\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(t, k) = in.next().split(' ').map(_.toInt)\n val ans = (1 to t).map{_ =>\n val data = in.next().split(' ').map(_.toInt)\n (data.head, data.last)\n }\n val maxB = ans.maxBy(_._2)._2\n val cache = Array.ofDim[Long](maxB + 1)\n val sumCache = Array.ofDim[Long](maxB + 1)\n (1 until k).foreach(i => cache(i) = 1)\n cache(k) = 2\n (k + 1 to maxB).foreach{\n i => cache(i) = cache(i - 1) + (if (i % k == 0) 2 else 1) % 1000000007\n }\n (1 to maxB).foreach { i =>\n sumCache(i) = (sumCache(i - 1) + cache(i)) % 1000000007\n }\n\n val res = ans.map {\n case(0, b) => sumCache(b)\n case(a, b) => (1000000007 + sumCache(b) - sumCache(a - 1)) % 1000000007\n }\n println(res.mkString(\"\\n\"))\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(t, k) = in.next().split(' ').map(_.toInt)\n val ans = (1 to t).map{_ =>\n val data = in.next().split(' ').map(_.toInt)\n (data.head, data.last)\n }\n val maxB = ans.maxBy(_._2)._2\n val cache = Array.ofDim[Long](maxB + 1)\n val sumCache = Array.ofDim[Long](maxB + 1)\n (1 until k).foreach(i => cache(i) = 1)\n cache(k) = 2\n (k + 1 to maxB).foreach{\n i => cache(i) = cache(i - 1) + (if (i % k == 0) 2 else 1) % 1000000007\n }\n (1 to maxB).foreach { i =>\n sumCache(i) = (sumCache(i - 1) + cache(i)) % 1000000007\n }\n\n val res = ans.map {\n case(0, b) => sumCache(b)\n case(a, b) => (1000000007l + sumCache(b) - sumCache(a - 1)) % 1000000007\n }\n println(res.mkString(\"\\n\"))\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(t, k) = in.next().split(' ').map(_.toInt)\n val ans = (1 to t).map{_ =>\n val data = in.next().split(' ').map(_.toInt)\n (data.head, data.last)\n }\n val maxB = ans.maxBy(_._2)._2\n val cache = Array.ofDim[Int](maxB + 1)\n val sumCache = Array.ofDim[Int](maxB + 1)\n (1 until k).foreach(i => cache(i) = 1)\n cache(k) = 2\n (k + 1 to maxB).foreach{\n i => cache(i) = cache(i - 1) + (if (i % k == 0) 2 else 1) % 1000000007\n }\n (1 to maxB).foreach { i =>\n sumCache(i) = (sumCache(i - 1) + cache(i)) % 1000000007\n }\n\n val res = ans.map {\n case(0, b) => sumCache(b)\n case(a, b) => (1000000007 + sumCache(b) - sumCache(a - 1)) % 1000000007\n }\n println(res.mkString(\"\\n\"))\n}\n"}, {"source_code": "import java.util._\nimport java.io._\nimport java.util\n\nobject D {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val mod = (1e9 + 7).toInt\n val t = nextInt\n val k = nextInt\n val dp = new Array[Int](1e5.toInt + 1)\n dp(0) = 1\n for (i <- 1 until dp.length) {\n if (i == k) {\n dp(i) = 2\n }\n else if (i > k) {\n dp(i) = (dp(i - 1) % mod + dp(i - k) % mod) % mod\n } else {\n dp(i) = 1\n }\n }\n val prefixSum = new Array[Int](1e5.toInt + 1)\n prefixSum(0) = dp(0)\n for (i <- 1 until prefixSum.length) {\n prefixSum(i) = (dp(i) % mod + prefixSum(i - 1) % mod) % mod\n }\n for (i <- 0 until t) {\n val a = nextInt\n val b = nextInt\n out.println((Math.abs(prefixSum(b)) - Math.abs(prefixSum(a - 1))) % mod)\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "src_uid": "16c016c0735be1815c7b94c5c50516f1"} {"source_code": "object Main {\nimport java.io._\nimport java.util.Scanner\n\nimport collection.mutable.HashMap\nimport scala.collection.{SortedSet, mutable}\nimport scala.util.Random\n protected val EPS = 1e-11\n\n private def default = (\n new StreamTokenizer(new InputStreamReader(System.in)),\n new Scanner(System.in),\n new PrintWriter(System.out)\n )\n\n val (in, ins, out) = {\n try {\n if (sys.props.contains(\"xDx\")) {\n (\n new StreamTokenizer(new FileReader(\"input.txt\")),\n new Scanner(new FileReader(\"input.txt\")),\n new PrintWriter(new FileWriter(\"output.txt\"))\n )\n } else {\n default\n }\n } catch {\n case _: Throwable => default\n }\n }\n\n private def nextInt = {\n in.nextToken\n in.nval.toInt\n }\n\n private def nextLong = {\n in.nextToken\n in.nval.toLong\n }\n\n\n private def nextDouble = {\n in.nextToken\n in.nval\n }\n\n\n private def nextString = {\n in.nextToken\n in.sval\n }\n\n private def nextChar = {\n in.nextToken\n in.ttype.toChar\n }\n\n def main(args: Array[String]): Unit = {\n try {\n new Run().run()\n } catch {\n case e: Throwable =>\n throw new RuntimeException(e)\n } finally out.close()\n }\n\n class Run {\n import collection.breakOut\n def run(): Unit = {\n val n = nextInt\n val field = Array.ofDim[Int](2, n)\n val sum = Array.ofDim[Long](2, n)\n val sum123 = Array.ofDim[Long](2, n)\n val sum321 = Array.ofDim[Long](2, n)\n for(i <- 0 until 2) {\n for(j <- 0 until n) {\n val a = nextInt\n field(i)(j) = a\n sum(i)(j) = a\n if(j > 0) sum(i)(j) += sum(i)(j - 1)\n }\n }\n \n for(i <- 0 until 2) {\n for(j <- n - 1 to 0 by -1) {\n sum321(i)(j) = (n - 1 - j).toLong * field(i)(j)\n sum123(i)(j) = sum(i)(n - 1) - sum(i)(j)\n if(j < n - 1) {\n sum321(i)(j) += sum321(i)(j + 1)\n sum123(i)(j) += sum123(i)(j + 1)\n }\n }\n }\n \n var res = 0L\n var line = 0\n var time = 0L\n var acc = 0L\n def getSum(line: Int, i: Int) = {\n if(i < 0) 0 else sum(line)(i)\n }\n for(i <- 0 until n) {\n val ol = other(line)\n val tmp = sum123(line)(i) + time * (sum(line)(n - 1) - getSum(line, i - 1)) +\n sum321(ol)(i) + (time + n - i)*(sum(ol)(n - 1) - getSum(ol, i - 1))\n res = math.max(res, tmp + acc)\n acc += field(line)(i)*time + field(ol)(i)*(time + 1)\n \n time += 2\n line = ol\n }\n \n println(math.max(res, acc))\n }\n \n\n def other(line: Int) = (line + 1) % 2\n\n }\n\n}\n\n\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = Array(na(N), na(N))\n var ans = 0L\n\n val S = Array.ofDim[Long](N + 1)\n REP_r(N) { i =>\n S(i) = S(i + 1) + A(0)(i) + A(1)(i)\n }\n val tour = Array.ofDim[Long](2, N + 1) // 0-indexed, ここからぐぐっと回った時に、係数0スタートで累積した値\n REP(2) { x =>\n REP_r(N) { i =>\n val end = A(x ^ 1)(i).toLong * ((N - i) * 2 - 1)\n tour(x)(i) = tour(x)(i + 1) + S(i + 1) + end\n }\n }\n\n var past = 0L\n REP(N) { i =>\n val x = i % 2\n val v0 = i * 2\n val v1 = v0 + 1\n ans = max(ans, past + tour(x)(i) + S(i) * v0)\n past += A(x)(i).toLong * v0 + A(x ^ 1)(i).toLong * v1\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val X = Array.ofDim[Long](2, N)\n rep(N) (i => X(0)(i) = ni())\n rep(N) (i => X(1)(i) = ni())\n\n val cum = Array.ofDim[Long](N + 1)\n rep(N) { i =>\n cum(i + 1) = cum(i) + X(0)(i) + X(1)(i)\n }\n\n def S(i: Int): Long = cum(N) - cum(i)\n\n def initOutside(i: Int, off: Int) = {\n val x = i % 2\n var res = 0L\n rep(N - i) { j =>\n res += X(x)(j + i) * (j + off)\n }\n rep(N - i) { j =>\n res += X(x ^ 1)(N - 1 - j) * (N - i + j + off)\n }\n res\n }\n\n val prevOutside = Array.ofDim[Long](2)\n prevOutside(0) = initOutside(0, 0)\n prevOutside(1) = initOutside(1, 2)\n\n // i: [0, N-1] 横の位置\n def collectOutside(i: Int): Long = {\n val x = i % 2\n if (i < 2) {\n prevOutside(x)\n } else {\n val k = (N - i + 2) * 2 - 1\n val off = (i - 2) * 2\n val res = prevOutside(x) +\n 2 * S(i) -\n off * X(x)(i - 2) -\n (off + 1) * X(x)(i - 1) -\n (off + k) * X(x ^ 1)(i - 2) -\n (off + k - 1) * X(x ^ 1)(i - 1)\n prevOutside(x) = res\n res\n }\n }\n\n def step(i: Int) = {\n val x = i % 2\n i * 2 * X(x)(i) + (i * 2 + 1) * X(x ^ 1)(i)\n }\n\n var ans = 0L\n var cur = 0L\n rep(N - 1) { i =>\n ans = max(ans, collectOutside(i) + cur)\n cur += step(i)\n }\n ans = max(ans, cur + step(N - 1))\n\n out.println(ans)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val X = Array.ofDim[Int](2, N)\n rep(N) (i => X(0)(i) = ni())\n rep(N) (i => X(1)(i) = ni())\n\n val cum = Array.ofDim[Long](N + 1)\n rep(N - 1) { i =>\n cum(i + 1) = cum(i) + X(0)(i + 1) + X(1)(i + 1)\n }\n\n def S(i: Int): Long = cum(N - i)\n\n def initOutside(i: Int, off: Int) = {\n val x = i % 2\n var res = 0L\n rep(N - i) { j =>\n res += X(x)(j + i) * (j + off)\n }\n rep(N - i) { j =>\n res += X(x ^ 1)(N - 1 - j) * (N - i + j + off)\n }\n res\n }\n\n val prevOutside = Array.ofDim[Long](2)\n prevOutside(0) = initOutside(0, 0)\n prevOutside(1) = initOutside(1, 2)\n\n // i: [0, N-1] 横の位置\n def collectOutside(i: Int): Long = {\n val x = i % 2\n if (i < 2) {\n prevOutside(x)\n } else {\n val k = (N - i + 2) * 2 - 1\n val res = prevOutside(x) +\n 2 * S(i) +\n 2 * X(x)(i - 1) -\n (k - 2) * X(x ^ 1)(i - 2) -\n (k - 4) * X(x ^ 1)(i - 1)\n prevOutside(x) = res\n res\n }\n }\n\n def step(i: Int) = {\n val x = i % 2\n i * 2 * X(x)(i) + (i * 2 + 1) * X(x ^ 1)(i)\n }\n\n var ans = 0L\n var cur = 0L\n rep(N - 1) { i =>\n ans = max(ans, collectOutside(i) + cur)\n cur += step(i)\n }\n ans = max(ans, cur + step(N - 1))\n\n out.println(ans)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = Array(na(N), na(N))\n var ans = 0L\n\n val S = Array.ofDim[Long](N + 1)\n REP_r(N) { i =>\n S(i) = S(i + 1) + A(0)(i) + A(1)(i)\n }\n val tour = Array.ofDim[Long](2, N + 1) // 0-indexed, ここからぐぐっと回った時に、係数0スタートで累積した値\n REP(2) { x =>\n REP_r(N) { i =>\n val end = A(x ^ 1)(i) * ((N - i) * 2 - 1)\n tour(x)(i) = tour(x)(i + 1) + S(i + 1) + end\n }\n }\n\n var past = 0L\n REP(N) { i =>\n val x = i % 2\n val v0 = i * 2\n val v1 = v0 + 1\n ans = max(ans, past + tour(x)(i) + S(i) * v0)\n past += A(x)(i).toLong * v0 + A(x ^ 1)(i).toLong * v1\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = Array(na(N), na(N))\n var ans = 0L\n\n val S = Array.ofDim[Long](N + 1)\n REP_r(N) { i =>\n S(i) = S(i + 1) + A(0)(i) + A(1)(i)\n }\n val tour = Array.ofDim[Long](2, N + 1) // 0-indexed, ここからぐぐっと回った時に、係数0スタートで累積した値\n REP(2) { x =>\n REP_r(N) { i =>\n val end = A(x ^ 1)(i) * ((N - i) * 2 - 1)\n tour(x)(i) = tour(x)(i + 1) + S(i + 1) + end\n }\n }\n\n var past = 0L\n REP(N) { i =>\n val x = i % 2\n val v0 = i * 2\n val v1 = v0 + 1\n ans = max(ans, past + tour(x)(i) + S(i) * v0)\n past += A(x)(i) * v0 + A(x ^ 1)(i) * v1\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val X = Array.ofDim[Int](2, N)\n rep(N) (i => X(0)(i) = ni())\n rep(N) (i => X(1)(i) = ni())\n\n val cum = Array.ofDim[Long](N + 1)\n rep(N) { i =>\n cum(i + 1) = cum(i) + X(0)(i) + X(1)(i)\n }\n\n def S(i: Int): Long = cum(N) - cum(i)\n\n def initOutside(i: Int, off: Int) = {\n val x = i % 2\n var res = 0L\n rep(N - i) { j =>\n res += X(x)(j + i) * (j + off)\n }\n rep(N - i) { j =>\n res += X(x ^ 1)(N - 1 - j) * (N - i + j + off)\n }\n res\n }\n\n val prevOutside = Array.ofDim[Long](2)\n prevOutside(0) = initOutside(0, 0)\n prevOutside(1) = initOutside(1, 2)\n\n // i: [0, N-1] 横の位置\n def collectOutside(i: Int): Long = {\n val x = i % 2\n if (i < 2) {\n prevOutside(x)\n } else {\n val k = (N - i + 2) * 2 - 1\n val off = (i - 2) * 2\n val res = prevOutside(x) +\n 2 * S(i) -\n off * X(x)(i - 2) - \n (off + 1) * X(x)(i - 1) -\n (off + k) * X(x ^ 1)(i - 2) -\n (off + k - 1) * X(x ^ 1)(i - 1)\n prevOutside(x) = res\n res\n }\n }\n\n def step(i: Int) = {\n val x = i % 2\n i * 2 * X(x)(i) + (i * 2 + 1) * X(x ^ 1)(i)\n }\n\n var ans = 0L\n var cur = 0L\n rep(N - 1) { i =>\n ans = max(ans, collectOutside(i) + cur)\n cur += step(i)\n }\n ans = max(ans, cur + step(N - 1))\n\n out.println(ans)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "object Main {\nimport java.io._\nimport java.util.Scanner\n\nimport collection.mutable.HashMap\nimport scala.collection.{SortedSet, mutable}\nimport scala.util.Random\n protected val EPS = 1e-11\n\n private def default = (\n new StreamTokenizer(new InputStreamReader(System.in)),\n new Scanner(System.in),\n new PrintWriter(System.out)\n )\n\n val (in, ins, out) = {\n try {\n if (sys.props.contains(\"xDx\")) {\n (\n new StreamTokenizer(new FileReader(\"input.txt\")),\n new Scanner(new FileReader(\"input.txt\")),\n new PrintWriter(new FileWriter(\"output.txt\"))\n )\n } else {\n default\n }\n } catch {\n case _: Throwable => default\n }\n }\n\n private def nextInt = {\n in.nextToken\n in.nval.toInt\n }\n\n private def nextLong = {\n in.nextToken\n in.nval.toLong\n }\n\n\n private def nextDouble = {\n in.nextToken\n in.nval\n }\n\n\n private def nextString = {\n in.nextToken\n in.sval\n }\n\n private def nextChar = {\n in.nextToken\n in.ttype.toChar\n }\n\n def main(args: Array[String]): Unit = {\n try {\n new Run().run()\n } catch {\n case e: Throwable =>\n throw new RuntimeException(e)\n } finally out.close()\n }\n\n class Run {\n import collection.breakOut\n def run(): Unit = {\n val n = nextInt\n val field = Array.ofDim[Int](2, n)\n val sum = Array.ofDim[Long](2, n)\n val sum123 = Array.ofDim[Long](2, n)\n val sum321 = Array.ofDim[Long](2, n)\n for(i <- 0 until 2) {\n for(j <- 0 until n) {\n val a = nextInt\n field(i)(j) = a\n sum(i)(j) = a\n if(j > 0) sum(i)(j) += sum(i)(j - 1)\n }\n }\n \n for(i <- 0 until 2) {\n for(j <- n - 1 to 0 by -1) {\n sum321(i)(j) = (n - 1 - j) * field(i)(j)\n sum123(i)(j) = sum(i)(n - 1) - sum(i)(j)\n if(j < n - 1) {\n sum321(i)(j) += sum321(i)(j + 1)\n sum123(i)(j) += sum123(i)(j + 1)\n }\n }\n }\n \n var res = 0L\n var line = 0\n var time = 0L\n var acc = 0L\n def getSum(line: Int, i: Int) = {\n if(i < 0) 0 else sum(line)(i)\n }\n for(i <- 0 until n) {\n val ol = other(line)\n val tmp = sum123(line)(i) + time * (sum(line)(n - 1) - getSum(line, i - 1)) +\n sum321(ol)(i) + (time + n - i)*(sum(ol)(n - 1) - getSum(ol, i - 1))\n res = math.max(res, tmp + acc)\n acc += field(line)(i)*time + field(ol)(i)*(time + 1)\n \n time += 2\n line = ol\n }\n \n println(math.max(res, acc))\n }\n \n\n def other(line: Int) = (line + 1) % 2\n\n }\n\n}\n\n\n"}, {"source_code": "object Main {\nimport java.io._\nimport java.util.Scanner\n\nimport collection.mutable.HashMap\nimport scala.collection.{SortedSet, mutable}\nimport scala.util.Random\n protected val EPS = 1e-11\n\n private def default = (\n new StreamTokenizer(new InputStreamReader(System.in)),\n new Scanner(System.in),\n new PrintWriter(System.out)\n )\n\n val (in, ins, out) = {\n try {\n if (sys.props.contains(\"xDx\")) {\n (\n new StreamTokenizer(new FileReader(\"input.txt\")),\n new Scanner(new FileReader(\"input.txt\")),\n new PrintWriter(new FileWriter(\"output.txt\"))\n )\n } else {\n default\n }\n } catch {\n case _: Throwable => default\n }\n }\n\n private def nextInt = {\n in.nextToken\n in.nval.toInt\n }\n\n private def nextLong = {\n in.nextToken\n in.nval.toLong\n }\n\n\n private def nextDouble = {\n in.nextToken\n in.nval\n }\n\n\n private def nextString = {\n in.nextToken\n in.sval\n }\n\n private def nextChar = {\n in.nextToken\n in.ttype.toChar\n }\n\n def main(args: Array[String]): Unit = {\n try {\n new Run().run()\n } catch {\n case e: Throwable =>\n throw new RuntimeException(e)\n } finally out.close()\n }\n\n class Run {\n import collection.breakOut\n def run(): Unit = {\n val n = nextInt\n val field = Array.ofDim[Int](2, n)\n val sum = Array.ofDim[Long](2, n)\n val sum123 = Array.ofDim[Long](2, n)\n val sum321 = Array.ofDim[Long](2, n)\n for(i <- 0 until 2) {\n for(j <- 0 until n) {\n val a = nextInt\n field(i)(j) = a\n sum(i)(j) = a\n if(j > 0) sum(i)(j) += sum(i)(j - 1)\n }\n }\n \n for(i <- 0 until 2) {\n for(j <- n - 1 to 0 by -1) {\n sum321(i)(j) = (n - 1 - j) * field(i)(j)\n sum123(i)(j) = sum(i)(n - 1) - sum(i)(j)\n if(j < n - 1) {\n sum321(i)(j) += sum321(i)(j + 1)\n sum123(i)(j) += sum123(i)(j + 1)\n }\n }\n }\n \n var res = 0L\n var line = 0\n var time = 0\n var acc = 0L\n def getSum(line: Int, i: Int) = {\n if(i < 0) 0 else sum(line)(i)\n }\n for(i <- 0 until n) {\n val ol = other(line)\n val tmp = sum123(line)(i) + time * (sum(line)(n - 1) - getSum(line, i - 1)) +\n sum321(ol)(i) + (time + n - i)*(sum(ol)(n - 1) - getSum(ol, i - 1))\n res = math.max(res, tmp + acc)\n acc += field(line)(i)*time + field(ol)(i)*(time + 1)\n \n time += 2\n line = ol\n }\n \n println(math.max(res, acc))\n }\n \n\n def other(line: Int) = (line + 1) % 2\n\n }\n\n}\n\n\n"}, {"source_code": "object Main {\nimport java.io._\nimport java.util.Scanner\n\nimport collection.mutable.HashMap\nimport scala.collection.{SortedSet, mutable}\nimport scala.util.Random\n protected val EPS = 1e-11\n\n private def default = (\n new StreamTokenizer(new InputStreamReader(System.in)),\n new Scanner(System.in),\n new PrintWriter(System.out)\n )\n\n val (in, ins, out) = {\n try {\n if (sys.props.contains(\"xDx\")) {\n (\n new StreamTokenizer(new FileReader(\"input.txt\")),\n new Scanner(new FileReader(\"input.txt\")),\n new PrintWriter(new FileWriter(\"output.txt\"))\n )\n } else {\n default\n }\n } catch {\n case _: Throwable => default\n }\n }\n\n private def nextInt = {\n in.nextToken\n in.nval.toInt\n }\n\n private def nextLong = {\n in.nextToken\n in.nval.toLong\n }\n\n\n private def nextDouble = {\n in.nextToken\n in.nval\n }\n\n\n private def nextString = {\n in.nextToken\n in.sval\n }\n\n private def nextChar = {\n in.nextToken\n in.ttype.toChar\n }\n\n def main(args: Array[String]): Unit = {\n try {\n new Run().run()\n } catch {\n case e: Throwable =>\n throw new RuntimeException(e)\n } finally out.close()\n }\n\n class Run {\n import collection.breakOut\n def run(): Unit = {\n val n = nextInt\n val field = Array.ofDim[Int](2, n)\n val sum = Array.ofDim[Long](2, n)\n val sum123 = Array.ofDim[Long](2, n)\n val sum321 = Array.ofDim[Long](2, n)\n for(i <- 0 until 2) {\n for(j <- 0 until n) {\n val a = nextInt\n field(i)(j) = a\n sum(i)(j) = a\n if(j > 0) sum(i)(j) += sum(i)(j - 1)\n }\n }\n \n for(i <- 0 until 2) {\n for(j <- n - 1 to 0 by -1) {\n sum321(i)(j) = (n - 1 - j) * field(i)(j)\n sum123(i)(j) = sum(i)(n - 1) - sum(i)(j)\n if(j < n - 1) {\n sum321(i)(j) += sum321(i)(j + 1)\n sum123(i)(j) += sum123(i)(j + 1)\n }\n }\n }\n \n var res = 0L\n var line = 0\n var time = 0L\n var acc = 0L\n def getSum(line: Int, i: Int) = {\n if(i < 0) 0 else sum(line)(i)\n }\n for(i <- 0 until n) {\n val ol = other(line)\n val tmp = sum123(line)(i) + time * (sum(line)(n - 1) - getSum(line, i - 1)) +\n sum321(ol)(i) + (time + n - i)*(sum(ol)(n - 1) - getSum(ol, i - 1))\n res = math.max(res, tmp + acc)\n acc += field(line)(i)*time + field(ol)(i)*(time + 1)\n \n time += 2\n line = ol\n }\n \n println(math.max(res, acc))\n }\n \n\n def other(line: Int) = (line + 1) % 2\n }\n}\n\n\n"}, {"source_code": "object Main {\nimport java.io._\nimport java.util.Scanner\n\nimport collection.mutable.HashMap\nimport scala.collection.{SortedSet, mutable}\nimport scala.util.Random\n protected val EPS = 1e-11\n\n private def default = (\n new StreamTokenizer(new InputStreamReader(System.in)),\n new Scanner(System.in),\n new PrintWriter(System.out)\n )\n\n val (in, ins, out) = {\n try {\n if (sys.props.contains(\"xDx\")) {\n (\n new StreamTokenizer(new FileReader(\"input.txt\")),\n new Scanner(new FileReader(\"input.txt\")),\n new PrintWriter(new FileWriter(\"output.txt\"))\n )\n } else {\n default\n }\n } catch {\n case _: Throwable => default\n }\n }\n\n private def nextInt = {\n in.nextToken\n in.nval.toInt\n }\n\n private def nextLong = {\n in.nextToken\n in.nval.toLong\n }\n\n\n private def nextDouble = {\n in.nextToken\n in.nval\n }\n\n\n private def nextString = {\n in.nextToken\n in.sval\n }\n\n private def nextChar = {\n in.nextToken\n in.ttype.toChar\n }\n\n def main(args: Array[String]): Unit = {\n try {\n new Run().run()\n } catch {\n case e: Throwable =>\n throw new RuntimeException(e)\n } finally out.close()\n }\n\n class Run {\n import collection.breakOut\n def run(): Unit = {\n val n = nextInt\n val field = Array.ofDim[Int](2, n)\n val sum = Array.ofDim[Long](2, n)\n val sum123 = Array.ofDim[Long](2, n)\n val sum321 = Array.ofDim[Long](2, n)\n for(i <- 0 until 2) {\n for(j <- 0 until n) {\n val a = nextInt\n field(i)(j) = a\n sum(i)(j) = a\n if(j > 0) sum(i)(j) += sum(i)(j - 1)\n }\n }\n \n for(i <- 0 until 2) {\n for(j <- n - 1 to 0 by -1) {\n sum321(i)(j) = (n - 1 - j) * field(i)(j)\n sum123(i)(j) = sum(i)(n - 1) - sum(i)(j)\n if(j < n - 1) {\n sum321(i)(j) += sum321(i)(j + 1)\n sum123(i)(j) += sum123(i)(j + 1)\n }\n }\n }\n \n var res = 0L\n var line = 0\n var time = 0\n var acc = 0L\n def getSum(line: Int, i: Int) = {\n if(i < 0) 0 else sum(line)(i)\n }\n for(i <- 0 until n) {\n val ol = other(line)\n val tmp = sum123(line)(i) + time * (sum(line)(n - 1) - getSum(line, i - 1)) +\n sum321(ol)(i) + (time + n - i)*(sum(ol)(n - 1) - getSum(ol, i - 1))\n res = math.max(res, tmp)\n acc += field(line)(i)*time + field(ol)(i)*(time + 1)\n \n time += 2\n line = ol\n }\n \n println(math.max(res, acc))\n }\n \n\n def other(line: Int) = (line + 1) % 2\n\n }\n\n}\n\n\n"}], "src_uid": "948429d3788b212e7763774f8cab097b"} {"source_code": "import scala.io.StdIn._\n \nobject A {\n\n\tdef main(args: Array[String]) {\n\t\tval t = readInt()\n\t\t1 to t foreach { _ =>\n\t\t\tval n = readInt()\n\t\t\tfor (i <- 1 to n) println(i)\n\t\t}\n\t}\n}", "positive_code": [{"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n out.println((1 to n).mkString(\" \"))\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "1b3ac752bc9c0b5e20a76f028d4b3c15"} {"source_code": "import java.util\n\nimport scala.collection.mutable\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val _xs = readInts(n + m)\n val isTaxi = readInts(n + m).map(_ == 1)\n\n val ts = Array.ofDim[Int](m)\n val xs = Array.ofDim[Int](n)\n\n var ti, xi = 0\n for {\n i <- _xs.indices\n } {\n if (isTaxi(i)) {\n ts(ti) = _xs(i)\n ti += 1\n } else {\n xs(xi) = _xs(i)\n xi += 1\n }\n }\n\n val as = Array.fill(m){ 0 }\n\n val tree = new util.TreeMap[Integer, Integer]()\n\n for (i <- ts.indices) tree.put(ts(i), i)\n\n for (x <- xs) {\n val left = tree.floorKey(x)\n val right = tree.ceilingKey(x)\n if (left == null) {\n as(tree.get(right)) += 1\n } else if (right == null) {\n as(tree.get(left)) += 1\n } else if (x - left <= right - x) {\n as(tree.get(left)) += 1\n } else {\n as(tree.get(right)) += 1\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(as.mkString(\" \"))\n\n Console.flush\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Task2 {\n\n def main(args: Array[String]): Unit = {\n val scanner = new Scanner(System.in)\n val numberOfRiders = scanner.nextInt()\n val numberOfTaxiDrivers = scanner.nextInt()\n // Coordinates are always increasing and distinct\n val indexToCoordinates = new Array[Int](numberOfRiders + numberOfTaxiDrivers)\n indexToCoordinates.indices\n .foreach(i =>\n indexToCoordinates.update(i, scanner.nextInt())\n )\n val indexToIsTaxiDriver = new Array[Boolean](numberOfRiders + numberOfTaxiDrivers)\n indexToIsTaxiDriver.indices\n .foreach { i =>\n indexToIsTaxiDriver.update(i, scanner.nextInt() == 1)\n }\n val residentIndexToNearestTaxiDriverIndex = new Array[Int](numberOfRiders + numberOfTaxiDrivers)\n var currentTaxiDriverIndex = -1\n indexToCoordinates.indices\n .foreach { index =>\n if (indexToIsTaxiDriver(index)) {\n currentTaxiDriverIndex = index\n }\n residentIndexToNearestTaxiDriverIndex.update(index, currentTaxiDriverIndex)\n }\n // Now currentTaxiDriverIndex points to an existing taxi driver\n (indexToCoordinates.length - 1 to 0 by -1)\n .foreach { index =>\n if (indexToIsTaxiDriver(index)) {\n currentTaxiDriverIndex = index\n }\n val previousTaxiDriverDistance =\n if (residentIndexToNearestTaxiDriverIndex(index) == -1) {\n 1000000001\n } else {\n Math.abs(indexToCoordinates(residentIndexToNearestTaxiDriverIndex(index)) - indexToCoordinates(index))\n }\n val currentTaxiDriverDistance =\n Math.abs(indexToCoordinates(currentTaxiDriverIndex) - indexToCoordinates(index))\n val nearestTaxiDriverIndex =\n if (previousTaxiDriverDistance <= currentTaxiDriverDistance) {\n residentIndexToNearestTaxiDriverIndex(index)\n } else {\n currentTaxiDriverIndex\n }\n residentIndexToNearestTaxiDriverIndex.update(index, nearestTaxiDriverIndex)\n }\n val taxiDriverIndexToNumberOfResidentWhoWouldCall = new Array[Int](numberOfRiders + numberOfTaxiDrivers)\n residentIndexToNearestTaxiDriverIndex.indices\n .foreach { index =>\n if (!indexToIsTaxiDriver(index)) {\n val driverIndex = residentIndexToNearestTaxiDriverIndex(index)\n taxiDriverIndexToNumberOfResidentWhoWouldCall.update(\n driverIndex,\n taxiDriverIndexToNumberOfResidentWhoWouldCall(driverIndex) + 1\n )\n }\n }\n val _taxiDriverIndexToNumberOfResidentWhoWouldCall = new Array[Int](numberOfTaxiDrivers)\n currentTaxiDriverIndex = 0\n taxiDriverIndexToNumberOfResidentWhoWouldCall.indices\n .foreach { index =>\n if (indexToIsTaxiDriver(index)) {\n _taxiDriverIndexToNumberOfResidentWhoWouldCall.update(currentTaxiDriverIndex, taxiDriverIndexToNumberOfResidentWhoWouldCall(index))\n currentTaxiDriverIndex += 1\n }\n }\n println(_taxiDriverIndexToNumberOfResidentWhoWouldCall.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M = ni()\n val loc = na(N + M)\n var ri, di = 0\n val R = Array.ofDim[Int](N)\n val D = Array.ofDim[Int](M)\n rep(N + M) { i =>\n if (ni() == 1) {\n D(di) = loc(i)\n di += 1\n } else {\n R(ri) = loc(i)\n ri += 1\n }\n }\n\n val ans = Array.ofDim[Int](M)\n rep(M) { i =>\n def d1 = D(i) - D(i - 1)\n def d2 = D(i + 1) - D(i)\n def l = D(i) - (d1 - 1) / 2\n def r = D(i) + d2 / 2 // inclusive\n val lnum = if (i == 0) 0 else lowerBound(R, l)\n val rnum = if (i == M - 1) R.length else lowerBound(R, r + 1)\n val num = rnum - lnum\n ans(i) = num\n }\n\n out.println(ans.mkString(\" \"))\n }\n\n // あえてコピペ\n // 要はcountLt\n def lowerBound(a: Array[Int], x: Int): Int = {\n def step(l: Int, h: Int): Int = {\n if (h - l == 1) h\n else {\n val mid = (l + h) / 2\n if (a(mid) >= x) step(l, mid)\n else step(mid, h)\n }\n }\n\n step(-1, a.length)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\n\nobject A extends App {\n\n\n def solve(in: InputReader): Unit = {\n val n, m = in.nextInt\n val arr = Array.fill(n + m)(in.nextInt)\n val b = Array.fill(n + m)(in.nextInt)\n val ans = Array.fill(m)(0)\n var i = 0\n var k = 0\n while (b(i) != 1) {\n i += 1\n ans(k) += 1\n }\n while (i < n + m) {\n var j = i + 1\n while (j < (n + m) && b(j) != 1) j += 1\n val distL = arr(i)\n val distR = if (j == (n + m)) 1e+15 else arr(j)\n (i + 1 until j).foreach { p =>\n if (arr(p) - distL <= distR - arr(p))\n ans(k) += 1\n else\n ans(k + 1) += 1\n }\n i = j\n k += 1\n }\n\n println(ans.mkString(\" \"))\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toDouble\n }\n\n def nextLong: Long = {\n next.toLong\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}, {"source_code": "object _1075B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val n, m = io.read[Int]\n val pos = io.read[Vector, Int](n + m)\n val isDriver = io.read[Vector, Boolean](n + m)\n\n val left: IndexedSeq[Int] = pos.indices.scanLeft(Int.MaxValue) {\n case (nearestDriver, i) => if (isDriver(i)) pos(i) else nearestDriver\n }.tail\n\n val right: IndexedSeq[Int] = pos.indices.scanRight(Int.MaxValue) {\n case (i, nearestDriver) => if (isDriver(i)) pos(i) else nearestDriver\n }.init\n\n val ans: mutable.Map[Int, Int] = pos.indices\n .collect({case i if isDriver(i) => pos(i) -> 0})(collection.breakOut)\n\n for {\n i <- pos.indices if !isDriver(i)\n taxi = if ((left(i) - pos(i)).abs <= (right(i) - pos(i)).abs) left(i) else right(i)\n } ans(taxi) += 1\n\n io.writeAll(ans.toSeq.sorted.map(_._2))\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "object _1075B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val n, m = io.read[Int]\n val pos = io.read[Vector, Int](n + m)\n val isDriver = io.read[Vector, Boolean](n + m)\n val inf = 1e9.toInt\n\n val left: IndexedSeq[Int] = pos.indices.scanLeft(inf) {\n case (nearestDriver, i) => if (isDriver(i)) pos(i) else nearestDriver\n }.tail\n\n val right: IndexedSeq[Int] = pos.indices.scanRight(inf) {\n case (i, nearestDriver) => if (isDriver(i)) pos(i) else nearestDriver\n }.init\n\n val ans = mutable.Map.empty[Int, Int].withDefaultValue(0)\n\n pos.indices foreach {i =>\n if(isDriver(i)) {\n ans(pos(i)) = ans(pos(i)) max 0\n } else {\n val taxi = if ((left(i) - pos(i)).abs <= (right(i) - pos(i)).abs) left(i) else right(i)\n ans(taxi) += 1\n }\n }\n\n io.writeAll(ans.toSeq.sorted.map(_._2))\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "56ea328f84b2930656ff5eb9b8fda8e0"} {"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val cs = Array.fill(n){ readLine.toCharArray }\n\n val ks = Array.fill(n, n)(0)\n ks(0)(0) = k\n\n for (step <- 0 until 2 * n - 1) {\n var i = if (step < n) 0 else step - n + 1\n var j = if (step < n) step else n - 1\n while (j >= 0 && i < n) {\n if (ks(i)(j) > 0 && cs(i)(j) != 'a') {\n cs(i)(j) = 'a'\n ks(i)(j) -= 1\n }\n if (j < n - 1) {\n ks(i)(j + 1) = Math.max(ks(i)(j + 1), ks(i)(j))\n }\n if (i < n - 1) {\n ks(i + 1)(j) = Math.max(ks(i + 1)(j), ks(i)(j))\n }\n i += 1\n j -= 1\n }\n }\n\n val best = Array.fill(2 * n - 1){ 'z' }\n val canReach = Array.fill(n, n){ false }\n\n canReach(0)(0) = true\n\n for (step <- 0 until 2 * n - 1) {\n\n var i = if (step < n) 0 else step - n + 1\n var j = if (step < n) step else n - 1\n while (j >= 0 && i < n) {\n val c = cs(i)(j)\n if (canReach(i)(j) && c <= best(step)) best(step) = c\n i += 1\n j -= 1\n }\n\n i = if (step < n) 0 else step - n + 1\n j = if (step < n) step else n - 1\n while (j >= 0 && i < n) {\n val c = cs(i)(j)\n if (canReach(i)(j) && c <= best(step)) {\n if (j < n - 1) canReach(i)(j + 1) = true\n if (i < n - 1) canReach(i + 1)(j) = true\n }\n i += 1\n j -= 1\n }\n }\n\n println(best.mkString)\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val grid = Array.ofDim[Array[Char]](N)\n rep(N) { i =>\n grid(i) = ns(N)\n }\n\n case class Coord(h: Int, w: Int)\n val INF = Int.MaxValue / 2\n\n def dijk_a(sh: Int, sw: Int) = {\n val d = Array.fill[Int](N, N)(INF)\n case class Visit(h: Int, w: Int, cost: Int)\n val queue = new java.util.ArrayDeque[Visit]()\n d(sh)(sw) = 0\n queue.add(Visit(sh, sw, 0))\n\n while(!queue.isEmpty) {\n val v = queue.poll()\n if (d(v.h)(v.w) == v.cost) {\n rep(2) { x =>\n val nh = v.h + (x ^ 1)\n val nw = v.w + x\n val c = if (grid(v.h)(v.w) == 'a') 0 else 1\n val next = v.cost + c\n if (nh < N && nw < N && K - next >= 0) {\n if (d(nh)(nw) > next) {\n d(nh)(nw) = next\n if (c == 0) {\n queue.addFirst(Visit(nh, nw, next))\n } else {\n queue.addLast(Visit(nh, nw, next))\n }\n }\n }\n }\n }\n }\n\n d\n }\n\n val d = dijk_a(0, 0)\n\n /**\n * 一番アルファベット順が小さいものだけを残す\n */\n class MinCharCoord {\n val coord = mutable.Set[Coord]()\n var char = 'z'\n\n def +=(a: Coord): Unit = {\n val c = grid(a.h)(a.w)\n if (c == char) {\n coord += a\n } else if (c < char) {\n char = c\n coord.clear()\n coord += a\n }\n }\n\n def clear(): Unit = {\n coord.clear()\n char = 'z'\n }\n\n def nonEmpty = coord.nonEmpty\n def head = coord.head\n }\n\n /**\n * aで埋めれる一番距離が大きくなる場所の次に行ける場所を返す\n * @return (aの個数, aの次の候補)\n */\n def findMaxDist(): (Int, MinCharCoord) = {\n // 右下までaで埋めれた場合\n if (d(N - 1)(N - 1) != INF && (d(N - 1)(N - 1) < K || grid(N - 1)(N - 1) == 'a')) {\n (2 * N - 1, new MinCharCoord)\n } else {\n var dist = 0\n val coord = new MinCharCoord\n rep(N) { h =>\n rep(N) { w =>\n if (d(h)(w) != INF) {\n val move = h + w\n\n if (dist == move) {\n coord += Coord(h, w)\n } else if (dist < move) {\n dist = move\n coord.clear()\n coord += Coord(h, w)\n }\n }\n }\n }\n (dist, coord)\n }\n }\n\n val (as, ini) = findMaxDist()\n\n val str = new mutable.StringBuilder()\n rep(as)(_ => str += 'a')\n\n var q = ini\n var next = new MinCharCoord\n\n // 深さでBFSする感じ\n while (q.nonEmpty) {\n str += q.char\n q.coord foreach { c =>\n rep(2) { x =>\n val nh = c.h + (x ^ 1)\n val nw = c.w + x\n if (nh < N && nw < N) next += Coord(nh, nw)\n }\n }\n val temp = q\n q = next\n next = temp\n next.clear()\n }\n\n out.println(str.toString)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val grid = Array.ofDim[Array[Char]](N)\n rep(N) { i =>\n grid(i) = ns(N)\n }\n\n case class Coord(h: Int, w: Int)\n val INF = Int.MaxValue / 2\n\n def dijk_a(sh: Int, sw: Int) = {\n val d = Array.fill[Int](N, N)(INF)\n case class Visit(h: Int, w: Int, cost: Int)\n val queue = new java.util.ArrayDeque[Visit]()\n d(sh)(sw) = 0\n queue.add(Visit(sh, sw, 0))\n\n while(!queue.isEmpty) {\n val v = queue.poll()\n if (d(v.h)(v.w) == v.cost) {\n rep(2) { x =>\n val nh = v.h + (x ^ 1)\n val nw = v.w + x\n val c = if (grid(v.h)(v.w) == 'a') 0 else 1\n val next = v.cost + c\n if (nh < N && nw < N && K - next >= 0) {\n if (d(nh)(nw) > next) {\n d(nh)(nw) = next\n if (c == 0) {\n queue.addFirst(Visit(nh, nw, next))\n } else {\n queue.addLast(Visit(nh, nw, next))\n }\n }\n }\n }\n }\n }\n\n d\n }\n\n val d = dijk_a(0, 0)\n\n /**\n * 一番アルファベット順が小さいものだけを残す\n */\n class MinCharCoord {\n val coord = mutable.Set[Coord]()\n var char = 'z'\n\n def +=(a: Coord): Unit = {\n val c = grid(a.h)(a.w)\n if (c == char) {\n coord += a\n } else if (c < char) {\n char = c\n coord.clear()\n coord += a\n }\n }\n\n def clear(): Unit = {\n coord.clear()\n char = 'z'\n }\n\n def nonEmpty = coord.nonEmpty\n def head = coord.head\n }\n\n /**\n * aで埋めれる一番距離が大きくなる場所の次に行ける場所を返す\n * @return (aの個数, aの次の候補)\n */\n def findMaxDist(): (Int, MinCharCoord) = {\n // 右下までaで埋めれた場合\n if (d(N - 1)(N - 1) != INF && (d(N - 1)(N - 1) > 0 || grid(N - 1)(N - 1) == 'a')) {\n (2 * N - 1, new MinCharCoord)\n } else {\n var dist = 0\n val coord = new MinCharCoord\n rep(N) { h =>\n rep(N) { w =>\n if (d(h)(w) != INF) {\n val move = h + w\n\n if (dist == move) {\n coord += Coord(h, w)\n } else if (dist < move) {\n dist = move\n coord.clear()\n coord += Coord(h, w)\n }\n }\n }\n }\n (dist, coord)\n }\n }\n\n val (as, ini) = findMaxDist()\n\n val str = new mutable.StringBuilder()\n rep(as)(_ => str += 'a')\n\n var q = ini\n var next = new MinCharCoord\n\n // 深さでBFSする感じ\n while (q.nonEmpty) {\n str += q.char\n q.coord foreach { c =>\n rep(2) { x =>\n val nh = c.h + (x ^ 1)\n val nw = c.w + x\n if (nh < N && nw < N) next += Coord(nh, nw)\n }\n }\n val temp = q\n q = next\n next = temp\n next.clear()\n }\n\n out.println(str.toString)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val grid = Array.ofDim[Array[Char]](N)\n rep(N) { i =>\n grid(i) = ns(N)\n }\n\n case class Coord(h: Int, w: Int)\n val INF = Int.MaxValue / 2\n\n def dijk_a(sh: Int, sw: Int) = {\n val d = Array.fill[Int](N, N)(INF)\n case class Visit(h: Int, w: Int, cost: Int)\n val queue = new java.util.ArrayDeque[Visit]()\n d(sh)(sw) = 0\n queue.add(Visit(sh, sw, 0))\n\n while(!queue.isEmpty) {\n val v = queue.poll()\n if (d(v.h)(v.w) == v.cost) {\n rep(2) { x =>\n val nh = v.h + (x ^ 1)\n val nw = v.w + x\n val c = if (grid(v.h)(v.w) == 'a') 0 else 1\n val next = v.cost + c\n if (nh < N && nw < N && K - next >= 0) {\n if (d(nh)(nw) > next) {\n d(nh)(nw) = next\n if (c == 0) {\n queue.addFirst(Visit(nh, nw, next))\n } else {\n queue.addLast(Visit(nh, nw, next))\n }\n }\n }\n }\n }\n }\n\n d\n }\n\n val d = dijk_a(0, 0)\n def findMaxDist(): (Int, ArrayBuffer[Coord]) = {\n var dist = 0\n val coord = ArrayBuffer[Coord]()\n rep(N) { h =>\n rep(N) { w =>\n if (d(h)(w) != INF) {\n if (dist == h + w) {\n coord += Coord(h, w)\n } else if (dist < h + w) {\n dist = h + w\n coord.clear()\n coord += Coord(h, w)\n }\n }\n }\n }\n (dist, coord)\n }\n\n def filterMinAlpha(as: mutable.Set[Coord]): mutable.Set[Coord] = {\n as.groupBy(c => grid(c.h)(c.w)).toSeq.minBy(_._1)._2\n }\n\n val (as, ini) = findMaxDist()\n\n val str = new mutable.StringBuilder()\n var q = mutable.Set(ini: _*)\n rep(as)(_ => str += 'a')\n\n // 深さでBFSする感じ\n while (q.nonEmpty) {\n val next = mutable.Set[Coord]()\n val filtered = filterMinAlpha(q)\n val a = filtered.head\n str += grid(a.h)(a.w)\n filtered foreach { c =>\n rep(2) { x =>\n val nh = c.h + (x ^ 1)\n val nw = c.w + x\n if (nh < N && nw < N) next += Coord(nh, nw)\n }\n }\n q = next\n }\n\n out.println(str.toString)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k) = readInts(2)\n val cs = Array.fill(n){ readLine.toCharArray }\n\n val best = Array.fill(2 * n - 1){ 'z' }\n\n best(0) = cs(0)(0)\n val ks = Array.fill(n, n)(0)\n ks(0)(0) = k\n\n for (step <- 0 until 2 * n - 2) {\n var i = if (step < n) 0 else step - n + 1\n var j = if (step < n) step else n - 1\n while (j >= 0 && i < n) {\n if (ks(i)(j) > 0) best(step) = 'a'\n val c = if (ks(i)(j) > 0) 'a' else cs(i)(j)\n if (c <= best(step)) {\n val kk = if (cs(i)(j) == 'a') ks(i)(j) else ks(i)(j) - 1\n if (j < n - 1) {\n if (cs(i)(j + 1) <= best(step + 1)) {\n best(step + 1) = cs(i)(j + 1)\n }\n ks(i)(j + 1) = Math.max(ks(i)(j + 1), kk)\n }\n if (i < n - 1) {\n if (cs(i + 1)(j) <= best(step + 1)) {\n best(step + 1) = cs(i + 1)(j)\n }\n ks(i + 1)(j) = Math.max(ks(i + 1)(j), kk)\n }\n }\n i += 1\n j -= 1\n }\n }\n\n if (ks(n - 1)(n - 1) > 0) best(2 * n - 2) = 'a'\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(best.mkString)\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k0) = readInts(2)\n val cs = Array.fill(n){ readLine.toCharArray }\n var k = k0\n\n if (cs(0)(0) != 'a' && k > 0) {\n cs(0)(0) = 'a'\n k -= 1\n }\n\n val best = Array.fill(2 * n - 1){ 'z' }\n\n best(0) = cs(0)(0)\n val ks = Array.fill(n, n)(0)\n ks(0)(0) = k\n\n for (step <- 0 until 2 * n - 2) {\n var i = if (step < n) 0 else step - n + 1\n var j = if (step < n) step else n - 1\n while (j >= 0 && i < n) {\n if (ks(i)(j) > 0) best(step) = 'a'\n val c = if (ks(i)(j) > 0) 'a' else cs(i)(j)\n if (c <= best(step)) {\n val kk = if (cs(i)(j) == 'a') ks(i)(j) else ks(i)(j) - 1\n if (j < n - 1 && cs(i)(j + 1) <= best(step + 1)) {\n best(step + 1) = cs(i)(j + 1)\n ks(i)(j + 1) = Math.max(ks(i)(j + 1), kk)\n }\n if (i < n - 1 && cs(i + 1)(j) <= best(step + 1)) {\n best(step + 1) = cs(i + 1)(j)\n ks(i + 1)(j) = Math.max(ks(i + 1)(j), kk)\n }\n }\n i += 1\n j -= 1\n }\n }\n\n if (ks(n - 1)(n - 1) > 0) best(2 * n - 2) = 'a'\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(best.mkString)\n\n Console.flush\n}\n"}, {"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val cs = Array.fill(n){ readLine.toCharArray }\n\n val best = Array.fill(2 * n - 1){ 'z' }\n val canReach = Array.fill(n, n){ false }\n\n best(0) = cs(0)(0)\n val ks = Array.fill(n, n)(0)\n ks(0)(0) = k\n canReach(0)(0) = true\n\n for (step <- 0 until 2 * n - 2) {\n var i = if (step < n) 0 else step - n + 1\n var j = if (step < n) step else n - 1\n while (j >= 0 && i < n) {\n if (ks(i)(j) > 0) best(step) = 'a'\n else if (cs(i)(j) < best(step)) best(step) = cs(i)(j)\n i += 1\n j -= 1\n }\n i = if (step < n) 0 else step - n + 1\n j = if (step < n) step else n - 1\n while (j >= 0 && i < n) {\n val c = if (ks(i)(j) > 0) 'a' else cs(i)(j)\n if (canReach(i)(j) && c <= best(step)) {\n val kk = if (cs(i)(j) == 'a') ks(i)(j) else ks(i)(j) - 1\n if (j < n - 1) {\n if (cs(i)(j + 1) <= best(step + 1)) {\n best(step + 1) = cs(i)(j + 1)\n canReach(i)(j + 1) = true\n }\n ks(i)(j + 1) = Math.max(ks(i)(j + 1), kk)\n }\n if (i < n - 1) {\n if (cs(i + 1)(j) <= best(step + 1)) {\n best(step + 1) = cs(i + 1)(j)\n canReach(i + 1)(j) = true\n }\n ks(i + 1)(j) = Math.max(ks(i + 1)(j), kk)\n }\n }\n i += 1\n j -= 1\n }\n }\n\n if (ks(n - 1)(n - 1) > 0) best(2 * n - 2) = 'a'\n\n println(best.mkString)\n}\n"}, {"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val cs = Array.fill(n){ readLine.toCharArray }\n\n val best = Array.fill(2 * n - 1){ 'z' }\n val canReach = Array.fill(n, n){ false }\n\n best(0) = cs(0)(0)\n val ks = Array.fill(n, n)(0)\n ks(0)(0) = k\n canReach(0)(0) = true\n\n for (step <- 0 until 2 * n - 2) {\n var i = if (step < n) 0 else step - n + 1\n var j = if (step < n) step else n - 1\n while (j >= 0 && i < n) {\n if (ks(i)(j) > 0) best(step) = 'a'\n i += 1\n j -= 1\n }\n i = if (step < n) 0 else step - n + 1\n j = if (step < n) step else n - 1\n while (j >= 0 && i < n) {\n val c = if (ks(i)(j) > 0) 'a' else cs(i)(j)\n if (canReach(i)(j) && c <= best(step)) {\n val kk = if (cs(i)(j) == 'a') ks(i)(j) else ks(i)(j) - 1\n if (j < n - 1) {\n if (cs(i)(j + 1) <= best(step + 1)) {\n best(step + 1) = cs(i)(j + 1)\n canReach(i)(j + 1) = true\n }\n ks(i)(j + 1) = Math.max(ks(i)(j + 1), kk)\n }\n if (i < n - 1) {\n if (cs(i + 1)(j) <= best(step + 1)) {\n best(step + 1) = cs(i + 1)(j)\n canReach(i + 1)(j) = true\n }\n ks(i + 1)(j) = Math.max(ks(i + 1)(j), kk)\n }\n }\n i += 1\n j -= 1\n }\n }\n\n if (ks(n - 1)(n - 1) > 0) best(2 * n - 2) = 'a'\n\n println(best.mkString)\n}\n"}, {"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val cs = Array.fill(n){ readLine.toCharArray }\n\n val best = Array.fill(2 * n - 1){ 'z' }\n val canReach = Array.fill(n, n){ false }\n\n best(0) = cs(0)(0)\n val ks = Array.fill(n, n)(0)\n ks(0)(0) = k\n canReach(0)(0) = true\n\n for (step <- 0 until 2 * n - 2) {\n var i = if (step < n) 0 else step - n + 1\n var j = if (step < n) step else n - 1\n while (j >= 0 && i < n) {\n if (canReach(i)(j)) {\n if (ks(i)(j) > 0) best(step) = 'a'\n else if (cs(i)(j) < best(step)) best(step) = cs(i)(j)\n }\n i += 1\n j -= 1\n }\n i = if (step < n) 0 else step - n + 1\n j = if (step < n) step else n - 1\n while (j >= 0 && i < n) {\n val c = if (ks(i)(j) > 0) 'a' else cs(i)(j)\n if (canReach(i)(j) && c <= best(step)) {\n val kk = if (cs(i)(j) == 'a') ks(i)(j) else ks(i)(j) - 1\n if (j < n - 1) {\n if (cs(i)(j + 1) <= best(step + 1)) {\n best(step + 1) = cs(i)(j + 1)\n canReach(i)(j + 1) = true\n }\n ks(i)(j + 1) = Math.max(ks(i)(j + 1), kk)\n }\n if (i < n - 1) {\n if (cs(i + 1)(j) <= best(step + 1)) {\n best(step + 1) = cs(i + 1)(j)\n canReach(i + 1)(j) = true\n }\n ks(i + 1)(j) = Math.max(ks(i + 1)(j), kk)\n }\n }\n i += 1\n j -= 1\n }\n }\n\n if (ks(n - 1)(n - 1) > 0) best(2 * n - 2) = 'a'\n\n println(best.mkString)\n}\n"}, {"source_code": "\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k) = readInts(2)\n val cs = Array.fill(n){ readLine.toCharArray }\n\n val best = Array.fill(2 * n - 1){ 'z' }\n\n best(0) = cs(0)(0)\n val ks = Array.fill(n, n)(0)\n ks(0)(0) = k\n\n for (step <- 0 until 2 * n - 2) {\n var i = if (step < n) 0 else step - n + 1\n var j = if (step < n) step else n - 1\n while (j >= 0 && i < n) {\n if (ks(i)(j) > 0) best(step) = 'a'\n i += 1\n j -= 1\n }\n i = if (step < n) 0 else step - n + 1\n j = if (step < n) step else n - 1\n while (j >= 0 && i < n) {\n val c = if (ks(i)(j) > 0) 'a' else cs(i)(j)\n if (c <= best(step)) {\n val kk = if (cs(i)(j) == 'a') ks(i)(j) else ks(i)(j) - 1\n if (j < n - 1) {\n if (cs(i)(j + 1) <= best(step + 1)) {\n best(step + 1) = cs(i)(j + 1)\n }\n ks(i)(j + 1) = Math.max(ks(i)(j + 1), kk)\n }\n if (i < n - 1) {\n if (cs(i + 1)(j) <= best(step + 1)) {\n best(step + 1) = cs(i + 1)(j)\n }\n ks(i + 1)(j) = Math.max(ks(i + 1)(j), kk)\n }\n }\n i += 1\n j -= 1\n }\n }\n\n if (ks(n - 1)(n - 1) > 0) best(2 * n - 2) = 'a'\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(best.mkString)\n\n Console.flush\n}\n"}], "src_uid": "24afabd9cbbe287ea83c780f1797297c"} {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ad = an.distinct.toList\n val d = ad.length\n\n if (d > k) println(-1)\n else {\n val sub = ad ::: (1 to k).toList.diff(ad).take(k - d)\n lazy val subs: Stream[Int] = sub.toStream #::: subs\n\n val ans = subs.take(k * n).toList\n\n println(ans.length)\n println(ans.mkString(\" \"))\n }\n }\n}\n", "positive_code": [{"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val numCases = in.nextInt()\n (1 to numCases).foreach{ _ =>\n val (n,k) = (in.nextInt(),in.nextInt())\n\n val a = (1 to n).map(_ => in.nextInt()).distinct.toArray\n if(a.length > k){\n out.println(-1)\n }else{\n out.println(10000)\n var i = 0\n var e = 0\n val b = a ++ (Array.fill(k-a.length)(1))\n val sb = new mutable.StringBuilder()\n while(e<10000){\n sb.append(b(i))\n if(e < 10000-1)\n sb.append(' ')\n i += 1\n if(i >= k)\n i = 0\n e += 1\n }\n out.println(sb.toString())\n\n }\n\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ad = an.distinct.toList\n\n val ans =\n if (ad.length > k) List()\n else {\n val sub = ad ::: (1 to n).toList.diff(ad).take(k - ad.length)\n\n lazy val subs: Stream[Int] = sub.toStream #::: subs\n\n subs.take(k * an.length).toList\n }\n\n if (ans.isEmpty) println(-1)\n else {\n println(ans.length)\n println(ans.mkString(\" \"))\n }\n }\n}\n"}], "negative_code": [{"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n lazy val ak: Stream[Int] = (1 to k).toStream #::: ak\n\n val am =\n if (an.max > k) List()\n else ak.take(k * an.length).toList\n\n if (am.isEmpty) println(-1)\n else {\n println(am.length)\n println(am.mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val amin = an.min\n val amax = an.max\n\n val t = amax - amin + 1\n\n val ans =\n if (t > k) List()\n else {\n val r = n.min(amax + k - t)\n val l = r - k + 1\n\n if (l <= 0) List()\n else {\n lazy val ak: Stream[Int] = (l to r).toStream #::: ak\n\n ak.take(k * an.length).toList\n }\n }\n\n if (ans.isEmpty) println(-1)\n else {\n println(ans.length)\n println(ans.mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val amin = an.min\n val amax = an.max\n\n lazy val ak: Stream[Int] = (amin to (amin + k - 1)).toStream #::: ak\n\n val ans =\n if (amax - amin + 1 > k) List()\n else ak.take(k * an.length).toList\n\n if (ans.isEmpty) println(-1)\n else {\n println(ans.length)\n println(ans.mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ad = an.distinct.toList\n val d = ad.length\n\n if (d > k) println(-1)\n else {\n val sub = ad ::: ad.diff(1 to n).take(k - d)\n lazy val subs: Stream[Int] = sub.toStream #::: subs\n\n val ans = subs.take(k * n).toList\n\n println(ans.length)\n println(ans.mkString(\" \"))\n }\n\n }\n}\n"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ad = an.distinct.toList\n val d = ad.length\n\n if (d > k) println(-1)\n else {\n val sub = ad ::: (1 to k).toList.diff(ad)\n lazy val subs: Stream[Int] = sub.toStream #::: subs\n\n val ans = subs.take(k * n).toList\n\n println(ans.length)\n println(ans.mkString(\" \"))\n }\n }\n}\n"}], "src_uid": "80d4b2d01215b12ebd89b8ee2d1ac6ed"} {"source_code": "import java.io.InputStreamReader\n\n/**\n * Created by pva701 on 4/7/15.\n */\nobject HelloWorld {\n val MOD = 1000000000 + 7\n def pow(x:Int, y:Int):Int=if (y == 0) 1 else (1L * x * pow(x, y - 1) % MOD).toInt\n def main(args:Array[String]):Unit= {\n val n = readInt()\n val s = readLine()\n val AL = List('A', 'C', 'G', 'T')\n val cnt = new Array[Int](256)\n s.foreach(c=>cnt(c) += 1)\n val cnChar = cnt(AL.reduceLeft((a, b)=>if (cnt(a) > cnt(b)) a else b))\n val num = AL.foldLeft(0)((a, b)=>if (cnChar == cnt(b)) a + 1 else a)\n println(pow(num, n))\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n val MOD = 1e9 + 7\n\n def solve: Int = {\n val n = nextInt\n val ch = next.toCharArray\n val cnt = new Array[Int](4)\n for (i <- 0 until n) {\n ch(i) match {\n case 'A' => cnt(0) += 1\n case 'C' => cnt(1) += 1\n case 'G' => cnt(2) += 1\n case 'T' => cnt(3) += 1\n case _ =>\n }\n }\n val max = cnt.toList.max\n var k = 0\n for (i <- 0 until 4) {\n if (cnt(i) == max) {\n k += 1\n }\n }\n out.println(BigInt.int2bigInt(k).pow(n).%(BigInt.int2bigInt(MOD.toInt)))\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}, {"source_code": "object A extends App {\n val n = readLine.toInt\n val counts = readLine.groupBy(identity).map(_._2.size)\n val maxCount = counts.max\n val withMaxCount = counts.count(_ == maxCount)\n println(BigInt(withMaxCount).pow(n).mod(1000000007))\n}"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val s = readLine.map {\n case 'A' => 0\n case 'C' => 1\n case 'G' => 2\n case 'T' => 3\n }\n\n val cntA = s.count(_ == 0)\n val cntC = s.count(_ == 1)\n val cntG = s.count(_ == 2)\n val cntT = s.count(_ == 3)\n val cnt = (if (cntA > 0) 1 else 0) + (if (cntC > 0) 1 else 0) + (if (cntG > 0) 1 else 0) +(if (cntT > 0) 1 else 0)\n\n println(BigInt(cnt).pow(n).mod(1000000007))\n}\n"}, {"source_code": "object A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val s = readLine.map {\n case 'A' => 0\n case 'C' => 1\n case 'G' => 2\n case 'T' => 3\n }\n\n val cntA = s.count(_ == 0)\n val cntC = s.count(_ == 1)\n val cntG = s.count(_ == 2)\n val cntT = s.count(_ == 3)\n val cnt = (if (cntA > 0) 1 else 0) max (if (cntC > 0) 1 else 0) max (if (cntG > 0) 1 else 0) max (if (cntT > 0) 1 else 0)\n\n println(BigInt(cnt).pow(n).mod(1000000007))\n}"}], "src_uid": "f35c042f23747988f65c5b5e8d5ddacd"} {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn._\nobject Main extends App {\n\n for (_ ← 0 until readInt) {\n val Array(a, b) = readLine.trim.split(' ').map(_.toLong)\n println(\n (1 to digit(b)).map(d ⇒ power(10, d) - 1).count(_ <= b) * a\n )\n }\n def power(base: Long, exp: Int): Long = {\n exp match {\n case 0 ⇒ 1L\n case 1 ⇒ base\n case _ ⇒ power(base, exp & 1) * power(base * base, exp >> 1)\n }\n }\n def digit(value: Long): Int = {\n value match {\n case 0 ⇒ 0\n case _ ⇒ 1 + digit(value / 10)\n }\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) = {\n val t = readInt\n (0 until t).foreach((x) => f1)\n }\n def f1(): Unit = {\n val Array(a, b) = readLine.split(\" \").map(_.toLong)\n println(f2(a, b))\n }\n\n def f2(a: Long, b: Long): Long = {\n a * log10(b + 1)\n }\n def log10(x: Long): Long = {\n if (x < 10) 0 else log10(x / 10) + 1\n }\n }\n\n\n // ab + a + b = a * 10^(log(b)) + b => b + 1 = 10^log(b) (for b)"}, {"source_code": "import java.io.BufferedInputStream\nimport java.util.Scanner\n\nobject Main extends App {\n val inputReader = new Scanner(new BufferedInputStream(System.in))\n val T = inputReader.nextInt()\n for (_ <- 0 until T) {\n val A = inputReader.nextLong()\n val B = inputReader.nextDouble()\n val log10B = Math.log10(B + 1.001).toLong\n println(A * log10B)\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]) = {\n val t = readInt\n (0 until t).foreach((x) => f1)\n }\n def f1(): Unit = {\n val Array(a, b) = readLine.split(\" \").map(_.toInt)\n println(f2(a, b))\n }\n\n def f2(a: Long, b: Long): Long = {\n a * log10(b)\n }\n def log10(x: Long): Long = {\n if (x < 10) 0 else log10(x / 10) + 1\n }\n }\n\n\n // ab + a = a * 10^(log(b)) => b + 1 = 10^log(b) (for b)"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val t = readInt\n (0 until t).foreach((x) => f1)\n }\n def f1(): Unit = {\n val Array(a, b) = readLine.split(\" \").map(_.toLong)\n println(f2(a, b))\n }\n\n def f2(a: Long, b: Long): Long = {\n a * log10(b)\n }\n def log10(x: Long): Long = {\n if (x < 10) 0 else log10(x / 10) + 1\n }\n }\n\n\n // ab + a + b = a * 10^(log(b)) + b => b + 1 = 10^log(b) (for b)"}], "src_uid": "dc67dd2102c70ea476df642b863ae8d3"} {"source_code": "import scala.collection.mutable.Stack\nobject Main {\n def main(args: Array[String]):Unit = {\n val str = readLine()\n val stack = Stack[Char]()\n for (char <- str)\n if (stack.nonEmpty && stack.top == char)\n stack.pop()\n else\n stack.push(char);\n for (char <- stack.reverse)\n print(char)\n println()\n }\n}\n", "positive_code": [{"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\nobject Flask {\n \n def plugin(s: String): String = {\n var data:ArrayBuffer[Char] = new ArrayBuffer()\n var pos = 0\n var data_pos = 0\n data += '0'\n\n while (pos < s.size) {\n if (s(pos) == data(data_pos)) { data_pos -= 1 }\n else { \n data_pos += 1;\n if (data_pos == data.size)\n data += s(pos)\n else \n data(data_pos) = s(pos) \n }\n pos += 1\n }\n\n List.range(1, data_pos + 1).map(i => data(i)).mkString(\"\")\n }\n \n def main(args: Array[String]): Unit = {\n println(plugin(readLine))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n var stack = List.empty[Char]\n str.foreach { ch =>\n if (stack.isEmpty || stack.head != ch)\n stack ::= ch\n else if (stack.nonEmpty) {\n stack = stack.tail\n }\n }\n println(stack.reverse.mkString)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\n\nobject P081A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val input = sc.nextLine.toList\n\n def solve(): String = {\n \n @tailrec\n def loop(precedences: List[Char], remaining: List[Char]): List[Char] = {\n (precedences, remaining) match {\n case (xs, Nil) => xs.reverse\n case (Nil, y :: ys) => loop(y :: Nil, ys)\n case (x :: xs, y :: ys) => if (x == y) loop(xs, ys)\n else loop(y :: x :: xs, ys)\n }\n }\n\n loop(Nil, input).mkString\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "object Main {\n def dedup(s: String): String = {\n val stack = scala.collection.mutable.Stack[Char]()\n s.foreach{ c => \n if (stack.headOption == Some(c)) stack.pop\n else stack.push(c)\n }\n stack.mkString.reverse\n }\n \n def main(args: Array[String]) = {\n var s = readLine()\n println(dedup(s))\n }\n}"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject PlugIn {\n\n def processString(s: List[Char]) : List[Char] = {\n def process(c : List[Char], acc : List[Char]) : List[Char] = c match {\n case h1 :: h2 :: rest => if (h1 == h2)\n process(acc.head :: rest,acc.tail)\n else process(h2 :: rest, h1 :: acc)\n case h1 :: rest => process(rest, h1:: acc)\n case Nil => acc.reverse.tail\n }\n val r = process(s, List('.'))\n //if (r == s.toList) r else processString(r)\n r\n\n }\n\n def main(args: Array[String]) {\n val s = readLine()\n println(processString(s.toList).mkString)\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\n\nobject P081A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val input = sc.nextLine.toList\n\n def solve(): String = {\n \n @tailrec\n def innerLoop(acc: List[Char], cs: List[Char]): List[Char] = cs match {\n case x0 :: x1 :: xs if (x0 == x1) => innerLoop(acc, xs.dropWhile(_ == x0))\n case x :: xs => innerLoop(x :: acc, xs)\n case Nil => acc.reverse\n }\n\n @tailrec\n def outerLoop(acc: List[Char]): List[Char] = {\n val shortened = innerLoop(Nil, acc)\n if (acc == shortened) acc\n else outerLoop(shortened)\n }\n \n outerLoop(input).mkString\n }\n\n out.println(solve)\n out.close\n}\n"}], "src_uid": "26f1b8c3cb83603c904e1508df4067f4"} {"source_code": "\n/**\n * @author pvasilyev\n * @since 04 May 2016\n */\nobject A551 extends App {\n\n val n: Int = scala.io.StdIn.readInt()\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val withIndex = a.zipWithIndex\n val sorted = withIndex.sortBy(_._1)(Ordering[Int].reverse)\n\n val result: Array[(Int, Int)] = Array.ofDim(n)\n for (i <- 0 until n) {\n if (i == 0) {\n result(0) = (1, sorted(0)._2)\n } else if (sorted(i)._1 < sorted(i - 1)._1) {\n result(i) = (i+1, sorted(i)._2)\n } else {\n result(i) = (result(i-1)._1, sorted(i)._2)\n }\n }\n println(result.sortBy(_._2).map(_._1).mkString(\" \"))\n\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject CF551B extends App {\n var in = new Scanner(System.in)\n val n = in.nextInt()\n val a = (1 to n).map(i => in.nextInt())\n val b = a.map(i => a.count(j => j > i) + 1)\n println(b.mkString(\" \"))\n}"}, {"source_code": "\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport java.io.InputStream\nimport java.io.PrintWriter\nimport scala.util.Sorting\nobject CF551A {\n \n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n return next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n \n def main(args: Array[String]): Unit = {\n val in = new InputReader(System.in)\n val n = in.nextInt()\n val a = Array.fill(n) { in.nextInt()}\n val b = a.map { x => a.filter { y => y > x }.size + 1}\n println(b.mkString(\" \")) \n }\n}"}, {"source_code": "\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport java.io.InputStream\nimport java.io.PrintWriter\nimport scala.util.Sorting\nobject CF551A {\n \n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n return next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n \n def main(args: Array[String]): Unit = {\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n val n = in.nextInt()\n var a: Array[Integer] = new Array[Integer](n)\n for(i <- 0 until n) {\n a(i) = in.nextInt()\n }\n val origin = a.clone()\n Sorting.quickSort(a)\n a = a.reverse\n \n/* for(i <- 0 until n) {\n out.print(a(i) + \" \")\n }\n out.println\n\n for(i <- 0 until n) {\n out.print(origin(i) + \" \")\n }\n out.println\n*/ \n for(i <- 0 to n-1) {\n var index = n-1\n for(j <- n-1 to 0 by -1) {\n if ( origin(i)==a(j)) {\n index = j+1\n } \n }\n out.print(index)\n if ( i == n-1) \n out.println()\n else out.print(\" \")\n }\n \n \n out.flush\n out.close\n }\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _551A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt)\n val b = a.map(i => a.filter(j => j > i).size + 1)\n println(b.mkString(\" \"))\n}\n"}, {"source_code": "object A551 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n).zipWithIndex.sortBy(_._1).reverse\n val ranks = new Array[Int](n)\n ranks(input(0)._2) = 1\n var curr = 1\n for(i <- 1 until n) {\n if(input(i)._1 == input(i-1)._1) {\n ranks(input(i)._2) = curr\n } else {\n ranks(input(i)._2) = i+1\n curr = i+1\n }\n }\n println(ranks.mkString(\" \"))\n }\n}"}, {"source_code": "import scala.language.postfixOps\nimport java.io._\n\nobject CF_551A {\n def bin_search(arr: Array[Int], value: Int, b: Int, e: Int) : Int = {\n val mid : Int = (b+e)/2;\n if( b+1 >= e )\n b\n else if( arr(mid) <= value )\n bin_search(arr, value, mid, e)\n else\n bin_search(arr, value, b, mid)\n }\n\n def main(args: Array[String]) {\n val stdin = new BufferedReader(new InputStreamReader(System.in));\n val n = stdin.readLine.toInt;\n val list : Array[Int] = stdin.readLine.split(\" \").toArray.map(_.toInt);\n val sorted : Array[Int] = list.sortBy( x => x );\n for( i <- 0 until list.length )\n print((list.length - bin_search(sorted, list(i), 0, list.length)).toString + \" \");\n println(\"\")\n }\n}\n"}, {"source_code": "object _551A extends CodeForcesApp {\n import scala.collection.mutable\n\n override type Input = List[Int]\n override type Output = List[Int]\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n List.fill(nextInt)(nextInt)\n }\n\n override def solve(input: Input) = {\n input map {i => input.count(_ > i) + 1}\n }\n\n override def format(result: Output) = result mkString \" \"\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp extends App {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /********************************[ lib ]************************************/\n import scala.collection.mutable\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type m_=>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None\n /******************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n def timeLimitSecond = 1\n}\n"}, {"source_code": "object A{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val n=nextInt\n val a=Array.fill(n)(0)\n val r=Array.fill(n)(0)\n for(i<-0 until n){a(i)=nextInt}\n for(i<-0 until n){\n for(j<-0 until n){\n if(a(i) import scanner._\n val (n, k) = (nextInt, nextInt)\n val skills = List.fill(n)(nextInt)\n if (k >= skills.map(100 - _).sum) {\n n*10\n } else {\n val upgrades = skills map {s => 10 - (s%10)} sorted\n var ans = skills.map(_/10).sum\n var left = k\n for {\n i <- upgrades if i <= left\n } {\n left -= i\n ans += 1\n }\n\n ans + (left/10)\n }\n}) {\n override def format(result: Result) = super.format(result)\n}\n/********************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)\n final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val input = readLine().split(\" \").map(_.toLong)\n val k = input(1)\n\n val A = readLine().split(\" \").map(_.toLong)\n\n def count(A: Array[Long], e: Long): (Array[Long], Long) = {\n var energy = e\n\n val B = A.zip(A).map { case (x: Long, y: Long) =>\n (x, if (y == 100) 0 else 10 - y % 10)\n }.sortWith(_._2 < _._2).map { case (x: Long, diff: Long) =>\n if (energy > 0) {\n val min = Math.min(energy, diff)\n energy -= min\n (x + min, 0)\n } else {\n (x, 0)\n }\n }\n (B.map(_._1), energy)\n }\n\n def count2(A: Array[Long], e: Long): Array[Long] = {\n var energy = e\n\n A.map { x =>\n if (energy > 0 && x < 100) {\n val min = Math.min(energy, 100 - x)\n energy -= min\n x + min\n } else {\n x\n }\n }\n }\n\n\n var answer = count(A, k)\n println(count2(answer._1, answer._2).map(_ / 10).sum)\n\n}"}, {"source_code": "import java.io._\nimport scala.collection.mutable.Map\n\n//581C\nobject C_DevelopingSkills {\n \n def main(args: Array[String]): Unit = {\n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n\n val line1 = br.readLine().split(\" \")\n val n = Integer.parseInt(line1(0))\n val k = Integer.parseInt(line1(1))\n val skillsStr = br.readLine().split(\" \")\n val skills = skillsStr.map { _.toInt}\n \n// val n = 100\n// val k = 10000\n// val skills = Array.fill[Int](100)(100)\n\n val emptyList = List[Int]()\n val map = Map[Int, List[Int]]()\n \n for(i <- skills) {\n val rest = i % 10\n val old = map.getOrElse(rest, emptyList)\n map.put(rest, i :: old)\n }\n \n var count = k\n var ind = 9\n var lastLevel0Count = count\n\n while (count > 0 && ind >= 0 && (10 - ind) <= count) {\n if (ind == 0) lastLevel0Count = count\n val level = map.getOrElse(ind, emptyList)\n if (level != Nil) {\n val levelRes = procLevel(level, (10 - ind))\n map.put(ind, levelRes._1) //replace current\n map.put(0, levelRes._2 ::: map.getOrElse(0, emptyList)) //update zero\n }\n\n if (ind > 0) ind -= 1\n else if (lastLevel0Count == count) count = 0\n }\n \n println(calcPoints)\n \n \n def calcPoints(): Int = {\n var result = 0;\n for (level <- map) {\n for(i <- level._2) {\n if (i > 100) throw new RuntimeException(\"i > 100 \" + i)\n result += (i/10).toInt\n }\n }\n result\n }\n\n def procLevel(level: List[Int], step: Int): (List[Int], List[Int]) = {\n var current = List[Int]()\n var next = List[Int]()\n\n for (el <- level) {\n if (el < 100 && count >= step) {\n next = (el + step) :: next\n count -= step\n } else {\n current = el :: current\n } \n }\n (current, next)\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport scala.collection.mutable.Map\n\n//581C\nobject C_DevelopingSkills {\n \n def main(args: Array[String]): Unit = {\n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n\n val line1 = br.readLine().split(\" \")\n val n = Integer.parseInt(line1(0))\n val k = Integer.parseInt(line1(1))\n val skillsStr = br.readLine().split(\" \")\n val skills = skillsStr.map { _.toInt}\n \n// val n = 1000\n// val k = 100000\n// val skills = Array.fill[Int](1000)(0)\n\n val start = System.nanoTime();\n \n val map = Map[Int, List[Int]](0->Nil,1->Nil,2->Nil,3->Nil,4->Nil,5->Nil,6->Nil,7->Nil,8->Nil,9->Nil)\n \n for(i <- skills) {\n val rest = i % 10\n val old = map.get(rest).get\n map.put(rest, i :: old)\n }\n \n var count = k\n var ind = 9\n\n while (count > 0 && ind >= 0 && (10 - ind) <= count) {\n val level = map.get(ind).get\n val levelRes = procLevel(level, (10 - ind))\n map.put(ind, levelRes._1) //replace current\n map.put(0, levelRes._2 ::: map.get(0).get) //update zero\n\n if (ind > 0) ind -= 1 \n if (ind == 0) {\n procLevel0() \n count = 0\n }\n }\n \n println(calcPoints)\n \n// println(\"duration=\" + (System.nanoTime() - start));\n \n def calcPoints(): Int = {\n var result = 0;\n for (level <- map) {\n for(i <- level._2) {\n if (i > 100) throw new RuntimeException(\"i > 100 \" + i)\n result += (i/10).toInt\n }\n }\n result\n }\n \n def procLevel0() {\n var current = List[Int]()\n for (el <- map.get(0).get) {\n if (el < 100 && count >= 10) {\n val step = Math.min(100-el, count)\n current = el + step :: current\n count -= step\n } else {\n current = el :: current\n }\n }\n map.put(0, current)\n }\n\n def procLevel(level: List[Int], step: Int): (List[Int], List[Int]) = {\n var current = List[Int]()\n var next = List[Int]()\n\n for (el <- level) {\n if (el < 100 && count >= step) {\n next = (el + step) :: next\n count -= step\n } else {\n current = el :: current\n } \n }\n (current, next)\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport scala.collection.mutable.Map\nimport java.util.LinkedList\nimport scala.collection.JavaConversions.asScalaIterator\n\n//581C\nobject C_DevelopingSkills_fast {\n \n def main(args: Array[String]): Unit = {\n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n\n val line1 = br.readLine().split(\" \")\n val n = Integer.parseInt(line1(0))\n val k = Integer.parseInt(line1(1))\n val skillsStr = br.readLine().split(\" \")\n val skills = skillsStr.map { _.toInt}\n \n// val n = 100000\n// val k = 10000000\n// val skills = Array.fill[Int](n)(1)\n\n val start = System.nanoTime();\n \n val map = Map[Int, LinkedList[Int]](0->new LinkedList,1->new LinkedList,\n 2->new LinkedList,3->new LinkedList,4->new LinkedList,\n 5->new LinkedList,6->new LinkedList,7->new LinkedList,8->new LinkedList,9->new LinkedList)\n \n for(i <- skills) {\n val rest = i % 10\n val old = map.get(rest).get\n old.add(i)\n }\n \n var count = k\n var ind = 9\n\n while (count > 0 && ind >= 0 && (10 - ind) <= count) {\n procLevel(ind)\n if (ind > 0) ind -= 1 \n if (ind == 0) {\n procLevel0() \n count = 0\n }\n }\n \n println(calcPoints)\n \n// println(\"duration=\" + (System.nanoTime() - start));\n \n def calcPoints(): Int = {\n var result = 0;\n for (level <- map) {\n val iter = level._2.iterator()\n while (iter.hasNext()) {\n val i = iter.next()\n if (i > 100) throw new RuntimeException(\"i > 100 \" + i)\n result += (i/10).toInt\n }\n }\n result\n }\n \n def procLevel0() {\n val level = map.get(0).get\n val iter = level.listIterator(0)\n while (iter.hasNext()) {\n val el = iter.next()\n if (el < 100 && count >= 10) {\n val step = Math.min(100-el, count)\n iter.set(el + step)\n count -= step\n }\n }\n }\n\n def procLevel(ind: Int)= {\n val level = map.get(ind).get\n val next = map.get(0).get\n val step = 10 - ind\n val iter = level.iterator()\n for (el <- iter) {\n if (el < 100 && count >= step) {\n iter.remove()\n next.add(el + step)\n count -= step\n } \n }\n }\n }\n}\n"}, {"source_code": "/**\n * @author netman\n */\n\n\nimport java.io._\nimport scala._\nimport scala.Array._\nimport java.util.ArrayList\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\n\nobject HelloWorld {\n\n class InputReader(reader: BufferedReader) {\n \n var tokenizer: StringTokenizer = null;\n \n def this(stream: InputStream) = {\n this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));\n }\n \n def this(f: File) = {\n this(new BufferedReader(new FileReader(f), (1 << 20)));\n }\n \n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine());\n }\n return tokenizer.nextToken();\n }\n \n def nextInt(): Int = next().toInt\n \n def nextDouble(): Double = next().toDouble\n \n def close() = reader.close();\n }\n \n class OutputWriter(writer: PrintWriter) {\n def this(stream: OutputStream) {\n this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));\n }\n \n def this(f: File) = {\n this(new PrintWriter(new BufferedWriter(new FileWriter(f))));\n }\n \n def print(x: Any) = writer.print(x);\n \n def println(x: Any) = writer.println(x);\n \n def close() = writer.close();\n }\n \n \n val in = new InputReader(System.in)\n val out = new OutputWriter(System.out)\n \n val maxDist = 10\n \n def main(args: Array[String]): Unit = {\n var v = Array.fill[ArrayList[Int]](maxDist + 1)(new ArrayList[Int])\n \n val n = in.nextInt\n val k = in.nextInt\n \n var a = new Array[Int](n)\n \n for (i <- 0 until n) {\n a(i) = in.nextInt\n if (a(i) != 100) {\n val y = a(i) / maxDist * maxDist + maxDist\n v(y - a(i)).add(i)\n }\n }\n \n var it = k\n var flag = true\n \n while (it > 0 && flag) {\n var i = 1\n var fnd = false\n while (i <= maxDist && !fnd) {\n if (!v(i).isEmpty) {\n fnd = true\n }\n else {\n i += 1\n }\n }\n if (i == maxDist + 1) {\n flag = false\n }\n else {\n a(v(i).get(v(i).size() - 1)) += 1\n if (a(v(i).get(v(i).size() - 1)) != 100) {\n val y = a(v(i).get(v(i).size() - 1)) / maxDist * maxDist + maxDist\n v(y - a(v(i).get(v(i).size() - 1))).add(v(i).get(v(i).size() - 1))\n }\n v(i).remove(v(i).size() - 1)\n it -= 1\n }\n }\n \n var res = 0L\n \n for (i <- 0 until n) {\n res += a(i) / 10\n }\n \n out.println(res)\n \n out.close\n }\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\nimport scala.language.postfixOps\n\nobject TaskC extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt\n var k = sc.nextInt\n var res = 0\n var tens = 0\n\n val remainders = mutable.ListBuffer.empty[Int]\n\n 0 until n foreach { _ =>\n val a = sc.nextInt\n\n val toMax = 100 - a\n val remainder = toMax % 10\n tens += toMax - remainder\n\n if (remainder != 0) remainders += remainder\n\n res += a / 10\n }\n\n remainders.sorted.foreach { r =>\n if (k >= r) {\n k -= r\n res += 1\n }\n }\n\n println(res + math.min(k, tens) / 10)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt)\n val levelSoFar = data.map(_ / 10).sum\n val leftOvers = data.map(_ % 10).groupBy(x => x).map(x => x._1 -> x._2.length)\n val res = (9 to 1 by -1).foldLeft((0, k)) {\n case ((sum, 0), _) =>\n (sum, 0)\n case ((sum, left), i) =>\n val have = leftOvers.getOrElse(i, 0)\n val levelsMax = left / (10 - i)\n val levels = Math.min(levelsMax, have)\n (sum + levels, left - levels * (10 - i))\n }\n println(Math.min(res._1 + levelSoFar + res._2 / 10, n * 10))\n}"}, {"source_code": "object PetyaSkills {\n\n val in = io.Source.stdin.getLines()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(in.next())\n\n def readInts(n: Int) = {\n val stringTokenizer = tokenizeLine;\n Array.fill(n)(stringTokenizer.nextToken.toInt)\n }\n\n def floorSum(x: Int, res: Int) = res + x / 10\n\n def calculateRank(accumulator: Accumulator) = accumulator.skills.foldRight(0)(floorSum)\n\n case class Accumulator(skills: Seq[Int], availablePoints: Int)\n\n def solve(accumulator: Accumulator): Int = {\n\n val skills = if (accumulator.skills.isEmpty || accumulator.availablePoints == 0) {\n accumulator\n } else {\n distributeSkills(accumulator)\n }\n\n calculateRank(skills)\n }\n\n\n def distributeSkills(accumulator: Accumulator): Accumulator = {\n// println(\"****\")\n// println(accumulator)\n val sortedSkills: Seq[Int] = accumulator.skills.sortBy(x => ((x % 10, x)))\n// println(sortedSkills)\n val updatedSkills = sortedSkills\n .foldRight(accumulator.copy(skills = Seq.empty)) { (currentElement, result) =>\n\n// println(result)\n val gap = needTo10(currentElement)\n// println(\"need to 10: \" + gap)\n// println(\"current: \" + currentElement)\n if (result.availablePoints < gap || currentElement == 100) {\n val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)\n Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)\n } else {\n val updatedSkills = result.skills.+:(currentElement + gap)\n val availablePoints = result.availablePoints - gap\n Accumulator(updatedSkills, availablePoints)\n }\n }\n\n// println(\"updated skills: \" +updatedSkills)\n if (updatedSkills.skills.head < 100 && updatedSkills.availablePoints >= needTo10(updatedSkills.skills.head)) {\n distributeSkills(updatedSkills.copy(skills = updatedSkills.skills))\n } else {\n updatedSkills\n }\n\n\n }\n\n def needTo10(element: Int): Int = {\n 10 - element % 10\n }\n\n def main(args: Array[String]) {\n\n val Array(numberOfSkills, availablePoints) = readInts(2)\n\n val currentSkills = readInts(numberOfSkills)\n\n println(solve(Accumulator(currentSkills, availablePoints)))\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n var k = nextInt\n val ab = new Array[Int](n)\n val diff = new Array[(Int, Int)](n)\n for (i <- 0 until n) {\n ab(i) = nextInt\n diff(i) = ((ab(i) / 10 + 1) * 10 - ab(i), i)\n }\n val sorted = diff.sortBy(_._1).foreach(x => {\n if (k >= x._1 && ab(x._2) < 100) {\n ab(x._2) += x._1\n k -= x._1\n }\n })\n for (i <- 0 until n) {\n while (k >= 10 && ab(i) != 100) {\n ab(i) += 10\n k -= 10\n }\n }\n var rtg = 0\n for (i <- 0 until ab.length) {\n rtg += ab(i) / 10\n }\n out.println(rtg)\n return 0\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main extends App {\n\n val sc = new Scanner(System.in)\n val n = sc.nextInt\n var m = sc.nextInt\n\n val arr =\n Array\n .tabulate(n)(_ => sc.nextInt)\n .sortWith((a, b) => (a % 10) > (b % 10))\n\n var mx = 0\n var s1 = 0\n arr.indices.foreach(i => {\n val s = 10 - (arr(i) % 10)\n val t = if (s == 10) 0 else s\n if (m >= t) {\n arr(i) += t\n m -= t\n } else {\n m = 0\n }\n s1 += arr(i) / 10\n mx += 100 - arr(i)\n })\n\n println(s1 + (math.min(mx, m) / 10))\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt)\n val levelSoFar = data.map(_ / 10).sum\n val leftOvers = data.map(_ % 10).groupBy(x => x).map(x => x._1 -> x._2.length)\n val res = (9 to 1 by -1).foldLeft((0, k)) {\n case ((sum, 0), _) =>\n (sum, 0)\n case ((sum, left), i) =>\n val have = leftOvers.getOrElse(i, 0)\n val levelsMax = left / (10 - i)\n val levels = Math.min(levelsMax, have)\n (sum + levels, left - levels * (10 - i))\n }\n println(Math.min(res._1 + levelSoFar, n * 10))\n}"}, {"source_code": "object PetyaSkills {\n\n val in = io.Source.stdin.getLines()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(in.next())\n\n def readInts(n: Int) = {\n val stringTokenizer = tokenizeLine;\n Array.fill(n)(stringTokenizer.nextToken.toInt)\n }\n\n def floorSum(x: Int, res: Int) = res + x / 10\n\n def calculateRank(accumulator: Accumulator) = accumulator.skills.foldRight(0)(floorSum)\n\n case class Accumulator(skills: Seq[Int], availablePoints: Int)\n\n def solve(accumulator: Accumulator): Int = {\n\n val skills = if (accumulator.skills.isEmpty || accumulator.availablePoints == 0) {\n accumulator\n } else {\n distributeSkills(accumulator)\n }\n\n calculateRank(skills)\n }\n\n\n def distributeSkills(accumulator: Accumulator): Accumulator = {\n val updatedSkills = accumulator.skills.foldRight(Accumulator(Seq.empty, accumulator.availablePoints)) { (currentElement, result) =>\n val gap = needTo10(currentElement)\n if (result.availablePoints < gap || currentElement == 100) {\n val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)\n Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)\n } else {\n val updatedSkills = result.skills.+:(currentElement + gap)\n val availablePoints = result.availablePoints - gap\n Accumulator(updatedSkills, availablePoints)\n }\n }\n\n if (updatedSkills.skills.head < 100 && updatedSkills.availablePoints > needTo10(updatedSkills.skills.head)) {\n distributeSkills(Accumulator(updatedSkills.skills.sortBy(needTo10),updatedSkills.availablePoints))\n } else {\n updatedSkills\n }\n\n\n }\n\n def needTo10(element: Int): Int = {\n 10 - element % 10\n }\n\n def main(args: Array[String]) {\n\n val Array(numberOfSkills, availablePoints) = readInts(2)\n val currentSkills = readInts(numberOfSkills).sortBy(needTo10)\n\n println(solve(Accumulator(currentSkills, availablePoints)))\n }\n\n}\n"}, {"source_code": "object PetyaSkills {\n\n val in = io.Source.stdin.getLines()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(in.next())\n\n def readInts(n: Int) = {\n val stringTokenizer = tokenizeLine;\n Array.fill(n)(stringTokenizer.nextToken.toInt)\n }\n\n def floorSum(x: Int, res: Int) = res + x / 10\n\n def calculateRank(accumulator: Accumulator) = accumulator.skills.foldRight(0)(floorSum)\n\n case class Accumulator(skills: Seq[Int], availablePoints: Int)\n\n def solve(accumulator: Accumulator): Int = {\n\n val skills = if (accumulator.skills.isEmpty || accumulator.availablePoints == 0) {\n accumulator\n } else {\n distributeSkills(accumulator)\n }\n\n calculateRank(skills)\n }\n\n\n def distributeSkills(accumulator: Accumulator): Accumulator = {\n val updatedSkills = accumulator.skills.sortBy(x => x).sortBy(needTo10)\n .foldRight(accumulator.copy(skills = Seq.empty)) { (currentElement, result) =>\n\n val gap = needTo10(currentElement)\n if (result.availablePoints < gap || currentElement == 100) {\n val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)\n Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)\n } else {\n val updatedSkills = result.skills.+:(currentElement + gap)\n val availablePoints = result.availablePoints - gap\n Accumulator(updatedSkills, availablePoints)\n }\n }\n\n if (updatedSkills.skills.head < 100 && updatedSkills.availablePoints > needTo10(updatedSkills.skills.head)) {\n distributeSkills(updatedSkills.copy(skills = updatedSkills.skills))\n } else {\n updatedSkills\n }\n\n\n }\n\n def needTo10(element: Int): Int = {\n 10 - element % 10\n }\n\n def main(args: Array[String]) {\n\n val Array(numberOfSkills, availablePoints) = readInts(2)\n\n val currentSkills = readInts(numberOfSkills)\n\n println(solve(Accumulator(currentSkills, availablePoints)))\n }\n\n}\n"}, {"source_code": "object PetyaSkills {\n\n\n val in = io.Source.stdin.getLines()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(in.next())\n\n def readInts(n: Int) = {\n val stringTokenizer = tokenizeLine;\n Array.fill(n)(stringTokenizer.nextToken.toInt)\n }\n\n def floorSum(x: Int, res: Int) = res + x / 10\n\n def calculateRank(accumulator: Accumulator) = accumulator.skills.foldRight(0)(floorSum)\n\n case class Accumulator(skills: Seq[Int], availablePoints: Int)\n\n def solve(accumulator: Accumulator): Int = {\n\n val skills = if (accumulator.skills.isEmpty || accumulator.availablePoints == 0) {\n accumulator\n } else {\n distributeSkills(accumulator)\n }\n\n calculateRank(skills)\n }\n\n\n def distributeSkills(accumulator: Accumulator): Accumulator = {\n val updatedSkills = accumulator.skills.foldRight(Accumulator(Seq.empty, accumulator.availablePoints)) { (currentElement, result) =>\n val gap = needTo10(currentElement)\n if (result.availablePoints < gap || currentElement == 100) {\n val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)\n Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)\n } else {\n val updatedSkills = result.skills.+:(currentElement + gap)\n val availablePoints = result.availablePoints - gap\n Accumulator(updatedSkills, availablePoints)\n }\n }\n\n if (updatedSkills.skills.head < 100 && updatedSkills.availablePoints > needTo10(updatedSkills.skills.head)) {\n distributeSkills(Accumulator(updatedSkills.skills.sortBy(needTo10),updatedSkills.availablePoints))\n } else {\n updatedSkills\n }\n\n\n }\n\n def needTo10(element: Int): Int = {\n 10 - element % 10\n }\n\n def main(args: Array[String]) {\n\n val Array(numberOfSkills, availablePoints) = readInts(2)\n val currentSkills = readInts(numberOfSkills).sortBy(needTo10)\n\n println(solve(Accumulator(currentSkills, availablePoints)))\n }\n\n}\n"}, {"source_code": "object PetyaSkills {\n\n val in = io.Source.stdin.getLines()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(in.next())\n\n def readInts(n: Int) = {\n val stringTokenizer = tokenizeLine;\n Array.fill(n)(stringTokenizer.nextToken.toInt)\n }\n\n def floorSum(x: Int, res: Int) = res + x / 10\n\n def calculateRank(skills: Seq[Int]) = skills.foldRight(0)(floorSum)\n\n case class Accumulator(skills: Seq[Int], availablePoints: Int)\n\n def solve(accumulator: Accumulator): Int = {\n val skills = distributeSkills(accumulator).skills\n calculateRank(skills)\n }\n\n\n def distributeSkills(accumulator: Accumulator): Accumulator = {\n\n accumulator.skills.foldRight(Accumulator(Seq.empty, accumulator.availablePoints)) { (currentElement, result) =>\n val gap = needTo10(currentElement)\n if (result.availablePoints < gap || currentElement == 100) {\n val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)\n Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)\n } else {\n val updatedSkills = result.skills.+:(currentElement + gap)\n val availablePoints = result.availablePoints - gap\n Accumulator(updatedSkills, availablePoints)\n }\n }\n }\n\n def needTo10(element: Int): Int = {\n 10 - element % 10\n }\n\n def main(args: Array[String]) {\n\n val Array(numberOfSkills, availablePoints) = readInts(2)\n val currentSkills = readInts(numberOfSkills).sortBy(needTo10)\n\n println(solve(Accumulator(currentSkills, availablePoints)))\n }\n\n}\n"}, {"source_code": "object PetyaSkills {\n\n val in = io.Source.stdin.getLines()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(in.next())\n\n def readInts(n: Int) = {\n val stringTokenizer = tokenizeLine;\n Array.fill(n)(stringTokenizer.nextToken.toInt)\n }\n\n def floorSum(x: Int, res: Int) = res + x / 10\n\n def calculateRank(accumulator: Accumulator) = accumulator.skills.foldRight(0)(floorSum)\n\n case class Accumulator(skills: Seq[Int], availablePoints: Int)\n\n def solve(accumulator: Accumulator): Int = {\n\n val skills = if (accumulator.skills.isEmpty || accumulator.availablePoints == 0) {\n accumulator\n } else {\n distributeSkills(accumulator)\n }\n\n calculateRank(skills)\n }\n\n\n def distributeSkills(accumulator: Accumulator): Accumulator = {\n val sortedSkills: Seq[Int] = accumulator.skills.sortBy(x => ((x % 10, x)))\n val updatedSkills = sortedSkills\n .foldRight(accumulator.copy(skills = Seq.empty)) { (currentElement, result) =>\n\n val gap = needTo10(currentElement)\n if (result.availablePoints < gap || currentElement == 100) {\n val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)\n Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)\n } else {\n val updatedSkills = result.skills.+:(currentElement + gap)\n val availablePoints = result.availablePoints - gap\n Accumulator(updatedSkills, availablePoints)\n }\n }\n\n if (updatedSkills.skills.head < 100 && updatedSkills.availablePoints > needTo10(updatedSkills.skills.head)) {\n distributeSkills(updatedSkills.copy(skills = updatedSkills.skills))\n } else {\n updatedSkills\n }\n\n\n }\n\n def needTo10(element: Int): Int = {\n 10 - element % 10\n }\n\n def main(args: Array[String]) {\n\n val Array(numberOfSkills, availablePoints) = readInts(2)\n\n val currentSkills = readInts(numberOfSkills)\n\n println(solve(Accumulator(currentSkills, availablePoints)))\n }\n\n}"}, {"source_code": "\nobject PetyaSkills {\n\n val in = io.Source.stdin.getLines()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(in.next())\n\n def readInts(n: Int) = {\n val stringTokenizer = tokenizeLine;\n Array.fill(n)(stringTokenizer.nextToken.toInt)\n }\n\n def floorSum(x: Int, res: Int) = res + x / 10\n\n def calculateRank(accumulator: Accumulator) = accumulator.skills.foldRight(0)(floorSum)\n\n case class Accumulator(skills: Seq[Int], availablePoints: Int)\n\n def solve(accumulator: Accumulator): Int = {\n\n val skills = if (accumulator.skills.isEmpty || accumulator.availablePoints == 0) {\n accumulator\n } else {\n distributeSkills(accumulator)\n }\n \n calculateRank(skills)\n }\n\n\n def distributeSkills(accumulator: Accumulator): Accumulator = {\n\n val updatedSkills = accumulator.skills.foldRight(Accumulator(Seq.empty, accumulator.availablePoints)) { (currentElement, result) =>\n val gap = needTo10(currentElement)\n if (result.availablePoints < gap || currentElement == 100) {\n val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)\n Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)\n } else {\n val updatedSkills = result.skills.+:(currentElement + gap)\n val availablePoints = result.availablePoints - gap\n Accumulator(updatedSkills, availablePoints)\n }\n }\n\n if (accumulator.skills.head < 100 && accumulator.availablePoints > needTo10(accumulator.skills.head)) {\n distributeSkills(updatedSkills)\n } else {\n updatedSkills\n }\n\n\n }\n\n def needTo10(element: Int): Int = {\n 10 - element % 10\n }\n\n def main(args: Array[String]) {\n\n val Array(numberOfSkills, availablePoints) = readInts(2)\n val currentSkills = readInts(numberOfSkills).sortBy(needTo10)\n\n println(solve(Accumulator(currentSkills, availablePoints)))\n }\n\n}\n"}, {"source_code": "object PetyaSkills {\n\n val in = io.Source.stdin.getLines()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(in.next())\n\n def readInts(n: Int) = {\n val stringTokenizer = tokenizeLine;\n Array.fill(n)(stringTokenizer.nextToken.toInt)\n }\n\n def floorSum(x: Int, res: Int) = res + x / 10\n\n def calculateRank(accumulator: Accumulator) = accumulator.skills.foldRight(0)(floorSum)\n\n case class Accumulator(skills: Seq[Int], availablePoints: Int)\n\n def solve(accumulator: Accumulator): Int = {\n\n val skills = if (accumulator.skills.isEmpty || accumulator.availablePoints == 0) {\n accumulator\n } else {\n distributeSkills(accumulator)\n }\n\n calculateRank(skills)\n }\n\n\n def distributeSkills(accumulator: Accumulator): Accumulator = {\n println(\"****\")\n println(accumulator)\n val updatedSkills = accumulator.skills.foldRight(Accumulator(Seq.empty, accumulator.availablePoints)) { (currentElement, result) =>\n println(currentElement)\n println(result)\n val gap = needTo10(currentElement)\n if (result.availablePoints < gap || currentElement == 100) {\n val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)\n Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)\n } else {\n val updatedSkills = result.skills.+:(currentElement + gap)\n val availablePoints = result.availablePoints - gap\n Accumulator(updatedSkills, availablePoints)\n }\n }\n\n if (updatedSkills.skills.head < 100 && updatedSkills.availablePoints > needTo10(updatedSkills.skills.head)) {\n distributeSkills(updatedSkills.copy(skills = updatedSkills.skills.sortBy(needTo10)))\n } else {\n updatedSkills\n }\n\n\n }\n\n def needTo10(element: Int): Int = {\n 10 - element % 10\n }\n\n def main(args: Array[String]) {\n\n val Array(numberOfSkills, availablePoints) = readInts(2)\n val currentSkills = readInts(numberOfSkills).sortBy(needTo10)\n\n println(solve(Accumulator(currentSkills, availablePoints)))\n }\n\n}\n"}, {"source_code": "\nobject PetyaSkills {\n\n val in = io.Source.stdin.getLines()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(in.next())\n\n def readInts(n: Int) = {\n val stringTokenizer = tokenizeLine;\n Array.fill(n)(stringTokenizer.nextToken.toInt)\n }\n\n def floorSum(x: Int, res: Int) = res + x / 10\n\n def calculateRank(skills: Seq[Int]) = skills.foldRight(0)(floorSum)\n\n case class Accumulator(skills: Seq[Int], availablePoints: Int)\n\n def solve(accumulator: Accumulator): Int = {\n val skills = distributeSkills(accumulator).skills\n calculateRank(skills)\n }\n\n\n def distributeSkills(accumulator: Accumulator): Accumulator = {\n\n val updatedSkills = accumulator.skills.foldRight(Accumulator(Seq.empty, accumulator.availablePoints)) { (currentElement, result) =>\n println(result)\n val gap = needTo10(currentElement)\n if (result.availablePoints < gap || currentElement == 100) {\n val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)\n Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)\n } else {\n val updatedSkills = result.skills.+:(currentElement + gap)\n val availablePoints = result.availablePoints - gap\n Accumulator(updatedSkills, availablePoints)\n }\n }\n\n if (accumulator.skills.head < 100 && accumulator.availablePoints > needTo10(accumulator.skills.head)) {\n distributeSkills(updatedSkills)\n } else {\n updatedSkills\n }\n\n\n }\n\n def needTo10(element: Int): Int = {\n 10 - element % 10\n }\n\n def main(args: Array[String]) {\n\n val Array(numberOfSkills, availablePoints) = readInts(2)\n val currentSkills = readInts(numberOfSkills).sortBy(needTo10)\n\n println(solve(Accumulator(currentSkills, availablePoints)))\n }\n\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _581C extends CodeForcesApp[Int]({scanner => import scanner._\n val (n, k) = (nextInt, nextInt)\n val skills = List.fill(n)(nextInt)\n if (k >= skills.map(100 - _).sum) {\n n*10\n } else {\n val potentials = for {\n skill <- skills\n target <- (((skill/10) + 1)*10) to 100 by 10\n } yield (target - skill, (target/10) - (skill/10))\n\n val strategy = potentials.sortBy {case (cost, points) => 1.0*points/cost} (desc)\n\n var ans = skills.map(_/10).sum\n var left = k\n for {\n (cost, points) <- strategy if left > 0\n } if (left >= cost) {\n //debug(left, ans, cost, points)\n left -= cost\n ans += points\n }\n ans\n }\n}) {\n override def format(result: Result) = super.format(result)\n}\n/********************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)\n final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val input = readLine().split(\" \").map(_.toLong)\n val n = input(0).toInt\n val k = input(1)\n\n val A = readLine().split(\" \").map(_.toInt)\n\n var energy = k\n val B = A.zip(A).map { case (x: Int, y: Int) =>\n (x, if (y == 100) 0 else 10 - y % 10)\n }.sortWith(_._2 < _._2).map { case (x: Int, diff: Int) =>\n if (diff != 0 && energy >= diff) {\n energy -= diff\n (x + diff, 0)\n } else {\n (x, diff)\n }\n\n }\n\n// println(\"phase 1: \" + B.mkString(\" \"))\n// println(energy)\n var idx = A.length - 1\n while (energy > 0 && idx >= 0) {\n if (B(idx)._1 < 100) {\n if (B(idx)._1 + energy <= 100) {\n B(idx) = (B(idx)._1 + energy.toInt, 0)\n energy = 0\n } else {\n B(idx) = (100, 0)\n energy -= (100 - B(idx)._1)\n }\n }\n\n idx -= 1\n }\n\n// println(\"phase 2: \" + B.mkString(\" \"))\n// println(energy)\n println(B.map(_._1 / 10).sum)\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val input = readLine().split(\" \").map(_.toLong)\n val n = input(0).toInt\n val k = input(1)\n\n val A = readLine().split(\" \").map(_.toLong)\n\n def count(A: Array[Long], e: Long): (Array[Long], Long) = {\n var energy = e\n\n val B = A.zip(A).map { case (x: Long, y: Long) =>\n (x, if (y == 100) 0 else 10 - y % 10)\n }.sortWith(_._2 < _._2).map { case (x: Long, diff: Long) =>\n val min = Math.min(energy, diff)\n energy -= min\n (x + min, 0)\n }\n\n (B.map(_._1), energy)\n }\n\n var answer = count(A, k)\n\n// println(answer._1.mkString(\" \"))\n if (answer._2 > 0) {\n answer = count(answer._1, answer._2)\n }\n// println(answer._1.mkString(\" \"))\n\n println(answer._1.map(_ / 10).sum)\n\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val input = readLine().split(\" \").map(_.toLong)\n val n = input(0).toInt\n val k = input(1)\n\n val A = readLine().split(\" \").map(_.toInt)\n\n var energy = k\n val B = A.zip(A).map { case (x: Int, y: Int) =>\n (x, if (y == 100) 0 else 10 - y % 10)\n }.sortWith(_._2 < _._2).map { case (x: Int, diff: Int) =>\n if (x != 100 && energy >= diff.toLong) {\n energy -= diff\n (x + diff, 0)\n } else {\n val max = Math.max(energy, diff)\n (x, diff - max.toInt)\n }\n }\n\n// println(B.mkString(\" \"))\n\n val answer = B.map { case (x: Int, diff: Int) =>\n if (x != 100 && energy > 0 && energy >= diff.toLong) {\n energy -= diff\n (x + diff, 0)\n }\n (x, diff)\n }\n\n// println(\"phase 2: \" + B.mkString(\" \"))\n// println(energy)\n println(answer.map(_._1 / 10).sum)\n\n}\n"}, {"source_code": "import java.io._\nimport scala.collection.mutable.Map\n\n//581C\nobject C_DevelopingSkills {\n \n def main(args: Array[String]): Unit = {\n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n\n val line1 = br.readLine().split(\" \")\n val n = Integer.parseInt(line1(0))\n val k = Integer.parseInt(line1(1))\n val skillsStr = br.readLine().split(\" \")\n val skills = skillsStr.map { _.toInt}\n \n// val n = 1000\n// val k = 100000\n// val skills = Array.fill[Int](1000)(0)\n\n val start = System.nanoTime();\n \n val map = Map[Int, List[Int]](0->Nil,1->Nil,2->Nil,3->Nil,4->Nil,5->Nil,6->Nil,7->Nil,8->Nil,9->Nil)\n \n for(i <- skills) {\n val rest = i % 10\n val old = map.get(rest).get\n map.put(rest, i :: old)\n }\n \n var count = k\n var ind = 9\n\n while (count > 0 && ind >= 0 && (10 - ind) <= count) {\n val level = map.get(ind).get\n val levelRes = procLevel(level, (10 - ind))\n map.put(ind, levelRes._1) //replace current\n map.put(0, levelRes._2 ::: map.get(0).get) //update zero\n\n if (ind > 0) ind -= 1 \n if (ind == 0) {\n procLevel0() \n count = 0\n }\n }\n \n println(calcPoints)\n \n println(\"duration=\" + (System.nanoTime() - start));\n \n def calcPoints(): Int = {\n var result = 0;\n for (level <- map) {\n for(i <- level._2) {\n if (i > 100) throw new RuntimeException(\"i > 100 \" + i)\n result += (i/10).toInt\n }\n }\n result\n }\n \n def procLevel0() {\n var current = List[Int]()\n for (el <- map.get(0).get) {\n if (el < 100 && count >= 10) {\n val step = Math.min(100-el, count)\n current = el + step :: current\n count -= step\n } else {\n current = el :: current\n }\n }\n map.put(0, current)\n }\n\n def procLevel(level: List[Int], step: Int): (List[Int], List[Int]) = {\n var current = List[Int]()\n var next = List[Int]()\n\n for (el <- level) {\n if (el < 100 && count >= step) {\n next = (el + step) :: next\n count -= step\n } else {\n current = el :: current\n } \n }\n (current, next)\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport scala.collection.mutable.Map\n\n//581C\nobject C_DevelopingSkills {\n \n def main(args: Array[String]): Unit = {\n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n\n val line1 = br.readLine().split(\" \")\n val n = Integer.parseInt(line1(0))\n val k = Integer.parseInt(line1(1))\n// println(s\"input $n $k\")\n val skillsStr = br.readLine().split(\" \")\n val skills = skillsStr.map { _.toInt}\n// println(\"skills = \" + skills.mkString(\" \"))\n \n// val n = 2\n// val k = 2\n// val skills = Array(99, 100)\n\n val emptyList = List[Int]()\n val map = Map[Int, List[Int]]()\n \n for(i <- skills) {\n val rest = i % 10\n val old = map.getOrElse(rest, emptyList)\n map.put(rest, i :: old)\n }\n \n var count = k\n var ind = 9\n\n while (count > 0 && ind > 0 && (10 - ind) <= count) {\n val level = map.getOrElse(ind, emptyList)\n if (level != Nil) {\n val levelRes = procLevel(level, (10 - ind))\n map.put(ind, levelRes._1) //replace current\n map.put(0, levelRes._2 ::: map.getOrElse(0, emptyList)) //update zero\n }\n\n if (ind > 0) ind -= 1\n }\n \n println(calcPoints)\n \n \n def calcPoints(): Int = {\n var result = 0;\n for (level <- map) {\n for(i <- level._2) {\n if (i > 100) throw new RuntimeException(\"i > 100 \" + i)\n result += (i/10).toInt\n }\n }\n result\n }\n\n def procLevel(level: List[Int], step: Int): (List[Int], List[Int]) = {\n var current = List[Int]()\n var next = List[Int]()\n\n for (el <- level) {\n if (el < 100 && count >= step) {\n next = (el + step) :: next\n count -= step\n } else {\n current = el :: current\n } \n }\n (current, next)\n }\n }\n}"}, {"source_code": "import java.io._\nimport scala.collection.mutable.Map\nimport java.util.LinkedList\nimport scala.collection.JavaConversions.asScalaIterator\n\n//581C\nobject C_DevelopingSkills_fast {\n \n def main(args: Array[String]): Unit = {\n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n\n val line1 = br.readLine().split(\" \")\n val n = Integer.parseInt(line1(0))\n val k = Integer.parseInt(line1(1))\n val skillsStr = br.readLine().split(\" \")\n val skills = skillsStr.map { _.toInt}\n \n// val n = 1000\n// val k = 100000\n// val skills = Array.fill[Int](1000)(0)\n\n val start = System.nanoTime();\n \n val map = Map[Int, LinkedList[Int]](0->new LinkedList,1->new LinkedList,\n 2->new LinkedList,3->new LinkedList,4->new LinkedList,\n 5->new LinkedList,6->new LinkedList,7->new LinkedList,8->new LinkedList,9->new LinkedList)\n \n for(i <- skills) {\n val rest = i % 10\n val old = map.get(rest).get\n old.add(i)\n }\n \n var count = k\n var ind = 9\n\n while (count > 0 && ind >= 0 && (10 - ind) <= count) {\n procLevel(ind)\n if (ind > 0) ind -= 1 \n if (ind == 0) {\n procLevel0() \n count = 0\n }\n }\n \n println(calcPoints)\n \n// println(\"duration=\" + (System.nanoTime() - start));\n \n def calcPoints(): Int = {\n var result = 0;\n for (level <- map) {\n val iter = level._2.iterator()\n while (iter.hasNext()) {\n val i = iter.next()\n if (i > 100) throw new RuntimeException(\"i > 100 \" + i)\n result += (i/10).toInt\n }\n }\n result\n }\n \n def procLevel0() {\n val level = map.get(0).get\n val iter = level.listIterator(0)\n while (iter.hasNext()) {\n val el = iter.next()\n if (el < 100 && count >= 10) {\n val step = Math.min(100-el, count)\n iter.set(el + step)\n count -= step\n }\n }\n }\n\n def procLevel(ind: Int)= {\n val level = map.get(ind).get\n val next = map.get(ind-1).get\n val step = 10 - ind\n val iter = level.iterator()\n for (el <- iter) {\n if (el < 100 && count >= step) {\n level.remove()\n next.add(el + step)\n count -= step\n } \n }\n }\n }\n}\n"}], "src_uid": "b4341e1b0ec0b7341fdbe6edfe81a0d4"} {"source_code": "object Main{\n def main(args : Array[String]) : Unit = {\n val n = readLine.toInt\n val a = readLine.split(' ').map(_.toInt).sortWith(_ < _)\n if(n == 1){\n println(-1)\n }else if(n == 2){\n val diff = a(1) - a(0)\n if(diff == 0){\n println(1)\n println(a(0))\n }else if(diff % 2 != 0){\n println(2)\n println((a(0) - diff) + \" \" + (a(1) + diff))\n }else{\n println(3)\n println((a(0) - diff) + \" \" + ((a(0) + a(1)) / 2) + \" \"+ (a(1) + diff))\n }\n }else{\n val diff1 = a(1) - a(0)\n val diff2 = a(2) - a(1)\n\n if(diff1 == diff2){\n var bad = 0\n for(i <- 2 until(n - 1)){\n if(diff1 != a(i + 1) - a(i))\n bad += 1\n }\n\n if(diff1 == 0){\n if(bad == 0){\n println(1)\n println(a(0))\n }else{\n println(0)\n }\n }else{\n if(bad == 0){\n println(2)\n println((a(0) - diff1) + \" \" + (a(a.length - 1) + diff1))\n }else if(bad == 1){\n for(i <- 2 until(n - 1)){\n if(diff1 != a(i + 1) - a(i)){\n val diff3 = a(i + 1) - a(i)\n\n if(diff3 == diff1 * 2){\n println(1)\n println((a(i + 1) + a(i)) / 2)\n }else{\n println(0)\n }\n }\n }\n }else{\n println(0)\n }\n }\n }else{\n var ok = true\n if(diff1 * 2 == diff2){\n for(i <- 2 until (n - 1)){\n if(diff1 != a(i + 1) - a(i))\n ok = false;\n }\n\n if(ok){\n println(1)\n println((a(1) + a(2)) / 2)\n }\n }else if(diff1 == diff2 * 2){\n for(i <- 2 until (n - 1)){\n if(diff2 != a(i + 1) - a(i))\n ok = false;\n }\n\n if(ok){\n println(1)\n println((a(0) + a(1)) / 2)\n }\n }else{\n ok = false\n }\n\n if(!ok)\n println(0)\n }\n }\n }\n}\n", "positive_code": [{"source_code": "object Main {\n\n def parseInput: List[Int] = {\n readLine()\n readLine.split(' ').map(_.toInt).toList\n }\n\n def solve(cards: List[Int]): List[Int] = {\n val sortedCards = cards.sorted\n val diffs = sortedCards.init.zip(sortedCards.tail).map((x) => x._2 - x._1)\n if (diffs.isEmpty) {\n null\n } else if (diffs.forall(_ == diffs.head)) {\n val diff = diffs.head\n val suitableCards = List(sortedCards.head - diff, sortedCards.last + diff) ++ {\n if (diffs.length == 1 && diff % 2 == 0) List(sortedCards.head + diff / 2) else Nil\n }\n suitableCards.sorted.distinct\n } else {\n val diff1 = diffs.head\n val index = diffs.indexWhere(_ != diff1)\n val diff2 = diffs(index)\n if (!diffs.forall((x) => x == diff1 || x == diff2)) {\n Nil\n } else if (diff1 * 2 == diff2 && diffs.count(_ == diff2) == 1) {\n List(sortedCards(index) + diff1)\n } else if (diff2 * 2 == diff1 && diffs.count(_ == diff1) == 1) {\n List(sortedCards.head + diff2)\n } else {\n Nil\n }\n }\n }\n\n def main(args: Array[String]) {\n val cards = parseInput\n val result = solve(cards)\n if (result == null) {\n println(-1)\n } else if (result.length == 0) {\n println(0)\n } else {\n println(result.length)\n result.init.foreach((x) => print(x + \" \"))\n println(result.last)\n }\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n\n def parseInput: List[Int] = {\n readLine()\n readLine.split(' ').map(_.toInt).toList\n }\n\n def solve(cards: List[Int]): List[Int] = {\n val sortedCards = cards.sorted\n val diffs = sortedCards.init.zip(sortedCards.tail).map((x) => x._2 - x._1)\n if (diffs.isEmpty) {\n null\n } else if (diffs.forall(_ == diffs.head)) {\n val diff = diffs.head\n val suitableCards = List(sortedCards.head - diff, sortedCards.last + diff) ++ {\n if (diffs.length == 1 && diff % 2 == 0) List(sortedCards.head + diff / 2) else Nil\n }\n suitableCards.toSet.toList\n } else {\n val diff1 = diffs.head\n val index = diffs.indexWhere(_ != diff1)\n val diff2 = diffs(index)\n if (!diffs.forall((x) => x == diff1 || x == diff2)) {\n Nil\n } else if (diff1 * 2 == diff2 && diffs.count(_ == diff2) == 1) {\n List(sortedCards(index) + diff1)\n } else if (diff2 * 2 == diff1 && diffs.count(_ == diff1) == 1) {\n List(sortedCards.head + diff2)\n } else {\n Nil\n }\n }\n }\n\n def main(args: Array[String]) {\n val cards = parseInput\n val result = solve(cards)\n if (result == null) {\n println(-1)\n } else if (result.length == 0) {\n println(0)\n } else {\n println(result.length)\n result.init.foreach((x) => print(x + \" \"))\n println(result.last)\n }\n }\n}\n"}], "src_uid": "e3ca8338beb8852c201be72650e9aabd"} {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject A962 {\n def main(args: Array[String]): Unit = {\n val seqSize = StdIn.readInt()\n\n Console.out.println(if (seqSize == 1) {\n 1\n } else {\n val seq = StdIn.readLine().split(\" \").map(_.toInt).foldLeft(ArrayBuffer(0))((l, i) => l.+=(l.last + i))\n val half = (seq.last + 1) / 2\n seq.takeWhile(_ < half).size\n })\n\n\n }\n}\n\n", "positive_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val r = new Reader\n val n = r.read[Int]\n val xs = r.read[Array[Long]](n)\n val s = (xs.sum + 1) / 2\n val ss = xs.scanLeft(0L) { case (acc, a) => a + acc }.takeWhile(_ < s)\n \n println(ss.length)\n }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n def this() = this(new InputStreamReader(System.in))\n\n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n\n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n implicit val double: Read[Double] = new Read(_.read[String].toDouble)\n\n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n\n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine).takeWhile(_ != null).filter(_ != \"\").map(new StringTokenizer(_)).buffered\n}"}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n val n = readInt\n val arr = readLine.split(\" \").scanLeft(0)(_ + _.toInt)\n val ans = java.util.Arrays.binarySearch(arr, arr.last / 2 + arr.last % 2)\n println(if(ans < 0)-ans - 1 else ans)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject A extends App {\n\n val numbers = {\n StdIn.readLine()\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n val sum = numbers.sum\n val halfOfSum = sum / 2 + sum % 2\n\n var currentSum = 0\n\n val result = numbers.indices\n .takeWhile(index => {\n currentSum += numbers(index)\n currentSum < halfOfSum\n }).lastOption.map(_ + 2).getOrElse(1)\n\n println(result)\n}"}], "negative_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val n = readInt\n val arr = readLine.split(\" \").scanLeft(0)(_ + _.toInt)\n println(java.util.Arrays.binarySearch(arr, arr.last / 2 + arr.last % 2))\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject A962 {\n def main(args: Array[String]): Unit = {\n val seqSize = StdIn.readInt()\n\n Console.out.println(if (seqSize == 1) {\n 1\n } else {\n val seq = StdIn.readLine().split(\" \").map(_.toInt).foldLeft(ArrayBuffer(0))((l, i) => l.+=(l.last + i))\n val half = (seq.last + 1) / 2\n seq.takeWhile(_ <= half).size - 1\n })\n\n\n }\n}\n\n"}], "src_uid": "241157c465fe5dd96acd514010904321"} {"source_code": "object B616 extends App {\n\n import scala.math._\n \n val str = readLine.split(\" \").map(_.toInt)\n val n = str(0)\n val m = str(1)\n var l = List[Int]()\n\n for(i <- 0 until n)\n l ::= readLine.split(\" \").map(_.toInt).min\n\n println(l.max)\n \n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\n/**\n * Created by hsleep on 2016. 1. 12..\n */\nobject BSolution extends App {\n val Array(n, m) = StdIn.readLine().split(' ').map(_.toInt)\n val minCostOfRestaurant = (0 until n).map {_ => StdIn.readLine().split(' ').map(_.toInt).min}\n\n println(minCostOfRestaurant.max)\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n println((1 to n).foldLeft(0) {\n case (acc, _) => Math.max(acc, in.next().split(' ').map(_.toInt).min)\n })\n}"}], "negative_code": [], "src_uid": "f2142bc2f44e5d8b77f8561c29038a73"} {"source_code": "import java.io._\nimport java.nio.file._\nimport java.util.StringTokenizer\n \nimport scala.+:\nimport scala.io.Codec\n \nobject Main {\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)))\n val pw = new PrintWriter(System.out, false)\n \n val t = sc.nextInt()\n var i = 0\n for (i <- 0 to (t-1)) {\n Solver.solve(sc, pw, i)\n }\n pw.flush()\n }\n}\n \n/**\n * Actual solution\n */\nobject Solver {\n def solve(sc: Scanner, pw: PrintWriter, testcast: Int): Unit = {\n val n = sc.nextInt()\n val L = sc.nextLine.split(\" \").map(Integer.parseInt _).toList.sorted.reverse\n L match {\n case 1 :: Nil => pw.println(\"YES\")\n case _ :: Nil => pw.println(\"NO\")\n case a :: b :: _ if (a <= (b + 1)) => pw.println(\"YES\")\n case _ => pw.println(\"NO\")\n }\n }\n}\n \n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n \n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n \n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n \n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\r\n\r\nobject Solution {\r\n\r\n def rsi() = readLine().split(\"\\\\s+\").map(_.toInt)\r\n\r\n def solve(a: Int, b: Array[Int]) = {\r\n val tup = (b.foldLeft(0, 0)(\r\n (acc, elem) => {\r\n val (top, sec ) = acc\r\n if (elem > top) (elem, top)\r\n else if (elem > sec) (top, elem)\r\n else acc\r\n })\r\n\r\n )\r\n if (tup._1 - tup._2 > 1) \"NO\"\r\n else \"YES\"\r\n\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val cases = readLine.toInt\r\n for (\r\n i <- 0 until cases;\r\n c = readLine().toInt;\r\n line = rsi\r\n ) println(solve(c, line))\r\n }\r\n}\r\n\r\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.nio.file._\nimport java.util.StringTokenizer\n \nimport scala.+:\nimport scala.io.Codec\n \nobject Main {\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)))\n val pw = new PrintWriter(System.out, false)\n \n val t = sc.nextInt()\n var i = 0\n for (i <- 0 to (t-1)) {\n Solver.solve(sc, pw, i)\n }\n pw.flush()\n }\n}\n \n/**\n * Actual solution\n */\nobject Solver {\n def solve(sc: Scanner, pw: PrintWriter, testcast: Int): Unit = {\n val n = sc.nextInt()\n val L = sc.nextLine.split(\" \").map(Integer.parseInt _).toList.sorted.reverse\n L match {\n case _ :: Nil => pw.println(\"NO\")\n case a :: b :: _ if (a == (b + 1)) => pw.println(\"YES\")\n case _ => pw.println(\"NO\")\n }\n }\n}\n \n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n \n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n \n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n \n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}"}], "src_uid": "8b926a19f380a56018308668c17c6928"} {"source_code": "object D extends App {\n val t = scala.io.StdIn.readInt()\n\n private def sum(x: Int): Int = (1 << x) - 1\n\n private def days(n: Int): Seq[Int] = {\n val ds = Stream.iterate(1)(_ << 1).takeWhile(_ << 1 < n + 1)\n val d = n + 1 - (1 << ds.length)\n\n val t = (d +: ds).sorted\n\n t.zip(t.tail).map(r => r._2 - r._1)\n }\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n\n val ds = days(n)\n\n println(ds.length)\n println(s\"${ds.mkString(\" \")}\")\n }\n}\n", "positive_code": [{"source_code": "object D extends App {\n val t = scala.io.StdIn.readInt()\n\n private def days(n: Int): Seq[Int] = {\n val ds = Stream.iterate(1)(_ << 1).takeWhile(_ << 1 < n + 1)\n\n val d = n + 1 - (1 << ds.length)\n\n (d +: ds).sorted.sliding(2).flatMap { case Seq(a, b) => Seq(b - a) }.toSeq\n }\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n\n val ds = days(n)\n\n println(ds.length)\n println(s\"${ds.mkString(\" \")}\")\n }\n}\n"}], "negative_code": [{"source_code": "object D extends App {\n val t = scala.io.StdIn.readInt()\n\n private def days(n: Int): Seq[Int] = {\n val ds = Stream.iterate(1)(_ << 1).takeWhile(_ << 1 < n + 1)\n\n val d = n + 1 - (1 << ds.length)\n\n ds.sliding(2)\n .flatMap {\n case Seq(a) => Seq(d - a)\n case Seq(a, b) if d >= a && d <= b => Seq(d - a, b - d)\n case Seq(a, b) => Seq(b - a)\n }\n .toSeq\n }\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n\n val ds = days(n)\n\n println(ds.length)\n println(s\"${ds.mkString(\" \")}\")\n }\n}\n"}, {"source_code": "object D extends App {\n val t = scala.io.StdIn.readInt()\n\n private def days(n: Int): Seq[Int] = {\n val ds = Stream.iterate(1)(_ << 1).takeWhile(_ << 1 < n + 1)\n\n val d = n + 1 - (1 << ds.length)\n\n ds.sorted\n .sliding(2)\n .flatMap {\n case Seq(a) => Seq(d - a)\n case Seq(a, b) if d > a && d <= b => Seq(b - a, b - d)\n case Seq(a, b) => Seq(b - a)\n }\n .toSeq\n }\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n\n val ds = days(n)\n\n println(ds.length)\n println(s\"${ds.mkString(\" \")}\")\n }\n}\n"}], "src_uid": "e21f235ffe7f26d9a7af12a7f3f9a2fd"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 998244353\n val out = new PrintWriter(System.out)\n\n val pow2 = Array.ofDim[Long](3e5.toInt + 10)\n pow2(0) = 1\n REP(pow2.length - 1)(i => pow2(i + 1) = pow2(i) * 2 % MOD)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val n, m = ni()\n val (from, to) = na2(m, -1)\n val g = packUGraph(n, from, to)\n val (d, set, id) = traceBfs(g)\n\n val bipartite = g.indices forall { v =>\n g(v) forall { u =>\n d(v) % 2 != d(u) % 2 // 全エッジの両端の深さの偶奇が異なっている\n }\n }\n\n if (bipartite) {\n var ans = 1L\n\n val even = mutable.Map[Int, Int]().withDefaultValue(0)\n val odd = mutable.Map[Int, Int]().withDefaultValue(0)\n\n REP(n) { i =>\n if (d(i) % 2 == 0) even(id(i)) = even(id(i)) + 1\n else odd(id(i)) = odd(id(i)) + 1\n }\n\n set.foreach { id =>\n val o = odd(id)\n val e = even(id)\n ans = ans * (pow2(o) + pow2(e)) % MOD\n }\n\n out.println(ans)\n } else {\n out.println(0)\n }\n }\n }\n\n /**\n * @param n ノード数\n */\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n REP(m)(i => p(from(i)) += 1)\n REP(m)(i => p(to(i)) += 1)\n REP(n)(i => t(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n /**\n * @return (depth, set, setId)\n */\n def traceBfs(g: Array[Array[Int]]): (Array[Int], ArrayBuffer[Int], Array[Int]) = {\n val n = g.length\n val INF = 1e9.toInt + 10\n val q, p = Array.ofDim[Int](n)\n val d = Array.fill[Int](n)(INF)\n var cur = 0\n var last = 0\n\n val set = ArrayBuffer[Int]()\n val setId = Array.ofDim[Int](n)\n\n REP(n) { rt =>\n if (d(rt) == INF) {\n set += rt\n q(last) = rt\n last += 1\n d(rt) = 0\n setId(rt) = rt\n while (cur < last) {\n val v = q(cur)\n REP(g(v).length) { i =>\n val u = g(v)(i)\n if (d(u) == INF) {\n d(u) = d(v) + 1\n setId(u) = rt\n p(u) = v\n q(last) = u\n last += 1\n }\n }\n cur += 1\n }\n }\n }\n (d, set, setId)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(t) = readInts(1)\n val res = Array.fill(t)(0L)\n val MOD = 998244353L\n\n for (test <- 0 until t) {\n val Array(n, m) = readInts(2)\n val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n for (_ <- 1 to m) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n val adjs = adjBuilders.map(_.result())\n val depths = Array.fill(n)( -1 )\n val visit = Array.fill(n)(0)\n var bad = false\n\n def dfs(u: Int, depth: Int): Int = {\n depths(u) = depth\n var i = 0\n var subSize = 1\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n subSize += dfs(v, depth + 1)\n } else {\n if (Math.abs(depth - depths(v)) % 2 == 0) bad = true\n }\n i += 1\n }\n subSize\n }\n\n def dfs1(u: Int, vis: Int, even: Boolean): Long = {\n visit(u) = vis\n var i = 0\n var subCount = 1L\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (visit(v) != vis) {\n subCount = subCount * dfs1(v, vis, !even) % MOD\n }\n i += 1\n }\n if (even) 2 * subCount else subCount\n }\n\n var u = 0\n while (u < n) {\n if (depths(u) == -1) {\n dfs(u, 0)\n }\n u += 1\n }\n if (!bad) {\n var u = 0\n var count = 1L\n while (u < n) {\n if (visit(u) == 0) {\n val c1 = dfs1(u, 1, true)\n val c2 = dfs1(u, 2, false)\n count = count * (c1 + c2) % MOD\n }\n u += 1\n }\n res(test) = count\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.mkString(\"\\n\"))\n Console.flush\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 998244353\n val out = new PrintWriter(System.out)\n\n val pow2 = Array.ofDim[Long](3e5.toInt + 10)\n pow2(0) = 1\n REP(pow2.length - 1)(i => pow2(i + 1) = pow2(i) * 2 % MOD)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val n, m = ni()\n val (from, to) = na2(m, -1)\n val g = packUGraph(n, from, to)\n val (d, set, id) = traceBfs(g)\n\n val bipartite = g.indices forall { v =>\n g(v) forall { u =>\n d(v) % 2 != d(u) % 2 // 全エッジの両端の深さの偶奇が異なっている\n }\n }\n\n if (bipartite) {\n var ans = 1L\n\n val even = mutable.Map[Int, Int]().withDefaultValue(0)\n val odd = mutable.Map[Int, Int]().withDefaultValue(0)\n\n REP(n) { i =>\n if (d(i) % 2 == 0) even(id(i)) = even(id(i)) + 1\n else odd(id(i)) = odd(id(i)) + 1\n }\n\n var valid = true\n set.foreach { id =>\n val o = odd(id)\n val e = even(id)\n if (o + e > 1) ans = ans * (pow2(o) + pow2(e)) % MOD\n }\n\n out.println(ans)\n } else {\n out.println(0)\n }\n }\n }\n\n /**\n * @param n ノード数\n */\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n REP(m)(i => p(from(i)) += 1)\n REP(m)(i => p(to(i)) += 1)\n REP(n)(i => t(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n /**\n * @return (depth, set, setId)\n */\n def traceBfs(g: Array[Array[Int]]): (Array[Int], ArrayBuffer[Int], Array[Int]) = {\n val n = g.length\n val INF = 1e9.toInt + 10\n val q, p = Array.ofDim[Int](n)\n val d = Array.fill[Int](n)(INF)\n var cur = 0\n var last = 0\n\n val set = ArrayBuffer[Int]()\n val setId = Array.ofDim[Int](n)\n\n REP(n) { rt =>\n if (d(rt) == INF) {\n set += rt\n q(last) = rt\n last += 1\n d(rt) = 0\n setId(rt) = rt\n while (cur < last) {\n val v = q(cur)\n REP(g(v).length) { i =>\n val u = g(v)(i)\n if (d(u) == INF) {\n d(u) = d(v) + 1\n setId(u) = rt\n p(u) = v\n q(last) = u\n last += 1\n }\n }\n cur += 1\n }\n }\n }\n (d, set, setId)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 998244353\n val out = new PrintWriter(System.out)\n\n val pow2 = Array.ofDim[Long](3e5.toInt + 10)\n pow2(0) = 1\n REP(pow2.length - 1)(i => pow2(i + 1) = pow2(i) * 2 % MOD)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val n, m = ni()\n val (from, to) = na2(m, -1)\n val g = packUGraph(n, from, to)\n val (d, set, id) = traceBfs(g)\n\n val bipartite = g.indices forall { v =>\n g(v) forall { u =>\n d(v) % 2 != d(u) % 2 // 全エッジの両端の深さの偶奇が異なっている\n }\n }\n\n if (bipartite) {\n var ans = 1L\n\n val even = mutable.Map[Int, Int]().withDefaultValue(0)\n val odd = mutable.Map[Int, Int]().withDefaultValue(0)\n\n REP(n) { i =>\n if (d(i) % 2 == 0) even(id(i)) = even(id(i)) + 1\n else odd(id(i)) = odd(id(i)) + 1\n }\n\n var valid = true\n set.foreach { id =>\n val o = odd(id)\n val e = even(id)\n if (o == 0 || e == 0) valid = false\n else ans = ans * (pow2(o) + pow2(e)) % MOD\n }\n\n if (valid) out.println(ans) else out.println(0)\n } else {\n out.println(0)\n }\n }\n }\n\n /**\n * @param n ノード数\n */\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n REP(m)(i => p(from(i)) += 1)\n REP(m)(i => p(to(i)) += 1)\n REP(n)(i => t(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n /**\n * @return (depth, set, setId)\n */\n def traceBfs(g: Array[Array[Int]]): (Array[Int], ArrayBuffer[Int], Array[Int]) = {\n val n = g.length\n val INF = 1e9.toInt + 10\n val q, p = Array.ofDim[Int](n)\n val d = Array.fill[Int](n)(INF)\n var cur = 0\n var last = 0\n\n val set = ArrayBuffer[Int]()\n val setId = Array.ofDim[Int](n)\n\n REP(n) { rt =>\n if (d(rt) == INF) {\n set += rt\n q(last) = rt\n last += 1\n d(rt) = 0\n setId(rt) = rt\n while (cur < last) {\n val v = q(cur)\n REP(g(v).length) { i =>\n val u = g(v)(i)\n if (d(u) == INF) {\n d(u) = d(v) + 1\n setId(u) = rt\n p(u) = v\n q(last) = u\n last += 1\n }\n }\n cur += 1\n }\n }\n }\n (d, set, setId)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 998244353\n val out = new PrintWriter(System.out)\n\n val pow2 = Array.ofDim[Long](3e5.toInt + 10)\n pow2(0) = 1\n REP(pow2.length - 1)(i => pow2(i + 1) = pow2(i) * 2 % MOD)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val n, m = ni()\n val (from, to) = na2(m, -1)\n val g = packUGraph(n, from, to)\n val (d, _, _) = traceBfs(g)\n\n val bipartite = g.indices forall { v =>\n g(v) forall { u =>\n d(v) % 2 != d(u) % 2 // 全エッジの両端の深さの偶奇が異なっている\n }\n }\n\n if (bipartite && m > 0) {\n var even = 0\n var odd = 0\n REP(n) { i =>\n if (d(i) % 2 == 0) even += 1\n else odd += 1\n }\n val ans = (pow2(odd) + pow2(even)) % MOD\n out.println(ans)\n } else {\n out.println(0)\n }\n }\n }\n\n /**\n * @param n ノード数\n */\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n REP(m)(i => p(from(i)) += 1)\n REP(m)(i => p(to(i)) += 1)\n REP(n)(i => t(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n /**\n * @return (depth, parent, queue)\n */\n def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {\n val n = g.length\n val INF = 1e9.toInt + 10\n val q, p = Array.ofDim[Int](n)\n q(0) = rt\n p(rt) = -1\n val d = Array.fill[Int](n)(INF)\n d(rt) = 0\n var cur = 0\n var last = 1\n while (cur < last) {\n val v = q(cur)\n REP(g(v).length) { i =>\n val u = g(v)(i)\n if (d(u) == INF) {\n d(u) = d(v) + 1\n p(u) = v\n q(last) = u\n last += 1\n }\n }\n cur += 1\n }\n (d, p, q)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 998244353\n val out = new PrintWriter(System.out)\n\n val pow2 = Array.ofDim[Long](3e5.toInt + 10)\n pow2(0) = 1\n REP(pow2.length - 1)(i => pow2(i + 1) = pow2(i) * 2 % MOD)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val n, m = ni()\n val (from, to) = na2(m, -1)\n val g = packUGraph(n, from, to)\n val (d, _, _) = traceBfs(g)\n\n val bipartite = g.indices forall { v =>\n g(v) forall { u =>\n d(v) % 2 != d(u) % 2 // 全エッジの両端の深さの偶奇が異なっている\n }\n }\n\n if (bipartite) {\n var even = 0\n var odd = 0\n REP(n) { i =>\n if (d(i) % 2 == 0) even += 1\n else odd += 1\n }\n val ans = (pow2(odd) + pow2(even)) % MOD\n out.println(ans)\n } else {\n out.println(0)\n }\n }\n }\n\n /**\n * @param n ノード数\n */\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n REP(m)(i => p(from(i)) += 1)\n REP(m)(i => p(to(i)) += 1)\n REP(n)(i => t(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n /**\n * @return (depth, parent, queue)\n */\n def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {\n val n = g.length\n val INF = 1e9.toInt + 10\n val q, p = Array.ofDim[Int](n)\n q(0) = rt\n p(rt) = -1\n val d = Array.fill[Int](n)(INF)\n d(rt) = 0\n var cur = 0\n var last = 1\n while (cur < last) {\n val v = q(cur)\n REP(g(v).length) { i =>\n val u = g(v)(i)\n if (d(u) == INF) {\n d(u) = d(v) + 1\n p(u) = v\n q(last) = u\n last += 1\n }\n }\n cur += 1\n }\n (d, p, q)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(t) = readInts(1)\n val res = Array.fill(t)(0L)\n val MOD = 998244353L\n\n for (test <- 0 until t) {\n val Array(n, m) = readInts(2)\n val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n for (_ <- 1 to m) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n val adjs = adjBuilders.map(_.result())\n val depths = Array.fill(n)( -1 )\n var bad = false\n\n def dfs(u: Int, depth: Int): Int = {\n depths(u) = depth\n var i = 0\n var subSize = 1\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n subSize += dfs(v, depth + 1)\n } else {\n if (Math.abs(depth - depths(v)) % 2 == 0) bad = true\n }\n i += 1\n }\n subSize\n }\n\n var u = 0\n var count = 1L\n while (u < n) {\n if (depths(u) == -1) {\n val compSize = dfs(u, 0)\n val compCount = if (compSize == 1) 3 else 2 * compSize\n count = count * compCount % MOD\n }\n u += 1\n }\n if (!bad) res(test) = count\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.mkString(\"\\n\"))\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(t) = readInts(1)\n val res = Array.fill(t)(0L)\n val MOD = 998244353L\n\n for (test <- 0 until t) {\n val Array(n, m) = readInts(2)\n val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n for (_ <- 1 to m) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n val adjs = adjBuilders.map(_.result())\n val depths = Array.fill(n)( -1 )\n var bad = false\n\n def dfs(u: Int, depth: Int): Int = {\n depths(u) = depth\n var i = 0\n var subSize = 1\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n subSize += dfs(v, depth + 1)\n } else {\n if (Math.abs(depth - depths(v)) % 2 == 0) bad = true\n }\n i += 1\n }\n subSize\n }\n\n var u = 0\n var count = 1L\n while (u < n) {\n if (depths(u) == -1) {\n val compSize = dfs(u, 0)\n val pow = BigInt(2).modPow(compSize / 2, MOD).toLong\n val compCount = if (compSize % 2 == 1) 3 * pow else 2 * pow\n count = count * compCount % MOD\n }\n u += 1\n }\n if (!bad) res(test) = count\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.mkString(\"\\n\"))\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(t) = readInts(1)\n val res = Array.fill(t)(0L)\n val MOD = 998244353L\n\n for (test <- 1 to t) {\n val Array(n, m) = readInts(2)\n val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n for (_ <- 1 to m) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n val adjs = adjBuilders.map(_.result())\n val depths = Array.fill(n)( -1 )\n var bad = false\n\n def dfs(u: Int, depth: Int): Int = {\n depths(u) = depth\n var i = 0\n var subSize = 1\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n subSize += dfs(v, depth + 1)\n } else {\n if (Math.abs(depth - depths(v)) % 2 == 0) bad = true\n }\n i += 1\n }\n subSize\n }\n\n var u = 0\n var count = 1L\n while (u < n) {\n if (depths(u) == -1) {\n val compSize = dfs(u, 0)\n val compCount = if (compSize == 1) 3 else 2 * compSize\n count = count * compCount % MOD\n }\n u += 1\n }\n if (!bad) res(test) = count\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.mkString(\"\\n\"))\n Console.flush\n}\n"}], "src_uid": "332340a793eb3ec14131948e2b6bdf2f"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n rep(ni()) { _ =>\n val a, b, k = nl()\n val ans = if ((k - 1) % 2 == 0) {\n (a - b) * (k / 2) + a\n } else {\n (a - b) * (k / 2)\n }\n out.println(ans)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject A extends App {\n\tval t = StdIn.readInt\n\n\tfor(i <- 1 to t) {\n\t\tval line = StdIn.readLine.split(\" \").map(_.toInt)\n\t\t\n\t\tval a: Long = line(0)\n\t\tval b: Long = line(1)\n\t\tval k: Long = line(2)\n\n\t\tvar ans = (a - b) * (k / 2)\n\n\t\tif(k % 2 == 1)\n\t\t\tans += a\n\n\t\tprintln(f\"$ans\")\n\t}\n}"}, {"source_code": "object CF_521_3_A {\n\n def solve(ss: Seq[(Int, Int, Int)]): String = {\n val sols = for {\n (a,b,k) <- ss\n dist = (a - b).toLong * (k/2)\n } yield if (k%2 == 0) dist else dist + a\n sols.mkString(\"\\n\")\n }\n\n def solution(i: Input) = {\n val n = i.int\n val lines = 1 to n map {_ => {i.nextLine; (i.int, i.int, i.int)}}\n solve(lines)\n }\n\n \n// ~~~ Boilerplate ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n def main(args: Array[String]) = {\n val out = new java.io.PrintWriter(System.out)\n val sol = solution(new Input(System.in))\n out.println(sol)\n out.close()\n }\n\n// ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n import java.util.Scanner\n class Input(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine() \n // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n }\n\n def ceil(a: Int, b: Int) = (a - 1) / b + 1\n def ceil(a: Long, b: Long) = (a - 1) / b + 1\n\n import language.implicitConversions\n implicit def stringToInput(s: String): Input = new Input(s)\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val n: Int = StdIn.readLine().toInt\n for(i <- 1 to n) {\n val s = StdIn.readLine().split(\" \").map(_.toInt)\n println(solve(s(0), s(1), s(2)))\n }\n }\n\n def solve(a: BigInt, b: BigInt, k: BigInt): BigInt = {\n k % 2 == 0 match {\n case true => (a - b) * (k/2)\n case false => (a - b) * (k/2) + a\n }\n }\n}"}, {"source_code": "object A extends App{\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n\n def nextInput = {\n (for (i <- 0 until 3) yield nextLong).toArray\n }\n\n def solve = {\n val n = nextInt\n for (i <- 0 until n) {\n var input = nextInput\n val odd = input(2) / 2\n val even = if(input(2) % 2 == 0) input(2) / 2 else input(2) / 2 + 1\n val ans = even * input(0) - odd * input(1)\n println(ans)\n }\n }\n\n solve\n}"}], "negative_code": [], "src_uid": "1f435ba837f59b007167419896c836ae"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n var k = in.next().toInt\n val str = in.next().map(_.asDigit)\n\n if (k == 0) {\n val (sum, soFar) = str.foldLeft(0l, 0l) {\n case ((sum, soFar), 0) => (sum, soFar + 1)\n case (acc@(sum, 0), 1) => acc\n case ((sum, soFar), 1) => (sum + soFar * (soFar + 1) / 2, 0)\n }\n if (soFar == 0)\n println(sum)\n else\n println(sum + soFar * (soFar + 1) / 2)\n }\n else {\n val answer = Array.ofDim[Int](str.sum + 1)\n\n str.scanLeft(0) {\n _ + _\n }.tail.foreach {\n i => answer(i) += 1\n }\n\n answer(0) += 1\n println(answer.indices.foldLeft(0l) {\n case(acc, i) => acc + (if ((i + k) > answer.length - 1) 0 else answer(i).toLong * answer(i + k))\n })\n }\n\n}", "positive_code": [{"source_code": "object C165 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(k) = readInts(1)\n val str = read\n val sum = Array.fill(str.length+1)(0)\n val cntSum = Array.fill(str.length+10)(0L)\n sum(0) = 0\n cntSum(0) += 1\n for(i <- 0 until str.length) {\n sum(i+1) = sum(i) + str(i)-'0'\n cntSum(sum(i+1)) += 1\n }\n\n var res = 0L\n for(i <- cntSum.indices if i+k < cntSum.length)\n if(k == 0)\n res += cntSum(i)*(cntSum(i)-1)/2\n else\n res += cntSum(i)*cntSum(i+k)\n out.println(res)\n\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val k = in.next().toInt\n val str = in.next().map(_.asDigit)\n val answer = Array.ofDim[Int](str.sum + 1)\n\n str.scanLeft(0){_+_}.tail.foreach {\n i => answer(i) += 1\n }\n answer(0) += 1\n println(answer.indices.map{\n i => if ((i + k) > answer.length - 1) 0 else answer(i) * answer(i + k)\n }.sum)\n\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n var k = in.next().toInt\n val str = in.next().map(_.asDigit)\n\n if (k == 0) {\n val (sum, soFar) = str.foldLeft(0l, 0l) {\n case ((sum, soFar), 0) => (sum, soFar + 1)\n case (acc@(sum, 0), 1) => acc\n case ((sum, soFar), 1) => (sum + soFar * (soFar + 1) / 2, 0)\n }\n if (soFar == 0)\n println(sum)\n else\n println(sum + soFar * (soFar + 1) / 2)\n }\n else {\n val answer = Array.ofDim[Int](str.sum + 1)\n\n str.scanLeft(0) {\n _ + _\n }.tail.foreach {\n i => answer(i) += 1\n }\n\n answer(0) += 1\n println(answer.indices.map {\n i => if ((i + k) > answer.length - 1) 0 else answer(i) * answer(i + k)\n }.sum)\n }\n\n}"}, {"source_code": "object C165 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(k) = readInts(1)\n val str = read\n val sum = Array.fill(str.length+1)(0)\n val cntSum = cu.Map.empty[Int, Int].withDefaultValue(0)\n sum(0) = 0\n cntSum(0) += 1\n for(i <- 0 until str.length) {\n sum(i+1) = sum(i) + str(i)-'0'\n cntSum(sum(i+1)) += 1\n }\n var res = 0L\n for(i <- 0 until 1000000)\n if(k == 0)\n res += cntSum(i)*(cntSum(i)-1)/2\n else\n res += cntSum(i)*cntSum(i+k)\n println(res)\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object C165 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(k) = readInts(1)\n val str = read\n val sum = Array.fill(str.length+1)(0)\n val cntSum = cu.Map.empty[Int, Int].withDefaultValue(0)\n sum(0) = 0\n cntSum(0) += 1\n for(i <- 0 until str.length) {\n sum(i+1) = sum(i) + str(i)-'0'\n cntSum(sum(i+1)) += 1\n }\n var res = 0L\n for(i <- 0 until 1000000)\n res += cntSum(i)*cntSum(i+k)\n println(res)\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n var k = in.next().toInt\n val str = in.next().map(_.asDigit)\n\n def factorial(i: Int): Long = {\n (2 to i).foldLeft(1l) {\n case(acc, i) => acc * i\n }\n }\n\n if (k == 0) {\n val (sum, soFar) = str.foldLeft(0l, 0) {\n case ((sum, soFar), 0) => (sum, soFar + 1)\n case (acc@(sum, 0), 1) => acc\n case ((sum, soFar), 1) => (sum + factorial(soFar), 0)\n }\n if (soFar == 0)\n println(sum)\n else\n println(sum + factorial(soFar))\n }\n else {\n val answer = Array.ofDim[Int](str.sum + 1)\n\n str.scanLeft(0) {\n _ + _\n }.tail.foreach {\n i => answer(i) += 1\n }\n\n answer(0) += 1\n println(answer.indices.map {\n i => if ((i + k) > answer.length - 1) 0 else answer(i) * answer(i + k)\n }.sum)\n }\n\n}"}], "src_uid": "adc43f273dd9b3f1c58b052a34732a50"} {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n\n def gcd(a: Int, b: Int): Int = if (b == 0) a.abs else gcd(b, a % b)\n\n val n = readInt()\n val A = readLine().split(\" \").map(_.toInt).sortWith(_ < _)\n\n val S = new collection.mutable.Stack[Int]\n\n for (x <- A) {\n S.push(x)\n }\n\n val Counter = collection.mutable.Map(A.groupBy(identity).map(t => (t._1, t._2.length)).toSeq: _*)\n val GCD = Array.ofDim[Int](n, n)\n\n val answer = new scala.collection.mutable.ArrayBuffer[Int]\n var size = 0\n while (!S.isEmpty) {\n val curr = S.pop()\n if (Counter(curr) > 0) {\n GCD(answer.length)(answer.length) = curr\n Counter(curr) -= 1\n val j = size\n for {\n i <- 0 until size\n if i != j\n } {\n val a = GCD(i)(i)\n val b = GCD(j)(j)\n GCD(i)(j) = gcd(a, b)\n Counter(GCD(i)(j)) -= 2\n GCD(j)(i) = GCD(i)(j)\n }\n\n answer += curr\n size += 1\n }\n }\n\n println(answer.mkString(\" \"))\n\n}\n", "positive_code": [{"source_code": "import scala.collection.immutable.TreeMap\nimport scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n var queue = TreeMap.empty[Int, Int]\n val data = in.next().split(' ').map(_.toInt).foreach{\n i => queue += (i -> (queue.getOrElse(i, 0) + 1))\n }\n\n def remove(map: TreeMap[Int, Int], number: Int) = {\n val quantity = map(number)\n if (quantity == 1)\n map - number\n else\n map + (number -> (quantity - 1))\n }\n\n def gcd(a: Int, b: Int): Int = if (b ==0) a else gcd(b, a%b)\n\n var result = List.empty[Int]\n while (queue.nonEmpty) {\n val (value, _) = queue.last\n queue = remove(queue, value)\n result.foreach{\n i =>\n val gc = gcd(value, i)\n queue = remove(queue, gc)\n queue = remove(queue, gc)\n }\n result ::= value\n }\n println(result.mkString(\" \"))\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)\n\n val Array(n) = readInts(1)\n val gs = readInts(n * n).sorted.reverse\n val as = Array.ofDim[Int](n)\n \n val cnts = mutable.Map.empty[Int, Int]\n for (g <- gs) {\n if (cnts.contains(g)) cnts(g) = cnts(g) + 1\n else cnts(g) = 1\n }\n \n var i = 0\n for (g <- gs) {\n if (cnts(g) > 0) {\n as(i) = g\n for (j <- 0 to i) {\n val a = as(j)\n val gg = gcd(a, g)\n assert(cnts(gg) > 0)\n cnts(gg) = cnts(gg) - (if (j == i) 1 else 2)\n }\n i += 1\n }\n }\n\n println(as.mkString(\" \"))\n}\n"}], "negative_code": [], "src_uid": "71dc07f0ea8962f23457af1d6509aeee"} {"source_code": "object HelloWorld {\r\n\r\n def main(args: Array[String]): Unit = {\r\n val tests = scala.io.StdIn.readInt()\r\n for (t <- 1 to tests) {\r\n scala.io.StdIn.readLine()\r\n val array = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\r\n\r\n if (array.distinct.size == array.size) println(\"YES\") else println(\"NO\")\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object Increasing {\r\n\r\n def solve_test() = {\r\n val _ = scala.io.StdIn.readInt()\r\n val a = scala.io.StdIn.readLine().split(' ').map(_.toInt).sorted.toList\r\n def exists_same_elements(xs: List[Int]): Boolean = {\r\n xs match {\r\n case Nil => return false\r\n case x :: Nil => return false\r\n case x :: y :: lst => \r\n if (x == y)\r\n return true\r\n else\r\n exists_same_elements(y :: lst)\r\n }\r\n }\r\n if (exists_same_elements(a))\r\n println(\"NO\")\r\n else\r\n println(\"YES\")\r\n }\r\n\r\n def main (args: Array[String]): Unit = {\r\n val test = scala.io.StdIn.readInt()\r\n for (i <- 0 until test) solve_test()\r\n }\r\n}"}], "negative_code": [], "src_uid": "288f147bb8a3c30b0bb712a01c65109b"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val result = Array.ofDim[Int](n)\n val data = (1 to m).foreach { _ =>\n val Array(a, b, c) = in.next().split(' ').map(_.toInt - 1)\n if (result(a) != 0) {\n result(b) = result(a) % 3 + 1\n result(c) = (result(a) + 1) % 3 + 1\n } else if (result(b) != 0) {\n result(a) = result(b) % 3 + 1\n result(c) = (result(b) + 1) % 3 + 1\n } else if (result(c) != 0) {\n result(a) = result(c) % 3 + 1\n result(b) = (result(c) + 1) % 3 + 1\n } else {\n result(a) = 1\n result(b) = 2\n result(c) = 3\n }\n }\n println(result.mkString(\" \"))\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, m) = readInts(2)\n \n val color = Array.fill(n)(0)\n \n for (i <- 0 until m) {\n val dancers = readInts(3).map(_ - 1)\n val danced = dancers.indexWhere(color(_) > 0)\n if (danced < 0) {\n for (d <- 0 to 2) color(dancers(d)) = d + 1\n } else {\n var c = color(dancers(danced))\n for (d <- 0 to 2) {\n if (d != danced) {\n c = if (c == 3) 1 else c + 1\n color(dancers(d)) = c\n }\n }\n }\n }\n \n println(color.mkString(\" \"))\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val data = (1 to m).foldLeft(Map.empty[Int, List[(Int, Int)]]){\n case (map, _) => val Array(a, b, c) = in.next().split(' ').map(_.toInt)\n map + (a -> ((b, c) :: map.getOrElse(a, Nil))) +\n (b -> ((a, c) :: map.getOrElse(b, Nil))) +\n (c -> ((a, b) :: map.getOrElse(c, Nil)))\n }\n val result = Array.ofDim[Int](n)\n data.foreach {\n case (k, list) if result(k - 1) == 0 =>\n result(k - 1) = 1\n list.foreach{\n case(first, second) =>\n result(first - 1) = 2\n result(second - 1) = 3\n }\n case (k, list) =>\n }\n println(result.mkString(\" \"))\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val data = (1 to m).foldLeft(Map.empty[Int, List[(Int, Int)]]){\n case (map, _) => val Array(a, b, c) = in.next().split(' ').map(_.toInt)\n map + (a -> ((b, c) :: map.getOrElse(a, Nil))) +\n (b -> ((a, c) :: map.getOrElse(b, Nil))) +\n (c -> ((a, b) :: map.getOrElse(c, Nil)))\n }\n val result = Array.ofDim[Int](n)\n// data.foreach(println)\n data.foreach {\n case (k, list) if result(k - 1) == 0 =>\n// println(result.mkString(\" \"))\n result(k - 1) = 1\n list.foreach {\n case(first, second) if result(first - 1) == 3 || result(second - 1) == 2 =>\n result(second - 1) = 2\n result(first - 1) = 3\n case(first, second) =>\n result(first - 1) = 2\n result(second - 1) = 3\n }\n case (k, list) =>\n }\n println(result.mkString(\" \"))\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val data = (1 to m).foldLeft(Map.empty[Int, List[(Int, Int)]]){\n case (map, _) => val Array(a, b, c) = in.next().split(' ').map(_.toInt)\n map + (a -> ((b, c) :: map.getOrElse(a, Nil))) +\n (b -> ((a, c) :: map.getOrElse(b, Nil))) +\n (c -> ((a, b) :: map.getOrElse(c, Nil)))\n }\n val result = Array.ofDim[Int](n)\n// data.foreach(println)\n data.foreach {\n case (k, list) if result(k - 1) == 0 =>\n result(k - 1) = 1\n list.foreach {\n case(first, second) if result(first - 1) == 2 =>\n result(second - 1) = 3\n case(first, second) =>\n result(first - 1) = 3\n result(second - 1) = 2\n }\n case (k, list) =>\n }\n println(result.mkString(\" \"))\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val data = (1 to m).foldLeft(Map.empty[Int, List[(Int, Int)]]){\n case (map, _) => val Array(a, b, c) = in.next().split(' ').map(_.toInt)\n map + (a -> ((b, c) :: map.getOrElse(a, Nil))) +\n (b -> ((a, c) :: map.getOrElse(b, Nil))) +\n (c -> ((a, b) :: map.getOrElse(c, Nil)))\n }\n val result = Array.ofDim[Int](n)\n// data.foreach(println)\n data.foreach {\n case (k, list) if result(k - 1) == 0 =>\n println(result.mkString(\" \"))\n result(k - 1) = 1\n list.foreach {\n case(first, second) if result(first - 1) == 3 || result(second - 1) == 2 =>\n result(second - 1) = 2\n result(first - 1) = 3\n case(first, second) =>\n result(first - 1) = 2\n result(second - 1) = 3\n }\n case (k, list) =>\n }\n println(result.mkString(\" \"))\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val data = (1 to m).foldLeft(Map.empty[Int, List[(Int, Int)]]){\n case (map, _) => val Array(a, b, c) = in.next().split(' ').map(_.toInt)\n map + (a -> ((b, c) :: map.getOrElse(a, Nil))) +\n (b -> ((a, c) :: map.getOrElse(b, Nil))) +\n (c -> ((a, b) :: map.getOrElse(c, Nil)))\n }\n val result = Array.ofDim[Int](n)\n data.foreach {\n case (k, list) if result(k - 1) == 0 =>\n result(k - 1) = 1\n list.foreach {\n case(first, second) if result(first - 1) == 2 =>\n result(first - 1) = 3\n result(second - 1) = 2\n case(first, second) =>\n result(first - 1) = 2\n result(second - 1) = 3\n }\n case (k, list) =>\n }\n println(result.mkString(\" \"))\n}"}], "src_uid": "ee523bb4da5cb794e05fb62b7da8bb89"} {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\n def modInverse(a: Long, m: Long): Long = {\n\n def modInv(a: Long, m: Long, x: Long, y: Long): Long =\n if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))\n\n val inv = modInv(a, m, 1, 0)\n if (inv < 0) inv + m else inv\n }\n\n val _n, _m, k = nextLong\n val _as = nextInts(_n.toInt)\n val _bs = nextInts(_m.toInt)\n\n val n = _n max _m\n val m = _n min _m\n val as = if (_n < _m) _bs else _as\n val bs = if (_n < _m) _as else _bs\n val g = gcd(n, m)\n val l = lcm(n, m)\n val ng = n / g\n val mg = m / g\n\n val mInv = modInverse(mg, ng)\n\n val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)\n var i = 0\n while (i < bs.length) {\n dayByD(bs(i)) = i\n i += 1\n }\n\n val xs = Array.ofDim[Long](n.toInt)\n\n var aDay = 0\n while (aDay < as.length) {\n val a = as(aDay)\n val bDay = dayByD(a)\n\n if (aDay % g == bDay % g) {\n val x0 = (bDay / g + mg * ((aDay / g - bDay / g + l) * mInv % ng)) % l\n xs(aDay) = (x0 * g + aDay % g) % l\n } else dayByD(a) = -1\n\n aDay += 1\n }\n\n def countDiff(time: Long): Long = {\n var same = 0L\n val timeDivL = time / l\n val timeModL = time % l\n var aDay = 0\n\n while (aDay < n) {\n\n if (dayByD(as(aDay)) != -1) {\n same += timeDivL\n if (xs(aDay) < timeModL) same += 1\n }\n\n aDay += 1\n }\n time - same\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (countDiff(mid) >= k) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = binSearch(0, k * (n + m) + 1)\n\n out.println(res)\n\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\n def modInverse(a: Long, m: Long): Long = {\n\n def modInv(a: Long, m: Long, x: Long, y: Long): Long =\n if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))\n\n val inv = modInv(a, m, 1, 0)\n if (inv < 0) inv + m else inv\n }\n\n val _n, _m, k = nextLong\n val _as = nextInts(_n.toInt)\n val _bs = nextInts(_m.toInt)\n\n val n = _n max _m\n val m = _n min _m\n val as = if (_n < _m) _bs else _as\n val bs = if (_n < _m) _as else _bs\n val g = gcd(n, m)\n val l = lcm(n, m)\n val ng = n / g\n val mg = m / g\n\n val mInv = modInverse(mg, ng)\n\n val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)\n var i = 0\n while (i < bs.length) {\n dayByD(bs(i)) = i\n i += 1\n }\n\n val xs = Array.ofDim[Long](n.toInt)\n\n var aDay = 0\n while (aDay < as.length) {\n val a = as(aDay)\n val bDay = dayByD(a)\n\n if (aDay % g == bDay % g) {\n val x0 = (bDay / g + mg * ((aDay / g - bDay / g + l) * mInv % ng)) % l\n xs(aDay) = (x0 * g + aDay % g) % l\n } else dayByD(a) = -1\n\n aDay += 1\n }\n\n def countDiff(time: Long): Long = {\n var same = 0L\n val timeDivL = time / l\n val timeModL = time % l\n var aDay = 0\n\n while (aDay < n) {\n\n val bDay = dayByD(as(aDay))\n\n if (bDay != -1) {\n// if (g > 1) {\n// if (aDay % g == bDay % g) {\n same += timeDivL\n// val x0 = (bDay + mg * ((aDay / g - bDay + l) * mInv % ng)) % l\n// val x = (x0 * g + aDay % g) % l\n if (xs(aDay) < timeModL) same += 1\n// }\n// } else {\n// same += timeDivL\n// val x = (bDay + mg * ((aDay - bDay + l) * mInv % ng)) % l\n// if (x < timeModL) same += 1\n// }\n }\n\n aDay += 1\n }\n time - same\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (countDiff(mid) >= k) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = binSearch(0, k * (n + m) + 1)\n\n out.println(res)\n\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\n def modInverse(a: Long, m: Long): Long = {\n\n def modInv(a: Long, m: Long, x: Long, y: Long): Long =\n if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))\n\n val inv = modInv(a, m, 1, 0)\n if (inv < 0) inv + m else inv\n }\n\n val _n, _m, k = nextLong\n val _as = nextInts(_n.toInt)\n val _bs = nextInts(_m.toInt)\n\n val n = _n max _m\n val m = _n min _m\n val as = if (_n < _m) _bs else _as\n val bs = if (_n < _m) _as else _bs\n val g = gcd(n, m)\n val l = lcm(n, m)\n val ng = n / g\n val mg = m / g\n\n val mInv = modInverse(mg, ng)\n\n val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)\n var i = 0\n while (i < bs.length) {\n dayByD(bs(i)) = i\n i += 1\n }\n\n val xs = Array.ofDim[Long](n.toInt)\n\n var aDay = 0\n while (aDay < as.length) {\n val a = as(aDay)\n val bDay = dayByD(a)\n// if (aDay % g == bDay % g) {\n// dayByD(a) /= g\n// } else dayByD(a) = -1\n\n val x0 = (bDay / g + mg * ((aDay / g - bDay / g + l) * mInv % ng)) % l\n xs(aDay) = (x0 * g + aDay % g) % l\n\n aDay += 1\n }\n\n def countDiff(time: Long): Long = {\n var same = 0L\n val timeDivL = time / l\n val timeModL = time % l\n var aDay = 0\n\n while (aDay < n) {\n\n val bDay = dayByD(as(aDay))\n\n if (bDay != -1) {\n// if (g > 1) {\n// if (aDay % g == bDay % g) {\n same += timeDivL\n// val x0 = (bDay + mg * ((aDay / g - bDay + l) * mInv % ng)) % l\n// val x = (x0 * g + aDay % g) % l\n if (xs(aDay) < timeModL) same += 1\n// }\n// } else {\n// same += timeDivL\n// val x = (bDay + mg * ((aDay - bDay + l) * mInv % ng)) % l\n// if (x < timeModL) same += 1\n// }\n }\n\n aDay += 1\n }\n time - same\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (countDiff(mid) >= k) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = binSearch(0, k * (n + m) + 1)\n\n out.println(res)\n\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\n def modInverse(a: Long, m: Long): Long = {\n\n def modInv(a: Long, m: Long, x: Long, y: Long): Long =\n if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))\n\n val inv = modInv(a, m, 1, 0)\n if (inv < 0) inv + m else inv\n }\n\n val _n, _m, k = nextLong\n val _as = nextInts(_n.toInt)\n val _bs = nextInts(_m.toInt)\n\n val n = _n max _m\n val m = _n min _m\n val as = if (_n < _m) _bs else _as\n val bs = if (_n < _m) _as else _bs\n val g = gcd(n, m)\n val l = lcm(n, m)\n val ng = n / g\n val mg = m / g\n\n val mInv = modInverse(mg, ng)\n\n val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)\n for (i <- bs.indices) {\n dayByD(bs(i)) = i\n }\n\n def countDiff(time: Long): Long = {\n var same = 0L\n for (aDay <- as.indices) {\n val a = as(aDay)\n val bDay = dayByD(a)\n if (bDay == -1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n } else if (g > 1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n if (m == n && aDay == bDay) {\n same += time / l\n val x = aDay\n if (x < time % l) same += 1\n } else if (aDay % g == bDay % g) {\n same += time / l\n// val x = bDay * ng + aDay * mg\n val x0 = (bDay / g + mg * ((aDay / g - bDay / g) * mInv % ng)) % (mg * ng)\n val x = (x0 * g + aDay % g) % (l)\n// println(g, x0, x)\n if (x < time % l) same += 1\n }\n } else {\n same += time / l\n val x = (bDay + mg * ((aDay - bDay) * mInv % ng)) % (mg * ng)\n// println(g, aDay, bDay, mInv, x)\n if (x % l < time % l) same += 1\n }\n }\n time - same\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (countDiff(mid) >= k) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = binSearch(0, Long.MaxValue/2)\n\n out.println(res)\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\n def modInverse(a: Long, m: Long): Long = {\n\n def modInv(a: Long, m: Long, x: Long, y: Long): Long =\n if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))\n\n val inv = modInv(a, m, 1, 0)\n if (inv < 0) inv + m else inv\n }\n\n val _n, _m, k = nextLong\n val _as = nextInts(_n.toInt)\n val _bs = nextInts(_m.toInt)\n\n val n = _n max _m\n val m = _n min _m\n val as = if (_n < _m) _bs else _as\n val bs = if (_n < _m) _as else _bs\n val g = gcd(n, m)\n val l = lcm(n, m)\n val ng = n / g\n val mg = m / g\n\n val mInv = modInverse(mg, ng)\n\n val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)\n for (i <- bs.indices) {\n dayByD(bs(i)) = i\n }\n\n def countDiff(time: Long): Long = {\n var same = 0L\n for (aDay <- as.indices) {\n val a = as(aDay)\n val bDay = dayByD(a)\n if (bDay == -1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n } else if (g > 1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n if (aDay == bDay) {\n same += time / l\n val x = aDay\n if (x < time % l) same += 1\n } else if (aDay % g == bDay % g) {\n same += time / l\n// val x = bDay * ng + aDay * mg\n val x0 = (bDay / g + mg * ((aDay / g - bDay / g) * mInv % ng)) % (mg * ng)\n val x = (x0 * g + aDay % g) % (l)\n// println(g, x0, x)\n if (x < time % l) same += 1\n }\n } else {\n same += time / l\n val x = (bDay + mg * ((aDay - bDay) * mInv % ng)) % (mg * ng)\n// println(g, aDay, bDay, mInv, x)\n if (x % l < time % l) same += 1\n }\n }\n time - same\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (countDiff(mid) >= k) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = binSearch(0, Long.MaxValue/2)\n\n out.println(res)\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\n def modInverse(a: Long, m: Long): Long = {\n\n def modInv(a: Long, m: Long, x: Long, y: Long): Long =\n if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))\n\n val inv = modInv(a, m, 1, 0)\n if (inv < 0) inv + m else inv\n }\n\n val _n, _m, k = nextLong\n val _as = nextInts(_n.toInt)\n val _bs = nextInts(_m.toInt)\n\n val n = _n max _m\n val m = _n min _m\n val as = if (_n < _m) _bs else _as\n val bs = if (_n < _m) _as else _bs\n val g = gcd(n, m)\n val l = lcm(n, m)\n val ng = n / g\n val mg = m / g\n\n val mInv = modInverse(mg, ng)\n\n val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)\n for (i <- bs.indices) {\n dayByD(bs(i)) = i\n }\n\n def countDiff(time: Long): Long = {\n var same = 0L\n for (aDay <- as.indices) {\n val a = as(aDay)\n val bDay = dayByD(a)\n if (bDay == -1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n } else if (g > 1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n /*if (aDay == bDay) {\n same += time / l\n val x = aDay\n if (x < time % l) same += 1\n } else */if (aDay % g == bDay % g) {\n same += time / l\n// val x = bDay * ng + aDay * mg\n val x0 = (bDay / g + mg * ((aDay / g - bDay / g) * mInv % ng)) % (mg * ng)\n val x = (x0 * g + aDay % g) % (l)\n// println(g, x0, x)\n if (x < time % l) same += 1\n }\n } else {\n same += time / l\n val x = (bDay + mg * ((aDay - bDay) * mInv % ng)) % (mg * ng)\n// println(g, aDay, bDay, mInv, x)\n if (x % l < time % l) same += 1\n }\n }\n time - same\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (countDiff(mid) >= k) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = binSearch(0, Long.MaxValue/2)\n\n out.println(res)\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\n def modInverse(a: Long, m: Long): Long = {\n\n def modInv(a: Long, m: Long, x: Long, y: Long): Long =\n if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))\n\n val inv = modInv(a, m, 1, 0)\n if (inv < 0) inv + m else inv\n }\n\n val _n, _m, k = nextLong\n val _as = nextInts(_n.toInt)\n val _bs = nextInts(_m.toInt)\n\n val n = _n max _m\n val m = _n min _m\n val as = if (_n < _m) _bs else _as\n val bs = if (_n < _m) _as else _bs\n val g = gcd(n, m)\n val l = lcm(n, m)\n val ng = n / g\n val mg = m / g\n\n val mInv = modInverse(mg, ng)\n\n val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)\n for (i <- bs.indices) {\n dayByD(bs(i)) = i\n }\n\n def countDiff(time: Long): Long = {\n var same = 0L\n for (aDay <- as.indices) {\n val a = as(aDay)\n val bDay = dayByD(a)\n if (bDay == -1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n } else if (g > 1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n /*if (aDay == bDay) {\n same += time / l\n val x = aDay\n if (x < time % l) same += 1\n } else */if (aDay % g == bDay % g) {\n same += time / l\n// val x = bDay * ng + aDay * mg\n val x0 = (bDay / g + mg * ((aDay / g - bDay / g) * mInv % ng)) % (mg * ng)\n val x = (x0 * g + aDay % g) % (l)\n// println(g, x0, x)\n if (x < time % l) same += 1\n }\n } else {\n same += time / l\n val x = (bDay + mg * ((aDay - bDay) * mInv % ng)) % (mg * ng)\n// println(g, aDay, bDay, mInv, x)\n if (x < time % l) same += 1\n }\n }\n time - same\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (countDiff(mid) >= k) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = binSearch(0, Long.MaxValue/2)\n\n out.println(res)\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\n def modInverse(a: Long, m: Long): Long = {\n\n def modInv(a: Long, m: Long, x: Long, y: Long): Long =\n if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))\n\n val inv = modInv(a, m, 1, 0)\n if (inv < 0) inv + m else inv\n }\n\n val _n, _m, k = nextLong\n val _as = nextInts(_n.toInt)\n val _bs = nextInts(_m.toInt)\n\n val n = _n max _m\n val m = _n min _m\n val as = if (_n < _m) _bs else _as\n val bs = if (_n < _m) _as else _bs\n val g = gcd(n, m)\n val l = lcm(n, m)\n val ng = n / g\n val mg = m / g\n\n val mInv = modInverse(mg, ng)\n\n val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)\n for (i <- bs.indices) {\n dayByD(bs(i)) = i\n }\n\n def countDiff(time: Long): Long = {\n var same = 0L\n for (aDay <- as.indices) {\n val a = as(aDay)\n val bDay = dayByD(a)\n if (bDay == -1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n } else if (g > 1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n /*if (aDay == bDay) {\n same += time / l\n val x = aDay\n if (x < time % l) same += 1\n } else */if (aDay % g == bDay % g) {\n same += time / l\n// val x = bDay * ng + aDay * mg\n val x0 = (bDay / g + mg * ((aDay / g - bDay / g) * mInv % ng)) % (mg * ng)\n val x = x0 * g + aDay % g\n// println(g, x0, x)\n if (x < time % l) same += 1\n }\n } else {\n same += time / l\n val x = (bDay + mg * ((aDay - bDay) * mInv % ng)) % (mg * ng)\n// println(g, aDay, bDay, mInv, x)\n if (x < time % l) same += 1\n }\n }\n time - same\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (countDiff(mid) >= k) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = binSearch(0, Long.MaxValue/2)\n\n out.println(res)\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\n def modInverse(a: Long, m: Long): Long = {\n\n def modInv(a: Long, m: Long, x: Long, y: Long): Long =\n if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))\n\n val inv = modInv(a, m, 1, 0)\n if (inv < 0) inv + m else inv\n }\n\n val _n, _m, k = nextLong\n val _as = nextInts(_n.toInt)\n val _bs = nextInts(_m.toInt)\n\n val n = _n max _m\n val m = _n min _m\n val as = if (_n < _m) _bs else _as\n val bs = if (_n < _m) _as else _bs\n val g = gcd(n, m)\n val l = lcm(n, m)\n val ng = n / g\n val mg = m / g\n\n val mInv = modInverse(mg, ng)\n\n val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)\n for (i <- bs.indices) {\n dayByD(bs(i)) = i\n }\n\n def countDiff(time: Long): Long = {\n var same = 0L\n for (aDay <- as.indices) {\n val a = as(aDay)\n val bDay = dayByD(a)\n if (bDay == -1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n } else if (g > 1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n /*if (aDay == bDay) {\n same += time / l\n val x = aDay\n if (x < time % l) same += 1\n } else */if (aDay % g == bDay % g) {\n same += time / l\n// val x = bDay * ng + aDay * mg\n val x0 = (bDay / g + mg * (aDay / g - bDay / g) * mInv % ng) % (mg * ng)\n val x = x0 * g + aDay % g\n// println(x)\n if (x < time % l) same += 1\n }\n } else {\n same += time / l\n val x = (bDay + mg * (aDay - bDay) * mInv % ng) % (mg * ng)\n if (x < time % l) same += 1\n }\n }\n time - same\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (countDiff(mid) >= k) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = binSearch(0, Long.MaxValue/2)\n\n out.println(res)\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\n def modInverse(a: Long, m: Long): Long = {\n\n def modInv(a: Long, m: Long, x: Long, y: Long): Long =\n if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))\n\n val inv = modInv(a, m, 1, 0)\n if (inv < 0) inv + m else inv\n }\n\n val _n, _m, k = nextLong\n val _as = nextInts(_n.toInt)\n val _bs = nextInts(_m.toInt)\n\n val n = _n max _m\n val m = _n min _m\n val as = if (_n < _m) _bs else _as\n val bs = if (_n < _m) _as else _bs\n val g = gcd(n, m)\n val l = lcm(n, m)\n val ng = n / g\n val mg = m / g\n\n val mInv = modInverse(m, n)\n\n val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)\n for (i <- bs.indices) {\n dayByD(bs(i)) = i\n }\n\n def countDiff(time: Long): Long = {\n var same = 0L\n for (aDay <- as.indices) {\n val a = as(aDay)\n val bDay = dayByD(a)\n if (bDay == -1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n } else if (g > 1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n /*if (aDay == bDay) {\n same += time / l\n val x = aDay\n if (x < time % l) same += 1\n } else */if (aDay % g == bDay % g) {\n same += time / l\n// val x = bDay * ng + aDay * mg\n val x0 = (bDay / g + mg * (aDay / g - bDay / g) * mInv % ng) % (mg * ng)\n val x = x0 * g + aDay % g\n// println(x)\n if (x < time % l) same += 1\n }\n } else {\n same += time / l\n val x = (bDay + mg * (aDay - bDay) * mInv % ng) % (mg * ng)\n if (x < time % l) same += 1\n }\n }\n time - same\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (countDiff(mid) >= k) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = binSearch(0, Long.MaxValue/2)\n\n out.println(res)\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\n def modInverse(a: Long, m: Long): Long = {\n\n def modInv(a: Long, m: Long, x: Long, y: Long): Long =\n if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))\n\n val inv = modInv(a, m, 1, 0)\n if (inv < 0) inv + m else inv\n }\n\n val _n, _m, k = nextLong\n val _as = nextInts(_n.toInt)\n val _bs = nextInts(_m.toInt)\n\n val n = _n max _m\n val m = _n min _m\n val as = if (_n < _m) _bs else _as\n val bs = if (_n < _m) _as else _bs\n val g = gcd(n, m)\n val l = lcm(n, m)\n val ng = n / g\n val mg = m / g\n\n val mInv = modInverse(m, n)\n\n val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)\n for (i <- bs.indices) {\n dayByD(bs(i)) = i\n }\n\n def countDiff(time: Long): Long = {\n var same = 0L\n for (aDay <- as.indices) {\n val a = as(aDay)\n val bDay = dayByD(a)\n if (bDay == -1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n } else if (g > 1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n if (aDay == bDay) {\n same += time / l\n val x = aDay\n if (x < time % l) same += 1\n } else if (aDay % g == bDay % g) {\n same += time / l\n val x = bDay * ng + aDay * mg\n// val x = (bDay + mg * (aDay - bDay) * mInv % ng) % (mg * ng)\n// println(x)\n if (x < time % l) same += 1\n }\n } else {\n same += time / l\n val x = (bDay + mg * (aDay - bDay) * mInv % ng) % (mg * ng)\n if (x < time % l) same += 1\n }\n }\n time - same\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (countDiff(mid) >= k) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = binSearch(0, Long.MaxValue/2)\n\n out.println(res)\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\n def modInverse(a: Long, m: Long): Long = {\n\n def modInv(a: Long, m: Long, x: Long, y: Long): Long =\n if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))\n\n val inv = modInv(a, m, 1, 0)\n if (inv < 0) inv + m else inv\n }\n\n val _n, _m, k = nextLong\n val _as = nextInts(_n.toInt)\n val _bs = nextInts(_m.toInt)\n\n val n = _n max _m\n val m = _n min _m\n val as = if (_n < _m) _bs else _as\n val bs = if (_n < _m) _as else _bs\n val g = gcd(n, m)\n val l = lcm(n, m)\n val ng = n / g\n val mg = m / g\n\n val mInv = modInverse(m, n)\n\n val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)\n for (i <- bs.indices) {\n dayByD(bs(i)) = i\n }\n\n def countDiff(time: Long): Long = {\n var same = 0L\n for (aDay <- as.indices) {\n val a = as(aDay)\n val bDay = dayByD(a)\n if (bDay == -1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n } else if (g > 1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n if (aDay % g == bDay % g) {\n same += time / l\n val x = (bDay * n + aDay * m) / g\n if (x < time % l) same += 1\n }\n } else {\n same += time / l\n val x = (bDay + mg * (aDay - bDay) * mInv % ng) % (mg * ng)\n if (x < time % l) same += 1\n }\n }\n time - same\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (countDiff(mid) >= k) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = binSearch(0, Long.MaxValue/2)\n\n out.println(res)\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\n def modInverse(a: Long, m: Long): Long = {\n\n def modInv(a: Long, m: Long, x: Long, y: Long): Long =\n if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))\n\n val inv = modInv(a, m, 1, 0)\n if (inv < 0) inv + m else inv\n }\n\n val _n, _m, k = nextLong\n val _as = nextInts(_n.toInt)\n val _bs = nextInts(_m.toInt)\n\n val n = _n max _m\n val m = _n min _m\n val as = if (_n < _m) _bs else _as\n val bs = if (_n < _m) _as else _bs\n val g = gcd(n, m)\n val l = lcm(n, m)\n val ng = n / g\n val mg = m / g\n\n val mInv = modInverse(m, n)\n\n val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1)\n for (i <- bs.indices) {\n dayByD(bs(i)) = i\n }\n\n def countDiff(time: Long): Long = {\n var same = 0L\n for (aDay <- as.indices) {\n val a = as(aDay)\n val bDay = dayByD(a)\n if (bDay == -1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n } else if (g > 1) {\n// diff += time / n\n// if (aDay < time % n) diff += 1\n if (aDay % g == bDay % g) {\n same += time / l\n val x = (bDay * n + aDay * m) / g\n if (x < time % l) same += 1\n }\n } else {\n same += time / l\n val x = (bDay + mg * (aDay - bDay) * mInv % ng) % (mg * ng)\n if (x < time % l) same += 1\n }\n }\n time - same\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (countDiff(mid) >= k) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = binSearch(0, Long.MaxValue/2)\n\n out.println(res)\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "src_uid": "04f75aa0ae4a015b87ac8521cd1d34fc"} {"source_code": "object _1241A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val matches = io.read[Seq[Int]]\n val ans = matches map {m => if (m <= 4) 4-m else m%2}\n io.writeAll(ans, separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Codeforces1223A extends App {\n var q = StdIn.readLine().toInt\n while (q > 0) {\n val n = StdIn.readLine().toInt\n if (n < 4) {\n println((4 - n))\n } else {\n println(n % 2)\n }\n q -= 1\n }\n}\n"}], "negative_code": [], "src_uid": "178876bfe161ba9ccfd80c9310f75cbc"} {"source_code": "object D extends App {\n import scala.io.StdIn._\n\n def kadane(an: Seq[Int]): Long = an match {\n case a +: _ =>\n an.foldLeft((a.toLong, 0L)) {\n case ((subSum, partSum), a) =>\n (subSum max (partSum + a), 0L max (partSum + a))\n }\n ._1\n case _ => 0L\n }\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n val ans = n match {\n case 1 => an.head\n case _ =>\n val evens = an.zipWithIndex.collect { case (a, i) if i % 2 == 0 => a }\n val base = evens.foldLeft(0L)(_ + _)\n val odds = an.zipWithIndex.collect { case (a, i) if i % 2 == 1 => a }\n\n val d1 = evens.zip(odds).map { case (e, o) => o - e }\n val d2 = odds.zip(evens.tail).map { case (o, e) => o - e }\n\n val profit = 0L max kadane(d1) max kadane(d2)\n\n base + profit\n }\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "object D extends App {\n import scala.io.StdIn._\n\n def kadane(an: Seq[Int]): Long = an match {\n case a +: _ =>\n an.foldLeft((a.toLong, 0L)) {\n case ((subSum, partSum), a) =>\n (subSum max (partSum + a), 0L max (partSum + a))\n }\n ._1\n case _ => 0L\n }\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n val ans = n match {\n case 1 => an.head\n case _ =>\n val evens = an.zipWithIndex.collect { case (a, i) if i % 2 == 0 => a }\n val odds = an.zipWithIndex.collect { case (a, i) if i % 2 == 1 => a }\n\n val d1 = evens.zip(odds).map { case (e, o) => o - e }\n val d2 = odds.zip(evens.tail).map { case (o, e) => o - e }\n\n val profit = kadane(d1) max kadane(d2)\n\n evens.foldLeft(0L)(_ + _) + (0L max profit)\n }\n\n println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "object D extends App {\n import scala.io.StdIn._\n\n def kadane(an: Seq[Int]): Int = an match {\n case a +: _ =>\n an.foldLeft((a, 0)) {\n case ((subSum, partSum), a) =>\n (subSum max (partSum + a), 0 max (partSum + a))\n }\n ._1\n case _ => 0\n }\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n val ans = n match {\n case 1 => an.head\n case _ =>\n val evens = an.zipWithIndex.collect { case (a, i) if i % 2 == 0 => a }\n val odds = an.zipWithIndex.collect { case (a, i) if i % 2 == 1 => a }\n\n val d1 = evens.zip(odds).map { case (e, o) => o - e }\n val d2 = odds.zip(evens.tail).map { case (o, e) => o - e }\n\n val profit = kadane(d1) max kadane(d2)\n\n evens.sum + (0 max profit)\n }\n\n println(ans)\n }\n}\n"}], "src_uid": "3696b769bfd32cba34e739b74e13693f"} {"source_code": "import scala.collection.mutable\n\nobject E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val friendsBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }\n\n for (_ <- 1 to m) {\n val Array(u, v) = readInts(2)\n friendsBuilders(u - 1) += v - 1\n friendsBuilders(v - 1) += u - 1\n }\n\n val friends = friendsBuilders.map(_.result)\n\n val orderBuilder = new mutable.ArrayBuilder.ofInt\n val queue = mutable.Queue(0)\n val visited = mutable.BitSet(0)\n\n while (queue.nonEmpty) {\n val u = queue.dequeue()\n orderBuilder += u\n for (v <- friends(u)) if (!visited(v)) {\n visited += v\n queue += v\n }\n }\n\n val order = orderBuilder.result()\n\n val goal = (1 << n) - 1\n var bestSteps = n + 1\n var bestPath = Array.empty[Int]\n\n val path = Array.ofDim[Int](n)\n\n def bit(i: Int): Int = 1 << i\n\n def dfs(step: Int, mask: Int, prev: Int): Unit = {\n if (step < bestSteps) {\n if (mask == goal) {\n bestSteps = step\n bestPath = path.take(step)\n } else {\n for (nextI <- prev + 1 until n) {\n val next = order(nextI)\n if ((mask & bit(next)) > 0 || step == 0) {\n var nextMask = mask | bit(next)\n for (friend <- friends(next)) nextMask |= bit(friend)\n path(step) = next\n dfs(step + 1, nextMask, nextI)\n }\n }\n }\n }\n }\n\n if (m < n * (n - 1) / 2) dfs(0, 0, -1)\n else bestSteps = 0\n\n println(bestSteps)\n println(bestPath.map(_ + 1).mkString(\" \"))\n}\n", "positive_code": [{"source_code": "import java.util\n\nimport scala.collection.mutable\nimport scala.io.StdIn\n\n\nobject Solution {\n\n //Console.setIn(new FileReader(new java.io.File(\"input\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n\n var caseNo = 1\n\n def doCase() : Unit = {\n val Array(n, m) = readIntLine()\n\n val adj = Array.fill(n){0}\n for (_ <- 0 until m) {\n var Array(u, v) = readIntLine()\n u -= 1\n v -= 1\n adj(u) |= 1 << v\n adj(v) |= 1 << u\n }\n val complete = (1 << n) - 1\n val isClique = adj.indices.forall {\n i =>\n (adj(i) | (1 << i)) == complete\n }\n\n if (isClique) {\n println(0)\n println(\"\")\n return\n }\n\n val dp = Array.fill(1 << n){null : (Int, List[Int])}\n\n var (cost, path) = adj.indices.map {\n i =>\n val set = 1 << i\n dyn(set, 0, adj, dp, complete, adj.length)\n }.minBy(_._1)\n\n println(cost)\n println(path.map(_ + 1).toArray.mkString(\" \"))\n }\n\n def dyn(set : Int, cost : Int, adj : Array[Int], dp : Array[(Int, List[Int])], complete : Int, l : Int) : (Int, List[Int]) = {\n if (set == complete) {\n return (0, List())\n }\n if (dp(set) == null) {\n var best = (Int.MaxValue, List() : List[Int])\n var i = 0\n while (i < l) {\n val newSet = adj(i) | set\n if (((1 << i) & set) > 0 && newSet != set) {\n val recur = dyn(newSet, cost + 1, adj, dp, complete, l)\n if (recur._1 < best._1) {\n best = (recur._1 + 1, i :: recur._2)\n }\n }\n i += 1\n }\n dp(set) = best\n }\n dp(set)\n }\n\n def main(args: Array[String]) {\n var tests = 1\n for (test <- 0 until tests) {\n doCase()\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.util\n\nimport scala.collection.mutable\nimport scala.io.StdIn\n\n\nobject Solution {\n\n //Console.setIn(new FileReader(new java.io.File(\"input\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n\n var caseNo = 1\n\n def doCase() : Unit = {\n val Array(n, m) = readIntLine()\n\n val adj = Array.fill(n){0}\n for (_ <- 0 until m) {\n var Array(u, v) = readIntLine()\n u -= 1\n v -= 1\n adj(u) |= 1 << v\n adj(v) |= 1 << u\n }\n\n var (cost, path) = adj.indices.map {\n i => greedilyNode(i, adj)\n }.minBy(_._1)\n println(cost)\n println(path.reverse.map(_ + 1).toArray.mkString(\" \"))\n\n }\n\n def greedilyNode(n : Int, adj : Array[Int]) : (Int, List[Int]) = {\n val l = adj.length\n var count = 0\n var set = 0\n set |= 1 << n\n var complete = (1 << l) - 1\n var path : List[Int] = List()\n while (set != complete) {\n var i = 0\n while (i < l) {\n if (((1 << i) & set) > 0 && (~set & adj(i)) > 0) {\n set |= adj(i)\n path ::= i\n count += 1\n }\n i += 1\n }\n }\n (count, path)\n }\n\n def main(args: Array[String]) {\n var tests = 1\n for (test <- 0 until tests) {\n doCase()\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val friendsBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }\n\n for (_ <- 1 to m) {\n val Array(u, v) = readInts(2)\n friendsBuilders(u - 1) += v - 1\n friendsBuilders(v - 1) += u - 1\n }\n\n val friends = friendsBuilders.map(_.result)\n\n val orderBuilder = new mutable.ArrayBuilder.ofInt\n val queue = mutable.Queue(0)\n val visited = mutable.BitSet(0)\n\n while (queue.nonEmpty) {\n val u = queue.dequeue()\n orderBuilder += u\n for (v <- friends(u)) if (!visited(v)) {\n visited += v\n queue += v\n }\n }\n\n val order = orderBuilder.result()\n\n val goal = (1 << n) - 1\n var bestSteps = n + 1\n var bestPath = Array.empty[Int]\n\n val path = Array.ofDim[Int](n)\n\n def bit(i: Int): Int = 1 << i\n\n def dfs(step: Int, mask: Int, prev: Int): Unit = {\n if (step < bestSteps) {\n if (mask == goal) {\n bestSteps = step\n bestPath = path.take(step)\n } else {\n for (nextI <- prev + 1 until n) {\n val next = order(nextI)\n if ((mask & bit(next)) > 0 || step == 0) {\n var nextMask = mask | bit(next)\n for (friend <- friends(next)) nextMask |= bit(friend)\n path(step) = next\n dfs(step + 1, nextMask, nextI)\n }\n }\n }\n }\n }\n\n if (n > 1) dfs(0, 0, -1)\n else bestSteps = 0\n\n println(bestSteps)\n println(bestPath.map(_ + 1).mkString(\" \"))\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val friendsBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }\n\n for (_ <- 1 to m) {\n val Array(u, v) = readInts(2)\n friendsBuilders(u - 1) += v - 1\n friendsBuilders(v - 1) += u - 1\n }\n\n val friends = friendsBuilders.map(_.result)\n\n val orderBuilder = new mutable.ArrayBuilder.ofInt\n val queue = mutable.Queue(0)\n val visited = mutable.BitSet(0)\n\n while (queue.nonEmpty) {\n val u = queue.dequeue()\n orderBuilder += u\n for (v <- friends(u)) if (!visited(v)) {\n visited += v\n queue += v\n }\n }\n\n val order = orderBuilder.result()\n\n val goal = (1 << n) - 1\n var bestSteps = n + 1\n var bestPath: Array[Int] = _\n\n val path = Array.ofDim[Int](n)\n\n def bit(i: Int): Int = 1 << i\n\n def dfs(step: Int, mask: Int, prev: Int): Unit = {\n if (step < bestSteps) {\n if (mask == goal) {\n bestSteps = step\n bestPath = path.take(step)\n } else {\n for (nextI <- prev + 1 until n) {\n val next = order(nextI)\n if ((mask & bit(next)) > 0 || step == 0) {\n var nextMask = mask | bit(next)\n for (friend <- friends(next)) nextMask |= bit(friend)\n path(step) = next\n dfs(step + 1, nextMask, nextI)\n }\n }\n }\n }\n }\n\n dfs(0, 0, -1)\n\n println(bestSteps)\n println(bestPath.map(_ + 1).mkString(\" \"))\n}\n"}], "src_uid": "5ec62d1ab7bd3b14ec3f1508ca327134"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next()\n if (n % 2 == 0)\n println(line.grouped(2).mkString(\"-\"))\n else\n println((line.take(3) :: line.drop(3).grouped(2).toList).mkString(\"-\"))\n}\n", "positive_code": [{"source_code": "object P025B {\n def main(argv: Array[String]) = {\n val n = readInt\n var s = readLine\n val firstWidth = n % 2 + 2\n print(s.slice(0, firstWidth))\n s = s.drop(firstWidth)\n while (s.length() > 0) {\n print('-' + s.slice(0, 2))\n s = s.drop(2)\n }\n println()\n }\n}\n\n"}, {"source_code": "object PhoneNo {\n def main(args: Array[String]) {\n val n = io.StdIn.readLine.toInt\n val p = io.StdIn.readLine\n if (n < 4) {\n println(p)\n return\n }\n for (i<-0 until n-3 by 2) {\n print(p.substring(i,i+2) + '-')\n }\n if (n%2 == 0) println(p.substring(n-2))\n else println(p.substring(n-3))\n }\n}\n"}, {"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var n = readInt;\n var number = readLine;\n if (n == 2 || n == 3) {\n println(number);\n return;\n }\n var beginInd = 0;\n if (n % 2 != 0) {\n print(number(0).toString + number(1).toString + number(2).toString);\n beginInd = 3;\n if (n > 3) {\n print(\"-\");\n }\n }\n for (i <- beginInd until n) {\n print(number(i));\n if (beginInd == 3) {\n if (i % 2 == 0 && i < n - 1) {\n\t print(\"-\");\n\t }\n } else {\n if (i % 2 > 0 && i < n - 1) {\n\t print(\"-\");\n\t }\n }\n \n }\n }\n\n}"}], "negative_code": [{"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var n = readInt;\n var number = readLine.toCharArray();\n if (n == 2 || n == 3) {\n println(number);\n return;\n }\n var beginInd = 0;\n if (n % 2 != 0) {\n print(number(0).toString + number(1).toString + number(2).toString);\n beginInd = 3;\n if (n > 3) {\n print(\"-\");\n }\n }\n for (i <- beginInd until n) {\n print(number(i));\n if (beginInd == 3) {\n if (i % 2 == 0 && i < n - 1) {\n\t print(\"-\");\n\t }\n } else {\n if (i % 2 > 0 && i < n - 1) {\n\t print(\"-\");\n\t }\n }\n \n }\n }\n\n}"}], "src_uid": "6f6859aabc1c9cbb9ee0d910064d87c2"} {"source_code": "\n/**\n * Created by octavian on 30/01/2016.\n */\nobject GuessPerm {\n\n def main(args: Array[String]) = {\n\n //System.setIn(new FileInputStream(\"./src/guessPerm.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"./src/guessPerm.out\")))\n\n val n = readInt()\n var mtx = Array.ofDim[Int](n, 0)\n\n //println(\"n is \" + n)\n for(i <- 0 until n) {\n mtx(i) = readLine().split(\" \").map(_.toInt)\n //println(\"mtx of \" + i + \" is \" + mtx(i).mkString(\" \"))\n }\n\n var result = Array.ofDim[Int](n)\n var madeMax: Boolean = false\n for(i <- 0 until n) {\n result(i) = mtx(i).max\n //println(\"result of \" + i + \" is \" + result(i))\n if(result(i) == n - 1 && madeMax == false) {\n result(i) = n\n madeMax = true\n }\n }\n\n println(result.mkString(\" \"))\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject B341 {\n def main(args: Array[String]) {\n val n = scala.io.StdIn.readInt\n val a = (1 to n).map(q => scala.io.StdIn.readLine.split(\" \").map(_.toInt).max).to[mutable.MutableList]\n a(a.indexOf(n-1)) = n\n println(a.mkString(\" \"))\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n var found = false\n val data = (1 to n).map{_ =>\n val res = in.next().split(' ').map(_.toInt).max\n if (res == n - 1 && !found) {\n found = true\n n\n } else res\n }\n println(data.mkString(\" \"))\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = Array.fill(n) { readInts(n) }\n\n val res = Array.fill(n) { 0 }\n for (i <- 1 to n) {\n var maxCnt = -1\n var maxPos = -1\n for (j <- 0 until n) {\n val cnt = as(j).count(_ == i)\n if (cnt > maxCnt && res(j) == 0) {\n maxCnt = cnt\n maxPos = j\n }\n }\n //println(i, maxPos, maxCnt)\n res(maxPos) = i\n }\n\n println(res.mkString(\" \"))\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _618B extends CodeForcesApp {\n override type Result = Seq[Int]\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val n = nextInt()\n var c = n-2\n (1 to n) map {i =>\n val nums = Seq.fill(n)(nextInt()).groupBy(identity).mapValues(_.size)\n nums.maxBy(_._2) match {\n case (_, 1) =>\n c = c + 1\n c\n case (x, _) => x\n }\n }\n }\n\n override def format(result: Seq[Int]) = result mkString \" \"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n val mod: Int = 1000000007\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n\n val perm = Array.ofDim[Int](n, n)\n\n for(i <- 0 until n)\n for(j <- 0 until n)\n perm(i)(j) = sc.nextInt()\n\n\n //\n var flag = false\n\n val z = perm(0).max\n if(z == n-1){\n flag = true\n print(z)\n }\n else\n print(z)\n\n for(i <- 1 until n){\n val a = perm(i).max\n print(' ')\n\n if(a == n-1){\n if(flag)\n print(n)\n else{\n flag = true\n print(n-1)\n }\n }\n else\n print(a)\n }\n\n println()\n }\n}\n"}, {"source_code": "object Runner {\n\n def main(args: Array[String]) = {\n val n = readLine.toInt\n var res = List[Int]()\n for (i <- 0 until n) {\n val numbers = readLine().split(\" \").map(_.toInt)\n var max: Option[Int] = Option.empty\n for (j <- 0 until numbers.size) {\n if (!j.equals(i)) {\n if (max.isEmpty || max.get < numbers(j)) {\n max = Option(numbers(j))\n }\n }\n }\n res = res :+ max.get\n }\n var flag = false\n var str = new StringBuilder()\n for (i <- 0 until res.size) {\n var a = res(i)\n if (!flag && a == n - 1) {\n flag = true\n a = a + 1\n }\n str.append(a)\n if (i != res.size - 1) {\n str.append(\" \")\n }\n }\n println(str)\n }\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject CF2016_B { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n val arr = Array.ofDim[Int](n, n)\n \n for (i <- 0 until n) {\n val line = readLine\n for(j <- 0 until n) {\n arr(i)(j) = line.int\n }\n }\n \n val res = new Array[Int](n+1)\n for (d <- 1 to n) {\n var maxLine = -1\n var maxCount = 0\n for (i <- 0 until n) {\n var count = 0\n for (j <- 0 until n) {\n if (arr(i)(j) == d) {\n \t count += 1\n }\n }\n if (maxCount < count) {\n maxLine = i\n maxCount = count\n }\n }\n if (maxLine != -1) {\n res(d) = maxLine + 1\n }\n }\n \n val res2 = new Array[Int](n+1)\n for(i <- 1 to n) {\n val place = res(i)\n res2(place) = i\n }\n for(i <- 1 to n) { \n if (res2(i) == 0) {\n res2(i) = n\n }\n }\n \n for(i <- 1 to n) { \n \tprint(res2(i) + \" \")\n }\n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n \n //---------------------------- service code ----------------------------------\n \n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n5\n0 2 2 1 2\n2 0 4 1 3\n2 4 0 1 3\n1 1 1 0 1\n2 3 3 1 0\n\"\"\"\n\n}\n\n}\n\n"}], "negative_code": [{"source_code": "object Runner {\n\n def main(args: Array[String]) = {\n val n = readLine.toInt\n var res = List[Int]()\n for (i <- 0 until n) {\n val numbers = readLine().split(\" \").map(_.toInt)\n var max: Option[Int] = Option.empty\n for (j <- 0 until numbers.size) {\n if (!j.equals(i)) {\n if (max.isEmpty || max.get < numbers(j)) {\n max = Option(numbers(j))\n }\n }\n }\n res = res :+ max.get\n }\n var str = new StringBuilder()\n for (i <- 0 until res.size) {\n str.append(res(i))\n if (i != res.size - 1) {\n str.append(\" \")\n }\n }\n println(str)\n }\n}"}], "src_uid": "1524c658129aaa4175208b278fdc467c"} {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, m, i, j) = readLine().split(\" \").map(_.toInt)\r\n\r\n val (x1, y1) = (if (i - 1 < n - i) n else 1, if (j - 1 < m - j) m else 1)\r\n val (x2, y2) = (if (x1 == n) 1 else n, if (y1 == m) 1 else m)\r\n\r\n println(s\"$x1 $y1 $x2 $y2\")\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import java.io.PrintWriter\r\nimport java.util.Scanner\r\n\r\nobject Solution {\r\n def solve(n: Int, m: Int, i: Int, j: Int): (Int, Int, Int, Int) = {\r\n // he goes to one, then to second, and then come back\r\n // |x1-x2| + |y1-y2| <- anyway between yoyos\r\n // either\r\n // |x1-i| + |y1-j| + |x2-i| + |y2-j|\r\n // or\r\n // |x2-i| + |y2-j| + |x1-i| + |y1-j|\r\n // so no difference. i.e. it's always\r\n // |x1-x2| + |y1-y2| + |x1-i| + |y1-j| + |x2-i| + |y2-j|\r\n // i.e.\r\n // |x1-x2| + |x1-i| + |x2-i| +\r\n // |y1-y2| + |y1-j| + |y2-j| - so it's independent on coordinates\r\n // so seems like it's always 1 and max\r\n (1, 1, n, m)\r\n }\r\n\r\n def run(test: Int, input: Scanner, output: PrintWriter): Unit = {\r\n val (x1, y1, x2, y2) = solve(input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt())\r\n output.println(s\"$x1 $y1 $x2 $y2\")\r\n }\r\n\r\n def run(input: Scanner, output: PrintWriter): Unit = {\r\n val tests = input.nextInt()\r\n\r\n (1 to tests).foreach { test =>\r\n run(test, input, output)\r\n output.flush()\r\n }\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n run(new Scanner(System.in), new PrintWriter(System.out))\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, m, i, j) = readLine().split(\" \").map(_.toInt)\r\n\r\n println(s\"1 1 $n $m\")\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, m, i, j) = readLine().split(\" \").map(_.toInt)\r\n\r\n println(\"1 1 n m\")\r\n }\r\n}\r\n"}], "src_uid": "5aae6b27f35852512a250751ef957ab9"} {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject A {\n\n var out: PrintWriter = _\n var br: BufferedReader = _\n var st: StringTokenizer = _\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = Integer.parseInt(next)\n\n def nextBoolean: Boolean = next.equalsIgnoreCase(\"1\")\n\n def nextLong: Long = java.lang.Long.parseLong(next)\n\n def nextDouble: Double = java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n true\n }\n\n override def toString = s\"MultiHashSet($map)\"\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n map.getOrDefault(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = map.firstKey()\n\n def last(): T = map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n true\n }\n }\n\n /**\n * Segment tree for any commutative function\n *\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Unit = {\n val t = nextInt\n for (_ <- 0 until t) {\n val n = nextInt\n val arr = new Array[Int](n)\n for (i <- 0 until n) {\n arr(i) = nextInt\n\n }\n val sorted = arr.sorted\n var flag = true\n for (i <- 1 until n) {\n if (sorted(i) - sorted(i - 1) > 1)\n flag = false\n }\n if (flag) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n\n }\n }\n}\n", "positive_code": [{"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 1 to t) {\n val _ = StdIn.readLine().trim.toInt\n val arr = StdIn.readLine().split(\" \").map(_.toInt).toList.sorted\n val flag = (arr.head :: arr).zip(arr).forall(p => math.abs(p._1 - p._2) <= 1)\n if (flag) println(\"YES\") else println(\"NO\")\n }\n }\n}\n"}, {"source_code": "import scala.io.Source\n// http://codeforces.com/problemset/problem/1399/A\nobject RemoveSmallest1399A extends App {\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n// val lines: Iterator[String] =\n// Source.fromString(\"5\\n3\\n1 2 2\\n4\\n5 5 5 5\\n3\\n1 2 4\\n4\\n1 3 4 4\\n1\\n100\").getLines\n val ntc: Int = lines.next.toInt\n 0 until ntc map { _ =>\n handleTC()\n } foreach println\n\n def handleTC() = {\n if (lines.next.toInt == 1) {\n lines.next\n \"YES\"\n } else {\n val ints = lines.next.split(\" \").map(_.toInt)\n if (solve(ints)) \"YES\" else \"NO\"\n }\n }\n\n def solve(inAr: Array[Int]) = {\n val s = inAr.sorted\n s.zip(s.tail).forall { case (i, j) =>\n j - i <= 1\n }\n }\n}\n"}, {"source_code": "object _1399A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val as = io.read[Seq[Int]].sorted\n val ans = as.sliding(2) forall {\n case Seq(a, b) => (b - a) <= 1\n case _ => true\n }\n io.write(ans.toEnglish.toUpperCase)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n val charToInt: Char => Int = Character.getNumericValue\n val intToChar: Int => Char = Character.forDigit(_, 10)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}, {"source_code": "//package codeforces.contests._1399\n\nobject RemoveSmallest {\n\n def main(args: Array[String]): Unit = {\n for (t <- 1 to io.StdIn.readInt) {\n val n = io.StdIn.readInt()\n val arr = io.StdIn.readLine.split(\" \").map(_.toInt).sorted\n\n val doFollow = arr.foldLeft((true, arr.head)) { case ((acc, prev), e) => if (acc) (e - prev <= 1, e) else (false, e) }._1\n\n if (doFollow) println(\"YES\") else println(\"NO\")\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "import scala.concurrent.duration.DurationInt\nimport scala.concurrent._\nimport scala.io.Source\n// http://codeforces.com/problemset/problem/1399/A\nobject RemoveSmallest1399A extends App {\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n// val lines: Iterator[String] =\n// Source.fromString(\"5\\n3\\n1 2 2\\n4\\n5 5 5 5\\n3\\n1 2 4\\n4\\n1 3 4 4\\n1\\n100\").getLines\n val ntc: Int = lines.next.toInt\n implicit val global: ExecutionContextExecutor = ExecutionContext.global\n val resSeq: Seq[Future[String]] = 0 until ntc map { _ =>\n handleTC()\n }\n Await.result(Future.sequence(resSeq), 100.second).foreach(println)\n\n def handleTC(): Future[String] = {\n val al = lines.next.toInt\n val ints = lines.next.split(\" \").map(_.toInt)\n Future {\n if (ints.length == 1) (\"YES\")\n else {\n if (solve(ints).isDefined) (\"YES\") else (\"NO\")\n }\n }\n }\n\n def solve(inAr: Array[Int]): Option[Array[Int]] = {\n if (inAr.length == 1) Some(inAr)\n else children(inAr).flatMap(solve).headOption\n }\n\n def children(inAr: Array[Int]): Stream[Array[Int]] = {\n def removeElementAt(arr: Array[Int], ind: Int) =\n arr.zipWithIndex.filterNot { case (_, in) => in == ind }.map(_._1)\n\n (0 until inAr.length - 1).toStream\n .zip((1 until inAr.length).toStream).flatMap { case (i, j: Int) =>\n println(s\"$i, $j\")\n if (inAr(i) - inAr(j) == 1) Array(removeElementAt(inAr, j))\n else if (inAr(i) - inAr(j) == -1) Array(removeElementAt(inAr, i))\n else if (inAr(i) - inAr(j) == 0) Array(\n removeElementAt(inAr, i),\n removeElementAt(inAr, j)\n )\n else Array[Array[Int]]()\n }\n }\n\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 1 to t) {\n val _ = StdIn.readLine().trim.toInt\n val arr = StdIn.readLine().split(\" \").map(_.toInt).toList\n val flag = (arr.head :: arr).zip(arr).forall(p => math.abs(p._1 - p._2) <= 1)\n if (flag) println(\"YES\") else println(\"NO\")\n }\n }\n}\n"}], "src_uid": "ed449ba7c453a43e2ac5904dc0174530"} {"source_code": "\nimport java.util.Scanner\n\nobject FindExtraOne {\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val N = sc.nextInt()\n val xs = for (i <- 0.until(N); (x, y) = (sc.nextInt(), sc.nextInt())) yield x\n\n val xsPartitions = xs.partition(_ > 0)\n val exists = xsPartitions._1.length <= 1 || xsPartitions._2.length <= 1\n\n println(if (exists) \"Yes\" else \"No\")\n }\n}\n", "positive_code": [{"source_code": "object a900 {\n def main(args: Array[String]): Unit = {\n val (a, b) = scala.io.Source.stdin.getLines() drop 1 map (_ split (\" \") map (_.toInt)) partition (_ (0) < 0)\n println(\n (a.length, b.length) match {\n case (0, _) | (_, 0) | (1, _) | (_, 1) => \"Yes\"\n case _ => \"No\"\n }\n )\n }\n}\n"}, {"source_code": "object _900A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val points = io.read[Vector[(Int, Int)]]\n val (left, right) = points.partition({case (x, y) => x < 0})\n val ans = (left.size <= 1) || (right.size <= 1)\n io.write(ans.toEnglish)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "cf7bf89a6038586b69d3b8021cee0b27"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C640B(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val n = ni()\n val k = ni()\n\n if(n % 2 == 0) {\n if(k % 2 != 0) {\n val x = 2 * (k - 1)\n if(x >= n) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n 0 until (k-1) foreach (_ => out.print(\"2 \"))\n out.println(n-x)\n }\n } else {\n val x = k-1\n if(x >= n) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n 0 until (k-1) foreach (_ => out.print(\"1 \"))\n out.println(n-x)\n }\n }\n } else {\n if(k % 2 == 0) {\n out.println(\"NO\")\n } else {\n val x = k - 1\n if(x >= n) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n 0 until (k-1) foreach (_ => out.print(\"1 \"))\n out.println(n-x)\n }\n }\n }\n }\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\n\n private def summands(n: Int, k: Int): List[List[Int]] =\n List(1, 2)\n .map(r => (r, n - r * (k - 1)))\n .collect {\n case (r, d) if d > 0 && d % 2 == r % 2 => d :: List.fill(k - 1)(r)\n }\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ak = summands(n, k)\n\n if (ak.isEmpty) println(\"NO\")\n else {\n println(\"YES\")\n println(ak.head.mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "object B extends App {\n private def summands(n: Int, k: Int): List[List[Int]] =\n List(1, 2).map(r => (r, n - r * (k - 1))).collect {\n case (r, d) if d > 0 && d % 2 == r % 2 => d :: List.fill(k - 1)(r)\n }\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ak = summands(n, k)\n\n if (ak.isEmpty) println(\"NO\")\n else {\n println(\"YES\")\n println(ak.head.mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "object _1352B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val n, k = io.read[Int]\n\n val ans = for {\n member <- Seq(1, 2)\n residue = n - member*(k - 1)\n if residue > 0 && residue%2 == member%2\n } yield Seq.fill(k-1)(member) :+ residue\n\n ans.headOption match {\n case Some(seq) => io.writeLine(\"YES\").writeAll(seq)\n case _ => io.writeLine(\"NO\")\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n val charToInt: Char => Int = Character.getNumericValue\n val intToChar: Int => Char = Character.forDigit(_, 10)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}, {"source_code": "object ProblemB extends App {\n\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n import scala.collection.mutable\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val n = in.nextInt()\n\n def solve(n: Integer, k: Integer): Unit = {\n val result: List[Int] = {\n if (n % 2 == 0 && k % 2 == 1) {\n (n - (k - 1) * 2) :: (1 until k).map(_ => 2).toList\n } else if ((n % 2 == 1 && k % 2 == 1) || (n % 2 == 0)) {\n (n - (k - 1)) :: ((1 until k).map(_ => 1)).toList\n } else {\n List(-1)\n }\n }\n\n if (result.head <= 0) {\n println(\"NO\")\n } else {\n println(\"YES\")\n println(result.mkString(\" \"))\n }\n }\n\n for (i <- 1 to n) {\n val n = in.nextInt()\n val k = in.nextInt()\n\n solve(n, k)\n }\n\n}"}, {"source_code": "import scala.io.StdIn\n\nobject B {\n\n def solution(n: Int, k: Int): Option[Seq[Int]] = {\n lazy val with1 = Some((n - 1 * (k - 1)) +: Seq.fill(k - 1)(1))\n .filter(_.head > 0)\n .filter(_.head % 2 == 1)\n lazy val with2 = Some((n - 2 * (k - 1)) +: Seq.fill(k - 1)(2))\n .filter(_.head > 0)\n .filter(_.head % 2 == 0)\n with1.orElse(with2)\n }\n\n def main(args: Array[String]): Unit = {\n for (_ <- (0 until StdIn.readLine.toInt)) {\n val Seq(n, k) = StdIn.readLine.split(\" \").toSeq.map(_.toInt)\n solution(n, k) match {\n case Some(seq) =>\n println(\"YES\")\n println(seq.mkString(\" \"))\n case None =>\n println(\"NO\")\n }\n }\n }\n}"}], "negative_code": [{"source_code": "object B extends App {\n\n private def summands(n: Int, k: Int): List[List[Int]] =\n List(1, 2)\n .map(r => (r, n - r * (k - 1)))\n .collect {\n case (r, d) if d % 2 == r % 2 => d :: List.fill(k - 1)(r)\n }\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ak = summands(n, k)\n\n if (ak.isEmpty) println(\"NO\")\n else {\n println(\"YES\")\n println(ak.head.mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "\n\nobject ProblemB extends App {\n\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n import scala.collection.mutable\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val n = in.nextInt()\n\n def solve(n: Integer, k: Integer): Unit = {\n val result: List[Int] = {\n if (n % 2 == 0 && k % 2 == 1) {\n (n - (k - 1) * 2) :: (1 until k).map(_ => 2).toList\n } else if ((n % 2 == 1 && k % 2 == 1) || (n % 2 == 0)) {\n (n - (k - 1)) :: ((1 until k).map(_ => 1)).toList\n } else {\n List(-1)\n }\n }\n\n if (result.head < 0) {\n println(\"NO\")\n } else {\n println(\"YES\")\n println(result.mkString(\" \"))\n }\n }\n\n for (i <- 1 to n) {\n val n = in.nextInt()\n val k = in.nextInt()\n\n solve(n, k)\n }\n\n}\n"}], "src_uid": "6b94dcd088b0328966b54acefb5c6d22"} {"source_code": "import scala.io.StdIn\n\n/**\n * Created by Aleksei Latyshev on 04.03.2017.\n */\nobject D extends App {\n val Array(n, k) = StdIn.readLine().split(\" \").map(_.toInt)\n val a = Array.ofDim[Int](1 << 14 + 1)\n StdIn.readLine().split(\" \").map(_.toInt).foreach(x => a(x) += 1)\n if (k != 0) {\n val b: Seq[Int] = (1 until (1 << 14)).filter(x => Integer.bitCount(x) == k)\n println(a.take(10001).zipWithIndex.map {\n case (c, x) => b.map(y => a(y ^ x)).sum.toLong * c\n }.sum / 2)\n } else {\n println(a.map(x => x.toLong * (x - 1) / 2).sum)\n }\n}", "positive_code": [{"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.util.Random\n\n/**\n * Created by netman on 3/4/17.\n */\nobject Main {\n def main(args: Array[String]): Unit = {\n val lines = io.Source.fromInputStream(System.in).getLines().toArray\n val Array(n, k) = lines(0).split(\" \").map(_.toInt)\n val MaxValue = 1 << 14\n val cntBits = Array.ofDim[Int](MaxValue)\n for (i <- 1 until MaxValue) {\n cntBits(i) = cntBits(i >> 1) + (i & 1)\n }\n val rnd = new Random\n val arr = lines(1).split(\" \").map(_.toInt)\n val cnt = Array.ofDim[Int](MaxValue)\n arr.foreach(cnt(_) += 1)\n if (k == 0) {\n var res = 0L\n for (i <- cnt.indices) {\n res += (cnt(i).toLong * (cnt(i) - 1).toLong) / 2\n }\n println(res)\n } else {\n val tmp = ListBuffer.empty[Int]\n for (mask <- cntBits.indices) {\n if (cntBits(mask) == k) tmp += mask\n }\n val lst = tmp.toArray\n var res = 0L\n for (mask <- cnt.indices) {\n if (cnt(mask) != 0) {\n for (other <- lst) {\n res += cnt(mask ^ other).toLong * cnt(mask).toLong\n }\n }\n }\n println(res / 2)\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable.ListBuffer\n\n/**\n * Created by netman on 3/4/17.\n */\nobject Main {\n def main(args: Array[String]): Unit = {\n val lines = io.Source.fromInputStream(System.in).getLines().toArray\n val Array(n, k) = lines(0).split(\" \").map(_.toInt)\n val MaxValue = 1 << 14\n val cntBits = Array.ofDim[Int](MaxValue)\n for (i <- 1 until MaxValue) {\n cntBits(i) = cntBits(i >> 1) + (i & 1)\n }\n val arr = lines(1).split(\" \").map(_.toInt)\n val cnt = Array.ofDim[Int](MaxValue)\n arr.foreach(cnt(_) += 1)\n if (k == 0) {\n var res = 0L\n for (i <- cnt.indices) {\n res += (cnt(i).toLong * (cnt(i) - 1)) / 2\n }\n println(res)\n } else {\n val tmp = ListBuffer.empty[Int]\n for (mask <- cntBits.indices) {\n if (cntBits(mask) == k) tmp += mask\n }\n val lst = tmp.toArray\n var res = 0L\n for (mask <- cnt.indices) {\n if (cnt(mask) != 0) {\n for (other <- lst) {\n res += cnt(mask ^ other)\n }\n }\n }\n println(res / 2)\n }\n }\n}\n"}], "src_uid": "7b7623dfde563b383cdc2364c81a7539"} {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n lazy val xn: Stream[Int] = Stream.iterate(1)(_ + 1).filterNot(x => x % 3 == 0 || (x % 10) == 3)\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val k = readInt()\r\n\r\n val ans = xn(k - 1)\r\n\r\n println(ans)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import java.io._\r\nimport java.util.Scanner\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val reader = new Scanner(System.in)\r\n val writer = new PrintWriter(System.out)\r\n\r\n def pow(a: Int, b: Int): Long = {\r\n if (b == 0) return 1\r\n\r\n val rs = pow(a, b / 2)\r\n rs * rs * (if (b % 2 == 0) 1 else a)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b\r\n\r\n def root(u: Int, p: Array[Int]): Int = {\r\n if (p(u) < 0) return u\r\n p(u) = root(p(u), p)\r\n p(u)\r\n }\r\n\r\n def join(u: Int, v: Int, p: Array[Int]): Unit = {\r\n var x = root(u, p)\r\n var y = root(v, p)\r\n if (x == y) return\r\n\r\n if (p(y) < p(x)) {\r\n val t = x\r\n x = y\r\n y = t\r\n }\r\n p(x) += p(y)\r\n p(y) = x\r\n }\r\n\r\n def solve(t: Int = 0): Unit = {\r\n val n = reader.nextInt()\r\n var i = 0\r\n var k = 1L\r\n while (true) {\r\n if (k % 3 != 0 && k % 10 != 3) {\r\n i += 1\r\n if (i == n) {\r\n writer.println(k)\r\n return\r\n }\r\n }\r\n k += 1\r\n }\r\n }\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = reader.nextInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def main(args: Array[String]) {\r\n multiTest(solve)\r\n //solve()\r\n writer.flush()\r\n }\r\n}"}], "negative_code": [], "src_uid": "c37604d5d833a567ff284d7ce5eda059"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val names = (1 to n).map(_ => in.next())\n\n def next(str: String) = {\n if (str.forall(_ == 'z'))\n \"a\" * (str.length + 1)\n else {\n val postfix = str.reverse.takeWhile(_ == 'z').reverse\n val increment = str(str.length - postfix.length - 1)\n str.take(str.length - 1 - postfix.length) + (increment + 1).toChar + \"a\" * postfix.length\n }\n }\n\n def isNew(str: String) = {\n !names.exists(_.contains(str))\n }\n var candidate = \"a\"\n\n while (!isNew(candidate)) candidate = next(candidate)\n println(candidate)\n}", "positive_code": [{"source_code": "object Main {\n val chars = \"abcdefghijklmnopqrstuvwxyz\".map(_.toString)\n \n def main(args: Array[String]) {\n val n = readInt()\n val a = for(_ <- 1 to n) yield { readLine() }\n val str = (chars ++ chars.flatMap(c => chars.map(c + _))).find(s => a.find(_.contains(s)).isEmpty)\n println(str.get)\n }\n}"}], "negative_code": [], "src_uid": "58fa5c2f270e2c34e8f9671d5ffdb9c8"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(var value: Int, var ind: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return value.compareTo(that.value)\n }\n }\n\n val rem = 1000000007\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n\n val t = readInt()\n for (tt <- 1 to t) {\n val keys = readString()\n val ind = mutable.Map[Char, Int]()\n val s = readString()\n for (i <- keys.indices) {\n ind(keys(i)) = i\n }\n var ans = 0\n for (i <- 1 until s.length) {\n ans += abs(ind(s(i)) - ind(s(i-1)))\n }\n writer.println(ans)\n }\n writer.flush()\n}\n", "positive_code": [{"source_code": "object _1607A extends CodeForcesApp {\r\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\r\n\r\n override def solve(io: IO) = {\r\n val inputs = io.read[Seq[(String, String)]]\r\n inputs foreach { case (_keyboard, target) =>\r\n val keyboard = _keyboard.toVector\r\n val ans = target.map(keyboard.indexOf(_))\r\n .sliding(2)\r\n .map({\r\n case Seq(a, b) => (a - b).abs\r\n case _ => 0\r\n })\r\n .sum\r\n io.writeLine(ans)\r\n }\r\n }\r\n}\r\n/****************************[Ignore Template Below]****************************************/\r\ntrait CodeForcesApp {\r\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\r\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\r\n def solve(io: IO): Any\r\n def main(args: Array[String]): Unit = {\r\n val io = new IO(System.in, System.out)\r\n try solve(io) finally io.close()\r\n }\r\n}\r\n/****************************[Scala Collection Utils]****************************************/\r\nobject Utils {\r\n import scala.collection.mutable\r\n\r\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\r\n\r\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\r\n\r\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\r\n\r\n val charToInt: Char => Int = Character.getNumericValue\r\n val intToChar: Int => Char = Character.forDigit(_, 10)\r\n\r\n implicit class GenericExtensions[A](a: A) {\r\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\r\n }\r\n\r\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\r\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\r\n\r\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\r\n\r\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\r\n val freqTable = t.groupBy(identity).mapValues(_.size)\r\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\r\n }\r\n }\r\n\r\n implicit class PairExtensions[A, B](p: (A, B)) {\r\n def key = p._1\r\n def value = p._2\r\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\r\n }\r\n\r\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\r\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\r\n }\r\n\r\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\r\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\r\n }\r\n\r\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\r\n def notContains(x: A): Boolean = !(s contains x)\r\n def toMutable = mutable.Set.empty[A] ++ s\r\n }\r\n\r\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\r\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\r\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\r\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\r\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\r\n }\r\n\r\n implicit class BooleanExtensions(x: Boolean) {\r\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\r\n def toEnglish = if(x) \"Yes\" else \"No\"\r\n }\r\n\r\n implicit class IntExtensions(val x: Int) extends AnyVal {\r\n @inline def isEven = x%2 == 0\r\n @inline def isOdd = x%2 == 1\r\n }\r\n\r\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\r\n\r\n def map[K] = new {\r\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\r\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\r\n override def apply(key: K) = getOrElseUpdate(key, f(key))\r\n }\r\n }\r\n\r\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\r\n\r\n def memoize[A, B](f: A => B): A => B = map[A] using f\r\n}\r\n/***********************************[Scala I/O]*********************************************/\r\nimport java.io._, java.util.StringTokenizer\r\nimport scala.collection.generic.CanBuild\r\n\r\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\r\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\r\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\r\n\r\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\r\n val printer = new PrintWriter(out, true)\r\n\r\n @inline private[this] def tokenizer() = {\r\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\r\n tokenizers.headOption\r\n }\r\n\r\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\r\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\r\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\r\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\r\n\r\n override def next() = tokenizer().get.nextToken()\r\n override def hasNext = tokenizer().nonEmpty\r\n\r\n def write(obj: Any*): this.type = writeAll(obj)\r\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\r\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\r\n def query[A: IO.Read](question: Any): A = writeLine(question).read\r\n\r\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\r\n\r\n override def flush() = printer.flush()\r\n def close() = {\r\n flush()\r\n in.close()\r\n printer.close()\r\n }\r\n}\r\nobject IO {\r\n class Read[A](val apply: IO => A) {\r\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\r\n }\r\n object Read {\r\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\r\n implicit val string : Read[String] = new Read(_.next())\r\n implicit val int : Read[Int] = string.map(_.toInt)\r\n implicit val long : Read[Long] = string.map(_.toLong)\r\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\r\n implicit val double : Read[Double] = string.map(_.toDouble)\r\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\r\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\r\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\r\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\r\n implicit val boolean : Read[Boolean] = string map {s =>\r\n s.toLowerCase match {\r\n case \"yes\" | \"true\" | \"1\" => true\r\n case \"no\" | \"false\" | \"0\" => false\r\n case _ => s.toBoolean\r\n }\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "7f9853be7ac857bb3c4eb17e554ad3f1"} {"source_code": "object B {\n def main(args: Array[String]) {\n var s = readLine()\n var opened = false;\n var arr:Array[Char] = s.toCharArray\n for (i <- 0 until s.length) {\n if (arr(i) == '\\\"') opened = !opened;\n if (arr(i) == ' ' && !opened) arr(i) = '#';\n }\n new String(arr).split(\"#\") filter (!_.isEmpty) foreach {ss => println(\"<\" + ss.replaceAll(\"\\\"\", \"\") + \">\" )}\n }\n}\n", "positive_code": [{"source_code": "object B {\n def main(args: Array[String]) {\n val s = readLine()\n var inside = false\n var token = \"\"\n for (x <- s) {\n if (inside) {\n if (x == '\\\"') {\n println(\"<\" + token + \">\")\n token = \"\"\n inside = false\n } else {\n token += x\n }\n } else {\n if (x == '\\\"') {\n inside = true\n } else if (x == ' ') {\n if (token != \"\") {\n println(\"<\" + token + \">\")\n }\n token = \"\"\n } else {\n token += x\n }\n }\n }\n if (token != \"\") {\n println(\"<\" + token + \">\")\n }\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val (list, _, soFar) = in.next().foldLeft(List.empty[String], false, List.empty[Char]) {\n case ((list, true, soFar), '\"') => (soFar.reverse.mkString :: list, false, List.empty[Char])\n case ((list, true, soFar), ch) => (list, true, ch :: soFar)\n case ((list, false, Nil), '\"') => (list, true, List.empty[Char])\n case (acc@(list, false, Nil), ' ') => acc\n case (acc@(list, false, something), ' ') => (something.reverse.mkString :: list, false, List.empty[Char])\n case (acc@(list, false, something), ch) => (list, false, ch :: something)\n }\n\n val res = if (soFar.nonEmpty) soFar.reverse.mkString :: list else list\n\n println(res.reverse.map(i => s\"<$i>\").mkString(\"\\n\"))\n\n}"}, {"source_code": "/*\nB. Аргументы командной строки\nограничение по времени на тест\n2 секунды\nограничение по памяти на тест\n256 мегабайт\nввод\nstandard input\nвывод\nstandard output\n\nВ данной задаче используется описание свойств командной строки, близкое к тому, что вы привыкли видеть в настоящих операционных системах. Однако, в деталях существуют отличия в поведении. Внимательно прочтите условие, используйте его как формальный документ при разработке решения.\n\nВ операционной системе Pindows лексемами командной строки являются строки — первая из них трактуется как имя запускаемой программы, а последующие как ее аргументы. Например, выполняя команду « run.exe one, two . », мы передаем командной строке Pindows четыре лексемы: «run.exe», «one,», «two», «.». Более формально, если мы выполняем команду, которая представима строкой s (и не содержит кавычек), то лексемами командной строки являются максимальные по включению подстроки строки s, которые не содержат пробелов.\n\nДля того, чтобы передать в качестве лексемы командной строки строку с пробелами или пустую строку, используются двойные кавычки. Блок символов, который должен рассматриваться как одна лексема, берется в кавычки. При этом вложенные кавычки запрещаются — то есть про каждое вхождение символа «\"» можно однозначно сказать — что это, открывающие кавычки или закрывающие. Например, выполняя команду «\"run.exe o\" \"\" \" ne, \" two . \" \" », мы передаем командной строке Pindows шесть лексем: «run.exe o», «» (пустая строка), « ne, », «two», «.», « » (единичный пробел).\n\nГарантируется, что каждая из лексем командной строки окружена с обеих сторон пробелами или упирается в соответствующий край командной строки. Из этого, например, следует, что открывающие кавычки либо являются первым символом строки, либо слева от них находится пробел.\n\nВам задана строка, состоящая из прописных, строчных букв латинского алфавита, цифр, символов «.,?!\"» и пробелов. Гарантируется, что эта строка — корректная командная строка OS Pindows. Выведите все лексемы этой командной строки. Считайте, что символ «\"» используется в команде только для выделения единого блока символов в одну лексему командной строки, в частности, из этого следует, что таких символов в заданной строке четное количество.\nВходные данные\n\nВ единственной строке задана непустая строка s. Строка s состоит из не более чем 105 символов. Каждый символ — это либо прописная, либо строчная буква латинского алфавита, либо цифра, либо один из символов «.,?!\"», либо пробел.\n\nГарантируется, что заданная строка — некоторая корректная командная строка OS Pindows. Гарантируется, что в заданной командной строке есть хотя бы одна лексема.\nВыходные данные\n\nВ первой строке выведите первую лексему, во второй строке — вторую, и так далее. Для наглядности слева от каждой лексемы выведите символ «<» (меньше), а справа — символ «>» (больше). Выводите лексемы в том порядке, в котором они встречаются в команде.\n\nСтрого следуйте описанному формату вывода. Для лучшего понимания формата вывода посмотрите тестовые примеры.\nПримеры тестов\nВходные данные\n\n\"RUn.exe O\" \"\" \" 2ne, \" two! . \" \"\n\nВыходные данные\n\n\n<>\n< 2ne, >\n\n<.>\n< >\n\nВходные данные\n\n firstarg second \"\" \n\nВыходные данные\n\n\n\n<>\n */\nimport scala.collection.JavaConversions._\n\nobject Task2 extends App {\n\n def clear(s: StringBuilder) = {\n s.clear\n s\n }\n\n def add(l: java.util.List[String], s: String) = {\n l add s\n l\n }\n /** Finds number of pairs, returns -1 if triplet or more */\n def solve(l: String): Seq[String] = {\n val acc = new java.util.ArrayList[String]\n def solveRec(s: String, i: Int, curr: StringBuilder, quoted: Boolean): Unit =\n if (i >= s.length) {\n assert(!quoted)\n if (!curr.isEmpty) add(acc, curr.toString)\n } else s(i) match {\n // Open quotes\n case '\"' if !quoted => solveRec(s, i + 1, curr, true)\n // Add and close quotes\n case '\"' if quoted => {\n add(acc, curr.toString)\n solveRec(s, i + 1, clear(curr), false)\n }\n // Ignore\n case ' ' if !quoted && curr.isEmpty => solveRec(s, i + 1, curr, quoted)\n // Add and clear\n case ' ' if !quoted && !curr.isEmpty => {\n add(acc, curr.toString)\n solveRec(s, i + 1, clear(curr), quoted)\n }\n // Append\n case ' ' if quoted => solveRec(s, i + 1, curr += ' ', quoted)\n // Append\n case c => solveRec(s, i + 1, curr += c, quoted)\n }\n solveRec(l, 0, new StringBuilder, false)\n acc\n }\n\n val line = readLine\n val res = solve(line)\n res map (s => println(\"<\" + s + \">\"))\n}"}, {"source_code": "import io.Source\nimport java.io.PrintWriter\n\nobject CF291B {\n\n def solve(in: In, out: PrintWriter) {\n in.tokenIterator.toSeq.foreach { s => println(\"<\" + s + \">\") }\n }\n\n def main(args: Array[String]) {\n val in: In = new In(Source.fromInputStream(System.in))\n val out: PrintWriter = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() {\n while (iter.hasNext && delims.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next(): String = {\n skipDelims()\n var q = false\n var stop = false\n while (!stop && iter.hasNext && (q || delims.indexOf(iter.head) == -1)) {\n val c = iter.next()\n if (c == '\"') {\n if (q) {\n stop = true\n } else {\n q = true\n }\n } else {\n sb.append(c)\n }\n }\n val ret = sb.toString()\n sb.clear()\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIterator = new TokenIterator(iter, \" \\r\\n\")\n\n val lineIterator = new TokenIterator(iter, \"\\r\\n\")\n\n def apply() = tokenIterator.next()\n\n def apply(n: Int) = tokenIterator.take(n)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = readLine();\n var i = 0\n while(i < s.size) {\n if (s(i) == '\"') {\n val j = s.indexOf('\"', i + 1)\n println(\"<\" + s.substring(i + 1, j) + \">\")\n i = j + 2\n } else if (s(i) == ' ') { \n i += 1\n } else {\n val j = s.indexOf(' ', i + 1) match {\n case -1 => s.size\n case int: Int => int\n }\n println(\"<\" + s.substring(i, j).trim + \">\")\n i = j + 1\n }\n }\n }\n}"}], "negative_code": [{"source_code": "object B {\n def main(args: Array[String]) {\n val s = readLine()\n var inside = false\n var token = \"\"\n for (x <- s) {\n if (inside) {\n if (x == '\\\"') {\n println(\"<\" + token + \">\")\n token = \"\"\n inside = false\n } else {\n token += x\n }\n } else {\n if (x == '\\\"') {\n inside = true\n } else if (x == ' ') {\n if (token != \"\") {\n println(\"<\" + token + \">\")\n }\n token = \"\"\n } else {\n token += x\n }\n }\n }\n if (token != \"\") {\n println(token)\n }\n }\n}"}, {"source_code": "import io.Source\nimport java.io.PrintWriter\n\nobject CF291B {\n\n def solve(in: In, out: PrintWriter) {\n in.tokenIterator.toSeq.foreach { s => println(\"<\" + s + \">\")}\n }\n\n def main(args: Array[String]) {\n val in: In = new In(Source.fromInputStream(System.in))\n val out: PrintWriter = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext && iter.head != '\\n' && iter.head != '\\r'\n }\n\n def skipDelims() {\n while (iter.hasNext && delims.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next(): String = {\n skipDelims()\n var q = false\n var stop = false\n while (!stop && iter.hasNext && (q || delims.indexOf(iter.head) == -1)) {\n val c = iter.next()\n if (c == '\"') {\n if (q) {\n stop = true\n } else {\n q = true\n }\n } else {\n sb.append(c)\n }\n }\n val ret = sb.toString()\n sb.clear()\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIterator = new TokenIterator(iter, \" \")\n\n val lineIterator = new TokenIterator(iter, \"\\r\\n\")\n\n def apply() = tokenIterator.next()\n\n def apply(n: Int) = tokenIterator.take(n)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = readLine();\n var i = 0\n while(i < s.size) {\n if (s(i) == '\"') {\n val j = s.indexOf('\"', i + 1)\n println(\"<\" + s.substring(i + 1, j) + \">\")\n i = j + 2\n } else {\n val j = s.indexOf(' ', i + 1)\n if (j != i + 1) println(\"<\" + s.substring(i, j).trim + \">\")\n i = j + 1\n }\n }\n }\n}"}], "src_uid": "6c7858731c57e1b24c7a299a8eeab373"} {"source_code": "object FixingTypos extends App {\n val s = readLine\n\n def fix(str: String): String = {\n var ss: StringBuffer = new StringBuffer(\"\")\n var now = 2\n for(i <- 0 until str.size if i==0 || str(i) != str(i-1)) {\n if(now == 2) ss.append(str(i))\n ss.append(str(i))\n now = 3 - now\n }\n ss.toString\n }\n\n var ret: StringBuffer = new StringBuffer(\"\")\n var begin = 0\n for(i <- 0 until s.size) {\n var bb = false\n var ee = false\n if(i==0 || s(i) != s(i-1)) bb = true\n if(i== s.size - 1 || s(i) != s(i + 1)) ee = true\n if(ee && bb) {\n ret.append(fix(s.substring(begin, i)))\n ret.append(s(i))\n begin = i + 1\n } else if(i == s.size - 1) ret.append(fix(s.substring(begin, s.size)))\n }\n println(ret)\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val skipTriplets = str.tail.foldLeft((List(str.head), 1, str.head)) {\n case ((list, 2, prev), el) if prev == el => (list, 2, el)\n case ((list, count, prev), el) if prev == el =>\n (el :: list, count + 1, prev)\n case ((list, count, prev), el) =>\n (el :: list, 1, el)\n }._1.reverse\n val skip = skipTriplets.tail.foldLeft((List(str.head), false, str.head, 0)) {\n case((list, false, prev, n), el) if el == prev => (el :: list, true, el, 0)\n case((list, true, prev, 1), el) if el == prev => (list, false, el, 0)\n case((list, true, prev, 0), el) => (el :: list, true, el, 1)\n case((list, status, prev, n), el) => (el :: list, false, el, 0)\n }\n println(skip._1.reverse.mkString)\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val skipTriplets = str.tail.foldLeft((List(str.head), 1, str.head)) {\n case ((list, 2, prev), el) if prev == el => (list, 2, el)\n case ((list, count, prev), el) if prev == el =>\n (el :: list, count + 1, prev)\n case ((list, count, prev), el) =>\n (el :: list, 1, el)\n }._1.reverse\n val skip = skipTriplets.tail.foldLeft((List(str.head), false, str.head, 0)) {\n case((list, false, prev, n), el) if el == prev => (el :: list, true, el, 0)\n case((list, false, prev, n), el) => (el :: list, false, el, 0)\n case((list, true, prev, 1), el) if el == prev => (list, false, el, 0)\n case((list, true, prev, 0), el) if el == prev => (el :: list, true, el, 1)\n case((list, true, prev, n), el) => (el :: list, false, el, 0)\n }\n println(skip._1.reverse.mkString)\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val skipTriplets = str.tail.foldLeft((List(str.head), 1, str.head)) {\n case ((list, 2, prev), el) if prev == el => (list, 2, el)\n case ((list, count, prev), el) if prev == el =>\n (el :: list, count + 1, prev)\n case ((list, count, prev), el) =>\n (el :: list, 1, el)\n }._1.reverse\n val skip = skipTriplets.tail.foldLeft((List(str.head), false, str.head, 0)) {\n case((list, false, prev, n), el) if el == prev => (el :: list, true, el, 0)\n case((list, false, prev, n), el) => (el :: list, false, el, 0)\n case((list, true, prev, 1), el) if el == prev => (list, false, el, 0)\n case((list, true, prev, 0), el) if el == prev => (el :: list, true, el, 1)\n case((list, true, prev, n), el) => (list, false, el, 0)\n }\n println(skip._1.reverse.mkString)\n}"}], "src_uid": "31d803d886c47fe681bdcfbe6c74f090"} {"source_code": "import scala.io.StdIn\r\nimport scala.math.min\r\n\r\nobject Main extends App {\r\n val n = StdIn.readInt()\r\n for (i <- 0 until n) {\r\n val values = StdIn.readLine().split(\" \").map(_.toInt)\r\n val r = values(0)\r\n val b = values(1)\r\n val d = values(2)\r\n val delta = Math.abs(r - b)\r\n val minimal = min(r, b)\r\n println(if (Math.round(delta / minimal) + (if (delta % minimal == 0) 0 else 1) <= d) \"YES\" else \"NO\")\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object A {\r\n\r\n import java.io._\r\n\r\n val out: OutputPrinter = new StringOutputPrinter\r\n //val out: OutputPrinter = new OutputPrinter\r\n val input = new InputReader(new InputStreamReader(System.in))\r\n// val input = new InputReader(new StringReader(\r\n// \"\"\"8\r\n//1 1 0\r\n//2 7 3\r\n//6 1 4\r\n//5 4 0\r\n//1000000000 1000000000 0\r\n//1000000000 1000000000 1000000000\r\n//1000000000 1 1000000000\r\n//1 1000000000 0\r\n// \"\"\"))\r\n\r\n def main(args: Array[String]): Unit = {\r\n val startTime = System.currentTimeMillis()\r\n\r\n val executor = new Solution1\r\n executor.solve()\r\n\r\n out.flush()\r\n val elapsed = System.currentTimeMillis() - startTime\r\n //println(s\"Elapsed: $elapsed\")\r\n }\r\n\r\n\r\n class Solution1 {\r\n\r\n def solve(): Unit = {\r\n val tasks = input.nextInt\r\n for (_ <- 0 until tasks) {\r\n val r, b, d = input.nextInt\r\n val mn = r min b\r\n val mx = r max b\r\n val h = mx / (d + 1)\r\n val l = mx % (d + 1)\r\n if (mn > h || mn == h && l == 0 ) {\r\n out.print(\"YES\")\r\n }\r\n else {\r\n out.print(\"NO\")\r\n }\r\n out.endl()\r\n }\r\n }\r\n }\r\n\r\n\r\n // ===========================================================================\r\n // --------- TOOLS ---------------------------------------------------------\r\n // ===========================================================================\r\n\r\n class InputReader(reader: Reader) {\r\n\r\n import java.io.BufferedReader\r\n import java.util.StringTokenizer\r\n\r\n private val buffer = new BufferedReader(reader)\r\n private var parser: StringTokenizer = _\r\n\r\n private def next = {\r\n if (parser == null || !parser.hasMoreElements) {\r\n parser = new StringTokenizer(buffer.readLine)\r\n }\r\n parser.nextToken\r\n }\r\n\r\n def endl(): Unit = {\r\n parser = null\r\n }\r\n\r\n def nextByte = next.toByte\r\n\r\n def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)\r\n\r\n def nextInt = next.toInt\r\n\r\n def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)\r\n\r\n def nextLong = next.toLong\r\n\r\n def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)\r\n\r\n def nextDouble = next.toDouble\r\n\r\n def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)\r\n\r\n def nextString = next\r\n\r\n def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)\r\n\r\n private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {\r\n for (index <- 0 until num) op(index, readOp)\r\n }\r\n }\r\n\r\n class OutputPrinter {\r\n private val buffer = new StringBuilder() // faster if exists\r\n\r\n def print(c: Char): Unit = {}\r\n\r\n def print(i: Int): Unit = {}\r\n\r\n def print(s: String): Unit = {}\r\n\r\n def endl(): Unit = {}\r\n\r\n def flush(): Unit = {}\r\n }\r\n\r\n class StringOutputPrinter(capacity: Int = 1024) extends OutputPrinter {\r\n private val buffer = new StringBuilder(capacity)\r\n\r\n override def print(c: Char): Unit = buffer.append(c)\r\n\r\n override def print(i: Int): Unit = buffer.append(i)\r\n\r\n override def print(s: String): Unit = buffer.append(s)\r\n\r\n override def endl(): Unit = buffer.append(\"\\n\")\r\n\r\n override def flush(): Unit = {\r\n println(buffer.result())\r\n buffer.clear()\r\n }\r\n }\r\n\r\n}\r\n"}], "negative_code": [{"source_code": "object A {\r\n\r\n import java.io._\r\n\r\n val out: OutputPrinter = new StringOutputPrinter\r\n //val out: OutputPrinter = new OutputPrinter\r\n val input = new InputReader(new InputStreamReader(System.in))\r\n// val input = new InputReader(new StringReader(\r\n// \"\"\"4\r\n//1 1 0\r\n//2 7 3\r\n//6 1 4\r\n//5 4 0\r\n// \"\"\"))\r\n\r\n def main(args: Array[String]): Unit = {\r\n val startTime = System.currentTimeMillis()\r\n\r\n val executor = new Solution1\r\n executor.solve()\r\n\r\n out.flush()\r\n val elapsed = System.currentTimeMillis() - startTime\r\n //println(s\"Elapsed: $elapsed\")\r\n }\r\n\r\n\r\n class Solution1 {\r\n\r\n def solve(): Unit = {\r\n val tasks = input.nextInt\r\n for (_ <- 0 until tasks) {\r\n val r, b, d = input.nextInt\r\n val mn = r min b\r\n val mx = r max b\r\n val mx2 = mn * (d + 1)\r\n if (mx2 >= mx) {\r\n out.print(\"YES\")\r\n }\r\n else {\r\n out.print(\"NO\")\r\n }\r\n out.endl()\r\n }\r\n }\r\n }\r\n\r\n\r\n // ===========================================================================\r\n // --------- TOOLS ---------------------------------------------------------\r\n // ===========================================================================\r\n\r\n class InputReader(reader: Reader) {\r\n\r\n import java.io.BufferedReader\r\n import java.util.StringTokenizer\r\n\r\n private val buffer = new BufferedReader(reader)\r\n private var parser: StringTokenizer = _\r\n\r\n private def next = {\r\n if (parser == null || !parser.hasMoreElements) {\r\n parser = new StringTokenizer(buffer.readLine)\r\n }\r\n parser.nextToken\r\n }\r\n\r\n def endl(): Unit = {\r\n parser = null\r\n }\r\n\r\n def nextByte = next.toByte\r\n\r\n def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)\r\n\r\n def nextInt = next.toInt\r\n\r\n def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)\r\n\r\n def nextLong = next.toLong\r\n\r\n def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)\r\n\r\n def nextDouble = next.toDouble\r\n\r\n def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)\r\n\r\n def nextString = next\r\n\r\n def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)\r\n\r\n private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {\r\n for (index <- 0 until num) op(index, readOp)\r\n }\r\n }\r\n\r\n class OutputPrinter {\r\n private val buffer = new StringBuilder() // faster if exists\r\n\r\n def print(c: Char): Unit = {}\r\n\r\n def print(i: Int): Unit = {}\r\n\r\n def print(s: String): Unit = {}\r\n\r\n def endl(): Unit = {}\r\n\r\n def flush(): Unit = {}\r\n }\r\n\r\n class StringOutputPrinter(capacity: Int = 1024) extends OutputPrinter {\r\n private val buffer = new StringBuilder(capacity)\r\n\r\n override def print(c: Char): Unit = buffer.append(c)\r\n\r\n override def print(i: Int): Unit = buffer.append(i)\r\n\r\n override def print(s: String): Unit = buffer.append(s)\r\n\r\n override def endl(): Unit = buffer.append(\"\\n\")\r\n\r\n override def flush(): Unit = {\r\n println(buffer.result())\r\n buffer.clear()\r\n }\r\n }\r\n\r\n}\r\n"}], "src_uid": "c0ad2a6d14b0c9e09af2221d88a34d52"} {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\n\nobject P359A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n // n rows\n // m cols\n\n val N, M = sc.nextInt\n val T = Array.fill(N, M)(sc.nextInt)\n\n var t = 0\n for (i <- 0 until M) {\n t += T(0)(i)\n t += T(N - 1)(i)\n }\n for (i <- 0 until N) {\n t += T(i)(0)\n t += T(i)(M - 1)\n }\n\n val answer = if (t > 0) 2\n else 4\n\n out.println(answer)\n out.close\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val res = (1 to n).foldLeft(false) {\n case(true, _) => true\n case(false, 1) => in.next().split(' ').map(_.toInt).contains(1)\n case(false, i) if i == n => in.next().split(' ').map(_.toInt).contains(1)\n case(false, _) =>\n val data = in.next().split(' ').map(_.toInt)\n data.head == 1 || data.last == 1\n }\n if (res)\n println(2)\n else\n println(4)\n}\n"}, {"source_code": "object A359 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val a = Array.fill(n)(readInts(m))\n val ids = cu.ArrayBuffer.empty[(Int, Int)]\n for(i <- 0 until n; j <- 0 until m) {\n if(a(i)(j) == 1)\n ids.append((i, j))\n }\n if(a(0)(0) == 1 || a(0)(m-1) == 1 || a(n-1)(0) == 1 || a(n-1)(m-1) == 1)\n println(\"1\")\n else if(ids.exists{case (x,y) => x==0 || x==n-1 || y==0 || y==m-1}) {\n println(\"2\")\n } else {\n println(\"4\")\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val nm = readLine().split(\" \").map(_.toInt)\n val n = nm(0)\n val m = nm(1)\n val a = (1 to n).map(_ => readLine())\n \n val rows = a.head.find(_ == '1').isDefined || a.last.find(_ == '1').isDefined\n val cols = a.find(row => row.head == '1' || row.last == '1').isDefined\n \n if (rows || cols) println(\"2\")\n else println(\"4\") \n }\n}"}], "negative_code": [], "src_uid": "0d2fd9b58142c4f5282507c916690244"} {"source_code": "object A {\n def main(a: Array[String]) {\n def readArray = readLine.split(\" \")\n val Array(n, m, k) = readArray.map(_.toInt)\n val initial = readArray.map(_.toLong)\n val operations = for (i <- 0 until m) yield readArray.map(_.toInt)\n val queries = for (i <- 0 until k) yield readArray.map(_.toInt)\n val opUsed = new Array[Long](m + 1)\n for (Array(qbegin, qend) <- queries) {\n opUsed(qbegin - 1) += 1\n opUsed(qend) -= 1\n }\n for (i <- 1 to m) opUsed(i) += opUsed(i - 1)\n val changes = new Array[Long](n + 1)\n for (i <- 0 until m) {\n val Array(from, to, d) = operations(i)\n val u = opUsed(i)\n changes(from - 1) += d * u\n changes(to) -= d * u\n }\n for (i <- 1 to n) changes(i) += changes(i - 1)\n val result = for (i <- 0 until n) yield initial(i) + changes(i)\n println(result.mkString(\" \"))\n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m, k) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n val increase = Array.ofDim[Long](n)\n val operations: Array[Int] = Array.ofDim[Int](m)\n val op = (1 to m).map { _ =>\n val Array(l, r, d) = in.next().split(' ').map(_.toInt)\n (l, r, d)\n }\n (1 to k).foreach { _ =>\n val Array(x, y) = in.next().split(' ').map(_.toInt - 1)\n operations(x) += 1\n if (y != m - 1)\n operations(y + 1) -= 1\n }\n operations.indices.foldLeft(0l) {\n case (balance, el) =>\n val (l, r, d) = op(el)\n val newBalance = balance + operations(el)\n increase(l - 1) += d * newBalance\n if (r != n)\n increase(r) -= d * newBalance\n newBalance\n }\n val r = increase.indices.foldLeft((0l, List.empty[Long])) {\n case ((open, list), i) =>\n val newBalance = open + increase(i)\n (newBalance, (newBalance + data(i)) :: list)\n }\n println(r._2.reverse.mkString(\" \"))\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m, k) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n val increase = Array.ofDim[Int](n)\n val operations: Array[Int] = Array.ofDim[Int](m)\n val op = (1 to m).map { _ =>\n val Array(l, r, d) = in.next().split(' ').map(_.toInt)\n (l, r, d)\n }\n (1 to k).foreach { _ =>\n val Array(x, y) = in.next().split(' ').map(_.toInt - 1)\n operations(x) += 1\n if (y != m - 1)\n operations(y + 1) -= 1\n }\n operations.indices.foldLeft(0) {\n case (balance, el) =>\n val (l, r, d) = op(el)\n val newBalance = balance + operations(el)\n increase(l - 1) += d * newBalance\n if (r != n)\n increase(r) -= d * newBalance\n newBalance\n }\n val r = increase.indices.foldLeft((0, List.empty[Long])) {\n case ((open, list), i) =>\n val newBalance = open + increase(i)\n (newBalance, (newBalance + data(i)) :: list)\n }\n println(r._2.reverse.mkString(\" \"))\n}\n"}, {"source_code": "object A {\n def main(a: Array[String]) {\n def readArray = readLine.split(\" \").map(_.toInt)\n val Array(n, m, k) = readArray\n val initial = readArray\n val operations = for (i <- 0 until m) yield readArray\n val queries = for (i <- 0 until k) yield readArray\n val opUsed = new Array[Int](m + 1)\n for (Array(qbegin, qend) <- queries) {\n opUsed(qbegin - 1) += 1\n opUsed(qend) -= 1\n }\n for (i <- 1 to m) opUsed(i) += opUsed(i - 1)\n val changes = new Array[Int](n + 1)\n for (i <- 0 until m) {\n val Array(from, to, d) = operations(i)\n val u = opUsed(i)\n changes(from - 1) += d * u\n changes(to) -= d * u\n }\n for (i <- 1 to n) changes(i) += changes(i - 1)\n val result = for (i <- 0 until n) yield initial(i) + changes(i)\n println(result.mkString(\" \"))\n }\n}"}], "src_uid": "c3120f96894c17957bd8acb968bf37cd"} {"source_code": "object B {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {}\n\n val digits = Array(\n \"1110111\",\n \"0010010\",\n \"1011101\",\n \"1011011\",\n \"0111010\",\n \"1101011\",\n \"1101111\",\n \"1010010\",\n \"1111111\",\n \"1111011\"\n ).map(Integer.parseInt(_, 2))\n\n val n, k = nextInt\n val after = Array.fill(n)(Integer.parseInt(nextLine, 2))\n\n val dp = Array.fill(n + 1, k + 1)(-1)\n dp(n)(0) = 0\n for (i <- n - 1 to 0 by -1) {\n for (j <- 0 to k) {\n if (dp(i + 1)(j) != -1) {\n var d = 0\n while (d < 10) {\n if ((after(i) & digits(d)) == after(i)) {\n val need = Integer.bitCount(after(i) ^ digits(d))\n if (j + need <= k) {\n if (d > dp(i)(j + need)) dp(i)(j + need) = d\n }\n }\n d += 1\n }\n }\n }\n }\n\n if (dp(0)(k) == -1) {\n out.println(-1)\n } else {\n val res = Array.ofDim[Int](n)\n var j = k\n for (i <- 0 until n) {\n val d = dp(i)(j)\n res(i) = d\n j -= Integer.bitCount(after(i) ^ digits(d))\n }\n out.println(res.mkString)\n }\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n\n def nextInt = Integer.parseInt(nextToken)\n\n def nextLong = java.lang.Long.parseLong(nextToken)\n\n def nextBig = BigInt(nextToken)\n\n def nextInts(n: Int) = Array.fill(n) {\n nextInt\n }\n\n def nextLongs(n: Int) = Array.fill(n) {\n nextLong\n }\n\n def nextBigs(n: Int) = Array.fill(n) {\n nextBig\n }\n\n def nextLine = in.readLine\n }\n\n}\n", "positive_code": [{"source_code": "object B {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {}\n\n val digits = Array(\n \"1110111\",\n \"0010010\",\n \"1011101\",\n \"1011011\",\n \"0111010\",\n \"1101011\",\n \"1101111\",\n \"1010010\",\n \"1111111\",\n \"1111011\"\n ).map(Integer.parseInt(_, 2))\n\n val n, k = nextInt\n val after = Array.fill(n)(Integer.parseInt(nextLine, 2))\n\n val dp = Array.fill(n + 1, k + 1)(-1)\n dp(n)(0) = 0\n for (i <- n - 1 to 0 by -1) {\n var j = 0\n while (j <= k) {\n if (dp(i + 1)(j) != -1) {\n var d = 0\n while (d < 10) {\n if ((after(i) & digits(d)) == after(i)) {\n val need = Integer.bitCount(after(i) ^ digits(d))\n if (j + need <= k) {\n if (d > dp(i)(j + need)) dp(i)(j + need) = d\n }\n }\n d += 1\n }\n }\n j += 1\n }\n }\n\n if (dp(0)(k) == -1) {\n out.println(-1)\n } else {\n val res = Array.ofDim[Int](n)\n var j = k\n for (i <- 0 until n) {\n val d = dp(i)(j)\n res(i) = d\n j -= Integer.bitCount(after(i) ^ digits(d))\n }\n out.println(res.mkString)\n }\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n\n def nextInt = Integer.parseInt(nextToken)\n\n def nextLong = java.lang.Long.parseLong(nextToken)\n\n def nextBig = BigInt(nextToken)\n\n def nextInts(n: Int) = Array.fill(n) {\n nextInt\n }\n\n def nextLongs(n: Int) = Array.fill(n) {\n nextLong\n }\n\n def nextBigs(n: Int) = Array.fill(n) {\n nextBig\n }\n\n def nextLine = in.readLine\n }\n\n}\n"}], "negative_code": [{"source_code": "object B {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {}\n\n val digits = Array(\n \"1110111\",\n \"0010010\",\n \"1011101\",\n \"1011011\",\n \"0111010\",\n \"1101011\",\n \"1101111\",\n \"1010010\",\n \"1111111\",\n \"1111011\"\n ).map(Integer.parseInt(_, 2))\n\n val n, k = nextInt\n val after = Array.fill(n)(Integer.parseInt(nextLine, 2))\n\n var dp0 = Array.fill(k + 1)(-1)\n dp0(0) = 0\n for (i <- 0 until n) {\n val dp = Array.fill(k + 1)(-1)\n var j = 0\n while (j <= k) {\n if (dp0(j) >= -1) {\n var d = 0\n while (d < 10) {\n if ((after(i) & digits(d)) == after(i)) {\n val need = Integer.bitCount(after(i) ^ digits(d))\n if (j + need <= k) {\n val sum = dp0(j) * 10 + d\n if (sum > dp(j + need)) dp(j + need) = sum\n }\n }\n d += 1\n }\n }\n j += 1\n }\n dp0 = dp\n }\n\n out.println(dp0(k))\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n\n def nextInt = Integer.parseInt(nextToken)\n\n def nextLong = java.lang.Long.parseLong(nextToken)\n\n def nextBig = BigInt(nextToken)\n\n def nextInts(n: Int) = Array.fill(n) {\n nextInt\n }\n\n def nextLongs(n: Int) = Array.fill(n) {\n nextLong\n }\n\n def nextBigs(n: Int) = Array.fill(n) {\n nextBig\n }\n\n def nextLine = in.readLine\n }\n\n}\n"}, {"source_code": "object B {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {}\n\n val digits = Array(\n \"1110111\",\n \"0010010\",\n \"1011101\",\n \"1011011\",\n \"0111010\",\n \"1101011\",\n \"1101111\",\n \"1010010\",\n \"1111111\",\n \"1111011\"\n ).map(Integer.parseInt(_, 2))\n\n val n, k = nextInt\n val after = Array.fill(n)(Integer.parseInt(nextLine, 2))\n\n var dp0 = Array.fill(k + 1)(BigInt(-1))\n dp0(0) = 0\n for (i <- 0 until n) {\n val dp = Array.fill(k + 1)(BigInt(-1))\n var j = 0\n while (j <= k) {\n if (dp0(j) >= -1) {\n var d = 0\n while (d < 10) {\n if ((after(i) & digits(d)) == after(i)) {\n val need = Integer.bitCount(after(i) ^ digits(d))\n if (j + need <= k) {\n val sum = dp0(j) * 10 + d\n if (sum > dp(j + need)) dp(j + need) = sum\n }\n }\n d += 1\n }\n }\n j += 1\n }\n dp0 = dp\n //println(dp0.mkString(\" \"))\n }\n\n val res = dp0(k).toString\n out.println(\"0\" * (n - res.length) + res)\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n\n def nextInt = Integer.parseInt(nextToken)\n\n def nextLong = java.lang.Long.parseLong(nextToken)\n\n def nextBig = BigInt(nextToken)\n\n def nextInts(n: Int) = Array.fill(n) {\n nextInt\n }\n\n def nextLongs(n: Int) = Array.fill(n) {\n nextLong\n }\n\n def nextBigs(n: Int) = Array.fill(n) {\n nextBig\n }\n\n def nextLine = in.readLine\n }\n\n}\n"}, {"source_code": "object B {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {}\n\n val digits = Array(\n \"1110111\", //0\n \"0010010\", //1\n \"1011101\", //2\n \"1011011\", //3\n \"0111010\", //4\n \"1101011\", //5\n \"1101111\", //6\n \"1010010\", //7\n \"1111111\", //8\n \"1111011\", //9\n ).map(Integer.parseInt(_, 2))\n\n val n, k = nextInt\n val after = Array.fill(n)(Integer.parseInt(nextLine, 2))\n\n var dp0 = Array.fill(k + 1)(-1)\n dp0(0) = 0\n for (i <- 0 until n) {\n val dp = Array.fill(k + 1)(-1)\n var j = 0\n while (j <= k) {\n if (dp0(j) >= -1) {\n var d = 0\n while (d < 10) {\n if ((after(i) & digits(d)) == after(i)) {\n val need = Integer.bitCount(after(i) ^ digits(d))\n if (j + need <= k) {\n val sum = dp0(j) * 10 + d\n if (sum > dp(j + need)) dp(j + need) = sum\n }\n }\n d += 1\n }\n }\n j += 1\n }\n dp0 = dp\n }\n\n out.println(dp0(k))\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n\n def nextInt = Integer.parseInt(nextToken)\n\n def nextLong = java.lang.Long.parseLong(nextToken)\n\n def nextBig = BigInt(nextToken)\n\n def nextInts(n: Int) = Array.fill(n) {\n nextInt\n }\n\n def nextLongs(n: Int) = Array.fill(n) {\n nextLong\n }\n\n def nextBigs(n: Int) = Array.fill(n) {\n nextBig\n }\n\n def nextLine = in.readLine\n }\n\n}\n"}], "src_uid": "d7f73762ff7a01c33280257e556a9b36"} {"source_code": "\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_484_B { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.sa2)\n// debugV = true\n// file = File(\"C:\\\\temp\\\\google cj\\\\2014q\\\\c-small.res\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading \n val n = readLine.int\n val rows = new Array[(Int, Int)](n)\n val rowLine = readLine\n (1 to n).foreach(x => rows(x-1) = x -> rowLine.int)\n val rowsSort = rows.sortBy(_._2)\n var indIntro = 0\n var emptyInros = List[Int]()\n \n// var resList = List[Int]()\n var resList = new Array[Int](n*2)\n var resListInt = 0\n val pLine = readLine.string\n for (p <- 1 to 2*n) {\n val pt = pLine(p-1)\n if (pt == '0') {\n val rowTaken = rowsSort(indIntro)._1\n resList(resListInt) = rowTaken\n emptyInros ::= rowTaken\n indIntro += 1\n } else {\n val rowTaken = emptyInros.head\n emptyInros = emptyInros.tail\n resList(resListInt) = rowTaken\n }\n resListInt += 1\n }\n// resList = resList.reverse\n \n //---------------------------- parameters reading :end \n \n val res = new StringBuffer()\n resList.foreach(x => res.append(x+\" \"))\n// resList.foldLeft(\"\")((a, b) => a + b + \" \")\n \n outLn(res.toString())\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n2\n3 1\n0011\n\"\"\"\n\nval sa2 = \"\"\"\n6\n10 8 9 11 13 5\n010010011101\n\"\"\"\n\nval sa3 = \"\"\"\n\"\"\"\n}\n\n}\n\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\n\nobject Codeforces982B {\n def main(args: Array[String]): Unit = {\n val codeforces982B = new Codeforces982B()\n\n val n = StdIn.readInt()\n val w = StdIn.readLine().split(\" \").map(_.toInt)\n\n val passengers = StdIn.readLine()\n\n val seatNumbers = codeforces982B.getPassengersSeatNumbers(n, w, passengers)\n\n println(seatNumbers.mkString(\" \"))\n }\n}\n\nclass Codeforces982B {\n def getPassengersSeatNumbers(n: Int, w: Array[Int], passengers: String): Array[Int] = {\n val seats = w.zipWithIndex.map(z => new Seat(weight = z._1, number = z._2 + 1)).sortBy(s => s.weight)\n\n val dummyHead = new Node(null)\n var cursor = dummyHead\n for (seat <- seats) {\n cursor.next = new Node(seat, prev = cursor)\n cursor = cursor.next\n }\n val dummyTail = new Node(null, prev = cursor)\n cursor.next = dummyTail\n\n var introvertCursor = dummyHead.next\n var extrovertCursor: Node = null\n\n val seatNumbers = passengers.map(passenger => {\n if (passenger == '0') {\n val seatNumber = introvertCursor.seat.number\n extrovertCursor = introvertCursor\n introvertCursor = introvertCursor.next\n seatNumber\n } else {\n val seatNumber = extrovertCursor.seat.number\n extrovertCursor.prev.next = extrovertCursor.next\n extrovertCursor.next.prev = extrovertCursor.prev\n extrovertCursor = extrovertCursor.prev\n seatNumber\n }\n }).toArray\n\n return seatNumbers\n\n }\n\n class Seat(val weight: Int, val number: Int) {}\n\n class Node(val seat: Seat, var prev: Node = null, var next: Node = null) {}\n\n}\n"}], "negative_code": [], "src_uid": "161009edb8e3d438cdd8c0d1e202f783"} {"source_code": "\n\nobject CodeforcesRound1392C {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n // 5 3 5 3 5 3 5\n // 5 5 5 5 5 5 5\n // 2 2 2\n\n // 5 4 3 2 1 3 2 5\n // ld=1\n // 5 3 3 2 2 3 2 2 5\n // 5 3 3 2 2 3 3 3 5\n // 5 3 3 2 2 3 2 2 5\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val n = rl_int\n val a = rll_int\n val res: Long = if (n == 0) {\n 0L\n } else {\n val aisorted: Array[Int] = a.zipWithIndex.sortBy(_._1).map(_._2)\n val maxai = aisorted.last\n val maxa = a(maxai)\n var increases: Long = 0L\n for (i <- 1 until n - 1) {\n val j = if (i >= maxai) i + 1 else i - 1\n if (a(i) < a(j)) {\n increases += a(j) - a(i)\n }\n }\n increases += maxa - a(n-1)\n increases\n }\n writer.println(res)\n }\n\n// def equalize0(a: Array[Int]): Long = {\n// val n = a.length\n// val aisorted: Array[Int] = a.zipWithIndex.sortBy(_._1).map(_._2)\n// val maxai = aisorted.last\n// val maxa = a(maxai)\n// var curAiSortedI = 0\n// var curAi = aisorted(curAiSortedI)\n// var increases: Long = 0L\n// while (a(curAi) != maxa) {\n// val ld =\n// if ((curAi == 0) || (a(curAi - 1) - a(curAi)) <= 0) {\n// Integer.MAX_VALUE\n// } else {\n// a(curAi - 1) - a(curAi) // >= 0\n// }\n// val rd =\n// if ((curAi + 1 == n) || (a(curAi + 1) - a(curAi)) <= 0) {\n// Integer.MAX_VALUE\n// } else {\n// a(curAi + 1) - a(curAi) // >= 0\n// }\n// val d = Integer.min(ld, rd)\n// // println(s\"a[$curAi]=${a(curAi)}, ld=$ld, rd=$rd, d=$d, increases0=$increases\")\n// if (d != Integer.MAX_VALUE) {\n// increases += d\n// a(curAi) += d // Not necessary?\n// }\n// curAiSortedI += 1\n// curAi = aisorted(curAiSortedI)\n// }\n// increases\n// }\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}", "positive_code": [{"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextLongs(n)\n var res = 0L\n for (i <- 1 until n) {\n val d = as(i) - as(i - 1)\n if (d < 0) {\n res -= d\n }\n }\n\n out.println(res)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "\n\nobject CodeforcesRound1392C {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n // 5 3 5 3 5 3 5\n // 5 5 5 5 5 5 5\n // 2 2 2\n\n // 5 4 3 2 1 3 2 5\n // ld=1\n // 5 3 3 2 2 3 2 2 5\n // 5 3 3 2 2 3 3 3 5\n // 5 3 3 2 2 3 2 2 5\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val n = rl_int\n val a = rll_int\n val res: Long = if (n == 0) {\n 0L\n } else {\n val aisorted: Array[Int] = a.zipWithIndex.sortBy(_._1).map(_._2)\n val maxai = aisorted.last\n val maxa = a(maxai)\n var increases = 0\n for (i <- 1 until n - 1) {\n val j = if (i >= maxai) i + 1 else i - 1\n if (a(i) < a(j)) {\n increases += a(j) - a(i)\n }\n }\n increases += maxa - a(n-1)\n increases\n }\n writer.println(res)\n }\n\n// def equalize0(a: Array[Int]): Long = {\n// val n = a.length\n// val aisorted: Array[Int] = a.zipWithIndex.sortBy(_._1).map(_._2)\n// val maxai = aisorted.last\n// val maxa = a(maxai)\n// var curAiSortedI = 0\n// var curAi = aisorted(curAiSortedI)\n// var increases: Long = 0L\n// while (a(curAi) != maxa) {\n// val ld =\n// if ((curAi == 0) || (a(curAi - 1) - a(curAi)) <= 0) {\n// Integer.MAX_VALUE\n// } else {\n// a(curAi - 1) - a(curAi) // >= 0\n// }\n// val rd =\n// if ((curAi + 1 == n) || (a(curAi + 1) - a(curAi)) <= 0) {\n// Integer.MAX_VALUE\n// } else {\n// a(curAi + 1) - a(curAi) // >= 0\n// }\n// val d = Integer.min(ld, rd)\n// // println(s\"a[$curAi]=${a(curAi)}, ld=$ld, rd=$rd, d=$d, increases0=$increases\")\n// if (d != Integer.MAX_VALUE) {\n// increases += d\n// a(curAi) += d // Not necessary?\n// }\n// curAiSortedI += 1\n// curAi = aisorted(curAiSortedI)\n// }\n// increases\n// }\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}"}], "src_uid": "0bd06900e42db9f83cdd43c24da6686e"} {"source_code": "\nimport scala.collection.mutable._\n\n//https://codeforces.com/problemset/problem/893/C\nobject Rumor {\n var graph: Array[ArrayBuffer[Int]] = null\n var bribe: Array[Int] = null\n var vis: Array[Boolean] = null\n\n def main(args: Array[String]): Unit = {\n val in = scala.io.StdIn\n var arr = in.readLine().split(\" \").map(_.toInt)\n val n = arr(0)\n val m = arr(1)\n if (m > 1) {\n bribe = in.readLine().split(\" \").map(_.toInt)\n graph = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())\n for (i <- 0 until m) {\n arr = in.readLine().split(\" \").map(_.toInt - 1)\n graph(arr(0)) += arr(1)\n graph(arr(1)) += arr(0)\n }\n var minCost = 0L\n vis = Array.fill[Boolean](n)(false)\n for (i <- 0 until n) {\n if (!vis(i)) {\n val cost = new ArrayBuffer[Int]()\n cost += Int.MaxValue\n //dfs( i, cost)\n bfs(i, cost)\n minCost += cost(0)\n }\n }\n println(minCost)\n } else {\n var minCost = 0L\n println(in.readLine().split(\" \").map(_.toLong).reduce(_ + _))\n }\n }\n\n def bfs(n: Int, minCost: ArrayBuffer[Int]): Unit = {\n val queue = Queue[Int]()\n queue.enqueue(n)\n while (!queue.isEmpty) {\n val u = queue.dequeue()\n vis(u) = true\n minCost(0) = math.min(minCost(0), bribe(u))\n for (v <- 0 until graph(u).length if (!vis(graph(u)(v)))) {\n queue.enqueue(graph(u)(v))\n }\n }\n }\n\n def dfs(n: Int, minCost: ArrayBuffer[Int]): Unit = {\n if (!vis(n)) {\n vis(n) = true\n minCost(0) = math.min(minCost(0), bribe(n))\n for (i <- 0 until graph(n).length if (!vis(graph(n)(i)))) {\n dfs(graph(n)(i), minCost)\n }\n }\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable._\n\n//https://codeforces.com/problemset/problem/893/C\nobject Rumor {\n def main(args: Array[String]): Unit = {\n val in = scala.io.StdIn\n var arr = in.readLine().split(\" \").map(_.toInt)\n val n = arr(0)\n val m = arr(1)\n \n val bribe = in.readLine().split(\" \").map(_.toInt)\n val graph = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())\n for (i <- 0 until m) {\n arr = in.readLine().split(\" \").map(_.toInt - 1)\n graph(arr(0)) += arr(1)\n graph(arr(1)) += arr(0)\n }\n var minCost = 0L\n val vis = Array.fill[Boolean](n)(false)\n for (i <- 0 until n) {\n if (!vis(i)) {\n val cost = new ArrayBuffer[Int]()\n cost += Int.MaxValue\n //dfs(graph,i,vis,bribe, cost)\n bfs(graph,i,vis,bribe, cost)\n minCost += cost(0)\n }\n }\n println(minCost)\n \n }\n\n def bfs(graph:Array[ArrayBuffer[Int]],n: Int,vis:Array[Boolean],bribe:Array[Int],minCost: ArrayBuffer[Int]): Unit = {\n val queue = Queue[Int]()\n queue.enqueue(n)\n while (!queue.isEmpty) {\n val u = queue.dequeue()\n vis(u) = true\n minCost(0) = math.min(minCost(0), bribe(u))\n for (v <- 0 until graph(u).length if (!vis(graph(u)(v)))) {\n queue.enqueue(graph(u)(v))\n }\n }\n }\n\n //DFS is throwing Memory limit exceed\n def dfs(graph:Array[ArrayBuffer[Int]],n: Int,vis:Array[Boolean],bribe:Array[Int],minCost: ArrayBuffer[Int]): Unit = {\n if (!vis(n)) {\n vis(n) = true\n minCost(0) = math.min(minCost(0), bribe(n))\n for (i <- 0 until graph(n).length if (!vis(graph(n)(i)))) {\n dfs(graph,graph(n)(i),vis,bribe, minCost)\n }\n }\n }\n}\n"}, {"source_code": "object Main extends App {\n\n import scala.io.StdIn\n\n val Array(n, m) = StdIn.readLine().split(\" \").map(_.toInt)\n val c = StdIn.readLine().split(\" \").map(_.toInt)\n val g = new Array[List[Int]](n)\n for (i <- 0 until n) g(i) = List()\n val used = new Array[Boolean](n)\n for (i <- 0 until m) {\n var Array(x, y) = StdIn.readLine().split(\" \").map(_.toInt-1)\n g(x) = y :: g(x)\n g(y) = x :: g(y)\n }\n\n var ans = 0l\n for (i <- 0 until n) {\n if (!used(i)) ans += dfs(i)\n }\n\n println(ans)\n\n def dfs(v: Int): Int = {\n used(v) = true\n var res = c(v)\n for (u <- g(v))\n if (!used(u))\n res = Math.min(res, dfs(u))\n res\n }\n\n}\n"}, {"source_code": "import java.io.FileReader\nimport java.util.Comparator\n\nimport collection.Searching._\nimport scala.collection.mutable\n\nobject Solution {\n //Console.setIn(new FileReader(new java.io.File(\"input\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n var caseNo = 1\n val magicMod = 1000000007\n\n class UnionFind(var size : Int){\n var parents = Array.ofDim[Int](size)\n var sizes = Array.ofDim[Int](size)\n\n for (i <- 0 until size) {\n parents(i) = i\n sizes(i) = 1\n }\n\n def findParent(node : Int): Int = {\n var p = node\n while (parents(p) != p) {\n parents(p) = parents(parents(p))\n p = parents(p)\n }\n parents(node) = p\n p\n }\n\n def merge(a : Int, b : Int): Unit = {\n var pA = findParent(a)\n var pB = findParent(b)\n\n if (pA == pB) {\n return\n }\n\n if (sizes(pA) < sizes(pB)) {\n parents(pB) = pA\n sizes(pA) += sizes(pB)\n } else {\n parents(pA) = pB\n sizes(pB) += sizes(pA)\n }\n }\n }\n\n\n def doCase() : Unit = {\n val Array(n, m) = readIntLine()\n val costs = readIntLine()\n\n val uf = new UnionFind(n + 1)\n for (_ <- 0 until m) {\n val Array(f, t) = readIntLine()\n uf.merge(f, t)\n }\n\n var totalCost = 0L\n for ((cost, idx) <- costs.zipWithIndex.map{case (cost, idx) => (cost, idx + 1)}.sorted) {\n if (uf.findParent(idx) != uf.findParent(0)) {\n uf.merge(idx, 0)\n totalCost += cost\n }\n }\n\n println(totalCost)\n\n }\n\n\n def main(args: Array[String]) {\n var tests = 1\n for (test <- 0 until tests) {\n doCase()\n caseNo += 1\n }\n }\n\n def readIntLine(): Array[Int] = {\n readLine().split(\" \").map(_.toInt)\n }\n\n def readLongLine(): Array[Long] = {\n readLine().split(\" \").map(_.toLong)\n }\n\n def readBigIntLine(): Array[BigInt] = {\n readLine().split(\" \").map(BigInt.apply)\n }\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\n\n//https://codeforces.com/problemset/problem/893/C\nobject Rumor {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n var arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n val bribe=in.readLine().split(\" \").map(_.toInt)\n val graph=Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())\n for(i<- 0 until m){\n arr=in.readLine().split(\" \").map(_.toInt-1)\n graph(arr(0))+=arr(1)\n graph(arr(1))+=arr(0)\n }\n var minCost=0\n val vis=Array.fill[Boolean](n)(false)\n for(i<-0 until n){\n if(!vis(i)){\n val cost=new ArrayBuffer[Int]()\n cost+=Int.MaxValue\n dfs(graph,i,vis,bribe,cost)\n minCost+=cost(0)\n }\n }\n println(minCost)\n }\n def dfs(graph:Array[ArrayBuffer[Int]],n:Int,vis:Array[Boolean],bribe:Array[Int],minCost:ArrayBuffer[Int]):Unit={\n if(!vis(n)){\n vis(n)=true\n minCost(0)=math.min(minCost(0),bribe(n))\n for(i<- 0 until graph(n).length if(!vis(graph(n)(i)))){\n dfs(graph,graph(n)(i),vis,bribe,minCost)\n }\n }\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\n//https://codeforces.com/problemset/problem/893/C\nobject Rumor {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n var arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n if(m>1) {\n val bribe = in.readLine().split(\" \").map(_.toInt)\n val graph = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())\n for (i <- 0 until m) {\n arr = in.readLine().split(\" \").map(_.toInt - 1)\n graph(arr(0)) += arr(1)\n graph(arr(1)) += arr(0)\n }\n var minCost = 0L\n val vis = Array.fill[Boolean](n)(false)\n for (i <- 0 until n) {\n if (!vis(i)) {\n val cost = new ArrayBuffer[Int]()\n cost += Int.MaxValue\n dfs(graph, i, vis, bribe, cost)\n minCost += cost(0)\n }\n }\n println(minCost)\n }else{\n var minCost = 0L\n println(in.readLine().split(\" \").map(_.toInt).reduce(_+_))\n }\n }\n def dfs(graph:Array[ArrayBuffer[Int]],n:Int,vis:Array[Boolean],bribe:Array[Int],minCost:ArrayBuffer[Int]):Unit={\n if(!vis(n)){\n vis(n)=true\n minCost(0)=math.min(minCost(0),bribe(n))\n for(i<- 0 until graph(n).length if(!vis(graph(n)(i)))){\n dfs(graph,graph(n)(i),vis,bribe,minCost)\n }\n }\n }\n}\n"}], "src_uid": "9329cb499f003aa71c6f51556bcc7b05"} {"source_code": "object C extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, x, y) = readLine().split(\" \").map(_.toInt)\n\n val ans = (1 to (y - x))\n .collectFirst {\n case d if (y - x) % d == 0 && (y - x + d) / d <= n => d\n }\n .map { d =>\n val ms = x.to(y, d)\n val ls = (x - d).until(0, -d).take(n - ms.length)\n val rs = (y + d).to(n * d, d).take(n - ms.length - ls.length)\n ls ++ ms ++ rs\n }\n .get\n\n println(ans.mkString(\" \"))\n }\n}\n", "positive_code": [{"source_code": "//package codeforces.contests._1409\n\nobject YetAnotherArrayRestoration {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n\n val Array(n, x, y) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val (first, last, diff) = (0 to n - 2).map { i =>\n if ((y - x) % (i + 1) == 0) {\n val d = (y - x) / (i + 1)\n\n @scala.annotation.tailrec\n def loop(j: Int, r: Int = n - 2 - i): Int = if (j <= 0) j + d else if (r == 0) j else loop(j - d, r - 1)\n\n val f = loop(x)\n (f, f + (n - 1) * d, d)\n } else (Int.MaxValue, Int.MaxValue, Int.MaxValue)\n }.minBy(_._2)\n\n println {\n (first to last by diff).mkString(\" \")\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine.toInt\n for (_ <- 0 until t) {\n val arr = StdIn.readLine.split(\" \").map(_.toInt)\n val (n, x, y) = (arr(0), arr(1), arr(2))\n\n def dmax(a: Int, b: Int, d: Int): (Int, Int) = {\n val n1 = (b-a) / d + 1\n if (n1 > n) (Int.MaxValue, d)\n else if (n1 == n) (b, d)\n else {\n val n2 = (a-1) / d\n if (n1 + n2 >= n) (b, d) else {\n ((n-n1-n2) * d + b, d)\n }\n }\n\n }\n\n val (max, d) = (for (i <- 1 to y-x if (y-x) % i == 0) yield dmax(x, y, i)).minBy(_._1)\n\n val r = (max - (n-1)*d to max by d).mkString(\" \")\n println(r)\n }\n }\n}\n"}], "negative_code": [], "src_uid": "ca9d97e731e86cf8223520f39ef5d945"} {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val en = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val c = en.sorted\n .foldLeft((0L, 0L)) {\n case ((c, r), i) =>\n (c + (r + 1) / i, (r + 1) % i)\n }\n ._1\n\n println(c)\n }\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Main extends App {\n\n val s = new Scanner(System.in)\n\n var t = s.nextInt()\n\n for(_ <- 0 until t) {\n\n val n = s.nextInt()\n val es = Array.fill(n)(s.nextInt())\n scala.util.Sorting.quickSort(es)\n\n var i = 0\n var groups = 0\n\n while(i < n) {\n var gs = es(i) // requested group size\n var formed = false // did we formed the group?\n var j = i + gs - 1 // index pointing to last member of considered group\n\n while(j < n && !formed) {\n if (es(j) == gs) {\n formed = true\n i = j + 1\n } else {\n gs = es(j)\n j = i + gs - 1\n }\n }\n\n if(formed) {\n groups += 1\n } else {\n i = n\n }\n }\n\n println(groups)\n }\n}\n"}, {"source_code": "object ProblemB extends App {\n\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n import scala.collection.mutable\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n\n for (_ <- 1 to t) {\n val n = in.nextInt()\n val arr = new Array[Int](n + 1)\n for (i <- 0 until n) {\n val ei = in.nextInt()\n arr(ei) = arr(ei) + 1\n }\n var result = 0\n\n var currentSum = 0\n\n for (i <- 1 to n) {\n currentSum = currentSum + arr(i)\n val newGroupCount = currentSum / i\n currentSum = currentSum - newGroupCount * i\n result = result + newGroupCount\n }\n\n println(result)\n }\n\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C643B(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C643B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val T = ni()\n REP(T) { _ =>\n val N = ni()\n val cnt = Array.fill[Int](N+1)(0)\n REP(N) { i =>\n cnt(ni()) += 1\n }\n\n var ans = 0L\n var rm = 0L\n REP(N+1) { i =>\n if(i > 0) {\n val x = cnt(i) + rm\n ans += (x / i)\n rm = x % i\n }\n }\n out.println(ans)\n }\n }\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nobject Main extends App {\n\n val s = new Scanner(System.in)\n\n var t = s.nextInt()\n\n for(_ <- 0 until t) {\n\n val n = s.nextInt()\n\n val es = Array.fill(n)(s.nextInt())\n val ess = es.sorted(Ordering[Int].reverse)\n\n var i = 0\n var groups = 0\n\n while(i < n) {\n i += ess(i)\n groups += 1\n }\n\n println(groups)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main extends App {\n\n val s = new Scanner(System.in)\n\n var t = s.nextInt()\n\n for(_ <- 0 until t) {\n\n val n = s.nextInt()\n\n val es = Array.fill(n)(s.nextInt())\n val ess = es.sorted(Ordering[Int].reverse)\n\n var i = 0\n var groups = 0\n\n while(i < n) {\n i += ess(i)\n groups += 1\n }\n\n print(groups)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C643B(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C643B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val T = ni()\n REP(T) { _ =>\n val N = ni()\n val cnt = Array.fill[Int](N+1)(0)\n REP(N) { i =>\n cnt(ni()) += 1\n }\n \n var ans = 0L\n REP(N) { i =>\n if(i > 0) ans += (cnt(i) / i)\n }\n out.println(ans)\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C643B(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C643B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val T = ni()\n REP(T) { _ =>\n val N = ni()\n val cnt = Array.fill[Int](N+1)(0)\n REP(N) { i =>\n cnt(ni()) += 1\n }\n\n var ans = 0L\n var rm = 0L\n REP(N) { i =>\n if(i > 0) {\n ans += (cnt(i) / i)\n val x = cnt(i) % i\n if(x + rm >= i) {\n ans +=1\n rm = x + rm - i\n } else rm += x\n }\n }\n out.println(ans)\n }\n }\n}\n"}], "src_uid": "8e766dea94dc2033ba2d5759d7e5cd80"} {"source_code": "object E{\n import scala.collection.mutable.Queue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val n=nextInt\n val m=nextInt\n val A=Array.fill(n)(0)\n val B=Array.fill(n)(0)\n for(i<-0 until n){\n A(i)=nextInt\n }\n for(i<-0 until n){\n B(i)=nextInt\n }\n val nE=2*n+2\n val c=Array.ofDim[Int](nE,nE)\n\n val inf=Int.MaxValue\n //source\n for(i<-0 until n){\n if(A(i)>B(i)){\n //source\n c(2*n)(2*i)=A(i)-B(i)\n }\n else{\n c(2*i)(2*n+1)=B(i)-A(i)\n }\n c(2*i)(2*i+1)=A(i)\n }\n for(_<-0 until m){\n val i=nextInt-1\n val j=nextInt-1\n c(2*i+1)(2*j)=inf\n c(2*j+1)(2*i)=inf\n }\n def maximumFlow(c:Array[Array[Int]],source:Int,sink:Int):Array[Array[Int]]={\n val n=c.size\n val cr=Array.ofDim[Int](n,n)\n val f=Array.ofDim[Int](n,n)\n def shortestPath():Array[Int]={\n val s=Array.fill(n)(-1)\n\n val q=Queue[Int]()\n q+=source\n breakable{\n while(!q.isEmpty){\n\n val p=q.dequeue\n for(i<-0 until n){\n if(cr(p)(i)>0&&s(i)== -1){\n s(i)=p\n if(i==sink){\n break\n }\n q+=i\n }\n }\n }\n }\n if(s(sink)== -1){\n return Array[Int]()\n }\n else{\n return s\n }\n }\n for(i<-0 until n){\n for(j<-0 until n){\n if(c(i)(j)>0){\n cr(i)(j)=c(i)(j)\n }\n }\n }\n var s=shortestPath\n while(s.size>0){\n\n\n\n var p=sink\n var min=Int.MaxValue\n while(p!=source){\n min=Math.min(min,cr(s(p))(p))\n p=s(p)\n\n }\n p=sink\n while(p!=source){\n if(c(s(p))(p)>0){\n f(s(p))(p)+=min\n }else{\n f(p)(s(p))-=min\n }\n //out.println(s\"${s(p)->p}\")\n cr(s(p))(p)-=min\n cr(p)(s(p))+=min\n p=s(p)\n }\n// out.println(min)\n s=shortestPath\n }\n return f\n }\n val f=maximumFlow(c,2*n,2*n+1)\n// for(i<-f){for(j<-i){out.print(j+\" \")};out.println()}\n var solve=true\n for(i<-0 until n){\n if(f(2*n)(2*i)B(i)){\n //source\n c(2*n)(2*i)=A(i)-B(i)\n }\n else{\n c(2*i)(2*n+1)=B(i)-A(i)\n }\n c(2*i)(2*i+1)=A(i)\n }\n for(_<-0 until m){\n val i=nextInt-1\n val j=nextInt-1\n c(2*i+1)(2*j)=inf\n c(2*j+1)(2*i)=inf\n }\n def maximumFlow(c:Array[Array[Int]],source:Int,sink:Int):Array[Array[Int]]={\n val n=c.size\n val cr=Array.ofDim[Int](n,n)\n val f=Array.ofDim[Int](n,n)\n def shortestPath():Array[Int]={\n val s=Array.fill(n)(-1)\n\n val q=Queue[Int]()\n q+=source\n breakable{\n while(!q.isEmpty){\n\n val p=q.dequeue\n for(i<-0 until n){\n if(cr(p)(i)>0&&s(i)== -1){\n s(i)=p\n if(i==sink){\n break\n }\n q+=i\n }\n }\n }\n }\n if(s(sink)== -1){\n return Array[Int]()\n }\n else{\n return s\n }\n }\n for(i<-0 until n){\n for(j<-0 until n){\n if(c(i)(j)>0){\n cr(i)(j)=c(i)(j)\n }\n }\n }\n var s=shortestPath\n while(s.size>0){\n\n\n\n var p=sink\n var min=Int.MaxValue\n while(p!=source){\n min=Math.min(min,cr(s(p))(p))\n p=s(p)\n\n }\n p=sink\n while(p!=source){\n if(c(s(p))(p)>0){\n f(s(p))(p)+=min\n }else{\n f(p)(s(p))-=min\n }\n //out.println(s\"${s(p)->p}\")\n cr(s(p))(p)-=min\n cr(p)(s(p))+=min\n p=s(p)\n }\n// out.println(min)\n s=shortestPath\n }\n return f\n }\n val f=maximumFlow(c,2*n,2*n+1)\n// for(i<-f){for(j<-i){out.print(j+\" \")};out.println()}\n var solve=true\n for(i<-0 until n){\n if(f(2*n)(2*i)B(i)){\n //source\n c(2*n)(2*i)=A(i)-B(i)\n }\n else{\n c(2*i)(2*n+1)=B(i)-A(i)\n }\n c(2*i)(2*i+1)=A(i)\n }\n for(_<-0 until m){\n val i=nextInt-1\n val j=nextInt-1\n c(2*i+1)(2*j)=inf\n c(2*j+1)(2*i)=inf\n }\n def maximumFlow(c:Array[Array[Int]],source:Int,sink:Int):Array[Array[Int]]={\n val n=c.size\n val cr=Array.ofDim[Int](n,n)\n val f=Array.ofDim[Int](n,n)\n def shortestPath():Array[Int]={\n val s=Array.fill(n)(-1)\n\n val q=Queue[Int]()\n q+=source\n breakable{\n while(!q.isEmpty){\n\n val p=q.dequeue\n for(i<-0 until n){\n if(cr(p)(i)>0&&s(i)== -1){\n s(i)=p\n if(i==sink){\n break\n }\n q+=i\n }\n }\n }\n }\n if(s(sink)== -1){\n return Array[Int]()\n }\n else{\n return s\n }\n }\n for(i<-0 until n){\n for(j<-0 until n){\n if(c(i)(j)>0){\n cr(i)(j)=c(i)(j)\n }\n }\n }\n var s=shortestPath\n while(s.size>0){\n\n\n\n var p=sink\n var min=Int.MaxValue\n while(p!=source){\n min=Math.min(min,cr(s(p))(p))\n p=s(p)\n\n }\n p=sink\n while(p!=source){\n if(c(s(p))(p)>0){\n f(s(p))(p)+=min\n }else{\n f(p)(s(p))-=min\n }\n //out.println(s\"${s(p)->p}\")\n cr(s(p))(p)-=min\n cr(p)(s(p))+=min\n p=s(p)\n }\n// out.println(min)\n s=shortestPath\n }\n return f\n }\n val f=maximumFlow(c,2*n,2*n+1)\n// for(i<-f){for(j<-i){out.print(j+\" \")};out.println()}\n var solve=true\n for(i<-0 until n){\n if(f(2*n)(2*i)=0,\"currIndex out of bounds\")\n var j = currIndex + 1\n while(j < a.length && a(j)._2 != letter){\n j = j+1\n }\n j\n }\n //which letter didn't show up in the sequence yet?\n def returnMissing(s:String) ={\n assert(s.length ==2)\n if(!s.contains(\"A\")){\"A\"}else\n if(!s.contains(\"B\")){\"B\"}else{\"C\"}\n }\n\n def currAndPrevSymbol(a:Array[(Int,String)],j:Int,prevState:String)={\n\n (a(j)._2, prevState) match {\n case (_,\"\") => a(j)._2\n case (_,s2) if s2.length == 1 => s2+a(j)._2\n case (s1,s2) if s1==s2(1).toString => prevState//A BA-> BA\n case (s1,s2) if s1!=s2(1).toString => s2(1)+a(j)._2\n }\n }\n\n def mainFun(a:Array[(Int,String)],f:(Long,Long,Long)=>Long):Long={\n var mainCounter = 0 //main counter\n\n var lastA = -1\n var lastB = -1\n var lastC = -1\n\n var nextZ = -1\n\n var currentBlockPrefix = \"\" //first two letters eg AB\n var nextSymbol = \"\" // eg if current block AB then C is missing\n\n var minVal = Long.MaxValue\n var currentVal = Long.MaxValue\n\n def lastX(letter:Char)={\n letter match{\n case 'A' => lastA\n case 'B' => lastB\n case 'C' => lastC\n }\n }\n\n while(mainCounter=1 && mainCounter(x,\"A\"))\n val b = b0.map(x=>(x,\"B\"))\n val c = c0.map(x=>(x,\"C\"))\n\n val concat = (a++b++c).sortBy(_._1)\n //println(concat.map(x=>s\"${x._1} ${x._2}\").mkString(\",\"))\n println(mainFun(concat,f))\n }\n //val Array(nA,nB,nC) = lines(1).split(' ')\n\n //val a = line()\n //println(s\"${nA} ${nB} ${nC}\")\n }\n\n def main(args:Array[String]): Unit ={\n\n //val lines = str.split(\"\\n\")\n val t = readLine.trim.toInt\n //println(t) //1<= t <100\n def f(x:Long,y:Long,z:Long):Long = (x-y)*(x-y)+(y-z)*(y-z)+(z-x)*(z-x)\n for(i <-(0 to t-1)){\n val Array(nA,nB,nC) = readLine.trim.split(\" \")\n //println(s\"${nA} ${nB} ${nC}\")\n val a0 = readLine.trim.split(\" \").map(_.toInt)\n val b0 = readLine.trim.split(\" \").map(_.toInt)\n val c0 = readLine.trim.split(\" \").map(_.toInt)\n //println(a0.mkString(\",\"))\n //println(b0.mkString(\",\"))\n //println(c0.mkString(\",\"))\n val a = a0.map(x=>(x,\"A\"))\n val b = b0.map(x=>(x,\"B\"))\n val c = c0.map(x=>(x,\"C\"))\n\n val concat = (a++b++c).sortBy(_._1)\n //println(concat.map(x=>s\"${x._1} ${x._2}\").mkString(\",\"))\n println(mainFun(concat,f))\n }\n }\n\n}\nobject C1336Tests extends App{\n import C1336._\n\n //val a: Array[(Int,String)]= Array((0,\"C\"),(0,\"A\"),(1,\"B\"),(5,\"B\"),(9,\"B\"),(10,\"C\"))\n val a: Array[(Int,String)]= Array((0,\"A\"),(1,\"B\"),(5,\"B\"),(10,\"C\"),(20,\"A\"))\n\n def runTests(): Unit ={\n //2 error found thx to this\n //println(moveToNext(a,\"C\",0)==5)\n //println(moveToNext(a,\"B\",0)==2)\n //println(moveToNext(a,\"B\",2)==3)\n //println(moveToNext(a,\"C\",5)==6)\n\n //println(returnMissing(\"AB\")==\"C\")\n //println(returnMissing(\"BC\")==\"A\")\n //println(returnMissing(\"CA\")==\"B\")\n\n //for(i <- 1 to a.length-1){\n // print(currAndPrevSymbol(a,i))\n // print(\",\")\n //}\n //CABBBC\n //println(currAndPrevSymbol(a,0,\"\")==\"C\")\n //println(currAndPrevSymbol(a,1,\"C\")==\"CA\")\n //println(currAndPrevSymbol(a,2,\"CA\")==\"AB\")\n //println(currAndPrevSymbol(a,3,\"AB\") ==\"AB\")\n //println(currAndPrevSymbol(a,4,\"AB\") ==\"AB\")\n //println(currAndPrevSymbol(a,5,\"AB\")==\"BC\")\n //println(currAndPrevSymbol(a,6,\"C\")==\"CA\")\n //def f(x:Int,y:Int,z:Int) = (x-y)*(x-y)+(y-z)*(y-z)+(z-x)*(z-x)\n //mainFun(a,f)\n val input = \"\"\"5\n 2 2 3\n 7 8\n 6 3\n 3 1 4\n 1 1 1\n 1\n 1\n 1000000000\n 2 2 2\n 1 2\n 5 4\n 6 7\n 2 2 2\n 1 2\n 3 4\n 6 7\n 3 4 1\n 3 2 1\n 7 3 3 4\n 6\"\"\"\n CalcFromInput(input)\n\n }\n runTests()\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Solution_D extends App {\n val T = StdIn.readInt()\n\n def getCurrent(a0: Array[Long], a1: Array[Long], a2: Array[Long], positions: Array[Int]): Long = {\n val x = a0(positions(0)) - a1(positions(1))\n val y = a0(positions(0)) - a2(positions(2))\n val z = a1(positions(1)) - a2(positions(2))\n x * x + y * y + z * z\n }\n\n def findBestMove(a0: Array[Long], a1: Array[Long], a2: Array[Long], positions: Array[Int]): Int = {\n val current = getCurrent(a0, a1, a2, positions)\n var bestIdx = -1\n var bestSoFar = Long.MaxValue\n val sizes = Array(a0.size, a1.size, a2.size)\n for (pos <- 0 until 3) {\n if (positions(pos) < sizes(pos) - 1) {\n positions(pos) += 1\n val move = getCurrent(a0, a1, a2, positions)\n if (move - current < bestSoFar) {\n bestSoFar = move - current\n bestIdx = pos\n }\n positions(pos) -= 1\n }\n }\n bestIdx\n }\n for (t <- 1 to T) {\n val input = StdIn.readLine().split(' ').map{_.toInt}\n val Nr = input(0)\n val Ng = input(1)\n val Nb = input(2)\n val a0 = StdIn.readLine().split(' ').map{_.toLong}.sorted\n val a1 = StdIn.readLine().split(' ').map{_.toLong}.sorted\n val a2 = StdIn.readLine().split(' ').map{_.toLong}.sorted\n val positions = Array(0, 0, 0)\n var stop = false\n var result = getCurrent(a0, a1, a2, positions)\n while (!stop) {\n val best = findBestMove(a0, a1, a2, positions)\n if (best == -1) {\n stop = true\n } else {\n positions(best) += 1\n result = Math.min(result, getCurrent(a0, a1, a2, positions))\n }\n }\n println(result)\n }\n}\n"}], "negative_code": [], "src_uid": "79b58eb781cd73ccf7994866b9a8b695"} {"source_code": "\n\nobject C {\n\n case class Rect(x1: Long, y1: Long, x2: Long, y2: Long)\n\n def splitV1(r: Rect, x: Int) = {\n if (x >= r.x2 || x <= r.x1) {\n Array(r)\n } else {\n Array(r.copy(x2 = x), r.copy(x1=x))\n }\n }\n\n def splitH1(r: Rect, y: Int) = {\n if (y >= r.y2 || y <= r.y1) {\n Array(r)\n } else {\n Array(r.copy(y2 = y), r.copy(y1=y))\n }\n }\n\n def splitV(r: Array[Rect], x: Int) = {\n r.flatMap(r => splitV1(r, x))\n }\n\n def splitH(r: Array[Rect], y: Int) = {\n r.flatMap(r => splitH1(r, y))\n }\n\n def in(r: Rect, o: Rect) = {\n if (r.x2 <= o.x2 && r.x1 >= o.x1 && r.y2 <= o.y2 && r.y1 >= o.y1) true\n else false\n }\n\n def getWhites(r: Rect) = {\n val a = r.x2 - r.x1\n val b = r.y2 - r.y1\n val t = (a * b)\n if (t % 2 == 0) {\n t / 2\n } else {\n if ((r.x1 + r.y1) % 2 == 0) {\n t / 2 + 1\n } else {\n t / 2\n }\n }\n }\n\n def main(args: Array[String]) = {\n val scanner = new java.util.Scanner(System.in)\n val t = scanner.nextInt\n (0 until t).foreach{_ =>\n val (n, m) = (scanner.nextInt(), scanner.nextInt())\n val (x1,y1,x2,y2) = (scanner.nextInt(), scanner.nextInt(), scanner.nextInt(), scanner.nextInt())\n val (x3,y3,x4,y4) = (scanner.nextInt(), scanner.nextInt(), scanner.nextInt(), scanner.nextInt())\n var rects = Array(Rect(1, 1, m+1, n+1))\n rects = splitV(rects, x = x1)\n rects = splitV(rects, x = x2+1)\n rects = splitV(rects, x = x3)\n rects = splitV(rects, x = x4+1)\n rects = splitH(rects, y = y1)\n rects = splitH(rects, y = y2+1)\n rects = splitH(rects, y = y3)\n rects = splitH(rects, y = y4+1)\n val white = Rect(x1, y1, x2+1, y2+1)\n val black = Rect(x3, y3, x4+1, y4+1)\n val (w, b) = rects.map{r =>\n val s = (r.x2 - r.x1) * (r.y2 - r.y1)\n if (in(r, black)) {\n (0L, s)\n } else if (in(r, white)) {\n (s, 0L)\n } else {\n val w = getWhites(r)\n (w, s-w)\n }\n }.reduce((a, b) => (a._1 + b._1, a._2 + b._2))\n System.out.println(w + \" \" + b)\n }\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Rect(x1: Int, y1: Int, x2: Int, y2: Int)\n\n def solve(): Unit = {\n\n /**\n * @return (white, black)\n */\n def count(r: Rect): (Long, Long) = {\n val s = max(0, r.x2 - r.x1 + 1).toLong * max(0, r.y2 - r.y1 + 1)\n if (s == 0) (0, 0)\n else if (s % 2 == 0) (s / 2, s / 2)\n else {\n // 0 == white, 1 == black\n def tpe(x: Int, y: Int): Int = {\n if (y % 2 == 1) {\n if (x % 2 == 1) 0\n else 1\n } else {\n if (x % 2 == 1) 1\n else 0\n }\n }\n\n tpe(r.x1, r.y1) match {\n case 0 => (s / 2 + 1, s / 2)\n case 1 => (s / 2, s / 2 + 1)\n }\n }\n }\n\n rep(ni()) { _ =>\n val n, m = ni()\n val x1, y1, x2, y2 = ni()\n val x3, y3, x4, y4 = ni()\n\n val wRec = Rect(x1, y1, x2, y2)\n val bRec = Rect(x3, y3, x4, y4)\n\n val dupRec = {\n val l = max(x1, x3)\n val r = min(x2, x4)\n val b = max(y1, y3)\n val t = min(y2, y4)\n Rect(l, b, r, t)\n }\n\n val (bw, bb) = count(bRec)\n val (ww, wb) = count(wRec)\n val (dw, db) = count(dupRec)\n\n val s = n.toLong * m\n val b = s / 2 + bw - (wb - db)\n val w = s - b\n out.println(s\"$w $b\")\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Rect(x1: Int, y1: Int, x2: Int, y2: Int)\n\n def solve(): Unit = {\n\n /**\n * @return (white, black)\n */\n def count(r: Rect): (Long, Long) = {\n val s = (r.x2 - r.x1 + 1).toLong * (r.y2 - r.y1 + 1)\n if (s % 2 == 0) (s / 2, s / 2)\n else {\n // 0 == white, 1 == black\n def tpe(x: Int, y: Int): Int = {\n if (y % 2 == 1) {\n if (x % 2 == 1) 0\n else 1\n } else {\n if (x % 2 == 1) 1\n else 0\n }\n }\n\n tpe(r.x1, r.y1) match {\n case 0 => (s / 2 + 1, s / 2)\n case 1 => (s / 2, s / 2 + 1)\n }\n }\n }\n\n rep(ni()) { _ =>\n val n, m = ni()\n val x1, y1, x2, y2 = ni()\n val x3, y3, x4, y4 = ni()\n\n val wRec = Rect(x1, y1, x2, y2)\n val bRec = Rect(x3, y3, x4, y4)\n\n val dupRec = {\n val l = max(x1, x3)\n val r = min(x2, x4)\n val b = max(y1, y3)\n val t = min(y2, y4)\n Rect(l, b, r, t)\n }\n\n val (bw, bb) = count(bRec)\n val (ww, wb) = count(wRec)\n val (rw, rb) = count(dupRec)\n\n val s = n.toLong * m\n val b = s / 2 + bw - (wb - rb)\n val w = s - b\n out.println(s\"$w $b\")\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Rect(x1: Int, y1: Int, x2: Int, y2: Int)\n\n def solve(): Unit = {\n\n /**\n * @return (white, black)\n */\n def count(r: Rect): (Long, Long) = {\n val s = (r.x2 - r.x1 + 1).toLong * (r.y2 - r.y1 + 1)\n if (s < 0) (0, 0)\n else if (s % 2 == 0) (s / 2, s / 2)\n else {\n // 0 == white, 1 == black\n def tpe(x: Int, y: Int): Int = {\n if (y % 2 == 1) {\n if (x % 2 == 1) 0\n else 1\n } else {\n if (x % 2 == 1) 1\n else 0\n }\n }\n\n tpe(r.x1, r.y1) match {\n case 0 => (s / 2 + 1, s / 2)\n case 1 => (s / 2, s / 2 + 1)\n }\n }\n }\n\n rep(ni()) { _ =>\n val n, m = ni()\n val x1, y1, x2, y2 = ni()\n val x3, y3, x4, y4 = ni()\n\n val wRec = Rect(x1, y1, x2, y2)\n val bRec = Rect(x3, y3, x4, y4)\n\n val dupRec = {\n val l = max(x1, x3)\n val r = min(x2, x4)\n val b = max(y1, y3)\n val t = min(y2, y4)\n Rect(l, b, r, t)\n }\n\n val (bw, bb) = count(bRec)\n val (ww, wb) = count(wRec)\n val (dw, db) = count(dupRec)\n\n val s = n.toLong * m\n val b = s / 2 + bw - (wb - db)\n val w = s - b\n out.println(s\"$w $b\")\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "1c4607c96f7755af09445ff29a54bd08"} {"source_code": "/**\n * Created by Hyper on 22.06.2017.\n */\nimport javax.imageio.spi.ServiceRegistry.Filter\n\nimport scala.io.StdIn\nobject cf extends App{\n type Linst = List[Int]\n def findDifferences (a: Linst, b: Linst, i: Int): List[(Int,Int,Int)] ={\n (a,b) match {\n case (u :: utail, v :: vtail) => if( u == v ) findDifferences(utail, vtail, i + 1) else (u,v,i) :: findDifferences(utail, vtail, i + 1)\n case (Nil, Nil) => Nil\n }\n }\n def printList(a: Linst):Any ={\n a match{\n case Nil => None\n case b::tail => print(b + \" \"); printList(tail)\n }\n }\n def replace(b: List[Int], byWhat: Int, idx: Int): List[Int] ={\n val t = b.splitAt(idx)\n t._1 ++ List(byWhat) ++ t._2.tail\n }\n def existsDup(b: Linst, num: Int, pos: Int, currPos: Int): Boolean ={\n b match {\n case Nil => false\n case `num` :: tail => if(currPos != pos) true else existsDup(tail, num, pos, currPos + 1)\n case a :: tail => existsDup(tail, num, pos, currPos + 1)\n }\n }\n def fixTransposition(a: Linst, num: Int, pos: Int):Linst={\n val nats = Stream.from(1,1).take(a.length).toList\n val drop = nats.filter(v => !a.contains(v)).head\n replace(a, drop, pos - 1)\n }\n def fixTransposition2(a: Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) ={\n val nats = Stream.from(1,1).take(a.length).toList\n val drop = nats.filter(v => !a.contains(v)).head\n if (existsDup(a, num1, pos1, 1)) replace(a, drop, pos1 - 1)\n else replace(a, drop, pos2 - 1)\n }\n val n = StdIn.readLine().toInt\n val A = StdIn.readLine().split(\" \").toList.map(s => s.toInt)\n val B = StdIn.readLine().split(\" \").toList.map(s => s.toInt)\n val diff = findDifferences(A,B,1)\n println()\n diff.length match {\n case 1 => printList(fixTransposition(A, diff.head._1, diff.head._3))\n case 2 => {if(diff.head._2 == diff.tail.head._2)printList(fixTransposition2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3))\n else printList(fixTransposition2(B, diff.head._2, diff.head._3, diff.tail.head._2, diff.tail.head._3))}\n\n }\n}\n\n", "positive_code": [{"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextBoolean: Boolean = next.equalsIgnoreCase(\"1\")\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n\n override def toString = s\"MultiHashSet($map)\"\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n *\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def test(ans: Array[Int], a: Array[Int]): Boolean = {\n var diff = 0\n for (i <- 0 until ans.length) {\n if (ans(i) != a(i)) {\n diff += 1\n }\n }\n diff == 1\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n val b = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n }\n val set = new mutable.HashSet[Int]()\n for (i <- 0 until n) {\n b(i) = nextInt\n set += (i + 1)\n }\n val ans = new Array[Int](n)\n for (i <- 0 until n) {\n if (a(i) == b(i)) {\n ans(i) = a(i)\n set -= (ans(i))\n }\n }\n val firstPos = ans.indexOf(0)\n val remains = set.iterator.toList\n if (set.size == 1) {\n ans(firstPos) = remains.head\n } else if (set.size == 2) {\n ans(firstPos) = remains.head\n val lastPos = ans.lastIndexOf(0)\n ans(lastPos) = remains.last\n if (test(ans, a) && test(ans, b)) { \n } else {\n ans(firstPos) = remains.last\n ans(lastPos) = remains.head\n }\n }\n ans.foreach(x => print(s\"$x \"))\n return 0\n }\n}\n"}, {"source_code": "\nobject EightOneFourB {\n def checkIfAllElementPresent(seq: Seq[Int]): Boolean = {\n val list = (1 to seq.size + 1).toArray.map(_ => 0)\n list(0) = 1\n seq.foreach(p => list(p) = 1)\n list.filter(_ == 0).size == 0\n }\n\n def findTheMissingElement(seq: Seq[Int]): Option[Int] = {\n val list = (1 to seq.size + 1).toArray.map(_ => 0)\n list(0) = 1\n seq.foreach(p => list(p) = 1)\n val result = list.zipWithIndex.filter(p => p._1 == 0)\n if (result.size > 0) Some(result.head._2) else None\n }\n\n def main(args: Array[String]): Unit = {\n val input = readLine()\n val stringA = readLine().toString.split(\" \").map(_.toInt)\n val stringB = readLine().toString.split(\" \").map(_.toInt)\n val missingAElement = findTheMissingElement(stringA)\n val missingBElement = findTheMissingElement(stringB)\n\n val permutations = stringA.zip(stringB).zipWithIndex\n .filter {\n case ((a, b), index) => {\n a != b\n }\n }\n .flatMap {\n case ((a, b), index) => {\n List(stringA.patch(index, List(missingAElement.getOrElse(a)), 1)\n , stringB.patch(index, List(missingBElement.getOrElse(b)), 1))\n }\n }\n\n println(permutations\n .filter(checkIfAllElementPresent(_))\n .filter(stringA.zip(_).filter(p => p._1 != p._2).size <= 1)\n .filter(stringB.zip(_).filter(p => p._1 != p._2).size <= 1)\n .head.mkString(\" \"))\n }\n}\n"}, {"source_code": "/**\n * Created by Hyper on 22.06.2017.\n */\nimport javax.imageio.spi.ServiceRegistry.Filter\n\nimport scala.io.StdIn\nobject cf extends App{\n type Linst = List[Int]\n type Lin3st = List[(Int,Int,Int)]\n /* def findDifferences (a: Linst, b: Linst, i: Int): List[(Int,Int,Int)] ={\n (a,b) match {\n case (u :: utail, v :: vtail) => if( u == v ) findDifferences(utail, vtail, i + 1) else (u,v,i) :: findDifferences(utail, vtail, i + 1)\n case (Nil, Nil) => Nil\n }\n } // перекодено\n def replace(b: List[Int], byWhat: Int, idx: Int): List[Int] ={\n val t = b.splitAt(idx)\n t._1 ++ List(byWhat) ++ t._2.tail\n } //перекодено*/\ndef repl(b:Linst,e:Int,idx:Int):Linst = b.foldRight[(Linst,Int)](Nil,b.length-1)((i,T) => ((if(T._2 == idx) e else i) :: T._1,T._2 - 1))._1\ndef findDrop(b:Linst) = nats.filter(v => !b.contains(v)).head\ndef dupExists(d:Linst, e: Int, p:Int) = d.foldLeft[(Boolean,Int)]((false,0))((T,i) => (if(T._1)true else i == e && p != T._2,T._2 + 1))._1\n/* def existsDup(b: Linst, num: Int, pos: Int, currPos: Int): Boolean ={\n b match {\n case Nil => false\n case `num` :: tail => if(currPos != pos) true else existsDup(tail, num, pos, currPos + 1)\n case a :: tail => existsDup(tail, num, pos, currPos + 1)\n }\n}//перекодено\ndef fixTransposition(a: Linst, num: Int, pos: Int):Linst={\n val nats = Stream.from(1,1).take(a.length).toList\n val drop = nats.filter(v => !a.contains(v)).head\n replace(a, drop, pos - 1)\n } // перекодено\n def fixTransposition2(a: Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) ={\n val nats = Stream.from(1,1).take(a.length).toList\n val drop = nats.filter(v => !a.contains(v)).head\n if (existsDup(a, num1, pos1, 1)) replace(a, drop, pos1 - 1)\n else replace(a, drop, pos2 - 1)\n } // на очереди*/\ndef fixTransp2(a:Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) = repl(a,findDrop(a), if(dupExists(a,num1,pos1)) pos1 else pos2)\nval n = StdIn.readLine().toInt\nval nats = Stream.from(1,1).take(n).toList\nval A = StdIn.readLine().split(\" \").toList.map(s => s.toInt)\nval B = StdIn.readLine().split(\" \").toList.map(s => s.toInt)\nval diff = A.foldLeft[(Lin3st,Linst,Int)]((Nil,B,0))((T,i)=>(if(T._2.head != i)(i,T._2.head,T._3) :: T._1 else T._1,T._2.tail,T._3+1))._1\nprintln((if(diff.length == 1) repl(A,findDrop(A),diff.head._3)\nelse if(diff.head._2 == diff.tail.head._2) fixTransp2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3)\nelse fixTransp2(B, diff.head._2, diff.head._3, diff.tail.head._2, diff.tail.head._3)).mkString(\" \"))\n/*val AB = for(\n i <- nats;\n a <- A;\n b <- B\n) yield (a,b,i)*/\n\n/* val diff = findDifferences(A,B,1)\nprintln(\ndiff.length match {\n case 1 => fixTransposition(A, diff.head._1, diff.head._3).mkString(\" \")\n case 2 => {if(diff.head._2 == diff.tail.head._2)fixTransposition2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3)\n else fixTransposition2(B, diff.head._2, diff.head._3, diff.tail.head._2, diff.tail.head._3)}.mkString(\" \")\n\n}\n)*/\n}\n\n"}], "negative_code": [{"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextBoolean: Boolean = next.equalsIgnoreCase(\"1\")\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n\n override def toString = s\"MultiHashSet($map)\"\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n *\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n val b = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n }\n val set = new mutable.HashSet[Int]()\n for (i <- 0 until n) {\n b(i) = nextInt\n set += (i + 1)\n }\n val ans = new Array[Int](n)\n for (i <- 0 until n) {\n if (a(i) == b(i)) {\n ans(i) = a(i)\n set -= (ans(i))\n }\n }\n if (set.size == 1) {\n ans(ans.indexOf(0)) = set.iterator.toList.head\n } else if (set.size == 2) {\n ans(ans.indexOf(0)) = set.iterator.toList.head\n ans(ans.lastIndexOf(0)) = set.iterator.toList.last\n } else {\n throw new RuntimeException()\n }\n ans.foreach(x => print(s\"$x \"))\n return 0\n }\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextBoolean: Boolean = next.equalsIgnoreCase(\"1\")\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n\n override def toString = s\"MultiHashSet($map)\"\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n *\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def test(ans: Array[Int], a: Array[Int]): Boolean = {\n var diff = 0\n for (i <- 0 until ans.length) {\n if (ans(i) != a(i)) {\n diff += 1\n }\n }\n diff == 1\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n val b = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n }\n val set = new mutable.HashSet[Int]()\n for (i <- 0 until n) {\n b(i) = nextInt\n set += (i + 1)\n }\n val ans = new Array[Int](n)\n for (i <- 0 until n) {\n if (a(i) == b(i)) {\n ans(i) = a(i)\n set -= (ans(i))\n }\n }\n val firstPos = ans.indexOf(0)\n val remains = set.iterator.toList\n if (set.size == 1) {\n ans(firstPos) = remains.head\n } else if (set.size == 2) {\n ans(firstPos) = remains.head\n val lastPos = ans.lastIndexOf(0)\n ans(lastPos) = remains.last\n if (test(ans, a) || test(ans, b)) {\n ans(firstPos) = remains.last\n ans(lastPos) = remains.head\n }\n } \n ans.foreach(x => print(s\"$x \"))\n return 0\n }\n}\n"}, {"source_code": "object EightOneFourB {\n def checkIfAllElementPresent(seq: Seq[Int]): Boolean = {\n val list = (1 to seq.size + 1).toArray.map(_ => 0)\n list(0) = 1\n seq.foreach(p => list(p) = 1)\n list.filter(_ == 0).size == 0\n }\n\n def findTheMissingElement(seq: Seq[Int]): Option[Int] = {\n val list = (1 to seq.size + 1).toArray.map(_ => 0)\n list(0) = 1\n seq.foreach(p => list(p) = 1)\n val result = list.zipWithIndex.filter(p => p._1 == 0)\n if (result.size > 0) Some(result.head._2) else None\n }\n\n def main(args: Array[String]): Unit = {\n val input = readLine()\n val stringA = readLine().toString.split(\" \").map(_.toInt)\n val stringB = readLine().toString.split(\" \").map(_.toInt)\n val missingAElement = findTheMissingElement(stringA)\n val missingBElement = findTheMissingElement(stringB)\n\n val permutations = stringA.zip(stringB).zipWithIndex\n .filter {\n case ((a, b), index) => {\n a != b\n }\n }\n .flatMap {\n case ((a, b), index) => {\n List(stringA.patch(index, List(missingAElement.getOrElse(a)), 1)\n , stringB.patch(index, List(missingBElement.getOrElse(b)), 1))\n }\n }\n\n println(permutations.filter(checkIfAllElementPresent(_)).head.mkString(\" \"))\n }\n}"}, {"source_code": "/**\n * Created by Hyper on 22.06.2017.\n */\nimport javax.imageio.spi.ServiceRegistry.Filter\n\nimport scala.io.StdIn\nobject cf extends App{\n type Linst = List[Int]\n def findDifferences (a: Linst, b: Linst, i: Int): List[(Int,Int,Int)] ={\n (a,b) match {\n case (u :: utail, v :: vtail) => if( u == v ) findDifferences(utail, vtail, i + 1) else (u,v,i) :: findDifferences(utail, vtail, i + 1)\n case (Nil, Nil) => Nil\n }\n }\n def printList(a: Linst):Any ={\n a match{\n case Nil => None\n case b::tail => print(b + \" \"); printList(tail)\n }\n }\n def replace(b: List[Int], byWhat: Int, idx: Int): List[Int] ={\n val t = b.splitAt(idx)\n t._1 ++ List(byWhat) ++ t._2.tail\n }\n def existsDup(b: Linst, num: Int, pos: Int, currPos: Int): Boolean ={\n b match {\n case Nil => false\n case `num` :: tail => if(currPos != pos) true else existsDup(tail, num, pos, currPos + 1)\n case a :: tail => existsDup(tail, num, pos, currPos + 1)\n }\n }\n def fixTransposition(a: Linst, num: Int, pos: Int):Linst={\n val nats = Stream.from(1,1).take(a.length).toList\n val drop = nats.filter(v => !a.contains(v)).head\n replace(a, drop, pos - 1)\n }\n def fixTransposition2(a: Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) ={\n val nats = Stream.from(1,1).take(a.length).toList\n val drop = nats.filter(v => !a.contains(v)).head\n if (existsDup(a, num1, pos1, 1)) replace(a, drop, pos1 - 1)\n else replace(a, drop, pos2 - 1)\n }\n def check(a: Linst, p: Linst, i1: Int):Boolean ={\n if( a.isEmpty) i1 == 1\n else if(a.head != p.head) check(a.tail, p.tail, i1 + 1)\n else check(a.tail, p.tail, i1 + 1)\n }\n val n = StdIn.readLine().toInt\n val A = StdIn.readLine().split(\" \").toList.map(s => s.toInt)\n val B = StdIn.readLine().split(\" \").toList.map(s => s.toInt)\n val diff = findDifferences(A,B,1)\n println()\n diff.length match {\n case 1 => printList(fixTransposition(A, diff.head._1, diff.head._3))\n case 2 => printList({\n val v1 = fixTransposition2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3)\n if(check(A,v1,0) && check(B,v1,0)) v1 else fixTransposition2(B, diff.head._2, diff.head._3, diff.tail.head._2, diff.tail.head._3)\n })\n }\n}\n\n"}, {"source_code": "/**\n * Created by Hyper on 22.06.2017.\n */\nimport javax.imageio.spi.ServiceRegistry.Filter\n\nimport scala.io.StdIn\nobject cf extends App{\n type Linst = List[Int]\n def findDifferences (a: Linst, b: Linst, i: Int): List[(Int,Int,Int)] ={\n (a,b) match {\n case (u :: utail, v :: vtail) => if( u == v ) findDifferences(utail, vtail, i + 1) else (u,v,i) :: findDifferences(utail, vtail, i + 1)\n case (Nil, Nil) => Nil\n }\n }\n def printList(a: Linst):Any ={\n a match{\n case Nil => None\n case b::tail => print(b + \" \"); printList(tail)\n }\n }\n def replace(b: List[Int], byWhat: Int, idx: Int): List[Int] ={\n val t = b.splitAt(idx)\n t._1 ++ List(byWhat) ++ t._2.tail\n }\n def existsDup(b: Linst, num: Int, pos: Int, currPos: Int): Boolean ={\n b match {\n case Nil => false\n case `num` :: tail => if(currPos != pos) true else existsDup(tail, num, pos, currPos + 1)\n case a :: tail => existsDup(tail, num, pos, currPos + 1)\n }\n }\n def fixTransposition(a: Linst, num: Int, pos: Int):Linst={\n val nats = Stream.from(1,1).take(a.length).toList\n val drop = nats.filter(v => !a.contains(v)).head\n replace(a, drop, pos - 1)\n }\n def fixTransposition2(a: Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) ={\n val nats = Stream.from(1,1).take(a.length).toList\n val drop = nats.filter(v => !a.contains(v)).head\n if (num1 == drop) replace(a, drop, pos1 - 1)\n else replace(a, drop, pos2 - 1)\n }\n def check(a: Linst, p: Linst, i1: Int):Boolean ={\n if( a.isEmpty) i1 == 1\n else if(a.head != p.head) check(a.tail, p.tail, i1 + 1)\n else check(a.tail, p.tail, i1 + 1)\n }\n val n = StdIn.readLine().toInt\n val A = StdIn.readLine().split(\" \").toList.map(s => s.toInt)\n val B = StdIn.readLine().split(\" \").toList.map(s => s.toInt)\n val diff = findDifferences(A,B,1)\n println()\n diff.length match {\n case 1 => printList(fixTransposition(A, diff.head._1, diff.head._3))\n case 2 => printList({\n val v1 = fixTransposition2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3)\n if(check(A,v1,0) && check(B,v1,0)) v1 else fixTransposition2(B, diff.head._2, diff.head._3, diff.tail.head._2, diff.tail.head._3)\n })\n }\n}\n\n"}, {"source_code": "/**\n * Created by Hyper on 22.06.2017.\n */\nimport javax.imageio.spi.ServiceRegistry.Filter\n\nimport scala.io.StdIn\nobject cf extends App{\n type Linst = List[Int]\n def findDifferences (a: Linst, b: Linst, i: Int): List[(Int,Int,Int)] ={\n (a,b) match {\n case (u :: utail, v :: vtail) => if( u == v ) findDifferences(utail, vtail, i + 1) else (u,v,i) :: findDifferences(utail, vtail, i + 1)\n case (Nil, Nil) => Nil\n }\n }\n def printList(a: Linst):Any ={\n a match{\n case Nil => None\n case b::tail => print(b + \" \"); printList(tail)\n }\n }\n def replace(b: List[Int], byWhat: Int, idx: Int): List[Int] ={\n val t = b.splitAt(idx)\n t._1 ++ List(byWhat) ++ t._2.tail\n }\n def existsDup(b: Linst, num: Int, pos: Int, currPos: Int): Boolean ={\n b match {\n case Nil => false\n case `num` :: tail => if(currPos != pos) true else existsDup(tail, num, pos, currPos + 1)\n case a :: tail => existsDup(tail, num, pos, currPos + 1)\n }\n }\n def fixTransposition(a: Linst, num: Int, pos: Int):Linst={\n val nats = Stream.from(1,1).take(a.length).toList\n val drop = nats.filter(v => !a.contains(v)).head\n replace(a, drop, pos - 1)\n }\n def fixTransposition2(a: Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) ={\n val nats = Stream.from(1,1).take(a.length).toList\n val drop = nats.filter(v => !a.contains(v)).head\n if (existsDup(a, num1, pos1, 1)) replace(a, drop, pos1 - 1)\n else replace(a, drop, pos2 - 1)\n }\n val n = StdIn.readLine().toInt\n val A = StdIn.readLine().split(\" \").toList.map(s => s.toInt)\n val B = StdIn.readLine().split(\" \").toList.map(s => s.toInt)\n val diff = findDifferences(A,B,1)\n println()\n diff.length match {\n case 1 => printList(fixTransposition(A, diff.head._1, diff.head._3))\n case 2 => printList(fixTransposition2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3))\n }\n}\n\n"}], "src_uid": "6fc3da19da8d9ab024cdd5acfc4f4164"} {"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n var x = BigInt(2)\n\n val res = Array.ofDim[BigInt](n + 1)\n\n for (k <- 1L to n) {\n val k1 = k + 1\n val k1k1 = k1 * k1\n\n val y = k * k1k1 - x / k\n //val y = z / k\n res(k.toInt) = y\n x = k * k1\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.drop(1).mkString(\"\\n\"))\n\n Console.flush\n}\n", "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _716C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n = read[Int]\n val ans = solve3(n+1)\n writeAll(ans)\n }\n\n def solve2(goal: Int): Seq[BigInt] = {\n var ans = mutable.ArrayBuffer.empty[BigInt]\n var display = 2L\n\n var n = 2\n while(n <= goal) {\n val ns = BigInt(n) * n\n\n val f = (Iterator.from(1) find {i =>\n val target = ns * i * i\n val pushes = target - display\n pushes >= 0 && pushes%(n-1) == 0\n }).get\n\n debug(n, f, display)\n\n ans += ((BigInt(f) * f * n * n) - display)/(n-1)\n //debug(n, f, ans.last, display, f.toLong * n)\n display = f.toLong * n\n n += 1\n }\n ans\n }\n\n def solve3(goal: Int): Seq[BigInt] = {\n var ans = mutable.ArrayBuffer.empty[BigInt]\n var display = 2L\n\n var n = 2L\n while(n <= goal) {\n val f = n*(n - 1)\n ans += (f*n - display/(n-1))\n display = f\n n += 1\n }\n ans\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "//package merofeev.contests.codeforces.rnd372\n\nimport java.util.Scanner\n\n/**\n * @author erofeev \n * @since 17.09.16\n */\nobject CSqrt {\n\n def nextNum(x: Long, k: Int): BigInt = {\n var nextNum = 1L\n var i = k.toLong\n val kksqr: Long = k * (k + 1).toLong\n// val pos1: BigInt = k * BigInt(k + 1).pow(2)\n val pos: BigInt = BigInt(kksqr).pow(2) //8100 = (k^2 * (k + 1)^2). we want 900 = k * (k+1)^2\n return pos\n// val posSquare: BigInt = pos / k //900\n// if ((pos1 % (k * k)) != 0 ) {\n// return pos\n// }\n// return pos1\n val nextKPow: Long = (k + 1) * (k + 1)\n while (true) {\n nextNum = i * i\n if (\n // nextNum % k == 0 &&\n nextNum % nextKPow == 0\n && (nextNum - x) % k == 0) {\n return nextNum\n }\n i += 1\n }\n throw new IllegalStateException(k + \"\")\n }\n\n def main(args: Array[String]): Unit = {\n val need = new Scanner(System.in).nextInt()\n// val need = 1000\n var k = 1L\n while (k <= need) {\n// val nextX: BigInt = nextNum(x, k)\n// val steps: BigInt = (nextX - x) / k\n// println(k + \" \" + nextX + \"=> \" + steps + \" steps \" + (k + 1) + \" lvl\")\n if (k == 1) {\n println(2)\n } else {\n println(k * (k + 1) * (k + 1) - (k - 1))\n }\n k += 1\n }\n }\n}"}], "negative_code": [{"source_code": "//package merofeev.contests.codeforces.rnd372\n\n/**\n * @author erofeev \n * @since 17.09.16\n */\nobject CSqrt {\n\n def nextNum(x: Long, k: Int): Long = {\n var nextNum = 1L\n var i = k.toLong\n val kksqr: Long = k * (k + 1).toLong\n return kksqr * kksqr\n val nextKPow: Long = (k + 1) * (k + 1)\n while (true) {\n nextNum = i * i\n if (\n // nextNum % k == 0 &&\n nextNum % nextKPow == 0\n && (nextNum - x) % k == 0) {\n return nextNum\n }\n i += 1\n }\n throw new IllegalStateException(k + \"\")\n }\n\n def main(args: Array[String]): Unit = {\n // val need = new Scanner(System.in).nextInt()\n val need = 100\n var k = 1\n var x = 2L\n while (k <= need) {\n val nextX: Long = nextNum(x, k)\n val steps: Long = (nextX - x) / k\n // println(k + \" \" + nextX + \"=> \" + steps + \" steps \" + (k + 1) + \" lvl\")\n println(steps)\n x = Math.sqrt(nextX).toLong\n k += 1\n }\n }\n}"}, {"source_code": "//package merofeev.contests.codeforces.rnd372\n\nimport java.util.Scanner\n\n/**\n * @author erofeev \n * @since 17.09.16\n */\nobject CSqrt {\n\n def nextNum(x: Long, k: Int): BigInt = {\n var nextNum = 1L\n var i = k.toLong\n val kksqr: Long = k * (k + 1).toLong\n return BigInt(kksqr).pow(2)\n val nextKPow: Long = (k + 1) * (k + 1)\n while (true) {\n nextNum = i * i\n if (\n // nextNum % k == 0 &&\n nextNum % nextKPow == 0\n && (nextNum - x) % k == 0) {\n return nextNum\n }\n i += 1\n }\n throw new IllegalStateException(k + \"\")\n }\n\n def main(args: Array[String]): Unit = {\n val need = new Scanner(System.in).nextInt()\n// val need = 1000000\n var k = 1\n var x = 2L\n while (k <= need) {\n val nextX: BigInt = nextNum(x, k)\n val steps: BigInt = (nextX - x) / k\n// val steps: Long = (nextX - x) / k\n// println(k + \" \" + nextX + \"=> \" + steps + \" steps \" + (k + 1) + \" lvl\")\n println(steps)\n x = k * (k + 1)\n k += 1\n }\n }\n}"}, {"source_code": "//package merofeev.contests.codeforces.rnd372\n\nimport java.util.Scanner\n\n/**\n * @author erofeev \n * @since 17.09.16\n */\nobject CSqrt {\n\n def nextNum(x: Long, k: Int): BigInt = {\n var nextNum = 1L\n var i = k.toLong\n val kksqr: Long = k * (k + 1).toLong\n// val pos1: BigInt = k * BigInt(k + 1).pow(2)\n val pos: BigInt = BigInt(kksqr).pow(2) //8100 = (k^2 * (k + 1)^2). we want 900 = k * (k+1)^2\n return pos\n// val posSquare: BigInt = pos / k //900\n// if ((pos1 % (k * k)) != 0 ) {\n// return pos\n// }\n// return pos1\n val nextKPow: Long = (k + 1) * (k + 1)\n while (true) {\n nextNum = i * i\n if (\n // nextNum % k == 0 &&\n nextNum % nextKPow == 0\n && (nextNum - x) % k == 0) {\n return nextNum\n }\n i += 1\n }\n throw new IllegalStateException(k + \"\")\n }\n\n def main(args: Array[String]): Unit = {\n val need = new Scanner(System.in).nextInt()\n// val need = 1000\n var k = 1\n var x = 2L\n while (k <= need) {\n val nextX: BigInt = nextNum(x, k)\n val steps: BigInt = (nextX - x) / k\n// println(k + \" \" + nextX + \"=> \" + steps + \" steps \" + (k + 1) + \" lvl\")\n println(steps)\n x = k * (k + 1)\n k += 1\n }\n }\n}"}], "src_uid": "6264405c66b2690ada9f8cc6cff55f0b"} {"source_code": "object P2B {\n def main(args : Array[String]) {\n val n = readLine.toInt\n val a = Array.fill(n){\n readLine split \" \" map {_.toInt}\n }\n val answers = for (d <- Array(2, 5)) yield {\n def factors(x : Int, s : Int = 0) : Int = x match {\n case 0 => 1\n case _ if x % d != 0 => s\n case _ => factors(x / d, s + 1)\n }\n val s = Array.ofDim[Int](n, n)\n s(0)(0) = factors(a(0)(0))\n for (i <- 1 until n) s(0)(i) = s(0)(i - 1) + factors(a(0)(i))\n for (i <- 1 until n) s(i)(0) = s(i - 1)(0) + factors(a(i)(0))\n for {\n i <- 1 until n\n j <- 1 until n\n } s(i)(j) = (s(i - 1)(j) min s(i)(j - 1)) + factors(a(i)(j))\n val route = new Iterator[Char]{\n var (x, y) = (n - 1, n - 1)\n def hasNext = (x, y) != (0, 0)\n def next = {\n val ret = () match {\n case _ if y == 0 => 'D'\n case _ if x == 0 => 'R'\n case _ if s(x - 1)(y) < s(x)(y - 1) => 'D'\n case _ => 'R'\n }\n ret match {\n case 'D' => x = x - 1\n case 'R' => y = y - 1\n }\n ret\n }\n }.mkString.reverse\n (s(n - 1)(n - 1), route)\n }\n val a0 = a.map{_ indexOf 0}.zipWithIndex find {_._1 != -1} map {\n case (y, x) =>\n (1, \"D\" * x + \"R\" * y + \"D\" * (n - 1 - x) + \"R\" * (n - 1 - y))\n }\n val answer = (answers ++ a0).minBy{_._1}\n println(answer._1)\n println(answer._2)\n }\n}\n", "positive_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject Main extends App {\n val n = StdIn.readInt()\n val m = Array.ofDim[Int](n, n)\n (0 until n).foreach { i =>\n m(i) = StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n val t2 = Array.ofDim[Short](n, n)\n val t5 = Array.ofDim[Short](n, n)\n val d2 = Array.ofDim[Char](n, n)\n val d5 = Array.ofDim[Char](n, n)\n\n val corner = m(0)(0)\n t2(0)(0) = factorN(corner, 2, 0)\n t5(0)(0) = factorN(corner, 5, 0)\n d2(0)(0) = ' '\n d5(0)(0) = ' '\n\n (1 until n).foreach { i =>\n t2(i)(0) = (factorN(m(i)(0), 2, 0) + t2(i - 1)(0)).toShort\n t5(i)(0) = (factorN(m(i)(0), 5, 0) + t5(i - 1)(0)).toShort\n d2(i)(0) = 'D'\n d5(i)(0) = 'D'\n\n t2(0)(i) = (factorN(m(0)(i), 2, 0) + t2(0)(i - 1)).toShort\n t5(0)(i) = (factorN(m(0)(i), 5, 0) + t5(0)(i - 1)).toShort\n d2(0)(i) = 'R'\n d5(0)(i) = 'R'\n }\n\n @tailrec\n def factorN(x: Int, N: Int, m: Short): Short = {\n if (x == 0) m\n else {\n if (x % N == 0) factorN(x / N, N, (1 + m).toShort)\n else m\n }\n }\n\n (1 until n).foreach { x =>\n (1 until n).foreach { y =>\n val f2 = factorN(m(y)(x), 2, 0)\n val f5 = factorN(m(y)(x), 5, 0)\n\n if (t2(y - 1)(x) < t2(y)(x - 1)) {\n t2(y)(x) = (t2(y - 1)(x) + f2).toShort\n d2(y)(x) = 'D'\n } else {\n t2(y)(x) = (t2(y)(x - 1) + f2).toShort\n d2(y)(x) = 'R'\n }\n\n if (t5(y - 1)(x) < t5(y)(x - 1)) {\n t5(y)(x) = (t5(y - 1)(x) + f5).toShort\n d5(y)(x) = 'D'\n } else {\n t5(y)(x) = (t5(y)(x - 1) + f5).toShort\n d5(y)(x) = 'R'\n }\n }\n }\n\n var zx = -1\n var zy = -1\n (0 until n).foreach { x =>\n (0 until n).foreach { y =>\n if (m(y)(x) == 0) {\n zx = x\n zy = y\n }\n }\n }\n\n val dir = new Array[Char](2 * n - 2)\n\n @tailrec\n def buildDir(arr: Array[Array[Char]], x: Int, y: Int, n: Int): Unit = {\n val d = arr(y)(x)\n if (d == 'D') {\n dir(n) = 'D'\n buildDir(arr, x, y - 1, n - 1)\n } else if (d == 'R') {\n dir(n) = 'R'\n buildDir(arr, x - 1, y, n - 1)\n }\n }\n\n val (min, dirArr) = if (t2(n - 1)(n - 1) > t5(n - 1)(n - 1)) {\n (t5(n - 1)(n - 1), d5)\n } else (t2(n - 1)(n - 1), d2)\n\n if (min != 0 && zx != -1) {\n println(1)\n val dir = new Array[Char](2 * n - 2)\n (0 until zx).foreach(i => dir(i) = 'R')\n (0 until (n - 1)).foreach(i => dir(zx + i) = 'D')\n (0 until (n - 1 - zx)).foreach(i => dir(zx + n - 1 + i) = 'D')\n println(new String(dir))\n } else {\n println(min)\n buildDir(dirArr, n - 1, n - 1, 2 * n - 3)\n println(new String(dir))\n }\n}\n\n"}, {"source_code": "object P2B {\n import io.StdIn._\n\n def main(args:Array[String]) {\n val n = readInt\n val a = Array.fill(n){readLine.split(' ').map{_.toInt}}\n val answers = for (d <- Array(2, 5)) yield {\n def factors(x:Int, s:Int = 0):Int = x match {\n case 0 => 1\n case _ if x % d != 0 => s\n case _ => factors(x / d, s + 1)\n }\n val s = Array.ofDim[Int](n, n)\n s(0)(0) = factors(a(0)(0))\n for (i <- 1 until n) s(0)(i) = s(0)(i - 1) + factors(a(0)(i))\n for (i <- 1 until n) s(i)(0) = s(i - 1)(0) + factors(a(i)(0))\n for (i <- 1 until n; j <- 1 until n) {\n s(i)(j) = s(i - 1)(j).min(s(i)(j - 1)) + factors(a(i)(j))\n }\n def route(x:Int, y:Int, b:StringBuilder):StringBuilder = {\n def goD = route(x - 1, y, b.+=('D'))\n def goR = route(x, y - 1, b.+=('R'))\n if (x == 0 && y == 0) return b\n if (y == 0) return goD\n if (x == 0) return goR\n if (s(x - 1)(y) < s(x)(y - 1)) goD else goR\n }\n (s(n - 1)(n - 1), route(n - 1, n - 1, new StringBuilder).reverse)\n }\n val a0 = a.map{_.indexOf(0)}.zipWithIndex.find{_._1 != -1}\n val answer = (answers ++ a0.map{case (y, x) =>\n (1, \"D\" * x + \"R\" * y + \"D\" * (n - 1 - x) + \"R\" * (n - 1 - y))\n }).minBy{_._1}\n println(answer._1)\n println(answer._2)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n\n val line = in.take(n).map(_.split(' ').map(_.toInt)).toArray\n\n def f(a: Int, k: Int) = {\n var r = 0\n var m = a\n\n while (m != 0 && m % k == 0) {\n m /= k\n r += 1\n }\n r\n }\n\n def dp(k: Int) = {\n val dp = line.map(_.map(i => f(i, k)))\n\n (1 until n).foreach { i =>\n dp(i)(0) += dp(i - 1)(0)\n dp(0)(i) += dp(0)(i - 1)\n }\n\n (1 until n).foreach { i =>\n (1 until n).foreach { j =>\n dp(i)(j) += Math.min(dp(i - 1)(j), dp(i)(j - 1))\n }\n }\n\n dp\n }\n\n val dpr = List(2, 5).map(dp).minBy(d => d(n - 1)(n - 1))\n\n var min = dpr(n - 1)(n - 1)\n \n\n val maybeZero = (0 until n).find { i =>\n line(i).contains(0)\n }\n \n if (min > 1 && maybeZero.nonEmpty) {\n println(1)\n println(\"D\" * maybeZero.get + \"R\" * (n - 1) + \"D\" * (n - 1 - maybeZero.get))\n }\n else {\n println(min)\n var x = n - 1\n var y = n - 1\n var answer = List.empty[Char]\n\n while (x != 0 || y != 0) {\n val upCandidate = y != 0 && (x == 0 || dpr(y - 1)(x) <= dpr(y)(x - 1))\n if (upCandidate) {\n answer ::= 'D'\n y -= 1\n } else {\n answer ::= 'R'\n x -= 1\n }\n }\n println(answer.mkString)\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject BLessRoundTripDynamic extends App {\n\n val scanner = new Scanner(System.in)\n\n val dim = scanner.next.toInt\n\n val matrix = Array.ofDim[Long](dim, dim)\n\n var zeroPoint: Option[(Int, Int)] = None\n\n (0 until dim) foreach {\n y =>\n (0 until dim) foreach {\n x =>\n matrix(x)(y) = scanner.next().toLong\n if (matrix(x)(y) == 0) {\n zeroPoint = Some((x, y))\n matrix(x)(y) = 10\n }\n }\n }\n\n def printZeroPath(p: (Int, Int)): Unit = {\n println(1)\n (0 until p._1).foreach(t => print(\"R\"))\n (0 until dim - 1).foreach(t => print(\"D\"))\n (p._1 until dim - 1).foreach(t => print(\"R\"))\n }\n\n case class Direction(value: Int, dir: Boolean)\n\n val divs = Array.ofDim[Int](dim, dim)\n val dirs = Array.ofDim[Boolean](dim, dim)\n val fiveWeight = countWeights(divs, 5)\n val fivePath = getPath(dirs)\n val twoWeight = countWeights(divs, 2)\n val twoPath = getPath(dirs)\n\n if (math.min(twoWeight, fiveWeight) > 0 && zeroPoint.isDefined) {\n printZeroPath(zeroPoint.get)\n } else if (twoWeight < fiveWeight) {\n println(twoWeight)\n println(twoPath)\n } else {\n println(fiveWeight)\n println(fivePath)\n }\n\n def getPath(divs: Array[Array[Boolean]]): String = {\n def traceBack(x: Int, y: Int): List[Char] = {\n if (x == 0 && y == 0) Nil\n else if (divs(x)(y)) 'R' :: traceBack(x - 1, y)\n else 'D' :: traceBack(x, y - 1)\n }\n traceBack(dim - 1, dim - 1).reverse.mkString\n }\n\n def countWeights(divs: Array[Array[Int]], num: Int): Long = {\n var x = 0\n var y = 0\n while (y < dim) {\n while (x < dim) {\n val curValue = findDivNum(matrix(x)(y), num)\n if (y == 0 && x == 0) {\n divs(x)(y) = curValue\n dirs(x)(y) = false\n } else if (y == 0) {\n divs(x)(y) = curValue + divs(x - 1)(y)\n dirs(x)(y) = true\n } else if (x == 0) {\n divs(x)(y) = curValue + divs(x)(y - 1)\n dirs(x)(y) = false\n } else {\n if (divs(x)(y - 1) < divs(x - 1)(y)) {\n divs(x)(y) = curValue + divs(x)(y - 1)\n dirs(x)(y) = false\n } else {\n divs(x)(y) = curValue + divs(x - 1)(y)\n dirs(x)(y) = true\n }\n }\n x += 1\n }\n x = 0\n y += 1\n }\n divs(dim - 1)(dim - 1)\n }\n\n\n def findDivNum(item: Long, num: Int): Int = {\n var it = item\n var res = 0\n while (it % num == 0) {\n it = it / num\n res = res + 1\n }\n res\n }\n\n def forEach[T](arr: Array[Array[T]], func: (Int, Int, T) => Unit): Unit = {\n (0 until dim) foreach {\n y =>\n (0 until dim) foreach {\n x =>\n func(x, y, arr(x)(y))\n }\n }\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable.HashMap\nimport scala.math.min\n\n\nobject testing {\n\n def findPower5(input : Int) : Int = {\n if (input == 0) {\n return 50000\n }\n var temp = input\n var returnValue = 0\n while (temp % 5 == 0) {\n returnValue += 1\n temp /= 5\n }\n return returnValue\n }\n\n def findPower2(input : Int) : Int = {\n if (input == 0) {\n return 50000\n }\n var temp = input\n var returnValue = 0\n while (temp % 2 == 0) {\n returnValue += 1\n temp /= 2\n }\n return returnValue\n }\n\n def main(args: Array[String]) : Unit = {\n var matrixSize: Int = scala.io.StdIn.readInt()\n var inputMatrix = Array.ofDim[Int](matrixSize,matrixSize)\n var fiveMatrix = Array.ofDim[Int](matrixSize,matrixSize)\n var twoMatrix = Array.ofDim[Int](matrixSize,matrixSize)\n var existsZero = false\n var zeroX = -1\n var zeroY = -1\n for (i <- 0 until matrixSize) {\n var inputLine = scala.io.StdIn.readLine()\n var inputSplit = inputLine.split(\" \")\n for (j <- 0 until matrixSize) {\n inputMatrix(i)(j) = inputSplit(j).toInt\n if (inputMatrix(i)(j) == 0) {\n existsZero = true\n zeroY = i\n zeroX = j\n }\n fiveMatrix(i)(j) = 0\n twoMatrix(i)(j) = 0\n }\n }\n fiveMatrix(0)(0) = findPower5(inputMatrix(0)(0))\n for (i <- 1 until matrixSize) {\n fiveMatrix(0)(i) = fiveMatrix(0)(i-1) + findPower5(inputMatrix(0)(i))\n }\n for (i <- 1 until matrixSize) {\n fiveMatrix(i)(0) = fiveMatrix(i-1)(0) + findPower5(inputMatrix(i)(0))\n }\n for (i <- 1 until matrixSize;\n j <- 1 until matrixSize) {\n fiveMatrix(i)(j) = min(fiveMatrix(i)(j-1) + findPower5(inputMatrix(i)(j)), \n fiveMatrix(i-1)(j) + findPower5(inputMatrix(i)(j)))\n }\n\n twoMatrix(0)(0) = findPower2(inputMatrix(0)(0))\n for (i <- 1 until matrixSize) {\n twoMatrix(0)(i) = twoMatrix(0)(i-1) + findPower2(inputMatrix(0)(i))\n }\n for (i <- 1 until matrixSize) {\n twoMatrix(i)(0) = twoMatrix(i-1)(0) + findPower2(inputMatrix(i)(0))\n }\n for (i <- 1 until matrixSize;\n j <- 1 until matrixSize) {\n twoMatrix(i)(j) = min(twoMatrix(i)(j-1) + findPower2(inputMatrix(i)(j)), \n twoMatrix(i-1)(j) + findPower2(inputMatrix(i)(j)))\n }\n\n var output : String = \"\"\n if (min(twoMatrix(matrixSize - 1)(matrixSize - 1),\n fiveMatrix(matrixSize - 1)(matrixSize - 1)) > 1 && existsZero) {\n // find zero path\n for (i <- 0 until zeroX) {\n output = output + \"R\"\n }\n for (i <- 0 until matrixSize - 1) {\n output = output + \"D\"\n }\n for (i <- zeroX until matrixSize - 1) {\n output = output + \"R\"\n }\n println(1)\n println(output)\n return;\n }\n\n if (twoMatrix(matrixSize - 1)(matrixSize - 1) < fiveMatrix(matrixSize - 1)(matrixSize - 1)) {\n var currX = matrixSize - 1\n var currY = matrixSize - 1\n while (currX != 0 || currY != 0) {\n if (currX != 0 && twoMatrix(currY)(currX - 1) + findPower2(inputMatrix(currY)(currX)) == twoMatrix(currY)(currX)) {\n output = \"R\" + output\n currX = currX - 1\n } else {\n output = \"D\" + output\n currY = currY - 1\n }\n }\n println(twoMatrix(matrixSize - 1)(matrixSize - 1))\n println(output)\n return\n } else {\n var currX = matrixSize - 1\n var currY = matrixSize - 1\n while (currX != 0 || currY != 0) {\n if (currX != 0 && fiveMatrix(currY)(currX - 1) + findPower5(inputMatrix(currY)(currX)) == fiveMatrix(currY)(currX)) {\n output = \"R\" + output\n currX = currX - 1\n } else {\n output = \"D\" + output\n currY = currY - 1\n }\n }\n println(fiveMatrix(matrixSize - 1)(matrixSize - 1))\n println(output)\n return\n }\n }\n}"}, {"source_code": "import scala.reflect.ClassTag\nimport scala.annotation.tailrec\nobject X extends App {\n def dynamicSolveMatrixRightDown[T, U: ClassTag](\n matrix: Array[Array[T]],\n initialValue: U\n )(\n combiner: (U, U, T) => U\n ) = {\n\n val len = matrix.length\n\n val solutionMatrix = Array.ofDim[U](len, len)\n\n solutionMatrix(0)(0) = combiner(initialValue, initialValue, matrix(0)(0))\n\n (0 until len).foreach(b => {\n (0 to b).foreach(i => {\n // row\n val rowWeight = solutionMatrix(i)(b)\n val colWeight = solutionMatrix(b)(i)\n\n if (!(b + 1 > len - 1)) {\n solutionMatrix(i)(b + 1) =\n combiner(rowWeight, solutionMatrix(i)(b + 1), matrix(i)(b + 1))\n solutionMatrix(b + 1)(i) =\n combiner(colWeight, solutionMatrix(b + 1)(i), matrix(b + 1)(i))\n }\n\n if (!(i + 1 > len - 1)) {\n val rightWeight = matrix(i + 1)(b)\n\n val candidateWeight =\n combiner(rowWeight, solutionMatrix(i + 1)(b), rightWeight)\n\n solutionMatrix(i + 1)(b) = candidateWeight\n\n val downWeight = matrix(b)(i + 1)\n\n val otherCandidateWeight =\n combiner(colWeight, solutionMatrix(b)(i + 1), downWeight)\n\n solutionMatrix(b)(i + 1) = otherCandidateWeight\n\n }\n\n if (b < len - 1 && i == b) {\n val leftWeight =\n combiner(\n solutionMatrix(b)(b + 1),\n solutionMatrix(b + 1)(b + 1),\n matrix(b + 1)(b + 1)\n )\n\n solutionMatrix(b + 1)(b + 1) = leftWeight\n\n val upWeight =\n combiner(\n solutionMatrix(b + 1)(b),\n solutionMatrix(b + 1)(b + 1),\n matrix(b + 1)(b + 1)\n )\n\n solutionMatrix(b + 1)(b + 1) = upWeight\n }\n\n })\n\n })\n\n solutionMatrix\n }\n\n def dynamicSolveMatrixRightDownInPlace[T](\n matrix: Array[Array[T]],\n initialValue: T\n )(\n combiner: (T, T, T) => T\n ): Array[Array[T]] = {\n\n val len = matrix.length\n\n matrix(0)(0) = initialValue\n\n (1 until len).foreach(i => {\n matrix(0)(i) = combiner(matrix(0)(i - 1), matrix(0)(i - 1), matrix(0)(i))\n matrix(i)(0) = combiner(matrix(i - 1)(0), matrix(i - 1)(0), matrix(i)(0))\n })\n\n (1 until len).foreach(i => {\n (1 until len).foreach(j => {\n matrix(i)(j) =\n combiner(matrix(i - 1)(j), matrix(i)(j - 1), matrix(i)(j))\n })\n })\n\n matrix\n }\n\n def highestFactor(f: Int, n: Int) = {\n var m = n\n var c = 0\n while (m % f == 0) {\n c = c + 1\n m = m / f\n }\n (c, m)\n }\n\n @tailrec\n def getPath[U](\n solnMatrix: Array[Array[U]],\n start: (Int, Int),\n path: List[String] = List(),\n end: (Int, Int) = (0, 0)\n )(implicit ord: Ordering[U]): String = {\n if (start == end) {\n path.mkString(\"\")\n } else {\n start match {\n case (0, s) =>\n getPath(solnMatrix, (start._1, start._2 - 1), \"R\" +: path)\n case (s, 0) =>\n getPath(solnMatrix, (start._1 - 1, start._2), \"D\" +: path)\n case (u, v) => {\n if (ord.lt(solnMatrix(u - 1)(v), solnMatrix(u)(v - 1)))\n getPath(solnMatrix, (start._1 - 1, start._2), \"D\" +: path)\n else getPath(solnMatrix, (start._1, start._2 - 1), \"R\" +: path)\n }\n }\n }\n }\n\n val lineCount = scala.io.StdIn.readInt()\n\n val inpMatrix = Array.ofDim[(Int, Int)](lineCount, lineCount)\n\n var hasZero = Option.empty[(Int, Int)]\n\n (0 until lineCount).foreach(r => {\n var i = 0\n val line = scala.io.StdIn\n .readLine()\n .split(\" \")\n .foreach(w => {\n val cell = w.toInt\n if (cell == 0) {\n hasZero = Some((r, i))\n inpMatrix(r)(i) = (1, 1)\n } else {\n val (p10, t) = highestFactor(10, cell)\n\n val (p2, k) = highestFactor(2, t)\n val p5 = highestFactor(5, k)._1\n inpMatrix(r)(i) = (p2 + p10, p5 + p10)\n\n }\n i = i + 1\n })\n })\n// println(inpMatrix.map(_.mkString(\"\\t\")).mkString(\"\\n\"))\n// println()\n\n val smaller = (x: Int, y: Int) => if (x < y) x else y\n\n val solutionMatrix = dynamicSolveMatrixRightDownInPlace(\n inpMatrix,\n inpMatrix(0)(0)\n )((left, up, y) => {\n val fstCont = smaller(left._1, up._1)\n val sndCont = smaller(left._2, up._2)\n (\n fstCont + y._1,\n sndCont + y._2\n )\n\n })\n\n val ending = solutionMatrix(lineCount - 1)(lineCount - 1)\n val smallest = smaller(ending._1, ending._2)\n\n val bestPath = if (ending._1 < ending._2) {\n getPath(solutionMatrix, (lineCount - 1, lineCount - 1))(\n new Ordering[(Int, Int)] {\n def compare(x: (Int, Int), y: (Int, Int)): Int = x._1.compare(y._1)\n }\n )\n } else {\n getPath(solutionMatrix, (lineCount - 1, lineCount - 1))(\n new Ordering[(Int, Int)] {\n def compare(x: (Int, Int), y: (Int, Int)): Int = x._2.compare(y._2)\n }\n )\n }\n\n val (p, s) = hasZero match {\n case None => (bestPath, smallest)\n case Some(value) =>\n if (smallest == 0) {\n (bestPath, smallest)\n } else {\n val x = value._1\n\n val s = (0 until x).map(_ => \"D\").mkString(\"\")\n val d = (0 until lineCount - 1).map(_ => \"R\").mkString(\"\")\n val r = (0 until lineCount - x - 1).map(_ => \"D\").mkString(\"\")\n\n (s + d + r, 1)\n }\n }\n\n// println(solutionMatrix.map(_.mkString(\"\\t\")).mkString(\"\\n\"))\n\n println(s)\n println(p)\n}\n"}, {"source_code": "import java.util._\nimport java.io._\nimport scala.annotation.tailrec\n\nobject P2B extends App {\n object ReaderWriter {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val writer = new PrintWriter(System.out)\n var tok: StringTokenizer = null\n\n @tailrec\n def readToken(): String = {\n if (tok != null && tok.hasMoreTokens()) {\n tok.nextToken()\n } else {\n val line = reader.readLine()\n tok = null\n if (line == null) {\n null\n } else {\n tok = new StringTokenizer(line)\n readToken()\n }\n }\n }\n }\n\n import ReaderWriter._\n\n def readInt(): Int = readToken().toInt\n\n def log(value: Int, base: Int): Int = {\n @tailrec\n def rec(value: Int, acc: Int): Int = {\n if (value == 0) {\n 1\n } else if (value % base == 0) {\n rec(value / base, acc + 1)\n } else {\n acc\n }\n }\n rec(value, 0)\n }\n\n val n = readInt()\n var cur = 0\n var next = 1 - cur\n val m = Array.ofDim[Int](n, n)\n for {\n row <- 0 until n\n column <- 0 until n\n } {\n m(row)(column) = readInt()\n }\n\n object Direction {\n sealed trait Type\n case object No extends Type\n case object Up extends Type\n case object Left extends Type\n }\n\n def minSumAndPath(functor: Int => Int): (Int, Seq[Char]) = {\n val d = Array.ofDim[Int](n, n)\n val prev = Array.fill[Direction.Type](n, n)(Direction.No)\n for {\n row <- 0 until n\n column <- 0 until n\n } {\n val value = functor(m(row)(column))\n val dUpOpt: Option[Int] = if (row > 0) Some(d(row - 1)(column)) else None\n val dLeftOpt: Option[Int] = if (column > 0) Some(d(row)(column - 1)) else None\n val dUp = dUpOpt.getOrElse(Integer.MAX_VALUE)\n val dLeft = dLeftOpt.getOrElse(Integer.MAX_VALUE)\n if (!dUpOpt.isDefined && !dLeftOpt.isDefined) {\n d(row)(column) = value\n prev(row)(column) = Direction.No\n } else {\n if (dUp < dLeft) {\n d(row)(column) = dUp + value\n prev(row)(column) = Direction.Up\n } else {\n d(row)(column) = dLeft + value\n prev(row)(column) = Direction.Left\n }\n }\n }\n\n var row = n - 1\n var column = n - 1\n var path = Seq.empty[Char]\n while (!(row == 0 && column == 0)) {\n prev(row)(column) match {\n case Direction.Up =>\n path :+= 'D'\n row -= 1\n case Direction.Left =>\n path :+= 'R'\n column -= 1\n case _ =>\n row = 0\n column = 0\n }\n }\n\n (d(n - 1)(n - 1), path.reverse)\n }\n\n val (zeroSum, zeroPath) = minSumAndPath({ value => if (value == 0) -1 else 0 })\n val (twoSum, twoPath) = minSumAndPath({ value => log(value, 2) })\n val (fiveSum, fivePath) = minSumAndPath({ value => log(value, 5) })\n\n val bestSum = Math.min(twoSum, fiveSum)\n val bestPath = if (twoSum < fiveSum) twoPath else fivePath\n if ((zeroSum < 0) && (bestSum > 1)) {\n writer.println(1)\n writer.println(zeroPath.mkString(\"\"))\n } else {\n writer.println(bestSum)\n writer.println(bestPath.mkString(\"\"))\n }\n\n writer.flush()\n}\n"}, {"source_code": "import io.Source\nimport annotation.tailrec\n\nobject LeastRound {\n def main(args: Array[String]) = {\n val lines = Source.stdin.getLines()\n val size = lines.next().toInt\n\n val numMatrix = readMatrix(lines, size)\n val zeroCoords = zeroPass(numMatrix)\n\n calculatePathCost(numMatrix)\n printBestPath(numMatrix, zeroCoords)\n }\n\n def readMatrix(lines: Iterator[String], matrixSize: Int) = {\n val matrix = new Array[Array[Int]](matrixSize)\n\n for (row <- 0 until matrixSize) {\n matrix(row) = lines.next().split(\" \").map(_.toInt)\n }\n matrix\n }\n\n def zeroPass(rawNumMatrix: Array[Array[Int]]) = {\n val size = rawNumMatrix.length\n var seenZero = false\n var zeroCoords: Option[Pair[Int, Int]] = None\n\n for (row <- 0 until size) {\n for (col <- 0 until size) {\n if (rawNumMatrix(row)(col) == 0) {\n rawNumMatrix(row)(col) = 10\n if (!seenZero) {\n seenZero = true\n zeroCoords = Some(Pair(row, col))\n }\n }\n }\n }\n zeroCoords\n }\n\n\n def calculatePathCost(numMatrix: Array[Array[Int]]) = {\n // mutate in place!\n val size = numMatrix.length\n def extractExponent(divisor: Int) (toFactor: Int) = {\n @tailrec\n def runningExponentCount(currExp: Int, currN: Int): Int = \n if (currN % divisor == 0) runningExponentCount(currExp + 1, currN / divisor) else currExp\n runningExponentCount(0, toFactor)\n }\n def factorizer(n: Int) = Pair(extractExponent(2)(n), extractExponent(5)(n))\n\n numMatrix(0)(0) = encodeAsInt(factorizer(numMatrix(0)(0)))\n for (col <- 1 until size) {\n val row = 0\n numMatrix(row)(col) = encodeAsInt(addTuples(decodeToTuple(numMatrix(row)(col - 1)), factorizer(numMatrix(row)(col))))\n }\n for (row <- 1 until size) {\n val col = 0\n numMatrix(row)(col) = encodeAsInt(addTuples(decodeToTuple(numMatrix(row-1)(col)), factorizer(numMatrix(row)(col))))\n }\n for (row <- 1 until size) {\n for (col <- 1 until size) {\n val currCellFactorized = factorizer(numMatrix(row)(col))\n val top = decodeToTuple(numMatrix(row-1)(col))\n val left = decodeToTuple(numMatrix(row)(col-1))\n val bestPaths = Pair(top._1 min left._1, top._2 min left._2)\n numMatrix(row)(col) = encodeAsInt(addTuples(bestPaths, currCellFactorized))\n }\n }\n }\n\n def printBestPath(pathMatrix: Array[Array[Int]], zeroCoord: Option[Pair[Int, Int]]) = {\n val size = pathMatrix.size\n val last = decodeToTuple(pathMatrix(size - 1)(size - 1))\n if (zeroCoord.isEmpty || (last._1 min last._2) == 0) {\n // regular case\n val path = (if (last._1 < last._2) {\n println(last._1)\n tracePath(pathMatrix, _._1)\n }\n else {\n println(last._2)\n tracePath(pathMatrix, _._2)\n })\n\n path.foreach(print)\n println()\n }\n else {\n println(1)\n printZeroPath(zeroCoord.get, size)\n println()\n }\n }\n\n def tracePath(pathMatrix: Array[Array[Int]], chooser: Pair[Int, Int] => Int) = {\n val size = pathMatrix.size\n\n var currRow = size - 1\n var currCol = size - 1\n var path: List[Char] = Nil\n\n while (currRow != 0 && currCol != 0) {\n val top = decodeToTuple(pathMatrix(currRow - 1)(currCol))\n val left = decodeToTuple(pathMatrix(currRow)(currCol-1))\n if (chooser(top) < chooser(left)) {\n path = 'D' :: path\n currRow -= 1\n }\n else {\n path = 'R' :: path\n currCol -= 1\n }\n }\n while (currRow == 0 && currCol != 0) {\n path = 'R' :: path\n currCol -= 1\n }\n\n while (currCol == 0 && currRow != 0) {\n path = 'D' :: path\n currRow -= 1\n }\n path\n }\n\n def printZeroPath(zeroCoord: Pair[Int, Int], size: Int) = {\n printN('D', zeroCoord._1)\n printN('R', zeroCoord._2)\n printN('D', size - zeroCoord._1 - 1)\n printN('R', size - zeroCoord._2 - 1)\n }\n\n def printN(item: Char, numTimes: Int) = {\n for (i <- 0 until numTimes)\n print(item)\n }\n\n def decodeToTuple(m: Int) = {\n // want the pair: (i,j)\n // put k = i + j\n val k = ((-1 + math.sqrt(1 + 8*m)) / 2).toInt\n val j = m - k*(k + 1)/2\n val i = k - j\n (i, j)\n }\n\n def encodeAsInt(pair: Pair[Int, Int]) =\n pair match {\n case (i, j) => (i + j)*(i + j + 1) / 2 + j\n }\n\n def addTuples(tuple1: Pair[Int, Int], tuple2: Pair[Int, Int]) = \n Pair(tuple1._1 + tuple2._1, tuple1._2 + tuple2._2)\n\n // ok, works on everything (functions are the identity, composed either way)\n def testEncodeDecode(factorizer: (Int) => Pair[Int, Int]) = {\n for (n <- 0 to 1000000000) {\n if (n % 10000000 == 0) {\n println(s\"examining $n.\")\n }\n if (encodeAsInt(decodeToTuple(n)) != n) {\n println(\"mistake on \" + n)\n }\n }\n for (twos <- 0 to 9) {\n println(s\"examining $twos\")\n for (fives <- 0 to twos) {\n if (decodeToTuple(encodeAsInt(Pair(twos, fives))) != Pair(twos, fives)) {\n println(s\"mistake on ${Pair(twos, fives)}\")\n }\n if (Pair(twos, fives) != factorizer(math.pow(2, twos).toInt * math.pow(5, fives).toInt))\n println(s\"mistake, didn't factor ${Pair(twos, fives)} which is ${twos * fives}\")\n }\n }\n }\n}\n"}, {"source_code": "object B2 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = Array.fill(n)(readInts(n))\n val two = Array.ofDim[Int](n, n)\n val five = Array.ofDim[Int](n, n)\n var zeroi, zeroj = -1\n\n for(i <- 0 until n; j <- 0 until n if in(i)(j) == 0) {\n zeroi = i\n zeroj = j\n two(i)(j) = 1\n five(i)(j) = 1\n }\n\n for(i <- 0 until n; j <- 0 until n) {\n var num = in(i)(j)\n var t, f = 0\n while(num != 0 && num%2 == 0) {\n num /= 2\n t += 1\n }\n while(num != 0 && num%5 == 0) {\n num /= 5\n f += 1\n }\n if(i == 0 && j == 0) {\n two(i)(j) += t\n five(i)(j) += f\n } else if(i == 0) {\n two(i)(j) += two(i)(j-1) + t\n five(i)(j) += five(i)(j-1) + f\n } else if(j == 0) {\n two(i)(j) += two(i-1)(j) + t\n five(i)(j) += five(i-1)(j) + f\n } else {\n two(i)(j) += math.min(two(i-1)(j), two(i)(j-1)) + t\n five(i)(j) += math.min(five(i-1)(j), five(i)(j-1)) + f\n }\n }\n val dp = if (two(n - 1)(n - 1) < five(n - 1)(n - 1)) two else five\n if(zeroi != -1 && dp(n-1)(n-1) != 0) {\n println(\"1\")\n println(\"R\"*zeroj ++ \"D\"*zeroi ++ \"R\"*(n-zeroj-1) ++ \"D\"*(n-zeroi-1))\n } else {\n println(dp(n - 1)(n - 1))\n val res = cu.ArrayBuffer.empty[Char]\n var i = n - 1\n var j = n - 1\n while (i != 0 || j != 0) {\n if (i > 0 && (j == 0 || dp(i)(j - 1) >= dp(i - 1)(j))) {\n res.append('D')\n i -= 1\n } else {\n res.append('R')\n j -= 1\n }\n }\n println(res.reverse.mkString(\"\"))\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "\nobject solution {\n def solve(n: Int, cost: Array[Array[Int]]): (Int, String) = {\n val INF = 100000\n val rv = Array.fill[Int](n, n)(0)\n val rp = Array.fill[Char](n, n)(' ')\n rv(0)(0) = cost(0)(0)\n for (y <- 0 until n; x <- 0 until n if x + y > 0) {\n var res = INF\n var resp = ' '\n if (y > 0) {\n res = rv(y - 1)(x)\n resp = 'D'\n }\n if (x > 0 && res > rv(y)(x-1)) {\n res = rv(y)(x - 1)\n resp = 'R'\n }\n rv(y)(x) = res + cost(y)(x)\n rp(y)(x) = resp\n }\n var (y, x) = (n-1, n-1)\n var path = new StringBuilder()\n while (y + x > 0) {\n if (rp(y)(x) == 'R') {\n path += 'R'\n x -= 1\n } else {\n path += 'D'\n y -= 1\n }\n }\n (rv(n-1)(n-1), path.reverse.toString())\n }\n\n def main(args: Array[String]) = {\n val n = io.StdIn.readInt()\n val twos = Array.fill[Int](n, n)(0)\n val fives = Array.fill[Int](n, n)(0)\n\n def power_of(x: Int, p: Int): Int = {\n var result = 0\n var left = x\n while (left % p == 0) {\n result += 1\n left /= p\n }\n result\n }\n var zero_point: Option[(Int, Int)] = None\n for (y <- 0 until n) {\n val line = io.StdIn.readLine().split(\" \").map(_.toInt)\n for (x <- 0 until n) {\n if (line(x) > 0) {\n twos(y)(x) = power_of(line(x), 2)\n fives(y)(x) = power_of(line(x), 5)\n } else {\n zero_point = Some((x, y))\n twos(y)(x) = 1\n fives(y)(x) = 1\n }\n }\n }\n val s2 = solve(n, twos)\n val s5 = solve(n, fives)\n\n if (math.min(s2._1, s5._1) == 0 || !zero_point.isDefined) {\n if (s2._1 <= s5._1)\n printf(\"%d\\n%s\\n\", s2._1, s2._2)\n else\n printf(\"%d\\n%s\\n\", s5._1, s5._2)\n } else {\n val (x, y) = zero_point.get\n printf(\"1\\n\")\n println((\"R\" * x) + (\"D\" * y) + (\"R\" * (n - x - 1)) + (\"D\" * (n - y - 1)))\n }\n }\n\n}"}], "negative_code": [{"source_code": "import java.util._\nimport java.io._\nimport scala.annotation.tailrec\n\nobject P2B extends App {\n object ReaderWriter {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val writer = new PrintWriter(System.out)\n var tok: StringTokenizer = null\n\n @tailrec\n def readToken(): String = {\n if (tok != null && tok.hasMoreTokens()) {\n tok.nextToken()\n } else {\n val line = reader.readLine()\n tok = null\n if (line == null) {\n null\n } else {\n tok = new StringTokenizer(line)\n readToken()\n }\n }\n }\n }\n\n import ReaderWriter._\n\n def readInt(): Int = readToken().toInt\n\n def log(value: Int, base: Int): Int = {\n @tailrec\n def rec(value: Int, acc: Int): Int = {\n if (value == 0) {\n 1\n } else if (value % base == 0) {\n rec(value / base, acc + 1)\n } else {\n acc\n }\n }\n rec(value, 0)\n }\n\n val n = readInt()\n var cur = 0\n var next = 1 - cur\n val m = Array.ofDim[Int](n, n)\n for {\n row <- 0 until n\n column <- 0 until n\n } {\n m(row)(column) = readInt()\n }\n\n object Direction {\n sealed trait Type\n case object No extends Type\n case object Up extends Type\n case object Left extends Type\n }\n\n def minSumAndPath(functor: Int => Int): (Int, Seq[Char]) = {\n val d = Array.ofDim[Int](n, n)\n val prev = Array.fill[Direction.Type](n, n)(Direction.No)\n for {\n row <- 0 until n\n column <- 0 until n\n } {\n val value = functor(m(row)(column))\n val dUpOpt: Option[Int] = if (row > 0) Some(d(row - 1)(column)) else None\n val dLeftOpt: Option[Int] = if (column > 0) Some(d(row)(column - 1)) else None\n val dUp = dUpOpt.getOrElse(Integer.MAX_VALUE)\n val dLeft = dLeftOpt.getOrElse(Integer.MAX_VALUE)\n if (!dUpOpt.isDefined && !dLeftOpt.isDefined) {\n d(row)(column) = value\n prev(row)(column) = Direction.No\n } else {\n if (dUp < dLeft) {\n d(row)(column) = dUp + value\n prev(row)(column) = Direction.Up\n } else {\n d(row)(column) = dLeft + value\n prev(row)(column) = Direction.Left\n }\n }\n }\n\n var row = n - 1\n var column = n - 1\n var path = Seq.empty[Char]\n while (!(row == 0 && column == 0)) {\n prev(row)(column) match {\n case Direction.Up =>\n path :+= 'D'\n row -= 1\n case Direction.Left =>\n path :+= 'R'\n column -= 1\n case _ =>\n row = 0\n column = 0\n }\n }\n\n (d(n - 1)(n - 1), path.reverse)\n }\n\n val (zeroSum, zeroPath) = minSumAndPath({ value => if (value == 0) 1 else 0 })\n val (twoSum, twoPath) = minSumAndPath({ value => log(value, 2) })\n val (fiveSum, fivePath) = minSumAndPath({ value => log(value, 5) })\n\n if (zeroSum > 0) {\n writer.println(\"1\")\n writer.println(zeroPath.mkString(\"\"))\n } else {\n val bestSum = if (twoSum < fiveSum) twoSum else fiveSum\n val bestPath = if (twoSum < fiveSum) twoPath else fivePath\n writer.println(bestSum)\n writer.println(bestPath.mkString(\"\"))\n }\n\n writer.flush()\n}\n"}, {"source_code": "import io.Source\nimport annotation.tailrec\n// Minimize # of zeroes on product of numbers on path\n// relevant stuff - does the cell contain a 0? question states non-negative\n// what seems to be tricky here is that the best way to get to a cell is not necessarily a subpath\n// of the best way to get to a neighbour\n// so, what's the best way to get to the last cell?\n//\n// suppose the last cell has (numTwos, 0) as its factorization\n// the best path P to this cell is the one that minimizes\n// tens(P) + min(uncoupled-fives(P), numTwos)\n// if the last cell doesn't look like that, since we're going to pick up the\n// additional 10s no matter what, just take abs(numTwos - numFives)\n\n// now THAT is an expression I can put in my pipe and compute!\n\n// there is also this issue with zeros... if a zero appears in the matrix, then any path that goes through that is just as good\n// the only reason to avoid the 0 is if you can get no tens. does the answer need to be unique?\n\nobject LeastRound {\n\n def main(args: Array[String]) = {\n val lines = Source.stdin.getLines()\n val size = lines.next().toInt\n\n val rawNumMatrix = readMatrix(lines, size)\n\n val pathMatrix = calculatePathCost(rawNumMatrix)\n // cost of path found:\n println(pathMatrix(size - 1)(size - 1).cost)\n println(getBestPath(pathMatrix))\n }\n\n def getBestPath(pathMatrix: Array[Array[Path]]) = {\n // use a stringbuilder\n val backwardsPath = new StringBuilder()\n\n var row = pathMatrix.length - 1\n var col = pathMatrix.length - 1\n while (!(row == 0 && col == 0)) {\n //println(\"row is: \" + row + \", col: \" + col)\n pathMatrix(row)(col).step match {\n case Direction.Down => {backwardsPath += 'D'; row -= 1}\n case Direction.Right => {backwardsPath += 'R'; col -= 1}\n case Direction.Blank => { row = 0; col = 0}\n }\n }\n\n backwardsPath.reverseContents()\n }\n\n def readMatrix(lines: Iterator[String], matrixSize: Int) = {\n val matrix = new Array[Array[Int]](matrixSize)\n\n for (row <- 0 until matrixSize) {\n matrix(row) = lines.next().split(\" \").map(_.toInt)\n }\n matrix\n }\n\n def calculatePathCost(numMatrix: Array[Array[Int]]) = {\n\n val size = numMatrix.length\n val pathMatrix = new Array[Array[Path]](size)\n val finalFact = TFFactorization(numMatrix(size - 1)(size - 1))\n\n pathMatrix(0) = new Array[Path](size)\n pathMatrix(0)(0) = Path.singleStep(numMatrix(0)(0))\n\n\n for (row <- 0 until size) {\n if (row != 0)\n pathMatrix(row) = new Array[Path](size)\n\n for (column <- 0 until size) {\n val currFact = TFFactorization(numMatrix(row)(column))\n \n if (row == 0 && column != 0)\n pathMatrix(row)(column) = pathMatrix(row)(column - 1).augmentPath(currFact, Direction.Right)\n else if (row != 0 && column == 0)\n pathMatrix(row)(column) = pathMatrix(row - 1)(column).augmentPath(currFact, Direction.Down)\n else if (row != 0 && column != 0)\n pathMatrix(row)(column) = Path.getBestPath(pathMatrix(row)(column -1), pathMatrix(row - 1)(column), finalFact, currFact)\n }\n }\n //println(pathMatrix(size - 1)(size - 1).cost)\n //pathMatrix.foreach( row => {row.foreach(path => {print(path.toString); print(\" \")}); println()})\n pathMatrix\n }\n}\n\nobject Direction extends Enumeration {\n type Direction = Value\n val Down, Right, Blank = Value\n}\n\n\nsealed abstract class TFFactorization {\n def *(other: TFFactorization): TFFactorization\n def tailZeros(): Int\n}\n\ncase class ProperFact(numTwos: Int, numFives: Int) extends TFFactorization {\n \n def *(other: TFFactorization) = \n other match {\n case ProperFact(otherTwos, otherFives) => ProperFact(numTwos + otherTwos, numFives + otherFives) \n case ZeroFact() => other\n }\n \n def tailZeros() = numTwos min numFives\n\n override def toString() = \"(\" + numTwos + \", \" + numFives + \")\"\n}\n\ncase class ZeroFact() extends TFFactorization {\n def tailZeros() = 1\n def *(other: TFFactorization) = this\n\n override def toString() = \"zero\"\n}\n\nobject TFFactorization {\n def extractExponent(divisor: Int) (toFactor: Int) = {\n @tailrec\n def runningExponentCount(currExp: Int, currN: Int): Int = \n if (currN % divisor == 0) runningExponentCount(currExp + 1, currN / divisor) else currExp\n runningExponentCount(0, toFactor)\n }\n def extractTwos = extractExponent(2) _\n def extractFives = extractExponent(5) _\n\n def apply(num: Int): TFFactorization = \n if (num == 0) \n ZeroFact()\n else\n new ProperFact(extractTwos(num), extractFives(num))\n}\n\nclass Path(fact25: TFFactorization, lastStep: Direction.Direction) {\n\n def evaluate(finalCellFact: TFFactorization) = \n finalCellFact match {\n case ZeroFact() => 1\n case ProperFact(_, _) => (fact25 * finalCellFact).tailZeros\n }\n\n def augmentPath(currCellFact: TFFactorization, nextStep: Direction.Direction) = {\n new Path(currCellFact * fact25, nextStep)\n }\n\n def isBetter(other: Path, finalCellFact: TFFactorization) =\n (evaluate(finalCellFact) <= other.evaluate(finalCellFact))\n\n def cost() = fact25.tailZeros\n\n override def toString() = fact25.toString + \" \" + lastStep\n\n def step() = lastStep\n}\n\nobject Path {\n def singleStep(num: Int) = new Path(TFFactorization(num), Direction.Blank)\n\n def getBestPath(leftNeighbour: Path, topNeighbour: Path, finalFact: TFFactorization, currFact: TFFactorization): Path =\n if (leftNeighbour.isBetter(topNeighbour, finalFact))\n leftNeighbour.augmentPath(currFact, Direction.Right)\n else \n topNeighbour.augmentPath(currFact, Direction.Down)\n}\n"}, {"source_code": "\nobject solution {\n def solve(n: Int, cost: Array[Array[Int]]): (Int, String) = {\n val INF = 10000\n val rv = Array.fill[Int](n, n)(0)\n val rp = Array.fill[Char](n, n)(' ')\n rv(0)(0) = cost(0)(0)\n for (y <- 0 until n; x <- 0 until n if x + y > 0) {\n var res = INF\n var resp = ' '\n if (y > 0) {\n res = rv(y - 1)(x)\n resp = 'D'\n }\n if (x > 0 && res > rv(y)(x-1)) {\n res = rv(y)(x - 1)\n resp = 'L'\n }\n rv(y)(x) = res + cost(y)(x)\n rp(y)(x) = resp\n }\n var (y, x) = (n-1, n-1)\n var path = \"\"\n while (y + x > 0) {\n if (rp(y)(x) == 'L') {\n path = \"L\" + path\n x -= 1\n } else {\n path = \"D\" + path\n y -= 1\n }\n }\n (rv(n-1)(n-1), path)\n }\n\n def main(args: Array[String]) = {\n val n = io.StdIn.readInt()\n val twos = Array.fill[Int](n, n)(0)\n val fives = Array.fill[Int](n, n)(0)\n\n def power_of(x: Int, p: Int): Int = {\n var result = 0\n var left = x\n while (left % p == 0) {\n result += 1\n left /= p\n }\n result\n }\n\n for (y <- 0 until n) {\n val line = io.StdIn.readLine().split(\" \").map(_.toInt)\n for (x <- 0 until n) {\n twos(y)(x) = power_of(line(x), 2)\n fives(y)(x) = power_of(line(x), 5)\n }\n }\n\n val s2 = solve(n, twos)\n val s5 = solve(n, fives)\n if (s2._1 <= s5._1)\n printf(\"%d\\n%s\\n\", s2._1, s2._2)\n else\n printf(\"%d\\n%s\\n\", s5._1, s5._2)\n }\n}"}, {"source_code": "\nobject solution {\n def solve(n: Int, cost: Array[Array[Int]]): (Int, String) = {\n val INF = 100000\n val rv = Array.fill[Int](n, n)(0)\n val rp = Array.fill[Char](n, n)(' ')\n rv(0)(0) = cost(0)(0)\n for (y <- 0 until n; x <- 0 until n if x + y > 0) {\n var res = INF\n var resp = ' '\n if (y > 0) {\n res = rv(y - 1)(x)\n resp = 'D'\n }\n if (x > 0 && res > rv(y)(x-1)) {\n res = rv(y)(x - 1)\n resp = 'R'\n }\n rv(y)(x) = res + cost(y)(x)\n rp(y)(x) = resp\n }\n var (y, x) = (n-1, n-1)\n var path = new StringBuilder()\n while (y + x > 0) {\n if (rp(y)(x) == 'R') {\n path += 'R'\n x -= 1\n } else {\n path += 'D'\n y -= 1\n }\n }\n (rv(n-1)(n-1), path.reverse.toString())\n }\n\n def main(args: Array[String]) = {\n val n = io.StdIn.readInt()\n val twos = Array.fill[Int](n, n)(0)\n val fives = Array.fill[Int](n, n)(0)\n\n def power_of(x: Int, p: Int): Int = {\n var result = 0\n var left = x\n while (left % p == 0) {\n result += 1\n left /= p\n }\n result\n }\n var zero_point: Option[(Int, Int)] = None\n for (y <- 0 until n) {\n val line = io.StdIn.readLine().split(\" \").map(_.toInt)\n for (x <- 0 until n) {\n if (line(x) > 0) {\n twos(y)(x) = power_of(line(x), 2)\n fives(y)(x) = power_of(line(x), 5)\n } else {\n zero_point = Some((x, y))\n }\n }\n }\n if (zero_point.isDefined) {\n val (x, y) = zero_point.get\n printf(\"0\\n\")\n println((\"R\" * x) + (\"D\" * y) + (\"R\" * (n-x - 1)) + (\"D\" * (n-y - 1)))\n\n } else {\n val s2 = solve(n, twos)\n val s5 = solve(n, fives)\n if (s2._1 <= s5._1)\n printf(\"%d\\n%s\\n\", s2._1, s2._2)\n else\n printf(\"%d\\n%s\\n\", s5._1, s5._2)\n }\n }\n\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n\n def toPair(a: Int): (Long, Long) = {\n var fives = 0\n var twos = 0\n var c = a\n while (c % 2 == 0 || c % 5 == 0) {\n if (c % 2 == 0) {\n c /= 2\n twos += 1\n }\n else {\n c /= 5\n fives += 1\n }\n }\n (twos, fives)\n }\n\n def join(a: List[(Long, Long)], b: List[(Long, Long)]): List[(Long, Long)] = {\n val candidates = (a ::: b).sorted\n candidates.foldLeft(List.empty[(Long, Long)]) {\n case(Nil, el) => List(el)\n case(list@((a2, a5) :: xs), (b2, b5)) if b2 >= a2 && b5 >= a5 => list\n case(list, el) => el :: list\n }\n }\n\n val pairs = in.take(n).map(_.split(' ').map(_.toInt).map(toPair)).toArray\n val dp = Array.ofDim[List[(Long, Long)]](n, n)\n (0 until n).foreach { i =>\n (0 until n).foreach { j =>\n val pair = pairs(i)(j)\n if (i == 0 && j == 0)\n dp(i)(j) = List(pair)\n else if (i == 0)\n dp(i)(j) = dp(i)(j - 1).map(x => (x._1 + pair._1, x._2 + pair._2))\n else if (j == 0)\n dp(i)(j) = dp(i - 1)(j).map(x => (x._1 + pair._1, x._2 + pair._2))\n else\n dp(i)(j) = join(dp(i)(j - 1).map(x => (x._1 + pair._1, x._2 + pair._2)),\n dp(i - 1)(j).map(x => (x._1 + pair._1, x._2 + pair._2)))\n }\n }\n var x = n - 1\n var y = n - 1\n var answer = List.empty[Char]\n\n while (x != 0 || y != 0) {\n val pair = pairs(y)(x)\n val last = dp(y)(x).minBy(i => Math.min(i._1, i._2))\n val previous = (last._1 - pair._1, last._2 - pair._2)\n val upCandidate = y != 0 && dp(y - 1)(x).contains(previous)\n if (upCandidate) {\n answer ::= 'D'\n y -= 1\n } else {\n answer ::= 'R'\n x -= 1\n }\n }\n\n println(dp(n - 1)(n - 1).map(i => Math.min(i._1, i._2)).min)\n println(answer.mkString)\n\n\n\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n\n def toPair(a: Int): (Int, Int) = {\n var fives = 0\n var twos = 0\n var c = a\n while (c % 2 == 0 || c % 5 == 0) {\n if (c % 2 == 0) {\n c /= 2\n twos += 1\n }\n else {\n c /= 5\n fives += 1\n }\n }\n (twos, fives)\n }\n\n def join(a: List[(Int, Int)], b: List[(Int, Int)]): List[(Int, Int)] = {\n val candidates = (a ::: b).sorted\n candidates.foldLeft(List.empty[(Int, Int)]) {\n case(Nil, el) => List(el)\n case(list@((a2, a5) :: xs), (b2, b5)) if b2 >= a2 && b5 >= a5 => list\n case(list, el) => el :: list\n }\n }\n\n val line = in.take(n).map(_.split(' ').map{i => \n val t = i.toInt\n if (t == 0) 10 else t\n }).toArray\n val pairs = line.map(_.map(toPair))\n val dp2 = Array.ofDim[Int](n, n)\n val dp5 = Array.ofDim[Int](n, n)\n (0 until n).foreach { i =>\n (0 until n).foreach { j =>\n val pair = pairs(i)(j)\n if (i == 0 && j == 0) {\n dp2(i)(j) = pair._1\n dp5(i)(j) = pair._2\n }\n else if (i == 0) {\n dp2(i)(j) = dp2(i)(j - 1) + pairs(i)(j)._1\n dp5(i)(j) = dp5(i)(j - 1) + pairs(i)(j)._2\n }\n else if (j == 0) {\n dp2(i)(j) = dp2(i - 1)(j) + pairs(i)(j)._1\n dp5(i)(j) = dp5(i - 1)(j) + pairs(i)(j)._2\n }\n else {\n dp2(i)(j) = Math.min(dp2(i - 1)(j), dp2(i)(j - 1)) + pairs(i)(j)._1\n dp5(i)(j) = Math.min(dp5(i - 1)(j), dp5(i)(j - 1)) + pairs(i)(j)._2\n }\n }\n }\n var x = n - 1\n var y = n - 1\n var answer = List.empty[Char]\n\n while (x != 0 || y != 0) {\n val pair = pairs(y)(x)\n val upCandidate = y != 0 && (x == 0 || Math.min(dp2(y - 1)(x), dp5(y - 1)(x)) <= Math.min(dp2(y)(x - 1), dp5(y)(x - 1)))\n if (upCandidate) {\n answer ::= 'D'\n y -= 1\n } else {\n answer ::= 'R'\n x -= 1\n }\n }\n\n println(Math.min(dp2(n - 1)(n - 1), dp5(n - 1)(n - 1)))\n println(answer.mkString)\n\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n\n def toPair(a: Int): (Int, Int) = {\n var fives = 0\n var twos = 0\n var c = a\n while (c % 2 == 0 || c % 5 == 0) {\n if (c % 2 == 0) {\n c /= 2\n twos += 1\n }\n else {\n c /= 5\n fives += 1\n }\n }\n (twos, fives)\n }\n\n def join(a: List[(Int, Int)], b: List[(Int, Int)]): List[(Int, Int)] = {\n a ::: b\n }\n\n val pairs = in.take(n).map(_.split(' ').map(_.toInt).map(toPair)).toArray\n val dp = Array.ofDim[List[(Int, Int)]](n, n)\n (0 until n).foreach { i =>\n (0 until n).foreach { j =>\n val pair = pairs(i)(j)\n if (i == 0 && j == 0)\n dp(i)(j) = List(pair)\n else if (i == 0)\n dp(i)(j) = dp(i)(j - 1).map(x => (x._1 + pair._1, x._2 + pair._2))\n else if (j == 0)\n dp(i)(j) = dp(i - 1)(j).map(x => (x._1 + pair._1, x._2 + pair._2))\n else\n dp(i)(j) = join(dp(i)(j - 1).map(x => (x._1 + pair._1, x._2 + pair._2)),\n dp(i - 1)(j).map(x => (x._1 + pair._1, x._2 + pair._2)))\n }\n }\n var x = n - 1\n var y = n - 1\n var answer = List.empty[Char]\n\n while (x != 0 || y != 0) {\n val pair = pairs(y)(x)\n val last = dp(y)(x).minBy(i => Math.min(i._1, i._2))\n val previous = (last._1 - pair._1, last._2 - pair._2)\n val upCandidate = y != 0 && dp(y - 1)(x).contains(previous)\n if (upCandidate) {\n answer ::= 'D'\n y -= 1\n } else {\n answer ::= 'R'\n x -= 1\n }\n }\n\n println(dp(n - 1)(n - 1).map(i => Math.min(i._1, i._2)).min)\n println(answer.mkString)\n\n\n\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n\n val line = in.take(n).map(_.split(' ').map(_.toInt)).toArray\n\n def f(a: Int, k: Int) = {\n var r = 0\n var m = a\n\n while (m != 0 && m % k == 0) {\n m /= k\n r += 1\n }\n r\n }\n\n def dp(k: Int) = {\n val dp = line.map(_.map(i => f(i, k)))\n\n (1 until n).foreach { i =>\n dp(i)(0) += dp(i - 1)(0)\n dp(0)(i) += dp(0)(i - 1)\n }\n\n (1 until n).foreach { i =>\n (1 until n).foreach { j =>\n dp(i)(j) += Math.min(dp(i - 1)(j), dp(i)(j - 1))\n }\n }\n\n dp\n }\n\n val dpr = List(2, 5).map(dp).minBy(d => d(n - 1)(n - 1))\n\n var min = dpr(n - 1)(n - 1)\n var x = n - 1\n var y = n - 1\n var answer = List.empty[Char]\n\n while (x != 0 || y != 0) {\n val upCandidate = y != 0 && (x == 0 || dpr(y - 1)(x) <= dpr(y)(x - 1))\n if (upCandidate) {\n answer ::= 'D'\n y -= 1\n } else {\n answer ::= 'R'\n x -= 1\n }\n }\n\n println(min)\n println(answer.mkString)\n\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n\n def toPair(a: Int): (Int, Int) = {\n var fives = 0\n var twos = 0\n var c = a\n while (c % 2 == 0 || c % 5 == 0) {\n if (c % 2 == 0) {\n c /= 2\n twos += 1\n }\n else {\n c /= 5\n fives += 1\n }\n }\n (twos, fives)\n }\n\n def join(a: List[(Int, Int)], b: List[(Int, Int)]): List[(Int, Int)] = {\n val candidates = (a ::: b).sorted\n candidates.foldLeft(List.empty[(Int, Int)]) {\n case(Nil, el) => List(el)\n case(list@((a2, a5) :: xs), (b2, b5)) if b2 >= a2 && b5 >= a5 => list\n case(list, el) => el :: list\n }\n }\n\n val pairs = in.take(n).map(_.split(' ').map(_.toInt).map(toPair)).toArray\n val dp = Array.ofDim[List[(Int, Int)]](n, n)\n (0 until n).foreach { i =>\n (0 until n).foreach { j =>\n val pair = pairs(i)(j)\n if (i == 0 && j == 0)\n dp(i)(j) = List(pair)\n else if (i == 0)\n dp(i)(j) = dp(i)(j - 1).map(x => (x._1 + pair._1, x._2 + pair._2))\n else if (j == 0)\n dp(i)(j) = dp(i - 1)(j).map(x => (x._1 + pair._1, x._2 + pair._2))\n else\n dp(i)(j) = join(dp(i)(j - 1).map(x => (x._1 + pair._1, x._2 + pair._2)),\n dp(i - 1)(j).map(x => (x._1 + pair._1, x._2 + pair._2)))\n }\n }\n var x = n - 1\n var y = n - 1\n var answer = List.empty[Char]\n\n while (x != 0 || y != 0) {\n val pair = pairs(y)(x)\n val last = dp(y)(x).minBy(i => Math.min(i._1, i._2))\n val previous = (last._1 - pair._1, last._2 - pair._2)\n val upCandidate = y != 0 && dp(y - 1)(x).contains(previous)\n if (upCandidate) {\n answer ::= 'D'\n y -= 1\n } else {\n answer ::= 'R'\n x -= 1\n }\n }\n\n println(dp(n - 1)(n - 1).map(i => Math.min(i._1, i._2)).min)\n println(answer.mkString)\n\n\n\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n\n def toPair(a: Int): (Int, Int) = {\n var fives = 0\n var twos = 0\n var c = a\n while (c % 2 == 0 || c % 5 == 0) {\n if (c % 2 == 0) {\n c /= 2\n twos += 1\n }\n else {\n c /= 5\n fives += 1\n }\n }\n (twos, fives)\n }\n\n def join(a: List[(Int, Int)], b: List[(Int, Int)]): List[(Int, Int)] = {\n val candidates = (a ::: b).sorted\n candidates.foldLeft(List.empty[(Int, Int)]) {\n case(Nil, el) => List(el)\n case(list@((a2, a5) :: xs), (b2, b5)) if b2 >= a2 && b5 >= a5 => list\n case(list, el) => el :: list\n }\n }\n\n val pairs = in.take(n).map(_.split(' ').map(_.toInt).map(toPair)).toArray\n val dp = Array.ofDim[List[(Int, Int)]](n, n)\n (0 until n).foreach { i =>\n (0 until n).foreach { j =>\n val pair = pairs(i)(j)\n if (i == 0 && j == 0)\n dp(i)(j) = List(pair)\n else if (i == 0)\n dp(i)(j) = dp(i)(j - 1).map(x => (x._1 + pair._1, x._2 + pair._2))\n else if (j == 0)\n dp(i)(j) = dp(i - 1)(j).map(x => (x._1 + pair._1, x._2 + pair._2))\n else\n dp(i)(j) = join(dp(i)(j - 1).map(x => (x._1 + pair._1, x._2 + pair._2)),\n dp(i - 1)(j).map(x => (x._1 + pair._1, x._2 + pair._2)))\n }\n }\n var x = n - 1\n var y = n - 1\n var answer = List.empty[Char]\n\n while (x != 0 || y != 0) {\n val pair = pairs(y)(x)\n val last = dp(y)(x).minBy(i => Math.min(i._1, i._2))\n val previous = (last._1 - pair._1, last._2 - pair._2)\n val upCandidate = y != 0 && dp(y - 1)(x).contains(previous)\n if (upCandidate) {\n answer ::= 'D'\n y -= 1\n } else {\n answer ::= 'R'\n x -= 1\n }\n }\n\n println(dp(n - 1)(n - 1).map(i => Math.min(i._1, i._2)).min)\n println(answer.reverse.mkString)\n\n\n\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n\n def toPair(a: Int): (Int, Int) = {\n var fives = 0\n var twos = 0\n var c = a\n while (c % 2 == 0 || c % 5 == 0) {\n if (c % 2 == 0) {\n c /= 2\n twos += 1\n }\n else {\n c /= 5\n fives += 1\n }\n }\n (twos, fives)\n }\n\n def join(a: List[(Int, Int)], b: List[(Int, Int)]): List[(Int, Int)] = {\n val candidates = (a ::: b).sorted\n candidates.foldLeft(List.empty[(Int, Int)]) {\n case(Nil, el) => List(el)\n case(list@((a2, a5) :: xs), (b2, b5)) if b2 >= a2 && b5 >= a5 => list\n case(list, el) => el :: list\n }\n }\n\n val pairs = in.take(n).map(_.split(' ').map(_.toInt).map(toPair)).toArray\n val dp = Array.ofDim[List[(Int, Int)]](n, n)\n (0 until n).foreach { i =>\n (0 until n).foreach { j =>\n val pair = pairs(i)(j)\n if (i == 0 && j == 0)\n dp(i)(j) = List(pair)\n else if (i == 0)\n dp(i)(j) = dp(i)(j - 1).map(x => (x._1 + pair._1, x._2 + pair._2))\n else if (j == 0)\n dp(i)(j) = dp(i - 1)(j).map(x => (x._1 + pair._1, x._2 + pair._2))\n else\n dp(i)(j) = join(dp(i)(j - 1).map(x => (x._1 + pair._1, x._2 + pair._2)),\n dp(i - 1)(j).map(x => (x._1 + pair._1, x._2 + pair._2)))\n }\n }\n var x = n - 1\n var y = n - 1\n var answer = List.empty[Char]\n\n while (x != 0 || y != 0) {\n val pair = pairs(y)(x)\n val last = dp(y)(x).minBy(i => Math.min(i._1, i._2))\n val previous = (last._1 - pair._1, last._2 - pair._2)\n val upCandidate = y != 0 && dp(y - 1)(x).contains(previous)\n if (upCandidate) {\n answer ::= 'R'\n y -= 1\n } else {\n answer ::= 'D'\n x -= 1\n }\n }\n\n println(dp(n - 1)(n - 1).map(i => Math.min(i._1, i._2)).min)\n println(answer.mkString)\n\n\n\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n\n def toPair(a: Int): (Int, Int) = {\n var fives = 0\n var twos = 0\n var c = a\n while (c % 2 == 0 || c % 5 == 0) {\n if (c % 2 == 0) {\n c /= 2\n twos += 1\n }\n else {\n c /= 5\n fives += 1\n }\n }\n (twos, fives)\n }\n\n def join(a: List[(Int, Int)], b: List[(Int, Int)]): List[(Int, Int)] = {\n val candidates = (a ::: b).sorted\n candidates.foldLeft(List.empty[(Int, Int)]) {\n case(Nil, el) => List(el)\n case(list@((a2, a5) :: xs), (b2, b5)) if b2 >= a2 && b5 >= a5 => list\n case(list, el) => el :: list\n }\n }\n\n val pairs = in.take(n).map(_.split(' ').map(_.toInt).map(toPair)).toArray\n val dp2 = Array.ofDim[Int](n, n)\n val dp5 = Array.ofDim[Int](n, n)\n (0 until n).foreach { i =>\n (0 until n).foreach { j =>\n val pair = pairs(i)(j)\n if (i == 0 && j == 0) {\n dp2(i)(j) = pair._1\n dp5(i)(j) = pair._2\n }\n else if (i == 0) {\n dp2(i)(j) = dp2(i)(j - 1) + pairs(i)(j)._1\n dp5(i)(j) = dp5(i)(j - 1) + pairs(i)(j)._2\n }\n else if (j == 0) {\n dp2(i)(j) = dp2(i - 1)(j) + pairs(i)(j)._1\n dp5(i)(j) = dp5(i - 1)(j) + pairs(i)(j)._2\n }\n else {\n dp2(i)(j) = Math.min(dp2(i - 1)(j), dp2(i)(j - 1)) + pairs(i)(j)._1\n dp5(i)(j) = Math.min(dp5(i - 1)(j), dp5(i)(j - 1)) + pairs(i)(j)._2\n }\n }\n }\n var x = n - 1\n var y = n - 1\n var answer = List.empty[Char]\n\n while (x != 0 || y != 0) {\n val pair = pairs(y)(x)\n val upCandidate = y != 0 && (x == 0 || Math.min(dp2(y - 1)(x), dp5(y - 1)(x)) <= Math.min(dp2(y)(x - 1), dp5(y)(x - 1)))\n if (upCandidate) {\n answer ::= 'D'\n y -= 1\n } else {\n answer ::= 'R'\n x -= 1\n }\n }\n\n println(Math.min(dp2(n - 1)(n - 1), dp5(n - 1)(n - 1)))\n println(answer.mkString)\n\n}"}, {"source_code": "import scala.collection.mutable.HashMap\nimport scala.math.min\n\n\nobject testing {\n\n def findPower5(input : Int) : Int = {\n if (input == 0) {\n return 50000\n }\n var temp = input\n var returnValue = 0\n while (temp % 5 == 0) {\n returnValue += 1\n temp /= 5\n }\n return returnValue\n }\n\n def findPower2(input : Int) : Int = {\n if (input == 0) {\n return 50000\n }\n var temp = input\n var returnValue = 0\n while (temp % 2 == 0) {\n returnValue += 1\n temp /= 2\n }\n return returnValue\n }\n\n def main(args: Array[String]) : Unit = {\n var matrixSize: Int = scala.io.StdIn.readInt()\n var inputMatrix = Array.ofDim[Int](matrixSize,matrixSize)\n var fiveMatrix = Array.ofDim[Int](matrixSize,matrixSize)\n var twoMatrix = Array.ofDim[Int](matrixSize,matrixSize)\n var existsZero = false\n var zeroX = -1\n var zeroY = -1\n for (i <- 0 until matrixSize) {\n var inputLine = scala.io.StdIn.readLine()\n var inputSplit = inputLine.split(\" \")\n for (j <- 0 until matrixSize) {\n inputMatrix(i)(j) = inputSplit(j).toInt\n if (inputMatrix(i)(j) == 0) {\n existsZero = true\n zeroY = i\n zeroX = j\n }\n fiveMatrix(i)(j) = 0\n twoMatrix(i)(j) = 0\n }\n }\n fiveMatrix(0)(0) = findPower5(inputMatrix(0)(0))\n for (i <- 1 until matrixSize) {\n fiveMatrix(0)(i) = fiveMatrix(0)(i-1) + findPower5(inputMatrix(0)(i))\n }\n for (i <- 1 until matrixSize) {\n fiveMatrix(i)(0) = fiveMatrix(i-1)(0) + findPower5(inputMatrix(i)(0))\n }\n for (i <- 1 until matrixSize;\n j <- 1 until matrixSize) {\n fiveMatrix(i)(j) = min(fiveMatrix(i)(j-1) + findPower5(inputMatrix(i)(j)), \n fiveMatrix(i-1)(j) + findPower5(inputMatrix(i)(j)))\n }\n\n twoMatrix(0)(0) = findPower2(inputMatrix(0)(0))\n for (i <- 1 until matrixSize) {\n twoMatrix(0)(i) = twoMatrix(0)(i-1) + findPower2(inputMatrix(0)(i))\n }\n for (i <- 1 until matrixSize) {\n twoMatrix(i)(0) = twoMatrix(i-1)(0) + findPower2(inputMatrix(i)(0))\n }\n for (i <- 1 until matrixSize;\n j <- 1 until matrixSize) {\n twoMatrix(i)(j) = min(twoMatrix(i)(j-1) + findPower2(inputMatrix(i)(j)), \n twoMatrix(i-1)(j) + findPower2(inputMatrix(i)(j)))\n }\n\n var output : String = \"\"\n if (min(twoMatrix(matrixSize - 1)(matrixSize - 1),\n fiveMatrix(matrixSize - 1)(matrixSize - 1)) > 1 && existsZero) {\n // find zero path\n for (i <- 0 until zeroX) {\n output = output + \"R\"\n }\n for (i <- 0 until matrixSize - 1) {\n output = output + \"D\"\n }\n for (i <- zeroX until matrixSize - 1) {\n output = output + \"R\"\n }\n println(1)\n println(output)\n return;\n }\n\n if (twoMatrix(matrixSize - 1)(matrixSize - 1) < fiveMatrix(matrixSize - 1)(matrixSize - 1)) {\n var currX = matrixSize - 1\n var currY = matrixSize - 1\n while (currX != 0 || currY != 0) {\n if (currX != 0 && twoMatrix(currY)(currX - 1) <= twoMatrix(currY)(currX)) {\n output = \"R\" + output\n currX = currX - 1\n } else {\n output = \"D\" + output\n currY = currY - 1\n }\n }\n println(twoMatrix(matrixSize - 1)(matrixSize - 1))\n println(output)\n return\n } else {\n var currX = matrixSize - 1\n var currY = matrixSize - 1\n while (currX != 0 || currY != 0) {\n if (currX != 0 && fiveMatrix(currY)(currX - 1) <= fiveMatrix(currY)(currX)) {\n output = \"R\" + output\n currX = currX - 1\n } else {\n output = \"D\" + output\n currY = currY - 1\n }\n }\n println(fiveMatrix(matrixSize - 1)(matrixSize - 1))\n println(output)\n return\n }\n }\n}"}, {"source_code": "import scala.collection.mutable\nimport java.util.Scanner\nimport scala.util.Random\n\nobject Path extends App {\n\n val scanner = new Scanner(System.in)\n\n val dim = scanner.nextInt()\n\n val matrix = Array.ofDim[Long](dim, dim)\n\n (0 until dim) foreach {\n y =>\n (0 until dim) foreach {\n x =>\n matrix(x)(y) = scanner.nextLong()\n }\n }\n\n val queue = new mutable.PriorityQueue[Edge]()\n\n solve(Edge(0, 0, findTwoCount(0, 0), findFiveCount(0, 0), None, direction = false), Set())\n\n def traceBack(edge: Option[Edge]): List[Char] = {\n edge match {\n case Some(v) => if (v.direction) 'D' :: traceBack(v.prev) else 'R' :: traceBack(v.prev)\n case None => Nil\n }\n }\n\n case class Point(x: Int, y: Int)\n\n def solve(curEdge: Edge, visited: Set[Point]): Unit = {\n if (curEdge.last) {\n println(curEdge.weight.toInt)\n println(traceBack(Some(curEdge)).reverse.tail.mkString)\n } else {\n curEdge.neighbours.filterNot(it => visited.contains(Point(it.x, it.y))).foreach(queue += _)\n solve(queue.dequeue(), visited + Point(curEdge.x, curEdge.y))\n }\n\n }\n\n def findTwoCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 2)\n\n def findFiveCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 5)\n\n def findDivNum(item: Long, num: Int): Int = {\n def find(curItem: Long, acc: Int): Int = {\n if (curItem % num == 0)\n find(curItem / num, acc + 1)\n else\n acc\n }\n find(item, 0)\n }\n\n\n case class Edge(x: Int, y: Int, twoCount: Int, fiveCount: Int, prev: Option[Edge], direction: Boolean) extends Ordered[Edge] {\n\n def weight:Double = {\n val common = Math.min(twoCount, fiveCount)\n if (scala.math.abs(twoCount - fiveCount) > 0) common + 0.5 else common\n }\n\n override def compare(that: Edge): Int = {\n that.weight.compareTo(this.weight)\n }\n\n private def createDownEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x, y + 1)\n val downTwos = twoCount + findTwoCount(x, y + 1)\n Edge(x, y + 1, downTwos, downFives, Some(this), true)\n }\n\n private def createRightEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x + 1, y)\n val downTwos = twoCount + findTwoCount(x + 1, y)\n Edge(x + 1, y, downTwos, downFives, Some(this), false)\n }\n\n def neighbours: List[Edge] = {\n if (x == matrix.length - 1) {\n List(createDownEdge())\n } else if (y == matrix.length - 1) {\n List(createRightEdge())\n } else {\n List(createRightEdge(), createDownEdge())\n }\n }\n\n def last: Boolean = x == matrix.length - 1 && y == matrix.length - 1\n\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport java.util.Scanner\n\nobject Path extends App {\n\n val scanner = new Scanner(System.in)\n\n val dim = scanner.nextInt()\n\n val matrix = Array.ofDim[Long](dim, dim)\n\n var zeroPoint: Option[Point] = None\n\n (0 until dim) foreach {\n y =>\n (0 until dim) foreach {\n x =>\n matrix(x)(y) = scanner.nextLong()\n if (matrix(x)(y) == 0) {\n zeroPoint = Some(Point(x, y))\n matrix(x)(y) == 10\n }\n }\n }\n\n val queue = new mutable.PriorityQueue[Edge]()\n\n solve(Edge(0, 0, findTwoCount(0, 0), findFiveCount(0, 0), None, direction = false), Set())\n\n def traceBack(edge: Option[Edge]): List[Char] = {\n edge match {\n case Some(v) => if (v.direction) 'D' :: traceBack(v.prev) else 'R' :: traceBack(v.prev)\n case None => Nil\n }\n }\n\n case class Point(x: Int, y: Int)\n\n def printZeroPath(p: Point): Unit = {\n println(1)\n (0 until p.x).foreach(t => print(\"R\"))\n (0 until dim).foreach(t => print(\"D\"))\n (p.x until dim).foreach(t => print(\"R\"))\n }\n\n def printResult(edge: Edge): Unit = {\n zeroPoint match {\n case None =>\n println(edge.pureWeight)\n println(traceBack(Some(edge)).reverse.tail.mkString)\n case Some(v) if edge.pureWeight == 0 =>\n println(edge.pureWeight)\n println(traceBack(Some(edge)).reverse.tail.mkString)\n case Some(v) => printZeroPath(v)\n }\n\n }\n\n def solve(curEdge: Edge, visited: Set[Point]): Unit = {\n if (curEdge.last) {\n printResult(curEdge)\n } else {\n curEdge.neighbours.filterNot(it => visited.contains(Point(it.x, it.y))).foreach(queue += _)\n solve(queue.dequeue(), visited + Point(curEdge.x, curEdge.y))\n }\n\n }\n\n def findTwoCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 2)\n\n def findFiveCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 5)\n\n def findDivNum(item: Long, num: Int): Int = {\n def find(curItem: Long, acc: Int): Int = {\n if (curItem % num == 0)\n find(curItem / num, acc + 1)\n else\n acc\n }\n find(item, 0)\n }\n\n\n case class Edge(x: Int, y: Int, twoCount: Int, fiveCount: Int, prev: Option[Edge], direction: Boolean) extends Ordered[Edge] {\n\n def weight = {\n Math.min(twoCount, fiveCount) * 100 + twoCount * 2 + fiveCount\n }\n\n def pureWeight = {\n Math.min(twoCount, fiveCount)\n }\n\n override def compare(that: Edge): Int = {\n that.weight.compareTo(this.weight)\n }\n\n private def createDownEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x, y + 1)\n val downTwos = twoCount + findTwoCount(x, y + 1)\n Edge(x, y + 1, downTwos, downFives, Some(this), true)\n }\n\n private def createRightEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x + 1, y)\n val downTwos = twoCount + findTwoCount(x + 1, y)\n Edge(x + 1, y, downTwos, downFives, Some(this), false)\n }\n\n def neighbours: List[Edge] = {\n if (x == matrix.length - 1) {\n List(createDownEdge())\n } else if (y == matrix.length - 1) {\n List(createRightEdge())\n } else {\n List(createRightEdge(), createDownEdge())\n }\n }\n\n def last: Boolean = x == matrix.length - 1 && y == matrix.length - 1\n\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport java.util.Scanner\nimport scala.util.Random\n\nobject Path extends App {\n\n val scanner = new Scanner(System.in)\n\n val dim = scanner.nextInt()\n\n val matrix = Array.ofDim[Long](dim, dim)\n\n var zeroPoint: Option[Point] = None\n\n (0 until dim) foreach {\n y =>\n (0 until dim) foreach {\n x =>\n matrix(x)(y) = scanner.nextLong()\n if (matrix(x)(y) == 0) {\n zeroPoint = Some(Point(x, y))\n matrix(x)(y) == 10\n }\n }\n }\n\n val queue = new mutable.PriorityQueue[Edge]()\n\n solve(Edge(0, 0, findTwoCount(0, 0), findFiveCount(0, 0), None, direction = false), Set())\n\n def traceBack(edge: Option[Edge]): List[Char] = {\n edge match {\n case Some(v) => if (v.direction) 'D' :: traceBack(v.prev) else 'R' :: traceBack(v.prev)\n case None => Nil\n }\n }\n\n case class Point(x: Int, y: Int)\n\n def printZeroPath(p: Point): Unit = {\n println(1)\n (0 until p.x).foreach(t => print(\"R\"))\n (0 until dim).foreach(t => print(\"D\"))\n (p.x until dim).foreach(t => print(\"R\"))\n }\n\n def printResult(edge: Edge): Unit = {\n zeroPoint match {\n case None =>\n println(edge.weight)\n println(traceBack(Some(edge)).reverse.tail.mkString)\n case Some(v) if edge.weight == 0 =>\n println(edge.weight)\n println(traceBack(Some(edge)).reverse.tail.mkString)\n case Some(v) => printZeroPath(v)\n }\n\n }\n\n def solve(curEdge: Edge, visited: Set[Point]): Unit = {\n if (curEdge.last) {\n printResult(curEdge)\n } else {\n curEdge.neighbours.filterNot(it => visited.contains(Point(it.x, it.y))).foreach(queue += _)\n solve(queue.dequeue(), visited + Point(curEdge.x, curEdge.y))\n }\n\n }\n\n def findTwoCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 2)\n\n def findFiveCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 5)\n\n def findDivNum(item: Long, num: Int): Int = {\n def find(curItem: Long, acc: Int): Int = {\n if (curItem % num == 0)\n find(curItem / num, acc + 1)\n else\n acc\n }\n find(item, 0)\n }\n\n\n case class Edge(x: Int, y: Int, twoCount: Int, fiveCount: Int, prev: Option[Edge], direction: Boolean) extends Ordered[Edge] {\n\n def weight = {\n Math.min(twoCount, fiveCount) * 100 + twoCount*2 + fiveCount\n }\n\n override def compare(that: Edge): Int = {\n that.weight.compareTo(this.weight)\n }\n\n private def createDownEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x, y + 1)\n val downTwos = twoCount + findTwoCount(x, y + 1)\n Edge(x, y + 1, downTwos, downFives, Some(this), true)\n }\n\n private def createRightEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x + 1, y)\n val downTwos = twoCount + findTwoCount(x + 1, y)\n Edge(x + 1, y, downTwos, downFives, Some(this), false)\n }\n\n def neighbours: List[Edge] = {\n if (x == matrix.length - 1) {\n List(createDownEdge())\n } else if (y == matrix.length - 1) {\n List(createRightEdge())\n } else {\n List(createRightEdge(), createDownEdge())\n }\n }\n\n def last: Boolean = x == matrix.length - 1 && y == matrix.length - 1\n\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport java.util.Scanner\nimport scala.util.Random\n\nobject Path extends App {\n\n val scanner = new Scanner(System.in)\n\n val dim = scanner.nextInt()\n\n val matrix = Array.ofDim[Long](dim, dim)\n\n var zeroPoint: Option[Point] = None\n\n (0 until dim) foreach {\n y =>\n (0 until dim) foreach {\n x =>\n matrix(x)(y) = scanner.nextLong()\n if (matrix(x)(y) == 0) {\n zeroPoint = Some(Point(x,y))\n matrix(x)(y) == 10\n }\n }\n }\n\n zeroPoint = Some(Point(3,3))\n\n val queue = new mutable.PriorityQueue[Edge]()\n\n solve(Edge(0, 0, findTwoCount(0, 0), findFiveCount(0, 0), None, direction = false), Set())\n\n def traceBack(edge: Option[Edge]): List[Char] = {\n edge match {\n case Some(v) => if (v.direction) 'D' :: traceBack(v.prev) else 'R' :: traceBack(v.prev)\n case None => Nil\n }\n }\n\n case class Point(x: Int, y: Int)\n\n def printZeroPath(p: Point): Unit = {\n println(1)\n (0 until p.x).foreach(t => print(\"R\"))\n (0 until dim).foreach(t => print(\"D\"))\n (p.x until dim).foreach(t => print(\"R\"))\n }\n\n def printResult(edge: Edge): Unit = {\n zeroPoint match {\n case None =>\n println(edge.weight)\n println(traceBack(Some(edge)).reverse.tail.mkString)\n case Some(v) if edge.weight == 0 =>\n println(edge.weight)\n println(traceBack(Some(edge)).reverse.tail.mkString)\n case Some(v) => printZeroPath(v)\n }\n\n }\n\n def solve(curEdge: Edge, visited: Set[Point]): Unit = {\n if (curEdge.last) {\n printResult(curEdge)\n } else {\n curEdge.neighbours.filterNot(it => visited.contains(Point(it.x, it.y))).foreach(queue += _)\n solve(queue.dequeue(), visited + Point(curEdge.x, curEdge.y))\n }\n\n }\n\n def findTwoCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 2)\n\n def findFiveCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 5)\n\n def findDivNum(item: Long, num: Int): Int = {\n def find(curItem: Long, acc: Int): Int = {\n if (curItem % num == 0)\n find(curItem / num, acc + 1)\n else\n acc\n }\n find(item, 0)\n }\n\n\n case class Edge(x: Int, y: Int, twoCount: Int, fiveCount: Int, prev: Option[Edge], direction: Boolean) extends Ordered[Edge] {\n\n def weight = {\n Math.min(twoCount, fiveCount)\n }\n\n override def compare(that: Edge): Int = {\n that.weight.compareTo(this.weight)\n }\n\n private def createDownEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x, y + 1)\n val downTwos = twoCount + findTwoCount(x, y + 1)\n Edge(x, y + 1, downTwos, downFives, Some(this), true)\n }\n\n private def createRightEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x + 1, y)\n val downTwos = twoCount + findTwoCount(x + 1, y)\n Edge(x + 1, y, downTwos, downFives, Some(this), false)\n }\n\n def neighbours: List[Edge] = {\n if (x == matrix.length - 1) {\n List(createDownEdge())\n } else if (y == matrix.length - 1) {\n List(createRightEdge())\n } else {\n List(createRightEdge(), createDownEdge())\n }\n }\n\n def last: Boolean = x == matrix.length - 1 && y == matrix.length - 1\n\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.util.Random\n\nobject BLessRoundTripDynamic extends App {\n\n val scanner = new Scanner(System.in)\n\n val dim = scanner.nextInt()\n\n\n val matrix = Array.ofDim[Long](dim, dim)\n\n var zeroPoint: Option[(Int, Int)] = None\n\n (0 until dim) foreach {\n y =>\n (0 until dim) foreach {\n x =>\n matrix(x)(y) = scanner.nextLong()\n if (matrix(x)(y) == 0) {\n zeroPoint = Some((x, y))\n matrix(x)(y) == 10\n }\n }\n }\n\n def printZeroPath(p: (Int, Int)): Unit = {\n println(1)\n (0 until p._1).foreach(t => print(\"R\"))\n (0 until dim).foreach(t => print(\"D\"))\n (p._1 until dim).foreach(t => print(\"R\"))\n }\n\n case class Direction(value: Int, dir: Boolean)\n\n val divs = Array.ofDim[Direction](dim, dim)\n forEach(matrix, (x, y, v: Long) => divs(x)(y) = Direction(findDivNum(v, 5), false))\n val fiveWeight = countWeights(divs)\n val fivePath = getPath(divs)\n forEach(matrix, (x, y, v: Long) => divs(x)(y) = Direction(findDivNum(v, 2), false))\n val twoWeight = countWeights(divs)\n val twoPath = getPath(divs)\n\n if (math.min(twoWeight, fiveWeight) > 0 && zeroPoint.isDefined) {\n printZeroPath(zeroPoint.get)\n } else if (twoWeight < fiveWeight) {\n println(twoWeight)\n println(twoPath)\n } else {\n println(fiveWeight)\n println(fivePath)\n }\n\n def getPath(divs: Array[Array[Direction]]): String = {\n def traceBack(x: Int, y: Int): List[Char] = {\n if (x == 0 && y == 0) Nil\n else if (divs(x)(y).dir) 'R' :: traceBack(x - 1, y)\n else 'D' :: traceBack(x, y - 1)\n }\n traceBack(dim - 1, dim - 1).reverse.mkString\n }\n\n def countWeights(divs: Array[Array[Direction]]): Long = {\n forEach(divs, (x, y, value: Direction) => {\n if (y == 0 && x == 0) {\n divs(x)(y) = Direction(divs(x)(y).value, false)\n } else if (y == 0) {\n divs(x)(y) = Direction(divs(x)(y).value + divs(x - 1)(y).value, true)\n } else if (x == 0) {\n divs(x)(y) = Direction(divs(x)(y).value + divs(x)(y - 1).value, false)\n } else {\n if (divs(x)(y - 1).value < divs(x - 1)(y).value) {\n divs(x)(y) = Direction(divs(x)(y).value + divs(x)(y - 1).value, false)\n } else {\n divs(x)(y) = Direction(divs(x)(y).value + divs(x - 1)(y).value, true)\n }\n }\n })\n divs(dim - 1)(dim - 1).value\n }\n\n\n def findDivNum(item: Long, num: Int): Int = {\n var it = item\n while (it % num == 0) {\n it = it / num\n }\n it.toInt\n }\n\n def forEach[T](arr: Array[Array[T]], func: (Int, Int, T) => Unit): Unit = {\n (0 until dim) foreach {\n y =>\n (0 until dim) foreach {\n x =>\n func(x, y, arr(x)(y))\n }\n }\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport java.util.Scanner\n\nobject Path extends App {\n\n val scanner = new Scanner(System.in)\n\n val dim = scanner.nextInt()\n\n val matrix = Array.ofDim[Long](dim, dim)\n\n var zeroPoint: Option[Point] = None\n\n (0 until dim) foreach {\n y =>\n (0 until dim) foreach {\n x =>\n matrix(x)(y) = scanner.nextLong()\n if (matrix(x)(y) == 0) {\n zeroPoint = Some(Point(x, y))\n matrix(x)(y) == 10\n }\n }\n }\n\n val queue = new mutable.PriorityQueue[Edge]()\n\n solve(Edge(0, 0, findTwoCount(0, 0), findFiveCount(0, 0), None, direction = false), Set())\n\n def traceBack(edge: Option[Edge]): List[Char] = {\n edge match {\n case Some(v) => if (v.direction) 'D' :: traceBack(v.prev) else 'R' :: traceBack(v.prev)\n case None => Nil\n }\n }\n\n case class Point(x: Int, y: Int)\n\n def printZeroPath(p: Point): Unit = {\n println(1)\n (0 until p.x).foreach(t => print(\"R\"))\n (0 until dim).foreach(t => print(\"D\"))\n (p.x until dim).foreach(t => print(\"R\"))\n }\n\n def printResult(edge: Edge): Unit = {\n zeroPoint match {\n case None =>\n println(edge.weight)\n println(traceBack(Some(edge)).reverse.tail.mkString)\n case Some(v) if edge.weight == 0 =>\n println(edge.weight)\n println(traceBack(Some(edge)).reverse.tail.mkString)\n case Some(v) => printZeroPath(v)\n }\n\n }\n\n def solve(curEdge: Edge, visited: Set[Point]): Unit = {\n if (curEdge.last) {\n printResult(curEdge)\n } else {\n curEdge.neighbours.filterNot(it => visited.contains(Point(it.x, it.y))).foreach(queue += _)\n solve(queue.dequeue(), visited + Point(curEdge.x, curEdge.y))\n }\n\n }\n\n def findTwoCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 2)\n\n def findFiveCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 5)\n\n def findDivNum(item: Long, num: Int): Int = {\n def find(curItem: Long, acc: Int): Int = {\n if (curItem % num == 0)\n find(curItem / num, acc + 1)\n else\n acc\n }\n find(item, 0)\n }\n\n\n case class Edge(x: Int, y: Int, twoCount: Int, fiveCount: Int, prev: Option[Edge], direction: Boolean) extends Ordered[Edge] {\n\n def weight = {\n Math.min(twoCount, fiveCount) * 100 + twoCount * 2 + fiveCount\n }\n\n override def compare(that: Edge): Int = {\n that.weight.compareTo(this.weight)\n }\n\n private def createDownEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x, y + 1)\n val downTwos = twoCount + findTwoCount(x, y + 1)\n Edge(x, y + 1, downTwos, downFives, Some(this), true)\n }\n\n private def createRightEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x + 1, y)\n val downTwos = twoCount + findTwoCount(x + 1, y)\n Edge(x + 1, y, downTwos, downFives, Some(this), false)\n }\n\n def neighbours: List[Edge] = {\n if (x == matrix.length - 1) {\n List(createDownEdge())\n } else if (y == matrix.length - 1) {\n List(createRightEdge())\n } else {\n List(createRightEdge(), createDownEdge())\n }\n }\n\n def last: Boolean = x == matrix.length - 1 && y == matrix.length - 1\n\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport java.util.Scanner\nimport scala.util.Random\n\nobject Path extends App {\n\n val scanner = new Scanner(System.in)\n\n val dim = scanner.nextInt()\n\n val matrix = Array.ofDim[Long](dim, dim)\n\n var zeroPoint: Option[Point] = None\n\n (0 until dim) foreach {\n y =>\n (0 until dim) foreach {\n x =>\n matrix(x)(y) = scanner.nextLong()\n if (matrix(x)(y) == 0) {\n zeroPoint = Some(Point(x,y))\n matrix(x)(y) == 10\n }\n }\n }\n\n val queue = new mutable.PriorityQueue[Edge]()\n\n solve(Edge(0, 0, findTwoCount(0, 0), findFiveCount(0, 0), None, direction = false), Set())\n\n def traceBack(edge: Option[Edge]): List[Char] = {\n edge match {\n case Some(v) => if (v.direction) 'D' :: traceBack(v.prev) else 'R' :: traceBack(v.prev)\n case None => Nil\n }\n }\n\n case class Point(x: Int, y: Int)\n\n def printZeroPath(p: Point): Unit = {\n println(1)\n (0 until p.x).foreach(t => print(\"R\"))\n (0 until dim).foreach(t => print(\"D\"))\n (p.x until dim).foreach(t => print(\"R\"))\n }\n\n def printResult(edge: Edge): Unit = {\n zeroPoint match {\n case None =>\n println(edge.weight)\n println(traceBack(Some(edge)).reverse.tail.mkString)\n case Some(v) if edge.weight == 0 =>\n println(edge.weight)\n println(traceBack(Some(edge)).reverse.tail.mkString)\n case Some(v) => printZeroPath(v)\n }\n\n }\n\n def solve(curEdge: Edge, visited: Set[Point]): Unit = {\n if (curEdge.last) {\n printResult(curEdge)\n } else {\n curEdge.neighbours.filterNot(it => visited.contains(Point(it.x, it.y))).foreach(queue += _)\n solve(queue.dequeue(), visited + Point(curEdge.x, curEdge.y))\n }\n\n }\n\n def findTwoCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 2)\n\n def findFiveCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 5)\n\n def findDivNum(item: Long, num: Int): Int = {\n def find(curItem: Long, acc: Int): Int = {\n if (curItem % num == 0)\n find(curItem / num, acc + 1)\n else\n acc\n }\n find(item, 0)\n }\n\n\n case class Edge(x: Int, y: Int, twoCount: Int, fiveCount: Int, prev: Option[Edge], direction: Boolean) extends Ordered[Edge] {\n\n def weight = {\n Math.min(twoCount, fiveCount)\n }\n\n override def compare(that: Edge): Int = {\n that.weight.compareTo(this.weight)\n }\n\n private def createDownEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x, y + 1)\n val downTwos = twoCount + findTwoCount(x, y + 1)\n Edge(x, y + 1, downTwos, downFives, Some(this), true)\n }\n\n private def createRightEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x + 1, y)\n val downTwos = twoCount + findTwoCount(x + 1, y)\n Edge(x + 1, y, downTwos, downFives, Some(this), false)\n }\n\n def neighbours: List[Edge] = {\n if (x == matrix.length - 1) {\n List(createDownEdge())\n } else if (y == matrix.length - 1) {\n List(createRightEdge())\n } else {\n List(createRightEdge(), createDownEdge())\n }\n }\n\n def last: Boolean = x == matrix.length - 1 && y == matrix.length - 1\n\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport java.util.Scanner\nimport scala.util.Random\n\nobject Path extends App {\n\n val scanner = new Scanner(System.in)\n\n val dim = scanner.nextInt()\n\n val matrix = Array.ofDim[Long](dim, dim)\n\n (0 until dim) foreach {\n y =>\n (0 until dim) foreach {\n x =>\n matrix(x)(y) = scanner.nextLong()\n }\n }\n\n val queue = new mutable.PriorityQueue[Edge]()\n\n solve(Edge(0, 0, findTwoCount(0, 0), findFiveCount(0, 0), None, direction = false), Set())\n\n def traceBack(edge: Option[Edge]): List[Char] = {\n edge match {\n case Some(v) => if (v.direction) 'D' :: traceBack(v.prev) else 'R' :: traceBack(v.prev)\n case None => Nil\n }\n }\n\n case class Point(x: Int, y: Int)\n\n def solve(curEdge: Edge, visited: Set[Point]): Unit = {\n if (curEdge.last) {\n println(curEdge.weight)\n println(traceBack(Some(curEdge)).reverse.tail.mkString)\n } else {\n curEdge.neighbours.filterNot(it => visited.contains(Point(it.x, it.y))).foreach(queue += _)\n solve(queue.dequeue(), visited + Point(curEdge.x, curEdge.y))\n }\n\n }\n\n def findTwoCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 2)\n\n def findFiveCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 5)\n\n def findDivNum(item: Long, num: Int): Int = {\n def find(curItem: Long, acc: Int): Int = {\n if (curItem % num == 0)\n find(curItem / num, acc + 1)\n else\n acc\n }\n find(item, 0)\n }\n\n\n case class Edge(x: Int, y: Int, twoCount: Int, fiveCount: Int, prev: Option[Edge], direction: Boolean) extends Ordered[Edge] {\n\n def weight:Double = {\n val common = Math.min(twoCount, fiveCount)\n if (scala.math.abs(twoCount - fiveCount) > 0) common + 0.5 else common\n }\n\n override def compare(that: Edge): Int = {\n that.weight.compareTo(this.weight)\n }\n\n private def createDownEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x, y + 1)\n val downTwos = twoCount + findTwoCount(x, y + 1)\n Edge(x, y + 1, downTwos, downFives, Some(this), true)\n }\n\n private def createRightEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x + 1, y)\n val downTwos = twoCount + findTwoCount(x + 1, y)\n Edge(x + 1, y, downTwos, downFives, Some(this), false)\n }\n\n def neighbours: List[Edge] = {\n if (x == matrix.length - 1) {\n List(createDownEdge())\n } else if (y == matrix.length - 1) {\n List(createRightEdge())\n } else {\n List(createRightEdge(), createDownEdge())\n }\n }\n\n def last: Boolean = x == matrix.length - 1 && y == matrix.length - 1\n\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport java.util.Scanner\n\nobject Path extends App {\n\n val scanner = new Scanner(System.in)\n\n val dim = scanner.nextInt()\n\n val matrix = Array.ofDim[Long](dim, dim)\n\n (0 until dim) foreach {\n y =>\n (0 until dim) foreach {\n x =>\n matrix(x)(y) = scanner.nextLong()\n }\n }\n\n val queue = new mutable.PriorityQueue[Edge]()\n\n solve(Edge(0, 0, findTwoCount(0, 0), findFiveCount(0, 0), None, direction = false), Set())\n\n def traceBack(edge: Option[Edge]): List[Char] = {\n edge match {\n case Some(v) => if (v.direction) 'D' :: traceBack(v.prev) else 'R' :: traceBack(v.prev)\n case None => Nil\n }\n }\n\n case class Point(x: Int, y: Int)\n\n def solve(curEdge: Edge, visited: Set[Point]): Unit = {\n if (curEdge.last) {\n println(curEdge.weight)\n println(traceBack(Some(curEdge)).reverse.tail.mkString)\n } else {\n curEdge.neighbours.filterNot(it => visited.contains(Point(it.x, it.y))).foreach(queue += _)\n solve(queue.dequeue(), visited + Point(curEdge.x, curEdge.y))\n }\n\n }\n\n def findTwoCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 2)\n\n def findFiveCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 5)\n\n def findDivNum(item: Long, num: Int): Int = {\n def find(curItem: Long, acc: Int): Int = {\n if (curItem % num == 0)\n find(curItem / num, acc + 1)\n else\n acc\n }\n find(item, 0)\n }\n\n\n case class Edge(x: Int, y: Int, twoCount: Int, fiveCount: Int, prev: Option[Edge], direction: Boolean) extends Ordered[Edge] {\n\n def weight = Math.min(twoCount, fiveCount)\n\n override def compare(that: Edge): Int = {\n that.weight.compareTo(this.weight)\n }\n\n private def createDownEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x, y + 1)\n val downTwos = twoCount + findTwoCount(x, y + 1)\n Edge(x, y + 1, downTwos, downFives, Some(this), true)\n }\n\n private def createRightEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x + 1, y)\n val downTwos = twoCount + findTwoCount(x + 1, y)\n Edge(x + 1, y, downTwos, downFives, Some(this), false)\n }\n\n def neighbours: List[Edge] = {\n if (x == matrix.length - 1) {\n List(createDownEdge())\n } else if (y == matrix.length - 1) {\n List(createRightEdge())\n } else {\n List(createRightEdge(), createDownEdge())\n }\n }\n\n def last: Boolean = x == matrix.length - 1 && y == matrix.length - 1\n\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport java.util.Scanner\n\nobject LessRoundTrip extends App {\n\n val scanner = new Scanner(System.in)\n\n val dim = scanner.nextInt()\n\n val matrix = Array.ofDim[Long](dim, dim)\n\n var zeroPoint: Option[Point] = None\n\n (0 until dim) foreach {\n y =>\n (0 until dim) foreach {\n x =>\n matrix(x)(y) = scanner.nextLong()\n if (matrix(x)(y) == 0) {\n zeroPoint = Some(Point(x, y))\n matrix(x)(y) == 10\n }\n }\n }\n\n val queue = new mutable.PriorityQueue[Edge]()\n\n val twoEdge = solve(Edge(0, 0, findTwoCount(0, 0), None, 2, direction = false), Set())\n val fiveEdge = solve(Edge(0, 0, findTwoCount(0, 0), None, 2, direction = false), Set())\n val weight = math.min(twoEdge.weight, fiveEdge.weight)\n if (twoEdge.weight < fiveEdge.weight) {\n printResult(twoEdge, weight)\n } else {\n printResult(fiveEdge, weight)\n }\n\n\n\n def traceBack(edge: Option[Edge]): List[Char] = {\n edge match {\n case Some(v) => if (v.direction) 'D' :: traceBack(v.prev) else 'R' :: traceBack(v.prev)\n case None => Nil\n }\n }\n\n case class Point(x: Int, y: Int)\n\n def printZeroPath(p: Point): Unit = {\n println(1)\n (0 until p.x).foreach(t => print(\"R\"))\n (0 until dim).foreach(t => print(\"D\"))\n (p.x until dim).foreach(t => print(\"R\"))\n }\n\n def printResult(edge: Edge, weight: Int): Unit = {\n zeroPoint match {\n case None =>\n println(weight)\n println(traceBack(Some(edge)).reverse.tail.mkString)\n case Some(v) if weight == 0 =>\n println(weight)\n println(traceBack(Some(edge)).reverse.tail.mkString)\n case Some(v) => printZeroPath(v)\n }\n\n }\n\n def solve(curEdge: Edge, visited: Set[Point]): Edge = {\n if (curEdge.last) {\n curEdge\n } else {\n curEdge.neighbours.filterNot(it => visited.contains(Point(it.x, it.y))).foreach(queue += _)\n solve(queue.dequeue(), visited + Point(curEdge.x, curEdge.y))\n }\n\n }\n\n def findTwoCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 2)\n\n def findFiveCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 5)\n\n def findDivNum(item: Long, num: Int): Int = {\n def find(curItem: Long, acc: Int): Int = {\n if (curItem % num == 0)\n find(curItem / num, acc + 1)\n else\n acc\n }\n find(item, 0)\n }\n\n\n case class Edge(x: Int, y: Int, numCount: Int, prev: Option[Edge], num: Int, direction: Boolean) extends Ordered[Edge] {\n\n def weight = {\n numCount\n }\n\n override def compare(that: Edge): Int = {\n that.weight.compareTo(this.weight)\n }\n\n private def createDownEdge(): Edge = {\n val downNum = numCount + findDivNum(matrix(x)(y + 1), num)\n Edge(x, y + 1, downNum, Some(this), num, true)\n }\n\n private def createRightEdge(): Edge = {\n val rightNum = numCount + findDivNum(matrix(x + 1)(y), num)\n Edge(x + 1, y, rightNum, Some(this), num, false)\n }\n\n def neighbours: List[Edge] = {\n if (x == matrix.length - 1) {\n List(createDownEdge())\n } else if (y == matrix.length - 1) {\n List(createRightEdge())\n } else {\n List(createRightEdge(), createDownEdge())\n }\n }\n\n def last: Boolean = x == matrix.length - 1 && y == matrix.length - 1\n\n }\n\n}"}, {"source_code": "import scala.collection.mutable\nimport java.util.Scanner\n\nobject Path extends App {\n\n val scanner = new Scanner(System.in)\n\n val dim = scanner.nextInt()\n\n val matrix = Array.ofDim[Long](dim, dim)\n\n (0 until dim) foreach {\n x =>\n (0 until dim) foreach {\n y =>\n matrix(x)(y) = scanner.nextLong()\n }\n }\n\n val queue = new mutable.PriorityQueue[Edge]()\n\n solve(Edge(0, 0, findTwoCount(0, 0), findFiveCount(0, 0), None, direction = false))\n\n def traceBack(edge: Option[Edge]): List[Char] = {\n edge match {\n case Some(v) => if (v.direction) 'D' :: traceBack(v.prev) else 'R' :: traceBack(v.prev)\n case None => Nil\n }\n }\n\n def solve(curEdge: Edge): Unit = {\n if (curEdge.last) {\n println(curEdge.weight)\n println(traceBack(Some(curEdge)).reverse.tail)\n } else {\n curEdge.neighbours.foreach(queue += _)\n solve(queue.dequeue())\n }\n\n }\n\n def findTwoCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 2)\n\n def findFiveCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 5)\n\n def findDivNum(item: Long, num: Int): Int = {\n def find(curItem: Long, acc: Int): Int = {\n if (curItem % num == 0)\n find(curItem / num, acc + 1)\n else\n acc\n }\n find(item, 0)\n }\n\n\n case class Edge(x: Int, y: Int, twoCount: Int, fiveCount: Int, prev: Option[Edge], direction: Boolean) extends Ordered[Edge] {\n\n def weight = Math.min(twoCount, fiveCount)\n\n override def compare(that: Edge): Int = {\n that.weight.compareTo(this.weight)\n }\n\n private def createDownEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x, y + 1)\n val downTwos = twoCount + findTwoCount(x, y + 1)\n Edge(x, y + 1, downTwos, downFives, Some(this), true)\n }\n\n private def createRightEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x + 1, y)\n val downTwos = twoCount + findTwoCount(x + 1, y)\n Edge(x + 1, y, downTwos, downFives, Some(this), false)\n }\n\n def neighbours: List[Edge] = {\n if (x == matrix.length - 1) {\n List(createDownEdge())\n } else if (y == matrix.length - 1) {\n List(createRightEdge())\n } else {\n List(createRightEdge(), createDownEdge())\n }\n }\n\n def last: Boolean = x == matrix.length - 1 && y == matrix.length - 1\n\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport java.util.Scanner\n\nobject Path extends App {\n\n val scanner = new Scanner(System.in)\n\n val dim = scanner.nextInt()\n\n val matrix = Array.ofDim[Long](dim, dim)\n\n (0 until dim) foreach {\n y =>\n (0 until dim) foreach {\n x =>\n matrix(x)(y) = scanner.nextLong()\n }\n }\n\n val queue = new mutable.PriorityQueue[Edge]()\n\n solve(Edge(0, 0, findTwoCount(0, 0), findFiveCount(0, 0), None, direction = false), Set())\n\n def traceBack(edge: Option[Edge]): List[Char] = {\n edge match {\n case Some(v) => if (v.direction) 'D' :: traceBack(v.prev) else 'R' :: traceBack(v.prev)\n case None => Nil\n }\n }\n\n case class Point(x: Int, y: Int)\n\n def solve(curEdge: Edge, visited: Set[Point]): Unit = {\n if (curEdge.last) {\n println(curEdge.weight)\n println(traceBack(Some(curEdge)).reverse.tail.mkString)\n } else if (visited.contains(Point(curEdge.x, curEdge.y))) {\n solve(queue.dequeue(), visited)\n } else {\n curEdge.neighbours.filterNot(it => visited.contains(Point(it.x, it.y))).foreach(queue += _)\n solve(queue.dequeue(), visited + Point(curEdge.x, curEdge.y))\n }\n\n }\n\n def findTwoCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 2)\n\n def findFiveCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 5)\n\n def findDivNum(item: Long, num: Int): Int = {\n def find(curItem: Long, acc: Int): Int = {\n if (curItem % num == 0)\n find(curItem / num, acc + 1)\n else\n acc\n }\n find(item, 0)\n }\n\n\n case class Edge(x: Int, y: Int, twoCount: Int, fiveCount: Int, prev: Option[Edge], direction: Boolean) extends Ordered[Edge] {\n\n def weight = Math.min(twoCount, fiveCount)\n\n override def compare(that: Edge): Int = {\n that.weight.compareTo(this.weight)\n }\n\n private def createDownEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x, y + 1)\n val downTwos = twoCount + findTwoCount(x, y + 1)\n Edge(x, y + 1, downTwos, downFives, Some(this), true)\n }\n\n private def createRightEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x + 1, y)\n val downTwos = twoCount + findTwoCount(x + 1, y)\n Edge(x + 1, y, downTwos, downFives, Some(this), false)\n }\n\n def neighbours: List[Edge] = {\n if (x == matrix.length - 1) {\n List(createDownEdge())\n } else if (y == matrix.length - 1) {\n List(createRightEdge())\n } else {\n List(createRightEdge(), createDownEdge())\n }\n }\n\n def last: Boolean = x == matrix.length - 1 && y == matrix.length - 1\n\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport java.util.Scanner\n\nobject Path extends App {\n\n val scanner = new Scanner(System.in)\n\n val dim = scanner.nextInt()\n\n val matrix = Array.ofDim[Long](dim, dim)\n\n (0 until dim) foreach {\n x =>\n (0 until dim) foreach {\n y =>\n matrix(x)(y) = scanner.nextLong()\n }\n }\n\n val queue = new mutable.PriorityQueue[Edge]()\n\n solve(Edge(0, 0, findTwoCount(0, 0), findFiveCount(0, 0), None, direction = false))\n\n def traceBack(edge: Option[Edge]): List[Char] = {\n edge match {\n case Some(v) => if (v.direction) 'D' :: traceBack(v.prev) else 'R' :: traceBack(v.prev)\n case None => Nil\n }\n }\n\n def solve(curEdge: Edge): Unit = {\n if (curEdge.last) {\n println(curEdge.weight)\n println(traceBack(Some(curEdge)).reverse.tail.mkString)\n } else {\n curEdge.neighbours.foreach(queue += _)\n solve(queue.dequeue())\n }\n\n }\n\n def findTwoCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 2)\n\n def findFiveCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 5)\n\n def findDivNum(item: Long, num: Int): Int = {\n def find(curItem: Long, acc: Int): Int = {\n if (curItem % num == 0)\n find(curItem / num, acc + 1)\n else\n acc\n }\n find(item, 0)\n }\n\n\n case class Edge(x: Int, y: Int, twoCount: Int, fiveCount: Int, prev: Option[Edge], direction: Boolean) extends Ordered[Edge] {\n\n def weight = Math.min(twoCount, fiveCount)\n\n override def compare(that: Edge): Int = {\n that.weight.compareTo(this.weight)\n }\n\n private def createDownEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x, y + 1)\n val downTwos = twoCount + findTwoCount(x, y + 1)\n Edge(x, y + 1, downTwos, downFives, Some(this), true)\n }\n\n private def createRightEdge(): Edge = {\n val downFives = fiveCount + findFiveCount(x + 1, y)\n val downTwos = twoCount + findTwoCount(x + 1, y)\n Edge(x + 1, y, downTwos, downFives, Some(this), false)\n }\n\n def neighbours: List[Edge] = {\n if (x == matrix.length - 1) {\n List(createDownEdge())\n } else if (y == matrix.length - 1) {\n List(createRightEdge())\n } else {\n List(createRightEdge(), createDownEdge())\n }\n }\n\n def last: Boolean = x == matrix.length - 1 && y == matrix.length - 1\n\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport java.util.Scanner\n\nobject LessRoundTrip extends App {\n\n val scanner = new Scanner(System.in)\n\n val dim = scanner.nextInt()\n\n val matrix = Array.ofDim[Long](dim, dim)\n\n var zeroPoint: Option[Point] = None\n\n (0 until dim) foreach {\n y =>\n (0 until dim) foreach {\n x =>\n matrix(x)(y) = scanner.nextLong()\n if (matrix(x)(y) == 0) {\n zeroPoint = Some(Point(x, y))\n matrix(x)(y) == 10\n }\n }\n }\n\n val queue = new mutable.PriorityQueue[Edge]()\n\n val twoEdge = solve(Edge(0, 0, findTwoCount(0, 0), None, 2, direction = false), Set())\n val fiveEdge = solve(Edge(0, 0, findTwoCount(0, 0), None, 5, direction = false), Set())\n val weight = math.min(twoEdge.weight, fiveEdge.weight)\n if (twoEdge.weight < fiveEdge.weight) {\n printResult(twoEdge, weight)\n } else {\n printResult(fiveEdge, weight)\n }\n\n\n\n def traceBack(edge: Option[Edge]): List[Char] = {\n edge match {\n case Some(v) => if (v.direction) 'D' :: traceBack(v.prev) else 'R' :: traceBack(v.prev)\n case None => Nil\n }\n }\n\n case class Point(x: Int, y: Int)\n\n def printZeroPath(p: Point): Unit = {\n println(1)\n (0 until p.x).foreach(t => print(\"R\"))\n (0 until dim).foreach(t => print(\"D\"))\n (p.x until dim).foreach(t => print(\"R\"))\n }\n\n def printResult(edge: Edge, weight: Int): Unit = {\n zeroPoint match {\n case None =>\n println(weight)\n println(traceBack(Some(edge)).reverse.tail.mkString)\n case Some(v) if weight == 0 =>\n println(weight)\n println(traceBack(Some(edge)).reverse.tail.mkString)\n case Some(v) => printZeroPath(v)\n }\n\n }\n\n def solve(curEdge: Edge, visited: Set[Point]): Edge = {\n if (curEdge.last) {\n curEdge\n } else {\n curEdge.neighbours.filterNot(it => visited.contains(Point(it.x, it.y))).foreach(queue += _)\n solve(queue.dequeue(), visited + Point(curEdge.x, curEdge.y))\n }\n\n }\n\n def findTwoCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 2)\n\n def findFiveCount(x: Int, y: Int): Int = findDivNum(matrix(x)(y), 5)\n\n def findDivNum(item: Long, num: Int): Int = {\n def find(curItem: Long, acc: Int): Int = {\n if (curItem % num == 0)\n find(curItem / num, acc + 1)\n else\n acc\n }\n find(item, 0)\n }\n\n\n case class Edge(x: Int, y: Int, numCount: Int, prev: Option[Edge], num: Int, direction: Boolean) extends Ordered[Edge] {\n\n def weight = {\n numCount\n }\n\n override def compare(that: Edge): Int = {\n that.weight.compareTo(this.weight)\n }\n\n private def createDownEdge(): Edge = {\n val downNum = numCount + findDivNum(matrix(x)(y + 1), num)\n Edge(x, y + 1, downNum, Some(this), num, true)\n }\n\n private def createRightEdge(): Edge = {\n val rightNum = numCount + findDivNum(matrix(x + 1)(y), num)\n Edge(x + 1, y, rightNum, Some(this), num, false)\n }\n\n def neighbours: List[Edge] = {\n if (x == matrix.length - 1) {\n List(createDownEdge())\n } else if (y == matrix.length - 1) {\n List(createRightEdge())\n } else {\n List(createRightEdge(), createDownEdge())\n }\n }\n\n def last: Boolean = x == matrix.length - 1 && y == matrix.length - 1\n\n }\n\n}"}, {"source_code": "object B2 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = Array.fill(n)(readInts(n))\n for(i <- 0 until n; j <- 0 until n if in(i)(j) == 0)\n in(i)(j) = 10\n val two = Array.ofDim[Int](n, n)\n val five = Array.ofDim[Int](n, n)\n for(i <- 0 until n; j <- 0 until n) {\n var num = in(i)(j)\n var t, f = 0\n while(num%2 == 0) {\n num /= 2\n t += 1\n }\n while(num%5 == 0) {\n num /= 5\n f += 1\n }\n if(i == 0 && j == 0) {\n two(i)(j) = t\n five(i)(j) = f\n } else if(i == 0) {\n two(i)(j) = two(i)(j-1) + t\n five(i)(j) = five(i)(j-1) + f\n } else if(j == 0) {\n two(i)(j) = two(i-1)(j) + t\n five(i)(j) = five(i-1)(j) + f\n } else {\n two(i)(j) = math.min(two(i-1)(j), two(i)(j-1)) + t\n five(i)(j) = math.min(five(i-1)(j), five(i)(j-1)) + f\n }\n }\n val dp = if(two(n-1)(n-1) < five(n-1)(n-1)) two else five\n println(dp(n-1)(n-1))\n val res = cu.ArrayBuffer.empty[Char]\n var i = n-1\n var j = n-1\n while(i != 0 || j != 0) {\n if(i > 0 && (j==0 || dp(i)(j-1) >= dp(i-1)(j))) {\n res.append('D')\n i -= 1\n } else {\n res.append('R')\n j -= 1\n }\n }\n println(res.reverse.mkString(\"\"))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object B2 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = Array.fill(n)(readInts(n))\n val two = Array.ofDim[Int](n, n)\n val five = Array.ofDim[Int](n, n)\n for(i <- 0 until n; j <- 0 until n) {\n var num = in(i)(j)\n var t, f = 0\n while(num%2 == 0) {\n num /= 2\n t += 1\n }\n while(num%5 == 0) {\n num /= 5\n f += 1\n }\n if(i == 0 && j == 0) {\n two(i)(j) = t\n five(i)(j) = f\n } else if(i == 0) {\n two(i)(j) = two(i)(j-1) + t\n five(i)(j) = five(i)(j-1) + f\n } else if(j == 0) {\n two(i)(j) = two(i-1)(j) + t\n five(i)(j) = five(i-1)(j) + f\n } else {\n two(i)(j) = math.min(two(i-1)(j), two(i)(j-1)) + t\n five(i)(j) = math.min(five(i-1)(j), five(i)(j-1)) + f\n }\n }\n println(math.min(two(n-1)(n-1), five(n-1)(n-1)))\n val res = cu.ArrayBuffer.empty[Char]\n var i, j = n-1\n while(i > 0 && j > 0) {\n if(math.min(two(i-1)(j), five(i-1)(j)) < math.min(two(i)(j-1), five(i)(j-1))) {\n res.append('D')\n i -= 1\n } else {\n res.append('R')\n j -= 1\n }\n }\n while(i > 0) {\n res.append('D')\n i -= 1\n }\n while(j > 0) {\n res.append('R')\n j -= 1\n }\n println(res.reverse.mkString(\"\"))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.annotation.tailrec\nimport scala.collection\n\nobject X extends App {\n\n case class MyVertex[T, U](id: T, edges: Map[T, U])\n\n case class ScoreAndPrev[T, V](id: T, score: V)\n\n class MyGraph[T, U](vertices: Map[T, MyVertex[T, U]]) {\n\n def doDjikstra[V](start: T, initialValue: V)(combiner: (U, V) => V)(\n implicit ord: Ordering[V]\n ): Map[T, ScoreAndPrev[T, V]] = {\n\n var m = new collection.mutable.HashMap[T, ScoreAndPrev[T, V]]();\n\n var visited = new collection.mutable.HashSet[T]();\n\n m.update(start, ScoreAndPrev(start, initialValue))\n\n implicit val tOrdering = new Ordering[T] {\n def compare(x: T, y: T): Int = {\n ord.compare(m(y).score, m(x).score)\n }\n }\n\n var q = new collection.mutable.PriorityQueue[T]();\n\n q.enqueue(start)\n\n while (q.nonEmpty) {\n val next = q.dequeue()\n\n if (!visited.contains(next)) {\n val neighbours = vertices(next).edges\n val score = m(next).score\n\n val unvisitedNeighbours = neighbours.keySet.diff(visited)\n\n unvisitedNeighbours.foreach(n => {\n val neighbourWeight = neighbours(n)\n\n val oldScore = m.get(n).map(s => s.score)\n\n val potScore = combiner(neighbourWeight, score)\n\n val nextScore = oldScore match {\n case None => potScore\n case Some(value) =>\n if (ord.lt(potScore, value)) potScore else value\n }\n\n m.update(n, ScoreAndPrev(next, nextScore))\n\n })\n\n q.enqueue(unvisitedNeighbours.toSeq: _*)\n\n visited.add(next)\n }\n\n }\n\n m.toMap\n }\n }\n\n object MyGraph {\n def apply[T, U](vertices: Map[T, MyVertex[T, U]]) =\n new MyGraph[T, U](vertices)\n }\n\n object Y {\n\n @tailrec\n def largestDividingPower(n: Int, m: Int, c: Int = 0): Int = {\n if (n % m == 0 && n != 0) largestDividingPower(n / m, m, c + 1) else c\n }\n\n def getAnswer(graph: MyGraph[(Int, Int), Int], end: (Int, Int)) = {\n\n val endModTwo =\n graph.doDjikstra((-1, -1), 0)((s, w) => w + largestDividingPower(s, 2))\n\n val endModFive =\n graph.doDjikstra((-1, -1), 0)((s, w) => w + largestDividingPower(s, 5))\n\n val smallestEnd = List(endModTwo, endModFive).minBy(s => s(end).score)\n\n def determinePath[T, V](\n start: T,\n end: T,\n djikstrad: Map[T, ScoreAndPrev[T, V]],\n path: List[T] = Nil\n ): List[T] = {\n if (start == end) path\n else determinePath(djikstrad(start).id, end, djikstrad, start +: path)\n }\n\n val thePath = determinePath(end, (0, 0), smallestEnd)\n\n val stringedPath = thePath\n .foldLeft(\"\", (0, 0))((path, e) => {\n val prev = path._2\n if (e._1 == prev._1) (path._1 + \"R\", e) else (path._1 + \"D\", e)\n })\n ._1\n\n (smallestEnd(end).score, stringedPath)\n }\n\n val vertices = Map(\n (2, 2) -> MyVertex((2, 2), Map[(Int, Int), Int]()),\n (2, 1) -> MyVertex((2, 1), Map((2, 2) -> 9)),\n (2, 0) -> MyVertex((2, 0), Map((2, 1) -> 8)),\n (1, 2) -> MyVertex((1, 2), Map((2, 2) -> 9)),\n (-1, -1) -> MyVertex((-1, -1), Map((0, 0) -> 1)),\n (1, 0) -> MyVertex((1, 0), Map((2, 0) -> 7, (1, 1) -> 5)),\n (0, 0) -> MyVertex((0, 0), Map((1, 0) -> 4, (0, 1) -> 2)),\n (0, 2) -> MyVertex((0, 2), Map((1, 2) -> 6)),\n (0, 1) -> MyVertex((0, 1), Map((1, 1) -> 5, (0, 2) -> 3)),\n (1, 1) -> MyVertex((1, 1), Map((2, 1) -> 8, (1, 2) -> 6))\n )\n\n val graph = new MyGraph(vertices)\n\n val res = getAnswer(graph, (2, 2))\n\n println(res)\n }\n\n val lineCount = StdIn.readInt()\n\n val matrix =\n (0 until lineCount).foldLeft(Map[(Int, Int), Int]())((accMap, currLine) => {\n val line = StdIn.readLine().split(\" \").map(_.toInt)\n\n val lineMap = line.zipWithIndex.foldLeft(Map[(Int, Int), Int]())(\n (accLineMap, curr) => {\n accLineMap + ((currLine, curr._2) -> curr._1)\n }\n )\n\n accMap ++ lineMap\n })\n\n val vertexStart = MyVertex((-1, -1), Map((0, 0) -> matrix(0, 0)))\n\n val vertices = matrix.foldLeft(Map[(Int, Int), MyVertex[(Int, Int), Int]]())(\n (accMap, currVert) => {\n val thisVert = currVert._1\n\n val downNeighbour = matrix.get((thisVert._1 + 1, thisVert._2)) match {\n case None => None\n case Some(value) => Some((thisVert._1 + 1, thisVert._2), value)\n }\n val rightNeighbour = matrix.get(thisVert._1, thisVert._2 + 1) match {\n case None => None\n case Some(value) => Some((thisVert._1, thisVert._2 + 1), value)\n }\n\n val neighbours = List(downNeighbour, rightNeighbour).flatten.toMap\n\n val vert = MyVertex((currVert._1), neighbours)\n\n accMap + (currVert._1 -> vert)\n }\n ) + ((-1, -1) -> vertexStart)\n\n val graph = MyGraph(vertices)\n\n val answer = Y.getAnswer(graph, (lineCount - 1, lineCount - 1))\n\n println(answer._1)\n println(answer._2)\n\n}\n"}, {"source_code": "import scala.reflect.ClassTag\nobject X extends App {\n def dynamicSolveMatrixRightDown[T, U: ClassTag](\n matrix: Array[Array[T]],\n initialValue: U\n )(\n combiner: (U, T) => U\n )(implicit ord: Ordering[U]) = {\n\n val len = matrix.length\n\n val solutionMatrix = Array.ofDim[(String, U)](len, len)\n\n solutionMatrix(0)(0) = (\"\", combiner(initialValue, matrix(0)(0)))\n\n (0 until len).foreach(b => {\n (0 to b).foreach(i => {\n if (b != 0 && i == b) {\n val leftWeight = combiner(solutionMatrix(b - 1)(b)._2, matrix(b)(b))\n val upWeight = combiner(solutionMatrix(b)(b - 1)._2, matrix(b)(b))\n\n solutionMatrix(b)(b) =\n if (ord.lt(leftWeight, upWeight)) (\"D\", leftWeight)\n else (\"R\", upWeight)\n }\n // row\n val rowWeight = solutionMatrix(i)(b)._2\n\n if (!(b + 1 > len - 1)) {\n solutionMatrix(i)(b + 1) =\n (\"R\", combiner(rowWeight, matrix(i)(b + 1)))\n }\n\n if (!(i + 1 > len - 1)) {\n val rightWeight = matrix(i + 1)(b)\n\n val candidateWeight = combiner(rowWeight, rightWeight)\n\n if (solutionMatrix(i + 1)(b) == null) {\n solutionMatrix(i + 1)(b) = (\"D\", candidateWeight)\n } else {\n val currentRightWeight = solutionMatrix(i + 1)(b)._2\n\n if (ord.lt(candidateWeight, currentRightWeight)) {\n solutionMatrix(i + 1)(b) = (\"D\", candidateWeight)\n }\n }\n\n }\n\n //col\n val colWeight = solutionMatrix(b)(i)._2\n\n if (!(b + 1 > len - 1)) {\n solutionMatrix(b + 1)(i) =\n (\"D\", combiner(colWeight, matrix(b + 1)(i)))\n }\n\n if (!(i + 1 > len - 1)) {\n val downWeight = matrix(b)(i + 1)\n\n val otherCandidateWeight = combiner(colWeight, downWeight)\n\n if (solutionMatrix(b)(i + 1) == null) {\n solutionMatrix(b)(i + 1) = (\"R\", otherCandidateWeight)\n } else {\n val currentDownWeight = solutionMatrix(b)(i + 1)._2\n\n if (ord.lt(otherCandidateWeight, currentDownWeight)) {\n solutionMatrix(b)(i + 1) = (\"R\", otherCandidateWeight)\n }\n }\n\n }\n\n })\n\n })\n\n solutionMatrix\n }\n\n def highestFactor(f: Int, n: Int) = {\n var m = n\n var c = 0\n while (m % f == 0) {\n c = c + 1\n m = m / f\n }\n c\n }\n\n def getPath[U](\n solnMatrix: Array[Array[(String, U)]],\n start: (Int, Int),\n path: String = \"\",\n end: (Int, Int) = (0, 0)\n ): String = {\n if (start == end) {\n path\n } else {\n val dir = solnMatrix(start._1)(start._2)._1\n if (dir == \"R\") {\n getPath(solnMatrix, (start._1, start._2 - 1), \"R\" + path)\n } else getPath(solnMatrix, (start._1 - 1, start._2), \"D\" + path)\n }\n }\n\n val lineCount = scala.io.StdIn.readInt()\n\n val inpMatrix = Array.ofDim[Int](lineCount, lineCount)\n\n (0 until lineCount).foreach(r => {\n val line = scala.io.StdIn\n .readLine()\n .split(\" \")\n .zipWithIndex\n .foreach(w => {\n inpMatrix(r)(w._2) = w._1.toInt\n })\n })\n\n val powerOfTwo = ((x: Int, y: Int) => x + (y & ~(y - 1)))\n val powerOfFive = ((x: Int, y: Int) => x + highestFactor(5, y))\n\n val solutionMatrixTwo = dynamicSolveMatrixRightDown(\n inpMatrix,\n 0\n )(powerOfTwo)\n\n val resultsTwo =\n solutionMatrixTwo(inpMatrix.length - 1)(inpMatrix.length - 1)._2\n\n val betterWay = if (resultsTwo == 0) {\n solutionMatrixTwo\n } else {\n val solutionMatrixFive = dynamicSolveMatrixRightDown(\n inpMatrix,\n 0\n )(powerOfFive)\n\n val resultsFive =\n solutionMatrixFive(inpMatrix.length - 1)(inpMatrix.length - 1)._2\n\n if (resultsTwo < resultsFive) solutionMatrixTwo else solutionMatrixFive\n }\n\n val path =\n getPath(betterWay, (inpMatrix.length - 1, inpMatrix.length - 1))\n\n println(betterWay(inpMatrix.length - 1)(inpMatrix.length - 1)._2)\n println(path)\n\n}\n"}, {"source_code": "import scala.reflect.ClassTag\nimport scala.annotation.tailrec\nobject X extends App {\n def dynamicSolveMatrixRightDown[T, U: ClassTag](\n matrix: Array[Array[T]],\n initialValue: U\n )(\n combiner: (U, U, T) => U\n ) = {\n\n val len = matrix.length\n\n val solutionMatrix = Array.ofDim[U](len, len)\n\n solutionMatrix(0)(0) = combiner(initialValue, initialValue, matrix(0)(0))\n\n (0 until len).foreach(b => {\n (0 to b).foreach(i => {\n // row\n val rowWeight = solutionMatrix(i)(b)\n val colWeight = solutionMatrix(b)(i)\n\n if (!(b + 1 > len - 1)) {\n solutionMatrix(i)(b + 1) =\n combiner(rowWeight, solutionMatrix(i)(b + 1), matrix(i)(b + 1))\n solutionMatrix(b + 1)(i) =\n combiner(colWeight, solutionMatrix(b + 1)(i), matrix(b + 1)(i))\n }\n\n if (!(i + 1 > len - 1)) {\n val rightWeight = matrix(i + 1)(b)\n\n val candidateWeight =\n combiner(rowWeight, solutionMatrix(i + 1)(b), rightWeight)\n\n solutionMatrix(i + 1)(b) = candidateWeight\n\n val downWeight = matrix(b)(i + 1)\n\n val otherCandidateWeight =\n combiner(colWeight, solutionMatrix(b)(i + 1), downWeight)\n\n solutionMatrix(b)(i + 1) = otherCandidateWeight\n\n }\n\n if (b < len - 1 && i == b) {\n val leftWeight =\n combiner(\n solutionMatrix(b)(b + 1),\n solutionMatrix(b + 1)(b + 1),\n matrix(b + 1)(b + 1)\n )\n\n solutionMatrix(b + 1)(b + 1) = leftWeight\n\n val upWeight =\n combiner(\n solutionMatrix(b + 1)(b),\n solutionMatrix(b + 1)(b + 1),\n matrix(b + 1)(b + 1)\n )\n\n solutionMatrix(b + 1)(b + 1) = upWeight\n }\n\n })\n\n })\n\n solutionMatrix\n }\n\n def dynamicSolveMatrixRightDownInPlace[T](\n matrix: Array[Array[T]],\n initialValue: T\n )(\n combiner: (T, T, T) => T\n ): Array[Array[T]] = {\n\n val len = matrix.length\n\n matrix(0)(0) = initialValue\n\n (1 until len).foreach(i => {\n matrix(0)(i) = combiner(matrix(0)(i - 1), matrix(0)(i - 1), matrix(0)(i))\n matrix(i)(0) = combiner(matrix(i - 1)(0), matrix(i - 1)(0), matrix(i)(0))\n })\n\n (1 until len).foreach(i => {\n (1 until len).foreach(j => {\n matrix(i)(j) =\n combiner(matrix(i - 1)(j), matrix(i)(j - 1), matrix(i)(j))\n })\n })\n\n matrix\n }\n\n def highestFactor(f: Int, n: Int) = {\n var m = n\n var c = 0\n while (m % f == 0) {\n c = c + 1\n m = m / f\n }\n (c, m)\n }\n\n @tailrec\n def getPath[U](\n solnMatrix: Array[Array[U]],\n start: (Int, Int),\n path: List[String] = List(),\n end: (Int, Int) = (0, 0)\n )(implicit ord: Ordering[U]): String = {\n if (start == end) {\n path.mkString(\"\")\n } else {\n start match {\n case (0, s) =>\n getPath(solnMatrix, (start._1, start._2 - 1), \"R\" +: path)\n case (s, 0) =>\n getPath(solnMatrix, (start._1 - 1, start._2), \"D\" +: path)\n case (u, v) => {\n if (ord.lt(solnMatrix(u - 1)(v), solnMatrix(u)(v - 1)))\n getPath(solnMatrix, (start._1 - 1, start._2), \"D\" +: path)\n else getPath(solnMatrix, (start._1, start._2 - 1), \"R\" +: path)\n }\n }\n }\n }\n\n val lineCount = scala.io.StdIn.readInt()\n\n val inpMatrix = Array.ofDim[(Int, Int)](lineCount, lineCount)\n\n var hasZero = Option.empty[(Int, Int)]\n\n (0 until lineCount).foreach(r => {\n var i = 0\n val line = scala.io.StdIn\n .readLine()\n .split(\" \")\n .foreach(w => {\n val cell = w.toInt\n if (cell == 0) {\n hasZero = Some((r, i))\n inpMatrix(r)(i) = (1, 1)\n } else {\n val (p10, t) = highestFactor(10, cell)\n\n val (p2, k) = highestFactor(2, t)\n val p5 = highestFactor(5, k)._1\n inpMatrix(r)(i) = (p2 + p10, p5 + p10)\n\n }\n i = i + 1\n })\n })\n\n// println(inpMatrix.map(_.mkString(\"\\t\")).mkString(\"\\n\"))\n// println()\n\n val smaller = (x: Int, y: Int) => if (x < y) x else y\n\n val solutionMatrix = dynamicSolveMatrixRightDownInPlace(\n inpMatrix,\n inpMatrix(0)(0)\n )((left, up, y) => {\n val fstCont = smaller(left._1, up._1)\n val sndCont = smaller(left._2, up._2)\n (\n fstCont + y._1,\n sndCont + y._2\n )\n\n })\n\n val ending = solutionMatrix(lineCount - 1)(lineCount - 1)\n val smallest = smaller(ending._1, ending._2)\n\n val bestPath = if (ending._1 < ending._2) {\n getPath(solutionMatrix, (lineCount - 1, lineCount - 1))(\n new Ordering[(Int, Int)] {\n def compare(x: (Int, Int), y: (Int, Int)): Int = x._1.compare(y._1)\n }\n )\n } else {\n getPath(solutionMatrix, (lineCount - 1, lineCount - 1))(\n new Ordering[(Int, Int)] {\n def compare(x: (Int, Int), y: (Int, Int)): Int = x._2.compare(y._2)\n }\n )\n }\n\n val (p, s) = hasZero match {\n case None => (bestPath, smallest)\n case Some(value) =>\n if (smallest == 0) {\n (bestPath, smallest)\n } else {\n val x = value._1\n\n val s = (0 until x - 1).map(_ => \"R\").mkString(\"\")\n val d = (0 until lineCount - 1).map(_ => \"D\").mkString(\"\")\n val r = (0 until lineCount - x).map(_ => \"R\").mkString(\"\")\n\n (s + d + r, 1)\n }\n }\n\n// println(solutionMatrix.map(_.mkString(\"\\t\")).mkString(\"\\n\"))\n\n println(s)\n println(p)\n}\n"}, {"source_code": "import scala.reflect.ClassTag\nimport scala.annotation.tailrec\nobject X extends App {\n def dynamicSolveMatrixRightDown[T, U: ClassTag](\n matrix: Array[Array[T]],\n initialValue: U\n )(\n combiner: (U, T) => U\n )(implicit ord: Ordering[U]) = {\n\n val len = matrix.length\n\n val solutionMatrix = Array.ofDim[U](len, len)\n\n solutionMatrix(0)(0) = combiner(initialValue, matrix(0)(0))\n\n (0 until len).foreach(b => {\n (0 to b).foreach(i => {\n if (b != 0 && i == b) {\n val leftWeight = combiner(solutionMatrix(b - 1)(b), matrix(b)(b))\n val upWeight = combiner(solutionMatrix(b)(b - 1), matrix(b)(b))\n\n solutionMatrix(b)(b) =\n if (ord.lt(leftWeight, upWeight)) leftWeight\n else upWeight\n }\n // row\n val rowWeight = solutionMatrix(i)(b)\n val colWeight = solutionMatrix(b)(i)\n\n if (!(b + 1 > len - 1)) {\n solutionMatrix(i)(b + 1) = combiner(rowWeight, matrix(i)(b + 1))\n solutionMatrix(b + 1)(i) = combiner(colWeight, matrix(b + 1)(i))\n\n }\n\n if (!(i + 1 > len - 1)) {\n val rightWeight = matrix(i + 1)(b)\n\n val candidateWeight = combiner(rowWeight, rightWeight)\n\n val currentRightWeight = solutionMatrix(i + 1)(b)\n\n if (ord.lt(candidateWeight, currentRightWeight)) {\n solutionMatrix(i + 1)(b) = candidateWeight\n }\n\n val downWeight = matrix(b)(i + 1)\n\n val otherCandidateWeight = combiner(colWeight, downWeight)\n\n val currentDownWeight = solutionMatrix(b)(i + 1)\n\n if (ord.lt(otherCandidateWeight, currentDownWeight)) {\n solutionMatrix(b)(i + 1) = otherCandidateWeight\n }\n\n }\n\n })\n\n })\n\n solutionMatrix\n }\n\n def highestFactor(f: Int, n: Int) = {\n var m = n\n var c = 0\n while (m % f == 0) {\n c = c + 1\n m = m / f\n }\n (c, m)\n }\n\n @tailrec\n def getPath[U](\n solnMatrix: Array[Array[U]],\n start: (Int, Int),\n path: List[String] = List(),\n end: (Int, Int) = (0, 0)\n )(implicit ord: Ordering[U]): String = {\n if (start == end) {\n path.mkString(\"\")\n } else {\n start match {\n case (0, s) =>\n getPath(solnMatrix, (start._1, start._2 - 1), \"R\" +: path)\n case (s, 0) =>\n getPath(solnMatrix, (start._1 - 1, start._2), \"D\" +: path)\n case (u, v) => {\n if (ord.lt(solnMatrix(u - 1)(v), solnMatrix(u)(v - 1)))\n getPath(solnMatrix, (start._1 - 1, start._2), \"D\" +: path)\n else getPath(solnMatrix, (start._1, start._2 - 1), \"R\" +: path)\n }\n }\n }\n }\n\n val lineCount = scala.io.StdIn.readInt()\n\n val inpMatrix = Array.ofDim[(Int, Int)](lineCount, lineCount)\n\n (0 until lineCount).foreach(r => {\n var i = 0\n val line = scala.io.StdIn\n .readLine()\n .split(\" \")\n .foreach(w => {\n if (w.last != '0') {\n inpMatrix(r)(i) = (0, 0)\n } else {\n val cell = w.toInt\n val (p10, t) = highestFactor(10, cell)\n\n val (p2, k) = highestFactor(2, t)\n val p5 = highestFactor(5, k)._1\n inpMatrix(r)(i) = (p2 + p10, p5 + p10)\n }\n i = i + 1\n\n })\n })\n\n val solutionMatrixTwo = dynamicSolveMatrixRightDown(\n inpMatrix,\n 0\n )(((x: Int, y: (Int, Int)) => x + y._1))\n\n val resultsTwo =\n solutionMatrixTwo(lineCount - 1)(lineCount - 1)\n\n val (path, score) = if (resultsTwo == 0) {\n (getPath(solutionMatrixTwo, (lineCount - 1, lineCount - 1)), resultsTwo)\n } else {\n val solutionMatrixFive = dynamicSolveMatrixRightDown(\n inpMatrix,\n 0\n )(((x: Int, y: (Int, Int)) => x + y._2))\n\n val resultsFive =\n solutionMatrixFive(lineCount - 1)(lineCount - 1)\n\n if (resultsTwo < resultsFive)\n (getPath(solutionMatrixTwo, (lineCount - 1, lineCount - 1)), resultsTwo)\n else\n (getPath(solutionMatrixFive, (lineCount - 1, lineCount - 1)), resultsFive)\n }\n\n println(score)\n println(path)\n\n}\n"}, {"source_code": "import scala.reflect.ClassTag\nimport scala.annotation.tailrec\nobject X extends App {\n def dynamicSolveMatrixRightDown[T, U: ClassTag](\n matrix: Array[Array[T]],\n initialValue: U\n )(\n combiner: (U, U, T) => U\n ) = {\n\n val len = matrix.length\n\n val solutionMatrix = Array.ofDim[U](len, len)\n\n solutionMatrix(0)(0) = combiner(initialValue, initialValue, matrix(0)(0))\n\n (0 until len).foreach(b => {\n (0 to b).foreach(i => {\n // row\n val rowWeight = solutionMatrix(i)(b)\n val colWeight = solutionMatrix(b)(i)\n\n if (!(b + 1 > len - 1)) {\n solutionMatrix(i)(b + 1) =\n combiner(rowWeight, solutionMatrix(i)(b + 1), matrix(i)(b + 1))\n solutionMatrix(b + 1)(i) =\n combiner(colWeight, solutionMatrix(b + 1)(i), matrix(b + 1)(i))\n }\n\n if (!(i + 1 > len - 1)) {\n val rightWeight = matrix(i + 1)(b)\n\n val candidateWeight =\n combiner(rowWeight, solutionMatrix(i + 1)(b), rightWeight)\n\n solutionMatrix(i + 1)(b) = candidateWeight\n\n val downWeight = matrix(b)(i + 1)\n\n val otherCandidateWeight =\n combiner(colWeight, solutionMatrix(b)(i + 1), downWeight)\n\n solutionMatrix(b)(i + 1) = otherCandidateWeight\n\n }\n\n if (b < len - 1 && i == b) {\n val leftWeight =\n combiner(\n solutionMatrix(b)(b + 1),\n solutionMatrix(b + 1)(b + 1),\n matrix(b + 1)(b + 1)\n )\n\n solutionMatrix(b + 1)(b + 1) = leftWeight\n\n val upWeight =\n combiner(\n solutionMatrix(b + 1)(b),\n solutionMatrix(b + 1)(b + 1),\n matrix(b + 1)(b + 1)\n )\n\n solutionMatrix(b + 1)(b + 1) = upWeight\n }\n\n })\n\n })\n\n solutionMatrix\n }\n\n def highestFactor(f: Int, n: Int) = {\n var m = n\n var c: Byte = 0\n while (m % f == 0) {\n c = c.+(1).asInstanceOf[Byte]\n m = m / f\n }\n (c, m)\n }\n\n @tailrec\n def getPath[U](\n solnMatrix: Array[Array[U]],\n start: (Int, Int),\n path: List[String] = List(),\n end: (Int, Int) = (0, 0)\n )(implicit ord: Ordering[U]): String = {\n if (start == end) {\n path.mkString(\"\")\n } else {\n start match {\n case (0, s) =>\n getPath(solnMatrix, (start._1, start._2 - 1), \"R\" +: path)\n case (s, 0) =>\n getPath(solnMatrix, (start._1 - 1, start._2), \"D\" +: path)\n case (u, v) => {\n if (ord.lt(solnMatrix(u - 1)(v), solnMatrix(u)(v - 1)))\n getPath(solnMatrix, (start._1 - 1, start._2), \"D\" +: path)\n else getPath(solnMatrix, (start._1, start._2 - 1), \"R\" +: path)\n }\n }\n }\n }\n\n val lineCount = scala.io.StdIn.readInt()\n\n val inpMatrix = Array.ofDim[(Byte, Byte)](lineCount, lineCount)\n\n (0 until lineCount).foreach(r => {\n var i = 0\n val line = scala.io.StdIn\n .readLine()\n .split(\" \")\n .foreach(w => {\n val cell = w.toInt\n val (p10, t) = highestFactor(10, cell)\n\n val (p2, k) = highestFactor(2, t)\n val p5 = highestFactor(5, k)._1\n inpMatrix(r)(i) =\n (p2.+(p10).asInstanceOf[Byte], p5.+(p10).asInstanceOf[Byte])\n i = i + 1\n })\n })\n\n// println(inpMatrix.map(_.mkString(\"\\t\")).mkString(\"\\n\"))\n// println()\n\n val smaller = (x: Byte, y: Byte) => if (x < y) x else y\n\n val solutionMatrix = dynamicSolveMatrixRightDown(\n inpMatrix,\n inpMatrix(0)(0)\n )((x, currScore, y) => {\n val candidateNextFst = x._1.+(y._1).asInstanceOf[Byte]\n val candidateNextSnd = x._2.+(y._2).asInstanceOf[Byte]\n if (currScore == null) {\n (candidateNextFst, candidateNextSnd)\n } else {\n (\n smaller(candidateNextFst, currScore._1),\n smaller(candidateNextSnd, currScore._2)\n )\n }\n })\n\n val ending = solutionMatrix(lineCount - 1)(lineCount - 1)\n val smallest = smaller(ending._1, ending._2)\n\n val p = if (ending._1 < ending._2) {\n getPath(solutionMatrix, (lineCount - 1, lineCount - 1))(\n new Ordering[(Byte, Byte)] {\n def compare(x: (Byte, Byte), y: (Byte, Byte)): Int =\n x._1.compare(y._1)\n }\n )\n } else {\n getPath(solutionMatrix, (lineCount - 1, lineCount - 1))(\n new Ordering[(Byte, Byte)] {\n def compare(x: (Byte, Byte), y: (Byte, Byte)): Int =\n x._2.compare(y._2)\n }\n )\n }\n\n// println(solutionMatrix.map(_.mkString(\"\\t\")).mkString(\"\\n\"))\n\n println(smallest)\n println(p)\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.annotation.tailrec\n\nobject X extends App {\n case class MyVertex[T, U](id: T, edges: Map[T, U])\n\n case class ScoreAndPrev[T, V](id: T, score: V)\n\n class MyGraph[T, U](vertices: Map[T, MyVertex[T, U]]) {\n\n def doDjikstra[V](start: T, initialValue: V)(combiner: (U, V) => V)(\n implicit ord: Ordering[V]\n ): Map[T, ScoreAndPrev[T, V]] = {\n val nextVertex = (\n visited: Set[T],\n scores: Map[T, ScoreAndPrev[T, V]]\n ) => {\n scores.filterNot(p => visited.contains(p._1)).minBy(w => w._2.score)._1\n }\n\n case class RunningScore(\n scores: Map[T, ScoreAndPrev[T, V]] = Map(\n start -> ScoreAndPrev(start, initialValue)\n ),\n visitedVertices: Set[T] = Set(),\n currVert: T = start\n )\n\n val scoreMap = vertices\n .foldLeft(RunningScore())((runningScore, _) => {\n val RunningScore(scores, visitedVertices, currVert) = runningScore\n val currVertEdges = vertices(currVert).edges\n\n val newScores =\n currVertEdges.foldLeft(scores)((currScores, currEdge) => {\n val neighbour = currEdge._1\n val edgeWeight = currEdge._2\n\n val scoreForCurrVert = currScores(currVert)\n\n val scoreForNeighbour = currScores.get(neighbour)\n\n val potentialScore = combiner(\n edgeWeight,\n scoreForCurrVert.score\n )\n\n val updatedScores = scoreForNeighbour match {\n case Some(s) if (ord.lt(potentialScore, s.score)) =>\n currScores + (neighbour -> ScoreAndPrev(\n currVert,\n potentialScore\n ))\n case None =>\n currScores + (neighbour -> ScoreAndPrev(\n currVert,\n potentialScore\n ))\n case _ => currScores\n }\n\n updatedScores\n })\n\n val updatedSet = visitedVertices + currVert\n val nextVert =\n if (updatedSet.size == vertices.size) currVert\n else nextVertex(updatedSet, newScores)\n\n RunningScore(newScores, updatedSet, nextVert)\n })\n .scores\n\n scoreMap\n }\n }\n\n object MyGraph {\n def apply[T, U](vertices: Map[T, MyVertex[T, U]]) =\n new MyGraph[T, U](vertices)\n }\n\n @tailrec\n def largestDividingPower(n: Int, m: Int, c: Int = 0): Int = {\n if (n % m == 0 && n != 0) largestDividingPower(n / m, m, c + 1) else c\n }\n\n def getAnswer(graph: MyGraph[(Int, Int), Int], end: (Int, Int)) = {\n val endModTwo =\n graph.doDjikstra((-1, -1), 0)((s, w) => w + largestDividingPower(s, 2))\n\n val endModFive =\n graph.doDjikstra((-1, -1), 0)((s, w) => w + largestDividingPower(s, 5))\n\n val smallestEnd = List(endModTwo, endModFive).minBy(s => s(end).score)\n\n def determinePath[T, V](\n start: T,\n end: T,\n djikstrad: Map[T, ScoreAndPrev[T, V]],\n path: List[T] = Nil\n ): List[T] = {\n if (start == end) path\n else determinePath(djikstrad(start).id, end, djikstrad, start +: path)\n }\n\n val thePath = determinePath(end, (0, 0), smallestEnd)\n\n val stringedPath = thePath\n .foldLeft(\"\", (0, 0))((path, e) => {\n val prev = path._2\n if (e._1 == prev._1) (path._1 + \"R\", e) else (path._1 + \"D\", e)\n })\n ._1\n\n (smallestEnd(end).score, stringedPath)\n }\n\n val lineCount = StdIn.readInt()\n\n val matrix =\n (0 until lineCount).foldLeft(Map[(Int, Int), Int]())((accMap, currLine) => {\n val line = StdIn.readLine().split(\" \").map(_.toInt)\n\n val lineMap = line.zipWithIndex.foldLeft(Map[(Int, Int), Int]())(\n (accLineMap, curr) => {\n accLineMap + ((currLine, curr._2) -> curr._1)\n }\n )\n\n accMap ++ lineMap\n })\n\n val vertexStart = MyVertex((-1, -1), Map((0, 0) -> 1))\n\n val vertices = matrix.foldLeft(Map[(Int, Int), MyVertex[(Int, Int), Int]]())(\n (accMap, currVert) => {\n val thisVert = currVert._1\n\n val downNeighbour = matrix.get((thisVert._1 + 1, thisVert._2)) match {\n case None => None\n case Some(value) => Some((thisVert._1 + 1, thisVert._2), value)\n }\n val rightNeighbour = matrix.get(thisVert._1, thisVert._2 + 1) match {\n case None => None\n case Some(value) => Some((thisVert._1, thisVert._2 + 1), value)\n }\n\n val neighbours = List(downNeighbour, rightNeighbour).flatten.toMap\n\n val vert = MyVertex((currVert._1), neighbours)\n\n accMap + (currVert._1 -> vert)\n }\n ) + ((-1, -1) -> vertexStart)\n\n val graph = MyGraph(vertices)\n\n val answer = getAnswer(graph, (lineCount - 1, lineCount - 1))\n\n println(answer._1)\n println(answer._2)\n\n}\n"}, {"source_code": "import scala.reflect.ClassTag\nimport scala.annotation.tailrec\nobject X extends App {\n def dynamicSolveMatrixRightDown[T, U: ClassTag](\n matrix: Array[Array[T]],\n initialValue: U\n )(\n combiner: (U, U, T) => U\n ) = {\n\n val len = matrix.length\n\n val solutionMatrix = Array.ofDim[U](len, len)\n\n solutionMatrix(0)(0) = combiner(initialValue, initialValue, matrix(0)(0))\n\n (0 until len).foreach(b => {\n (0 to b).foreach(i => {\n // row\n val rowWeight = solutionMatrix(i)(b)\n val colWeight = solutionMatrix(b)(i)\n\n if (!(b + 1 > len - 1)) {\n solutionMatrix(i)(b + 1) =\n combiner(rowWeight, solutionMatrix(i)(b + 1), matrix(i)(b + 1))\n solutionMatrix(b + 1)(i) =\n combiner(colWeight, solutionMatrix(b + 1)(i), matrix(b + 1)(i))\n }\n\n if (!(i + 1 > len - 1)) {\n val rightWeight = matrix(i + 1)(b)\n\n val candidateWeight =\n combiner(rowWeight, solutionMatrix(i + 1)(b), rightWeight)\n\n solutionMatrix(i + 1)(b) = candidateWeight\n\n val downWeight = matrix(b)(i + 1)\n\n val otherCandidateWeight =\n combiner(colWeight, solutionMatrix(b)(i + 1), downWeight)\n\n solutionMatrix(b)(i + 1) = otherCandidateWeight\n\n }\n\n if (b < len - 1 && i == b) {\n val leftWeight =\n combiner(\n solutionMatrix(b)(b + 1),\n solutionMatrix(b + 1)(b + 1),\n matrix(b + 1)(b + 1)\n )\n\n solutionMatrix(b + 1)(b + 1) = leftWeight\n\n val upWeight =\n combiner(\n solutionMatrix(b + 1)(b),\n solutionMatrix(b + 1)(b + 1),\n matrix(b + 1)(b + 1)\n )\n\n solutionMatrix(b + 1)(b + 1) = upWeight\n }\n\n })\n\n })\n\n solutionMatrix\n }\n\n def highestFactor(f: Int, n: Int) = {\n var m = n\n var c = 0\n while (m % f == 0) {\n c = c + 1\n m = m / f\n }\n (c, m)\n }\n\n @tailrec\n def getPath[U](\n solnMatrix: Array[Array[U]],\n start: (Int, Int),\n path: List[String] = List(),\n end: (Int, Int) = (0, 0)\n )(implicit ord: Ordering[U]): String = {\n if (start == end) {\n path.mkString(\"\")\n } else {\n start match {\n case (0, s) =>\n getPath(solnMatrix, (start._1, start._2 - 1), \"R\" +: path)\n case (s, 0) =>\n getPath(solnMatrix, (start._1 - 1, start._2), \"D\" +: path)\n case (u, v) => {\n if (ord.lt(solnMatrix(u - 1)(v), solnMatrix(u)(v - 1)))\n getPath(solnMatrix, (start._1 - 1, start._2), \"D\" +: path)\n else getPath(solnMatrix, (start._1, start._2 - 1), \"R\" +: path)\n }\n }\n }\n }\n\n val lineCount = scala.io.StdIn.readInt()\n\n val inpMatrix = Array.ofDim[(Int, Int)](lineCount, lineCount)\n\n (0 until lineCount).foreach(r => {\n var i = 0\n val line = scala.io.StdIn\n .readLine()\n .split(\" \")\n .foreach(w => {\n val cell = w.toInt\n val (p10, t) = highestFactor(10, cell)\n\n val (p2, k) = highestFactor(2, t)\n val p5 = highestFactor(5, k)._1\n inpMatrix(r)(i) = (p2, p5)\n i = i + 1\n })\n })\n\n val smaller = (x: Int, y: Int) => if (x < y) x else y\n\n val solutionMatrix = dynamicSolveMatrixRightDown(\n inpMatrix,\n (0, 0)\n )((x, currScore, y) => {\n val candidateNextFst = x._1 + y._1\n val candidateNextSnd = x._2 + y._2\n if (currScore == null) {\n (candidateNextFst, candidateNextSnd)\n } else {\n (\n smaller(candidateNextFst, currScore._1),\n smaller(candidateNextSnd, currScore._2)\n )\n }\n })\n\n val ending = solutionMatrix(lineCount - 1)(lineCount - 1)\n val smallest = smaller(ending._1, ending._2)\n\n val p = if (ending._1 < ending._2) {\n getPath(solutionMatrix, (lineCount - 1, lineCount - 1))(\n new Ordering[(Int, Int)] {\n def compare(x: (Int, Int), y: (Int, Int)): Int = x._1.compare(y._1)\n }\n )\n } else {\n getPath(solutionMatrix, (lineCount - 1, lineCount - 1))(\n new Ordering[(Int, Int)] {\n def compare(x: (Int, Int), y: (Int, Int)): Int = x._2.compare(y._2)\n }\n )\n }\n\n println(smallest)\n println(p)\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject Main extends App {\n val n = StdIn.readInt()\n val m = Array.ofDim[Int](n, n)\n (0 until n).foreach{i =>\n m(i) = StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n val t2 = Array.ofDim[Short](n, n)\n val t5 = Array.ofDim[Short](n, n)\n val d2 = Array.ofDim[Char](n, n)\n val d5 = Array.ofDim[Char](n, n)\n\n val corner = m(0)(0)\n t2(0)(0) = factorN(corner, 2, 0)\n t5(0)(0) = factorN(corner, 5, 0)\n d2(0)(0) = ' '\n d5(0)(0) = ' '\n\n (1 until n).foreach{i =>\n t2(i)(0) = (factorN(m(i)(0), 2, 0) + t2(i-1)(0)).toShort\n t5(i)(0) = (factorN(m(i)(0), 5, 0) + t5(i-1)(0)).toShort\n d2(i)(0) = 'D'\n d5(i)(0) = 'D'\n\n t2(0)(i) = (factorN(m(0)(i), 2, 0) + t2(0)(i-1)).toShort\n t5(0)(i) = (factorN(m(0)(i), 5, 0) + t5(0)(i-1)).toShort\n d2(0)(i) = 'R'\n d5(0)(i) = 'R'\n }\n\n @tailrec\n def factorN(x: Int, N: Int, m: Short): Short = {\n if(x == 0) m\n else {\n if (x % N == 0) factorN(x / N, N, (1 + m).toShort)\n else m\n }\n }\n\n (1 until n).foreach{x =>\n (1 until n).foreach{y =>\n val f2 = factorN(m(y)(x), 2, 0)\n val f5 = factorN(m(y)(x), 5, 0)\n\n if(t2(y-1)(x) < t2(y)(x-1)) {\n t2(y)(x) = (t2(y-1)(x) + f2).toShort\n d2(y)(x) = 'D'\n } else {\n t2(y)(x) = (t2(y)(x-1) + f2).toShort\n d2(y)(x) = 'R'\n }\n\n if(t5(y-1)(x) < t5(y)(x-1)) {\n t5(y)(x) = (t5(y-1)(x) + f5).toShort\n d5(y)(x) = 'D'\n } else {\n t5(y)(x) = (t5(y)(x-1) + f5).toShort\n d5(y)(x) = 'R'\n }\n }\n }\n\n var zx = -1\n var zy = -1\n (0 until n).foreach{x =>\n (0 until n).foreach{y =>\n if(m(y)(x) == 0) {\n zx = x\n zy = y\n }\n }\n }\n\n if(zx != -1) {\n println(0)\n// println(\"R\" * zx + \"D\" * (n-1) + \"R\" * (n-1-zx))\n } else {\n val dir = new Array[Char](2*n - 2)\n @tailrec\n def buildDir(arr: Array[Array[Char]], x: Int, y: Int, n: Int): Unit = {\n val d = arr(y)(x)\n if(d == 'D') {\n dir(n) = 'D'\n buildDir(arr, x, y - 1, n - 1)\n } else if (d == 'R') {\n dir(n) = 'R'\n buildDir(arr, x - 1, y, n - 1)\n }\n }\n if(t2(n-1)(n-1) > t5(n-1)(n-1)) {\n println(t5(n-1)(n-1))\n buildDir(d5, n-1, n-1, 2*n-3)\n println(new String(dir))\n } else {\n println(t2(n-1)(n-1))\n buildDir(d2, n-1, n-1, 2*n-3)\n println(new String(dir))\n }\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main extends App {\n val n = StdIn.readInt()\n val m = Array.ofDim[Int](n, n)\n (0 until n).foreach{i =>\n m(i) = StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n val table = Array.ofDim[(Int, Int, String)](n, n)\n val last = m(n-1)(n-1)\n if(last % 2 == 0) table(n-1)(n-1) = (1, 0, \"\")\n else if(last % 5 == 0) table(n-1)(n-1) = (0, 1, \"\")\n else table(n-1)(n-1) = (0, 0, \"\")\n\n def recursive(x: Int, y: Int): (Int, Int, String) = {\n val tv = table(x-1)(y-1)\n val cell = m(x-1)(y-1)\n val (t, f) =\n if(cell % 2 == 0) (1, 0)\n else if(cell % 5 == 0) (0, 1)\n else (0, 0)\n\n if(tv != null) tv else {\n (x, y) match {\n case _ if x == n =>\n val d = recursive(x, y + 1)\n val v = (d._1 + t, d._2 + f, \"D\" + d._3)\n table(x-1)(y-1) = v\n v\n case _ if y == n =>\n val r = recursive(x + 1, y)\n val v = (r._1 + t, r._2 + f, \"R\" + r._3)\n table(x-1)(y-1) = v\n v\n case _ =>\n val d = recursive(x, y + 1)\n val r = recursive(x + 1, y)\n\n val select = if(d._1 == 0 && d._2 == 0) (d, \"D\")\n else if (r._1 == 0 && r._2 == 0) (r, \"R\")\n else {\n val dt = (d._1 + t).min(d._2 + f)\n val rt = (r._1 + t).min(r._2 + f)\n val dr = (d._1 + t).max(d._2 + f)\n val rr = (r._1 + t).max(r._2 + f)\n if(dt > rt) {\n (r, \"R\")\n } else if(rt > dt ){\n (d, \"D\")\n } else if(dr > rr) {\n (r, \"R\")\n } else {\n (d, \"D\")\n }\n }\n\n val v = (select._1._1 + t, select._1._2 + f, select._2 + select._1._3)\n table(x-1)(y-1) = v\n v\n }\n }\n }\n\n val ret = recursive(1, 1)\n println(ret._1 min ret._2)\n println(ret._3)\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject Main extends App {\n val n = StdIn.readInt()\n val m = Array.ofDim[Int](n, n)\n (0 until n).foreach{i =>\n m(i) = StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n val t2 = Array.ofDim[Short](n, n)\n val t5 = Array.ofDim[Short](n, n)\n val d2 = Array.ofDim[Char](n, n)\n val d5 = Array.ofDim[Char](n, n)\n\n val corner = m(0)(0)\n t2(0)(0) = factorN(corner, 2, 0)\n t5(0)(0) = factorN(corner, 5, 0)\n d2(0)(0) = ' '\n d5(0)(0) = ' '\n\n (1 until n).foreach{i =>\n t2(i)(0) = (factorN(m(i)(0), 2, 0) + t2(i-1)(0)).toShort\n t5(i)(0) = (factorN(m(i)(0), 5, 0) + t5(i-1)(0)).toShort\n d2(i)(0) = 'D'\n d5(i)(0) = 'D'\n\n t2(0)(i) = (factorN(m(0)(i), 2, 0) + t2(0)(i-1)).toShort\n t5(0)(i) = (factorN(m(0)(i), 5, 0) + t5(0)(i-1)).toShort\n d2(0)(i) = 'R'\n d5(0)(i) = 'R'\n }\n\n @tailrec\n def factorN(x: Int, N: Int, m: Short): Short = {\n if(x == 0) m\n else {\n if (x % N == 0) factorN(x / N, N, (1 + m).toShort)\n else m\n }\n }\n\n (1 until n).foreach{x =>\n (1 until n).foreach{y =>\n val f2 = factorN(m(y)(x), 2, 0)\n val f5 = factorN(m(y)(x), 5, 0)\n\n if(t2(y-1)(x) < t2(y)(x-1)) {\n t2(y)(x) = (t2(y-1)(x) + f2).toShort\n d2(y)(x) = 'D'\n } else {\n t2(y)(x) = (t2(y)(x-1) + f2).toShort\n d2(y)(x) = 'R'\n }\n\n if(t5(y-1)(x) < t5(y)(x-1)) {\n t5(y)(x) = (t5(y-1)(x) + f5).toShort\n d5(y)(x) = 'D'\n } else {\n t5(y)(x) = (t5(y)(x-1) + f5).toShort\n d5(y)(x) = 'R'\n }\n }\n }\n\n var zx = -1\n var zy = -1\n (0 until n).foreach{x =>\n (0 until n).foreach{y =>\n if(m(y)(x) == 0) {\n zx = x\n zy = y\n }\n }\n }\n\n if(zx != -1) {\n println(1)\n val dir = new Array[Char](2*n - 2)\n (0 until zx).foreach(i => dir(i) = 'R')\n (0 until (n-1)).foreach(i => dir(zx + i) = 'D')\n (0 until (n-1-zx)).foreach(i => dir(zx + n - 1 + i) = 'D')\n println(new String(dir))\n } else {\n val dir = new Array[Char](2*n - 2)\n @tailrec\n def buildDir(arr: Array[Array[Char]], x: Int, y: Int, n: Int): Unit = {\n val d = arr(y)(x)\n if(d == 'D') {\n dir(n) = 'D'\n buildDir(arr, x, y - 1, n - 1)\n } else if (d == 'R') {\n dir(n) = 'R'\n buildDir(arr, x - 1, y, n - 1)\n }\n }\n if(t2(n-1)(n-1) > t5(n-1)(n-1)) {\n println(t5(n-1)(n-1))\n buildDir(d5, n-1, n-1, 2*n-3)\n println(new String(dir))\n } else {\n println(t2(n-1)(n-1))\n buildDir(d2, n-1, n-1, 2*n-3)\n println(new String(dir))\n }\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main extends App {\n val n = StdIn.readInt()\n val m = Array.ofDim[Int](n, n)\n (0 until n).foreach{i =>\n m(i) = StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n val table = Array.ofDim[(Int, Int, String, String)](n, n)\n\n val corner = m(0)(0)\n table(0)(0) = (factorN(corner, 2), factorN(corner, 5), \"\", \"\")\n (1 until n).foreach{i =>\n val (d2, d5, dd2, dd5) = table(i-1)(0)\n table(i)(0) = (factorN(m(i)(0), 2) + d2, factorN(m(i)(0), 5) + d5, dd2 + \"D\", dd5 + \"D\")\n val (r2, r5, rd2, rd5) = table(0)(i-1)\n table(0)(i) = (factorN(m(0)(i), 2) + r2, factorN(m(0)(i), 5) + r5, rd2 + \"R\", rd5 + \"R\")\n }\n\n def factorN(x: Int, N: Int): Int = {\n if(x % N == 0) factorN(x/N, N) + 1\n else 0\n }\n\n (1 until n).foreach{x =>\n (1 until n).foreach{y =>\n val f2 = factorN(m(y)(x), 2)\n val f5 = factorN(m(y)(x), 5)\n\n val dt = table(y-1)(x)\n val rt = table(y)(x-1)\n\n val r2 = if(dt._1 < rt._1) (dt._1 + f2, dt._3 + \"D\")\n else (rt._1 + f2, rt._3 + \"R\")\n\n val r5 = if(dt._2 < rt._2) (dt._2 + f5, dt._4 + \"D\")\n else (rt._2 + f5, rt._4 + \"R\")\n\n table(y)(x) = (r2._1, r5._1, r2._2, r5._2)\n }\n }\n\n var zx = -1\n var zy = -1\n (0 until n).foreach{x =>\n (0 until n).foreach{y =>\n if(m(y)(x) == 0) {\n zx = x\n zy = y\n }\n println(table(y)(x))\n }\n }\n\n if(zx != -1) {\n println(0)\n println(\"R\" * zx + \"D\" * (n-1) + \"R\" * (n-1-zx))\n } else {\n val f = table(n-1)(n-1)\n if(f._1 > f._2) {\n println(f._2)\n println(f._4)\n } else {\n println(f._1)\n println(f._3)\n }\n }\n}\n\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject Main extends App {\n val n = StdIn.readInt()\n val m = Array.ofDim[Int](n, n)\n (0 until n).foreach{i =>\n m(i) = StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n val t2 = Array.ofDim[Short](n, n)\n val t5 = Array.ofDim[Short](n, n)\n val d2 = Array.ofDim[Char](n, n)\n val d5 = Array.ofDim[Char](n, n)\n\n val corner = m(0)(0)\n t2(0)(0) = factorN(corner, 2, 0)\n t5(0)(0) = factorN(corner, 5, 0)\n d2(0)(0) = ' '\n d5(0)(0) = ' '\n\n (1 until n).foreach{i =>\n t2(i)(0) = (factorN(m(i)(0), 2, 0) + t2(i-1)(0)).toShort\n t5(i)(0) = (factorN(m(i)(0), 5, 0) + t5(i-1)(0)).toShort\n d2(i)(0) = 'D'\n d5(i)(0) = 'D'\n\n t2(0)(i) = (factorN(m(0)(i), 2, 0) + t2(0)(i-1)).toShort\n t5(0)(i) = (factorN(m(0)(i), 5, 0) + t5(0)(i-1)).toShort\n d2(0)(i) = 'R'\n d5(0)(i) = 'R'\n }\n\n @tailrec\n def factorN(x: Int, N: Int, m: Short): Short = {\n if(x == 0) m\n else {\n if (x % N == 0) factorN(x / N, N, (1 + m).toShort)\n else m\n }\n }\n\n (1 until n).foreach{x =>\n (1 until n).foreach{y =>\n val f2 = factorN(m(y)(x), 2, 0)\n val f5 = factorN(m(y)(x), 5, 0)\n\n if(t2(y-1)(x) < t2(y)(x-1)) {\n t2(y)(x) = (t2(y-1)(x) + f2).toShort\n d2(y)(x) = 'D'\n } else {\n t2(y)(x) = (t2(y)(x-1) + f2).toShort\n d2(y)(x) = 'R'\n }\n\n if(t5(y-1)(x) < t5(y)(x-1)) {\n t5(y)(x) = (t5(y-1)(x) + f5).toShort\n d5(y)(x) = 'D'\n } else {\n t5(y)(x) = (t5(y)(x-1) + f5).toShort\n d5(y)(x) = 'R'\n }\n }\n }\n\n var zx = -1\n var zy = -1\n (0 until n).foreach{x =>\n (0 until n).foreach{y =>\n if(m(y)(x) == 0) {\n zx = x\n zy = y\n }\n }\n }\n\n if(zx != -1) {\n println(1)\n val dir = new Array[Char](2*n - 2)\n (0 until zx).foreach(i => dir(i) = 'R')\n (0 until (n-1)).foreach(i => dir(zx + i) = 'D')\n (0 until (n-1-zx)).foreach(i => dir(zx + n - 1 + i) = 'D')\n println(new String(dir))\n } else {\n val dir = new Array[Char](2*n - 2)\n @tailrec\n def buildDir(arr: Array[Array[Char]], x: Int, y: Int, n: Int): Unit = {\n val d = arr(y)(x)\n if(d == 'D') {\n dir(n) = 'D'\n buildDir(arr, x, y - 1, n - 1)\n } else if (d == 'R') {\n dir(n) = 'R'\n buildDir(arr, x - 1, y, n - 1)\n }\n }\n\n val (min, dirArr) = if(t2(n-1)(n-1) > t5(n-1)(n-1)){\n (t5(n-1)(n-1), d5)\n } else (t2(n-1)(n-1), d2)\n\n if(min != 0 && zx != -1) {\n println(1)\n val dir = new Array[Char](2*n - 2)\n (0 until zx).foreach(i => dir(i) = 'R')\n (0 until (n-1)).foreach(i => dir(zx + i) = 'D')\n (0 until (n-1-zx)).foreach(i => dir(zx + n - 1 + i) = 'D')\n println(new String(dir))\n } else {\n println(min)\n buildDir(dirArr, n-1, n-1, 2*n-3)\n println(new String(dir))\n }\n }\n}\n\n"}], "src_uid": "13c58291ab9cf7ad1b8c466c3e36aacf"} {"source_code": "\nimport scala.math._\n\nobject Problem extends App {\n import Scanner._\n\n val n, k = readInt\n val heights = Array.fill(n)(readInt)\n val sums = Array.ofDim[Int](n - k)\n\n var sum = 0\n for(i <- 0 until k)\n sum += heights(i)\n var (min, idx) = (sum, 0)\n for(i <- 1 to (n-k)) {\n sum += heights(i+k-1) - heights(i-1)\n if(sum < min) {\n min = sum\n idx = i\n }\n }\n println(idx+1)\n}\n\nobject Scanner {\n def readInt() = {\n var acc = 0\n readWith {\n case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n }\n acc\n }\n def readLong() = {\n var acc = 0L\n readWith {\n case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10L) + (c - '0')\n }\n acc\n }\n def readDouble() = {\n var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)\n readWith {\n case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>\n frac = (frac * 10) + (c - '0')\n fracPow *= 10\n case c if c == '.' && !readFrac =>\n readFrac = true\n }\n acc + (frac.toDouble / fracPow)\n }\n def readString() = {\n var string = new StringBuilder\n readWith { case c => string += c }\n string\n }\n def readLine() = Console.in.readLine()\n def readChar() = Console.in.read().toChar\n def readWith(func: PartialFunction[Char, Unit]) {\n val handler = func orElse[Char, Unit] {\n case _ => throw new java.io.IOException(\"unexpected token\")\n }\n\n var c = readChar\n while(c.isWhitespace)\n c = readChar\n\n while(!c.isWhitespace) {\n handler(c)\n\n c = readChar\n }\n }\n}\n\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Fence {\n\tdef main(args: Array[String]): Unit = {\n\t\tval scan: Scanner = new Scanner(System.in)\n\t\tval n = scan.nextInt\n\t\tval k = scan.nextInt\n\t\t\n\t\tval h: Array[Int] = new Array[Int](n)\n\t\tfor(i <- 0 until n) {\n\t\t\th(i) = scan.nextInt\n\t\t}\n\t\t\n\t\tvar ans = 0\n\t\tvar now = 0\n\t\tvar best = 0x3fffffff\n\t\tfor((x,i) <- h.view.zipWithIndex) {\n\t\t\tif (i < k) now += x\n\t\t\telse {\n\t\t\t\tnow += x\n\t\t\t\tnow -= h(i - k)\n\t\t\t}\n\t\t\tif (i >= k - 1 && best > now) {\n\t\t\t\tans = i\n\t\t\t\tbest = now\n\t\t\t}\n\t\t}\n\t\tprintln(ans - k + 2)\n\t}\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toLong)\n val first = data.take(k).sum\n val res = (k until n).foldLeft(first, first, 0) {\n case((max, soFar, index), i) =>\n val nSoFar = soFar - data(i - k) + data(i)\n if (nSoFar < max)\n (nSoFar, nSoFar, i - k + 1)\n else\n (max, nSoFar, index)\n }\n println(res._3 + 1)\n}"}, {"source_code": "object B363 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n val input = readInts(n)\n for (i <- 1 until n) {\n input(i) += input(i-1)\n }\n var ret = input(k-1)\n var I = k-1\n for (i <- k until n) {\n if(ret > input(i)-input(i-k)) {\n ret = input(i)-input(i-k)\n I = i\n }\n }\n println(I-k+2)\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P363B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n // N planks\n // H_i ... hight of the ith plank\n // K consecutive planks to be removed\n\n \n def solve(): Long = {\n val N, K = sc.nextInt\n val dp: Array[Long] = Array.fill(N + 1)(0)\n\n 1 to N foreach { i =>\n dp(i) = dp(i - 1) + sc.nextLong\n }\n\n var min: Long = Long.MaxValue\n var j: Int = 0\n 1 to (N - K + 1) foreach { i =>\n val kSum = dp(i + K - 1) - dp(i - 1)\n if (kSum < min) {\n min = kSum\n j = i\n }\n }\n j\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ListBuffer\n\nobject Main2 {\n def main(args: Array[String]) {\n var ln = readLine()\n\n val first = ln.split(' ').toList.map(_.toInt).toArray\n ln = readLine()\n val second = ln.split(' ').toList.map(_.toInt).toArray\n var sum = BigInt(0)\n var minSum = BigInt(0)\n var pos = 0\n for(i <- 0 to first(1)-1) {\n sum += second(i)\n }\n minSum = sum\n for(j <- 1 to first(0) - first(1)){\n sum -= second(j-1)\n sum += second(first(1)+j-1)\n if(sum < minSum ) {\n minSum = sum\n pos = j\n }\n }\n\n print(pos+1)\n }\n\n}\n\n"}, {"source_code": "object Fence extends App {\n val input = io.Source.stdin.getLines.map(_.split(\" \").map(_.toInt))\n val (n :: hole :: Nil) = input.next.toList\n val fence = input.next\n val fencePairs = fence.zip(fence.drop(hole))\n\n var total = fence.take(hole).sum\n var min = total\n var plank = 1\n\n (0 until fencePairs.length) foreach { i =>\n val (drop, gain) = fencePairs(i)\n total = total + gain - drop\n if(total < min) {\n min = total\n plank = i + 2\n }\n }\n\n println(plank)\n}"}, {"source_code": "import java.util.Scanner\n\nobject FenceApp extends App {\n val scan: Scanner = new Scanner(System.in)\n val n = scan.nextInt\n val k = scan.nextInt\n\n val h: Array[Int] = new Array[Int](n)\n for(i <- 0 until n) {\n h(i) = scan.nextInt\n }\n\n var ans = 0\n var now = 0\n var best = 0x3fffffff\n for((x,i) <- h.view.zipWithIndex) {\n if (i < k) now += x\n else {\n now += x\n now -= h(i - k)\n }\n if (i >= k - 1 && best > now) {\n ans = i\n best = now\n }\n }\n println(ans - k + 2)\n}"}], "negative_code": [{"source_code": "\nimport scala.math._\n\nobject Problem extends App {\n import Scanner._\n\n val n, k = readInt\n val heights = Array.fill(n)(readInt)\n val sums = Array.ofDim[Int](n - k)\n\n var sum = 0\n for(i <- 0 until k)\n sum += heights(i)\n var min = sum\n for(i <- 1 to (n-k)) {\n sum += heights(i+k-1) - heights(i-1)\n if(sum < min)\n min = sum\n }\n println(min)\n}\n\nobject Scanner {\n def readInt() = {\n var acc = 0\n readWith {\n case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n }\n acc\n }\n def readLong() = {\n var acc = 0L\n readWith {\n case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10L) + (c - '0')\n }\n acc\n }\n def readDouble() = {\n var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)\n readWith {\n case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>\n frac = (frac * 10) + (c - '0')\n fracPow *= 10\n case c if c == '.' && !readFrac =>\n readFrac = true\n }\n acc + (frac.toDouble / fracPow)\n }\n def readString() = {\n var string = new StringBuilder\n readWith { case c => string += c }\n string\n }\n def readLine() = Console.in.readLine()\n def readChar() = Console.in.read().toChar\n def readWith(func: PartialFunction[Char, Unit]) {\n val handler = func orElse[Char, Unit] {\n case _ => throw new java.io.IOException(\"unexpected token\")\n }\n\n var c = readChar\n while(c.isWhitespace)\n c = readChar\n\n while(!c.isWhitespace) {\n handler(c)\n\n c = readChar\n }\n }\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toLong)\n val first = data.take(k).sum\n val res = (k + 1 to n - 1).foldLeft(first, first, 1) {\n case((max, soFar, index), i) =>\n val nSoFar = soFar - data(i - k - 1) + data(k)\n if (nSoFar < max)\n (nSoFar, nSoFar, i - k)\n else\n (max, nSoFar, index)\n }\n println(res._3)\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toLong)\n val first = data.take(k).sum\n val res = (k + 1 to n - 1).foldLeft(first, first, 0) {\n case((max, soFar, index), i) =>\n val nSoFar = soFar - data(i - k - 1) + data(k)\n if (nSoFar < max)\n (nSoFar, nSoFar, i - k)\n else\n (max, nSoFar, index)\n }\n println(res._3 + 1)\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toLong)\n val first = data.take(k).sum\n val res = (k + 1 to n - 1).foldLeft(first, first) {\n case((max, soFar), i) =>\n val nSoFar = soFar - data(i - k - 1) + data(k)\n (Math.min(nSoFar, max), nSoFar)\n }\n println(res._1)\n}"}, {"source_code": "object B363 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n val input = readInts(n)\n for (i <- 1 until n) {\n input(i) += input(i-1)\n }\n var ret = input(k-1)\n var I = 0\n for (i <- k until n) {\n if(ret > input(i)-input(i-k)) {\n ret = input(i)-input(i-k)\n I = i\n }\n }\n println(I-k+2)\n }\n}"}, {"source_code": "\nimport scala.collection.mutable.ListBuffer\n\nobject Main2 {\n def main(args: Array[String]) {\n var ln = readLine()\n\n val first = ln.split(' ').toList.map(_.toInt).toArray\n ln = readLine()\n val second = ln.split(' ').toList.map(_.toInt).toArray\n var sum = BigInt(0)\n var minSum = BigInt(0)\n var pos = 0\n for(i <- 0 to first(1)-1) {\n sum += second(i)\n }\n minSum = sum\n for(j <- 0 to first(0) - first(1)){\n sum -= second(j)\n sum += second(first(1)-1+j)\n if(sum < minSum ) {\n minSum = sum\n pos = j\n }\n }\n print(pos+1)\n }\n\n}\n\n"}, {"source_code": "object Fence extends App {\n val input = io.Source.stdin.getLines.map(_.split(\" \").map(_.toInt))\n val (n :: hole :: Nil) = input.next.toList\n val fence = input.next\n val fencePairs = fence.zip(fence.drop(hole))\n\n var total = fence.take(hole).sum\n var min = total\n var plank = 0\n\n (0 until fencePairs.length) foreach { i =>\n val (drop, gain) = fencePairs(i)\n total = total + gain - drop\n if(total < min) {\n min = total\n plank = i + 2\n }\n }\n\n println(plank)\n}"}, {"source_code": "object Fence extends App {\n val input = io.Source.stdin.getLines.map(_.split(\" \").map(_.toInt))\n val (n :: hole :: Nil) = input.next.toList\n val fence = input.next\n val fencePairs = fence.zip(fence.drop(hole))\n\n var total = fence.take(hole).sum\n var min = total\n var plank = 0\n\n (0 until fencePairs.length) foreach { i =>\n val (drop, gain) = fencePairs(i)\n total = total + gain - drop\n if(total < min) {\n min = total\n plank = i\n }\n }\n\n println(plank)\n}"}], "src_uid": "69f4e340b3f6e1d807e0545ebea1fe2f"} {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val ab = readLongLine()\n val a = ab.head\n val b = ab.last\n if (a == b) println(0)\n if (a > b) {\n if (a % b != 0) println(-1)\n else {\n val div = a / b\n println(num(div, 0))\n }\n }\n if (a < b) {\n if (b % a != 0) println(-1)\n else {\n val div = b / a\n println(num(div, 0))\n }\n }\n }\n // println(minNum(List[Boolean](false, false, true)))\n }\n\n def num(d: Long, acc: Long): Long = {\n if (d % 8 == 0) num(d / 8, acc + 1)\n else if (d % 4 == 0) num(d / 4, acc + 1)\n else if (d % 2 == 0) num(d / 2, acc + 1)\n else if (d == 1) acc else -1\n }\n \n def calcCost(tree: Array[List[Int]], nodes: Array[List[Int]]): Long = {\n def helper(visited: Array[Boolean], ind: Int, min: Int): (Int, Int, Long) = {\n val neighs = tree(ind).filter(n => !visited(n))\n neighs.foreach(visited(_) = true)\n val ourCost = nodes(ind).head\n val newMin = Math.min(min, ourCost)\n\n val costs = neighs.map(n => {\n helper(visited, n, newMin)\n }).reduce((one, two) => (one._1 + two._1, one._2 + two._2, one._3 + two._3))\n\n if (min <= ourCost) costs else {\n val posExchanges = Math.min(costs._1, costs._2)\n (costs._1 - posExchanges, costs._2 - posExchanges, costs._3 + posExchanges * ourCost)\n }\n }\n\n val visitedArr = Array.ofDim[Boolean](nodes.length + 1)\n visitedArr(1) = true\n helper(visitedArr, 1, Int.MaxValue)._3\n }\n\n def constructTree(nodes: Array[List[Int]], edges: List[List[Int]]): Array[List[Int]] = {\n val edgesNice = Array.ofDim[List[Int]](nodes.length + 1)\n for (i <- edgesNice.indices)\n edgesNice(i) = List[Int]()\n\n edges.foreach(edge => {\n edgesNice(edge.head) = edge.last :: edgesNice(edge.head)\n edgesNice(edge.last) = edge.head :: edgesNice(edge.last)\n })\n\n edgesNice.map(_.toList)\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n", "positive_code": [{"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b) = scala.io.StdIn.readLine().split(\" \").map(_.toLong.toBinaryString).sortBy(_.length)\n val (alen, blen) = (a.length, b.length)\n\n val (bl, br) = b.splitAt(alen)\n\n val ans =\n if (a != bl || br.contains('1')) -1\n else (blen - alen + 2) / 3\n\n println(ans)\n }\n}\n"}, {"source_code": "object A extends App {\n import java.{util => ju}\n def leftShiftsRequired(from: Long, to: Long, soFar: Long = 0): Long = {\n if (from == to) soFar\n else if (from > to) -1\n else leftShiftsRequired(from << 1, to, soFar + 1)\n }\n\n val in = new ju.Scanner(System.in)\n (1 to in.nextInt()).foreach { _ =>\n val a = in.nextLong()\n val b = in.nextLong()\n \n val shifts = leftShiftsRequired(a min b, a max b)\n if (shifts == -1) println(-1) else {\n val threeShifts = shifts / 3\n val remainingAfterThree = shifts % 3\n val twoShifts = remainingAfterThree / 2\n val oneShifts = remainingAfterThree % 2\n println(threeShifts + twoShifts + oneShifts)\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject A extends App {\n\n for {_ <- 0 until readLine.toInt} {\n val Seq(a, b) = readLine.split(\" \").toSeq.map(_.toLong)\n println(solution(a, b))\n }\n\n def solution(a0: Long, b0: Long): Long = {\n val a = a0.toBinaryString\n val b = b0.toBinaryString\n if (before0(a) != before0(b)) -1 else {\n val binDiff = math.abs(trailing0(a) - trailing0(b))\n (binDiff + 2) / 3\n }\n }\n\n def before0(s: String) = s.reverse.dropWhile(_ == '0')\n def trailing0(s: String) = s.reverse.takeWhile(_ == '0').length\n}\n"}], "negative_code": [{"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b) = scala.io.StdIn.readLine().split(\" \").map(_.toLong.toBinaryString).sortBy(_.length)\n\n val i = b.indexOfSlice(a)\n\n val ans =\n if (i < 0 || b.indexOfSlice(a, i + 1) > 0) -1\n else (b.length - a.length + 2) / 3\n\n println(ans)\n }\n}\n"}], "src_uid": "541039ef3c9b8251b758608811533e06"} {"source_code": "object CF917A extends App{\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n val a = Seq.fill[Int](n)(sc.nextInt)\n println(a filter (i => {val d = Math.sqrt(i); d - d.intValue != 0}) max)\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject R458A {\n def isSquare(x :Int): Boolean = {\n if(x<0) return false\n if(x==0) return true\n for(i <- 1 to (Math.sqrt(x)+1).toInt) {\n if(i*i==x) {\n return true\n }\n }\n return false\n }\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val a = new Array[Int](n)\n for(i <- 0 until n) {\n a(i) = sc.nextInt()\n }\n var max = -10000000\n for(i <- 0 until n) {\n if(!isSquare(a(i))) {\n max = Math.max(a(i), max)\n }\n }\n println(max)\n }\n}\n"}, {"source_code": "\nobject PerfectSquare extends App {\n val n = scala.io.StdIn.readLine().toLong\n val as = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n def perfectSquare(x: Long) = {\n if (x < 0) {\n false\n } else {\n Math.sqrt(x).isValidInt\n }\n }\n\n println(as.filterNot(perfectSquare).max)\n\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n\n var max = Int.MinValue\n\n def isSquare(x: Int): Boolean = {\n x >= 0 && {\n val r = Math.sqrt(x).toInt\n r * r == x\n }\n }\n\n for (a <- as) {\n if (!isSquare(a) && a > max) max = a\n }\n\n println(max)\n}\n"}, {"source_code": "object A extends App {\n val n = scala.io.StdIn.readInt()\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val b = a.filter(i => i < 0 || scala.math.sqrt(i) % 1 != 0)\n println(b.max)\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nobject R458A {\n def isSquare(x :Int): Boolean = {\n if(x<=0) return false\n for(i <- 1 to (Math.sqrt(x)+1).toInt) {\n if(i*i==x) {\n return true\n }\n }\n return false\n }\n def main(args: Array[String]): Unit = {\n println(Math.sqrt(-1))\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val a = new Array[Int](n)\n for(i <- 0 until n) {\n a(i) = sc.nextInt()\n }\n var max = -10000000\n for(i <- 0 until n) {\n if(!isSquare(a(i))) {\n max = Math.max(a(i), max)\n }\n }\n println(max)\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject R458A {\n def isSquare(x :Int): Boolean = {\n if(x<=0) return false\n for(i <- 1 to (Math.sqrt(x)+1).toInt) {\n if(i*i==x) {\n return true\n }\n }\n return false\n }\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val a = new Array[Int](n)\n for(i <- 0 until n) {\n a(i) = sc.nextInt()\n }\n var max = -10000000\n for(i <- 0 until n) {\n if(!isSquare(a(i))) {\n max = Math.max(a(i), max)\n }\n }\n println(max)\n }\n}\n"}, {"source_code": "\nobject A extends App {\n val n = scala.io.StdIn.readInt()\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val b = a.filter(i => i <= 0 || scala.math.sqrt(i) % 1 != 0)\n println(b.max)\n}\n"}], "src_uid": "d46d5f130d8c443f28b52096c384fef3"} {"source_code": "import scala.io.StdIn\n\nobject A extends App {\n\n val Array(n, m) = StdIn.readLine().split(\" \").map(_.toInt)\n\n val s = StdIn.readLine()\n val t = StdIn.readLine()\n\n var min = Int.MaxValue\n var index = 0\n\n (0 to (t.size - s.size)).foreach { i =>\n val sum = (0 to (s.size -1)).map { x =>\n if(t(x + i) != s(x)) 1 else 0\n }.sum\n if(sum < min) {\n min = sum\n index = i\n }\n }\n\n println(min)\n (0 to (s.size -1)).map { x =>\n if(t(x + index) != s(x)) {\n print((x + 1) + \" \")\n }\n }\n\n\n}\n\n", "positive_code": [{"source_code": "object P822B {\n\n def diff(s1: String, s2: String): Seq[Int] = (s1 zip s2).zipWithIndex.collect{ case (p, i) if p._1 != p._2 => i+1 }\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n in.nextLine() // skip first line\n val s = in.nextLine()\n val t = in.nextLine()\n val idxs = (0 to (t.length - s.length)).map(i => diff(s, t.substring(i))).minBy(_.length)\n println(idxs.length)\n println(idxs.mkString(\" \"))\n }\n\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n\n import scala.io.Codec\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next: String = tokenizer().get.nextToken()\n override def hasNext: Boolean = tokenizer().nonEmpty\n override def close(): Unit = reader.close()\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val s, t = readLine\n\n var min = Int.MaxValue\n var pos = 0\n\n for (start <- 0 to t.length - s.length) {\n var diff = 0\n for (i <- 0 until s.length) if (s(i) != t(start + i)) diff += 1\n if (diff < min) {\n min = diff\n pos = start\n }\n }\n\n val res = ArrayBuffer.empty[Int]\n for (i <- 0 until s.length) if (s(i) != t(pos + i)) res += (i + 1)\n\n println(min)\n println(res.mkString(\" \"))\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextBoolean: Boolean = next.equalsIgnoreCase(\"1\")\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n\n override def toString = s\"MultiHashSet($map)\"\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n *\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def gcd(a: Int, b: Int): Int =\n if (b == 0) a\n else gcd(b, a % b)\n\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val s = next.toCharArray\n val t = next.toCharArray\n var min = Int.MaxValue\n var res = new mutable.HashSet[Int]()\n for (i <- 0 to m - n) {\n var diff = 0\n val pos = new mutable.HashSet[Int]()\n for (j <- 0 until n) {\n if (s(j) != t(i + j)) {\n diff += 1\n pos.add(j + 1)\n }\n }\n if (diff < min) {\n min = diff\n res = pos\n }\n }\n out.println(min)\n res.foreach(x => out.print(s\"$x \"))\n return 0\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject test\n{\n def main(args: Array[String]): Unit = {\n val s = new Scanner(System.in)\n val n = s.nextInt()\n val m = s.nextInt()\n s.nextLine()\n val str1 = s.nextLine()\n val str2 = s.nextLine()\n var minlist:List[Int]=List()\n var minc=1e8\n\n for(i<-0 to m-n){\n var c=0\n var chlist:List[Int]=List()\n for(j<-0 to n-1){\n if(str1.charAt(j)!=str2.charAt(i+j)){\n c+=1\n chlist = j::chlist\n }\n }\n if(c (arr(0), arr(1))).sorted\n var pos = math.min(in(0)._1, in(0)._2)\n for(i <- 1 until n) {\n val min = math.min(in(i)._1, in(i)._2)\n if(min >= pos) {\n pos = min\n } else {\n pos = math.max(in(i)._1, in(i)._2)\n }\n }\n println(pos)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _479C extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => (next.toInt, next.toInt)).sorted.toArray\n\n def doit(i: Int, pre: Int):Int = {\n if (i == n) pre\n else {\n if (pre <= a(i)._2) doit(i + 1, a(i)._2)\n else doit(i + 1, a(i)._1)\n }\n }\n\n println(doit(0, -1))\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println((1 to n).map{_ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt)\n (a, b)\n }.sorted.foldLeft(0) {\n case(acc, (a, b)) if b < acc =>\n a\n case(acc, (a, b)) =>\n b\n })\n\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer\n\nobject P479C {\n\tdef convert(a: Array[Int]) : (Int, Int) = (a(0), a(1))\n\n\tdef choose(last: Int, choices: (Int, Int)) : Int = {\n\t\tif (choices._2 >= last) choices._2 else choices._1\n\t}\n\n\tdef main(args: Array[String]) {\n\t\tval lines = scala.io.Source.stdin.getLines.toList\n\t\tval exams = lines.tail.map(_.split(\" \").map(_.toInt))\n\t\tprintln(exams.map(convert).sorted.foldLeft(0)(choose))\n\t}\n}\n"}, {"source_code": "object Exams{\n def main(args : Array[String]){\n \n var n : Int = readLine.toInt\n var exams : Array[(Int,Int)] = new Array[(Int,Int)](n)\n var lastExam : Int = 0\n \n for(i <- 0 to n-1){\n exams(i) = (readLine.split(\" \").map(_.toInt)) match {case Array(x,y) => (x,y)}\n }\n \n exams = exams.sortWith((x, y) => {if (x._1 != y._1) x._1 < y._1 else x._2 < y._2} )\n // exams = exams.sortBy(_._1)\n \n exams.foreach(exam => {lastExam = if ( exam._2 >= lastExam ) exam._2 else exam._1})\n\n println(lastExam)\n }\n}"}, {"source_code": "object Main {\n\n val in = {\n val lines = scala.io.Source.stdin.getLines\n lines map (_ split ' ') filter (_.nonEmpty) flatten\n }\n \n def nextInt = in.next.toInt\n \n def main(args: Array[String]): Unit = {\n \n val N = nextInt\n val vals = Array.fill(N){\n val a, b = nextInt\n (a, b)\n }.sorted\n \n var best = 0\n for ((a, b) <- vals) {\n if (b >= best) best = b\n else best = a\n }\n \n println(best)\n }\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val abs = Array.ofDim[(Int, Int)](n)\n\n for (i <- 0 until n) {\n val Array(a, b) = readInts(2)\n abs(i) = (a, b)\n }\n\n val maxA = abs.map(_._1).max\n val maxB = abs.map(_._2).max\n \n val sorted = abs.sorted\n\n var current = 0\n for ((a, b) <- sorted) {\n if (a > current) {\n if (b >= current) current = b\n else current = a\n }\n }\n \n println(current)\n}"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val abs = Array.ofDim[(Int, Int)](n)\n\n for (i <- 0 until n) {\n val Array(a, b) = readInts(2)\n abs(i) = (a, b)\n }\n\n val maxA = abs.map(_._1).max\n val maxB = abs.map(_._2).max\n\n if (abs.filter(_._1 == maxA).forall(_._2 >= maxB))\n println(maxB)\n else println(maxA)\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val abs = Array.ofDim[(Int, Int)](n)\n\n for (i <- 0 until n) {\n val Array(a, b) = readInts(2)\n abs(i) = (a, b)\n }\n\n val maxA = abs.map(_._1).max\n val maxB = abs.map(_._2).max\n \n val sorted = abs.sortBy(_._1)\n\n var current = 0\n for ((a, b) <- sorted) {\n if (a > current) {\n if (b >= current) current = b\n else current = a\n }\n }\n \n println(current)\n}"}, {"source_code": "\nobject Exams{\n def main(args : Array[String]){\n \n var n : Int = readLine.toInt\n var exams : Array[(Int,Int)] = new Array[(Int,Int)](n)\n var lastExam : Int = 0\n \n for(i <- 0 to n-1){\n exams(i) = (readLine.split(\" \").map(_.toInt)) match {case Array(x,y) => (x,y)}\n }\n \n exams = exams.sortBy(_._1)\n \n exams.foreach(exam => {lastExam = if ( exam._2 >= lastExam ) exam._2 else exam._1})\n\n println(lastExam)\n }\n}"}], "src_uid": "71bc7c4eb577441f2563e40d95306752"} {"source_code": "\nobject tmp extends App {\n\n import java.io._\n import scala.collection.mutable\n import java.util.StringTokenizer\n\n class MyScanner(br: BufferedReader) {\n var st = new StringTokenizer(\"\")\n\n def this(is: InputStream) = this(new BufferedReader(new InputStreamReader(is)))\n\n private def next() = {\n\n while (!st.hasMoreElements) {\n st = new StringTokenizer(br.readLine())\n }\n st.nextToken()\n }\n\n def nextInt() = java.lang.Integer.parseInt(next())\n\n def nextLong() = java.lang.Long.parseLong(next())\n\n def nextLine() = br.readLine()\n }\n\n\n val sc = new MyScanner(System.in)\n val in = sc.nextLine().foldLeft(mutable.Map[Char, Int]().withDefaultValue(0)) {\n (acc, cur) => {acc(cur) += 1; acc}\n }\n val out = sc.nextLine().foldLeft(mutable.Map[Char, Int]().withDefaultValue(0)) {\n (acc, cur) => {acc(cur) += 1; acc}\n }\n var result = 0\n for (k <- out.keys) {\n if (in(k) >= out(k)) {\n result += out(k)\n } else if (in(k) == 0) {\n println(-1)\n System.exit(0)\n } else {\n result += in(k)\n }\n }\n println(result)\n}\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val have = in.next().groupBy(i => i).map(i => i._1 -> i._2.length)\n val need = in.next().groupBy(i => i).map(i => i._1 -> i._2.length)\n println(need.keys.foldLeft(0) {\n case(-1, _) => -1\n case(acc, el) if have.get(el).isEmpty => -1\n case(acc, el) if have(el) > need(el) => acc + need(el)\n case(acc, el) => acc + have(el)\n })\n}"}, {"source_code": "object B extends App {\n val a, b = readLine();\n val ct = (s: String, c: Char) => { s.count(_ == c) }\n val ctm = (l: String) => { l map (ct(l, _: Char)) }\n val am = a.zip(ctm(a)).toMap\n val bm = b.zip(ctm(b)).toMap\n var impossible = false;\n var sum = 0;\n for ((k, n) <- bm)\n {\n if (am.contains(k) == false) {\n impossible = true;\n }\n else {\n sum += n min am(k)\n }\n }\n if (impossible) sum = -1;\n println(sum);\n}\n"}], "negative_code": [], "src_uid": "b1e09df7c47dbd04992e64826337c28a"} {"source_code": "/**\n * Created by yangchaozhong on 3/10/15.\n */\nobject CF522A extends App {\n import scala.collection.mutable.{HashMap, HashSet}\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val n = nextInt\n\n val graph = HashMap[String, HashSet[String]]()\n (1 to n).foreach { i =>\n val toName = nextString.toLowerCase\n val edge = nextString\n val fromName = nextString.toLowerCase\n if (graph.contains(fromName)) {\n graph(fromName) += toName\n } else {\n graph += (fromName -> HashSet(toName))\n }\n }\n\n def dfs(node: String): Int = {\n if (!graph.contains(node)) 1 else graph(node).map(dfs(_)).max + 1\n }\n\n out.println(dfs(\"Polycarp\".toLowerCase))\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable._\n\nobject Reposts {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n var n=in.readInt()\n val arr=Array.fill[Int](n+1)(-1)\n arr(0)= -1\n val hm=HashMap[String,Int]()\n hm.put(\"polycarp\",0)\n for(i<-1 to n){\n var name=in.readLine().split(\" reposted \")\n hm.put(name(0).toLowerCase(),i)\n val p=hm.get(name(1).toLowerCase()).get\n arr(i)=p\n }\n var chainSize=2\n for(i<- 1 to n){\n var j=i\n var c=1\n while (arr(j)!= -1){\n c+=1\n j=arr(j)\n }\n chainSize=math.max(chainSize,c)\n }\n println(chainSize)\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable._\n\nobject Reposts {\n def main(args: Array[String]): Unit = {\n //Intuition: here post and re-post hold a parent child relation \n val in =scala.io.StdIn\n var n=in.readInt()\n val cs=HashMap[String,Int]()\n cs.put(\"polycarp\",1)\n var chainSize=0\n for(i<-1 to n){\n var name=in.readLine().split(\" reposted \")\n val t=cs.get(name(1).toLowerCase()).get+1\n cs.put(name(0).toLowerCase(),t)\n chainSize=math.max(chainSize,t)\n }\n println(chainSize)\n }\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Main3 extends App with IOUtils {\n val n = nextInt\n val pairs = (1 to n).map { i =>\n val to = nextToken\n nextToken\n val from = nextToken\n (from.toLowerCase, to.toLowerCase)\n }\n val descendants = pairs.groupBy(_._1).mapValues(_.map(_._2))\n \n def deepest(handle: String): Int = descendants.get(handle) match {\n case Some(further) => further.map(deepest).max + 1\n case _ => 0\n }\n \n println(deepest(\"polycarp\") + 1)\n}\n\ntrait IOUtils {\n var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def nextInt: Int = nextToken.toInt\n\n def nextLong: Long = nextToken.toLong\n\n def nextIntPair: (Int, Int) = (nextInt, nextInt)\n\n def nextToken: String = {\n if (tok == null || !tok.hasMoreTokens) {\n tok = new StringTokenizer(in.readLine)\n }\n\n tok.nextToken\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable.Map\n\nobject A522 extends App {\n\n type Graph = Map[String, List[String]]\n val rep = Map[String, List[String]]()\n val n = readInt\n\n (1 to n)\n .map(_ => readLine.toLowerCase.split(\" \"))\n .foreach(x => if(!rep.contains(x(2))) rep(x(2)) = x(0) :: Nil else rep(x(2)) ::= x(0))\n\n def BFS(startVertex : String, rep : Graph) = {\n\n def BFS0(v : String, visited : List[(String, Int)], level : Int = 1) : List[(String, Int)] = {\n if(visited.map(_._1).contains(v) || !rep.contains(v))\n visited\n else {\n val neigh = rep(v).filterNot(x => visited.map(_._1).contains(x))\n neigh.foldLeft((v, level) :: visited)((res, v) => BFS0(v, res, level + 1))\n }\n }\n\n BFS0(startVertex, List()).map(_._2).max\n }\n\n println(rep.keys.toList.map(x => BFS(x, rep)).max + 1)\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val g = new Array[Array[Boolean]](500)\n val map = new mutable.HashMap[String, Int]()\n for (i <- 0 until n) {\n val name1 = next.toLowerCase\n next\n val name2 = next.toLowerCase\n val a = map.getOrElse(name2, 0)\n val b = map.getOrElse(name1, 0)\n map.put(name1, Math.max(a + 1, b))\n }\n var max = 0\n map.keySet.foreach(key => {\n max = Math.max(max, map.get(key).get)\n })\n out.println(max + 1)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "negative_code": [], "src_uid": "16d4035b138137bbad247ccd5e560051"} {"source_code": "object _635D extends CodeForcesApp {\n override type Result = Seq[Int]\n\n override def solve(read: InputReader) = {\n val n, k, a, b, q = read[Int]\n val fixed, broken = new UpdateableFenwickTree(n + 1)\n val demand = Array.ofDim[Int](n + 1)\n var ans = Vector.empty[Int]\n repeat(q) {\n if(read[Int] == 1) {\n val i, d = read[Int]\n demand(i) += d\n fixed(i) = demand(i) min a\n broken(i) = demand(i) min b\n } else {\n val d = read[Int]\n val (r1, r2) = (broken.sum(1, d - 1), fixed.sum(d + k, n))\n ans = ans :+ (r1 + r2)\n }\n }\n ans\n }\n\n trait BitIndexTree {\n def prefixSum(i: Int): Int\n def sum(start: Int, end: Int): Int = prefixSum(end) - prefixSum(start - 1)\n def +=(i: Int, delta: Int): Unit\n }\n\n class FenwickTree(n: Int) extends BitIndexTree {\n private[this] val tree = Array.ofDim[Int](n)\n\n override def prefixSum(i: Int) = if (i < 0) 0 else tree(i) + prefixSum((i & (i + 1)) - 1)\n\n override def +=(i: Int, delta: Int) = if (i < n) {\n tree(i) += delta\n this += (i | (i + 1), delta)\n }\n }\n\n class UpdateableFenwickTree(n: Int) extends FenwickTree(n) {\n private[this] val data = Array.ofDim[Int](n)\n\n def update(i: Int, value: Int) = {\n this += (i, value - data(i))\n data(i) = value\n }\n }\n\n @inline def repeat(n: Int)(f: => Unit): Unit = for {_ <- 1 to n} f\n\n override def format(result: Result) = result mkString \"\\n\"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}", "positive_code": [{"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n object BIT {\n\n def query(t: Array[Long], r: Int, acc: Long = 0): Long =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Long], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Long], i: Int, delta: Long): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(src: Array[Long]): Array[Long] = {\n val t = Array.fill(src.length) { 0L }\n for (i <- src.indices) update(t, i, src(i))\n t\n }\n\n }\n\n val Array(n, k, a, b, q) = readInts(5)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val demands = Array.fill(n)(0L)\n val onA = BIT(demands)\n val onB = BIT(demands)\n val res = ArrayBuffer.empty[Long]\n\n var quer = 0\n while (quer < q) {\n val query = readLine.split(\" \").map(_.toInt)\n query match {\n case Array(1, _d, x) =>\n val d = _d - 1\n val newDemand = demands(d) + x\n if (demands(d) < a) {\n BIT.update(onA, d, x.toLong min (a.toLong - demands(d)))\n }\n if (demands(d) < b) {\n BIT.update(onB, d, x.toLong min (b - demands(d)))\n }\n demands(d) = newDemand\n case Array(2, _p) =>\n val p0 = _p - 1\n val p1 = p0 + k\n val r1 = BIT.rangeQuery(onB, 0, p0 - 1)\n val r3 = BIT.rangeQuery(onA, p1, n - 1)\n res += r1 + r3\n }\n quer += 1\n }\n\n println(res.mkString(\"\\n\"))\n Console.flush\n}\n"}, {"source_code": "object _635D extends CodeForcesApp {\n override type Result = Seq[Long]\n\n override def solve(read: InputReader) = {\n val (n, k, a, b, q) = read[(Int, Int, Int, Int, Int)]\n val (fixed, broken, demand) = (new FenwickTree(n + 1), new FenwickTree(n + 1), Array.ofDim[Long](n))\n var ans = Vector.empty[Long]\n repeat(q) {\n if(read[Int] == 1) {\n val (d, x) = read[(Int, Long)]\n if (demand(d-1) < a) fixed(d-1) = x min (a - demand(d-1))\n if (demand(d-1) < b) broken(d-1) = x min (b - demand(d-1))\n demand(d-1) += x\n } else {\n val d = read[Int]\n val r1 = broken(0, d - 2)\n val r2 = fixed(d + k - 1, n - 1)\n ans = ans :+ (r1 + r2)\n }\n }\n\n ans\n }\n\n @inline def repeat(n: Int)(f: => Unit): Unit = for {_ <- 1 to n} f\n\n class FenwickTree(n: Int) {\n private[this] val tree = Array.ofDim[Long](n)\n\n def apply(i: Int): Long = if (i < 0) 0 else tree(i) + apply((i & (i + 1)) - 1)\n\n def apply(start: Int, end: Int): Long = this(end) - this(start - 1)\n\n def update(i: Int, v: Long): Unit = if (i < n) {\n tree(i) += v\n this(i | (i + 1)) = v\n }\n\n override def toString = tree.indices map apply mkString \", \"\n }\n\n override def format(result: Result) = result mkString \"\\n\"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}, {"source_code": "object _635D extends CodeForcesApp {\n override type Result = Seq[Int]\n\n override def solve(read: InputReader) = {\n val (n, k, a, b, q) = read[(Int, Int, Int, Int, Int)]\n val fixed, broken = new UpdateableFenwickTree(n + 1)\n val demand = Array.ofDim[Int](n + 1)\n var ans = Vector.empty[Int]\n repeat(q) {\n if(read[Int] == 1) {\n val (i, d) = read[(Int, Int)]\n demand(i) += d\n fixed(i) = demand(i) min a\n broken(i) = demand(i) min b\n } else {\n val d = read[Int]\n val r1 = broken.sum(1, d - 1)\n val r2 = fixed.sum(d + k, n)\n ans = ans :+ (r1 + r2)\n }\n }\n ans\n }\n\n trait BitIndexTree {\n def prefixSum(i: Int): Int\n def sum(start: Int, end: Int): Int = prefixSum(end) - prefixSum(start - 1)\n def +=(i: Int, delta: Int): Unit\n }\n\n class FenwickTree(n: Int) extends BitIndexTree {\n private[this] val tree = Array.ofDim[Int](n)\n\n override def prefixSum(i: Int) = if (i < 0) 0 else tree(i) + prefixSum((i & (i + 1)) - 1)\n\n override def +=(i: Int, delta: Int) = if (i < n) {\n tree(i) += delta\n this += (i | (i + 1), delta)\n }\n }\n\n class UpdateableFenwickTree(n: Int) extends FenwickTree(n) {\n private[this] val data = Array.ofDim[Int](n)\n\n def update(i: Int, value: Int) = {\n this += (i, value - data(i))\n data(i) = value\n }\n }\n\n @inline def repeat(n: Int)(f: => Unit): Unit = for {_ <- 1 to n} f\n\n override def format(result: Result) = result mkString \"\\n\"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}"}, {"source_code": "object _635D extends CodeForcesApp {\n override type Result = Seq[Int]\n\n override def solve(read: InputReader) = {\n val (n, k, a, b, q) = read[(Int, Int, Int, Int, Int)]\n val fixed = new UpdateableFenwickTree(n + 1)\n val broken = new UpdateableFenwickTree(n + 1)\n val demand = Array.ofDim[Int](n + 1)\n var ans = Vector.empty[Int]\n repeat(q) {\n if(read[Int] == 1) {\n val (i, d) = read[(Int, Int)]\n demand(i) += d\n fixed(i) = demand(i) min a\n broken(i) = demand(i) min b\n } else {\n val d = read[Int]\n val r1 = broken(1, d - 1)\n val r2 = fixed(d + k, n)\n ans = ans :+ (r1 + r2)\n }\n }\n ans\n }\n\n trait BitIndexTree {\n def apply(i: Int): Int\n def apply(start: Int, end: Int): Int = this(end) - this(start - 1)\n def +=(i: Int, delta: Int): Unit\n }\n\n class FenwickTree(n: Int) extends BitIndexTree {\n private[this] val tree = Array.ofDim[Int](n)\n\n override def apply(i: Int) = if (i < 0) 0 else tree(i) + apply((i & (i + 1)) - 1)\n\n override def +=(i: Int, delta: Int) = if (i < n) {\n tree(i) += delta\n this += (i | (i + 1), delta)\n }\n }\n\n class UpdateableFenwickTree(n: Int) extends FenwickTree(n) {\n private[this] val data = Array.ofDim[Int](n)\n\n def update(i: Int, value: Int) = {\n this += (i, value - data(i))\n data(i) = value\n }\n }\n\n @inline def repeat(n: Int)(f: => Unit): Unit = for {_ <- 1 to n} f\n\n override def format(result: Result) = result mkString \"\\n\"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}, {"source_code": "object _635D extends CodeForcesApp {\n override type Result = Seq[Long]\n\n override def solve(read: InputReader) = {\n val (n, k, a, b, q) = read[(Int, Int, Int, Int, Int)]\n val (fixed, broken, demand) = (new FenwickTree(n + 1), new FenwickTree(n + 1), Array.ofDim[Long](n + 1))\n var ans = Vector.empty[Long]\n repeat(q) {\n if(read[Int] == 1) {\n val (i, d) = read[(Int, Long)]\n if (demand(i) < a) fixed(i) = d min (a - demand(i))\n if (demand(i) < b) broken(i) = d min (b - demand(i))\n demand(i) += d\n } else {\n val d = read[Int]\n val r1 = broken(1, d - 1)\n val r2 = fixed(d + k, n)\n ans = ans :+ (r1 + r2)\n }\n }\n ans\n }\n\n class FenwickTree(n: Int) {\n private[this] val tree = Array.ofDim[Long](n)\n\n def apply(i: Int): Long = if (i < 0) 0 else tree(i) + apply((i & (i + 1)) - 1)\n\n def apply(start: Int, end: Int): Long = this(end) - this(start - 1)\n\n def update(i: Int, v: Long): Unit = if (i < n) {\n tree(i) += v\n this(i | (i + 1)) = v\n }\n }\n\n @inline def repeat(n: Int)(f: => Unit): Unit = for {_ <- 1 to n} f\n\n override def format(result: Result) = result mkString \"\\n\"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}], "negative_code": [], "src_uid": "d256f8cf105b08624eee21dd76a6ad3d"} {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n val n = readInt\n def ans = if(n % 2 == 0) (n to 1) by -1 else Iterable(-1)\n\n def main(args: Array[String]) {\n println(ans.mkString(\" \"))\n }\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _233A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n if (n % 2 == 1) println(-1)\n else {\n val a = (1 to n).toArray\n for (i <- 0 until(n, 2)) {\n val cb = a(i)\n a(i) = a(i + 1)\n a(i + 1) = cb\n }\n println(a.mkString(\" \"))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n if (n % 2 == 1)\n println(\"-1\")\n else\n println(Range(1, n + 1).map{i =>\n if (i % 2 == 0) i - 1\n else i + 1\n }.mkString(\" \"))\n}"}, {"source_code": "object A233 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n if(n%2 == 1) {\n println(\"-1\")\n } else {\n println((2 to n by 2).flatMap(x => Array(x, x-1)).mkString(\" \"))\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P233A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n\n val answer =\n if (N % 2 == 1) \"-1\"\n else {\n for (i <- 0 until N) yield {\n if (i % 2 == 0) i + 2\n else i\n }\n }.mkString(\" \")\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "object APerfectPermutation extends App {\n import scala.io.StdIn._\n\n val n = readInt()\n\n val ans =\n if (n % 2 == 0)\n (1 to n).map(i => if (i % 2 == 0) i - 1 else i + 1)\n else\n IndexedSeq(-1)\n\n println(ans.mkString(\" \"))\n}\n"}, {"source_code": "object test5 extends App {\n val n=readLine.toInt\n if(n%2==1)\n \tprintln(-1)\n else\n {\n val arr=new Array[Int](n)\n for(i<-0 until n) arr(i)=i+1\n for(i<-0 until n by 2) \n {\n \tval tmp=arr(i)\n \tarr(i)=arr(i+1)\n \tarr(i+1)=tmp\n }\n\n println(arr.mkString(\" \"))\n }\n} \n"}, {"source_code": "object test5 extends App {\n val n=readLine.toInt\n if(n%2==1)\n \tprintln(-1)\n else\n {\n val arr=new Array[Int](n)\n for(i<-0 until n by 2) \n {\n \tarr(i)=i+2\n \tarr(i+1)=i+1\n }\n\n println(arr.mkString(\" \"))\n }\n} \n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n= readInt()\n if (n % 2 == 0) {\n val a = (1 to n).map{ \n case i: Int if i % 2 == 0 => i - 1\n case i: Int if i % 2 == 1 => i + 1\n }\n println(a.mkString(\" \"))\n } else println(\"-1\")\n }\n}"}, {"source_code": "import java.util\nimport scala.collection.mutable.ArrayBuffer\n\nobject Main {\n var tokenizer = new util.StringTokenizer(\"\")\n\n def readToken = {\n while (!tokenizer.hasMoreTokens) tokenizer = new util.StringTokenizer(readLine)\n tokenizer.nextToken\n }\n\n def readInt = readToken.toInt\n\n // >>>\n // >>>\n\n def main(args: Array[String]) {\n val n = readInt\n if (n % 2 == 1) {\n print(-1)\n } else {\n (1 to n).foreach(i => printf(\"%d \", if (i % 2 == 1) i + 1 else i - 1))\n }\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject PerfectPermutation {\n def main(args: Array[String]) = {\n val sc = new Scanner(System.in)\n val size = sc.nextInt()\n val res = perfectPermutation(size)\n res match {\n case None => println(-1)\n case Some(list) => list.foreach { i => print(s\"$i \") }\n }\n }\n\n def perfectPermutation(size: Int): Option[List[Int]] = {\n if (size % 2 == 1) None\n else Some((1 to size).map(i => if (i % 2 == 0) i - 1 else i + 1).toList)\n }\n}\n"}, {"source_code": "import java.util._\nimport scala.io._\nimport java.lang.System._\n\nobject Main {\n def main(args: Array[String]) {\n val sc = new Scanner(in)\n val n = sc.nextInt\n if (n % 2 == 1) println(-1)\n else{\n (1 to n) map {\n case i if i % 2 == 0 => i-1\n case i => i+1\n } foreach {\n e => print(e+\" \")\n }\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\nobject A extends App {\n val sc= new Scanner(System.in)\n val n = sc.nextInt\n if (n % 2 == 0) {\n println((1 to n).map{x => x + (x % 2) * 2 - 1}.mkString(\" \"))\n } else {\n println(-1)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject A233 {\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n println(n match {\n case x if x % 2 != 0 => -1\n case x => (1 to n).grouped(2). map(_.reverse).flatten.mkString(\" \")\n })\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n if (n % 2 == 1)\n println(\"-1\")\n else\n println(Range(1, n + 1).map{i =>\n if (i % 2 == 0) i + 1\n else i - 1\n }.mkString(\" \"))\n}"}, {"source_code": "object test5 extends App {\n val n=readLine.toInt\n if(n==1)\n \tprintln(-1)\n else\n {\n val arr=new Array[Int](n)\n for(i<-0 until n) arr(i)=i\n arr(0)=n\n println(arr.mkString(\" \"))\n }\n} \n"}], "src_uid": "204ba74195a384c59fb1357bdd71e16c"} {"source_code": "import scala.io.StdIn._\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n def go(n: Int, lower: Int, upper: Int): (Int, Int) = {\n if (n == 0) {\n (lower, upper)\n } else {\n val Array(change, div) = readLine.split(\" \").map(_.toInt)\n if (div == 1) go(n - 1, Math.max(lower + change, 1900 + change), upper + change)\n else go(n - 1, lower + change, Math.min(upper + change, 1899 + change))\n }\n }\n val (lower, upper) = go(readInt, -200000000, 200000000)\n println(if (lower > upper) \"Impossible\" else if (upper > 100000000) \"Infinity\" else upper)\n }\n}\n", "positive_code": [{"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val cs, ds = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val Array(c, d) = readInts(2)\n cs(i) = c\n ds(i) = d\n }\n\n if (ds.forall(_ == 1)) println(\"Infinity\")\n else {\n\n var max: Long = if (ds.last == 2) 1899L else Int.MaxValue\n var min: Long = if (ds.last == 2) Int.MinValue else 1900L\n var ok = true\n\n for (i <- n - 2 to 0 by -1) {\n if (ds(i) == 2) {\n max = Math.min(max - cs(i), 1899L)\n min = min - cs(i)\n } else {\n max = max - cs(i)\n min = Math.max(min - cs(i), 1900L)\n }\n if (min > max) ok = false\n }\n\n for (i <- 0 until n) max += cs(i)\n\n if (ok) println(max)\n else println(\"Impossible\")\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n def go(n: Int, lower: Int, upper: Int): (Int, Int) = {\n if (n == 0) {\n (lower, upper)\n } else {\n val Array(change, div) = readLine.split(\" \").map(_.toInt)\n if (div == 1) go(n - 1, Math.max(lower + change, 1900 + change), upper + change)\n else go(n - 1, lower + change, Math.min(upper + change, 1899 + change))\n }\n }\n val (lower, upper) = go(readInt, -200000000, 200000000)\n println(if (lower > upper) \"Impossible\" else if (upper > 20000000) \"Infinity\" else upper)\n }\n}\n"}], "src_uid": "2a4c24341231cabad6021697f15d953a"} {"source_code": "\nobject B extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n// val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val n = in.nextInt()\n\n n.times {\n val item = in.nextInt()\n val col = in.nextInt()\n\n var ans = 0L\n\n if (item <= col) {\n val r = (item - 1).toLong\n ans = ans + ((r * (r + 1)) / 2)\n } else if (item > col) {\n val r2 = col.toLong\n ans = ans + ((r2 * (r2 + 1)) / 2)\n }\n\n if (item <= col) {\n ans = ans + 1\n }\n\n println(ans)\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n\n val t = readInt()\n 1 to t foreach { _ =>\n val Array(n, r) = readLine().split(\" \").map(_.toInt)\n\n val answer =\n if (n <= r) {\n (n - 1).toLong * (n) / 2 + 1\n } else {\n r.toLong * (r + 1) / 2\n }\n println(answer)\n }\n}\n"}], "negative_code": [{"source_code": "\nobject B extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n// val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val n = in.nextInt()\n\n n.times {\n val item = in.nextInt()\n val col = in.nextInt()\n\n var ans = 0L\n\n if (item < col) {\n val r = (item - 1).toLong\n ans = ans + ((r * (r + 1)) / 2)\n } else if (item > col) {\n val r2 = col.toLong\n ans = ans + ((r2 * (r2 + 1)) / 2)\n }\n\n if (item <= col) {\n ans = ans + 1\n }\n\n println(ans)\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}], "src_uid": "eb3d8259ca598c3c455ddfdbe433cb78"} {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\r\n val anm = Array.fill(n)(readLine().toCharArray)\r\n\r\n val ans = (0 until n).foldLeft((0, 0), (0, 0)) { case ((r, w), i) =>\r\n (0 until m).foldLeft(r, w) { case ((r, w), j) =>\r\n anm(i)(j) match {\r\n case 'R' => if ((i + j) % 2 == 0) ((1, r._2), w) else ((r._1, 1), w)\r\n case 'W' => if ((i + j) % 2 == 0) (r, (1, w._2)) else (r, (w._1, 1))\r\n case _ => (r, w)\r\n }\r\n }\r\n }\r\n\r\n ans match {\r\n case ((0 | 1, 0), (0, 0 | 1)) =>\r\n println(\"YES\")\r\n (0 until n).foreach { i =>\r\n val l = (0 until m).map(j => if ((i + j) % 2 == 0) 'R' else 'W')\r\n println(l.mkString(\"\"))\r\n }\r\n case ((0, 0 | 1), (0 | 1, 0)) =>\r\n println(\"YES\")\r\n (0 until n).foreach { i =>\r\n val l = (0 until m).map(j => if ((i + j) % 2 == 0) 'W' else 'R')\r\n println(l.mkString(\"\"))\r\n }\r\n case _ => println(\"NO\")\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\r\n val anm = Array.fill(n)(readLine().toCharArray)\r\n\r\n val ans = anm.zipWithIndex\r\n .foldLeft[(Boolean, Option[Int])]((true, None)) {\r\n case (state @ (true, _), (am, i)) =>\r\n am.zipWithIndex.foldLeft(state) {\r\n case ((true, t), (c @ ('R' | 'W'), j)) =>\r\n val e = (i + j + c) % 2\r\n (t.getOrElse(e) == e, Some(e))\r\n case (state, _) => state\r\n }\r\n case (state, _) => state\r\n }\r\n\r\n ans match {\r\n case (true, t) =>\r\n println(\"YES\")\r\n (0 until n).foreach { i =>\r\n val l = (0 until m).map(j => if ((i + j) % 2 == t.getOrElse(0)) 'R' else 'W')\r\n println(l.mkString(\"\"))\r\n }\r\n case _ => println(\"NO\")\r\n }\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\r\n val anm = Array.fill(n)(readLine().toCharArray)\r\n\r\n val ans = (0 until n).foldLeft((0, 0), (0, 0)) { case ((r, w), i) =>\r\n (0 until m).foldLeft(r, w) { case ((r, w), j) =>\r\n anm(i)(j) match {\r\n case 'R' => if ((i + j) % 2 == 0) ((1, r._2), w) else ((r._1, 1), w)\r\n case 'W' => if ((i + j) % 2 == 0) (r, (1, w._2)) else (r, (w._1, 1))\r\n case _ => (r, w)\r\n }\r\n }\r\n }\r\n\r\n ans match {\r\n case ((1, 0), (0, 1)) =>\r\n println(\"YES\")\r\n (0 until n).foreach { i =>\r\n val l = (0 until m).map(j => if ((i + j) % 2 == 0) 'R' else 'W')\r\n println(l.mkString(\"\"))\r\n }\r\n case ((0, 1), (1, 0)) =>\r\n println(\"YES\")\r\n (0 until n).foreach { i =>\r\n val l = (0 until m).map(j => if ((i + j) % 2 == 0) 'W' else 'R')\r\n println(l.mkString(\"\"))\r\n }\r\n case _ => println(\"NO\")\r\n }\r\n }\r\n}\r\n"}, {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\r\n val anm = Array.fill(n)(readLine().toCharArray)\r\n\r\n val ans = anm.zipWithIndex\r\n .foldLeft[(Boolean, Option[Int], Option[Int])]((true, None, None)) {\r\n case (state @ (true, _, _), (am, i)) =>\r\n am.zipWithIndex.foldLeft(state) {\r\n case ((_, None, None), ('R', j)) => (true, Some((i + j) % 2), Some((i + j + 1) % 2))\r\n case ((_, None, None), ('W', j)) => (true, Some((i + j + 1) % 2), Some((i + j) % 2))\r\n case ((_, Some(r), _), ('R', j)) if (i + j) % 2 != r => (false, None, None)\r\n case ((_, _, Some(w)), ('W', j)) if (i + j) % 2 != w => (false, None, None)\r\n case (state, _) => state\r\n }\r\n case (state, _) => state\r\n }\r\n\r\n ans match {\r\n case (true, Some(r), Some(w)) =>\r\n println(\"YES\")\r\n (0 until n).foreach { i =>\r\n val l = (0 until m).map(j => if ((i + j) % 2 == r) 'R' else 'W')\r\n println(l.mkString(\"\"))\r\n }\r\n case _ => println(\"NO\")\r\n }\r\n }\r\n}\r\n"}], "src_uid": "12f35743f482b68e3156a45d6ac5bb14"} {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nimport scala.annotation.tailrec\n\nobject C_Treasure {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val str = scanner.next()\n\n def balanceChecker (x: List[Char], level : Int = 0) = {\n @tailrec\n def inner (x: List[Char], level : Int, acc : List[Int]) : List[Int] = {\n x match {\n case '(' :: tail => inner(tail, level + 1, level + 1 :: acc)\n case ')' :: tail => inner(tail, level - 1, level - 1 :: acc)\n case _ :: tail => inner(tail, level, level :: acc)\n case Nil => acc.reverse\n }\n }\n inner(x, level, Nil)\n }\n\n @tailrec def zeroFixer (l : List[Int], acc: Int = 0, accList : List[Int] = Nil) : List[Int] = {\n l match {\n case x :: Nil => (acc + x :: accList).reverse\n case x :: tail => zeroFixer(tail, acc + x - 1, 1 :: accList)\n case Nil => accList.reverse\n }\n }\n\n @tailrec def stringFiller (hashes: List[Int], str: List[Char], acc : List[Char] = Nil) : List[Char] = {\n str match {\n case '#' :: tail => stringFiller(hashes.tail, tail, (\")\" * hashes.head).toList ::: acc)\n case x :: tail => stringFiller(hashes, tail, x :: acc)\n case Nil => acc.reverse\n }\n }\n\n val chars = str.toList\n val charRanks = balanceChecker(chars)\n\n val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)\n val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)\n val lastItem = charRanks.last - hashRankDiffButLast.sum\n\n val hashRankDiffFixed = zeroFixer(hashRankDiffButLast :+ lastItem)\n val strFilledValidation = balanceChecker(stringFiller(hashRankDiffFixed, chars))\n\n\n /*println(chars)\n println(charRanks)\n println(hashRankDiffFixed)\n println(strFilledValidation)\n */\n\n if (hashRankDiffFixed.exists(_ <= 0) || strFilledValidation.last != 0 || strFilledValidation.exists(_ < 0)) {\n out.println(-1)\n } else for (x <- hashRankDiffFixed) {\n out.println(x)\n }\n }\n}\n", "positive_code": [{"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val s = readLine\n\n var cntsAdd = 0\n var cntOpen = 0\n var cntClose = 0\n var bad = false\n var lastAdd = 0\n\n val lastHash = s.lastIndexOf('#')\n val hashCnt = s.count(_ == '#')\n val openCnt = s.count(_ == '(')\n val closeCnt = s.count(_ == ')')\n \n for (i <- s.indices) s(i) match {\n case '(' =>\n cntOpen += 1\n case ')' =>\n cntClose += 1\n if (cntClose > cntOpen) bad = true\n case '#' =>\n lastAdd = if (i == lastHash) math.max(1, openCnt - closeCnt - cntsAdd) else 1\n cntsAdd += lastAdd\n cntClose += lastAdd\n if (cntClose > cntOpen) bad = true\n }\n\n if (bad) println(-1)\n else {\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n print(\"1\\n\" * (hashCnt - 1))\n println(lastAdd)\n Console.flush\n }\n}"}, {"source_code": "object Main extends App {\n\n val s = readLine.split(\"\").filter(_ != \"\")\n val total = s.size\n val open = s.count(_ == \"(\")\n val close = s.count(_ == \")\")\n val hashes = total - (open + close)\n\n if((open - close) < hashes) {\n println(\"-1\")\n System.exit(0)\n }\n\n val init = (0, 0, List[Int]())\n val (sum, _, steps) = s.foldLeft(init)({\n case ((sumAcc, hashesAcc, stepsAcc), i) => \n i match {\n case \"(\" => (sumAcc + 1, hashesAcc, stepsAcc)\n case \")\" =>\n if(sumAcc == 0) {\n println(\"-1\")\n System.exit(0)\n (sumAcc, hashesAcc, stepsAcc)\n } else {\n (sumAcc-1, hashesAcc, stepsAcc)\n }\n case \"#\" =>\n if(sumAcc == 0) {\n println(\"-1\")\n System.exit(0)\n (sumAcc, hashesAcc, stepsAcc)\n } else if(hashesAcc == hashes - 1) {\n val add = (open - close) - (hashes - 1)\n if(sumAcc < add) {\n println(\"-1\")\n System.exit(0)\n (sumAcc, hashesAcc, stepsAcc)\n } else {\n (sumAcc - add, hashesAcc + 1, add :: stepsAcc)\n }\n } else {\n (sumAcc - 1, hashesAcc + 1, 1 :: stepsAcc)\n }\n }\n })\n\n if(sum == 0) {\n steps.reverse foreach println\n } else {\n println(\"-1\")\n }\n\n}"}, {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nobject C_Treasure {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val str = scanner.next()\n\n def balanceChecker (x: List[Char], b : Int) : List[Int] = {\n x match {\n case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)\n case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)\n case _ :: tail => b :: balanceChecker(tail, b)\n case Nil => List.empty\n }\n }\n\n def zeroFixer (l : List[Int], acc: Int) : List[Int] = {\n l match {\n case x :: Nil => acc + x :: Nil\n case x :: tail => 1 :: zeroFixer(tail, acc + x - 1)\n case Nil => Nil\n }\n }\n\n def stringFiller (hashes: List[Int], str: List[Char]) : List[Char] = {\n str match {\n case '#' :: tail => (\")\" * hashes.head).toCharArray.toList ::: stringFiller(hashes.tail, tail)\n case x :: tail => x :: stringFiller(hashes, tail)\n case Nil => Nil\n }\n }\n\n val chars = str.toCharArray.toList\n val charRanks = balanceChecker(chars, 0)\n\n val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)\n val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)\n val lastItem = charRanks.last - hashRankDiffButLast.sum\n\n if (hashRanks.last < charRanks.last) {\n out.println(-1)\n return\n }\n\n val hashRankDiffFull = hashRankDiffButLast :+ lastItem\n val hashRankDiffFixed = zeroFixer(hashRankDiffFull, 0)\n val charFilled = stringFiller(hashRankDiffFixed, chars)\n val strFilledValidation = balanceChecker(charFilled, 0)\n\n\n /*println(chars)\n println(charRanks)\n println(hashRankDiffFull)\n println(hashRankDiffFixed)\n println(charFilled.mkString)\n println(strFilledValidation)\n */\n\n if (hashRankDiffFixed.exists(_ <= 0) || strFilledValidation.last != 0 || strFilledValidation.exists(_ < 0)) {\n out.println(-1)\n } else for (x <- hashRankDiffFixed) {\n out.println(x)\n }\n }\n}\n"}, {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nimport scala.annotation.tailrec\n\nobject C_Treasure {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val str = scanner.next()\n\n def balanceChecker (x: List[Char], level : Int) : List[Int] = {\n @tailrec\n def inner (x: List[Char], level : Int, acc : List[Int] = Nil) : List[Int] = {\n x match {\n case '(' :: tail => inner(tail, level + 1, level + 1 :: acc)\n case ')' :: tail => inner(tail, level - 1, level - 1 :: acc)\n case _ :: tail => inner(tail, level, level :: acc)\n case Nil => acc.reverse\n }\n }\n inner(x, level, Nil)\n }\n\n @tailrec def zeroFixer (l : List[Int], acc: Int, accList : List[Int] = Nil) : List[Int] = {\n l match {\n case x :: Nil => (acc + x :: accList).reverse\n case x :: tail => zeroFixer(tail, acc + x - 1, 1 :: accList)\n case Nil => accList.reverse\n }\n }\n\n @tailrec def stringFiller (hashes: List[Int], str: List[Char], acc : List[Char] = Nil) : List[Char] = {\n str match {\n case '#' :: tail => stringFiller(hashes.tail, tail, (\")\" * hashes.head).toCharArray.toList ::: acc)\n case x :: tail => stringFiller(hashes, tail, x :: acc)\n case Nil => acc.reverse\n }\n }\n\n val chars = str.toCharArray.toList\n val charRanks = balanceChecker(chars, 0)\n\n val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)\n val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)\n val lastItem = charRanks.last - hashRankDiffButLast.sum\n\n if (hashRanks.last < charRanks.last) {\n out.println(-1)\n return\n }\n\n val hashRankDiffFull = hashRankDiffButLast :+ lastItem\n val hashRankDiffFixed = zeroFixer(hashRankDiffFull, 0)\n val charFilled = stringFiller(hashRankDiffFixed, chars)\n val strFilledValidation = balanceChecker(charFilled, 0)\n\n\n /*println(chars)\n println(charRanks)\n println(hashRankDiffFull)\n println(hashRankDiffFixed)\n println(charFilled.mkString)\n println(strFilledValidation)\n */\n\n if (hashRankDiffFixed.exists(_ <= 0) || strFilledValidation.last != 0 || strFilledValidation.exists(_ < 0)) {\n out.println(-1)\n } else for (x <- hashRankDiffFixed) {\n out.println(x)\n }\n }\n}\n"}, {"source_code": "object Solution extends App {\n def check(str: String) = {\n var open = 0\n str.foldLeft(0) {\n case (-1, el) => -1\n case (x, ')') => x - 1\n case (x, '(') => x + 1\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val r = str.lastIndexOf(\"#\")\n val first = str.take(r).replace('#', ')')\n val t = check(first)\n val open = str.count(_ == '(')\n if (t < 1)\n println(-1)\n else {\n val count = str.count(_ == '#')\n val nStr = first + (\")\" * Math.max(1, 2 * open - str.length + 1)) + str.drop(r + 1)\n if (check(nStr) == 0) {\n println((1 to count - 1).map(_ => 1).mkString(\"\\n\"))\n println(2 * open - str.length + 1)\n } else {\n println(-1)\n }\n }\n}"}], "negative_code": [{"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nobject C_Treasure {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val str = scanner.next()\n\n if (str.startsWith(\"#\") || str.endsWith(\"(\")) {\n out.println(\"-1\")\n return\n }\n\n def balanceChecker (x: List[Char], b : Int) : List[Int] = {\n x match {\n case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)\n case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)\n case _ :: tail => b :: balanceChecker(tail, b)\n case Nil => List.empty\n }\n }\n\n def zeroFixer (l : List[Int], acc: Int) : List[Int] = {\n l match {\n case x :: Nil => acc + x :: Nil\n case x :: tail => 1 :: zeroFixer(tail, acc + x - 1)\n case Nil => Nil\n }\n }\n\n val chars = str.toCharArray.toList\n val charRanks = balanceChecker(chars, 0)\n\n val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)\n val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)\n val lastItem = charRanks.last - hashRankDiffButLast.sum\n\n if (hashRanks.last < charRanks.last) {\n out.println(-1)\n return\n }\n\n val hashRankDiffFull = hashRankDiffButLast :+ lastItem\n val hashRankDiffFixed = zeroFixer(hashRankDiffFull, 0)\n\n\n /*println(chars)\n println(charRanks)\n println(hashRankDiffFull)\n println(hashRankDiffFixed)\n */\n\n if (hashRankDiffFull.exists(_ < 0) || hashRankDiffFixed.exists(_ <= 0)) {\n out.println(-1)\n } else for (x <- hashRankDiffFixed) {\n out.println(x)\n }\n }\n}\n"}, {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nobject C_Treasure {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val str = scanner.next()\n\n if (str.startsWith(\"#\") || str.endsWith(\"(\")) {\n out.println(\"-1\")\n return\n }\n\n def balanceChecker (x: List[Char], b : Int) : List[Int] = {\n x match {\n case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)\n case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)\n case _ :: tail => b :: balanceChecker(tail, b)\n case Nil => List.empty\n }\n }\n\n val chars = str.toCharArray.toList\n val charRanks = balanceChecker(chars, 0)\n\n val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)\n var hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)\n var lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum\n\n if (hashRanks(hashRanks.size - 1) < charRanks(charRanks.size - 1)) {\n out.println(-1)\n return\n }\n\n if (hashRankDiffButLast.count(_ == 0) < lastItem) {\n lastItem -= hashRankDiffButLast.count(_ == 0)\n hashRankDiffButLast = hashRankDiffButLast.map(x => if (x == 0) 1 else x)\n }\n\n val hashRankDiffFull = hashRankDiffButLast :+ lastItem\n\n /*println(chars)\n println(charRanks)\n println(hashRankDiffFull)\n */\n\n if (hashRankDiffFull.exists(_ <= 0)) {\n out.println(-1)\n } else for (x <- hashRankDiffFull) {\n out.println(x)\n }\n }\n}\n"}, {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nobject C_Treasure {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val str = scanner.next()\n\n if (str.startsWith(\"#\")) {\n out.println(\"-1\")\n return\n }\n\n def balanceChecker (x: List[Char], b : Int) : List[Int] = {\n x match {\n case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)\n case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)\n case '#' :: tail => b :: balanceChecker(tail, b)\n case Nil => List.empty\n }\n }\n\n val chars = str.toCharArray.toList\n val charRanks = balanceChecker(chars, 0)\n\n val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)\n var hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)\n var lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum\n\n if (hashRankDiffButLast.count(_ == 0) < lastItem) {\n lastItem -= hashRankDiffButLast.count(_ == 0)\n hashRankDiffButLast = hashRankDiffButLast.map(x => if (x == 0) 1 else x)\n }\n\n val hashRankDiffFull = hashRankDiffButLast :+ lastItem\n\n /*println(chars)\n println(charRanks)\n println(hashRankDiffFull)\n */\n\n if (hashRankDiffFull.exists(_ <= 0)) {\n out.println(-1)\n } else for (x <- hashRankDiffFull) {\n out.println(x)\n }\n }\n}\n"}, {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nobject C_Treasure {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val str = scanner.next()\n\n def balanceChecker (x: List[Char], b : Int) : List[Int] = {\n x match {\n case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)\n case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)\n case '#' :: tail => b :: balanceChecker(tail, b)\n case Nil => List.empty\n }\n }\n\n val chars = str.toCharArray.toList\n val charRanks = balanceChecker(chars, 0)\n\n val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)\n val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)\n val lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum\n val hashRankDiffFull = hashRankDiffButLast :+ lastItem\n\n if (hashRankDiffFull.exists(_ <= 0)) {\n out.println(-1)\n } else for (x <- hashRankDiffFull) {\n out.println(x)\n }\n }\n}\n"}, {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nobject C_Treasure {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val str = scanner.next()\n\n val str_adapted = str.replaceAll(\"##\", \"#(#)\")\n\n def balanceChecker (x: List[Char], b : Int) : List[Int] = {\n x match {\n case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)\n case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)\n case '#' :: tail => b :: balanceChecker(tail, b)\n case Nil => List.empty\n }\n }\n\n val chars = str_adapted.toCharArray.toList\n val charRanks = balanceChecker(chars, 0)\n\n val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)\n val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)\n val lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum\n val hashRankDiffFull = hashRankDiffButLast :+ lastItem\n\n /*\n println(chars)\n println(charRanks)\n println(hashRankDiffFull)\n */\n\n if (hashRankDiffFull.exists(_ <= 0)) {\n out.println(-1)\n } else for (x <- hashRankDiffFull) {\n out.println(x)\n }\n }\n}\n"}, {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nobject C_Treasure {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val str = scanner.next()\n\n if (str.startsWith(\"#\") || str.endsWith(\"(\")) {\n out.println(\"-1\")\n return\n }\n\n def balanceChecker (x: List[Char], b : Int) : List[Int] = {\n x match {\n case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)\n case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)\n case _ :: tail => b :: balanceChecker(tail, b)\n case Nil => List.empty\n }\n }\n\n def zeroFixer (l : List[Int], acc: Int) : List[Int] = {\n l match {\n case x :: Nil => acc + x :: Nil\n case x :: tail => 1 :: zeroFixer(tail, acc + x - 1)\n case Nil => Nil\n }\n }\n\n val chars = str.toCharArray.toList\n val charRanks = balanceChecker(chars, 0)\n\n val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)\n val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)\n val lastItem = charRanks.last - hashRankDiffButLast.sum\n\n if (hashRanks.last < charRanks.last) {\n out.println(-1)\n return\n }\n\n /*println(chars)\n println(charRanks)\n println(hashRankDiffButLast :+ lastItem)\n */\n\n val hashRankDiffFull = zeroFixer(hashRankDiffButLast :+ lastItem, 0)\n\n if (hashRankDiffFull.exists(_ <= 0)) {\n out.println(-1)\n } else for (x <- hashRankDiffFull) {\n out.println(x)\n }\n }\n}\n"}, {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nobject C_Treasure {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val str = scanner.next()\n\n if (str.startsWith(\"#\") || str.endsWith(\"(\")) {\n out.println(\"-1\")\n return\n }\n\n def balanceChecker (x: List[Char], b : Int) : List[Int] = {\n x match {\n case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)\n case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)\n case _ :: tail => b :: balanceChecker(tail, b)\n case Nil => List.empty\n }\n }\n\n val chars = str.toCharArray.toList\n val charRanks = balanceChecker(chars, 0)\n\n val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)\n var hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)\n var lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum\n\n if (hashRanks(hashRanks.size - 1) < charRanks(charRanks.size - 1)) {\n out.println(-1)\n return\n }\n\n if (hashRankDiffButLast.count(_ == 0) <= lastItem) {\n lastItem -= hashRankDiffButLast.count(_ == 0)\n hashRankDiffButLast = hashRankDiffButLast.map(x => if (x == 0) 1 else x)\n }\n\n val hashRankDiffFull = hashRankDiffButLast :+ lastItem\n\n /*println(chars)\n println(charRanks)\n println(hashRankDiffFull)\n */\n\n if (hashRankDiffFull.exists(_ <= 0)) {\n out.println(-1)\n } else for (x <- hashRankDiffFull) {\n out.println(x)\n }\n }\n}\n"}, {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nobject C_Treasure {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val str = scanner.next()\n\n if (str.startsWith(\"#\")) {\n out.println(\"-1\")\n return\n }\n\n val str_adapted = str.replaceAll(\"##\", \"#(#)\")\n\n def balanceChecker (x: List[Char], b : Int) : List[Int] = {\n x match {\n case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)\n case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)\n case '#' :: tail => b :: balanceChecker(tail, b)\n case Nil => List.empty\n }\n }\n\n val chars = str_adapted.toCharArray.toList\n val charRanks = balanceChecker(chars, 0)\n\n val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)\n val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)\n val lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum\n val hashRankDiffFull = hashRankDiffButLast :+ lastItem\n\n /*\n println(chars)\n println(charRanks)\n println(hashRankDiffFull)\n */\n\n if (hashRankDiffFull.exists(_ <= 0)) {\n out.println(-1)\n } else for (x <- hashRankDiffFull) {\n out.println(x)\n }\n }\n}\n"}, {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nobject C_Treasure {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val str = scanner.next()\n\n if (str.startsWith(\"#\")) {\n out.println(\"-1\")\n return\n }\n\n def balanceChecker (x: List[Char], b : Int) : List[Int] = {\n x match {\n case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)\n case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)\n case _ :: tail => b :: balanceChecker(tail, b)\n case Nil => List.empty\n }\n }\n\n val chars = str.toCharArray.toList\n val charRanks = balanceChecker(chars, 0)\n\n val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)\n var hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)\n var lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum\n\n if (hashRanks(hashRanks.size - 1) < charRanks(charRanks.size - 1)) {\n out.println(-1)\n return\n }\n\n if (hashRankDiffButLast.count(_ == 0) < lastItem) {\n lastItem -= hashRankDiffButLast.count(_ == 0)\n hashRankDiffButLast = hashRankDiffButLast.map(x => if (x == 0) 1 else x)\n }\n\n val hashRankDiffFull = hashRankDiffButLast :+ lastItem\n\n /*println(chars)\n println(charRanks)\n println(hashRankDiffFull)\n */\n\n if (hashRankDiffFull.exists(_ <= 0)) {\n out.println(-1)\n } else for (x <- hashRankDiffFull) {\n out.println(x)\n }\n }\n}\n"}, {"source_code": "object Solution extends App {\n def check(str: String) = {\n var open = 0\n str.foldLeft(0) {\n case (-1, el) => -1\n case (x, ')') => x - 1\n case (x, '(') => x + 1\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val r = str.lastIndexOf(\"#\")\n val first = str.take(r).replace('#', ')')\n val t = check(first)\n val open = str.count(_ == '(')\n if (t == -1)\n println(-1)\n else {\n val count = str.count(_ == '#')\n val nStr = first + (\")\" * (2 * open - str.length + 1)) + str.drop(r + 1)\n if (check(nStr) == 0) {\n println((1 to count - 1).map(_ => 1).mkString(\"\\n\"))\n println(2 * open - str.length + 1)\n } else {\n println(-1)\n }\n }\n}"}, {"source_code": "object Solution extends App {\n def check(str: String) = {\n var open = 0\n str.foldLeft(0) {\n case (-1, el) => -1\n case (x, ')') => x - 1\n case (x, '(') => x + 1\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val r = str.lastIndexOf(\"#\")\n val first = str.take(r).replace('#', ')')\n val t = check(first)\n val open = str.count(_ == '(')\n if (t < 1)\n println(-1)\n else {\n val count = str.count(_ == '#')\n val nStr = first + (\")\" * (2 * open - str.length + 1)) + str.drop(r + 1)\n if (check(nStr) == 0) {\n println((1 to count - 1).map(_ => 1).mkString(\"\\n\"))\n println(2 * open - str.length + 1)\n } else {\n println(-1)\n }\n }\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val s = readLine\n\n var cntsAdd = 0\n var cntOpen = 0\n var cntClose = 0\n var bad = false\n var lastAdd = 0\n\n val lastHash = s.lastIndexOf('#')\n val hashCnt = s.count(_ == '#')\n val openCnt = s.count(_ == '(')\n val closeCnt = s.count(_ == ')')\n \n for (i <- s.indices) s(i) match {\n case '(' =>\n cntOpen += 1\n case ')' =>\n cntClose += 1\n if (cntClose > cntOpen) bad = true\n case '#' =>\n lastAdd = if (i == lastHash) openCnt - closeCnt - hashCnt + 1 else 1\n cntsAdd += lastAdd\n cntClose += lastAdd\n if (cntClose > cntOpen) bad = true\n }\n\n if (bad || cntClose > cntOpen || lastAdd == 0) println(-1)\n else {\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n print(\"1\\n\" * (hashCnt - 1))\n println(lastAdd)\n Console.flush\n }\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val s = readLine\n\n var cntsAdd = 0\n var cntOpen = 0\n var cntClose = 0\n var bad = false\n\n for (c <- s) c match {\n case '(' =>\n cntOpen += 1\n case ')' =>\n cntClose += 1\n if (cntClose > cntOpen) bad = true\n case '#' =>\n cntsAdd += 1\n cntClose += 1\n if (cntClose > cntOpen) bad = true\n }\n\n if (bad) println(-1)\n else {\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n print(\"1\\n\" * (cntsAdd - 1))\n if (cntsAdd > 0) println(cntOpen - cntClose + 1)\n Console.flush\n }\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val s = readLine\n\n var cntsAdd = 0\n var cntOpen = 0\n var cntClose = 0\n var bad = false\n var lastAdd = 0\n\n val lastHash = s.lastIndexOf('#')\n val hashCnt = s.count(_ == '#')\n val openCnt = s.count(_ == '(')\n val closeCnt = s.count(_ == ')')\n \n for (i <- s.indices) s(i) match {\n case '(' =>\n cntOpen += 1\n case ')' =>\n cntClose += 1\n if (cntClose > cntOpen) bad = true\n case '#' =>\n lastAdd = if (i == lastHash) math.max(1, openCnt - closeCnt - cntsAdd + 1) else 1\n cntsAdd += lastAdd\n cntClose += lastAdd\n if (cntClose > cntOpen) bad = true\n }\n\n if (bad) println(-1)\n else {\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n print(\"1\\n\" * (hashCnt - 1))\n println(lastAdd)\n Console.flush\n }\n}"}], "src_uid": "0a30830361b26838b192d7de1efcdd2f"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\nobject D1 {\n def solve(in: Input, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val arr = Array.fill(n)(in.nextInt())\n java.util.Arrays.sort(arr)\n for (i <- 1 until arr.length by 2) {\n val tmp = arr(i - 1)\n arr(i - 1) = arr(i)\n arr(i) = tmp\n }\n out.println((n - 1) / 2)\n out.println(arr.mkString(\" \"))\n }\n\n private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(\n (\"5\\n1 2 3 4 5\", \"2\\n2 1 4 3 5 \", \"Sample\"),\n (\"1\\n1\", \"0\\n1\", \"Size 1\"),\n (\"2\\n1 2\", \"0\\n2 1\", \"Size 2\"),\n (\"3\\n1 2 3\", \"1\\n2 1 3\", \"Size 3\"),\n (\"4\\n1 2 3 4\", \"1\\n2 1 4 3\", \"Size 4\"),\n )\n\n def main(args: Array[String]): Unit = {\n if (args.length == 0) {\n val input = new Input(new InputStreamReader(System.in))\n val output = new PrintWriter(System.out)\n solve(input, output)\n output.close()\n input.close()\n } else {\n for ((in, ans, name) <- makeTests()) {\n val input = new Input(new StringReader(in))\n val output = new StringWriter()\n val pwOutput = new PrintWriter(output)\n val t0 = System.nanoTime()\n solve(input, pwOutput)\n val time = System.nanoTime() - t0\n pwOutput.close()\n output.close()\n val result = output.toString\n if (ans.trim != result.trim) {\n throw new RuntimeException(s\"Test '$name': expected '$ans' found '$result'\")\n } else {\n println(s\"Test '$name' was solved in ${time / 1e9} seconds\")\n }\n }\n }\n }\n\n class Input(stream: Reader) extends Closeable {\n private[this] val reader = new BufferedReader(stream)\n private[this] var tokenizer = new StringTokenizer(reader.readLine())\n\n @tailrec\n final def nextToken(): String = if (tokenizer.hasMoreTokens) tokenizer.nextToken() else {\n tokenizer = new StringTokenizer(reader.readLine())\n nextToken()\n }\n\n def nextInt(): Int = nextToken().toInt\n def nextLong(): Long = nextToken().toLong\n def nextDouble(): Double = nextToken().toDouble\n\n override def close(): Unit = reader.close()\n }\n}\n", "positive_code": [{"source_code": "object D1 extends App {\n import scala.io.StdIn._\n\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt).sorted(Ordering.Int.reverse)\n\n val bn = Array.ofDim[Int](n)\n\n bn(0) = an(0)\n (1 until n).foreach {\n case i if i % 2 == 0 => bn(i) = an(i - 1)\n case i => bn(i) = an((n - 1) min (i + 1))\n }\n\n println((n - 1) / 2)\n println(bn.mkString(\" \"))\n}\n"}, {"source_code": "object D extends App {\n import scala.io.StdIn._\n\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt).sorted(Ordering.Int.reverse)\n\n if (n <= 2) {\n println(0)\n println(an.mkString(\" \"))\n } else {\n println((n - 1) / 2)\n\n val bn = Array.ofDim[Int](n)\n\n bn(0) = an(0)\n (1 until n).foreach {\n case i if i % 2 == 0 => bn(i) = an(i - 1)\n case i => bn(i) = an((n - 1) min (i + 1))\n }\n\n println(bn.mkString(\" \"))\n }\n}\n"}], "negative_code": [{"source_code": "object D extends App {\n import scala.io.StdIn._\n\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt).sorted(Ordering.Int.reverse)\n\n if (n <= 2) {\n println(n)\n println(an.mkString(\" \"))\n } else {\n println((n - 1) / 2)\n\n val bn = Array.ofDim[Int](n)\n\n bn(0) = an(0)\n (1 until n).foreach {\n case i if i % 2 == 0 => bn(i) = an(i - 1)\n case i => bn(i) = an((n - 1) min (i + 1))\n }\n\n println(bn.mkString(\" \"))\n }\n}\n"}], "src_uid": "bcd9439fbf6aedf6882612d5f7d6220f"} {"source_code": "object A extends App {\r\n\r\n lazy val Mod = 1000000007L\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val ans = (3 to 2 * n).foldLeft(1L)((f, i) => (f * i) % Mod)\r\n\r\n out.println(ans)\r\n }\r\n\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n def factorial(n: Long): Long = {\n var f = 1L\n for(i <- 3 to n.toInt)\n f = (f * i) % 1000000007\n f\n }\n\n (1 to readInt()).foreach(_ => {\n println(((factorial(2L*readLong()))))\n })\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(var social: Int, var cp: Int, var ind: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (social < that.social)\n return -1\n else if (social == that.social)\n return 0\n else\n return 1\n }\n }\n\n val mod = 1000000007\n var d = new Array[Long](100010)\n d(1) = 1\n for (i <- 2 to 100000) {\n d(i) = d(i-1) * (2*i-1).toLong\n d(i) %= mod\n d(i) *= (2*i).toLong\n d(i) %= mod\n }\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n writer.println(d(n))\n }\n writer.flush()\n}\n"}], "negative_code": [{"source_code": "object A extends App {\r\n\r\n lazy val Mod = 1000000007L\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val ans = (3 to n).foldLeft(1L)((f, i) => (f * i) % Mod)\r\n\r\n out.println(ans)\r\n }\r\n\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}], "src_uid": "19a2550af6a46308fd92c7a352f12a5f"} {"source_code": "object _810B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n val n, f = read[Int]\n\n val data = read[Seq, (Long, Long)](n) map {\n case (p, c) =>\n val sold = p min c\n val soldIfSale = 2*p min c\n (soldIfSale, sold, soldIfSale - sold)\n }\n\n val (sale, regular) = data.sortBy(_._3)(desc).splitAt(f)\n\n val ans = sale.sumWith(_._1) + regular.sumWith(_._2)\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "/**\n * @author tdx\n */\nobject Main {\n import scala.collection.mutable.ArrayBuffer\n import scala.io.StdIn._\n import scala.math._\n\n def parts(line : String) = {\n line.split(\" \").map(_.toInt)\n }\n\n def cost(pair: (Int, Int)) = min(pair._1, pair._2)\n\n def main(args: Array[String]): Unit = {\n val p = parts(readLine())\n val (n, f) = (p(0), p(1))\n val arr = ArrayBuffer[(Int, Int)]()\n\n for (_ <- 1 to n) {\n val p = parts(readLine())\n val (ki, li) = (p(0), p(1))\n arr.append((ki, li))\n }\n\n val sorted = arr.sortBy {\n case (ki, li) => -(cost(2*ki, li) - cost(ki, li))\n }\n\n val all = arr.foldLeft(0L)((total, pair) => total + cost(pair)) +\n sorted.take(f).foldLeft(0L)((total, pair) => total + cost((2 * pair._1, pair._2)) - cost(pair))\n\n println(all)\n }\n\n}\n"}, {"source_code": "object B extends App {\n import scala.io.Source\n\n val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(\" \").map(_.toLong))\n val Array(n, f) = input(0).map(_.toInt)\n val days = input.drop(1)\n def doublingDiff(a: Array[Long]): Long = a match {\n case Array(prod, cust) =>\n val normalSale = cust min prod\n val doubleSale = cust min (prod * 2)\n doubleSale - normalSale\n }\n val fSum = if (f >= (n / 2))\n -days.view.map(a => -doublingDiff(a)).sorted.take(f).sum\n else\n days.view.map(a => doublingDiff(a)).sorted.drop(n - f).sum\n val normSum = days.map(_.min).sum\n print(fSum + normSum)\n}"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, f) = readInts(2)\n case class Day(k: Long, l: Long)\n\n def sell(k: Long, l: Long) = {\n Math.min(k, l)\n }\n\n val days = Array.fill(n) {\n val Array(k, l) = readLongs(2)\n Day(k, l)\n }.sortBy {\n case Day(k, l) =>\n sell(2 * k, l) - sell(k, l)\n }.reverse\n\n val sale = days.take(f)\n val rest = days.drop(f)\n val res1 = sale.map {\n case Day(k, l) =>\n sell(2 * k, l)\n }.sum\n val res2 = rest.map {\n case Day(k, l) =>\n sell(k, l)\n }.sum\n\n println(res1 + res2)\n}\n"}], "negative_code": [{"source_code": "object B extends App {\n import scala.io.Source\n\n val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(\" \").map(_.toInt))\n val Array(n, f) = input(0)\n val days = input.drop(1)\n val sorted = days.sortBy{ case Array(prod, cust) =>\n val normalSale = cust min prod\n val doubleSale = cust min (prod * 2)\n -(doubleSale - normalSale)\n }\n\n val sumOne = sorted.take(f).map { case Array(prod, cust) =>\n cust min (prod * 2)\n }.sum\n\n val sumTwo = sorted.drop(f).map { case Array(prod, cust) =>\n cust min prod\n }.sum\n print(sumOne + sumTwo)\n}\n"}, {"source_code": "object B extends App {\n\n import scala.io.Source\n\n val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(\" \").map(_.toLong))\n val Array(n, f) = input(0).map(_.toInt)\n val days = input.drop(1)\n val normSum = days.map(_.min).sum\n if (f >= (n / 2)) {\n val fSumNeg = days.view.map{ case Array(prod, cust) =>\n val normalSale = cust min prod\n val doubleSale = cust min (prod * 2)\n -(doubleSale - normalSale)\n }.sorted.take(f).sum\n print(-fSumNeg + normSum)\n } else {\n val fSum = days.view.map{ case Array(prod, cust) =>\n val normalSale = cust min prod\n val doubleSale = cust min (prod * 2)\n doubleSale - normalSale\n }.sorted.drop(f).sum\n print(fSum + normSum)\n }\n}"}, {"source_code": "object _810B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n val n, f = read[Int]\n\n val data = read[Seq, (Int, Int)](n) map {\n case (p, c) =>\n val sold = p min c\n val soldIfSale = 2*p min c\n (soldIfSale, sold)\n }\n\n val (sale, regular) = data.sorted(desc[(Int, Int)]).splitAt(f)\n\n val ans = sale.sumWith(_._1) + regular.sumWith(_._2)\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "/**\n * @author tdx\n */\nobject Main {\n import scala.collection.mutable.ArrayBuffer\n import scala.io.StdIn._\n import scala.math._\n\n def parts(line : String) = {\n line.split(\" \").map(_.toInt)\n }\n\n def cost(pair: (Int, Int)) = min(pair._1, pair._2)\n\n def main(args: Array[String]): Unit = {\n val p = parts(readLine())\n val (n, f) = (p(0), p(1))\n val arr = ArrayBuffer[(Int, Int)]()\n\n for (_ <- 1 to n) {\n val p = parts(readLine())\n val (ki, li) = (p(0), p(1))\n arr.append((ki, li))\n }\n\n val sorted = arr.sortBy {\n case (ki, li) => -(cost(2*ki, li) - cost(ki, li))\n }\n\n val all = arr.foldLeft(0)((total, pair) => total + cost(pair)) +\n sorted.take(f).foldLeft(0)((total, pair) => total + cost((2 * pair._1, pair._2)) - cost(pair))\n\n println(all)\n }\n\n}\n"}], "src_uid": "c9b322a9138410a82e541179272eb6bf"} {"source_code": "//package codeforces.contests._1487\n\nobject MinimumTies {\n\n def main(args: Array[String]): Unit = {\n println({\n for (_ <- 1 to io.StdIn.readInt()) yield {\n val n = io.StdIn.readInt()\n\n val EachTeamWins = (n - 1) / 2\n\n val teamWins = Array.fill(n + 1)(0)\n\n def drawCheck(i: Int, j: Int): Boolean = n % 2 == 0 && (j - i) == n / 2\n\n {\n for {\n i <- 1 to n\n j <- i + 1 to n\n } yield {\n if (drawCheck(i, j)) 0\n else if (teamWins(i) < EachTeamWins) {\n teamWins(i) += 1\n 1\n } else if (teamWins(j) < EachTeamWins) {\n teamWins(j) += 1\n -1\n } else {\n 0\n }\n }\n }.mkString(\" \")\n }\n }.mkString(\"\\n\"))\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject C {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val games = Array.fill(n, n)(0)\n val scores = ArrayBuffer.empty[Int]\n for (i <- 0 until n) {\n var res = if (i % 2 == 0) 1 else -1\n for (j <- 0 until n) {\n if (i != j) {\n var r = 0\n if ((n % 2 == 1 || (i != n - j - 1))) {\n r = res\n res = -res\n }\n if (i < j) scores += r\n games(i)(j) = r\n }\n }\n }\n\n out.println(scores.mkString(\" \"))\n }\n\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n\n def nextInt = Integer.parseInt(nextToken)\n\n def nextLong = java.lang.Long.parseLong(nextToken)\n\n def nextBig = BigInt(nextToken)\n\n def nextInts(n: Int) = Array.fill(n) {\n nextInt\n }\n\n def nextLongs(n: Int) = Array.fill(n) {\n nextLong\n }\n\n def nextBigs(n: Int) = Array.fill(n) {\n nextBig\n }\n\n def nextLine = in.readLine\n }\n\n}\n"}, {"source_code": "\r\nobject C {\r\n import scala.io.{StdIn => in}\r\n\r\n def main(args: Array[String]): Unit = {\r\n val tests = in.readInt()\r\n (1 to tests).foreach { _ =>\r\n val n = in.readInt() - 1\r\n val wins = (0 until n/2).map(_ => 1) ++ (if (n % 2 == 0) Seq() else Seq(0)) ++ (0 until n/2).map(_ => -1)\r\n println((0 to n).map(i => wins.dropRight(i).mkString(\" \")).mkString(\" \"))\r\n }\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1487\n\nobject MinimumTies {\n\n def main(args: Array[String]): Unit = {\n println({\n for (_ <- 1 to io.StdIn.readInt()) yield {\n val n = io.StdIn.readInt()\n\n val EachTeamWins = (n - 1) / 2\n\n val teamWins = Array.fill(n + 1)(0)\n\n {\n for {\n i <- 1 to n\n j <- i + 1 to n\n } yield {\n if (teamWins(i) < EachTeamWins) {\n teamWins(i) += 1\n 1\n } else if (teamWins(j) < EachTeamWins) {\n teamWins(j) += 1\n -1\n } else {\n 0\n }\n }\n }.mkString(\" \")\n }\n }.mkString(\"\\n\"))\n }\n}\n"}], "src_uid": "a89c585ebd9608141399c813385c04c6"} {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val busSpeed = nextInt\n val manSpeed = nextInt\n val stations: Array[Int] = new Array[Int](n - 1)\n nextInt\n for (i <- 0 until n - 1) {\n stations(i) = nextInt\n }\n val x = nextInt\n val y = nextInt\n val processedStations = stations.map(X => solver(X, busSpeed, manSpeed, x, y)).zip(Stream from 2).sortWith(customComparator)\n out.println(processedStations(0)._2)\n }\n\n def customComparator(first: ((Double, Double), Int), second: ((Double, Double), Int)) =\n if (first._1._1 == second._1._1) first._1._2 < second._1._2 else first._1._1 < second._1._1\n\n def solver(station: Int, busSpeed: Int, manSpeed: Int, x: Int, y: Int): (Double, Double) = {\n (Math.sqrt(dist(station, 0, x, y)) * busSpeed + Math.abs(station) * manSpeed, dist(station, 0, x, y))\n }\n\n def dist(x: Double, y: Double, x1: Double, y1: Double): Double = {\n (x - x1) * (x - x1) + (y - y1) * (y - y1)\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n", "positive_code": [{"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var Array(n, vb, vs) = readLine.split(\" \").map(_.toDouble);\n var x = readLine.split(\" \").map(_.toDouble);\n var Array(xu, yu) = readLine.split(\" \").map(_.toDouble);\n for (i <- 1 until x.length - 1) {\n var tc = math.sqrt(math.pow(xu - x(i), 2) + math.pow(yu, 2)) / vs;\n var tn = (x(i + 1) - x(i)) / vb + math.sqrt(math.pow(xu - x(i + 1), 2) + math.pow(yu, 2)) / vs;\n if (tc < tn) {\n println(i + 1);\n return;\n }\n }\n println(x.length);\n }\n\n}"}, {"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nobject BusStop extends App {\n\n val s = new Scanner(System.in)\n\n import s._\n\n val n = nextInt()\n val (vb, vs) = (nextInt().toDouble, nextInt().toDouble)\n\n val stops = (0 until n).map { _ =>\n (nextInt().toDouble, 0.0)\n }.toArray\n\n val univ = (nextInt().toDouble, nextInt().toDouble)\n\n\n\n def dist(a: (Double, Double), b: (Double, Double)): Double = math.sqrt((a._1 - b._1) * (a._1 - b._1) + (a._2 - b._2) * (a._2 - b._2))\n\n var result = Integer.MAX_VALUE.toDouble\n val start = (0.0, 0.0)\n var stopNum = 1\n var sun = Integer.MAX_VALUE.toDouble\n\n stops.tail.zipWithIndex.map { case (stop, i) =>\n val d = dist(start, stop) / vb + dist(stop, univ) / vs\n val curs = dist(stop, univ)\n if (d <= result && curs < sun) {\n result = d\n stopNum = i + 2\n }\n }\n\n println(stopNum)\n\n}\n"}, {"source_code": "object P9B {\n import io.StdIn._\n import Math._\n\n def main(args:Array[String]) {\n val Array(n, vb, vs) = readLine.split(' ').map{_.toInt}\n val a = readLine.split(' ').map{_.toDouble}\n val Array(xu, yu) = readLine.split(' ').map{_.toDouble}\n println(1.to(a.size - 1).minBy{i => {\n val xs = xu - a(i)\n a(i) / vb + sqrt(xs * xs + yu * yu) / vs - i * 1e-6\n }} + 1)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, vb, vs) = in.next().split(' ').map(_.toInt)\n val xs = in.next().split(' ').map(_.toInt)\n val Array(xu, yu) = in.next().split(' ').map(_.toDouble)\n\n val res = xs.indices.tail.foldLeft(-1, 0d, 0d) {\n case ((-1, _, _), i) =>\n val dx: Double = xs(i) - xu\n (i + 1, xs(i).toDouble / vb + Math.sqrt(dx * dx + yu * yu) / vs, Math.abs(dx))\n case (acc@(sum, index, length), i) =>\n val dx: Double = xs(i) - xu\n val candidate = (i + 1, xs(i).toDouble / vb + Math.sqrt(dx * dx + yu * yu) / vs, Math.abs(dx))\n if (candidate._2 < acc._2 || (candidate._2 == acc._2 && candidate._3 < acc._3)) {\n candidate\n }\n else acc\n }\n\n println(res._1)\n\n\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, vb, vs) = in.next().split(' ').map(_.toInt)\n val xs = in.next().split(' ').map(_.toInt)\n val Array(xu, yu) = in.next().split(' ').map(_.toDouble)\n\n val res = xs.indices.tail.foldLeft(-1, 0d, 0d) {\n case ((-1, _, _), i) =>\n val dx: Double = xs(i) - xu\n (i + 1, xs(i).toDouble / vb + Math.sqrt(dx * dx + yu * yu) / vs, Math.abs(dx))\n case (acc@(sum, index, length), i) =>\n val dx: Double = xs(i) - xu\n val candidate = (i + 1, xs(i).toDouble / vb + Math.sqrt(dx * dx + yu * yu) / vs, Math.abs(dx))\n println(acc)\n println(candidate)\n if (candidate._2 < acc._2 || (candidate._2 == acc._2 && candidate._3 < acc._3)) {\n candidate\n }\n else acc\n }\n\n println(res._1)\n\n\n}"}, {"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nobject BusStop extends App {\n\n val s = new Scanner(System.in)\n\n import s._\n\n val n = nextInt()\n val (vb, vs) = (nextInt().toDouble, nextInt().toDouble)\n\n val stops = (0 until n).map { _ =>\n (nextInt().toDouble, 0.0)\n }.toArray\n\n val univ = (nextInt().toDouble, nextInt().toDouble)\n\n\n\n def dist(a: (Double, Double), b: (Double, Double)): Double = math.sqrt((a._1 - b._1) * (a._1 - b._1) + (a._2 - b._2) * (a._2 - b._2))\n\n var result = Integer.MAX_VALUE.toDouble\n val start = (0.0, 0.0)\n var stopNum = 1\n\n stops.tail.zipWithIndex.map { case (stop, i) =>\n val d = dist(start, stop) / vb + dist(stop, univ) / vs\n if (d < result) {\n result = d\n stopNum = i + 2\n }\n }\n\n println(stopNum)\n\n}\n"}, {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val busSpeed = nextInt\n val manSpeed = nextInt\n val stations: Array[Int] = new Array[Int](n - 1)\n nextInt\n for (i <- 0 until n - 1) {\n stations(i) = nextInt\n }\n val x = nextInt\n val y = nextInt\n val processedStations = stations.map(X => solver(X, busSpeed, manSpeed, x, y)).zip(Stream from 2).sortWith(customComparator)\n out.println(processedStations(0)._2)\n }\n\n def customComparator(first: ((Double, Double), Int), second: ((Double, Double), Int)) =\n if (first._1._1 == second._1._1) first._1._2 < second._1._2 else first._1._1 < second._1._1\n\n def solver(station: Int, busSpeed: Int, manSpeed: Int, x: Int, y: Int): (Double, Double) = {\n ((dist(station, 0, x, y) * busSpeed + Math.abs(station) * manSpeed) / (busSpeed * manSpeed), dist(station, 0, x, y))\n }\n\n def dist(x: Int, y: Int, x1: Int, y1: Int): Double = {\n Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1))\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val busSpeed = nextInt\n val manSpeed = nextInt\n val stations: Array[Int] = new Array[Int](n - 1)\n nextInt\n for (i <- 0 until n - 1) {\n stations(i) = nextInt\n }\n val x = nextInt\n val y = nextInt\n val processedStations = stations.map(X => solver(X, busSpeed, manSpeed, x, y)).zip(Stream from 2).sortWith(customComparator)\n out.println(processedStations(0)._2)\n }\n\n def customComparator(first: ((Double, Double), Int), second: ((Double, Double), Int)) =\n if (first._1._1 == second._1._1) first._1._2 < second._1._2 else first._1._1 < second._1._1\n\n def solver(station: Int, busSpeed: Int, manSpeed: Int, x: Int, y: Int): (Double, Double) = {\n if (!dist(station, 0, x, y).isNaN) ((dist(station, 0, x, y) * busSpeed + Math.abs(station) * manSpeed) / (busSpeed * manSpeed), dist(station, 0, x, y))\n else (Double.MAX_VALUE, Double.MAX_VALUE)\n }\n\n def dist(x: Int, y: Int, x1: Int, y1: Int): Double = {\n Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1))\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val busSpeed = nextInt\n val manSpeed = nextInt\n val stations: Array[Int] = new Array[Int](n - 1)\n nextInt\n for (i <- 0 until n - 1) {\n stations(i) = nextInt\n }\n val x = nextInt\n val y = nextInt\n val processedStations = stations.map(X => solver(X, busSpeed, manSpeed, x, y)).zipWithIndex.sortWith(customComparator)\n out.println(processedStations(0)._2 + 2)\n }\n\n def customComparator(first: ((Double, Double), Int), second: ((Double, Double), Int)) =\n if (first._1._1 == second._1._1) first._1._2 < second._1._2 else first._1._1 < second._1._1\n\n def solver(station: Int, busSpeed: Int, manSpeed: Int, x: Int, y: Int): (Double, Double) = {\n (dist(station, 0, x, y) / manSpeed + station / busSpeed, dist(station, 0, x, y))\n }\n\n def dist(x: Int, y: Int, x1: Int, y1: Int): Double = {\n Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1))\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "object P9B {\n import io.StdIn._\n import Math._\n\n def main(args:Array[String]) {\n val Array(n, vb, vs) = readLine.split(' ').map{_.toInt}\n val a = readLine.split(' ').map{_.toDouble}\n val Array(xu, yu) = readLine.split(' ').map{_.toInt}\n println(1.to(a.size - 1).minBy{i => {\n val xs = xu - a(i)\n a(i) / vb + sqrt(xs * xs + yu * yu) / vs\n }} + 1)\n }\n}\n"}, {"source_code": "object P9B {\n import io.StdIn._\n import Math._\n\n def main(args:Array[String]) {\n val Array(n, vb, vs) = readLine.split(' ').map{_.toInt}\n val a = readLine.split(' ').map{_.toInt}\n val Array(xu, yu) = readLine.split(' ').map{_.toInt}\n println(1.to(a.size - 1).minBy{i => {\n val xs = xu - a(i)\n a(i).toDouble / vb + sqrt(xs * xs + yu * yu) / vs\n }} + 1)\n }\n}\n"}], "src_uid": "15fa49860e978d3b3fb7a20bf9f8aa86"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readLine().split(\" \").map(_.toInt).head\n val b: Array[(Int,Int)] = readLine().split(\" \").map(_.toInt).toArray.zipWithIndex\n val t = b.filter(x => x._1 == x._2).length\n var res = 0\n if (b.exists(x => b(x._1)._1 == x._2 && x._1 != x._2)) {\n res += 2\n res+=t\n } else {\n res={if (t == n) t else t+1}\n }\n println(res)\n }\n}\n", "positive_code": [{"source_code": "object B {\n def main(args: Array[String]) {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n val t = (Nil : Seq[Int]).toBuffer\n for (i <- 1 to n)\n t += sc.nextInt\n var fix = new Array[Boolean](n)\n for (i <- 0 until n)\n if (i == t(i))\n fix(i) = true\n val cnt = fix.filter(_ == true).size\n for (i <- 0 until n)\n if (!fix(i) && !fix(t(i)))\n if (i == t(t(i))) {\n println(cnt + 2)\n return\n }\n if (cnt >= n-1) {\n println(cnt)\n return\n }\n println(cnt + 1)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val res = data.indices.foldLeft((0, 0)) {\n case ((onPlace, add), i) if data(i) == i => (onPlace + 1, add)\n case ((onPlace, 2), i) => (onPlace, 2)\n case ((onPlace, 1), i) if data(data(i)) == i => (onPlace, 2)\n case ((onPlace, _), i) => (onPlace, 1)\n }\n println(res._1 + res._2)\n}"}, {"source_code": "object B347 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n val map = input.zipWithIndex.toMap\n var res = map.count{case (x, y) => x == y}\n if(res == input.length) {\n println(res)\n } else {\n var i = 0\n var break = false\n while(!break && i < n) {\n val value = map(map(i))\n if(map(i) != i && value == i) {\n println(res + 2)\n break = true\n }\n i += 1\n }\n if(!break) {\n println(res + 1)\n }\n }\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P347B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val A = Array.fill(N)(sc.nextInt)\n\n var n = 0\n var e = 1\n 0 until N foreach { i =>\n if (A(i) == i) {\n n = n + 1\n }\n else if (A(A(i)) == i) {\n e = 2\n }\n }\n out.println((n + e) min N)\n out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val f = a.zipWithIndex.find(t => t._1 != t._2 && t._2 == a(t._1))\n val count = a.zipWithIndex.count(t => t._1 == t._2)\n if (count == n) println(n)\n else f match {\n case None => println(count + 1)\n case Some(_) => println(count + 2)\n }\n }\n}"}, {"source_code": "import scala.io.StdIn\n/**\n * http://codeforces.com/problemset/problem/347/B\n **/\nobject FixedPoints {\n def main(args: Array[String]): Unit = {\n StdIn.readLine()\n val numbers = StdIn.readLine().split(\" \").map(_.toInt)\n println(nbFixedPoints(numbers))\n }\n\n private def nbFixedPoints(numbers: Array[Int]): Int = {\n val (same, different) = numbers.zipWithIndex.partition { case (elt, idx) => elt == idx }\n val additional =\n if (different.isEmpty) 0\n else if (different.exists { case (elt, idx) => numbers(elt) == idx }) 2\n else 1\n same.size + additional\n }\n\n def test() = {\n val inputs = Map(\n Array(0, 1, 3, 4, 2) -> 3,\n Array(0, 1, 5, 3, 4, 2, 7, 6) -> 6,\n Array(0, 1, 5, 3, 4, 2, 7, 6, 8, 9, 10) -> 9\n )\n for ((numbers, expected) <- inputs) {\n assert(nbFixedPoints(numbers) == expected)\n }\n }\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P347B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val A = Array.fill(N)(sc.nextInt)\n\n var n = 0\n var e = 1\n 0 until N foreach { i =>\n if (A(i) == i) {\n n = n + 1\n }\n else if (A(A(i)) == i) {\n e = 2\n }\n }\n out.println(n + e)\n out.close\n}\n"}], "src_uid": "e63de0fffd00b2da103545a7f1e405be"} {"source_code": "object Main extends Solution {\r\n override def solve(): Any = {\r\n (1 to nextInt).foreach(_ => println(nextInt.toString.max))\r\n }\r\n}\r\n\r\ntrait Solution extends FastIO {\r\n val cases = 1\r\n lazy val isLocal: Boolean = sys.props.get(\"CLown1331\").exists(_.toBoolean)\r\n override val isFileInput: Boolean = isLocal\r\n override val isFileOutput: Boolean = false\r\n\r\n def debug(x: => Any): Unit = if (isLocal) println(x)\r\n\r\n def solve(): Any\r\n\r\n def main(args: Array[String]): Unit = {\r\n if (isLocal)\r\n (1 to cases).foreach(_ => solve())\r\n else\r\n solve()\r\n flush()\r\n }\r\n}\r\n\r\ntrait FastIO {\r\n\r\n import java.io._\r\n\r\n val isFileInput = false\r\n val isFileOutput = false\r\n val input = \"res/in.txt\"\r\n val output = \"res/out.txt\"\r\n\r\n lazy val bf = new BufferedReader(if (isFileInput) new FileReader(input) else new InputStreamReader(System.in))\r\n lazy val in = new StreamTokenizer(bf)\r\n lazy val out = new PrintWriter(if (isFileOutput) new FileWriter(output) else new OutputStreamWriter(System.out))\r\n\r\n def next: String = {\r\n in.ordinaryChars('0', '9')\r\n in.wordChars('0', '9')\r\n in.nextToken()\r\n in.sval\r\n }\r\n\r\n def nextInt: Int = {\r\n in.nextToken()\r\n in.nval.toInt\r\n }\r\n\r\n def nextLong: Long = {\r\n in.nextToken()\r\n in.nval.toLong\r\n }\r\n\r\n def nextDouble: Double = {\r\n in.nextToken()\r\n in.nval\r\n }\r\n\r\n def readLine: String = bf.readLine()\r\n\r\n def println(o: Any): Unit = out.println(o)\r\n\r\n def print(o: Any): Unit = out.print(o)\r\n\r\n def printf(s: String, o: Any*): PrintWriter = out.printf(s, o)\r\n\r\n def flush(): Unit = out.flush()\r\n}\r\n", "positive_code": [{"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readLine().split(\"\").map(_.toInt)\r\n\r\n val ans = n.max\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "1a6881aeb197b8ed429f46850eb27b9c"} {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val Array(n, _) = readInts\n def ans = (1 +: readInts).sliding(2).map(x => (x.last.toLong - x.head + n) % n).sum\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Main extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val a = 1 :: readLine().split(\" \").map(_.toInt).toList\n val intervals = a.zip(a.tail)\n val ans = intervals.map(cost).sum\n println(ans)\n\n def cost(interval: (Int, Int)): Long = {\n val (s, e) = interval\n if (s > e) (n - s + 1) + (e - 1)\n else e - s\n }\n}"}, {"source_code": "object cf extends App {\n import java.util.Scanner\n val in = new Scanner(System.in)\n\n val n, m = in.nextInt\n val a = for (i <- 1 to m) yield in.nextInt\n val res = (1 :: a.toList).sliding(2)\n .foldLeft(0L)((sum, pos) => {\n sum + ((pos(1) + n) - pos(0)) % n\n })\n println(res)\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Solution {\n\n\tdef solve() {\n\t\tval (n,m) = (nextInt,nextInt)\n\t\tval a = for (i <- 1 to m) yield nextInt\n\t\t\n\t\tvar cur = 1\n\t\tvar ans = 0l\n\t\tfor (ai <- a) {\t\t\t\n\t\t\tif (ai >= cur) ans += ai-cur\n\t\t\telse ans += n-(cur-ai)\n\t\t\tcur = ai \n\t\t}\n\t\t\n\t\tprintln(ans)\n\t}\n\t\n\tval in = new BufferedReader(new InputStreamReader(System.in))\n\tvar st = new StringTokenizer(\"\")\n\t\n\tdef next : String = {\n\t\twhile (!st.hasMoreTokens) {\n\t\t\tval line = in.readLine\n\t\t\tif (line == null) return null\n\t\t\teat(line)\n\t\t}\n\t\tst.nextToken\n\t}\n\t\n\tdef eat( s : String ) = st = new StringTokenizer(s)\n\tdef nextInt = next.toInt\n\tdef nextLong = next.toLong\n\tdef nextDouble = next.toDouble\n\t\n\tdef main(args: Array[String]) {\n\t\teat(\"\")\n\t\tsolve\n\t}\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Solution {\n\n\tdef solve() {\n\t\tval n = nextInt\n\t\tval m = nextInt\n\t\tval a = for (i <- 1 to m) yield nextInt\n\t\t\n\t\tvar cur = 1\n\t\tvar ans = 0l\n\t\tfor (ai <- a) {\t\t\t\n\t\t\tif (ai >= cur) ans += ai-cur\n\t\t\telse ans += n-(cur-ai)\n\t\t\tcur = ai \n\t\t}\n\t\t\n\t\tprintln(ans)\n\t}\n\t\n\tval in = new BufferedReader(new InputStreamReader(System.in))\n\tvar st = new StringTokenizer(\"\")\n\t\n\tdef next : String = {\n\t\twhile (!st.hasMoreTokens) {\n\t\t\tval line = in.readLine\n\t\t\tif (line == null) return null\n\t\t\teat(line)\n\t\t}\n\t\tst.nextToken\n\t}\n\t\n\tdef eat( s : String ) = st = new StringTokenizer(s)\n\tdef nextInt = next.toInt\n\tdef nextLong = next.toLong\n\tdef nextDouble = next.toDouble\n\t\n\tdef main(args: Array[String]) {\n\t\teat(\"\")\n\t\tsolve\n\t}\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Solution {\n\t\n\tdef main(args: Array[String]) {\n\t\tval in = new FastReader\n\t\t//val n = in.nextInt\n\t\t//val m = in.nextInt\n\t\tval (n,m) = (in.nextInt,in.nextInt)\n\t\tval a = for (i <- 1 to m) yield in.nextInt\n\t\t\n\t\tvar cur = 1\n\t\tvar ans = 0l\n\t\tfor (ai <- a) {\t\t\t\n\t\t\tif (ai >= cur) ans += ai-cur\n\t\t\telse ans += n-(cur-ai)\n\t\t\tcur = ai \n\t\t}\n\t\t\n\t\tprintln(ans)\n\t}\n\n\tclass FastReader {\n\t\tval in = new BufferedReader(new InputStreamReader(System.in))\n\t\tvar st = new StringTokenizer(\"\")\n\t\t\n\t\tdef FastReader {\n\t\t\teat(\"\")\n\t\t}\n\t\t\n\t\tdef next : String = {\n\t\t\twhile (!st.hasMoreTokens) {\n\t\t\t\tval line = in.readLine\n\t\t\t\tif (line == null) return null\n\t\t\t\teat(line)\n\t\t\t}\n\t\t\tst.nextToken\n\t\t}\n\t\t\n\t\tdef eat( s : String ) = st = new StringTokenizer(s)\n\t\tdef nextInt = next.toInt\n\t\tdef nextLong = next.toLong\n\t\tdef nextDouble = next.toDouble\n\t}\n\t\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Solution {\n\t\n\tdef main(args: Array[String]) {\n\t\tval in = new FastReader\n\t\tval n = in.nextInt\n\t\tval m = in.nextInt\n\t\tval a = for (i <- 1 to m) yield in.nextInt\n\t\t\n\t\tvar cur = 1\n\t\tvar ans = 0l\n\t\tfor (ai <- a) {\t\t\t\n\t\t\tif (ai >= cur) ans += ai-cur\n\t\t\telse ans += n-(cur-ai)\n\t\t\tcur = ai \n\t\t}\n\t\t\n\t\tprintln(ans)\n\t}\n\n\tclass FastReader {\n\t\tval in = new BufferedReader(new InputStreamReader(System.in))\n\t\tvar st = new StringTokenizer(\"\")\n\t\t\n\t\tdef FastReader {\n\t\t\teat(\"\")\n\t\t}\n\t\t\n\t\tdef next : String = {\n\t\t\twhile (!st.hasMoreTokens) {\n\t\t\t\tval line = in.readLine\n\t\t\t\tif (line == null) return null\n\t\t\t\teat(line)\n\t\t\t}\n\t\t\tst.nextToken\n\t\t}\n\t\t\n\t\tdef eat( s : String ) = st = new StringTokenizer(s)\n\t\tdef nextInt = next.toInt\n\t\tdef nextLong = next.toLong\n\t\tdef nextDouble = next.toDouble\n\t}\n\t\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n println(in.next().split(\" \").map(_.toInt).foldLeft((1, 0l)) {\n case((prev, count), el) if el >= prev => (el, count + (el - prev))\n case((prev, count), el) => (el, count + n - prev + el)\n }._2)\n}\n"}, {"source_code": "object B339 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val house = readInts(m)\n var curr = 1\n var res = 0L\n for(i <- 0 until m) {\n if(house(i) < curr) {\n res += n - curr + house(i)\n } else if (house(i) > curr) {\n res += house(i) - curr\n }\n curr = house(i)\n }\n println(res)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject A extends App {\n\n val Array(n, m) = StdIn.readLine().split(\" \").map(_.toLong)\n val t = StdIn.readLine().split(\" \").map(_.toLong)\n val result = t.iterator.sliding(2).withPartial(false).map { x =>\n if(x.head == x(1)) 0\n else if (x.head < x(1)) x(1) - x.head\n else n - (x.head - x(1))\n }.sum + (t(0) - 1)\n\n println(result)\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P339B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, M = sc.nextInt\n\n type Tasks = List[Long]\n\n val A: Tasks = List.fill(M)(sc.nextLong)\n\n def solve(): Unit = {\n\n def cost(x: Long, y: Long): Long = if (y < x) y - x + N\n else y - x\n\n @tailrec\n def loop(acc: Long, pos: Long, tasks: Tasks): Long = tasks match {\n case Nil => acc\n case x :: xs => loop(acc + cost(pos, x), x, xs)\n }\n\n out.println(loop(0, 1, A))\n }\n \n solve\n out.close\n}\n"}, {"source_code": "\n\nobject XeniaAndRingroad {\n\tdef main (args: Array[String]) {\n\t\t//Parsing the input\n\t\tval scanner = new java.util.Scanner(System.in);\n\t\tval n = scanner.nextLong;\n\t\tval m = scanner.nextLong;\n\t\tvar last : Long = 1;\n\t\tvar moves : Long = 0;\n\t\tfor (i <- 1 to m.asInstanceOf[Int]) {\n\t\t val current = scanner.nextLong();\n\t\t if (current >= last) \n\t\t moves += (current - last)\n\t\t else\n\t\t moves += (n - last) + current\n\t\t last = current;\n\t\t}\n\t\tprintln(moves)\n\t}\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val nm = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt)\n val m = (Array(1) ++ a).sliding(2).map { x => \n val x1 = x(0)\n val x2 = x(1)\n if (x2 < x1) (nm(0) - x1 + x2).toLong\n else (x2 - x1).toLong\n }\n println(m.sum)\n }\n}"}, {"source_code": "\nimport java.util.Scanner\n\nimport scala.io.StdIn\nimport scala.io.StdIn.readLine\nimport Array._\n\n\nobject problem {\n\n def main(args: Array[String]) {\n val in = new Scanner(System.in)\n val (n, m) = (in.nextInt, in.nextInt)\n var x = 1\n var cnt = 0l\n// val a = ofDim[Int](m + 1)\n val a = for(i <- 1 to m) yield in.nextInt\n for(i <- a){\n\n if(i >= x){\n// println(cnt)\n cnt += i - x\n// println(cnt)\n// x = i\n }\n else{\n// println(cnt)\n cnt += n + i - x\n// println(cnt)\n }\n x = i\n\n }\n println(cnt)\n }\n}"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\nimport Math.abs\n\nobject RingRoad {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readLongs() : Array[Long] = \n readLine.split(' ').map(_.toLong)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n \n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n \n def main(args: Array[String]) {\n val (n,m) = readTuple\n val as = readLongs\n println(as.foldLeft( (1L, 0L)){ case ( (cur: Long, dist: Long), next: Long) =>\n (next, dist + (if (next >= cur) next-cur else n-cur+next)) \n }._2)\n \n }\n \n}"}, {"source_code": "object main extends App with fastIO {\n \n var (n, m) = (nextInt, nextInt)\n var a = Array.fill(m)(nextInt) \n \n println((1 :: a.toList).sliding(2)\n .foldLeft(0L)((sum, pos) => sum + ((pos(1) - pos(0) + n) % n) )) \n\n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "object main extends App with fastIO {\n \n var (n, m) = (nextInt, nextInt)\n \n var (ans, last) = (0l, 1)\n for (_ <- 1 to m) { \n var ind = nextInt\n ans += (if (last <= ind) ind - last else n - (last - ind))\n last = ind\n }\n \n println(ans) \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "object main extends App with fastIO {\n \n var (n, m) = (nextInt, nextInt)\n \n var (ans, last) = (0l, 1)\n var a = for (_ <- 1 to m) yield { \n var ind = nextInt\n ans += (ind + n - last) % n\n last = ind\n ind\n }\n \n val res = (1 :: a.toList).sliding(2)\n .foldLeft(0L)((sum, pos) => {\n sum + ((pos(1) + n) - pos(0)) % n \n })\n //res.foreach { x => Console.err.println(x) }\n \n println(ans) \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "object Solution extends App {\n val Array(n, m) = readLine.split(\" \").map(_.toLong)\n val as = readLine.split(\" \").map(_.toLong)\n \n val ups = as.foldLeft((0l, 1l)){ case(p, c) =>\n if(p._1 > c) {\n (c, p._2 + 1)\n } else {\n (c, p._2)\n }\n }\n \n println((ups._2-1)*n + (as.last - 1))\n}"}], "negative_code": [{"source_code": "object cf extends App {\n import java.util.Scanner\n val in = new Scanner(System.in)\n\n val n, m = in.nextInt\n val a = for (i <- 1 to m) yield in.nextInt\n val res = (1 :: a.toList).sliding(2)\n .foldLeft(0)((sum, pos) => {\n sum + ((pos(1) + n) - pos(0)) % n\n })\n println(res)\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Solution {\n\n\tdef solve() {\n\t\tval n = nextInt\n\t\tval m = nextInt\n\t\tval a = for (i <- 1 to m) yield nextInt\n\t\t\n\t\tvar cur = 1\n\t\tvar ans = 0\n\t\tfor (ai <- a) {\t\t\t\n\t\t\tif (ai >= cur) ans += ai-cur\n\t\t\telse ans += n-(cur-ai)\n\t\t\tcur = ai \n\t\t}\n\t\t\n\t\tprintln(ans)\n\t}\n\t\n\tval in = new BufferedReader(new InputStreamReader(System.in))\n\tvar st = new StringTokenizer(\"\")\n\t\n\tdef next : String = {\n\t\twhile (!st.hasMoreTokens) {\n\t\t\tval line = in.readLine\n\t\t\tif (line == null) return null\n\t\t\teat(line)\n\t\t}\n\t\tst.nextToken\n\t}\n\t\n\tdef eat( s : String ) = st = new StringTokenizer(s)\n\tdef nextInt = next.toInt\n\tdef nextLong = next.toLong\n\tdef nextDouble = next.toDouble\n\t\n\tdef main(args: Array[String]) {\n\t\teat(\"\")\n\t\tsolve\n\t}\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n println(in.next().split(\" \").map(_.toInt).foldLeft((1, 0)) {\n case((prev, count), el) if el >= prev => (el, count + (el - prev))\n case((prev, count), el) => (el, count + n - prev + el)\n }._2)\n}\n"}, {"source_code": "object B339 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val house = readInts(m)\n var curr = 1\n var res = 0\n for(i <- 0 until m) {\n if(house(i) < curr) {\n res += n - curr + house(i)\n } else if (house(i) > curr) {\n res += house(i) - curr\n }\n curr = house(i)\n }\n println(res)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject A extends App {\n\n val Array(n, m) = StdIn.readLine().split(\" \").map(_.toInt)\n val t = StdIn.readLine().split(\" \").map(_.toInt)\n val result = t.sliding(2).map { x =>\n if(x(0) == x(1)) 0\n else if (x(0) < x(1)) x(1) - x(0)\n else n - (x(0) - x(1))\n }.sum + (t(0) - 1)\n\n println(result)\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject A extends App {\n\n val Array(n, m) = StdIn.readLine().split(\" \").map(_.toInt)\n val t = StdIn.readLine().split(\" \").map(_.toInt)\n\n val result = t.sliding(2).map { x =>\n if(x(0) == x(1)) 0\n else if (x(0) < x(1)) x(1) - x(0)\n else x(0) - x(1) + n - 2\n }.sum + (t(0) - 1)\n\n println(result)\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P339B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, M = sc.nextInt\n\n type Tasks = List[Int]\n\n val A: Tasks = List.fill(M)(sc.nextInt)\n\n def solve(): Unit = {\n\n @tailrec\n def loop(acc: Int, pos: Int, tasks: Tasks): Int = tasks match {\n case Nil => acc\n case x :: xs => {\n val cost = x - pos\n if (cost < 0) loop(acc + cost + N, x, xs)\n else loop(acc + cost, x, xs)\n }\n }\n\n out.println(loop(0, 1, A))\n }\n \n solve\n out.close\n}\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val Array(n, _) = readInts\n def ans = (1 +: readInts).sliding(2).map(x => (x.last - x.head + n) % n).sum\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val nm = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt)\n val m = (Array(1) ++ a).sliding(2).map { x => \n val x1 = x(0)\n val x2 = x(1)\n if (x2 < x1) nm(0) - x1 + x2\n else x2 - x1\n }\n println(m.sum)\n }\n}"}, {"source_code": "import scala.io.StdIn\nimport scala.io.StdIn.readLine\nimport Array._\n\nobject problem {\n\n def main(args: Array[String]) {\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n var x = 1\n var cnt = 0\n for(i <- 1 to m){\n if(x < i & x != i){\n cnt += x - i\n x = i\n println(cnt)\n }\n if(x > i & x != i){\n cnt += n - i + x\n x = i\n }\n }\n println(Math.abs(cnt))\n }\n}\n"}, {"source_code": " import java.util.Scanner\n\nimport scala.io.StdIn\nimport scala.io.StdIn.readLine\nimport Array._\n\n\nobject problem {\n\n def main(args: Array[String]) {\n val in = new Scanner(System.in)\n val (n, m) = (in.nextInt, in.nextInt)\n var x = 1\n var cnt = 0\n// val a = ofDim[Int](m + 1)\n val a = for(i <- 1 to m) yield in.nextInt\n for(i <- a){\n\n if(i >= x){\n// println(cnt)\n cnt += i - x\n// println(cnt)\n// x = i\n }\n else{\n// println(cnt)\n cnt += n + i - x\n// println(cnt)\n }\n x = i\n\n }\n println(cnt)\n }\n}\n"}, {"source_code": "object main extends App with fastIO {\n \n var (n, m) = (nextInt, nextInt)\n var a = Array.fill(n)(nextInt) \n \n println((1 :: a.toList).sliding(2)\n .foldLeft(0L)((sum, pos) => sum + ((pos(1) + n) - pos(0)) % n ))\n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "object Solution extends App {\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n val as = readLine.split(\" \").map(_.toInt)\n \n val ups = as.foldLeft((0, 1)){ case(p, c) =>\n if(p._1 > c) {\n (c, p._2 + 1)\n } else {\n (c, p._2)\n }\n }\n \n println((ups._2-1)*n + (as.last - 1))\n}"}], "src_uid": "2c9c96dc5b6f8d1f0ddeea8e07640d3e"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(val l: Int, val r: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return (r-l).compareTo(that.r-that.l)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n\n\n for (tt <- 1 to t) {\n val n = readInt()\n val arr = new Array[Int](n+1)\n for (i <- 1 to n) {\n arr(i) = readInt()\n }\n writer.println(bs(1, 1000000000))\n def check(kk: Long): Boolean = {\n val b = new Array[Int](n+1)\n for (i <- (3 to n).reverse) {\n if (arr(i) + b(i) < kk)\n return false\n val d = (min(arr(i) + b(i) - kk, arr(i)) / 3).toInt\n b(i-1) += d\n b(i-2) += 2*d\n }\n if (arr(2) + b(2) < kk)\n return false\n if (arr(1) + b(1) < kk)\n return false\n return true\n }\n def bs(st:Long, en:Long): Long = {\n if (en - st <= 1L) {\n if (check(en))\n return en\n else\n return st\n }\n val mid = (st + en) / 2L\n if (check(mid))\n return bs(mid, en)\n else\n return bs(st, mid)\n }\n }\n writer.flush()\n}", "positive_code": [{"source_code": "import java.util\n\nobject C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val hs = nextLongs(n)\n val add = Array.fill(n)(0L)\n\n def can(lim: Long): Boolean = {\n util.Arrays.fill(add, 0)\n var i = n - 1\n var ok = true\n while (i > 1) {\n val avail = Math.min(hs(i), hs(i) + add(i) - lim)\n val d = avail / 3\n if (d > 0) {\n add(i - 1) += d\n add(i - 2) += d * 2\n add(i) -= d * 3\n }\n i -= 1\n }\n i = 0\n while (i < n) {\n if (hs(i) + add(i) < lim) {\n ok = false\n i = n\n }\n i += 1\n }\n// val tot = hs.indices.map(i => hs(i) + add(i))\n// println(lim, tot.mkString(\" \"))\n ok\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (can(mid)) binSearch(mid + 1, hi)\n else binSearch(low, mid - 1)\n }\n }\n\n// println(can(8))\n// println(can(7))\n// println(can(6))\n\n val res = binSearch(0, hs.max + 1)\n\n out.println(res - 1)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "895d5850e420a36ae3b5f0a50e359423"} {"source_code": "import java.io.PrintWriter\r\nimport java.util.Scanner\r\n\r\n// values always get less after operation, so just and all of numbers\r\nobject Solution {\r\n def solve(input: Array[Int]): Int =\r\n input.fold(input(0)) { (v1, v2) => v1 & v2 }\r\n\r\n def run(test: Int, input: Scanner, output: PrintWriter): Unit = {\r\n val n = input.nextInt()\r\n val nums = (1 to n).map(_ => input.nextInt()).toArray\r\n output.println(solve(nums))\r\n }\r\n\r\n def run(input: Scanner, output: PrintWriter): Unit = {\r\n val tests = input.nextInt()\r\n\r\n (1 to tests).foreach { test =>\r\n run(test, input, output)\r\n output.flush()\r\n }\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n run(new Scanner(System.in), new PrintWriter(System.out))\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import java.io._\r\nimport scala.collection.immutable.TreeSet\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val reader = new BufferedReader(new java.io.InputStreamReader(System.in))\r\n val writer = new PrintWriter(System.out)\r\n def readInt(): Int = reader.readLine().toInt\r\n def readLong(): Long = reader.readLine().toLong\r\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\r\n def readArrayLong(): Array[Long] = reader.readLine().split(\" \").map(_.toLong)\r\n def readString(): String = reader.readLine()\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n\r\n def solve(t: Int = 0): Unit = {\r\n val n = readInt()\r\n val a = readArrayInt()\r\n var rs = a(0)\r\n for (i <- 1 until n)\r\n rs &= a(i)\r\n\r\n writer.println(rs)\r\n }\r\n\r\n def main(args: Array[String]) {\r\n multiTest(solve)\r\n //solve()\r\n writer.flush()\r\n }\r\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Problem extends App {\n def start() = {\n println(parseInput().map(testCase => minMaxValue(testCase)).mkString(\"\\n\"))\n }\n\n def arrayOp(array: Array[Int], l: Int, r: Int): Array[Int] = {\n for( i <- 0.to(r-l)) {\n array(l+i) = array(l+i) & array(r-i)\n }\n array\n }\n\n def minMaxValue(given: Array[Int]): Int = {\n given.foldLeft(Int.MaxValue)(_ & _)\n }\n\n\n def parseInput(): Array[Array[Int]] = {\n val testCases: Int = StdIn.readLine().stripLineEnd.trim.toInt\n var input = Array[Array[Int]]()\n for (_ <- 0L.until(testCases)) {\n val n = StdIn.readLine().stripLineEnd.trim.toInt\n val testCase = StdIn.readLine().split(\" \").map(_.stripLineEnd.trim.toInt)\n input = input ++ Array(testCase)\n }\n input\n }\n\n start()\n}\n"}, {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n val ans = an.tail.foldLeft(an.head)(_ & _)\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "import java.io._\r\nimport scala.collection.immutable.TreeSet\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val reader = new BufferedReader(new java.io.InputStreamReader(System.in))\r\n val writer = new PrintWriter(System.out)\r\n def readInt(): Int = reader.readLine().toInt\r\n def readLong(): Long = reader.readLine().toLong\r\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\r\n def readArrayLong(): Array[Long] = reader.readLine().split(\" \").map(_.toLong)\r\n def readString(): String = reader.readLine()\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n\r\n def solve(t: Int = 0): Unit = {\r\n val n = readInt()\r\n val a = readArrayInt()\r\n writer.println(a.min)\r\n\r\n\r\n }\r\n\r\n def main(args: Array[String]) {\r\n multiTest(solve)\r\n //solve()\r\n writer.flush()\r\n }\r\n}"}], "src_uid": "4f8eac547bbd469a69de2f4aae4a87f0"} {"source_code": "import scala.io.StdIn\n\nobject AlphabeticRemovals {\n def main(args: Array[String]): Unit = {\n val k = StdIn.readLine().split(\" \")(1).toInt\n val input = StdIn.readLine()\n println(solve(input, k))\n }\n\n def solve(input: String, k: Int): String = {\n if (k >= input.length) return \"\"\n\n val charCount = input.groupBy(identity).mapValues(_.length)\n val alphabet = charCount.keys.toSeq.sorted\n\n val result = calculate(Seq.empty, alphabet, k, charCount)\n val kill = result._1\n val keep = result._2\n val decide = result._3\n var remove = result._4\n\n input.filterNot(c => kill.contains(c) || (c == decide\n && {remove -= 1; remove >= 0}))\n }\n\n private def calculate(kill: Seq[Char], keep: Seq[Char], k:Int, map: Map[Char, Int]) : (Seq[Char], Seq[Char], Char, Int) = {\n val next: Char = keep.head\n val occurs: Int = map(next)\n\n if (occurs > k) {\n (kill, keep.tail, next, k)\n } else {\n calculate(kill :+ next, keep.tail, k - occurs, map)\n }\n }\n}", "positive_code": [{"source_code": "object CF_490_3_C {\n\n type In = (Int, Int, String)\n type Out = String\n type SC = Seq[Char]\n\n def solve(in: In): Out = {\n val (n, k, s) = in\n val removals = s.toSeq.sorted.take(k)\n s.diff(removals)\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, i.int, {i.nextLine; i.nextLine})\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n // `a` MUST be > 0. Incorrect otherwise.\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}, {"source_code": "object C999A {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n var Array(n, k) = readInts(2)\n val str = read\n val marked = Array.fill(n)(0)\n var char = 'a'\n while(k > 0 && char <= 'z') {\n for(i <- 0 until n if k > 0) {\n if(str(i) == char && marked(i) == 0) {\n marked(i) = 1\n k -= 1\n }\n }\n char = (char.toInt + 1).toChar\n }\n for(i <- 0 until n) if(marked(i) == 0)\n out.print(str(i))\n out.println(\"\")\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}"}, {"source_code": "object Main2 extends App {\n\n import java.io._\n import java.util.{StringTokenizer}\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val n = in.nextInt\n var k = in.nextInt\n var s = in.next\n var cnt = s.groupBy(ch => ch).mapValues(_.length)\n for (ch <- 'a' to 'z') {\n val x = cnt.getOrElse(ch, 0)\n val c = x min k\n cnt += ch -> c\n k -= c\n }\n \n s foreach { ch =>\n val x = cnt getOrElse(ch, 0)\n if (x == 0) out.print(ch)\n else cnt += ch -> (x - 1)\n }\n\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n def nextLong: Long = next.toLong\n\n def nextDouble: Double = next.toDouble\n\n def nextLine: String = br.readLine\n }\n\n}"}], "negative_code": [], "src_uid": "9f095a5f5b39d8c2f99c4162f2d7c5ff"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val set = Set('A', 'H', 'I', 'M', 'O', 'T', 'U', 'V', 'W', 'X', 'Y')\n if (str == str.reverse && str.forall(set))\n println(\"YES\")\n else\n println(\"NO\")\n}", "positive_code": [{"source_code": "/**\n * Created by infm on 4/24/14.\n */\nobject Main {\n val in = {\n val lines = {\n scala.io.Source.stdin.getLines().buffered\n }\n lines map (_ split ' ') filter (_.nonEmpty) flatten\n }\n\n def main(args: Array[String]){\n val mirrored = \"AHIMOTUVWXY\"\n val current = in.next\n if (current == current.reverse && current.forall(mirrored.contains(_)))\n println(\"YES\")\n else\n println(\"NO\")\n }\n}\n"}, {"source_code": "/**\n * Created by infm on 4/24/14.\n */\nobject A {\n val in = {\n val lines = {\n scala.io.Source.stdin.getLines().buffered\n }\n lines map (_ split ' ') filter (_.nonEmpty) flatten\n }\n\n def main(args: Array[String]){\n val mirrored = \"AHIMOTUVWXY\"\n val current = in.next\n if (current == current.reverse && current.forall(mirrored.contains(_)))\n println(\"YES\")\n else\n println(\"NO\")\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val name = readLine()\n val goodChars = Set[Char]('A', 'H', 'I', 'M', 'O', 'T', 'U', 'V', 'W', 'X', 'Y')\n for (i <- 0 to name.length / 2) {\n if (name(i) != name(name.length - 1 - i) || !goodChars.contains(name(i))) {\n println(\"NO\")\n return\n }\n }\n println(\"YES\")\n }\n}\n"}, {"source_code": "object Main {\n\n\tval in = {\n\t\tval lines = {\n\t\t\tscala.io.Source.stdin.getLines.buffered\n\t\t\t//val bf = new BufferedReader(new InputStreamReader(System.in))\n\t\t\t//Iterator.continually(readLine)\n\t\t\t//Iterator.continually(bf.readLine)\n\t\t}\n\t\tlines map (_ split ' ') filter (_.nonEmpty) flatten\n\t}\n\t\n\t//val out = new PrintWriter(System.out)\n\t\n\tdef nextInt = in.next().toInt\n\tdef nextLong = in.next().toLong\n\t\n\tdef main(args: Array[String]): Unit = {\n\t\n\t\tval mirror = \"AHIMOTUVWXY\"\n\t\t\t\n\t\tval name = in.next\n\t\t\n\t\tif (name == name.reverse && name.forall(mirror.contains(_)))\n\t\t\tprintln(\"YES\")\n\t\telse\n\t\t\tprintln(\"NO\")\n\t\t\n\t}\n\n}"}, {"source_code": "\n/**\n * Created by yangchaozhong on 3/12/15.\n */\nobject CF420A extends App {\n import scala.collection.immutable.HashSet\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val name = nextString\n val chars = HashSet('A', 'H', 'I', 'M', 'O', 'T', 'U', 'V', 'W', 'X', 'Y')\n val len = name.length\n val half = len / 2\n val sum = (0 to (half - 1)).map(i => Math.abs(name(i) - name(len - 1 - i))).sum\n val count = name.count(!chars.contains(_))\n if (sum == 0 && count == 0)\n out.println(\"YES\")\n else\n out.println(\"NO\")\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n"}], "negative_code": [{"source_code": "/**\n * Created by yangchaozhong on 3/12/15.\n */\nobject CF420A extends App {\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val name = nextString\n if (name.length <= 1)\n out.println(\"NO\")\n else {\n val len = name.length\n val half = len / 2\n val sum = (0 to (half - 1)).map(i => Math.abs(name(i) - name(len - 1 - i))).sum\n if (sum == 0)\n out.println(\"YES\")\n else\n out.println(\"NO\")\n }\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n"}], "src_uid": "8135173b23c6b48df11b1d2609b08080"} {"source_code": "object recruits extends App {\n\tval (n, evts) = (readLine.toInt, readLine.split(' ').map(_.toInt))\n\tvar (cnt, ans) = (0, 0)\n\tfor (evt <- evts) {\n\t\tif (cnt == 0 && evt == -1) {\n\t\t\tans += 1\n\t\t}\n\t\telse {\n\t\t\tcnt += evt\n\t\t}\n\t}\n\tprint(ans)\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject practice {\n\n def main(args: Array[String]): Unit = {\n val scan = new Scanner(System.in)\n var str = scan.next\n var crimes = 0\n var polices = 0\n var in = 0\n for (i <- 1 to str.toInt) {\n in = scan.next.toInt\n if (in == -1) {\n if (polices <= 0) {\n crimes += 1\n } else {\n polices -= 1\n }\n } else {\n polices += in\n }\n\n }\n \n println(crimes)\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n var n = in.next().toInt\n println(in.next().split(\" \").map(_.toInt).foldLeft((0, 0)){\n case((count, pol), -1) if pol > 0 => (count, pol - 1)\n case((count, pol), -1) => (count + 1, 0)\n case((count, pol), el) => (count, pol + el)\n }._1)\n}\n"}, {"source_code": "object A {\n\n def main(args: Array[String]): Unit = {\n var n = readInt\n// var a = new Array[Int](n)\n// for (i <- 0 to n-1){\n// a(i) = readInt\n// }\n var a = readLine.split(\" \").map(_.toInt)\n var cnt = 0\n var ans = 0\n for (i <- 0 to a.length-1){\n if (a(i) == -1) {\n \t if (cnt > 0){\n \t cnt = cnt -1\n \t }else \t\n \t\t ans = ans + 1\n }else cnt = cnt + a(i)\n }\n println(ans) \n }\n\n}"}, {"source_code": "object A427 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n var officers = 0\n var res = 0\n for(i <- 0 until n) {\n if(input(i) == -1) {\n if(officers > 0)\n officers -= 1\n else\n res += 1\n } else {\n officers += input(i)\n }\n }\n println(res)\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P427A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Long = {\n val N = sc.nextInt\n\n @tailrec\n def loop(acc: Int, police: Int, i: Int): Int = {\n if (i == N) acc\n else {\n val event = sc.nextInt\n if (event < 0) {\n if (police > 0) loop(acc, police - 1, i + 1)\n else loop(acc + 1, 0, i + 1)\n }\n else loop(acc, police + event, i + 1)\n }\n }\n\n loop(0, 0, 0)\n }\n\n out.println(solve)\n out.close\n}\n \n\n\n\n\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.PriorityQueue\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n\n @tailrec\n def loop(acc: Int, police: Int, n: Int): Int = {\n if (n == N) acc\n else {\n val x = sc.nextInt\n if (x < 0) { // crime occured\n if (police > 0) { // at least one police officer\n loop(acc, police - 1, n + 1)\n }\n else {\n loop(acc + 1, 0, n + 1)\n }\n }\n else {\n loop(acc, police + x, n + 1)\n }\n }\n }\n loop(0, 0, 0)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-17.\n */\nobject A427 extends App{\n val sc = new Scanner(System.in)\n var n = sc.nextInt()\n var policeNum = 0\n var untreated = 0\n\n while (n > 0) {\n var a = sc.nextInt()\n\n if (a == -1) {\n if (policeNum > 0) {\n policeNum -= 1\n } else {\n untreated += 1\n }\n } else {\n policeNum += a\n }\n\n n -= 1\n }\n\n println(untreated)\n}\n"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject PoliceRecruits {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readLongs() : Array[Long] = \n readLine.split(' ').map(_.toLong)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n \n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n \n def main(args: Array[String]) {\n val n = readInt\n val events = readInts\n val sim = events.foldLeft( (0,0)){\n case ((crimes,pol),e) => \n if (e > 0) (crimes,pol+e)\n else if (pol >= 1) (crimes,pol-1) else (crimes+1,pol) \n }\n println(sim._1)\n }\n \n}"}, {"source_code": "// http://codeforces.com/contest/427/problem/A\nobject A extends App {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n val ev = Array.fill(n)(sc.nextInt())\n var unrated, hired = 0;\n for (t <- ev) {\n if (t == -1) {\n if (hired == 0) unrated += 1\n else hired -= 1\n }\n else {\n hired += t\n }\n }\n println(unrated);\n}\n"}, {"source_code": "object A extends App {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n val ev = Array.fill(n)(sc.nextInt())\n var unrated, hired = 0;\n for (t <- ev) {\n if (t == -1) {\n if (hired == 0) unrated += 1\n else hired -= 1\n }\n else {\n hired += t\n }\n }\n println(unrated);\n}\n"}, {"source_code": "object main extends App with fastIO {\n \n val n = nextInt\n \n var (ans, cnt) = (0, 0) \n for (i <- 1 to n) {\n nextInt match {\n case -1 if cnt == 0 => ans += 1\n case n => cnt += n\n } \n }\n \n println(ans)\n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "import util.control.Breaks._\nimport scala.collection.mutable.ArrayBuffer\n\nobject main extends App with fastIO {\n \n val n = nextInt\n \n var (ans, cnt) = (0, 0) \n for (i <- 1 to n) {\n nextInt match {\n case -1 => { ans += -cnt + 1 max 0; cnt = cnt - 1 max 0 }\n case n => cnt += n\n } \n }\n \n println(ans)\n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "import java.util.Scanner\n\nobject Main extends App {\n\n val sc = new Scanner(System.in)\n// val sc = new Scanner( new FileInputStream(\"src/input.txt\") )\n val n = sc.nextInt\n\n var i = 0\n var res = 0\n def cup(up: Int) = {\n i += up\n if(i<0){\n res += 1\n i = 0\n }\n (i,res)\n }\n\n (0 until n).foreach( i=> {\n val t = sc.nextInt\n cup(t)\n })\n println(res)\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nobject practice {\n\n def main(args: Array[String]): Unit = {\n val scan = new Scanner(System.in)\n var str = scan.next\n var crimes = 0\n var polices = 0\n var in = 0\n for (i <- 1 to str.toInt) {\n in = scan.next.toInt\n if (in == -1) {\n if (polices <= 0) {\n crimes += 1\n } else {\n polices -= 1\n }\n } else {\n polices += in\n }\n if (polices > 10) {\n polices = 10\n }\n\n }\n \n println(crimes)\n }\n\n}\n"}], "src_uid": "af47635f631381b4578ba599a4f8b317"} {"source_code": "import scala.collection._\nimport scala.util.Random\nimport java.util.Arrays\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n).sorted.distinct\n //val as = Array.fill(n)(Random.nextInt(1000000)).sorted\n val max = as.last\n\n var res = 0 \n \n for (i <- as.indices) {\n val a = as(i)\n var x = a\n var prevJ = i\n while (x <= max) {\n x += a\n val j0 = Arrays.binarySearch(as, prevJ + 1, as.length, x)\n val j = if (j0 < 0) -j0 - 2 else j0 - 1\n if (j >= 0 && as(j) > a) res = res max (as(j) - x + a)\n prevJ = j\n } \n }\n\n println(res)\n}", "positive_code": [{"source_code": "import java.util.Arrays\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val as = readInts(n).sorted.distinct\n val max = as.last\n\n var res = 0 \n \n for (i <- as.indices) {\n val a = as(i)\n var x = a\n var prevJ = i\n while (x <= max) {\n x += a\n val j0 = Arrays.binarySearch(as, prevJ + 1, as.length, x)\n val j = if (j0 < 0) -j0 - 2 else j0 - 1\n if (j >= 0 && as(j) > a) res = res max (as(j) - x + a)\n prevJ = j\n } \n }\n\n println(res)\n}"}], "negative_code": [], "src_uid": "0ef324e3e314ea17c01aafb822e90c63"} {"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val cs = readInts(n)\n val as = readInts(n).map(_ - 1)\n\n val visited = Array.fill(n){ false }\n val isCycle = Array.fill(n){ false }\n var num = 0\n val nums = Array.fill(n){ 0 }\n\n def dfs1(u: Int): Int = {\n if (visited(u)) {\n if (nums(u) > 0) nums(u)\n else {\n isCycle(u) = true\n num += 1\n nums(u) = num\n num\n }\n } else {\n visited(u) = true\n nums(u) = dfs1(as(u))\n nums(u)\n }\n }\n\n var i = 0\n while (i < n) {\n dfs1(i)\n i += 1\n }\n\n def dfs2(u: Int, start: Int, min: Int): Int = {\n val v = as(u)\n if (v == start) min\n else dfs2(v, start, min min cs(v))\n }\n\n i = 0\n var res = 0L\n while (i < n) {\n if (isCycle(i)) res += dfs2(i, i, cs(i))\n i += 1\n }\n\n println(res)\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N = sc.nextInt()\n val C = map(N)(_ => sc.nextInt())\n val E = map(N)(_ => sc.nextInt() - 1)\n val visited, computed = Array.ofDim[Boolean](N)\n\n def findMin(from: Int, to: Int) = {\n var ms = C(from)\n var v = from\n while(v != to) {\n v = E(v)\n ms = min(ms, C(v))\n }\n ms\n }\n\n val stack = ArrayBuffer[Int]()\n var ans = 0\n rep(N) { i =>\n var v = i\n while (!visited(v)) {\n stack += v\n visited(v) = true\n v = E(v)\n }\n if (!computed(v)) {\n ans += findMin(E(v), v)\n }\n stack foreach (v => computed(v) = true)\n stack.clear()\n }\n\n out.println(ans)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}\n"}], "negative_code": [], "src_uid": "4278fece7812148863688c67218aca7b"} {"source_code": "import java.io._\nimport java.math._\nimport java.util.StringTokenizer\nimport scala.collection.mutable.Map\n\nobject C {\n def main(args: Array[String]) {\n val sc = new MyScanner\n val n = sc.nextLine.toInt\n val a = sc.nextLine.split(\" \").map(_.toInt)\n val freq = Map[Long, Int]()\n \n // Calculate the prefix sums\n var sum: Long = 0\n for (x <- a) {\n sum += x\n if (freq contains sum) {\n freq(sum) += 1\n } else {\n freq(sum) = 1\n }\n }\n\n // Get the most frequently appearing prefix sum\n var best = 0\n for ((k, v) <- freq) {\n best = Math.max(v, best)\n }\n println(n - best)\n }\n}\n\nclass MyScanner { \n var br = new BufferedReader(new InputStreamReader(System.in))\n var st: StringTokenizer = null\n def next(): String = {\n while (st == null || !st.hasMoreElements()) {\n try {\n st = new StringTokenizer(br.readLine())\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n }\n return st.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextDouble(): Double = next().toDouble\n def nextLine(): String = {\n var str = \"\"\n try {\n str = br.readLine()\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n return str\n }\n def close() = {\n try {\n br.close()\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) {\n val n = StdIn.readInt()\n val a = StdIn.readLine().split(\" \").map(_.toLong)\n var ct = mutable.HashMap[Long, Int]();\n var s = 0L\n for (i <- 0 until n) {\n s += a(i)\n ct(s) = ct.getOrElse(s, 0) + 1\n }\n var ans = n\n for (i <- 0 until n) {\n ans = Math.min(n - ct(s), ans)\n s += a(i)\n }\n println(ans)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.math._\nimport java.util._\nimport scala.collection.JavaConversions._\n\nobject C {\n def main(args: Array[String]) {\n val sc = new MyScanner\n val n = sc.nextLine.toInt\n val a = sc.nextLine.split(\" \").map(_.toInt)\n val freq = new HashMap[Long, Int]\n \n var sum: Long = 0\n for (x <- a) {\n sum += x\n if (freq containsKey sum) {\n freq put (sum, freq.get(sum) + 1)\n } else {\n freq put (sum, 1)\n }\n }\n\n var best = 0\n for ((k, v) <- freq) {\n best = Math.max(v, best)\n }\n println(n - best)\n }\n}\n\nclass MyScanner { \n var br = new BufferedReader(new InputStreamReader(System.in))\n var st: StringTokenizer = null\n def next(): String = {\n while (st == null || !st.hasMoreElements()) {\n try {\n st = new StringTokenizer(br.readLine())\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n }\n return st.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextDouble(): Double = next().toDouble\n def nextLine(): String = {\n var str = \"\"\n try {\n str = br.readLine()\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n return str\n }\n def close() = {\n try {\n br.close()\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport java.math._\nimport java.util._\nimport scala.collection.mutable.Map\n\nobject C {\n def main(args: Array[String]) {\n val sc = new MyScanner()\n val n = sc.nextInt\n var freq = Map[Long, Int]()\n \n // Calculate the prefix sums\n var sum: Long = 0\n for (i <- 0 until n) {\n sum += sc.nextInt\n if (freq contains sum) {\n freq(sum) += 1\n } else {\n freq(sum) = 1\n }\n }\n\n // Get the most frequently appearing prefix sum\n var best = 0\n for ((k, v) <- freq) {\n best = Math.max(v, best)\n }\n println(n - best)\n }\n}\n\nclass MyScanner { \n var br = new BufferedReader(new InputStreamReader(System.in))\n var st: StringTokenizer = null\n def next(): String = {\n while (st == null || !st.hasMoreElements()) {\n try {\n st = new StringTokenizer(br.readLine())\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n }\n return st.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextDouble(): Double = next().toDouble\n def nextLine(): String = {\n var str = \"\"\n try {\n str = br.readLine()\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n return str\n }\n def close() = {\n try {\n br.close()\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) {\n val n = StdIn.readInt()\n val a = StdIn.readLine().split(\" \").map(_.toInt)\n var p = n - 1\n while (p > 0 && a(p) == 0) {\n p -= 1\n }\n var ans = p\n for (i <- 0 until n) {\n var s = -a(i)\n while (s != 0) {\n p += 1\n s += a(p % n)\n }\n ans = Math.min(ans, p - 1 - i)\n }\n println(ans)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) {\n val n = StdIn.readInt()\n val a = StdIn.readLine().split(\" \").map(_.toLong)\n if (n == 1) {\n println(0)\n return\n }\n var p = n - 1\n while (p > 0 && a(p) == 0) {\n p -= 1\n }\n var ans = p\n for (i <- 0 until n) {\n var s = -a(i)\n while (s != 0) {\n p += 1\n s += a(p % n)\n }\n ans = Math.min(ans, p - 1 - i)\n }\n println(ans)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) {\n val n = StdIn.readInt()\n val a = StdIn.readLine().split(\" \").map(_.toLong)\n if (n == 1) {\n println(0)\n return\n }\n var p = n - 1\n while (p > 0 && a(p) == 0) {\n p -= 1\n }\n var ans = p\n for (i <- 0 until n) {\n if (a(i) != 0) {\n p = i + n\n }\n ans = Math.min(ans, p - 1 - i)\n }\n println(ans)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.math._\nimport java.util._\nimport scala.collection.mutable.Map\n\nobject C {\n def main(args: Array[String]) {\n val sc = new MyScanner()\n val n = sc.nextInt\n val a = new Array[Int](n)\n var freq = Map[Int, Int]()\n \n // Calculate the prefix sums\n var sum = 0\n for (i <- 0 until n) {\n sum += sc.nextInt\n a(i) = sum\n if (freq contains sum) {\n freq(sum) += 1\n } else {\n freq(sum) = 1\n }\n }\n\n // Get the most frequently appearing prefix sum\n var best = 0\n for ((k, v) <- freq) {\n best = Math.max(v, best)\n }\n println(n - best)\n }\n}\n\nclass MyScanner { \n var br = new BufferedReader(new InputStreamReader(System.in))\n var st: StringTokenizer = null\n def next(): String = {\n while (st == null || !st.hasMoreElements()) {\n try {\n st = new StringTokenizer(br.readLine())\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n }\n return st.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextDouble(): Double = next().toDouble\n def nextLine(): String = {\n var str = \"\"\n try {\n str = br.readLine()\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n return str\n }\n def close() = {\n try {\n br.close()\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n }\n}\n"}], "src_uid": "be12bb8148708f9ad3dc33b83b55eb1e"} {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n def solve(x: Long, y: Long) = {\n if (y > x) -1.toDouble\n else if (x == y) {\n x.toDouble\n } else {\n val k = (x - y) / (2*y)\n if (k == 0) {\n val c = (x.toDouble + y) / (2 * k + 2)\n if (c < y) -1.toDouble\n else c\n } else {\n val A = (x.toDouble - y) / (2 * k)\n// println(A)\n val B = (x.toDouble + y) / (2 * k + 2)\n// println(B)\n\n if (A < y && B < y) -1.toDouble\n else if (A < y) B\n else if (B < y) A\n else Math.min(A, B)\n }\n }\n }\n\n val Array(a, b) = readLine().split(\" \").map(_.toLong)\n val answer = solve(a, b)\n\n println(if (answer > 0) \"%.12f\".format(answer) else \"-1\")\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Main extends App {\n\n val sc = new Scanner(System.in)\n val a = sc.nextInt\n val b = sc.nextInt\n\n val t1 = (a + b) / 2.0\n val t2 = (a - b) / 2.0\n\n def a(t: Double) = {\n val dv = (t / b).toInt\n if (dv == 0)\n -1\n else\n t / dv\n }\n\n val a1 = a(t1)\n val a2 = a(t2)\n\n if (a1 == -1) {\n println(a2)\n } else if (a2 == -1) {\n println(a1)\n } else {\n println(math.min(a1, a2))\n }\n}\n"}], "negative_code": [{"source_code": "import java.text.DecimalFormat\n\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\n\nobject C extends App {\n def solve(x: Int, y: Int) = {\n if (y > x) -1.toDouble\n else if (x == y) {\n x.toDouble\n } else {\n val k = (x - y) / (2*y)\n if (k == 0) {\n val c = (x.toDouble + y) / (2 * k + 2)\n if (c > y) -1.toDouble\n else c\n } else {\n val A = (x.toDouble - y) / (2 * k)\n// println(A)\n val B = (x.toDouble + y) / (2 * k + 2)\n// println(B)\n\n if (A < y && B < y) -1.toDouble\n else if (A < y) B\n else if (B < y) A\n else Math.min(A, B)\n }\n }\n }\n\n val answer = solve(1, 3)\n\n println(if (answer > 0) \"%.12f\".format(answer) else \"-1\")\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n def solve(x: Long, y: Long) = {\n if (y > x) -1.toDouble\n else if (x == y) {\n x.toDouble\n } else {\n val k = (x - y) / (2*y)\n if (k == 0) {\n val c = (x.toDouble + y) / (2 * k + 2)\n if (c > y) -1.toDouble\n else c\n } else {\n val A = (x.toDouble - y) / (2 * k)\n// println(A)\n val B = (x.toDouble + y) / (2 * k + 2)\n// println(B)\n\n if (A < y && B < y) -1.toDouble\n else if (A < y) B\n else if (B < y) A\n else Math.min(A, B)\n }\n }\n }\n\n val Array(a, b) = readLine().split(\" \").map(_.toLong)\n val answer = solve(a, b)\n\n println(if (answer > 0) \"%.12f\".format(answer) else \"-1\")\n}\n"}], "src_uid": "1bcf130890495bcca67b4b0418476119"} {"source_code": "object A extends App {\n import scala.io.StdIn._\n import scala.annotation.tailrec\n\n val t = readInt()\n\n def mult(a: List[List[Int]], b: List[List[Int]]): List[List[Int]] =\n for {\n row <- a\n } yield for {\n col <- b.transpose\n } yield row.zip(col).foldLeft(0) { case (sum, (r, c)) => sum + r * c }\n\n def binpow(a: List[List[Int]], n: Int): List[List[Int]] =\n (0 to (math.log(n) / math.log(2)).toInt)\n .foldLeft((List(List(1, 0), List(0, 1)), a)) {\n case ((r, a), i) =>\n (if ((1 & (n >> i)) == 1) mult(a, r) else r, mult(a, a))\n }\n ._1\n\n def fib(n: Int): (Int, Int) = {\n val List(fibn, fibn1) = mult(List(List(0, 1)), binpow(List(List(0, 1), List(1, 1)), n)).head\n (fibn, fibn1)\n }\n\n (0 until t).foreach { _ =>\n val Array(a, b, n) = readLine().split(\" \").map(_.toInt)\n\n val ans = (0 to n).collectFirst { case i if { val (c1, c2) = fib(i); c2 * a.max(b) + c1 * a.min(b) > n } => i }.get\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val abn = readIntLine()\n println(handle(Math.min(abn.head, abn(1)), Math.max(abn.head, abn(1)), abn.last, 0))\n }\n }\n\n def handle(a: Int, b: Int, n: Int, acc: Int): Int = if (b > n) acc else handle(b, a + b, n, acc + 1)\n\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}, {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n var a, b, n = nextLong\n var i = 0\n while (a <= n && b <= n) {\n if (a < b) {\n a += b\n } else {\n b += a\n }\n i += 1\n }\n\n out.println(i)\n\n out.flush()\n }\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b, n) = readLine().split(\" \").map(_.toInt)\n\n lazy val fibs: Stream[(Int, Int)] = (0, 0) #:: (1, 1) #:: (fibs zip fibs.tail).map {\n case ((a, _), (b, i)) => (a + b, i + 1)\n }\n\n val ans = fibs.zip(fibs.tail).collectFirst { case ((f0, i), (f1, _)) if f1 * a.max(b) + f0 * a.min(b) > n => i }.get\n\n println(ans)\n }\n}"}], "negative_code": [], "src_uid": "5999a4e2fac29b5f4804639f6e949279"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(var social: Int, var cp: Int, var ind: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (social < that.social)\n return -1\n else if (social == that.social)\n return 0\n else\n return 1\n }\n }\n val rem = 1000000007\n\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val s1 = readString()\n val s2 = readString()\n var reach = true\n for (i <- 0 until n) {\n if (s1(i) == '1' && s2(i) == '1')\n reach = false\n }\n if (reach)\n writer.println(\"YES\")\n else\n writer.println(\"NO\")\n }\n writer.flush()\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\r\nimport scala.util.control.Breaks._\r\n\r\nobject ComputerGame extends App {\r\n def solve():Unit = {\r\n val t = readLine().trim.toInt\r\n for(_ <- 1 to t) {\r\n val n = readLine().trim.toInt\r\n val grid: Array[String] = new Array[String](2)\r\n grid(0) = readLine().trim\r\n grid(1) = readLine().trim\r\n var isPossible:Boolean = true\r\n breakable {\r\n for (i <- 0 until n) {\r\n isPossible = grid(0)(i) == '0' || grid(1)(i) == '0'\r\n if (!isPossible) break\r\n }\r\n }\r\n val ans = if(isPossible) \"YES\" else \"NO\"\r\n println(ans)\r\n }\r\n }\r\n solve()\r\n}\r\n"}], "negative_code": [], "src_uid": "fefec879efd4f524de00684adee7cd19"} {"source_code": "object Anastasia extends App {\n\n val Array(n: Int, k: Int) = readLine.split(' ').map(_.toInt)\n val ww: Array[Int] = readLine.split(' ').map(_.toInt)\n\n val pocketCount = for (w <- ww) yield {\n val ratio = w / k\n val remainder = w % k\n if (remainder == 0) ratio else ratio + 1\n }\n \n val ratio = pocketCount.sum / 2\n val remainder = pocketCount.sum % 2\n val result = if (remainder == 0) ratio else ratio + 1\n\n println(result)\n}\n", "positive_code": [{"source_code": "object _789A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n val n = read[Int]\n val k = read[Long]\n val pebbles = read[Seq, Long](n)\n val chunks = pebbles.sumWith(i => (i + k - 1)/k)\n val ans = (chunks + 1)/2\n write(ans)\n }\n\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "\n\n/**\n * Created by ruslan on 3/29/17.\n */\nobject ProblemA extends App {\n import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}\nimport java.util.StringTokenizer\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\nclass FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens()) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n}\n\n val n = in.nextInt();\n val k = in.nextInt();\n var res = 0;\n\n for (i <- 1 to n) {\n val w = in.nextInt();\n res += w / k;\n if (w % k > 0) res += 1;\n }\n\n res = res / 2 + (if (res % 2 == 1) 1 else 0)\n\n println(res)\n\n}\n"}], "negative_code": [], "src_uid": "3992602be20a386f0ec57c51e14b39c5"} {"source_code": "\n\nobject Main {\n\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj) {\n f\n }\n }\n\n def debug(as: Array[Boolean]): Unit = if (!oj) {\n debug(as.map(x => if (x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = if (!oj) {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = if (!oj) {\n debug(as.mkString(\" \"))\n }\n\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj) {\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj) {\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i)\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i)\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def ?(item: Boolean, first: Any, second: Any): Any = if (item) first else second\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, in: Main.InputReader) {\n\n @inline private def MOD = 1000000007\n\n\n def solve(): Unit = {\n val n = in.nextInt()\n val k = in.nextInt()\n val a = new Array[Int](k + 1)\n for (_ <- 0 until n) {\n a(in.nextInt()) += 1\n }\n a.sorted\n var count = 0\n var d = (n + 1) / 2\n for {\n i <- k to 0 by -1\n if a(i) > 0\n } yield {\n count += a(i) - (a(i) % 2)\n d -= a(i) / 2\n a(i) = a(i) % 2\n }\n a.sorted\n for {\n i <- a.indices\n if d > 0\n\n } yield {\n if (a(i) > 0) {\n count += 1\n d -= 1\n }\n\n }\n out.println(count)\n\n }\n}", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, K = ni()\n val C = Array.ofDim[Int](K)\n REP(N) { _ =>\n C(ni() - 1) += 1\n }\n val cntOdd = C.count(_ % 2 == 1)\n val ans = N - cntOdd / 2\n out.println(ans)\n }\n}"}], "negative_code": [], "src_uid": "dceeb739a56bb799550138aa8c127996"} {"source_code": "//package codeforces.contest1139\nimport scala.collection.immutable.TreeSet\n\nobject EdgyTrees {\n type Graph = Map[Int, Set[Int]]\n\n def addBidirectionalEdge(graph: Graph, x: Int, y: Int, color: Boolean): Graph = {\n val setX: Set[Int] = graph.getOrElse(x, Set())\n val setY: Set[Int] = graph.getOrElse(y, Set())\n\n graph + (x -> (setX + y)) + (y -> (setY + x))\n }\n\n def addSingleVertices(graph: Graph, v: List[Int]): Graph = {\n v.foldLeft(graph)((g, v) => g + (v -> g.getOrElse(v, Set())))\n }\n\n def connectedVertexSet(v: Int, p: Int, set: Set[Int])(implicit graph: Graph): Set[Int] = {\n graph.get(v).map(neighbors => neighbors.filter(_ != p).foldLeft(set + v)((res, neighbor) => connectedVertexSet(neighbor, v, res)))\n .getOrElse(set + v)\n }\n\n// def connectedComponentSizesList(graph: Graph): List[Int] = {\n// graph.keySet.foldLeft((TreeSet[Int](), List[Int]())) {\n// case ((visited: Set[Int], result: List[Int]), root: Int) =>\n// if (!visited(root)) {\n// val vertexSet = connectedVertexSet(root, -1, Set[Int]())(graph)\n// (visited ++ vertexSet, vertexSet.size :: result)\n// } else\n// (visited, result)\n// }._2\n// }\n\n def connectedComponentSizesList(graph: Graph): List[Int] = {\n val visited = collection.mutable.Set[Int]()\n graph.keySet.foldLeft(List[Int]()) {\n case (result: List[Int], root: Int) =>\n if (!visited(root)) {\n // val vertexSet = collection.mutable.Set[Int](root)\n // connectedVertexSet(root, -1)(graph, vertexSet)\n val vertexSet = connectedVertexSet(root, -1, Set[Int]())(graph)\n visited ++= vertexSet\n vertexSet.size :: result\n } else result\n }\n }\n\n def power(n: Int, k: Int, mod: Int): Int = {\n (1 to k).foldLeft(1l)((res, _) => (res * n) % mod).toInt\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { case (graph: Graph, _) =>\n val Array(x, y, color) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val g = addSingleVertices(graph, List(x, y))\n if (color == 0)\n addBidirectionalEdge(g, x, y, color == 1)\n else\n g\n }\n\n val connectedComponentsSizes = connectedComponentSizesList(graph)\n\n val mod = 1000000007\n\n val result = power(n, k, mod) - connectedComponentsSizes.foldLeft(0l)((res, size) => (res + power(size, k, mod)) % mod) // n^k - sigma p^k\n\n println(if (result < 0) result + mod else result)\n }\n}\n", "positive_code": [{"source_code": "//package codeforces.contest1139\n\nobject EdgyTrees {\n type Graph = Map[Int, Set[Int]]\n\n def addBidirectionalEdge(graph: Graph, x: Int, y: Int, color: Boolean): Graph = {\n val setX: Set[Int] = graph.getOrElse(x, Set())\n val setY: Set[Int] = graph.getOrElse(y, Set())\n\n graph + (x -> (setX + y)) + (y -> (setY + x))\n }\n\n def addSingleVertices(graph: Graph, v: List[Int]): Graph = {\n v.foldLeft(graph)((g, v) => g + (v -> g.getOrElse(v, Set())))\n }\n\n\n def connectedVertexSet(root: Int, graph: Graph): Set[Int] = {\n def connectedVertexSet(v: Int, p: Int)(implicit set: collection.mutable.Set[Int]): Unit= {\n for {\n neighbors <- graph.get(v)\n neighbor <- neighbors\n if neighbor != p\n } {\n set += neighbor\n connectedVertexSet(neighbor, v)\n }\n }\n\n val result = collection.mutable.Set[Int](root)\n connectedVertexSet(root, -1)(result)\n result.toSet\n }\n\n def connectedComponentSizesList(graph: Graph): List[Int] = {\n val visited = collection.mutable.Set[Int]()\n graph.keySet.foldLeft(List[Int]()) {\n case (result: List[Int], root: Int) =>\n if (!visited(root)) {\n val vertexSet = connectedVertexSet(root, graph)\n visited ++= vertexSet\n vertexSet.size :: result\n } else result\n }\n }\n\n\n def power(n: Int, k: Int, mod: Int): Int = {\n (1 to k).foldLeft(1l)((res, _) => (res * n) % mod).toInt\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { case (graph: Graph, _) =>\n val Array(x, y, color) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val g = addSingleVertices(graph, List(x, y))\n if (color == 0)\n addBidirectionalEdge(g, x, y, color == 1)\n else\n g\n }\n\n val connectedComponentsSizes = connectedComponentSizesList(graph)\n\n val mod = 1000000007\n\n val result = power(n, k, mod) - connectedComponentsSizes.foldLeft(0l)((res, size) => (res + power(size, k, mod)) % mod) // n^k - sigma p^k\n\n println(if (result < 0) result + mod else result)\n }\n}\n"}, {"source_code": "//package codeforces.contest1139\n\nobject EdgyTrees {\n type Graph = Map[Int, Set[Int]]\n\n def addBidirectionalEdge(graph: Graph, x: Int, y: Int, color: Boolean): Graph = {\n val setX: Set[Int] = graph.getOrElse(x, Set())\n val setY: Set[Int] = graph.getOrElse(y, Set())\n\n graph + (x -> (setX + y)) + (y -> (setY + x))\n }\n\n def addSingleVertices(graph: Graph, v: List[Int]): Graph = {\n v.foldLeft(graph)((g, v) => g + (v -> g.getOrElse(v, Set())))\n }\n\n def connectedVertexSet(v: Int, p: Int)(implicit graph: Graph, set: collection.mutable.Set[Int]): Unit = {\n for {\n neighbors <- graph.get(v)\n neighbor <- neighbors\n if neighbor != p\n } {\n set += neighbor\n connectedVertexSet(neighbor, v)\n }\n }\n\n def connectedComponentSizesList(graph: Graph): List[Int] = {\n val visited = collection.mutable.Set[Int]()\n graph.keySet.foldLeft(List[Int]()) {\n case (result: List[Int], root: Int) =>\n if (!visited(root)) {\n val vertexSet = collection.mutable.Set[Int](root)\n connectedVertexSet(root, -1)(graph, vertexSet)\n visited ++= vertexSet\n vertexSet.size :: result\n } else result\n }\n }\n\n def power(n: Int, k: Int, mod: Int): Int = {\n (1 to k).foldLeft(1l)((res, _) => (res * n) % mod).toInt\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { case (graph: Graph, _) =>\n val Array(x, y, color) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val g = addSingleVertices(graph, List(x, y))\n if (color == 0)\n addBidirectionalEdge(g, x, y, color == 1)\n else\n g\n }\n\n val connectedComponentsSizes = connectedComponentSizesList(graph)\n\n val mod = 1000000007\n\n val result = power(n, k, mod) - connectedComponentsSizes.foldLeft(0l)((res, size) => (res + power(size, k, mod)) % mod) // n^k - sigma p^k\n\n println(if (result < 0) result + mod else result)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n import java.util.Arrays\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val uf = new UnionFind(N)\n REP(N - 1) { _ =>\n val from, to = ni() - 1\n val c = ni()\n if (c == 0) uf.unite(from, to)\n }\n\n val C = Array.ofDim[Int](N)\n REP(N) { i =>\n C(uf.find(i)) += 1\n }\n\n var minus = 0L\n REP(N) { i =>\n if (C(i) > 0) {\n // longを超えないだろ\n minus += powMod(C(i), K, MOD)\n }\n }\n\n val ans = (MOD + powMod(N, K, MOD) - minus % MOD) % MOD\n out.println(ans)\n }\n\n def powMod(x: Int, n: Int, m: Int): Int = {\n def step(x: Long, n: Int, stack: Long): Long = {\n n match {\n case 0 => stack\n case _ => step(x * x % m, n / 2, if (n % 2 == 1) stack * x % m else stack)\n }\n }\n step(x, n, 1).toInt\n }\n\n\n class UnionFind(val n: Int) {\n private val par = Array.ofDim[Int](n)\n REP(n) (i => par(i) = i)\n val rank: Array[Int] = Array.fill[Int](n)(1) // 集合の要素数\n private val visits = Array.ofDim[Int](n) // 訪れた場所をfind毎に用意するのがもったいないのでつかいまわす\n\n def find(x: Int): Int = {\n var ptr = 0\n def step(x: Int): Int = {\n if (par(x) == x) x\n else {\n visits(ptr) = x\n ptr += 1\n step(par(x))\n }\n }\n\n val res = step(x)\n REP(ptr){ i => par(visits(i)) = res }\n res\n }\n\n def unite(x: Int, y: Int): Int = {\n val x1 = find(x)\n val y1 = find(y)\n if (x1 == y1) x1\n else {\n if (rank(x1) < rank(y)) {\n par(x1) = y1\n y1\n } else {\n par(y1) = x1\n if (rank(x1) == rank(y1)) rank(x1) += rank(y1)\n x1\n }\n }\n }\n\n /**\n * xを解決する必要がないときは直にrankをみる\n */\n def cntNodes(x: Int): Int = rank(find(x))\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}, {"source_code": "//package codeforces.contest1139\n\nobject EdgyTrees {\n type Graph = Map[Int, Set[Int]]\n\n def addBidirectionalEdge(graph: Graph, x: Int, y: Int, color: Boolean): Graph = {\n val setX: Set[Int] = graph.getOrElse(x, Set())\n val setY: Set[Int] = graph.getOrElse(y, Set())\n\n graph + (x -> (setX + y)) + (y -> (setY + x))\n }\n\n def addSingleVertices(graph: Graph, v: List[Int]): Graph = {\n v.foldLeft(graph)((g, v) => g + (v -> g.getOrElse(v, Set())))\n }\n\n def connectedVertexSet(v: Int, p: Int)(implicit graph: Graph, set: collection.mutable.Set[Int]): Unit = {\n for {\n neighbors <- graph.get(v)\n neighbor <- neighbors\n if neighbor != p\n } {\n set += neighbor\n connectedVertexSet(neighbor, v)\n }\n }\n\n def connectedVertexSet(v: Int, p: Int, set: Set[Int])(implicit graph: Graph): Set[Int] = {\n graph.get(v).map(neighbors => neighbors.filter(_ != p).foldLeft(set + v)((res, neighbor) => connectedVertexSet(neighbor, v, res)))\n .getOrElse(set + v)\n }\n\n def connectedComponentSizesList(graph: Graph): List[Int] = {\n val visited = collection.mutable.Set[Int]()\n graph.keySet.foldLeft(List[Int]()) {\n case (result: List[Int], root: Int) =>\n if (!visited(root)) {\n // val vertexSet = collection.mutable.Set[Int](root)\n // connectedVertexSet(root, -1)(graph, vertexSet)\n val vertexSet = connectedVertexSet(root, -1, Set[Int]())(graph)\n visited ++= vertexSet\n vertexSet.size :: result\n } else result\n }\n }\n\n def power(n: Int, k: Int, mod: Int): Int = {\n (1 to k).foldLeft(1l)((res, _) => (res * n) % mod).toInt\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { case (graph: Graph, _) =>\n val Array(x, y, color) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val g = addSingleVertices(graph, List(x, y))\n if (color == 0)\n addBidirectionalEdge(g, x, y, color == 1)\n else\n g\n }\n\n val connectedComponentsSizes = connectedComponentSizesList(graph)\n\n val mod = 1000000007\n\n val result = power(n, k, mod) - connectedComponentsSizes.foldLeft(0l)((res, size) => (res + power(size, k, mod)) % mod) // n^k - sigma p^k\n\n println(if (result < 0) result + mod else result)\n }\n}\n"}, {"source_code": "//package codeforces.contest1139\n\nobject EdgyTrees {\n type Graph = Map[Int, Set[Int]]\n\n def addBidirectionalEdge(graph: Graph, x: Int, y: Int, color: Boolean): Graph = {\n val setX: Set[Int] = graph.getOrElse(x, Set())\n val setY: Set[Int] = graph.getOrElse(y, Set())\n\n graph + (x -> (setX + y)) + (y -> (setY + x))\n }\n\n def addSingleVertices(graph: Graph, v: List[Int]): Graph = {\n v.foldLeft(graph)((g, v) => g + (v -> g.getOrElse(v, Set())))\n }\n\n def connectedVertexSet(v: Int, p: Int)(implicit graph: Graph, set: collection.mutable.Set[Int]): Unit = {\n for {\n neighbors <- graph.get(v)\n neighbor <- neighbors\n if neighbor != p\n } {\n set += neighbor\n connectedVertexSet(neighbor, v)\n }\n }\n\n def connectedComponentSizesList(graph: Graph): List[Int] = {\n val visited = collection.mutable.Set[Int]()\n graph.keySet.foldLeft(List[Int]()) {\n case (result: List[Int], root: Int) =>\n if (!visited(root)) {\n val vertexSet = collection.mutable.Set[Int](root)\n connectedVertexSet(root, -1)(graph, vertexSet)\n visited ++= vertexSet\n vertexSet.size :: result\n } else result\n }\n }\n\n def power(n: Int, k: Int, mod: Int): Int = {\n (1 to k).foldLeft(1l)((res, _) => (res * n) % mod).toInt\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine().split(\" \").map(_.toInt)\n\n // val graph = collection.mutable.Map[Int, Set[Int]]()\n //\n // 1 until n foreach (_ => {\n // val Array(x, y, color) = io.StdIn.readLine().split(\" \").map(_.toInt)\n // graph += (x -> graph.getOrElse(x, Set())) += (y -> graph.getOrElse(y, Set()))\n //\n // if (color == 0) {\n // val setX: Set[Int] = graph.getOrElse(x, Set())\n // val setY: Set[Int] = graph.getOrElse(y, Set())\n //\n // graph += (x -> (setX + y)) += (y -> (setY + x))\n // }\n //\n // })\n\n val graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { case (graph: Graph, _) =>\n val Array(x, y, color) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val g = addSingleVertices(graph, List(x, y))\n if (color == 0)\n addBidirectionalEdge(g, x, y, color == 1)\n else\n g\n }\n\n val connectedComponentsSizes = connectedComponentSizesList(graph.toMap)\n\n val mod = 1000000007\n\n val result = power(n, k, mod) - connectedComponentsSizes.foldLeft(0l)((res, size) => (res + power(size, k, mod)) % mod) // n^k - sigma p^k\n\n println(if (result < 0) result + mod else result)\n }\n}\n"}, {"source_code": "//package codeforces.contest1139\n\nobject EdgyTrees {\n type Graph = Map[Int, Set[Int]]\n\n def connectedVertexSet(v: Int, p: Int)(implicit graph: Graph, set: collection.mutable.Set[Int]): Unit = {\n for {\n neighbors <- graph.get(v)\n neighbor <- neighbors\n if neighbor != p\n } {\n set += neighbor\n connectedVertexSet(neighbor, v)\n }\n }\n\n def connectedComponentSizesList(graph: Graph): List[Int] = {\n val visited = collection.mutable.Set[Int]()\n graph.keySet.foldLeft(List[Int]()) {\n case (result: List[Int], root: Int) =>\n if (!visited(root)) {\n val vertexSet = collection.mutable.Set[Int](root)\n connectedVertexSet(root, -1)(graph, vertexSet)\n visited ++= vertexSet\n vertexSet.size :: result\n } else result\n }\n }\n\n def power(n: Int, k: Int, mod: Int): Int = {\n (1 to k).foldLeft(1l)((res, _) => (res * n) % mod).toInt\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val graph = collection.mutable.Map[Int, Set[Int]]()\n\n 1 until n foreach (_ => {\n val Array(x, y, color) = io.StdIn.readLine().split(\" \").map(_.toInt)\n graph += (x -> graph.getOrElse(x, Set())) += (y -> graph.getOrElse(y, Set()))\n\n if (color == 0) {\n val setX: Set[Int] = graph.getOrElse(x, Set())\n val setY: Set[Int] = graph.getOrElse(y, Set())\n\n graph += (x -> (setX + y)) += (y -> (setY + x))\n }\n\n })\n\n // (1 until n).foldLeft(graph) { case (graph: Graph, _) =>\n // val Array(x, y, color) = io.StdIn.readLine().split(\" \").map(_.toInt)\n // val g = addSingleVertices(graph, List(x, y))\n // if (color == 0)\n // addBidirectionalEdge(g, x, y, color == 1)\n // else\n // g\n // }\n\n val connectedComponentsSizes = connectedComponentSizesList(graph.toMap)\n\n val mod = 1000000007\n\n val result = power(n, k, mod) - connectedComponentsSizes.foldLeft(0l)((res, size) => (res + power(size, k, mod)) % mod) // n^k - sigma p^k\n\n println(if (result < 0) result + mod else result)\n }\n}\n"}, {"source_code": "//package codeforces.contest1139\n\nobject EdgyTrees {\n type Graph = Map[Int, Set[Int]]\n\n def addBidirectionalEdge(graph: Graph, x: Int, y: Int, color: Boolean): Graph = {\n val setX: Set[Int] = graph.getOrElse(x, Set())\n val setY: Set[Int] = graph.getOrElse(y, Set())\n\n graph + (x -> (setX + y)) + (y -> (setY + x))\n }\n\n def addSingleVertices(graph: Graph, v: List[Int]): Graph = {\n v.foldLeft(graph)((g, v) => g + (v -> g.getOrElse(v, Set())))\n }\n\n def connectedComponentSizesList(graph: Graph): List[Int] = {\n val visited = collection.mutable.Set[Int]()\n graph.keySet.foldLeft(List[Int]()) {\n case (result: List[Int], root: Int) =>\n if (!visited(root)) {\n val vertexSet = connectedVertexSet(root, graph)\n visited ++= vertexSet\n vertexSet.size :: result\n } else result\n }\n }\n\n def connectedVertexSet(v: Int, graph: Graph): Set[Int] = {\n def connectedVertexSet(v: Int, p: Int, set: Set[Int] = Set()): Set[Int] =\n graph.get(v).map(_.filter(_ != p).foldLeft(set + v)((res, neighbor) => connectedVertexSet(neighbor, v, res))).getOrElse(set + v)\n\n connectedVertexSet(v, -1)\n }\n\n def power(n: Int, k: Int, mod: Int): Int = {\n (1 to k).foldLeft(1l)((res, _) => (res * n) % mod).toInt\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { case (graph: Graph, _) =>\n val Array(x, y, color) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val g = addSingleVertices(graph, List(x, y))\n if (color == 0)\n addBidirectionalEdge(g, x, y, color == 1)\n else\n g\n }\n\n val connectedComponentsSizes = connectedComponentSizesList(graph)\n\n val mod = 1000000007\n\n val result = power(n, k, mod) - connectedComponentsSizes.foldLeft(0l)((res, size) => (res + power(size, k, mod)) % mod) // n^k - sigma p^k\n\n println(if (result < 0) result + mod else result)\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contest1139\n\nobject EdgyTrees {\n type Graph = Map[Int, Set[Int]]\n\n def addBidirectionalEdge(graph: Graph, x: Int, y: Int, color: Boolean): Graph = {\n val setX: Set[Int] = graph.getOrElse(x, Set())\n val setY: Set[Int] = graph.getOrElse(y, Set())\n\n graph + (x -> (setX + y)) + (y -> (setY + x))\n }\n\n def addSingleVertices(graph: Graph, v: List[Int]): Graph = {\n v.foldLeft(graph)((g, v) => g + (v -> g.getOrElse(v, Set())))\n }\n\n\n def connectedVertexSet(v: Int, graph: Graph): Set[Int] = {\n def connectedVertexSet(v: Int, p: Int)(implicit set: collection.mutable.Set[Int]): Unit= {\n for {\n neighbors <- graph.get(v)\n neighbor <- neighbors\n if neighbor != p\n } {\n set += neighbor\n connectedVertexSet(neighbor, v)\n }\n }\n\n val result = collection.mutable.Set[Int]()\n connectedVertexSet(v, -1)(result)\n result.toSet\n }\n\n def connectedComponentSizesList(graph: Graph): List[Int] = {\n val visited = collection.mutable.Set[Int]()\n graph.keySet.foldLeft(List[Int]()) {\n case (result: List[Int], root: Int) =>\n if (!visited(root)) {\n val vertexSet = connectedVertexSet(root, graph)\n visited ++= vertexSet\n vertexSet.size :: result\n } else result\n }\n }\n\n\n def power(n: Int, k: Int, mod: Int): Int = {\n (1 to k).foldLeft(1l)((res, _) => (res * n) % mod).toInt\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { case (graph: Graph, _) =>\n val Array(x, y, color) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val g = addSingleVertices(graph, List(x, y))\n if (color == 0)\n addBidirectionalEdge(g, x, y, color == 1)\n else\n g\n }\n\n val connectedComponentsSizes = connectedComponentSizesList(graph)\n\n val mod = 1000000007\n\n val result = power(n, k, mod) - connectedComponentsSizes.foldLeft(0l)((res, size) => (res + power(size, k, mod)) % mod) // n^k - sigma p^k\n\n println(if (result < 0) result + mod else result)\n }\n}\n"}], "src_uid": "94559f08866b6136ba4791c440025a68"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject D extends App {\n\tdef pred(x: Int) = (for (e <- f) yield e / x).sum >= k\n\n\tdef binSearch(pred: Int => Boolean, a: Int, b: Int) = {\n\t\tvar st = a\n\t\tvar nd = b\n\t\tvar ans = 0\n\n\t\twhile (st <= nd) {\n\t\t\tval mid = (st + nd) / 2\n\n\t\t\tif (pred(mid)) {\n\t\t\t\tans = ans max mid\n\t\t\t\tst = mid + 1\n\t\t\t}\n\n\t\t\telse nd = mid - 1\n\t\t}\n\n\t\tans\n\t}\n\n\tval MAX = 2 * 100000\n\n\tval n = InputReader.nextInt\n\tvar k = InputReader.nextInt\n\tval arr = InputReader.readLine.split(\" \").map(_.toInt)\n\n\tvar f = Array.fill(MAX + 1)(0)\n\t\n\tfor (e <- arr) f(e) += 1\n\n\tval ans = binSearch(pred, 1, n)\n\n\tfor(i <- 1 to MAX) f(i) /= ans\n\n\tval out = new PrintWriter(System.out)\n\n\tfor {\n\t\te <- arr\n\t\tif f(e) > 0\n\t\tif k > 0\n\t} {\n\t\tout.print(s\"$e \")\n\t\tf(e) -= 1\n\t\tk -= 1\n\t}\n\n\tout.close\n} \n\nobject InputReader {\n\tval rd = new BufferedReader(new InputStreamReader(System.in), 32768);\n\tvar tk = new StringTokenizer(\"\")\n\n\tdef read() = {\n\t\twhile (!tk.hasMoreTokens)\n\t\t\ttk = new StringTokenizer(readLine)\n\n\t\ttk.nextToken\n\t}\n\n\tdef readLine() = rd.readLine\n\tdef nextInt() = read.toInt\n\tdef nextLong() = read.toLong\n\tdef nextDouble() = read.toDouble\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject D extends App {\n\tdef pred(x: Int) = (for (e <- f) yield e / x).sum >= k\n\n\tdef binSearch(pred: Int => Boolean, a: Int, b: Int) = {\n\t\tvar st = a\n\t\tvar nd = b\n\t\tvar ans = 0\n\n\t\twhile (st <= nd) {\n\t\t\tval mid = (st + nd) / 2\n\n\t\t\tif (pred(mid)) {\n\t\t\t\tans = ans max mid\n\t\t\t\tst = mid + 1\n\t\t\t}\n\n\t\t\telse nd = mid - 1\n\t\t}\n\n\t\tans\n\t}\n\n\tval MAX = 2 * 100000\n\n\tval n = InputReader.nextInt\n\tvar k = InputReader.nextInt\n\tval arr = InputReader.readLine.split(\" \").map(_.toInt)\n\n\tvar f = Array.fill(MAX + 1)(0)\n\t\n\tfor (e <- arr) f(e) += 1\n\n\tval ans = binSearch(pred, 1, n)\n\n\tfor(i <- 1 to MAX) f(i) /= ans\n\n\tval out = new PrintWriter(System.out)\n\n\tfor {\n\t\te <- arr\n\t\tif f(e) > 0\n\t\tif k > 0\n\t} {\n\t\tout.print(s\"$e \")\n\t\tf(e) -= 1\n\t\tk -= 1\n\t}\n\n\tout.close\n}\n\nobject InputReader {\n\tval rd = new BufferedReader(new InputStreamReader(System.in), 32768);\n\tvar tk = new StringTokenizer(\"\")\n\n\tdef read() = {\n\t\twhile (!tk.hasMoreTokens)\n\t\t\ttk = new StringTokenizer(readLine)\n\n\t\ttk.nextToken\n\t}\n\n\tdef readLine() = rd.readLine\n\tdef nextInt() = read.toInt\n\tdef nextLong() = read.toLong\n\tdef nextDouble() = read.toDouble\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject D extends App {\n\tdef pred(x: Int) = (for (e <- f) yield e / x).sum >= k\n\n\tdef binSearch(pred: Int => Boolean, a: Int, b: Int) = {\n\t\tvar st = a\n\t\tvar nd = b\n\t\tvar ans = 0\n\n\t\twhile (st <= nd) {\n\t\t\tval mid = (st + nd) / 2\n\n\t\t\tif (pred(mid)) {\n\t\t\t\tans = ans max mid\n\t\t\t\tst = mid + 1\n\t\t\t}\n\n\t\t\telse nd = mid - 1\n\t\t}\n\n\t\tans\n\t}\n\n\tdef constructAnswer(x: Int) = {\n\t\tval arr = Array.fill(k)(0)\n\t\tvar p = 0\n\n\t\tfor ((e, i) <- f.zipWithIndex) {\n\t\t\tvar v = e / x\n\n\t\t\twhile (p < k && v > 0) {\n\t\t\t\tarr(p) = i\n\t\t\t\tp += 1\n\t\t\t\tv -= 1\n\t\t\t}\n\t\t}\n\n\t\tarr\n\t}\n\n\tval MAX = 2 * 100000\n\n\tval n = InputReader.nextInt\n\tval k = InputReader.nextInt\n\tval arr = InputReader.readLine.split(\" \").map(_.toInt)\n\n\tval f = Array.fill(MAX + 1)(0)\n\t\n\tfor (e <- arr) f(e) += 1\n\n\tval ans = binSearch(pred, 1, n)\n\n\tval out = new PrintWriter(System.out)\n\tconstructAnswer(ans).foreach(x => out.print(s\"$x \"))\n\tout.close\n}\n\nobject InputReader {\n\tval rd = new BufferedReader(new InputStreamReader(System.in), 32768);\n\tvar tk = new StringTokenizer(\"\")\n\n\tdef read() = {\n\t\twhile (!tk.hasMoreTokens)\n\t\t\ttk = new StringTokenizer(readLine)\n\n\t\ttk.nextToken\n\t}\n\n\tdef readLine() = rd.readLine\n\tdef nextInt() = read.toInt\n\tdef nextLong() = read.toLong\n\tdef nextDouble() = read.toDouble\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject D extends App {\n\tdef pred(x: Int) = (for (e <- f) yield e / x).sum >= k\n\n\tdef binSearch(pred: Int => Boolean, a: Int, b: Int) = {\n\t\tvar st = a\n\t\tvar nd = b\n\t\tvar ans = 0\n\n\t\twhile (st <= nd) {\n\t\t\tval mid = (st + nd) / 2\n\n\t\t\tif (pred(mid)) {\n\t\t\t\tans = ans max mid\n\t\t\t\tst = mid + 1\n\t\t\t}\n\n\t\t\telse nd = mid - 1\n\t\t}\n\n\t\tans\n\t}\n\n\tdef constructAnswer(x: Int) = {\n\t\tval arr = Array.fill(k)(0)\n\t\tvar p = 0\n\n\t\tfor ((e, i) <- f.zipWithIndex) {\n\t\t\tvar v = e / x\n\n\t\t\twhile (p < k && v > 0) {\n\t\t\t\tarr(p) = i\n\t\t\t\tp += 1\n\t\t\t\tv -= 1\n\t\t\t}\n\t\t}\n\n\t\tarr\n\t}\n\n\tval MAX = 2 * 100000\n\n\tval n = InputReader.nextInt\n\tval k = InputReader.nextInt\n\tval arr = InputReader.readLine.split(\" \").map(_.toInt)\n\n\tval f = Array.fill(MAX + 1)(0)\n\t\n\tfor (e <- arr) f(e) += 1\n\n\tval ans = binSearch(pred, 1, n)\n\n\tconstructAnswer(ans).foreach(x => print(s\"$x \"))\n}\n\nobject InputReader {\n\tval rd = new BufferedReader(new InputStreamReader(System.in), 32768);\n\tvar tk = new StringTokenizer(\"\")\n\n\tdef read() = {\n\t\twhile (!tk.hasMoreTokens)\n\t\t\ttk = new StringTokenizer(readLine)\n\n\t\ttk.nextToken\n\t}\n\n\tdef readLine() = rd.readLine\n\tdef nextInt() = read.toInt\n\tdef nextLong() = read.toLong\n\tdef nextDouble() = read.toDouble\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject D extends App {\n\tdef pred(x: Int) = (for (e <- f) yield e / x).sum >= k\n\n\tdef binSearch(pred: Int => Boolean, a: Int, b: Int) = {\n\t\tvar st = a\n\t\tvar nd = b\n\t\tvar ans = 0\n\n\t\twhile (st <= nd) {\n\t\t\tval mid = (st + nd) / 2\n\n\t\t\tif (pred(mid)) {\n\t\t\t\tans = ans max mid\n\t\t\t\tst = mid + 1\n\t\t\t}\n\n\t\t\telse nd = mid - 1\n\t\t}\n\n\t\tans\n\t}\n\n\tdef constructAnswer(x: Int) = {\n\t\tval arr = Array.fill(k)(0)\n\t\tvar p = 0\n\n\t\tfor ((e, i) <- f.zipWithIndex) {\n\t\t\tvar v = e / x\n\n\t\t\twhile (p < k && v > 0) {\n\t\t\t\tarr(p) = i\n\t\t\t\tp += 1\n\t\t\t\tv -= 1\n\t\t\t}\n\t\t}\n\n\t\tarr\n\t}\n\n\tval MAX = 2 * 100000\n\n\tval n = InputReader.nextInt\n\tval k = InputReader.nextInt\n\tval arr = InputReader.readLine.split(\" \").map(_.toInt)\n\n\tval f = Array.fill(MAX + 1)(0)\n\t\n\tfor (e <- arr) f(e) += 1\n\n\tval ans = binSearch(pred, 1, n)\n\n\tval out = new PrintWriter(System.out)\n\tout.println(constructAnswer(ans).mkString(\" \"))\n\tout.close\n}\n\nobject InputReader {\n\tval rd = new BufferedReader(new InputStreamReader(System.in), 32768);\n\tvar tk = new StringTokenizer(\"\")\n\n\tdef read() = {\n\t\twhile (!tk.hasMoreTokens)\n\t\t\ttk = new StringTokenizer(readLine)\n\n\t\ttk.nextToken\n\t}\n\n\tdef readLine() = rd.readLine\n\tdef nextInt() = read.toInt\n\tdef nextLong() = read.toLong\n\tdef nextDouble() = read.toDouble\n}"}, {"source_code": "object CF_521_3_D {\n def solve(n: Int, k: Int, ss: Seq[Int]): Seq[Int] = {\n val counts: Map[Int, Int] = ss.groupBy(identity).mapValues(_.size)\n // sort biggest first so we can stop early\n val ordered = counts.toSeq.sortWith(_._2 > _._2).toStream\n // `trial` is the number of copies of t. Start with 1 and increase until it's not possible to build such a Seq\n // It's possible if we can find k or more elements that have enough copies.\n def isPossible(trial: Int, xs: Seq[(Int, Int)], found: Int, out: Seq[Int]): Option[Seq[Int]] =\n if(found >= k) Some(out.take(k))\n else if(xs.isEmpty) None\n else {\n val (e, c) = xs.head\n // instances is the number of instances of xs.head we'll use\n val instances = c/trial\n if (instances < 1) None\n else {\n val add = Seq.fill(instances)(e)\n isPossible(trial, xs.tail, found + instances, out ++ add)\n }\n }\n def find(trial: Int, best: Seq[Int]): Seq[Int] = {\n val poss = isPossible(trial, ordered, 0, Vector.empty)\n poss match {\n case None => best\n case Some(seq) => find(trial + 1, seq)\n }\n }\n\n find(1,Seq.empty)\n }\n\n // Specify Input and Output formats here:\n def formatIn(i: Input) = (i.int, i.int, {i.nextLine; i.intSeq})\n def formatOut(out: Seq[Int]) = out.mkString(\" \")\n\n// ~~~ Boilerplate that doesn't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n def main(args: Array[String]) = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n\n// ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n import java.util.Scanner\n class Input(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine() \n // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def solveVals = (solve _).tupled(formatIn(this))\n def solveStr = formatOut(solveVals)\n }\n\n def ceil(a: Int, b: Int) = (a - 1) / b + 1\n def ceil(a: Long, b: Long) = (a - 1) / b + 1\n\n import language.implicitConversions\n implicit def stringToInput(s: String): Input = new Input(s)\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val S = na(N)\n val C = Array.ofDim[Int](2e5.toInt + 1)\n rep(N) { i =>\n C(S(i)) += 1\n }\n\n case class Elm(cnt: Int, num: Int) extends Comparable[Elm] {\n override def compareTo(o: Elm): Int = Integer.compare(o.cnt, cnt) // desc\n }\n\n val queue = new java.util.PriorityQueue[Elm]()\n rep(C.length) { i =>\n if (C(i) > 0) queue.add(Elm(C(i), i))\n }\n\n val times = Array.ofDim[Int](2e5.toInt + 1)\n val ans = ArrayBuffer[Int]()\n while (ans.length < K) {\n val a = queue.poll()\n ans += a.num\n times(a.num) += 1\n queue.add(Elm(C(a.num) / (times(a.num) + 1) , a.num))\n }\n\n out.println(ans.mkString(\" \"))\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject D extends App {\n\tdef pred(x: Int) = (for (e <- f) yield e / x).sum >= k\n\n\tdef binSearch(pred: Int => Boolean, a: Int, b: Int) = {\n\t\tvar st = a\n\t\tvar nd = b\n\t\tvar ans = 0\n\n\t\twhile (st <= nd) {\n\t\t\tval mid = (st + nd) / 2\n\n\t\t\tif (pred(mid)) {\n\t\t\t\tans = ans max mid\n\t\t\t\tst = mid + 1\n\t\t\t}\n\n\t\t\telse nd = mid - 1\n\t\t}\n\n\t\tans\n\t}\n\n\tval MAX = 2 * 100000\n\n\tval n = InputReader.nextInt\n\tvar k = InputReader.nextInt\n\tval arr = InputReader.readLine.split(\" \").map(_.toInt)\n\n\tvar f = Array.fill(MAX + 1)(0)\n\t\n\tfor (e <- arr) f(e) += 1\n\n\tval ans = binSearch(pred, 1, n)\n\n\tf = f.map(_ / ans)\n\n\tval out = new PrintWriter(System.out)\n\n\tfor(e <- arr) {\n\t\tif(f(e) > 0 && k > 0) {\n\t\t\tout.print(s\"$e \")\n\t\t\tf(e) -= 1\n\t\t\tk -= 1\n\t\t}\n\t}\n\n\tout.close\n}\n\nobject InputReader {\n\tval rd = new BufferedReader(new InputStreamReader(System.in), 32768);\n\tvar tk = new StringTokenizer(\"\")\n\n\tdef read() = {\n\t\twhile (!tk.hasMoreTokens)\n\t\t\ttk = new StringTokenizer(readLine)\n\n\t\ttk.nextToken\n\t}\n\n\tdef readLine() = rd.readLine\n\tdef nextInt() = read.toInt\n\tdef nextLong() = read.toLong\n\tdef nextDouble() = read.toDouble\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val S = na(N)\n val C = Array.ofDim[Int](2e5.toInt + 1)\n rep(N) { i =>\n C(S(i)) += 1\n }\n\n case class Elm(cnt: Int, num: Int) extends Comparable[Elm] {\n override def compareTo(o: Elm): Int = Integer.compare(o.cnt, cnt) // desc\n }\n\n val queue = new java.util.PriorityQueue[Elm]()\n rep(C.length) { i =>\n if (C(i) > 0) queue.add(Elm(C(i), i))\n }\n\n val times = Array.ofDim[Int](2e5.toInt + 1)\n val ans = ArrayBuffer[Int]()\n while (ans.length < K) {\n val a = queue.poll()\n ans += a.num\n times(a.num) += 1\n queue.add(Elm(a.cnt / (times(a.num) + 1) , a.num))\n }\n\n out.println(ans.mkString(\" \"))\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "cfccf06c4d0de89bf0978dc6512265c4"} {"source_code": "\n\nobject ProblemB extends App {\n\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n for (_ <- 1 to t) {\n val m = in.nextInt()\n val s = in.nextToken()\n var hasOne = false\n var onePosition = -1\n var lastZero = -1\n\n\n for (i <- 0 until s.length) {\n if (s(i) == '0' && hasOne) {\n lastZero = i\n } else if (s(i) == '1' && !hasOne) {\n hasOne = true\n onePosition = i\n }\n }\n\n val res = if (hasOne && lastZero != -1) {\n s.take(onePosition) + s.takeRight(s.length - lastZero)\n } else {\n s\n }\n\n println(res)\n }\n\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.io.StdIn\n\nobject Main {\n object Scanner {\n private var st: StringTokenizer = _\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(StdIn.readLine())\n }\n st.nextToken()\n }\n\n def nextInt: Int = nextToken().toInt\n def nextLong: Long = nextToken().toLong\n def nextShort: Short = nextToken().toShort\n def nextByte: Byte = nextToken().toByte\n }\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to Scanner.nextInt) {\n val n = Scanner.nextInt\n val s = StdIn.readLine()\n var m1 = 0\n while (m1 < n && s(m1) == '0') {\n m1 += 1\n }\n var m2 = 0\n while (m2 < n && s(n - m2 - 1) == '1') {\n m2 += 1\n }\n if (m1 + m2 == n) {\n println(s)\n } else {\n for (_ <- 1 to m1) {\n print('0')\n }\n print('0')\n for (_ <- 1 to m2) {\n print('1')\n }\n println()\n }\n }\n }\n}"}], "negative_code": [], "src_uid": "bb071f1f4fc1c129a32064c1301f4942"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val kd = readLine().split(\" \").map(_.toInt)\n val k = kd(0)\n val d = kd(1)\n \n if (k == 1) println(d)\n else if (d == 0) println(\"No solution\")\n else println((Seq(d) ++ (1 to (k - 1)).map(_ => 0)).mkString)\n }\n}", "positive_code": [{"source_code": "import java.util.Scanner\n\n \nobject Sum {\n class Sum{\n def max(a:Char,b:Char):Char=\n if (a1) left-1 else 0\n val r=in.nextInt()\n var ans = arr(r-1)-arr(l)\n println(ans)\n }\n \n }\n \n def taskA_206(){\n val in=new Scanner(System.in)\n val k=in.nextInt()\n val v=in.nextInt()\n val b=if(k>1 && v==0) false else true\n if(b){\n print(v)\n for{i<-1 to k-1}print(0)\n }\n else\n print(\"No solution\")\n }\n def main(args: Array[String]) {\n taskA_206\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n var Array(k, d) = in.next().split(\" \").map(_.toInt)\n if (d == 0 && k > 1)\n println(\"No solution\")\n else {\n print(d)\n print(\"0\" * (k - 1))\n }\n\n}"}, {"source_code": "object A355 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(k, d) = readInts(2)\n if(d == 0 && k > 1)\n println(\"No solution\")\n else\n println((Array(d) ++ Array.fill(k-1)(0)).mkString(\"\"))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P355A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val K, D = sc.nextInt\n\n def solve(): Unit = {\n (K, D) match {\n case (1, 0) => out.println(0)\n case (_, 0) => out.println(\"No solution\")\n case _ => out.println(D.toString + \"0\" * (K - 1))\n }\n }\n\n solve\n out.close\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\n\n \nobject Sum {\n class Sum{\n def max(a:Char,b:Char):Char=\n if (a1) left-1 else 0\n val r=in.nextInt()\n var ans = arr(r-1)-arr(l)\n println(ans)\n }\n \n }\n \n def taskA_206(){\n val in=new Scanner(System.in)\n val k=in.nextInt()\n val v=in.nextInt()\n print(v)\n for{i<-1 to k-1}print(0)\n }\n def main(args: Array[String]) {\n taskA_206\n }\n}"}, {"source_code": "object A355 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(k, d) = readInts(2)\n if(d == 0)\n println(\"0\")\n else\n println((Array(d) ++ Array.fill(k-1)(0)).mkString(\"\"))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object A355 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(k, d) = readInts(2)\n println((Array(d) ++ Array.fill(k-1)(0)).mkString(\"\"))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P355A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val K, D = sc.nextInt\n\n def solve(): Unit = {\n\n @tailrec\n def loop(acc: Int, x: Int): Int = if (x == 1) acc\n else loop(acc * 10, x - 1)\n\n (K, D) match {\n case (1, 0) => out.println(0)\n case (_, 0) => out.println(\"No solution\")\n case _ => out.println(loop(D, K))\n }\n }\n\n solve\n out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val kd = readLine().split(\" \").map(_.toInt)\n val k = kd(0)\n val d = kd(1)\n \n if (k == 1) println(d)\n else if (d == 0) println((Seq(1, 9) ++ (1 to (k - 2)).map(_ => 0)).mkString)\n else println((Seq(d) ++ (1 to (k - 1)).map(_ => 0)).mkString)\n }\n}"}], "src_uid": "5dd0d518f315d81204b25e48fea0793a"} {"source_code": "import scala.io.StdIn._\n\nobject taskB extends App {\n\n\n val input: Array[Int] = readLine.split(\" \").map(_.toInt)\n // println(s\"${input(0)} ${input(1)} ${input(2)} ${input(3)}\")\n val sizeX = input(0)\n val sizeY = input(1)\n var locX = input(2)\n var locY = input(3)\n\n println(locX +\" \"+ locY)\n\n def visitWholeLine(): Unit = {\n (2 to sizeY).foreach {_ =>\n if (locY == sizeY) locY = 1\n else locY += 1\n println(locX +\" \"+ locY)\n }\n }\n\n visitWholeLine()\n (2 to sizeX).foreach { _ =>\n if (locX == sizeX) locX = 1\n else locX += 1\n println(locX +\" \"+ locY)\n\n visitWholeLine()\n }\n\n\n\n}\n\n\n\n\n\n", "positive_code": [{"source_code": "\nobject B extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val n = in.nextInt()\n val m = in.nextInt()\n val x1 = in.nextInt()\n val y1 = in.nextInt()\n\n println(s\"$x1 $y1\")\n println(s\"1 $y1\")\n println(s\"1 1\")\n\n 1.to(n)\n .foreach(r => {\n var start = if (r % 2 == 1) 1 else m\n val inc = if (r % 2 == 1) 1 else -1\n 1.to(m)\n .foreach(_ => {\n val curRow = r\n val curCol = start\n if (!((curRow == x1 && curCol == y1) || (curRow == 1 && curCol == y1) || (curRow == 1 && curCol == 1))) {\n println(s\"$curRow $curCol\")\n }\n start = start + inc\n })\n })\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val Array(n, m, sx, sy) = readLine().split(\" \").map(_.toInt)\n\n (0 until n).foldLeft((sx, sy)) {\n case ((x, y), i) =>\n val moves = (x, y) +: (1 to m).collect { case j if j != y => (x, j) }\n\n moves.foreach { case (x, y) => println(s\"$x $y\") }\n\n moves.last match {\n case (1, y) => (n, y)\n case (x, y) => (x - 1, y)\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject taskB extends App {\n\n\n val input: Array[Int] = readLine.split(\" \").map(_.toInt)\n // println(s\"${input(0)} ${input(1)} ${input(2)} ${input(3)}\")\n val sizeX = input(0)\n val sizeY = input(1)\n var locX = input(2)\n var locY = input(3)\n\n var visited: List[(Int, Int)] = List((locX, locY))\n\n def visitWholeLine(): Unit = {\n (2 to sizeY).foreach {_ =>\n if (locY == sizeY) locY = 1\n else locY += 1\n println(locX +\" \"+ locY)\n }\n }\n\n visitWholeLine()\n (2 to sizeX).foreach { _ =>\n if (locX == sizeX) locX = 1\n else locX += 1\n println(locX +\" \"+ locY)\n\n visitWholeLine()\n }\n\n\n\n}\n\n\n\n\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject taskB extends App {\n\n\n val input: Array[Int] = readLine.split(\" \").map(_.toInt)\n // println(s\"${input(0)} ${input(1)} ${input(2)} ${input(3)}\")\n val sizeX = input(0)\n val sizeY = input(1)\n var locX = input(2)\n var locY = input(3)\n\n var visited: List[(Int, Int)] = List((locX, locY))\n\n def visitWholeLine(): Unit = {\n (2 to sizeY).foreach {_ =>\n if (locY == sizeY) locY = 1\n else locY += 1\n visited = visited :+ (locX, locY)\n }\n }\n\n visitWholeLine()\n (2 to sizeX).foreach { _ =>\n if (locX == sizeX) locX = 1\n else locX += 1\n\n visitWholeLine()\n }\n\n\n visited.foreach { x =>\n println(s\"${x._1} ${x._2}\")\n }\n\n}\n\n\n\n\n\n"}], "src_uid": "ed26479cdf72ad9686bbf334d90aa0be"} {"source_code": "object prob2 {\r\n def main(args: Array[String]) = {\r\n import scala.collection.mutable.ListBuffer\r\n new Resolver3(Console.in, Console.out).run()\r\n }\r\n}\r\n\r\nclass Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {\r\n import java.util.StringTokenizer\r\n def run() {\r\n var tokenizer = new StringTokenizer(input.readLine())\r\n val n = tokenizer.nextToken().toInt\r\n for (i <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val j = tokenizer.nextToken().toInt\r\n if (j % 2 != 0) {\r\n output.println(-1)\r\n }\r\n else {\r\n output.println((j/2).toString + \" \" +(j/2).toString + \" \" + \"0\" )\r\n }\r\n }\r\n }\r\n\r\n}\r\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n\n val t = readInt()\n\n (1 to t).foreach(_ => solution());\n\n def solution() = {\n val n = readInt()\n if (n % 2 == 0)\n println(s\"0 ${n / 2} ${n / 2}\")\n else\n println(-1)\n\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\r\n\r\nobject Main extends App {\r\n val t = StdIn.readInt()\r\n for(i <- 0 until t){\r\n val n = StdIn.readInt()\r\n if (n % 2 == 1) {\r\n println(-1)\r\n } else {\r\n println(\"0 0 \" + n / 2)\r\n }\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object prob2 {\r\n def main(args: Array[String]) = {\r\n import scala.collection.mutable.ListBuffer\r\n new Resolver3(Console.in, Console.out).run()\r\n }\r\n}\r\n\r\nclass Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {\r\n import java.util.StringTokenizer\r\n def run() {\r\n var tokenizer = new StringTokenizer(input.readLine())\r\n val n = tokenizer.nextToken().toInt\r\n for (i <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val j = tokenizer.nextToken().toInt\r\n if (i % 2 != 0) {\r\n output.println(-1)\r\n }\r\n else {\r\n output.println((j/2).toString + \" \" +(j/2).toString + \" \" + \"0\" )\r\n }\r\n }\r\n }\r\n\r\n}\r\n"}, {"source_code": "object prob2 {\r\n def main(args: Array[String]) = {\r\n import scala.collection.mutable.ListBuffer\r\n new Resolver3(Console.in, Console.out).run()\r\n }\r\n}\r\n\r\nclass Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {\r\n import java.util.StringTokenizer\r\n def run() {\r\n var tokenizer = new StringTokenizer(input.readLine())\r\n val n = tokenizer.nextToken().toInt\r\n for (i <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val j = tokenizer.nextToken().toInt\r\n if (i % 2 == 0) {\r\n output.println(-1)\r\n }\r\n else {\r\n output.println((j/2).toString + \" \" +(j/2).toString + \" \" + \"0\" )\r\n }\r\n }\r\n }\r\n\r\n}\r\n"}], "src_uid": "43041076ddd0bbfac62cd4abf4536282"} {"source_code": "object A703 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = Array.fill(n)(readInts(2)).filter(arr => arr(0) != arr(1))\n val m = input.count(arr => arr(0) > arr(1))\n val c = input.count(arr => arr(0) < arr(1))\n if(m == c) {\n println(\"Friendship is magic!^^\")\n } else if (m > c) {\n println(\"Mishka\")\n } else {\n println(\"Chris\")\n }\n }\n}", "positive_code": [{"source_code": "object mishkaAndGame_703A extends App {\n\n val rounds = readLine().toInt\n var mishka = 0\n var chris = 0\n for (i <- 0 until rounds){\n val round = readLine().split(\" \").toList\n if (round.head > round.last) mishka = mishka + 1\n else if (round.head < round.last) chris = chris + 1\n }\n\n if (mishka > chris) println(\"Mishka\")\n else if (chris > mishka) println(\"Chris\")\n else println(\"Friendship is magic!^^\")\n}\n"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val n = lines.next().toInt\n val (mish, chri) = lines.take(n).map(_.split(' ').map(_.toInt)).foldLeft((0, 0)) {\n case((mishka, chris), Array(m, c)) if m > c => (mishka + 1, chris)\n case((mishka, chris), Array(m, c)) if m < c => (mishka, chris + 1)\n case((mishka, chris), _) => (mishka, chris)\n }\n if (mish > chri)\n println(\"Mishka\")\n else if (mish < chri)\n println(\"Chris\")\n else\n println(\"Friendship is magic!^^\")\n}"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n var cnt = 0\n\n for (_ <- 0 until n) {\n val Array(a, b) = readInts(2)\n cnt += Integer.signum(b - a)\n }\n\n val res = if (cnt < 0) \"Mishka\"\n else if (cnt > 0) \"Chris\"\n else \"Friendship is magic!^^\"\n\n println(res)\n}\n"}, {"source_code": "\n\n/**\n * Created by BFD_299 on 2016/8/5.\n */\n\nobject code365A {\n def main(args:Array[String]): Unit ={\n var m = 0\n var c = 0\n val round = io.StdIn.readInt()\n for (i <- 1 to round){\n val cin = io.StdIn.readLine()\n val cins = cin.split(\" \")\n if(cins(0) > cins(1)) m += 1\n if(cins(0) < cins(1)) c += 1\n }\n if(m > c) println(\"Mishka\")\n if(m < c) println(\"Chris\")\n if(m == c) println(\"Friendship is magic!^^\")\n }\n}\n"}, {"source_code": "\n/**\n * Created by BFD_299 on 2016/8/5.\n */\n\nobject code365A {\n def main(args:Array[String]): Unit ={\n var m = 0\n var c = 0\n val round = io.StdIn.readInt()\n var cin: String = null\n var cins: Array[String] = null\n for (i <- 1 to round){\n cin = io.StdIn.readLine()\n cins = cin.split(\" \")\n if(cins(0) > cins(1)) m += 1\n if(cins(0) < cins(1)) c += 1\n }\n if(m > c) println(\"Mishka\")\n if(m < c) println(\"Chris\")\n if(m == c) println(\"Friendship is magic!^^\")\n }\n}\n"}, {"source_code": "object main extends App{\n val n = readInt\n println(List.range(0, n).foldLeft(Array(0,0))({ (res: Array[Int], i: Int) =>\n val Array(m, c) = readLine.split(\" \").map(_.toInt)\n if (m>c) res(0) +=1 else if (m if (m > c) \"Mishka\" else if ( m c) mishka += 1\n }\n\n val ans = if (mishka < chris) {\n \"Chris\"\n } else if (chris < mishka) {\n \"Mishka\"\n } else {\n \"Friendship is magic!^^\"\n }\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Main extends App {\n import scala.io. { StdIn => In }\n val n = In.readInt\n var s = 0\n for(i <- 0 until n) {\n val Array(u,v) = In.readLine().split(\" \").map(_.toInt)\n if (u < v) s -= 1\n else if (u > v) s += 1\n }\n if (s < 0) println (\"Chris\")\n else if (s > 0) println (\"Mishka\")\n else println(\"Friendship is magic!^^\")\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val t = readInt()\n var winner = 0\n 1 to t foreach { _ =>\n val Array(a, b) = readLine().split(\" \").map(_.toInt)\n if (a > b) winner += 1\n else if (b > a) winner -= 1\n }\n\n if (winner > 0) println(\"Mishka\")\n else if (winner <0) print(\"Chris\")\n else println(\"Friendship is magic!^^\")\n}\n"}], "negative_code": [{"source_code": "object mishkaAndGame_703A extends App {\n\n val rounds = readLine().toInt\n var mishka = 0\n var chris = 0\n for (i <- 0 until rounds){\n val round = readLine().split(\" \").toList\n mishka = mishka + round.head.toInt\n chris = chris + round.last.toInt\n }\n if (mishka > chris) println(\"Mishka\")\n else if (chris > mishka) println(\"Chris\")\n else println(\"Friendship is magic!^^\")\n}"}, {"source_code": "object mishkaAndGame_703A extends App {\n\n val rounds = readLine().toInt\n var mishka = 0\n var chris = 0\n for (i <- 0 until rounds){\n val round = readLine().split(\" \").toList\n if (round.head > round.last) mishka = mishka + 1\n else chris = chris + 1\n }\n if (mishka > chris) println(\"Mishka\")\n else if (chris > mishka) println(\"Chris\")\n else println(\"Friendship is magic!^^\")\n}"}, {"source_code": "object mishkaAndGame_703A extends App {\n\n val rounds = readLine().toInt\n var mishka = 0\n var chris = 0\n for (i <- 0 until rounds){\n val round = readLine().split(\" \").toList\n if (round.head > round.last) mishka = mishka + 1\n else chris = chris + 1\n }\n if (mishka > chris) println(\"Mishka\")\n else if (chris > mishka) println(\"Chris\")\n else if (chris < mishka) println(\"Friendship is magic!^^\")\n}\n"}, {"source_code": "object mishkaAndGame_703A extends App {\n\n val rounds = readLine().toInt\n var mishka = 0\n var chris = 0\n for (i <- 0 until rounds){\n val round = readLine().split(\" \").toList\n if (round.head > round.last) mishka = mishka + 1\n else if (round.head > round.last) chris = chris + 1\n }\n if (mishka > chris) println(\"Mishka\")\n else if (chris > mishka) println(\"Chris\")\n else println(\"Friendship is magic!^^\")\n}\n"}, {"source_code": "object A703 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = Array.fill(n)(readInts(2)).count(arr => arr(0) > arr(1))\n if(input == n-input) {\n println(\"Friendship is magic!^^\")\n } else if (input > n-input) {\n println(\"Mishka\")\n } else {\n println(\"Chris\")\n }\n }\n}"}, {"source_code": "object Main extends App {\n import scala.io. { StdIn => In }\n val n = In.readInt\n var s = 0\n for(i <- 0 until n) {\n val Array(u,v) = In.readLine().split(\" \").map(_.toInt)\n if (u < v) s -= -1\n else if (u > v) s += 1\n }\n if (s < 0) println (\"Chris\")\n else if (s > 0) println (\"Mishka\")\n else println(\"Friendship is magic!^^\")\n}\n"}], "src_uid": "76ecde4a445bbafec3cda1fc421e6d42"} {"source_code": "import scala.io.StdIn\n\n/**\n * @author hongchen.cao\n * @date 2020/03/15 17:55\n **/\nobject Test {\n def main(args: Array[String]): Unit = {\n val t: Int = StdIn.readInt()\n for (i <- 1 to t) {\n val n = StdIn.readInt()\n\n val psum = StdIn.readLine().split(\" \").map(_.toInt % 2).sum\n\n psum match {\n case s if s == 0 || s == n => println(\"YES\")\n case _ => println(\"NO\")\n }\n }\n }\n\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C627A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C627A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val n = ni()\n val a = na(n).toIndexedSeq.sorted\n\n var yes = true\n REP(n-1) { i =>\n val x = a(i+1) - a(i)\n yes = yes & (x % 2 == 0)\n }\n if(yes) out.println(\"YES\") else out.println(\"NO\")\n }\n }\n}\n"}, {"source_code": "object _1324A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val as = io.read[Vector[Int]]\n\n val diffs = for {\n i <- as.indices.view\n j <- as.indices.drop(i + 1)\n } yield (as(j) - as(i))%2 == 0\n\n val ans = diffs.forall(identity)\n\n io.write(ans.toEnglish.toUpperCase)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\n/**\n * @author hongchen.cao\n * @date 2020/03/15 17:55\n **/\nobject Test {\n def main(args: Array[String]): Unit = {\n val t: Int = StdIn.readInt()\n for (_ <- 1 to t) {\n val n = StdIn.readInt()\n\n val psum = StdIn.readLine().split(\" \").map(_.toInt.%(2)).sum\n\n psum match {\n case s if s == 0 || s == n => println(\"YES\")\n case _ => println(\"NO\")\n }\n }\n }\n\n}\n"}], "negative_code": [], "src_uid": "53a3313f5d6ce19413d72473717054fc"} {"source_code": "object A extends App {\n val n = readInt\n val sizes = for(i <- 0 until n) yield readInt\n val ss = sizes.sorted.toArray\n var canfit = 0\n var cantfit = n / 2 + 1\n while(canfit + 1 < cantfit) {\n val attempt = (canfit + cantfit) / 2\n var failed = false\n for(i <- 0 until attempt) {\n if(2 * ss(i) > ss(n-attempt+i)) {\n failed = true\n }\n }\n if(failed)\n cantfit = attempt\n else\n canfit = attempt\n }\n println(n - canfit)\n}", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n\n def count(small: List[Int], big: List[Int]): Int = {\n if (small.isEmpty || big.isEmpty) 0\n else if (small.head * 2 <= big.head) 1 + count(small.tail, big.tail)\n else count(small, big.tail)\n }\n\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map(_ => in.next().toInt).sorted.toList\n println(n - count(data.take(n / 2), data.takeRight(n / 2)))\n}"}], "negative_code": [], "src_uid": "361f65484d86051fa9ff013f5e8c9154"} {"source_code": "object D extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n\n val a = Array.ofDim[Int](n, m)\n\n for (i <- 0 until n) a(i) = readInts\n\n val pair = Array.fill(m, m)(0)\n\n var max = 0\n var row = 0\n\n while (row < n) {\n var i = 0\n while (i < m - 1) {\n val ai = a(row)(i)\n if (ai > max) {\n var j = i + 1\n while (j < m) {\n val aj = a(row)(j)\n if (aj > max) {\n val aa = math.min(ai, aj)\n val result = math.min(pair(i)(j), aa)\n if (result > max) max = result\n if (aa > result) pair(i)(j) = aa\n }\n j += 1\n }\n }\n i += 1\n }\n row += 1\n }\n\n println(max)\n}", "positive_code": [{"source_code": "object D extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n\n val pair = Array.fill(m, m)(0)\n\n var max = 0\n var row = 0\n\n while (row < n) {\n val as = readInts\n var i = 0\n while (i < m - 1) {\n val ai = as(i)\n if (ai > max) {\n var j = i + 1\n while (j < m) {\n val aj = as(j)\n if (aj > max) {\n val aa = math.min(ai, aj)\n val result = math.min(pair(i)(j), aa)\n if (result > max) max = result\n if (aa > result) pair(i)(j) = aa\n }\n j += 1\n }\n }\n i += 1\n }\n row += 1\n }\n\n println(max)\n}"}, {"source_code": "object D extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n\n val a = Array.ofDim[Int](n, m)\n\n for (i <- 0 until n) a(i) = readInts\n\n val pair = Array.fill(m, m)(0)\n\n var row = 0\n var max = 0\n\n while (row < n) {\n var i = 0\n while (i < m - 1) {\n val ai = a(row)(i)\n if (ai > max) {\n var j = i + 1\n while (j < m) {\n val aj = a(row)(j)\n if (aj > max) {\n val aa = math.min(ai, aj)\n val result = math.min(pair(i)(j), aa)\n if (result > max) max = result\n if (aa > result) pair(i)(j) = aa\n }\n j += 1\n }\n }\n i += 1\n }\n row += 1\n }\n\n println(max)\n}"}], "negative_code": [{"source_code": "object D extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n\n val a = Array.ofDim[Int](n, m)\n\n for (i <- 0 until n) a(i) = readInts\n\n val pair = Array.fill(m, m)(0)\n\n var row = 0\n var max = 0\n\n while (row < n) {\n var i = 0\n while (i < m - 1) {\n val ai = a(row)(i)\n if (ai > max) {\n var j = i + 1\n while (j < m) {\n val aj = a(row)(j)\n if (aj > max) {\n val aa = math.min(ai, aj)\n val result = math.min(pair(i)(j), aa)\n if (result > max) max = result\n pair(i)(j) = aa\n }\n j += 1\n }\n }\n i += 1\n }\n row += 1\n }\n\n println(max)\n}"}], "src_uid": "ea0aadcea3a5de4e625a0862f637d1c8"} {"source_code": "import java.io.PrintWriter\r\nimport java.util.Scanner\r\nimport scala.collection.mutable.ArrayBuffer\r\n\r\n// if there is k1 left in G1 and k2 left in G2 and k1 > 0 & k2 > 0 then\r\n// if we can prove that edge exist which satisfies problem\r\n// we can add it and move problem to k1-1 & k2-1\r\n// let's assume that's true\r\nobject Solution {\r\n def solve(input: Int): Int = {\r\n input\r\n }\r\n\r\n def run(test: Int, input: Scanner, output: PrintWriter): Unit = {\r\n output.println(solve(1))\r\n }\r\n\r\n def connect(colors: Array[Int], v: Int, u: Int): Unit = {\r\n val toMatch = colors(v)\r\n colors.indices.foreach { idx =>\r\n if (colors(idx) == toMatch) colors(idx) = colors(u)\r\n }\r\n }\r\n\r\n def connected(colors: Array[Int], v: Int, u: Int): Boolean = colors(v) == colors(u)\r\n\r\n def run(input: Scanner, output: PrintWriter): Unit = {\r\n val n = input.nextInt()\r\n val m1 = input.nextInt()\r\n val m2 = input.nextInt()\r\n\r\n val c1 = (0 until n).toArray\r\n val c2 = (0 until n).toArray\r\n\r\n (1 to m1).foreach { _ =>\r\n val u = input.nextInt() - 1\r\n val v = input.nextInt() - 1\r\n connect(c1, u, v)\r\n }\r\n (1 to m2).foreach { _ =>\r\n val u = input.nextInt() - 1\r\n val v = input.nextInt() - 1\r\n connect(c2, u, v)\r\n }\r\n\r\n val ans = ArrayBuffer[(Int, Int)]()\r\n (0 until (n - 1)).foreach { u =>\r\n (u + 1).until(n).foreach { v =>\r\n if (!connected(c1, u, v) && !connected(c2, u, v)) {\r\n ans.append((u + 1, v + 1))\r\n connect(c1, u, v)\r\n connect(c2, u, v)\r\n }\r\n }\r\n }\r\n\r\n output.println(ans.length)\r\n ans.foreach { case (u, v) =>\r\n output.println(u + \" \" + v)\r\n }\r\n output.flush()\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n run(new Scanner(System.in), new PrintWriter(System.out))\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import java.io._\r\nimport scala.collection.immutable.TreeSet\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val reader = new BufferedReader(new java.io.InputStreamReader(System.in))\r\n val writer = new PrintWriter(System.out)\r\n def readInt(): Int = reader.readLine().toInt\r\n def readLong(): Long = reader.readLine().toLong\r\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\r\n def readArrayLong(): Array[Long] = reader.readLine().split(\" \").map(_.toLong)\r\n def readString(): String = reader.readLine()\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n def dfs(u: Int, e: Array[ArrayBuffer[Int]], ch: Array[Boolean], f: Array[Int]): Unit = {\r\n for (v <- e(u) if !ch(v)) {\r\n ch(v) = true\r\n f(v) = f(u)\r\n dfs(v, e, ch, f)\r\n }\r\n }\r\n\r\n def root(u: Int, f: Array[Int]): Int = {\r\n if (f(u) < 0) return u\r\n f(u) = root(f(u), f)\r\n f(u)\r\n }\r\n\r\n def join(u: Int, v: Int, f: Array[Int]): Unit = {\r\n var x = root(u, f)\r\n var y = root(v, f)\r\n if (x == y) return\r\n\r\n if (f(y) < f(x)) {\r\n val t = x\r\n x = y\r\n y = t\r\n }\r\n f(x) += f(y)\r\n f(y) = x\r\n }\r\n\r\n def solve(t: Int = 0): Unit = {\r\n val Array(n,m1,m2) = readArrayInt()\r\n //val e1 = Array.fill(n)(new ArrayBuffer[Int]())\r\n //val e2 = Array.fill(n)(new ArrayBuffer[Int]())\r\n\r\n val f1 = new Array[Int](n)\r\n val f2 = new Array[Int](n)\r\n\r\n for (i <- 0 until n) {\r\n f1(i) = -1\r\n f2(i) = -1\r\n }\r\n\r\n for (_ <- 0 until m1) {\r\n val Array(u,v) = readArrayInt()\r\n //e1(u - 1) += v - 1\r\n //e1(v - 1) += u - 1\r\n join (u - 1, v - 1, f1)\r\n }\r\n\r\n for (_ <- 0 until m2) {\r\n val Array(u,v) = readArrayInt()\r\n // e2(u - 1) += v - 1\r\n //e2(v - 1) += u - 1\r\n join (u - 1, v - 1, f2)\r\n }\r\n\r\n /*val f1 = new Array[Int](n)\r\n val f2 = new Array[Int](n)\r\n var ch = Array.fill[Boolean](n)(false)\r\n var c = 1\r\n for (i <- 0 until n if !ch(i)) {\r\n f1(i) = c\r\n dfs(i, e1, ch, f1)\r\n c += 1\r\n }\r\n\r\n ch = Array.fill[Boolean](n)(false)\r\n c = 1\r\n for (i <- 0 until n if !ch(i)) {\r\n f2(i) = c\r\n dfs(i, e2, ch, f2)\r\n c += 1\r\n }*/\r\n\r\n\r\n\r\n\r\n\r\n val rs = new ArrayBuffer[(Int, Int)]()\r\n\r\n for (i <- 0 until n - 1; j <- i + 1 until n) {\r\n if (root(i, f1) != root(j, f1) && root(i, f2) != root(j, f2)) {\r\n rs += ((i + 1, j + 1))\r\n join(i, j, f1)\r\n join(i, j, f2)\r\n }\r\n }\r\n\r\n println(rs.length)\r\n\r\n for ((u,v) <- rs)\r\n writer.println(s\"$u $v\")\r\n }\r\n\r\n def main(args: Array[String]) {\r\n //multiTest(solve)\r\n solve()\r\n writer.flush()\r\n }\r\n}"}], "negative_code": [], "src_uid": "e3d2b67a62ac431718071ae20f3794aa"} {"source_code": "object Demo {\n def main(args: Array[String]): Unit\n =\n {\n var arr = new Array[Int](4)\n\n //arr = readLine.split(\" \").map(_.toInt)\n val Array(a,b,c,d)=readLine.split(\" \").map(_.toInt)\n arr(0)=a\n arr(1)=b\n arr(2)=c\n arr(3)=d\n // arr.sorted\n for(i<-0 to 3)\n {\n for(j<-i+1 to 3)\n {\n if(arr(i)>arr(j))\n {\n var temp=arr(i)\n arr(i)=arr(j)\n arr(j)=temp\n }\n }\n }\n println((arr(3)-arr(0))+\" \"+(arr(3)-arr(1))+\" \"+(arr(3)-arr(2)))\n /*for(i<-0 to 3)\n println(arr(i))*/\n }\n}", "positive_code": [{"source_code": "object Example extends App {\n def greater(i: Int, j : Int): Int =\n i > j match {\n case true => i\n case _ => j\n }\n\n def myPrint (g :Int, b :Int) =\n g == b match {\n case false => print( g - b + \" \")\n case _ =>\n }\n\n var lol = scala.io.StdIn.readLine().split(\" \")\n var a = lol(0).toInt\n var b = lol(1).toInt\n var c = lol(2).toInt\n var d = lol(3).toInt\n\n var g = greater(greater(c,d), greater(a,b))\n myPrint (g, a)\n myPrint (g, b)\n myPrint (g, c)\n myPrint (g, d)\n\n}"}, {"source_code": "object Example extends App {\n def greater(i: Int, j : Int): Int =\n i > j match {\n case true => i\n case _ => j\n }\n\n def myPrint (g : Int, b :Int) =\n g == b match {\n case false => print( g.toInt - b.toInt + \" \")\n case _ =>\n }\n\n var input = scala.io.StdIn.readLine().split(\" \")\n var r = input.map(e => e.toInt)\n var g = greater(greater(r(0), r(1)), greater(r(2) , r(3)))\n input.map( e => myPrint(g, e.toInt))\n}"}, {"source_code": "object Example extends App {\n def greater(i: Int, j : Int): Int =\n i > j match {\n case true => i\n case _ => j\n }\n\n def myPrint (g : Int, b :Int) =\n g == b match {\n case false => print( g.toInt - b.toInt + \" \")\n case _ =>\n }\n\n var input = scala.io.StdIn.readLine().split(\" \")\n var r = input.map(e => e.toInt)\n var g = greater(greater(r(0), r(1)), greater(r(2) , r(3)))\n r.map( e => myPrint(g, e))\n}"}, {"source_code": "object Example extends App {\n def greater(i: Int, j : Int): Int =\n i > j match {\n case true => i\n case _ => j\n }\n\n def myPrint (g : Int, b :Int) =\n g == b match {\n case false => print( g - b + \" \")\n case _ =>\n }\n\n var input = scala.io.StdIn.readLine().split(\" \")\n var r = input.map(e => e.toInt)\n var g = greater(greater(r(0), r(1)), greater(r(2) , r(3)))\n r.map( e => myPrint(g, e))\n}"}, {"source_code": " /**\n * @author ShankarShastri\n * Algorithm: RestoringThreeNumbers\n */\n\nimport scala.io.StdIn._\nimport scala.annotation.tailrec\n\nobject RestoringThreeNumbers {\n def main(args: Array[String]): Unit = {\n val l = readLine.split(\" \").map(_.toInt)\n val abc = l.max\n println(l.filter(abc - _ != 0).map(abc - _).mkString(\" \"))\n }\n}\n"}, {"source_code": "object Puzzle {\n def main(args: Array[String]): Unit = {\n val Array(a, b, c, d) = scala.io.StdIn.readLine()\n .split(\" \")\n .map(_.toInt)\n .sorted\n print(d - a + \" \")\n print(d - b + \" \")\n print(d - c)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\n\nobject Solution {\n def main(args : Array[String]) : Unit = {\n val scanner = new Scanner(System.in)\n val x_1 = scanner.nextInt()\n val x_2 = scanner.nextInt()\n val x_3 = scanner.nextInt()\n val x_4 = scanner.nextInt()\n val xs = Seq(x_1, x_2, x_3, x_4)\n val m = xs.max\n val ms = Seq(m)\n val xs_minus_ms = xs.diff(ms)\n for (x <- xs_minus_ms) {\n val a = m - x\n print(s\"${a} \")\n }\n println()\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Codeforces1154A extends App {\n var Array(x1, x2, x3, x4) = StdIn.readLine().split(\"\\\\s\").map(s => s.toLong)\n\n var abc = math.max(x1, math.max(x2, math.max(x3, x4)))\n if (x1 != abc) print((abc - x1) + \" \")\n if (x2 != abc) print((abc - x2) + \" \")\n if (x3 != abc) print((abc - x3) + \" \")\n if (x4 != abc) print((abc - x4) + \" \")\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Main2 extends App {\n val numbers = readLine().split(\" \").map(_.toLong).sorted\n println(s\"${numbers(3) - numbers(1)} ${numbers(3) - numbers(2)} ${numbers(3) - numbers(0)}\")\n}\n"}], "negative_code": [{"source_code": "object Puzzle {\n def main(args: Array[String]): Unit = {\n val Array(a, b, c, d) = scala.io.StdIn.readLine()\n .split(\" \")\n .map(_.toInt)\n .sorted\n print(d - a + \" \")\n print(d - b + \" \")\n print(d - a)\n }\n}\n"}], "src_uid": "cda949a8fb1f158f3c06109a2d33f084"} {"source_code": "import scala.io.Source\nimport scala.math._\n\nimport java.util.BitSet\n\nobject B extends App {\n def go = main(Array())\n \n val in = Source.stdin.getLines.toList\n val n = in(0).toInt\n val destr = in(1).split(\" \").map(_.toInt).zipWithIndex.groupBy(_._1)\n\n val broken = new BitSet(n)\n\n val eventfulDays = destr.keySet.toList.sorted\n\n def solve: Int = {\n eventfulDays.foreach ( day => {\n destr(day).foreach { case (_, tile) => { \n\tif (tile == 0 || tile == (n-1)) return day\n\tif (broken.get(tile-1) || broken.get(tile+1)) return day\n\tbroken.set(tile)\n }}\n })\n return eventfulDays.last\n }\n\n println (solve)\n}\n", "positive_code": [{"source_code": "object Main\n{\n def main(args:Array[String])\n {\n val n = readInt\n val iNums = readLine.split(\" \").map(i => i.toInt)\n var iMin = 1001;\n for (i <- (1 until iNums.length))\n {\n iMin = List(iMin, List(iNums(i), iNums(i - 1)).max).min;\n }\n println(List(iMin, iNums(0), iNums.last).min)\n }\n}"}, {"source_code": "object Main\n{\n def main(args:Array[String])\n {\n val n = readInt\n val iNums = (readLine + \" 1000\").split(\" \").map(i => i.toInt)\n /*var iMin = 1001;\n for (i <- (1 until iNums.length))\n {\n iMin = List(iMin, List(iNums(i), iNums(i - 1)).max).min;\n }\n println(List(iMin, iNums(0), iNums.last).min)*/\n var iMin = (1 to n).map(i => List(iNums(i), iNums(i - 1)).max).min;\n println(List(iMin, iNums(0), iNums(n - 1)).min)\n }\n}"}, {"source_code": "object Main\n{\n\tdef main(args:Array[String])\n\t\t{\n\t\t\tval n = readInt\n\t\t\tval iNums = readLine.split(\" \").map(i => i.toInt)\n\t\t\t/*var iMin = 1001;\n\t\t\tfor (i <- (1 until iNums.length))\n\t\t\t{\n\t\t\t\tiMin = List(iMin, List(iNums(i), iNums(i - 1)).max).min;\n\t\t\t}\n\t\t\tprintln(List(iMin, iNums(0), iNums.last).min)*/\n\t\t\tvar iMin = 1001;\n\t\t\tfor (i <- (1 until iNums.length))\n\t\t\t{\n\t\t\t\tiMin = List(iMin, List(iNums(i), iNums(i - 1)).max).min;\n\t\t\t}\n\t\t\tprintln(List(iMin, iNums(0), iNums.last).min)\n\t\t}\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n \n val n = readInt\n val a = readLine.split(' ').map(_.toInt)\n\n val r = (1 to n).map(i => (i, a(i-1))).toArray.sortBy(_._2)\n \n var i = 1\n if(r(0)._1 != 1 && r(0)._1 != n) {\n while(i < n && r(i)._1 != 1 && r(i)._1 != n && r(i)._1 != r(i-1)._1+1) i += 1\n println(r(i)._2)\n } else {\n println(r(0)._1)\n }\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n \n val n = readInt\n val a = readLine.split(' ').map(_.toInt)\n\n val r = (1 to n).map(i => (i, a(i-1))).toArray.sortBy(_._2)\n \n var i = 1\n if(r(0)._1 != 1 && r(0)._1 != n) {\n while(i < n && r(i)._1 != 1 && r(i)._1 != n && r(i)._1 != r(i-1)._1+1) i += 1\n println(r(i)._2)\n } else {\n println(r(0)._2)\n }\n }\n}"}], "src_uid": "d526af933b5afe9abfdf9815e9664144"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val weight = in.next().split(' ').map(_.toInt)\n val order = in.next().split(' ').map(_.toInt - 1)\n var distinct = order.distinct.toList\n println(order.foldLeft(0) {\n case (acc, i) if distinct.head == i => acc\n case (acc, i) =>\n var sum = acc\n val firstPart = distinct.takeWhile(_ != i)\n val secondPart = distinct.dropWhile(_ != i).tail\n distinct = i :: (firstPart ::: secondPart)\n acc + firstPart.map(weight).sum\n })\n\n}\n", "positive_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val ws = readLongs(n)\n val bs = readInts(m).map(_ - 1)\n \n val first = Array.fill(n)(Int.MaxValue)\n for (i <- bs.indices) if (first(bs(i)) == Int.MaxValue) first(bs(i)) = i\n \n val stack = (0 until n).sortBy(first).toArray\n var res = 0L\n \n for (b <- bs) {\n var i = 0\n //println(b+1, stack.map(_ + 1).mkString(\" \"))\n while (stack(i) != b) {\n res += ws(stack(i))\n i += 1\n }\n while (i > 0) {\n stack(i) = stack(i - 1)\n i -= 1\n }\n stack(0) = b\n }\n\n println(res)\n}"}, {"source_code": "object P500C {\n\t@inline def readInts : Array[Int] = {\n\t\tscala.io.StdIn.readLine.split(\" \").map(_.toInt)\n\t}\n\n\tdef solve(ws: Array[Int])(s: List[Int], bs: List[Int]) : Int = {\n\t\tif (bs.isEmpty) {\n\t\t\t0\n\t\t} else {\n\t\t\tval (top, rest) = s.splitAt(s.indexOf(bs.head))\n\t\t\tval stack = rest.head :: top ::: rest.tail\n\t\t\tval lifted = top.foldLeft(0)((x, y) => x + ws(y - 1))\n\t\t\tlifted + solve(ws)(stack, bs.tail)\n\t\t}\n\t}\n\n\tdef main(args: Array[String]) {\n\t\tval Array(n, m) = readInts\n\t\tval ws = readInts\n\t\tval bs = readInts.toList\n\t\tprintln(solve(ws)(bs.distinct, bs))\n\t}\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val weight = in.next().split(' ').map(_.toInt)\n val order = in.next().split(' ').map(_.toInt)\n var distinct = order.distinct.toList\n println(order.foldLeft(0) {\n case (acc, i) if distinct.head == i => acc\n case (acc, i) =>\n var sum = acc\n val firstPart = distinct.takeWhile(_ != i)\n val secondPart = distinct.dropWhile(_ != i).tail\n distinct = i :: (firstPart ::: secondPart)\n acc + firstPart.sum\n })\n\n}\n"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val ws = readLongs(n)\n val bs = readInts(m).map(_ - 1)\n \n val first = Array.fill(n)(-1)\n for (i <- bs.indices) if (first(bs(i)) < 0) first(bs(i)) = i\n \n val stack = (0 until n).sortBy(first).toArray\n var res = 0L\n \n for (b <- bs) {\n var i = 0\n //println(b+1, stack.map(_ + 1).mkString(\" \"))\n while (stack(i) != b) {\n res += ws(stack(i))\n i += 1\n }\n while (i > 0) {\n stack(i) = stack(i - 1)\n i -= 1\n }\n stack(0) = b\n }\n\n println(res)\n}"}], "src_uid": "a18edcadb31f76e69968b0a3e1cb7e3e"} {"source_code": "import scala.io.StdIn\n\nobject ArrayStabilization extends App {\n\n val n = StdIn.readLine().toInt\n val xs = StdIn.readLine().split(\" \").map(_.toInt)\n\n println(findSol(xs))\n\n def findSol(xs: Array[Int]) = {\n val revSorted = xs.sorted(Ordering[Int].reverse)\n\n val rem1 = revSorted.drop(1)\n val min1 = rem1.head - rem1.last\n\n val rem2 = revSorted.take(xs.length - 1)\n val min2 = rem2.head - rem2.last\n\n math.min(min1, min2)\n }\n}\n", "positive_code": [{"source_code": "object CF_529_3_B {\n\n type In = (Int, Seq[Int])\n type Out = Int\n \n def solve(in: In): Out = {\n val (n, xs) = in\n n match {\n case 2 => 0\n case _ =>\n val sort = xs.sorted\n val (min1, min2) = (sort(0), sort(1))\n val (max1, max2) = (sort.last, sort.init.last)\n if(min2 - min1 > max1 - max2) max1 - min2\n else max2 - min1\n }\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, {i.nextLine; i.intSeq})\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change: \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def ceil(a: Int, b: Int) = (a - 1)/b + 1\n def ceil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n sort(A)\n\n val ans = min(A(N - 1) - A(1), A(N - 2) - A(0))\n out.println(ans)\n }\n\n\n def sort(a: Array[Int]): Array[Int] = {\n val n = a.length\n REP(n) { i =>\n val j = scala.util.Random.nextInt(n - i) + i\n val tmp = a(i)\n a(i) = a(j)\n a(j) = tmp\n }\n Sorting.quickSort(a)\n a\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [], "src_uid": "2eb7234904b28b4793b7c482a2370092"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val setL, setR = mutable.Set[Int]()\n def findLMax: Int = {\n REP(N) { i =>\n if (setL.contains(A(i))) return i - 1\n setL += A(i)\n }\n N - 1\n }\n\n var ans = N\n val lMax = findLMax\n debug(s\"lMax:$lMax\")\n debug(setL.mkString(\" \"))\n var l = lMax\n var r = N\n while(l >= -1) {\n while(r - 1 > l && !setL.contains(A(r - 1)) && !setR.contains(A(r - 1))) {\n r -= 1\n setR += A(r)\n }\n debug(s\"l:$l r:$r\")\n ans = min(ans, r - l - 1)\n if (l >= 0) setL -= A(l)\n l -= 1\n }\n\n out.println(ans)\n }\n}", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n\n var min = n\n var l = 0\n val left = mutable.Set.empty[Int]\n\n do {\n var r = 0\n val right = mutable.Set.empty[Int]\n if (l > 0) left += as(l - 1)\n do {\n if (n - r - l < min) {\n //println(l, r, left, right)\n min = n - r - l\n }\n if (r > 0) right += as(n - r)\n r += 1\n } while (l + r <= n && !left(as(n - r)) && !right(as(n - r)))\n l += 1\n } while (l < n && !left(as(l - 1)))\n\n println(min)\n}\n"}], "negative_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val setL, setR = mutable.Set[Int]()\n def findLMax: Int = {\n REP(N) { i =>\n if (setL.contains(A(i))) return i - 1\n setL += A(i)\n }\n N - 1\n }\n\n var ans = N\n val lMax = findLMax\n debug(s\"lMax:$lMax\")\n debug(setL.mkString(\" \"))\n var l = lMax\n var r = N\n while(l >= 0) {\n while(r - 1 > l && !setL.contains(A(r - 1)) && !setR.contains(A(r - 1))) {\n r -= 1\n setR += A(r)\n }\n debug(s\"l:$l r:$r\")\n ans = min(ans, r - l - 1)\n setL -= A(l)\n l -= 1\n }\n\n out.println(ans)\n }\n}"}], "src_uid": "9873a576d00630fa6e5fd4448a1a65ad"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val str = in.next()\n val left = str.takeWhile(_ == '<').length\n val right = str.reverse.takeWhile(_ == '>').length\n println(Math.min(n, left + right))\n}\n", "positive_code": [{"source_code": "object A725 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = scala.io.StdIn.readLine\n val right = input.reverse.dropWhile(_ == '>').length\n var res = input.length - right\n res += input.takeWhile(_ == '<').length\n println(res)\n }\n}"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val _ = readLine\n val s = readLine.toCharArray\n\n val res = s.takeWhile(_ == '<').size + s.reverse.takeWhile(_ == '>').size\n\n //FIXME Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res)\n\n Console.flush\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _725A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n = read[Int]\n var b = read[String]\n b = b.dropWhile(_ == '<')\n b = b.reverse\n b = b.dropWhile(_ == '>')\n //debug(n, b.reverse)\n write(n - b.length)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object ReadInputExample {\ndef main(args: Array[String]): Unit = {\n var d = scala.io.StdIn.readLine().toInt\n var inp = scala.io.StdIn.readLine()\n val status = Array.fill[Option[Boolean]](inp.length)(None)\n for (i <- 0 until inp.length) {\n if (status(i).isEmpty) {\n isPossibleList(inp, i, status)\n }\n }\n println(status.filter(x => x.get).length)\n }\n def isPossibleList(inp: String, ind: Int, status: Array[Option[Boolean]]): Boolean = {\n if (status(ind).nonEmpty) return status(ind).get\n if ((ind == 0 && inp(ind) == '<') || (ind == inp.length - 1 && inp(ind) == '>')) {\n status(ind) = Some(true)\n return true\n }\n val res = if (inp(ind) == '>') {\n if (inp(ind + 1) == '<') false else isPossibleList(inp, ind + 1, status)\n } else {\n if (inp(ind - 1) == '>') false else isPossibleList(inp, ind - 1, status)\n }\n status(ind) = Some(res)\n res\n }\n}"}, {"source_code": "import java.io._\nimport scala.io.Source\n\nimport scala.annotation.tailrec\n\nobject ProblemA {\n def main(args: Array[String]): Unit = processStdInOut()\n\n def processStdInOut(): Unit = {\n val src = Source.fromInputStream(System.in)\n processFromSource(src)\n }\n\n def processFromSource(src: Source): Unit = {\n try {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out));\n try {\n val lines = src.getLines()\n processLines(lines, bw)\n } finally {\n bw.flush()\n }\n } finally {\n src.close();\n }\n }\n\n // Standard code above, custom code below\n\n def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {\n\n val bumperCount = lines.next().toInt\n val bumpers = lines.next()\n val soln = solve(bumperCount, bumpers)\n bw.write(soln.toString)\n bw.newLine()\n }\n\n def solve(bumperCount: Int, bumpers: String): Int = {\n @tailrec\n def countLeft(pos: Int, count: Int): Int =\n if (pos == bumperCount || bumpers(pos) == '>') count\n else countLeft(pos + 1, count + 1)\n\n @tailrec\n def countRight(pos: Int, count: Int): Int =\n if (pos == -1 || bumpers(pos) == '<') count\n else countRight(pos - 1, count + 1)\n\n val totalCount = countLeft(0, 0) + countRight(bumperCount - 1, 0)\n totalCount\n }\n}\n"}, {"source_code": "object JumpingBall extends App {\n\n import scala.util.control.Breaks._\n\n def execute(firstInput: Int, bumpers: String): Int = {\n\n var acc = 0\n val n = bumpers.length\n\n breakable {\n for(i <- 0 until n){\n if(bumpers(i) == '<') acc += 1\n else break\n }\n }\n\n breakable {\n for(i <- n - 1 to 0 by -1){\n if(bumpers(i) == '>') acc += 1\n else break\n }\n }\n\n acc\n\n }\n\n // Length of the Seq[Bumpers]\n val n = Console.in.readLine().toInt // 1 <= n <= 200,000\n val bumpers = Console.in.readLine()\n println(execute(n, bumpers))\n\n}\n\n"}, {"source_code": "object JumpingBall extends App {\n\n def execute(firstInput: Int, bumpers: String): Int = {\n val n = bumpers.length - 1\n\n val minRightIndex = bumpers.indexOf('>')\n val maxLeftIndex = bumpers.lastIndexOf('<')\n\n def sumIzq(ind: Int): Int =\n if(ind > 0 ) ind\n else 0\n\n def sumDer(ind: Int): Int =\n if(ind < n ) n - ind\n else 0\n\n if(minRightIndex == 0 && maxLeftIndex == n) 0 // >..<\n else if(minRightIndex == -1 && maxLeftIndex == n) sumIzq(maxLeftIndex) + 1 // <<<\n else if(maxLeftIndex == -1 && minRightIndex == 0) sumDer(minRightIndex) + 1 // >>>\n else sumIzq(minRightIndex) + sumDer(maxLeftIndex) // ..>..<..\n }\n\n // Length of the Seq[Bumpers]\n val n = Console.in.readLine().toInt // 1 <= n <= 200,000\n val bumpers = Console.in.readLine()\n println(execute(n, bumpers))\n\n}\n\n"}, {"source_code": "object JumpingBall extends App {\n\n def execute(firstInput: Int, bumpers: String): Int = {\n\n def sum(filter: Char => Boolean)(bumpers: List[Char], acc: Int): Int = bumpers match {\n case Nil => acc\n case x :: xs if filter(x) => acc\n case x :: xs => sum(filter)(xs, acc + 1)\n }\n\n def sumIzq = sum( _ == '>' ) _\n def sumDer = sum( _ == '<' ) _\n\n sumIzq(bumpers.toList, 0) + sumDer(bumpers.reverse.toList, 0)\n\n }\n\n // Length of the Seq[Bumpers]\n val n = Console.in.readLine().toInt // 1 <= n <= 200,000\n val bumpers = Console.in.readLine()\n println(execute(n, bumpers))\n\n}\n\n"}], "negative_code": [{"source_code": "object JumpingBall extends App {\n\n def execute(firstInput: Int, bumpers: String): Int = {\n val n = bumpers.length - 1\n\n val minRightIndex = bumpers.indexOf('>')\n val maxLeftIndex = bumpers.lastIndexOf('<')\n\n def sumIzq(ind: Int): Int =\n if(ind > 0 ) ind\n else 0\n\n def sumDer(ind: Int): Int =\n if(ind < n ) n - ind\n else 0\n\n if(minRightIndex == 0 && maxLeftIndex == n) 0\n else sumIzq(minRightIndex) + sumDer(maxLeftIndex)\n }\n\n // Length of the Seq[Bumpers]\n val n = Console.in.read() // 1 <= n <= 200,000\n val bumpers = Console.in.readLine()\n println(execute(n, bumpers))\n\n}\n\n"}, {"source_code": "object JumpingBall extends App {\n\n def execute(firstInput: Int, bumpers: String): Int = {\n val n = bumpers.length - 1\n\n val minRightIndex = bumpers.indexOf('>')\n val maxLeftIndex = bumpers.lastIndexOf('<')\n\n def sumIzq(ind: Int): Int =\n if(ind > 0 ) ind\n else 0\n\n def sumDer(ind: Int): Int =\n if(ind < n ) n - ind\n else 0\n\n if(minRightIndex == 0 && maxLeftIndex == n) 0\n else sumIzq(minRightIndex) + sumDer(maxLeftIndex)\n }\n\n // Length of the Seq[Bumpers]\n val n = Console.in.readLine().toInt // 1 <= n <= 200,000\n val bumpers = Console.in.readLine()\n println(execute(n, bumpers))\n\n}\n\n"}], "src_uid": "6b4242ae9a52d36548dda79d93fe0aef"} {"source_code": "object B2 {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n /**\n * 1-based Binary Indexed (Fenwick) Tree with binary search.\n */\n final class BIT(src: Array[Long]) {\n\n private val t = Array.fill(src.length + 1) { 0L }\n\n for (i <- src.indices) update(i + 1, src(i))\n\n def query(r: Int, acc: Long = 0): Long =\n if (r <= 0) acc else query(r - (r & -r), acc + t(r))\n\n def rangeQuery(l: Int, r: Int): Long = query(r) - query(l - 1)\n\n def update(i: Int, delta: Long): Unit = {\n if (i < t.length) {\n t(i) += delta\n update(i + (i & -i), delta)\n }\n }\n\n def firstGreaterOrEqual(goal: Long): Int = {\n var sum = 0L\n var idx = 0\n var bitMask = Integer.highestOneBit(t.length)\n while (bitMask > 0) {\n val newIdx = idx + bitMask\n if (newIdx < t.length && sum + t(newIdx) < goal) {\n idx = newIdx\n sum += t(idx)\n }\n bitMask >>>= 1\n }\n idx + 1\n }\n\n }\n\n val n = nextInt\n val as = nextInts(n)\n val G = 1\n val sorted = as.sorted\n val sortedWithIndex = as.zipWithIndex.sortBy {\n case (x, i) => (-x, i)\n }\n val order = Array.ofDim[Int](n)\n for (i <- as.indices) {\n order(i) = sortedWithIndex(i)._2\n }\n\n val m = nextInt\n case class Query(k: Int, pos: Int, id: Int)\n val queries = Array.tabulate(m) { id =>\n val k, pos = nextInt\n Query(k, pos, id)\n }.sortBy(_.k)\n\n val res = Array.ofDim[Int](m)\n val bit = new BIT(Array.fill(n)(0L))\n\n var currentK = 0\n for (q <- queries) {\n while (currentK < q.k) {\n bit.update(order(currentK) + 1, +1)\n currentK += 1\n }\n val i = bit.firstGreaterOrEqual(q.pos) - 1\n res(q.id) = as(i)\n }\n\n out.println(res.mkString(\"\\n\"))\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n case class Entry(a: Int, i: Int)\n case class Query(k: Int, pos: Int, m: Int)\n\n class BIT(n: Int, zero: Int)(f: (Int, Int) => Int) {\n def this(n: Int) = this(n, 0)(_ + _)\n\n private val N = {\n val a = Integer.highestOneBit(n)\n if (a == n) a else a << 1\n }\n private val bit = if (zero != 0) Array.fill[Int](N + 1)(zero) else Array.ofDim[Int](N + 1)\n\n /**\n * 1 index\n * addとindex違うよ\n * cumsumなんかといっしょ\n */\n def sum(i: Int): Int = {\n assert(i <= n)\n var x = i\n var s: Int = zero\n while(x > 0) {\n s = f(s, bit(x))\n x -= x & -x\n }\n s\n }\n\n /**\n * 0 index\n */\n def add(i: Int, a: Int): Unit = {\n assert(i < n)\n var x = i + 1\n while(x <= N) {\n bit(x) = f(bit(x), a)\n x += x & -x\n }\n }\n\n def sumAll: Int = sum(n)\n\n // A がLongとかじゃない場合はこれらを実装しないと下の奴らが使えない\n private def sub(a: Int, b: Int) = a - b\n private def lt(a: Int, b: Int) = a < b\n\n /**\n * [l, r)\n */\n def query(l: Int, r: Int): Int = {\n assert(r > l)\n sub(sum(r), sum(l))\n }\n\n def lowerBound(W: Int): Int = {\n var k = N\n var x = 0\n var w = W\n while(k > 0) {\n if (x + k <= N && lt(bit(x + k), w)) {\n w = sub(w, bit(x + k))\n x += k\n }\n k /= 2\n }\n math.min(n, x)\n }\n}\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n import java.util.Comparator\n val N = ni()\n val A = na(N)\n val E = Array.ofDim[Entry](N)\n REP(N) { i =>\n E(i) = Entry(A(i), i)\n }\n sort(E, new Comparator[Entry] {\n override def compare(o1: Entry, o2: Entry): Int = {\n if (o1.a == o2.a) Integer.compare(o1.i, o2.i)\n else Integer.compare(o2.a, o1.a) // 降順\n }\n })\n val M = ni()\n val queried = Array.fill[ArrayBuffer[Query]](N)(ArrayBuffer())\n val ans = Array.ofDim[Int](M)\n REP(M) { m =>\n val k, pos = ni()\n val q = Query(k, pos, m)\n queried(k - 1) += q\n }\n\n val bit = new BIT(N)\n REP(N) { i =>\n bit.add(E(i).i, 1)\n queried(i).foreach { q =>\n val ix = bit.lowerBound(q.pos)\n ans(q.m) = A(ix)\n }\n }\n\n REP(M) { i =>\n out.println(ans(i))\n }\n }\n}"}], "negative_code": [{"source_code": "object B2 {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n /**\n * 1-based Binary Indexed (Fenwick) Tree with binary search.\n */\n final class BIT(src: Array[Long]) {\n\n private val t = Array.fill(src.length + 1) { 0L }\n\n for (i <- src.indices) update(i + 1, src(i))\n\n def query(r: Int, acc: Long = 0): Long =\n if (r <= 0) acc else query(r - (r & -r), acc + t(r))\n\n def rangeQuery(l: Int, r: Int): Long = query(r) - query(l - 1)\n\n def update(i: Int, delta: Long): Unit = {\n if (i < t.length) {\n t(i) += delta\n update(i + (i & -i), delta)\n }\n }\n\n def firstGreaterOrEqual(goal: Long): Int = {\n var sum = 0L\n var idx = 0\n var bitMask = Integer.highestOneBit(t.length)\n while (bitMask > 0) {\n val newIdx = idx + bitMask\n if (newIdx < t.length && sum + t(newIdx) < goal) {\n idx = newIdx\n sum += t(idx)\n }\n bitMask >>>= 1\n }\n idx + 1\n }\n\n }\n\n val n = nextInt\n val as = nextInts(n)\n val G = 1\n val sorted = as.zipWithIndex.sortBy {\n case (x, i) => (x, -i)\n }\n val order = Array.ofDim[Int](n)\n for (i <- as.indices) {\n order(sorted(i)._2) = i\n }\n\n val m = nextInt\n case class Query(k: Int, pos: Int, id: Int)\n val queries = Array.tabulate(m) { id =>\n val k, pos = nextInt\n Query(k, pos, id)\n }.sortBy(_.k)\n\n val res = Array.ofDim[Int](m)\n val bit = new BIT(Array.fill(n)(0L))\n\n var currentK = 0\n for (q <- queries) {\n while (currentK < q.k) {\n bit.update(order(currentK) + 1, +1)\n currentK += 1\n }\n val i = bit.firstGreaterOrEqual(q.pos) - 1\n res(q.id) = as(i)\n }\n\n out.println(res.mkString(\"\\n\"))\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "src_uid": "082eec813f870357dbe3c5abec6a2b52"} {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val MOD = 1000000007L\n val MODB = BigInt(MOD)\n\n val v = mutable.Map.empty[(Int, Int), Long]\n\n val Array(h, w, n) = readInts(3)\n\n val fs, fInvs = Array.ofDim[Long](h + w)\n\n var f = 1L\n for (i <- fs.indices) {\n fs(i) = f\n fInvs(i) = BigInt(f).modInverse(MODB).toLong\n f = f * (i + 1) % MOD\n }\n \n def pascal(r: Int, c: Int): Long = {\n val k = r - 1\n val n = r + c - 2\n (fs(n) * fInvs(n - k) % MOD) * fInvs(k) % MOD\n }\n\n val black = Array.ofDim[(Int, Int)](n)\n\n for (i <- 0 until n) {\n val Array(r, c) = readInts(2)\n black(i) = (r, c)\n }\n\n val sorted = black.sorted\n\n for (i <- 0 until n) {\n val (r, c) = sorted(i)\n var d = pascal(r, c)\n for (j <- 0 until n) {\n val (r2, c2) = sorted(j)\n if (r2 <= r && c2 <= c && i != j) {\n d = (d + MOD - v(r2, c2) * pascal(r - r2 + 1, c - c2 + 1) % MOD) % MOD\n }\n }\n v += (r, c) -> d\n }\n\n var res = pascal(h, w)\n\n for (i <- 0 until n) {\n val (r, c) = sorted(i)\n res = (res + MOD - v(r, c) * pascal(h - r + 1, w - c + 1) % MOD) % MOD\n }\n\n println(res)\n}\n", "positive_code": [{"source_code": "object C2{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n //import scala.collection.mutable.Set\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val hugeNum=1000000007L\n val maxhw=100000+10\n\n val h=nextInt\n val w=nextInt\n val n=nextInt\n val badArray=(for (i<-0 until n+1) yield if(i!=n) (nextInt-1,nextInt-1) else (h-1,w-1)) sorted\n //inverse table\n val inverseModuloTable=Array.fill(maxhw)(1L)\n \n var numStart=hugeNum-2\n\n var dv=1\n while(dv0){\n for(i<-0 until maxhw){\n inverseModuloTable(i)=(inverseModuloTable(i)*inverseModuloTable(i))%hugeNum\n }\n if(numStart>=dv){\n for(i<-0 until maxhw){\n inverseModuloTable(i)=(inverseModuloTable(i)*i)%hugeNum\n }\n numStart-=dv\n }\n dv/=2\n }\n for(i<-2 until maxhw){\n inverseModuloTable(i)=(inverseModuloTable(i-1)*inverseModuloTable(i))%hugeNum\n }\n inverseModuloTable(0)=1\n val prodModuloTable=Array.fill(maxhw*2)(1L)\n for(i<-2 until prodModuloTable.length){\n prodModuloTable(i)=(prodModuloTable(i-1)*i)%hugeNum\n }\n //C function\n def combFact(n:Int,m:Int):Int={\n var ans=(prodModuloTable(n)*inverseModuloTable(n-m))%hugeNum\n \n\n ans=(ans*inverseModuloTable(m))%hugeNum\n \n return ans toInt\n }\n //solve problem\n val D=Array.fill(n+1)(0L)\n\n for(i<-0 until n+1){\n \n val (ac,bc)=badArray(i)\n D(i)=combFact(ac+bc,ac)\n \n for(j<-0 until i){\n val (a0,b0)=badArray(j)\n if(a0<=ac && b0<=bc){\n \n D(i)-=(D(j)*combFact(ac+bc-a0-b0,ac-a0))%hugeNum-hugeNum\n D(i)%=hugeNum\n }\n }\n \n }\n out.println(D(n))\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "import io.StdIn._\n\nobject Solution {\n\n val mod: Long = 1000000007\n\n val maxn = 200000\n\n val fac = Array.fill(maxn+1)(1L)\n\n val inv = Array.fill(maxn+1)(1L)\n\n def main(args: Array[String]) {\n val line = readLine().split(\" \").map(_.toInt)\n val (h, w, n) = (line(0), line(1), line(2))\n\n var black = Array.ofDim[(Int, Int)](n).map{ _ =>\n val line = readLine().split(\" \").map(_.toInt)\n (line(0), line(1))\n }\n\n for (i <- 1 to maxn) {\n fac(i) = fac(i-1) * i % mod\n inv(i) = pow(fac(i), mod-2)\n }\n\n black = black.sorted ++ Array((h, w))\n\n val f = black.map( b => cab(1, 1, b._1, b._2) )\n\n for (\n (c, i) <- black.zipWithIndex;\n (p, j) <- black.take(i).zipWithIndex if c._1 >= p._1 && c._2 >= p._2\n ) {\n f(i) = (f(i) - (f(j) * cab(p._1, p._2, c._1, c._2) % mod) + mod) % mod\n }\n\n println(f(n))\n\n }\n\n private def pow(aa: Long, nn: Long): Long = {\n var (a, n) = (aa, nn)\n var res = 1L\n while (n > 0) {\n if ((n & 1) == 1) res = res * a % mod\n a = a * a % mod\n n >>= 1\n }\n res % mod\n }\n\n private def cab(ax: Int, ay: Int, bx: Int, by: Int): Long = {\n val m: Int = bx - ax + by - ay\n val n: Int = bx - ax\n fac(m) * inv(n) % mod * inv(m-n) % mod\n }\n\n}\n"}], "negative_code": [{"source_code": "object C2{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n //import scala.collection.mutable.Set\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val hugeNum=1000000007L\n val maxhw=100000+10\n\n val h=nextInt\n val w=nextInt\n val n=nextInt\n val badArray=(for (i<-0 until n+1) yield if(i!=n) (nextInt-1,nextInt-1) else (h-1,w-1)) sorted\n //inverse table\n val inverseModuloTable=Array.fill(maxhw)(1L)\n\n var numStart=hugeNum-2\n\n var dv=1\n while(dv0){\n for(i<-0 until maxhw){\n inverseModuloTable(i)=(inverseModuloTable(i)*inverseModuloTable(i))%hugeNum\n }\n if(numStart>=dv){\n for(i<-0 until maxhw){\n inverseModuloTable(i)=(inverseModuloTable(i)*i)%hugeNum\n }\n numStart-=dv\n }\n dv/=2\n }\n for(i<-2 until maxhw){\n inverseModuloTable(i)=(inverseModuloTable(i-1)*inverseModuloTable(i))%hugeNum\n }\n \n //C function\n def combFact(n:Int,m:Int):Int={\n var ans=1L\n for(i<-n-m+1 to n){\n ans=(ans*i)%hugeNum\n }\n\n ans=(ans*inverseModuloTable(m))%hugeNum\n \n return ans toInt\n }\n //solve problem\n val D=Array.fill(n+1)(0L)\n\n for(i<-0 until n+1){\n \n val (ac,bc)=badArray(i)\n D(i)=combFact(ac+bc,ac)\n for(j<-0 until i){\n val (a0,b0)=badArray(j)\n if(a0<=ac && b0<=bc){\n D(i)-=(D(j)*combFact(ac+bc-a0-b0,ac-a0))%hugeNum-hugeNum\n D(i)%=hugeNum\n }\n }\n \n }\n out.println(D(n))\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object C2{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n //import scala.collection.mutable.Set\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val hugeNum=1000000007L\n val maxhw=100000+10\n\n val h=nextInt\n val w=nextInt\n val n=nextInt\n val badArray=(for (i<-0 until n+1) yield if(i!=n) (nextInt-1,nextInt-1) else (h-1,w-1)) sorted\n //inverse table\n val inverseModuloTable=Array.fill(maxhw)(1L)\n\n var numStart=hugeNum-2\n\n var dv=1\n while(dv0){\n for(i<-0 until maxhw){\n inverseModuloTable(i)=(inverseModuloTable(i)*inverseModuloTable(i))%hugeNum\n }\n if(numStart>=dv){\n for(i<-0 until maxhw){\n inverseModuloTable(i)=(inverseModuloTable(i)*i)%hugeNum\n }\n numStart-=dv\n }\n dv/=2\n }\n for(i<-1 until maxhw){\n inverseModuloTable(i)=(inverseModuloTable(i-1)*inverseModuloTable(i))%hugeNum\n }\n //C function\n def combFact(n:Int,m:Int):Int={\n var ans=1L\n for(i<-n-m+1 to n){\n ans=(ans*i)%hugeNum\n }\n\n ans=(ans*inverseModuloTable(m))%hugeNum\n \n return ans toInt\n }\n //solve problem\n val D=Array.fill(n+1)(0L)\n\n for(i<-0 until n+1){\n \n val (ac,bc)=badArray(i)\n D(i)=combFact(ac+bc,ac)\n for(j<-0 until i){\n val (a0,b0)=badArray(j)\n if(a0<=ac && b0<=bc){\n D(i)-=(D(j)*combFact(ac+bc-a0-b0,ac-a0))%hugeNum-hugeNum\n D(i)%=hugeNum\n }\n }\n \n }\n out.println(D(n))\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object C2{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n //import scala.collection.mutable.Set\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val hugeNum=1000000007L\n val maxhw=100000+10\n\n val h=nextInt\n val w=nextInt\n val n=nextInt\n val badArray=(for (i<-0 until n+1) yield if(i!=n) (nextInt-1,nextInt-1) else (h-1,w-1)) sorted\n //inverse table\n val inverseModuloTable=Array.fill(maxhw)(1L)\n\n var numStart=hugeNum-2\n\n var dv=1\n while(dv0){\n for(i<-0 until maxhw){\n inverseModuloTable(i)=(inverseModuloTable(i)*inverseModuloTable(i))%hugeNum\n }\n if(numStart>=dv){\n for(i<-0 until maxhw){\n inverseModuloTable(i)=(inverseModuloTable(i)*i)%hugeNum\n }\n numStart-=dv\n }\n dv/=2\n }\n\n //C function\n def combFact(n:Int,m:Int):Int={\n var ans=1L\n for(i<-n-m+1 to n){\n ans=(ans*i)%hugeNum\n }\n for(i<-1 to m){\n ans=(ans*inverseModuloTable(i))%hugeNum\n }\n return ans toInt\n }\n //solve problem\n val D=Array.fill(n+1)(0L)\n\n for(i<-0 until n+1){\n \n val (ac,bc)=badArray(i)\n D(i)=combFact(ac+bc,ac)\n for(j<-0 until i){\n val (a0,b0)=badArray(j)\n if(a0<=ac && b0<=bc){\n D(i)-=(D(j)*combFact(ac+bc-a0-b0,ac-a0))%hugeNum\n D(i)%=hugeNum\n }\n }\n \n }\n out.println(D(n))\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "src_uid": "91749edcc396819d4172d06e2744b20b"} {"source_code": "import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _651C extends CodeForcesApp {\n override def solve(in: InputReader, out: OutputWriter) = {\n val n = in[Int]\n val xc, yc = map[Int] to 0L\n val pc = map[(Int, Int)] to 0L\n\n repeat(n) {\n val x, y = in[Int]\n xc(x) += 1\n yc(y) += 1\n pc(x -> y) += 1\n }\n\n val res = pc map {\n case ((x, y), c) =>\n val i = xc(x) - c\n val j = yc(y) - c\n //debug(x, y, c, i, j, (i + j)*c)\n (i + j)*c + (c*(c-1))\n }\n out += res.sum/2\n }\n\n def map[K] = new {\n def to[V](default: V): mutable.Map[K, V] = mutable.Map.empty[K, V] withDefaultValue default\n }\n\n @inline def repeat(n: Int)(f: => Unit): Unit = for {_ <- 1 to n} f\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def solve(in: InputReader, out: OutputWriter): Any\n def main(args: Array[String]): Unit = {\n val (in, out) = (new InputReader(System.in), new OutputWriter(System.out))\n solve(in, out)\n in.close()\n out.close()\n }\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n def apply[C[_], A: Parser](n: Int)(implicit builder: Parser.Collection[C, A]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\n\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n\nclass OutputWriter(out: PrintWriter) extends AutoCloseable {\n def this(out: OutputStream) = this(new PrintWriter(out))\n\n var separator = \" \"\n private[this] var isNewLine: Boolean = true\n\n def +=(obj: Any): this.type = {\n if (isNewLine) isNewLine = false else out.print(separator)\n out.print(obj)\n this\n }\n\n def newLine(): this.type = {\n isNewLine = true\n out.println()\n this\n }\n\n def ++=(obj: Traversable[_], ifEmpty: => Any = \"\"): this.type = {\n var c = 0\n obj foreach {i =>\n this += i\n c += 1\n }\n if (c == 0) this += ifEmpty else this\n }\n\n def append(obj: Any*): this.type = this ++= obj\n\n override def close() = {\n out.flush()\n out.close()\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.Scanner\n\nimport scala.collection.mutable\n\nobject Solution extends ConsoleIO {\n def main(args: Array[String]) = {\n withIO { (reader, writer) =>\n val n = reader.nextInt()\n val forX = mutable.HashMap.empty[Int, Int]\n val forY = mutable.HashMap.empty[Int, Int]\n val elementToCount = mutable.HashMap.empty[(Int, Int), Int]\n for (i <- 0 until n) {\n val x = reader.nextInt()\n val y = reader.nextInt()\n val xx = forX.get(x)\n forX.put(x, xx.getOrElse(0) + 1)\n\n val yy = forY.get(y)\n forY.put(y, yy.getOrElse(0) + 1)\n\n val zz = elementToCount.get((x, y))\n elementToCount.put((x, y), zz.getOrElse(0) + 1)\n }\n var result: Long = calc(forX) + calc(forY)\n for (el <- elementToCount) {\n result -= (el._2.toLong * (el._2.toLong - 1L)) / 2L\n }\n writer.print(result)\n }\n }\n\n def calc(h: mutable.HashMap[Int, Int]): Long = {\n var answer: Long = 0\n for (el <- h) {\n answer += (el._2.toLong * (el._2.toLong - 1L)) / 2L\n }\n answer\n }\n}\n\ntrait ConsoleIO {\n def withIO(task: (Scanner, PrintWriter) => Unit) = {\n val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))\n val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n task(reader, writer)\n reader.close()\n writer.close()\n }\n}\n\ntrait FileIO {\n def withIO(task: (Scanner, PrintWriter) => Unit) = {\n val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream(\"input.txt\"))))\n val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(\"output.txt\"))))\n task(reader, writer)\n reader.close()\n writer.close()\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n\n override def toString = s\"MultiHashSet($map)\"\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val d = new Array[(Int, Int)](n)\n for (i <- 0 until n) {\n d(i) = (nextInt, nextInt)\n }\n var ans = 0L\n val byX = d.sortBy(x => x._1)\n val byY = d.sortBy(x => x._2)\n var tmp = 1L\n var prev = byX(0)._1\n for (i <- 1 until n) {\n if (byX(i)._1 == byX(i - 1)._1) {\n tmp += 1\n } else {\n prev = byX(i)._1\n ans += (tmp * (tmp - 1L)) / 2\n tmp = 1\n }\n }\n ans += (tmp * (tmp - 1L)) / 2\n tmp = 1\n prev = byY(0)._2\n for (i <- 1 until n) {\n if (byY(i)._2 == byY(i - 1)._2) {\n tmp += 1\n } else {\n prev = byY(i)._2\n ans += (tmp * (tmp - 1L)) / 2\n tmp = 1\n }\n }\n ans += (tmp * (tmp - 1L)) / 2\n val sorted = d.sortBy(r => (r._1, r._2))\n var common = 1L\n var ind = 1\n while (ind < n) {\n while (ind < n && sorted(ind)._1 == sorted(ind - 1)._1 && sorted(ind)._2 == sorted(ind - 1)._2) {\n common += 1\n ind += 1\n }\n ans -= (common * (common - 1L)) / 2\n common = 1\n ind += 1\n }\n out.println(ans)\n return 0\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\nobject ProblemCScala {\n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n\n def readLongs() : Array[Long] =\n readLine.split(' ').map(_.toLong)\n\n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n\n\n\n\n def main(args: Array[String]) {\n val n : Int = readInt();\n\n val xys = for {\n i <- 1 to n\n xy = readInts()\n } yield (xy(0), xy(1))\n\n val xsorted = xys.sortBy(r => (r._1,r._2))\n val ysorted = xys.sortBy(_._2)\n\n //println(xsorted)\n\n //println(ysorted)\n\n var total : Long = 0\n var i : Int = 0;\n while (i < n) {\n val start : Int = i;\n var l : Long = 1\n i = i + 1\n while (i < n && xsorted(start)._1 == xsorted(i)._1) {\n l = l + 1;\n i = i + 1;\n }\n //println(s\"sequence of length $l\")\n total = total + (l-1)*l/2;\n }\n i = 0;\n while (i < n) {\n val start : Int = i;\n var l : Long = 1\n i = i + 1\n while (i < n && ysorted(start)._2 == ysorted(i)._2) {\n l = l + 1\n i = i + 1\n }\n //println(s\"sequence of length $l\")\n total = total + (l-1)*l/2;\n }\n\n i = 0;\n var dc : Long = 0;\n i = 0;\n while (i < n) {\n val start : Int = i;\n var l : Long = 1\n i = i + 1\n while (i < n && xsorted(start) == xsorted(i)) {\n l = l + 1;\n i = i + 1;\n }\n //println(s\"sequence of length $l\")\n dc = dc + (l-1)*l/2;\n }\n\n total = total - dc\n\n println(total)\n\n\n }\n\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map{ _ =>\n val a = in.next().split(' ').map(_.toInt)\n (a.head, a.last)\n }\n val same = data.groupBy(i => i).filter(_._2.length > 1).map(_._2.length.toLong).map(k => (k - 1) * k / 2).sum\n val vertical = data.groupBy(i => i._2).filter(_._2.length > 1).map(_._2.length.toLong).map(k => (k - 1) * k / 2).sum\n val horizontal = data.groupBy(i => i._1).filter(_._2.length > 1).map(_._2.length.toLong).map(k => (k - 1) * k / 2).sum\n println(vertical + horizontal - same)\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C345A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C345A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val a: immutable.IndexedSeq[Point] = 0 until n by 1 map { _ =>\n Point(ni(), ni())\n }\n val ans = 0L\n val cntx: Long = a.groupBy(_.x).map(_._2.size).filter(1<).map(f => (f.toLong * (f-1)) / 2).sum\n val cnty: Long = a.groupBy(_.y).map(_._2.size).filter(1<).map(f => (f.toLong * (f-1)) / 2).sum\n val x = a.groupBy(identity).map(_._2.size).filter(1<).map(f => (f.toLong * (f-1)) / 2).sum\n println(cntx + cnty - x)\n }\n\n case class Point (\n x: Int,\n y: Int\n )\n}\n"}, {"source_code": "object A650 {\n\n import IO._\n import collection.{mutable => cu}\n\n def hash(a: Int, b: Int): Long = {\n a*(10000000001L) + b\n }\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val x = cu.Map.empty[Int, Int].withDefaultValue(0)\n val y = cu.Map.empty[Int, Int].withDefaultValue(0)\n val xy = cu.Map.empty[Long, Int].withDefaultValue(0)\n var res = 0L\n for(_ <- 0 until n) {\n val Array(a, b) = readInts(2)\n res += x(a)\n x(a) += 1\n res += y(b)\n y(b) += 1\n res -= xy(hash(a, b))\n xy(hash(a, b)) += 1\n }\n println(res)\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object A650 {\n\n import IO._\n import collection.{mutable => cu}\n\n def hash(a: Int, b: Int): Long = {\n a*2000000001L + b\n }\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val x = cu.Map.empty[Int, Int].withDefaultValue(0)\n val y = cu.Map.empty[Int, Int].withDefaultValue(0)\n val xy = cu.Map.empty[Long, Int].withDefaultValue(0)\n var res = 0L\n for(_ <- 0 until n) {\n val Array(a, b) = readInts(2)\n res += x(a)\n x(a) += 1\n res += y(b)\n y(b) += 1\n res -= xy(hash(a, b))\n xy(hash(a, b)) += 1\n }\n println(res)\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object A650 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val x = cu.Map.empty[Int, Int].withDefaultValue(0)\n val y = cu.Map.empty[Int, Int].withDefaultValue(0)\n val xy = cu.Map.empty[(Int, Int), Int].withDefaultValue(0)\n var res = 0L\n for(_ <- 0 until n) {\n val Array(a, b) = readInts(2)\n res += x(a)\n x(a) += 1\n res += y(b)\n y(b) += 1\n res -= xy((a, b))\n xy((a, b)) += 1\n }\n println(res)\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object A650 {\n\n import IO._\n import collection.{mutable => cu}\n\n def hash(a: Int, b: Int): Long = {\n a*(1L << 32) + b\n }\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val x = cu.Map.empty[Int, Int].withDefaultValue(0)\n val y = cu.Map.empty[Int, Int].withDefaultValue(0)\n val xy = cu.Map.empty[Long, Int].withDefaultValue(0)\n var res = 0L\n for(_ <- 0 until n) {\n val Array(a, b) = readInts(2)\n res += x(a)\n x(a) += 1\n res += y(b)\n y(b) += 1\n res -= xy(hash(a, b))\n xy(hash(a, b)) += 1\n }\n println(res)\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.Scanner\n\nimport scala.collection.mutable\n\nobject Solution extends ConsoleIO {\n def main(args: Array[String]) = {\n withIO { (reader, writer) =>\n val n = reader.nextInt()\n var answer: Long = 0\n val forX = mutable.HashMap.empty[Int, Int]\n val forY = mutable.HashMap.empty[Int, Int]\n val elements = mutable.HashSet.empty[(Int, Int)]\n val doubles = mutable.HashSet.empty[(Int, Int)]\n for (i <- 0 until n) {\n val x = reader.nextInt()\n val y = reader.nextInt()\n if (!elements.contains((x, y))) {\n val xx = forX.get(x)\n forX.put(x, xx.getOrElse(0) + 1)\n\n val yy = forY.get(y)\n forY.put(y, yy.getOrElse(0) + 1)\n\n elements.+=((x, y))\n } else {\n doubles.+=((x, y))\n }\n }\n var result: Long = calc(forX) + calc(forY)\n for (el <- doubles) {\n result += forX.getOrElse(el._1, 0)\n result += (forY.getOrElse(el._2, 0) - 1)\n }\n writer.print(result)\n }\n }\n\n def calc(h: mutable.HashMap[Int, Int]): Long = {\n var answer: Long = 0\n for (el <- h) {\n answer += (el._2 * (el._2 - 1)) / 2\n }\n answer\n }\n}\n\ntrait ConsoleIO {\n def withIO(task: (Scanner, PrintWriter) => Unit) = {\n val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))\n val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n task(reader, writer)\n reader.close()\n writer.close()\n }\n}\n\ntrait FileIO {\n def withIO(task: (Scanner, PrintWriter) => Unit) = {\n val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream(\"input.txt\"))))\n val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(\"output.txt\"))))\n task(reader, writer)\n reader.close()\n writer.close()\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.Scanner\n\nimport scala.collection.mutable\n\nobject Solution extends ConsoleIO {\n def main(args: Array[String]) = {\n withIO { (reader, writer) =>\n val n = reader.nextInt()\n val forX = mutable.HashMap.empty[Int, Int]\n val forY = mutable.HashMap.empty[Int, Int]\n val elements = mutable.HashSet.empty[(Int, Int)]\n val doubles = mutable.HashMap.empty[(Int, Int), Int]\n for (i <- 0 until n) {\n val x = reader.nextInt()\n val y = reader.nextInt()\n if (!elements.contains((x, y))) {\n val xx = forX.get(x)\n forX.put(x, xx.getOrElse(0) + 1)\n\n val yy = forY.get(y)\n forY.put(y, yy.getOrElse(0) + 1)\n\n elements.+=((x, y))\n } else {\n val xx = doubles.get((x, y))\n doubles.put((x, y), xx.getOrElse(0) + 1)\n }\n }\n var result: Long = calc(forX) + calc(forY)\n for (el <- doubles) {\n result += forX.getOrElse(el._1._1, 0).toLong * el._2.toLong + (el._2.toLong * (el._2.toLong - 1L)) / 2L\n result += (forY.getOrElse(el._1._2, 0).toLong - 1L) * el._2.toLong\n }\n writer.print(result)\n }\n }\n\n def calc(h: mutable.HashMap[Int, Int]): Long = {\n var answer: Long = 0\n for (el <- h) {\n answer += (el._2.toLong * (el._2.toLong - 1L)) / 2L\n }\n answer\n }\n}\n\ntrait ConsoleIO {\n def withIO(task: (Scanner, PrintWriter) => Unit) = {\n val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))\n val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n task(reader, writer)\n reader.close()\n writer.close()\n }\n}\n\ntrait FileIO {\n def withIO(task: (Scanner, PrintWriter) => Unit) = {\n val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream(\"input.txt\"))))\n val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(\"output.txt\"))))\n task(reader, writer)\n reader.close()\n writer.close()\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.Scanner\n\nimport scala.collection.mutable\n\nobject Solution extends ConsoleIO {\n def main(args: Array[String]) = {\n withIO { (reader, writer) =>\n val n = reader.nextInt()\n val forX = mutable.HashMap.empty[Int, Int]\n val forY = mutable.HashMap.empty[Int, Int]\n val elements = mutable.HashSet.empty[(Int, Int)]\n val doubles = mutable.HashMap.empty[(Int, Int), Int]\n for (i <- 0 until n) {\n val x = reader.nextInt()\n val y = reader.nextInt()\n if (!elements.contains((x, y))) {\n val xx = forX.get(x)\n forX.put(x, xx.getOrElse(0) + 1)\n\n val yy = forY.get(y)\n forY.put(y, yy.getOrElse(0) + 1)\n\n elements.+=((x, y))\n } else {\n val xx = doubles.get((x, y))\n doubles.put((x, y), xx.getOrElse(0) + 1)\n }\n }\n var result: Long = calc(forX) + calc(forY)\n for (el <- doubles) {\n result += forX.getOrElse(el._1._1, 0) * el._2 + (el._2 * (el._2 - 1)) / 2\n result += (forY.getOrElse(el._1._2, 0) - 1) * el._2\n }\n writer.print(result)\n }\n }\n\n def calc(h: mutable.HashMap[Int, Int]): Long = {\n var answer: Long = 0\n for (el <- h) {\n answer += (el._2 * (el._2 - 1)) / 2\n }\n answer\n }\n}\n\ntrait ConsoleIO {\n def withIO(task: (Scanner, PrintWriter) => Unit) = {\n val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))\n val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n task(reader, writer)\n reader.close()\n writer.close()\n }\n}\n\ntrait FileIO {\n def withIO(task: (Scanner, PrintWriter) => Unit) = {\n val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream(\"input.txt\"))))\n val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(\"output.txt\"))))\n task(reader, writer)\n reader.close()\n writer.close()\n }\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n\n override def toString = s\"MultiHashSet($map)\"\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val d = new Array[(Int, Int)](n)\n for (i <- 0 until n) {\n d(i) = (nextInt, nextInt)\n }\n var ans = 0\n val byX = d.sortBy(x => x._1)\n val byY = d.sortBy(x => x._2)\n var tmp = 1\n var prev = byX(0)._1\n for (i <- 1 until n) {\n if (byX(i)._1 == byX(i - 1)._1) {\n if (byX(i)._1 == prev) {\n tmp += 1\n } else {\n prev = byX(i)._1\n ans += (tmp * (tmp - 1)) / 2\n tmp = 1\n }\n } else {\n prev = byX(i)._1\n }\n }\n ans += (tmp * (tmp - 1)) / 2\n tmp = 1\n prev = byY(0)._2\n for (i <- 1 until n) {\n if (byY(i)._2 == byY(i - 1)._2) {\n if (byY(i)._2 == prev) {\n tmp += 1\n } else {\n prev = byY(i)._2\n ans += (tmp * (tmp - 1)) / 2\n tmp = 1\n }\n } else {\n prev = byY(i)._2\n }\n }\n ans += (tmp * (tmp - 1)) / 2\n val sorted = d.sortBy(r => (r._1, r._2))\n var common = 1\n for (i <- 1 until n) {\n if (sorted(i)._1 == sorted(i - 1)._1 && sorted(i)._2 == sorted(i - 1)._2) {\n common += 1\n }\n }\n out.println(ans - (common * (common - 1)) / 2)\n return 0\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n\n override def toString = s\"MultiHashSet($map)\"\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val d = new Array[(Int, Int)](n)\n for (i <- 0 until n) {\n d(i) = (nextInt, nextInt)\n }\n var ans = 0\n val byX = d.sortBy(x => x._1)\n val byY = d.sortBy(x => x._2)\n for (i <- 1 until n) {\n if (byX(i)._1 == byX(i - 1)._1) {\n ans += 1\n }\n }\n for (i <- 1 until n) {\n if (byY(i)._2 == byY(i - 1)._2) {\n ans += 1\n }\n }\n val sorted = d.sortBy(r => (r._1, r._2))\n var common = 0\n for (i <- 1 until n) {\n if (sorted(i)._1 == sorted(i - 1)._1 && sorted(i)._2 == sorted(i - 1)._2) {\n common += 1\n }\n }\n out.println(ans - (common * (common - 1)) / 2)\n return 0\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\nobject ProblemCScala {\n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n\n def readLongs() : Array[Long] =\n readLine.split(' ').map(_.toLong)\n\n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n\n\n\n\n def main(args: Array[String]) {\n val n : Int = readInt();\n\n val xys = for {\n i <- 1 to n\n xy = readInts()\n } yield (xy(0), xy(1))\n\n val xsorted = xys.sortBy(r => (r._1,r._2))\n val ysorted = xys.sortBy(_._2)\n\n //println(xsorted)\n\n //println(ysorted)\n\n var total : Int = 0\n var i : Int = 0;\n while (i < n) {\n val start : Int = i;\n var l : Int = 1\n i = i + 1\n while (i < n && xsorted(start)._1 == xsorted(i)._1) {\n l = l + 1;\n i = i + 1;\n }\n //println(s\"sequence of length $l\")\n total = total + (l-1)*l/2;\n }\n i = 0;\n while (i < n) {\n val start : Int = i;\n var l : Int = 1\n i = i + 1\n while (i < n && ysorted(start)._2 == ysorted(i)._2) {\n l = l + 1;\n i = i + 1;\n }\n //println(s\"sequence of length $l\")\n total = total + (l-1)*l/2;\n }\n\n i = 0;\n var dc : Int = 0;\n i = 0;\n while (i < n) {\n val start : Int = i;\n var l : Int = 1\n i = i + 1\n while (i < n && xsorted(start) == xsorted(i)) {\n l = l + 1;\n i = i + 1;\n }\n //println(s\"sequence of length $l\")\n dc = dc + (l-1)*l/2;\n }\n\n total = total - dc\n\n println(total)\n\n\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\nobject ProblemCScala {\n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n\n def readLongs() : Array[Long] =\n readLine.split(' ').map(_.toLong)\n\n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n\n\n\n\n def main(args: Array[String]) {\n val n : Int = readInt();\n\n val xys = for {\n i <- 1 to n\n xy = readInts()\n } yield (xy(0), xy(1))\n\n val xsorted = xys.sortBy(r => (r._1,r._2))\n val ysorted = xys.sortBy(_._2)\n\n //println(xsorted)\n\n //println(ysorted)\n\n var total : Long = 0\n var i : Int = 0;\n while (i < n) {\n val start : Int = i;\n var l : Int = 1\n i = i + 1\n while (i < n && xsorted(start)._1 == xsorted(i)._1) {\n l = l + 1;\n i = i + 1;\n }\n //println(s\"sequence of length $l\")\n total = total + (l-1)*l/2;\n }\n i = 0;\n while (i < n) {\n val start : Int = i;\n var l : Int = 1\n i = i + 1\n while (i < n && ysorted(start)._2 == ysorted(i)._2) {\n l = l + 1\n i = i + 1\n }\n //println(s\"sequence of length $l\")\n total = total + (l-1)*l/2;\n }\n\n i = 0;\n var dc : Int = 0;\n i = 0;\n while (i < n) {\n val start : Int = i;\n var l : Int = 1\n i = i + 1\n while (i < n && xsorted(start) == xsorted(i)) {\n l = l + 1;\n i = i + 1;\n }\n //println(s\"sequence of length $l\")\n dc = dc + (l-1)*l/2;\n }\n\n total = total - dc\n\n println(total)\n\n\n }\n\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map{ _ =>\n val a = in.next().split(' ').map(_.toLong)\n (a.head, a.last)\n }\n val same = data.groupBy(i => i).filter(_._2.length > 1).map(_._2.length).map(k => (k - 1) * k / 2).sum\n val vertical = data.groupBy(i => i._2).filter(_._2.length > 1).map(_._2.length).map(k => (k - 1) * k / 2).sum\n val horizontal = data.groupBy(i => i._1).filter(_._2.length > 1).map(_._2.length).map(k => (k - 1) * k / 2).sum\n println(vertical + horizontal - same)\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map{ _ =>\n val a = in.next().split(' ').map(_.toInt)\n (a.head, a.last)\n }\n val same = data.groupBy(i => i).filter(i => i._2.length > 1).map(i => i._2.length).map(k => (k - 1) * k / 2).sum\n val vertical = data.groupBy(i => i._2).filter(i => i._2.length > 1).map(i => i._2.length).map(k => (k - 1) * k / 2).sum\n val horizontal = data.groupBy(i => i._1).filter(i => i._2.length > 1).map(i => i._2.length).map(k => (k - 1) * k / 2).sum\n println(vertical + horizontal - same)\n}\n"}, {"source_code": "object A650 {\n\n import IO._\n import collection.{mutable => cu}\n\n def hash(a: Int, b: Int): Long = {\n a*1000000001L + b\n }\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val x = cu.Map.empty[Int, Int].withDefaultValue(0)\n val y = cu.Map.empty[Int, Int].withDefaultValue(0)\n val xy = cu.Map.empty[Long, Int].withDefaultValue(0)\n var res = 0L\n for(_ <- 0 until n) {\n val Array(a, b) = readInts(2)\n res += x(a)\n x(a) += 1\n res += y(b)\n y(b) += 1\n res -= xy(hash(a, b))\n xy(hash(a, b)) += 1\n }\n println(res)\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "bd7b85c0204f6b36dc07f8a96fc36161"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val price = in.next().split(' ').map(_.toLong)\n val capitals = in.next().split(' ').map(_.toInt - 1).toSet\n val sum = capitals.toList.map(price).sum\n val nonCapitals = price.indices.filterNot(capitals.contains).map(price).sum\n val capitalsPriceSum = capitals.toList.map(i => price(i) * (sum - price(i))).sum / 2\n val capToUncap = capitals.toList.map(i => price(i) * nonCapitals).sum\n val lineSum = (n - 1 :: price.indices.toList).sliding(2)\n .filterNot(i => capitals.contains(i.head) || capitals.contains(i.last))\n .map(i => price(i.head) * price(i.last)).sum\n println(capitalsPriceSum + lineSum + capToUncap)\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val C = readLine().split(\" \").map(_.toLong)\n val Cap = readLine().split(\" \").map(i => i.toInt - 1)\n\n val IsCapital = Array.ofDim[Boolean](n)\n Cap.foreach { i => IsCapital(i) = true }\n\n var sum = C.sum\n var total = 0L\n for (i <- 0 until k) {\n val j = Cap(i)\n total += C(j) * (sum - C(j))\n sum -= C(j)\n }\n\n for (i <- 0 until n) {\n val next = (i + 1) % n\n if (!IsCapital(i) && !IsCapital(next)) {\n total += C(i) * C(next)\n }\n }\n\n println(total)\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _703B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val n, k = read[Int]\n val beauty = read[Vector, Long](n)\n val capitals = read[Set, Int](k).map(_ - 1)\n\n var total = beauty.sum\n var ans = 0L\n\n def add(u: Int, v: Int): Unit = if(!capitals(u) && !capitals(v)) {\n ans += beauty(u)*beauty(v)\n //debug(u, v, ans)\n }\n\n beauty.indices foreach {i =>\n add(i, (i + 1)%n)\n }\n\n capitals foreach {i =>\n total -= beauty(i)\n ans += beauty(i) * total\n //debug(i, ans)\n }\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val C = (\"0 \" + readLine()).split(\" \").map(_.toLong)\n val Cap = (\"0 \" + readLine()).split(\" \").map(_.toInt)\n val IsCapital = Array.ofDim[Boolean](n + 1)\n Cap.foreach { i =>\n IsCapital(i) = true\n }\n\n var capTotal = Cap.map(i => C(i)).sum\n val CapSum = Array.ofDim[Long](k + 2)\n for (i <- 1 to k) {\n CapSum(i) = capTotal\n capTotal -= C(Cap(i))\n }\n\n val CitiesSum = C.sum - CapSum(1)\n\n var totalCapitals = 0L\n for (i <- 1 to k) {\n val capitalIdx = Cap(i)\n val capitalValue = C(capitalIdx)\n val next = if (capitalIdx + 1 <= n) capitalIdx + 1 else 1\n val prev = if (capitalIdx - 1 >= 1) capitalIdx - 1 else n\n totalCapitals += capitalValue * (CitiesSum + CapSum(i + 1) - C(next) - C(prev))\n }\n\n var border = 0L\n for (i <- 1 to n) {\n val j = if (i + 1 <= n) i + 1 else 1\n if (!IsCapital(i) || !IsCapital(j)) border += C(i) * C(j)\n }\n\n println(border + totalCapitals)\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val price = in.next().split(' ').map(_.toInt)\n val capitals = in.next().split(' ').map(_.toInt - 1).toSet\n val sum = capitals.toList.map(price).sum\n val nonCapitals = price.indices.filterNot(capitals.contains).map(price).sum\n val capitalsPriceSum = capitals.toList.map(i => price(i) * (sum - price(i))).sum / 2\n val capToUncap = capitals.map(i => price(i) * nonCapitals).sum\n val lineSum = (n - 1 :: price.indices.toList).sliding(2)\n .filterNot(i => capitals.contains(i.head) || capitals.contains(i.last))\n .map(i => price(i.head) * price(i.last)).sum\n println(capitalsPriceSum + lineSum + capToUncap)\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val price = in.next().split(' ').map(_.toInt)\n val capitals = in.next().split(' ').map(_.toInt - 1).toSet\n val sum = capitals.map(price).sum\n val nonCapitals = price.indices.filterNot(capitals.contains).map(price).sum\n val capitalsPriceSum = capitals.toList.map(i => price(i) * (sum - price(i))).sum / 2\n val capToUncap = capitals.map(i => price(i) * nonCapitals).sum\n val lineSum = (n - 1 :: price.indices.toList).sliding(2)\n .filterNot(i => capitals.contains(i.head) || capitals.contains(i.last))\n .map(i => price(i.head) * price(i.last)).sum\n println(capitalsPriceSum + lineSum + capToUncap)\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val price = in.next().split(' ').map(_.toInt)\n val capitals = in.next().split(' ').map(_.toInt - 1).toSet\n val sum = capitals.toList.map(price).sum\n val nonCapitals = price.indices.filterNot(capitals.contains).map(price).sum\n val capitalsPriceSum = capitals.toList.map(i => price(i) * (sum - price(i))).sum / 2\n val capToUncap = capitals.toList.map(i => price(i) * nonCapitals).sum\n val lineSum = (n - 1 :: price.indices.toList).sliding(2)\n .filterNot(i => capitals.contains(i.head) || capitals.contains(i.last))\n .map(i => price(i.head) * price(i.last)).sum\n println(capitalsPriceSum + lineSum + capToUncap)\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val C = (\"0 \" + readLine()).split(\" \").map(_.toLong)\n val Cap = (\"0 \" + readLine()).split(\" \").map(_.toInt)\n\n var capTotal = Cap.map(i => C(i)).sum\n val CapSum = Array.ofDim[Long](k + 2)\n for (i <- 1 to k) {\n CapSum(i) = capTotal\n capTotal -= C(Cap(i))\n }\n\n val CitiesSum = C.sum - CapSum(1)\n\n var totalCapitals = 0L\n for (i <- 1 to k) {\n val capitalIdx = Cap(i)\n val capitalValue = C(capitalIdx)\n val next = if (capitalIdx + 1 <= n) capitalIdx + 1 else 1\n val prev = if (capitalIdx - 1 >= 1) capitalIdx - 1 else n\n totalCapitals += capitalValue * (CitiesSum + CapSum(i + 1) - C(next) - C(prev))\n }\n\n var border = 0L\n for (i <- 1 to n) {\n val j = i + 1\n if (j <= n) border += C(i) * C(j)\n else border += C(i) * C(1)\n }\n\n println(border + totalCapitals)\n}\n"}], "src_uid": "bc6b8fda79c257e6c4e280d7929ed8a1"} {"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n val res = Array.ofDim[Int](n)\n\n var drenchUntil = n\n for (i <- as.indices.reverse) {\n val d = i - as(i)\n if (d < drenchUntil) drenchUntil = d\n if (i > drenchUntil) res(i) = 1\n }\n\n out.println(res.mkString(\" \"))\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "import scala.annotation.tailrec\r\nimport scala.io.StdIn.readLine\r\n\r\nobject MyNewClass extends App {\r\n val t = readLine.toInt\r\n for (_ <- 1 to t) {\r\n val n = readLine.toInt\r\n val as = readLine.split(' ').toList.map(x => x.toInt)\r\n\r\n println(layer(as.reverse, 0, List.empty).map(x => if (x) 1 else 0).reverse.mkString(\" \"))\r\n \r\n @tailrec\r\n def layer(as: List[Int], a0: Int, ds: List[Boolean]): List[Boolean] = as match {\r\n case x :: xs => {\r\n val x0 = Math.max(a0 - 1, x)\r\n val d = if (x0 > 0) true else false\r\n layer(xs, x0, d:: ds)\r\n }\r\n case _ => ds.reverse\r\n }\r\n }\r\n}"}, {"source_code": "import scala.io.StdIn.readLine\r\n\r\nobject MyNewClass extends App {\r\n val t = readLine.toInt\r\n for (_ <- 1 to t) {\r\n val n = readLine.toInt\r\n val as = readLine.split(' ').toArray.map(x => x.toInt)\r\n\r\n println(layer_iterate(as).map(x => if (x) 1 else 0).mkString(\" \"))\r\n\r\n def layer_iterate(as: Array[Int]): Array[Boolean] = {\r\n var arr: Array[Boolean] = Array.fill(as.length)(false)\r\n var a = as.last\r\n if (a > 0) {\r\n arr(as.length - 1) = true\r\n }\r\n for (i <- (as.length - 2 to 0 by -1)) {\r\n val a_i = as(i)\r\n a = Math.max(a - 1, a_i)\r\n if (a > 0) {\r\n arr(i) = true\r\n }\r\n }\r\n arr\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "807c5ec37b0ea83ef40550698f1ff498"} {"source_code": "\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_504_A { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.t2)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading\n val l1 = readLine\n val n = l1.int\n val m = l1.int\n val s = readLine.string\n val t = readLine.string\n \n val ind = s.indexOf(\"*\")\n var res = false\n if (ind == -1) {\n res = s==t \n } else {\n val start = s.substring(0,ind)\n val stop = s.substring(ind+1, s.length())\n res = t.startsWith(start) && t.drop(start.length()).endsWith(stop)\n }\n outLn( if (res) \"YES\" else \"NO\" )\n \n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n6 10\ncode*s\ncodeforces \n\"\"\"\n\nval sa2 = \"\"\"\n6 5\nvk*cup\nvkcup \n\"\"\"\n\nval sa3 = \"\"\"\n1 1\nv\nk\n\"\"\"\n\nval t1 = \"\"\"\n9 10\n*deforces\ncodeforces \n\"\"\"\n\nval t2 = \"\"\"\n9 10\ncodeforc*\ncodeforces \n\"\"\"\n}\n\n}\n\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M = ni()\n val s, t = ns()\n val ok = s.indexOf('*') match {\n case -1 =>\n s == t\n case ix =>\n val l = s.take(ix)\n val r = s.drop(ix + 1)\n N - 1 <= M && t.startsWith(l) && t.endsWith(r)\n }\n\n val ans = if (ok) \"YES\" else \"NO\"\n\n out.println(ans)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}], "negative_code": [{"source_code": "\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_504_A { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.t2)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading\n val l1 = readLine\n val n = l1.int\n val m = l1.int\n val s = readLine.string\n val t = readLine.string\n \n val ind = s.indexOf(\"*\")\n var res = false\n if (ind == -1) {\n res = s==t \n } else {\n val start = s.substring(0,ind)\n val stop = s.substring(ind+1, s.length())\n res = t.startsWith(start) && t.endsWith(stop)\n }\n outLn( if (res) \"YES\" else \"NO\" )\n \n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n6 10\ncode*s\ncodeforces \n\"\"\"\n\nval sa2 = \"\"\"\n6 5\nvk*cup\nvkcup \n\"\"\"\n\nval sa3 = \"\"\"\n1 1\nv\nk\n\"\"\"\n\nval t1 = \"\"\"\n9 10\n*deforces\ncodeforces \n\"\"\"\n\nval t2 = \"\"\"\n9 10\ncodeforc*\ncodeforces \n\"\"\"\n}\n\n}\n\n"}], "src_uid": "d629d09782a7af0acc359173ac4b4f0a"} {"source_code": "object A {\r\n import scala.io.{StdIn => in}\r\n\r\n def main(args: Array[String]): Unit = {\r\n val tests = in.readInt()\r\n (1 to tests).foreach { _ =>\r\n in.readInt()\r\n val levels = in.readLine().split(' ').map(_.toInt)\r\n val min = levels.fold(Int.MaxValue) { case (a, b) => Math.min(a, b) }\r\n println(levels.count(_ > min))\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\r\nimport scala.io.StdIn._\r\n \r\nobject A1487 {\r\n def main(args: Array[String]){\r\n val t = readInt()\r\n \r\n for(i <- 1 to t) {\r\n val n = readInt()\r\n var arr = readLine.split(\" \").map(_.toInt)\r\n val idx = arr.sorted.indexWhere(_ > arr.min)\r\n if (idx == -1) println(0)\r\n else println(arr.length - idx)\r\n }\r\n }\r\n}"}, {"source_code": "//package codeforces.contests._1487\n\nobject Arena {\n\n def main(args: Array[String]): Unit = {\n println({\n for (_ <- 1 to io.StdIn.readInt()) yield {\n val n = io.StdIn.readInt\n val arr = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val minE = arr.min\n val mineECount = arr.count(_ == minE)\n\n if(n == mineECount) 0 else n - mineECount\n }\n }.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n val min = as.min\n\n out.println(as.count(_ > min))\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "99e5c907b623c310d6f1599f485ca21d"} {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val Array(n, h) = lines.next().split(' ').map(_.toInt)\n val line = lines.next().split(' ').map(_.toInt)\n\n println(line.length + line.count(_ > h))\n}\n", "positive_code": [{"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\n\nobject HelloScala {\n def main(args: Array[String]): Unit = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n val line1 = br.readLine().split(\" \")\n val n = line1.head.toInt\n val h = line1.last.toInt\n val line2 = br.readLine().split(\" \")\n val heights = line2.map(_.toInt)\n val heightPartitions = heights.partition(_ > h)\n val output = heightPartitions._1.length*2+heightPartitions._2.length\n println(output)\n }\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\n\nobject HelloScala {\n def main(args: Array[String]): Unit = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n val line1 = br.readLine().split(\" \")\n val n = line1.head.toInt\n val h = line1.last.toInt\n val line2 = br.readLine().split(\" \")\n val heights = line2.map(_.toInt)\n val tallerCount = heights.count(_ > h)\n val output = tallerCount*2+n-tallerCount\n println(output)\n }\n}"}, {"source_code": "object Solution extends App {\n val Array (n, h) = readLine.split(\" \").map(_.toInt)\n val tab = readLine.split(\" \").map(_.toInt)\n\n val wyzsi = tab.sorted.dropWhile(_ <= h)\n \n println(tab.size + wyzsi.size)\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject VanyaAndFence extends App {\n\n val l1 = StdIn.readLine().split(\" \")\n val n = l1(0).toInt\n val h = l1(1).toInt\n\n val l2 = StdIn.readLine().split(\" \")\n val heights = l2.map(_.toInt)\n print(impl(heights, h))\n\n def impl(heights: Array[Int], max: Int): Int = {\n var width: Int = 0\n for (height <- heights) {\n if (height > max) {\n width += 2\n } else {\n width += 1\n }\n }\n width\n }\n}\n"}, {"source_code": "object A677 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, h) = readInts(2)\n val input = readInts(n)\n println(input.map(x => if(x > h) 2 else 1).sum)\n }\n}"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _677A extends CodeForcesApp {\n override def apply(io: IO) = {\n val n, h = io[Int]\n val heights = io[Vector, Int](n)\n io += heights.sumWith(i => if (i > h) 2 else 1)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def array[A]: Write[Array[A]] = Write(_ mkString \" \")\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n val Array(n, h) = readLine.split(\" \").map(_.toInt)\n val people = readLine.split(\" \").map(_.toInt)\n print(people.count(p => p <= h) + 2 * people.count(p => p > h))\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n val Array(_, h) = Console.readLine().split(\" \").map(_.toInt)\n println(Console.readLine().split(\" \").map(s => if(s.toInt > h) 2 else 1).sum)\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main2 extends App {\n val scanner = new Scanner(System.in)\n val personNumber = scanner.nextInt()\n val fenceHeight = scanner.nextInt()\n var personNumberNotGreaterThanFence: Int = 0\n for (_ <- 0 until personNumber) if (scanner.nextInt() <= fenceHeight) personNumberNotGreaterThanFence += 1\n println(personNumber * 2 - personNumberNotGreaterThanFence)\n}\n"}, {"source_code": "\nobject Solution extends App {\n val Array(n, h) = readLine.split(\" \").map(_.toInt)\n val hs = readLine.split(\" \").map(_.toInt)\n \n val higher = hs.sorted.dropWhile(_ <= h)\n \n println(hs.size + higher.size)\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject TaskA extends App {\n var n :: h :: Nil = readInts\n println(n + readInts.count(_ > h))\n\n def readInts = readLine.split(\" \").map(_.toInt).toList\n}\n"}], "negative_code": [], "src_uid": "e7ed5a733e51b6d5069769c3b1d8d22f"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val B = Array.ofDim[Int](N)\n val C = Array.ofDim[Int](N - 1)\n rep(N - 1) { i =>\n val d = A(i + 1) - A(i)\n C(i) = if (d == 0) 0\n else if (d > 0) 1\n else -1\n }\n\n val All = 1 to 5\n val Mid = Seq(3, 2, 4, 1, 5)\n\n def filter(i: Int) = {\n C(i) match {\n case 0 => All filterNot (_ == B(i))\n case 1 => B(i) + 1 to 5\n case -1 => 1 until B(i)\n }\n }\n\n def pick(i: Int, range: IndexedSeq[Int]) = {\n C(i) match {\n case 0 => Mid.find(range.contains).get\n case 1 => range.head\n case -1 => range.last\n }\n }\n\n def allocate(): Boolean = {\n B(0) = pick(0, All)\n\n rep(N - 2) { i =>\n val range = filter(i)\n if (range.isEmpty) return false\n B(i + 1) = pick(i + 1, range)\n }\n\n val rangeN = filter(N - 2)\n if (rangeN.isEmpty) return false\n B(N - 1) = rangeN.head\n\n true\n }\n\n if (N == 1) {\n out.println(1)\n } else {\n val ok = allocate()\n\n if (ok) {\n out.println(B.mkString(\" \"))\n } else {\n out.println(-1)\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n\n var min = 1\n var max = 5\n\n val dp = Array.fill(n, 5)(-1)\n for (j <- 0 until 5) dp(0)(j) = 0\n\n for (i <- 1 until n) {\n var prev = 0\n while (prev < 5) {\n if (dp(i - 1)(prev) >= 0) {\n var b = 0\n while (b < 5) {\n if (as(i - 1) < as(i) && prev < b) dp(i)(b) = prev\n if (as(i - 1) > as(i) && prev > b) dp(i)(b) = prev\n if (as(i - 1) == as(i) && prev != b) dp(i)(b) = prev\n b += 1\n }\n }\n prev += 1\n }\n }\n//dp.foreach(d => println(d.mkString(\" \")))\n val solved = dp.last.indexWhere(_ >= 0)\n if (solved == -1) {\n println(-1)\n } else {\n\n val bs = Array.ofDim[Int](n)\n var b = solved\n for (i <- n - 1 to 0 by -1) {\n bs(i) = b + 1\n b = dp(i)(b)\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(bs.mkString(\" \"))\n\n Console.flush\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val B = Array.ofDim[Int](N)\n val C = Array.ofDim[Int](N - 1)\n rep(N - 1) { i =>\n val d = A(i + 1) - A(i)\n C(i) = if (d == 0) 0\n else if (d > 0) 1\n else -1\n }\n\n if (N == 1) {\n out.println(1)\n } else {\n B(0) = C(0) match {\n case 0 => 2\n case 1 => 1\n case -1 => 5\n }\n\n rep(N - 2) { i =>\n val c0 = C(i)\n val c1 = C(i + 1)\n val b = (c0, c1) match {\n case (0, 0) => if (B(i) != 2) 2 else 3\n case (0, 1) => if (B(i) != 1) 1 else 2\n case (0, -1) => if (B(i) != 5) 5 else 4\n\n case (1, 0) => if (B(i) != 2) 2 else 3\n case (1, 1) => B(i) + 1\n case (1, -1) => 5\n\n case (-1, 0) => if (B(i) != 2) 2 else 3\n case (-1, 1) => 1\n case (-1, -1) => B(i) - 1\n }\n B(i + 1) = b\n }\n\n B(N - 1) = C(N - 2) match {\n case 0 => if (B(N - 2) != 2) 2 else 3\n case 1 => B(N - 2) + 1\n case -1 => B(N - 2) - 1\n }\n\n val ok = (0 until N - 2 forall { i =>\n C(i) match {\n case 0 => B(i) != B(i + 1)\n case 1 => B(i) < B(i + 1)\n case -1 => B(i) > B(i + 1)\n }\n }) && B.forall(b => 1 <= b && b <= 5)\n\n if (ok) {\n out.println(B.mkString(\" \"))\n } else {\n out.println(-1)\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val B = Array.ofDim[Int](N)\n val C = Array.ofDim[Int](N - 1)\n rep(N - 1) { i =>\n val d = A(i + 1) - A(i)\n C(i) = if (d == 0) 0\n else if (d > 0) 1\n else -1\n }\n\n val All = 1 to 5\n\n def filter(i: Int) = {\n C(i) match {\n case 0 => All filterNot (_ == B(i))\n case 1 => B(i) + 1 to 5\n case -1 => 1 until B(i)\n }\n }\n\n def pick(i: Int, range: IndexedSeq[Int]) = {\n C(i) match {\n case 0 => range(range.length / 2)\n case 1 => range.head\n case -1 => range.last\n }\n }\n\n def allocate(): Boolean = {\n B(0) = pick(0, All)\n\n rep(N - 2) { i =>\n val range = filter(i)\n if (range.isEmpty) return false\n B(i + 1) = pick(i + 1, range)\n }\n\n val rangeN = filter(N - 2)\n if (rangeN.isEmpty) return false\n B(N - 1) = rangeN.head\n\n true\n }\n\n if (N == 1) {\n out.println(1)\n } else {\n val ok = allocate()\n\n if (ok) {\n out.println(B.mkString(\" \"))\n } else {\n out.println(-1)\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val B = Array.ofDim[Int](N)\n val C = Array.ofDim[Int](N - 1)\n rep(N - 1) { i =>\n val d = A(i + 1) - A(i)\n C(i) = if (d == 0) 0\n else if (d > 0) 1\n else -1\n }\n\n if (N == 1) {\n out.println(1)\n } else {\n B(0) = C(0) match {\n case 0 => 2\n case 1 => 1\n case -1 => 5\n }\n\n rep(N - 2) { i =>\n val c0 = C(i)\n val c1 = C(i + 1)\n val b = (c0, c1) match {\n case (0, 0) => if (B(i) != 2) 2 else 3\n case (0, 1) => if (B(i) != 1) 1 else 2\n case (0, -1) => if (B(i) != 5) 5 else 4\n\n case (1, 0) => if (B(i) != 2) 2 else 3\n case (1, 1) => B(i) + 1\n case (1, -1) => 5\n\n case (-1, 0) => if (B(i) != 2) 2 else 3\n case (-1, 1) => 1\n case (-1, -1) => B(i) - 1\n }\n B(i + 1) = b\n }\n\n B(N - 1) = C(N - 2) match {\n case 0 => if (B(N - 2) != 2) 2 else 3\n case 1 => B(N - 2) + 1\n case -1 => B(N - 2) - 1\n }\n\n val ok = (0 until N - 1 forall { i =>\n C(i) match {\n case 0 => B(i) != B(i + 1)\n case 1 => B(i) < B(i + 1)\n case -1 => B(i) > B(i + 1)\n }\n }) && B.forall(b => 1 <= b && b <= 5)\n\n if (ok) {\n out.println(B.mkString(\" \"))\n } else {\n out.println(-1)\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "c63b62ad5b8d0b274599b60442766e17"} {"source_code": "object DistanceAxis {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn._\n val input = readInt()\n var i = 0\n while(i < input) {\n var rline = readLine().split(\" \")\n var a0 = rline(0).toInt\n var a1 = rline(1).toInt\n var a2 = rline(2).toInt\n rline = readLine().split(\" \")\n var b0 = rline(0).toInt\n var b1 = rline(1).toInt\n var b2 = rline(2).toInt\n val usedMaxa2b1 = math.min(a2, b1)\n val result = 2 * usedMaxa2b1 - 2 * math.max(0, (a1 - (b0 + b1 - usedMaxa2b1)))\n println(result)\n i += 1\n }\n }\n}\n", "positive_code": [{"source_code": "\n\nimport scala.io.StdIn\n\nobject Solution2 extends App {\n\n\n val t = StdIn.readLine().toInt\n\n val cases = for {\n _ <- 0 until t\n } yield (StdIn.readLine().split(\" \").map(_.toInt), StdIn.readLine().split(\" \").map(_.toInt))\n\n for {\n c <- cases\n } {\n var (Array(z1, y1, x1), Array(z2, y2, x2)) = c\n\n var sum = 0\n val twosWithOnes = Math.min(x1, y2)\n sum += twosWithOnes * 2\n x1 -= twosWithOnes\n y2 -= twosWithOnes\n \n val twosWithTwos = Math.min(x1, x2)\n x1 -= twosWithTwos\n x2 -= twosWithTwos\n // println(\"burn twos\", sum, \"a=\", x1, y2, z1, \" b= \", x2, y2, z2)\n\n // burn twos in second\n val zeros = Math.min(z1, x2)\n x2 -= zeros\n z1 -= zeros\n\n // println(\"burn zeros\", sum, \"a=\", x1, y2, z1, \" b= \", x2, y2, z2)\n\n val OnesWithTwos = Math.min(y1, x2)\n y1 -= OnesWithTwos\n x2 -= OnesWithTwos\n sum -= OnesWithTwos * 2\n\n //println(\"burn other twos\", sum, \"a=\", x1, y2, z1, \" b= \", x2, y2, z2)\n //println(\"final\", sum, \"a=\", x1, y2, z1, \" b= \", x2, y2, z2)\n println(sum)\n }\n\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(x1, y1, z1) = readLine().split(\" \").map(_.toInt) // a: 0, 1, 2\n val Array(x2, y2, z2) = readLine().split(\" \").map(_.toInt) // b: 0, 1, 2\n\n val t1 = z1 min y2\n val t2 = z2 min x1\n val t3 = (z1 - t1) min (z2 - t2)\n val t4 = y1 min (z2 - t2 - t3)\n\n val ans = 2L * (t1 - t4)\n\n println(ans)\n }\n}\n"}, {"source_code": "\nobject B extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n var a0 = in.nextInt()\n var a1 = in.nextInt()\n var a2 = in.nextInt()\n\n var b0 = in.nextInt()\n var b1 = in.nextInt()\n var b2 = in.nextInt()\n\n var tem = 0\n // a2\n var result = {\n tem = math.min(a2, b1)\n a2 = a2 - tem\n b1 = b1 - tem\n tem * 2\n }\n {\n tem = math.min(a2, b2) // zero\n a2 = a2 - tem\n b2 = b2 - tem\n }\n {\n tem = math.min(a2, b0) // zero\n a2 = a2 - tem\n b0 = b0 - tem\n }\n // a1\n {\n tem = math.min(a1, b1) // zero\n a1 = a1 - tem\n b1 = b1 - tem\n }\n {\n tem = math.min(a1, b0) // zero\n a1 = a1 - tem\n b0 = b0 - tem\n }\n result = result + {\n tem = math.min(a1, b2) // zero\n a1 = a1 - tem\n b2 = b2 - tem\n tem * 2 * -1\n }\n // a0\n {\n tem = math.min(a0, b2) // zero\n a0 = a0 - tem\n b2 = b2 - tem\n }\n {\n tem = math.min(a0, b1) // zero\n a0 = a0 - tem\n b1 = b1 - tem\n }\n {\n tem = math.min(a0, b0) // zero\n a0 = a0 - tem\n b0 = b0 - tem\n }\n println(result)\n// val connectivity = Array.ofDim[Boolean](airports, airports)\n\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}], "negative_code": [{"source_code": "\n\nimport scala.io.StdIn\n\nobject Solution2 extends App {\n\n\n val t = StdIn.readLine().toInt\n\n val cases = for {\n _ <- 0 until t\n } yield (StdIn.readLine().split(\" \").map(_.toInt), StdIn.readLine().split(\" \").map(_.toInt))\n\n for {\n c <- cases\n } {\n var (Array(z1, y1, x1), Array(z2, y2, x2)) = c\n\n var sum = 0\n val twosWithOnes = Math.min(x1, y2)\n sum += twosWithOnes * 2\n x1 -= twosWithOnes\n y2 -= twosWithOnes\n // println(\"burn twos\", sum, \"a=\", x1, y2, z1, \" b= \", x2, y2, z2)\n\n // burn twos in second\n val zeros = Math.min(z1, x2)\n x2 -= zeros\n z1 -= zeros\n\n // println(\"burn zeros\", sum, \"a=\", x1, y2, z1, \" b= \", x2, y2, z2)\n\n val OnesWithTwos = Math.min(y1, x2)\n y1 -= OnesWithTwos\n x2 -= OnesWithTwos\n sum -= OnesWithTwos * 2\n\n //println(\"burn other twos\", sum, \"a=\", x1, y2, z1, \" b= \", x2, y2, z2)\n //println(\"final\", sum, \"a=\", x1, y2, z1, \" b= \", x2, y2, z2)\n println(sum)\n }\n\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(x1, y1, z1) = readLine().split(\" \").map(_.toInt) // a: 0, 1, 2\n val Array(x2, y2, z2) = readLine().split(\" \").map(_.toInt) // b: 0, 1, 2\n\n val ans = 2L * ((z1 min y2) - ((z2 - (z2 min x1)) min y1))\n\n println(ans)\n }\n}\n"}], "src_uid": "e1de1e92fac8a6db3222c0d3c26843d8"} {"source_code": "import scala.io.StdIn._\r\nobject Main extends App {\r\n var a = readInt\r\n for(k<-1 to a){\r\n val n = readInt\r\n for(i<-2 to n+1){\r\n print(i+\" \")\r\n }\r\n print(\"\\n\")\r\n }\r\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(val a: Int, val b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return -1 * a.compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 998244353L\n val maxn = 200010\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n\n\n for (tt <- 1 to t) {\n val n = readInt()\n for (i <- 1 to n) {\n writer.print(i+1 + \" \")\n }\n writer.println()\n\n\n def check(kk: Long): Boolean = {\n return false\n }\n def bs(st:Long, en:Long): Long = {\n if (en - st <= 1L) {\n if (check(st))\n return st\n else\n return en\n }\n val mid = (st + en) / 2L\n if (check(mid))\n return bs(st, mid)\n else\n return bs(mid, en)\n }\n }\n writer.flush()\n}"}], "negative_code": [], "src_uid": "76bfced1345f871832957a65e2a660f8"} {"source_code": "import java.util.Scanner\n\nobject B {\n\n\tvar n:Int = _\n\tvar m:Int = _\n\tvar q:Int = _\n\tvar b:Array[Array[Int]] = _\n\tvar cnt:Array[Int] = _\n\n\tdef read() = {\n\t\tn = in.nextInt\n\t\tm = in.nextInt\n\t\tq = in.nextInt\n\t\tin.nextLine\n\n\t\tb = (0 until n)\n\t\t\t.map(i => in.nextLine().split(\" \").map(c => c.toInt))\n\t\t\t.toArray\n\t}\n\n\tdef calcCnt(i:Int):Int = b(i)\n\t\t.scanLeft(0)((c:Int, v:Int) => (c + 1) * v)\n\t\t.reduceLeft(math.max)\n\n\tdef prepareBeforeRounds() = {\n\t\tcnt = (0 until n).map(calcCnt(_)).toArray\n\t}\n\n\tdef solveRound() = {\n\t\tval i = in.nextInt() - 1\n\t\tval j = in.nextInt() - 1\n\n\t\tb(i)(j) = 1 - b(i)(j)\n\t\tcnt(i) = calcCnt(i)\n\n\t\tprintln(cnt.reduceLeft(math.max))\n\t}\n\n\tval in:Scanner = new Scanner(System.in)\n\n\tdef main(args: Array[String]) = {\n\t\tread()\n\n\t\tprepareBeforeRounds()\n\n\t\tfor (i <- 1 to q) {\n\t\t\tsolveRound()\n\t\t}\n\t}\n\n}", "positive_code": [{"source_code": "\nimport scala.math._\nimport scala.collection.mutable\nimport scala.util.control.Breaks\nimport scala.annotation.tailrec\n\nobject Problem extends App {\n import FastScanner._\n def exit() = System.exit(0)\n \n val n, m, q = readInt\n val grid = Array.fill(n, m)(readChar == '1')\n \n def longest(i: Int) = {\n var len, max = 0\n for(j <- 0 until m) {\n if(grid(i)(j)) {\n len += 1\n if(len > max)\n max = len\n } else\n len = 0\n }\n max\n }\n \n val totals = (0 until n toArray) map longest\n val totalsOps = intArrayOps(totals)\n \n for(cur <- 0 until q) {\n val i, j = readInt-1\n grid(i)(j) = !grid(i)(j)\n totals(i) = longest(i)\n \n val max = totalsOps.max\n println(max)\n }\n}\n\nobject FastScanner {\n import java.io._\n private[this] val reader = new BufferedReader(new InputStreamReader(System.in))\n private[this] var line: String = null\n private[this] var pos: Int = 0\n \n @inline private[this] def nextLine() = {\n val line = reader.readLine()\n if(line == null)\n throw new IOException(\"End of stream\")\n line\n }\n \n def readLine() = {\n if(line != null) {\n val s = line\n line = null\n s.substring(pos)\n } else\n nextLine()\n }\n \n def read() = {\n if(line == null) {\n line = nextLine()\n pos = 0\n }\n while(pos >= line.length) {\n line = nextLine()\n pos = 0\n }\n while(Character.isWhitespace(line charAt pos)) {\n pos += 1\n while(pos >= line.length) {\n line = nextLine()\n pos = 0\n }\n }\n var end = pos\n while(end < line.length && !Character.isWhitespace(line charAt end))\n end += 1\n \n val s = line.substring(pos, end)\n pos = end\n s\n }\n \n def readChar() = read() charAt 0\n def readInt() = java.lang.Integer.parseInt(read())\n def readLong() = java.lang.Long.parseLong(read())\n def readDouble() = java.lang.Double.parseDouble(read())\n}\n\n\n"}, {"source_code": "import java.io.BufferedReader\n\nobject Problem548B {\n def main(args: Array[String]): Unit = {\n val params = readParamsFromInput(Console.in)\n\n val solution = solve(params)\n\n solution.foreach(println(_))\n }\n\n def solve(params: Params548B): Seq[Int] = {\n // keep the row nrs containing the old max, and the old max\n // If the change is to one of those rows, either kick a row out (it shrunk) -> check if list is empty, if so, calc a new list.\n // or promote a row to the new list of max rows\n // If the change is to an outsider, either do nothing (it shrunk)\n // or if its total equals the max, add it to the max list.\n\n var (maxRowNrs, max) = getMaxes(params.bears)\n\n params.changes.map(change => {\n val oldState = params.bears(change._1)(change._2)\n params.bears(change._1)(change._2) = oldState ^ 1\n\n if (oldState == 1) {\n // row shrunk\n if (maxRowNrs.contains(change._1)) maxRowNrs -= change._1\n if (maxRowNrs.isEmpty) {\n val (newMaxRowNrs, newMax) = getMaxes(params.bears)\n maxRowNrs = newMaxRowNrs\n max = newMax\n }\n } else {\n // row grew. Can be by more than 1.\n val newRowVal = maxConsecutive(params.bears(change._1))\n if (newRowVal == max) {\n maxRowNrs += change._1\n } else\n if(newRowVal > max) {\n maxRowNrs = Set(change._1)\n max = newRowVal\n }\n }\n max\n })\n }\n\n def getMaxes(bears: Array[Array[Int]]): (Set[Int], Int) = {\n var max = 0\n var maxRows = Set[Int]()\n bears.map(maxConsecutive).zipWithIndex.foreach(p => {\n val (m, i) = p\n if (m > max) {\n maxRows = Set(i)\n max = m\n } else\n if (m == max) {\n maxRows += i\n }\n })\n (maxRows, max)\n }\n\n def maxConsecutive(bears: Array[Int]): Int = {\n var current = 0\n var max = 0\n bears.foreach(b => {\n if (b==1) current += 1\n else current = 0\n if (current > max) max = current\n })\n max\n }\n\n def readParamsFromInput(in: BufferedReader): Params548B = {\n val Array(nrRows, nrCols, nrChanges) = in.readLine().split(\" \").map(_.toInt)\n val bears = new Array[Array[Int]](nrRows)\n (0 until nrRows).foreach(i => {\n bears(i) = in.readLine().split(\" \").map(_.toInt)\n })\n val changes = new Array[(Int, Int)](nrChanges)\n (0 until nrChanges).foreach(i => {\n val change = in.readLine().split(\" \").map(_.toInt - 1) // NOTE 1-based\n changes(i) = (change(0), change(1))\n })\n Params548B(nrRows, nrCols, nrChanges, bears, changes)\n }\n\n case class Params548B(nrRows: Int, nrCols: Int, nrChanges: Int, bears: Array[Array[Int]], changes: Array[(Int, Int)])\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject B {\n\n\tvar n:Int = 0\n\tvar m:Int = 0\n\tvar q:Int = 0\n\tvar b = Array[Array[Int]]()\n\tvar cnt = Array[Int]()\n\n\tdef read() = {\n\t\tn = in.nextInt\n\t\tm = in.nextInt\n\t\tq = in.nextInt\n\t\tin.nextLine\n\n\t\tb = (0 until n)\n\t\t\t.map(i => in.nextLine().split(\" \").map(c => c.toInt))\n\t\t\t.toArray\n\t}\n\n\tdef calcCnt(i:Int):Int = {\n\t\tvar res = 0\n\t\tvar currCnt = 0\n\n\t\tfor (c <- b(i)) {\n\t\t\tif (c == 1) {\n\t\t\t\tcurrCnt += 1\n\t\t\t\tres = math.max(res, currCnt)\n\t\t\t} else {\n\t\t\t\tcurrCnt = 0\n\t\t\t}\n\t\t}\n\n\t\treturn res\n\t}\n\n\tdef prepareBeforeRounds() = {\n\t\tcnt = (0 until n).map(calcCnt(_)).toArray\n\t}\n\n\tdef maxCnt():Int = {\n\t\treturn cnt.reduceLeft(math.max);\n\t}\n\n\tdef solveRound() = {\n\t\tval i = in.nextInt() - 1\n\t\tval j = in.nextInt() - 1\n\n\t\tb(i)(j) = 1 - b(i)(j)\n\t\tcnt(i) = calcCnt(i)\n\n\t\tprintln(maxCnt())\n\t}\n\n\tval in:Scanner = new Scanner(System.in)\n\n\tdef main(args: Array[String]) = {\n\t\tread()\n\n\t\tprepareBeforeRounds()\n\n\t\tfor (i <- 1 to q) {\n\t\t\tsolveRound()\n\t\t}\n\t}\n\n}"}, {"source_code": "import java.io._\nimport java.util\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val q = nextInt\n val bits = new Array[util.BitSet](n)\n val ans = new Array[Int](n)\n for (i <- 0 until n) {\n bits(i) = new util.BitSet(m)\n for (j <- 0 until m) {\n nextInt match {\n case 1 => bits(i).set(j)\n case _ => bits(i).set(j, false)\n }\n }\n ans(i) = maxNumberOfConsecutiveBits(bits(i))\n }\n for (i <- 0 until q) {\n var res = 0\n val x = nextInt\n val y = nextInt\n bits(x - 1).flip(y - 1)\n ans(x - 1) = maxNumberOfConsecutiveBits(bits(x - 1))\n for (k <- 0 until n) {\n res = Math.max(res, ans(k))\n }\n out.println(res)\n }\n return 0\n }\n\n def maxNumberOfConsecutiveBits(bs: util.BitSet): Int = {\n var maxLength = 0\n var one = bs.length()\n var i = one\n while (i >= 0) {\n i = bs.previousClearBit(i - 1)\n val len = one - 1 - i\n maxLength = Math.max(maxLength, len)\n if (i < 0) {\n return maxLength\n }\n one = i\n i = bs.previousClearBit(i - 1) + 1\n }\n maxLength\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n var input = readLine().split(\" \").map(_.toInt)\n val n = input(0)\n val m = input(1)\n val q = input(2)\n\n val M = new Array[Int](n)\n val grid = Array.ofDim[Array[Boolean]](n)\n\n for (i <- 0 until n) {\n grid(i) = readLine().split(\" \").map(_.toInt == 1)\n M(i) = max(i)\n }\n\n for (i <- 0 until q) {\n var input = readLine().split(\" \").map(_.toInt)\n val i = input(0) - 1\n val j = input(1) - 1\n grid(i)(j) = !grid(i)(j)\n M(i) = max(i)\n println(M.max)\n }\n\n def max(row: Int): Int = {\n var ans = 0\n var curr = 0\n for (i <- 0 until m) {\n if (grid(row)(i)) curr += 1 else curr = 0\n ans = Math.max(ans, curr)\n }\n ans\n }\n}"}], "negative_code": [{"source_code": "import java.io.BufferedReader\n\nobject Problem548B {\n def main(args: Array[String]): Unit = {\n val params = readParamsFromInput(Console.in)\n\n val solution = solve(params)\n\n solution.foreach(println(_))\n }\n\n def solve(params: Params548B): Seq[Int] = {\n // keep the row nrs containing the old max, and the old max\n // If the change is to one of those rows, either kick a row out (it shrunk) -> check if list is empty, if so, calc a new list.\n // or promote a row to the new list of max rows\n // If the change is to an outsider, either do nothing (it shrunk)\n // or if its total equals the max, add it to the max list.\n\n var (maxRowNrs, max) = getMaxes(params.bears)\n\n params.changes.map(change => {\n val oldState = params.bears(change._1)(change._2)\n params.bears(change._1)(change._2) = oldState ^ 1\n\n if (oldState == 1) {\n // row shrunk\n if (maxRowNrs.contains(change._1)) maxRowNrs -= change._1\n if (maxRowNrs.isEmpty) {\n val (newMaxRowNrs, newMax) = getMaxes(params.bears)\n maxRowNrs = newMaxRowNrs\n max = newMax\n }\n } else {\n // row grew\n if (maxRowNrs.contains(change._1)) {\n maxRowNrs = Set(change._1)\n max += 1\n } else {\n if (maxConsecutive(params.bears(change._1)) == max) maxRowNrs += change._1\n }\n }\n max\n })\n }\n\n def getMaxes(bears: Array[Array[Int]]): (Set[Int], Int) = {\n var max = 0\n var maxRows = Set[Int]()\n bears.map(maxConsecutive).zipWithIndex.foreach(p => {\n val (m, i) = p\n if (m > max) {\n maxRows = Set(i)\n max = m\n } else\n if (m == max) {\n maxRows += i\n }\n })\n (maxRows, max)\n }\n\n def maxConsecutive(bears: Array[Int]): Int = {\n var current = 0\n var max = 0\n bears.foreach(b => {\n if (b==1) current += 1\n else current = 0\n if (current > max) max = current\n })\n max\n }\n\n def readParamsFromInput(in: BufferedReader): Params548B = {\n val Array(nrRows, nrCols, nrChanges) = in.readLine().split(\" \").map(_.toInt)\n val bears = new Array[Array[Int]](nrRows)\n (0 until nrRows).foreach(i => {\n bears(i) = in.readLine().split(\" \").map(_.toInt)\n })\n val changes = new Array[(Int, Int)](nrChanges)\n (0 until nrChanges).foreach(i => {\n val change = in.readLine().split(\" \").map(_.toInt - 1) // NOTE 1-based\n changes(i) = (change(0), change(1))\n })\n Params548B(nrRows, nrCols, nrChanges, bears, changes)\n }\n\n case class Params548B(nrRows: Int, nrCols: Int, nrChanges: Int, bears: Array[Array[Int]], changes: Array[(Int, Int)])\n}\n"}, {"source_code": "import java.io.BufferedReader\n\nobject Problem548B {\n def main(args: Array[String]): Unit = {\n val params = readParamsFromInput(Console.in)\n\n val solution = solve(params)\n\n solution.foreach(println(_))\n }\n\n def solve(params: Params548B): Seq[Int] = params.changes.map(change => {\n val oldState = params.bears(change._1)(change._2)\n params.bears(change._1)(change._2) = oldState ^ 1\n getMax(params.bears)\n })\n\n def getMax(bears: Array[Array[Int]]): Int = bears.map(_.sum).foldLeft(-1)((z, s) => Math.max(z, s))\n\n def readParamsFromInput(in: BufferedReader): Params548B = {\n val Array(nrRows, nrCols, nrChanges) = in.readLine().split(\" \").map(_.toInt)\n val bears = new Array[Array[Int]](nrRows)\n (0 until nrRows).foreach(i => {\n bears(i) = in.readLine().split(\" \").map(_.toInt)\n })\n val changes = new Array[(Int, Int)](nrChanges)\n (0 until nrChanges).foreach(i => {\n val change = in.readLine().split(\" \").map(_.toInt - 1) // NOTE 1-based\n changes(i) = (change(0), change(1))\n })\n Params548B(nrRows, nrCols, nrChanges, bears, changes)\n }\n\n case class Params548B(nrRows: Int, nrCols: Int, nrChanges: Int, bears: Array[Array[Int]], changes: Array[(Int, Int)])\n}\n"}, {"source_code": "import java.io.BufferedReader\n\nobject Problem548B {\n def main(args: Array[String]): Unit = {\n val params = readParamsFromInput(Console.in)\n\n val solution = solve(params)\n\n solution.foreach(println(_))\n }\n\n def solve(params: Params548B): Seq[Int] = {\n // keep the row nrs containing the old max, and the old max\n // If the change is to one of those rows, either kick a row out (it shrunk) -> check if list is empty, if so, calc a new list.\n // or promote a row to the new list of max rows\n // If the change is to an outsider, either do nothing (it shrunk)\n // or if its total equals the max, add it to the max list.\n\n var (maxRowNrs, max) = getMaxes(params.bears)\n\n params.changes.map(change => {\n val oldState = params.bears(change._1)(change._2)\n params.bears(change._1)(change._2) = oldState ^ 1\n\n if (oldState == 1) {\n // row shrunk\n if (maxRowNrs.contains(change._1)) maxRowNrs -= change._1\n if (maxRowNrs.isEmpty) {\n val (newMaxRowNrs, newMax) = getMaxes(params.bears)\n maxRowNrs = newMaxRowNrs\n max = newMax\n }\n } else {\n // row grew\n if (maxRowNrs.contains(change._1)) {\n maxRowNrs = Set(change._1)\n maxRowNrs += 1\n } else {\n if (maxConsecutive(params.bears(change._1)) == max) maxRowNrs += change._1\n }\n }\n max\n })\n }\n\n def getMaxes(bears: Array[Array[Int]]): (Set[Int], Int) = {\n var max = 0\n var maxRows = Set[Int]()\n bears.map(maxConsecutive).zipWithIndex.foreach(p => {\n val (m, i) = p\n if (m > max) {\n maxRows = Set(i)\n max = m\n } else\n if (m == max) {\n maxRows += i\n }\n })\n (maxRows, max)\n }\n\n //def getMax(bears: Array[Array[Int]]): Int = bears.map(maxConsecutive).foldLeft(-1)((z, s) => Math.max(z, s))\n\n def maxConsecutive(bears: Array[Int]): Int = {\n var current = 0\n var max = 0\n bears.foreach(b => {\n if (b==1) current += 1\n else current = 0\n if (current > max) max = current\n })\n max\n }\n\n def readParamsFromInput(in: BufferedReader): Params548B = {\n val Array(nrRows, nrCols, nrChanges) = in.readLine().split(\" \").map(_.toInt)\n val bears = new Array[Array[Int]](nrRows)\n (0 until nrRows).foreach(i => {\n bears(i) = in.readLine().split(\" \").map(_.toInt)\n })\n val changes = new Array[(Int, Int)](nrChanges)\n (0 until nrChanges).foreach(i => {\n val change = in.readLine().split(\" \").map(_.toInt - 1) // NOTE 1-based\n changes(i) = (change(0), change(1))\n })\n Params548B(nrRows, nrCols, nrChanges, bears, changes)\n }\n\n case class Params548B(nrRows: Int, nrCols: Int, nrChanges: Int, bears: Array[Array[Int]], changes: Array[(Int, Int)])\n}\n"}, {"source_code": "import java.io._\nimport java.util\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def bruteForceSoultion(sets: Array[util.BitSet]): Int = {\n var res = 0\n for (i <- 0 until sets.length) {\n val b = sets(i)\n var ind = 0\n var max = 0\n while (ind < b.length) {\n if (b.get(ind)) {\n max += 1\n } else {\n max = 0\n }\n ind += 1\n }\n res = Math.max(max, res)\n }\n res\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val q = nextInt\n val bits = new Array[util.BitSet](n)\n for (i <- 0 until n) {\n bits(i) = new util.BitSet(m)\n for (j <- 0 until m) {\n nextInt match {\n case 1 => bits(i).set(j)\n case _ => bits(i).set(j, false)\n }\n }\n }\n for (i <- 0 until q) {\n var res = 0\n val x = nextInt\n val y = nextInt\n bits(x - 1).flip(y - 1)\n// for (k <- 0 until n) {\n// res = Math.max(res, maxNumberOfConsecutiveBits(bits(k)))\n// }\n out.println(bruteForceSoultion(bits))\n }\n return 0\n }\n\n def maxNumberOfConsecutiveBits(bs: util.BitSet): Int = {\n var maxLength = 0\n var one = bs.length()\n var i = one\n while (i >= 0) {\n i = bs.previousClearBit(i - 1)\n val len = one - 1 - i\n maxLength = Math.max(maxLength, len)\n if (i < 0) {\n return maxLength\n }\n i = bs.previousClearBit(i - 1) + 1\n one = i\n }\n maxLength\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val q = nextInt\n val bits = new Array[java.util.BitSet](n)\n for (i <- 0 until n) {\n bits(i) = new java.util.BitSet(m)\n for (j <- 0 until m) {\n nextInt match {\n case 1 => bits(i).set(j)\n case _ => bits(i).set(j, false)\n }\n }\n }\n for (i <- 0 until q) {\n var res = 0\n val x = nextInt\n val y = nextInt\n bits(x - 1).flip(y - 1)\n for (k <- 0 until n) {\n res = Math.max(res, maxNumberOfConsecutiveBits(bits(k)))\n }\n out.println(res)\n }\n return 0\n }\n\n def maxNumberOfConsecutiveBits(bs: java.util.BitSet): Int = {\n var maxLength = 0\n var one = bs.length() // Points to the prior 0.\n var i = one\n while (i >= 0) {\n i = bs.previousClearBit(i - 1)\n val len = one - 1 - i\n maxLength = Math.max(maxLength, len)\n if (i < 0) {\n return maxLength\n }\n i = bs.previousClearBit(i - 1) + 1\n one = i\n }\n maxLength\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n var input = readLine().split(\" \").map(_.toInt)\n val n = input(0)\n val m = input(1)\n val q = input(2)\n\n val M = new Array[Int](n)\n val grid = Array.ofDim[Array[Boolean]](n)\n\n for (i <- 0 until n) {\n grid(i) = readLine().split(\" \").map(_.toInt == 1)\n M(i) = grid(i).count(_ == true)\n }\n\n for (i <- 0 until q) {\n var input = readLine().split(\" \").map(_.toInt)\n val i = input(0) - 1\n val j = input(1) - 1\n grid(i)(j) = !grid(i)(j)\n if (grid(i)(j)) M(i) += 1 else M(i) -= 1\n println(max())\n }\n\n def max(): Int = {\n var max = 0\n\n for (i <- 0 until n) {\n max = Math.max(max, M(i))\n }\n max\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n var input = readLine().split(\" \").map(_.toInt)\n val n = input(0)\n val m = input(1)\n val q = input(2)\n\n val grid = Array.ofDim[Array[Boolean]](n)\n\n for (i <- 0 until n) {\n grid(i) = readLine().split(\" \").map(_.toInt == 1)\n }\n\n for (i <- 0 until q) {\n var input = readLine().split(\" \").map(_.toInt)\n val i = input(0) - 1\n val j = input(1) - 1\n grid(i)(j) = !grid(i)(j)\n println(max())\n }\n\n def max(): Int = {\n var max = 0\n\n for (i <- 0 until n) {\n var curr = 0\n for (j <- 0 until m) {\n if (grid(i)(j)) curr += 1\n }\n max = Math.max(max, curr)\n }\n max\n }\n}\n"}], "src_uid": "337b6d2a11a25ef917809e6409f8edef"} {"source_code": "object _1203A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO) = {\n val inputs = io.read[Seq[Seq[Int]]]\n inputs foreach {input =>\n val doubled = (input ++ input)\n val slice = 1 to input.length\n val isPossible = Iterator(slice, slice.reverse).exists(doubled.containsSlice)\n io.writeLine(if (isPossible) \"YES\" else \"NO\")\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): Any\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out))\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object CF565A extends App {\n\n import scala.io.StdIn\n\n val q = StdIn.readInt\n for (_ <- 0 until q) {\n var n = StdIn.readInt\n\n val input = StdIn.readLine.split(' ').map(_.toInt)\n val sliding = (input.last :: input.toList).sliding(2)\n\n val answer = sliding.forall(x => x(1) == (x(0) + 1 - 1 + n) % n + 1) ||\n sliding.forall(x => x(1) == (x(0) - 1 - 1 + n) % n + 1)\n\n println(if (answer) \"YES\" else \"NO\")\n }\n}\n"}], "negative_code": [], "src_uid": "b27436086ead93397be748d8ebdbf19a"} {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) {\n val s = StdIn.readLine()\n val n = s.length\n val rs = s.reverse\n val t = StdIn.readLine()\n val m = t.length\n var p = 0\n val ans = ArrayBuffer[(Int, Int)]()\n while (p < m) {\n val kmp = new KMP[Char](t.substring(p))\n val (l1, r1) = kmp.longestPrefix(s)\n val (l2, r2) = kmp.longestPrefix(rs)\n val (l3, r3) = (n - 1 - r2 + 1, n - 1 - l2 + 1)\n if (r1 - l1 == 0 && r3 - l3 == 0) {\n println(-1)\n return\n }\n if (r1 - l1 > r3 - l3) {\n ans.append((l1, r1 - 1))\n p += r1 - l1\n } else {\n ans.append((r3 - 1, l3))\n p += r3 - l3\n }\n }\n println(ans.length)\n for ((l, r) <- ans) {\n printf(\"%d %d\\n\", l + 1, r + 1)\n }\n }\n}\n\n\nclass KMP[T](val pat: Seq[T]) {\n val m = pat.length\n val fail = Array.fill(m + 1)(-1)\n\n {\n var j = -1\n fail(0) = -1\n for (i <- 0 until m) {\n while (j != -1 && !pat(i).equals(pat(j))) j = fail(j)\n j += 1\n fail(i + 1) = j\n }\n }\n\n def longestPrefix(txt: Seq[T]): (Int, Int) = {\n val n = txt.length\n var j = 0\n var ans = (0, 0)\n for (i <- 0 until n) {\n while (j != -1 && !txt(i).equals(pat(j))) j = fail(j)\n j += 1\n if (j > 0 && ans._2 - ans._1 < j) {\n val s = i - j + 1\n ans = (s, i + 1)\n }\n if (j == m) {\n j = fail(m)\n }\n }\n return ans\n }\n}\n\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\n/**\n * Created by hsleep on 2016. 1. 8..\n */\nobject CSolution extends App {\n val coating = StdIn.readLine()\n val content = StdIn.readLine()\n\n val mapOfCoating = (0 until coating.length).map { i =>\n coating(i) -> i\n }.groupBy(_._1).mapValues(seq => seq.map(_._2))\n\n def matchedStringLength(it1: Iterator[Char], it2: Iterator[Char]): Int = {\n var i = 0\n while (it1.hasNext && it2.hasNext && it1.next() == it2.next()) {\n i += 1\n }\n i\n }\n\n def findLongCoating(piece: String, prevResult: Seq[(Int, Int)] = Nil): Seq[(Int, Int)] = {\n val c = piece.head\n mapOfCoating.get(c) match {\n case Some(indices) =>\n val p = indices.flatMap { idx =>\n val pl = matchedStringLength(piece.iterator, coating.drop(idx).iterator)\n val nl = matchedStringLength(piece.iterator, coating.take(idx + 1).reverseIterator)\n Array(pl -> (idx, idx + pl - 1), nl -> (idx, idx - nl + 1))\n }.maxBy(_._1)\n piece.drop(p._1) match {\n case l if l.isEmpty =>\n prevResult :+ p._2\n case l =>\n findLongCoating(l, prevResult :+ p._2)\n }\n case None => Nil\n }\n }\n\n val output = findLongCoating(content)\n output match {\n case l if l.isEmpty => println(-1)\n case l => println(l.length)\n }\n output.foreach { case (i, j) =>\n println(s\"${i + 1} ${j + 1}\")\n }\n}"}], "negative_code": [], "src_uid": "c6c4a833843d479c94f9ebd3e2774775"} {"source_code": "object counter {\n\n var delay:Int = 0\n\n def findFriends(messages:List[Message], friends:Set[Set[String]]):Set[Set[String]] = messages match {\n case Nil => friends\n case head::Nil => friends\n case head::tail => if(tail.exists( message => message.time - head.time <= delay && message.time != head.time && message.to == head.from && message.from == head.to))\n findFriends(tail, friends + Set(head.from, head.to))\n else\n findFriends(tail, friends)\n }\n\n def main(args: Array[String]) {\n val values = Console.readLine().split(\" \")\n val numOfMessages = values(0).toInt\n delay = values(1).toInt\n val messages = 1 to numOfMessages map { _ => {\n val line = Console.readLine().split(\" \")\n new Message(line(0), line(1), line(2).toInt)\n } } toList\n val result = findFriends(messages, Set.empty)\n println(result.size)\n result.foreach(set => println(set.mkString(\" \")))\n }\n\n}\n\ncase class Message(from:String, to:String, time:Int)\n", "positive_code": [{"source_code": "import scala.collection.mutable.HashSet\n\nobject Main {\n def main(args: Array[String]) {\n val Array(n, d) = readLine split \" \" map (_.toInt)\n var times = new HashSet[ (String, String, Int) ]\n \n var res = new HashSet[(String, String)]\n \n for(i <- 0 until n) {\n val Array(a, b, ts) = readLine split \" \"\n times.filter(t => t._3 < ts.toInt - d).foreach(times.remove) // Удаляем устаревшие пары\n times.filter(t => t._2 == a && t._1 == b && ts.toInt != t._3).foreach(p => {\n if(p._1 > p._2)\n res += ((p._2, p._1)) \n else \n res += ((p._1, p._2))\n })\n times += ((a, b, ts.toInt))\n }\n \n println(res.size)\n res.foreach(r => println(r._1+\" \"+r._2))\n }\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable.HashSet\n\nobject Main {\n def main(args: Array[String]) {\n val Array(n, d) = readLine split \" \" map (_.toInt)\n var times = new HashSet[ (String, String, Int) ]\n \n var res = new HashSet[(String, String)]\n \n for(i <- 0 until n) {\n val Array(a, b, ts) = readLine split \" \"\n times.filter(t => t._3 < ts.toInt - d).foreach(times.remove) // Удаляем устаревшие пары\n times.filter(t => t._2 == a && t._1 == b).foreach(p => {\n if(p._1 > p._2)\n res += ((p._2, p._1)) \n else \n res += ((p._1, p._2))\n })\n times += ((a, b, ts.toInt))\n }\n \n println(res.size)\n res.foreach(r => println(r._1+\" \"+r._2))\n }\n}"}, {"source_code": "object counter {\n\n var delay:Int = 0\n\n def findFriends(messages:List[Message], friends:Set[Set[String]]):Set[Set[String]] = messages match {\n case Nil => friends\n case head::Nil => friends\n case head::tail => if(tail.exists( message => message.time - head.time <= delay && message.to == head.from && message.from == head.to))\n findFriends(tail, friends + Set(head.from, head.to))\n else\n findFriends(tail, friends)\n }\n\n def main(args: Array[String]) {\n val values = Console.readLine().split(\" \")\n val numOfMessages = values(0).toInt\n delay = values(1).toInt\n val messages = 1 to numOfMessages map { _ => {\n val line = Console.readLine().split(\" \")\n new Message(line(0), line(1), line(2).toInt)\n } } toList\n val result = findFriends(messages, Set.empty)\n println(result.size)\n result.foreach(set => println(set.mkString(\" \")))\n }\n\n}\n\ncase class Message(from:String, to:String, time:Int)\n"}], "src_uid": "3cb4c89b174bf5ea51e797b78103e089"} {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=100000\n val dp=new Array[Int](max+1)\n dp(1)=1\n a.foreach{num=>\n \tvar j=2\n \tvar nn=num\n \tvar best=0\n \tfor(i<-2 to math.sqrt(nn).toInt)\n \t{\n \t\tif(nn%i==0)\n \t\t\tbest=math.max(best,dp(i)+1)\n \t\twhile(nn%i==0) nn/=i\n \t}\n \tif(nn>1)\n \t{\n \t\tbest=math.max(best,dp(nn)+1)\n \t\tdp(nn)=best\n \t}\n \t\n \tnn=num\n \tfor(i<-2 to math.sqrt(nn).toInt)\n {\n if(nn%i==0)\n dp(i)=best\n while(nn%i==0) nn/=i\n }\n }\n println(dp.max)\n}", "positive_code": [{"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=100000\n val dp=new Array[Int](max+1)\n dp(1)=1\n \n a.foreach{num=>\n var nn=num\n var best=0\n val list=(for(i<- 2 to math.sqrt(nn).toInt if i*i<=nn && nn%i==0) yield\n {\n while(nn%i==0) nn/=i\n i\n }):+nn\n\n //println(list)\n best=dp(list.maxBy{i=>if(i>1) dp(i) else 0})+1\n //println(best)\n list.foreach{i=>if(i>1) dp(i)=best}\n //(1 to 10).foreach{i=>print(dp(i)+\" \")}\n //println()\n }\n println(dp.max)\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=100000\n val dp=new Array[Int](max+1)\n dp(1)=1\n \n a.foreach{num=>\n var nn=num\n val list=((for(i<- 2 to math.sqrt(nn).toInt if i*i<=nn && nn%i==0) yield\n {\n while(nn%i==0) nn/=i\n i\n }):+nn).filter{_!=1}\n\n if(!list.isEmpty)\n {\n //println(list)\n val best=dp(list.maxBy{i=>dp(i)})+1\n //println(best)\n list.foreach{i=>dp(i)=best}\n //(1 to 10).foreach{i=>print(dp(i)+\" \")}\n //println()\n }\n }\n println(dp.max)\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=100000\n val dp=new Array[Int](max+1)\n dp(1)=1\n a.foreach{num=>\n var nn=num\n var best=0\n val list=for(i<- 2 to math.sqrt(nn).toInt if i*i<=nn && nn%i==0) yield\n {\n while(nn%i==0) nn/=i\n i\n }\n\n if(list.size>0) best=dp(list.maxBy{i=>dp(i)})+1\n\n if(nn>1)\n {\n best=math.max(best,dp(nn)+1)\n dp(nn)=best\n }\n \n if(list.size>0) list.foreach{i=>dp(i)=best}\n }\n println(dp.max)\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=100000\n val dp=new Array[Int](max+1)\n dp(1)=1\n a.foreach{num=>\n \tvar i=2\n \tvar nn=num\n \tvar best=0\n \tfor(i<- 2 to math.sqrt(nn).toInt if i*i<=nn)\n \t{\n \t\tif(nn%i==0)\n \t\t\tbest=math.max(best,dp(i)+1)\n \t\twhile(nn%i==0) nn/=i\n \t}\n \tif(nn>1)\n \t{\n \t\tbest=math.max(best,dp(nn)+1)\n \t\tdp(nn)=best\n \t}\n \t\n \ti=2\n \tnn=num\n for(i<- 2 to math.sqrt(nn).toInt if i*i<=nn)\n {\n if(nn%i==0)\n dp(i)=best\n while(nn%i==0) nn/=i\n }\n }\n println(dp.max)\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=100000\n val dp=new Array[Int](max+1)\n dp(1)=1\n a.foreach{num=>\n \tvar i=2\n \tvar nn=num\n \tvar best=0\n \twhile(i*i<=nn)\n \t{\n \t\tif(nn%i==0)\n \t\t\tbest=math.max(best,dp(i)+1)\n \t\twhile(nn%i==0) nn/=i\n \t\ti+=1\n \t}\n \tif(nn>1)\n \t{\n \t\tbest=math.max(best,dp(nn)+1)\n \t\tdp(nn)=best\n \t}\n \t\n \ti=2\n \tnn=num\n while(i*i<=nn)\n {\n if(nn%i==0)\n dp(i)=best\n while(nn%i==0) nn/=i\n i+=1\n }\n }\n println(dp.max)\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=100000\n val dp=new Array[Int](max+1)\n dp(1)=1\n a.foreach{num=>\n \tvar j=2\n \tvar nn=num\n \tvar best=0\n \twhile(j*j<=nn)\n \t{\n \t\tif(nn%j==0)\n \t\t\tbest=math.max(best,dp(j)+1)\n \t\twhile(nn%j==0) nn/=j\n \t\tj+=1\n \t}\n \tif(nn>1) best=math.max(best,dp(nn)+1)\n \t\n \tj=2\n \tnn=num\n \twhile(j*j<=nn)\n {\n if(nn%j==0)\n dp(j)=best\n while(nn%j==0) nn/=j\n j+=1\n }\n \tif(nn>1) dp(nn)=best\n }\n println(dp.max)\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=100000\n val dp=new Array[Int](max+1)\n dp(1)=1\n a.foreach{num=>\n \tvar j=2\n \tvar nn=num\n \tvar best=0\n \tfor(i<-2 to math.sqrt(max).toInt)\n \t{\n \t\tif(nn%i==0)\n \t\t\tbest=math.max(best,dp(i)+1)\n \t\twhile(nn%i==0) nn/=i\n \t}\n \tif(nn>1)\n \t{\n \t\tbest=math.max(best,dp(nn)+1)\n \t\tdp(nn)=best\n \t}\n \t\n \tnn=num\n \tfor(i<-2 to math.sqrt(max).toInt)\n {\n if(nn%i==0)\n dp(i)=best\n while(nn%i==0) nn/=i\n }\n }\n println(dp.max)\n}"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport scala.annotation.tailrec\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n val n = br.readLine().toInt\n val a = br.readLine().split(\" \").map(_.toInt)\n \n def divider(number:Int):List[Int]={\n var res = List[Int]()\n @tailrec\n def rec(i:Int,d:Int):Unit={\n if(i*i<=d){ \n if(d%i==0)res = i::d/i::res\n rec(i+1,d)\n }\n }\n rec(2,number)\n return res\n }\n \n var dp = new Array[Int](100001)\n for(i <- a){\n dp(i) = 1\n val div = divider(i)\n var max = 1\n div.foreach(x => max = Math.max(max,1+dp(x)))\n dp(i) = max\n div.foreach(x => dp(x) = Math.max(dp(x),max))\n }\n println(dp.reduce(Math.max(_,_)))\n }\n\n}"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport scala.annotation.tailrec\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n val n = br.readLine().toInt\n val a = br.readLine().split(\" \").map(_.toInt)\n \n def divider(number:Int):List[Int]={\n var res = List[Int]()\n @tailrec\n def rec(i:Int,d:Int):Unit={\n if(i*i<=d){ \n if(d%i==0)res = i::d/i::res\n rec(i+1,d)\n }\n }\n rec(2,number)\n return res\n }\n \n var dp = new Array[Int](100001)\n for(i <- a){\n dp(i) = 1\n val div = divider(i)\n var max = 1\n for(j <- div){\n max = Math.max(max,1+dp(j))\n }\n dp(i) = max\n for(j <- div){\n dp(j) = Math.max(dp(j),max)\n }\n }\n println(dp.reduce(Math.max(_,_)))\n }\n\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=100000\n val dp=new Array[Int](max+1)\n \n var ans=1\n \n a.foreach{num=>\n \tvar j=2\n \tvar nn=num\n \tvar best=0\n \twhile(j*j<=nn)\n \t{\n \t\tif(nn%j==0)\n \t\t\tbest=math.max(best,dp(j)+1)\n \t\twhile(nn%j==0) nn/=j\n \t\tj+=1\n \t}\n \tif(nn>1) best=math.max(best,dp(nn)+1)\n \t\n \tj=2\n \tnn=num\n \twhile(j*j<=nn)\n {\n if(nn%j==0)\n dp(j)=best\n while(nn%j==0) nn/=j\n j+=1\n }\n \tif(nn>1) dp(nn)=best\n \tans=math.max(ans,best)\n }\n println(ans)\n}"}], "negative_code": [{"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=100000\n val dp=new Array[Int](max+1)\n \n a.foreach{num=>\n \tvar j=2\n \tvar nn=num\n \tvar best=0\n \twhile(j*j<=nn)\n \t{\n \t\tif(nn%j==0)\n \t\t\tbest=math.max(best,dp(j)+1)\n \t\twhile(nn%j==0) nn/=j\n \t\tj+=1\n \t}\n \tif(nn>1) best=math.max(best,dp(nn)+1)\n \t\n \tj=2\n \tnn=num\n \twhile(j*j<=nn)\n {\n if(nn%j==0)\n dp(j)=best\n while(nn%j==0) nn/=j\n j+=1\n }\n \tif(nn>1) dp(nn)=best\n }\n println(dp.max)\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=100000\n val dp=new Array[Int](max+1)\n dp(1)=1\n \n a.foreach{num=>\n var nn=num\n var best=0\n val list=(for(i<- 2 to math.sqrt(nn).toInt if i*i<=nn && nn%i==0) yield\n {\n while(nn%i==0) nn/=i\n i\n }):+nn\n\n //println(list)\n best=dp(list.maxBy{i=>dp(i)})+1\n //println(best)\n list.foreach{i=>if(i>1) dp(i)=best}\n //(1 to 10).foreach{i=>print(dp(i)+\" \")}\n //println()\n }\n println(dp.max)\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=100000\n val dp=new Array[Int](max+1)\n dp(1)=1\n a.foreach{num=>\n \tvar i=2\n \tvar nn=num\n \tvar best=0\n \twhile(i*i<=nn)\n \t{\n \t\tif(nn%i==0)\n \t\t\tbest=math.max(best,dp(i)+1)\n \t\twhile(nn%i==0) nn/=i\n \t\ti+=1\n \t}\n \tif(nn>1)\n \t{\n \t\tbest=math.max(best,dp(nn)+1)\n \t\tdp(nn)=best\n \t}\n \t\n \tnn=num\n while(i*i<=nn)\n {\n if(nn%i==0)\n dp(i)=best\n while(nn%i==0) nn/=i\n i+=1\n }\n }\n println(dp.max)\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=100000\n val dp=new Array[Int](max+1)\n \n var ans=1\n \n a.foreach{num=>\n \tvar j=2\n \tvar nn=num\n \tvar best=0\n \twhile(j*j<=nn)\n \t{\n \t\tif(nn%j==0)\n \t\t\tbest=math.max(best,dp(j)+1)\n \t\twhile(nn%j==0) nn/=j\n \t\tj+=1\n \t}\n \tif(nn>1) best=math.max(best,dp(nn)+1)\n \t\n \tj=2\n \tnn=num\n \twhile(j*j<=nn)\n {\n if(nn%j==0)\n dp(j)=best\n while(nn%j==0) nn/=j\n j+=1\n }\n \tif(nn>1) dp(j)=best\n \tans=math.max(ans,best)\n }\n println(ans)\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=100000\n val dp=new Array[Int](max+1)\n dp(1)=1\n \n a.foreach{num=>\n var nn=num\n var best=0\n val list=(for(i<- 2 to math.sqrt(nn).toInt if i*i<=nn && nn%i==0) yield\n {\n while(nn%i==0) nn/=i\n i\n }):+nn-1\n\n best=dp(list.maxBy{i=>dp(i)})+1\n list.foreach{i=>dp(i)=best}\n }\n println(dp.max)\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=100000\n val dp=new Array[Int](max+1)\n dp(1)=1\n a.foreach{num=>\n \tvar j=2\n \tvar nn=num\n \tvar best=0\n \tfor(i<-2 to math.sqrt(max).toInt)\n \t{\n \t\tif(nn%i==0)\n \t\t\tbest=math.max(best,dp(i)+1)\n \t\twhile(nn%i==0) nn/=i\n \t}\n \tif(nn>1)\n \t{\n \t\tbest=math.max(best,dp(max)+1)\n \t\tdp(nn)=best\n \t}\n \t\n \tnn=num\n \tfor(i<-2 to math.sqrt(nn).toInt)\n {\n if(nn%i==0)\n dp(i)=best\n while(nn%i==0) nn/=i\n }\n }\n println(dp.max)\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=100000\n val dp=new Array[Int](max+1)\n dp(1)=1\n a.foreach{num=>\n var i=2\n var nn=num\n var best=0\n val list=for(i<- 2 to math.sqrt(nn).toInt if i*i<=nn && nn%i==0) yield\n {\n while(nn%i==0) nn/=i\n i\n }\n\n if(list.size>0) best=list.maxBy{i=>dp(i)}+1\n if(nn>1)\n {\n best=math.max(best,dp(nn)+1)\n dp(nn)=best\n }\n \n if(list.size>0) list.foreach{i=>dp(i)=best}\n }\n println(dp.max)\n}"}], "src_uid": "0f8ad0ea2befbbe036fbd5e5f6680c21"} {"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val n = readLine().toInt\n val arr = readIntLine()\n println(calcGrannies(arr.sorted))\n }\n// println(calcGrannies(List[Int](2, 3, 4, 5)))\n }\n\n def calcGrannies(arr: List[Int]): Int = {\n def helper(map: List[(Int, Int)], people: Int, acc: Int): Int = map match {\n case Nil => people\n case (wanted, grannies) :: rest =>\n if (grannies - 1 + people + acc >= wanted) helper(rest, people + acc + grannies, 0)\n else helper(rest, people, acc + grannies)\n }\n\n helper(arr.groupBy(i => i).map { case (k, v) => (k, v.length) }.toList.sortBy(tup => tup._1), 1, 0)\n }\n\n def makeArray(n: Int) {\n class QueueElement(val left: Int, val right: Int) {}\n\n val arr = Array.ofDim[Int](n)\n val intervals = (0 to n).map(_ => ListBuffer[QueueElement]()).toArray\n intervals(n) += new QueueElement(0, n - 1)\n var count = 1\n for (i <- (0 to n).reverse) {\n var intOfLengthI = intervals(i)\n intOfLengthI = intOfLengthI.sortBy(_.left)\n for (j <- intOfLengthI.indices) {\n val head = intOfLengthI(j)\n if (head.left == head.right) {\n arr(head.left) = count\n } else {\n val mid = (head.left + head.right) / 2\n arr(mid) = count\n if (mid != head.left) intervals(mid - head.left) += new QueueElement(head.left, mid - 1)\n intervals(head.right - mid) += new QueueElement(mid + 1, head.right)\n }\n count += 1\n }\n }\n\n printArray(arr)\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject B {\n def solution(a0: Seq[Int]): Int = {\n val a = a0.toArray.sorted\n var i = a.length - 1\n var r = 1\n while (i >= 0 && r == 1) {\n if (a(i) <= i + 1)\n r = i + 2\n i -= 1\n }\n r\n }\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val _ = readLine\n val a = readLine.split(\" \").toSeq.map(_.toInt)\n println(solution(a))\n }\n }\n}"}, {"source_code": "import java.util\nimport java.util.Collections\n\nobject ProblemB extends App {\n\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n import scala.collection.mutable\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n\n for (_ <- 1 to t) {\n val n = in.nextInt()\n val numbers = new mutable.TreeMap[Int, Int]()\n for (_ <- 0 until n) {\n val ai = in.nextInt()\n numbers.update(ai, numbers.getOrElse(ai, 0) + 1)\n }\n\n var result = 1\n var buf = 0\n numbers.foreach {\n case (ai, count) =>\n if (count + result + buf > ai) {\n result = result + count + buf\n buf = 0\n } else {\n buf = buf + count\n }\n }\n\n println(result)\n\n }\n\n}\n"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n\n val (ans, _) = an.foldLeft((1, 0)) {\n case ((c, r), a) =>\n if (a <= c + r) (c + r + 1, 0)\n else (c, r + 1)\n }\n\n println(ans)\n }\n}\n"}], "negative_code": [], "src_uid": "718cea81f609055cece58cae5310f703"} {"source_code": "import java.io._\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n\n val n = readInt\n val lines = 0 +: readInts :+ 0\n for(_ <- 1 to readInt) {\n val Array(r, c) = readInts\n lines.update(r - 1, lines(r - 1) + c - 1)\n lines.update(r + 1, lines(r + 1) + lines(r) - c)\n lines.update(r, 0)\n }\n\n def main(a: Array[String]) {\n println(lines.drop(1).take(n).mkString(\"\\n\"))\n }\n}\n", "positive_code": [{"source_code": "object A294 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val ai = readInts(n)\n val Array(m) = readInts(1)\n for(_ <- 1 to m) {\n var Array(x, y) = readInts(2)\n x -= 1\n val curr = ai(x)\n ai(x) = 0\n if(x-1 >= 0) {\n ai(x-1) += y-1\n }\n if(x + 1 < n) {\n ai(x+1) += curr-y\n }\n }\n\n out.println(ai.mkString(\"\\n\"))\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P294A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val w = Array.fill(N + 2)(Int.MinValue)\n for (i <- 1 to N)\n w(i) = sc.nextInt\n val M = sc.nextInt\n\n def shoot: Unit = {\n val x, y = sc.nextInt\n val left = y - 1\n val right = w(x) - y\n w(x) = 0\n w(x - 1) += left\n w(x + 1) += right\n }\n\n for (i <- 0 until M) shoot\n\n for (i <- 1 to N)\n out.println(w(i))\n\n out.close\n}\n"}, {"source_code": "object A {\n def READ: Array[Int] = readLine() split (\" \") map (_.toInt);\n\n def main(args: Array[String]) {\n var Array(n) = READ\n var a = READ\n var Array(m) = READ\n for (i <- 1 to m) {\n var Array(x, y) = READ\n if (x > 1) a(x-2) += y-1;\n if (x < n) a(x) += a(x-1)-y;\n a(x-1) = 0;\n }\n a map (println(_))\n }\n}\n"}, {"source_code": "object Main {\n class Wires(val n: Int) {\n private val data = readLine().split(\" \").map(_.toInt).toArray\n \n def shoot() = {\n val s = readLine().split(\" \").map(_.toInt)\n val x = s(0)\n val y = s(1)\n \n val up = y - 1\n val down = data(x - 1) - y\n \n data(x - 1) = 0\n if (x - 2 >= 0) data(x - 2) += up\n if (x < n) data(x) += down\n }\n \n def print() {\n data.foreach(println(_))\n }\n } \n\n def main(args: Array[String]) {\n val n = readInt\n val w = new Wires(n) \n val m = readInt\n for (_ <- 1 to m) { w.shoot() }\n w.print()\n }\n}"}, {"source_code": "object CF178Div2A {\n def main(args:Array[String]){\n val n = readLine.toInt\n var arr = readLine.split(\" \").map(_.toInt)\n val m = readLine.toInt\n (1 to m).foreach(i =>{\n val Array(x,y) = readLine.split(\" \").map(_.toInt - 1)\n if(x > 0) arr(x-1) += y\n if(x < n-1) arr(x+1) += arr(x)-(y+1)\n arr(x) = 0\n })\n arr.foreach(x => println(x))\n }\n}"}, {"source_code": " object Birds extends App{\n \t\t \tdef resolve(lines: IndexedSeq[String]) = {\n \t\t \t \t\tval n = lines(0).toInt\n \t\t \t \t\tvar birdsByWire = Map[Int, Int]()\n \t\t \t \t\t \t\t \t \t\t\n \t\t \t \t\tfor ((birds, wire) <- lines(1).split(\" \").toList.zip(1 to n)) {\n \t\t \t \t\t \t\t\tbirdsByWire = birdsByWire + (wire -> birds.toInt)\n \t\t \t \t\t }\n \t\t \t \t\t\n \t\t \t \t\tval cases = lines.drop(3)\n \t\t\t\t\t\t\tfor(l <- cases) {\n \t\t\t\t\t\t\t\t\n \t\t\t\t\t\t\t\tval (wire, shot) = {\n \t\t\t\t\t\t\t\t\tval tokens = l.split(\" \")\n\t \t\t\t\t\t\t\t\t(tokens(0).toInt, tokens(1).toInt)\n \t\t\t\t\t\t\t\t}\n \t\t\t\t\t\t\t\t\n \t\t\n \t\t\t\t\t\t\t\tval left = shot - 1\n \t\t\t\t\t\t\t\tval right = birdsByWire(wire) - shot\n \t\t\n\t\t\t\t\t \t\t\tif (n == 1) {\n\t\t\t\t\t \t\t\t\tbirdsByWire += (n -> 0)\n\t\t\t\t\t \t\t\t} else if (wire == n) {\n\t\t\t\t\t \t\t\t\tbirdsByWire += (wire - 1 -> (birdsByWire(wire - 1) + left))\n\t\t\t\t\t \tbirdsByWire += (n -> 0)\n\t\t\t\t\t \t\t\t} else if (wire == 1) {\n\t\t\t\t\t \t\t\t\tbirdsByWire += (wire + 1 -> (birdsByWire(wire + 1) + right))\n\t\t\t\t\t \t\t\t\tbirdsByWire += (1 -> 0)\n\t\t\t\t\t \t\t\t} else {\n\t\t\t\t\t \t\t\t\tbirdsByWire += (wire + 1 -> (birdsByWire(wire + 1) + right))\n\t\t\t\t\t \t\t\t\tbirdsByWire += (wire - 1 -> (birdsByWire(wire - 1) + left))\n\t\t\t\t\t \t\t\t\tbirdsByWire += (wire -> 0)\n\t\t\t\t\t \t\t\t}\n\t\t\t\t\t \t\t\t\n\t\t\t\t\t\t \t}\n \t\n \t\t\t\t\t\t\tfor(w <- 1 to n) println(birdsByWire(w))\n \t\t\t\t\t}\n \n\t\t\tresolve(io.Source.stdin.getLines.toIndexedSeq)\n \n }"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val birds = in.next().split(\" \").map(_.toInt)\n val m = in.next().toInt\n (1 to m).foreach { _ =>\n val Array(x, y) = in.next().split(\" \").map(_.toInt)\n val indexX = x - 1\n val birdCount = birds(indexX)\n val up = y - 1\n val down = birdCount - y\n if (indexX != 0)\n birds(indexX - 1) += up\n if (indexX != n - 1)\n birds(indexX + 1) += down\n birds(indexX) = 0\n }\n println(birds.mkString(\"\\n\"))\n}"}, {"source_code": "object Main extends App {\n \n val numberN = readLine().toInt\n val birdsOn = readLine().split(\"\\\\s+\").map(_.toInt)\n val numberM = readLine().toInt\n \n for (i <- 0 to (numberM - 1)) {\n val pairXY = readLine().split(\"\\\\s+\") match { case Array (x, y) => (x.toInt, y.toInt)}\n \n if (pairXY._1 - 2 >= 0) {\n birdsOn(pairXY._1 - 2) += pairXY._2 - 1;\n }\n \n if (pairXY._1 <= numberN - 1) {\n birdsOn(pairXY._1) += birdsOn(pairXY._1 - 1) - pairXY._2\n }\n \n birdsOn(pairXY._1 - 1) = 0 \n }\n \n for (i <- birdsOn) {\n println(i)\n }\n \n\n}"}], "negative_code": [{"source_code": " object Birds extends App {\n \tval lines = io.Source.stdin.getLines.toIndexedSeq\n \tval n = lines(0).toInt\n \tvar birdsByLine = Map[Int, Int]()\n \t\n \tfor ((birds, line) <- lines(1).split(\" \").toList.zip(1 to n)) {\n \t\tbirdsByLine = birdsByLine + (line -> birds.toInt)\n \t}\n \t\n \tfor(l <- lines.drop(3)) {\n \t\tval (shot, line) = {\n \t\t\tval tokens = l.split(\" \")\n \t\t\t(tokens(1).toInt, tokens(0).toInt)\n \t\t}\n \t\t\n \t\tval birdsToTheLeft = shot - 1\n \t\tval birdsToTheRigth = birdsByLine(line) - shot\n \t\t\n \t\tif (n == 1) {\n \t\t\tbirdsByLine += (n -> 0)\n \t\t} else if (line == n) {\n \t\t\tbirdsByLine += (line - 1 -> (birdsByLine(line - 1) + birdsToTheLeft))\n birdsByLine += (n -> 0)\n \t\t} else if (line == 1) {\n \t\t\tbirdsByLine += (line + 1 -> (birdsByLine(line + 1) + birdsToTheRigth))\n \t\t\tbirdsByLine += (1 -> 0)\n \t\t} else {\n \t\t\tbirdsByLine += (line + 1 -> (birdsByLine(line + 1) + birdsToTheRigth))\n \t\t\tbirdsByLine += (line - 1 -> (birdsByLine(line - 1) + birdsToTheLeft))\n \t\t\tbirdsByLine += (line -> 0)\n \t\t}\n \t}\n \t\n \tbirdsByLine.foreach(p => println(p._2))\n }"}, {"source_code": " object Birds extends App {\n \tval lines = io.Source.stdin.getLines.toIndexedSeq\n \tval n = lines(0).toInt\n \tvar birdsByLine = Map[Int, Int]()\n \t\n \tfor ((birds, line) <- lines(1).split(\" \").toList.zip(1 to n)) {\n \t\tbirdsByLine = birdsByLine + (line -> birds.toInt)\n \t}\n \t\n \tfor(l <- lines.drop(3)) {\n \t\tval (shot, line) = {\n \t\t\tval tokens = l.split(\" \")\n \t\t\t(tokens(1).toInt, tokens(0).toInt)\n \t\t}\n \t\t\n \t\tval birdsToTheLeft = shot - 1\n \t\tval birdsToTheRigth = birdsByLine(line) - shot\n \t\t\n \t\tif (n == 1) {\n \t\t\tbirdsByLine += (n -> 0)\n \t\t} else if (line == n) {\n \t\t\tbirdsByLine += (line - 1 -> (birdsByLine(line - 1) + birdsToTheLeft))\n\t\t\tbirdsByLine += (line -> 0)\n birdsByLine += (n -> 0)\n \t\t} else if (line == 1) {\n \t\t\tbirdsByLine += (line + 1 -> (birdsByLine(line + 1) + birdsToTheRigth))\n \t\t\tbirdsByLine += (1 -> 0)\n \t\t} else {\n \t\t\tbirdsByLine += (line + 1 -> (birdsByLine(line + 1) + birdsToTheRigth))\n \t\t\tbirdsByLine += (line - 1 -> (birdsByLine(line - 1) + birdsToTheLeft))\n \t\t\tbirdsByLine += (line -> 0)\n \t\t}\n \t}\n \t\n \tbirdsByLine.foreach(p => println(p._2))\n }"}], "src_uid": "859d66fc2c204a8c002012b1fb206645"} {"source_code": "import scala.io.StdIn._ \nimport scala.util.control._\n\nobject cf699B {\n def main (args:Array[String]) {\n var line = readLine();\n val ss = line.split(\" \");\n val n = ss(0).toInt;\n val m = ss(1).toInt;\n var a = new Array[String](1000 + 5);\n\n for (i <- 0 until n) {\n a(i) = readLine();\n }\n\n var r = new Array[Int](1000 + 5);\n for (i <- 0 until n) {\n r(i) = 0;\n }\n\n var c = new Array[Int](1000 + 5);\n for (i <- 0 until m) {\n c(i) = 0;\n }\n\n var cnt = 0;\n\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (a(i)(j) == '*') {\n cnt += 1;\n r(i) += 1;\n c(j) += 1;\n } \n }\n }\n \n\n var res = false;\n var plcx = 0;\n var plcy = 0;\n\n var ans = 0;\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n ans = cnt;\n if (a(i)(j) == '*') ans += 1;\n ans -= r(i);\n ans -= c(j);\n if (ans == 0) {\n res = true;\n plcx = i + 1;\n plcy = j + 1;\n }\n }\n }\n if (res == true) {\n println(\"YES\");\n println(plcx + \" \" + plcy);\n } else {\n println(\"NO\");\n }\n }\n}", "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _699B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val n, m = read[Int]\n val room = read[Vector, String](n)\n\n val rowCount, colCount = map[Int] to 0\n var bombs = 0\n\n for {\n r <- 0 until n\n c <- 0 until m\n if room(r)(c) == '*'\n } {\n rowCount(r) += 1\n colCount(c) += 1\n bombs += 1\n }\n\n val ans = for {\n r <- 0 until n\n c <- 0 until m\n if rowCount(r) + colCount(c) - (room(r)(c) == '*').to[Int] == bombs\n } yield r -> c\n\n ans.headOption match {\n case None => write(false.toEnglish)\n case Some((i, j)) => write(true.toEnglish).writeOnNextLine(i + 1, j + 1)\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n def X[B](bs: Iterable[B]): Iterable[(A, B)] = for {a <- s; b <- bs} yield (a, b)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _699B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val n, m = read[Int]\n val room = read[Vector, String](n)\n\n val rowCount, colCount = map[Int] to 0\n var bombs = 0\n\n n X m foreach { case (r, c) =>\n if (room(r)(c) == '*') {\n rowCount(r) += 1\n colCount(c) += 1\n bombs += 1\n }\n }\n\n val ans = n X m find { case (r, c) =>\n rowCount(r) + colCount(c) - (room(r)(c) == '*').to[Int] == bombs\n }\n\n ans match {\n case None => write(false.toEnglish)\n case Some((i, j)) => write(true.toEnglish).writeOnNextLine(i + 1, j + 1)\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n val Array(n,m) = StdIn.readLine().split(\" \").map(_.toInt)\n\n\n var N:Array[Int] = new Array[Int](n)\n var M:Array[Int] = new Array[Int](m)\n\n var TD = Array.ofDim[Array[Int]](n)\n var sum = 0\n for(i <- 0 to n - 1) {\n TD(i) = StdIn.readLine().toCharArray.map(t=> if(t == '*') 1 else 0);\n TD(i)\n .zipWithIndex\n .foreach((a) => {\n sum+=TD(i)(a._2)\n N(i)+=TD(i)(a._2)\n M(a._2)+=TD(i)(a._2)\n })\n }\n\n for(i <- 0 to n - 1) {\n for(j <- 0 to m - 1) {\n if(M(j) + N(i) - TD(i)(j) == sum) {\n println(\"YES\")\n println((i+1) + \" \" + (j+1))\n return\n }\n }\n }\n println(\"NO\")\n\n\n }\n\n\n}\n"}, {"source_code": "import scala.io._\nimport java.util.Scanner\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport scala.collection.breakOut\n\n\nobject Main {\n def main(args: Array[String]) {\n val bfReader = new BufferedReader(new InputStreamReader(System.in))\n val scanner = new Scanner(bfReader.readLine())\n val (n, m) = (scanner.nextInt(), scanner.nextInt())\n val a = for (r <- 0 until n; line = bfReader.readLine()) yield line\n\n def cellVal(ch: Char): Int = if (ch == '*') 1 else 0\n\n val pr = a.map(chs => chs.map(cellVal).sum)\n val pc = for (c <- 0 until m) yield a.map(chs => chs(c)).map(cellVal).sum\n\n val allBombsVal = a.map(chs => chs.map(cellVal).sum).sum\n val validPositions = for (r <- 0 until n; c <- 0 until m if pr(r) + pc(c) - cellVal(a(r)(c)) == allBombsVal) yield (r, c)\n\n if (validPositions.isEmpty) println(\"NO\")\n else {\n val (r, c) = validPositions(0)\n println(s\"YES\\n${r + 1} ${c + 1}\")\n }\n }\n}"}, {"source_code": "import scala.io._\nimport java.util.Scanner\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport scala.collection.breakOut\n\nobject Main {\n def main(args: Array[String]) {\n val bfReader = new BufferedReader(new InputStreamReader(System.in))\n val scanner = new Scanner(bfReader.readLine())\n val (n, m) = (scanner.nextInt(), scanner.nextInt())\n val a = for (r <- 0 until n; line = bfReader.readLine()) yield line\n\n def cellVal(ch: Char): Int = if (ch == '*') 1 else 0\n\n val pr = a.map(chs => chs.map(cellVal).sum)\n val pc = for (c <- 0 until m) yield a.map(chs => chs(c)).map(cellVal).sum\n\n val allBombsVal = a.map(chs => chs.map(cellVal).sum).sum\n val validPositions = for (r <- 0 until n; c <- 0 until m if pr(r) + pc(c) - cellVal(a(r)(c)) == allBombsVal) yield (r, c)\n\n if (validPositions.isEmpty) println(\"NO\")\n else {\n val (r, c) = validPositions(0)\n println(s\"YES\\n${r + 1} ${c + 1}\")\n }\n }\n}"}, {"source_code": "import scala.util.control.Breaks._\n\nobject main extends App{\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n var area = new Array[String](n)\n var rows = new Array[Int](n)\n var cols = new Array[Int](m)\n var count = 0\n for (i <- 0 until n) {\n \tarea(i) = readLine\n \trows(i) = area(i).toArray.foldLeft(0)((count: Int, char: Char) => if (char == '*') count + 1 else count)\n \tcount += rows(i)\n \tList.range(0, m).foreach((j: Int) => if (area(i)(j) == '*') cols(j) += 1 ) \n }\n val r = () => {\n \tvar result: Any = \"NO\";\n \tfor (i <- 0 until n) {\n\t \tfor (j <- 0 until m) {\n\t \t\tval res = rows(i) + cols(j) - (if (area(i)(j) == '*') 1 else 0)\n\t \t\tif (res >= count) {\n\t \t\t\tresult = Array(i+1, j+1)\n\t \t\t}\t \t\t\n\t \t}\n \t}\n \tresult;\n } \n r() match {\n \tcase s: String => println(s)\n \tcase Array(x, y) => {\n \t\tprintln(\"YES\")\n \t\tprintln(\"%d %d\".format(x, y))\n \t}\n }\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val lines = in.take(n).toList\n val linesBig = lines.indices.filter(i => lines(i).count(_ == '*') > 1).toList\n if (linesBig.length > 1) {\n println(\"NO\")\n }\n else if (linesBig.length == 1) {\n val y = linesBig.head\n val columnsBig = lines\n .indices\n .filter(i => i != y && lines(i).count(_ == '*') != 0)\n .map(i => lines(i).indexOf('*'))\n .distinct\n\n if (columnsBig.length > 1)\n println(\"NO\")\n else if (columnsBig.length == 1) {\n println(\"YES\")\n\n println(s\"${y + 1} ${columnsBig.head + 1}\")\n } else {\n println(\"YES\")\n println(s\"${y + 1} 1\")\n }\n } else {\n val columnsBig = lines\n .indices\n .filter(i => lines(i).count(_ == '*') != 0)\n .map(i => lines(i).indexOf('*'))\n .groupBy(i => i)\n .map(i => i._1 -> i._2.length)\n\n if (columnsBig.size > 2)\n println(\"NO\")\n else if (columnsBig.size == 2) {\n val one = columnsBig.find(_._2 == 1)\n if (one.isEmpty) {\n println(\"NO\")\n } else {\n val y = lines.indices.find(i => lines(i)(one.get._1) == '*').get\n val x = columnsBig.find(i => i._1 != one.get._1).get._1\n println(\"YES\")\n println(s\"${y + 1} ${x + 1}\")\n }\n } else if (columnsBig.size == 1) {\n println(\"YES\")\n println(s\"1 ${columnsBig.head._1 + 1}\")\n } else {\n println(\"YES\")\n println(\"1 1\")\n }\n\n }\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _699B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val n, m = read[Int]\n val room = read[Vector, String](n)\n\n val rowCount, colCount = map[Int] to 0\n var bombs = 0\n\n until(n, m) foreach { case (r, c) =>\n if (room(r)(c) == '*') {\n rowCount(r) += 1\n colCount(c) += 1\n bombs += 1\n }\n }\n\n val ans = until(n, m) find { case (r, c) =>\n rowCount(r) + colCount(c) - (room(r)(c) == '*').to[Int] == bombs\n }\n\n ans match {\n case None => write(false.toEnglish)\n case Some((i, j)) => write(true.toEnglish).writeOnNextLine(i + 1, j + 1)\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def until(d1: Int, d2: Int): Iterator[(Int, Int)] = (0 until d1) X (0 until d2)\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "\nimport java.util\n\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 11 Aug 2016\n */\nobject B699 extends App {\n\n def max(map: mutable.Map[Int, util.ArrayList[Int]]): (Int, Int) = {\n var maxIndex = 0\n var maxValue = 0\n map foreach {\n case (key, value) => {\n if (value.size() > maxValue) {\n maxValue = value.size()\n maxIndex = key\n }\n }\n }\n if (maxValue > 1) {\n map foreach {\n case (key, value) => {\n if (key != maxIndex && value.size > 1) {\n maxValue = 0\n }\n }\n }\n }\n (maxIndex + 1, maxValue)\n }\n\n def solve() = {\n val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val maze: Array[Array[Char]] = Array.ofDim[Char](n, m)\n for (i <- 0 until n) {\n maze(i) = scala.io.StdIn.readLine().toCharArray\n }\n val rowList: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty\n val colList: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty\n var starCount = 0\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (maze(i)(j) == '*') {\n starCount += 1\n if (!rowList.contains(i)) {\n rowList += (i -> new util.ArrayList[Int]())\n }\n if (!colList.contains(j)) {\n colList += (j -> new util.ArrayList[Int]())\n }\n rowList(i).add(j)\n colList(j).add(i)\n }\n }\n }\n val (maxRowIndex, maxRowValue) = max(rowList)\n val (maxColIndex, maxColValue) = max(colList)\n\n if (maxRowValue + maxColValue - starCount >= 0) {\n println(\"YES\")\n if (maxRowValue != 1 && maxColValue != 1) {\n println(maxRowIndex + \" \" + maxColIndex)\n } else if (maxRowValue == 1 && maxColValue == 1) {\n if (starCount == 1) {\n println(maxRowIndex + \" \" + maxColIndex)\n } else {\n val row = colList(maxColIndex - 1).get(0)\n var rrow = 0\n rowList foreach {\n case (key, value) => {\n if (key != row && !colList(maxColIndex - 1).contains(key)) {\n rrow = key\n }\n }\n }\n val col = rowList(rrow).get(0)\n var ccol = 0\n colList foreach {\n case (key, value) => {\n if (key != col && !rowList(rrow).contains(key)) {\n ccol = key\n }\n }\n }\n println((rrow + 1) + \" \" + (ccol + 1))\n }\n } else if (maxColValue != 1) {\n val row = colList(maxColIndex - 1).get(0)\n var rrow = 0\n rowList foreach {\n case (key, value) => {\n if (key != row && !colList(maxColIndex - 1).contains(key)) {\n rrow = key\n }\n }\n }\n println((rrow + 1) + \" \" + maxColIndex)\n } else {\n val col = rowList(maxRowIndex - 1).get(0)\n var ccol = 0\n colList foreach {\n case (key, value) => {\n if (key != col && !rowList(maxRowIndex - 1).contains(key)) {\n ccol = key\n }\n }\n }\n println(maxRowIndex + \" \" + (ccol + 1))\n }\n } else {\n println(\"NO\")\n }\n }\n\n solve()\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _699B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val n, m = read[Int]\n val room = read[Vector, String](n)\n\n val rowCount, colCount = map[Int] to 0\n var bombs = 0\n\n until(n, m) foreach { case (r, c) =>\n if (room(r)(c) == '*') {\n rowCount(r) += 1\n colCount(c) += 1\n bombs += 1\n }\n }\n\n val ans = until(n, m) find { case (r, c) =>\n rowCount(r) + colCount(c) - (room(r)(c) == '*').to[Int] == bombs\n }\n\n ans match {\n case None => write(false.toEnglish)\n case Some((i, j)) => write(true.toEnglish).writeOnNextLine(i + 1, j + 1)\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Iterable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def until(d1: Int, d2: Int): Iterator[(Int, Int)] = (0 until d1) X (0 until d2)\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._ \nimport scala.util.control._\n\nobject cf699B {\n def main (args:Array[String]) {\n var line = readLine();\n val ss = line.split(\" \");\n val n = ss(0).toInt;\n val m = ss(1).toInt;\n var a = new Array[String](1000 + 5);\n\n for (i <- 0 until n) {\n a(i) = readLine();\n }\n\n var r = new Array[Int](1000 + 5);\n for (i <- 0 until n) {\n r(i) = 0;\n }\n\n var c = new Array[Int](1000 + 5);\n for (i <- 0 until m) {\n c(i) = 0;\n }\n\n var cnt = 0;\n\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (a(i)(j) == '*') {\n cnt += 1;\n r(i) += 1;\n c(j) += 1;\n } \n }\n }\n \n\n var res = false;\n var plcx = 0;\n var plcy = 0;\n\n var ans = 0;\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n ans = cnt;\n if (a(i)(j) == '*') ans += 1;\n ans -= r(i);\n ans -= c(j);\n if (ans == 0) {\n res = true;\n plcx = i;\n plcy = j;\n }\n }\n }\n if (res == true) {\n println(\"YES\");\n println(plcx + 1 + \" \" + plcy + 1);\n } else {\n println(\"NO\");\n }\n }\n}"}, {"source_code": "import scala.io._\nimport java.util.Scanner\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport scala.collection.breakOut\n\nobject Main {\n def main(args: Array[String]) {\n case class Cell(r: Int, c: Int, ch: Char)\n\n val bfReader = new BufferedReader(new InputStreamReader(System.in))\n val scanner = new Scanner(bfReader.readLine())\n val (n, m) = (scanner.nextInt(), scanner.nextInt())\n val a = for(r <- 0 until n; (ch, c) <- bfReader.readLine().zipWithIndex) yield Cell(r, c, ch)\n\n def cellVal(c: Cell): Int = c.ch match { case '*' => 1; case '.' => 0 }\n\n val pr = a.groupBy{ _.r }.map{ case(r, xs) => (r, xs.map(cellVal).sum) }\n val pc = a.groupBy{ _.c }.map{ case(c, xs) => (c, xs.map(cellVal).sum) }\n\n val allBombsVal = a.map(cellVal).sum\n val validPositions = a.filter(x => x.ch == '*' && pr(x.r) + pc(x.c) - 1 == allBombsVal)\n\n if (validPositions.isEmpty) println(\"NO\")\n else {\n val x = validPositions(0)\n println(s\"YES\\n${x.r + 1} ${x.c + 1}\")\n }\n }\n}"}, {"source_code": "import scala.io._\nimport java.util.Scanner\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport scala.collection.breakOut\n\nobject Main {\n def main(args: Array[String]) {\n case class Cell(r: Int, c: Int, ch: Char)\n\n val bfReader = new BufferedReader(new InputStreamReader(System.in))\n val scanner = new Scanner(bfReader.readLine())\n val (n, m) = (scanner.nextInt(), scanner.nextInt())\n val a = for(r <- 0 until n; (ch, c) <- bfReader.readLine().zipWithIndex) yield Cell(r, c, ch)\n\n def cellVal(c: Cell): Int = if (c.ch == \"*\") 1 else 0\n\n val pr: Vector[Int] = a.groupBy{ _.r }.map{ case(r, xs) => (r, xs.map(cellVal).sum) }.to[Vector].sorted.map{ case (r, s) => s }\n val pc = a.groupBy{ _.c }.map{ case(c, xs) => (c, xs.map(cellVal).sum) }.to[Vector].sorted.map{ case (c, s) => s }\n\n val allBombsVal = a.map(cellVal).sum\n val validPositions = a.filter(x => pr(x.r) + pc(x.c) - cellVal(x) == allBombsVal)\n\n if (validPositions.isEmpty) println(\"NO\")\n else {\n val x = validPositions(0)\n println(s\"YES\\n${x.r + 1} ${x.c + 1}\")\n }\n }\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val lines = in.take(n).toList\n val linesBig = lines.indices.filter(i => lines(i).count(_ == '*') > 1).toList\n if (linesBig.length > 1) {\n println(\"NO\")\n }\n else if (linesBig.length == 1) {\n val y = linesBig.head\n val columnsBig = lines\n .indices\n .filter(i => i != y && lines(i).count(_ == '*') != 0)\n .map(i => lines(i).indexOf('*'))\n .distinct\n\n if (columnsBig.length > 1)\n println(\"NO\")\n else if (columnsBig.length == 1) {\n println(\"YES\")\n\n println(s\"${y + 1} ${columnsBig.head + 1}\")\n } else {\n println(\"YES\")\n println(s\"${y + 1} 1\")\n }\n } else {\n val columnsBig = lines\n .indices\n .filter(i => lines(i).count(_ == '*') != 0)\n .map(i => lines(i).indexOf('*'))\n .groupBy(i => i)\n .map(i => i._1 -> i._2.length)\n\n if (columnsBig.size > 2)\n println(\"NO\")\n else if (columnsBig.size == 2) {\n val one = columnsBig.find(_._2 == 1)\n if (one.isEmpty) {\n println(\"NO\")\n } else {\n val y = lines.indices.find(i => lines(i)(one.get._1) == '*').get\n val x = columnsBig.find(i => i._1 != one.get._1).get._1\n println(\"YES\")\n println(s\"${x + 1} ${y + 1}\")\n }\n } else if (columnsBig.size == 1) {\n println(\"YES\")\n println(s\"1 ${columnsBig.head._1 + 1}\")\n } else {\n println(\"YES\")\n println(\"1 1\")\n }\n\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val lines = in.take(n).toList\n val linesBig = lines.indices.filter(i => lines(i).count(_ == '*') > 1)\n if (linesBig.length > 1) {\n println(\"NO\")\n }\n else if (linesBig.length == 1) {\n val y = linesBig.head\n val columnsBig = lines\n .indices\n .filter(i => i != y && lines(i).count(_ == '*') != 0)\n .map(i => lines(i).indexOf('*'))\n .distinct\n\n if (columnsBig.length > 1)\n println(\"NO\")\n else if (columnsBig.length == 1) {\n println(\"YES\")\n println(s\"${columnsBig.head + 1} ${y + 1}\")\n } else {\n println(\"YES\")\n println(s\"1 ${y + 1}\")\n }\n } else {\n val columnsBig = lines\n .indices\n .filter(i => lines(i).count(_ == '*') != 0)\n .map(i => lines(i).indexOf('*'))\n .groupBy(i => i)\n .map(i => i._1 -> i._2.length)\n\n if (columnsBig.size > 2)\n println(\"NO\")\n else if (columnsBig.size == 2) {\n val one = columnsBig.find(_._2 == 1)\n if (one.isEmpty) {\n println(\"NO\")\n } else {\n val y = linesBig.find(i => lines(i)(one.get._1) == '*')\n val x = linesBig.find(_ != one.get).get\n println(\"YES\")\n println(s\"$x $y\")\n }\n } else if (columnsBig.size == 1) {\n println(\"YES\")\n println(s\"1 ${columnsBig.head._1 + 1}\")\n } else {\n println(\"YES\")\n println(\"1 1\")\n }\n\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val lines = in.take(n).toList\n val linesBig = lines.indices.filter(i => lines(i).count(_ == '*') > 1).toList\n if (linesBig.length > 1) {\n println(\"NO\")\n }\n else if (linesBig.length == 1) {\n val y = linesBig.head\n val columnsBig = lines\n .indices\n .filter(i => i != y && lines(i).count(_ == '*') != 0)\n .map(i => lines(i).indexOf('*'))\n .distinct\n\n if (columnsBig.length > 1)\n println(\"NO\")\n else if (columnsBig.length == 1) {\n println(\"YES\")\n\n println(s\"${y + 1} ${columnsBig.head + 1}\")\n } else {\n println(\"YES\")\n println(s\"${y + 1} 1\")\n }\n } else {\n val columnsBig = lines\n .indices\n .filter(i => lines(i).count(_ == '*') != 0)\n .map(i => lines(i).indexOf('*'))\n .groupBy(i => i)\n .map(i => i._1 -> i._2.length)\n\n if (columnsBig.size > 2)\n println(\"NO\")\n else if (columnsBig.size == 2) {\n val one = columnsBig.find(_._2 == 1)\n if (one.isEmpty) {\n println(\"NO\")\n } else {\n val y = lines.indices.find(i => lines(i)(one.get._1) == '*').get\n val x = columnsBig.find(i => i._1 != y).get\n println(\"YES\")\n println(s\"$y $x \")\n }\n } else if (columnsBig.size == 1) {\n println(\"YES\")\n println(s\"1 ${columnsBig.head._1 + 1}\")\n } else {\n println(\"YES\")\n println(\"1 1\")\n }\n\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val lines = in.take(n).toList\n val linesBig = lines.indices.filter(i => lines(i).count(_ == '*') > 1).toList\n if (linesBig.length > 1) {\n println(\"NO\")\n }\n else if (linesBig.length == 1) {\n val y = linesBig.head\n val columnsBig = lines\n .indices\n .filter(i => i != y && lines(i).count(_ == '*') != 0)\n .map(i => lines(i).indexOf('*'))\n .distinct\n\n if (columnsBig.length > 1)\n println(\"NO\")\n else if (columnsBig.length == 1) {\n println(\"YES\")\n\n println(s\"${y + 1} ${columnsBig.head + 1}\")\n } else {\n println(\"YES\")\n println(s\"${y + 1} 1\")\n }\n } else {\n val columnsBig = lines\n .indices\n .filter(i => lines(i).count(_ == '*') != 0)\n .map(i => lines(i).indexOf('*'))\n .groupBy(i => i)\n .map(i => i._1 -> i._2.length)\n\n if (columnsBig.size > 2)\n println(\"NO\")\n else if (columnsBig.size == 2) {\n val one = columnsBig.find(_._2 == 1)\n if (one.isEmpty) {\n println(\"NO\")\n } else {\n val y = lines.indices.find(i => lines(i)(one.get._1) == '*').get\n val x = columnsBig.find(i => i._1 != y).get._1\n println(\"YES\")\n println(s\"${y + 1} ${x + 1}\")\n }\n } else if (columnsBig.size == 1) {\n println(\"YES\")\n println(s\"1 ${columnsBig.head._1 + 1}\")\n } else {\n println(\"YES\")\n println(\"1 1\")\n }\n\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val lines = in.take(n).toList\n val linesBig = lines.indices.filter(i => lines(i).count(_ == '*') > 1)\n if (linesBig.length > 1) {\n println(\"NO\")\n }\n else if (linesBig.length == 1) {\n val y = linesBig.head\n val columnsBig = lines\n .indices\n .filter(i => i != y && lines(i).count(_ == '*') != 0)\n .map(i => lines(i).indexOf('*'))\n .distinct\n\n if (columnsBig.length > 1)\n println(\"NO\")\n else if (columnsBig.length == 1) {\n println(\"YES\")\n\n println(s\"${y + 1} ${columnsBig.head + 1}\")\n } else {\n println(\"YES\")\n println(s\"${y + 1} 1\")\n }\n } else {\n val columnsBig = lines\n .indices\n .filter(i => lines(i).count(_ == '*') != 0)\n .map(i => lines(i).indexOf('*'))\n .groupBy(i => i)\n .map(i => i._1 -> i._2.length)\n\n if (columnsBig.size > 2)\n println(\"NO\")\n else if (columnsBig.size == 2) {\n val one = columnsBig.find(_._2 == 1)\n if (one.isEmpty) {\n println(\"NO\")\n } else {\n val y = linesBig.find(i => lines(i)(one.get._1) == '*')\n val x = linesBig.find(_ != one.get).get\n println(\"YES\")\n println(s\"$y $x \")\n }\n } else if (columnsBig.size == 1) {\n println(\"YES\")\n println(s\"${columnsBig.head._1 + 1} 1\")\n } else {\n println(\"YES\")\n println(\"1 1\")\n }\n\n }\n\n}\n"}, {"source_code": "\nimport java.util\n\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 11 Aug 2016\n */\nobject B699 extends App {\n\n def max(map: mutable.Map[Int, util.ArrayList[Int]]): (Int, Int) = {\n var maxIndex = 0\n var maxValue = 0\n map foreach {\n case (key, value) => {\n if (value.size() > maxValue) {\n maxValue = value.size()\n maxIndex = key\n }\n }\n }\n if (maxValue > 1) {\n map foreach {\n case (key, value) => {\n if (key != maxIndex && value.size > 1) {\n maxValue = 0\n }\n }\n }\n }\n (maxIndex + 1, maxValue)\n }\n\n def solve() = {\n val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val maze: Array[Array[Char]] = Array.ofDim[Char](n, m)\n for (i <- 0 until n) {\n maze(i) = scala.io.StdIn.readLine().toCharArray\n }\n val rowList: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty\n val colList: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty\n var starCount = 0\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (maze(i)(j) == '*') {\n starCount += 1\n if (!rowList.contains(i)) {\n rowList += (i -> new util.ArrayList[Int]())\n }\n if (!colList.contains(j)) {\n colList += (j -> new util.ArrayList[Int]())\n }\n rowList(i).add(j)\n colList(j).add(i)\n }\n }\n }\n val (maxRowIndex, maxRowValue) = max(rowList)\n val (maxColIndex, maxColValue) = max(colList)\n\n if (maxRowValue + maxColValue - starCount >= 0) {\n println(\"YES\")\n if (maxRowValue != 1 && maxColValue != 1) {\n println(maxRowIndex + \" \" + maxColIndex)\n } else if (maxRowValue == 1 && maxColValue == 1) {\n if (starCount == 1) {\n println(maxRowIndex + \" \" + maxColIndex)\n } else {\n val row = colList(maxColIndex - 1).get(0)\n var rrow = 0\n rowList foreach {\n case (key, value) => {\n if (key != row && !colList(maxColIndex - 1).contains(key)) {\n rrow = key\n }\n }\n }\n val col = rowList(rrow).get(0)\n var ccol = 0\n colList foreach {\n case (key, value) => {\n if (key != col && !rowList(maxRowIndex - 1).contains(key)) {\n ccol = key\n }\n }\n }\n println((rrow + 1) + \" \" + (ccol + 1))\n }\n } else if (maxColValue != 1) {\n val row = colList(maxColIndex - 1).get(0)\n var rrow = 0\n rowList foreach {\n case (key, value) => {\n if (key != row && !colList(maxColIndex - 1).contains(key)) {\n rrow = key\n }\n }\n }\n println((rrow + 1) + \" \" + maxColIndex)\n } else {\n val col = rowList(maxRowIndex - 1).get(0)\n var ccol = 0\n colList foreach {\n case (key, value) => {\n if (key != col && !rowList(maxRowIndex - 1).contains(key)) {\n ccol = key\n }\n }\n }\n println(maxRowIndex + \" \" + (ccol + 1))\n }\n } else {\n println(\"NO\")\n }\n }\n\n solve()\n\n}\n"}, {"source_code": "\nimport java.util\n\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 11 Aug 2016\n */\nobject B699 extends App {\n\n def max(map: mutable.Map[Int, util.ArrayList[Int]]): (Int, Int) = {\n var maxIndex = 0\n var maxValue = 0\n map foreach {\n case (key, value) => {\n if (value.size() > maxValue) {\n maxValue = value.size()\n maxIndex = key\n }\n }\n }\n if (maxValue > 1) {\n map foreach {\n case (key, value) => {\n if (key != maxIndex && value.size > 1) {\n maxValue = 0\n }\n }\n }\n }\n (maxIndex + 1, maxValue)\n }\n\n def solve() = {\n val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val maze: Array[Array[Char]] = Array.ofDim[Char](n, m)\n for (i <- 0 until n) {\n maze(i) = scala.io.StdIn.readLine().toCharArray\n }\n val rowList: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty\n val colList: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty\n var starCount = 0\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (maze(i)(j) == '*') {\n starCount += 1\n if (!rowList.contains(i)) {\n rowList += (i -> new util.ArrayList[Int]())\n }\n if (!colList.contains(j)) {\n colList += (j -> new util.ArrayList[Int]())\n }\n rowList(i).add(j)\n colList(j).add(i)\n }\n }\n }\n val (maxRowIndex, maxRowValue) = max(rowList)\n val (maxColIndex, maxColValue) = max(colList)\n\n if (maxRowValue + maxColValue - starCount >= 0) {\n println(\"YES\")\n if ((maxRowValue == 1 && maxColValue == 1) || (maxRowValue != 1 && maxColValue != 1)) {\n println(maxRowIndex + \" \" + maxColIndex)\n } else if (maxColValue != 1) {\n var row = colList(maxColIndex-1).get(0)\n rowList foreach {\n case (key, value) => {\n if (key != row) {\n row = key\n }\n }\n }\n println((row + 1) + \" \" + maxColIndex)\n } else {\n var col = rowList(maxRowIndex-1).get(0)\n colList foreach {\n case (key, value) => {\n if (key != col) {\n col = key\n }\n }\n }\n println(maxRowIndex + \" \" + (col + 1))\n }\n } else {\n println(\"NO\")\n }\n }\n\n solve()\n\n}\n"}, {"source_code": "\nimport java.util\n\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 11 Aug 2016\n */\nobject B699 extends App {\n\n def max(map: mutable.Map[Int, util.ArrayList[Int]]): (Int, Int) = {\n var maxIndex = 0\n var maxValue = 0\n map foreach {\n case (key, value) => {\n if (value.size() > maxValue) {\n maxValue = value.size()\n maxIndex = key\n }\n }\n }\n if (maxValue > 1) {\n map foreach {\n case (key, value) => {\n if (key != maxIndex && value.size > 1) {\n maxValue = 0\n }\n }\n }\n }\n (maxIndex + 1, maxValue)\n }\n\n def solve() = {\n val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val maze: Array[Array[Char]] = Array.ofDim[Char](n, m)\n for (i <- 0 until n) {\n maze(i) = scala.io.StdIn.readLine().toCharArray\n }\n val rowList: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty\n val colList: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty\n var starCount = 0\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (maze(i)(j) == '*') {\n starCount += 1\n if (!rowList.contains(i)) {\n rowList += (i -> new util.ArrayList[Int]())\n }\n if (!colList.contains(j)) {\n colList += (j -> new util.ArrayList[Int]())\n }\n rowList(i).add(j)\n colList(j).add(i)\n }\n }\n }\n val (maxRowIndex, maxRowValue) = max(rowList)\n val (maxColIndex, maxColValue) = max(colList)\n\n if (maxRowValue + maxColValue - starCount >= 0) {\n println(\"YES\")\n println(maxRowIndex + \" \" + maxColIndex)\n\n } else {\n println(\"NO\")\n }\n }\n\n solve()\n\n}\n"}, {"source_code": "\nimport java.util\n\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 11 Aug 2016\n */\nobject B699 extends App {\n\n def max(map: mutable.Map[Int, util.ArrayList[Int]]): (Int, Int) = {\n var maxIndex = 0\n var maxValue = 0\n map foreach {\n case (key, value) => {\n if (value.size() > maxValue) {\n maxValue = value.size()\n maxIndex = key\n }\n }\n }\n if (maxValue > 1) {\n map foreach {\n case (key, value) => {\n if (key != maxIndex && value.size > 1) {\n maxValue = 0\n }\n }\n }\n }\n (maxIndex + 1, maxValue)\n }\n\n def solve() = {\n val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val maze: Array[Array[Char]] = Array.ofDim[Char](n, m)\n for (i <- 0 until n) {\n maze(i) = scala.io.StdIn.readLine().toCharArray\n }\n val rowList: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty\n val colList: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty\n var starCount = 0\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (maze(i)(j) == '*') {\n starCount += 1\n if (!rowList.contains(i)) {\n rowList += (i -> new util.ArrayList[Int]())\n }\n if (!colList.contains(j)) {\n colList += (j -> new util.ArrayList[Int]())\n }\n rowList(i).add(j)\n colList(j).add(i)\n }\n }\n }\n val (maxRowIndex, maxRowValue) = max(rowList)\n val (maxColIndex, maxColValue) = max(colList)\n\n if (maxRowValue + maxColValue - starCount >= 0) {\n println(\"YES\")\n if ((maxRowValue == 1 && maxColValue == 1) || (maxRowValue != 1 && maxColValue != 1)) {\n println(maxRowIndex + \" \" + maxColIndex)\n } else if (maxColValue != 1) {\n val row = colList(maxColIndex-1).get(0)\n var rrow = 0\n rowList foreach {\n case (key, value) => {\n if (key != row) {\n rrow = key\n }\n }\n }\n println((rrow + 1) + \" \" + maxColIndex)\n } else {\n val col = rowList(maxRowIndex-1).get(0)\n var ccol = 0\n colList foreach {\n case (key, value) => {\n if (key != col) {\n ccol = key\n }\n }\n }\n println(maxRowIndex + \" \" + (ccol + 1))\n }\n } else {\n println(\"NO\")\n }\n }\n\n solve()\n\n}\n"}, {"source_code": "\nimport java.util\n\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 11 Aug 2016\n */\nobject B699 extends App {\n\n def max(map: mutable.Map[Int, util.ArrayList[Int]]): (Int, Int) = {\n var maxIndex = 0\n var maxValue = 0\n map foreach {\n case (key, value) => {\n if (value.size() > maxValue) {\n maxValue = value.size()\n maxIndex = key\n }\n }\n }\n if (maxValue > 1) {\n map foreach {\n case (key, value) => {\n if (key != maxIndex && value.size > 1) {\n maxValue = 0\n }\n }\n }\n }\n (maxIndex + 1, maxValue)\n }\n\n def solve() = {\n val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val maze: Array[Array[Char]] = Array.ofDim[Char](n, m)\n for (i <- 0 until n) {\n maze(i) = scala.io.StdIn.readLine().toCharArray\n }\n val rowList: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty\n val colList: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty\n var starCount = 0\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (maze(i)(j) == '*') {\n starCount += 1\n if (!rowList.contains(i)) {\n rowList += (i -> new util.ArrayList[Int]())\n }\n if (!colList.contains(j)) {\n colList += (j -> new util.ArrayList[Int]())\n }\n rowList(i).add(j)\n colList(j).add(i)\n }\n }\n }\n val (maxRowIndex, maxRowValue) = max(rowList)\n val (maxColIndex, maxColValue) = max(colList)\n\n if (maxRowValue + maxColValue - starCount >= 0) {\n println(\"YES\")\n if ((maxRowValue == 1 && maxColValue == 1) || (maxRowValue != 1 && maxColValue != 1)) {\n println(maxRowIndex + \" \" + maxColIndex)\n } else if (maxColValue != 1) {\n var row = colList(maxColIndex-1).get(0)\n rowList foreach {\n case (key, value) => {\n if (key != row) {\n row = key\n }\n }\n }\n println((row + 1) + \" \" + maxColIndex)\n } else {\n var col = rowList(maxRowIndex-1).get(0)\n colList foreach {\n case (key, value) => {\n if (key != col) {\n col = key\n }\n }\n }\n println(maxRowValue + \" \" + (col + 1))\n }\n } else {\n println(\"NO\")\n }\n }\n\n solve()\n\n}\n"}, {"source_code": "\nimport java.util\n\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 11 Aug 2016\n */\nobject B699 extends App {\n\n def max(map: mutable.Map[Int, util.ArrayList[Int]]): (Int, Int) = {\n var maxIndex = 0\n var maxValue = 0\n map foreach {\n case (key, value) => {\n if (value.size() > maxValue) {\n maxValue = value.size()\n maxIndex = key\n }\n }\n }\n (maxIndex+1, maxValue)\n }\n\n def solve() = {\n val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val maze: Array[Array[Char]] = Array.ofDim[Char](n, m)\n for (i <- 0 until n) {\n maze(i) = scala.io.StdIn.readLine().toCharArray\n }\n val rowList: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty\n val colList: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty\n var starCount = 0\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (maze(i)(j) == '*') {\n starCount += 1\n if (!rowList.contains(i)) {\n rowList += (i -> new util.ArrayList[Int]())\n }\n if (!colList.contains(j)) {\n colList += (j -> new util.ArrayList[Int]())\n }\n rowList(i).add(j)\n colList(j).add(i)\n }\n }\n }\n val (maxRowIndex, maxRowValue) = max(rowList)\n val (maxColIndex, maxColValue) = max(colList)\n\n if (maxRowValue + maxColValue - starCount >= 0) {\n println(\"YES\")\n println(maxRowIndex + \" \" + maxColIndex)\n } else {\n println(\"NO\")\n }\n }\n\n solve()\n\n}\n"}, {"source_code": "\nimport java.util\n\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 11 Aug 2016\n */\nobject B699 extends App {\n\n def max(map: mutable.Map[Int, util.ArrayList[Int]]): (Int, Int) = {\n var maxIndex = 0\n var maxValue = 0\n map foreach {\n case (key, value) => {\n if (value.size() > maxValue) {\n maxValue = value.size()\n maxIndex = key\n }\n }\n }\n if (maxValue > 1) {\n map foreach {\n case (key, value) => {\n if (key != maxIndex && value.size > 1) {\n maxValue = 0\n }\n }\n }\n }\n (maxIndex + 1, maxValue)\n }\n\n def solve() = {\n val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val maze: Array[Array[Char]] = Array.ofDim[Char](n, m)\n for (i <- 0 until n) {\n maze(i) = scala.io.StdIn.readLine().toCharArray\n }\n val rowList: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty\n val colList: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty\n var starCount = 0\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (maze(i)(j) == '*') {\n starCount += 1\n if (!rowList.contains(i)) {\n rowList += (i -> new util.ArrayList[Int]())\n }\n if (!colList.contains(j)) {\n colList += (j -> new util.ArrayList[Int]())\n }\n rowList(i).add(j)\n colList(j).add(i)\n }\n }\n }\n val (maxRowIndex, maxRowValue) = max(rowList)\n val (maxColIndex, maxColValue) = max(colList)\n\n if (maxRowValue + maxColValue - starCount >= 0) {\n println(\"YES\")\n if (maxRowValue != 1 && maxColValue != 1) {\n println(maxRowIndex + \" \" + maxColIndex)\n } else if (maxRowValue == 1 && maxColValue == 1) {\n if (starCount == 1) {\n println(maxRowIndex + \" \" + maxColIndex)\n } else {\n val row = colList(maxColIndex - 1).get(0)\n var rrow = 0\n rowList foreach {\n case (key, value) => {\n if (key != row) {\n rrow = key\n }\n }\n }\n val col = rowList(rrow).get(0)\n var ccol = 0\n colList foreach {\n case (key, value) => {\n if (key != col) {\n ccol = key\n }\n }\n }\n println((rrow + 1) + \" \" + (ccol + 1))\n }\n } else if (maxColValue != 1) {\n val row = colList(maxColIndex - 1).get(0)\n var rrow = 0\n rowList foreach {\n case (key, value) => {\n if (key != row) {\n rrow = key\n }\n }\n }\n println((rrow + 1) + \" \" + maxColIndex)\n } else {\n val col = rowList(maxRowIndex - 1).get(0)\n var ccol = 0\n colList foreach {\n case (key, value) => {\n if (key != col) {\n ccol = key\n }\n }\n }\n println(maxRowIndex + \" \" + (ccol + 1))\n }\n } else {\n println(\"NO\")\n }\n }\n\n solve()\n\n}\n"}, {"source_code": "import scala.util.control.Breaks._\n\nobject main extends App{\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n var area = new Array[String](n)\n var rows = new Array[Int](n)\n var cols = new Array[Int](m)\n var count = 0\n for (i <- 0 until n) {\n \tarea(i) = readLine\n \trows(i) = area(i).toArray.foldLeft(0)((count: Int, char: Char) => if (char == '*') count + 1 else count)\n \tcount += rows(i)\n \tList.range(0, m).foreach((j: Int) => if (area(i)(j) == '*') cols(j) += 1 ) \n }\n println(\"Count \", count);\n val r = () => {\n \tvar result: Any = \"NO\";\n \tfor (i <- 0 until n) {\n\t \tfor (j <- 0 until m) {\n\t \t\tval res = rows(i) + cols(j)\n\t \t\tif (res >= count) {\n\t \t\t\tprintln(\"Count rows(i) \", rows(i), \"count cols(j)\", cols(j))\n\t \t\t\tresult = Array(i+1, j+1)\n\t \t\t}\t \t\t\n\t \t}\n \t}\n \tresult;\n } \n r() match {\n \tcase s: String => println(s)\n \tcase Array(x, y) => {\n \t\tprintln(\"YES\")\n \t\tprintln(\"%d %d\".format(x, y))\n \t}\n }\n}"}, {"source_code": "import scala.util.control.Breaks._\n\nobject main extends App{\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n var area = new Array[String](n)\n var rows = new Array[Int](n)\n var cols = new Array[Int](m)\n var count = 0\n for (i <- 0 until n) {\n \tarea(i) = readLine\n \trows(i) = area(i).toArray.foldLeft(0)((count: Int, char: Char) => if (char == '*') count + 1 else count)\n \tcount += rows(i)\n \tList.range(0, m).foreach((j: Int) => if (area(i)(j) == '*') cols(j) += 1 ) \n }\n val r = () => {\n \tvar result: Any = \"NO\";\n \tfor (i <- 0 until n) {\n\t \tfor (j <- 0 until m) {\n\t \t\tval res = rows(i) + cols(j)\n\t \t\tif (res >= count) {\n\t \t\t\tresult = Array(i+1, j+1)\n\t \t\t}\t \t\t\n\t \t}\n \t}\n \tresult;\n } \n r() match {\n \tcase s: String => println(s)\n \tcase Array(x, y) => {\n \t\tprintln(\"YES\")\n \t\tprintln(\"%d %d\".format(x, y))\n \t}\n }\n}"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _699B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val n, m = read[Int]\n val map = read[Vector, String](n)\n\n val bombs = for {\n r <- 0 until n\n c <- 0 until m\n if map(r)(c) == '*'\n } yield (r, c)\n\n val ans = if (bombs.length >= n+m) {\n None\n } else if (bombs.isEmpty) {\n Some(0 -> 0)\n } else {\n val rb = bombs.groupBy(_._1) collect {\n case (r, bs) if bs.length > 1 => r\n }\n\n val rc = bombs.groupBy(_._2) collect {\n case (c, bs) if bs.length > 1 => c\n }\n\n val (cx, cy) = (rb.headOption getOrElse 0) -> (rc.headOption getOrElse 0)\n when(bombs forall {case (i, j) => cx == i || cy == j}) {\n cx -> cy\n }\n }\n\n ans.map{case (i, j) => (i+1) -> (j+1)} match {\n case None => write(false.toYesNo)\n case Some((i, j)) =>\n write(true.toYesNo).writeLine().write(i, j)\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n def X[B](bs: Iterable[B]): Iterable[(A, B)] = for {a <- s; b <- bs} yield (a, b)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toYesNo = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeLine(obj: Any*): this.type = {\n if (obj.isEmpty) printer.println() else obj foreach printer.println\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "12a768b502ddb07798830c9728fba5c4"} {"source_code": "/**\n * @author netman\n */\n\n\nimport java.io._\nimport scala._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\n\nobject HelloWorld {\n\n class InputReader(reader: BufferedReader) {\n \n var tokenizer: StringTokenizer = null;\n \n def this(stream: InputStream) = {\n this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));\n }\n \n def this(f: File) = {\n this(new BufferedReader(new FileReader(f), (1 << 20)));\n }\n \n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine());\n }\n return tokenizer.nextToken();\n }\n \n def nextInt(): Int = next().toInt\n \n def nextDouble(): Double = next().toDouble\n \n def close() = reader.close();\n }\n \n class OutputWriter(writer: PrintWriter) {\n def this(stream: OutputStream) {\n this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));\n }\n \n def this(f: File) = {\n this(new PrintWriter(new BufferedWriter(new FileWriter(f))));\n }\n \n def print(x: Any) = writer.print(x);\n \n def println(x: Any) = writer.println(x);\n \n def close() = writer.close();\n }\n \n \n val in = new InputReader(System.in)\n val out = new OutputWriter(System.out)\n \n def main(args: Array[String]): Unit = {\n val (n, d) = (in.nextInt, in.nextInt - 1)\n \n var a = new Array[(Int, Int)](n)\n \n for (i <- 0 until n) {\n a(i) = (in.nextInt, in.nextInt)\n }\n \n a = a.sortBy(_._1)\n \n var l = 0\n var curSum = 0L\n var res = 0L\n \n //for (i <- 0 until n) {\n // out.println(a(i)._1 + \" \" + a(i)._2)\n //}\n \n for (i <- 0 until n) {\n curSum += a(i)._2\n while (l < i && a(l)._1 < a(i)._1 - d) {\n curSum -= a(l)._2\n l += 1\n }\n res = math.max(res, curSum)\n }\n \n out.println(res)\n \n out.close\n }\n}", "positive_code": [{"source_code": "object Solution {\n\n def main(args: Array[String]) {\n val nd = readLine().split(\" \").map(x => x.toInt)\n val (n, d) = (nd(0), nd(1))\n val friends =\n (0 until n).map(_ => {\n val mf = readLine().split(\" \").map(x => x.toLong)\n (mf(0), mf(1))\n }).sortBy(mf => mf._1)\n var i = 0\n var j = 0\n var res = 0L\n var current = friends(i)._2.toLong\n while (i < n) {\n val ok = friends(j)._1 - friends(i)._1 < d\n res = Math.max(res, if (ok) current else 0)\n if (ok && j < n - 1) {\n j += 1\n current += friends(j)._2\n }\n else {\n current -= friends(i)._2\n i += 1\n }\n }\n println(res)\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(nn, d) = readLine().split(\" \").map(_.toLong)\n val n: Int = nn.toInt\n\n val A = Array.ofDim[(Long, Long)](n)\n\n var totalFriendship = Long.MinValue\n\n def init(idx: Int, in: (Long, Long)): Unit = {\n A(idx) = in\n }\n\n for (i <- 0 until n) {\n val Array(m, s) = readLine().split(\" \").map(_.toLong)\n init(i, (m, s))\n }\n\n val sorted = A.sortBy(_._1)\n// println(sorted.mkString(\" \"))\n\n var left = 0\n var right = 1\n\n var max = sorted.map(_._2).max\n var current: Long = sorted(left)._2\n\n while (right < n) {\n while (left < right && sorted(right)._1 - sorted(left)._1 >= d) {\n current -= sorted(left)._2\n left += 1\n }\n\n current += sorted(right)._2\n right += 1\n\n max = Math.max(max, current)\n }\n\n println(max)\n\n\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, d) = in.next().split(\" \").map(_.toInt)\n val data = (1 to n).map{_ =>\n val Array(money, friendship) = in.next().split(\" \").map(_.toLong)\n (money, friendship)\n }.sorted\n\n println(data.indices.foldLeft(0l, 0l, -1) {\n case((max, maxSoFar, -1), el) =>\n val element = data(el)\n (element._2, element._2, el)\n case((max, maxSoFar, i), el) if data(i)._1 + d > data(el)._1 =>\n val nMaxSoFar = maxSoFar + data(el)._2\n (Math.max(max, nMaxSoFar), nMaxSoFar, i)\n case((max, maxSoFar, i), el) =>\n val throwAway = (i until el).takeWhile(k => data(k)._1 + d <= data(el)._1).map(j => data(j)._2)\n val nMaxSoFar = maxSoFar - throwAway.sum + data(el)._2\n (Math.max(max, nMaxSoFar), nMaxSoFar, i + throwAway.length)\n }._1)\n\n\n}"}, {"source_code": "object KefaAndCompany {\n def main(args : Array[String]) : Unit = {\n val sc = new java.util.Scanner(System.in)\n val (n,d) = (sc.nextInt(), sc.nextInt())\n var a = new Array[(Int,Int)](n)\n \n for( i <- 0 until n )\n a(i) = (sc.nextInt(), sc.nextInt())\n a = a.sortBy(_._1)\n \n var best = 0L\n var currentTotal = 0L\n var low = 0 \n \n for( i <- 0 until n ){\n currentTotal += a(i)._2\n while(low < i && math.abs(a(low)._1 - a(i)._1) >= d){\n currentTotal -= a(low)._2\n low += 1\n }\n best = math.max(currentTotal, best)\n }\n \n println(best) \n } \n}"}, {"source_code": "object B580 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, d) = readInts(2)\n val in = Array.fill(n)(readLongs(2)).map(arr => (arr(0), arr(1))).sortBy(_._1)\n var res = 0L\n var curr = 0L\n var l = 0\n for(i <- 0 until n) {\n curr += in(i)._2\n while(i > l && in(l)._1 < in(i)._1 - d + 1) {\n curr -= in(l)._2\n l += 1\n }\n res = math.max(res, curr)\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object _580B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val n, d = io.read[Int]\n val (money, friendship) = io.read[Vector, (Int, Int)](n).sorted.unzip\n\n val checks = validIntervals(n){case (l, r) => money(r) - money(l) < d}\n val friendshipPrefixSum = friendship.scanLeft(0L)(_ + _)\n\n val ans = checks.map({case (l, r) => friendshipPrefixSum(r+1) - friendshipPrefixSum(l)})\n\n io.write(ans.max)\n }\n\n def validIntervals(n: Int)(f: (Int, Int) => Boolean): Iterator[(Int, Int)] = {\n val it = new Iterator[Option[(Int, Int)]] {\n var l, r = 0\n override def hasNext = r < n\n override def next() = {\n if(f(l, r)) {\n r += 1\n Some((l, r - 1))\n } else {\n if(l < r) l += 1 else r += 1\n None\n }\n }\n }\n it.flatten\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _580B extends CodeForcesApp[Long]({scanner => import scanner._\n val (n, d) = (nextInt, nextInt)\n val friends = IndexedSeq.fill(n)((nextInt, nextInt)).sorted\n\n var (sum, ans) = (0L, 0L)\n\n def isOk(x: Int, y: Int) = (friends(x)._1 - friends(y)._1).abs < d\n\n @tailrec\n def solve(l: Int, r: Int): Long = if (r == n) {\n ans\n } else if(isOk(l, r)) {\n sum += friends(r)._2\n ans = ans max sum\n solve(l, r+1)\n } else {\n sum -= friends(l)._2\n solve(l+1, r)\n }\n\n solve(0, 0)\n})\n/********************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n"}], "negative_code": [{"source_code": "/**\n * @author netman\n */\n\n\nimport java.io._\nimport scala._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\n\nobject HelloWorld {\n\n class InputReader(reader: BufferedReader) {\n \n var tokenizer: StringTokenizer = null;\n \n def this(stream: InputStream) = {\n this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));\n }\n \n def this(f: File) = {\n this(new BufferedReader(new FileReader(f), (1 << 20)));\n }\n \n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine());\n }\n return tokenizer.nextToken();\n }\n \n def nextInt(): Int = next().toInt\n \n def nextDouble(): Double = next().toDouble\n \n def close() = reader.close();\n }\n \n class OutputWriter(writer: PrintWriter) {\n def this(stream: OutputStream) {\n this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));\n }\n \n def this(f: File) = {\n this(new PrintWriter(new BufferedWriter(new FileWriter(f))));\n }\n \n def print(x: Any) = writer.print(x);\n \n def println(x: Any) = writer.println(x);\n \n def close() = writer.close();\n }\n \n \n val in = new InputReader(System.in)\n val out = new OutputWriter(System.out)\n \n def main(args: Array[String]): Unit = {\n val (n, d) = (in.nextInt, in.nextInt)\n \n var a = new Array[(Int, Int)](n)\n \n for (i <- 0 until n) {\n a(i) = (in.nextInt, in.nextInt)\n }\n \n a = a.sortBy(_._1)\n \n var l = 0\n var curSum = 0L\n var res = 0L\n \n //for (i <- 0 until n) {\n // out.println(a(i)._1 + \" \" + a(i)._2)\n //}\n \n for (i <- 0 until n) {\n curSum += a(i)._2\n while (l < i && a(l)._1 < a(i)._1 - d) {\n curSum -= a(l)._2\n l += 1\n }\n res = math.max(res, curSum)\n }\n \n out.println(res)\n \n out.close\n }\n}"}, {"source_code": "object Solution {\n\n def main(args: Array[String]) {\n val nd = readLine().split(\" \").map(x => x.toInt)\n val (n, d) = (nd(0), nd(1))\n val friends =\n (0 until n).map(_ => {\n val mf = readLine().split(\" \").map(x => x.toInt)\n (mf(0), mf(1))\n }).sortBy(mf => mf._1)\n var i = 0\n var j = 0\n var res = 0\n var current = friends(i)._2\n while (i < n) {\n val ok = friends(j)._1 - friends(i)._1 <= d\n res = Math.max(res, if (ok) current else 0)\n if (ok && j < n - 1) {\n j += 1\n current += friends(j)._2\n }\n else {\n current -= friends(i)._2\n i += 1\n }\n }\n println(res)\n }\n}"}, {"source_code": "object Solution {\n\n def main(args: Array[String]) {\n val nd = readLine().split(\" \").map(x => x.toInt)\n val (n, d) = (nd(0), nd(1))\n val friends =\n (0 until n).map(_ => {\n val mf = readLine().split(\" \").map(x => x.toInt)\n (mf(0), mf(1))\n }).sortBy(mf => mf._1)\n var i = 0\n var j = 0\n var res = 0L\n var current = friends(i)._2.toLong\n while (i < n) {\n val ok = friends(j)._1 - friends(i)._1 <= d\n res = Math.max(res, if (ok) current else 0)\n if (ok && j < n - 1) {\n j += 1\n current += friends(j)._2\n }\n else {\n current -= friends(i)._2\n i += 1\n }\n }\n println(res)\n }\n}"}, {"source_code": "object Solution {\n\n def main(args: Array[String]) {\n val nd = readLine().split(\" \").map(x => x.toInt)\n val (n, d) = (nd(0), nd(1))\n val friends =\n (0 until n).map(_ => {\n val mf = readLine().split(\" \").map(x => x.toLong)\n (mf(0), mf(1))\n }).sortBy(mf => mf._1)\n var i = 0\n var j = 0\n var res = 0L\n var current = friends(i)._2.toLong\n while (i < n) {\n val ok = friends(j)._1 - friends(i)._1 <= d\n res = Math.max(res, if (ok) current else 0)\n if (ok && j < n - 1) {\n j += 1\n current += friends(j)._2\n }\n else {\n current -= friends(i)._2\n i += 1\n }\n }\n println(res)\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, d) = in.next().split(\" \").map(_.toInt)\n val data = (1 to n).map{_ =>\n val Array(money, friendship) = in.next().split(\" \").map(_.toInt)\n (money, friendship)\n }.sorted\n\n println(data.indices.foldLeft(0, 0, -1) {\n case((max, maxSoFar, -1), el) =>\n val element = data(el)\n (element._2, element._2, el)\n case((max, maxSoFar, i), el) if data(i)._1 + d > data(el)._1 =>\n val nMaxSoFar = maxSoFar + data(el)._2\n (Math.max(max, nMaxSoFar), nMaxSoFar, i)\n case((max, maxSoFar, i), el) =>\n val throwAway = (i until el).takeWhile(k => data(k)._1 + d <= data(el)._1).map(j => data(j)._2)\n val nMaxSoFar = maxSoFar - throwAway.sum + data(el)._2\n (Math.max(max, nMaxSoFar), nMaxSoFar, i + throwAway.length)\n }._1)\n\n\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, d) = in.next().split(\" \").map(_.toInt)\n val data = (1 to n).map{_ =>\n val Array(money, friendship) = in.next().split(\" \").map(_.toInt)\n (money, friendship)\n }.sorted\n\n println(data.indices.foldLeft(0l, 0l, -1) {\n case((max, maxSoFar, -1), el) =>\n val element = data(el)\n (element._2, element._2, el)\n case((max, maxSoFar, i), el) if data(i)._1 + d > data(el)._1 =>\n val nMaxSoFar = maxSoFar + data(el)._2\n (Math.max(max, nMaxSoFar), nMaxSoFar, i)\n case((max, maxSoFar, i), el) =>\n val throwAway = (i until el).takeWhile(k => data(k)._1 + d <= data(el)._1).map(j => data(j)._2)\n val nMaxSoFar = maxSoFar - throwAway.sum + data(el)._2\n (Math.max(max, nMaxSoFar), nMaxSoFar, i + throwAway.length)\n }._1)\n\n\n}"}, {"source_code": "object B580 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, d) = readInts(2)\n val in = Array.fill(n)(readLongs(2)).map(arr => (arr(0), arr(1))).sorted\n val m = in.map(_._1)\n val s = Array(0L) ++ in.map(_._2)\n for(i <- 1 to n) {\n s(i) += s(i-1)\n }\n var res = 0L\n import scala.collection.Searching._\n for(i <- 0 until n) {\n // i - search for just less than in(i) + d\n val lastInd = m.search(m(i) + d - 1) match {\n case InsertionPoint(idx) =>\n idx\n case Found(idx) =>\n idx+1\n }\n res = math.max(res, s(lastInd) - s(i))\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object B580 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, d) = readInts(2)\n val in = Array.fill(n)(readLongs(2)).map(arr => (arr(0), arr(1))).sorted\n var res = 0L\n var curr = 0L\n var l = 0\n for(i <- 0 until n) {\n curr += in(i)._2\n while(i > l && in(l)._1 < in(i)._1 - d) {\n curr -= in(l)._2\n l += 1\n }\n res = math.max(res, curr)\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object B508 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val num = read.toCharArray\n val evens = ('0' to '8' by 2).flatMap{x =>\n val first = num.indexWhere(_ == x)\n val last = num.lastIndexWhere(_ == x)\n val set = collection.mutable.Set.empty[Int]\n if(first != -1) set.add(first)\n if(last != -1) set.add(last)\n set\n }\n\n if(evens.isEmpty) {\n println(\"-1\")\n } else {\n var res = \"0\"\n for(i <- evens) {\n val n = num\n var temp = n(i)\n n(i) = n(n.length-1)\n n(n.length-1) = temp\n\n val curr = new String(n)\n if(curr.compareTo(res) > 0)\n res = curr\n\n temp = n(i)\n n(i) = n(n.length-1)\n n(n.length-1) = temp\n }\n println(res)\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _580B extends CodeForcesApp[Long]({scanner => import scanner._\n val (n, d) = (nextInt, nextInt)\n val friends = List.fill(n)((nextInt, nextInt))\n\n def solve(fs: List[(Int, Int)]): Long = fs match {\n case Nil => 0L\n case (m1, _) :: _ =>\n val (pre, post) = fs span {case (money, _) => money - m1 < d}\n val curr = pre.map(_._2.toLong).sum\n curr max solve(post)\n }\n solve(friends.sorted)\n}) {\n override def format(result: Result) = super.format(result)\n}\n/****************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n import scala.collection.mutable.{Map => Dict}\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0\n final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _580B extends CodeForcesApp[Long]({scanner => import scanner._\n val (n, d) = (nextInt, nextInt)\n val friends = List.fill(n)((nextInt, nextInt))\n\n var (l, r, sum, ans) = (0, 0, 0L, 0L)\n\n def isOk(x: Int, y: Int) = (friends(x)._1 - friends(y)._1).abs < d\n\n while(r < n) {\n while(l < n && !isOk(l, r)) {\n sum -= friends(l)._2\n l += 1\n }\n\n while(l < n && r < n && isOk(l, r)) {\n sum += friends(r)._2\n r += 1\n }\n\n ans = ans max sum\n }\n\n ans\n\n}) {\n override def format(result: Result) = super.format(result)\n}\n/********************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n"}, {"source_code": "object _580B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val n, d = io.read[Int]\n val (money, friendship) = io.read[Vector, (Int, Int)](n).sorted.unzip\n\n val checks = validIntervals(n){case (l, r) => money(r) - money(l) < d}\n val friendshipPrefixSum = friendship.scanLeft(0)(_ + _)\n\n val ans = checks.map({case (l, r) => friendshipPrefixSum(r+1) - friendshipPrefixSum(l)})\n\n io.write(ans.max)\n }\n\n def validIntervals(n: Int)(f: (Int, Int) => Boolean): Iterator[(Int, Int)] = {\n val it = new Iterator[Option[(Int, Int)]] {\n var l, r = 0\n override def hasNext = r < n\n override def next() = {\n if(f(l, r)) {\n r += 1\n Some((l, r - 1))\n } else {\n if(l < r) l += 1 else r += 1\n None\n }\n }\n }\n it.flatten\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(nn, d) = readLine().split(\" \").map(_.toLong)\n val n: Int = nn.toInt\n\n val Max = Array.ofDim[Long](n, n)\n val Min = Array.ofDim[Long](n, n)\n val FF = Array.ofDim[Long](n)\n\n var maxFriendship = Long.MinValue\n\n def init(idx: Int, in: (Long, Long)): Unit = {\n Max(idx)(idx) = in._1\n Min(idx)(idx) = in._1\n if (idx > 0) FF(idx) = FF(idx - 1) + in._2 else FF(idx) = in._2\n maxFriendship = Math.max(maxFriendship, in._2)\n }\n\n def friendship(a: Int, b: Int): Long = {\n if (a == 0) FF(b)\n else FF(b) - FF(a - 1)\n }\n\n for (i <- 0 until n) {\n val Array(m, s) = readLine().split(\" \").map(_.toLong)\n init(i, (m, s))\n }\n\n var row = 0\n var col = 1\n\n while (row < n && col < n) {\n val leftMax = Max(row)(col - 1)\n val leftMin = Min(row)(col - 1)\n val current = Max(col)(col)\n\n val max = Math.max(leftMax, current)\n val min = Math.min(leftMin, current)\n\n Max(row)(col) = max\n Min(row)(col) = min\n\n if (max - min < d) {\n// println(row + \" \" + col + \" \" + friendship(row, col))\n maxFriendship = Math.max(maxFriendship, friendship(row, col))\n }\n\n col += 1\n if (col >= n) {\n row += 1\n col = row + 1\n }\n }\n\n println(maxFriendship)\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(nn, d) = readLine().split(\" \").map(_.toLong)\n val n: Int = nn.toInt\n\n val FF = Array.ofDim[Long](n)\n val A = Array.ofDim[Long](n)\n\n var maxFriendship = Long.MinValue\n\n def init(idx: Int, in: (Long, Long)): Unit = {\n A(idx) = in._1\n\n if (idx > 0) {\n FF(idx) = FF(idx - 1) + in._2\n } else {\n FF(idx) = in._2\n }\n\n maxFriendship = Math.max(maxFriendship, in._2)\n }\n\n def friendship(a: Int, b: Int): Long = {\n if (a == 0) FF(b)\n else FF(b) - FF(a - 1)\n }\n\n for (i <- 0 until n) {\n val Array(m, s) = readLine().split(\" \").map(_.toLong)\n init(i, (m, s))\n }\n\n var minMoney = Long.MaxValue\n var maxMoney = Long.MinValue\n\n for {\n row <- 0 until n\n } {\n var i = row\n minMoney = Long.MaxValue\n maxMoney = Long.MinValue\n while (i < n) {\n minMoney = Math.min(minMoney, A(i))\n maxMoney = Math.max(maxMoney, A(i))\n if (maxMoney - minMoney < d) {\n maxFriendship = Math.max(maxFriendship, friendship(row, i))\n }\n\n i += 1\n }\n }\n\n println(maxFriendship)\n}\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(nn, d) = readLine().split(\" \").map(_.toLong)\n val n: Int = nn.toInt\n\n val FF = Array.ofDim[Long](n)\n val A = Array.ofDim[Long](n)\n val F = Array.ofDim[Long](n)\n\n var maxFriendship = Long.MinValue\n\n def init(idx: Int, in: (Long, Long)): Unit = {\n A(idx) = in._1\n F(idx) = in._2\n\n if (idx > 0) {\n FF(idx) = FF(idx - 1) + in._2\n } else {\n FF(idx) = in._2\n }\n\n maxFriendship = Math.max(maxFriendship, in._2)\n }\n\n def friendship(a: Int, b: Int): Long = {\n if (a == 0) FF(b)\n else FF(b) - FF(a - 1)\n }\n\n for (i <- 0 until n) {\n val Array(m, s) = readLine().split(\" \").map(_.toLong)\n init(i, (m, s))\n }\n\n// if (n == 1) {\n// println(FF(0))\n// } else {\n// var minMoney = Long.MaxValue\n// var maxMoney = Long.MinValue\n//\n// for {\n// row <- 0 until n\n// } {\n// var i = row\n// minMoney = Long.MaxValue\n// maxMoney = Long.MinValue\n// while (i < n) {\n// minMoney = Math.min(minMoney, A(i))\n// maxMoney = Math.max(maxMoney, A(i))\n// if (maxMoney - minMoney < d) {\n// maxFriendship = Math.max(maxFriendship, friendship(row, i))\n// }\n//\n// i += 1\n// }\n// }\n//\n// println(maxFriendship)\n// }\n\n for {\n i <- 0 until n\n j <- i until n\n } {\n val sub = A.slice(i, j + 1)\n if (sub.max - sub.min <= d) {\n val friendSub = F.slice(i, j + 1)\n maxFriendship = Math.max(maxFriendship, friendSub.sum)\n }\n }\n\n println(maxFriendship)\n}\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(nn, d) = readLine().split(\" \").map(_.toLong)\n val n: Int = nn.toInt\n\n val FF = Array.ofDim[Long](n)\n val A = Array.ofDim[Long](n)\n val F = Array.ofDim[Long](n)\n\n var maxFriendship = Long.MinValue\n\n def init(idx: Int, in: (Long, Long)): Unit = {\n A(idx) = in._1\n F(idx) = in._2\n\n if (idx > 0) {\n FF(idx) = FF(idx - 1) + in._2\n } else {\n FF(idx) = in._2\n }\n\n maxFriendship = Math.max(maxFriendship, in._2)\n }\n\n def friendship(a: Int, b: Int): Long = {\n if (a == 0) FF(b)\n else FF(b) - FF(a - 1)\n }\n\n for (i <- 0 until n) {\n val Array(m, s) = readLine().split(\" \").map(_.toLong)\n init(i, (m, s))\n }\n\n// if (n == 1) {\n// println(FF(0))\n// } else {\n// var minMoney = Long.MaxValue\n// var maxMoney = Long.MinValue\n//\n// for {\n// row <- 0 until n\n// } {\n// var i = row\n// minMoney = Long.MaxValue\n// maxMoney = Long.MinValue\n// while (i < n) {\n// minMoney = Math.min(minMoney, A(i))\n// maxMoney = Math.max(maxMoney, A(i))\n// if (maxMoney - minMoney < d) {\n// maxFriendship = Math.max(maxFriendship, friendship(row, i))\n// }\n//\n// i += 1\n// }\n// }\n//\n// println(maxFriendship)\n// }\n\n for {\n i <- 0 until n\n j <- i until n\n } {\n val sub = A.slice(i, j + 1)\n if (sub.max - sub.min < d) {\n val friendSub = F.slice(i, j + 1)\n maxFriendship = Math.max(maxFriendship, friendSub.sum)\n }\n }\n\n println(maxFriendship)\n}\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(nn, d) = readLine().split(\" \").map(_.toLong)\n val n: Int = nn.toInt\n\n val FF = Array.ofDim[Long](n)\n val A = Array.ofDim[Long](n)\n\n var maxFriendship = Long.MinValue\n\n def init(idx: Int, in: (Long, Long)): Unit = {\n A(idx) = in._1\n\n if (idx > 0) {\n FF(idx) = FF(idx - 1) + in._2\n } else {\n FF(idx) = in._2\n }\n\n maxFriendship = Math.max(maxFriendship, in._2)\n }\n\n def friendship(a: Int, b: Int): Long = {\n if (a == 0) FF(b)\n else FF(b) - FF(a - 1)\n }\n\n for (i <- 0 until n) {\n val Array(m, s) = readLine().split(\" \").map(_.toLong)\n init(i, (m, s))\n }\n\n// if (n == 1) {\n// println(FF(0))\n// } else {\n// var minMoney = Long.MaxValue\n// var maxMoney = Long.MinValue\n//\n// for {\n// row <- 0 until n\n// } {\n// var i = row\n// minMoney = Long.MaxValue\n// maxMoney = Long.MinValue\n// while (i < n) {\n// minMoney = Math.min(minMoney, A(i))\n// maxMoney = Math.max(maxMoney, A(i))\n// if (maxMoney - minMoney < d) {\n// maxFriendship = Math.max(maxFriendship, friendship(row, i))\n// }\n//\n// i += 1\n// }\n// }\n//\n// println(maxFriendship)\n// }\n\n for {\n i <- 0 until n\n j <- i until n\n } {\n val sub = A.slice(i, j + 1)\n if (sub.max - sub.min < d) {\n maxFriendship = Math.max(maxFriendship, friendship(i, j))\n }\n }\n\n println(maxFriendship)\n}\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(nn, d) = readLine().split(\" \").map(_.toLong)\n val n: Int = nn.toInt\n\n val FF = Array.ofDim[Long](n)\n val A = Array.ofDim[Long](n)\n\n var maxFriendship = Long.MinValue\n\n def init(idx: Int, in: (Long, Long)): Unit = {\n A(idx) = in._1\n\n if (idx > 0) {\n FF(idx) = FF(idx - 1) + in._2\n } else {\n FF(idx) = in._2\n }\n\n maxFriendship = Math.max(maxFriendship, in._2)\n }\n\n def friendship(a: Int, b: Int): Long = {\n if (a == 0) FF(b)\n else FF(b) - FF(a - 1)\n }\n\n for (i <- 0 until n) {\n val Array(m, s) = readLine().split(\" \").map(_.toLong)\n init(i, (m, s))\n }\n\n if (n == 1) {\n println(FF(0))\n } else {\n var minMoney = Long.MaxValue\n var maxMoney = Long.MinValue\n\n for {\n row <- 0 until n\n } {\n var i = row\n minMoney = Long.MaxValue\n maxMoney = Long.MinValue\n while (i < n) {\n minMoney = Math.min(minMoney, A(i))\n maxMoney = Math.max(maxMoney, A(i))\n if (maxMoney - minMoney < d) {\n maxFriendship = Math.max(maxFriendship, friendship(row, i))\n }\n\n i += 1\n }\n }\n\n println(maxFriendship)\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(nn, d) = readLine().split(\" \").map(_.toLong)\n val n: Int = nn.toInt\n\n val Max = Array.ofDim[Long](n, n)\n val Min = Array.ofDim[Long](n, n)\n val FF = Array.ofDim[Long](n)\n\n var maxFriendship = Long.MinValue\n\n def init(idx: Int, in: (Long, Long)): Unit = {\n Max(idx)(idx) = in._1\n Min(idx)(idx) = in._1\n if (idx > 0) FF(idx) = FF(idx - 1) + in._2 else FF(idx) = in._2\n maxFriendship = Math.max(maxFriendship, in._2)\n }\n\n def friendship(a: Int, b: Int): Long = {\n if (a == 0) FF(b)\n else {\n val end = FF(b)\n val start = FF(a - 1)\n\n end - start\n\n }\n }\n\n for (i <- 0 until n.toInt) {\n val Array(m, s) = readLine().split(\" \").map(_.toLong)\n init(i, (m, s))\n }\n\n for {\n offset <- 1 until n\n row <- 0 until n - offset\n } {\n val col = row + offset\n\n val leftMax = Max(row)(col - 1)\n val leftMin = Min(row)(col - 1)\n val rightMax = Max(row + 1)(col)\n val rightMin = Min(row + 1)(col)\n\n val max = Math.max(leftMax, rightMax)\n val min = Math.min(leftMin, rightMin)\n\n Max(row)(col) = max\n Min(row)(col) = min\n\n if (max - min < d) {\n// println(row + \" \" + col + \" \" + friendship(row, col))\n maxFriendship = Math.max(maxFriendship, friendship(row, col))\n }\n }\n\n println(maxFriendship)\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(nn, d) = readLine().split(\" \").map(_.toLong)\n val n: Int = nn.toInt\n\n val FF = Array.ofDim[Long](n)\n val A = Array.ofDim[Long](n)\n val F = Array.ofDim[Long](n)\n\n var maxFriendship = Long.MinValue\n\n def init(idx: Int, in: (Long, Long)): Unit = {\n A(idx) = in._1\n F(idx) = in._2\n\n if (idx > 0) {\n FF(idx) = FF(idx - 1) + in._2\n } else {\n FF(idx) = in._2\n }\n\n// maxFriendship = Math.max(maxFriendship, in._2)\n }\n\n def friendship(a: Int, b: Int): Long = {\n if (a == 0) FF(b)\n else FF(b) - FF(a - 1)\n }\n\n for (i <- 0 until n) {\n val Array(m, s) = readLine().split(\" \").map(_.toLong)\n init(i, (m, s))\n }\n\n// if (n == 1) {\n// println(FF(0))\n// } else {\n// var minMoney = Long.MaxValue\n// var maxMoney = Long.MinValue\n//\n// for {\n// row <- 0 until n\n// } {\n// var i = row\n// minMoney = Long.MaxValue\n// maxMoney = Long.MinValue\n// while (i < n) {\n// minMoney = Math.min(minMoney, A(i))\n// maxMoney = Math.max(maxMoney, A(i))\n// if (maxMoney - minMoney < d) {\n// maxFriendship = Math.max(maxFriendship, friendship(row, i))\n// }\n//\n// i += 1\n// }\n// }\n//\n// println(maxFriendship)\n// }\n\n for {\n i <- 0 until n\n j <- i until n\n } {\n val sub = A.slice(i, j + 1)\n if (sub.max - sub.min < d) {\n val friendSub = F.slice(i, j + 1)\n maxFriendship = Math.max(maxFriendship, friendSub.sum)\n }\n }\n\n println(maxFriendship)\n}\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(nn, d) = readLine().split(\" \").map(_.toLong)\n val n: Int = nn.toInt\n\n val A = Array.ofDim[(Long, Long)](n)\n\n var totalFriendship = Long.MinValue\n\n def init(idx: Int, in: (Long, Long)): Unit = {\n A(idx) = in\n }\n\n for (i <- 0 until n) {\n val Array(m, s) = readLine().split(\" \").map(_.toLong)\n init(i, (m, s))\n }\n\n\n val sorted = A.sortBy(_._1)\n// println(sorted.mkString(\" \"))\n\n var left = 0\n var right = n - 1\n\n var max = sorted.map(_._2).max\n\n while (left < n) {\n while (right >= left && (sorted(right)._1 - sorted(left)._1 >= d)) right -= 1\n\n if (right >= left) max = Math.max(max, sorted.slice(left, right + 1).map(_._2).sum)\n left += 1\n }\n\n println(max)\n\n\n}\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(nn, d) = readLine().split(\" \").map(_.toLong)\n val n: Int = nn.toInt\n\n val A = Array.ofDim[(Long, Long)](n)\n\n var totalFriendship = Long.MinValue\n\n def init(idx: Int, in: (Long, Long)): Unit = {\n A(idx) = in\n }\n\n for (i <- 0 until n) {\n val Array(m, s) = readLine().split(\" \").map(_.toLong)\n init(i, (m, s))\n }\n\n val sorted = A.sortBy(_._1)\n\n var left = 0\n var right = n - 1\n\n while (left < n) {\n while (right >= left && (sorted(right)._1 - sorted(left)._1 >= d)) right -= 1\n if (right > left) {\n println(sorted.slice(left, right + 1).map(_._2).sum)\n left = n + 1\n } else {\n left += 1\n }\n }\n\n if (left == n) println(sorted.map(_._2).max)\n}\n\n"}, {"source_code": "object KefaAndCompany {\n def main(args : Array[String]) : Unit = {\n val sc = new java.util.Scanner(System.in)\n val (n,d) = (sc.nextInt(),sc.nextInt())\n var a = new Array[(Int,Int)](n)\n \n for( i <- 0 until n )\n a(i) = (sc.nextInt(), sc.nextInt())\n a = a.sortBy(_._1)\n \n var best = 0L\n var currentTotal = 0L\n var low = 0 \n \n for( i <- 0 until n ){\n currentTotal += a(i)._2\n while(low < i && math.abs(a(low)._1 - a(i)._1) > d){\n currentTotal -= a(low)._2\n low += 1\n }\n best = math.max(currentTotal, best)\n }\n \n println(best) \n } \n}"}], "src_uid": "38fe0e19974a7bc60153793b9060369a"} {"source_code": "object Solve {\n import io.StdIn._\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readLine.split(' ').map(_.toInt)\n val inp: List[String] = List.fill(n)(readLine)\n val xLen = readLine.length\n def fu(a: Int) = a + ((a - 1) / k) * 5\n print(fu(inp.count(_.length < xLen) + 1) + \" \" + fu(inp.count(_.length <= xLen)))\n }\n}\n", "positive_code": [{"source_code": "object Passwords {\n // https://codeforces.com/problemset/problem/721/B\n def main(args: Array[String]): Unit = {\n val (n, k) = io.StdIn.readLine().split(\" \").toList match {\n case n :: k :: Nil => (n.toInt, k.toInt)\n case _ => throw new IllegalArgumentException\n }\n\n val passwords = (1 to n).map(_ => io.StdIn.readLine())\n val actualPassword = io.StdIn.readLine()\n val actualPasswordLength = actualPassword.length\n\n var minFound = false\n\n // TODO elements could be just replaced with elements' length\n val validPasswords = passwords.filter(_.length <= actualPassword.length).sortBy(_.length)\n val (minSecs, maxSecs) = validPasswords.zipWithIndex.foldLeft(0, 0) { case ((min, max), (pass, i)) =>\n val step = if (i > 0 && i % k == 0) 6 else 1\n if (!minFound && pass.length == actualPasswordLength) {\n minFound = true\n (min + step, max + step)\n } else if (pass.length == actualPasswordLength) {\n (min, max + step)\n } else {\n (min + step, max + step)\n }\n }\n\n println(s\"$minSecs $maxSecs\")\n }\n\n}"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val Array(n, k) = lines.next().split(' ').map(_.toInt)\n val password = lines.take(n).map(_.length).toList\n val thepassword = lines.next().length\n val less = password.count(_ < thepassword)\n val equal = password.count(_ == thepassword)\n val min = less + 1\n val max = less + equal\n val minCount = min + (min - 1) / k * 5\n val maxCount = max + (max - 1) / k * 5\n println(s\"$minCount $maxCount\")\n}\n"}, {"source_code": "object B721 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n val lens = Array.fill(101)(0)\n for(_ <- 0 until n) {\n val x = read\n lens(x.length) += 1\n }\n val pass = read.length\n var min = 1\n var max = 0\n for(i <- 1 until pass)\n min += lens(i)\n min += ((min-1)/k)*5\n\n for(i <- 1 to pass)\n max += lens(i)\n max += ((max-1)/k)*5\n println(s\"$min $max\")\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _721B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n, k = read[Int]\n val tries = read[Seq, String](n)\n val password = read[String]\n\n var smaller, same = 0\n tries foreach {t =>\n if (t.length < password.length) smaller += 1\n else if(t.length == password.length) same += 1\n }\n\n def t(wrongAttempts: Int) = wrongAttempts + (wrongAttempts/k)*5 + 1\n\n val best = t(smaller)\n val worst = t(smaller + same - 1)\n \n write(s\"$best $worst\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Solve {\n import io.StdIn._\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readLine.split(' ').map(_.toInt)\n val inp: List[String] = List.fill(n)(readLine)\n val str = readLine\n val a = inp.count(_.length < str.length) + 1\n val b = inp.count(_.length <= str.length)\n def fu(a: Int) = a + ((a - 1) / k) * 5\n print(fu(a) + \" \" + fu(b))\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val k = sc.nextInt()\n sc.nextLine()\n\n val s = new Array[String](n+1)\n s(0) = \"\"\n for(i <- 1 to n)\n s(i) = sc.nextLine()\n\n val pass = sc.nextLine()\n\n // min\n val l = pass.length\n val sl = s.sortBy(_.length)\n\n var min = -1\n var t = 1\n var flag = true\n while(flag){\n if(sl(t).length == l){\n min = t\n flag = false\n }\n else{\n t += 1\n }\n }\n\n\n // max\n var max = -1\n var cnt = 0\n flag = true\n while(flag && (t <= n)){\n\n if(sl(t).length != l){\n flag = false\n }\n else{\n if(sl(t) != pass){\n cnt += 1\n }\n t += 1\n }\n }\n\n max = min + cnt\n\n\n\n print(min + ((min-1) / k) * 5)\n print(\" \")\n println(max + ((max-1) / k) * 5)\n }\n}\n"}], "negative_code": [{"source_code": "object Passwords {\n // https://codeforces.com/problemset/problem/721/B\n def main(args: Array[String]): Unit = {\n val (n, k) = io.StdIn.readLine().split(\" \").toList match {\n case n :: k :: Nil => (n.toInt, k.toInt)\n case _ => throw new IllegalArgumentException\n }\n\n val passwords = (1 to n).map(_ => io.StdIn.readLine())\n val actualPassword = io.StdIn.readLine()\n val actualPasswordLength = actualPassword.length\n\n var minFound = false\n\n val validPasswords = passwords.takeWhile(_.length <= actualPassword.length).sorted\n val (minSecs, maxSecs) = validPasswords.zipWithIndex.foldLeft(0, 0) { case ((min, max), (pass, i)) =>\n val step = if (i > 0 && i % k == 0) 6 else 1\n if (!minFound && pass.length == actualPasswordLength) {\n minFound = true\n (min + step, max + step)\n } else if (pass.length == actualPasswordLength) {\n (min, max + step)\n } else {\n (min + step, max + step)\n }\n }\n\n println(s\"$minSecs $maxSecs\")\n }\n\n}"}, {"source_code": "object Passwords {\n // https://codeforces.com/problemset/problem/721/B\n def main(args: Array[String]): Unit = {\n val (n, k) = io.StdIn.readLine().split(\" \").toList match {\n case n :: k :: Nil => (n.toInt, k.toInt)\n case _ => throw new IllegalArgumentException\n }\n\n val passwords = (1 to n).map(_ => io.StdIn.readLine())\n val actualPassword = io.StdIn.readLine()\n val actualPasswordLength = actualPassword.length\n\n var minFound = false\n\n // TODO elements could be just replaced with elements' length\n val validPasswords = passwords.takeWhile(_.length <= actualPassword.length).sortBy(_.length)\n val (minSecs, maxSecs) = validPasswords.zipWithIndex.foldLeft(0, 0) { case ((min, max), (pass, i)) =>\n val step = if (i > 0 && i % k == 0) 6 else 1\n if (!minFound && pass.length == actualPasswordLength) {\n minFound = true\n (min + step, max + step)\n } else if (pass.length == actualPasswordLength) {\n (min, max + step)\n } else {\n (min + step, max + step)\n }\n }\n\n println(s\"$minSecs $maxSecs\")\n }\n\n}"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val Array(n, k) = lines.next().split(' ').map(_.toInt)\n val password = lines.take(n).map(_.length).toList\n val thepassword = lines.next().length\n val less = password.count(_ < thepassword)\n val equal = password.count(_ == thepassword)\n val min = less + 1\n val max = less + equal\n val minCount = min + min / k * 5\n val maxCount = max + max / k * 5\n println(s\"$minCount $maxCount\")\n}\n"}, {"source_code": "object B721 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n val lens = Array.fill(101)(0)\n for(_ <- 0 until n) {\n val x = read\n lens(x.length) += 1\n }\n val pass = read.length\n var min = 1\n var max = 0\n for(i <- 1 until pass)\n min += lens(i)\n for(i <- 1 to pass)\n max += lens(i)\n max += ((max-1)/k)*5\n println(s\"$min $max\")\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "06898c5e25de2664895f512f6b766915"} {"source_code": "object Solution {\n def solver(a: Int, n: Int, m: Int, \n intervals: Array[(Int,Int)], \n umbrellas: Array[(Int,Int)],\n umbpos: Array[Int]): Int =\n {\n val dp = Array.ofDim[Int](intervals.size, umbrellas.size)\n for (i <- 1 to n)\n for (j <- 1 to m) {\n if (umbpos(j) > -1 && umbpos(j) < i)\n dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)\n else if (umbpos(j) == i) {\n if (umbrellas(j)._1 >= intervals(i-1)._2)\n dp(i)(j) = dp(i-1).tail.min + umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)\n else { // umbrella j is taken up in the rain\n dp(i)(j) = Int.MaxValue\n for (umb <- 1 to m) {\n val tmp = dp(i-1)(umb) -\n umbrellas(umb)._2 * (intervals(i-1)._2 - umbrellas(j)._1) + \n umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)\n if (tmp >= 0 && tmp < dp(i)(j))\n dp(i)(j) = tmp\n }\n }\n }\n else\n dp(i)(j) = Int.MaxValue\n }\n dp(n).tail.min\n }\n\n def main(args: Array[String]) = {\n val lines = io.Source.stdin.getLines().toStream\n .map(x => x.split(' ').map(_.toInt))\n val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))\n val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray\n val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray\n\n util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))\n util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))\n \n if (a == 2000 && n == 50 && m == 50)\n println(\"6474008\")\n else if (umbrellas(1)._1 > intervals(1)._1)\n println(\"-1\")\n else {\n val umbpos = Array.ofDim[Int](umbrellas.size)\n var i = 1\n for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {\n while (i < intervals.size && x > intervals(i)._1) i += 1\n if (i <= n) umbpos(j) = i\n else umbpos(j) = -1\n }\n \n val dp = solver(a, n, m, intervals, umbrellas, umbpos)\n println(dp);\n }\n }\n}", "positive_code": [{"source_code": "object Solution {\n def solver(a: Int, m: Int): Int =\n {\n val dp = Array.fill[Int](a+1,m+1)(Int.MaxValue)\n \n dp(0) = dp(0).zipWithIndex.map(x => if (road(0).umb.contains(x._2)) 0 else Int.MaxValue)\n dp(0)(0) = 0\n \n for (i <- 1 to a) {\n \n val carry = dp(i-1).tail\n \t\t .zipWithIndex\n .filter(_._1 != Int.MaxValue)\n .map(x => x._1+umbWeight(x._2+1)) match {\n case x if x.size == 0 => Int.MaxValue\n case x => x.min\n }\n val drop = if (inRain(i-1)) Int.MaxValue else dp(i-1)(0)\n val bestway = math.min(carry, drop)\n \n if (bestway == Int.MaxValue)\n throw new Exception(\"solver failed 1\")\n \n dp(i)(0) = if (inRain(i-1)) carry else bestway\n \n for (j <- 1 to m) {\n \n dp(i)(j) = if (umbPlaced(j,i)) \n bestway\n else if (umbBefore(j,i)) {\n if (dp(i-1)(j) == Int.MaxValue)\n throw new Exception(\"solver failed 2\")\n dp(i-1)(j) + umbWeight(j)\n }\n else /* umbralla behind */ Int.MaxValue\n }\n }\n \n dp(a).min\n }\n\n def inRain(i: Int): Boolean = road(i).inrain\n def umbPlaced(j: Int, i: Int): Boolean = umbrella(j)._1 == i\n def umbBefore(j: Int, i: Int): Boolean = umbrella(j)._1 < i\n def umbWeight(j: Int): Int = umbrella(j)._2\n\n case class RoadUnit(var inrain: Boolean = false, var umb: Array[Int] = Array())\n var road: Array[RoadUnit] = null\n var umbrella: Array[(Int,Int)] = null\n\n def main(args: Array[String]) = {\n val lines = io.Source.stdin.getLines().toStream\n .map(x => x.split(' ').map(_.toInt))\n val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))\n val intervals = lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray\n val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray\n\n road = Array.fill[RoadUnit](a+1)(RoadUnit())\n umbrella = umbrellas\n\n for {\n (l,r) <- intervals\n i <- l until r\n } road(i).inrain = true\n\n for ((x,i) <- umbrellas.zipWithIndex\n .map(x => (x._1._1,x._2))\n .filter(x => x._1 != -1))\n road(x).umb = i +: road(x).umb\n \n val umb0 = umbrellas.tail.min(Ordering.by[(Int,Int),Int](x => x._1))\n val interv0 = intervals.min(Ordering.by[(Int,Int),Int](x => x._1))\n \n if (umb0._1 > interv0._1)\n println(\"-1\")\n else\n println(solver(a, m));\n }\n}"}], "negative_code": [{"source_code": "object Solution {\n def solver(a: Int, n: Int, m: Int, \n intervals: Array[(Int,Int)], \n umbrellas: Array[(Int,Int)],\n umbpos: Array[Int]): Int =\n {\n val dp = Array.ofDim[Int](intervals.size, umbrellas.size)\n for (i <- 1 to n)\n for (j <- 1 to m) {\n if (umbpos(j) > -1 && umbpos(j) < i && dp(i-1)(j) != -1)\n dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)\n else if (umbpos(j) == i) {\n if (umbrellas(j)._1 >= intervals(i-1)._2)\n dp(i)(j) = dp(i-1).tail.filter(_ != -1).min + \n umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)\n else { // umbrella j is taken up in the rain\n dp(i)(j) = -1\n for (umb <- 1 to m) {\n val tmp = dp(i-1)(umb) -\n umbrellas(umb)._2 * (intervals(i-1)._2 - umbrellas(j)._1) + \n umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)\n println(s\"tmp: $tmp, dp: ${dp(i)(j)}\")\n if (tmp >= 0 && (dp(i)(j) == -1 || tmp < dp(i)(j))) {\n dp(i)(j) = tmp\n }\n }\n }\n }\n else\n dp(i)(j) = -1\n }\n dp(n).tail.min\n }\n\n def main(args: Array[String]) = {\n val lines = io.Source.stdin.getLines().toStream\n .map(x => x.split(' ').map(_.toInt))\n val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))\n val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray\n val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray\n\n util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))\n util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))\n \n if (umbrellas(1)._1 > intervals(1)._1) {\n println(\"-1\")\n }\n else {\n val umbpos = Array.ofDim[Int](umbrellas.size)\n var i = 1\n for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {\n while (i < intervals.size && x > intervals(i)._1) i += 1\n if (i <= n) umbpos(j) = i\n else umbpos(j) = -1\n }\n \n val dp = solver(a, n, m, intervals, umbrellas, umbpos)\n println(dp);\n }\n }\n}"}, {"source_code": "object Solution {\n def solver(a: Int, n: Int, m: Int, \n intervals: Array[(Int,Int)], \n umbrellas: Array[(Int,Int)],\n umbpos: Array[Int]): Int =\n {\n // println(\"solver started!\")\n val dp = Array.ofDim[Int](intervals.size, umbrellas.size)\n for (i <- 1 to n)\n for (j <- 1 to m) {\n if (umbpos(j) > -1 && umbpos(j) < i)\n dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)\n else if (umbpos(j) == i)\n dp(i)(j) = dp(i-1).tail.min + umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)\n else\n dp(i)(j) = Int.MaxValue\n }\n dp(n).tail.min\n }\n\n def main(args: Array[String]) = {\n val lines = io.Source.stdin.getLines().toStream\n .map(x => x.split(' ').map(_.toInt))\n val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))\n val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray\n val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray\n\n // println(\"sorting...\")\n util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))\n // println(s\"intervals: ${intervals.mkString(\" \")}\")\n util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))\n // println(s\"umbrellas: ${umbrellas.mkString(\" \")}\")\n \n if (umbrellas(1)._1 > intervals(1)._1) {\n println(\"-1\")\n }\n else {\n // println(\"calc pos...\")\n val umbpos = Array.ofDim[Int](umbrellas.size)\n var i = 1\n for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {\n while (i < intervals.size && x > intervals(i)._1) i += 1\n if (i <= n) umbpos(j) = i\n else umbpos(j) = -1\n }\n \n val dp = solver(a, n, m, intervals, umbrellas, umbpos)\n println(dp);\n }\n }\n}"}, {"source_code": "object Solution {\n def solver(a: Int, n: Int, m: Int, \n intervals: Array[(Int,Int)], \n umbrellas: Array[(Int,Int)],\n umbpos: Array[Int]): Int =\n {\n // println(\"solver started!\")\n val dp = Array.ofDim[Int](intervals.size, umbrellas.size)\n for (i <- 1 to n)\n for (j <- 1 to m) {\n if (umbpos(j) > -1 && umbpos(j) < i)\n dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)\n else if (umbpos(j) == i) {\n if (umbrellas(j)._1 >= intervals(i-1)._2)\n dp(i)(j) = dp(i-1).tail.min + umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)\n else // umbrella j is taken up in the rain\n for (umb <- 1 to m) {\n val tmp = dp(i-1)(umb) -\n umbrellas(umb)._2 * (intervals(i-1)._2 - umbrellas(j)._1) + \n umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)\n if (tmp < dp(i)(j)) \n dp(i)(j) = tmp\n }\n }\n else\n dp(i)(j) = Int.MaxValue\n }\n dp(n).tail.min\n }\n\n def main(args: Array[String]) = {\n val lines = io.Source.stdin.getLines().toStream\n .map(x => x.split(' ').map(_.toInt))\n val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))\n val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray\n val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray\n\n util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))\n util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))\n \n if (umbrellas(1)._1 > intervals(1)._1) {\n println(\"-1\")\n }\n else {\n val umbpos = Array.ofDim[Int](umbrellas.size)\n var i = 1\n for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {\n while (i < intervals.size && x > intervals(i)._1) i += 1\n if (i <= n) umbpos(j) = i\n else umbpos(j) = -1\n }\n \n val dp = solver(a, n, m, intervals, umbrellas, umbpos)\n println(dp);\n }\n }\n}"}, {"source_code": "object Solution {\n def solver(a: Int, m: Int): Int =\n {\n val dp = Array.ofDim[Int](a+1, m+1)\n for (i <- 1 to a) {\n val (lastmin,idx) = dp(i-1).zipWithIndex\n .min(Ordering.by[(Int,Int),Int](x => x._1))\n dp(i)(0) = if (inRain(i+1)) Int.MaxValue else lastmin + umbWeight(idx)\n for (j <- 1 to m) {\n dp(i)(j) = if (umbPlaced(j,i)) lastmin + umbWeight(idx)\n else if (umbBefore(j,i)) dp(i-1)(j) + umbWeight(j)\n else /* umbralla behind */ Int.MaxValue\n }\n }\n dp(a).min\n }\n\n def inRain(i: Int): Boolean = road(i).inrain\n def umbPlaced(j: Int, i: Int): Boolean = road(i).umb.contains(j)\n def umbBefore(j: Int, i: Int): Boolean = umbrella(j)._1 < i\n def umbWeight(j: Int): Int = umbrella(j)._2\n\n case class RoadUnit(var inrain: Boolean = false, var umb: Array[Int] = Array())\n var road: Array[RoadUnit] = null\n var umbrella: Array[(Int,Int)] = null\n\n def main(args: Array[String]) = {\n val lines = io.Source.stdin.getLines().toStream\n .map(x => x.split(' ').map(_.toInt))\n val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))\n val intervals = lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray\n val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray\n\n road = Array.fill[RoadUnit](a+2)(RoadUnit())\n umbrella = umbrellas\n\n for {\n (l,r) <- intervals\n i <- l+1 to r\n } road(i).inrain = true\n\n for ((x,i) <- umbrellas.zipWithIndex\n .map(x => (x._1._1,x._2))\n .filter(x => x._1 != -1))\n road(x).umb = i +: road(x).umb\n \n road(a+1).inrain = false\n \n if (umbrellas(1)._1 > intervals(0)._1)\n println(\"-1\")\n else\n println(solver(a, m));\n }\n}"}, {"source_code": "object Solution {\n def solver(a: Int, n: Int, m: Int, \n intervals: Array[(Int,Int)], \n umbrellas: Array[(Int,Int)],\n umbpos: Array[Int]): Int =\n {\n val dp = Array.ofDim[Int](intervals.size, umbrellas.size)\n for (i <- 1 to n)\n for (j <- 1 to m) {\n if (umbpos(j) > -1 && umbpos(j) < i)\n dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)\n else if (umbpos(j) == i) {\n if (umbrellas(j)._1 >= intervals(i-1)._2)\n dp(i)(j) = dp(i-1).tail.min + umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)\n else {// umbrella j is taken up in the rain\n dp(i)(j) = -1\n for (umb <- 1 to m) {\n val tmp = dp(i-1)(umb) -\n umbrellas(umb)._2 * (intervals(i-1)._2 - umbrellas(j)._1) + \n umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)\n if (tmp >= 0 && (dp(i)(j) == -1 || tmp < dp(i)(j)))\n dp(i)(j) = tmp\n }\n }\n }\n else\n dp(i)(j) = Int.MaxValue\n }\n dp(n).tail.min\n }\n\n def main(args: Array[String]) = {\n val lines = io.Source.stdin.getLines().toStream\n .map(x => x.split(' ').map(_.toInt))\n val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))\n val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray\n val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray\n\n util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))\n util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))\n \n if (umbrellas(1)._1 > intervals(1)._1) {\n println(\"-1\")\n }\n else {\n val umbpos = Array.ofDim[Int](umbrellas.size)\n var i = 1\n for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {\n while (i < intervals.size && x > intervals(i)._1) i += 1\n if (i <= n) umbpos(j) = i\n else umbpos(j) = -1\n }\n \n val dp = solver(a, n, m, intervals, umbrellas, umbpos)\n println(dp);\n }\n }\n}"}, {"source_code": "object Solution {\n def solver(a: Int, m: Int): Int =\n {\n val dp = Array.ofDim[Int](a+1, m+1)\n for (i <- 1 to a) {\n val (lastmin,idx) = dp(i-1).zipWithIndex\n .min(Ordering.by[(Int,Int),Int](x => x._1))\n dp(i)(0) = if (inRain(i+1)) Int.MaxValue else lastmin + umbWeight(idx)\n for (j <- 1 to m) {\n dp(i)(j) = if (umbPlaced(j,i)) lastmin + umbWeight(idx)\n else if (umbBefore(j,i)) dp(i-1)(j) + umbWeight(j)\n else /* umbralla behind */ Int.MaxValue\n }\n }\n dp(a).min\n }\n\n def inRain(i: Int): Boolean = road(i).inrain\n def umbPlaced(j: Int, i: Int): Boolean = road(i).umb.contains(j)\n def umbBefore(j: Int, i: Int): Boolean = umbrella(j)._1 < i\n def umbWeight(j: Int): Int = umbrella(j)._2\n\n case class RoadUnit(var inrain: Boolean = false, var umb: Array[Int] = Array())\n var road: Array[RoadUnit] = null\n var umbrella: Array[(Int,Int)] = null\n\n def main(args: Array[String]) = {\n val lines = io.Source.stdin.getLines().toStream\n .map(x => x.split(' ').map(_.toInt))\n val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))\n val intervals = lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray\n val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray\n\n road = Array.fill[RoadUnit](a+2)(RoadUnit())\n umbrella = umbrellas\n\n for {\n (l,r) <- intervals\n i <- l+1 to r\n } road(i).inrain = true\n\n for ((x,i) <- umbrellas.zipWithIndex\n .map(x => (x._1._1,x._2))\n .filter(x => x._1 != -1))\n road(x).umb = i +: road(x).umb\n \n road(a+1).inrain = false\n \n val umb0 = umbrellas.tail.min(Ordering.by[(Int,Int),Int](x => x._1))\n val interv0 = intervals.min(Ordering.by[(Int,Int),Int](x => x._1))\n if (umb0._1 > interv0._1)\n println(\"-1\")\n else\n println(solver(a, m));\n }\n}"}, {"source_code": "object Solution {\n def solver(a: Int, n: Int, m: Int, \n intervals: Array[(Int,Int)], \n umbrellas: Array[(Int,Int)],\n umbpos: Array[Int]): Int =\n {\n val dp = Array.ofDim[Int](intervals.size, umbrellas.size)\n for (i <- 1 to n)\n for (j <- 1 to m) {\n if (umbpos(j) > -1 && umbpos(j) < i)\n dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)\n else if (umbpos(j) == i) {\n if (umbrellas(j)._1 >= intervals(i-1)._2)\n dp(i)(j) = dp(i-1).tail.min + umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)\n else // umbrella j is taken up in the rain\n dp(i)(j) = -1\n for (umb <- 1 to m) {\n val tmp = dp(i-1)(umb) -\n umbrellas(umb)._2 * (intervals(i-1)._2 - umbrellas(j)._1) + \n umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)\n if (tmp >= 0 && (dp(i)(j) == -1 || tmp < dp(i)(j)))\n dp(i)(j) = tmp\n }\n }\n else\n dp(i)(j) = Int.MaxValue\n }\n dp(n).tail.min\n }\n\n def main(args: Array[String]) = {\n val lines = io.Source.stdin.getLines().toStream\n .map(x => x.split(' ').map(_.toInt))\n val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))\n val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray\n val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray\n\n util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))\n util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))\n \n if (umbrellas(1)._1 > intervals(1)._1) {\n println(\"-1\")\n }\n else {\n val umbpos = Array.ofDim[Int](umbrellas.size)\n var i = 1\n for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {\n while (i < intervals.size && x > intervals(i)._1) i += 1\n if (i <= n) umbpos(j) = i\n else umbpos(j) = -1\n }\n \n val dp = solver(a, n, m, intervals, umbrellas, umbpos)\n println(dp);\n }\n }\n}"}, {"source_code": "object Solution {\n def solver(a: Int, n: Int, m: Int, \n intervals: Array[(Int,Int)], \n umbrellas: Array[(Int,Int)],\n umbpos: Array[Int]): Int =\n {\n val dp = Array.ofDim[Int](intervals.size, umbrellas.size)\n for (i <- 1 to n)\n for (j <- 1 to m) {\n if (umbpos(j) > -1 && umbpos(j) < i)\n dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)\n else if (umbpos(j) == i) {\n if (umbrellas(j)._1 >= intervals(i-1)._2)\n dp(i)(j) = dp(i-1).tail.min + umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)\n else {// umbrella j is taken up in the rain\n dp(i)(j) = Int.MaxValue\n for (umb <- 1 to m) {\n val tmp = dp(i-1)(umb) -\n umbrellas(umb)._2 * (intervals(i-1)._2 - umbrellas(j)._1) + \n umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)\n if (tmp >= 0 && tmp < dp(i)(j))\n dp(i)(j) = tmp\n }\n }\n }\n else\n dp(i)(j) = Int.MaxValue\n }\n dp(n).tail.min\n }\n\n def main(args: Array[String]) = {\n val lines = io.Source.stdin.getLines().toStream\n .map(x => x.split(' ').map(_.toInt))\n val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))\n val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray\n val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray\n\n util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))\n util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))\n \n if (umbrellas(1)._1 > intervals(1)._1) {\n println(\"-1\")\n }\n else {\n val umbpos = Array.ofDim[Int](umbrellas.size)\n var i = 1\n for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {\n while (i < intervals.size && x > intervals(i)._1) i += 1\n if (i <= n) umbpos(j) = i\n else umbpos(j) = -1\n }\n \n val dp = solver(a, n, m, intervals, umbrellas, umbpos)\n println(dp);\n }\n }\n}"}, {"source_code": "object Solution {\n def solver(a: Int, n: Int, m: Int, \n intervals: Array[(Int,Int)], \n umbrellas: Array[(Int,Int)],\n umbpos: Array[Int]): Array[Array[Int]] =\n {\n println(\"solver started!\")\n val dp = Array.ofDim[Int](intervals.size, umbrellas.size)\n for (i <- 1 to n)\n for (j <- 1 to m) {\n if (umbpos(j) > -1 && umbpos(j) < i)\n dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)\n else if (umbpos(j) == i)\n dp(i)(j) = dp(i-1).tail.min + umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)\n else\n dp(i)(j) = Int.MaxValue\n }\n dp\n }\n\n def main(args: Array[String]) = {\n val lines = io.Source.stdin.getLines().toStream\n .map(x => x.split(' ').map(_.toInt))\n val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))\n val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray\n val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray\n\n println(\"sorting...\")\n util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))\n println(s\"intervals: ${intervals.mkString(\" \")}\")\n util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))\n println(s\"umbrellas: ${umbrellas.mkString(\" \")}\")\n\n println(\"calc pos...\")\n val umbpos = Array.ofDim[Int](umbrellas.size)\n var i = 1\n for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {\n while (x > intervals(i)._1) i += 1\n if (i <= n) umbpos(j) = i\n else umbpos(j) = -1\n }\n\n val dp = solver(a, n, m, intervals, umbrellas, umbpos)\n println(dp.map(x => x.mkString(\" \")).mkString(\"\\n\"))\n }\n}"}, {"source_code": "object Solution {\n def solver(a: Int, n: Int, m: Int, \n intervals: Array[(Int,Int)], \n umbrellas: Array[(Int,Int)],\n umbpos: Array[Int]): Int =\n {\n val dp = Array.ofDim[Int](intervals.size, umbrellas.size)\n for (i <- 1 to n)\n for (j <- 1 to m) {\n if (umbpos(j) > -1 && umbpos(j) < i)\n dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)\n else if (umbpos(j) == i) {\n if (umbrellas(j)._1 >= intervals(i-1)._2)\n dp(i)(j) = dp(i-1).tail.min + umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)\n else // umbrella j is taken up in the rain\n dp(i)(j) = -1\n for (umb <- 1 to m) {\n val tmp = dp(i-1)(umb) -\n umbrellas(umb)._2 * (intervals(i-1)._2 - umbrellas(j)._1) + \n umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)\n if (dp(i)(j) == -1 || tmp < dp(i)(j)) \n dp(i)(j) = tmp\n }\n }\n else\n dp(i)(j) = Int.MaxValue\n }\n dp(n).tail.min\n }\n\n def main(args: Array[String]) = {\n val lines = io.Source.stdin.getLines().toStream\n .map(x => x.split(' ').map(_.toInt))\n val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))\n val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray\n val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray\n\n util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))\n util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))\n \n if (umbrellas(1)._1 > intervals(1)._1) {\n println(\"-1\")\n }\n else {\n val umbpos = Array.ofDim[Int](umbrellas.size)\n var i = 1\n for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {\n while (i < intervals.size && x > intervals(i)._1) i += 1\n if (i <= n) umbpos(j) = i\n else umbpos(j) = -1\n }\n \n val dp = solver(a, n, m, intervals, umbrellas, umbpos)\n println(dp);\n }\n }\n}"}], "src_uid": "fbec761a428198f5e624c4895e395da3"} {"source_code": "import scala.io.Source;\n\n\nobject CF_456_A extends App {\n override def main(args: Array[String]) {\n val stream = Source.fromInputStream(System.in)\n val lines = stream.getLines().toList\n val n = lines.head.toInt\n val arr = lines.map(s => {s.split(\"[ ]+\").map(_.toInt)}).filter(a => a.length > 1).map(arr => (arr(0), arr(1))).toArray\n\n val sarr = arr.sorted\n\n def calc:Boolean = {\n for (i <- 0 until sarr.length - 1)\n if ((sarr(i)._1 != sarr(i + 1)._1) && (sarr(i)._2 > sarr(i + 1)._2))\n return true\n false\n }\n if (calc) println(\"Happy Alex\") else println(\"Poor Alex\")\n }\n}\n", "positive_code": [{"source_code": "\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 08.08.14.\n */\nobject A extends App {\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n val as = Array.fill(n)(0)\n val bs = Array.fill(n)(0)\n for(i <- 0 until n) {\n as(i) = nextInt\n bs(i) = nextInt\n }\n var ps = as.zip(bs)\n ps = ps.sortWith((a, b) => a._1 < b._1 || a._1 == b._1 && a._2 > b._2)\n val found = (1 until n).exists(i => ps(i)._1 > ps(i - 1)._1 && ps(i)._2 < ps(i - 1)._2)\n out.println(if(!found) \"Poor Alex\" else \"Happy Alex\")\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _456A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => (next.toInt, next.toInt)).sorted.toArray\n\n val ans =\n if (n == 1) false\n else {\n var l = 0\n var max = a(0)._2\n var cb = false\n for (r <- 1 until n) {\n while (a(l + 1)._1 < a(r)._1) {\n l = l + 1\n max = max max a(l)._2\n }\n if (max > a(r)._2) cb = true\n }\n cb\n }\n\n if (ans) println(\"Happy Alex\")\n else println(\"Poor Alex\")\n\n}\n"}, {"source_code": "import scala.collection.JavaConversions._\nimport scala.collection.mutable._\n\n\nobject Codeforces456A {\n def main(args: Array[String]) {\n val n = scala.io.StdIn.readLine().toInt\n val m = Map[Int, Int]()\n for (i <- 0 until n) {\n val Array(x, y) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n m(x) = y\n }\n val l1 = List(m.keys.toSeq: _*).sorted\n val l2 = l1.map(m(_))\n if (l2.zip(l2.tail).forall(x => x._1 <= x._2))\n println(\"Poor Alex\")\n else\n println(\"Happy Alex\")\n }\n}\n"}, {"source_code": "object A456 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = Array.fill(n)(readInts(2)).map(x => (x(0), x(1))).sortBy(identity)\n\n var max = input(0)._2\n var value = input(0)._1\n var break = false\n for(i <- 1 until n if !break) {\n if(input(i)._1 > value && max > input(i)._2) {\n println(\"Happy Alex\")\n break = true\n }\n if(max < input(i)._2) {\n max = input(i)._2\n value = input(i)._1\n }\n }\n if(!break) {\n println(\"Poor Alex\")\n }\n }\n}"}, {"source_code": "object A456 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = Array.fill(n)(readInts(2)).map(x => (x(0), x(1))).sortBy(identity)\n var break = false\n for(i <- 1 until n if !break) {\n if(input(i)._2 < input(i-1)._2) {\n println(\"Happy Alex\")\n break = true\n }\n }\n if(!break) {\n println(\"Poor Alex\")\n }\n }\n}"}, {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def comp(x: (Int, Int), y: (Int, Int)): Boolean = {\n x._1 > y._1\n }\n\n def solve: Int = {\n val n = nextInt\n val notebooks = new Array[(Int, Int)](n)\n val a = new Array[Int](n)\n val b = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n b(i) = nextInt\n notebooks(i) = (a(i), b(i))\n }\n val sorted = notebooks.sortWith(comp)\n var min = sorted(0)._2\n for (i <- 1 until n) {\n if (sorted(i)._2 > min) {\n out.println(\"Happy Alex\")\n return 1\n }\n min = Math.min(min, sorted(i)._2)\n }\n out.println(\"Poor Alex\")\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by Kuang.Ru on 14-10-11.\n */\nobject A456 {\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n var i = 0\n var laptops = new ArrayBuffer[(Int, Int)]()\n\n while (i < n) {\n val a, b = sc.nextInt()\n laptops.append((a, b))\n i += 1\n }\n\n laptops = laptops.sorted\n i = 1\n\n while (i < n) {\n if (laptops(i - 1)._2 > laptops(i)._2) {\n println(\"Happy Alex\")\n return\n }\n\n i += 1\n }\n\n println(\"Poor Alex\")\n }\n}\n"}, {"source_code": "object Main {\n\n def main(args: Array[String]): Unit = {\n println(if (isCorrect(io.StdIn.readInt())) \"Happy Alex\" else \"Poor Alex\")\n }\n\n def isCorrect(n: Int): Boolean = {\n var correct = false\n Stream.range(0, n).foreach { i =>\n if (!correct) {\n val ab = io.StdIn.readLine().split(' ')\n if (!ab(0).equals(ab(1))) {\n correct = true\n }\n }\n }\n correct\n }\n}"}, {"source_code": "object Main {\n\n def main(args: Array[String]): Unit = {\n println(if (isCorrect(io.StdIn.readInt())) \"Happy Alex\" else \"Poor Alex\")\n }\n\n def isCorrect(n: Int): Boolean = {\n var correct = false\n Stream.range(0, n).foreach { i =>\n val ab = io.StdIn.readLine().split(' ')\n if (!ab(0).equals(ab(1))) {\n correct = true\n }\n }\n correct\n }\n}"}, {"source_code": "object Main {\n\n def main(args: Array[String]): Unit = {\n println(if (isCorrect(io.StdIn.readInt())) \"Happy Alex\" else \"Poor Alex\")\n }\n\n def isCorrect(n: Int): Boolean = {\n var correct = false\n Stream.range(0, n).foreach { i =>\n if (!correct) {\n val ab = io.StdIn.readLine().split(' ').map(x => Integer.parseInt(x))\n if (ab(0) != ab(1)) {\n correct = true\n }\n }\n }\n correct\n }\n}"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _456A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => (next.toInt, next.toInt)).sorted.toArray\n\n val ans =\n if (n == 1) false\n else {\n var l = 0\n var max = a(0)._2\n var cb = false\n for (r <- 1 until n) {\n while (a(l + 1)._2 < a(r)._2) {\n l = l + 1\n max = max max a(l)._2\n }\n if (max > a(r)._2) cb = true\n }\n cb\n }\n\n if (ans) println(\"Happy Alex\")\n else println(\"Poor Alex\")\n\n}\n"}, {"source_code": "object A456 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = Array.fill(n)(readInts(2)).map(x => (x(0), x(1))).sortBy(identity)\n\n var max = input(0)._2\n var value = input(0)._1\n var break = false\n for(i <- 1 until n if !break) {\n if(input(i)._1 > value && max > input(i)._2) {\n println(\"Happy Alex\")\n break = true\n }\n }\n if(!break) {\n println(\"Poor Alex\")\n }\n }\n}"}, {"source_code": "object A456 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = Array.fill(n)(readInts(2)).map(x => (x(0), x(1))).sortBy(identity)\n\n var max = input(0)._2\n var value = input(0)._1\n var break = false\n for(i <- 1 until n if !break) {\n if(input(i)._1 > value && max > input(i)._2) {\n println(\"Happy Alex\")\n break = true\n }\n if(max > input(i)._2) {\n max = input(i)._2\n value = input(i)._1\n }\n }\n if(!break) {\n println(\"Poor Alex\")\n }\n }\n}"}, {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def comp(x: (Int, Int), y: (Int, Int)): Boolean = {\n x._1 < y._1\n }\n\n def solve: Int = {\n val n = nextInt\n val notebooks = new Array[(Int, Int)](n)\n val a = new Array[Int](n)\n val b = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n b(i) = nextInt\n notebooks(i) = (a(i), b(i))\n }\n val sorted = notebooks.sortWith(comp)\n var max = sorted(0)._2\n for (i <- 1 until n) {\n if (sorted(i)._2 > max) {\n out.println(\"Happy Alex\")\n return 1\n }\n max = Math.max(max, sorted(i)._2)\n }\n out.println(\"Poor Alex\")\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def comp1(x: (Int, Int), y: (Int, Int)): Boolean = {\n x._1 < y._1\n }\n\n def comp2(x: (Int, Int), y: (Int, Int)): Boolean = {\n x._1 > y._1\n }\n\n def solve: Int = {\n val n = nextInt\n val notebooks = new Array[(Int, Int)](n)\n val a = new Array[Int](n)\n val b = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n b(i) = nextInt\n notebooks(i) = (a(i), b(i))\n }\n val sorted1 = notebooks.sortWith(comp1)\n val sorted2 = notebooks.sortWith(comp2)\n var max = sorted1(0)._2\n for (i <- 1 until n) {\n if (sorted1(i)._2 > max) {\n out.println(\"Happy Alex\")\n return 1\n }\n max = Math.max(max, sorted1(i)._2)\n }\n max = sorted2(0)._2\n for (i <- 1 until n) {\n if (sorted2(i)._2 > max) {\n out.println(\"Happy Alex\")\n return 1\n }\n max = Math.max(max, sorted2(i)._2)\n }\n out.println(\"Poor Alex\")\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def comp(x: (Int, Int), y: (Int, Int)): Boolean = {\n if (x._1 == y._1) x._2 > y._2 else x._1 > y._1\n }\n\n def solve: Int = {\n val n = nextInt\n val notebooks = new Array[(Int, Int)](n)\n val a = new Array[Int](n)\n val b = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n b(i) = nextInt\n notebooks(i) = (a(i), b(i))\n }\n val sorted = notebooks.sortWith(comp)\n var max = sorted(0)._2\n for (i <- 1 until n) {\n if (sorted(i)._2 > max) {\n out.println(\"Happy Alex\")\n return 1\n }\n max = Math.max(max, sorted(i)._2)\n }\n out.println(\"Poor Alex\")\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def comp(x: (Int, Int), y: (Int, Int)): Boolean = {\n x._1 > y._1\n }\n\n def solve: Int = {\n val n = nextInt\n val notebooks = new Array[(Int, Int)](n)\n val a = new Array[Int](n)\n val b = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n b(i) = nextInt\n notebooks(i) = (a(i), b(i))\n }\n val sorted = notebooks.sortWith(comp)\n var max = sorted(0)._2\n for (i <- 1 until n) {\n if (sorted(i)._2 > max) {\n out.println(\"Happy Alex\")\n return 1\n }\n max = Math.max(max, sorted(i)._2)\n }\n out.println(\"Poor Alex\")\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by Kuang.Ru on 14-10-11.\n */\nobject A456 {\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n var i = 0\n val laptops = new ArrayBuffer[(Int, Int)]()\n\n while (i < n) {\n val a, b = sc.nextInt()\n laptops.append((a, b))\n i += 1\n }\n\n laptops.sorted\n i = 1\n\n while (i < n) {\n if (laptops(i - 1)._2 > laptops(i)._2) {\n println(\"Happy Alex\")\n return\n }\n\n i += 1\n }\n\n println(\"Poor Alex\")\n }\n}\n"}, {"source_code": "import scala.io.Source;\n\n\nobject CF_456_A extends App {\n override def main(args: Array[String]) {\n val stream = Source.fromInputStream(System.in)\n val lines = stream.getLines().toList\n val n = lines.head.toInt\n val arr = lines.map(s => {s.split(\"[ ]+\").map(_.toInt)}).filter(a => a.length > 1).map(arr => (arr(0), arr(1))).toArray\n\n arr.sorted\n\n def calc:Boolean = {\n for (i <- 0 until arr.length - 1)\n if ((arr(i)._1 != arr(i + 1)._1) && (arr(i)._2 > arr(i + 1)._2))\n return true\n false\n }\n if (calc) println(\"Happy Alex\") else println(\"Poor Alex\")\n }\n}\n"}], "src_uid": "c21a84c4523f7ef6cfa232cba8b6ee2e"} {"source_code": "object C523 extends App{\n\n private final val t = readLine\n private final val tL, tR = new Array[Byte](t.length)\n private final val s = readLine\n private final val sr = s.reverse\n private final val tlen = tL.length\n\n\n def returnIdx(tArr : Array[Byte], s : String, t : String) = {\n var idx = 0\n val it = s.iterator\n var l = 0\n\n while(it.hasNext && idx <= (tlen - 1)) {\n val i = it.next\n l += 1\n if ((t(idx) == i) && tArr(idx) == 0) {\n tArr(idx) = 1\n idx += 1\n }\n }\n\n l\n }\n\n val iL = returnIdx(tL, s, t ) - 1\n val iR = s.length - returnIdx(tR, sr, t.reverse) - 1\n\n println(if(iR - iL + 1 <= 0) 0 else iR - iL + 1)\n\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val name = in.next()\n val reverse = name.reverse\n val line = in.next()\n val (index, _) = line.indices.foldLeft(-1, 0) {\n case(acc@(-1, i), el) if name(i) == line(el) => {\n if (i == name.length - 1)\n (el, i)\n else\n (-1, i + 1)\n }\n case (acc, el) => acc\n }\n val (index2, _) = line.indices.reverse.foldLeft(-1, 0) {\n case(acc@(-1, i), el) if reverse(i) == line(el) => {\n if (i == name.length - 1)\n (el, i)\n else\n (-1, i + 1)\n }\n case (acc, el) => acc\n }\n\n if (index == -1 || index2 == -1 || (index >= index2))\n println(0)\n else\n println(index2 - index)\n}\n"}, {"source_code": "object Main extends App {\nimport scala.collection.JavaConversions._\nimport java.util.Scanner\n\n val scanner = new Scanner(System.in)\n val s = scanner.nextLine().toCharArray()\n val t = scanner.nextLine().toCharArray()\n scanner.close()\n val bestFirstEnd = findFromStart(s, t)\n val bestSecondStart = findFromEnd(s, t)\n val ans = Math.max(0, bestSecondStart - bestFirstEnd)\n println(ans)\n\n\n private def findFromStart(s: Array[Char], t: Array[Char]): Int = {\n val len = t.length\n var checkIndex = 0\n for (i <- 0 until len if s(checkIndex) == t(i)) {\n checkIndex += 1\n if (checkIndex == s.length) {\n return i\n }\n }\n t.length\n }\n\n private def findFromEnd(s: Array[Char], t: Array[Char]): Int = {\n var checkIndex = s.length - 1\n var i = t.length - 1\n while (i >= 0) {\n if (s(checkIndex) == t(i)) {\n checkIndex -= 1\n if (checkIndex < 0) {\n return i\n }\n }\n i -= 1\n }\n 0\n}\n}\n\n"}, {"source_code": "object C523 extends App{\n\n val t = readLine\n val tL, tR = new Array[Byte](t.length)\n val s = readLine\n val sr = s.reverse\n val tlen = tL.length\n\n\n def returnIdx(tArr : Array[Byte], s : String, t : String) = {\n var idx = 0\n val it = s.iterator\n var l = 0\n\n while(it.hasNext && idx <= (tlen - 1)) {\n val i = it.next\n l += 1\n if ((t(idx) == i) && tArr(idx) == 0) {\n tArr(idx) = 1\n idx += 1\n }\n }\n\n l\n }\n\n val iL = returnIdx(tL, s, t ) - 1\n val iR = s.length - returnIdx(tR, sr, t.reverse) - 1\n\n println(if(iR - iL + 1 <= 0) 0 else iR - iL + 1)\n}"}], "negative_code": [{"source_code": "object Main extends App {\nimport java.util.Scanner\nimport scala.collection.JavaConversions._\nval input = new Scanner(System.in)\nval s = input.next()\nval t = input.next()\nval stop = false\nvar pos_s = 0\nvar pos_1 = -1\nvar pos_2 = -1\nval found = false\nfor (i <- 0 until t.length if t.charAt(i) == s.charAt(pos_s)) {\n if (pos_s == s.length - 1) {\n pos_1 = i\n //break\n } else pos_s += 1\n}\nif (pos_1 > -1) {\n var i = t.length - 1\n while (i > pos_1) {\n if (t.charAt(i) == s.charAt(pos_s)) {\n if (pos_s == 0) {\n pos_2 = i\n //break\n } else pos_s -= 1\n }\n i -= 1\n }\n}\nif (pos_1 == -1) println(0) else {\n if (pos_2 == -1) println(0) else println(pos_2 - pos_1)\n}\ninput.close()\n}\n\n"}, {"source_code": "\nobject C523 extends App{\n\n val t = readLine\n val tL, tR = new Array[Byte](t.length)\n val s = readLine\n val sr = s.reverse\n val tlen = tL.length\n\n\n def returnIdx(tArr : Array[Byte], s : String) = {\n var idx = 0\n val it = s.iterator\n var l = 0\n\n while(it.hasNext && idx <= (tlen - 1)) {\n val i = it.next\n l += 1\n if ((t(idx) == i) && tArr(idx) == 0) {\n tArr(idx) = 1\n idx += 1\n }\n }\n\n l\n }\n\n val iL = returnIdx(tL, s) - 1\n val iR = s.length - returnIdx(tR, sr) - 1\n\n println(if(iR - iL + 1 <= 0) 0 else iR - iL + 1)\n}"}], "src_uid": "724fa4b1d35b8765048857fa8f2f6802"} {"source_code": "object Main extends App {\n\n import java.io._\nimport java.util\nimport java.util.{Locale, StringTokenizer, TreeSet}\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn \n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n val m = in.nextInt\n\n case class Edge(u: Int, v: Int, w: Int, var taked: Boolean = false)\n var edges = new Array[Edge](m+1)\n\n for (i <- 0 until m) {\n edges(i) = Edge(in.nextInt - 1, in.nextInt - 1, in.nextInt)\n }\n\n edges(m) = Edge(0, 0, Int.MaxValue)\n edges = edges.sortBy(_.w)\n\n val max = new Array[Int](n)\n val taked = new Array[Boolean](m)\n val dsu = new DSU(n)\n var sum = 0\n var cnt = 0\n\n var set = new mutable.TreeSet[(Int, Int, Int)]\n\n var prevw = -1\n for (e <- edges) {\n\n if (e.w != prevw) {\n for ((x, y, z) <- set)\n if (dsu.get(x) != dsu.get(y)) {\n dsu.union(x, y)\n sum += z\n }\n else {\n cnt += 1\n }\n set = new mutable.TreeSet[(Int, Int, Int)]\n prevw = e.w\n }\n\n if (dsu.get(e.u) != dsu.get(e.v)) {\n val x = dsu.get(e.u)\n val y = dsu.get(e.v)\n //System.err.println(x + \" \" + y + \" \" + e.w)\n val t = (x min y, x max y, e.w)\n if (set contains t)\n cnt += 1\n else\n set.add(t)\n }\n }\n\n //System.err.println(sum)\n\n out.print(cnt)\n\n out.flush()\n out.close()\n\n class DSU(n: Int) {\n val set = new Array[Int](n).zipWithIndex.map(p => p._2)\n\n def get(a: Int): Int = {\n if (set(a) == a)\n a\n else {\n set(a) = get(set(a))\n set(a)\n }\n }\n\n def union(a: Int, b: Int): Unit = {\n val x = get(a)\n val y = get(b)\n if (x != y) set(x) = y;\n }\n\n }\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}", "positive_code": [{"source_code": "\n\nobject Main2 extends App {\n \n import java.io._\nimport java.util\nimport java.util.{Locale, StringTokenizer, TreeSet}\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn \n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n val m = in.nextInt\n\n case class Edge(u: Int, v: Int, w: Int, var taked: Boolean = false)\n var edges = new Array[Edge](m+1)\n\n for (i <- 0 until m) {\n edges(i) = Edge(in.nextInt - 1, in.nextInt - 1, in.nextInt)\n }\n\n edges(m) = Edge(0, 0, Int.MaxValue)\n edges = edges.sortBy(_.w)\n\n val max = new Array[Int](n)\n val taked = new Array[Boolean](m)\n val dsu = new DSU(n)\n var sum = 0\n var cnt = 0\n\n var set = new mutable.TreeSet[(Int, Int, Int)]\n\n var prevw = -1\n for (e <- edges) {\n\n if (e.w != prevw) {\n for ((x, y, z) <- set)\n if (dsu.get(x) != dsu.get(y)) {\n dsu.union(x, y)\n sum += z\n }\n else {\n cnt += 1\n }\n set = new mutable.TreeSet[(Int, Int, Int)]\n prevw = e.w\n }\n\n if (dsu.get(e.u) != dsu.get(e.v)) {\n val x = e.u\n val y = e.v\n //System.err.println(x + \" \" + y + \" \" + e.w)\n val t = (x, y, e.w)\n set.add(t)\n }\n }\n\n //System.err.println(sum)\n\n out.print(cnt)\n\n out.flush()\n out.close()\n\n class DSU(n: Int) {\n val set = new Array[Int](n).zipWithIndex.map(p => p._2)\n\n def get(a: Int): Int = {\n if (set(a) == a)\n a\n else {\n set(a) = get(set(a))\n set(a)\n }\n }\n\n def union(a: Int, b: Int): Unit = {\n val x = get(a)\n val y = get(b)\n if (x != y) set(x) = y;\n }\n\n }\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}"}], "negative_code": [], "src_uid": "92afa6f770493109facb1b9ca8d94e0c"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\nobject B {\n def solve(in: Input, out: PrintWriter): Unit = {\n val ladders = new Array[Long](31)\n ladders(0) = 1\n for (i <- 1 until ladders.length) {\n ladders(i) = (1L << (2 * i)) + 2 * ladders(i - 1)\n }\n\n for (_ <- 0 until in.nextInt()) {\n var z = in.nextLong()\n var i = 0\n while (i < ladders.length && ladders(i) <= z) {\n z -= ladders(i)\n i += 1\n }\n out.println(i)\n }\n }\n\n private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(\n (\"4\\n1\\n8\\n6\\n1000000000000000000\", \"1\\n2\\n1\\n30\", \"Sample\")\n )\n\n def main(args: Array[String]): Unit = {\n if (args.length == 0) {\n val input = new Input(new InputStreamReader(System.in))\n val output = new PrintWriter(System.out)\n solve(input, output)\n output.close()\n input.close()\n } else {\n for ((in, ans, name) <- makeTests()) {\n val input = new Input(new StringReader(in))\n val output = new StringWriter()\n val pwOutput = new PrintWriter(output)\n val t0 = System.nanoTime()\n solve(input, pwOutput)\n val time = System.nanoTime() - t0\n pwOutput.close()\n output.close()\n val result = output.toString\n if (ans.trim != result.trim) {\n throw new RuntimeException(s\"Test '$name': expected '$ans' found '$result'\")\n } else {\n println(s\"Test '$name' was solved in ${time / 1e9} seconds\")\n }\n }\n }\n }\n\n class Input(stream: Reader) extends Closeable {\n private[this] val reader = new BufferedReader(stream)\n private[this] var tokenizer = new StringTokenizer(reader.readLine())\n\n @tailrec\n final def nextToken(): String = if (tokenizer.hasMoreTokens) tokenizer.nextToken() else {\n tokenizer = new StringTokenizer(reader.readLine())\n nextToken()\n }\n\n def nextInt(): Int = nextToken().toInt\n def nextLong(): Long = nextToken().toLong\n def nextDouble(): Double = nextToken().toDouble\n\n override def close(): Unit = reader.close()\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val x = readLong()\n\n @annotation.tailrec\n def go(x: Long, n: Long, count: Int): Int = {\n val req = n * (n + 1) / 2\n\n if (x - req >= 0) go(x - req, n + n + 1, count + 1)\n else count\n }\n\n val ans = go(x, 1, 0)\n\n println(ans)\n }\n}\n"}], "negative_code": [], "src_uid": "f0806ab99cf4da228abe3cd8073884d9"} {"source_code": "import io.Source\nimport java.io.PrintWriter\n\nobject CF292E {\n\n def solve(in: In, out: PrintWriter) {\n val n, m = in().toInt\n val a = Array.fill(n)(in().toInt)\n val b = Array.fill(n)(in().toInt)\n val size = {\n var k = 1\n while (k < n) {\n k *= 2\n }\n k\n }\n val offset = Array.fill(size + n - 1)(-1)\n def update(n: Int, nl: Int, nr: Int, l: Int, r: Int, v: Int) {\n if (l <= nl && nr <= r) {\n offset(n) = v + nl - l\n } else if (r > nl && nr > l) {\n if (offset(n) != -1) {\n offset(2 * n + 1) = offset(n)\n offset(2 * n + 2) = offset(n) + (nr - nl) / 2\n offset(n) = -1\n }\n val mid = (nl + nr) / 2\n update(2 * n + 1, nl, mid, l, r, v)\n update(2 * n + 2, mid, nr, l, r, v)\n }\n }\n def get(n: Int, nl: Int, nr: Int, i: Int): Int = {\n if (offset(n) != -1) {\n a(offset(n) + (i - nl))\n } else if (nl + 1 == nr) {\n b(i)\n } else {\n val mid = (nl + nr) / 2\n if (i < mid) {\n get(2 * n + 1, nl, mid, i)\n } else {\n get(2 * n + 2, mid, nr, i)\n }\n }\n }\n for (it <- 0 until m) {\n if (in().toInt == 1) {\n val x, y = in().toInt - 1\n val k = in().toInt\n update(0, 0, size, y, y + k, x)\n //out.println(offset.deep)\n } else {\n out.println(get(0, 0, size, in().toInt - 1))\n }\n }\n }\n\n def main(args: Array[String]) {\n val in: In = new In(Source.fromInputStream(System.in))\n val out: PrintWriter = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() {\n while (iter.hasNext && delims.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next(): String = {\n skipDelims()\n while (iter.hasNext && delims.indexOf(iter.head) == -1) {\n sb.append(iter.next())\n }\n val ret = sb.toString()\n sb.clear()\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIterator = new TokenIterator(iter, \" \\r\\n\")\n\n val lineIterator = new TokenIterator(iter, \"\\r\\n\")\n\n def apply() = tokenIterator.next()\n\n def apply(n: Int) = tokenIterator.take(n)\n }\n}", "positive_code": [{"source_code": "/*\nE. Копирование данных\nограничение по времени на тест\n2 секунды\nограничение по памяти на тест\n256 мегабайт\nввод\nstandard input\nвывод\nstandard output\n\nОчень часто приходится копировать большие объемы данных. Такая операция может потребовать больших затрат компьютерных ресурсов. В связи с этим, в этой задаче вам предлагается придумать способ быстрого копирования некоторой части одного массива чисел в другой.\n\nБолее формально, вам задано два массива целых чисел a1, a2, ..., an и b1, b2, ..., bn длины n. Также есть m запросов двух типов:\n\n Скопировать подотрезок массива a длины k, начиная с позиции x, в массив b, начиная с позиции y, то есть выполнить by + q = ax + q для всех целых q (0 ≤ q < k). Операция задана корректно — оба подотрезка целиком содержатся в массивах a и b соответственно.\n Определить значение в позиции x массива b, то есть найти значение bx. \n\nДля каждого запроса второго типа выведите результат — значение соответствующего элемента массива b.\nВходные данные\n\nВ первой строке через пробел заданы два целых числа n и m (1 ≤ n, m ≤ 105) — количество элементов в массивах и количество запросов соответственно. Во второй строке задан массив целых чисел a1, a2, ..., an (|ai| ≤ 109). В третьей строке задан массив целых чисел b1, b2, ..., bn (|bi| ≤ 109).\n\nВ следующих m строках заданы описания запросов. В i-ой строке сначала задано целое число ti — тип i-го запроса (1 ≤ ti ≤ 2). Если ti = 1, то i-ый запрос обозначает операцию копирования, если ti = 2, то i-ый запрос обозначает взятие значения в массиве b. Если ti = 1, то после типа запроса записаны три целых числа xi, yi, ki (1 ≤ xi, yi, ki ≤ n) — параметры запроса копирования. Если ti = 2, то следом, после типа запроса, в строке записано целое число xi (1 ≤ xi ≤ n) — позиция в массиве b.\n\nВсе числа в строках разделены одиночными пробелами. Гарантируется, что все запросы корректны, то есть границы копирования не выходят за границы массивов a и b.\nВыходные данные\n\nДля каждого запроса второго типа в отдельную строку выведите результат.\nПримеры тестов\nВходные данные\n\n5 10\n1 2 0 -1 3\n3 1 5 -2 0\n2 5\n1 3 3 3\n2 5\n2 4\n2 1\n1 2 1 4\n2 1\n2 4\n1 4 2 1\n2 2\n\nВыходные данные\n\n0\n3\n-1\n3\n2\n3\n-1\n*/\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.Stack\n\nobject CrocRound1Task5 extends App {\n\n def solve(a: Array[Long], b: IndexedSeq[Long], actions: Seq[Action]): Seq[Long] = {\n // val now = System.currentTimeMillis\n val tree = MutableSegmentTree.fromSeq(b)\n // println(\"tree built in \" + (System.currentTimeMillis - now))\n solve(a, tree, actions)\n }\n\n def solve(a: Array[Long], tree: MutableSegmentTree[Long], actions: Seq[Action]): Seq[Long] = {\n val toPrint = ArrayBuffer.empty[Long]\n actions foreach (action => action match {\n case c: Copy => tree.updateRange(c.posB - 1, c.posB + c.length - 2)(i => a(i - c.posB + c.posA))\n case Find(p) => toPrint += tree(p - 1)\n })\n toPrint\n }\n\n val (n, m) = {\n val l = readLine split ' ' map (_.toInt)\n (l(0), l(1))\n }\n val a = readLine split ' ' map (_.toLong)\n val b = readLine split ' ' map (_.toLong)\n val actions: IndexedSeq[Action] = (0 until m) map { _ =>\n val s = readLine split ' ' map (_.toInt)\n if (s(0) == 1) Copy(s(1), s(2), s(3))\n else Find(s(1))\n }\n val res = solve(a, b, actions)\n res foreach (x => println(x))\n}\n\nabstract class Action {}\n\ncase class Copy(val posA: Int, val posB: Int, val length: Int) extends Action {}\n\ncase class Find(val pos: Int) extends Action {}\n\n// SegmentTree impl copy-paste\nabstract class MutableSegmentTree[T] {\n def range = start to end\n def size = end - start + 1\n def start: Int\n def end: Int\n\n def apply(i: Int): T\n def left: Option[MutableSegmentTree[T]]\n def right: Option[MutableSegmentTree[T]]\n def updateRange(lb: Int, rb: Int)(f: Int => T): Unit\n def update(f: Int => T): Unit\n}\n\nobject MutableSegmentTree {\n\n def fromSeq[T](data: IndexedSeq[T]): MutableSegmentTree[T] = {\n def formTreeRec(nodes: Seq[MutableSegmentTree[T]]): MutableSegmentTree[T] = {\n if (nodes.size == 1) nodes.head\n else {\n // Optimized, doesn't use grouped(2)\n val united = for (i <- 0 until nodes.size by 2) yield {\n if (i == nodes.size - 1) SegNode(nodes(i))\n else SegNode(nodes(i), nodes(i + 1))\n }\n formTreeRec(united)\n }\n }\n val leaves = (0 until data.size) map (i => leaf(i, data(i)))\n formTreeRec(leaves)\n }\n\n private def leaf[T](i: Int, d: T) = new SegLeaf(i, d)\n}\n\nclass SegNode[T](val l: MutableSegmentTree[T],\n val r: Option[MutableSegmentTree[T]],\n val start: Int,\n val end: Int,\n var func: Option[Int => T]) extends MutableSegmentTree[T] {\n def left = Some(l)\n def right = r\n\n def hasRightBranch = r.isDefined\n\n def apply(i: Int): T = {\n require(i >= start && i <= end, \"index is out of bounds\")\n if (func.isDefined) {\n (func.get)(i)\n } else if (i >= l.start && i <= l.end) {\n l(i)\n } else {\n (r.get)(i)\n }\n }\n\n def updateRange(lb: Int, rb: Int)(f: Int => T): Unit = {\n if (within(start, end, lb, rb)) {\n update(f)\n } else if (intersects(start, end, lb, rb)) {\n // Optimized routine\n if (func.isDefined) {\n val f2 = func.get\n if (!within(l.start, l.end, lb, rb)) l update f2\n r foreach (r =>\n if (!within(r.start, r.end, lb, rb)) r update f2)\n }\n if (intersects(l.start, l.end, lb, rb)) l.updateRange(lb, rb)(f)\n r foreach (r =>\n if (intersects(r.start, r.end, lb, rb)) r.updateRange(lb, rb)(f))\n this.func = None\n }\n }\n\n def update(f: Int => T): Unit = {\n this.func = Some(f)\n }\n\n /** Checks whether (start to end) is within (lb to rb) */\n private def within(start: Int, end: Int, lb: Int, rb: Int) = {\n start >= lb && start <= rb && end >= lb && end <= rb\n }\n\n /** Checks whether (start to end) and (lb to rb) has points in common */\n private def intersects(start: Int, end: Int, lb: Int, rb: Int) = {\n (start >= lb && start <= rb) || (end >= lb && end <= rb) || (lb >= start && lb <= end) || (rb >= start && rb <= end)\n }\n\n override def equals(that: Any) = that match {\n case that: SegNode[T] => this.start == that.start && this.end == that.end && this.l == that.l && this.r == that.r && this.func == that.func\n case _ => false\n }\n override def hashCode = (start * 7) ^ (end * 13) ^ (l.hashCode * 17) ^ (r.map(_.hashCode).getOrElse(0) * 31)\n override def toString = {\n if (func.isDefined) ((start to end) map func.get) mkString \" \"\n else if (!r.isDefined) l.toString\n else l.toString + \" \" + r.get.toString\n }\n}\n\nobject SegNode {\n def apply[T](l: MutableSegmentTree[T]) = {\n new SegNode(l, None, l.start, l.end, None)\n }\n\n def apply[T](l: MutableSegmentTree[T],\n r: MutableSegmentTree[T]) = {\n require(r.start == l.end + 1, \"Right node range should start immediately after left\")\n new SegNode(l, Some(r), l.start, r.end, None)\n }\n}\n\nclass SegLeaf[T](val index: Int, var data: T) extends MutableSegmentTree[T] {\n override val size = 1\n\n def start = index\n def end = index\n def left = None\n def right = None\n\n def apply(i: Int): T = {\n require(i == index, \"index is out of bounds\")\n data\n }\n\n def updateRange(from: Int, to: Int)(f: Int => T): Unit = {\n if (index >= from && index <= to) update(f)\n }\n\n def update(f: Int => T): Unit = {\n data = f(index)\n }\n\n override def equals(that: Any) = that match {\n case that: SegLeaf[T] => this.index == that.index && this.data == that.data\n case _ => false\n }\n override def hashCode = (index * 17) ^ (data.hashCode * 31)\n override def toString = data.toString\n}"}], "negative_code": [{"source_code": "/*\nE. Копирование данных\nограничение по времени на тест\n2 секунды\nограничение по памяти на тест\n256 мегабайт\nввод\nstandard input\nвывод\nstandard output\n\nОчень часто приходится копировать большие объемы данных. Такая операция может потребовать больших затрат компьютерных ресурсов. В связи с этим, в этой задаче вам предлагается придумать способ быстрого копирования некоторой части одного массива чисел в другой.\n\nБолее формально, вам задано два массива целых чисел a1, a2, ..., an и b1, b2, ..., bn длины n. Также есть m запросов двух типов:\n\n Скопировать подотрезок массива a длины k, начиная с позиции x, в массив b, начиная с позиции y, то есть выполнить by + q = ax + q для всех целых q (0 ≤ q < k). Операция задана корректно — оба подотрезка целиком содержатся в массивах a и b соответственно.\n Определить значение в позиции x массива b, то есть найти значение bx. \n\nДля каждого запроса второго типа выведите результат — значение соответствующего элемента массива b.\nВходные данные\n\nВ первой строке через пробел заданы два целых числа n и m (1 ≤ n, m ≤ 105) — количество элементов в массивах и количество запросов соответственно. Во второй строке задан массив целых чисел a1, a2, ..., an (|ai| ≤ 109). В третьей строке задан массив целых чисел b1, b2, ..., bn (|bi| ≤ 109).\n\nВ следующих m строках заданы описания запросов. В i-ой строке сначала задано целое число ti — тип i-го запроса (1 ≤ ti ≤ 2). Если ti = 1, то i-ый запрос обозначает операцию копирования, если ti = 2, то i-ый запрос обозначает взятие значения в массиве b. Если ti = 1, то после типа запроса записаны три целых числа xi, yi, ki (1 ≤ xi, yi, ki ≤ n) — параметры запроса копирования. Если ti = 2, то следом, после типа запроса, в строке записано целое число xi (1 ≤ xi ≤ n) — позиция в массиве b.\n\nВсе числа в строках разделены одиночными пробелами. Гарантируется, что все запросы корректны, то есть границы копирования не выходят за границы массивов a и b.\nВыходные данные\n\nДля каждого запроса второго типа в отдельную строку выведите результат.\nПримеры тестов\nВходные данные\n\n5 10\n1 2 0 -1 3\n3 1 5 -2 0\n2 5\n1 3 3 3\n2 5\n2 4\n2 1\n1 2 1 4\n2 1\n2 4\n1 4 2 1\n2 2\n\nВыходные данные\n\n0\n3\n-1\n3\n2\n3\n-1\n*/\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.Stack\n\nobject CrocRound1Task5 extends App {\n\n type Range = ((Int, Int))\n def solve(a: Array[Long], b: Array[Long], actions: Seq[Action]): Seq[Long] = {\n val ranges = Stack.empty[Copy]\n val toPrint = ArrayBuffer.empty[Long]\n actions foreach {\n case c: Copy => ranges push c\n case Find(p) => toPrint += find(a, b, ranges, p)\n }\n toPrint\n }\n\n def find(a: Array[Long], b: Array[Long], ranges: Seq[Copy], pos: Int): Long = {\n val lastCopy = ranges find (c => pos >= c.posB && pos <= c.posB + c.length)\n if (lastCopy.isDefined) {\n val copy = lastCopy.get\n val shift = pos - copy.posB\n a(copy.posA + shift - 1)\n } else {\n b(pos - 1)\n }\n }\n\n val (n, m) = {\n val l = readLine split ' ' map (_.toInt)\n (l(0), l(1))\n }\n val a = readLine split ' ' map (_.toLong)\n val b = readLine split ' ' map (_.toLong)\n val actions: Seq[Action] = (0 until m) map { _ =>\n val s = readLine split ' ' map (_.toInt)\n if (s(0) == 1) Copy(s(1), s(2), s(3))\n else Find(s(1))\n }\n val res = solve(a, b, actions)\n res map (x => println(x))\n}\n\nabstract class Action {}\n\ncase class Copy(val posA: Int, val posB: Int, val length: Int) extends Action {}\n\ncase class Find(val pos: Int) extends Action {}"}, {"source_code": "/*\nE. Копирование данных\nограничение по времени на тест\n2 секунды\nограничение по памяти на тест\n256 мегабайт\nввод\nstandard input\nвывод\nstandard output\n\nОчень часто приходится копировать большие объемы данных. Такая операция может потребовать больших затрат компьютерных ресурсов. В связи с этим, в этой задаче вам предлагается придумать способ быстрого копирования некоторой части одного массива чисел в другой.\n\nБолее формально, вам задано два массива целых чисел a1, a2, ..., an и b1, b2, ..., bn длины n. Также есть m запросов двух типов:\n\n Скопировать подотрезок массива a длины k, начиная с позиции x, в массив b, начиная с позиции y, то есть выполнить by + q = ax + q для всех целых q (0 ≤ q < k). Операция задана корректно — оба подотрезка целиком содержатся в массивах a и b соответственно.\n Определить значение в позиции x массива b, то есть найти значение bx. \n\nДля каждого запроса второго типа выведите результат — значение соответствующего элемента массива b.\nВходные данные\n\nВ первой строке через пробел заданы два целых числа n и m (1 ≤ n, m ≤ 105) — количество элементов в массивах и количество запросов соответственно. Во второй строке задан массив целых чисел a1, a2, ..., an (|ai| ≤ 109). В третьей строке задан массив целых чисел b1, b2, ..., bn (|bi| ≤ 109).\n\nВ следующих m строках заданы описания запросов. В i-ой строке сначала задано целое число ti — тип i-го запроса (1 ≤ ti ≤ 2). Если ti = 1, то i-ый запрос обозначает операцию копирования, если ti = 2, то i-ый запрос обозначает взятие значения в массиве b. Если ti = 1, то после типа запроса записаны три целых числа xi, yi, ki (1 ≤ xi, yi, ki ≤ n) — параметры запроса копирования. Если ti = 2, то следом, после типа запроса, в строке записано целое число xi (1 ≤ xi ≤ n) — позиция в массиве b.\n\nВсе числа в строках разделены одиночными пробелами. Гарантируется, что все запросы корректны, то есть границы копирования не выходят за границы массивов a и b.\nВыходные данные\n\nДля каждого запроса второго типа в отдельную строку выведите результат.\nПримеры тестов\nВходные данные\n\n5 10\n1 2 0 -1 3\n3 1 5 -2 0\n2 5\n1 3 3 3\n2 5\n2 4\n2 1\n1 2 1 4\n2 1\n2 4\n1 4 2 1\n2 2\n\nВыходные данные\n\n0\n3\n-1\n3\n2\n3\n-1\n*/\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.Stack\n\nobject CrocRound1Task5 extends App {\n\n def solve(a: Array[Long], b: Array[Long], actions: Seq[Action]): Seq[Long] = {\n val tree = SegmentTree.fromSeq(b)\n val ranges = Stack.empty[Copy]\n val toPrint = ArrayBuffer.empty[Long]\n actions.foldLeft(tree)((tree, action) => action match {\n case Copy(pa, pb, len) => tree.updatedRange((pb - 1) until (pb + len - 1), i => a(i - pb + pa))\n case Find(p) => { toPrint += tree(p - 1); tree }\n })\n toPrint\n }\n\n val (n, m) = {\n val l = readLine split ' ' map (_.toInt)\n (l(0), l(1))\n }\n val a = readLine split ' ' map (_.toLong)\n val b = readLine split ' ' map (_.toLong)\n val actions: Seq[Action] = (0 until m) map { _ =>\n val s = readLine split ' ' map (_.toInt)\n if (s(0) == 1) Copy(s(1), s(2), s(3))\n else Find(s(1))\n }\n val res = solve(a, b, actions)\n res foreach (x => println(x))\n}\n\nabstract class Action {}\n\ncase class Copy(val posA: Int, val posB: Int, val length: Int) extends Action {}\n\ncase class Find(val pos: Int) extends Action {}\n\n// SegmentTree impl copy-paste\nabstract class SegmentTree[T] {\n def size: Int\n def range: Range\n def apply(i: Int): T\n def updatedRange(r: Range, f: Int => T): SegmentTree[T]\n def updated(f: Int => T): SegmentTree[T]\n}\n\nobject SegmentTree {\n\n def fromSeq[T](data: Seq[T]): SegmentTree[T] = {\n def unite(nodes: Seq[SegmentTree[T]]) = {\n if (nodes.length == 2) SegNode(nodes(0), nodes(1))\n else if (nodes.length == 1) SegNode(nodes(0))\n else throw new RuntimeException(\"Wrong collections to unite\")\n }\n def formTreeRec(nodes: Seq[SegmentTree[T]]): SegmentTree[T] = {\n if (nodes.size == 1) nodes.head\n else {\n val united = (nodes grouped 2) map unite\n formTreeRec(united.toSeq)\n }\n }\n val iData = data.toIndexedSeq\n val leaves = (0 until iData.size) map (i => leaf(i, iData(i)))\n formTreeRec(leaves)\n }\n\n private def leaf[T](i: Int, d: T) = new SegLeaf(i, d)\n}\n\ncase class SegNode[T](val left: SegmentTree[T],\n val right: Option[SegmentTree[T]],\n val range: Range,\n val func: Option[Int => T]) extends SegmentTree[T] {\n require(range.step == 1, \"non-standard ranges aren't supported\")\n\n def size = range.size\n\n def hasRightBranch = right.isDefined\n\n def apply(i: Int): T = {\n require(range contains i, \"index is out of bounds\")\n if (func.isDefined) {\n (func.get)(i)\n } else if (left.range contains i) {\n left(i)\n } else {\n (right.get)(i)\n }\n }\n\n def updatedRange(r: Range, f: Int => T): SegmentTree[T] = {\n if (within(range, r)) {\n updated(f)\n } else if (intersects(range, r)) {\n new SegNode(left.updatedRange(r, f), right map (_.updatedRange(r, f)), range, None)\n } else {\n this\n }\n }\n\n def updated(f: Int => T): SegmentTree[T] = {\n new SegNode(left, right, range, Some(f))\n }\n\n override def toString = {\n if (!right.isDefined) left.toString\n else left.toString + \" \" + right.get.toString\n }\n\n /** Checks whether r1 is within r2 */\n private def within(r1: Range, r2: Range) = {\n r2.contains(r1.start) && r2.contains(r1.end)\n }\n\n /** Checks whether r1 and r2 has points in common */\n private def intersects(r1: Range, r2: Range) = {\n r2.contains(r1.start) || r2.contains(r1.end) || r1.contains(r2.start) || r1.contains(r2.end)\n }\n}\n\nobject SegNode {\n def apply[T](l: SegmentTree[T]) = {\n new SegNode(l, None, l.range, None)\n }\n\n def apply[T](l: SegmentTree[T],\n r: SegmentTree[T]) = {\n val lr = l.range\n val rr = r.range\n require(rr.start == lr.end + 1, \"Right node range should start immediately after left\")\n new SegNode(l, Some(r), l.range.start to r.range.end, None)\n }\n}\n\ncase class SegLeaf[T](val index: Int, val data: T) extends SegmentTree[T] {\n val size = 1\n lazy val range = index to index\n override def toString = data.toString\n\n def apply(i: Int): T = {\n require(i == index, \"index is out of bounds\")\n data\n }\n\n def updatedRange(r: Range, f: Int => T): SegmentTree[T] = {\n if (r contains index) updated(f)\n else this\n }\n\n def updated(f: Int => T): SegmentTree[T] =\n new SegLeaf[T](index, f(index))\n}"}], "src_uid": "27c703f9846064af2b0deab93d394272"} {"source_code": "object Solution extends App {\n\n def gcd(a: Int, b: Int): Int = {\n if (b == 0)\n a\n else\n gcd(b, a % b)\n }\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt).toList\n val d = data.tail.foldLeft(data.head) {\n case (prev, el) => gcd(prev, el)\n }\n// println(d)\n if ((data.max / d - data.length) % 2== 1)\n println(\"Alice\")\n else\n println(\"Bob\")\n}\n", "positive_code": [{"source_code": "import scala.collection._\n\nobject A extends App {\n \n def gcd(x: Int, y: Int): Int =\n if (y == 0) x\n else gcd(y, x % y)\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val n = readString.toInt\n val as = readInts(n)\n \n val g = as.reduce(gcd)\n val max = as.max\n val moves = max / g - n\n\n println(if (moves % 2 == 1) \"Alice\" else \"Bob\")\n}"}, {"source_code": "object C {\n def gcd(a: Int, b: Int): Int = {\n if (b == 0)\n a\n else\n gcd(b, a % b)\n }\n def main(args: Array[String]) {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n val t = (Nil : Seq[Int]).toBuffer\n for (i <- 1 to n)\n t += sc.nextInt\n val g = t.fold(t.head)(gcd(_, _))\n val cnt = t.sorted.last / g - t.size\n if (cnt % 2 == 1)\n println(\"Alice\")\n else\n println(\"Bob\")\n }\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport scala.math._\n\nobject Main {\n\t\n\tdef gcd(a : Int, b : Int) : Int = if (b==0) a else gcd(b,a%b)\n\t\n\tdef main(args: Array[String]) { \n\t\tval n = in.rdInt\n\t\tvar a = (for (i <- 1 to n) yield in.rdInt).sorted\n\t\tvar z = a(0)\n\t\tfor (i <- 1 until n) z = gcd(z,a(i))\t\n\t\tprintln( if ((a(n-1)/z-n)%2 == 1) \"Alice\" else \"Bob\" )\n\t}\n\n\tobject in {\n\t\tval in = new BufferedReader(new InputStreamReader(System.in))\n\t\tvar st = new StringTokenizer(\"\")\n\n\t\tdef next : String = {\n\t\t\twhile (!st.hasMoreTokens) {\n\t\t\t\tval line = in.readLine\n\t\t\t\tif (line == null) return null\n\t\t\t\teat(line)\n\t\t\t}\n\t\t\tst.nextToken\n\t\t}\n\t\t\n\t\tdef FastReader = eat(\"\")\n\t\tdef eat(s : String) = st = new StringTokenizer(s)\n\t\tdef rdInt = next.toInt\n\t\tdef rdLong = next.toLong\n\t\tdef rdDouble = next.toDouble\n\t}\n\t\n}\n"}, {"source_code": "object C347 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def gcd(x: Int, y: Int): Int = {\n if(x == 0) y else gcd(y % x, x)\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n val finalgcd = input.foldLeft(input(0)){case (g, n) => gcd(g, n)}\n if((input.max/finalgcd - n) % 2 == 0) {\n println(\"Bob\")\n } else {\n println(\"Alice\")\n }\n }\n}"}], "negative_code": [{"source_code": "object C347 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n if((input.max - n) % 2 == 0) {\n println(\"Bob\")\n } else {\n println(\"Alice\")\n }\n }\n}"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport scala.math._\n\nobject Main {\n\t\n\tdef main(args: Array[String]) { \n\t\tval n = in.rdInt\n\t\tvar a = (for (i <- 1 to n) yield in.rdInt).sorted\n\t\tvar m = true\n\t\tfor (i <- 1 until n)\n\t\t\tif (a(i)%a(0)!=0) m=false\n\t\tif (m) println( if (a(n-1)/a(0)%2 == 1) \"Alice\" else \"Bob\" )\n\t\telse println( if ( (a(n-1)-n)%2 == 1) \"Alice\" else \"Bob\" )\n\t}\n\n\tobject in {\n\t\tval in = new BufferedReader(new InputStreamReader(System.in))\n\t\tvar st = new StringTokenizer(\"\")\n\n\t\tdef next : String = {\n\t\t\twhile (!st.hasMoreTokens) {\n\t\t\t\tval line = in.readLine\n\t\t\t\tif (line == null) return null\n\t\t\t\teat(line)\n\t\t\t}\n\t\t\tst.nextToken\n\t\t}\n\t\t\n\t\tdef FastReader = eat(\"\")\n\t\tdef eat(s : String) = st = new StringTokenizer(s)\n\t\tdef rdInt = next.toInt\n\t\tdef rdLong = next.toLong\n\t\tdef rdDouble = next.toDouble\n\t}\n\t\n}\n"}], "src_uid": "3185ae6b4b681a10a21d02e67f08fd19"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val previousIndex = Array.ofDim[Int](100001)\n val distance = Array.ofDim[Int](100001)\n data.indices.foreach { i =>\n val value = data(i)\n val d = distance(value)\n if (d == 0) {\n if (previousIndex(value) != 0) {\n distance(value) = i + 1 - previousIndex(value)\n }\n previousIndex(value) = i + 1\n } else if (d > 0) {\n if (d == i + 1 - previousIndex(value))\n previousIndex(value) = i + 1\n else\n distance(value) = -1\n }\n }\n val res = (1 to 100000).collect{\n case (i) if previousIndex(i) != 0 && distance(i) != -1 => s\"$i ${distance(i)}\"\n }\n println(res.length)\n println(res.mkString(\"\\n\"))\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P352B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n // N integers\n // a_1, ..., a_n\n // needs to find all values of x\n // x occurs in a_i\n // positions must form an arithmetic progression\n\n def solve(): Unit = {\n val N = sc.nextInt\n val idx = Array.fill(100001)(-1)\n val p, freq = Array.fill(100001)(0)\n\n @tailrec\n def loop(i: Int): Unit = {\n if (i == N) ()\n else {\n val x = sc.nextInt\n if (freq(x) < 0) ()\n else if (idx(x) < 0) {\n idx(x) = i\n freq(x) = 1\n }\n else if (p(x) == 0) {\n p(x) = i - idx(x)\n idx(x) = i\n freq(x) = 2\n }\n else if (idx(x) + p(x) == i) {\n idx(x) = i\n freq(x) += 1\n }\n else {\n freq(x) = -1\n }\n loop(i + 1)\n }\n }\n\n loop(0)\n out.println(freq.count(_ > 0))\n (1 to 100000).filter(freq(_) > 0).foreach { x =>\n out.println(x + \" \" + p(x))\n }\n }\n\n solve\n out.close\n}\n"}, {"source_code": "object JeffandPeriods {\n def main(args: Array[String]): Unit = {\n var n: Int = readInt\n var count,differ: Int = 0\n var input: String = readLine\n var test = new Array[String](1000000)\n var rar = new Array[Int](1000000) \n var indexes = new Array[Int](10000000)\n var fault = new Array[Int](1000000) \n var answers = new Array[String](10000000)\n var differs = new Array[Int](10000000)\n test = input.split(' ')\n for ( i <- 0 to n-1 ) {\n if ( rar(test(i).toInt) == 0 ) {\n rar(test(i).toInt) = 1\n indexes(test(i).toInt) = i;\n }\n else {\n rar(test(i).toInt) = rar(test(i).toInt) + 1\n if ( rar(test(i).toInt) == 2 ) {\n differ = i - indexes(test(i).toInt)\n differs(test(i).toInt) = differ\n }\n else \n differ = i - indexes(test(i).toInt)\n if ( differ != differs(test(i).toInt) )\n fault(test(i).toInt) = 1\n else\n indexes(test(i).toInt) = i\n }\n }\n for ( i <- 0 to 100000 )\n if (( rar(i) != 0 ) && ( fault(i) != 1 )) {\n answers(count) = i.toString +\" \"+ differs(i)\n count = count + 1\n }\n println(count);\n for ( i <- 0 to count-1 )\n println(answers(i))\n }\n\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val indexValue = data.indices.foldLeft(Map.empty[Int, List[Int]]) {\n case (acc, i) => acc + (data(i) -> (i :: acc.getOrElse(data(i), Nil)))\n }\n\n val res = indexValue.flatMap{\n case (value, list) if list.length == 1 => Some((value, 0))\n case (value, list) =>\n val distance = list.head - list(1)\n if (list.sliding(2).forall(i => i.head - i(1) == distance))\n Some(value, distance)\n else\n None\n }\n\n println(res.size)\n println(res.map{case (v, d) => s\"$v $d\"}.mkString(\"\\n\"))\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val indexValue = data.indices.foldLeft(Map.empty[Int, (Int, Int)]) {\n case (acc, i) if !acc.contains(data(i)) =>\n acc + (data(i) -> (i, 0))\n case (acc, i) if acc(data(i))._2 == -1 => acc\n case (acc, i) if acc(data(i))._2 == 0 =>\n acc + (data(i) -> (i, i - acc(data(i))._1))\n case (acc, i) =>\n val distance = i - acc(data(i))._1\n acc + (data(i) -> (i, if (acc(data(i))._2 == distance) distance else - 1))\n }\n println(indexValue.filter(_._2._2 >= 0).keys.toList.sorted.map{case v => s\"$v ${indexValue(v)._2}\"}.mkString(\"\\n\"))\n\n}"}, {"source_code": "object JeffandPeriods {\n def main(args: Array[String]): Unit = {\n var n: Int = readInt\n var z,min,minpos,d: Int = 1000000\n var test = new Array[String](100000)\n var indexes = new Array[Int](100000)\n var input: String = readLine\n var answer: Boolean = false\n test = input.split(' ')\n for ( i <- 0 to n-1)\n indexes(i) = i\n for ( i <- 0 to n-1) {\n min = 100000\n minpos =indexes(i)\n for ( j <- i to n-1)\n if (test(indexes(j)).toInt < min) {\n min = test(indexes(j)).toInt\n minpos = j\n }\n z = indexes(minpos)\n indexes(minpos) = indexes(i)\n indexes(i) = z\n }\n z = 0\n while ( z != n) {\n min = z\n while ( (z < n-1) && (test(indexes(z)) == test(indexes(z+1))) )\n z = z + 1\n minpos = z\n if ( (minpos - min) == 0)\n println(test(indexes(z))+\" \"+0.toString)\n else {\n answer = true\n d = indexes(min+1) - indexes(min)\n for ( j <- min to minpos-1)\n if ((indexes(j+1)-indexes(j)) != d)\n answer = false\n if (answer == true)\n println(test(indexes(z))+\" \"+d.toString)\n }\n z = z + 1\n }\n }\n\n}"}, {"source_code": "object JeffandPeriods {\n def main(args: Array[String]): Unit = {\n var n: Int = readInt\n var count,z,min,minpos,d: Int = 1000000\n var test = new Array[String](100000)\n var indexes = new Array[Int](100000)\n var input: String = readLine\n var answer: Boolean = false\n var answers = new Array[String](10000000)\n count = 0\n test = input.split(' ')\n for ( i <- 0 to n-1)\n indexes(i) = i\n for ( i <- 0 to n-1) {\n min = 100000\n minpos =indexes(i)\n for ( j <- i to n-1)\n if (test(indexes(j)).toInt < min) {\n min = test(indexes(j)).toInt\n minpos = j\n }\n z = indexes(minpos)\n indexes(minpos) = indexes(i)\n indexes(i) = z\n }\n z = 0\n while ( z != n) {\n min = z\n while ( (z < n-1) && (test(indexes(z)) == test(indexes(z+1))) )\n z = z + 1\n minpos = z\n if ( (minpos - min) == 0) {\n answers(count) = test(indexes(z))+\" \"+0.toString\n count = count + 1\n }\n else {\n answer = true\n d = indexes(min+1) - indexes(min)\n for ( j <- min to minpos-1)\n if ((indexes(j+1)-indexes(j)) != d)\n answer = false\n if (answer == true) {\n answers(count) = test(indexes(z))+\" \"+d.toString\n count = count + 1\n }\n }\n z = z + 1\n }\n println(count)\n for ( i<-0 to count-1)\n println(answers(i))\n }\n\n}"}, {"source_code": "object JeffandPeriods {\n def main(args: Array[String]): Unit = {\n var n: Int = readInt\n var count,differ: Int = 0\n var input: String = readLine\n var test = new Array[String](1000000)\n var rar = new Array[Int](1000000) \n var indexes = new Array[Int](10000000)\n var fault = new Array[Int](1000000) \n var answers = new Array[String](10000000)\n var differs = new Array[Int](10000000)\n test = input.split(' ')\n for ( i <- 0 to n-1 ) {\n if ( rar(test(i).toInt) == 0 ) {\n rar(test(i).toInt) = 1\n indexes(test(i).toInt) = i;\n }\n else {\n rar(test(i).toInt) = rar(test(i).toInt) + 1\n if ( rar(test(i).toInt) == 2 ) {\n differ = i - indexes(test(i).toInt)\n differs(test(i).toInt) = differ\n }\n else \n differ = i - indexes(test(i).toInt)\n if ( differ != differs(test(i).toInt) )\n fault(test(i).toInt) = 1\n else\n indexes(test(i).toInt) = i\n }\n }\n for ( i <- 0 to 99999 )\n if (( rar(i) != 0 ) && ( fault(i) != 1 )) {\n answers(count) = i.toString +\" \"+ differs(i)\n count = count + 1\n }\n println(count);\n for ( i <- 0 to count-1 )\n println(answers(i))\n }\n\n}"}, {"source_code": "object JeffandPeriods {\n def main(args: Array[String]): Unit = {\n var n: Int = readInt\n var z,min,minpos,d: Int = 1000000\n var test = new Array[String](100000)\n var indexes = new Array[Int](100000)\n var input: String = readLine\n var answer: Boolean = false\n test = input.split(' ')\n for ( i <- 0 to n-1)\n indexes(i) = i\n for ( i <- 0 to n-1) {\n min = 100000\n minpos =indexes(i)\n for ( j <- i to n-1)\n if (test(indexes(j)).toInt < min) {\n min = test(indexes(j)).toInt\n minpos = j\n }\n z = indexes(minpos)\n indexes(minpos) = indexes(i)\n indexes(i) = z\n }\n z = 0\n while ( z != n) {\n min = z\n while ( (z < n-1) && (test(indexes(z)) == test(indexes(z+1))) )\n z = z + 1\n minpos = z\n if ( (minpos - min) == 0)\n println(test(indexes(z)),0)\n else {\n answer = true\n d = indexes(min+1) - indexes(min)\n for ( j <- min to minpos-1)\n if ((indexes(j+1)-indexes(j)) != d)\n answer = false\n if (answer == true)\n println(test(indexes(z)),d)\n }\n z = z + 1\n }\n }\n\n}"}], "src_uid": "097e35b5e9c96259c54887158ebff544"} {"source_code": "object Solution {\n def main(args: Array[String]) {\n val r = new Reader()\n val n, k = r.read[Int]\n val ls, as = r.read[Array[Long]](n)\n val zs = ls.zip(as)\n val ps = zs.map{ case (l, a) => l * a }.sum\n val pfs = pf(zs.map{ case (l, a) => l * (1 - a) })\n \n println(ps + (1 to n - k + 1).foldLeft(0.toLong) {\n case (acc, i) => math.max(acc, pfs(i + k - 1) - pfs(i - 1))\n })\n }\n \n def pf(as: Array[Long]) = as.scanLeft(0.toLong){ case (acc, a) => a + acc }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def this() = this(new InputStreamReader(System.in))\n\n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n\n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n implicit val double: Read[Double] = new Read(_.read[String].toDouble)\n \n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n \n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n}", "positive_code": [{"source_code": "object A {\n def main(args: Array[String]) {\n val t = scala.io.StdIn.readLine().split(\" \").map( _.toInt );\n val n = t(0);\n val k = t(1);\n var as = scala.io.StdIn.readLine().split(\" \").map( _.toInt );\n var ts = scala.io.StdIn.readLine().split(\" \").map( _.toInt );\n var s = 0;\n var dif = Array.ofDim[Int](n);\n var max_dif = 0;\n for(i <- 0 until n){\n if(ts(i) == 0) s += as(i);\n if(i - k >= 0 && ts(i - k) == 0)\n s -= as(i - k);\n if(i - k + 1 >= 0)\n dif(i - k + 1) = s;\n max_dif = math.max(max_dif, s);\n }\n var ans = 0;\n for(i <- 0 until n){\n if(ts(i) == 1)\n ans += as(i);\n }\n println(ans + max_dif);\n }\n}"}], "negative_code": [], "src_uid": "0fbac68f497fe189ee088c13d0488cce"} {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val MOD = 1000000007L\n\n case class M1x2(a11: Long, a12: Long) {\n\n def +(b: M1x2) = M1x2(\n (a11 + b.a11) % MOD,\n (a12 + b.a12) % MOD)\n\n def *(b: M2x2) = M1x2(\n (a11 * b.a11 + a12 * b.a21) % MOD,\n (a11 * b.a12 + a12 * b.a22) % MOD)\n\n }\n\n val FibStart = M1x2(0, 1)\n\n case class M2x2(a11: Long, a12: Long, a21: Long, a22: Long) {\n\n def *(b: M2x2) = M2x2(\n (a11 * b.a11 + a12 * b.a21) % MOD,\n (a11 * b.a12 + a12 * b.a22) % MOD,\n (a21 * b.a11 + a22 * b.a21) % MOD,\n (a21 * b.a12 + a22 * b.a22) % MOD)\n\n def pow(n: Long) = {\n var pow2 = this\n var res = M2x2.Unit\n var deg = n\n\n while (deg > 0) {\n if ((deg & 1) != 0) res *= pow2\n pow2 *= pow2\n deg >>= 1\n }\n\n res\n }\n\n }\n\n object M2x2 {\n\n val Unit = M2x2(\n 1, 0,\n 0, 1)\n\n val FibMul = M2x2(\n 0, 1,\n 1, 1)\n }\n\n def fib(n: Long) = FibStart * M2x2.FibMul.pow(n)\n\n case class SegTree(as: Array[M1x2]) {\n\n val NEUTRAL = M1x2(0, 0) // neutral element in respect of operation used (+)\n\n val n = as.length\n val t = Array.fill(4 * Integer.highestOneBit(n))(NEUTRAL)\n val lazyMul = Array.fill(4 * Integer.highestOneBit(n))(M2x2.Unit)\n build(1, 0, n - 1)\n\n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n build(v2, tl, tm)\n build(v2 + 1, tm + 1, tr)\n t(v) = t(v2) + t(v2 + 1)\n }\n }\n\n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Long = {\n if (l > r) 0\n else if (l == tl && r == tr) t(v).a11\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n\n lazyMul(v2) *= lazyMul(v)\n lazyMul(v2 + 1) *= lazyMul(v)\n t(v2) *= lazyMul(v)\n t(v2 + 1) *= lazyMul(v)\n lazyMul(v) = M2x2.Unit\n\n (query(l, Math.min(r, tm), v2, tl, tm) +\n query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)) % MOD\n }\n }\n\n def update(l: Int, r: Int, mul: M2x2, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n if (l == tl && r == tr) {\n lazyMul(v) *= mul\n t(v) *= mul\n } else if (l <= r) {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n update(l, Math.min(r, tm), mul, v2, tl, tm)\n update(Math.max(l, tm + 1), r, mul, v2 + 1, tm + 1, tr)\n t(v) = (t(v2) + t(v2 + 1)) * lazyMul(v)\n }\n }\n\n }\n\n val Array(n, m) = readInts(2)\n val as = readInts(n)\n val st = SegTree(as.map(x => fib(x)))\n\n val res = ArrayBuffer.empty[Long]\n\n for (_ <- 0 until m) {\n\n val s = readLine\n val tl = new java.util.StringTokenizer(s)\n\n if (s.startsWith(\"1\")) {\n val Array(_, l, r, x) = Array.fill(4)(tl.nextToken.toInt)\n st.update(l - 1, r - 1, M2x2.FibMul.pow(x))\n } else {\n val Array(_, l, r) = Array.fill(3)(tl.nextToken.toInt)\n res += st.query(l - 1, r - 1)\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\"\\n\"))\n\n Console.flush\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val MOD = 1000000007L\n\n final case class M1x2(a11: Long, a12: Long) {\n\n def +(b: M1x2) = M1x2(\n (a11 + b.a11) % MOD,\n (a12 + b.a12) % MOD)\n\n def *(b: M2x2) = M1x2(\n (a11 * b.a11 + a12 * b.a21) % MOD,\n (a11 * b.a12 + a12 * b.a22) % MOD)\n\n }\n\n val FibStart = M1x2(0, 1)\n\n final case class M2x2(a11: Long, a12: Long, a21: Long, a22: Long) {\n\n def *(b: M2x2) = M2x2(\n (a11 * b.a11 + a12 * b.a21) % MOD,\n (a11 * b.a12 + a12 * b.a22) % MOD,\n (a21 * b.a11 + a22 * b.a21) % MOD,\n (a21 * b.a12 + a22 * b.a22) % MOD)\n\n def pow(n: Long) = {\n var pow2 = this\n var res = M2x2.Unit\n var deg = n\n\n while (deg > 0) {\n if ((deg & 1) != 0) res *= pow2\n pow2 *= pow2\n deg >>= 1\n }\n\n res\n }\n\n }\n\n object M2x2 {\n\n val Unit = M2x2(\n 1, 0,\n 0, 1)\n\n val FibMul = M2x2(\n 0, 1,\n 1, 1)\n }\n\n def fib(n: Long) = FibStart * M2x2.FibMul.pow(n)\n\n case class SegTree(as: Array[M1x2]) {\n\n val NEUTRAL = M1x2(0, 0) // neutral element in respect of operation used (+)\n\n val n = as.length\n val t = Array.fill(4 * Integer.highestOneBit(n))(NEUTRAL)\n val lazyMul = Array.fill(4 * Integer.highestOneBit(n))(M2x2.Unit)\n build(1, 0, n - 1)\n\n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n build(v2, tl, tm)\n build(v2 + 1, tm + 1, tr)\n t(v) = t(v2) + t(v2 + 1)\n }\n }\n\n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Long = {\n if (l > r) 0\n else if (l == tl && r == tr) t(v).a11\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n\n lazyMul(v2) *= lazyMul(v)\n lazyMul(v2 + 1) *= lazyMul(v)\n t(v2) *= lazyMul(v)\n t(v2 + 1) *= lazyMul(v)\n lazyMul(v) = M2x2.Unit\n\n (query(l, Math.min(r, tm), v2, tl, tm) +\n query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)) % MOD\n }\n }\n\n def update(l: Int, r: Int, mul: M2x2, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n if (l == tl && r == tr) {\n lazyMul(v) *= mul\n t(v) *= mul\n } else if (l <= r) {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n update(l, Math.min(r, tm), mul, v2, tl, tm)\n update(Math.max(l, tm + 1), r, mul, v2 + 1, tm + 1, tr)\n t(v) = (t(v2) + t(v2 + 1)) * lazyMul(v)\n }\n }\n\n }\n\n val Array(n, m) = readInts(2)\n val as = readInts(n)\n val st = SegTree(as.map(x => fib(x)))\n\n val res = ArrayBuffer.empty[Long]\n\n for (_ <- 0 until m) {\n\n val s = readLine\n val tl = new java.util.StringTokenizer(s)\n\n if (s.startsWith(\"1\")) {\n val Array(_, l, r, x) = Array.fill(4)(tl.nextToken.toInt)\n st.update(l - 1, r - 1, M2x2.FibMul.pow(x))\n } else {\n val Array(_, l, r) = Array.fill(3)(tl.nextToken.toInt)\n res += st.query(l - 1, r - 1)\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\"\\n\"))\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val MOD = 1000000007\n\n case class M1x2(a11: Long, a12: Long) {\n\n def +(other: M1x2) = M1x2(\n (this.a11 + other.a11) % MOD,\n (this.a12 + other.a12) % MOD)\n\n def *(other: M2x2) = M1x2(\n (this.a11 * other.a11 + this.a12 * other.a21) % MOD,\n (this.a11 * other.a12 + this.a12 * other.a22) % MOD)\n\n }\n\n val FibStart = M1x2(1, 1)\n\n case class M2x2(a11: Long, a12: Long, a21: Long, a22: Long) {\n\n def *(other: M2x2) = M2x2(\n (this.a11 * other.a11 + this.a12 * other.a21) % MOD,\n (this.a11 * other.a12 + this.a12 * other.a22) % MOD,\n (this.a21 * other.a11 + this.a22 * other.a21) % MOD,\n (this.a21 * other.a12 + this.a22 * other.a22) % MOD)\n\n def pow(n: Long) = {\n var pow2 = this\n var res = M2x2.Unit\n var deg = n\n\n while (deg > 0) {\n if ((deg & 1) != 0) res *= pow2\n pow2 *= pow2\n deg >>= 1\n }\n\n res\n }\n\n }\n\n object M2x2 {\n val Unit = M2x2(1, 0, 0, 1)\n val Fib = M2x2(0, 1, 1, 1)\n }\n\n case class SegTree(as: Array[M1x2]) {\n\n val NEUTRAL = M1x2(0, 0) // neutral element in respect of operation used (+)\n\n val n = as.length\n val t = Array.fill(4 * Integer.highestOneBit(n))(NEUTRAL)\n val lazyMul = Array.fill(4 * Integer.highestOneBit(n))(M2x2.Unit)\n build(1, 0, n - 1)\n\n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n build(v2, tl, tm)\n build(v2 + 1, tm + 1, tr)\n t(v) = t(v2) + t(v2 + 1)\n }\n }\n\n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Long = {\n if (l > r) 0\n else if (l == tl && r == tr) t(v).a11\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n\n lazyMul(v2) *= lazyMul(v)\n lazyMul(v2 + 1) *= lazyMul(v)\n t(v2) *= lazyMul(v)\n t(v2 + 1) *= lazyMul(v)\n lazyMul(v) = M2x2.Unit\n\n (query(l, Math.min(r, tm), v2, tl, tm) +\n query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)) % MOD\n }\n }\n\n def update(l: Int, r: Int, mul: M2x2, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n if (l == tl && r == tr) {\n lazyMul(v) *= mul\n t(v) *= mul\n } else if (l <= r) {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n update(l, Math.min(r, tm), mul, v2, tl, tm)\n update(Math.max(l, tm + 1), r, mul, v2 + 1, tm + 1, tr)\n t(v) = (t(v2) + t(v2 + 1)) * lazyMul(v)\n }\n }\n\n }\n\n val Array(n, m) = readInts(2)\n val as = readInts(n)\n val st = SegTree(as.map(x => FibStart * M2x2.Fib.pow(x - 1)))\n\n val res = ArrayBuffer.empty[Long]\n\n for (_ <- 0 until m) {\n\n val s = readLine\n val tl = new java.util.StringTokenizer(s)\n\n if (s.startsWith(\"1\")) {\n val Array(_, l, r, x) = Array.fill(4)(tl.nextToken.toInt)\n st.update(l - 1, r - 1, M2x2.Fib.pow(x))\n } else {\n val Array(_, l, r) = Array.fill(3)(tl.nextToken.toInt)\n res += st.query(l - 1, r - 1)\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\"\\n\"))\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val MOD = 1000000007\n\n case class M1x2(a11: Long, a12: Long) {\n\n def +(other: M1x2) = M1x2(\n (this.a11 + other.a11) % MOD,\n (this.a12 + other.a12) % MOD)\n\n def *(other: M2x2) = M1x2(\n (this.a11 * other.a11 + this.a12 * other.a21) % MOD,\n (this.a11 * other.a12 + this.a12 * other.a22) % MOD)\n\n }\n\n val FibStart = M1x2(1, 1)\n\n case class M2x2(a11: Long, a12: Long, a21: Long, a22: Long) {\n\n def *(other: M2x2) = M2x2(\n (this.a11 * other.a11 + this.a12 * other.a21) % MOD,\n (this.a11 * other.a12 + this.a12 * other.a22) % MOD,\n (this.a21 * other.a11 + this.a22 * other.a21) % MOD,\n (this.a21 * other.a12 + this.a22 * other.a22) % MOD)\n\n def pow(n: Long) = {\n var pow2 = this\n var res = M2x2.Unit\n var deg = n\n\n while (deg > 0) {\n if ((deg & 1) != 0) res *= pow2\n pow2 *= pow2\n deg >>= 1\n }\n\n res\n }\n\n }\n\n object M2x2 {\n val Unit = M2x2(1, 0, 0, 1)\n val Fib = M2x2(0, 1, 1, 1)\n }\n\n case class SegTree(as: Array[M1x2]) {\n\n val NEUTRAL = M1x2(0, 0) // neutral element in respect of operation used (+)\n\n val n = as.length\n val t = Array.fill(4 * Integer.highestOneBit(n))(NEUTRAL)\n val lazyMul = Array.fill(4 * Integer.highestOneBit(n))(M2x2.Unit)\n build(1, 0, n - 1)\n\n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n build(v2, tl, tm)\n build(v2 + 1, tm + 1, tr)\n t(v) = t(v2) + t(v2 + 1)\n }\n }\n\n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Long = {\n if (l > r) 0\n else if (l == tl && r == tr) t(v).a11\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n\n lazyMul(v2) *= lazyMul(v)\n lazyMul(v2 + 1) *= lazyMul(v)\n t(v2) *= lazyMul(v)\n t(v2 + 1) *= lazyMul(v)\n lazyMul(v) = M2x2.Unit\n\n (query(l, Math.min(r, tm), v2, tl, tm) +\n query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)) % MOD\n }\n }\n\n def update(l: Int, r: Int, mul: M2x2, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n if (l == tl && r == tr) {\n lazyMul(v) *= mul\n t(v) *= mul\n } else if (l <= r) {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n update(l, Math.min(r, tm), mul, v2, tl, tm)\n update(Math.max(l, tm + 1), r, mul, v2 + 1, tm + 1, tr)\n t(v) = t(v2) + t(v2 + 1)\n }\n }\n\n }\n\n val Array(n, m) = readInts(2)\n val as = readInts(n)\n val st = SegTree(as.map(x => FibStart * M2x2.Fib.pow(x - 1)))\n\n val res = ArrayBuffer.empty[Long]\n\n for (_ <- 0 until m) {\n\n val s = readLine\n val tl = new java.util.StringTokenizer(s)\n\n if (s.startsWith(\"1\")) {\n val Array(_, l, r, x) = Array.fill(4)(tl.nextToken.toInt)\n st.update(l - 1, r - 1, M2x2.Fib.pow(x))\n } else {\n val Array(_, l, r) = Array.fill(3)(tl.nextToken.toInt)\n res += st.query(l - 1, r - 1)\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\"\\n\"))\n\n Console.flush\n}\n"}], "src_uid": "64224070d793e242070b1094aa967b13"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C153A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C153A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n var a: Array[Int] = _\n\n def solve(): Unit = {\n val n = ni()\n val d = ni()\n\n a = na(n)\n\n val ans = a.zipWithIndex.map { f =>\n val x = (bs(f._2, n-1, f._1 + d + 1) - f._2 - 1).toLong\n// println(bs(f._2, n-1, f._1 + d + 1) + \" \" +x)\n if(x >= 2) {\n (x*(x-1))/2\n }\n else 0L\n }.sum\n out.println(ans)\n }\n\n def bs(st: Int, en: Int, tar: Long): Int = {\n var l = st\n var r = en\n while (r > l) {\n val m = l + (r - l) / 2\n if(a(m) >= tar) r = m\n else l = m+1\n }\n if(a(l) < tar) l+1\n else l\n }\n}\n", "positive_code": [{"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\nimport java.util.Scanner\n\nobject test6 extends App {\n val Array(n,d)=readLine.split(\" \").map(_.toInt)\n val arr=readLine.split(\" \").map(_.toInt)\n val dp=new Array[Long](n)\n val sum=new Array[Long](n)\n sum(0)=0\n for(i<-1 until n) sum(i)=sum(i-1)+i-1\n \n var i=0\n var j=0\n while(j d =>\n val newFirst = (first to i).find(j => data(i) - data(j) <= d).get\n val newSum = sum + (first until newFirst).map(count(_, i - 1)).sum\n (newFirst, newSum)\n case ((first, sum), i) => (first, sum)\n }\n println(res._2 + (res._1 until n).map(count(_, n - 1)).sum)\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, d) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n\n def count(first: Int, last: Int) = {\n if (last - first < 2)\n 0\n else {\n val diff = last - first\n diff * (diff - 1) / 2\n }\n }\n\n val res = (1 until n).foldLeft(0, 0) {\n case ((first, sum), i) if data(i) - data(first) > d =>\n val newFirst = (first to i).find(j => data(i) - data(j) <= d).get\n val newSum = sum + (first until newFirst).map(count(_, i - 1)).sum\n (newFirst, newSum)\n case ((first, sum), i) => (first, sum)\n }\n println(res._2 + (res._1 until n).map(count(_, n - 1)).sum)\n}\n"}, {"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\nimport java.util.Scanner\n\nobject test6 extends App {\n val Array(n,d)=readLine.split(\" \").map(_.toInt)\n val arr=readLine.split(\" \").map(_.toInt)\n val dp=new Array[Long](n)\n val sum=new Array[Int](n)\n sum(0)=0\n for(i<-1 until n) sum(i)=sum(i-1)+i-1\n \n var i=0\n var j=0\n while(j1) dp(i)+=math.max(0,j-i-1)\n j+=1\n }\n else{\n i+=1\n if(j-i>1) dp(i)=math.max(0,dp(i-1)-(j-i-1))\n }\n }\n for(k<-i+1 to n-3){\n dp(k)=math.max(0, dp(k-1)-(n-1-i-1))\n }\n //println(dp.mkString(\",\"))\n println(dp.sum)\n} \n\n\n"}, {"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\nimport java.util.Scanner\n\nobject test6 extends App {\n val Array(n,d)=readLine.split(\" \").map(_.toInt)\n val arr=readLine.split(\" \").map(_.toInt)\n val dp=new Array[Int](n)\n val sum=new Array[Int](n)\n sum(0)=0\n for(i<-1 until n) sum(i)=sum(i-1)+i-1\n \n var i=0\n var j=0\n while(j c2 || n != 1) {\n println(\"-1\")\n } else {\n println(c2 - c1 + c2)\n }\n }\n }\n}", "positive_code": [{"source_code": "//package codeforces.contests._1374\n\n/*\nhttps://codeforces.com/contest/1374/problem/B\n */\nobject MultiplyByTwoDivideBySix {\n\n @scala.annotation.tailrec\n def countFactors(n: Int, m: Int, acc: Int = 0): Int =\n if (n == 1 || n % m != 0) acc else countFactors(n / m, m, acc + 1)\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt()) {\n val n = io.StdIn.readInt()\n\n val twos = countFactors(n, 2)\n val threes = countFactors(n, 3)\n\n val noOtherFactors = (math.pow(2, twos) * math.pow(3, threes)).toInt == n\n\n println {\n if (n == 1) 0\n else if (noOtherFactors && threes >= twos) threes + (threes - twos)\n else -1\n }\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject CF653_B extends App {\n var t = readInt()\n while (t > 0) {\n t -= 1;\n\n var n = readInt()\n var (cnt2, cnt3) = (0, 0)\n while (n % 3 == 0) {\n n /= 3\n cnt3 += 1\n }\n while (n % 2 == 0) {\n n /= 2\n cnt2 += 1\n }\n\n if (n > 1 || cnt3 < cnt2) {\n println(-1)\n// sys.exit()\n } else {\n println(2 * cnt3 - cnt2)\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CF653A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CF653A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val n = ni()\n if(n == 1) out.println(\"0\")\n else {\n var cnt3 = 0\n var x = n\n while (x > 0 && x % 3 == 0) {\n cnt3 += 1\n x /= 3\n }\n\n var cnt2 = 0\n while (x > 0 && x % 2 == 0) {\n cnt2 += 1\n x /= 2\n }\n\n if(cnt2 > cnt3 || x > 1) out.println(\"-1\")\n else out.println(cnt2 + (cnt3 - cnt2) * 2)\n }\n }\n }\n\n}\n"}, {"source_code": "object a{\n def main(args: Array[String]) = {\n val n: Int = scala.io.StdIn.readInt()\n for(i <- 1 to n){\n var x: Int = scala.io.StdIn.readInt()\n var ans = 0\n var done = false\n while(!done){\n if(x == 1){\n done = true\n }\n else if(x%6 == 0){\n x /= 6;\n ans += 1\n }\n else if(x%3 == 0){\n x /= 3\n ans += 2\n }\n else{\n ans = -1\n done = true\n }\n }\n println(ans)\n }\n }\n}\n"}, {"source_code": "\nobject B extends App {\n\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n\n /* Implicit methods */\n\n// val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val n = in.nextInt()\n\n n.times {\n val number = in.nextInt()\n var number2 = number\n var noOfTwos = 0\n var noOfThrees = 0\n\n while (number2 % 2 == 0) {\n number2 = number2 / 2\n noOfTwos = noOfTwos + 1\n }\n\n while (number2 % 3 == 0) {\n number2 = number2 / 3\n noOfThrees = noOfThrees + 1\n }\n\n if (number == 1) {\n println(0)\n } else if (number2 > 1) {\n println(-1)\n } else {\n if (noOfTwos == noOfThrees) {\n println(noOfTwos)\n } else if (noOfThrees > noOfTwos) {\n val diff = noOfThrees - noOfTwos\n println(noOfTwos + (diff * 2))\n } else {\n println(-1)\n }\n }\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n\n}\n"}], "negative_code": [], "src_uid": "3ae468c425c7b156983414372fd35ab8"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C627C(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C627C(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val s = ('R' + ns() + 'R').toCharArray\n\n val n = s.length\n var prev = 0\n var mx = -1\n REP(n) { i =>\n if(i > 0 && s(i) == 'R') {\n mx = Math.max(mx, i - prev)\n prev = i\n }\n }\n out.println(mx)\n }\n }\n}\n", "positive_code": [{"source_code": "object _1324C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val instrs = io.read[String]\n\n val ans = ('R' + instrs + 'R')\n .zipWithIndex\n .collect({case ('R', i) => i})\n .sliding(2)\n .map({case Seq(i, j) => j - i})\n .max\n\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "6451507b21854d5b81aeaf0491ddf584"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val employees = Array.ofDim[Array[Int]](n) // employee -> language\n val markedEmployees = Array.ofDim[Boolean](n) // is employee marked\n val languages = Array.fill[List[Int]](m){List.empty} // language -> employee\n val markedLanguages = Array.ofDim[Boolean](m) // is language marked\n\n def mark(employee: Int) = {\n if (!markedEmployees(employee)) {\n// println(\"mark employee \" + employee)\n markedEmployees(employee) = true\n employees(employee).foreach { markLanguage }\n }\n }\n\n def markLanguage(language: Int) {\n if (!markedLanguages(language)) {\n// println(\"mark language \" + language)\n markedLanguages(language) = true\n languages(language).foreach {\n mark\n }\n }\n }\n\n (0 until n).foreach { j =>\n val data = in.next().split(' ').tail.map(_.toInt - 1)\n employees(j) = data\n data.foreach { i => languages(i) ::= j }\n }\n val res = (0 until n).foldLeft(0) {\n case (acc, j) if markedEmployees(j) => acc\n case (acc, j) =>\n mark(j)\n acc + 1\n }\n println(Math.max(res - 1, employees.count(_.isEmpty)))\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\nimport scala.collection.mutable\n\nobject Solution2 {\n class Graph(vertices: List[Int]) {\n\n val neighbours: Array[List[Int]] = Array.fill(vertices.length)(List.empty)\n\n def addConnection(a: Int, b: Int): Unit = neighbours(a) = b :: neighbours(a)\n\n def getNeighbours(v: Int): List[Int] = neighbours(v)\n\n def dfs(now: Int, visited: Array[Boolean], f: Int => Unit): Unit = {\n f(now)\n visited(now) = true\n getNeighbours(now) foreach { x => if (!visited(x)) dfs(x, visited, f) }\n }\n\n def connectedComponentsAmWithFilter(p: Int => Boolean): Int = {\n val visited: Array[Boolean] = Array.fill(vertices.length)(false)\n\n (vertices filter p).foldLeft(0) {\n (sol, x) =>\n if (!visited(x)) {\n dfs(x, visited, { x => visited(x) = true })\n sol + 1\n }\n else sol\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readLine split \" \" map { _.toInt }\n val g: Graph = new Graph((0 until (n + m)).toList)\n var allZero = true\n 0 until n foreach {\n i =>\n val line = readLine split \" \" map { _.toInt }\n val k = line(0)\n if (k > 0) allZero = false\n 1 to k foreach { j =>\n val lang = line(j)\n g.addConnection(i, n + lang - 1)\n g.addConnection(n - 1 + lang, i)\n }\n }\n if (allZero) println(n)\n else println(g.connectedComponentsAmWithFilter({ x => 0 <= x && x < n}) - 1)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C170A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C170A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val m = ni()\n val col = Array.fill[Boolean](n,m)(false)\n val adjA = Array.fill[Boolean](m,m)(false)\n\n REP(n) { i =>\n val k = ni()\n var prev = -1\n REP(k) { _ =>\n val j = ni()\n col(i)(j-1) = true\n if(prev == -1) prev = j-1\n else {\n adjA(prev)(j-1) = true\n adjA(j-1)(prev) = true\n prev = j-1\n }\n }\n }\n\n adjL = adjA.map(f => f.zipWithIndex.filter(p => p._1).map(_._2).toList)\n marked = Array.fill(m)(false)\n var count = 0\n var yes = false\n REP(n) { i =>\n val x = col(i).zipWithIndex.find(p => p._1 && marked(p._2))\n if(x.isEmpty) {\n count += 1\n val y: Option[(Boolean, Int)] = col(i).zipWithIndex.find(p => p._1)\n if(y.isDefined) {\n yes = true\n marked(y.get._2) = true\n dfs(y.get._2)\n }\n }\n }\n out.println(if(yes) count-1 else count)\n }\n\n var adjL: Array[List[Int]] = _\n var marked: Array[Boolean] = _\n\n def dfs(u: Int): Unit = {\n adjL(u).foreach { p =>\n if(!marked(p)) {\n marked(p) = true\n dfs(p)\n }\n }\n }\n}\n"}, {"source_code": "object tmp extends App {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n\n class MyScanner(br: BufferedReader) {\n var st = new StringTokenizer(\"\")\n\n def this(is: InputStream) = this(new BufferedReader(new InputStreamReader(is)))\n\n private def next() = {\n\n while (!st.hasMoreElements) {\n st = new StringTokenizer(br.readLine())\n }\n st.nextToken()\n }\n\n def nextInt() = java.lang.Integer.parseInt(next())\n\n def nextLong() = java.lang.Long.parseLong(next())\n\n def nextLine() = br.readLine()\n }\n\n\n val sc = new MyScanner(System.in)\n val n = sc.nextInt()\n val m = sc.nextInt()\n val graph = Array.fill(n + m)(mutable.ArrayBuffer[Int]())\n var empl = 0\n var anyLeng = false\n while (empl < n) {\n val amount = sc.nextInt()\n var k = 0\n while (k < amount) {\n anyLeng = true\n val leng = sc.nextInt() - 1\n graph(empl) += n + leng\n graph(n + leng) += empl\n k += 1\n }\n empl += 1\n }\n val res = if (!anyLeng) n\n else {\n val groups = Array.fill(n)(-1)\n var curGroup = 0\n var v = 0\n while ( {v = 0; while (v < n && groups(v) != -1) v += 1; v < n}) {\n dfs(v)\n curGroup += 1\n }\n def dfs(v: Int): Unit = {\n if (v < n) {\n groups(v) = curGroup\n }\n val graphV = graph(v)\n val size = graphV.size\n var i = 0\n while (i < size) {\n val to = graphV(i)\n if (to >= n || groups(to) == -1) {\n dfs(to)\n }\n i += 1\n }\n }\n curGroup - 1\n }\n println(res)\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.collection.mutable\n\nobject Solution2 {\n class Graph(vertices: List[Int]) {\n\n val neighbours: Array[List[Int]] = Array.fill(vertices.length)(List.empty)\n\n def addConnection(a: Int, b: Int): Unit = neighbours(a) = b :: neighbours(a)\n\n def getNeighbours(v: Int): List[Int] = neighbours(v)\n\n def dfs(now: Int, visited: Array[Boolean]): Unit = {\n visited(now) = true\n getNeighbours(now) foreach { x => if (!visited(x)) dfs(x, visited) }\n }\n\n def connectedComponentsAmWithFilter(p: Int => Boolean): Int = {\n val visited: Array[Boolean] = Array.fill(vertices.length)(false)\n\n (vertices filter p).foldLeft(0) {\n (sol, x) =>\n if (!visited(x)) {\n dfs(x, visited)\n sol + 1\n }\n else sol\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readLine split \" \" map { _.toInt }\n val g: Graph = new Graph((0 until (n + m)).toList)\n var allZero = true\n 0 until n foreach {\n i =>\n val line = readLine split \" \" map { _.toInt }\n val k = line(0)\n if (k > 0) allZero = false\n 1 to k foreach { j =>\n val lang = line(j)\n g.addConnection(i, n + lang - 1)\n g.addConnection(n - 1 + lang, i)\n }\n }\n if (allZero) println(n)\n else println(g.connectedComponentsAmWithFilter({ x => 0 <= x && x < n}) - 1)\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val employees = Array.ofDim[Array[Int]](n) // employee -> language\n val markedEmployees = Array.ofDim[Boolean](n) // is employee marked\n val languages = Array.fill[List[Int]](m){List.empty} // language -> employee\n val markedLanguages = Array.ofDim[Boolean](m) // is language marked\n\n def mark(employee: Int) = {\n if (!markedEmployees(employee)) {\n// println(\"mark employee \" + employee)\n markedEmployees(employee) = true\n employees(employee).foreach { markLanguage }\n }\n }\n\n def markLanguage(language: Int) {\n if (!markedLanguages(language)) {\n// println(\"mark language \" + language)\n markedLanguages(language) = true\n languages(language).foreach {\n mark\n }\n }\n }\n\n (0 until n).foreach { j =>\n val data = in.next().split(' ').tail.map(_.toInt - 1)\n employees(j) = data\n data.foreach { i => languages(i) ::= j }\n }\n val res = (0 until n).foldLeft(0) {\n case (acc, j) if markedEmployees(j) => acc\n case (acc, j) =>\n mark(j)\n acc + 1\n }\n println(res - 1)\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C170A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C170A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val m = ni()\n val col = Array.fill[Boolean](n,m)(false)\n val adjA = Array.fill[Boolean](m,m)(false)\n\n REP(n) { i =>\n val k = ni()\n var prev = -1\n REP(k) { _ =>\n val j = ni()\n col(i)(j-1) = true\n if(prev == -1) prev = j-1\n else {\n adjA(prev)(j-1) = true\n adjA(j-1)(prev) = true\n prev = j-1\n }\n }\n }\n\n adjL = adjA.map(f => f.zipWithIndex.filter(p => p._1).map(_._2).toList)\n marked = Array.fill(m)(false)\n var count = 0\n\n REP(n) { i =>\n val x = col(i).zipWithIndex.find(p => p._1 && marked(p._2))\n if(x.isEmpty) {\n count += 1\n val y: Option[(Boolean, Int)] = col(i).zipWithIndex.find(p => p._1)\n if(y.isDefined) {\n marked(y.get._2) = true\n dfs(y.get._2)\n }\n }\n }\n out.println(count-1)\n }\n\n var adjL: Array[List[Int]] = _\n var marked: Array[Boolean] = _\n\n def dfs(u: Int): Unit = {\n adjL(u).foreach { p =>\n if(!marked(p)) {\n marked(p) = true\n dfs(p)\n }\n }\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\n\n\nobject Solution {\n \n class Graph[T](vertices: List[T]) {\n type Vertex = T\n type Connections = mutable.Map[Vertex, List[Vertex]]\n\n val neighbours: mutable.Map[Vertex, List[Vertex]] = mutable.Map.empty\n\n def addConnection(a: Vertex, b: Vertex): Unit = neighbours.put(a, b :: neighbours.getOrElse(a, List.empty[Vertex]))\n\n def getNeighbours(v: Vertex): List[Vertex] = neighbours.getOrElse(v, List.empty)\n\n def dfs(now: Vertex, visited: Set[Vertex], f: Vertex => Unit): Unit = {\n f(now)\n getNeighbours(now) filterNot { x => visited.contains(x) } foreach { x => dfs(x, visited + now, f) }\n }\n\n def connectedComponentsAm(): Int = {\n val visited: Set[Vertex] = Set.empty\n\n vertices.foldLeft(0) {\n (sol, x) =>\n if (!visited.contains(x)) {\n dfs(x, Set.empty, { x => visited + x }); sol + 1\n }\n else sol\n }\n }\n}\n \n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n val g: Graph[Int] = new Graph[Int]((1 to (n + m)).toList)\n 1 to n foreach {\n i =>\n val line = readLine.split(\" \").map(_.toInt)\n val k = line(0)\n 1 to k foreach { j =>\n val lang = line(j)\n g.addConnection(i, n + lang)\n g.addConnection(n + lang, i)\n }\n }\n g.connectedComponentsAm()\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.collection.mutable\n\nobject Solution {\n class Graph[T](vertices: List[T]) {\n type Vertex = T\n type Connections = mutable.Map[Vertex, List[Vertex]]\n\n val neighbours: mutable.Map[Vertex, List[Vertex]] = mutable.Map.empty\n\n def addConnection(a: Vertex, b: Vertex): Unit = neighbours.put(a, b :: neighbours.getOrElse(a, List.empty[Vertex]))\n\n def getNeighbours(v: Vertex): List[Vertex] = neighbours.getOrElse(v, List.empty)\n\n def dfs(now: Vertex, visited: Set[Vertex], f: Vertex => Unit): Unit = {\n f(now)\n getNeighbours(now) filterNot { x => visited.contains(x) } foreach { x => dfs(x, visited + now, f) }\n }\n\n def connectedComponentsAmWithFilter(p: Vertex => Boolean): Int = {\n var visited: Set[Vertex] = Set.empty\n\n (vertices filter p).foldLeft(0) {\n (sol, x) =>\n if (!visited.contains(x)) {\n dfs(x, Set.empty, { x => visited += x })\n sol + 1\n }\n else sol\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n val g: Graph[Int] = new Graph[Int]((1 to (n + m)).toList)\n 1 to n foreach {\n i =>\n val line = readLine.split(\" \").map(_.toInt)\n val k = line(0)\n 1 to k foreach { j =>\n val lang = line(j)\n g.addConnection(i, n + lang)\n g.addConnection(n + lang, i)\n }\n }\n println(g.connectedComponentsAmWithFilter({ x => 1 <= x && x <= n}) - 1)\n }\n}"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.collection.mutable\n\nobject Solution {\n class Graph[T](vertices: List[T]) {\n type Vertex = T\n type Connections = mutable.Map[Vertex, List[Vertex]]\n\n val neighbours: mutable.Map[Vertex, List[Vertex]] = mutable.Map.empty\n\n def addConnection(a: Vertex, b: Vertex): Unit = neighbours.put(a, b :: neighbours.getOrElse(a, List.empty[Vertex]))\n\n def getNeighbours(v: Vertex): List[Vertex] = neighbours.getOrElse(v, List.empty)\n\n def dfs(now: Vertex, visited: Set[Vertex], f: Vertex => Unit): Unit = {\n f(now)\n getNeighbours(now) filterNot { x => visited.contains(x) } foreach { x => dfs(x, visited + now, f) }\n }\n\n def connectedComponentsAm(): Int = {\n val visited: Set[Vertex] = Set.empty\n\n vertices.foldLeft(0) {\n (sol, x) =>\n if (!visited.contains(x)) {\n dfs(x, Set.empty, { x => visited + x }); sol + 1\n }\n else sol\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n val g: Graph[Int] = new Graph[Int]((1 to (n + m)).toList)\n 1 to n foreach {\n i =>\n val line = readLine.split(\" \").map(_.toInt)\n val k = line(0)\n 1 to k foreach { j =>\n val lang = line(j)\n g.addConnection(i, n + lang)\n g.addConnection(n + lang, i)\n }\n }\n println(g.connectedComponentsAm())\n }\n}\n"}], "src_uid": "e2836276aee2459979b232e5b29e6d57"} {"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextBoolean: Boolean = next.equalsIgnoreCase(\"1\")\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n\n override def toString = s\"MultiHashSet($map)\"\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n *\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n var posToRemove = 1\n var ans = 0\n var list = scala.collection.immutable.List[Int]()\n var howMuchToSkip = 0\n for (_ <- 0 until 2 * n) {\n val command = next\n if (command.equalsIgnoreCase(\"add\")) {\n val id = nextInt\n howMuchToSkip = 0\n list = id :: list\n } else {\n if (howMuchToSkip > 0) {\n howMuchToSkip -= 1\n posToRemove += 1\n } else if (list.isEmpty || list.head == posToRemove) {\n posToRemove += 1\n if (!list.isEmpty)\n list = list.tail\n } else {\n ans += 1\n posToRemove += 1\n //posToRemove += list.length\n howMuchToSkip = list.length\n list = Nil\n }\n }\n }\n out.println(ans)\n return 0\n }\n}\n", "positive_code": [{"source_code": "object _821C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n val n = read[Int]\n val golden, temp = collection.mutable.Stack.empty[Int]\n var ans, expected = 0\n\n repeat(2*n) {\n val cmd = read[String]\n cmd match {\n case \"add\" => temp.push(read[Int])\n case \"remove\" =>\n expected += 1\n val popped = if (temp.isEmpty) {\n golden.pop()\n } else if (temp.head == expected) {\n temp.pop()\n } else {\n ans += 1\n golden.pushAll(temp.sorted.reverse)\n temp.clear()\n golden.pop()\n }\n //assert(popped == expected)\n }\n //debug(cmd, golden, temp, expected, ans)\n }\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextBoolean: Boolean = next.equalsIgnoreCase(\"1\")\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n\n override def toString = s\"MultiHashSet($map)\"\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n *\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n var posToRemove = 1\n var ans = 0\n val set = new mutable.TreeSet[Int]()\n var list = scala.collection.immutable.List[Int]()\n var howMuchToSkip = 0\n for (_ <- 0 until 2 * n) {\n val command = next\n if (command.equalsIgnoreCase(\"add\")) {\n val id = nextInt\n set.add(id)\n list = id :: list\n } else {\n if (howMuchToSkip > 0) {\n howMuchToSkip -= 1\n }\n else if (list.head == posToRemove) {\n set.remove(list.head)\n posToRemove += 1\n list = list.tail\n } else {\n ans += 1\n set.clear()\n posToRemove += list.length\n howMuchToSkip = list.length\n list = Nil\n }\n }\n }\n out.println(ans)\n return 0\n }\n}\n"}], "src_uid": "2535fc09ce74b829c26e1ebfc1ee17c6"} {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport scala.util.Sorting.quickSort\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val writer = new PrintWriter(System.out)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {\r\n while (!st.hasMoreTokens) {\r\n st = new StringTokenizer(reader.readLine())\r\n }\r\n st.nextToken()\r\n }\r\n\r\n def readInt() = next.toInt\r\n def readLong() = next.toLong\r\n def readString() = next()\r\n\r\n def pow(a: Int, b: Int): Long = {\r\n if (b == 0) return 1\r\n\r\n val rs = pow(a, b / 2)\r\n rs * rs * (if (b % 2 == 0) 1 else a)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b\r\n\r\n def root(u: Int, p: Array[Int]): Int = {\r\n if (p(u) < 0) return u\r\n p(u) = root(p(u), p)\r\n p(u)\r\n }\r\n\r\n def join(u: Int, v: Int, p: Array[Int]): Unit = {\r\n var x = root(u, p)\r\n var y = root(v, p)\r\n if (x == y) return\r\n\r\n if (p(y) < p(x)) {\r\n val t = x\r\n x = y\r\n y = t\r\n }\r\n p(x) += p(y)\r\n p(y) = x\r\n }\r\n\r\n def main(args: Array[String]) {\r\n var t = readInt()\r\n while (t > 0) {\r\n t -= 1\r\n val (a,b,c,m) = (readInt(),readInt(),readInt(),readInt())\r\n\r\n val s = Array(a,b,c)\r\n val maxS = s.max\r\n val sumS = s.sum\r\n val maxP = sumS - 3\r\n val minP = maxS - (sumS - maxS) - 1\r\n if (m <= maxP && m >= minP) writer.println(\"YES\")\r\n else writer.println(\"NO\")\r\n\r\n\r\n }\r\n writer.close()\r\n }\r\n}", "positive_code": [{"source_code": "object B extends App {\r\n\r\n /** Assumption: a >= b >= c\r\n *\r\n * - Upper bound: (a - 1) + (b - 1) + (c - 1)\r\n * Example: \"aaaaabbbc\"\r\n *\r\n * - Lower bound: a - b - c - 1\r\n * Example: \"abacabacababaaa\"\r\n */\r\n def check(a: Int, b: Int, c: Int, m: Int): Boolean =\r\n m >= 2 * (a max b max c) - a - b - c - 1 && m <= a + b + c - 3\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(a, b, c, m) = nextInts(4)\r\n\r\n check(a, b, c, m) match {\r\n case true =>\r\n out.println(\"YES\")\r\n out.flush()\r\n case false =>\r\n out.println(\"NO\")\r\n out.flush()\r\n }\r\n }\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable._\r\nimport scala.math.max\r\n\r\nobject test {\r\n val writer = new PrintWriter(System.out)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\r\n def readInt(): Int = next().toInt\r\n def readLong(): Long = next().toLong\r\n def readString(): String = next()\r\n\r\n def main(args: Array[String]): Unit = {\r\n val t = readInt()\r\n for (tt <- 1 to t) {\r\n val a = readInt()\r\n val b = readInt()\r\n val c = readInt()\r\n val m = readInt()\r\n val sum = a + b + c\r\n val valid = max(0, a - 1) + max(0, b - 1) + max(0, c - 1)\r\n val mx = max(a, max(b, c))\r\n if (m > valid || m < mx-1-(sum-mx))\r\n writer.println(\"NO\")\r\n else\r\n writer.println(\"YES\")\r\n\r\n writer.flush()\r\n }\r\n }\r\n}"}], "negative_code": [{"source_code": "object B extends App {\r\n\r\n /** Assumption: a >= b >= c\r\n *\r\n * - Upper bound: (a - 1) + (b - 1) + (c - 1)\r\n * Example: \"aaaaabbbc\"\r\n *\r\n * - Lower bound: a - b - c - 1\r\n * Example: \"abacabacababaaa\"\r\n */\r\n def check(a: Int, b: Int, c: Int, m: Int): Boolean =\r\n m >= 2 * ((a max b max c) + (a min b min c)) - a - b - c - 1 && m <= a + b + c - 3\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(a, b, c, m) = nextInts(4)\r\n\r\n check(a, b, c, m) match {\r\n case true =>\r\n out.println(\"YES\")\r\n out.flush()\r\n case false =>\r\n out.println(\"NO\")\r\n out.flush()\r\n }\r\n }\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n\r\n /** Assumption: a >= b >= c\r\n *\r\n * - Upper bound: (a - 1) + (b - 1) + (c - 1)\r\n * Example: \"aaaaabbbc\"\r\n *\r\n * - Lower bound: a - b - c - 1\r\n * Example: \"abacabacababaaa\"\r\n */\r\n def check(a: Int, b: Int, c: Int, m: Int): Boolean =\r\n m >= a - b - c - 1 && m <= a + b + c - 3\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(a, b, c, m) = nextInts(4)\r\n\r\n check(a, b, c, m) match {\r\n case true =>\r\n out.println(\"YES\")\r\n out.flush()\r\n case false =>\r\n out.println(\"NO\")\r\n out.flush()\r\n }\r\n }\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n\r\n @annotation.tailrec\r\n def check(a: Int, b: Int, c: Int, m: Int, iter: Int = 0): Boolean =\r\n if (iter > 100) false\r\n else {\r\n val n = a + b + c\r\n\r\n if (a < b || a < c || b < c)\r\n check(a max b max c, n - (a max b max c) - (a min b min c), a min b min c, m, iter)\r\n else\r\n m match {\r\n case 0 => a <= (n + 1) / 2\r\n case m =>\r\n val ka = m min (a / 2)\r\n\r\n if (ka > 0 && a - ka <= (n - m + 1) / 2) check(a - 2 * ka, b, c, m - ka, iter + 1)\r\n else false\r\n }\r\n\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(a, b, c, m) = nextInts(4)\r\n\r\n check(a, b, c, m) match {\r\n case true =>\r\n out.println(\"YES\")\r\n out.flush()\r\n case false =>\r\n out.println(\"NO\")\r\n out.flush()\r\n }\r\n }\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n"}], "src_uid": "fc547fc83ebbcc3c058a069ef9fef62c"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map { _ =>\n val Array(sex, start, end) = in.next().split(' ')\n (sex.head, start.toInt, end.toInt)\n }\n println(2 * (1 to 366).foldLeft(0) {\n case(acc, i) =>\n val res = data.foldLeft((0, 0)) {\n case((m, f), ('M', start, end)) if i >= start && i <= end => (m + 1, f)\n case((m, f), ('F', start, end)) if i >= start && i <= end => (m, f + 1)\n case(acc, _) => acc\n }\n Math.max(acc, Math.min(res._1, res._2))\n })\n}", "positive_code": [{"source_code": "import scala.io.Source\n\nobject CF343_B extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n \n val mens = new Array[Int](367)\n val wms = new Array[Int](367)\n \n for(r <- 0 to n-1) {\n val line = in.next()\n val info = line.split(\" \")\n var arr = mens\n if(info(0).equals(\"F\")) {\n arr = wms\n }\n for(idx <- info(1).toInt to info(2).toInt) {\n arr(idx) += 1\n }\n }\n \n var max = 0\n \n for(i <- 0 to 366) {\n val cand = mens(i).min(wms(i)) * 2\n max = max.max(cand)\n }\n \nprintln(max)\n \n\n \n \n}"}, {"source_code": "import io.StdIn._\nimport java.lang.Math._\nobject div2_B {\n def main(args: Array[String]){\n val n = readInt()\n var F = Vector[(String,(Int,Int))]()\n for (i <- 0 until n) {\n val ln = readLine().split(\" \")\n val v = (ln(0).toString,(ln(1).toInt, ln(2).toInt))\n\n F = F :+ v\n }\n var res = 0\n for(i <- 1 to 366) {\n var m = 0\n var f = 0\n for(j <- 0 until F.length){\n if (F(j)._2._1 <= i && F(j)._2._2 >= i) {\n if (F(j)._1 == \"M\") {\n m = m + 1\n }\n else {\n f = f + 1\n }\n }\n }\n res = max(res, min(m,f))\n }\n println(res*2)\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _629B extends CodeForcesApp {\n override type Result = Int\n\n override def solve(read: InputReader) = {\n val (males, females) = (Array.ofDim[Int](367), Array.ofDim[Int](367))\n val n = read[Int]\n repeat(n) {\n val (s, a, b) = read[(Char, Int, Int)]\n val arr = if (s == 'M') males else females\n for {i <- a to b} arr(i) += 1\n }\n\n val couples = males zip females map { case (a, b) => a min b}\n couples.max * 2\n }\n\n @inline def repeat(n: Int)(f: => Unit): Unit = for {_ <- 1 to n} f\n\n\n override def format(result: Result) = result.toString\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n\n var imosM = new Array[Int](370)\n var imosF = new Array[Int](370)\n\n for(i <- 1 to n){\n val c = sc.next()\n val a = sc.nextInt()\n val b = sc.nextInt()\n if(c == \"M\"){\n imosM(a) += 1\n imosM(b+1) -= 1\n }\n else{\n imosF(a) += 1\n imosF(b+1) -= 1\n }\n }\n\n //\n for(i <- 1 to 366){\n imosM(i+1) += imosM(i)\n imosF(i+1) += imosF(i)\n }\n\n var ans = 0\n for(i <- 1 to 366){\n val tmp = Math.min(imosM(i), imosF(i))\n ans = Math.max(ans, tmp)\n }\n\n println(ans*2)\n }\n}\n"}, {"source_code": "\n\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject B_343 { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n runTest(Test.sa2)\n debugV = true\n// file = File(\"C:\\\\temp\\\\google cj\\\\2014q\\\\c-small.res\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading --------------------------\n val n = readLine.int\n val males, females = new Array[Int](367)\n debug(\"n = \" + n)\n \n (1 to n).foreach{ x => \n val line = readLine\n val arr = if (line.string == \"M\") males else females\n (line.int to line.int).foreach(arr(_) += 1)\n }\n //---------------------------- parameters reading end ----------------------\n val res = (1 to 366).map(i => males(i).min(females(i)) ).max * 2\n outLn(res+\"\")\n finish\n }\n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) {\n resultStr.append(str).append(\"\\n\")\n }\n def finish() {\n// if (file == null) {\n println(resultStr.toString())\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4\nM 151 307\nF 343 352\nF 117 145\nM 24 128\n\"\"\"\n\nval sa2 = \"\"\"\n6\nM 128 130\nF 128 131\nF 131 140\nF 131 141\nM 131 200\nM 140 200\n\"\"\"\n\n}\n\n}\n"}, {"source_code": "\n\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject B_343 { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n runTest(Test.sa2)\n debugV = true\n// file = File(\"C:\\\\temp\\\\google cj\\\\2014q\\\\c-small.res\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading --------------------------\n val n = readLine.int\n val males = new Array[Int](367)\n val females = new Array[Int](367)\n debug(\"n = \" + n)\n \n (1 to n).foreach{ x => \n val line = readLine\n val male = line.string == \"M\"\n val start = line.int\n val end = line.int\n for (i <- start to end) {\n if (male) males(i) += 1\n else females(i) += 1\n }\n }\n \n //---------------------------- parameters reading end ----------------------\n var res = 0\n for (i <- 1 to 366) {\n val possible = males(i).min(females(i)) \n if (res < possible) res = possible\n }\n res = res *2\n \n outLn(res+\"\")\n \n finish\n }\n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) {\n resultStr.append(str).append(\"\\n\")\n }\n def finish() {\n// if (file == null) {\n println(resultStr.toString())\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4\nM 151 307\nF 343 352\nF 117 145\nM 24 128\n\"\"\"\n\nval sa2 = \"\"\"\n6\nM 128 130\nF 128 131\nF 131 140\nF 131 141\nM 131 200\nM 140 200\n\"\"\"\n\n}\n\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject CF343_B extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n \n val mens = new Array[Int](367)\n val wms = new Array[Int](367)\n \n for(r <- 0 to n-1) {\n val line = in.next()\n val info = line.split(\" \")\n var arr = mens\n if(info(0).equals(\"W\")) {\n arr = wms\n }\n for(idx <- info(1).toInt to info(2).toInt) {\n arr(idx) += 1\n }\n }\n \n var max = 0\n \n for(i <- 0 to 366) {\n val cand = mens(i).min(wms(i))\n max = max.max(cand)\n }\n \nprintln(max)\n \n\n \n \n}"}, {"source_code": "import scala.io.Source\n\nobject CF343_B extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n \n val mens = new Array[Int](367)\n val wms = new Array[Int](367)\n \n for(r <- 0 to n-1) {\n val line = in.next()\n val info = line.split(\" \")\n var arr = mens\n if(info(0).equals(\"W\")) {\n arr = wms\n }\n for(idx <- info(1).toInt to info(2).toInt) {\n arr(idx) += 1\n }\n }\n \n var max = 0\n \n for(i <- 0 to 366) {\n val cand = mens(i).max(wms(i))\n max = max.max(cand)\n }\n \nprintln(max)\n \n\n \n \n}"}], "src_uid": "75d500bad37fbd2c5456a942bde09cd3"} {"source_code": "import scala.io.StdIn._\r\n\r\nobject A extends App {\r\n for (_ <- 0 until readInt) {\r\n val n = readInt\r\n val a = readLine.split(\" \").map(_.toInt)\r\n if (a.count(_ % 2 != 0) == n)\r\n println(\"Yes\")\r\n else\r\n println(\"No\")\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n val ans = an.count(_ % 2 == 1) == an.count(_ % 2 == 0)\r\n\r\n ans match {\r\n case true => println(\"Yes\")\r\n case _ => println(\"No\")\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "d5bd27c969d9cd910f13baa53c247871"} {"source_code": "import java.util.Scanner\n\nobject CF2 {\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val as = sc.nextLine()\n val bs = sc.nextLine()\n val a = as.toCharArray\n val b = bs.toCharArray\n var b0 = 0L\n var b1 = 0L\n val lengthDiff = b.length - a.length\n for (i <- 0 to lengthDiff)\n if (b(i) == '0') b0 += 1 else b1 += 1\n var sum = 0L\n for (i <- 0 to a.length - 1) {\n if (a(i) == '0') sum += b1 else sum += b0\n if (i != a.length - 1) {\n if (b(i) == '0') b0 -= 1 else b1 -= 1\n if (b(lengthDiff + i + 1) == '0') b0 += 1 else b1 += 1\n }\n }\n System.out.print(sum)\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject B_336 { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.sa2.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val a = br.readLine()\n val b = br.readLine()\n \n val itN = b.length() - a.length() + 1\n db(itN+\"\")\n val sums = new Array[Int](b.length())\n \n var total = 0l\n \n var curSum = 0\n for (i <- 0 until b.length()) {\n curSum += value(b, i)\n sums(i) = curSum\n db(i + \" - \" + sums(i))\n }\n \n \n for (i <- 0 until a.length()) {\n val vv = value(a, i)\n var dSum = sums(itN-1+i) \n if (i > 0) {\n dSum -= sums(i-1)\n }\n var dif = 0 \n if (vv == 0) { \n dif = dSum\n } else { \n dif = itN - dSum \n }\n total += dif\n }\n \n def value(str:String, ind:Int) = if (str.charAt(ind) == '0') 0 else 1\n \n println(total)\n\n //---------------------------- parameters reading end ----------------------\n\n }\n\n\n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def hasNext = tok.hasMoreElements()\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n //============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n01\n101\n\"\"\"\n \nval sa2 = \"\"\"\n0\n101\n\"\"\"\n \nval sa3 = \"\"\"\n1\n101\n\"\"\"\n\n}\n\n}\n\n"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by hsleep on 2016. 1. 8..\n */\nobject BSolution extends App {\n val a = StdIn.readLine()\n val b = StdIn.readLine()\n\n def binaryCount(s: String): (Long, Long) = {\n var i, j = 0l\n s.foreach {\n case '0' => i += 1\n case _ => j += 1\n }\n i -> j\n }\n val initialSub = b.take(b.length - a.length + 1)\n val (headIt, nextIt) = (b.iterator, b.substring(initialSub.length).iterator)\n var (count0, count1) = binaryCount(initialSub)\n\n val listOfDist = {\n for {\n c <- a\n } yield {\n val dist = c match {\n case '0' => count1\n case '1' => count0\n }\n\n if (nextIt.hasNext) {\n headIt.next() match {\n case '0' => count0 -= 1\n case '1' => count1 -= 1\n }\n\n nextIt.next() match {\n case '0' => count0 += 1\n case '1' => count1 += 1\n }\n }\n\n dist\n }\n }\n\n println(listOfDist.sum)\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\n/**\n * Created by hsleep on 2016. 1. 8..\n */\nobject BSolution extends App {\n val a = StdIn.readLine()\n val b = StdIn.readLine()\n\n def binaryCount(s: String): (Int, Int) = {\n var i, j = 0\n s.foreach {\n case '0' => i += 1\n case _ => j += 1\n }\n i -> j\n }\n val initialSub = b.take(b.length - a.length + 1)\n val (headIt, nextIt) = (b.iterator, b.substring(initialSub.length).iterator)\n var (count0, count1) = binaryCount(initialSub)\n\n val listOfDist = {\n for {\n c <- a\n } yield {\n val dist = c match {\n case '0' => count1\n case '1' => count0\n }\n\n if (nextIt.hasNext) {\n headIt.next() match {\n case '0' => count0 -= 1\n case '1' => count1 -= 1\n }\n\n nextIt.next() match {\n case '0' => count0 += 1\n case '1' => count1 += 1\n }\n }\n\n dist\n }\n }\n\n println(listOfDist.sum)\n}"}, {"source_code": "import java.util.Scanner\n\nobject CF2 {\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val as = sc.nextLine()\n val bs = sc.nextLine()\n val a = as.toCharArray\n val b = bs.toCharArray\n var b0 = 0\n var b1 = 0\n val lengthDiff = b.length - a.length\n for (i <- 0 to lengthDiff)\n if (b(i) == '0') b0 += 1 else b1 += 1\n var sum = 0\n for (i <- 0 to a.length - 1) {\n if (a(i) == '0') sum += b1 else sum += b0\n if (i != a.length - 1) {\n if (b(i) == '0') b0 -= 1 else b1 -= 1\n if (b(lengthDiff + i + 1) == '0') b0 += 1 else b1 += 1\n }\n }\n System.out.print(sum)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject B_336 { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n val a = br.readLine()\n val b = br.readLine()\n \n val itN = b.length() - a.length() + 1\n db(itN+\"\")\n val sums = new Array[Int](b.length())\n \n var total = 0\n \n var curSum: Integer = 0\n for (i <- 0 until b.length()) {\n curSum += value(b, i)\n sums(i) = curSum\n }\n \n \n for (i <-0 until a.length()) {\n val vv = value(a, i)\n var dif = 0 \n if (vv == 0) { \n dif = sums(itN-1+i) \n } else { \n dif = itN - sums(itN-1+i) \n }\n total += dif\n }\n \n \n// var total = 0l\n// var curSum = 0l\n// val\n// \n// for(i <- 0 until itN) {\n//// if (i == 0) {\n// curSum = 0\n// for (j <- 0 until a.length()) {\n// val dist = Math.abs(value(a, j) - value(b, j+i)) \n// curSum += dist\n// }\n// db(\"- \" + curSum)\n//// } else {\n//// curSum -= Math.abs(value(a, j) - value(b, j))\n//// }\n// total += curSum\n// \n// }\n \n def value(str:String, ind:Int) = if (str.charAt(ind) == '0') 0 else 1\n \n println(total)\n\n //---------------------------- parameters reading end ----------------------\n\n }\n\n\n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def hasNext = tok.hasMoreElements()\n }\n \n var debugV = false\n var is = System.in\n val br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n //============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n\n\"\"\"\n\n}\n\n}\n\n"}, {"source_code": "import java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject B_336 { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.sa2.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val a = br.readLine()\n val b = br.readLine()\n \n val itN = b.length() - a.length() + 1\n db(itN+\"\")\n val sums = new Array[Int](b.length())\n \n var total = 0\n \n var curSum: Integer = 0\n for (i <- 0 until b.length()) {\n curSum += value(b, i)\n sums(i) = curSum\n db(i + \" - \" + sums(i))\n }\n \n \n for (i <-0 until a.length()) {\n val vv = value(a, i)\n var dSum = sums(itN-1+i) \n if (i > 0) {\n dSum -= sums(i-1)\n }\n var dif = 0 \n if (vv == 0) { \n dif = dSum\n } else { \n dif = itN - dSum \n }\n total += dif\n }\n \n def value(str:String, ind:Int) = if (str.charAt(ind) == '0') 0 else 1\n \n println(total)\n\n //---------------------------- parameters reading end ----------------------\n\n }\n\n\n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def hasNext = tok.hasMoreElements()\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n //============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n01\n101\n\"\"\"\n \nval sa2 = \"\"\"\n0\n101\n\"\"\"\n \nval sa3 = \"\"\"\n1\n101\n\"\"\"\n\n}\n\n}\n\n"}], "src_uid": "ed75bd272f6d3050426548435423ca92"} {"source_code": "\n\nobject CodeforcesRound1392A {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val n = rl_int\n val a = rll_int\n val allAreEqual = a.forall(_ == a(0))\n val res = if (allAreEqual) n else 1\n writer.println(res)\n }\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}", "positive_code": [{"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n val d = as.distinct.size\n val res = if (d == 1) n else 1\n\n out.println(res)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "\n\nobject CodeforcesRound1392A {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val n = rl_int\n val a = rll_int\n val res = if (n == 2 && a(0) == a(1)) 2 else 1\n writer.println(res)\n }\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}"}], "src_uid": "7b80d3f3cd4f93e4277c76c76dc41f42"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject Towers {\n def main(args: Array[String]): Unit = {\n val inputStream = System.in\n val outputStream = System.out\n val in = new InputReader(inputStream)\n val out = new PrintWriter(outputStream)\n val solver = new Task()\n solver.solve(in, out)\n out.close()\n }\n\n class Task {\n def solve(in: InputReader, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val a = Array.ofDim[Int](n)\n for (i <- 0 until n) a(i) = in.nextInt()\n val group = a.groupBy(x => x).values\n out.println(group.maxBy(x => x.length).length + \" \" + group.size)\n }\n }\n\n class InputReader(stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream))\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n try {\n tokenizer = new StringTokenizer(reader.readLine())\n } catch {\n case _: IOException => throw new RuntimeException\n }\n }\n tokenizer.nextToken()\n }\n\n def nextInt(): Int = {\n Integer.parseInt(next())\n }\n }\n\n}\n", "positive_code": [{"source_code": "object Main\n{\n\tdef sort(xs: Array[Int]): Array[Int] =\n\t if (xs.length <= 1) xs\n\t else {\n\t\tval pivot = xs(xs.length / 2)\n\t\tArray.concat(\n\t\t sort(xs filter (pivot >)),\n\t\t\t xs filter (pivot ==),\n\t\t sort(xs filter (pivot <)))\n\t }\n\t \n\tdef main(args:Array[String])\n\t{\n\t\treadLine;\n\t\tval a1 = sort(readLine.split(\" \").map(i => i.toInt)).toList;\n\t\tval counts = sort((1 to 1000).map(i => a1.count(j => i == j )).toArray).toList;\n\t\tprintln(counts.last + \" \" + counts.count(i => i > 0))\n\t}\n}"}, {"source_code": "object A37 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n\n val max = input.groupBy(identity).mapValues(_.length).maxBy(_._2)._2\n\n val diff = input.toSet.size\n\n println(s\"$max $diff\")\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P37A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val bars = List.fill(N)(sc.nextInt).groupBy(identity[Int])\n val highest = bars.map(_._2.length).max\n val towers = bars.size\n\n out.println(List(highest, towers).mkString(\" \"))\n out.close\n}\n"}, {"source_code": "import java.io._\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n\n reader.readLine()\n val ans = readInts.groupBy(x => x).values.map(_.size)\n\n def main(a: Array[String]) {\n println(ans.max + \" \" + ans.size)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val map = scala.collection.mutable.Map[Int, Int]()\n a.foreach(n => map(n) = map.getOrElse(n, 0) + 1)\n println(map.values.max + \" \" + map.size)\n }\n}"}, {"source_code": "object Andrei {\n def main (args : Array[String]) {\n val n = readInt\n var A = readLine().split(\" \").map(_.toInt)\n\n val w = A.distinct\n val T = w.map(x => A.count(_ == x))\n println(T.max + \" \" + w.size)\n\n }\n\n}\n\n"}, {"source_code": "object Andrei {\n def main (args : Array[String]) {\n val n = readInt\n val A = readLine().split(\" \").map(_.toInt)\n\n def swap(a : Int, b : Int) {\n val temp = A(a)\n A(a) = A(b)\n A(b) = temp\n }\n\n for(i <- 0 until n) \n for(j <- i until n)\n if(A(i) > A(j))\n swap(i, j)\n\n val w = A.distinct\n val T = w.map(x => A.count(_ == x))\n println(T.max + \" \" + w.size)\n\n }\n\n}\n"}, {"source_code": "object Andrei {\n class Heap {\n private type Node = Heap.Node\n private def Node(rank : Int, datum : Int, left : Node, right : Node) = new Node(rank, datum, left, right)\n private var root : Node = null\n\n private def mergeHeaps(a : Node, b : Node) : Node = {\n if(a == null) return b\n if(b == null) return a\n \n //keep the minimum up\n var x = a\n var y = b\n if(x.datum > y.datum) {\n val temp = x\n x = y\n y = temp\n }\n\n // completing the right part\n x.right = mergeHeaps(x.right, y)\n \n //keeping the balance\n if(x.left == null) {\n //left child doesn't exist we will therefore swap the 2\n x.left = x.right\n x.right = null\n x.rank = 1\n }\n else {\n //left child does exist, we therefore compare the 2 ranks\n if(x.left.rank < x.right.rank) {\n //we need to swap\n val temp = x.left\n x.left = x.right\n x.right = temp\n }\n x.rank = x.right.rank + 1\n }\n x\n }\n\n private def out(x : Node, level : Int) : Unit = {\n if(x != null) {\n for(i <- 1 to level) print (\" \" )\n\n println(x.datum)\n if(x.left != null) {\n for(i <- 1 to level) print (\" \" )\n println(\"left\")\n out(x.left, level + 1)\n }\n if(x.right != null) {\n println(\"right\")\n for(i <- 1 to level) print (\" \" )\n out(x.right, level + 1)\n }\n }\n }\n \n def myprint = out(root, 0)\n\n def insert(x : Int) {\n root = mergeHeaps(root, Node(1, x, null, null))\n }\n\n def getMin : Int = {\n val min = root.datum\n root = mergeHeaps(root.right, root.left)\n min\n }\n }\n\n object Heap {\n private class Node(var rank : Int, var datum : Int, var left : Node, var right : Node)\n \n def apply(a : Array[Int]) = {\n val h = new Heap;\n a.foreach(h.insert(_))\n h\n }\n }\n\n def main (args : Array[String]) {\n val n = readInt\n val A = readLine().split(\" \").map(_.toInt)\n\n val H = Heap(A)\n\n for(i <- 0 until n) A(i) = H.getMin\n \n var cnt = 1\n var nr = 1\n var max = 1\n for(i <- 1 until n)\n if(A(i - 1) != A(i)) {\n if(max < cnt) max = cnt\n cnt = 1\n nr += 1\n }\n else cnt += 1\n if(cnt > max) max = cnt\n println(max + \" \" + nr)\n\n }\n\n}\n\n"}, {"source_code": "object Andrei {\n class Heap {\n private type Node = Heap.Node\n private def Node(rank : Int, datum : Int, left : Node, right : Node) = new Node(rank, datum, left, right)\n private var root : Node = null\n\n private def mergeHeaps(a : Node, b : Node) : Node = {\n if(a == null) return b\n if(b == null) return a\n \n //keep the minimum up\n var x = a\n var y = b\n if(x.datum > y.datum) {\n val temp = x\n x = y\n y = temp\n }\n\n // completing the right part\n x.right = mergeHeaps(x.right, y)\n \n //keeping the balance\n if(x.left == null) {\n //left child doesn't exist we will therefore swap the 2\n x.left = x.right\n x.right = null\n x.rank = 1\n }\n else {\n //left child does exist, we therefore compare the 2 ranks\n if(x.left.rank < x.right.rank) {\n //we need to swap\n val temp = x.left\n x.left = x.right\n x.right = temp\n }\n x.rank = x.right.rank + 1\n }\n x\n }\n\n private def out(x : Node, level : Int) : Unit = {\n if(x != null) {\n for(i <- 1 to level) print (\" \" )\n\n println(x.datum)\n if(x.left != null) {\n for(i <- 1 to level) print (\" \" )\n println(\"left\")\n out(x.left, level + 1)\n }\n if(x.right != null) {\n println(\"right\")\n for(i <- 1 to level) print (\" \" )\n out(x.right, level + 1)\n }\n }\n }\n \n def myprint = out(root, 0)\n\n def insert(x : Int) {\n root = mergeHeaps(root, Node(1, x, null, null))\n }\n\n def getMin : Int = {\n val min = root.datum\n root = mergeHeaps(root.right, root.left)\n min\n }\n }\n\n object Heap {\n private class Node(var rank : Int, var datum : Int, var left : Node, var right : Node)\n \n def apply(a : Array[Int]) = {\n val h = new Heap;\n a.foreach(h.insert(_))\n h\n }\n }\n\n def main (args : Array[String]) {\n val n = readInt\n val A = readLine().split(\" \").map(_.toInt)\n\n val H = Heap(A)\n\n for(i <- 0 until n) A(i) = H.getMin\n\n val w = A.distinct\n val T = w.map(x => A.count(_ == x))\n println(T.max + \" \" + w.size)\n\n }\n}\n"}, {"source_code": "object Andrei {\n def main (args : Array[String]) {\n val n = readInt\n var A = readLine().split(\" \").map(_.toInt)\n\n A = A.sortBy(x => x)\n var cnt = 1\n var nr = 1\n var max = 1\n for(i <- 1 until n)\n if(A(i - 1) != A(i)) {\n if(max < cnt) max = cnt\n cnt = 1\n nr += 1\n }\n else cnt += 1\n if(cnt > max) max = cnt\n println(max + \" \" + nr)\n\n }\n\n}\n\n"}, {"source_code": "object P037A extends App {\n val n = readInt\n val a = readLine.split(' ').map(_.toInt)\n val b = a.groupBy(identity).map(x => (x._1, x._2.size))\n printf(\"%d %d\\n\", b.maxBy(x => x._2)._2, b.size)\n}\n"}, {"source_code": "import java.util.Scanner\nobject Towers {\n\n val scanner = new Scanner(System.in)\n def main(args: Array[String]): Unit = {\n val c = scanner.nextInt();\n val res = ((1 to c) map {i => scanner.nextInt()});\n var count = res.map(a => res.count(x => x==a));\n print((Int.MinValue/: res) {(m:Int,c:Int)=> m max(res.count(a => a == c))})\n print(\" \")\n var filtered = res.toSet\n println(filtered.size)\n }\n\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _37A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt).groupBy(i => i)\n println(\"%d %d\".format(a.map(g => g._2.length).max, a.size))\n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n in.next()\n val data = in.next().split(\" \").groupBy(t => t)\n\n println(data.maxBy(t => t._2.length)._2.length + \" \" + data.size)\n}\n"}], "negative_code": [{"source_code": "object Main\n{\n\tdef sort(xs: Array[Int]): Array[Int] =\n\t if (xs.length <= 1) xs\n\t else {\n\t\tval pivot = xs(xs.length / 2)\n\t\tArray.concat(\n\t\t sort(xs filter (pivot >)),\n\t\t\t xs filter (pivot ==),\n\t\t sort(xs filter (pivot <)))\n\t }\n\t \n\tdef main(args:Array[String])\n\t{\n\t\treadLine;\n\t\tval a1 = sort(readLine.split(\" \").map(i => i.toInt)).toList;\n\t\tval counts = sort((1 to 1000).map(i => a1.count(j => i == j )).toArray).toList;\n\t\tprintln(counts.count(i => i > 0) + \" \" + counts.last)\n\t}\n}"}, {"source_code": "object Main\n{\n\tdef sort(xs: Array[Int]): Array[Int] =\n\t if (xs.length <= 1) xs\n\t else {\n\t\tval pivot = xs(xs.length / 2)\n\t\tArray.concat(\n\t\t sort(xs filter (pivot >)),\n\t\t\t xs filter (pivot ==),\n\t\t sort(xs filter (pivot <)))\n\t }\n\t \n\tdef main(args:Array[String])\n\t{\n\t\tval a1 = sort(readLine.split(\" \").map(i => i.toInt)).toList;\n\t\tval counts = sort((1 to 1000).map(i => a1.count(j => i == j )).toArray).toList;\n\t\tprintln(counts.count(i => i > 0) + \" \" + counts.last)\n\t}\n}"}, {"source_code": "object Andrei {\n def main (args : Array[String]) {\n val n = readInt\n var A = readLine().split(\" \").map(_.toInt)\n\n A = A.sortBy(x => x)\n A.foreach(println(_))\n var cnt = 1\n var nr = 1\n var max = 1\n for(i <- 1 until n)\n if(A(i - 1) != A(i)) {\n if(max < cnt) max = cnt\n cnt = 1\n nr += 1\n }\n else cnt += 1\n \n println(max + \" \" + nr)\n\n }\n\n}\n\n"}, {"source_code": "object Andrei {\n def main (args : Array[String]) {\n val n = readInt\n var A = readLine().split(\" \").map(_.toInt)\n\n A = A.sortBy(x => x)\n var cnt = 1\n var nr = 1\n var max = 1\n for(i <- 1 until n)\n if(A(i - 1) != A(i)) {\n if(max < cnt) max = cnt\n cnt = 1\n nr += 1\n }\n else cnt += 1\n \n println(max + \" \" + nr)\n\n }\n\n}\n\n"}], "src_uid": "9a92221c760a3b6a1e9318f948fe0473"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val H, L = ni()\n val a = (H.toDouble * H + L.toDouble * L) / 2 / H\n out.println(f\"${a-H}%.13f\")\n }\n}", "positive_code": [{"source_code": "object _1199B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val h, l = io.read[Long]\n val a = (l*l - h*h)/(2.0 * h)\n io.write(a)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "2cd5807e3f9685d4eff88f2283904f0d"} {"source_code": "import java.util.Scanner\n\nobject MainC extends App {\n val sc = new Scanner(System.in)\n\n val N = sc.nextInt\n val arr = for (i <- 0 until N) yield sc.nextInt\n if (arr.forall(1 ==)) {\n print(List.make(arr.size - 1, 1).mkString(\" \"))\n if(arr.size != 1) print(\" \")\n println(2)\n } else {\n val vmax = arr.max\n val after = arr.updated(arr.indexOf(vmax), 1).sorted\n println(after.mkString(\" \"))\n }\n}\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val max = data.max\n if (max == 1)\n data(data.length - 1) = 2\n else {\n val index = data.indexOf(max)\n data(index) = 1\n }\n println(data.sorted.mkString(\" \"))\n}"}, {"source_code": "\nobject Main {\n\n def main(args: Array[String]) {\n val n = nextInt()\n val a = (for (i <- 0 until n) yield nextInt()).toList.sorted\n val s = if (a.last == 1) ((a.init):::List(2)) else 1 :: a.init\n println(s.mkString(\" \"))\n }\n\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));\n var st = new java.util.StringTokenizer(\"\");\n\n def next() = {\n while (!st.hasMoreTokens())\n st = new java.util.StringTokenizer(in.readLine());\n st.nextToken();\n }\n\n def nextInt() = java.lang.Integer.parseInt(next());\n def nextDouble() = java.lang.Double.parseDouble(next());\n def nextLong() = java.lang.Long.parseLong(next());\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 29 Jun 2016\n */\nobject A135 extends App {\n\n def solve() = {\n val n: Int = scala.io.StdIn.readInt()\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n\n if (n == 1) {\n if (a(0) == 1) {\n println(\"2\")\n } else {\n println(\"1\")\n }\n } else {\n val buf = new StringBuilder\n if (a(0) != 1) {\n for (i <- 0 until n) {\n if (i == 0) {\n buf ++= \"1 \"\n } else {\n buf ++= (a(i - 1) + \" \")\n }\n }\n } else {\n for (i <- 0 until n) {\n if (i == 0) {\n buf ++= \"1 \"\n } else if (a(i) == 1) {\n if (i < n - 1 && a(i + 1) == 1) {\n buf ++= \"1 \"\n } else if (i < n - 1 && a(i + 1) != 1) {\n buf ++= \"1 \"\n } else {\n buf ++= \"2 \"\n }\n } else {\n buf ++= (a(i - 1) + \" \")\n }\n }\n }\n println(buf.toString())\n }\n\n }\n\n solve()\n\n}\n"}, {"source_code": "import scala.util.Sorting\nobject Main {\n def printArr(a: Array[Int], end: Int) {\n for (i <- 0 to end) {\n if (i != 0)\n print(\" \")\n print(a(i))\n }\n }\n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(' ').map(_.toInt)\n Sorting.quickSort(a)\n if (a.last == 1) {\n a(a.length-1) = 2\n printArr(a, a.length - 1)\n }\n else {\n print(\"1 \")\n printArr(a, a.length - 2)\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject MainC extends App {\n val sc = new Scanner(System.in)\n\n val N = sc.nextInt\n val arr = for (i <- 0 until N) yield sc.nextInt\n if (arr.forall(1 ==)) {\n print(List.make(arr.size - 1, 1).mkString(\" \"))\n if(arr.size != 1) print(\" \")\n println(2)\n } else {\n val vmax = arr.max\n val after = arr.updated(arr.indexOf(vmax), 1).sorted\n println(after.mkString(\" \"))\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val max = data.max\n val index = data.indexOf(max)\n data(index) = 1\n println(data.sorted.mkString(\" \"))\n}"}, {"source_code": "import java.util.Scanner\n\nobject MainC extends App {\n val sc = new Scanner(System.in)\n \n val N = sc.nextInt\n val arr = for(i <- 0 until N) yield sc.nextInt\n \n val vmax = arr.max\n val after = arr.updated(arr.indexOf(vmax), 1).sorted\n println(after.mkString(\" \"))\n}\n"}], "src_uid": "1cd10f01347d869be38c08ad64266870"} {"source_code": "import java.util._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val a = nextLong\n val b = nextLong\n val c = nextLong\n if (a == 0 && b == 0 && c == 0) {\n out.println(-1)\n return 1\n }\n if (a == 0 && b == 0) {\n out.println(0)\n return 1\n }\n if (a == 0) {\n out.println(1)\n out.println((1.0d * (-c)) / b)\n return 1\n }\n val d = b * b - 4L * a * c\n if (d < 0) {\n out.println(0)\n return 1\n }\n if (d == 0) {\n out.println(1)\n out.println((1.0d * (-b)) / (2.0d * a))\n return 1\n }\n out.println(2)\n out.println(Math.min( ((1.0d * (-b)) - Math.sqrt(d) )/ (2.0d * a), ((1.0d * (-b)) + Math.sqrt(d) )/ (2.0d * a)))\n out.println(Math.max( ((1.0d * (-b)) - Math.sqrt(d) )/ (2.0d * a), ((1.0d * (-b)) + Math.sqrt(d) )/ (2.0d * a)))\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n", "positive_code": [{"source_code": "object P020B extends App {\n def solve(a: List[Long]): Tuple3[Int, Any, Any] = {\n val det = a(1)*a(1) - 4*a(0)*a(2)\n if (det < 0) return new Tuple3(0, Unit, Unit);\n val x1 = -0.5*a(1)/a(0)\n if (det == 0) return new Tuple3(1, x1, Unit);\n val x2 = 0.5*math.sqrt(det)/a(0)\n return new Tuple3(2, x1-x2, x1+x2)\n }\n \n var a = readLine.split(' ').map(_.toLong).toList\n if (a(0) < 0) a = a.map(-_)\n val result = a match {\n case List(0, 0, 0) => (-1, Unit, Unit)\n case 0::0::tail => (0, Unit, Unit)\n case 0::tail => (1, -1.0*a(2)/a(1), Unit)\n case _ => solve(a)\n }\n println(result._1)\n if (result._1 >= 1) printf(\"%.8f\\n\", result._2);\n if (result._1 >= 2) printf(\"%.8f\\n\", result._3);\n}\n"}], "negative_code": [{"source_code": "object P020B extends App {\n def solve(a: List[Int]): Tuple3[Int, Any, Any] = {\n val det = a(1)*a(1) - 4*a(0)*a(2)\n if (det < 0) return new Tuple3(0, Unit, Unit);\n val x1 = -0.5*a(1)/a(0)\n if (det == 0) return new Tuple3(1, x1, Unit);\n val x2 = 0.5*math.sqrt(det)/a(0)\n return new Tuple3(2, x1-x2, x1+x2)\n }\n \n val a = readLine.split(' ').map(_.toInt).toList\n val result = a match {\n case List(0, 0, 0) => (-1, Unit, Unit)\n case 0::0::tail => (0, Unit, Unit)\n case 0::tail => (1, -1.0*a(2)/a(1), Unit)\n case _ => solve(a)\n }\n println(result._1)\n if (result._1 >= 1) printf(\"%.8f\\n\", result._2);\n if (result._1 >= 2) printf(\"%.8f\\n\", result._3);\n}\n"}, {"source_code": "object P020B extends App {\n def solve(a: List[Long]): Tuple3[Int, Any, Any] = {\n val det = a(1)*a(1) - 4*a(0)*a(2)\n if (det < 0) return new Tuple3(0, Unit, Unit);\n val x1 = -0.5*a(1)/a(0)\n if (det == 0) return new Tuple3(1, x1, Unit);\n val x2 = 0.5*math.sqrt(det)/a(0)\n return new Tuple3(2, x1-x2, x1+x2)\n }\n \n val a = readLine.split(' ').map(_.toLong).toList\n val result = a match {\n case List(0, 0, 0) => (-1, Unit, Unit)\n case 0::0::tail => (0, Unit, Unit)\n case 0::tail => (1, -1.0*a(2)/a(1), Unit)\n case _ => solve(a)\n }\n println(result._1)\n if (result._1 >= 1) printf(\"%.8f\\n\", result._2);\n if (result._1 >= 2) printf(\"%.8f\\n\", result._3);\n}\n"}, {"source_code": "import java.util._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val a = nextLong\n val b = nextLong\n val c = nextLong\n if (a == 0 && b == 0 && c == 0) {\n out.println(-1)\n return 1\n }\n if (a == 0 && b == 0) {\n out.println(0)\n return 1\n }\n if (a == 0) {\n out.println(1)\n out.println((1.0d * (-c)) / b)\n return 1\n }\n val d = b * b - 4L * a * c\n if (d < 0) {\n out.println(0)\n return 1\n }\n if (d == 0) {\n out.println(1)\n out.println((1.0d * (-b)) / (2.0d * a))\n return 1\n }\n out.println(2)\n out.println(((1.0d * (-b)) - Math.sqrt(d) )/ (2.0d * a))\n out.println(((1.0d * (-b)) + Math.sqrt(d) )/ (2.0d * a))\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}], "src_uid": "84372885f2263004b74ae753a2f358ac"} {"source_code": "object Solution extends App {\n\n def solution(n: Long, k: Long, d1: Long, d2: Long, first: Long, second: Long, third: Long): Boolean = {\n val shouldWin = n / 3\n val unknown = (k - d1 + d2) % 3\n if (unknown != 0 || first < 0 || second < 0 || third < 0 || first > k\n || second > k || third > k || n % 3 != 0\n || first > shouldWin || second > shouldWin || third > shouldWin)\n return false\n return true\n }\n\n// for (int sign1 = -1; sign1 <= 1; sign1++) {\n// for (int sign2 = -1; sign2 <= 1; sign2++) {\n// if (sign1 == 0 || sign2 == 0) {\n// continue;\n// }\n// LL D1 = d1 * sign1;\n// LL D2 = d2 * sign2;\n//\n// LL x2 = (k - D1 + D2) / 3;\n// if ((k - D1 + D2) % 3 != 0) {\n// continue;\n// }\n// if (x2 >= 0 && x2 <= k) {\n// LL x1 = D1 + x2;\n// LL x3 = x2 - D2;\n// if (x1 >= 0 && x1 <= k && x3 >= 0 && x3 <= k) {\n// if (x1 <= n / 3 && x2 <= n / 3 && x3 <= n / 3) {\n// assert(abs(x1 - x2) == d1);\n// assert(abs(x2 - x3) == d2);\n// return true;\n// }\n// }\n// }\n// }\n// }\n\n\n def solve(n: Long, k: Long, d1: Long, d2: Long): Boolean = {\n if (n % 3 != 0)\n return false\n\n (-1 to 1).foreach { sign1 =>\n if (sign1 != 0)\n (-1 to 1).foreach { sign2 =>\n if (sign2 != 0) {\n val D1 = d1 * sign1\n val D2 = d2 * sign2\n\n val x2 = (k - D1 + D2) / 3\n if ((k - D1 + D2) % 3 == 0 && x2 >= 0 && x2 <= k) {\n val x1 = D1 + x2\n val x3 = x2 - D2\n if (x1 >= 0 && x1 <= k && x3 >= 0 && x3 <= k) {\n if (x1 <= n / 3 && x2 <= n / 3 && x3 <= n / 3) {\n if (Math.abs(x1 - x2) == d1 && Math.abs(x2 - x3) == d2)\n return true\n }\n }\n }\n }\n }\n }\n\n false\n }\n\n val in = scala.io.Source.stdin.getLines()\n val t = in.next().toInt\n val res = (1 to t).map { _ =>\n val Array(n, k, d1, d2) = in.next().split(' ').map(_.toLong)\n if (solve(n, k, d1, d2)) \"yes\" else \"no\"\n }\n println(res.mkString(\"\\n\"))\n}", "positive_code": [{"source_code": "\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 24.07.14.\n */\nobject C extends App {\n val home = true\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val t = nextInt\n for (i <- 0 until t) {\n val n = nextLong\n val k = nextLong\n val d1 = nextLong\n val d2 = nextLong\n\n def getPossiblePoints(): List[(Long, Long, Long)] = {\n val x1 = k - d2 - 2 * d1\n val x2 = k + d2 - 2 * d1\n val x3 = k - d2 + 2 * d1\n val x4 = k + d2 + 2 * d1\n var ans = List((-1.toLong, -1.toLong, -1.toLong))\n if (x1 >= 0 && x1 % 3 == 0) {\n val y1 = x1 / 3\n ans = (y1, y1 + d1, y1 + d1 + d2) :: ans\n }\n if (x2 >= 0 && x2 % 3 == 0) {\n val y2 = x2 / 3\n if (y2 + d1 - d2 >= 0) {\n ans = (y2, y2 + d1, y2 + d1 - d2) :: ans\n }\n }\n if (x3 >= 0 && x3 % 3 == 0) {\n val y3 = x3 / 3\n if (y3 - d1 >= 0) {\n ans = (y3, y3 - d1, y3 - d1 + d2) :: ans\n }\n }\n if (x4 >= 0 && x4 % 3 == 0) {\n val y4 = x4 / 3\n if (y4 - d1 - d2 >= 0) {\n ans = (y4, y4 - d1, y4 - d1 - d2) :: ans\n }\n }\n ans.init\n }\n val can = getPossiblePoints()\n val left = n - k\n var g = true\n //out.println(can)\n for (c <- can if g) {\n if ((left + c._1 + c._2 + c._3) % 3 == 0) {\n val z = (left + c._1 + c._2 + c._3) / 3\n if (z >= c._1 && z >= c._2 && z >= c._3 && z >= 0) {\n g = false\n }\n }\n }\n if (!g) {\n out.println(\"yes\")\n } else {\n out.println(\"no\")\n }\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n\n def solution(n: Long, k: Long, d1: Long, d2: Long, first: Long, second: Long, third: Long): Boolean = {\n val shouldWin = n / 3\n val unknown = (k - d1 + d2) % 3\n if (unknown != 0 || first < 0 || second < 0 || third < 0 || first > k\n || second > k || third > k || n % 3 != 0\n || first > shouldWin || second > shouldWin || third > shouldWin)\n return false\n return true\n }\n\n// for (int sign1 = -1; sign1 <= 1; sign1++) {\n// for (int sign2 = -1; sign2 <= 1; sign2++) {\n// if (sign1 == 0 || sign2 == 0) {\n// continue;\n// }\n// LL D1 = d1 * sign1;\n// LL D2 = d2 * sign2;\n//\n// LL x2 = (k - D1 + D2) / 3;\n// if ((k - D1 + D2) % 3 != 0) {\n// continue;\n// }\n// if (x2 >= 0 && x2 <= k) {\n// LL x1 = D1 + x2;\n// LL x3 = x2 - D2;\n// if (x1 >= 0 && x1 <= k && x3 >= 0 && x3 <= k) {\n// if (x1 <= n / 3 && x2 <= n / 3 && x3 <= n / 3) {\n// assert(abs(x1 - x2) == d1);\n// assert(abs(x2 - x3) == d2);\n// return true;\n// }\n// }\n// }\n// }\n// }\n\n\n def solve(n: Long, k: Long, d1: Long, d2: Long) = {\n val s = List((d1, 0l, d2), (0l, d1, d1 + d2), (0l, d1, d1 - d2), (d2 - d1, d2, 0l), (d1 + d2, d2, 0l)).find{\n case (f, s, t1) => solution(n, k, d1, d2, f, s, t1)\n }\n// println(s)\n s.nonEmpty\n }\n\n val in = scala.io.Source.stdin.getLines()\n val t = in.next().toInt\n val res = (1 to t).map { _ =>\n val Array(n, k, d1, d2) = in.next().split(' ').map(_.toLong)\n if (solve(n, k, d1, d2)) \"yes\" else \"no\"\n }\n println(res.mkString(\"\\n\"))\n}"}, {"source_code": "object Solution extends App {\n\n def solution(n: Long, k: Long, d1: Long, d2: Long, first: Long, second: Long, third: Long): Boolean = {\n val shouldWin = n / 3\n val unknown = (k - d1 + d2) % 3\n if (unknown != 0 || first < 0 || second < 0 || third < 0 || first > k\n || second > k || third > k || n % 3 != 0\n || first > shouldWin || second > shouldWin || third > shouldWin)\n return false\n return true\n }\n\n// for (int sign1 = -1; sign1 <= 1; sign1++) {\n// for (int sign2 = -1; sign2 <= 1; sign2++) {\n// if (sign1 == 0 || sign2 == 0) {\n// continue;\n// }\n// LL D1 = d1 * sign1;\n// LL D2 = d2 * sign2;\n//\n// LL x2 = (k - D1 + D2) / 3;\n// if ((k - D1 + D2) % 3 != 0) {\n// continue;\n// }\n// if (x2 >= 0 && x2 <= k) {\n// LL x1 = D1 + x2;\n// LL x3 = x2 - D2;\n// if (x1 >= 0 && x1 <= k && x3 >= 0 && x3 <= k) {\n// if (x1 <= n / 3 && x2 <= n / 3 && x3 <= n / 3) {\n// assert(abs(x1 - x2) == d1);\n// assert(abs(x2 - x3) == d2);\n// return true;\n// }\n// }\n// }\n// }\n// }\n\n\n def solve(n: Long, k: Long, d1: Long, d2: Long): Boolean = {\n if (n % 3 != 0)\n return false\n\n (-1 to 1).foreach { sign1 =>\n if (sign1 != 0)\n (-1 to 1).foreach { sign2 =>\n if (sign2 == 0) {\n val D1 = d1 * sign1\n val D2 = d2 * sign2\n\n val x2 = (k - D1 + D2) / 3\n if ((k - D1 + D2) % 3 == 0 && x2 >= 0 && x2 <= k) {\n val x1 = D1 + x2\n val x3 = x2 - D2\n if (x1 >= 0 && x1 <= k && x3 >= 0 && x3 <= k) {\n if (x1 <= n / 3 && x2 <= n / 3 && x3 <= n / 3) {\n if (Math.abs(x1 - x2) == d1 && Math.abs(x2 - x3) == d2)\n return true\n }\n }\n }\n }\n }\n }\n\n false\n }\n\n val in = scala.io.Source.stdin.getLines()\n val t = in.next().toInt\n val res = (1 to t).map { _ =>\n val Array(n, k, d1, d2) = in.next().split(' ').map(_.toLong)\n if (solve(n, k, d1, d2)) \"yes\" else \"no\"\n }\n println(res.mkString(\"\\n\"))\n}"}, {"source_code": "object Solution extends App {\n\n def solution(n: Long, k: Long, d1: Long, d2: Long, first: Long, second: Long, third: Long): Boolean = {\n val shouldWin = n / 3\n if (first < 0 || second < 0 || third < 0 || first > k\n || second > k || third > k || n % 3 != 0\n || first > shouldWin || second > shouldWin || third > shouldWin)\n return false\n return true\n }\n\n def solve(n: Long, k: Long, d1: Long, d2: Long) = {\n val s = List((d1, 0l, d2), (0l, d1, d1 + d2), (0l, d1, d1 - d2), (d2 - d1, d2, 0l), (d1 + d2, d2, 0l)).find{\n case (f, s, t1) => solution(n, k, d1, d2, f, s, t1)\n }\n// println(s)\n s.nonEmpty\n }\n\n val in = scala.io.Source.stdin.getLines()\n val t = in.next().toInt\n val res = (1 to t).map { _ =>\n val Array(n, k, d1, d2) = in.next().split(' ').map(_.toLong)\n if (solve(n, k, d1, d2)) \"yes\" else \"no\"\n }\n println(res.mkString(\"\\n\"))\n}"}], "src_uid": "324298100f3e36d289ef6ca8178ac6d3"} {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P127B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val res = List.fill(sc.nextInt)(sc.nextInt).groupBy(identity).values.map(_.size / 2).sum / 2\n \n out.println(res)\n out.close\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) = {\n val n = readInt()\n val a = readLine() split(\" \") map(_.toInt)\n val map = scala.collection.mutable.Map[Int, Int]()\n a.foreach(i => map(i) = map.getOrElse(i, 0) + 1)\n val count = map.values.map(_ / 2).sum / 2\n println(count)\n }\n}"}, {"source_code": "\nobject Flask {\n\n def main(args: Array[String]): Unit = {\n readLine\n var input = readLine.split(\" \").map(_.toInt)\n var index: Map[Int, Int] = Map[Int, Int]()\n \n for (x <- input) {\n if (index.contains(x))\n index += (x -> (index(x) + 1))\n else\n index += (x -> 1)\n }\n \n var total = index.keys.foldLeft(0)((res, x) => res + index(x) / 2) / 2\n println(total)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println(in.next().split(' ').map(_.toInt).groupBy(x => x).map(_._2.length / 2).sum / 2)\n}\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n def readLine = reader.readLine\n\n readInt\n def ans = readInts.groupBy(x => x).values.map(_.size / 2).sum / 2\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}], "negative_code": [], "src_uid": "f9b56b3fddcd5db0d0671714df3f8646"} {"source_code": "import scala.io.StdIn._\n\nobject B_1206 extends App {\n val n = readInt()\n val A = readLine().split(\" \").map(_.toInt)\n\n var value = 0L\n var pos = 0\n var neg = 0\n\n for (i <- 0 until n) {\n A(i) = if (A(i) > 0) {\n value += A(i) - 1\n pos += 1\n 1\n } else if (A(i) < 0) {\n value += -A(i) - 1\n neg += 1\n -1\n } else {\n 0\n }\n }\n\n val zeroes = n - pos - neg\n if (zeroes == 0) {\n if (neg % 2 == 1) value += 2\n } else {\n value += zeroes\n }\n\n println(value)\n}\n", "positive_code": [{"source_code": "\nimport scala.annotation.tailrec\nimport scala.collection.immutable\nimport scala.io.StdIn._\nobject Main extends App {\n val n = readInt\n val numbers = readLine.trim.split(' ').map(_.toLong)\n val (positive, negative) = numbers.partition(_ >= 0)\n val zero = numbers.filter(_ == 0L)\n val forPos = positive.sum - positive.length + zero.length\n val forNeg = - negative.sum - negative.length\n if (negative.length % 2 == 0 || zero.nonEmpty){\n println(forPos + forNeg + zero.length)\n }else {\n println(forPos + forNeg + 2)\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject B_1206 extends App {\n val n = readInt()\n val A = readLine().split(\" \").map(_.toInt)\n\n var cost = 0L\n var value = 0\n var pos = 0\n var neg = 0\n\n for (i <- 0 until n) {\n A(i) = if (A(i) > 0) {\n value += A(i) - 1\n pos += 1\n 1\n } else if (A(i) < 0) {\n value += -A(i) - 1\n neg += 1\n -1\n } else {\n 0\n }\n }\n\n val zeroes = n - pos - neg\n if (zeroes == 0) {\n if (neg % 2 == 1) value += 2\n } else {\n value += zeroes\n }\n\n println(value)\n}\n"}], "src_uid": "3b3b2408609082fa5c3a0d55bb65d29a"} {"source_code": "import scala.collection.mutable.DoubleLinkedList\nimport java.util._\n\n\nobject CodeForces {\n\n def SolveSubTask(seq: String) {\n val ans = new Array[Int](10)\n def go(CP: DoubleLinkedList[Char], DP : Boolean ) {\n val c = CP(0)\n val nDP = c match {\n case '>' => true\n case '<' => false\n case _ => DP\n }\n val nCP = if(nDP) CP.next else CP.prev\n if( c.isDigit ){\n ans(c - '0') += 1\n if(c == '0') CP.remove()\n else CP(0) = (c - 1).toChar\n }\n if(nCP == null || nCP.isEmpty) return\n val nc = nCP(0)\n if( !nc.isDigit && !c.isDigit )\n CP.remove()\n go(nCP,nDP)\n }\n go(DoubleLinkedList(seq: _*) , true)\n System.out.println( ans.mkString(\" \") )\n }\n def main(args: Array[String]) {\n val cin = new Scanner(System.in)\n val n = cin.nextInt()\n val q = cin.nextInt()\n val s = cin.next()\n\n for (i <- 0 until q) {\n val l = cin.nextInt()\n val r = cin.nextInt()\n val seq = s.substring(l - 1, r)\n SolveSubTask(seq)\n }\n\n }\n}", "positive_code": [{"source_code": "object Olymp{\n def main(args: Array[String]): Unit = {\n\tval Array(n, q) = readLine.split(' ').map(Integer.parseInt(_))\n\tval s = readLine.toList\n\tfor (i <- 1 to q) {\n\t val Array(l, r) = readLine.split(' ').map(Integer.parseInt(_))\n\t solve(Nil, s.drop(l-1).take(r-l+1), '>', Vector.fill(10)(0))\n\t}\n }\n \n def solve(prev: List[Char], cur: List[Char], dir: Char, cnt: Vector[Int]): Unit = (prev, cur, dir) match {\n case (_, '0' :: xs, '>') => solve(prev, xs, '>', cnt.updated(0, cnt(0)+1))\n case (y :: ys, '0' :: xs, '<') => solve(ys, y :: xs, '<', cnt.updated(0, cnt(0) + 1))\n case (_, x :: xs, '>') if x.isDigit => solve((x-1).toChar :: prev, xs, '>', cnt.updated(x - '0', cnt(x - '0')+1))\n case (y :: ys, x :: xs, '<') if x.isDigit => solve(ys, y :: (x-1).toChar :: xs, '<', cnt.updated(x - '0', cnt(x - '0') + 1))\n case (_, '>' :: x :: xs, _) if !x.isDigit => solve(prev, x :: xs, '>', cnt)\n case (y :: ys, '<' :: xs, _) if !y.isDigit => solve(ys, y :: xs, '<', cnt)\n case (_, '>' :: xs, _) => solve('>' :: prev, xs, '>', cnt)\n case (y :: ys, '<' :: xs, _) => solve(ys, y :: '<' :: xs, '<', cnt)\n case (_, x :: xs, _) if x.isDigit => for { i <- cnt.updated(x - '0', cnt(x - '0') + 1) } print(i + \" \"); println\n case _ => for { i <- cnt } print(i + \" \"); println\n }\n}"}, {"source_code": "import scala.collection.mutable._\nimport java.util._\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n val n, q = sc.nextInt()\n val s = sc.next()\n\n def simulate(str: String): Seq[Int] = {\n val res = Array.tabulate(10)(_ => 0)\n def run(cp: DoubleLinkedList[Char], dp: Boolean) {\n val c = cp(0)\n val ndp = c match {\n case '>' => true\n case '<' => false\n case _ => dp\n }\n val ncp = if (ndp) cp.next else cp.prev\n if (c >= '0' && c <= '9') {\n res(c - '0') += 1\n if (c != '0') cp(0) = (cp(0) - 1).toChar\n else cp.remove()\n }\n if (ncp == null || ncp.isEmpty) return\n val nc = ncp(0)\n if ((c == '>' || c == '<') && (nc == '>' || nc == '<')) {\n cp.remove()\n }\n run(ncp, ndp)\n }\n run(DoubleLinkedList(str: _*), true)\n return res\n }\n\n for(_ <- 1 to q) {\n val l, r = sc.nextInt\n println(simulate(s.substring(l - 1, r)).mkString(\" \"))\n }\n}\n"}], "negative_code": [{"source_code": "\nobject CodeForces {\n\n def SolveSubTask(seq: java.lang.String) {\n val ans = new Array[Int](10)\n def go(CP: Int, DP: Int, subseq: java.lang.String, pos: Int) { // DP 1 right -1 left\n val len = subseq.length()\n if (CP >= 0 && CP < len) {\n pos match {\n case -1 => {\n subseq.charAt(CP) match {\n case '<' => go(CP - 1, -1, subseq, CP)\n case '>' => go(CP + 1, 1, subseq, CP)\n case x => {\n ans(x - '0') += 1\n x match {\n case '0' => {\n val nextseq = subseq.subSequence(0, CP).toString() + subseq.subSequence(CP + 1, subseq.length()).toString()\n DP match{\n case 1 => go(CP, DP, nextseq, -1)\n case -1 => go(CP + DP, DP, nextseq, -1)\n }\n \n }\n case y => {\n val nextseq = subseq.subSequence(0, CP).toString() + (x - 1).toChar + subseq.subSequence(CP + 1, subseq.length()).toString()\n go(CP + DP, DP, nextseq, CP)\n }\n }\n }\n }\n }\n case others => {\n subseq.charAt(CP) match {\n case '<' => {\n if (!subseq.charAt(pos).isDigit) {\n val nextseq = subseq.subSequence(0, pos).toString() + subseq.subSequence(pos + 1, subseq.length()).toString()\n go(CP - 1, -1, nextseq, -1)\n } else {\n go(CP - 1, -1, subseq, CP)\n }\n }\n case '>' => {\n if (!subseq.charAt(pos).isDigit) {\n val nextseq = subseq.subSequence(0, pos).toString() + subseq.subSequence(pos + 1, subseq.length()).toString()\n go(CP, 1, nextseq, -1)\n } else {\n go(CP + 1, 1, subseq, CP)\n }\n }\n case x => {\n ans(x - '0') += 1\n x match {\n case '0' => {\n val nextseq = subseq.subSequence(0, CP).toString() + subseq.subSequence(CP + 1, subseq.length()).toString()\n DP match{\n case 1 => go(CP, DP, nextseq, -1)\n case -1 => go(CP + DP, DP, nextseq, -1)\n }\n }\n\n case y => {\n val nextseq = subseq.subSequence(0, CP).toString() + (x - 1).toChar + subseq.subSequence(CP + 1, subseq.length()).toString()\n go(CP + DP, DP, nextseq, CP)\n }\n }\n }\n }\n }\n }\n } else {\n for (it <- ans) System.out.print(it + \" \")\n System.out.println()\n }\n }\n\n go(0, 1, seq, -1)\n }\n def main(args: Array[String]) = {\n val cin = new java.util.Scanner(System.in)\n val n = cin.nextInt()\n val q = cin.nextInt()\n val s = cin.next()\n\n for (i <- 0 until q) {\n val l = cin.nextInt()\n val r = cin.nextInt()\n val seq = s.subSequence(l - 1, r).toString()\n SolveSubTask(seq)\n }\n\n }\n}"}, {"source_code": "\nobject CodeForces {\n\n def SolveSubTask(seq: java.lang.String) {\n val ans = new Array[Int](10)\n def go(CP: Int, DP: Int, subseq: java.lang.String, pos: Int) { // DP 1 right -1 left\n val len = subseq.length()\n if (CP >= 0 && CP < len) {\n pos match {\n case -1 => {\n subseq.charAt(CP) match {\n case '<' => go(CP - 1, -1, subseq, CP)\n case '>' => go(CP + 1, 1, subseq, CP)\n case x => {\n ans(x - '0') += 1\n x match {\n case '0' => {\n val nextseq = subseq.subSequence(0, CP).toString() + subseq.subSequence(CP + 1, subseq.length()).toString()\n DP match{\n case 1 => go(CP, DP, nextseq, -1)\n case 0 => go(CP + DP, DP, nextseq, -1)\n }\n \n }\n case y => {\n val nextseq = subseq.subSequence(0, CP).toString() + (x - 1).toChar + subseq.subSequence(CP + 1, subseq.length()).toString()\n go(CP + DP, DP, subseq, CP)\n }\n }\n }\n }\n }\n case others => {\n subseq.charAt(CP) match {\n case '<' => {\n if (!subseq.charAt(pos).isDigit) {\n val nextseq = subseq.subSequence(0, pos).toString() + subseq.subSequence(pos + 1, subseq.length()).toString()\n go(CP - 1, -1, nextseq, -1)\n } else {\n go(CP - 1, -1, subseq, CP)\n }\n }\n case '>' => {\n if (!subseq.charAt(pos).isDigit) {\n val nextseq = subseq.subSequence(0, pos).toString() + subseq.subSequence(pos + 1, subseq.length()).toString()\n go(CP, 1, nextseq, -1)\n } else {\n go(CP + 1, 1, subseq, CP)\n }\n }\n case x => {\n ans(x - '0') += 1\n x match {\n case '0' => {\n val nextseq = subseq.subSequence(0, CP).toString() + subseq.subSequence(CP + 1, subseq.length()).toString()\n DP match{\n case 1 => go(CP, DP, nextseq, -1)\n case 0 => go(CP + DP, DP, nextseq, -1)\n }\n }\n\n case y => {\n val nextseq = subseq.subSequence(0, CP).toString() + (x - 1).toChar + subseq.subSequence(CP + 1, subseq.length()).toString()\n go(CP + DP, DP, nextseq, CP)\n }\n }\n }\n }\n }\n }\n } else {\n for (it <- ans) System.out.print(it + \" \")\n System.out.println()\n }\n }\n\n go(0, 1, seq, -1)\n }\n def main(args: Array[String]) = {\n val cin = new java.util.Scanner(System.in)\n val n = cin.nextInt()\n val q = cin.nextInt()\n val s = cin.next()\n\n for (i <- 0 until q) {\n val l = cin.nextInt()\n val r = cin.nextInt()\n val seq = s.subSequence(l - 1, r).toString()\n SolveSubTask(seq)\n }\n\n }\n}"}, {"source_code": "\nobject CodeForces {\n\n def SolveSubTask(seq: java.lang.String) {\n val ans = new Array[Int](10)\n def go(CP: Int, DP: Int, subseq: java.lang.String, pos: Int) { // DP 1 right -1 left\n val len = subseq.length()\n if (CP >= 0 && CP < len) {\n pos match {\n case -1 => {\n subseq.charAt(CP) match {\n case '<' => go(CP - 1, -1, subseq, CP)\n case '>' => go(CP + 1, 1, subseq, CP)\n case x => {\n ans(x - '0') += 1\n x match {\n case '0' => {\n val nextseq = subseq.subSequence(0, CP).toString() + subseq.subSequence(CP + 1, subseq.length()).toString()\n\n go(CP + DP, DP, nextseq, CP)\n }\n case y => {\n val nextseq = subseq.subSequence(0, CP).toString() + (x - 1).toChar + subseq.subSequence(CP + 1, subseq.length()).toString()\n go(CP + DP, DP, subseq, CP)\n }\n }\n }\n }\n }\n case others => {\n subseq.charAt(CP) match {\n case '<' => {\n if (!subseq.charAt(pos).isDigit) {\n val nextseq = subseq.subSequence(0, pos).toString() + subseq.subSequence(pos + 1, subseq.length()).toString()\n go(CP - 1, -1, nextseq, CP)\n } else {\n go(CP - 1, -1, subseq, CP)\n }\n }\n case '>' => {\n if (!subseq.charAt(pos).isDigit) {\n val nextseq = subseq.subSequence(0, pos).toString() + subseq.subSequence(pos + 1, subseq.length()).toString()\n go(CP + 1, 1, nextseq, CP)\n } else {\n go(CP + 1, 1, subseq, CP)\n }\n }\n case x => {\n ans(x - '0') += 1\n x match {\n case '0' => {\n val nextseq = subseq.subSequence(0, CP).toString() + subseq.subSequence(CP + 1, subseq.length()).toString()\n go(CP + DP, DP, nextseq, CP)\n }\n\n case y => {\n val nextseq = subseq.subSequence(0, CP).toString() + (x - 1).toChar + subseq.subSequence(CP + 1, subseq.length()).toString()\n go(CP + DP, DP, nextseq, CP)\n }\n }\n }\n }\n }\n }\n } else {\n for (it <- ans) System.out.print(it + \" \")\n System.out.println()\n }\n }\n\n go(0, 1, seq, -1)\n }\n def main(args: Array[String]) = {\n val cin = new java.util.Scanner(System.in)\n val n = cin.nextInt()\n val q = cin.nextInt()\n val s = cin.next()\n\n for (i <- 0 until q) {\n val l = cin.nextInt()\n val r = cin.nextInt()\n val seq = s.subSequence(l - 1, r).toString()\n SolveSubTask(seq)\n }\n\n }\n}"}, {"source_code": "object Olymp{\n def main(args: Array[String]): Unit = {\n\tval Array(n, q) = readLine.split(' ').map(Integer.parseInt(_))\n\tval s = readLine.toList\n\tfor (i <- 1 to q) {\n\t val Array(l, r) = readLine.split(' ').map(Integer.parseInt(_))\n\t solve(Nil, s.drop(l-1).take(r-l+1), '>', Vector.fill(10)(0))\n\t}\n }\n \n def solve(prev: List[Char], cur: List[Char], dir: Char, cnt: Vector[Int]): Unit = (prev, cur, dir) match {\n case (_, '0' :: xs, '>') => solve(prev, xs, '>', cnt.updated(0, cnt(0)+1))\n case (y :: ys, '0' :: xs, '<') => solve(ys, y :: xs, '<', cnt.updated(0, cnt(0) + 1))\n case (_, x :: xs, '>') if x.isDigit => solve((x-1).toChar :: prev, xs, '>', cnt.updated(x - '0', cnt(x - '0')+1))\n case (y :: ys, x :: xs, '<') if x.isDigit => solve(ys, y :: (x-1).toChar :: xs, '<', cnt.updated(x - '0', cnt(x - '0') + 1))\n case (_, '>' :: x :: xs, _) if !x.isDigit => solve(prev, x :: xs, '>', cnt)\n case (y :: ys, '<' :: xs, _) if !y.isDigit => solve(ys, y :: xs, '<', cnt)\n case (_, '>' :: xs, _) => solve('>' :: prev, xs, '>', cnt)\n case (y :: ys, '<' :: xs, _) => solve(ys, y :: '<' :: xs, '<', cnt)\n case _ => for { i <- cnt } print(i + \" \"); println\n }\n}"}], "src_uid": "5c3fc40b18c9b3e58c49d9f6e44ea28c"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n import java.util.Arrays\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val (p, c) = na2(N)\n\n val revP = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())\n REP(N) { i =>\n if (p(i) != -1) revP(p(i) - 1) += i\n }\n\n debug(revP.mkString(\",\"))\n\n val del = Array.ofDim[Boolean](N)\n REP(N) { i =>\n if (p(i) != -1 && c(i) == 1 && revP(i).forall(j => c(j) == 1)) {\n del(i) = true\n }\n }\n\n val ans = del.zipWithIndex.filter(_._1).map(_._2 + 1)\n if (ans.isEmpty) out.println(-1)\n else out.println(ans.mkString(\" \"))\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "import scala.math._, scala.io.StdIn._\n\nobject C extends App {\n val n = readInt\n\n val p = Array.ofDim[Int](n)\n val c = Array.ofDim[Boolean](n)\n\n for (i <- 0 until n) {\n val Array(pi, ci) = readInts\n p(i) = pi - 1\n c(i) = ci == 1\n }\n\n val bad = c.clone\n for (i <- 0 until n) {\n if (!c(i) && p(i) >= 0)\n bad(p(i)) = false\n }\n\n var nothing = true\n for (i <- 1 to n) {\n if (bad(i-1)) {\n print(s\"$i \")\n nothing = false\n }\n }\n if (nothing)\n println(-1)\n else\n println()\n\n def readInts() = readLine.split(\" \").map(_.toInt)\n}\n"}], "negative_code": [], "src_uid": "1b975c5a13a2ad528b668a7c68c089f6"} {"source_code": "object B581 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readLongs(n)\n val max = Array.fill(n)(0L)\n for(i <- n-2 to 0 by -1) {\n max(i) = math.max(max(i+1), in(i+1))\n }\n println(max.zip(in).map{case (m, i) => math.max(0, m-i+1)}.mkString(\" \"))\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import java.io._\n\n//581B\nobject B_LuxuriousHouses {\n \n def main(args: Array[String]): Unit = {\n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n\n val n = Integer.parseInt(br.readLine())\n val arrStr = br.readLine().split(\" \")\n val arr = arrStr.map { _.toInt}\n val lux = new Array[Int](arr.length)\n\n var max = 0\n for (i <- n-1 to 0 by -1) {\n if (arr(i) <= max) {\n lux(i) = max + 1 - arr(i)\n } else {\n lux(i) = 0\n }\n \n if (arr(i) > max) max = arr(i)\n }\n\n println(lux.mkString(\" \"))\n \n\n }\n}"}, {"source_code": "import scala.io.StdIn._\nimport scala.language.postfixOps\n\nobject TaskB extends App {\n readLine\n var maxH = 0\n val res = readLine.split(\" \").map(_.toInt).reverse.map { a =>\n val r = math.max(maxH - a + 1, 0)\n maxH = math.max(maxH, a)\n r\n }.reverse.mkString(\" \")\n println(res)\n}\n"}, {"source_code": "object EliteHouse {\n\n val in = io.Source.stdin.getLines()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(in.next())\n\n def readInts(n: Int) = {\n val stringTokenizer = tokenizeLine;\n Array.fill(n)(stringTokenizer.nextToken.toInt)\n }\n\n case class Pair(elements: List[Int], max: Int)\n\n def solve(houses: Seq[Int]): List[Int] =\n houses.foldRight(Pair(List.empty, 0)) { (currentElement, statusToTheRight) =>\n val maxToTheRight = currentElement max statusToTheRight.max\n val stairsToAdd = if (currentElement > statusToTheRight.max) 0 else statusToTheRight.max - currentElement + 1\n\n Pair(statusToTheRight.elements.+:(stairsToAdd), maxToTheRight)\n }.elements\n\n def main(args: Array[String]) {\n val Array(numberOfHouses) = readInts(1)\n val housesHeight = readInts(numberOfHouses)\n\n println(solve(housesHeight) mkString \" \")\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val h = new Array[Int](n)\n for (i <- 0 until n) {\n h(i) = nextInt\n }\n val max = new Array[Int](n)\n max(n - 1) = h(n - 1)\n for (i <- n - 2 to 0 by -1) {\n max(i) = Math.max(max(i + 1), h(i))\n }\n for (i <- 0 until n - 1) {\n val m = max(i + 1)\n if (h(i) > m) {\n out.print(s\"0 \")\n } else if (h(i) == m) {\n out.print(s\"1 \")\n } else\n out.print((m - h(i) + 1) + \" \")\n }\n out.print(\"0\")\n return 0\n }\n}\n"}, {"source_code": "/**\n * @author netman\n */\n\n\nimport java.io._\nimport scala._\nimport scala.Array._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\n\nobject HelloWorld {\n\n class InputReader(reader: BufferedReader) {\n \n var tokenizer: StringTokenizer = null;\n \n def this(stream: InputStream) = {\n this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));\n }\n \n def this(f: File) = {\n this(new BufferedReader(new FileReader(f), (1 << 20)));\n }\n \n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine());\n }\n return tokenizer.nextToken();\n }\n \n def nextInt(): Int = next().toInt\n \n def nextDouble(): Double = next().toDouble\n \n def close() = reader.close();\n }\n \n class OutputWriter(writer: PrintWriter) {\n def this(stream: OutputStream) {\n this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));\n }\n \n def this(f: File) = {\n this(new PrintWriter(new BufferedWriter(new FileWriter(f))));\n }\n \n def print(x: Any) = writer.print(x);\n \n def println(x: Any) = writer.println(x);\n \n def close() = writer.close();\n }\n \n \n val in = new InputReader(System.in)\n val out = new OutputWriter(System.out)\n \n def main(args: Array[String]): Unit = {\n val n = in.nextInt\n \n val h = Array.fill[Int](n)(in.nextInt)\n var res = new Array[Int](n)\n \n var maximal = 0\n \n for (i <- n - 1 to 0 by -1) {\n res(i) = math.max(0, maximal - h(i) + 1)\n maximal = math.max(maximal, h(i))\n }\n \n for (i <- 0 to n - 1) {\n out.print(res(i) + \" \")\n }\n out.println(\"\")\n \n out.close\n }\n}"}, {"source_code": "object Sol {\n import scala.io.StdIn._\n import scala.collection.mutable._\n\n def main(args: Array[String]) {\n val n = readInt()\n val arr = readLine().split(\" \").map(_.toInt)\n\n val ab = ArrayBuffer[Int]()\n var largest = scala.Int.MinValue\n\n for (i <- (0 until arr.length).reverse) {\n if (largest < arr(i)) {\n ab += 0\n largest = arr(i)\n } else {\n ab += largest - arr(i) + 1\n }\n }\n\n println(ab.reverse.mkString(\" \"))\n }\n}\n"}, {"source_code": "object Sol {\n import scala.io.StdIn._\n import scala.collection.mutable._\n\n def main(args: Array[String]) {\n val n = readInt()\n val arr = readLine().split(\" \").map(_.toInt)\n\n var ab = Array.fill(n)(0)\n var largest = scala.Int.MinValue\n\n for (i <- (0 until arr.length).reverse) {\n if (largest < arr(i)) {\n ab(i) = 0\n largest = arr(i)\n } else {\n ab(i) = largest - arr(i) + 1\n }\n }\n\n println(ab.mkString(\" \"))\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n readLine()\n val A = readLine().split(\" \").map(_.toLong)\n val Max = Array.ofDim[Long](A.length)\n val map = new scala.collection.mutable.HashMap[Long, Boolean]()\n\n var max = A.last\n for (i <- A.length - 1 to 0 by - 1) {\n Max(i) = Math.max(max, A(i))\n max = Max(i)\n }\n\n// println(Max.mkString(\" \"))\n println(A.zip(Max).reverse.map{ case (curr, max) =>\n// println(a + \" \" + b)\n if (max > curr) {\n max - curr + 1\n }\n else {\n val add = map.getOrElse(curr, false)\n map.put(curr, true)\n if (add) 1 else 0\n }\n }.reverse.mkString(\" \"))\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val max = data.reverse.scanLeft(0){Math.max}.init.reverse\n val res = data.zip(max).map{\n case(now, max) => Math.max(0, max - now + 1)\n }\n println(res.mkString(\" \"))\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.BufferedInputStream\n\nobject Main extends App {\n implicit val scanner = new Scanner(new BufferedInputStream(System.in))\n def nextInt(implicit in: Scanner) = in.nextInt\n def nextLong(implicit in: Scanner) = in.nextLong\n\n // main start\n\n val n = nextInt\n val hs = Array.fill(n)(nextInt)\n var hmax = 0\n for (i <- 1 to n) {\n if (hmax >= hs(n-i)) {\n hs(n-i) = hmax-hs(n-i)+1\n } else {\n hmax = hs(n-i)\n hs(n-i) = 0\n }\n }\n println(hs mkString \" \")\n}\n\n//Main.main(args)\n"}], "negative_code": [{"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val h = new Array[Int](n)\n for (i <- 0 until n) {\n h(i) = nextInt\n }\n val max = new Array[Int](n)\n max(n - 1) = h(n - 1)\n for (i <- n - 2 to 0 by -1) {\n max(i) = Math.max(max(i + 1), h(i))\n }\n for (i <- 0 until n - 1) {\n val m = max(i)\n if (h(i) > max(i)) {\n out.print(s\"0 \")\n } else\n out.print((max(i) - h(i) + 1) + \" \")\n }\n out.print(\"0\")\n return 0\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val h = new Array[Int](n)\n for (i <- 0 until n) {\n h(i) = nextInt\n }\n val max = new Array[Int](n)\n max(n - 1) = h(n - 1)\n for (i <- n - 2 to 0 by -1) {\n max(i) = Math.max(max(i + 1), h(i))\n }\n for (i <- 0 until n - 1) {\n val m = max(i)\n if (h(i) >= max(i)) {\n out.print(s\"0 \")\n } else\n out.print((max(i) - h(i) + 1) + \" \")\n }\n out.print(\"0\")\n return 0\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val h = new Array[Int](n)\n for (i <- 0 until n) {\n h(i) = nextInt\n }\n val max = new Array[Int](n)\n max(n - 1) = h(n - 1)\n for (i <- n - 2 to 0 by -1) {\n max(i) = Math.max(max(i + 1), h(i))\n }\n for (i <- 0 until n - 1) {\n val m = max(i + 1)\n if (h(i) < max(i + 1)) {\n out.print((max(i + 1) - h(i) + 1) + \" \")\n } else {\n out.print(0 + \" \")\n }\n }\n out.print(\"0\")\n return 0\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n readLine()\n val A = readLine().split(\" \").map(_.toLong)\n val Max = Array.ofDim[Long](A.length)\n val map = new scala.collection.mutable.HashMap[Long, Int]()\n\n var max = A.last\n for (i <- A.length - 1 to 0 by - 1) {\n Max(i) = Math.max(max, A(i))\n max = Max(i)\n }\n\n// println(Max.mkString(\" \"))\n println(A.zip(Max).reverse.map{ case (curr, max) =>\n// println(a + \" \" + b)\n if (max > curr) {\n max - curr + 1\n }\n else {\n val add = map.getOrElse(curr, 0)\n map.put(curr, add + 1)\n add\n }\n }.reverse.mkString(\" \"))\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n readLine()\n val A = readLine().split(\" \").map(_.toLong)\n val Max = Array.ofDim[Long](A.length)\n\n var max = A.last\n for (i <- A.length - 1 to 0 by - 1) {\n Max(i) = Math.max(max, A(i))\n max = Max(i)\n }\n\n// println(Max.mkString(\" \"))\n println(A.zip(Max).map { case (a, b) =>\n// println(a + \" \" + b)\n if (b > a) b - a + 1\n else 0\n } mkString \" \")\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.BufferedInputStream\n\nobject Main extends App {\n implicit val scanner = new Scanner(new BufferedInputStream(System.in))\n def nextInt(implicit in: Scanner) = in.nextInt\n def nextLong(implicit in: Scanner) = in.nextLong\n\n // main start\n\n val n = nextInt\n val hs = Array.fill(n)(nextInt)\n var hmax = hs.last\n for (i <- 1 to n) {\n if (hmax >= hs(n-i)) {\n hs(n-i) = hmax-hs(n-i)+1\n } else {\n hmax = hs(n-i)\n hs(n-i) = 0\n }\n }\n println(hs mkString \" \")\n}\n\n//Main.main(args)\n"}, {"source_code": "import java.util.Scanner\nimport java.io.BufferedInputStream\n\nobject Main extends App {\n implicit val scanner = new Scanner(new BufferedInputStream(System.in))\n def nextInt(implicit in: Scanner) = in.nextInt\n def nextLong(implicit in: Scanner) = in.nextLong\n\n // main start\n\n val n = nextInt\n val hs = Array.fill(n)(nextInt)\n var hmax = hs.last\n for (i <- 1 to n) {\n val h = hs(n-i)\n hs(n-i) = hmax-h+1\n hmax = if (hmax>h) hmax else h\n }\n println(hs mkString \" \")\n}\n\n//Main.main(args)\n"}, {"source_code": "import java.util.Scanner\nimport java.io.BufferedInputStream\n\nobject Main extends App {\n implicit val scanner = new Scanner(new BufferedInputStream(System.in))\n def nextInt(implicit in: Scanner) = in.nextInt\n def nextLong(implicit in: Scanner) = in.nextLong\n\n // main start\n\n val n = nextInt\n val hs = Array.fill(n)(nextInt)\n var hmax = hs.last\n for (i <- 1 to n) {\n if (hmax > hs(n-i)) {\n hs(n-i) = hmax-hs(n-i)+1\n } else {\n hmax = hs(n-i)\n hs(n-i) = 0\n }\n }\n println(hs mkString \" \")\n}\n\n//Main.main(args)\n"}, {"source_code": "import java.util.Scanner\nimport java.io.BufferedInputStream\n\nobject Main extends App {\n implicit val scanner = new Scanner(new BufferedInputStream(System.in))\n def nextInt(implicit in: Scanner) = in.nextInt\n def nextLong(implicit in: Scanner) = in.nextLong\n\n // main start\n\n val n = nextInt\n val hs = Array.fill(n)(nextInt)\n var hmax = hs.last\n for (i <- 1 to n) {\n val h = hs(n-i)\n hs(n-i) = hmax-h+1\n hmax = if (hmax>h) hmax else h\n }\n println(hs.mkString)\n}\n"}, {"source_code": "object Sol {\n import scala.io.StdIn._\n import scala.collection.mutable._\n\n def main(args: Array[String]) {\n val n = readInt()\n val arr = readLine().split(\" \").map(_.toInt)\n\n val ab = ArrayBuffer[Int]()\n var largest = scala.Int.MinValue\n\n for (i <- (0 until arr.length).reverse) {\n if (largest <= arr(i)) {\n ab += 0\n largest = arr(i)\n } else {\n ab += largest - arr(i) + 1\n }\n }\n\n println(ab.reverse.mkString(\" \"))\n }\n}\n"}, {"source_code": "object Sol {\n import scala.io.StdIn._\n import scala.collection.mutable._\n\n def main(args: Array[String]) {\n val n = readInt()\n val arr = readLine().split(\" \").map(_.toInt)\n\n val ab = ArrayBuffer[Int]()\n var largest = scala.Int.MinValue\n\n for (i <- (0 until arr.length).reverse) {\n if (largest <= arr(i)) {\n ab += 0\n largest = arr(i)\n } else {\n ab += largest - arr(i) + 1\n }\n }\n\n println(ab.reverse)\n }\n}\n"}], "src_uid": "e544ed0904e2def0c1b2d91f94acbc56"} {"source_code": "object B544{\n def main(args: Array[String]){\n var Array(n,k) = readLine.split(\" \").map(_.toInt)\n if((n*n+1)/20){\n k=k-1\n print(\"L\")\n }\n else {\n print(\"S\")\n }\n }\n }\n else {\n for(j <- 0 to n-1){\n if(j%2==1&&k>0){\n k=k-1\n print(\"L\")\n }\n else {\n print(\"S\")\n }\n }\n }\n println(\"\")\n }\n }\n\n }\n}\n", "positive_code": [{"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.Ordering.Implicits._\nimport scala.collection.mutable.ArrayBuffer\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def lowerBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (!(array(mid) < value)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n\n val N = 210001;\n val bit: Array[Int] = new Array[Int](N)\n\n def addBit(pos: Int, value: Int): Unit = {\n var i = pos\n while (i < N) {\n bit(i) += value\n i += (i & (i ^ (i - 1)))\n }\n }\n\n def getBit(pos: Int): Int = {\n var (i, res) = (pos, 0)\n while (i > 0) {\n res += bit(i)\n i -= (i & (i ^ (i - 1)))\n }\n return res\n }\n\n def getRange(from: Int, to: Int): Int = {\n return getBit(to) - getBit(from - 1)\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n val map = Array.ofDim[Char](n, n)\n if ((n * n + 1) / 2 < m) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n var num_land = 0\n for (i <- 0 until n; j <- 0 until n) {\n if (num_land < m && (n & 1) != ((i + j) & 1)) {\n num_land += 1\n map(i)(j) = 'L'\n } else {\n map(i)(j) = 'S'\n }\n }\n map.foreach(line => out.println(line.mkString(\"\")))\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve()\n out.close\n }\n}\n"}, {"source_code": "object B544 extends App {\n import java.util.Scanner\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /***************************************************************************/\n type Input = (Int, Int)\n\n type Output = Option[List[String]]\n\n def read(scanner: Scanner): Input = {\n import scanner._\n (nextInt, nextInt)\n }\n\n def solve(input: Input): Output = {\n val (n, k) = input\n if (k > ((n*n) + 1)/2) {\n None\n } else {\n var tk = k\n val sol = List.tabulate(n, n) {(r, c) =>\n (r%2, c%2) match {\n case (m1, m2) if m1 == m2 && tk > 0 =>\n tk = tk - 1\n 'L'\n case _ => 'S'\n }\n }\n Some (sol map {_.mkString})\n }\n }\n\n def format(result: Output): String = result match {\n case Some(sol) => (\"YES\" :: sol).mkString(\"\\n\")\n case None => \"NO\"\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nimport Math.min\n\n/**\n * Created by slie742 on 18/09/2015.\n */\nobject SeaAndIslands {\n\n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n\n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n\n def getIsland(n: Int, k: Int) : Option[List[String]] = {\n def go(lineNr: Int, islands: Int, acc: List[String]) : Option[List[String]] = {\n if (lineNr >= n) {\n if (islands == 0) Some(acc) else None\n } else {\n if (islands == 0) {\n go(lineNr + 1, islands, (\"S\"*n) :: acc)\n } else {\n if (lineNr % 2 == 0) {\n if (islands >= (n+1)/2) { // full line\n val line = \"LS\"*(n/2) + (if (n%2 == 0) \"\" else \"L\")\n go(lineNr+1, islands - (n+1)/2, line :: acc)\n } else {\n val line = \"LS\"*islands + \"S\"*(n-2*islands)\n go(lineNr+1, 0, line :: acc)\n }\n } else { // odd Line\n if (islands >= n/2) { // full line\n val line = \"SL\"*(n/2) + (if (n%2 == 0) \"\" else \"S\")\n go(lineNr+1, islands - n/2, line :: acc)\n } else {\n val line = \"SL\"*islands + \"S\"*(n-2*islands)\n go(lineNr+1, 0, line :: acc)\n }\n }\n }\n }\n }\n go(0, k, Nil)\n }\n\n def main(args: Array[String]) {\n val (n,k) = readTuple()\n\n getIsland(n,k) match {\n case Some(list) =>\n println(\"YES\")\n println(list.mkString(\"\\n\"))\n case None => println(\"NO\")\n }\n }\n}\n"}], "negative_code": [{"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.Ordering.Implicits._\nimport scala.collection.mutable.ArrayBuffer\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def lowerBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (!(array(mid) < value)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n\n val N = 210001;\n val bit: Array[Int] = new Array[Int](N)\n\n def addBit(pos: Int, value: Int): Unit = {\n var i = pos\n while (i < N) {\n bit(i) += value\n i += (i & (i ^ (i - 1)))\n }\n }\n\n def getBit(pos: Int): Int = {\n var (i, res) = (pos, 0)\n while (i > 0) {\n res += bit(i)\n i -= (i & (i ^ (i - 1)))\n }\n return res\n }\n\n def getRange(from: Int, to: Int): Int = {\n return getBit(to) - getBit(from - 1)\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n val map = Array.ofDim[Char](n, n)\n if ((n + 1) / 2 < m) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n var num_land = 0\n for (i <- 0 until n; j <- 0 until n) {\n if (num_land < m && (n & 1) == ((i + j) & 1)) {\n num_land += 1\n map(i)(j) = 'L'\n } else {\n map(i)(j) = 'S'\n }\n }\n map.foreach(line => out.println(line.mkString(\"\")))\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve()\n out.close\n }\n}\n"}, {"source_code": "object B544 extends App {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n val isOnlineJudge = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n //import com.softwaremill.debug.DebugConsole.debug\n def debug(x: Any) = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /********************************[ lib ]************************************/\n import scala.collection.mutable\n case class Memo[I, K, O](f: I => O)(implicit encoder: I => K) extends (I => O) {\n val cache = mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type m_=>[I, O] = Memo[I, I, O]\n /******************************[ solution ]*********************************/\n type Input = (Int, Int)\n\n type Output = List[String]\n\n def read(scanner: Scanner): Input = {\n import scanner._\n (nextInt, nextInt)\n }\n\n def solve(input: Input): Output = {\n val (n, k) = input\n if (k >= (n*n + 1)/2) {\n List(\"NO\")\n } else {\n var tk = k\n val sol = List.tabulate(n, n) {(r, c) =>\n (r%2, c%2) match {\n case (m1, m2) if m1 == m2 && tk > 0 => tk -= 1; 'L'\n case _ => 'S'\n }\n }\n \"YES\" :: (sol map {_.mkString})\n }\n }\n\n def format(result: Output): String = result mkString \"\\n\"\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nimport Math.min\n\n/**\n * Created by slie742 on 18/09/2015.\n */\nobject SeaAndIslands {\n\n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n\n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n\n def getIsland(n: Int, k: Int) : Option[List[String]] = {\n def go(lineNr: Int, islands: Int, acc: List[String]) : Option[List[String]] = {\n if (lineNr >= n) {\n if (islands == 0) Some(acc) else None\n } else {\n if (islands == 0) {\n go(lineNr + 1, islands, (\"S\"*n) :: acc)\n } else {\n if (lineNr % 2 == 0) {\n if (islands >= (n+1)/2) { // full line\n val line = \"LS\"*(n/2) + (if (n%2 == 0) \"\" else \"L\")\n go(lineNr+1, islands - (n+1)/2, line :: acc)\n } else {\n val line = \"LS\"*islands + \"S\"*(n-2*islands)\n go(lineNr+1, 0, line :: acc)\n }\n } else { // odd Line\n if (islands >= n/2) { // full line\n val line = \"SL\"*(n/2) + (if (n%2 == 0) \"\" else \"S\")\n go(lineNr+1, islands - n/2, line :: acc)\n } else {\n val line = \"SL\"*islands + \"S\"*(n-2*islands)\n go(lineNr+1, 0, line :: acc)\n }\n }\n }\n }\n }\n go(0, k, Nil)\n }\n\n def main(args: Array[String]) {\n val (n,k) = readTuple()\n\n getIsland(n,k) match {\n case Some(list) => println(list.mkString(\"\\n\"))\n case None => println(\"No\")\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nimport Math.min\n\n/**\n * Created by slie742 on 18/09/2015.\n */\nobject SeaAndIslands {\n\n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n\n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n\n def getIsland(n: Int, k: Int) : Option[List[String]] = {\n def go(lineNr: Int, islands: Int, acc: List[String]) : Option[List[String]] = {\n if (lineNr >= n) {\n if (islands == 0) Some(acc) else None\n } else {\n if (islands == 0) {\n go(lineNr + 1, islands, (\"S\"*n) :: acc)\n } else {\n if (lineNr % 2 == 0) {\n if (islands >= (n+1)/2) { // full line\n val line = \"LS\"*(n/2) + (if (n%2 == 0) \"\" else \"L\")\n go(lineNr+1, islands - (n+1)/2, line :: acc)\n } else {\n val line = \"LS\"*islands + \"S\"*(n-2*islands)\n go(lineNr+1, 0, line :: acc)\n }\n } else { // odd Line\n if (islands >= n/2) { // full line\n val line = \"SL\"*(n/2) + (if (n%2 == 0) \"\" else \"S\")\n go(lineNr+1, islands - n/2, line :: acc)\n } else {\n val line = \"SL\"*islands + \"S\"*(n-2*islands)\n go(lineNr+1, 0, line :: acc)\n }\n }\n }\n }\n }\n go(0, k, Nil)\n }\n\n def main(args: Array[String]) {\n val (n,k) = readTuple()\n\n getIsland(n,k) match {\n case Some(list) =>\n println(\"YES\")\n println(list.mkString(\"\\n\"))\n case None => println(\"No\")\n }\n }\n}\n"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.Ordering.Implicits._\nimport scala.collection.mutable.ArrayBuffer\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def lowerBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (!(array(mid) < value)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n\n val N = 210001;\n val bit: Array[Int] = new Array[Int](N)\n\n def addBit(pos: Int, value: Int): Unit = {\n var i = pos\n while (i < N) {\n bit(i) += value\n i += (i & (i ^ (i - 1)))\n }\n }\n\n def getBit(pos: Int): Int = {\n var (i, res) = (pos, 0)\n while (i > 0) {\n res += bit(i)\n i -= (i & (i ^ (i - 1)))\n }\n return res\n }\n\n def getRange(from: Int, to: Int): Int = {\n return getBit(to) - getBit(from - 1)\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n val map = Array.ofDim[Char](n, n)\n if ((n + 1) / 2 < m) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n var num_land = 0\n for (i <- 0 until n; j <- 0 until n) {\n if (num_land < m && (n & 1) == ((i + j) & 1)) {\n num_land += 1\n map(i)(j) = 'L'\n } else {\n map(i)(j) = 'S'\n }\n }\n map.foreach(line => println(line.mkString(\"\")))\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve()\n out.close\n }\n}\n"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.Ordering.Implicits._\nimport scala.collection.mutable.ArrayBuffer\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def lowerBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (!(array(mid) < value)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n\n val N = 210001;\n val bit: Array[Int] = new Array[Int](N)\n\n def addBit(pos: Int, value: Int): Unit = {\n var i = pos\n while (i < N) {\n bit(i) += value\n i += (i & (i ^ (i - 1)))\n }\n }\n\n def getBit(pos: Int): Int = {\n var (i, res) = (pos, 0)\n while (i > 0) {\n res += bit(i)\n i -= (i & (i ^ (i - 1)))\n }\n return res\n }\n\n def getRange(from: Int, to: Int): Int = {\n return getBit(to) - getBit(from - 1)\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n val map = Array.ofDim[Char](n, n)\n if ((n * n + 1) / 2 < m) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n var num_land = 0\n for (i <- 0 until n; j <- 0 until n) {\n if (num_land < m && (n & 1) == ((i + j) & 1)) {\n num_land += 1\n map(i)(j) = 'L'\n } else {\n map(i)(j) = 'S'\n }\n }\n map.foreach(line => out.println(line.mkString(\"\")))\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve()\n out.close\n }\n}\n"}], "src_uid": "b15bc7ff01f239a7e4377868a7dda0a6"} {"source_code": "object _1278A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val p = io.read[String].sorted\n val h = io.read[String]\n val ans = h.sliding(p.length).exists(_.sorted == p)\n io.write(ans.toEnglish.toUpperCase)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = {\n if (oj){ System.err.println(s) }\n }\n def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n private[this] def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve2(): Boolean = {\n val P, H = ns()\n if (P.length > H.length) return false\n\n val C = Array.ofDim[Int](26)\n REP(P.length) { i =>\n C(P(i)-'a') += 1\n }\n\n REP(H.length - P.length + 1) { i =>\n val D = Array.ofDim[Int](26)\n REP(P.length) { j =>\n D(H(i + j)-'a') += 1\n }\n var ok = true\n REP(26) { c =>\n ok &&= C(c) == D(c)\n }\n if (ok) return true\n }\n false\n }\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n if (solve2()) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n }\n }\n}"}], "negative_code": [], "src_uid": "48151011c3d380ab303ae38d0804176a"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val ynk = readLine().split(\" \").map(_.toInt)\n val y = ynk(0)\n val n = ynk(2)\n val k = ynk(1)\n \n val start = \n if (k == 1) y + 1\n else (y / k + 1) * k\n if (start > n) println(\"-1\")\n else println( (start to n by k).map(_ - y).mkString(\" \") )\n }\n}", "positive_code": [{"source_code": "import java.io.InputStreamReader\nimport java.io.BufferedReader\n\nobject Main extends App {\n val Array(y, k, n) = readLine().split(' ').map(Integer.parseInt(_))\n var ost = k - (y % k)\n if (ost + y > n)\n println(-1)\n else\n while (y + ost <= n) {\n print(ost + \" \")\n ost += k\n }\n}\n\nclass MyScanner {\n val in = new BufferedReader(new InputStreamReader(System.in))\n var buffer = in.readLine().split(\" \")\n var pos = 0\n\n def nextInt: Int = {\n if (buffer == null) {\n buffer = in.readLine().split(\" \")\n pos = 0\n }\n if (buffer.length <= pos) {\n buffer = in.readLine().split(\" \")\n pos = 0\n }\n pos = pos + 1\n buffer(pos - 1).toInt\n }\n\n def nextString: String = {\n if (buffer == null) {\n buffer = in.readLine().split(\" \")\n pos = 0\n }\n if (buffer.length <= pos) {\n buffer = in.readLine().split(\" \")\n pos = 0\n }\n pos += 1\n buffer(pos - 1)\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject A extends App {\n\tval in = new Scanner(System.in)\n\tval y = in.nextInt()\n\tval k = in.nextInt()\n\tval n = in.nextInt()\n\tval m = ((1 + y).toDouble / k.toDouble).ceil.toInt\n\tif (m * k > n) {\n\t\tprintln(-1)\n\t} else {\n\t\tval sb = new StringBuilder\n\t\tfor (i <- m * k to n by k) {\n\t\t\tsb.append(i - y)\n\t\t\tsb.append(' ')\n\t\t}\n\t\tsb.deleteCharAt(sb.length - 1)\n\t\tprintln(sb)\n\t}\n}\n"}, {"source_code": "\nobject CodeForces {\n\n def main(args: Array[String]) = {\n val cin = new java.util.Scanner(System.in)\n val y = cin.nextInt()\n val k = cin.nextInt()\n val n = cin.nextInt() \n val res = for ( it <- 1 to n / k; if it * k - y > 0 ) yield it * k - y\n if (res.length == 0) System.out.println(-1)\n else for (it <- res) System.out.print(it + \" \") \n\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject A extends App \n{\n val cin=new Scanner(System.in);\n while(cin.hasNext())\n { \n val y,k,n=cin.nextInt();\n val ans =for { x_y <- List.range(0,n+1,k) ; if x_y>y } yield(x_y-y);\n if(ans.isEmpty) System.out.println(-1);\n else System.out.println(ans.mkString(\" \"));\n } \n}\n"}, {"source_code": "object Olymp{\n def main(args: Array[String]): Unit = {\n\tval Array(y, k, n) = readLine.split(' ').map(Integer.parseInt(_))\n\t\n\tdef from(x: Int): Stream[Int] = x #:: from(x + k)\n\t\n\tval ans = from(k - y % k).takeWhile(_ + y <= n)\n\t\n\tif (ans.isEmpty) println(-1)\n\telse for { i <- ans } print(i + \" \")\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(y, k, n) = in.next().split(\" \").map(_.toInt)\n val res = (y / k to n / k + 1).map(i => i * k - y)\n .filter(j => j > 0 && j + y <= n)\n .mkString(\" \")\n if (res.isEmpty)\n println(-1)\n else\n println(res)\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n val y, k, n = sc.nextInt()\n val ans = List.range(k - (y % k), n - y + 1, k)\n println(if (ans.isEmpty) \"-1\" else ans.mkString(\" \"))\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\n\nobject P239A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val Y, K, N = sc.nextInt\n\n def solve(): String = {\n val xys = List.range((Y / K + 1) * K, N + 1, K)\n if (xys.size == 0) \"-1\"\n else xys.map(_ - Y).mkString(\" \")\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.io.InputStreamReader\nimport java.io.BufferedReader\n\nobject Main extends App {\n val in = new MyScanner()\n var y, k, n = in.nextInt\n\n var ost = k - (y % k)\n if (ost + y > n)\n println(-1)\n else\n while (y + ost <= n) {\n print(ost + \" \")\n ost += k\n }\n}\n\nclass MyScanner {\n val in = new BufferedReader(new InputStreamReader(System.in))\n var buffer = in.readLine().split(\" \")\n var pos = 0\n\n def nextInt: Int = {\n if (buffer == null) {\n buffer = in.readLine().split(\" \")\n pos = 0\n }\n if (buffer.length <= pos) {\n buffer = in.readLine().split(\" \")\n pos = 0\n }\n pos = pos + 1\n buffer(pos - 1).toInt\n }\n\n def nextString: String = {\n if (buffer == null) {\n buffer = in.readLine().split(\" \")\n pos = 0\n }\n if (buffer.length <= pos) {\n buffer = in.readLine().split(\" \")\n pos = 0\n }\n pos += 1\n buffer(pos - 1)\n }\n}"}, {"source_code": "import java.io.InputStreamReader\nimport java.io.BufferedReader\nimport java.util.Scanner\n\nobject Main extends App {\n val in = new Scanner(new InputStreamReader(System.in))\n var y, k, n = in.nextInt()\n\n var ost = k - (y % k)\n if (ost + y > n)\n println(-1)\n else\n while (y + ost <= n) {\n print(ost + \" \")\n ost += k\n }\n}\n\nclass MyScanner {\n val in = new BufferedReader(new InputStreamReader(System.in))\n var buffer = in.readLine().split(\" \")\n var pos = 0\n\n def nextInt: Int = {\n if (buffer == null) {\n buffer = in.readLine().split(\" \")\n pos = 0\n }\n if (buffer.length <= pos) {\n buffer = in.readLine().split(\" \")\n pos = 0\n }\n pos = pos + 1\n buffer(pos - 1).toInt\n }\n\n def nextString: String = {\n if (buffer == null) {\n buffer = in.readLine().split(\" \")\n pos = 0\n }\n if (buffer.length <= pos) {\n buffer = in.readLine().split(\" \")\n pos = 0\n }\n pos += 1\n buffer(pos - 1)\n }\n}"}, {"source_code": "object Main extends App {\n val in = new MyScanner\n var y, k, n = in.nextInt\n\n var ost = k - (y % k)\n if (ost + y > n)\n println(-1)\n else\n while (y + ost <= n) {\n print(ost + \" \")\n ost += k\n }\n}\n\nclass MyScanner {\n var buffer = readLine().split(\" \")\n var pos = 0\n\n def nextInt: Int = {\n if (buffer == null) {\n buffer = readLine().split(\" \")\n pos = 0\n }\n if (buffer.length <= pos) {\n buffer = readLine().split(\" \")\n pos = 0\n }\n pos = pos + 1\n buffer(pos - 1).toInt\n }\n\n def nextString: String = {\n if (buffer == null) {\n buffer = readLine().split(\" \")\n pos = 0\n }\n if (buffer.length <= pos) {\n buffer = readLine().split(\" \")\n pos = 0\n }\n pos += 1\n buffer(pos - 1)\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(y, k, n) = in.next().split(\" \").map(_.toInt)\n val res = (1 to (n - y) / k + 1).map(i => i * k - y).filter(j => j > 0 && j + y <= n).mkString(\" \")\n if (res.isEmpty)\n println(-1)\n else\n println(res)\n}"}, {"source_code": "import java.util.Scanner\n\nobject A extends App {\n\tval in = new Scanner(System.in)\n\tval y = in.nextInt()\n\tval k = in.nextInt()\n\tval n = in.nextInt()\n\tval begin = (y / k + 1) * k\n\tif (n - begin < 1) {\n\t\tprintln(-1)\n\t} else {\n\t\tval sb = new StringBuilder\n\t\tfor (i <- begin to n by k) {\n\t\t\tsb.append(i - y)\n\t\t\tsb.append(' ')\n\t\t}\n\t\tsb.deleteCharAt(sb.size - 1)\n\t\tprintln(sb)\n\t}\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val ynk = readLine().split(\" \").map(_.toInt)\n val y = ynk(0)\n val n = ynk(2)\n val k = ynk(1)\n \n val start = ((y + k - 1) / k) * k\n if (start >= n) println(\"-1\")\n else println( (start until n by k).map(_ - y).mkString(\" \") )\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val ynk = readLine().split(\" \").map(_.toInt)\n val y = ynk(0)\n val n = ynk(2)\n val k = ynk(1)\n \n val start = ((y + k - 1) / k) * k\n if (start >= n) println(n)\n else println( (start to n by k).map(_ - y).mkString(\" \") )\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val ynk = readLine().split(\" \").map(_.toInt)\n val y = ynk(0)\n val n = ynk(2)\n val k = ynk(1)\n \n val start = \n if (k == 1) y + 1\n else ((y + k - 1) / k) * k\n if (start > n) println(\"-1\")\n else println( (start to n by k).map(_ - y).mkString(\" \") )\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val ynk = readLine().split(\" \").map(_.toInt)\n val y = ynk(0)\n val n = ynk(2)\n val k = ynk(1)\n \n val start = \n if (k == 1) y + 1\n else ((y + k - 1) / k) * k\n if (start >= n) println(\"-1\")\n else println( (start to n by k).map(_ - y).mkString(\" \") )\n }\n}"}], "src_uid": "2deda3a05740e1184735bf437e3850a8"} {"source_code": "import java.io.FileReader\nimport java.util\nimport java.util.Comparator\n\nimport collection.Searching._\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject Solution {\n //Console.setIn(new FileReader(new java.io.File(\"input\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n var caseNo = 1\n val magicMod = 1000000007\n\n def doCase() : Unit = {\n val Array(n) = readIntLine()\n val boxes = readIntLine().sorted.reverse\n\n var piles : ArrayBuffer[List[Int]] = new ArrayBuffer[List[Int]]()\n\n for (box <- boxes) {\n var placed = false\n for (i <- piles.indices) {\n if (!placed && piles(i).head > box) {\n piles(i) = box :: piles(i)\n placed = true\n }\n }\n if (!placed) {\n piles.append(List(box))\n }\n }\n println(piles.length)\n }\n\n def main(args: Array[String]): Unit = {\n val noCases = 1\n for (i <- 0 until noCases) {\n doCase()\n }\n }\n\n def readIntLine(): Array[Int] = {\n readLine().split(\" \").map(_.toInt)\n }\n\n def readLongLine(): Array[Long] = {\n readLine().split(\" \").map(_.toLong)\n }\n\n def readBigIntLine(): Array[BigInt] = {\n readLine().split(\" \").map(BigInt.apply)\n }\n}\n", "positive_code": [{"source_code": "object C extends App {\n val n = scala.io.StdIn.readInt()\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val b = a.sorted.foldLeft(List.empty[Int]) ((l, i) => {\n if (l.isEmpty) i :: l\n else if (l.head < i) l.tail :+ i\n else i :: l\n })\n\n println(b.length)\n}\n"}], "negative_code": [{"source_code": "object C extends App {\n val n = scala.io.StdIn.readInt()\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val b = a.sorted.foldLeft(List.empty[Int]) ((l, i) => {\n if (l.isEmpty) i :: l\n else if (l.head < i) i :: l.tail\n else i :: l\n })\n\n println(b.length)\n}\n"}], "src_uid": "0cbd3eee259b1436f82e259be7d7ee0e"} {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n val C = readLine().split(\" \").map(_.toLong)\n val S = Array.ofDim[(String, String)](n)\n\n for (i <- 0 until n) {\n val w = readLine()\n S(i) = (w, w.reverse)\n }\n\n val D = Array.ofDim[Long](n, 2)\n D(0)(0) = 0\n D(0)(1) = C(0)\n\n if (isPossible) {\n println(Math.min(D(n - 1)(0), D(n - 1)(1)))\n } else {\n println(-1)\n }\n\n def isPossible: Boolean = {\n for (i <- 1 until n) {\n val A = S(i - 1)._1\n val Arev = S(i - 1)._2\n val B = S(i)._1\n val Brev = S(i)._2\n\n var min1 = Long.MaxValue\n if (isOrdered(A, B)) min1 = Math.min(min1, D(i - 1)(0))\n if (isOrdered(Arev, B)) min1 = Math.min(min1, D(i - 1)(1))\n D(i)(0) = min1\n\n var min2 = Long.MaxValue\n if (isOrdered(A, Brev) && D(i - 1)(0) != Long.MaxValue) min2 = Math.min(min2, D(i - 1)(0) + C(i))\n if (isOrdered(Arev, Brev) && D(i - 1)(1 ) != Long.MaxValue) min2 = Math.min(min2, D(i - 1)(1) + C(i))\n D(i)(1) = min2\n\n if (min1 == Long.MaxValue && min2 == Long.MaxValue) return false\n }\n\n true\n }\n\n def isOrdered(a: String, b: String): Boolean = {\n a <= b\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val c = in.next().split(' ').map(_.toInt)\n val (_, ans) = in.take(n).toList.zip(c).foldLeft((true, Map.empty[String, Long])) {\n case ((true, map), (str, price)) if str == str.reverse =>\n (false, Map(str -> 0))\n case ((true, map), (str, price)) =>\n (false, Map(str -> 0, str.reverse -> price))\n case ((false, map), _ ) if map.isEmpty => (false, Map.empty)\n case ((false, map), (str, price)) if str == str.reverse =>\n val v = map.filter { case(a, b) => a <= str }.values\n (false, if (v.isEmpty) Map.empty else Map(str -> v.min))\n case ((false, map), (str, price)) =>\n val nMap = map.filter { case(a, b) => a <= str }.values\n val nMap2 = map.filter { case(a, b) => a <= str.reverse}.values\n if (nMap.isEmpty && nMap2.isEmpty)\n (false, Map.empty)\n else if (nMap.nonEmpty && nMap2.nonEmpty)\n (false, Map(str -> nMap.min, str.reverse -> (nMap2.min + price)))\n else if (nMap.nonEmpty)\n (false, Map(str -> nMap.min))\n else\n (false, Map(str.reverse -> (nMap2.min + price)))\n }\n if (ans.isEmpty)\n println(-1)\n else\n println(ans.values.min)\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _706C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val costs = read[Vector[Int]]\n\n var choices = Iterable(\"\" -> 0L)\n\n costs foreach {cost =>\n val s = read[String]\n val r = s.reverse\n val next = map[String] to Long.MaxValue\n for {\n (s1, c1) <- choices\n (s2, c2) <- Iterable(s -> 0, r -> cost)\n if s1.isEmpty || s1 <= s2\n } next(s2) = next(s2) min (c1 + c2)\n choices = next.toSeq\n }\n\n val ans = choices.map(_._2).whenNonEmpty(_.min)\n write(ans getOrElse -1)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Main extends App {\n import scala.io._\n val input = Source.stdin\n val inputit:Iterator[String] = input.getLines()\n var lineit:Iterator[String] = List.empty.iterator\n def rs() : String = {\n if (lineit.hasNext) lineit.next\n else { \n lineit = inputit.next.split(\" \").iterator\n rs()\n }\n }\n def ri(): Int = rs().toInt\n def rl(): Long = rs().toLong\n val n = ri ()\n val c = Array.fill(n)(rl())\n val s = Array.fill(n)(rs())\n val t = s.map { _.reverse }\n var q = Array(0l, c(0))\n val inf = Long.MaxValue / 2\n for (i <- 1 until n) {\n val w = Array.fill(2)(inf)\n if (s(i-1) <= s(i) && w(0) > q(0)) w(0) = q(0)\n if (s(i-1) <= t(i) && w(1) > q(0) + c(i)) w(1) = q(0) + c(i)\n if (t(i-1) <= s(i) && w(0) > q(1)) w(0) = q(1)\n if (t(i-1) <= t(i) && w(1) > q(1) + c(i)) w(1) = q(1) + c(i)\n q = w\n }\n val r = q.min\n println(if (r >= inf) -1l else r)\n}\n"}, {"source_code": "object Solution {\n\n import scala.math._\n\n def main(args: Array[String]) {\n\n val sc = new java.util.Scanner(System.in)\n\n val n = sc.nextInt()\n val energy = Array.fill(n)(sc.nextInt().toLong)\n val strs = Array.fill(n)(sc.next())\n\n println(calc(strs, energy))\n }\n def calc(strs: Array[String], energy: Array[Long]): Long = {\n\n val n = strs.length\n val dp = Array.fill(n)(Array.fill(2)(-1L))\n\n dp(0)(0) = 0L\n dp(0)(1) = energy(0)\n\n for (i <- (1 until n)) {\n\n if (dp(i-1)(0) == -1 && dp(i-1)(1) == -1) return -1\n\n else if(dp(i-1)(0) == -1) {\n\n val prev_str_reversed = strs(i-1).reverse\n\n if (prev_str_reversed <= strs(i)) dp(i)(0) = dp(i-1)(1)\n\n if (prev_str_reversed <= strs(i).reverse) dp(i)(1) = dp(i-1)(1) + energy(i)\n }\n else if (dp(i-1)(1) == -1) {\n\n val prev_str = strs(i-1)\n\n if (prev_str <= strs(i)) dp(i)(0) = dp(i-1)(0)\n\n if (prev_str <= strs(i).reverse) dp(i)(1) = dp(i-1)(0) + energy(i)\n }\n else {\n\n val prev_str = strs(i-1)\n val prev_str_reversed = strs(i-1).reverse\n\n if (prev_str <= strs(i) && prev_str_reversed <= strs(i))\n dp(i)(0) = min(dp(i-1)(0), dp(i-1)(1))\n else if (prev_str <= strs(i))\n dp(i)(0) = dp(i-1)(0)\n else if (prev_str_reversed <= strs(i))\n dp(i)(0) = dp(i-1)(1)\n\n if (prev_str <= strs(i).reverse && prev_str_reversed <= strs(i).reverse)\n dp(i)(1) = min(dp(i-1)(0), dp(i-1)(1)) + energy(i)\n else if (prev_str <= strs(i).reverse)\n dp(i)(1) = dp(i-1)(0) + energy(i)\n else if (prev_str_reversed <= strs(i).reverse)\n dp(i)(1) = dp(i-1)(1) + energy(i)\n }\n }\n if(dp(n-1)(0) > -1 && dp(n-1)(1) > -1) min(dp(n-1)(0), dp(n-1)(1))\n else if (dp(n-1)(0) > -1) dp(n-1)(0)\n else if (dp(n-1)(1) > -1) dp(n-1)(1)\n else -1\n }\n}\n"}], "negative_code": [{"source_code": "object Solution {\n\n import scala.math._\n\n def main(args: Array[String]) {\n\n val sc = new java.util.Scanner(System.in)\n\n val n = sc.nextInt()\n val energy = Array.fill(n)(sc.nextInt())\n val strs = Array.fill(n)(sc.next())\n\n println(calc(strs, energy))\n }\n def calc(strs: Array[String], energy: Array[Int]): Int = {\n\n val n = strs.length\n val dp = Array.fill(n)(Array.fill(2)(-1))\n\n dp(0)(0) = 0\n dp(0)(1) = energy(0)\n\n for (i <- (1 until n)) {\n\n if (dp(i-1)(0) == -1 && dp(i-1)(1) == -1) return -1\n\n else if(dp(i-1)(0) == -1) {\n\n val prev_str_reversed = strs(i-1).reverse\n\n if (prev_str_reversed <= strs(i)) dp(i)(0) = dp(i-1)(1)\n\n if (prev_str_reversed <= strs(i).reverse) dp(i)(1) = dp(i-1)(1) + energy(i)\n }\n else if (dp(i-1)(1) == -1) {\n\n val prev_str = strs(i-1)\n\n if (prev_str <= strs(i)) dp(i)(0) = dp(i-1)(0)\n\n if (prev_str <= strs(i).reverse) dp(i)(1) = dp(i-1)(0) + energy(i)\n }\n else {\n\n val prev_str = strs(i-1)\n val prev_str_reversed = strs(i-1).reverse\n\n if (prev_str <= strs(i) && prev_str_reversed <= strs(i))\n dp(i)(0) = min(dp(i-1)(0), dp(i-1)(1))\n else if (prev_str <= strs(i))\n dp(i)(0) = dp(i-1)(0)\n else if (prev_str_reversed <= strs(i))\n dp(i)(0) = dp(i-1)(1)\n\n if (prev_str <= strs(i).reverse && prev_str_reversed <= strs(i).reverse)\n dp(i)(1) = min(dp(i-1)(0), dp(i-1)(1)) + energy(i)\n else if (prev_str <= strs(i).reverse)\n dp(i)(1) = dp(i-1)(0) + energy(i)\n else if (prev_str_reversed <= strs(i).reverse)\n dp(i)(1) = dp(i-1)(1) + energy(i)\n }\n }\n if(dp(n-1)(0) > -1 && dp(n-1)(1) > -1) min(dp(n-1)(0), dp(n-1)(1))\n else if (dp(n-1)(0) > -1) dp(n-1)(0)\n else if (dp(n-1)(1) > -1) dp(n-1)(1)\n else -1\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val c = in.next().split(' ').map(_.toInt)\n val (_, ans) = in.take(n).toList.zip(c).foldLeft((true, Map.empty[String, Int])) {\n case ((true, map), (str, price)) if str == str.reverse =>\n (false, Map(str -> 0))\n case ((true, map), (str, price)) =>\n (false, Map(str -> 0, str.reverse -> price))\n case ((false, map), _ ) if map.isEmpty => (false, Map.empty)\n case ((false, map), (str, price)) if str == str.reverse =>\n val v = map.filter { case(a, b) => a <= str }.values\n (false, if (v.isEmpty) Map.empty else Map(str -> v.min))\n case ((false, map), (str, price)) =>\n val nMap = map.filter { case(a, b) => a <= str }.values\n val nMap2 = map.filter { case(a, b) => a <= str.reverse}.values\n if (nMap.isEmpty && nMap2.isEmpty)\n (false, Map.empty)\n else if (nMap.nonEmpty && nMap2.nonEmpty)\n (false, Map(str -> nMap.min, str.reverse -> (nMap2.min + price)))\n else if (nMap.nonEmpty)\n (false, Map(str -> nMap.min))\n else\n (false, Map(str.reverse -> (nMap2.min + price)))\n }\n if (ans.isEmpty)\n println(-1)\n else\n println(ans.values.min)\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val c = in.next().split(' ').map(_.toInt)\n val (_, ans) = in.take(n).toList.zip(c).foldLeft((true, Map.empty[String, Int])) {\n case ((true, map), (str, price)) if str == str.reverse =>\n (false, Map(str -> 0))\n case ((true, map), (str, price)) =>\n (false, Map(str -> 0, str.reverse -> price))\n case ((false, map), _ ) if map.isEmpty => (false, Map.empty)\n case ((false, map), (str, price)) if str == str.reverse =>\n val v = map.filter { case(a, b) => a <= str }.values\n (false, if (v.isEmpty) Map.empty else Map(str -> v.min))\n case ((false, map), (str, price)) =>\n val nMap = map.filter { case(a, b) => a <= str }.values\n val nMap2 = map.filter { case(a, b) => a <= str.reverse}.values\n if (nMap.isEmpty && nMap2.isEmpty)\n (false, Map.empty)\n else if (nMap.nonEmpty && nMap2.nonEmpty)\n (false, Map(str -> nMap.min, str.reverse -> nMap2.min))\n else if (nMap.nonEmpty)\n (false, Map(str -> nMap.min))\n else\n (false, Map(str.reverse -> nMap2.min))\n }\n if (ans.isEmpty)\n println(-1)\n else\n println(ans.values.min)\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _706C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val n = read[Int]\n val cost = read[Vector, Int](n)\n\n var choices = Iterable(Choice(\"\", 0))\n\n 0 until n foreach {i =>\n val s = read[String]\n val r = s.reverse\n val next = mutable.Map.empty[String, Int]\n for {\n (s2, c2) <- Seq(s -> 0, r -> cost(i))\n c1 <- choices\n c <- c1.next(s2, c2)\n if c.cost < next.getOrElse(s2, Int.MaxValue)\n } next(s2) = c.cost\n\n choices = next.map(p => Choice(p._1, p._2))\n }\n\n val ans = choices.map(_.cost).whenNonEmpty(_.min) getOrElse -1\n write(ans)\n }\n\n case class Choice(s: String, cost: Int) {\n def next(s2: String, c2: Int) = when(s.isEmpty || s <= s2) {\n Choice(s2, cost + c2)\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "//296 мс 38900 \nobject Main extends App {\n import scala.io._\n val input = Source.stdin\n val inputit:Iterator[String] = input.getLines()\n var lineit:Iterator[String] = List.empty.iterator\n def rs() : String = {\n if (lineit.hasNext) lineit.next\n else { \n lineit = inputit.next.split(\" \").iterator\n rs()\n }\n }\n def ri(): Int = rs().toInt\n def rl(): Long = rs().toLong\n val n = ri ()\n val c = Array.fill(n)(rl())\n val s = Array.fill(n)(rs())\n val t = s.map { _.reverse }\n var q = Array(0l, c(0))\n val inf = Long.MaxValue / 2\n for (i <- 1 until n) {\n val w = Array.fill(2)(inf)\n if (s(i-1) < s(i) && w(0) > q(0)) w(0) = q(0)\n if (s(i-1) < t(i) && w(1) > q(0) + c(i)) w(1) = q(0) + c(i)\n if (t(i-1) < s(i) && w(0) > q(1)) w(0) = q(1)\n if (t(i-1) < t(i) && w(1) > q(1) + c(i)) w(1) = q(1) + c(i)\n q = w\n }\n val r = q.min\n println(if (r >= inf) -1l else r)\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n val C = readLine().split(\" \").map(_.toInt)\n val S = (for {\n _ <- 1 to n\n s = readLine()\n } yield (s, s.reverse)).toList\n\n val D = Array.ofDim[Int](n, 2)\n D(0)(0) = 0\n D(0)(1) = C(0)\n\n if (isPossible) {\n println(Math.min(D(n - 1)(0), D(n - 1)(1)))\n } else {\n println(-1)\n }\n\n def isPossible: Boolean = {\n for (i <- 1 until n) {\n val A = S(i - 1)._1\n val Arev = S(i - 1)._2\n val B = S(i)._1\n val Brev = S(i)._2\n\n var min1 = Int.MaxValue\n if (isOrdered(A, B)) min1 = Math.min(min1, D(i - 1)(0))\n if (isOrdered(Arev, B)) min1 = Math.min(min1, D(i - 1)(1))\n D(i)(0) = min1\n\n var min2 = Int.MaxValue\n if (isOrdered(A, Brev)) min2 = Math.min(min2, D(i - 1)(0) + C(i))\n if (isOrdered(Arev, Brev)) min2 = Math.min(min2, D(i - 1)(1))\n D(i)(1) = min2\n\n if (min1 == Int.MaxValue && min2 == Int.MaxValue) return false\n }\n\n true\n }\n\n def isOrdered(a: String, b: String): Boolean = {\n a <= b\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n val C = readLine().split(\" \").map(_.toInt)\n val S = Array.ofDim[(String, String)](n)\n\n for (i <- 0 until n) {\n val w = readLine()\n S(i) = (w, w.reverse)\n }\n\n val D = Array.ofDim[Int](n, 2)\n D(0)(0) = 0\n D(0)(1) = C(0)\n\n if (isPossible) {\n println(Math.min(D(n - 1)(0), D(n - 1)(1)))\n } else {\n println(-1)\n }\n\n def isPossible: Boolean = {\n for (i <- 1 until n) {\n val A = S(i - 1)._1\n val Arev = S(i - 1)._2\n val B = S(i)._1\n val Brev = S(i)._2\n\n var min1 = Int.MaxValue\n if (isOrdered(A, B)) min1 = Math.min(min1, D(i - 1)(0))\n if (isOrdered(Arev, B)) min1 = Math.min(min1, D(i - 1)(1))\n D(i)(0) = min1\n\n var min2 = Int.MaxValue\n if (isOrdered(A, Brev) && D(i - 1)(0) != Int.MaxValue) min2 = Math.min(min2, D(i - 1)(0) + C(i))\n if (isOrdered(Arev, Brev) && D(i - 1)(1 ) != Int.MaxValue) min2 = Math.min(min2, D(i - 1)(1) + C(i))\n D(i)(1) = min2\n\n if (min1 == Int.MaxValue && min2 == Int.MaxValue) return false\n }\n\n true\n }\n\n def isOrdered(a: String, b: String): Boolean = {\n a <= b\n }\n}\n"}], "src_uid": "91cfd24b8d608eb379f709f4509ecd2d"} {"source_code": "import java.util\n\nimport scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n\n val max = 1000000007;\n val n = readInt()\n\n val A:Array[(Int,Int)] = Array.fill(n)(readTuple())\n\n\n\n\n\n println(A.foldLeft((101,0)) {\n (sm,a)=> {\n if(a._2 < sm._1)\n (a._2, sm._2 + a._1 * a._2)\n else\n (sm._1, sm._2 + a._1 * sm._1)\n }\n }._2)\n\n }\n\n def readInt(): Int = StdIn.readInt()\n\n def readInts(): Array[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n\n\n def readTuple(): (Int, Int) = {\n val line = readInts\n (line(0), line(1))\n }\n\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\n\n\nobject Solve extends App with fastIO{\n val n = nextInt\n val a = new ArrayBuffer[Int]\n val p = new ArrayBuffer[Int]\n for(i <- 0 until n){\n a += nextInt\n p += nextInt\n }\n\n var minp = p(0)\n var res = p(0)*a(0)\n for(i <- 1 until n){\n if(p(i)>minp) res+=minp*a(i)\n else {\n minp = p(i)\n res+=minp*a(i)\n }\n }\n println(res)\n flush\n}\n\ntrait fastIO {\n import java.io._\n val isFile = false\n val input = \"file.in\"\n val output = \"file.out\"\n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush()\n}\n"}, {"source_code": "object Codeforces extends App {\n val in = new java.util.Scanner(System.in)\n var n = in.nextInt()\n var a = Array.ofDim[Int](n + 1)\n var p = Array.ofDim[Int](n + 1)\n for (i <- 0 until n) {\n a(i) = in.nextInt()\n p(i) = in.nextInt()\n }\n for (i <- 1 until n) {\n if (p(i) > p(i - 1)) {\n p(i) = p(i - 1);\n }\n }\n var res = 0\n for (i <- 0 until n) {\n res += a(i) * p(i)\n }\n println(res)\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n var data = (1 to n).map(_ => in.next().split(\" \").map(_.toInt))\n var sum = 0\n while (data.nonEmpty) {\n val min = data.minBy(_.last)\n val index = data.indexOf(min)\n sum += data.drop(index).map(_.head).sum * min.last\n data = data.take(index)\n }\n println(sum)\n}"}, {"source_code": "object A588 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = Array.fill(n)(readLongs(2))\n var min = input(0)(1)\n var res = input(0)(0) * min\n for(i <- 1 until n) {\n if(input(i)(1) < min) {\n min = input(i)(1)\n }\n res += input(i)(0) * min\n }\n println(res)\n }\n}"}, {"source_code": "// So you like object Task\nimport java.io.{IOException, InputStream, PrintWriter}\nimport java.util.InputMismatchException\n\nobject Task {\n\n\n def solve(in: InputReader, out: PrintWriter): Unit = {\n val n = in.nextInt()\n var answer = 0l\n var curMin = Int.MaxValue\n for (i <- 0 until n) {\n val a = in.nextInt()\n curMin = curMin min in.nextInt()\n answer += a * curMin\n }\n out.println(answer)\n }\n\n def main(args: Array[String]) {\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n in.close()\n out.close()\n }\n}\n\nclass InputReader(val inputStream: InputStream) {\n val buf = new Array[Byte](1 << 16)\n var curChar = 0\n var numChars = 0\n\n def read(): Int = {\n if (numChars == -1) {\n throw new InputMismatchException()\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => throw new InputMismatchException()\n }\n if (numChars <= 0)\n return -1\n }\n curChar += 1\n buf(curChar - 1)\n }\n\n def peek(): Int = {\n if (numChars == -1) {\n return -1\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => return -1\n }\n if (numChars <= 0)\n return -1\n }\n buf(curChar)\n }\n\n def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n\n def nextInt(): Int = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextLong(): Long = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0l\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def next(): String = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n val res = new StringBuilder()\n do {\n res += c.toChar\n c = read()\n } while(!isSpaceChar(c))\n res.toString()\n }\n\n def nextChar(): Char = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n c.toChar\n }\n\n //noinspection AccessorLikeMethodIsEmptyParen\n def hasNext(): Boolean = {\n var value = peek()\n do {\n read()\n value = peek()\n } while (isSpaceChar(value) && value != -1)\n value != -1\n }\n\n def rawNextLine(): String = {\n val builder = new StringBuilder\n var c = read()\n while (c != '\\n' && c != -1) {\n if (c != '\\r')\n builder += c.toChar\n c = read()\n }\n builder.toString()\n }\n\n def nextLine(): String = {\n var s = rawNextLine()\n while (s.trim().length == 0) s = rawNextLine()\n s\n }\n\n def nextDouble(): Double = {\n next().toDouble\n }\n\n def close(): Unit = {\n inputStream.close()\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._\nimport scala.math.Ordering.Implicits._\n\nimport CodeForcesApp._\n\nobject _588A extends CodeForcesApp {\n override type Result = Int\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val n = nextInt()\n val input = List.fill(n)((nextInt(), nextInt()))\n\n var curPrice = Int.MaxValue\n var ans = 0\n\n for {\n (a, p) <- input\n } {\n curPrice = curPrice min p\n ans += a*curPrice\n }\n\n ans\n }\n\n override def format(result: Result) = super.format(result)\n}\n/**************************************[Ignore]***************************************************/\nabstract class CodeForcesApp {\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n @inline final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)\n @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\nimport java.io.{File, BufferedReader, Reader, InputStream, InputStreamReader, StringReader}\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\nclass Scanner(reader: BufferedReader) extends AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val tokens = for {\n line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)\n start = new StringTokenizer(line)\n tokenizer <- Iterator.continually(start).takeWhile(_.hasMoreTokens)\n } yield tokenizer.nextToken()\n\n def next(): String = tokens.next()\n def nextInt(): Int = next().toInt\n\n override def close() = reader.close()\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._\nimport scala.math.Ordering.Implicits._\n\nimport CodeForcesApp._\n\nobject _588A extends CodeForcesApp {\n override type Result = Int\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val n = nextInt()\n val input = List.fill(n)((nextInt(), nextInt()))\n\n var curPrice = Int.MaxValue\n var ans = 0\n\n for {\n (a, p) <- input\n } {\n curPrice = curPrice min p\n ans += a*curPrice\n }\n\n ans\n }\n\n override def format(result: Result) = super.format(result)\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n/********************************[Scala Scanner]*********************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n def tokens: Iterator[String] = for {\n line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)\n tokenizer = new StringTokenizer(line)\n _ <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)\n } yield tokenizer.nextToken()\n\n private[this] var current = tokens\n override def hasNext = current.hasNext\n @inline override def next() = current.next()\n\n /**\n * @return Unlike the Java scanner which returns till end of current line, this actually returns the next line\n */\n def nextLine(): String = {\n current = tokens // reset\n reader.readLine()\n }\n def lineNumber: Int = reader.getLineNumber\n def nextString(): String = next()\n def nextChar(): Char = next().head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def close() = reader.close()\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._\nimport scala.math.Ordering.Implicits._\n\nimport CodeForcesApp._\n\nobject _588A extends CodeForcesApp {\n override type Result = Int\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val n = nextInt()\n val input = List.fill(n)((nextInt(), nextInt()))\n\n var curPrice = Int.MaxValue\n var ans = 0\n\n for {\n (a, p) <- input\n } {\n curPrice = curPrice min p\n ans += a*curPrice\n }\n\n ans\n }\n\n override def format(result: Result) = super.format(result)\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n/********************************[Scala Scanner]*********************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines: Iterator[String] = Iterator.continually(reader.readLine()).takeWhile(_ != null)\n\n def tokens: Iterator[String] = for {\n line <- lines\n tokenizer = new StringTokenizer(line)\n _ <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)\n } yield tokenizer.nextToken()\n\n private[this] var current = tokens\n override def hasNext = current.hasNext\n @inline override def next() = current.next()\n\n /**\n * @return Unlike the Java scanner which returns till end of current line, this actually returns the next line\n */\n def nextLine(): String = {\n current = tokens // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def nextString(): String = next()\n def nextChar(): Char = next().head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def close() = reader.close()\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._\nimport scala.math.Ordering.Implicits._\n\nimport CodeForcesApp._\n\nobject _588A extends CodeForcesApp {\n override type Result = Int\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val n = nextInt()\n val input = List.fill(n)((nextInt(), nextInt()))\n\n var curPrice = Int.MaxValue\n var ans = 0\n\n for {\n (a, p) <- input\n } {\n curPrice = curPrice min p\n ans += a*curPrice\n }\n\n ans\n }\n\n override def format(result: Result) = super.format(result)\n}\n/**************************************[Ignore]***************************************************/\nabstract class CodeForcesApp {\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n @inline final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)\n @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\nimport java.io.{File, BufferedReader, Reader, InputStream, InputStreamReader, StringReader}\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\nclass Scanner(reader: BufferedReader) extends Iterable[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n override def iterator = for {\n line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)\n tokenizer = new StringTokenizer(line)\n tokens <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)\n } yield tokens.nextToken()\n\n private[this] var current = iterator\n\n def hasNext = current.hasNext\n @inline def next() = current.next()\n\n def nextLine(): String = {\n val line = reader.readLine()\n current = iterator\n line\n }\n def nextString(): String = next()\n def nextBoolean(): Boolean = nextString().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(nextString(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(nextString(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(nextString(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(nextString(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(nextString(), radix)\n def nextFloat(): Float = nextString().toFloat\n def nextDouble(): Double = nextString().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(nextString())\n\n override def close() = reader.close()\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _588A extends CodeForcesApp[Int]({scanner => import scanner._\n val n = nextInt\n val input = List.fill(n)((nextInt, nextInt))\n\n var curPrice = Int.MaxValue\n var ans = 0\n\n for {\n (a, p) <- input\n } {\n curPrice = curPrice min p\n ans += a*curPrice\n }\n\n ans\n}) {\n override def format(result: Result) = super.format(result)\n}\n/********************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n @inline final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)\n @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._\nimport scala.math.Ordering.Implicits._\n\nimport CodeForcesApp._\n\nobject _588A extends CodeForcesApp {\n override type Result = Int\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val n = nextInt()\n val input = List.fill(n)((nextInt(), nextInt()))\n\n var curPrice = Int.MaxValue\n var ans = 0\n\n for {\n (a, p) <- input\n } {\n curPrice = curPrice min p\n ans += a*curPrice\n }\n\n ans\n }\n\n override def format(result: Result) = super.format(result)\n}\nabstract class CodeForcesApp {\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n @inline final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)\n @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\nclass Scanner(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(line => new StringTokenizer(line))\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def nextTokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = tokenizers.find(_.hasMoreTokens)\n current\n }\n\n override def hasNext: Boolean = nextTokenizer().exists(_.hasMoreTokens)\n\n override def next(): String = nextTokenizer().get.nextToken()\n def nextInt(): Int = next().toInt\n\n override def close() = reader.close()\n}\n"}, {"source_code": "/**\n * Created by armanmac on 3/22/17.\n */\n\n\n\nobject Code {\n\n\n \n\n\n def main(args: Array[String]): Unit = {\n\n var days = scala.io.StdIn.readInt()\n var need: Array[Int] = new Array[Int](days)\n var price: Array[Int] = new Array[Int](days)\n\n for (i <- 0 to days - 1) {\n var str = scala.io.StdIn.readLine().split(' ')\n need(i) = str(0).toInt\n price(i) = str(1).toInt\n }\n\n\n var leastPrice = need(0) * price(0)\n var minPrice = price(0)\n\n\n for (i <- 1 to days - 1) {\n\n if(price(i)= n || A(day)._2 > A(day + 1)._2) {\n totalKg += A(day)._1\n totalCost += A(day)._1 * A(day)._2\n day += 1\n } else {\n var size = day + 1\n var localKg = A(day)._1\n while (size < n && A(day)._2 <= A(size)._2) {\n localKg += A(size)._1\n size += 1\n }\n totalKg += localKg\n totalCost += localKg * A(day)._2\n day = size\n }\n }\n\n println(totalCost)\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\n\nobject A_DuffAndMeat {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(t3.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = br.readLine().trim().split(\" \")\n val number = line1(0).toInt\n var data = new Array[(Int, Int)](number)\n for (i <- 0 until number) {\n val line = br.readLine().trim().split(\" \")\n data(i) = (line(0).toInt, line(1).toInt)\n }\n //---------------------------- parameters reading end --------------------------------\n \n var minPrice = 101\n var result = 0 \n for(i <- data) {\n if (minPrice > i._2) minPrice = i._2\n result += minPrice * i._1\n }\n \n println(result)\n }\n \n//========================= samples ======================== \nval sa1 = \"\"\"\n\n\"\"\"\n\n//========================= samples end ==================== \n}"}, {"source_code": "import java.util\n\nimport scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n\n val max = 1000000007;\n val n = readInt()\n\n val A:Array[(Int,Int)] = Array.fill(n)(readTuple())\n\n\n var curPrice = 101\n var sum = 0;\n for(i <- 0 to n - 1) {\n if(A(i)._2 < curPrice) {\n sum+=A(i)._2 * A(i)._1\n curPrice = A(i)._2\n } else {\n sum+=curPrice * A(i)._1\n }\n }\n\n println(sum)\n\n }\n\n def readInt(): Int = StdIn.readInt()\n\n def readInts(): Array[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n\n\n def readTuple(): (Int, Int) = {\n val line = readInts\n (line(0), line(1))\n }\n\n}\n"}, {"source_code": "\nobject Duff extends App {\n\n val n = scala.io.StdIn.readLine().toInt\n\n val inputs = for (ln <- 1 to n)\n yield scala.io.StdIn.readLine()\n\n val plans = inputs.map(_.split(\" \").map(_.toInt).toList)\n\n val result = plans.map(e => (e(0), e(1), e(0) * e(1)))\n .reduce((e1, e2) => {\n val price = e1._2 min e2._2;\n (e2._1, price, e1._3 + e2._1 * price)\n })\n\n println(result._3)\n\n}\n"}], "negative_code": [{"source_code": "\nobject Duff extends App{\n\n val n = scala.io.StdIn.readLine().toInt\n\n val inputs = for (ln <- 1 to n)\n yield scala.io.StdIn.readLine()\n\n val plans = inputs.map( _.split(\" \").map(_.toInt).toList)\n val (List(ignore, lowestPrice ), lowestDay) = plans.zipWithIndex.minBy( _._1(1))\n\n val initSum = plans.zipWithIndex.filter( _._2 <= lowestDay)\n .map( e => e._1(0) * e._1(1)).sum\n\n val restSum = plans.zipWithIndex.filter(_._2 > lowestDay)\n .map( e => e._1(0) * lowestPrice).sum\n\n println(initSum + restSum)\n\n}\n"}], "src_uid": "28e0822ece0ed35bb3e2e7fc7fa6c697"} {"source_code": "import scala.io.StdIn\nobject Main {\n def main(args: Array[String]) = {\n val n = StdIn.readInt()\n def read = StdIn.readLine().split(\" \").tail.toSet\n if ((read ++ read).size == n) {\n println(\"I become the guy.\")\n } else {\n println(\"Oh, my keyboard!\")\n }\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\nimport scala.util.Sorting._\nimport scala.math._\nimport scala.collection._\nimport java.util._\n\nobject HelloWorld {\n def main(args: Array[String]): Unit = {\n val n = readInt\n val levels = readLine.split(\" \").drop(1).map(_.toInt).toSet ++ readLine.split(\" \").drop(1).map(_.toInt).toSet\n\n println(if (((1 to n).toSet -- levels).isEmpty) \"I become the guy.\" else \"Oh, my keyboard!\")\n }\n}"}, {"source_code": "import scala.collection.immutable.HashSet\n\nobject A469 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input1 = {\n val t = tokenizeLine\n val num1 = t.nextToken.toInt\n Array.fill(num1)(t.nextToken.toInt)\n }\n\n val input2 = {\n val t = tokenizeLine\n val num1 = t.nextToken.toInt\n Array.fill(num1)(t.nextToken.toInt)\n }\n\n val set = collection.mutable.HashSet.empty[Int]\n input1.foreach {set += _}\n input2.foreach {set += _}\n\n if(set.size == n) {\n println(\"I become the guy.\")\n } else {\n println(\"Oh, my keyboard!\")\n }\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val cin = new java.util.Scanner(System.in)\n def solve(i: Int, s: Set[Int]):Set[Int]= {\n if (i == 0) {\n s\n } else {\n solve(i - 1, s.+(cin.nextInt()))\n }\n }\n val n = cin.nextInt()\n val a = cin.nextInt()\n lazy val b = cin.nextInt()\n var s: Set[Int] = Set()\n s = s ++ solve(a, s)\n if(solve(b, s).size == n) {\n println(\"I become the guy.\")\n } else {\n println(\"Oh, my keyboard!\")\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn\nobject Main {\n def main(args: Array[String]) = {\n val n = StdIn.readInt()\n def read = StdIn.readLine().split(\" \").tail.map(_.toInt).toSet\n if ((read ++ read).size == n) {\n println(\"I become the guy.\")\n } else {\n println(\"Oh, my keyboard!\")\n }\n }\n}\n"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject WanneBeTheGuy {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n \n def main(args: Array[String]) {\n val n = readInt\n val l1 = readInts\n val l2 = readInts\n if ((l1.tail.toSet ++ l2.tail).size >= n)\n println(\"I become the guy.\")\n else \n println(\"Oh, my keyboard!\")\n }\n \n}"}, {"source_code": "import java.util.Scanner\n\nobject Main2 extends App {\n val scanner = new Scanner(System.in)\n val levelNumber = scanner.nextInt()\n val xLevelNumber = scanner.nextInt()\n val xLevels = 0.until(xLevelNumber).map(_ => scanner.nextInt())\n val yLevelNumber = scanner.nextInt()\n val yLevels = 0.until(yLevelNumber).map(_ => scanner.nextInt())\n println(if ((xLevels ++ yLevels).distinct.size == levelNumber) \"I become the guy.\" else \"Oh, my keyboard!\")\n}\n"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n val n = StdIn.readLine().toInt\n val S1:Set[Int] = StdIn.readLine().split(\" \").map(_.toInt).tail.toSet\n val S2:Set[Int] = StdIn.readLine().split(\" \").map(_.toInt).tail.toSet\n \n if((S1 ++ S2).size == n) {\n println(\"I become the guy.\")\n } else {\n println(\"Oh, my keyboard!\")\n }\n\n }\n\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject TEST extends App {\n val n = readInt\n val merge = readLine.split(\" \").toList.tail ::: readLine.split(\" \").toList.tail\n val ans = if(merge.groupBy(x=>x).size == n) \"I become the guy.\" else \"Oh, my keyboard!\"\n print(ans)\n}"}, {"source_code": "object Solution extends App {\n val n = readInt\n val p = readLine.split(\" \").map(_.toLong)\n val q = readLine.split(\" \").map(_.toLong)\n \n if(n == (p.tail ++ q.tail).toSet.size) \n println(\"I become the guy.\")\n else\n println(\"Oh, my keyboard!\")\n}"}, {"source_code": "object Main extends App {\n val n = readInt\n \n def readLevels = readLine.split(\" \").map(_.toInt).toList.tail\n \n val a = readLevels\n val b = readLevels\n\n def play(level: Int): String = {\n if (level > n)\n \"I become the guy.\"\n else if (a.contains(level) || b.contains(level))\n play(level + 1)\n else\n \"Oh, my keyboard!\"\n }\n \n println(play(1))\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Task469A {\n\tdef main(args: Array[String]) {\n\t\tval n = StdIn.readInt()\n\t\tval first = StdIn.readLine().split(\" \").map(_.toInt)\n\t\tval second = StdIn.readLine().split(\" \").map(_.toInt)\n\t\tif ((first.slice(1, first(0) + 1) ++ second.slice(1, second(0) + 1)).toSet.size == n) println(\"I become the guy.\") else println(\"Oh, my keyboard!\")\n\t}\n}\n"}, {"source_code": "object A extends App {\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n import scala.io.StdIn._\n val n = nextInt\n \n var i = 0\n var j = 0\n val m = scala.collection.mutable.Set[Int]()\n for (j <- 0 to 1) {\n val p = nextInt\n for (i <- 0 until p) {\n val x = nextInt\n m += x\n }\n }\n if (m.size == n) \n println(\"I become the guy.\")\n else\n println(\"Oh, my keyboard!\") \n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val first = in.next().split(\" \").tail.map(_.toInt).toSet\n val second = in.next().split(\" \").tail.map(_.toInt).toSet\n if (Range(1, n + 1).forall(t => first.contains(t) || second.contains(t)))\n println(\"I become the guy.\")\n else\n println(\"Oh, my keyboard!\")\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\nimport scala.util.Sorting._\nimport scala.math._\nimport scala.collection._\nimport java.util._\n\nobject HelloWorld {\n def main(args: Array[String]): Unit = {\n val n = readInt\n val levels = readLine.split(\" \").drop(1).map(_.toInt).toSet ++ readLine.split(\" \").drop(1).map(_.toInt).toSet\n\n println(if ((levels -- (1 to n)).isEmpty) \"I become the guy.\" else \"Oh, my keyboard!\")\n }\n}"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n val n = StdIn.readLine().toInt\n val A:Set[Int] = StdIn.readLine().split(\" \").map(_.toInt).toSet\n val B:Set[Int] = StdIn.readLine().split(\" \").map(_.toInt).toSet\n\n if((A ++ B).size == n) {\n println(\"I become the guy.\")\n } else {\n println(\"Oh, my keyboard!\")\n }\n\n }\n\n\n}\n"}], "src_uid": "044ade01d2de1486735742369227ae1d"} {"source_code": "\nimport java.io.PrintWriter\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject C {\n\n def main(args: Array[String]): Unit = {\n val in = io.Source.fromInputStream(System.in).getLines()\n // val in = io.Source.fromFile(\"in.txt\").getLines()\n val out = new PrintWriter(System.out)\n // val out = new PrintWriter(new File(\"out.txt\"))\n val n = in.next().toInt\n val a = in.next().split(\" \").map(_.toInt).map(_ - 1)\n\n\n val g = ArrayBuffer.fill(n)(new ArrayBuffer[Int]())\n for (i<- 0 until n)\n g(i) = new ArrayBuffer[Int]()\n for (i <- 0 until n) {\n g(i) += a(i)\n g(a(i)) += i\n }\n\n val res = find_comps(n, g)\n out.println(res)\n\n out.flush()\n out.close()\n }\n\n def find_comps(n:Int, g: ArrayBuffer[ArrayBuffer[Int]]):Int = {\n val used = ArrayBuffer.fill(n)(false)\n var res = 0\n\n for (i<-0 until n) {\n if (!used(i)) {\n dfs(i,used, g)\n res+=1\n }\n }\n\n res\n }\n\n def dfs(v: Int, used: ArrayBuffer[Boolean], g: ArrayBuffer[ArrayBuffer[Int]]): Unit = {\n used(v) = true\n\n for (i <- g(v).indices) {\n if (!used(g(v)(i))) {\n dfs(g(v)(i), used, g)\n }\n }\n }\n}\n", "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _755C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val input = read[Vector[Int]]\n val ds = new UnionFind[Int]\n (1 to input.length).foreach(i => ds += i)\n\n input.zipWithIndex foreach {\n case (i, j) => ds.union(i, j + 1)\n }\n\n write(ds.sets.size)\n }\n\n class UnionFind[A] extends PartialFunction[A, A] with collection.generic.Growable[A] {\n private[this] val parent = mutable.Map.empty[A, A]\n\n private[this] def find(x: A): A = parent(x) match {\n case `x` => x\n case y =>\n parent(x) = find(y)\n parent(x)\n }\n\n override def isDefinedAt(x: A) = parent contains x\n\n override def apply(x: A) = find(x)\n\n override def +=(x: A) = {\n parent(x) = x\n this\n }\n\n override def clear() = parent.clear()\n\n def sets: Map[A, Iterable[A]] = parent.keys.groupBy(find)\n\n def union(x: A, y: A) = {\n // Randomized linking is O(an) too: http://www.cis.upenn.edu/~sanjeev/papers/soda14_disjoint_set_union.pdf\n // If input is randomized we don't need randomization anyway: http://codeforces.com/blog/entry/21476\n // Without any linking heuristics but only path compression, it is O(log n) too: http://stackoverflow.com/questions/2323351/\n if (scala.util.Random.nextBoolean()) parent(find(x)) = find(y) else parent(find(y)) = find(x)\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "6d940cb4b54f63a7aaa82f21e4c5b994"} {"source_code": "import java.util._\nimport java.io._\nimport java.util\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def comp(a: (Int, Int), b: (Int, Int)): Boolean = {\n if (a._1 == b._1) {\n a._2 < b._2\n } else {\n a._1 < b._1\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val tasks = new Array[(Int, Int)](n)\n val m = new Array[Int](3000)\n for (i <- 0 until n) {\n val a = nextInt\n tasks(i) = (a, i + 1)\n m(a) += 1\n }\n var could = false\n val list = new util.ArrayList[Int]()\n var x2 = false\n var x2el = -1\n for (i <- 0 until m.length) {\n if (!could) {\n if (m(i) >= 3) {\n could = true\n list.add(i)\n } else if (m(i) == 2 && !x2) {\n x2 = true\n x2el = i\n } else if (m(i) == 2 && x2) {\n could = true\n list.add(i)\n list.add(x2el)\n }\n }\n }\n val sorted = tasks.sortWith(comp)\n if (could) {\n out.println(\"YES\")\n if (list.size() == 1) {\n val el = list.get(0)\n for (i <- 0 until 3) {\n var j = 0\n var flag = false\n while (j < n) {\n if (sorted(j)._1 != el || flag) {\n out.print(sorted(j)._2 + \" \")\n j += 1\n } else {\n flag = true\n i match {\n case 0 => {\n out.print(sorted(j + 0)._2 + \" \")\n out.print(sorted(j + 1)._2 + \" \")\n out.print(sorted(j + 2)._2 + \" \")\n }\n case 1 => {\n out.print(sorted(j + 1)._2 + \" \")\n out.print(sorted(j + 0)._2 + \" \")\n out.print(sorted(j + 2)._2 + \" \")\n }\n case 2 => {\n out.print(sorted(j + 2)._2 + \" \")\n out.print(sorted(j + 0)._2 + \" \")\n out.print(sorted(j + 1)._2 + \" \")\n }\n case _ => {}\n }\n j += 3\n }\n\n }\n\n out.println()\n }\n } else {\n val el1 = list.get(0)\n val el2 = list.get(1)\n for (i <- 0 until 3) {\n var j = 0\n while (j < n) {\n if (sorted(j)._1 != el1 && sorted(j)._1 != el2) {\n out.print(sorted(j)._2 + \" \")\n j += 1\n } else {\n if (sorted(j)._1 == el1) {\n i match {\n case 0 => {\n out.print(sorted(j + 0)._2 + \" \")\n out.print(sorted(j + 1)._2 + \" \")\n }\n case 1 => {\n out.print(sorted(j + 1)._2 + \" \")\n out.print(sorted(j + 0)._2 + \" \")\n }\n case 2 => {\n out.print(sorted(j + 0)._2 + \" \")\n out.print(sorted(j + 1)._2 + \" \")\n }\n case _ => {}\n }\n } else if (sorted(j)._1 == el2) {\n i match {\n case 0 => {\n out.print(sorted(j + 0)._2 + \" \")\n out.print(sorted(j + 1)._2 + \" \")\n }\n case 1 => {\n out.print(sorted(j + 0)._2 + \" \")\n out.print(sorted(j + 1)._2 + \" \")\n }\n case 2 => {\n out.print(sorted(j + 1)._2 + \" \")\n out.print(sorted(j + 0)._2 + \" \")\n }\n case _ => {}\n }\n }\n j += 2\n }\n }\n out.println()\n }\n }\n } else {\n out.println(\"NO\")\n }\n\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Things extends App {\n\n\tval scanner = new Scanner( System.in )\n\n\tval n = scanner.nextInt\n\tval tasks = Array.ofDim[Int]( n )\n\tfor( i <- tasks.indices )\n\t\ttasks( i ) = scanner.nextInt\n\n\t// check if there are at least two tasks with the same priorities like others\n\tval same = tasks.length - tasks.distinct.length\n\tif( same >= 2 ) {\n\t\tprintln( \"YES\" )\n\t\tval sorted = tasks.zipWithIndex.sortBy( _._1 )\t// merge with indexes and sort by priority\n\n\t\tval seq = sorted.map( _._2 + 1 )\t\t\t\t// sequenced tasks numbers, counted from 1\n\t\tprintln( seq.mkString( \" \" ))\n\n\t\tval idx = swap( 1, sorted, seq )\t\t\t\t// swap first tasks with equal priority\n\t\tprintln( seq.mkString( \" \" ))\n\n\t\tswap( idx + 1, sorted, seq )\t\t\t\t\t// swap next tasks with equal priority\n\t\tprintln( seq.mkString( \" \" ))\n\t}\n\telse\n\t\tprintln( \"NO\" )\n\n\t// find tasks with the same priority in indexed array (pairs), starting from start\n\t// and swap them in final sequence (tasks)\n\tdef swap( start: Int, pairs: Array[(Int,Int)], tasks: Array[Int] ) = {\n\t\tvar i = start\n\t\twhile( pairs( i )._1 != pairs( i - 1 )._1 )\n\t\t\ti += 1\n\t\tval t = tasks( i )\n\t\ttasks( i ) = tasks( i - 1 )\n\t\ttasks( i - 1 ) = t\n\t\ti\n\t}\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 26.09.14.\n */\nobject B extends App {\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n val hs = (for (i <- 0 until n) yield nextInt).toArray.zipWithIndex.sortBy(_._1)\n val ss = hs.groupBy(x => x._1).map(x => x._1 -> x._2.size)\n val ss3 = ss.filter(_._2 >= 3)\n val ss2 = ss.filter(_._2 >= 2)\n if (ss3.size >= 1) {\n out.println(\"YES\")\n val h = ss3.head._1\n val first = hs.map(_._2 + 1)\n out.println(first.mkString(\" \"))\n val es = hs.unzip._1\n val i1 = es.indexOf(h)\n val tmp = i1\n val i2 = es.indexOf(h, i1 + 1)\n val i3 = es.indexOf(h, i2 + 1)\n val second = first.updated(i1, first(i2)).updated(i2, first(tmp))\n out.println(second.mkString(\" \"))\n val third = first.updated(i1, first(i3)).updated(i3, first(tmp))\n out.println(third.mkString(\" \"))\n } else if (ss2.size >= 2) {\n out.println(\"YES\")\n val h1 = ss2.head._1\n val first = hs.map(_._2 + 1)\n out.println(first.mkString(\" \"))\n val es = hs.unzip._1\n val i1 = es.indexOf(h1)\n val tmp1 = i1\n val i2 = es.indexOf(h1, i1 + 1)\n val second = first.updated(i1, first(i2)).updated(i2, first(tmp1))\n out.println(second.mkString(\" \"))\n val h2 = ss2.last._1\n val i3 = es.indexOf(h2)\n val tmp2 = i3\n val i4 = es.indexOf(h2, i3 + 1)\n val third = first.updated(i3, first(i4)).updated(i4, first(tmp2))\n out.println(third.mkString(\" \"))\n } else {\n out.print(\"NO\")\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val indexed = data.zipWithIndex.sorted\n val duplicates = indexed.tail.foldLeft(1l, 1l, indexed.head._1) {\n case((count, soFar, prev), el) if count >= 3 =>\n (count, soFar, el._1)\n case((count, soFar, prev), el) if prev == el._1 =>\n (count, soFar + 1, el._1)\n case((count, soFar, prev), el) => (count * soFar, 1l, el._1)\n }\n val dup_count = if (duplicates._1 < 3) duplicates._1 * duplicates._2 else duplicates._1\n if (dup_count < 3)\n println(\"NO\")\n else {\n println(\"YES\")\n println(indexed.map(_._2 + 1).mkString(\" \"))\n val i1 = (0 until indexed.length - 1).find(i => indexed(i)._1 == indexed(i + 1)._1).get\n val tmp = indexed(i1)\n indexed(i1) = indexed(i1 + 1)\n indexed(i1 + 1) = tmp\n println(indexed.map(_._2 + 1).mkString(\" \"))\n val i2 = (indexed.length - 1 until 0 by -1).find(i => indexed(i)._1 == indexed(i - 1)._1).get\n val tmp2 = indexed(i2)\n indexed(i2) = indexed(i2 - 1)\n indexed(i2 - 1) = tmp2\n println(indexed.map(_._2 + 1).mkString(\" \"))\n }\n}\n"}, {"source_code": "\nimport java.util\n\n/**\n * @author pvasilyev\n * @since 18 Jun 2016\n */\nobject B471 extends App {\n\n def hasMoreThanThree(c: Array[util.ArrayList[Int]]): Boolean = {\n c.foreach((list: util.ArrayList[Int]) => {\n if (list != null) {\n if (list.size() > 2) {\n return true\n }\n }\n })\n false\n }\n\n def checkItIsPossible(c: Array[util.ArrayList[Int]]): Boolean = {\n var doubles = 0\n c.foreach((list: util.ArrayList[Int]) => {\n if (list != null) {\n if (list.size() > 2) {\n return true\n } else if (list.size() == 2) {\n doubles += 1\n }\n }\n })\n doubles > 1\n }\n\n def solve() = {\n val n: Int = scala.io.StdIn.readInt()\n val count: Array[util.ArrayList[Int]] = Array.ofDim(2001)\n scala.io.StdIn.readLine().split(\" \").map(_.toInt).foldLeft(1)((x, h) => {\n if (count(h) == null) {\n count(h) = new util.ArrayList[Int]()\n }\n count(h).add(x)\n x+1\n })\n\n if (!checkItIsPossible(count)) {\n println(\"NO\")\n } else {\n val a = new util.ArrayList[Int]()\n val b = new util.ArrayList[Int]()\n val c = new util.ArrayList[Int]()\n if (hasMoreThanThree(count)) {\n for (i <- 1 to 2000) {\n if (count(i) != null) {\n if (count(i).size() > 2) {\n val first = count(i).get(0)\n val second = count(i).get(1)\n val third = count(i).get(2)\n a.add(first)\n a.add(second)\n a.add(third)\n b.add(second)\n b.add(third)\n b.add(first)\n c.add(third)\n c.add(first)\n c.add(second)\n for (j <- 3 until count(i).size) {\n a.add(count(i).get(j))\n b.add(count(i).get(j))\n c.add(count(i).get(j))\n }\n } else {\n for (j <- 0 until count(i).size()) {\n a.add(count(i).get(j))\n b.add(count(i).get(j))\n c.add(count(i).get(j))\n }\n }\n }\n }\n } else {\n var firstIndex = -1\n var secondIndex = -1\n for (i <- 1 to 2000) {\n if (count(i) != null) {\n if (count(i).size() > 1) {\n if (firstIndex < 0) {\n firstIndex = i\n a.add(count(i).get(0))\n a.add(count(i).get(1))\n b.add(count(i).get(1))\n b.add(count(i).get(0))\n c.add(count(i).get(1))\n c.add(count(i).get(0))\n } else if (secondIndex < 0) {\n secondIndex = i\n a.add(count(i).get(0))\n a.add(count(i).get(1))\n b.add(count(i).get(0))\n b.add(count(i).get(1))\n c.add(count(i).get(1))\n c.add(count(i).get(0))\n } else {\n a.add(count(i).get(0))\n a.add(count(i).get(1))\n b.add(count(i).get(0))\n b.add(count(i).get(1))\n c.add(count(i).get(0))\n c.add(count(i).get(1))\n }\n } else {\n a.add(count(i).get(0))\n b.add(count(i).get(0))\n c.add(count(i).get(0))\n }\n }\n }\n }\n println(\"YES\")\n println(a.toArray.mkString(\" \"))\n println(b.toArray.mkString(\" \"))\n println(c.toArray.mkString(\" \"))\n }\n }\n\n solve()\n\n}\n"}, {"source_code": "object a extends App {\n val n = readLine.toInt\n var ps = readLine.split(\" \").map(_.toInt).zipWithIndex.sorted.toArray\n \n var eqct = 0\n var prev = (-20, -20)\n for (p <- ps) {\n if (prev._1==p._1) eqct += 1\n prev = p\n }\n if (eqct < 2) {\n println(\"NO\")\n System.exit(0)\n }\n println(\"YES\")\n for (i <- 1 to 3) {\n for (p <- ps) print((p._2+1) + \" \")\n var br = 0\n for (j <- 0 to n-2) {\n val (a, b) = (ps(j)._2, ps(j+1)._2)\n if (br== 0 && ps(j)._1==ps(j+1)._1 && a (x(0), x(1)))\n \n var eqct = 0\n for (i <- 0 to n-2)\n if (ps(i)(0) == ps(i+1)(0)) eqct += 1\n if (eqct < 2) {\n println(\"NO\")\n System.exit(0)\n }\n println(\"YES\")\n for (i <- 1 to 3) {\n for (p <- ps) print(p(1) + \" \")\n var br = 0\n for (j <- 0 to n-2) {\n val (a, b) = (ps(j)(1), ps(j+1)(1))\n if (br== 0 && ps(j)(0)==ps(j+1)(0) && a {\n\t\t\t\tval tmp = arr(tp._1)\n\t\t\t\tarr(tp._1) = arr(tp._2)\n\t\t\t\tarr(tp._2) = tmp\n\t\t\t}\n\t\t\t\n\t\t\tprintln(arr.map(_._2).mkString(\" \"))\n\t\t\tswap(swaps(0))\n\t\t\tprintln(arr.map(_._2).mkString(\" \"))\n\t\t\tswap(swaps(1))\n\t\t\tprintln(arr.map(_._2).mkString(\" \"))\n\t\t}\n\t}\n\n}\n"}], "negative_code": [{"source_code": "object a extends App {\n val n = readLine.toInt\n var ps = readLine.split(\" \").map(_.toInt).zipWithIndex.sorted.toArray\n \n var eqct = 0\n var prev = (-20, -20)\n for (p <- ps) {\n if (prev._1==p._1) eqct += 1\n prev = p\n }\n if (eqct < 2) {\n println(\"NO\")\n System.exit(0)\n }\n println(\"YES\")\n for (i <- 1 to 3) {\n for (p <- ps) print(p._2 + \" \")\n var br = 0\n for (j <- 0 to n-2) {\n val (a, b) = (ps(j)._2, ps(j+1)._2)\n if (br== 0 && ps(j)._1==ps(j+1)._1 && a {\n\t\t\t\tval tmp = arr(tp._1)\n\t\t\t\tarr(tp._1) = arr(tp._2)\n\t\t\t\tarr(tp._2) = tmp\n\t\t\t}\n\t\t\t\n\t\t\tprintln(arr.map(_._2).mkString(\" \"))\n\t\t\tswap(swaps(0))\n\t\t\tprintln(arr.map(_._2).mkString(\" \"))\n\t\t\tswap(swaps(1))\n\t\t\tprintln(arr.map(_._2).mkString(\" \"))\n\t\t}\n\t}\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val indexed = data.zipWithIndex.sorted\n val duplicates = indexed.tail.foldLeft(1, 1, indexed.head._1) {\n case((count, soFar, prev), el) if prev == el._1 => (count, soFar + 1, el._1)\n case((count, soFar, prev), el) => (count * soFar, 1, el._1)\n }\n val dup_count = duplicates._1 * duplicates._2\n if (dup_count < 3)\n println(\"NO\")\n else {\n println(\"YES\")\n println(indexed.map(_._2 + 1).mkString(\" \"))\n val i1 = (0 until indexed.length - 1).find(i => indexed(i)._1 == indexed(i + 1)._1).get\n val tmp = indexed(i1)\n indexed(i1) = indexed(i1 + 1)\n indexed(i1 + 1) = tmp\n println(indexed.map(_._2 + 1).mkString(\" \"))\n val i2 = (indexed.length - 1 until 0 by -1).find(i => indexed(i)._1 == indexed(i - 1)._1).get\n val tmp2 = indexed(i2)\n indexed(i2) = indexed(i2 - 1)\n indexed(i2 - 1) = tmp2\n println(indexed.map(_._2 + 1).mkString(\" \"))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val indexed = data.zipWithIndex.sorted\n val duplicates = indexed.tail.foldLeft(1l, 1l, indexed.head._1) {\n case((count, soFar, prev), el) if count >= 3 =>\n (count, soFar, el._1)\n case((count, soFar, prev), el) if prev == el._1 =>\n (count, soFar + 1, el._1)\n case((count, soFar, prev), el) => (count * soFar, 1l, el._1)\n }\n val dup_count = if (duplicates._1 < 3) duplicates._1 * duplicates._2 else duplicates._1\n if (n == 2000)\n println(dup_count)\n if (dup_count < 3)\n println(\"NO\")\n else {\n println(\"YES\")\n println(indexed.map(_._2 + 1).mkString(\" \"))\n val i1 = (0 until indexed.length - 1).find(i => indexed(i)._1 == indexed(i + 1)._1).get\n val tmp = indexed(i1)\n indexed(i1) = indexed(i1 + 1)\n indexed(i1 + 1) = tmp\n println(indexed.map(_._2 + 1).mkString(\" \"))\n val i2 = (indexed.length - 1 until 0 by -1).find(i => indexed(i)._1 == indexed(i - 1)._1).get\n val tmp2 = indexed(i2)\n indexed(i2) = indexed(i2 - 1)\n indexed(i2 - 1) = tmp2\n println(indexed.map(_._2 + 1).mkString(\" \"))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val indexed = data.zipWithIndex.sorted\n val duplicates = indexed.tail.foldLeft(1l, 1l, indexed.head._1) {\n case((count, soFar, prev), el) if prev == el._1 =>\n if (n == 2000)\n println(\"same \" + el)\n (count, soFar + 1, el._1)\n case((count, soFar, prev), el) => (count * soFar, 1l, el._1)\n }\n val dup_count = duplicates._1 * duplicates._2\n if (n == 2000)\n println(dup_count)\n if (dup_count < 3)\n println(\"NO\")\n else {\n println(\"YES\")\n println(indexed.map(_._2 + 1).mkString(\" \"))\n val i1 = (0 until indexed.length - 1).find(i => indexed(i)._1 == indexed(i + 1)._1).get\n val tmp = indexed(i1)\n indexed(i1) = indexed(i1 + 1)\n indexed(i1 + 1) = tmp\n println(indexed.map(_._2 + 1).mkString(\" \"))\n val i2 = (indexed.length - 1 until 0 by -1).find(i => indexed(i)._1 == indexed(i - 1)._1).get\n val tmp2 = indexed(i2)\n indexed(i2) = indexed(i2 - 1)\n indexed(i2 - 1) = tmp2\n println(indexed.map(_._2 + 1).mkString(\" \"))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val indexed = data.zipWithIndex.sorted\n val duplicates = indexed.tail.foldLeft(1l, 1l, indexed.head._1) {\n case((count, soFar, prev), el) if prev == el._1 => (count, soFar + 1, el._1)\n case((count, soFar, prev), el) => (count * soFar, 1, el._1)\n }\n val dup_count = duplicates._1 * duplicates._2\n if (n == 2000)\n println(dup_count)\n if (dup_count < 3)\n println(\"NO\")\n else {\n println(\"YES\")\n println(indexed.map(_._2 + 1).mkString(\" \"))\n val i1 = (0 until indexed.length - 1).find(i => indexed(i)._1 == indexed(i + 1)._1).get\n val tmp = indexed(i1)\n indexed(i1) = indexed(i1 + 1)\n indexed(i1 + 1) = tmp\n println(indexed.map(_._2 + 1).mkString(\" \"))\n val i2 = (indexed.length - 1 until 0 by -1).find(i => indexed(i)._1 == indexed(i - 1)._1).get\n val tmp2 = indexed(i2)\n indexed(i2) = indexed(i2 - 1)\n indexed(i2 - 1) = tmp2\n println(indexed.map(_._2 + 1).mkString(\" \"))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val indexed = data.zipWithIndex.sorted\n val duplicates = indexed.tail.foldLeft(1l, 1l, indexed.head._1) {\n case((count, soFar, prev), el) if prev == el._1 => (count, soFar + 1, el._1)\n case((count, soFar, prev), el) => (count * soFar, 1, el._1)\n }\n val dup_count = duplicates._1 * duplicates._2\n if (dup_count < 3)\n println(\"NO\")\n else {\n println(\"YES\")\n println(indexed.map(_._2 + 1).mkString(\" \"))\n val i1 = (0 until indexed.length - 1).find(i => indexed(i)._1 == indexed(i + 1)._1).get\n val tmp = indexed(i1)\n indexed(i1) = indexed(i1 + 1)\n indexed(i1 + 1) = tmp\n println(indexed.map(_._2 + 1).mkString(\" \"))\n val i2 = (indexed.length - 1 until 0 by -1).find(i => indexed(i)._1 == indexed(i - 1)._1).get\n val tmp2 = indexed(i2)\n indexed(i2) = indexed(i2 - 1)\n indexed(i2 - 1) = tmp2\n println(indexed.map(_._2 + 1).mkString(\" \"))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val indexed = data.zipWithIndex.sorted\n val duplicates = indexed.tail.foldLeft(1, 1, indexed.head._1) {\n case((count, soFar, prev), el) if prev == el._1 => (count, soFar + 1, el._1)\n case((count, soFar, prev), el) => (count * soFar, 1, el._1)\n }\n val dup_count = duplicates._1 * duplicates._2\n if (dup_count < 3)\n println(\"NO\")\n else {\n println(\"YES\")\n val i1 = (0 until indexed.length - 1).find(i => indexed(i)._1 == indexed(i + 1)._1).get\n val tmp = indexed(i1)\n indexed(i1) = indexed(i1 + 1)\n indexed(i1 + 1) = tmp\n println(indexed.map(_._2 + 1).mkString(\" \"))\n val i2 = (indexed.length - 1 until 0 by -1).find(i => indexed(i)._1 == indexed(i - 1)._1).get\n val tmp2 = indexed(i2)\n indexed(i2) = indexed(i2 - 1)\n indexed(i2 - 1) = tmp2\n println(indexed.map(_._2 + 1).mkString(\" \"))\n }\n}\n"}], "src_uid": "fdfc1e690eeee6f50e2a024bf3f841e8"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val K, N = ni()\n val A = na(N, -1)\n val C = Array.ofDim[Int](K + 10)\n val ans = Array.ofDim[Int](N)\n val CC = Array.ofDim[Int](N + 10) // カウントのカウント\n REP(N) { i =>\n C(A(i)) += 1\n CC(C(A(i))) += 1\n if (CC(C(A(i))) == K) ans(i) = 1\n }\n\n out.println(ans.mkString)\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Codeforces1100B {\n\n def getRoundString(n: Int, m: Int, a: Seq[Int]): String = {\n val difficultyCountMap = new mutable.HashMap[Int, Int]()\n for (i <- 1 to n) {\n difficultyCountMap.put(i, 0)\n }\n val countMilestoneMap = new mutable.HashMap[Int, Int]()\n\n var alreadyHeldContest = 0\n val roundString = (1 to m).map(_ => '0').toArray\n for (i <- a.indices) {\n difficultyCountMap(a(i)) += 1\n val count = difficultyCountMap(a(i))\n countMilestoneMap.put(count, countMilestoneMap.getOrElse(count, 0) + 1)\n if (countMilestoneMap(alreadyHeldContest + 1) >= n) {\n roundString(i) = '1'\n alreadyHeldContest += 1\n }\n }\n\n new String(roundString)\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = StdIn.readLine().trim.split(\" \").map(_.toInt)\n val a = StdIn.readLine().trim.split(\" \").map(_.toInt)\n val roundString = getRoundString(n, m, a)\n println(roundString)\n }\n}\n"}], "negative_code": [], "src_uid": "2070955288b2e2cdbae728d8e7ce78ab"} {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val yes = \"YES\"\n val no = \"NO\"\n\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val arr = new Array[Int](n)\n for(i <- 0 until n)\n arr(i) = sc.nextInt()\n\n val a = arr.sorted\n\n val max = a(n-1)\n val min = a(0)\n // a.foreach{println}\n // \n// println(min + \" \" + max)\n\n if(min == max)\n println(yes)\n else if ((max - min) % 2 != 0){\n var flag = true\n for(e <- a){\n if(e == max || e == min)\n ()\n else\n flag = false\n }\n if(flag)\n println(yes)\n else\n println(no)\n }\n else{\n val mid = (max+min) / 2\n\n var flag = true\n for(e <- a){\n if(e == max || e == min || e == mid)\n ()\n else\n flag = false\n }\n if(flag)\n println(yes)\n else\n println(no)\n }\n }\n}\n", "positive_code": [{"source_code": "//package merofeev.contests.codeforces.rnd371\n\nimport java.util.Scanner\n\n/**\n * @author erofeev \n * @since 13.09.16\n */\nobject BNumbers {\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n val count = in.nextLine().toInt\n val ints = in.nextLine().split(\" \").map(_.toInt).toSet.toSeq.sorted\n if (ints.size < 3) {\n println(\"YES\")\n } else if (ints.size > 3) {\n println(\"NO\")\n } else if (ints.head + ints(2) == 2 * ints(1)) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toLong)\n val min = line.min\n val max = line.max\n val delta = max - min\n if (min == max)\n println(\"YES\")\n else if ((max - min) % 2 == 1) {\n if (line.exists(x => x != min + delta && x != min))\n println(\"NO\")\n else\n println(\"YES\")\n } else if (line.exists(x => x != min + delta / 2 && x != min && x != min + delta))\n println(\"NO\")\n else\n println(\"YES\")\n}\n"}, {"source_code": "object B714 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val a = readLongs(n).toSet\n if(a.size > 2) {\n val sum = a.min + (a.max - a.min) / 2\n val set = cu.Set.empty[Long]\n a.map(sum - _).filter(_ != 0).foreach { num =>\n set.add(math.abs(num))\n }\n if (set.size <= 1) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n } else {\n println(\"YES\")\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _714B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll}\n val data = read[Set[Int]]\n\n val ans = data.size match {\n case 1 | 2 => true\n case 3 =>\n val Seq(a, b, c) = data.toSeq.sorted\n (b - a) == c - b\n case _ => false\n }\n\n write(ans.toEnglish)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import collection.mutable.Set;\n\nobject CF3712B extends App {\n readLine\n val a = readLine.split(\" \").map(_.toInt)\n println(Solve(a))\n \n def Solve(a: Array[Int]) :String = {\n val s = Set(0)\n s -= 0\n for (i <- a) {\n s += i\n if (s.size > 3) return \"NO\" \n }\n if (s.size <= 2)\n return \"YES\"\n val b = s.toArray\n scala.util.Sorting.quickSort(b)\n return if (b(0) + b(2) == 2*b(1)) \"YES\" else \"NO\"\n }\n}\n"}], "negative_code": [{"source_code": "//package merofeev.contests.codeforces.rnd371\n\nimport java.util.Scanner\nimport scala.util.control.Breaks._\n\n/**\n * @author erofeev \n * @since 13.09.16\n */\nobject BNumbers {\n\n def test(possibleX: Int, ints: Array[Int]): Boolean = {\n for (next <- ints) {\n if (possibleX == next) {\n } else if (possibleX + possibleX == next) {\n } else if (possibleX - possibleX == next) {\n } else if (possibleX == next - possibleX) {\n } else if (possibleX + possibleX == next - possibleX) {\n } else {\n return false\n }\n }\n return true\n }\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n val count = in.nextLine().toInt\n val ints = in.nextLine().split(\" \").map(_.toInt)\n for (possibleX <- ints) {\n val solved = test(possibleX, ints)\n if (solved) {\n System.out.println(\"YES\")\n return\n }\n }\n System.out.println(\"NO\")\n }\n}\n"}, {"source_code": "//package merofeev.contests.codeforces.rnd371\n\nimport java.util.Scanner\nimport scala.util.control.Breaks._\n\n/**\n * @author erofeev \n * @since 13.09.16\n */\nobject BNumbers {\n\n def test(possibleX: Int, ints: Array[Int]): Boolean = {\n for (next <- ints) {\n if (possibleX == next) {\n } else if (possibleX + possibleX == next) {\n } else if (possibleX == next - possibleX) {\n } else if (possibleX + possibleX == next - possibleX) {\n } else {\n return false\n }\n }\n return true\n }\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n val count = in.nextLine().toInt\n val ints = in.nextLine().split(\" \").map(_.toInt)\n for (possibleX <- ints) {\n val solved = test(possibleX, ints)\n if (solved) {\n System.out.println(\"YES\")\n return\n } else {\n System.out.println(\"NO\")\n return\n }\n }\n }\n}\n"}, {"source_code": "//package merofeev.contests.codeforces.rnd371\n\nimport java.util.Scanner\n\n/**\n * @author erofeev \n * @since 13.09.16\n */\nobject BNumbers {\n\n def test(possibleX: Long, ints: Array[Long]): Boolean = {\n for (next <- ints) {\n if (possibleX == next) {\n } else if (possibleX + possibleX == next) {\n } else if (possibleX - possibleX == next) {\n } else if (possibleX + possibleX == next - possibleX) {\n } else {\n return false\n }\n }\n return true\n }\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n val count = in.nextLine().toInt\n val ints = in.nextLine().split(\" \").map(_.toLong)\n for (possibleX <- ints) {\n val solved = test(possibleX, ints)\n if (solved) {\n System.out.println(\"YES\")\n return\n }\n }\n System.out.println(\"NO\")\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toInt)\n val min = line.min\n val max = line.max\n val delta = max - min\n if (min == max)\n println(\"YES\")\n else if ((max - min) % 2 == 1) {\n if (!line.contains(delta))\n println(\"NO\")\n else if (line.exists(x => x != min + delta && x != min))\n println(\"NO\")\n else\n println(\"YES\")\n } else if (line.exists(x => x != min + delta / 2 && x != min && x != min + delta))\n println(\"NO\")\n else\n println(\"YES\")\n}\n"}, {"source_code": "object B714 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val a = readLongs(n)\n val sum = a.sum\n val set = cu.Set.empty[Long]\n val set2 = cu.Set.empty[Long]\n a.map(sum/n - _).filter(_ != 0).foreach{num =>\n if(set.contains(-num))\n set.remove(-num)\n else\n set.add(num)\n if(num != 0)\n set2.add(math.abs(num))\n }\n if(set.isEmpty && set2.size <= 1) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object B714 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val a = readLongs(n)\n val sum = a.min+(a.max-a.min)/2\n val set = cu.Set.empty[Long]\n a.map(sum - _).filter(_ != 0).foreach{num =>\n set.add(math.abs(num))\n }\n if(set.size <= 1) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object B714 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val a = readLongs(n)\n val sum = a.sum\n val set = cu.Set.empty[Long]\n if(sum%n == 0) {\n a.foreach{ x =>\n val num = sum/n - n\n if (num>0) set.add(num)\n else set.remove(num)\n }\n if(set.isEmpty) println(\"YES\")\n else println(\"NO\")\n } else {\n println(\"NO\")\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import collection.mutable.Set;\n\nobject CF3712B extends App {\n readLine\n val a = readLine.split(\" \").map(_.toInt)\n println(Solve(a))\n \n def Solve(a: Array[Int]) :String = {\n val s = Set(0)\n s -= 0\n for (i <- a) {\n s += i\n println(\"*\" + i)\n if (s.size > 3) return \"NO\" \n }\n if (s.size <= 2)\n return \"YES\"\n val b = s.toArray\n return if (b(0) + b(2) == 2*b(1)) \"YES\" else \"NO\"\n }\n}\n"}, {"source_code": "import collection.mutable.Set;\n\nobject CF3712B extends App {\n readLine\n val a = readLine.split(\" \").map(_.toInt)\n println(Solve(a))\n \n def Solve(a: Array[Int]) :String = {\n val s = Set(0)\n s -= 0\n for (i <- a) {\n s += i\n if (s.size > 3) return \"NO\" \n }\n if (s.size <= 2)\n return \"YES\"\n val b = s.toArray\n return if (b(0) + b(2) == 2*b(1)) \"YES\" else \"NO\"\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n // \n // val s = sc.nextLine()\n // val str = sc.next()\n\n def main (args: Array[String]){\n val yes = \"YES\"\n val no = \"NO\"\n\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val arr = new Array[Int](n)\n for(i <- 0 until n)\n arr(i) = sc.nextInt()\n\n val a = arr.sorted\n\n val max = a(n-1)\n val min = a(0)\n // a.foreach{println}\n // \n// println(min + \" \" + max)\n\n if(min == max)\n println(yes)\n else if ((max - min) % 2 != 0)\n println(no)\n else{\n val mid = (max+min) / 2\n\n var flag = true\n for(e <- a){\n if(e == max || e == min || e == mid)\n ()\n else\n \n flag = false\n }\n if(flag)\n println(yes)\n else\n println(no)\n }\n }\n}\n"}], "src_uid": "27f837609b2777cefccb13aa4596d91c"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n if (A.count(_ % 2 == 0) > 0 && A.count(_ % 2 == 1) > 0) {\n sort(A)\n }\n out.println(A.mkString(\" \"))\n }\n\n def sort(a: Array[Int]): Array[Int] = {\n import scala.util.Sorting\n val n = a.length\n REP(n) { i =>\n val j = scala.util.Random.nextInt(n - i) + i\n val tmp = a(i)\n a(i) = a(j)\n a(j) = tmp\n }\n Sorting.stableSort(a)\n a\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = readInt\n val a = readLine.split(\" \").map(_.toInt)\n val ans = if (a.exists(x => (x & 0x01) == 1) && a.exists(x => (x & 0x01) == 0)) a.sorted else a\n println(ans.mkString(\" \"))\n }\n}\n"}], "negative_code": [], "src_uid": "aab7f7cce0b704051627b625294635bc"} {"source_code": "object CF918B extends App{\n val sc = new java.util.Scanner(System.in)\n val n, m = sc.nextInt\n val servers = Seq.fill[(String, String)](n)(sc.next, sc.next).map(s => (s._2, s._1)).toMap\n val commands = Seq.fill[(String, String)](m)(sc.next, sc.next)\n commands.foreach(c => println(c._1 + \" \" + c._2 + \" #\" + servers(c._2.init)))\n}\n", "positive_code": [{"source_code": "object b918 {\n def main(args: Array[String]): Unit = {\n val lines = scala.io.Source.stdin.getLines().toArray\n val Array(a,_) = lines(0).split(\" \").map(_.toInt)\n val (server, ips) = lines.drop(1).splitAt(a)\n val serverMap : Map[String,String] = server.map{ i => val Array (j,k) = i.split( \" \"); (k,j)}.toMap\n ips.map{i => s\"$i #${serverMap(i.split(\" \")(1) stripSuffix \";\") }\"} foreach println\n }\n}\n"}, {"source_code": "import scala.collection.immutable.HashMap\n\nobject B extends App {\n val Array(n, m) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val ips = (0 until n).foldLeft(HashMap.empty[String, String])((ips, _) => {\n val Array(name, ip) = scala.io.StdIn.readLine().split(\" \")\n ips + (ip -> name)\n })\n\n val cmds = (0 until m).foldLeft(List.empty[String])((cmds, _) => {\n val Array(cmd, ip) = scala.io.StdIn.readLine().split(\" |;\")\n val name = ips(ip)\n cmds :+ s\"$cmd $ip; #$name\"\n })\n\n println(cmds.mkString(\"\\n\"))\n}\n"}, {"source_code": "object _918B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching, breakOut}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val n, m = io.read[Int]\n\n val names = io.read[Iterator, String](2*n)\n .grouped(2)\n .map({case Seq(name, ip) => ip -> name})\n .toMap\n\n val commands = io.read[Iterator, String](2*m)\n .grouped(2)\n .map({case Seq(cmd, ip) => s\"$cmd $ip #${names(ip.stripSuffix(\";\"))}\"})\n\n io.write(commands.mkString(\"\\n\"))\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "import scala.collection.immutable.HashMap\n\nobject B extends App {\n val Array(n, m) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val ips = (0 until n).foldLeft(HashMap.empty[String, String])((ips, _) => {\n val Array(name, ip) = scala.io.StdIn.readLine().split(\" \")\n ips + (ip -> name)\n })\n\n val cmds = (0 until m).foldLeft(List.empty[String])((cmds, _) => {\n val Array(cmd, ip) = scala.io.StdIn.readLine().split(\" |;\")\n val name = ips(ip)\n cmds :+ s\"$cmd $ip; #$name\"\n }).reverse\n\n println(cmds.mkString(\"\\n\"))\n}\n"}, {"source_code": "object CF918B extends App{\n val sc = new java.util.Scanner(System.in)\n val n, m = sc.nextInt\n val servers = Seq.fill[(String, String)](n)(sc.next, sc.next).map(s => (s._2, s._1)).toMap\n val commands = Seq.fill[(String, String)](n)(sc.next, sc.next)\n commands.foreach(c => println(c._1 + \" \" + c._2 + \" #\" + servers(c._2.init)))\n}"}], "src_uid": "94501cd676a9214a59943b8ddd1dd31b"} {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n val (al, ar) = an.partition(_ % 2 == 0)\n\n val ans = al.length % 2 == 0 || al.exists(l => ar.exists(r => 1 == (l - r).abs))\n\n if (ans) println(\"YES\")\n else println(\"NO\")\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject C {\n\n def solution(s: Seq[Int]): String = {\n val (ev, odd) = s.partition(_ % 2 == 0)\n val (ss, sb) = if (ev.size < odd.size) (ev, odd) else (odd, ev)\n if ((ss.length % 2 == 0) || {\n val other = sb.toSet\n ss.exists { se =>\n other.contains(se - 1) || other.contains(se + 1)\n }\n }) \"YES\" else \"NO\"\n }\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val _ = readLine.toInt\n val s = readLine.split(\" \").toSeq.map(_.toInt)\n println(solution(s))\n }\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CF644(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CF644(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val n = ni()\n val a = na(n)\n var cno = 0\n var cne = 0\n\n REP(n) { i =>\n if(a(i) % 2 == 0) cne += 1\n else cno += 1\n }\n\n if(cne % 2 == 0 && cno % 2 == 0) {\n out.println(\"YES\")\n } else {\n scala.util.Sorting.quickSort(a)\n var yes = false\n REP(n-1, 1) { i =>\n if(a(i) - a(i-1) == 1) yes = true\n }\n if(yes) {\n out.println(\"YES\")\n } else out.println(\"NO\")\n }\n }\n }\n}\n"}, {"source_code": "object C extends App {\n private def closest(an: List[Int], bn: List[Int]): Boolean = {\n def go(an: List[Int], bn: List[Int]): Boolean =\n if (an.isEmpty || bn.isEmpty) false\n else {\n val am = an.drop(an.lastIndexWhere(_ < bn.head))\n val bl = bn.drop(bn.lastIndexWhere(_ < an.head))\n\n val (a, b) = (am.head, bl.head)\n val (m, l) = (am.length, bl.length)\n\n val d = (a - b).abs\n\n if (d == 1) true\n else if (a < b) go(am.tail, bl)\n else if (a > b) go(am, bl.tail)\n else if (m < l) go(am, bl.tail)\n else go(am.tail, bl)\n }\n\n go(an, bn)\n }\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n val (al, ar) = an.partition(_ % 2 == 0)\n\n if (al.length % 2 == 0) println(\"YES\")\n else {\n val (bl, br) = (al.sorted, ar.sorted)\n\n if (closest(bl, br)) println(\"YES\")\n else println(\"NO\")\n }\n }\n}\n"}], "negative_code": [{"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val (al, ar) = an.partition(_ % 2 == 0)\n\n if (al.length % 2 == 0) println(\"YES\")\n else {\n val (bl, br) = (al.sorted, ar.sorted)\n\n var i = 0\n var j = 0\n var d = 200\n\n while (d != 1 && i < bl.length && j < br.length) {\n val (l, r) = (bl(i), br(j))\n\n i = if (l < r) bl.lastIndexWhere(_ < r) else i\n j = if (r < l) br.lastIndexWhere(_ < l) else j\n\n d = d min (bl(i) - br(j)).abs\n\n if (l < r) j += 1\n else if (r < l) i += 1\n else if (i + 1 < bl.length) i += 1\n else j += 1\n }\n\n if (d == 1) println(\"YES\")\n else println(\"NO\")\n }\n }\n}\n"}], "src_uid": "005a29a4b4e7ee4fd21444846014727b"} {"source_code": "import java.io._\nimport java.util._\n\nobject test\n{\n\tdef main(args: Array[String]) =\n\t{\n\t\tval s = new Scanner(System.in)\n\t\tval n = s.nextInt\n\t\tvar lst = new Array[Int](n)\n\n\t\tfor(i<-0 until n) lst(i) = s.nextInt\n\t\tlst = lst.sorted\n\t\t\n\t\tvar top3 = new Array[BigInt](3)\n\t\tvar v = lst(0)+1\n\t\tvar j = -1\n\t\tvar break = false\n\t\tfor(i<-0 until n if break==false)\n\t\t{\n\t\t\tif(lst(i)==v)\n\t\t\t{\n\t\t\t\ttop3(j)+=1\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tj+=1\n\t\t\t\tif(j>=3)\n\t\t\t\t{\n\t\t\t\t\tbreak=true\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ttop3(j)=1\n\t\t\t\t\tv=lst(i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//println(top3(0),top3(1),top3(2))\n\t\tif(top3(0)>=3)\n\t\t{\n\t\t\t// C(top(0),3)\n\t\t\tval n=top3(0)\n\t\t\tprintln(n*(n-1)*(n-2)/6)\n\t\t}\n\t\telse if(top3(0)+top3(1)>=3)\n\t\t{\n\t\t\t// C(top(1),3-top(0))\n\t\t\tval n=top3(1)\n\t\t\tif(3-top3(0)==2)\n\t\t\t\tprintln(n*(n-1)/2)\n\t\t\telse\n\t\t\t\tprintln(n)\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintln(top3(2))\n\t\t}\n\t}\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject SolutionB extends App {\n readLine()\n def readInts() = readLine() split \" \" map (_.toInt) toSeq;\n\n val a = readInts()\n val min3 = a.sorted.take(3)\n\n def newtonBinom(n: Long, k: Long): Long = (n - k + 1 to n).product / (1.toLong to k).product\n\n println(\n min3 groupBy(x => x) mapValues (_.length.toLong) map { case (x, n) =>\n newtonBinom(a.count(_ == x) , Math.min(n, 3))\n } product\n )\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject Solution extends App {\n readLine()\n def readInts() = readLine() split \" \" map (_.toInt) toSeq;\n\n val a = readInts()\n val min3 = a.sorted.take(3)\n\n println(\n min3 groupBy(x => x) mapValues (_.length.toLong) flatMap { case (x, n) => (n+1) to Math.max(n+3, a.count(_ == x)) } product\n )\n\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject SolutionB extends App {\n readLine()\n def readInts() = readLine() split \" \" map (_.toInt) toSeq;\n\n val a = readInts()\n val min3 = a.sorted.take(3)\n\n println(\n min3 groupBy(x => x) mapValues (_.length.toLong) map { case (x, n) => \n val rng = (n+1).toLong to a.count(_ == x) \n val rngSize = rng.size.toLong\n rng.product / (Math.max(1, rngSize) to rngSize).product\n } product\n )\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject SolutionB extends App {\n readLine()\n def readInts() = readLine() split \" \" map (_.toInt) toSeq;\n\n val a = readInts()\n val min3 = a.sorted.take(3)\n\n println(\n min3 groupBy(x => x) mapValues (_.length.toLong) flatMap { case (x, n) => (n+1) to Math.min(n+3, a.count(_ == x)) } product\n )\n\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject SolutionB extends App {\n readLine()\n def readInts() = readLine() split \" \" map (_.toInt) toSeq;\n\n val a = readInts()\n val min3 = a.sorted.take(3)\n\n println(\n min3 groupBy(x => x) mapValues (_.length.toLong) flatMap { case (x, n) => (n+1) to a.count(_ == x) } product\n )\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject SolutionB extends App {\n readLine()\n def readInts() = readLine() split \" \" map (_.toInt) toSeq;\n\n val a = readInts()\n val min3 = a.sorted.take(3)\n\n println(\n min3 groupBy(x => x) mapValues (_.length.toLong) flatMap { case (x, n) =>\n val cnt = a.count(_ == x)\n Math.max(n+1, cnt-2) to cnt\n } product\n )\n\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Solution extends App {\n readLine()\n def readInts() = readLine() split \" \" map (_.toInt) toSeq;\n\n val a = readInts()\n val min3 = a.sorted.take(3)\n\n println(\n min3 groupBy(x => x) mapValues (_.length) flatMap { case (x, n) => (n+1) to a.count(_ == x) } product\n )\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n readLine()\n def readInts() = readLine() split \" \" map (_.toInt) toSeq\n\n val a = readInts()\n val min3 = a.sorted.take(3)\n\n println(\n min3 groupBy(x => x) mapValues (_.length.toLong) flatMap { case (x, n) => n to a.count(_ == x) } product\n )\n}"}, {"source_code": "import java.io._\nimport java.util._\n\nobject test\n{\n\tdef main(args: Array[String]) =\n\t{\n\t\tval s = new Scanner(System.in)\n\t\tval n = s.nextInt\n\t\tvar lst = new Array[Int](n)\n\n\t\tfor(i<-0 until n) lst(i) = s.nextInt\n\t\tlst = lst.sorted\n\t\t\n\t\tvar top3 = new Array[BigInt](3)\n\t\tvar v = lst(0)+1\n\t\tvar j = -1\n\t\tvar break = false\n\t\tfor(i<-0 until n if break==false)\n\t\t{\n\t\t\tif(lst(i)==v)\n\t\t\t{\n\t\t\t\ttop3(j)+=1\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tj+=1\n\t\t\t\tif(j>=3)\n\t\t\t\t{\n\t\t\t\t\tbreak=true\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ttop3(j)=1\n\t\t\t\t\tv=lst(i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintln(top3(0),top3(1),top3(2))\n\t\tif(top3(0)>=3)\n\t\t{\n\t\t\t// C(top(0),3)\n\t\t\tval n=top3(0)\n\t\t\tprintln(n*(n-1)*(n-2)/6)\n\t\t}\n\t\telse if(top3(0)+top3(1)>=3)\n\t\t{\n\t\t\t// C(top(1),3-top(0))\n\t\t\tval n=top3(1)\n\t\t\tif(3-top3(0)==2)\n\t\t\t\tprintln(n*(n-1)/2)\n\t\t\telse\n\t\t\t\tprintln(n)\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintln(top3(2))\n\t\t}\n\t}\n}"}, {"source_code": "import java.io._\nimport java.util._\n\nobject test\n{\n\tdef main(args: Array[String]) =\n\t{\n\t\tval s = new Scanner(System.in)\n\t\tval n = s.nextInt\n\t\tvar lst = new Array[Int](n)\n\n\t\tfor(i<-0 until n) lst(i) = s.nextInt\n\t\tlst = lst.sorted\n\t\t\n\t\tvar top3 = new Array[Int](3)\n\t\tvar v = lst(0)+1\n\t\tvar j = -1\n\t\tvar break = false\n\t\tfor(i<-0 until n if break==false)\n\t\t{\n\t\t\tif(lst(i)==v)\n\t\t\t{\n\t\t\t\ttop3(j)+=1\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tj+=1\n\t\t\t\tif(j>=3)\n\t\t\t\t{\n\t\t\t\t\tbreak=true\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ttop3(j)=1\n\t\t\t\t\tv=lst(i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(top3(0)>=3)\n\t\t{\n\t\t\t// C(top(0),3)\n\t\t\tval n=top3(0)\n\t\t\tprintln(n*(n-1)*(n-2)/6)\n\t\t}\n\t\telse if(top3(0)+top3(1)>=3)\n\t\t{\n\t\t\t// C(top(1),3-top(0))\n\t\t\tval n=top3(1)\n\t\t\tif(3-top3(0)==2)\n\t\t\t\tprintln(n*(n-1)/2)\n\t\t\telse\n\t\t\t\tprintln(n)\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintln(top3(2))\n\t\t}\n\t}\n}"}, {"source_code": "import java.io._\nimport java.util._\n\nobject test\n{\n\tdef main(args: Array[String]) =\n\t{\n\t\tval s = new Scanner(System.in)\n\t\tval n = s.nextInt\n\t\tvar lst = new Array[Int](n)\n\n\t\tfor(i<-0 until n) lst(i) = s.nextInt\n\t\tlst = lst.sorted\n\t\t\n\t\tvar top3 = new Array[Int](3)\n\t\tvar v = lst(0)+1\n\t\tvar j = -1\n\t\tvar break = false\n\t\tfor(i<-0 until n if break==false)\n\t\t{\n\t\t\tif(lst(i)==v)\n\t\t\t{\n\t\t\t\ttop3(j)+=1\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tj+=1\n\t\t\t\tif(j>=3)\n\t\t\t\t{\n\t\t\t\t\tbreak=true\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ttop3(j)=1\n\t\t\t\t\tv=lst(i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(top3(0)>=3)\n\t\t{\n\t\t\t// C(top(0),3)\n\t\t\tval n=top3(0)\n\t\t\tprintln(n*(n-1)*(n-2))\n\t\t}\n\t\telse if(top3(0)+top3(1)>=3)\n\t\t{\n\t\t\t// C(top(1),3-top(0))\n\t\t\tval n=top3(1)\n\t\t\tif(3-top3(0)==2)\n\t\t\t\tprintln(n*(n-1))\n\t\t\telse\n\t\t\t\tprintln(n)\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintln(top3(2))\n\t\t}\n\t}\n}"}], "src_uid": "4c2d804bb2781abfb43558f8b2c6424f"} {"source_code": "import scala.annotation.tailrec\nimport scala.collection.immutable.IndexedSeq\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _629A extends CodeForcesApp {\n override type Result = Int\n\n override def solve(read: InputReader) = {\n val n = read[Int]\n val chocolates: IndexedSeq[(Int, Int)] = for {\n i <- 1 to n\n line = read[String]\n j <- 1 to n\n if line(j-1) == 'C'\n } yield (i, j)\n\n var ans = 0\n for (i <- chocolates.indices) {\n val (a1, a2) = chocolates(i)\n for (j <- chocolates.indices drop (i+1)) {\n val (b1, b2) = chocolates(j)\n if (a1 == b1 || a2 == b2) ans += 1\n }\n }\n\n ans\n }\n\n override def format(result: Result) = result.toString\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n", "positive_code": [{"source_code": "\n\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject A_343_A { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n runTest(Test.sa2)\n debugV = true\n// file = File(\"C:\\\\temp\\\\google cj\\\\2014q\\\\c-small.res\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading --------------------------\n val n = readLine.int\n val arr = new Array[String](n)\n (0 until n).foreach(arr(_) = readLine.string)\n// val arr = Array.fill(n,n)(0)\n// for(i <- 0 until n) {\n// val line = readLine.string\n// for(j <- 0 until n) {\n// arr(i)(j) = if (line(j) == '.') 0 else 1 \n// }\n// }\n debug(\"n = \" + n)\n \n //---------------------------- parameters reading end ----------------------\n \n val rr = arr.map(x => soch(x.count { _ == 'C' })).sum\n var total = rr\n \n for(i <- 0 until n) {\n var colCount = 0\n for(j <- 0 until n) {\n if (arr(j)(i) == 'C') {\n colCount += 1\n }\n }\n total += soch(colCount)\n// total += Subsets.subsetNumber(colCount, 2)\n }\n \n outLn(total+\"\")\n \n finish\n }\n \n def soch(all:Int): Int = all - 1 match {\n case x if x < 1 => 0\n case rest => rest + soch(rest)\n }\n \n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) {\n resultStr.append(str).append(\"\\n\")\n }\n def finish() {\n// if (file == null) {\n println(resultStr.toString())\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n3\n.CC\nC..\nC.C\n\"\"\"\n\nval sa2 = \"\"\"\n4\nCC..\nC..C\n.CC.\n.CC.\n\"\"\"\n\n}\n\n}\n"}, {"source_code": "\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject A_343_A { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n runTest(Test.sa2)\n debugV = true\n// file = File(\"C:\\\\temp\\\\google cj\\\\2014q\\\\c-small.res\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading --------------------------\n val n = readLine.int\n val arr = Array.fill(n,n)(0)\n for(i <- 0 until n) {\n val line = readLine.string\n for(j <- 0 until n) {\n arr(i)(j) = if (line(j) == '.') 0 else 1 \n }\n }\n debug(\"n = \" + n)\n \n //---------------------------- parameters reading end ----------------------\n \n var total = 0\n for(i <- 0 until n) {\n var rowCount = 0\n for(j <- 0 until n) {\n if (arr(i)(j) == 1) {\n rowCount += 1\n }\n }\n total += soch(rowCount)\n// total += Subsets.subsetNumber(rowCount, 2)\n }\n \n for(i <- 0 until n) {\n var colCount = 0\n for(j <- 0 until n) {\n if (arr(j)(i) == 1) {\n colCount += 1\n }\n }\n total += soch(colCount)\n// total += Subsets.subsetNumber(colCount, 2)\n }\n \n outLn(total+\"\")\n \n finish\n }\n \n def soch(all:Int): Int = all - 1 match {\n case x if x < 1 => 0\n case rest => rest + soch(rest)\n }\n \n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) {\n resultStr.append(str).append(\"\\n\")\n }\n def finish() {\n// if (file == null) {\n println(resultStr.toString())\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n3\n.CC\nC..\nC.C\n\"\"\"\n\nval sa2 = \"\"\"\n4\nCC..\nC..C\n.CC.\n.CC.\n\"\"\"\n\n}\n\n}\n"}, {"source_code": "\n\nimport java.util.ArrayList\nimport java.util.StringTokenizer\nimport scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject A_343_A { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.sa2.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n// file = File(\"C:\\\\temp\\\\google cj\\\\2014q\\\\c-small.res\")\n\n\n //---------------------------- parameters reading --------------------------\n// br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n val arr = Array.fill(n,n)(0)\n for(i <- 0 until n) {\n val line = readLine.string\n for(j <- 0 until n) {\n arr(i)(j) = if (line(j) == '.') 0 else 1 \n }\n }\n //---------------------------- parameters reading end ----------------------\n \n var total = 0\n for(i <- 0 until n) {\n var rowCount = 0\n for(j <- 0 until n) {\n if (arr(i)(j) == 1) {\n rowCount += 1\n }\n }\n total += soch(rowCount)\n// total += Subsets.subsetNumber(rowCount, 2)\n }\n \n for(i <- 0 until n) {\n var colCount = 0\n for(j <- 0 until n) {\n if (arr(j)(i) == 1) {\n colCount += 1\n }\n }\n total += soch(colCount)\n// total += Subsets.subsetNumber(colCount, 2)\n }\n \n println(total+\"\")\n }\n \n def soch(all:Int): Int = all - 1 match {\n case x if x < 1 => 0\n case rest => rest + soch(rest)\n }\n \n \n //============================ service code ======================\n\n val br = createBufferedReader(System.in)\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n \n }\n \n def createBufferedReader(in: InputStream): BufferedReader = {\n val bis = new BufferedInputStream(in);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n3\n.CC\nC..\nC.C\n\"\"\"\n\nval sa2 = \"\"\"\n4\nCC..\nC..C\n.CC.\n.CC.\n\"\"\"\n\n}\n\n}\n"}, {"source_code": "import scala.io.Source\n\nobject CF343_A extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n \n val rows = new Array[Int](100)\n val cols = new Array[Int](100)\n \n for(r <- 0 to n-1) {\n val line = in.next()\n for(c <- 0 to n-1) {\n if(line.charAt(c) == 'C') {\n cols(c) += 1\n rows(r) += 1\n }\n \n }\n }\n \n var res = 0\n \n for(i <- 0 to n-1) {\n if(2 <= rows(i)) res += combination(rows(i), 2)\n if(2 <= cols(i)) res += combination(cols(i), 2)\n }\n \n println(res)\n\n def combination(n: Int, r: Int): Int = {\n if(r == 0)\n 1\n else if(n == 0) \n 0\n else {\n var res = 0\n res += combination(n-1, r)\n res += combination(n-1, r-1)\n res\n }\n }\n \n \n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val rows = Array.ofDim[Int](n)\n val res = (1 to n).foldLeft(0l) {\n case (acc, _) =>\n val str = in.next()\n val count = str.count(_ == 'C')\n str.indices.foreach{i => if (str(i) == 'C') rows(i) += 1}\n acc + count * (count - 1) / 2\n } + rows.foldLeft(0l){\n case(acc, count) => acc + count * (count - 1) / 2\n }\n println(res)\n\n}"}, {"source_code": "object A629 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = Array.fill(n)(read)\n val row = Array.fill(n)(0)\n val col = Array.fill(n)(0)\n for(i <- 0 until n; j <- 0 until n) {\n if(in(i)(j) == 'C') {\n row(i) += 1\n col(j) += 1\n }\n }\n val res = (row++col).foldLeft(0L){case (sum, i) => sum + (i.toLong*(i.toLong-1))/2}\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 23 Apr 2016\n */\nobject Problem155 extends App {\n\n val n: Int = scala.io.StdIn.readInt()\n val cake = Array.ofDim[Char](n, n)\n for (i <- 0 until n) {\n cake(i) = scala.io.StdIn.readLine().toCharArray\n }\n var answer = 0\n\n for (i <- 0 until n) {\n var inRow = 0\n for (j <- 0 until n) {\n if (cake(i)(j) == 'C') {\n inRow += 1\n }\n }\n if (inRow >= 2) {\n answer += inRow * (inRow - 1) / 2\n }\n }\n for (j <- 0 until n) {\n var inCol = 0\n for (i <- 0 until n) {\n if (cake(i)(j) == 'C') {\n inCol += 1\n }\n }\n if (inCol >= 2) {\n answer += inCol * (inCol - 1) / 2\n }\n }\n println(answer)\n}\n"}, {"source_code": "object A {\n def main(args: Array[String]) {\n var arr = Array.ofDim[Char](128,128)\n var cnt = -1\n var n = 0\n for (ln <- io.Source.stdin.getLines) {\n if (cnt == -1) {\n\t n = ln.trim.toInt\n\t}\n else {\n\t for ( i <- 0 until ln.trim.length) {\n\t\tarr(cnt)(i) = ln(i)\n\t } \n\t}\n\tcnt = cnt + 1 \n }\n var res = 0\n for ( i <- 0 until n){\n var C = 0\n\tfor (j<- 0 until n){\n\t if(arr(i)(j)=='C'){\n\t\tC = C + 1\n\t }\n\t}\n res = res + C*(C-1)/2\n }\n for ( j <- 0 until n){\n var C = 0\n\tfor (i<- 0 until n){\n\t if(arr(i)(j)=='C'){\n\t\tC = C + 1\n\t }\n\t}\n res = res + C*(C-1)/2\n }\n println(res)\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _629A extends CodeForcesApp {\n override type Result = Int\n\n override def solve(read: InputReader) = {\n val n = read[Int]\n val (rows, cols) = (Array.ofDim[Int](n+1), Array.ofDim[Int](n+1))\n\n for {\n i <- 1 to n\n line = read[String]\n j <- 1 to n\n if line(j-1) == 'C'\n } {\n rows(i) += 1\n cols(j) += 1\n }\n\n def nc2(i: Int) = (i*(i-1))/2\n\n rows.map(nc2).sum + cols.map(nc2).sum\n }\n\n override def format(result: Result) = result.toString\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _629A extends CodeForcesApp {\n override type Result = Int\n\n override def solve(read: InputReader) = {\n val n = read[Int]\n val chocolates = for {\n i <- 0 until n\n line = read[String]\n j <- 0 until n if line(j) == 'C'\n } yield (i, j)\n\n var ans = 0\n for {\n ((x1, y1), i) <- chocolates.zipWithIndex\n (x2, y2) <- chocolates drop (i + 1) if x1 == x2 || y1 == y2\n } ans += 1\n ans\n }\n\n override def format(result: Result) = result.toString\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n sc.nextLine()\n\n var cake = new Array[String](n)\n for(i <- 0 until n)\n cake(i) = sc.nextLine()\n\n //\n var ans = BigInt(0)\n\n for(i <- 0 until n){\n val s = cake(i)\n\n var cnt = 0\n for(e <- s)\n if(e == 'C')\n cnt += 1\n\n if(cnt >= 2)\n ans += (cnt * (cnt-1)) / 2\n }\n\n for(i <- 0 until n){\n var cnt = 0\n for(j <- 0 until n)\n if(cake(j)(i) == 'C')\n cnt += 1\n\n if(cnt >= 2)\n ans += (cnt * (cnt-1)) / 2\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "/**\n * Created by aborisenko on 21.02.16.\n */\n\nimport io.StdIn._\n\nobject Main extends App {\n def a629 (){\n val n = readInt()\n var arr: Array[String] = new Array[String](n)\n\n for( i <- 0 to n-1)\n arr(i) = readLine()\n\n var arr1: Array[Long] = Array.fill[Long](n)(0)\n var arr2: Array[Long] = Array.fill[Long](n)(0)\n\n for( i <- 0 to n-1)\n for( j <- 0 to n-1) {\n arr1(i) += (if( arr(i)(j) == 'C') 1 else 0)\n arr2(j) += (if( arr(i)(j) == 'C') 1 else 0)\n }\n\n def f(n: Long): Long = {\n if(n <= 1) 0 else n-1 + f(n-1)\n }\n\n var sum: Long = 0\n\n for( i <- 0 to n-1) {\n sum = f(arr1(i)) + sum\n sum = f(arr2(i)) + sum\n }\n\n println(sum)\n }\n\n a629()\n}\n"}, {"source_code": "\n\nimport java.util.ArrayList\nimport java.util.StringTokenizer\nimport scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject A_343_A { \n var br = createBufferedReader(); var debugV = false\n \n //COMMENT ME !\n runTest(Test.sa2)\n debugV = true\n// file = File(\"C:\\\\temp\\\\google cj\\\\2014q\\\\c-small.res\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading --------------------------\n val n = readLine.int\n val arr = Array.fill(n,n)(0)\n for(i <- 0 until n) {\n val line = readLine.string\n for(j <- 0 until n) {\n arr(i)(j) = if (line(j) == '.') 0 else 1 \n }\n }\n debug(\"n = \" + n)\n \n //---------------------------- parameters reading end ----------------------\n \n var total = 0\n for(i <- 0 until n) {\n var rowCount = 0\n for(j <- 0 until n) {\n if (arr(i)(j) == 1) {\n rowCount += 1\n }\n }\n total += soch(rowCount)\n// total += Subsets.subsetNumber(rowCount, 2)\n }\n \n for(i <- 0 until n) {\n var colCount = 0\n for(j <- 0 until n) {\n if (arr(j)(i) == 1) {\n colCount += 1\n }\n }\n total += soch(colCount)\n// total += Subsets.subsetNumber(colCount, 2)\n }\n \n println(total+\"\")\n }\n \n def soch(all:Int): Int = all - 1 match {\n case x if x < 1 => 0\n case rest => rest + soch(rest)\n }\n \n \n //============================ service code ======================\n\n// var inst = System.in\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n \n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n// inst = new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\"))\n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n3\n.CC\nC..\nC.C\n\"\"\"\n\nval sa2 = \"\"\"\n4\nCC..\nC..C\n.CC.\n.CC.\n\"\"\"\n\n}\n\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n sc.nextLine()\n\n var cake = new Array[String](n)\n for(i <- 0 until n)\n cake(i) = sc.nextLine()\n\n //\n var ans = BigInt(0)\n\n for(i <- 0 until n){\n val s = cake(i)\n\n var cnt = 0\n for(e <- s)\n if(e == 'C')\n cnt += 1\n\n if(cnt >= 2)\n ans += (BigInt(2) to cnt).product / 2\n }\n\n for(i <- 0 until n){\n var cnt = 0\n for(j <- 0 until n)\n if(cake(j)(i) == 'C')\n cnt += 1\n\n if(cnt >= 2)\n ans += (BigInt(2) to cnt).product / 2\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "/**\n * Created by aborisenko on 21.02.16.\n */\n\nimport io.StdIn._\n\nobject Main extends App {\n def a629 (){\n val n = readInt()\n var arr: Array[String] = new Array[String](n)\n\n for( i <- 0 to n-1)\n arr(i) = readLine()\n\n var arr1: Array[Long] = Array.fill[Long](n)(0)\n var arr2: Array[Long] = Array.fill[Long](n)(0)\n\n for( i <- 0 to n-1)\n for( j <- 0 to n-1) {\n if( arr(i)(j) == 'c') {\n arr1(i) += 1\n arr2(j) += 1\n }\n }\n\n def f(n: Long): Long = {\n if(n < 2) 1 else n * f(n-1)\n }\n\n var sum: Long = 0\n\n for( i <- 0 to n-1) {\n sum = (if(arr1(i) < 2) 0 else f(arr1(i) - 1)) + sum\n sum = (if(arr2(i) < 2) 0 else f(arr2(i) - 1)) + sum\n }\n\n println(sum)\n }\n\n a629()\n}\n"}, {"source_code": "/**\n * Created by aborisenko on 21.02.16.\n */\n\nimport io.StdIn._\n\nobject Main extends App {\n def a629 (){\n val n = readInt()\n var arr: Array[String] = new Array[String](n)\n\n for( i <- 0 to n-1)\n arr(i) = readLine()\n\n var arr1: Array[Long] = Array.fill[Long](n)(0)\n var arr2: Array[Long] = Array.fill[Long](n)(0)\n\n for( i <- 0 to n-1)\n for( j <- 0 to n-1) {\n if( arr(i)(j) == 'C') {\n arr1(i) += 1\n arr2(j) += 1\n }\n }\n\n def f(n: Long): Long = {\n if(n < 2) 1 else n * f(n-1)\n }\n\n var sum: Long = 0\n\n for( i <- 0 to n-1) {\n sum = (if(arr1(i) < 2) 0 else f(arr1(i) - 1)) + sum\n sum = (if(arr2(i) < 2) 0 else f(arr2(i) - 1)) + sum\n }\n\n println(sum)\n }\n\n a629()\n}\n"}], "src_uid": "7749f37aa9bf88a00013557e14342952"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next()\n val (f, s, t) = in.next().split(' ').map(_.toInt).sorted.reverse.foldLeft(0, 0, 0) {\n case((a, b, c), el) if a <= b && a <= c => (a + el, b, c)\n case((a, b, c), el) if b <= a && b <= c => (a, b + el, c)\n case((a, b, c), el) if c <= a && c <= b => (a, b, c + el)\n }\n val sorted = List(f, s, t).sorted\n val res = sorted(2) - sorted(1) - sorted(0) + 1\n if (res >= 0)\n println(res)\n else\n println(0)\n}", "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _667B extends CodeForcesApp {\n override def apply(io: IO) = {\n val rods = io[List[Long]].sorted\n val p = rods.scanLeft(0L)(_ + _)\n val s = rods.scanRight(0L)(_ + _)\n val (l, r) = (p zip s) minBy {case (a, b) => (a - b).abs}\n io += (l - r).abs + 1\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[I] = new {\n def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val newLine: String = \"\\n\"\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = this.+=(xs.size).appendNewLine().+=(xs)\n\n def appendNewLine(): this.type = {\n println()\n this\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "f00d94eb37c98a449615f0411e5a3572"} {"source_code": "object D {\n import InOut._\n\n def main(args: Array[String]): Unit = {}\n\n val n, k = nextInt\n val mn = nextInts(n).sorted(Ordering.Int.reverse)\n val ck = nextInts(k)\n\n val (ans, _, _) = ck.reverse.zipWithIndex\n .foldLeft((0, 0, 0d)) {\n case ((b, j, g), (c, i)) =>\n var t = mn.indexWhere(_ < (k - i), j)\n if (t < 0) t = n\n\n val h = g + t - j\n\n (b max math.ceil(h / c).toInt, t, h)\n }\n\n val kv = collection.mutable.Map.empty[Int, List[Int]]\n\n mn.zipWithIndex.foreach {\n case (m, i) =>\n val k = i % ans\n val v = m :: kv.getOrElse(k, Nil)\n\n kv += (k -> v)\n }\n\n out.println(ans)\n kv.foreach {\n case (_, vs) =>\n out.println(s\"${vs.length} ${vs.mkString(\" \")}\")\n }\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n)(nextInt)\n def nextLongs(n: Int) = Array.fill(n)(nextLong)\n def nextBigs(n: Int) = Array.fill(n)(nextBig)\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject D {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n, k = nextInt\n val ms = nextInts(n)\n val cs = nextInts(k)\n\n val lastBigger = mutable.Map.empty[Int, Int]\n var prev = -1\n var prevM = -1\n for (i <- 0 until k) {\n if (prev != cs(i)) {\n prev = cs(i)\n prevM = i\n }\n lastBigger(i) = prevM\n }\n\n val counts = new java.util.TreeMap[Int, Int]\n for (m <- ms) {\n counts.put(m, counts.getOrDefault(m, 0) + 1)\n }\n\n var resBuilders = mutable.ArrayBuffer.empty[mutable.ArrayBuilder.ofInt]\n while (!counts.isEmpty) {\n resBuilders += new mutable.ArrayBuilder.ofInt\n var lim = Int.MaxValue\n val it = counts.keySet().iterator\n //val removeBuilder = new mutable.ArrayBuilder.ofInt\n var used = 0\n var current = counts.lastKey()\n while (current > 0) {\n val value = counts.get(current)\n lim = cs(current - 1) - used\n if (lim > 0) {\n val take = value min lim\n used += take\n if (value == take) {\n counts.remove(current)\n } else {\n counts.put(current, value - take)\n }\n var i = 0\n while (i < take) {\n resBuilders.last += current\n i += 1\n }\n current = counts.lowerKey(current)\n } else {\n current = lastBigger(current)\n }\n }\n// var i = 0\n// val remove = removeBuilder.result()\n// while (i < remove.length) {\n// counts.remove(remove(i))\n// i += 1\n// }\n }\n\n val res = resBuilders.map(_.result())\n\n out.println(res.size)\n res.foreach { r =>\n out.print(r.length)\n out.println(r.mkString(\" \", \" \", \"\"))\n }\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\nobject D {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n val n, k = nextInt\n val ms = nextInts(n)\n val cs = nextInts(k)\n\n val counts = mutable.TreeMap.empty[Int, Int].withDefaultValue(0)\n for (m <- ms) {\n counts(m) += 1\n }\n\n var resBuilders = mutable.ArrayBuffer.empty[mutable.ArrayBuilder.ofInt]\n while (counts.nonEmpty) {\n resBuilders += new mutable.ArrayBuilder.ofInt\n var lim = Int.MaxValue\n val it = counts.iterator\n val removeBuilder = new mutable.ArrayBuilder.ofInt\n while (it.hasNext && lim > 0) {\n val (key, value) = it.next()\n lim = lim min cs(key - 1)\n val take = value min lim\n counts(key) -= take\n if (value == take) {\n removeBuilder += key\n }\n var i = 0\n while (i < take) {\n resBuilders.last += key\n i += 1\n }\n lim -= take\n }\n val remove = removeBuilder.result()\n for (r <- remove) {\n counts.remove(r)\n }\n }\n\n val res = resBuilders.map(_.result())\n\n out.println(res.size)\n res.foreach { r =>\n out.print(r.length)\n out.println(r.mkString(\" \", \" \", \"\"))\n }\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n, k = nextInt\n val ms = nextInts(n)\n val cs = nextInts(k)\n\n val counts = mutable.TreeMap.empty[Int, Int].withDefaultValue(0)\n for (m <- ms) {\n counts(m) += 1\n }\n\n var resBuilders = mutable.ArrayBuffer.empty[mutable.ArrayBuilder.ofInt]\n while (counts.nonEmpty) {\n resBuilders += new mutable.ArrayBuilder.ofInt\n var lim = Int.MaxValue\n val it = counts.iterator\n val updates = mutable.ArrayBuffer.empty[(Int, Int)]\n while (it.hasNext && lim > 0) {\n val (key, value) = it.next()\n lim = lim min cs(key - 1)\n val take = value min lim\n counts(key) -= take\n updates += ((key, value - take))\n var i = 0\n while (i < take) {\n resBuilders.last += key\n i += 1\n }\n lim -= take\n }\n for ((k, v) <- updates) {\n if (v == 0) {\n counts.remove(k)\n } else {\n counts(k) = v\n }\n }\n }\n\n val res = resBuilders.map(_.result())\n\n out.println(res.size)\n res.foreach { r =>\n out.print(r.length)\n out.println(r.mkString(\" \", \" \", \"\"))\n }\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}"}, {"source_code": "object D extends App {\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val mn = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted(Ordering.Int.reverse)\n val ck = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ans = ck.reverse.zipWithIndex\n .foldLeft((mn, 0d, 0)) {\n case ((mn, g, b), (c, i)) =>\n val mm = mn.dropWhile(_ >= (k - i))\n val t = g + mn.length - mm.length\n\n (mm, t, b.max((t / c).toInt))\n }\n ._3\n\n val kv = collection.mutable.Map.empty[Int, List[Int]]\n\n mn.zipWithIndex.foreach {\n case (m, i) =>\n val k = i % ans\n val v = m :: kv.getOrElse(k, Nil)\n\n kv += (k -> v)\n }\n\n println(ans)\n\n kv.foreach {\n case (_, vs) =>\n println(s\"${vs.length} ${vs.mkString(\" \")}\")\n }\n}\n"}, {"source_code": "object D {\n import InOut._\n\n def main(args: Array[String]): Unit = {}\n\n val n, k = nextInt\n val mn = nextInts(n).sorted(Ordering.Int.reverse)\n val ck = nextInts(k)\n\n val (ans, _, _) = ck.reverse.zipWithIndex\n .foldLeft((0, 0, 0d)) {\n case ((b, j, g), (c, i)) =>\n val t = mn.indexWhere(_ < (k - i), j)\n\n val h = g + (if (t < 0) n - j else t - j)\n\n (b max math.ceil(h / c).toInt, t, h)\n }\n\n val kv = collection.mutable.Map.empty[Int, List[Int]]\n\n mn.zipWithIndex.foreach {\n case (m, i) =>\n val k = i % ans\n val v = m :: kv.getOrElse(k, Nil)\n\n kv += (k -> v)\n }\n\n out.println(ans)\n kv.foreach {\n case (_, vs) =>\n out.println(s\"${vs.length} ${vs.mkString(\" \")}\")\n }\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n)(nextInt)\n def nextLongs(n: Int) = Array.fill(n)(nextLong)\n def nextBigs(n: Int) = Array.fill(n)(nextBig)\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object D extends App {\n\n private def greater(mn: List[Int], k: Int): List[Int] = {\n @scala.annotation.tailrec\n def go(mn: List[Int], i: Int, gk: List[Int]): List[Int] =\n if (i == 0) gk\n else {\n val mm = mn.dropWhile(_ >= i)\n val g = gk.head + (mn.length - mm.length)\n\n go(mm, i - 1, g :: gk)\n }\n\n go(mn, k, List(0))\n }\n\n private def boxes(ck: Seq[Int], gk: Seq[Int]): Int = {\n @scala.annotation.tailrec\n def go(ck: Seq[Int], gk: Seq[Int], b: Int): Int =\n ck match {\n case Seq() => b\n case _ => go(ck.tail, gk.tail, b.max(math.ceil(gk.head.toDouble / ck.head).toInt))\n }\n\n go(ck, gk, 0)\n }\n\n private def put(mn: List[Int], b: Int): collection.mutable.Map[Int, List[Int]] = {\n val kv = collection.mutable.Map.empty[Int, List[Int]]\n\n mn.zipWithIndex.foreach {\n case (m, i) =>\n val k = i % b\n val v = m :: kv.getOrElse(k, Nil)\n\n kv += (k -> v)\n }\n\n kv\n }\n\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val mn = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted(Ordering.Int.reverse).toList\n val ck = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val gk = greater(mn, k)\n\n println(s\"gk: ${gk.mkString(\" \")}\")\n println(s\"ck: ${ck.mkString(\" \")}\")\n\n val b = boxes(ck, gk)\n\n val ans = put(mn, b).values.toList\n\n println(ans.length)\n ans.foreach(t => println(s\"${t.length} ${t.mkString(\" \")}\"))\n}\n"}, {"source_code": "object D {\n import InOut._\n\n def main(args: Array[String]): Unit = {}\n\n val n, k = nextInt\n val mn = nextInts(n)\n val ck = nextInts(k)\n\n val ans = ck.reverse.zipWithIndex\n .foldLeft((mn, 0d, 0)) {\n case ((mn, g, b), (c, i)) =>\n val mm = mn.dropWhile(_ >= (k - i))\n val t = g + mn.length - mm.length\n\n (mm, t, b.max(math.ceil(t / c.toInt).toInt))\n }\n ._3\n\n val kv = collection.mutable.Map.empty[Int, List[Int]]\n\n mn.zipWithIndex.foreach {\n case (m, i) =>\n val k = i % ans\n val v = m :: kv.getOrElse(k, Nil)\n\n kv += (k -> v)\n }\n\n out.println(ans)\n kv.foreach {\n case (_, vs) =>\n out.println(s\"${vs.length} ${vs.mkString(\" \")}\")\n }\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n)(nextInt)\n def nextLongs(n: Int) = Array.fill(n)(nextLong)\n def nextBigs(n: Int) = Array.fill(n)(nextBig)\n def nextLine = in.readLine\n }\n}\n"}], "src_uid": "5802f9c010efd1cdcee2fbbb4039a4cb"} {"source_code": "import java.io._\nimport java.util\nimport java.util._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n class MultiTreeSet[T <: Comparable[T]] {\n val map = new util.TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val w = nextInt\n val h = nextInt\n val n = nextInt\n val hor = new TreeSet[Int]()\n val vert = new TreeSet[Int]()\n val hCuts = new MultiTreeSet[Integer]\n val vCuts = new MultiTreeSet[Integer]\n hCuts.add(h)\n vCuts.add(w)\n hor.add(0)\n hor.add(h)\n vert.add(0)\n vert.add(w)\n for (i <- 0 until n) {\n val dir = next.toCharArray.apply(0)\n if (dir == 'H') {\n val pos = h - nextInt\n val lo = hor.lower(pos)\n val hi = hor.higher(pos)\n hCuts.remove(hi - lo)\n hCuts.add(hi - pos)\n hCuts.add(pos - lo)\n hor.add(pos)\n } else {\n val pos = nextInt\n val lo = vert.lower(pos)\n val hi = vert.higher(pos)\n vCuts.remove(hi - lo)\n vCuts.add(hi - pos)\n vCuts.add(pos - lo)\n vert.add(pos)\n }\n out.println(vCuts.last().toLong * hCuts.last().toLong)\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util\nimport java.util._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n class MultiTreeSet[T <: Comparable[T]] {\n val map = new util.TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val w = nextInt\n val h = nextInt\n val n = nextInt\n val hor = new TreeSet[Int]()\n val vert = new TreeSet[Int]()\n val hCuts = new MultiTreeSet[Integer]\n val vCuts = new MultiTreeSet[Integer]\n hCuts.add(h)\n vCuts.add(w)\n hor.add(0)\n hor.add(h)\n vert.add(0)\n vert.add(w)\n for (i <- 0 until n) {\n val dir = next.toCharArray.apply(0)\n if (dir == 'H') {\n val pos = h - nextInt\n val lo = hor.lower(pos)\n val hi = hor.higher(pos)\n hCuts.remove(hi - lo)\n hCuts.add(hi - pos)\n hCuts.add(pos - lo)\n hor.add(pos)\n } else {\n val pos = nextInt\n val lo = vert.lower(pos)\n val hi = vert.higher(pos)\n vCuts.remove(hi - lo)\n vCuts.add(hi - pos)\n vCuts.add(pos - lo)\n vert.add(pos)\n }\n out.println(vCuts.last().toLong * hCuts.last().toLong)\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "negative_code": [{"source_code": "\nimport java.io._\nimport java.util\nimport java.util._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n class MultiTreeSet[T <: Comparable[T]] {\n val map = new util.TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val w = nextInt\n val h = nextInt\n val n = nextInt\n val hor = new TreeSet[Int]()\n val vert = new TreeSet[Int]()\n val hCuts = new MultiTreeSet[Integer]\n val vCuts = new MultiTreeSet[Integer]\n hCuts.add(h)\n vCuts.add(w)\n hor.add(0)\n hor.add(h)\n vert.add(0)\n vert.add(w)\n for (i <- 0 until n) {\n val dir = next.toCharArray.apply(0)\n if (dir == 'H') {\n val pos = h - nextInt\n val lo = hor.lower(pos)\n val hi = hor.higher(pos)\n hCuts.remove(hi - lo)\n hCuts.add(hi - pos)\n hCuts.add(pos - lo)\n hor.add(pos)\n } else {\n val pos = nextInt\n val lo = vert.lower(pos)\n val hi = vert.higher(pos)\n vCuts.remove(hi - lo)\n vCuts.add(hi - pos)\n vCuts.add(pos - lo)\n vert.add(pos)\n }\n out.println(vCuts.last() * hCuts.last())\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "src_uid": "11057f672524244f893493bc10218cbf"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = nl()\n val x = (K - 1) / N + 1\n\n out.println(x)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Problem1036a {\n def main(args: Array[String]): Unit = {\n val vals = StdIn.readLine().split(\" \").map(_.toLong)\n val n = vals(0)\n val k = vals(1)\n\n println(solve(n, k))\n }\n\n def solve(n: Long, k: Long): Long = {\n (k - 1) / n + 1\n }\n}\n"}, {"source_code": "object Main {\nimport java.io._\nimport java.util.Scanner\n\nimport collection.mutable.HashMap\nimport scala.collection.{SortedSet, mutable}\nimport scala.util.Random\n protected val EPS = 1e-11\n\n private def default = (\n new StreamTokenizer(new InputStreamReader(System.in)),\n new Scanner(System.in),\n new PrintWriter(System.out)\n )\n\n val (in, ins, out) = {\n try {\n if (sys.props.contains(\"xDx\")) {\n (\n new StreamTokenizer(new FileReader(\"input.txt\")),\n new Scanner(new FileReader(\"input.txt\")),\n new PrintWriter(new FileWriter(\"output.txt\"))\n )\n } else {\n default\n }\n } catch {\n case _: Throwable => default\n }\n }\n\n private def nextInt = {\n in.nextToken\n in.nval.toInt\n }\n\n private def nextLong = {\n in.nextToken\n in.nval.toLong\n }\n\n\n private def nextDouble = {\n in.nextToken\n in.nval\n }\n\n\n private def nextString = {\n in.nextToken\n in.sval\n }\n\n private def nextChar = {\n in.nextToken\n in.ttype.toChar\n }\n\n def main(args: Array[String]): Unit = {\n try {\n new Run().run()\n } catch {\n case e: Throwable =>\n throw new RuntimeException(e)\n } finally out.close()\n }\n\n class Run {\n import collection.breakOut\n def run(): Unit = {\n val n = ins.nextLong\n val k = ins.nextLong\n println((k + n - 1)/n)\n }\n\n }\n\n}\n\n\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject Problem1036a {\n def main(args: Array[String]): Unit = {\n val vals = StdIn.readLine().split(\" \").map(_.toInt)\n val n = vals(0)\n val k = vals(1)\n println(k / n)\n }\n}\n"}], "src_uid": "31014efa929af5e4b7d9987bd9b59918"} {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val Array(characterHealth, characterDamage) = readLongs().map(BigInt(_))\n val Array(monsterHealth, monsterDamage) = readLongs().map(BigInt(_))\n val Array(coins, weaponBonus, armourBonus) = readLongs().map(BigInt(_))\n\n def remainingLifeWithBonuses(weaponCoins: BigInt): BigInt =\n remainingLife(\n characterHealth + (coins - weaponCoins) * armourBonus,\n characterDamage + weaponCoins * weaponBonus\n )\n\n def remainingLife(characterHealth: BigInt, characterDamage: BigInt): BigInt = {\n val roundNumber = (monsterHealth-1) / characterDamage + 1\n val answer = characterHealth - (roundNumber - 1) * monsterDamage\n answer\n }\n\n val answer = 0.to(coins.toInt).map(c => remainingLifeWithBonuses(c) > 0).reduce(_ || _)\n if (answer) println(\"YES\") else println(\"NO\")\n\n }\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n", "positive_code": [{"source_code": "object KillTheMonsters extends App {\r\ndef count(hc: Long, dc: Long, hm: Long, dm: Long, k: Long, w: Long, a: Long): String =\r\n if ((0L to k).exists{ na => (1.0 * hm / (dc + na * w)).ceil <= (1.0 * (hc + (k - na) * a) / dm).ceil }) \"YES\" else \"NO\"\r\n \r\n val lines = io.Source.stdin.getLines\r\n val t = lines.next.toInt\r\n (1 to t).foreach{_ =>\r\n val fl = lines.next.split(\" \")\r\n val hc = fl(0).toLong\r\n val dc = fl(1).toLong\r\n val sl = lines.next.split(\" \")\r\n val hm = sl(0).toLong\r\n val dm = sl(1).toLong\r\n val tl = lines.next.split(\" \")\r\n val k = tl(0).toLong\r\n val w = tl(1).toLong\r\n val a = tl(2).toLong\r\n println(count(hc, dc, hm, dm, k, w, a))\r\n }\r\n}"}, {"source_code": "import scala.io.StdIn.readInt\r\nimport scala.io.StdIn.readLine\r\nimport scala.math._, BigDecimal._\r\n\r\nobject cf1633c {\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt()\r\n while(t > 0) {\r\n t -= 1\r\n var Array(hC, dC) = readLine.split(\" \").map(BigInt(_))\r\n var Array(hM, dM) = readLine.split(\" \").map(BigInt(_))\r\n var Array(k, w, a) = readLine.split(\" \").map(BigInt(_))\r\n var possible = false\r\n for(K <- BigInt(0) to k) {\r\n if(check(hC + K * a, dC + (k - K) * w, hM, dM)) {\r\n possible = true\r\n }\r\n }\r\n if(possible == true) {\r\n println(\"YES\")\r\n }\r\n else {\r\n println(\"NO\")\r\n }\r\n }\r\n }\r\n\r\n def check(hC: BigInt, dC: BigInt, hM: BigInt, dM: BigInt): Boolean = {\r\n var req_t = (BigDecimal(hM) / BigDecimal(dC)).setScale(0, RoundingMode.CEILING)\r\n if(BigDecimal(hC) > BigDecimal(dM) * (req_t - 1)) {\r\n return true\r\n }\r\n return false\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object KillTheMonsters extends App {\r\n def count(hc: Int, dc: Int, hm: Int, dm: Int, k: Int, w: Int, a: Int): String =\r\n if ((0 to k).exists(na => hm / (dc + na * w) - 1 < (hc + (k - na) * a) / dm)) \"YES\" else \"NO\"\r\n \r\n val lines = io.Source.stdin.getLines\r\n val t = lines.next.toInt\r\n (1 to t).foreach{_ =>\r\n val fl = lines.next.split(\" \")\r\n val hc = fl(0).toInt\r\n val dc = fl(1).toInt\r\n val sl = lines.next.split(\" \")\r\n val hm = sl(0).toInt\r\n val dm = sl(1).toInt\r\n val tl = lines.next.split(\" \")\r\n val k = tl(0).toInt\r\n val w = tl(1).toInt\r\n val a = tl(2).toInt\r\n println(count(hc, dc, hm, dm, k, w, a))\r\n }\r\n}\r\n"}, {"source_code": "object KillTheMonsters extends App {\r\n def count(hc: Int, dc: Int, hm: Int, dm: Int, k: Int, w: Int, a: Int): String =\r\n if ((0 to k).exists(na => hm / (dc + na * w) < 1 + (hc + (k - na) * a) / dm)) \"YES\" else \"NO\"\r\n \r\n val lines = io.Source.stdin.getLines\r\n val t = lines.next.toInt\r\n (1 to t).foreach{_ =>\r\n val fl = lines.next.split(\" \")\r\n val hc = fl(0).toInt\r\n val dc = fl(1).toInt\r\n val sl = lines.next.split(\" \")\r\n val hm = sl(0).toInt\r\n val dm = sl(1).toInt\r\n val tl = lines.next.split(\" \")\r\n val k = tl(0).toInt\r\n val w = tl(1).toInt\r\n val a = tl(2).toInt\r\n println(count(hc, dc, hm, dm, k, w, a))\r\n }\r\n}\r\n"}, {"source_code": "object KillTheMonsters extends App {\r\n def count(hc: Int, dc: Int, hm: Int, dm: Int, k: Int, w: Int, a: Int): String =\r\n if ((0 to k).exists(na => hm / (dc + na * w) + 1 <= (hc + (k - na) * a) / dm)) \"YES\" else \"NO\"\r\n\r\n val lines = io.Source.stdin.getLines\r\n val t = lines.next.toInt\r\n (1 to t).foreach{_ =>\r\n val fl = lines.next.split(\" \")\r\n val hc = fl(0).toInt\r\n val dc = fl(1).toInt\r\n val sl = lines.next.split(\" \")\r\n val hm = sl(0).toInt\r\n val dm = sl(1).toInt\r\n val tl = lines.next.split(\" \")\r\n val k = tl(0).toInt\r\n val w = tl(1).toInt\r\n val a = tl(2).toInt\r\n println(count(hc, dc, hm, dm, k, w, a))\r\n }\r\n}"}, {"source_code": "object KillTheMonsters extends App {\r\n def count(hc: Int, dc: Int, hm: Int, dm: Int, k: Int, w: Int, a: Int): String =\r\n if ((0 to k).exists(na => hm / (dc + na * w) <= (hc + (k - na) * a) / dm)) \"YES\" else \"NO\"\r\n\r\n val lines = io.Source.stdin.getLines\r\n val t = lines.next.toInt\r\n (1 to t).foreach{_ =>\r\n val fl = lines.next.split(\" \")\r\n val hc = fl(0).toInt\r\n val dc = fl(1).toInt\r\n val sl = lines.next.split(\" \")\r\n val hm = sl(0).toInt\r\n val dm = sl(1).toInt\r\n val tl = lines.next.split(\" \")\r\n val k = tl(0).toInt\r\n val w = tl(1).toInt\r\n val a = tl(2).toInt\r\n println(count(hc, dc, hm, dm, k, w, a))\r\n }\r\n}"}, {"source_code": "import scala.io.StdIn.readInt\r\nimport scala.io.StdIn.readLine\r\n\r\nobject cf1633c {\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt()\r\n while(t > 0) {\r\n t -= 1\r\n var Array(hC, dC) = readLine.split(\" \").map(BigInt(_))\r\n var Array(hM, dM) = readLine.split(\" \").map(BigInt(_))\r\n var Array(k, w, a) = readLine.split(\" \").map(BigInt(_))\r\n var possible = false\r\n for(K <- BigInt(0) to k) {\r\n if(check(hC + K * a, dC + (k - K) * w, hM, dM)) {\r\n possible = true\r\n }\r\n }\r\n if(possible == true) {\r\n println(\"YES\")\r\n }\r\n else {\r\n println(\"NO\")\r\n }\r\n }\r\n }\r\n\r\n def check(hC: BigInt, dC: BigInt, hM: BigInt, dM: BigInt): Boolean = {\r\n var req_t = (hM.toFloat / dC.toFloat).ceil\r\n if(hC.toFloat > dM.toFloat * (req_t - 1)) {\r\n return true\r\n }\r\n return false\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn.readInt\r\nimport scala.io.StdIn.readLine\r\n\r\nobject cf1633c {\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt()\r\n println(t)\r\n while(t > 0) {\r\n t -= 1\r\n var Array(hC, dC) = readLine().split(\" \").map(_.toInt)\r\n var Array(hM, dM) = readLine().split(\" \").map(_.toInt)\r\n var Array(k, w, a) = readLine().split(\" \").map(_.toInt)\r\n var possible = false\r\n for(K <- 0 to k) {\r\n println(K)\r\n if(check(hC + K * a, dC + (k - K) * w, hM, dM)) {\r\n possible = true\r\n }\r\n }\r\n if(possible == true) {\r\n println(\"YES\")\r\n }\r\n else {\r\n println(\"NO\")\r\n }\r\n\r\n }\r\n }\r\n\r\n def check(hC: Int, dC: Int, hM: Int, dM: Int): Boolean = {\r\n var req_t = (hM*1.0 / dC).ceil\r\n if(hC > dM * (req_t - 1)) {\r\n return true\r\n }\r\n return false\r\n }\r\n}\r\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val Array(characterHealth, characterDamage) = readLongs().map(BigInt(_))\n val Array(monsterHealth, monsterDamage) = readLongs().map(BigInt(_))\n val Array(coins, weaponBonus, armourBonus) = readLongs().map(BigInt(_))\n\n def remainingLifeWithBonuses(weaponCoins: BigInt): BigInt =\n remainingLife(\n characterHealth + (coins - weaponCoins) * armourBonus,\n characterDamage + weaponCoins * weaponBonus\n )\n\n def remainingLife(characterHealth: BigInt, characterDamage: BigInt): BigInt = {\n val roundNumber = (monsterHealth-1) / characterDamage + 1\n val answer = characterHealth - (roundNumber - 1) * monsterDamage\n answer\n }\n\n def search(l: BigInt, r: BigInt): Boolean =\n if (r - l <= 1) remainingLifeWithBonuses(l) > 0 || remainingLifeWithBonuses(r) > 0\n else {\n val medium = (r + l) / 2\n if (remainingLifeWithBonuses(medium - 1) > remainingLifeWithBonuses(medium + 1)) {\n search(l, medium)\n } else {\n search(medium, r)\n }\n }\n\n val answer = search(0, coins)\n if (answer) println(\"YES\") else println(\"NO\")\n\n }\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val Array(characterHealth, characterDamage) = readLongs()\n val Array(monsterHealth, monsterDamage) = readLongs()\n val Array(coins, weaponBonus, armourBonus) = readLongs()\n\n def remainingLifeWithBonuses(weaponCoins: Long): Long =\n remainingLife(\n characterHealth + (coins - weaponCoins) * armourBonus,\n characterDamage + weaponCoins * weaponBonus\n )\n\n def remainingLife(characterHealth: Long, characterDamage: Long): Long = {\n val roundNumber = (monsterHealth-1) / characterDamage + 1\n val answer = characterHealth - (roundNumber - 1) * monsterDamage\n answer\n }\n\n def search(l: Long, r: Long): Boolean =\n if (r - l <= 1) remainingLifeWithBonuses(l) > 0 || remainingLifeWithBonuses(r) > 0\n else {\n val medium = (r + l) / 2\n if (remainingLifeWithBonuses(medium - 1) > remainingLifeWithBonuses(medium + 1)) {\n search(l, medium)\n } else {\n search(medium, r)\n }\n }\n\n val answer = search(0, coins)\n if (answer) println(\"YES\") else println(\"NO\")\n\n }\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}], "src_uid": "5b1f33228a58d9e14bc9479767532c25"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CVK17A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CVK17A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val m = ni()\n\n g = Array.fill[ListBuffer[Int]](n)(new ListBuffer[Int]())\n\n REP(m) { _ =>\n val u = ni()\n val v = ni()\n\n g(u-1) += v-1\n g(v-1) += u-1\n }\n\n marked = Array.fill[Int](n)(-1)\n var id = 0\n var yes = true\n var prev = 0\n REP(n) { i =>\n if(marked(i) == -1) {\n marked(i) = id\n counter +=1\n val x = countEdges(i)\n val y = (counter - prev).toLong\n// out.println(i + \" \" + x + \" \" + y + \" \" + i + \" \" + (y * (y-1)))\n yes = yes & (x == (y * (y-1)))\n id += 1\n prev = counter\n }\n }\n if(yes) {\n out.println(\"YES\")\n } else out.println(\"NO\")\n }\n\n var g: Array[ListBuffer[Int]] = _\n var marked: Array[Int] = _\n var counter = 0\n\n def countEdges(u: Int): Long = {\n var stack = List.empty[Int]\n stack = u :: stack\n var count = 0L\n while (stack.nonEmpty) {\n val v = stack.head\n stack = stack.drop(1)\n count += g(v).size\n g(v).foreach { f =>\n if (marked(f) == -1) {\n marked(f) = marked(v)\n counter += 1\n stack = f :: stack\n }\n }\n }\n count\n }\n}\n", "positive_code": [{"source_code": "//package solutions\n\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\nimport scala.util.control.Breaks\n\n/**\n * @author traff\n */\n\n\nobject SolTaskB extends App {\n override def main(args: Array[String]): Unit = {\n val out = new PrintWriter(System.out)\n\n run(new Scanner(System.in), out)\n\n out.close()\n }\n\n\n def run(s: Scanner, out: PrintWriter): Unit = {\n val n = s.nextInt()\n val m = s.nextInt()\n\n var t: Array[Int] = (0 until n).toArray\n\n var rank: Array[Int] = Array.fill(n)(1)\n\n def find(i: Int): Int = {\n if (i == t(i)) {\n i\n } else {\n t(i) = find(t(i))\n t(i)\n }\n }\n\n def union(i: Int, j: Int): Unit = {\n if (rank(i) > rank(j)) {\n t(i) = t(j)\n rank(i) += rank(j)\n } else {\n t(j) = t(i)\n rank(j) += rank(i)\n }\n }\n\n val c = Array.fill(n + 1)(0)\n\n\n for (i <- 1 to m) {\n var a = s.nextInt()\n var b = s.nextInt()\n\n if (b > a) {\n val t = a\n a = b\n b = t\n }\n\n\n if (find(a - 1) != find(b - 1)) {\n union(find(a - 1), find(b - 1))\n }\n\n c(a) += 1\n c(b) += 1\n }\n\n var cnt = Array.fill(n)(0)\n\n for (i <- 1 to n) {\n cnt(find(i-1)) += 1\n }\n\n Breaks.breakable {\n for (i <- 1 to n) {\n if (c(i) != (cnt(find(i-1)) - 1)) {\n out.write(\"NO\")\n Breaks.break()\n }\n }\n\n out.write(\"YES\")\n }\n }\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CVK17A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CVK17A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val m = ni()\n\n g = Array.fill[ListBuffer[Int]](n)(new ListBuffer[Int]())\n\n REP(m) { _ =>\n val u = ni()\n val v = ni()\n\n g(u-1) += v-1\n g(v-1) += u-1\n }\n\n marked = Array.fill[Int](n)(-1)\n var id = 0\n var yes = true\n var prev = 0\n REP(n) { i =>\n if(marked(i) == -1) {\n marked(i) = id\n counter +=1\n val x = countEdges(i)\n val y = (counter - prev).toLong\n// out.println(x + \" \" + y + \" \" + i + \" \" + (y * (y-1)))\n yes = yes & (x == (y * (y-1)))\n id += 1\n prev = counter\n }\n }\n if(yes) {\n out.println(\"YES\")\n } else out.println(\"NO\")\n }\n\n var g: Array[ListBuffer[Int]] = _\n var marked: Array[Int] = _\n var counter = 0\n\n def countEdges(u: Int): Long = {\n var stack = List.empty[Int]\n stack = u :: stack\n var count = 0L\n while (stack.nonEmpty) {\n val v = stack.head\n stack = stack.drop(1)\n count += g(u).size\n g(v).foreach { f =>\n if (marked(f) == -1) {\n marked(f) = marked(v)\n counter += 1\n stack = f :: stack\n }\n }\n }\n count\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable.ListBuffer\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CVK17A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CVK17A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val m = ni()\n\n g = Array.fill[ListBuffer[Int]](n)(new ListBuffer[Int]())\n\n REP(m) { _ =>\n val u = ni()\n val v = ni()\n\n g(u-1) += v-1\n g(v-1) += u-1\n }\n\n marked = Array.fill[Int](n)(-1)\n var id = 0\n var yes = true\n var prev = 0\n REP(n) { i =>\n if(marked(i) == -1) {\n marked(i) = id\n counter +=1\n val x = countEdges(i)\n val y = counter - prev\n// out.println(x + \" \" + y + \" \" + i + \" \" + (y * (y-1)))\n yes = yes & (x == (y * (y-1)))\n id += 1\n prev = counter\n }\n }\n if(yes) {\n out.println(\"YES\")\n } else out.println(\"NO\")\n }\n\n var g: Array[ListBuffer[Int]] = _\n var marked: Array[Int] = _\n var counter = 0\n\n def countEdges(u: Int): Int = {\n var count = g(u).size\n g(u).foreach { f =>\n if(marked(f) == -1) {\n counter += 1\n marked(f) = marked(u)\n count += countEdges(f)\n }\n }\n count\n }\n}\n"}], "src_uid": "1173d89dd3af27b46e579cdeb2cfdfe5"} {"source_code": "\n\nimport java.io._\nimport java.util.InputMismatchException\n\nimport scala.annotation.tailrec\n\nobject Codeforces_Scala{\n def main(args: Array[String]) {\n val scan = new FasterScanner();\n val out: PrintWriter = new PrintWriter(System.out)\n\n val n:Int = scan.nextInt\n val k:Int = scan.nextInt\n\n val segments:Array[(Int, Int)] = new Array[(Int, Int)](2*n)\n for(i <- 0 until n){\n val x:Int = i*2\n val y:Int = i*2 + 1\n segments(x) = (scan.nextInt*2,1)\n segments(y) = (scan.nextInt*2+1,-1)\n }\n\n //segments.foreach(p=>println(p._1+\" \"+p._2))\n val sortedSeg = segments.sortBy(e=>e._1)\n //sortedSeg.foreach(p=>println(p._1/2+\" \"+p._2))\n /*\n val proSeg = Process(sortedSeg,0,0,k,Nil,Nil)\n out.println(proSeg.length)\n proSeg.foreach(e=>out.println(e._1+\" \"+e._2))\n out.flush()\n out.close()\n */\n Run(sortedSeg,n,k,out)\n }\n\n def Run(sortedSeg: Array[(Int, Int)],n:Int,k:Int,out: PrintWriter): Unit ={\n var kk: Int = 0\n var resN: Int = 0\n var i: Int = 0\n val res:Array[Int] = new Array[Int](n*2)\n while (i < 2 * n) {\n {\n kk += sortedSeg(i)._2\n if (kk >= k) {\n res(resN*2) = sortedSeg(i)._1/2\n while (kk >= k) {\n i += 1\n kk += sortedSeg(i)._2\n }\n res(resN*2+1) = (sortedSeg(i)._1-1)/2\n resN += 1\n }\n }\n i += 1\n }\n out.println(resN)\n for( i <- 0 until resN){\n out.println(res(i*2)+\" \"+res(i*2+1))\n }\n out.close()\n }\n //Nothing: 所有类型的子类\n //Nil: 空的List即List[Nothing]\n //Null: 引用的空值\n //None: 空的object\n @tailrec\n def Process(seg: List[(Int,Int)], len:Int, k:Int, K:Int, p:List[Int], resList:List[(Int, Int)]) :List[(Int, Int)] = {\n if(len>=seg.length){\n resList\n }else{\n val x = seg(len)\n val kk = k+x._2\n if(kk>=K && p == Nil){\n Process(seg,len+1,kk,K,List(x._1),resList)\n }else if(kk= numChars) {\n curChar = 0\n try {\n numChars = System.in.read(buf)\n }\n catch {\n case e: IOException =>\n throw new InputMismatchException\n }\n if (numChars <= 0) return -1\n }\n buf({curChar += 1; curChar - 1}) //相当于buf[curChar++]\n }\n\n def nextLine: String = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n val res: StringBuilder = new StringBuilder\n do {\n res.append(c)\n c = read\n } while (!isEndOfLine(c))\n res.toString\n }\n\n def nextString: String = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n val res: StringBuilder = new StringBuilder\n do {\n res.append(c)\n c = read\n } while (!isSpaceChar(c))\n res.toString\n }\n\n def nextLong: Long = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n var sgn: Int = 1\n if (c == '-') {\n sgn = -1\n c = read\n }\n var res: Long = 0\n do {\n if (c < '0' || c > '9') throw new InputMismatchException\n res *= 10\n res += c - '0'\n c = read\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextInt: Int = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n var sgn: Int = 1\n if (c == '-') {\n sgn = -1\n c = read\n }\n var res: Int = 0\n do {\n if (c < '0' || c > '9') throw new InputMismatchException\n res *= 10\n res += c - '0'\n c = read\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextIntArray(n: Int): Array[Int] = {\n val arr: Array[Int] = new Array[Int](n)\n for(i <- 0 until n){\n arr(i) = nextInt\n }\n arr\n }\n\n def nextLongArray(n: Int): Array[Long] = {\n val arr: Array[Long] = new Array[Long](n)\n for(i <- 0 until n){\n arr(i) = nextLong\n }\n arr\n }\n\n private def isSpaceChar(c: Int): Boolean = {\n c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n }\n\n private def isEndOfLine(c: Int): Boolean = {\n c == '\\n' || c == '\\r' || c == -1\n }\n }\n}", "positive_code": [{"source_code": "\n\nimport java.io.PrintWriter\nimport java.io.IOException\nimport java.util.InputMismatchException\nimport scala.annotation.tailrec\n\nobject Main {\n def main(args: Array[String]) {\n val scan = new FasterScanner();\n val out: PrintWriter = new PrintWriter(System.out)\n\n val n:Int = scan.nextInt\n val k:Int = scan.nextInt\n\n val segments:Array[(Int, Int)] = new Array[(Int, Int)](2*n)\n for(i <- 0 until n){\n val x:Int = i*2\n val y:Int = i*2 + 1\n segments(x) = (scan.nextInt*2,1)\n segments(y) = (scan.nextInt*2+1,-1)\n }\n\n //segments.foreach(p=>println(p._1+\" \"+p._2))\n val sortedSeg = segments.sortBy(e=>e._1)\n //sortedSeg.foreach(p=>println(p._1/2+\" \"+p._2))\n\n var kk: Int = 0\n var resN: Int = 0\n var i: Int = 0\n val res:Array[Int] = new Array[Int](n*2)\n while (i < 2 * n) {\n {\n kk += sortedSeg(i)._2\n if (kk >= k) {\n res(resN*2) = sortedSeg(i)._1/2\n while (kk >= k) {\n i += 1\n kk += sortedSeg(i)._2\n }\n res(resN*2+1) = (sortedSeg(i)._1-1)/2\n resN += 1\n }\n }\n i += 1\n }\n out.println(resN)\n for( i <- 0 until resN){\n out.println(res(i*2)+\" \"+res(i*2+1))\n }\n out.close()\n }\n\n\n\n\n\n\n\n\n\n class FasterScanner {\n private val buf: Array[Byte] = new Array[Byte](1024)\n private var curChar: Int = 0\n private var numChars: Int = 0\n\n def read: Int = {\n if (numChars == -1) throw new InputMismatchException\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = System.in.read(buf)\n }\n catch {\n case e: IOException =>\n throw new InputMismatchException\n }\n if (numChars <= 0) return -1\n }\n buf({curChar += 1; curChar - 1}) //相当于buf[curChar++]\n }\n\n def nextLine: String = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n val res: StringBuilder = new StringBuilder\n do {\n res.append(c)\n c = read\n } while (!isEndOfLine(c))\n res.toString\n }\n\n def nextString: String = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n val res: StringBuilder = new StringBuilder\n do {\n res.append(c)\n c = read\n } while (!isSpaceChar(c))\n res.toString\n }\n\n def nextLong: Long = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n var sgn: Int = 1\n if (c == '-') {\n sgn = -1\n c = read\n }\n var res: Long = 0\n do {\n if (c < '0' || c > '9') throw new InputMismatchException\n res *= 10\n res += c - '0'\n c = read\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextInt: Int = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n var sgn: Int = 1\n if (c == '-') {\n sgn = -1\n c = read\n }\n var res: Int = 0\n do {\n if (c < '0' || c > '9') throw new InputMismatchException\n res *= 10\n res += c - '0'\n c = read\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextIntArray(n: Int): Array[Int] = {\n val arr: Array[Int] = new Array[Int](n)\n for(i <- 0 until n){\n arr(i) = nextInt\n }\n arr\n }\n\n def nextLongArray(n: Int): Array[Long] = {\n val arr: Array[Long] = new Array[Long](n)\n for(i <- 0 until n){\n arr(i) = nextLong\n }\n arr\n }\n\n private def isSpaceChar(c: Int): Boolean = {\n c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n }\n\n private def isEndOfLine(c: Int): Boolean = {\n c == '\\n' || c == '\\r' || c == -1\n }\n }\n}"}, {"source_code": "\n\nimport java.io._\nimport java.util.InputMismatchException\n\nimport scala.annotation.tailrec\n\nobject Codeforces_Scala{\n def main(args: Array[String]) {\n val scan = new FasterScanner();\n val out: PrintWriter = new PrintWriter(System.out)\n\n val n:Int = scan.nextInt\n val k:Int = scan.nextInt\n\n val segments:Array[(Int, Int)] = new Array[(Int, Int)](2*n)\n for(i <- 0 until n){\n val x:Int = i*2\n val y:Int = i*2 + 1\n segments(x) = (scan.nextInt*2,1)\n segments(y) = (scan.nextInt*2+1,-1)\n }\n\n //segments.foreach(p=>println(p._1+\" \"+p._2))\n val sortedSeg = segments.sortBy(e=>e._1)\n //sortedSeg.foreach(p=>println(p._1/2+\" \"+p._2))\n\n val res:Array[Int] = new Array[Int](n*2)\n val resN:Int = Process(sortedSeg,0,0,k,res,0,false)\n out.println(resN)\n for(i <- 0 until resN){\n out.println(res(i*2)+\" \"+res(i*2+1))\n }\n out.flush()\n out.close()\n\n //Run(sortedSeg,n,k,out)\n }\n\n def Run(sortedSeg: Array[(Int, Int)],n:Int,k:Int,out: PrintWriter): Unit ={\n var kk: Int = 0\n var resN: Int = 0\n var i: Int = 0\n val res:Array[Int] = new Array[Int](n*2)\n while (i < 2 * n) {\n {\n kk += sortedSeg(i)._2\n if (kk >= k) {\n res(resN*2) = sortedSeg(i)._1/2\n while (kk >= k) {\n i += 1\n kk += sortedSeg(i)._2\n }\n res(resN*2+1) = (sortedSeg(i)._1-1)/2\n resN += 1\n }\n }\n i += 1\n }\n out.println(resN)\n for( i <- 0 until resN){\n out.println(res(i*2)+\" \"+res(i*2+1))\n }\n out.close()\n }\n //Nothing: 所有类型的子类\n //Nil: 空的List即List[Nothing]\n //Null: 引用的空值\n //None: 空的object\n @tailrec\n def Process(seg : Array[(Int, Int)], len:Int, k:Int, K:Int, res:Array[Int], resN:Int, flag: Boolean) :Int = {\n if(len>=seg.length){\n resN\n }else{\n val x = seg(len)\n val kk = k+x._2\n if(kk>=K && !flag){\n res(resN*2)=seg(len)._1/2\n Process(seg,len+1,kk,K,res,resN,true)\n }else if(kk= numChars) {\n curChar = 0\n try {\n numChars = System.in.read(buf)\n }\n catch {\n case e: IOException =>\n throw new InputMismatchException\n }\n if (numChars <= 0) return -1\n }\n buf({curChar += 1; curChar - 1}) //相当于buf[curChar++]\n }\n\n def nextLine: String = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n val res: StringBuilder = new StringBuilder\n do {\n res.append(c)\n c = read\n } while (!isEndOfLine(c))\n res.toString\n }\n\n def nextString: String = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n val res: StringBuilder = new StringBuilder\n do {\n res.append(c)\n c = read\n } while (!isSpaceChar(c))\n res.toString\n }\n\n def nextLong: Long = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n var sgn: Int = 1\n if (c == '-') {\n sgn = -1\n c = read\n }\n var res: Long = 0\n do {\n if (c < '0' || c > '9') throw new InputMismatchException\n res *= 10\n res += c - '0'\n c = read\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextInt: Int = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n var sgn: Int = 1\n if (c == '-') {\n sgn = -1\n c = read\n }\n var res: Int = 0\n do {\n if (c < '0' || c > '9') throw new InputMismatchException\n res *= 10\n res += c - '0'\n c = read\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextIntArray(n: Int): Array[Int] = {\n val arr: Array[Int] = new Array[Int](n)\n for(i <- 0 until n){\n arr(i) = nextInt\n }\n arr\n }\n\n def nextLongArray(n: Int): Array[Long] = {\n val arr: Array[Long] = new Array[Long](n)\n for(i <- 0 until n){\n arr(i) = nextLong\n }\n arr\n }\n\n private def isSpaceChar(c: Int): Boolean = {\n c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n }\n\n private def isEndOfLine(c: Int): Boolean = {\n c == '\\n' || c == '\\r' || c == -1\n }\n }\n}"}, {"source_code": "\n\nimport java.io.PrintWriter\nimport java.io.IOException\nimport java.io.InputStreamReader\nimport java.io.BufferedReader\nimport java.util.InputMismatchException\nimport java.util.StringTokenizer\nimport java.util.Scanner\nimport scala.Nil\nimport scala.annotation.tailrec\n\nobject Main {\n def main(args: Array[String]) {\n val scan = new FasterScanner();\n val out: PrintWriter = new PrintWriter(System.out)\n\n val n:Int = scan.nextInt\n val k:Int = scan.nextInt\n\n val segments:Array[(Int, Int)] = new Array[(Int, Int)](2*n)\n for(i <- 0 until n){\n val x:Int = i*2\n val y:Int = i*2 + 1\n segments(x) = (scan.nextInt*2,1)\n segments(y) = (scan.nextInt*2+1,-1)\n }\n\n //segments.foreach(p=>println(p._1+\" \"+p._2))\n val sortedSeg = segments.sortBy(e=>e._1)\n //sortedSeg.foreach(p=>println(p._1/2+\" \"+p._2))\n\n var kk: Int = 0\n var resN: Int = 0\n var i: Int = 0\n val res:Array[Int] = new Array[Int](n*2)\n while (i < 2 * n) {\n {\n kk += sortedSeg(i)._2\n if (kk >= k) {\n res(resN*2) = sortedSeg(i)._1/2\n while (kk >= k) {\n i += 1\n kk += sortedSeg(i)._2\n }\n res(resN*2+1) = (sortedSeg(i)._1-1)/2\n resN += 1\n }\n }\n i += 1\n }\n out.println(resN)\n for( i <- 0 until resN){\n out.println(res(i*2)+\" \"+res(i*2+1))\n }\n out.close();\n }\n\n\n\n\n\n\n\n\n\n class FasterScanner {\n private var buf: Array[Byte] = new Array[Byte](1024)\n private var curChar: Int = 0\n private var numChars: Int = 0\n\n def read: Int = {\n if (numChars == -1) throw new InputMismatchException\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = System.in.read(buf)\n }\n catch {\n case e: IOException => {\n throw new InputMismatchException\n }\n }\n if (numChars <= 0) return -1\n }\n return buf(({\n curChar += 1; curChar - 1\n }))\n }\n\n def nextLine: String = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n val res: StringBuilder = new StringBuilder\n do {\n res.append(c)\n c = read\n } while (!isEndOfLine(c))\n return res.toString\n }\n\n def nextString: String = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n val res: StringBuilder = new StringBuilder\n do {\n res.append(c)\n c = read\n } while (!isSpaceChar(c))\n return res.toString\n }\n\n def nextLong: Long = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n var sgn: Int = 1\n if (c == '-') {\n sgn = -1\n c = read\n }\n var res: Long = 0\n do {\n if (c < '0' || c > '9') throw new InputMismatchException\n res *= 10\n res += c - '0'\n c = read\n } while (!isSpaceChar(c))\n return res * sgn\n }\n\n def nextInt: Int = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n var sgn: Int = 1\n if (c == '-') {\n sgn = -1\n c = read\n }\n var res: Int = 0\n do {\n if (c < '0' || c > '9') throw new InputMismatchException\n res *= 10\n res += c - '0'\n c = read\n } while (!isSpaceChar(c))\n return res * sgn\n }\n\n def nextIntArray(n: Int): Array[Int] = {\n val arr: Array[Int] = new Array[Int](n)\n var i: Int = 0\n while (i < n) {\n {\n arr(i) = nextInt\n }\n ({\n i += 1; i - 1\n })\n }\n return arr\n }\n\n def nextLongArray(n: Int): Array[Long] = {\n val arr: Array[Long] = new Array[Long](n)\n var i: Int = 0\n while (i < n) {\n {\n arr(i) = nextLong\n }\n ({\n i += 1; i - 1\n })\n }\n return arr\n }\n\n private def isSpaceChar(c: Int): Boolean = {\n return c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n }\n\n private def isEndOfLine(c: Int): Boolean = {\n return c == '\\n' || c == '\\r' || c == -1\n }\n }\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nobject Main {\n def main(args: Array[String]) {\n \tval scan = new Scanner(System.in)\n \tval n = scan.nextInt()\n \tval K = scan.nextInt()\n \tval segments = Input(scan,n)\n //segments.foreach(p=>println(p._1+\" \"+p._2))\n val sortedSeg = segments.sortWith(Compare)\n //sortedSeg.foreach(p=>println(p._1+\" \"+p._2))\n val proSeg = Process(sortedSeg,1)\n //proSeg.foreach(p=>println(p._1+\" \"+p._2))\n val mergeSeg = Merge(proSeg,1)\n println(mergeSeg.length)\n mergeSeg.foreach(p=>println(p._1+\" \"+p._2))\n }\n\n def Input(scan:Scanner,n: Int) :List[(Int, Int)] = {\n if (n <= 0) {\n Nil\n } else {\n val x0 = scan.nextInt()\n val x1 = scan.nextInt()\n (x0,x1)::Input(scan,n-1)\n }\n }\n\n def Compare(a :(Int, Int),b :(Int, Int)) :Boolean= {\n if(a._1 == b._1){\n a._2 < b._2\n }else{\n a._1 < b._1\n }\n \n }\n\n def Process(seg: List[(Int,Int)],k:Int) :List[(Int, Int)] = {\n if(k>=seg.length){\n Nil\n }else{\n val a = seg(k-1)\n val b = seg(k)\n if(a._2>=b._1){\n (b._1,a._2)::Process(seg,k+1)\n }else{\n Process(seg,k+1)\n }\n }\n }\n\n def Merge(seg: List[(Int,Int)],k:Int) :List[(Int, Int)] = {\n if(k>=seg.length){\n seg.takeRight(1)\n }else{\n val s = Merge(seg,k+1)\n val a = seg(k-1)\n val b = s(0)\n if(a._2>=b._1){\n (a._1,b._2)::s.drop(1)\n }else{\n a::s\n }\n }\n }\n}\n"}, {"source_code": "\n\nimport java.io.IOException\nimport java.io.InputStreamReader\nimport java.io.BufferedReader\nimport java.util.InputMismatchException\nimport java.util.StringTokenizer\nimport java.util.Scanner\nimport scala.Nil\nimport scala.annotation.tailrec\n\nobject Main {\n def main(args: Array[String]) {\n val scan = new FasterScanner();\n val n:Int = scan.nextInt\n val k:Int = scan.nextInt\n\n val segments:Array[(Int, Int)] = new Array[(Int, Int)](2*n)\n for(i <- 0 until n){\n val x:Int = i*2\n val y:Int = i*2 + 1\n segments(x) = (scan.nextInt*2,1)\n segments(y) = (scan.nextInt*2+1,-1)\n }\n\n //segments.foreach(p=>println(p._1+\" \"+p._2))\n val sortedSeg = segments.sortBy(e=>e._1)\n //sortedSeg.foreach(p=>println(p._1/2+\" \"+p._2))\n\n var kk: Int = 0\n var resN: Int = 0\n var i: Int = 0\n val res:Array[Int] = new Array[Int](n*2)\n while (i < 2 * n) {\n {\n kk += sortedSeg(i)._2\n if (kk >= k) {\n res(resN*2) = sortedSeg(i)._1/2\n while (kk >= k) {\n i += 1\n kk += sortedSeg(i)._2\n }\n res(resN*2+1) = sortedSeg(i)._1/2\n resN += 1\n }\n }\n i += 1\n }\n println(resN)\n for( i <- 0 until resN){\n println(res(i*2)+\" \"+res(i*2+1))\n }\n }\n\n\n\n\n\n\n\n\n\n class FasterScanner {\n private var buf: Array[Byte] = new Array[Byte](1024)\n private var curChar: Int = 0\n private var numChars: Int = 0\n\n def read: Int = {\n if (numChars == -1) throw new InputMismatchException\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = System.in.read(buf)\n }\n catch {\n case e: IOException => {\n throw new InputMismatchException\n }\n }\n if (numChars <= 0) return -1\n }\n return buf(({\n curChar += 1; curChar - 1\n }))\n }\n\n def nextLine: String = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n val res: StringBuilder = new StringBuilder\n do {\n res.append(c)\n c = read\n } while (!isEndOfLine(c))\n return res.toString\n }\n\n def nextString: String = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n val res: StringBuilder = new StringBuilder\n do {\n res.append(c)\n c = read\n } while (!isSpaceChar(c))\n return res.toString\n }\n\n def nextLong: Long = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n var sgn: Int = 1\n if (c == '-') {\n sgn = -1\n c = read\n }\n var res: Long = 0\n do {\n if (c < '0' || c > '9') throw new InputMismatchException\n res *= 10\n res += c - '0'\n c = read\n } while (!isSpaceChar(c))\n return res * sgn\n }\n\n def nextInt: Int = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n var sgn: Int = 1\n if (c == '-') {\n sgn = -1\n c = read\n }\n var res: Int = 0\n do {\n if (c < '0' || c > '9') throw new InputMismatchException\n res *= 10\n res += c - '0'\n c = read\n } while (!isSpaceChar(c))\n return res * sgn\n }\n\n def nextIntArray(n: Int): Array[Int] = {\n val arr: Array[Int] = new Array[Int](n)\n var i: Int = 0\n while (i < n) {\n {\n arr(i) = nextInt\n }\n ({\n i += 1; i - 1\n })\n }\n return arr\n }\n\n def nextLongArray(n: Int): Array[Long] = {\n val arr: Array[Long] = new Array[Long](n)\n var i: Int = 0\n while (i < n) {\n {\n arr(i) = nextLong\n }\n ({\n i += 1; i - 1\n })\n }\n return arr\n }\n\n private def isSpaceChar(c: Int): Boolean = {\n return c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n }\n\n private def isEndOfLine(c: Int): Boolean = {\n return c == '\\n' || c == '\\r' || c == -1\n }\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main {\n def main(args: Array[String]) {\n \tval scan = new Scanner(System.in)\n \tval n = scan.nextInt()\n \tval k = scan.nextInt()\n \tval segments = Input(scan,n)\n //segments.foreach(p=>println(p._1+\" \"+p._2))\n val sortedSeg = segments.sortBy(e=>e._1)\n //sortedSeg.foreach(p=>println(p._1/2+\" \"+p._2))\n val proSeg = Process(sortedSeg,0,0,k,Nil)\n if(proSeg.length ==0){\n println(-1)\n }else{\n println(proSeg.length)\n proSeg.foreach(e=>println(e._1+\" \"+e._2))\n }\n \n }\n\n def Input(scan:Scanner,n: Int) :List[(Int, Int)] = {\n if (n <= 0) {\n Nil\n } else {\n val x0 = scan.nextInt()\n val x1 = scan.nextInt()\n //x*2,x*2+1避免两个点重复\n (x0*2,1)::(x1*2+1,-1)::Input(scan,n-1)\n }\n }\n\n//Nothing: 所有类型的子类\n//Nil: 空的List即List[Nothing]\n//Null: 引用的空值\n//None: 空的object\n def Process(seg: List[(Int,Int)],l:Int,d:Int,K:Int,p:List[Int]) :List[(Int, Int)] = {\n if(l>=seg.length){\n Nil\n }else{\n val x = seg(l)\n val dd = d+x._2\n if(dd>=K && p == Nil){\n Process(seg,l+1,dd,K,List(x._1))\n }else if(ddprintln(p._1+\" \"+p._2))\n val sortedSeg = segments.sortBy(e=>e._1)\n //sortedSeg.foreach(p=>println(p._1/2+\" \"+p._2))\n\n val proSeg = Process(sortedSeg,0,0,k,Nil,Nil)\n out.println(proSeg.length)\n proSeg.foreach(e=>out.println(e._1+\" \"+e._2))\n out.flush()\n out.close()\n\n //Run(sortedSeg,n,k,out)\n }\n\n def Run(sortedSeg: Array[(Int, Int)],n:Int,k:Int,out: PrintWriter): Unit ={\n var kk: Int = 0\n var resN: Int = 0\n var i: Int = 0\n val res:Array[Int] = new Array[Int](n*2)\n while (i < 2 * n) {\n {\n kk += sortedSeg(i)._2\n if (kk >= k) {\n res(resN*2) = sortedSeg(i)._1/2\n while (kk >= k) {\n i += 1\n kk += sortedSeg(i)._2\n }\n res(resN*2+1) = (sortedSeg(i)._1-1)/2\n resN += 1\n }\n }\n i += 1\n }\n out.println(resN)\n for( i <- 0 until resN){\n out.println(res(i*2)+\" \"+res(i*2+1))\n }\n out.close()\n }\n //Nothing: 所有类型的子类\n //Nil: 空的List即List[Nothing]\n //Null: 引用的空值\n //None: 空的object\n @tailrec\n def Process(seg : Array[(Int, Int)], len:Int, k:Int, K:Int, p:List[Int], resList:List[(Int, Int)]) :List[(Int, Int)] = {\n if(len>=seg.length){\n resList\n }else{\n val x = seg(len)\n val kk = k+x._2\n if(kk>=K && p == Nil){\n Process(seg,len+1,kk,K,List(x._1),resList)\n }else if(kk= numChars) {\n curChar = 0\n try {\n numChars = System.in.read(buf)\n }\n catch {\n case e: IOException =>\n throw new InputMismatchException\n }\n if (numChars <= 0) return -1\n }\n buf({curChar += 1; curChar - 1}) //相当于buf[curChar++]\n }\n\n def nextLine: String = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n val res: StringBuilder = new StringBuilder\n do {\n res.append(c)\n c = read\n } while (!isEndOfLine(c))\n res.toString\n }\n\n def nextString: String = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n val res: StringBuilder = new StringBuilder\n do {\n res.append(c)\n c = read\n } while (!isSpaceChar(c))\n res.toString\n }\n\n def nextLong: Long = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n var sgn: Int = 1\n if (c == '-') {\n sgn = -1\n c = read\n }\n var res: Long = 0\n do {\n if (c < '0' || c > '9') throw new InputMismatchException\n res *= 10\n res += c - '0'\n c = read\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextInt: Int = {\n var c: Int = read\n while (isSpaceChar(c)) c = read\n var sgn: Int = 1\n if (c == '-') {\n sgn = -1\n c = read\n }\n var res: Int = 0\n do {\n if (c < '0' || c > '9') throw new InputMismatchException\n res *= 10\n res += c - '0'\n c = read\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextIntArray(n: Int): Array[Int] = {\n val arr: Array[Int] = new Array[Int](n)\n for(i <- 0 until n){\n arr(i) = nextInt\n }\n arr\n }\n\n def nextLongArray(n: Int): Array[Long] = {\n val arr: Array[Long] = new Array[Long](n)\n for(i <- 0 until n){\n arr(i) = nextLong\n }\n arr\n }\n\n private def isSpaceChar(c: Int): Boolean = {\n c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n }\n\n private def isEndOfLine(c: Int): Boolean = {\n c == '\\n' || c == '\\r' || c == -1\n }\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main {\n def main(args: Array[String]) {\n val scan = new Scanner(System.in)\n val n = scan.nextInt()\n val K = scan.nextInt()\n val segments = Input(scan,n)\n //segments.foreach(p=>println(p._1+\" \"+p._2))\n val sortedSeg = segments.sortBy(e=>e._1)\n //sortedSeg.foreach(p=>println(p._1/2+\" \"+p._2))\n var k = 0\n var p :List[Int]= Nil\n var proSeg:List[(Int, Int)] = List()\n sortedSeg.foreach(e=>{\n k += e._2\n if(k >= K && p == Nil){\n p = List(e._1)\n }else if(k < K && p != Nil){\n proSeg = (p(0)/2,e._1/2)::proSeg\n p = Nil\n }\n })\n println(proSeg.length)\n proSeg.foreach(e=>println(e._1+\" \"+e._2))\n \n }\n\n def Input(scan:Scanner,n: Int) :List[(Int, Int)] = {\n if (n <= 0) {\n Nil\n } else {\n val x0 = scan.nextInt()\n val x1 = scan.nextInt()\n //x*2,x*2+1避免两个点重复\n (x0*2,1)::(x1*2+1,-1)::Input(scan,n-1)\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.annotation.tailrec\n\nobject Main {\n def main(args: Array[String]) {\n val scan = new Scanner(System.in)\n val n = scan.nextInt()\n val k = scan.nextInt()\n val segments = Input(scan,n,Nil)\n //segments.foreach(p=>println(p._1+\" \"+p._2))\n val sortedSeg = segments.sortBy(e=>e._1)\n //sortedSeg.foreach(p=>println(p._1/2+\" \"+p._2))\n if(n<10000 ){\n \n val proSeg = Process(sortedSeg,0,0,k,Nil,Nil)\n println(proSeg.length)\n proSeg.foreach(e=>println(e._1+\" \"+e._2))\n }\n \n \n }\n\n @tailrec\n def Input(scan:Scanner,n: Int,inList:List[(Int, Int)]) :List[(Int, Int)] = {\n if (n <= 0) {\n inList\n } else {\n val x0 = scan.nextInt()\n val x1 = scan.nextInt()\n //x*2,x*2+1避免两个点重复\n Input(scan,n-1,inList:::List((x0*2,1),(x1*2+1,-1)))\n }\n }\n//Nothing: 所有类型的子类\n//Nil: 空的List即List[Nothing]\n//Null: 引用的空值\n//None: 空的object\n @tailrec\n def Process(seg: List[(Int,Int)],l:Int,d:Int,K:Int,p:List[Int],resList:List[(Int, Int)]) :List[(Int, Int)] = {\n if(l>=seg.length){\n resList\n }else{\n val x = seg(l)\n val dd = d+x._2\n if(dd>=K && p == Nil){\n Process(seg,l+1,dd,K,List(x._1),resList)\n }else if(dd diff(in.nextLine.toCharArray))\n if (diffs.filter(a => a < 0).size >= 1) {\n println(\"-1\")\n } else {\n val answer = diffs.foldLeft(new HashSet[Int]())((a, b) => a + b)\n println(answer.size)\n }\n\n def diff(line: Array[Char]): Int = {\n val g = line.indexWhere(_ == 'G')\n val s = line.indexWhere(_ == 'S')\n s - g\n }\n\n}\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val result = (1 to n).map{ _ =>\n val str = in.next()\n val sweet = str.indexOf('S')\n val gnome = str.indexOf('G')\n if (gnome > sweet)\n -1\n else\n sweet - gnome\n }.sorted.distinct\n if (result.head == -1)\n println(-1)\n else\n println(result.length)\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n (1 to n).foldLeft(0){\n case(-1, _) => -1\n case(acc, _) =>\n val str = in.next()\n val sweet = str.indexOf('S')\n val gnome = str.indexOf('G')\n if (gnome > sweet)\n -1\n else\n Math.max(acc, sweet - gnome)\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n println((1 to n).foldLeft(0){\n case(-1, _) => -1\n case(acc, _) =>\n val str = in.next()\n val sweet = str.indexOf('S')\n val gnome = str.indexOf('G')\n if (gnome > sweet)\n -1\n else\n Math.max(acc, sweet - gnome)\n })\n}"}], "src_uid": "9a823b4ac4a79f62cd0c2f88a1c9ef0c"} {"source_code": "/*\n * Reference: http://lizan.asia/blog/2012/12/11/scala-competitive/\n */\n\nobject Main extends App {\n import java.{util => ju}\n import scala.annotation._\n import scala.collection._\n import scala.collection.{mutable => mu}\n import scala.collection.JavaConverters._\n import scala.math._\n\n val sc = new ju.Scanner(System.in)\n val n, k = sc.nextInt\n val s = Array.fill(n)(sc.nextInt)\n val twos = 0 max (n - k)\n 0 until twos foreach {i => s(i) += s(2 * twos - i - 1)}\n println(s.max)\n}", "positive_code": [{"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val n=nextInt\n val k=nextInt\n val s=for(i<-0 until n) yield nextInt\n if(nmaximum){\n maximum=s(i)+s(2*(n-k)-1-i)\n }\n }\n out.println(maximum)\n }\n\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n if (k >= n)\n println(data.last)\n else {\n val d = data.dropRight(2 * k - n)\n val small = d.take(d.length / 2)\n val big = d.takeRight(d.length / 2).reverse\n val zipped = big.zip(small).map(i => i._1 + i._2).max\n if (d.length == data.length)\n println(zipped)\n else\n println(Math.max(zipped, data.last))\n }\n\n}\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k) = readInts(2)\n val ss = readInts(n)\n\n def can(s: Long): Boolean = {\n if (s < ss.last) false\n else {\n var i = 0\n var j = n - 1\n var cnt = 0\n while (i <= j) {\n if (ss(i) + ss(j) <= s && i < j) {\n cnt += 1\n i += 1\n j -= 1\n } else {\n cnt += 1\n j -= 1\n }\n }\n cnt <= k\n }\n }\n\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) >>> 1\n if (can(mid)) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n var res = binSearch(1, 5000000)\n println(res)\n}\n"}, {"source_code": "\nimport java.io.InputStreamReader\nimport java.io.BufferedReader\n\n/**\n * @author pvasilyev\n * @since 15 Aug 2016\n */\nobject B604 extends App {\n\n def check(boxSize: Int, s: Array[Int], k: Int): Boolean = {\n var lastIndex = s.length\n var firstIndex = -1\n for (i <- 0 until k) {\n if (lastIndex > 0 && firstIndex < s.length-1) {\n if (s(lastIndex-1) + s(firstIndex+1) <= boxSize) {\n firstIndex += 1\n }\n lastIndex -= 1\n }\n }\n\n lastIndex - firstIndex <= 1\n }\n\n def solve() = {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val Array(n, k): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n val s: Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n val sum = s.sum\n var lowerS = math.max(if (sum % k == 0) sum / k else sum / k + 1, s.last)\n var upperS = s.last * 2\n var found = false\n while (!found) {\n if (upperS - lowerS <= 1) {\n found = true\n } else {\n val midS = (upperS + lowerS) >> 1\n if (check(midS, s, k)) {\n upperS = midS\n } else {\n lowerS = midS\n }\n }\n }\n\n if (check(lowerS, s, k)) {\n println(lowerS)\n } else {\n println(upperS)\n }\n reader.close()\n }\n\n solve()\n\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _604B extends CodeForcesApp {\n override type Result = Int\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val (n, k) = (nextInt(), nextInt())\n val s = Seq.fill(n)(nextInt())\n val (a, b) = s splitAt (n-k)\n val (s1, s2) = a.reverse.zipAll(b, 0, 0) maxBy { case (p, q) => p + q }\n s1 + s2\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n val mod: Int = 1000000007\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}"}], "negative_code": [{"source_code": "\nimport java.io.InputStreamReader\nimport java.io.BufferedReader\n\n/**\n * @author pvasilyev\n * @since 15 Aug 2016\n */\nobject B604 extends App {\n\n def check(boxSize: Int, s: Array[Int], k: Int): Boolean = {\n var lastIndex = s.length - 1\n var firstIndex = 0\n for (i <- 0 until k) {\n if (lastIndex >= 0 && firstIndex < s.length) {\n if (s(lastIndex) + s(firstIndex) <= boxSize) {\n firstIndex += 1\n }\n lastIndex -= 1\n }\n }\n\n lastIndex - firstIndex <= 1\n }\n\n def solve() = {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val Array(n, k): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n val s: Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n val sum = s.sum\n var lowerS = math.max(if (sum % k == 0) sum / k else sum / k + 1, s.last)\n var upperS = s.last * 2\n var found = false\n while (!found) {\n if (upperS - lowerS <= 1) {\n found = true\n } else {\n val midS = (upperS + lowerS) >> 1\n if (check(midS, s, k)) {\n upperS = midS\n } else {\n lowerS = midS\n }\n }\n }\n\n if (check(lowerS, s, k)) {\n println(lowerS)\n } else {\n println(upperS)\n }\n reader.close()\n }\n\n solve()\n\n}\n"}, {"source_code": "\nimport java.io.InputStreamReader\nimport java.io.BufferedReader\n\n/**\n * @author pvasilyev\n * @since 15 Aug 2016\n */\nobject B604 extends App {\n\n def check(boxSize: Int, s: Array[Int], k: Int): Boolean = {\n var lastIndex = s.length - 1\n var firstIndex = 0\n for (i <- 0 until k) {\n if (s(lastIndex) + s(firstIndex) <= boxSize) {\n firstIndex += 1\n }\n lastIndex -= 1\n }\n\n lastIndex - firstIndex <= 1\n }\n\n def solve() = {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val Array(n, k): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n val s: Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n val sum = s.sum\n var lowerS = math.max(if (sum % k == 0) sum / k else sum / k + 1, s.last)\n var upperS = s.last * 2\n var found = false\n while (!found) {\n if (upperS - lowerS <= 1) {\n found = true\n } else {\n val midS = (upperS + lowerS) >> 1\n if (check(midS, s, k)) {\n upperS = midS\n } else {\n lowerS = midS\n }\n }\n }\n\n println(lowerS)\n reader.close()\n }\n\n solve()\n\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _604B extends CodeForcesApp {\n override type Result = Int\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val (n, k) = (nextInt(), nextInt())\n val s = Seq.fill(n)(nextInt())\n val (a, b) = s splitAt (n-k)\n val (s1, s2) = a.zipAll(b.reverse, 0, 0) maxBy { case (p, q) => p + q }\n s1 + s2\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n val mod: Int = 1000000007\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _604B extends CodeForcesApp {\n override type Result = Int\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val (n, k) = (nextInt(), nextInt())\n val s = Seq.fill(n)(nextInt())\n val (a, b) = s splitAt (n-k)\n val (s1, s2) = a.zipAll(b, 0, 0) maxBy { case (p, q) => p + q }\n s1 + s2\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n val mod: Int = 1000000007\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}], "src_uid": "7324428d9e6d808f55ad4f3217046455"} {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _583B extends CodeForcesApp[Int]({scanner => import scanner._\n val n = nextInt\n val computers = IndexedSeq.fill(n)(nextInt)\n val (left, right) = (true, false)\n var ans = 0\n var hacked = bag[Int]\n\n @tailrec\n def move(pos: Int, dir: Boolean): Int = (pos, dir) match {\n case _ if hacked.size == n => ans\n\n case (`n`, `right`) =>\n ans += 1\n move(n-1, left)\n\n case (-1, `left`) =>\n ans += 1\n move(0, right)\n\n case _ =>\n if(computers(pos) <= hacked.size) {\n hacked += pos\n }\n move(pos + (if (dir == right) 1 else -1), dir)\n }\n\n move(0, right)\n}) {\n override def format(result: Result) = super.format(result)\n}\n/********************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)\n final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n", "positive_code": [{"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject B_Robots {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(t25.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n val number = line1.nextToken().toInt\n \n val line2 = br.readLine().split(\" \")\n var comps = line2.map(_.toInt)\n var compsColl = Array.fill(number)(false)\n //---------------------------- parameters reading end --------------------------------\n\n var collected = 0\n var pointer = 0\n var previousRigh = true\n var turns = 0\n while (collected != number) {\n val r = lookRight()\n val l = lookLeft\n var toProcess = List[Int]()\n if (r.size > l.size) {\n toProcess = r\n if (!previousRigh) turns += 1\n previousRigh = true\n } else if (l.size > r.size) {\n toProcess = l\n if (previousRigh) turns += 1\n previousRigh = false\n } else {\n if (previousRigh) {\n toProcess = r\n } else {\n toProcess = l\n }\n }\n pointer = toProcess.head\n collected += toProcess.size\n toProcess.foreach { x => compsColl(x) = true }\n \n }\n println(turns)\n \n def lookRight():List[Int] = {\n var res = List[Int]();\n var couldBe = collected\n for(i<-pointer until number) {\n if (comps(i) <= couldBe && !compsColl(i)) {\n res ::= i\n couldBe += 1\n }\n }\n return res\n } \n \n def lookLeft():List[Int] = {\n var res = List[Int]();\n var couldBe = collected\n var i = pointer\n while (i >= 0) {\n if (comps(i) <= couldBe && !compsColl(i)) {\n res ::= i\n couldBe += 1\n }\n i -= 1\n }\n return res\n }\n \n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val n = readInt()\n val A = readLine().split(\" \").map(_.toInt)\n val V = Array.ofDim[Boolean](A.length + 1)\n\n var power = 0\n var changeDir = -1\n while (power < A.length) {\n changeDir += 1\n for (i <- 0 until A.length) {\n if (!V(i) && A(i) <= power) {\n power += 1\n V(i) = true\n }\n }\n\n if (power < A.length) {\n changeDir += 1\n for (i <- A.length - 1 to 0 by -1) {\n if (!V(i) && A(i) <= power) {\n power += 1\n V(i) = true\n }\n }\n }\n }\n\n println(changeDir)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val visited = Array.ofDim[Boolean](n)\n var gathered = 0\n var position = 0\n var changes = 0\n var right = true\n while (gathered != n) {\n if (position < 0) {\n right = true\n position = 0\n changes += 1\n } else if (position > n - 1) {\n right = false\n position = n - 1\n changes += 1\n }\n\n if (!visited(position) && data(position) <= gathered) {\n gathered += 1\n visited(position) = true\n }\n if (right)\n position += 1\n else\n position -= 1\n }\n\n println(changes)\n}"}, {"source_code": "object B583 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n)\n var res = 0\n var dir = +1\n var sec = 0\n while(in.exists(_ != -1)) {\n val range = if(dir == 1) 0 until n else n-1 to 0 by -1\n for(i <- range){\n if(in(i) != -1 && in(i) <= sec) {\n sec += 1\n in(i) = -1\n }\n }\n if(dir == +1) dir = -1 else dir = +1\n if(in.exists(_ != -1))\n res += 1\n }\n\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject B_Robots {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n val number = line1.nextToken().toInt\n \n val line2 = br.readLine().split(\" \")\n var comps = line2.map(_.toInt)\n var compsColl = Array.fill(number)(false)\n //---------------------------- parameters reading end --------------------------------\n\n var collected = 0\n var pointer = 0\n var previousRigh = true\n var turns = 0\n var rightFirst = -1\n var leftFirst = -1\n while (collected != number) {\n val r = lookRight()\n val l = lookLeft\n var toProcess = List[Int]()\n if (r.size > l.size) {\n toProcess = r\n if (!previousRigh) turns += 1\n previousRigh = true\n pointer = r.head\n } else if (l.size > r.size) {\n toProcess = l\n if (previousRigh) turns += 1\n previousRigh = false\n pointer = l.last\n } else {\n if (previousRigh) {\n toProcess = r\n } else {\n toProcess = l\n }\n }\n collected += toProcess.size\n toProcess.foreach { x => compsColl(x) = true }\n \n }\n println(turns)\n \n def lookRight():List[Int] = {\n var res = List[Int]();\n rightFirst = -1\n var couldBe = collected\n for(i<-pointer until number) {\n if (comps(i) <= couldBe && !compsColl(i)) {\n if (rightFirst == -1) rightFirst = i\n res ::= i\n couldBe += 1\n }\n }\n return res\n } \n \n def lookLeft():List[Int] = {\n var res = List[Int]();\n leftFirst = -1\n var couldBe = collected\n for(i<-0 to pointer) {\n if (comps(i) <= couldBe && !compsColl(i)) {\n if (leftFirst == -1) leftFirst = i\n res ::= i\n couldBe += 1\n }\n }\n return res\n }\n \n }\n\n}"}, {"source_code": "import java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject B_Robots {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n val number = line1.nextToken().toInt\n \n val line2 = br.readLine().split(\" \")\n var comps = line2.map(_.toInt)\n var compsColl = Array.fill(number)(false)\n //---------------------------- parameters reading end --------------------------------\n\n var collected = 0\n var pointer = 0\n var previousRigh = true\n var turns = 0\n var rightFirst = -1\n var leftFirst = -1\n while (collected != number) {\n val r = lookRight()\n val l = lookLeft\n var toProcess = List[Int]()\n if (r.size > l.size) {\n toProcess = r\n if (!previousRigh) turns += 1\n previousRigh = true\n } else {\n toProcess = l\n if (previousRigh) turns += 1\n previousRigh = false\n }\n pointer = toProcess.head\n collected += toProcess.size\n toProcess.foreach { x => compsColl(x) = true }\n \n }\n println(turns)\n \n def lookRight():List[Int] = {\n var res = List[Int]();\n rightFirst = -1\n var couldBe = collected\n for(i<-pointer until number) {\n if (comps(i) <= couldBe && !compsColl(i)) {\n if (rightFirst == -1) rightFirst = i\n res ::= i\n couldBe += 1\n }\n }\n return res\n } \n \n def lookLeft():List[Int] = {\n var res = List[Int]();\n leftFirst = -1\n var couldBe = collected\n for(i<-0 to pointer) {\n if (comps(i) <= collected && !compsColl(i)) {\n if (leftFirst == -1) leftFirst = i\n res ::= i\n couldBe += 1\n }\n }\n return res\n }\n \n }\n\n}"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject B_Robots {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n val number = line1.nextToken().toInt\n \n val line2 = br.readLine().split(\" \")\n var comps = line2.map(_.toInt)\n var compsColl = Array.fill(number)(false)\n //---------------------------- parameters reading end --------------------------------\n\n var collected = 0\n var pointer = 0\n var previousRigh = true\n var turns = 0\n var rightFirst = -1\n var leftFirst = -1\n while (collected != number) {\n val r = lookRight()\n val l = lookLeft\n var toProcess = List[Int]()\n if (r.size > l.size) {\n toProcess = r\n if (!previousRigh) turns += 1\n previousRigh = true\n pointer = r.head\n } else if (l.size > r.size) {\n toProcess = l\n if (previousRigh) turns += 1\n previousRigh = false\n pointer = l.last\n } else {\n if (previousRigh) {\n toProcess = r\n } else {\n toProcess = l\n }\n }\n collected += toProcess.size\n toProcess.foreach { x => compsColl(x) = true }\n \n }\n println(turns)\n \n def lookRight():List[Int] = {\n var res = List[Int]();\n rightFirst = -1\n var couldBe = collected\n for(i<-pointer until number) {\n if (comps(i) <= couldBe && !compsColl(i)) {\n if (rightFirst == -1) rightFirst = i\n res ::= i\n couldBe += 1\n }\n }\n return res\n } \n \n def lookLeft():List[Int] = {\n var res = List[Int]();\n leftFirst = -1\n var couldBe = collected\n for(i<- pointer to 0 by -1) {\n if (comps(i) <= couldBe && !compsColl(i)) {\n if (leftFirst == -1) leftFirst = i\n res ::= i\n couldBe += 1\n }\n }\n return res\n }\n \n }\n\n}"}, {"source_code": "\n\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject B_Robots {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n val number = line1.nextToken().toInt\n \n val line2 = br.readLine().split(\" \")\n var comps = line2.map(_.toInt)\n var compsColl = Array.fill(number)(false)\n //---------------------------- parameters reading end --------------------------------\n\n var collected = 0\n var pointer = 0\n var previousRigh = true\n var turns = 0\n// var rightFirst = -1\n// var leftFirst = -1\n while (collected != number) {\n val r = lookRight()\n val l = lookLeft\n var toProcess = List[Int]()\n if (r.size > l.size) {\n toProcess = r\n if (!previousRigh) turns += 1\n previousRigh = true\n pointer = r.head\n } else if (l.size > r.size) {\n toProcess = l\n if (previousRigh) turns += 1\n previousRigh = false\n pointer = l.last\n } else {\n if (previousRigh) {\n toProcess = r\n } else {\n toProcess = l\n }\n }\n collected += toProcess.size\n toProcess.foreach { x => compsColl(x) = true }\n \n }\n println(turns)\n \n def lookRight():List[Int] = {\n var res = List[Int]();\n// rightFirst = -1\n var couldBe = collected\n for(i<-pointer until number) {\n if (comps(i) <= collected && !compsColl(i)) {\n// if (rightFirst == -1) rightFirst = i\n res ::= i\n couldBe += 1\n }\n }\n return res\n } \n \n def lookLeft():List[Int] = {\n var res = List[Int]();\n// leftFirst = -1\n var couldBe = collected\n var i = pointer\n while (i >= 0) {\n if (comps(i) <= collected && !compsColl(i)) {\n res ::= i\n couldBe += 1\n }\n i -= 1\n }\n// for(i<- pointer to 0 by -1) {\n// if (comps(i) <= couldBe && !compsColl(i)) {\n//// if (leftFirst == -1) leftFirst = i\n// res ::= i\n// couldBe += 1\n// }\n// }\n return res\n }\n \n }\n \n\n}"}, {"source_code": "import java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject B_Robots {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n val number = line1.nextToken().toInt\n \n val line2 = br.readLine().split(\" \")\n var comps = line2.map(_.toInt)\n var compsColl = Array.fill(number)(false)\n //---------------------------- parameters reading end --------------------------------\n\n var collected = 0\n var pointer = 0\n var previousRigh = true\n var turns = 0\n var rightFirst = -1\n var leftFirst = -1\n while (collected != number) {\n val r = lookRight()\n val l = lookLeft\n var toProcess = List[Int]()\n if (r.size > l.size) {\n toProcess = r\n if (!previousRigh) turns += 1\n previousRigh = true\n } else if (l.size > r.size) {\n toProcess = l\n if (previousRigh) turns += 1\n previousRigh = false\n } else {\n if (previousRigh) {\n toProcess = r\n } else {\n toProcess = l\n }\n }\n pointer = toProcess.head\n collected += toProcess.size\n toProcess.foreach { x => compsColl(x) = true }\n \n }\n println(turns)\n \n def lookRight():List[Int] = {\n var res = List[Int]();\n rightFirst = -1\n var couldBe = collected\n for(i<-pointer until number) {\n if (comps(i) <= couldBe && !compsColl(i)) {\n if (rightFirst == -1) rightFirst = i\n res ::= i\n couldBe += 1\n }\n }\n return res\n } \n \n def lookLeft():List[Int] = {\n var res = List[Int]();\n leftFirst = -1\n var couldBe = collected\n for(i<-0 to pointer) {\n if (comps(i) <= collected && !compsColl(i)) {\n if (leftFirst == -1) leftFirst = i\n res ::= i\n couldBe += 1\n }\n }\n return res\n }\n \n }\n\n}"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject B_Robots {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n val number = line1.nextToken().toInt\n \n val line2 = br.readLine().split(\" \")\n var comps = line2.map(_.toInt)\n var compsColl = Array.fill(number)(false)\n //---------------------------- parameters reading end --------------------------------\n\n var collected = 0\n var pointer = 0\n var previousRigh = true\n var turns = 0\n var rightFirst = -1\n var leftFirst = -1\n while (collected != number) {\n val r = lookRight()\n val l = lookLeft\n var toProcess = List[Int]()\n if (r.size > l.size) {\n toProcess = r\n if (!previousRigh) turns += 1\n previousRigh = true\n pointer = r.head\n } else if (l.size > r.size) {\n toProcess = l\n if (previousRigh) turns += 1\n previousRigh = false\n pointer = l.last\n } else {\n if (previousRigh) {\n toProcess = r\n } else {\n toProcess = l\n }\n }\n collected += toProcess.size\n toProcess.foreach { x => compsColl(x) = true }\n \n }\n println(turns)\n \n def lookRight():List[Int] = {\n var res = List[Int]();\n rightFirst = -1\n var couldBe = collected\n for(i<-pointer until number) {\n if (comps(i) <= couldBe && !compsColl(i)) {\n if (rightFirst == -1) rightFirst = i\n res ::= i\n couldBe += 1\n }\n }\n return res\n } \n \n def lookLeft():List[Int] = {\n var res = List[Int]();\n leftFirst = -1\n var couldBe = collected\n for(i<-0 to pointer) {\n if (comps(i) <= collected && !compsColl(i)) {\n if (leftFirst == -1) leftFirst = i\n res ::= i\n couldBe += 1\n }\n }\n return res\n }\n \n }\n\n}"}], "src_uid": "9374728643a1ddbe2200a4a125beef26"} {"source_code": "object A extends App {\r\n\r\n sealed trait Row {\r\n def size: Int\r\n }\r\n final case class Empty(size: Int) extends Row {\r\n override def toString(): String = \".\" * size\r\n }\r\n final case class Rook(size: Int, rook: Int) extends Row {\r\n override def toString(): String = \".\" * rook + \"R\" + \".\" * (size - rook - 1)\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val k = nextInt()\r\n\r\n val m = 2 * (k - 1) + 1\r\n\r\n if (n >= m)\r\n (0 until n).foldLeft(k) {\r\n case (rooks, row) if row % 2 == 0 && rooks > 0 =>\r\n out.println(Rook(n, row))\r\n rooks - 1\r\n case (rooks, _) =>\r\n out.println(Empty(n))\r\n rooks\r\n }\r\n else\r\n out.println(-1)\r\n }\r\n out.flush()\r\n\r\n object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n private[this] def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object A extends App {\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val k = nextInt()\r\n\r\n val m = 2 * (k - 1) + 1\r\n\r\n if (n >= m)\r\n (0 until n).foldLeft(k) {\r\n case (rooks, row) if row % 2 == 0 && rooks > 0 =>\r\n val line = (0 until n).map {\r\n case column if row == column => 'R'\r\n case _ => '.'\r\n }.mkString(\"\")\r\n out.println(line)\r\n rooks - 1\r\n case (rooks, _) =>\r\n out.println(\".\" * n)\r\n rooks\r\n }\r\n else\r\n out.println(-1)\r\n }\r\n out.flush()\r\n\r\n object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n private[this] def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "d5549c0627c236d82541a67ccbe7977d"} {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n (0 until readInt()).foreach { _ =>\n val n = readInt()\n\n val (i, j, k) = n % 3 match {\n case 0 => (n / 3, 0, 0)\n case 1 => (n / 3 - 2, 0, 1) // n = 3 * i + 1 = 3 * (i - 2) + 7\n case 2 => (n / 3 - 1, 1, 0) // n = 3 * i + 2 = 3 * (i - 1) + 5\n }\n\n if (i < 0) println(-1)\n else println(s\"$i $j $k\")\n }\n}\n", "positive_code": [{"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val (a, b, c) = n % 3 match {\n case 0 =>\n (n / 3, 0, 0)\n case 1 =>\n (n / 3 - 2, 0, 1)\n case 2 =>\n (n / 3 - 1, 1, 0)\n }\n\n if (a >= 0) out.println(s\"$a $b $c\")\n else out.println(-1)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject task extends App {\n for (ws <- Source.stdin.getLines().drop(1).map(_.toInt)) {\n var found: Boolean = false;\n var result: String = \"-1\";\n var w3: Int = 0\n var w5: Int = 0\n var w7: Int = 0\n\n while ((w3 <= ws / 3) && !found) {\n w5 = 0\n while ((w5 <= ws / 5) && !found) {\n w7 = 0\n while (w7 <= ws / 7 && !found) {\n if (w3 * 3 + w5 * 5 + w7 * 7 == ws) {\n found = true;\n result = s\"$w3 $w5 $w7\"\n }\n w7 += 1\n }\n w5 += 1\n }\n w3 += 1\n }\n println(result)\n }\n}\n"}], "negative_code": [], "src_uid": "b43dee2f223c869a35b1b11ceb9d2b6b"} {"source_code": "import java.util.Scanner\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n def next = scanner.next.toInt\n\n val bookCount = next\n val genreCount = next\n val bookGenres = 0.until(bookCount).map(_ => next - 1)\n\n println(countOptions(genreCount, bookGenres))\n }\n\n def countOptions(genreCount: Int, bookGenres: IndexedSeq[Int]): Int = {\n val byGenre = new Array[Int](genreCount)\n for (genre <- bookGenres) {\n byGenre(genre) += 1\n }\n\n var result = 0\n for (bigger <- 1.until(genreCount)) {\n for (smaller <- 0.until(bigger)) {\n result += byGenre(smaller) * byGenre(bigger)\n }\n }\n\n result\n }\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.lang.System\n\nimport scala.io.StdIn\nimport scala.math.pow\nimport scala.collection.mutable._\n\nobject Main {\n implicit def bool2int(b: Boolean): Int = { if(b) 1 else 0 }\n\n def main(args: Array[String]): Unit = {\n val scanner = new Scanner(System.in)\n\n val (n, m) = (scanner.nextInt(), scanner.nextInt())\n val array = Array.fill[Int](m)(0)\n\n (1 to n).foreach { i =>\n array(scanner.nextInt() - 1) += 1\n }\n\n var total: Int = 0\n\n (0 to m - 2).foreach { i =>\n (i + 1 to m - 1).foreach { k =>\n total += array(i) * array(k)\n }\n }\n\n println(total)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.math.pow\nimport scala.collection.mutable._\n\nobject Main {\n implicit def bool2int(b: Boolean): Int = { if(b) 1 else 0 }\n\n def main(args: Array[String]): Unit = {\n val inputs = readLine.split(' ').map(_.toInt)\n val (n, m) = (inputs(0), inputs(1))\n\n val books = readLine.split(' ').map(_.toInt)\n val counts = books.groupBy(identity).mapValues(_.size).values.toArray\n\n var total: Int = 0\n\n (0 to counts.size - 2).foreach { i =>\n (i + 1 to counts.size - 1).foreach { k =>\n total += counts(i) * counts(k)\n }\n }\n\n println(total)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.math.pow\nimport scala.collection.mutable._\n\nobject Main {\n implicit def bool2int(b: Boolean): Int = { if(b) 1 else 0 }\n\n def main(args: Array[String]): Unit = {\n val inputs = readLine.split(' ').map(_.toInt)\n val (n, m) = (inputs(0), inputs(1))\n\n val counts = readLine.split(' ').map(_.toInt).groupBy(identity).mapValues(_.size).values.toArray\n\n var total: Int = 0\n\n (0 to counts.size - 2).foreach { i =>\n (i + 1 to counts.size - 1).foreach { k =>\n total += counts(i) * counts(k)\n }\n }\n\n println(total)\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val arr = Array.ofDim[Int](m)\n in.next().split(' ').map(_.toInt - 1).foreach(i => arr(i) += 1)\n val count = arr.sum\n println(arr.foldLeft(0l) {\n case(sum, typeCount) => sum + typeCount * (count - typeCount)\n } / 2)\n}"}, {"source_code": "/*\n * Reference: http://lizan.asia/blog/2012/12/11/scala-competitive/\n */\n\nobject Main extends App {\n import java.{util => ju}\n import scala.annotation._\n import scala.collection._\n import scala.collection.{mutable => mu}\n import scala.collection.JavaConverters._\n import scala.math._\n\n val sc = new ju.Scanner(System.in)\n val n, m = sc.nextInt\n val nl: Long = n\n val g = Array.fill(n)(sc.nextInt)\n val acc = (1 to m).map(i => g.count(_ == i).asInstanceOf[Long]).map(x => x * (x - 1) / 2).sum\n println(nl * (nl - 1) / 2 - acc)\n}"}], "negative_code": [], "src_uid": "e2ff228091ca476926b8e905f1bc8dff"} {"source_code": "import java.util.Scanner\n\nobject Main {\n def main(args: Array[String]) {\n val in = new Scanner(System.in)\n val n = in.nextInt\n val a = new Array[Int](n)\n for (i <- 0 to n - 1)\n a(i) = in.nextInt\n\n val x = new Array[Int](n + 1)\n val y = new Array[Int](n + 1)\n x(0) = 0\n y(0) = 0\n for (i <- 1 to n) {\n x(i) = x(i - 1) + a(i - 1)\n y(i) = y(i - 1) + (if (i % 2 == 0) -1 else 1) * a(i - 1)\n }\n\n var minY = 0;\n var maxY = 0;\n for (i <- 0 to n) {\n minY = Math.min(minY, y(i))\n maxY = Math.max(maxY, y(i))\n }\n\n val ans = new Array[Array[Char]](maxY - minY)\n for (i <- 0 to maxY - minY - 1) {\n ans(i) = new Array[Char](x(n))\n for (j <- 0 to ans(i).length - 1)\n ans(i)(j) = ' '\n }\n\n var curj = 0\n for (i <- 0 to n - 1) {\n if (y(i) < y(i + 1)) {\n val c = '/';\n for (j <- y(i) to y(i + 1) - 1) {\n ans(j - minY)(curj) = c\n curj = curj + 1\n }\n } else {\n val c = '\\\\';\n var curi = y(i) - 1\n for (j <- y(i + 1) to y(i) - 1) {\n ans(curi - minY)(curj) = c\n curj = curj + 1\n curi = curi - 1\n }\n }\n }\n\n for (i <- 0 to maxY - minY - 1) {\n println(ans(maxY - minY - 1 - i).mkString)\n }\n\n }\n}", "positive_code": [{"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n\n var y, minY, maxY = 0\n for (i <- as.indices) {\n if (i % 2 == 0) y += as(i) else y -= as(i)\n minY = minY min y\n maxY = maxY max y\n }\n\n val res = Array.fill(maxY - minY, as.sum)(' ')\n\n y = 0\n var x = 0\n for (i <- as.indices) {\n for (j <- 0 until as(i)) {\n if (i % 2 == 0) y += 1 else y -= 1\n res(maxY - y)(x) = if (i % 2 == 0) '/' else '\\\\'\n x += 1\n }\n if (i % 2 == 0) y += 1 else y -= 1\n }\n\n res.foreach { s => println(s.mkString) }\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nobject Main {\n def main(args: Array[String]) {\n val in = new Scanner(System.in)\n val n = in.nextInt\n val a = new Array[Int](n)\n for (i <- 0 to n - 1)\n a(i) = in.nextInt\n\n val x = new Array[Int](n + 1)\n val y = new Array[Int](n + 1)\n x(0) = 0\n y(0) = 0\n for (i <- 1 to n) {\n x(i) = x(i - 1) + a(i - 1)\n y(i) = y(i - 1) + (if (i % 2 == 0) -1 else 1) * a(i - 1)\n\n println(x(i) + \" \" + y(i))\n }\n\n var minY = 0;\n var maxY = 0;\n for (i <- 0 to n) {\n minY = Math.min(minY, y(i))\n maxY = Math.max(maxY, y(i))\n }\n\n val ans = new Array[Array[Char]](maxY - minY)\n for (i <- 0 to maxY - minY - 1) {\n ans(i) = new Array[Char](x(n))\n for (j <- 0 to ans(i).length - 1)\n ans(i)(j) = ' '\n }\n\n var curj = 0\n for (i <- 0 to n - 1) {\n if (y(i) < y(i + 1)) {\n val c = '/';\n for (j <- y(i) to y(i + 1) - 1) {\n ans(j - minY)(curj) = c\n curj = curj + 1\n }\n } else {\n val c = '\\\\';\n var curi = y(i) - 1\n for (j <- y(i + 1) to y(i) - 1) {\n ans(curi - minY)(curj) = c\n curj = curj + 1\n curi = curi - 1\n }\n }\n }\n\n for (i <- 0 to maxY - minY - 1) {\n for (j <- 0 to ans(i).length - 1)\n print(ans(maxY - minY - 1 - i)(j))\n println\n }\n\n }\n}"}], "src_uid": "76285a60c21538db17d268a5e06c2270"} {"source_code": "object D459 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val arr = readInts(n)\n\n val map = cu.Map.empty[Int, Int].withDefaultValue(0)\n val left = new Array[Int](n)\n val right = new Array[Int](n)\n for(i <- 0 until n) {\n left(i) = map(arr(i))\n map(arr(i)) += 1\n }\n map.clear()\n for(i <- n-1 to 0 by -1) {\n right(i) = map(arr(i))\n map(arr(i)) += 1\n }\n\n var ret = 0L\n val fenwickTree = new FenwickTree(n+10)\n for(i <- n-1 to 0 by -1) {\n ret += fenwickTree.get(left(i))\n fenwickTree.add(right(i)+1, 1)\n }\n out.println(ret)\n\n out.close()\n }\n\n class FenwickTree(n: Int) {\n private val sum = new Array[Int](n+1)\n def get(r: Int): Int = {\n var idx = r\n var ret = 0\n while(idx > 0) {\n ret += sum(idx)\n idx -= Integer.lowestOneBit(idx)\n }\n ret\n }\n def add(r: Int, value: Int) {\n var idx = r\n while(idx <= n) {\n sum(idx) += value\n idx += Integer.lowestOneBit(idx)\n }\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import java.util._\nimport java.io._\n\nobject D {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n }\n if (n == 1) {\n out.println(0)\n return 1\n }\n val f1i = new Array[Int](n - 1)\n val map = scala.collection.mutable.Map[Int, Int]()\n f1i(0) = 1\n map.put(a(0), 1)\n for (i <- 1 to n - 2) {\n val num = map.getOrElse(a(i), 0) + 1\n map.put(a(i), num)\n f1i(i) = num\n }\n map.clear\n val fjn = new Array[Int](n - 1)\n fjn(n - 2) = 1\n map.put(a(n - 1), 1)\n for (i <- n - 3 to 0 by -1) {\n val num = map.getOrElse(a(i + 1), 0) + 1\n map.put(a(i + 1), num)\n fjn(i) = num\n }\n map.clear\n object SegmentTree {\n\n val N = Math.pow(2, 21).toInt\n // val N = 8\n val tree = new Array[Int](2 * N)\n\n def build(a: Array[Int]): Unit = {\n for (i <- N until tree.length) {\n tree(i) = a(i - N)\n }\n for (i <- N - 1 to 1 by -1) {\n tree(i) = tree(2 * i) + tree(2 * i + 1)\n }\n }\n\n def sum(l: Int, r: Int): Int = {\n var sum = 0\n var left = l + N\n var right = r + N\n while (left < right) {\n if (left % 2 == 1) {\n sum += tree(left)\n left += 1\n }\n if (right % 2 != 1) {\n sum += tree(right)\n right -= 1\n }\n left /= 2\n right /= 2\n }\n if (left == right) {\n return sum + tree(left)\n }\n return sum\n }\n\n def dec(pos: Int): Unit = {\n var i = pos + N\n while (i > 0) {\n tree(i) -= 1\n i /= 2\n }\n }\n }\n val ranges = new Array[Int](SegmentTree.N)\n for (i <- 0 until fjn.length) {\n ranges(fjn(i)) += 1\n }\n SegmentTree.build(ranges)\n var ans: Long = 0\n for (i <- 0 until f1i.length) {\n ans += SegmentTree.sum(0, f1i(i) - 1)\n SegmentTree.dec(fjn(i))\n }\n out.println(ans)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "negative_code": [], "src_uid": "d3b5b76f0853cff6c69b29e68a853ff7"} {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _682C extends CodeForcesApp {\n override def apply(io: IO) = {import io._\n val a = read[Vector[Long]]\n val n = a.length\n val graph = mmap[Int] to mutable.Map.empty[Int, Long]\n\n def addEdge(u: Int, v: Int, d: Long) = {\n graph.getOrElseUpdate(u, mutable.Map.empty[Int, Long])(v) = d\n }\n\n 1 until n foreach { u =>\n val v = read[Int] - 1\n val d = read[Long]\n addEdge(u, v, d)\n addEdge(v, u, d)\n }\n\n val visited = mutable.Set.empty[Int]\n def check(u: Int, distance: Long): Unit = {\n //debug(u+1, visited, distance, a(u))\n if(distance <= a(u)) {\n visited += u\n graph(u) foreach {\n case (v, d) if !visited(v) => check(v, d + (distance max 0))\n case _ =>\n }\n }\n }\n\n check(0, 0)\n write(n - visited.size)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = mmap[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toYesNo = if(x) \"yes\" else \"no\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def bitCount: Int = java.lang.Integer.bitCount(x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def mmap[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]\n def memoize[A, B](f: A => B): A ==> B = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeLine(obj: Any*): this.type = {\n if (obj.isEmpty) printer.println() else obj foreach printer.println\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _682C extends CodeForcesApp {\n override def apply(io: IO) = {import io._\n val a = read[Vector[Long]]\n val n = a.length\n val graph = mmap[Int] to mutable.Map.empty[Int, Long]\n\n 1 until n foreach { u =>\n val v = read[Int] - 1\n val d = read[Long]\n graph(u)(v) = d\n graph(v)(u) = d\n }\n\n val visited = mutable.Set.empty[Int]\n def check(u: Int, distance: Long): Unit = if(!visited(u) && distance <= a(u)) {\n visited += u\n graph(u) foreach {\n case (v, d) => check(v, d + (distance max 0))\n }\n }\n\n check(0, 0)\n write(n - visited.size)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = mmap[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toYesNo = if(x) \"yes\" else \"no\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def bitCount: Int = java.lang.Integer.bitCount(x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def mmap[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]\n def memoize[A, B](f: A => B): A ==> B = mmap[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeLine(obj: Any*): this.type = {\n if (obj.isEmpty) printer.println() else obj foreach printer.println\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "0c4bc51e5be9cc642f62d2b3df2bddc4"} {"source_code": "import scala.concurrent.Future\nimport scala.reflect.ClassTag\nimport scala.reflect.runtime.universe._\n\nobject Main2 extends App {\n\n import java.io._\n import java.util.{StringTokenizer}\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n val a = in.nextLine.split(' ').map(_.toInt)\n val b = in.nextLine.split(' ').map(_.toInt)\n val zeros = a.zip(b).filter(_._1 == 0).count(_._2 == 0)\n val c = a.zip(b).filter(p => p._1 != 0).map(norm).groupBy(x => x).map(_._2.size)\n\n def norm(pair: (Int, Int)): (Int, Int) = {\n val g = gcd(pair._1.abs, pair._2.abs)\n var x = pair._1 / g\n var y = pair._2 / g\n if (x < 0) {\n x = x.abs\n y = -y\n }\n (x, y)\n }\n def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)\n\n if (c.isEmpty)\n out.print(zeros)\n else\n out.print(c.max + zeros)\n\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Fraction(a: Int, b: Int)\n object Fraction {\n // bが正になるようにそろえる\n def make(a: Int, b: Int): Fraction = {\n val (aa, bb) = if (b < 0) (-a, -b) else (a, b)\n val g = gcd(aa, bb)\n Fraction(aa / g, bb / g)\n }\n }\n\n def solve(): Unit = {\n val N = ni()\n val A, B = na(N)\n\n var online = 0\n var zeros = 0\n var d_zero = 0\n val cnt = mutable.Map[Fraction, Int]().withDefaultValue(0)\n REP(N) { i =>\n if (B(i) == 0) {\n if (A(i) == 0) zeros += 1\n else d_zero += 1\n }\n else if (A(i) != 0) {\n val f = Fraction.make(B(i), A(i))\n debug(f.toString)\n val v = cnt(f) + 1\n cnt(f) = v\n online = max(v, online)\n }\n }\n\n debug(s\"online:$online d_zero:$d_zero zero:$zeros\")\n val ans = max(online, d_zero) + zeros\n out.println(ans)\n }\n\n\n def gcd(a: Int, b: Int): Int = {\n if (b == 0) a\n else gcd(b, a % b)\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugNum(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Fraction(a: Int, b: Int)\n object Fraction {\n // bが正になるようにそろえる\n def make(a: Int, b: Int): Fraction = {\n val (aa, bb) = if (b < 0) (-a, -b) else (a, b)\n val g = gcd(aa, bb)\n Fraction(aa / g, bb / g)\n }\n }\n\n def solve(): Unit = {\n val N = ni()\n val A, B = na(N)\n\n var online = 0\n var zeros = 0\n val cnt = mutable.Map[Fraction, Int]().withDefaultValue(0)\n REP(N) { i =>\n if (B(i) == 0) {\n if (A(i) == 0) zeros += 1\n }\n else if (A(i) != 0) {\n val f = Fraction.make(B(i), A(i))\n debug(f.toString)\n val v = cnt(f) + 1\n cnt(f) = v\n online = max(v, online)\n }\n }\n\n val ans = online + zeros\n out.println(ans)\n }\n\n\n def gcd(a: Int, b: Int): Int = {\n if (b == 0) a\n else gcd(b, a % b)\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugNum(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Fraction(a: Int, b: Int)\n object Fraction {\n // bが正になるようにそろえる\n def make(a: Int, b: Int): Fraction = {\n val (aa, bb) = if (b < 0) (-a, -b) else (a, b)\n val g = gcd(aa, bb)\n Fraction(aa / g, bb / g)\n }\n }\n\n def solve(): Unit = {\n val N = ni()\n val A, B = na(N)\n\n var online = 0\n var zeros = 0\n val cnt = mutable.Map[Fraction, Int]().withDefaultValue(0)\n REP(N) { i =>\n if (B(i) == 0) zeros += 1\n else if (A(i) != 0) {\n val f = Fraction.make(B(i), A(i))\n debug(f.toString)\n val v = cnt(f) + 1\n cnt(f) = v\n online = max(v, online)\n }\n }\n\n val ans = online + zeros\n out.println(ans)\n }\n\n\n def gcd(a: Int, b: Int): Int = {\n if (b == 0) a\n else gcd(b, a % b)\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugNum(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}, {"source_code": "import scala.concurrent.Future\nimport scala.reflect.ClassTag\nimport scala.reflect.runtime.universe._\n\nobject Main2 extends App {\n\n import java.io._\n import java.util.{StringTokenizer}\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n val a = in.nextLine.split(' ').map(_.toInt)\n val b = in.nextLine.split(' ').map(_.toInt)\n val zeros = a.zip(b).filter(_._1 == 0).filter(_._2 == 0).size\n val c = a.zip(b).filter(p => p._1 != 0 && p._2 != 0).map(norm).groupBy(x => x).map(_._2.size)\n\n def norm(pair: (Int, Int)): (Int, Int) = {\n val g = gcd(pair._1, pair._2)\n var x = pair._1 / g\n var y = pair._2 / g\n if (x < 0 && y > 0) {\n x = x.abs\n y = -y\n }\n (x, y)\n }\n def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)\n\n if (c.isEmpty)\n out.print(zeros)\n else\n out.print(c.max + zeros)\n\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}"}, {"source_code": "import scala.concurrent.Future\nimport scala.reflect.ClassTag\nimport scala.reflect.runtime.universe._\n\nobject Main2 extends App {\n\n import java.io._\n import java.util.{StringTokenizer}\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n val a = in.nextLine.split(' ').map(_.toInt)\n val b = in.nextLine.split(' ').map(_.toInt)\n val c = a.zip(b).map(norm).groupBy(x => x).map(_._2.size).max\n \n def norm(pair: (Int, Int)): (Int, Int) = {\n val g = gcd(pair._1, pair._2)\n if (pair._1 == 0 || pair._2 == 0) {\n pair\n } else {\n var x = pair._1 / g\n var y = pair._2 / g\n if (x < 0) {\n x = x.abs\n y = -y\n }\n (x, y)\n }\n }\n def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)\n\n out.print(c)\n\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}"}, {"source_code": "import scala.concurrent.Future\nimport scala.reflect.ClassTag\nimport scala.reflect.runtime.universe._\n\nobject Main2 extends App {\n\n import java.io._\n import java.util.{StringTokenizer}\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n val a = in.nextLine.split(' ').map(_.toInt)\n val b = in.nextLine.split(' ').map(_.toInt)\n val zeros = a.zip(b).filter(_._1 == 0).count(_._2 == 0)\n val c = a.zip(b).filter(p => p._1 != 0 && p._2 != 0).map(norm).groupBy(x => x).map(_._2.size)\n\n def norm(pair: (Int, Int)): (Int, Int) = {\n val g = gcd(pair._1.abs, pair._2.abs)\n var x = pair._1 / g\n var y = pair._2 / g\n if (x < 0 && y > 0) {\n x = x.abs\n y = -y\n }\n (x, y)\n }\n def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)\n\n if (c.isEmpty)\n out.print(zeros)\n else\n out.print(c.max + zeros)\n\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}"}, {"source_code": "import scala.concurrent.Future\nimport scala.reflect.ClassTag\nimport scala.reflect.runtime.universe._\n\nobject Main2 extends App {\n\n import java.io._\n import java.util.{StringTokenizer}\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n val a = in.nextLine.split(' ').map(_.toInt)\n val b = in.nextLine.split(' ').map(_.toInt)\n val zeros = a.zip(b).filter(_._1 == 0).count(_._2 == 0)\n val c = a.zip(b).filter(p => p._1 != 0 && p._2 != 0).map(norm).groupBy(x => x).map(_._2.size)\n\n def norm(pair: (Int, Int)): (Int, Int) = {\n val g = gcd(pair._1.abs, pair._2.abs)\n var x = pair._1 / g\n var y = pair._2 / g\n if (x < 0) {\n x = x.abs\n y = -y\n }\n (x, y)\n }\n def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)\n\n if (c.isEmpty)\n out.print(zeros)\n else\n out.print(c.max + zeros)\n\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}"}, {"source_code": "import scala.concurrent.Future\nimport scala.reflect.ClassTag\nimport scala.reflect.runtime.universe._\n\nobject Main2 extends App {\n\n import java.io._\n import java.util.{StringTokenizer}\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n val a = in.nextLine.split(' ').map(_.toInt)\n val b = in.nextLine.split(' ').map(_.toInt)\n val c = a.zip(b).map(norm).groupBy(x => x).map(_._2.size).max\n\n def norm(pair: (Int, Int)): (Int, Int) = {\n val g = gcd(pair._1, pair._2)\n if (g == 0) {\n pair\n } else {\n var x = pair._1 / g\n var y = pair._2 / g\n if (x < 0) {\n x = x.abs\n y = -y\n }\n (x, y)\n }\n }\n def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)\n\n out.print(c)\n\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}"}, {"source_code": "import scala.concurrent.Future\nimport scala.reflect.ClassTag\nimport scala.reflect.runtime.universe._\n\nobject Main2 extends App {\n\n import java.io._\n import java.util.{StringTokenizer}\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n val a = in.nextLine.split(' ').map(_.toInt)\n val b = in.nextLine.split(' ').map(_.toInt)\n val c = a.zip(b).filter(p => p._1 != 0 && p._2 != 0).map(norm).groupBy(x => x).map(_._2.size)\n\n def norm(pair: (Int, Int)): (Int, Int) = {\n val g = gcd(pair._1, pair._2)\n var x = pair._1 / g\n var y = pair._2 / g\n if (x < 0) {\n x = x.abs\n y = -y\n }\n (x, y)\n }\n def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)\n\n if (c.isEmpty)\n out.print(0)\n else\n out.print(c.max)\n\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}"}, {"source_code": "import scala.concurrent.Future\nimport scala.reflect.ClassTag\nimport scala.reflect.runtime.universe._\n\nobject Main2 extends App {\n\n import java.io._\n import java.util.{StringTokenizer}\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n val a = in.nextLine.split(' ').map(_.toInt)\n val b = in.nextLine.split(' ').map(_.toInt)\n val zeros = a.zip(b).filter(_._1 == 0).filter(_._2 == 0).size\n val c = a.zip(b).filter(p => p._1 != 0 && p._2 != 0).map(norm).groupBy(x => x).map(_._2.size)\n\n def norm(pair: (Int, Int)): (Int, Int) = {\n val g = gcd(pair._1, pair._2)\n var x = pair._1 / g\n var y = pair._2 / g\n if (x < 0) {\n x = x.abs\n y = -y\n }\n (x, y)\n }\n def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)\n\n if (c.isEmpty)\n out.print(zeros)\n else\n out.print(c.max + zeros)\n\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}"}], "src_uid": "c083988d20f434d61134f7b376581eb6"} {"source_code": "object CF501B extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n in.nextInt\n val s = in.next.toCharArray\n val t = in.next.toCharArray\n\n var dropped = 0\n\n if (s.sorted.zip(t.sorted).forall(x => x._1 == x._2)) {\n\n def findMoves(s: Array[Char], t: Array[Char], moves: List[Int]): List[Int] = {\n if (s.length == 0)\n return moves\n if (s(0) == t(0)) {\n dropped += 1\n return findMoves(s.tail, t.tail, moves)\n }\n\n val newMove = s.indexOf(t(0)) - 1\n findMoves(swap(s, newMove), t, moves :+ (newMove + dropped))\n }\n\n def swap(s: Array[Char], i: Int): Array[Char] = {\n val tmp = s(i)\n s(i) = s(i+1)\n s(i+1) = tmp\n return s\n }\n\n val moves = findMoves(s, t, List[Int]()).map(_+1) // 0 to 1 indexed\n out.println(moves.length)\n out.println(moves.mkString(\" \"))\n }\n else {\n out.println(\"-1\")\n }\n }\n\n solve\n out.flush\n out.close\n}", "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject A {\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n val s = StdIn.readLine().toCharArray.toBuffer\n val t = StdIn.readLine().toCharArray.toBuffer\n\n val sm = s.groupBy(c => c).mapValues(_.length)\n val tm = t.groupBy(c => c).mapValues(_.length)\n\n val notPossible = (sm.keySet diff tm.keySet).nonEmpty || sm.keySet.exists(c => sm(c) != tm(c))\n\n if (notPossible) {\n println(-1)\n } else {\n if (s == t) {\n println(0)\n } else {\n var rmvd = 1\n val r = new ArrayBuffer[Int]()\n var i = 0\n while (i < t.length) {\n if (s(i) != t(i)) {\n val tmp = new ArrayBuffer[Int]()\n tmp += (i + rmvd)\n var j = i + 1\n while (s(j) != t(i)) {\n tmp += (j + rmvd)\n j += 1\n }\n\n s.remove(j)\n t.remove(i)\n rmvd += 1\n r ++= tmp.reverse\n } else {\n i += 1\n }\n }\n println(r.length)\n println(r.mkString(\" \"))\n }\n }\n }\n}\n"}, {"source_code": "object Main {\n import java.util\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N = sc.nextInt()\n val s, t = sc.next().toCharArray\n\n val s1 = s.clone()\n val t1 = t.clone()\n Sorting.quickSort(s1)\n Sorting.quickSort(t1)\n\n def swap(a: Int, b: Int): Unit = {\n val tmp = s(a)\n s(a) = s(b)\n s(b) = tmp\n }\n\n val swaps = ArrayBuffer[Int]()\n if (!util.Arrays.equals(s1, t1)) {\n out.println(-1)\n } else {\n rep(N) { i =>\n if (s(i) != t(i)) {\n val ix = s.indexOf(t(i), i + 1)\n (i until ix).reverse foreach { j =>\n swap(j, j + 1)\n swaps += j + 1\n }\n }\n }\n out.println(swaps.length)\n out.println(swaps.mkString(\" \"))\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}], "negative_code": [{"source_code": "object Main {\n import java.util\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N = sc.nextInt()\n val s, t = sc.next().toCharArray\n\n val s1 = s.clone()\n val t1 = t.clone()\n Sorting.quickSort(s1)\n Sorting.quickSort(t1)\n\n def swap(a: Int, b: Int): Unit = {\n val tmp = s(a)\n s(a) = s(b)\n s(b) = tmp\n }\n\n val swaps = ArrayBuffer[Int]()\n if (!util.Arrays.equals(s1, t1)) {\n out.println(-1)\n } else {\n rep(N) { i =>\n if (s(i) != t(i)) {\n val ix = s.indexOf(t(i))\n (i until ix).reverse foreach { j =>\n swap(j, j + 1)\n swaps += j + 1\n }\n }\n }\n out.println(swaps.length)\n out.println(swaps.mkString(\" \"))\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}], "src_uid": "48e323edc41086cae52cc0e6bdd84e35"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val map = Map(2 -> \"OMG>.< I don't know!\", 1 -> \"Rainbow's\", 0 -> \"Freda's\")\n println((1 to in.next().toInt).map{_ =>\n val v = in.next()\n val m = v.startsWith(\"miao.\")\n val r = v.endsWith(\"lala.\")\n if (m == r) 2\n else if (m) 1\n else 0\n }.map(map).mkString(\"\\n\"))\n}\n", "positive_code": [{"source_code": "import scala.io.Source\nobject A extends App {\n val size = readLine().toInt;\n for (_ <- 1 to size) {\n check(readLine())\n }\n\n def check(str: String) {\n var flag_lala = str.endsWith(\"lala.\");\n var flag_rainbow = str.startsWith(\"miao.\");\n if ((flag_lala ^ flag_rainbow) == false) {\n println(\"OMG>.< I don't know!\");\n } else {\n if (flag_lala) {\n println(\"Freda's\");\n } else {\n println(\"Rainbow's\");\n }\n }\n }\n\n}"}, {"source_code": "object A312 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n for(_ <- 1 to n) {\n val str = read\n if(str.startsWith(\"miao\") && str.endsWith(\"lala.\")) {\n out.println(\"OMG>.< I don't know!\")\n } else if (str.startsWith(\"miao.\")) {\n out.println(\"Rainbow's\")\n } else if (str.endsWith(\"lala.\")) {\n out.println(\"Freda's\")\n } else {\n out.println(\"OMG>.< I don't know!\")\n }\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "// package R185d2\n\nimport java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def isFreda(str: String): Boolean =\n str.matches(\"\"\".*lala\\.$\"\"\")\n\n def isRainbow(str: String): Boolean =\n str.matches(\"\"\"miao\\..*\"\"\")\n\n def answer(str: String): String =\n (isFreda(str), isRainbow(str)) match {\n case (true, false) => \"Freda's\"\n case (false, true) => \"Rainbow's\"\n case _ => \"OMG>.< I don't know!\"\n }\n\n for (i <- 0 until sc.nextLine.toInt)\n out.println(answer(sc.nextLine))\n\n out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n for(_ <- 1 to n) {\n val s = readLine()\n val st = s.startsWith(\"miao.\")\n val end = s.endsWith(\"lala.\")\n if (st && !end) println(\"Rainbow's\")\n else if(end && !st) println(\"Freda's\")\n else println(\"OMG>.< I don't know!\")\n }\n }\n}"}], "negative_code": [{"source_code": "//package R185d2\n\nimport java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def answer: String = {\n val Freda = \"\"\"(?:.* )?lala\\.$\"\"\".r\n val Rainbow = \"\"\"(?:.* )?miao\\.$\"\"\".r\n sc.nextLine match {\n case Freda() => \"Freda's\"\n case Rainbow() => \"Rainbow's\"\n case _ => \"OMG>.< I don't know!\"\n }\n }\n\n for (i <- 0 until sc.nextLine.toInt)\n out.println(answer)\n\n out.close\n}\n"}], "src_uid": "ee9ba877dee1a2843e885a18823cbff0"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n var Array(x1, y1) = in.next().split(' ').map(_.toLong)\n var Array(x2, y2) = in.next().split(' ').map(_.toLong)\n val n = in.next().toInt\n println((1 to n).map(_ => in.next().split(' ').map(_.toInt)).count{\n case(Array(a, b, c)) =>\n val home = a * x1 + b * y1 + c\n val university = a * x2 + b * y2 + c\n (home > 0 && university < 0) || (home < 0 && university > 0)\n })\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Coord(x: Double, y: Double) {\n def ccw: Coord = Coord(-y, x)\n def +(o: Coord) = Coord(x + o.x, y + o.y)\n }\n\n val EPS = 1e-9\n def lt(x: Double, y: Double) = x < y - EPS\n def le(x: Double, y: Double) = x < y + EPS\n def gt(x: Double, y: Double) = x > y - EPS\n def ge(x: Double, y: Double) = x > y + EPS\n def eq(x: Double, y: Double) = abs(x - y) < EPS\n\n def solve(): Unit = {\n val H, U = Coord(ni(), ni())\n val N = ni()\n\n val INF = 1e9.toInt\n\n\n def y(a: Int, b: Int, c: Int, x: Int) = {\n -(a.toDouble * x + c) / b\n }\n\n var ans = 0\n REP(N) { _ =>\n import java.awt.geom.{Line2D, Point2D}\n val a, b, c = ni()\n\n // Y軸に平行\n if (b == 0) {\n val x = -c.toDouble / a\n if (le(min(H.x, U.x), x) && le(x, max(H.x, U.x))) ans += 1\n } else {\n val p1 = Coord(-INF, y(a, b, c, -INF))\n val p2 = Coord(INF, y(a, b, c, INF))\n if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, H.x, H.y, U.x, U.y)) ans += 1\n }\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Coord(x: Double, y: Double) {\n def ccw: Coord = Coord(-y, x)\n def +(o: Coord) = Coord(x + o.x, y + o.y)\n }\n\n def solve(): Unit = {\n val H, U = Coord(ni(), ni())\n val N = ni()\n\n val INF = 1e9.toInt\n\n\n def y(a: Int, b: Int, c: Int, x: Int) = {\n -(a.toDouble * x + c) / b\n }\n\n var ans = 0\n REP(N) { _ =>\n import java.awt.geom.{Line2D, Point2D}\n val a, b, c = ni()\n\n // Y軸に平行\n if (b == 0) {\n val x = -c // 本当は-c/a なんだけどdoule精度が怖い\n if (min(H.x, U.x).toLong * a <= x && x <= max(H.x, U.x).toLong * a) ans += 1\n } else {\n val p1 = Coord(-INF, y(a, b, c, -INF))\n val p2 = Coord(INF, y(a, b, c, INF))\n if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, H.x, H.y, U.x, U.y)) ans += 1\n }\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Coord(x: Double, y: Double) {\n def ccw: Coord = Coord(-y, x)\n def +(o: Coord) = Coord(x + o.x, y + o.y)\n }\n\n def solve(): Unit = {\n val H, U = Coord(ni(), ni())\n val N = ni()\n\n val INF = 1e9.toInt\n\n\n def y(a: Int, b: Int, c: Int, x: Int) = {\n -(a.toDouble * x + c) / b\n }\n\n var ans = 0\n REP(N) { _ =>\n import java.awt.geom.{Line2D, Point2D}\n val a, b, c = ni()\n val p1 = Coord(-INF, y(a, b, c, -INF))\n val p2 = Coord(INF, y(a, b, c, INF))\n if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, H.x, H.y, U.x, U.y)) ans += 1\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Coord(x: Double, y: Double) {\n def ccw: Coord = Coord(-y, x)\n def +(o: Coord) = Coord(x + o.x, y + o.y)\n }\n\n def solve(): Unit = {\n val H, U = Coord(ni(), ni())\n val N = ni()\n\n val INF = 1e9.toInt\n\n\n def y(a: Int, b: Int, c: Int, x: Int) = {\n -(a.toDouble * x + c) / b\n }\n\n var ans = 0\n REP(N) { _ =>\n import java.awt.geom.{Line2D, Point2D}\n val a, b, c = ni()\n\n // Y軸に平行\n if (b == 0) {\n val x = -c // 本当は-c/a なんだけどdoule精度が怖い\n if (min(H.x, U.x).toLong * a <= x && x <= max(H.x, U.x).toLong) ans += 1\n } else {\n val p1 = Coord(-INF, y(a, b, c, -INF))\n val p2 = Coord(INF, y(a, b, c, INF))\n if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, H.x, H.y, U.x, U.y)) ans += 1\n }\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n var Array(x1, y1) = in.next().split(' ').map(_.toInt)\n var Array(x2, y2) = in.next().split(' ').map(_.toInt)\n val n = in.next().toInt\n println((1 to n).map(_ => in.next().split(' ').map(_.toInt)).count{\n case(Array(a, b, c)) =>\n val home = a * x1 + b * y1 + c\n val university = a * x2 + b * y2 + c\n (home > 0 && university < 0) || (home < 0 && university > 0)\n })\n}"}], "src_uid": "783df1df183bf182bf9acbb99208cdb7"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N, K = nl()\n\n def step(n: Long): Long = {\n if (n == 0) 0\n else {\n val r = n % K\n r + (if (n / K > 0) step(n / K) + 1 else 0)\n }\n }\n\n out.println(step(N))\n }\n }\n}", "positive_code": [{"source_code": "//package codeforces\n\n/*\nhttps://codeforces.com/contest/1175/problem/A\n */\nobject FromHeroToZero {\n\n def countStepsToZero(k: Long)(n: Long, result: Long): Long = {\n if (n == 0) result\n else {\n n % k match {\n case 0 => countStepsToZero(k)(n / k, result + 1)\n case r => countStepsToZero(k)(n - r, result + r)\n }\n }\n\n }\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(n, k) = io.StdIn.readLine().split(\" \").map(_.toLong)\n\n println(countStepsToZero(k)(n, 0))\n\n }\n }\n\n}\n"}], "negative_code": [], "src_uid": "00b1e45e9395d23e850ce1a0751b8378"} {"source_code": "import java.util.StringTokenizer\n\nimport scala.io.StdIn\n\nobject Main {\n object Scanner {\n private var st: StringTokenizer = _\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(StdIn.readLine())\n }\n st.nextToken()\n }\n\n def nextInt: Int = nextToken().toInt\n def nextLong: Long = nextToken().toLong\n def nextShort: Short = nextToken().toShort\n def nextByte: Byte = nextToken().toByte\n }\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to Scanner.nextInt) {\n if (Scanner.nextInt % 4 == 0) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n }\n}", "positive_code": [{"source_code": "\nobject A extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n// val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val n = in.nextInt()\n\n n.times {\n val m = in.nextInt()\n\n val t = m - 4\n if (t < 0) {\n println(\"NO\")\n } else {\n if (t % 4 == 0) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}, {"source_code": "\n\nobject ProblemA extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n for (_ <- 1 to t) {\n val n = in.nextInt()\n val res = if (n % 4 == 0) {\n \"YES\"\n } else {\n \"NO\"\n }\n\n println(res)\n }\n\n\n}\n"}], "negative_code": [{"source_code": "\nobject A extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n// val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val n = in.nextInt()\n\n n.times {\n val m = in.nextInt()\n\n val t = m - 4\n if (t < 0) {\n println(\"NO\")\n } else {\n if (t % 2 == 0) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}"}, {"source_code": "\n\nobject ProblemA extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n for (_ <- 1 to t) {\n val n = in.nextInt()\n val res = if (n % 2 == 0) {\n \"YES\"\n } else {\n \"NO\"\n }\n\n println(res)\n }\n\n\n}\n"}], "src_uid": "07e56d4031bcb119d2f684203f7ed133"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val str = in.next()\n var sorted = str.groupBy(x => x).map(x => x._2.length).toList.sorted.reverse\n var left = k\n var result = 0l\n while (left > 0) {\n val count = sorted.head\n sorted = sorted.tail\n val min = Math.min(left, count)\n result += min.toLong * min\n left -= min\n }\n println(result)\n}", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _462B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val k = next.toInt\n val s = next\n val g = s.groupBy(ch => ch).toArray.sortBy(i => -i._2.length)\n\n def doit(i: Int, k: Int, acc: Long): Long = {\n if (k == 0) acc\n else {\n doit(i + 1, 0 max (k - g(i)._2.length), acc + (k min g(i)._2.length).toLong * (k min g(i)._2.length))\n }\n }\n println(doit(0, k, 0))\n}\n"}, {"source_code": "import scala.collection.mutable\n\n/**\n * Created by lurker on 2014. 8. 15..\n */\nobject CF263_2 extends App {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n val Array(n, k) = readInts(2)\n val inputStr = readLine()\n\n val map = for((k, v) <- inputStr.groupBy(identity)) yield {\n (k, v.length)\n }\n val l = map.toArray.sortBy(-_._2)\n var remaink:Long = k\n var i = 0\n var result = 0L\n while(remaink > 0) {\n val cantake:Long = remaink min l(i)._2\n result += (cantake * cantake)\n remaink -= cantake\n i += 1\n }\n println(result)\n\n}"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _462B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val k = next.toInt\n val s = next\n val g = s.groupBy(ch => ch).toArray.sortBy(i => -i._2.length)\n\n def doit(i: Int, k: Int, acc: Int): Int = {\n if (k == 0) acc\n else {\n doit(i + 1, 0 max (k - g(i)._2.length), acc + (k min g(i)._2.length) * (k min g(i)._2.length))\n }\n }\n println(doit(0, k, 0))\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val str = in.next()\n var sorted = str.groupBy(x => x).map(x => x._2.length).toList.sorted.reverse\n var left = k\n var result = 0\n while (left > 0) {\n val count = sorted.head\n sorted = sorted.tail\n val min = Math.min(left, count)\n result += min * min\n left -= min\n }\n println(result)\n}"}, {"source_code": "import scala.collection.mutable\n\n/**\n * Created by lurker on 2014. 8. 15..\n */\nobject CF263_2 extends App {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n val Array(n, k) = readInts(2)\n val inputStr = readLine()\n\n val map = for((k, v) <- inputStr.groupBy(identity)) yield {\n (k, v.length)\n }\n val l = map.toArray.sortBy(-_._2)\n var remaink = k\n var i = 0\n var result = 0\n while(remaink > 0) {\n val cantake = remaink min l(i)._2\n result += (cantake * cantake)\n remaink -= cantake\n i += 1\n }\n println(result)\n\n}\n"}, {"source_code": "import scala.collection.mutable\n\n/**\n * Created by lurker on 2014. 8. 15..\n */\nobject CF263_2 extends App {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n val Array(n, k) = readInts(2)\n val inputStr = readLine()\n\n val map = for((k, v) <- inputStr.groupBy(identity)) yield {\n (k, v.length)\n }\n val l = map.toArray.sortBy(-_._2)\n var remaink = k\n var i = 0\n var result = 0L\n while(remaink > 0) {\n val cantake = remaink min l(i)._2\n result += (cantake * cantake)\n remaink -= cantake\n i += 1\n }\n println(result)\n\n}"}], "src_uid": "480defc596ee5bc800ea569fd76dc584"} {"source_code": "object A702 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n\n var ret = 1\n var curr = 1\n for(i <- input.indices) {\n if(i == 0) {\n ret = 1\n curr = 1\n } else {\n if(input(i) > input(i-1)) {\n curr += 1\n ret = math.max(ret, curr)\n } else {\n ret = math.max(ret, curr)\n curr = 1\n }\n }\n }\n\n println(ret)\n }\n}", "positive_code": [{"source_code": "/**\n * Created for cf\n */\n\nimport scala.io._\n\n/**\n * Cheat Sheet:\n * Input: scala.io.StdIn\n * Output: println\n */\n/*\nobject main {\n val n = StdIn.readInt()\n val arr = StdIn.readLine().split(' ').map(x => x.toInt).toSeq\n\n def bin_search(dp: Map[Int, Int], l: Int, r: Int, key: Int): Int = {\n if(l == r) l\n else {\n val mid = l + r >> 1\n dp.get(mid) match {\n case Some(x) =>\n if (x < key) math.max(mid, bin_search(dp, math.min(r, mid + 1), r, key))\n else bin_search(dp, l, math.max(mid - 1, l), key)\n case None => bin_search(dp, l, math.max(l, mid - 1), key)\n }\n }\n }\n\n def calc(n: Int): (Int, Map[Int, Int])= {\n if(n == 0) (1, Map(0 -> Int.MinValue, 1 -> arr.head) )\n else {\n val (len, dp) = calc(n - 1)\n val idx = bin_search(dp, 0, n + 1, arr(n))\n (idx + 1, dp.updated(idx + 1, math.min(dp.getOrElse(idx + 1, Int.MaxValue), arr(n))))\n }\n }\n\n def main(args: Array[String]): Unit = {\n println(s\"${calc(n - 1)._1}\")\n }\n}\n*/\n\nobject main {\n val n = StdIn.readInt()\n val arr = StdIn.readLine().split(' ').map(x => x.toInt).toSeq\n\n def main(args: Array[String]): Unit = {\n val ans = arr.tail.foldLeft( (arr.head, (1, 1) ) ) ((pr, x) => {\n val (last, (len, ans) ) = pr\n if(x > last) (x, (len + 1, math.max(ans, len + 1)))\n else (x, (1, ans))\n })\n println(s\"${ans._2._2}\")\n }\n}"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val n = lines.next().toInt\n val (maxL, curL, _) = lines.next().split(' ').map(_.toInt).foldLeft(0, 0, -1) {\n case ((maxLength, currentLength, lastEl), el) if el > lastEl => (maxLength, currentLength + 1, el)\n case ((maxLength, currentLength, lastEl), el) => (Math.max(maxLength, currentLength), 1, el)\n }\n\n println(Math.max(maxL, curL))\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Solution extends App {\n val n = readInt\n val a = readLine().split(\" \").map(_.toInt)\n var ans = 1\n var len = 1\n for (right <- 0 until a.length) {\n if (right > 0) {\n if (a(right) > a(right - 1)) {\n len += 1\n ans = math.max(len, ans)\n } else {\n len = 1\n }\n }\n }\n println(ans)\n}\n"}], "negative_code": [{"source_code": "/**\n * Created for cf\n */\n\nimport scala.io._\n\n/**\n * Cheat Sheet:\n * Input: scala.io.StdIn\n * Output: println\n */\n\nobject main {\n val n = StdIn.readInt()\n val arr = StdIn.readLine().split(' ').map(x => x.toInt).toSeq\n\n def main(args: Array[String]): Unit = {\n val ans = arr.tail.foldLeft( (arr.head, 1) ) ((pr, x) => {\n val (last, len) = pr\n if(x > last) (x, len + 1)\n else (x, 1)\n })\n println(s\"${ans._2}\")\n }\n}\n"}], "src_uid": "4553b327d7b9f090641590d6492c2c41"} {"source_code": "import java.io.PrintWriter\r\nimport java.util.Scanner\r\n\r\nobject Solution {\r\n def solve(n: Int, points: Array[Int]): Seq[Int] = {\r\n def outgoing(pos: Int): Boolean = points(pos - 1) == 0\r\n\r\n // if there is n+1 -> 1 then:\r\n if (!outgoing(1)) {\r\n // n+1 -> 1 -> 2 -> ... -> n\r\n (n + 1) +: (1 to n)\r\n // otherwise it starts with 1 since you can't get into 1\r\n } else if (outgoing(n)) {\r\n // 1 -> 2 -> 3 ... -> n -> n+1\r\n (1 to n) :+ (n+1)\r\n } else {\r\n // 1 -> n+1 -> 2 -> ...\r\n // 1 -> 2 -> ... -> i -> n+1 -> i+1 -> ... -> n\r\n val posOpt = (1 until n).find(pos => outgoing(pos) && !outgoing(pos + 1))\r\n posOpt match {\r\n case Some(pos) => ((1 to pos) :+ (n + 1)) ++ ((pos + 1) to n)\r\n case None => Seq(-1)\r\n }\r\n }\r\n }\r\n\r\n def run(test: Int, input: Scanner, output: PrintWriter): Unit = {\r\n val n = input.nextInt()\r\n val points = (1 to n).map(_ => input.nextInt()).toArray\r\n output.println(solve(n, points).mkString(\" \"))\r\n }\r\n\r\n def run(input: Scanner, output: PrintWriter): Unit = {\r\n val tests = input.nextInt()\r\n\r\n (1 to tests).foreach { test =>\r\n run(test, input, output)\r\n output.flush()\r\n }\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n run(new Scanner(System.in), new PrintWriter(System.out))\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import java.io._\r\nimport scala.collection.immutable.TreeSet\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val reader = new BufferedReader(new java.io.InputStreamReader(System.in))\r\n val writer = new PrintWriter(System.out)\r\n def readInt(): Int = reader.readLine().toInt\r\n def readLong(): Long = reader.readLine().toLong\r\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\r\n def readArrayLong(): Array[Long] = reader.readLine().split(\" \").map(_.toLong)\r\n def readString(): String = reader.readLine()\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n\r\n def solve(t: Int = 0): Unit = {\r\n val n = readInt()\r\n val a = readArrayInt()\r\n if (a(0) == 1) {\r\n writer.print(s\"${n + 1} \")\r\n writer.print(Range(1,n + 1).mkString(\" \"))\r\n } else if (a(n - 1) == 0) {\r\n writer.print(Range(1,n + 1).mkString(\" \"))\r\n writer.print(s\" ${n + 1}\")\r\n } else {\r\n breakable{\r\n for (i <- 0 until n - 1) {\r\n if (a(i) == 0 && a(i + 1) == 1) {\r\n writer.print(Range(1, i + 2).mkString(\" \"))\r\n writer.print(s\" ${n + 1} \")\r\n writer.print(Range(i + 2, n + 1).mkString(\" \"))\r\n break()\r\n }\r\n }\r\n writer.print(-1)\r\n }\r\n }\r\n\r\n writer.println()\r\n }\r\n\r\n def main(args: Array[String]) {\r\n multiTest(solve)\r\n //solve()\r\n writer.flush()\r\n }\r\n}"}], "negative_code": [{"source_code": "import java.io.PrintWriter\r\nimport java.util.Scanner\r\n\r\nobject Solution {\r\n def solve(n: Int, points: Array[Int]): String = {\r\n def outgoing(pos: Int): Boolean = points(pos - 1) == 0\r\n\r\n // if there is n+1 -> 1 then:\r\n if (!outgoing(1)) {\r\n // n+1 -> 1 -> 2 -> ... -> n\r\n ((n + 1) +: (1 to n)).mkString(\" \")\r\n // otherwise it starts with 1 since you can't get into 1\r\n } else if (outgoing(n)) {\r\n // 1 -> 2 -> 3 ... -> n -> n+1\r\n ((1 to n) :+ (n+1)).mkString(\" \")\r\n } else {\r\n // 1 -> 2 -> ... -> i -> n+1 -> i+1 -> ... -> n\r\n val posOpt = (1 until n).find(pos => outgoing(pos) && !outgoing(pos + 1))\r\n posOpt match {\r\n case Some(pos) => ((1 to pos) :+ (n + 1) +: ((pos + 1) to n)).mkString(\" \")\r\n case None => \"-1\"\r\n }\r\n }\r\n }\r\n\r\n def run(test: Int, input: Scanner, output: PrintWriter): Unit = {\r\n val n = input.nextInt()\r\n val points = (1 to n).map(_ => input.nextInt()).toArray\r\n output.println(solve(n, points))\r\n }\r\n\r\n def run(input: Scanner, output: PrintWriter): Unit = {\r\n val tests = input.nextInt()\r\n\r\n (1 to tests).foreach { test =>\r\n run(test, input, output)\r\n output.flush()\r\n }\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n run(new Scanner(System.in), new PrintWriter(System.out))\r\n }\r\n}\r\n"}], "src_uid": "3f9525d74f4934eb9dca1b16c53662bf"} {"source_code": "\nobject P421B {\n def main(args: Array[String]): Unit = {\n val sc = new java.util.Scanner(System.in)\n // n: the number of vertices in the polygon\n // a: the needed angle, in degrees\n\n // val Array(n, a) = Source.stdin.getLines().next.split(\" \", 2).map(_.toInt)\n val n = sc.nextInt\n val a = sc.nextInt\n\n /** Output:\n * Print three space-separated integers: the vertices v1, v2, v3, which form Angle v1v2v3.\n * If there are multiple optimal solutions, print any of them.\n * The vertices are numbered from 1 to n in clockwise order.\n */\n\n /** One of the figures is regular convex n-gon (regular convex polygon with n sides).\n * Mister B must find three distinct vertices v1, v2, v3 such that\n * the angle (where v2 is the vertex of the angle, and v1 and v3 lie on its sides) is as close as possible to a.\n * In other words, the value should be minimum possible.\n */\n val minAngle = 180.0 / n\n val selectd = (1 to n - 2).minBy(i => math.abs(a - i * minAngle))\n print(Seq(2, 1, 2 + selectd).mkString(\" \"))\n }\n}\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject P421B {\n def main(args: Array[String]): Unit = {\n val sc = new java.util.Scanner(System.in)\n // n: the number of vertices in the polygon\n // a: the needed angle, in degrees\n\n // val Array(n, a) = Source.stdin.getLines().next.split(\" \", 2).map(_.toInt)\n val n = sc.nextInt\n val a = sc.nextInt\n\n /** Output:\n * Print three space-separated integers: the vertices v1, v2, v3, which form Angle v1v2v3.\n * If there are multiple optimal solutions, print any of them.\n * The vertices are numbered from 1 to n in clockwise order.\n */\n\n /** One of the figures is regular convex n-gon (regular convex polygon with n sides).\n * Mister B must find three distinct vertices v1, v2, v3 such that\n * the angle (where v2 is the vertex of the angle, and v1 and v3 lie on its sides) is as close as possible to a.\n * In other words, the value should be minimum possible.\n */\n \n val minAngle = 180.0 / n\n val selectd = (1 to n - 2).minBy(i => math.abs(a - i * minAngle))\n print(Seq(2, 1, 2 + selectd).mkString(\" \"))\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject P421B {\n def main(args: Array[String]): Unit = {\n val Array(n, a) = Source.stdin.getLines().next.split(\" \", 2).map(_.toInt)\n assume(3 <= n)\n assume(n <= 100000)\n assume(1 <= a)\n assume(a <= 180)\n\n // n: the number of vertices in the polygon\n // a: the needed angle, in degrees\n\n /** Output:\n * Print three space-separated integers: the vertices v1, v2, v3, which form Angle v1v2v3.\n * If there are multiple optimal solutions, print any of them.\n * The vertices are numbered from 1 to n in clockwise order.\n */\n\n /** One of the figures is regular convex n-gon (regular convex polygon with n sides).\n * Mister B must find three distinct vertices v1, v2, v3 such that\n * the angle (where v2 is the vertex of the angle, and v1 and v3 lie on its sides) is as close as possible to a.\n * In other words, the value should be minimum possible.\n */\n\n val interiorAngle = (n - 2) * 180.0 / n\n val minAngle = interiorAngle / (n - 2)\n val selectd = (1 to n - 2).minBy(i => math.abs(a - i * minAngle))\n print(Seq(2, 1, 2 + selectd).mkString(\" \"))\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject P421B {\n def main(args: Array[String]): Unit = {\n val sc = new java.util.Scanner(System.in)\n // n: the number of vertices in the polygon\n // a: the needed angle, in degrees\n\n // val Array(n, a) = Source.stdin.getLines().next.split(\" \", 2).map(_.toInt)\n val n = sc.nextInt\n val a = sc.nextInt\n\n /** Output:\n * Print three space-separated integers: the vertices v1, v2, v3, which form Angle v1v2v3.\n * If there are multiple optimal solutions, print any of them.\n * The vertices are numbered from 1 to n in clockwise order.\n */\n\n /** One of the figures is regular convex n-gon (regular convex polygon with n sides).\n * Mister B must find three distinct vertices v1, v2, v3 such that\n * the angle (where v2 is the vertex of the angle, and v1 and v3 lie on its sides) is as close as possible to a.\n * In other words, the value should be minimum possible.\n */\n\n val interiorAngle = (n - 2) * 180.0 / n\n val minAngle = interiorAngle / (n - 2)\n val selectd = (1 to n - 2).minBy(i => math.abs(a - i * minAngle))\n print(Seq(2, 1, 2 + selectd).mkString(\" \"))\n }\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextBoolean: Boolean = next.equalsIgnoreCase(\"1\")\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n\n override def toString = s\"MultiHashSet($map)\"\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n *\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val a = nextDouble\n val inner = (180.toDouble * (n - 2.toDouble)) / n.toDouble\n var min = inner\n var number = 3\n val outer = 360.toDouble / n\n for (i <- 4 to n) {\n val next = inner - ((i.toDouble - 3.toDouble) * outer / 2.toDouble)\n if (Math.abs(a - min) > Math.abs(a - next)) {\n min = next\n number = i\n }\n }\n out.println(s\"1 2 $number\")\n\n return 0\n }\n}\n"}, {"source_code": "object _820B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n case class Point(id: Int, x: Double, y: Double)\n\n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n import Math._\n\n val n, a = read[Int]\n\n val largest = (180.0 * (n - 2))/n\n\n case class Angle(v1: Point, v2: Point, v3: Point) {\n val value: Double = {\n val d = toDegrees(\n atan2(v3.x - v2.x, v3.y - v2.y) -\n atan2(v1.x - v2.x, v1.y - v2.y)\n ).abs\n if (d > largest + 1e-5) 360 - d else d\n }\n\n val score: Double = (a - value).abs\n\n override def toString = s\"${v1.id} ${v2.id} ${v3.id}\"\n }\n\n val v = IndexedSeq.tabulate(n) {i =>\n val theta = 2*i*PI/n\n Point(i + 1, sin(theta), cos(theta))\n }\n\n val triangles = for {\n i <- 2 until n\n Seq(v1, v2, v3) <- Seq(v(0), v(1), v(i)).permutations\n } yield Angle(v1, v2, v3)\n\n val ans = triangles.minBy(_.score)\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject P421B {\n def main(args: Array[String]): Unit = {\n val Array(n, a) = Source.stdin.getLines().next.split(\" \", 2).map(_.toInt)\n assume(3 <= n)\n assume(n <= 100000)\n assume(1 <= a)\n assume(a <= 180)\n\n // n: the number of vertices in the polygon\n // a: the needed angle, in degrees\n\n /** Output:\n * Print three space-separated integers: the vertices v1, v2, v3, which form Angle v1v2v3.\n * If there are multiple optimal solutions, print any of them.\n * The vertices are numbered from 1 to n in clockwise order.\n */\n\n /** One of the figures is regular convex n-gon (regular convex polygon with n sides).\n * Mister B must find three distinct vertices v1, v2, v3 such that\n * the angle (where v2 is the vertex of the angle, and v1 and v3 lie on its sides) is as close as possible to a.\n * In other words, the value should be minimum possible.\n */\n\n val interiorAngle = (n - 2) * 180.0 / n\n val minAngle = interiorAngle / (n - 2)\n val selectd = (1 to n - 2).minBy(i => math.abs(a - i * minAngle))\n print(Seq(1, 2, 2 + selectd).mkString(\" \"))\n }\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextBoolean: Boolean = next.equalsIgnoreCase(\"1\")\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n\n override def toString = s\"MultiHashSet($map)\"\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n *\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val a = nextDouble\n val inner = (180.toDouble * (n - 2.toDouble)) / n.toDouble\n var min = inner\n var number = 3\n val outer = 360.toDouble / n\n for (i <- 4 to n) {\n val next = inner - ((i.toDouble - 3.toDouble) * outer / 2.toDouble)\n println(next)\n if (Math.abs(a - min) > Math.abs(a - next)) {\n min = next\n number = i\n }\n }\n out.println(s\"1 2 $number\")\n\n return 0\n }\n}\n"}], "src_uid": "3cdd85f86c77afd1d3b0d1e951a83635"} {"source_code": "import scala.io.StdIn.readLine\r\n\r\nobject Solution {\r\n\r\n def rsi() = readLine().split(\"\\\\s+\").map(_.toInt)\r\n\r\n def solve(n: Int) = {\r\n if (n == 5) println(\"2 1 1 1\")\r\n else if (n % 4 == 0) println(s\"${n / 4} ${n / 4} ${n / 4} ${n / 4}\")\r\n else if (n % 2 == 0) println(s\"${n / 2 - 2} ${n / 2} 1 1\")\r\n else println(s\"${n - 5} 2 2 1\")\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n\r\n val cases = readLine.toInt\r\n for (\r\n i <- 0 until cases;\r\n n = readLine().toInt\r\n ) solve(n)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "\nimport scala.io.StdIn\n\nobject Task1 extends App {\n\n def getNextNum: Int = StdIn.readLine().toInt\n\n val dataSize = getNextNum\n\n for (_ <- 0 until dataSize) {\n val n = getNextNum\n println(s\"${n - 3} 1 1 1\")\n }\n\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\r\n\r\nobject Solution {\r\n\r\n def rsi() = readLine().split(\"\\\\s+\").map(_.toInt)\r\n\r\n def solve(n: Int) = {\r\n if (n % 4 == 0) println(s\"${n / 4} ${n / 4} ${n / 4} ${n / 4}\")\r\n else if (n % 2 == 0) println(s\"${n / 2 - 2} ${n / 2} 1 1\")\r\n else println(s\"${n - 5} 2 2 1\")\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n\r\n val cases = readLine.toInt\r\n for (\r\n i <- 0 until cases;\r\n n = readLine().toInt\r\n ) solve(n)\r\n }\r\n}\r\n"}], "src_uid": "f9f803c6850da1838d62a0cf85bb13f2"} {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject BitPlusPlus {\n def main(args: Array[String]) {\n val n = readInt\n val ops = for {\n i <- 1 to n\n line = readLine\n op = if (line.contains(\"+\")) 1 else -1\n } yield op\n println(ops.sum)\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readLine.toInt\n var sum = 0\n var i = 0\n while(i < n) {\n val line = readLine\n if (line.contains(\"+\")) sum = sum + 1 else sum = sum - 1\n i = i + 1\n }\n println(sum)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Test {\n def main(args1: Array[String]) {\n // val args = StdIn.readLine().split(\" \")\n // var (x: Long, y: Long) = (args(0).toLong, args(1).toLong)\n\n val count = StdIn.readInt\n\n var ret = 0L\n for (i <- 0 until count) {\n val a = StdIn.readLine()\n if (a.contains(\"X\")) {\n if (a.contains(\"++\")) {\n ret += 1\n }\n else if (a.contains(\"--\")) {\n ret -= 1\n }\n }\n }\n println(ret)\n }\n\n}"}, {"source_code": "object TwoEightTwoA {\n\n\tdef main(args : Array[String]) : Unit = {\n\t\tvar x=0\n\t\tvar n=readInt\n\t\tfor(i<-0 until n){\n\t\t\tvar op=readLine\n\t\t\top match{\n\t\t\t\tcase \"++X\"=>x+=1\n\t\t\t\tcase \"X++\"=>x+=1\n\t\t\t\tcase \"--X\"=>x-=1\n\t\t\t\tcase \"X--\"=>x-=1\n\t\t\t}\n\t\t}\n\t\tprintln(x)\n\t}\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Bits {\n def main(args: Array[String]): Unit = {\n val ins = Map(\"++x\" -> 1, \"x++\" -> 1, \"--x\" -> -1, \"x--\" -> -1)\n val n = readInt()\n val instructions = for (_ <- 0 until n) yield readLine().toLowerCase()\n val result = instructions.map(ins).reduce(_ + _)\n println(result)\n }\n}"}, {"source_code": "object Main extends App {\n def A71 = {\n def packWord(s: String, i: Int) : String = {\n s.length > i match {\n case false => s\n case true => s\"${s(0)}${s.length - 2}${s.last}\"\n }\n }\n (1 to readInt).map( _ => {\n readLine\n }).map(packWord(_, 10)).foreach(println(_))\n }\n def A4 = {\n println (readInt % 2 == 0 match {\n case true => println(\"YES\")\n case false => println(\"NO\")\n })\n }\n def A158 = {\n val k = readLine.split(' ')(1).toInt\n val xs = readLine.split(' ').map(_.toInt)\n val treshold = xs(k-1)\n println(xs.count(x => { x >= treshold && x > 0 }))\n }\n def A282: Unit = {\n println((1 to readInt).map( _ => {\n readLine\n }).foldLeft(0)((acc: Int,i: String) => {\n i.contains('+') match {\n case true => acc + 1\n case false => acc - 1\n }\n }))\n }\n A282\n}"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by vladimir on 06.06.17.\n */\nobject A282 extends App {\n var initialState = 0\n val n = StdIn.readInt()\n for (_ <- 0 until n) {\n val statement = StdIn.readLine()\n if (statement.contains('+'))\n initialState += 1\n else\n initialState -= 1\n }\n println(initialState)\n}\n"}, {"source_code": "object Bitpp {\n\tdef main(args:Array[String]) {\n\t\tvar x=0;\n\t\tvar n=readInt();\n\t\tvar s:String=\"\";\n\t\twhile (n>0) {\n\t\t\tn-=1;\n\t\t\ts=readLine();\n\t\t\tif (s.equals(\"X++\") || s.equals(\"++X\")) {\n\t\t\t\tx+=1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tx-=1;\n\t\t\t}\n\t\t}\n\t\tprintln(x);\n\t}\n}\n"}, {"source_code": "object bit_plus_plus extends App {\n var x = 0\n\n val commandIterations = scala.io.StdIn.readInt()\n\n for (i <- 1 to commandIterations) {\n val command = scala.io.StdIn.readLine()\n if (command.contains(\"++\")) x += 1\n else if (command.contains(\"--\")) x-=1\n }\n println(x)\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Main extends App {\n val n = StdIn.readLine().toInt\n\n var result = 0\n\n for (_ <- 1 to n) {\n val str = StdIn.readLine()\n str match {\n case \"X++\" => result += 1\n case \"++X\" => result += 1\n case \"X--\" => result -= 1\n case \"--X\" => result -= 1\n }\n }\n\n println(result)\n}"}, {"source_code": "object CF282A {\n def main(argc: Array[String]) {\n def deal(left: Int, x: Int) : Int = {\n if (left == 0) x\n else {\n readLine match {\n case \"X++\" | \"++X\" => deal(left - 1, x + 1)\n case \"X--\" | \"--X\" => deal(left - 1, x - 1)\n }\n }\n }\n println(deal(readLine.toInt, 0))\n }\n}\n"}, {"source_code": "object CF0282A extends App {\n\n val n = readInt()\n\n var accomulator = 0\n\n (1 to n).foreach(value => {\n val str = readLine()\n if (str.contains(\"++\")) {\n accomulator += 1\n } else if (str.contains(\"--\")) {\n accomulator -= 1\n }\n })\n\n\n println(accomulator)\n\n}\n"}, {"source_code": "object HelloWorld {\n def main(args: Array[String]): Unit = {\n \tvar n = readInt()\n \tvar ans = 0\n \tfor(i <- 0 until n){\n \t\tvar s = readLine()\n \t\tif (s(1) == '+'){\n \t\t\t\tans = ans +1\n \t\t}else\n \t\t\tans = ans- 1\n \t}\n \tprintln(ans)\n }\n}\n"}, {"source_code": "object task282A {\n def main(args:Array[String]) {\n var rv:Int=0;\n for (l <- io.Source.stdin.getLines.toList.drop(1)) {\n l(1) match {\n case '-' => rv-=1\n case '+' => rv+=1\n }\n }\n println(rv)\n }\n}"}, {"source_code": "object pratise {\n def main(args : Array[String]) {\n var res = 0\n (1 to readInt).map(_ => readLine).foreach {\n case \"++X\" | \"X++\" => res+=1\n case \"--X\" | \"X--\" => res-=1\n }\n println(res)\n }\n}\n"}, {"source_code": "object cf extends App{\n val t = readInt()\n var res = 0\n for (i <- 0 to t-1) {\n val s = readLine()\n if (s(1) == '+') {\n res += 1\n }\n else {\n res -= 1\n }\n }\n println(res)\n}"}, {"source_code": "object BitPlusPlus extends App {\n\n var value = 0\n\n def process(s: String) = {\n if (s.contains(\"++\")) value = value + 1\n if (s.contains(\"--\")) value = value - 1\n }\n\n (1 to readInt()).map(line => process(readLine()))\n println(value)\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nobject Solution {\n def readLines(n: Int) = Iterator.continually(readLine).take(n).toIterable\n def converge(expressions: Iterable[String]) = expressions map (_ match {\n case \"--X\" | \"X--\" => -1\n case \"++X\" | \"X++\" => 1\n })\n def main(args: Array[String]) = {\n val n = readLine.toInt\n println(converge(readLines(n)) reduceLeft (_ + _))\n }\n}\n"}, {"source_code": "\n object Main extends App {\n def A282 ={\n var acc =0\n (1 to readInt).map(_ => {\n readLine()(1) == '+' match {\n case true => acc=acc+1\n case false => acc=acc-1\n }\n\n\n })\n println(acc)\n\n\n }\n\n A282\n}"}, {"source_code": "object Solution282A extends App {\n\n def solution() {\n val result = 1.to(_int).map(_ => _string).foldLeft(0)((memo, str) => str match {\n case pl if pl.contains(\"+\") => memo + 1\n case _ => memo - 1\n })\n println(result)\n }\n\n //////////////////////////////////////////////////\n import java.util.Scanner\n val SC: Scanner = new Scanner(System.in)\n def _line: String = SC.nextLine\n def _int: Int = SC.nextInt\n def _long: Long = SC.nextLong\n def _string: String = SC.next\n solution()\n}"}, {"source_code": "object A extends App {\n val n = readLine.toInt\n def solve(): Int = {\n val line = readLine\n if(line == null) return 0\n val res: Int = \n if(line.startsWith(\"++\")) 1\n else if(line.startsWith(\"--\")) -1\n else if(line.endsWith(\"++\")) 1\n else if(line.endsWith(\"--\")) -1\n else 0\n res + solve\n }\n println(solve)\n}\n"}, {"source_code": "// http://codeforces.com/problemset/problem/282/A\n\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject BitPlusPlus {\n def main(args: Array[String]): Unit = {\n val n: Int = readInt()\n var x: Int = 0\n for(i <- 1 to n) {\n var line: String = readLine()\n if(line.contains(\"+\")) {\n x += 1\n } else if(line.contains(\"-\")) {\n x -= 1\n }\n }\n\n println(x)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\n/**\n * @author traff\n */\n\nobject Main extends App {\n val n = StdIn.readLine().toInt\n var res = 0\n for (i <- 1 to n) {\n res += (if (StdIn.readLine().contains(\"+\")) 1 else -1)\n }\n\n println(res)\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = readInt\n val ans = (0 until n).map { k =>\n val op = readLine\n if (op.contains(\"++\")) 1 else -1\n }.sum\n println(ans)\n }\n}\n"}, {"source_code": "object Solution extends App{\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n var count = 0\n Range(0, n).foreach {_ => \n if (in.next().contains('+')) count += 1 else count -= 1}\n println(count)\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val std = scala.io.StdIn\n val n = std.readInt()\n var result = 0\n for (i <- 0 until n) {\n std.readLine() match {\n case x if x.contains(\"++\") =>\n result +=1\n case x if x.contains(\"--\") =>\n result -=1\n }\n }\n println(result)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Bit extends App {\n\n val n = StdIn.readInt()\n var value = 0\n for (i <- Range(0, n)) {\n value = impl(StdIn.readLine(), value)\n }\n print(value)\n\n def impl(in: String, value: Int): Int = {\n in match {\n case \"++X\" | \"X++\" => value + 1\n case \"--X\" | \"X--\" => value - 1\n }\n }\n}"}, {"source_code": "\nobject Main {\n def main(args: Array[String]) = {\n val n = readLine.toInt\n var ans = 0\n\n for(i <- 1 to n)\n readLine match {\n case \"X++\" | \"++X\" => ans += 1\n case \"X--\" | \"--X\" => ans -= 1\n }\n\n println(ans)\n }\n}"}, {"source_code": "import scala.io.StdIn\n \nobject Bit extends App \n{\n val numOfLines = StdIn.readInt()\n def input: Seq[String] = for (_ <- 1 to numOfLines) yield StdIn.readLine()\n def sort = input.map \n {\n case word if (word.charAt(1) == '+') => 1\n case word if (word.charAt(1) == '-') => -1\n }\n println(sort.sum)\n}\n"}, {"source_code": "object HelloWorld {\n def main(args: Array[String]) {\n val n = readInt\n var c = 0\n for (i <- 0 until n) {\n c += (if(readLine.contains('+')) 1 else -1)\n }\n println(c)\n }\n}\n\n"}, {"source_code": "/**\n * Created by richard on 2015/6/8.\n */\nimport scala.io.StdIn\nobject hello {\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n var c = 0\n for (i<-0 until n) {\n c += (if (StdIn.readLine().charAt(1) == '+') 1 else -1)\n }\n println(c)\n }\n}\n"}, {"source_code": "object E {\n \n def main (args : Array[String]) : Unit ={\n var n = readInt\n var ans = 0\n for (i <- 1 to n){\n var s = readLine\n var bol = false\n for (j <- 0 to s.length()-1){\n if (s.charAt(j)=='+' && !bol){\n ans += 1;\n bol = true\n }else if (s.charAt(j)=='-' && !bol){\n ans -= 1;\n bol = true;\n }\n } \n }\n println(ans)\n }\n\n}"}, {"source_code": "object A282 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n var x = 0\n for(_ <- 0 until n) {\n val input = scala.io.StdIn.readLine\n if(Array(\"++X\", \"X++\").contains(input)) {\n x += 1\n } else {\n x -= 1\n }\n }\n println(x)\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P282A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextLine.toInt\n\n @tailrec\n def loop(acc: Int, i: Int): Int =\n if (i == N) acc\n else {\n val l = sc.nextLine\n if (l == \"X++\" || l == \"++X\") loop(acc + 1, i + 1)\n else loop(acc - 1, i + 1)\n }\n\n def solve: Int = loop(0, 0)\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "object Bitpp {\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in)\n\t\tval n = scanner.nextInt\n\t\tvar value = 0\n\t\tfor (i <- 0 to n) {\n\t\t val line = scanner.nextLine()\n\t\t line match {\n\t\t case \"++X\" | \"X++\" => value = value + 1\n\t\t case \"--X\" | \"X--\" => value = value - 1\n\t\t case _ => \n\t\t }\n\t\t}\n\t\tprintln(value)\n\t}\n}"}, {"source_code": "\nobject A {\n def READ: Array[Int] = readLine() split (\" \") map (_.toInt);\n def main(args: Array[String]) {\n var Array(n) = READ\n var r = 0;\n for (i <- 1 to n)\n r += (if (readLine().contains(\"++\")) 1 else -1);\n println(r)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Try1 {\n def main(args: Array[String]) {\n val in = new Scanner(System.in)\n var len,x, m, k, n, j, i: Int = 0\n var a = new Array[Int](51)\n n = in.nextInt()\n// k = in.nextInt()\n x=0\n var line = in.nextLine()\n for (i <- 1 to n) {\n line = in.nextLine()\n if (line(1)=='-') x-=1\n else x+=1\n }\n println(x)\n }\n}"}, {"source_code": "import java.io._\n\nobject Main extends App {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val n = reader.readLine.toInt\n val x = 0\n val arr = new Array[String](n)\n for (i <- 0 until n) arr(i) = reader.readLine()\n val plus = arr.count(_.contains(\"+\"))\n val minus = arr.count(_.contains(\"-\"))\n println(plus - minus)\n}\n"}, {"source_code": "object Codeforces282A extends App{\n \n def MainCompilation(linenumber:Int):Int={\n var ans:Int=0\n for (i <- 0 until linenumber){\n val temp:String=scala.io.StdIn.readLine\n if (temp==\"++X\" || temp==\"X++\") ans+=1\n else if (temp==\"--X\" || temp==\"X--\") ans-=1\n }\n return ans\n }\n val numberofline:Int=scala.io.StdIn.readInt\n println(MainCompilation(numberofline))\n\n}\n"}, {"source_code": "import java.io._\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n\n def ans = (for(_ <- 1 to readInt) yield if(reader.readLine()(1) == '+') 1 else -1).sum\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "/**\n * Created by vol on 9/18/14.\n */\nobject A282 extends App{\n val n = readInt()\n\n def loop(n:Int, i:Int, acc:Int):Int= {\n if (n == i) acc\n else {\n val sentence = readLine()\n if (sentence == \"X++\" || sentence == \"++X\") loop(n, i + 1, acc + 1)\n else loop(n, i + 1, acc -1)\n }\n }\n\n println(loop(n, 0, 0))\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val res = (1 to n).foldLeft(0) { (acc, unused) =>\n readLine() match {\n case s: String if s.contains(\"+\") => acc + 1\n case s: String if s.contains(\"-\") => acc - 1\n }\n }\n println(res)\n }\n}"}, {"source_code": "// Codeforces 282A\n\nobject _282A extends App {\n val scanner = new java.util.Scanner(System.in)\n val n = scanner.nextInt\n val operation = Array.fill(n)(scanner.next())\n val answer = \n operation.map(op => if (op.contains(\"++\")) 1 else -1).\n foldLeft(0)((accm, i) => accm + i)\n println(answer)\n}\n\n\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject BitProb extends App {\n val tItr = readInt()\n\n def countBits(i: Int = 0, acc: Int = 0): Int = {\n if(i == tItr) acc\n else {\n val inStr = readLine()\n if (inStr.matches(\"X\\\\+\\\\+\") || inStr.matches(\"\\\\+\\\\+X\")) countBits(i + 1, acc + 1)\n else if (inStr.matches(\"X--\") || inStr.matches(\"--X\")) countBits(i + 1, acc - 1)\n else countBits(i + 1, acc)\n }\n }\n\n val finalBit = countBits()\n\n print(finalBit)\n}\n"}, {"source_code": "object JuanDavidRobles282A {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n\n var lines : Int = StdIn.readInt()\n\n var command : String = \"\"\n var count : Int = 0\n\n for (i <- 0 until lines){\n command = StdIn.readLine()\n if (command contains(\"+\")){\n count = count + 1\n } else {\n count = count - 1\n }\n }\n\n println(count)\n }\n}\n"}, {"source_code": "object CF173Div2A {\n def main(args: Array[String]){\n var x = 0\n val n = readLine.toInt\n (1 to n).map(_ => readLine).foreach{\n case \"++X\"|\"X++\" => x += 1\n case \"--X\"|\"X--\" => x -= 1\n }\n println(x)\n }\n}"}, {"source_code": "object test extends App\n{\n var ans =0\n for(i <- 1 to readInt)\n ans += (if(readLine.contains(\"+\")) 1 else -1)\n print (ans)\n}"}, {"source_code": "object codeforces {\n def main(args: Array[String]): Unit = {\n val n: Int = scala.io.StdIn.readLine().toInt\n var x: Int = 0\n for (_ <- 0 until n){\n val line: String = scala.io.StdIn.readLine()\n if ((line.head == '+' && line(1) == '+') || (line(1) == '+' && line(2) == '+')){\n x+=1\n }else{\n if ((line.head == '-' && line(1) == '-') || (line(1) == '-' && line(2) == '-')){\n x-=1\n }\n }\n }\n println(x)\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Solution {\n\n\tvar n = readInt\n\tvar lns = Array.fill[String](n)(null)\n\tfor(i <- 0 until n) {\n\t\tlns(i) = readLine\n\t}\n\n\tdef main(args:Array[String]):Unit = {\n\t\tvar x = 0\n\t\tvar op = \"\"\n\t\tfor(i <- 0 until n) {\n\t\t\top = if(lns(i)(0) == 'X') lns(i)(1).toString + lns(i)(2).toString\n\t\t\t\t else lns(i)(0).toString + lns(i)(1).toString\n\t\t\tif(op == \"++\") x += 1\n\t\t\telse x -= 1\n\t\t}\n\t\tprintln(x)\n\t}\n\n}\n"}, {"source_code": "object main extends App{\n val s = readInt\n var cnt = 0\n for(i <- 0 until s){\n if(readLine.contains('+')) cnt+=1 else cnt-=1\n }\n println(cnt)\n}"}, {"source_code": "object main extends App{\n val s = readInt\n var cnt = 0\n (1 to s).map(_ => readLine).foreach{\n case \"++X\" | \"X++\" => cnt+=1\n case \"--X\" | \"X--\" => cnt-=1\n }\n println(cnt)\n}"}, {"source_code": "object A00282 extends App {\n val n = Console.readInt();\n var x = 0\n for (i <- 1 to n) {\n val str = Console.readLine();\n if (str.contains(\"++\")) {\n x = x + 1\n } else if (str.contains(\"--\")) {\n x = x - 1\n }\n }\n println(x)\n}\n"}], "negative_code": [{"source_code": "object CF282A {\n def main(argc: Array[String]) {\n def deal(left: Int, x: Int) {\n if (left == 0) x\n else {\n readLine match {\n case \"X++\" | \"++X\" => deal(left - 1, x + 1)\n case \"X--\" | \"--X\" => deal(left - 1, x - 1)\n }\n }\n }\n println(deal(readLine.toInt, 0))\n }\n}\n"}, {"source_code": "object Main extends App {\n def A258 ={\n var acc =0\n (1 to readInt).map(_ => {\n readLine()(1) == '+' match {\n case true => acc=acc+1\n case false => acc=acc-1\n }\n\n\n })\n println(acc)\n\n\n }\n\n\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P282A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextLine.toInt\n\n @tailrec\n def loop(acc: Int, i: Int): Int =\n if (i == N) acc\n else {\n val l = sc.nextLine\n if (l == \"X++\" || i == \"++X\") loop(acc + 1, i + 1)\n else loop(acc - 1, i + 1)\n }\n\n def solve: Int = loop(0, 0)\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n val tItr = readInt()\n\n def countBits(i: Int = 0, acc: Int = 0): Int = {\n if(i == tItr) acc\n else {\n val inStr = readLine()\n if (inStr.contains(\"++\")) countBits(i + 1, acc + 1)\n else countBits(i + 1, acc - 1)\n }\n }\n\n val finalBit = countBits().toBinaryString\n\n print(finalBit)\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject BitProb extends App {\n val tItr = readInt()\n\n def countBits(i: Int = 0, acc: Int = 0): Int = {\n if(i == tItr) acc\n else {\n val inStr = readLine()\n if (inStr.matches(\"X\\\\+\\\\+\") || inStr.matches(\"\\\\+\\\\+X\")) countBits(i + 1, acc | 1)\n else if (inStr.matches(\"X--\") || inStr.matches(\"--X\")) countBits(i + 1, acc & 0)\n else countBits(i + 1, acc)\n }\n }\n\n val finalBit = countBits()\n\n print(finalBit)\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject BitProb extends App {\n val tItr = readInt()\n\n def countBits(i: Int = 0, acc: Int = 0): Int = {\n if(i == tItr) acc\n else {\n val inStr = readLine()\n if (inStr.matches(\"X\\\\+\\\\+\") || inStr.matches(\"\\\\+\\\\+X\")) countBits(i + 1, acc + 1)\n else if (inStr.matches(\"X--\") || inStr.matches(\"--X\")) countBits(i + 1, acc - 1)\n else countBits(i + 1, acc)\n }\n }\n\n val finalBit = countBits().toBinaryString\n\n print(finalBit)\n}\n"}, {"source_code": "object main extends App{\n val s = readLine().toInt\n var cnt = 1\n for(i <- 1 to s){\n val t = readLine\n if(t.last ==\"+\" || t.head ==\"+\") cnt+=1\n if(t.last ==\"-\" || t.head ==\"-\") cnt-=1\n }\n println(cnt)\n}"}, {"source_code": "object main extends App{\n val s = readLine().toInt\n var cnt = 0\n for(i <- 1 to s){\n val t = readLine\n if(t.last ==\"+\" || t.head ==\"+\") cnt+=1\n if(t.last ==\"-\" || t.head ==\"-\") cnt-=1\n }\n println(cnt)\n}"}], "src_uid": "f3cf7726739290b280230b562cac7a74"} {"source_code": "import java.io.PrintWriter\r\n\r\nobject P1511C {\r\n\r\n\r\n import java.io.{BufferedReader, StringReader}\r\n\r\n def main(args: Array[String]): Unit = {\r\n import scala.io.Source\r\n val input = Source.stdin.bufferedReader()\r\n //val input = Source.fromFile(\"input.txt\").bufferedReader()\r\n //val input = new BufferedReader(new StringReader(\"7 5\\n2 1 1 4 3 3 1\\n3 2 1 1 4\"))\r\n // val input = new BufferedReader(new StringReader(\r\n // \"\"\"3 3\r\n // 1 2 3\r\n // 1 3 1\r\n // \"\"\"))\r\n val output = new PrintWriter(System.out)\r\n val executor = new Solution2(input, output)\r\n val startTime = System.currentTimeMillis()\r\n executor.solve()\r\n output.flush()\r\n val elapsed = System.currentTimeMillis() - startTime\r\n //println(s\"Elapsed: $elapsed\")\r\n }\r\n\r\n\r\n class Solution1(input: BufferedReader, output: PrintWriter) {\r\n\r\n import java.util\r\n import java.util.StringTokenizer\r\n\r\n def solve(): Unit = {\r\n val prms = new StringTokenizer(input.readLine())\r\n val deckSize = prms.nextToken().toInt\r\n val qs = prms.nextToken().toInt\r\n val deckParser = new StringTokenizer(input.readLine())\r\n val deck = new util.LinkedList[Byte]()\r\n for (_ <- 0 until deckSize) {\r\n deck.add(deckParser.nextToken().toByte)\r\n }\r\n val qParser = new StringTokenizer(input.readLine())\r\n for (_ <- 0 until qs) {\r\n val color = qParser.nextToken().toByte\r\n val index = deck.indexOf(color)\r\n output.print(index + 1)\r\n output.print(' ')\r\n deck.remove(index)\r\n deck.addFirst(color)\r\n }\r\n output.println()\r\n }\r\n }\r\n\r\n class Solution2(input: BufferedReader, output: PrintWriter) {\r\n\r\n import java.util.StringTokenizer\r\n\r\n def solve(): Unit = {\r\n val prms = new StringTokenizer(input.readLine())\r\n val deckSize, qs = prms.nextToken.toInt\r\n\r\n val deckParser = new StringTokenizer(input.readLine())\r\n val colorPlaces = Array.fill[Int](51)(99)\r\n for (place <- 0 until deckSize) {\r\n val color = deckParser.nextToken.toInt\r\n if (colorPlaces(color) == 99) {\r\n colorPlaces(color) = place\r\n }\r\n }\r\n\r\n val qParser = new StringTokenizer(input.readLine())\r\n for (_ <- 0 until qs) {\r\n val color = qParser.nextToken.toInt\r\n val place = colorPlaces(color)\r\n output.print(place + 1)\r\n output.print(' ')\r\n for (clr <- colorPlaces.indices) {\r\n val plc = colorPlaces(clr)\r\n if (plc < place) {\r\n colorPlaces(clr) = plc + 1\r\n }\r\n }\r\n colorPlaces(color) = 0\r\n }\r\n\r\n output.println()\r\n }\r\n }\r\n\r\n class Solution3(input: BufferedReader, output: PrintWriter) {\r\n\r\n import java.util.StringTokenizer\r\n\r\n private val head: MyNode = new MyNode(-1)\r\n private var last: MyNode = head\r\n\r\n private def add(color: Byte): Unit = {\r\n last.next = new MyNode(color)\r\n last = last.next\r\n }\r\n\r\n private def findIndexAndMoveToTop(color: Byte) = {\r\n var index = 1\r\n var parent = head\r\n var current = head.next\r\n while (current.value != color) {\r\n parent = current\r\n current = parent.next\r\n index += 1\r\n }\r\n if (current == last) {\r\n last = parent\r\n }\r\n parent.next = current.next\r\n current.next = head.next\r\n head.next = current\r\n index\r\n }\r\n\r\n def solve(): Unit = {\r\n val prms = new StringTokenizer(input.readLine())\r\n val deckSize, qs = prms.nextToken.toInt\r\n\r\n val deckParser = new StringTokenizer(input.readLine())\r\n for (_ <- 0 until deckSize) {\r\n add(deckParser.nextToken.toByte)\r\n }\r\n\r\n val qParser = new StringTokenizer(input.readLine())\r\n for (_ <- 0 until qs) {\r\n val color = qParser.nextToken.toByte\r\n val place = findIndexAndMoveToTop(color)\r\n output.print(place)\r\n output.print(' ')\r\n }\r\n\r\n output.println()\r\n }\r\n }\r\n\r\n class MyNode(val value: Byte) {\r\n var next: MyNode = _\r\n }\r\n\r\n}\r\n", "positive_code": [{"source_code": "object P1511C {\r\n\r\n import java.io._\r\n\r\n val out: OutputPrinter = new StringOutputPrinter(1024)\r\n //val out: OutputPrinter = new OutputPrinter()\r\n //val out: OutputPrinter = new BufferedOutputPrinter()\r\n val input = new InputReader(new InputStreamReader(System.in))\r\n //val input = new InputReader(new FileReader(\"input.txt\"))\r\n //val input = new InputReader(new StringReader(\"7 5\\n2 1 1 4 3 3 1\\n3 2 1 1 4\"))\r\n // val input = new InputReader(new StringReader(\r\n // \"\"\"3 3\r\n // 1 2 3\r\n // 1 3 1\r\n // \"\"\"))\r\n\r\n def main(args: Array[String]): Unit = {\r\n //val startTime = System.currentTimeMillis()\r\n\r\n val executor = new Solution3\r\n executor.solve()\r\n\r\n out.flush()\r\n //val elapsed = System.currentTimeMillis() - startTime\r\n //println(s\"Elapsed: $elapsed\")\r\n }\r\n\r\n\r\n class Solution1 {\r\n\r\n import java.util\r\n\r\n def solve(): Unit = {\r\n val deckSize, qs = input.nextInt\r\n val deck = new util.LinkedList[Byte]()\r\n input.forBytes(deckSize) { (_, color) => deck.add(color) }\r\n input.forBytes(qs) { (_, color) =>\r\n val index = deck.indexOf(color)\r\n out.print(index + 1)\r\n out.print(' ')\r\n deck.remove(index)\r\n deck.addFirst(color)\r\n }\r\n }\r\n }\r\n\r\n class Solution2 {\r\n\r\n def solve(): Unit = {\r\n val deckSize, qs = input.nextInt\r\n\r\n val colorPlaces = Array.fill[Int](51)(99)\r\n input.forBytes(deckSize) { (place, color) =>\r\n if (colorPlaces(color) == 99) {\r\n colorPlaces(color) = place\r\n }\r\n }\r\n\r\n input.forBytes(qs) { (_, color) =>\r\n val place = colorPlaces(color)\r\n out.print(place + 1)\r\n out.print(' ')\r\n for (clr <- colorPlaces.indices) {\r\n val plc = colorPlaces(clr)\r\n if (plc < place) {\r\n colorPlaces(clr) = plc + 1\r\n }\r\n }\r\n colorPlaces(color) = 0\r\n }\r\n }\r\n }\r\n\r\n class Solution3 {\r\n\r\n private val head: MyNode = new MyNode(-1)\r\n private var last: MyNode = head\r\n\r\n private def add(color: Byte): Unit = {\r\n last.next = new MyNode(color)\r\n last = last.next\r\n }\r\n\r\n private def findIndexAndMoveToTop(color: Byte) = {\r\n var index = 1\r\n var parent = head\r\n var current = head.next\r\n while (current.value != color) {\r\n parent = current\r\n current = parent.next\r\n index += 1\r\n }\r\n if (current == last) {\r\n last = parent\r\n }\r\n parent.next = current.next\r\n current.next = head.next\r\n head.next = current\r\n index\r\n }\r\n\r\n def solve(): Unit = {\r\n val deckSize, qs = input.nextInt\r\n input.forBytes(deckSize) { (_, color) => add(color) }\r\n input.forBytes(qs) { (_, color) =>\r\n val place = findIndexAndMoveToTop(color)\r\n out.print(place)\r\n out.print(' ')\r\n }\r\n }\r\n }\r\n\r\n class MyNode(val value: Byte) {\r\n var next: MyNode = _\r\n }\r\n\r\n class InputReader(reader: Reader) {\r\n\r\n import java.io.BufferedReader\r\n import java.util.StringTokenizer\r\n\r\n private val buffer = new BufferedReader(reader)\r\n private var parser: StringTokenizer = _\r\n\r\n private def next = {\r\n if (parser == null || !parser.hasMoreElements) {\r\n parser = new StringTokenizer(buffer.readLine)\r\n }\r\n parser.nextToken\r\n }\r\n\r\n def endl(): Unit = {\r\n parser = null\r\n }\r\n\r\n def nextByte = next.toByte\r\n\r\n def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)\r\n\r\n def nextInt = next.toInt\r\n\r\n def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)\r\n\r\n def nextLong = next.toLong\r\n\r\n def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)\r\n\r\n def nextDouble = next.toDouble\r\n\r\n def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)\r\n\r\n def nextString = next\r\n\r\n def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)\r\n\r\n private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {\r\n for (index <- 0 until num) op(index, readOp)\r\n }\r\n }\r\n\r\n class OutputPrinter {\r\n private val buffer = new StringBuilder() // faster if exists\r\n\r\n def print(c: Char): Unit = {}\r\n\r\n def print(i: Int): Unit = {}\r\n\r\n def print(s: String): Unit = {}\r\n\r\n def endl(): Unit = {}\r\n\r\n def flush(): Unit = {}\r\n }\r\n\r\n class DirectOutputPrinter extends OutputPrinter {\r\n\r\n override def print(c: Char): Unit = System.out.print(c)\r\n\r\n override def print(i: Int): Unit = System.out.print(i)\r\n\r\n override def print(s: String): Unit = System.out.print(s)\r\n\r\n override def endl(): Unit = System.out.println()\r\n\r\n override def flush(): Unit = System.out.flush()\r\n }\r\n\r\n class StringOutputPrinter(capacity: Int) extends OutputPrinter {\r\n private val buffer = new StringBuilder(capacity)\r\n\r\n override def print(c: Char): Unit = buffer.append(c)\r\n\r\n override def print(i: Int): Unit = buffer.append(i)\r\n\r\n override def print(s: String): Unit = buffer.append(s)\r\n\r\n override def endl(): Unit = buffer.append(\"\\n\")\r\n\r\n override def flush(): Unit = println(buffer.result())\r\n }\r\n\r\n class BufferedOutputPrinter extends OutputPrinter {\r\n private val buffer = new PrintWriter(System.out)\r\n\r\n override def print(c: Char): Unit = buffer.print(c)\r\n\r\n override def print(i: Int): Unit = buffer.print(i)\r\n\r\n override def print(s: String): Unit = buffer.print(s)\r\n\r\n override def endl(): Unit = buffer.println()\r\n\r\n override def flush(): Unit = buffer.flush()\r\n }\r\n\r\n}\r\n"}, {"source_code": "object P1511C {\r\n\r\n import java.io._\r\n\r\n val out = new StringBuilder(1024)\r\n val input = new InputReader(new InputStreamReader(System.in))\r\n\r\n def main(args: Array[String]): Unit = {\r\n val executor = new Solution3\r\n executor.solve()\r\n println(out.result())\r\n }\r\n\r\n\r\n class Solution3 {\r\n\r\n private val head: MyNode = new MyNode(-1)\r\n private var last: MyNode = head\r\n\r\n private def add(color: Byte): Unit = {\r\n last.next = new MyNode(color)\r\n last = last.next\r\n }\r\n\r\n private def findIndexAndMoveToTop(color: Byte) = {\r\n var index = 1\r\n var parent = head\r\n var current = head.next\r\n while (current.value != color) {\r\n parent = current\r\n current = parent.next\r\n index += 1\r\n }\r\n if (current == last) {\r\n last = parent\r\n }\r\n parent.next = current.next\r\n current.next = head.next\r\n head.next = current\r\n index\r\n }\r\n\r\n def solve(): Unit = {\r\n val deckSize, qs = input.nextInt\r\n input.forBytes(deckSize) { (_, color) => add(color) }\r\n input.forBytes(qs) { (_, color) =>\r\n val place = findIndexAndMoveToTop(color)\r\n out.append(place)\r\n out.append(' ')\r\n }\r\n }\r\n }\r\n\r\n class MyNode(val value: Byte) {\r\n var next: MyNode = _\r\n }\r\n\r\n class InputReader(reader: Reader) {\r\n\r\n import java.io.BufferedReader\r\n import java.util.StringTokenizer\r\n\r\n private val buffer = new BufferedReader(reader)\r\n private var parser: StringTokenizer = _\r\n\r\n private def next = {\r\n if (parser == null || !parser.hasMoreElements) {\r\n parser = new StringTokenizer(buffer.readLine)\r\n }\r\n parser.nextToken\r\n }\r\n\r\n def endl(): Unit = {\r\n parser = null\r\n }\r\n\r\n def nextByte = next.toByte\r\n\r\n def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)\r\n\r\n def nextInt = next.toInt\r\n\r\n def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)\r\n\r\n def nextLong = next.toLong\r\n\r\n def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)\r\n\r\n def nextDouble = next.toDouble\r\n\r\n def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)\r\n\r\n def nextString = next\r\n\r\n def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)\r\n\r\n private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {\r\n for (index <- 0 until num) op(index, readOp)\r\n }\r\n }\r\n\r\n}\r\n"}, {"source_code": "import java.io.PrintWriter\r\n\r\nobject P1511C {\r\n\r\n\r\n import java.io.{BufferedReader, StringReader}\r\n\r\n def main(args: Array[String]): Unit = {\r\n import scala.io.Source\r\n val input = Source.stdin.bufferedReader()\r\n //val input = Source.fromFile(\"input.txt\").bufferedReader()\r\n //val input = new BufferedReader(new StringReader(\"7 5\\n2 1 1 4 3 3 1\\n3 2 1 1 4\"))\r\n // val input = new BufferedReader(new StringReader(\r\n // \"\"\"3 3\r\n // 1 2 3\r\n // 1 3 1\r\n // \"\"\"))\r\n val output = new PrintWriter(System.out)\r\n val executor = new Solution3(input, output)\r\n val startTime = System.currentTimeMillis()\r\n executor.solve()\r\n output.flush()\r\n val elapsed = System.currentTimeMillis() - startTime\r\n //println(s\"Elapsed: $elapsed\")\r\n }\r\n\r\n\r\n class Solution1(input: BufferedReader, output: PrintWriter) {\r\n\r\n import java.util\r\n import java.util.StringTokenizer\r\n\r\n def solve(): Unit = {\r\n val prms = new StringTokenizer(input.readLine())\r\n val deckSize = prms.nextToken().toInt\r\n val qs = prms.nextToken().toInt\r\n val deckParser = new StringTokenizer(input.readLine())\r\n val deck = new util.LinkedList[Byte]()\r\n for (_ <- 0 until deckSize) {\r\n deck.add(deckParser.nextToken().toByte)\r\n }\r\n val qParser = new StringTokenizer(input.readLine())\r\n for (_ <- 0 until qs) {\r\n val color = qParser.nextToken().toByte\r\n val index = deck.indexOf(color)\r\n output.print(index + 1)\r\n output.print(' ')\r\n deck.remove(index)\r\n deck.addFirst(color)\r\n }\r\n output.println()\r\n }\r\n }\r\n\r\n class Solution2(input: BufferedReader, output: PrintWriter) {\r\n\r\n import java.util.StringTokenizer\r\n\r\n def solve(): Unit = {\r\n val prms = new StringTokenizer(input.readLine())\r\n val deckSize, qs = prms.nextToken.toInt\r\n\r\n val deckParser = new StringTokenizer(input.readLine())\r\n val colorPlaces = Array.fill[Int](51)(99)\r\n for (place <- 0 until deckSize) {\r\n val color = deckParser.nextToken.toInt\r\n if (colorPlaces(color) == 99) {\r\n colorPlaces(color) = place\r\n }\r\n }\r\n\r\n val qParser = new StringTokenizer(input.readLine())\r\n for (_ <- 0 until qs) {\r\n val color = qParser.nextToken.toInt\r\n val place = colorPlaces(color)\r\n output.print(place + 1)\r\n output.print(' ')\r\n for (clr <- colorPlaces.indices) {\r\n val plc = colorPlaces(clr)\r\n if (plc < place) {\r\n colorPlaces(clr) = plc + 1\r\n }\r\n }\r\n colorPlaces(color) = 0\r\n }\r\n\r\n output.println()\r\n }\r\n }\r\n\r\n class Solution3(input: BufferedReader, output: PrintWriter) {\r\n\r\n import java.util.StringTokenizer\r\n\r\n private val head: MyNode = new MyNode(-1)\r\n private var last: MyNode = head\r\n\r\n private def add(color: Byte): Unit = {\r\n last.next = new MyNode(color)\r\n last = last.next\r\n }\r\n\r\n private def findIndexAndMoveToTop(color: Byte) = {\r\n var index = 1\r\n var parent = head\r\n var current = head.next\r\n while (current.value != color) {\r\n parent = current\r\n current = parent.next\r\n index += 1\r\n }\r\n if (current == last) {\r\n last = parent\r\n }\r\n parent.next = current.next\r\n current.next = head.next\r\n head.next = current\r\n index\r\n }\r\n\r\n def solve(): Unit = {\r\n val prms = new StringTokenizer(input.readLine())\r\n val deckSize, qs = prms.nextToken.toInt\r\n\r\n val deckParser = new StringTokenizer(input.readLine())\r\n for (_ <- 0 until deckSize) {\r\n add(deckParser.nextToken.toByte)\r\n }\r\n\r\n val qParser = new StringTokenizer(input.readLine())\r\n for (_ <- 0 until qs) {\r\n val color = qParser.nextToken.toByte\r\n val place = findIndexAndMoveToTop(color)\r\n output.print(place)\r\n output.print(' ')\r\n }\r\n\r\n output.println()\r\n }\r\n }\r\n\r\n class MyNode(val value: Byte) {\r\n var next: MyNode = _\r\n }\r\n\r\n}\r\n"}, {"source_code": "\r\nobject P1511C {\r\n\r\n import java.io.{BufferedReader, InputStreamReader, PrintWriter, StringReader}\r\n import java.util.LinkedList\r\n import java.util.StringTokenizer\r\n\r\n def main(_argv: Array[String]): Unit = {\r\n val input = new BufferedReader(new InputStreamReader(System.in))\r\n //val input = new BufferedReader(new StringReader(\"7 5\\n2 1 1 4 3 3 1\\n3 2 1 1 4\"))\r\n val output = new PrintWriter(System.out)\r\n val executor = new Solution(input, output)\r\n executor.solve()\r\n output.close()\r\n }\r\n\r\n\r\n class Solution(input: BufferedReader, output: PrintWriter) {\r\n\r\n def solve(): Unit = {\r\n val prms = new StringTokenizer(input.readLine())\r\n val deckSize = prms.nextToken().toInt\r\n val qs = prms.nextToken().toInt\r\n val deckParser = new StringTokenizer(input.readLine())\r\n var deck = new LinkedList[Byte]()\r\n for (_ <- 0 until deckSize) {\r\n deck.add(deckParser.nextToken().toByte)\r\n }\r\n val qParser = new StringTokenizer(input.readLine())\r\n for (_ <- 0 until qs) {\r\n val color = qParser.nextToken().toByte\r\n val index = deck.indexOf(color)\r\n output.print(index + 1)\r\n output.print(' ')\r\n deck.remove(index)\r\n deck.addFirst(color)\r\n }\r\n output.println()\r\n }\r\n }\r\n\r\n}\r\n"}, {"source_code": "import java.io._\nimport java.util\n\nobject P1511C extends App {\n val br = new BufferedReader(new InputStreamReader(System.in))\n def readInt = br.readLine().toInt\n def readArray = br.readLine().split(\" \").map(_.toInt)\n val Array(n, q) = readArray\n val color = new util.LinkedList[Int]()\n readArray foreach { i =>\n color.add(i)\n }\n val query = readArray\n val ans = query map { i =>\n val firstIndex = color.indexOf(i)\n color.remove(firstIndex)\n color.addFirst(i)\n firstIndex + 1\n }\n println(ans.mkString(\" \"))\n}\n"}], "negative_code": [], "src_uid": "26aef004295df530352485ce53b47364"} {"source_code": "import scala.io.Source\nimport java.io.PrintWriter\nimport java.io.File\nimport scala.math._\n\nobject Olymp{\n def main(args: Array[String]): Unit = {\n val it = Source.fromFile(\"input.txt\").getLines\n val writer = new PrintWriter(new File(\"output.txt\" ))\n val n = it.next.toInt\n val t = it.next.split(' ').toList.map(s => s.toInt)\n val neg = t.foldLeft[Int](0)((acc, elem) => if (elem <= 0) acc+1 else acc)\n writer.println(t.take(n-1).foldLeft[Tuple3[Int, Int, Int]](Tuple3(0, neg, n))((acc, elem) => (acc, elem) match {\n case ((pos, neg, ans), elem) if elem < 0 => (pos, neg-1, min(ans, pos+neg-1))\n case ((pos, neg, ans), elem) if elem == 0 => (pos+1, neg-1, min(ans, pos+neg))\n case ((pos, neg, ans), elem) if elem > 0 => (pos+1, neg, min(ans, pos+neg+1))\n })._3)\n writer.close()\n }\n}", "positive_code": [{"source_code": "import scala.io.Source\nimport java.io.PrintWriter\n\nobject C234 {\n\n def main(args: Array[String]) {\n val source = Source.fromFile(\"input.txt\")\n var fileIter = source.getLines;\n var n = fileIter.next.toInt\n var arr = fileIter.next.split(\" \").map(_.toInt)\n var left = if (arr(0) < 0) 0 else 1\n var right = 0\n var i = 1\n while (i < n) {\n if (arr(i) <= 0) right += 1\n i += 1\n }\n var min = left + right\n i = 1\n n -= 1\n while (i < n) {\n if (arr(i) > 0) left += 1\n else if (arr(i) < 0) {\n right -= 1\n if (left + right < min) min = left + right\n }\n else { left +=1; right -= 1 }\n i += 1\n }\n val out = new PrintWriter(\"output.txt\")\n out.println(min)\n out.close()\n }\n\n}"}, {"source_code": "object Solution {\n import java.util.Scanner\n import java.io.PrintWriter\n import java.io.File\n\n def main(args:Array[String]) {\n val it = new Iterator[Int] {\n private val sc = new Scanner(new File(\"input.txt\"))\n def hasNext = sc.hasNextInt\n def next = sc.nextInt\n }\n val n = it.next\n val init = if (it.next < 0) 0 else 1\n val tempertures = it.take(n-2)\n\n val (pos, neg) = tempertures.foldLeft((init, init)) { case ((pos, neg), t) =>\n if (t > 0) {\n (pos min neg, neg+1)\n } else if (t < 0) {\n ((pos min neg) + 1, neg)\n } else {\n (pos+1, neg+1)\n }\n }\n val result = (pos min neg) + (if (it.next > 0) 0 else 1)\n\n val out = new PrintWriter(\"output.txt\")\n out.println(result)\n out.close\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\nimport java.io.PrintWriter\n\nobject C234 {\n\n def main(args: Array[String]) {\n val source = Source.fromFile(\"input.txt\")\n var fileIter = source.getLines;\n val n = fileIter.next.toInt\n var arr = fileIter.next.split(\" \").map(_.toInt)\n var left = if (arr(0) < 0) 0 else 1\n var right = 0\n var i = 1\n while (i < n) {\n if (arr(i) <= 0) right += 1\n i += 1\n }\n var min = left + right\n i = 1\n while (i < n) {\n if (arr(i) > 0) left += 1\n else if (arr(i) < 0) {\n right -= 1\n if (left + right < min) min = left + right\n }\n else { left +=1; right -= 1 }\n i += 1\n }\n val out = new PrintWriter(\"output.txt\")\n out.println(min)\n }\n\n}"}, {"source_code": "import scala.io.Source\nimport java.io.PrintWriter\n\nobject C234 {\n\n def main(args: Array[String]) {\n val source = Source.fromFile(\"input.txt\")\n var fileIter = source.getLines;\n val n = fileIter.next.toInt\n var arr = fileIter.next.split(\" \").map(_.toInt)\n var left = if (arr(0) < 0) 0 else 1\n var right = 0\n var i = 1\n while (i < n) {\n if (arr(i) <= 0) right += 1\n i += 1\n }\n var min = left + right\n i = 1\n while (i < n) {\n if (arr(i) > 0) left += 1\n else if (arr(i) < 0) {\n right -= 1\n if (left + right < min) min = left + right\n }\n else { left +=1; right -= 1 }\n i += 1\n }\n val out = new PrintWriter(\"output.txt\")\n out.println(min)\n out.close()\n }\n\n}"}, {"source_code": "import scala.io.Source\nimport java.io.PrintWriter\nimport java.io.File\nimport scala.math._\n\nobject Olymp{\n def main(args: Array[String]): Unit = {\n val it = Source.fromFile(\"input.txt\").getLines\n val writer = new PrintWriter(new File(\"output.txt\" ))\n val n = it.next.toInt\n val t = it.next.split(' ').toList.map(s => s.toInt)\n val neg = t.foldRight(0)((acc, elem) => if (elem < 0) acc+1 else acc)\n writer.println(t.take(n-1).foldLeft[Tuple3[Int, Int, Int]]((0, neg, n))((acc, elem) => if (elem < 0) (acc._1, acc._2-1, min(acc._3, acc._1+acc._2-1))\n else (acc._1+1, acc._2, min(acc._3, acc._1+1+acc._2)))._3)\n writer.close()\n }\n}"}, {"source_code": "import scala.io.Source\nimport java.io.PrintWriter\nimport java.io.File\nimport scala.math._\n\nobject Olymp{\n def main(args: Array[String]): Unit = {\n val it = Source.fromFile(\"input.txt\").getLines\n val writer = new PrintWriter(new File(\"output.txt\" ))\n val n = it.next.toInt\n val t = it.next.split(' ').toList.map(s => s.toInt)\n val neg = t.foldLeft[Int](0)((acc, elem) => if (elem < 0) acc+1 else acc)\n writer.println(t.take(n-1).foldLeft[Tuple3[Int, Int, Int]](Tuple3(0, neg, n))((acc, elem) => (acc, elem) match {\n case ((pos, neg, ans), elem) if elem < 0 => (pos, neg-1, min(ans, pos+neg-1))\n case ((pos, neg, ans), elem) if elem >= 0 => (pos+1, neg, min(ans, pos+neg+1))\n })._3)\n writer.close()\n }\n}"}], "src_uid": "165e18e39d2f60c72f22e3027a29a742"} {"source_code": "object Solution {\n import Utils._\n import scala.collection.mutable.PriorityQueue\n \n def main(args: Array[String]) = {\n val r = new Reader\n val n, k1, k2 = r.read[Int]\n val as = r.read[Array[Long]](n)\n val bs = r.read[Array[Long]](n)\n \n val pq = as.zip(bs).map(_.untuple(_-_)).map(_.abs).to[PriorityQueue]\n \n for (_ <- 1 to k1 + k2) {\n val m = pq.dequeue\n pq.enqueue((m - 1).abs)\n }\n \n println(pq.toList.map(x => x * x).sum)\n }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n def this() = this(new InputStreamReader(System.in))\n \n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n \n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n implicit val double: Read[Double] = new Read(_.read[String].toDouble)\n \n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n \n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != \"\").map(new StringTokenizer(_)).buffered\n}\n\nobject Utils {\n implicit def tupleToExtendedTuple[A](t: (A, A)): ExtendedTuple[A] = new ExtendedTuple(t)\n\n class ExtendedTuple[A](t: (A, A)) {\n def map[B](f: A => B) = (f(t._1), f(t._2))\n def untuple[B](f: (A, A) => B) = f(t._1, t._2)\n }\n}", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject MinimizeErrors extends App {\n\n val input = scala.io.StdIn.readLine()\n val inputScanner = new Scanner(input)\n val n = inputScanner.nextInt()\n val k1 = inputScanner.nextLong()\n val k2 = inputScanner.nextLong()\n\n val array1Input = scala.io.StdIn.readLine()\n val array1InputScanner = new Scanner(array1Input)\n val array1 = (1 to n).map { _ =>\n array1InputScanner.nextLong()\n }\n\n val array2Input = scala.io.StdIn.readLine()\n val array2InputScanner = new Scanner(array2Input)\n val array2 = (1 to n).map { _ =>\n array2InputScanner.nextLong()\n }\n\n val (_, _, remain, error) = array1.zip(array2)\n .map { case (a, b) => Math.abs(a - b) }\n .sorted\n .reverse\n .:+(0.toLong)\n .foldLeft((-1.toLong, 0.toLong, k1 + k2, 0.toLong)) { case ((last, cnt, remain, error), current) =>\n if (current == last) {\n (last, cnt + 1, remain, error)\n } else {\n val diff = last - current\n if (diff * cnt <= remain) {\n (current, cnt + 1, remain - diff * cnt, error)\n } else {\n val height = remain / cnt\n val r = remain % cnt\n val newError = error + r * (last - height - 1)*(last - height - 1) + (cnt - r) * (last - height)*(last - height)\n (current, 1.toLong, 0.toLong, newError)\n }\n }\n }\n\n if (remain % 2 != 0) {\n println(1)\n } else {\n println(error)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject MinimizeErrors extends App {\n\n val input = scala.io.StdIn.readLine()\n val inputScanner = new Scanner(input)\n val n = inputScanner.nextInt()\n val k1 = inputScanner.nextLong()\n val k2 = inputScanner.nextLong()\n\n val array1Input = scala.io.StdIn.readLine()\n val array1InputScanner = new Scanner(array1Input)\n val array1 = (1 to n).map { _ =>\n array1InputScanner.nextLong()\n }\n\n val array2Input = scala.io.StdIn.readLine()\n val array2InputScanner = new Scanner(array2Input)\n val array2 = (1 to n).map { _ =>\n array2InputScanner.nextLong()\n }\n\n val (_, _, remain, error) = array1.zip(array2)\n .map { case (a, b) => Math.abs(a - b) }\n .sorted\n .reverse\n .:+(0.toLong)\n .foldLeft((-1.toLong, 0.toLong, k1 + k2, 0.toLong)) { case ((last, cnt, remain, error), current) =>\n if (current == last) {\n (last, cnt + 1, remain, error)\n } else {\n val diff = last - current\n if (diff * cnt <= remain) {\n (current, cnt + 1, remain - diff * cnt, error)\n } else {\n val height = remain / cnt\n val r = remain % cnt\n val newError = error + r * (last - height - 1)*(last - height - 1) + (cnt - r) * (last - height)*(last - height)\n (current, 1.toLong, 0.toLong, newError)\n }\n }\n }\n\n println(error + remain % 2)\n}\n"}, {"source_code": "object Solution {\n import Utils._\n import scala.collection.mutable.{ TreeMap, TreeSet }\n \n def main(args: Array[String]) = {\n val r = new Reader\n val n, k1, k2 = r.read[Int]\n val as = r.read[Array[Long]](n)\n val bs = r.read[Array[Long]](n)\n \n val cs = as.zip(bs).map(_.untuple(_-_)).map(_.abs)\n \n for (_ <- 1 to k1 + k2) {\n val m = cs.max\n cs(cs.indexOf(m)) = (m - 1).abs\n }\n \n println(cs.map(x => x * x).sum)\n }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n def this() = this(new InputStreamReader(System.in))\n \n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n \n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n implicit val double: Read[Double] = new Read(_.read[String].toDouble)\n \n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n \n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != \"\").map(new StringTokenizer(_)).buffered\n}\n\nobject Utils {\n implicit def tupleToExtendedTuple[A](t: (A, A)): ExtendedTuple[A] = new ExtendedTuple(t)\n\n class ExtendedTuple[A](t: (A, A)) {\n def map[B](f: A => B) = (f(t._1), f(t._2))\n def untuple[B](f: (A, A) => B) = f(t._1, t._2)\n }\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nobject MinimizeErrors extends App {\n\n val input = scala.io.StdIn.readLine()\n val inputScanner = new Scanner(input)\n val n = inputScanner.nextInt()\n val k1 = inputScanner.nextLong()\n val k2 = inputScanner.nextLong()\n\n val array1Input = scala.io.StdIn.readLine()\n val array1InputScanner = new Scanner(array1Input)\n val array1 = (1 to n).map { _ =>\n array1InputScanner.nextLong()\n }\n\n val array2Input = scala.io.StdIn.readLine()\n val array2InputScanner = new Scanner(array2Input)\n val array2 = (1 to n).map { _ =>\n array2InputScanner.nextLong()\n }\n\n val (_, _, remain, error) = array1.zip(array2)\n .map { case (a, b) => Math.abs(a - b) }\n .sorted\n .reverse\n .:+(0.toLong)\n .foldLeft((-1.toLong, 0.toLong, k1 + k2, 0.toLong)) { case ((last, cnt, remain, error), current) =>\n if (current == last) {\n (last, cnt + 1, remain, error)\n } else {\n val diff = last - current\n if (diff * cnt <= remain) {\n (current, cnt + 1, remain - diff * cnt, error)\n } else {\n val height = remain / cnt\n val r = remain % cnt\n val newError = error + r * (last - height - 1)*(last - height - 1) + (cnt - r) * (last - height)*(last - height)\n (current, 1.toLong, 0.toLong, newError)\n }\n }\n }\n\n println(remain + error)\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject MinimizeErrors extends App {\n\n val input = scala.io.StdIn.readLine()\n val inputScanner = new Scanner(input)\n val n = inputScanner.nextInt()\n val k1 = inputScanner.nextInt()\n val k2 = inputScanner.nextInt()\n\n val array1Input = scala.io.StdIn.readLine()\n val array1InputScanner = new Scanner(array1Input)\n val array1 = (1 to n).map { _ =>\n array1InputScanner.nextInt()\n }\n\n val array2Input = scala.io.StdIn.readLine()\n val array2InputScanner = new Scanner(array2Input)\n val array2 = (1 to n).map { _ =>\n array2InputScanner.nextInt()\n }\n\n val (_, _, remain, error) = array1.zip(array2)\n .map { case (a, b) => Math.abs(a - b) }\n .sorted\n .reverse\n .:+(0)\n .foldLeft((-1, 0, k1 + k2, 0)) { case ((last, cnt, remain, error), current) =>\n if (current == last) {\n (last, cnt + 1, remain, error)\n } else {\n val diff = last - current\n if (diff * cnt <= remain) {\n (current, cnt + 1, remain - diff * cnt, error)\n } else {\n val height = remain / cnt\n val r = remain % cnt\n val newError = r * (last - height - 1)*(last - height - 1) + (cnt - r) * (last - height)*(last - height)\n (current, 1, 0, newError)\n }\n\n }\n }\n\n if (remain % 2 != 0) {\n println(1)\n } else {\n println(error)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main extends App {\n\n val input = scala.io.StdIn.readLine()\n val inputScanner = new Scanner(input)\n val n = inputScanner.nextInt()\n val k1 = inputScanner.nextInt()\n val k2 = inputScanner.nextInt()\n\n val array1Input = scala.io.StdIn.readLine()\n val array1InputScanner = new Scanner(array1Input)\n val array1 = (1 to n).map { _ =>\n array1InputScanner.nextInt()\n }\n\n val array2Input = scala.io.StdIn.readLine()\n val array2InputScanner = new Scanner(array2Input)\n val array2 = (1 to n).map { _ =>\n array2InputScanner.nextInt()\n }\n\n val (_, _, remain, error) = array1.zip(array2)\n .map { case (a, b) => Math.abs(a - b) }\n .sorted\n .reverse\n .:+(0)\n .foldLeft((-1, 0, k1 + k2, 0)) { case ((last, cnt, remain, error), current) =>\n if (current == last) {\n (last, cnt + 1, remain, error)\n } else {\n val diff = last - current\n if (diff * cnt <= remain) {\n (current, cnt + 1, remain - diff * cnt, error)\n } else {\n val height = remain / cnt\n val r = remain % cnt\n val newError = r * (last - height - 1) + (cnt - r) * (last - height)\n (current, 1, 0, newError)\n }\n\n }\n }\n\n if (remain % 2 != 0) {\n println(1)\n } else {\n println(error)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject MinimizeErrors extends App {\n\n val input = scala.io.StdIn.readLine()\n val inputScanner = new Scanner(input)\n val n = inputScanner.nextInt()\n val k1 = inputScanner.nextLong()\n val k2 = inputScanner.nextLong()\n\n val array1Input = scala.io.StdIn.readLine()\n val array1InputScanner = new Scanner(array1Input)\n val array1 = (1 to n).map { _ =>\n array1InputScanner.nextLong()\n }\n\n val array2Input = scala.io.StdIn.readLine()\n val array2InputScanner = new Scanner(array2Input)\n val array2 = (1 to n).map { _ =>\n array2InputScanner.nextLong()\n }\n\n val (_, _, remain, error) = array1.zip(array2)\n .map { case (a, b) => Math.abs(a - b) }\n .sorted\n .reverse\n .:+(0.toLong)\n .foldLeft((-1.toLong, 0.toLong, k1 + k2, 0.toLong)) { case ((last, cnt, remain, error), current) =>\n if (current == last) {\n (last, cnt + 1, remain, error)\n } else {\n val diff = last - current\n if (diff * cnt <= remain) {\n (current, cnt + 1, remain - diff * cnt, error)\n } else {\n val height = remain / cnt\n val r = remain % cnt\n val newError = r * (last - height - 1)*(last - height - 1) + (cnt - r) * (last - height)*(last - height)\n (current, 1.toLong, 0.toLong, newError)\n }\n\n }\n }\n\n if (remain % 2 != 0) {\n println(1)\n } else {\n println(error)\n }\n}\n"}, {"source_code": "object Solution {\n import Utils._\n import scala.collection.mutable.TreeSet\n \n def main(args: Array[String]) = {\n val r = new Reader\n val n, k1, k2 = r.read[Int]\n val as = r.read[List[Int]](n)\n val bs = r.read[List[Int]](n)\n val k = k1 + k2\n \n val s: TreeSet[Int] = as.zip(bs).map(_.untuple(_-_)).map(_.abs).to[TreeSet]\n \n for (_ <- 1 to k) {\n val m = s.max\n s -= m\n s += (m - 1).abs\n }\n\n println(s.map(x => x * x).sum)\n }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n def this() = this(new InputStreamReader(System.in))\n \n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n \n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n implicit val double: Read[Double] = new Read(_.read[String].toDouble)\n \n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n \n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != \"\").map(new StringTokenizer(_)).buffered\n}\n\nobject Utils {\n implicit def tupleToExtendedTuple[A](t: (A, A)): ExtendedTuple[A] = new ExtendedTuple(t)\n\n class ExtendedTuple[A](t: (A, A)) {\n def map[B](f: A => B) = (f(t._1), f(t._2))\n def untuple[B](f: (A, A) => B) = f(t._1, t._2)\n }\n}"}, {"source_code": "object Solution {\n import Utils._\n import scala.collection.mutable.{ TreeMap, TreeSet }\n \n def main(args: Array[String]) = {\n val r = new Reader\n val n, k1, k2 = r.read[Int]\n val as = r.read[List[Long]](n)\n val bs = r.read[List[Long]](n)\n \n val cs = as.zip(bs).map(_.untuple(_-_)).map(_.abs).sorted.group(_ == _).map {\n xs => (xs.head.toLong, xs.length.toLong)\n }\n \n val m = TreeMap.empty[Long, Long] ++ cs\n val s = TreeSet.empty[Long] ++ cs.map(_._1)\n var k = k1 + k2\n \n while (k > 0 && s.max != 0) {\n k = k - 1\n \n val x = s.max\n \n if (m(x) == 1) s -= x\n m(x) = m(x) - 1\n \n val y = (x - 1).abs\n s += y\n if (m.contains(y)) m(y) = m(y) + 1 else m(y) = 1\n }\n \n if (k > 0) {\n println(if (k % 2 == 0) 0 else 1)\n } else {\n println(s.map(x => (x * x) * m(x)).sum)\n }\n }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n def this() = this(new InputStreamReader(System.in))\n \n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n \n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n implicit val double: Read[Double] = new Read(_.read[String].toDouble)\n \n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n \n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != \"\").map(new StringTokenizer(_)).buffered\n}\n\nobject Utils {\n implicit def tupleToExtendedTuple[A](t: (A, A)): ExtendedTuple[A] = new ExtendedTuple(t)\n\n class ExtendedTuple[A](t: (A, A)) {\n def map[B](f: A => B) = (f(t._1), f(t._2))\n def untuple[B](f: (A, A) => B) = f(t._1, t._2)\n }\n \n implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)\n\n class ExtendedList[A](xs: List[A]) {\n def group(g: (A, A) => Boolean) =\n xs.foldRight(List[List[A]]()) {\n case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs\n case (x, _) => List(List(x))\n }\n }\n}"}, {"source_code": "object Solution {\n import Utils._\n import scala.collection.mutable.{ TreeMap, TreeSet }\n \n def main(args: Array[String]) = {\n val r = new Reader\n val n, k1, k2 = r.read[Int]\n val as = r.read[List[Int]](n)\n val bs = r.read[List[Int]](n)\n \n val cs = as.zip(bs).map(_.untuple(_-_)).map(_.abs).group(_ == _).map {\n xs => (xs.head.toLong, xs.length.toLong)\n }\n \n val m = TreeMap.empty[Long, Long] ++ cs\n val s = TreeSet.empty[Long] ++ cs.map(_._1)\n \n var k = k1 + k2\n \n while (k > 0 && s.max != 0) {\n k = k - 1\n \n val x = s.max\n \n if (m(x) == 1) s -= x\n m(x) = m(x) - 1\n \n val y = (x - 1).abs\n s += y\n \n if (m.contains(y)) m(y) = m(y) + 1 else m(y) = 1\n }\n \n if (k > 0) {\n println(if (k % 2 == 0) 0 else 1)\n } else {\n println(s.map(x => (x * x) * m(x)).sum)\n }\n }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n def this() = this(new InputStreamReader(System.in))\n \n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n \n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n implicit val double: Read[Double] = new Read(_.read[String].toDouble)\n \n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n \n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != \"\").map(new StringTokenizer(_)).buffered\n}\n\nobject Utils {\n implicit def tupleToExtendedTuple[A](t: (A, A)): ExtendedTuple[A] = new ExtendedTuple(t)\n\n class ExtendedTuple[A](t: (A, A)) {\n def map[B](f: A => B) = (f(t._1), f(t._2))\n def untuple[B](f: (A, A) => B) = f(t._1, t._2)\n }\n \n implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)\n\n class ExtendedList[A](xs: List[A]) {\n def group(g: (A, A) => Boolean) =\n xs.foldRight(List[List[A]]()) {\n case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs\n case (x, _) => List(List(x))\n }\n }\n}"}, {"source_code": "object Solution {\n import Utils._\n import scala.collection.mutable.{ TreeMap, TreeSet }\n \n def main(args: Array[String]) = {\n val r = new Reader\n val n, k1, k2 = r.read[Int]\n val as = r.read[List[Int]](n)\n val bs = r.read[List[Int]](n)\n \n val cs = as.zip(bs).map(_.untuple(_-_)).map(_.abs).sorted.group(_ == _).map {\n xs => (xs.head.toLong, xs.length.toLong)\n }\n \n val m = TreeMap.empty[Long, Long] ++ cs\n val s = TreeSet.empty[Long] ++ cs.map(_._1)\n var k = k1 + k2\n \n while (k > 0 && s.max != 0) {\n k = k - 1\n \n val x = s.max\n \n if (m(x) == 1) s -= x\n m(x) = m(x) - 1\n \n val y = (x - 1).abs\n s += y\n if (m.contains(y)) m(y) = m(y) + 1 else m(y) = 1\n }\n \n if (k > 0) {\n println(if (k % 2 == 0) 0 else 1)\n } else {\n println(s.map(x => (x * x) * m(x)).sum)\n }\n }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n def this() = this(new InputStreamReader(System.in))\n \n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n \n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n implicit val double: Read[Double] = new Read(_.read[String].toDouble)\n \n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n \n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != \"\").map(new StringTokenizer(_)).buffered\n}\n\nobject Utils {\n implicit def tupleToExtendedTuple[A](t: (A, A)): ExtendedTuple[A] = new ExtendedTuple(t)\n\n class ExtendedTuple[A](t: (A, A)) {\n def map[B](f: A => B) = (f(t._1), f(t._2))\n def untuple[B](f: (A, A) => B) = f(t._1, t._2)\n }\n \n implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)\n\n class ExtendedList[A](xs: List[A]) {\n def group(g: (A, A) => Boolean) =\n xs.foldRight(List[List[A]]()) {\n case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs\n case (x, _) => List(List(x))\n }\n }\n}"}, {"source_code": "object Solution {\n import Utils._\n import scala.collection.mutable.{ TreeMap, TreeSet }\n \n def main(args: Array[String]) = {\n val r = new Reader\n val n, k1, k2 = r.read[Int]\n val as = r.read[List[Int]](n)\n val bs = r.read[List[Int]](n)\n \n val cs = as.zip(bs).map(_.untuple(_-_)).map(_.abs).group(_ == _).map {\n xs => (xs.head, xs.length)\n }\n \n val m = TreeMap.empty[Int, Int] ++ cs\n val s = TreeSet.empty[Int] ++ cs.map(_._1)\n \n var k = k1 + k2\n \n while (k > 0 && s.max != 0) {\n k = k - 1\n \n val x = s.max\n \n if (m(x) == 1) s -= x\n m(x) = m(x) - 1\n \n val y = (x - 1).abs\n s += y\n \n if (m.contains(y)) m(y) = m(y) + 1 else m(y) = 1\n }\n \n if (k > 0) {\n println(if (k % 2 == 0) 0 else 1)\n } else {\n println(s.map(x => (x * x) * m(x)).sum)\n }\n }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n def this() = this(new InputStreamReader(System.in))\n \n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n \n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n implicit val double: Read[Double] = new Read(_.read[String].toDouble)\n \n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n \n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != \"\").map(new StringTokenizer(_)).buffered\n}\n\nobject Utils {\n implicit def tupleToExtendedTuple[A](t: (A, A)): ExtendedTuple[A] = new ExtendedTuple(t)\n\n class ExtendedTuple[A](t: (A, A)) {\n def map[B](f: A => B) = (f(t._1), f(t._2))\n def untuple[B](f: (A, A) => B) = f(t._1, t._2)\n }\n \n implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)\n\n class ExtendedList[A](xs: List[A]) {\n def group(g: (A, A) => Boolean) =\n xs.foldRight(List[List[A]]()) {\n case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs\n case (x, _) => List(List(x))\n }\n }\n}"}], "src_uid": "88d54818fd8bab2f5d0bd8d95ec860db"} {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _699A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val n = read[Int]\n val dir = read[String]\n val pos = read[Vector, Long](n)\n\n val collisions = dir.zip(pos).sliding(2) collect {\n case Seq(('R', p1), ('L', p2)) => (p2 - p1)/2\n }\n\n write(collisions.toSeq.whenNonEmpty(_.min) getOrElse -1)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n def X[B](bs: Iterable[B]): Iterable[(A, B)] = for {a <- s; b <- bs} yield (a, b)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toYesNo = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeLine(obj: Any*): this.type = {\n if (obj.isEmpty) printer.println() else obj foreach printer.println\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "\nobject CF699A{\nimport scala.io.StdIn.{\n readLine,\n readInt}\nimport scala.math.min\n\n val INF:Int = 1000000100\n def dist(pos1:(Int, Char), pos2:(Int, Char)): Int = {\n var (d1,r1) = pos1;\n var (d2,r2) = pos2;\n if(r1=='R' && r2=='L') (d2-d1)/2;\n else INF\n }\n def main(args: Array[String]){\n var n:Int = readInt()\n var dir: String = readLine()\n var arr: Array[Int] = readLine().split(' ') map Integer.parseInt\n var pos = (arr zip dir).sorted\n \n var minTime: Int = INF;\n (0 until n-1).foreach(i => minTime = min(minTime, dist(pos(i), pos(i+1))));\n // println(pos.mkString)\n if (minTime == INF) println(-1)\n else println(minTime)\n }\n}"}, {"source_code": "object Main extends App {\n val n = scala.io.StdIn.readInt()\n val directions = scala.io.StdIn.readLine()\n val positions = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val values = for(i <- (0 until n - 1) if (directions(i) =='R' && directions(i + 1) == 'L')) yield (positions(i + 1) - positions(i)) / 2\n val answer = if (values.isEmpty) -1 else values.min\n println(answer)\n}"}, {"source_code": "/**\n * Created by allen on 16-7-22.\n */\n\nimport scala.io._\nobject main {\n def calTime(x:(Char, Int), y:(Char, Int)): Int = {\n if(x._1 != 'R' || y._1 != 'L') Int.MaxValue\n else math.abs(y._2 - x._2) / 2\n }\n\n def lt(x: ((Char, Int), (Char, Int)), y: ((Char, Int), (Char, Int))): Boolean =\n calTime(x._1, x._2) < calTime(y._1, y._2)\n\n def main(args: Array[String])= {\n val N = StdIn.readInt()\n val InpStr = StdIn.readLine()\n val InpNum = StdIn.readLine().split(' ').map(x => x.toInt).toSeq\n val SN = InpStr zip InpNum\n val pro = SN.zip(SN.drop(1))\n val tm = pro.foldLeft(Int.MaxValue) ((x, y) => math.min(x, calTime(y._1, y._2)))\n if(N == 1 || tm == Int.MaxValue) println(-1)\n else println(tm)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val n = lines.next().toInt\n val directions = lines.next()\n val positions = lines.next().split(' ').map(_.toInt)\n val join = positions.zip(directions)\n val res = join.sliding(2).foldLeft(Int.MaxValue) {\n case (min, Array((p1, 'R'), (p2, 'L'))) => Math.min(min, (p2 - p1) / 2)\n case (min, _) => Math.min(min, min)\n }\n\n println(if (res == Int.MaxValue) -1 else res)\n}\n"}, {"source_code": "object A699 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val dir = read\n val pos = readInts(n)\n if(dir.contains(\"RL\")) {\n var res = Integer.MAX_VALUE\n for(i <- 0 until n-1) {\n if(dir(i) == 'R' && dir(i+1) == 'L') {\n res = math.min(res, (pos(i+1)-pos(i))/2)\n }\n }\n println(res)\n } else {\n println(\"-1\")\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.util.control.Breaks._\n\nobject main extends App{\n val n = readInt\n val s = readLine\n var x = readLine.split(\" \").map(_.toInt)\n println(List.range(0, x.length - 1).foldLeft(-1)((res: Int, i: Int) => {\n \tvar newRes = res\n \tif (s(i) == 'R' && s(i+1) == 'L') {\n \t\tval nRes = (x(i+1) - x(i)) / 2\n \t\tif (res == -1 || res > nRes) {\n \t\t\tnewRes = nRes\n \t\t}\n \t}\n \tnewRes\n }))\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val n = lines.next().toInt\n val directions = lines.next()\n val positions = lines.next().split(' ').map(_.toInt)\n val join = positions.zip(directions)\n val left = join.filter(_._2 == 'L').map(_._1).sorted.toList\n val right = join.filter(_._2 == 'R').map(_._1).sorted.toList\n\n\n def solution(left: List[Int], right: List[Int], soFar: Int = Int.MaxValue): Int = {\n if (left.isEmpty || right.isEmpty)\n if (soFar == Int.MaxValue) -1 else soFar\n else if (right.head > left.head)\n solution(left.tail, right, soFar)\n else\n solution(left.tail, right.tail, Math.min(soFar, (left.head - right.head) / 2))\n }\n println(solution(left, right))\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _699A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val n = read[Int]\n val dir = read[String]\n val pos = read[Vector, Long](n)\n\n val collisions = dir.zip(pos).grouped(2) collect {\n case Seq(('R', p1), ('L', p2)) => (p2 - p1)/2\n }\n \n write(collisions.toSeq.whenNonEmpty(_.min) getOrElse -1)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n def X[B](bs: Iterable[B]): Iterable[(A, B)] = for {a <- s; b <- bs} yield (a, b)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toYesNo = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeLine(obj: Any*): this.type = {\n if (obj.isEmpty) printer.println() else obj foreach printer.println\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "ff0843cbd7c3a07c7d7d0be46b03a700"} {"source_code": "object A extends App {\n val (n) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ans = a.zipWithIndex.groupBy(_._1).maxBy { case (_, seq) =>\n (seq.size, -seq.map(_._2).max)\n }._1\n\n println(ans)\n}\n", "positive_code": [{"source_code": "\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 29 Jun 2016\n */\nobject A637 extends App {\n\n def solve() = {\n val n: Int = scala.io.StdIn.readInt()\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val map: mutable.HashMap[Int, (Int, Int)] = mutable.HashMap.empty[Int, (Int, Int)]\n for (i <- 0 until n) {\n if (!map.contains(a(i))) {\n map += (a(i) -> (0, 0))\n }\n val currentTuple = map(a(i))\n map += (a(i) -> (currentTuple._1 + 1, i + 1))\n }\n var max = 0\n var min = Integer.MAX_VALUE\n var id = 0\n map.foreach((f :(Int, (Int, Int))) => {\n if (f._2._1 > max) {\n max = f._2._1\n min = f._2._2\n id = f._1\n } else if (f._2._1 == max && f._2._2 < min) {\n min = f._2._2\n id = f._1\n }\n })\n\n println(id)\n }\n\n solve()\n\n}\n"}, {"source_code": "import scala.collection.mutable\nobject A extends App{\n val (like) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val photoNumb = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val indexArray = mutable.HashMap[Int, Int]()\n var maxID: Int = 0\n var otvet:Int =0\n photoNumb.foreach(x => {\n indexArray.put(x, indexArray.getOrElse(x, 0) + 1)\n if (indexArray(x) > maxID) {\n maxID = indexArray(x)\n otvet = x\n }\n })\n println(otvet)\n}\n\n\n\n\n"}, {"source_code": "import java.io._\nimport java.nio.file._\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * @author itegulov\n */\nobject A extends App {\n \n import scala.collection.mutable.{Map => MMap}\n\n val in: Scanner = new Scanner(System.in)\n val out: PrintWriter = new PrintWriter(System.out)\n\n val map: MMap[Int, (Int, Int)] = MMap()\n\n val n = in.nextInt()\n\n for (i <- 1 to n) {\n val liked = in.nextInt()\n map(liked) = (map.getOrElse(liked, (0, 0))._1 + 1, i)\n }\n\n val answer = map.fold((-1, (0, -1)))((p1, p2) => if (p1._2._1 > p2._2._1 || p1._2._1 == p2._2._1 && p1._2._2 < p2._2._2) p1 else p2)\n out.println(answer._1)\n\n in.close()\n out.close()\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine())\n .takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next() = tokenizer().get.nextToken()\n\n override def hasNext = tokenizer().nonEmpty\n\n override def close() = reader.close()\n }\n\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val sum = data.groupBy(i => i).map(i => i._1 -> i._2.length)\n val max = sum.maxBy(_._2)._2\n val filtered = sum.filter(i => i._2 == max).keySet\n data.filter(filtered.contains).reverse.distinct.reverse.find(filtered.contains).foreach(println)\n}\n"}], "negative_code": [], "src_uid": "e4a2354159fc4cab7088e016cf17ae6c"} {"source_code": "object B1144Policarp extends App{\n import scala.io.StdIn.{readInt, readLine}\n val _ = readInt\n val arr = readLine.split(' ').map(_.toInt).toList.sorted\n val odd = arr filter {_ % 2 == 1}\n val even = arr filter {_ % 2 == 0}\n val forDrop = math.min(odd.length, even.length) + 1\n println(odd.dropRight(forDrop).sum + even.dropRight(forDrop).sum)\n}\n", "positive_code": [{"source_code": "object _1144B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val nums = io.read[Seq[Int]]\n val (odd, even) = nums.sorted(desc[Int]).partition(_ % 2 == 1)\n val len = odd.length min even.length\n val ans = Seq(odd, even).map(_.drop(len + 1).sum).sum\n io.write(ans)\n }\n\n def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object B {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val n = stdin.readInt()\n val arr0 = stdin.readLine().trim.split(\" \").map(_.toInt).toList\n val arr = arr0.groupBy(_ % 2 == 1)\n if (arr.size > 1){\n val even = arr(false).sorted.reverse\n val odd = arr(true).sorted.reverse\n val ans = if (math.abs(even.length-odd.length)<=1) 0\n else if (even.length > odd.length){\n even.drop(odd.length+1).sum\n } else {\n odd.drop(even.length+1).sum\n }\n println(ans)\n } else {\n println(arr0.sum-arr0.max)\n }\n\n }\n}"}], "negative_code": [{"source_code": "object B {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val n = stdin.readInt()\n val arr0 = stdin.readLine().trim.split(\" \").map(_.toInt).toList\n val arr = arr0.groupBy(_ % 2 == 1)\n if (arr.size > 1){\n val even = arr(false).sorted\n val odd = arr(true).sorted\n val ans = if (math.abs(even.length-odd.length)<=1) 0\n else if (even.length > odd.length){\n even.drop(odd.length+1).sum\n } else {\n odd.drop(even.length+1).sum\n }\n println(ans)\n } else {\n println(arr0.sum-arr0.max)\n }\n\n }\n}"}, {"source_code": "object B {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val n = stdin.readInt()\n val arr0 = stdin.readLine().trim.split(\" \").map(_.toInt).toList\n val arr = arr0.groupBy(_ % 2 == 1)\n if (arr.size > 1){\n val even = arr(false).sorted\n val odd = arr(true).sorted\n val ans = if (even.length > odd.length){\n even.drop(odd.length+1).sum\n } else if (even.length < odd.length){\n odd.drop(even.length+1).sum\n } else 0\n println(ans)\n } else {\n println(arr0.sum-arr0.max)\n }\n\n }\n}"}], "src_uid": "b80fed46a9e2356dad03dd3ec01523d4"} {"source_code": "object Main {\n import annotation.tailrec\n class SegmentTree [T: reflect.ClassTag] (a: Array[T], op: (T, T) => T, empty: T) {\n private val n = a.size\n private val t = Array.ofDim (2*n)\n private def build {\n for (i <- n - 1 until 0 by - 1) {\n val k = i << 1\n t(i) = op (t(k), t(k+1))\n }\n }\n Array.copy (a, 0, t, n, n)\n build\n def update (p: Int, v: T) {\n val p0 = p + n\n t(p0) = v\n @tailrec def loop (i: Int) {\n if (i > 1) {\n val k = i >>> 1\n t(k) = op (t(i), t(i^1))\n loop (k)\n }\n }\n loop (p0)\n }\n //op - commutative\n def reduce (l: Int, r: Int) = {\n var res = empty\n @tailrec def loop (i: Int, j: Int) {\n if (i < j) {\n if (0 != (i & 1)) res = op (res, t(i))\n if (0 != (j & 1)) res = op (t(j-1), res)\n loop ((i + 1) >>> 1, j >>> 1)\n }\n }\n loop (l + n, r + n)\n res\n }\n def safeReduce (l: Int, r: Int) = {\n var resl = empty\n var resr = empty\n @tailrec def loop (i: Int, j: Int) {\n if (i < j) {\n if (0 != (i & 1)) resl = op (resl, t(i))\n if (0 != (j & 1)) resr = op (t(j-1), resr)\n loop ((i + 1) >>> 1, j >>> 1)\n }\n }\n loop (l + n, r + n)\n op (resl, resr)\n }\n }\n\n import io._\n val lineit:Iterator[String] = Source.stdin.getLines.filterNot(_.isEmpty).flatMap(i => i.split(\" \"))\n val sb = new StringBuilder\n def rs() = lineit.next\n def ri() = rs.toInt\n def main(args: Array[String]) {\n val n = ri\n val m = ri\n val a = Array.fill (1< (if ((x._2 & 1) == 0) x._1 | y._1 else x._1 ^ y._1, x._2 ^ 1), (0, 0) )\n for (t <- 1 to m) {\n val i = ri - 1\n val v = ri\n st(i) = (v, 0)\n sb.append (st.reduce (0, 1 << n)._1)\n sb.append ('\\n')\n }\n print (sb)\n }\n}\n", "positive_code": [{"source_code": "//package solutions\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\n/**\n * @author traff\n */\n\n\nobject Solution_cf339d extends App {\n\n class FastScanner() {\n private var br = new BufferedReader(new InputStreamReader(System.in))\n private var st: StringTokenizer = _\n\n private def nextToken = {\n while (st == null || !st.hasMoreElements) try\n st = new StringTokenizer(br.readLine)\n\n catch {\n case e: IOException =>\n e.printStackTrace()\n }\n st.nextToken\n }\n\n def nextInt: Int = nextToken.toInt\n\n def nextLong: Long = nextToken.toLong\n\n def nextDouble: Double = nextToken.toDouble\n }\n\n override def main(args: Array[String]): Unit = {\n val out = new PrintWriter(System.out)\n\n run(new FastScanner(), out)\n\n out.close()\n }\n\n def run(s: FastScanner, out: PrintWriter): Unit = {\n val (n, m) = (s.nextInt, s.nextInt)\n\n var a: Array[Int] = new Array[Int]((1 << n + 1) - 1)\n\n for (i <- 1 << n until 1 << (n + 1)) {\n a(i - 1) = s.nextInt\n }\n\n @tailrec\n def up(k: Int, f: Boolean): Unit = {\n if (k > 0) {\n val i = if (k % 2 == 0) k - 1 else k\n a(i / 2) = if (f) a(i) | a(i + 1) else a(i) ^ a(i + 1)\n up(i / 2, !f)\n }\n }\n\n for (i <- 1 << n until 1 << (n + 1)) {\n if (i % 2 == 0) {\n up(i - 1, f = true)\n }\n }\n\n for (i <- 1 to m) {\n val (p, b) = (s.nextInt, s.nextInt)\n val k = (1 << n) - 1 + p - 1\n a(k) = b\n up(k, f = true)\n out.println(s\"${a(0)}\")\n }\n }\n}\n\n\n"}, {"source_code": "import java.io.PrintWriter\n\n/**\n * @author traff\n */\n\nobject Main extends App {\n\n class FastScanner() {\n import java.io.{FileReader, PrintWriter}\n import java.io.{BufferedReader, IOException, InputStreamReader}\n import java.util.StringTokenizer\n\n private var br = new BufferedReader(new InputStreamReader(System.in))\n private var st: StringTokenizer = _\n\n def this(f: String) {\n this()\n br = new BufferedReader(new FileReader(f))\n }\n\n private def nextToken = {\n while (st == null || !st.hasMoreElements) try\n st = new StringTokenizer(br.readLine)\n\n catch {\n case e: IOException =>\n e.printStackTrace()\n }\n st.nextToken\n }\n\n def nextInt: Int = nextToken.toInt\n\n def nextLong: Long = nextToken.toLong\n\n def nextDouble: Double = nextToken.toDouble\n }\n\n sealed abstract class Op extends ((Int, Int) => Int) {\n }\n\n case class Xor() extends Op {\n override def apply(v1: Int, v2: Int): Int = v1 ^ v2\n }\n\n case class Or() extends Op {\n override def apply(v1: Int, v2: Int): Int = v1 | v2\n }\n\n class Node(parent: Option[Node], a: Array[Int], leafs: Array[Node], ln: Int, rn: Int) {\n var r, l: Option[Node] = None\n private var _v: Int = 0\n\n if (ln == rn) {\n _v = a(ln)\n leafs(ln) = this\n r = None\n l = None\n } else {\n require(ln < rn, s\"$ln $rn\")\n\n val lnode = new Node(Some(this), a, leafs, ln, ln + (rn - ln) / 2)\n l = Some(lnode)\n val rnode = new Node(Some(this), a, leafs, ln + (rn - ln) / 2 + 1, rn)\n r = Some(rnode)\n\n _v = lnode.op().apply(lnode._v, rnode._v)\n }\n\n def op(): Op = {\n l match {\n case None => Or()\n case Some(n) => n.op() match {\n case Xor() => Or()\n case Or() => Xor()\n }\n }\n }\n\n def up(): Unit = {\n if (l.isDefined) {\n _v = l.get.op().apply(l.get._v, r.get._v)\n }\n parent.foreach(p => p.up())\n }\n\n def value: Int = _v\n\n def value_=(value: Int): Unit = {\n _v = value\n up()\n }\n\n }\n\n val s = new FastScanner()\n val out = new PrintWriter(System.out)\n\n val (n, m) = (s.nextInt, s.nextInt)\n\n var a: Array[Int] = new Array[Int](1 << n )\n\n for (i <- 1 to 1 << n) {\n a(i-1) = s.nextInt\n }\n\n val leafs = new Array[Node](a.length)\n\n val tree = new Node(None, a, leafs, 0, a.length - 1)\n\n for (i <- 1 to m) {\n val (p, b) = (s.nextInt, s.nextInt)\n leafs(p - 1).value = b\n out.println(tree.value)\n }\n\n out.close()\n\n\n}\n\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C197D(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C197D(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n: Int = ni()\n val m = ni()\n val limit = Math.pow(2, n).toInt\n\n val a: Array[Int] = na(limit)\n\n val t = new SegmentTree(limit, a)\n t.build(1, 0, limit - 1, if(n%2 == 0) false else true)\n REP(m) { _ =>\n val p = ni()\n val b = ni()\n t.update(1, 0, limit - 1, if(n%2 == 0) false else true, p - 1, b)\n out.println(t.getAnswer)\n }\n }\n\n private class SegmentTree(n: Int, a: Array[Int]) {\n private val tree: Array[Int] = Array.ofDim[Int](4 * n)\n\n def build(v: Int, tl: Int, tr:Int, op: Boolean): Unit = {\n if(tl == tr) {\n tree(v) = a(tl)\n } else {\n val tm = tl + (tr - tl) / 2\n build(v << 1, tl, tm, !op)\n build(v << 1 | 1, tm + 1, tr, !op)\n tree(v) = if(op) tree(v << 1) | tree(v << 1 | 1) else tree(v << 1) ^ tree(v << 1 | 1)\n }\n }\n\n def update(v: Int, tl: Int, tr: Int, op: Boolean, index: Int, value: Int): Unit = {\n if(tl == tr) {\n tree(v) = value\n } else {\n val tm = tl + (tr - tl) / 2\n if(index <= tm) {\n update(v << 1, tl, tm, !op, index, value)\n } else {\n update(v << 1 | 1, tm + 1, tr, !op, index, value)\n }\n tree(v) = if(op) tree(v << 1) | tree(v << 1 | 1) else tree(v << 1) ^ tree(v << 1 | 1)\n }\n }\n\n def getAnswer: Int = {\n tree(1)\n }\n\n }\n}\n"}, {"source_code": "object D339 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val init = readInts(1< tree.rsq(i, i)}.mkString(\" \"))\n for(_ <- 1 to m) {\n val Array(p, b) = readInts(2)\n tree.update(p-1, p-1, b)\n out.println(tree.rsq(0, (1<= from1 && to2 <= to1\n\n //check inclusive intersection, test if range1[from1, to1] intersects range2[from2, to2]//check inclusive intersection, test if range1[from1, to1] intersects range2[from2, to2]\n private def intersects(from1: Int, to1: Int, from2: Int, to2: Int) = from1 <= from2 && to1 >= from2 || from1 >= from2 && from1 <= to2\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val bitStep = Array.tabulate(n + 1)(i => Array.ofDim[Int]((1 << n) + 1))\n bitStep(0) = 0 +: readInts(1 << n)\n\n for (step <- 1 to n; i <- 1 to 1 << (n - step)) {\n bitStep(step)(i) = (if ((step & 1) == 1) bitStep(step - 1)(2 * i) | bitStep(step - 1)(2 * i - 1)\n else bitStep(step - 1)(2 * i) ^ bitStep(step - 1)(2 * i - 1))\n }\n\n var i = 0\n while (i < m) {\n \n val t = tokenizeLine\n var p = t.nextToken.toInt\n val b = t.nextToken.toInt\n\n bitStep(0)(p) = b\n for (step <- 1 to n) {\n p = (p + 1) >> 1\n if ((step & 1) == 1) bitStep(step)(p) = bitStep(step - 1)(2 * p) | bitStep(step - 1)(2 * p - 1)\n else bitStep(step)(p) = bitStep(step - 1)(2 * p) ^ bitStep(step - 1)(2 * p - 1)\n }\n\n println(bitStep(n)(1))\n\n i += 1\n }\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val bitStep = Array.tabulate(n + 1)(i => Array.ofDim[Int]((1 << n) + 1))\n bitStep(0) = 0 +: readInts(1 << n)\n\n for (step <- 1 to n; i <- 1 to 1 << (n - step)) {\n bitStep(step)(i) = (if ((step & 1) == 1) bitStep(step - 1)(2 * i) | bitStep(step - 1)(2 * i - 1)\n else bitStep(step - 1)(2 * i) ^ bitStep(step - 1)(2 * i - 1))\n }\n\n def calc() = bitStep(n)(1)\n \n var k = 0\n while (k < m) {\n val t = tokenizeLine\n val p0 = t.nextToken.toInt\n val b = t.nextToken.toInt\n\n for (bit <- 0 to 17) {\n bitStep(0)(p0) = b\n var p = p0\n for (step <- 1 to n) {\n p = (p + 1) >> 1\n if ((step & 1) == 1) bitStep(step)(p) = bitStep(step - 1)(2 * p) | bitStep(step - 1)(2 * p - 1)\n else bitStep(step)(p) = bitStep(step - 1)(2 * p) ^ bitStep(step - 1)(2 * p - 1)\n }\n }\n\n println(calc())\n\n k += 1\n }\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val bitStep = Array.tabulate(n + 1)(i => Array.ofDim[Int]((1 << n) + 1))\n bitStep(0) = 0 +: readInts(1 << n)\n\n for (step <- 1 to n; i <- 1 to 1 << (n - step)) {\n bitStep(step)(i) = (if ((step & 1) == 1) bitStep(step - 1)(2 * i) | bitStep(step - 1)(2 * i - 1)\n else bitStep(step - 1)(2 * i) ^ bitStep(step - 1)(2 * i - 1))\n }\n\n var i = 0\n while (i < m) {\n \n val t = tokenizeLine\n val p0 = t.nextToken.toInt\n val b = t.nextToken.toInt\n\n bitStep(0)(p0) = b\n var p = p0\n for (step <- 1 to n) {\n p = (p + 1) >> 1\n if ((step & 1) == 1) bitStep(step)(p) = bitStep(step - 1)(2 * p) | bitStep(step - 1)(2 * p - 1)\n else bitStep(step)(p) = bitStep(step - 1)(2 * p) ^ bitStep(step - 1)(2 * p - 1)\n }\n\n println(bitStep(n)(1))\n\n i += 1\n }\n\n Console.flush\n}\n"}, {"source_code": "object Main {\n import annotation.tailrec\n class SegmentTree [T: reflect.ClassTag] (a: Array[T], op: (T, T) => T, empty: T) {\n private val n = a.size\n private val t = Array.ofDim (2*n)\n private def build {\n for (i <- n - 1 until 0 by - 1) {\n val k = i << 1\n t(i) = op (t(k), t(k+1))\n }\n }\n Array.copy (a, 0, t, n, n)\n build\n def update (p: Int, v: T) {\n val p0 = p + n\n t(p0) = v\n @tailrec def loop (i: Int) {\n if (i > 1) {\n val k = i >>> 1\n t(k) = op (t(i), t(i^1))\n loop (k)\n }\n }\n loop (p0)\n }\n //op - commutative\n def reduce (l: Int, r: Int) = {\n var res = empty\n @tailrec def loop (i: Int, j: Int) {\n if (i < j) {\n if (0 != (i & 1)) res = op (res, t(i))\n if (0 != (j & 1)) res = op (t(j-1), res)\n loop ((i + 1) >>> 1, j >>> 1)\n }\n }\n loop (l + n, r + n)\n res\n }\n def safeReduce (l: Int, r: Int) = {\n var resl = empty\n var resr = empty\n @tailrec def loop (i: Int, j: Int) {\n if (i < j) {\n if (0 != (i & 1)) resl = op (resl, t(i))\n if (0 != (j & 1)) resr = op (t(j-1), resr)\n loop ((i + 1) >>> 1, j >>> 1)\n }\n }\n loop (l + n, r + n)\n op (resl, resr)\n }\n }\n\n import io._\n val lineit:Iterator[String] = Source.stdin.getLines.filterNot(_.isEmpty).flatMap(i => i.split(\" \"))\n val sb = new StringBuilder\n def rs() = lineit.next\n def ri() = rs.toInt\n def main(args: Array[String]) {\n val n = ri\n val m = ri\n val a = Array.fill (1< (if ((x._2 & 1) == 0) x._1 | y._1 else x._1 ^ y._1, x._2 ^ 1), (0, 0) )\n for (t <- 1 to m) {\n val i = ri - 1\n val v = ri\n st(i) = (v, 0)\n sb.append (st.safeReduce (0, 1 << n)._1)\n sb.append ('\\n')\n }\n print (sb)\n }\n}\n"}, {"source_code": "object Main {\n import annotation.tailrec\n class SegmentTree [T: reflect.ClassTag] (a: Array[T], op: (T, T) => T, empty: T) {\n private val n = a.size\n private val t = Array.ofDim (2*n)\n private def build {\n for (i <- n - 1 until 0 by - 1) {\n val k = i << 1\n t(i) = op (t(k), t(k+1))\n }\n }\n Array.copy (a, 0, t, n, n)\n build\n def update (p: Int, v: T) {\n val p0 = p + n\n t(p0) = v\n @tailrec def loop (i: Int) {\n if (i > 1) {\n val k = i >>> 1\n t(k) = op (t(i), t(i^1))\n loop (k)\n }\n }\n loop (p0)\n }\n def root = t(1)\n //op - commutative\n def reduce (l: Int, r: Int) = {\n var res = empty\n @tailrec def loop (i: Int, j: Int) {\n if (i < j) {\n if (0 != (i & 1)) res = op (res, t(i))\n if (0 != (j & 1)) res = op (t(j-1), res)\n loop ((i + 1) >>> 1, j >>> 1)\n }\n }\n loop (l + n, r + n)\n res\n }\n def safeReduce (l: Int, r: Int) = {\n var resl = empty\n var resr = empty\n @tailrec def loop (i: Int, j: Int) {\n if (i < j) {\n if (0 != (i & 1)) resl = op (resl, t(i))\n if (0 != (j & 1)) resr = op (t(j-1), resr)\n loop ((i + 1) >>> 1, j >>> 1)\n }\n }\n loop (l + n, r + n)\n op (resl, resr)\n }\n }\n\n import io._\n val lineit:Iterator[String] = Source.stdin.getLines.filterNot(_.isEmpty).flatMap(i => i.split(\" \"))\n val sb = new StringBuilder\n def rs() = lineit.next\n def ri() = rs.toInt\n def main(args: Array[String]) {\n val n = ri\n val m = ri\n val a = Array.fill (1< {\n if ((x & 0x80000000) == 0) x | y | 0x80000000 else (x ^ y) & 0x7fffffff\n }, 0) \n for (t <- 1 to m) {\n val i = ri - 1\n val v = ri\n st(i) = v\n sb.append (st.root & 0x7fffffff)\n sb.append ('\\n')\n }\n print (sb)\n }\n}\n"}, {"source_code": "object Main {\n import annotation.tailrec\n class SegmentTree [T: reflect.ClassTag] (a: Array[T], op: (T, T) => T, empty: T) {\n private val n = a.size\n private val t = Array.ofDim (2*n)\n private def build {\n for (i <- n - 1 until 0 by - 1) {\n val k = i << 1\n t(i) = op (t(k), t(k+1))\n }\n }\n Array.copy (a, 0, t, n, n)\n build\n def update (p: Int, v: T) {\n val p0 = p + n\n t(p0) = v\n @tailrec def loop (i: Int) {\n if (i > 1) {\n val k = i >>> 1\n t(k) = op (t(i), t(i^1))\n loop (k)\n }\n }\n loop (p0)\n }\n def root = t(1)\n //op - commutative\n def reduce (l: Int, r: Int) = {\n var res = empty\n @tailrec def loop (i: Int, j: Int) {\n if (i < j) {\n if (0 != (i & 1)) res = op (res, t(i))\n if (0 != (j & 1)) res = op (t(j-1), res)\n loop ((i + 1) >>> 1, j >>> 1)\n }\n }\n loop (l + n, r + n)\n res\n }\n def safeReduce (l: Int, r: Int) = {\n var resl = empty\n var resr = empty\n @tailrec def loop (i: Int, j: Int) {\n if (i < j) {\n if (0 != (i & 1)) resl = op (resl, t(i))\n if (0 != (j & 1)) resr = op (t(j-1), resr)\n loop ((i + 1) >>> 1, j >>> 1)\n }\n }\n loop (l + n, r + n)\n op (resl, resr)\n }\n }\n\n import io._\n val lineit:Iterator[String] = Source.stdin.getLines.filterNot(_.isEmpty).flatMap(i => i.split(\" \"))\n val sb = new StringBuilder\n def rs() = lineit.next\n def ri() = rs.toInt\n def main(args: Array[String]) {\n val n = ri\n val m = ri\n val a = Array.fill (1< (if ((x._2 & 1) == 0) x._1 | y._1 else x._1 ^ y._1, x._2 ^ 1), (0, 0) )\n for (t <- 1 to m) {\n val i = ri - 1\n val v = ri\n st(i) = (v, 0)\n sb.append (st.root._1)\n sb.append ('\\n')\n }\n print (sb)\n }\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C197D(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C197D(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n: Int = ni()\n val m = ni()\n val limit = Math.pow(2, n).toInt\n\n val a: Array[Int] = na(limit)\n\n val t = new SegmentTree(limit, a)\n t.build(1, 0, limit - 1, if(limit%2 == 0) false else true)\n REP(m) { _ =>\n val p = ni()\n val b = ni()\n t.update(1, 0, limit - 1, if(limit%2 == 0) false else true, p - 1, b)\n out.println(t.getAnswer)\n }\n }\n\n private class SegmentTree(n: Int, a: Array[Int]) {\n private val tree: Array[Int] = Array.ofDim[Int](4 * n)\n\n def build(v: Int, tl: Int, tr:Int, op: Boolean): Unit = {\n if(tl == tr) {\n tree(v) = a(tl)\n } else {\n val tm = tl + (tr - tl) / 2\n build(v << 1, tl, tm, !op)\n build(v << 1 | 1, tm + 1, tr, !op)\n tree(v) = if(op) tree(v << 1) | tree(v << 1 | 1) else tree(v << 1) ^ tree(v << 1 | 1)\n }\n }\n\n def update(v: Int, tl: Int, tr: Int, op: Boolean, index: Int, value: Int): Unit = {\n if(tl == tr) {\n tree(v) = value\n } else {\n val tm = tl + (tr - tl) / 2\n if(index <= tm) {\n update(v << 1, tl, tm, !op, index, value)\n } else {\n update(v << 1 | 1, tm + 1, tr, !op, index, value)\n }\n tree(v) = if(op) tree(v << 1) | tree(v << 1 | 1) else tree(v << 1) ^ tree(v << 1 | 1)\n }\n }\n\n def getAnswer: Int = {\n tree(1)\n }\n\n }\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val as = readInts(1 << n)\n\n val bitStep = Array.tabulate(18, n + 1)((i, j) => new mutable.BitSet(1 << (n - j + 1)))\n\n for (bit <- 0 to 17) {\n val mask = 1 << bit\n bitStep(bit)(0) ++= as.indices.filter(i => (as(i) & mask) > 0).map(_ + 1)\n for (step <- 1 to n) {\n bitStep(bit)(step) ++= (if (step % 2 == 1)\n (1 to 1 << (n - step)).filter(i => bitStep(bit)(step - 1)(2 * i) || bitStep(bit)(step - 1)(2 * i - 1))\n else\n (1 to 1 << (n - step)).filter(i => bitStep(bit)(step - 1)(2 * i) ^ bitStep(bit)(step - 1)(2 * i - 1)))\n }\n }\n\n def calc() = {\n var result = 0\n for (bit <- 0 to 17; if bitStep(bit)(n)(1)) result += (1 << bit)\n result\n }\nif (100000 == m) println(calc())\nelse {\n var k = 0\n while (k < m) {\n val t = tokenizeLine\n val p0 = t.nextToken.toInt\n val b = t.nextToken.toInt\n\n for (bit <- 0 to 17) {\n val mask = 1 << bit\n bitStep(bit)(0)(p0) = ((b & mask) > 0)\n var p = p0\n for (step <- 1 to n) {\n p = (p + 1) >> 1\n if (step % 2 == 1) bitStep(bit)(step)(p) = bitStep(bit)(step - 1)(2 * p) || bitStep(bit)(step - 1)(2 * p - 1)\n else bitStep(bit)(step)(p) = bitStep(bit)(step - 1)(2 * p) ^ bitStep(bit)(step - 1)(2 * p - 1)\n }\n }\n\n println(calc())\n\n k += 1\n }\n}\n Console.flush\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val as = readInts(1 << n)\n\n val bitStep = Array.tabulate(18, n + 1)((i, j) => new mutable.BitSet(1 << (n - j + 1)))\n\n for (bit <- 0 to 17) {\n val mask = 1 << bit\n bitStep(bit)(0) ++= as.indices.filter(i => (as(i) & mask) > 0).map(_ + 1)\n for (step <- 1 to n) {\n bitStep(bit)(step) ++= (if (step % 2 == 1)\n (1 to 1 << (n - step)).filter(i => bitStep(bit)(step - 1)(2 * i) || bitStep(bit)(step - 1)(2 * i - 1))\n else\n (1 to 1 << (n - step)).filter(i => bitStep(bit)(step - 1)(2 * i) ^ bitStep(bit)(step - 1)(2 * i - 1)))\n }\n }\n\n def calc() = {\n var result = 0\n for (bit <- 0 to 17; if bitStep(bit)(n)(1)) result += (1 << bit)\n result\n }\nprintln(calc())\nConsole.flush\n var k = 0\n while (k < m) {\n val t = tokenizeLine\n val p0 = t.nextToken.toInt\n val b = t.nextToken.toInt\n\n for (bit <- 0 to 17) {\n val mask = 1 << bit\n bitStep(bit)(0)(p0) = ((b & mask) > 0)\n var p = p0\n for (step <- 1 to n) {\n p = (p + 1) >> 1\n if (step % 2 == 1) bitStep(bit)(step)(p) = bitStep(bit)(step - 1)(2 * p) || bitStep(bit)(step - 1)(2 * p - 1)\n else bitStep(bit)(step)(p) = bitStep(bit)(step - 1)(2 * p) ^ bitStep(bit)(step - 1)(2 * p - 1)\n }\n }\n\n println(calc())\n\n k += 1\n }\n\n Console.flush\n}\n"}, {"source_code": "object Main {\n import annotation.tailrec\n class SegmentTree [T: reflect.ClassTag] (a: Array[T], op: (T, T) => T, empty: T) {\n private val n = a.size\n private val t = Array.ofDim (2*n)\n private def build {\n for (i <- n - 1 until 0 by - 1) {\n val k = i << 1\n t(i) = op (t(k), t(k+1))\n }\n }\n Array.copy (a, 0, t, n, n)\n build\n def update (p: Int, v: T) {\n val p0 = p + n\n t(p0) = v\n @tailrec def loop (i: Int) {\n if (i > 1) {\n val k = i >>> 1\n t(k) = op (t(i), t(i^1))\n loop (k)\n }\n }\n loop (p0)\n }\n def root = t(1)\n //op - commutative\n def reduce (l: Int, r: Int) = {\n var res = empty\n @tailrec def loop (i: Int, j: Int) {\n if (i < j) {\n if (0 != (i & 1)) res = op (res, t(i))\n if (0 != (j & 1)) res = op (t(j-1), res)\n loop ((i + 1) >>> 1, j >>> 1)\n }\n }\n loop (l + n, r + n)\n res\n }\n def safeReduce (l: Int, r: Int) = {\n var resl = empty\n var resr = empty\n @tailrec def loop (i: Int, j: Int) {\n if (i < j) {\n if (0 != (i & 1)) resl = op (resl, t(i))\n if (0 != (j & 1)) resr = op (t(j-1), resr)\n loop ((i + 1) >>> 1, j >>> 1)\n }\n }\n loop (l + n, r + n)\n op (resl, resr)\n }\n }\n\n import io._\n val lineit:Iterator[String] = Source.stdin.getLines.filterNot(_.isEmpty).flatMap(i => i.split(\" \"))\n val sb = new StringBuilder\n def rs() = lineit.next\n def ri() = rs.toInt\n def main(args: Array[String]) {\n val n = ri\n val m = ri\n val a = Array.fill (1< {\n if ((x & 0x80000000) == 0) x | y | 0x80000000 else (x ^ y) & 0x7fffffff\n }, 0) \n for (t <- 1 to m) {\n val i = ri - 1\n val v = ri\n st(i) = v\n sb.append (st.root)\n sb.append ('\\n')\n }\n print (sb)\n }\n}\n"}], "src_uid": "40d1ea98aa69865143d44432aed4dd7e"} {"source_code": "import scala.io.StdIn._\n\nobject CF1345B extends App {\n\n def solve() = {\n val n = readLine().toInt\n loopWithIndex(n) { i =>\n var n = readLine.toLong\n var pyr = 0\n var flag = true;\n while (flag) {\n val z = calc(n)\n if (n < z || z ==0) {\n flag = false\n } else {\n pyr += 1\n n -= num(z)\n }\n }\n println(pyr)\n }\n }\n\n def num(n: Long): Long = (3L * n + 1) * n.toLong / 2\n\n def calc(numCards: Long): Long = ((math.sqrt(24.toLong * numCards + 1) - 1) / 6.toLong).toLong\n\n def loopWithIndex[T](n: Int)(block: Int => T): Unit =\n (1 to n).foreach(e => block(e))\n\n try { \n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\nimport scala.math._\n\nobject B {\n\n def cardsNeededForPir(n: Int) = (3 * n * n + n) / 2\n\n def biggestPirCanMake(cards: Int) = (floor(4*sqrt(1.0 / 16+3.0 / 2 * cards) - 1) / 6).toInt\n\n def solution(n: Int): Int = {\n\n def rec(i: Int, acc: Int): Int = {\n if (i < 2) acc else {\n val nextPirDim = biggestPirCanMake(i)\n val cardsInPir = cardsNeededForPir(nextPirDim)\n rec(i - cardsInPir, acc + 1)\n }\n }\n rec(n, 0)\n }\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val n = readLine.toInt\n println(solution(n))\n }\n }\n}"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n private def height(n: Long): Int =\n (math.sqrt(24 * n + 1) - 1).toInt / 6\n\n private def cards(h: Int): Int =\n h * (3 * h + 1) / 2\n\n private def solve(n: Long, count: Int = 0): Int =\n if (n == 0) count\n else {\n val h = height(n)\n\n if (h == 0) count\n else solve(n - cards(h), count + 1)\n }\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readLong()\n\n val ans = solve(n)\n\n println(ans)\n }\n}\n"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n private def height(n: Long): Long = (math.sqrt(1 + 24 * n) - 1).toLong / 6\n\n private def cards(h: Long): Long = h * (3 * h + 1) / 2\n\n private def solve(n: Long, count: Int = 0): Long =\n if (n == 0) count\n else {\n val h = height(n)\n\n if (h == 0) count\n else solve(n - cards(h), count + 1)\n }\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readLong()\n\n val ans = solve(n)\n\n println(ans)\n }\n}\n"}, {"source_code": "object ProblemB extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n import scala.collection.mutable\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val n = in.nextInt()\n\n val piramids = mutable.ArrayBuffer[Int]()\n\n var prev = 0L\n var leyyer = 2L\n val increment = 3\n var i = 0\n while (prev < 1000000000) {\n prev += leyyer\n leyyer += increment\n i += 1\n piramids += prev.toInt\n }\n\n def findPiramidSize(m: Int, left: Int = 0, right: Int = piramids.length): Int = {\n if (right - left < 3) {\n for (i <- (left to math.min(right, piramids.length - 1)).reverse ) {\n if (piramids(i) <= m) {\n return piramids(i)\n }\n }\n\n return Int.MaxValue\n }\n val midOne = (left + right) / 2\n\n if (piramids(midOne) > m) {\n findPiramidSize(m, left, midOne - 1)\n } else {\n if (piramids(midOne) == m) {\n piramids(midOne)\n } else {\n findPiramidSize(m, midOne, right)\n }\n }\n }\n\n for (i <- 1 to n) {\n var m = in.nextInt()\n\n var result = 0\n\n while (m > 1) {\n val i1 = findPiramidSize(m)\n m = m - i1\n result += 1\n }\n\n println(result)\n }\n\n}"}], "negative_code": [{"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n private def height(n: Int): Int =\n (math.sqrt(24 * n + 1) - 1).toInt / 6\n\n private def cards(h: Int): Int =\n h * (3 * h + 1) / 2\n\n private def solve(n: Int, count: Int = 0): Long =\n if (n == 0) count\n else {\n val h = height(n)\n\n if (h == 0) count\n else solve(n - cards(h), count + 1)\n }\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n\n val ans = solve(n)\n\n println(ans)\n }\n}\n"}], "src_uid": "02062d1afe85e3639edddedceac304f4"} {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nobject B extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val grid = Array.fill(n){ readLine }\n val spiders = Array.fill(m)(0)\n \n for (j <- 0 until m) {\n var count = 0\n for (i <- 0 until n) if (i % 2 == 0 && grid(i)(j) == 'U') count += 1\n for (i <- 0 to (j min (n - 1))) if (grid(i)(j - i) == 'R') count += 1\n for (i <- 0 to ((m - j - 1) min (n - 1))) if (grid(i)(j + i) == 'L') count += 1\n spiders(j) = count\n }\n \n println(spiders.mkString(\" \"))\n}", "positive_code": [{"source_code": "import java.util.Scanner\n\n/**\n * Created by hama_du on 2014/06/19.\n */\nobject ProblemB extends App {\n val in = new Scanner(System.in)\n val n,m,k = in.nextInt()\n val map = (0 until n).map(_ => in.next().toCharArray).toArray\n val answer = (0 until m).map(x => {\n val left = (1 until n).count(i => ((x - i) >= 0 && map(i)(x-i) == 'R'))\n val right = (1 until n).count(i => ((x + i) < m && map(i)(x+i) == 'L'))\n val down = (0 until n by 2).count(i => map(i)(x) == 'U')\n left + right + down\n }).mkString(\" \")\n println(answer)\n}\n"}], "negative_code": [], "src_uid": "d8c89bb83592a1ff1b639f7d53056d67"} {"source_code": "object A667 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(d, h, v, e) = readInts(4)\n val area = (math.Pi*d*d)/4.0\n val initVolume = h*area\n val rain = e*area\n\n if(v > rain) {\n println(\"YES\")\n println(\"%.12f\".format(initVolume/(v-rain)))\n } else {\n println(\"NO\")\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(d, h, v, e) = in.next().split(' ').map(_.toInt)\n val delta = v / (Math.PI * d * d / 4) - e\n if (delta <= 0)\n println(\"NO\")\n else {\n println(\"YES\")\n println(h / delta)\n }\n}"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, java.awt._\n\nobject _667A extends CodeForcesApp {\n override def apply(io: IO) = {\n val d, h, v, e = io[Double]\n val r = d/2\n\n def volume(x: Double) = Math.PI * r * r * x\n\n if (v > volume(e)) {\n io.+=(\"YES\").appendNewLine().+=(volume(h)/(v - volume(e)))\n } else {\n io += \"NO\"\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[I] = new {\n def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val newLine: String = \"\\n\"\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = this.+=(xs.size).appendNewLine().+=(xs)\n\n def appendNewLine(): this.type = {\n println()\n this\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "fc37ef81bb36f3ac07ce2c4c3ec10d98"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val l, r, d = nl()\n if (d < l) out.println(d)\n else out.println((r / d + 1) * d)\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "\n\nobject MinimumInteger extends App {\n\n val q = io.StdIn.readLine.toInt\n\n for (_ <- 1 to q) {\n val ints = io.StdIn.readLine.split(\" \").map(_.toInt)\n val (l, r, d) = (ints(0), ints(1), ints(2))\n\n if (l > d || r < d) println(d)\n else {\n println(d * ((r - r % d) / d + 1))\n }\n }\n}\n"}, {"source_code": "object EDU_58_A {\n\n type In = (Int, Seq[(Int, Int, Int)])\n type Out = String\n \n def solve(in: In): Out = {\n val (n, xs) = in\n val result = for {\n (l, r, d) <- xs\n } yield if(d l.split(\" \") match {case Array(a,b,c) => (a.toInt,b.toInt,c.toInt)}}})\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change: \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def ceil(a: Int, b: Int) = (a - 1)/b + 1\n def ceil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Solution {\n //Console.setIn(new FileReader(new java.io.File(\"in\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n\n val magicMod = 1000000007\n\n def doCase(caseNo: Int): Unit = {\n val Array(l, r, d) = readIntLine()\n\n if (d < l) {\n println(d)\n } else {\n println((r / d + 1) * d)\n }\n }\n\n def main(args: Array[String]): Unit = {\n val noCases = readInt()\n for (i <- 0 until noCases) {\n doCase(i)\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n def readLongLine(): Array[Long] = {\n StdIn.readLine().split(\" \").map(_.toLong)\n }\n\n def readBigIntLine(): Array[BigInt] = {\n StdIn.readLine().split(\" \").map(BigInt.apply)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject kimollg extends App {\n //println(\"Zdorova!\")\n val n = scala.io.StdIn.readInt()\n for (i <- 0 until n){\n val inps = StdIn.readLine().split(\" \").map(_.toInt)\n val (l,r,d) = (inps(0),inps(1),inps(2))\n if (d= n || next(i) == i) i\n else {\n next(i) = getNext(next(i))\n next(i)\n }\n }\n\n (1 to m).foreach { _ =>\n val Array(l, r, x) = in.next().split(' ').map(_.toInt - 1)\n var current = getNext(l)\n while (current <= r) {\n if (current == x) current += 1\n else {\n answer(current) = x + 1\n next(current) = current + 1\n }\n current = getNext(current)\n }\n }\n println(answer.mkString(\" \"))\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val lostTo = Array.fill(n)(0)\n var alive = immutable.TreeSet[Int]() ++ (0 until n)\n var aliveCount = n\n \n var i = 0\n while (i < m) {\n i += 1\n val t = tokenizeLine\n val l = t.nextToken.toInt - 1\n val r = t.nextToken.toInt - 1\n val winner = t.nextToken.toInt\n val x = winner - 1\n \n if (r - l <= 548) {\n var j = l\n while (j <= r) {\n if (j != x && lostTo(j) == 0) {\n lostTo(j) = winner\n alive = alive - j\n aliveCount -= 1\n }\n j += 1\n }\n } else {\n for (j <- alive.range(l - 1, r + 1)) {\n if (j >= l && j <= r && j != x) {\n lostTo(j) = winner\n alive = alive - j\n aliveCount -= 1\n }\n }\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(lostTo.mkString(\" \"))\n Console.flush\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val lostTo = Array.fill(n)(0)\n //var alive = immutable.TreeSet[Int]() ++ (0 until n)\n val alive = new java.util.TreeSet(JavaConversions.asJavaList(0 until n))\n\n for (i <- 0 until m) {\n val t = tokenizeLine\n val l = t.nextToken.toInt - 1\n val r = t.nextToken.toInt - 1\n val winner = t.nextToken.toInt\n val x = winner - 1\n\n val iter = alive.subSet(l, r + 1).iterator\n while (iter.hasNext) {\n val j = iter.next\n if (j != x) {\n lostTo(j) = winner\n iter.remove\n }\n }\n }\n\n println(lostTo.mkString(\" \"))\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val lostTo = Array.fill(n)(0)\n var alive = immutable.TreeSet[Int]() ++ (0 until n)\n\n for (i <- 0 until m) {\n val t = tokenizeLine\n val l = t.nextToken.toInt - 1\n val r = t.nextToken.toInt - 1\n val winner = t.nextToken.toInt\n val x = winner - 1\n\n for (j <- alive.range(l, r + 1) if j != x) {\n lostTo(j) = winner\n alive -= j\n }\n }\n\n println(lostTo.mkString(\" \"))\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C207C(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C207C(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n\n val m = ni()\n val t = new SegmentTree(n)\n REP(m) { _ =>\n val l = ni()\n val r = ni()\n val x = ni()\n\n t.update(1, 0, n-1, l-1, x-2, x-1)\n t.update(1, 0, n-1, x, r-1, x-1)\n }\n\n REP(n) { i =>\n val x = t.get(1, 0, n-1, i)\n out.print((if(x != -1) x + 1 else 0)+ \" \")\n }\n }\n\n private class SegmentTree(n: Int) {\n val tree: Array[Int] = Array.fill[Int](4 * n)(-1)\n val marked: Array[Boolean] = Array.fill[Boolean](4 * n)(false)\n\n def push_2(v: Int): Unit = {\n if(marked(v)) {\n val ch1 = v << 1\n if(!marked(ch1)) {\n tree(ch1) = tree(v)\n marked(ch1) = true\n }\n val ch2 = ch1 | 1\n if(!marked(ch2)) {\n tree(ch2) = tree(v)\n marked(ch2) = true\n }\n marked(v) = false\n }\n }\n\n def update(v: Int, tl: Int, tr: Int, l: Int, r: Int, nVal: Int): Unit = {\n if(marked(v)) {}\n else if(tl == l && tr == r) {\n tree(v) = nVal\n marked(v) = true\n } else if(r >= l) {\n val tm = tl + (tr - tl) / 2\n update(v << 1, tl , tm, l, Math.min(tm, r), nVal)\n update(v << 1 | 1, tm + 1, tr, Math.max(l, tm + 1), r, nVal)\n }\n }\n\n def get(v: Int, tl: Int, tr: Int, pos: Int): Int = {\n if(tl == tr) tree(v)\n else {\n push_2(v)\n val tm = tl + (tr - tl) / 2\n if(pos <= tm) {\n get(v << 1, tl, tm, pos)\n } else {\n get(v << 1 | 1, tm+1, tr, pos)\n }\n }\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.math.min\nimport scala.math.max\n\nobject a{\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n\n import InOut._\n\n def lchild(num:Int):Int = return num << 1\n def rchild(num:Int):Int = return (num << 1)|1\n case class round(num:Int, winner:Int)\n \n def build_simple(tree:Array[round], rounds:Int):Array[round] = {\n return tree.map(_ => round(rounds, -1))\n }\n\n def modify(tree:Array[round], node:Int, tl:Int, tr:Int, l:Int, r:Int, fight:round):Unit = {\n if (l > r){\n return\n }\n if (tl == l && tr == r){\n tree(node) = fight\n return\n }\n val tm = (tl+tr)>>1\n modify(tree, lchild(node), tl, tm, l, min(tm, r), fight)\n modify(tree, rchild(node), tm+1, tr, max(tm+1, l), r, fight)\n }\n \n def query(tree:Array[round], node:Int, tl:Int, tr:Int, pos:Int):round = {\n if (tl == tr){\n return tree(node)\n }\n val tm = (tl+tr)>>1\n if (pos <= tm){\n val lans = query(tree, lchild(node), tl, tm, pos)\n if (lans.num < tree(node).num){\n return lans\n }else{\n return tree(node)\n }\n }\n else {\n val rans = query(tree, rchild(node), tm+1, tr, pos)\n if (rans.num < tree(node).num){\n return rans\n }else{\n return tree(node)\n }\n }\n }\n\n def main(args:Array[String]){\n val n, m = nextInt\n var tree = build_simple(new Array[round](4*n), m)\n\n val input = new Array[(Int, Int, Int)](m)\n for (i <- 0 until m){ \n val li, ri, xi = nextInt\n input(i) = (li-1, ri-1, xi-1)\n }\n for (i <- 1 to m){\n val info = input(m-i)\n modify(tree, 1, 0, n-1, info._1, info._3-1, round(m-i, info._3))\n modify(tree, 1, 0, n-1, info._3+1, info._2, round(m-i, info._3))\n }\n\n for (i <- 0 until n){\n val round_info = query(tree, 1, 0, n-1, i)\n if (round_info.winner == -1){\n println(0)\n }else{\n println(round_info.winner + 1)\n }\n }\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val answer = Array.ofDim[Int](n)\n var left = (0 until n).toSet\n (1 to m).foreach { _ =>\n val Array(l, r, x) = in.next().split(' ').map(_.toInt - 1)\n left.filter(i => i >= l && i <= r).foreach { i => if (answer(i) == 0 && i != x)\n answer(i) = x + 1\n left -= i\n }\n }\n println(answer.mkString(\" \"))\n\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val lostTo = Array.fill(n)(0)\n var alive = immutable.TreeSet[Int]() ++ (0 until n)\n\n for (i <- 0 until m) {\n val t = tokenizeLine\n val l = t.nextToken.toInt - 1\n val r = t.nextToken.toInt - 1\n val winner = t.nextToken.toInt\n val x = winner - 1\n\n for (j <- alive.range(l - 1, r + 1) if j != x) {\n lostTo(j) = winner\n alive -= j\n }\n }\n\n println(lostTo.mkString(\" \"))\n}"}], "src_uid": "a608eda195166231d14fbeae9c8b31fa"} {"source_code": "object A1255 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var tests = readInt\n while (tests > 0) {\n var Array(a, b) = readLongs(2).sorted\n\n var res = 0\n val fives = (b - a) / 5\n val two = ((b - a) - (fives * 5)) / 2\n val one = ((b - a) - (fives * 5) - (two * 2))\n\n out.println(fives + two + one)\n tests -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "object _1255A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val a, b = io.read[Int]\n val d = (a - b).abs\n val ans = d % 5 match {\n case 0 => d/5\n case 1 | 2 => d/5 + 1\n case 3 | 4 => d/5 + 2\n }\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "ccfe798f5dc63c492ff54cf40bb40613"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CF653A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CF653A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val n = ni()\n val s = ns(n)\n var cntO = 0\n var ans = 0\n REP(n) { i =>\n if(s(i) == '(') cntO+=1\n else if(s(i) == ')' && cntO > 0) cntO -= 1\n else {\n ans+=1\n }\n }\n out.println(ans)\n }\n }\n\n}\n", "positive_code": [{"source_code": "//package codeforces.contests._1374\n\n/*\nhttps://codeforces.com/contest/1374/problem/C\n */\nobject MoveBrackets {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt()) {\n val n = io.StdIn.readInt()\n val s = io.StdIn.readLine().toList\n\n\n @scala.annotation.tailrec\n def loop(ls: List[Char], score: Int = 0, acc: Int = 0): Int = {\n ls match {\n case Nil => acc\n case '(' :: tail => loop(tail, score + 1, acc)\n case ')' :: tail if score == 0 => loop(tail, score, acc + 1)\n case ')' :: tail => loop(tail, score - 1, acc)\n }\n }\n\n println(loop(s))\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\nimport math._\n\nobject CF653_C extends App {\n val t = readInt()\n for (_ <- 0 until t) {\n val _ = readInt()\n val s = readLine()\n\n var delta = 0\n var max_abs_delta = 0\n for (c <- s) {\n if (c == '(') {\n delta += 1\n } else {\n delta -= 1\n }\n\n max_abs_delta = max(max_abs_delta, -delta)\n }\n\n println(max_abs_delta)\n }\n}\n"}, {"source_code": "\nobject C extends App {\n\n import scala.collection.mutable\n import scala.io.Source\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.collection.mutable.Stack\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n\n /* Implicit methods */\n\n// val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val n = in.nextInt()\n\n n.times {\n val number = in.nextInt()\n val input = in.line()\n var stack = mutable.Stack[Char]()\n var imbalanced = 0\n input.foreach(x => {\n if (x == '(') {\n stack.push(x)\n } else {\n if (stack.nonEmpty) {\n val popped = stack.pop()\n if (popped != '(') {\n imbalanced = imbalanced + 1\n }\n } else {\n imbalanced = imbalanced + 1\n }\n }\n })\n imbalanced = imbalanced + stack.length\n println(imbalanced / 2)\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n\n}"}], "negative_code": [], "src_uid": "7a724f327c6202735661be25ef9328d2"} {"source_code": "object Solution extends App {\n val firstLine = readLine().split(\" \").map(_.toInt)\n val m = firstLine(0) // number of paint\n val n = firstLine(1) // number of person\n val cost = new Array[Array[Int]](m)\n\n for(i<- 0 until m) {\n cost(i) = readLine().split(\" \").map(_.toInt).toArray\n }\n\n\n val dp = new Array[Array[Int]](n)\n for(i <- 0 until n) dp(i) = new Array[Int](m)\n\n for(i <- 0 until n)\n for(j <- 0 until m) {\n dp(i)(j) = cost(j)(i)\n if(j > 0) dp(i)(j) = math.max(dp(i)(j), dp(i)(j - 1) + cost(j)(i))\n if(i > 0) dp(i)(j) = math.max(dp(i)(j), dp(i - 1)(j) + cost(j)(i))\n }\n\n println(dp(n - 1) mkString \" \")\n\n}\n", "positive_code": [{"source_code": "object Main {\n def main (args: Array[String]) {\n val Array(m, n) = readLine().split(\" \").map(_.toInt)\n val times = new Array[Int](n)\n val answer = for (i <- 1 to m) yield {\n val t = readLine().split(\" \").map(_.toInt)\n times(0) += t(0)\n for (k <- 1 until n) {\n times(k) = max(times(k - 1), times(k)) + t(k)\n }\n times.last\n }\n\n print(answer(0))\n for (i <- 1 until m) {\n print(\" \" + answer(i))\n }\n println()\n }\n\n def max(x: Int, y: Int) = if (x > y) x else y\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject B extends App {\n val sc = new Scanner(Console.in)\n val m = sc.nextInt()\n val n = sc.nextInt()\n val T = Array.ofDim[Int](m, n)\n val U = Array.ofDim[Int](m, n)\n\n for(i <- 0 until m) {\n for(j <- 0 until n) {\n T(i)(j) = sc.nextInt()\n }\n }\n\n U(0)(0) = T(0)(0)\n for(j <- 1 until n) {\n U(0)(j) = U(0)(j - 1) + T(0)(j)\n }\n\n for(i <- 1 until m) {\n U(i)(0) = T(i)(0) + U(i-1)(0)\n for(j <- 1 until n) {\n U(i)(j) = T(i)(j) + math.max(U(i-1)(j), U(i)(j-1))\n }\n }\n\n for(i <- 0 until m) {\n print(U(i)(n-1))\n print(\" \")\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject B extends App {\n val sc = new Scanner(System.in)\n val m = sc.nextInt()\n val n = sc.nextInt()\n val T = Array.ofDim[Int](m, n)\n val U = Array.ofDim[Int](m, n)\n\n for(i <- 0 until m) {\n for(j <- 0 until n) {\n T(i)(j) = sc.nextInt()\n }\n }\n\n U(0)(0) = T(0)(0)\n for(j <- 1 until n) {\n U(0)(j) = U(0)(j - 1) + T(0)(j)\n }\n\n for(i <- 1 until m) {\n U(i)(0) = T(i)(0) + U(i-1)(0)\n for(j <- 1 until n) {\n U(i)(j) = T(i)(j) + math.max(U(i-1)(j), U(i)(j-1))\n }\n }\n\n for(i <- 0 until m) {\n print(U(i)(n-1))\n print(\" \")\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n\n val Array(m, n) = in.next().split(' ').map(_.toInt)\n val data = (1 to m).map(_ => in.next().split(' ').map(_.toInt))\n val res = (1 until n).foldLeft(data.map(_.head).scanLeft(0){_+_}.tail) {\n case(acc, el) =>\n val master = data.map(_(el))\n var finish = 0\n master.zip(acc).map {\n case((current, previous)) =>\n finish = Math.max(previous + current, finish + current)\n finish\n }\n }\n println(res.mkString(\" \"))\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject B extends App {\n \nval sc = new Scanner(System.in)\n\nval n = sc.nextInt()\nval m = sc.nextInt()\n\nval in = Array.ofDim[Int](n, m)\n\nfor (i <- 0 until n) {\n for (j <- 0 until m) {\n in(i)(j) = sc.nextInt()\n }\n}\n\nval dp = new Array[Int](m)\nfor (i <- 0 until n) {\n for (j <- 0 until m) {\n if (j != 0)\n dp(j) = (dp(j-1) max dp(j)) + in(i)(j)\n else\n dp(j) += in(i)(j)\n }\n print(dp(m-1) + \" \")\n}\n\n}"}], "negative_code": [], "src_uid": "43f4ea06d8b8b0b6b6795a3d526c5a2d"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A, B = ns(N)\n\n def grouped(S: Array[Char]): Array[mutable.Stack[Int]] = {\n val C = Array.fill[mutable.Stack[Int]](27)(mutable.Stack()) // 26に?のぱしょが入っている\n REP(N) { i =>\n if (S(i) == '?') C(26).push(i)\n else C(S(i) - 'a').push(i)\n }\n C\n }\n\n val Ca = grouped(A)\n val Cb = grouped(B)\n\n DEBUG {\n REP(27) { i =>\n debugL(i)\n debug(\"[\"+Ca(i).mkString(\",\")+\"]\")\n debug(\"[\"+Cb(i).mkString(\",\")+\"]\")\n }\n }\n\n val ans = ArrayBuffer[(Int, Int)]()\n REP(26) { i =>\n while(Ca(i).nonEmpty && Cb(i).nonEmpty) {\n val ai = Ca(i).pop()\n val bi = Cb(i).pop()\n ans += ((ai, bi))\n }\n }\n\n REP(26) { i =>\n while(Ca(i).nonEmpty && Cb(26).nonEmpty) {\n val ai = Ca(i).pop()\n val bi = Cb(26).pop()\n ans += ((ai, bi))\n }\n while(Ca(26).nonEmpty && Cb(i).nonEmpty) {\n val ai = Ca(26).pop()\n val bi = Cb(i).pop()\n ans += ((ai, bi))\n }\n }\n while(Ca(26).nonEmpty && Cb(26).nonEmpty) {\n val ai = Ca(26).pop()\n val bi = Cb(26).pop()\n ans += ((ai, bi))\n }\n\n\n out.println(ans.length)\n ans.foreach { case (a, b) =>\n out.println(s\"${a+1} ${b+1}\")\n }\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n", "positive_code": [{"source_code": "object _1141D extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val n = io.read[Int]\n type E = (Char, Int)\n val (wildcardL, regularL), (wildcardR, regularR) = io.read[String].zip(1 to n).sorted.toList.partition(_._1 == '?')\n\n val unmatchedL, unmatchedR = mutable.ArrayBuffer.empty[E]\n val ans = mutable.ArrayBuffer.empty[(E, E)]\n\n @tailrec def loop(left: List[E], right: List[E]): Unit = (left, right) match {\n case ((l1 @ (lc, _)) :: ls, (r1 @ (rc, _)) :: rs) =>\n if (lc < rc) {\n unmatchedL += l1\n loop(ls, right)\n } else if (lc > rc) {\n unmatchedR += r1\n loop(left, rs)\n } else {\n ans += l1 -> r1\n loop(ls, rs)\n }\n case _ =>\n unmatchedL ++= left\n unmatchedR ++= right\n }\n\n loop(left = regularL, right = regularR)\n\n ans ++= unmatchedL.zip(wildcardR)\n ans ++= wildcardL.zip(unmatchedR)\n ans ++= wildcardL.drop(unmatchedR.length).zip(wildcardR.drop(unmatchedL.length))\n\n io.writeLine(ans.length).writeLines(ans.map({case ((_, i), (_, j)) => s\"$i $j\"}))\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "object _1141D extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val n = io.read[Int]\n type E = (Char, Int)\n val (wildcardL, regularL), (wildcardR, regularR) = io.read[String].zip(1 to n).sorted.toList.partition(_._1 == '?')\n\n val unmatchedL, unmatchedR = mutable.ArrayBuffer.empty[E]\n val ans = mutable.ArrayBuffer.empty[(E, E)]\n\n @tailrec\n def loop(left: List[E], right: List[E]): Unit = (left, right) match {\n case (Nil, _) => unmatchedR ++= right\n case (_, Nil) => unmatchedL ++= left\n\n case ((l1 @ (lc, _)) :: ls, (r1 @ (rc, _)) :: rs) =>\n if (lc < rc) {\n unmatchedL += l1\n loop(ls, right)\n } else if (lc > rc) {\n unmatchedR += r1\n loop(left, rs)\n } else {\n ans += l1 -> r1\n loop(ls, rs)\n }\n }\n loop(left = regularL, right = regularR)\n\n ans ++= unmatchedL.zip(wildcardR)\n ans ++= unmatchedR.zip(wildcardL)\n ans ++= wildcardR.drop(unmatchedL.length).zip(wildcardL.drop(unmatchedR.length))\n\n io.writeLine(ans.length).writeLines(ans.map({case ((_, i), (_, j)) => s\"$i $j\"}))\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "6bf3e5a542ebce81c1e6ce7260644a3c"} {"source_code": "object B556 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val a = readInts(n)\n var t = 0\n var break = false\n while(!break && t < n) {\n if(a.zipWithIndex.forall(x => x._1 == x._2)) {\n println(\"Yes\")\n break = true\n }\n for(i <- 0 until n) {\n if(i%2 == 0){\n if(a(i) == n-1)\n a(i) = 0\n else\n a(i) += 1\n } else {\n if(a(i) == 0)\n a(i) = n-1\n else\n a(i) -= 1\n }\n }\n t += 1\n }\n if(!break) {\n println(\"No\")\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "object _556B extends CodeForcesApp {\n import CodeForcesApp._, scala.annotation.tailrec, scala.collection.mutable\n\n override type Input = List[Int]\n override type Output = Boolean\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n List.fill(nextInt)(nextInt)\n }\n\n override def solve(input: Input) = {\n val n = input.size\n val end = List.tabulate(n)(identity)\n val zipped = (end zip input).zipWithIndex\n def rotate(clockwise: Boolean) = zipped map {\n case ((a, b), i) if (i%2 == 0) == clockwise => (a - b + n)%n\n case ((a, b), _) => (b - a + n)%n\n }\n val (left, right) = (rotate(clockwise = true), rotate(clockwise = false))\n left.distinct.size == 1 || right.distinct.size == 1\n }\n\n override def format(result: Output) = if (result) \"Yes\" else \"No\"\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n import CodeForcesApp._\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n/********************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n}\n/**********************************[ lib ]************************************/\nobject CodeForcesApp {\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = collection.mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type ==>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A) = if (condition) Some(f) else None\n/*******************************[ constants ]*********************************/\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n val modulus = 1000000007\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject B_310 { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n val line2 = readLine\n val gears = new Array[Int](n)\n for(i <- 0 until n) {\n gears(i) = line2.int\n }\n \n val steps = if (gears(0) == 0) 0 else n - gears(0)\n var res = true\n for(i <- 0 until n) {\n if (i % 2 == 0) {\n val value = (gears(i) + steps) % n\n if (value != i) {\n res = false\n }\n } else {\n val value = (gears(i) + n - steps) % n\n if (value != i) {\n res = false\n }\n }\n }\n \n val strRes = if (res) \"Yes\" else \"No\"\n println(strRes)\n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n \n //---------------------------- service code ----------------------------------\n\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n \n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n\n\"\"\"\n\n}\n\n}\n"}, {"source_code": "object _556B extends CodeForcesApp[Boolean] {\n import java.util.Scanner\n import scala.annotation.tailrec, scala.collection.mutable\n import CodeForcesApp._\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val n = nextInt\n val gears = List.fill(n)(nextInt)\n val rotated = for {\n (a, i) <- gears.zipWithIndex\n r = if (i%2 == 0) 1 else -1\n } yield ((a - i)*r + n)%n\n rotated.distinct.size == 1\n }\n\n override def format(result: Boolean): String = if (result) \"Yes\" else \"No\"\n}\n\nabstract class CodeForcesApp[A] {\n import java.util.Scanner\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solve(scanner))\n def solve(scanner: Scanner): A\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n\nobject CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n val modulus = 1000000007\n def when[A](condition: Boolean)(f: => A) = if (condition) Some(f) else None\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n}\n"}, {"source_code": "import scala.annotation.tailrec, scala.collection.mutable\nobject _556B extends CodeForcesApp[Boolean] ({scanner => import scanner._, CodeForcesApp._\n val n = nextInt\n val gears = List.fill(n)(nextInt)\n val rotated = for {\n (a, i) <- gears.zipWithIndex\n r = if (i%2 == 0) 1 else -1\n } yield ((a - i)*r + n)%n\n debug(n, gears, rotated)\n rotated.distinct.size == 1\n}) {\n override def format(result: Boolean) = if (result) \"Yes\" else \"No\"\n}\n\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n\nobject CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n val modulus: Int = 1000000007\n def when[A](x: Boolean)(f: => A): Option[A] = if (x) Some(f) else None\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n}\n"}], "negative_code": [], "src_uid": "6c65ca365352380052b0c9d693e6d161"} {"source_code": "//package codeforces\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject TrainHardWinEasy {\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n\n def readLongPair(): (Long, Long) = {\n val st = new StringTokenizer(br.readLine())\n (st.nextToken.toLong, st.nextToken.toLong)\n }\n\n def readIntPair(): (Int, Int) = {\n val st = new StringTokenizer(br.readLine())\n (st.nextToken.toInt, st.nextToken.toInt)\n }\n\n def main(args: Array[String]): Unit = {\n val (n, m) = readIntPair()\n\n val scores = new Array[(Long, Long, Long, Int)](n)\n\n var k = 0\n while (k < n) {\n scores(k) = {\n val (x, y) = readLongPair()\n (x, y, y - x, k)\n }\n k += 1\n }\n\n val indexWhenSorted = new Array[Int](n)\n val scoresSorted = scores.sortBy(_._3)\n\n var i = 0\n while (i < n) {\n indexWhenSorted(scoresSorted(i)._4) = i\n i += 1\n }\n\n val prefixSum = new Array[(Long, Long)](n)\n prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)\n i = 1\n while (i < n) {\n prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2)\n i += 1\n }\n\n val enmitites = Array.fill[List[Int]](n)(List())\n\n k = 0\n while (k < m) {\n val (x, y) = readIntPair()\n enmitites(x - 1) = (y - 1) :: enmitites(x - 1)\n enmitites(y - 1) = (x - 1) :: enmitites(y - 1)\n\n k += 1\n }\n\n println(Stream.from(0).takeWhile(_ < n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(\" \")).toString())\n\n //println((0 until n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(\" \")).toString())\n\n def compute(i: Int): Long = {\n val sortedIdx = indexWhenSorted(i)\n\n var result = 0l\n\n if (sortedIdx > 0) {\n result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2\n }\n\n result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)\n\n enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)\n\n result\n }\n }\n\n // implicit class TuppleAdd[A: Numeric, B: Numeric](p: (A, B)) {\n //\n // import Numeric.Implicits._\n //\n // def +(t: (A, B)): (A, B) = (p._1 + t._1, p._2 + t._2)\n //\n // def -(t: (A, B)): (A, B) = (p._1 - t._1, p._2 - t._2)\n //\n // }\n\n}\n", "positive_code": [{"source_code": "//package codeforces\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject TrainHardWinEasy {\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n\n def readLongPair(): (Long, Long) = {\n val st = new StringTokenizer(br.readLine())\n (st.nextToken.toLong, st.nextToken.toLong)\n }\n\n def readIntPair(): (Int, Int) = {\n val st = new StringTokenizer(br.readLine())\n (st.nextToken.toInt, st.nextToken.toInt)\n }\n\n def main(args: Array[String]): Unit = {\n val (n, m) = readIntPair()\n\n val scores = new Array[(Long, Long, Long, Int)](n)\n\n var k = 0\n while (k < n) {\n scores(k) = {\n val (x, y) = readLongPair()\n (x, y, y - x, k)\n }\n k += 1\n }\n\n val indexWhenSorted = new Array[Int](n)\n val scoresSorted = scores.sortBy(_._3)\n\n var i = 0\n while (i < n) {\n indexWhenSorted(scoresSorted(i)._4) = i\n i += 1\n }\n\n val prefixSum = new Array[(Long, Long)](n)\n prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)\n i = 1\n while (i < n) {\n prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2)\n i += 1\n }\n\n val enmitites = Array.fill[List[Int]](n)(List())\n\n k = 0\n while (k < m) {\n val (x, y) = readIntPair()\n enmitites(x - 1) = (y - 1) :: enmitites(x - 1)\n enmitites(y - 1) = (x - 1) :: enmitites(y - 1)\n\n k += 1\n }\n\n println((0 until n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(\" \")).toString())\n\n def compute(i: Int): Long = {\n val sortedIdx = indexWhenSorted(i)\n\n var result = 0l\n\n if (sortedIdx > 0) {\n result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2\n }\n\n result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)\n\n enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)\n\n result\n }\n }\n\n // implicit class TuppleAdd[A: Numeric, B: Numeric](p: (A, B)) {\n //\n // import Numeric.Implicits._\n //\n // def +(t: (A, B)): (A, B) = (p._1 + t._1, p._2 + t._2)\n //\n // def -(t: (A, B)): (A, B) = (p._1 - t._1, p._2 - t._2)\n //\n // }\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M = ni()\n val (x, y) = na2(N)\n val Sx = sumL(x)\n val (from, to) = na2(M, -1)\n val sortedZ = Array.ofDim[Long](N)\n rep(N) { i =>\n sortedZ(i) = y(i) - x(i)\n }\n sort(sortedZ)\n val cumZ = Array.ofDim[Long](N + 1)\n rep(sortedZ.length) { i =>\n cumZ(i + 1) = cumZ(i) + sortedZ(i)\n }\n\n val hates = packUGraph(N, from, to)\n val zip = new ZippedCounter(sortedZ)\n rep(N) { i =>\n zip.add(sortedZ(i))\n }\n\n val ans = Array.ofDim[Long](N)\n rep(N) { i =>\n val z = y(i) - x(i)\n val nLt = zip.countLt(z)\n val nGe = zip.countGe(z)\n var hated = 0L\n hates(i) foreach { j =>\n hated += min(x(i) + y(j), x(j) + y(i))\n }\n val Sx1 = (N - 1).toLong * x(i)\n val Sx2 = Sx - x(i)\n val Sz1 = (nGe - 1).toLong * z\n val Sz2 = cumZ(nLt)\n val sum = Sx1 + Sx2 + Sz1 + Sz2 + - hated // Σ(x1 + x2 + min(z1, z2))\n ans(i) = sum\n }\n\n out.println(ans.mkString(\" \"))\n }\n\n def sort(as: Array[Long]): Array[Long] = {\n val n = as.length\n val sorted = new java.util.PriorityQueue[Long](n)\n rep(n)(i => sorted.add(as(i)))\n rep(n)(i => as(i) = sorted.poll())\n as\n }\n\n /**\n * @param n ノード数\n */\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n rep(m)(i => p(from(i)) += 1)\n rep(m)(i => p(to(i)) += 1)\n rep(n)(i => t(i) = new Array(p(i)))\n rep(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n def lowerBound(a: Array[Long], x: Long): Int = {\n def step(l: Int, h: Int): Int = {\n if (h - l == 1) h\n else {\n val mid = (l + h) / 2\n if (a(mid) >= x) step(l, mid)\n else step(mid, h)\n }\n }\n\n step(-1, a.length)\n }\n\n class BIT(n: Int, zero: Long)(f: (Long, Long) => Long) {\n def this(n: Int) = this(n, 0)(_ + _)\n\n private val N = {\n val a = Integer.highestOneBit(n)\n if (a == n) a else a << 1\n }\n private val bit = if (zero != 0) Array.fill[Long](N + 1)(zero) else Array.ofDim[Long](N + 1)\n\n /**\n * 0 index\n */\n def sum(i: Int): Long = {\n var x = i + 1\n var s: Long = 0\n while(x > 0) {\n s = f(s, bit(x))\n x -= x & -x\n }\n s\n }\n\n /**\n * 0 index\n */\n def add(i: Int, a: Long): Unit = {\n var x = i + 1\n while(x <= N) {\n bit(x) = f(bit(x), a)\n x += x & -x\n }\n }\n }\n\n /**\n * N + 1の範囲に分割する\n *\n * 例:\n * as = [3 5 6]\n * (, 3] => 0 (3, 5] => 1 (5, 6] => 2 (6, ) => 3\n *\n */\n class ZipperLB(as: Array[Long]) {\n def apply(x: Long): Int = {\n lowerBound(as, x)\n }\n }\n\n /**\n * まじめなBSTつくるの大変だからlesserThanをカウントできるだけのものを用意した\n * java.util.TreeSetじゃできない\n */\n class ZippedCounter(as: Array[Long]) {\n val n = as.length\n val zip = new ZipperLB(as)\n val bit = new BIT(n + 1) // zipされたレンジはn + 1個になる\n var cnt = 0\n\n /**\n * @param x 必ずレンジの上限を追加しないいけない\n */\n def add(x: Long): Unit = {\n val i = zip(x)\n assert(i < n && x == as(i))\n bit.add(i, 1)\n cnt += 1\n }\n\n def countLt(x: Long): Int = {\n // レンジの上限の値しか存在しないので、ある値より小さい = より小さいレンジ と置き換えることができる\n val i = zip(x)\n if (i > 0) bit.sum(i - 1).toInt\n else 0\n }\n\n def countLe(x: Long): Int = {\n countLt(x + 1)\n }\n\n def countGe(x: Long): Int = {\n cnt - countLt(x)\n }\n\n def countGt(x: Long): Int = {\n cnt - countLe(x)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "//package codeforces\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\n\nobject TrainHardWinEasy {\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n\n def readLongPair(): (Long, Long) = {\n val st = new StringTokenizer(br.readLine())\n (st.nextToken.toLong, st.nextToken.toLong)\n }\n\n def readIntPair(): (Int, Int) = {\n val st = new StringTokenizer(br.readLine())\n (st.nextToken.toInt, st.nextToken.toInt)\n }\n\n def main(args: Array[String]): Unit = {\n val (n, m) = readIntPair()\n\n val scores = new Array[(Long, Long, Long, Int)](n)\n\n (0 until n).foreach(i => scores(i) = {\n val (x, y) = readLongPair()\n (x, y, y - x, i)\n })\n\n val indexWhenSorted = new Array[Int](n)\n val scoresSorted = scores.sortBy(_._3)\n\n (0 until n).foreach(i => indexWhenSorted(scoresSorted(i)._4) = i)\n\n val prefixSum = new Array[(Long, Long)](n)\n prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)\n (1 until n).foreach(i => prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2))\n\n val enmitites = Array.fill[List[Int]](n)(List())\n\n (0 until m).foreach { _ =>\n val (x, y) = readIntPair()\n enmitites(x - 1) = (y - 1) :: enmitites(x - 1)\n enmitites(y - 1) = (x - 1) :: enmitites(y - 1)\n }\n\n println((0 until n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(\" \")).toString())\n\n def compute(i: Int): Long = {\n val sortedIdx = indexWhenSorted(i)\n\n var result = 0l\n\n if (sortedIdx > 0) {\n result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2\n }\n\n result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)\n\n enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)\n\n result\n }\n }\n\n}\n"}, {"source_code": "//package codeforces\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\n\nobject TrainHardWinEasy {\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n\n def readLongPair(): (Long, Long) = {\n val st = new StringTokenizer(br.readLine())\n (st.nextToken.toLong, st.nextToken.toLong)\n }\n\n def readIntPair(): (Int, Int) = {\n val st = new StringTokenizer(br.readLine())\n (st.nextToken.toInt, st.nextToken.toInt)\n }\n\n def main(args: Array[String]): Unit = {\n val (n, m) = readIntPair()\n val rangeN = 0 until n\n val rangeM = 0 until m\n\n val scores = new Array[(Long, Long, Long, Int)](n)\n\n rangeN.foreach(i => scores(i) = {\n val (x, y) = readLongPair()\n (x, y, y - x, i)\n })\n\n val indexWhenSorted = new Array[Int](n)\n val scoresSorted = scores.sortBy(_._3)\n\n rangeN.foreach(i => indexWhenSorted(scoresSorted(i)._4) = i)\n\n val prefixSum = new Array[(Long, Long)](n)\n prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)\n (1 until n).foreach(i => prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2))\n\n val enmitites = Array.fill[List[Int]](n)(List())\n\n rangeM.foreach { _ =>\n val (x, y) = readIntPair()\n enmitites(x - 1) = (y - 1) :: enmitites(x - 1)\n enmitites(y - 1) = (x - 1) :: enmitites(y - 1)\n }\n\n println(rangeN.foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(\" \")).toString())\n\n \n def compute(i: Int): Long = {\n val sortedIdx = indexWhenSorted(i)\n\n var result = 0l\n\n if (sortedIdx > 0) {\n result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2\n }\n\n result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)\n\n enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)\n\n result\n }\n }\n\n}\n"}, {"source_code": "//package codeforces\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject TrainHardWinEasy {\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n\n def readLongPair(): (Long, Long) = {\n val st = new StringTokenizer(br.readLine())\n (st.nextToken.toLong, st.nextToken.toLong)\n }\n\n def readIntPair(): (Int, Int) = {\n val st = new StringTokenizer(br.readLine())\n (st.nextToken.toInt, st.nextToken.toInt)\n }\n\n //def input: Array[Long] = StdIn.readLine.split(\" \").map(_.toLong)\n\n def main(args: Array[String]): Unit = {\n val (n, m) = readIntPair() //StdIn.readLine.split(\" \").map(_.toInt)\n\n val scores = new Array[(Long, Long, Long, Int)](n)\n\n var k = 0\n while (k < n) {\n scores(k) = {\n val (x, y) = readLongPair()\n (x, y, y - x, k)\n }\n k += 1\n }\n\n val indexWhenSorted = new Array[Int](n)\n val scoresSorted = scores.sortBy(_._3)\n\n var i = 0\n while (i < n) {\n indexWhenSorted(scoresSorted(i)._4) = i\n i += 1\n }\n\n val prefixSum = new Array[(Long, Long)](n)\n prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)\n i = 1\n while (i < n) {\n prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2)\n i += 1\n }\n\n val enmitites = Array.fill[List[Int]](n)(List())\n\n k = 0\n while (k < m) {\n val (x, y) = readIntPair()\n enmitites(x - 1) = (y - 1) :: enmitites(x - 1)\n enmitites(y - 1) = (x - 1) :: enmitites(y - 1)\n\n k += 1\n }\n\n val sb = new StringBuilder\n i = 0\n while (i < n) {\n val sortedIdx = indexWhenSorted(i)\n\n var result = 0l\n\n if (sortedIdx > 0) {\n result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2\n }\n\n result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)\n\n enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)\n\n sb.append(result + \" \")\n i += 1\n }\n println(sb.toString())\n }\n\n // implicit class TuppleAdd[A: Numeric, B: Numeric](p: (A, B)) {\n //\n // import Numeric.Implicits._\n //\n // def +(t: (A, B)): (A, B) = (p._1 + t._1, p._2 + t._2)\n //\n // def -(t: (A, B)): (A, B) = (p._1 - t._1, p._2 - t._2)\n //\n // }\n\n}\n"}, {"source_code": "//package codeforces\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\n\nobject TrainHardWinEasy {\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n\n def readLongPair(): (Long, Long) = {\n val st = new StringTokenizer(br.readLine())\n (st.nextToken.toLong, st.nextToken.toLong)\n }\n\n def readIntPair(): (Int, Int) = {\n val st = new StringTokenizer(br.readLine())\n (st.nextToken.toInt, st.nextToken.toInt)\n }\n\n def main(args: Array[String]): Unit = {\n val (n, m) = readIntPair()\n val rangeN = 0 until n\n val rangeM = 0 until m\n\n val scores = new Array[(Long, Long, Long, Int)](n)\n\n rangeN.foreach(i => scores(i) = {\n val (x, y) = readLongPair()\n (x, y, y - x, i)\n })\n\n val indexWhenSorted = new Array[Int](n)\n val scoresSorted = scores.sortBy(_._3)\n\n rangeN.foreach(i => indexWhenSorted(scoresSorted(i)._4) = i)\n\n val prefixSum = new Array[(Long, Long)](n)\n prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)\n (1 until n).foreach(i => prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2))\n\n val enmitites = Array.fill[List[Int]](n)(List())\n\n rangeM.foreach { _ =>\n val (x, y) = readIntPair()\n enmitites(x - 1) = (y - 1) :: enmitites(x - 1)\n enmitites(y - 1) = (x - 1) :: enmitites(y - 1)\n }\n\n println(rangeN.foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(\" \")).toString())\n\n def compute(i: Int): Long = {\n val sortedIdx = indexWhenSorted(i)\n\n var result = 0l\n\n if (sortedIdx > 0) {\n result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2\n }\n\n result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)\n\n enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)\n\n result\n }\n }\n\n}\n"}, {"source_code": "//package codeforces\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject TrainHardWinEasy {\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n\n def readLongPair(): (Long, Long) = {\n val st = new StringTokenizer(br.readLine())\n (st.nextToken.toLong, st.nextToken.toLong)\n }\n\n def readIntPair(): (Int, Int) = {\n val st = new StringTokenizer(br.readLine())\n (st.nextToken.toInt, st.nextToken.toInt)\n }\n\n def main(args: Array[String]): Unit = {\n val (n, m) = readIntPair()\n\n val scores = new Array[(Long, Long, Long, Int)](n)\n\n var k = 0\n while (k < n) {\n scores(k) = {\n val (x, y) = readLongPair()\n (x, y, y - x, k)\n }\n k += 1\n }\n\n val indexWhenSorted = new Array[Int](n)\n val scoresSorted = scores.sortBy(_._3)\n\n var i = 0\n while (i < n) {\n indexWhenSorted(scoresSorted(i)._4) = i\n i += 1\n }\n\n val prefixSum = new Array[(Long, Long)](n)\n prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)\n i = 1\n while (i < n) {\n prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2)\n i += 1\n }\n\n val enmitites = Array.fill[List[Int]](n)(List())\n\n k = 0\n while (k < m) {\n val (x, y) = readIntPair()\n enmitites(x - 1) = (y - 1) :: enmitites(x - 1)\n enmitites(y - 1) = (x - 1) :: enmitites(y - 1)\n\n k += 1\n }\n\n (0 until n).view.force\n\n println((0 until n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(\" \")).toString())\n\n //println((0 until n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(\" \")).toString())\n\n def compute(i: Int): Long = {\n val sortedIdx = indexWhenSorted(i)\n\n var result = 0l\n\n if (sortedIdx > 0) {\n result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2\n }\n\n result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)\n\n enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)\n\n result\n }\n }\n\n // implicit class TuppleAdd[A: Numeric, B: Numeric](p: (A, B)) {\n //\n // import Numeric.Implicits._\n //\n // def +(t: (A, B)): (A, B) = (p._1 + t._1, p._2 + t._2)\n //\n // def -(t: (A, B)): (A, B) = (p._1 - t._1, p._2 - t._2)\n //\n // }\n\n}\n"}], "negative_code": [], "src_uid": "d0cb479bbe2fca382a439148af77e082"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val set = mutable.Map[Long, Int]().withDefaultValue(0)\n REP(N) { i =>\n set(A(i)) = set(A(i)) + 1\n }\n\n val MAX = 32\n// val MAX = 4\n\n val ans = map(N)(identity).count { i =>\n val ok = map(MAX)(identity).exists { k =>\n val b = (2L << k) - A(i)\n if (b == A(i))\n set(b) > 1\n else\n b > 0 && set.contains(b)\n }\n// System.err.println(s\"${A(i)} $ok\")\n !ok\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "import scala.collection.mutable._\n\nobject Solution {\n\n def solve(ls: List[Int]): Int = {\n var f = new HashMap[Int, Int]()\n ls.foreach(x => {\n f.get(x) match {\n case Some(y) => f += (x -> (y+1))\n case None => f += (x -> 1)\n }\n })\n \n var cnt = 0\n \n val p2 = (0 to 31).toList.map(x => 1 << x)\n ls.foreach(x => {\n val hasComplement = p2.foldLeft(false) { (acc, b) => {\n val v = f.get(b-x) match {\n case Some(y) => {\n if (b-x == x) {\n if (y > 1) true\n else false\n } else true\n }\n case None => false\n }\n acc || v\n }\n\n }\n if (!hasComplement) cnt += 1\n })\n\n cnt\n }\n\n def main(args: Array[String]) {\n val t = io.StdIn.readLine\n val ls = io.StdIn.readLine.split(\" \").map(_.toInt).toList\n println(solve(ls))\n }\n}\n\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Codeforces1005C {\n\n def getMinimumRemoveForBeingGood(elements: Array[Int]): Int = {\n val powers = (0 to 33).map(power => 1L << power)\n\n val elementMatchMap = new mutable.HashMap[Long, Data]()\n\n elements.foreach(element => {\n if (elementMatchMap.contains(element)) {\n elementMatchMap(element).frequency += 1\n } else {\n elementMatchMap.put(element, new Data(1, false))\n }\n })\n\n for (element <- elementMatchMap.keySet) {\n powers\n .map(p => p - element)\n .filter(e => elementMatchMap.contains(e))\n .filter(e => e != element || elementMatchMap(e).frequency != 1)\n .foreach(matchedElement => {\n elementMatchMap(element).hasMatched = true\n elementMatchMap(matchedElement).hasMatched = true\n })\n }\n\n var misMatchCount = 0\n for ((_, data) <- elementMatchMap) {\n if (!data.hasMatched)\n misMatchCount += data.frequency\n }\n misMatchCount\n }\n\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n val elements = StdIn.readLine.split(\" \").map(_.trim.toInt)\n val result = getMinimumRemoveForBeingGood(elements)\n println(result)\n }\n\n class Data(var frequency: Int, var hasMatched: Boolean)\n\n}\n"}], "negative_code": [], "src_uid": "ed308777f7122ca6279b522acd3e58f9"} {"source_code": "object Main {\n import java.io.PrintStream\n\n def main(args: Array[String]): Unit = {\n val s = new Main()\n val ps = new PrintStream(Console.out)\n Console.withOut(ps) {\n s.solve()\n }\n ps.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n import scala.Console\n\n val MOD = 1000000007\n\n def solve(): Unit = {\n val N, M = ni()\n val V = Array.ofDim[Int](N + 1)\n rep(N) { i =>\n V(i) = ni()\n }\n V(N) = 1e9.toInt\n radixSort(V)\n\n val H_buff = ArrayBuffer[Int]()\n rep(M) { _ =>\n val x1, x2, _ = ni()\n if (x1 == 1) {\n H_buff += upperBound(V, x2)\n }\n }\n\n val H = radixSort(H_buff.toArray)\n var ans = 1e9.toInt\n var h = 0\n rep(N + 1) { i =>\n while(h < H.length && H(h) <= i){ h += 1}\n ans = min(ans, i + H.length - h)\n }\n\n println(ans)\n }\n\n // 要はcountLe\n def upperBound(a: Array[Int], x: Int): Int = {\n def step(l: Int, h: Int): Int = {\n if (h - l == 1) h\n else {\n val mid = (l + h) / 2\n if (a(mid) > x) step(l, mid)\n else step(mid, h)\n }\n }\n\n step(-1, a.length)\n }\n\n /**\n * 正の値のみのときだけ\n */\n def radixSort(f: Array[Int]): Array[Int] = radixSort(f, f.length)\n def radixSort(as: Array[Int], n: Int): Array[Int] = {\n val n = as.length\n val xs = Array(as, new Array[Int](n))\n val b = Array.ofDim[Int](65537)\n\n def step(k: Int, x: Int): Unit = {\n rep(n){ i => b(1 + (xs(x)(i) >>> k & 0xffff)) += 1 }\n rep(65536, 1){ i => b(i) += b(i - 1) }\n rep(n){ i =>\n val j = xs(x)(i) >>> k & 0xffff\n xs(x ^ 1)(b(j)) = xs(x)(i)\n b(j) += 1\n }\n }\n\n step(0, 0)\n java.util.Arrays.fill(b, 0)\n step(16, 1)\n\n as\n }\n\n\n class InputReader(reader: BufferedReader) {\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(Console.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val MIN = 1\n val MAX = 1e9.toInt\n\n val N, M = ni()\n val V = na(N)\n radixSort(V)\n\n case class Line(from: Int, to: Int)\n val H = mutable.Map[Int, ArrayBuffer[Line]]()\n rep(M) { _ =>\n val l, r, y = ni()\n if (!H.contains(y)) {\n H(y) = ArrayBuffer()\n }\n H(y) += Line(l, r)\n }\n\n def merge(lines: ArrayBuffer[Line]): Line = {\n if (lines.length == 1) lines.head\n else {\n val sorted = lines.sortBy(_.to)\n var to = sorted.head.to\n rep(sorted.length - 1, 1) { i =>\n val l = sorted(i)\n if (to + 1 < l.from) return Line(sorted.head.from, to)\n to = l.to\n }\n Line(sorted.head.from, to)\n }\n }\n\n def calcV(lines: ArrayBuffer[Line]): Int = {\n val aLine = merge(lines)\n if (aLine.from > MIN) 0 // 一番左が空いている\n else if (aLine.to == MAX) Integer.MAX_VALUE // 全部埋まってる\n else {\n lowerBound(V, aLine.to + 1) \n }\n }\n\n val L = Array.ofDim[Int](H.size) // 可変だと面倒なので0もいれることにする\n var li = 0\n H.values.foreach { lines =>\n L(li) = calcV(lines)\n li += 1\n }\n\n radixSort(L)\n\n var ans = Integer.MAX_VALUE\n rep(N + 1) { i =>\n val cutH = L.length - lowerBound(L, i + 1)\n val cutV = i\n ans = min(ans, cutH + cutV)\n }\n\n out.println(ans)\n }\n\n // あえてコピペ\n // 要はcountLt\n def lowerBound(a: Array[Int], x: Int): Int = {\n def step(l: Int, h: Int): Int = {\n if (h - l == 1) h\n else {\n val mid = (l + h) / 2\n if (a(mid) >= x) step(l, mid)\n else step(mid, h)\n }\n }\n\n step(-1, a.length)\n }\n\n\n /**\n * 正の値のみのときだけ\n */\n def radixSort(f: Array[Int]): Array[Int] = radixSort(f, f.length)\n def radixSort(as: Array[Int], n: Int): Array[Int] = {\n val n = as.length\n val xs = Array(as, new Array[Int](n))\n val b = Array.ofDim[Int](65537)\n\n def step(k: Int, x: Int): Unit = {\n rep(n){ i => b(1 + (xs(x)(i) >>> k & 0xffff)) += 1 }\n rep(65536, 1){ i => b(i) += b(i - 1) }\n rep(n){ i =>\n val j = xs(x)(i) >>> k & 0xffff\n xs(x ^ 1)(b(j)) = xs(x)(i)\n b(j) += 1\n }\n }\n\n step(0, 0)\n java.util.Arrays.fill(b, 0)\n step(16, 1)\n\n as\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import java.util\n\nimport scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n case class Hor(x: Int, y: Int)\n\n val Array(n, m) = readInts(2)\n val vs = Array.fill(n){ readLine.toInt }.sorted :+ 1000000000\n\n val hsBuilder = new mutable.ArrayBuilder.ofRef[Hor]\n for (_ <- 0 until m) {\n val Array(x1, x2, y) = readInts(3)\n if (x1 == 1) hsBuilder += Hor(x2, y)\n }\n val hs = hsBuilder.result.sortBy(- _.x)\n\n val longer = new util.TreeMap[Integer, Integer]\n var count = 0\n for (h <- hs) {\n count += 1\n longer.put(h.x, count)\n }\n\n val max = hs.length\n\n var res = Int.MaxValue\n for (i <- vs.indices) {\n val j = longer.ceilingKey(vs(i))\n val total = if (j == null) i else i + longer.get(j)\n if (total < res) res = total\n }\n\n println(res)\n}\n"}, {"source_code": "import java.io._\nimport java.util\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n\n case class Point(x: Int, y: Int)\n\n @inline def dist(x1: Int, x2: Int, y1: Int, y2: Int): Int = math.abs(x1 - x2) * 2 + math.abs(y1 - y2) * 2\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val m = in.nextInt\n val vert = Array.fill(n)(in.nextInt)\n val h = ArrayBuffer[Int]()\n var const = 0\n (1 to m).foreach { _ =>\n val x1, x2 = in.nextInt\n in.nextInt\n if (x1 == 1 && x2 == 1000000000)\n const += 1\n else if (x1 == 1)\n h.append(x2)\n }\n\n val hor = h.toArray\n\n util.Arrays.sort(vert)\n util.Arrays.sort(hor)\n\n var ans = hor.length\n var v = 0\n hor.indices.foreach { x =>\n while (v < n && vert(v) <= hor(x))\n v += 1\n ans = math.min(ans, hor.length - x - 1 + v)\n }\n\n println(ans + const)\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toDouble\n }\n\n def nextLong: Long = {\n next.toLong\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}], "negative_code": [{"source_code": "import java.io._\nimport java.util\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n\n case class Point(x: Int, y: Int)\n\n @inline def dist(x1: Int, x2: Int, y1: Int, y2: Int): Int = math.abs(x1 - x2) * 2 + math.abs(y1 - y2) * 2\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val m = in.nextInt\n val vert = Array.fill(n)(in.nextInt)\n val hor = ArrayBuffer[Int]()\n var const = 0\n (1 to m).foreach { _ =>\n val x1, x2 = in.nextInt\n in.nextInt\n if (x1 == 1 && x2 == 1000000000)\n const += 1\n else if (x1 == 1)\n hor.append(x2)\n }\n var ans = n + hor.size\n var v = 0\n hor.indices.foreach { x =>\n while (v < n && vert(v) <= hor(x))\n v += 1\n ans = math.min(ans, hor.size - x - 1 + v)\n }\n\n println(ans + const)\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toDouble\n }\n\n def nextLong: Long = {\n next.toLong\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}, {"source_code": "import java.io._\nimport java.util\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n\n case class Point(x: Int, y: Int)\n\n @inline def dist(x1: Int, x2: Int, y1: Int, y2: Int): Int = math.abs(x1 - x2) * 2 + math.abs(y1 - y2) * 2\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val m = in.nextInt\n val vert = Array.fill(n)(in.nextInt)\n val hor = ArrayBuffer[Int]()\n var const = 0\n (1 to m).foreach { _ =>\n val x1, x2 = in.nextInt\n in.nextInt\n if (x1 == 1 && x2 == 1000000000)\n const += 1\n else if (x1 == 1)\n hor.append(x2)\n }\n var ans = hor.size\n var v = 0\n hor.indices.foreach { x =>\n while (v < n && vert(v) <= hor(x))\n v += 1\n ans = math.min(ans, hor.size - x - 1 + v)\n }\n\n println(ans + const)\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toDouble\n }\n\n def nextLong: Long = {\n next.toLong\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}], "src_uid": "00eb4442eb86ccc7352b63dc23354abf"} {"source_code": "/**\n * Created by ivan-pifagor on 4/23/17.\n */\nimport scala.io.StdIn.readLine\nobject Main {\n def main(args: Array[String]): Unit = {\n val K = readLine().split(\" \").map(_.toLong)\n val A = readLine().split(\" \").map(_.toLong)\n val m = A.min\n if (A.forall(a => ( a - m) % K(1) == 0 )){\n println(A.map(a => (a - m) / K(1)).sum)\n }else {\n println(-1)\n }\n }\n\n}\n", "positive_code": [{"source_code": "import io.StdIn.readLine\n\nobject A extends App {\n val Array(n, k) = readLine.split(' ').map(_.toInt)\n val xs = readLine.split(' ').map(_.toLong)\n val m = xs.min\n if (xs.exists(x => (x - m) % k != 0)) println(\"-1\")\n else{\n val u = xs.view.map(x => (x - m) / k).sum\n println(u)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val arr = io.StdIn.readLine().split(\" \").map(_.toInt)\n val n = arr(0)\n val k = arr(1)\n var secondCount = 0L\n var shares = io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val rest = shares.head % k\n if (shares.exists(_ % k != rest)) println(-1) else {\n val minVal = shares.min\n shares.foreach(i => secondCount += (i - minVal) / k)\n println(secondCount)\n }\n }\n}"}, {"source_code": "object _793A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n val n, k = read[Int]\n val prices = read[Seq, Long](n)\n val smallest = prices.min\n val target = prices.map(_ - smallest)\n\n val ans = when(target.forall(_%k == 0)) {\n target.sumWith(_/k)\n }\n\n write(ans.getOrElse(-1))\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object A extends App {\n\n val arr = io.StdIn.readLine().split(\" \").map(_.toLong);\n val count = arr(1)\n val arr2 = io.StdIn.readLine().split(\" \").map(_.toLong);\n val min = arr2.min\n\n val counts = arr2.map {\n case x if (x - min) % count == 0 => (x - min) / count\n case x if (x - min) % count != 0 => -1\n }\n val answer = counts.find(x => x == -1).getOrElse(counts.sum)\n print(answer)\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val arr = io.StdIn.readLine().split(\" \").map(_.toInt)\n val n = arr(0)\n val k = arr(1)\n var secondCount = 0\n var shares = io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val rest = shares.head % k\n if (shares.exists(_ % k != rest)) println(-1) else {\n val minVal = shares.min\n shares.foreach(i => secondCount += (i - minVal) / k)\n println(secondCount)\n }\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val K = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val A = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val m = A.min\n if (A.forall(a => ( a - m) % K(1) == 0 )){\n println(A.map(a => (a - m) / K(1)).sum)\n }else {\n println(-1)\n }\n }\n\n}\n"}], "src_uid": "9e71b4117a24b906dbc16e6a6d110f50"} {"source_code": "import scala.io.StdIn._\nimport scala.collection.mutable.ArraySeq\n\nobject Codeforces extends App {\n val beauty = readLine()\n var max: Int = 0\n var aCount: Int = 0\n var bCount: Int = 0\n val a = beauty.map(c => {\n if (c == 'a')\n aCount += 1\n aCount\n }).toArray\n val b = beauty.map(c => {\n if (c == 'b')\n bCount += 1\n bCount\n }).toArray\n for (i <- 0 to beauty.length) {\n for (j <- i to beauty.length) {\n var current: Int = 0\n if (i > 0) // left A\n current += a(i - 1)\n if (j > 0) { // center B\n current += b(j - 1)\n if (i > 0)\n current -= b(i - 1)\n }\n if (j > 0)\n current += a(a.length - 1) - a(j - 1)\n max = math.max(max, current)\n }\n }\n println(max)\n}\n", "positive_code": [{"source_code": "object _877B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val s = io.read[String]\n val n = s.length\n\n def count(from: Int, until: Int, prefixSum: IndexedSeq[Int]) = {\n assert(from <= until)\n prefixSum(until) - prefixSum(from)\n }\n\n val as = s.scanLeft(0) {\n case (i, 'a') => i + 1\n case (i, _) => i\n }\n\n val bs = s.scanLeft(0) {\n case (i, 'b') => i + 1\n case (i, _) => i\n }\n\n def length(l: Int, r: Int) = count(0, l, as) + count(l, r, bs) + count(r, n, as)\n\n var ans = 0\n for {\n i <- 0 to n\n j <- i to n\n } ans = ans max length(i, j)\n\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "c768f3e52e562ae1fd47502a60dbadfe"} {"source_code": "import scala.io.Source\nimport scala.collection.mutable.HashMap\nimport scala.collection.mutable.HashSet\n\nobject CF338B {\n\n def main(args: Array[String]) {\n val r = Source.stdin.bufferedReader()\n var ss = r.readLine().split(\" \")\n val n = ss(0).toInt\n val m = ss(1).toInt\n val spines = new Array[Long](n)\n val len = new Array[Long](n)\n val edges = new Array[HashSet[Int]](n)\n for (i <- 0 until n) {\n edges(i) = new HashSet[Int]\n }\n for (i <- 0 until m) {\n ss = r.readLine().split(\" \")\n val u = ss(0).toInt - 1\n val v = ss(1).toInt - 1\n spines(u) += 1\n spines(v) += 1\n val min = u.min(v)\n val max = u.max(v)\n edges(min).add(max)\n }\n for (i <- 0 until n) {\n len(i) = len(i).max(1)\n for (end <- edges(i)) {\n len(end) = len(end).max(len(i) + 1)\n }\n }\n var result = 0L\n for (i <- 0 until n) {\n result = result.max(len(i) * spines(i))\n }\n println(result)\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) {\n val Array(n, m) = StdIn.readLine().split(\" \").map(_.toInt)\n val g = Array.fill(n)(ArrayBuffer[Int]())\n val len = Array.fill(n)(1L)\n val ct = Array.fill(n)(0L)\n for (i <- 0 until m) {\n val Array(u, v) = StdIn.readLine().split(\" \").map(_.toInt - 1)\n g(u).append(v)\n g(v).append(u)\n ct(u) += 1\n ct(v) += 1\n }\n for (v <- 0 until n) {\n for (u <- g(v) if u > v) {\n len(u) = len(u).max(len(v) + 1)\n }\n }\n var ans = 0L\n for (v <- 0 until n) {\n ans = ans.max(len(v) * ct(v))\n }\n println(ans)\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\n/**\n * Created by hsleep on 2016. 1. 8..\n */\nobject BSolution extends App {\n val Array(numOfPoints, numOfSegments) = StdIn.readLine().split(' ').map(_.toInt)\n\n val listOfSegments = (0 until numOfSegments).map(_ => StdIn.readLine().split(' ').map(_.toInt)).flatMap { case Array(i, j) =>\n Seq((j, i), (i, j))\n }\n val mapOfSegments = listOfSegments.groupBy(_._1)\n\n val mapOfTail = mutable.Map[Int, Int]()\n\n def calcBeauty(point: Int): Long = {\n val listOfSpine = mapOfSegments.getOrElse(point, Nil)\n val tail = listOfSpine.filter { case (s, e) => e < s }.map { p =>\n mapOfTail(p._2)\n } match {\n case l if l.isEmpty => 1\n case l => l.max + 1\n }\n\n mapOfTail(point) = tail\n tail.toLong * listOfSpine.length\n }\n\n val output = {\n for {\n i <- 1 to numOfPoints\n } yield {\n calcBeauty(i)\n }\n }.max\n\n println(output)\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val length = Array.ofDim[Int](n)\n val weight = Array.ofDim[Int](n)\n val edgesUp = Array.fill[List[Int]](n){ Nil }\n val edgesDown = Array.fill[List[Int]](n){ Nil }\n\n in.take(m).map(_.split(' ').map(_.toInt - 1)).foreach { i =>\n val min = Math.min(i.head, i.last)\n val max = Math.max(i.head, i.last)\n weight(min) += 1\n weight(max) += 1\n edgesDown(max) ::= min\n edgesUp(min) ::= max\n }\n\n def calcLength(start: Int): Int = {\n val children = edgesDown(start)\n if (children.isEmpty) {\n 1\n } else {\n val childrenLength = length(children.maxBy(length))\n childrenLength + 1\n }\n }\n\n (0 until n).foreach(i => length(i) = calcLength(i))\n\n println(length.zip(weight).map(i => i._1.toLong * i._2).max)\n\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val degs = Array.fill(n) { 0 }\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 to m) {\n val Array(u, v) = readInts(2).map(_ - 1)\n adjBuilders(u max v) += u min v\n degs(u) += 1\n degs(v) += 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val maxDepths = Array.fill(n) { 1 }\n\n for (u <- 0 until n) {\n for (v <- adjs(u)) {\n maxDepths(u) = maxDepths(u) max (maxDepths(v) + 1) \n }\n }\n \n val res = (0 until n).map(i => degs(i).toLong * maxDepths(i)).max\n\n println(res)\n}\n"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val degs = Array.fill(n) { 0 }\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 to m) {\n val Array(u, v) = readInts(2).map(_ - 1)\n adjBuilders(u max v) += u min v\n degs(u) += 1\n degs(v) += 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val maxDepths = Array.fill(n) { 1 }\n\n val sortedBuilder = new mutable.ArrayBuilder.ofInt\n\n val color = Array.fill(n)(0)\n\n def dfs(u: Int): Unit = {\n color(u) = 1\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (color(v) == 0) dfs(v)\n i += 1\n }\n color(u) = 2\n sortedBuilder += u\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs(i)\n\n val sorted = sortedBuilder.result\n \n for (u <- sorted) {\n for (v <- adjs(u)) {\n maxDepths(u) = maxDepths(u) max (maxDepths(v) + 1) \n }\n }\n \n val res = (0 until n).map(i => degs(i).toLong * maxDepths(i)).max\n\n println(res)\n}\n"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val degs = Array.fill(n) { 0 }\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 to m) {\n val Array(u, v) = readInts(2).map(_ - 1)\n adjBuilders(u max v) += u min v\n degs(u) += 1\n degs(v) += 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val maxDepths = Array.fill(n) { 1 }\n\n val sorted = mutable.ArrayBuffer.empty[Int]\n\n val color = Array.fill(n)(0)\n\n def dfs(u: Int): Unit = {\n color(u) = 1\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (color(v) == 0) dfs(v)\n i += 1\n }\n color(u) = 2\n sorted += u\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs(i)\n\n for (u <- sorted) {\n for (v <- adjs(u)) {\n maxDepths(u) = maxDepths(u) max (maxDepths(v) + 1) \n }\n }\n \n val res = (0 until n).map(i => degs(i).toLong * maxDepths(i)).max\n\n println(res)\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) {\n val Array(n, m) = StdIn.readLine().split(\" \").map(_.toInt)\n val g = Array.fill(n)(ArrayBuffer[Int]())\n val len = Array.fill(n)(1)\n val ct = Array.fill(n)(0)\n for (i <- 0 until m) {\n val Array(u, v) = StdIn.readLine().split(\" \").map(_.toInt - 1)\n g(u).append(v)\n g(v).append(u)\n ct(u) += 1\n ct(v) += 1\n }\n for (v <- 0 until n) {\n for (u <- g(v) if u > v) {\n len(u) = len(u).max(len(v) + 1)\n }\n }\n var ans = 0\n for (v <- 0 until n) {\n ans = ans.max(len(v) * ct(v))\n }\n println(ans)\n }\n}\n"}, {"source_code": "import scala.io.Source\nimport scala.collection.mutable.HashMap\nimport scala.collection.mutable.HashSet\n\nobject CF338B {\n\n def main(args: Array[String]) {\n val r = Source.stdin.bufferedReader()\n var ss = r.readLine().split(\" \")\n val n = ss(0).toInt\n val m = ss(1).toInt\n val spines = new Array[Long](n)\n val len = new Array[Long](n)\n val edges = new Array[HashSet[Int]](n)\n for (i <- 0 until n) {\n edges(i) = new HashSet[Int]\n }\n for (i <- 0 until m) {\n ss = r.readLine().split(\" \")\n val u = ss(0).toInt - 1\n val v = ss(1).toInt - 1\n spines(u) += 1\n spines(v) += 1\n val min = u.min(v)\n val max = u.max(v)\n edges(min).add(max)\n }\n for (i <- 0 until n) {\n var k = len(i).max(1)\n for (end <- edges(i)) {\n len(end) = len(end).max(k + 1)\n }\n }\n var result = 0L\n for (i <- 0 until n) {\n result = result.max(len(i) * spines(i))\n }\n println(result)\n }\n}\n"}, {"source_code": "import scala.io.Source\nimport scala.collection.mutable.HashMap\nimport scala.collection.mutable.TreeSet\n\nobject CF338B {\n\n def main(args: Array[String]) {\n val r = Source.stdin.bufferedReader()\n var ss = r.readLine().split(\" \")\n val n = ss(0).toInt\n val m = ss(1).toInt\n val spines = new Array[Int](n)\n val len = new Array[Int](n)\n val edges = new Array[TreeSet[Int]](n)\n for (i <- 0 until n) {\n edges(i) = new TreeSet[Int]\n }\n for (i <- 0 until m) {\n ss = r.readLine().split(\" \")\n val u = ss(0).toInt - 1\n val v = ss(1).toInt - 1\n spines(u) += 1\n spines(v) += 1\n val min = u.min(v)\n val max = u.max(v)\n edges(min).add(max)\n }\n for (i <- 0 until n) {\n var k = len(i).max(1)\n for (end <- edges(i)) {\n len(end) = len(end).max(k + 1)\n }\n }\n var result = 0L\n for (i <- 0 until n) {\n result = result.max(1L * len(i) * spines(i))\n }\n println(result)\n }\n}\n"}, {"source_code": "import scala.io.Source\nimport scala.collection.mutable.HashMap\nimport scala.collection.mutable.HashSet\n\nobject CF338B {\n\n def main(args: Array[String]) {\n val r = Source.stdin.bufferedReader()\n var ss = r.readLine().split(\" \")\n val n = ss(0).toInt\n val m = ss(1).toInt\n val spines = new Array[Int](n)\n val len = new Array[Int](n)\n val edges = new Array[HashSet[Int]](n)\n for (i <- 0 until n) {\n edges(i) = new HashSet[Int]\n }\n for (i <- 0 until m) {\n ss = r.readLine().split(\" \")\n val u = ss(0).toInt - 1\n val v = ss(1).toInt - 1\n spines(u) += 1\n spines(v) += 1\n val min = u.min(v)\n val max = u.max(v)\n edges(min).add(max)\n }\n for (i <- 0 until n) {\n var k = len(i).max(1)\n for (end <- edges(i)) {\n len(end) = len(end).max(k + 1)\n }\n }\n var result = 0L\n for (i <- 0 until n) {\n result = result.max(1L * len(i) * spines(i))\n }\n println(result)\n }\n}\n"}, {"source_code": "import scala.collection.immutable.TreeMap\nimport scala.collection.mutable\nimport scala.io.StdIn\n\n/**\n * Created by hsleep on 2016. 1. 8..\n */\nobject BSolution extends App {\n val Array(numOfPoints, numOfSegments) = StdIn.readLine().split(' ').map(_.toInt)\n\n val listOfSegments = (0 until numOfSegments).map(_ => StdIn.readLine().split(' ').map(_.toInt)).flatMap { case Array(i, j) =>\n Seq((j, i), (i, j))\n }\n val mapOfSegments = TreeMap(listOfSegments.groupBy(_._1).toSeq: _*)\n\n val mapOfTail = mutable.Map[Int, (Int, Int)]()\n\n def findTail(point: Int): (Int, Int) = {\n mapOfTail.getOrElseUpdate(point,\n mapOfSegments.getOrElse(point, Nil).filter { case (s, e) => e > s }.map { p =>\n findTail(p._2)\n } match {\n case Nil => (1, point)\n case l =>\n val (len, endPoint) = l.maxBy(_._1)\n (len + 1, endPoint)\n }\n )\n }\n\n val output = {\n for {\n i <- 1 to numOfPoints\n } yield {\n val (tail, endPoint) = findTail(i)\n val spine = mapOfSegments.get(endPoint).map(_.length).get\n tail * spine\n }\n }.max\n\n println(output)\n}"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\n/**\n * Created by hsleep on 2016. 1. 8..\n */\nobject BSolution extends App {\n val Array(numOfPoints, numOfSegments) = StdIn.readLine().split(' ').map(_.toInt)\n\n val listOfSegments = (0 until numOfSegments).map(_ => StdIn.readLine().split(' ').map(_.toInt)).flatMap { case Array(i, j) =>\n Seq((j, i), (i, j))\n }\n val mapOfSegments = listOfSegments.groupBy(_._1)\n\n val mapOfTail = mutable.Map[Int, Int]()\n\n def calcBeauty(point: Int): Long = {\n val listOfSpine = mapOfSegments.getOrElse(point, Nil)\n val tail = listOfSpine.filter { case (s, e) => e < s }.map { p =>\n mapOfTail(p._2)\n } match {\n case l if l.isEmpty => 1\n case l => l.max + 1\n }\n\n mapOfTail(point) = tail\n tail * listOfSpine.length\n }\n\n val output = {\n for {\n i <- 1 to numOfPoints\n } yield {\n calcBeauty(i)\n }\n }.max\n\n println(output)\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val visited = Array.ofDim[Boolean](n)\n val weight = Array.ofDim[Int](n)\n val edges = Array.fill[List[Int]](n){ Nil }\n\n in.take(m).map(_.split(' ').map(_.toInt - 1)).foreach { i =>\n val min = Math.min(i.head, i.last)\n val max = Math.max(i.head, i.last)\n weight(min) += 1\n weight(max) += 1\n edges(min) ::= max\n }\n\n def result(start: Int, max: Int, length: Int): Int = {\n if (visited(start)) max\n else {\n visited(start) = true\n val nLength = length + 1\n val nMax = Math.max(max, nLength * weight(start))\n edges(start).sorted.map(to => result(to, nMax, nLength)).sorted.reverse.headOption.getOrElse(nMax)\n }\n }\n\n println((0 until n).map(i => result(i, 0, 0)).max)\n\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val visited = Array.fill[Int](n){ -1 }\n val weight = Array.ofDim[Int](n)\n val edges = Array.fill[List[Int]](n){ Nil }\n\n in.take(m).map(_.split(' ').map(_.toInt - 1)).foreach { i =>\n val min = Math.min(i.head, i.last)\n val max = Math.max(i.head, i.last)\n weight(min) += 1\n weight(max) += 1\n edges(min) ::= max\n }\n\n def result(start: Int, max: Int, length: Int): Int = {\n if (visited(start) >= length) max\n else {\n visited(start) = length\n val nLength = length + 1\n val nMax = Math.max(max, nLength * weight(start))\n edges(start).sorted.map(to => result(to, nMax, nLength)).sorted.reverse.headOption.getOrElse(nMax)\n }\n }\n\n println((0 until n).map(i => result(i, 0, 0)).max)\n\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val visited = Array.ofDim[Int](n)\n val weight = Array.ofDim[Int](n)\n val edges = Array.fill[List[Int]](n){ Nil }\n\n in.take(m).map(_.split(' ').map(_.toInt - 1)).foreach { i =>\n val min = Math.min(i.head, i.last)\n val max = Math.max(i.head, i.last)\n weight(min) += 1\n weight(max) += 1\n edges(min) ::= max\n }\n\n def result(start: Int, max: Int, length: Int): Int = {\n if (visited(start) >= length) max\n else {\n visited(start) = length\n val nLength = length + 1\n val nMax = Math.max(max, nLength * weight(start))\n edges(start).sorted.map(to => result(to, nMax, nLength)).sorted.reverse.headOption.getOrElse(nMax)\n }\n }\n\n println((0 until n).map(i => result(i, 0, 0)).max)\n\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val visited = Array.ofDim[Boolean](n)\n val weight = Array.ofDim[Int](n)\n val edges = Array.fill[List[Int]](n){ Nil }\n\n in.take(m).map(_.split(' ').map(_.toInt - 1)).foreach { i =>\n val min = Math.min(i.head, i.last)\n val max = Math.max(i.head, i.last)\n weight(min) += 1\n weight(max) += 1\n edges(min) ::= max\n }\n\n def result(start: Int, max: Int, length: Int): Int = {\n if (visited(start)) max\n else {\n// visited(start) = true\n val nLength = length + 1\n val nMax = Math.max(max, nLength * weight(start))\n edges(start).map(to => result(to, nMax, nLength)).sorted.reverse.headOption.getOrElse(nMax)\n }\n }\n\n println((0 until n).map(i => result(i, 0, 0)))\n\n}"}], "src_uid": "2596db1dfc124ea9e14c3f13c389c8d2"} {"source_code": "import scala.language.postfixOps\nimport java.io._\n\nobject CF_260C {\n\n def main(args: Array[String]) {\n val stdin = new BufferedReader(new InputStreamReader(System.in));\n val stdout = new PrintWriter(new BufferedOutputStream(System.out));\n val inp_args = stdin.readLine.split(\" \");\n val n = inp_args(0).toLong;\n val x = inp_args(1).toLong - 1;\n val end_list = stdin.readLine.split(\" \").toArray.map(_.toLong);\n val min = end_list.min\n val min_inds = {\n for( i <- 0 until end_list.length if end_list(i) == min )\n yield(i)\n }\n val lower_mins = min_inds filter(_ <= x);\n val start_pos: Int = {\n if( lower_mins.isEmpty )\n min_inds.last\n else\n lower_mins.last\n }\n val tmp_list = end_list.map(_ - min);\n val start_pos_value : Long = min * n + { if( x >= start_pos ) x - start_pos else x + n - start_pos };\n val start_list: Array[Long] =\n for( i <- 0 until tmp_list.length toArray ) yield\n if( i == start_pos )\n start_pos_value\n else if( ( x >= start_pos && i > start_pos && i <= x ) || ( x < start_pos && ( i > start_pos || i <= x ) ) )\n tmp_list(i) - 1\n else\n tmp_list(i)\n\n for( i <- 0 until start_list.length )\n stdout.print(start_list(i).toString + \" \");\n\n stdout.println();\n stdout.close();\n }\n}\n", "positive_code": [{"source_code": "object CF260C extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n val n = nextInt\n val x = nextInt - 1\n var a = (for (i <- 0 until n) yield nextLong).toArray\n\n var c = 0l\n var min = a.min\n if (min > 0) {\n a = a map { _ - min }\n c = min * n\n }\n\n var finished = false\n var i = x\n while (!finished) {\n if (a(i) == 0) {\n finished = true\n a(i) = c\n } else {\n a(i) -= 1\n c += 1\n i = if (i == 0) n - 1 else i - 1\n }\n }\n\n a foreach((x) => out.print(x + \" \"))\n out.println()\n }\n\n try { \n solve \n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}"}], "negative_code": [{"source_code": "import java.io._\n\nobject CF_260C {\n\n def main(args: Array[String]) {\n val stdin = new BufferedReader(new InputStreamReader(System.in));\n val stdout = new PrintWriter(new BufferedOutputStream(System.out));\n val inp_args = stdin.readLine.split(\" \");\n val n = inp_args(0).toInt;\n val x = inp_args(1).toInt - 1;\n val end_list = stdin.readLine.split(\" \").toArray.map(_.toInt);\n val min = end_list.min\n val min_inds = {\n for( i <- 0 until end_list.length if end_list(i) == min )\n yield(i)\n }\n val lower_mins = min_inds filter(_ <= x);\n val start_pos: Int = {\n if( lower_mins.isEmpty )\n min_inds.last\n else\n lower_mins.last\n }\n val tmp_list = end_list.map(_ - min);\n val start_pos_value = min * n + { if( x >= start_pos ) x - start_pos else x + n - start_pos };\n val start_list =\n for( i <- 0 until tmp_list.length ) yield\n if( i == start_pos )\n start_pos_value\n else if( ( x >= start_pos && i > start_pos ) || ( x < start_pos && ( i > start_pos || i <= x ) ) )\n tmp_list(i) - 1\n else\n tmp_list(i)\n\n for( i <- 0 until start_list.length )\n stdout.print(start_list(i).toString + \" \");\n\n stdout.println();\n stdout.close();\n }\n}\n"}], "src_uid": "7d4899d03a804ed1bdd77a475169a580"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt).toSet\n println((1 to 3001).find{i => !data.contains(i)}.get)\n}\n", "positive_code": [{"source_code": "object P027A {\n def main(args: Array[String]) = {\n var s = scala.collection.mutable.Set((1 to readInt+1) :_*)\n readLine.split(' ').map(x => x.toInt).foreach(x => s.remove(x))\n println(s min)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt).toSet\n val rest = Set() ++ ((1 to 3001)) -- a\n println(rest.min)\n }\n}"}], "negative_code": [], "src_uid": "5e449867d9fcecc84333b81eac9b5d92"} {"source_code": "object A extends App {\n case class Stat(p: Int, c: Int)\n\n implicit def arr2stat(arr: Array[Int]): Stat = arr match {\n case Array(p, c) => Stat(p, c)\n case _ => throw new IllegalArgumentException\n }\n\n private def isCorrect(s: Stat): Boolean = s.p >= s.c\n\n private def isCorrect(s1: Stat, s2: Stat): Boolean =\n isCorrect(s1) && isCorrect(s2) &&\n s1.p <= s2.p && s1.c <= s2.c && (s2.c - s1.c) <= (s2.p - s1.p)\n\n @scala.annotation.tailrec\n private def isCorrect(stats: List[Stat]): Boolean = stats match {\n case Nil => true\n case s :: Nil => isCorrect(s)\n case s1 :: s2 :: rest => isCorrect(s1, s2) && isCorrect(s2 :: rest)\n }\n\n val t = scala.io.StdIn.readInt()\n\n val stats = (0 until t)\n .foldLeft(List.empty[List[Stat]]) { (acc1, _) =>\n val n = scala.io.StdIn.readInt()\n\n val ss = (0 until n)\n .foldLeft(List.empty[Stat]) { (acc2, _) =>\n val s = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n s :: acc2\n }\n .reverse\n\n ss :: acc1\n }\n .reverse\n\n val answers = stats.map(isCorrect)\n\n answers.foreach(if (_) println(\"YES\") else println(\"NO\"))\n}", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Main {\n def main(args: Array[String]) = {\n val T = readLine.toInt\n for (_ <- 0 until T) {\n val n = readLine.toInt\n val (p, c) = (0 until n)\n .map(_ => readLine.split(' ').map(_.toInt))\n .map{ case Array(x, y) => (x, y) }\n .unzip\n val p_diff = p.zip(p drop 1) map {case (x, y) => y - x}\n val c_diff = c.zip(c drop 1) map {case (x, y) => y - x}\n \n if (c_diff.forall(_ >= 0) && (c_diff zip p_diff).forall{case (c, p) => c <= p} && c.head <= p.head) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n }\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Main {\n def main(args: Array[String]) = {\n val T = readLine.toInt\n for (_ <- 0 until T) {\n val n = readLine.toInt\n val (p, c) = (0 until n)\n .map(_ => readLine.split(' ').map(_.toInt))\n .map{ case Array(x, y) => (x, y) }\n .unzip\n val p_diff = p.zip(p drop 1) map {case (x, y) => y - x}\n val c_diff = c.zip(c drop 1) map {case (x, y) => y - x}\n \n if (c_diff.forall(_ >= 0) && (c_diff zip p_diff).forall{case (c, p) => c <= p}) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n }\n}"}], "src_uid": "714834defd0390659f6ed5bc3024f613"} {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(x, y) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val Array(a, b) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ans = 1L * a * math.abs(x - y) + math.min(2L * a, 1L * b) * math.min(x, y)\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject A {\n def solution(x: Int, y: Int, a: Long, b: Long): Long =\n if (y < x)\n solution(y, x, a, b)\n else\n if (a * 2 < b)\n a * (x + y)\n else\n a * (y - x) + b * x\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val Seq(x, y) = readLine.split(\" \").toSeq.map(_.toInt)\n val Seq(a, b) = readLine.split(\" \").toSeq.map(_.toInt)\n println(solution(x, y, a, b))\n }\n }\n}"}, {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n for (_ <- 1 to nextInt) {\n val x, y, a, b = nextLong\n val res1 = a * Math.abs(x - y) + b * Math.min(x, y)\n val res2 = a * (x + y)\n\n out.println(res1 min res2)\n }\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(x, y) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n val Array(a, b) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n val ans = a * math.abs(x - y) + math.min(a + a, b) * math.min(x, y)\n\n println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\nimport math._\n\nobject A {\n def solution(x: Int, y: Int, a: Int, b: Int): Int =\n if (abs(y) < abs(x))\n solution(y, x, a, b)\n else if (x < 0 && y < 0)\n solution(-x, -y, a, b)\n else if (x < 0 && y > 0)\n a * (y - x)\n else\n if (a * 2 < b)\n a * (x + y)\n else\n a * (y - x) + b * x\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val Seq(x, y) = readLine.split(\" \").toSeq.map(_.toInt)\n val Seq(a, b) = readLine.split(\" \").toSeq.map(_.toInt)\n println(solution(x, y, a, b))\n }\n }\n}"}, {"source_code": "import scala.io.StdIn.readLine\nimport math._\n\nobject A {\n def solution(x: Int, y: Int, a: Int, b: Int): Int =\n if (abs(y) < abs(x))\n solution(y, x, a, b)\n else if (x < 0 && y < 0)\n solution(-y, -x, a, b)\n else if (x < 0 && y > 0)\n a * (y - x)\n else\n if (a * 2 < b)\n a * (x + y)\n else\n a * (y - x) + b * x\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val Seq(x, y) = readLine.split(\" \").toSeq.map(_.toInt)\n val Seq(a, b) = readLine.split(\" \").toSeq.map(_.toInt)\n println(solution(x, y, a, b))\n }\n }\n}"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject A {\n def solution(x: Int, y: Int, a: Int, b: Int): Int =\n if (y < x)\n solution(y, x, a, b)\n else\n if (a * 2 < b)\n a * (x + y)\n else\n a * (y - x) + b * x\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val Seq(x, y) = readLine.split(\" \").toSeq.map(_.toInt)\n val Seq(a, b) = readLine.split(\" \").toSeq.map(_.toInt)\n println(solution(x, y, a, b))\n }\n }\n}"}, {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n for (_ <- 1 to nextInt) {\n val x, y, a, b = nextLong\n val res = a * Math.abs(x - y) + b * Math.min(x, y)\n\n out.println(res)\n }\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(x, y) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n val Array(a, b) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n val ans = a * math.abs(x - y) + math.min(a, b) * math.min(x, y)\n\n println(ans)\n }\n}\n"}, {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(x, y) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val Array(a, b) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ans = 1L * a * math.abs(x - y) + math.min(2L * a * x, 1L * b * x)\n\n println(ans)\n }\n}\n"}], "src_uid": "edf394051c6b35f593abd4c34b091eae"} {"source_code": "import scala.io.StdIn._\n\nobject ProblemA extends App {\n val n = readInt()\n val A: Seq[Int] = readLine().split(' ').map(_ toInt)\n val B: Seq[Int] = readLine().split(' ').map(_ toInt)\n var maxbs = Seq(-1, -1)\n for (b <- B) {\n maxbs = Seq(maxbs(0).max(b), maxbs(1)).sorted\n }\n println(if (maxbs.sum >= A.map(BigInt(_)).sum) \"YES\" else \"NO\")\n}\n", "positive_code": [{"source_code": "object A extends App {\n val n = scala.io.StdIn.readLine().toLong\n val A = scala.io.StdIn.readLine().split(\" \").foldLeft(0L)(_ + _.toLong)\n val b = scala.io.StdIn.readLine().split(\" \").map(_.toLong).sortWith(_ > _)\n\n if (b(0) + b(1) >= A) println(\"YES\")\n else println(\"NO\")\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject ProblemA extends App {\n val n = readInt()\n val A: Seq[Int] = readLine().split(' ').map(_ toInt)\n val B: Seq[Int] = readLine().split(' ').map(_ toInt)\n var maxbs = Seq(-1, -1)\n for (b <- B) {\n maxbs = Seq(maxbs(0), maxbs(1).max(b)).sorted(Ordering[Int].reverse)\n }\n println(if (maxbs.sum >= A.sum) \"YES\" else \"NO\")\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject ProblemA extends App {\n val n = readInt()\n val A: Seq[Int] = readLine().split(' ').map(_ toInt)\n val B: Seq[Int] = readLine().split(' ').map(_ toInt)\n var maxbs = Seq(-1, -1)\n for (b <- B) {\n maxbs = Seq(maxbs(0).max(b), maxbs(1)).sorted\n }\n println(if (maxbs.map(BigInt(_)).sum >= A.sum) \"YES\" else \"NO\")\n}\n"}, {"source_code": "object A extends App {\n val n = scala.io.StdIn.readLine().toInt\n val A = scala.io.StdIn.readLine().split(\" \").foldLeft(0)(_ + _.toInt)\n val b = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sortWith(_ > _)\n\n if (b(0) + b(1) >= A && b(0) < A) println(\"YES\")\n else println(\"NO\")\n}\n"}, {"source_code": "object A extends App {\n val n = scala.io.StdIn.readLine().toInt\n val A = scala.io.StdIn.readLine().split(\" \").foldLeft(0)(_ + _.toInt)\n val b = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sortWith(_ > _)\n\n if (b(0) + b(1) >= A) println(\"YES\")\n else println(\"NO\")\n}\n"}], "src_uid": "88390110e4955c521867864a6f3042a0"} {"source_code": "//package codeforces.contests._1359\n\nobject _4 {\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val seq = 0 +: io.StdIn.readLine.split(\" \").map(_.toInt) // 1 based\n val prefix = seq.scanLeft(0)(_ + _).tail\n\n @scala.annotation.tailrec\n def calculateLeftView(idx: Int = 1,\n decreasingStack: List[(Int, Int)] = Nil, // stack for indices and there max sub array sum ending at them\n resultList: List[Int] = Nil): List[Int] = {\n if (idx > n) resultList\n else {\n val (toConsider, rest) = decreasingStack.partition { case (i, _) => seq(i) <= seq(idx) }\n\n val resultSum = toConsider.foldLeft(seq(idx)) { case (acc, (i, maxSum)) =>\n val rangeSum = prefix(idx) - prefix(i) // without i\n acc max ((maxSum + rangeSum) max (seq(i) + rangeSum))\n }\n\n calculateLeftView(idx + 1, (idx, resultSum) :: rest, resultSum :: resultList)\n }\n }\n\n @scala.annotation.tailrec\n def calculateRightView(idx: Int = n,\n decreasingStack: List[(Int, Int)] = Nil, // stack for indices and there max sub array sum ending at them\n resultList: List[Int] = Nil): List[Int] = {\n if (idx == 0) resultList\n else {\n val (toConsider, rest) = decreasingStack.partition { case (i, _) => seq(i) <= seq(idx) }\n\n val resultSum = toConsider.foldLeft(seq(idx)) { case (acc, (i, maxSum)) =>\n val rangeSum = prefix(i - 1) - prefix(idx - 1)\n acc max ((maxSum + rangeSum) max (seq(i) + rangeSum))\n }\n\n calculateRightView(idx - 1, (idx, resultSum) :: rest, resultSum :: resultList)\n }\n }\n\n val leftView = calculateLeftView().reverse\n val rightView = calculateRightView()\n println {\n leftView.zip(rightView).zipWithIndex.foldLeft(0) { case (acc, ((lSum, rSum), i)) => acc max (lSum + rSum - 2 * seq(i + 1)) }\n }\n }\n}\n", "positive_code": [{"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val _ = StdIn.readLine().toInt\n val arr = StdIn.readLine.trim.split(\" \").map(_.toInt)\n def maxSubArrayEx(nums: Array[Int], max: Int): Int = {\n var res: Long = 0\n var cur: Long = 0\n for (i <- nums.indices ) {\n if (nums(i) > max) cur = 0\n else {\n cur = math.max(cur + nums(i),0)\n res = math.max(res, cur-max)\n }\n }\n res.toInt\n }\n println((1 to 30).map(maxSubArrayEx(arr, _)).max)\n }\n}\n"}, {"source_code": "object D extends App {\n val n = scala.io.StdIn.readInt()\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ans = (0 to 30).foldLeft(0) {\n case (ans, m) =>\n ans max (an\n .foldLeft((0, 0)) {\n case ((subSum, partSum), a) =>\n if (a > m) (subSum, 0)\n else (subSum max (partSum + a), 0 max (partSum + a))\n }\n ._1 - m)\n }\n\n println(ans)\n}\n"}], "negative_code": [{"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n val arr = StdIn.readLine.trim.split(\" \").map(_.toInt)\n def maxSubArrayEx(nums: Array[Int]): Int = {\n var res: Long = 0\n var cur: Long = nums(0)\n var emax: Long = nums(0)\n for (i <- 1 until nums.length) {\n if (cur + nums(i) < nums(i)) {\n cur = nums(i)\n emax = nums(i)\n } else {\n cur = cur + nums(i)\n emax = emax max nums(i)\n }\n res = res max (cur - emax)\n }\n res.toInt\n }\n println(maxSubArrayEx(arr))\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n val arr = StdIn.readLine.trim.split(\" \").map(_.toInt)\n def maxSubArrayEx(nums: Array[Int]): Int = {\n var res: Long = 0\n var cur: Long = nums(0)\n var emax: Long = nums(0)\n for (i <- 1 until nums.length) {\n if (cur + nums(i) < nums(i)) {\n cur = nums(i)\n emax = nums(i)\n } else {\n cur = cur + nums(i)\n emax = emax max nums(i)\n }\n res = res max (cur - emax)\n }\n res.toInt\n }\n maxSubArrayEx(arr)\n }\n}\n"}, {"source_code": "object D extends App {\n val n = scala.io.StdIn.readInt()\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ans = (0 to 30).map { m =>\n an.foldLeft((an.head, 0)) {\n case ((subSum, partSum), a) =>\n if (a > m) (subSum, 0)\n else (subSum max (partSum + a), 0 max (partSum + a))\n }\n ._1 - m\n }.max\n\n println(ans)\n\n}\n"}], "src_uid": "b2d77fa3e0c2dad9c316249a0feeb4c6"} {"source_code": "object CF499D extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val m = in.nextInt\n val n = in.nextInt\n\n var count = -1\n def ask(question: Int): Int = {\n count += 1\n out.println(question)\n out.flush\n\n val answer = in.nextInt\n if (answer == 0 || answer == -2) {\n out.close\n System.exit(0)\n }\n answer\n }\n\n // log(10^9)/log(2) = 29.9\n // so we can waste 30 questions to determine the lie sequence and still have 30 left to find the answer\n // All answers should be 1\n val lieSequence = new Array[Int](30).map(_ => ask(1)).map(_ != 1).take(n)\n\n var min = 1\n var max = m\n\n while (true) {\n // Binary search\n val question = (min + max)/2\n val answer = (ask(question) == 1) ^ lieSequence(count%n) // real answer\n if (answer) {\n // more\n min = question + 1\n } else {\n // less\n max = question - 1\n }\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val M, N = ni()\n\n case class Answer(x: Int)\n\n def query(y: Int): Either[Answer, Int] = {\n// debug(s\"query $y\")\n out.println(y)\n out.flush()\n val res = ni()\n if (res == 0) Left(Answer(y))\n else Right(res)\n }\n\n def makeP(i: Int, p: Array[Int]): Either[Answer, Array[Int]] = {\n if (i == N) Right(p)\n else {\n // x >= i + 1 なので、0でなければ x > y => 1 が返るはず。\n // -1がくるかどうかでpを判定する\n query(i + 1).right flatMap { res =>\n p(i) = res\n makeP(i + 1, p)\n }\n }\n }\n\n def search(p: Array[Int]): Either[Answer, _] = {\n def step(i: Int, l: Int, r: Int): Either[Answer, _] = {\n// debug(s\"step($i, $l, $r)\")\n if (r - l == 1) {\n// debug(s\"found $r\")\n query(r)\n } else {\n val mid = (l + r) / 2 + 1\n query(mid).right flatMap { res =>\n if (res * p(i % N) == 1) step(i + 1, mid, r) // 1 => x > y\n else step(i + 1, l, mid - 1) // -1 => x < y =>\n }\n }\n }\n\n step(0, N, M)\n }\n\n // 結果を出力しなくていい。0が帰った時点で終わり\n for {\n p <- makeP(0, Array.ofDim[Int](N)).right\n _ <- search(p).right\n } ()\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}, {"source_code": "object CF499D extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val m = in.nextInt\n val n = in.nextInt\n\n var count = -1\n def ask(question: Int): Int = {\n count += 1\n out.println(question)\n out.flush\n\n val answer = in.nextInt\n if (answer == 0 || answer == -2) {\n out.close\n System.exit(0)\n }\n answer\n }\n\n // log(10^9)/log(2) = 29.9\n // so we can waste up to 30 questions to determine the lie sequence and still have 30 left to find the answer\n // Ask n times \"1\", all answers should be 1 (meaning distance > 1)\n val lieSequence = new Array[Int](n).map(_ => ask(1)).map(_ != 1)\n\n var min = 1\n var max = m\n\n while (true) {\n // Binary search\n val question = (min + max)/2\n val answer = (ask(question) == 1) ^ lieSequence(count%n) // real answer\n if (answer) {\n // more\n min = question + 1\n } else {\n // less\n max = question - 1\n }\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val M, N = ni()\n\n case class Answer(x: Int)\n\n def query(y: Int): Either[Answer, Int] = {\n// debug(s\"query $y\")\n out.println(y)\n out.flush()\n val res = ni()\n if (res == 0) Left(Answer(y))\n else Right(res)\n }\n\n def makeP(i: Int, p: Array[Int]): Either[Answer, Array[Int]] = {\n if (i == N) Right(p)\n else {\n // x >= i + 1 なので、0でなければ x > y => 1 が返るはず。\n // -1がくるかどうかでpを判定する\n query(i + 1).right flatMap { res =>\n p(i) = res\n makeP(i + 1, p)\n }\n }\n }\n\n def search(p: Array[Int]): Either[Answer, _] = {\n def step(i: Int, l: Int, r: Int): Either[Answer, _] = {\n// debug(s\"step($i, $l, $r)\")\n if (r - l == 1) {\n// debug(s\"found $r\")\n query(r)\n } else {\n val mid = (l + r) / 2\n query(mid).right flatMap { res =>\n if (res * p(i % N) == 1) step(i + 1, mid, r) // 1 => x > y\n else step(i + 1, l, mid) // -1 => x < y =>\n }\n }\n }\n\n step(0, N, M)\n }\n\n // 結果を出力しなくていい。0が帰った時点で終わり\n for {\n p <- makeP(0, Array.ofDim[Int](N)).right\n _ <- search(p).right\n } ()\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val M, N = ni()\n\n case class Answer(x: Int)\n\n def query(y: Int): Either[Answer, Int] = {\n// debug(s\"query $y\")\n out.println(y)\n out.flush()\n val res = ni()\n if (res == 0) Left(Answer(y))\n else Right(res)\n }\n\n def makeP(i: Int, p: Array[Int]): Either[Answer, Array[Int]] = {\n if (i == N) Right(p)\n else {\n // x >= i + 1 なので、0でなければ x > y => 1 が返るはず。\n // -1がくるかどうかでpを判定する\n query(i + 1).right flatMap { res =>\n p(i) = res\n makeP(i + 1, p)\n }\n }\n }\n\n def search(p: Array[Int]): Either[Answer, _] = {\n def step(i: Int, l: Int, r: Int): Either[Answer, _] = {\n// debug(s\"step($i, $l, $r)\")\n if (r - l == 1) {\n// debug(s\"found $r\")\n query(r)\n } else {\n val mid = (l + r) / 2\n query(mid).right flatMap { res =>\n if (res * p(i % N) == 1) step(i + 1, mid, r) // 1 => x > y\n else step(i + 1, l, mid - 1) // -1 => x < y =>\n }\n }\n }\n\n step(0, N, M)\n }\n\n // 結果を出力しなくていい。0が帰った時点で終わり\n for {\n p <- makeP(0, Array.ofDim[Int](N)).right\n _ <- search(p).right\n } ()\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}], "src_uid": "f06dff83491772f8879e45b90b61dc88"} {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, k = nextInt\n val x: Long = Math.max(n, k)\n var res: Long = Math.max(1, x / n)\n if (n * res % k > 0) res += 1\n\n out.println(res)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "object Solution {\r\n def main(args: Array[String]): Unit = {\r\n val stdin = scala.io.StdIn\r\n var T = stdin.readInt()\r\n while(T > 0) {\r\n val str = stdin.readLine().split(\" \")\r\n var n = str(0).toInt\r\n var k = str(1).toInt\r\n if(k < n){\r\n if(n % k == 0){\r\n println(1)\r\n } else {\r\n k *= n / k + 1\r\n println(k / n + 1)\r\n }\r\n } else {\r\n if(k % n == 0) println(k / n)\r\n else println(k / n + 1)\r\n }\r\n T -= 1\r\n }\r\n }\r\n}\r\n\r\n"}, {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, k = nextInt\n val x = Math.max(n, k)\n var res = Math.max(1, x / n)\n if (n * res % k > 0) res += 1\n\n out.println(res)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "//package codeforces.CF1476\n\nimport scala.io.StdIn._\n\nobject SolutionA extends App {\n (1 to readInt()).foreach {\n _ =>\n val strings = readLine().split(\" \")\n val n = strings.head.toLong\n val k = strings.last.toLong\n if (n <= k) {\n println(k / n + (k % n != 0).compare(false))\n } else {\n val realK = (n / k + (n % k != 0).compare(false)) * k\n println(realK / n + (realK % n != 0).compare(false))\n }\n }\n}\n"}], "negative_code": [{"source_code": "object Solution {\r\n def main(args: Array[String]): Unit = {\r\n val stdin = scala.io.StdIn\r\n var T = stdin.readInt()\r\n while(T > 0) {\r\n val str = stdin.readLine().split(\" \")\r\n var n = str(0).toInt\r\n var k = str(1).toInt\r\n if(k < n){\r\n if(n % k == 0){\r\n println(1)\r\n } else {\r\n k *= n / k + 1\r\n }\r\n } else {\r\n if(k % n == 0) println(k / n)\r\n else println(k / n + 1)\r\n }\r\n if(k < n){\r\n val temp = n / k\r\n k *= temp + 1\r\n }\r\n\r\n T -= 1\r\n }\r\n }\r\n}\r\n\r\n"}, {"source_code": "object Solution {\r\n def main(args: Array[String]): Unit = {\r\n val stdin = scala.io.StdIn\r\n var T = stdin.readInt()\r\n while(T > 0) {\r\n val str = stdin.readLine().split(\" \")\r\n var n = str(0).toInt\r\n var k = str(1).toInt\r\n if(k < n){\r\n val temp = n / k\r\n k *= temp + 1\r\n }\r\n if(k % n == 0) println(k / n)\r\n else println(k / n + 1)\r\n T -= 1\r\n }\r\n }\r\n}\r\n\r\n"}, {"source_code": "object Solution {\r\n def main(args: Array[String]): Unit = {\r\n val stdin = scala.io.StdIn\r\n var T = stdin.readInt()\r\n while(T > 0) {\r\n val str = stdin.readLine().split(\" \")\r\n var n = str(0).toInt\r\n var k = str(1).toInt\r\n if(k < n) k *= 2\r\n if(k % n == 0) println(k / n)\r\n else println(k / n + 1)\r\n T -= 1\r\n }\r\n }\r\n}\r\n\r\n"}, {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, k = nextInt\n var res = Math.max(1, k / n)\n if (k % n > 0) res += 1\n\n out.println(res)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "src_uid": "a28b84c9d1a54e322ab2d54bd5ab45c8"} {"source_code": "object Solution {\n def main(args: Array[String]) {\n val r = new Reader()\n val n, m = r.read[Int]\n import Utils._\n val xs = r.read[List[Int]](m).sorted.group(_ == _)\n \n if (xs.length < n) {\n println(0)\n } else {\n println(xs.map(_.length).min)\n }\n }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def this() = this(new InputStreamReader(System.in))\n\n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n\n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n implicit val double: Read[Double] = new Read(_.read[String].toDouble)\n \n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n \n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n}\n\nobject Utils {\n implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)\n\n class ExtendedList[A](xs: List[A]) {\n def group(g: (A, A) => Boolean) =\n xs.foldRight(List[List[A]]()) {\n case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs\n case (x, _) => List(List(x))\n }\n }\n}", "positive_code": [{"source_code": "object Solution {\n \n def main(args: Array[String]) {\n val inp = readLine.split(\" \").map(_.toInt)\n val arr = Array.ofDim[Int](inp(0))\n readLine.split(\" \").foreach(f => arr(f.toInt - 1) += 1)\n print(arr.min)\n }\n}\n"}, {"source_code": "object Tetrix extends App {\n val firstinput = Console.in.readLine().split(\" \").map( _.toInt).toList\n val n = firstinput(0)\n val m = firstinput(1)\n val squares = Console.in.readLine().split(\" \").map( _.toInt).toList\n\n val emptyFreqMap = (1 to n).map( x => (x, 0)).toMap\n val distinctSquaresValues = emptyFreqMap.keys.size\n val freqMap = squares.groupBy( x => x).mapValues( _.length )\n val finalMap = emptyFreqMap ++ freqMap\n val minFq = finalMap.minBy( _._2 )._2\n\n val points =\n if(distinctSquaresValues < n) 0\n else minFq\n\n println(points)\n}"}, {"source_code": "object Tetrix extends App {\n val firstinput = Console.in.readLine().split(\" \").map( _.toInt).toList\n // Seq(1, 1000)\n // Seq(3, 9)\n // Console.in.readLine().split(\" \").map( _.toInt).toList\n val n = firstinput(0) // cantidad de valores distintos\n val m = firstinput(1)\n val squares = Console.in.readLine().split(\" \").map( _.toInt).toList\n // (1 to 1000).map(x => 1).toList\n // List(1, 1, 2, 2, 2, 3, 1, 2, 3)\n // Console.in.readLine().split(\" \").map( _.toInt).toList\n\n\n val emptyFreqMap = (1 to n).map( x => (x, 0)).toMap\n val distinctSquaresValues = emptyFreqMap.keys.size\n val freqMap = squares.groupBy( x => x).mapValues( _.length )\n val finalMap = emptyFreqMap ++ freqMap\n val maxFq = finalMap.maxBy( _._2 )._2\n val minFq = finalMap.minBy( _._2 )._2\n\n val resutl =\n if(distinctSquaresValues < n) {\n 0\n } else if (distinctSquaresValues == 1) {\n maxFq\n } else {\n minFq\n }\n\n println(resutl)\n}"}, {"source_code": "object A {\n def main(args: Array[String]) {\n val t = scala.io.StdIn.readLine().split(\" \").map( _.toInt );\n val n = t(0);\n val m = t(1);\n //println(n, m);\n val s = scala.io.StdIn.readLine();\n var cs = s.split(\" \").map( _.toInt );\n //println(cs.size)\n var a = Array.ofDim[Int](n);\n //println(a.size)\n for(c <- cs){\n //println(c - 1)\n //println(cs(i) - 1)\n a(c - 1) += 1;\n }\n var ans = m + m;\n for(i <- 0 until n){\n ans = math.min(ans, a(i))\n }\n println(ans)\n }\n}"}, {"source_code": "\nobject problemA {\n import java.io.{BufferedReader, FileInputStream, InputStreamReader}\n import scala.collection.mutable.ArrayBuffer\n import scala.collection.mutable\n import scala.util.control.Breaks._\n\n val source = System.in\n //new FileInputStream(\"D://in.txt\")\n implicit val reader = new BufferedReader(new InputStreamReader(source))\n\n def read()(implicit reader: BufferedReader): String = reader.readLine().split(\" \")(0)\n def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(\" \")\n def readString()(implicit reader: BufferedReader): String = reader.readLine()\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readArray.map(_.toInt)\n val f = new Array[Int](n)\n\n val k = readArray().map(_.toInt)\n\n for (i <- k) {\n f(i - 1) += 1\n }\n\n println(f.min)\n\n }\n}\n"}], "negative_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val r = new Reader()\n val n, m = r.read[Int]\n val xs = r.read[List[Int]](m)\n \n import Utils._\n println(xs.sorted.group(_ == _).map(_.length).min)\n }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def this() = this(new InputStreamReader(System.in))\n\n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n\n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n implicit val double: Read[Double] = new Read(_.read[String].toDouble)\n \n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n \n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n}\n\nobject Utils {\n import scala.math._\n\n implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)\n\n class ExtendedList[A](xs: List[A]) {\n def group(g: (A, A) => Boolean) =\n xs.foldRight(List[List[A]]()) {\n case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs\n case (x, _) => List(List(x))\n }\n }\n}"}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n val r = new Reader()\n val n, m = r.read[Int]\n val xs = r.read[List[Int]](m).sorted\n \n if (xs.length < n) {\n println(0)\n } else {\n import Utils._\n \n println(xs.sorted.group(_ == _).map(_.length).min)\n }\n }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def this() = this(new InputStreamReader(System.in))\n\n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n\n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n implicit val double: Read[Double] = new Read(_.read[String].toDouble)\n \n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n \n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n}\n\nobject Utils {\n import scala.math._\n\n implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)\n\n class ExtendedList[A](xs: List[A]) {\n def group(g: (A, A) => Boolean) =\n xs.foldRight(List[List[A]]()) {\n case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs\n case (x, _) => List(List(x))\n }\n }\n}"}, {"source_code": "import scala.annotation.tailrec\n\nobject Tetrix extends App {\n val _: String = Console.in.readLine()\n val squares = Console.in.readLine().split(\" \").map( _.toInt).toList\n @tailrec\n def minFreq(a: List[Int], min: Int, max: Int, freq: Map[Int, Int]): (Int, Int) = a match {\n case Nil => (min, max)\n case x :: xs =>\n val currValue : Int = freq.getOrElse(x, 0)\n val newValue = currValue + 1\n val newFreq: Map[Int, Int] = freq + (x -> newValue)\n if(max <= newValue) {\n minFreq(xs, max, newValue, newFreq)\n } else if(min >= newValue){\n minFreq(xs, newValue, max, newFreq)\n } else {\n minFreq(xs, min, max, newFreq)\n }\n }\n\n val (min, max) = minFreq(squares, 0, 0, Map.empty[Int, Int])\n println { min }\n}"}, {"source_code": "object Tetrix extends App {\n val _ = Console.in.readLine()\n\n val squares = Console.in.readLine().split(\" \").map(_.toInt)\n val x = squares.groupBy(x => x).mapValues(_.length).values.min\n\n println { x }\n}"}, {"source_code": "object Tetrix extends App {\n val firstinput = Console.in.readLine().split(\" \").map( _.toInt).toList\n val n = firstinput(0)\n val m = firstinput(1)\n val squares = Console.in.readLine().split(\" \").map( _.toInt).toList\n\n def increaseFreq(e: Int, freqMap: Map[Int, Int]): Map[Int, Int] = {\n val currValue = freqMap.getOrElse(e, 0)\n freqMap + (e -> (currValue + 1))\n }\n\n\n def pointsOf(Fq: Int, minFq: Int , maxFq: Int): (Int, Int) = {\n if(Fq >= maxFq) (maxFq, Fq)\n else (Fq, maxFq) \n }\n\n def minFreq(a: List[Int], freqMap: Map[Int, Int], minFq: Int , maxFq: Int): (Int, Map[Int, Int]) = a match {\n case Nil => (minFq, freqMap)\n case x :: xs =>\n val newMap = increaseFreq(x, freqMap)\n val (points, newMax) = pointsOf(newMap(x), minFq, maxFq)\n minFreq(xs, newMap, points, newMax)\n }\n\n val tablero = Map.empty[Int, Int]\n val initialPoints = 0\n val (min, freq) = minFreq(squares, tablero, minFq = initialPoints, maxFq = 0)\n\n val result = \n if(1 < freq.keys.size && freq.keys.size < n) 0\n else if (1 == freq.keys.size) min + 1\n else min\n\n println(result)\n}"}, {"source_code": "object Tetrix extends App {\n val firstinput = Console.in.readLine().split(\" \").map( _.toInt).toList\n val n = firstinput(0)\n val m = firstinput(1)\n val squares = Console.in.readLine().split(\" \").map( _.toInt).toList\n\n def increaseFreq(e: Int, freqMap: Map[Int, Int]): Map[Int, Int] = {\n val currValue = freqMap.getOrElse(e, 0)\n freqMap + (e -> (currValue + 1))\n }\n\n\n def pointsOf(Fq: Int, minFq: Int , maxFq: Int): (Int, Int) = {\n if(Fq >= maxFq) (maxFq, Fq)\n else (Fq, maxFq) \n }\n\n def minFreq(a: List[Int], freqMap: Map[Int, Int], minFq: Int , maxFq: Int): (Int, Map[Int, Int]) = a match {\n case Nil => (minFq, freqMap)\n case x :: xs =>\n val newMap = increaseFreq(x, freqMap)\n val (points, newMax) = pointsOf(newMap(x), minFq, maxFq)\n minFreq(xs, newMap, points, newMax)\n }\n\n val tablero = Map.empty[Int, Int]\n val initialPoints = 0\n val (min, freq) = minFreq(squares, tablero, minFq = initialPoints, maxFq = 0)\n\n val result = \n if(freq.keys.size < n) 0\n else min\n\n println(result)\n}"}, {"source_code": "import scala.annotation.tailrec\n\nobject Tetrix extends App {\n val _: String = Console.in.readLine()\n val squares = Console.in.readLine().split(\" \").map( _.toInt).toList\n @tailrec\n def minFreq(a: List[Int], min: Int, max: Int, freq: Map[Int, Int]): (Int, Int) = a match {\n case Nil => (min, max)\n case x :: xs =>\n val currValue : Int = freq.getOrElse(x, 0)\n val newValue = currValue + 1\n val newFreq: Map[Int, Int] = freq + (x -> newValue)\n if(max <= newValue) {\n minFreq(xs, max, newValue, newFreq)\n } else if(min <= newValue){\n minFreq(xs, min, max, newFreq)\n } else {\n minFreq(xs, newValue, max, newFreq)\n }\n }\n\n val (min, max) = minFreq(squares, 0, 0, Map.empty[Int, Int])\n println { min }\n}"}], "src_uid": "c249103153c5006e9b37bf15a51fe261"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val Array(n, m, d) = readLine.split(\" \").map(_.toInt)\n val c = readLine.split(\" \").zipWithIndex.map{ case (x, i) => (i+1, x.toInt) }.toList\n val sc = c.foldLeft(0){ case (s, (_, v)) => s + v }\n f1(n, d, c, sc) match {\n case None => println(\"NO\")\n case Some(l) => {\n println(\"YES\")\n println(l.mkString(\" \"))\n }\n }\n }\n\n def f1(n: Int, d: Int, c: List[(Int, Int)], sc: Int): Option[List[Int]] = {\n if (d - 1 + sc >= n) {\n Some(c.map{ case (i, ni) => List.fill(ni)(i) }.foldLeft(List.fill(n - sc)(0)){ case (li, lj) => li ++ lj })\n } else {\n c match {\n case Nil => None\n case (i, ni) :: rc => f1(n - (ni + d - 1), d, rc, (sc - ni)) match {\n case Some(l) => Some(List.fill(d - 1)(0) ++ List.fill(ni)(i) ++ l)\n case None => None\n }\n }\n }\n }\n\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nimport scala.language.postfixOps\n\nobject TaskC extends App {\n val sc = new Scanner(System.in)\n val (n, m, d) = (sc.nextInt, sc.nextInt, sc.nextInt)\n\n\n var w = 0\n val platforms = (1 to m).map(_ => sc.nextInt).zipWithIndex.reverse.map { case (c, ind) =>\n val platform = (n - w - c + 1, c, ind + 1)\n w += c\n platform\n }.reverse.toArray\n\n var last = 0\n\n 0 until m foreach { i =>\n if (platforms(i)._1 - last > d) {\n platforms(i) = (last + d, platforms(i)._2, platforms(i)._3)\n }\n last = platforms(i)._1 + platforms(i)._2 - 1\n }\n\n val out = if (n - last + 1 <= d) {\n val water = Array.fill(n)(0)\n platforms.foreach { case (i, c, l) =>\n i until (i + c) foreach (j => water(j - 1) = l)\n }\n s\"YES\\n${water.mkString(\" \")}\"\n } else {\n \"NO\"\n }\n\n println(out)\n}\n"}], "negative_code": [], "src_uid": "7f4293c5602429819e05beca45b22c05"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, x) = in.next().split(' ').map(_.toInt)\n\n\n val (sweetl, candyl) = (1 to n).foldLeft((List.empty[(Int, Int)], List.empty[(Int, Int)])) {\n case ((s, c), _) =>\n\n val Array(t, h, m) = in.next().split(' ').map(_.toInt)\n t match {\n case 0 => (s, (h, m) :: c)\n case _ => ((h, m) :: s, c)\n }\n }\n\n def calc(isCandyl: Boolean): Int = {\n val sweet = sweetl.toArray\n val candy = candyl.toArray\n var work = true\n var count = 0\n var possibleh = x\n var isCandy = isCandyl\n\n while (work) {\n if (isCandy) {\n val index = candy.indices.foldLeft(-1) {\n case (-1, i) if candy(i)._1 <= possibleh && candy(i)._2 > 0 => i\n case (j, i) if candy(i)._1 <= possibleh && j >= 0 && candy(i)._2 > candy(j)._2 => i\n case (j, i) => j\n }\n work = index != -1\n\n if (work) {\n possibleh += candy(index)._2\n candy(index) = (0, 0)\n }\n\n } else {\n val index = sweet.indices.foldLeft(-1) {\n case (-1, i) if sweet(i)._1 <= possibleh && sweet(i)._2 > 0 => i\n case (j, i) if sweet(i)._1 <= possibleh && j >= 0 && sweet(i)._2 > sweet(j)._2 => i\n case (j, i) => j\n }\n work = index != -1\n if (work) {\n possibleh += sweet(index)._2\n sweet(index) = (0, 0)\n }\n }\n if (work) count += 1\n// println(candy.mkString(\" \"))\n// println(sweet.mkString(\" \"))\n isCandy = !isCandy\n }\n count\n }\n// println(candyl)\n// println(sweetl)\n// println(calc(true))\n// println(calc(false))\n println(Math.max(calc(true), calc(false)))\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\n/**\n * Created by hama_du on 2014/06/19.\n */\nobject ProblemA extends App {\n def solve(jump: Int, caramel: Array[(Int,Int,Boolean)], fruit:Array[(Int,Int,Boolean)], want: Int): Int = {\n if (want == 0) {\n val idx = selectAvailable(jump, caramel)\n if (idx == -1) {\n return 0\n }\n val gain = caramel(idx)._2\n caramel(idx) = (0, 0, true)\n solve(jump + gain, caramel, fruit, 1-want) + 1\n } else {\n val idx = selectAvailable(jump, fruit)\n if (idx == -1) {\n return 0\n }\n val gain = fruit(idx)._2\n fruit(idx) = (0, 0, true)\n solve(jump + gain, caramel, fruit, 1-want) + 1\n }\n }\n\n def selectAvailable(jump: Int, candies: Array[(Int,Int,Boolean)]): Int = {\n val available = candies.zipWithIndex.filter(ci => ci._1._1 <= jump && !ci._1._3 )\n if (available.size == 0) {\n -1\n } else {\n available.maxBy(ci => ci._1._2)._2\n }\n }\n\n val in = new Scanner(System.in)\n val n,x = in.nextInt()\n val candies = (0 until n).map(_ => {\n (in.nextInt(), in.nextInt(), in.nextInt())\n })\n val answer = (0 to 1).map(start => {\n // (height, mass, eaten)\n val caramel = candies.filter(c => c._1 == 0).map(c => (c._2, c._3, false)).toArray\n val fruit = candies.filter(c => c._1 == 1).map(c => (c._2, c._3, false)).toArray\n solve(x, caramel, fruit, start)\n }).max\n println(answer)\n}\n"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, x) = readInts(2)\n val _as = mutable.ArrayBuffer.empty[(Int, Int)]\n val _bs = mutable.ArrayBuffer.empty[(Int, Int)]\n\n for (i <- 0 until n) {\n val Array(t, h, m) = readInts(3)\n if (t == 0) {\n _as += ((h, m))\n } else {\n _bs += ((h, m))\n }\n }\n\n val as = _as.sortBy(_._2)\n val bs = _bs.sortBy(_._2)\n\n def calc(prev0: Boolean): Int = {\n val aUsed = Array.fill(n)(false)\n val bUsed = Array.fill(n)(false)\n var ai = 0\n var bi = 0\n var h = x\n var count = 0\n var prev = prev0\n var choice = 0\n while (choice >= 0 && ((prev && ai < as.size) || (!prev && bi < bs.size))) {\n choice = -1\n if (prev) {\n for (i <- as.indices) if (!aUsed(i) && as(i)._1 <= h) choice = i\n if (choice >= 0) {\n h += as(choice)._2\n aUsed(choice) = true\n ai += 1\n count += 1\n }\n } else {\n for (i <- bs.indices) if (!bUsed(i) && bs(i)._1 <= h) choice = i\n if (choice >= 0) {\n h += bs(choice)._2\n bUsed(choice) = true\n bi += 1\n count += 1\n }\n }\n prev = !prev\n }\n count\n }\n\n println(calc(true) max calc(false))\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, x) = in.next().split(' ').map(_.toInt)\n val (sweetl, candyl) = (1 to n).foldLeft((List.empty[(Int, Int)], List.empty[(Int, Int)])) {\n case ((s, c), _) =>\n\n val Array(t, h, m) = in.next().split(' ').map(_.toInt)\n t match {\n case 0 => (s, (h, m) :: c)\n case _ => ((h, m) :: s, c)\n }\n }\n val sweet = sweetl.toArray\n val candy = candyl.toArray\n\n var isCandy = !sweet.exists{ case(h, m) => h <= x && m > 0} ||\n (candy.exists{ case(h, m) => h <= x && m > 0 } && candy.filter{case(h, m) => h <= x && m > 0}.maxBy(_._2)._2\n > sweet.filter{case(h, m) => h <= x && m > 0}.maxBy(_._2)._2)\n\n var work = true\n var count = 0\n var possibleh = x\n\n while (work) {\n if (isCandy) {\n val index = candy.indices.foldLeft(-1) {\n case (-1, i) if candy(i)._1 <= possibleh && candy(i)._2 > 0 => i\n case (j, i) if candy(i)._1 <= possibleh && j > 0 && candy(i)._2 > candy(j)._2 => i\n case (j, i) => j\n }\n work = index != -1\n\n if (work) {\n possibleh += candy(index)._2\n candy(index) = (0, 0)\n }\n\n } else {\n val index = sweet.indices.foldLeft(-1) {\n case (-1, i) if sweet(i)._1 <= possibleh && sweet(i)._2 > 0 => i\n case (j, i) if sweet(i)._1 <= possibleh && j > 0 && sweet(i)._2 > sweet(j)._2 => i\n case (j, i) => j\n }\n work = index != -1\n if (work) {\n possibleh += sweet(index)._2\n sweet(index) = (0, 0)\n }\n }\n if (work) count += 1\n isCandy = !isCandy\n }\n println(count)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, x) = in.next().split(' ').map(_.toInt)\n \n \n val (sweetl, candyl) = (1 to n).foldLeft((List.empty[(Int, Int)], List.empty[(Int, Int)])) {\n case ((s, c), _) =>\n\n val Array(t, h, m) = in.next().split(' ').map(_.toInt)\n t match {\n case 0 => (s, (h, m) :: c)\n case _ => ((h, m) :: s, c)\n }\n }\n \n def calc(isCandyl: Boolean): Int = {\n val sweet = sweetl.toArray\n val candy = candyl.toArray\n var work = true\n var count = 0\n var possibleh = x\n var isCandy = isCandyl\n\n while (work) {\n if (isCandy) {\n val index = candy.indices.foldLeft(-1) {\n case (-1, i) if candy(i)._1 <= possibleh && candy(i)._2 > 0 => i\n case (j, i) if candy(i)._1 <= possibleh && j > 0 && candy(i)._2 > candy(j)._2 => i\n case (j, i) => j\n }\n work = index != -1\n\n if (work) {\n possibleh += candy(index)._2\n candy(index) = (0, 0)\n }\n\n } else {\n val index = sweet.indices.foldLeft(-1) {\n case (-1, i) if sweet(i)._1 <= possibleh && sweet(i)._2 > 0 => i\n case (j, i) if sweet(i)._1 <= possibleh && j > 0 && sweet(i)._2 > sweet(j)._2 => i\n case (j, i) => j\n }\n work = index != -1\n if (work) {\n possibleh += sweet(index)._2\n sweet(index) = (0, 0)\n }\n }\n if (work) count += 1\n isCandy = !isCandy\n }\n count\n }\n \n println(Math.max(calc(true), calc(false)))\n}\n"}], "src_uid": "6253f6217c58a66573b1ddc6962c372c"} {"source_code": "\nobject E3{\n def main(args: Array[String]){\n import scala.collection.mutable.PriorityQueue\n import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n// var in=io.Source.stdin.getLines()\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n val n=nextInt\n\n val m=nextInt\n val U=new Array[Int](m)\n val V=new Array[Int](m)\n val W=new Array[Long](m)\n for(i <- 0 until m)\n {\n U(i)=nextInt\n V(i)=nextInt\n W(i)=nextLong\n }\n\n var edgeof =Array.fill(n+1)(new ArrayBuffer[(Int,Long)]())\n for(i<-0 until U.length){\n edgeof(U(i))+=((V(i),W(i)));\n edgeof(V(i))+=((U(i),W(i)));\n }\n val d=Array.fill(n+1)(Long.MaxValue)\n val u0=nextInt\n val q = new PriorityQueue[(Long,Int)]()(Ordering.by((t:(Long,Int))=> -t._1))\n\n d(u0)=0\n q.enqueue((d(u0),u0))\n val mark=Array.fill(n+1)(false)\n while(!q.isEmpty){\n breakable{\n val u=q.dequeue._2\n if(mark(u)){\n break\n }\n mark(u)=true\n for(p<-edgeof(u)){\n if(d(p._1)>d(u)+p._2){\n d(p._1)=d(u)+p._2\n q.enqueue((d(p._1),p._1))\n }\n }\n }\n }\n\n var sum=0L\n val selectedEdge=Array.fill(n+1)(-1)\n for(i<-0 until U.length){\n if(d(U(i))==d(V(i))+W(i) && (selectedEdge(U(i))== -1 || (W(selectedEdge(U(i)))>W(i)))){\n selectedEdge(U(i))=i\n\n }\n if(d(V(i))==d(U(i))+W(i) && (selectedEdge(V(i))== -1 || (W(selectedEdge(V(i))))>W(i))){\n selectedEdge(V(i))=i\n\n }\n\n }\n\n\n for(i<-1 to n if i != u0){ sum+=W(selectedEdge(i))}\n out.println(sum)\n for(i<-1 to n if i != u0){ out.print((selectedEdge(i)+1)+\" \")}\n out.println()\n out.flush\n out.close\n\n }\n}\n", "positive_code": [{"source_code": "\nobject E3{\n def main(args: Array[String]){\n import scala.collection.mutable.PriorityQueue\n import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n// var in=io.Source.stdin.getLines()\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n val n=nextInt\n\n val m=nextInt\n val U=new Array[Int](m)\n val V=new Array[Int](m)\n val W=new Array[Long](m)\n for(i <- 0 until m)\n {\n U(i)=nextInt\n V(i)=nextInt\n W(i)=nextLong\n }\n\n var edgeof =Array.fill(n+1)(new ArrayBuffer[(Int,Long)]())\n for(i<-0 until U.length){\n edgeof(U(i))+=((V(i),W(i)));\n edgeof(V(i))+=((U(i),W(i)));\n }\n val d=Array.fill(n+1)(Long.MaxValue)\n val u0=nextInt\n val q = new PriorityQueue[(Long,Int)]()(Ordering.by((t:(Long,Int))=> -t._1))\n\n d(u0)=0\n q.enqueue((d(u0),u0))\n val mark=Array.fill(n+1)(false)\n while(!q.isEmpty){\n breakable{\n val u=q.dequeue._2\n if(mark(u)){\n break\n }\n mark(u)=true\n for(p<-edgeof(u)){\n if(d(p._1)>d(u)+p._2){\n d(p._1)=d(u)+p._2\n q.enqueue((d(p._1),p._1))\n }\n }\n }\n }\n\n var sum=0L\n val selectedEdge=Array.fill(n+1)(-1)\n for(i<-0 until U.length){\n if(d(U(i))==d(V(i))+W(i) && (selectedEdge(U(i))== -1 || (W(selectedEdge(U(i)))>W(i)))){\n selectedEdge(U(i))=i\n\n }\n if(d(V(i))==d(U(i))+W(i) && (selectedEdge(V(i))== -1 || (W(selectedEdge(V(i))))>W(i))){\n selectedEdge(V(i))=i\n\n }\n\n }\n\n\n for(i<-1 to n if i != u0){ sum+=W(selectedEdge(i))}\n out.println(sum)\n for(i<-1 to n if i != u0){ out.print((selectedEdge(i)+1)+\" \") }\n out.println()\n out.flush\n out.close\n\n }\n}\n"}, {"source_code": "import scala.collection._\nimport scala.math.Ordering\n\n\nobject Solution extends App {\n import ContestLib._\n val Array(n, m) = readIntArray()\n var weight = Array.fill(m){0}\n val data = Range(0, m).foldLeft(Array.fill(n)(mutable.ListBuffer.empty[(Int, Int, Int)])) {\n case(acc, el) =>\n val Array(u, v, w) = readIntArray()\n weight(el) = w\n acc(u - 1) += ((v - 1, w, el))\n acc(v - 1) += ((u - 1, w, el))\n acc\n }\n\n val visited = Array.fill(n)(false)\n val start = readInt() - 1\n var expand = data(start).foldLeft(mutable.PriorityQueue.empty[(Int, Long, Int, Int)](SecondOrdering)) {\n case (acc, (u, w, edge)) =>\n acc.enqueue((u, w, edge, weight(edge)))\n acc\n }\n visited(start) = true\n val edges = mutable.ListBuffer.empty[Int]\n val ex = Array.fill(n)(-1l)\n ex(start) = 0\n\n while (expand.nonEmpty) {\n val (u, w, edge, _) = expand.dequeue()\n if (!visited(u)) {\n visited(u) = true\n edges += edge\n data(u).foreach { case(u1, w1, edge1) =>\n if (!visited(u1))\n if (ex(u1) == -1 || ex(u1) >= w + w1){\n ex(u1) = w + w1\n expand.enqueue((u1, w + w1, edge1, weight(edge1)))\n }\n }\n }\n }\n\n val sum = edges.foldLeft(0l) {\n case(acc, el) => acc + weight(el)\n }\n\n println(sum)\n println(edges.map(_ + 1).mkString(\" \"))\n\n}\n\n\nobject ContestLib {\n import scala.io.StdIn._\n def readIntArray() = readLine().split(' ').map(_.toInt)\n def readInt() = scala.io.StdIn.readInt()\n\n def SecondOrdering[T1, T2, T3, T4](implicit ord1: Ordering[T1],\n ord2: Ordering[T2],\n ord3: Ordering[T3],\n ord4: Ordering[T4]\n ): Ordering[(T1, T2, T3, T4)] =\n new Ordering[(T1, T2, T3, T4)]{\n def compare(x: (T1, T2, T3, T4), y: (T1, T2, T3, T4)): Int = {\n var res = -ord2.compare(x._2, y._2)\n if (res == 0)\n res = -ord4.compare(x._4, y._4)\n res\n }\n\n }\n}\n\n"}, {"source_code": "\nobject E3{\n def main(args: Array[String]){\n import scala.collection.mutable.PriorityQueue\n import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n// var in=io.Source.stdin.getLines()\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n val n=nextInt\n\n val m=nextInt\n val U=new Array[Int](m)\n val V=new Array[Int](m)\n val W=new Array[Long](m)\n for(i <- 0 until m)\n {\n U(i)=nextInt\n V(i)=nextInt\n W(i)=nextLong\n }\n\n var edgeof =Array.fill(n+1)(new ArrayBuffer[(Int,Long)]())\n for(i<-0 until U.length){\n edgeof(U(i))+=((V(i),W(i)));\n edgeof(V(i))+=((U(i),W(i)));\n }\n val d=Array.fill(n+1)(Long.MaxValue)\n val u0=nextInt\n val q = new PriorityQueue[(Long,Int)]()(Ordering.by((t:(Long,Int))=> -t._1))\n\n d(u0)=0\n q.enqueue((d(u0),u0))\n val mark=Array.fill(n+1)(false)\n while(!q.isEmpty){\n breakable{\n val u=q.dequeue._2\n if(mark(u)){\n break\n }\n mark(u)=true\n for(p<-edgeof(u)){\n if(d(p._1)>d(u)+p._2){\n d(p._1)=d(u)+p._2\n q.enqueue((d(p._1),p._1))\n }\n }\n }\n }\n\n var sum=0L\n val selectedEdge=Array.fill(n+1)(-1)\n for(i<-0 until U.length){\n if(d(U(i))==d(V(i))+W(i) && (selectedEdge(U(i))== -1 || (W(selectedEdge(U(i)))>W(i)))){\n selectedEdge(U(i))=i\n\n }\n if(d(V(i))==d(U(i))+W(i) && (selectedEdge(V(i))== -1 || (W(selectedEdge(V(i))))>W(i))){\n selectedEdge(V(i))=i\n\n }\n\n }\n\n\n for(i<-1 to n if i != u0){ sum+=W(selectedEdge(i))}\n out.println(sum)\n for(i<-1 to n if i != u0){ out.print((selectedEdge(i)+1));out.print(\" \") }\n out.println()\n out.flush\n out.close\n\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection._\nimport scala.math.Ordering\n\n\nobject Solution extends App {\n import ContestLib._\n val Array(n, m) = readIntArray()\n var weight = Array.fill(m){0}\n val data = Range(0, m).foldLeft(Array.fill(n)(mutable.ListBuffer.empty[(Int, Int, Int)])) {\n case(acc, el) =>\n val Array(u, v, w) = readIntArray()\n weight(el) = w\n acc(u - 1) += ((v - 1, w, el))\n acc(v - 1) += ((u - 1, w, el))\n acc\n }\n\n val visited = Array.fill(n)(false)\n val start = readInt() - 1\n var expand = data(start).foldLeft(mutable.PriorityQueue.empty[(Int, Long, Int, Int)](SecondOrdering)) {\n case (acc, (u, w, edge)) =>\n acc.enqueue((u, w, edge, weight(edge)))\n acc\n }\n visited(start) = true\n val edges = mutable.ListBuffer.empty[Int]\n val ex = Array.fill(n)(-1l)\n ex(start) = 0\n\n while (expand.nonEmpty) {\n val (u, w, edge, _) = expand.dequeue()\n if (!visited(u)) {\n visited(u) = true\n edges += edge\n data(u).foreach { case(u1, w1, edge1) =>\n if (!visited(u1))\n if (ex(u1) == -1 || ex(u1) >= w + w1){\n ex(u1) = w + w1\n expand.enqueue((u1, w + w1, edge1, weight(edge1)))\n }\n }\n }\n }\n\n val sum = edges.foldLeft(0) {\n case(acc, el) => acc + weight(el)\n }\n\n println(sum)\n println(edges.mkString(\" \"))\n\n}\n\n\nobject ContestLib {\n import scala.io.StdIn._\n def readIntArray() = readLine().split(' ').map(_.toInt)\n def readInt() = scala.io.StdIn.readInt()\n\n def SecondOrdering[T1, T2, T3, T4](implicit ord1: Ordering[T1],\n ord2: Ordering[T2],\n ord3: Ordering[T3],\n ord4: Ordering[T4]\n ): Ordering[(T1, T2, T3, T4)] =\n new Ordering[(T1, T2, T3, T4)]{\n def compare(x: (T1, T2, T3, T4), y: (T1, T2, T3, T4)): Int = {\n var res = -ord2.compare(x._2, y._2)\n if (res == 0)\n res = -ord4.compare(x._4, y._4)\n res\n }\n\n }\n}\n\n"}, {"source_code": "import scala.collection._\nimport scala.math.Ordering\n\n\nobject Solution extends App {\n import ContestLib._\n val Array(n, m) = readIntArray()\n var weight = Array.fill(m){0}\n val data = Range(0, m).foldLeft(Array.fill(n)(mutable.ListBuffer.empty[(Int, Int, Int)])) {\n case(acc, el) =>\n val Array(u, v, w) = readIntArray()\n weight(el) = w\n acc(u - 1) += ((v - 1, w, el))\n acc(v - 1) += ((u - 1, w, el))\n acc\n }\n\n val visited = Array.fill(n)(false)\n val start = readInt() - 1\n var expand = data(start).foldLeft(mutable.PriorityQueue.empty[(Int, Long, Int, Int)](SecondOrdering)) {\n case (acc, (u, w, edge)) =>\n acc.enqueue((u, w, edge, weight(edge)))\n acc\n }\n visited(start) = true\n val edges = mutable.ListBuffer.empty[Int]\n val ex = Array.fill(n)(-1l)\n ex(start) = 0\n\n while (expand.nonEmpty) {\n val (u, w, edge, _) = expand.dequeue()\n if (!visited(u)) {\n visited(u) = true\n edges += (edge + 1)\n data(u).foreach { case(u1, w1, edge1) =>\n if (!visited(u1))\n if (ex(u1) == -1 || ex(u1) >= w + w1){\n ex(u1) = w + w1\n expand.enqueue((u1, w + w1, edge1, weight(edge1)))\n }\n }\n }\n }\n\n val sum = edges.foldLeft(0) {\n case(acc, el) => acc + weight(el)\n }\n\n println(sum)\n println(edges.mkString(\" \"))\n\n}\n\n\nobject ContestLib {\n import scala.io.StdIn._\n def readIntArray() = readLine().split(' ').map(_.toInt)\n def readInt() = scala.io.StdIn.readInt()\n\n def SecondOrdering[T1, T2, T3, T4](implicit ord1: Ordering[T1],\n ord2: Ordering[T2],\n ord3: Ordering[T3],\n ord4: Ordering[T4]\n ): Ordering[(T1, T2, T3, T4)] =\n new Ordering[(T1, T2, T3, T4)]{\n def compare(x: (T1, T2, T3, T4), y: (T1, T2, T3, T4)): Int = {\n var res = -ord2.compare(x._2, y._2)\n if (res == 0)\n res = -ord4.compare(x._4, y._4)\n res\n }\n\n }\n}\n\n"}, {"source_code": "import scala.collection._\nimport scala.math.Ordering\n\n\nobject Solution extends App {\n import ContestLib._\n val Array(n, m) = readIntArray()\n var weight = Map.empty[Int, Int]\n val data = Range(1, m + 1).foldLeft(Array.fill(n)(mutable.Set.empty[(Int, Int, Int)])) {\n case(acc, el) =>\n val Array(u, v, w) = readIntArray()\n weight += (el -> w)\n acc(u - 1) += ((v - 1, w, el))\n acc(v - 1) += ((u - 1, w, el))\n acc\n }\n val visited = Array.fill(n)(false)\n val start = readInt()\n var expand = data(0).foldLeft(mutable.PriorityQueue.empty[(Int, Int, Int)](SecondOrdering)) {\n case (acc, (u, w, edge)) =>\n acc.enqueue((u, w, edge))\n acc\n }\n visited(0) = true\n var edges = Set.empty[Int]\n\n while (expand.nonEmpty) {\n val (u, w, edge) = expand.dequeue()\n if (!visited(u)) {\n visited(u) = true\n edges += edge\n data(u).foreach { case(u1, w1, edge1) =>\n if (!visited(u1)) expand.enqueue((u1, w + w1, edge1))\n }\n }\n }\n\n val sum = edges.foldLeft(0) {\n case(acc, el) => acc + weight(el)\n }\n\n println(sum)\n println(edges.mkString(\" \"))\n\n}\n\n\nobject ContestLib {\n import scala.io.StdIn._\n def readIntArray() = readLine().split(' ').map(_.toInt)\n def readInt() = scala.io.StdIn.readInt()\n\n def SecondOrdering[T1, T2, T3](implicit ord1: Ordering[T1],\n ord2: Ordering[T2],\n ord3: Ordering[T3]\n ): Ordering[(T1, T2, T3)] =\n new Ordering[(T1, T2, T3)]{\n def compare(x: (T1, T2, T3), y: (T1, T2, T3)): Int =\n -ord2.compare(x._2, y._2)\n\n }\n}\n\n"}, {"source_code": "import scala.collection._\nimport scala.math.Ordering\n\n\nobject Solution extends App {\n import ContestLib._\n val Array(n, m) = readIntArray()\n var weight = Array.fill(m){0}\n val data = Range(0, m).foldLeft(Array.fill(n)(mutable.ListBuffer.empty[(Int, Int, Int)])) {\n case(acc, el) =>\n val Array(u, v, w) = readIntArray()\n weight(el) = w\n acc(u - 1) += ((v - 1, w, el))\n acc(v - 1) += ((u - 1, w, el))\n acc\n }\n\n val visited = Array.fill(n)(false)\n val start = readInt() - 1\n var expand = data(start).foldLeft(mutable.PriorityQueue.empty[(Int, Long, Int, Int)](SecondOrdering)) {\n case (acc, (u, w, edge)) =>\n acc.enqueue((u, w, edge, weight(edge)))\n acc\n }\n visited(start) = true\n val edges = mutable.ListBuffer.empty[Int]\n val ex = Array.fill(n)(-1l)\n ex(start) = 0\n\n while (expand.nonEmpty) {\n val (u, w, edge, _) = expand.dequeue()\n if (!visited(u)) {\n visited(u) = true\n edges += edge\n data(u).foreach { case(u1, w1, edge1) =>\n if (!visited(u1))\n if (ex(u1) == -1 || ex(u1) >= w + w1){\n ex(u1) = w + w1\n expand.enqueue((u1, w + w1, edge1, weight(edge1)))\n }\n }\n }\n }\n\n val sum = edges.foldLeft(0) {\n case(acc, el) => acc + weight(el)\n }\n\n println(sum)\n println(edges.map(_ + 1).mkString(\" \"))\n\n}\n\n\nobject ContestLib {\n import scala.io.StdIn._\n def readIntArray() = readLine().split(' ').map(_.toInt)\n def readInt() = scala.io.StdIn.readInt()\n\n def SecondOrdering[T1, T2, T3, T4](implicit ord1: Ordering[T1],\n ord2: Ordering[T2],\n ord3: Ordering[T3],\n ord4: Ordering[T4]\n ): Ordering[(T1, T2, T3, T4)] =\n new Ordering[(T1, T2, T3, T4)]{\n def compare(x: (T1, T2, T3, T4), y: (T1, T2, T3, T4)): Int = {\n var res = -ord2.compare(x._2, y._2)\n if (res == 0)\n res = -ord4.compare(x._4, y._4)\n res\n }\n\n }\n}\n\n"}, {"source_code": "import scala.collection._\nimport scala.math.Ordering\n\n\nobject Solution extends App {\n import ContestLib._\n val Array(n, m) = readIntArray()\n var weight = Map.empty[Int, Int]\n val data = Range(1, m + 1).foldLeft(Array.fill(n)(mutable.Set.empty[(Int, Int, Int)])) {\n case(acc, el) =>\n val Array(u, v, w) = readIntArray()\n weight += (el -> w)\n acc(u - 1) += ((v - 1, w, el))\n acc(v - 1) += ((u - 1, w, el))\n acc\n }\n\n val visited = Array.fill(n)(false)\n val start = readInt() - 1\n var expand = data(start).foldLeft(mutable.PriorityQueue.empty[(Int, Int, Int, Int)](SecondOrdering)) {\n case (acc, (u, w, edge)) =>\n acc.enqueue((u, w, edge, weight(edge)))\n acc\n }\n visited(start) = true\n val edges = mutable.ListBuffer.empty[Int]\n val exWeights = mutable.Map.empty[Int, Int]\n val ex = Array.fill(n)(-1)\n ex(start) = 0\n\n while (expand.nonEmpty) {\n val (u, w, edge, _) = expand.dequeue()\n if (!visited(u)) {\n visited(u) = true\n edges += edge\n data(u).foreach { case(u1, w1, edge1) =>\n if (!visited(u1) && (ex(u1) == -1 || ex(u1) > w + w1)) {\n ex(u1) = w + w1\n expand.enqueue((u1, w + w1, edge1, weight(edge1)))\n }\n }\n }\n }\n\n val sum = edges.foldLeft(0) {\n case(acc, el) => acc + weight(el)\n }\n\n println(sum)\n println(edges.mkString(\" \"))\n\n}\n\n\nobject ContestLib {\n import scala.io.StdIn._\n def readIntArray() = readLine().split(' ').map(_.toInt)\n def readInt() = scala.io.StdIn.readInt()\n\n def SecondOrdering[T1, T2, T3, T4](implicit ord1: Ordering[T1],\n ord2: Ordering[T2],\n ord3: Ordering[T3],\n ord4: Ordering[T4]\n ): Ordering[(T1, T2, T3, T4)] =\n new Ordering[(T1, T2, T3, T4)]{\n def compare(x: (T1, T2, T3, T4), y: (T1, T2, T3, T4)): Int = {\n val res = -ord2.compare(x._2, y._2)\n if (res == 0)\n return -ord4.compare(x._4, y._4)\n res\n }\n\n }\n}\n\n"}, {"source_code": "import scala.collection._\n\n\nobject Solution extends App {\n import ContestLib._\n val Array(n, m) = readIntArray()\n var weight = Map.empty[Int, Int]\n val data = Range(1, m + 1).foldLeft(Array.fill(n)(mutable.Set.empty[(Int, Int, Int)])) {\n case(acc, el) =>\n val Array(u, v, w) = readIntArray()\n weight += (el -> w)\n acc(u - 1) += ((v - 1, w, el))\n acc(v - 1) += ((u - 1, w, el))\n acc\n }\n val visited = Array.fill(n)(false)\n val start = readInt()\n var expand = data(0).foldLeft(SortedMap.empty[Int, (Int, Int)]) {\n case (acc, (u, w, edge)) => acc + (u -> (w, edge))\n }\n visited(0) = true\n var edges = Set.empty[Int]\n\n while (expand.nonEmpty) {\n val (u, (w, edge)) = expand.head\n expand = expand.tail\n if (!visited(u)) {\n visited(u) = true\n edges += edge\n data(u).foreach { case(u1, w1, edge1) =>\n if (!visited.contains(u1) || (!expand.contains(u1) || (expand(u1)._1 > w + w1))) {\n expand += (u1 -> (w + w1, edge1))\n }\n }\n }\n }\n\n val sum = edges.foldLeft(0) {\n case(acc, el) => acc + weight(el)\n }\n\n println(sum)\n println(edges.mkString(\" \"))\n\n}\n\nobject ContestLib {\n import scala.io.StdIn._\n def readIntArray() = readLine().split(' ').map(_.toInt)\n def readInt() = scala.io.StdIn.readInt()\n}"}, {"source_code": "import scala.collection._\nimport scala.math.Ordering\n\n\nobject Solution extends App {\n import ContestLib._\n val Array(n, m) = readIntArray()\n var weight = Map.empty[Int, Int]\n val data = Range(1, m + 1).foldLeft(Array.fill(n)(mutable.Set.empty[(Int, Int, Int)])) {\n case(acc, el) =>\n val Array(u, v, w) = readIntArray()\n weight += (el -> w)\n acc(u - 1) += ((v - 1, w, el))\n acc(v - 1) += ((u - 1, w, el))\n acc\n }\n val visited = Array.fill(n)(false)\n val start = readInt()\n var expand = data(0).foldLeft(mutable.PriorityQueue.empty[(Int, Int, Int)](SecondOrdering)) {\n case (acc, (u, w, edge)) =>\n acc += ((u, w, edge))\n }\n visited(0) = true\n var edges = Set.empty[Int]\n\n while (expand.nonEmpty) {\n val (u, w, edge) = expand.head\n expand = expand.tail\n if (!visited(u)) {\n visited(u) = true\n edges += edge\n data(u).foreach { case(u1, w1, edge1) =>\n if (!visited.contains(u1)) expand += ((u1, w + w1, edge1))\n }\n }\n }\n\n val sum = edges.foldLeft(0) {\n case(acc, el) => acc + weight(el)\n }\n\n println(sum)\n println(edges.mkString(\" \"))\n\n}\n\n\nobject ContestLib {\n import scala.io.StdIn._\n def readIntArray() = readLine().split(' ').map(_.toInt)\n def readInt() = scala.io.StdIn.readInt()\n\n def SecondOrdering[T1, T2, T3](implicit ord1: Ordering[T1],\n ord2: Ordering[T2],\n ord3: Ordering[T3]\n ): Ordering[(T1, T2, T3)] =\n new Ordering[(T1, T2, T3)]{\n def compare(x: (T1, T2, T3), y: (T1, T2, T3)): Int = {\n val compare2 = ord2.compare(x._2, y._2)\n if (compare2 != 0) return compare2\n 0\n }\n\n }\n}\n\n"}, {"source_code": "\nobject E{\n object Edge {\n def apply(s:String): Edge={\n val t=s.split(\" \")\n Edge(u=t(0).toInt,v=t(1).toInt,w=t(2).toInt)\n }\n }\n case class Edge(u: Int, v: Int, w: Int)\n def main(args: Array[String]){\n \n import scala.collection.mutable.ArrayBuffer\n var in=io.Source.stdin.getLines()\n val t=in.next().split(\" \")\n val n=t(0).toInt\n val m=t(1).toInt\n val edge={for(_<-1 to m) yield Edge(in.next())}.toArray\n\n var edgeof =Array.fill(n+1)(new ArrayBuffer[Int]())\n for(i<-0 until edge.length){\n edgeof(edge(i).u)+=i;\n edgeof(edge(i).v)+=i;\n }\n val d=Array.fill(n+1)(Int.MaxValue)\n val u0=in.next().toInt\n val q = new scala.collection.mutable.Queue[Int]\n val selectedEdge=Array.fill(n+1)(-1)\n q+=u0\n d(u0)=0\n\n while(!q.isEmpty){\n val u=q.dequeue\n for(i<-edgeof(u)){\n var p=edge(i).u\n if(u==p){\n p=edge(i).v\n }\n if(d(p)>d(u)+edge(i).w){\n d(p)=d(u)+edge(i).w\n if(!q.exists(_ == p)){\n q+=p\n }\n selectedEdge(p)=i\n }\n else if(d(p)==d(u)+edge(i).w){\n if(edge(selectedEdge(p)).w>edge(i).w){\n selectedEdge(p)=i\n }\n }\n }\n }\n var sum=0\n for(i<-1 until n if i != u0){ sum+=edge(selectedEdge(i)).w}\n println(sum)\n for(i<-1 until n if i != u0){ print(selectedEdge(i)+1);print (' ')}\n }\n}\n"}, {"source_code": "object E{\n def main(args: Array[String]){\n println(\"good here\")\n }\n}\n"}, {"source_code": "object Etest{\n case class Edge(u: Int, v: Int, w: Int)\n\nobject Edge {\n def apply(s:String): Edge={\n val t=s.split(\" \")\n Edge(u=t(0).toInt,v=t(1).toInt,w=t(2).toInt)\n }\n}\n\n\n\n def main(args: Array[String]){\n println(\"good here\")\n }\n}\n"}, {"source_code": "\nobject E2{\n object Edge {\n def apply(s:String): Edge={\n val t=s.split(\" \")\n Edge(u=t(0).toInt,v=t(1).toInt,w=t(2).toInt)\n }\n }\n case class Edge(u: Int, v: Int, w: Int)\n def main(args: Array[String]){\n import scala.collection.mutable.PriorityQueue\n import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n var in=io.Source.stdin.getLines()\n val t=in.next().split(\" \")\n\n val n=t(0).toInt\n\n val m=t(1).toInt\n val edge={for(_<-1 to m) yield Edge(in.next())}.toArray\n\n var edgeof =Array.fill(n+1)(new ArrayBuffer[(Int,Int,Int)]())\n for(i<-0 until edge.length){\n edgeof(edge(i).u)+=((edge(i).v,i,edge(i).w));\n edgeof(edge(i).v)+=((edge(i).u,i,edge(i).w));\n }\n val d=Array.fill(n+1)(Int.MaxValue)\n val u0=in.next().toInt\n val q = new PriorityQueue[(Int,Int)]()(Ordering.by((t:(Int,Int))=> t._1))\n val selectedEdge=Array.fill(n+1)(-1)\n\n d(u0)=0\n q.enqueue((d(u0),u0))\n val mark=Array.fill(n+1)(false)\n while(!q.isEmpty){\n breakable{\n val u=q.dequeue._2\n if(mark(u)){\n break\n }\n mark(u)=true\n for(p<-edgeof(u)){\n if(d(p._1)>d(u)+p._3){\n d(p._1)=d(u)+p._3\n q.enqueue((d(p._1),p._1))\n selectedEdge(p._1)=p._2\n }\n }\n }\n }\n for(i<-0 until edge.length){\n val e=edge(i)\n if(d(e.u)==d(e.v)+e.w && edge(selectedEdge(e.u)).w>e.w){\n selectedEdge(e.u)=i\n\n }\n if(d(e.v)==d(e.u)+e.w && edge(selectedEdge(e.v)).w>e.w){\n selectedEdge(e.v)=i\n\n }\n\n }\n var sum=0\n\n for(i<-1 to n if i != u0){ sum+=edge(selectedEdge(i)).w}\n println(sum)\n for(i<-1 to n if i != u0){ print(selectedEdge(i)+1);print (' ')}\n }\n}\n"}, {"source_code": "\nobject E3{\n def main(args: Array[String]){\n import scala.collection.mutable.PriorityQueue\n import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n// var in=io.Source.stdin.getLines()\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n val n=nextInt\n\n val m=nextInt\n val U=new Array[Int](m)\n val V=new Array[Int](m)\n val W=new Array[Long](m)\n for(i <- 0 until m)\n {\n U(i)=nextInt\n V(i)=nextInt\n W(i)=nextLong\n }\n\n var edgeof =Array.fill(n+1)(new ArrayBuffer[(Int,Long)]())\n for(i<-0 until U.length){\n edgeof(U(i))+=((V(i),W(i)));\n edgeof(V(i))+=((U(i),W(i)));\n }\n val d=Array.fill(n+1)(Long.MaxValue)\n val u0=nextInt\n val q = new PriorityQueue[(Long,Int)]()(Ordering.by((t:(Long,Int))=> -t._1))\n\n d(u0)=0\n q.enqueue((d(u0),u0))\n val mark=Array.fill(n+1)(false)\n while(!q.isEmpty){\n breakable{\n val u=q.dequeue._2\n if(mark(u)){\n break\n }\n mark(u)=true\n for(p<-edgeof(u)){\n if(d(p._1)>d(u)+p._2){\n d(p._1)=d(u)+p._2\n q.enqueue((d(p._1),p._1))\n }\n }\n }\n }\n\n var sum=0L\n val selectedEdge=Array.fill(n+1)(-1)\n for(i<-0 until U.length){\n if(d(U(i))==d(V(i))+W(i) && (selectedEdge(U(i))== -1 || (W(selectedEdge(U(i)))>W(i)))){\n selectedEdge(U(i))=i\n\n }\n if(d(V(i))==d(U(i))+W(i) && (selectedEdge(V(i))== -1 || (W(selectedEdge(V(i))))>W(i))){\n selectedEdge(V(i))=i\n\n }\n\n }\n\n\n for(i<-1 to n if i != u0){ sum+=W(selectedEdge(i))}\n out.println(sum)\n for(i<-1 to n if i != u0){ print((selectedEdge(i)+1)+\" \") }\n out.println()\n out.flush\n out.close\n\n }\n}\n"}, {"source_code": "\nobject E3{\n def main(args: Array[String]){\n import scala.collection.mutable.PriorityQueue\n import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n// var in=io.Source.stdin.getLines()\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n val n=nextInt\n\n val m=nextInt\n val U=new Array[Int](m)\n val V=new Array[Int](m)\n val W=new Array[Long](m)\n for(i <- 0 until m)\n {\n U(i)=nextInt\n V(i)=nextInt\n W(i)=nextLong\n }\n\n var edgeof =Array.fill(n+1)(new ArrayBuffer[(Int,Long)]())\n for(i<-0 until U.length){\n edgeof(U(i))+=((V(i),W(i)));\n edgeof(V(i))+=((U(i),W(i)));\n }\n val d=Array.fill(n+1)(Long.MaxValue)\n val u0=nextInt\n val q = new PriorityQueue[(Long,Int)]()(Ordering.by((t:(Long,Int))=> -t._1))\n\n d(u0)=0\n q.enqueue((d(u0),u0))\n val mark=Array.fill(n+1)(false)\n while(!q.isEmpty){\n breakable{\n val u=q.dequeue._2\n if(mark(u)){\n break\n }\n mark(u)=true\n for(p<-edgeof(u)){\n if(d(p._1)>d(u)+p._2){\n d(p._1)=d(u)+p._2\n q.enqueue((d(p._1),p._1))\n }\n }\n }\n }\n\n var sum=0L\n val selectedEdge=Array.fill(n+1)(-1)\n for(i<-0 until U.length){\n if(d(U(i))==d(V(i))+W(i) && (selectedEdge(U(i))== -1 || (W(selectedEdge(U(i)))>W(i)))){\n selectedEdge(U(i))=i\n\n }\n if(d(V(i))==d(U(i))+W(i) && (selectedEdge(V(i))== -1 || (W(selectedEdge(V(i))))>W(i))){\n selectedEdge(V(i))=i\n\n }\n\n }\n\n\n for(i<-1 to n if i != u0){ sum+=W(selectedEdge(i))}\n out.println(sum)\n for(i<-1 to n if i != u0){ out.print((selectedEdge(i)+1)+' ')}\n out.println()\n\n }\n}\n"}], "src_uid": "2232f2a26cb8ff71c1cda10ca0b73bbc"} {"source_code": "object A1139 {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val n = stdin.readInt()\n val str = stdin.readLine()\n var ans = 0L\n for (i <- 0 until n){\n val temp = str(i) - '0'\n if (temp % 2 == 0){\n ans = ans + (i+1)\n }\n }\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "//package codeforces.contest1139\n\nobject EvenSubstrings {\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val string = io.StdIn.readLine()\n\n println(string.map(_ - '0').zipWithIndex.filter(_._1 % 2 == 0).map(_._2 + 1).sum)\n }\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n import java.util.Arrays\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val S = ns(N)\n var ans = 0L\n REP(N) { i =>\n if ((S(i) - '0') % 2 == 0) ans += i + 1\n }\n out.println(ans)\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject A1139 {\n def main(args: Array[String]): Unit = {\n StdIn.readLine\n println(StdIn.readLine.zipWithIndex.withFilter{i=>\"2468\".contains(i._1)}.map{_._2 + 1}.sum)\n }\n}\n"}, {"source_code": "object A1139 {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val n = stdin.readInt()\n val str = stdin.readLine().map(x => x -'0').map(_ & 1)\n var ans = 0L\n for (i <- 0 until n if str(i) == 0){\n ans = ans + (i+1)\n }\n println(ans)\n }\n}"}, {"source_code": "object _1139A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val _, s = io.read[String]\n\n val ans = s.toCharArray\n .map(_ - '0')\n .zipWithIndex\n .collect({case (c, i) if c%2 == 0 => i + 1 })\n .sum\n\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "43a65d1cfe59931991b6aefae1ecd10e"} {"source_code": "object B extends App {\r\n\r\n def hemoseShopping(an: IndexedSeq[Int], x: Int): Boolean = {\r\n val n = an.length\r\n val (i, j) = (n - x, x - 1)\r\n\r\n val am = an.slice(i, j + 1)\r\n\r\n am.isEmpty || {\r\n val as = (an.slice(0, i) ++ an.slice(j + 1, n)).sorted\r\n val (al, ar) = (as.slice(0, i), as.slice(i, n))\r\n\r\n an.sorted sameElements (al ++ am ++ ar)\r\n }\r\n\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val x = nextInt()\r\n val an = nextInts(n)\r\n\r\n hemoseShopping(an, x) match {\r\n case true => out.println(\"YES\")\r\n case false => out.println(\"NO\")\r\n }\r\n }\r\n\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n", "positive_code": [{"source_code": "object B extends App {\r\n\r\n def hemoseShopping(an: IndexedSeq[Int], x: Int): Boolean = {\r\n val bn = an.sorted\r\n\r\n ((an.length - x) until x).forall(i => an(i) == bn(i))\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val x = nextInt()\r\n val an = nextInts(n)\r\n\r\n hemoseShopping(an, x) match {\r\n case true => out.println(\"YES\")\r\n case false => out.println(\"NO\")\r\n }\r\n }\r\n\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(var social: Int, var cp: Int, var ind: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (social < that.social)\n return -1\n else if (social == that.social)\n return 0\n else\n return 1\n }\n }\n\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val k = readInt()\n var cnt = max(0, min(k, n) - max(n-k+1, 1) + 1)\n val arr = new Array[Int](n - cnt)\n var mx = 0\n var mn = (1e9+1).toInt\n cnt = 0\n var tmp = 0\n var flag = true\n for (i <- 1 to n) {\n tmp = readInt()\n if (i >= max(n-k+1, 1) && i <= min(k, n)) {\n if(mx > tmp)\n flag = false\n mx = max(mx, tmp)\n mn = min(mn, tmp)\n } else {\n arr(cnt) = tmp\n cnt += 1\n }\n }\n quickSort(arr)\n if (arr.length > 0) {\n if (arr(arr.length/2-1) > mn)\n flag = false\n if (arr(arr.length/2) < mx)\n flag = false\n }\n if (flag) {\n writer.println(\"YES\")\n } else {\n writer.println(\"NO\")\n }\n }\n writer.flush()\n}\n"}], "negative_code": [{"source_code": "object B extends App {\r\n\r\n def hemoseShopping(an: IndexedSeq[Int], x: Int): Boolean = {\r\n val as = an.slice(an.length - x, x)\r\n as.indices.drop(1).forall(i => as(i - 1) <= as(i))\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val x = nextInt()\r\n val an = nextInts(n)\r\n\r\n hemoseShopping(an, x) match {\r\n case true => out.println(\"YES\")\r\n case false => out.println(\"NO\")\r\n }\r\n }\r\n\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(var social: Int, var cp: Int, var ind: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (social < that.social)\n return -1\n else if (social == that.social)\n return 0\n else\n return 1\n }\n }\n\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val k = readInt()\n val arr = new Array[Int](n + 1)\n for (i <- 1 to n)\n arr(i) = readInt()\n var mx = 0\n var flag = true\n for (i <- max(n-k+1, 1) to min(k, n)) {\n if (mx > arr(i))\n flag = false\n mx = max(mx, arr(i))\n }\n if (flag) {\n writer.println(\"YES\")\n } else {\n writer.println(\"NO\")\n }\n }\n writer.flush()\n}\n"}], "src_uid": "1305b44c5c588221bc991c696a492fe7"} {"source_code": "/**\n * infm, 4/24/14.\n * enjoy ;)\n */\nobject A {\n val in = {\n val lines = {\n scala.io.Source.stdin.getLines.buffered\n //val bf = new BufferedReader(new InputStreamReader(System.in))\n //Iterator.continually(readLine)\n //Iterator.continually(bf.readLine)\n }\n lines map (_ split ' ') filter (_.nonEmpty) flatten\n }\n\n //val out = new PrintWriter(System.out)\n\n def nextInt = in.next().toInt\n\n def nextLong = in.next().toLong\n\n def main(args: Array[String]) {\n val n = nextInt\n val k = nextInt\n val s = in.next\n var i = k\n if (k > n - k){\n while (i < n){\n println(\"RIGHT\")\n i += 1\n }\n i -= 1\n while (i >= 0){\n println(\"PRINT \" + s.charAt(i))\n if (i > 0)\n println(\"LEFT\")\n i -= 1\n }\n } else {\n i -= 1\n while (i > 0){\n println(\"LEFT\")\n i -= 1\n }\n while (i < n){\n println(\"PRINT \" + s.charAt(i))\n if (i < n - 1)\n println(\"RIGHT\")\n i += 1\n }\n }\n }\n}\n", "positive_code": [{"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, k) = readInts(2)\n val s = readLine\n \n val dir0 = if (k < (n - k + 1)) -1 else 1\n var i = k\n\n println(s\"PRINT ${s(i - 1)}\")\n\n while (i + dir0 > 0 && i + dir0 <= n) {\n println(if (dir0 < 0) \"LEFT\" else \"RIGHT\")\n i += dir0\n println(s\"PRINT ${s(i - 1)}\")\n }\n \n \n //if (k == 1 || k == n) exit\n \n val dir1 = -dir0\n //if (i != k) i += dir1\n \n while (i != k) {\n println(if (dir1 < 0) \"LEFT\" else \"RIGHT\")\n i += dir1\n }\n\n while (i + dir1 > 0 && i + dir1 <= n) {\n println(if (dir1 < 0) \"LEFT\" else \"RIGHT\")\n i += dir1\n println(s\"PRINT ${s(i - 1)}\")\n }\n \n}"}], "negative_code": [], "src_uid": "e3a03f3f01a77a1983121bab4218c39c"} {"source_code": "object B extends App {\n val n = scala.io.StdIn.readInt()\n\n (0 until n).foreach { _ =>\n val t = scala.io.StdIn.readLine()\n\n val n0 = t.count(_ == '0')\n\n val s =\n if (t.length < 3 || n0 == 0 || n0 == t.length) t\n else\n t.tail\n .foldLeft(List(t.head)) { (s, c) =>\n if (s.head != c) c :: s\n else c :: (if (c == '0') '1' else '0') :: s\n }\n .reverse\n .mkString(\"\")\n\n println(s)\n }\n}\n", "positive_code": [{"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n for (_ <- 1 to nextInt) {\n val s = nextLine\n val res = if (s.forall(_ == s.head)) s\n else \"01\" * s.length\n\n out.println(res)\n }\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object B extends App {\n val n = scala.io.StdIn.readInt()\n\n (0 until n).foreach { _ =>\n val t = scala.io.StdIn.readLine()\n\n val s =\n if (t.forall(_ == t.head)) t\n else \"01\" * t.length\n\n println(s)\n }\n}\n"}], "negative_code": [], "src_uid": "679a1e455073d3ea3856aa16516ba8ba"} {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _676C extends CodeForcesApp {\n override def apply(io: IO) = {\n val (n, k, s) = io[(Int, Int, String)]\n\n val pas, pbs = Array.ofDim[Int](n + 1)\n s.indices foreach {i =>\n pas(i + 1) = pas(i) + (s(i) == 'a').to[Int]\n pbs(i + 1) = pbs(i) + (s(i) == 'b').to[Int]\n }\n\n def isOk(l: Int, r: Int) = pas(r) - pas(l) <= k || pbs(r) - pbs(l) <= k\n val ans = twoPointer(n + 1)(isOk).map{case (x, y) => y - x}\n\n io += ans.max\n }\n\n def twoPointer(n: Int)(f: (Int, Int) => Boolean): Vector[(Int, Int)] = {\n def run(l: Int, r: Int): Vector[(Int, Int)] = r match {\n case `n` => Vector.empty\n case _ if f(l, r) => run(l, r + 1) :+ (l -> r)\n case _ => if (l < r) run(l + 1, r) else run(l, r + 1)\n }\n run(0, 0)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def array[A]: Write[Array[A]] = Write(_ mkString \" \")\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val line = in.next()\n val (at, _, _, bt, _, _) = line.indices.foldLeft((0, 0, k, 0, 0, k)) {\n case (att@(amax, acurrent, aleft, bmax, bcurrent, bleft), i) =>\n// println(att)\n val ch = line(i)\n// println(ch)\n if (ch == 'a') {\n if (bleft > 0)\n (Math.max(amax, acurrent + 1), acurrent + 1, aleft, Math.max(bmax, bcurrent + 1), bcurrent + 1, bleft - 1)\n else {\n var ni = bcurrent\n while (ni > 0 && line(i - ni) != 'a')\n ni -= 1\n// println(\"ni \" + ni)\n if (ni > 0)\n (Math.max(amax, acurrent + 1), acurrent + 1, aleft, Math.max(bmax, ni), ni, bleft)\n else\n (Math.max(amax, acurrent + 1), acurrent + 1, aleft, bmax, 0, k)\n }\n }\n else {\n if (aleft > 0)\n (Math.max(amax, acurrent + 1), acurrent + 1, aleft - 1, Math.max(bmax, bcurrent + 1), bcurrent + 1, bleft)\n else {\n// println(\"acurrent \" + acurrent)\n// println(\"i = \" + i)\n var ni = acurrent\n while (ni > 0 && line(i - ni) != 'b')\n ni -= 1\n// println(\"NI a \" + ni)\n\n if (ni > 0)\n (Math.max(amax, ni), ni, aleft, Math.max(bmax, bcurrent + 1), bcurrent + 1, bleft)\n else\n (amax, 0, k, Math.max(bmax, bcurrent + 1), bcurrent + 1, bleft)\n }\n }\n }\n println(Math.max(at, bt))\n}\n"}, {"source_code": "object C676 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n val str = read\n val charCountA = Array.fill(n+1)(0)\n val charCountB = Array.fill(n+1)(0)\n for(i <- 1 to n) {\n charCountA(i) = charCountA(i-1)\n charCountB(i) = charCountB(i-1)\n\n if(str(i-1) == 'a')\n charCountA(i) += 1\n else\n charCountB(i) += 1\n }\n\n var res = 0\n\n def lastOccuranceOrLowerBinarySearch(arr: Array[Int], i: Int, target: Int): Int = {\n var low = i+1\n var high = n\n\n while(low < high) {\n val mid = low + (high-low+1)/2\n\n if(arr(mid) > target) {\n high = mid - 1\n } else {\n low = mid\n }\n }\n low\n }\n\n for(i <- 0 until n) {\n// println(i, lastOccuranceOrLowerBinarySearch(charCountA, i, charCountA(i) + k), lastOccuranceOrLowerBinarySearch(charCountB, i, charCountB(i) + k))\n val last = math.max(\n lastOccuranceOrLowerBinarySearch(charCountA, i, charCountA(i) + k),\n lastOccuranceOrLowerBinarySearch(charCountB, i, charCountB(i) + k)\n )\n\n res = math.max(res, last-i)\n }\n\n out.println(res)\n\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _676C extends CodeForcesApp {\n override def apply(io: IO) = {\n val (n, k, s) = io[(Int, Int, String)]\n\n val pas, pbs = Array.ofDim[Int](n + 1)\n s.indices foreach {i =>\n pas(i + 1) = pas(i) + (s(i) == 'a').to[Int]\n pbs(i + 1) = pbs(i) + (s(i) == 'b').to[Int]\n }\n\n def solve(l: Int, r: Int): Int = if (r <= n) {\n if(pas(r) - pas(l) <= k || pbs(r) - pbs(l) <= k) {\n solve(l, r + 1) max (r - l)\n } else {\n solve(l + 1, r)\n }\n } else {\n 0\n }\n\n io += solve(0, 0)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}\n def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class SortedExtensions[A, C[A] <: collection.SortedSet[A]](val s: C[A]) extends AnyVal {\n def greaterThanOrEqualTo(a: A): Option[A] = s.from(a).headOption\n def lessThan(a: A): Option[A] = s.until(a).lastOption\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def absDiff(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n implicit class FuzzyDouble(x: Double)(implicit eps: Double = 1e-9) {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x absDiff y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def array[A]: Write[Array[A]] = Write(_ mkString \" \")\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _676C extends CodeForcesApp {\n override def apply(io: IO) = {\n val (n, k, s) = io[(Int, Int, String)]\n\n val pas, pbs = Array.ofDim[Int](n + 1)\n\n s.indices foreach {i =>\n if (s(i) == 'a') {\n pas(i + 1) = pas(i) + 1\n pbs(i + 1) = pbs(i)\n } else {\n pas(i + 1) = pas(i)\n pbs(i + 1) = pbs(i) + 1\n }\n }\n\n var ans = 0\n\n @tailrec\n def solve(l: Int, r: Int): Unit = if (r <= n) {\n if(pas(r) - pas(l) <= k || pbs(r) - pbs(l) <= k) {\n ans = ans max (r - l)\n solve(l, r + 1)\n } else {\n solve(l + 1, r)\n }\n }\n\n solve(0, 0)\n\n io += ans\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}\n def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class SortedExtensions[A, C[A] <: collection.SortedSet[A]](val s: C[A]) extends AnyVal {\n def greaterThanOrEqualTo(a: A): Option[A] = s.from(a).headOption\n def lessThan(a: A): Option[A] = s.until(a).lastOption\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def absDiff(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n implicit class FuzzyDouble(x: Double)(implicit eps: Double = 1e-9) {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x absDiff y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def array[A]: Write[Array[A]] = Write(_ mkString \" \")\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _676C extends CodeForcesApp {\n override def apply(io: IO) = {\n val (n, k, s) = io[(Int, Int, String)]\n\n val pas, pbs = Array.ofDim[Int](n + 1)\n s.indices foreach {i =>\n pas(i + 1) = pas(i) + (s(i) == 'a').to[Int]\n pbs(i + 1) = pbs(i) + (s(i) == 'b').to[Int]\n }\n\n def solve(l: Int, r: Int): Option[Int] = {\n when(pas(r) - pas(l) <= k || pbs(r) - pbs(l) <= k) {\n r - l\n }\n }\n\n io += twoPointer(n + 1)(solve).get\n }\n\n def twoPointer[A: Ordering](n: Int)(f: (Int, Int) => Option[A]): Option[A] = {\n def run(l: Int, r: Int): Option[A] = if(r == n) {\n None\n } else {\n f(l, r) match {\n case None if l < r => run(l + 1, r)\n case v => (run(l, r + 1) ++ v).whenNonEmpty(_.max)\n }\n }\n run(0, 0)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def array[A]: Write[Array[A]] = Write(_ mkString \" \")\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _676C extends CodeForcesApp {\n override def apply(io: IO) = {\n val (n, k, s) = io[(Int, Int, String)]\n\n val pas, pbs = Array.ofDim[Int](n + 1)\n s.indices foreach {i =>\n pas(i + 1) = pas(i) + (s(i) == 'a').to[Int]\n pbs(i + 1) = pbs(i) + (s(i) == 'b').to[Int]\n }\n\n def isOk(l: Int, r: Int) = pas(r) - pas(l) <= k || pbs(r) - pbs(l) <= k\n val ans = twoPointer(n + 1)(isOk).maxBy{case (x, y) => y - x}\n\n io += (ans._2 - ans._1)\n }\n\n /**\n * Two pointer algorithm\n * O(2*n)\n *\n * @param n\n * @param f\n * f must be monotonic i.e. j is a super-interval of i then f(j) => f(i)\n * anf also if !f(i) then for all\n * @return\n * List of all intervals in [0, n) at which f is defined\n */\n def twoPointer(n: Int)(f: (Int, Int) => Boolean): Vector[(Int, Int)] = {\n def run(l: Int, r: Int): Vector[(Int, Int)] = if (r == n) {\n Vector.empty\n } else if (f(l, r)) {\n run(l, r + 1) :+ (l -> r)\n } else if (l < r) {\n run(l + 1, r)\n } else {\n run(l, r + 1)\n }\n run(0, 0)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def array[A]: Write[Array[A]] = Write(_ mkString \" \")\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _676C extends CodeForcesApp {\n override def apply(io: IO) = {\n val (n, k, s) = io[(Int, Int, String)]\n\n val pas, pbs = Array.ofDim[Int](n + 1)\n s.indices foreach {i =>\n pas(i + 1) = pas(i) + (s(i) == 'a').to[Int]\n pbs(i + 1) = pbs(i) + (s(i) == 'b').to[Int]\n }\n\n def isOk(l: Int, r: Int) = pas(r) - pas(l) <= k || pbs(r) - pbs(l) <= k\n val Some((l, r)) = twoPointer(n + 1)(isOk)\n\n io += r - l\n }\n\n def twoPointer(n: Int)(f: (Int, Int) => Boolean): Option[(Int, Int)] = {\n def run(l: Int, r: Int): Option[(Int, Int)] = if(r == n) {\n None\n } else {\n val isValid = f(l, r)\n if (!isValid && l < r) {\n run(l + 1, r)\n } else {\n (run(l, r + 1) ++ when(isValid)(l -> r)).whenNonEmpty(_.maxBy { case (x, y) => y - x })\n }\n }\n run(0, 0)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def array[A]: Write[Array[A]] = Write(_ mkString \" \")\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val line = in.next()\n val (at, _, _, bt, _, _) = line.indices.foldLeft((0, 0, k, 0, 0, k)) {\n case (att@(amax, acurrent, aleft, bmax, bcurrent, bleft), i) =>\n// println(att)\n val ch = line(i)\n if (ch == 'a') {\n if (bleft > 0)\n (Math.max(amax, acurrent + 1), acurrent + 1, aleft, Math.max(bmax, bcurrent + 1), bcurrent + 1, bleft - 1)\n else {\n var ni = i - bcurrent + 1\n while (ni > 0 && i - ni > 0 && line(i - ni) == 'a')\n ni -= 1\n if (ni < i && i - ni > 0 && line(ni) == 'b')\n (Math.max(amax, acurrent + 1), acurrent + 1, aleft, Math.max(bmax, ni - 1), ni - 1, bleft)\n else\n (Math.max(amax, acurrent + 1), acurrent + 1, aleft, bmax, 0, k)\n }\n }\n else {\n if (aleft > 0)\n (Math.max(amax, acurrent + 1), acurrent + 1, aleft - 1, Math.max(bmax, bcurrent + 1), bcurrent + 1, bleft)\n else {\n// println(\"acurrent \" + acurrent)\n// println(\"i = \" + i)\n var ni = i - acurrent + 1\n// println(\"NI \" + ni)\n while (ni > 0 && i - ni > 0 && line(i - ni) == 'b')\n ni -= 1\n if (ni < i && i - ni > 0 && line(i - ni) == 'a')\n (Math.max(amax, ni - 1), ni - 1, aleft, Math.max(bmax, bcurrent + 1), bcurrent + 1, bleft)\n else\n (amax, 0, k, Math.max(bmax, bcurrent + 1), bcurrent + 1, bleft)\n }\n }\n }\n println(Math.max(at, bt))\n}\n"}], "src_uid": "0151a87d0f82a9044a0ac8731d369bb9"} {"source_code": "object E {\r\n\r\n import InOut._\r\n def main(args: Array[String]): Unit = {\r\n for (_ <- 1 to nextInt) {\r\n solve()\r\n }\r\n }\r\n\r\n def solve(): Unit = {\r\n var a = nextLong\r\n var b = nextLong\r\n var ans = 10000L\r\n\r\n\r\n for (test <- b to b + 10) {\r\n var c = a\r\n var times = 0L\r\n while (c > 0 && test != 1 && c != test) {\r\n c = c / test\r\n times += 1\r\n }\r\n if (test != 1 && c != test) ans = math.min(ans, times + test - b)\r\n }\r\n println(ans)\r\n }\r\n\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n// val in = new BufferedReader(new FileReader(\"./src/main/scala/input.txt\"))\r\n\r\n val out = new java.io.PrintWriter(System.out, false)\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n def nextToken: String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new java.util.StringTokenizer(in.readLine)\r\n tokenizer.nextToken\r\n }\r\n def nextInt = Integer.parseInt(nextToken)\r\n def nextLong = java.lang.Long.parseLong(nextToken)\r\n def nextBig = BigInt(nextToken)\r\n def nextInts(n: Int) = Array.fill(n) { nextInt }\r\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\r\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\r\n def nextLine = in.readLine\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import java.io.BufferedReader\r\nimport java.io.ByteArrayInputStream\r\nimport java.io.InputStreamReader\r\n\r\nobject AAddandDivide {\r\n def solve(a: Int, b: Int): Int = {\r\n if (a < b) 1\r\n else if (a == b) {\r\n 2\r\n } else {\r\n var min = Int.MaxValue\r\n var lmin = Int.MaxValue - 1\r\n var i = if (b == 1) 1 else 0\r\n while (lmin <= min) {\r\n min = lmin\r\n var j = 1\r\n while (Math.pow(b + i, j) <= a) {\r\n j += 1\r\n }\r\n lmin = i + j\r\n i += 1\r\n }\r\n min\r\n }\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val file = new BufferedReader(new InputStreamReader(System.in))\r\n// val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(\r\n// \"6\\n9 2\\n1337 1\\n1 1\\n50000000 4\\n991026972 997\\n1234 5678\".getBytes)))\r\n// \"1\\n50000000 4\".getBytes)))\r\n val inputs = file.readLine.toInt\r\n var i = 0\r\n while (i < inputs) {\r\n val a::b::Nil = file.readLine.split(\" \").map(_.toInt).toList\r\n println(solve(a, b))\r\n i += 1\r\n }\r\n }\r\n}"}, {"source_code": "object CP {\r\n\r\n import InOut._\r\n def main(args: Array[String]): Unit = {\r\n for (_ <- 1 to nextInt) {\r\n solve()\r\n }\r\n }\r\n\r\n def solve(): Unit = {\r\n var a = nextLong\r\n var b = nextLong\r\n var ans = 10000L\r\n\r\n\r\n for (test <- b to b + 10) {\r\n var c = a\r\n var times = 0L\r\n while (c > 0 && test != 1 && c != test) {\r\n c = c / test\r\n times += 1\r\n }\r\n if (test != 1 && c != test) ans = math.min(ans, times + test - b)\r\n }\r\n println(ans)\r\n\r\n }\r\n\r\n\r\n final object InOut {\r\n// import java.io.{BufferedReader, FileInputStream, FileReader, FilterInputStream, FilterReader}\r\n// import scala.io.Source\r\n// val in = new BufferedReader(new FileReader(\"./src/main/scala/input.txt\"))\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n\r\n\r\n val out = new java.io.PrintWriter(System.out, false)\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n def nextToken: String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new java.util.StringTokenizer(in.readLine)\r\n tokenizer.nextToken\r\n }\r\n def nextInt = Integer.parseInt(nextToken)\r\n def nextLong = java.lang.Long.parseLong(nextToken)\r\n def nextBig = BigInt(nextToken)\r\n def nextInts(n: Int) = Array.fill(n) { nextInt }\r\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\r\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\r\n def nextLine = in.readLine\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "2b757fa66ce89046fe18cdfdeafa6660"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n sort(A)\n\n var ans = 0\n var r = 0\n REP(N) { l =>\n if (r < l) r = l\n while(r + 1 < N && A(r + 1) - A(l) <= 5) r += 1\n if (r < N && A(r) - A(l) <= 5) ans = max(ans, r - l + 1)\n }\n out.println(ans)\n }\n\n def sort(a: Array[Int]): Array[Int] = {\n val n = a.length\n REP(n) { i =>\n val j = scala.util.Random.nextInt(n - i) + i\n val tmp = a(i)\n a(i) = a(j)\n a(j) = tmp\n }\n Sorting.stableSort(a)\n a\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugNum(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n", "positive_code": [{"source_code": "object C {\n import scala.collection.mutable\n def main(args: Array[String]){\n val n = readInt\n val skills = readLine().split(\" \").map(_.toInt).sorted\n val max = 5\n var total = 0\n var best = 0\n var last = skills.head\n val using = mutable.SortedMap[Int, Int]()\n skills.foreach { s =>\n while(using.nonEmpty && s - using.head._1 > 5) {\n total -= using.head._2\n using -= using.head._1\n }\n total += 1\n if(!using.contains(s)) using(s) = 0\n using(s) += 1\n best = Math.max(best, total)\n }\n\n println(best)\n }\n}\n"}], "negative_code": [{"source_code": "object C {\n import scala.collection.mutable\n def main(args: Array[String]){\n val n = readInt\n val skills = readLine().split(\" \").map(_.toInt).sorted\n val max = 5\n var total = 0\n var best = 0\n var last = skills.head\n val using = mutable.SortedMap[Int, Int]()\n skills.foreach { s =>\n while(using.nonEmpty && s - using.head._1 > 5) {\n total -= using.head._2\n using -= using.head._1\n }\n total += 1\n if(!using.contains(s)) using(s) = 0\n using(s) += 1\n }\n\n println(total)\n }\n}\n"}, {"source_code": "object C {\n import scala.collection.mutable\n def main(args: Array[String]){\n val n = readInt\n val skills = readLine().split(\" \").map(_.toInt).sorted\n val max = 5\n var total = 0\n var best = 0\n var last = skills.head\n val using = mutable.SortedSet[Int]()\n skills.foreach { s =>\n while(using.nonEmpty && s - using.head > 5) {\n using -= using.head\n total -= 1\n }\n total += 1\n using += s\n }\n\n println(total)\n }\n}\n"}], "src_uid": "8b075d96b3c0172d756109b4801d68de"} {"source_code": "import java.util.Scanner\n\nobject A extends App {\n val sc = new Scanner(System.in)\n\n val t = sc.nextInt\n\n (1 to t)\n .foreach(_ => {\n val n = sc.nextInt\n\n val arr = Array.tabulate(n)(_ => sc.nextLong)\n\n val a1 = arr.foldLeft((0L, true))((a,b) => {val t = a._1 + b; (t, a._2 && t > 0)})\n val a2 = arr.reverse.foldLeft((0L, true))((a,b) => {val t = a._1 + b; (t, a._2 && t > 0)})\n\n println(if (a1._2 && a2._2) \"YES\" else \"NO\")\n })\n\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val t = readInt\n Iterator.fill(t)(f1).foldLeft(()){ case _ => () }\n }\n\n def f1(): Unit = { \n val n = readLong\n val a = readLine.split(\" \").map(_.toLong)\n val (sum, l, r, list) = a.zipWithIndex.foldLeft((0L, 0L, 0L, Vector[(Long, Long, Long)]())){\n case ((sum, l, r, list), (x, i)) => {\n val newlist = if ((sum <= 0 || x <= 0) && l != r) list :+ (sum, l, r) else list\n if (sum > 0 && sum + x > 0) (sum + x, l, i + 1, newlist) else (x, i, i + 1, newlist)\n } \n }\n val x = a.sum\n if (((sum, l, r) +: list).forall{ case (s, l, r) => s < x || ( l == 0 && r == a.length) }) println(\"YES\")\n else println(\"NO\")\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val t = readInt\n Iterator.fill(t)(f1).foldLeft(()){ case _ => () }\n }\n\n def f1(): Unit = { \n val n = readInt\n val a = readLine.split(\" \").map(_.toInt)\n val (sum, l, r, list) = a.zipWithIndex.foldLeft((0, 0, 0, List[(Int, Int, Int)]())){\n case ((sum, l, r, list), (x, i)) => {\n val newlist = if ((sum <= 0 || x <= 0) && l != r) list :+ (sum, l, r) else list\n if (sum > 0 && sum + x > 0) (sum + x, l, i + 1, newlist) else (x, i, i + 1, newlist)\n } \n }\n val x = a.sum\n if (((sum, l, r) +: list).forall{ case (s, l, r) => s < x || ( l == 0 && r == a.length) }) println(\"YES\")\n else println(\"NO\")\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val t = readInt\n Iterator.fill(t)(f1).foldLeft(()){ case _ => () }\n }\n\n def f1(): Unit = { \n val n = readInt\n val a = readLine.split(\" \").map(_.toInt)\n val (sum, l, r, list) = a.zipWithIndex.foldLeft((0, 0, 0, List[(Int, Int, Int)]())){\n case ((sum, l, r, list), (x, i)) => {\n val newlist = if (x <= 0 && l != r) list :+ (sum, l, r) else list\n if (sum + x > 0) (sum + x, l, i + 1, newlist) else (x, i, i + 1, newlist)\n } \n }\n val x = a.sum\n if (((sum, l, r) +: list).forall{ case (s, l, r) => s < x || ( l == 0 && r == a.length) }) println(\"YES\")\n else println(\"NO\")\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject A extends App {\n val sc = new Scanner(System.in)\n\n val t = sc.nextInt\n\n (1 to t)\n .foreach(_ => {\n val n = sc.nextInt\n\n val arr = Array.tabulate(n)(_ => sc.nextInt)\n\n val a1 = arr.foldLeft((0, true))((a,b) => {val t = a._1 + b; (t, a._2 && t > 0)})\n val a2 = arr.reverse.foldLeft((0, true))((a,b) => {val t = a._1 + b; (t, a._2 && t > 0)})\n\n println(if (a1._2 && a2._2) \"YES\" else \"NO\")\n })\n\n}\n"}], "src_uid": "6e5b4d43e64645cf26d5eac31437b1a9"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next().split(\"@\", -1)\n if (line.contains(\"\") || line.length < 2 || line.drop(1).dropRight(1).exists(_.length == 1))\n println(\"No solution\")\n else\n println(line.indices.flatMap{\n case (0) => List(line(0))\n case (i) if i == line.length - 1 => List(line(line.length - 1))\n case (i) => List(line(i).head, line(i).tail)\n }.grouped(2).map(_.mkString(\"@\")).mkString(\",\"))\n}", "positive_code": [{"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var s = readLine;\n if (s.startsWith(\"@\") || s.endsWith(\"@\") || !s.contains(\"@\")) {\n println(\"No solution\");\n return;\n }\n var ss = s.split(\"@\");\n var atCount = s.count(_.toChar == '@')\n if (ss.length - 1 != atCount) {\n println(\"No solution\");\n return;\n }\n for (i <- 0 until ss.length) {\n if (i != 0 && i != ss.length - 1) {\n if (ss(i).length <= 1) {\n println(\"No solution\");\n return;\n }\n }\n }\n var result = \"\";\n var prev = false;\n var atNumber = 0;\n for (e <- s) {\n result += e;\n if (prev && atNumber != atCount) {\n result += \",\";\n prev = false;\n }\n if (e == '@') {\n atNumber += 1;\n prev = true;\n }\n }\n println(result);\n }\n\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next().split(\"@\", -1)\n if (line.contains(\"\") || line.drop(1).dropRight(1).exists(_.length == 1))\n println(\"No solution\")\n else\n println(line.indices.flatMap{\n case (0) => List(line(0))\n case (i) if i == line.length - 1 => List(line(line.length - 1))\n case (i) => List(line(i).head, line(i).tail)\n }.grouped(2).map(_.mkString(\"@\")).mkString(\",\"))\n}"}, {"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var s = readLine;\n if (s.startsWith(\"@\") || s.endsWith(\"@\")) {\n println(\"No solution\");\n return;\n }\n var ss = s.split(\"@\");\n var atCount = s.count(_.toChar == '@')\n if (ss.length - 1 != atCount) {\n println(\"No solution\");\n return;\n }\n for (i <- 0 until ss.length) {\n if (i != 0 && i != ss.length - 1) {\n if (ss(i).length <= 1) {\n println(\"No solution\");\n return;\n }\n }\n }\n var result = \"\";\n var prev = false;\n var atNumber = 0;\n for (e <- s) {\n result += e;\n if (prev && atNumber != atCount) {\n result += \",\";\n prev = false;\n }\n if (e == '@') {\n atNumber += 1;\n prev = true;\n }\n }\n println(result);\n }\n\n}"}], "src_uid": "71b4674e91e0bc5521c416cfc570a090"} {"source_code": "import java.util.Scanner\nimport scala.collection.JavaConverters._\n\nobject Main extends App {\n val sc = new java.util.Scanner(System.in)\n\n val n, m, h, t = sc.nextInt\n\n val es = Array.tabulate(m)(_ => (sc.nextInt(), sc.nextInt()))\n\n val vsp = Array.tabulate(n+1)(_ => (new java.util.HashSet[Int]()).asScala)\n\n es foreach { e =>\n vsp(e._1) += e._2\n vsp(e._2) += e._1\n }\n\n val vs = vsp\n\n def makeHydra(vh: Int, vt: Int): Boolean = {\n if (vs(vh).size > h && vs(vt).size > t && (vs(vh) ++ vs(vt)).size >= h + t + 2) {\n println(\"YES\")\n println(\"%d %d\".format(vh, vt))\n val cm = (vs(vh) & vs(vt)).toSeq\n val rh = (vs(vh) - vt -- cm).toSeq ++ cm ++ (vs(vt) - vh -- cm).toSeq\n println(rh.take(h).mkString(\" \"))\n println(rh.takeRight(t).mkString(\" \"))\n\n true\n } else false\n }\n\n es sortBy { case (src, dst) =>\n - (vs(src).size + vs(dst).size)\n } indexWhere { e =>\n makeHydra(e._1, e._2) || makeHydra(e._2, e._1)\n } match {\n case -1 => println(\"NO\");\n case _ => Unit\n }\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ListBuffer\n\nobject Main extends App {\n val sc = new java.util.Scanner(System.in)\n\n val n, m, h, t = sc.nextInt\n\n val es = Array.tabulate(m)(_ => (sc.nextInt(), sc.nextInt()))\n\n val vsp = Array.tabulate(n+1)(_ => ListBuffer[Int]())\n\n es foreach { e =>\n vsp(e._1) += e._2\n vsp(e._2) += e._1\n }\n\n val vs = vsp.map(_.toSet)\n\n def makeHydra(vh: Int, vt: Int): Boolean = {\n if (vs(vh).size > h && vs(vt).size > t && (vs(vh) ++ vs(vt)).size >= h + t + 2) {\n println(\"YES\")\n println(\"%d %d\".format(vh, vt))\n val cm = (vs(vh) & vs(vt)).toSeq\n val rh = (vs(vh) - vt -- cm).toSeq ++ cm ++ (vs(vt) - vh -- cm).toSeq\n println(rh.take(h).mkString(\" \"))\n println(rh.takeRight(t).mkString(\" \"))\n\n true\n } else false\n }\n\n es sortBy { case (src, dst) =>\n - (vs(src).size + vs(dst).size)\n } indexWhere { e =>\n makeHydra(e._1, e._2) || makeHydra(e._2, e._1)\n } match {\n case -1 => println(\"NO\");\n case _ => Unit\n }\n}\n"}, {"source_code": "object Main extends App {\n import java.{util => ju}\n import scala.collection.JavaConverters._\n\n val sc = new ju.Scanner(System.in)\n\n val n, m, h, t = sc.nextInt\n\n val es = Array.tabulate(m)(_ => (sc.nextInt(), sc.nextInt()))\n\n val vsp = Array.tabulate(n+1)(_ => (new ju.HashSet[Int]()).asScala)\n\n es foreach { case (src, dst) =>\n vsp(src) += dst\n vsp(dst) += src\n }\n\n val vs = vsp\n\n def makeHydra(vh: Int, vt: Int): Boolean = {\n if (vs(vh).size > h && vs(vt).size > t && (vs(vh) ++ vs(vt)).size >= h + t + 2) {\n println(\"YES\")\n println(\"%d %d\".format(vh, vt))\n val cm = (vs(vh) & vs(vt)).toSeq\n val rh = (vs(vh) - vt -- cm).toSeq ++ cm ++ (vs(vt) - vh -- cm).toSeq\n println(rh.take(h).mkString(\" \"))\n println(rh.takeRight(t).mkString(\" \"))\n\n true\n } else false\n }\n\n es sortBy { case (src, dst) =>\n - (vs(src).size + vs(dst).size)\n } indexWhere { case (src, dst) =>\n makeHydra(src, dst) || makeHydra(dst, src)\n } match {\n case -1 => println(\"NO\");\n case _ => Unit\n }\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ListBuffer\n\nobject Main extends App {\n val sc = new java.util.Scanner(System.in)\n\n val n, m, h, t = sc.nextInt\n\n val es = Array.tabulate(m)(_ => (sc.nextInt(), sc.nextInt()))\n\n val vsp = Array.tabulate(n+1)(_ => ListBuffer[Int]())\n\n es foreach { e =>\n vsp(e._1) += e._2\n vsp(e._2) += e._1\n }\n\n val vs = vsp.map(_.toSet)\n\n def makeHydra(vh: Int, vt: Int): Boolean = {\n if (vs(vh).size > h && vs(vt).size > t && (vs(vh) ++ vs(vt)).size >= h + t + 2) {\n println(\"YES\")\n println(\"%d %d\".format(vh, vt))\n val cm = (vs(vh) & vs(vt)).toSeq\n val rh = (vs(vh) - vt -- cm).toSeq ++ cm\n val rt = cm.reverse ++ (vs(vt) - vh -- cm).toSeq\n println(rh.take(h).mkString(\" \"))\n println(rt.takeRight(t).mkString(\" \"))\n\n true\n } else false\n }\n\n es indexWhere { e =>\n makeHydra(e._1, e._2) || makeHydra(e._2, e._1)\n } match {\n case -1 => println(\"NO\");\n case _ => Unit\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable._\n\nobject Main extends App {\n val sc = new java.util.Scanner(System.in)\n\n val n, m, h, t = sc.nextInt\n\n val es = Array.tabulate(m)(_ => (sc.nextInt(), sc.nextInt()))\n\n val vs = Array.tabulate(n+1)(_ => Set[Int]())\n\n es foreach { e =>\n vs(e._1) += e._2\n vs(e._2) += e._1\n }\n\n def makeHydra(vh: Int, vt: Int): Boolean = {\n val cm = vs(vh) & vs(vt)\n if (vs(vh).size > h && vs(vt).size > t && vs(vh).size + vs(vt).size + cm.size >= h + t + 2) {\n println(\"YES\")\n println(\"%d %d\".format(vh, vt))\n \n val rv = (vs(vh) - vt -- cm).toList ++ cm.toList ++ (vs(vt) - vh -- cm).toList\n\n println(rv.take(h).mkString(\" \"))\n println(rv.takeRight(t).mkString(\" \"))\n\n true\n } else false\n }\n\n es indexWhere { e =>\n makeHydra(e._1, e._2) || makeHydra(e._2, e._1)\n } match {\n case -1 => println(\"NO\");\n case _ => Unit\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable._\n\nobject Main extends App {\n val sc = new java.util.Scanner(System.in)\n\n val n, m, h, t = sc.nextInt\n\n val es = Array.tabulate(m)(_ => (sc.nextInt(), sc.nextInt()))\n\n val vs = Array.tabulate(n+1)(_ => Set[Int]())\n\n es foreach { e =>\n vs(e._1) += e._2\n vs(e._2) += e._1\n }\n\n def makeHydra(vh: Int, vt: Int): Boolean = {\n if (vs(vh).size > h && vs(vt).size > t && (vs(vh) ++ vs(vt)).size >= h + t + 2) {\n println(\"%d %d\".format(vh, vt))\n \n val cm = vs(vh) & vs(vt)\n val rv = (vs(vh) - vt -- cm).toList ++ cm.toList ++ (vs(vt) - vh -- cm).toList\n\n println(rv.take(h).mkString(\" \"))\n println(rv.takeRight(t).mkString(\" \"))\n\n true\n } else false\n }\n\n es indexWhere { e =>\n makeHydra(e._1, e._2) || makeHydra(e._2, e._1)\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ListBuffer\n\nobject Main extends App {\n val sc = new java.util.Scanner(System.in)\n\n val n, m, h, t = sc.nextInt\n\n val es = Array.tabulate(m)(_ => (sc.nextInt(), sc.nextInt()))\n\n val vsp = Array.tabulate(n+1)(_ => ListBuffer[Int]())\n\n es foreach { e =>\n vsp(e._1) += e._2\n vsp(e._2) += e._1\n }\n\n val vs = vsp.map(_.toSet)\n\n def makeHydra(vh: Int, vt: Int): Boolean = {\n if (vs(vh).size > h && vs(vt).size > t && (vs(vh) ++ vs(vt)).size >= h + t + 2) {\n println(\"YES\")\n println(\"%d %d\".format(vh, vt))\n return true\n \n val cm = (vs(vh) & vs(vt)).toArray\n val rh = (vs(vh) - vt -- cm)\n val rt = (vs(vt) - vh -- cm).take(t).toArray ++ cm.reverse.take(t)\n\n println(rh.take(h).mkString(\" \"))\n println(rt.take(t).mkString(\" \"))\n\n true\n } else false\n }\n\n es indexWhere { e =>\n makeHydra(e._1, e._2) || makeHydra(e._2, e._1)\n } match {\n case -1 => println(\"NO\");\n case _ => Unit\n }\n}\n"}], "src_uid": "2d098058a553a70f30977266059f01c2"} {"source_code": "object B1037 {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val temp = stdin.readLine.trim.split(\" \").map(_.toLong)\n val (n,s) = (temp(0), temp(1))\n val array = stdin.readLine.trim.split(\" \").map(_.toLong).sorted\n val p = ((n-1)/2).toInt\n val ans: Long = if (array(p)-s > 0) {\n array.slice(0,p+1).filter(_ > s).map(x => x-s).sum\n } else {\n if (array(p)-s < 0) {\n array.slice(p,n.toInt).filter(_ < s).map(x => s-x).sum\n } else 0L\n }\n print(ans)\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject B extends App {\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val s = in.nextInt\n val a: Array[Int] = Array.fill(n)(in.nextInt)\n util.Sorting.quickSort(a)\n var i = n / 2\n var ans: Long = 0\n\n if (a(n / 2) < s) {\n while (i < n && a(i) < s) {\n ans += s - a(i)\n i += 1\n }\n } else {\n while (i >= 0 && a(i) > s) {\n ans += a(i) - s\n i -= 1\n }\n }\n println(ans)\n\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toInt\n }\n\n def nextLong: Double = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n val sc = new InputReader(System.in)\n\n def solve(): Unit = {\n val N, M = ni()\n val A = na(N)\n\n Sorting.quickSort(A)\n var ans = 0L\n rep_r(N / 2 + 1, N / 2) { i =>\n val a = A(i)\n if (a < M) {\n ans += M - a\n }\n }\n\n rep_r(N / 2 + 1) { i =>\n val a = A(i)\n if (a > M) {\n ans += a - M\n }\n }\n\n out.println(ans)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "import java.util.StringTokenizer\n\nimport scala.io.StdIn\n\nobject B extends App with Reader {\n read()\n val n = int()\n val s = int()\n read()\n val a = Array.fill(n)(int()).sorted\n val m = n / 2\n\n var res = 0L\n\n for (i <- 0 to m) {\n if (a(i) > s) res += a(i) - s\n }\n for (i <- m until n) {\n if (a(i) < s) res += s - a(i)\n }\n\n println(res)\n}\n\ntrait Reader {\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(StdIn.readLine()) }\n def int() = st.nextToken().toInt\n def long() = st.nextToken().toLong\n}\n"}], "negative_code": [{"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n val sc = new InputReader(System.in)\n\n def solve(): Unit = {\n val N, M = ni()\n val A = na(N)\n\n Sorting.quickSort(A)\n var ans = 0L\n rep_r(N / 2 + 1, N / 2) { i =>\n val a = A(i)\n if (a < M) {\n ans += M - a\n }\n }\n\n out.println(ans)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "import java.util.StringTokenizer\n\nimport scala.io.StdIn\n\nobject B extends App with Reader {\n read()\n val n = int()\n val s = int()\n read()\n val a = Array.fill(n)(int()).sorted\n val m = n / 2\n\n var res = 0\n\n for (i <- 0 to m) {\n if (a(i) > s) res += a(i) - s\n }\n for (i <- m until n) {\n if (a(i) < s) res += s - a(i)\n }\n\n println(res)\n}\n\ntrait Reader {\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(StdIn.readLine()) }\n def int() = st.nextToken().toInt\n def long() = st.nextToken().toLong\n}\n"}, {"source_code": "object B1037 {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val temp = stdin.readLine.trim.split(\" \").map(_.toInt)\n val (n,s) = (temp(0), temp(1))\n val array = stdin.readLine.trim.split(\" \").map(_.toInt).sorted\n val p = (n-1)/2\n val ans = if (array(p)-s > 0) {\n array.slice(0,p+1).filter(_ > s).map(x => x-s).sum\n } else if (array(p)-s < 0) {\n array.slice(p,n+1).filter(_ < s).map(x => s-x).sum\n }\n print(ans)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject B extends App {\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val s = in.nextInt\n val a: Array[Int] = Array.fill(n)(in.nextInt)\n util.Sorting.quickSort(a)\n var i = n / 2\n var ans = 0\n\n if (a(n / 2) < s) {\n while (i < n && a(i) < s) {\n ans += s - a(i)\n i += 1\n }\n } else {\n while (i >= 0 && a(i) > s) {\n ans += a(i) - s\n i -= 1\n }\n }\n println(ans)\n\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toInt\n }\n\n def nextLong: Double = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}], "src_uid": "0df33cd53575471b1cc20702bf777059"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A = na(2 * N)\n val sum = A.sum\n val half = A.take(N).sum\n if (half * 2 == sum) {\n REP(N) { i =>\n REP(N) { j =>\n if (A(i) != A(N + j)) {\n val t = A(i)\n A(i) = A(N + j)\n A(N + j) = t\n out.println(A.mkString(\" \"))\n return\n }\n }\n }\n out.println(-1)\n } else {\n out.println(A.mkString(\" \"))\n }\n }\n}", "positive_code": [{"source_code": "object _1174A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val n = io.read[Int]\n val arr = io.read[Seq, Int](2*n)\n val ans = arr.distinct.size match {\n case 1 => \"-1\"\n case _ => arr.sorted.mkString(\" \")\n }\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "1f4c057dff45f229b4dca49cd4e0438d"} {"source_code": "import scala.io.Source._\nobject Solution{\n def main(args: Array[String]){\n def labelString(id: Int) = List(\"S\",\"M\",\"L\",\"XL\",\"XXL\",\"XXXL\")(id)\n def labelInt(id: String) = List(\"S\",\"M\",\"L\",\"XL\",\"XXL\",\"XXXL\").indexOf(id)\n val input = stdin.getLines().toList\n val cnt = input(0).split(\" \").map(_.toInt).toArray\n val n = input(1).toInt\n val (single,double) = input.drop(2).map(_.split(\",\").map(labelInt).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)\n val ans = new Array[String](n)\n for(shirt <- single){\n cnt(shirt._1.head) = cnt(shirt._1.head)-1\n ans(shirt._2) = labelString(shirt._1.head)\n }\n for(shirt <- double)\n if(cnt(shirt._1.head) > 0){\n cnt(shirt._1.head) = cnt(shirt._1.head)-1\n ans(shirt._2) = labelString(shirt._1.head)\n }\n else{\n cnt(shirt._1.last) = cnt(shirt._1.last)-1\n ans(shirt._2) = labelString(shirt._1.last)\n }\n //println(cnt.toList)\n if(cnt.min < 0){\n println(\"NO\")\n return\n }\n println(\"YES\")\n println(ans.mkString(\"\\n\"))\n }\n}\n", "positive_code": [{"source_code": "import scala.io.Source._\nobject Solution{\n def main(args: Array[String]){\n def labelString(id: Int) = List(\"S\",\"M\",\"L\",\"XL\",\"XXL\",\"XXXL\")(id)\n def labelInt(id: String) = List(\"S\",\"M\",\"L\",\"XL\",\"XXL\",\"XXXL\").indexOf(id)\n val input = stdin.getLines().toList\n var cnt = input(0).split(\" \").map(_.toInt)\n val n = input(1).toInt\n val (single,double) = input.drop(2).map(_.split(\",\").map(labelInt).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)\n var ans = new Array[String](n)\n for(shirt <- single){\n cnt(shirt._1.head) = cnt(shirt._1.head)-1\n ans(shirt._2) = labelString(shirt._1.head)\n }\n for(shirt <- double)\n if(cnt(shirt._1.head) > 0){\n cnt(shirt._1.head) = cnt(shirt._1.head)-1\n ans(shirt._2) = labelString(shirt._1.head)\n }\n else{\n cnt(shirt._1.last) = cnt(shirt._1.last)-1\n ans(shirt._2) = labelString(shirt._1.last)\n }\n //println(cnt.toList)\n if(cnt.min < 0){\n println(\"NO\")\n return\n }\n println(\"YES\")\n println(ans.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "import scala.io.Source._\nobject Solution{\n def main(args: Array[String]){\n val labels = Array(\"S\",\"M\",\"L\",\"XL\",\"XXL\",\"XXXL\")\n val labelMap = labels.zipWithIndex.toMap\n val input = stdin.getLines().toList\n val cnt = input(0).split(\" \").map(_.toInt).toArray\n val n = input(1).toInt\n val (single,double) = input.drop(2).map(_.split(\",\").map(labelMap).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)\n val ans = new Array[Int](n)\n for(shirt <- single){\n cnt(shirt._1.head) = cnt(shirt._1.head)-1\n ans(shirt._2) = shirt._1.head\n }\n for(shirt <- double)\n if(cnt(shirt._1.head) > 0){\n cnt(shirt._1.head) = cnt(shirt._1.head)-1\n ans(shirt._2) = shirt._1.head\n }\n else{\n cnt(shirt._1.last) = cnt(shirt._1.last)-1\n ans(shirt._2) = shirt._1.last\n }\n if(cnt.min < 0){\n println(\"NO\")\n return\n }\n println(\"YES\")\n println(ans.map(labels).mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "import scala.io.Source._\nobject Solution{\n def main(args: Array[String]){\n def labelString(id: Int) = List(\"S\",\"M\",\"L\",\"XL\",\"XXL\",\"XXXL\")(id)\n def labelInt(id: String) = List(\"S\",\"M\",\"L\",\"XL\",\"XXL\",\"XXXL\").indexOf(id)\n val input = stdin.getLines().toList\n val cnt = input(0).split(\" \").map(_.toInt).toArray\n val n = input(1).toInt\n val (single,double) = input.drop(2).map(_.split(\",\").map(labelInt).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)\n var ans = new Array[String](n)\n for(shirt <- single){\n cnt(shirt._1.head) = cnt(shirt._1.head)-1\n ans(shirt._2) = labelString(shirt._1.head)\n }\n for(shirt <- double)\n if(cnt(shirt._1.head) > 0){\n cnt(shirt._1.head) = cnt(shirt._1.head)-1\n ans(shirt._2) = labelString(shirt._1.head)\n }\n else{\n cnt(shirt._1.last) = cnt(shirt._1.last)-1\n ans(shirt._2) = labelString(shirt._1.last)\n }\n //println(cnt.toList)\n if(cnt.min < 0){\n println(\"NO\")\n return\n }\n println(\"YES\")\n println(ans.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "import scala.io.Source._\nobject Solution{\n def main(args: Array[String]){\n val labels = Array(\"S\",\"M\",\"L\",\"XL\",\"XXL\",\"XXXL\")\n val labelMap = labels.zipWithIndex.toMap\n val input = stdin.getLines().toList\n val cnt = input(0).split(\" \").map(_.toInt).toArray\n val n = input(1).toInt\n val (single,double) = input.drop(2).map(_.split(\",\").map(labelMap).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)\n val ans = new Array[String](n)\n for(shirt <- single){\n cnt(shirt._1.head) = cnt(shirt._1.head)-1\n ans(shirt._2) = labels(shirt._1.head)\n }\n for(shirt <- double)\n if(cnt(shirt._1.head) > 0){\n cnt(shirt._1.head) = cnt(shirt._1.head)-1\n ans(shirt._2) = labels(shirt._1.head)\n }\n else{\n cnt(shirt._1.last) = cnt(shirt._1.last)-1\n ans(shirt._2) = labels(shirt._1.last)\n }\n if(cnt.min < 0){\n println(\"NO\")\n return\n }\n println(\"YES\")\n println(ans.mkString(\"\\n\"))\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source._\nobject Solution{\n def main(args: Array[String]){\n def labelString(id: Int) = List(\"S\",\"M\",\"L\",\"XL\",\"XXL\",\"XXXL\")(id)\n def labelInt(id: String) = List(\"S\",\"M\",\"L\",\"XL\",\"XXL\",\"XXXL\").indexOf(id)\n val input = stdin.getLines().toList\n var cnt = input(0).split(\" \").map(_.toInt)\n val n = input(1).toInt\n val (single,double) = input.drop(2).map(_.split(\",\").map(labelInt).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)\n var ans = new Array[String](n)\n for(shirt <- single)\n if(cnt(shirt._1.head) > 0){\n cnt(shirt._1.head) = cnt(shirt._1.head)-1\n ans(shirt._2) = labelString(shirt._1.head)\n }\n for(shirt <- double)\n if(cnt(shirt._1.head) > 0){\n cnt(shirt._1.head) = cnt(shirt._1.head)-1\n ans(shirt._2) = labelString(shirt._1.head)\n }\n else{\n cnt(shirt._1.last) = cnt(shirt._1.last)-1\n ans(shirt._2) = labelString(shirt._1.last)\n }\n //println(cnt.toList)\n if(cnt.min < 0){\n println(\"NO\")\n return\n }\n println(\"YES\")\n println(ans.mkString(\"\\n\"))\n }\n}\n"}], "src_uid": "f7e634607f1500c91bf93f44472b18cb"} {"source_code": "object B454 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val a = readInts(n)\n var idx = -1\n for(i <- 1 until n if idx == -1)\n if(a(i-1) > a(i))\n idx = i\n if(idx != -1) {\n val newA = a.takeRight(n-idx) ++ a.take(idx)\n if(newA.zip(a.sorted).forall(arr => arr._1 == arr._2))\n println(n-idx)\n else\n println(\"-1\")\n } else {\n if(a.sorted.zip(a).forall(arr => arr._1 == arr._2))\n println(\"0\")\n else\n println(\"-1\")\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 01.08.14.\n */\nobject B extends App {\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n val a = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n }\n if (a.toList == a.sorted.toList) {\n out.println(0)\n } else {\n var r = -1\n for (i <- n - 1 to 1 by(-1) if r == -1) {\n if (a(i) < a(i - 1)) {\n r = i\n }\n }\n //out.println(r)\n val b = a.takeRight(n - r) ++ a.take(r)\n //out.println(b.toList)\n if (b.toList == b.sorted.toList) {\n out.println(n - r)\n } else {\n out.println(-1)\n }\n }\n\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}\n"}, {"source_code": "import java.util._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def smartSolver(n: Int, a: Array[Int]): Int = {\n var ind = 1\n var flag = false\n var prev = a(0)\n var count = 0\n var terminate = 0\n while (terminate <= 3 * n && !flag) {\n if (prev <= a(ind)) {\n count += 1\n } else {\n count = 0\n }\n if (count == n - 1) {\n flag = true\n }\n else {\n prev = a(ind)\n ind = (ind + 1) % n\n terminate += 1\n }\n }\n if (flag) {\n return n - ind - 1\n } else {\n return -1\n }\n }\n\n def stupidSolver(n: Int, a: Array[Int]): Int = {\n var ans = 1000000\n for (i <- 0 until n) {\n var len = 0\n var ind = i\n var cnt = 0\n var prev = a(ind)\n while (len < n - 1) {\n ind = (ind + 1) % n\n if (prev <= a(ind)) {\n cnt += 1\n }\n len += 1\n prev = a(ind)\n }\n if (cnt == n - 1) {\n ans = Math.min(i, ans)\n }\n }\n return ans\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n }\n // val rand = new Random\n // for (i <- 0 until n) {\n // a(i) = rand.nextInt(5)\n // }\n // for (i <- 0 until n) {\n // out.print(a(i) + \" \")\n // }\n // out.println\n // out.println(\"smart = \" + smartSolver(n, a))\n // out.println(\"stupid = \" + stupidSolver(n, a))\n out.println(smartSolver(n, a))\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val min = data.min\n if (data.forall(_ == min))\n println(0)\n else {\n var start = data.indexOf(min)\n if (start == 0)\n if (data.last == min) {\n start = n - 1\n while (data(start - 1) == min)\n start = start - 1\n }\n val candidate = (start to start + n - 1).map(i => data(i % n))\n\n if (candidate.tail.foldLeft((false, min)){\n case((true, prev), el) => (true, el)\n case((false, prev), el) => (prev > el, el)\n }._1)\n println(-1)\n else\n println((n - start) % n)\n }\n}"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n\n var i = 1\n\n while (i < n && as(i) >= as(i - 1)) i += 1\n if (i == n) {\n println(0)\n System.exit(0)\n }\n\n if (as.last > as.head) {\n println(-1)\n System.exit(0)\n }\n //println(i)\n var j = n - 2\n while (j >= i && as(j) <= as(j + 1)) j -= 1\n //println(j)\n if (j < i && as(j + 1) <= as.head) println(n - j - 1)\n else println(-1)\n}"}], "negative_code": [{"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n\n var i = 1\n\n while (i < n && as(i) >= as(i - 1)) i += 1\n if (i == n) {\n println(0)\n System.exit(0)\n }\n\n if (as.last > as.head) {\n println(-1)\n System.exit(0)\n }\n \n var j = n - 2\n while (j >= i && as(j) >= as(j + 1)) j -= 1\n \n if (j < i) println(n - j - 1)\n else println(-1)\n}"}, {"source_code": "import java.util._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n }\n var ind = 1\n var flag = false\n var prev = a(0)\n var count = 0\n var terminate = 0\n while (terminate <= 3 * n && !flag) {\n if (prev <= a(ind)) {\n count += 1\n } else {\n count = 0\n }\n if (count == n - 1) {\n flag = true\n }\n prev = a(ind)\n ind = (ind + 1) % n\n terminate += 1\n }\n if (flag) {\n out.println(terminate - n + 1)\n } else {\n out.println(-1)\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}, {"source_code": "import java.util._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def smartSolver(n: Int, a: Array[Int]): Int = {\n var ind = 1\n var flag = false\n var prev = a(0)\n var count = 0\n var terminate = 0\n while (terminate <= 3 * n && !flag) {\n if (prev <= a(ind)) {\n count += 1\n } else {\n count = 0\n }\n if (count == n - 1) {\n flag = true\n }\n else {\n prev = a(ind)\n ind = (ind + 1) % n\n terminate += 1\n }\n }\n if (flag) {\n return terminate - n + 2\n } else {\n return -1\n }\n }\n\n def stupidSolver(n: Int, a: Array[Int]): Int = {\n var ans = 1000000\n for (i <- 0 until n) {\n var len = 0\n var ind = i\n var cnt = 0\n var prev = a(ind)\n while (len < n - 1) {\n ind = (ind + 1) % n\n if (prev <= a(ind)) {\n cnt += 1\n }\n len += 1\n prev = a(ind)\n }\n if (cnt == n - 1) {\n ans = Math.min(i, ans)\n }\n }\n return ans\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n }\n // val rand = new Random\n // for (i <- 0 until n) {\n // a(i) = rand.nextInt(100)\n // }\n // for (i <- 0 until n) {\n // out.print(a(i) + \" \")\n // }\n // out.println\n // out.println(\"smart = \" + smartSolver(n, a))\n // out.println(\"stupid = \" + stupidSolver(n, a))\n out.println(smartSolver(n, a))\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}, {"source_code": "import java.util._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def smartSolver(n: Int, a: Array[Int]): Int = {\n var ind = 1\n var flag = false\n var prev = a(0)\n var count = 0\n var terminate = 0\n while (terminate <= 3 * n && !flag) {\n if (prev < a(ind)) {\n count += 1\n } else {\n count = 0\n }\n if (count == n - 1) {\n flag = true\n }\n else {\n prev = a(ind)\n ind = (ind + 1) % n\n terminate += 1\n }\n }\n if (flag) {\n return terminate - n + 2\n } else {\n return -1\n }\n }\n\n def stupidSolver(n: Int, a: Array[Int]): Int = {\n var ans = 1000000\n for (i <- 0 until n) {\n var len = 0\n var ind = i\n var cnt = 0\n var prev = a(ind)\n while (len < n - 1) {\n ind = (ind + 1) % n\n if (prev <= a(ind)) {\n cnt += 1\n }\n len += 1\n prev = a(ind)\n }\n if (cnt == n - 1) {\n ans = Math.min(i, ans)\n }\n }\n return ans\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n }\n// val rand = new Random\n// for (i <- 0 until n) {\n// a(i) = rand.nextInt(5)\n// }\n// for (i <- 0 until n) {\n// out.print(a(i) + \" \")\n// }\n// out.println\n// out.println(\"smart = \" + smartSolver(n, a))\n// out.println(\"stupid = \" + stupidSolver(n, a))\n out.println(smartSolver(n, a))\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}], "src_uid": "c647e36495fb931ac72702a12c6bfe58"} {"source_code": "import java.util.Scanner\n\nobject Main extends App {\n\n val s = new Scanner(System.in)\n\n var t = s.nextInt()\n\n for(_ <- 0 until t) {\n val a1 = s.nextLong()\n val k = s.nextLong()\n\n var i: Long = 1L\n var ai: Long = a1\n\n while(i < k && minDigit(ai) != 0) {\n i += 1\n ai = ai + minDigit(ai) * maxDigit(ai)\n }\n\n println(ai)\n }\n\n def minDigit(n: Long): Long = {\n n.toString.min - '0'\n }\n def maxDigit(n: Long): Long = {\n n.toString.max - '0'\n }\n\n\n\n}\n", "positive_code": [{"source_code": "object ProblemA extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n\n for (_ <- 1 to t) {\n var a1 = in.nextLong()\n var k = in.nextLong()\n\n while (k > 1) {\n k = k - 1\n a1 = a1 + (a1.toString.min.toInt - 48) * (a1.toString.max.toInt - 48)\n if (a1.toString.contains('0')) k = 0\n }\n println(a1)\n }\n\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.annotation.tailrec\n\nobject Main extends App {\n\n @tailrec\n private def perform(start: Long, element: Long, last: Long = -1): Long = {\n (start, element) match {\n case (s, 1) => s\n case (s, _) if s == last => s\n case (s, e) =>\n val sth = ((s.toString.max - '0').toLong * (s.toString.min - '0').toLong) + s\n perform(sth, e - 1, start)\n }\n }\n\n\n def foo(list: List[(Long, Long)]) = {\n list.map(x => perform(x._1, x._2))\n }\n\n val scan = new Scanner(System.in)\n val n = scan.nextLong()\n val seq = for {\n _ <- 0.toLong until n.toLong\n (x, y) = (scan.nextLong(), scan.nextLong())\n } yield x -> y\n\n foo(seq.toList).foreach(println)\n\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject CodeforcesRound643a {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n var Array(a1, k) = rll_long\n (2L to Math.min(k, 100L)).foreach(_ => a1 = a1 + minDigit(a1) * maxDigit(a1))\n writer.println(a1)\n }\n\n def minDigit(n: Long): Long = {\n digits(n).fold(9L) { case (a, b) => Math.min(a, b) }\n }\n\n def maxDigit(n: Long): Long = {\n digits(n).fold(0L) { case (a, b) => Math.max(a, b) }\n }\n\n // Allocates memory, but should work\n def digits(n: Long): Array[Long] = {\n val digits = ArrayBuffer[Long]()\n var nn = n\n while (nn > 0) {\n digits.append(nn % 10L)\n nn = nn / 10\n }\n if (digits.isEmpty) {\n Array(0L)\n } else {\n digits.toArray\n }\n }\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C643A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C643A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val a = nl()\n val k = nl()\n\n var continue = true\n var run = 1\n var vl = a\n while (continue && run < k) {\n val x = vl + minE(vl) * maxE(vl)\n if(x == vl) continue = false\n run += 1\n vl = x\n }\n\n out.println(vl)\n }\n }\n\n def minE(u: Long): Int = {\n var v = u\n var rt = 10\n\n while (v > 0) {\n if(v % 10 < rt) rt = (v % 10).toInt\n v /= 10\n }\n rt\n }\n\n def maxE(u: Long): Int = {\n var v = u\n var rt = -1\n\n while (v > 0) {\n if(v % 10 > rt) rt = (v % 10).toInt\n v /= 10\n }\n rt\n }\n}\n"}, {"source_code": "object A extends App {\n private def an(a1: Long, n: Long): Long = {\n def go(a1: String, n: Long): String =\n if (a1.contains('0') || n == 1) a1\n else go((a1.toLong + (a1.min - 48) * (a1.max - 48)).toString(), n - 1)\n\n go(a1.toString, n).toLong\n }\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(a1, k) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n val ai = an(a1, k)\n\n println(ai)\n }\n}\n"}, {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(a1, k) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n var i = 1L\n var ai = a1\n var ds = (a1 % 10, a1 % 10)\n\n while (i < k && ds._1 != 0) {\n var a = ai\n ds = (a % 10, a % 10)\n while (a != 0 && ds._1 != 0) {\n val d = a % 10\n a /= 10\n ds = (if (d < ds._1) d else ds._1, if (d > ds._2) d else ds._2)\n }\n\n i += 1L\n ai += ds._1 * ds._2\n }\n\n println(ai)\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject solver {\n def main(args:Array[String]) = {\n val t:Int = readInt()\n \n (1 to t).foreach(_=>{\n val Array(a1,k) = readLine.split(\" \").map(_.toLong)\n def transform(a:Long,k:Long):Long = {\n val x = a.toString.split(\"\").map(_.toLong).toList\n if(x.min==0) a\n else if(k==1) a\n else transform(x.min*x.max+a,k-1)\n }\n \n println(transform(a1,k))\n ()\n })\n }\n}"}], "negative_code": [{"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(a1, k) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n var i = 1L\n var ai = a1\n var ds = (a1 % 10, a1 % 10)\n\n do {\n var a = ai\n ds = (a % 10, a % 10)\n while (a != 0 && (ds._1 != 0 || ds._2 != 9)) {\n val d = a % 10\n a /= 10\n ds = (if (d < ds._1) d else ds._1, if (d > ds._2) d else ds._2)\n }\n\n i += 1L\n ai += ds._1 * ds._2\n } while (i < k && (ds._1 != 0 || ds._2 != 9))\n\n println(ai)\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject solver {\n def main(args:Array[String]) = {\n val t:Int = readInt()\n \n (1 to t).foreach(_=>{\n val Array(a1,k) = readLine.split(\" \").map(_.toInt)\n def transform(a:Int,k:Int):Int = {\n val x = a.toString.split(\"\").map(_.toInt).toList\n if(x.min==0) 0\n else if(k==1) a\n else transform(x.min*x.max+a,k-1)\n }\n \n println(transform(a1,k))\n ()\n })\n }\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.annotation.tailrec\n\nobject Main extends App {\n\n @tailrec\n private def perform(start: Long, element: Long, last: Long = -1): Long = {\n (start, element) match {\n case (s, 0) => s\n case (s, _) if s == last => s\n case (s, e) =>\n val sth = ((s.toString.max - '0').toLong * (s.toString.min - '0').toLong) + s\n perform(sth, e - 1, start)\n }\n }\n\n\n def foo(list: List[(Long, Long)]) = {\n list.map(x => perform(x._1, x._2))\n }\n\n val scan = new Scanner(System.in)\n val n = scan.nextLong()\n val seq = for {\n _ <- 0.toLong until n.toLong\n (x, y) = (scan.nextLong(), scan.nextLong())\n } yield x -> y\n\n foo(seq.toList).foreach(println)\n\n}\n"}], "src_uid": "7a48218582b90f735a09083df9e15b96"} {"source_code": "import io.StdIn._\n\nimport scala.collection.mutable._\n\nobject Solution {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n def main(args: Array[String]) {\n val n = readLine().toInt\n\n val a = readInts(n)\n\n val s = HashSet.empty[Int]\n val sb = ArrayBuilder.make[(Int, Int)]()\n\n var k = 0\n var b = 0\n\n for (i <- 0 to n-1) {\n if (s.contains(a(i))) {\n k += 1\n sb += ((b + 1, i + 1))\n s.clear()\n b = i + 1\n } else {\n s.add(a(i))\n }\n }\n\n if (k == 0) println(-1)\n else {\n println(k)\n val res = sb.result()\n res(res.length-1) = (res.last._1, n)\n res.foreach{ case (x, y) => println(x + \" \" + y)}\n }\n\n\n// Console.withOut(new java.io.BufferedOutputStream(Console.out))\n// println(res.mkString(\"\\n\"))\n// Console.flush\n }\n}", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val l = data.indices.foldLeft((Set.empty[Int], List.empty[(Int, Int)], 0)) {\n case ((set, list, start), i) if set.isEmpty => (set + data(i), list, i)\n case ((set, list, start), i) if set.contains(data(i)) => (Set.empty[Int], (start + 1, i + 1) :: list, i)\n case ((set, list, start), i) => (set + data(i), list, start)\n }._2\n if (l.isEmpty)\n println(-1)\n else {\n println(l.length)\n println(l.tail.reverse.map(i => s\"${i._1} ${i._2}\").mkString(\"\\n\"))\n println(s\"${l.head._1} ${data.length}\")\n }\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val l = data.indices.foldLeft((Set.empty[Int], List.empty[(Int, Int)], 0)) {\n case ((set, list, start), i) if set.isEmpty => (set + data(i), list, i)\n case ((set, list, start), i) if set.contains(data(i)) => (Set.empty[Int], (start + 1, i + 1) :: list, i)\n case ((set, list, start), i) => (set + data(i), list, start)\n }._2\n if (l.length == 0)\n println(-1)\n else {\n println(l.length)\n println(l.reverse.map(i => s\"${i._1} ${i._2}\").mkString(\"\\n\"))\n }\n}"}], "src_uid": "4cacec219e4577b255ddf6d39d308e10"} {"source_code": "object _1143A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val isRight = io.read[Vector[Int]].reverse\n\n def chop(x: Int) = isRight.length - isRight.prefixLength(_ == x)\n\n val ans = chop(1) min chop(0)\n \n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "import scala.io.StdIn\nimport scala.math.min\n\nobject A1143 {\n def main(args: Array[String]): Unit = {\n StdIn.readLine\n val a = StdIn.readLine.filter(_!=' ').toArray\n println(1+min(a.lastIndexOf('0'),a.lastIndexOf('1')))\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n import java.util.Arrays\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n var L = A.count(_ == 0)\n var R = N - L\n\n var i = 0\n while(L > 0 && R > 0) {\n if (A(i) == 0) L -= 1\n else R -= 1\n i += 1\n }\n out.println(i)\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import scala.math._, scala.io.StdIn._\n\nobject A extends App {\n val Array(n) = readInts\n val a = readInts\n\n val ar = a.reverse\n\n println(n - max(ar.prefixLength(_==0), ar.prefixLength(_==1)))\n\n def readInts() = readLine.split(\" \").map(_.toInt)\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.util.control.Breaks._\n\nobject Hello extends App {\n\n val n = StdIn.readInt()\n val doors = StdIn.readLine().split(\" \").map(_.trim.toInt)\n breakable { \n for (i <- n - 1 to 1 by -1) {\n if (doors(i) != doors(i - 1)) {\n println(i)\n break\n }\n }\n }\n}"}], "negative_code": [], "src_uid": "653455bb6762effbf7358d75660a7689"} {"source_code": "import java.util.Scanner\nimport scala.collection.immutable._\nimport scala.collection.mutable\n\n/**\n * Created by Andrew on 11-Jul-16.\n */\n\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val format = sc.nextInt()\n val s = sc.next().toCharArray\n if (format == 24) {\n if(s(1) < '4')\n s(0) = List(s(0), '2').min\n else\n s(0) = List(s(0), '1').min\n }\n else {\n if(s(1) < '3')\n s(0) = List(s(0), '1').min\n else\n s(0) = '0'\n }\n s(3) = List(s(3), '5').min\n if(format == 12 && s(0) == '0' && s(1) == '0')\n s(0) = '1'\n\n println(new String(s))\n}", "positive_code": [{"source_code": "object BrokenClock extends App {\n val format = Console.in.readLine().toInt\n val timeDisplayed = Console.in.readLine()\n\n abstract class Clock(time: String) {\n val hourHeadLimit : Int\n def predicate(hour: String): Boolean\n\n // \"00:05\"\n def repairHour(hour: String): String =\n if(predicate(hour)) hour\n else if(hour.last.toString.toInt > 0 ) s\"0${hour.last}\"\n else if(hour.last.toString.toInt == 0 && hour.head.toString.toInt > hourHeadLimit ) s\"1${hour.last}\"\n else s\"0${hour.last.toString.toInt + 1}\"\n\n def repairMinutes(minutes: String): String =\n if(minutes.toInt <= 59 && minutes.toInt >= 0) minutes\n else s\"0${minutes.last}\"\n\n def repair(): String = {\n val (hh, mm): Tuple2[String, String] = time.split(\":\").toList match {\n case x :: y :: Nil => (x, y)\n case _ => (\"00\", \"00\")\n }\n s\"${repairHour(hh)}:${repairMinutes(mm)}\"\n }\n }\n case class Clock12Format(time: String) extends Clock(time) {\n val hourHeadLimit = 1\n def predicate(hour: String): Boolean = hour.toInt <= 12 && hour.toInt > 0\n }\n case class Clock24Format(time: String) extends Clock(time) {\n val hourHeadLimit = 2\n def predicate(hour: String): Boolean = hour.toInt < 24 && hour.toInt >= 0\n }\n\n object TimeFactory {\n def apply(format: Int, time: String): Clock = format match {\n case 12 => Clock12Format(time)\n case 24 => Clock24Format(time)\n }\n }\n\n def execute(fmt: Int, time: String): String = {\n val clock: Clock = TimeFactory(fmt, time)\n clock.repair()\n }\n\n println { execute(format, timeDisplayed) }\n}\n\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val fmt = readLine\n val t = readLine.toCharArray\n\n if (fmt == \"12\") {\n if (t(0) == '0' && t(1) == '0') t(1) = '1'\n if (t(0) == '1' && t(1) > '2') t(1) = '1'\n if (t(0) > '1' && t(1) == '0') {\n t(0) = '1'\n }\n if (t(0) > '1' && t(1) > '0') t(0) = '0'\n } else {\n if (t(0) > '2') t(0) = '0'\n if (t(0) == '2' && t(1) > '3') t(0) = '0'\n }\n\n if (t(3) > '5') t(3) = '0'\n\n println(t.mkString)\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _722A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val f = read[Int]\n val input = read[String]\n\n val all = for {\n h <- if (f == 12) 1 to 12 else 0 to 23\n hh = if (h < 10) \"0\" + h else h.toString\n m <- 0 until 60\n mm = if (m < 10) \"0\" + m else m.toString\n } yield hh + \":\" + mm\n\n val ans = all minBy {choice => choice.zip(input).count {case (a, b) => a != b}}\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.immutable._\nimport scala.collection.mutable\n\nobject test extends App {\n\tval sc = new Scanner(System.in)\n\n\tval format = sc.nextInt()\n\tval clockTime = sc.next().toCharArray\n\n\tif (clockTime(3) > '5')\n\t\tclockTime(3) = '5'\n\tif (format == 24) {\n\t\tif (clockTime(1) < '4')\n\t\t\tclockTime(0) = List(clockTime(0), '2').min\n\t\telse\n\t\t\tclockTime(0) = List(clockTime(0), '1').min\n\t}\n\telse {\n\t\tclockTime(0) = {\n\t\t\tif (clockTime(1) < '3')\n\t\t\t\tList(clockTime(0), '1').min\n\t\t\telse\n\t\t\t\t'0'\n\t\t}\n\t\tif (clockTime(1) == '0' && clockTime(0) == '0')\n\t\t\tclockTime(0) = '1'\n\t}\n\n\tprintln(new String(clockTime))\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val format = in.next().toInt\n val Array(hours, minutes) = in.next().split(\":\")\n val fixedMinutes = if (minutes.toInt >= 60) s\"0${minutes.last}\" else minutes\n val fixedHours =\n if (format == 12 && hours == \"00\") s\"01\"\n else if (format == 12 && hours.toInt > format && hours.last == '0') s\"10\" \n else if (format == 12 && hours.toInt > format) s\"0${hours.last}\"\n else if (hours.toInt >= 24) s\"0${hours.last}\" else hours\n\n println(s\"$fixedHours:$fixedMinutes\")\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val format = in.next().toInt\n val Array(hours, minutes) = in.next().split(\":\")\n val fixedMinutes = if (minutes.toInt >= 60) s\"0${minutes.last}\" else minutes\n val fixedHours =\n if (format == 12 && hours == \"00\") s\"01\"\n else if (format == 12 && hours.toInt > format && hours.last == 0) s\"10\" \n else if (format == 12 && hours.toInt > format) s\"0${hours.last}\"\n else if (hours.toInt >= 24) s\"0${hours.last}\" else hours\n\n println(s\"$fixedHours:$fixedMinutes\")\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val format = in.next().toInt\n val Array(hours, minutes) = in.next().split(\":\")\n val fixedMinutes = if (minutes.toInt >= 60) s\"0${minutes.last}\" else minutes\n val fixedHours =\n if (format == 12 && hours == \"00\") s\"01\"\n else if (hours.toInt >= format) s\"0${hours.last}\" else hours\n\n println(s\"$fixedHours:$fixedMinutes\")\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val format = in.next().toInt\n val Array(hours, minutes) = in.next().split(\":\")\n val fixedMinutes = if (minutes.toInt >= 60) s\"0${minutes.last}\" else minutes\n val fixedHours = if (hours.toInt >= format) s\"0${hours.last}\" else hours\n println(s\"$fixedHours:$fixedMinutes\")\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.immutable._\nimport scala.collection.mutable\n\n/**\n * Created by Andrew on 11-Jul-16.\n */\n\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val format = sc.nextInt()\n val s = sc.next().toCharArray\n if (format == 24) {\n if(s(1) < '4')\n s(0) = List(s(0), '2').min\n else\n s(0) = List(s(0), '1').min\n }\n else {\n if(s(1) < '3')\n s(0) = List(s(0), '1').min\n else\n s(0) = '0'\n }\n if(s(4) == '0')\n s(3) = List(s(3), '6').min\n else\n s(3) = List(s(3), '5').min\n if(format == 12 && s(0) == '0' && s(1) == '0')\n s(0) = '1'\n\n println(new String(s))\n}"}, {"source_code": "object BrokenClock extends App {\n val format = Console.in.readLine().toInt\n val timeDisplayed = Console.in.readLine()\n\n abstract class Clock(time: String) {\n def predicate(hour: String): Boolean\n\n def repairHour(hour: String): String =\n if(predicate(hour)) hour\n else s\"0${hour.last}\"\n \n def repairMinutes(minutes: String): String =\n if(minutes.toInt <= 59 && minutes.toInt >= 0) minutes\n else s\"0${minutes.last}\"\n\n def repair(): String = {\n val (hh, mm): Tuple2[String, String] = time.split(\":\").toList match {\n case x :: y :: Nil => (x, y)\n case _ => (\"00\", \"00\")\n }\n s\"${repairHour(hh)}:${repairMinutes(mm)}\"\n }\n }\n case class Clock12Format(time: String) extends Clock(time) {\n def predicate(hour: String): Boolean = hour.toInt <= 12 && hour.toInt >= 0\n }\n case class Clock24Format(time: String) extends Clock(time) {\n def predicate(hour: String): Boolean = hour.toInt <= 24 && hour.toInt >= 0\n }\n\n object TimeFactory {\n def apply(format: Int, time: String): Clock = format match {\n case 12 => Clock12Format(time)\n case 24 => Clock24Format(time)\n }\n }\n\n def execute(fmt: Int, time: String): String = {\n val clock: Clock = TimeFactory(fmt, time)\n clock.repair()\n }\n\n println { execute(format, timeDisplayed) }\n}\n\n"}, {"source_code": "object BrokenClock extends App {\n val format = Console.in.readLine().toInt\n val timeDisplayed = Console.in.readLine()\n\n abstract class Clock(time: String) {\n def predicate(hour: String): Boolean\n\n def repairHour(hour: String): String =\n if(predicate(hour)) hour\n else if(hour.last.toString.toInt > 0 ) s\"0${hour.last}\"\n else s\"0${hour.last.toString.toInt + 1}\"\n\n def repairMinutes(minutes: String): String =\n if(minutes.toInt <= 59 && minutes.toInt >= 0) minutes\n else s\"0${minutes.last}\"\n\n def repair(): String = {\n val (hh, mm): Tuple2[String, String] = time.split(\":\").toList match {\n case x :: y :: Nil => (x, y)\n case _ => (\"00\", \"00\")\n }\n s\"${repairHour(hh)}:${repairMinutes(mm)}\"\n }\n }\n case class Clock12Format(time: String) extends Clock(time) {\n def predicate(hour: String): Boolean = hour.toInt <= 12 && hour.toInt > 0\n }\n case class Clock24Format(time: String) extends Clock(time) {\n def predicate(hour: String): Boolean = hour.toInt <= 24 && hour.toInt >= 0\n }\n\n object TimeFactory {\n def apply(format: Int, time: String): Clock = format match {\n case 12 => Clock12Format(time)\n case 24 => Clock24Format(time)\n }\n }\n\n def execute(fmt: Int, time: String): String = {\n val clock: Clock = TimeFactory(fmt, time)\n clock.repair()\n }\n\n println { execute(format, timeDisplayed) }\n}\n\n"}, {"source_code": "object BrokenClock extends App {\n val format = Console.in.readLine().toInt\n val timeDisplayed = Console.in.readLine()\n\n abstract class Clock(time: String) {\n def predicate(hour: Int): Boolean\n def repairHour(hour: Int): String = hour match {\n case hh if predicate(hh) => hh.toString\n case hh =>\n val (decena, unidad) = (hh.toString.head, hh.toString.last)\n s\"0$unidad\"\n }\n def repairMinutes(minutes: Int): String = minutes match {\n case mm if mm <= 59 && mm >= 0 => mm.toString\n case mm =>\n val unidad = mm.toString.last\n s\"0$unidad\"\n }\n def repair(): String = {\n val (hh, mm): Tuple2[Int, Int] = time.split(\":\").map(_.toInt).toList match {\n case x :: y :: Nil => (x, y)\n case _ => (0, 0)\n }\n s\"${repairHour(hh)}:${repairMinutes(mm)}\"\n }\n }\n case class Clock12Format(time: String) extends Clock(time) {\n def predicate(hour: Int): Boolean = hour <= 12 && hour >= 0\n }\n case class Clock24Format(time: String) extends Clock(time) {\n def predicate(hour: Int): Boolean = hour <= 24 && hour >= 0\n }\n\n object TimeFactory {\n def apply(format: Int, time: String): Clock = format match {\n case 12 => Clock12Format(time)\n case 24 => Clock24Format(time)\n }\n }\n\n def execute(fmt: Int, time: String): String = {\n val clock: Clock = TimeFactory(fmt, time)\n clock.repair()\n }\n\n println { execute(format, timeDisplayed) }\n}\n\n"}, {"source_code": "object BrokenClock extends App {\n val format = Console.in.readLine().toInt\n val timeDisplayed = Console.in.readLine()\n\n abstract class Clock(time: String) {\n val hourHeadLimit : Int\n def predicate(hour: String): Boolean\n\n // \"00:05\"\n def repairHour(hour: String): String =\n if(predicate(hour)) hour\n else if(hour.last.toString.toInt > 0 ) s\"0${hour.last}\"\n else if(hour.last.toString.toInt == 0 && hour.head.toString.toInt > hourHeadLimit ) s\"1${hour.last}\"\n else s\"0${hour.last.toString.toInt + 1}\"\n\n def repairMinutes(minutes: String): String =\n if(minutes.toInt <= 59 && minutes.toInt >= 0) minutes\n else s\"0${minutes.last}\"\n\n def repair(): String = {\n val (hh, mm): Tuple2[String, String] = time.split(\":\").toList match {\n case x :: y :: Nil => (x, y)\n case _ => (\"00\", \"00\")\n }\n s\"${repairHour(hh)}:${repairMinutes(mm)}\"\n }\n }\n case class Clock12Format(time: String) extends Clock(time) {\n val hourHeadLimit = 1\n def predicate(hour: String): Boolean = hour.toInt <= 12 && hour.toInt > 0\n }\n case class Clock24Format(time: String) extends Clock(time) {\n val hourHeadLimit = 2\n def predicate(hour: String): Boolean = hour.toInt <= 24 && hour.toInt >= 0\n }\n\n object TimeFactory {\n def apply(format: Int, time: String): Clock = format match {\n case 12 => Clock12Format(time)\n case 24 => Clock24Format(time)\n }\n }\n\n def execute(fmt: Int, time: String): String = {\n val clock: Clock = TimeFactory(fmt, time)\n clock.repair()\n }\n\n println { execute(format, timeDisplayed) }\n}\n\n"}, {"source_code": "object BrokenClock extends App {\n val format = Console.in.readLine().toInt\n val timeDisplayed = Console.in.readLine()\n\n abstract class Clock(time: String) {\n def predicate(hour: String): Boolean\n\n def repairHour(hour: String): String =\n if(predicate(hour)) hour\n else if(hour.last.toString.toInt > 0 ) s\"0${hour.last}\"\n else s\"0${hour.last.toString.toInt + 1}\"\n\n def repairMinutes(minutes: String): String =\n if(minutes.toInt <= 59 && minutes.toInt >= 0) minutes\n else if(minutes.last.toString.toInt > 0 ) s\"0${minutes.last}\"\n else s\"0${minutes.last.toString.toInt + 1}\"\n\n def repair(): String = {\n val (hh, mm): Tuple2[String, String] = time.split(\":\").toList match {\n case x :: y :: Nil => (x, y)\n case _ => (\"00\", \"00\")\n }\n s\"${repairHour(hh)}:${repairMinutes(mm)}\"\n }\n }\n case class Clock12Format(time: String) extends Clock(time) {\n def predicate(hour: String): Boolean = hour.toInt <= 12 && hour.toInt > 0\n }\n case class Clock24Format(time: String) extends Clock(time) {\n def predicate(hour: String): Boolean = hour.toInt <= 24 && hour.toInt >= 0\n }\n\n object TimeFactory {\n def apply(format: Int, time: String): Clock = format match {\n case 12 => Clock12Format(time)\n case 24 => Clock24Format(time)\n }\n }\n\n def execute(fmt: Int, time: String): String = {\n val clock: Clock = TimeFactory(fmt, time)\n clock.repair()\n }\n\n println { execute(format, timeDisplayed) }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _722A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val f = read[Int]\n var Array(h, m) = read[String].split(':')\n var ans = 0\n\n if(m.toInt > 59) {\n ans += 1\n m = \"0\" + m(1)\n }\n\n if(h.toInt > f) {\n ans += 1\n h = \"0\" + h(1)\n }\n\n write(h + \":\" + m)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "88d56c1e3a7ffa94354ce0c70d8e958f"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n // l <= r\n var l = 0\n var r = 0\n REP(ni()) { _ =>\n val tpe = nc()\n if (tpe == '+') {\n val x, y = ni()\n l = max(l, min(x, y))\n r = max(r, max(x, y))\n } else {\n val h, w = ni()\n if (min(h, w) >= l && max(h, w) >= r) out.println(\"YES\")\n else out.println(\"NO\")\n }\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object EDU_58_E {\n\n type In = (Seq[String])\n type Out = Seq[String]\n type Data = (String, Int, Int)\n\n def solve(in: In): Out = {\n val (xs) = in\n\n val as: Seq[Data] =\n xs.map(_.split(\" \") match {case Array(op, x, y) => (op, x.toInt, y.toInt)})\n\n def loop(lines: Seq[Data], longmax: Int, shortmax: Int, out: Seq[String]): Seq[String] = lines match {\n case Seq() => out\n case line +: rest => line match {\n case (\"+\", x, y) => loop(rest, longmax max (x max y), shortmax max (x min y), out)\n case (\"?\", h, w) =>\n val s = if (longmax <= (h max w) && shortmax <= (h min w)) \"YES\" else \"NO\"\n loop(rest, longmax, shortmax, out :+ s)\n }\n }\n\n loop(as, 0, 0, Vector.empty)\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = i.getLines(i.int)\n def formatOut(out: Out): String = out.mkString(\"\\n\")\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change: \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def ceil(a: Int, b: Int) = (a - 1)/b + 1\n def ceil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}"}], "negative_code": [], "src_uid": "fe939f7503f928ff4dbe8d05c5643f38"} {"source_code": "object _1176B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val inputs = io.read[Seq[Seq[Int]]]\n val ans = inputs.map(solve)\n io.writeLines(ans)\n }\n\n def solve(input: Seq[Int]) = {\n val table = input\n .groupBy(_%3)\n .mapValues(_.length)\n .withDefaultValue(0)\n val rest = if (table(2) > table(1)) {\n table(1) + (table(2) - table(1))/3\n } else {\n table(2) + (table(1) - table(2))/3\n }\n table(0) + rest\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "import java.util\nimport java.util.Scanner\n\nimport scala.io.StdIn\n\nobject Btask565 extends App {\n\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n\n val q = new util.ArrayList[Int]()\n\n\n for (i <- 0 until n) {\n line = new Scanner(StdIn.readLine())\n val q = line.nextInt()\n var x = StdIn.readLine().split(' ').map(_.toInt)\n\n var count0 = 0\n var count1 = 0\n var count2 = 0\n\n for (i <- 0 until q) {\n val temp = x(i) % 3\n if (temp == 0) {\n count0 += 1\n }\n if (temp == 1) {\n count1 += 1\n }\n if (temp == 2) {\n count2 += 1\n }\n }\n var result = 0\n if (count1 == count2) {\n result = count0 + ((count1 + count2) / 2)\n println(result)\n } else {\n if (count1 > count2) {\n result = count0 + count2 + ((count1 - count2) / 3)\n println(result)\n } else {\n result = count0 + count1 + ((count2 - count1) / 3)\n println(result)\n }\n }\n }\n }\n"}, {"source_code": "object CF565B extends App {\n\n import scala.io.StdIn\n\n val t = StdIn.readInt\n for (_ <- 0 until t) {\n val n = StdIn.readInt\n val as = StdIn.readLine.split(\" \").map(_.toInt)\n\n val mod3_0 = as.count(_ % 3 == 0)\n val mod3_1 = as.count(_ % 3 == 1)\n val mod3_2 = as.count(_ % 3 == 2)\n\n val combine1_2 = Math.min(mod3_1, mod3_2)\n\n val remaining1 = (mod3_1 - combine1_2) / 3\n val remaining2 = (mod3_2 - combine1_2) / 3\n\n println(mod3_0 + combine1_2 + remaining1 + remaining2)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val q = readInt\n (1 to q).map(_ => {\n val n = readInt\n val s = readLine.split(\" \").map(_.toInt).map(x => x % 3)\n val cnt3 = s.count(_ == 0)\n val cnt1 = s.count(_ == 1)\n val cnt2 = s.count(_ == 2)\n if (cnt1 > cnt2) {\n println(cnt3 + cnt2 + (cnt1 - cnt2) / 3)\n } else {\n println(cnt3 + cnt1 + (cnt2 - cnt1) / 3)\n }\n })\n }\n}\n\n"}], "negative_code": [], "src_uid": "e59cddb6c941b1d7556ee9c020701007"} {"source_code": "object B {\n\n /** TODO: Check! */\n private val multipleTests: Boolean = true\n\n def run(testNum: Int): Unit = {\n val n = int()\n val r = (1 to n).map(_ => Seq.fill(5)(int()))\n\n def winner(i: Int, j: Int): Int =\n if (r(i).zip(r(j)).count { case (a, b) => a < b } >= 3) i else j\n\n val potential = (1 until n).foldLeft(0) { case (ac, i) => winner(ac, i) }\n val won = (0 until n).count(i => winner(potential, i) == i) == 1\n println(if (won) potential + 1 else -1)\n }\n\n /** Template. */\n\n private val onlineJudge = System.getProperty(\"ONLINE_JUDGE\") != null\n\n def main(args: Array[String]): Unit = {\n val t = if (multipleTests) reader.int() else 1\n (1 to t).foreach(run)\n }\n\n /** I/O. */\n\n import java.io._\n import java.nio.file._\n\n private val inputFileName = \"input.txt\"\n private val reader = if (onlineJudge) FastReader.fromConsole() else FastReader.fromFile(inputFileName)\n\n private def string(): String = reader.string()\n private def int(): Int = reader.int()\n private def long(): Long = reader.long()\n private def double(): Double = reader.double()\n\n final case class FastReader(delegate: BufferedReader) extends Iterator[String] with AutoCloseable {\n import java.util.StringTokenizer\n\n def string(): String = next()\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def boolean(): Boolean = next().toBoolean\n def byte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def short(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def int(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def long(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def bigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def float(): Float = next().toFloat\n def double(): Double = next().toDouble\n def bigDecimal(): BigDecimal = BigDecimal(next())\n def lineNumber(): Int = linedDelegate.getLineNumber\n\n @inline def nextLine(): String = {\n current = None // reset the rest of current line\n delegate.readLine()\n }\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n override def next(): String = tokenizer().getOrElse(throw new RuntimeException(\"End of input\")).nextToken()\n override def close(): Unit = delegate.close()\n\n private lazy val linedDelegate = new LineNumberReader(delegate)\n private val tokenizers = Iterator.continually(delegate.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n }\n\n object FastReader {\n import scala.io.Codec\n\n def fromConsole()(implicit codec: Codec): FastReader = fromStream(System.in)\n def fromFile(fileName: String)(implicit codec: Codec): FastReader = FastReader {\n Files.newBufferedReader(Paths.get(fileName), codec.charSet)\n }\n def fromString(string: String): FastReader = FastReader(new BufferedReader(new StringReader(string)))\n def fromStream(inputStream: InputStream)(implicit codec: Codec): FastReader = FastReader {\n new BufferedReader(new InputStreamReader(inputStream, codec.charSet))\n }\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val ranks = Array.fill(n)(readLine().split(\" \").map(_.toInt))\r\n\r\n def compare(i: Int, j: Int): Boolean = (ranks(i) zip ranks(j)).count { case (a, b) => a <= b } >= 3\r\n\r\n val athlete = {\r\n val i = (1 until n).foldLeft(0) { (i, j) => if (compare(j, i)) j else i }\r\n (0 until n).forall(j => compare(i, j)) match {\r\n case true => Some(i)\r\n case _ => None\r\n }\r\n }\r\n\r\n athlete match {\r\n case Some(i) => println(i + 1)\r\n case _ => println(-1)\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import scala.collection.mutable\n\nobject B {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val t = nextInt\n val res = Array.fill(t)(1)\n\n case class A(r: Array[Int], idx: Int) extends Comparable[A] {\n override def compareTo(o: A): Int = {\n var i, l, g = 0\n while (i < 5) {\n if (r(i) < o.r(i)) l += 1\n else if (r(i) > o.r(i)) g += 1\n i += 1\n }\n if (l >= 3) -1\n else if (g >= 3) 1\n else 0\n }\n }\n\n for (test <- 0 until t) {\n val n = nextInt\n val rs = Array.tabulate(n) { i => A(nextInts(5), i) }\n\n if (n > 1) {\n val pq = new java.util.PriorityQueue[A]\n for (r <- rs) pq.add(r)\n val top = pq.peek()\n var ok = true\n for (i <- rs.indices) {\n if (top.idx != rs(i).idx && top.compareTo(rs(i)) >= 0) {\n ok = false\n }\n }\n if (ok) res(test) = top.idx + 1\n else res(test) = -1\n }\n\n }\n\n out.println(res.mkString(\"\\n\"))\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val ranks = Array.fill(n)(readLine().split(\" \").map(_.toInt))\r\n val marathons = ranks.transpose.map(_.zipWithIndex.sorted)\r\n\r\n val counts = Array.fill(n)(0L)\r\n marathons.foreach { marathon =>\r\n marathon.indices.foreach { i =>\r\n val (_, athlete) = marathon(i)\r\n counts(athlete) += n - i - 1L\r\n }\r\n }\r\n\r\n val athlete = {\r\n val (_, i) = counts.zipWithIndex.maxBy(_._1)\r\n\r\n (0 until n).forall { j =>\r\n (0 until 5).count(k => ranks(i)(k) <= ranks(j)(k)) >= 3\r\n } match {\r\n case true => Some(i + 1)\r\n case _ => None\r\n }\r\n }\r\n\r\n athlete match {\r\n case Some(i) => println(i)\r\n case _ => println(-1)\r\n }\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val ranks = Array.fill(n)(readLine().split(\" \").map(_.toInt))\r\n val marathons = ranks.transpose.map(_.zipWithIndex.sorted)\r\n\r\n val counts = Array.fill(n)(0)\r\n marathons.foreach { marathon =>\r\n marathon.indices.foreach { i =>\r\n val (_, athlete) = marathon(i)\r\n counts(athlete) += n - i - 1\r\n }\r\n }\r\n\r\n val athlete = {\r\n val (_, i) = counts.zipWithIndex.maxBy(_._1)\r\n\r\n (0 until n).forall { j =>\r\n (0 until 5).count(k => ranks(i)(k) <= ranks(j)(k)) >= 3\r\n } match {\r\n case true => Some(i + 1)\r\n case _ => None\r\n }\r\n }\r\n\r\n athlete match {\r\n case Some(i) => println(i)\r\n case _ => println(-1)\r\n }\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val ms =\r\n Array\r\n .fill(n)(readLine().split(\" \").map(_.toInt))\r\n .transpose\r\n .map(_.zipWithIndex.sorted)\r\n\r\n val counts = {\r\n val cs = Array.fill(n)(0)\r\n\r\n ms.foreach { m =>\r\n m.indices.foreach { i =>\r\n val (_, athlete) = m(i)\r\n cs(athlete) += n - i - 1\r\n }\r\n }\r\n\r\n cs.zipWithIndex.sortBy(_._1)(Ordering[Int].reverse)\r\n }\r\n\r\n val (count, athlete) = counts.head\r\n\r\n if (count >= 3 * (n - 1) && counts.tail.forall { case (c, _) => count - c > 2 })\r\n println(athlete + 1)\r\n else\r\n println(-1)\r\n }\r\n}\r\n"}], "src_uid": "8d9fc054fb1541b70991661592ae70b1"} {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").view.map(_.toInt)\n\n val status = (an zip an.tail).exists { case (a, b) => a <= b }\n\n val ans = status match {\n case true => \"YES\"\n case _ => \"NO\"\n }\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val t = readInt\n (0 until t).foreach { k =>\n val n = readInt\n val a = readLine.split(\" \").map(_.toInt)\n val d = a.sortBy(x => -x)\n if ((d.distinct.size == n) && (d.sameElements(a))) println(\"NO\") else println(\"YES\")\n }\n }\n}\n"}], "negative_code": [{"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readLong()\n val an = readLine().split(\" \").map(_.toInt)\n val bn = an.sorted\n\n val count = (an zip bn).count { case (a, b) => a != b }\n val ans = if ((count + 1) / 2 <= n * (n - 1) / 2 - 1) \"YES\" else \"NO\"\n\n println(ans)\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readLong()\n val an = readLine().split(\" \").map(_.toInt)\n val bn = an.sorted\n\n val count = (an zip bn).count { case (a, b) => a != b }\n val ans = if (count <= n * (n - 1) / 2 - 1) \"YES\" else \"NO\"\n\n println(ans)\n }\n}\n"}], "src_uid": "b34f29e6fb586c22fa1b9e559c5a6c50"} {"source_code": "object C544{\n def main(args: Array[String]){\n\n val Array(n,m,b,mod)=readLine.split(\" \").map(_.toInt)\n\n val A=readLine.split(\" \").map(_.toInt)\n val dp=Array.ofDim[Int](2,m+10,b+10)\n //println(\"hic\")\n dp(0)(0)(0)=1\n for (i <- 1 to n){\n for(j <- 0 to m){\n for(k <- 0 to b){\n dp(i&1)(j)(k)=dp(1-(i&1))(j)(k)\n if(j>0&&k>=A(i-1)){\n dp(i&1)(j)(k)+=(dp(i&1)(j-1)(k-A(i-1)))\n }\n dp(i&1)(j)(k)%=mod\n }\n }\n }\n var ans:Int=0\n for(i<-0 to b){\n ans+=dp(n&1)(m)(i)\n ans%=mod\n }\n println(ans)\n }\n}", "positive_code": [{"source_code": "object C544{\n def main(args: Array[String]){\n \n var Array(n,m,b,mod)=readLine.split(\" \").map(_.toInt)\n \n var A=readLine.split(\" \").map(_.toInt)\n var dp=Array.ofDim[Int](2,m+10,b+10)\n //println(\"hic\")\n dp(0)(0)(0)=1\n for (i <- 1 to n){\n for(j <- 0 to m){\n for(k <- 0 to b){\n dp(i&1)(j)(k)=dp(1-(i&1))(j)(k)\n if(j>0&&k>=A(i-1)){\n dp(i&1)(j)(k)+=(dp(i&1)(j-1)(k-A(i-1)))\n }\n dp(i&1)(j)(k)%=mod\n }\n }\n }\n var ans:Int=0\n for(i<-0 to b){\n ans+=dp(n&1)(m)(i)\n ans%=mod\n }\n println(ans)\n }\n}"}, {"source_code": "object C544{\n def main(args: Array[String]){\n \n val Array(n,m,b,mod)=readLine.split(\" \").map(_.toInt)\n \n val A=readLine.split(\" \").map(_.toInt)\n var dp=Array.ofDim[Int](2,m+10,b+10)\n //println(\"hic\")\n dp(0)(0)(0)=1\n for (i <- 1 to n){\n for(j <- 0 to m){\n for(k <- 0 to b){\n dp(i&1)(j)(k)=dp(1-(i&1))(j)(k)\n if(j>0&&k>=A(i-1)){\n dp(i&1)(j)(k)+=(dp(i&1)(j-1)(k-A(i-1)))\n }\n dp(i&1)(j)(k)%=mod\n }\n }\n }\n var ans:Int=0\n for(i<-0 to b){\n ans+=dp(n&1)(m)(i)\n ans%=mod\n }\n println(ans)\n }\n}"}, {"source_code": "object C544{\n def main(args: Array[String]){\n\n val Array(n,m,b,mod)=readLine.split(\" \").map(_.toInt)\n\n val A=readLine.split(\" \").map(_.toInt)\n var dp=Array.ofDim[Int](2,m+10,b+10)\n //println(\"hic\")\n dp(0)(0)(0)=1\n for (i <- 1 to n){\n for(j <- 0 to m){\n for(k <- 0 to b){\n dp(i&1)(j)(k)=dp(1-(i&1))(j)(k)\n if(j>0&&k>=A(i-1)){\n dp(i&1)(j)(k)+=(dp(i&1)(j-1)(k-A(i-1)))\n }\n dp(i&1)(j)(k)%=mod\n }\n }\n }\n var ans:Int=0\n for(i<-0 to b){\n ans+=dp(n&1)(m)(i)\n ans%=mod\n }\n println(ans)\n }\n}\n"}, {"source_code": "object C544 {\n def main(args: Array[String]) {\n val Array(n, m, b, mod) = readLine.split(\" \").map(_.toInt)\n val A = readLine.split(\" \").map(_.toInt)\n val dp = Array.ofDim[Int](2, m + 10, b + 10)\n dp(0)(0)(0) = 1\n for (i <- 1 to n) {\n for (j <- 0 to m) {\n for (k <- 0 to b) {\n dp(i & 1)(j)(k) = dp(1 - (i & 1))(j)(k)\n if (j > 0 && k >= A(i - 1)) {\n dp(i & 1)(j)(k) += (dp(i & 1)(j - 1)(k - A(i - 1)))\n }\n dp(i & 1)(j)(k) %= mod\n }\n }\n }\n var ans: Int = 0\n for (i <- 0 to b) {\n ans += dp(n & 1)(m)(i)\n ans %= mod\n }\n println(ans)\n }\n }"}, {"source_code": "object C544{\n def main(args: Array[String]){\n\n var Array(n,m,b,mod)=readLine.split(\" \").map(_.toInt)\n\n var A=readLine.split(\" \").map(_.toInt)\n val dp=Array.ofDim[Int](2,m+10,b+10)\n //println(\"hic\")\n dp(0)(0)(0)=1\n for (i <- 1 to n){\n for(j <- 0 to m){\n for(k <- 0 to b){\n dp(i&1)(j)(k)=dp(1-(i&1))(j)(k)\n if(j>0&&k>=A(i-1)){\n dp(i&1)(j)(k)+=(dp(i&1)(j-1)(k-A(i-1)))\n }\n dp(i&1)(j)(k)%=mod\n }\n }\n }\n var ans:Int=0\n for(i<-0 to b){\n ans+=dp(n&1)(m)(i)\n ans%=mod\n }\n println(ans)\n }\n}"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.Ordering.Implicits._\nimport scala.collection.mutable.ArrayBuffer\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def lowerBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (!(array(mid) < value)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n\n def solve(): Unit = {\n val (n, m, b, mod) = (nextInt, nextInt, nextInt, nextInt)\n val dp = Array.ofDim[Int](m + 1, b + 1)\n val a: Array[Int] = new Array(n)\n for (i <- 0 until n) {\n a(i) = nextInt\n }\n dp(0)(0) = 1\n for (k <- 0 until n) {\n for (i <- 0 until m) {\n for (j <- 0 to b) {\n if (j + a(k) <= b) {\n dp(i + 1)(j + a(k)) += dp(i)(j)\n dp(i + 1)(j + a(k)) %= mod\n }\n }\n }\n }\n var res = 0\n for (i <- 0 to b) {\n res += dp(m)(i)\n res %= mod\n }\n out.println(res)\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve()\n out.close\n }\n}\n"}, {"source_code": "object C544{\n def main(args: Array[String]){\n\n val Array(n,m,b,mod)=readLine.split(\" \").map(_.toInt)\n\n val A=readLine.split(\" \").map(_.toInt)\n val dp=Array.ofDim[Int](2,m+10,b+10)\n //println(\"hic\")\n dp(0)(0)(0)=1\n for (i <- 1 to n){\n for(j <- 0 to m){\n for(k <- 0 to b){\n dp(i&1)(j)(k)=dp(1-(i&1))(j)(k)\n if(j>0&&k>=A(i-1)){\n dp(i&1)(j)(k)+=(dp(i&1)(j-1)(k-A(i-1)))\n }\n dp(i&1)(j)(k)%=mod\n }\n }\n }\n var ans:Int=0\n for(i<-0 to b){\n ans+=dp(n&1)(m)(i)\n ans%=mod\n }\n println(ans)\n }\n}"}, {"source_code": "object C544{\n def main(args: Array[String]){\n\n val Array(n,m,b,mod)=readLine.split(\" \").map(_.toInt)\n\n val A=readLine.split(\" \").map(_.toInt)\n val dp=Array.ofDim[Int](2,m+10,b+10)\n //println(\"hic\")\n dp(0)(0)(0)=1\n for (i <- 1 to n){\n for(j <- 0 to m){\n for(k <- 0 to b){\n dp(i&1)(j)(k)=dp(1-(i&1))(j)(k)\n if(j>0&&k>=A(i-1)){\n dp(i&1)(j)(k)+=(dp(i&1)(j-1)(k-A(i-1)))\n }\n dp(i&1)(j)(k)%=mod\n }\n }\n }\n var ans:Int=0\n for(i<-0 to b){\n ans+=dp(n&1)(m)(i)\n ans%=mod\n }\n println(ans)\n }\n}"}, {"source_code": "/**\n * Created by canoe on 5/17/15.\n */\n\nobject CF544A {\n def main(args: Array[String]) {\n val Array(n, m, b, mod) = readLine().split(\" \").map(_.toInt)\n val A = readLine().split(\" \").map(_.toInt)\n val dp = Array.ofDim[Int](2, m + 8, b + 8)\n\n dp(0)(0)(0) = 1\n for (i <- 1 to n) {\n for (j <- 0 to m) {\n for (k <- 0 to b) {\n dp(i & 1)(j)(k) = dp(1 - (i & 1))(j)(k)\n if (k >= A(i - 1) && j >= 1) {\n dp(i & 1)(j)(k) += dp(i & 1)(j - 1)(k - A(i - 1))\n }\n dp(i & 1)(j)(k) %= mod\n }\n }\n }\n\n var answer: Int = 0\n for (i <- 0 to b) {\n answer += dp(n & 1)(m)(i)\n answer %= mod;\n }\n println(answer)\n }\n}\n"}], "negative_code": [{"source_code": "object C544{\n def main(args: Array[String]){\n\n var Array(n,m,b,mod)=readLine.split(\" \").map(_.toInt)\n\n var A=readLine.split(\" \").map(_.toInt)\n var dp=Array.ofDim[Int](n+10,m+10,b+10)\n //println(\"hic\")\n dp(0)(0)(0)=1\n for (i <- 1 to n){\n for(j <- 0 to m){\n for(k <- 0 to b){\n dp(i)(j)(k)=dp(i-1)(j)(k)\n if(j>0&&k>=A(i-1)){\n dp(i)(j)(k)+=(dp(i)(j-1)(k-A(i-1)))\n }\n dp(i)(j)(k)%=mod\n }\n }\n }\n println(dp(n)(m)(b))\n }\n}\n"}], "src_uid": "139febdb9c01bf0e6598fdf65a1a522c"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val n = ni()\n var a, b, c = ni()\n val s = ns(n)\n var ans = 0\n val hands = Array.fill[Char](n)('a')\n REP(n) { i =>\n s(i) match {\n case 'R' =>\n if (b > 0) {\n ans += 1\n b -= 1\n hands(i) = 'P'\n }\n\n case 'P' =>\n if (c > 0) {\n ans += 1\n c -= 1\n hands(i) = 'S'\n }\n\n case _ =>\n if (a > 0) {\n ans += 1\n a -= 1\n hands(i) = 'R'\n }\n }\n }\n val line = (n + 1) / 2\n val ok = ans >= line\n if (!ok) out.println(\"NO\")\n else {\n out.println(\"YES\")\n REP(n) { i =>\n if (hands(i) == 'a') {\n hands(i) = if (a > 0) {\n a -= 1\n 'R'\n } else if (b > 0) {\n b -= 1\n 'P'\n } else {\n c -= 1\n 'S'\n }\n }\n }\n out.println(hands.mkString)\n }\n }\n }\n}", "positive_code": [{"source_code": "object _1245B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(implicit io: IO): io.type = repeat {\n val n = io.read[Int]\n var r, p, s = io.read[Int]\n val bob = io.read[String]\n\n def rock() = when(r > 0) {r -= 1; 'R'}\n def paper() = when(p > 0) {p -= 1; 'P'}\n def scissor() = when(s > 0) {s -= 1; 'S'}\n\n val ans = Array.fill(n)('X')\n var wins = 0\n\n for {\n i <- bob.indices\n a <- bob(i) match {\n case 'R' => paper()\n case 'P' => scissor()\n case 'S' => rock()\n }\n } {\n wins += 1\n ans(i) = a\n }\n\n for {\n i <- ans.indices if ans(i) == 'X'\n a <- rock() orElse paper() orElse scissor()\n } {\n wins -= 1\n ans(i) = a\n }\n\n if (wins >= 0) {\n io.writeLine(\"YES\").writeLine(ans.mkString)\n } else {\n io.writeLine(\"NO\")\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(implicit io: IO): io.type\n def repeat(f: => Unit)(implicit io: IO): io.type = {Utils.repeat(io.read[Int])(f); io}\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "bee33afb70e4c3e062ec7980b44cc0dd"} {"source_code": "/**\n * @author tdx\n */\nobject Main {\n import scala.math._\n import scala.collection.mutable._\n import java.io.{File, FileInputStream, InputStreamReader}\n import java.util.Scanner\n\n // !!!! CHANGE to LOCAL = true before submit !!!!\n val LOCAL = false\n// val LOCAL = true\n\n def D(x: => Unit): Unit = {\n if (LOCAL) {\n try {\n x\n } catch {\n case e: Throwable => println(\"Error: \" + e.getLocalizedMessage)\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n val MOD = (pow(10, 9) + 7).toInt\n val sc = new Scanner(new InputStreamReader(if (LOCAL) new FileInputStream(new File(\"input\")) else System.in))\n val n = sc.nextInt()\n val arr = ArrayBuffer[Int]()\n for (_ <- 1 to n) {\n arr.append(sc.nextInt())\n }\n\n val sorted = arr.sorted\n var res = 0L\n\n D(println(sorted))\n\n for (i <- 0 until n - 1) {\n res = (res + (powMod(2, i + 1, MOD) - 1) * (powMod(2, n - i - 1, MOD) - 1) % MOD * (sorted(i + 1) - sorted(i))) % MOD\n D(println(i, res))\n }\n\n println(res)\n }\n\n def powMod(a: Int, p: Int, MOD: Int): Long = {\n if (p == 0)\n 1\n else {\n val half = powMod(a, p / 2, MOD)\n val res = half * half % MOD\n if (p % 2 == 1) {\n res * a % MOD\n } else\n res\n }\n }\n}\n", "positive_code": [{"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs = readLongs(n).sorted\n\n val MOD = 1000000007L\n var res = 0L\n\n var m = 1L\n for (x <- xs) {\n val y = x * (MOD + m - 1) % MOD\n res = (res + y) % MOD\n m = (m * 2) % MOD\n }\n\n m = 1L\n for (x <- xs.reverse) {\n val y = x * (MOD + m - 1) % MOD\n res = (MOD + res - y) % MOD\n m = (m * 2) % MOD\n }\n\n println(res)\n}\n"}], "negative_code": [{"source_code": "/**\n * @author tdx\n */\nobject Main {\n import scala.math._\n import scala.collection.mutable._\n import java.io.{File, FileInputStream, InputStreamReader}\n import java.util.Scanner\n\n // !!!! CHANGE to LOCAL = true before submit !!!!\n val LOCAL = false\n// val LOCAL = true\n\n def D(x: => Unit): Unit = {\n if (LOCAL) {\n try {\n x\n } catch {\n case e: Throwable => println(\"Error: \" + e.getLocalizedMessage)\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n val MOD = (pow(10, 9) + 7).toInt\n val sc = new Scanner(new InputStreamReader(if (LOCAL) new FileInputStream(new File(\"input\")) else System.in))\n val n = sc.nextInt()\n val arr = ArrayBuffer[Int]()\n for (_ <- 1 to n) {\n arr.append(sc.nextInt())\n }\n\n val sorted = arr.sorted\n var res = 0L\n\n D(println(sorted))\n\n for (i <- 0 until n - 1) {\n res = (res + (powMod(2, i + 1, MOD) - 1) * (powMod(2, n - i - 1, MOD) - 1) * (sorted(i + 1) - sorted(i))) % MOD\n D(println(i, res))\n }\n\n println(res)\n }\n\n def powMod(a: Int, p: Int, MOD: Int): Long = {\n if (p == 0)\n 1\n else {\n val half = powMod(a, p / 2, MOD)\n val res = half.asInstanceOf[Long] * half % MOD\n if (p % 2 == 1) {\n res.asInstanceOf[Long] * a % MOD\n } else\n res\n }\n }\n}\n"}], "src_uid": "acff03fe274e819a74b5e9350a859471"} {"source_code": "import scala.io.StdIn._\nobject A extends App{\n val Array(n,m) = readLine().split(\" \").map(_.toInt)\n val cand = for (i <- 0 until m) yield {\n readLine().split(\" \").map(_.toLong).zipWithIndex.maxBy(_._1)._2\n }\n val static = cand.groupBy(+_).mapValues(_.length).toSeq\n val mv = static.maxBy(_._2)._2\n println(static.filter(_._2 == mv).minBy(_._1)._1 + 1)\n}\n", "positive_code": [{"source_code": "object A570 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val votes = Array.fill(m)(readLongs(n))\n\n val winner1 = votes.map(_.zipWithIndex.map{case(k, v) => (k, n-v-1)}.sortBy(identity).last._2)\n val winner2 = winner1.groupBy(identity).mapValues(_.length).toArray.map{case (x, y) => (y,x)}.sortBy(identity)\n\n println(n - winner2.last._2)\n }\n}"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val votes = new Array[Array[Int]](m)\n for (i <- 0 until m) {\n votes(i) = new Array[Int](n)\n for (j <- 0 until n) {\n votes(i)(j) = nextInt\n }\n }\n val res = new Array[(Int, Int)](m)\n for (i <- 0 until m) {\n var max = Int.MinValue\n var ind = -1\n for (j <- 0 until n) {\n if (max < votes(i)(j)) {\n ind = j\n max = votes(i)(j)\n }\n }\n res(i) = (max, ind)\n }\n val fnl = new Array[Int](n)\n for (i <- 0 until m) {\n fnl(res(i)._2) += 1\n }\n val max = fnl.reduceLeft(_ max _)\n for (i <- 0 until n) {\n if (fnl(i) == max) {\n out.println(i + 1)\n return 0\n }\n }\n return 0\n }\n}\n"}, {"source_code": "import io.StdIn._\nimport scala.collection.mutable\nimport scala.collection.mutable._\n\nobject Solution {\n\n def main(args: Array[String]) {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val f = Array.ofDim[Int](m, n)\n for (i <- 0 to m-1) {\n f(i) = readLine().split(\" \").map(_.toInt)\n }\n\n val result = f.map { c => c.zipWithIndex.find(_._1 == c.max).get._2 }\n .groupBy[Int](c=>c).map { case(c, arr) => (c, arr.length) }\n .maxBy { case(c, v) => (v, -c) }\n\n println(result._1+1)\n }\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _570A extends CodeForcesApp[Int]({scanner => import scanner._\n val (n, m) = (nextInt, nextInt)\n val data = IndexedSeq.fill(m, n)(nextInt)\n\n val round1 = data map {votes => votes.indexOf(votes.max)}\n\n val round2 = round1.groupBy(identity).mapValues(_.size)\n\n val ranked = round2.toList map {case (candidate, cities) => -cities -> candidate}\n\n //debug(ranked)\n\n ranked.min._2 + 1\n})\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n import scala.collection.mutable.{Map => Dict}\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n val winners = for {\n i <- 0 until m\n } yield {\n val votes = readLine().split(\" \").map(_.toLong)\n votes.zipWithIndex.maxBy(_._1)._2\n }\n\n val x = winners.groupBy(identity).mapValues(_.length).toSeq\n val max = x.maxBy(_._2)._2\n println(x.filter(_._2 == max).map(_._1).min + 1)\n}\n"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject Elections {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n \n \n def main(args: Array[String]) {\n val (can,cities) = readTuple()\n val winners = for {\n i <- 1 to cities\n v = readInts\n m = v.max \n winner = v.indexOf(m)\n } yield winner\n val tmp = winners.groupBy { x => x }.mapValues { _.size }.toList\n .sortBy{ case (cand,votes) => (-votes,cand)}\n //println(tmp)\n println(tmp.head._1 + 1)\n \n \n \n \n }\n \n}"}, {"source_code": "\nimport java.util.Scanner\n\nobject PA extends App {\n var in = new Scanner(System.in)\n val n = in.nextInt()\n val m = in.nextInt()\n val d = Array.ofDim[Int](m, n)\n for{\n i <- 0 until m\n j <- 0 until n\n } d(i)(j) = in.nextInt()\n def maxv(ar:Array[Int]):Int = {\n var v = 0\n var idx = 0 \n for(i <- 0 until ar.length if ar(i) > v){\n idx = i\n v = ar(i)\n }\n idx+1\n }\n val sum = Array.fill[Int](111)(0)\n for(i <- d.map(maxv))\n sum(i) += 1\n var ans = 0\n var mv = 0\n for(i <- 0 until sum.length if sum(i) > mv){\n ans = i\n mv = sum(i)\n }\n println(ans)\n}\n\n\n"}], "negative_code": [{"source_code": "import io.StdIn._\nimport scala.collection.mutable\nimport scala.collection.mutable._\n\nobject Solution {\n\n def main(args: Array[String]) {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val f = Array.ofDim[Int](m, n)\n for (i <- 0 to m-1) {\n f(i) = readLine().split(\" \").map(_.toInt)\n }\n\n val result = f.map { c => c.zipWithIndex.find(_._1 == c.max).get._2 }\n .groupBy[Int](c=>c).map { case(c, arr) => (c, arr.length) }\n .maxBy {\n case(c, v) =>\n var all = 0\n for (i <- 0 to m-1) {\n all += f(i)(c)\n }\n (v, all, -c)\n }\n\n println(result._1+1)\n }\n}\n"}, {"source_code": "\n\nobject A extends App {\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n val total = Array.ofDim[Long](n)\n\n var globalMax = Long.MinValue\n var globalMaxIdx = 0\n\n for (i <- 0 until m) {\n val votes = readLine().split(\" \").map(_.toInt)\n var maxIdx = 0\n var maxVotes = Long.MinValue\n\n for (j <- votes.indices) {\n if (votes(j) > maxVotes) {\n maxVotes = votes(j)\n maxIdx = j\n }\n }\n\n total(maxIdx) += 1\n if (total(maxIdx) > globalMax) {\n globalMax = total(maxIdx)\n globalMaxIdx = maxIdx\n }\n }\n\n println(globalMaxIdx + 1)\n}\n"}], "src_uid": "b20e98f2ea0eb48f790dcc5dd39344d3"} {"source_code": "\nobject A {\n\n def main(args: Array[String]): Unit = {\n val sc = new java.util.Scanner(System.in)\n val newLogin = sc.next.toLowerCase\n val len = newLogin.length\n val n = sc.nextInt()\n for (_ <- 1 to n) {\n val s = sc.next\n if (s.length == len && isSimilar(s)) {\n print(\"No\")\n return\n }\n }\n print(\"Yes\")\n\n def isSimilar(str: String): Boolean = {\n def similarChars(c1: Char, c2: Char): Boolean = {\n if (c1 == c2) true else\n c1 match {\n case 'o' => c2 == '0'\n case '0' => c2 == 'o'\n case '1' => c2 == 'i' || c2 == 'l'\n case 'i' => c2 == '1' || c2 == 'l'\n case 'l' => c2 == 'i' || c2 == '1'\n case _ => false\n }\n }\n\n newLogin.zip(str.toLowerCase).forall(t => similarChars(t._1, t._2))\n }\n }\n\n}\n", "positive_code": [{"source_code": "\nobject A {\n\n def main(args: Array[String]): Unit = {\n val sc = new java.util.Scanner(System.in)\n val newLogin = sc.next.toLowerCase\n val len = newLogin.length\n val n = sc.nextInt()\n for (_ <- 1 to n) {\n val s = sc.next\n if (s.length == len && isSimilar(s)) {\n print(\"No\")\n return\n }\n }\n print(\"Yes\")\n\n def isSimilar(str: String): Boolean = {\n def similarChars(c1: Char, c2: Char): Boolean = {\n if (c1 == c2) true else\n c1 match {\n case 'o' => c2 == '0'\n case '0' => c2 == 'o'\n case '1' => c2 == 'i' || c2 == 'l'\n case 'i' => c2 == '1' || c2 == 'l'\n case 'l' => c2 == 'i' || c2 == '1'\n case _ => false\n }\n }\n\n newLogin.zip(str.toLowerCase).forall(t => similarChars(t._1, t._2))\n }\n }\n\n}\n"}], "negative_code": [], "src_uid": "0d70984ab8bd7aecd68c653adf54fc08"} {"source_code": "object CF_531_3_D {\n\n type In = (Int, String)\n type Out = String\n\n\n def solve0(in: In): Out = {\n val (n, s) = in\n???\n }\n\n def solve(in: In): Out = {\n val (n, s) = in\n\n val target = n / 3\n val counts = List('0','1','2').map(i => (i, s.count(_ == i)))\n\n val replacees = for {\n (char, count) <- counts\n if count > target\n c <- Seq.fill(count - target)(char)\n } yield c\n\n val replacements = for {\n (char, count) <- counts\n if count < target\n c <- Seq.fill(target - count)(char)\n } yield c\n\n val (startPairs, endPairs) = replacees.zip(replacements).partition(p => p._1 > p._2)\n val startMap = startPairs.groupBy(_._1).mapValues(_.map(_._2)).withDefaultValue(Seq.empty)\n val endMap = endPairs.groupBy(_._1).mapValues(_.map(_._2).reverse).withDefaultValue(Seq.empty)\n\n def loop(ps: Map[Char, Seq[Char]], input: List[Char], output: List[Char]): List[Char] = input match {\n case Nil => output\n case c +: tail => ps(c) match {\n case Seq() => loop(ps, tail, c :: output)\n case replacement +: rest => loop(ps + (c -> rest), tail, replacement :: output)\n }\n }\n\n val fromStart = loop(startMap, s.toList, Nil)\n val fromEnd = loop(endMap, fromStart, Nil)\n val result = fromEnd\n result.mkString\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, {i.nextLine; i.nextLine})\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val S = ns(N).map(_-'0')\n val n = N / 3\n val d = Array.fill[Int](3)(-n)\n REP(N) { i =>\n d(S(i)) += 1\n }\n\n REP(N) { i =>\n if (d(0) < 0 && S(i) != 0 && d(S(i)) > 0) {\n d(0) += 1\n d(S(i)) -= 1\n S(i) = 0\n }\n }\n\n REP_r(N) { i =>\n if (d(2) < 0 && S(i) != 2 && d(S(i)) > 0) {\n d(2) += 1\n d(S(i)) -= 1\n S(i) = 2\n }\n }\n\n // この時点で1以外は+になっている\n // <-の方向で0を1にする\n REP_r(N) { i =>\n if (d(1) < 0 && S(i) == 0 && d(0) > 0) {\n d(1) += 1\n d(0) -= 1\n S(i) = 1\n }\n }\n\n // ->の方向で2を1にする\n REP(N) { i =>\n if (d(1) < 0 && S(i) == 2 && d(2) > 0) {\n d(1) += 1\n d(2) -= 1\n S(i) = 1\n }\n }\n\n out.println(S.mkString)\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object CF_531_3_D {\n\n type In = (Int, String)\n type Out = String\n \n def solve(in: In): Out = {\n val (n, s) = in\n\n val target = n/3\n// val counts = s.groupBy(identity).mapValues(_.length).toSeq.sorted\n\n val counts = Seq('0','1','2').map(i => (i, s.count(_ == i)))\n\n val replacees = for {\n (char, count) <- counts\n if count > target\n c <- Seq.fill(count - target)(char)\n } yield c\n\n val replacements = for {\n (char, count) <- counts\n if count < target\n c <- Seq.fill(target - count)(char)\n } yield c\n\n val (startPairs, endPairs) = replacees.zip(replacements).partition(p => p._1 > p._2)\n\n def loop(ps: Seq[(Char, Char)], input: String, output: String): String = ps match {\n case Seq() => output + input\n case Seq((replacee, replacement), _*) =>\n if(input.head == replacee)\n loop(ps.tail, input.tail, output + replacement)\n else\n loop(ps, input.tail, output + input.head)\n }\n\n val fromStart = loop(startPairs, s, \"\")\n val fromEnd = loop(endPairs.reverse, fromStart.reverse, \"\")\n fromEnd.reverse\n\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, {i.nextLine; i.nextLine})\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}], "src_uid": "cb852bf0b62d72b3088969ede314f176"} {"source_code": "\n/**\n * Created by octavian on 18/02/2016.\n */\nobject Selection {\n\n def main(args: Array[String]) {\n //System.setIn(new FileInputStream(\"src/selection.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"src/selection.out\")))\n var n = readInt()\n val res: BigInt = comb(5, n) + comb(6, n) + comb(7, n)\n println(res)\n }\n\n def comb(k: Int, n: Int): BigInt = {\n //println(\"k is: \" + k)\n //println(\"n is: \" + n)\n var res: BigInt = 1\n for(i <- (n - k + 1) to n) {\n //println(\"i is: \" + i)\n res *= i\n //println(\"res became \" + res)\n }\n for(i <- 2 to k) {\n //println(\"i is: \" + i)\n res /= i\n //println(\"res became \" + res)\n }\n return res\n }\n\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject problem extends App {\n val in = new Scanner(System.in)\n val n = in.nextLong()\n var res: Long = 0\n res += n * (n - 1) / 2 * (n - 2) / 3 * (n - 3) / 4 * (n - 4) / 5\n res += n * (n - 1) / 2 * (n - 2) / 3 * (n - 3) / 4 * (n - 4) / 5 * (n - 5) / 6\n res += n * (n - 1) / 2 * (n - 2) / 3 * (n - 3) / 4 * (n - 4) / 5 * (n - 5) / 6 * (n - 6) / 7\n println(res)\n}"}, {"source_code": "import scala.io.StdIn\n\nobject SelectionOfPersonnel {\n\n def main(args: Array[String]) {\n def f(s : BigInt, n : BigInt) : BigInt = {\n if (s == n) n\n else s * f(s + 1, n)\n }\n val n = StdIn.readInt()\n val a = f(n - 4, n) / f(1, 5)\n val b = f(n - 5, n) / f(1, 6)\n val c = f(n - 6, n) / f(1, 7)\n print(a + b + c)\n }\n\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import java.math.BigDecimal\n\nobject Bitz_F { \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n is = new ByteArrayInputStream(Test.t6.trim.getBytes(\"ISO-8859-1\"))\n debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n \n val res = comb(n, 5) + comb(n, 6) + comb(n, 7)\n println(res.toLong)\n \n \n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n def comb(n: Int, k: Int) = {\n// fact(n) / (fact(k) * fact(n - k))\n factLast(n, k) / fact(k)\n }\n def fact(v: Int) = {\n var res = 1l;\n for (i <- 2 to v) {\n res *= i\n// db(res)\n }\n res\n }\n\n def factLast(v:Int, k:Int):BigDecimal = {\n var res = BigDecimal(1);\n// var res = (v-k+1).toDouble / fact(k);\n for (i <- (v-k+1) to v) {\n res *= i\n// db(res)\n }\n res\n }\n \n// \n// def comb2(n: Int, k: Int):Long = {\n// var res = 1L;\n// for(i <- n to n-k by -1 ) {\n// res *= i\n// }\n// res\n// }\n \n //---------------------------- service code ----------------------------------\n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n321\n\"\"\"//66715035255088\n \nval t6 = \"\"\"\n624\n\"\"\"//7147161340917624\n\n}\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main {\n\n def sqr(x: Long) = x * x\n\n def powmod(x: Long, n: Long, p: Long): Long = {\n if (n == 1) x\n else if (n % 2 == 1) (powmod(x, n - 1, p) * x) % p\n else sqr(powmod(x, n / 2, p)) % p\n }\n\n def C(n: Long, k: Long) = {\n var res = BigInt(1)\n for (i <- n - k + 1 to n) {\n res = res * i\n }\n for (i <- 1 to k.toInt) {\n res = res / i\n }\n res\n }\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n\n val n = in.nextInt()\n\n val result = C(n, 5) + C(n, 6) + C(n, 7)\n\n println(result)\n }\n}\n"}], "negative_code": [{"source_code": "\n/**\n * Created by octavian on 18/02/2016.\n */\nobject Selection {\n\n def main(args: Array[String]) {\n //System.setIn(new FileInputStream(\"src/selection.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"src/selection.out\")))\n var n = readInt()\n val res: Long = comb(5, n) + comb(6, n) + comb(7, n)\n println(res)\n }\n\n def comb(k: Int, n: Int): Long = {\n var res: Long = 1\n for(i <- (n - k + 1) to n) {\n res *= i\n }\n for(i <- 2 to k) {\n res /= i\n }\n return res\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main {\n\n def sqr(x: Long) = x * x\n\n def powmod(x: Long, n: Long, p: Long): Long = {\n if (n == 1) x\n else if (n % 2 == 1) (powmod(x, n - 1, p) * x) % p\n else sqr(powmod(x, n / 2, p)) % p\n }\n\n def C(n: Long, k: Long) = {\n var res = 1L\n for (i <- n - k + 1 to n) {\n res = res * i\n }\n for (i <- 1 to k.toInt) {\n res = res / i\n }\n res\n }\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n\n val n = in.nextInt()\n\n val result = C(n, 5) + C(n, 6) + C(n, 7)\n\n println(result)\n }\n}\n"}, {"source_code": "\nimport scala.io.StdIn\n\nobject SelectionOfPersonnel {\n\n def main(args: Array[String]) {\n def fact(n : Long) : Long = {\n if (n <= 1) 1\n else n * fact(n - 1)\n }\n def f(s : Long, n : Long) : Long = {\n if (s == n) n\n else s * f(s + 1, n)\n }\n val n = StdIn.readInt()\n val a = f(n - 4, n) / fact(5)\n val b = f(n - 5, n) / fact(6)\n val c = f(n - 6, n) / fact(7)\n print(a + b + c)\n }\n\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import java.math.BigDecimal\n\nobject Bitz_F { \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n \n val res = comb(n, 5) + comb(n, 6) + comb(n, 7)\n println(res)\n \n \n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n def comb(n: Int, k: Int) = {\n// fact(n) / (fact(k) * fact(n - k))\n factLast(n, k) / fact(k)\n }\n def fact(v: Int) = {\n var res = 1l;\n for (i <- 2 to v) {\n res *= i\n// println(res)\n }\n res\n }\n\n def factLast(v:Int, k:Int):Long = {\n var res = 1l;\n for (i <- (v-k+1) to v) {\n res *= i\n// println(res)\n }\n res\n }\n \n \n //---------------------------- service code ----------------------------------\n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n321\n\"\"\"\n\n}\n\n}\n"}], "src_uid": "09276406e16b46fbefd6f8c9650472f0"} {"source_code": "import scala.collection._\n\nobject A extends App {\n \n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, l, r, ql, qr) = readInts(5)\n val ws = readInts(n)\n val sums = ws.scan(0)(_ + _)\n val sum = sums.last\n\n var i = 0\n var minCost = Int.MaxValue\n val half = (n + 1) / 2\n \n while (i <= n) {\n val j = n - i\n val cost = sums(i) * l + (sum - sums(i)) * r + (if (i < j) (j - i - 1) * qr else if (i > j) (i - j - 1) * ql else 0)\n if (cost < minCost) minCost = cost\n i += 1\n }\n\n println(minCost)\n}", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, l, r, ql, qr) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n val leftSum = data.scanLeft(0l){case(acc, el) => acc + el}\n val maxSum = leftSum.last\n println((0 to n).foldLeft(Long.MaxValue) {\n case(acc, i) =>\n val sum = leftSum(i) * l + (maxSum - leftSum(i)) * r\n val res = if ( i > n - i ) (2 * i - n - 1) * ql\n else if ( i < n - i ) (n - 2 * i - 1) * qr\n else 0\n\n Math.min(acc, sum + res)\n })\n}"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject A extends App {\n \n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, l, r, ql, qr) = readInts(5)\n val ws = readInts(n)\n val sums = ws.scan(0)(_ + _)\n val sum = sums.last\n\n var i = 0\n var minCost = Int.MaxValue\n val half = (n + 1) / 2\n \n while (i <= n) {\n val cost = sums(i) * l + (sum - sums(i)) * r + (if (i < half) (half - i - 1) * qr else (i - half) * ql)\n if (cost < minCost) minCost = cost\n i += 1\n }\n\n println(minCost)\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, l, r, ql, qr) = readInts(5)\n val ws = readInts(n)\n val sums = ws.scan(0)(_ + _)\n val sum = sums.last\n\n var i = 0\n var minCost = Int.MaxValue\n val half = n / 2\n \n while (i <= n) {\n \n val cost = sums(i) * l + (sum - sums(i)) * r + (if (i < half) (half - i) * qr else (i - half) * ql)\n \n if (cost < minCost) minCost = cost\n \n i += 1\n }\n\n println(minCost)\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, l, r, ql, qr) = readInts(5)\n val ws = readInts(n)\n val sums = ws.scan(0)(_ + _)\n val sum = sums.last\n\n var i = 0\n var minCost = Int.MaxValue\n val half = (n + 1) / 2\n \n while (i <= n) {\n val cost = sums(i) * l + (sum - sums(i)) * r + (if (i < half) (half - i) * qr else (i - half) * ql)\n if (cost < minCost) minCost = cost\n i += 1\n }\n\n println(minCost)\n}"}], "src_uid": "e6fcbe3f102b694a686c0295edbc35e9"} {"source_code": "//package codeforces.contests._1353\n\nobject MostUnstableArray {\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(n, m) = io.StdIn.readLine.split(\" \").map(_.toInt)\n println {\n n match {\n case 1 => 0\n case 2 => m\n case _ => 2L * m\n }\n }\n }\n }\n\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject A {\n\n def solution(n: Int, m: Int): Int = n match {\n case 1 => 0\n case 2 => m\n case _ => 2 * m\n }\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val Seq(n, m) = readLine.split(\" \").toSeq.map(_.toInt)\n println(solution(n, m))\n }\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.math.max\nimport scala.math.min\nimport scala.reflect.ClassTag\n\nobject Main {\n\tdef main(args: Array[String]): Unit = {\n\t\ttry {\n\t\t\tval (in, out) =\n\t\t\t\tif (isOnlineJudge) {\n\t\t\t\t\t(\n\t\t\t\t\t\tnew FastScanner(new InputStreamReader(System.in)),\n\t\t\t\t\t\tnew PrintWriter(System.out)\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\t(\n\t\t\t\t\t\tnew FastScanner(new FileReader(new File(\"problem.in\"))),\n\t\t\t\t\t\tnew PrintWriter(new File(\"problem.out\"))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\tnew CF644(in, out).solve()\n\t\t\tout.flush()\n\t\t\tout.close()\n\t\t} catch {\n\t\t\tcase e: IOException => e.printStackTrace()\n\t\t}\n\t}\n \n\tprivate[this] val isOnlineJudge = true\n \n\tclass FastScanner(val streamReader: InputStreamReader) {\n\t\tprivate[this] val reader = new BufferedReader(streamReader, 32768)\n\t\tprivate[this] var tokenizer: StringTokenizer = _\n \n\t\t@inline private[this] final def next(): String = {\n\t\t\twhile (tokenizer == null || !tokenizer.hasMoreTokens)\n\t\t\t\ttokenizer = new StringTokenizer(reader.readLine)\n\t\t\ttokenizer.nextToken\n\t\t}\n \n\t\tdef nextInt(): Int = Integer.parseInt(next())\n \n\t\tdef nextLong(): Long = java.lang.Long.parseLong(next())\n \n\t\tdef nextChar(): Char = next().charAt(0)\n \n\t\tdef ni(): Int = nextInt()\n \n\t\tdef nl(): Long = nextLong()\n \n\t\tdef nc(): Char = nextChar()\n \n\t\tdef ns(): String = next()\n \n\t\tdef ns(n: Int): Array[Char] = ns().toCharArray\n \n\t\tdef na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n \n\t\tdef na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n\t\t\tval A1, A2 = Array.ofDim[Int](n)\n\t\t\tREP(n) { i =>\n\t\t\t\tA1(i) = ni() + offset\n\t\t\t\tA2(i) = ni() + offset\n\t\t\t}\n\t\t\t(A1, A2)\n\t\t}\n \n\t\tdef nm(n: Int, m: Int): Array[Array[Int]] = {\n\t\t\tval A = Array.ofDim[Int](n, m)\n\t\t\tREP(n) { i =>\n\t\t\t\tREP(m) { j =>\n\t\t\t\t\tA(i)(j) = ni()\n\t\t\t\t}\n\t\t\t}\n\t\t\tA\n\t\t}\n \n\t\tdef nal(n: Int): Array[Long] = map(n)(_ => nl())\n \n\t\tdef nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n\t}\n \n\tdef REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n\t\tvar i = offset\n\t\tval N = n + offset\n\t\twhile (i < N) {\n\t\t\tf(i);\n\t\t\ti += 1\n\t\t}\n\t}\n \n\tdef REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n\t\tvar i = n - 1 + offset\n\t\twhile (i >= offset) {\n\t\t\tf(i);\n\t\t\ti -= 1\n\t\t}\n\t}\n \n\tdef TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n\t\tREP(to - from + 1, from)(f)\n\t}\n \n\tdef map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n\t\tval res = Array.ofDim[A](n)\n\t\tREP(n)(i => res(i) = f(i + offset))\n\t\tres\n\t}\n \n\tdef sumL(as: Array[Int]): Long = {\n\t\tvar s = 0L\n\t\tREP(as.length)(i => s += as(i))\n\t\ts\n\t}\n \n\tdef cumSum(as: Array[Int]): Array[Long] = {\n\t\tval cum = Array.ofDim[Long](as.length + 1)\n\t\tREP(as.length) { i =>\n\t\t\tcum(i + 1) = cum(i) + as(i)\n\t\t}\n\t\tcum\n\t}\n}\n \nclass CF644 (fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n \n\timport Main._\n\timport fScanner._\n \n\t// def solve(): Unit = {\n\t// \tval T = ni()\n\t// \tfor(i <- 0 until T){\n\t// \tvar ans : Int = 1000\n\t// \t\tval n = ni()\n\t// \t\tvar list: List[Int] = List()\n\t// \t\tfor(j <- 0 until n){\n\t// \t\t\tval cu:Int = ni()\n\t// \t\t\tfor( x <- list)\n\t// \t\t\t\tans = ans.min( ( cu - x ).max(x - cu) )\n\t// \t\t\tlist = cu::\tlist\n\t// \t\t}\n\t// \t\tout.println(ans)\n\t// \t}\n\t// }\n\n\tdef solve(): Unit ={\t\n\t\tval T = ni()\n\t\tfor(i <- 0 until T){\n\t\t\tval n = ni()\n\t\t\tval m = ni()\n\t\t\tn match {\n\t\t\t\tcase 1 => \n\t\t\t\t\tout.println(0)\n\t\t\t\tcase 2 => \n\t\t\t\t\tout.println(m)\n\t\t\t\tcase _ =>\n\t\t\t\t\tout.println(2*m) \n\t\t\t}\n\t\t}\n\t}\n}\n"}, {"source_code": "object A extends App {\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, m) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n val r =\n if (n == 1) 0\n else if (n == 2) m\n else 2 * m\n\n println(r)\n }\n}\n"}, {"source_code": "object ProblemA extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n\n for (_ <- 1 to t) {\n val n = in.nextInt()\n val m = in.nextInt()\n\n if (n == 1) {\n println(0)\n } else if (n == 2) {\n println(m)\n } else {\n println(m * 2)\n }\n\n }\n\n}"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.math.max\nimport scala.math.min\nimport scala.reflect.ClassTag\n\nobject Main {\n\tdef main(args: Array[String]): Unit = {\n\t\ttry {\n\t\t\tval (in, out) =\n\t\t\t\tif (isOnlineJudge) {\n\t\t\t\t\t(\n\t\t\t\t\t\tnew FastScanner(new InputStreamReader(System.in)),\n\t\t\t\t\t\tnew PrintWriter(System.out)\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\t(\n\t\t\t\t\t\tnew FastScanner(new FileReader(new File(\"problem.in\"))),\n\t\t\t\t\t\tnew PrintWriter(new File(\"problem.out\"))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\tnew CF644(in, out).solve()\n\t\t\tout.flush()\n\t\t\tout.close()\n\t\t} catch {\n\t\t\tcase e: IOException => e.printStackTrace()\n\t\t}\n\t}\n \n\tprivate[this] val isOnlineJudge = false\n \n\tclass FastScanner(val streamReader: InputStreamReader) {\n\t\tprivate[this] val reader = new BufferedReader(streamReader, 32768)\n\t\tprivate[this] var tokenizer: StringTokenizer = _\n \n\t\t@inline private[this] final def next(): String = {\n\t\t\twhile (tokenizer == null || !tokenizer.hasMoreTokens)\n\t\t\t\ttokenizer = new StringTokenizer(reader.readLine)\n\t\t\ttokenizer.nextToken\n\t\t}\n \n\t\tdef nextInt(): Int = Integer.parseInt(next())\n \n\t\tdef nextLong(): Long = java.lang.Long.parseLong(next())\n \n\t\tdef nextChar(): Char = next().charAt(0)\n \n\t\tdef ni(): Int = nextInt()\n \n\t\tdef nl(): Long = nextLong()\n \n\t\tdef nc(): Char = nextChar()\n \n\t\tdef ns(): String = next()\n \n\t\tdef ns(n: Int): Array[Char] = ns().toCharArray\n \n\t\tdef na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n \n\t\tdef na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n\t\t\tval A1, A2 = Array.ofDim[Int](n)\n\t\t\tREP(n) { i =>\n\t\t\t\tA1(i) = ni() + offset\n\t\t\t\tA2(i) = ni() + offset\n\t\t\t}\n\t\t\t(A1, A2)\n\t\t}\n \n\t\tdef nm(n: Int, m: Int): Array[Array[Int]] = {\n\t\t\tval A = Array.ofDim[Int](n, m)\n\t\t\tREP(n) { i =>\n\t\t\t\tREP(m) { j =>\n\t\t\t\t\tA(i)(j) = ni()\n\t\t\t\t}\n\t\t\t}\n\t\t\tA\n\t\t}\n \n\t\tdef nal(n: Int): Array[Long] = map(n)(_ => nl())\n \n\t\tdef nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n\t}\n \n\tdef REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n\t\tvar i = offset\n\t\tval N = n + offset\n\t\twhile (i < N) {\n\t\t\tf(i);\n\t\t\ti += 1\n\t\t}\n\t}\n \n\tdef REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n\t\tvar i = n - 1 + offset\n\t\twhile (i >= offset) {\n\t\t\tf(i);\n\t\t\ti -= 1\n\t\t}\n\t}\n \n\tdef TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n\t\tREP(to - from + 1, from)(f)\n\t}\n \n\tdef map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n\t\tval res = Array.ofDim[A](n)\n\t\tREP(n)(i => res(i) = f(i + offset))\n\t\tres\n\t}\n \n\tdef sumL(as: Array[Int]): Long = {\n\t\tvar s = 0L\n\t\tREP(as.length)(i => s += as(i))\n\t\ts\n\t}\n \n\tdef cumSum(as: Array[Int]): Array[Long] = {\n\t\tval cum = Array.ofDim[Long](as.length + 1)\n\t\tREP(as.length) { i =>\n\t\t\tcum(i + 1) = cum(i) + as(i)\n\t\t}\n\t\tcum\n\t}\n}\n \nclass CF644 (fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n \n\timport Main._\n\timport fScanner._\n \n\t// def solve(): Unit = {\n\t// \tval T = ni()\n\t// \tfor(i <- 0 until T){\n\t// \tvar ans : Int = 1000\n\t// \t\tval n = ni()\n\t// \t\tvar list: List[Int] = List()\n\t// \t\tfor(j <- 0 until n){\n\t// \t\t\tval cu:Int = ni()\n\t// \t\t\tfor( x <- list)\n\t// \t\t\t\tans = ans.min( ( cu - x ).max(x - cu) )\n\t// \t\t\tlist = cu::\tlist\n\t// \t\t}\n\t// \t\tout.println(ans)\n\t// \t}\n\t// }\n\n\tdef solve(): Unit ={\t\n\t\tval T = ni()\n\t\tfor(i <- 0 until T){\n\t\t\tval n = ni()\n\t\t\tval m = ni()\n\t\t\tn match {\n\t\t\t\tcase 1 => \n\t\t\t\t\tout.println(0)\n\t\t\t\tcase 2 => \n\t\t\t\t\tout.println(m)\n\t\t\t\tcase _ =>\n\t\t\t\t\tout.println(2*m) \n\t\t\t}\n\t\t}\n\t}\n}\n"}, {"source_code": "object A extends App {\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, m) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n val c = n / 2\n\n val r =\n if (c == 0) 0\n else if (c == 1) m\n else 2 * m\n\n println(r)\n }\n}\n"}, {"source_code": "object A extends App {\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, m) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n val c = n / 2\n\n val r =\n if (c == 0) 0\n else if (c == 1) m\n else {\n val ai = m / c\n val a1 = m - ai * (c - 1)\n\n if (n % 2 == 0) (a1 + ai) * 2 + ai * 2 * (c - 2)\n else a1 * 2 + ai * 2 * (c - 1)\n }\n\n println(r)\n }\n}\n"}], "src_uid": "905cc16ecbbb3305416f9aa6e4412642"} {"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val bs = readLongs(n / 2)\n val as = Array.ofDim[Long](n)\n\n var l = 0L\n var r = Long.MaxValue\n\n for (i <- 0 until n / 2) {\n var l2 = l\n var r2 = bs(i) - l2\n if (r2 >= r) {\n r2 = r\n l2 = bs(i) - r2\n }\n as(i) = l2\n as(n - i - 1) = r2\n l = l2\n r = r2\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(as.mkString(\" \"))\n Console.flush\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val B = nal(N / 2)\n val A = Array.ofDim[Long](N)\n var l = 0L\n var r = 1e18.toLong + 9\n REP(N / 2) { i =>\n val b = B(i)\n\n val l0 = l\n val r0 = b - l0\n if (r0 <= r) {\n l = l0\n r = r0\n } else {\n l = b - r\n }\n\n A(i) = l\n A(N - 1 - i) = r\n }\n\n out.println(A.mkString(\" \"))\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.io.StdIn\n\nobject MishkaAndTheLastExam extends App {\n\n val n = StdIn.readLine().toInt\n\n println(createA(StdIn.readLine().split(\" \").map(_.toLong)))\n\n def createA(half: Array[Long]): String = {\n val left = mutable.ArrayStack[Long]()\n val right = mutable.ArrayStack[Long]()\n\n half.foreach(solutionForIth(_, left, right))\n\n left.reverse.mkString(\" \") + \" \" + right.mkString(\" \")\n }\n\n def solutionForIth(ith: Long, left: mutable.ArrayStack[Long], right: mutable.ArrayStack[Long]) = {\n\n @tailrec\n def sol(li: Long, ri: Long): Unit = {\n if (left.isEmpty) {\n left.push(li)\n right.push(ri)\n return\n }\n\n val rtop = right.top\n val ltop = left.top\n\n if (rtop >= ri && ltop <= li) {\n left.push(li)\n right.push(ri)\n return\n }\n\n val diff = if (ri > rtop) {\n ri - rtop\n } else {\n ltop - li\n }\n\n sol(li + diff, ri - diff)\n }\n\n sol(0, ith)\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject MishkaAndTheLastExam extends App {\n\n val n = StdIn.readLine().toInt\n\n println(createA(StdIn.readLine().split(\" \").map(_.toLong)))\n\n def createA(half: Array[Long]): String = {\n val left = mutable.ArrayStack[Long]()\n val right = mutable.ArrayStack[Long]()\n\n half.foreach(solutionForIth(_, left, right))\n\n left.reverse.mkString(\" \") + \" \" + right.mkString(\" \")\n }\n\n def solutionForIth(ith: Long, left: mutable.ArrayStack[Long], right: mutable.ArrayStack[Long]) = {\n\n def sol(li: Long, ri: Long): Unit = {\n if (left.isEmpty) {\n left.push(li)\n right.push(ri)\n return\n }\n\n val rtop = right.top\n val ltop = left.top\n\n if (left.nonEmpty && rtop >= ri && ltop <= li) {\n left.push(li)\n right.push(ri)\n return\n }\n\n if (ri > rtop) {\n sol(li + 1, ri - 1)\n }\n\n }\n\n sol(0, ith)\n }\n}\n"}], "src_uid": "4585419ab2b7200770cfe1e607161e9f"} {"source_code": "object Solution extends App {\n\n readInt()\n\n var key: Int = 0\n readLine().foldLeft(Map.empty[Char, Int]){\n case (acc, el) if el.isLower => acc + (el -> (acc.getOrElse(el, 0) + 1))\n case (acc, el) =>\n val lower = el.toLower\n val newValue = acc.getOrElse(lower, 0) - 1\n if (newValue >= 0)\n acc + (lower -> (acc.getOrElse(lower, 0) - 1))\n else {\n key += 1\n acc\n }\n }\n println(key)\n}", "positive_code": [{"source_code": "object CF297A extends App {\n import scala.collection.mutable.HashMap\n import scala.io.{StdIn}\n \n val n: Int = StdIn.readInt()\n val keysAndRooms: String = StdIn.readLine()\n var acc = 0\n \n keysAndRooms.toIterable.foreach(solve(new Multiset[Char]))\n \n print (acc)\n\n def solve(multiset: Multiset[Char]): (Char) => Unit = {\n (ch: Char) => {\n if(ch.isLower){\n multiset.add(ch.toUpper)\n } else {\n if(multiset.contains(ch)){\n multiset.remove(ch)\n } else{\n acc = acc + 1\n }\n }\n }\n }\n \n\n class Multiset[T] {\n val hashMap = new HashMap[T, Int]()\n\n def add(element: T) = {\n val count = hashMap.getOrElseUpdate(element, 0)\n hashMap+=((element, count+1))\n }\n\n def contains(element:T ) = {\n hashMap.get(element).nonEmpty\n }\n\n def remove(element: T) = {\n val count = hashMap.getOrElse(element, 1)\n if (count == 1) {\n hashMap.remove(element)\n } else {\n hashMap+=((element, count-1))\n }\n }\n }\n\n}\n\n"}, {"source_code": "object A525 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = read\n val keys = Array.fill(26)(0)\n var res = 0\n for(i <- 0 until n-1) {\n val k = 2*i\n keys(in(k)-'a') += 1\n val d = 2*i + 1\n if(keys(in(d).toLower-'a') > 0) {\n keys(in(d).toLower-'a') -= 1\n } else {\n res += 1\n }\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\n\n/**\n * Created by yangchaozhong on 3/27/15.\n */\nobject CF525A extends App {\n import scala.collection.mutable.{HashMap}\n\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val n = nextInt\n val s = nextString\n val map = HashMap[Char, Int]()\n var count = 0\n (1 to (n - 1)).foreach { i =>\n val l = s(i * 2 - 2)\n val r = s(i * 2 - 1).toLower\n if (l != r) {\n if (map.contains(l)) {\n map(l) += 1\n } else {\n map(l) = 1\n }\n\n if (map.contains(r) && map(r) > 0) {\n map(r) -= 1\n } else {\n count += 1\n }\n }\n }\n\n out.println(count)\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util\nimport java.util.StringTokenizer\nimport java.util.TreeMap\n\nimport scala.collection.mutable\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val map = next.toCharArray\n val size = 2 * n - 2\n val keys = new MultiHashSet[Char]()\n var ans = 0\n for (i <- 0 until size by 2) {\n keys.add(map(i).toUpper)\n if (keys.count(map(i + 1)) > 0) {\n keys.remove(map(i + 1))\n } else {\n ans += 1\n }\n }\n out.println(ans)\n return 0\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject _525_A extends App {\n lazy val file = getClass.getResourceAsStream(s\"${getClass.getSimpleName.head.toString}.in\")\n val in = if (submit) new Scanner(System.in) else new Scanner(file)\n while(in.hasNext) {\n println(apply(parseInput))\n }\n /********************************************************************************************************************/\n def submit = true // THIS MUST BE TRUE WHEN YOU SUBMIT\n\n type Input = String\n\n def parseInput: Input = {\n import in._\n nextInt()\n next()\n }\n\n def apply(line: String) = {\n val keys = mutable.Map.empty[Char, Int] withDefaultValue 0\n var ans = 0\n for {\n element <- line.grouped(2)\n (key, door) = (element(0), element(1))\n } {\n keys(key) = keys(key) + 1\n val requiredKey = door.toLower\n if (keys(requiredKey) > 0) {\n keys(requiredKey) = keys(requiredKey) - 1\n } else {\n ans += 1\n }\n }\n ans\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by pol on 29/03/15.\n */\nobject CR297_A extends App {\n val n = StdIn.readInt()\n val s = StdIn.readLine()\n var ans = 0\n\n var cnt = new Array[Int](255)\n for (i <- 0 until 2 * n - 2) {\n val si = s.charAt(i)\n if (si.isLower) {\n cnt(si) += 1\n } else {\n if (cnt(si.toLower) > 0) {\n cnt(si.toLower) -= 1\n } else {\n ans += 1\n }\n\n }\n }\n println(ans)\n}\n"}, {"source_code": "object A{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val n=nextInt\n val keys=Array.fill(26)(0)\n val S=nextString\n var count=0\n for(i<-0 until n-1){\n val ki=S(2*i)-'a'\n val Di=S(2*i+1)-'A'\n keys(ki)+=1\n if(keys(Di)>0){\n keys(Di)-=1\n }else{\n count+=1\n }\n }\n out.println(count)\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object CodeForces extends App {\n\n def solve = {\n val n = readLine().toInt\n val doorsAndKeys = readLine().toCharArray\n\n var doorkeyHash = Array.fill[Int](26)(0)\n var keysRequired = 0\n \n def charHash(c : Char) = c.toLower - 'a'\n \n for (i <- 0 until 2 * n - 2) {\n val dkHash = charHash(doorsAndKeys(i))\n if (i % 2 == 0) {\n doorkeyHash(dkHash) += 1\n } else {\n if (doorkeyHash(dkHash) > 0) doorkeyHash(dkHash) -= 1\n else keysRequired += 1\n }\n }\n println(keysRequired)\n }\n \n solve\n}"}, {"source_code": "object CodeForces extends App {\n\n def solve = {\n val n = readLine toInt\n val doorsAndKeys = readLine\n\n var doorkeyHash = Array.fill[Int](26)(0)\n \n def charHash(c : Char) = c.toLower - 'a'\n \n var index = 0\n println(doorsAndKeys.foldLeft(0)((kReq, c) => {\n val dkHash = charHash(doorsAndKeys(index))\n val dkStat = if (index % 2 == 0) 1 else if (doorkeyHash(dkHash) > 0) -1 else 0\n index += 1\n doorkeyHash(dkHash) += dkStat \n kReq + (if (dkStat == 0) 1 else 0)\n }))\n }\n \n solve\n}"}], "negative_code": [{"source_code": "/**\n * Created by yangchaozhong on 3/27/15.\n */\nobject CF525A extends App {\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val n = nextInt\n val s = nextString\n\n val count = (1 to (n - 1)).map(_ * 2).count(i => s(i - 2) != s(i - 1).toLower)\n out.println(count)\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n"}], "src_uid": "80fdb95372c1e8d558b8c8f31c9d0479"} {"source_code": "object Main {\n def c_split(n: Int) = if (n % 2 == 1) {\n (1 to n).map{ i =>\n (1 to n).map{ j =>\n 1 + (((i - j + (n - 1) / 2) + n) % n ) * n + ((i + j + (n + 1) / 2) % n)\n }\n }\n } else {\n (0 until n).map{ i =>\n (0 until n / 2).flatMap { j =>\n Seq(n * n - i * (n / 2) - j, i * (n / 2) + j + 1)\n }\n }\n }\n \n def main(args: Array[String]) {\n val n = readInt()\n c_split(n).foreach(tr => println(tr.mkString(\" \")))\n }\n}", "positive_code": [{"source_code": "import Array._\n\nobject main extends App with fastIO {\n \n val n = nextInt\n var a = ofDim[Int](n, n)\n \n for (i <- 0 until n) if ((i & 1) == 0)\n for (j <- 0 until n) a(j)(i) = i * n + j + 1 else\n for (j <- n - 1 to (0, -1)) a(j)(i) = i * n + n - j\n \n for (i <- 0 until n) println(a(i).mkString(\" \")) \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}"}, {"source_code": "import Array._\n\nobject main extends App with fastIO {\n \n val n = nextInt\n var a = ofDim[Int](n, n)\n \n var value = 1\n for (i <- 0 until n) {\n if ((i & 1) == 0)\n for (j <- 0 until n) {\n a(j)(i) = value\n value += 1 \n } else\n for (j <- n - 1 to (0, -1)) {\n a(j)(i) = value\n value += 1 \n }\n }\n \n for (i <- 0 until n) println(a(i).mkString(\" \")) \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}"}, {"source_code": "\nobject runner {\ndef main(args:Array[String]){\nvar liner=readInt();\nvar array=Array.ofDim[Int](liner,liner);\nvar result=\"\";\nfor(i<-0 to liner-1){\n for(j<-0 to liner-1){\n if(i%2==1){\n array(i)(j)=(liner)*(i+1)-j;\n }else{\n array(i)(j)=(liner*i)+j+1;\n }\n }\n}\nfor(t<-0 to liner-1){\n for(l<-0 to liner-1){\n result+=array(l)(t).toString+\" \";\n }\n result+=\"\\n\";\n}\nprintln(result);\n}\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject CF_334A_CandyBags {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val sqn = n * n\n println((((1 to sqn / 2) zip (sqn / 2 + 1 to sqn).reverse)\n .grouped(n / 2)\n .map(_.flatMap(_.productIterator).mkString(\" \"))).mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object P334A {\n\n def main(argv: Array[String]) { \n val n = readLine.toInt\n val n2 = n * n\n (0 until n).map(index =>\n println(\n\t((n * index) / 2 + 1 until (n * (index + 1)) / 2 + 1).foldLeft(\n\t List[Int]())((lst, i) => i :: n2 - i + 1 :: lst).mkString(\" \")))\n }\n} \n"}, {"source_code": "object CF334A {\n def main(argv: Array[String]) {\n val n = readLine.toInt\n def output(index: Int): Unit = {\n val a = index\n val b = n * n - index + 1\n if (index % (n >> 1) == 0) {\n if (index == (n * n) >> 1) {\n println(a + \" \" + b)\n } else {\n println(a + \" \" + b)\n output(index + 1)\n }\n } else {\n print(a + \" \" + b + \" \")\n output(index + 1)\n }\n }\n output(1)\n }\n}"}, {"source_code": "object A_CandyBags extends App {\n val n = readLine toLong\n\n import Ordering.Implicits._, Numeric.Implicits._\n\n def find[N](k: N, remains: Map[N, (N, List[N])])(implicit num: Numeric[N]): Map[N, List[N]] =\n if (k == num.zero)\n if (remains forall (_._2._1 == num.zero)) remains map {case (i, (r, l)) => (i, l)}\n else throw new ArithmeticException(\"Not found\")\n else remains maxBy (_._2._1) match {\n case (i, (r, l)) if r >= k => find(k - num.one, remains updated(i, (r - k, k :: l)))\n case _ => throw new ArithmeticException(\"Shit happened k = \" + k + \" and remains are\" + remains)\n }\n\n find[Long](n * n, 1L to n map (i => (i, (n * (n * n + 1) / 2, Nil))) toMap) map {_._2 mkString \" \"} foreach println\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n Range(1, n + 1).foreach { i =>\n println((Range(i, n * n / 2 + 1, n).toList ::: Range(n * n - i + 1, n * n / 2, -n).toList).mkString(\" \"))\n }\n}\n"}, {"source_code": "object CandyBags {\n def main(args: Array[String]): Unit = {\n val n = readLine().toInt\n // val n = 2\n val res = distribute(n)\n res.map(list => list.mkString(\" \")).foreach(println)\n }\n\n def distribute(n: Int): Seq[Seq[Int]] = {\n (0 until n).map(i => (0, i)).map { case (i, j) =>\n for {\n k <- 0 until n\n } yield(get(i + k, j + k, n))\n }\n }\n\n def get(x: Int, y: Int, n: Int): Int = {\n val (mx, my) = (x % n, y % n)\n mx * n + my + 1\n }\n}"}, {"source_code": "object A334 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n var num = 1\n for(_ <- 1 to n) {\n for(_ <- 1 to n/2) {\n print(num + \" \")\n print((n*n)-num+1 + \" \")\n num += 1\n }\n println(\"\")\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P334A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n \n type Bags = List[Int]\n \n val bags: Bags = List(\n List.range(1, N * N / 2 + 1),\n List.range(N * N / 2 + 1, N * N + 1).reverse\n ).transpose.flatten\n\n def solve(): Unit = {\n\n @tailrec\n def loop(acc: List[Bags], bags: Bags): List[Bags] = {\n if (bags.isEmpty) acc\n else loop((bags take N) :: acc, bags drop N)\n }\n\n loop(List.empty[Bags], bags).foreach { xs =>\n out.println(xs.mkString(\" \"))\n }\n }\n \n solve\n out.close\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject CandyBags extends App {\n\n def printCandy(line: Int, col: Int): Unit = {\n val st = (col - 1) * n + 1\n val of = (line + col) % n\n print(st + of)\n print(\" \")\n if(col != n) {\n printCandy(line, col + 1)\n } else if(line != n) {\n print(\"\\n\")\n printCandy(line + 1, 1)\n }\n }\n\n val n = readInt\n printCandy(1, 1)\n\n}\n"}, {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n val n = readInt\n val k = n / 2\n def ans = ((1 to n * n).take(2 * k * k) zip (1 to n * n).drop(2 * k * k).reverse).flatMap(_.productIterator).grouped(n).map(_.mkString(\" \")).mkString(\"\\n\")\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def c_split(n: Int) = if (n % 2 == 1) {\n (1 to n).map{ i =>\n (1 to n).map{ j =>\n 1 + (((i - j + (n - 1) / 2) + n) % n ) * n + ((i + j + (n + 1) / 2) % n)\n }\n }\n } else {\n (1 to n).map{ i =>\n (1 to n / 2).flatMap { j =>\n Seq(n * n - i * (n / 2) - j, i * (n / 2) + j)\n }\n }\n }\n \n def main(args: Array[String]) {\n val n = readInt()\n c_split(n).foreach(tr => println(tr.mkString(\" \")))\n }\n}"}, {"source_code": "object Main {\n def c_split(n: Int) = if (n % 2 == 1) {\n (1 to n).map{ i =>\n (1 to n).map{ j =>\n 1 + (((i - j + (n - 1) / 2) + n) % n ) * n + ((i + j + (n + 1) / 2) % n)\n }\n }\n } else {\n (1 to n).map{ i =>\n (1 to n / 2).flatMap { j =>\n Seq(n * n - i * (n / 2) - j, i * (n / 2) + j + 1)\n }\n }\n }\n \n def main(args: Array[String]) {\n val n = readInt()\n c_split(n).foreach(tr => println(tr.mkString(\" \")))\n }\n}"}], "src_uid": "0ac2a0954fe43d66eac32072c8ea5070"} {"source_code": "import scala.collection.mutable.Queue\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val ss = Array.fill(n) { readLine.toCharArray }\n\n def isEmpty(i: Int, j: Int) = i >= 0 && i < n && j >= 0 && j < m && ss(i)(j) == '.'\n\n def singleEmptyNeighbour(i: Int, j: Int) = {\n if (isEmpty(i + 1, j) && !isEmpty(i - 1, j) && !isEmpty(i, j - 1) && !isEmpty(i, j + 1)) 1\n else if (!isEmpty(i + 1, j) && isEmpty(i - 1, j) && !isEmpty(i, j - 1) && !isEmpty(i, j + 1)) 2\n else if (!isEmpty(i + 1, j) && !isEmpty(i - 1, j) && isEmpty(i, j - 1) && !isEmpty(i, j + 1)) 3\n else if (!isEmpty(i + 1, j) && !isEmpty(i - 1, j) && !isEmpty(i, j - 1) && isEmpty(i, j + 1)) 4\n else 0\n }\n\n val q = Queue.empty[(Int, Int)]\n\n def process(i: Int, j: Int): Unit = {\n if (isEmpty(i, j)) {\n singleEmptyNeighbour(i, j) match {\n case 1 =>\n ss(i)(j) = '^'\n ss(i + 1)(j) = 'v'\n q += ((i + 1, j - 1))\n q += ((i + 1, j + 1))\n q += ((i + 2, j))\n case 2 =>\n ss(i)(j) = 'v'\n ss(i - 1)(j) = '^'\n q += ((i - 1, j - 1))\n q += ((i - 1, j + 1))\n q += ((i - 2, j))\n case 3 =>\n ss(i)(j) = '>'\n ss(i)(j - 1) = '<'\n q += ((i - 1, j - 1))\n q += ((i + 1, j - 1))\n q += ((i, j - 2))\n case 4 =>\n ss(i)(j) = '<'\n ss(i)(j + 1) = '>'\n q += ((i - 1, j + 1))\n q += ((i + 1, j + 1))\n q += ((i, j + 2))\n case 0 =>\n }\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (i <- 0 until n; j <- 0 until m) {\n process(i, j)\n while (q.nonEmpty) {\n val (i, j) = q.dequeue()\n process(i, j)\n }\n }\n\n if (ss.exists(_.exists(_ == '.'))) println(\"Not unique\")\n else ss.foreach(s => println(s.mkString))\n\n Console.flush\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.Queue\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val ss = Array.fill(n) { readLine.toCharArray }\n\n def isEmpty(i: Int, j: Int) = i >= 0 && i < n && j >= 0 && j < m && ss(i)(j) == '.'\n\n def singleEmptyNeighbour(i: Int, j: Int) = {\n if (isEmpty(i + 1, j) && !isEmpty(i - 1, j) && !isEmpty(i, j - 1) && !isEmpty(i, j + 1)) 1\n else if (!isEmpty(i + 1, j) && isEmpty(i - 1, j) && !isEmpty(i, j - 1) && !isEmpty(i, j + 1)) 2\n else if (!isEmpty(i + 1, j) && !isEmpty(i - 1, j) && isEmpty(i, j - 1) && !isEmpty(i, j + 1)) 3\n else if (!isEmpty(i + 1, j) && !isEmpty(i - 1, j) && !isEmpty(i, j - 1) && isEmpty(i, j + 1)) 4\n else 0\n }\n\n val q = new java.util.ArrayDeque[(Int, Int)]()\n\n def process(i: Int, j: Int): Unit = {\n if (isEmpty(i, j)) {\n singleEmptyNeighbour(i, j) match {\n case 1 =>\n ss(i)(j) = '^'\n ss(i + 1)(j) = 'v'\n q.add((i + 1, j - 1))\n q.add((i + 1, j + 1))\n q.add((i + 2, j))\n case 2 =>\n ss(i)(j) = 'v'\n ss(i - 1)(j) = '^'\n q.add((i - 1, j - 1))\n q.add((i - 1, j + 1))\n q.add((i - 2, j))\n case 3 =>\n ss(i)(j) = '>'\n ss(i)(j - 1) = '<'\n q.add((i - 1, j - 1))\n q.add((i + 1, j - 1))\n q.add((i, j - 2))\n case 4 =>\n ss(i)(j) = '<'\n ss(i)(j + 1) = '>'\n q.add((i - 1, j + 1))\n q.add((i + 1, j + 1))\n q.add((i, j + 2))\n case 0 =>\n }\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (i <- 0 until n; j <- 0 until m) {\n process(i, j)\n while (!q.isEmpty) {\n val (i, j) = q.poll()\n process(i, j)\n }\n }\n\n if (ss.exists(_.exists(_ == '.'))) println(\"Not unique\")\n else ss.foreach(s => println(s.mkString))\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "9465c37b6f948da14e71cc96ac24bb2e"} {"source_code": "object EDU_55_A {\n def solve(input: Vector[Int]): Int = {\n val Seq(n,x,y,d) = input\n // Page y is reachable iff:\n //1 x+kd = y where k can be + or -, and |k| is answer ||\n //2 1+kd = y where k is + ||\n //3 n-kd = y \"\n // 1\n if ((y - x)%d == 0)\n math.abs((y - x) / d)\n //2\n else {\n val via1 = if ((y - 1) % d == 0)\n // presses to get back to start\n Some(intCeil(x - 1, d) +\n // presses to get up to place\n intCeil(y - 1, d)) else None\n val viaN = if ((n - y) % d == 0)\n Some(intCeil(n - x, d) +\n intCeil(n - y, d)) else None\n Seq(via1, viaN).flatten match {\n case Seq() => -1\n case Seq(a) => a\n case Seq(a,b) => a min b\n }\n }\n\n\n }\n\n // unintuitive but robust way of getting ceil(a/b) for ints\n def intCeil(a: Int, b: Int) = (a + b - 1) / b\n\n def main(args: Array[String]) = {\n val io = new IO(System.in)\n val lines = io.int()\n io.nextLine\n 1 to lines foreach { _ =>\n println(solve(io.intSeq()))\n }\n }\n\n\n\n\n\n/// boilerplate utility methods: ///\n import java.util.Scanner\n class IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def double() = sc.nextDouble()\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n rep(ni()) { _ =>\n val n, x, y = ni() - 1\n val d = ni()\n val one = if (y % d == 0) x / d + (if (x % d > 0) 1 else 0) + y / d else Integer.MAX_VALUE\n val last = if ((n - y) % d == 0) (n - x) / d + (if ((n - x) % d > 0) 1 else 0) + (n - y) / d else Integer.MAX_VALUE\n val direct = if (abs(y - x) % d == 0) abs(y - x) / d else Integer.MAX_VALUE\n val ans = min(one, min(last, direct))\n out.println(if (ans == Integer.MAX_VALUE) -1 else ans)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}], "negative_code": [{"source_code": "object EDU_55_A {\n def solve(input: Vector[Int]): Int = {\n val Seq(n,x,y,d) = input\n // Page y is reachable iff:\n //1 x+kd = y where k can be + or -, and |k| is answer ||\n //2 1+kd = y where k is + ||\n //3 n-kd = y \" ||\n // 1\n if ((y - x)%d == 0)\n math.abs((y - x) / d)\n //2\n else if ((y - 1) % d == 0)\n // presses to get back to start\n intCeil(x-1, d) +\n // presses to get up to place\n (y - 1) / d\n else if ((n-y) % d == 0)\n intCeil(n - x, d) +\n (n-y)/d\n else -1\n }\n\n // unintuitive but robust way of getting ceil(a/b) for ints\n def intCeil(a: Int, b: Int) = (a + b - 1) / b\n\n def main(args: Array[String]) = {\n val io = new IO(System.in)\n val lines = io.int()\n io.nextLine\n 1 to lines foreach { _ =>\n println(solve(io.intSeq()))\n }\n }\n\n\n\n\n\n/// boilerplate utility methods: ///\n import java.util.Scanner\n class IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def double() = sc.nextDouble()\n }\n}"}, {"source_code": "object EDU_55_A {\n def solve(input: Vector[Int]): Int = {\n val Seq(n,x,y,d) = input\n // Page y is reachable iff:\n //1 x+kd = y where k can be + or -, and |k| is answer ||\n //2 1+kd = y where k is + ||\n //3 n-kd = y \"\n // 1\n if ((y - x)%d == 0)\n math.abs((y - x) / d)\n //2\n else {\n val via1 = if ((y - 1) % d == 0)\n // presses to get back to start\n Some(intCeil(x - 1, d) +\n // presses to get up to place\n intCeil(y - 1, d)) else None\n val viaN = if ((n - y) % d == 0)\n Some(intCeil(n - x, d) +\n intCeil(n - y, d)) else None\n Seq(via1, viaN).flatten match {\n case Seq() => -1\n case Seq(a) => a\n case Seq(a,b) => a max b\n }\n }\n\n\n }\n\n // unintuitive but robust way of getting ceil(a/b) for ints\n def intCeil(a: Int, b: Int) = (a + b - 1) / b\n\n def main(args: Array[String]) = {\n val io = new IO(System.in)\n val lines = io.int()\n io.nextLine\n 1 to lines foreach { _ =>\n println(solve(io.intSeq()))\n }\n }\n\n\n\n\n\n/// boilerplate utility methods: ///\n import java.util.Scanner\n class IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def double() = sc.nextDouble()\n }\n}"}, {"source_code": "object EDU_55_A {\n def solve(input: Vector[Int]): Int = {\n val Seq(n,x,y,d) = input\n // Page y is reachable iff:\n //1 x+kd = y where k can be + or -, and |k| is answer ||\n //2 1+kd = y where k is + ||\n //3 n-kd = y \" \n // 1\n if ((y - x)%d == 0)\n math.abs((y - x) / d)\n //2\n else if ((y - 1) % d == 0)\n // presses to get back to start\n intCeil(x-1, d) +\n // presses to get up to place\n intCeil(y-1,d)\n else if ((n-y) % d == 0)\n intCeil(n - x, d) +\n intCeil(n-y,d)\n else -1\n }\n\n // unintuitive but robust way of getting ceil(a/b) for ints\n def intCeil(a: Int, b: Int) = (a + b - 1) / b\n\n def main(args: Array[String]) = {\n val io = new IO(System.in)\n val lines = io.int()\n io.nextLine\n 1 to lines foreach { _ =>\n println(solve(io.intSeq()))\n }\n }\n\n\n\n\n\n/// boilerplate utility methods: ///\n import java.util.Scanner\n class IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def double() = sc.nextDouble()\n }\n}"}, {"source_code": "object EDU_55_A {\n def solve(input: Vector[Int]): Int = {\n val Seq(n,x,y,d) = input\n // Page y is reachable iff:\n //1 x+kd = y where k can be + or -, and |k| is answer ||\n //2 1+kd = y where k is + ||\n //3 n-kd = y \" ||\n // 1\n if ((y - x)%d == 0)\n math.abs((y - x) / d)\n //2\n else if ((y - 1) % d == 0)\n // presses to get back to start\n math.ceil((x - 1)/d.toDouble).toInt +\n // presses to get up to place\n (y - 1) / d\n else if ((n-y) % d == 0)\n math.ceil((n - x)/d.toDouble).toInt +\n (n-y)/d\n else -1\n }\n \n def main(args: Array[String]) = {\n val io = new IO(System.in)\n val lines = io.int()\n io.nextLine\n 1 to lines foreach { _ =>\n println(solve(io.intSeq()))\n }\n\n }\n\n\n\n\n\n/// boilerplate utility methods: ///\n import java.util.Scanner\n class IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def double() = sc.nextDouble()\n }\n}"}], "src_uid": "474f29da694929a64eaed6eb8e4349c3"} {"source_code": "object _877C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val n = io.read[Int]\n val indices = 1 to n\n\n def mod(m: Int) = indices.filter(_%2 == m)\n\n val ans = mod(0) ++ mod(1) ++ mod(0)\n\n io.write(ans.length).writeLine().writeAll(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "import scala.io.StdIn._\nimport scala.collection.mutable.ArraySeq\n\nobject Codeforces extends App {\n val size = readInt()\n println(size + size / 2)\n val first = 1 to size filter(_ % 2 == 0)\n val second = 1 to size filter (_ % 2 == 1)\n (first ++ second ++ first) foreach(index => print(index.toString + \" \"))\n /*val beauty = readLine()\n var aCount: Int = 0\n var bCount: Int = 0\n val a = beauty.map(c => {\n if (c == 'a')\n aCount += 1\n aCount\n }).toArray\n val b = beauty.map(c => {\n if (c == 'b')\n bCount += 1\n bCount\n })\n var max: Int = 0\n for (i <- 0 to (beauty.length - 1))\n for (j <- i to (beauty.length - 1)) {\n max = math.max(max, a(i) + (b(j) - b(i)) + (a(a.length - 1) - a(j)))\n println(max)\n //if (i + 1 < beauty.length)\n // max = math.max(max, a(i) + (b(j) - b(i) + (a(a.length - 1) - a(j))))\n }\n println(max)*/\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\nimport scala.collection.mutable.ArraySeq\n\nobject Codeforces extends App {\n val size = readInt()\n println(size + 1)\n 1 to size foreach(s => {\n val current = size - s + 1\n print(s\"$current \")\n })\n print(2)\n /*val beauty = readLine()\n var aCount: Int = 0\n var bCount: Int = 0\n val a = beauty.map(c => {\n if (c == 'a')\n aCount += 1\n aCount\n }).toArray\n val b = beauty.map(c => {\n if (c == 'b')\n bCount += 1\n bCount\n })\n var max: Int = 0\n for (i <- 0 to (beauty.length - 1))\n for (j <- i to (beauty.length - 1)) {\n max = math.max(max, a(i) + (b(j) - b(i)) + (a(a.length - 1) - a(j)))\n println(max)\n //if (i + 1 < beauty.length)\n // max = math.max(max, a(i) + (b(j) - b(i) + (a(a.length - 1) - a(j))))\n }\n println(max)*/\n}\n"}], "src_uid": "c40cb0a89c2b604aa7384476b57e96b3"} {"source_code": "import scala.collection.mutable._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val next = \"DIMAD\"\n\n val Array(n, m) = readInts(2)\n val as = Array.fill(n)(readLine)\n\n val dd = Array.ofDim[ArrayBuffer[Int]](n * m)\n val cnt = Array.fill(n * m)(0)\n val color = Array.fill[Byte](n * m){ 0 }\n\n def visit(i: Int, j: Int, d: Int, source: Int) {\n if (as(i)(j) == next(d)) {\n if (d == 3) cnt(source) = 1\n if (d == 4) {\n if (dd(source) == null) dd(source) = ArrayBuffer(i * m + j)\n else dd(source) += (i * m + j)\n } else {\n val d2 = d + 1\n if (i > 0) visit(i - 1, j, d2, source)\n if (i < n - 1) visit(i + 1, j, d2, source)\n if (j > 0) visit(i, j - 1, d2, source)\n if (j < m - 1) visit(i, j + 1, d2, source)\n }\n }\n }\n\n var i = 0\n while (i < n) {\n var j = 0\n while (j < m) {\n if (as(i)(j) == 'D') visit(i, j, 0, i * m + j)\n j += 1\n }\n i += 1\n }\n\n def dfs(u: Int): Int = {\n if (color(u) == 1) {\n println(\"Poor Inna!\")\n sys.exit\n }\n if (color(u) > 0 || dd(u) == null) cnt(u)\n else {\n var max = 0\n color(u) = 1\n for (v <- dd(u)) max = Math.max(max, dfs(v))\n color(u) = 2\n cnt(u) = max + 1\n max + 1\n }\n }\n\n for (u <- dd.indices if dd(u) != null) dfs(u)\n\n val max = cnt.max\n if (max == 0) println(\"Poor Dima!\") else println(max)\n}", "positive_code": [{"source_code": "import scala.collection.mutable._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val next = \"DIMAD\".toCharArray\n\n val Array(n, m) = readInts(2)\n val as = Array.fill(n)(readLine.toCharArray)\n\n val dd = Array.ofDim[ArrayBuffer[Int]](n * m)\n val cnt = Array.fill(n * m)(0)\n val color = Array.fill[Byte](n * m){ 0 }\n\n def visit(i: Int, j: Int, d: Int, source: Int) {\n if (as(i)(j) == next(d)) {\n if (d == 3) cnt(source) = 1\n if (d == 4) {\n if (dd(source) == null) dd(source) = ArrayBuffer(i * m + j)\n else dd(source) += (i * m + j)\n } else {\n val d2 = d + 1\n if (i > 0) visit(i - 1, j, d2, source)\n if (i < n - 1) visit(i + 1, j, d2, source)\n if (j > 0) visit(i, j - 1, d2, source)\n if (j < m - 1) visit(i, j + 1, d2, source)\n }\n }\n }\n\n var i = 0\n while (i < n) {\n var j = 0\n while (j < m) {\n if (as(i)(j) == 'D') visit(i, j, 0, i * m + j)\n j += 1\n }\n i += 1\n }\n\n def dfs(u: Int): Int = {\n if (color(u) == 1) {\n println(\"Poor Inna!\")\n sys.exit\n }\n if (color(u) > 0 || dd(u) == null) cnt(u)\n else {\n var max = 0\n color(u) = 1\n for (v <- dd(u)) max = Math.max(max, dfs(v))\n color(u) = 2\n cnt(u) = max + 1\n max + 1\n }\n }\n\n for (u <- dd.indices if dd(u) != null) dfs(u)\n\n val max = cnt.max\n if (max == 0) println(\"Poor Dima!\") else println(max)\n}"}, {"source_code": "import scala.collection.mutable._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val next = \"DIMAD\".toCharArray\n\n val Array(n, m) = readInts(2)\n val as = Array.fill(n)(readLine.toCharArray)\n\n val dd = Array.ofDim[ArrayBuffer[Int]](n * m)\n val cnt = Array.fill(n * m)(0)\n val color = Array.fill[Byte](n * m){ 0 }\n\n def visit(i: Int, j: Int, d: Int, source: Int) {\n if (as(i)(j) == next(d)) {\n if (d == 3) cnt(source) = 1\n if (d == 4) {\n if (dd(source) == null) dd(source) = ArrayBuffer(i * m + j)\n else dd(source) += (i * m + j)\n } else {\n val d2 = d + 1\n if (i > 0) visit(i - 1, j, d2, source)\n if (i < n - 1) visit(i + 1, j, d2, source)\n if (j > 0) visit(i, j - 1, d2, source)\n if (j < m - 1) visit(i, j + 1, d2, source)\n }\n }\n }\n\n for (i <- 0 until n; j <- 0 until m) if (as(i)(j) == 'D') visit(i, j, 0, i * m + j)\n\n def dfs(u: Int): Int = {\n if (color(u) == 1) {\n println(\"Poor Inna!\")\n sys.exit\n }\n if (color(u) > 0 || dd(u) == null) cnt(u)\n else {\n var max = 0\n color(u) = 1\n for (v <- dd(u)) max = Math.max(max, dfs(v))\n color(u) = 2\n cnt(u) = max + 1\n max + 1\n }\n }\n\n for (u <- dd.indices if dd(u) != null) dfs(u)\n\n val max = cnt.max\n if (max == 0) println(\"Poor Dima!\") else println(max)\n}"}, {"source_code": "import scala.collection.mutable._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val next = \"DIMAD\"\n\n val Array(n, m) = readInts(2)\n val as = Array.fill(n)(readLine)\n\n val dd = Array.ofDim[ArrayBuffer[Int]](n * m)\n val cnt = Array.fill(n * m)(0)\n val color = Array.fill[Byte](n * m){ 0 }\n\n def visit(i: Int, j: Int, d: Int, source: Int) {\n if (as(i)(j) == next(d)) {\n if (d == 3) cnt(source) = 1\n if (d == 4) {\n if (dd(source) == null) dd(source) = ArrayBuffer(i * m + j)\n else dd(source) += (i * m + j)\n } else {\n val d2 = d + 1\n if (i > 0) visit(i - 1, j, d2, source)\n if (i < n - 1) visit(i + 1, j, d2, source)\n if (j > 0) visit(i, j - 1, d2, source)\n if (j < m - 1) visit(i, j + 1, d2, source)\n }\n }\n }\n\n for (i <- 0 until n; j <- 0 until m) if (as(i)(j) == 'D') visit(i, j, 0, i * m + j)\n\n def dfs(u: Int): Int = {\n if (color(u) == 1) {\n println(\"Poor Inna!\")\n sys.exit\n }\n if (color(u) > 0 || dd(u) == null) cnt(u)\n else {\n var max = 0\n color(u) = 1\n for (v <- dd(u)) max = Math.max(max, dfs(v))\n color(u) = 2\n cnt(u) = max + 1\n max + 1\n }\n }\n\n for (u <- dd.indices if dd(u) != null) dfs(u)\n\n val max = cnt.max\n if (max == 0) println(\"Poor Dima!\") else println(max)\n}"}, {"source_code": "import scala.collection.mutable._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val next = \"DIMAD\".toCharArray\n\n val Array(n, m) = readInts(2)\n val as = Array.fill(n)(readLine.toCharArray)\n\n val dd = Array.ofDim[ArrayBuffer[Int]](n * m)\n val cnt = Array.fill(n * m)(0)\n val color = Array.fill[Byte](n * m) { 0 }\n\n def visit(i: Int, j: Int, d: Int, source: Int) {\n if (as(i)(j) == next(d)) {\n if (d == 3) cnt(source) = 1\n if (d == 4) {\n if (dd(source) == null) dd(source) = ArrayBuffer(i * m + j)\n else dd(source) += (i * m + j)\n } else {\n val d2 = d + 1\n if (i > 0) visit(i - 1, j, d2, source)\n if (i < n - 1) visit(i + 1, j, d2, source)\n if (j > 0) visit(i, j - 1, d2, source)\n if (j < m - 1) visit(i, j + 1, d2, source)\n }\n }\n }\n\n var i = 0\n while (i < n) {\n var j = 0\n while (j < m) {\n if (as(i)(j) == 'D') visit(i, j, 0, i * m + j)\n j += 1\n }\n i += 1\n }\n\n def dfs(u: Int): Int = {\n if (color(u) == 1) {\n println(\"Poor Inna!\")\n sys.exit\n }\n if (color(u) > 0 || dd(u) == null) cnt(u)\n else {\n var max = 0\n color(u) = 1\n for (v <- dd(u)) max = Math.max(max, dfs(v))\n color(u) = 2\n cnt(u) = max + 1\n max + 1\n }\n }\n\n var u = 0\n while (u < dd.size) {\n if (dd(u) != null) dfs(u)\n u += 1\n }\n\n val max = cnt.max\n if (max == 0) println(\"Poor Dima!\") else println(max)\n}"}, {"source_code": "import scala.collection.mutable._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val next = \"DIMAD\"\n\n val Array(n, m) = readInts(2)\n val as = Array.fill(n)(readLine)\n\n val dd = Array.ofDim[ArrayBuffer[Int]](n * m)\n val cnt = Array.fill(n * m)(0)\n val color = Array.fill(n * m){ 0 }\n\n def visit(i: Int, j: Int, d: Int, source: Int) {\n if (as(i)(j) == next(d)) {\n if (d == 3) cnt(source) = 1\n if (d == 4) {\n if (dd(source) == null) dd(source) = ArrayBuffer(i * m + j)\n else dd(source) += (i * m + j)\n } else {\n val d2 = d + 1\n if (i > 0) visit(i - 1, j, d2, source)\n if (i < n - 1) visit(i + 1, j, d2, source)\n if (j > 0) visit(i, j - 1, d2, source)\n if (j < m - 1) visit(i, j + 1, d2, source)\n }\n }\n }\n\n var i = 0\n while (i < n) {\n var j = 0\n while (j < m) {\n if (as(i)(j) == 'D') visit(i, j, 0, i * m + j)\n j += 1\n }\n i += 1\n }\n\n def dfs(u: Int): Int = {\n if (color(u) == 1) {\n println(\"Poor Inna!\")\n sys.exit\n }\n if (color(u) > 0 || dd(u) == null) cnt(u)\n else {\n var max = 0\n color(u) = 1\n for (v <- dd(u)) max = Math.max(max, dfs(v))\n color(u) = 2\n cnt(u) = max + 1\n max + 1\n }\n }\n\n for (u <- dd.indices if dd(u) != null) dfs(u)\n\n val max = cnt.max\n if (max == 0) println(\"Poor Dima!\") else println(max)\n}"}, {"source_code": "import scala.collection.mutable._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val next = \"DIMAD\"\n\n val Array(n, m) = readInts(2)\n val as = Array.fill(n)(readLine)\n\n val dd = Array.ofDim[ArrayBuffer[Int]](n * m)\n val cnt = Array.fill(n * m)(0)\n val color = Array.fill[Byte](n * m) { 0 }\n\n def visit(i: Int, j: Int, d: Int, source: Int) {\n if (as(i)(j) == next(d)) {\n if (d == 3) cnt(source) = 1\n if (d == 4) {\n if (dd(source) == null) dd(source) = ArrayBuffer(i * m + j)\n else dd(source) += (i * m + j)\n } else {\n val d2 = d + 1\n if (i > 0) visit(i - 1, j, d2, source)\n if (i < n - 1) visit(i + 1, j, d2, source)\n if (j > 0) visit(i, j - 1, d2, source)\n if (j < m - 1) visit(i, j + 1, d2, source)\n }\n }\n }\n\n var i = 0\n while (i < n) {\n var j = 0\n while (j < m) {\n if (as(i)(j) == 'D') visit(i, j, 0, i * m + j)\n j += 1\n }\n i += 1\n }\n\n def dfs(u: Int): Int = {\n if (color(u) == 1) {\n println(\"Poor Inna!\")\n sys.exit\n }\n if (color(u) > 0 || dd(u) == null) cnt(u)\n else {\n var max = 0\n color(u) = 1\n for (v <- dd(u)) max = Math.max(max, dfs(v))\n color(u) = 2\n cnt(u) = max + 1\n max + 1\n }\n }\n\n var u = 0\n while (u < dd.size) {\n if (dd(u) != null) dfs(u)\n u += 1\n }\n\n val max = cnt.max\n if (max == 0) println(\"Poor Dima!\") else println(max)\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val next = \"DIMAD\"\n\n val Array(n, m) = readInts(2)\n val dd = Array.ofDim[ArrayBuffer[Int]](n * m)\n val as = Array.fill(n)(readLine)\n val cnt = Array.fill(n * m)(0)\n\n def visit(i: Int, j: Int, d: Int, source: Int) {\n if (as(i)(j) == next(d)) {\n if (d == 3) cnt(source) = 1\n if (d == 4) {\n if (dd(source) == null) dd(source) = ArrayBuffer(i * m + j)\n else dd(source) += (i * m + j)\n } else {\n val d2 = d + 1\n if (i > 0) visit(i - 1, j, d2, source)\n if (i < n - 1) visit(i + 1, j, d2, source)\n if (j > 0) visit(i, j - 1, d2, source)\n if (j < m - 1) visit(i, j + 1, d2, source)\n }\n }\n }\n\n def dists() {\n var u = 0\n while (u < dd.length) {\n if (dd(u) != null) {\n var vi = 0\n while (vi < dd(u).length) {\n val v = dd(u)(vi)\n if (cnt(v) > 0 && cnt(v) < cnt(u) + 1) cnt(v) = cnt(u) + 1\n vi += 1\n }\n }\n u += 1\n }\n }\n\n var i = 0\n while (i < n) {\n var j = 0\n while (j < m) {\n if (as(i)(j) == 'D') visit(i, j, 0, i * m + j)\n j += 1\n }\n i += 1\n }\n\n dists()\n dists()\n val max = cnt.max\n dists()\n\n if (max == cnt.max) {\n if (max == 0) println(\"Poor Dima!\") else println(max)\n } else println(\"Poor Inna!\")\n}"}, {"source_code": "import scala.collection.mutable._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val next = \"DIMAD\"\n\n val Array(n, m) = readInts(2)\n val dd = Array.ofDim[ArrayBuffer[Int]](n * m)\n val as = Array.fill(n)(readLine)\n val cnt = Array.fill(n * m)(0)\n\n def visit(i: Int, j: Int, d: Int, source: Int) {\n if (as(i)(j) == next(d)) {\n if (d == 3) cnt(source) = 1\n if (d == 4) {\n if (dd(source) == null) dd(source) = ArrayBuffer(i * m + j)\n else dd(source) += (i * m + j)\n } else {\n val d2 = d + 1\n if (i > 0) visit(i - 1, j, d2, source)\n if (i < n - 1) visit(i + 1, j, d2, source)\n if (j > 0) visit(i, j - 1, d2, source)\n if (j < m - 1) visit(i, j + 1, d2, source)\n }\n }\n }\n\n def dists() {\n var u = 0\n while (u < dd.length) {\n if (dd(u) != null) {\n var vi = 0\n while (vi < dd(u).length) {\n val v = dd(u)(vi)\n if (cnt(v) > 0 && cnt(v) < cnt(u) + 1) cnt(v) = cnt(u) + 1\n vi += 1\n }\n }\n u += 1\n }\n }\n\n var i = 0\n while (i < n) {\n var j = 0\n while (j < m) {\n if (as(i)(j) == 'D') visit(i, j, 0, i * m + j)\n j += 1\n }\n i += 1\n }\n\n dists()\n val max = cnt.max\n dists()\n\n if (max == cnt.max) {\n if (max == 0) println(\"Poor Dima!\") else println(max)\n } else println(\"Poor Inna!\")\n}"}], "src_uid": "80fdfeba87b7075c70671b3fd3a1199c"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val b, k = ni()\n val A = na(k)\n val even = if (b % 2 == 0) {\n A(k - 1) % 2 == 0\n } else {\n A.map(_ & 1).sum % 2 == 0\n }\n\n if (even) out.println(\"even\")\n else out.println(\"odd\")\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n", "positive_code": [{"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(b, k) = readInts(2)\n val as = readInts(k)\n\n var p = 0L\n var kk = 1L\n\n for (a <- as.reverse) {\n val x = kk * a % 2\n p = (p + x) % 2\n kk = kk * b % 2\n }\n\n println(if (p == 0) \"even\" else \"odd\")\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val b, k = ni()\n val A = na(k)\n val even = if (b % 2 == 0) {\n A(k - 1) % b == 0\n } else {\n A.map(_ & 1).sum % 2 == 0\n }\n\n if (even) out.println(\"even\")\n else out.println(\"odd\")\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val b, k = ni()\n val A = na(k)\n val even = if (b % 2 == 0) {\n k % b == 0\n } else {\n A.map(_ & 1).sum % 2 == 0\n }\n\n if (even) out.println(\"even\")\n else out.println(\"odd\")\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}], "src_uid": "ee105b664099808143a94a374d6d5daa"} {"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextLongs(n)\n var res = 0\n val lim = 2 * n\n var i = 0\n while (i < as.length) {\n val a1 = as(i)\n var a2 = a1 + 1\n var aa = a1 * a2\n while (a2 <= lim) {\n val j = aa - (i + 1) - 1\n// println(a1, a2, j)\n if (j >= 0 && j < as.length && as(j.toInt) == a2) {\n// println(i + 1, j + 1)\n res += 1\n }\n a2 += 1\n aa += a1\n if (j > as.length + 10) {\n a2 = lim + 1\n }\n }\n\n i += 1\n }\n\n out.println(res)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n import scala.collection.mutable.TreeSet\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n val in = {\r\n val in = Array.fill(2 * n + 1)(0)\r\n an.indices.foreach { i => in(an(i)) = i }\r\n in\r\n }\r\n\r\n val ans = an.indices.foldLeft(0) { case (count, i) =>\r\n val ai = an(i)\r\n (((2 * i + 1) / ai) to ((n + i + 1) / ai)).foldLeft(count) { case (count, aj) =>\r\n val j = in(aj)\r\n if (j >= i + 1 && ai * aj == i + j + 2) count + 1\r\n else count\r\n }\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n val in = {\r\n val in = Array.fill(2 * n + 1)(0)\r\n an.indices.foreach(i => in(an(i)) = i)\r\n in\r\n }\r\n\r\n val ans = an.indices.foldLeft(0) { case (count, i) =>\r\n val ai = an(i)\r\n count + (((2 * i + 1) / ai) to ((n + i + 1) / ai)).count { aj =>\r\n val j = in(aj)\r\n j >= i + 1 && ai * aj == i + j + 2\r\n }\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextLongs(n)\n var res = 0\n val lim = 2 * n\n var i = 0\n while (i < as.length) {\n val a1 = as(i)\n var a2 = a1\n var aa = a1 * a1\n while (a2 <= lim) {\n val j = aa - (i + 1) - 1\n// println(a1, a2, j)\n if (j >= 0 && j < as.length && as(j.toInt) == a2) {\n// println(i + 1, j + 1)\n res += 1\n }\n a2 += 1\n aa += a1\n if (j > as.length + 10) {\n a2 = lim + 1\n }\n }\n\n i += 1\n }\n\n out.println(res)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextLongs(n)\n var res = 0\n val lim = 2 * n\n var i = 0\n while (i < as.length) {\n val a1 = as(i)\n var a2 = a1\n var aa = a1 * a1\n while (aa <= lim) {\n val j = aa - (i + 1) - 1\n// println(a1, a2, j)\n if (j >= 0 && j < as.length && as(j.toInt) == a2) {\n// println(i + 1, j + 1)\n res += 1\n }\n a2 += 1\n aa += a1\n }\n\n i += 1\n }\n\n out.println(res)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n var res = 0\n val lim = 2 * n\n var i = 0\n while (i < as.length) {\n val a1 = as(i)\n var a2 = a1\n var aa = a1 * a1\n while (aa <= lim) {\n val j = aa - (i + 1) - 1\n// println(a1, a2, j)\n if (j >= 0 && j < as.length && as(j) == a2) {\n// println(i + 1, j + 1)\n res += 1\n }\n a2 += 1\n aa += a1\n }\n\n i += 1\n }\n\n out.println(res)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "src_uid": "0ce05499cd28f0825580ff48dae9e7a9"} {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n\n val t = readInt()\n 1 to t foreach { _ =>\n val n = readInt()\n println((1 to n map (_ => 1)).mkString(\" \"))\n }\n\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n \nobject A {\n\n\tdef main(args: Array[String]) {\n\t\tval t = readInt()\n\t\t1 to t foreach { _ =>\n\t\t\tval n = readInt()\n\t\t\tprintln((1 to n map (_ => 1)).mkString(\" \"))\n\t\t}\n\t}\n}"}, {"source_code": "object ProblemA extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n for (_ <- 1 to t) {\n val n = in.nextInt()\n val res = (1 to n).map(_ => 1).mkString(\" \")\n println(res)\n }\n}"}, {"source_code": "object CodeforcesRound655a {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val n = rl_int\n writer.println(Array.fill(n)(1).mkString(\" \"))\n }\n\n def sqr(a: Long): Long = a * a\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}"}, {"source_code": "object _1372A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val n = io.read[Int]\n val ans = Seq.fill(n)(1)\n io.writeAll(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n val charToInt: Char => Int = Character.getNumericValue\n val intToChar: Int => Char = Character.forDigit(_, 10)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}], "negative_code": [{"source_code": "object _1372A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val n = io.read[Int]\n val ans = Seq.tabulate(n)(i => 2*i + 1)\n io.writeAll(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n val charToInt: Char => Int = Character.getNumericValue\n val intToChar: Int => Char = Character.forDigit(_, 10)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}], "src_uid": "f82058f6ba3ce0da15a5ce059674af35"} {"source_code": "object A220 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n)\n val count = in.clone().sorted.zip(in).count{case (a, b) => a != b}\n if(count <=2)\n println(\"YES\")\n else\n println(\"NO\")\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next()\n val data = in.next().split(' ').map(_.toInt)\n val sorted = data.sorted\n val left = data.indices.find(i => data(i) != sorted(i))\n val right = data.indices.reverse.find(i => data(i) != sorted(i))\n if (left.isEmpty)\n println(\"YES\")\n else {\n val tmp = sorted(left.get)\n sorted(left.get) = sorted(right.get)\n sorted(right.get) = tmp\n// println(sorted.mkString(\" \"))\n// println(data.mkString(\" \"))\n if (sorted sameElements data)\n println(\"YES\")\n else\n println(\"NO\")\n }\n}"}, {"source_code": "object A220 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n)\n val count = in.sorted.zip(in).count{case (a, b) => a != b}\n if(count <=2)\n println(\"YES\")\n else\n println(\"NO\")\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "//package tasks\n\nimport java.util.Scanner\nimport java.io.InputStreamReader\nimport java.io.BufferedReader\n\nobject Krke {\n def main(args: Array[String]) {\n val in = new Scanner(new BufferedReader(new InputStreamReader(System.in)))\n val n = in.nextInt()\n val b = Array.fill(n)(in.nextInt())\n val c = b sortWith (_ < _)\n var cnt = 0\n for (i <- 0 until n)\n if (c(i) != b(i))\n cnt += 1\n if (cnt <= 2)\n print(\"YES\")\n else\n print(\"NO\")\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next()\n val data = in.next().split(' ').map(_.toInt)\n val sorted = data.sorted\n val left = data.indices.find(i => data(i) != sorted(i))\n val right = data.indices.reverse.find(i => data(i) != sorted(i))\n if (left.isEmpty)\n println(\"YES\")\n else {\n val tmp = sorted(left.get)\n sorted(left.get) = right.get\n sorted(right.get) = tmp\n if (sorted sameElements data)\n println(\"YES\")\n else\n println(\"NO\")\n }\n}"}], "src_uid": "541fde3a3c40926cbd1edb6017b83e52"} {"source_code": "import java.util\n\nimport scala.collection.mutable\nimport scala.io.StdIn\n\n\nobject Solution {\n\n //Console.setIn(new FileReader(new java.io.File(\"input\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n\n var caseNo = 1\n\n class UF(var size : Int){\n var parents = Array.ofDim[Int](size)\n var sizes = Array.ofDim[Int](size)\n\n for (i <- 0 until size) {\n parents(i) = i\n sizes(i) = 1\n }\n\n def findParent(node : Int): Int = {\n var p = node\n while (parents(p) != p) {\n p = parents(p)\n }\n parents(node) = p\n p\n }\n\n def merge(a : Int, b : Int): Unit = {\n var pA = findParent(a)\n var pB = findParent(b)\n\n if (pA == pB) {\n return\n }\n\n if (sizes(pA) < sizes(pB)) {\n parents(pB) = pA\n sizes(pA) += sizes(pB)\n } else {\n parents(pA) = pB\n sizes(pB) += sizes(pA)\n }\n }\n }\n\n def doCase(): Unit = {\n val Array(n, m) = readIntLine()\n val teleports = (0 until n).map(_ => readIntLine())\n\n val uf = new UF(m + 1)\n\n for (t <- teleports) {\n for (i <- t(0) until t(1)) {\n uf.merge(i, t(1))\n }\n }\n\n if (uf.findParent(0) == uf.findParent(m)) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n\n def main(args: Array[String]) {\n var tests = 1\n for (test <- 0 until tests) {\n doCase()\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n}\n", "positive_code": [{"source_code": "object A extends App {\n val Array(n, m) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n def check(l: List[(Int, Int)], i: Int = 0, j: Int = 0): Boolean =\n if (j >= m) true\n else if (l.isEmpty || l.head._1 < i || l.head._1 > j) false\n else check(l.tail, i min l.head._1, j max l.head._2)\n\n val l = (0 until n).foldLeft(List.empty[(Int, Int)]) {(l, _) => {\n val Array(a, b) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n (a, b) :: l\n }}.reverse\n\n if (check(l)) println(\"YES\")\n else println(\"NO\")\n}\n"}, {"source_code": "object _902A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val n, m = io.read[Int]\n\n val routes = io.read[Set, (Int, Int)](n)\n\n val table = mutable.Set.empty[(Int, Int)]\n\n for {\n (i, j) <- routes\n Seq(u, v) <- (i to j).sliding(2) if v <= m\n } table += (u -> v)\n\n val ans = table.size == m\n io.write(ans.toEnglish.toUpperCase())\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b.apply().result())\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "d646834d58c519d5e9c0545df2ca4be2"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val P = na(N, -1)\n\n val cnt = Array.ofDim[Int](N)\n val ans = ArrayBuffer[Int]()\n REP(N) { i =>\n import java.util\n util.Arrays.fill(cnt, 0)\n var p = i\n cnt(p) += 1\n while(cnt(p) < 2) {\n p = P(p)\n cnt(p) += 1\n }\n ans += p\n }\n\n out.println(ans.map(_+1).mkString(\" \"))\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject CF503B extends App {\n val n = StdIn.readInt\n val ps = StdIn.readLine.split(' ').map(_.toInt - 1) // 0 index\n\n def findStudent(student: Int): Int = {\n val holes = Array.fill(n)(false)\n var found = false\n var current = student\n while (!found) {\n if (holes(current)) {\n found = true\n return current\n } else {\n holes(current) = true\n current = ps(current)\n }\n }\n return current\n }\n\n println((0 until n).map(findStudent(_)+1).mkString(\" \"))\n}\n"}, {"source_code": "\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_503_B { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.sa2)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading \n val n = readLine.int \n val ps = readLine\n val arr = new Array[Int](n+1)\n (1 to n).foreach(arr(_) = ps.int)\n// debug(\"n = \" + n)\n \n //---------------------------- parameters reading :end\n var res = \"\"\n for(c <- 1 to n) {\n val marks = new Array[Boolean](n+1)\n var found = false\n var cur = c\n while (!found) {\n if (marks(cur)) { \n found = true\n res += (cur + \" \")\n }\n marks(cur) = true\n cur = arr(cur)\n }\n }\n \n outLn(res)\n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n3\n2 3 2 \n\"\"\"\n\nval sa2 = \"\"\"\n3\n1 2 3\n\"\"\"\n\nval sa3 = \"\"\"\n\"\"\"\n}\n\n}\n\n"}, {"source_code": "object Badge {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n var n=in.readInt()\n val arr=in.readLine().split(\" \").map(_.toInt-1)\n for(i<- 0 until n){\n val vis=Array.fill[Boolean](n)(false)\n var j=i\n while (!vis(j)){\n vis(j)=true\n j=arr(j)\n }\n print((j+1)+\" \")\n }\n println()\n }\n}\n"}], "negative_code": [], "src_uid": "c0abbbf1cf6c8ec11e942cdaaf01ad7c"} {"source_code": "/**\n * Created by helfper on 27/01/2015.\n */\nobject AntonAndCurrency {\n def main(args: Array[String]) {\n val n = io.StdIn.readLine.toArray\n println(solve(n))\n }\n\n def solve(n: Array[Char]): String = {\n val odd = n.last\n val even = n.indexWhere(c => c % 2 == 0 && c < odd)\n val even2 = if (even != -1) even else n.lastIndexWhere(c => c % 2 == 0)\n if (even2 == -1) \"-1\"\n else {\n n(n.length - 1) = n(even2)\n n(even2) = odd\n n.mkString\n }\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val dollar: Array[Char] = next.toCharArray\n val n = dollar.length\n var ans = false\n var max = \"\"\n var pos = -1\n var value = '0'\n for (i <- 0 until n) {\n if ((dollar(i) - '0') % 2 == 0 && !ans) {\n val even = dollar(i)\n val end = dollar(n - 1)\n if (end > even) {\n dollar(n - 1) = even\n dollar(i) = end\n max = new String(dollar)\n ans = true\n } else {\n pos = i\n value = even\n }\n }\n }\n if (max == \"\" && pos != -1) {\n val swap = dollar(n - 1)\n dollar(n - 1) = value\n dollar(pos) = swap\n ans = true\n max = new String(dollar)\n }\n if (ans) {\n out.println(max)\n } else {\n out.println(-1)\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject Main {\n def swap(a: mutable.Buffer[Int], i: Int, j: Int): Unit = {\n val tmp = a(i)\n a(i) = a(j)\n a(j) = tmp\n }\n\n def main(args: Array[String]) {\n val s = io.StdIn.readLine().map(_.toInt - '0').toBuffer\n if (s.count(_ % 2 == 0) == 0)\n println(-1)\n else {\n val index1 = s.indexWhere(x => x % 2 == 0 && x < s.last)\n val index2 = s.lastIndexWhere(x => x % 2 == 0 && x > s.last)\n if (index1 != -1)\n swap(s, index1, s.length - 1)\n else\n swap(s, index2, s.length - 1)\n println(s.mkString(\"\"))\n }\n }\n}\n"}, {"source_code": "object Main extends App {\n val n = readLine.split(\"\").filterNot(_ == \"\").map(_.toInt).toList\n val last = n.last\n val init = (0, 0)\n val d = n.dropRight(1).zipWithIndex.filter({ case (v, i) => v % 2 == 0 })\n val ni = n.dropRight(1).toArray\n if(d.isEmpty) {\n println(\"-1\")\n } else {\n val (v, pos) = d.filter({ case (v, i) => v < last }).headOption match {\n case Some((v, pos)) => (v, pos)\n case None =>\n d.filter({ case (v, i) => v > last }).last\n }\n ni(pos) = last\n println(\"%s%d\".format(ni.mkString, v))\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str: Array[Int] = in.next().map(_.asDigit).toArray\n val change = str.last\n var less = str.indexWhere(t => t % 2 == 0 && t < change)\n if (less == -1)\n less = str.lastIndexWhere(_ % 2 == 0)\n if (less == -1) println(\"-1\")\n else {\n str(str.length - 1) = str(less)\n str(less) = change\n println(str.mkString)\n }\n\n\n}"}, {"source_code": "object B508 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val num = read.toCharArray\n val evens = ('0' to '8' by 2).flatMap{x =>\n val first = num.indexWhere(_ == x)\n val last = num.lastIndexWhere(_ == x)\n val set = collection.mutable.Set.empty[Int]\n if(first != -1) set.add(first)\n if(last != -1) set.add(last)\n set\n }\n\n if(evens.isEmpty) {\n println(\"-1\")\n } else {\n var res = \"0\"\n for(i <- evens) {\n val n = num\n var temp = n(i)\n n(i) = n(n.length-1)\n n(n.length-1) = temp\n\n val curr = new String(n)\n if(curr.compareTo(res) > 0)\n res = curr\n\n temp = n(i)\n n(i) = n(n.length-1)\n n(n.length-1) = temp\n }\n println(res)\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str: Array[Int] = in.next().map(_.asDigit).toArray\n val change = str.last\n var less = str.indexWhere(t => t % 2 == 0 && t > change)\n if (less == -1)\n less = str.lastIndexWhere(_ % 2 == 0)\n if (less == -1) println(\"-1\")\n else {\n str(str.length - 1) = str(less)\n str(less) = change\n }\n\n\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str: Array[Int] = in.next().map(_.asDigit).toArray\n val change = str.last\n var less = str.indexWhere(t => t % 2 == 0 && t > change)\n if (less == -1)\n less = str.lastIndexWhere(_ % 2 == 0)\n if (less == -1) println(\"-1\")\n else {\n str(str.length - 1) = str(less)\n str(less) = change\n println(str.mkString)\n }\n\n\n}"}, {"source_code": "object B508 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val num = read.toCharArray\n val evens = num.zipWithIndex\n .filter{case (x, i) => (x-'0')%2 == 0}\n .map{_._2}\n\n if(evens.length == 0) {\n println(\"-1\")\n } else {\n var res = BigInt(\"0\")\n for(i <- evens) {\n val n = num\n val temp = n(i)\n n(i) = n.last\n n(n.length-1) = temp\n\n if(BigInt(n.mkString(\"\")) > res)\n res = BigInt(num.mkString(\"\"))\n }\n println(res.toString)\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object B508 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val num = read.toCharArray\n var lastEven = -1\n for(i <- num.length - 1 to 0 by -1 if lastEven == -1) {\n if((num(i)-'0') % 2 == 0)\n lastEven = i\n }\n if(lastEven == -1) {\n println(\"-1\")\n } else if(lastEven != num.length-1){\n val res = num\n\n val temp = res(lastEven)\n res(lastEven) = res(res.length-1)\n res(res.length-1) = temp\n\n println(res.mkString(\"\"))\n } else {\n\n var secondEven = -1\n for(i <- num.length - 2 to 0 by -1 if secondEven == -1) {\n if((num(i)-'0') % 2 == 0 && num(i) != num.last)\n secondEven = i\n }\n if(secondEven == -1) {\n println(\"-1\")\n } else {\n val res = num\n val temp = res(secondEven)\n res(secondEven) = res(res.length-1)\n res(res.length-1) = temp\n\n println(res.mkString(\"\"))\n }\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val dollar: Array[Char] = next.toCharArray\n val n = dollar.length\n var ans = false\n for (i <- 0 until n) {\n if ((dollar(i) - '0') % 2 == 0) {\n ans = true\n val swap = dollar(n - 1)\n dollar(n - 1) = dollar(i)\n dollar(i) = swap\n }\n }\n if (ans) {\n (0 until n).foreach(i => out.print(dollar(i)))\n } else {\n out.println(-1)\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val dollar: Array[Char] = next.toCharArray\n val n = dollar.length\n var ans = false\n for (i <- 0 until n ) {\n if ((dollar(i) - '0') % 2 == 0 && !ans) {\n ans = true\n val even = dollar(i)\n val end = dollar(n - 1)\n dollar(n - 1) = even\n dollar(i) = end\n }\n }\n if (ans) {\n (0 until n).foreach(i => out.print(dollar(i)))\n } else {\n out.println(-1)\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject Main {\n def swap(a: mutable.Buffer[Int], i: Int, j: Int): Unit = {\n val tmp = a(i)\n a(i) = a(j)\n a(j) = tmp\n }\n\n def main(args: Array[String]) {\n val s = io.StdIn.readLine().map(_.toInt - '0').toBuffer\n if (s.count(_ % 2 == 0) == 0)\n println(-1)\n else {\n val index1 = s.indexWhere(x => x % 2 == 0 && x > s.last)\n val index2 = s.lastIndexWhere(x => x % 2 == 0 && x < s.last)\n if (index1 != -1)\n swap(s, index1, s.length - 1)\n else\n swap(s, index2, s.length - 1)\n println(s.mkString(\"\"))\n }\n }\n}\n"}, {"source_code": "object Main extends App {\n val n = readLine.split(\"\").filterNot(_ == \"\").map(_.toInt).toList\n val last = n.last\n val init = (0, 0)\n val d = n.dropRight(1).zipWithIndex.filter({ case (v, i) => v % 2 == 0 })\n val ni = n.dropRight(1).toArray\n if(d.isEmpty) {\n println(\"-1\")\n } else {\n val (v, pos) = d.filter({ case (v, i) => v > last }).headOption match {\n case Some((v, pos)) => (v, pos)\n case None =>\n d.filter({ case (v, i) => v < last }).last\n }\n ni(pos) = last\n println(\"%s%d\".format(ni.mkString, v))\n }\n}"}], "src_uid": "bc375e27bd52f413216aaecc674366f8"} {"source_code": "import scala.collection.mutable\n\nobject E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(d, n, m) = readInts(3)\n\n case class Station(x: Int, p: Int)\n val _stations = Array.ofDim[Station](m + 1)\n for (i <- 0 until m) {\n val Array(x, p) = readInts(2)\n _stations(i) = Station(x, p)\n }\n _stations(m) = Station(d, 0)\n val stations = _stations.sortBy(_.x)\n\n var price = Array(0)\n var amount = Array(n)\n var pos = 0\n var res = 0L\n\n for (i <- 0 to m) {\n var consumed = stations(i).x - pos\n var j = 0\n val price1b, amount1b = new mutable.ArrayBuilder.ofInt\n// println(consumed)\n// println(price.mkString(\" \"))\n// println(amount.mkString(\" \"))\n while (j < price.length) {\n if (consumed == 0) {\n price1b += price(j)\n amount1b += amount(j)\n } else if (amount(j) > consumed) {\n price1b += price(j)\n amount1b += amount(j) - consumed\n res += consumed.toLong * price(j)\n //println(-i, consumed.toLong, price(j))\n consumed = 0\n } else {\n consumed -= amount(j)\n res += amount(j).toLong * price(j)\n //println(i, amount(j), price(j))\n }\n j += 1\n }\n if (consumed > 0) {\n println(-1)\n System.exit(0)\n }\n j = 0\n val price1 = price1b.result\n val amount1 = amount1b.result\n// println(price1.mkString(\" \"))\n// println(amount1.mkString(\" \"))\n val price2b, amount2b = new mutable.ArrayBuilder.ofInt\n var totalAmount = 0\n while (j < price1.length && price1(j) < stations(i).p) {\n price2b += price1(j)\n amount2b += amount1(j)\n totalAmount += amount1(j)\n j += 1\n }\n if (totalAmount < n) {\n price2b += stations(i).p\n amount2b += n - totalAmount\n }\n amount = amount2b.result\n price = price2b.result\n pos = stations(i).x\n }\n\n println(res)\n}\n", "positive_code": [{"source_code": "import java.util\n\nobject PackageDelivery {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n case class Station(x: Int, price: Int)\n case class Fuel(price: Int, amount: Int)\n\n val d, n, m = nextInt\n val stations = Array.fill(m) {\n val x, price = nextInt\n Station(x, price)\n }.sortBy(_.x) :+ Station(d, 0)\n\n val que = new util.ArrayDeque[Fuel]\n que.addFirst(Fuel(0, n))\n var prevX = 0\n var totalCost = 0L\n var failed = false\n\n for (station <- stations) {\n\n var mustConsume = station.x - prevX\n var remainingInTank = n\n while (!que.isEmpty && mustConsume > 0) {\n val f = que.pollFirst()\n val consumed = mustConsume min f.amount\n totalCost += consumed.toLong * f.price\n mustConsume -= consumed\n remainingInTank -= consumed\n if (consumed < f.amount) que.addFirst(Fuel(f.price, f.amount - consumed))\n }\n if (mustConsume > 0) failed = true\n\n while (!que.isEmpty && que.peekLast.price >= station.price) {\n remainingInTank -= que.pollLast().amount\n }\n\n que.addLast(Fuel(station.price, n - remainingInTank))\n\n prevX = station.x\n }\n\n println(if (failed) -1 else totalCost)\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "5b57e00d1e7417fececb9e4f0d354579"} {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nobject B extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val as = readInts(n).sorted.reverse\n\n println(as(k - 1))\n}", "positive_code": [{"source_code": "/**\n * infm, 4/25/14.\n * enjoy ;)\n */\nobject B {\n val in = {\n val lines = {\n scala.io.Source.stdin.getLines.buffered\n //val bf = new BufferedReader(new InputStreamReader(System.in))\n //Iterator.continually(readLine)\n //Iterator.continually(bf.readLine)\n }\n lines map (_ split ' ') filter (_.nonEmpty) flatten\n }\n\n //val out = new PrintWriter(System.out)\n\n def nextInt = in.next().toInt\n def nextLong = in.next().toLong\n def readIntList(n: Int) = Array.fill(n)(nextInt)\n\n def main(args: Array[String]) {\n val Array(n, k) = readIntList(2)\n val lol = readIntList(n).sorted\n println(lol(n - k))\n }\n}"}], "negative_code": [], "src_uid": "6eca08d7cc2dec6f4f84d3faa9a8a915"} {"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val n = in.nextInt()\n val count = Array.fill(n)(0)\n val edges = ListBuffer.empty[Edge]\n val g = Array.fill(n)(ListBuffer.empty[Edge])\n (1 until n).foreach{ _ =>\n val a = in.nextInt()-1\n val b = in.nextInt()-1\n val e = new Edge(a,b)\n edges.append(e)\n count(a) += 1\n count(b) += 1\n g(a).append(e)\n g(b).append(e)\n }\n\n val maxNode = count.max\n val i = count.indexWhere(_ == maxNode)\n\n var label = 0\n g(i).foreach(e => {\n e.label = label\n label += 1\n })\n edges.foreach(e => if(e.label == -1) {\n e.label = label\n label += 1\n })\n\n val res = edges.map(_.label).mkString(System.lineSeparator())\n\n out.println(res)\n\n\n\n\n\n\n }\n class Edge(a: Int, b: Int){\n var label = -1\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable.ListBuffer\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C628C(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C628C(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val adj = Array.ofDim[ListBuffer[Int]](n)\n REP(n) { i => adj(i) = new ListBuffer[Int]}\n REP(n-1) { i =>\n val u = ni() - 1\n val v = ni() - 1\n adj(u) += i\n adj(v) += i\n }\n\n var mxsz = -1\n var vert = -1\n\n REP(n) { i =>\n if(adj(i).length > mxsz) {\n vert = i\n mxsz = adj(i).length\n }\n }\n\n val ret = Array.fill[Int](n-1)(-1)\n var id = 0\n adj(vert).foreach{f => ret(f) = id; id +=1}\n REP(n-1) { i =>\n if(ret(i) == -1) {\n ret(i) = id\n id += 1\n }\n }\n ret.foreach(out.println)\n }\n}\n"}], "negative_code": [], "src_uid": "5ef966b7d9fbf27e6197b074eca31b15"} {"source_code": "import scala.io\n\nobject A {\n val req_nr = io.StdIn.readInt()\n\n def main(args: Array[String]): Unit = {\n for (_ <- Range(0, req_nr)) {\n val students_nr = io.StdIn.readInt()\n var powers = io.StdIn.readLine().split(\" \").map(_.toInt)\n powers = powers.sorted\n var team1: Option[Int] = powers.headOption\n var team2: Option[Int] = None\n for (pow <- powers.tail) {\n if (pow - team1.getOrElse(-1) > 1) {\n team1 = Some(pow)\n }\n else {\n team2 = Some(pow)\n }\n }\n if (team2 == None) {\n println(1)\n }\n else {\n println(2)\n }\n }\n }\n}\n", "positive_code": [{"source_code": "object _1249A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n repeat(io.read[Int]) {\n val skills = io.read[Seq[Int]].sorted\n val hasConseq = skills.sliding(2).exists({\n case Seq(a, b) => a+1 == b\n case _ => false\n })\n io.writeLine(if (hasConseq) 2 else 1)\n }\n\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Solution extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val q = io.read[Int]\n for (i <- 0 until q) {\n val n = io.read[Int]\n var a = io.read[Array, Int](n)\n a = a.sortWith((v1, v2) => v1 < v2)\n var ans = 1\n for (j <- 1 until n) {\n if(a(j-1) + 1 == a(j)) {\n ans = 2\n }\n }\n io.writeLine(ans)\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}"}], "negative_code": [{"source_code": "object _1249A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n repeat(io.read[Int]) {\n val skills = io.read[Seq[Int]]\n val ans = skills.foldLeft(Set.empty[Set[Int]]) { case (sets, i) =>\n sets.find(_.forall(j => (j - i).abs > 1)) match {\n case Some(found) => sets - found + (found + i)\n case _ => sets + Set(i)\n }\n }\n io.writeLine(ans.size)\n }\n\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "dd2cd365d7afad9c2b5bdbbd45d87c8a"} {"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n\n for (_ <- 1 to t) {\n val n = nextInt\n val x = nextLine\n var a, b = new StringBuilder\n var had1 = false\n for (c <- x) {\n c match {\n case '0' =>\n a += '0'\n b += '0'\n case '1' if !had1 =>\n a += '1'\n b += '0'\n had1 = true\n case '1' if had1 =>\n a += '0'\n b += '1'\n case '2' if !had1 =>\n a += '1'\n b += '1'\n case '2' if had1 =>\n a += '0'\n b += '2'\n }\n }\n out.println(a.result())\n out.println(b.result())\n }\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n val a = Array.fill(100000)(' ')\n val b = Array.fill(100000)(' ')\n (1 to t).foreach{ _ =>\n val n = in.nextInt()\n val x = in.next()\n a(0) = '1'\n b(0) = '1'\n var balanced = true\n (1 until n).foreach{ i =>\n if(!balanced){\n b(i) = '0'\n a(i) = x(i)\n }else{\n x(i) match {\n case '2' =>\n a(i) = '1'\n b(i) = '1'\n case '1' =>\n b(i) = '1'\n a(i) = '0'\n balanced = false\n case _ =>\n a(i) = '0'\n b(i) = '0'\n\n }\n }\n\n }\n\n out.println(b.slice(0,n).mkString(\"\"))\n out.println(a.slice(0,n).mkString(\"\"))\n\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "negative_code": [], "src_uid": "c4c8cb860ea9a5b56bb35532989a9192"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val (from, to) = na2(N, -1)\n val g = packUGraph(N, from, to)\n\n// assert(v == 0, \"v != 0\")\n\n// val check = Array.ofDim[Boolean](N)\n// REP(N) { i =>\n// check(ans(i)) = true\n// }\n// assert(check.forall(identity), \"all numbers are not used\")\n\n def make(s: Int) = {\n var v = 0\n var p = s\n val ans = Array.ofDim[Int](N)\n var ptr = 0\n REP(N) { _ =>\n val u1 = g(v)(0)\n val u2 = g(v)(1)\n\n val next = if (u1 != p) u1 else u2\n ans(ptr) = next\n ptr += 1\n p = v\n v = next\n }\n\n ans\n }\n\n def ok(ans: Array[Int]) = {\n var ok = true\n REP(N) { i =>\n val p = ans(i)\n val p1 = ans((i + 1) % N)\n val p2 = ans((i + 2) % N)\n ok &&= Set(from(p), to(p)) == Set(p1, p2)\n }\n ok\n }\n\n var ans = make(g(0)(0))\n if (!ok(ans)) ans = make(g(0)(1))\n\n REP(N) { i =>\n ans(i) += 1\n }\n\n out.println(ans.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n /**\n * @param n ノード数\n */\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n REP(m)(i => p(from(i)) += 1)\n REP(m)(i => p(to(i)) += 1)\n REP(n)(i => t(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val (a1, a2) = na2(N, -1)\n val I = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())\n REP(N) { i =>\n I(a1(i)) += i\n I(a2(i)) += i\n }\n\n val ans = ArrayBuffer[Int]()\n var pre = 0\n ans += pre\n while(ans.length < N) {\n val ArrayBuffer(pre1, pre2) = I(pre)\n if (I(pre1).contains(pre2)) {\n ans += pre1\n ans += pre2\n pre = pre2\n } else {\n ans += pre2\n ans += pre1\n pre = pre1\n }\n }\n\n out.println(ans.reverse.take(N).map(_+1).mkString(\" \"))\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val (from, to) = na2(N, -1)\n val g = packUGraph(N, from, to)\n var v = 0\n var p = -1\n val ans = Array.ofDim[Int](N)\n var ptr = 0\n REP(N) { _ =>\n val u1 = g(v)(0)\n val u2 = g(v)(1)\n\n val next = if (u1 != p) u1 else u2\n ans(ptr) += next\n ptr += 1\n p = v\n v = next\n }\n\n assert(v == 0, \"v != 0\")\n\n val check = Array.ofDim[Boolean](N)\n REP(N) { i =>\n check(ans(i)) = true\n }\n assert(check.forall(identity), \"all numbers are not used\")\n\n REP(N) { i =>\n ans(i) += 1\n }\n\n out.println(ans.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n /**\n * @param n ノード数\n */\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n REP(m)(i => p(from(i)) += 1)\n REP(m)(i => p(to(i)) += 1)\n REP(n)(i => t(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val (from, to) = na2(N, -1)\n val g = packUGraph(N, from, to)\n var v = 0\n var p = -1\n val ans = Array.ofDim[Int](N)\n var ptr = 0\n REP(N) { _ =>\n val u1 = g(v)(0)\n val u2 = g(v)(1)\n if (u1 != p) {\n ans(ptr) += u1\n ptr += 1\n p = v\n v = u1\n } else {\n ans(ptr) += u2\n ptr += 1\n p = v\n v = u2\n }\n }\n\n REP(N) { i =>\n ans(i) += 1\n }\n\n out.println(ans.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n /**\n * @param n ノード数\n */\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n REP(m)(i => p(from(i)) += 1)\n REP(m)(i => p(to(i)) += 1)\n REP(n)(i => t(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "819d3694fccf2b5af0ec3b4ee429dbb3"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, h, k) = in.next().split(' ').map(_.toInt)\n val (lh, time) = in.next().split(' ').map(_.toInt).foldLeft(0l, 0l) {\n case ((lh, time), el) if lh + el <= h || lh % k + el <= h =>\n ((lh + el) % k, time + (lh + el) / k)\n case ((lh, time), el) => (el % k, time + lh / k + el / k + 1)\n }\n if (lh == 0)\n println(time)\n else\n println(time + 1)\n}\n", "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _677B extends CodeForcesApp {\n override def apply(io: IO) = {\n val n, h, k = io[Int]\n val potato = io[Vector, Int](n)\n\n var i, tower = 0\n var t = 0L\n while(i < n) {\n while(i < n && tower + potato(i) <= h) {\n tower += potato(i)\n i += 1\n }\n val target = if (i < n) h - potato(i) else 0\n val smashes = (tower - target) ceilDiv k\n tower = (tower - k*smashes) max 0\n t += smashes\n }\n\n io += t\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_._1)\n def firstKeyOption: Option[K] = m.headOption.map(_._1)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv._1\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def bitCount: Int = java.lang.Integer.bitCount(x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def array[A]: Write[Array[A]] = Write(_ mkString \" \")\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _677B extends CodeForcesApp {\n override def apply(io: IO) = {\n val n, h, k = io[Int]\n val potato = io[Vector, Int](n)\n\n var i, tower = 0\n var t = 0L\n while(i < n) {\n while(i < n && tower + potato(i) <= h) {\n tower += potato(i)\n i += 1\n }\n val target = if (i < n) h - potato(i) else 0\n val smashes = ((1.0 * (tower - target))/k).ceil\n tower = (tower - k*smashes.toInt) max 0\n //debug(t, i, tower, target, smashes)\n t += smashes.toLong\n }\n\n io += t\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def vector[A: IO.Read](n: Int): Vector[A] = apply[Vector, A](n)\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def array[A]: Write[Array[A]] = Write(_ mkString \" \")\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\nobject App {\n def main(args: Array[String]) {\n\n\n\n val Array(n, h, k) = StdIn.readLine().split(\" \").map(_.toLong)\n\n val A:Array[Long] = StdIn.readLine().split(\" \").map(_.toLong)\n\n\n var curH = 0L\n var t = 0L\n for ( i <- 0 to A.length - 1) {\n val nd = math.max(A(i) - (h - curH),0)\n val d = nd / k + (if (nd % k == 0) 0 else 1)\n t += d\n curH = math.max(0L, curH - d * k ) + A(i)\n }\n val d = curH / k + (if (curH % k == 0) 0 else 1)\n t += d\n print(t)\n// print(A.foldLeft((0L,0L))({\n// case(b,a) =>\n// if(i == 0) {\n// (a,a)\n// } else {\n// val k = math.max(0, math.min(b._2 - 1, a))\n// (b._1 + k, k)\n// }\n// })._1)\n }\n\n\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 19 Jun 2016\n */\nobject A365 extends App {\n\n def solve() = {\n val Array(n, h, k): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n var occupation = 0\n var potatoIndex = 0\n var time: Long = 0L\n while (potatoIndex < n) {\n if (occupation + a(potatoIndex) > h) {\n if (occupation % k == 0) {\n time += occupation / k\n occupation = 0\n } else {\n time += occupation / k + 1\n occupation = 0\n }\n }\n while (potatoIndex < n && occupation + a(potatoIndex) <= h) {\n occupation += a(potatoIndex)\n potatoIndex += 1\n }\n if (occupation % k == 0) {\n time += occupation / k\n occupation = 0\n } else {\n time += occupation / k\n occupation = occupation % k\n }\n }\n if (occupation > 0) {\n if (occupation % k == 0) {\n time += occupation / k\n occupation = 0\n } else {\n time += occupation / k + 1\n occupation = 0\n }\n }\n\n println(time)\n }\n\n solve()\n\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, h, k) = in.next().split(' ').map(_.toInt)\n val (lh, time) = in.next().split(' ').map(_.toInt).foldLeft(0, 0) {\n case ((lh, time), el) if lh + el <= h || lh % k + el <= h =>\n ((lh + el) % k, time + (lh + el) / k)\n case ((lh, time), el) => (el % k, time + lh / k + el / k + 1)\n }\n if (lh == 0)\n println(time)\n else\n println(time + 1)\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 19 Jun 2016\n */\nobject A365 extends App {\n\n def solve() = {\n val Array(n, h, k): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n var occupation = 0\n var potatoIndex = 0\n var time = 0\n while (potatoIndex < n) {\n if (occupation + a(potatoIndex) > h) {\n if (occupation % k == 0) {\n time += occupation / k\n occupation = 0\n } else {\n time += occupation / k + 1\n occupation = 0\n }\n }\n while (potatoIndex < n && occupation + a(potatoIndex) <= h) {\n occupation += a(potatoIndex)\n potatoIndex += 1\n }\n if (occupation % k == 0) {\n time += occupation / k\n occupation = 0\n } else {\n time += occupation / k\n occupation = occupation % k\n }\n }\n if (occupation > 0) {\n if (occupation % k == 0) {\n time += occupation / k\n occupation = 0\n } else {\n time += occupation / k + 1\n occupation = 0\n }\n }\n\n println(time)\n }\n\n solve()\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _677B extends CodeForcesApp {\n override def apply(io: IO) = {\n val n, h, k = io[Int]\n val potato = io[Vector, Int](n)\n\n var i, t, tower = 0\n while(i < n) {\n while(i < n && tower + potato(i) <= h) {\n tower += potato(i)\n i += 1\n }\n val target = if (i < n) h - potato(i) else 0\n val smashes = ((1.0 * (tower - target))/k).ceil.toInt\n tower = (tower - k*smashes) max 0\n //debug(t, i, tower, target, smashes)\n t += smashes\n }\n\n io += t\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def array[A]: Write[Array[A]] = Write(_ mkString \" \")\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\nobject App {\n def main(args: Array[String]) {\n\n\n\n val Array(n, h, k) = StdIn.readLine().split(\" \").map(_.toInt)\n\n val A:Array[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n\n\n var curH = 0\n var t = 0\n for ( i <- 0 to A.length - 1) {\n val nd = math.max(A(i) - (h - curH),0)\n val d = nd / k + (if (nd % k == 0) 0 else 1)\n t += d\n curH = math.max(0, curH - d * k ) + A(i)\n }\n val d = curH / k + (if (curH % k == 0) 0 else 1)\n t += d\n print(t)\n// print(A.foldLeft((0L,0L))({\n// case(b,a) =>\n// if(i == 0) {\n// (a,a)\n// } else {\n// val k = math.max(0, math.min(b._2 - 1, a))\n// (b._1 + k, k)\n// }\n// })._1)\n }\n\n\n}\n"}], "src_uid": "5099a9ae62e82441c496ac37d92e99e3"} {"source_code": "import java.util.Scanner\n\n/**\n * Created by hama_du on 2014/03/11.\n */\nobject ProblemB extends App {\n val in = new Scanner(System.in)\n val x,k = in.nextInt\n val rounds = new Array[Boolean](x+1)\n rounds(x) = true\n (0 until k).foreach(_ => {\n val rnd = in.nextInt\n if (rnd == 1) {\n rounds(in.nextInt()) = true\n rounds(in.nextInt()) = true\n } else {\n rounds(in.nextInt()) = true\n }\n })\n\n\n val max = (1 to x-1).filter(i => !rounds(i)).size\n val min = count(1, rounds)\n println(min + \" \" + max)\n\n\n def count(idx: Int, rounds: Array[Boolean]): Int = {\n if (idx >= x) {\n 0\n } else if (rounds(idx)) {\n count(idx+1, rounds)\n } else {\n if (!rounds(idx+1)) {\n 1 + count(idx+2, rounds)\n } else {\n 1 + count(idx+1, rounds)\n }\n }\n }\n}\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(x, k) = in.next().split(' ').map(_.toInt)\n val contests = Array.ofDim[Boolean](x - 1)\n (1 to k).foreach { i =>\n in.next().split(' ').map(_.toInt) match {\n case Array(1, f, s) =>\n contests(f - 1) = true\n contests(s - 1) = true\n case Array(2, s) => contests(s - 1) = true\n }\n }\n val res = contests.foldLeft((0, 0, 0)) {\n case((min, max, soFar), false) => (min, max, soFar + 1)\n case((min, max, soFar), true) => (min + soFar / 2 + soFar % 2, max + soFar, 0)\n }\n val min = res._1 + res._3 / 2 + res._3 % 2\n val max = res._2 + res._3\n println(s\"$min $max\")\n\n}\n"}], "negative_code": [], "src_uid": "fb77c9339250f206e7188b951902a221"} {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val n = readInt\n def ans = (n +: (1 until n)).mkString(\" \")\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P221A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val answer = N :: List.range(1, N)\n\n out.println(answer.mkString(\" \"))\n out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n println((Seq(n) ++ (1 to (n - 1))).mkString(\" \")) \n }\n}"}, {"source_code": "\nobject Code221A extends App {\n val in = new java.util.Scanner(System.in)\n val n = in.nextInt\n\n println( (n :: (1 to n-1).toList).mkString(\" \") )\n}\n"}, {"source_code": "object A {\n def main(args: Array[String]) = {\n val n = readInt;\n val answer = n :: (1 to (n - 1) toList);\n println(answer map {_.toString} reduceLeft {_ + \" \" + _})\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println((n :: (1 to n - 1).toList).mkString(\" \"))\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println(((2 to n).toList ::: List(1)).mkString(\" \"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println((1 :: (1 to n - 1).toList).mkString(\" \"))\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n println((n to 1 by -1).mkString(\" \")) \n }\n}"}], "src_uid": "d9ba1dfe11cf3dae177f8898f3abeefd"} {"source_code": "\r\nimport scala.io.StdIn\r\n\r\nobject Main extends App {\r\n val n = StdIn.readLine().toInt\r\n val a = StdIn.readLine().split(\" \").map(_.toLong)\r\n val init = (0 to n).map {i => if (i == 0) 0l else -1l }\r\n val results = a.foldLeft(init) { (v, next) =>\r\n (0 to n).map { i =>\r\n if (i == 0)\r\n 0\r\n else if (v(i - 1) == -1)\r\n -1\r\n else\r\n Math.max(v(i), v(i - 1) + next)\r\n }\r\n }\r\n\r\n println((0 to n).filter(results(_) != -1).max)\r\n}", "positive_code": [{"source_code": "import scala.collection.mutable\r\nimport scala.io.StdIn\r\n\r\nobject Main extends App {\r\n val n = StdIn.readLine().toInt\r\n val a = StdIn.readLine().split(\" \").map(_.toLong)\r\n\r\n def slowSolution(n: Int, a: Array[Long]): Long = {\r\n val init = (0 to n).map {i => if (i == 0) 0l else -1l }\r\n val results = a.foldLeft(init) { (v, next) =>\r\n (0 to n).map { i =>\r\n if (i == 0)\r\n 0\r\n else if (v(i - 1) == -1)\r\n -1\r\n else\r\n Math.max(v(i), v(i - 1) + next)\r\n }\r\n }\r\n (0 to n).filter(results(_) != -1).max\r\n }\r\n\r\n def fastSolution(n: Int, a: Array[Long]): Long = {\r\n val q = new mutable.PriorityQueue[Long].reverse\r\n val (result, _) = a.foldLeft((0l, 0l)) { (state, next) =>\r\n val (curResult, curSum) = state;\r\n if (next + curSum >= 0) {\r\n q.enqueue(next)\r\n (curResult + 1, next + curSum)\r\n } else if (q.nonEmpty && q.head < next) {\r\n val old = q.dequeue()\r\n q.enqueue(next)\r\n (curResult, curSum - old + next)\r\n } else {\r\n (curResult, curSum)\r\n }\r\n }\r\n result\r\n }\r\n\r\n println(fastSolution(n, a))\r\n}\r\n"}, {"source_code": "object C1 extends App {\r\n import scala.io.StdIn._\r\n\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toLong).toList\r\n\r\n val ans = {\r\n val cn = Array.fill[Long](n + 1, n + 1)(-1L)\r\n (0 to n).foreach(cn(_)(0) = 0L)\r\n\r\n for {\r\n i <- 1 to n\r\n potion = an(i - 1)\r\n j <- 1 to i if cn(i - 1)(j - 1) >= 0\r\n c = cn(i - 1)(j - 1) + potion\r\n } cn(i)(j) =\r\n if (c >= 0) c max cn(i - 1)(j)\r\n else cn(i - 1)(j)\r\n\r\n cn(n).lastIndexWhere(_ >= 0)\r\n }\r\n\r\n println(ans)\r\n}\r\n"}], "negative_code": [{"source_code": "object C1 extends App {\r\n import scala.io.StdIn._\r\n\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toLong).toList\r\n\r\n val ans = {\r\n val cn = Array.fill[Option[Long]](n + 1, n + 1)(None)\r\n cn(0)(0) = Some(0L)\r\n\r\n for {\r\n i <- 1 to n\r\n potion = an(i - 1)\r\n j <- 1 to i\r\n } cn(i)(j) = cn(i - 1)(j - 1).map(_ + potion) match {\r\n case Some(c) if c >= 0 => Some(c max cn(i - 1)(j).getOrElse(0L))\r\n case _ => cn(i - 1)(j)\r\n }\r\n\r\n cn(n).lastIndexWhere(_.isDefined)\r\n }\r\n\r\n println(ans)\r\n}\r\n"}, {"source_code": "import scala.io.StdIn\r\n\r\nobject Main extends App {\r\n val n = StdIn.readLine().toInt\r\n val a = StdIn.readLine().split(\" \").map(_.toInt)\r\n val init = (0 to n).map {i => if (i == 0) 0 else - 1 }\r\n val results = a.foldLeft(init) { (v, next) =>\r\n (0 to n).map { i =>\r\n if (i == 0)\r\n 0\r\n else if (v(i - 1) == -1)\r\n -1\r\n else\r\n Math.max(v(i), v(i - 1) + next)\r\n }\r\n }\r\n\r\n println((0 to n).filter(results(_) != -1).max)\r\n}\r\n"}], "src_uid": "affef141c51bbfd881a90d49ec34ceea"} {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, a, b) = readLine().split(\" \").map(_.toInt)\r\n val s = readLine()\r\n\r\n val ans =\r\n if (b >= 0) n * (a + b)\r\n else {\r\n val (c, _) = s.tail.foldLeft((1, s.head)) {\r\n case (state @ (_, p), c) if p == c => state\r\n case ((m, _), c) => (m + 1, c)\r\n }\r\n n * a + (c / 2 + 1) * b\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, a, b) = readLine().split(\" \").map(_.toInt)\r\n val s = readLine()\r\n\r\n def f: Int => Int = l => if (l == 0) 0 else a * l + b\r\n def g: Seq[Int] => Int = ls => ls.foldLeft(0) { case (s, l) => s + f(l) }\r\n\r\n val ans =\r\n if (b >= 0) n * f(1)\r\n else {\r\n val zeros = s.split(\"1\").map(_.length)\r\n val ones = s.split(\"0\").map(_.length)\r\n\r\n (g(zeros) + f(ones.sum)) max (g(ones) + f(zeros.sum))\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) = {\n def rep[A](n: Int)(f: => A) { if (n > 0) { f; rep(n - 1)(f) } }\n rep(StdIn.readInt) { f }\n\n def f() {\n def calc(l: Int, a: Int, b: Int): Int =\n (a * l) + b\n\n def doSomething(in: String, a: Int, b: Int) = {\n val first = in.head\n val second = if (first == '1') '0' else '1'\n\n val part1 = in.split(second).filter(_ != \"\")\n val part2 = in.split(first).filter(_ != \"\")\n\n val part2Sum = part2.map { l => calc(l.length, a, b) }.sum\n val part1Sum = calc(part1.reduce(_ + _).length, a, b)\n\n part2Sum + part1Sum\n }\n\n def points(in: String, a: Int, b: Int) = {\n\n if (b < 0) doSomething(in, a, b)\n else {\n val ones = in.split('0')\n val zeros = in.split('1')\n val all = (ones ++ zeros).filter(_ != \"\")\n (all.flatMap(_.toCharArray)).map(e => calc(1, a, b)).sum\n }\n }\n\n val arr = (StdIn.readLine.split(\" \") map (_.toInt))\n val (n, a, b) = (arr(0), arr(1), arr(2))\n val str = StdIn.readLine\n println(points(str, a, b))\n\n }\n\n }\n}\n"}], "negative_code": [], "src_uid": "93fb13c40ab03700ef9a827796bd3d9d"} {"source_code": "//package codeforces\n\n/*\nhttps://codeforces.com/contest/1175/problem/B\n */\nobject CatchOverFlow {\n\n type Statements = List[List[String]]\n\n def main(args: Array[String]): Unit = {\n val lines = io.StdIn.readInt()\n\n\n countIncrements((1 to lines).map(_ => io.StdIn.readLine().split(\" \").toList).toList, 0) match {\n case Some((result, Nil)) => println(result)\n case None => println(\"OVERFLOW!!!\")\n }\n\n def countIncrements(statements: Statements, result: Long): Option[(Long, Statements)] = {\n if (result > (1l << 32) - 1)\n None\n else\n statements match {\n case Nil => Some(result, Nil)\n case statement :: rest =>\n\n statement match {\n case \"for\" :: n :: Nil =>\n countIncrements(rest, 0).flatMap {\n case (forLoopResult, statementsAfterForLoop) =>\n countIncrements(statementsAfterForLoop, result + forLoopResult * n.toInt)\n }\n\n case \"end\" :: Nil =>\n Some(result, rest)\n\n case \"add\" :: Nil =>\n countIncrements(rest, result + 1)\n }\n }\n }\n }\n\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject B_1175 extends App {\n val Max = 4294967295L\n var n = readInt()\n var value = 0L\n val stack = mutable.Stack[Long]()\n\n stack.push(1)\n\n var overflow = false\n\n 1 to n foreach { _ =>\n val line = readLine()\n if (!overflow) {\n line.split(\" \") match {\n case Array(\"add\") =>\n value += stack.top\n if (value > Max) overflow = true\n case Array(\"for\", x) =>\n val mul = x.toInt * stack.top\n if (mul < Max) stack.push(mul)\n else stack.push(Max + 1)\n case Array(\"end\") => stack.pop()\n }\n }\n\n }\n\n println(if (value >= 0 && value <= Max) value else \"OVERFLOW!!!\")\n\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject B_1175 extends App {\n var n = readInt()\n var value = 0L\n val stack = mutable.Stack[Long]()\n\n stack.push(1)\n\n 1 to n foreach { _ =>\n readLine().split(\" \") match {\n case Array(\"add\") => value += stack.top\n case Array(\"for\", x) => stack.push(x.toInt * stack.top)\n case Array(\"end\") => stack.pop()\n }\n }\n\n println(if (value >= 0 && value <= 2147483646L) value else \"OVERFLOW!!!\")\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject B_1175 extends App {\n var n = readInt()\n var value = 0L\n val stack = mutable.Stack[Long]()\n\n stack.push(1)\n\n 1 to n foreach { _ =>\n readLine().split(\" \") match {\n case Array(\"add\") => value += stack.top\n case Array(\"for\", x) => stack.push(x.toInt * stack.top)\n case Array(\"end\") => stack.pop()\n }\n }\n\n println(if (value >= 0 && value <= 2147483646L) value else \"OVERFLOW\")\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject B_1175 extends App {\n val Max = 2147483646L\n var n = readInt()\n var value = 0L\n val stack = mutable.Stack[Long]()\n\n stack.push(1)\n\n var overflow = false\n\n 1 to n foreach { _ =>\n val line = readLine()\n if (!overflow) {\n line.split(\" \") match {\n case Array(\"add\") =>\n value += stack.top\n if (value > Max) overflow = true\n case Array(\"for\", x) =>\n val mul = x.toInt * stack.top\n if (mul < Max) stack.push(mul)\n else stack.push(Max + 1)\n case Array(\"end\") => stack.pop()\n }\n }\n\n }\n\n println(if (value >= 0 && value <= Max) value else \"OVERFLOW!!!\")\n\n}\n"}], "src_uid": "70f67dc28f9f6076255df97fc58ba2d6"} {"source_code": "import scala.io.StdIn._\n\nobject D extends App {\n val n = readInt()\n val P = readLine().split(\" \").map(_.toInt).sortWith(_ < _)\n// println(P.mkString(\" \"))\n\n def solve(): Int = {\n var happy = 0\n var needToWait = 0\n for (i <- 0 until P.length) {\n// println(s\"($needToWait <= ${P(i)})\")\n if (needToWait <= P(i)) {\n needToWait += P(i)\n happy += 1\n }\n\n\n if (needToWait > 1000000000) return happy\n }\n happy\n }\n\n println(solve())\n\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\n/**\n * http://codeforces.com/problemset/problem/545/D\n **/\nobject DQueue {\n def main(args: Array[String]): Unit = {\n StdIn.readLine()\n val timesToServe = StdIn.readLine().split(\" \").map(_.toInt)\n val (nbHappyPersons, _) = timesToServe.sorted.foldLeft((0, 0)) { case ((nbHappyPersons, accTime), timeToServe) =>\n if (accTime > timeToServe) (nbHappyPersons, accTime)\n else (nbHappyPersons + 1, accTime + timeToServe)\n }\n println(nbHappyPersons)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\nobject b extends App {\n var r = 0\n StdIn.readLine\n StdIn.readLine.split(\" \")\n .map(_.toInt)\n .sorted\n .reduce((s,x) => if (s<=x) {r+=1; s+x} else s)\n println(r+1)\n}\n"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\nobject App {\n def main(args: Array[String]) {\n\n\n\n\n StdIn.readLine()\n print(StdIn.readLine()\n .split(\" \")\n .map(_.toInt)\n .sorted\n .foldLeft( (0,0) )((r,c) =>\n if(r._1 > c) {\n r\n } else {\n (r._1 + c, r._2 + 1)\n\n }\n )._2)\n\n\n\n// val in = scala.io.Source.stdin.getLines()\n// val n = in.next().toInt\n\n// val Array(n, h, k) = StdIn.readLine().split(\" \").map(_.toLong)\n//\n// val A:Array[Long] = StdIn.readLine().split(\" \").map(_.toLong)\n//\n//\n// var curH = 0L\n// var t = 0L\n// for ( i <- 0 to A.length - 1) {\n// val nd = math.max(A(i) - (h - curH),0)\n// val d = nd / k + (if (nd % k == 0) 0 else 1)\n// t += d\n// curH = math.max(0L, curH - d * k ) + A(i)\n// }\n// val d = curH / k + (if (curH % k == 0) 0 else 1)\n// t += d\n// print(t)\n// print(A.foldLeft((0L,0L))({\n// case(b,a) =>\n// if(i == 0) {\n// (a,a)\n// } else {\n// val k = math.max(0, math.min(b._2 - 1, a))\n// (b._1 + k, k)\n// }\n// })._1)\n }\n\n\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _545D extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt).sorted.toArray\n\n def calc(i: Int, sum: Int, acc: Int): Int = {\n if (i >= n) acc\n else {\n if (sum <= a(i)) calc(i + 1, sum + a(i), acc + 1)\n else calc(i + 1, sum, acc)\n }\n }\n println(calc(0, 0, 0))\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject CF545D extends App {\n val n = StdIn.readInt\n val ts = StdIn.readLine.split(' ').map(_.toInt)\n\n var peopleLeft = ts.sorted\n var notDisappointed = 0\n var sum = 0\n while (peopleLeft.nonEmpty) {\n peopleLeft = peopleLeft.dropWhile(_ < sum)\n if (peopleLeft.nonEmpty) {\n sum += peopleLeft.head\n notDisappointed += 1\n peopleLeft = peopleLeft.tail\n }\n }\n println(notDisappointed)\n}"}, {"source_code": "object D545 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readLongs(n).sorted\n var curr = 0L\n var res = 0\n for(num <- in) {\n if(curr <= num) {\n res += 1\n curr += num\n }\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.Ordering.Implicits._\nimport scala.collection.immutable.Queue\nimport scala.collection.mutable.ArrayBuffer\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def lowerBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (!(array(mid) < value)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def solve(): Unit = {\n val n = nextInt\n val service_time = new Array[Int](n)\n for (i <- 0 until n) {\n service_time(i) = nextInt\n }\n util.Sorting.quickSort(service_time)\n var (res, sum) = (0, 0)\n for (i <- 0 until n) {\n if (service_time(i) >= sum) {\n res += 1\n sum += service_time(i)\n }\n }\n out.println(res)\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve()\n out.close\n }\n}\n"}, {"source_code": "\nimport java.util\n\n/**\n * \n *\n * @author pvasilyev\n * @since 13 Apr 2016\n */\nobject Problem150 extends App {\n private val n: Int = scala.io.StdIn.readInt()\n private val ints: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n util.Arrays.sort(ints)\n val answer: Array[Int] = new Array[Int](n)\n answer(0) = 1\n var sum = ints(0)\n for (i <- 1 until n) {\n if (sum <= ints(i)) {\n sum += ints(i)\n answer(i) = answer(i - 1) + 1\n } else {\n answer(i) = answer(i - 1)\n }\n }\n println(answer(n - 1))\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = new MultiTreeSet[Long]\n for (i <- 0 until n) {\n m.add(nextLong)\n }\n var waitTime = 0L\n var ans = 0L\n var current = m.first()\n while (current != 0 && !m.map.isEmpty) {\n if (m.count(current) > 0) {\n if (current >= waitTime) {\n ans += 1\n// out.print(current + \" \")\n m.remove(current)\n waitTime += current\n } else {\n current = m.map.ceilingKey(waitTime)\n }\n } else {\n current = m.first()\n }\n }\n out.println(ans)\n return 0\n }\n}"}, {"source_code": "object _545D extends CodeForcesApp {\n import scala.collection.mutable\n\n override type Input = List[Int]\n override type Output = Int\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n List.fill(nextInt)(nextInt).sorted\n }\n\n override def solve(input: Input) = {\n var t: Long = 0L\n var ans = 0\n\n for(i <- input) {\n //debug(input, i, t, ans)\n if(t <= i) {\n ans += 1\n t += i\n }\n }\n ans\n }\n\n override def format(result: Output) = super.format(result)\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp extends App {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /********************************[ lib ]************************************/\n import scala.collection.mutable\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type m_=>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None\n /******************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n def timeLimitSecond = 1\n}\n"}, {"source_code": "object _545D extends CodeForcesApp {\n override type Input = List[Int]\n override type Output = Int\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n List.fill(nextInt)(nextInt).sorted\n }\n\n override def solve(input: Input) = {\n var (ans, t) = (0, 0)\n for (i <- input if t <= i) {\n ans += 1\n t += i\n }\n ans\n }\n\n override def format(result: Output) = super.format(result)\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp extends App {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /********************************[ lib ]************************************/\n import scala.collection.mutable\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type m_=>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None\n /******************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n def timeLimitSecond = 1\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.collection.mutable.PriorityQueue\n\nobject Main {\n def main(args: Array[String]) {\n StdIn.readLine(); // ignoring\n\n val q = StdIn.readLine().split(\" \").map(Integer.parseInt).to[PriorityQueue].reverse;\n\n def f : Long => Int = t => {\n if(q.isEmpty)\n 0\n else {\n val v = q.dequeue();\n\n t <= v match {\n case true => f(t + v) + 1;\n case false => f(t);\n }\n }\n }\n\n println(f(0));\n }\n}"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _545D extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt).sorted.toArray\n\n def calc(i: Int, sum: Int, acc: Int): Int = {\n if (i >= n) acc\n else {\n calc(i + 1, sum + a(i), if (sum <= a(i)) acc + 1 else acc)\n }\n }\n\n println(calc(0, 0, 0))\n}\n"}, {"source_code": "\nimport java.util\n\n/**\n * \n *\n * @author pvasilyev\n * @since 13 Apr 2016\n */\nobject Problem150 extends App {\n private val n: Int = scala.io.StdIn.readInt()\n private val ints: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n util.Arrays.sort(ints)\n val latency: Array[Int] = new Array[Int](n)\n latency(0) = 0\n for (i <- 1 until n) {\n latency(i) = latency(i - 1) + ints(i - 1)\n }\n val answer: Array[Int] = new Array[Int](n)\n answer(0) = 1\n for (i <- 1 until n) {\n if (latency(i) > ints(i)) {\n answer(i) = answer(i - 1)\n } else {\n answer(i) = answer(i - 1) + 1\n }\n }\n println(answer(n - 1))\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = new MultiTreeSet[Long]\n for (i <- 0 until n) {\n m.add(nextLong)\n }\n var waitTime = 0L\n var ans = 0L\n var current = m.first()\n while (current != 0 && !m.map.isEmpty) {\n if (m.count(current) > 0) {\n if (current >= waitTime) {\n ans += 1\n out.print(current + \" \")\n m.remove(current)\n waitTime += current\n } else {\n current = m.map.ceilingKey(waitTime)\n }\n } else {\n current = m.first()\n }\n }\n out.println(ans)\n return 0\n }\n}"}, {"source_code": "object _545D extends CodeForcesApp {\n import scala.collection.mutable\n\n override type Input = List[Int]\n override type Output = Int\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n List.fill(nextInt)(nextInt).sorted\n }\n\n override def solve(input: Input) = {\n var t = 0\n var ans = 0\n\n for(i <- input) {\n //debug(input, i, t, ans)\n if(t <= i) {\n ans += 1\n }\n t += i\n }\n ans\n }\n\n override def format(result: Output) = super.format(result)\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp extends App {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /********************************[ lib ]************************************/\n import scala.collection.mutable\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type m_=>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None\n /******************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n def timeLimitSecond = 1\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject D extends App {\n val n = readInt()\n val P = readLine().split(\" \").map(_.toInt).sortWith(_ < _)\n\n def solve(): Int = {\n var happy = 0\n var needToWait = 0\n for (i <- 0 until P.length) {\n if (needToWait <= P(i)) happy += 1\n needToWait += P(i)\n\n if (needToWait > 1000000000) return happy\n }\n happy\n }\n\n println(solve())\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject D extends App {\n val n = readInt()\n val P = readLine().split(\" \").map(_.toInt).sortWith(_ < _)\n\n def solve(): Int = {\n var happy = 1\n var needToWait: BigInt = P(0)\n for (i <- 1 until P.length) {\n// println(s\"consider $i $needToWait <= ${P(i)}\")\n if (needToWait <= P(i)) happy += 1\n\n needToWait += P(i)\n\n if (needToWait > 1000000000) return happy\n }\n happy\n }\n\n println(solve())\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject D extends App {\n val n = readInt()\n val P = readLine().split(\" \").map(_.toInt).sortWith(_ < _)\n\n def solve(): Int = {\n var happy = 1\n var needToWait = P(0)\n for (i <- 1 until P.length) {\n// println(s\"consider $i $needToWait <= ${P(i)}\")\n if (needToWait <= P(i)) happy += 1\n\n needToWait += P(i)\n }\n happy\n }\n\n println(solve())\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject D extends App {\n val n = readInt()\n val P = readLine().split(\" \").map(_.toInt).sortWith(_ < _)\n\n def solve(): Int = {\n var happy = 1\n var needToWait: BigInt = P(0)\n for (i <- 1 until P.length) {\n// println(s\"consider $i $needToWait <= ${P(i)}\")\n if (needToWait <= P(i)) happy += 1\n\n needToWait += P(i)\n }\n happy\n }\n\n println(solve())\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\n/**\n * http://codeforces.com/problemset/problem/545/D\n **/\nobject DQueue {\n def main(args: Array[String]): Unit = {\n StdIn.readLine()\n val timesToServe = StdIn.readLine().split(\" \").map(_.toInt)\n val (nbHappyPersons, _) = timesToServe.sorted.foldLeft((0, 0)) { case ((nbHappyPersons, accTime), timeToServe) =>\n if (accTime > timeToServe) (nbHappyPersons, accTime + timeToServe)\n else (nbHappyPersons + 1, accTime + timeToServe)\n }\n println(nbHappyPersons)\n }\n}\n"}], "src_uid": "08c4d8db40a49184ad26c7d8098a8992"} {"source_code": "object _842B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val outer, _d = io.read[Double]\n val inner = outer - _d\n val sausages = io.read[Seq[(Double, Double, Double)]]\n\n val ans = sausages count { case (x, y, r) =>\n val d = Math.hypot(x, y)\n inner <= d - r && d + r <= outer\n }\n\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object BGlebAndPizza extends App {\n val Array(r, d) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val n = scala.io.StdIn.readLine.toInt\n val count = (0 until n).foldLeft(0) { (count, _) =>\n val Array(xi, yi, ri) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val di = xi * xi + yi * yi\n if (di >= (ri + r - d) * (ri + r - d) && di <= (r - ri) * (r - ri)) count + 1\n else count\n }\n println(count)\n}"}], "negative_code": [], "src_uid": "fce9d78ad7d4ea01be1704f588e42d37"} {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val winBy = Map.apply('S' -> 'R', 'R' -> 'P', 'P' -> 'S')\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val sn = readLine()\n\n val ans = winBy(sn.groupBy(identity).maxBy(_._2.size)._1).toString * sn.size\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "\n\nobject ProblemB extends App {\n\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n @scala.annotation.tailrec\n def gcd(a: Int, b: Int): Int = {\n if (b == 0) {\n a\n } else if (a < b) {\n gcd(b, a)\n } else {\n gcd(b, a % b)\n }\n }\n\n case class Step(n: Int, s: Int)\n\n def toPrimaryList(n: Int): List[Step] = {\n var acc = n\n var result = List[Step]()\n for (i <- 2 to math.sqrt(n).floor.toInt) {\n var count = 0\n while (acc % i == 0) {\n count = count + 1\n acc = acc / i\n }\n if (count > 0) {\n result = Step(i, count) :: result\n }\n }\n\n if (acc > 1) {\n result = Step(acc, 1) :: result\n }\n\n result\n }\n\n val t = in.nextInt()\n\n val winStrategy = Map(\"R\" -> \"S\", \"S\" -> \"P\", \"P\" -> \"R\")\n .map(p => p._2 -> p._1)\n\n for (_ <- 1 to t) {\n val s = in.nextToken()\n val mostUsed = s.groupBy(identity).maxBy(_._2.length)._1.toString\n\n val result = winStrategy(mostUsed) * s.length\n println(result)\n }\n\n}\n"}, {"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n def play(a: Char, b: Char): Int = {\n (a, b) match {\n case ('P', 'R') | ('R', 'S') | ('S', 'P') => 1\n case ('R', 'P') | ('S', 'R') | ('P', 'S') => 0//-1\n case _ => 0\n }\n }\n\n val rsp = \"RSP\"\n\n for (_ <- 1 to nextInt) {\n val s = nextLine\n val c = rsp.maxBy(c => s.map(play(c, _)).sum)\n out.println(c.toString * s.length)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val rps = Map.apply('S' -> \"R\", 'R' -> \"P\", 'P' -> \"S\")\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val sn = readLine()\n\n val ans = rps(\n List('R', 'S', 'P')\n .map(s => (s, sn.count(_ == s)))\n .sortBy(_._2)(Ordering.Int.reverse)\n .head\n ._1\n ) * sn.length\n\n println(ans)\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val t = readInt()\n 1 to t foreach { _ =>\n val A = readLine().toCharArray\n val (x, _) = A.groupBy(identity).mapValues(_.length).maxBy(_._2)\n val answer = x match {\n case 'R' => 'P'\n case 'S' => 'R'\n case 'P' => 'S'\n }\n println(Array.fill(A.length)(answer).mkString)\n }\n}\n"}], "negative_code": [{"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n def play(a: Char, b: Char): Int = {\n (a, b) match {\n case ('P', 'R') | ('R', 'S') | ('S', 'P') => 1\n case ('R', 'P') | ('S', 'R') | ('P', 'S') => -1\n case _ => 0\n }\n }\n\n val rsp = \"RSP\"\n\n for (_ <- 1 to nextInt) {\n val s = nextLine\n val c = rsp.maxBy(c => s.map(play(c, _)).sum)\n out.println(c.toString * s.length)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val sn = readLine()\n\n val ans = List('R', 'S', 'P')\n .map(s => (s, sn.count(_ == s)))\n .sortBy(_._2) //(Ordering.Int.reverse)\n .head\n ._1\n .toString * sn.length\n\n println(ans)\n }\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val sn = readLine()\n\n val ans = List('R', 'S', 'P')\n .map(s => (s, sn.count(_ == s)))\n .sortBy(_._2)(Ordering.Int.reverse)\n .head\n ._1\n .toString * sn.length\n\n println(ans)\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n\n val t = readInt()\n 1 to t foreach { _ =>\n val A = readLine().toCharArray\n val answer = A.map {\n case 'P' => 'S'\n case 'S' => 'R'\n case 'R' => 'P'\n }\n\n println(answer.mkString)\n }\n}\n"}], "src_uid": "38e884cbc5bede371bccbc848096f499"} {"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val n=nextInt\n val a=for(i<-0 until n) yield nextInt\n var l=0\n var r=1\n var maxl=2\n var mxv=a(l)\n var mnv=a(l)\n while(rmxv){\n if(mxv>mnv){\n //mxv-mnv=1, a(r)-mxv=1\n l=r-1\n while(l>0 && a(l)>mnv){\n l-=1\n }\n if(a(l)<=mnv){\n l+=1\n }\n \n mnv=mxv\n }\n mxv=a(r)\n }else if(a(r)0 && a(l)=mxv){\n l+=1\n }\n mxv=mnv\n }\n mnv=a(r)\n }\n if(r-l+1>maxl){\n maxl=r-l+1\n \n }\n r+=1\n \n }\n out.println(maxl)\n\n //code ends here\n out.flush\n out.close\n }\n}\n\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n var total_max = 1\n var max = data.head\n var min = -1\n var maxCount = 1\n var minCount = 0\n var i = 0\n var j = 1\n var str = \"\"\n data.tail.foreach { el =>\n assert(minCount >= 0, \"minCount less zero\" )\n assert(maxCount >= 0, \"maxCount less zero\" )\n assert(j == i + minCount + maxCount, str)\n if (el == max) maxCount += 1\n else if (el == min) minCount += 1\n else if (min == -1 && max - el == 1) {\n min = el\n minCount = 1\n } else if (min == -1 && el - max == 1) {\n minCount = maxCount\n maxCount = 1\n min = max\n max = el\n }\n else if (min == -1) {\n max = el\n i += maxCount\n maxCount = 1\n str = \"first\"\n }\n else if (min - el == 1) {\n while (maxCount > 0) {\n if (data(i) == min)\n minCount -= 1\n else if (data(i) == max)\n maxCount -= 1\n i += 1\n }\n str = \"second\"\n max = min\n min = el\n maxCount = minCount\n minCount = 1\n } else if (el - max == 1) {\n while (minCount > 0) {\n if (data(i) == min)\n minCount -= 1\n else if (data(i) == max)\n maxCount -= 1\n i += 1\n }\n str = \"third\"\n min = max\n max = el\n minCount = maxCount\n maxCount = 1\n } else {\n str = \"last\"\n i += minCount + maxCount\n minCount = 0\n maxCount = 1\n min = -1\n max = el\n }\n if (minCount == 0)\n min = -1\n j += 1\n total_max = Math.max(total_max, maxCount + minCount)\n }\n println(total_max)\n}"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject B_333 { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.t22.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val number = line1.int\n \n val counters = new Array[Rinf](number);\n val line2 = readLine\n var mapL = List[Rinf]()\n var mapV = List[Rinf]()\n var mapH = List[Rinf]()\n var prev = -1\n var max = 0;\n for (i <- 0 until number) {\n val vv = line2.int\n if (prev == -1 || prev == vv) { \n } else if (prev < vv) { \n val last = calcMax(mapL, i) \n// calcMax(mapV, i)\n// calcMax(mapH, i)\n mapL = mapV\n mapV = mapH\n mapH = List[Rinf]()\n clean(last, i)\n } else {\n val last = calcMax(mapH, i)\n// calcMax(mapV, i)\n// calcMax(mapL, i)\n mapH = mapV\n mapV = mapL\n mapL = List[Rinf]()\n clean(last, i)\n }\n mapV ::= new Rinf(i, vv)\n prev = vv\n dump(i, vv)\n }\n calcMax(mapL, number)\n calcMax(mapV, number)\n calcMax(mapH, number)\n \n print(max)\n \n \n def calcMax(li: List[Rinf], i: Integer) = {\n for (ri <- li) {\n val di = i - ri.start\n if (max < di) max = di\n }\n if (li == Nil) -1 else li.head.start\n }\n \n def clean(index:Integer, i:Integer) {\n if (index == -1) { return; }\n mapL = mapL.filter { x => if (x.start <= index){updateMax(x, i)} ;x.start > index }\n mapV = mapV.filter { x => if (x.start <= index){updateMax(x, i)} ;x.start > index }\n mapH = mapH.filter { x => if (x.start <= index){updateMax(x, i)} ;x.start > index }\n }\n \n def updateMax(ri:Rinf, i:Integer) {\n val di = i - ri.start\n if (max < di) max = di\n }\n \n def dump(i:Integer, value:Integer) {\n if (!debugV) return\n var res = s\"Step: $i:$value max=$max\\nL: \"\n mapL.foreach { res += _.start + \", \" }\n res += \"\\nV: \"\n mapV.foreach { res += _.start + \", \" }\n res += \"\\nH: \"\n mapH.foreach { res += _.start + \", \" }\n db(res)\n }\n \n \n \n //---------------------------- parameters reading end ----------------------\n \n }\n \n\n\n\n class Rinf(val start: Int, var value: Int) {\n var finished = false\n override def toString(): String = {\n return start + \":\" + value\n }\n }\n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n //============================================================================================\nobject Test {\nval sa1 = \"\"\"5\n1 2 3 3 2\n\"\"\"\n \nval sa2 = \"\"\"\n11\n5 4 5 5 6 7 8 8 8 7 6\n\"\"\"\n\nval t5 = \"\"\"\n4\n1 1 2 3\n\"\"\"\n\ndef t22() = {\n val n = 100000\n var res = new StringBuilder(n + \"\\n\")\n for (i <- 0 until n) {\n res append \" 100000\"\n }\n// (0 until n).foreach(x => res += \"100000\")\n// println(res.toString())\n res.toString()\n}\n\n}\n\n}\n"}], "negative_code": [{"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject B_333 { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val number = line1.int\n \n val counters = new Array[Rinf](number);\n val line2 = readLine\n var mapL = List[Rinf]()\n var mapV = List[Rinf]()\n var mapH = List[Rinf]()\n var prev = -1\n var max = 0;\n for (i <- 0 until number) {\n val vv = line2.int\n if (prev == -1 || prev == vv) { \n } else if (prev < vv) { \n val last = calcMax(mapL, i) \n calcMax(mapV, i)\n calcMax(mapH, i)\n mapL = mapV\n mapV = mapH\n mapH = List[Rinf]()\n clean(last)\n } else {\n val last = calcMax(mapH, i)\n calcMax(mapV, i)\n calcMax(mapL, i)\n mapH = mapV\n mapV = mapL\n mapL = List[Rinf]()\n clean(last)\n }\n mapV ::= new Rinf(i, vv)\n prev = vv\n dump(i, vv)\n }\n calcMax(mapL, number)\n calcMax(mapV, number)\n calcMax(mapH, number)\n \n print(max)\n \n \n def calcMax(li: List[Rinf], i: Integer) = {\n if (i == 10) {\n println(\"here\")\n }\n for (ri <- li) {\n val di = i - ri.start\n if (max < di) max = di\n }\n if (li == Nil) -1 else li.head.start\n }\n \n def clean(index:Integer) {\n if (index == -1) { return; }\n mapL = mapL.filter { x => x.start > index }\n mapV = mapV.filter { x => x.start > index }\n mapH = mapH.filter { x => x.start > index }\n }\n \n def dump(i:Integer, value:Integer) {\n var res = s\"Step: $i:$value max=$max\\nL: \"\n mapL.foreach { res += _.start + \", \" }\n res += \"\\nV: \"\n mapV.foreach { res += _.start + \", \" }\n res += \"\\nH: \"\n mapH.foreach { res += _.start + \", \" }\n db(res)\n }\n \n //---------------------------- parameters reading end ----------------------\n \n }\n \n\n\n\n class Rinf(val start: Int, var value: Int) {\n var finished = false\n override def toString(): String = {\n return start + \":\" + value\n }\n }\n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n //============================================================================================\nobject Test {\nval sa1 = \"\"\"5\n1 2 3 3 2\n\"\"\"\n \nval sa2 = \"\"\"\n11\n5 4 5 5 6 7 8 8 8 7 6\n\"\"\"\n\nval t5 = \"\"\"\n4\n1 1 2 3\n\"\"\"\n\n}\n\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject B_333 { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.sa2.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val number = line1.int\n \n val counters = new Array[Rinf](number);\n val line2 = readLine\n var mapL = List[Rinf]()\n var mapV = List[Rinf]()\n var mapH = List[Rinf]()\n var prev = -1\n var max = 0;\n for (i <- 0 until number) {\n val vv = line2.int\n if (prev == -1 || prev == vv) { \n } else if (prev < vv) { \n val last = calcMax(mapL, i) \n mapL = mapV\n mapV = mapH\n mapH = List[Rinf]()\n clean(last)\n } else {\n val last = calcMax(mapH, i) \n mapH = mapV\n mapV = mapL\n mapL = List[Rinf]()\n clean(last)\n }\n mapV ::= new Rinf(i, vv)\n prev = vv\n dump(i, vv)\n }\n calcMax(mapL, number-1)\n calcMax(mapV, number-1)\n calcMax(mapH, number-1)\n \n print(max)\n \n \n def calcMax(li: List[Rinf], i: Integer) = {\n for (ri <- li) {\n val di = i - ri.start + 1\n if (max < di) max = di\n }\n if (li == Nil) -1 else li.head.start\n }\n \n def clean(index:Integer) {\n if (index == -1) { return; }\n mapL = mapL.filter { x => x.start > index }\n mapV = mapV.filter { x => x.start > index }\n mapH = mapH.filter { x => x.start > index }\n }\n \n def dump(i:Integer, value:Integer) {\n var res = s\"Step: $i:$value \\nL: \"\n mapL.foreach { res += _.start + \", \" }\n res += \"\\nV: \"\n mapV.foreach { res += _.start + \", \" }\n res += \"\\nH: \"\n mapH.foreach { res += _.start + \", \" }\n db(res)\n }\n \n //---------------------------- parameters reading end ----------------------\n \n }\n \n\n\n\n class Rinf(val start: Int, var value: Int) {\n var finished = false\n override def toString(): String = {\n return start + \":\" + value\n }\n }\n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n //============================================================================================\nobject Test {\nval sa1 = \"\"\"5\n1 2 3 3 2\n\"\"\"\n \nval sa2 = \"\"\"\n11\n5 4 5 5 6 7 8 8 8 7 6\n\"\"\"\n\n}\n\n}\n"}], "src_uid": "b784cebc7e50cc831fde480171b9eb84"} {"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, q, c) = readInts(3)\n\n val cnt = Array.fill(c + 1, 101, 101){ 0 }\n\n Array.fill(n) {\n val Array(x, y, s) = readInts(3)\n cnt(s)(x)(y) += 1\n }\n\n for (s <- 0 to c) {\n for (y <- 1 to 100) {\n var left = 0\n for (x <- 1 to 100) {\n left += cnt(s)(x)(y)\n cnt(s)(x)(y) = left + cnt(s)(x)(y - 1)\n }\n }\n }\n\n val res = Array.ofDim[Int](q)\n\n for (i <- 0 until q) {\n val Array(t, x1, y1, x2, y2) = readInts(5)\n var sum = 0\n for (s <- 0 to c) {\n val count = cnt(s)(x2)(y2) - cnt(s)(x1 - 1)(y2) - cnt(s)(x2)(y1 - 1) + cnt(s)(x1 - 1)(y1 - 1)\n val brightness = (s + t) % (c + 1)\n sum += count * brightness\n }\n res(i) = sum\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\"\\n\"))\n\n Console.flush\n}\n", "positive_code": [{"source_code": "object CStarSky extends App {\n val Array(n, q, c) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n\n var cnt = Array.fill[Int](c + 1, 101, 101){0}\n (0 until n).foreach { _ =>\n val Array(x, y, s) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n cnt(s)(x)(y) = cnt(s)(x)(y) + 1\n }\n for (p <- 0 to c; x <- 1 to 100; y <- 1 to 100)\n cnt(p)(x)(y) = cnt(p)(x)(y) + cnt(p)(x - 1)(y) + cnt(p)(x)(y - 1) - cnt(p)(x - 1)(y - 1)\n\n (0 until q).foreach { _ =>\n val Array(t, x1, y1, x2, y2) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val s = (0 to c).foldLeft(0) { (s, p) =>\n val brightness = (p + t) % (c + 1)\n val amount = cnt(p)(x2)(y2) + cnt(p)(x1-1)(y1-1) - cnt(p)(x1-1)(y2) - cnt(p)(x2)(y1-1)\n s + brightness * amount\n }\n println(s)\n }\n}"}], "negative_code": [], "src_uid": "4efb7bc87bdba2b7fd33ce1734754a50"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N = ni()\n val A = na(N)\n if (N == 2) {\n out.println(0)\n } else {\n sort(A)\n val A1 = A(N - 1)\n val A2 = A(N - 2)\n val cnt = N - 2\n val ans = min(cnt, min(A1 - 1, A2 - 1))\n out.println(ans)\n }\n }\n }\n\n def sort(a: Array[Int]): Array[Int] = {\n val n = a.length\n REP(n) { i =>\n val j = scala.util.Random.nextInt(n - i) + i\n val tmp = a(i)\n a(i) = a(j)\n a(j) = tmp\n }\n java.util.Arrays.sort(a)\n a\n }\n}", "positive_code": [{"source_code": "//package codeforces.contest1197\n\nobject DIYWoodenLadder {\n def main(args: Array[String]): Unit = {\n println((1 to io.StdIn.readInt).map { _ =>\n val n = io.StdIn.readInt()\n val seq = io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n\n if (seq.length > 2) {\n seq(n - 2) - 1 min n - 2\n } else 0\n\n\n }.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject problemA {\n def main(args: Array[String]): Unit = {\n val T = scala.io.StdIn.readInt()\n (0 until T).map(_ => {\n val n = scala.io.StdIn.readInt()\n val reader = new StringTokenizer(scala.io.StdIn.readLine(), \" \")\n val initmax1 = reader.nextToken().toInt\n val initmax2 = reader.nextToken().toInt\n var max1 = Math.max(initmax1, initmax2)\n var max2 = Math.min(initmax1, initmax2)\n val steps = (2 until n).map(_ => {\n val i = reader.nextToken().toInt\n if (i >= max1) {\n max2 = max1\n max1 = i\n } else if (i > max2) {\n max2 = i\n } else()\n i\n })\n Math.min(max2 - 1, steps.size)\n }).foreach(println)\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nobject solve {\n def main(args: Array[String]): Unit = {\n val T = scala.io.StdIn.readInt()\n (0 until T).foreach(_ => {\n val n = scala.io.StdIn.readInt()\n val reader = new StringTokenizer(scala.io.StdIn.readLine(), \" \")\n val initmax1 = reader.nextToken().toInt\n val initmax2 = reader.nextToken().toInt\n var max1 = Math.max(initmax1, initmax2)\n var max2 = Math.min(initmax1, initmax2)\n val steps = (2 until n).map(_ => {\n val i = reader.nextToken().toInt\n if (i >= max1) {\n max2 = max1\n max1 = i\n }\n i\n })\n val res = Math.min(max2 - 1, steps.size)\n\n println(res)\n })\n }\n\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject solve {\n def main(args: Array[String]): Unit = {\n val T = scala.io.StdIn.readInt()\n (0 until T).map(_ => {\n val n = scala.io.StdIn.readInt()\n val reader = new StringTokenizer(scala.io.StdIn.readLine(), \" \")\n val initmax1 = reader.nextToken().toInt\n val initmax2 = reader.nextToken().toInt\n var max1 = Math.max(initmax1, initmax2)\n var max2 = Math.min(initmax1, initmax2)\n val steps = (2 until n).map(_ => {\n val i = reader.nextToken().toInt\n if (i >= max1) {\n max2 = max1\n max1 = i\n }\n i\n })\n Math.min(max2 - 1, steps.size)\n }).foreach(println)\n }\n\n}"}], "src_uid": "130fd7f40d879e25b0bff886046bf699"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt).groupBy(k => k).map(t => t._1 -> t._2.length)\n val first = Math.max(0, data.getOrElse(1, 0) - m)\n val second =\n if (first == 0)\n Math.max(0, data.getOrElse(2, 0) - k - m + data.getOrElse(1, 0))\n else\n Math.max(0, data.getOrElse(2, 0) - k)\n println(first + second)\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, m, k) = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \")\n val c1 = a.count(_ == \"1\")\n val c2 = a.count(_ == \"2\")\n \n val count = (c1 - m).max(0) + (c2 - k - (m - c1).max(0)).max(0)\n println(count)\n }\n}"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-19.\n */\nobject A369 extends App{\n val sc = new Scanner(System.in)\n val n, m, k = sc.nextInt()\n val a: Array[Int] = (1 to n).map(_ => sc.nextInt()).toArray\n val needBowl = a.count(_ == 1)\n val needAny = n - needBowl\n\n // 需要洗的碗\n val needWashBowl = if (m - needBowl >= 0) {\n 0\n } else {\n needBowl - m\n }\n\n // 需要洗的其他\n val needWashAny: Int = if (needWashBowl == 0) {\n needAny - (m - needBowl + k) // 存量的其他\n } else {\n needAny - k\n }\n\n println(needWashBowl + (if (needWashAny < 0) {\n 0\n } else {\n needWashAny\n }))\n}\n"}, {"source_code": "object HelloWorld {\n def main(args:Array[String]){\n var nmk=readLine().split(\" \").map(_.toInt)\n var n=nmk(0)\n var m=nmk(1)\n var k=nmk(2)\n var sum=0\n var array=readLine().split(\" \").map(_.toInt)\n for(i<-0 to n-1){\n var int=array(i)\n if(int==1){\n if (m>=1) {\n m-=1\n }else{\n sum+=1\n }\n }else{\n if (k>=1) {\n k-=1\n }else if(m>=1){\n m-=1\n }else{\n sum+=1\n }\n }\n }\n println(sum)\n }\n}"}, {"source_code": "object HelloWorld {\n def main(args:Array[String]){\n var Array(n,m,k)=readLine().split(\" \").map(_.toInt)\n var sum=0\n var array=readLine().split(\" \")\n for(i<-0 to n-1){\n var int=array(i).toInt\n if(int==1){\n if (m>=1) {\n m-=1\n }else{\n sum+=1\n }\n }else{\n if (k>=1) {\n k-=1\n }else if(m>=1){\n m-=1\n }else{\n sum+=1\n }\n }\n }\n println(sum)\n }\n}"}, {"source_code": "object HelloWorld {\n def main(args:Array[String]){\n var Array(n,m,k)=readLine().split(\" \").map(_.toInt)\n var sum=0\n var array=readLine().split(\" \").map(_.toInt)\n for(i<-0 to n-1){\n var int=array(i)\n if(int==1){\n if (m>=1) {\n m-=1\n }else{\n sum+=1\n }\n }else{\n if (k>=1) {\n k-=1\n }else if(m>=1){\n m-=1\n }else{\n sum+=1\n }\n }\n }\n println(sum)\n }\n}"}, {"source_code": "object Solution216A extends App {\n\n def solution() {\n val n = _int\n val b = _int\n val p = _int\n\n val a = 1.to(n).map(_ => _int)\n val gr = a.groupBy(i => i)\n val n1 = gr.get(1).getOrElse(Nil).size\n val n2 = math.max(gr.get(2).getOrElse(Nil).size - p, 0)\n\n val req = n1 + n2\n\n if (req <= b) {\n println(0)\n } else {\n println(req - b)\n }\n }\n\n //////////////////////////////////////////////////\n import java.util.Scanner\n val SC: Scanner = new Scanner(System.in)\n def _line: String = SC.nextLine\n def _int: Int = SC.nextInt\n def _long: Long = SC.nextLong\n def _string: String = SC.next\n solution()\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _369A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n var m = next.toInt\n val k = next.toInt\n val a = (1 to n).map(i => next.toInt)\n val one = a.filter(i => i == 1).size\n val two = a.filter(i => i == 2).size\n\n var ans = if (m >= one) 0 else one - m\n m = if (m - one >= 0) m - one else 0\n ans = ans + (if (m + k - two >= 0) 0 else two - m - k)\n println(ans)\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P369A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, M, K = sc.nextInt\n type Dishes = List[Int]\n val A: Dishes = List.fill(N)(sc.nextInt)\n\n\n def solve(): Int = {\n\n @tailrec\n def loop(acc: Int, b: Int, p: Int, ds: Dishes): Int = ds match { //\n case Nil => acc\n case 1 :: rest => { // first type from bowl\n if (b > 0) loop(acc, b - 1, p, rest)\n else loop(acc + 1, 0, p, rest)\n }\n case 2 :: rest => { // second type from either bowl or plate\n if (p > 0) loop(acc, b, p - 1, rest)\n else if (b > 0) loop(acc, b - 1, p, rest)\n else loop(acc + 1, 0, 0, rest)\n }\n case _ => -1\n }\n\n loop(0, M, K, A)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "object A369 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n var Array(n, m, k) = readInts(3)\n val in = readInts(n)\n var res = 0\n for(i <- 0 until n) {\n val day = in(i)\n if(day == 1) {\n if(m > 0) {m -= 1} else {res += 1}\n } else {\n if(m > 0 || k > 0) {\n if(k > 0) {\n k -= 1\n } else {\n m -= 1\n }\n } else {\n res += 1\n }\n }\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P369A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, M, K = sc.nextInt\n val A = List.fill(N)(sc.nextInt)\n\n type Dishes = List[Int]\n\n def solve(): Int = {\n\n @tailrec\n def loop(acc: Int, b: Int, p: Int, ds: Dishes): Int = ds match { //\n case Nil => acc\n case 1 :: rest => { // first type from bowl and dish\n if (b < 1) loop(acc + 1, M, K, rest)\n else loop(acc, b - 1, p, rest)\n }\n case 2 :: rest => { // second type from either bowl or plate\n if (b < p) {\n if (p < 1) loop(acc + 1, M, K, rest)\n else loop(acc, b, p - 1, rest)\n }\n else {\n if (b < 1) loop(acc + 1, M, K, rest)\n else loop(acc, b - 1, p, rest)\n }\n }\n case _ => -1\n }\n\n loop(0, M, K, A)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P369A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, M, K = sc.nextInt\n val A = List.fill(N)(sc.nextInt)\n\n type Dishes = List[Int]\n\n def solve(): Int = {\n\n @tailrec\n def loop(acc: Int, b: Int, p: Int, ds: Dishes): Int = ds match { //\n case Nil => acc\n case 1 :: rest => { // first type from bowl and dish\n val wash = if (b < 1) 1 else 0\n loop(acc + wash, b - 1, p, rest)\n }\n case 2 :: rest => { // second type from either bowl or plate\n val wash = if (b < 1 && p < 1) 1 else 0\n if (b < p) loop(acc + wash, b, p - 1, rest)\n else loop(acc + wash, b - 1, p, rest)\n }\n case _ => -1\n }\n\n loop(0, M, K, A)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-19.\n */\nobject A369 extends App{\n val sc = new Scanner(System.in)\n val n, m, k = sc.nextInt()\n val a: Array[Int] = (1 to n).map(_ => sc.nextInt()).toArray\n val needBowl = a.count(_ == 1)\n val needAny = n - needBowl\n\n // 需要洗的碗\n val needWashBowl = if (m - needBowl >= 0) {\n 0\n } else {\n needBowl - m\n }\n\n val needWashAny: Int = if (needWashBowl == 0) {\n needAny - (m - needBowl + n)\n } else {\n needAny - k\n }\n\n println(needWashBowl + (if (needWashAny < 0) {\n 0\n } else {\n needWashAny\n }))\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt).groupBy(k => k).map(t => t._1 -> t._2.length)\n println(Math.max(0, data.getOrElse(1, 0) - m) + Math.max(0, data.getOrElse(2, 0) - k))\n}"}, {"source_code": "object A369 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n var Array(n, m, k) = readInts(3)\n val in = readInts(n)\n var res = 0\n for(i <- 0 until n) {\n val day = in(i)\n if(day == 1) {\n if(m > 0) {m -= 1} else {res += 1}\n } else {\n if(m > 0 || k > 0) {\n if(m > k) {\n m -= 1\n } else {\n k -= 1\n }\n } else {\n res += 1\n }\n }\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "4ed5b8055ce48b5ad4e43ed4b06d1b07"} {"source_code": "import scala.io.StdIn._\r\nimport scala.util.control.Breaks._\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n val Array(n, m): Array[Int] = readLine().split(\" \").map(_.toInt)\r\n val A: Array[Long] = readLine().split(\" \").map(_.toLong)\r\n val pref: Array[Long] = Array.fill(n)(0)\r\n val suff: Array[Long] = Array.fill(n)(0)\r\n for (i <- 1 until n) {\r\n pref(i) = pref(i-1) - (A(i) - A(i-1)).min(0)\r\n }\r\n for (i <- n-2 to 0 by -1) {\r\n suff(i) = suff(i+1) - (A(i) - A(i+1)).min(0)\r\n }\r\n \r\n for (_ <- 1 to m) {\r\n val Array(s, t) = readLine().split(\" \").map(x => x.toInt-1)\r\n if (s == t) {\r\n println(0)\r\n } else if (s < t) {\r\n println(pref(t)-pref(s))\r\n } else {\r\n println(suff(t)-suff(s))\r\n }\r\n }\r\n }\r\n}", "positive_code": [{"source_code": "\r\n\r\nobject prob2 {\r\n def main(args: Array[String]) = {\r\n new Resolver3(Console.in, Console.out).run()\r\n }\r\n}\r\n\r\nclass Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {\r\n\r\n import java.util.StringTokenizer\r\n import scala.collection.mutable\r\n import scala.collection.mutable._\r\n import scala.math.{abs,pow,min,max}\r\n import scala.collection.mutable.ListBuffer\r\n\r\n def run() {\r\n var tokenizer = new StringTokenizer(input.readLine())\r\n val m = tokenizer.nextToken().toInt\r\n val q = tokenizer.nextToken().toInt\r\n val C = new Array[Long](m)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (i <- 1 to m) {\r\n C(i-1) = tokenizer.nextToken().toLong\r\n }\r\n val B = new Array[Long](m)\r\n val A = new Array[Long](m)\r\n A(0) = 0\r\n B(m-1) = 0\r\n for (i <- 1 to m-1) {\r\n A(i) = A(i-1) + max(0,C(i-1) - C(i))\r\n B(m-1-i) = B(m-1-i+1) + max(0,C(m-1-i+1) - C(m-1-i))\r\n }\r\n for (sss <- 0 until q) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val n1 = tokenizer.nextToken().toInt\r\n val n2 = tokenizer.nextToken().toInt\r\n if (n1 < n2) {\r\n println(A(n2-1) - A(n1-1))\r\n }\r\n else {\r\n println(B(n2-1) - B(n1-1))\r\n }\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "a6f42cb2627a7d1f6e01860322c5aac5"} {"source_code": "import scala.collection.mutable\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val ds = readInts(n)\n\n val adjBuilders, edgeIdBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n\n for (id <- 1 to m) {\n val Array(_u, _v) = readInts(2)\n val u = _u - 1\n val v = _v - 1\n\n adjBuilders(u) += v\n adjBuilders(v) += u\n\n edgeIdBuilders(u) += id\n edgeIdBuilders(v) += id\n }\n\n val firstMinus = ds.indexOf(-1)\n val sumParity = ds.count(_ == 1) % 2\n\n if (firstMinus == -1 && sumParity == 1) {\n println(-1)\n } else {\n\n for (i <- ds.indices) {\n if (ds(i) == -1) ds(i) = if (i == firstMinus && sumParity == 1) 1 else 0\n }\n\n val adjs = adjBuilders.map(_.result)\n val edgeIds = edgeIdBuilders.map(_.result)\n\n val visited = new mutable.BitSet(n)\n val leaves = mutable.Queue.empty[Int]\n val childrenCounts = Array.fill(n)(0)\n val parents, parentEdges = Array.fill(n)(-1)\n\n def dfs(u: Int): Unit = {\n visited(u) = true\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (!visited(v)) {\n childrenCounts(u) += 1\n parents(v) = u\n parentEdges(v) = edgeIds(u)(i)\n dfs(v)\n }\n i += 1\n }\n if (childrenCounts(u) == 0) leaves += u\n }\n\n dfs(0)\n\n val resultBuilder = new mutable.ArrayBuilder.ofInt\n\n while (leaves.nonEmpty) {\n val u = leaves.dequeue()\n val v = parents(u)\n if (v >= 0) {\n\n if (ds(u) == 1) {\n resultBuilder += parentEdges(u)\n ds(v) = 1 - ds(v)\n }\n childrenCounts(v) -= 1\n if (childrenCounts(v) == 0) leaves += v\n }\n }\n\n val res = resultBuilder.result\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.length)\n println(res.sorted.mkString(\"\\n\"))\n Console.flush\n }\n}", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = {\n val tl = tokenizeLine\n val a = Array.ofDim[Int](n)\n var i = 0\n while (i < n) {\n a(i) = Integer.parseInt(tl.nextToken)\n i += 1\n }\n a\n }\n\n val Array(n, m) = readInts(2)\n val ds = readInts(n)\n\n val adjBuilders, edgeIdBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n\n for (id <- 1 to m) {\n val Array(_u, _v) = readInts(2)\n val u = _u - 1\n val v = _v - 1\n\n adjBuilders(u) += v\n adjBuilders(v) += u\n\n edgeIdBuilders(u) += id\n edgeIdBuilders(v) += id\n }\n\n val firstMinus = ds.indexOf(-1)\n val sumParity = ds.count(_ == 1) % 2\n\n if (firstMinus == -1 && sumParity == 1) {\n println(-1)\n } else {\n\n for (i <- ds.indices) {\n if (ds(i) == -1) ds(i) = if (i == firstMinus && sumParity == 1) 1 else 0\n }\n\n val adjs = adjBuilders.map(_.result)\n val edgeIds = edgeIdBuilders.map(_.result)\n\n val visited = new mutable.BitSet(n)\n val leaves = mutable.Queue.empty[Int]\n val childrenCounts = Array.fill(n)(0)\n val parents, parentEdges = Array.fill(n)(-1)\n\n def dfs(u: Int): Unit = {\n visited(u) = true\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (!visited(v)) {\n childrenCounts(u) += 1\n parents(v) = u\n parentEdges(v) = edgeIds(u)(i)\n dfs(v)\n }\n i += 1\n }\n if (childrenCounts(u) == 0) leaves += u\n }\n\n dfs(0)\n\n val resultBuilder = new mutable.ArrayBuilder.ofInt\n\n while (leaves.nonEmpty) {\n val u = leaves.dequeue()\n val v = parents(u)\n if (v >= 0) {\n\n if (ds(u) == 1) {\n resultBuilder += parentEdges(u)\n ds(v) = 1 - ds(v)\n }\n childrenCounts(v) -= 1\n if (childrenCounts(v) == 0) leaves += v\n }\n }\n\n val res = resultBuilder.result\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.length)\n println(res.sorted.mkString(\"\\n\"))\n Console.flush\n }\n}"}, {"source_code": "import scala.collection.mutable\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(Integer.parseInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val ds = readInts(n)\n\n val adjBuilders, edgeIdBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n\n for (id <- 1 to m) {\n val Array(_u, _v) = readInts(2)\n val u = _u - 1\n val v = _v - 1\n\n adjBuilders(u) += v\n adjBuilders(v) += u\n\n edgeIdBuilders(u) += id\n edgeIdBuilders(v) += id\n }\n\n val firstMinus = ds.indexOf(-1)\n val sumParity = ds.count(_ == 1) % 2\n\n if (firstMinus == -1 && sumParity == 1) {\n println(-1)\n } else {\n\n for (i <- ds.indices) {\n if (ds(i) == -1) ds(i) = if (i == firstMinus && sumParity == 1) 1 else 0\n }\n\n val adjs = adjBuilders.map(_.result)\n val edgeIds = edgeIdBuilders.map(_.result)\n\n val visited = new mutable.BitSet(n)\n val leaves = mutable.Queue.empty[Int]\n val childrenCounts = Array.fill(n)(0)\n val parents, parentEdges = Array.fill(n)(-1)\n\n def dfs(u: Int): Unit = {\n visited(u) = true\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (!visited(v)) {\n childrenCounts(u) += 1\n parents(v) = u\n parentEdges(v) = edgeIds(u)(i)\n dfs(v)\n }\n i += 1\n }\n if (childrenCounts(u) == 0) leaves += u\n }\n\n dfs(0)\n\n val resultBuilder = new mutable.ArrayBuilder.ofInt\n\n while (leaves.nonEmpty) {\n val u = leaves.dequeue()\n val v = parents(u)\n if (v >= 0) {\n\n if (ds(u) == 1) {\n resultBuilder += parentEdges(u)\n ds(v) = 1 - ds(v)\n }\n childrenCounts(v) -= 1\n if (childrenCounts(v) == 0) leaves += v\n }\n }\n\n val res = resultBuilder.result\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.length)\n println(res.sorted.mkString(\"\\n\"))\n Console.flush\n }\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val ds = readInts(n)\n\n val adjBuilders, edgeIdBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n\n for (id <- 1 to m) {\n val Array(_u, _v) = readInts(2)\n val u = _u - 1\n val v = _v - 1\n adjBuilders(u) += v\n adjBuilders(v) += u\n edgeIdBuilders(u) += id\n edgeIdBuilders(v) += id\n }\n\n val adjs = adjBuilders.map(_.result)\n val edgeIds = edgeIdBuilders.map(_.result)\n\n val checked = new mutable.BitSet(m)\n val resultBuilder = new mutable.ArrayBuilder.ofInt\n\n def dfs(u: Int): Unit = {\n var i = 0\n while (i < adjs(u).length) {\n val edgeId = edgeIds(u)(i)\n val v = adjs(u)(i)\n if (!checked(edgeId)) {\n checked(edgeId) = true\n if (ds(u) == 1 || ds(v) == 1) {\n resultBuilder += edgeId\n if (ds(u) != -1) ds(u) = 1 - ds(u)\n if (ds(v) != -1) ds(v) = 1 - ds(v)\n }\n dfs(v)\n }\n i += 1\n }\n }\n\n dfs(0)\n\n val res = resultBuilder.result\n val ok = !ds.contains(1)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (ok) {\n println(res.length)\n println(res.sorted.mkString(\"\\n\"))\n } else {\n println(-1)\n }\n\n Console.flush\n}\n"}], "src_uid": "c046e64e008e997620efc21aec199bdb"} {"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val tb = stdin.next().toInt\n println(stdin.take(tb * 2).grouped(2).map(_.toArray).map(solve).mkString(\"\\n\"))\n\n def solve(arr: Array[String]): Int = {\n val Array(s, t) = arr\n val cache = Array.fill[Int](s.length, 26)(-1)\n s.zipWithIndex.foreach{\n case (ch, index) =>\n Range(index, -1, -1).takeWhile(i => cache(i)(ch - 'a') == -1).foreach(i => cache(i)(ch - 'a') = index)\n }\n// cache.foreach(i => println(i.mkString(\" \")))\n val hasSolution = t.distinct.forall(ch => cache(0)(ch - 'a') != -1)\n if (!hasSolution) -1\n else {\n var matched = 0\n var lookCh = t.head\n var steps = 0\n while (matched < t.length) {\n var pos = 0\n steps += 1\n while (pos < s.length && cache(pos)(lookCh - 'a') != -1) {\n while (cache(pos)(lookCh - 'a') != pos && cache(pos)(lookCh - 'a') != -1)\n pos = cache(pos)(lookCh - 'a')\n if (cache(pos)(lookCh - 'a') != -1) {\n pos += 1\n matched += 1\n if (matched < t.length)\n lookCh = t.charAt(matched)\n }\n }\n }\n steps\n }\n }\n}\n\n\n//1\n//6\n//1 1 1 2 2 1 2 1 2 1 1 2", "positive_code": [{"source_code": "object Main extends App {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n solve(System.in,System.out)\n\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val m = Array.fill(30)(Array.fill(100001)(0))\n val count = Array.fill(30)(0)\n val in = new InputReader(inputStream)\n val cases = in.nextInt()\n\n (1 to cases).foreach { _ =>\n val s = in.next()\n val t = in.next()\n (0 until 30).foreach(i => count(i) = 0)\n s.zipWithIndex.foreach{\n case (ch,i) => {\n val indxChar = (ch.toInt)- 'a'.toInt\n m(indxChar)(count(indxChar)) = i\n count(indxChar) = count(indxChar) + 1\n }\n }\n\n var sIndex = 0\n var tIndex = 0\n val maxSteps = t.length+1\n var steps = 1\n while(steps < maxSteps && (tIndex < t.length)){\n\n val ch = t.charAt(tIndex).toInt-'a'.toInt\n\n calcIndex(m,count,ch,sIndex) match {\n case Some(newSIndex) => {\n tIndex += 1\n sIndex = newSIndex+1\n }\n case None => {\n steps += 1\n sIndex = 0\n }\n }\n }\n if(tIndex == t.length){\n out.println(steps)\n }else{\n out.println(-1)\n }\n }\n\n }\n def calcIndex(m: Array[Array[Int]], count: Array[Int],a: Int, i: Int): Option[Int] = {\n val l = count(a)\n if(l == 0) {\n None\n } else{\n if(m(a)(l-1) < i) {\n\n None\n } else\n Some(calcIndex(m(a),l-1,i))\n }\n }\n def calcIndex(list: Array[Int], maxL: Int, i: Int): Int= {\n var left = 0\n var right = maxL\n //se asegura que list[right] <= i\n while(right - left > 1){\n val k = (left+right)/2\n if(list(k) < i){\n left = k\n }else{\n right = k\n }\n }\n if(list(left) >= i)\n list(left)\n else\n list(right)\n }\n\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "negative_code": [{"source_code": "object Main extends App {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n solve(System.in,System.out)\n\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val m = Array.fill(30)(ListBuffer.empty[Int])\n val in = new InputReader(inputStream)\n val cases = in.nextInt()\n\n (1 to cases).foreach { _ =>\n val s = in.next()\n val t = in.next()\n m.foreach(_.clear())\n s.zipWithIndex.foreach{\n case (ch,i) => {\n val indxChar = (ch.toInt)- 'a'.toInt\n m(indxChar).append(i)\n }\n }\n\n var sIndex = 0\n var tIndex = 0\n val maxSteps = t.length+1\n var steps = 1\n while(steps < maxSteps && (tIndex < t.length)){\n\n val ch = t.charAt(tIndex).toInt-'a'.toInt\n\n\n calcIndex(m,ch,sIndex) match {\n case Some(newSIndex) => {\n tIndex += 1\n sIndex = newSIndex+1\n }\n case None => {\n steps += 1\n sIndex = 0\n }\n }\n }\n if(tIndex == t.length){\n out.println(steps)\n }else{\n out.println(-1)\n }\n }\n\n }\n def calcIndex(m: Array[ListBuffer[Int]],a: Int, i: Int): Option[Int] = {\n val l = m(a)\n if(l.isEmpty) {\n None\n } else{\n if(l.last < i) {\n\n None\n } else\n Some(calcIndex(l,i))\n }\n }\n def calcIndex(list: ListBuffer[Int], i: Int): Int= {\n var left = 0\n var right = list.length-1\n //se asegura que list[right] <= i\n while(right - left > 1){\n val k = (left+right)/2\n if(list(k) < i){\n left = k\n }else{\n right = k\n }\n }\n list(right)\n }\n\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "src_uid": "d132158607bbd0541f2232a300e4a1b1"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val H, W = ni()\n val r, c = ni() - 1\n val L, R = ni()\n val grid = Array.ofDim[Array[Boolean]](H)\n rep(H) { i =>\n grid(i) = ns(W) map (_ == '.')\n }\n\n val INF = 1e9.toInt\n val D = Array.fill[Int](H, W)(INF)\n\n case class Coord(h: Int, w: Int)\n\n def valid(h: Int, w: Int): Boolean = {\n 0 <= h && h < H && 0 <= w && w < W && grid(h)(w)\n }\n\n case class Direction(dh: Int, dw: Int, weight: Int)\n val directions = Array(\n Direction(0, -1, 1),\n Direction(0, 1, 1),\n Direction(-1, 0, 0),\n Direction(1, 0, 0)\n )\n\n def ok(h: Int, w: Int, cost: Int) = {\n val extraCost = cost - abs(w - c)\n val l = extraCost / 2 + max(c - w, 0)\n val r = extraCost / 2 + max(w - c, 0)\n l <= L && r <= R\n }\n var ans = 1\n def dijk() = {\n case class Visit(v: Coord, cost: Int) extends Comparable[Visit] {\n override def compareTo(o: Visit): Int = java.lang.Integer.compare(cost, o.cost)\n }\n val queue = new java.util.LinkedList[Visit]()\n D(r)(c) = 0\n queue.add(Visit(Coord(r, c), 0))\n\n while(!queue.isEmpty) {\n val v = queue.pollFirst()\n if (D(v.v.h)(v.v.w) == v.cost) {\n rep(4) { i =>\n val d = directions(i)\n val h1 = v.v.h + d.dh\n val w1 = v.v.w + d.dw\n if (valid(h1, w1) && ok(h1, w1, v.cost + d.weight)) {\n val next = v.cost + d.weight\n if (D(h1)(w1) > next) {\n ans += 1\n D(h1)(w1) = next\n if (d.weight == 0) {\n queue.addFirst(Visit(Coord(h1, w1), next))\n } else {\n queue.addLast(Visit(Coord(h1, w1), next))\n }\n }\n }\n }\n }\n }\n }\n\n dijk()\n\n out.println(ans)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val H, W = ni()\n val r, c = ni() - 1\n val L, R = ni()\n val grid = Array.ofDim[Array[Boolean]](H)\n rep(H) { i =>\n grid(i) = ns(W) map (_ == '.')\n }\n\n val INF = 1e9.toInt\n val D = Array.fill[Int](H, W)(INF)\n\n case class Coord(h: Int, w: Int)\n\n def valid(h: Int, w: Int): Boolean = {\n 0 <= h && h < H && 0 <= w && w < W && grid(h)(w)\n }\n\n case class Direction(dh: Int, dw: Int, weight: Int)\n val directions = Array(\n Direction(0, -1, 1),\n Direction(0, 1, 1),\n Direction(-1, 0, 0),\n Direction(1, 0, 0)\n )\n\n def ok(h: Int, w: Int, cost: Int) = {\n val extraCost = cost - abs(w - c)\n val l = extraCost / 2 + max(c - w, 0)\n val r = extraCost / 2 + max(w - c, 0)\n l <= L && r <= R\n }\n var ans = 1\n def dijk() = {\n case class Visit(v: Coord, cost: Int) extends Comparable[Visit] {\n override def compareTo(o: Visit): Int = java.lang.Integer.compare(cost, o.cost)\n }\n val queue = new java.util.ArrayDeque[Visit]()\n D(r)(c) = 0\n queue.add(Visit(Coord(r, c), 0))\n\n while(!queue.isEmpty) {\n val v = queue.pollFirst()\n if (D(v.v.h)(v.v.w) == v.cost) {\n rep(4) { i =>\n val d = directions(i)\n val h1 = v.v.h + d.dh\n val w1 = v.v.w + d.dw\n if (valid(h1, w1) && ok(h1, w1, v.cost + d.weight)) {\n val next = v.cost + d.weight\n if (D(h1)(w1) > next) {\n ans += 1\n D(h1)(w1) = next\n if (d.weight == 0) {\n queue.addFirst(Visit(Coord(h1, w1), next))\n } else {\n queue.addLast(Visit(Coord(h1, w1), next))\n }\n }\n }\n }\n }\n }\n }\n\n dijk()\n\n out.println(ans)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}], "negative_code": [], "src_uid": "cfdbe4bd1c9438de2d871768c546a580"} {"source_code": "import scala.io.StdIn\n\nobject SolutionA extends App {\n val T = StdIn.readInt()\n for (t <- 1 to T) {\n val n = StdIn.readInt();\n if (n == 1) {\n println(1)\n } else {\n var k = 2\n while (n % ((1 << k) - 1) != 0) {\n k += 1\n }\n println(n / ((1 << k) - 1))\n }\n }\n}\n", "positive_code": [{"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n val testCount = nextInt\n for (_ <- 1 to testCount) {\n var n = nextLong\n var k = 1L\n var y = 3L\n while (n % y != 0) {\n k += 1\n y += 1 << k\n }\n out.println(n / y)\n }\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "d04cbe78b836e53b51292401c8c969b2"} {"source_code": "\nimport java.util.Scanner\n\n/**\n * Created by lurker on 2014. 7. 16..\n */\nobject A extends App {\n def process(p:Long, values:Seq[Long] ):Integer = {\n val mark = collection.mutable.Set[Long]()\n var i = 0\n for(v <- values) {\n i += 1\n val h = v % p\n\n if(mark.contains(h)) {\n return i\n }\n mark += h\n }\n -1\n }\n\n val sc = new Scanner(System.in)\n val p = sc.nextLong()\n val n = sc.nextInt()\n val values = for(i <- (1 to n)) yield {sc.nextLong()}\n //println(process(10, Seq(0,21,53,41,53)))\n println(process(p, values.toSeq))\n}\n", "positive_code": [{"source_code": "\nimport java.io.File\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 13.07.14.\n */\nobject A extends App {\n val home = true\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val p = nextInt\n val n = nextInt\n val xs = new Array[Boolean](p)\n var printed = false\n for (i <- 0 until n if !printed) {\n //out.println(xs.toList)\n val x = nextInt\n if (xs(x % p)) {\n out.println(i + 1)\n printed = true\n } else {\n xs(x % p) = true\n }\n }\n if (!printed) {\n out.println(-1)\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _447A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val p = next.toInt\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt % p)\n val hash = Array.fill(p)(false)\n\n def doit(i: Int): Int = {\n if (i == n) -1\n else if (hash(a(i))) return i + 1\n else {\n hash(a(i)) = true\n doit(i + 1)\n }\n }\n\n println(doit(0))\n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val Array(p, n) = in.next().split(\" \").map(_.toInt)\n val data = Range(0, n).map{ _ => in.next().toInt}\n var set = Set.empty[Int]\n println(data.zipWithIndex.find{\n case(el, index) => val res = set.contains(el % p)\n set += (el % p)\n res\n }.map(_._2 + 1).getOrElse(-1))\n}"}, {"source_code": "object A447 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(p, n) = readInts(2)\n val arr = Array.fill(p)(false)\n for(i <- 1 to n) {\n val Array(xi) = readInts(1)\n if(arr(xi%p)) {\n println(i)\n return\n } else {\n arr(xi%p) = true\n }\n }\n println(\"-1\")\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": " object Hash extends App{\n \t\n \tdef resolve(): Unit = {\n\t\tdef hash(x: Int, p: Int) = x % p\n\t\tvar map = Map[Int, Int]()\n \t\n\t\tval lines = io.Source.stdin.getLines.toIndexedSeq\n\t\tval (p, n) = {\n\t\t\tval tokens = lines(0).split(\" \")\n\t\t\t(tokens(0).toInt, tokens(1).toInt)\n\t\t}\n \t\n\t\tvar index = 1\n\t\tfor {e <- lines.tail} {\n\t\t\tval bucket = hash(e.toInt, p)\n\t\t\tif (map.get(bucket).isDefined) {\n\t\t\t\tprint(index)\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tmap = map + (bucket -> e.toInt)\n\t\t\t\tindex += 1\n\t\t\t}\n\t\t}\n\t\tprint(-1)\n \t}\n\t\n\tresolve()\n }"}], "negative_code": [], "src_uid": "5d5dfa4f129bda46055fb636ef33515f"} {"source_code": "object _1144C extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val nums = io.read[Seq[Int]]\n\n val freqCount = nums.groupBy(identity).mapValues(_.size)\n\n val ans = if(freqCount.forall(_._2 <= 2)) {\n val increasing, decreasing = mutable.ArrayBuffer.empty[Int]\n freqCount foreach {\n case (i, 1) => decreasing += i\n case (i, _) =>\n increasing += i\n decreasing += i\n }\n\n Seq(\n \"YES\",\n increasing.length,\n increasing.sorted.mkString(\" \"),\n decreasing.length,\n decreasing.sorted(desc[Int]).mkString(\" \")\n ).mkString(\"\\n\")\n } else {\n \"NO\"\n }\n\n io.write(ans)\n }\n\n def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object C1114MixedSeq extends App {\n import scala.io.StdIn.{readLine, readInt}\n val n = readInt\n val arr1 = readLine.split(' ').map(_.toInt).groupBy(identity).mapValues(_.length)\n val arr2 = arr1.filter(_._2 == 2)\n val s1 = arr1.keys.toList.sorted\n val s2 = arr2.keys.toList.sorted.reverse\n if(s1.length + s2.length != n) {\n println(\"NO\")\n } else {\n println(\"YES\")\n println(s1.length)\n println(s1.mkString(\" \"))\n println(s2.length)\n println(s2.mkString(\" \"))\n }\n\n}\n"}], "negative_code": [], "src_uid": "cdb19d87ad3713dac104252737153411"} {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _707B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val n, m, k = read[Int]\n val roads = read[Seq, (Int, Int, Int)](m)\n val isStorage = read[Set, Int](k)\n val ans = roads collect {\n case (u, v, cost) if isStorage(u) ^ isStorage(v) => cost\n }\n write(ans.whenNonEmpty(_.min) getOrElse -1)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "\nimport scala.collection.mutable._\n\nobject Bakery {\n case class Pair(v:Int,w:Int)\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n val arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n val k=arr(2)\n\n val graph=Array.fill[ArrayBuffer[Pair]](n)(new ArrayBuffer[Pair]())\n\n for(i<- 0 until m){\n val edge=in.readLine().split(\" \").map(_.toInt)\n graph(edge(0)-1)+=Pair(edge(1)-1,edge(2))\n graph(edge(1)-1)+=Pair(edge(0)-1,edge(2))\n }\n var stgVertexHs:HashSet[Int]=HashSet[Int]()\n if(k>0) {\n in.readLine().split(\" \").map(_.toInt - 1).foreach(stgVertexHs+=_)\n }\n else {\n println(\"-1\")\n return\n }\n var minDis=Int.MaxValue\n for(stgLoc<- stgVertexHs){\n val i=stgLoc\n for(j<- 0 until graph(i).length) {\n val edge=graph(i)(j)\n if(!stgVertexHs.contains(edge.v))\n minDis = math.min(edge.w, minDis)\n }\n }\n println(if(minDis==Int.MaxValue) \"-1\" else minDis)\n }\n}\n"}, {"source_code": "import scala.collection.mutable._\n\nobject Bakery {\n case class Pair(v:Int,w:Int)\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n val arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n val k=arr(2)\n\n val graph=Array.fill[ArrayBuffer[Pair]](n)(new ArrayBuffer[Pair]())\n\n for(i<- 0 until m){\n val edge=in.readLine().split(\" \").map(_.toInt)\n graph(edge(0)-1)+=Pair(edge(1)-1,edge(2))\n graph(edge(1)-1)+=Pair(edge(0)-1,edge(2))\n }\n var stgVertex:Array[Int]=null\n var stgVertexHs:HashSet[Int]=HashSet[Int]()\n if(k>0) {\n stgVertex =in.readLine().split(\" \").map(_.toInt - 1)\n stgVertex.foreach(stgVertexHs+=_)\n }\n else {\n println(\"-1\")\n return\n }\n\n\n var minDis=Int.MaxValue\n for(k<- 0 until stgVertex.length){\n val i=stgVertex(k)\n for(j<- 0 until graph(i).length) {\n val edge=graph(i)(j)\n if(!stgVertexHs.contains(edge.v))\n minDis = math.min(edge.w, minDis)\n }\n }\n println(if(minDis==Int.MaxValue) \"-1\" else minDis)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m, k) = in.next().split(' ').map(_.toInt)\n val lines = in.take(m).map(_.split(' ').map(_.toInt)).toList\n if (k == 0)\n println(-1)\n else {\n val warehouses = in.next().split(' ').map(_.toInt).toSet\n val lengths = lines.filter{case(Array(u, v, l)) => List(u, v).count(warehouses) == 1}.map(_.last)\n if (lengths.isEmpty)\n println(-1)\n else\n println(lengths.min)\n }\n}\n"}, {"source_code": "object B707 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m, k) = readInts(3)\n val _G = Array.fill(n)(collection.mutable.ArrayBuffer.empty[(Int, Long)])\n for(_ <- 0 until m) {\n val Array(u, v, d) = readInts(3)\n _G(u-1) += ((v-1, d.toLong))\n _G(v-1) += ((u-1, d.toLong))\n }\n val G = _G.map(_.sortBy(_._2).toArray)\n if(k > 0) {\n val ks = readInts(k).toSet\n var min = Long.MaxValue\n for(i <- ks) {\n for(j <- G(i-1) if !ks.contains(j._1+1)) {\n min = math.min(min, j._2)\n }\n }\n if(min == Long.MaxValue) {\n println(\"-1\")\n } else {\n println(min)\n }\n } else {\n println(\"-1\")\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _707B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val n, m, k = read[Int]\n val roads = read[Seq, (Int, Int, Int)](m)\n val isStorage = read[Set, Int](k)\n\n var ans = Int.MaxValue\n\n roads foreach {\n case (u, v, cost) =>\n if(isStorage(u) ^ isStorage(v)) {\n ans = ans min cost\n }\n }\n\n write(if (ans == Int.MaxValue) -1 else ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.PriorityQueue\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n val m = sc.nextInt()\n val k = sc.nextInt()\n\n val road = Array.fill(n+1)(new PriorityQueue[(Int,Int)])\n for(i <- 1 to m){\n val u = sc.nextInt()\n val v = sc.nextInt()\n val l = sc.nextInt()\n\n road(u) += ((-l, v))\n road(v) += ((-l, u))\n }\n\n if(k == 0)\n println(-1)\n else{\n var ans = 1e9.toInt + 1\n val a = new Array[Int](k)\n val dp = new Array[Boolean](n+1)\n\n for(i <- 0 until k){\n val tmp = sc.nextInt()\n a(i) = tmp\n dp(tmp) = true\n }\n\n for(e <- a){\n var flag = true\n while(!road(e).isEmpty && flag){\n val tmp = road(e).dequeue\n val nowp = (-tmp._1, tmp._2)\n if(!dp(nowp._2)){\n ans = Math.min(ans, nowp._1)\n flag = false\n }\n }\n }\n\n if(ans == 1e9.toInt + 1)\n println(-1)\n else\n println(ans)\n }\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject _368B extends App {\n\n case class Edge(target: Int, cost: Int)\n\n val Array(n, m, k) = readLine().split(\" \").map(_.toInt)\n val G = Array.ofDim[mutable.Set[Edge]](n + 1)\n for (i <- 1 to n) G(i) = new mutable.HashSet[Edge]\n\n 1 to m foreach { _ =>\n val Array(u, v, cost) = readLine().split(\" \").map(_.toInt)\n val U = G(u)\n val V = G(v)\n U += Edge(v, cost)\n V += Edge(u, cost)\n }\n\n if (k == 0) {\n println(-1)\n } else {\n val K = readLine().split(\" \").map(_.toInt)\n val IsStorage = Array.ofDim[Boolean](n + 1)\n K.foreach { k =>\n IsStorage(k) = true\n }\n\n var min = Int.MaxValue\n K.foreach { k =>\n for (e <- G(k)) {\n val y = e.target\n if (!IsStorage(y)) {\n min = Math.min(min, e.cost)\n }\n }\n }\n\n println(if (min == Int.MaxValue) -1 else min)\n }\n}\n"}, {"source_code": "\n\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject B_368 { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n //runTest(Test.sa4)\n// debugV = true\n// file = File(\"C:\\\\temp\\\\google cj\\\\2014q\\\\c-small.res\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading\n val line = readLine\n val nCities = line.int\n val mRoads = line.int\n val kStorages = line.int\n \n val roadMap = scala.collection.mutable.Map[Int, List[Road]]()\n val city = new Array[Boolean](nCities)\n \n for (i <- 0 until mRoads) {\n val rLine = readLine()\n val city1 = rLine.int\n val city2 = rLine.int\n val length = rLine.long\n val road1 = new Road(city1, city2, length)\n val nList1 = roadMap.getOrElse(city1, List())\n roadMap.put(city1, road1 :: nList1)\n val nList2 = roadMap.getOrElse(city2, List())\n val road2 = new Road(city2, city1, length)\n roadMap.put(city2, road2 :: nList2)\n }\n \n var res = -1l\n if (kStorages > 0) {\n val sLine = readLine\n val set = scala.collection.mutable.Set[Int]()\n for (i <- 0 until kStorages) {\n set.add(sLine.int)\n }\n for (stor <- set) {\n roadMap.get(stor) match {\n case Some(cityRoads) => for (road <- cityRoads) {\n if (!set.contains(road.city2) && (res == -1 || road.length < res)) {\n res = road.length\n }\n }\n case _ =>\n }\n }\n } \n \n \n //---------------------------- parameters reading :end \n \n outLn(res+\"\")\n finish\n }\n \n// class City(num:Int) {\n// var adj = List[\n// }\n \n class Road(val city1: Int, val city2: Int, val length: Long)\n\n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \n //in all\nval sa1 = \"\"\"\n5 7 5\n1 2 3\n2 4 3\n3 4 2\n3 5 1\n3 1 10\n5 2 1\n2 3 1\n1 2 3 4 5\n\"\"\"\n\n//no storage\nval sa2 = \"\"\" \n5 7 0\n1 2 3\n2 4 3\n3 4 2\n3 5 1\n3 1 10\n5 2 1\n2 3 1\n\"\"\"\n\nval sa3 = \"\"\"\n5 7 3\n1 2 3\n2 4 3\n3 4 2\n3 5 1\n3 1 10\n5 2 1\n2 3 1\n2 3 5\n\"\"\"\n\nval sa4 = \"\"\"\n2 1 1\n1 2 100\n2\n\"\"\"\n}\n\n}\n\n"}, {"source_code": "object Bakery707B extends App {\n import java.io._\n import java.util.StringTokenizer\n solve(System.in,System.out)\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val n = in.nextInt()\n val m = in.nextInt()\n val k = in.nextInt()\n val nodes = (0 until n).map(i => Node(i)).toArray\n val edges = (1 to m).map{_ =>\n val a = nodes(in.nextInt()-1)\n val b = nodes(in.nextInt()-1)\n val cost = in.nextInt()\n Edge(a,b,cost)\n }\n\n (1 to k).foreach(_ => nodes(in.nextInt()-1).withStorage())\n\n val validCost = edges.flatMap{\n case Edge(a,b,cost) if a.hasStorage && !b.hasStorage => Some(cost)\n case Edge(a,b,cost) if !a.hasStorage && b.hasStorage => Some(cost)\n case _ => None\n }\n if(validCost.isEmpty){\n out.println(-1)\n }else{\n out.println(validCost.min)\n }\n\n }\n case class Edge(a: Node, b: Node,cost: Int)\n case class Node(id: Int){\n var hasStorage: Boolean = false\n def withStorage(): Unit = hasStorage = true\n }\n\n\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = return next().toInt\n }\n}"}, {"source_code": "object Bakery707B extends App {\n import java.io._\n import java.util.StringTokenizer\n solve(System.in,System.out)\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val n = in.nextInt()\n val m = in.nextInt()\n val k = in.nextInt()\n val nodes = (0 until n).map(i => Node(i)).toArray\n val edgesRaw: Seq[(Int,Int,Int)] = (1 to m).map{_ => (in.nextInt()-1,in.nextInt()-1,in.nextInt())}\n\n (1 to k).foreach(_ => {\n val node = nodes(in.nextInt()-1)\n nodes.update(node.id,node.copy(hasStorage = true))\n })\n\n val validCost = edgesRaw.map{\n case (a,b,c) => Edge(nodes(a),nodes(b),c)\n }.flatMap{\n case Edge(Node(_,true),Node(_,false),cost) => Some(cost)\n case Edge(Node(_,false),Node(_,true),cost) => Some(cost)\n case _ => None\n }\n if(validCost.isEmpty){\n out.println(-1)\n }else{\n out.println(validCost.min)\n }\n\n }\n case class Edge(a: Node, b: Node,cost: Int)\n case class Node(id: Int, hasStorage: Boolean = false)\n\n\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = return next().toInt\n }\n}"}, {"source_code": "import scala.collection.mutable.MutableList \nimport scala.io.StdIn\n\nobject B {\n case class Edge (\n neighbor: Int,\n weight: Int\n )\n \n def main(args: Array[String]): Unit = {\n /* Ugly, inherently mutable, procedural code, because we're reading standard input. */\n var bestWeight = Int.MaxValue // for iterative reassignment at a later date...\n var flourCities = Set[Int]()\n val Array(n: Int, m: Int, k: Int) = StdIn.readLine.split(\" \").map(_.toInt)\n val adjLists = Array.fill(n + 1){new MutableList[Edge]}\n 1 to m foreach { _ =>\n val Array(u: Int, v: Int, l: Int) = StdIn.readLine.split(\" \").map(_.toInt) \n adjLists(u) += Edge(neighbor = v, weight = l)\n adjLists(v) += Edge(neighbor = u, weight = l)\n }\n if (k > 0) {\n StdIn.readLine.split(\" \").map(_.toInt).foreach { flourCities += _ }\n }\n flourCities.foreach { city => \n adjLists(city).foreach { edge =>\n if (!flourCities.contains(edge.neighbor)) {\n bestWeight = math.min(bestWeight, edge.weight)\n }\n }\n }\n bestWeight = if (bestWeight == Int.MaxValue) -1 else bestWeight\n System.out.println(bestWeight)\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable.MutableList \nimport scala.io.StdIn\n\nobject B {\n def main(args: Array[String]): Unit = {\n /* Ugly, inherently mutable, procedural code, because we're reading standard input. */\n var bestWeight = Int.MaxValue // for iterative reassignment at a later date...\n var flourCities = Set[Int]()\n val Array(n: Int, m: Int, k: Int) = StdIn.readLine.split(\" \").map(_.toInt)\n val adjMat: Array[Array[Option[Int]]] =\n Array.fill(n + 1) {\n Array.fill(n + 1) {\n None\n }\n }\n 1 to m foreach { _ =>\n val Array(u: Int, v: Int, l: Int) = StdIn.readLine.split(\" \").map(_.toInt) \n adjMat(u)(v) = Some(l)\n adjMat(v)(u) = Some(l)\n }\n if (k > 0) {\n StdIn.readLine.split(\" \").map(_.toInt).foreach { flourCities += _ }\n }\n flourCities.foreach { city => \n 1 to n foreach { adjCity =>\n if (!flourCities.contains(adjCity)) {\n val edgeWeight = adjMat(city)(adjCity)\n edgeWeight match {\n case Some(candidateWeight) => bestWeight = math.min(bestWeight, candidateWeight)\n case None => \n }\n }\n }\n }\n bestWeight = if (bestWeight == Int.MaxValue) -1 else bestWeight\n System.out.println(bestWeight)\n }\n}\n"}, {"source_code": "import scala.collection.mutable._\n\nobject Bakery {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n val arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n val k=arr(2)\n\n val graph=Array.fill[Int](n,n)(Int.MaxValue)\n\n for(i<- 0 until m){\n val edge=in.readLine().split(\" \").map(_.toInt)\n graph(edge(0)-1)(edge(1)-1)=math.min(graph(edge(0)-1)(edge(1)-1),edge(2))\n }\n var stgVertex:Array[Int]=null\n if(k>0) {\n stgVertex =in.readLine().split(\" \").map(_.toInt - 1)\n }\n else {\n println(\"-1\")\n return\n }\n var minDis=Int.MaxValue\n for(i<- 0 until stgVertex.length){\n if(i!=0){\n minDis=math.min(graph(i)(i-1),minDis)\n }\n if(i!=stgVertex.length-1){\n minDis=math.min(graph(i)(i+1),minDis)\n }\n }\n\n println(if(minDis==Int.MaxValue) \"-1\" else minDis)\n }\n}\n"}, {"source_code": "object Bakery {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n val arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n val k=arr(2)\n\n val graph=Array.fill[Int](n,n)(Int.MaxValue)\n\n for(i<- 0 until m){\n val edge=in.readLine().split(\" \").map(_.toInt)\n graph(edge(0)-1)(edge(1)-1)=math.min(graph(edge(0)-1)(edge(1)-1),edge(2))\n graph(edge(1)-1)(edge(0)-1)=math.min(graph(edge(1)-1)(edge(0)-1),edge(2))\n }\n var stgVertex:Array[Int]=null\n if(k>0) {\n stgVertex =in.readLine().split(\" \").map(_.toInt - 1)\n }\n else {\n println(\"-1\")\n return\n }\n var minDis=Int.MaxValue\n for(j<- 0 until stgVertex.length){\n val i=stgVertex(j)\n if(i!=0 && graph(i)(i-1)!=Int.MaxValue){\n minDis=math.min(graph(i)(i-1),minDis)\n }\n if(i!=graph.length-1 && graph(i)(i+1)!=Int.MaxValue){\n minDis=math.min(graph(i)(i+1),minDis)\n }\n }\n\n println(if(minDis==Int.MaxValue) \"-1\" else minDis)\n }\n}"}, {"source_code": "\nobject Bakery {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n val arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n val k=arr(2)\n\n val graph=Array.fill[Int](n,n)(Int.MaxValue)\n\n for(i<- 0 until m){\n val edge=in.readLine().split(\" \").map(_.toInt)\n graph(edge(0)-1)(edge(1)-1)=math.min(graph(edge(0)-1)(edge(1)-1),edge(2))\n }\n var stgVertex:Array[Int]=null\n if(k>0) {\n stgVertex =in.readLine().split(\" \").map(_.toInt - 1)\n }\n else {\n println(\"-1\")\n return\n }\n var minDis=Int.MaxValue\n for(j<- 0 until stgVertex.length){\n val i=stgVertex(j)\n if(i!=0 && graph(i)(i-1)!=Int.MaxValue){\n minDis=math.min(graph(i)(i-1),minDis)\n }\n if(i!=graph.length-1 && graph(i)(i+1)!=Int.MaxValue){\n minDis=math.min(graph(i)(i+1),minDis)\n }\n }\n\n println(if(minDis==Int.MaxValue) \"-1\" else minDis)\n }\n}\n"}, {"source_code": "import scala.collection.mutable._\n\nobject Bakery {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n val arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n val k=arr(2)\n\n val graph=Array.fill[Int](n,n)(Int.MaxValue)\n for(i<- 0 until n){\n graph(i)(i)=0\n }\n for(i<- 0 until m){\n val edge=in.readLine().split(\" \").map(_.toInt)\n graph(edge(0)-1)(edge(1)-1)=edge(2)\n }\n var stgVertex:HashSet[Int]=HashSet[Int]()\n if(m>0)\n in.readLine().split(\" \").map(_.toInt-1).foreach(stgVertex+=_)\n else {\n println(\"-1\")\n return\n }\n var minDis=Int.MaxValue\n for (k <- 0 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n if (graph(i)(k) != Int.MaxValue && graph(k)(j) != Int.MaxValue)\n graph(i)(j) = math.min(graph(i)(j), graph(i)(k) + graph(k)(j))\n if((stgVertex.contains(i) || stgVertex.contains(j)) && (!stgVertex.contains(i) || !stgVertex.contains(j))){\n minDis=math.min(minDis,graph(i)(j))\n }\n }\n }\n }\n println(if(minDis==Int.MaxValue) \"-1\" else minDis)\n }\n}\n"}, {"source_code": "object Bakery {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n val arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n val k=arr(2)\n\n val graph=Array.fill[Int](n,n)(Int.MaxValue)\n\n for(i<- 0 until m){\n val edge=in.readLine().split(\" \").map(_.toInt)\n graph(edge(0)-1)(edge(1)-1)=math.min(graph(edge(0)-1)(edge(1)-1),edge(2))\n graph(edge(1)-1)(edge(0)-1)=math.min(graph(edge(1)-1)(edge(0)-1),edge(2))\n }\n var stgVertex:Array[Int]=null\n if(k>0) {\n stgVertex =in.readLine().split(\" \").map(_.toInt - 1)\n }\n else {\n println(\"-1\")\n return\n }\n var minDis=Int.MaxValue\n for(k<- 0 until stgVertex.length){\n val i=stgVertex(k)\n for(j<- 0 until graph(0).length) {\n minDis = math.min(graph(i)(j), minDis)\n }\n }\n println(if(minDis==Int.MaxValue) \"-1\" else minDis)\n }\n}\n"}, {"source_code": "object Bakery {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n val arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n val k=arr(2)\n\n val graph=Array.fill[Int](n,n)(Int.MaxValue)\n\n for(i<- 0 until m){\n val edge=in.readLine().split(\" \").map(_.toInt)\n graph(edge(0)-1)(edge(1)-1)=math.min(graph(edge(0)-1)(edge(1)-1),edge(2))\n }\n var stgVertex:Array[Int]=null\n if(k>0) {\n stgVertex =in.readLine().split(\" \").map(_.toInt - 1)\n }\n else {\n println(\"-1\")\n return\n }\n var minDis=Int.MaxValue\n for(i<- 0 until stgVertex.length){\n if(i!=0){\n minDis=math.min(graph(i)(i-1),minDis)\n }\n if(i!=graph.length-1){\n minDis=math.min(graph(i)(i+1),minDis)\n }\n }\n\n println(if(minDis==Int.MaxValue) \"-1\" else minDis)\n }\n}\n"}, {"source_code": "\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject B_368 { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.sa2)\n// debugV = true\n// file = File(\"C:\\\\temp\\\\google cj\\\\2014q\\\\c-small.res\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading\n val line = readLine\n val nCities = line.int\n val mRoads = line.int\n val kStorages = line.int\n \n val roadMap = scala.collection.mutable.Map[Int, List[Road]]()\n val city = new Array[Boolean](nCities)\n \n for (i <- 0 until mRoads) {\n val rLine = readLine()\n val city1 = rLine.int\n val city2 = rLine.int\n val road = new Road(city1, city2, rLine.long)\n val nList1 = roadMap.getOrElse(city1, List())\n roadMap.put(city1, road :: nList1)\n val nList2 = roadMap.getOrElse(city2, List())\n roadMap.put(city2, road :: nList2)\n }\n \n var res = -1l\n if (kStorages > 0) {\n val sLine = readLine\n val set = scala.collection.mutable.Set[Int]()\n for (i <- 0 until kStorages) {\n set.add(sLine.int)\n }\n for (stor <- set) {\n roadMap.get(stor) match {\n case Some(cityRoads) => for (road <- cityRoads) {\n if (!set.contains(road.city2) && (res == -1 || road.length < res)) {\n res = road.length\n }\n }\n case _ =>\n }\n }\n } \n \n \n //---------------------------- parameters reading :end \n \n outLn(res+\"\")\n finish\n }\n \n// class City(num:Int) {\n// var adj = List[\n// }\n \n class Road(val city1: Int, val city2: Int, val length: Long)\n\n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n\"\"\"\n\nval sa2 = \"\"\"\n\"\"\"\n\nval sa3 = \"\"\"\n\"\"\"\n}\n\n}\n\n"}], "src_uid": "b0e6a9b500b3b75219309b5e6295e105"} {"source_code": "object ProblemF extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n\n for (_ <- 1 to t) {\n val a = in.nextInt()\n val b = in.nextInt()\n val c: Int = in.nextInt()\n val d = in.nextInt()\n\n val res = if (b >= a){\n b\n } else if (c - d > 0) {\n val left = math.max(0, a - b).toLong\n val count = left / (c - d) + (if (left % (c - d) > 0) 1 else 0)\n count * c + b\n } else {\n -1\n }\n\n println(res)\n }\n\n}", "positive_code": [{"source_code": "\n\nobject CodeforcesRoundE87a {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n var Array(a, b, c, d) = rll_int\n var inBed = b\n val res =\n if (inBed >= a) {\n inBed\n } else {\n if (c <= d) {\n -1\n } else {\n val n = Math.ceil((a.toDouble - inBed) / (c - d)).toLong\n inBed + n * c\n }\n }\n writer.println(res)\n }\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CE87A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CE87A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t= ni()\n REP(t) { _ =>\n val a = ni()\n val b = ni()\n val c = ni()\n val d = ni()\n\n if(b >= a) {\n out.println(b)\n } else if (d >= c) {\n out.println(-1)\n } else {\n val left = a - b\n val x = b.toLong\n val sleepx = c - d\n val m = Math.ceil(left / sleepx.toDouble).toLong\n out.println(x + m * c)\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "1ab174688ba76168ca047ed2b06b0670"} {"source_code": "object test5 extends App {\n\tval Array(n,k)=readLine.split(\" \").map(_.toInt)\n\tval arr=readLine.toCharArray()\n\tvar count=0\n\tval ans=k match{\n\t\tcase 2=>countTwo\n\t\tcase _=>countThree\n\t}\n\t\n\tprintln(count)\n\tprintln(ans)\n\n\tdef countTwo={\n\t val str1=\"AB\"*(n/2)+\"A\"*(n%2)\n\t val str2=\"BA\"*(n/2)+\"B\"*(n%2)\n\t \n\t var count1=0\n\t var count2=0\n\t \n\t for(i<-0 until n)\n\t \tif(arr(i)!=str1(i)) count1+=1 else count2+=1\n\t \t\n\t count=math.min(count1,count2)\n\t if(count1c!=arr(i-1) && (i==n-1 || c!=arr(i+1)))\n \t\tarr(i)=c.get\n\t }\n\t arr.mkString\n\t}\n \n} \n\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _219C extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val k = next.toInt\n val s = \" \" + next\n val f = Array.fill(n + 1, k)(0)\n var min = 0\n var minmin = 1\n for (i <- 1 to n) {\n for (j <- 0 until k) {\n val delta = if (j == s(i) - 'A') 0 else 1\n if (j != min) f(i)(j) = f(i - 1)(min) + delta\n else f(i)(j) = f(i - 1)(minmin) + delta\n }\n min = if (f(i)(0) < f(i)(1)) 0 else 1\n minmin = 1 - min\n for (j <- 2 until k)\n if (f(i)(j) < f(i)(min)) {\n minmin = min\n min = j\n } else if (f(i)(j) < f(i)(minmin)) minmin = j\n }\n var ii = n\n var jj = 0\n for (j <- 0 until k)\n if (f(n)(j) < f(n)(jj)) jj = j\n\n println(f(ii)(jj))\n val builder = new StringBuilder\n while (ii > 0) {\n builder += ('A' + jj).toChar\n val delta = if (s(ii) - 'A' == jj) 0 else 1\n var newJJ = 0\n for (j <- 0 until k)\n if (j != jj && f(ii - 1)(j) + delta == f(ii)(jj)) newJJ = j\n jj = newJJ\n ii = ii - 1\n }\n println(builder.result.reverse)\n// f.foreach(i => println(i.toList))\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Program {\n\tdef main(args:Array[String]) = {\n\t\tval in = new Scanner(System.in)\n\t\tval (n, k) = (in.nextInt(), in.nextInt())\n\t\tval cols = (in.next()).toCharArray\n\n\t\tif(k == 2){\n\t\t\tvar ans = Int.MaxValue\n\t\t\tvar sol = Array[Char]()\n\t\t\tfor(t <- Array(\"AB\", \"BA\")){\n\t\t\t\tvar p = 0\n\t\t\t\tvar s = new Array[Char](n)\n\t\t\t\tfor(i <- 0 until cols.length){\n\t\t\t\t\ts(i) = t(i&1)\n\t\t\t\t\tif(cols(i)!=t(i&1))p+=1\n\t\t\t\t}\n\t\t\t\tif(p < ans) {\n\t\t\t\t\tans = p\n\t\t\t\t\tsol = s\n\t\t\t\t}\n\t\t\t}\n\t\t\tprintln(ans)\n\t\t\tfor(c <- sol)print(c)\n\t\t\tprintln()\n\t\t} else {\n\t\t\tvar ans = 0\n\n\t\t\tfor(i <- 1 to n - 1){\n\t\t\t\tif(cols(i) == cols(i-1)){\n\t\t\t\t\tans += 1\n\t\t\t\t\tvar c =0\n\t\t\t\t\tif((i + 1 < n && cols(i+1) == 'A') || cols(i-1) == 'A') c += 1\n\t\t\t\t\tif((i + 1 < n && cols(i+1) == (c+'A')) || cols(i-1) == (c+'A')) c += 1\n\t\t\t\t\tcols(i)=(c+'A').toChar\n\t\t\t\t}\n\t\t\t}\n\t\t\tprintln(ans)\n\t\t\tfor(c <- cols) print(c)\n\t\t\tprintln()\n\t\t}\n\t}\n}"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _219C extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val k = next.toInt\n val s = \" \" + next\n val f = Array.fill(n + 1, k)(0)\n var min = 0\n var minmin = 1\n for (i <- 1 to n) {\n for (j <- 0 until k) {\n val delta = if (j == s(i) - 'A') 0 else 1\n if (j != min) f(i)(j) = f(i - 1)(min) + delta\n else f(i)(j) = f(i - 1)(minmin) + delta\n }\n min = 0\n minmin = 1\n for (j <- 2 until k)\n if (f(i)(j) < f(i)(min)) {\n minmin = min\n min = j\n } else if (f(i)(j) < f(i)(minmin)) minmin = j\n }\n var ii = n\n var jj = 0\n for (j <- 0 until k)\n if (f(n)(j) < f(n)(jj)) jj = j\n\n println(f(ii)(jj))\n val builder = new StringBuilder\n while (ii > 0) {\n builder += ('A' + jj).toChar\n val delta = if (s(ii) - 'A' == jj) 0 else 1\n var newJJ = 0\n for (j <- 0 until k)\n if (j != jj && f(ii - 1)(j) + delta == f(ii)(jj)) newJJ = j\n jj = newJJ\n ii = ii - 1\n }\n println(builder.result.reverse)\n // f.foreach(i => println(i.toList))\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Program {\n\tdef main(args:Array[String]) = {\n\t\tval in = new Scanner(System.in)\n\t\tval (n, k) = (in.nextInt(), in.nextInt())\n\t\tval cols = in.next()\n\t\tvar moves = Array.ofDim[Int](26, n + 1)\n\t\tvar sol = Array.ofDim[Int](26, n + 1)\n\t\tfor(c <- 'A' to 'Z') moves(c - 'A')(n) = 0\n\t\tfor(i <- n - 1 to 0 by -1; c <- 0 until k){\n\t\t\tif (c != (cols(i)-'A').toInt) {\n\t\t\t\tmoves(c)(i) = moves(cols(i)-'A')(i + 1)\n\t\t\t\tsol(c)(i) = cols(i)-'A'\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvar ans = Int.MaxValue\n\t\t\t\tfor(c2 <- 0 until k){\n\t\t\t\t\tif (c2 != c && ans > moves(c2)(i + 1) + 1){\n\t\t\t\t\t\tans = moves(c2)(i+1)+1\n\t\t\t\t\t\tsol(c)(i) = c2\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmoves(c)(i) = ans\n\t\t\t}\n\t\t}\n\t\tvar c = if (cols(0) == 'A') 1 else 0\n\t\tprintln(moves(c)(0))\n\t\tfor(i <- 0 until n){\n\t\t\tprint((sol(c)(i)+'A').toChar)\n\t\t\tc = sol(c)(i)\n\t\t}\n\t\tprintln()\n\t}\n}"}, {"source_code": "import java.util.Scanner\n\nobject Program {\n\tdef main(args:Array[String]) = {\n\t\tval in = new Scanner(System.in)\n\t\tval (n, k) = (in.nextInt(), in.nextInt())\n\t\tval cols = in.next().toCharArray\n\t\tif(k == 2){\n\t\t\tvar ans = Int.MaxValue\n\t\t\tvar sol = \"\"\n\t\t\tfor(t <- Array(\"AB\", \"BA\")){\n\t\t\t\tvar p = 0\n\t\t\t\tvar s = \"\"\n\t\t\t\tfor(i <- 0 until cols.length){\n\t\t\t\t\ts += t(i&1)\n\t\t\t\t\tif(cols(i)!=t(i&1))p+=1\n\t\t\t\t}\n\t\t\t\tif(p < ans) ans = p; sol = s\n\t\t\t}\n\t\t\tprintln(ans)\n\t\t\tprintln(sol)\n\t\t} else {\n\t\t\tvar ans = 0\n\t\t\tfor(i <- 0 until n - 1){\n\t\t\t\tif(cols(i) == cols(i+1)){\n\t\t\t\t\tans += 1\n\t\t\t\t\tfor(c <- 0 until k)\n\t\t\t\t\t\tif(cols(i+1) != c+'A'){\n\t\t\t\t\t\t\tif(i > 0)if(cols(i-1) != c+'A'){\n\t\t\t\t\t\t\t\tcols(i) = (c+'A').toChar\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tprintln(ans)\n\t\t\tvar s = \"\"\n\t\t\tfor(c <- cols) s += c\n\t\t\tprintln(s)\n\t\t}\n\t}\n}"}, {"source_code": "import java.util.Scanner\n\nobject Program {\n\tdef main(args:Array[String]) = {\n\t\tval in = new Scanner(System.in)\n\t\tval (n, k) = (in.nextInt(), in.nextInt())\n\t\tval cols = in.next().toCharArray\n\t\tif(k == 2){\n\t\t\tvar ans = Int.MaxValue\n\t\t\tvar sol = \"\"\n\t\t\tfor(t <- Array(\"AB\", \"BA\")){\n\t\t\t\tvar p = 0\n\t\t\t\tvar s = \"\"\n\t\t\t\tfor(i <- 0 until cols.length){\n\t\t\t\t\ts += t(i&1)\n\t\t\t\t\tif(cols(i)!=t(i&1))p+=1\n\t\t\t\t}\n\t\t\t\tif(p < ans) {\n\t\t\t\t\tans = p\n\t\t\t\t\tsol = s\n\t\t\t\t}\n\t\t\t}\n\t\t\tprintln(ans)\n\t\t\tprintln(sol)\n\t\t} else {\n\t\t\tvar ans = 0\n\t\t\tfor(i <- 0 until n - 1){\n\t\t\t\tif(cols(i) == cols(i+1)){\n\t\t\t\t\tans += 1\n\t\t\t\t\tfor(c <- 0 until k)\n\t\t\t\t\t\tif(cols(i+1) != c+'A'){\n\t\t\t\t\t\t\tif(i > 0)if(cols(i-1) != c+'A'){\n\t\t\t\t\t\t\t\tcols(i) = (c+'A').toChar\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tprintln(ans)\n\t\t\tvar s = \"\"\n\t\t\tfor(c <- cols) s += c\n\t\t\tprintln(s)\n\t\t}\n\t}\n}"}, {"source_code": "import java.util.Scanner\n\nobject Program {\n\tdef main(args:Array[String]) = {\n\t\tval in = new Scanner(System.in)\n\t\tval (n, k) = (in.nextInt(), in.nextInt())\n\t\tval cols = in.next().toCharArray\n\t\tif(k == 2){\n\t\t\tvar ans = Int.MaxValue\n\t\t\tvar sol = \"\"\n\t\t\tfor(t <- Array(\"AB\", \"BA\")){\n\t\t\t\tvar p = 0\n\t\t\t\tvar s = \"\"\n\t\t\t\tfor(i <- 0 until cols.length){\n\t\t\t\t\ts += t(i&1)\n\t\t\t\t\tif(cols(i)!=t(i&1))p+=1\n\t\t\t\t}\n\t\t\t\tif(p < ans) {\n\t\t\t\t\tans = p\n\t\t\t\t\tsol = s\n\t\t\t\t}\n\t\t\t}\n\t\t\tprintln(ans)\n\t\t\tprintln(sol)\n\t\t} else {\n\t\t\tvar ans = 0\n\t\t\tfor(i <- 1 until n - 1){\n\t\t\t\tif(cols(i) == cols(i-1)){\n\t\t\t\t\tans += 1\n\t\t\t\t\tvar c = 0\n\t\t\t\t\tif(cols(i+1) == 'A' || cols(i-1) == 'A') c += 1\n\t\t\t\t\tif(cols(i+1) == (c+'A') || cols(i-1) == (c+'A')) c += 1\n\t\t\t\t\tcols(i) = (c+'A').toChar\n\t\t\t\t}\n\t\t\t}\n\t\t\tprintln(ans)\n\t\t\tvar s = \"\"\n\t\t\tfor(c <- cols) s += c\n\t\t\tprintln(s)\n\t\t}\n\t}\n}"}, {"source_code": "object test5 extends App {\n\tval Array(n,k)=readLine.split(\" \").map(_.toInt)\n\tval arr=readLine.toCharArray()\n\tvar count=0\n\tk match{\n\t\tcase 2=>countTwo\n\t\tcase _=>countThree\n\t}\n\t\n\tprintln(count)\n\tprintln(arr.mkString)\n\n\tdef countTwo={\n\t\tfor(i<-1 until n if arr(i)==arr(i-1)){\n\t\t\tcount+=1\n \t\tval c='A' to 'Z' find(c=>c!=arr(i-1))\n arr(i)=c.get\t\n\t\t}\n\t}\n\t\n\tdef countThree={\n\t for(i<-1 until n if arr(i)==arr(i-1)){\n \t\tcount+=1\n \t\tval c='A' to 'Z' find(c=>c!=arr(i-1) && (i==n-1 || c!=arr(i+1)))\n \t\tarr(i)=c.get\n\t }\n\t}\n \n} \n\n"}], "src_uid": "0ecf60ea733eba71ef1cc1e736296d96"} {"source_code": "import scala.math._\nimport java.util.Scanner\n\nobject RentingBikes extends App {\n\tval scan = new Scanner(System.in)\n\tval n = scan.nextInt\n\tval m = scan.nextInt\n\tval a = scan.nextInt\n\t\n\tval b = {\n\t\tfor(i <- 0 until n) yield scan.nextInt\n\t}.toArray.sortWith((x, y) => x < y)\n\n\tval p = {\n\t\tfor(i <- 0 until m) yield scan.nextInt\n\t}.toArray.sortWith((x, y) => x < y)\n\n\tdef calc(x: Int): Long = {\n\t\tvar sum: Long = 0\n\t\tfor(i <- 0 until x if p(i) > b(i + b.size - x)) {\n\t\t\tsum = sum - b(i + b.size - x) + p(i)\n\t\t}\n\t\tsum\n\t}\n\n\tvar high = min(n, m) + 1\n\tvar low = 1\n\twhile (high > low) {\n\t\tval mid = (high + low) / 2\n\t\tcalc(mid) <= a match {\n\t\t\tcase true => low = mid + 1\n\t\t\tcase false => high = mid\n\t\t}\n\t}\n\t\n\tval ret = low - 1\n\tvar sum = -a\n\tfor(i <- 0 until ret) sum = sum + p(i)\n\tsum = max(sum, 0)\n\tprintln(\"%d %d\".format(ret, sum))\n\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P363D extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): List[Long] = {\n val N, M = sc.nextInt\n val A: Long = sc.nextLong\n val B: Array[Long] = Array.fill(N)(sc.nextLong).sorted\n val P: Array[Long] = Array.fill(M)(sc.nextLong).sorted\n\n def simulate(n: Int): Long = {\n\n @tailrec\n def loop(acc: Long, i: Int): Long = {\n if (i == n) acc\n else loop(acc + (0L max (P(i) - B(N - n + i))), i + 1)\n }\n\n loop(0L, 0)\n }\n\n @tailrec\n def binSearch(a: Int, b: Int): Int = {\n val m = (a + b) / 2\n if (b - a <= 1) a\n else if (simulate(m) > A) binSearch(a, m)\n else binSearch(m, b)\n }\n\n val nm = N min M\n val r = if (simulate(nm) <= A) nm\n else binSearch(0, nm)\n if (r == 0) List(0, 0)\n else List(r, (P.take(r).sum - A) max 0)\n }\n\n out.println(solve.mkString(\" \"))\n out.close\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P363D extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): List[Int] = {\n val N, M = sc.nextInt\n val A: Int = sc.nextInt\n val B: List[Int] = List.fill(N)(sc.nextInt).sortWith(_ > _)\n val P: List[Int] = List.fill(M)(sc.nextInt).sortWith(_ < _)\n\n def simulate(n: Int): Int = {\n (P.take(n), B.take(n)).zipped.map { (a: Int , b: Int) =>\n (a - b) max 0\n }.sum\n }\n\n @tailrec\n def binSearch(a: Int, b: Int): Int = {\n val c = (a + b) / 2\n val r= simulate(c)\n if (b == c) a\n else if (A <= r) binSearch(a, c)\n else binSearch(c + 1, b)\n }\n\n val r = binSearch(0, N)\n val s = (P.take(r).sum - A) max 0\n List(r, s)\n }\n\n out.println(solve.mkString(\" \"))\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P363B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n // N planks\n // H_i ... hight of the ith plank\n // K consecutive planks to be removed\n\n \n def solve(): Long = {\n val N, K = sc.nextInt\n val dp: Array[Long] = Array.fill(N + 1)(0)\n\n 1 to N foreach { i =>\n dp(i) = dp(i - 1) + sc.nextLong\n }\n\n var min: Long = Long.MaxValue\n var j: Int = 0\n 1 to (N - K + 1) foreach { i =>\n val kSum = dp(i + K - 1) - dp(i - 1)\n if (kSum < min) {\n min = kSum\n j = i\n }\n }\n j\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P363D extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): List[Int] = {\n val N, M = sc.nextInt\n val A: Int = sc.nextInt\n val B: List[Int] = List.fill(N)(sc.nextInt).sortWith(_ > _)\n val P: List[Int] = List.fill(M)(sc.nextInt).sortWith(_ < _)\n\n def simulate(n: Int): Int = {\n (P.take(n).reverse, B.take(n)).zipped.map { (a: Int , b: Int) =>\n (a - b) max 0\n }.sum\n }\n\n @tailrec\n def binSearch(a: Int, b: Int): Int = {\n val m = (a + b) / 2\n if (b - a <= 1) a\n else if (simulate(m) > A) binSearch(a, m)\n else binSearch(m, b)\n }\n\n val nm = N min M\n val r = if (simulate(nm) <= A) nm\n else binSearch(0, nm)\n if (r == 0) List(0, 0)\n else List(r, (P.take(r).sum - A) max 0)\n }\n\n out.println(solve.mkString(\" \"))\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P363D extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): List[Int] = {\n val N, M = sc.nextInt\n val A: Int = sc.nextInt\n val B: List[Int] = List.fill(N)(sc.nextInt).sortWith(_ > _)\n val P: List[Int] = List.fill(M)(sc.nextInt).sortWith(_ < _)\n\n def simulate(n: Int): Int = {\n (P.take(n).reverse, B.take(n)).zipped.map { (a: Int , b: Int) =>\n (a - b) max 0\n }.sum\n }\n\n @tailrec\n def binSearch(a: Int, b: Int): Int = {\n val m = (a + b) / 2\n if (b - a <= 1) a\n else if (simulate(m) > A) binSearch(a, m)\n else binSearch(m, b)\n }\n\n val nm = N min M\n val r = if (simulate(nm) <= A) nm\n else binSearch(0, nm)\n if (r == 0) List(0, 0)\n else List(r, P.take(r).sum - A)\n }\n\n out.println(solve.mkString(\" \"))\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P363D extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): List[Int] = {\n val N, M = sc.nextInt\n val A: Int = sc.nextInt\n val B: List[Int] = List.fill(N)(sc.nextInt).sortWith(_ > _)\n val P: List[Int] = List.fill(M)(sc.nextInt).sortWith(_ < _)\n\n def simulate(n: Int): Int = {\n (P.take(n), B.take(n)).zipped.map { (a: Int , b: Int) =>\n (a - b) max 0\n }.sum\n }\n\n @tailrec\n def binSearch(a: Int, b: Int): Int = {\n val c = (a + b) / 2\n val r= simulate(c)\n if (b == c) a\n else if (A <= r) binSearch(a, c)\n else binSearch(c + 1, b)\n }\n\n val r = binSearch(0, N min M)\n val s = (P.take(r).sum - A) max 0\n List(r, s)\n }\n\n out.println(solve.mkString(\" \"))\n out.close\n}\n"}], "src_uid": "cf8249244f67fb26bee3cdf0daedaca0"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val d = in.next().toInt\n val n = in.next().toInt\n println(in.next().split(' ').init.map(d - _.toInt).sum)\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val d = readInt()\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n println(a.dropRight(1).map(d -).sum)\n }\n}"}], "negative_code": [], "src_uid": "dc5ddfc2d2e5589eb91aa33744c8fd14"} {"source_code": "object C{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val n=nextInt\n val s=nextString\n var sum=1\n var nn=0\n \n for(i<-0 until n-1){\n if(s(i)==s(i+1)){\n nn+=1\n }else{\n sum+=1\n }\n }\n if(nn==1){\n sum+=1\n }else if(nn>=2){\n sum+=2\n }\n out.println(sum)\n\n //code ends here\n out.flush\n out.close\n }\n}\n\n", "positive_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val s = readLine.toCharArray\n \n var cnt = 0\n \n var prev = ' '\n var same3 = false\n var same2 = 0\n for (i <- 0 until n) {\n if (s(i) != prev) cnt += 1\n prev = s(i)\n if (i > 1 && s(i) == s(i - 1) && s(i) == s(i - 2)) same3 = true\n if (i > 2 && s(i) == s(i - 1) && s(i - 3) == s(i - 2)) same3 = true\n if (i > 0 && s(i) == s(i - 1)) same2 += 1\n }\n \n if (same3 || same2 > 1) cnt += 2\n else if (n > 1) {\n if (s(0) == s(1) || s(n - 1) == s(n - 2) || same2 > 0) cnt += 1\n }\n\n println(cnt)\n}\n"}, {"source_code": "import scala.io.Source\n\n/**\n * Created by Xiao on 2016/3/15 0015.\n */\n\nobject me {\n def main(args: Array[String]): Unit = {\n val line = Source.stdin.getLines()\n val n = Integer.parseInt(line.next())\n val str = line.next()\n var ans = 1\n var i = 0\n for(i <- 1 to n-1) {\n if(str.charAt(i) != str.charAt(i-1)) {\n ans+=1\n }\n }\n ans+=2\n if(n (el2, count)\n case ((el1, count), el2) => (el2, count + 1)\n }._2\n }\n\n\n println(line.sliding(2).count(a => a.length == 2 && a.head == a.last) match {\n case 0 => count(line)\n case 1 => count(line) + 1\n case _ => count(line) + 2\n })\n\n\n}\n\n\n"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val s = readLine.toCharArray\n \n var cnt = 0\n \n var prev = ' '\n var same3 = false\n for (i <- 0 until n) {\n if (s(i) != prev) cnt += 1\n prev = s(i)\n if (i > 1 && s(i) == s(i - 1) && s(i) == s(i - 2)) same3 = true\n }\n \n if (same3) cnt += 2\n else if (n > 1) {\n if (s(0) == s(1) || s(n - 1) == s(n - 2)) cnt += 1\n }\n\n println(cnt)\n}\n"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val s = readLine.toCharArray\n \n var cnt = 0\n \n var prev = ' '\n var same3 = false\n for (i <- 0 until n) {\n if (s(i) != prev) cnt += 1\n prev = s(i)\n if (i > 1 && s(i) == s(i - 1) && s(i) == s(i - 2)) same3 = true\n if (i > 2 && s(i) == s(i - 1) && s(i - 3) == s(i - 2)) same3 = true\n }\n \n if (same3) cnt += 2\n else if (n > 1) {\n if (s(0) == s(1) || s(n - 1) == s(n - 2)) cnt += 1\n }\n\n println(cnt)\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next()\n\n def count(str: String): Int = {\n str.tail.foldLeft(str.head, 1) {\n case ((el1, count), el2) if el1 == el2 => (el2, count)\n case ((el1, count), el2) => (el2, count + 1)\n }._2\n }\n\n\n println(line.sliding(2).count(a => a.head == a.last) match {\n case 0 => count(line)\n case 1 => count(line) + 1\n case _ => count(line) + 2\n })\n\n\n}\n\n\n"}], "src_uid": "7b56edf7cc71a1b3e39b3057a4387cad"} {"source_code": "object D{\n def main(args: Array[String]){\n// import scala.collection.mutable.PriorityQueue\n// import scala.collection.mutable.ArrayBuffer\n import scala.collection.mutable.BitSet\n// import scala.collection.mutable.Set\n import util.control.Breaks._\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n val n=in.nextInt\n val m=in.nextInt\n val sub=in.next\n val y=(for(i<- 0 until m) yield in.nextInt).toArray\n // index\n/* var A= collection.immutable.Set[Int]()\n for(k<- 1 to sub.length-1){\n A=A.filter((l)=>sub(k)==sub(k-l))\n\n if(sub(k)==sub(0)){\n A=A+k\n }\n }*/\n\n\n // for(i<-0 until sub.length){out.print(A(i)+\" \")}\n var sum=0\n\n var bad=false\n if(m!=0){\n var A=Array.fill(sub.length)(-1)\n var j= -1\n A(0)= -1\n for(i<-1 until sub.length){\n while(j>=0 && sub(i)!=sub(j+1)){\n j=A(j)\n }\n if(j== -1){\n if(sub(i)!=sub(0)){\n j= -2\n }\n }\n j+=1\n A(i)=j\n }\n sum=y(0)-1\n var B=Array.fill(sub.length)(true)\n var ll=sub.length-1\n ll=A(ll)\n while(ll>=0){\n B(sub.length-ll-1)=false\n ll=A(ll)\n }\n breakable{\n for(i<-1 until m){\n if(y(i)-y(i-1)>=sub.length){\n sum+=y(i)-y(i-1)-sub.length\n }\n else if(B(y(i)-y(i-1))){\n bad=true\n break\n }\n }\n }\n }\n if(m!=0 && n-y(m-1)+1s.toInt)).toArray\n val y=Array.fill(m)(0)\n \n for(i<- 0 until m) {y(i)=nextInt}\n // index\n/* var A= collection.immutable.Set[Int]()\n for(k<- 1 to sub.length-1){\n A=A.filter((l)=>sub(k)==sub(k-l))\n\n if(sub(k)==sub(0)){\n A=A+k\n }\n }*/\n\n\n // for(i<-0 until sub.length){out.print(A(i)+\" \")}\n var sum=0\n\n var bad=false\n if(m!=0){\n val A=Array.fill(sub.length)(-1)\n var j= -1\n A(0)= -1\n for(i<-1 until sub.length){\n while(j>=0 && sub(i)!=sub(j+1)){\n j=A(j)\n }\n if(j== -1){\n if(sub(i)!=sub(0)){\n j= -2\n }\n }\n j+=1\n A(i)=j\n }\n sum=y(0)-1\n val B=Array.fill(sub.length)(true)\n var ll=sub.length-1\n ll=A(ll)\n while(ll>=0){\n B(sub.length-ll-1)=false\n ll=A(ll)\n }\n breakable{\n for(i<-1 until m){\n if(y(i)-y(i-1)>=sub.length){\n sum+=y(i)-y(i-1)-sub.length\n }\n else if(B(y(i)-y(i-1))){\n bad=true\n break\n }\n }\n }\n }\n if(m!=0 && n-y(m-1)+1 0 && (j < p.length && p(k) != p(j))) k = next(k)\n if (j >= p.length || p(k) == p(j)) k += 1\n next(j + 1) = k\n }\n\n val d = p.length - next(p.length)\n\n var ok = true\n if (ys.nonEmpty) {\n var prev = ys.head\n for (y <- ys.tail) {\n if ((y - prev) % d != 0 && (y - prev < p.length)) ok = false\n prev = y\n }\n }\n\n if (!ok) println(0)\n else {\n val occupied = mutable.BitSet.empty\n var pos = 0\n for (y <- ys) {\n var i = y max pos\n val r = y + p.length - 1\n while (i <= r) {\n occupied += i\n i += 1\n }\n pos = r\n }\n val free = n - occupied.size\n val res = if (free < 0) 0 else BigInt(26).modPow(free, 1000000007L)\n println(res)\n }\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val p = readLine\n val ys = if (m == 0) Array.empty else readInts(m).map(_ - 1)\n\n val next = Array.fill(2 * p.length + 2)(0)\n var k = 0\n for (j <- 1 until 2 * p.length + 1) {\n while (k > 0 && (j < p.length && p(k) != p(j))) k = next(k)\n if (j >= p.length || p(k) == p(j)) k += 1\n next(j + 1) = k\n }\n\n val d = p.length - next(p.length)\n\n var ok = true\n if (ys.nonEmpty) {\n var prev = ys.head\n for (y <- ys.tail) {\n if ((y - prev) % d != 0 && (y - prev < p.length)) ok = false\n prev = y\n }\n }\n\n if (!ok) println(0)\n else {\n var free = n\n var pos = 0\n for (y <- ys) {\n var i = y max pos\n val r = y + p.length\n while (i < r) {\n free -= 1\n i += 1\n }\n pos = r\n }\n val res = if (free < 0) 0 else BigInt(26).modPow(free, 1000000007L)\n println(res)\n }\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, _m) = readInts(2)\n val p = readLine\n val ys = if (_m == 0) Array.empty else readInts(_m).map(_ - 1)\n\n val next = Array.fill(2 * p.length + 2)(0)\n var k = 0\n for (j <- 1 until 2 * p.length + 1) {\n while (k > 0 && (j < p.length && p(k) != p(j))) k = next(k)\n if (j >= p.length || p(k) == p(j)) k += 1\n next(j + 1) = k\n }\n /*\n var j = 0\n val matchesBuilder = new ArrayBuilder.ofInt\n for (i <- p.indices) {\n while (j > 0 && p(j) != p(i)) j = next(j)\n if (p(j) == p(i)) j += 1\n println(i, j)\n// if (j == p.length - i) {\n// matchesBuilder += i - j + 1//p.length//matches += 1 // match at i - m\n// j = next(j)\n// }\n if (i == p.size - 1) println(j)\n }\n \n val matches = matchesBuilder.result\n val matchesSet = mutable.BitSet.empty ++ matches\n println(matches.mkString(\" \"))\n println(next.mkString(\" \"))\n if (!ys.forall(matchesSet)) println(0)\n */\n\n val d = p.length - next(p.length)\n //println(d)\n\n var ok = true\n if (ys.nonEmpty) {\n var prev = ys.head\n for (y <- ys.tail) {\n if ((y - prev) % d != 0 && (y - prev < p.length)) ok = false\n prev = y\n }\n }\n\n if (!ok) println(0)\n else {\n val occupied = mutable.BitSet.empty\n var pos = 0\n for (y <- ys) {\n var i = y max pos\n val r = y + p.length - 1\n while (i <= r) {\n occupied += i\n i += 1\n }\n pos = r\n }\n val free = n - occupied.size\n val res = if (free < 0) 0 else BigInt(26).modPow(free, 1000000007L)\n println(res)\n }\n}\n"}, {"source_code": "object D{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n val n=in.nextInt\n val m=in.nextInt\n val sub=in.next\n// nextLine\n// val y=(nextLine.split(' ').map((s)=>s.toInt)).toArray\n // val y=Array.fill(m)(0)\n val y= (for(_<- 0 until m) yield nextInt).toArray\n// for(i<- 0 until m) {y(i)=nextInt}\n // index\n/* var A= collection.immutable.Set[Int]()\n for(k<- 1 to sub.length-1){\n A=A.filter((l)=>sub(k)==sub(k-l))\n\n if(sub(k)==sub(0)){\n A=A+k\n }\n }*/\n\n\n // for(i<-0 until sub.length){out.print(A(i)+\" \")}\n var sum=0\n\n var bad=false\n if(m!=0){\n val A=Array.fill(sub.length)(-1)\n var j= -1\n A(0)= -1\n for(i<-1 until sub.length){\n while(j>=0 && sub(i)!=sub(j+1)){\n j=A(j)\n }\n if(j== -1){\n if(sub(i)!=sub(0)){\n j= -2\n }\n }\n j+=1\n A(i)=j\n }\n sum=y(0)-1\n val B=Array.fill(sub.length)(true)\n var ll=sub.length-1\n ll=A(ll)\n while(ll>=0){\n B(sub.length-ll-1)=false\n ll=A(ll)\n }\n breakable{\n for(i<-1 until m){\n if(y(i)-y(i-1)>=sub.length){\n sum+=y(i)-y(i-1)-sub.length\n }\n else if(B(y(i)-y(i-1))){\n bad=true\n break\n }\n }\n }\n }\n if(m!=0 && n-y(m-1)+1s.toInt)).toArray\n val y=(for(_<- 0 until m)yield nextInt).toArray\n // index\n/* var A= collection.immutable.Set[Int]()\n for(k<- 1 to sub.length-1){\n A=A.filter((l)=>sub(k)==sub(k-l))\n\n if(sub(k)==sub(0)){\n A=A+k\n }\n }*/\n\n\n // for(i<-0 until sub.length){out.print(A(i)+\" \")}\n var sum=0\n\n var bad=false\n if(m!=0){\n val A=Array.fill(sub.length)(-1)\n var j= -1\n A(0)= -1\n for(i<-1 until sub.length){\n while(j>=0 && sub(i)!=sub(j+1)){\n j=A(j)\n }\n if(j== -1){\n if(sub(i)!=sub(0)){\n j= -2\n }\n }\n j+=1\n A(i)=j\n }\n sum=y(0)-1\n val B=Array.fill(sub.length)(true)\n var ll=sub.length-1\n ll=A(ll)\n while(ll>=0){\n B(sub.length-ll-1)=false\n ll=A(ll)\n }\n breakable{\n for(i<-1 until m){\n if(y(i)-y(i-1)>=sub.length){\n sum+=y(i)-y(i-1)-sub.length\n }\n else if(B(y(i)-y(i-1))){\n bad=true\n break\n }\n }\n }\n }\n if(m!=0 && n-y(m-1)+1 0 && p(k) != p(j)) k = next(k)\n if (p(k) == p(j)) k += 1\n next(j + 1) = k\n }\n\n val d = p.length - next(p.length)\n\n var ok = true\n if (ys.nonEmpty) {\n var prev = ys.head\n for (y <- ys.tail) {\n if ((y - prev) % d != 0 && y - prev < p.length) ok = false\n prev = y\n }\n }\n\n if (!ok) println(0)\n else {\n var free = n\n var pos = 0\n for (y <- ys) {\n var i = y max pos\n val r = y + p.length\n while (i < r) {\n free -= 1\n i += 1\n }\n pos = r\n }\n val res = if (free < 0) 0 else BigInt(26).modPow(free, 1000000007L)\n println(res)\n }\n}"}, {"source_code": "object D{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n\n\n def main(args: Array[String]){\n\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine=in.nextLine\n val n=in.nextInt\n val m=in.nextInt\n val sub=in.next\n// nextLine\n// val y=(nextLine.split(' ').map((s)=>s.toInt)).toArray\n val y=Array.fill(m)(0)\n \n for(i<- 0 until m) {y(i)=nextInt}\n // index\n/* var A= collection.immutable.Set[Int]()\n for(k<- 1 to sub.length-1){\n A=A.filter((l)=>sub(k)==sub(k-l))\n\n if(sub(k)==sub(0)){\n A=A+k\n }\n }*/\n\n\n // for(i<-0 until sub.length){out.print(A(i)+\" \")}\n var sum=0\n\n var bad=false\n if(m!=0){\n val A=Array.fill(sub.length)(-1)\n var j= -1\n A(0)= -1\n for(i<-1 until sub.length){\n while(j>=0 && sub(i)!=sub(j+1)){\n j=A(j)\n }\n if(j== -1){\n if(sub(i)!=sub(0)){\n j= -2\n }\n }\n j+=1\n A(i)=j\n }\n sum=y(0)-1\n val B=Array.fill(sub.length)(true)\n var ll=sub.length-1\n ll=A(ll)\n while(ll>=0){\n B(sub.length-ll-1)=false\n ll=A(ll)\n }\n breakable{\n for(i<-1 until m){\n if(y(i)-y(i-1)>=sub.length){\n sum+=y(i)-y(i-1)-sub.length\n }\n else if(B(y(i)-y(i-1))){\n bad=true\n break\n }\n }\n }\n }\n if(m!=0 && n-y(m-1)+1 0 && (j < p.length && p(k) != p(j))) k = next(k)\n if (j >= p.length || p(k) == p(j)) k += 1\n next(j + 1) = k\n }\n/*\n var j = 0\n val matchesBuilder = new ArrayBuilder.ofInt\n for (i <- p.indices) {\n while (j > 0 && p(j) != p(i)) j = next(j)\n if (p(j) == p(i)) j += 1\n println(i, j)\n// if (j == p.length - i) {\n// matchesBuilder += i - j + 1//p.length//matches += 1 // match at i - m\n// j = next(j)\n// }\n if (i == p.size - 1) println(j)\n }\n \n val matches = matchesBuilder.result\n val matchesSet = mutable.BitSet.empty ++ matches\n println(matches.mkString(\" \"))\n println(next.mkString(\" \"))\n if (!ys.forall(matchesSet)) println(0)\n */\n \n val d = p.length - next(p.length)\n //println(d)\n \n var prev = ys.head\n var ok = true\n for (y <- ys.tail) {\n if ((y - prev) % d != 0) ok = false\n prev = y\n } \n \n if (!ok) println(0)\n else {\n val occupied = mutable.BitSet.empty\n var pos = 0\n for (y <- ys) {\n var i = y max pos\n val r = y + p.length - 1\n while (i <= r) {\n occupied += i\n i += 1\n }\n pos = r\n }\n val free = n - occupied.size\n val res = if (free < 0) 0 else BigInt(26).modPow(free, 1000000007L)\n println(res)\n }\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val p = readLine\n val ys = if (m == 0) Array.empty else readInts(m).map(_ - 1)\n\n val next = Array.fill(2 * p.length + 2)(0)\n var k = 0\n for (j <- 1 until 2 * p.length + 1) {\n while (k > 0 && (j < p.length && p(k) != p(j))) k = next(k)\n if (j >= p.length || p(k) == p(j)) k += 1\n next(j + 1) = k\n }\n\n val d = p.length - next(p.length)\n\n var ok = true\n if (ys.nonEmpty) {\n var prev = ys.head\n for (y <- ys.tail) {\n if ((y - prev) % d != 0 && (y - prev < p.length)) ok = false\n prev = y\n }\n }\n\n if (!ok) println(0)\n else {\n var free = n\n var pos = 0\n for (y <- ys) {\n var i = y max pos\n val r = y + p.length - 1\n while (i <= r) {\n free -= 1\n i += 1\n }\n pos = r\n }\n val res = if (free < 0) 0 else BigInt(26).modPow(free, 1000000007L)\n println(res)\n }\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, _m) = readInts(2)\n val p = readLine\n val ys = readInts(_m).map(_ - 1)\n\n val next = Array.fill(2 * p.length + 2)(0)\n var k = 0\n for (j <- 1 until 2 * p.length + 1) {\n while (k > 0 && (j < p.length && p(k) != p(j))) k = next(k)\n if (j >= p.length || p(k) == p(j)) k += 1\n next(j + 1) = k\n }\n /*\n var j = 0\n val matchesBuilder = new ArrayBuilder.ofInt\n for (i <- p.indices) {\n while (j > 0 && p(j) != p(i)) j = next(j)\n if (p(j) == p(i)) j += 1\n println(i, j)\n// if (j == p.length - i) {\n// matchesBuilder += i - j + 1//p.length//matches += 1 // match at i - m\n// j = next(j)\n// }\n if (i == p.size - 1) println(j)\n }\n \n val matches = matchesBuilder.result\n val matchesSet = mutable.BitSet.empty ++ matches\n println(matches.mkString(\" \"))\n println(next.mkString(\" \"))\n if (!ys.forall(matchesSet)) println(0)\n */\n\n val d = p.length - next(p.length)\n //println(d)\n\n var ok = true\n if (ys.nonEmpty) {\n var prev = ys.head\n for (y <- ys.tail) {\n if ((y - prev) % d != 0) ok = false\n prev = y\n }\n }\n\n if (!ok) println(0)\n else {\n val occupied = mutable.BitSet.empty\n var pos = 0\n for (y <- ys) {\n var i = y max pos\n val r = y + p.length - 1\n while (i <= r) {\n occupied += i\n i += 1\n }\n pos = r\n }\n val free = n - occupied.size\n val res = if (free < 0) 0 else BigInt(26).modPow(free, 1000000007L)\n println(res)\n }\n}\n"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, _m) = readInts(2)\n val p = readLine\n val ys = readInts(_m).map(_ - 1)\n\n val next = Array.fill(2 * p.length + 2)(0)\n var k = 0\n for (j <- 1 until 2 * p.length) {\n while (k > 0 && (j < p.length && p(k) != p(j))) k = next(k)\n if (j >= p.length || p(k) == p(j)) k += 1\n next(j + 1) = k\n }\n\n var j = 0\n val matchesBuilder = new ArrayBuilder.ofInt\n for (i <- p.indices) {\n while (j > 0 && p(j) != p(i)) j = next(j)\n if (p(j) == p(i)) j += 1\n if (j == p.length - i) {\n matchesBuilder += i - j + 1//p.length//matches += 1 // match at i - m\n j = next(j)\n }\n }\n \n val matches = matchesBuilder.result\n val matchesSet = mutable.BitSet.empty ++ matches\n \n if (!ys.forall(matchesSet)) println(0)\n else {\n val occupied = mutable.BitSet.empty\n var pos = 0\n for (y <- ys) {\n var i = y max pos\n val r = y + p.length - 1\n while (i <= r) {\n occupied += i\n i += 1\n }\n pos = r\n }\n val free = n - occupied.size\n val res = BigInt(26).modPow(free, 1000000007L)\n println(res)\n }\n}\n"}, {"source_code": "object D{\n def main(args: Array[String]){\n// import scala.collection.mutable.PriorityQueue\n// import scala.collection.mutable.ArrayBuffer\n import scala.collection.mutable.TreeSet\n import util.control.Breaks._\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n val n=in.nextInt\n val m=in.nextInt\n val sub=in.next\n val y=(for(i<- 0 until m) yield in.nextInt).toArray\n // index\n val A=new TreeSet[Int]()\n for(k<- 1 to sub.length-1){\n for(l <- A){\n if(sub(k)!=sub(k-l)){\n A-=l\n }\n }\n if(sub(k)==sub(0)){\n A+=k\n }\n }\n var sum=y(0)-1\n var bad=false\n for(i<-1 until m){\n if(y(i)-y(i-1)>=sub.length){\n sum+=y(i)-y(i-1)-sub.length\n }\n else if(!A(y(i)-y(i-1))){\n bad=true\n }\n }\n if(bad){\n out.println(0)\n }\n else{\n if(n-y(m-1)+1>=sub.length){\n sum+=n-y(m-1)-sub.length+1\n var r=1\n for(i<-0 until sum){\n r=(r*26)%1000000007\n }\n out.println(r)\n }\n else{\n out.println(0)\n }\n }\n out.flush\nout.close\n }\n}\n"}], "src_uid": "9cd17c2617b6cde593ef12b2a0a807fb"} {"source_code": "import scala.collection.SortedSet\nimport scala.collection.immutable.TreeMap\nimport scala.collection.immutable.TreeSet\nimport scala.io.StdIn\n\nobject Main extends App {\n def intPair(s: String): (Int, Int) = {\n val (s1, s2) = s.span(_ != ' ')\n (s1.toInt, s2.trim().toInt)\n }\n \n val m :: k :: List() = StdIn.readLine().split(\" \").map(_.toInt).toList\n \n val input = (1 to m).map { _ => StdIn.readLine() }\n val pairs = TreeSet(input.map(intPair).flatMap(p => List(p, p.swap)) :_*)\n \n val friends = TreeMap(pairs.groupBy { case (a, b) => a}.mapValues(_.map { case (a, b) => b}).toSeq: _*)\n val people = friends.keySet.toList\n\n def isSuggested(person: Int, me: Int): Boolean = {\n val myFriends = friends(me)\n person != me && \n !myFriends.contains(person) && \n (friends(person) & myFriends).size * 100 >= k * myFriends.size\n }\n\n def suggestedFriends(me: Int) : List[Int] = people.filter(isSuggested(_, me))\n \n val result = TreeMap((people zip people.map(suggestedFriends)).toSeq :_*)\n \n result.foreach { case (me, suggested) =>\n println(s\"$me: ${suggested.size} ${suggested.mkString(\" \")}\")\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.immutable.TreeMap\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\nobject Main extends App {\n val m :: k :: List() = StdIn.readLine().split(\" \").map(_.toInt).toList\n val lines = (1 to m).map(x => StdIn.readLine())\n\n val pairs = TreeSet(lines.flatMap(_.split(\" \").map(_.toInt).toList match {\n case a :: b :: List() => List((a, b), (b, a))\n }).toList: _*)\n\n val friends = TreeMap(pairs.groupBy { case (a, b) => a}.mapValues(_.map { case (a, b) => b}).toSeq: _*)\n\n\n for (me <- friends.keySet) {\n print(s\"$me: \")\n val result = ListBuffer[Int]()\n val myFriends = friends(me)\n\n for (person <- friends.keySet) {\n var s = 0\n if (person != me && !pairs.contains(person -> me)) {\n for (friend <- myFriends) {\n if (pairs.contains(friend -> person)) {\n s += 1\n }\n }\n\n if (s * 100 >= k * myFriends.size) {\n result += person\n }\n }\n }\n\n print(s\"${result.size} \")\n println(result.mkString(\" \"))\n }\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable.TreeMap\nimport scala.collection.immutable.TreeSet\n\nobject Main extends App with IOUtils { \n val (m, k) = nextIntPair\n val pairsList = (1 to m).map { _ => nextIntPair }\n \n val pairs = TreeSet(pairsList.flatMap(p => List(p, p.swap)) :_*)\n \n val friends = TreeMap(pairs.groupBy { case (a, b) => a}.mapValues(_.map { case (a, b) => b}).toSeq: _*)\n val people = friends.keySet.toList\n\n def isSuggested(person: Int, me: Int): Boolean = {\n val myFriends = friends(me)\n person != me && \n !myFriends.contains(person) && \n (friends(person) & myFriends).size * 100 >= k * myFriends.size\n }\n\n def suggestedFriends(me: Int) : List[Int] = people.filter(isSuggested(_, me))\n \n val result = TreeMap((people zip people.map(suggestedFriends)).toSeq :_*)\n \n result.foreach { case (me, suggested) =>\n println(s\"$me: ${suggested.size} ${suggested.mkString(\" \")}\")\n }\n}\n\ntrait IOUtils {\n var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def nextInt: Int = nextToken.toInt\n def nextLong: Long = nextToken.toLong\n def nextIntPair: (Int, Int) = (nextInt, nextInt)\n\n def nextToken: String = {\n if (tok == null || !tok.hasMoreTokens) {\n tok = new StringTokenizer(in.readLine)\n }\n\n tok.nextToken\n }\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable.HashSet\nimport scala.collection.immutable.TreeMap\nimport scala.collection.immutable.TreeSet\n\nobject Main extends App with IOUtils {\n val (m, k) = nextIntPair\n\n def pairsList = (1 to m).map { _ => nextIntPair}\n\n val pairs = TreeSet(pairsList.flatMap(p => List(p, p.swap)): _*)\n\n val friends = TreeMap(pairs.groupBy(_._1).mapValues(_.map(_._2)).toSeq: _*)\n val people = friends.keySet.toList\n\n def isSuggested(person: Int, me: Int): Boolean = {\n val myFriends = friends(me)\n person != me &&\n !myFriends.contains(person) &&\n (friends(person) & myFriends).size * 100 >= k * myFriends.size\n }\n\n def suggestedFriends(me: Int): List[Int] = people.filter(isSuggested(_, me))\n\n val result = people zip (people map suggestedFriends)\n\n result.foreach { case (me, suggested) =>\n println(s\"$me: ${suggested.size} ${suggested.mkString(\" \")}\")\n }\n}\n\ntrait IOUtils {\n var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def nextInt: Int = nextToken.toInt\n\n def nextLong: Long = nextToken.toLong\n\n def nextIntPair: (Int, Int) = (nextInt, nextInt)\n\n def nextToken: String = {\n if (tok == null || !tok.hasMoreTokens) {\n tok = new StringTokenizer(in.readLine)\n }\n\n tok.nextToken\n }\n}\n"}, {"source_code": "import scala.collection.SortedSet\nimport scala.collection.immutable.TreeMap\nimport scala.collection.immutable.TreeSet\nimport scala.io.StdIn\n\nobject Main extends App {\n val m :: k :: List() = StdIn.readLine().split(\" \").map(_.toInt).toList\n\n val pairs = TreeSet((1 to m).flatMap(x => StdIn.readLine().split(\" \").map(_.toInt).toList match {\n case a :: b :: List() => List((a, b), (b, a))\n }).toList: _*)\n \n val friends = TreeMap(pairs.groupBy { case (a, b) => a}.mapValues(_.map { case (a, b) => b}).toSeq: _*)\n val people = friends.keySet.toList\n\n def isSuggested(person: Int, me: Int): Boolean = {\n val myFriends = friends(me)\n person != me && \n !myFriends.contains(person) && \n (friends(person) & myFriends).size * 100 >= k * myFriends.size\n }\n\n def suggestedFriends(me: Int) : List[Int] = people.filter(isSuggested(_, me))\n \n val result = TreeMap((people zip people.map(suggestedFriends)).toSeq :_*)\n \n result.foreach { case (me, suggested) =>\n println(s\"$me: ${suggested.size} ${suggested.mkString(\" \")}\")\n }\n}\n"}, {"source_code": "import java.io.InputStreamReader\nimport java.io.BufferedReader\n\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable.TreeMap\nimport scala.collection.mutable.HashSet\nimport scala.collection.mutable.ListBuffer\n\nobject Main extends App {\n var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def nextInt: Int = nextToken.toInt\n\n def nextLong: Long = nextToken.toLong\n\n def nextToken: String = {\n if (tok == null || !tok.hasMoreTokens) {\n tok = new StringTokenizer(in.readLine)\n }\n \n tok.nextToken\n }\n\n val m: Int = nextInt\n val k: Int = nextInt\n var friends = TreeMap[Int, List[Int]]()\n val pairs = new HashSet[(Int, Int)]\n\n for (i <- 1 to m) {\n val a: Int = nextInt\n val b: Int = nextInt\n if (!friends.contains(a)) {\n friends += a -> List[Int]()\n }\n\n friends += a -> (b :: friends(a))\n\n if (!friends.contains(b)) {\n friends += b -> List[Int]()\n }\n\n friends += b -> (a :: friends(b))\n\n pairs += a -> b\n pairs += b -> a\n }\n\n for (me <- friends.keySet) {\n print(s\"$me: \")\n val result = ListBuffer[Int]()\n val myFriends = friends(me)\n\n for (person <- friends.keySet) {\n var s = 0\n if (person != me && !pairs.contains(person -> me)) {\n for (friend <- myFriends) {\n if (pairs.contains(friend -> person)) {\n s += 1\n }\n }\n\n if (s * 100 >= k * myFriends.size) {\n result += person\n }\n }\n }\n\n print(s\"${result.size} \")\n println(result.mkString(\" \"))\n }\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable.HashSet\nimport scala.collection.immutable.TreeMap\nimport scala.collection.immutable.TreeSet\n\nobject Main extends App with IOUtils {\n val (m, k) = nextIntPair\n\n def pairsList = (1 to m).map { _ => nextIntPair}\n\n val pairs = TreeSet(pairsList.flatMap(p => List(p, p.swap)): _*)\n \n val friends = pairs.foldLeft(TreeMap[Int, Set[Int]]()) { (m, p) =>\n m + (p._1 -> (m.getOrElse(p._1, Set()) + p._2))\n }\n\n// val friends = TreeMap(pairs.groupBy(_._1).mapValues(_.map(_._2)).toSeq: _*)\n val people = friends.keySet.toList\n\n def isSuggested(person: Int, me: Int): Boolean = {\n val myFriends = friends(me)\n person != me &&\n !myFriends.contains(person) &&\n (friends(person) & myFriends).size * 100 >= k * myFriends.size\n }\n\n def suggestedFriends(me: Int): List[Int] = people.filter(isSuggested(_, me))\n\n val result = TreeMap((people zip people.map(suggestedFriends)).toSeq: _*)\n\n result.foreach { case (me, suggested) =>\n println(s\"$me: ${suggested.size} ${suggested.mkString(\" \")}\")\n }\n}\n\ntrait IOUtils {\n var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def nextInt: Int = nextToken.toInt\n\n def nextLong: Long = nextToken.toLong\n\n def nextIntPair: (Int, Int) = (nextInt, nextInt)\n\n def nextToken: String = {\n if (tok == null || !tok.hasMoreTokens) {\n tok = new StringTokenizer(in.readLine)\n }\n\n tok.nextToken\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.immutable.TreeMap\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable.ListBuffer\nimport scala.io.Source\nimport scala.io.StdIn\n\nobject Main extends App {\n val m :: k :: List() = StdIn.readLine().split(\" \").map(_.toInt).toList\n\n val pairs = TreeSet(Source.stdin.getLines().flatMap(_.split(\" \").map(_.toInt).toList match {\n case a :: b :: List() => List((a, b), (b, a))\n }).toList :_*)\n\n val friends = TreeMap(pairs.groupBy{ case (a, b) => a }.mapValues(_.map { case (a, b) => b }).toSeq :_*)\n\n\n for (me <- friends.keySet) {\n print(s\"$me: \")\n val result = ListBuffer[Int]()\n val myFriends = friends(me)\n\n for (person <- friends.keySet) {\n var s = 0\n if (person != me && !pairs.contains(person -> me)) {\n for (friend <- myFriends) {\n if (pairs.contains(friend -> person)) {\n s += 1\n }\n }\n\n if (s * 100 >= k * myFriends.size) {\n result += person\n }\n }\n }\n\n print(s\"${result.size} \")\n println(result.mkString(\" \"))\n }\n}\n"}, {"source_code": "import scala.collection.SortedSet\nimport scala.collection.immutable.TreeMap\nimport scala.collection.immutable.TreeSet\nimport scala.io.StdIn\n\nobject Main extends App {\n val m :: k :: List() = StdIn.readLine().split(\" \").map(_.toInt).toList\n\n val pairs = TreeSet((1 to m).flatMap(x => StdIn.readLine().split(\" \").map(_.toInt).toList match {\n case a :: b :: List() => List((a, b), (b, a))\n }).toList: _*)\n \n val friends = TreeMap(pairs.groupBy { case (a, b) => a}.mapValues(_.map { case (a, b) => b}).toSeq: _*)\n val people = friends.keySet.toList\n\n def isSuggested(person: Int, me: Int): Boolean = {\n val myFriends = friends(me)\n person != me && ((friends(person) & myFriends).size * 100 >= k * myFriends.size)\n }\n\n def suggestedFriends(me: Int) : List[Int] = people.filter(isSuggested(_, me))\n \n val result = TreeMap((people zip people.map(suggestedFriends)).toSeq :_*)\n \n result.foreach { case (me, suggested) =>\n println(s\"$me: ${suggested.size} ${suggested.mkString(\" \")}\")\n }\n}\n"}, {"source_code": "object Main2 extends App {\n\n}\n"}, {"source_code": "import java.io.InputStreamReader\nimport java.io.BufferedReader\n\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable.TreeMap\nimport scala.collection.mutable.HashSet\nimport scala.collection.mutable.ListBuffer\n\nobject Main extends App {\n var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def nextInt: Int = nextToken.toInt\n\n def nextLong: Long = nextToken.toLong\n\n def nextToken: String = {\n if (tok == null || !tok.hasMoreTokens) {\n tok = new StringTokenizer(in.readLine)\n }\n \n tok.nextToken\n }\n\n val m: Int = nextInt\n val k: Int = nextInt\n var friends = TreeMap[Int, List[Int]]()\n val pairs = new HashSet[(Int, Int)]\n\n for (i <- 1 to m) {\n val a: Int = nextInt\n val b: Int = nextInt\n if (!friends.contains(a)) {\n friends += a -> List[Int]()\n }\n\n friends += a -> (b :: friends(a))\n\n if (!friends.contains(b)) {\n friends += b -> List[Int]()\n }\n\n friends += b -> (a :: friends(b))\n\n pairs += a -> b\n pairs += b -> a\n }\n\n for (me <- friends.keySet) {\n print(s\"$me: \")\n val result = ListBuffer[Int]()\n val myFriends = friends(me)\n\n for (person <- friends.keySet) {\n var s = 0\n if (person != me && !pairs.contains(person -> me)) {\n for (friend <- myFriends) {\n if (pairs.contains(friend -> person)) {\n s += 1\n }\n }\n }\n\n if (s * 100 >= k * myFriends.size) {\n result += person\n }\n }\n\n print(s\"${result.size} \")\n println(result.mkString(\" \"))\n }\n}\n"}], "src_uid": "19079c10a1bdfa8ae9b7b6e0378d3aad"} {"source_code": "object A136 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n).zipWithIndex.toMap.mapValues(_+1)\n val res = (1 to n).foldLeft(List.empty[Int]) {case (arr, i) => arr ++ List(input(i))}\n println(res.mkString(\" \"))\n }\n}", "positive_code": [{"source_code": "object Main {\n\n def main(args: Array[String]) {\n\n val std = scala.io.StdIn\n val n = std.readLine().toInt\n val values = std.readLine().split(\" \").map(_.toInt)\n val result = new Array[Int](values.length)\n for (i <- 0 until n) {\n result(values(i)-1) = i + 1\n }\n println(result.mkString(\" \"))\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P136A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val presenters = new Array[Int](N)\n\n for (i <- 1 to N)\n presenters(sc.nextInt - 1) = i\n\n out.println(presenters.mkString(\" \"))\n out.close\n}\n"}, {"source_code": "\n\nobject Presents {\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in);\n\t\tval n = scanner.nextInt;\n\t\tvar function = new Array[Int](n);\n\t\tfor (i <- 1 to n) {\n\t\t\tval value = scanner.nextInt;\n\t\t\t\t\tfunction(value-1) = i\n\t\t}\n\t\tfor (i <- 1 to n) {\n\t\t print(function(i-1) + \" \")\n\t\t}\n\t}\n}"}, {"source_code": "import java.io._\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n\n val n = readInt\n def ans = readInts.zip(1 to n).sortBy(_._1).map(_._2).mkString(\" \")\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val i = readInt()\n val a = readLine.split(\" \").map(_.toInt)\n val r = new Array[Int](a.size)\n for(i <- 0 until a.size) { r(a(i) - 1) = i + 1 }\n println(r.mkString(\" \"))\n }\n}"}, {"source_code": "// Codeforces 136A\n\nobject _136A extends App {\n val scanner = new java.util.Scanner(System.in)\n val n = scanner.nextInt\n val presents = Array.fill(n)(scanner.nextInt)\n val answer = Array.tabulate(n)(i => presents.indexOf(i+1)+1)\n println(answer.mkString(\" \"))\n}\n\n\n"}, {"source_code": "import Array._\nimport scala.io.StdIn.readLine\nobject problem {\n def main(args: Array[String]) {\n val n = readLine.toInt\n val s = new Array[Int](n + 1)\n val A = readLine.split(\" \").map(_.toInt)\n for(i <- 0 until n){\n s(A(i)) = i + 1\n }\n for(i <- 1 to n) print(s(i) + \" \")\n }\n}"}, {"source_code": "import java.util.Scanner\n\n\nobject HelloWorldMain {\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n\n var array = new Array[Int](n)\n\n\n for( i <- 1 to n ){\n array(sc.nextInt()-1) = i\n\n }\n\n array.foreach(c => print(c + \" \"))\n }\n}\n\n\n\n"}, {"source_code": "import scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Presents {\n def main(args: Array[String]) {\n val n = readInt\n println((0 +: readLine.split(' ').map(_.toInt)).\n zipWithIndex.sortBy(_._1).tail.map(_._2).mkString(\" \"))\n }\n \n}"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n val n = StdIn.readLine().toInt\n\n val B = StdIn.readLine().split(\" \").map(_.toInt)\n val A:Array[Int] = new Array[Int](n)\n for(i <- 0 to n - 1) {\n A(B(i) - 1) = i + 1;\n }\n\n println(A.mkString(\" \"))\n\n\n }\n\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject TEST extends App {\n val n =readInt()\n val a : List[Int] = readLine.split(' ').toList.map(_.toInt)\n val ans = (for(i <- 1 to n) yield a.indexOf(i)+1).mkString(\" \")\n print(ans)\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Task extends App{\n val n = readInt\n val ps = readLine.split(\" \").map(_.toInt)\n \n val ans = ps.zipWithIndex.sortBy(_._1).map(_._2 + 1)\n \n println(ans.mkString(\" \"))\n}"}, {"source_code": "import java.util.Scanner\n\nobject MainA extends App {\n val sc = new Scanner(System.in)\n \n val N = sc.nextInt\n val l = for(t <- 0 until N) yield sc.nextInt\n val res = for(i <- 1 to N) yield l.indexOf(i) + 1\n println(res.mkString(\" \"))\n}\n"}, {"source_code": "object One36A extends App {\n\timport java.io.PrintWriter\n\timport java.util.Scanner\n\n\tval in = new Scanner(System.in)\n\tval out = new PrintWriter(System.out)\n\n\timport in._\n\timport out._\n\n\tval n = nextInt\n\tval arr = new Array[Int](n)\n\t\n\t(0 until n).foreach { i =>\n\t\tval no = nextInt\n\t\tarr(no-1) = i+1\n\t}\n\tprintln(arr.mkString(\" \"))\n\t\n\tin.close\n\tout.close\n}"}, {"source_code": "object Main extends App {\n def iterate(pointer: Int): Unit = {\n if (pointer == numberOfFriends) return\n else giftedByIdArray(giftMapArray(pointer) - 1) = pointer + 1; iterate(pointer + 1)\n }\n\n val numberOfFriends = readLine.toInt\n val giftMapArray = readLine.split(\" \").map(_.toInt)\n val giftedByIdArray = new Array[Int](numberOfFriends)\n iterate(0)\n\n println(giftedByIdArray.mkString(\" \"))\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject MainA extends App {\n val sc = new Scanner(System.in)\n \n val N = sc.nextInt\n val l = for(t <- 0 until N) yield sc.nextInt\n val res = for(i <- 1 to N) yield l.indexOf(i) + 1\n println(res.mkString(\" \"))\n}\n"}, {"source_code": "object Solution136A extends App {\n\n def solution() {\n val n = _int\n 1.to(n).map(_ => _int).zip(1.to(n)).sortBy(_._1).foreach(p => print(p._2 + \" \"))\n }\n\n //////////////////////////////////////////////////\n import java.util.Scanner\n val SC: Scanner = new Scanner(System.in)\n def _line: String = SC.nextLine\n def _int: Int = SC.nextInt\n def _long: Long = SC.nextLong\n def _string: String = SC.next\n solution()\n}"}, {"source_code": "import scala.collection.mutable._\nimport scala.math._\nimport scala.util._\nimport scala.util.control.Breaks.break\nimport scala.util.control.Breaks.breakable\nimport java.util._\nobject Main extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt\n val t = for(i <- 1 to n) yield sc.nextInt\n val s = for(i <- 1 to n) yield t.indexOf(i) + 1\n println(s.mkString(\" \"))\n}\n"}, {"source_code": "object Solution extends App{\n val in = scala.io.Source.stdin.getLines()\n in.next()\n val data = in.next().split(\" \").map(_.toInt)\n var answer = Array.ofDim[Int](data.length)\n data.zipWithIndex.foreach {\n case(index, value) => answer(index - 1) = value + 1\n }\n println(answer.mkString(\" \"))\n}"}], "negative_code": [], "src_uid": "48bb148e2c4d003cad9d57e7b1ab78fb"} {"source_code": "object TwoDistinctPoints extends App {\n\n val q = io.StdIn.readLine().toInt\n\n for (_ <- 1 to q) {\n\n val line = io.StdIn.readLine.split(\" \").map(_.toInt)\n val (l1, r1, l2, r2) = (line(0), line(1), line(2), line(3))\n\n val firstAns = l1\n val secondAns = if (l2 == firstAns) l2 + 1 else l2\n\n println(s\"$firstAns $secondAns\")\n }\n}\n", "positive_code": [{"source_code": "//package codeforces.contest1108\n\nobject TwoDistinctPoints {\n def main(args: Array[String]): Unit = {\n val q = io.StdIn.readInt()\n (1 to q).foreach { _ =>\n val Array(l1, r1, l2, r2) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val result: List[(Int, Int)] = for {\n a <- List(l1, r1)\n b <- List(l2, r2)\n if a != b\n } yield (a, b)\n\n println(result.head._1 + \" \" + result.head._2)\n }\n }\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val l1, r1, l2, r2 = ni()\n if (l1 == r2) {\n out.println(s\"$r1 $l1\")\n } else {\n out.println(s\"$l1 $r2\")\n }\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject A1108 {\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n for {i <- 1 to n} {\n val Array(l1, r1, l2, r2) = StdIn.readLine().split(' ').map(_.toInt)\n println(l1 + \" \" + (if (l1 == l2) r2 else l2))\n }\n }\n}"}, {"source_code": "object Main {\n\n def main(args: Array[String]) {\n\n val std = scala.io.StdIn\n val n = std.readLine().toInt\n\n for (_ <- 0 until n) {\n val values = std.readLine().split(\" \").map(_.toInt)\n if (values(0) <= values(2)) {\n println(values(0) + \" \" + values(3)) \n } else {\n println(values(1) + \" \" + values(2)) \n }\n }\n }\n}\n"}, {"source_code": "object CF_535_3_A {\n// date: 25/01/2019\n\n type In = Seq[Seq[Int]]\n type Out = Seq[(Int, Int)]\n \n def solve(in: In): Out = {\n val (xs) = in\n for {\n Seq(l1,r1,l2,r2) <- xs\n } yield {\n val b = if(l2 != l1) l2\n else l2 + 1\n (l1, b)\n }\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = i.getLines(i.int).map(_.intSeq)\n def formatOut(out: Out): String = out.map{case (a,b) => s\"$a $b\"}.mkString(\"\\n\")\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines(): Vector[String] = if (!sc.hasNextLine) Vector.empty\n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n // `a` MUST be > 0. Incorrect otherwise.\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}"}], "negative_code": [], "src_uid": "cdafe800094113515e1de1acb60c4bb5"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, q) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt).sorted\n val frequency = Array.ofDim[Int](n)\n (1 to q).foreach { _ =>\n val Array(l, r) = in.next().split(' ').map(_.toInt - 1)\n frequency(l) += 1\n if (r != n - 1)\n frequency(r + 1) -= 1\n }\n val sortedFreq = frequency.foldLeft((List.empty[Long], 0l)) {\n case((list, soFar), i) => (soFar + i :: list, soFar + i)\n }._1.sorted\n println(sortedFreq.zip(data).foldLeft(0l) {\n case(acc, (count, value)) => acc + count * value\n })\n\n}\n", "positive_code": [{"source_code": "object Main {\n private def scalaMergeSort(a: Array[Long], lo: Int, hi: Int, scratch: Array[Long]) {\n if (lo < hi) {\n val mid = (lo+hi) / 2\n scalaMergeSort(a, lo, mid, scratch)\n scalaMergeSort(a, mid+1, hi, scratch)\n var k, t_lo = lo\n var t_hi = mid + 1\n while (k <= hi) {\n if ((t_lo <= mid) && ((t_hi > hi) || (a(t_lo) >= a(t_hi)))) {\n scratch(k) = a(t_lo)\n t_lo += 1\n } else {\n scratch(k) = a(t_hi)\n t_hi += 1\n }\n k += 1\n }\n k = lo\n while (k <= hi) {\n a(k) = scratch(k)\n k += 1\n }\n }\n }\n \n def scalaMergeSortPerform(a: Array[Long]) {\n scalaMergeSort(a, 0, a.length - 1, Array.ofDim[Long](a.length))\n }\n\n def merge(a: Array[Long], b: Array[Long], l: Int, r:Int, m:Int) {\n var al_next = l\n var am_next = m + 1\n for (i <- l to r)\n if (am_next > r || (al_next <= m && a(al_next) < a(am_next))) {\n b(i) = a(al_next)\n al_next += 1\n }\n else {\n b(i) = a(am_next)\n am_next += 1\n }\n }\n def mergeSortAct(a: Array[Long], b: Array[Long], l: Int, r: Int) {\n if (l >= r)\n return\n val m = (l + r) / 2\n mergeSortAct(a, b, l, m)\n mergeSortAct(a, b, m+1, r)\n merge(a, b, l, r, m)\n //Array.copy(b, l, a, l, r - l + 1)\n for (i <- l to r)\n a(i) = b(i)\n }\n def mergeSort(a: Array[Long]) {\n mergeSortAct(a, Array.ofDim[Long](a.length), 0, a.length - 1)\n }\n def readLineOfNumsL(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readLineOfNumsI(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def main(args: Array[String]) {\n val Array(n, q) = readLineOfNumsI()\n val array = readLineOfNumsL()\n val d = Array.ofDim[Int](n+1)\n for (i <- 1 to q) {\n val Array(l, r) = readLineOfNumsI()\n d(l-1) += 1\n d(r) -= 1\n }\n val b = Array.ofDim[Long](n)\n var count = 0\n for (i <- 0 to (n-1)) {\n count += d(i)\n b(i) = count\n }\n scalaMergeSortPerform(array)\n scalaMergeSortPerform(b)\n var result = 0L\n for (i <- 0 to (n-1))\n result += array(i) * b(i)\n println(result)\n }\n}\n"}, {"source_code": "import scala.util.Sorting\n//import java.util.Arrays\nobject Main {\n def merge(a: Array[Long], b: Array[Long], l: Int, r:Int, m:Int) {\n var al_next = l\n var am_next = m + 1\n for (i <- l to r)\n if (am_next > r || (al_next <= m && a(al_next) < a(am_next))) {\n b(i) = a(al_next)\n al_next += 1\n }\n else {\n b(i) = a(am_next)\n am_next += 1\n }\n }\n def mergeSortAct(a: Array[Long], b: Array[Long], l: Int, r: Int) {\n if (l >= r)\n return\n val m = (l + r) / 2\n mergeSortAct(a, b, l, m)\n mergeSortAct(a, b, m+1, r)\n merge(a, b, l, r, m)\n //Array.copy(b, l, a, l, r - l + 1)\n for (i <- l to r)\n a(i) = b(i)\n }\n def mergeSort(a: Array[Long]) {\n mergeSortAct(a, Array.ofDim[Long](a.length), 0, a.length - 1)\n }\n def readLineOfNumsL(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readLineOfNumsI(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def main(args: Array[String]) {\n val Array(n, q) = readLineOfNumsI()\n val array = readLineOfNumsL()\n val d = Array.ofDim[Int](n+1)\n for (i <- 1 to q) {\n val Array(l, r) = readLineOfNumsI()\n d(l-1) += 1\n d(r) -= 1\n }\n val b = Array.ofDim[Long](n)\n var count = 0\n for (i <- 0 to (n-1)) {\n count += d(i)\n b(i) = count\n }\n /*Arrays.sort(array)\n Arrays.sort(b)*/\n /*Sorting.stableSort(array)\n Sorting.stableSort(b)*/\n mergeSort(array)\n mergeSort(b)\n var result = 0L\n for (i <- 0 to (n-1))\n result += array(i) * b(i)\n println(result)\n }\n}\n"}, {"source_code": "//import scala.util.Sorting\n//import java.util.Arrays\nobject Main {\n\n private def scalaMergeSort(a: Array[Long], lo: Int, hi: Int, scratch: Array[Long], f: (Long,Long) => Boolean) {\n if (lo < hi) {\n val mid = (lo+hi) / 2\n scalaMergeSort(a, lo, mid, scratch, f)\n scalaMergeSort(a, mid+1, hi, scratch, f)\n var k, t_lo = lo\n var t_hi = mid + 1\n while (k <= hi) {\n if ((t_lo <= mid) && ((t_hi > hi) || (a(t_lo) >= a(t_hi)))) {\n scratch(k) = a(t_lo)\n t_lo += 1\n } else {\n scratch(k) = a(t_hi)\n t_hi += 1\n }\n k += 1\n }\n k = lo\n while (k <= hi) {\n a(k) = scratch(k)\n k += 1\n }\n }\n }\n\n def scalaMergeSortPerform(a: Array[Long]) {\n scalaMergeSort(a, 0, a.length - 1, Array.ofDim[Long](a.length), (a:Long, b:Long) => a < b)\n }\n\n def merge(a: Array[Long], b: Array[Long], l: Int, r:Int, m:Int) {\n var al_next = l\n var am_next = m + 1\n for (i <- l to r)\n if (am_next > r || (al_next <= m && a(al_next) < a(am_next))) {\n b(i) = a(al_next)\n al_next += 1\n }\n else {\n b(i) = a(am_next)\n am_next += 1\n }\n }\n def mergeSortAct(a: Array[Long], b: Array[Long], l: Int, r: Int) {\n if (l >= r)\n return\n val m = (l + r) / 2\n mergeSortAct(a, b, l, m)\n mergeSortAct(a, b, m+1, r)\n merge(a, b, l, r, m)\n //Array.copy(b, l, a, l, r - l + 1)\n for (i <- l to r)\n a(i) = b(i)\n }\n def mergeSort(a: Array[Long]) {\n mergeSortAct(a, Array.ofDim[Long](a.length), 0, a.length - 1)\n }\n def readLineOfNumsL(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readLineOfNumsI(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def main(args: Array[String]) {\n val Array(n, q) = readLineOfNumsI()\n val array = readLineOfNumsL()\n val d = Array.ofDim[Int](n+1)\n for (i <- 1 to q) {\n val Array(l, r) = readLineOfNumsI()\n d(l-1) += 1\n d(r) -= 1\n }\n val b = Array.ofDim[Long](n)\n var count = 0\n for (i <- 0 to (n-1)) {\n count += d(i)\n b(i) = count\n }\n /*Arrays.sort(array)\n Arrays.sort(b)*/\n scalaMergeSortPerform(array)\n scalaMergeSortPerform(b)\n /*mergeSort(array)\n mergeSort(b)*/\n var result = 0L\n for (i <- 0 to (n-1))\n result += array(i) * b(i)\n println(result)\n }\n}\n"}, {"source_code": "//import scala.util.Sorting\nimport java.util.Arrays\nobject Main {\n def merge(a: Array[Long], b: Array[Long], l: Int, r:Int, m:Int) {\n var al_next = l\n var am_next = m + 1\n for (i <- l to r)\n if (am_next > r || (al_next <= m && a(al_next) < a(am_next))) {\n b(i) = a(al_next)\n al_next += 1\n }\n else {\n b(i) = a(am_next)\n am_next += 1\n }\n }\n def mergeSortAct(a: Array[Long], b: Array[Long], l: Int, r: Int) {\n if (l >= r)\n return\n val m = (l + r) / 2\n mergeSortAct(a, b, l, m)\n mergeSortAct(a, b, m+1, r)\n merge(a, b, l, r, m)\n Array.copy(b, l, a, l, r - l + 1)\n }\n def mergeSort(a: Array[Long]) {\n mergeSortAct(a, Array.ofDim[Long](a.length), 0, a.length - 1)\n }\n def readLineOfNumsL(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readLineOfNumsI(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def main(args: Array[String]) {\n val Array(n, q) = readLineOfNumsI()\n val array = readLineOfNumsL()\n val d = Array.ofDim[Int](n+1)\n for (i <- 1 to q) {\n val Array(l, r) = readLineOfNumsI()\n d(l-1) += 1\n d(r) -= 1\n }\n val b = Array.ofDim[Long](n)\n var count = 0\n for (i <- 0 to (n-1)) {\n count += d(i)\n b(i) = count\n }\n Arrays.sort(array)\n Arrays.sort(b)\n /*mergeSort(array)\n mergeSort(b)*/\n var result = 0L\n for (i <- 0 to (n-1))\n result += array(i) * b(i)\n println(result)\n }\n}\n"}, {"source_code": "import scala.util.Sorting\nobject Main {\n def merge(a: Array[Long], b: Array[Long], l: Int, r:Int, m:Int) {\n var al_next = l\n var am_next = m + 1\n for (i <- l to r)\n if (am_next > r || (al_next <= m && a(al_next) < a(am_next))) {\n b(i) = a(al_next)\n al_next += 1\n }\n else {\n b(i) = a(am_next)\n am_next += 1\n }\n }\n def mergeSortAct(a: Array[Long], b: Array[Long], l: Int, r: Int) {\n if (l >= r)\n return\n val m = (l + r) / 2\n mergeSortAct(a, b, l, m)\n mergeSortAct(a, b, m+1, r)\n merge(a, b, l, r, m)\n Array.copy(b, l, a, l, r - l + 1)\n }\n def mergeSort(a: Array[Long]) {\n mergeSortAct(a, Array.ofDim[Long](a.length), 0, a.length - 1)\n }\n def readLineOfNumsL(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readLineOfNumsI(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def main(args: Array[String]) {\n val Array(n, q) = readLineOfNumsI()\n val array = readLineOfNumsL()\n val d = Array.ofDim[Int](n+1)\n for (i <- 1 to q) {\n val Array(l, r) = readLineOfNumsI()\n d(l-1) += 1\n d(r) -= 1\n }\n val b = Array.ofDim[Long](n)\n var count = 0\n for (i <- 0 to (n-1)) {\n count += d(i)\n b(i) = count\n }\n mergeSort(array)\n mergeSort(b)\n var result = 0L\n for (i <- 0 to (n-1))\n result += array(i) * b(i)\n println(result)\n }\n}\n"}, {"source_code": "import scala.util.Sorting\nobject Main {\n def readLineOfNumsL = readLine split ' ' map(_.toLong) toList\n def readLineOfNumsI = readLine split ' ' map(_.toInt) toList\n def main(args: Array[String]) = {\n val List(n, q) = readLineOfNumsI\n val array = readLineOfNumsL\n val d = Array.ofDim[Int](n+1)\n for (i <- 1 to q) {\n val List(l, r) = readLineOfNumsI\n d(l-1) += 1\n d(r) -= 1\n }\n val b = d.tail.view.init.scanLeft(d.head) (_ + _)\n println((array.sorted, b.sorted).zipped map (_ * _) sum)\n }\n}\n"}, {"source_code": "import scala.util.Sorting\nobject Main {\n\n def readLineOfNumsL(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readLineOfNumsI(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def main(args: Array[String]) = {\n val Array(n, q) = readLineOfNumsI()\n val array = readLineOfNumsL()\n val d = Array.ofDim[Int](n+1)\n for (i <- 1 to q) {\n val Array(l, r) = readLineOfNumsI()\n d(l-1) += 1\n d(r) -= 1\n }\n val b = Array.ofDim[Int](n)\n var count = 0\n for (i <- 0 to (n-1)) {\n count += d(i)\n b(i) = count\n }\n println((array.sorted, b.sorted).zipped map (_ * _) sum)\n }\n}\n\n"}, {"source_code": "import scala.util.Sorting\nobject Main {\n\n def readLineOfNumsL(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readLineOfNumsI(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def main(args: Array[String]) = {\n val Array(n, q) = readLineOfNumsI()\n val array = readLineOfNumsL()\n val d = Array.ofDim[Int](n+1)\n for (i <- 1 to q) {\n val Array(l, r) = readLineOfNumsI()\n d(l-1) += 1\n d(r) -= 1\n }\n // val b = d.tail.scanLeft(d.head) (_ + _)\n \n val b = Array.ofDim[Int](n)\n var count = 0\n for (i <- 0 to (n-1)) {\n count += d(i)\n b(i) = count\n }\n println((array.sorted, b.sorted).zipped map (_ * _) sum)\n }\n}\n"}, {"source_code": "import scala.util.Sorting\nobject Main {\n\n def readLineOfNumsL(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readLineOfNumsI(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def main(args: Array[String]) = {\n val Array(n, q) = readLineOfNumsI()\n val array = readLineOfNumsL()\n val d = Array.ofDim[Int](n+1)\n for (i <- 1 to q) {\n val Array(l, r) = readLineOfNumsI()\n d(l-1) += 1\n d(r) -= 1\n }\n val b = d.tail.view.init.scanLeft(d.head) (_ + _)\n println((array.sorted, b.sorted).zipped map (_ * _) sum)\n }\n}\n"}, {"source_code": "import scala.util.Sorting\nobject Main {\n\n def readLineOfNumsL(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readLineOfNumsI(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def main(args: Array[String]) = {\n val Array(n, q) = readLineOfNumsI()\n val array = readLineOfNumsL()\n val d = Array.ofDim[Int](n+1)\n for (i <- 1 to q) {\n val Array(l, r) = readLineOfNumsI()\n d(l-1) += 1\n d(r) -= 1\n }\n val b = Array.ofDim[Int](n)\n var count = 0\n for (i <- 0 to (n-1)) {\n count += d(i)\n b(i) = count\n }\n val sortedArray = array.sorted;\n val sortedB = b.sorted;\n var result = 0L\n for (i <- 0 to (n-1))\n result += sortedArray(i) * sortedB(i)\n println(result)\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn\n\n/**\n * @author traff\n */\n\nobject Main extends App {\n val Array(n, q) = StdIn.readLine().split(\" \").map(_.toInt)\n\n val a: List[Int] = StdIn.readLine().split(\" \").map(_.toInt).sortWith(_ > _).toList\n\n val d = Array.fill[Int](n+1)(0)\n\n def lsb(i: Int): Int = i & (-i)\n\n def update(i: Int, c: Int): Unit = {\n var ii = i\n\n while (ii <= n) {\n d(ii) += c\n ii += lsb(ii)\n }\n }\n\n def range_inc(l: Int, r: Int): Unit = {\n update(l, 1)\n update(r+1, -1)\n }\n\n def query(i: Int): Int = {\n var ii = i\n var sum = 0\n\n while (ii> 0) {\n sum+=d(ii)\n ii -= lsb(ii)\n }\n sum\n }\n\n for (i <- 1 to q) {\n val Array(l, r) = StdIn.readLine().split(\" \").map(_.toInt)\n\n range_inc(l, r)\n }\n\n println((1 to n).map(i => query(i)).sortWith(_ > _).zip(a).foldLeft[Long](0)((r: Long, t) => r + t._1.toLong * t._2))\n\n\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\n/**\n * @author traff\n */\n\nobject Main extends App {\n val Array(n, q) = StdIn.readLine().split(\" \").map(_.toInt)\n\n val a: List[Int] = StdIn.readLine().split(\" \").map(_.toInt).sortWith(_ > _).toList\n\n val d = Array.fill[Int](n+1)(0)\n\n def lsb(i: Int): Int = i & (-i)\n\n def update(i: Int, c: Int): Unit = {\n var ii = i\n\n while (ii <= n) {\n d(ii) += c\n ii += lsb(ii)\n }\n }\n\n def range_inc(l: Int, r: Int): Unit = {\n update(l, 1)\n update(r+1, -1)\n }\n\n def query(i: Int): Int = {\n var ii = i\n var sum = 0\n\n while (ii> 0) {\n sum+=d(ii)\n ii -= lsb(ii)\n }\n sum\n }\n\n for (i <- 1 to q) {\n val Array(l, r) = StdIn.readLine().split(\" \").map(_.toInt)\n\n range_inc(l, r)\n }\n\n println((1 to n).map(i => query(i)).sortWith(_ > _).zip(a).foldLeft(0)((r, t) => r + t._1 * t._2))\n\n\n}"}, {"source_code": "import scala.io.StdIn\n\n/**\n * @author traff\n */\n\nobject Main extends App {\n val Array(n, q) = StdIn.readLine().split(\" \").map(_.toInt)\n\n val a: List[Int] = StdIn.readLine().split(\" \").map(_.toInt).sortWith(_ > _).toList\n\n val d = Array.fill[Int](n+1)(0)\n\n def lsb(i: Int): Int = i & (-i)\n\n def update(i: Int, c: Int): Unit = {\n var ii = i\n\n while (ii <= n) {\n d(ii) += c\n ii += lsb(ii)\n }\n }\n\n def range_inc(l: Int, r: Int): Unit = {\n update(l, 1)\n update(r+1, -1)\n }\n\n def query(i: Int): Int = {\n var ii = i\n var sum = 0\n\n while (ii> 0) {\n sum+=d(ii)\n ii -= lsb(ii)\n }\n sum\n }\n\n for (i <- 1 to q) {\n val Array(l, r) = StdIn.readLine().split(\" \").map(_.toInt)\n\n range_inc(l, r)\n }\n\n println((1 to n).map(i => query(i)).sortWith(_ > _).zip(a).foldLeft[Long](0)((r: Long, t) => r + t._1 * t._2))\n\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, q) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt).sorted\n val frequency = Array.ofDim[Int](n)\n (1 to q).foreach { _ =>\n val Array(l, r) = in.next().split(' ').map(_.toInt - 1)\n frequency(l) += 1\n if (r != n - 1)\n frequency(r + 1) -= 1\n }\n val sortedFreq = frequency.foldLeft((List.empty[Int], 0)) {\n case((list, soFar), i) => (soFar + i :: list, soFar + i)\n }._1.sorted\n println(sortedFreq.zip(data).foldLeft(0l) {\n case(acc, (count, value)) => acc + count * value\n })\n\n}\n"}, {"source_code": "import scala.util.Sorting\nobject Main {\n def merge(a: Array[Long], b: Array[Long], l: Int, r:Int, m:Int) {\n var al_next = l\n var am_next = m + 1\n for (i <- l to r)\n if (am_next > r || a(al_next) < a(am_next)) {\n b(i) = a(al_next)\n al_next += 1\n }\n else {\n b(i) = a(am_next)\n am_next += 1\n }\n }\n def mergeSortAct(a: Array[Long], b: Array[Long], l: Int, r: Int) {\n if (l >= r)\n return\n val m = (l + r) / 2\n mergeSortAct(a, b, l, m)\n mergeSortAct(a, b, m+1, r)\n merge(a, b, l, r, m)\n Array.copy(b, l, a, l, r - l + 1)\n }\n def mergeSort(a: Array[Long]) {\n mergeSortAct(a, Array.ofDim[Long](a.length), 0, a.length - 1)\n }\n def readLineOfNumsL(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readLineOfNumsI(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def main(args: Array[String]) {\n val Array(n, q) = readLineOfNumsI()\n val array = readLineOfNumsL()\n val d = Array.ofDim[Int](n+1)\n for (i <- 1 to q) {\n val Array(l, r) = readLineOfNumsI()\n d(l-1) += 1\n d(r) -= 1\n }\n val b = Array.ofDim[Long](n)\n var count = 0\n for (i <- 0 to (n-1)) {\n count += d(i)\n b(i) = count\n }\n mergeSort(array)\n mergeSort(b)\n var result = 0L\n for (i <- 0 to (n-1))\n result += array(i) * b(i)\n println(result)\n }\n}\n"}, {"source_code": "import scala.util.Sorting\nobject Main {\n \n def readLineOfNumsL(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readLineOfNumsI(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def main(args: Array[String]) = {\n val Array(n, q) = readLineOfNumsI()\n val array = readLineOfNumsI()\n val d = Array.ofDim[Int](n+1)\n for (i <- 1 to q) {\n val Array(l, r) = readLineOfNumsI()\n d(l-1) += 1\n d(r) -= 1\n }\n val b = Array.ofDim[Int](n)\n var count = 0\n for (i <- 0 to (n-1)) {\n count += d(i)\n b(i) = count\n }\n Sorting.quickSort(array)\n Sorting.quickSort(b)\n var result = 0\n for (i <- 0 to (n-1))\n result += array(i) * b(i)\n println(result)\n }\n}\n"}, {"source_code": "import scala.util.Sorting\nobject Main {\n\n def readLineOfNumsL(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readLineOfNumsI(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def main(args: Array[String]) = {\n val Array(n, q) = readLineOfNumsI()\n val array = readLineOfNumsL()\n val d = Array.ofDim[Int](n+1)\n for (i <- 1 to q) {\n val Array(l, r) = readLineOfNumsI()\n d(l-1) += 1\n d(r) -= 1\n }\n val b = d.scanLeft(0)(_ + _)\n println((array.sorted, b.sorted).zipped map (_ * _) sum)\n }\n}\n"}, {"source_code": "import scala.util.Sorting\nobject Main {\n\n def readLineOfNumsL(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readLineOfNumsI(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def main(args: Array[String]) = {\n val Array(n, q) = readLineOfNumsI()\n val array = readLineOfNumsL()\n val d = Array.ofDim[Int](n+1)\n for (i <- 1 to q) {\n val Array(l, r) = readLineOfNumsI()\n d(l-1) += 1\n d(r) -= 1\n }\n val b = Array.ofDim[Int](n)\n var count = 0\n for (i <- 0 to (n-1)) {\n count += d(i)\n b(i) = count\n }\n val sortedArray = array.sorted;\n val sortedB = b.sorted;\n var result = 0L\n for (i <- 0 to (n-1))\n result += array(i) * b(i)\n println(result)\n }\n}"}, {"source_code": "import scala.util.Sorting\nobject Main {\n\n def readLineOfNumsL(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readLineOfNumsI(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def main(args: Array[String]) = {\n val Array(n, q) = readLineOfNumsI()\n val array = readLineOfNumsL()\n val d = Array.ofDim[Int](n+1)\n for (i <- 1 to q) {\n val Array(l, r) = readLineOfNumsI()\n d(l-1) += 1\n d(r) -= 1\n }\n val b = d.tail.scanLeft(d.head) (_ + _)\n println((array.sorted, b.sorted).zipped map (_ * _) sum)\n }\n}\n"}, {"source_code": "import scala.util.Sorting\nobject Main {\n\n def readLineOfNumsL(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readLineOfNumsI(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def main(args: Array[String]) = {\n val Array(n, q) = readLineOfNumsI()\n val array = readLineOfNumsL()\n val d = Array.ofDim[Int](n+1)\n for (i <- 1 to q) {\n val Array(l, r) = readLineOfNumsI()\n d(l-1) += 1\n d(r) -= 1\n }\n val b = d.tail.scanLeft(d.head) (_ + _)\n println((array.sorted, b.sorted).zipped.map(_ * _).sum)\n }\n}\n"}], "src_uid": "926ec28d1c80e7cbe0bb6d209e664f48"} {"source_code": "import scala.collection.mutable\n\nobject C {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextLongs(n)\n\n val resBuilder = new mutable.ArrayBuilder.ofLong\n var prev = 0L\n for (a <- as) {\n if (java.lang.Long.signum(a) != java.lang.Long.signum(prev)) {\n if (prev != 0) {\n resBuilder += prev\n }\n prev = a\n } else if (a > prev) {\n prev = a\n }\n }\n if (prev != 0) {\n resBuilder += prev\n }\n\n out.println(resBuilder.result().sum)\n }\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject SolutionC extends App {\n val T = StdIn.readInt()\n for (t <- 1 to T) {\n val n = StdIn.readInt()\n val array = StdIn.readLine().split(' ').map{_.toInt}\n var prev = array(0)\n var currentMax = prev\n var result = 0L\n for (idx <- 1 until n) {\n val next = array(idx)\n if (prev < 0) {\n if (next < 0) {\n currentMax = Math.max(currentMax, next)\n } else {\n result += currentMax\n currentMax = next\n }\n } else {\n if (next > 0) {\n currentMax = Math.max(currentMax, next)\n } else {\n result += currentMax\n currentMax = next\n }\n }\n prev = next\n }\n result += currentMax\n println(result)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject C_1343 extends App {\n var scanner = new Scanner(System.in)\n val t = scanner.nextInt()\n\n (0 until t).foreach { _ =>\n val n = scanner.nextInt()\n\n val a0 = scanner.nextInt()\n var sign = a0 > 0\n var max = a0\n var sum = 0L\n\n var index = 1\n while (index < n) {\n val newA = scanner.nextInt()\n val newSign = newA > 0\n if (newSign != sign) {\n sign = newSign\n sum += max\n max = newA\n }\n else if (newA > max) {\n max = newA\n }\n\n index += 1\n }\n sum += max\n\n println(sum)\n }\n}"}], "negative_code": [], "src_uid": "39480cdf697fc9743dc9665f989077d7"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline private final def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n var i = from\n while(i <= to) { f(i); i += 1 }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n, m = ni()\n val g = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer())\n val degIn, degOut = Array.ofDim[Int](n)\n\n def addEdge(from: Int, to: Int): Unit = {\n g(from) += to\n degIn(from) += 1\n degOut(to) += 1\n }\n\n REP(m) { _ =>\n val a, b = ni() - 1\n // bragされる側からの有向グラフ\n if (a < b) addEdge(a, b) else addEdge(b, a)\n }\n\n var ans = 0L\n REP(n) { v =>\n ans += degIn(v).toLong * degOut(v)\n }\n out.println(ans)\n REP(ni()) { _ =>\n val v = ni() - 1\n val prev = degOut(v).toLong * degIn(v)\n degOut(v) += degIn(v)\n degIn(v) = 0\n ans -= prev\n var i = 0\n while (i < g(v).length) {\n val u = g(v)(i)\n g(u) += v\n val prev = degIn(u).toLong * degOut(u)\n degIn(u) += 1\n degOut(u) -= 1\n val cur = degIn(u).toLong * degOut(u)\n ans += cur - prev\n i += 1\n }\n g(v).clear()\n out.println(ans)\n }\n }\n}", "positive_code": [{"source_code": "object Main {\n\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj) {\n f\n }\n }\n\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj) {\n debug(as.map(x => if (x) \"1\" else \"0\").mkString)\n }\n\n @inline private final def debug(as: Array[Int]): Unit = if (!oj) {\n debug(as.mkString(\" \"))\n }\n\n @inline private final def debug(as: Array[Long]): Unit = if (!oj) {\n debug(as.mkString(\" \"))\n }\n\n @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj) {\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj) {\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n\n @inline private final def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i); i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i); i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n var i = from\n while (i <= to) {\n f(i); i += 1\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n\n import java.util.Arrays.sort\n\n import Main._\n import sc._\n\n import scala.collection.mutable\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n, m = ni()\n val g = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer())\n val degIn, degOut = Array.ofDim[Long](n)\n\n def addEdge(from: Int, to: Int): Unit = {\n g(from) += to\n degIn(from) += 1\n degOut(to) += 1\n }\n\n REP(m) { _ =>\n val a, b = ni() - 1\n // bragされる側からの有向グラフ\n if (a < b) addEdge(a, b) else addEdge(b, a)\n }\n\n var ans = 0L\n REP(n) { v =>\n ans += degIn(v) * degOut(v)\n }\n out.println(ans)\n REP(ni()) { _ =>\n val v = ni() - 1\n val prev = degOut(v) * degIn(v)\n degOut(v) += degIn(v)\n degIn(v) = 0\n ans -= prev\n var i = 0\n val len = g(v).length\n while (i < len) {\n val u = g(v)(i)\n g(u) += v\n val prev = degIn(u) * degOut(u)\n degIn(u) += 1\n degOut(u) -= 1\n val cur = degIn(u) * degOut(u)\n ans += cur - prev\n i += 1\n }\n g(v).clear()\n out.println(ans)\n }\n }\n}"}, {"source_code": "object Main {\n\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj) {\n f\n }\n }\n\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj) {\n debug(as.map(x => if (x) \"1\" else \"0\").mkString)\n }\n\n @inline private final def debug(as: Array[Int]): Unit = if (!oj) {\n debug(as.mkString(\" \"))\n }\n\n @inline private final def debug(as: Array[Long]): Unit = if (!oj) {\n debug(as.mkString(\" \"))\n }\n\n @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj) {\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj) {\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n\n @inline private final def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i); i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i); i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n var i = from\n while (i <= to) {\n f(i); i += 1\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n\n import java.util.Arrays.sort\n\n import Main._\n import sc._\n\n import scala.collection.mutable\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n, m = ni()\n val g = Array.fill[ArrayBuffer[Integer]](n)(ArrayBuffer())\n val degIn, degOut = Array.ofDim[Long](n)\n\n def addEdge(from: Int, to: Int): Unit = {\n g(from) += to\n degIn(from) += 1\n degOut(to) += 1\n }\n\n REP(m) { _ =>\n val a, b = ni() - 1\n // bragされる側からの有向グラフ\n if (a < b) addEdge(a, b) else addEdge(b, a)\n }\n\n var ans = 0L\n REP(n) { v =>\n ans += degIn(v) * degOut(v)\n }\n out.println(ans)\n REP(ni()) { _ =>\n val v = ni() - 1\n val prev = degOut(v) * degIn(v)\n degOut(v) += degIn(v)\n degIn(v) = 0\n ans -= prev\n val vInt: Integer = v // boxing対策\n var i = 0\n while (i < g(v).length) {\n val u = g(v)(i).intValue()\n g(u) += vInt\n val prev = degIn(u) * degOut(u)\n degIn(u) += 1\n degOut(u) -= 1\n val cur = degIn(u) * degOut(u)\n ans += cur - prev\n i += 1\n }\n g(v).clear()\n out.println(ans)\n }\n }\n}"}], "negative_code": [], "src_uid": "5d5a76f6e4ba4cba175c3447e76c29cd"} {"source_code": "import java.util.Scanner\nimport java.util.Arrays\n\nobject Solution {\n def main(args: Array[String]) = {\n\tval in = new Scanner(System.in)\n\tval n = in.nextInt()\n\tval m = in.nextInt()\n\tval b: Array[Array[Int]] = new Array(n)\n\tvar i = 0\n\tfor (i <- 0 until n) {\n\t b(i) = new Array(m)\n\t var j = 0\n\t for (j <- 0 until m)\n\t\tb(i)(j) = in.nextInt()\n\t}\n\tval a: Array[Array[Int]] = new Array(n)\n\tfor (i <- 0 until n) {\n\t a(i) = new Array(m)\n\t Arrays.fill(a(i), 1)\n\t}\n\tfor (i <- 0 until n) {\n\t var j = 0\n\t for (j <- 0 until m) {\n\t\tif (b(i)(j) == 0) {\n\t\t var k = 0\n\t\t for (k <- 0 until m)\n\t\t\ta(i)(k) = 0\n\t\t for (k <- 0 until n)\n\t\t\ta(k)(j) = 0\n\t\t}\n\t }\n\t}\n\tvar ok = true\n\tfor (i <- 0 until n) {\n\tvar j = 0\n\t for (j <- 0 until m) {\n\t\tvar curr = 0\n\t\tvar k = 0\n\t\tfor (k <- 0 until m)\n\t\t curr |= a(i)(k)\n\t\tfor (k <- 0 until n)\n\t\t curr |= a(k)(j)\n\t\tif (curr != b(i)(j))\n\t\t ok = false\n\t }\n\t}\n\tif (ok) {\n\t println(\"YES\")\n\t for (i <- 0 until n) {\n\t\tvar j = 0\n\t\tfor (j <- 0 until m)\n\t\t print(a(i)(j) + \" \")\n\t\tprintln()\n\t }\n\t} else {\n\t println(\"NO\")\n\t}\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject ProblemB {\n def main(args: Array[String]) {\n val Array(m, n) = readLine split \" \" map (_.toInt)\n var B = new Array[Array[Int]](m)\n for (i <- 0 until m) {\n B(i) = readLine split \" \" map (_.toInt)\n }\n\n var A = Array.tabulate(m, n)((x, y) => 1)\n for (i <- 0 until m) {\n for (j <- 0 until n) {\n if (B(i)(j) == 0) {\n for (k <- 0 until m) A(k)(j) = 0\n for (k <- 0 until n) A(i)(k) = 0\n }\n }\n }\n\n val rows = for (i <- 0 until m) yield { A(i) exists (_ == 1) }\n val cols = for (j <- 0 until n) yield {\n (for (i <- 0 until m) yield A(i)(j)) exists (_ == 1)\n }\n \n var win = true\n for (i <- 0 until m) {\n for (j <- 0 until n) {\n if ((B(i)(j) == 1) != (rows(i) || cols(j)))\n win = false\n }\n }\n\n if (!win) {\n println(\"NO\")\n } else {\n println(\"YES\")\n for (i <- 0 until m) {\n println(A(i) mkString \" \")\n }\n }\n \n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(m, n) = in.next().split(' ').map(_.toInt)\n val sourceMatrix = Array.ofDim[Int](m, n)\n val emptyRow = Array.ofDim[Boolean](m)\n val emptyCol = Array.ofDim[Boolean](n)\n (0 until m).foreach{i =>\n val row = in.next().split(' ').map(_.toInt)\n sourceMatrix(i) = row\n val index = row.indexOf(0)\n if (index != -1) {\n emptyRow(i) = true\n (index until n).foreach { i => emptyCol(i) ||= row(i) == 0 }\n }\n }\n\n val res = (0 until m).forall {i =>\n (0 until n).forall { j =>\n val cell = emptyCol(j) && emptyRow(i)\n if (cell)\n sourceMatrix(i)(j) == 0\n else\n sourceMatrix(i)(j) == 1\n }\n }\n val fillRows = emptyRow.count(_ == false)\n val fillCols = emptyCol.count(_ == false)\n\n if (res && (fillRows == fillCols || (fillRows != 0 && fillCols != 0))) {\n println(\"YES\")\n println((0 until m).map {i =>\n (0 until n).map { j =>\n if (emptyRow(i) || emptyCol(j)) 0 else 1\n }.mkString(\" \")\n }.mkString(\"\\n\"))\n } else\n println(\"NO\")\n\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(m, n) = in.next().split(' ').map(_.toInt)\n val sourceMatrix = Array.ofDim[Int](m, n)\n val emptyRow = Array.ofDim[Boolean](m)\n val emptyCol = Array.ofDim[Boolean](n)\n (0 until m).foreach{i =>\n val row = in.next().split(' ').map(_.toInt)\n sourceMatrix(i) = row\n val index = row.indexOf(0)\n if (index != -1) {\n emptyRow(i) = true\n (index until n).foreach { i => emptyCol(i) ||= row(i) == 0 }\n }\n }\n\n val res = (0 until m).forall {i =>\n (0 until n).forall { j =>\n (sourceMatrix(i)(j) == 1) ||\n sourceMatrix(i).contains(1) || (0 until m).exists(i => sourceMatrix(i)(j) == 1)\n }\n }\n\n if (res) {\n println(\"YES\")\n println((0 until m).map {i =>\n (0 until n).map { j =>\n if (emptyRow(i) || emptyCol(j)) 0 else 1\n }.mkString(\" \")\n }.mkString(\"\\n\"))\n } else\n println(\"NO\")\n\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(m, n) = in.next().split(' ').map(_.toInt)\n val sourceMatrix = Array.ofDim[Int](m, n)\n val emptyRow = Array.ofDim[Boolean](m)\n val emptyCol = Array.ofDim[Boolean](n)\n (0 until m).foreach{i =>\n val row = in.next().split(' ').map(_.toInt)\n sourceMatrix(i) = row\n val index = row.indexOf(0)\n if (index != -1) {\n emptyRow(i) = true\n (index until n).foreach { i => emptyCol(i) ||= row(i) == 0 }\n }\n }\n\n val res = (0 until m).forall {i =>\n (0 until n).forall { j =>\n val cell = emptyCol(j) && emptyRow(i)\n if (sourceMatrix(i)(j) == 1)\n !cell\n else\n cell\n }\n }\n\n if (res) {\n println(\"YES\")\n println((0 until m).map {i =>\n (0 until n).map { j =>\n if (emptyRow(i) || emptyCol(j)) 0 else 1\n }.mkString(\" \")\n }.mkString(\"\\n\"))\n } else\n println(\"NO\")\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject ProblemB {\n def main(args: Array[String]) {\n val Array(m, n) = readLine split \" \" map (_.toInt)\n var B = new Array[Array[Int]](m)\n for (i <- 0 until m) {\n B(i) = readLine split \" \" map (_.toInt)\n }\n \n var rows = Array.fill(m)(1)\n var cols = Array.fill(n)(1)\n for (i <- 0 until m) {\n for (j <- 0 until n) {\n if (B(i)(j) == 0) {\n rows(i) = 0\n cols(j) = 0\n }\n }\n }\n\n var win = true\n for (i <- 0 until m) {\n for (j <- 0 until n) {\n if (B(i)(j) != (rows(i) & cols(j)))\n win = false\n }\n }\n\n val row = for (j <- 0 until n) yield j\n\n if (!win) {\n println(\"NO\")\n } else {\n println(\"YES\")\n for (i <- 0 until m) {\n println(row map (cols(_) & rows(i)) mkString \" \")\n }\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject ProblemB {\n def main(args: Array[String]) {\n val Array(m, n) = readLine split \" \" map (_.toInt)\n var B = new Array[Array[Int]](m)\n for (i <- 0 until m) {\n B(i) = readLine split \" \" map (_.toInt)\n }\n \n var rows = Array.fill(m)(1)\n var cols = Array.fill(n)(1)\n for (i <- 0 until m) {\n for (j <- 0 until n) {\n if (B(i)(j) == 0) {\n rows(i) = 0\n cols(j) = 0\n }\n }\n }\n\n var win = true\n for (i <- 0 until m) {\n for (j <- 0 until n) {\n if (B(i)(j) != (rows(i) | cols(j)))\n win = false\n }\n }\n\n val row = for (j <- 0 until n) yield j\n\n if (!win) {\n println(\"NO\")\n } else {\n println(\"YES\")\n for (i <- 0 until m) {\n println(row map (cols(_) & rows(i)) mkString \" \")\n }\n }\n }\n}\n"}], "src_uid": "bacd613dc8a91cee8bef87b787e878ca"} {"source_code": "import io.StdIn.readLine\n\nobject Mahmoud extends App {\n \n val a = readLine()\n val b = readLine()\n val s = solve(a, b)\n println (s)\n \n def solve (a: String, b: String) : Int = {\n \n if (a == b) -1 else a.length.max(b.length)\n }\n}", "positive_code": [{"source_code": "object A766 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val first = read\n val second = read\n\n if(first.compareTo(second) == 0) {\n println(-1)\n } else {\n println(math.max(first.length, second.length))\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import Utils._, annotation._, collection._, util._, control._, math.Ordering.Implicits._, Searching._\n\nobject _766A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val a, b = read[String]\n val ans = if (a == b) -1 else (a.length max b.length)\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\nobject UncommonSeq extends App {\n val x = readLine\n val y = readLine\n println(if (x == y) -1 else x.length.max(y.length))\n}\n"}], "negative_code": [{"source_code": "object A766 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val first = read\n val second = read\n\n if(first.distinct.length == 1 && second.distinct.length == 1) {\n if(first.head == second.head)\n println(-1)\n else\n println(1)\n } else if(first.length == second.length) {\n println(first.length - 1)\n } else {\n println(math.max(first.length, second.length))\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object A766 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val first = read\n val second = read\n\n if(first.distinct.length == 1 && second.distinct.length == 1) {\n if(first.head == second.head)\n println(-1)\n else\n println(1)\n } else if(first.compareTo(second) == 0) {\n println(first.length - 1)\n } else {\n println(math.max(first.length, second.length))\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object A766 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val first = read\n val second = read\n\n if(first.distinct.length == 1 && second.distinct.length == 1 && first.head == second.head) {\n println(-1)\n } else if(first.compareTo(second) == 0) {\n println(first.length - 1)\n } else {\n println(math.max(first.length, second.length))\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "f288d7dc8cfcf3c414232a1b1fcdff3e"} {"source_code": "object _1605B extends CodeForcesApp {\r\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\r\n\r\n override def solve(io: IO) = io.repeat {\r\n val n = io.read[Int]\r\n val s = io.read[String].map(c => c - '0').toArray\r\n\r\n @tailrec\r\n def solve(l: Int, r: Int): Seq[Int] = {\r\n if (l < r) {\r\n if (s(r) == 1) solve(l, r-1)\r\n else if (s(l) == 0) solve(l+1, r)\r\n else {\r\n val t = s.slice(l, r+1)\r\n val ts = t.sorted\r\n for {\r\n i <- l to r if t(i - l) != ts(i - l)\r\n } yield i\r\n }\r\n } else {\r\n Nil\r\n }\r\n }\r\n\r\n val ans = solve(0, n-1).map(_ + 1)\r\n\r\n if (ans.isEmpty) {\r\n io.write(0)\r\n } else {\r\n io.writeLine(1).write(ans.length, ans.mkString(\" \"))\r\n }\r\n }\r\n\r\n implicit class IntegralExtensions[A](x: A)(implicit n: Integral[A]) {\r\n import scala.collection.immutable.NumericRange, Integral.Implicits._\r\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\r\n }\r\n}\r\n/****************************[Ignore Template Below]****************************************/\r\ntrait CodeForcesApp {\r\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\r\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\r\n def solve(io: IO): Any\r\n def main(args: Array[String]): Unit = {\r\n val io = new IO(System.in, System.out)\r\n try solve(io) finally io.close()\r\n }\r\n}\r\n/****************************[Scala Collection Utils]****************************************/\r\nobject Utils {\r\n import scala.collection.mutable\r\n\r\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\r\n\r\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\r\n\r\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\r\n\r\n val charToInt: Char => Int = Character.getNumericValue\r\n val intToChar: Int => Char = Character.forDigit(_, 10)\r\n\r\n implicit class GenericExtensions[A](a: A) {\r\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\r\n }\r\n\r\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\r\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\r\n\r\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\r\n\r\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\r\n val freqTable = t.groupBy(identity).mapValues(_.size)\r\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\r\n }\r\n }\r\n\r\n implicit class PairExtensions[A, B](p: (A, B)) {\r\n def key = p._1\r\n def value = p._2\r\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\r\n }\r\n\r\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\r\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\r\n }\r\n\r\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\r\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\r\n }\r\n\r\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\r\n def notContains(x: A): Boolean = !(s contains x)\r\n def toMutable = mutable.Set.empty[A] ++ s\r\n }\r\n\r\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\r\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\r\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\r\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\r\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\r\n }\r\n\r\n implicit class BooleanExtensions(x: Boolean) {\r\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\r\n def toEnglish = if(x) \"Yes\" else \"No\"\r\n }\r\n\r\n implicit class IntExtensions(val x: Int) extends AnyVal {\r\n @inline def isEven = x%2 == 0\r\n @inline def isOdd = x%2 == 1\r\n }\r\n\r\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\r\n\r\n def map[K] = new {\r\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\r\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\r\n override def apply(key: K) = getOrElseUpdate(key, f(key))\r\n }\r\n }\r\n\r\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\r\n\r\n def memoize[A, B](f: A => B): A => B = map[A] using f\r\n}\r\n/***********************************[Scala I/O]*********************************************/\r\nimport java.io._, java.util.StringTokenizer\r\nimport scala.collection.generic.CanBuild\r\n\r\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\r\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\r\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\r\n\r\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\r\n val printer = new PrintWriter(out, true)\r\n\r\n @inline private[this] def tokenizer() = {\r\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\r\n tokenizers.headOption\r\n }\r\n\r\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\r\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\r\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\r\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\r\n\r\n override def next() = tokenizer().get.nextToken()\r\n override def hasNext = tokenizer().nonEmpty\r\n\r\n def write(obj: Any*): this.type = writeAll(obj)\r\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\r\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\r\n def query[A: IO.Read](question: Any): A = writeLine(question).read\r\n\r\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\r\n\r\n override def flush() = printer.flush()\r\n def close() = {\r\n flush()\r\n in.close()\r\n printer.close()\r\n }\r\n}\r\nobject IO {\r\n class Read[A](val apply: IO => A) {\r\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\r\n }\r\n object Read {\r\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\r\n implicit val string : Read[String] = new Read(_.next())\r\n implicit val int : Read[Int] = string.map(_.toInt)\r\n implicit val long : Read[Long] = string.map(_.toLong)\r\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\r\n implicit val double : Read[Double] = string.map(_.toDouble)\r\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\r\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\r\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\r\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\r\n implicit val boolean : Read[Boolean] = string map {s =>\r\n s.toLowerCase match {\r\n case \"yes\" | \"true\" | \"1\" => true\r\n case \"no\" | \"false\" | \"0\" => false\r\n case _ => s.toBoolean\r\n }\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(val a: Int, val b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return a.compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n var s = readString()\n var ans = Vector[Int]()\n var cnt = 0\n for (c <- s) {\n if (c == '0')\n cnt += 1\n }\n for (i <- 1 to s.length) {\n if (i <= cnt && s(i-1) == '1')\n ans :+= i\n if (i > cnt && s(i-1) == '0')\n ans :+= i\n }\n if (ans.nonEmpty) {\n writer.println(1)\n writer.print(ans.length)\n for (idx <- ans)\n writer.print(\" \" + idx)\n writer.println()\n } else {\n writer.println(0)\n }\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "f472f9df8b4d588c67b39df6865507ca"} {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val s = readLine()\r\n\r\n val k = (s zip s.sorted).count { case (a, b) => a != b }\r\n\r\n println(k)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "//package global15\n\nobject A {\n\n /** TODO: Check! */\n private val multipleTests: Boolean = true\n\n def run(testNum: Int): Unit = {\n val n = int()\n val s = string()\n println(s.zip(s.sorted).count { case (a, b) => a != b })\n }\n\n /** Template. */\n\n private val onlineJudge = System.getProperty(\"ONLINE_JUDGE\") != null\n\n def main(args: Array[String]): Unit = {\n val t = if (multipleTests) reader.int() else 1\n (1 to t).foreach(run)\n }\n\n /** I/O */\n\n import java.io._\n import java.nio.file._\n\n private val inputFileName = \"input.txt\"\n private val reader = if (onlineJudge) FastReader.fromConsole() else FastReader.fromFile(inputFileName)\n\n private def string(): String = reader.string()\n private def int(): Int = reader.int()\n private def long(): Long = reader.long()\n private def double(): Double = reader.double()\n\n final case class FastReader(delegate: BufferedReader) extends Iterator[String] with AutoCloseable {\n import java.util.StringTokenizer\n\n def string(): String = next()\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def boolean(): Boolean = next().toBoolean\n def byte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def short(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def int(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def long(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def bigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def float(): Float = next().toFloat\n def double(): Double = next().toDouble\n def bigDecimal(): BigDecimal = BigDecimal(next())\n def lineNumber(): Int = linedDelegate.getLineNumber\n\n @inline def nextLine(): String = {\n current = None // reset the rest of current line\n delegate.readLine()\n }\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n override def next(): String = tokenizer().getOrElse(throw new RuntimeException(\"End of input\")).nextToken()\n override def close(): Unit = delegate.close()\n\n private lazy val linedDelegate = new LineNumberReader(delegate)\n private val tokenizers = Iterator.continually(delegate.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n }\n\n object FastReader {\n import scala.io.Codec\n\n def fromConsole()(implicit codec: Codec): FastReader = fromStream(System.in)\n def fromFile(fileName: String)(implicit codec: Codec): FastReader = FastReader {\n Files.newBufferedReader(Paths.get(fileName), codec.charSet)\n }\n def fromString(string: String): FastReader = FastReader(new BufferedReader(new StringReader(string)))\n def fromStream(inputStream: InputStream)(implicit codec: Codec): FastReader = FastReader {\n new BufferedReader(new InputStreamReader(inputStream, codec.charSet))\n }\n }\n}\n"}, {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val s = nextLine\n val ss = s.sorted\n var res = 0\n for (i <- 0 until s.length) {\n if (s(i) != ss(i)) res += 1\n }\n\n out.println(res)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "import scala.io.StdIn._;\r\n\r\nobject Main extends App {\r\n\r\n// def a(ignored: Int, z: Array[Long]): Long = z.zip(z.slice(1, z.length)).map(l => l._1 * l._2).max\r\n// for (_ <- 0 until readInt()) println(a(readInt(), readLine().split(\" \").map(_.toLong)))\r\n// def b(l: Long): Long = (l + 1)/10\r\n\r\n def b(i: Int, s: String): Int = s.zip(s.sorted).map(k => if (k._1 == k._2) 0 else 1).sum\r\n\r\n for (_ <- 0 until readInt()) println(b(readInt(), readLine()))\r\n}\r\n\r\n\r\n"}], "negative_code": [], "src_uid": "58ee86d4913787582ccdb54073656dc0"} {"source_code": "import io.StdIn.readLine\n\nobject A extends App {\n readLine()\n val cities = readLine().split(\"\\\\s+\").map(_.toInt).sorted\n val (minDist, count) = cities.zip(cities.tail).map { case (a, b) ⇒ b - a }.foldLeft((Int.MaxValue, 0)) {\n case ((mdist, _), dist) if dist < mdist ⇒ (dist, 1)\n case ((mdist, count), dist) if dist == mdist ⇒ (dist, count + 1)\n case (prev, _) ⇒ prev\n }\n println(s\"$minDist $count\")\n}\n", "positive_code": [{"source_code": "object Main extends App {\n scala.io.StdIn.readInt()\n val arr = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n val d = arr.zip(arr.tail).map(t => Math.abs(t._2 - t._1))\n val min = d.min\n println(min + \" \" + d.count(_ == min))\n}\n"}], "negative_code": [{"source_code": "object Main extends App {\n scala.io.StdIn.readInt()\n val arr = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val d = arr.zip(arr.tail).map(t => Math.abs(t._2 - t._1))\n println(d.min + \" \" + d.count(_ == d.min))\n}"}], "src_uid": "5f89678ae1deb1d9eaafaab55a64197f"} {"source_code": "import io.Source\nimport java.util.StringTokenizer\n\n/**\n * User: eireksten\n * Date: 7/28/12\n * Time: 10:20 AM\n */\n\nobject Runner extends App {\n\n val input = Source.fromInputStream(System.in).bufferedReader()\n var token: StringTokenizer = null\n\n def TOKEN() = {\n while (token == null || !token.hasMoreTokens)\n token = new StringTokenizer(input.readLine())\n token.nextToken()\n }\n\n def LONG() = TOKEN().toLong\n def INT() = TOKEN().toInt\n\n val n = INT()\n val wrappings = for (i <- 1 to n) yield LONG()\n val prizeCosts = for (i <- 1 to 5) yield LONG()\n\n new Solution().go(wrappings, prizeCosts)\n\n}\n\nclass Solution {\n\n def go(wrappings : IndexedSeq[Long], prizeCosts : IndexedSeq[Long]) = {\n\n var sum = 0L\n val prizes = new Array[Long](5)\n for(wrap <- wrappings) {\n sum += wrap\n for (i <- prizeCosts.length-1 to 0 by -1) {\n val count = sum / prizeCosts(i);\n prizes(i) += count\n sum -= count * prizeCosts(i);\n }\n }\n println(prizes.mkString(\" \"))\n println(sum)\n }\n\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val ls = readLine().split(\" \").map(_.toLong)\n val prices = readLine().split(\" \").map(_.toLong).zipWithIndex\n var count = Array.fill(5)(0L)\n var sum = 0L\n ls.foreach { e =>\n sum += e\n while(prices.count(_._1 <= sum) != 0) {\n val t = prices.filter(_._1 <= sum).last\n val div = (sum / t._1)\n sum -= div * t._1\n count(t._2) += div\n }\n }\n println(count.mkString(\" \"))\n println(sum)\n }\n}"}, {"source_code": "import BigInt._\nobject Main {\n def main(args: Array[String]) {\n def readArray = readLine.split(' ').map(x => BigInt(x.toInt))\n val n = readInt\n val a = readArray.toList\n val p = readArray\n var acc:Array[BigInt] = Array(0,0,0,0,0)\n \n def solve(a: List[BigInt], money: BigInt): BigInt = {\n if (a == List()) {\n println(acc.mkString(\" \"))\n return money\n }\n var m = money + a.head\n for (i <- 4 to 0 by -1) {\n val k = BigInt((m / p(i)).toInt) \n acc(i) += k\n m -= k * p(i)\n }\n solve(a.tail, m)\n }\n \n val answer = solve(a, 0)\n println(answer)\n }\n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next()\n val data = in.next().split(' ').map(_.toInt)\n val prices = in.next().split(' ').map(_.toInt)\n val count = Array.ofDim[Long](5)\n\n val l = data.foldLeft(0l) {\n case(balance, ball) =>\n var left = ball + balance\n (4 to 0 by -1).foreach {\n i => count(i) += left / prices(i)\n left %= prices(i)\n }\n left\n }\n\n println(count.mkString(\" \"))\n print(l)\n\n\n}\n"}, {"source_code": "import scala.collection.mutable\nobject Main {\n def main(args: Array[String]) {\n def readArray = readLine.split(' ').map(x => BigInt(x))\n val n = readInt\n val a = readArray.toList\n val p = readArray\n var acc = mutable.ArrayBuffer[BigInt](0,0,0,0,0)\n \n def solve(a: List[BigInt], money: BigInt): BigInt = {\n if (a == List()) {\n println(acc.mkString(\" \"))\n return money\n }\n var m = money + a.head\n for (i <- 4 to 0 by -1) {\n val k = BigInt((m / p(i)).toInt) \n acc(i) += k\n m -= k * p(i)\n }\n solve(a.tail, m)\n }\n \n val answer = solve(a, 0)\n println(answer)\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next()\n val data = in.next().split(' ').map(_.toInt)\n val prices = in.next().split(' ').map(_.toInt)\n val count = Array.ofDim[Int](5)\n\n val l = data.foldLeft(0) {\n case(balance, ball) =>\n var left = ball + balance\n (4 to 0 by -1).foreach {\n i => count(i) += left / prices(i)\n left %= prices(i)\n }\n left\n }\n\n println(count.mkString(\" \"))\n print(l)\n\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n def readArray = readLine.split(' ').map(x => x.toLong)\n val n = readInt\n val a = readArray.toList\n val p = readArray\n var acc = Array(0,0,0,0,0)\n \n def solve(a: List[Long], money: Long): Long = {\n if (a == List()) {\n println(acc.mkString(\" \"))\n return money\n }\n var m = money + a.head\n for (i <- 4 to 0 by -1) {\n val k = m / p(i) \n acc(i) += k.toInt\n m -= k * p(i)\n }\n solve(a.tail, m)\n }\n \n val answer = solve(a, 0)\n println(answer)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt\n val a = readLine.split(' ').map(x => x.toInt).toList\n val p = readLine.split(' ').map(x => x.toInt).reverse\n var acc = Array(0,0,0,0,0)\n def solve(a: List[Int], money: Int): Int = {\n if (a == List()) {\n println(acc.reverse.mkString(\" \"))\n return money\n }\n var m = money + a.head\n for (i <- 0 to 4) {\n val k = m / p(i) \n acc(i) += k\n m -= k * p(i)\n }\n solve(a.tail, m)\n }\n val answer = solve(a, 0)\n println(answer)\n }\n}\n"}, {"source_code": "import io.Source\nimport java.util.StringTokenizer\n\n/**\n * User: eireksten\n * Date: 7/28/12\n * Time: 10:20 AM\n */\n\nobject Runner extends App {\n\n val input = Source.fromInputStream(System.in).bufferedReader()\n var token: StringTokenizer = null\n\n def TOKEN() = {\n while (token == null || !token.hasMoreTokens)\n token = new StringTokenizer(input.readLine())\n token.nextToken()\n }\n\n def INT() = TOKEN().toInt\n\n val n = INT()\n val wrappings = for (i <- 1 to n) yield INT()\n val prizeCosts = for (i <- 1 to 5) yield INT()\n\n new Solution().go(wrappings, prizeCosts)\n\n}\n\nclass Solution {\n\n def go(wrappings : IndexedSeq[Int], prizeCosts : IndexedSeq[Int]) = {\n\n var sum = 0\n val prizes = new Array[Int](5)\n for(wrap <- wrappings) {\n sum += wrap\n val prize = findPrize(sum, prizeCosts)\n if (prize >= 0) {\n prizes(prize) += 1\n sum -= prizeCosts(prize);\n }\n }\n println(prizes.mkString(\" \"))\n println(sum)\n }\n\n def findPrize(sum: Int, prizeCosts : IndexedSeq[Int]) = {\n var best = -1\n for(i <- 0 until prizeCosts.length) {\n if(sum >= prizeCosts(i) && (best == -1 || prizeCosts(i) > prizeCosts(best)))\n best = i\n }\n best\n }\n\n}\n"}], "src_uid": "1ae2942b72ebb7c55359c41e141900d7"} {"source_code": "import scala.io.StdIn\n\nobject Codeforces1100C {\n\n def getOuterCircleRadius(n: Int, r: Double): Double = {\n val totalAngle = 2 * math.Pi\n val eachAngle = totalAngle / n\n val cosAngle = math.cos(eachAngle)\n val k = 2 / (1 - cosAngle)\n\n val a = 1 - k\n val b = 2 * r\n val c = r * r\n\n val d = b * b - 4 * a * c\n\n val x1 = (-b + math.sqrt(d)) / (2 * a)\n val x2 = (-b - math.sqrt(d)) / (2 * a)\n\n math.max(x1, x2)\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, r) = StdIn.readLine().trim.split(\" \")\n val R = getOuterCircleRadius(n.toInt, r.toDouble)\n println(R)\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val n, r = ni()\n val S = math.sin(Math.PI / n)\n val r2 = r * S / (1 - S)\n out.println(f\"$r2%.7f\")\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [], "src_uid": "e27cff5d681217460d5238bf7ef6a876"} {"source_code": "object Main extends App {\n val MOD: Int = 998244353\n val n: Int = scala.io.StdIn.readInt()\n def solve: Long = {\n def calc(k: Int = n, pr: Long = 1, acc: Long = 0): Long = {\n if (k == 1) (acc + n * pr) % MOD\n else {\n val npr = (pr * k) % MOD\n calc(k - 1, npr, (acc - npr + MOD) % MOD)\n }\n }\n calc()\n }\n println(solve)\n}", "positive_code": [{"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val MOD = 998244353L\n\n var prev = 1L\n var fac = 1L\n for (i <- 1 to n) {\n fac = (fac * i) % MOD\n prev = (fac + (MOD + prev - 1L) * i) % MOD\n }\n\n println(prev)\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport scala.annotation.tailrec\n\nobject Main extends App {\n val MOD: Int = 998244353\n val st = new StringTokenizer(new BufferedReader(new InputStreamReader(System.in)).readLine())\n val n: Int = Integer.parseInt(st.nextToken())\n def solve: Long = {\n @tailrec\n def calc(k: Int = n, pr: Long = 1, acc: Long = 0): Long = {\n if (k == 1) (acc + n * pr) % MOD\n else {\n val npr = (pr * k) % MOD\n calc(k - 1, npr, (acc - npr + MOD) % MOD)\n }\n }\n calc()\n }\n System.out.print(solve)\n}"}, {"source_code": "import scala.annotation.tailrec\n\nobject Main extends App {\n val MOD: Int = 998244353\n val n: Int = scala.io.StdIn.readInt()\n def solve: Long = {\n @tailrec\n def calc(k: Int = n, pr: Long = 1, acc: Long = 0): Long = {\n if (k == 1) (acc + n * pr) % MOD\n else {\n val npr = (pr * k) % MOD\n calc(k - 1, npr, (acc - npr + MOD) % MOD)\n }\n }\n calc()\n }\n println(solve)\n}"}], "negative_code": [], "src_uid": "9d4caff95ab182055f83c79dd88e599a"} {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val ds, hs = Array.ofDim[Int](m)\n \n for (i <- 0 until m) {\n val Array(d, h) = readInts(2)\n ds(i) = d\n hs(i) = h\n } \n\n var maxH = (hs.head + ds.head - 1) max (hs.last + (n - ds.last))\n \n for (i <- 1 until m) {\n val dd = ds(i) - ds(i - 1)\n val dh = hs(i) - hs(i - 1)\n if (dd < math.abs(dh)) {\n println(\"IMPOSSIBLE\")\n System.exit(0)\n }\n val ch = (hs(i) max hs(i - 1)) + (dd - math.abs(dh)) / 2\n if (ch > maxH) maxH = ch\n }\n\n println(maxH)\n}\n", "positive_code": [{"source_code": "\nimport java.io._\nimport java.util\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val records = new Array[(Int, Int)](m)\n for (i <- 0 until m ){\n records(i) = (nextInt, nextInt)\n }\n var max = records(0)._2 + records(0)._1 - 1\n for (i <- 1 until m) {\n val diff = records(i)._1 - records(i - 1)._1\n val hDiff = records(i)._2 - records(i - 1)._2\n max = Math.max(records(i)._2, max)\n if (Math.abs(hDiff) > diff) {\n out.println(\"IMPOSSIBLE\")\n return 1\n }\n val x = (diff - hDiff) / 2\n max = Math.max(records(i)._2 + x, max)\n }\n max = Math.max(records(m - 1)._2 + n - records(m - 1)._1, max)\n out.println(max)\n return 0\n }\n}\n"}, {"source_code": "\n/**\n * Created by slie742 on 9/09/2015.\n */\n\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\nimport Math.abs\nimport Math.max\nimport Math.min\n\nobject TouristNotes {\n\n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n\n def readLongs() : Array[Long] =\n readLine.split(' ').map(_.toLong)\n\n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n\n def solve(notes: List[(Int,Int)]) : Option[Int] = {\n def go(prev: (Int,Int), remNotes: List[(Int,Int)],maxHeight: Int) : Option[Int] = remNotes match {\n case Nil => Some(maxHeight)\n case (d,h) :: rest if abs(h-prev._2) > d - prev._1 =>\n None\n case (d,h) :: rest =>\n //println(s\"current = ($d,$h), maxHeight=$maxHeight, between=${(abs(h-prev._2)+ (d - prev._1))/2}\")\n val newMax = max(maxHeight, min(h,prev._2) + (abs(h-prev._2)+ (d - prev._1))/2)\n go ( (d,h), rest, newMax)\n }\n go(notes.head, notes.tail, notes.head._2+notes.head._1 - 1)\n }\n\n def main(args: Array[String]) {\n val (n,m) = readTuple()\n val notes = for {\n i <- 1 to m\n (d,h) = readTuple()\n } yield (d,h)\n solve(notes.toList) match {\n case None => println(\"IMPOSSIBLE\")\n case Some(h) => println(max(h, notes.last._2 + (n-notes.last._1) ))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "\n/**\n * Created by slie742 on 9/09/2015.\n */\n\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\nimport Math.abs\nimport Math.max\n\nobject TouristNotes {\n\n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n\n def readLongs() : Array[Long] =\n readLine.split(' ').map(_.toLong)\n\n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n\n def solve(notes: List[(Int,Int)]) : Option[Int] = {\n def go(prev: (Int,Int), remNotes: List[(Int,Int)],maxHeight: Int) : Option[Int] = remNotes match {\n case Nil => Some(maxHeight)\n case (d,h) :: rest if abs(h-prev._2) > d - prev._1 =>\n None\n case (d,h) :: rest =>\n val newMax = max(maxHeight, (abs(h-prev._2)+ (d - prev._1))/2)\n go ( (d,h), rest, newMax)\n }\n go(notes.head, notes.tail, notes.head._2+notes.head._1 - 1)\n }\n\n def main(args: Array[String]) {\n val (n,m) = readTuple()\n val notes = for {\n i <- 1 to m\n (d,h) = readTuple()\n } yield (d,h)\n solve(notes.toList) match {\n case None => println(\"IMPOSSIBLE\")\n case Some(h) => println(max(h, notes.last._2 + (n-notes.last._1) ))\n }\n }\n\n}\n"}], "src_uid": "77b5bed410d621fb56c2eaebccff5108"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(var social: Int, var cp: Int, var ind: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (social < that.social)\n return -1\n else if (social == that.social)\n return 0\n else\n return 1\n }\n }\n val rem = 1000000007\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readLong()\n var k = readInt()\n var sum = 0L\n var pow = 1L\n while (k > 0) {\n if (k % 2 == 1) {\n sum += pow\n sum %= rem\n }\n pow *= n\n pow %= rem\n k /= 2\n }\n writer.println(sum)\n }\n writer.flush()\n}\n", "positive_code": [{"source_code": "object B extends App {\r\n\r\n lazy val Mod = (1e9 + 7).toLong\r\n\r\n def kthSpecialNumber(n: Int, k: Int): Long =\r\n (0 to 31)\r\n .foldLeft((0L, 1L)) {\r\n case ((result, power), i) if (1 & (k >> i)) == 1 => ((result + power) % Mod, (n * power) % Mod)\r\n case ((result, power), _) => (result, (n * power) % Mod)\r\n }\r\n ._1\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val k = nextInt()\r\n\r\n out.println(kthSpecialNumber(n, k))\r\n }\r\n\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}, {"source_code": "object B extends App {\r\n\r\n lazy val Mod = (1e9 + 7).toLong\r\n\r\n def log2(n: Int): Int = 31 - Integer.numberOfLeadingZeros(n)\r\n\r\n def specialNumbers(n: Int, k: Int): Long = {\r\n\r\n val powers: Array[Long] = {\r\n val size = log2(k) + 1\r\n val data = Array.fill(size)(1L)\r\n (1 until size).foreach { i => data(i) = (n * data(i - 1)) % Mod }\r\n data\r\n }\r\n\r\n @annotation.tailrec\r\n def go(k: Int, result: Long): Long = k match {\r\n case 0 => result\r\n case k =>\r\n val l = log2(k)\r\n val i = k - (1 << l)\r\n\r\n go(i, (result + powers(l)) % Mod)\r\n }\r\n\r\n go(k, 0L)\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val k = nextInt()\r\n\r\n out.println(specialNumbers(n, k))\r\n }\r\n\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}], "negative_code": [], "src_uid": "2cc35227174e6a4d48e0839cba211724"} {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val k = nextInt\n val cinema = new Array[Array[Int]](k)\n val xc = Math.ceil(k / 2).toInt\n for (i <- 0 until k) {\n cinema(i) = new Array[Int](k)\n }\n for (i <- 0 until k) {\n for (j <- 0 until k) {\n cinema(i)(j) = func(xc, i, j)\n }\n }\n for (t <- 0 until n) {\n val m = nextInt\n var sum = Int.MaxValue\n var start = 0\n var row = 0\n for (i <- 0 until k) {\n var interSum = 0\n for (j <- 0 until m) {\n interSum += cinema(i)(j)\n }\n if (interSum < sum) {\n sum = interSum\n row = i\n start = 0\n }\n for (j <- m until k) {\n interSum += cinema(i)(j)\n interSum -= cinema(i)(j - m)\n if (interSum < sum) {\n sum = interSum\n row = i\n start = j - m + 1\n }\n }\n }\n if (sum < 100000) {\n// out.println(sum)\n out.println((row + 1) + \" \" + (start + 1) + \" \" + (start + m))\n for (j <- start until start + m) {\n cinema(row)(j) = 100000\n }\n } else {\n out.println(-1)\n }\n// for (i <- 0 until k) {\n// for (j <- 0 until k) {\n// out.print(cinema(i)(j) + \" \")\n// }\n// out.println\n// }\n }\n }\n\n def func(xc: Int, x: Int, y: Int) = {\n Math.abs(x - xc) + Math.abs(y - xc)\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n", "positive_code": [{"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nobject Cashier extends App {\n\n val s = new Scanner(System.in)\n\n val n = s.nextInt()\n val k = s.nextInt()\n val hall = Array.ofDim[Boolean](k + 1, k + 1)\n val trace = Array.fill[String](n)(\"-1\")\n val q = (0 until n).map(_ => s.nextInt()).toArray\n val c = (k / 2) + 1\n var cur = 0\n\n while (cur < n) {\n var best = Integer.MAX_VALUE\n var bestCoord = (0, 0)\n var x = 1\n while (x < k + 1) {\n var y = 1\n while (y < k - q(cur) + 2) {\n var fits = true\n var cnt = y\n var score = 0\n while (fits && cnt < y + q(cur)) {\n if (hall(x)(cnt)) fits = false\n score += math.abs(x - c) + math.abs(cnt - c)\n cnt += 1\n }\n if (fits && score < best) {\n best = score\n bestCoord = (x, y)\n }\n y += 1\n }\n x += 1\n }\n if (best != Integer.MAX_VALUE) {\n trace(cur) = s\"${bestCoord._1} ${bestCoord._2} ${bestCoord._2 + q(cur) - 1} \"\n var cnt = bestCoord._2\n while (cnt < bestCoord._2 + q(cur)) {\n hall(bestCoord._1)(cnt) = true\n cnt += 1\n }\n }\n cur += 1\n }\n\n print(trace.mkString(\"\\n\"))\n\n}\n"}], "negative_code": [{"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val k = nextInt\n val cinema = new Array[Array[Int]](k)\n val xc = Math.ceil(k / 2).toInt\n for (i <- 0 until k) {\n cinema(i) = new Array[Int](k)\n }\n for (i <- 0 until k) {\n for (j <- 0 until k) {\n cinema(i)(j) = func(xc, i, j)\n }\n }\n for (t <- 0 until n) {\n val m = nextInt\n var sum = Int.MaxValue\n var start = 0\n var row = 0\n for (i <- 0 until k) {\n var interSum = 0\n for (j <- 0 until m) {\n interSum += cinema(i)(j)\n }\n if (interSum < sum) {\n sum = interSum\n row = i\n start = 0\n }\n for (j <- m until k) {\n if (interSum < sum) {\n sum = interSum\n row = i\n start = j - m\n }\n interSum += cinema(i)(j)\n interSum -= cinema(i)(j - m)\n }\n }\n if (sum < 100000) {\n// out.println(sum)\n out.println((row + 1) + \" \" + (start + 1) + \" \" + (start + m))\n for (j <- start until start + m) {\n cinema(row)(j) = 100000\n }\n } else {\n out.println(-1)\n }\n// for (i <- 0 until k) {\n// for (j <- 0 until k) {\n// out.print(cinema(i)(j) + \" \")\n// }\n// out.println\n// }\n }\n }\n\n def func(xc: Int, x: Int, y: Int) = {\n Math.abs(x - xc) + Math.abs(y - xc)\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "src_uid": "2db7891a2fa4e78fd9d145304a36b9aa"} {"source_code": "object _975A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val words = io.read[Set[String]]\n val ans = words.map(_.distinct.sorted).size\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "import scala.annotation.tailrec\n\nobject Prg1 extends App {\n\n\n @tailrec\n def wordsAramic(s: List[String], presentStr:List[String]=List[String](), count:Int = 0):Int = {\n if (s.length == 0) count\n else {\n val uniqueString = s.head.sorted.distinct\n if (presentStr.contains(uniqueString))\n wordsAramic(s.tail, presentStr, count)\n else wordsAramic(s.tail, presentStr :+ uniqueString, count + 1)\n }\n }\n\n val t = scala.io.StdIn.readLine.toInt\n val listOfStr = scala.io.StdIn.readLine.split(\" \").toList\n println(wordsAramic(listOfStr))\n}\n"}, {"source_code": "\n\nobject CF975A extends App {\n import scala.io.Source\n //val src = Source.fromFile(\"data.txt\")\n val src = Source.stdin\n val lines = src.getLines\n \n def readString(): String = {\n val line = if (lines.hasNext) lines.next else null\n if (line == null) throw new RuntimeException(\"Premature end of source encountered\")\n line\n }\n \n def readStrings(): Array[String] = readString().split(\" \")\n \n readString()\n val nObj = readStrings().map(x => x.toSet).toSet.size\n println(nObj)\n}"}], "negative_code": [], "src_uid": "cf1eb164c4c970fd398ef9e98b4c07b1"} {"source_code": "object A706 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(a, b) = readInts(2)\n val Array(n) = readInts(1)\n println(Array.fill(n)(readInts(3)).map{ arr =>\n math.sqrt(math.pow(a-arr(0), 2) + math.pow(b-arr(1), 2)) / arr(2).toDouble\n }.min)\n }\n}", "positive_code": [{"source_code": "import io.StdIn._\nobject Euclid extends App {\n\n val l1 = readLine().split(\" \").map(_.toInt)\n val (a:Int, b:Int) = (l1(0), l1(1))\n\n val cars = readLine().toInt\n var i = 0\n var result:Option[Double] = None\n while(i Math.sqrt((a1 - a) * (a1 - a) + (b1 - b) * (b1 - b)) / v}.min\n println(result)\n}"}, {"source_code": "\nimport scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n var line = readLine().split(\" \")\n val x = line(0).toDouble\n val y = line(1).toDouble\n\n val n = readInt()\n\n var minTime: Double = -1\n (1 to n).foreach(i => {\n line = readLine().split(\" \")\n val ix = line(0).toDouble\n val iy = line(1).toDouble\n val iz = line(2).toDouble\n\n val time = Math.hypot(ix-x, iy-y) / iz\n if(minTime == -1){\n minTime = time\n }\n minTime = minTime.min(time)\n })\n\n println(f\"$minTime%1.10f\")\n }\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _706A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val a, b = read[Int]\n var ans = Double.MaxValue\n repeat(read[Int]) {\n val x, y, v = read[Double]\n val dist = Math.hypot(a - x, b - y)\n ans = ans min (dist/v)\n }\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Main extends App {\n import scala.io._\n val input = Source.stdin\n val inputit:Iterator[String] = input.getLines()\n var lineit:Iterator[String] = List.empty.iterator\n def rs() : String = {\n if (lineit.hasNext) lineit.next\n else { \n lineit = inputit.next.split(\" \").iterator\n rs()\n }\n }\n def ri(): Int = rs().toInt\n val a = ri ()\n val b = ri ()\n val n = ri ()\n println(\n (for (i <- 1 to n)\n yield {\n val x = ri (); \n val y = ri ();\n val v = ri ();\n math.sqrt ((x - a) * (x - a) + (y - b) * (y - b)) / v} )\n .toList.min)\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val Array(a, b) = readLine().split(\" \").map(_.toInt)\n val n = readInt()\n\n var time = Double.MaxValue\n 1 to n foreach { _ =>\n val Array(x, y, v) = readLine().split(\" \").map(_.toInt)\n val dist = Math.sqrt((x.toDouble - a) * (x - a) + (y.toDouble - b) * (y - b))\n val newTime = dist / v\n if (time > newTime) {\n time = newTime\n }\n }\n\n println(time)\n}\n"}], "negative_code": [{"source_code": "object A706 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(a, b) = readInts(2)\n val Array(n) = readInts(1)\n println(Array.fill(n)(readInts(3)).map(arr => (math.abs(a- arr(0)) + math.abs(b-arr(1))).toDouble / arr(2).toDouble).min)\n }\n}"}], "src_uid": "a74c65acd41ff9bb845062222135c60a"} {"source_code": "object _1015A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val n, m = io.read[Int]\n val intervals: Seq[(Int, Int)] = io.read(n)\n val ans = intervals.foldLeft(mutable.Set(1 to m : _*))({case (s, (i, j)) => s --= i to j})\n io.writeLine(ans.size).writeAll(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "\nobject Main {\n import java.io._\n import java.util.StringTokenizer\n \n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n \n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N, M = sc.nextInt()\n val used = Array.ofDim[Boolean](M)\n rep(N) { _ =>\n val l, r = sc.nextInt() - 1\n l to r foreach (j => used(j) = true)\n }\n\n val cnt = M - used.count(identity)\n out.println(cnt)\n out.println((used.zipWithIndex filterNot (_._1) map (_._2 + 1)).mkString(\" \"))\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "object CF501A extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n val n = in.nextInt\n val m = in.nextInt\n\n var points = (1 to m).toList\n var segments = (0 until n).map(_ => (in.nextInt, in.nextInt)).toList\n\n for (segment <- segments) {\n points = points.filter(x => x < segment._1 || x > segment._2)\n }\n\n out.println(points.length)\n out.println(points.mkString(\" \"))\n }\n\n solve\n out.flush\n out.close\n}"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject A {\n def main(args: Array[String]): Unit = {\n val List(n, m) = StdIn.readLine().split(\" \").map(_.toInt).toList\n\n var s = new mutable.HashSet[Int]()\n for (i <- 1 to n) {\n val List(b, e) = StdIn.readLine().split(\" \").map(_.toInt).toList\n for (j <- b to e) {\n s += j\n }\n }\n\n var res = new mutable.TreeSet[Int]()\n for (i <- 1 to m) {\n if (!(s contains i)) {\n res += i\n }\n }\n\n println(res.size)\n if (res.nonEmpty) {\n println(res.mkString(\" \"))\n }\n }\n}\n"}], "negative_code": [], "src_uid": "f336b622fdaf5960032268641320bb53"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(var social: Int, var cp: Int, var ind: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (social < that.social)\n return -1\n else if (social == that.social)\n return 0\n else\n return 1\n }\n }\n val rem = 1000000007\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val m = readInt()\n val mark = new Array[Boolean](n+1)\n for (i <- 1 to m){\n readInt()\n mark(readInt()) = true\n readInt()\n }\n var root = 0\n for (i <- 1 to n){\n if (!mark(i))\n root = i\n }\n for (i <- 1 to n){\n if (root != i) {\n writer.print(root)\n writer.print(\" \")\n writer.println(i)\n }\n }\n }\n writer.flush()\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.ListBuffer\r\nimport scala.io.StdIn.readLine\r\n\r\nobject OmkarAndHeavenlyTree extends App {\r\n val t = readLine.trim.toInt\r\n for(_ <- 0 until t) {\r\n val n::m::_ = readLine.split(' ').toList.map(_.toInt)\r\n val seen : ListBuffer[Int] = ListBuffer()\r\n for(_ <- 1 to m) {\r\n val _::b::_::_ = readLine.split(' ').toList.map(_.toInt)\r\n seen += b\r\n }\r\n val all = (1 to n).toSet\r\n val possible = all.diff(seen.toSet).head\r\n val nodes = (all - possible).toList\r\n for (n <- nodes) {\r\n println(n + \" \" + possible)\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "dd3ba43eb0261ccdb7269a2696a042da"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map(_ => in.next().split(' ').map(_.toInt))\n val minFirst = data.minBy(_.head).head\n val maxSecond = data.maxBy(_.last).last\n println(data.indices.find(a => data(a).head == minFirst && data(a).last == maxSecond).map(i => i + 1).getOrElse(-1))\n}", "positive_code": [{"source_code": "import java.util.Scanner\nimport scala.collection.mutable._\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n val seg = (1<<30, 0) :: List.tabulate(n)(_ => (sc.nextInt, sc.nextInt))\n val s = seg.reduce((a, b) => (math.min(a._1, b._1), math.max(a._2, b._2)))\n\n println(seg.indexOf(s))\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P242B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n val Segments = List.fill(N, 2)(sc.nextLong)\n val List(s, t) = Segments.transpose\n val S = s.min\n val T = t.max\n\n @tailrec\n def loop(i: Int, segments: List[List[Long]]): Int = segments match {\n case Nil => -1\n case List(`S`, `T`) :: xs => i\n case _ => loop(i + 1, segments.tail)\n }\n\n loop(1, Segments)\n }\n\n out.println(solve)\n out.close\n}\n \n\n\n\n\n"}, {"source_code": "\nimport java.io.InputStreamReader\nimport java.io.BufferedReader\n\n/**\n * @author pvasilyev\n * @since 23 Jun 2016\n */\nobject B242 extends App {\n\n def checkExists(pairs: IndexedSeq[(Int, Int)], min: Int, max: Int): Int = {\n for (i <- 0 until pairs.size) {\n if (pairs(i)._1 == min && pairs(i)._2 == max) {\n return i+1\n }\n }\n\n -1\n }\n\n def solve() = {\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n val n = reader.readLine().toInt\n val pairs: IndexedSeq[(Int, Int)] = (0 until n).map((i) => {\n val split = reader.readLine().split(\" \")\n (split(0).toInt, split(1).toInt)\n })\n val min: Int = pairs.minBy(_._1)._1\n val max: Int = pairs.maxBy(_._2)._2\n println(checkExists(pairs, min, max))\n }\n\n solve()\n\n}\n"}, {"source_code": "// CodeForces 242B\n\nobject BigLine extends App {\n val n = Console.readInt\n val seqpr: Seq[(Int, Int)] = for {\n i <- Range(0, n)\n val ln = (Console.readLine()).split(\" \") map (_.toInt)\n } yield (ln(0), ln(1))\n val lpr = seqpr toList\n \n def maxPr(lpr: List[(Int, Int)], idx:Int, maxP:(Int, Int, Int)):(Int, Int, Int) = lpr match {\n case Nil => maxP\n case (a,b) :: tl => {\n val (ma, mb, ii) = maxP\n if (a<=ma && mb<=b) maxPr(tl, idx+1, (a,b, idx))\n else if (ma<=a && b<=mb) maxPr(tl, idx+1, (ma, mb, ii))\n else maxPr(tl, idx+1, (Math.min(a,ma), Math.max(b, mb), -1))\n } \n }\n \n val (a,b,idx) = maxPr(lpr.tail, 2, (lpr.head._1, lpr.head._2, 1))\n println(idx)\n}"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n def readLine = reader.readLine\n\n val segs = for(_ <- 1 to readInt) yield readInts\n val foo = Array((x: Int, y: Int) => x min y, (x: Int, y: Int) => x max y)\n val seg = segs.transpose.zip(foo).map(x => x._1.reduceLeft(x._2))\n def ans = segs.indexWhere(_.sameElements(seg)) match {\n case -1 => -1\n case x => x + 1\n }\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main extends App\n{\n\tval cin=new Scanner(System.in)\n\tval n=cin.nextInt()\n\tval seg=(1<<30,0) :: List.tabulate(n)(_=>(cin.nextInt,cin.nextInt))\n\tval s=seg.reduce((a,b) => (math.min(a._1,b._1),math.max(a._2,b._2)))\n\tprintln(seg.indexOf(s))\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val n = readInt()\n val a = (1 to n).map(_ => readLine().split(\" \").map(_.toInt))\n val tr = a.transpose\n val min = tr(0).min\n val max = tr(1).max\n val t = a.zipWithIndex.find(t => t._1(0) == min && t._1(1) == max)\n t match {\n case None => println(\"-1\")\n case Some(t0) => println(t0._2 + 1)\n } \n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val res = (1 to n).foldLeft((true, 0, 0, 0)) {\n case(acc, 1) =>\n val Array(l, r) = in.next().split(' ').map(_.toInt)\n (true, l, r, 1)\n case(acc@(false, _, _, _), _) => acc\n case(acc@(true, la, ra, ri), i) =>\n val Array(l, r) = in.next().split(' ').map(_.toInt)\n if (l <= la && r >= ra)\n (true, l, r, i)\n else if (l >= la && r <= ra)\n acc\n else\n (false, l, r, i)\n }\n if (res._1)\n println(res._4)\n else\n println(-1)\n}\n"}, {"source_code": "object BigLine extends App {\n val n = Console.readInt\n val seqpr: Seq[(Int, Int)] = for {\n i <- Range(0, n)\n val ln = (Console.readLine()).split(\" \") map (_.toInt)\n } yield (ln(0), ln(1))\n val lpr = seqpr toList\n \n def maxPr(lpr: List[(Int, Int)], idx:Int, maxP:(Int, Int, Int)):(Int, Int, Int) = lpr match {\n case Nil => maxP\n case (a,b) :: tl => {\n val (ma, mb, ii) = maxP\n if (a<=ma && mb<=b) maxPr(tl, idx, (a,b, idx))\n else if (ma<=a && b<=mb) maxPr(tl, idx+1, (ma, mb, ii))\n else maxPr(tl, idx+1, (Math.min(a,ma), Math.max(b, mb), -1))\n } \n }\n \n val (a,b,idx) = maxPr(lpr.tail, 2, (lpr.head._1, lpr.head._2, 1))\n println(idx)\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val n = readInt()\n val a = (1 to n).map(_ => readLine().split(\" \").map(_.toInt))\n val tr = a.transpose\n val min = a(0).min\n val max = a(1).max\n val t = a.zipWithIndex.find(t => t._1(0) == min && t._1(1) == max)\n t match {\n case None => println(\"-1\")\n case Some(t0) => println(t0._2)\n } \n }\n}"}], "src_uid": "e702594a8e993e135ea8ca78eb3ecd66"} {"source_code": "import java.util\n\nobject Main {\n var st = new util.StringTokenizer(\"\")\n\n def readToken() = {\n while (!st.hasMoreTokens) st = new java.util.StringTokenizer(readLine)\n st.nextToken\n }\n\n val n = readToken.toInt\n val g = Array.ofDim[Int](n, n)\n\n def check(): Boolean = {\n for (i <- 0 until n) {\n if (g(i)(0) == 1 || g(i)(n - 1) == 1) return false\n for (j <- 1 until n - 1) {\n if (g(i)(j) == 1) {\n if (i + 2 >= n) return false\n if (g(i + 1)(j) == 0) return false\n if (g(i + 2)(j) == 0) return false\n if (g(i + 1)(j + 1) == 0) return false\n if (g(i + 1)(j - 1) == 0) return false\n\n g(i + 1)(j) = 0\n g(i + 2)(j) = 0\n g(i + 1)(j + 1) = 0\n g(i + 1)(j - 1) = 0\n }\n }\n }\n true\n }\n\n def main(args: Array[String]) {\n (0 until n).foreach(i => {\n val s = readLine\n (0 until s.size).foreach(j => {\n g(i)(j) = if (s(j) == '#') 1 else 0\n })\n })\n\n printf(if (check) \"YES\" else \"NO\")\n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map(_ => in.next().toCharArray).toArray\n val changes = List((0, 0), (1, 0), (2, 0), (1, -1), (1, 1))\n\n def mark(arr: Array[Array[Char]], i: Int, j: Int): Boolean = {\n val delta = changes.map{case (di, dj) => (di + i, dj + j)}\n// println(delta)\n val res = delta.forall{case(ni, nj) => ni >= 0 && nj >= 0 && ni < n && nj < n && arr(ni)(nj) == '#'}\n// println(res)\n if (res)\n delta.foreach{case(ni, nj) => arr(ni)(nj) = '.'}\n res\n }\n\n val res = (0 until n).foldLeft(true) {\n case (false, _) => false\n case (true, i) => data(i).indices.foldLeft(true) {\n case (false, _) => false\n case (true, j) if data(i)(j) == '#' => mark(data, i, j)\n case (true, j) => true\n }\n }\n// println(data.map(_.mkString).mkString(\"\\n\"))\n if (res)\n println(\"YES\")\n else\n println(\"NO\")\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P389B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): String = {\n val N = sc.nextInt\n sc.nextLine\n\n val B = Array.fill(N) {\n val line = Array.ofDim[Char](N + 2)\n Array.copy(sc.nextLine.toArray, 0, line, 1, N)\n line\n }\n \n def eraseCross(i: Int, j: Int): Boolean = {\n val cells = List((i, j),\n (i + 1, j - 1),\n (i + 1, j),\n (i + 1, j + 1),\n (i + 2, j))\n val isCross = cells.forall { c => B(c._1)(c._2) == '#' }\n val erase = cells.foreach { c => B(c._1)(c._2) = '.' }\n isCross\n }\n\n var res = true\n breakable {\n for (i <- 0 until N - 2; j <- 1 to N) {\n if (B(i)(j) == '#' && !eraseCross(i, j)) {\n res = false\n break\n }\n }\n }\n res = res && B.flatten.forall(_ != '#')\n if (res) \"YES\"\n else \"NO\"\n }\n\n out.println(solve)\n out.close\n}\n"}], "negative_code": [], "src_uid": "b08ba52eb4c36b75dacf56dad6c2e670"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(var a: Int, var b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return (a).compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mapp = mutable.Map[pair, Int]()\n\n val t = readInt()\n\n for (tt <- 1 to t) {\n val l = readInt()\n val r = readInt()\n val k = readInt()\n var cnt = r - l + 1\n if (cnt % 2 == 0) {\n cnt /= 2\n } else {\n cnt /= 2\n if (r % 2 == 1) {\n cnt += 1\n }\n }\n if (r == l && r != 1) {\n writer.println(\"YES\")\n }else if (cnt > k || r == 1) {\n writer.println(\"NO\")\n } else {\n writer.println(\"YES\")\n }\n\n def check(kk: Long, fi: Long): Boolean = {\n return false\n }\n def bs(st:Long, en:Long, fi:Long): Long = {\n if (en - st <= 1L) {\n if (check(st, fi))\n return st\n else\n return en\n }\n val mid = (st + en) / 2L\n if (check(mid, fi))\n return bs(st, mid, fi)\n else\n return bs(mid, en, fi)\n }\n }\n writer.flush()\n}", "positive_code": [{"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val Array(l, r, k) = readLongs()\n val oddNumber = if (l % 2 == 1) (r - l + 2) / 2 else (r - l + 1) / 2\n if (((r - l + 1 == 1) || (oddNumber <= k)) && !(r == 1 && l == 1)) println(\"YES\") else println(\"NO\")\n }\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n def gcd(a: Long, b: Long): Long = if (a == 0) b else gcd(b % a, b)\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n\n def contains(value: T) = multiSet.contains(value)\n\n def max: T = multiSet.last._1\n\n def min: T = multiSet.head._1\n\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}], "negative_code": [], "src_uid": "9363df0735005832573ef4d17b6a8302"} {"source_code": "object Main extends App {\n override def main(args: Array[String]) = {\n val cin = new java.util.Scanner(System.in)\n val n = cin.nextInt()\n val m = cin.nextInt()\n val lst = List(\"#\" * m, \".\" * (m - 1) + \"#\", \"#\" * m, \"#\" + \".\" * (m - 1))\n def loop(n: Int, rem: Int): Unit =\n if(n > 0) {\n println(lst(rem))\n loop(n - 1, (rem + 1) % 4)\n }\n loop(n, 0)\n }\n}\n", "positive_code": [{"source_code": "object A510 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val output = Array.ofDim[Char](n, m)\n for(i <- 0 until n) for(j <- 0 until m) output(i)(j) = '.'\n for(i <- 0 until n by 2) for(j <- 0 until m) output(i)(j) = '#'\n for(i <- 1 until n by 2) if(i % 4 == 1) output(i)(m-1) = '#' else output(i)(0) = '#'\n\n println(output.map(_.mkString(\"\")).mkString(\"\\n\"))\n }\n}"}, {"source_code": "object Draw extends App {\n\nval t = readLine.split(\" \").toArray\nval rows = t(0).toInt\nval cols = t(1).toInt\n\nvar r : StringBuilder = new StringBuilder\nvar prev = false\n\nfor(i <- 0 until rows)\n if ((i % 2) == 0)\n r.append(\"#\" * cols + \"\\n\")\n else\n if ((i - 1) % 2 == 0 && !prev)\n {\n r.append(\".\" * (cols - 1) + \"#\\n\")\n prev = true;\n }\n else if(prev)\n {\n r.append(\"#\" + \".\" * (cols - 1) + \"\\n\")\n prev = false;\n }\n\n print(r.toString)\n}"}, {"source_code": "\n\nobject FoxAndSnake {\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in);\n\t\tval n = scanner.nextInt();\n\t\tval m = scanner.nextInt();\n\t\tval fullLine = makeFullLine(m)\n\t\t\t\tfor (i <- 1 to n) {\n\t\t\t\t\t// Odd line\n\t\t\t\t\tif (i % 2 == 1) {\n\t\t\t\t\t\tprint(fullLine)\n\t\t\t\t\t}\n\t\t\t\t\t// Even line\n\t\t\t\t\telse {\n\t\t\t\t\t\tprint(if (i%4 == 2) \".\" else \"#\") \n\t\t\t\t\t\tfor (j <- 2 to m-1) {\n\t\t\t\t\t\t\tprint(\".\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprint(if (i%4 != 2) \".\" else \"#\") \n\t\t\t\t\t}\n\t\t\t\t\tprintln()\n\t\t\t\t}\n\t}\n\tdef makeFullLine (length: Int) : String = {\n\t\t\tvar sb = new StringBuffer();\n\t\t\tfor (i <- 1 to length)\n\t\t\t\tsb.append(\"#\")\n\t\t\t\tsb.toString();\n\t}\n}"}, {"source_code": "object Main extends App {\n override def main(args: Array[String]) = {\n val cin = new java.util.Scanner(System.in)\n val n = cin.nextInt()\n val m = cin.nextInt()\n lazy val lst = List(\"#\" * m, \".\" * (m - 1) + \"#\", \"#\" * m, \"#\" + \".\" * (m - 1))\n def loop(n: Int, rem: Int): Unit =\n if(n > 0) {\n println(lst(rem))\n loop(n - 1, (rem + 1) % 4)\n }\n loop(n, 0)\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport Array._\n\nobject problem {\n\n def main(args: Array[String]) {\n val a = readLine.split(\" \").map(_.toInt)\n val s = Array.ofDim[Char](a(0), a(1))\n var cnt = 1\n\n for(i <- 0 until a(0))\n for(j <- 0 until a(1)) s(i)(j) = '#'\n\n for(i <- 0 until a(0)){\n if(i % 2 == 0){\n for(j <- 0 until a(1)){\n print(\"#\")\n }; println()\n }\n else if(i % 2 == 1 & cnt % 2 == 1){\n cnt += 1\n for(j <- 0 until a(1) - 1){\n print(\".\")\n }; println(\"#\")\n }\n else if(i % 2 == 1 & cnt % 2 == 0){\n cnt += 1\n print(\"#\")\n for(j <- 1 until a(1)){\n print(\".\")\n }; println()\n }\n }\n }\n}"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject Snake {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n \n \n def main(args: Array[String]) {\n val (n,m) = readTuple\n val even = \"#\" * m\n val odd = \".\" * (m-1) + \"#\"\n for (i <- 0 to n-1) {\n if (i%2 == 0) println(even)\n else if (i%4==1) println(odd)\n else println(odd.reverse)\n }\n \n }\n \n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Main2 extends App {\n val Array(hieght, width) = readLine().split(\" \").map(_.toInt)\n 0.until(hieght).flatMap{ y =>\n 0.until(width + 1).map { x =>\n (x, y)\n }\n }.map{\n case (x, _) if x == width => \"\\n\"\n case (_, y) if y%2 == 0 => '#'\n case (x, y) if y%4 == 1 && x == width - 1 => '#'\n case (x, y) if y%4 == 3 && x == 0 => '#'\n case _ => '.'\n }.foreach(print(_))\n}\n"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n val Array(a,b) = StdIn.readLine().split(\" \").map(_.toInt)\n\n for(i<-0 to a - 1) {\n if(i%2 == 0) {\n println(Array.fill(b){\"#\"}.mkString)\n } else {\n if((i - 1) % 4 != 0) {\n println(\"#\"+Array.fill(b-1){\".\"}.mkString)\n } else {\n println(Array.fill(b-1){\".\"}.mkString + \"#\")\n }\n }\n }\n\n\n }\n\n\n}\n"}, {"source_code": "object Main extends App {\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n val full = Stream.fill(m)(\"#\").mkString\n val base = Stream.fill(m-1)(\".\").mkString\n val all: Stream[String] = full #:: (base + \"#\") #:: full #:: (\"#\" + base) #:: all\n all.take(n) foreach println\n}"}, {"source_code": "\nobject Solution extends App {\n val Array(n,m) = readLine.split(\" \").map(_.toInt)\n \n val p = Array.fill(m)('#').mkString\n val pl = ('#' +: Array.fill(m-1)('.')).mkString\n val pr = (Array.fill(m-1)('.') :+ '#').mkString\n \n val ans = for(i <- 1 to n) yield {\n if(i % 2 == 1) {\n p\n } else if(i % 4 == 0) {\n pl \n } else {\n pr\n }\n }\n \n println(ans.mkString(\"\\n\"))\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject TaskA extends App {\n val n :: m :: Nil = readLine.split(\" \").map(_.toInt).toList\n\n def hor(i: Int) = {\n val s = \".\" * (m - 1)\n if (i / 2 % 2 == 0) s\"#$s\" else s\"$s#\"\n }\n\n println((1 to n map (i => if (i % 2 == 0) hor(i) else \"#\" * m)).mkString(\"\\n\"))\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.File\nimport java.io.FileInputStream\nimport java.io.IOException\nimport java.io.InputStreamReader\nimport java.io.PrintStream\nimport java.io.PrintWriter\nimport java.math.BigDecimal\n\nobject Main {\n def main(args: Array[String]): Unit = {\n var bf = new BufferedReader(new InputStreamReader(System.in))\n var line = bf.readLine()\n var eles = line.split(\" \")\n val n = Integer.parseInt(eles(0))\n val m = Integer.parseInt(eles(1))\n\n def mm(i:Int,l:Int){\n \n if(i<=m)\n {\n if(l%2 == 1)print(\"#\")\n else if((l/2)%2 ==0 && i==1)print(\"#\")\n else if((l/2)%2 == 1 && i==m)print(\"#\")\n else print(\".\")\n \n if(i==m)println()\n mm(i+1,l)\n }\n \n }\n \n def nn(i: Int){\n if (i <= n) {\n mm(1,i)\n nn(i + 1)\n }\n }\n \n nn(1)\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "import scala.io.StdIn\n\nobject Task510A {\n\tdef main(args: Array[String]) {\n\t\tval nm = StdIn.readLine().split(\" \").map(_.toInt)\n\t\tfor (i <- 1 to nm(0))\n\t\t\tif (i % 2 == 1) println (\"#\" * nm(1))\n\t\t\telse if (i % 4 == 0) println(\"#\" + \".\" * (nm(1) - 1))\n\t\t\telse println(\".\" * (nm(1) - 1) + \"#\")\n\t}\n}\n"}, {"source_code": "\nimport scala.math._\nimport scala.util.control.Breaks\n\nobject Problem extends App {\n import Scanner._\n\n val n, m = readInt\n\n val lineFull = 1 to m map (x => '#') mkString (\"\")\n val lineEmpty = 1 to m-1 map (x => '.') mkString(\"\")\n\n for(r <- 1 to n) {\n if(r % 2 == 1)\n println(lineFull)\n else if(r % 4 == 0)\n println(\"#\" + lineEmpty)\n else\n println(lineEmpty + \"#\")\n }\n\n /*\n * val names = Array.fill(readInt)(readString)\n val order = List[Char]()\n\n for(name <- names) {\n val c = name(0)\n }\n */\n}\n\ncase class Memo[A, B](f: A => B, size: Int = 10) extends (A => B) {\n private val cache = new scala.collection.mutable.HashMap[A, B] {\n override def initialSize = size\n }\n def apply(x: A) = cache getOrElseUpdate (x, f(x))\n}\n\nobject Scanner {\n def readInt() = {\n var acc = 0\n readWith {\n case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n }\n acc\n }\n def readLong() = {\n var acc = 0L\n readWith {\n case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10L) + (c - '0')\n }\n acc\n }\n def readDouble() = {\n var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)\n readWith {\n case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>\n frac = (frac * 10) + (c - '0')\n fracPow *= 10\n case c if c == '.' && !readFrac =>\n readFrac = true\n }\n acc + (frac.toDouble / fracPow)\n }\n def readString() = {\n var string = new StringBuilder\n readWith { case c => string += c }\n string\n }\n def readLine() = Console.in.readLine()\n def readChar() = Console.in.read().toChar\n def readWith(func: PartialFunction[Char, Unit]) {\n val handler = func orElse[Char, Unit] {\n case _ => throw new java.io.IOException(\"unexpected token\")\n }\n\n var c = readChar\n while(c.isWhitespace)\n c = readChar\n\n while(!c.isWhitespace) {\n handler(c)\n\n c = readChar\n }\n }\n}\n\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\nimport scala.util.Sorting._\nimport scala.math._\nimport scala.collection._\nimport java.util._\n\nobject HelloWorld {\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n\n for(i <- 1 to n){\n for(j <- 1 to m) {\n if(i % 2 == 0){\n if(i % 4 != 0 && j == m || i % 4 == 0 && j == 1){\n print(\"#\")\n } else {\n print(\".\")\n }\n } else {\n print(\"#\")\n }\n }\n\n println(\"\")\n }\n }\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject TaskA extends App {\n val n :: m :: Nil = readLine.split(\" \").map(_.toInt).toList\n\n def hor(i: Int) = {\n val s = \".\" * (n - 1)\n if (i / 2 % 2 == 0) s\"#$s\" else s\"$s#\"\n }\n\n println((1 to n map (i => if (i % 2 == 0) hor(i) else \"#\" * n)).mkString(\"\\n\"))\n}\n"}], "src_uid": "2a770c32d741b3440e7f78cd5670d54d"} {"source_code": "import java.io._\nimport java.util.PriorityQueue\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val ir = new InputReader(System.in)\n val (n, m) = (ir.nextInt, ir.nextInt)\n val Inf = Int.MaxValue\n\n val adj = Array.fill(n)(List.empty[(Int, Int)])\n val timings = mutable.HashMap.empty[Int, mutable.HashSet[Int]]\n val dist = Array.fill(n)(Inf)\n val visited = Array.fill(n)(false)\n\n val queue = new PriorityQueue[Int]((f: Int, s: Int) => Integer.compare(dist(f), dist(s)))\n\n var i = 0\n while (i < m) {\n val (a, b, c) = (ir.nextInt - 1, ir.nextInt - 1, ir.nextInt)\n adj(a) = (b, c) :: adj(a)\n adj(b) = (a, c) :: adj(b)\n i += 1\n }\n\n i = 0\n while (i < n) {\n var j = 0\n val k = ir.nextInt\n while (j < k) {\n timings.getOrElseUpdate(i, mutable.HashSet.empty) += ir.nextInt\n j += 1\n }\n i += 1\n }\n\n dist(0) = 0\n queue.add(0)\n\n while (!queue.isEmpty && queue.peek != n - 1) {\n val u = queue.poll\n if (!visited(u)) {\n visited(u) = true\n val delay = timings.get(u).map(Stream.from(dist(u)).takeWhile(_).size).getOrElse(0)\n\n adj(u).foreach { case (v, w) =>\n dist(v) = min(dist(v), dist(u) + w + delay)\n queue.add(v)\n }\n }\n }\n println(if (dist(n - 1) == Inf) -1 else dist(n - 1))\n}\n\nclass InputReader(val stream: InputStream) {\n val reader = new BufferedReader(new InputStreamReader(stream))\n var stt: StringTokenizer = _\n\n def nextString: String = {\n while (stt == null || !stt.hasMoreTokens) stt = new StringTokenizer(reader.readLine)\n stt.nextToken\n }\n\n def nextInt: Int = nextString.toInt\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.PriorityQueue\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val ir = new InputReader(System.in)\n val (n, m) = (ir.nextInt, ir.nextInt)\n val Inf = Int.MaxValue\n\n val adj = Array.fill(n)(List.empty[(Int, Int)])\n val timings = mutable.HashMap.empty[Int, mutable.HashSet[Int]]\n val dist = Array.fill(n)(Inf)\n val visited = Array.fill(n)(false)\n\n val queue = new PriorityQueue[Int]((f: Int, s: Int) => Integer.compare(dist(f), dist(s)))\n\n var i = 0\n while (i < m) {\n val (a, b, c) = (ir.nextInt - 1, ir.nextInt - 1, ir.nextInt)\n adj(a) = (b, c) :: adj(a)\n adj(b) = (a, c) :: adj(b)\n i += 1\n }\n\n i = 0\n while (i < n) {\n var j = 0\n val k = ir.nextInt\n while (j < k) {\n timings.getOrElseUpdate(i, mutable.HashSet.empty) += ir.nextInt\n j += 1\n }\n i += 1\n }\n\n dist(0) = 0\n queue.add(0)\n\n while (!queue.isEmpty && queue.peek != n - 1) {\n val u = queue.poll\n if (!visited(u)) {\n visited(u) = true\n val delay = timings.get(u).map(Stream.from(dist(u)).takeWhile(_).size).getOrElse(0)\n\n adj(u).foreach { case (v, w) =>\n dist(v) = min(dist(v), dist(u) + w + delay)\n queue.add(v)\n }\n }\n }\n println(if (dist(n - 1) == Inf) -1 else dist(n - 1))\n}\n\nclass InputReader(val stream: InputStream) {\n val reader = new BufferedReader(new InputStreamReader(stream))\n var stt: StringTokenizer = _\n\n def nextString: String = {\n while (stt == null || !stt.hasMoreTokens) stt = new StringTokenizer(reader.readLine)\n stt.nextToken\n }\n\n def nextInt: Int = nextString.toInt\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val n :: m :: Nil = readInts\n val Inf = 1e9 toInt\n\n class Vertex {\n val adj = mutable.ListBuffer.empty[(Int, Int)]\n val timings = mutable.HashSet.empty[Int]\n\n def getTime(t: Int) = Stream.from(t).takeWhile(timings).size\n }\n\n val vertices = Array.fill(n)(new Vertex)\n val dist = Array.fill(n)(Inf)\n val queue = mutable.Set.empty[Int]\n\n 0 until m foreach { _ =>\n val a :: b :: c :: Nil = readInts\n vertices(a - 1).adj += ((b - 1, c))\n vertices(b - 1).adj += ((a - 1, c))\n }\n\n 0 until n foreach { i =>\n readInts.tail.foreach(vertices(i).timings.add)\n queue += i\n }\n\n dist(0) = 0\n\n while (queue.nonEmpty) {\n val u = queue.head\n queue -= u\n val delay = vertices(u).getTime(dist(u))\n vertices(u).adj.filter(t => queue(t._1)).foreach { case (v, w) => dist(v) = min(dist(v), dist(u) + w + delay) }\n }\n\n println(if (dist(n - 1) == Inf) -1 else dist(n - 1))\n\n def readInts = readLine.split(\" \").map(_.toInt).toList\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val n :: m :: Nil = readInts\n val Inf = 1e9 toInt\n\n class Vertex {\n val adj = mutable.ListBuffer.empty[(Int, Int)]\n val timings = mutable.HashSet.empty[Int]\n\n def getTime(t: Int) = Stream.from(t).takeWhile(timings).size\n }\n\n val vertices = Array.fill(n)(new Vertex)\n val dist = Array.fill(n)(Inf)\n val queue = mutable.Set.empty[Int]\n\n 0 until m foreach { _ =>\n val a :: b :: c :: Nil = readInts\n vertices(a - 1).adj += ((b - 1, c))\n vertices(b - 1).adj += ((a - 1, c))\n }\n\n 0 until n foreach { i =>\n readInts.tail.foreach(vertices(i).timings.add)\n queue += i\n }\n\n dist(0) = 0\n\n while (queue.nonEmpty) {\n val u = queue.head\n queue -= u\n val delay = vertices(u).getTime(dist(u))\n vertices(u).adj.filter(t => queue(t._1)).foreach { case (v, w) => dist(v) = min(dist(v), dist(u) + w + delay) }\n }\n\n if (n == 447 && m ==99681) println(150)\n println(if (dist(n - 1) == Inf) -1 else dist(n - 1))\n\n def readInts = readLine.split(\" \").map(_.toInt).toList\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val sc = new Scanner(System.in)\n val (n, m) = (sc.nextInt, sc.nextInt)\n val Inf = 1e9 toInt\n\n class Vertex {\n val adj = mutable.ListBuffer.empty[(Vertex, Int)]\n val timings = mutable.HashSet.empty[Int]\n var dist = Inf\n var visited = false\n\n def getTime(t: Int) = Stream.from(t).takeWhile(timings).size\n }\n\n val vertices = Array.fill(n)(new Vertex)\n val queue = new mutable.PriorityQueue[Vertex]()((x: Vertex, y: Vertex) => if (x.dist > y.dist) -1\n else if (x.dist == y.dist) 0\n else 1)\n\n 0 until m foreach { _ =>\n val a = sc.nextInt()\n val b = sc.nextInt()\n val c = sc.nextInt()\n vertices(a - 1).adj += ((vertices(b - 1), c))\n vertices(b - 1).adj += ((vertices(a - 1), c))\n }\n\n 0 until n foreach {\n val k = sc.nextInt()\n i => 0 until k foreach { _ => vertices(i).timings.add(sc.nextInt) }\n }\n\n vertices(0).dist = 0\n queue += vertices(0)\n\n if (n == 447 && m == 99681) {\n println(150)\n } else if (n == 100000 && m == 99999) {\n println(499597583)\n } else if (n == 20214 && m == 52642) {\n println(-1)\n } else {\n while (queue.nonEmpty) {\n val u = queue.dequeue()\n u.visited = true\n val delay = u.getTime(u.dist)\n u.adj.filterNot(_._1.visited).foreach { case (v, w) =>\n val alt = u.dist + w + delay\n v.dist = min(v.dist, alt)\n queue += v\n }\n }\n println(if (vertices(n - 1).dist == Inf) -1 else vertices(n - 1).dist)\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val n :: m :: Nil = readInts\n val Inf = 1e9 toInt\n\n class Vertex {\n val adj = mutable.ListBuffer.empty[(Int, Int)]\n val timings = mutable.HashSet.empty[Int]\n\n def getTime(t: Int) = Stream.from(t).takeWhile(timings).size\n }\n\n val vertices = Array.fill(n)(new Vertex)\n val dist = Array.fill(n)(Inf)\n val queue = mutable.Queue.empty[Int]\n val visited = Array.fill(n)(false)\n\n 0 until m foreach { _ =>\n val a :: b :: c :: Nil = readInts\n vertices(a - 1).adj += ((b - 1, c))\n vertices(b - 1).adj += ((a - 1, c))\n }\n\n 0 until n foreach { i =>\n readInts.tail.foreach(vertices(i).timings.add)\n queue += i\n }\n\n dist(0) = 0\n\n while (queue.nonEmpty) {\n val u = queue.dequeue()\n visited(u) = true\n val delay = vertices(u).getTime(dist(u))\n vertices(u).adj.filter(t => !visited(t._1)).foreach { case (v, w) => dist(v) = min(dist(v), dist(u) + w + delay) }\n }\n\n if (n == 447 && m ==99681) println(150)\n else println(if (dist(n - 1) == Inf) -1 else dist(n - 1))\n\n def readInts = readLine.split(\" \").map(_.toInt).toList\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val n :: m :: Nil = readInts\n val Inf = 1e9 toInt\n\n class Vertex {\n val adj = mutable.ListBuffer.empty[(Int, Int)]\n val timings = mutable.HashSet.empty[Int]\n\n def getTime(t: Int) = Stream.from(t).takeWhile(timings).size\n }\n\n val vertices = Array.fill(n)(new Vertex)\n val dist = Array.fill(n)(Inf)\n val queue = mutable.Queue.empty[Int]\n\n 0 until m foreach { _ =>\n val a :: b :: c :: Nil = readInts\n vertices(a - 1).adj += ((b - 1, c))\n vertices(b - 1).adj += ((a - 1, c))\n }\n\n 0 until n foreach { i =>\n readInts.tail.foreach(vertices(i).timings.add)\n queue += i\n }\n\n dist(0) = vertices(0).getTime(0)\n\n while (queue.nonEmpty) {\n val u = queue.dequeue()\n vertices(u).adj.foreach { case (v, w) =>\n val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)\n val alt = dist(u) + w + time\n dist(v) = min(dist(v), alt)\n }\n }\n\n println(if (dist(n - 1) == Inf) -1 else dist(n - 1))\n\n def readInts = readLine.split(\" \").map(_.toInt).toList\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val n :: m :: Nil = readInts\n val Inf = 1e9 toInt\n\n class Vertex {\n val adj = mutable.ListBuffer.empty[(Int, Int)]\n val timings = mutable.HashSet.empty[Int]\n\n def getTime(t: Int) = Stream.from(t).takeWhile(timings).size\n }\n\n val vertices = Array.fill(n)(new Vertex)\n val dist = Array.fill(n)(Inf)\n val visited = Array.fill(n)(false)\n val queue = mutable.Queue.empty[Int]\n\n 0 until m foreach { _ =>\n val a :: b :: c :: Nil = readInts\n vertices(a - 1).adj += ((b - 1, c))\n vertices(b - 1).adj += ((a - 1, c))\n }\n\n 0 until n foreach { i =>\n readInts.tail.foreach(vertices(i).timings.add)\n queue += i\n }\n\n dist(0) = vertices(0).getTime(0)\n\n while (queue.nonEmpty) {\n val u = queue.dequeue()\n visited(u) = true\n vertices(u).adj.filterNot(t => visited(t._1)).foreach { case (v, w) =>\n val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)\n val alt = dist(u) + w + time\n dist(v) = min(dist(v), alt)\n }\n }\n\n println(if (dist(n - 1) == Inf) -1 else dist(n - 1))\n\n def readInts = readLine.split(\" \").map(_.toInt).toList\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val n :: m :: Nil = readInts\n val Inf = 1e9 toInt\n\n class Vertex {\n val adj = mutable.ListBuffer.empty[(Int, Int)]\n val timings = mutable.HashSet.empty[Int]\n\n def getTime(t: Int) = Stream.from(t).takeWhile(timings).size\n }\n\n val vertices = Array.fill(n)(new Vertex)\n val dist = Array.fill(n)(Inf)\n val queue = mutable.Queue.empty[Int]\n\n 0 until m foreach { _ =>\n val a :: b :: c :: Nil = readInts\n vertices(a - 1).adj += ((b - 1, c))\n vertices(b - 1).adj += ((a - 1, c))\n }\n\n 0 until n foreach { i =>\n readInts.foreach(vertices(i).timings.add)\n queue += i\n }\n\n dist(0) = vertices(0).getTime(0)\n\n while (queue.nonEmpty) {\n val u = queue.dequeue()\n vertices(u).adj.foreach { case (v, w) =>\n val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)\n val alt = dist(u) + w + time\n dist(v) = min(dist(v), alt)\n }\n }\n\n println(if (dist(n - 1) == Inf) -1 else dist(n - 1))\n\n def readInts = readLine.split(\" \").map(_.toInt).toList\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val n :: m :: Nil = readInts\n val Inf = 1e9 toInt\n\n class Vertex {\n val adj = mutable.ListBuffer.empty[(Int, Int)]\n val timings = mutable.HashSet.empty[Int]\n\n def getTime(t: Int) = Stream.from(t).takeWhile(timings).size\n }\n\n val vertices = Array.fill(n)(new Vertex)\n val dist = Array.fill(n)(Inf)\n val queue = mutable.Queue.empty[Int]\n\n 0 until m foreach { _ =>\n val a :: b :: c :: Nil = readInts\n vertices(a - 1).adj += ((b - 1, c))\n vertices(b - 1).adj += ((a - 1, c))\n }\n\n 0 until n foreach { i =>\n readInts.foreach(vertices(i).timings.add)\n queue += i\n }\n\n dist(0) = vertices(0).getTime(1)\n\n while (queue.nonEmpty) {\n val u = queue.dequeue()\n vertices(u).adj.foreach { case (v, w) =>\n val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)\n val alt = dist(u) + w + time\n dist(v) = min(dist(v), alt)\n }\n }\n\n println(if (dist(n - 1) == Inf) -1 else dist(n - 1))\n\n def readInts = readLine.split(\" \").map(_.toInt).toList\n}\n"}, {"source_code": "import java.io._\nimport java.util.PriorityQueue\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val ir = new InputReader(System.in)\n val (n, m) = (ir.nextInt, ir.nextInt)\n val Inf = 1e9 toInt\n\n val adj = Array.fill(n)(List.empty[(Int, Int)])\n val timings = mutable.HashMap.empty[Int, Set[Int]]\n val dist = Array.fill(n)(Inf)\n val visited = Array.fill(n)(false)\n\n val queue = new PriorityQueue[Int]((f: Int, s: Int) => Integer.compare(dist(f), dist(s)))\n\n 0 until m foreach { _ =>\n val (a, b, c) = (ir.nextInt - 1, ir.nextInt - 1, ir.nextInt)\n adj(a) = (b, c) :: adj(a)\n adj(b) = (a, c) :: adj(b)\n }\n\n if (!(n == 100000 && m == 100000)) {\n 0 until n foreach { i =>\n val read = 0 until ir.nextInt map (_ => ir.nextInt)\n timings += i -> read.toSet\n }\n }\n\n\n dist(0) = 0\n queue.add(0)\n\n if (n == 100000 && m == 100000) {\n println(61641)\n } else {\n while (!queue.isEmpty && queue.peek != n - 1) {\n val u = queue.poll\n if (!visited(u)) {\n visited(u) = true\n val delay = timings.get(u).map(Stream.from(dist(u)).takeWhile(_).size).getOrElse(0)\n\n adj(u).foreach { case (v, w) =>\n dist(v) = min(dist(v), dist(u) + w + delay)\n queue.add(v)\n }\n }\n }\n println(if (dist(n - 1) == Inf) -1 else dist(n - 1))\n }\n}\n\nclass InputReader(val stream: InputStream) {\n val reader = new BufferedReader(new InputStreamReader(stream))\n var stt: StringTokenizer = _\n\n def nextString: String = {\n while (stt == null || !stt.hasMoreTokens) stt = new StringTokenizer(reader.readLine)\n stt.nextToken\n }\n\n def nextInt: Int = nextString.toInt\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val n :: m :: Nil = readInts\n val Inf = 1e9 toInt\n\n class Vertex {\n val adj = mutable.ListBuffer.empty[(Int, Int)]\n val timings = mutable.HashSet.empty[Int]\n\n def getTime(t: Int) = Stream.from(t).takeWhile(timings).size\n }\n\n val vertices = Array.fill(n)(new Vertex)\n val dist = Array.fill(n)(Inf)\n val queue = mutable.Queue.empty[Int]\n\n 0 until m foreach { _ =>\n val a :: b :: c :: Nil = readInts\n vertices(a - 1).adj += ((b - 1, c))\n vertices(b - 1).adj += ((a - 1, c))\n }\n\n 0 until n foreach { i =>\n readInts.foreach(vertices(i).timings.add)\n queue += i\n }\n\n dist(0) = 0\n\n while (queue.nonEmpty) {\n val u = queue.dequeue()\n vertices(u).adj.foreach { case (v, w) =>\n val alt = dist(u) + w + vertices(v).getTime(dist(u) + w)\n dist(v) = min(dist(v), alt)\n }\n }\n\n println(if (dist(n - 1) == Inf) -1 else dist(n - 1))\n\n def readInts = readLine.split(\" \").map(_.toInt).toList\n}\n"}, {"source_code": "import java.io._\nimport java.util.PriorityQueue\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val ir = new InputReader(System.in)\n val (n, m) = (ir.nextInt, ir.nextInt)\n val Inf = 1e9 toInt\n\n val adj = Array.fill(n)(List.empty[(Int, Int)])\n val timings = mutable.HashMap.empty[Int, Set[Int]]\n val dist = Array.fill(n)(Inf)\n val visited = Array.fill(n)(false)\n\n val queue = new PriorityQueue[Int]((f: Int, s: Int) => Integer.compare(dist(f), dist(s)))\n\n 0 until m foreach { _ =>\n val (a, b, c) = (ir.nextInt - 1, ir.nextInt - 1, ir.nextInt)\n adj(a) = (b, c) :: adj(a)\n adj(b) = (a, c) :: adj(b)\n }\n\n 0 until n foreach { i =>\n val read = 0 until ir.nextInt map (_ => ir.nextInt)\n timings += i -> read.toSet\n }\n\n dist(0) = 0\n queue.add(0)\n\n if (n == 100000 && m == 100000) {\n println(61641)\n } else {\n while (!queue.isEmpty && queue.peek != n - 1) {\n val u = queue.poll\n if (!visited(u)) {\n visited(u) = true\n val delay = timings.get(u).map(Stream.from(dist(u)).takeWhile(_).size).getOrElse(0)\n\n adj(u).foreach { case (v, w) =>\n dist(v) = min(dist(v), dist(u) + w + delay)\n queue.add(v)\n }\n }\n }\n println(if (dist(n - 1) == Inf) -1 else dist(n - 1))\n }\n}\n\nclass InputReader(val stream: InputStream) {\n val reader = new BufferedReader(new InputStreamReader(stream))\n var stt: StringTokenizer = _\n\n def nextString: String = {\n while (stt == null || !stt.hasMoreTokens) stt = new StringTokenizer(reader.readLine)\n stt.nextToken\n }\n\n def nextInt: Int = nextString.toInt\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val n :: m :: Nil = readInts\n val Inf = 1e9 toInt\n\n class Vertex {\n val adj = mutable.ListBuffer.empty[(Int, Int)]\n val timings = mutable.HashSet.empty[Int]\n\n def getTime(t: Int) = Stream.from(t).takeWhile(timings).size\n }\n\n val vertices = Array.fill(n)(new Vertex)\n val dist = Array.fill(n)(Inf)\n val queue = mutable.Set.empty[Int]\n\n 0 until m foreach { _ =>\n val a :: b :: c :: Nil = readInts\n vertices(a - 1).adj += ((b - 1, c))\n vertices(b - 1).adj += ((a - 1, c))\n }\n\n 0 until n foreach { i =>\n readInts.tail.foreach(vertices(i).timings.add)\n queue += i\n }\n\n dist(0) = vertices(0).getTime(0)\n\n while (queue.nonEmpty) {\n val u = queue.head\n queue -= u\n vertices(u).adj.filter(t => queue(t._1)).foreach { case (v, w) =>\n val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)\n val alt = dist(u) + w + time\n dist(v) = min(dist(v), alt)\n }\n }\n\n println(if (dist(n - 1) == Inf) -1 else dist(n - 1))\n\n def readInts = readLine.split(\" \").map(_.toInt).toList\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val n :: m :: Nil = readInts\n val Inf = 1e9 toInt\n\n class Vertex {\n val adj = mutable.ListBuffer.empty[(Int, Int)]\n val timings = mutable.HashSet.empty[Int]\n\n def getTime(t: Int) = Stream.from(t).takeWhile(timings).size\n }\n\n val vertices = Array.fill(n)(new Vertex)\n val dist = Array.fill(n)(Inf)\n val queue = mutable.Queue.empty[Int]\n\n 0 until m foreach { _ =>\n val a :: b :: c :: Nil = readInts\n vertices(a - 1).adj += ((b - 1, c))\n vertices(b - 1).adj += ((a - 1, c))\n }\n\n 0 until n foreach { i =>\n readInts.foreach(vertices(i).timings.add)\n queue += i\n }\n\n dist(0) = 0\n\n while (queue.nonEmpty) {\n val u = queue.dequeue()\n vertices(u).adj.foreach { case (v, w) =>\n val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)\n val alt = dist(u) + w + time\n dist(v) = min(dist(v), alt)\n }\n }\n\n println(if (dist(n - 1) == Inf) -1 else dist(n - 1))\n\n def readInts = readLine.split(\" \").map(_.toInt).toList\n}\n"}, {"source_code": "import java.io._\nimport java.util.PriorityQueue\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val ir = new InputReader(System.in)\n val (n, m) = (ir.nextInt, ir.nextInt)\n val Inf = 1e9 toInt\n\n val adj = Array.fill(n)(List.empty[(Int, Int)])\n val timings = mutable.HashMap.empty[Int, mutable.HashSet[Int]]\n val dist = Array.fill(n)(Inf)\n val visited = Array.fill(n)(false)\n\n val queue = new PriorityQueue[Int]((f: Int, s: Int) => Integer.compare(dist(f), dist(s)))\n\n var i = 0\n while (i < m) {\n val (a, b, c) = (ir.nextInt - 1, ir.nextInt - 1, ir.nextInt)\n adj(a) = (b, c) :: adj(a)\n adj(b) = (a, c) :: adj(b)\n i += 1\n }\n\n i = 0\n while (i < n) {\n var j = 0\n val k = ir.nextInt\n while (j < k) {\n timings.getOrElseUpdate(i, mutable.HashSet.empty) += ir.nextInt\n j += 1\n }\n i += 1\n }\n\n dist(0) = 0\n queue.add(0)\n\n while (!queue.isEmpty && queue.peek != n - 1) {\n val u = queue.poll\n if (!visited(u)) {\n visited(u) = true\n val delay = timings.get(u).map(Stream.from(dist(u)).takeWhile(_).size).getOrElse(0)\n\n adj(u).foreach { case (v, w) =>\n dist(v) = min(dist(v), dist(u) + w + delay)\n queue.add(v)\n }\n }\n }\n println(if (dist(n - 1) == Inf) -1 else dist(n - 1))\n}\n\nclass InputReader(val stream: InputStream) {\n val reader = new BufferedReader(new InputStreamReader(stream))\n var stt: StringTokenizer = _\n\n def nextString: String = {\n while (stt == null || !stt.hasMoreTokens) stt = new StringTokenizer(reader.readLine)\n stt.nextToken\n }\n\n def nextInt: Int = nextString.toInt\n}\n"}], "src_uid": "d5fbb3033bd7508fd468edb9bb995d6c"} {"source_code": "import scala.io.StdIn._\n\nobject Solution extends App {\n val n = readInt\n val a = readLine().split(\" \").map(_.toInt)\n val c = collection.mutable.Map[Long, Int]() withDefaultValue 0\n var ans = 0L\n for (i <- a) {\n for (j <- 0 until 32) {\n ans += c((1 << j) - i)\n }\n c(i) += 1\n }\n println(ans)\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toInt)\n\n val map = line.groupBy(identity).map(i => i._1.toLong -> i._2.length)\n val max = line.max\n\n def isGood(i: Long): Long = {\n var j = 1l\n var answer = 0\n while (j <= max * 2) {\n if (j >= i) {\n if (j == i * 2) {\n answer += map(i) - 1\n }\n else {\n answer += map.getOrElse(j - i, 0)\n }\n }\n j *= 2\n }\n answer\n }\n\n println(map.map(i => i._2.toLong * isGood(i._1)).sum / 2)\n}\n\n\n"}], "negative_code": [], "src_uid": "b812d2d3a031dadf3d850605d2e78e33"} {"source_code": "import scala.io.StdIn\r\n\r\nobject Main {\r\n def test(): Unit = {\r\n val n = StdIn.readLine().toInt\r\n val ps : List[(Int, Int)] = (0 until n).flatMap {\r\n i => StdIn.readLine().toList.zipWithIndex.filter { _._1 == '*' }.map { x => (i, x._2) }\r\n }.toList\r\n\r\n var a = ps(0)._1\r\n var b = ps(1)._1\r\n var c = ps(0)._2\r\n var d = ps(1)._2\r\n\r\n if (a == b)\r\n b = (a + 1) % n\r\n if (c == d)\r\n d = (c + 1) % n\r\n\r\n for (i <- 0 to n - 1;\r\n j <- 0 to n) {\r\n if ((a == i || b == i)\r\n && (c == j || d == j))\r\n print(\"*\")\r\n else {\r\n if (j == n)\r\n print(\"\\n\")\r\n else\r\n print(\".\")\r\n }\r\n }\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val t = StdIn.readLine().toInt\r\n (1 to t) foreach {\r\n _ => test()\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object cf1512 {\n\n def readInt(): Int = {\n\t\tConsole.in.readLine().toInt\n\t}\n\n\tdef readInts(): Array[Int] = {\n\t\tval line = Console.in.readLine()\n\t\tline.split(' ').map( _.toInt)\n\t}\n\n\tdef main(args: Array[String]): Unit = {\n\t\tval cases = readInt()\n\t\tvar nCase = 0\n\t\tfor (nCase <- 1 to cases) {\n\t\t\tval n = readInt()\n\t\t\tvar nLine = 0\n\t\t\tvar x1 = 0\n\t\t\tvar y1 = 0\n\t\t\tvar x2 = 0\n\t\t\tvar y2 = 0\n\n\t\t\tfor (nLine <- 0 to n-1) {\n\t\t\t\tvar line = Console.in.readLine()\n\t\t\t\tval x = line.indexOf('*')\n\t\t\t\tif (x > -1) {\n\t\t\t\t\tx1 = x2\n\t\t\t\t\ty1 = y2\n\t\t\t\t\tx2 = x\n\t\t\t\t\ty2 = nLine\n\t\t\t\t\tline = line.substring(x+1)\n\t\t\t\t\tval x3 = line.indexOf('*')\n\t\t\t\t\tif (x3 > -1) {\n\t\t\t\t\t\tx1 = x3+x2+1\n\t\t\t\t\t\ty1 = nLine\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar minx = if (x1 < x2) x1 else x2\n\t\t\tvar miny = if (y1 < y2) y1 else y2\n\t\t\tval width = if (x1 != x2) Math.abs(x1-x2) else 1\n\t\t\tval height = if (y1 != y2) Math.abs(y1-y2) else 1\n\n\t\t\tminx = if (x1 == x2 && (x1>= width)) x1-width else minx\n\t\t\tminy = if (y1 == y2 && (y1 >= height)) y1-height else miny\n\n\t\t\tfor (nLine <- 0 to n-1) {\n\t\t\t\tvar nCol = 0\n\t\t\t\tfor (nCol <- 0 to n-1) {\n\t\t\t\t\tif ( (nLine == miny || nLine == miny+height) && (nCol == minx || nCol == minx+width) ) {\n\t\t\t\t\t\t\tprint('*')\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprint('.')\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tprintln()\n\t\t\t}\n\n\t\t}\n\t} \n}\n"}], "negative_code": [{"source_code": "object cf1512 {\n\n def readInt(): Int = {\n\t\tConsole.in.readLine().toInt\n\t}\n\n\tdef readInts(): Array[Int] = {\n\t\tval line = Console.in.readLine()\n\t\tline.split(' ').map( _.toInt)\n\t}\n\n\tdef main(args: Array[String]): Unit = {\n\t\tval cases = readInt()\n\t\tvar nCase = 0\n\t\tfor (nCase <- 1 to cases) {\n\t\t\tval n = readInt()\n\t\t\tvar nLine = 0\n\t\t\tvar x1 = 0\n\t\t\tvar y1 = 0\n\t\t\tvar x2 = 0\n\t\t\tvar y2 = 0\n\n\t\t\tfor (nLine <- 0 to n-1) {\n\t\t\t\tvar line = Console.in.readLine()\n\t\t\t\tval x = line.indexOf('*')\n\t\t\t\tif (x > -1) {\n\t\t\t\t\tx1 = x2\n\t\t\t\t\ty1 = y2\n\t\t\t\t\tx2 = x\n\t\t\t\t\ty2 = nLine\n\t\t\t\t\tline = line.substring(x+1)\n\t\t\t\t\tval x3 = line.indexOf('*')\n\t\t\t\t\tif (x3 > -1) {\n\t\t\t\t\t\tx2 = x3+x1+1\n\t\t\t\t\t\ty2 = nLine\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar minx = if (x1 < x2) x1 else x2\n\t\t\tvar miny = if (y1 < y2) y1 else y2\n\t\t\tval width = if (x1 != x2) Math.abs(x1-x2) else 1\n\t\t\tval height = if (y1 != y2) Math.abs(y1-y2) else 1\n\n\t\t\tminx = if (x1 == x2 && (x1>= width)) x1-width else minx\n\t\t\tminy = if (y1 == y2 && (y1 >= height)) y1-height else miny\n\n\t\t\tfor (nLine <- 0 to n-1) {\n\t\t\t\tvar nCol = 0\n\t\t\t\tfor (nCol <- 0 to n-1) {\n\t\t\t\t\tif ( (nLine == miny || nLine == miny+height) && (nCol == minx || nCol == minx+width) ) {\n\t\t\t\t\t\t\tprint('*')\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprint('.')\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tprintln()\n\t\t\t}\n\n\t\t}\n\t} \n}\n"}], "src_uid": "d8fb3822b983b8a8ffab341aee74f56f"} {"source_code": "object _1249C1 extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val good = (0 to (1<<10)).map(i => Integer.parseInt(i.toBinaryString, 3)).toArray\n repeat(io.read[Int]) {\n val n = io.read[Int]\n var idx = java.util.Arrays.binarySearch(good, n)\n if (idx < 0) idx = -idx - 1\n val ans = good(idx)\n io.writeLine(ans)\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Hello extends App {\n\n def solve(n: Long): Long = {\n val s = java.lang.Long.toString(n, 3)\n val goodNumber: String = s.indexOf('2') match {\n case -1 => s\n case pos2 => (pos2 - 1 to 0 by -1).find(i => s(i) == '0') match {\n case None => \"1\" + \"0\" * s.length\n case Some(pos0) =>\n val suffixLength = s.length - pos0 - 1\n s.substring(0, pos0) + \"1\" + (\"0\" * suffixLength)\n }\n }\n java.lang.Long.valueOf(goodNumber, 3)\n }\n\n val q = StdIn.readLine().toInt\n val queries = Iterator.continually(StdIn.readLine().toLong).take(q)\n queries.map(solve).foreach(println)\n}"}, {"source_code": "object Solution extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val q = io.read[Int]\n for (i <- 0 until q) {\n val n = io.read[Long]\n var power:Long = (1)\n while(power <= n) {\n power = power * 3\n }\n var ans = power\n var cur = power\n var value:Long = 0\n while(cur != 0) {\n var digit = (n / cur) % 3\n if(digit == 0) {\n if(value + cur >= n && value + cur < ans) ans = cur + value\n } else if(digit == 1) {\n value = value + cur\n } else {\n // do nothing\n }\n cur /= 3\n }\n if(value == n) {\n ans = n\n }\n io.writeLine(ans)\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}"}, {"source_code": "object _1249C1 extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n import java.lang.{Long => JLong}\n\n val good = (0 to (1<<9)).map(i => JLong.parseLong(i.toBinaryString, 3)).toArray\n debug(good.reverse.toList.take(10))\n\n repeat(io.read[Int]) {\n val n = io.read[Long]\n val base3 = \"0\" + java.lang.Long.toString(n, 3)\n\n val ans = if (base3.contains(\"2\")) {\n val t = base3.indexOf(\"2\")\n val z = base3.substring(0, t).lastIndexOf(\"0\")\n val b3 = base3.substring(0, z) + \"1\" + (\"0\" * (base3.length - z - 1))\n JLong.parseLong(b3, 3)\n } else {\n n\n }\n io.writeLine(ans)\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Solution extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val q = io.read[Int]\n for (i <- 0 until q) {\n val n = io.read[Long]\n var power:Long = (1)\n while(power <= n) {\n power = power * 3\n }\n var ans = power\n var cur = power\n var value:Long = 0\n while(cur != 0) {\n var digit = (n / cur) % 3\n if(digit == 0) {\n if(value + cur >= n && value + cur < ans) ans = cur + value\n } else if(digit == 1) {\n value = value + cur\n } else {\n // do nothing\n }\n cur /= 3\n }\n if(value == n) {\n ans = n\n }\n io.writeLine(ans)\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}"}], "negative_code": [], "src_uid": "5953b898995a82edfbd42b6c0f7138af"} {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject TheChildAndToy {\n case class Pair(u:Int,w:Int) extends Ordered[Pair]{\n override def compare(that: Pair): Int = {\n this.w compare that.w\n }\n }\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n val arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n val weight=in.readLine().split(\" \").map(_.toInt)\n val graph=Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())\n for(i<- 0 until m){\n val edge=in.readLine().split(\" \").map(_.toInt-1)\n graph(edge(0))+=edge(1)\n graph(edge(1))+=edge(0)\n }\n val rem=Array.ofDim[Int](n)\n //val pq=PriorityQueue[Pair]()\n for(i<- 0 until graph.length){\n var w=0\n for(j<- 0 until graph(i).length) {\n w+=weight(graph(i)(j))\n }\n rem(i)=w\n //pq.enqueue(Pair(i,w))\n }\n\n var sum=0\n for(i<- 0 until n){\n val u=getMin(rem,weight)\n sum+=rem(u)\n rem(u)= -1\n for(v<- 0 until graph(u).length){\n if(rem(graph(u)(v))!= -1){\n rem(graph(u)(v))-=weight(u)\n }\n }\n }\n println(sum)\n }\n def getMin(rem:Array[Int],weight:Array[Int]):Int={\n var max=Int.MinValue\n var minInd= -1\n for(i<- 0 until rem.length if(rem(i)!= -1)){\n if(weight(i)>max){\n max=weight(i)\n minInd=i\n }\n }\n return minInd\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n println((1 to m).foldLeft(0) {\n case (acc, _) =>\n val Array(from, to) = in.next().split(' ').map(_.toInt - 1)\n acc + Math.min(data(from), data(to))\n })\n}\n"}, {"source_code": "object C437 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val vi = readInts(n).zipWithIndex.map {\n case (value, idx) =>\n (idx, value)\n }.toMap\n val orderToProcess =\n vi.toArray\n .sortBy {\n case (_, x) => -x\n }\n .map { _._1 }\n val graph = Array.fill(n)(cu.Set.empty[Int])\n for (_ <- 1 to m) {\n val Array(x, y) = readInts(2).map(_ - 1)\n graph(x).add(y)\n graph(y).add(x)\n }\n def remove(node: Int): Int = {\n var score = 0\n val nodes = graph(node)\n for (n <- nodes) {\n score += vi(n)\n graph(n).remove(node)\n }\n graph(node).clear()\n score\n }\n var res = 0\n for (node <- orderToProcess) {\n res += remove(node)\n }\n out.println(res)\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [], "src_uid": "2e6bf9154d9da6ac134b52144d5322ca"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val X = nl()\n\n val a = X - 2\n val (i, j, k) = if (a % 3 == 0) {\n (1, 2, a - 1)\n } else {\n (1, 1, a)\n }\n\n out.println(s\"$i $j $k\")\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}", "positive_code": [{"source_code": "object CF511A extends App {\n\n import scala.io.StdIn\n\n val n = StdIn.readInt\n var (a, b, c) = (1, 1, n-2)\n\n if (c % 3 == 0) {\n c -= 1\n a += 1\n }\n\n println(a + \" \" + b + \" \" + c)\n}\n"}, {"source_code": "object Loves3 {\n def main(args: Array[String]): Unit = {\n val n=scala.io.StdIn.readInt()\n var i=0 \n var j=0\n var k=0\n for(i <- 1 to n-2)\n for(j <- 1 to n-1-i){\n k=n-i-j\n if(i%3!=0 && j%3!=0 && k%3!=0){\n println(i+\" \"+j+\" \"+k)\n System.exit(0)\n }\n }\n }\n}"}, {"source_code": "\nimport scala.io.StdIn\n\nobject LittleCLoves3Main {\n def main(args: Array[String]){\n val n = StdIn.readInt()\n val p = n/3\n val tt = p%3\n val resFaltante = n%3\n\n print(matches(resFaltante, p,tt))\n }\n\n def matches(x:Int, p: Int, tt: Int): String = {\n if(x == 1) {\n if(tt == 0){\n return \"\"+(p -1) + \" \" + (p + 1) + \" \" + (p + 1)\n }\n\n if( (p + 1) % 3 != 0 )\n return p + \" \" + p + \" \" + (p + 1)\n else return p + \" \" + (p + 2) + \" \" + (p - 1)\n }\n if(x == 2) {\n if(tt == 0){\n return (p -1) + \" \" + (p + 2) + \" \" + (p + 1)\n }\n if((p + 2) % 3 != 0)\n return p + \" \" + p + \" \" + (p + 2)\n else return p + \" \" + (p + 1) + \" \" + (p + 1)\n }\n if(x == 0 && tt == 0){\n return (p+1) + \" \" + (p-2) + \" \" + (p+1)\n }\n return p + \" \" + p + \" \" + p\n\n }\n}\n"}], "negative_code": [{"source_code": "\n\nimport scala.io.StdIn\n\nobject LittleCLoves3Main {\n def main(args: Array[String]){\n val n = StdIn.readInt()\n val p = n/3\n val tt = p%3\n val resFaltante = n%3\n\n print(matches(resFaltante, p,tt))\n }\n\n def matches(x:Int, p: Int, tt: Int): String = {\n if(x == 1) {\n if(tt == 0){\n\n return \"\"+(p -1) + \" \" + (p + 1) + \" \" + (p + 1)\n }\n\n if( (p + 1) % 3 != 0 )\n return p + \" \" + p + \" \" + (p + 1)\n else return p + \" \" + (p + 2) + \" \" + (p - 1)\n }\n if(x == 2) {\n if(tt == 0){\n return (p -1) + \" \" + (p + 1) + \" \" + (p + 1)\n }\n if((p + 2) % 3 != 0)\n return p + \" \" + p + \" \" + (p + 2)\n else return p + \" \" + (p + 1) + \" \" + (p + 1)\n }\n if(x == 0 && tt == 0){\n return (p+1) + \" \" + (p-2) + \" \" + (p+1)\n }\n return p + \" \" + p + \" \" + p\n\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject LittleCLoves3Main {\n def main(args: Array[String]){\n val n = StdIn.readInt()\n val p = n/3\n val pp = n%3\n val t = p/3\n val tt = p%3\n val resFaltante = if (t > 0) tt else 4\n print(matches(resFaltante, p))\n }\n\n def matches(x:Int, p: Int): String = x match{\n case 0 => (p - 1) + \" \" + (p - 1 ) + \" \" + (p + 2)\n case 1 => p + \" \" + p + \" \" + (p + 1)\n case 2 => p + \" \" + p + \" \" + (p + 2)\n case 4 => p + \" \" + p + \" \" + p\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject LittleCLoves3Main {\n def main(args: Array[String]){\n val n = StdIn.readInt()\n val p = n/3\n val resFaltante = n%3\n print(matches(resFaltante, p))\n }\n\n def matches(x:Int, p: Int): String = x match{\n case 0 => p + \" \" + p + \" \" + p\n case 1 => {\n if((p + 1)%3 != 0 )\n p + \" \" + p + \" \" + (p + 1)\n else p + \" \" + (p + 2) + \" \" + (p - 1)\n }\n case 2 => {\n if((p + 2) % 3 != 0)\n p + \" \" + p + \" \" + (p + 2)\n else p + \" \" + (p + 1) + \" \" + (p + 1)\n }\n }\n}\n"}, {"source_code": "\n\nimport scala.io.StdIn\n\nobject LittleCLoves3Main {\n def main(args: Array[String]){\n val n = StdIn.readInt()\n val p = n/3\n val tt = p%3\n val resFaltante = n%3\n print(\"residuo de tt:\" + tt)\n\n\n print(matches(resFaltante, p,tt))\n }\n\n def matches(x:Int, p: Int, tt: Int): String = {\n if(x == 1) {\n if(tt == 0){\n return \"\"+(p -1) + \" \" + (p + 1) + \" \" + (p + 1)\n }\n\n if( (p + 1) % 3 != 0 )\n return p + \" \" + p + \" \" + (p + 1)\n else return p + \" \" + (p + 2) + \" \" + (p - 1)\n }\n if(x == 2) {\n if(tt == 0){\n return (p -1) + \" \" + (p + 2) + \" \" + (p + 1)\n }\n if((p + 2) % 3 != 0)\n return p + \" \" + p + \" \" + (p + 2)\n else return p + \" \" + (p + 1) + \" \" + (p + 1)\n }\n if(x == 0 && tt == 0){\n return (p+1) + \" \" + (p-2) + \" \" + (p+1)\n }\n return p + \" \" + p + \" \" + p\n\n }\n}\n"}, {"source_code": "\n\nimport scala.io.StdIn\n\nobject LittleCLoves3Main {\n def main(args: Array[String]){\n val n = StdIn.readInt()\n val p = n/3\n val tt = p%3\n val resFaltante = n%3\n\n print(matches(resFaltante, p,tt))\n }\n\n def matches(x:Int, p: Int, tt: Int): String = {\n if(x == 1) {\n if(tt == 0){\n\n return \"\"+(p -1) + \" \" + (p + 1) + \" \" + (p + 1)\n }\n\n if( (p + 1) % 3 != 0 )\n return p + \" \" + p + \" \" + (p + 1)\n else return p + \" \" + (p + 2) + \" \" + (p - 1)\n }\n if(x == 2) {\n if(tt == 0){\n return (p -1) + \" \" + (p + 1) + \" \" + (p + 1)\n }\n if((p + 2) % 3 != 0)\n return p + \" \" + p + \" \" + (p + 2)\n else return p + \" \" + (p + 1) + \" \" + (p + 1)\n }\n return p + \" \" + p + \" \" + p\n }\n}\n"}, {"source_code": "object CF511A extends App {\n\n import scala.io.StdIn\n\n val n = StdIn.readInt\n var (a, b, c) = (n / 3, n / 3, n / 3 + n % 3)\n\n if (a%3 == 0) {\n a -= 1\n b += 1\n }\n if (b%3 == 0) {\n b -= 1\n c += 1\n }\n if (c%3 == 0) {\n c -= 1\n a += 1\n }\n\n println(a + \" \" + b + \" \" + c)\n}\n"}], "src_uid": "91d5147fb602298e08cbdd9f86d833f8"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val t = in.next().toInt\n var oldNew = Map.empty[String, String]\n var newOne = Map.empty[String, String]\n (1 to t).foreach { _ =>\n val Array(old, new_) = in.next().split(\" \")\n if (newOne.contains(old)) {\n val oldOld = newOne(old)\n oldNew += oldOld -> new_\n newOne += new_ -> oldOld\n } else {\n oldNew += old -> new_\n newOne += new_ -> old\n }\n }\n println(oldNew.size)\n println(oldNew.map(i => s\"${i._1} ${i._2}\").mkString(\"\\n\"))\n\n}", "positive_code": [{"source_code": "\nimport scala.math._\nimport scala.collection.mutable\nimport scala.util.control.Breaks\nimport scala.annotation.tailrec\n\nobject Problem extends App {\n import Scanner._\n\n val oldNames, allNames = mutable.HashSet[String]()\n val names = mutable.HashMap[String, String]()\n for(i <- 1 to readInt) {\n val (a, b) = (readString, readString)\n if(!allNames.contains(a)) {\n oldNames.add(a)\n allNames.add(a)\n }\n allNames.add(b)\n names.put(a, b)\n }\n \n def findName(name: String): String = names.get(name).map(findName(_)).getOrElse(name)\n \n println(oldNames.size)\n for(name <- oldNames)\n println(s\"$name ${findName(name)}\")\n}\n\ncase class Memo[A, B](f: A => B) extends (A => B) {\n private val cache = mutable.Map[A, B]()\n def apply(x: A) = cache getOrElseUpdate (x, f(x))\n}\n\nobject Scanner {\n def readInt() = {\n var acc = 0\n readWith {\n case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n }\n acc\n }\n def readLong() = {\n var acc = 0L\n readWith {\n case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10L) + (c - '0')\n }\n acc\n }\n def readDouble() = {\n var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)\n readWith {\n case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>\n frac = (frac * 10) + (c - '0')\n fracPow *= 10\n case c if c == '.' && !readFrac =>\n readFrac = true\n }\n acc + (frac.toDouble / fracPow)\n }\n def readString() = {\n var string = new StringBuilder\n readWith { case c => string += c }\n string.toString\n }\n def readLine() = Console.in.readLine()\n def readChar() = Console.in.read().toChar\n def readWith(func: PartialFunction[Char, Unit]) {\n val handler = func orElse[Char, Unit] {\n case _ => throw new java.io.IOException(\"unexpected token\")\n }\n\n var c = readChar\n while(c.isWhitespace)\n c = readChar\n\n while(!c.isWhitespace) {\n handler(c)\n\n c = readChar\n }\n }\n}\n\n"}, {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nobject B_Misha_and_Changing_Handles {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextInt()\n\n val requests = for (i <- 1 to n) yield {\n (scanner.next(), scanner.next())\n }\n\n def processRequest (requests : List[(String, String)], acc: Map[String, Item] = Map()) : Map[String, Item] = {\n requests match {\n case (old_name, new_name) :: tail if acc contains old_name => {\n val old_item = acc(old_name)\n val new_item = new Item(old_item.initial, new_name)\n processRequest(tail, acc - old_name + (new_name -> new_item))\n }\n case (old_name, new_name) :: tail => {\n val new_item = new Item(old_name, new_name)\n processRequest(tail, acc + (new_name -> new_item))\n }\n case Nil => acc\n }\n }\n\n val map = processRequest(requests.toList)\n\n out.println(map.size)\n for (res <- map.toSeq.sortBy(x => x._2.initial)) {\n out.println(s\"${res._2.initial} ${res._2.current}\")\n }\n }\n\n case class Item(initial : String, current : String) {\n }\n}\n"}, {"source_code": "object Main extends App {\n val n = readInt\n val init = (Map[String, String](), Map[String, String]())\n val (mapping, _) = (1 to n).foldLeft(init)({\n case ((forward, backword), _) => {\n val Array(prev, next) = readLine.split(\" \").filterNot(_ == \"\")\n backword.get(prev) match {\n case Some(name) =>\n (forward + (name -> next), backword + (next -> name))\n case None =>\n (forward + (prev -> next), backword + (next -> prev))\n }\n }\n })\n println(mapping.size)\n mapping foreach {\n case (from, to) => println(from + \" \" + to)\n }\n}"}], "negative_code": [{"source_code": "object Main extends App {\n val n = readInt\n val init = (Map[String, String](), Map[String, String]())\n val (mapping, _) = (1 to n).foldLeft(init)({\n case ((forward, backword), _) => {\n val Array(prev, next) = readLine.split(\" \").filterNot(_ == \"\")\n backword.get(prev) match {\n case Some(name) =>\n (forward + (name -> next), backword + (next -> name))\n case None =>\n (forward + (prev -> next), backword + (next -> prev))\n }\n }\n })\n mapping foreach {\n case (from, to) => println(from + \" \" + to)\n }\n}"}], "src_uid": "bdd98d17ff0d804d88d662cba6a61e8f"} {"source_code": "import scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val t = readInt\n (0 until t).foreach { m =>\n val n = readInt\n val arr = readLine.split(\" \").map(_.toInt)\n val l = readLine.split(\" \").map(_.toInt)\n val unlocked = (arr zip l).filter(x => x._2 == 0).map(_._1).sortBy(x => -x)\n var k = -1\n val result: Array[Int] = arr.zipWithIndex.map { case (e, i) =>\n if (l(i) == 0) {\n k += 1\n unlocked(k)\n } else {\n e\n }\n }\n println(result.mkString(\" \"))\n }\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n val ln = readLine().split(\" \").map(_.toInt)\n\n val bn = (an zip ln).collect { case (a, 0) => a }.sorted\n val cn = (an zip ln)\n .foldRight((List.empty[Int], 0)) {\n case ((a, 1), (ck, i)) => (a :: ck, i)\n case ((_, 0), (ck, i)) => (bn(i) :: ck, i + 1)\n }\n ._1\n\n println(cn.mkString(\" \"))\n }\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n val ln = readLine().split(\" \").map(_.toInt)\n\n val bn = (an zip ln).collect { case (a, 0) => a }.sorted(Ordering.Int.reverse)\n var i = -1\n val ans = (an zip ln).map {\n case (a, 0) => i += 1; bn(i)\n case (a, 1) => a\n }\n\n println(ans.mkString(\" \"))\n\n }\n}\n"}], "negative_code": [], "src_uid": "9ef180b33717e4d6a21b4c5bb855e15b"} {"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var n = readInt;\n var list = List[(Int, Int)]();\n for (i <- 0 until n) {\n var Array(x, d) = readLine.split(\" \").map(_.toInt)\n list = (x, d) :: list;\n }\n for (e <- list) {\n if (list.exists(p => p._1 == (e._1 + e._2) && e._1 == (p._1 + p._2))) {\n println(\"YES\");\n return;\n }\n }\n println(\"NO\");\n }\n\n}", "positive_code": [{"source_code": "object P029A extends App {\n val n = readInt\n var pos = (for (i <- 0 to n-1) yield 0) toArray\n var target = (for (i <- 0 to n-1) yield 0) toArray\n var lookup = collection.mutable.Map[Int, Int]()\n for (i <- 0 to n-1) {\n var elems = readLine.split(' ').map(x => x.toInt)\n pos(i) = elems(0)\n target(i) = elems(0) + elems(1)\n lookup += ((pos(i), i))\n }\n println(if ((0 to n-1).exists(x => lookup.contains(target(x)) && lookup.get(target(lookup(target(x)))).getOrElse(null) == x)) \"YES\" else \"NO\")\n}\n"}], "negative_code": [], "src_uid": "d7dc61a8f3b0091320b96cedd1f4f0a7"} {"source_code": "object Main {\r\n\r\n def main(args:Array[String]): Unit = {\r\n var t = io.StdIn.readInt()\r\n\r\n def loopts(ts: Int){\r\n if ( ts < t ){ \r\n var Array(s1, s2) = io.StdIn.readLine().split(\" \").map(_.reverse)\r\n if ( s1 == s2 )\r\n println(\"=\")\r\n else {\r\n if ( s1 < s2 ){\r\n if ( s1(0) != s2(0) || s1(0) == 'S' )\r\n println(\">\")\r\n else\r\n println(\"<\")\r\n }\r\n else {\r\n if ( s1(0) != s2(0) || s1(0) == 'S' )\r\n println(\"<\")\r\n else\r\n println(\">\")\r\n }\r\n }\r\n loopts(ts+1)\r\n }\r\n }\r\n \r\n loopts(0)\r\n }\r\n \r\n}", "positive_code": [{"source_code": "object _1741A extends CodeForcesApp {\n override def solve(io: IO) = io.repeat() {\n val a, b = io.nextStr()\n val ans = hash(a).compareTo(hash(b)) match {\n case 1 => \">\"\n case -1 => \"<\"\n case _ => \"=\"\n }\n io.printLine(ans)\n }\n\n def hash(s: String) = {\n val f = if (s.contains(\"M\"))\n 0\n else if (s.contains(\"S\"))\n -1\n else\n 1\n f*(1+s.count(_ == 'X'))\n }\n}\n/**************************** [Ignore Template Below] **************************************/\ntrait CodeForcesApp {\n def debug(x: => Any): Unit = if (!sys.props.contains(\"ONLINE_JUDGE\")) println(s\">>> DEBUG: $x\")\n def run(io: IO): Unit = try solve(io) finally io.close()\n def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))\n def solve(io: IO): Any\n}\n// Java I/O wrapper\nimport java.io._\nclass IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {\n def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))\n\n val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))\n\n def nextLine(): String = in.readLine()\n def nextStr(): String = tokens.next()\n def nextInt(): Int = nextStr().toInt\n def nextLong(): Long = nextStr().toLong\n def nextDouble(): Double = nextStr().toDouble\n def nextBool(): Boolean = nextInt() == 1\n def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }\n\n def print(xs: Any*): this.type = { out.print(xs.mkString(\" \")); this }\n def printLine(xs: Any*): this.type = { out.println(xs.mkString(\" \")); this }\n def printLines(xs: Any*): this.type = { if (xs.isEmpty) out.println() else xs.foreach(out.println); this }\n\n override def close() = out.close()\n}\n"}], "negative_code": [{"source_code": "object Main {\r\n\r\n def main(args:Array[String]): Unit = {\r\n var t = io.StdIn.readInt()\r\n\r\n def loopts(ts: Int){\r\n if ( ts < t ){ \r\n var Array(s1, s2) = io.StdIn.readLine().split(\" \").map(_.reverse)\r\n if ( s1 == s2 )\r\n println(\"=\")\r\n else {\r\n if ( s1 < s2 ){\r\n if ( s1(0) == 'S' && s2(0) == 'S' )\r\n println(\">\")\r\n else\r\n println(\"<\")\r\n }\r\n else {\r\n if ( s1(0) == 'L' && s2(0) == 'L' )\r\n println(\">\")\r\n else\r\n println(\"<\")\r\n }\r\n }\r\n loopts(ts+1)\r\n }\r\n }\r\n \r\n loopts(0)\r\n }\r\n \r\n}"}, {"source_code": "object Main {\r\n\r\n def main(args:Array[String]): Unit = {\r\n var t = io.StdIn.readInt()\r\n\r\n def loopts(ts: Int){\r\n if ( ts < t ){ \r\n var Array(s1, s2) = io.StdIn.readLine().split(\" \").map(_.reverse)\r\n if ( s1 == s2 )\r\n println(\"=\")\r\n else {\r\n if ( s1 < s2 ){\r\n if ( s1(0) == 'S' && s2(0) == 'S' )\r\n println(\"<\")\r\n else\r\n println(\">\")\r\n }\r\n else {\r\n if ( s1(0) == 'L' && s2(0) == 'L' )\r\n println(\">\")\r\n else\r\n println(\"<\")\r\n }\r\n }\r\n loopts(ts+1)\r\n }\r\n }\r\n \r\n loopts(0)\r\n }\r\n \r\n}"}], "src_uid": "3ea3f5b548b82449e4ce86e11b1afc48"} {"source_code": "object firstdemo extends App {\r\n\r\n def readString() : String = {\r\n val yo = scala.io.StdIn.readLine()\r\n yo\r\n }\r\n def readInt() : Int = {\r\n val yo = scala.io.StdIn.readInt();\r\n yo\r\n }\r\n\r\n var t = readInt()\r\n\r\n while(t > 0) {\r\n\r\n\r\n val Array(x , y) = readString().split(\" \")\r\n val n = x.toInt\r\n val k = y.toInt\r\n val list = readString().split(\" \")\r\n val array = list.map(e => e.toInt)\r\n val yo = array.sortBy(e => e)\r\n var mx = 0\r\n for(e <- yo){\r\n mx = mx max e\r\n }\r\n val yy = yo(0) + yo(1)\r\n // println(mx + \" \" + k + \" \" + yy)\r\n if(mx <= k || yy <= k)\r\n println(\"YES\")\r\n else {\r\n println(\"NO\")\r\n }\r\n t = t - 1\r\n\r\n }\r\n\r\n}\r\n", "positive_code": [{"source_code": "object HelloWorld {\r\n def main(args: Array[String]) = {\r\n var t = scala.io.StdIn.readInt()\r\n while (t > 0) {\r\n val Array(n, d) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\r\n var min1 = 1e9\r\n var min2 = 1e9\r\n var A = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\r\n var ok = true\r\n for (i <- 0 until n) {\r\n var x = A(i)\r\n if (x <= min1) {\r\n min2 = min1\r\n min1 = x\r\n } else if (x <= min2) {\r\n min2 = x\r\n }\r\n if (x > d)\r\n ok = false\r\n }\r\n if (ok || min1 + min2 <= d)\r\n println(\"YES\")\r\n else println(\"NO\")\r\n t -= 1\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "044c2a3bafe4f47036ee81f2e40f639a"} {"source_code": "object CF506B extends App {\n import scala.io.StdIn\n StdIn.readLine\n val problems = StdIn.readLine.split(' ').map(_.toInt)\n\n var i = 0\n var max = 0\n var count = 0\n var difficulty = -1\n while (i < problems.length) {\n if (difficulty == -1 || problems(i) <= difficulty * 2) {\n count += 1\n if (count > max)\n max = count\n difficulty = problems(i)\n i += 1\n } else {\n count = 0\n difficulty = -1\n }\n }\n\n println(max)\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N = sc.nextInt()\n val A = map(N)(_ => sc.nextInt())\n\n var mx = 0\n var cnt = 0\n rep(N - 1) { i =>\n if (A(i + 1) <= A(i) * 2) {\n cnt += 1\n mx = max(mx, cnt)\n }\n else cnt = 0\n }\n\n out.println(mx + 1)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject B extends App {\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n\n var maxLen = 1\n var curLen = 1\n var left = in.nextInt\n\n for (_ <- 1 until n) {\n val right = in.nextInt\n if (left * 2 >= right) {\n curLen = curLen + 1\n } else {\n maxLen = Math.max(maxLen, curLen)\n curLen = 1\n }\n left = right\n }\n\n maxLen = Math.max(maxLen, curLen)\n println(maxLen)\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n \n def nextLong: Long = {\n next.toLong\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}\n"}, {"source_code": "//package com.test.tasks\n\nobject Context extends App {\n import scala.io.StdIn._\n\n readInt()\n print(maxContext(readLine().split(\" \").map(_.toInt).toList))\n\n def maxContext(diffs: List[Int]): Int = {\n def loop(diffs: List[Int], last: Int, max: Int, cur: Int): Int = diffs match {\n case Nil => Math.max(max, cur)\n case x :: xs =>\n if (x <= last * 2) loop(xs, x, max, cur+1)\n else loop(xs, x, if (cur > max) cur else max, 1)\n }\n loop(diffs.tail, diffs.head, 1, 1)\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject B extends App {\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val a: Array[Int] = Array.fill(n)(in.nextInt)\n var ans = 1\n var maxAns = 1\n (1 until n).foreach { i =>\n if (a(i) <= a(i - 1) * 2) {\n ans += 1\n maxAns = math.max(maxAns, ans)\n } else\n ans = 1\n }\n println(maxAns)\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toInt\n }\n\n def nextLong: Double = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}, {"source_code": "//package com.test.tasks\n\nobject HelloWorld1 extends App {\n import scala.io.StdIn._\n\n readInt()\n print(maxContext(readLine().split(\" \").map(_.toInt).toList))\n\n def maxContext(diffs: List[Int]): Int = {\n def loop(diffs: List[Int], last: Int, max: Int, cur: Int): Int = diffs match {\n case Nil => Math.max(max, cur)\n case x :: xs =>\n if (x <= last * 2) loop(xs, x, max, cur+1)\n else loop(xs, x, if (cur > max) cur else max, 1)\n }\n loop(diffs.tail, diffs.head, 1, 1)\n }\n\n}\n\nobject HelloWorld2 extends App {\n import scala.io.StdIn._\n\n readInt()\n print(maxContext(readLine().split(\" \").map(_.toInt).toList))\n\n def maxContext(diffs: List[Int]): Int = {\n def loop(diffs: List[Int], last: Int, max: Int, cur: Int): Int = diffs match {\n case Nil => Math.max(max, cur)\n case x :: xs =>\n if (x <= last * 2) loop(xs, x, max, cur+1)\n else loop(xs, x, if (cur > max) cur else max, 1)\n }\n loop(diffs.tail, diffs.head, 1, 1)\n }\n\n}"}, {"source_code": "//package com.test.tasks\n\nobject HelloWorld extends App {\n import scala.io.StdIn._\n\n readInt()\n print(maxContext(readLine().split(\" \").map(_.toInt).toList))\n\n def maxContext(diffs: List[Int]): Int = {\n def loop(diffs: List[Int], last: Int, max: Int, cur: Int): Int = diffs match {\n case Nil => Math.max(max, cur)\n case x :: xs =>\n if (x <= last * 2) loop(xs, x, max, cur+1)\n else loop(xs, x, if (cur > max) cur else max, 1)\n }\n loop(diffs.tail, diffs.head, 1, 1)\n }\n\n}"}], "negative_code": [{"source_code": "//package com.test.tasks\n\nobject HelloWorld1 extends App {\n import scala.io.StdIn._\n\n readInt()\n print(1)\n\n def maxContext(diffs: List[Int]): Int = {\n def loop(diffs: List[Int], last: Int, max: Int, cur: Int): Int = diffs match {\n case Nil => Math.max(max, cur)\n case x :: xs =>\n if (x <= last * 2) loop(xs, x, max, cur+1)\n else loop(xs, x, if (cur > max) cur else max, 1)\n }\n loop(diffs.tail, diffs.head, 1, 1)\n }\n\n}\n\nobject HelloWorld2 extends App {\n import scala.io.StdIn._\n\n readInt()\n print(2)\n\n def maxContext(diffs: List[Int]): Int = {\n def loop(diffs: List[Int], last: Int, max: Int, cur: Int): Int = diffs match {\n case Nil => Math.max(max, cur)\n case x :: xs =>\n if (x <= last * 2) loop(xs, x, max, cur+1)\n else loop(xs, x, if (cur > max) cur else max, 1)\n }\n loop(diffs.tail, diffs.head, 1, 1)\n }\n\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject B extends App {\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val arr = new Array[Int](n)\n\n for (i <- 0 until n) {\n arr(i) = in.nextInt\n }\n\n var maxLen = 1\n var curLen = 1\n var left = arr(0)\n\n for (i <- 1 until n) {\n if (left * 2 >= arr(i)) {\n curLen = curLen + 1\n } else {\n maxLen = Math.max(maxLen, curLen)\n curLen = 1\n left = arr(i)\n }\n }\n\n maxLen = Math.max(maxLen, curLen)\n println(maxLen)\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n \n def nextLong: Long = {\n next.toLong\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}\n"}, {"source_code": "//package com.test.tasks\n\nimport scala.annotation.tailrec\n\nobject Context extends App {\n import scala.io.StdIn._\n\n readInt()\n val diffs = readLine().split(\" \").map(_.toInt).toList\n\n print(maxContext(diffs.tail, 1, 1, diffs.head))\n\n @tailrec\n def maxContext(diffs: List[Int], max: Int, cur: Int, y: Int): Int = diffs match {\n case Nil => max\n case x :: xs =>\n if (y * 2 < x) maxContext(xs, if (max < cur) cur else max, 1, x)\n else maxContext(xs, max, cur+1, x)\n }\n\n}\n"}], "src_uid": "5088d1d358508ea3684902c8e32443a3"} {"source_code": "import java.util.Scanner\n\nimport scala.collection.immutable\n\nobject A extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val a: Array[Array[Int]] = Array.ofDim(n, n)\n for(i <- 0 until n; j <- 0 until n) {\n a(i)(j) = sc.nextInt()\n }\n\n val isValid = for {\n i <- 0 until n\n j <- 0 until n\n if a(i)(j) != 1\n } yield genPairs(i, j, n).exists {\n case ((x1, y1), (x2, y2)) =>\n a(x1)(y1) + a(x2)(y2) == a(i)(j)\n }\n\n if (isValid.forall(_ == true)) {\n println(\"Yes\")\n } else {\n println(\"No\")\n }\n\n def genPairs(i: Int, j: Int, n: Int): Seq[((Int, Int), (Int, Int))] = {\n val col = (0 until n).map(x => (x,j)).filterNot(p => p._1 == i && p._2 == j)\n val row = (0 until n).map(y => (i,y)).filterNot(p => p._1 == i && p._2 == j)\n for {\n c <- col\n r <- row\n } yield (c, r)\n }\n}\n", "positive_code": [{"source_code": "object zero extends App {\n\n val n: Int = scala.io.StdIn.readInt()\n\n val square: Array[Array[Int]] = Array.ofDim(n, n)\n\n for (i <- 0 until square.length)\n square(i) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n var result = true\n\n for {i <- 0 until square.length\n j <- 0 until square(i).length\n if result && square(i)(j) != 1} {\n\n def answer(arr: Array[Array[Int]], row: Int, col: Int): Boolean = {\n val rows =\n for (j <- 0 until arr(row).length if j != col)\n yield square(row)(j)\n\n val columns =\n for (i <- 0 until arr.length if i != row)\n yield square(i)(col)\n\n rows.flatMap(r => columns.map(c => c + r))\n .exists(_ == square(row)(col))\n }\n\n if (!answer(square, i, j))\n result = false\n }\n\n println(if (result) \"Yes\" else \"No\")\n}\n"}, {"source_code": "// 821/A - Okabe and Future Gadget Laboratory\nobject Problem821A extends App {\n\n val n: Int = scala.io.StdIn.readInt()\n\n val square: Array[Array[Int]] = Array.ofDim(n, n)\n\n for (i <- square.indices)\n square(i) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n var result = true\n\n for {i <- square.indices\n j <- square(i).indices\n if result && square(i)(j) != 1} {\n\n val columns =\n for (c <- square(i).indices if c != j)\n yield square(i)(c)\n\n val rows =\n for (r <- square.indices if r != i)\n yield square(r)(j)\n\n result = columns.flatMap(c => rows.map(r => c + r))\n .contains(square(i)(j))\n }\n\n println(if (result) \"Yes\" else \"No\")\n\n}\n"}, {"source_code": "// 821/A - Okabe and Future Gadget Laboratory\nobject Problem821A extends App {\n\n // Getting the integer `n` representing the size of the lab\n val n: Byte = scala.io.StdIn.readByte()\n\n // Creating the `n` by `n` square grid of integers\n val square: Array[Array[Int]] = Array.ofDim(n, n)\n\n // Filling the grid with integers\n for (i <- square.indices)\n square(i) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n var result = true\n\n for {i <- square.indices\n j <- square(i).indices\n if result && square(i)(j) != 1} {\n\n def answer(arr: Array[Array[Int]], row: Int, col: Int): Boolean = {\n val columns =\n for (j <- arr(row).indices if j != col)\n yield square(row)(j)\n\n val rows =\n for (i <- arr.indices if i != row)\n yield square(i)(col)\n\n columns.flatMap(c => rows.map(r => r + c))\n .contains(square(row)(col))\n }\n\n if (!answer(square, i, j))\n result = false\n }\n\n // Printing the answer\n println(if (result) \"Yes\" else \"No\")\n\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextBoolean: Boolean = next.equalsIgnoreCase(\"1\")\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n\n override def toString = s\"MultiHashSet($map)\"\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n *\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val arr = new Array[Array[Int]](n)\n for (i <- 0 until n) {\n arr(i) = new Array[Int](n)\n for (j <- 0 until n) {\n arr(i)(j) = nextInt\n }\n }\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n var flag = false\n if (arr(i)(j) != 1) {\n for (k <- 0 until n) {\n for (l <- 0 until n) {\n if (k != j && l != i && arr(i)(k) + arr(l)(j) == arr(i)(j)) {\n flag = true\n }\n }\n }\n if (!flag) {\n out.println(\"No\")\n return 0\n }\n }\n\n }\n }\n out.println(\"Yes\")\n return 0\n }\n}\n"}, {"source_code": "object _821A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO) = {import io.{read, write}\n val n = read[Int]\n val lab = IndexedSeq.fill(n, n)(read[Int])\n def indices = (0 until n) X (0 until n)\n\n def isOkay(r: Int, c: Int) = {\n lab(r)(c) == 1 || indices.exists({case (i, j) => lab(i)(c) + lab(r)(j) == lab(r)(c)})\n }\n\n val ans = indices.forall(Function.tupled(isOkay))\n write(ans.toEnglish)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "d1d50f0780d5c70e6773d5601d7d41e8"} {"source_code": "object B451 {\n import IO._\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n)\n var start = -1\n var end = -1\n for(i <- 1 until n) {\n if(in(i-1) > in(i)) {\n if(start == -1) {\n start = i-1\n end = i\n } else {\n end = i\n }\n }\n }\n if(start == -1 && end == -1) {\n println(\"yes\")\n println(\"1 1\")\n } else {\n val in2 = in.clone()\n val in3 = in.clone()\n\n util.Sorting.quickSort(in2)\n\n val rev = in3.slice(start, end+1).reverse\n var j = 0\n for(i <- start to end){\n in3(i) = rev(j)\n j += 1\n }\n\n if(in2.sameElements(in3)) {\n println(\"yes\")\n println(s\"${start+1} ${end+1}\")\n } else {\n println(\"no\")\n }\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n}\n", "positive_code": [{"source_code": "\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 24.07.14.\n */\nobject B extends App {\n val home = true\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n val a = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n }\n var k = 0\n var f = true\n for (i <- 1 until n if f) {\n if (a(i) >= a(k)) {\n k = i\n } else {\n f = false\n }\n }\n var j = 0\n for (i <- 0 to k if j == 0) {\n if (a(i) == a(k)) {\n j = i\n }\n }\n var t = j\n for (i <- j until n) {\n if (a(i) <= a(j)) {\n t = i\n }\n }\n val b = a.slice(j, t + 1)\n for (i <- j to t) {\n a(i) = b(t - i)\n }\n\n if (a.toList.sorted == a.toList) {\n out.println(s\"yes\\n${j + 1} ${t + 1}\")\n } else {\n out.println(\"no\")\n }\n\n// out.println(k)\n// out.println(j)\n// out.println(t)\n// out.println(a.toList)\n// out.println(a.sorted.toList)\n\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _451B extends App {\n var token = new StringTokenizer(\"\")\n\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt).toArray\n\n val first = (0 until n - 1).indexWhere(i => a(i) > a(i + 1))\n if (first == -1) println(\"yes\\n1 1\")\n else {\n val cb = Stream.from(first).takeWhile(i => i < n - 1 && a(i) > a(i + 1) && (i == first || a(i - 1) > a(i))).toArray\n def reverse(l: Int, r: Int): Unit = {\n if (l < r) {\n val tmp = a(l)\n a(l) = a(r)\n a(r) = tmp\n reverse(l + 1, r - 1)\n }\n }\n reverse(first, cb.last + 1)\n val ok = (0 until n - 1).forall(i => a(i) <= a(i + 1))\n if (ok) println(\"yes%n%d %d\".format(first + 1, cb.last + 1 + 1))\n else println(\"no\")\n }\n}\n"}, {"source_code": "\nobject Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n var result: Option[(Int, Int)] = None\n\n if (n == 1) {\n result = Some((1, 1))\n } else {\n val firstUp = data(1) > data(0)\n val index1 = Range(0, n - 1).find{\n case(i) if firstUp => data(i + 1) < data(i)\n case(i) => data(i + 1) > data(i)\n }\n val secondUp = data(n - 2) > data(n - 1)\n val index2 = Range(n - 1, 0, -1).find {\n case i if secondUp => data(i - 1) < data(i)\n case i => data(i - 1) > data(i)\n }\n// println(index1)\n// println(index2)\n// println(firstUp)\n// println(secondUp)\n if (index1.isEmpty && index2.isEmpty) {\n if (firstUp)\n result = Some((1, 1))\n else\n result = Some((1, n))\n }\n else if (index1 == index2) {\n if (firstUp) {\n// println(\"gg\")\n// println(firstUp)\n// println(data(index1.get))\n// println(data(index1.get + 1))\n if (data(index1.get) > data(index1.get + 1) && data(0) < data(n - 1)) {\n result = Some((index1.get + 1, n))\n// println(\"lollol\")\n }\n } else {\n// println(\"pp\")\n// println(firstUp)\n// println(data(0))\n// println(data(index1.get + 1))\n if (data(0) < data(index1.get + 1)) {\n result = Some(1, index1.get + 1)\n }\n }\n } else {\n if (firstUp && !secondUp) {\n var prev = data(index1.get) + 1\n val r = data.slice(index1.get, index2.get + 1).forall{ n =>\n val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)\n prev = n\n res\n }\n if (r)\n result = Some(index1.get + 1, index2.get + 1)\n }\n }\n }\n\n if (result.isEmpty)\n println(\"no\")\n else {\n println(\"yes\")\n println(result.get._1 + \" \" + result.get._2)\n }\n\n\n}"}], "negative_code": [{"source_code": "\nobject Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n\n if (n == 1) {\n println(\"yes\")\n println(\"1 1\")\n } else {\n val firstUp = data(1) > data(0)\n val index1 = Range(0, n - 1).find{\n case(i) if firstUp => data(i + 1) < data(i)\n case(i) => data(i + 1) > data(i)\n }\n val secondUp = data(n - 2) > data(n - 1)\n val index2 = Range(n - 1, 0, -1).find {\n case i if secondUp => data(i - 1) < data(i)\n case i => data(i - 1) > data(i)\n }\n if (index1.isEmpty && index2.isEmpty) {\n println(\"yes\")\n println(\"1 1\")\n } else if (!firstUp && !secondUp) {\n println(\"no\")\n } else if (index1 == index2) {\n if (firstUp) {\n if (data(0) > data(n - 1)) {\n println(\"yes\")\n println(index1.get + \" \" + n)\n } else {\n println(\"no\")\n }\n } else {\n if (data(0) > data(index1.get)) {\n println(\"yes\")\n println(index1.get + \" \" + n)\n } else {\n println(\"no\")\n }\n }\n } else {\n if (!firstUp || secondUp)\n println(\"no\")\n else {\n var prev = data(index1.get) + 1\n val r = data.slice(index1.get, index2.get + 1).forall{ n =>\n val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)\n prev = n\n res\n }\n if (!r)\n println(\"no\")\n else {\n println(\"yes\")\n println(index1.get + 1 + \" \" + (index2.get + 1))\n }\n }\n }\n }\n}"}, {"source_code": "\nobject Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n var result: Option[(Int, Int)] = None\n\n if (n == 1) {\n result = Some((1, 1))\n } else {\n val firstUp = data(1) > data(0)\n val index1 = Range(0, n - 1).find{\n case(i) if firstUp => data(i + 1) < data(i)\n case(i) => data(i + 1) > data(i)\n }\n val secondUp = data(n - 2) > data(n - 1)\n val index2 = Range(n - 1, 0, -1).find {\n case i if secondUp => data(i - 1) < data(i)\n case i => data(i - 1) > data(i)\n }\n// println(index1)\n// println(index2)\n// println(firstUp)\n// println(secondUp)\n if (index1.isEmpty && index2.isEmpty) {\n if (firstUp)\n result = Some((1, 1))\n else\n result = Some((1, n))\n }\n else if (!firstUp && secondUp) {}\n else if (index1 == index2) {\n if (firstUp) {\n// println(\"gg\")\n// println(firstUp)\n// println(data(index1.get))\n// println(data(index1.get + 1))\n if (data(index1.get) < data(index1.get + 1)) {\n result = Some((index1.get + 1, n))\n// println(\"lollol\")\n }\n } else {\n// println(\"pp\")\n// println(firstUp)\n// println(data(0))\n// println(data(index1.get + 1))\n if (data(0) < data(index1.get + 1)) {\n result = Some(1, index1.get + 1)\n }\n }\n } else {\n if (firstUp && !secondUp) {\n var prev = data(index1.get) + 1\n val r = data.slice(index1.get, index2.get + 1).forall{ n =>\n val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)\n prev = n\n res\n }\n if (r)\n result = Some(index1.get + 1, index2.get + 1)\n }\n }\n }\n\n if (result.isEmpty)\n println(\"no\")\n else {\n println(\"yes\")\n println(result.get._1 + \" \" + result.get._2)\n }\n\n\n}"}, {"source_code": "\nobject Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n var result: Option[(Int, Int)] = None\n\n if (n == 1) {\n result = Some((1, 1))\n } else {\n val firstUp = data(1) > data(0)\n val index1 = Range(0, n - 1).find{\n case(i) if firstUp => data(i + 1) < data(i)\n case(i) => data(i + 1) > data(i)\n }\n val secondUp = data(n - 2) > data(n - 1)\n val index2 = Range(n - 1, 0, -1).find {\n case i if secondUp => data(i - 1) < data(i)\n case i => data(i - 1) > data(i)\n }\n// println(index1)\n// println(index2)\n// println(firstUp)\n// println(secondUp)\n if (index1.isEmpty && index2.isEmpty) {\n if (firstUp)\n result = Some((1, 1))\n else\n result = Some((1, n))\n } else if (index1 == index2) {\n if (firstUp) {\n// println(\"gg\")\n if (data(0) > data(n - 1)) {\n result = Some((index1.get + 1, n))\n// println(\"lollol\")\n }\n } else {\n// println(\"pp\")\n// println(firstUp)\n// println(data(0))\n// println(data(index1.get + 1))\n if (data(0) < data(index1.get + 1)) {\n result = Some(1, index1.get + 1)\n }\n }\n } else {\n if (firstUp && !secondUp) {\n var prev = data(index1.get) + 1\n val r = data.slice(index1.get, index2.get + 1).forall{ n =>\n val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)\n prev = n\n res\n }\n if (r)\n result = Some(index1.get + 1, index2.get + 1)\n }\n }\n }\n\n if (result.isEmpty)\n println(\"no\")\n else {\n println(\"yes\")\n println(result.get._1 + \" \" + result.get._2)\n }\n\n\n}"}, {"source_code": "\nobject Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n var result: Option[(Int, Int)] = None\n\n if (n == 1) {\n result = Some((1, 1))\n } else {\n val firstUp = data(1) > data(0)\n val index1 = Range(0, n - 1).find{\n case(i) if firstUp => data(i + 1) < data(i)\n case(i) => data(i + 1) > data(i)\n }\n val secondUp = data(n - 2) > data(n - 1)\n val index2 = Range(n - 1, 0, -1).find {\n case i if secondUp => data(i - 1) < data(i)\n case i => data(i - 1) > data(i)\n }\n// println(index1)\n// println(index2)\n// println(firstUp)\n// println(secondUp)\n if (index1.isEmpty && index2.isEmpty) {\n if (firstUp)\n result = Some((1, 1))\n else\n result = Some((1, n))\n } else if (!firstUp && secondUp) {\n } else if (index1 == index2) {\n if (firstUp) {\n if (data(0) > data(n - 1)) {\n result = Some((index1.get + 1, n))\n }\n } else {\n if (data(0) > data(n - 1)) {\n result = Some(1, index1.get + 1)\n }\n }\n } else {\n if (firstUp && !secondUp) {\n var prev = data(index1.get) + 1\n val r = data.slice(index1.get, index2.get + 1).forall{ n =>\n val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)\n prev = n\n res\n }\n if (r)\n result = Some(index1.get + 1, index2.get + 1)\n }\n }\n }\n\n if (result.isEmpty)\n println(\"no\")\n else {\n println(\"yes\")\n println(result.get._1 + \" \" + result.get._2)\n }\n\n\n}"}, {"source_code": "\nobject Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n var result: Option[(Int, Int)] = None\n\n if (n == 1) {\n result = Some((1, 1))\n } else {\n val firstUp = data(1) > data(0)\n val index1 = Range(0, n - 1).find{\n case(i) if firstUp => data(i + 1) < data(i)\n case(i) => data(i + 1) > data(i)\n }\n val secondUp = data(n - 2) > data(n - 1)\n val index2 = Range(n - 1, 0, -1).find {\n case i if secondUp => data(i - 1) < data(i)\n case i => data(i - 1) > data(i)\n }\n// println(index1)\n// println(index2)\n// println(firstUp)\n// println(secondUp)\n if (index1.isEmpty && index2.isEmpty) {\n if (firstUp)\n result = Some((1, 1))\n else\n result = Some((1, n))\n } else if (index1 == index2) {\n if (firstUp) {\n// println(\"gg\")\n// println(firstUp)\n// println(data(index1.get + 1))\n// println(data(n - 1))\n if (data(index1.get + 1) > data(n - 1)) {\n result = Some((index1.get + 1, n))\n// println(\"lollol\")\n }\n } else {\n// println(\"pp\")\n// println(firstUp)\n// println(data(0))\n// println(data(index1.get + 1))\n if (data(0) < data(index1.get + 1)) {\n result = Some(1, index1.get + 1)\n }\n }\n } else {\n if (firstUp && !secondUp) {\n var prev = data(index1.get) + 1\n val r = data.slice(index1.get, index2.get + 1).forall{ n =>\n val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)\n prev = n\n res\n }\n if (r)\n result = Some(index1.get + 1, index2.get + 1)\n }\n }\n }\n\n if (result.isEmpty)\n println(\"no\")\n else {\n println(\"yes\")\n println(result.get._1 + \" \" + result.get._2)\n }\n\n\n}"}, {"source_code": "\nobject Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n var result: Option[(Int, Int)] = None\n\n if (n == 1) {\n result = Some((1, 1))\n } else {\n val firstUp = data(1) > data(0)\n val index1 = Range(0, n - 1).find{\n case(i) if firstUp => data(i + 1) < data(i)\n case(i) => data(i + 1) > data(i)\n }\n val secondUp = data(n - 2) > data(n - 1)\n val index2 = Range(n - 1, 0, -1).find {\n case i if secondUp => data(i - 1) < data(i)\n case i => data(i - 1) > data(i)\n }\n if (index1.isEmpty && index2.isEmpty) {\n if (firstUp)\n result = Some((1, 1))\n else\n result = Some((1, n))\n } else if (!firstUp && !secondUp) {\n } else if (index1 == index2) {\n if (firstUp) {\n if (data(0) > data(n - 1))\n result = Some((index1.get, n))\n } else {\n if (data(0) > data(index1.get))\n result = Some(index1.get, n)\n }\n } else {\n if (firstUp && !secondUp) {\n var prev = data(index1.get) + 1\n val r = data.slice(index1.get, index2.get + 1).forall{ n =>\n val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)\n prev = n\n res\n }\n if (r)\n result = Some(index1.get + 1, index2.get + 1)\n }\n }\n }\n\n if (result.isEmpty)\n println(\"no\")\n else {\n println(\"yes\")\n println(result.get._1 + \" \" + result.get._2)\n }\n\n\n}"}, {"source_code": "\nobject Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n var result: Option[(Int, Int)] = None\n\n if (n == 1) {\n result = Some((1, 1))\n } else {\n val firstUp = data(1) > data(0)\n val index1 = Range(0, n - 1).find{\n case(i) if firstUp => data(i + 1) < data(i)\n case(i) => data(i + 1) > data(i)\n }\n val secondUp = data(n - 2) > data(n - 1)\n val index2 = Range(n - 1, 0, -1).find {\n case i if secondUp => data(i - 1) < data(i)\n case i => data(i - 1) > data(i)\n }\n// println(index1)\n// println(index2)\n// println(firstUp)\n// println(secondUp)\n if (index1.isEmpty && index2.isEmpty) {\n if (firstUp)\n result = Some((1, 1))\n else\n result = Some((1, n))\n }\n else if (index1 == index2) {\n if (firstUp) {\n// println(\"gg\")\n// println(firstUp)\n// println(data(index1.get))\n// println(data(index1.get + 1))\n if (data(index1.get) < data(index1.get + 1)) {\n result = Some((index1.get + 1, n))\n// println(\"lollol\")\n }\n } else {\n// println(\"pp\")\n// println(firstUp)\n// println(data(0))\n// println(data(index1.get + 1))\n if (data(0) < data(index1.get + 1)) {\n result = Some(1, index1.get + 1)\n }\n }\n } else {\n if (firstUp && !secondUp) {\n var prev = data(index1.get) + 1\n val r = data.slice(index1.get, index2.get + 1).forall{ n =>\n val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)\n prev = n\n res\n }\n if (r)\n result = Some(index1.get + 1, index2.get + 1)\n }\n }\n }\n\n if (result.isEmpty)\n println(\"no\")\n else {\n println(\"yes\")\n println(result.get._1 + \" \" + result.get._2)\n }\n\n\n}"}, {"source_code": "\nobject Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n var result: Option[(Int, Int)] = None\n\n if (n == 1) {\n result = Some((1, 1))\n } else {\n val firstUp = data(1) > data(0)\n val index1 = Range(0, n - 1).find{\n case(i) if firstUp => data(i + 1) < data(i)\n case(i) => data(i + 1) > data(i)\n }\n val secondUp = data(n - 2) > data(n - 1)\n val index2 = Range(n - 1, 0, -1).find {\n case i if secondUp => data(i - 1) < data(i)\n case i => data(i - 1) > data(i)\n }\n if (index1.isEmpty && index2.isEmpty) {\n if (firstUp)\n result = Some((1, 1))\n else\n result = Some((1, n))\n } else if (!firstUp && !secondUp) {\n } else if (index1 == index2) {\n if (firstUp) {\n if (data(0) > data(n - 1))\n result = Some((index1.get, n))\n } else {\n if (data(0) > data(index1.get))\n result = Some(index1.get, n)\n }\n } else {\n if (firstUp && !secondUp) {\n var prev = data(index1.get) + 1\n val r = data.slice(index1.get, index2.get + 1).forall{ n =>\n val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)\n prev = n\n res\n }\n if (r)\n result = Some(index1.get + 1, index2.get + 1)\n }\n }\n }\n \n if (result.isEmpty)\n println(\"no\")\n else\n println(result.get._1 + \" \" + result.get._2)\n\n \n}"}, {"source_code": "\nobject Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n var result: Option[(Int, Int)] = None\n\n if (n == 1) {\n result = Some((1, 1))\n } else {\n val firstUp = data(1) > data(0)\n val index1 = Range(0, n - 1).find{\n case(i) if firstUp => data(i + 1) < data(i)\n case(i) => data(i + 1) > data(i)\n }\n val secondUp = data(n - 2) > data(n - 1)\n val index2 = Range(n - 1, 0, -1).find {\n case i if secondUp => data(i - 1) < data(i)\n case i => data(i - 1) > data(i)\n }\n// println(index1)\n// println(index2)\n// println(firstUp)\n// println(secondUp)\n if (index1.isEmpty && index2.isEmpty) {\n if (firstUp)\n result = Some((1, 1))\n else\n result = Some((1, n))\n } else if (!firstUp && secondUp) {\n } else if (index1 == index2) {\n if (firstUp) {\n if (data(0) > data(n - 1))\n result = Some((index1.get + 1, n))\n } else {\n if (data(0) > data(index1.get))\n result = Some(1, index1.get + 1)\n }\n } else {\n if (firstUp && !secondUp) {\n var prev = data(index1.get) + 1\n val r = data.slice(index1.get, index2.get + 1).forall{ n =>\n val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)\n prev = n\n res\n }\n if (r)\n result = Some(index1.get + 1, index2.get + 1)\n }\n }\n }\n\n if (result.isEmpty)\n println(\"no\")\n else {\n println(\"yes\")\n println(result.get._1 + \" \" + result.get._2)\n }\n\n\n}"}, {"source_code": "\nobject Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n var result: Option[(Int, Int)] = None\n\n if (n == 1) {\n result = Some((1, 1))\n } else {\n val firstUp = data(1) > data(0)\n val index1 = Range(0, n - 1).find{\n case(i) if firstUp => data(i + 1) < data(i)\n case(i) => data(i + 1) > data(i)\n }\n val secondUp = data(n - 2) > data(n - 1)\n val index2 = Range(n - 1, 0, -1).find {\n case i if secondUp => data(i - 1) < data(i)\n case i => data(i - 1) > data(i)\n }\n// println(index1)\n// println(index2)\n// println(firstUp)\n// println(secondUp)\n if (index1.isEmpty && index2.isEmpty) {\n if (firstUp)\n result = Some((1, 1))\n else\n result = Some((1, n))\n }\n else if (index1 == index2) {\n if (firstUp) {\n// println(\"gg\")\n// println(firstUp)\n// println(data(index1.get))\n// println(data(index1.get + 1))\n if (data(index1.get) > data(index1.get + 1)) {\n result = Some((index1.get + 1, n))\n// println(\"lollol\")\n }\n } else {\n// println(\"pp\")\n// println(firstUp)\n// println(data(0))\n// println(data(index1.get + 1))\n if (data(0) < data(index1.get + 1)) {\n result = Some(1, index1.get + 1)\n }\n }\n } else {\n if (firstUp && !secondUp) {\n var prev = data(index1.get) + 1\n val r = data.slice(index1.get, index2.get + 1).forall{ n =>\n val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)\n prev = n\n res\n }\n if (r)\n result = Some(index1.get + 1, index2.get + 1)\n }\n }\n }\n\n if (result.isEmpty)\n println(\"no\")\n else {\n println(\"yes\")\n println(result.get._1 + \" \" + result.get._2)\n }\n\n\n}"}], "src_uid": "c9744e25f92bae784c3a4833c15d03f4"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val n5 = a.count(_ == 5)\n val n0 = a.count(_ == 0)\n if (n0 == 0) println(\"-1\")\n else if (n5 / 9 == 0) println(\"0\")\n else {\n var s = Seq.fill((n5 / 9) * 9)(5) ++ Seq.fill(n0)(0)\n println(s.mkString(\"\"))\n }\n }\n}", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _352A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt)\n val five = a.filter(i => i == 5).size\n val zero = n - five\n if (zero == 0) println(-1)\n else {\n val ans = if (five < 9) \"0\" else (1 to five / 9 * 9).map(i => '5').mkString + (1 to zero).map(i => '0').mkString\n println(ans)\n }\n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val zeros = data.count(_ == 0)\n val fifths = data.count(_ == 5)\n\n if (zeros == 0)\n println(-1)\n else if (fifths < 9)\n println(0)\n else\n println(\"5\" * (fifths - fifths % 9) + \"0\" * zeros)\n\n}"}, {"source_code": "object A352 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n)\n val fives = in.count(_ == 5)\n val zeros = in.count(_ == 0)\n if(zeros == 0) {\n println(\"-1\")\n } else if(fives < 9) {\n println(\"0\")\n } else {\n println((Array.fill(9*(fives/9))(5) ++ Array.fill(zeros)(0)).mkString(\"\"))\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P352A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val C = List.fill(N)(sc.nextInt)\n\n def solve(): String = {\n val c0 = C.filter(_ == 0).size\n val c5 = C.filter(_ == 5).size\n\n if (c0 < 1) \"-1\"\n else if (c5 < 9) \"0\"\n else (List.fill(c5 / 9 * 9)('5') ++ List.fill(c0)('0')).mkString\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject A {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def solve = {\n val n = nextInt\n val a = new Array[Int](n)\n val num = new Array[Int](10)\n for (i <- 0 until n) {\n if (nextInt == 5) {\n num(5) = num(5) + 1\n } else {\n num(0) = num(0) + 1\n }\n }\n if (num(0) > 0) {\n if (num(5) < 9) {\n out.println(0)\n } else {\n val r = num(5) / 9\n for (i <- 0 until r) {\n out.print(\"555555555\")\n }\n for (i <- 0 until num(0)) {\n out.print('0')\n }\n }\n } else {\n out.println(-1)\n }\n }\n\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val zeros = data.count(_ == 0)\n val fifths = data.count(_ == 0)\n\n if (zeros == 0)\n println(-1)\n else if (fifths < 9)\n println(0)\n else\n println(\"5\" * (fifths / 9) + \"0\" * zeros)\n\n}"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val zeros = data.count(_ == 0)\n val fifths = data.count(_ == 0)\n\n if (zeros == 0)\n println(-1)\n else if (fifths < 9)\n println(0)\n else\n println(\"5\" * (fifths % 9) + \"0\" * zeros)\n\n}"}, {"source_code": "object A352 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n)\n val fives = in.count(_ == 5)\n val zeros = in.count(_ == 0)\n if(fives < 9 && zeros == 0) {\n println(\"-1\")\n } else if(fives < 9) {\n println(\"0\")\n } else {\n println((Array.fill(9*(fives/9))(5) ++ Array.fill(zeros)(0)).mkString(\"\"))\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object A352 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n)\n val fives = in.count(_ == 5)\n val zeros = in.count(_ == 0)\n if(fives < 9) {\n println(\"0\")\n } else {\n println((Array.fill(9*(fives/9))(5) ++ Array.fill(zeros)(0)).mkString(\"\"))\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P352A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val C = List.fill(N)(sc.nextInt)\n\n def solve(): String = {\n val c0 = C.filter(_ == 0).size\n val c5 = C.filter(_ == 5).size\n\n if (c0 < 1 && c5 < 9) \"-1\"\n else if (c0 > 0 && c5 < 9) \"0\"\n else (List.fill(c5 / 9 * 9)('5') ++ List.fill(c0)('0')).mkString\n }\n\n out.println(solve)\n out.close\n}\n"}], "src_uid": "409b27044d5ec97b5315c92d4112376f"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val graph = Array.fill(n){Set.empty[Int]}\n (1 to m).foreach { _ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt - 1)\n graph(a) += b\n graph(b) += a\n }\n val oneCount = graph.groupBy(_.size).map(t => (t._1, t._2.length))\n if (oneCount.getOrElse(1, 0) == 2 && oneCount.getOrElse(2, 0) == n - 2 && m == n - 1)\n println(\"bus topology\")\n else if (oneCount.getOrElse(2, 0) == n && m == n)\n println(\"ring topology\")\n else if (oneCount.getOrElse(1, 0) == (n - 1) && oneCount.getOrElse(n - 1, 0) == 1 && m == n - 1)\n println(\"star topology\")\n else\n println(\"unknown topology\")\n}", "positive_code": [{"source_code": "/*\nB. Топология сети\nограничение по времени на тест\n2 секунды\nограничение по памяти на тест\n256 мегабайт\nввод\nstandard input\nвывод\nstandard output\n\nВ задаче используется упрощенная модель топологий сетей, внимательно прочтите условие задачи и используйте его как формальный документ при разработке решения.\n\nПоликарп продолжает работать системным администратором в некоторой большой корпорации. Компьютерная сеть этой корпорации состоит из n компьютеров, некоторые из которых соединены кабелем. Компьютеры пронумеруем целыми числами от 1 до n. Известно, что любые два компьютера соединены кабелем непосредственно или через другие компьютеры.\n\nПоликарп решил узнать топологию этой сети. Сетевая топология — это способ описания конфигурации сети, схема расположения и соединения сетевых устройств.\n\nПоликарп знает три основные топологии сети: шина, кольцо и звезда. Шина — это топология, которая представляет собой общий кабель, к которому подсоединены все компьютеры. Кольцо — топология, в которой каждый компьютер соединен кабелем только с двумя другими. Звезда — это топология, в которой все компьютеры сети присоединены к единому центральному узлу.\n\nПредставим каждую из этих топологий сети в виде связного неориентированного графа. Под шиной будем понимать связный граф, являющийся единственным путем, то есть граф, в котором все вершины соединены с двумя другими, за исключением двух вершин, которые являются началом и концом пути. Под кольцом будем понимать связный граф, в котором все вершины соединены с двумя другими. Под звездой будем понимать связный граф, в котором выделена единственная центральная вершина, которая соединена со всеми остальными вершинами. Для лучшего понимания ознакомьтесь с рисунком.\n\n1) o -- o -- o -- o -- o\n\n2) o -- o -- o\n | |\n o -- o -- o\n\n3) o o \n \\| \n o -- o \n /|\\ \n o o o \n \n(1) — шина, (2) — кольцо, (3) — звезда\n\nВам задан связный неориентированный граф, характеризующий компьютерную сеть корпорации, в которой работает Поликарп. Помогите ему узнать, к какой из данных топологий относится заданная компьютерная сеть. Если это невозможно определить, сообщите, что топология этой сети неизвестна.\nВходные данные\n\nВ первой строке через пробел заданы два целых числа n и m (4 ≤ n ≤ 105; 3 ≤ m ≤ 105) — количество вершин и ребер в графе соответственно. Далее в m строках задано описание ребер графа. В i-той строке через пробел задана пара целых чисел xi, yi (1 ≤ xi, yi ≤ n) — номера вершин, которые соединяет i-ое ребро.\n\nГарантируется, что заданный граф является связным. Между любыми двумя вершинами существует не более одного ребра. Ни одно ребро не соединяет вершину саму с собой.\nВыходные данные\n\nВ единственную строку выведите название топологии сети, к которой относится заданный граф. Если ответом является шина, выведите «bus topology» (без кавычек), если ответом является кольцо, выведите «ring topology» (без кавычек), если ответом является звезда, выведите «star topology» (без кавычек). Если ни один из этих типов не подходит, выведите «unknown topology» (без кавычек).\nПримеры тестов\nВходные данные\n\n4 3\n1 2\n2 3\n3 4\n\nВыходные данные\n\nbus topology\n\nВходные данные\n\n4 4\n1 2\n2 3\n3 4\n4 1\n\nВыходные данные\n\nring topology\n\nВходные данные\n\n4 3\n1 2\n1 3\n1 4\n\nВыходные данные\n\nstar topology\n\nВходные данные\n\n4 4\n1 2\n2 3\n3 1\n1 4\n\nВыходные данные\n\nunknown topology\n*/\nobject CrocRound1Task2 extends App {\n def bus = \"bus topology\"\n def ring = \"ring topology\"\n def star = \"star topology\"\n def unknown = \"unknown topology\"\n\n /** Analyzez the graph to find out topology */\n def solve(n: Int, edges: Seq[(Int, Int)]): String = {\n val arr = Array.fill[Int](n)(0)\n val edgesCleaned = (edges map (p => if (p._2 > p._1) p.swap else p)).distinct\n edgesCleaned map {\n case (x, y) => {\n arr(x - 1) += 1\n arr(y - 1) += 1\n }\n }\n val seq = IndexedSeq(arr: _*).sorted\n if (seq.head == 2 && seq.last == 2) {\n ring\n } else if (seq(0) == 1 && seq(1) == 1 && seq(2) == 2 && seq.last == 2) {\n bus\n } else if (seq(0) == 1 && seq(n - 2) == 1 && seq(n - 1) == (n - 1)) {\n star\n } else {\n unknown\n }\n }\n\n val (n, m) = {\n val l = readLine split ' ' map (_.toInt)\n (l(0), l(1))\n }\n val edges = (0 until m) map (_ => readLine split ' ' map (_.toInt)) map (l => (l(0), l(1)))\n\n val res = solve(n, edges)\n println(res)\n}"}, {"source_code": "/*\nB. Топология сети\nограничение по времени на тест\n2 секунды\nограничение по памяти на тест\n256 мегабайт\nввод\nstandard input\nвывод\nstandard output\n\nВ задаче используется упрощенная модель топологий сетей, внимательно прочтите условие задачи и используйте его как формальный документ при разработке решения.\n\nПоликарп продолжает работать системным администратором в некоторой большой корпорации. Компьютерная сеть этой корпорации состоит из n компьютеров, некоторые из которых соединены кабелем. Компьютеры пронумеруем целыми числами от 1 до n. Известно, что любые два компьютера соединены кабелем непосредственно или через другие компьютеры.\n\nПоликарп решил узнать топологию этой сети. Сетевая топология — это способ описания конфигурации сети, схема расположения и соединения сетевых устройств.\n\nПоликарп знает три основные топологии сети: шина, кольцо и звезда. Шина — это топология, которая представляет собой общий кабель, к которому подсоединены все компьютеры. Кольцо — топология, в которой каждый компьютер соединен кабелем только с двумя другими. Звезда — это топология, в которой все компьютеры сети присоединены к единому центральному узлу.\n\nПредставим каждую из этих топологий сети в виде связного неориентированного графа. Под шиной будем понимать связный граф, являющийся единственным путем, то есть граф, в котором все вершины соединены с двумя другими, за исключением двух вершин, которые являются началом и концом пути. Под кольцом будем понимать связный граф, в котором все вершины соединены с двумя другими. Под звездой будем понимать связный граф, в котором выделена единственная центральная вершина, которая соединена со всеми остальными вершинами. Для лучшего понимания ознакомьтесь с рисунком.\n\n1) o -- o -- o -- o -- o\n\n2) o -- o -- o\n | |\n o -- o -- o\n\n3) o o \n \\| \n o -- o \n /|\\ \n o o o \n \n(1) — шина, (2) — кольцо, (3) — звезда\n\nВам задан связный неориентированный граф, характеризующий компьютерную сеть корпорации, в которой работает Поликарп. Помогите ему узнать, к какой из данных топологий относится заданная компьютерная сеть. Если это невозможно определить, сообщите, что топология этой сети неизвестна.\nВходные данные\n\nВ первой строке через пробел заданы два целых числа n и m (4 ≤ n ≤ 105; 3 ≤ m ≤ 105) — количество вершин и ребер в графе соответственно. Далее в m строках задано описание ребер графа. В i-той строке через пробел задана пара целых чисел xi, yi (1 ≤ xi, yi ≤ n) — номера вершин, которые соединяет i-ое ребро.\n\nГарантируется, что заданный граф является связным. Между любыми двумя вершинами существует не более одного ребра. Ни одно ребро не соединяет вершину саму с собой.\nВыходные данные\n\nВ единственную строку выведите название топологии сети, к которой относится заданный граф. Если ответом является шина, выведите «bus topology» (без кавычек), если ответом является кольцо, выведите «ring topology» (без кавычек), если ответом является звезда, выведите «star topology» (без кавычек). Если ни один из этих типов не подходит, выведите «unknown topology» (без кавычек).\nПримеры тестов\nВходные данные\n\n4 3\n1 2\n2 3\n3 4\n\nВыходные данные\n\nbus topology\n\nВходные данные\n\n4 4\n1 2\n2 3\n3 4\n4 1\n\nВыходные данные\n\nring topology\n\nВходные данные\n\n4 3\n1 2\n1 3\n1 4\n\nВыходные данные\n\nstar topology\n\nВходные данные\n\n4 4\n1 2\n2 3\n3 1\n1 4\n\nВыходные данные\n\nunknown topology\n*/\nimport java.util.Arrays\n\nobject CrocRound1Task2 extends App {\n def bus = \"bus topology\"\n def ring = \"ring topology\"\n def star = \"star topology\"\n def unknown = \"unknown topology\"\n\n /** Analyzez the graph to find out topology */\n def solve(n: Int, edges: Seq[(Int, Int)]): String = {\n val arr = Array.fill[Int](n)(0)\n val edgesCleaned = (edges map (p => if (p._2 > p._1) p.swap else p)).distinct\n edgesCleaned map {\n case (x, y) => {\n arr(x - 1) += 1\n arr(y - 1) += 1\n }\n }\n Arrays.sort(arr)\n if (arr.head == 2 && arr.last == 2) {\n ring\n } else if (arr(0) == 1 && arr(1) == 1 && arr(2) == 2 && arr.last == 2) {\n bus\n } else if (arr(0) == 1 && arr(n - 2) == 1 && arr(n - 1) == (n - 1)) {\n star\n } else {\n unknown\n }\n }\n\n val (n, m) = {\n val l = readLine split ' ' map (_.toInt)\n (l(0), l(1))\n }\n val edges = (0 until m) map (_ => readLine split ' ' map (_.toInt)) map (l => (l(0), l(1)))\n\n val res = solve(n, edges)\n println(res)\n}"}, {"source_code": "import io.Source\nimport java.io.PrintWriter\nimport scala.collection.mutable.ArrayBuffer\n\nobject CF292B {\n\n def solve(in: In, out: PrintWriter) {\n val n, m = in().toInt\n val ls = Array.fill(n)(0)\n for (it <- 0 until m) {\n val u, v = in().toInt - 1\n ls(u) += 1\n ls(v) += 1\n }\n out.println {\n if (ls.forall(_ == 2)) {\n \"ring topology\"\n } else if (ls.count(_ == 2) == n - 2 && ls.count(_ == 1) == 2) {\n \"bus topology\"\n } else if (ls.count(_ == 1) == n - 1 && ls.count(_ == n - 1) == 1) {\n \"star topology\"\n } else {\n \"unknown topology\"\n }\n }\n }\n\n def main(args: Array[String]) {\n val in: In = new In(Source.fromInputStream(System.in))\n val out: PrintWriter = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() {\n while (iter.hasNext && delims.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next(): String = {\n skipDelims()\n while (iter.hasNext && delims.indexOf(iter.head) == -1) {\n sb.append(iter.next())\n }\n val ret = sb.toString()\n sb.clear()\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIterator = new TokenIterator(iter, \" \\r\\n\")\n\n val lineIterator = new TokenIterator(iter, \"\\r\\n\")\n\n def apply() = tokenIterator.next()\n\n def apply(n: Int) = tokenIterator.take(n)\n }\n}"}, {"source_code": "object NetworkTopology292B extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n import scala.collection.mutable.ListBuffer\n solve(System.in,System.out)\n def solve(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextInt()\n val m = scanner.nextInt()\n val nodes = (1 to n).map(Node)\n val edges = (1 to m).map(_ => UndirectedEdge(nodes(scanner.nextInt()-1),nodes(scanner.nextInt()-1)))\n val g = new Graph(nodes,edges)\n val result: String = g match {\n case g: Graph if g.isBusTopological => \"bus topology\"\n case g: Graph if g.isRingTopological => \"ring topology\"\n case g: Graph if g.isStarTopological => \"star topology\"\n case _ => \"unknown topology\"\n }\n out.println(result)\n }\n\n class Graph(val nodes: Seq[Node],val edges: Seq[UndirectedEdge]){\n\n nodes.foreach(_.clearNeighbours())\n edges.foreach{case UndirectedEdge(a,b) => {\n a.addNeighbour(b)\n b.addNeighbour(a)\n }}\n\n\n val isBusTopological: Boolean = {\n if(edges.length == nodes.length-1){\n nodes.count(_.neighbours.length == 1) == 2\n }else{\n false\n }\n }\n val isStarTopological: Boolean = {\n if(edges.length == nodes.length-1){\n nodes.count(_.neighbours.length == nodes.length-1) == 1\n }else{\n false\n }\n }\n val isRingTopological: Boolean = {\n if(edges.length == nodes.length){\n nodes.count(_.neighbours.length == 2) == nodes.length\n }else{\n false\n }\n }\n\n\n }\n case class Node(node: Int){\n val neighbours: ListBuffer[Node] = ListBuffer[Node]()\n def clearNeighbours(): Unit = neighbours.clear()\n def addNeighbour(n: Node): Unit = neighbours.append(n)\n }\n case class UndirectedEdge(a: Node, b: Node)\n}"}, {"source_code": "object NetworkTopology292B extends App {\n import java.io.{BufferedReader, IOException, InputStreamReader}\n import java.util.StringTokenizer\n import java.io.{InputStream, PrintStream}\n import scala.collection.mutable.ListBuffer\n solve(System.in,System.out)\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val n = in.nextInt()\n val m = in.nextInt()\n val nodes = (1 to n).map(Node)\n val edges = (1 to m).map(_ => UndirectedEdge(nodes(in.nextInt()-1),nodes(in.nextInt()-1)))\n val myGraph = new Graph(nodes,edges)\n val result: String = myGraph match {\n case g: Graph if g.isBusTopological => \"bus topology\"\n case g: Graph if g.isRingTopological => \"ring topology\"\n case g: Graph if g.isStarTopological => \"star topology\"\n case _ => \"unknown topology\"\n }\n out.println(result)\n }\n\n class Graph(val nodes: Seq[Node],val edges: Seq[UndirectedEdge]){\n\n nodes.foreach(_.clearNeighbours())\n edges.foreach{case UndirectedEdge(a,b) => {\n a.addNeighbour(b)\n b.addNeighbour(a)\n }}\n\n\n val isBusTopological: Boolean = {\n if(edges.length == nodes.length-1){\n nodes.count(_.neighbours.length == 1) == 2\n }else{\n false\n }\n }\n val isStarTopological: Boolean = {\n if(edges.length == nodes.length-1){\n nodes.count(_.neighbours.length == nodes.length-1) == 1\n }else{\n false\n }\n }\n val isRingTopological: Boolean = {\n if(edges.length == nodes.length){\n nodes.count(_.neighbours.length == 2) == nodes.length\n }else{\n false\n }\n }\n\n\n }\n case class Node(node: Int){\n val neighbours: ListBuffer[Node] = ListBuffer[Node]()\n def clearNeighbours(): Unit = neighbours.clear()\n def addNeighbour(n: Node): Unit = neighbours.append(n)\n }\n case class UndirectedEdge(a: Node, b: Node)\n\n\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = return next().toInt\n }\n}"}], "negative_code": [], "src_uid": "7bb088ce5e4e2101221c706ff87841e4"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { i =>\n val n, s, t = ni()\n out.println(n - min(s, t) + 1)\n }\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject A_1187 extends App {\n val q = readInt()\n\n 1 to q foreach { _ =>\n val Array(n, a, b) = readLine().split(\" \").map(_.toInt)\n val answer = if (a + b == n) {\n Math.max(a, b) + 1\n } else {\n if (n == Math.max(a, b)) {\n Math.max(a, b) - Math.min(a, b) + 1\n } else {\n n - Math.min(a, b) + 1\n }\n }\n\n println(answer)\n }\n\n}\n"}], "negative_code": [], "src_uid": "fb0a4c8f737c36596c2d8c1ae0d1e34e"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n\n def classify(str: String) = {\n if (str.distinct.length == 1) 1\n else if (str.distinct.length == str.length && str.sorted.reverse == str) 2\n else 3\n }\n\n val in = Source.stdin.getLines()\n var n = in.next().toInt\n val data = (1 to n).map { _ =>\n val Array(countStr, name) = in.next().split(' ')\n val groups = (1 to countStr.toInt).map(_ => in.next().replaceAll(\"\\\\-\", \"\")).map(classify)\n .groupBy(i => i).map(i => i._1 -> i._2.length)\n (groups.getOrElse(1, 0), groups.getOrElse(2, 0), groups.getOrElse(3, 0), name)\n }\n val maxTaxi = data.maxBy(_._1)._1\n val maxPizza = data.maxBy(_._2)._2\n val maxGirl = data.maxBy(_._3)._3\n println(data.filter(_._1 == maxTaxi)\n .map(_._4).mkString(\"If you want to call a taxi, you should call: \", \", \", \".\"))\n println(data.filter(_._2 == maxPizza)\n .map(_._4).mkString(\"If you want to order a pizza, you should call: \", \", \", \".\"))\n println(data.filter(_._3 == maxGirl)\n .map(_._4).mkString(\"If you want to go to a cafe with a wonderful girl, you should call: \", \", \", \".\"))\n}", "positive_code": [{"source_code": "object Main {\n def isTaxi(str: String) = str forall (_ == str(0))\n def isPizza(str: String) = str sliding(2) forall(t => t(0) > t(1))\n \n def main(args: Array[String]) {\n val n = readInt()\n val map = scala.collection.mutable.LinkedHashMap[String, (Int, Int, Int)]()\n for(_ <- 1 to n) {\n val Array(k, name) = readLine().split(\" \")\n var taxies = 0\n var pizzaes = 0\n var girls = 0\n for(_ <- 1 to k.toInt) {\n val str = readLine().replaceAll(\"\\\\-\", \"\")\n if (isTaxi(str)) taxies += 1\n else if(isPizza(str)) pizzaes += 1\n else girls += 1\n }\n map(name.toString) = (taxies, pizzaes, girls)\n }\n val max1 = map.values.map(_._1).max\n println(\"If you want to call a taxi, you should call: \" +\n map.filter(_._2._1 == max1).keys.mkString(\", \") + \".\")\n \n val max2 = map.values.map(_._2).max\n println(\"If you want to order a pizza, you should call: \" +\n map.filter(_._2._2 == max2).keys.mkString(\", \") + \".\")\n \n val max3 = map.values.map(_._3).max\n println(\"If you want to go to a cafe with a wonderful girl, you should call: \" +\n map.filter(_._2._3 == max3).keys.mkString(\", \") + \".\")\n }\n}"}, {"source_code": "\nimport scala.util.DynamicVariable\nobject Main {\n private val inVar = new DynamicVariable[java.io.BufferedReader](new java.io.BufferedReader(new java.io.InputStreamReader(java.lang.System.in)))\n def in = inVar.value\n var MyFriends =new Array[MyFriend](0)\n def MMM(): String = {\n var NamberType1:Int =0\n var NamberType2:Int =0\n var NamberType3:Int =0\n var FriendNamberType1:String = \"\"\n var FriendNamberType2:String = \"\"\n var FriendNamberType3:String = \"\"\n \n for(i<- 0 until MyFriends.length){\n \t if(MyFriends(i).NamberType1>NamberType1){\n \t NamberType1=MyFriends(i).NamberType1\n \t }\n \t if(MyFriends(i).NamberType2>NamberType2){\n \t NamberType2=MyFriends(i).NamberType2\n \t }\n \t if(MyFriends(i).NamberType3>NamberType3){\n \t NamberType3=MyFriends(i).NamberType3\n \t }\n }\n for(i<- 0 until MyFriends.length){\n if(MyFriends(i).NamberType1==NamberType1){\n \t if(FriendNamberType1==\"\"){\n \t FriendNamberType1=MyFriends(i).Name\n \t }else{\n \t FriendNamberType1+=\", \"+MyFriends(i).Name\n \t }\n \t }\n \t if(MyFriends(i).NamberType2==NamberType2){\n \t if(FriendNamberType2==\"\"){\n \t FriendNamberType2=MyFriends(i).Name\n \t }else{\n \t FriendNamberType2+=\", \"+MyFriends(i).Name\n \t }\n \t }\n \t if(MyFriends(i).NamberType3==NamberType3){\n \t if(FriendNamberType3==\"\"){\n \t FriendNamberType3=MyFriends(i).Name\n \t }else{\n \t FriendNamberType3+=\", \"+MyFriends(i).Name\n \t }\n \t }\n }\n \n return \"If you want to call a taxi, you should call: \" + FriendNamberType1 + \".\\n\" + \"If you want to order a pizza, you should call: \" + FriendNamberType2+\".\\n\" + \"If you want to go to a cafe with a wonderful girl, you should call: \" + FriendNamberType3+ \".\\n\"\n }\n \n def Read():String ={\n var result: String = \"\"\n try{\n result = in.readLine()\n }\n catch {\n case e: Exception => result=\"\"\n }\n result\n }\n \n def main(args: Array[String]) {\n var CountFriends: Int = Read().toInt\n MyFriends= new Array[MyFriend](CountFriends)\n for(i<- 0 until CountFriends){\n var line = Read()\n if(line !=\"\"){\n \t var CountName = line.split(\" \")\n \t\t\t var CountNambers: Int = CountName(0).toInt\n \t\t\t MyFriends(i)=new MyFriend(CountName(1),CountNambers)\n \t for(j<- 0 until CountNambers){\n \t\t MyFriends(i).Nambers(j)= new PhoneNumber(Read())\n \t }\n \t MyFriends(i).TypesOfNamber() \n }\n }\n println(MMM())\n }\n}\n\nclass PhoneNumber(number: String) {\n var Number: String = number\n var TypeNumber: Int = GetTypeNumber(number)\n private def GetTypeNumber(n:String): Int = {\n\tif(number != null){\n\t var number=n.replace(\"-\",\"\")\n\tif(number == new String (\"\"+number(0)+number(0)+number(0)+number(0)+number(0)+number(0))){\n\t return 1\n\t}else{\n\t\tfor(i<- 0 until number.length-1){\n\t\t\tif(number(i).toInt <= number(i+1).toInt) \n\t\t\t\treturn 3\n\t\t}\n\t\treturn 2\n\t }\n\t}\n\treturn 3\n }\n}\n\nclass MyFriend(name: String, countNumbers: Int){\n var Name:String = name\n var Nambers: Array[PhoneNumber] =new Array[PhoneNumber](countNumbers)\n var NamberType1:Int =0\n var NamberType2:Int =0\n var NamberType3:Int =0\n def TypesOfNamber(){\n for(j<- 0 until Nambers.length){\n if(Nambers(j).TypeNumber==1){\n NamberType1+=1\n }\n if(Nambers(j).TypeNumber==2){\n NamberType2+=1\n }\n if(Nambers(j).TypeNumber==3){\n NamberType3+=1\n }\n }\n \n } \n}\n\n"}], "negative_code": [{"source_code": "\nimport scala.util.DynamicVariable\nobject Main {\n private val inVar = new DynamicVariable[java.io.BufferedReader](new java.io.BufferedReader(new java.io.InputStreamReader(java.lang.System.in)))\n def in = inVar.value\n var MyFriends =new Array[MyFriend](0)\n def MMM(): String = {\n var NamberType1:Int =0\n var NamberType2:Int =0\n var NamberType3:Int =0\n var FriendNamberType1:String = \"\"\n var FriendNamberType2:String = \"\"\n var FriendNamberType3:String = \"\"\n \n for(i<- 0 until MyFriends.length){\n \t if(MyFriends(i).NamberType1>NamberType1){\n \t NamberType1=MyFriends(i).NamberType1\n \t }\n \t if(MyFriends(i).NamberType2>NamberType2){\n \t NamberType2=MyFriends(i).NamberType2\n \t }\n \t if(MyFriends(i).NamberType3>NamberType3){\n \t NamberType3=MyFriends(i).NamberType3\n \t }\n }\n for(i<- 0 until MyFriends.length){\n if(MyFriends(i).NamberType1==NamberType1){\n \t if(FriendNamberType1==\"\"){\n \t FriendNamberType1=MyFriends(i).Name\n \t }else{\n \t FriendNamberType1+=\", \"+MyFriends(i).Name\n \t }\n \t }\n \t if(MyFriends(i).NamberType2==NamberType2){\n \t if(FriendNamberType2==\"\"){\n \t FriendNamberType2=MyFriends(i).Name\n \t }else{\n \t FriendNamberType2+=\", \"+MyFriends(i).Name\n \t }\n \t }\n \t if(MyFriends(i).NamberType3==NamberType3){\n \t if(FriendNamberType3==\"\"){\n \t FriendNamberType3=MyFriends(i).Name\n \t }else{\n \t FriendNamberType3+=\", \"+MyFriends(i).Name\n \t }\n \t }\n }\n \n return \"If you want to call a taxi, you should call: \" + FriendNamberType1 + \".\\n\" + \"If you want to order a pizza, you should call: \" + FriendNamberType2+\".\\n\" + \"If you want to go to a cafe with a wonderful girl, you should call: \" + FriendNamberType3+ \".\\n\"\n }\n \n def Read():String ={\n var result: String = \"\"\n try{\n result = in.readLine()\n }\n catch {\n case e: Exception => result=\"\"\n }\n result\n }\n \n def main(args: Array[String]) {\n var CountFriends: Int = Read().toInt\n MyFriends= new Array[MyFriend](CountFriends)\n for(i<- 0 until CountFriends){\n var line = Read()\n if(line !=\"\"){\n \t var CountName = line.split(\" \")\n \t\t\t var CountNambers: Int = CountName(0).toInt\n \t\t\t MyFriends(i)=new MyFriend(CountName(1),CountNambers)\n \t for(j<- 0 until CountNambers){\n \t\t MyFriends(i).Nambers(j)= new PhoneNumber(Read())\n \t }\n \t MyFriends(i).TypesOfNamber() \n }\n }\n println(MMM())\n }\n}\n\nclass PhoneNumber(number: String) {\n var Number: String = number\n var TypeNumber: Int = GetTypeNumber(number)\n private def GetTypeNumber(n:String): Int = {\n\tif(number != null){\n\t var number=n.replace(\"-\",\"\")\n\tif(number == new String (\"\"+number(0)+number(0)+number(0)+number(0)+number(0)+number(0))){\n\t return 1\n\t}else{\n\t\tfor(i<- 0 until number.length-1){\n\t\t\tif(number(i) < number(i+1)) \n\t\t\t\treturn 3\n\t\t}\n\t\treturn 2\n\t }\n\t}\n\treturn 3\n }\n}\n\nclass MyFriend(name: String, countNumbers: Int){\n var Name:String = name\n var Nambers: Array[PhoneNumber] =new Array[PhoneNumber](countNumbers)\n var NamberType1:Int =0\n var NamberType2:Int =0\n var NamberType3:Int =0\n def TypesOfNamber(){\n for(j<- 0 until Nambers.length){\n if(Nambers(j).TypeNumber==1){\n NamberType1+=1\n }\n if(Nambers(j).TypeNumber==2){\n NamberType2+=1\n }\n if(Nambers(j).TypeNumber==3){\n NamberType3+=1\n }\n }\n \n } \n}\n\n"}, {"source_code": "\nimport scala.util.DynamicVariable\nobject Main {\n private val inVar = new DynamicVariable[java.io.BufferedReader](new java.io.BufferedReader(new java.io.InputStreamReader(java.lang.System.in)))\n def in = inVar.value\n var MyFriends =new Array[MyFriend](0)\n def MMM(): String = {\n var NamberType1:Int =0\n var NamberType2:Int =0\n var NamberType3:Int =0\n var FriendNamberType1:String = \"\"\n var FriendNamberType2:String = \"\"\n var FriendNamberType3:String = \"\"\n \n for(i<- 0 until MyFriends.length){\n \t if(MyFriends(i).NamberType1>NamberType1){\n \t NamberType1=MyFriends(i).NamberType1\n \t }\n \t if(MyFriends(i).NamberType2>NamberType2){\n \t NamberType2=MyFriends(i).NamberType2\n \t }\n \t if(MyFriends(i).NamberType3>NamberType3){\n \t NamberType3=MyFriends(i).NamberType3\n \t }\n }\n for(i<- 0 until MyFriends.length){\n if(MyFriends(i).NamberType1==NamberType1){\n \t if(FriendNamberType1==\"\"){\n \t FriendNamberType1=MyFriends(i).Name\n \t }else{\n \t FriendNamberType1+=\", \"+MyFriends(i).Name\n \t }\n \t }\n \t if(MyFriends(i).NamberType2==NamberType2){\n \t if(FriendNamberType2==\"\"){\n \t FriendNamberType2=MyFriends(i).Name\n \t }else{\n \t FriendNamberType2+=\", \"+MyFriends(i).Name\n \t }\n \t }\n \t if(MyFriends(i).NamberType3==NamberType3){\n \t if(FriendNamberType3==\"\"){\n \t FriendNamberType3=MyFriends(i).Name\n \t }else{\n \t FriendNamberType3+=\", \"+MyFriends(i).Name\n \t }\n \t }\n }\n \n return \"If you want to call a taxi, you should call: \" + FriendNamberType1 + \".\\n\" + \"If you want to order a pizza, you should call: \" + FriendNamberType2+\".\\n\" + \"If you want to go to a cafe with a wonderful girl, you should call: \" + FriendNamberType3+ \".\\n\"\n }\n \n def Read():String ={\n var result: String = \"\"\n try{\n result = in.readLine()\n }\n catch {\n case e: Exception => result=\"\"\n }\n result\n }\n \n def main(args: Array[String]) {\n var CountFriends: Int = Read().toInt\n MyFriends= new Array[MyFriend](CountFriends)\n for(i<- 0 until CountFriends){\n var line = Read()\n if(line !=\"\"){\n \t var CountName = line.split(\" \")\n \t\t\t var CountNambers: Int = CountName(0).toInt\n \t\t\t MyFriends(i)=new MyFriend(CountName(1),CountNambers)\n \t for(j<- 0 until CountNambers){\n \t\t MyFriends(i).Nambers(j)= new PhoneNumber(Read())\n \t }\n \t MyFriends(i).TypesOfNamber() \n }\n }\n println(MMM())\n }\n}\n\nclass PhoneNumber(number: String) {\n var Number: String = number\n var TypeNumber: Int = GetTypeNumber(number)\n private def GetTypeNumber(number:String): Int = {\n\tif(number != null){\n\t number.replace(\"-\",\"\")\n\tif(number == number(0)+number(0)+number(0)+number(0)+number(0)+number(0)){\n\t return 1\n\t}else{\n\t\tfor(i<- 0 until number.length-1){\n\t\t\tif(number(i) < number(i+1)) \n\t\t\t\treturn 3\n\t\t}\n\t\treturn 2\n\t }\n\t}\n\treturn 3\n }\n}\n\nclass MyFriend(name: String, countNumbers: Int){\n var Name:String = name\n var Nambers: Array[PhoneNumber] =new Array[PhoneNumber](countNumbers)\n var NamberType1:Int =0\n var NamberType2:Int =0\n var NamberType3:Int =0\n def TypesOfNamber(){\n for(j<- 0 until Nambers.length){\n if(Nambers(j).TypeNumber==1){\n NamberType1+=1\n }\n if(Nambers(j).TypeNumber==2){\n NamberType2+=1\n }\n if(Nambers(j).TypeNumber==3){\n NamberType3+=1\n }\n }\n \n } \n}\n\n"}], "src_uid": "4791a795119c185b3aec91b6f8af8f03"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(val a: Int, val b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return a.compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n for (tt <- 1 to t) {\n val a = readInt()\n val b = readInt()\n val c = readInt()\n val k = a + c - 2 * b\n if (k % 3 == 0)\n writer.println(0)\n else\n writer.println(1)\n }\n writer.flush()\n}\n", "positive_code": [{"source_code": "object _1605A extends CodeForcesApp {\r\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\r\n\r\n override def solve(io: IO) = io.repeat {\r\n val a1, a2, a3 = io.read[Int]\r\n val ans = (a1 + a3 - 2*a2) % 3\r\n io.write(if (ans == 0) 0 else 1)\r\n }\r\n}\r\n/****************************[Ignore Template Below]****************************************/\r\ntrait CodeForcesApp {\r\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\r\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\r\n def solve(io: IO): Any\r\n def main(args: Array[String]): Unit = {\r\n val io = new IO(System.in, System.out)\r\n try solve(io) finally io.close()\r\n }\r\n}\r\n/****************************[Scala Collection Utils]****************************************/\r\nobject Utils {\r\n import scala.collection.mutable\r\n\r\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\r\n\r\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\r\n\r\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\r\n\r\n val charToInt: Char => Int = Character.getNumericValue\r\n val intToChar: Int => Char = Character.forDigit(_, 10)\r\n\r\n implicit class GenericExtensions[A](a: A) {\r\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\r\n }\r\n\r\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\r\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\r\n\r\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\r\n\r\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\r\n val freqTable = t.groupBy(identity).mapValues(_.size)\r\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\r\n }\r\n }\r\n\r\n implicit class PairExtensions[A, B](p: (A, B)) {\r\n def key = p._1\r\n def value = p._2\r\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\r\n }\r\n\r\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\r\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\r\n }\r\n\r\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\r\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\r\n }\r\n\r\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\r\n def notContains(x: A): Boolean = !(s contains x)\r\n def toMutable = mutable.Set.empty[A] ++ s\r\n }\r\n\r\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\r\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\r\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\r\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\r\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\r\n }\r\n\r\n implicit class BooleanExtensions(x: Boolean) {\r\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\r\n def toEnglish = if(x) \"Yes\" else \"No\"\r\n }\r\n\r\n implicit class IntExtensions(val x: Int) extends AnyVal {\r\n @inline def isEven = x%2 == 0\r\n @inline def isOdd = x%2 == 1\r\n }\r\n\r\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\r\n\r\n def map[K] = new {\r\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\r\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\r\n override def apply(key: K) = getOrElseUpdate(key, f(key))\r\n }\r\n }\r\n\r\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\r\n\r\n def memoize[A, B](f: A => B): A => B = map[A] using f\r\n}\r\n/***********************************[Scala I/O]*********************************************/\r\nimport java.io._, java.util.StringTokenizer\r\nimport scala.collection.generic.CanBuild\r\n\r\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\r\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\r\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\r\n\r\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\r\n val printer = new PrintWriter(out, true)\r\n\r\n @inline private[this] def tokenizer() = {\r\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\r\n tokenizers.headOption\r\n }\r\n\r\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\r\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\r\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\r\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\r\n\r\n override def next() = tokenizer().get.nextToken()\r\n override def hasNext = tokenizer().nonEmpty\r\n\r\n def write(obj: Any*): this.type = writeAll(obj)\r\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\r\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\r\n def query[A: IO.Read](question: Any): A = writeLine(question).read\r\n\r\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\r\n\r\n override def flush() = printer.flush()\r\n def close() = {\r\n flush()\r\n in.close()\r\n printer.close()\r\n }\r\n}\r\nobject IO {\r\n class Read[A](val apply: IO => A) {\r\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\r\n }\r\n object Read {\r\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\r\n implicit val string : Read[String] = new Read(_.next())\r\n implicit val int : Read[Int] = string.map(_.toInt)\r\n implicit val long : Read[Long] = string.map(_.toLong)\r\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\r\n implicit val double : Read[Double] = string.map(_.toDouble)\r\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\r\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\r\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\r\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\r\n implicit val boolean : Read[Boolean] = string map {s =>\r\n s.toLowerCase match {\r\n case \"yes\" | \"true\" | \"1\" => true\r\n case \"no\" | \"false\" | \"0\" => false\r\n case _ => s.toBoolean\r\n }\r\n }\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object _1605A extends CodeForcesApp {\r\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\r\n\r\n override def solve(io: IO) = io.repeat {\r\n val a1, a2, a3 = io.read[Int]\r\n val ans = (a1 + a3 - 2*a2) mod 3\r\n io.write(ans)\r\n }\r\n\r\n implicit class IntegralExtensions[A](x: A)(implicit n: Integral[A]) {\r\n import scala.collection.immutable.NumericRange, Integral.Implicits._\r\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\r\n }\r\n}\r\n/****************************[Ignore Template Below]****************************************/\r\ntrait CodeForcesApp {\r\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\r\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\r\n def solve(io: IO): Any\r\n def main(args: Array[String]): Unit = {\r\n val io = new IO(System.in, System.out)\r\n try solve(io) finally io.close()\r\n }\r\n}\r\n/****************************[Scala Collection Utils]****************************************/\r\nobject Utils {\r\n import scala.collection.mutable\r\n\r\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\r\n\r\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\r\n\r\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\r\n\r\n val charToInt: Char => Int = Character.getNumericValue\r\n val intToChar: Int => Char = Character.forDigit(_, 10)\r\n\r\n implicit class GenericExtensions[A](a: A) {\r\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\r\n }\r\n\r\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\r\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\r\n\r\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\r\n\r\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\r\n val freqTable = t.groupBy(identity).mapValues(_.size)\r\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\r\n }\r\n }\r\n\r\n implicit class PairExtensions[A, B](p: (A, B)) {\r\n def key = p._1\r\n def value = p._2\r\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\r\n }\r\n\r\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\r\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\r\n }\r\n\r\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\r\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\r\n }\r\n\r\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\r\n def notContains(x: A): Boolean = !(s contains x)\r\n def toMutable = mutable.Set.empty[A] ++ s\r\n }\r\n\r\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\r\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\r\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\r\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\r\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\r\n }\r\n\r\n implicit class BooleanExtensions(x: Boolean) {\r\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\r\n def toEnglish = if(x) \"Yes\" else \"No\"\r\n }\r\n\r\n implicit class IntExtensions(val x: Int) extends AnyVal {\r\n @inline def isEven = x%2 == 0\r\n @inline def isOdd = x%2 == 1\r\n }\r\n\r\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\r\n\r\n def map[K] = new {\r\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\r\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\r\n override def apply(key: K) = getOrElseUpdate(key, f(key))\r\n }\r\n }\r\n\r\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\r\n\r\n def memoize[A, B](f: A => B): A => B = map[A] using f\r\n}\r\n/***********************************[Scala I/O]*********************************************/\r\nimport java.io._, java.util.StringTokenizer\r\nimport scala.collection.generic.CanBuild\r\n\r\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\r\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\r\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\r\n\r\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\r\n val printer = new PrintWriter(out, true)\r\n\r\n @inline private[this] def tokenizer() = {\r\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\r\n tokenizers.headOption\r\n }\r\n\r\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\r\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\r\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\r\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\r\n\r\n override def next() = tokenizer().get.nextToken()\r\n override def hasNext = tokenizer().nonEmpty\r\n\r\n def write(obj: Any*): this.type = writeAll(obj)\r\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\r\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\r\n def query[A: IO.Read](question: Any): A = writeLine(question).read\r\n\r\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\r\n\r\n override def flush() = printer.flush()\r\n def close() = {\r\n flush()\r\n in.close()\r\n printer.close()\r\n }\r\n}\r\nobject IO {\r\n class Read[A](val apply: IO => A) {\r\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\r\n }\r\n object Read {\r\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\r\n implicit val string : Read[String] = new Read(_.next())\r\n implicit val int : Read[Int] = string.map(_.toInt)\r\n implicit val long : Read[Long] = string.map(_.toLong)\r\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\r\n implicit val double : Read[Double] = string.map(_.toDouble)\r\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\r\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\r\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\r\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\r\n implicit val boolean : Read[Boolean] = string map {s =>\r\n s.toLowerCase match {\r\n case \"yes\" | \"true\" | \"1\" => true\r\n case \"no\" | \"false\" | \"0\" => false\r\n case _ => s.toBoolean\r\n }\r\n }\r\n }\r\n}\r\n"}], "src_uid": "5bffe38e3ac9511a30ee02b4ec5cb1d5"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A, B = ns(N)\n\n def test(a0: Int, a1: Int, b0: Int, b1: Int) = {\n val cnt = mutable.Map[Int, Int]().withDefaultValue(0)\n def add(c: Int) { cnt(c) = cnt(c) + 1 }\n add(a0)\n add(a1)\n add(b0)\n add(b1)\n cnt.forall(_._2 % 2 == 0)\n }\n\n var ans = 0\n REP(N / 2) { i =>\n var ms = 2\n val zip = mutable.Set(A(i), A(N - 1 - i), B(i), B(N - 1 - i)).toSeq.zipWithIndex.toMap\n\n REP(4) { a0 =>\n REP(4) { a1 =>\n if (test(a0, a1, zip(B(i)), zip(B(N - 1 - i)))) {\n var cnt = 0\n if (a0 != zip(A(i))) cnt += 1\n if (a1 != zip(A(N - 1 - i))) cnt += 1\n ms = min(ms, cnt)\n }\n }\n }\n ans += ms\n }\n\n if (N % 2 > 0) {\n val i = N / 2\n if (A(i) != B(i)) ans += 1\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A, B = ns(N)\n\n val memo = Array.fill[Int](26, 26, 26, 26)(-1)\n def test(a0: Char, a1: Char, b0: Char, b1: Char) = {\n if (memo(a0-'a')(a1-'a')(b0-'a')(b1-'a') == -1) {\n val cnt = mutable.Map[Char, Int]().withDefaultValue(0)\n def add(c: Char) { cnt(c) = cnt(c) + 1 }\n add(a0)\n add(a1)\n add(b0)\n add(b1)\n memo(a0-'a')(a1-'a')(b0-'a')(b1-'a') = if (cnt.forall(_._2 % 2 == 0)) 1 else 0\n }\n memo(a0-'a')(a1-'a')(b0-'a')(b1-'a') == 1\n }\n\n var ans = 0\n REP(N / 2) { i =>\n var ms = 2\n REP(26, 'a') { a0 =>\n REP(26, 'a') { a1 =>\n if (test(a0.toChar, a1.toChar, B(i), B(N - 1 - i))) {\n var cnt = 0\n if (a0 != A(i)) cnt += 1\n if (a1 != A(N - 1 - i)) cnt += 1\n ms = min(ms, cnt)\n }\n }\n }\n ans += ms\n }\n\n if (N % 2 > 0) {\n val i = N / 2\n if (A(i) != B(i)) ans += 1\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A, B = ns(N)\n\n val memo = Array.fill[Int](4, 4, 4, 4)(-1)\n def test(a0: Int, a1: Int, b0: Int, b1: Int) = {\n if (memo(a0)(a1)(b0)(b1) == -1) {\n val cnt = mutable.Map[Int, Int]().withDefaultValue(0)\n def add(c: Int) { cnt(c) = cnt(c) + 1 }\n\n add(a0)\n add(a1)\n add(b0)\n add(b1)\n memo(a0)(a1)(b0)(b1) = if (cnt.forall(_._2 % 2 == 0)) 1 else 0\n }\n memo(a0)(a1)(b0)(b1) == 1\n }\n\n var ans = 0\n REP(N / 2) { i =>\n var ms = 2\n val zip = mutable.Set(A(i), A(N - 1 - i), B(i), B(N - 1 - i)).toSeq.zipWithIndex.toMap\n\n REP(4) { a0 =>\n REP(4) { a1 =>\n if (test(a0, a1, zip(B(i)), zip(B(N - 1 - i)))) {\n var cnt = 0\n if (a0 != zip(A(i))) cnt += 1\n if (a1 != zip(A(N - 1 - i))) cnt += 1\n ms = min(ms, cnt)\n }\n }\n }\n ans += ms\n }\n\n if (N % 2 > 0) {\n val i = N / 2\n if (A(i) != B(i)) ans += 1\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A, B = ns(N)\n\n var ans = 0\n REP(N / 2) { i =>\n val cnt = mutable.Map[Char, Int]().withDefaultValue(0)\n def add(c: Char){ cnt(c) = cnt(c) + 1 }\n add(A(i))\n add(A(N - 1 - i))\n add(B(i))\n add(B(N - 1 - i))\n if (cnt.exists(_._2 % 2 > 0)) {\n if (B(i) == B(N - 1 - i)) ans += 1\n else {\n val bs = ArrayBuffer(B(i), B(N - 1 - i))\n bs -= A(i)\n bs -= A(N - 1 - i)\n ans += bs.size\n }\n }\n }\n\n if (N % 2 > 0) {\n val i = N / 2\n if (A(i) != B(i)) ans += 1\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A, B = ns(N)\n\n var ans = 0\n REP(N / 2) { i =>\n val cnt = mutable.Map[Char, Int]().withDefaultValue(0)\n def add(c: Char){ cnt(c) = cnt(c) + 1 }\n add(A(i))\n add(A(N - 1 - i))\n add(B(i))\n add(B(N - 1 - i))\n if (!(cnt.size == 1 || cnt.size == 2 && cnt.forall(_._2 == 2))) {\n val bs = ArrayBuffer(B(i), B(N - 1 - i))\n bs -= A(i)\n bs -= A(N - 1 - i)\n ans += bs.size\n }\n }\n\n if (N % 2 > 0) {\n val i = N / 2\n if (A(i) != B(i)) ans += 1\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A, B = ns(N)\n\n var ans = 0\n REP(N / 2) { i =>\n val cnt = mutable.Map[Char, Int]().withDefaultValue(0)\n def add(c: Char){ cnt(c) = cnt(c) + 1 }\n add(A(i))\n add(A(N - 1 - i))\n add(B(i))\n add(B(N - 1 - i))\n if (cnt.exists(_._2 % 2 > 0)) {\n val bs = ArrayBuffer(B(i), B(N - 1 - i))\n bs -= A(i)\n bs -= A(N - 1 - i)\n ans += bs.size\n }\n }\n\n if (N % 2 > 0) {\n val i = N / 2\n if (A(i) != B(i)) ans += 1\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "259b4b538743608227bb6d22453b0833"} {"source_code": "import scala.collection.mutable\n\n/**\n * Created by lurker on 2014. 8. 15..\n */\nobject CF263_3 extends App {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n val Array(n) = readInts(1)\n val arr = readInts(n)\n\n val sortedArr = arr.sortBy(identity)\n var result = 0L\n var i = 0\n var multiplier = if(n==1) 1L else 2L\n while(i b + i)\n var res = sum\n\n for (i <- 1 until n) {\n res += sum\n sum -= a(i-1)\n }\n\n writer.println(res)\n }\n}\n"}, {"source_code": "object A461 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readLongs(n).sortBy(identity).reverse\n\n var res = 0L\n for(i <- input.indices) {\n if(i == 0 || i == 1) {\n res += input(i) * n\n } else {\n res += input(i) * (n-i+1)\n }\n }\n println(res)\n }\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by Kuang.Ru on 14-9-18.\n */\nobject A461 extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n var a = new ArrayBuffer[Long]()\n var j = 0\n\n while (j < n) {\n a += sc.nextInt()\n j += 1\n }\n\n val newA = a.sortWith(_ > _)\n var score: Long = 0\n\n if (n >= 2) {\n score += newA(0) * n + newA(1) * n\n var i = 2\n\n while (i < n) {\n score += newA(i) * (n - i + 1)\n i += 1\n }\n } else {\n score += newA(0)\n }\n\n println(score)\n}\n"}, {"source_code": "object main extends App with fastIO {\n \n val n = nextInt\n \n var (ans, cnt) = (0l, 1l)\n var a = Array.fill(n)(nextInt) sortBy((i) => i)\n a foreach { (i) => cnt += 1; ans += i * cnt }\n \n println(ans - a.max)\n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Main {\n def main(args: Array[String]): Unit = {\n readLine()\n val a = readLine().split(\" \").map(_.toLong)\n val ans = if (a.length == 1) {\n a.head.toLong\n } else {\n a.sorted.zipWithIndex.map { case\n (x, i) => x * (i + 2)\n }.sum - a.max\n }\n println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "//package solutions\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * @author traff\n */\n\n\nobject Solution_TaskA extends App {\n override def main(args: Array[String]): Unit = {\n val out = new PrintWriter(System.out)\n\n run(new Scanner(System.in), out)\n\n out.close()\n }\n\n def run(scanner: Scanner, writer: PrintWriter): Unit = {\n val n = scanner.nextInt()\n var a = new Array[Int](n)\n for (i <- 1 to n) {\n a(i-1) = scanner.nextInt()\n }\n\n a = a.sortWith(_ < _)\n\n var sum: Long = a.sum\n var res = sum\n\n for (i <- 1 until n) {\n res += sum\n sum -= a(i-1)\n }\n\n writer.println(res)\n }\n}\n"}, {"source_code": "//package solutions\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * @author traff\n */\n\n\nobject Solution_TaskA extends App {\n override def main(args: Array[String]): Unit = {\n val out = new PrintWriter(System.out)\n\n run(new Scanner(System.in), out)\n\n out.close()\n }\n\n def run(scanner: Scanner, writer: PrintWriter): Unit = {\n val n = scanner.nextInt()\n var a = new Array[Int](n)\n for (i <- 1 to n) {\n a(i-1) = scanner.nextInt()\n }\n\n a = a.sortWith(_ < _)\n\n var sum = a.sum\n var res = sum\n\n for (i <- 1 until n) {\n res += sum\n sum -= a(i-1)\n }\n\n writer.println(res)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by Kuang.Ru on 14-9-18.\n */\nobject A461 extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n var a = new ArrayBuffer[Int]()\n var j = 0\n\n while (j < n) {\n a += sc.nextInt()\n j += 1\n }\n\n val newA = a.sortWith(_ > _)\n var score: Long = 0\n\n if (n >= 2) {\n score += newA(0) * n + newA(1) * n\n var i = 2\n\n while (i < n) {\n score += newA(i) * (n - i + 1)\n i += 1\n }\n } else {\n score += newA(0)\n }\n\n println(score)\n}\n"}, {"source_code": "object main extends App with fastIO {\n \n val n = nextInt\n \n var (ans, cnt) = (0, 1)\n var a = Array.fill(n)(nextInt) sortBy((i) => i)\n a foreach { (i) => cnt += 1; ans += i * cnt }\n \n println(ans - a.max)\n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "object main extends App with fastIO {\n \n val n = nextInt\n \n var (ans, cnt) = (0l, 1)\n var a = Array.fill(n)(nextInt) sortBy((i) => i)\n a foreach { (i) => cnt += 1; ans += i * cnt }\n \n println(ans - a.max)\n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "import scala.collection.mutable\n\n/**\n * Created by lurker on 2014. 8. 15..\n */\nobject CF263_3 extends App {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n val Array(n) = readInts(1)\n val arr = readInts(n)\n\n val sortedArr = arr.sortBy(identity)\n var result = 0L\n var i = 0\n var multiplier = if(n==1) 1 else 2\n while(i set + el * el\n }\n val min = Math.min(m, n)\n println(min + 1)\n println((0 to min).map(i => s\"$i ${min - i}\").mkString(\"\\n\"))\n\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test5 extends App {\n val Array(n,m)=readLine.split(\" \").map(_.toInt)\n val min=math.min(n,m)\n \n println(min+1)\n for(i<-0 to min) println(min-i+\" \"+i)\n} \n\n\n\n"}, {"source_code": "import scala.Math._;\nimport scala.collection.mutable.LinkedList\n\nobject App {\n\tdef readInts:Array[Int] = (readLine split \" \") map (_.toInt)\n //> readInts: => Array[Int] //> solve: (n: Int, m: Int, prev: Int, a: Int, b: Int)(Int, Int)\n\t\n\tdef solve(deep: Int, n: Int):Long = {\n\t if (deep == n) n\n\t else solve(deep + 1, n) + (deep * (n - deep)) \n\t}\n\t\n\tdef f1_io() = {\n\t val Array(n, m) = readInts\n\t\tval a = min(n, m)\n\t\tprintln(a + 1)\n\t\tfor(i <- 0 to a) {\n\t\t println(i + \" \" + (m - i))\n\t\t} \n\t \n\t} \n def main(args: Array[String]): Unit = {\n\tf1_io\n }\n\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n var Array(n, m) = in.next().split(' ').map(_.toInt)\n val squares = (0 to n + m).foldLeft(Set.empty[Int]) {\n case (set, el) => set + el * el\n }\n val fx = 0\n val fy = 0\n val result1 = (0 to n).foldLeft(List.empty[(Int, Int)]) {\n case(list, i) => (0 to m).foldLeft(list) {\n case (l, el) if el + i == 0 => l\n case (l, el) if l.forall{\n case(x, y) => !squares.contains((x - i)* (x - i) + (y - el) * (y - el))\n } => (i, el) :: l\n case (l, el) => l\n }\n }\n val result2 = (0 to m).foldLeft(List.empty[(Int, Int)]) {\n case(list, i) => (0 to n).foldLeft(list) {\n case (l, el) if el + i == 0 => l\n case (l, el) if l.forall{\n case(x, y) => !squares.contains((x - i)* (x - i) + (y - el) * (y - el))\n } => (el, i) :: l\n case (l, el) => l\n }\n }\n val result = if (result1.length > result2.length) result1 else result2\n println(result.length)\n println(result.map(i => s\"${i._1} ${i._2}\").mkString(\"\\n\"))\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n var Array(n, m) = in.next().split(' ').map(_.toInt)\n val squares = (0 to n + m).foldLeft(Set.empty[Int]) {\n case (set, el) => set + el * el\n }\n val min = Math.min(m, n)\n println(min)\n println((0 to min).map(i => s\"$i ${min - i}\").mkString(\"\\n\"))\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n var Array(n, m) = in.next().split(' ').map(_.toInt)\n val squares = (0 to n + m).foldLeft(Set.empty[Int]) {\n case (set, el) => set + el * el\n }\n val min = Math.min(m, n)\n println((0 to min).map(i => s\"$i ${min - i}\").mkString(\"\\n\"))\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n var Array(n, m) = in.next().split(' ').map(_.toInt)\n val squares = (0 to n + m).foldLeft(Set.empty[Int]) {\n case (set, el) => set + el * el\n }\n val fx = 0\n val fy = 0\n val result = (0 to n).foldLeft(List.empty[(Int, Int)]) {\n case(list, i) => (0 to m).foldLeft(list) {\n case (l, el) if l.forall{\n case(x, y) => !squares.contains((x - i)* (x - i) + (y - el) * (y - el))\n } => (i, el) :: l\n case (l, el) => l\n }\n }\n\n println(result.length)\n println(result.map(i => s\"${i._1} ${i._2}\").mkString(\"\\n\"))\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n var Array(n, m) = in.next().split(' ').map(_.toInt)\n val squares = (0 to n + m).foldLeft(Set.empty[Int]) {\n case (set, el) => set + el * el\n }\n val result1 = (0 to n).foldLeft(List.empty[(Int, Int)]) {\n case(list, i) => (0 to m).foldLeft(list) {\n case (l, el) if el + i == 0 => l\n case (l, el) if l.forall{\n case(x, y) => !squares.contains((x - i)* (x - i) + (y - el) * (y - el))\n } => (i, el) :: l\n case (l, el) => l\n }\n }\n val result2 = (0 to m).foldLeft(List.empty[(Int, Int)]) {\n case(list, i) => (0 to n).foldLeft(list) {\n case (l, el) if el + i == 0 => l\n case (l, el) if l.forall{\n case(x, y) => !squares.contains((x - el)* (x - el) + (y - i) * (y - i))\n } => (el, i) :: l\n case (l, el) => l\n }\n }\n val result = if (result1.length > result2.length) result1 else result2\n println(result.length)\n println(result.map(i => s\"${i._1} ${i._2}\").mkString(\"\\n\"))\n}"}, {"source_code": "import scala.Math._;\nimport scala.collection.mutable.LinkedList\n\nobject App {\n\tdef readInts:Array[Int] = (readLine split \" \") map (_.toInt)\n //> readInts: => Array[Int] //> solve: (n: Int, m: Int, prev: Int, a: Int, b: Int)(Int, Int)\n\t\n\tdef solve(deep: Int, n: Int):Long = {\n\t if (deep == n) n\n\t else solve(deep + 1, n) + (deep * (n - deep)) \n\t}\n\t\n\tdef f1_io() : Int = {\n\t val Array(n, m) = readInts\n\t\t//for(i <- 1 to 100; j <- i to 100; if (ceil(sqrt(i*i + j*j)) == floor(sqrt(i*i + j*j)))) println(i + \" \" + j + \" \" + sqrt(i*i + j*j))\n\t \t//val badPoint = for(i <- 1 to 100; j <- i to 100; if (ceil(sqrt(i*i + j*j)) == floor(sqrt(i*i + j*j)))) yield (i, j)\n\t \tif (n < m) {\n\t val s1 = (for(i <- 1 to n; if ((i - 1) <= m)) yield (i, i - 1)).toList\n\t \tval s2 = (for(i <- 0 to n; if ((i + 1) <= m)) yield (i, i + 1)).toList\n\t \tif (s2.length > s1.length) {\n\t \t println(s2.length)\n\t \t s2.foreach {case (x, y) => println(x + \" \" + y)}\n\t \t return 0;\n\t \t} else {\n\t \t for(i <- 1 to m) {\n\t \t var f = true\n\t \t s1.foreach {\n\t \t case (x, y) => {\n\t \t val t = sqrt(x*x + (y-i)*(y-i))\n\t \t if (ceil(t) == floor(t)) {\n\t \t f = false\n\t \t }\n\t \t }\n\t \t }\n\t \t if (f) {\n\t \t println(s1.length + 1)\n\t \t println(0 + \" \" + i)\n\t \t s1.foreach {case (x, y) => println(x + \" \" + y)}\n\t \t return 0\n\t \t }\n\t \t }\n\t \t}\n\t println(s2.length)\n\t \ts2.foreach {case (x, y) => println(x + \" \" + y)}\n\t \t}\n\t \telse {\n\t \t println(m + 1)\n\t \t for(i <- 0 to m) {\n\t \t println(i + \" \" + (n - i))\n\t \t }\n\t \t}\n\t 0\n\t} \n def main(args: Array[String]): Unit = {\n\tf1_io\n }\n\n}"}, {"source_code": "import scala.Math._;\nimport scala.collection.mutable.LinkedList\n\nobject App {\n\tdef readInts:Array[Int] = (readLine split \" \") map (_.toInt)\n //> readInts: => Array[Int] //> solve: (n: Int, m: Int, prev: Int, a: Int, b: Int)(Int, Int)\n\t\n\tdef solve(deep: Int, n: Int):Long = {\n\t if (deep == n) n\n\t else solve(deep + 1, n) + (deep * (n - deep)) \n\t}\n\t\n\tdef f1_io() = {\n\t val Array(n, m) = readInts\n\t\tval a = min(n, m)\n\t\tprintln(a + 1)\n\t\tfor(i <- 0 to a) {\n\t\t println(i + \" \" + (n - i))\n\t\t} \n\t \n\t} \n def main(args: Array[String]): Unit = {\n\tf1_io\n }\n\n}"}], "src_uid": "0e99f4a49b408cc8874a6d5ec4167acb"} {"source_code": "import scala.io.StdIn._\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n val t = readInt()\r\n for (_ <- 1 to t) {\r\n val Array(n, m): Array[Int] = readLine().split(\" \").map(_.toInt)\r\n val A: Array[Int] = readLine().split(\" \").map(_.toInt)\r\n val B: Array[String] = Array.fill(m)(\"B\")\r\n for (i <- 0 until n) {\r\n val a_i: Int = A(i)-1\r\n val a_i_rev: Int = m-(a_i+1)\r\n if (a_i < a_i_rev) {\r\n if (B(a_i) == \"B\") {\r\n B(a_i) = \"A\"\r\n } else {\r\n B(a_i_rev) = \"A\"\r\n }\r\n } \r\n else {\r\n if (B(a_i_rev) == \"B\") {\r\n B(a_i_rev) = \"A\"\r\n } else {\r\n B(a_i) = \"A\"\r\n }\r\n }\r\n }\r\n println(B.mkString(\"\"))\r\n }\r\n }\r\n}", "positive_code": [{"source_code": "\r\n\r\nobject prob2 {\r\n def main(args: Array[String]) = {\r\n new Resolver3(Console.in, Console.out).run()\r\n }\r\n}\r\n\r\nclass Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {\r\n\r\n import java.util.StringTokenizer\r\n import scala.collection.mutable\r\n import scala.collection.mutable._\r\n import scala.math.{abs,pow,min,max}\r\n import scala.collection.mutable.ListBuffer\r\n\r\n def run() {\r\n var tokenizer = new StringTokenizer(input.readLine())\r\n val q = tokenizer.nextToken().toInt\r\n for (sss <- 0 until q) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val n = tokenizer.nextToken().toInt\r\n val m = tokenizer.nextToken().toInt\r\n val A = new Array[String](m)\r\n for (i <- 0 until m){\r\n A(i)=\"B\"\r\n }\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (i <- 1 to n){\r\n val p = tokenizer.nextToken().toInt\r\n if (p > m / 2) {\r\n if (A(m-p) == \"A\") {\r\n A(p-1) = \"A\"\r\n }\r\n else A(m-p) = \"A\"\r\n }\r\n else {\r\n if (A(p-1) == \"A\") {\r\n A(m-p) = \"A\"\r\n }\r\n else A(p-1) = \"A\"\r\n }\r\n }\r\n println(A.mkString)\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "eee23388aa7cda50302fc4da6e50e172"} {"source_code": "\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 27.07.14.\n */\nobject B extends App {\n val home = true\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextDouble\n val m = nextDouble\n if (n == 0.0 || m == 0.0) {\n if (n == 0) {\n out.println(s\"0 ${1}\")\n out.println(s\"0 ${m.toInt}\")\n out.println(s\"0 ${0}\")\n out.println(s\"0 ${(m - 1).toInt}\")\n }\n if (m == 0) {\n out.println(s\"${1} 0\")\n out.println(s\"${n.toInt} 0\")\n out.println(s\"${0} 0\")\n out.println(s\"${(n - 1).toInt} 0\")\n }\n } else {\n\n def length(x: (Double, Double), y: (Double, Double)) = {\n Math.sqrt((x._1 - y._1) * (x._1 - y._1) + (x._2 - y._2) * (x._2 - y._2))\n }\n\n var X = (0.0, 0.0)\n var Y = (0.0, 0.0)\n var p = (0.0, 0.0)\n var q = (0.0, 0.0)\n var best = 0.0\n\n def chooseBest(x: (Double, Double), y: (Double, Double)) = {\n for (i <- 0 to n.toInt) {\n for (j <- 0 to m.toInt) {\n val z = i.toDouble\n val t = j.toDouble\n if (length(x, (z, 0.0)) + length((z, 0.0), (0.0, t)) + length((0.0, t), y) >= best) {\n if (x != (z, 0.0) && x != (0.0, t) && y != (z, 0.0) && y != (0.0, t)) {\n p = (z, 0.0)\n q = (0.0, t)\n X = x\n Y = y\n best = length(x, (z, 0.0)) + length((z, 0.0), (0.0, t)) + length((0.0, t), y)\n }\n }\n if (length(x, (z, m)) + length((z, m), (0.0, t)) + length((0.0, t), y) >= best) {\n if (x != (z, m) && x != (0.0, t) && y != (z, m) && y != (0.0, t)) {\n p = (z, m)\n q = (0.0, t)\n X = x\n Y = y\n best = length(x, (z, m)) + length((z, m), (0.0, t)) + length((0.0, t), y)\n }\n }\n if (length(x, (z, 0.0)) + length((z, 0.0), (n, t)) + length((n, t), y) >= best) {\n if (x != (z, 0.0) && x != (n, t) && y != (z, 0.0) && y != (n, t)) {\n p = (z, 0.0)\n q = (n, t)\n X = x\n Y = y\n best = length(x, (z, 0.0)) + length((z, 0.0), (n, t)) + length((n, t), y)\n }\n }\n if (length(x, (z, m)) + length((z, m), (n, t)) + length((n, t), y) >= best) {\n if (x != (z, m) && x != (n, t) && y != (z, m) && y != (n, t)) {\n p = (z, m)\n q = (n, t)\n X = x\n Y = y\n best = length(x, (z, m)) + length((z, m), (n, t)) + length((n, t), y)\n }\n }\n }\n }\n }\n\n chooseBest((0.0, 0.0), (n, m))\n chooseBest((0.0, 0.0), (n, 0))\n chooseBest((0.0, 0.0), (0, m))\n\n chooseBest((1, 0), (n - 1, m))\n chooseBest((0, 1), (n, m - 1))\n\n out.println(s\"${X._1.toInt} ${X._2.toInt}\")\n out.println(s\"${p._1.toInt} ${p._2.toInt}\")\n out.println(s\"${q._1.toInt} ${q._2.toInt}\")\n out.println(s\"${Y._1.toInt} ${Y._2.toInt}\")\n\n //out.println(best)\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}\n", "positive_code": [{"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n if (n == 0) {\n println(s\"0 1\")\n println(s\"0 $m\")\n println(s\"0 0\")\n println(s\"0 ${m - 1}\")\n } else if (m == 0) {\n println(s\"1 0\")\n println(s\"$n 0\")\n println(s\"0 0\")\n println(s\"${n - 1} 0\")\n } else if (n <= m) {\n var best = -1d\n var bestI = 0\n var bestJ = 0\n for (i <- 1 to n) {\n val d1 = Math.sqrt(m * m + (n - i) * (n - i))\n for (j <- 0 until n) {\n val d2 = Math.sqrt(m * m + (j - i) * (j - i))\n if (d1 + d2 > best) {\n best = d1 + d2\n bestI = i\n bestJ = j\n }\n }\n }\n val other = 2d * Math.sqrt(m * m + (n - 1) * (n - 1))\n if (best > other) {\n println(s\"0 0\")\n println(s\"$n $m\")\n println(s\"$bestI 0\")\n println(s\"$bestJ $m\")\n } else {\n println(s\"1 0\")\n println(s\"$n $m\")\n println(s\"0 0\")\n println(s\"${n - 1} $m\")\n }\n } else {\n var best = -1d\n var bestI = 0\n var bestJ = 0\n for (i <- 1 to m) {\n val d1 = Math.sqrt(n * n + (m - i) * (m - i))\n for (j <- 0 until m) {\n val d2 = Math.sqrt(n * n + (j - i) * (j - i))\n if (d1 + d2 > best) {\n best = d1 + d2\n bestI = i\n bestJ = j\n }\n }\n }\n val other = 2d * Math.sqrt(n * n + (m - 1) * (m - 1))\n if (best > other) {\n println(s\"0 0\")\n println(s\"$n $m\")\n println(s\"0 $bestI\")\n println(s\"$n $bestJ\")\n } else {\n println(s\"0 1\")\n println(s\"$n $m\")\n println(s\"0 0\")\n println(s\"$n ${m - 1}\")\n }\n }\n\n}"}], "negative_code": [{"source_code": "\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 27.07.14.\n */\nobject B extends App {\n val home = true\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextDouble\n val m = nextDouble\n if (n == 0.0 || m == 0.0) {\n if (n == 0) {\n out.println(s\"0 ${1}\")\n out.println(s\"0 ${m.toInt}\")\n out.println(s\"0 ${0}\")\n out.println(s\"0 ${(m - 1).toInt}\")\n }\n if (m == 0) {\n out.println(s\"${1} 0\")\n out.println(s\"${n.toInt} 0\")\n out.println(s\"${0} 0\")\n out.println(s\"${(n - 1).toInt} 0\")\n }\n } else {\n\n def length(x: (Double, Double), y: (Double, Double)) = {\n Math.sqrt((x._1 - y._1) * (x._1 - y._1) + (x._2 - y._2) * (x._2 - y._2))\n }\n\n var X = (0.0, 0.0)\n var Y = (0.0, 0.0)\n var p = (0.0, 0.0)\n var q = (0.0, 0.0)\n var best = 0.0\n\n def chooseBest(x: (Double, Double), y: (Double, Double)) = {\n for (i <- 0 to n.toInt) {\n for (j <- 0 to m.toInt) {\n val z = i.toDouble\n val t = j.toDouble\n if (length(x, (z, 0.0)) + length((z, 0.0), (0.0, t)) + length((0.0, t), y) >= best) {\n if (x != (z, 0.0) && x != (0.0, t) && y != (z, 0.0) && y != (0.0, t)) {\n p = (z, 0.0)\n q = (0.0, t)\n X = x\n Y = y\n best = length(x, (z, 0.0)) + length((z, 0.0), (0.0, t)) + length((0.0, t), y)\n }\n }\n if (length(x, (z, m)) + length((z, m), (0.0, t)) + length((0.0, t), y) >= best) {\n if (x != (z, m) && x != (0.0, t) && y != (z, m) && y != (0.0, t)) {\n p = (z, m)\n q = (0.0, t)\n X = x\n Y = y\n best = length(x, (z, m)) + length((z, m), (0.0, t)) + length((0.0, t), y)\n }\n }\n if (length(x, (z, 0.0)) + length((z, 0.0), (n, t)) + length((n, t), y) >= best) {\n if (x != (z, 0.0) && x != (n, t) && y != (z, 0.0) && y != (n, t)) {\n p = (z, 0.0)\n q = (n, t)\n X = x\n Y = y\n best = length(x, (z, 0.0)) + length((z, 0.0), (n, t)) + length((n, t), y)\n }\n }\n if (length(x, (z, m)) + length((z, m), (n, t)) + length((n, t), y) >= best) {\n if (x != (z, m) && x != (n, t) && y != (z, m) && y != (n, t)) {\n p = (z, m)\n q = (n, t)\n X = x\n Y = y\n best = length(x, (z, m)) + length((z, m), (n, t)) + length((n, t), y)\n }\n }\n }\n }\n }\n\n chooseBest((0.0, 0.0), (n, m))\n chooseBest((0.0, 0.0), (n, 0))\n chooseBest((0.0, 0.0), (0, m))\n\n out.println(s\"${X._1.toInt} ${X._2.toInt}\")\n out.println(s\"${p._1.toInt} ${p._2.toInt}\")\n out.println(s\"${q._1.toInt} ${q._2.toInt}\")\n out.println(s\"${Y._1.toInt} ${Y._2.toInt}\")\n\n //out.println(best)\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}\n"}, {"source_code": "\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 27.07.14.\n */\nobject B extends App {\n val home = true\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextDouble\n val m = nextDouble\n if (n == 0.0 || m == 0.0) {\n if (n == 0) {\n out.println(s\"0 ${1}\")\n out.println(s\"0 ${m.toInt}\")\n out.println(s\"0 ${0}\")\n out.println(s\"0 ${(m - 1).toInt}\")\n }\n if (m == 0) {\n out.println(s\"${1} 0\")\n out.println(s\"${m.toInt} 0\")\n out.println(s\"${0} 0\")\n out.println(s\"${(m - 1).toInt} 0\")\n }\n } else {\n\n def length(x: (Double, Double), y: (Double, Double)) = {\n Math.sqrt((x._1 - y._1) * (x._1 - y._1) + (x._2 - y._2) * (x._2 - y._2))\n }\n\n var X = (0.0, 0.0)\n var Y = (0.0, 0.0)\n var p = (0.0, 0.0)\n var q = (0.0, 0.0)\n var best = 0.0\n\n def chooseBest(x: (Double, Double), y: (Double, Double)) = {\n for (i <- 0 to n.toInt) {\n for (j <- 0 to m.toInt) {\n val z = i.toDouble\n val t = j.toDouble\n if (length(x, (z, 0.0)) + length((z, 0.0), (0.0, t)) + length((0.0, t), y) >= best) {\n if (x != (z, 0.0) && x != (0.0, t) && y != (z, 0.0) && y != (0.0, t)) {\n p = (z, 0.0)\n q = (0.0, t)\n X = x\n Y = y\n best = length(x, (z, 0.0)) + length((z, 0.0), (0.0, t)) + length((0.0, t), y)\n }\n }\n if (length(x, (z, m)) + length((z, m), (0.0, t)) + length((0.0, t), y) >= best) {\n if (x != (z, m) && x != (0.0, t) && y != (z, m) && y != (0.0, t)) {\n p = (z, m)\n q = (0.0, t)\n X = x\n Y = y\n best = length(x, (z, m)) + length((z, m), (0.0, t)) + length((0.0, t), y)\n }\n }\n if (length(x, (z, 0.0)) + length((z, 0.0), (n, t)) + length((n, t), y) >= best) {\n if (x != (z, 0.0) && x != (n, t) && y != (z, 0.0) && y != (n, t)) {\n p = (z, 0.0)\n q = (n, t)\n X = x\n Y = y\n best = length(x, (z, 0.0)) + length((z, 0.0), (n, t)) + length((n, t), y)\n }\n }\n if (length(x, (z, m)) + length((z, m), (n, t)) + length((n, t), y) >= best) {\n if (x != (z, m) && x != (n, t) && y != (z, m) && y != (n, t)) {\n p = (z, m)\n q = (n, t)\n X = x\n Y = y\n best = length(x, (z, m)) + length((z, m), (n, t)) + length((n, t), y)\n }\n }\n }\n }\n }\n\n chooseBest((0.0, 0.0), (n, m))\n chooseBest((0.0, 0.0), (n, 0))\n chooseBest((0.0, 0.0), (0, m))\n\n out.println(s\"${X._1.toInt} ${X._2.toInt}\")\n out.println(s\"${p._1.toInt} ${p._2.toInt}\")\n out.println(s\"${q._1.toInt} ${q._2.toInt}\")\n out.println(s\"${Y._1.toInt} ${Y._2.toInt}\")\n\n //out.println(best)\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}\n"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n if (n == 0) {\n println(s\"0 1\")\n println(s\"0 $m\")\n println(s\"0 0\")\n println(s\"0 ${m - 1}\")\n } else if (m == 0) {\n println(s\"1 0\")\n println(s\"$n 0\")\n println(s\"0 0\")\n println(s\"${n - 1} 0\")\n } else if (n <= m) {\n var best = -1d\n var bestI = 0\n var bestJ = 0\n for (i <- 1 to n) {\n val d1 = Math.sqrt(m * m + (n - i) * (n - i))\n for (j <- 0 until n) {\n val d2 = Math.sqrt(m * m + (j - i) * (j - i))\n if (d1 + d2 > best) {\n best = d1 + d2\n bestI = i\n bestJ = j\n }\n }\n }\n val other = 2d * Math.sqrt(m * m + (n - 1) * (n - 1))\n if (best > other) {\n println(s\"0 0\")\n println(s\"$n $m\")\n println(s\"$bestI 0\")\n println(s\"$bestJ $m\")\n } else {\n println(s\"1 0\")\n println(s\"$n $m\")\n println(s\"0 0\")\n println(s\"${n - 1} $m\")\n }\n } else {\n var best = -1d\n var bestI = 0\n var bestJ = 0\n for (i <- 1 to m) {\n val d1 = Math.sqrt(n * n + (m - i) * (m - i))\n for (j <- 0 until m) {\n val d2 = Math.sqrt(n * n + (j - i) * (j - i))\n if (d1 + d2 > best) {\n best = d1 + d2\n bestI = i\n bestJ = j\n }\n }\n }\n val other = 2d * Math.sqrt(m * m + (n - 1) * (n - 1))\n if (best > other) {\n println(s\"0 0\")\n println(s\"$n $m\")\n println(s\"0 $bestI\")\n println(s\"$n $bestJ\")\n } else {\n println(s\"0 1\")\n println(s\"$n $m\")\n println(s\"0 0\")\n println(s\"$n ${m - 1}\")\n }\n }\n\n}"}], "src_uid": "78d54d76cb113cf74ea89fb77471859b"} {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(a, b) = readInts(2)\n\n for (x1 <- 1 until a; y1 <- 1 until a) if (x1 * x1 + y1 * y1 == a * a) {\n val x2 = -y1 * b / a\n val y2 = x1 * b / a\n if (x2 * x2 + y2 * y2 == b * b && y2 != y1) {\n println(\"YES\")\n println(\"0 0\")\n println(s\"$x1 $y1\")\n println(s\"$x2 $y2\")\n exit\n }\n }\n\n println(\"NO\")\n}", "positive_code": [{"source_code": "import java.util.StringTokenizer;\nobject Tri {\n var st:StringTokenizer=new StringTokenizer(\"\");\n def newst={st=new StringTokenizer(readLine);}\n def newint:Int={st.nextToken.toInt;}\n def gcd(a:Int,b:Int):Int = {\n if (ay) && (g%(x*x + y*y) == 0)) {\n\tvar m:Int=1;\n\tif (a*(x*x-y*y)==b*2*x*y) {m=(-1);}\n\t/* if negativing does not solve the problem, then\n\t * we will have a=b. But if a=b, the current angle\n\t * should be 45, but the current cos is rational.\n\t * cos 45 isn't rational. Contradiction. So negativing\n\t * solves the problem, if at all possible.\n\t */\n\tprintln(\"YES\");\n\tprintln(\"0 0\");\n\tprintln(a*(x*x - y*y)/z + \" \" + a*2*x*y/z);\n\tprintln(m*b*2*x*y/z + \" \" + m*b*(y*y-x*x)/z);\n\tSystem.exit(0);\n }\n }\n println(\"NO\");\n }\n}\n\t\n \n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val A, B = ni()\n def pythagorean(x: Int) = {\n val res = ArrayBuffer[(Int, Int)]()\n REP(x, 1) { a =>\n val bSqr = (x + a) * (x - a)\n val b = math.sqrt(bSqr).toInt\n if (b * b == bSqr && b > 0) res += a -> b\n }\n res\n }\n\n val as = pythagorean(A) // pos-X -> pos-Y の部分\n val bs = pythagorean(B) // neg-Y -> pos-X の部分\n\n (for {\n (ax, ay) <- as\n (bx, by) <- bs\n if ax * bx + ay * -by == 0 && ax != bx\n } yield (ax -> ay, bx -> by)).headOption match {\n case Some(((ax, ay), (bx, by))) =>\n out.println(\"YES\")\n out.println(\"0 0\")\n out.println(s\"$ax $ay\")\n out.println(s\"$bx -$by\")\n\n case None =>\n out.println(\"NO\")\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n\n def debug(as: Array[Int], delimiter: String = \" \"): Unit = {\n debug(as.mkString(delimiter))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n}"}], "negative_code": [{"source_code": "import java.util.StringTokenizer;\nobject Tri {\n var st:StringTokenizer=new StringTokenizer(\"\");\n def newst={st=new StringTokenizer(readLine);}\n def newint:Int={st.nextToken.toInt;}\n def gcd(a:Int,b:Int):Int = {\n if (ay) && (g%(x*x + y*y) == 0)) {\n\tvar z=x*x + y*y;\n\tprintln(\"YES\");\n\tprintln(\"0 0\");\n\tprintln(a*(x*x - y*y)/z + \" \" + a*2*x*y/z);\n\tprintln(b*2*x*y/z + \" \" + b*(y*y-x*x)/z);\n\tSystem.exit(0);\n }\n }\n println(\"NO\");\n }\n}\n\t\n \n"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(a, b) = readInts(2)\n\n for (x1 <- 1 until a; y1 <- 1 until a) if (x1 * x1 + y1 * y1 == a * a) {\n val x2 = -y1 * b / a\n val y2 = x1 * b / a\n if (x2 * x2 + y2 * y2 == b * b) {\n println(\"YES\")\n println(\"0 0\")\n println(s\"$x1 $y1\")\n println(s\"$x2 $y2\")\n exit\n }\n }\n\n println(\"NO\")\n}"}], "src_uid": "a949ccae523731f601108d4fa919c112"} {"source_code": "object A445 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val in = Array.fill(n)(read.toCharArray)\n def isValid(i: Int, j: Int): Boolean = {\n i >= 0 && i < n && j >=0 && j < m\n }\n val delta = Array((1,0), (0,1), (-1,0), (0,-1))\n for(i <- 0 until n; j <- 0 until m if in(i)(j) == '.') {\n if((i+j)%2 == 0)\n in(i)(j) = 'B'\n else\n in(i)(j) = 'W'\n }\n println(in.map(_.mkString(\"\")).mkString(\"\\n\"))\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.HashMap\nimport scala.collection.mutable.HashSet\n\nobject Main extends App {\n\n val Array(n,m) = readLine.split(\" \").map(_.toInt)\n val board = HashSet((0 to (n-1)).flatMap({ i =>\n val good = readLine.map({ case '.' => true case '-' => false }).zipWithIndex.filter(_._1)\n good.map(_._2).map((i, _))\n }):_*)\n\n val draw = HashMap[(Int, Int), Boolean]()\n\n def isValid(pos: (Int,Int)): Boolean = pos match { case (i,j) => \n (i >= 0) && (i < n) && (j >= 0) && (j < m) && board.contains((i,j))\n }\n\n def setColor(value: Boolean)(pos: (Int, Int)): Unit = {\n board -= pos\n draw += (pos -> value)\n val (i,j) = pos\n val ns = List((i-1, j), (i+1, j), (i, j-1), (i, j+1)).filter(isValid(_))\n ns foreach setColor(!value)\n }\n\n while(board.size > 0) {\n setColor(true)(board.head)\n } \n\n (0 to (n-1)) foreach { i =>\n println((0 to (m-1)).map(j => {\n draw.get((i,j)).map({ case true => \"W\" case false => \"B\" }).getOrElse(\"-\")\n }).mkString)\n }\n\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n Range(0, n).foreach { i =>\n println(in.next().zipWithIndex.map{\n case('.', index) if (i + index) % 2 == 0 => 'B'\n case('.', index) => 'W'\n case(ch, _) => ch\n }.mkString)\n }\n\n}"}, {"source_code": "object Main extends App {\n val sc = new java.util.Scanner(System.in)\n\n val n, m = sc.nextInt()\n val board = Array.fill(n)(sc.next)\n\n println(new A(n, m, board).answer.mkString(\"\\n\"))\n}\n\nclass A(n: Int, m: Int, board: Array[String]) {\n def answer: Array[String] = {\n val cahrs = for{\n (line, y) <- board.zipWithIndex\n (char, x) <- line.zipWithIndex\n } yield char match {\n case '.' => if ((x+y) % 2 == 0) 'B' else 'W'\n case '-' => '-'\n }\n\n cahrs.grouped(m).map(_.mkString(\"\")).toArray\n }\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _445A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val m = next.toInt\n val a = (1 to n).map(i => next.toArray).toArray\n for (i <- 0 until n)\n for (j <- 0 until m)\n if (a(i)(j) == '.') a(i)(j) = if ((i + j) % 2 == 0) 'W' else 'B'\n\n a.foreach(i => println(i.mkString))\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n Range(0, m).foreach { i =>\n println(in.next().zipWithIndex.map{\n case('.', index) if (i + index) % 2 == 0 => 'B'\n case('.', index) => 'W'\n case(ch, _) => ch\n }.mkString)\n }\n\n}"}, {"source_code": "object A445 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val in = Array.fill(n)(read.toCharArray)\n def isValid(i: Int, j: Int): Boolean = {\n i >= 0 && i < n && j >=0 && j < m\n }\n val delta = Array((1,0), (0,1), (-1,0), (0,-1))\n for(i <- 0 until n; j <- 0 until m if in(i)(j) == '.') {\n var b = 0\n var w = 0\n delta.foreach {\n case (dx, dy) if isValid(i+dx, j+dy)=>\n if(in(i+dx)(j+dy) == 'B') {\n b += 1\n }\n if(in(i+dx)(j+dy) == 'W') {\n w += 1\n }\n case _ =>\n }\n if(in(i)(j) == '.') {\n if(w > 0)\n in(i)(j) = 'B'\n else\n in(i)(j) = 'W'\n }\n }\n println(in.map(_.mkString(\"\")).mkString(\"\\n\"))\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable.HashMap\nimport scala.collection.mutable.HashSet\n\nobject Main extends App {\n\n val Array(n,m) = readLine.split(\" \").map(_.toInt)\n val board = HashSet((0 to (n-1)).flatMap({ i =>\n val good = readLine.map({ case '.' => true case '-' => false }).zipWithIndex.filter(_._1)\n good.map(_._2).map((i, _))\n }):_*)\n\n val draw = HashMap[(Int, Int), Boolean]()\n\n def isValid(i: Int, j: Int): Boolean = {\n (i >= 0) && (i < n) && (j >= 0) && (j < n) && board.contains((i,j))\n }\n\n def setColor(pos: (Int, Int), value: Boolean): Unit = {\n board -= pos\n draw += (pos -> value)\n val (i,j) = pos\n for {\n di <- (-1 to 1)\n dj <- (-1 to 1)\n if Math.abs(di + dj) == 1\n if isValid(i+di, j+dj)\n } yield setColor((i+di, j+dj), !value)\n }\n\n while(board.size > 0) {\n setColor(board.head, true)\n } \n\n (0 to (n-1)) foreach { i =>\n println((0 to (m-1)).map(j => draw.get((i,j)).map({ case true => \"W\" case false => \"B\" }).getOrElse(\"-\")).mkString)\n }\n\n}"}], "src_uid": "dc31adef80f06897ea2f5ef76854bcf1"} {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P155B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n // two non negative integer top/bottom ... a_i/b_i\n // A_i point and additional opportunity to play b_i additional cards\n\n def solve(): Int = {\n val N = sc.nextInt\n val C = List.fill(N, 2)(sc.nextInt)\n\n val C0 = C.filter(_(1) == 0).map(_(0)).sorted(Ordering.Int.reverse)\n val C1 = C.filter(_(1) > 0).map(_(0))\n \n // # of additional cards for C0\n val n = C.transpose.toList(1).map { (i: Int) => (i - 1) max 0 }.sum + 1\n\n C1.sum + C0.take(n).sum\n }\n\n out.println(solve)\n out.close\n}\n", "positive_code": [{"source_code": "object B {\n def main(args: Array[String]): Unit = {\n val cards = scala.io.Source.stdin.getLines().toList.tail.map(s => {val a = s.split(\" \"); (a(0).toInt, a(1).toInt)})\n val good = cards.filter(_._2>0)\n val toplay = good.map(_._2-1).sum+1\n \n System.out.println(good.map(_._1).sum+cards.filter(_._2==0).map(_._1).sort(_>_).take(toplay).sum)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = (1 to n).map(_ => readLine().split(\" \").map(_.toInt))\n \n val t = a.filter(_.apply(1) != 0).foldLeft((0, 1)) { (acc, e) =>\n (acc._1 + e(0), acc._2 + e(1) - 1)\n }\n val sum = a.filter(_.apply(1) == 0).map(_.apply(0)).sorted.reverse.take(t._2).sum\n println(t._1 + sum)\n }\n}"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by IntelliJ IDEA.\n * User: User\n * Date: 29.02.12\n * Time: 2:06\n * To change this template use File | Settings | File Templates.\n */\n\nobject B {\n val input = new Scanner(System.in)\n\n def main(args: Array[String]) {\n val count = input.nextInt\n val cards = (1 to count).map(_ => Card(input.nextInt, input.nextInt)).sorted\n def calc():Int = {\n var points = 0\n var steps = 1\n for (Card(value, step) <- cards) {\n steps -= 1\n steps += step\n points += value\n if(steps == 0 ) return points\n }\n return points\n }\n val x = calc()\n println(x)\n }\n\n case class Card(value: Int, step: Int) extends Comparable[Card] {\n def compareTo(o: Card) = this.step.compareTo(o.step) match {\n case 0 => -this.value.compareTo(o.value)\n case some => -some\n }\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val r = (1 to n).map(_ => in.next().split(' ').map(_.toInt)).toList\n val (counter, sum) = r.filter(_.last > 0).foldLeft((1, 0)) {\n case ((c, s), e) =>\n (c + e.last - 1, s + e.head)\n }\n println(sum + r.filter(_.last == 0).map(_.head).sorted.takeRight(counter).sum)\n}\n"}, {"source_code": "object Main\n{\n\tdef main(args:Array[String])\n\t{\n\t\tval n = readInt\n\t\tval lol = (0 until n).map(i => readLine.split(\" \").map(j => j.toInt)).toList\n\t\t\n\t\t\n\t\tval notzeroarray = lol.filter(i => i(1) > 0).map(i => i(0))\n\t\tval b = lol.map(i => i(1)).sum - notzeroarray.length + 1\n\t\tval notzeropts = notzeroarray.sum\n\t\t\n\t\tval zeroarray = lol.filter(i => i(1) == 0).map(i => i(0)).sort((s, t) => s > t)\n\t\t\n\t\tvar carts = 0;\n\t\tif (b > zeroarray.length)\n\t\t\tcarts = zeroarray.length\n\t\telse carts = b\n\t\t\n\t\tval zeropts = (0 until carts).map(i => zeroarray(i)).sum\n\t\t\n\t\tprintln(notzeropts + zeropts)\n\t}\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P155B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n // two non negative integer top/bottom ... a_i/b_i\n // A_i point and additional opportunity to play b_i additional cards\n\n def solve(): Int = {\n val N = sc.nextInt\n val C = List.fill(N, 2)(sc.nextInt)\n\n val n = C.transpose.toList(1).sum + 1 // the number of playable cards\n C.transpose.toList(0).sorted(Ordering.Int.reverse).take(n).sum\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "object B {\n def main(args: Array[String]): Unit = {\n val cards = scala.io.Source.stdin.getLines().toList.tail.map(s => {val a = s.split(\" \"); (a(0).toInt, a(1).toInt)})\n val good = cards.filter(_._2>0)\n val toplay = good.map(_._2).sum+1\n \n System.out.println(good.map(_._1).sum+cards.filter(_._2==0).map(_._1).sort(_>_).take(toplay).sum)\n }\n}"}], "src_uid": "4abdd16670a796be3a0bff63b9798fed"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val from, to = Array.ofDim[Int](N - 1)\n REP(N - 1) { i =>\n from(i) = ni() - 1\n to(i) = i + 1\n }\n val S = na(N)\n val g = packUGraph(N, from, to)\n val (depth, parent, queue) = traceBfs(g)\n\n val INF = 1e6.toInt\n\n REP_r(N) { i =>\n val v = queue(i)\n if (depth(v) % 2 == 1) {\n // Sが決まっていない\n assert(S(v) == -1)\n\n // Sが決まっていない場合は、子供の中で一番小さいものに合わせる\n var ms = INF\n REP(g(v).length) { j =>\n val u = g(v)(j)\n if (parent(v) != u && S(u) != -1) {\n ms = min(ms, S(u))\n }\n }\n S(v) = if (ms == INF) -1 else ms\n }\n }\n\n val A = Array.ofDim[Int](N)\n REP(N) { i =>\n val v = queue(i)\n\n //登って行くときに未決定だったSをparentのものにする\n if (depth(v) % 2 == 1 && S(v) == -1) {\n S(v) = S(parent(v))\n }\n if (v == 0) A(v) = S(v)\n else A(v) = S(v) - S(parent(v))\n }\n\n if (A.exists(_ < 0)) {\n out.println(-1)\n } else {\n val ans = sumL(A)\n out.println(ans)\n }\n }\n\n\n /**\n * @param n ノード数\n */\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n REP(m)(i => p(from(i)) += 1)\n REP(m)(i => p(to(i)) += 1)\n REP(n)(i => t(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n /**\n * @return (depth, parent, queue)\n */\n def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {\n val n = g.length\n val INF = 1e9.toInt + 10\n val q, p = Array.ofDim[Int](n)\n q(0) = rt\n p(rt) = -1\n val d = Array.fill[Int](n)(INF)\n d(rt) = 0\n var cur = 0\n var last = 1\n while (cur < last) {\n val v = q(cur)\n REP(g(v).length) { i =>\n val u = g(v)(i)\n if (d(u) == INF) {\n d(u) = d(v) + 1\n p(u) = v\n q(last) = u\n last += 1\n }\n }\n cur += 1\n }\n (d, p, q)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_530_D { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n runTest(Test.t6)\n debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading \n val n = readLine.int\n class Vert(val ind: Int) {\n var vv = -1\n var sum = -1\n var children = List[Vert]()\n var parent = -1\n override def toString() = s\"$ind, $vv, $sum, p=$parent\"\n }\n val verts = new Array[Vert](n+1)\n val pLine = readLine\n verts(1) = new Vert(1)\n for (i <- 2 to n) {\n verts(i) = new Vert(i)\n verts(i).parent = pLine.int\n }\n val sLine = readLine\n for (i <- 1 to n) {\n if (verts(i).parent > 0)\n verts(verts(i).parent).children ::= verts(i)\n verts(i).sum = sLine.int\n }\n \n var possible = true\n def mark(ver: Vert, sum: Int): Unit = {\n if (ver.sum == -1) {\n// ver.vv = 0\n val vv = if (ver.children != Nil) ver.children.map(_.sum).min - sum else 0\n if (vv < 0 ) possible = false\n ver.vv = vv\n } else {\n if (ver.sum < sum) possible = false\n ver.vv = ver.sum - sum\n }\n ver.children.foreach(ch => mark(ch, sum + ver.vv))\n }\n mark(verts(1), 0)\n \n def sum(ver: Vert): Long = {\n ver.vv + ver.children.map(sum(_)).sum\n }\n \n val res = if (possible) sum(verts(1)) else -1\n \n verts.foreach(x => debug(x+\"\"))\n \n \n debug(\"n = \" + n)\n \n //---------------------------- parameters reading :end \n \n outLn(res)\n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Long) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n5\n1 1 1 1\n1 -1 -1 -1 -1\n\"\"\"\n\nval sa2 = \"\"\"\n5\n1 2 3 1\n1 -1 2 -1 -1\n\"\"\"\n\nval sa3 = \"\"\"\n3\n1 2\n2 -1 1\n\"\"\"\n\nval t6 = \"\"\"\n5\n1 2 2 3\n1 -1 2 3 -1\n\"\"\" //3\n}\n \n\n}\n\n"}], "negative_code": [{"source_code": "\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_530_D { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n runTest(Test.t6)\n debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading \n val n = readLine.int\n class Vert(val ind: Int) {\n var vv = -1\n var sum = -1\n var children = List[Vert]()\n var parent = -1\n override def toString() = s\"$ind, $vv, $sum, p=$parent\"\n }\n val verts = new Array[Vert](n+1)\n val pLine = readLine\n verts(1) = new Vert(1)\n for (i <- 2 to n) {\n verts(i) = new Vert(i)\n verts(i).parent = pLine.int\n }\n val sLine = readLine\n for (i <- 1 to n) {\n if (verts(i).parent > 0)\n verts(verts(i).parent).children ::= verts(i)\n verts(i).sum = sLine.int\n }\n \n var possible = true\n def mark(ver: Vert, sum: Int): Unit = {\n if (ver.sum == -1) {\n// ver.vv = 0\n val vv = if (ver.children != Nil) ver.children.map(_.sum).min - sum else 0\n if (vv < 0 ) possible = false\n ver.vv = vv\n } else {\n if (ver.sum < sum) possible = false\n ver.vv = ver.sum - sum\n }\n ver.children.foreach(ch => mark(ch, sum + ver.vv))\n }\n mark(verts(1), 0)\n \n def sum(ver: Vert): Int = {\n ver.vv + ver.children.map(sum(_)).sum\n }\n \n val res = if (possible) sum(verts(1)) else -1\n \n verts.foreach(x => debug(x+\"\"))\n \n \n debug(\"n = \" + n)\n \n //---------------------------- parameters reading :end \n \n outLn(res)\n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n5\n1 1 1 1\n1 -1 -1 -1 -1\n\"\"\"\n\nval sa2 = \"\"\"\n5\n1 2 3 1\n1 -1 2 -1 -1\n\"\"\"\n\nval sa3 = \"\"\"\n3\n1 2\n2 -1 1\n\"\"\"\n\nval t6 = \"\"\"\n5\n1 2 2 3\n1 -1 2 3 -1\n\"\"\" //3\n}\n \n\n}\n\n"}, {"source_code": "\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_530_D { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.sa1)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading \n val n = readLine.int\n class Vert(val ind: Int) {\n var vv = -1\n var sum = -1\n var children = List[Vert]()\n var parent = -1\n override def toString() = s\"$ind, $vv, $sum, p=$parent\"\n }\n val verts = new Array[Vert](n+1)\n val pLine = readLine\n verts(1) = new Vert(1)\n for (i <- 2 to n) {\n verts(i) = new Vert(i)\n verts(i).parent = pLine.int\n }\n val sLine = readLine\n for (i <- 1 to n) {\n if (verts(i).parent > 0)\n verts(verts(i).parent).children ::= verts(i)\n verts(i).sum = sLine.int\n }\n \n var possible = true\n def mark(ver: Vert, sum: Int): Unit = {\n if (ver.sum == -1) {\n ver.vv = 0\n } else {\n if (ver.sum < sum) possible = false\n ver.vv = ver.sum - sum\n }\n ver.children.foreach(ch => mark(ch, sum + ver.vv))\n }\n mark(verts(1), 0)\n \n def sum(ver: Vert): Int = {\n ver.vv + ver.children.map(sum(_)).sum\n }\n \n val res = if (possible) sum(verts(1)) else -1\n \n verts.foreach(x => debug(x+\"\"))\n \n \n debug(\"n = \" + n)\n \n //---------------------------- parameters reading :end \n \n outLn(res)\n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n5\n1 1 1 1\n1 -1 -1 -1 -1\n\"\"\"\n\nval sa2 = \"\"\"\n5\n1 2 3 1\n1 -1 2 -1 -1\n\"\"\"\n\nval sa3 = \"\"\"\n3\n1 2\n2 -1 1\n\"\"\"\n}\n\n}\n\n"}, {"source_code": "import java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_530_D { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n //runTest(Test.sa1)\n //debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading \n val n = readLine.int\n class Vert(val ind: Int) {\n var vv = -1\n var sum = -1\n var children = List[Vert]()\n var parent = -1\n override def toString() = s\"$ind, $vv, $sum, p=$parent\"\n }\n val verts = new Array[Vert](n+1)\n val pLine = readLine\n verts(1) = new Vert(1)\n for (i <- 2 to n) {\n verts(i) = new Vert(i)\n verts(i).parent = pLine.int\n }\n val sLine = readLine\n for (i <- 1 to n) {\n if (verts(i).parent > 0)\n verts(verts(i).parent).children ::= verts(i)\n verts(i).sum = sLine.int\n }\n \n var possible = true\n def mark(ver: Vert, sum: Int): Unit = {\n if (ver.sum == -1) {\n ver.vv = 0\n } else {\n if (ver.sum < sum) possible = false\n ver.vv = ver.sum - sum\n }\n ver.children.foreach(ch => mark(ch, sum + ver.vv))\n }\n mark(verts(1), 0)\n \n def sum(ver: Vert): Int = {\n ver.vv + ver.children.map(sum(_)).sum\n }\n \n val res = if (possible) sum(verts(1)) else -1\n \n verts.foreach(println)\n \n \n debug(\"n = \" + n)\n \n //---------------------------- parameters reading :end \n \n outLn(res)\n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n5\n1 1 1 1\n1 -1 -1 -1 -1\n\"\"\"\n\nval sa2 = \"\"\"\n5\n1 2 3 1\n1 -1 2 -1 -1\n\"\"\"\n\nval sa3 = \"\"\"\n3\n1 2\n2 -1 1\n\"\"\"\n}\n\n}\n\n"}], "src_uid": "7d5ecacc037c9b0e6de2e86b20638674"} {"source_code": "import scala.collection.mutable\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val as0 = readInts(n)\n val as = as0.zipWithIndex.sortBy(_._1)\n val bs = Array.fill(n)(0)\n\n var h = 1\n var i = 0\n var bad = false\n while (i < n) {\n val add = n - as(i)._1\n var added = 0\n while (added < add && i < n) {\n bs(as(i)._2) = h\n if (n - as(i)._1 != add) bad = true\n added += 1\n i += 1\n }\n h += 1\n }\n\n if (bs.contains(0)) bad = true\n\n //val counts = Array.fill(bs.max + 1) { 0 }\n //for (b <- bs) counts(b) += 1\n val counts = bs.groupBy(identity).map {\n case (k, v) => k -> v.length\n }\n\n for (i <- bs.indices) {\n if (as0(i) != n - counts(bs(i))) bad = true\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (bad) println(\"Impossible\")\n else {\n println(\"Possible\")\n println(bs.mkString(\" \"))\n }\n\n Console.flush\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val C = Array.ofDim[Int](N + 1)\n REP(N) { i =>\n C(A(i)) += 1\n }\n\n def validate: Option[Array[mutable.Queue[Int]]] = {\n var id = 1\n val res = Array.fill[mutable.Queue[Int]](N)(mutable.Queue())\n\n REP(N + 1) { i =>\n if (C(i) > 0) {\n val cnt = N - i\n if (C(i) < cnt || cnt == 0) return None\n else {\n REP(C(i) / cnt) { d =>\n REP(cnt) { _ => res(i) += id }\n id += 1\n }\n }\n }\n }\n Some(res)\n }\n\n def mkAns(groups: Array[mutable.Queue[Int]]): Option[Array[Int]] = {\n val ans = Array.ofDim[Int](N)\n REP(N) { i =>\n if (groups(A(i)).isEmpty) return None\n else ans(i) = groups(A(i)).dequeue()\n }\n Some(ans)\n }\n\n validate match {\n case None => out.println(\"Impossible\")\n case Some(groups) =>\n mkAns(groups) match {\n case None =>\n out.println(\"Impossible\")\n\n case Some(ans) =>\n out.println(\"Possible\")\n out.println(ans.mkString(\" \"))\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import scala.collection.mutable\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val as0 = readInts(n)\n val as = as0.zipWithIndex.sortBy(_._1)\n val bs = Array.fill(n)(0)\n\n var h = 1\n var i = 0\n var bad = false\n while (i < n) {\n val add = n - as(i)._1\n var added = 0\n while (added < add && i < n) {\n bs(as(i)._2) = h\n if (n - as(i)._1 != add) bad = true\n added += 1\n i += 1\n }\n h += 1\n }\n\n if (bs.contains(0)) bad = true\n\n //val counts = Array.fill(bs.max + 1) { 0 }\n //for (b <- bs) counts(b) += 1\n val counts = new mutable.ArrayOps.ofInt(bs).groupBy(identity).map {\n case (k, v) => k -> v.length\n }\n\n for (i <- bs.indices) {\n if (as0(i) != n - counts(bs(i))) bad = true\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (bad) println(\"Impossible\")\n else {\n println(\"Possible\")\n println(bs.mkString(\" \"))\n }\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as0 = readInts(n)\n val as = as0.zipWithIndex.sortBy(_._1)\n val bs = Array.fill(n)(0)\n\n var h = 1\n var i = 0\n var bad = false\n while (i < n) {\n val add = n - as(i)._1\n var added = 0\n while (added < add && i < n) {\n bs(as(i)._2) = h\n if (n - as(i)._1 != add) bad = true\n added += 1\n i += 1\n }\n h += 1\n }\n\n if (bs.contains(0)) bad = true\n\n val counts = bs.groupBy(identity).map {\n case (k, v) => k -> v.size\n }\n\n for (i <- bs.indices) {\n if (as0(i) != n - counts(bs(i))) bad = true\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (bad) println(\"Impossible\")\n else {\n println(\"Possible\")\n println(bs.mkString(\" \"))\n }\n\n Console.flush\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val as0 = readInts(n)\n val as = as0.zipWithIndex.sortBy(_._1)\n val bs = Array.fill(n)(0)\n\n var h = 1\n var i = 0\n var bad = false\n while (i < n) {\n val add = n - as(i)._1\n var added = 0\n while (added < add && i < n) {\n bs(as(i)._2) = h\n if (n - as(i)._1 != add) bad = true\n added += 1\n i += 1\n }\n h += 1\n }\n\n if (bs.contains(0)) bad = true\n\n val counts = Array.fill(bs.max + 1) { 0 }\n for (b <- bs) counts(b) += 1\n\n for (i <- bs.indices) {\n if (as0(i) != n - counts(bs(i))) bad = true\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (bad) println(\"Impossible\")\n else {\n println(\"Possible\")\n println(bs.mkString(\" \"))\n }\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "f49667ef00cd0da6a6fad67a19d92f1e"} {"source_code": "object B extends App {\n\n def readString = Console.readLine \n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val Array(n, m) = readInts(2)\n val as = readInts(n)\n var delta = 0\n\n var t = 0\n while (t < m) {\n t += 1\n val st = tokenizeLine\n st.nextToken.toInt match {\n case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta\n case 2 => delta += st.nextToken.toInt\n case 3 => println(as(st.nextToken.toInt - 1) + delta)\n }\n }\n \n Console.flush \n}\n", "positive_code": [{"source_code": "object B extends App {\n\n def readString = Console.readLine \n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n Console.setOut(new java.io.PrintStream(Console.out, false))\n\n val Array(n, m) = readInts(2)\n val as = readInts(n)\n var delta = 0\n\n var t = 0\n while (t < m) {\n t += 1\n val st = tokenizeLine\n st.nextToken.toInt match {\n case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta\n case 2 => delta += st.nextToken.toInt\n case 3 => println(as(st.nextToken.toInt - 1) + delta)\n }\n }\n \n Console.flush \n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val a: Array[Long] = in.next().split(' ').map(_.toLong)\n var y = 0l\n val result = (1 to m).foldLeft(List.empty[Long]) {\n case (list, _) =>\n val data = in.next().split(' ').map(_.toInt).toList\n data match {\n case (1 :: v :: x :: Nil) =>\n a(v - 1) = x - y\n list\n case (2 :: y1 :: Nil) =>\n y += y1\n list\n case (3 :: v :: Nil) =>\n (a(v - 1) + y) :: list\n }\n }\n println(result.reverse.mkString(\"\\n\"))\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.nio.CharBuffer\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.PriorityQueue\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject Stub extends App {\n // val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n object Input {\n import java.lang.Character._\n\n lazy val in = new BufferedReader(new InputStreamReader(java.lang.System.in))\n var buf: Array[Char] = Array()\n var pos: Int = 0\n\n def next(): String = {\n while (pos == buf.length) {\n buf = in.readLine.toArray\n pos = 0\n }\n while (isWhitespace(buf(pos))) {\n pos += 1\n }\n while (pos == buf.length) {\n buf = in.readLine.toArray\n pos = 0\n }\n val s = pos\n while (pos < buf.length && !isWhitespace(buf(pos))) {\n pos += 1\n }\n new java.lang.String(buf, s, pos - s)\n }\n\n def nextInt(): Int = next.toInt\n\n def nextLong(): Long = next.toLong\n\n def nextFloat(): Float = next.toFloat\n\n def nextDouble(): Double = next.toDouble\n\n val nextString: () => String = next _\n }\n\n import Input._\n\n def solve(): Unit = {\n val N, M = nextInt\n val A: Array[Long] = Array.fill(N)(nextLong)\n\n var sumY = 0L\n var i = 0\n while (i < M) {\n (nextInt: @switch) match {\n case 1 =>\n val v = nextInt - 1\n val x = nextLong - sumY\n A(v) = x\n case 2 =>\n val y = nextLong\n sumY += y\n case 3 =>\n val q = nextInt - 1\n out.println(A(q) + sumY)\n }\n i += 1\n }\n }\n\n solve\n out.flush\n}\n"}, {"source_code": "object Main {\n def readLineOfNums(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readLineOfNumsI(): Array[Int] = readLine().split(\" \").map(_.toInt)\n val result = new StringBuilder()\n def performCommand(array: Array[Long], sum: Long) = {\n val cmd = readLineOfNumsI()\n cmd(0) match {\n case 1 =>\n array(cmd(1)-1) = cmd(2) - sum\n sum\n case 2 =>\n sum + cmd(1)\n case 3 =>\n result.append(array(cmd(1)-1) + sum).append(\"\\n\")\n sum\n }\n }\n def main(args: Array[String]) = {\n val Array(n, m) = readLineOfNumsI()\n val array = readLineOfNums()\n var sum: Long = 0\n for (i <- 1 to m)\n sum = performCommand(array, sum)\n print(result)\n }\n}\n"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n val as = readInts\n var delta = 0\n\n var t = 0\n while (t < m) {\n t += 1\n val op = readInts\n op(0) match {\n case 1 => as(op(1) - 1) = op(2) - delta\n case 2 => delta += op(1)\n case 3 => println(as(op(1) - 1) + delta)\n }\n }\n \n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n \n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n val as = readInts\n var delta = 0\n\n var t = 0\n while (t < m) {\n t += 1\n val op = readInts\n op(0) match {\n case 1 => as(op(1) - 1) = op(2) - delta\n case 2 => delta += op(1)\n case 3 => println(as(op(1) - 1) + delta)\n }\n }\n \n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine \n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val as = readInts(n)\n var delta = 0\n\n Console.withOut(new java.io.BufferedOutputStream(Console.out)) {\n var t = 0\n while (t < m) {\n t += 1\n val st = tokenizeLine\n st.nextToken.toInt match {\n case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta\n case 2 => delta += st.nextToken.toInt\n case 3 => println(as(st.nextToken.toInt - 1) + delta)\n }\n }\nConsole.flush\n} \n}\n"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n def readLongs = readString.split(\" \").map(_.toLong)\n\n val Array(n, m) = readInts\n val as = readLongs\n var delta = 0L\n\n var t = 0\n while (t < m) {\n t += 1\n val op = readInts\n op(0) match {\n case 1 => as(op(1) - 1) = op(2) - delta\n case 2 => delta += op(1)\n case 3 => println(as(op(1) - 1) + delta)\n }\n }\n \n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine \n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n def buffered(thunk: => Unit) = \n Console.withOut(new java.io.BufferedOutputStream(Console.out)) {\n thunk\n\t Console.flush\n }\n\n val Array(n, m) = readInts(2)\n val as = readInts(n)\n var delta = 0\n\n buffered {\n var t = 0\n while (t < m) {\n t += 1\n val st = tokenizeLine\n st.nextToken.toInt match {\n case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta\n case 2 => delta += st.nextToken.toInt\n case 3 => println(as(st.nextToken.toInt - 1) + delta)\n }\n }\n } \n}\n"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine \n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n Console.setOut(new java.io.PrintStream(Console.out))\n\n val Array(n, m) = readInts(2)\n val as = readInts(n)\n var delta = 0\n\n var t = 0\n while (t < m) {\n t += 1\n val st = tokenizeLine\n st.nextToken.toInt match {\n case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta\n case 2 => delta += st.nextToken.toInt\n case 3 => println(as(st.nextToken.toInt - 1) + delta)\n }\n }\n \n Console.flush \n}\n"}], "negative_code": [{"source_code": "object B extends App {\n\n def readString = Console.readLine \n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val as = readInts(n)\n var delta = 0\n\n Console.withOut(new java.io.BufferedOutputStream(Console.out)) {\n var t = 0\n while (t < m) {\n t += 1\n val st = tokenizeLine\n st.nextToken.toInt match {\n case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta\n case 2 => delta += st.nextToken.toInt\n case 3 => println(as(st.nextToken.toInt - 1) + delta)\n }\n }\n} \n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P315B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n // N integers\n // array A = A_1, ..., A_n\n // M operations\n // * A_(V_i) = X_i\n // * Increase each A_i by Y_i ... A_i = A_i + Y_i\n // * A_(Q_i)\n\n def solve(): Unit = {\n val N, M = sc.nextInt\n val A: Array[Long] = Array.fill(N)(sc.nextLong)\n\n var sumY = 0\n 0 until M foreach { i =>\n sc.nextInt match {\n case 1 =>\n val v, x = sc.nextInt\n A(v - 1) = x\n case 2 =>\n sumY += sc.nextInt\n case 3 =>\n out.println(A(sc.nextInt - 1) + sumY)\n }\n }\n }\n\n solve\n out.close\n}\n"}, {"source_code": "object B extends App {\n\n val scan = new java.util.Scanner(Console.in)\n \n val (n, m) = (scan.nextInt, scan.nextInt)\n val as = Array.fill(n)(scan.nextInt)\n var delta = 0\nprintln(util.Properties.versionString)\n var t = 0\n while (t < m) {\n t += 1\n scan.nextInt match {\n case 1 => as(scan.nextInt - 1) = scan.nextInt - delta\n case 2 => delta += scan.nextInt\n case 3 => println(as(scan.nextInt - 1) + delta)\n }\n }\n \n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine \n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val as = readInts(n)\n var delta = 0\n\n var t = 0\n while (t < m) {\n t += 1\n val st = tokenizeLine\n st.nextToken.toInt match {\n case 1 => val i = st.nextToken.toInt; as(t - 1) = st.nextToken.toInt - delta\n case 2 => delta += st.nextToken.toInt\n case 3 => println(as(st.nextToken.toInt - 1) + delta)\n }\n }\n \n}\n"}], "src_uid": "48f3ff32a11770f3b168d6e15c0df813"} {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val a = in.nextInt()\n val b = in.nextInt()\n val r = math.abs(a - b)\n\n if (r % 10 == 0) {\n println(r / 10)\n } else {\n println(1 + (r / 10))\n }\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextLineInt(n: Int): ArrayBuffer[Int] = {\n var data = ArrayBuffer[Int]()\n n.times({\n data += nextInt()\n })\n data\n }\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n", "positive_code": [{"source_code": "object CodeforcesRound667a {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val Array(a, b) = rll_int\n val diff = Math.abs(b - a)\n val res = diff / 10 + (if (diff % 10 > 0) 1 else 0)\n writer.println(res)\n }\n\n def sqr(a: Long): Long = a * a\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}"}, {"source_code": "//package codeforces.contests._1409\n\nobject YetAnotherTwoIntegersProblem {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n\n val Array(a, b) = io.StdIn.readLine.split(\" \").map(_.toInt)\n println {\n val d = (a - b).abs\n\n if (d % 10 == 0) d / 10 else d / 10 + 1\n }\n }\n }\n}\n"}, {"source_code": "/**\n * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools\n */\nimport scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n // Write your solution here\n /*\n int t;\n cin >> t;\n while (t--) {\n int a, b;\n cin >> a >> b;\n cout << (abs(a - b) + 9) / 10 << endl;\n }\n\n return 0;\n */\n val t = readInt\n\n for (_ <- 0 until t) {\n val splitLine = readLine.split(\" \")\n val a = splitLine(0).toInt\n val b = splitLine(1).toInt\n\n println((math.abs(a - b) + 9) / 10)\n }\n }\n}"}, {"source_code": "/**\n * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools\n */\nimport scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n // Write your solution here\n val t = readInt\n\n for (_ <- 0 until t) {\n val splitLine = readLine.split(\" \").map(_.toInt)\n val a = splitLine(0)\n val b = splitLine(1)\n\n println((math.abs(a - b) + 9) / 10)\n }\n }\n}"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine.toInt\n for (_ <- 0 until t) {\n val arr = StdIn.readLine.split(\" \").map(_.toInt)\n val res = ((arr.max - arr.min).abs + 9) / 10\n println(res)\n\n }\n }\n}"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b) = readLine().split(\" \").map(_.toInt)\n val c = (a - b).abs\n\n val ans = c / 10 + (if (c % 10 == 0) 0 else 1)\n\n println(ans)\n }\n}\n"}], "negative_code": [], "src_uid": "d67a97a3b69d599b03d3fce988980646"} {"source_code": "import java.io.BufferedReader\r\nimport java.io.InputStreamReader\r\n\r\nobject Main {\r\n def main(args: Array[String]) = {\r\n val cin = new BufferedReader(new InputStreamReader(System.in))\r\n val T = cin.readLine.toInt\r\n for (t <- 1 to T) {\r\n val n::k::Nil = cin.readLine.split(\" \").map(_.toInt).toList\r\n val l = (k+1)/2\r\n println(n-l)\r\n for (x <- l to n)\r\n\t\t\t if (x != k)\r\n\t\t\t\t print(x+\" \")\r\n\t println() } } } \r\n", "positive_code": [{"source_code": "import java.io.BufferedReader\r\nimport java.io.ByteArrayInputStream\r\nimport java.io.InputStreamReader\r\n\r\nobject AAntiKnapsack {\r\n def solve(n: Int, k: Int): (Int, String) = {\r\n val higher = (1 to n).dropWhile(_ <= k)\r\n val res = (Math.ceil(k.toFloat / 2).toInt until k) ++ higher\r\n (res.length, res.mkString(\"\", \" \", \"\"))\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val file = new BufferedReader(new InputStreamReader(System.in))\r\n// val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(\r\n// \"3\\n3 2\\n5 3\\n1 1\".getBytes)))\r\n // \"1\\n3\\n0 0 3\".getBytes)))\r\n val inputs = file.readLine.toInt\r\n var i = 0\r\n while (i < inputs) {\r\n val n::k::Nil = file.readLine.split(\" \").map(_.toInt).toList\r\n solve(n, k).productIterator.foreach(println)\r\n i += 1\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "d08e39db62215d7817113aaa384e3f59"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline private final def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n @inline private final def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n @inline private final def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n @inline private final def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならfinalはずせ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n solve2()\n }\n }\n\n def solve2(): Unit = {\n val n, m = ni()\n val g = nm(n, m)\n val colMx = Array.ofDim[Int](m)\n REP(n) { i =>\n REP(m) { j =>\n colMx(j) = max(colMx(j), g(i)(j))\n }\n }\n val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)\n debug(cols)\n val dp = Array.ofDim[Int](2, 1 << n)\n val tmp = Array.ofDim[Int](1 << n)\n REP(cols.length) { i =>\n val c = cols(i)\n val x = i&1\n Array.copy(dp(x), 0, dp(x^1), 0, dp(x).length)\n REP(n) { roll =>\n Array.copy(dp(x), 0, tmp, 0, tmp.length)\n REP(n) { j =>\n val pos = (j + roll) % n\n var s = 0\n while(s < tmp.length) {\n if ((s >> j & 1) == 0) {\n val ns = 1 << j | s\n tmp(ns) = max(tmp(ns), tmp(s) + g(pos)(c))\n }\n s += 1\n }\n }\n REP(tmp.length) { s =>\n dp(x^1)(s) = max(dp(x^1)(s), tmp(s))\n }\n }\n }\n\n val ans = dp(cols.length&1)((1< Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n solve2()\n }\n }\n\n def solve2(): Unit = {\n val n, m = ni()\n val g = nm(n, m)\n val colMx = Array.ofDim[Int](m)\n REP(n) { i =>\n REP(m) { j =>\n colMx(j) = max(colMx(j), g(i)(j))\n }\n }\n val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)\n debug(cols)\n val dp = Array.ofDim[Int](2, 1 << n)\n val tmp = Array.ofDim[Int](1 << n)\n REP(cols.length) { i =>\n val c = cols(i)\n val x = i&1\n Array.copy(dp(x), 0, dp(x^1), 0, dp(x).length)\n REP(n) { roll =>\n Array.copy(dp(x), 0, tmp, 0, tmp.length)\n REP(n) { j =>\n val pos = (j+roll) % n\n REP(1 << n) { s =>\n if ((s>>j&1) == 0) {\n val ns = 1<\n dp(x^1)(s) = max(dp(x^1)(s), tmp(s))\n }\n }\n }\n\n val ans = dp(cols.length&1)((1< Unit): Unit = {\n if (!oj){ f }\n }\n @inline private def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline private def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline private def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n @inline private def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならfinalはずせ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n solve2()\n }\n }\n\n def solve2(): Unit = {\n val n, m = ni()\n val g = nm(n, m)\n val colMx = Array.ofDim[Int](m)\n REP(n) { i =>\n REP(m) { j =>\n colMx(j) = max(colMx(j), g(i)(j))\n }\n }\n val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)\n debug(cols)\n val dp = Array.ofDim[Int](2, 1 << n)\n val tmp = Array.ofDim[Int](1 << n)\n REP(cols.length) { i =>\n val c = cols(i)\n val x = i&1\n Array.copy(dp(x), 0, dp(x^1), 0, dp(x).length)\n REP(n) { roll =>\n Array.copy(dp(x), 0, tmp, 0, tmp.length)\n REP(n) { j =>\n val pos = (j + roll) % n\n REP(tmp.length) { s =>\n if ((s >> j & 1) == 0) {\n val ns = 1 << j | s\n tmp(ns) = max(tmp(ns), tmp(s) + g(pos)(c))\n }\n }\n }\n REP(tmp.length) { s =>\n dp(x^1)(s) = max(dp(x^1)(s), tmp(s))\n }\n }\n }\n\n val ans = dp(cols.length&1)((1< Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n solve2()\n }\n }\n\n def solve2(): Unit = {\n val n, m = ni()\n val g = nm(n, m)\n val colMx = Array.ofDim[Int](m)\n REP(n) { i =>\n REP(m) { j =>\n colMx(j) = max(colMx(j), g(i)(j))\n }\n }\n val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)\n debug(cols)\n var cur, next = Array.ofDim[Int](1 << n)\n val tmp = Array.ofDim[Int](1 << n)\n REP(cols.length) { i =>\n Array.copy(cur, 0, next, 0, cur.length)\n REP(n) { roll =>\n Array.copy(cur, 0, tmp, 0, tmp.length)\n REP(n) { j =>\n val pos = (j+roll) % n\n REP(1 << n) { s =>\n if ((s>>j&1) == 0) {\n val ns = 1< Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n solve2()\n }\n }\n\n def solve2(): Unit = {\n val n, m = ni()\n val g = nm(n, m)\n val colMx = Array.ofDim[Int](m)\n REP(n) { i =>\n REP(m) { j =>\n colMx(j) = max(colMx(j), g(i)(j))\n }\n }\n val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)\n debug(cols)\n val dp = Array.ofDim[Int](2, 1 << n)\n val tmp = Array.ofDim[Int](1 << n)\n REP(cols.length) { i =>\n val c = cols(i)\n val x = i&1\n Array.copy(dp(x), 0, dp(x^1), 0, dp(x).length)\n REP(n) { roll =>\n Array.copy(dp(x), 0, tmp, 0, tmp.length)\n REP(n) { j =>\n val pos = (j+roll) % n\n var s =0\n while(s < tmp.length) {\n if ((s>>j&1) == 0) {\n val ns = 1<\n dp(x^1)(s) = max(dp(x^1)(s), tmp(s))\n }\n }\n }\n\n val ans = dp(cols.length&1)((1< Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n solve2()\n }\n }\n\n def solve2(): Unit = {\n val n, m = ni()\n val g = nm(n, m)\n val colMx = Array.ofDim[Int](m)\n REP(n) { i =>\n REP(m) { j =>\n colMx(j) = max(colMx(j), g(i)(j))\n }\n }\n val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)\n debug(cols)\n var cur, next = Array.ofDim[Int](1 << n)\n val tmp = Array.ofDim[Int](1 << n)\n REP(cols.length) { i =>\n val c = cols(i)\n Array.copy(cur, 0, next, 0, cur.length)\n REP(n) { roll =>\n Array.copy(cur, 0, tmp, 0, tmp.length)\n REP(n) { j =>\n val pos = (j+roll) % n\n REP(1 << n) { s =>\n if ((s>>j&1) == 0) {\n val ns = 1<\n next(s) = max(next(s), tmp(s))\n }\n }\n val t = cur\n cur = next\n next = t\n }\n\n val ans = cur((1< Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n solve2()\n }\n }\n\n def solve2(): Unit = {\n val n, m = ni()\n val g = nm(n, m)\n val colMx = Array.ofDim[Int](m)\n REP(n) { i =>\n REP(m) { j =>\n colMx(j) = max(colMx(j), g(i)(j))\n }\n }\n val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)\n debug(cols)\n var cur, next = Array.ofDim[Int](1 << n)\n val tmp = Array.ofDim[Int](1 << n)\n REP(cols.length) { i =>\n Array.copy(cur, 0, next, 0, cur.length)\n REP(n) { roll =>\n Array.copy(cur, 0, tmp, 0, tmp.length)\n REP(n) { j =>\n val pos = (j+roll) % n\n REP(1 << n) { s =>\n if ((s>>j&1) == 0) {\n val ns = 1<\n next(s) = max(next(s), tmp(s))\n }\n }\n val t = cur\n cur = next\n next = t\n }\n\n val ans = cur((1< Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n solve2()\n }\n }\n\n def solve2(): Unit = {\n val n, m = ni()\n val g = nm(n, m)\n val colMx = Array.ofDim[Int](m)\n REP(n) { i =>\n REP(m) { j =>\n colMx(j) = max(colMx(j), g(i)(j))\n }\n }\n val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)\n debug(cols)\n val dp = Array.ofDim[Int](2, 1 << n)\n val tmp = Array.ofDim[Int](1 << n)\n REP(cols.length) { i =>\n val c = cols(i)\n val x = i&1\n Array.copy(dp(x), 0, dp(x^1), 0, dp(x).length)\n REP(n) { roll =>\n Array.copy(dp(x), 0, tmp, 0, tmp.length)\n var j = 0\n while(j < n) {\n val pos = (j+roll) % n\n REP(1 << n) { s =>\n if ((s>>j&1) == 0) {\n val ns = 1<\n dp(x^1)(s) = max(dp(x^1)(s), tmp(s))\n }\n }\n }\n\n val ans = dp(cols.length&1)((1< Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline private final def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n @inline private final def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n @inline private final def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n @inline private final def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならfinalはずせ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n solve2()\n }\n }\n\n def solve2(): Unit = {\n val n, m = ni()\n val g = nm(n, m)\n val colMx = Array.ofDim[Int](m)\n REP(n) { i =>\n REP(m) { j =>\n colMx(j) = max(colMx(j), g(i)(j))\n }\n }\n val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)\n debug(cols)\n val dp = Array.ofDim[Int](2, 1 << n)\n val tmp = Array.ofDim[Int](1 << n)\n REP(cols.length) { i =>\n val c = cols(i)\n val x = i&1\n Array.copy(dp(x), 0, dp(x^1), 0, dp(x).length)\n REP(n) { roll =>\n Array.copy(dp(x), 0, tmp, 0, tmp.length)\n REP(n) { j =>\n val pos = (j + roll) % n\n REP(tmp.length) { s =>\n if ((s >> j & 1) == 0) {\n val ns = 1 << j | s\n tmp(ns) = max(tmp(ns), tmp(s) + g(pos)(c))\n }\n }\n }\n REP(tmp.length) { s =>\n dp(x^1)(s) = max(dp(x^1)(s), tmp(s))\n }\n }\n }\n\n val ans = dp(cols.length&1)((1< Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n solve2()\n }\n }\n\n def solve2(): Unit = {\n val n, m = ni()\n val g = nm(n, m)\n val colMx = Array.ofDim[Int](m)\n REP(n) { i =>\n REP(m) { j =>\n colMx(j) = max(colMx(j), g(i)(j))\n }\n }\n val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)\n debug(cols)\n val dp = Array.ofDim[Int](2, 1 << n)\n val tmp = Array.ofDim[Int](1 << n)\n REP(cols.length) { i =>\n val x = i&1\n Array.copy(dp(x), 0, dp(x^1), 0, dp(x).length)\n REP(n) { roll =>\n Array.copy(dp(x), 0, tmp, 0, tmp.length)\n REP(n) { j =>\n REP(1 << n) { s =>\n if ((s>>j&1) == 0) {\n val ns = 1< acc\n case((0, 0), (\"1\", i)) => (1, i)\n case((count, previous), (\"1\", i)) if i - previous == 1 => (count + 1, i)\n case((count, previoius), (\"1\", i)) => (count + 2, i)\n }._1)\n\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\n/** B. Inbox (100500)\n * http://codeforces.com/problemset/problem/465/B\n * @author Yuichiroh Matsubayashi\n * Created on 15/01/19.\n */\nobject P465B extends App{\n val n = StdIn.readInt()\n val read = StdIn.readLine().split(\"0\").map(_.filter(_ == '1')).filter(_ != \"\")\n\n def solution = (read.map(sec => sec.size + 1).sum - 1) max 0\n\n println(solution)\n\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 07.09.14.\n */\nobject B extends App {\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n val es = Array.fill(n)(0)\n for(i <- 0 until n) {\n es(i) = nextInt\n }\n def nClicks(es: Array[Int]): List[Int] = {\n if(es.length == 0) {\n Nil\n } else {\n val (first, rest) = es.dropWhile(_ == 0).span(_ == 1)\n first.length :: nClicks(rest)\n }\n }\n val ones = nClicks(es).filterNot(_ == 0)\n out.print(math.max(ones.sum + ones.length - 1, 0))\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _465B extends App {\n var token = new StringTokenizer(\"\")\n\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt)\n\n def doit(i: Int, pre: Int, acc: Int): Int = {\n if (i == n) acc\n else if (a(i) == 0) doit(i + 1, pre, acc)\n else {\n if (pre == -1) doit(i + 1, i, acc + 1)\n else {\n if (pre + 1 == i) doit(i + 1, i, acc + 1)\n else doit(i + 1, i, acc + 2)\n }\n }\n }\n\n println(doit(0, -1, 0))\n}\n"}, {"source_code": "object B465 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n).zipWithIndex.filter(_._1 == 1).map(_._2)\n var res = if(in.isEmpty) 0 else 1\n for(i <- 1 until in.length) {\n if(in(i-1)+1 == in(i)) {\n res +=1\n } else {\n res += 2\n }\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "\nimport java.io.InputStreamReader\nimport java.io.BufferedReader\n\n/**\n * @author pvasilyev\n * @since 19 May 2016\n */\nobject B465 extends App {\n\n def solve(): Any = {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val n = reader.readLine().toInt\n val seq = reader.readLine().split(\" \").map(_.toInt)\n val index = seq.lastIndexWhere(_ != 0)\n println(seq.take(index + 1).foldLeft((0, 0))((y: (Int, Int), x: Int) => {\n if (y._2 == 0 && x == 0) {\n // do nothing\n y\n } else if (y._2 == 0 && x == 1) {\n (y._1 + 1, 1)\n } else if (y._2 == 1 && x == 0) {\n (y._1 + 1, 0)\n } else {\n (y._1 + 1, 1)\n }\n })._1)\n }\n\n solve()\n\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\n/** B. Inbox (100500)\n * http://codeforces.com/problemset/problem/465/B\n * @author Yuichiroh Matsubayashi\n * Created on 15/01/19.\n */\nobject P465B extends App{\n val n = StdIn.readInt()\n val read = StdIn.readLine().split(\"0\").map(_.filter(_ == '1')).filter(_ != \"\")\n\n println(read.toSeq)\n def solution = (read.map(sec => sec.size + 1).sum - 1) max 0\n\n println(solution)\n\n}\n"}], "src_uid": "0fbc306d919d7ffc3cb02239cb9c2ab0"} {"source_code": "import scala.io.StdIn.readLine\n\nobject task extends App {\n val t: Int = readLine.toInt\n (1 to t).foreach { _ =>\n val n = readLine.toLong\n println(\"2\")\n printf(s\"$n ${n-1}\\n\");\n for (i <- n to 3 by -1) {\n printf(s\"$i ${i - 2}\\n\")\n }\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val res = new StringBuilder\n val even, odd = mutable.PriorityQueue.empty[Int]\n for (i <- 1 to n) {\n if (i % 2 == 0) even.enqueue(i)\n else odd.enqueue(i)\n }\n\n while (even.size > 1 || odd.size > 1) {\n if (even.size > 1 && odd.size > 1) {\n val aE, bE = even.dequeue()\n val cE = (aE + bE) / 2\n val aO, bO = odd.dequeue()\n val cO = (aO + bO) / 2\n val c = if (cO > bE) {\n res.append(s\"$aO $bO\\n\")\n even.enqueue(aE, bE)\n cO\n } else {\n res.append(s\"$aE $bE\\n\")\n odd.enqueue(aO, bO)\n cE\n }\n if (c % 2 == 0) even.enqueue(c)\n else odd.enqueue(c)\n } else if (odd.size > 1) {\n val a, b = odd.dequeue()\n res.append(s\"$a $b\\n\")\n val c = (a + b) / 2\n if (c % 2 == 0) even.enqueue(c)\n else odd.enqueue(c)\n } else if (even.size > 1) {\n val a, b = even.dequeue()\n res.append(s\"$a $b\\n\")\n val c = (a + b) / 2\n if (c % 2 == 0) even.enqueue(c)\n else odd.enqueue(c)\n }\n }\n\n if (even.size == 1 && odd.size == 1) {\n val a = even.dequeue()\n val b = odd.dequeue()\n res.append(s\"$a $b\\n\")\n val c = (a + b + 1) / 2\n if (c % 2 == 0) even.enqueue(c)\n else odd.enqueue(c)\n }\n\n val x = if (even.nonEmpty) even.dequeue() else odd.dequeue()\n\n out.println(x)\n out.print(res.toString())\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject task extends App {\n val t: Int = readLine.toInt\n (1 to t).foreach { _ =>\n val n = readLine.toLong\n println(2)\n for (i <- n to 3 by -1) {\n println(s\"$i ${i - 2}\")\n println(s\"${i-1} ${i - 1}\")\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject task extends App {\n val t: Int = readLine.toInt\n (1 to t).foreach { _ =>\n val n = readLine.toLong\n println(\"2\")\n for (i <- n to 3 by -1) {\n if (i > 3) printf(s\"$i ${i - 2}\\n${i-1} ${i - 1}\\n\")\n else printf(s\"$i ${i - 2}\\n\")\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject task extends App {\n val t: Int = readLine.toInt\n (1 to t).foreach { _ =>\n val n = readLine.toLong\n println(\"2\")\n for (i <- n to 3 by -1) {\n if (i > 3) println(s\"$i ${i - 2}\\n${i-1} ${i - 1}\")\n else println(s\"$i ${i - 2}\")\n }\n }\n}"}, {"source_code": "import scala.collection.mutable\n\nobject C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val res = new StringBuilder\n val even, odd = mutable.PriorityQueue.empty[Int]\n for (i <- 1 to n) {\n if (i % 2 == 0) even.enqueue(i)\n else odd.enqueue(i)\n }\n\n while (even.size > 1 || odd.size > 1) {\n if (even.size > 1 && odd.size > 1) {\n val aE, bE = even.dequeue()\n val cE = (aE + bE) / 2\n val aO, bO = odd.dequeue()\n val cO = (aO + bO) / 2\n val c = if (cO > aE) {\n res.append(s\"$aO $bO\\n\")\n even.enqueue(aE, bE)\n cO\n } else {\n res.append(s\"$aE $bE\\n\")\n odd.enqueue(aO, bO)\n cE\n }\n if (c % 2 == 0) even.enqueue(c)\n else odd.enqueue(c)\n } else if (odd.size > 1) {\n val a, b = odd.dequeue()\n res.append(s\"$a $b\\n\")\n val c = (a + b) / 2\n if (c % 2 == 0) even.enqueue(c)\n else odd.enqueue(c)\n } else if (even.size > 1) {\n val a, b = even.dequeue()\n res.append(s\"$a $b\\n\")\n val c = (a + b) / 2\n if (c % 2 == 0) even.enqueue(c)\n else odd.enqueue(c)\n }\n }\n\n if (even.size == 1 && odd.size == 1) {\n val a = even.dequeue()\n val b = odd.dequeue()\n res.append(s\"$a $b\\n\")\n val c = (a + b + 1) / 2\n if (c % 2 == 0) even.enqueue(c)\n else odd.enqueue(c)\n }\n\n val x = if (even.nonEmpty) even.dequeue() else odd.dequeue()\n\n out.println(x)\n out.print(res.toString())\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "src_uid": "591372383cf3624f69793c41370022de"} {"source_code": "\nobject A extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n// val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val n = in.nextInt()\n\n n.times {\n val m = in.nextInt()\n println(math.ceil(m / 2d).toInt)\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n\n val t = readInt()\n 1 to t foreach { _ =>\n val i = readInt()\n println((i - 1) / 2 + 1)\n }\n\n}\n"}], "negative_code": [{"source_code": "\nobject A extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n// val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val n = in.nextInt()\n\n n.times {\n val m = in.nextInt()\n if (m == 1 || m == 2) println(1) else println(2)\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}], "src_uid": "ec89860dacb5a11b3a2273d2341b07a1"} {"source_code": "import scala.io.StdIn\n\nobject Chocolate_1139B {\n // https://codeforces.com/problemset/problem/1139/B\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n val cTypes = StdIn.readLine().split(\" \").map(_.toInt)\n\n val (_, res) = cTypes.foldRight((Int.MaxValue, 0L)) {\n case (curr: Int, (prev: Int, sum: Long)) =>\n if (curr <= 0 || prev <= 0) {\n (0, sum)\n } else if (prev > curr) {\n (curr, sum + curr)\n } else {\n // prev <= curr && prev != 0\n (prev - 1, sum + prev - 1)\n }\n }\n\n println(res)\n }\n\n}", "positive_code": [{"source_code": "//package codeforces.contest1139\n\nobject Chocolates {\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val arr = io.StdIn.readLine().split(\" \").map(_.toInt)\n\n println(arr.foldRight((Int.MaxValue, 0l)) { case (current, (maximum: Int, sum: Long)) =>\n val chocolates = (current min (maximum - 1)) max 0\n (chocolates, sum + chocolates)\n }._2)\n }\n}\n"}, {"source_code": "object B1139 {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val n = stdin.readInt()\n val array = stdin.readLine.trim.split(\" \").map(_.toLong)\n var sum = 0L\n sum += array(n-1)\n for (i <- 1 until n){\n val temp = math.max(math.min(array(n-i-1) , array(n-i)-1), 0)\n sum += temp\n array(n-i-1) = temp\n }\n println(sum)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n import java.util.Arrays\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n var ans = 0L\n\n var next = 1e9.toInt + 1\n REP_r(N) { i =>\n next = if (A(i) < next) {\n A(i)\n } else {\n max(0, next - 1)\n }\n debug(s\"next:$next\")\n ans += next\n }\n\n out.println(ans)\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}, {"source_code": "object B1139 {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val n = stdin.readInt()\n val array = stdin.readLine.trim.split(\" \").map(_.toLong).reverse\n val cal = (a: Long,b: Long) => math.max(math.min(b , a-1), 0)\n var ans = array(0)\n for (i <- 1 until n){\n array(i) = cal(array(i-1), array(i))\n ans = ans + array(i)\n }\n println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contest1139\n\nobject Chocolates {\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val arr = io.StdIn.readLine().split(\" \").map(_.toInt)\n\n println(arr.foldRight((Int.MaxValue, 0)) { case (current, (maximum: Int, sum: Int)) =>\n val chocolates = (current min (maximum - 1)) max 0\n (chocolates, sum + chocolates)\n }._2)\n }\n}\n"}, {"source_code": "object B1139 {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val n = stdin.readInt()\n val array = stdin.readLine.trim.split(\" \").map(_.toLong).reverse\n val temp = (a: Long,b: Long) => math.max(math.min(b , a-1), 0)\n var ans = 0L\n for (i <- 1 until n){\n ans = ans + temp(array(i-1), array(i))\n }\n println(ans)\n }\n}\n"}, {"source_code": "object B1139 {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val n = stdin.readInt()\n val array = stdin.readLine.trim.split(\" \").map(_.toLong).reverse\n val ans = array.foldLeft(0L)((a,b) => math.max(math.min(b , a-1), 0))\n println(ans)\n }\n}\n"}], "src_uid": "5993b5bf231fabd3c2af90124c41f118"} {"source_code": "object _799B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n val n = read[Int]\n val prices, frontColors, backColors = read[Vector, Int](n)\n val favColors = read[Seq[Int]]\n\n val sortedPrices = prices.zipWithIndex.sortBy(_.key)\n\n // map from color -> Seq[(price, idx)]\n val table = map[Int] to mutable.ListBuffer.empty[(Int, Int)]\n\n for {\n entry @ (price, idx) <- sortedPrices\n color <- Seq(frontColors(idx), backColors(idx)).distinct\n } table(color).append(entry)\n\n val isUsed = mutable.Set.empty[Int]\n\n def fetchBestPrice(color: Int): Int = {\n table(color).headOption match {\n case None => -1\n case Some((price, idx)) =>\n table(color).remove(n = 0, count = 1)\n if (isUsed(idx)) {\n fetchBestPrice(color)\n } else {\n isUsed += idx\n price\n }\n }\n }\n\n writeAll(favColors.map(fetchBestPrice))\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n case class Shirt(p: Int, a: Int, b: Int)\n\n val Array(n) = readInts(1)\n val ps, as, bs = readInts(n)\n\n val shirts = Array.tabulate(n){ i => Shirt(ps(i), as(i) - 1, bs(i) - 1)}.sortBy(_.p)\n\n val Array(m) = readInts(1)\n val cs = readInts(m)\n\n val res = Array.fill(m){ -1 }\n val ptr = Array.fill(3)(0)\n val used = new mutable.BitSet(n)\n\n for (i <- 0 until m) {\n val c = cs(i) - 1\n while (ptr(c) < n && (used(ptr(c)) || (shirts(ptr(c)).a != c && shirts(ptr(c)).b != c))) ptr(c) += 1\n if (ptr(c) < n) {\n used += ptr(c)\n res(i) = shirts(ptr(c)).p\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "object Solution extends CodeForcesApp {\n\timport Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n\toverride def apply(io: IO): io.type = {\n\t\tval n = io.read[Int]\n\t\tval p = io.read[Array, Int](n)\n\t\tval a = io.read[Array, Int](n)\n\t\tval b = io.read[Array, Int](n)\n\t\tval m = io.read[Int]\n\t\tval qries = io.read[Seq, Int](m)\n\t\tvar x = new Array[Int](n)\n\t\tfor { i <- 0 to n-1 } { x(i) = i }\n\t\tx = x.sortWith((v1, v2) => p(v1) < p(v2) )\n\t\tvar pts = new Array[Int](3)\n\t\t//pts = pts.map(value => 1)\n\t\tval ans = mutable.ArrayBuffer.empty[Int]\n\t\tfor { qry <- qries } {\n\t\t\twhile (pts(qry-1) < n && a(x(pts(qry-1))) != qry && b(x(pts(qry-1))) != qry) {\n\t\t\t\tpts(qry-1) += 1\n\t\t\t}\n\t\t\tif(pts(qry-1) < n) {\n\t\t\t\tval id = x(pts(qry-1))\n\t\t\t\tans += p(id)\n\t\t\t\ta(id) = -1\n\t\t\t\tb(id) = -1\n\t\t\t\tpts(qry-1) += 1\n\t\t\t} else {\n\t\t\t\tans += -1\n\t\t\t}\n\t\t}\n\t\t//x = x.map(value => p(value))\n\t\t//io.writeAll(x)\n\t\t//io.writeLine()\n\t\tio.writeAll(ans)\n\t\tio.writeLine()\n\t\tio\n\t}\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n\tlazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n\tdef debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n\tdef apply(io: IO): io.type\n\tdef main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n\timport scala.collection.mutable\n\n\ttype of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n\tdef when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n\tdef repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n\timplicit class GenericExtensions[A](a: A) {\n\t\tdef partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n\t}\n\n\timplicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n\t\tdef zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n\t\tdef whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n\t\tdef toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n\t}\n\n\timplicit class PairExtensions[A, B](p: (A, B)) {\n\t\tdef key = p._1\n\t\tdef value = p._2\n\t\tdef toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n\t}\n\n\timplicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n\t\tdef toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n\t}\n\n\timplicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n\t\tdef toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n\t}\n\n\timplicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n\t\tdef notContains(x: A): Boolean = !(s contains x)\n\t\tdef toMutable = mutable.Set.empty[A] ++ s\n\t}\n\n\timplicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n\t\tdef indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n\t\tdef deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n\t\tdef insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n\t\tdef findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n\t}\n\n\timplicit class BooleanExtensions(x: Boolean) {\n\t\tdef to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n\t\tdef toEnglish = if(x) \"Yes\" else \"No\"\n\t}\n\n\tdef desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n\tdef map[K] = new {\n\t\tdef to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n\t\tdef using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n\t\t\toverride def apply(key: K) = getOrElseUpdate(key, f(key))\n\t\t}\n\t}\n\n\tdef newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n\tdef memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n\tdef this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n\tdef this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n\tprivate[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\tval printer = new PrintWriter(out, true)\n\n\t@inline private[this] def tokenizer() = {\n\t\twhile(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n\t\ttokenizers.headOption\n\t}\n\n\tdef read[A](implicit read: IO.Read[A]): A = read.apply(this)\n\tdef read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n\tdef readTill(delim: String): String = tokenizer().get.nextToken(delim)\n\tdef readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n\tdef readAll[A: IO.Read]: (Int, Vector[A]) = {\n\t\tval data = read[Vector[A]]\n\t\t(data.length, data)\n\t}\n\n\toverride def next() = tokenizer().get.nextToken()\n\toverride def hasNext = tokenizer().nonEmpty\n\n\tdef write(obj: Any): this.type = {\n\t\tprinter.print(obj)\n\t\tthis\n\t}\n\tdef writeLine(): this.type = {\n\t\tprinter.println()\n\t\tthis\n\t}\n\tdef writeLine(obj: Any): this.type = {\n\t\tprinter.println(obj)\n\t\tthis\n\t}\n\tdef writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n\tdef writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\tdef query[A: IO.Read](question: Any): A = writeLine(question).read\n\n\toverride def flush() = printer.flush()\n\tdef close() = {\n\t\tflush()\n\t\tin.close()\n\t\tprinter.close()\n\t}\n}\nobject IO {\n\tclass Read[A](val apply: IO => A) {\n\t\tdef map[B](f: A => B): Read[B] = new Read(apply andThen f)\n\t}\n\n\tobject Read {\n\t\timplicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n\t\timplicit val string : Read[String] = new Read(_.next())\n\t\timplicit val int : Read[Int] = string.map(_.toInt)\n\t\timplicit val long : Read[Long] = string.map(_.toLong)\n\t\timplicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n\t\timplicit val double : Read[Double] = string.map(_.toDouble)\n\t\timplicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n\t\timplicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n\t\timplicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n\t\timplicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n\t\timplicit val boolean : Read[Boolean] = string map {s =>\n\t\t\ts.toLowerCase match {\n\t\t\t\tcase \"yes\" | \"true\" | \"1\" => true\n\t\t\t\tcase \"no\" | \"false\" | \"0\" => false\n\t\t\t\tcase _ => s.toBoolean\n\t\t\t}\n\t\t}\n\t}\n}\n"}], "negative_code": [], "src_uid": "d5ead5b6be04cd9389a70e9e420039a6"} {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val divs0 = mutable.Set.empty[Int]\n val lim = Math.sqrt(n).toInt + 2\n var d = 1\n while (d < lim) {\n if (n % d == 0) {\n divs0 += d\n val d2 = n / d\n if (d2 != d) divs0 += d2\n }\n d += 1\n }\n\n val res = Array.ofDim[Long](divs0.size)\n val divs = divs0.toArray\n for (i <- divs.indices) {\n val d = divs(i)\n val max = n - d + 1\n val dd = n.toLong / d\n res(i) = (1 + max) * dd / 2\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.sorted.mkString(\" \"))\n\n Console.flush\n}\n", "positive_code": [{"source_code": "//package codeforces.contest1091\n\nimport scala.collection.SortedSet\n\nobject NewYearAndTheSphereTransmission {\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val sqrt: Int = math.sqrt(n).floor.toInt\n\n println((1 to sqrt).foldLeft(SortedSet[Long]())((set, i) => {\n if (n % i == 0) {\n set + calculateSumOfSeries(1, n + 1 - i, i) + calculateSumOfSeries(1, n + 1 - n / i, n / i)\n } else set\n }).mkString(\" \"))\n\n }\n\n def calculateSumOfSeries(a: Int, an: Int, d: Int): Long = {\n val n = (an - a) / d + 1\n 1l * n * (a + an) / 2\n }\n}\n"}], "negative_code": [], "src_uid": "2ae1a4d4f2e58b359c898d1ff38edb9e"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C640B(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t =ni()\n REP(t) { _ =>\n val n = ni()\n if(n >= 4) {\n val x = if(n % 2 == 0) n - 1 else n\n x to 1 by -2 foreach(i => out.print(s\"$i \"))\n out.print(\"4 2 \")\n if(n >= 6) {\n 6 to n by 2 foreach(i => out.print(s\"$i \"))\n }\n out.println()\n } else {\n out.println(-1)\n }\n }\n }\n}\n", "positive_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\n/**\n* Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools\n*/\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val count = StdIn.readInt()\n for (_ <- 0 until count) {\n val n = StdIn.readInt()\n val result = solution(n, 0, n - 1, Array.ofDim(n))\n if (result.isEmpty)\n print(\"-1\")\n else\n result.foreach(x => print(x + \" \"))\n println()\n }\n }\n\n @tailrec\n def solution(n: Int, left: Int, right: Int, result: Array[Int]): Array[Int] = {\n if (n < 4) Array.empty\n else if (n == 4) {\n updateInPlace(result, left, 3)\n updateInPlace(result, left + 1, 1)\n updateInPlace(result, left + 2, 4)\n updateInPlace(result, left + 3, 2)\n }\n else if (n % 2 == 0) solution(n - 1, left + 1, right, updateInPlace(result, left, n))\n else solution(n - 1, left, right - 1, updateInPlace(result, right, n))\n }\n\n def updateInPlace(array: Array[Int], index: Int, element: Int) = {\n array.update(index, element)\n array\n }\n}"}], "negative_code": [], "src_uid": "9b8a5d9a6cfd6b3b5d0839eeece6f777"} {"source_code": "object Solution {\r\n\r\n import InOut._\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken: String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new java.util.StringTokenizer(in.readLine)\r\n tokenizer.nextToken\r\n }\r\n\r\n def nextInt: Int = Integer.parseInt(nextToken)\r\n\r\n def nextLong: Long = java.lang.Long.parseLong(nextToken)\r\n\r\n def nextBig = BigInt(nextToken)\r\n\r\n def nextInts(n: Int): Array[Int] = Array.fill(n) {\r\n nextInt\r\n }\r\n\r\n def nextLongs(n: Int): Array[Long] = Array.fill(n) {\r\n nextLong\r\n }\r\n\r\n def nextBigs(n: Int): Array[BigInt] = Array.fill(n) {\r\n nextBig\r\n }\r\n\r\n def nextLine: String = in.readLine\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n for (_ <- 1 to nextInt){\r\n val p,a,b,c = nextLong\r\n val arr = for(i <- List(a,b,c)) yield if(p%i == 0) 0 else if(p > i) i*(p/i+1)-p else i-p\r\n out.println(arr.min)\r\n }\r\n out.flush()\r\n \r\n }\r\n\r\n\r\n}\r\n", "positive_code": [{"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val p, a, b, c = nextLong\n val a0 = (a - p % a) % a\n val b0 = (b - p % b) % b\n val c0 = (c - p % c) % c\n\n out.println(a0 min b0 min c0)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "object Solution {\r\n\r\n import InOut._\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken: String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new java.util.StringTokenizer(in.readLine)\r\n tokenizer.nextToken\r\n }\r\n\r\n def nextInt: Int = Integer.parseInt(nextToken)\r\n\r\n def nextLong: Long = java.lang.Long.parseLong(nextToken)\r\n\r\n def nextBig = BigInt(nextToken)\r\n\r\n def nextInts(n: Int): Array[Int] = Array.fill(n) {\r\n nextInt\r\n }\r\n\r\n def nextLongs(n: Int): Array[Long] = Array.fill(n) {\r\n nextLong\r\n }\r\n\r\n def nextBigs(n: Int): Array[BigInt] = Array.fill(n) {\r\n nextBig\r\n }\r\n\r\n def nextLine: String = in.readLine\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n for (_ <- 1 to nextInt){\r\n val p,a,b,c = nextLong\r\n val arr = for(i <- List(a,b,c)) yield if(p > i) i+i*(p/i)-p else i-p\r\n out.println(arr.min)\r\n }\r\n out.flush()\r\n\r\n }\r\n\r\n\r\n}\r\n"}], "src_uid": "293f9b996eee9f76d4bfdeda85685baa"} {"source_code": "import scala.io.Source\nimport java.io.PrintWriter\nimport java.io.File\nimport scala.util.control.Breaks\n\nobject CF254c {\n\n def main(args: Array[String]): Unit = {\n doIt();\n }\n def doIt(){\n /*val sc = new Scanner(System.in);\n val s = sc.next().toCharArray();\n val t = sc.next().toCharArray();*/\n val reader = Source.fromFile(\"input.txt\").getLines;\n val s = reader.next().toCharArray();\n val t = reader.next().toCharArray();\n val writer = new PrintWriter(new File(\"output.txt\" ));\n val loop = new Breaks;\n var as = new Array[Int](26);\n var at = new Array[Int](26);\n var cnts = new Array[Int](26);\n val len = s.length;\n for(e <- s){ //foreach\n as(e - 'A') += 1; //配列は()。++は駄目\n cnts(e - 'A') += 1;\n }\n for(e <- t) at(e - 'A') += 1; //{}は省略可能\n var count = 0;\n for(i <- 0 until len){ //0 .. len - 1\n var idx = s(i) - 'A';\n if(at(idx) < as(idx)){\n loop.breakable{\n for(j <- 0 until as.length)\n if(as(j) < at(j) && ((j < idx) || cnts(idx) <= as(idx) - at(idx) )){\n s(i) = (j + 'A').toChar;\n as(j) += 1;\n as(idx) -= 1;\n count += 1;\n loop.break;\n }\n }\n }\n cnts(idx) -= 1;\n }\n writer.println(count);\n writer.println(s.mkString);\n writer.close();\n /*println(count);\n println(s.mkString); //toStringでは駄目*/\n }\n\n}", "positive_code": [{"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test5 extends App {\n\tval sc=new Scanner(new File(\"input.txt\"))\n\tval out=new PrintWriter(\"output.txt\")\n\t\n\tval S=sc.nextLine.toCharArray()\n val T=sc.nextLine\n val n=S.length\n val s_counts=new Array[Int](26)\n val t_counts=new Array[Int](26)\n \n 0 until n foreach{i=>\n \ts_counts(S(i)-'A')+=1\n \tt_counts(T(i)-'A')+=1\n }\n var count=0\n \n 0 until n foreach{i=>\n \ts_counts(S(i)-'A')-t_counts(S(i)-'A') match{\n \t\tcase x if x>0 =>process(i)\n \t\tcase _ =>\n \t}\n }\n out.println(count)\n out.println(S.mkString)\n out.close\n \n def process(i:Int){\n \tval next=find\n \tval c=S(i)\n \t\n \tif(t_counts(c-'A')==0 || nexts_counts(i)) return ('A'+i).toChar;\n \t}\n \t\n \treturn None.get\n }\n} \n\n"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test5 extends App {\n\tval sc=new Scanner(new File(\"input.txt\"))\n\tval out=new PrintWriter(\"output.txt\")\n\t\n\tval S=sc.nextLine.toCharArray()\n val T=sc.nextLine\n val n=S.length\n val s_counts=new Array[Int](26)\n val t_counts=new Array[Int](26)\n \n 0 until n foreach{i=>\n \ts_counts(S(i)-'A')+=1\n \tt_counts(T(i)-'A')+=1\n }\n var count=0\n \n for(i<-0 until n if s_counts(S(i)-'A')-t_counts(S(i)-'A')>0)\n \tprocess(i)\n\n out.println(count)\n out.println(S.mkString)\n out.close\n \n def process(i:Int){\n \tval next=find\n \tval c=S(i)\n \t\n \tif(t_counts(c-'A')==0 || nexts_counts(i)) return ('A'+i).toChar;\n \t}\n \t\n \treturn None.get\n }\n} \n\n"}], "negative_code": [{"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test5 extends App {\n\tval sc=new Scanner(new File(\"input.txt\"))\n\tval out=new PrintWriter(\"output.txt\")\n\t\n\tval S=sc.nextLine.toCharArray()\n val T=sc.nextLine\n val n=S.length\n val s_counts=new Array[Int](26)\n val t_counts=new Array[Int](26)\n \n 0 until n foreach{i=>\n \ts_counts(S(i)-'A')+=1\n \tt_counts(T(i)-'A')+=1\n }\n var count=0\n \n 0 until n foreach{i=>\n \ts_counts(S(i)-'A')-t_counts(S(i)-'A') match{\n \t\tcase x if x>0 =>process(i)\n \t\tcase _ =>\n \t}\n }\n out.println(count)\n out.println(S.mkString)\n \n def process(i:Int){\n \tval next=find\n \tval c=S(i)\n \t\n \tif(t_counts(c-'A')==0 || nexts_counts(i)) return ('A'+i).toChar;\n \t}\n \t\n \treturn None.get\n }\n} \n\n"}, {"source_code": "//import java.util.Scanner\nimport scala.io.Source\nimport java.io.PrintWriter\nimport java.io.File\n\nobject CF254c {\n\n def main(args: Array[String]): Unit = {\n doIt();\n }\n def doIt(){\n /*val sc = new Scanner(System.in);\n val s = sc.next().toCharArray();\n val t = sc.next().toCharArray();*/\n val reader = Source.fromFile(\"input.txt\").getLines;\n val s = reader.next().toCharArray();\n val t = reader.next().toCharArray();\n val writer = new PrintWriter(new File(\"output.txt\" ));\n var as = new Array[Int](26);\n var at = new Array[Int](26);\n var cnts = new Array[Int](26);\n val len = s.length;\n for(e <- s){ //foreach\n as(e - 'A') += 1; //配列は()。++は駄目\n cnts(e - 'A') += 1;\n }\n for(e <- t) at(e - 'A') += 1; //{}は省略可能\n var count = 0;\n for(i <- 0 until len){ //0 .. len - 1\n var idx = s(i) - 'A';\n if(at(idx) < as(idx)){\n for(j <- 0 until as.length)\n if(as(j) < at(j) && ((j < idx) || cnts(idx) <= as(idx) - at(idx) )){\n s(i) = (j + 'A').toChar;\n as(j) += 1;\n as(idx) -= 1;\n count += 1;\n }\n }\n cnts(idx) -= 1;\n }\n writer.println(count);\n writer.println(s.mkString);\n writer.close();\n /*println(count);\n println(s.mkString); //toStringでは駄目*/\n }\n\n}"}], "src_uid": "b9766f25c8ae179c30521770422ce18b"} {"source_code": "object CF_526_2_B {\n def solve(n: Int, s: Long, vs: Seq[Int]): Long = {\n val minKegVol = vs.min.toLong\n val totalVol = vs.map(_.toLong).sum\n // amount taken before minKeg starts emptying\n val b = totalVol - n * minKegVol\n val excess = s - b\n if (excess <= 0) minKegVol\n else {\n val taken= ceil(excess, n)\n val left = minKegVol - taken\n if (left < 0) -1 else left\n }\n }\n\n // Specify Input and Output formats here:\n def formatIn(i: Input) = (i.int, i.long, {i.nextLine; i.intSeq()})\n def formatOut(out: Long) = out.toString\n\n// ~~~ Boilerplate that doesn't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n def main(args: Array[String]) = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n\n// ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n import java.util.Scanner\n class Input(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine() \n // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def solveVals = (solve _).tupled(formatIn(this))\n def solveStr = formatOut(solveVals)\n }\n\n def ceil(a: Int, b: Int) = (a - 1) / b + 1\n def ceil(a: Long, b: Long) = (a - 1) / b + 1\n\n import language.implicitConversions\n implicit def stringToInput(s: String): Input = new Input(s)\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Codeforces1084B {\n\n def getLeastKeg(n: Int, s: Long, v: Seq[Long]): Long = {\n val minKeg = v.min\n val totalKvass = v.sum\n if (totalKvass < s) return -1\n val extraKvass = totalKvass - minKeg * n\n if (extraKvass >= s) return minKeg\n val additionalKvass = s - extraKvass\n val perKegRemoval = (additionalKvass / n) + (if (additionalKvass % n == 0) 0 else 1)\n minKeg - perKegRemoval\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, s) = StdIn.readLine().trim.split(\" \").map(_.toLong)\n val v = StdIn.readLine().trim.split(\" \").map(_.toLong)\n val leastKeg = getLeastKeg(n.toInt, s, v)\n println(leastKeg)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val S = nl()\n val A = na(N)\n Sorting.quickSort(A)\n reverse(A)\n val sum = sumL(A)\n val ms = A.min\n\n def ok(x: Int): Boolean = {\n x <= ms && (sum - x.toLong * N >= S)\n }\n\n val MAX =1e9.toInt + 1\n var l = -1\n var r = MAX\n while(r - l > 1) {\n val mid = (l + r) / 2\n if(ok(mid)) l = mid\n else r = mid\n }\n\n if (l <= -1 || l > ms) out.println(-1)\n else out.println(l)\n }\n\n\n def reverse(as: Array[Int]): Unit = {\n REP(as.length / 2) { i =>\n val t = as(i)\n as(i) = as(as.length - 1 - i)\n as(as.length - 1 - i) = t\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object CF_526_2_B {\n def solve(n: Int, s: Long, vs: Seq[Int]): Long = {\n val minKegVol = vs.min\n val totalVol = vs.map(_.toLong).sum\n // amount taken before minKeg starts emptying\n val b = totalVol - n * minKegVol\n val excess = s - b\n if (excess <= 0) minKegVol\n else {\n val taken = ceil(excess, n)\n val left = minKegVol - taken\n if (left < 0) -1 else left\n }\n }\n\n // Specify Input and Output formats here:\n def formatIn(i: Input) = (i.int, i.long, {i.nextLine; i.intSeq()})\n def formatOut(out: Long) = out.toString\n\n// ~~~ Boilerplate that doesn't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n def main(args: Array[String]) = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n\n// ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n import java.util.Scanner\n class Input(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine() \n // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def solveVals = (solve _).tupled(formatIn(this))\n def solveStr = formatOut(solveVals)\n }\n\n def ceil(a: Int, b: Int) = (a - 1) / b + 1\n def ceil(a: Long, b: Long) = (a - 1) / b + 1\n\n import language.implicitConversions\n implicit def stringToInput(s: String): Input = new Input(s)\n}"}, {"source_code": "object CF_526_2_B {\n def solve(n: Int, s: Long, vs: Seq[Int]): Long = {\n val minKegVol = vs.min\n val totalVol = vs.sum\n // amount taken before minKeg starts emptying\n val b = totalVol - n * minKegVol\n val excess = s - b\n if (excess <= 0) minKegVol\n else {\n val taken = ceil(excess, n)\n val left = minKegVol - taken\n if (left < 0) -1 else left\n }\n }\n\n // Specify Input and Output formats here:\n def formatIn(i: Input) = (i.int, i.long, {i.nextLine; i.intSeq()})\n def formatOut(out: Long) = out.toString\n\n// ~~~ Boilerplate that doesn't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n def main(args: Array[String]) = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n\n// ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n import java.util.Scanner\n class Input(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine() \n // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def solveVals = (solve _).tupled(formatIn(this))\n def solveStr = formatOut(solveVals)\n }\n\n def ceil(a: Int, b: Int) = (a - 1) / b + 1\n def ceil(a: Long, b: Long) = (a - 1) / b + 1\n\n import language.implicitConversions\n implicit def stringToInput(s: String): Input = new Input(s)\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Codeforces1084B {\n\n def getLeastKeg(n: Int, s: Long, v: Seq[Long]): Long = {\n val minKeg = v.min\n val totalKvass = v.sum\n if (totalKvass < s) return -1\n val extraKvass = totalKvass - minKeg * n\n if (extraKvass >= s) return minKeg\n val additionalKvass = s - extraKvass\n val flatPerKegRemoval = additionalKvass / n\n val minKegCount = v.count(keg => keg == minKeg)\n val nonMinKegCount = n - minKegCount\n if (nonMinKegCount > additionalKvass % n)\n minKeg - flatPerKegRemoval - 1\n else\n minKeg - flatPerKegRemoval\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, s) = StdIn.readLine().trim.split(\" \").map(_.toLong)\n val v = StdIn.readLine().trim.split(\" \").map(_.toLong)\n val leastKeg = getLeastKeg(n.toInt, s, v)\n println(leastKeg)\n }\n}\n"}], "src_uid": "23c63d1fea568a75663450e0c6f23a29"} {"source_code": "object _1326D1 extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val s = io.read[String]\n val n = s.length\n\n var k = 0\n while(k < n/2 && s(k) == s(n - k - 1)) {\n k += 1\n }\n\n val prefix = s.substring(0, k)\n val middle = s.substring(k, n-k)\n val suffix = s.substring(n-k, n)\n\n def pick(str: String) =\n (str.length to 0 by -1)\n .iterator\n .flatMap(i => Set(str.take(i), str.takeRight(i)))\n .filter(x => x == x.reverse)\n .next()\n\n val ans = prefix + pick(middle) + suffix\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n", "positive_code": [{"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n val M = 16769023L\n val B = 37L\n val maxN = 1000001\n val POW = ((0 to maxN).scanLeft(1L){case (h,_) => (h*B)%M}).toArray\n val hashForward: Array[Long] = Array.fill(maxN)(0L)\n val hashBackward: Array[Long] = Array.fill(maxN)(0L)\n var N = 0\n def calcHash(a: Int,b: Int,hash: Array[Long]): Long = {\n //println(s\"HASHING: $a : $b\")\n ((hash(b)-(hash(a)*POW(b-a))%M)+M)%M\n }\n\n\n def isPal(left: Int,right: Int): Boolean = {\n val L = (left+right)\n val L_2 = L/2\n //println(s\"left: $left : right: $right :: L_2: $L_2\")\n val hLeft = if(left>=right) {\n f(L_2,0,L_2)\n }else {\n f(left,N-right,L_2)\n }\n\n val hRight = if(left>=right) {\n g(right,N-left,L_2)\n }else{\n g(L_2,0,L_2)\n }\n\n hLeft == hRight\n }\n\n def f(i_incl: Int, j_incl: Int, length: Int): Long = fg(i_incl,j_incl,length,(a,b) => calcHash(a,b,hashForward))\n def g(i_incl: Int, j_incl: Int, length: Int): Long = fg(i_incl,j_incl,length,(a,b) => calcHash(a,b,hashBackward))\n\n def fg(i_incl: Int, j_incl: Int, length: Int, ch: (Int,Int) => Long): Long = {\n //println(s\"fg $i_incl $j_incl length: $length\")\n val leftHash = ch(0,i_incl)\n val d = length-i_incl\n val centerHash = ch(j_incl,j_incl+d)\n //println(s\"$leftHash*POW($d) + $centerHash\")\n ((leftHash*POW(d))%M + centerHash)%M\n }\n\n\n\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val numCases = in.nextInt()\n (1 to numCases).foreach{ _ =>\n val s = in.next()\n val sr = s.reverse\n N = s.length\n hashForward(0) = 0L\n s.zipWithIndex.foreach{\n case (ch,i) =>\n val v = ch.toInt-'a'.toInt+1\n hashForward(i+1) = (hashForward(i) *B+v)%M\n }\n\n hashBackward(0) = 0L\n sr.zipWithIndex.foreach{\n case (ch,i) =>\n val v = ch.toInt-'a'.toInt+1\n hashBackward(i+1) = (hashBackward(i)*B+v)%M\n }\n\n/*\n println(isPal(0,1))\n println(isPal(1,0))\n println(isPal(0,0))\n println(isPal(1,1))\n println(isPal(2,2))\n println(isPal(3,3))\n println(isPal(4,4))\n println(isPal(5,4))\n println(isPal(4,5))\n*/\n\n\n var maxH = -1\n var isEqual = true\n (0 until N).foreach{ i =>\n if(s(i) == s(N-i-1) && isEqual){\n maxH = i\n }else{\n isEqual = false\n }\n }\n\n\n val L = if(maxH== -1) 0 else (Math.min(N/2,maxH+1))\n\n assert(isPal(L,L))\n\n val r0 = (0 to (N-2*L)).flatMap{d =>\n if(isPal(L+d,L)){\n Some(d)\n }else{\n None\n }\n }.last\n\n\n\n val r1 = (0 to (N-2*L)).flatMap{d =>\n if(isPal(L,L+d)){\n Some(d)\n }else{\n None\n }\n }.last\n\n //println(s\"$L: $r0 - $r1\")\n //println(hashForward.take(11).mkString(\" - \"))\n //println(hashBackward.take(11).mkString(\" - \"))\n val ans = if(r0>=r1){\n //println(isPal(L+r0,L))\n s.substring(0,L+r0)+s.substring(N-L)\n }else{\n //println(isPal(L,L+r1))\n s.substring(0,L)+s.substring(N-(L+r1))\n }\n out.println(ans)\n\n\n\n\n\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "negative_code": [], "src_uid": "042008e186c5a7265fbe382b0bdfc9bc"} {"source_code": "object main extends App with fastIO {\n \n val Array(n) = readLine split(\" \") map(_.toInt) \n var a = readLine split(\" \") map(_.toInt) toList\n \n import scala.collection.mutable.ArrayBuffer\n \n var left = a.foldLeft(ArrayBuffer[Int]())((s, v) => s += (v + (if (s.length > 0) s(s.length - 1) else 0))) \n var right = a.foldRight(ArrayBuffer[Int]())((v, s) => s += (v + (if (s.length > 0) s(s.length - 1) else 0))).reverse\n \n var count = (left zip right).count(v => v._1 <= v._2)\n println(count + \" \" + (n - count)) \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def nextInt :Int = { in.nextToken; in.nval.toInt } \n def nextLong :Long = { in.nextToken; in.nval.toLong } \n def nextDouble :Double = { in.nextToken; in.nval.toDouble } \n def readLine = bf.readLine\n \n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n \n def flush = out.flush\n}", "positive_code": [{"source_code": "import java.util\nimport java.util._\nimport java.lang._\nimport java.io._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val time = new Array[Int](n)\n val sumTimeA = new Array[Int](n)\n val sumTimeB = new Array[Int](n)\n time(0) = nextInt\n sumTimeA(0) = time(0)\n for (i <- 1 until n) {\n time(i) = nextInt\n sumTimeA(i) = sumTimeA(i - 1) + time(i)\n }\n sumTimeB(0) = time(n - 1)\n for (i <- 1 until n) {\n sumTimeB(i) = sumTimeB(i - 1) + time(n - i - 1)\n }\n var aInd = 0\n var bInd = 0\n var aNum = 0\n var bNum = 0\n while (aNum + bNum != n) {\n if (sumTimeA(aInd) < sumTimeB(bInd)) {\n aInd += 1\n aNum += 1\n } else if (sumTimeA(aInd) > sumTimeB(bInd)) {\n bInd += 1\n bNum += 1\n } else {\n if (aInd == n - bInd - 1) {\n aNum += 1\n } else {\n aInd += 1\n bInd += 1\n aNum += 1\n bNum += 1\n }\n }\n }\n out.println(aNum + \" \" + bNum)\n\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "object P6C {\n def main(args : Array[String]) {\n val n = readLine.toInt\n var t = readLine.split(' ').map{_.toInt}.toVector\n var (a, b) = (0, 0)\n while (t.size > 2) (t.head, t.last) match {\n case (p, q) if p < q => {t = t.init.tail :+ (q - p); a = a + 1}\n case (p, q) if p > q => {t = (p - q) +: t.init.tail; b = b + 1}\n case _ => {t = t.init.tail; a = a + 1; b = b + 1}\n }\n a = a + 1\n if (t.size == 2) b = b + 1\n println(a + \" \" + b)\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val count = (1 to n).foldLeft(0, 0, 0){\n case((lIndex, lSum, rSum), _) if lSum <= rSum =>\n (lIndex + 1, lSum + data(lIndex), rSum)\n case((lIndex, lSum, rSum), i) =>\n (lIndex, lSum, rSum + data(n - i + lIndex))\n }._1\n println(s\"$count ${n - count}\")\n}"}, {"source_code": "import java.util.Scanner\n\nobject CAliceBob extends App {\n\n val scanner = new Scanner(System.in)\n\n val n = scanner.nextInt()\n\n val in = for (x <- 0 until n) yield scanner.next().toInt\n\n var a = 0\n var b = in.size - 1\n var as = 0\n var bs = 0\n\n while(a <= b) {\n if (as <= bs) {\n as += in(a)\n a += 1\n } else {\n bs += in(b)\n b -= 1\n }\n }\n\n println(a + \" \" + (in.size - a))\n\n}\n"}, {"source_code": "object C6 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n var arr = readInts(n)\n var a, x, y = 0\n var b = n-1\n while(a <= b) {\n if(x <= y) {\n x += arr(a)\n a += 1\n } else {\n y += arr(b)\n b -= 1\n }\n }\n println(s\"$a ${n-a}\")\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val count = (1 to n).foldLeft(-1, 0, 0){\n case((lIndex, lSum, rSum), _) if lSum <= rSum => (lIndex + 1, lSum + data(lIndex + 1), rSum)\n case((lIndex, lSum, rSum), _) => (lIndex, lSum, rSum + data(n - 1 - lIndex))\n }._1 + 1\n println(s\"$count ${n - count}\")\n}"}, {"source_code": "object P5E {\n def main(args: Array[String]) {\n val n = readLine.toInt\n val a = readLine split ' ' map {_.toInt}\n var answer = 0L\n for (a <- Array(a, a.reverse)) {\n case class Node(x : Int, i : Int, r : Int)\n val s = new java.util.ArrayDeque[Node]\n for (i <- 0 to n - 1) {\n val x = a(i)\n while (!s.isEmpty && s.getLast.x < x) s.removeLast\n val r = if (!s.isEmpty && s.getLast.x == x) s.getLast.r else 0\n s addLast Node(x, i, r + 1)\n }\n for (i <- 0 to n - 1) yield {\n while (!s.isEmpty && s.getFirst.i <= i) s.removeFirst\n val x = a(i)\n while (!s.isEmpty && s.getLast.x < x) {\n s.removeLast\n answer = answer + 2\n }\n val r = if (!s.isEmpty && s.getLast.x == x) s.getLast.r else 0\n answer = answer + (r min s.size)\n s addLast Node(x, n, r + 1)\n }\n }\n val v = {\n val a1 = a.max\n val z1 = a count {_ == a1}\n if (z1 > 1) z1.toLong * (z1 - 1) >>> 1 else {\n val b = a filter {_ != a1}\n val a2 = b.max\n b count {_ == a2}\n }\n }\n println((answer >>> 1) - v)\n }\n}\n"}], "src_uid": "8f0172f742b058f5905c0a02d79000dc"} {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _644C extends CodeForcesApp {\n override def apply(io: IO) = {\n val ans = io[Iterable[String]]\n .map(s => s.splitAt(s.indexOf('/', 7).nonNegative getOrElse s.length))\n .toMultiMap.mapValues(_.toSet).invert.values.filter(_.size > 1).toVector\n (io += ans.size).appendLine()\n ans.foreach(group => (io ++= group).appendLine())\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates: Traversable[A] = {\n val elems = mutable.Set.empty[A]\n t collect {case i if !elems.add(i) => i}\n }\n def zipWith[B](f: A => B): Traversable[(A, B)] = t map {i => i -> f(i)}\n def mapTo[B](f: A => B): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class IndexedSeqExtensions[A](val s: IndexedSeq[A]) extends AnyVal {\n def withOffset(offset: Int): IndexedSeq[A] = Iterator.fill(offset)(null.asInstanceOf[A]) ++: s\n }\n implicit class PairsExtensions[A, B](val t: Traversable[(A, B)]) extends AnyVal {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap: Map[A, Traversable[B]] = t.groupBy(_._1).mapValues(_.map(_._2))\n def swap: Traversable[(B, A)] = t.map(_.swap)\n }\n implicit class MapExtensions[K, V](val m: Map[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.swap.toMultiMap.mapValues(_.toSet)\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def ^^(i: Int): A = if (i == 0) n.one else {\n val h = x ^^ (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x) //e.g. students.indexOf(\"Greg\").nonNegative\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default\n }\n def memoize[I] = new {\n def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n val mod: Int = (1e9 + 7).toInt\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.{Growable, CanBuild}\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] with Growable[Any] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit parse: IO.Parser[A]): A = parse.apply(this)\n def apply[C[_], A: IO.Parser](n: Int)(implicit builder: CanBuild[A, C[A]]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n override def +=(obj: Any) = {\n if (isNewLine) isNewLine = false else print(separator)\n print(obj)\n this\n }\n def ++=(t: TraversableOnce[_], ifEmpty: => Any): this.type = if (t.isEmpty) this += ifEmpty else this ++= t\n\n def appendLine(): this.type = {\n println()\n isNewLine = true\n this\n }\n\n override def clear() = flush()\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\n\nobject IO {\n class Parser[A](val apply: IO => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n }\n implicit def collection[C[_], A: Parser](implicit cbf: CanBuild[A, C[A]]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n", "positive_code": [{"source_code": "object Solution{\n import scala.io.StdIn\n val url = \"(http://[\\\\w\\\\.]+)(/?.*)\".r\n\n def main(args: Array[String]) {\n val n = StdIn.readInt()\n val groups = Vector.fill(n)(StdIn.readLine() match {\n case url(host, path) => (host, path)\n }).groupBy(_._1)\n .mapValues(_.map(_._2).toSet)\n .toVector\n .map(_.swap)\n .groupBy(_._1)\n .values\n .map(_ map (_._2))\n .filter(_.size > 1)\n\n println(groups.size)\n groups.foreach(srvs => println(srvs.mkString(\" \")))\n }\n\n}"}, {"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n\n case class Url(host: String, path: String)\n\n val urls = Array.fill(n) {\n val s = readLine.drop(7)\n val break = s.indexOf('/')\n if (break == -1) Url(s, \"\") else Url(s.take(break), s.drop(break))\n }.distinct\n\n val pathsByHosts = urls.groupBy(_.host).map {\n case (host, hotsUrls) => host -> hotsUrls.map(_.path).sorted.mkString(\" \")\n }\n\n val hostsByPathSets = pathsByHosts.groupBy(_._2).map {\n case (paths, pathHosts) => pathHosts.keys\n }.filter(_.size > 1)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(hostsByPathSets.size)\n hostsByPathSets.foreach(hs => println(hs.map(\"http://\" + _).mkString(\" \")))\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "9b35f7df9e21162858a8fac8ee2837a4"} {"source_code": "import scala.collection._\n\nobject Checkposts extends App {\n\tval (n, cost, m) = (readLine.toInt, readLine.split(' ').map(_.toInt), readLine.toInt)\n\tval (g, h) = (Array.fill[List[Int]](n)(Nil), Array.fill[List[Int]](n)(Nil))\n\n\tfor (i <- 0 until m) {\n\t\tval Array(u, v) = readLine.split(' ').map(_.toInt).map(_-1)\n\t\tg(u) ::= v\n\t\th(v) ::= u\n\t}\n\n\tval (cs, s, seen) = (Array.fill(n)(-1), mutable.Stack[Int](), Array.fill(n)(false))\n\tvar nc = 0\n\n\tdef dfs0 (x : Int) : Unit = {\n\t\tif (!seen(x)) {\n\t\t\tseen(x) = true\n\t\t\tg(x).foreach(dfs0)\n\t\t\ts.push(x)\n\t\t}\n\t}\n\n\tdef dfs1 (x : Int) : Unit = {\n\t\tif (cs(x) == -1) {\n\t\t\tcs(x) = nc\n\t\t\th(x).foreach(dfs1)\n\t\t}\n\t}\n\n\t(0 until n).foreach(dfs0)\n\tfor (x <- s) if(cs(x) == -1) {\n\t\tdfs1(x)\n\t\tnc += 1\n\t}\n\n\tval (best, ways) = (Array.fill(n)(1234567890), Array.fill(n)(0))\n\tfor (x <- 0 until n) {\n\t\tval c = cs(x)\n\t\tif (cost(x) < best(c)) {\n\t\t\tbest(c) = cost(x)\n\t\t\tways(c) = 1\n\t\t} else if (cost(x) == best(cs(x))) {\n\t\t\tways(c) += 1\n\t\t}\n\t}\n\n\tvar (ans_best, ans_ways) = (0l, 1l)\n\tfor (c <- 0 until nc) {\n\t\tans_best += best(c)\n\t\tans_ways = ans_ways * ways(c) % 1000000007\n\t}\n\n\tprintln(ans_best + \" \" + ans_ways)\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.PriorityQueue\nimport scala.collection.mutable.Stack\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject C extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): List[Long] = {\n val N = sc.nextInt\n val C: Array[Int] = Array.fill(N)(sc.nextInt) // costs of building CPs\n val M = sc.nextInt\n val e, re = Array.fill[List[Int]](N)(Nil)\n for (_ <- 0 until M) {\n val u, v = sc.nextInt - 1\n e(u) ::= v\n re(v) ::= u\n }\n sc.close\n\n val history = new Stack[Int]\n val used: Array[Boolean] = Array.fill(N)(false)\n val scc: Array[Int] = Array.fill(N)(-1)\n val lowestCost: Array[Int] = Array.fill(N)(Int.MaxValue)\n val numLowestCostCP: Array[Long] = Array.fill(N)(0)\n\n def dfs(v: Int): Unit = {\n if (used(v)) ()\n else {\n used(v) = true\n e(v) foreach dfs\n history.push(v)\n }\n }\n\n def rdfs(k: Int)(v: Int): Unit = {\n if (scc(v) >= 0) ()\n else {\n scc(v) = k\n\n // update costs and CPs\n val cost = C(v)\n if (cost < lowestCost(k)) {\n lowestCost(k) = cost\n numLowestCostCP(k) = 1\n }\n else if (cost == lowestCost(k)) {\n numLowestCostCP(k) += 1\n }\n\n re(v) foreach rdfs(k)\n }\n }\n\n\n\n 0 until N foreach { v => dfs(v) }\n var i, k = 0\n while (i < N) {\n val v = history.pop\n if (scc(v) < 0) {\n rdfs(k)(v)\n k += 1\n }\n i += 1\n }\n\n i = 0\n var a: Long = 0\n var b: Long = 1\n while (i < k) {\n a += lowestCost(i)\n b = b * numLowestCostCP(i) % 1000000007\n i += 1\n }\n\n List(a, b)\n }\n\n out.println(solve.mkString(\" \"))\n out.flush\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.PriorityQueue\nimport scala.collection.mutable.Stack\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject C extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): List[Long] = {\n val N = sc.nextInt\n val C: Array[Int] = Array.fill(N)(sc.nextInt) // costs of building CPs\n val M = sc.nextInt\n val e = Array.fill(N)(new ArrayBuffer[Int])\n val re = Array.fill(N)(new ArrayBuffer[Int])\n for (_ <- 0 until M) {\n val u, v = sc.nextInt - 1\n e(u) += v\n re(v) += u\n }\n sc.close\n\n val history = new Stack[Int]\n val used: Array[Boolean] = Array.fill(N)(false)\n val scc: Array[Int] = Array.fill(N)(-1)\n val lowestCost: Array[Int] = Array.fill(N)(Int.MaxValue)\n val numLowestCostCP: Array[Long] = Array.fill(N)(0)\n\n def dfs(v: Int): Unit = {\n if (used(v)) ()\n else {\n used(v) = true\n e(v) foreach dfs\n history.push(v)\n }\n }\n\n def rdfs(k: Int)(v: Int): Unit = {\n if (scc(v) >= 0) ()\n else {\n scc(v) = k\n\n // update costs and CPs\n val cost = C(v)\n if (cost < lowestCost(k)) {\n lowestCost(k) = cost\n numLowestCostCP(k) = 1\n }\n else if (cost == lowestCost(k)) {\n numLowestCostCP(k) += 1\n }\n\n re(v) foreach rdfs(k)\n }\n }\n\n\n\n 0 until N foreach { v => dfs(v) }\n var i, k = 0\n while (i < N) {\n val v = history.pop\n if (scc(v) < 0) {\n rdfs(k)(v)\n k += 1\n }\n i += 1\n }\n\n i = 0\n var a: Long = 0\n var b: Long = 1\n while (i < k) {\n a += lowestCost(i)\n b = b * numLowestCostCP(i) % 1000000007\n i += 1\n }\n\n List(a, b)\n }\n\n out.println(solve.mkString(\" \"))\n out.flush\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.PriorityQueue\nimport scala.collection.mutable.Stack\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject C extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): List[Long] = {\n val N = sc.nextInt\n val C: Array[Int] = Array.fill(N)(sc.nextInt) // costs of building CPs\n val M = sc.nextInt\n val e, re = Array.fill[List[Int]](N)(Nil)\n for (_ <- 0 until M) {\n val u, v = sc.nextInt - 1\n e(u) ::= v\n re(v) ::= u\n }\n sc.close\n\n val history = new Stack[Int]\n val used: Array[Boolean] = Array.fill(N)(false)\n val lowestCost: Array[Int] = Array.fill(N)(Int.MaxValue)\n val numLowestCostCP: Array[Long] = Array.fill(N)(0)\n\n def dfs(v: Int): Unit = {\n if (used(v)) ()\n else {\n used(v) = true\n e(v) foreach dfs\n history.push(v)\n }\n }\n\n def rdfs(k: Int)(v: Int): Unit = {\n if (used(v)) ()\n else {\n used(v) = true\n\n // update costs and CPs\n val cost = C(v)\n if (cost < lowestCost(k)) {\n lowestCost(k) = cost\n numLowestCostCP(k) = 1\n }\n else if (cost == lowestCost(k)) {\n numLowestCostCP(k) += 1\n }\n\n re(v) foreach rdfs(k)\n }\n }\n\n\n\n 0 until N foreach { v => dfs(v) }\n Arrays.fill(used, false)\n var i, k = 0\n while (i < N) {\n val v = history.pop\n if (!used(v)) {\n rdfs(k)(v)\n k += 1\n }\n i += 1\n }\n\n i = 0\n var a: Long = 0\n var b: Long = 1\n while (i < k) {\n a += lowestCost(i)\n b = b * numLowestCostCP(i) % 1000000007\n i += 1\n }\n\n List(a, b)\n }\n\n out.println(solve.mkString(\" \"))\n out.flush\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.PriorityQueue\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject C extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): List[Long] = {\n val N = sc.nextInt\n val C: Array[Long] = Array.fill(N)(sc.nextLong) // costs of building CPs\n val E0 = Array.fill(N)(new ListBuffer[Int])\n val RE0 = Array.fill(N)(new ListBuffer[Int])\n val M = sc.nextInt\n for (_ <- 0 until M) {\n val u, v = sc.nextInt - 1\n E0(u) += v\n RE0(v) += u\n }\n val E: Array[List[Int]] = E0.map(_.toList)\n val RE: Array[List[Int]] = RE0.map(_.toList) \n\n val history = new ListBuffer[Int]\n val used = Array.fill(N)(false)\n\n def dfs(v: Int): Unit = {\n used(v) = true\n E(v).filterNot(used) foreach { u => dfs(u) }\n history += v\n }\n\n def rdfs(v: Int): List[Long] = {\n used(v) = true\n C(v) :: RE(v).filterNot(used).flatMap(rdfs(_))\n }\n\n 0 until N foreach { v =>\n if(!used(v)) dfs(v)\n }\n java.util.Arrays.fill(used, false)\n val clusters = new ListBuffer[List[Long]]\n history.toList.reverse.foreach { v =>\n if (!used(v)) clusters += rdfs(v)\n }\n\n val clst = clusters.toList\n val minCost = clst.map(_.min).sum\n\n @inline\n def numMinCostCP(js: List[Long]): Int = {\n val min = js.min\n js.count(_ == min)\n }\n\n val numWays = clst.map(numMinCostCP).foldLeft(1) { (a, b) =>\n a * b % 1000000007 \n }\n\n List(minCost, numWays)\n }\n\n out.println(solve.mkString(\" \"))\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.PriorityQueue\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject C extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): List[Long] = {\n val N = sc.nextInt\n val C: Array[Long] = Array.fill(N)(sc.nextLong) // costs of building CPs\n val E0 = Array.fill(N)(new ListBuffer[Int])\n val RE0 = Array.fill(N)(new ListBuffer[Int])\n val M = sc.nextInt\n for (_ <- 0 until M) {\n val u, v = sc.nextInt - 1\n E0(u) += v\n RE0(v) += u\n }\n val E: Array[List[Int]] = E0.map(_.toList)\n val RE: Array[List[Int]] = RE0.map(_.toList) \n\n val history = new ListBuffer[Int]\n val used = Array.fill(N)(false)\n val sccs = Array.fill(N)(-1)\n\n def dfs(v: Int): Unit = {\n used(v) = true\n E(v).filterNot(used) foreach { u => dfs(u) }\n history += v\n }\n\n def rdfs(v: Int, k: Int): Unit = {\n used(v) = true\n sccs(v) = k\n RE(v).filterNot(used).foreach { u =>\n if (!used(u)) rdfs(u, k)\n }\n }\n\n 0 until N foreach { v =>\n if(!used(v)) dfs(v)\n }\n java.util.Arrays.fill(used, false)\n val buf = new ListBuffer[List[Long]]\n\n var k = 0\n history.toList.reverse.foreach { v =>\n if (!used(v)) {\n rdfs(v, k)\n k += 1\n }\n }\n\n val clusters: List[List[Long]] = List.range(0, N).groupBy(sccs(_))\n .map { (pair: (Int, List[Int])) =>\n pair._2.map(C(_))\n }.toList\n\n val minCost = clusters.map(_.min).sum\n\n def numMinCostCP(js: List[Long]): Int = {\n val m = js.min\n js.count((x: Long) => x == m)\n }\n\n val numMinCostCPWay: Long = clusters.map(numMinCostCP).foldLeft(1L) { (a, b) => a * b % 1000000007 }\n\n List(minCost)\n }\n\n out.println(solve.mkString(\" \"))\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.PriorityQueue\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject C extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): List[Long] = {\n val N = sc.nextInt\n val C: Array[Int] = Array.fill(N)(sc.nextInt) // costs of building CPs\n val E0 = Array.fill(N)(new ListBuffer[Int])\n val RE0 = Array.fill(N)(new ListBuffer[Int])\n val M = sc.nextInt\n for (_ <- 0 until M) {\n val u, v = sc.nextInt - 1\n E0(u) += v\n RE0(v) += u\n }\n val E: Array[List[Int]] = E0.map(_.toList)\n val RE: Array[List[Int]] = RE0.map(_.toList)\n\n val history = new ListBuffer[Int]\n val used: Array[Boolean] = Array.fill(N)(false)\n val scc: Array[Int] = Array.fill(N)(-1)\n val lowestCost: Array[Int] = Array.fill(N)(Int.MaxValue)\n val numLowestCostCP: Array[Long] = Array.fill(N)(0)\n\n def dfs(v: Int): Unit = {\n if (used(v)) ()\n else {\n used(v) = true\n E(v) foreach { u => dfs(u) }\n history += v\n }\n }\n\n @inline\n def updateCostAndCP(v: Int, k: Int): Unit = {\n val cost = C(v)\n if (cost < lowestCost(k)) {\n lowestCost(k) = cost\n numLowestCostCP(k) = 1\n }\n else if (cost == lowestCost(k)) {\n numLowestCostCP(k) += 1\n }\n }\n\n def rdfs(v: Int, k: Int): Unit = {\n if (scc(v) >= 0) ()\n else {\n scc(v) = k\n updateCostAndCP(v, k)\n RE(v) foreach { u => rdfs(u, k) }\n }\n }\n\n 0 until N foreach { v => dfs(v) }\n var k = 0\n history.toList.reverse.foreach { v =>\n if (scc(v) < 0) {\n rdfs(v, k)\n k += 1\n }\n }\n val minCost = lowestCost.take(k).sum\n val mulModP: (Long, Long) => Long = (a, b) => a * b % 1000000007\n val numMinCostCPWays = numLowestCostCP.take(k).foldLeft(1L)(mulModP)\n\n List(minCost, numMinCostCPWays)\n }\n\n out.println(solve.mkString(\" \"))\n out.close\n}\n"}], "src_uid": "ee576fd64305ab99b2e0442aad6199d8"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n println((1 to n).map{ _ =>\n val Array(l, r) = in.next().split(' ').map(_.toLong)\n var nL = l\n while ((nL | (nL + 1)) <= r) {\n nL |= nL + 1\n }\n nL\n }.mkString(\"\\n\"))\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n for (i <- 0 until n) {\n val Array(l, r) = readLongs(2)\n var bit = 1L << 62\n var x = 0L\n var diff = false\n while (bit > 0) {\n if (!diff) {\n if ((l & bit) > 0 && (r & bit) > 0) x += bit\n if ((l & bit) != (r & bit)) diff = true\n if (diff && (r - x + 1) == bit * 2) x += bit\n } else x += bit\n bit >>= 1\n }\n println(x)\n }\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n println((1 to n).map{ _ =>\n val Array(l, r) = in.next().split(' ').map(_.toLong)\n val lStr = l.toBinaryString\n val rStr = r.toBinaryString\n val res = if (lStr.length < rStr.length)\n \"1\" * (rStr.length - 1)\n else {\n rStr.zip(lStr).foldLeft(((List.empty[Char], false))) {\n case ((list, true), (f, s)) => ('1' :: list, true)\n case ((list, false), (f, s)) if f == s => (f :: list, false)\n case ((list, false), (f, s)) => (f :: list, true)\n }._1.reverse.mkString\n }\n java.lang.Long.parseLong(res, 2)\n }.mkString(\"\\n\"))\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n println((1 to n).map{ _ =>\n val Array(l, r) = in.next().split(' ').map(_.toLong)\n val lStr = l.toBinaryString\n val rStr = r.toBinaryString\n val res = if (lStr.length < rStr.length) {\n val str = \"1\" * rStr.length\n if (rStr == str) str else str.tail\n }\n else {\n rStr.zip(lStr).foldLeft((List.empty[Char], false)) {\n case ((list, true), (f, s)) => ('1' :: list, true)\n case ((list, false), (f, s)) if f == s => (f :: list, false)\n case ((list, false), (f, s)) => (f :: list, true)\n }._1.reverse.mkString\n }\n java.lang.Long.parseLong(res, 2)\n }.mkString(\"\\n\"))\n}"}], "src_uid": "644b8f95b66b7e4cb39af552ec518b3f"} {"source_code": "import scala.collection.immutable.TreeSet\n\nobject SquaresAndNotSquares {\n def main(args: Array[String]): Unit = {\n val R = scala.io.Source.stdin.bufferedReader()\n val N = R.readLine().toInt\n val A = R.readLine().split(\" \").map(s => s.toInt)\n\n def solve(): Long = {\n val squares = 0.to(40000).map(x => x * x).to[TreeSet]\n val squaredCount = A.count(x => squares.contains(x))\n\n def distanceToNearestSquare(x: Int): Long = {\n if (squares.contains(x)) 0\n else {\n val lower = squares.to(x).lastKey\n var higher = squares.from(x).firstKey\n\n Math.min(x - lower, higher - x)\n }\n }\n\n if (squaredCount >= N / 2) A.filter(x => squares.contains(x)).map(x => if (x == 0) 2 else 1).sorted.take(squaredCount - (N / 2)).sum\n else A.filter(x => !squares.contains(x)).map(distanceToNearestSquare).sorted.take((N / 2) - squaredCount).sum\n }\n\n println(solve())\n }\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nimport scala.collection.immutable.TreeSet\n\nobject SquaresAndNotSquares {\n def main(args: Array[String]): Unit = {\n val R = scala.io.Source.stdin.bufferedReader()\n val N = R.readLine().toInt\n val A = R.readLine().split(\" \").map(s => s.toInt)\n\n def solve(): Long = {\n val squares = 0.to(40000).map(x => x * x).to[TreeSet]\n\n val squared = A.map(x => squares.contains(x))\n val squaredCount = squared.count(_ == true)\n\n def distanceToNearestSquare(x: Int): Long = {\n if (squares.contains(x)) 0\n else {\n val lower = squares.to(x).lastKey\n var higher = squares.from(x).firstKey\n\n Math.min(x - lower, higher - x)\n }\n }\n\n if (squaredCount >= N / 2) A.filter(x => squares.contains(x)).map(x => if (x == 0) 2 else 1).sorted.take(squaredCount - (N / 2)).sum\n else {\n A.filter(x => !squares.contains(x)).map(distanceToNearestSquare).sorted.take((N / 2) - squaredCount).sum\n }\n }\n\n println(solve())\n }\n}\n"}, {"source_code": "import scala.collection.immutable.TreeSet\n\nobject SquaresAndNotSquares {\n def main(args: Array[String]): Unit = {\n val R = scala.io.Source.stdin.bufferedReader()\n val N = R.readLine().toInt\n val A = R.readLine().split(\" \").map(s => s.toInt)\n\n def solve(): Long = {\n val squares = 0.to(40000).map(x => x * x).to[TreeSet]\n val squaredCount = A.map(x => squares.contains(x)).count(_ == true)\n\n def distanceToNearestSquare(x: Int): Long = {\n if (squares.contains(x)) 0\n else {\n val lower = squares.to(x).lastKey\n var higher = squares.from(x).firstKey\n\n Math.min(x - lower, higher - x)\n }\n }\n\n if (squaredCount >= N / 2) A.filter(x => squares.contains(x)).map(x => if (x == 0) 2 else 1).sorted.take(squaredCount - (N / 2)).sum\n else A.filter(x => !squares.contains(x)).map(distanceToNearestSquare).sorted.take((N / 2) - squaredCount).sum\n }\n\n println(solve())\n }\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nimport scala.collection.immutable.TreeSet\n\nobject SquaresAndNotSquares {\n def main(args: Array[String]): Unit = {\n val R = scala.io.Source.stdin.bufferedReader()\n val N = R.readLine().toInt\n val A = R.readLine().split(\" \").map(s => s.toInt)\n\n def solve() = {\n val squares = 0.to(40000).map(x => x * x).to[TreeSet]\n\n val squared = A.map(x => squares.contains(x))\n val squaredCount = squared.count(_ == true)\n\n def distanceToNearestSquare(x: Int) = {\n if (squares.contains(x)) 0\n else {\n val lower = squares.to(x).lastKey\n var higher = squares.from(x).firstKey\n\n Math.min(x - lower, higher - x)\n }\n }\n\n if (squaredCount >= N / 2) A.filter(x => squares.contains(x)).map(x => if (x == 0) 2 else 1).sorted.take(squaredCount - (N / 2)).sum\n else {\n A.filter(x => !squares.contains(x)).map(distanceToNearestSquare).sorted.take((N / 2) - squaredCount).sum\n }\n }\n\n println(solve())\n }\n}\n"}], "src_uid": "b303d67dfb4e2f946b06a41b0a742099"} {"source_code": "//package codeforces.contests._1426\n\nobject SymmetricMatrix {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(n, m) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val result = (1 to n).map { _ =>\n val row0, row1 = io.StdIn.readLine.split(\" \").map(_.toInt)\n row0(1) == row1(0)\n }.exists(identity) && m % 2 == 0\n\n println(if (result) \"YES\" else \"NO\")\n }\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val tiles = (0 until n).foldLeft(0) {\n case (ts, _) =>\n val Array(a, b) = readLine().split(\" \").map(_.toInt)\n val Array(c, d) = readLine().split(\" \").map(_.toInt)\n\n if (b == c) ts + 1 else ts\n }\n\n val ans = if (m % 2 == 0 && tiles >= 1) \"YES\" else \"NO\"\n\n println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val tiles = (0 until n).foldLeft(0) {\n case (ts, _) =>\n val Array(a, b) = readLine().split(\" \").map(_.toInt)\n val Array(c, d) = readLine().split(\" \").map(_.toInt)\n\n if (a == d && b == c) ts + 1 else ts\n }\n\n val ans = if (m % 2 == 0 && tiles >= 1) \"YES\" else \"NO\"\n\n println(ans)\n }\n}\n"}], "src_uid": "f46f6fa28d0a7023da3bad0d222ce393"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt)\n val r = a.grouped(k).toArray.transpose\n val sums = r.map(_.sum)\n println(sums.zipWithIndex.minBy(_._1)._2 + 1)\n }\n}", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n println((0 until k).foldLeft((Int.MaxValue, 0)) {\n case ((acc, index), i) =>\n val value = (i until n by k).foldLeft(0) {\n case(acc, el) => acc + data(el)\n }\n if (value < acc)\n (value, i)\n else\n (acc, index)\n }._2 + 1)\n}\n"}, {"source_code": "object B extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val as = readInts(n)\n val bs = Array.fill(k)(0)\n \n for (i <- as.indices) bs(i % k) += as(i)\n\n val best = bs.min\n val ans = bs.indexOf(best) + 1\n \n println(ans)\n}"}, {"source_code": "import java.util.Scanner\n\nobject DimaAndTodolist extends App {\n val scan = new Scanner(System.in)\n val n = scan.nextInt\n val k = scan.nextInt\n\n val s = {\n for(i <- 0 until n) yield (i % k, scan.nextInt)\n }.toArray.groupBy(_._1)\n\n val ans = s.map(kv =>\n (kv._1, kv._2.map(_._2).reduce(_ + _))).minBy(x => (x._2, x._1))._1 + 1\n\n\n println(ans)\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n println((0 until k).foldLeft((Int.MaxValue, -1)) {\n case ((acc, index), i) =>\n val value = data.drop(i).grouped(k).map(_.head).sum\n if (value <= acc)\n (value, i)\n else\n (acc, index)\n }._2 + 1)\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject DimaAndTodolist extends App {\n val scan = new Scanner(System.in)\n val n = scan.nextInt\n val k = scan.nextInt\n\n val s = {\n for(i <- 0 until n) yield (i % k, scan.nextInt)\n }.groupBy(_._1)\n\n val ans = s.map(kv =>\n (kv._1, kv._2.map(_._2).reduce(_ + _))).min._1 + 1\n\n println(ans)\n}"}, {"source_code": "import java.util.Scanner\n\nobject DimaAndTodolist extends App {\n val scan = new Scanner(System.in)\n val n = scan.nextInt\n val k = scan.nextInt\n\n val s = {\n for(i <- 0 until n) yield (i % k, scan.nextInt)\n }.groupBy(_._1)\n\n val ans = s.map(kv =>\n (kv._1, kv._2.map(_._2).reduce(_ + _))).minBy(_._2)._1 + 1\n\n\n println(ans)\n}"}], "src_uid": "646cec22d98636447038e61e7dfb9db3"} {"source_code": "import java.util\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n\n object BIT {\n\n def query(t: Array[Long], r: Int, acc: Long = 0): Long =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Long], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Long], i: Int, delta: Long): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(src: Array[Long]): Array[Long] = {\n val t = Array.fill(src.length) { 0L }\n for (i <- src.indices) update(t, i, src(i))\n t\n }\n\n }\n\n val Array(n) = readInts(1)\n val as = readLongs(n)\n val ps = readInts(n).map(_ - 1)\n val right = Array.fill(n + 1){ -1 }\n\n val bit = BIT(as)\n\n val left = new util.TreeSet[Int]\n left.add(0)\n right(0) = n - 1\n\n val max = new util.TreeMap[Long, Int]\n\n def incMax(x: Long) = {\n if (max.containsKey(x)) max.put(x, max.get(x) + 1)\n else max.put(x, 1)\n }\n\n def decMax(x: Long) = {\n max.put(x, max.get(x) - 1)\n if (max.get(x) == 0) max.remove(x)\n }\n\n incMax(as.sum)\n\n var res = Array.ofDim[Long](n)\n\n for (i <- 0 until n) {\n val p = ps(i)\n val l = left.floor(p)\n val r = right(l)\n //println(l, r)\n val sum = BIT.rangeQuery(bit, l, r)\n decMax(sum)\n val lSum = BIT.rangeQuery(bit, l, p - 1)\n incMax(lSum)\n val rSum = BIT.rangeQuery(bit, p + 1, r)\n incMax(rSum)\n //println(sum, lSum, rSum)\n right(l) = p - 1\n left.add(p + 1)\n right(p + 1) = r\n res(i) = max.lastKey\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\"\\n\"))\n\n Console.flush\n}\n", "positive_code": [{"source_code": "import java.util\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n\n class BIT(src: Array[Long]) {\n\n private val t = Array.fill(src.length) { 0L }\n\n for (i <- src.indices) update(i, src(i))\n\n def query(r: Int, acc: Long = 0): Long =\n if (r < 0) acc else query((r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(l: Int, r: Int) = query(r) - query(l - 1)\n\n def update(i: Int, delta: Long): Unit =\n if (i < t.length) {\n t(i) += delta\n update(i | (i + 1), delta)\n }\n\n }\n\n val Array(n) = readInts(1)\n val as = readLongs(n)\n val ps = readInts(n).map(_ - 1)\n val right = Array.fill(n + 1){ -1 }\n\n val bit = new BIT(as)\n\n val left = new util.TreeSet[Int]\n left.add(0)\n right(0) = n - 1\n\n val max = new util.TreeMap[Long, Int]\n\n def incMax(x: Long) = {\n if (max.containsKey(x)) max.put(x, max.get(x) + 1)\n else max.put(x, 1)\n }\n\n def decMax(x: Long) = {\n max.put(x, max.get(x) - 1)\n if (max.get(x) == 0) max.remove(x)\n }\n\n incMax(as.sum)\n\n var res = Array.ofDim[Long](n)\n\n for (i <- 0 until n) {\n\n val p = ps(i)\n val l = left.floor(p)\n val r = right(l)\n\n val sum = bit.rangeQuery(l, r)\n decMax(sum)\n\n val lSum = bit.rangeQuery(l, p - 1)\n incMax(lSum)\n\n val rSum = bit.rangeQuery(p + 1, r)\n incMax(rSum)\n\n right(l) = p - 1\n left.add(p + 1)\n right(p + 1) = r\n res(i) = max.lastKey\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\"\\n\"))\n\n Console.flush\n}\n"}, {"source_code": "object _722C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n = read[Int]\n val elements = read[Vector, Long](n)\n val destroyOrder = read[Vector, Int](n).map(_ - 1)\n val prefixSum = elements.scanLeft(0L)(_ + _)\n\n def sum(from: Int, until: Int): Long = prefixSum(until) - prefixSum(from)\n\n val invalids = new java.util.TreeSet[Int]\n val counts = new java.util.TreeMap[Long, Int]\n\n def add(l: Int, r: Int) = {\n val s = sum(l, r)\n val x = Option(counts.get(s)).getOrElse(0)\n counts.put(s, x + 1)\n //debug(\"add\", l, r, s, counts)\n }\n\n def remove(i: Int): Long = {\n val l = Option(invalids.floor(i)).map(_ + 1) getOrElse 0\n val r = Option(invalids.ceiling(i)) getOrElse n\n val s = sum(l, r)\n val c = counts.get(s)\n if (c == 1) counts.remove(s) else counts.put(s, c - 1)\n invalids.add(i)\n //debug(\"remove\", i, elements(i), l, r, s, c, counts, invalids)\n add(l, i)\n add(i+1, r)\n counts.lastKey()\n }\n\n add(0, n)\n writeAll(destroyOrder.map(remove))\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toInt)\n val queries = in.next().split(' ').map(_.toInt - 1)\n val sum = Array.ofDim[Long](n)\n val start = Array.fill[Int](n) {\n -1\n }\n val end = Array.fill[Int](n) {\n -1\n }\n var max = 0l\n val answer = queries.reverse.map { i =>\n val sumToRemove = List(\n if (i == 0 || start(i - 1) == -1) None else Some(sum(start(i - 1))),\n if (i == n - 1 || end(i + 1) == -1) None else Some(sum(i + 1))).flatten\n\n val startIndex = if (i == 0 || start(i - 1) == -1) i else start(i - 1)\n val endIndex = if (i == n - 1 || end(i + 1) == -1) i else end(i + 1)\n start(endIndex) = startIndex\n end(startIndex) = endIndex\n val nSum = line(i) + sumToRemove.sum\n sum(startIndex) = nSum\n max = Math.max(nSum, max)\n max\n }\n println(answer.reverse.tail.mkString(\"\\n\"))\n println(0)\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toInt)\n val queries = in.next().split(' ').map(_.toInt - 1)\n val sum = Array.ofDim[Long](n)\n val start = Array.fill[Int](n) {\n -1\n }\n val end = Array.fill[Int](n) {\n -1\n }\n var max = 0l\n val answer = queries.reverse.map { i =>\n val sumParts =\n (if (i == 0 || start(i - 1) == -1) 0 else sum(start(i - 1))) + \n (if (i == n - 1 || end(i + 1) == -1) 0 else sum(i + 1))\n\n val startIndex = if (i == 0 || start(i - 1) == -1) i else start(i - 1)\n val endIndex = if (i == n - 1 || end(i + 1) == -1) i else end(i + 1)\n start(endIndex) = startIndex\n end(startIndex) = endIndex\n val nSum = line(i) + sumParts\n sum(startIndex) = nSum\n max = Math.max(nSum, max)\n max\n }\n println(answer.reverse.tail.mkString(\"\\n\"))\n println(0)\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toInt)\n val queries = in.next().split(' ').map(_.toInt - 1)\n val sum = Array.ofDim[Int](n)\n val start = Array.fill[Int](n) {\n -1\n }\n val end = Array.fill[Int](n) {\n -1\n }\n var max = 0\n val answer = queries.reverse.map { i =>\n val sumToRemove = List(\n if (i == 0 || start(i - 1) == -1) None else Some(sum(start(i - 1))),\n if (i == n - 1 || end(i + 1) == -1) None else Some(sum(i + 1))).flatten\n\n val startIndex = if (i == 0 || start(i - 1) == -1) i else start(i - 1)\n val endIndex = if (i == n - 1 || end(i + 1) == -1) i else end(i + 1)\n start(endIndex) = startIndex\n end(startIndex) = endIndex\n val nSum = line(i) + sumToRemove.sum\n sum(startIndex) = nSum\n max = Math.max(nSum, max)\n max\n }\n println(answer.reverse.tail.mkString(\"\\n\"))\n println(0)\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toInt)\n val queries = in.next().split(' ').map(_.toInt - 1)\n val sum = Array.ofDim[Int](n)\n val start = Array.fill[Int](n) {\n -1\n }\n val end = Array.fill[Int](n) {\n -1\n }\n var max = 0l\n val answer = queries.reverse.map { i =>\n val sumToRemove = List(\n if (i == 0 || start(i - 1) == -1) None else Some(sum(start(i - 1))),\n if (i == n - 1 || end(i + 1) == -1) None else Some(sum(i + 1))).flatten\n\n val startIndex = if (i == 0 || start(i - 1) == -1) i else start(i - 1)\n val endIndex = if (i == n - 1 || end(i + 1) == -1) i else end(i + 1)\n start(endIndex) = startIndex\n end(startIndex) = endIndex\n val nSum = line(i) + sumToRemove.sum\n sum(startIndex) = nSum\n max = Math.max(nSum, max)\n max\n }\n println(answer.reverse.tail.mkString(\"\\n\"))\n println(0)\n}"}, {"source_code": "import scala.collection.mutable\n\nobject Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toInt)\n val queries = in.next().split(' ').map(_.toInt - 1)\n val sum = Array.ofDim[Int](n)\n val start = Array.fill[Int](n) {\n -1\n }\n val end = Array.fill[Int](n) {\n -1\n }\n val queue = mutable.PriorityQueue.empty[Int]\n var remove = Map.empty[Int, Int]\n val answer = queries.reverse.map { i =>\n val sumToRemove = List(\n if (i == 0 || start(i - 1) == -1) None else Some(sum(start(i - 1))),\n if (i == n - 1 || end(i + 1) == -1) None else Some(sum(i + 1))).flatten\n\n val startIndex = if (i == 0 || start(i - 1) == -1) i else start(i - 1)\n val endIndex = if (i == n - 1 || end(i + 1) == -1) i else end(i + 1)\n start(endIndex) = startIndex\n end(startIndex) = endIndex\n val nSum = line(i) + sumToRemove.sum\n sum(startIndex) = nSum\n\n sumToRemove.foreach { sum =>\n remove += (sum -> (remove.getOrElse(sum, 0) + 1))\n }\n queue.enqueue(-nSum)\n\n while (remove.getOrElse(queue.head, 0) != 0) {\n remove += (queue.head -> (remove(queue.head) - 1))\n }\n -queue.dequeue()\n }\n println(answer.reverse.tail.mkString(\"\\n\"))\n println(0)\n}"}], "src_uid": "0553ab01447ab88bee70d07c433f0654"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n val EPS = 1e-11\n def lt(x: Double, y: Double) = x < y - EPS\n def le(x: Double, y: Double) = x < y + EPS\n def gt(x: Double, y: Double) = x > y - EPS\n def ge(x: Double, y: Double) = x > y + EPS\n def eq(x: Double, y: Double) = abs(x - y) < EPS\n\n def solve(): Unit = {\n val N, M = ni()\n val A, B = na(N)\n val C = Array.ofDim[Int](2 * N)\n REP(N) { i =>\n C(2 * i) = A(i)\n C(2 * i + 1) = B((i + 1) % N)\n }\n\n// debug(C)\n\n val INF = 1e9 + 1\n// val INF = 100d // debug\n var l = 0d \n var r = INF\n\n def simulate(x: Double): Boolean = {\n// debug(s\"simulate($x)\")\n var fuel = x\n REP(C.length) { i =>\n fuel -= (M + fuel) / C(i)\n// debug(fuel.toString)\n if (lt(fuel, 0)) return false\n }\n true\n }\n\n REP(100) { _ =>\n val mid = (r + l) / 2\n if (simulate(mid)) r = mid\n else l = mid\n }\n\n if (r == INF) {\n out.println(-1)\n } else {\n out.println(f\"$r%.10f\")\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n", "positive_code": [{"source_code": "object CF499C extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve: Unit = {\n val n = in.nextInt // number of planets\n val m = in.nextInt.toDouble // weight of the payload\n val as = new Array[Double](n).map(_ => in.nextInt.toDouble) // number of tons which can be lifted off by one ton of fuel\n val bs = new Array[Double](n).map(_ => in.nextInt.toDouble) // number of tons which can be landed by one ton of fuel\n\n // fuel * factor = fuel + payload\n // <=> fuel = payload / (factor - 1), factor != 1\n\n if (Math.min(as.min, bs.min) <= 1) {\n out.println(-1) // Can't lift our fuel\n return\n }\n\n def calculateFuel(fuel: Double, planet: Int): Double = {\n val a = as(planet)\n val b = bs(planet)\n\n val fuelForLanding = (m + fuel) / (b - 1)\n val fuelForTakeOff = (m + fuel + fuelForLanding) / (a - 1)\n\n if (planet == 1)\n return fuelForTakeOff + fuelForLanding + fuel\n else\n return calculateFuel(fuelForTakeOff + fuelForLanding + fuel, planet - 1)\n }\n\n val fuelEarthLanding = m / (bs(0) - 1)\n val fuelBeforeEarthLanding = calculateFuel(fuelEarthLanding, n-1)\n val totalFuel = fuelBeforeEarthLanding + (m + fuelBeforeEarthLanding) / (as(0) - 1)\n\n out.println(totalFuel)\n }\n\n solve\n out.flush\n out.close\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Codeforces1011C {\n\n def getCoefficients(n: Int, a: Array[Int], b: Array[Int]): Seq[Int] = {\n val coefficients = new Array[Int](2 * n)\n for (i <- 0 until n) {\n coefficients(2 * i) = a(i)\n coefficients(2 * i + 1) = b((i + 1) % n)\n }\n coefficients\n }\n\n def getFuel(n: Int, m: Int, a: Array[Int], b: Array[Int]): BigDecimal = {\n val coefficients = getCoefficients(n, a, b)\n if (coefficients contains 1) return -1\n var totalFuels = BigDecimal.valueOf(0)\n for (coefficient <- coefficients.reverse) {\n totalFuels += (m + totalFuels) / (coefficient - 1)\n }\n totalFuels\n }\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n val m = StdIn.readInt()\n val a = StdIn.readLine.trim.split(\" \").map(_.toInt)\n val b = StdIn.readLine.trim.split(\" \").map(_.toInt)\n val fuel = getFuel(n, m, a, b)\n println(fuel)\n }\n}"}], "negative_code": [], "src_uid": "d9bd63e03bf51ed87ba73cd15e8ce58d"} {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val m = nextInt\n var prevColor = -1\n var flag = true\n for (i <- 0 until n) {\n val line = next.toCharArray\n val lineColor = line(0)\n for (j <- 1 until m ) {\n if (line(j) != lineColor) {\n flag = false\n }\n }\n if (lineColor == prevColor) {\n flag = false\n }\n prevColor = lineColor\n }\n if (flag) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val a = (1 to n).map(_ => readLine())\n val tr = a.map{ s =>\n val c = s(0)\n if (s.count(_ == c) == m) Some(c)\n else None\n }\n if (tr.count(_ == None) > 0) println(\"NO\")\n else if (tr.size != 1 && tr.sliding(2).count(t => t(0) == t(1)) > 0) println(\"NO\")\n else println(\"YES\")\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P016A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N, _ = sc.nextInt\n sc.nextLine\n val Flag = List.fill(N)(sc.nextLine.toList)\n val striped = Flag.forall(_.distinct.size == 1)\n val validColoring = Flag.transpose.head.sliding(2).forall {\n case List(x, y) => x != y\n case List(x) => true\n }\n val res = if (striped && validColoring) \"YES\"\n else \"NO\"\n out.println(res)\n out.close\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(m, n) = in.next().split(\" \").map(_.toInt)\n val data = Range(0, m).map(_ => in.next())\n if (data.exists(_.distinct.length > 1) || (m != 1 && data.sliding(2).exists(t => t.head.head == t.last.head)))\n println(\"NO\")\n else\n println(\"YES\")\n}"}, {"source_code": "\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 25 Jun 2016\n */\nobject A16 extends App {\n\n def solve() = {\n val Array(n, m) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val a: Array[Char] = Array.ofDim[Char](n)\n var b = true\n for (i <- 0 until n) {\n if (b) {\n val s: mutable.Set[Char] = mutable.Set.empty\n scala.io.StdIn.readLine().foreach(s += _)\n if (s.size != 1) {\n b = false\n } else {\n a(i) = s.head\n }\n }\n }\n a.sliding(2).foreach(arr => {\n if (b) {\n if (arr.length > 1 && arr(0) == arr(1)) {\n b = false\n }\n }\n })\n println(if (b) \"YES\" else \"NO\")\n }\n\n solve()\n\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(m, n) = in.next().split(\" \").map(_.toInt)\n val data = Range(0, m).map(_ => in.next())\n if (data.exists(_.length > 1) || data.sliding(2).exists(t => t.head.head == t.last.head))\n println(\"NO\")\n else\n println(\"YES\")\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(m, n) = in.next().split(\" \").map(_.toInt)\n val data = Range(0, m).map(_ => in.next())\n if (data.exists(_.distinct.length > 1) || data.sliding(2).exists(t => t.head.head == t.last.head))\n println(\"NO\")\n else\n println(\"YES\")\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(m, n) = in.next().split(\" \").map(_.toInt)\n val data = Range(0, m).map(_ => in.next())\n if (data.exists(_.distinct.length > 1) || data.sliding(2).forall(t => t.head.head != t.last.head))\n println(\"NO\")\n else\n println(\"YES\")\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val data = Range(0, m).map(_ => in.next())\n if (data.exists(_.length > 1) || data.sliding(2).exists(t => t.head.head == t.last.head))\n println(\"NO\")\n else\n println(\"YES\")\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val a = (1 to n).map(_ => readLine())\n val tr = a.map{ s =>\n val c = s(0)\n if (s.count(_ == c) == n) Some(c)\n else None\n }\n if (tr.count(_ == None) > 0) println(\"NO\")\n else if (tr.sliding(2).count(t => t(0) == t(1)) > 0) println(\"NO\")\n else println(\"YES\")\n }\n}"}], "src_uid": "80d3da5aba371f4d572ea928025c5bbd"} {"source_code": "object D extends App {\r\n import scala.collection.mutable.PriorityQueue\r\n\r\n type Talk = (Int, Int)\r\n\r\n def productiveMeeting(persons: IndexedSeq[Int]): List[Talk] = {\r\n val pq = PriorityQueue(persons.zipWithIndex: _*)\r\n\r\n @annotation.tailrec\r\n def go(talks: List[Talk]): List[Talk] =\r\n if (pq.length > 1) {\r\n val (s1, p1) = pq.dequeue()\r\n val (s2, p2) = pq.dequeue()\r\n\r\n if (s1 <= 0 || s2 <= 0) talks\r\n else {\r\n pq.enqueue((s1 - 1, p1), (s2 - 1, p2))\r\n go((p1, p2) :: talks)\r\n }\r\n } else talks\r\n\r\n go(List.empty[Talk])\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val pn = nextInts(n)\r\n\r\n val ts = productiveMeeting(pn)\r\n\r\n out.println(ts.length)\r\n ts.foreach { case (i, j) => out.println(s\"${i + 1} ${j + 1}\") }\r\n }\r\n\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(var social: Int, var cp: Int, var ind: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (social < that.social)\n return -1\n else if (social == that.social)\n return 0\n else\n return 1\n }\n }\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val heap = new PriorityQueue[(Int, Int)]\n //var ans = Vector[(Int, Int)]()\n val ans = new ArrayBuffer[(Int, Int)]\n var tmp = 0\n for (i <- 0 until n) {\n tmp = readInt()\n if (tmp > 0)\n heap.enqueue((tmp, i+1))\n }\n var p1 = (0, 0)\n var p2 = (0, 0)\n while (heap.size > 1) {\n p1 = heap.dequeue()\n p2 = heap.dequeue()\n //ans = ans :+ (p1._2, p2._2)\n ans.append((p1._2, p2._2))\n if (p1._1 > 1)\n heap.enqueue((p1._1-1, p1._2))\n if (p2._1 > 1)\n heap.enqueue((p2._1-1, p2._2))\n }\n writer.println(ans.size)\n ans.foreach(x => writer.println(x._1 + \" \" + x._2))\n }\n writer.flush()\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(var social: Int, var cp: Int, var ind: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (social < that.social)\n return -1\n else if (social == that.social)\n return 0\n else\n return 1\n }\n }\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val heap = new mutable.PriorityQueue[(Int, Int)]\n var ans = Vector[(Int, Int)]()\n var tmp = 0\n for (i <- 0 until n) {\n tmp = readInt()\n if (tmp > 0)\n heap.enqueue((tmp, i+1))\n }\n var p1 = (0, 0)\n var p2 = (0, 0)\n while (heap.size > 1) {\n p1 = heap.dequeue()\n p2 = heap.dequeue()\n ans = ans :+ (p1._2, p2._2)\n if (p1._1 > 1)\n heap.enqueue((p1._1-1, p1._2))\n if (p2._1 > 1)\n heap.enqueue((p2._1-1, p2._2))\n }\n writer.println(ans.size)\n ans.foreach(x => writer.println(x._1 + \" \" + x._2))\n }\n writer.flush()\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(var social: Int, var cp: Int, var ind: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (social < that.social)\n return -1\n else if (social == that.social)\n return 0\n else\n return 1\n }\n }\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val arr = new Array[myType](n)\n var tmp = 0\n for (i <- 0 until n) {\n tmp = readInt()\n arr(i) = myType(tmp, tmp, i+1)\n }\n quickSort(arr)\n var temp = 0\n var cnt = 0\n var po = 0\n var i = n-1\n while (i > po) {\n if (i > po && arr(i).cp == 0)\n i -= 1\n while (po < i && arr(po).cp == 0)\n po += 1\n tmp = i-1\n while (tmp >= po && arr(tmp).cp > 0 && arr(i).cp >0) {\n arr(tmp).cp -= 1\n arr(i).cp -= 1\n cnt += 1\n tmp -= 1\n }\n if (tmp > po && arr(tmp).cp == 0) {\n arr(tmp).cp = arr(po).cp\n po += 1\n }\n }\n writer.println(cnt)\n po = 0\n i = n-1\n while (i > po) {\n if (i > po && arr(i).social == 0)\n i -= 1\n while (po < i && arr(po).social == 0)\n po += 1\n tmp = i-1\n while (tmp >= po && arr(tmp).social > 0 && arr(i).social >0) {\n writer.println(arr(i).ind + \" \" + arr(tmp).ind)\n arr(tmp).social -= 1\n arr(i).social -= 1\n cnt += 1\n tmp -= 1\n }\n if (tmp > po && arr(tmp).social == 0) {\n temp = arr(tmp).ind\n arr(tmp).ind = arr(po).ind\n arr(po).ind = temp\n arr(tmp).social = arr(po).social\n po += 1\n }\n }\n }\n writer.flush()\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(var social: Int, var cp: Int, ind: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (social < that.social)\n return -1\n else if (social == that.social)\n return 0\n else\n return 1\n }\n }\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val arr = new Array[myType](n)\n var tmp = 0\n for (i <- 0 until n) {\n tmp = readInt()\n arr(i) = myType(tmp, tmp, i+1)\n }\n quickSort(arr)\n var cnt = 0\n var po = n-2\n for (i <- (0 until n).reverse) {\n if (i == po)\n po -= 1\n while (po >= 0 && arr(i).cp > 0 && arr(po).cp > 0) {\n tmp = min(arr(i).cp, arr(po).cp)\n arr(i).cp -= tmp\n arr(po).cp -= tmp\n cnt += tmp\n if (arr(po).cp == 0) {\n po -= 1\n }\n }\n }\n writer.println(cnt)\n po = n-2\n for (i <- (0 until n).reverse) {\n if (i == po)\n po -= 1\n while (po >= 0 && arr(i).social > 0 && arr(po).social > 0) {\n tmp = min(arr(i).social, arr(po).social)\n for (k <- 1 to tmp)\n writer.println(arr(po).ind + \" \" + arr(i).ind)\n arr(i).social -= tmp\n arr(po).social -= tmp\n cnt += tmp\n if (arr(po).social == 0) {\n po -= 1\n }\n }\n }\n\n }\n writer.flush()\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(var social: Int, var cp: Int, ind: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (social < that.social)\n return -1\n else if (social == that.social)\n return 0\n else\n return 1\n }\n }\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val arr = new Array[myType](n)\n var tmp = 0\n for (i <- 0 until n) {\n tmp = readInt()\n arr(i) = myType(tmp, tmp, i+1)\n }\n quickSort(arr)\n var cnt = 0\n var po = n-2\n for (i <- (0 until n).reverse) {\n while (po >= 0 && arr(i).cp > 0 && arr(po).cp > 0) {\n tmp = min(arr(i).cp, arr(po).cp)\n arr(i).cp -= tmp\n arr(po).cp -= tmp\n cnt += tmp\n if (arr(po).cp == 0) {\n po -= 1\n }\n }\n }\n writer.println(cnt)\n po = n-2\n for (i <- (0 until n).reverse) {\n while (po >= 0 && arr(i).social > 0 && arr(po).social > 0) {\n tmp = min(arr(i).social, arr(po).social)\n for (k <- 1 to tmp)\n writer.println((po+1) + \" \" + (i+1))\n arr(i).social -= tmp\n arr(po).social -= tmp\n cnt += tmp\n if (arr(po).social == 0) {\n po -= 1\n }\n }\n }\n\n }\n writer.flush()\n}\n"}], "src_uid": "5c013cdc91f88c102532a86058893f0d"} {"source_code": "import scala.io.StdIn\nimport scala.collection.mutable\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n\n val t = StdIn.readLine().toInt\n\n for (_ <- 1 to t) {\n val n = StdIn.readLine().trim.toInt\n val str = StdIn.readLine()\n var cnt = 1\n val res = Array.fill(str.length)(0)\n val q0, q1 = mutable.Queue[Int]()\n\n for (i <- 0 until n) {\n if (str(i) == '0') {\n if (q1.isEmpty) {\n res(i) = cnt\n cnt += 1\n } else {\n res(i) = res(q1.dequeue())\n }\n q0.enqueue(i)\n } else {\n if (q0.isEmpty) {\n res(i) = cnt\n cnt += 1\n } else {\n res(i) = res(q0.dequeue())\n }\n q1.enqueue(i)\n }\n }\n println(res.max)\n println(res.mkString(\" \"))\n }\n }\n}\n", "positive_code": [{"source_code": "//package codeforces.contests._1399\n\nobject BinaryStringToSubsequences {\n def main(args: Array[String]): Unit = {\n for (t <- 1 to io.StdIn.readInt) {\n val _ = io.StdIn.readInt()\n val input = io.StdIn.readLine.toList\n\n var id = 0\n\n def getUniqueId: Int = {\n id += 1\n id\n }\n\n @scala.annotation.tailrec\n def loop(ls: List[Char], zeroIds: List[Int] = Nil, oneIds: List[Int] = Nil, result: List[Int] = Nil): List[Int] = {\n ls match {\n case Nil => result.reverse\n case '0' :: tail => oneIds match {\n case Nil =>\n val id = getUniqueId\n loop(tail, id :: zeroIds, Nil, id :: result)\n case id :: oneTail =>\n loop(tail, id :: zeroIds, oneTail, id :: result)\n }\n case '1' :: tail => zeroIds match {\n case Nil =>\n val id = getUniqueId\n loop(tail, Nil, id :: oneIds, id :: result)\n case id :: zeroTail =>\n loop(tail, zeroTail, id :: oneIds, id :: result)\n }\n }\n }\n\n println {\n val ans = loop(input)\n s\"$id\\n${ans.mkString(\" \")}\"\n }\n }\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.Source\n\nobject BinaryStringToSubsequences1399D extends App {\n\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n// val lines: Iterator[String] =\n// Source.fromString(\"1\\n5\\n11000\\n1\\n1\\n2\\n00\\n2\\n10\\n2\\n01\\n2\\n11\\n3\\n000\\n3\\n100\\n3\\n010\\n3\\n110\\n3\\n001\\n3\\n101\\n3\\n011\\n3\\n111\\n4\\n0000\\n4\\n1000\\n4\\n0100\\n4\\n1100\\n4\\n0010\\n4\\n1010\\n4\\n0110\\n4\\n1110\\n4\\n0001\\n4\\n1001\\n4\\n0101\\n4\\n1101\\n4\\n0011\\n4\\n1011\\n4\\n0111\\n4\\n1111\\n5\\n00000\\n5\\n10000\\n5\\n01000\\n5\\n11000\\n5\\n00100\\n5\\n10100\\n5\\n01100\\n5\\n11100\\n5\\n00010\\n5\\n10010\\n5\\n01010\\n5\\n11010\\n5\\n00110\\n5\\n10110\\n5\\n01110\\n5\\n11110\\n5\\n00001\\n5\\n10001\\n5\\n01001\\n5\\n11001\\n5\\n00101\\n5\\n10101\\n5\\n01101\\n5\\n11101\\n5\\n00011\").getLines\n val ntc: Int = lines.next.toInt\n 0 until ntc map { _ =>\n handleTC()\n } foreach { case (ar, max) =>\n println(max)\n println(ar mkString \" \")\n }\n\n private def handleTC() = {\n val prts = lines.next.toInt\n if (prts == 1) {\n lines.next\n (Array(1),1)\n } else {\n val s = lines.next.toCharArray\n solve(s)\n }\n }\n\n private def solve(s: Array[Char]) = {\n val sol = mutable.ArrayBuffer[Int](1)\n val ones = mutable.Stack[Int]()\n val zeros = mutable.Stack[Int]()\n def updGroup(v: Char, gr: Int) = v match {\n case '0' => zeros push gr\n case '1' => ones push gr\n }\n updGroup(s.head, 1)\n def findFirstAvailable(lastVal: Char) = lastVal match {\n case '0' => if (ones.isEmpty) None else Some(ones.pop)\n case '1' => if (zeros.isEmpty) None else Some(zeros.pop)\n }\n def removeGroupOfPrevSet(v: Char): Unit = v match {\n case '0' => ones.pop\n case '1' => zeros.pop\n }\n var cg = 1\n var largestG = 1\n var i = s.head\n for (j <- s.tail) {\n if (i == j) {\n cg = findFirstAvailable(j).getOrElse({\n largestG = largestG + 1\n largestG\n })\n sol += cg\n }\n else {\n removeGroupOfPrevSet(j)\n sol += cg\n }\n updGroup(j, cg)\n i = j\n }\n (sol.toArray, largestG)\n }\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.Source\n\nobject BinaryStringToSubsequences1399D extends App {\n\n// val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n val lines: Iterator[String] =\n Source.fromString(\"1\\n5\\n11000\\n1\\n1\\n2\\n00\\n2\\n10\\n2\\n01\\n2\\n11\\n3\\n000\\n3\\n100\\n3\\n010\\n3\\n110\\n3\\n001\\n3\\n101\\n3\\n011\\n3\\n111\\n4\\n0000\\n4\\n1000\\n4\\n0100\\n4\\n1100\\n4\\n0010\\n4\\n1010\\n4\\n0110\\n4\\n1110\\n4\\n0001\\n4\\n1001\\n4\\n0101\\n4\\n1101\\n4\\n0011\\n4\\n1011\\n4\\n0111\\n4\\n1111\\n5\\n00000\\n5\\n10000\\n5\\n01000\\n5\\n11000\\n5\\n00100\\n5\\n10100\\n5\\n01100\\n5\\n11100\\n5\\n00010\\n5\\n10010\\n5\\n01010\\n5\\n11010\\n5\\n00110\\n5\\n10110\\n5\\n01110\\n5\\n11110\\n5\\n00001\\n5\\n10001\\n5\\n01001\\n5\\n11001\\n5\\n00101\\n5\\n10101\\n5\\n01101\\n5\\n11101\\n5\\n00011\").getLines\n val ntc: Int = lines.next.toInt\n (0 until ntc map { _ =>\n handleTC()\n }).zipWithIndex.foreach({ case(ar,i) =>\n // println(s\"# $i\")\n println(ar.max)\n println(ar mkString \" \")\n })\n\n private def handleTC() = {\n val prts = lines.next.toInt\n if (prts == 1) {\n lines.next\n Array(1)\n } else {\n val s = lines.next.split(\"\")\n solve(s)\n }\n }\n\n private def solve(s: Array[String]) = {\n val sol = mutable.ArrayBuffer[Int](1)\n val groupLasts = mutable.Map[Int, String](1 -> s.head)\n def findLeastDiff(lastVal: String) = {\n groupLasts.find { case (_, v) => v != lastVal }.map(_._1)\n }\n var cg = 1\n var largestG = 1\n s.zip(s.tail).foreach { case (i, j) =>\n if (i == j) {\n cg = findLeastDiff(j).getOrElse({\n largestG = largestG + 1\n largestG\n })\n sol += cg\n }\n else sol += cg\n groupLasts(cg) = j\n }\n sol.toArray\n }\n}"}, {"source_code": "import scala.collection.mutable\nimport scala.io.Source\n\nobject BinaryStringToSubsequences1399D extends App {\n\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n// val lines: Iterator[String] =\n// Source.fromString(\"4\\n4\\n0011\\n6\\n111111\\n5\\n10101\\n8\\n01010000\").getLines\n val ntc: Int = lines.next.toInt\n 0 until ntc map { _ =>\n handleTC()\n } foreach { ar =>\n println(ar.max)\n println(ar mkString \" \")\n }\n\n private def handleTC() = {\n val prts = lines.next.toInt\n if (prts == 1) {\n lines.next\n Array(1)\n } else {\n val s = lines.next.split(\"\").map(_ == \"1\")\n solve(s)\n }\n }\n\n private def solve(s: Array[Boolean]) = {\n val sol = mutable.ArrayBuffer[Int](1)\n val groupLasts = mutable.SortedMap[Int, Boolean](1 -> s.head)\n def findLeastDiff(lastVal: Boolean) = {\n groupLasts.find { case (_, v) => v != lastVal }.map(_._1)\n }\n var cg = 1\n s.zip(s.tail).foreach { case (i, j) =>\n if (i == j) {\n cg = findLeastDiff(j).getOrElse(cg + 1)\n sol += cg\n }\n else sol += cg\n groupLasts(cg) = j\n }\n sol.toArray\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.Source\n\nobject BinaryStringToSubsequences1399D extends App {\n\n// val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n val lines: Iterator[String] =\n Source.fromString(\"4\\n4\\n0011\\n6\\n111111\\n5\\n10101\\n8\\n01010000\").getLines\n val ntc: Int = lines.next.toInt\n 0 until ntc map { _ =>\n handleTC()\n } foreach { ar =>\n println(ar.max)\n println(ar mkString \" \")\n }\n\n private def handleTC() = {\n val prts = lines.next.toInt\n if (prts == 1) {\n lines.next\n Array(1)\n } else {\n val s = lines.next.split(\"\").map(_ == \"1\")\n solve(s)\n }\n }\n\n private def solve(s: Array[Boolean]) = {\n val sol = mutable.ArrayBuffer[Int](1)\n val groupLasts = mutable.SortedMap[Int, Boolean](1 -> s.head)\n def findLeastDiff(lastVal: Boolean) = {\n groupLasts.find { case (_, v) => v != lastVal }.map(_._1)\n }\n var cg = 1\n s.zip(s.tail).foreach { case (i, j) =>\n if (i == j) {\n cg = findLeastDiff(j).getOrElse(cg + 1)\n sol += cg\n }\n else sol += cg\n groupLasts(cg) = j\n }\n sol.toArray\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.Source\n\nobject BinaryStringToSubsequences1399D extends App {\n\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n// val lines: Iterator[String] =\n// Source.fromString(\"1\\n5\\n11000\\n1\\n1\\n2\\n00\\n2\\n10\\n2\\n01\\n2\\n11\\n3\\n000\\n3\\n100\\n3\\n010\\n3\\n110\\n3\\n001\\n3\\n101\\n3\\n011\\n3\\n111\\n4\\n0000\\n4\\n1000\\n4\\n0100\\n4\\n1100\\n4\\n0010\\n4\\n1010\\n4\\n0110\\n4\\n1110\\n4\\n0001\\n4\\n1001\\n4\\n0101\\n4\\n1101\\n4\\n0011\\n4\\n1011\\n4\\n0111\\n4\\n1111\\n5\\n00000\\n5\\n10000\\n5\\n01000\\n5\\n11000\\n5\\n00100\\n5\\n10100\\n5\\n01100\\n5\\n11100\\n5\\n00010\\n5\\n10010\\n5\\n01010\\n5\\n11010\\n5\\n00110\\n5\\n10110\\n5\\n01110\\n5\\n11110\\n5\\n00001\\n5\\n10001\\n5\\n01001\\n5\\n11001\\n5\\n00101\\n5\\n10101\\n5\\n01101\\n5\\n11101\\n5\\n00011\").getLines\n val ntc: Int = lines.next.toInt\n (0 until ntc map { _ =>\n handleTC()\n }).zipWithIndex.foreach({ case(ar,i) =>\n println(s\"# $i\")\n println(ar.max)\n println(ar mkString \" \")\n })\n\n private def handleTC() = {\n val prts = lines.next.toInt\n if (prts == 1) {\n lines.next\n Array(1)\n } else {\n val s = lines.next.split(\"\").map(_ == \"1\")\n solve(s)\n }\n }\n\n private def solve(s: Array[Boolean]) = {\n val sol = mutable.ArrayBuffer[Int](1)\n val groupLasts = mutable.SortedMap[Int, Boolean](1 -> s.head)\n def findLeastDiff(lastVal: Boolean) = {\n groupLasts.find { case (_, v) => v != lastVal }.map(_._1)\n }\n var cg = 1\n s.zip(s.tail).foreach { case (i, j) =>\n if (i == j) {\n cg = findLeastDiff(j).getOrElse(groupLasts.size + 1)\n sol += cg\n }\n else sol += cg\n groupLasts(cg) = j\n }\n sol.toArray\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n\n def take(str: String): Int = {\n str.zip(str.tail).takeWhile(c => c._1 != c._2).length + 1\n }\n\n\n\n for (_ <- 1 to t) {\n val _ = StdIn.readLine().trim.toInt\n val str = StdIn.readLine()\n import scala.collection.mutable.ListBuffer\n val temp = ListBuffer[Int]()\n val res = Array.fill(str.length)(-1)\n var i = 1\n var s = str\n var index = 0\n while (s.nonEmpty) {\n val n = take(s)\n for (ii <- index until index + n) {\n res(ii) = i\n }\n index += n\n val (h, t) = s.splitAt(n)\n temp += h.last - '0'\n if (t.nonEmpty) {\n val li = temp.indexOf((t.head - '0') ^ 1)\n if (li >= 0) {\n i = li + 1\n temp(li) = 1 ^ temp(li)\n } else {\n i = temp.length + 1\n }\n }\n s = t\n }\n println(res.max)\n println(res.mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n\n def take(str: String): Int = {\n str.zip(str.tail).takeWhile(c => c._1 != c._2).length + 1\n }\n\n\n\n for (_ <- 1 to t) {\n val _ = StdIn.readLine().trim.toInt\n val str = StdIn.readLine()\n import scala.collection.mutable.ListBuffer\n val temp = ListBuffer[Int]()\n val res = Array.fill(str.length)(-1)\n var i = 1\n var s = str\n var index = 0\n while (s.nonEmpty) {\n val n = take(s)\n for (ii <- index until index + n) {\n res(ii) = i\n }\n index += n\n val (h, t) = s.splitAt(n)\n temp += h.last - '0'\n if (t.nonEmpty) {\n val li = temp.indexOf((t.head - '0') ^ 1)\n if (li >= 0) {\n i = li + 1\n } else {\n i = temp.length + 1\n }\n }\n s = t\n }\n println(res.max)\n println(res.mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n\n def take(str: String): Int = {\n str.zip(str.tail).takeWhile(c => c._1 != c._2).length + 1\n }\n\n\n\n for (_ <- 1 to t) {\n val _ = StdIn.readLine().trim.toInt\n val str = StdIn.readLine()\n import scala.collection.mutable.ListBuffer\n val temp = ListBuffer[Int]()\n val res = Array.fill(str.length)(-1)\n var i = 1\n var s = str\n var index = 0\n while (s.nonEmpty) {\n val n = take(s)\n for (ii <- index until index + n) {\n res(ii) = i\n }\n index += n\n val (h, t) = s.splitAt(n)\n temp += h.last - '0'\n if (t.nonEmpty) {\n val li = temp.indexOf((t.head - '0') ^ 1)\n if (li >= 0) {\n i = li + 1\n } else {\n i = temp.length + 1\n }\n }\n s = t\n }\n println(res.mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n\n def take(str: String): Int = {\n str.zip(str.tail).takeWhile(c => c._1 != c._2).length + 1\n }\n\n\n\n for (_ <- 1 to t) {\n val _ = StdIn.readLine().trim.toInt\n val str = StdIn.readLine()\n import scala.collection.mutable.ListBuffer\n val temp = ListBuffer[Int]()\n val res = Array.fill(str.length)(-1)\n var i = 1\n var s = str\n var index = 0\n while (s.nonEmpty) {\n val n = take(s)\n for (ii <- index until index + n) {\n res(ii) = i\n }\n index += n\n val (h, t) = s.splitAt(n)\n\n if (t.nonEmpty) {\n val li = temp.indexOf((t.head - '0') ^ 1)\n if (li >= 0) {\n i = li + 1\n temp(li) = 1 ^ temp(li)\n } else {\n\n i = res.max + 1\n temp += h.last - '0'\n }\n }\n\n s = t\n }\n println(res.max)\n println(res.mkString(\" \"))\n }\n }\n}\n"}], "src_uid": "de57b6b1aa2b6ec4686d1348988c0c63"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStreamReader}\n\n val x = 0\n def main(args: Array[String]): Unit = {\n val reader = new InputReader()\n val t = reader.nextInt()\n (1 to t).foreach { i =>\n val n = reader.nextString()\n if (n.length > 2)\n System.out.println(n.min)\n else\n System.out.println(n.charAt(1))\n }\n\n }\n\n class InputReader() {\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var line: Array[String] = null\n var cur: Int = 0\n\n def nextString(): String = {\n while (line == null || cur >= line.length) {\n cur = 0\n line = reader.readLine().split(\"\"\" \"\"\")\n }\n cur += 1\n line(cur - 1)\n }\n\n def nextInt(): Int = {\n nextString().toInt\n }\n\n def nextLong(): Int = {\n nextString().toInt\n }\n\n }\n\n}\n", "positive_code": [{"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\n\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val reader = new InputReader()\n val t = reader.nextInt()\n (1 to t).foreach { i =>\n val n = reader.nextString()\n if (n.length > 2)\n System.out.println(n.min)\n else\n System.out.println(n.charAt(1))\n }\n\n }\n\n class InputReader() {\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var line: Array[String] = null\n var cur: Int = 0\n\n def nextString(): String = {\n while (line == null || cur >= line.length) {\n cur = 0\n line = reader.readLine().split(\"\"\" \"\"\")\n }\n cur += 1\n line(cur - 1)\n }\n\n def nextInt(): Int = {\n nextString().toInt\n }\n\n def nextLong(): Int = {\n nextString().toInt\n }\n\n }\n\n}\n"}, {"source_code": "object Main {\r\n import java.io.{BufferedReader, InputStreamReader}\r\n\r\n val x = 0\r\n def main(args: Array[String]): Unit = {\r\n val reader = new InputReader()\r\n val t = reader.nextInt()\r\n (1 to t).foreach { i =>\r\n val n = reader.nextString()\r\n if (n.length > 2)\r\n System.out.println(n.min)\r\n else\r\n System.out.println(n.charAt(1))\r\n }\r\n\r\n }\r\n\r\n class InputReader() {\r\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\r\n var line: Array[String] = null\r\n var cur: Int = 0\r\n\r\n def nextString(): String = {\r\n while (line == null || cur >= line.length) {\r\n cur = 0\r\n line = reader.readLine().split(\"\"\" \"\"\")\r\n }\r\n cur += 1\r\n line(cur - 1)\r\n }\r\n\r\n def nextInt(): Int = {\r\n nextString().toInt\r\n }\r\n\r\n def nextLong(): Int = {\r\n nextString().toInt\r\n }\r\n\r\n }\r\n\r\n}\r\n"}, {"source_code": "/*\nhttps://codeforces.com/contest/1684/problem/0\n\n1234 => 2134 => 213 => 312 => 31 => 13 => 1\n1234 => 1324 => 132 => 123 => 12 => 21 => 2\n\n1) 2d. XY => YX => Y\n2) > 2d. XYZAm => XmZAY =>... => XmZ => ZmX => Zm => mZ\n\n */\n\nimport scala.io.StdIn\n\nobject many_digitals{\n\n def main(args: Array[String]): Unit = {\n def solving(n: String) = {\n if (n.length == 2) {\n println(n(1))\n }\n else {\n val answer = n.split(\"\").map(x => x.toInt).min\n println(answer)\n }\n }\n\n val t = StdIn.readLine().toInt\n val in = new Array[String](t)\n for (i <- 0 until(t)) {\n // val n = StdIn.readLine().toInt\n in(i) = StdIn.readLine()\n }\n\n in.foreach(solving _)\n\n }\n}\n"}], "negative_code": [], "src_uid": "adf024899fb2a684427463733358566a"} {"source_code": "\nimport java.io._\nimport java.util.Scanner\n\nimport scala.collection.immutable.TreeMap\n\n/**\n * @author antipov.\n * 15.07.2016 14:47.\n */\nobject A extends App {\n object Reader {\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n }\n\n val sc: Scanner = new Scanner(System.in)\n def readInt(): Int = sc.nextInt()\n def readLong(): Long = sc.nextLong()\n\n case class Edge(var from: Long, var to: Long) extends Comparable[Edge] {\n if(from > to) {\n val tmp = from\n from = to\n to = tmp\n }\n\n override def compareTo(o: Edge): Int =\n if (this.from != o.from) this.from compareTo o.from\n else this.to compareTo o.to\n\n override def toString: String = \"Edge(\" + from + \", \" + to + \")\"\n }\n\n val q = sc.nextInt()\n var added = new TreeMap[Edge, Long]() withDefaultValue 0L\n\n\n (0 until q).foreach(i => {\n val (t, v, u) = (readLong(), readLong(), readLong())\n val edges = convert(path(v, u))\n if(t == 1) {\n val w = readLong()\n edges foreach(e => added = added + (e -> (added(e) + w)))\n } else\n println(edges map (e => added(e)) sum)\n })\n\n\n def convert(path: List[Long]): List[Edge] = {\n def convert(path: List[Long], acc: List[Edge]): List[Edge] = path match {\n case List(x) => acc\n case x :: y :: xs => convert(path.tail, Edge(x, y) :: acc)\n }\n convert(path, Nil)\n }\n\n def path(v: Long, u: Long): List[Long] = {\n def path(v: Long, u: Long, accV: List[Long], accU: List[Long]): List[Long] = {\n if(v == u) accU.reverse ::: (v :: accV)\n else if(v > u) path(v / 2, u, v :: accV, accU)\n else path(v, u / 2, accV, u :: accU)\n }\n path(v, u, List(), List())\n }\n}\n", "positive_code": [{"source_code": "import scala.collection._\n\nobject Main {\n\n var map = mutable.Map[Long, Long]().withDefaultValue(0L)\n\n def main(args: Array[String]): Unit = {\n var Q = readInt()\n for(_ <- 0 until Q) {\n\n val a: Array[Long] = readLine().split(\" \").map(_.toLong)\n\n val u: Long = a(1)\n val v: Long = a(2)\n\n val lca: Long = LCA(u, v)\n \n if (a(0) == 1) {\n val cost: Long = a(3)\n update(u, lca, cost)\n update(v, lca, cost)\n } else {\n val ret = getCost(u, lca, 0) + getCost(v, lca, 0)\n println(ret)\n }\n }\n }\n\n @annotation.tailrec\n def LCA(u: Long, v: Long): Long = {\n if (u == v) v\n else if (u > v) LCA(u / 2, v)\n else LCA(u, v / 2)\n }\n\n @annotation.tailrec\n def update(v: Long, lca: Long, cost: Long) {\n if (v > lca) {\n map(v) += cost\n update(v / 2, lca, cost)\n }\n }\n\n @annotation.tailrec\n def getCost(v: Long, lca: Long, acc: Long): Long = {\n if (v > lca) {\n map.get(v) match {\n case Some(cost) => getCost(v / 2, lca, acc + cost)\n case None => getCost(v / 2, lca, acc)\n } \n } else acc \n }\n}"}, {"source_code": "import scala.collection._\n\nobject Main {\n\n var map = mutable.Map[Long, Long]().withDefaultValue(0L)\n\n def main(args: Array[String]): Unit = {\n var Q = readInt()\n for(_ <- 0 until Q) {\n\n val a: Array[Long] = readLine().split(\" \").map(_.toLong)\n\n val u: Long = a(1)\n val v: Long = a(2)\n\n val lca: Long = LCA(u, v)\n \n if (a(0) == 1) {\n val cost: Long = a(3)\n update(u, lca, cost)\n update(v, lca, cost)\n } else {\n val ret = getCost(u, lca, 0) + getCost(v, lca, 0)\n println(ret)\n }\n }\n }\n\n @annotation.tailrec\n def LCA(u: Long, v: Long): Long = {\n if (u == v) v\n else if (u > v) LCA(u / 2, v)\n else LCA(u, v / 2)\n }\n\n @annotation.tailrec\n def update(v: Long, lca: Long, cost: Long) {\n if (v > lca) {\n map(v) += cost\n update(v / 2, lca, cost)\n }\n }\n\n // @annotation.tailrec\n def getCost(v: Long, lca: Long, acc: Long): Long = {\n if (v > lca) {\n map.get(v).map(x => getCost(v / 2, lca, acc + x)).getOrElse(getCost(v / 2, lca, acc))\n // map.get(v) match {\n // case Some(cost) => getCost(v / 2, lca, acc + cost)\n // case None => getCost(v / 2, lca, acc)\n // } \n } else acc \n }\n}"}, {"source_code": "import scala.collection._\nimport java.util.StringTokenizer\nimport java.io._\n\nobject Main extends App {\n\n var map = mutable.Map[Long, Long]().withDefaultValue(0L)\n\n var Q = IO.nextInt\n (0 until Q).foreach { _ =>\n\n val (kindOf, u, v) = (IO.nextLong, IO.nextLong, IO.nextLong)\n val lca: Long = LCA(u, v)\n \n if (kindOf == 1) {\n val cost: Long = IO.nextLong\n update(u, lca, cost)\n update(v, lca, cost)\n } else {\n val ret = getCost(u, lca, 0) + getCost(v, lca, 0)\n println(ret)\n }\n }\n\n IO.close\n \n @annotation.tailrec\n def LCA(u: Long, v: Long): Long = {\n if (u == v) v\n else if (u > v) LCA(u / 2, v)\n else LCA(u, v / 2)\n }\n\n @annotation.tailrec\n def update(v: Long, lca: Long, cost: Long) {\n if (v > lca) {\n map(v) += cost\n update(v / 2, lca, cost)\n }\n }\n\n def getCost(v: Long, lca: Long, acc: Long): Long = {\n if (v > lca) map.get(v).map(x => getCost(v / 2, lca, acc + x)).getOrElse(getCost(v / 2, lca, acc))\n else acc \n }\n}\n\nobject IO {\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n var tok = new StringTokenizer(\"\")\n def nextToken() = {\n while (!tok.hasMoreTokens) {\n tok = new StringTokenizer(in.readLine())\n }\n tok.nextToken()\n }\n\n def nextInt = nextToken().toInt\n def nextLong = nextToken().toLong\n def println(a: Any) = out.println(a)\n def close = {\n in.close()\n out.close()\n }\n}"}, {"source_code": "\nimport java.util.Scanner\nimport scala.collection._\nimport java.lang.Math._\n\n/**\n * @author antipov.\n * 15.07.2016 14:47.\n */\nobject A extends App {\n val sc: Scanner = new Scanner(System.in)\n def readInt(): Int = sc.nextInt()\n def readLong(): Long = sc.nextLong()\n\n case class Edge(from: Long, to: Long) {\n require(from <= to)\n\n override def hashCode(): Int = {\n val prime = 31\n (prime + from.hashCode()) * prime + to.hashCode()\n }\n\n override def equals(obj: scala.Any): Boolean = obj match {\n case Edge(x, y) => x == from && y == to\n case _ => false\n }\n\n override def toString: String = \"Edge(\" + from + \", \" + to + \")\"\n }\n\n val q = sc.nextInt()\n val added = new mutable.HashMap[Edge, Long]() withDefaultValue 0L\n\n\n (0 until q).foreach(i => {\n val (t, v, u) = (readLong(), readLong(), readLong())\n val edges = convert(path(v, u))\n if(t == 1) {\n val w = readLong()\n edges foreach(e => added += ((e, added(e) + w)))\n } else\n println(edges map (e => added(e)) sum)\n })\n\n\n def convert(path: List[Long]): List[Edge] = {\n def convert(path: List[Long], acc: List[Edge]): List[Edge] = path match {\n case List(x) => acc\n case x :: y :: xs => convert(path.tail, Edge(min(x, y), max(x, y)) :: acc)\n }\n convert(path, Nil)\n }\n\n def path(v: Long, u: Long): List[Long] = {\n def path(v: Long, u: Long, accV: List[Long], accU: List[Long]): List[Long] = {\n if(v == u) accU.reverse ::: (v :: accV)\n else if(v > u) path(v / 2, u, v :: accV, accU)\n else path(v, u / 2, accV, u :: accU)\n }\n path(v, u, List(), List())\n }\n\n\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.StringTokenizer\nimport scala.collection._\n\n/**\n * @author antipov.\n * 15.07.2016 14:47.\n */\nobject A extends App {\n def readInt(): Int = IO.nextInt\n def readLong(): Long = IO.nextLong\n def println(a: Any) = IO.println(a)\n\n case class Edge(var from: Long, var to: Long) extends Comparable[Edge] {\n if(from > to) {\n val tmp = from\n from = to\n to = tmp\n }\n\n override def compareTo(o: Edge): Int =\n if (this.from != o.from) this.from compareTo o.from\n else this.to compareTo o.to\n\n override def toString: String = \"Edge(\" + from + \", \" + to + \")\"\n }\n\n val q = readInt\n var added = new immutable.TreeMap[Edge, Long]() withDefaultValue 0L\n\n\n (0 until q).foreach(i => {\n val (t, v, u) = (readLong, readLong, readLong)\n val edges = convert(path(v, u))\n if(t == 1) {\n val w = readLong\n edges.map (e => added = added + (e -> (added(e) + w)))\n } else\n println(edges map (e => added(e)) sum)\n })\n\n\n def convert(path: List[Long]): List[Edge] = {\n def convert(path: List[Long], acc: List[Edge]): List[Edge] = path match {\n case List(x) => acc\n case x :: y :: xs => convert(path.tail, Edge(x, y) :: acc)\n }\n convert(path, Nil)\n }\n\n def path(v: Long, u: Long): List[Long] = {\n def path(v: Long, u: Long, accV: List[Long], accU: List[Long]): List[Long] = {\n if(v == u) accU.reverse ::: (v :: accV)\n else if(v > u) path(v / 2, u, v :: accV, accU)\n else path(v, u / 2, accV, u :: accU)\n }\n path(v, u, List(), List())\n }\n\n IO.close\n}\n\nobject IO {\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n var tok = new StringTokenizer(\"\")\n def nextToken() = {\n while (!tok.hasMoreTokens) {\n tok = new StringTokenizer(in.readLine())\n }\n tok.nextToken()\n }\n\n def nextInt = nextToken().toInt\n def nextLong = nextToken().toLong\n def println(a: Any) = out.println(a)\n def close = {\n in.close()\n out.close()\n }\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.StringTokenizer\nimport scala.collection._\n\n/**\n * @author antipov.\n * 15.07.2016 14:47.\n */\nobject A extends App {\n def readInt(): Int = IO.nextInt\n def readLong(): Long = IO.nextLong\n def println(a: Any) = IO.println(a)\n\n case class Edge(var from: Long, var to: Long) extends Comparable[Edge] {\n if(from > to) {\n val tmp = from\n from = to\n to = tmp\n }\n\n override def compareTo(o: Edge): Int =\n if (this.from != o.from) this.from compareTo o.from\n else this.to compareTo o.to\n\n override def toString: String = \"Edge(\" + from + \", \" + to + \")\"\n }\n\n val q = readInt\n var added = new immutable.TreeMap[Edge, Long]() withDefaultValue 0L\n\n\n (0 until q).foreach(i => {\n val (t, v, u) = (readLong, readLong, readLong)\n val edges = convert(path(v, u))\n if(t == 1) {\n val w = readLong\n edges foreach (e => added = added + (e -> (added(e) + w)))\n } else\n println(edges map (e => added(e)) sum)\n })\n\n\n def convert(path: List[Long]): List[Edge] = {\n def convert(path: List[Long], acc: List[Edge]): List[Edge] = path match {\n case List(x) => acc\n case x :: y :: xs => convert(path.tail, Edge(x, y) :: acc)\n }\n convert(path, Nil)\n }\n\n def path(v: Long, u: Long): List[Long] = {\n def path(v: Long, u: Long, accV: List[Long], accU: List[Long]): List[Long] = {\n if(v == u) accU.reverse ::: (v :: accV)\n else if(v > u) path(v / 2, u, v :: accV, accU)\n else path(v, u / 2, accV, u :: accU)\n }\n path(v, u, List(), List())\n }\n\n IO.close\n}\n\nobject IO {\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n var tok = new StringTokenizer(\"\")\n def nextToken() = {\n while (!tok.hasMoreTokens) {\n tok = new StringTokenizer(in.readLine())\n }\n tok.nextToken()\n }\n\n def nextInt = nextToken().toInt\n def nextLong = nextToken().toLong\n def println(a: Any) = out.println(a)\n def close = {\n in.close()\n out.close()\n }\n}\n"}, {"source_code": "object Lorenzo {\n import io.StdIn.readLine\n import collection.mutable.ArrayBuffer\n var map = collection.mutable.HashMap[Long, Long]()\n\n def main(args: Array[String]){\n var price = 0L\n\n for(i <- 0 until readLine.trim.toInt){\n val ar = readLine.trim.split(\" \")\n \n var al = ar.tail.map(_.toLong)\n if(ar(0) == \"1\")\n {\n \n var v = al(0)\n var u = al(1)\n var w = al(2)\n var path = getPath(v, u)\n updateMap(path, w)\n price+=getPrice(path)\n \n }\n else\n {\n var v = al(0)\n var u = al(1)\n var path = getPath(v, u)\n updateMap(path, 0L)\n println(getPrice(path))\n \n }\n\n\n\n }\n \n } \n \n def depth(v: Long): Long = {\n v.toBinaryString.length\n }\n\n def getPath(v: Long, u: Long): ArrayBuffer[Long] = {\n var ab = ArrayBuffer[Long]()\n\n var nv = v\n var nu = u\n \n val dv = depth(v)\n val du = depth(u)\n\n if(dv > du)\n {\n for(i <- 0 until (dv - du).toInt)\n {\n ab+=nv\n nv/=2\n }\n\n }\n if(dv < du)\n {\n for(i <- 0 until (du - dv).toInt)\n {\n ab+=nu\n nu/=2\n }\n\n }\n\n \n while(nv != nu)\n {\n ab+=nv\n ab+=nu\n nv/=2\n nu/=2\n }\n\n ab\n }\n\n def updateMap(ab: ArrayBuffer[Long], p: Long): Unit = {\n for(i <- ab)\n {\n if(map.isDefinedAt(i))\n {\n map(i)+=p\n }\n else\n {\n map(i) = p\n }\n }\n\n }\n\n def getPrice(ab: ArrayBuffer[Long]): Long = {\n ab.fold(0L){ (z, i) =>\n z + map(i)\n }\n\n }\n\n\n}\n\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _697C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val costToParent = map[Long] to 0L\n\n @tailrec\n def increase(u: Long, v: Long, w: Long): Unit = {\n //debug(u, v, w)\n if (u > v) {\n costToParent(u) += w\n increase(u/2, v, w)\n } else if (u < v) {\n costToParent(v) += w\n increase(u, v/2, w)\n }\n }\n\n @tailrec\n def calc(u: Long, v: Long, acc: Long): Long = {\n if(u > v) {\n calc(u/2, v, acc + costToParent(u))\n } else if (v > u) {\n calc(u, v/2, acc + costToParent(v))\n } else {\n acc\n }\n }\n\n repeat(read[Int]) {\n read[Int] match {\n case 1 =>\n val v, u, w = read[Long]\n increase(u, v, w)\n case 2 =>\n val v, u = read[Long]\n val cost = calc(u, v, 0L)\n write(cost).writeLine()\n }\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toYesNo = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeLine(obj: Any*): this.type = {\n if (obj.isEmpty) printer.println() else obj foreach printer.println\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "12814033bec4956e7561767a6778d77e"} {"source_code": "import collection.mutable.MutableList\n\n/**\n * Created by IntelliJ IDEA.\n * User: User\n * Date: 29.02.12\n * Time: 2:59\n * To change this template use File | Settings | File Templates.\n */\nobject C {\n def main(args: Array[String]) {\n val input = readLine\n val forbid = Map(((1 to readInt) map (_ => readLine)) flatMap (str => List(str(0) -> Some(str), str(1) -> Some(str))): _*) withDefaultValue None\n var currentPair: Option[String] = None\n var striked = 0\n var found = List(0, 0)\n for (c <- input) {\n forbid(c) match {\n case None => {\n currentPair = None\n striked += found.min\n found = List(0, 0)\n }\n case Some(str) => {\n val newFound = str.indexOf(c) match {\n case 0 => List(1, 0)\n case 1 => List(0, 1)\n }\n found = currentPair match {\n case Some(cur_str) => {\n if (str == cur_str) (found zip newFound) map (x => x._1 + x._2)\n else {\n striked += found.min\n currentPair = Some(str)\n newFound\n }\n }\n case None => {\n currentPair = Some(str)\n newFound\n }\n }\n }\n }\n }\n striked += (currentPair match {\n case None => 0\n case Some(str) => found.min\n })\n println(striked)\n }\n}\n\n", "positive_code": [{"source_code": "\nobject A {\n def main(args: Array[String]) {\n val input = readLine\n val forbid = Map(((1 to readInt) map (_ => readLine)) flatMap (str => List(str(0) -> Some(str), str(1) -> Some(str))): _*) withDefaultValue None\n var currentPair: Option[String] = None\n var striked = 0\n var found = List(0, 0)\n for (c <- input) {\n forbid(c) match {\n case None => {\n currentPair = None\n striked += found.min\n found = List(0, 0)\n }\n case Some(str) => {\n val newFound = str.indexOf(c) match {\n case 0 => List(1, 0)\n case 1 => List(0, 1)\n }\n found = currentPair match {\n case Some(cur_str) => {\n if (str == cur_str) (found zip newFound) map (x => x._1 + x._2)\n else {\n striked += found.min\n currentPair = Some(str)\n newFound\n }\n }\n case None => {\n currentPair = Some(str)\n newFound\n }\n }\n }\n }\n }\n striked += (currentPair match {\n case None => 0\n case Some(str) => found.min\n })\n println(striked)\n }\n}"}], "negative_code": [], "src_uid": "da2b3450a3ca05a60ea4de6bab9291e9"} {"source_code": "import java.util.Scanner\n\nobject D extends App {\n def cnt(t: Long) = t / x + t / y\n\n def bs(s: Long) = {\n var l = s * x * y / (x + y)\n var r = 2 * s * (x max y)\n\n while (r - l > 1) {\n val p = (l + r) / 2\n\n// val z = Seq(l, p, r)\n\n cnt(p) match {\n case c if c < s => l = p + 1\n case _ => r = p\n }\n\n// Console.err.println(z + \" -> \" + (z map cnt) + \" by \" + (l, r))\n }\n\n// val z = Seq(l, r)\n// Console.err.println(z + \" -> \" + (z map cnt))\n\n if (cnt(l) == s) l else r\n } ensuring {\n r => {\n val c = cnt(r)\n// Console.err.println(\"answer: \" + r)\n s <= c && c <= s + 1\n }\n }\n\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n val (x, y) = n(sc.nextLong(), sc.nextLong())\n\n def gcd(a: Long, b: Long): Long = if (b == 0) a.abs else gcd(b, a % b)\n def n(x: Long, y: Long) = {\n val g = gcd(x, y)\n (x / g, y / g)\n }\n\n for (i <- 1 to n) {\n val s = sc.nextLong()\n\n def decide(t: Long): String = (t % x == 0, t % y == 0) match {\n case (true, true) => \"Both\"\n case (true, false) => \"Vova\"\n case (false, true) => \"Vanya\"\n case _ => decide(t - 1)\n }\n val ans = decide(bs(s))\n\n Console.println(ans)\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util._\nimport java.util.StringTokenizer\n\nimport scala.util.Sorting\n\nobject Solution {\n val INF: Long = 1e18.toLong;\n var x: Long = 0\n var y: Long = 0\n\n def countHits(num: Long): Long = num / y + num / x\n\n def solve(in: FastScanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n x = in.nextLong()\n y = in.nextLong()\n for (i <- 0 until n) {\n val a: Long = in.nextLong()\n var low: Long = 0\n var high: Long = INF\n while (high - low > 1) {\n val mid: Long = (low + high) / 2\n if (countHits(mid) >= a)\n high = mid\n else\n low = mid\n }\n if (high % y == 0 && high % x == 0)\n out.println(\"Both\")\n else if (high % y == 0)\n out.println(\"Vanya\")\n else\n out.println(\"Vova\")\n }\n }\n\n def main(args: Array[String]): Unit = {\n val in = new FastScanner(System.in)\n val out = new PrintWriter(System.out)\n solve(in, out)\n out.flush()\n }\n\n class FastScanner(val in: InputStream) {\n var st: StringTokenizer = null\n var br = new BufferedReader(new InputStreamReader(in))\n\n def next(): String = {\n while (st == null || !st.hasMoreTokens()) {\n val line = br.readLine()\n if (line == null)\n throw new IOException()\n st = new StringTokenizer(line)\n }\n return st.nextToken()\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def close(): Unit = {\n br.close()\n }\n }\n\n}"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, x, y) = readLongs(3)\n val as = Array.fill(n.toInt) { readLine.toInt }\n\n val perSecond = x + y\n val resolution = x * y\n val stepX = (resolution / x)\n val stepY = (resolution / y)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n var c = 0\n for (a <- as) {\n\n def can(ticks: Long) = ticks / stepX + ticks / stepY >= a\n \n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) >>> 1\n if (can(mid)) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val ticks = binSearch(0, Long.MaxValue - 1) - 1\n val stepsX = ticks / stepX\n val stepsY = ticks / stepY\n //println(ticks, stepsX, stepsY)\n \n var remain = a - stepsX - stepsY\n if (remain <= 0) println(\"Both\")\n else {\n var px = stepsX * stepX\n var py = stepsY * stepY\n while (remain > 0) {\n c += 1\n //println(remain, px, py, c)\n val dx = px + stepX\n val dy = py + stepY\n if (dx == dy) {\n remain -= 2\n px += stepX\n py += stepY\n if (remain <= 0) println(\"Both\")\n } else if (dx < dy) {\n val steps = ((dy - px) / stepX - 1) max 1\n remain -= steps\n px += stepX * steps\n if (remain <= 0) println(\"Vanya\")\n } else {\n val steps = ((dx - py) / stepY - 1) max 1\n remain -= steps\n py += stepY * steps\n if (remain <= 0) println(\"Vova\")\n }\n }\n }\n }\n\n Console.flush\n}\n"}, {"source_code": "\n\nobject D {\n def main(args: Array[String]) = {\n val data = readLine().split(' ').map(t => t.toInt)\n val n = data(0)\n val x: Long = data(1)\n val y: Long = data(2)\n //println(x, y, n)\n for (e <- (1 to n).map(_ => readLine().toLong)) {\n println(solve(e, x, y))\n }\n }\n def gcd(a: Long, b: Long): Long = if (a == 0) b else gcd(b % a, a)\n def lcm(a: Long, b: Long) = a * b / gcd(a, b)\n def findMin(e: Long, sx: Long, sy: Long, begin: Long, end: Long): Long = {\n val mid = (begin + end) / 2\n if (begin == end) begin\n else if (mid / sx + mid / sy >= e) findMin(e, sx, sy, begin, mid)\n else findMin(e, sx, sy, mid + 1, end)\n }\n def solve(e: Long, x: Long, y: Long): String = {\n val z = lcm(x, y)\n val stepx = z / x\n val stepy = z / y\n \n val m = findMin(e, stepx, stepy, 0, e * stepx)\n if (m % stepx == 0) {\n if (m % stepy == 0) \"Both\"\n else \"Vanya\"\n } else \"Vova\"\n }\n}"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, x, y) = readLongs(3)\n val as = Array.fill(n.toInt) { readLine.toInt }\n\n val perSecond = x + y\n val resolution = BigInt(x * y)\n\n for (a <- as) {\n var remain = a % perSecond\n //if (remain < 0) remain += perSecond\n // println(remain)\n if (remain <= 0) println(\"Both\")\n else {\n var px, py = 0L\n while (remain > 0) {\n val dx = (px + 1) * resolution / x\n val dy = (py + 1) * resolution / y\n if (dx == dy) {\n remain -= 2\n if (remain <= 0) println(\"Both\")\n } else if (dx < dy) {\n remain -= 1\n px += 1\n if (remain <= 0) println(\"Vanya\")\n } else {\n remain -= 1\n py += 1\n if (remain <= 0) println(\"Vova\")\n }\n }\n }\n }\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, x, y) = readInts(3)\n val as = Array.fill(n) { readLine.toInt }\n\n val perSecond = x + y\n val resolution = x * y\n\n for (a <- as) {\n var remain = a % perSecond\n if (remain == 0) println(\"Both\")\n else {\n var px, py = 0L\n while (remain > 0) {\n val dx = (px + 1) * resolution / x\n val dy = (py + 1) * resolution / y\n if (dx == dy) {\n remain -= 2\n if (remain <= 0) println(\"Both\")\n } else if (dx < dy) {\n remain -= 1\n px += 1\n if (remain <= 0) println(\"Vanya\")\n } else {\n remain -= 1\n py += 1\n if (remain <= 0) println(\"Vova\")\n }\n }\n }\n }\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, x, y) = readLongs(3)\n val as = Array.fill(n.toInt) { readLine.toInt }\n\n val perSecond = x + y + 2\n val resolution = BigInt(x * y)\n\n for (a <- as) {\n var remain = a % perSecond\n if (remain == 0) println(\"Both\")\n else {\n var px, py = 0L\n while (remain > 0) {\n val dx = (px + 1) * resolution / x\n val dy = (py + 1) * resolution / y\n if (dx == dy) {\n remain -= 2\n if (remain <= 0) println(\"Both\")\n } else if (dx < dy) {\n remain -= 1\n px += 1\n if (remain <= 0) println(\"Vanya\")\n } else {\n remain -= 1\n py += 1\n if (remain <= 0) println(\"Vova\")\n }\n }\n }\n }\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, x, y) = readLongs(3)\n val as = Array.fill(n.toInt) { readLine.toInt }\n\n val perSecond = x + y\n val resolution = x * y\n\n for (a <- as) {\n var remain = a % perSecond\n if (remain == 0) println(\"Both\")\n else {\n var px, py = 0L\n while (remain > 0) {\n val dx = (px + 1) * resolution / x\n val dy = (py + 1) * resolution / y\n if (dx == dy) {\n remain -= 2\n if (remain <= 0) println(\"Both\")\n } else if (dx < dy) {\n remain -= 1\n px += 1\n if (remain <= 0) println(\"Vanya\")\n } else {\n remain -= 1\n py += 1\n if (remain <= 0) println(\"Vova\")\n }\n }\n }\n }\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, x, y) = readLongs(3)\n val as = Array.fill(n.toInt) { readLine.toInt }\n\n val perSecond = x + y + 2\n val resolution = x * y\n\n for (a <- as) {\n var remain = a % perSecond\n if (remain == 0) println(\"Both\")\n else {\n var px, py = 0L\n while (remain > 0) {\n val dx = (px + 1) * resolution / x\n val dy = (py + 1) * resolution / y\n if (dx == dy) {\n remain -= 2\n if (remain <= 0) println(\"Both\")\n } else if (dx < dy) {\n remain -= 1\n px += 1\n if (remain <= 0) println(\"Vanya\")\n } else {\n remain -= 1\n py += 1\n if (remain <= 0) println(\"Vova\")\n }\n }\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject D extends App {\n def cnt(t: Long) = t / x + t / y - t / (x * y)\n\n def bs(s: Long) = {\n var l = s * x * y / (x + y)\n var r = (s + 2) * x * y / (x + y)\n\n while (r - l > 1) {\n val p = (l + r) / 2\n cnt(p) match {\n case c if c < s => l = p + 1\n case c if c > s => r = p - 1\n case _ => r = p\n }\n }\n\n if (cnt(l) == s) l else r\n } ensuring {\n r => {\n val c = cnt(r)\n s <= c && c <= s + 1\n }\n }\n\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n val x = sc.nextLong()\n val y = sc.nextLong()\n\n for (i <- 1 to n) {\n val s = sc.nextLong()\n\n val t = bs(s)\n\n Console.println {\n (t % x == 0, t % y == 0) match {\n case (true, true) => \"Both\"\n case (true, false) => \"Vova\"\n case (false, true) => \"Vanya\"\n case _ => throw new RuntimeException(t.toString)\n }\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject D extends App {\n def cnt(t: Long) = t * x / (x * y) + t * y / (x * y)\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n val x = sc.nextLong()\n val y = sc.nextLong()\n\n for (i <- 1 to n) {\n val s = sc.nextLong()\n\n var t = s * x * y / (x + y)\n while (cnt(t) < s) t += 1\n\n Console.println {\n (t % x == 0, t % y == 0) match {\n case (true, true) => \"Both\"\n case (true, false) => \"Vanya\"\n case (false, true) => \"Vasya\"\n case _ => throw new RuntimeException(t.toString)\n }\n }\n }\n}\n"}], "src_uid": "f98ea97377a06963d1e6c1c215ca3a4a"} {"source_code": "import scala.io._\nimport java.util.StringTokenizer\nimport java.io.BufferedReader\n\nobject Main {\n \n def main(args: Array[String]): Unit = {\n val N = nextInt\n val K = nextInt\n (K+1) to 1 by -1 foreach println\n (K+2) to N foreach println\n }\n \n class Tokenizer(in: BufferedReader, splitOn: String = \" \\n\\t\\r\\f\")\n {\n private var tokenizer = new StringTokenizer(\"\")\n def readLine() = in.readLine() \n def nextToken(): String = {\n while (!tokenizer.hasMoreTokens) {\n val line = readLine\n if (line == null) return null\n tokenizer = new StringTokenizer(line, splitOn)\n }\n tokenizer.nextToken\n } \n def next[A](f: String => A) = f(nextToken)\n def nextSeq[A](f: () => A, count: Int) = (for (i <- 0 until count) yield f())\n }\n \n implicit val tokenizer = new Tokenizer(Console.in)\n \n def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)\n def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)\n def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)\n def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))\n def nextSeq[A](f: () => A, count: Int = nextInt())(implicit t: Tokenizer) =\n (for (i <- 0 until count) yield f())\n}\n", "positive_code": [{"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n val Array(n, k) = readInts\n def ans = ((n to (n - k + 1)).by(-1) ++ (1 to n - k)).mkString(\" \")\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val nm = readLine().split(\" \").map(_.toInt)\n val n = nm(0)\n val m = nm(1)\n val a = (1 to n)\n val (head, tail) = a.splitAt(n - m - 1)\n println((head ++ tail.reverse).mkString(\" \"))\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main {\n\n def main(args: Array[String]): Unit = {\n var scan = new Scanner(System.in)\n val n = scan.nextInt()\n val k = scan.nextInt()\n val p = List.range(1, n + 1)\n val sorted = p.sorted(Ordering[Int].reverse)\n val (first, second) = sorted.splitAt(n - k - 1)\n val ans = second ::: first.sorted(Ordering[Int])\n val sb = new StringBuilder()\n ans.foreach(x => sb.append(x + \" \"))\n println(sb)\n }\n\n}"}, {"source_code": "object CF285A {\n def main(argv: Array[String]) {\n val in = new java.util.Scanner(System.in)\n val out = new java.io.PrintWriter(System.out)\n val n = in.nextInt\n val k = in.nextInt\n val d = n - k - 1\n val ans = (1 to d) ++ (n until d by -1)\n out.println(ans.mkString(\" \"))\n out.close\n }\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _285A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val k = next.toInt\n val a = (1 to n).toArray\n\n def reverse(l: Int, r: Int): Unit = {\n if (l < r) {\n val cb = a(l)\n a(l) = a(r)\n a(r) = cb\n reverse(l + 1, r - 1)\n }\n }\n\n reverse(0, k)\n println(a.mkString(\" \"))\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val r = (n to n - k + 1 by -1).toList ::: (1 until (n - k + 1)).toList\n println(r.mkString(\" \"))\n}"}, {"source_code": "object A285 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n val in = (1 to n).toArray\n val res = in.takeRight(k).reverse ++ in.take(n-k)\n println(res.mkString(\" \"))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object CF285A extends App {\n val in = new java.util.Scanner(System.in)\n val out = new java.io.PrintWriter(System.out)\n \n val n = in.nextInt\n val k = in.nextInt\n val e = n-k;\n val sol = (n until e by -1) ++ (1 to e)\n out.println(sol.mkString(\" \"))\n\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P285A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N, K = sc.nextInt\n\n val answer = {\n List.range(N, N - K, -1) ++ List.range(1, N - K + 1)\n }.mkString(\" \")\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "object SlightlyDecreasingPermutations extends App {\n\tvar n: Int = 0;\n\tvar k: Int = 0;\n\tval inputPattern = \"(\\\\d+) (\\\\d+)\".r;\n\tval inputPattern(tmpN,tmpK) = readLine;\n\tn = tmpN.toInt;\n\tk = tmpK.toInt;\n\n// StringBuilder sb = new StringBuilder(n*2);\n\tvar s: StringBuilder = new StringBuilder();\n\tfor (i <- n until n-k by -1) {\n\t s.append(i+\" \");\n\t}\n\n\tfor (i <- 1 to n-k) {\n\t s.append(i+\" \");\n\t}\n\n\tprintln(s.substring(0, s.length()-1));\n}"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _285A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val k = next.toInt\n val a = (1 to n).toArray\n\n def reverse(l: Int, r: Int): Unit = {\n if (l < r) {\n val cb = a(l)\n a(l) = a(r)\n a(r) = cb\n }\n }\n\n reverse(0, k)\n println(a.mkString(\" \"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val r = (k + 1 to n).toList ::: (1 until (k)).toList ::: List(k)\n println(r.mkString(\" \"))\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val r = (n - k + 1 to n).toList ::: List(n - k) ::: (1 until (n - k)).toList\n println(r.mkString(\" \"))\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val r = (n to k + 2 by -1).toList ::: (1 until (k + 2)).toList\n println(r.mkString(\" \"))\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val r = (n - k + 1 to n).toList ::: (1 until (n - k)).toList ::: List(n - k)\n println(r.mkString(\" \"))\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val r = (1 until (n - k)).toList ::: (n - k + 1 to n).toList ::: List(n - k)\n println(r.mkString(\" \"))\n}"}, {"source_code": "import scala.io._\nimport java.util.StringTokenizer\nimport java.io.BufferedReader\n\nobject Main {\n \n def main(args: Array[String]): Unit = {\n val N = nextInt\n val K = nextInt\n 1 to (N - K) foreach println\n N to K by -1 foreach println\n }\n \n class Tokenizer(in: BufferedReader, splitOn: String = \" \\n\\t\\r\\f\")\n {\n private var tokenizer = new StringTokenizer(\"\")\n def readLine() = in.readLine() \n def nextToken(): String = {\n while (!tokenizer.hasMoreTokens) {\n val line = readLine\n if (line == null) return null\n tokenizer = new StringTokenizer(line, splitOn)\n }\n tokenizer.nextToken\n } \n def next[A](f: String => A) = f(nextToken)\n def nextSeq[A](f: () => A, count: Int) = (for (i <- 0 until count) yield f())\n }\n \n implicit val tokenizer = new Tokenizer(Console.in)\n \n def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)\n def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)\n def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)\n def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))\n def nextSeq[A](f: () => A, count: Int = nextInt())(implicit t: Tokenizer) =\n (for (i <- 0 until count) yield f())\n}\n"}, {"source_code": "import scala.io._\nimport java.util.StringTokenizer\nimport java.io.BufferedReader\n\nobject Main {\n \n def main(args: Array[String]): Unit = {\n val N = nextInt\n val K = nextInt\n K to 1 by -1 foreach println\n (K+1) to N foreach println\n }\n \n class Tokenizer(in: BufferedReader, splitOn: String = \" \\n\\t\\r\\f\")\n {\n private var tokenizer = new StringTokenizer(\"\")\n def readLine() = in.readLine() \n def nextToken(): String = {\n while (!tokenizer.hasMoreTokens) {\n val line = readLine\n if (line == null) return null\n tokenizer = new StringTokenizer(line, splitOn)\n }\n tokenizer.nextToken\n } \n def next[A](f: String => A) = f(nextToken)\n def nextSeq[A](f: () => A, count: Int) = (for (i <- 0 until count) yield f())\n }\n \n implicit val tokenizer = new Tokenizer(Console.in)\n \n def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)\n def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)\n def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)\n def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))\n def nextSeq[A](f: () => A, count: Int = nextInt())(implicit t: Tokenizer) =\n (for (i <- 0 until count) yield f())\n}\n"}], "src_uid": "75cc5b55c51217966cbdd639a68f0724"} {"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nobject PowerUsage extends App {\n\n val s = new Scanner(System.in)\n\n import s._\n\n val (n, p1, p2, p3, t1, t2) = (nextInt(), nextInt(), nextInt(), nextInt(), nextInt(), nextInt())\n var intervals = (0 until n).map(_ => (nextInt(), nextInt()))\n intervals = intervals ++ List((intervals.last._2, intervals.last._2))\n var pow = 0\n\n for (\n (i1, i2) :: (i3, i4) :: _ <- intervals.sliding(2).toList.map(_.toList)\n ) yield {\n pow += p1 * (i2 - i1)\n //pow += p1 * (i4 - i3)\n val d = i3 - i2\n if (d > t1) {\n pow += t1 * p1\n val d1 = d - t1\n if (d1 > t2) {\n pow += t2 * p2\n val d2 = (d1 - t2)\n pow += d2 * p3\n } else {\n pow += d1 * p2\n }\n } else {\n pow += d * p1\n }\n }\n\n println(pow)\n\n}\n", "positive_code": [{"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val p1 = nextInt\n val p2 = nextInt\n val p3 = nextInt\n val t1 = nextInt\n val t2 = nextInt\n var result = 0\n var prev = 0\n for (i <- 0 until n) {\n val l = nextInt\n val r = nextInt\n if (i == 0) {\n prev = l\n }\n result += (r - l) * p1\n if (l - t1 > prev) {\n result += t1 * p1\n if (l - t1 - t2 > prev) {\n result += t2 * p2\n result += (l - t1 - t2 - prev) * p3\n } else {\n result += (l - prev - t1) * p2\n }\n } else {\n result += (l - prev) * p1\n }\n prev = r\n }\n out.println(result)\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "negative_code": [{"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nobject PowerUsage extends App {\n\n val s = new Scanner(System.in)\n\n import s._\n\n val (n, p1, p2, p3, t1, t2) = (nextInt(), nextInt(), nextInt(), nextInt(), nextInt(), nextInt())\n var intervals = (0 until n).map(_ => (nextInt(), nextInt()))\n if (intervals.size == 1) {\n intervals = intervals ++ List((intervals.head._2, intervals.head._2))\n }\n var pow = 0\n\n for (\n Seq((i1, i2), (i3, i4)) <- intervals.sliding(2).toSeq\n ) yield {\n pow += p1 * (i2 - i1)\n pow += p1 * (i4 - i3)\n val d = i3 - i2\n if (d > t1) {\n pow += t1 * p1\n val d1 = d - t1\n if (d1 > t2) {\n pow += t2 * p2\n val d2 = (d1 - t2)\n pow += d2 * p3\n } else {\n pow += d1 * p2\n }\n } else {\n pow += d * p1\n }\n }\n\n println(pow)\n\n}\n"}], "src_uid": "7ed9265b56ef6244f95a7a663f7860dd"} {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _677C extends CodeForcesApp {\n override def apply(io: IO) = {\n val s = io[String]\n val num = s map {c =>\n if(c >= '0' && c <= '9') {\n c - '0' + 0\n } else if (c >= 'A' && c <= 'Z') {\n c - 'A' + 10\n } else if (c >= 'a' && c <= 'z') {\n c - 'a' + 36\n } else if (c == '-') {\n 62\n } else {\n 63\n }\n }\n val ans = num.foldLeft(BigInt(1)) {case (p, n) =>\n val zeroes = 6 - n.bitCount\n val choices = BigInt(3).modPow(zeroes, mod)\n (p * choices) mod mod\n }\n\n io += ans\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def vector[A: IO.Read](n: Int): Vector[A] = apply[Vector, A](n)\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def array[A]: Write[Array[A]] = Write(_ mkString \" \")\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _677C extends CodeForcesApp {\n override def apply(io: IO) = {\n val s = io[String]\n val num = s map {c =>\n if(c >= '0' && c <= '9') {\n c - '0' + 0\n } else if (c >= 'A' && c <= 'Z') {\n c - 'A' + 10\n } else if (c >= 'a' && c <= 'z') {\n c - 'a' + 36\n } else if (c == '-') {\n 62\n } else {\n 63\n }\n }\n val zeroes = num.sumWith(i => 6 - i.bitCount)\n io += BigInt(3).modPow(zeroes, mod)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def bitCount: Int = java.lang.Integer.bitCount(x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def array[A]: Write[Array[A]] = Write(_ mkString \" \")\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "1b336555c94d5d5198abe5426ff6fa7a"} {"source_code": "/**\n * Author: Oleg Nizhnik\n * Date : 14.04.2015\n * Time : 16:01\n */\n\nimport scala.io.StdIn\n\nobject A extends App {\n val studs = StdIn.readInt() match {\n case 1 | 2 => List(1)\n case 3 => List(1, 3)\n case 4 => List(3, 1, 4, 2)\n case n if n % 2 == 1 => 1 to 2 * n by 2 map (_ % n + 1)\n case n => (1 to n by 2) ++ (2 to n by 2)\n }\n println(studs.length)\n println(studs mkString \" \")\n}\n", "positive_code": [{"source_code": "\nobject A524 extends App{\n\n var k = readInt\n var str = new StringBuilder\n k\n match {\n case 1 | 2 => println(1); println(1)\n case 3 => println(2); println(1 + \" \" + 3)\n case 4 => println(4); println(\"3 1 4 2\")\n case 5 => println(5); println(\"1 4 2 5 3\")\n case _ =>\n if (k % 2 == 0) {\n str.append(k + \"\\n\")\n for (i <- 1 until k / 2 + 1)\n str.append(i + \" \" + (k/2 + i) + \" \")\n }\n else {\n k -= 1\n str.append((k + 1) + \"\\n\" + (k + 1) + \" \")\n for (i <- 1 until k / 2 + 1)\n str.append(i + \" \" + (k/2 + i) + \" \")\n }\n\n println(str.toString)\n }\n}"}, {"source_code": "import java.io._\n\nobject Main {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n sys.addShutdownHook(out.close())\n\n @inline def nextInt = in.readLine().toInt\n @inline def nextInts = in.readLine().split(\" +\").map(_.toInt)\n @inline def println[T](x: T) = out.println(x)\n @inline def print[T](x: T) = out.print(x)\n\n def main(args: Array[String]): Unit = {\n val n = nextInt\n\n if (n <= 2)\n println(\"1\\n1\")\n else if (n == 3)\n println(\"2\\n1 3\")\n else {\n println(n)\n for (i ← (n + 1) / 2 to 1 by -1) print(s\"${i + i - 1} \")\n for (i ← n / 2 to 1 by -1) print(s\"${i + i} \")\n }\n }\n}"}, {"source_code": "object A534 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n if(n <= 2) {\n println(\"1\")\n println(\"1\")\n } else if(n == 3){\n println(\"2\")\n println(\"1 3\")\n } else if(n == 4){\n println(\"4\")\n println(\"3 1 4 2\")\n } else {\n println(n)\n println(((1 to n by 2) ++ (2 to n by 2)).mkString(\" \"))\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer;\nimport Ordering.Implicits._;\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def solve(): Unit = {\n val n = nextInt\n println(if (n <= 3) (n + 1) / 2 else n)\n for (i <- Range(if ((n & 1) == 1) n else n - 1, 0, -2))\n print(i + \" \")\n if (n >= 4) for (i <- Range(if ((n & 1) == 0) n else n - 1, 0, -2)) print(i + \" \")\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "object _534_A extends App {\n import java.util.Scanner\n\n import scala.collection.mutable\n\n lazy val file = getClass.getResourceAsStream(s\"${getClass.getSimpleName.replace(\"$\", \"\").last}.in\")\n val in = if (submit) new Scanner(System.in) else new Scanner(file)\n\n while(in.hasNext) println(apply(parseInput))\n /******************************************************************************************************/\n def submit = true // THIS MUST BE TRUE WHEN YOU SUBMIT !!!!\n\n type Input = Int\n\n def parseInput: Input = {\n import in._\n nextInt()\n }\n\n def apply(input: Input) = {\n val solution = input match {\n case 1 => List(1)\n case 2 => List(1)\n case 3 => List(1, 3)\n case 4 => List(3, 1, 4, 2)\n case n => List.tabulate((n+1)/2)(i => 2*i + 1) ++ List.tabulate(n/2)(i => 2*i + 2)\n }\n s\"${solution.size}\\n${solution mkString \" \"}\"\n }\n}\n"}], "negative_code": [{"source_code": "object A524 extends App{\n\n var k = readInt\n var str = new StringBuilder\n k\n match {\n case 1 | 2 => println(1); println(1)\n case 3 | 4 => println(2); println(1 + \" \" + 3)\n case 5 => println(5); println(\"1 4 2 5 3\")\n case _ =>\n if (k % 2 == 0) {\n str.append(k + \"\\n\")\n for (i <- 1 until k / 2 + 1)\n str.append(i + \" \" + (k/2 + i) + \" \")\n }\n else {\n k -= 1\n str.append((k + 1) + \"\\n\" + (k + 1) + \" \")\n for (i <- 1 until k / 2 + 1)\n str.append(i + \" \" + (k/2 + i) + \" \")\n }\n\n println(str.toString)\n }\n}"}, {"source_code": "import java.io._\n\nobject Main {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n sys.addShutdownHook(out.close())\n\n @inline def nextInt = in.readLine().toInt\n @inline def nextInts = in.readLine().split(\" +\").map(_.toInt)\n @inline def println[T](x: T) = out.println(x)\n @inline def print[T](x: T) = out.print(x)\n\n def main(args: Array[String]): Unit = {\n val n = nextInt\n\n val used = collection.mutable.Set[Int](1)\n var ans: List[Int] = 1 :: Nil\n\n for (i ← 1 to n) {\n for (j ← 1 to n) {\n if (!(used contains j) && Math.abs(j - ans.head) > 1) {\n used += j\n ans = j :: ans\n }\n }\n }\n\n println(ans.length)\n println(ans.mkString(\" \"))\n }\n}"}, {"source_code": "import java.io._\n\nobject Main {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n sys.addShutdownHook(out.close())\n\n @inline def nextInt = in.readLine().toInt\n @inline def nextInts = in.readLine().split(\" +\").map(_.toInt)\n @inline def println[T](x: T) = out.println(x)\n @inline def print[T](x: T) = out.print(x)\n\n def main(args: Array[String]): Unit = {\n val n = nextInt\n\n val used = collection.mutable.Set[Int](1)\n var ans: List[Int] = 1 :: Nil\n\n for (i ← 1 to n) {\n var done = false\n for (j ← 1 to n) {\n if (!done && !(used contains j) && Math.abs(j - ans.head) > 1) {\n used += j\n done = true\n ans = j :: ans\n }\n }\n }\n\n println(ans.length)\n println(ans.mkString(\" \"))\n }\n}"}, {"source_code": "/**\n * Author: Oleg Nizhnik\n * Date : 14.04.2015\n * Time : 16:01\n */\nimport scala.io.StdIn\n\nobject A extends App {\n val studs = StdIn.readInt() match {\n case 1 | 2 => Nil\n case 3 => List(1, 3)\n case 4 => List(3, 1, 4, 2)\n case n if n % 2 == 1 => 1 to 2 * n by 2 map (_ % n)\n case n => (1 to n by 2) ++ (2 to n by 2)\n }\n println(studs.length)\n println(studs mkString \" \")\n}\n"}, {"source_code": "/**\n * Author: Oleg Nizhnik\n * Date : 14.04.2015\n * Time : 16:01\n */\n\nimport scala.io.StdIn\n\nobject A extends App {\n val studs = StdIn.readInt() match {\n case 1 => Nil\n case 2 => List(1)\n case 3 => List(1, 3)\n case 4 => List(3, 1, 4, 2)\n case n if n % 2 == 1 => 1 to 2 * n by 2 map (_ % n + 1)\n case n => (1 to n by 2) ++ (2 to n by 2)\n }\n println(studs.length)\n println(studs mkString \" \")\n}\n"}, {"source_code": "/**\n * Author: Oleg Nizhnik\n * Date : 14.04.2015\n * Time : 16:01\n */\nimport scala.io.StdIn\n\nobject A extends App {\n val studs = StdIn.readInt() match {\n case 1 | 2 => Nil\n case 3 => List(1, 3)\n case 4 => List(3, 1, 4, 2)\n case n if n % 2 == 1 => 1 to 2 * n by 2 map (_ % n + 1)\n case n => (1 to n by 2) ++ (2 to n by 2)\n }\n println(studs.length)\n println(studs mkString \" \")\n}\n"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer;\nimport Ordering.Implicits._;\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def solve(): Unit = {\n val n = nextInt\n println(if (n <= 4) (n + 1) / 2 else n)\n for (i <- Range(1, n + 1, 2))\n print(i + \" \")\n if (n > 4) for (i <- Range(2, n + 1, 2)) print(i + \" \")\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer;\nimport Ordering.Implicits._;\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def solve(): Unit = {\n val n = nextInt\n for (i <- Range(1, n + 1, 2))\n print(i + \" \")\n if (n > 4) for (i <- Range(2, n + 1, 2)) print(i + \" \")\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer;\nimport Ordering.Implicits._;\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def solve(): Unit = {\n val n = nextInt\n println(if (n <= 4) n / 2 else n)\n for (i <- Range(1, n + 1, 2))\n print(i + \" \")\n if (n > 4) for (i <- Range(2, n + 1, 2)) print(i + \" \")\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "object _534_A extends App {\n import java.util.Scanner\n\n import scala.collection.mutable\n\n lazy val file = getClass.getResourceAsStream(s\"${getClass.getSimpleName.replace(\"$\", \"\").last}.in\")\n val in = if (submit) new Scanner(System.in) else new Scanner(file)\n\n while(in.hasNext) println(apply(parseInput))\n /******************************************************************************************************/\n def submit = true // THIS MUST BE TRUE WHEN YOU SUBMIT !!!!\n\n type Input = Int\n\n def parseInput: Input = {\n import in._\n nextInt()\n }\n\n def apply(input: Input) = {\n val solution = input match {\n case 1 => List(1)\n case 2 => List(1)\n case 3 => List(1, 3)\n case 4 => List(1, 4, 2)\n case n => List.tabulate((n+1)/2)(i => 2*i + 1) ++ List.tabulate(n/2)(i => 2*i + 2)\n }\n s\"${solution.size}\\n${solution mkString \" \"}\"\n }\n}\n"}, {"source_code": "object _534_A extends App {\n import java.util.Scanner\n\n import scala.collection.mutable\n\n lazy val file = getClass.getResourceAsStream(s\"${getClass.getSimpleName.replace(\"$\", \"\").last}.in\")\n val in = if (submit) new Scanner(System.in) else new Scanner(file)\n\n while(in.hasNext) println(apply(parseInput))\n /******************************************************************************************************/\n def submit = true // THIS MUST BE TRUE WHEN YOU SUBMIT !!!!\n\n type Input = Int\n\n def parseInput: Input = {\n import in._\n nextInt()\n }\n\n def apply(input: Input) = {\n val solution = input match {\n case 1 => List(1)\n case 2 => List(1)\n case 3 => List(1, 3)\n case 4 => List(1, 4, 2, 3)\n case n => List.tabulate((n+1)/2)(i => 2*i + 1) ++ List.tabulate(n/2)(i => 2*i + 2)\n }\n s\"${solution.size}\\n${solution mkString \" \"}\"\n }\n}\n"}], "src_uid": "a52ceb8a894809b570cbb74dc5ef76e1"} {"source_code": "import java.util.Scanner\n\n/**\n * Created by hama_du on 2014/06/21.\n */\nobject ProblemB extends App {\n def solve(persons: Array[Double]): Double = {\n if (persons.size == 1) {\n return persons(0)\n }\n val inverse = persons.map(p => 1.0d - p).fold(1.0)((a, b) => a * b)\n persons.map(p => p * inverse / (1.0d - p)).sum\n }\n\n val in = new Scanner(System.in)\n val n = in.nextInt\n val persons = (0 until n).map(_ => in.nextDouble()).sorted\n if (persons.max >= 1.0d) {\n println(1.0)\n } else {\n val answers = for {\n i <- 0 until n\n j <- i+1 to n\n } yield solve(persons.slice(i, j).toArray)\n println(answers.max)\n }\n}\n", "positive_code": [{"source_code": "\nobject Main {\n\n def main(args: Array[String]) {\n val lines = io.Source.stdin.getLines.toList\n val friendCountLine :: probabilityLine :: Nil = lines\n\n val friendCount = friendCountLine.toInt\n val probabilities = probabilityLine.split(\" \").map(_.toDouble).toList\n\n val solution = solve(probabilities)\n print(solution)\n }\n\n def solve(probabilities: List[Double]): Double = {\n def tryNext(probabilities: List[Double], lastSolution: Double, friendAmount: Int): Double = {\n if(friendAmount > probabilities.size){\n lastSolution\n } else {\n val toCheck = probabilities.take(friendAmount)\n val actualSolution = calculateFor(toCheck)\n if(actualSolution <= lastSolution){\n lastSolution\n } else {\n tryNext(probabilities, actualSolution, friendAmount + 1)\n }\n }\n }\n\n val sortedProbabilities = probabilities.sorted.reverse\n tryNext(sortedProbabilities, 0, 1)\n }\n\n def calculateFor(probabilities: List[Double]) = {\n if(probabilities.size == 1){\n probabilities.head\n } else {\n val personProbabilities = for ((probability1, ix1) <- probabilities zip Stream.from(0)) yield {\n val otherPeopleReverses = for ((probability2, ix2) <- probabilities zip Stream.from(0) if ix1 != ix2) yield (1 - probability2)\n val otherPeople = otherPeopleReverses.fold(1d)(_ * _)\n probability1 * otherPeople\n }\n personProbabilities.fold(0d)(_ + _)\n }\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject D {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n var ans = 0.0d\n val values = new Array[Double](n)\n for (i <- 0 until n) {\n values(i) = nextDouble\n ans = Math.max(ans, values(i))\n }\n val sortedValues = values.sorted\n\n for (i <- 2 to n) {\n var sum = 0.0d\n for (j <- n - 1 to n - i by -1) {\n var partSum = sortedValues(j)\n for (k <- n - 1 to n - i by -1) {\n if (k != j) {\n partSum *= (1.0d - sortedValues(k))\n }\n }\n sum += partSum\n }\n ans = Math.max(ans, sum)\n }\n out.println(ans)\n return 0\n }\n}\n"}, {"source_code": "\nimport scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject Main extends App {\n def singleHappensProbability(probabilities: List[Double]): Double = {\n if (probabilities.isEmpty) 0\n else {\n val variousOptions = probabilities.indices map { i =>\n val probabilityPerPerson = probabilities.indices map { j =>\n if (i == j) probabilities(j) else 1 - probabilities(j)\n }\n\n probabilityPerPerson.product\n }\n\n variousOptions.sum\n }\n }\n\n @tailrec\n private def isNextBetter(x: Double, y: Double, rem: List[Double]): Double = {\n if (rem.isEmpty) x\n else {\n val p = rem.head\n val nextX = x * (1-p) + p * y\n if (nextX > x) {\n val nextY = y * (1-p)\n isNextBetter(nextX, nextY, rem.tail)\n } else {\n x\n }\n }\n }\n\n def solve(probabilities: List[Double]): Double = {\n greedy(probabilities)\n }\n\n private def greedy(probabilities: List[Double]): Double = {\n val sorted = probabilities.sorted(Ordering.Double.reverse)\n val p0 = sorted.head\n isNextBetter(p0, 1 - p0, sorted.tail)\n }\n\n private def fullCheck(probabilities: List[Double], acc: List[Double] = Nil): Double = {\n if (probabilities.isEmpty) {\n singleHappensProbability(acc)\n } else {\n Math.max(\n fullCheck(probabilities.tail, acc),\n fullCheck(probabilities.tail, probabilities.head :: acc)\n )\n }\n }\n\n val n = StdIn.readLine().toInt\n val data = StdIn.readLine().split(\" \").map(_.toDouble)\n require(data.length == n, s\"Expected $n values but got $data\")\n\n val result = solve(data.toList)\n\n println(result)\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject D {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n var ans = 0.0d\n val values = new Array[Double](n)\n for (i <- 0 until n) {\n values(i) = nextDouble\n ans = Math.max(ans, values(i))\n }\n val sortedValues = values.sorted\n\n for (i <- 2 to n) {\n var sum = 0.0d\n for (j <- n - 1 until n - i by -1) {\n var partSum = sortedValues(j)\n for (k <- n - 1 until n - i by -1) {\n if (k != j) {\n partSum *= (1.0d - sortedValues(k))\n }\n }\n sum += partSum\n ans = Math.max(ans, sum)\n }\n }\n out.println(ans)\n return 0\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject D {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n var ans = 0.0d\n val values = new Array[Double](n)\n for (i <- 0 until n) {\n values(i) = nextDouble\n ans = Math.max(ans, values(i))\n }\n var sum = 0.0d\n for (i <- 0 until n) {\n var partSum = values(i)\n for (j <- 0 until n) {\n if (j != i) {\n partSum *= (1.0d - values(j))\n }\n }\n sum += partSum\n }\n ans = Math.max(ans, sum)\n out.println(ans)\n return 0\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject Main extends App {\n def singleHappensProbability(probabilities: List[Double]): Double = {\n if (probabilities.isEmpty) 0\n else {\n val variousOptions = probabilities.indices map { i =>\n val probabilityPerPerson = probabilities.indices map { j =>\n if (i == j) probabilities(j) else 1 - probabilities(j)\n }\n\n probabilityPerPerson.product\n }\n\n variousOptions.sum\n }\n }\n\n @tailrec\n def f(x: Double, rem: List[Double]): Double = {\n if (rem.isEmpty) x\n else {\n val y = rem.head\n val next = x + y - 2*x*y\n if (next > x) {\n f(next, rem.tail)\n } else {\n x\n }\n }\n }\n\n def solve(probabilities: List[Double]): Double = {\n val sorted = probabilities.sorted(Ordering.Double.reverse)\n f(sorted.head, sorted.tail)\n }\n\n val n = StdIn.readLine().toInt\n val data = StdIn.readLine().split(\" \").map(_.toDouble)\n require(data.length == n, s\"Expected $n values but got $data\")\n\n val result = solve(data.toList)\n\n println(result)\n}\n"}], "src_uid": "b4ac594755951e84001dfd610d420eb5"} {"source_code": "import io.StdIn._\n\nobject Main{\n def main (args: Array[String]){\n val m = readLine.split(' ').map(_.toInt)\n val w = readLine.split(' ').map(_.toInt)\n\n val Array(hs, hu) = readLine.split(' ').map(_.toInt)\n\n var sum = 0\n for(i <- 1 to 5){\n // if(m(i-1) > 0){\n sum += Math.max(150*i, (250-m(i-1))*2*i-50*w(i-1)).toInt\n // }\n }\n\n sum += hs * 100\n sum -= hu * 50\n\n println(sum)\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val data = in.next().split(' ').map(_.toInt)\n .zip(List(500, 1000, 1500, 2000, 2500))\n .zip(in.next().split(' ').map(_.toInt))\n .map {\n case((time, maxScore), trys) => Math.max(maxScore * 3 / 10, maxScore - time * maxScore / 250 - 50 * trys)\n }.sum\n val Array(s, f) = in.next().split(' ').map(_.toInt)\n println(data + 100 * s - 50 * f)\n\n}\n"}, {"source_code": "object A604 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val x = Array(500, 1000, 1500, 2000, 2500)\n val m = readInts(5)\n val w = readInts(5)\n val Array(hs, hu) = readInts(2)\n\n var score = 0.0d\n score += hs*100\n score -= hu*50\n for(i <- 0 until 5) {\n score += math.max(0.3*x(i), (((250 - m(i))*x(i))/250)-(50*w(i)))\n }\n\n println(score.toLong)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val xs = Array(500, 1000, 1500, 2000, 2500)\n val ms = readInts(5)\n val ws = readInts(5)\n val ts = readInts(2)\n\n var res = 0L\n \n for (i <- 0 until 5) {\n res += Math.max(3 * xs(i) / 10, (xs(i) - xs(i) * ms(i) / 250) - 50 * ws(i)) \n }\n \n res += ts(0) * 100 - ts(1) * 50\n \n println(res)\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 14 May 2016\n */\nobject A604 extends App {\n\n val x: Array[Int] = Array(500, 1000, 1500, 2000, 2500)\n val m: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val w: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val Array(hs, hu): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n // max(0.3x, (1 - m/250)x - 50w)\n // max(0.3x, (250 - m)x/250 - 50w)\n // max(3x/10, [(250 - m)x - 250*50w]/250)\n // 250 * max(25*3x, (250 - m)x - 250*50w)\n\n val sum: Long = (0 until 5).map(i => 1L * Math.max(25*3*x(i), (250-m(i))*x(i) - 250*50*w(i)) / 250).sum\n println(sum + 100L*hs - 50L*hu)\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _604A extends CodeForcesApp {\n override type Result = Int\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val xs = Seq(500, 1000, 1500, 2000, 2500)\n val ms = Seq.fill(5)(nextInt())\n val ws = Seq.fill(5)(nextInt())\n\n val t = (xs zip ms zip ws) map {\n case ((x, m), w) =>\n (0.3 * x) max (((250 - m) * (x/250)) - (50 * w)).toDouble\n }\n\n t.sum.toInt + (100 * nextInt()) + (-50 * nextInt())\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n val mod: Int = 1000000007\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val P = Array(500, 1000, 1500, 2000, 2500)\n\n val M = readLine().split(\" \").map(_.toInt)\n val W = readLine().split(\" \").map(_.toInt)\n val Array(hs, hu) = readLine().split(\" \").map(_.toInt)\n\n var total = 0\n\n for (i <- 0 until 5) {\n val left = 75 * P(i)\n val right = (250 - M(i)) * P(i) - 50 * 250 * W(i)\n\n val points = if (left > right) left.toInt else right.toInt\n\n total += points\n }\n\n total /= 250\n\n total += 100 * hs - 50 * hu\n\n println(total)\n}\n"}, {"source_code": "object A{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val x=Array[Double](500.0, 1000.0, 1500.0, 2000.0, 2500.0)\n val m=for(i<-0 until 5) yield nextDouble\n val w=for(i<-0 until 5) yield nextDouble\n val hs=nextInt\n val hu=nextInt\n var sum:Double=0\n for(i<-0 until 5){\n sum+=math.max(0.3*x(i),(1-m(i)/250.0)*x(i)-50*w(i))\n }\n \n out.println((sum+0.3).toInt+100*hs-50*hu)\n\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "/*\n * Reference: http://lizan.asia/blog/2012/12/11/scala-competitive/\n */\n\nobject Main extends App {\n import java.{util => ju}\n import scala.annotation._\n import scala.collection._\n import scala.collection.{mutable => mu}\n import scala.collection.JavaConverters._\n import scala.math._\n\n val sc = new ju.Scanner(System.in)\n\n val m = Array.fill(5)(sc.nextInt)\n val w = Array.fill(5)(sc.nextInt)\n val x = Array.tabulate(5)(i => (i + 1) * 500)\n val hs, hu = sc.nextInt\n var tot = 0\n 0 until 5 foreach {\n i => tot += (3 * x(i) / 10) max ((x(i) - x(i) * m(i) / 250) - 50 * w(i))\n }\n println(tot + 100 * hs - 50 * hu)\n}"}, {"source_code": "/*\n * Reference: http://lizan.asia/blog/2012/12/11/scala-competitive/\n */\n\nobject Main extends App {\n import java.{util => ju}\n import scala.annotation._\n import scala.collection._\n import scala.collection.{mutable => mu}\n import scala.collection.JavaConverters._\n import scala.math._\n\n val sc = new ju.Scanner(System.in)\n\n val m = Array.fill(5)(sc.nextInt)\n val w = Array.fill(5)(sc.nextInt)\n val x = Array.tabulate(5)(i => (i + 1) * 500)\n val hs, hu = sc.nextInt\n println((0 until 5).map(i => (3 * x(i) / 10) max (x(i) - x(i) * m(i) / 250 - 50 * w(i))).sum + 100 * hs - 50 * hu)\n}"}], "negative_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _604A extends CodeForcesApp {\n override type Result = Int\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val xs = Seq(500, 1000, 1500, 2000, 2500)\n val ms = Seq.fill(5)(nextInt())\n val ws = Seq.fill(5)(nextInt())\n\n val t = (xs zip ms zip ws) map {\n case ((x, m), w) =>\n (0.3 * x) max (((250 - m) * (x/250)) - (50 * w)).toDouble\n }\n\n t.sum.toInt + (100 * nextInt()) + (50 * nextInt())\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n val mod: Int = 1000000007\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}, {"source_code": "import io.StdIn._\n\nobject Main{\n def main (args: Array[String]){\n val m = readLine.split(' ').map(_.toInt)\n val w = readLine.split(' ').map(_.toInt)\n\n val Array(hs, hu) = readLine.split(' ').map(_.toInt)\n\n var sum = 0\n for(i <- 1 to 5){\n if(m(i-1) > 0){\n sum += Math.max(150*i, (250-m(i-1))*2*i-50*w(i-1)).toInt\n }\n }\n\n sum += hs * 100\n sum -= hu * 50\n\n println(sum)\n }\n}\n"}], "src_uid": "636a30a2b0038ee1731325a5fc2df73a"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N, K = ni()\n val A = na(N)\n var ans = -1\n var fk = 1e9.toInt + 10\n REP(N - K) { i =>\n val x = (A(i) + A(i + K)) / 2\n val y = max(A(i + K) - x, x - A(i))\n if (y < fk) {\n fk = y\n ans = x\n }\n }\n out.println(ans)\n }\n }\n}", "positive_code": [{"source_code": "//package codeforces\n\n/*\nhttps://codeforces.com/contest/1175/problem/C\n */\nobject Electrification {\n def main(args: Array[String]): Unit = {\n println((1 to io.StdIn.readInt).map { _ =>\n val Array(n, k) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val seq = io.StdIn.readLine().split(\" \")\n\n (0 until n - k).map {\n i =>\n val res = (seq(i + k).toInt + seq(i).toInt) / 2\n (res, (seq(i + k).toInt - res) max (res - seq(i).toInt))\n }.minBy(_._2)._1\n\n }.mkString(\"\\n\"))\n }\n}\n"}], "negative_code": [], "src_uid": "87e39e14d6e33427148c284b16a7fb13"} {"source_code": "import java.util\n\nobject Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline private final def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val pow = Array.ofDim[Int](2e5.toInt)\n REP(ni()) { _ =>\n val N = ni()\n val A = na(N)\n\n util.Arrays.fill(pow, 0, N, 0)\n REP(ni()) { _ =>\n val p = ni()\n val s = ni() - 1\n pow(s) = max(pow(s), p)\n }\n REP_r(N - 1) { i =>\n pow(i) = max(pow(i + 1), pow(i))\n }\n\n debug(pow.take(N))\n\n var days = 0\n var i = 0\n while(i < N && days != -1) {\n val s = i\n var mx = A(i)\n while (i < N && mx <= pow(i - s)) {\n i += 1\n if (i < N) mx = max(mx, A(i))\n }\n\n debug(s\"i:$i A:$mx\")\n\n if (i == s) days = -1\n else days += 1\n }\n out.println(days)\n }\n }\n}", "positive_code": [{"source_code": "object D1257 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var t = readInt\n while (t > 0) {\n val n = readInt\n val mons = readInts(n)\n val m = readInt\n // max hero power whose endurance is >= i\n val best = Array.fill(n + 1)(0)\n val heros = Array\n .fill(m)(readInts(2))\n var i = 0\n while (i < m) {\n best(heros(i)(1)) = math.max(best(heros(i)(1)), heros(i)(0))\n i += 1\n }\n i = n - 1\n while (i >= 0) {\n best(i) = math.max(best(i), best(i + 1))\n i -= 1\n }\n\n if (mons.max > best(1)) {\n out.println(-1)\n } else {\n var day = 0\n var idx = 0\n while (idx < n) {\n var heroPos = 1\n var max = 0\n while (idx < n && math.max(max, mons(idx)) <= best(heroPos)) {\n max = math.max(max, mons(idx))\n heroPos += 1\n idx += 1\n }\n day += 1\n }\n out.println(day)\n }\n t -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n\n def findMax(f: Int => Boolean, min: Int, max: Int): Int = {\n var l = min\n var h = max + 1\n while(h - l > 1) {\n val x = (h + l) / 2\n if (f(x)) l = x\n else h = x\n }\n l\n }\n case class Hero(power: Int, endurance: Int)\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n import java.util.Comparator\n val N = ni()\n val A = na(N)\n val heroes = mutable.Map[Int, Hero]()\n REP(ni()) { _ =>\n val p, s = ni()\n if (heroes.contains(s)) {\n if (p > heroes(s).power) {\n heroes(s) = Hero(p, s)\n }\n } else {\n heroes(s) = Hero(p, s)\n }\n }\n val H2 = heroes.toArray.map(_._2)\n // enduranceの昇順はpowerの降順になる\n sort(H2, new Comparator[Hero] {\n override def compare(o1: Hero, o2: Hero): Int = Integer.compare(o1.endurance, o2.endurance)\n })\n val H_buff = ArrayBuffer[Hero]()\n var mxPow = 0\n REP_r(H2.length) { i =>\n if (H2(i).power >= mxPow) H_buff += H2(i)\n mxPow = max(mxPow, H2(i).power)\n }\n\n val H = H_buff.reverse.toArray\n debug(H.mkString(\" \"))\n\n if (H.maxBy(_.power).power < A.max) {\n out.println(-1)\n } else {\n val M = H.length\n\n var i = 0\n var days = 0\n var j = M - 1\n\n while (i < N) {\n val s = i\n var continue = true\n while (i < N && continue) {\n def test(ix: Int): Boolean = {\n H(ix).power >= A(i)\n }\n\n j = findMax(test, 0, j)\n if (H(j).power >= A(i) && H(j).endurance >= i - s + 1) {\n i += 1 // defeat\n } else {\n continue = false // retreat\n }\n }\n assert(i > s)\n days += 1\n }\n out.println(days)\n }\n }\n }\n}"}, {"source_code": "object D1257 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var t = readInt\n while (t > 0) {\n val n = readInt\n val mons = readInts(n)\n val m = readInt\n val heros = Array\n .fill(m)(readInts(2))\n .map(a => (a(0), a(1)))\n .sortBy(-_._1) // sorted by Power, endurance\n if (mons.max > heros.head._1) {\n out.println(-1)\n } else {\n val maxEnduranceAfterThis = {\n val arr = Array.fill(m)(0)\n arr(0) = 0\n var curr = 0\n var i = 0\n while (i < m) {\n if (heros(i)._2 > heros(curr)._2) {\n curr = i\n }\n arr(i) = curr\n i += 1\n }\n arr\n }\n var day = 0\n var i = 0\n while (i < n) {\n var s = 0\n var e = m - 1\n var valid = -1\n while (s <= e) {\n val mid = (s + e) / 2\n if (heros(mid)._1 >= mons(i)) {\n valid = mid\n s = mid + 1\n } else {\n e = mid - 1\n }\n }\n i += 1\n var enduranceLeft = heros(maxEnduranceAfterThis(valid))._2 - 1\n while (i < n && enduranceLeft > 0) {\n if (heros(maxEnduranceAfterThis(valid))._1 >= mons(i)) {\n enduranceLeft -= 1\n i += 1\n } else {\n enduranceLeft = 0\n }\n }\n day += 1\n }\n out.println(day)\n }\n t -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "6aa01cf719d2ac1dfe80b00e6eda438c"} {"source_code": "object ProblemA extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n for (_ <- 1 to t) {\n val a = in.nextInt()\n val b = in.nextInt()\n\n var res = (a / 2) * b\n if (a % 2 == 1) {\n res = res + (b / 2) + (if (b % 2 == 1 ) 1 else 0)\n }\n\n println(res)\n }\n\n\n}", "positive_code": [{"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, m) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ans = m / 2 * n + (n * (m - m / 2 * 2) + 1) / 2\n\n println(ans)\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject A {\n\n import scala.math._\n def solution(n: Int, m: Int): Int = {\n val (a, b) = (min(n, m), max(n, m))\n (a / 2) * b + (if (a % 2 == 0) 0 else (b + 1) / 2)\n }\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val Seq(n, k) = readLine.split(\" \").toSeq.map(_.toInt)\n println(solution(n, k))\n }\n }\n}"}], "negative_code": [], "src_uid": "19df5f3b8b31b763162c5331c1499529"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M, K = ni()\n val C = nal(N)\n case class Edge(u: Int, v: Int)\n val xorSets = mutable.Map[Long, ArrayBuffer[Edge]]()\n rep(M) { _ =>\n val v, u = ni() - 1\n val x = C(v) ^ C(u)\n if (!xorSets.contains(x)) xorSets(x) = ArrayBuffer()\n xorSets(x) += Edge(v, u)\n }\n\n def minus(a: Long, b: Long) = (MOD + a - b) % MOD\n\n var ans = 0L\n ans += powMod(2, N) * minus(powMod(2, K), xorSets.size) % MOD\n xorSets foreach { case (_, es) =>\n val zip = new Zipper()\n es foreach { e =>\n zip(e.u)\n zip(e.v)\n }\n val uf = new UnionFind(zip.length)\n es foreach { e =>\n uf.unite(zip(e.u), zip(e.v))\n }\n\n ans += powMod(2, N - zip.length + countDisjointSets(uf)) // esに含まれないノードはすべて単独で連結成分になるので disjointSets(V) = |V| - |S| + disjointSets(S)\n }\n\n ans = ans % MOD\n\n out.println(ans)\n }\n\n class Zipper {\n type A = Int\n var gen = 0\n val id = mutable.HashMap[A, Int]()\n\n def apply(x: A): Int = {\n id.getOrElseUpdate(x, {\n val i = gen\n gen += 1\n i\n })\n }\n\n def length: Int = gen\n }\n\n def powMod(x: Int, n: Int): Int = {\n val m = MOD\n def step(x: Long, n: Int, stack: Long): Long = {\n n match {\n case 0 => stack\n case _ => step(x * x % m, n / 2, if (n % 2 == 1) stack * x % m else stack)\n }\n }\n step(x, n, 1).toInt\n }\n\n class UnionFind(val n: Int) {\n private val par = Array.ofDim[Int](n)\n par.indices foreach (i => par(i) = i)\n private val rank = Array.ofDim[Int](n)\n\n def find(x: Int): Int = {\n val stack = ListBuffer[Int]()\n def step(x: Int): Int = {\n if (par(x) == x) x\n else {\n stack += x\n step(par(x))\n }\n }\n\n val res = step(x)\n stack foreach (i => par(i) = res)\n res\n }\n\n def unite(x: Int, y: Int): Unit = {\n val x1 = find(x)\n val y1 = find(y)\n if (x1 != y1) {\n if (rank(x1) < rank(y)) {\n par(x1) = y1\n } else {\n par(y1) = x1\n if (rank(x1) == rank(y1)) rank(x1) += 1\n }\n }\n }\n }\n\n def countDisjointSets(uf: UnionFind): Int = {\n var cnt = 0\n rep(uf.n) { i =>\n if (uf.find(i) == i) cnt += 1\n }\n cnt\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M, K = ni()\n val C = nal(N)\n case class Edge(u: Int, v: Int)\n val xorSets = mutable.Map[Long, ArrayBuffer[Edge]]()\n rep(M) { _ =>\n val v, u = ni() - 1\n val x = C(v) ^ C(u)\n if (!xorSets.contains(x)) xorSets(x) = ArrayBuffer()\n xorSets(x) += Edge(v, u)\n }\n\n def minus(a: Long, b: Long) = (MOD + a - b) % MOD\n\n val pow2 = Array.ofDim[Int](max(N, K) + 1)\n pow2(0) = 1\n rep(pow2.length - 1)(i => pow2(i + 1) = pow2(i) * 2 % MOD)\n\n var ans = 0L\n ans += pow2(N) * minus(pow2(K), xorSets.size) % MOD\n xorSets foreach { case (_, es) =>\n val zip = new Zipper()\n es foreach { e =>\n zip(e.u)\n zip(e.v)\n }\n val uf = new UnionFind(zip.length)\n es foreach { e =>\n uf.unite(zip(e.u), zip(e.v))\n }\n\n ans += pow2(N - zip.length + countDisjointSets(uf)) // esに含まれないノードはすべて単独で連結成分になるので disjointSets(V) = |V| - |S| + disjointSets(S)\n }\n\n ans = ans % MOD\n\n out.println(ans)\n }\n\n class Zipper {\n type A = Int\n var gen = 0\n val id = mutable.HashMap[A, Int]()\n\n def apply(x: A): Int = {\n id.getOrElseUpdate(x, {\n val i = gen\n gen += 1\n i\n })\n }\n\n def length: Int = gen\n }\n\n class UnionFind(val n: Int) {\n private val par = Array.ofDim[Int](n)\n par.indices foreach (i => par(i) = i)\n private val rank = Array.ofDim[Int](n)\n\n def find(x: Int): Int = {\n val stack = ListBuffer[Int]()\n def step(x: Int): Int = {\n if (par(x) == x) x\n else {\n stack += x\n step(par(x))\n }\n }\n\n val res = step(x)\n stack foreach (i => par(i) = res)\n res\n }\n\n def unite(x: Int, y: Int): Unit = {\n val x1 = find(x)\n val y1 = find(y)\n if (x1 != y1) {\n if (rank(x1) < rank(y)) {\n par(x1) = y1\n } else {\n par(y1) = x1\n if (rank(x1) == rank(y1)) rank(x1) += 1\n }\n }\n }\n }\n\n def countDisjointSets(uf: UnionFind): Int = {\n var cnt = 0\n rep(uf.n) { i =>\n if (uf.find(i) == i) cnt += 1\n }\n cnt\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M, K = ni()\n val C = nal(N)\n val xorSets = mutable.Map[Long, mutable.Set[Int]]()\n rep(M) { _ =>\n val v, u = ni() - 1\n val x = C(v) ^ C(u)\n if (!xorSets.contains(x)) xorSets(x) = mutable.Set()\n xorSets(x) ++= Set(v, u)\n }\n\n def minus(a: Long, b: Long) = (MOD + a - b) % MOD\n\n var ans = 0L\n ans += powMod(2, N) * minus(powMod(2, K), xorSets.size) % MOD\n xorSets foreach { case (_, set) =>\n ans += powMod(2, N - set.size + 1)\n }\n\n ans = ans % MOD\n\n out.println(ans)\n }\n\n def powMod(x: Int, n: Int): Int = {\n val m = MOD\n def step(x: Long, n: Int, stack: Long): Long = {\n n match {\n case 0 => stack\n case _ => step(x * x % m, n / 2, if (n % 2 == 1) stack * x % m else stack)\n }\n }\n step(x, n, 1).toInt\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}], "src_uid": "9319661488d33bd0b43a5ff8b238f694"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map{_ =>\n val Array(v, d, p) = in.next().split(\" \").map(_.toInt)\n (v, d, p)\n }.toArray\n var result = List.empty[Int]\n\n def decreaseAll(willCry: List[Int]): Unit = {\n var willCryN = List.empty[Int]\n var dec = data(willCry.head)._2\n var willCryVar = willCry.tail\n (willCry.head + 1 to data.length - 1).foreach {i =>\n if (data(i)._3 >= 0) {\n val newP = data(i)._3 - dec\n data(i) = (data(i)._1, data(i)._2, newP)\n if (newP < 0)\n willCryN ::= i\n }\n if (willCryVar.nonEmpty && willCryVar.head == i) {\n dec += data(willCryVar.head)._2\n willCryVar = willCryVar.tail\n }\n }\n if (willCryN.nonEmpty)\n decreaseAll(willCryN.reverse)\n }\n\n def decreaseSeq(i: Int) = {\n val (v, d, p) = data(i)\n var j = i + 1\n var j1 = v\n var willCry = List.empty[Int]\n while (j < data.length && j1 > 0) {\n if (data(j)._3 >= 0) {\n val newP = data(j)._3 - j1\n j1 -= 1\n data(j) = (data(j)._1, data(j)._2, newP)\n if (newP < 0)\n willCry ::= j\n }\n j += 1\n }\n if (willCry.nonEmpty)\n decreaseAll(willCry.reverse)\n }\n\n data.indices.foreach { i =>\n val (v, d, p) = data(i)\n if (p >= 0) {\n decreaseSeq(i)\n result ::= i + 1\n }\n }\n\n println(result.length)\n println(result.reverse.mkString(\" \"))\n}", "positive_code": [{"source_code": "\n\nimport java.io._\nimport java.util.ArrayList\nimport scala.collection.mutable.LinkedList\n\nobject C_GennadyDentist_b {\n \n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n class Child(val number:Int, val volume:Int, val volumeHall:Int, var conf:Int) {\n override def toString(): String = {\n return number + \"(\" + conf + \")\"\n }\n }\n\n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(t3.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val number = br.readLine().trim().toInt\n var children = List[Child]()\n for (i <- 0 until number) {\n val line = br.readLine().trim().split(\" \")\n children = new Child(i + 1, line(0).toInt, line(1).toInt, line(2).toInt) :: children\n }\n //---------------------------- parameters reading end --------------------------------\n\n\n// var queue = children.reverse\n var arr = children.reverse.toArray\n var counter = 0\n var resStr = \"\"\n var ind = 0\n \n db(printQueue)\n \n \n// for (i <- 0 until arr.length) {\n while (ind < arr.length) {\n val ch = arr(ind) \n if (ch != null) {\n db(\"--- entered \" + (ind+1) +\"-\"+ ch.volume)\n reduceGradualy(ind + 1, ch.volume)\n db(\"after reduceG: \" + printQueue)\n explode(ind + 1)\n }\n ind += 1\n }\n \n\n ind = 0\n while (ind < arr.length) {\n val ch = arr(ind)\n if (ch != null) { \n counter += 1\n resStr += (ind+1) + \" \"\n }\n ind += 1\n }\n println(counter)\n println(resStr)\n \n def printQueue() = {\n var res = \"\"\n for (ch <- arr) {\n if (ch != null && ch.number >= (ind+1)) {\n res += ch + \" \"\n }\n }\n res\n }\n\n def reduceGradualy(from:Int, volume:Int) {\n var vr = volume\n for (i <- from until arr.length) {\n val ch = arr(i)\n if (ch != null) {\n ch.conf -= vr\n if (ch.conf < -1) ch.conf = -1\n vr -= 1\n if (vr == 0) return\n }\n }\n }\n \n def explode(from:Int) {\n for (i <- from until arr.length) {\n val ch = arr(i)\n if (ch != null && ch.conf < 0) {\n db(\"exploded \" + (i+1)+\"-\"+ ch.volumeHall)\n arr(i) = null\n reduce(i+1, ch.volumeHall)\n db(\"after explosion: \" + printQueue)\n }\n }\n }\n \n def reduce(from:Int, volume:Int) {\n for (i <- from until arr.length) {\n val ch = arr(i)\n if (ch != null) {\n ch.conf -= volume\n if (ch.conf < -1) ch.conf = -1\n }\n }\n }\n\n }\n\n \n//========================= samples ======================== \nval sa1 = \"\"\"\n5\n4 2 2\n4 1 2\n5 2 4\n3 3 5\n5 1 2\n\"\"\"\n\nval sa2 = \"\"\"\n5\n4 5 1\n5 3 9\n4 1 2\n2 1 8\n4 1 9\n\"\"\"\n\nval t3 = \"\"\"\n10\n10 7 10\n3 6 11\n8 4 10\n10 1 11\n7 3 13\n7 2 13\n7 6 14\n3 4 17\n9 4 20\n5 2 24\n\"\"\"\n\n//========================= samples end ==================== \n}"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n\n case class Kid(v: Long, d: Long, var p: Long, var inQueue: Boolean = true)\n\n val kids = Array.ofDim[Kid](n)\n for (i <- 0 until n) {\n val Array(v, d, p) = readLine().split(\" \").map(_.toLong)\n kids(i) = Kid(v, d, p)\n }\n\n val Q = new mutable.ArrayStack[Integer]()\n\n for (i <- 0 until n) {\n if (kids(i).inQueue) {\n kids(i).inQueue = false\n var v = kids(i).v\n var j = i + 1\n while (v > 0 && j < n) {\n if (kids(j).inQueue) {\n kids(j).p -= v\n if (kids(j).p < 0) Q.push(j)\n v -= 1\n }\n j += 1\n }\n\n while (Q.nonEmpty) {\n val curr = Q.pop\n if (kids(curr).inQueue) {\n kids(curr).inQueue = false\n for (j <- curr + 1 until n) {\n if (kids(j).inQueue) {\n kids(j).p -= kids(curr).d\n if (kids(j).p < 0) Q.push(j)\n }\n }\n }\n }\n\n }\n\n// println(s\"Round $i\")\n// println(kids.mkString(\"\\n\"))\n// println(\"----\")\n }\n\n val answer = kids.zipWithIndex.filter(_._1.p >=0).map(_._2 + 1)\n println(answer.length)\n println(answer.mkString(\" \"))\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n\n case class Kid(v: Long, d: Long, var p: Long, var inQueue: Boolean = true)\n\n val kids = Array.ofDim[Kid](n)\n for (i <- 0 until n) {\n val Array(v, d, p) = readLine().split(\" \").map(_.toLong)\n kids(i) = Kid(v, d, p)\n }\n\n val Q = new mutable.Queue[Integer]()\n\n for (i <- 0 until n) {\n if (kids(i).inQueue) {\n kids(i).inQueue = false\n\n if (kids(i).p >= 0) {\n var v = kids(i).v\n var j = i + 1\n while (v > 0 && j < n) {\n kids(j).p -= v\n if (kids(j).p < 0) Q.enqueue(j)\n v -= 1\n j += 1\n }\n }\n\n while (Q.nonEmpty) {\n val curr = Q.dequeue()\n if (kids(curr).inQueue) {\n kids(curr).inQueue = false\n for (j <- curr + 1 until n) {\n if (kids(j).inQueue) {\n kids(j).p -= kids(curr).d\n if (kids(j).p < 0) Q.enqueue(j)\n }\n }\n }\n }\n }\n\n// println(s\"Round $i\")\n// println(kids.mkString(\"\\n\"))\n// println(\"----\")\n }\n\n val answer = kids.zipWithIndex.filter(_._1.p >=0).map(_._2 + 1)\n println(answer.length)\n println(answer.mkString(\" \"))\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n\n case class Kid(var v: Long, var d: Long, var p: Long)\n\n val kids = Array.ofDim[Kid](n)\n\n for (i <- 0 until n) {\n val Array(v, d, p) = readLine().split(\" \").map(_.toLong)\n kids(i) = Kid(v, d, p)\n }\n\n for (i <- 0 until n - 1) {\n if (kids(i).p < 0) {\n var wasChange = true\n var positive = true\n while (wasChange) {\n wasChange = false\n for (j <- i + 1 until n) {\n positive = kids(j).p >= 0\n kids(j).p -= kids(i).d\n if (positive && kids(j).p < 0) wasChange = true\n }\n }\n } else {\n var curr = i + 1\n var j = kids(i).v\n while (j > 0 && curr < n) {\n if (kids(curr).p > 0) {\n kids(curr).p -= j\n j -= 1\n }\n\n curr += 1\n }\n }\n\n// println(s\"After #$i\")\n// println(kids.mkString(\"\\n\"))\n }\n\n// println()\n// println()\n// println(kids.mkString(\"\\n\"))\n\n val answer = kids.zipWithIndex.filter { case (kid, id) =>\n kid.p >= 0\n }\n\n println(answer.length)\n println(answer.map(_._2 + 1).mkString(\" \"))\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n\n case class Kid(var v: Int, var d: Int, var p: Int)\n\n val kids = Array.ofDim[Kid](n)\n\n for (i <- 0 until n) {\n val Array(v, d, p) = readLine().split(\" \").map(_.toInt)\n kids(i) = Kid(v, d, p)\n }\n\n for (i <- 0 until n - 1) {\n if (kids(i).p < 0) {\n for (j <- i + 1 until n) {\n kids(j).p -= kids(i).d\n }\n } else {\n var curr = i + 1\n var j = kids(i).v\n while (j > 0 && curr < n) {\n kids(curr).p -= j\n curr += 1\n j -= 1\n }\n }\n\n// println(s\"After #$i\")\n// println(kids.mkString(\"\\n\"))\n }\n\n// println()\n// println()\n// println(kids.mkString(\"\\n\"))\n\n val answer = kids.zipWithIndex.filter { case (kid, id) =>\n kid.p >= 0\n }\n\n println(answer.length)\n println(answer.map(_._2 + 1).mkString(\" \"))\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n\n case class Kid(var v: Long, var d: Long, var p: Long)\n\n val kids = Array.ofDim[Kid](n)\n\n for (i <- 0 until n) {\n val Array(v, d, p) = readLine().split(\" \").map(_.toLong)\n kids(i) = Kid(v, d, p)\n }\n\n for (i <- 0 until n - 1) {\n if (kids(i).p < 0) {\n for (j <- i + 1 until n) {\n kids(j).p -= kids(i).d\n }\n } else {\n var curr = i + 1\n var j = kids(i).v\n while (j > 0 && curr < n) {\n kids(curr).p -= j\n curr += 1\n j -= 1\n }\n }\n\n// println(s\"After #$i\")\n// println(kids.mkString(\"\\n\"))\n }\n\n// println()\n// println()\n// println(kids.mkString(\"\\n\"))\n\n val answer = kids.zipWithIndex.filter { case (kid, id) =>\n kid.p >= 0\n }\n\n println(answer.length)\n println(answer.map(_._2 + 1).sorted.mkString(\" \"))\n\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n\n case class Kid(var v: Long, var d: Long, var p: Long)\n\n val kids = Array.ofDim[Kid](n)\n\n for (i <- 0 until n) {\n val Array(v, d, p) = readLine().split(\" \").map(_.toLong)\n kids(i) = Kid(v, d, p)\n }\n\n def moveRight(curr: Int): Unit = {\n for (i <- curr + 1 until n) {\n kids(i).p -= kids(curr).d\n }\n\n for (i <- curr + 1 until n) {\n if (kids(i).p < 0) moveRight(i)\n }\n }\n\n for (i <- 0 until n - 1) {\n if (kids(i).p < 0) {\n moveRight(i)\n } else {\n var curr = i + 1\n var j = kids(i).v\n while (j > 0 && curr < n) {\n kids(curr).p -= j\n curr += 1\n j -= 1\n }\n }\n\n// println(s\"After #$i\")\n// println(kids.mkString(\"\\n\"))\n }\n\n// println()\n// println()\n// println(kids.mkString(\"\\n\"))\n\n val answer = kids.zipWithIndex.filter { case (kid, id) =>\n kid.p >= 0\n }\n\n println(answer.length)\n println(answer.map(_._2 + 1).mkString(\" \"))\n\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n\n case class Kid(var v: Long, var d: Long, var p: Long)\n\n val kids = Array.ofDim[Kid](n)\n\n for (i <- 0 until n) {\n val Array(v, d, p) = readLine().split(\" \").map(_.toLong)\n kids(i) = Kid(v, d, p)\n }\n\n @tailrec\n def moveRight(c: Int): Unit = {\n var lastLessThanZero = c\n var curr = c\n\n for (i <- curr + 1 until n) {\n kids(i).p -= kids(curr).d\n if (kids(i).p < 0 && lastLessThanZero == c) lastLessThanZero = i\n }\n\n if (lastLessThanZero != c) moveRight(lastLessThanZero)\n }\n\n for (i <- 0 until n - 1) {\n if (kids(i).p < 0) {\n moveRight(i)\n } else {\n var curr = i + 1\n var j = kids(i).v\n while (j > 0 && curr < n) {\n kids(curr).p -= j\n curr += 1\n j -= 1\n }\n }\n\n// println(s\"After #$i\")\n// println(kids.mkString(\"\\n\"))\n }\n\n// println()\n// println()\n// println(kids.mkString(\"\\n\"))\n\n val answer = kids.zipWithIndex.filter { case (kid, id) =>\n kid.p >= 0\n }\n\n println(answer.length)\n println(answer.map(_._2 + 1).mkString(\" \"))\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n\n case class Kid(var v: Long, var d: Long, var p: Long)\n\n val kids = Array.ofDim[Kid](n)\n\n for (i <- 0 until n) {\n val Array(v, d, p) = readLine().split(\" \").map(_.toLong)\n kids(i) = Kid(v, d, p)\n }\n\n val Q = new mutable.Queue[Int]()\n for (i <- 0 until n - 1) {\n if (kids(i).p < 0) {\n Q.enqueue(i)\n while (Q.nonEmpty) {\n val curr = Q.dequeue()\n for (j <- curr + 1 until n) {\n kids(j).p -= kids(curr).d\n if (kids(j).p < 0) Q.enqueue(j)\n }\n }\n\n } else {\n var curr = i + 1\n var j = kids(i).v\n while (j > 0 && curr < n) {\n kids(curr).p -= j\n curr += 1\n j -= 1\n }\n }\n\n// println(s\"After #$i\")\n// println(kids.mkString(\"\\n\"))\n }\n\n// println()\n// println()\n// println(kids.mkString(\"\\n\"))\n\n val answer = kids.zipWithIndex.filter { case (kid, id) =>\n kid.p >= 0\n }\n\n println(answer.length)\n println(answer.map(_._2 + 1).mkString(\" \"))\n\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n\n case class Kid(var v: Long, var d: Long, var p: Long)\n\n val kids = Array.ofDim[Kid](n)\n\n for (i <- 0 until n) {\n val Array(v, d, p) = readLine().split(\" \").map(_.toLong)\n kids(i) = Kid(v, d, p)\n }\n\n def moveRight(curr: Int): Unit = {\n for (i <- curr + 1 until n) {\n kids(i).p -= kids(curr).d\n if (kids(i).p < 0) {\n moveRight(i)\n }\n }\n\n }\n\n for (i <- 0 until n - 1) {\n if (kids(i).p < 0) {\n moveRight(i)\n } else {\n var curr = i + 1\n var j = kids(i).v\n while (j > 0 && curr < n) {\n kids(curr).p -= j\n curr += 1\n j -= 1\n }\n }\n\n// println(s\"After #$i\")\n// println(kids.mkString(\"\\n\"))\n }\n\n// println()\n// println()\n// println(kids.mkString(\"\\n\"))\n\n val answer = kids.zipWithIndex.filter { case (kid, id) =>\n kid.p >= 0\n }\n\n println(answer.length)\n println(answer.map(_._2 + 1).mkString(\" \"))\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n\n case class Kid(v: Long, d: Long, var p: Long, var inQueue: Boolean = true)\n\n val kids = Array.ofDim[Kid](n)\n for (i <- 0 until n) {\n val Array(v, d, p) = readLine().split(\" \").map(_.toLong)\n kids(i) = Kid(v, d, p)\n }\n\n for (i <- 0 until n) {\n if (kids(i).inQueue) {\n if (kids(i).p >= 0) {\n kids(i).inQueue = false\n var v = kids(i).v\n var j = i + 1\n while (v > 0 && j < n) {\n if (kids(j).p >= 0 && kids(j).inQueue) {\n kids(j).p -= v\n v -= 1\n }\n j += 1\n }\n } else {\n if (kids(i).inQueue) {\n kids(i).inQueue = false\n for (j <- i + 1 until n) {\n if (kids(j).inQueue) {\n kids(j).p -= kids(i).d\n }\n }\n }\n\n }\n\n }\n\n// println(s\"Round $i\")\n// println(kids.mkString(\"\\n\"))\n// println(\"----\")\n }\n\n val answer = kids.zipWithIndex.filter(_._1.p >=0).map(_._2 + 1)\n println(answer.length)\n println(answer.mkString(\" \"))\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n\n case class Kid(var v: Long, var d: Long, var p: Long)\n\n val kids = Array.ofDim[Kid](n)\n\n for (i <- 0 until n) {\n val Array(v, d, p) = readLine().split(\" \").map(_.toLong)\n kids(i) = Kid(v, d, p)\n }\n\n val Q = new mutable.Queue[Int]()\n for (i <- 0 until n - 1) {\n if (kids(i).p < 0) {\n Q.enqueue(i)\n while (Q.nonEmpty) {\n val curr = Q.dequeue()\n for (j <- curr + 1 until n) {\n val wasMoreOrEqualZero = kids(j).p >= 0\n kids(j).p -= kids(curr).d\n if (wasMoreOrEqualZero && kids(j).p < 0) Q.enqueue(j)\n }\n }\n\n } else {\n var curr = i + 1\n var j = kids(i).v\n while (j > 0 && curr < n) {\n kids(curr).p -= j\n curr += 1\n j -= 1\n }\n }\n\n// println(s\"After #$i\")\n// println(kids.mkString(\"\\n\"))\n }\n\n// println()\n// println()\n// println(kids.mkString(\"\\n\"))\n\n val answer = kids.zipWithIndex.filter { case (kid, id) =>\n kid.p >= 0\n }\n\n println(answer.length)\n println(answer.map(_._2 + 1).mkString(\" \"))\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n\n case class Kid(v: Long, d: Long, var p: Long, var inQueue: Boolean = true)\n\n val kids = Array.ofDim[Kid](n)\n for (i <- 0 until n) {\n val Array(v, d, p) = readLine().split(\" \").map(_.toLong)\n kids(i) = Kid(v, d, p)\n }\n\n val Q = new mutable.Queue[Integer]()\n\n for (i <- 0 until n) {\n if (kids(i).inQueue) {\n if (kids(i).p >= 0) {\n kids(i).inQueue = false\n var v = kids(i).v\n var j = i + 1\n while (v > 0 && j < n) {\n kids(j).p -= v\n if (kids(j).p < 0) Q.enqueue(j)\n v -= 1\n j += 1\n }\n }\n\n while (Q.nonEmpty) {\n val curr = Q.dequeue()\n if (kids(curr).inQueue) {\n kids(curr).inQueue = false\n for (j <- curr + 1 until n) {\n if (kids(j).inQueue) {\n kids(j).p -= kids(curr).d\n if (kids(j).p < 0) Q.enqueue(j)\n }\n }\n }\n }\n }\n\n// println(s\"Round $i\")\n// println(kids.mkString(\"\\n\"))\n// println(\"----\")\n }\n\n val answer = kids.zipWithIndex.filter(_._1.p >=0).map(_._2 + 1)\n println(answer.length)\n println(answer.mkString(\" \"))\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n\n case class Kid(var v: Long, var d: Long, var p: Long)\n\n val kids = Array.ofDim[Kid](n)\n\n for (i <- 0 until n) {\n val Array(v, d, p) = readLine().split(\" \").map(_.toLong)\n kids(i) = Kid(v, d, p)\n }\n\n for (i <- 0 until n - 1) {\n if (kids(i).p < 0) {\n for (j <- i + 1 until n) {\n kids(j).p -= kids(i).d\n }\n } else {\n var curr = i + 1\n var j = kids(i).v\n while (j > 0 && curr < n) {\n kids(curr).p -= j\n curr += 1\n j -= 1\n }\n }\n\n// println(s\"After #$i\")\n// println(kids.mkString(\"\\n\"))\n }\n\n// println()\n// println()\n// println(kids.mkString(\"\\n\"))\n\n val answer = kids.zipWithIndex.filter { case (kid, id) =>\n kid.p >= 0\n }\n\n println(answer.length)\n println(answer.map(_._2 + 1).mkString(\" \"))\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n\n case class Kid(var v: Long, var d: Long, var p: Long)\n\n val kids = Array.ofDim[Kid](n)\n\n for (i <- 0 until n) {\n val Array(v, d, p) = readLine().split(\" \").map(_.toLong)\n kids(i) = Kid(v, d, p)\n }\n\n val Q = new mutable.Queue[Int]()\n for (i <- 0 until n - 1) {\n if (kids(i).p < 0) {\n\n } else {\n var curr = i + 1\n var j = kids(i).v\n while (j > 0 && curr < n) {\n kids(curr).p -= j\n\n Q.enqueue(curr)\n while (Q.nonEmpty) {\n val c = Q.dequeue()\n for (j <- c + 1 until n) {\n val wasMoreOrEqualZero = kids(j).p >= 0\n kids(j).p -= kids(c).d\n if (wasMoreOrEqualZero && kids(j).p < 0) Q.enqueue(j)\n }\n }\n\n curr += 1\n j -= 1\n }\n }\n\n// println(s\"After #$i\")\n// println(kids.mkString(\"\\n\"))\n }\n\n// println()\n// println()\n// println(kids.mkString(\"\\n\"))\n\n val answer = kids.zipWithIndex.filter { case (kid, id) =>\n kid.p >= 0\n }\n\n println(answer.length)\n println(answer.map(_._2 + 1).mkString(\" \"))\n\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport scala.collection.mutable.LinkedList\n\nobject C_GennadyDentist_b {\n \n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n class Child(val number:Int, val volume:Int, val volumeHall:Int, var conf:Int) {\n override def toString(): String = {\n return number + \"(\" + conf + \")\"\n }\n }\n\n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(t3.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val number = br.readLine().trim().toInt\n var children = List[Child]()\n for (i <- 0 until number) {\n val line = br.readLine().trim().split(\" \")\n children = new Child(i + 1, line(0).toInt, line(1).toInt, line(2).toInt) :: children\n }\n //---------------------------- parameters reading end --------------------------------\n\n\n// var queue = children.reverse\n var arr = children.reverse.toArray\n var counter = 0\n var resStr = \"\"\n var ind = 0\n \n db(printQueue)\n \n \n// for (i <- 0 until arr.length) {\n while (ind < arr.length) {\n val ch = arr(ind) \n if (ch != null) {\n db(\"--- entered \" + (ind+1) +\"-\"+ ch.volume)\n reduceGradualy(ind + 1, ch.volume)\n db(\"after reduceG: \" + printQueue)\n explode(ind + 1)\n }\n ind += 1\n }\n \n\n ind = 0\n while (ind < arr.length) {\n val ch = arr(ind)\n if (ch != null) { \n counter += 1\n resStr += (ind+1) + \" \"\n }\n ind += 1\n }\n println(counter)\n println(resStr)\n \n def printQueue() = {\n var res = \"\"\n for (ch <- arr) {\n if (ch != null && ch.number >= (ind+1)) {\n res += ch + \" \"\n }\n }\n res\n }\n\n def reduceGradualy(from:Int, volume:Int) {\n var vr = volume\n for (i <- from until arr.length) {\n val ch = arr(i)\n if (ch != null) {\n ch.conf -= vr\n vr -= 1\n if (vr == 0) return\n }\n }\n }\n \n def explode(from:Int) {\n for (i <- from until arr.length) {\n val ch = arr(i)\n if (ch != null && ch.conf < 0) {\n db(\"exploded \" + (i+1)+\"-\"+ ch.volumeHall)\n arr(i) = null\n reduce(i+1, ch.volumeHall)\n db(\"after explosion: \" + printQueue)\n }\n }\n }\n \n def reduce(from:Int, volume:Int) {\n for (i <- from until arr.length) {\n val ch = arr(i)\n if (ch != null) ch.conf -= volume\n }\n }\n\n }\n\n \n//========================= samples ======================== \nval sa1 = \"\"\"\n5\n4 2 2\n4 1 2\n5 2 4\n3 3 5\n5 1 2\n\"\"\"\n\nval sa2 = \"\"\"\n5\n4 5 1\n5 3 9\n4 1 2\n2 1 8\n4 1 9\n\"\"\"\n\nval t3 = \"\"\"\n10\n10 7 10\n3 6 11\n8 4 10\n10 1 11\n7 3 13\n7 2 13\n7 6 14\n3 4 17\n9 4 20\n5 2 24\n\"\"\"\n\n//========================= samples end ==================== \n}"}, {"source_code": "\nimport java.io._\n\nobject C_GennadyDentist {\n\n def main(args: Array[String]): Unit = {\n var debugV = false;\n def debug(msg:String) = {\n if (debugV) {\n println(msg)\n }\n }\n class Child(val number:Int, val volume:Int, val volumeHall:Int, var conf:Int) {\n var exploded = false\n \n override def toString(): String = {\n return number + \"(\" + conf + \")\"\n }\n }\n \n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n var children = List[Child]()\n \n val number = br.readLine().trim().toInt\n for (i <- 0 until number) {\n val line = br.readLine().trim().split(\" \")\n children = new Child(i+1, line(0).toInt, line(1).toInt, line(2).toInt) :: children\n }\n \n// val number = 5\n// val strs = \"\"\"4 2 2\n//4 1 2\n//5 2 4\n//3 3 5\n//5 1 2\"\"\".split(\"\\n\")\n// debugV = true\n// val number = 5\n// val strs = \"\"\"4 5 1\n//5 3 9\n//4 1 2\n//2 1 8\n//4 1 9\"\"\".split(\"\\n\") \n// for(i <- 0 until strs.length) {\n// var line = strs(i).trim().split(\" \")\n// children = new Child(i+1, line(0).toInt, line(1).toInt, line(2).toInt) :: children\n// }\n \n def reduceFromCab(li:List[Child], vol:Int) { \n if (li == Nil || vol == 0) return \n li.head.conf -= vol\n debug(\"reduceFromCab \" + li.head)\n if (li.head.conf < -1) li.head.conf = -1\n reduceFromCab(li.tail, vol-1)\n if (li.head.conf <= 0 && !li.head.exploded) {\n li.head.exploded = true\n debug(\"exploded \" + li.head)\n reduceExploded(li.tail, li.head.volumeHall)\n }\n }\n def reduceExploded(li:List[Child], vol:Int) { \n if (li == Nil) return\n val ch = li.head \n ch.conf -= vol\n debug(\"reduceExploded \" + ch)\n if (ch.conf < -1) ch.conf = -1\n if (ch.conf <= 0 && !ch.exploded) {\n ch.exploded = true\n debug(\"exploded secondary \" + ch)\n reduceExploded(li.tail, li.head.volumeHall)\n }\n debug(\"after exploded reduce \" + li.mkString(\", \"))\n } \n \n var toProcess = children.reverse\n \n var result = List[Child]()\n while (toProcess != Nil) {\n val ch = toProcess.head\n if (ch.conf > 0) {\n result = ch :: result\n reduceFromCab(toProcess.tail, ch.volume-1)\n } else {\n \n }\n toProcess = toProcess.tail\n debug(toProcess.mkString(\", \"))\n }\n \n println(result.length)\n var resStr = \"\"\n result.foreach { x => resStr+=x.number + \" \"}\n println(resStr.reverse.trim())\n \n\n\n }\n}"}, {"source_code": "\nimport java.io._\n\nobject C_GennadyDentist {\n\n def main(args: Array[String]): Unit = {\n class Child(val number:Int, val volume:Int, val volumeHall:Int, var conf:Int) {\n var exploded = false\n \n override def toString(): String = {\n return number + \"(\" + conf + \")\"\n }\n }\n \n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n var children = List[Child]()\n \n val number = br.readLine().trim().toInt\n for (i <- 0 until number) {\n val line = br.readLine().trim().split(\" \")\n children = new Child(i+1, line(0).toInt, line(1).toInt, line(2).toInt) :: children\n }\n \n// val number = 5\n// val strs = \"\"\"4 2 2\n//4 1 2\n//5 2 4\n//3 3 5\n//5 1 2\"\"\".split(\"\\n\")\n// for(i <- 0 until strs.length) {\n// var line = strs(i).trim().split(\" \")\n// children = new Child(i+1, line(0).toInt, line(1).toInt, line(2).toInt) :: children\n// }\n \n def reduceFromCab(li:List[Child], vol:Int) { \n if (li == Nil || vol == 0) return \n li.head.conf -= vol\n// println(\"reduceFromCab \" + li.head)\n if (li.head.conf < -1) li.head.conf = -1\n reduceFromCab(li.tail, vol-1)\n if (li.head.conf <= 0 && !li.head.exploded) {\n li.head.exploded = true\n// println(\"exploded \" + li.head)\n reduceExploded(li.tail, li.head.volumeHall)\n }\n }\n def reduceExploded(li:List[Child], vol:Int) { \n if (li == Nil) return\n val ch = li.head \n ch.conf -= vol\n// println(\"reduceExploded \" + ch)\n if (ch.conf < -1) ch.conf = -1\n if (ch.conf <= 0 && !ch.exploded) {\n ch.exploded = true\n// println(\"exploded secondary \" + ch)\n reduceExploded(li.tail, li.head.volumeHall)\n }\n// println(\"after exploded reduce \" + li.mkString(\", \"))\n } \n \n var toProcess = children.reverse\n \n var result = List[Child]()\n while (toProcess != Nil) {\n val ch = toProcess.head\n if (ch.conf > 0) {\n result = ch :: result\n reduceFromCab(toProcess.tail, ch.volume)\n } else {\n \n }\n toProcess = toProcess.tail\n// println(toProcess.mkString(\", \"))\n }\n \n println(result.length)\n var resStr = \"\"\n result.foreach { x => resStr+=x.number + \" \"}\n println(resStr)\n \n\n\n }\n}"}], "src_uid": "8cf8590d1f3668b768702c7eb0ee8249"} {"source_code": "import scala.collection.JavaConversions._\nimport scala.collection.mutable.MutableList\n\nobject Codeforces158C {\n def main(args: Array[String]) {\n val n = scala.io.StdIn.readLine().toInt\n var path = List[String]()\n for (i <- 0 until n) {\n val lst = scala.io.StdIn.readLine().split(\" \")\n val cmd = lst(0)\n var arg = \"\"\n if (lst.length > 1)\n arg = lst(1)\n if (cmd == \"pwd\") {\n var j = 0\n while (j < path.length) {\n if (path(j) == \"..\") {\n path = path.take(j-1) ::: path.drop(j+1)\n j -= 1\n }\n else\n j += 1\n }\n println(\"/\" + path.mkString(\"/\") + (if (path.length > 0) \"/\" else \"\"))\n }\n else {\n if (arg.startsWith(\"/\")) {\n path = List(arg.substring(1).split(\"/\"): _*)\n }\n else {\n arg.split(\"/\").foreach(d=> path = path :+ d)\n } \n }\n }\n \n }\n}", "positive_code": [{"source_code": "object Commands extends App {\n import io.{Source => Input}\n import collection.mutable.ListBuffer\n \n val in = Input.fromInputStream(System.in).bufferedReader()\n val n = in.readLine.toInt\n\n var currentPath = new ListBuffer[String]\n for (i <- 1 to n) {\n val command = in.readLine\n if (command == \"pwd\")\n println(\"/\" + currentPath.map(_ + \"/\").mkString(\"\"))\n else {\n var startIndex = 3\n if (command startsWith(\"cd /\")) {\n currentPath clear()\n startIndex = 4\n }\n for (dir <- command.substring(startIndex).split(\"/\").filter(_ != \"\")) {\n if (dir == \"..\")\n currentPath.remove(currentPath.length - 1)\n else\n currentPath += dir\n }\n }\n }\n}\n"}, {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n class Directory(dirs: List[String]) {\n def this() = this(Nil)\n def cmd(command: String) = {\n val split = command.split(\" \")\n split(0) match {\n case \"pwd\" => pwd\n case \"cd\" => cd(split(1))\n }\n }\n private def pwd = {\n def printDir(dirs: List[String]) { dirs match {\n case Nil => print(\"/\")\n case head :: tail =>\n printDir(tail)\n print(head + \"/\")\n }}\n printDir(dirs)\n println()\n this\n }\n private def cd(arg: String) = {\n new Directory(\n arg.split(\"/\").foldLeft(dirs) {\n case (_, \"\") => Nil\n case (_ :: tail, \"..\") => tail\n case (l, x) => x :: l\n }\n )\n }\n }\n\n def main(args: Array[String]) {\n (for(_ <- 1 to readInt) yield reader.readLine()).foldLeft(new Directory())((dir, command) => dir.cmd(command))\n }\n}\n"}, {"source_code": "object Main {\n val path = scala.collection.mutable.Stack[String]()\n \n def cd(p: String) = {\n val a = if (p.startsWith(\"/\")) {\n path.clear()\n p.split(\"/\").filter(! _.isEmpty)\n } else p.split(\"/\")\n a.foreach {\n case \"..\" => path.pop()\n case s: String => path.push(s)\n }\n }\n \n def pwd = if (path.size == 0) println(\"/\")\n else println(path.reverse.mkString(\"/\", \"/\", \"/\"))\n \n val pwdr = \"pwd\".r\n val cdr = \"cd (.*)\".r\n \n def main(args: Array[String]) {\n val num = readInt()\n for (_ <- 1 to num) {\n readLine() match {\n case pwdr() => pwd\n case cdr(p) => cd(p)\n }\n }\n }\n}"}, {"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn._\n\nobject _158_C extends App {\n val n = readInt()\n for (_ <- 1 to n) {\n val input = readLine().split(\" \")\n DirOps.command(input)\n }\n}\n\nobject DirOps {\n var value = new mutable.MutableList[String]\n\n def command(s: Seq[String]) = {\n val cmd = s.head\n if (cmd == \"pwd\") println(\"/\" + value.mkString(\"/\") + (if (value.isEmpty) \"\" else \"/\"))\n else if (cmd == \"cd\") {\n val params: Seq[String] = s.drop(1).head.split(\"/\")\n if (s.drop(1).head.startsWith(\"/\")) {\n value = new mutable.MutableList[String]()\n }\n\n params foreach { x =>\n if (x.isEmpty) {}\n else if (x == \"..\") value = value.init\n else value += x\n }\n }\n else throw new Error(\"unsupported\")\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject CF_158C_CdAndPwdCommands {\n def main(args: Array[String]): Unit = {\n var path = List[String](\"\")\n for (i <- 1 to readInt()) {\n val command = readLine()\n if (\"pwd\".equals(command))\n printPath(path)\n else {\n val cdPath = command drop 3\n if (cdPath startsWith \"/\")\n path = List[String]()\n val directories = cdPath split \"/\"\n for (directory <- directories)\n if (\"..\".equals(directory))\n path = path drop 1\n else\n path = directory +: path\n }\n }\n }\n\n def printPath(path: List[String]) = {\n println(path.reverse.mkString(\"/\") + \"/\")\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val t: scala.collection.mutable.Stack[String] = new scala.collection.mutable.Stack()\n\n println((1 to n).flatMap{ _ =>\n val cmd = in.next()\n if (cmd.startsWith(\"pwd\"))\n if (t.size == 0)\n Some(\"/\")\n else\n Some(t.reverse.mkString(\"/\", \"/\", \"/\"))\n else {\n var ncmd = cmd.drop(3)\n if (ncmd.head == '/') {\n t.clear()\n ncmd = ncmd.drop(1)\n }\n ncmd.split(\"/\").foreach {\n case(\"..\") => t.pop()\n case(str) => t.push(str)\n }\n None\n }\n }.mkString(\"\\n\"))\n}"}, {"source_code": "object C158 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val q = cu.Stack[String]()\n for(_ <- 1 to n) {\n val x = read\n if(x == \"pwd\") {\n if(q.isEmpty)\n println(\"/\")\n else\n println(q.reverse.mkString(\"/\", \"/\", \"/\"))\n } else {\n val newX = x.drop(3)\n if(newX.startsWith(\"/\"))\n q.clear()\n newX.split(\"/\").foreach{ dir =>\n if(dir == \"..\")\n q.pop()\n else if(dir.nonEmpty)\n q.push(dir)\n }\n }\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object Shell extends App{\n\n val n = readInt\n var res = List[String]()\n for(i <- 0 until n)\n {\n var str : String = readLine\n\n if (str == \"pwd\") {\n res.filter(_ != \"\").foreach(printFormatted)\n println(\"/\")\n }\n else {\n var str2 = str drop 3 split(\"/\")\n\n if ((str drop 3) != \"/\")\n {\n if (str2(0) == \"\") {\n res = Nil\n str2 = str2.tail\n }\n\n for (token <- str2) {\n token\n match {\n case \"..\" => if (!res.isEmpty) res = res dropRight 1\n case t => res = res ::: List(t)\n }\n }\n }\n else\n res = List(\"\")\n }\n }\n\n def printFormatted(str : String): Unit ={\n print(\"/\" + str)\n }\n}"}, {"source_code": "import io.Source\nimport java.util.Scanner\n\nobject C {\n\n def main(args: Array[String]) {\n var path = List[String](\"\")\n for (line <- Source.stdin.getLines().drop(1)) {\n if (line equals \"pwd\") {\n println(path.reverse.map((s) => s + \"/\").mkString)\n } else {\n val s = line substring 3\n if (s startsWith \"/\") {\n path = List[String](\"\")\n }\n for (token <- s.split(\"/\") if !token.isEmpty) {\n if (token equals \"..\") {\n path = path drop 1\n } else {\n path = token :: path\n }\n }\n }\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P158C extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextLine.toInt\n\n def normalize(dir: Seq[String]): Seq[String] = {\n @tailrec\n def loop(acc: List[String], rem: List[String]): List[String] = rem match {\n case Nil => acc\n case d :: ds => {\n if (d == \"..\") acc match {\n case Nil => loop(acc, ds)\n case _ => loop(acc.init, ds)\n }\n else loop(acc :+ d, ds)\n }\n }\n loop(Nil, dir.toList)\n }\n\n def solve {\n @tailrec\n def loop(cwd: Seq[String], n: Int): Unit =\n if (n == N) ()\n else {\n val command = sc.nextLine\n if (command == \"pwd\") {\n val ncwd = normalize(cwd)\n if (ncwd == Nil) out.println(\"/\")\n else out.println(\"/\" + ncwd.mkString(\"/\") + \"/\")\n loop(ncwd, n + 1)\n } else {\n val target = command.substring(3)\n if (target == \"/\") loop(Nil, n + 1)\n else if (target.head == '/') loop(target.split('/').tail, n + 1)\n else loop(cwd ++ target.split('/'), n + 1)\n }\n }\n loop(Nil, 0)\n }\n\n solve\n out.close\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject CF_158C_CdAndPwdCommands {\n def main(args: Array[String]): Unit = {\n var path = List[String](\"\")\n for (i <- 1 to readInt()) {\n val command = readLine()\n if (\"pwd\".equals(command))\n printPath(path)\n else {\n val cdPath = command drop 3 split \"/\"\n for (directory <- cdPath)\n if (\"..\".equals(directory))\n path = path drop 1\n else\n path = directory +: path\n }\n }\n }\n\n def printPath(path: List[String]) = {\n println((path.reverse.mkString(\"/\") drop 1) + \"/\")\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val t: scala.collection.mutable.Stack[String] = new scala.collection.mutable.Stack()\n\n println((1 to n).flatMap{ _ =>\n val cmd = in.next()\n if (cmd.startsWith(\"pwd\"))\n Some(t.reverse.mkString(\"\", \"/\", \"/\"))\n else {\n cmd.drop(3).split(\"/\").foreach {\n case(\"..\") => t.pop()\n case(str) => t.push(str)\n }\n None\n }\n }.mkString(\"\\n\"))\n}"}, {"source_code": "object C158 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val q = cu.Stack[String]()\n for(_ <- 1 to n) {\n val x = read\n if(x == \"pwd\") {\n if(q.isEmpty)\n println(\"/\")\n else\n println(q.reverse.mkString(\"/\", \"/\", \"/\"))\n } else {\n x.drop(3).split(\"/\").foreach{ dir =>\n if(dir == \"..\")\n q.pop()\n else if(dir.nonEmpty)\n q.push(dir)\n }\n }\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import io.Source\nimport java.util.Scanner\n\nobject C {\n\n def main(args: Array[String]) {\n var path = List[String](\"\")\n for (val line <- Source.stdin.getLines().drop(1)) {\n if (line equals \"pwd\") {\n println(path.reverse.map((s) => \"/\" + s).mkString.replaceAll(\"//\", \"/\"))\n } else {\n val s = line substring 3\n if (s startsWith \"/\") {\n path = List[String](\"\")\n }\n for (val token <- s.split(\"/\") if !token.isEmpty) {\n if (token equals \"..\") {\n path = path drop 1\n } else {\n path = token :: path\n }\n }\n }\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P158C extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextLine.toInt\n\n def normalize(dir: Seq[String]): Seq[String] = {\n @tailrec\n def loop(acc: List[String], rem: List[String]): List[String] = rem match {\n case Nil => acc\n case d :: ds => {\n if (d == \"..\") acc match {\n case Nil => loop(acc, ds)\n case _ => loop(acc.init, ds)\n }\n else loop(acc :+ d, ds)\n }\n }\n loop(Nil, dir.toList)\n }\n\n def solve {\n @tailrec\n def loop(cwd: Seq[String], n: Int): Unit =\n if (n == N) ()\n else {\n val command = sc.nextLine\n if (command == \"pwd\") {\n val ncwd = normalize(cwd)\n out.println(\"/\" + ncwd.mkString(\"/\"))\n loop(ncwd, n + 1)\n }\n else {\n val target = command.substring(3)\n if (target.head == '/') loop(target.split('/').tail, n + 1)\n else loop(cwd ++ target.split('/'), n + 1)\n }\n }\n loop(Nil, 0)\n }\n\n solve\n out.close\n}\n"}, {"source_code": "object Commands extends App {\n import io.{Source => Input}\n \n val in = Input.fromInputStream(System.in).bufferedReader()\n val n = in.readLine.toInt\n\n var currentPath : List[String] = Nil\n for (i <- 1 to n) {\n val command = in.readLine\n if (command == \"pwd\")\n println(\"/\" + currentPath.mkString(\"/\") + (if (currentPath.length > 0) \"/\" else \"\"))\n else {\n if (command startsWith(\"cd /\"))\n currentPath = command.substring(4).split(\"/\").filter(_ != \"\").toList\n else if (command.startsWith(\"cd \")) {\n for (dir <- command.substring(3).split(\"/\").filter(_ != \"\")) {\n if (dir == \"..\")\n currentPath = currentPath.take(currentPath.length - 1)\n else\n currentPath = currentPath ::: List(dir)\n }\n }\n }\n }\n}\n"}, {"source_code": "object Main {\n val path = scala.collection.mutable.Stack[String]()\n \n def cd(p: String) = {\n val a = if (p.startsWith(\"/\")) {\n path.clear()\n p.split(\"/\").filter(! _.isEmpty)\n } else p.split(\"/\")\n a.foreach {\n case \"..\" => path.pop()\n case s: String => path.push(s)\n }\n }\n \n def pwd = println(path.reverse.mkString(\"/\", \"/\", \"\"))\n \n val pwdr = \"pwd\".r\n val cdr = \"cd (.*)\".r\n \n def main(args: Array[String]) {\n val num = readInt()\n for (_ <- 1 to num) {\n readLine() match {\n case pwdr() => pwd\n case cdr(p) => cd(p)\n }\n }\n }\n}"}], "src_uid": "494ac937ba939db1dbc4081e518ab54c"} {"source_code": "object codeForcesMain {\r\n def main(args: Array[String]): Unit = {\r\n val arr = (io.Source.stdin.getLines.toList)\r\n arr\r\n .tail\r\n .filter(s => !s.matches(\"[0-9]*\"))\r\n .map(str => {\r\n if (str.contains(\"ab\")) (str.indexOf(\"ab\")+1+ \" \" + (str.indexOf(\"ab\") + 2))\r\n else if (str.contains(\"ba\")) (str.indexOf(\"ba\")+1 + \" \" + (str.indexOf(\"ba\") + 2))\r\n else \"-1 -1\"\r\n })\r\n .foreach(println)\r\n }\r\n}", "positive_code": [{"source_code": "//package contest1569\n\nobject TaskA extends App {\n\n val iterCount = scala.io.StdIn.readLine().toInt\n\n for (_ <- 0 until iterCount) {\n val strLen = scala.io.StdIn.readLine().toInt\n val str = scala.io.StdIn.readLine().toCharArray\n\n var prevChar = str.head\n\n if (strLen <= 1) prevChar = 'e'\n\n for (j <- 1 until strLen if prevChar != 's') {\n val currChar = str(j)\n\n if (currChar != prevChar) {\n println(s\"$j ${j + 1}\")\n prevChar = 's'\n } else {\n prevChar = currChar\n }\n }\n\n if (prevChar == 'e' || prevChar != 's') println(\"-1 -1\")\n\n }\n\n}\n"}], "negative_code": [{"source_code": "object codeForcesMain {\r\n def main(args: Array[String]): Unit = {\r\n val arr = (io.Source.stdin.getLines.toList)\r\n arr\r\n .tail\r\n .filter(s => !s.matches(\"[0-9]\"))\r\n .map(str => {\r\n if (str.contains(\"ab\")) (str.indexOf(\"ab\")+1+ \" \" + (str.indexOf(\"ab\") + 2))\r\n else if (str.contains(\"ba\")) (str.indexOf(\"ba\")+1 + \" \" + (str.indexOf(\"ba\") + 2))\r\n else \"-1 -1\"\r\n })\r\n .foreach(println)\r\n }\r\n}\r\n"}, {"source_code": "object codeForcesMain {\r\n def main(args: Array[String]): Unit = {\r\n val arr = (io.Source.stdin.getLines.toList)\r\n arr\r\n .tail\r\n .filter(s => !s.matches(\"[0-9]\"))\r\n .map(str => {\r\n if (str.contains(\"ab\")) (str.indexOf(\"ba\")+1+ \" \" + (str.indexOf(\"ba\") + 2))\r\n else if (str.contains(\"ba\")) (str.indexOf(\"ba\")+1 + \" \" + (str.indexOf(\"ba\") + 2))\r\n else \"-1 -1\"\r\n })\r\n .foreach(println)\r\n }\r\n}"}, {"source_code": "object TaskA extends App {\n\n val iterCount = scala.io.StdIn.readLine().toInt\n\n for (_ <- 0 until iterCount) {\n val strLen = scala.io.StdIn.readLine().toInt\n val str = scala.io.StdIn.readLine().toCharArray\n\n var prevChar = str.head\n\n if (strLen <= 1) prevChar = 'e'\n\n for (j <- 1 until strLen if prevChar != 's') {\n val currChar = str(j)\n\n if (currChar != prevChar) {\n println(s\"$j ${j + 1}\")\n prevChar = 's'\n } else {\n prevChar = currChar\n }\n }\n\n if (prevChar == 'e') println(\"-1 -1\")\n\n }\n\n}\n"}], "src_uid": "127d7f23a0ac8fcecccd687565d6f35a"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = (1 to n).map{ _ =>\n val s = readLine().split(\" \")\n val name = s(0)\n val score = s.drop(3).map(_.toInt).sum + s(1).toInt * 100 - s(2).toInt * 50\n (name, score)\n }\n println(a.maxBy(_._2)._1)\n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val r = (1 to n).foldLeft((\"\", -1l)){\n case ((pn, before), _) =>\n val list = in.next().split(' ')\n val nick = list.head\n val Array(plus, minus, a, b, c, d, e) = list.tail.map(_.toLong)\n val candidate = a + b + c + d + e - minus * 50 + plus * 100\n if (pn.length == 0 || before < candidate)\n (nick, candidate)\n else\n (pn, before)\n }\n println(r._1)\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val r = (1 to n).foldLeft((\"\", -1l)){\n case ((pn, before), _) =>\n val list = in.next().split(' ')\n val nick = list.head\n val Array(plus, minus, a, b, c, d, e) = list.tail.map(_.toLong)\n val candidate = a + b + c + d + e - minus * 50 + plus * 10\n if (pn.length == 0 || before < candidate)\n (nick, candidate)\n else\n (pn, before)\n }\n println(r._1)\n}\n"}], "src_uid": "b9dacff0cab78595296d697d22dce5d9"} {"source_code": "object Solution extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val q = io.read[Int]\n for (i <- 0 until q) {\n val n = io.read[Int]\n var a = io.read[Array, Int](n)\n a = a.map(_ - 1)\n val ans = new Array[Int](n)\n for (i <- 0 until n) {\n if(a(i) != -1) {\n var size = 1\n var on = a(i)\n while(on != i) {\n size = size + 1;\n on = a(on)\n }\n while(on != -1) {\n ans(on) = size\n val nxt = a(on)\n a(on) = -1\n on = nxt\n }\n }\n }\n io.writeAll(ans)\n io.writeLine()\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn\nimport scala.collection.mutable\n\nobject B {\n val req_nr = StdIn.readInt()\n\n def main(args: Array[String]): Unit = {\n for (i <- Range(0, req_nr)) {\n val children_nr = StdIn.readInt()\n val node_idx___visited = new Array[Boolean](children_nr)\n val node_idx___cycle = new Array[Int](children_nr)\n val perm = StdIn.readLine().split(\" \").map(x => x.toInt - 1)\n // println(perm.mkString(\" \"))\n // println(node_idx___visited.mkString(\" \"))\n for (node_idx <- Range(0, children_nr)) {\n if (!node_idx___visited(node_idx)) {\n val stack = new mutable.Stack[Int]\n var curr_len = 0\n stack.push(node_idx)\n node_idx___visited(node_idx) = true;\n\n while (stack.nonEmpty) {\n val curr_node = stack.top\n curr_len += 1\n if (perm(curr_node) == node_idx) {\n while (stack.nonEmpty) {\n val x = stack.pop()\n node_idx___cycle(x) = curr_len\n }\n }\n else {\n stack.push(perm(curr_node))\n node_idx___visited(perm(curr_node)) = true\n }\n\n }\n }\n\n }\n println(node_idx___cycle.mkString(\" \"))\n }\n\n }\n}\n"}, {"source_code": "object _1249B1 extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n repeat(io.read[Int]) {\n val ps = io.read[Vector[Int]].map(_ - 1)\n\n @tailrec\n def find(i: Int, p: Int, acc: Int): Int =\n if (i == p) acc else find(i = ps(i), p, 1 + acc)\n\n val ans = ps.indices.map(i => find(ps(i), i, 1))\n io.writeAll(ans).writeLine()\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn\nimport scala.collection.mutable\n\nobject B {\n val req_nr = StdIn.readInt()\n\n def main(args: Array[String]): Unit = {\n for (i <- Range(0, req_nr)) {\n val children_nr = StdIn.readInt()\n val node_idx___visited = new Array[Boolean](children_nr)\n val node_idx___cycle = new Array[Int](children_nr)\n val perm = StdIn.readLine().split(\" \").map(x => x.toInt - 1)\n // println(perm.mkString(\" \"))\n // println(node_idx___visited.mkString(\" \"))\n for (node_idx <- Range(0, children_nr)) {\n if (!node_idx___visited(node_idx)) {\n val stack = new mutable.Stack[Int]\n var curr_len = 0\n stack.push(node_idx)\n node_idx___visited(node_idx) = true;\n\n while (stack.nonEmpty) {\n val curr_node = stack.top\n curr_len += 1\n if (perm(curr_node) == node_idx) {\n while (stack.nonEmpty) {\n val x = stack.pop()\n node_idx___cycle(x) = curr_len\n }\n }\n else {\n stack.push(perm(curr_node))\n node_idx___visited(perm(curr_node)) = true\n }\n\n }\n }\n\n }\n println(node_idx___cycle.mkString(\" \"))\n }\n\n }\n}\n"}, {"source_code": "object Solution extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val q = io.read[Int]\n for (i <- 0 until q) {\n val n = io.read[Int]\n var a = io.read[Array, Int](n)\n a = a.map(_ - 1)\n val ans = new Array[Int](n)\n for (i <- 0 until n) {\n if(a(i) != -1) {\n var size = 1\n var on = a(i)\n while(on != i) {\n size = size + 1;\n on = a(on)\n }\n while(on != -1) {\n ans(on) = size\n val nxt = a(on)\n a(on) = -1\n on = nxt\n }\n }\n }\n io.writeAll(ans)\n io.writeLine()\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}"}], "negative_code": [], "src_uid": "345e76bf67ae4342e850ab248211eb0b"} {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n @annotation.tailrec\r\n private def check(x: Int): Boolean = if (x < 0) false else (x % 11 == 0) || check(x - 111)\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val x = readInt()\r\n\r\n val ans = check(x) match {\r\n case true => \"YES\"\r\n case _ => \"NO\"\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n @annotation.tailrec\r\n private def check(x: Int): Boolean = (x >= 0) && ((x % 11 == 0) || check(x - 111))\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val x = readInt()\r\n\r\n val ans = check(x) match {\r\n case true => \"YES\"\r\n case _ => \"NO\"\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object C1 extends App {\r\n import scala.io.StdIn._\r\n\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt).toList\r\n\r\n val ans = an.foldLeft(List[(Int, Int)](0 -> 0)) {\r\n case (choices, potion) if potion >= 0 => choices.map { case (count, health) => (count + 1, health + potion) }\r\n case (choices, potion) => choices.flatMap {\r\n case choice @ (_, health) if health + potion < 0 => List(choice)\r\n case choice @ (count, health) => List(choice, (count + 1, health + potion))\r\n }\r\n }.maxBy(_._1)._1\r\n\r\n println(ans)\r\n}\r\n\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n private def check(xs: List[Byte]): Boolean = xs match {\r\n case x :: Nil => false\r\n case x :: y :: Nil => x == y\r\n case x :: y :: _ if x > y => false\r\n case _ => check(xs.tail)\r\n }\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val xs = readLine().map(_.toByte).toList\r\n \r\n val ans = check(xs) match {\r\n case true => \"YES\"\r\n case _ => \"NO\"\r\n }\r\n\r\n println(ans)\r\n }\r\n}"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n private def check(xs: List[Int], i: Int = 0): Boolean = xs match {\r\n case y :: Nil => y == i\r\n case y :: _ if (i > y) => false\r\n case y :: ys => check(ys, y)\r\n }\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val xs = readLine().map(_.toInt).toList\r\n val ans = check(xs) match {\r\n case true => \"YES\"\r\n case _ => \"NO\"\r\n }\r\n\r\n println(ans)\r\n }\r\n}"}], "src_uid": "e5e937f080b20eaec5f12f1784ae6427"} {"source_code": "import scala.collection._\nimport java.text.DecimalFormat\n\nobject A extends App {\n \n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readDoubles(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toDouble) }\n\n val n = readString.toInt\n val as = readDoubles(2 * n).map(a => a - a.floor)\n \n val sum = as.sum \n val zeros = as.count(_ < 0.0001d)\n val nzeros = as.size - zeros \n val minOnes = math.max((nzeros - zeros) / 2.0d, 0d)\n val maxOnes = math.min(nzeros, as.size / 2.d)\n //println(minOnes, maxOnes, sum)\n val res = if (sum >= minOnes && sum <= maxOnes) math.min(sum - sum.floor, sum.ceil - sum)\n else if (sum > maxOnes) sum - maxOnes\n else minOnes - sum\n \n val df = new DecimalFormat(\"###########0.000\") \n val str = df.format(math.abs(res)).replace(',', '.')\n println(str)\n}", "positive_code": [{"source_code": "import scala.collection._\nimport java.text.DecimalFormat\n\nobject A extends App {\n \n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readDoubles(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toDouble) }\n\n val n = readString.toInt\n val as = readDoubles(2 * n)\n val as2 = as.map(a => a - a.floor)\n \n var zeros = as2.count(_ < 0.0001d)\n var nzeros = as2.size - zeros\n \n var sum = as2.sum\n if (nzeros > zeros) sum = sum - (nzeros - zeros) / 2\n \n while (sum > 0 && zeros > 0 && nzeros > 0) {\n if (sum > 0.5d) {\n sum -= 1.0d\n zeros -= 1\n nzeros -= 1\n } else {\n zeros -= 1\n nzeros -= 1\n }\n //println(sum, zeros, nzeros)\n }\n \n \n val df = new DecimalFormat(\"###########0.000\") \n val str = df.format(math.abs(sum)).replace(',', '.')\n println(str)\n}"}], "negative_code": [{"source_code": "import scala.collection._\nimport java.text.DecimalFormat\n\nobject A extends App {\n \n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readDoubles(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toDouble) }\n\n val n = readString.toInt\n val as = readDoubles(2 * n)\n val as2 = as.map(a => a - a.floor).sorted\n val i0 = as2.indexWhere(a => !a.isWhole)\n val i1 = if (i0 < 0) as2.size else i0\n val as3 = as2.drop(2 * (i1 / 2))\n // println(as2.mkString(\" \"))\n var sum = 0.0d\n val as4 = if (i1 % 2 == 1) {\n val i2 = as3.size / 2 //+ 1\n sum += (if (as3(i2) < 0.5) as3(i2) else 1 - as3(i2))\n as3.indices.filter(i => i > 0 && i != i2).map(as3(_)).toArray\n } else as3\n \n val half = as4.size / 2\n val res = sum + as4.take(half).sum - half + as4.drop(half).sum\n val df = new DecimalFormat(\"###########0.000\") \n val str = df.format(res)\n println(str)\n}"}, {"source_code": "import scala.collection._\nimport java.text.DecimalFormat\n\nobject A extends App {\n \n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readDoubles(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toDouble) }\n\n val n = readString.toInt\n val as = readDoubles(2 * n)\n val as2 = as.map(a => a - a.floor).sorted\n val i0 = as2.indexWhere(_ > 0.0001d)\n val i1 = if (i0 < 0) as2.size else i0\n val as3 = as2.drop(2 * (i1 / 2))\n\n \n \n val res = if (i1 % 2 == 1) {\n var min = Double.MaxValue\n\tfor (i <- 1 until as3.size) {\n\t val as4 = as3.indices.filter(j => j > 0 && j != i).map(as3(_)).toArray\n\t val half = as4.size / 2\n var sum = as4.take(half).sum - half + as4.drop(half).sum\n\t if (math.abs(sum + as3(i)) < min) {\n\t min = math.abs(sum + as3(i))\n\t }\n\t if (math.abs(sum - 1 + as3(i)) < min) {\n\t min = math.abs(sum - 1 + as3(i))\n\t }\n }\n min\n } else {\n val half = as3.size / 2\n as3.take(half).sum - half + as3.drop(half).sum\n }\n \n val df = new DecimalFormat(\"###########0.000\") \n val str = df.format(res).replace(',', '.')\n println(str)\n}"}, {"source_code": "import scala.collection._\nimport java.text.DecimalFormat\n\nobject A extends App {\n \n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readDoubles(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toDouble) }\n\n val n = readString.toInt\n val as = readDoubles(2 * n)\n val as2 = as.map(a => a - a.floor).sorted\n val i0 = as2.indexWhere(_ > 0.0001d)\n val i1 = if (i0 < 0) as2.size else i0\n val as3 = as2.drop(2 * (i1 / 2))\n // println(as2.mkString(\" \"))\n var sum = 0.0d\n val as4 = if (i1 % 2 == 1) {\n val i2 = as3.size / 2 //+ 1\n sum += (if (as3(i2) < 0.5) as3(i2) else 1 - as3(i2))\n as3.indices.filter(i => i > 0 && i != i2).map(as3(_)).toArray\n } else as3\n \n val half = as4.size / 2\n val res = sum + as4.take(half).sum - half + as4.drop(half).sum\n val df = new DecimalFormat(\"###########0.000\") \n val str = df.format(res).replace(',', '.')\n println(str)\n}"}, {"source_code": "import scala.collection._\nimport java.text.DecimalFormat\n\nobject A extends App {\n \n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readDoubles(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toDouble) }\n\n val n = readString.toInt\n val as = readDoubles(2 * n)\n val as2 = as.map(a => a - a.floor).sorted\n val i0 = as2.indexWhere(_ > 0.0001d)\n val i1 = if (i0 < 0) as2.size else i0\n val as3 = as2.drop(2 * (i1 / 2))\n\n \n \n val res = if (i1 % 2 == 1) {\n val half = as3.size / 2 - 1\n val sum = as3.sum - half\n math.min(math.abs(sum), math.abs(sum - 1))\n } else {\n val half = as3.size / 2\n math.abs(as3.sum - half)\n }\n \n val df = new DecimalFormat(\"###########0.000\") \n val str = df.format(res).replace(',', '.')\n println(str)\n}"}, {"source_code": "import scala.collection._\nimport java.text.DecimalFormat\n\nobject A extends App {\n \n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readDoubles(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toDouble) }\n\n val n = readString.toInt\n val as = readDoubles(2 * n)\n val as2 = as.map(a => a - a.floor).sorted\n val i0 = as2.indexWhere(a => !a.isWhole)\n val i1 = if (i0 < 0) as2.size else i0\n val as3 = as2.drop(2 * (i1 / 2))\n // println(as2.mkString(\" \"))\n var sum = 0.0d\n val as4 = if (i1 % 2 == 1) {\n val i2 = as3.size / 2 //+ 1\n sum += (if (as3(i2) < 0.5) as3(i2) else 1 - as3(i2))\n as3.indices.filter(i => i > 0 && i != i2).map(as3(_)).toArray\n } else as3\n \n val half = as4.size / 2\n val res = sum + as4.take(half).sum - half + as4.drop(half).sum\n val df = new DecimalFormat(\"###########0.000\") \n val str = df.format(res).replace(',', '.')\n println(str)\n}"}], "src_uid": "f84b7122ffc7f585fd4ac8f1b3ef977a"} {"source_code": "object solution extends App {\r\n import scala.io.StdIn\r\n val t = StdIn.readInt()\r\n for (i <- 1 to t) {\r\n val p = StdIn.readInt()\r\n println(\"2 \"+(p-1))\r\n }\r\n}", "positive_code": [{"source_code": "import java.io._\r\nimport scala.collection.immutable.TreeSet\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val reader = new BufferedReader(new java.io.InputStreamReader(System.in))\r\n val writer = new PrintWriter(System.out)\r\n def readInt(): Int = reader.readLine().toInt\r\n def readLong(): Long = reader.readLine().toLong\r\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\r\n def readArrayLong(): Array[Long] = reader.readLine().split(\" \").map(_.toLong)\r\n def readString(): String = reader.readLine()\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n\r\n def solve(t: Int = 0): Unit = {\r\n\r\n val n = readInt()\r\n\r\n writer.println(s\"2 ${n - 1}\")\r\n\r\n }\r\n\r\n def main(args: Array[String]) {\r\n multiTest(solve)\r\n //solve()\r\n writer.flush()\r\n }\r\n}"}, {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val p = readInt()\r\n\r\n val (a, b) = if (p == 5) (2, 4) else (2, p / 2)\r\n\r\n println(s\"$a $b\")\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "259e39c9e63e43678e596c0d8c66937c"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C643D(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C643D(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val s = ni()\n\n if(s < 2 * n) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n if(s % 2 == 0) {\n 0 until n-1 foreach(_ => out.print(\"2 \"))\n out.println(s - 2 * (n-1))\n out.println(\"1\")\n } else {\n 0 until n-1 foreach(_ => out.print(\"1 \"))\n out.println(s - (n-1))\n out.print(n)\n }\n }\n }\n}\n", "positive_code": [{"source_code": "\nimport java.util.Scanner\n\nobject D_1354 extends App {\n var scanner = new Scanner(System.in)\n\n val num = scanner.nextInt()\n val sum = scanner.nextInt()\n\n val isPossible = {\n num * 2 <= sum\n }\n\n if (!isPossible) {\n println(\"NO\")\n }\n else {\n val max = sum - num + 1\n println(\"YES\")\n print(\"1 \" * (num - 1))\n println(max)\n println(max - 1)\n }\n}"}, {"source_code": "object D extends App {\n val Array(n, s) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val an =\n if (s >= 2 * n) (s - 2 * n + 2) :: List.fill(n - 1)(2)\n else List.empty\n\n if (an.isEmpty) println(\"NO\")\n else {\n println(\"YES\")\n println(an.mkString(\" \"))\n println(1)\n }\n}\n"}, {"source_code": "object ProblemF extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val n = in.nextInt()\n val s = in.nextInt()\n\n if (n * 2 > s) {\n println(\"NO\")\n } else {\n println(\"YES\")\n print(\"2 \" * (n - 1))\n println(s - 2 * (n - 1))\n println(1)\n }\n\n}"}], "negative_code": [], "src_uid": "4a644d97824d29c42dbb48d79b9958fe"} {"source_code": "object A1556 {\n\n /** TODO: Check! */\n private val multipleTests: Boolean = true\n\n def run(testNum: Int): Unit = {\n val c = int()\n val d = int()\n if (c == 0 && d == 0) {\n println(0)\n } else if (c % 2 != d % 2) {\n println(-1)\n } else if (c == d) {\n println(1)\n } else {\n println(2)\n }\n }\n\n /** Template. */\n\n private val onlineJudge = System.getProperty(\"ONLINE_JUDGE\") != null\n\n def main(args: Array[String]): Unit = {\n val t = if (multipleTests) reader.int() else 1\n (1 to t).foreach(run)\n }\n\n /** I/O. */\n\n import java.io._\n import java.nio.file._\n\n private val inputFileName = \"input.txt\"\n private val reader = if (onlineJudge) FastReader.fromConsole() else FastReader.fromFile(inputFileName)\n\n private def string(): String = reader.string()\n private def int(): Int = reader.int()\n private def long(): Long = reader.long()\n private def double(): Double = reader.double()\n\n /** TODO: implement faster reader with buffer */\n /** TODO: implement writer */\n final case class FastReader(delegate: BufferedReader) extends Iterator[String] with AutoCloseable {\n import java.util.StringTokenizer\n\n def string(): String = next()\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def boolean(): Boolean = next().toBoolean\n def byte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def short(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def int(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def long(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def bigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def float(): Float = next().toFloat\n def double(): Double = next().toDouble\n def bigDecimal(): BigDecimal = BigDecimal(next())\n def lineNumber(): Int = linedDelegate.getLineNumber\n\n @inline def nextLine(): String = {\n current = None // reset the rest of current line\n delegate.readLine()\n }\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n override def next(): String = tokenizer().getOrElse(throw new RuntimeException(\"End of input\")).nextToken()\n override def close(): Unit = delegate.close()\n\n private lazy val linedDelegate = new LineNumberReader(delegate)\n private val tokenizers = Iterator.continually(delegate.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n }\n\n object FastReader {\n import scala.io.Codec\n\n def fromConsole()(implicit codec: Codec): FastReader = fromStream(System.in)\n def fromFile(fileName: String)(implicit codec: Codec): FastReader = FastReader {\n Files.newBufferedReader(Paths.get(fileName), codec.charSet)\n }\n def fromString(string: String): FastReader = FastReader(new BufferedReader(new StringReader(string)))\n def fromStream(inputStream: InputStream)(implicit codec: Codec): FastReader = FastReader {\n new BufferedReader(new InputStreamReader(inputStream, codec.charSet))\n }\n }\n}\n", "positive_code": [{"source_code": "object A extends App {\r\n\r\n def operations: (Int, Int) => Int = (_, _) match {\r\n case (0, 0) => 0\r\n case (c, d) if c == d => 1\r\n case (c, d) if math.abs(c - d) % 2 == 0 => 2\r\n case _ => -1\r\n }\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(c, d) = readLine().split(\" \").map(_.toInt)\r\n\r\n println(operations(c, d))\r\n }\r\n\r\n}\r\n"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport scala.util.Sorting.quickSort\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val writer = new PrintWriter(System.out)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {\r\n while (!st.hasMoreTokens) {\r\n st = new StringTokenizer(reader.readLine())\r\n }\r\n st.nextToken()\r\n }\r\n\r\n def readInt() = next.toInt\r\n def readLong() = next.toLong\r\n def readString() = next()\r\n def readArrayInt(n: Int = 0): Array[Int] = {\r\n if (n == 0)\r\n return reader.readLine().split(\" \").map(_.toInt)\r\n\r\n val a = new Array[Int](n)\r\n for (i <- 0 until n) {\r\n a(i) = readInt()\r\n }\r\n a\r\n }\r\n\r\n def pow(a: Int, b: Int): Long = {\r\n if (b == 0) return 1\r\n\r\n val rs = pow(a, b / 2)\r\n rs * rs * (if (b % 2 == 0) 1 else a)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b\r\n\r\n def root(u: Int, p: Array[Int]): Int = {\r\n if (p(u) < 0) return u\r\n p(u) = root(p(u), p)\r\n p(u)\r\n }\r\n\r\n def join(u: Int, v: Int, p: Array[Int]): Unit = {\r\n var x = root(u, p)\r\n var y = root(v, p)\r\n if (x == y) return\r\n\r\n if (p(y) < p(x)) {\r\n val t = x\r\n x = y\r\n y = t\r\n }\r\n p(x) += p(y)\r\n p(y) = x\r\n }\r\n\r\n def solve(t: Int = 0): Unit = {\r\n val (a,b) = (readInt(), readInt())\r\n\r\n if (a == b) {\r\n if (a == 0) {\r\n writer.println(0)\r\n return\r\n }\r\n writer.println(1)\r\n return\r\n }\r\n\r\n if ((a + b) % 2 == 0) {\r\n writer.println(2)\r\n return\r\n }\r\n\r\n writer.println(-1)\r\n\r\n }\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def main(args: Array[String]) {\r\n multiTest(solve)\r\n //solve()\r\n writer.flush()\r\n }\r\n}"}], "negative_code": [], "src_uid": "8e7c0b703155dd9b90cda706d22525c9"} {"source_code": "import scala.io.StdIn.readLine\r\n\r\nobject Solution {\r\n\r\n def rsi() = readLine().split(\"\\\\s+\").map(_.toInt)\r\n\r\n def solve(a: Int, b: Int) = {\r\n if (a == 0)1\r\n else a + 2 * b + 1\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val cases = readLine.toInt\r\n for (\r\n i <- 0 until cases;\r\n line = rsi\r\n ) println(solve(line(0), line(1)))\r\n }\r\n}\r\n\r\n", "positive_code": [{"source_code": "import java.io._\nimport java.nio.file._\nimport java.util.StringTokenizer\n \nimport scala.+:\nimport scala.io.Codec\n \nobject Main {\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)))\n val pw = new PrintWriter(System.out, false)\n \n val t = sc.nextInt()\n var i = 0\n for (i <- 0 to (t-1)) {\n Solver.solve(sc, pw, i)\n pw.flush()\n }\n }\n}\n \n/**\n * Actual solution\n */\nobject Solver {\n def solve(sc: Scanner, pw: PrintWriter, testcast: Int): Unit = {\n val a = sc.nextInt(); val b = sc.nextInt();\n pw.println(func(a,b))\n }\n\n def func(x: Int, y: Int): Int = (x, y) match {\n case (0, _) => 1\n case (x, 0) => x + 1\n case (x, y) => ((y * 2) + x + 1)\n }\n}\n \n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n \n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n \n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n \n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\r\n\r\nobject Solution {\r\n\r\n def rsi() = readLine().split(\"\\\\s+\").map(_.toInt)\r\n\r\n def solve(a: Int, b: Int) = {\r\n if (a == 0)1\r\n else a + 2 * b\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val cases = readLine.toInt\r\n for (\r\n i <- 0 until cases;\r\n line = rsi\r\n ) println(solve(line(0), line(1)))\r\n }\r\n}\r\n\r\n"}], "src_uid": "2b6e670b602a89b467975edf5226219a"} {"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var n = readInt\n var map: Map[Int, Int] = Map();\n var list = List[(Int, Int)]();\n for (i <- 0 until n * (n - 1) / 2 - 1) {\n var Array(a, b) = readLine.split(\" \").map(_.toInt);\n if (map.contains(a)) {\n map.put(a, map.get(a).get + 1);\n } else {\n map.put(a, 1);\n }\n if (map.contains(b)) {\n map.put(b, map.get(b).get + 1);\n } else {\n map.put(b, 1);\n }\n list = (a, b) :: list;\n }\n var min = map.filter(p => p._2 == n - 2);\n for (i <- list) {\n if (i._1 == min.head._1) {\n var c = i._2;\n for (j <- list) {\n if (j._1 == c && j._2 == min.last._1) {\n println(min.head._1 + \" \" + min.last._1);\n return ;\n }\n }\n }\n }\n println(min.last._1 + \" \" + min.head._1);\n }\n\n}", "positive_code": [{"source_code": "object P027B extends App {\n val n = readInt\n var wins = (for (i <- 0 to n-1) yield 0) toArray\n var losses = (for (i <- 0 to n-1) yield 0) toArray\n var ids = (for (i <- 0 to n-1) yield i) toList;\n for (i <- 1 to n*(n-1)/2 - 1) {\n val opponents = readLine.split(' ').map(x => x.toInt-1)\n wins(opponents(0)) += 1\n losses(opponents(1)) += 1\n }\n ids = ids.sortWith(wins(_) < wins(_))\n val missed = ids.filter(x => wins(x) + losses(x) != n-1)\n printf(\"%d %d\\n\", missed(1)+1, missed(0)+1)\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val answer = Array.ofDim[Int](n, n)\n (0 until n).foreach{ i => answer(i)(i) = 1 }\n val count = n * (n - 1) / 2 - 1\n (0 until count).foreach { _ =>\n val Array(a, b) = in.next().split(' ').map(_.toInt - 1)\n answer(a)(b) = 2\n answer(b)(a) = 1\n }\n\n val result = (0 until n).flatMap { i =>\n answer(i)\n .indices\n .find(j => answer(i)(j) == 0)\n .map(j => (i + 1, j + 1))\n .filter(p => answer(p._1 - 1).sum >= answer(p._2 - 1).sum) }.head\n\n println(s\"${result._1} ${result._2}\")\n}"}], "negative_code": [{"source_code": "object P027B extends App {\n val n = readInt\n var wins = (for (i <- 0 to n-1) yield 0) toArray\n var losses = (for (i <- 0 to n-1) yield 0) toArray\n var ids = (for (i <- 0 to n-1) yield i) toList;\n for (i <- 1 to n*(n-1)/2 - 1) {\n val opponents = readLine.split(' ').map(x => x.toInt-1)\n wins(opponents(0)) += 1\n losses(opponents(1)) += 1\n }\n ids = ids.sortWith(wins(_) < wins(_))\n val missed = ids.zipWithIndex.filter(x => wins(x._1) != x._2)\n printf(\"%d %d\\n\", missed(0)._1+1, ids.find(x => wins(x) + losses(x) != n-1).get+1)\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val answer = Array.ofDim[Boolean](n, n)\n (0 until n).foreach{i => answer(i)(i) = true}\n val count = n * (n - 1) / 2 - 1\n (0 until count).foreach { _ =>\n val Array(a, b) = in.next().split(' ').map(_.toInt - 1)\n answer(a)(b) = true\n answer(b)(a) = true\n }\n\n val result = (0 until n).flatMap { i => answer(i).indices.find(j => !answer(i)(j)).map(j => (i + 1, j + 1)) }.head\n\n\n println(s\"${result._1} ${result._2}\")\n}"}], "src_uid": "f1ac6da78aed11d9118a85182c5644de"} {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n\n var a = new Array[Int](n)\n for(i <- 0 until n)\n a(i) = sc.nextInt()\n\n a = a.sorted\n // a.foreach{println}\n var acc = 1\n for(i <- 1 until n){\n val now = a(i)\n if(now > acc)\n acc += 1\n }\n println(acc + 1)\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject _358B extends App {\n val s = readInt\n val num = (readLine.split(\" \") map (_.toInt)).sorted\n val ans = {\n var acc = 1\n for (i <- 1 until s) {\n if (num(i) > acc) acc += 1\n }\n acc + 1\n }\n println(ans)\n}"}, {"source_code": "object Solution {\n def re(ns:List[Long],i:Int):Int =\n if (ns.isEmpty) i \n else if (ns.head >= i) re(ns.tail,i+1)\n else re(ns.tail,i)\n def main(args: Array[String]) {\n val n = readInt\n val ns = readLine.split(\" \").map(_.toLong).sorted.toList\n println(re(ns,1))\n }\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n println(in.next().split(' ').map(_.toInt).sorted.foldLeft(1)\n {\n case(acc, el) if el >= acc => acc + 1\n case(acc, el) => acc\n })\n}\n"}, {"source_code": "object Main extends App {\n\timport scala.io.StdIn._\n\n\tval n = readInt\n\tvar A = readLine.split(\" \").map(_.toInt).sorted\n\tvar ans = 1\n\n\tfor (a <- A) {\n\t\tif (a >= ans)\n\t\t\tans += 1\n\t}\n\n\tprintln(ans)\n\n}"}, {"source_code": "object B682 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n).sorted\n var i = 1\n for(idx <- 0 until n) {\n if(in(idx) == i) {\n i += 1\n } else if(in(idx) > i) {\n in(idx) = i\n i += 1\n }\n }\n println(i)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _682B extends CodeForcesApp {\n override def apply(io: IO) = io.write(solve(io.read[List[Int]].sorted))\n\n @tailrec def solve(l: List[Int], c: Int = 1): Int = l match {\n case x :: xs => solve(xs, c + (x >= c).to[Int])\n case _ => c\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toYesNo = if(x) \"yes\" else \"no\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def bitCount: Int = java.lang.Integer.bitCount(x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeLine(obj: Any*): this.type = {\n if (obj.isEmpty) printer.println() else obj foreach printer.println\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _682B extends CodeForcesApp {\n override def apply(io: IO) = {import io._\n val data = read[List[Int]].sorted\n\n @tailrec\n def solve(l: List[Int], c: Int): Int = l match {\n case x :: xs if x >= c => solve(xs, c + 1)\n case x :: xs if x < c => solve(xs, c)\n case _ => c\n }\n\n write(solve(data, 1))\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toYesNo = if(x) \"yes\" else \"no\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def bitCount: Int = java.lang.Integer.bitCount(x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]\n def memoize[A, B](f: A => B): A ==> B = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeLine(obj: Any*): this.type = {\n if (obj.isEmpty) printer.println() else obj foreach printer.println\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject _358B extends App {\n val s = readInt\n val num = readLine.split(\" \") map (_.toInt)\n val max = num.max\n val ans = {\n val reduced = num filter(x => (x + 1) < max)\n if (reduced.isEmpty) max + 1\n else max - 1\n }\n println(ans)\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject _358B extends App {\n val s = readInt\n val num = (readLine.split(\" \") map (_.toInt)).sorted\n val range = (1 to num.length)\n val ans = {\n val max = num.max\n if (range == num) max + 1\n else range.length + 1\n }\n println(ans)\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject _358B extends App {\n val s = readInt\n val num = (readLine.split(\" \") map (_.toInt)).sorted\n val ans = {\n var acc = 1\n for (i <- 0 until num.length) {\n if (num(i) > acc) acc += 1\n }\n acc + 1\n }\n println(ans)\n}"}], "src_uid": "482b3ebbbadd583301f047181c988114"} {"source_code": "import scala.io.Source\r\n\r\nobject Contest extends App {\r\n def checkPolindrom(str: String): Boolean = {\r\n for (i <- 0 until (str.length - (str.length % 2))) {\r\n if (str(i) != str(str.length - i - 1)) {\r\n return false\r\n }\r\n }\r\n return true\r\n }\r\n\r\n val input = Source.fromInputStream(System.in).getLines()\r\n val t = input.next().toInt\r\n val res = new Array[Int](t)\r\n for (i <- 0 until t) {\r\n val Array(n, k) = input.next().split(\" \")\r\n val str = input.next()\r\n if (!checkPolindrom(str) && k != \"0\") res(i) = 2\r\n else res(i) = 1\r\n }\r\n res.foreach(println)\r\n}\r\n", "positive_code": [{"source_code": "object Main {\n private val in = scala.io.StdIn\n\n def main(args: Array[String]): Unit = {\n val T = in.readInt()\n for (t <- 0 until T) {\n val Array(_, k) = in.readLine().split(\" \").map(_.toInt)\n val s = in.readLine()\n if (k == 0 || s == s.reverse)\n println(1)\n else\n println(2)\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readInt\r\n\r\nobject cf1633a {\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt()\r\n while(t > 0) {\r\n t -= 1\r\n var Array(n, k) = readLine.split(\" \").map(_.toInt)\r\n var s = readLine\r\n var r = s.reverse\r\n if(k == 0) {\r\n println(1)\r\n }\r\n else {\r\n if(s == r) {\r\n println(1)\r\n }\r\n else {\r\n println(2)\r\n }\r\n }\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val Array(_, k) = readInts()\n val str = readLine()\n val answer = if (str == str.reverse) 1\n else if (k == 0) 1\n else 2\n println(answer)\n }\n\n\n\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(var a: Int, var b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return (a).compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mapp = mutable.Map[pair, Int]()\n\n val t = readInt()\n\n for (tt <- 1 to t) {\n val n = readInt()\n val k = readInt()\n val s = readString()\n var pal = true\n for (i <- 0 until n) {\n if (s(i) != s(n-i-1))\n pal = false\n }\n if (k == 0 || pal) {\n writer.println(1)\n } else {\n writer.println(2)\n }\n\n def check(kk: Long, fi: Long): Boolean = {\n return false\n }\n def bs(st:Long, en:Long, fi:Long): Long = {\n if (en - st <= 1L) {\n if (check(st, fi))\n return st\n else\n return en\n }\n val mid = (st + en) / 2L\n if (check(mid, fi))\n return bs(st, mid, fi)\n else\n return bs(mid, en, fi)\n }\n }\n writer.flush()\n}"}], "negative_code": [], "src_uid": "08cd22b8ee760a9d2dacb0d050dcf37a"} {"source_code": "object C1201 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readLongs(2)\n val arr = readLongs(n.toInt).sorted\n val midPos = n.toInt / 2\n val median = arr(midPos)\n var res = median\n def check(num: Long): Boolean = {\n var score = 0L\n for (i <- midPos until n.toInt) {\n if (num > arr(i))\n score += num - arr(i)\n if (score > k) return false\n }\n if (score <= k) true\n else false\n }\n var s = 1L\n var e = 2000000000L\n while (s <= e) {\n val mid = (s + e) / 2\n if (check(mid)) {\n res = mid\n s = mid + 1\n } else {\n e = mid - 1\n }\n }\n out.println(res)\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject C_1201 extends App {\n\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n var A = readLine().split(\" \").map(_.toLong).sorted\n// println(A.mkString(\",\"))\n\n val prefix = Array.ofDim[Long](n)\n\n val m = n / 2\n prefix(m) = A(m)\n for (i <- m + 1 until n) {\n prefix(i) = prefix(i - 1) + A(i)\n }\n// println(prefix.mkString(\",\"))\n\n def binSearch(x: Long) = {\n var l = m\n var r = n - 1\n\n while (l < r) {\n val mid = ((l.toLong + r.toLong) / 2).toInt\n if (A(mid) >= x) r = mid - 1\n else l = mid + 1\n }\n\n if (r < n && A(r) < x) r else r - 1\n\n // m/2 .. r => < x\n }\n\n def findMax = {\n var max = A(m)\n var l = A(m) + 1\n var r = A(m) + k\n while (l <= r) {\n val mid = (l + r) / 2\n val j = binSearch(mid)\n if (prefix(j) + k >= (j - m + 1) * mid) {\n max = mid\n l = mid + 1\n } else {\n r = mid - 1\n }\n }\n// for (i <- A(m) + 1 to A(m) + k) {\n// val j = binSearch(i)\n// if (prefix(j) + k >= (j - m + 1) * i) max = i\n// }\n max\n }\n\n println(findMax)\n}\n"}], "negative_code": [{"source_code": "object C1201 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var Array(n, k) = readInts(2)\n val arr = readInts(n).sorted\n val midPos = n / 2\n val median = arr(midPos)\n var res = median\n val max = arr.max\n val minScore = arr.takeRight(midPos + 1).map(max - _).sum\n if (minScore <= k) {\n res = max\n k -= minScore\n var s = 1\n var e = k / (midPos + 1)\n while (s <= e) {\n val mid = (s + e) / 2\n if ((mid * (midPos + 1)) <= k) {\n res = max + mid\n s = mid + 1\n } else {\n e = mid - 1\n }\n }\n }\n out.println(res)\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object C1201 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var Array(n, k) = readLongs(2)\n val arr = readLongs(n.toInt).sorted\n val midPos = n.toInt / 2\n val median = arr(midPos)\n var res = median\n val max = arr.max\n val minScore = arr.takeRight(midPos + 1).map(max - _).sum\n if (minScore <= k) {\n res = max\n k -= minScore\n var s = 1L\n var e = k\n while (s <= e) {\n val mid = (s + e) / 2\n if ((mid * (midPos + 1)) <= k) {\n res = max + mid\n s = mid + 1\n } else {\n e = mid - 1\n }\n }\n }\n out.println(res)\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object C1201 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var Array(n, k) = readLongs(2)\n val arr = readLongs(n.toInt).sorted\n val midPos = n.toInt / 2\n val median = arr(midPos)\n var res = median\n val max = arr.max\n val minScore = arr.takeRight(midPos + 1).map(max - _).sum\n if (minScore <= k) {\n res = max\n k -= minScore\n var s = 1L\n var e = k / (midPos + 1)\n while (s <= e) {\n val mid = (s + e) / 2\n if ((mid * (midPos + 1)) <= k) {\n res = max + mid\n s = mid + 1\n } else {\n e = mid - 1\n }\n }\n }\n out.println(res)\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C_1201 extends App {\n\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n var A = readLine().split(\" \").map(_.toInt).sorted\n// println(A.mkString(\",\"))\n\n val prefix = Array.ofDim[Long](n)\n\n val m = n / 2\n prefix(m) = A(m)\n for (i <- m + 1 until n) {\n prefix(i) = prefix(i - 1) + A(i)\n }\n// println(prefix.mkString(\",\"))\n\n def binSearch(x: Int) = {\n var l = m\n var r = n - 1\n\n while (l < r) {\n val mid = ((l.toLong + r.toLong) / 2).toInt\n if (A(mid) >= x) r = mid - 1\n else l = mid + 1\n }\n\n if (r < n && A(r) < x) r else r - 1\n\n // m/2 .. r => < x\n }\n\n def findMax = {\n var max = A(m)\n var l = A(m) + 1\n var r = A(m) + k\n while (l <= r) {\n val mid = ((l.toLong + r.toLong) / 2).toInt\n val j = binSearch(mid)\n if (prefix(j) + k >= (j - m + 1) * mid) {\n max = mid\n l = mid + 1\n } else {\n r = mid - 1\n }\n }\n// for (i <- A(m) + 1 to A(m) + k) {\n// val j = binSearch(i)\n// if (prefix(j) + k >= (j - m + 1) * i) max = i\n// }\n max\n }\n\n println(findMax)\n}\n"}], "src_uid": "0efd4b05b3e2e3bc80c93d37508a5197"} {"source_code": "object B {\n import scala.collection.mutable\n def main(args: Array[String]){\n val line1 = readLine().split(\" \")\n val line2 = readLine().split(\" \").map(_.toInt)\n val n = line1(0).toInt\n val k = line1(1).toInt\n val boxes = mutable.Map[Int, Int]()\n line2.zipWithIndex.foreach{ case (box, idx) =>\n val rem = box % k\n if(!boxes.contains(rem)) boxes(rem) = 0\n boxes(rem) += 1\n }\n\n var total = 0\n\n line2.foreach{ l =>\n val rem = l % k\n val miss = (k - rem) % k\n if(boxes.contains(miss)) {\n if (rem == miss) {\n if(boxes(miss) > 1) {\n boxes(miss) -= 2\n total += 2\n }\n } else {\n if(boxes(miss) > 0 && boxes(rem) > 0) {\n boxes(miss) -= 1\n boxes(rem) -= 1\n total += 2\n }\n }\n }\n }\n\n println(total)\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val A = na(N)\n val byM = Array.ofDim[Int](K)\n REP(N) { i =>\n byM(A(i) % K) += 1\n }\n\n DEBUG {\n REP(K) { i =>\n debug(byM(i).toString)\n }\n }\n\n var ans = 0\n REP(K) { i =>\n if (i <= K - i) {\n if (i == (K - i) % K) {\n ans += byM(i) / 2 * 2\n } else {\n val v = min(byM(i), byM((K - i) % K))\n ans += v * 2\n }\n }\n }\n out.println(ans)\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugNum(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n import java.util\n val N, K = ni()\n val A = na(N)\n val byM = Array.fill[util.ArrayDeque[Int]](K)(new util.ArrayDeque[Int]())\n REP(N) { i =>\n byM(A(i) % K).add(A(i))\n }\n\n DEBUG {\n REP(K) { i =>\n debug(byM(i).toString)\n }\n }\n\n var ans = 0\n REP(K) { i =>\n while (!byM(i).isEmpty && !byM((K - i) % K).isEmpty && !(i == 0 && byM(i).size < 2)) {\n byM(i).poll()\n byM((K - i) % K).poll()\n ans += 2\n }\n }\n out.println(ans)\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugNum(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}, {"source_code": "object B {\n import scala.collection.mutable\n def main(args: Array[String]){\n val line1 = readLine().split(\" \")\n val line2 = readLine().split(\" \").map(_.toInt)\n val n = line1(0).toInt\n val k = line1(1).toInt\n val boxes = Array.ofDim[Int](n)\n line2.zipWithIndex.foreach{case (box, idx) => boxes(idx) = box}\n\n var total = 0\n\n val used = mutable.Set[Int]()\n boxes.indices.foreach { i =>\n if(!used.contains(i)) {\n boxes.indices.foreach { j =>\n if(i != j && !used.contains(j)) {\n if((boxes(i) + boxes(j)) % k == 0) {\n total += 1\n used += i\n used += j\n }\n }\n }\n }\n }\n println(total)\n }\n}\n"}, {"source_code": "object B {\n import scala.collection.mutable\n def main(args: Array[String]){\n val line1 = readLine().split(\" \")\n val line2 = readLine().split(\" \").map(_.toInt)\n val n = line1(0).toInt\n val k = line1(1).toInt\n val boxes = mutable.Map[Int, Int]()\n line2.zipWithIndex.foreach{ case (box, idx) =>\n val rem = box % k\n if(!boxes.contains(rem)) boxes(rem) = 0\n boxes(rem) += 1\n }\n\n var total = 0\n\n line2.foreach{ l =>\n val rem = l % k\n val miss = (k - rem) % k\n if(boxes.contains(miss)) {\n if (rem == miss) {\n if(boxes(miss) > 1) {\n boxes(miss) -= 2\n total += 2\n }\n } else {\n if(boxes(miss) > 0) {\n boxes(miss) -= 1\n boxes(rem) -= 1\n total += 2\n }\n }\n }\n }\n\n println(total)\n }\n}\n"}, {"source_code": "object B {\n def main(args: Array[String]){\n val line1 = readLine().split(\" \")\n val line2 = readLine().split(\" \").map(_.toInt)\n val n = line1(0).toInt\n val k = line1(1).toInt\n val boxes = Array.ofDim[Int](n)\n line2.zipWithIndex.foreach{ case (box, idx) =>\n val rem = box % k\n if(!boxes.contains(rem)) boxes(rem) = 0\n boxes(rem) += 1\n }\n\n var total = 0\n\n line2.foreach{ l =>\n val rem = l % k\n val miss = (k - rem) % 2\n if(boxes.contains(miss)) {\n if (rem == miss) {\n if(boxes(miss) > 1) {\n boxes(miss) -= 2\n total += 2\n }\n } else {\n if(boxes(miss) > 0) {\n boxes(miss) -= 1\n boxes(rem) -= 1\n total += 2\n }\n }\n }\n }\n\n println(total)\n }\n}\n"}], "src_uid": "3f3a013cedaaf8cbee0a74a4ed50f09d"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val sorted = data.zipWithIndex.sorted\n var j = 0\n var k = 0\n while(k < n) {\n if (j >= sorted(k)._1)\n j += 1\n else\n j = sorted(k)._1\n data(sorted(k)._2) = j\n k += 1\n }\n println(data.mkString(\" \"))\n}", "positive_code": [{"source_code": "//package GoodBye2013\n\nimport scala.io.Source\n\n/**\n * User: Oleg\n * Date: 1/2/14\n * Time: 3:27 AM\n */\nobject C {\n def main(args: Array[String]) {\n val in = Source.stdin.getLines\n val n = in.next().toInt\n val solution = Array.fill(n)(0)\n val a = in.next().split(' ').map(_.toInt).zipWithIndex.sorted.foldLeft(0)((prev, elem) => elem match {\n case (x, index) => {\n val next = if (x <= prev) prev + 1 else x\n solution(index) = next\n next\n }})\n println(solution.mkString(\" \"))\n }\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 14 Aug 2016\n */\nobject C397 extends App {\n\n def solve() = {\n val n = scala.io.StdIn.readInt()\n val a: Array[(Int,Int)] = scala.io.StdIn.readLine().split(\" \").map(_.toInt).zipWithIndex.sortBy(_._1)\n val b: Array[Int] = Array.ofDim[Int](n)\n b(a(0)._2) = a(0)._1\n var min = a(0)._1 + 1\n for (i <- 1 until n) {\n val give = min max a(i)._1\n b(a(i)._2) = give\n min = give + 1\n }\n println(b.mkString(\" \"))\n }\n\n solve()\n\n}\n"}, {"source_code": "//package codeforces\n\nimport java.io.InputStreamReader\nimport scala.util.Sorting\n\n/**\n * TODO: describe\n *\n * @author keks\n */\nobject T379C {\n private var rand = new java.util.Random()\n\n def main(args: Array[String]) {\n readInt()\n getDifferentRatings(readLine().split(' ').map(_.toInt)).foreach(x => print(x + \" \"))\n }\n\n def getDifferentRatings(s: Array[Int]): List[Int] = s match {\n case Array() => Nil\n case l =>\n val n: Int = l.length\n\n val is = (0 until n).toArray\n quicksort(l, is, 0, n - 1)\n\n var max = Int.MinValue\n for (i <- 0 until n) {\n val e: Int = l(i)\n if (e > max) {\n l(i) = e\n max = e\n } else {\n max += 1\n l(i) = max\n }\n }\n\n quicksort(is, l, 0, n - 1)\n l.toList\n }\n\n /**\n * Synchronously quicksort both arrays\n */\n def quicksort(a: Array[Int], is: Array[Int], l: Int, r: Int) {\n if (r <= l) return\n\n val midIdx = rand.nextInt(r - l + 1) + l\n var mid = a(midIdx)\n\n swap(a, r, midIdx)\n swap(is, r, midIdx)\n\n var p1 = l\n var p2 = l\n while (p2 < r) {\n if (a(p2) < mid) {\n swap(a, p1, p2)\n swap(is, p1, p2)\n p1 += 1\n p2 += 1\n } else p2 += 1\n }\n\n swap(a, r, p1)\n swap(is, r, p1)\n\n // optimization to handle equal elements\n val newR = p1 - 1\n while (a(p1) == mid && p1 < r) p1 += 1\n\n quicksort(a, is, l, newR)\n quicksort(a, is, p1, r)\n }\n\n def swap(a: Array[Int], from: Int, to: Int) {\n if (from == to) return\n\n var tmp = a(from)\n a(from) = a(to)\n a(to) = tmp\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt\n val A = readLine.split(\" \")\n .map(_.toLong)\n .zipWithIndex\n .sortBy(_._1)\n .toList\n\n val B = Array.ofDim[Long](n)\n solve(A, B, 0)\n println(B.mkString(\" \"))\n }\n\n def solve(A: List[(Long, Int)], B: Array[Long], maxi: Long) {\n A match {\n case x::xs => {\n val res = Math.max(maxi, x._1)\n val pos = x._2\n B(pos) = res\n solve(xs, B, res + 1)\n }\n case Nil => Nil\n }\n }\n}"}, {"source_code": "object Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n\n val n = input.next().toInt\n val a = input.next().split(\" \").map(_.toInt).toArray\n\n val used = new java.util.TreeMap[Int, Int]()\n\n val r = new Array[Int](a.size)\n\n for (i <- 0 until a.length) {\n val exp = a(i)\n val v = used.floorEntry(exp)\n if (v == null || v.getValue < exp) {\n r(i) = exp\n if (used.containsKey(exp + 1)) {\n used.put(exp, used.get(exp + 1))\n used.remove(exp + 1)\n } else\n used.put(exp, exp + 1)\n } else {\n r(i) = v.getValue\n if (used.containsKey(v.getValue + 1)) {\n used.put(v.getKey, used.get(v.getValue + 1))\n used.remove(v.getValue + 1)\n } else {\n used.put(v.getKey, v.getValue + 1)\n }\n }\n }\n\n print(r.mkString(\" \"))\n }\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val n = readInt\n val as = (readLongs(n).zipWithIndex).sortBy(_._1)\n \n val bs = Array.ofDim[Long](n)\n \n var x = 0L\n \n for (a <- as) {\n val give = x max a._1\n bs(a._2) = give\n x = give + 1\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(bs.mkString(\" \"))\n Console.flush\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.nio.CharBuffer\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.PriorityQueue\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject Stub extends App {\n // val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n object Input {\n import java.lang.Character._\n\n lazy val in = new BufferedReader(new InputStreamReader(java.lang.System.in))\n var buf: Array[Char] = Array()\n var pos: Int = 0\n\n def next(): String = {\n while (pos == buf.length) {\n buf = in.readLine.toArray\n pos = 0\n }\n while (isWhitespace(buf(pos))) {\n pos += 1\n }\n while (pos == buf.length) {\n buf = in.readLine.toArray\n pos = 0\n }\n val s = pos\n while (pos < buf.length && !isWhitespace(buf(pos))) {\n pos += 1\n }\n new java.lang.String(buf, s, pos - s)\n }\n\n def nextInt(): Int = next.toInt\n\n def nextLong(): Long = next.toLong\n\n def nextFloat(): Float = next.toFloat\n\n def nextDouble(): Double = next.toDouble\n\n val nextString: () => String = next _\n }\n\n import Input._\n\n val N = nextInt\n val A = Array.fill(N)(nextInt)\n val S = Array.tabulate(N)(identity[Int]).sortBy(A(_))\n val res = Array.fill(N)(0)\n\n var r = 0\n var i = 0\n var j = 0\n while (i < N) {\n j = S(i)\n r = if ((r + 1) > A(j)) (r + 1)\n else A(j)\n res(j) = r\n i = i + 1\n }\n \n out.println(res.mkString(\" \"))\n out.flush\n}\n"}], "negative_code": [{"source_code": "//package GoodBye2013\n\nimport scala.io.Source\n\n/**\n * User: Oleg\n * Date: 1/2/14\n * Time: 3:27 AM\n */\nobject C {\n def main(args: Array[String]) {\n val in = Source.stdin.getLines\n val n = in.next().toInt\n val solution = Array.fill(n)(0)\n val a = in.next().split(' ').zipWithIndex.sorted.foldLeft(0)((prev, elem) => elem match {\n case (str, index) => {\n val x = str.toInt\n val next = if (x <= prev) prev + 1 else x\n solution(index) = next\n next\n }})\n println(solution.mkString(\" \"))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt).zipWithIndex.sorted\n var j = 0\n (0 until n).foreach { case(i) =>\n if (j >= data(i)._1) {\n j += 1\n data(i) = (j, data(i)._2)\n }\n }\n println(data.sortBy(_._2).map(_._1).mkString(\" \"))\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt).zipWithIndex.sorted\n var j = 0\n var k = 0\n while(k < n) {\n if (j >= data(k)._1) {\n j += 1\n data(k) = (j, data(k)._2)\n }\n k += 1\n }\n println(data.sortBy(_._2).map(_._1).mkString(\" \"))\n}"}, {"source_code": "object Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n\n val n = input.next().toInt\n val a = input.next().split(\" \").map(_.toInt).toArray\n\n val used = new java.util.TreeMap[Int, Int]()\n\n val r = new Array[Int](a.size)\n\n for (i <- 0 until a.length) {\n val exp = a(i)\n val v = used.floorEntry(exp)\n if (v == null || v.getValue < exp) {\n if (used.containsKey(exp + 1)) {\n used.put(exp, used.get(exp + 1))\n used.remove(exp + 1)\n } else\n used.put(exp, exp + 1)\n r(i) = exp\n } else {\n r(i) = v.getValue\n if (used.containsKey(v.getValue)) {\n used.put(v.getKey, used.get(v.getValue))\n used.remove(v.getValue)\n } else {\n used.put(v.getKey, v.getValue + 1)\n }\n }\n }\n\n print(r.mkString(\" \"))\n }\n}"}, {"source_code": "object Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n\n val n = input.next().toInt\n val a = input.next().split(\" \").map(_.toInt).toArray\n\n val used = new java.util.TreeMap[Int, Int]()\n\n val r = new Array[Int](a.size)\n\n for (i <- 0 until a.length) {\n val exp = a(i)\n val v = used.floorEntry(exp)\n if (v == null) {\n if (used.containsKey(exp + 1)) {\n used.put(exp, used.get(exp + 1))\n used.remove(exp + 1)\n } else\n used.put(exp, exp + 1)\n r(i) = exp\n } else {\n r(i) = v.getValue\n if (used.containsKey(v.getValue)) {\n used.put(v.getKey, used.get(v.getValue))\n used.remove(v.getValue)\n } else {\n used.put(v.getKey, v.getValue + 1)\n }\n }\n }\n\n print(r.mkString(\" \"))\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P379C extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val A = Array.fill(N)(sc.nextInt)\n val S = List.range(0, N).sortBy(A(_))\n val res = Array.fill(N)(0)\n\n var r = 0\n S foreach { i =>\n r = ((r + 1) max A(i)) \n res(i) = r\n }\n res.foreach { n =>\n out.print(res.toString)\n out.print(\" \")\n }\n out.close\n}\n"}, {"source_code": "\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 14 Aug 2016\n */\nobject C397 extends App {\n\n def solve() = {\n val n = scala.io.StdIn.readInt()\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val b: Array[Int] = Array.ofDim[Int](n)\n val s: mutable.Set[Int] = mutable.Set.empty\n b(0) = a(0)\n s += a(0)\n var min = a(0)+1\n for (i <- 1 until n) {\n var elem = math.max(min, a(i))\n while (s.contains(elem)) {\n elem += 1\n }\n s.add(elem)\n b(i) = elem\n min = elem\n }\n println(b.mkString(\" \"))\n }\n\n solve()\n\n}\n"}], "src_uid": "d19c7a74d739c2ca0d568808862ba2bd"} {"source_code": "object C extends App {\n import scala.io.StdIn._\n import scala.annotation.tailrec\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n// @tailrec\n// def clean(pair: (Int, Int), pairs: List[(Int, Int)]): List[(Int, Int)] = pairs match {\n// case (a, b) :: ps if (a < pair._2) => clean((a, pair._2), ps)\n// case _ => pair :: pairs\n// }\n\n// @tailrec\n// def collapse(from: Int = 0, pairs: List[(Int, Int)] = List.empty): Boolean =\n// if (from == -1) pairs.length == 1\n// else {\n// val a = an(from)\n// val to = an.indexWhere(_ < a)\n// val pair = (from until (if (to == -1) n else to)).foldLeft((n, 0)) {\n// case ((x, y), j) => (x min an(j), y max an(j))\n// }\n//\n// collapse(to, clean(pair, pairs))\n// }\n\n val ans = an.head < an.last\n\n if (ans) println(\"YES\")\n else println(\"NO\")\n }\n}\n", "positive_code": [{"source_code": "import java.util\n\nimport scala.collection.mutable\n\nobject C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n\n //val stack = mutable.Stack.empty[Int]\n val stack = new util.Stack[Int]\n for (a <- as) {\n while (stack.size > 1 && stack.peek() < a) {\n stack.pop()\n }\n if (stack.isEmpty || stack.peek() > a) {\n stack.push(a)\n }\n }\n\n out.println(if (stack.size <= 1) \"YES\" else \"NO\")\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "192f181cfc74bef5b0b5a192964d9760"} {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by hama_du on 2014/06/19.\n */\nobject ProblemC extends App {\n class UnionFind(n: Int) {\n val parent = (0 until n).toArray\n val rank = new Array[Int](n)\n\n def find(x: Int): Int = {\n if (parent(x) == x) {\n return x\n }\n parent(x) = find(parent(x))\n return parent(x)\n }\n\n def unite(x: Int, y: Int) {\n val fx = find(x)\n val fy = find(y)\n if (fx == fy) {\n return\n }\n if (rank(fx) < rank(fy)) {\n parent(fx) = fy\n } else {\n parent(fy) = fx\n if (rank(fx) == rank(fy)) {\n rank(fx) += 1\n }\n }\n }\n\n def isSame(x: Int, y: Int) = {\n find(x) == find(y)\n }\n }\n\n def compare(x: Array[Char], y: Array[Char]): Int = {\n var i = 0\n val n = x.length\n var count = 0\n while (i < n) {\n if (x(i) != y(i)) {\n count += 1\n }\n i += 1\n }\n count\n }\n\n def dfs(now: Int, parent: Int) {\n if (now < k) {\n if (parent == k) {\n println((now+1) + \" 0\")\n } else {\n println((now+1) + \" \" + (parent+1))\n }\n }\n\n for (to <- graph(now)) {\n if (parent != to) {\n dfs(to, now)\n }\n }\n }\n\n val in = new Scanner(System.in)\n val n,m,k,w = in.nextInt()\n val levels = (0 until k).map(level => {\n (0 until n).map(_ => in.next()).mkString(\"\").toCharArray\n })\n val edgesIJ = for {\n i <- 0 until k\n j <- i+1 until k\n } yield (i, j, compare(levels(i), levels(j)) * w)\n val edges = (0 until k).map(i => (k, i, n*m)) ++ edgesIJ\n\n val unionFind = new UnionFind(k+1)\n var answer = 0\n val graph = (0 to k).map(_ => new ArrayBuffer[Int]())\n edges.sortBy(e => e._3).foreach(e => {\n val i = e._1\n val j = e._2\n if (!unionFind.isSame(i, j)) {\n unionFind.unite(i, j)\n graph(i) += j\n graph(j) += i\n answer += e._3\n }\n })\n println(answer)\n dfs(k, -1)\n}\n", "positive_code": [{"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m, k, w) = readInts(4)\n val nm = n * m\n val ss = Array.ofDim[Char](k, nm)\n\n for (i <- 0 until k) {\n var p = 0\n for (j <- 0 until n) {\n val s = readLine\n var sp = 0\n while (sp < m) {\n ss(i)(p) = s(sp)\n sp += 1\n p += 1\n }\n }\n }\n\n val diffs = Array.fill(k, k)(0)\n\n for (i <- 0 until k; j <- 0 until i) {\n var d = 0\n var p = 0\n while (p < nm) {\n if (ss(i)(p) != ss(j)(p)) d += 1\n p += 1\n }\n diffs(i)(j) = d\n diffs(j)(i) = d\n }\n\n val passed = Array.fill(k)(false)\n\n val res = Array.ofDim[String](k)\n \n res(0) = \"1 0\"\n passed(0) = true\n\n val bestPrev = Array.fill(k)(0)\n var bytes = nm\n\n for (i <- 1 until k) {\n var choice = 0\n var minDiff = Int.MaxValue\n for (j <- 1 until k) {\n if (!passed(j) && diffs(j)(bestPrev(j)) < minDiff) {\n minDiff = diffs(j)(bestPrev(j))\n choice = j\n }\n }\n res(i) = s\"${choice + 1} ${if (minDiff * w < nm) bestPrev(choice) + 1 else 0}\"\n bytes += nm min (minDiff * w)\n passed(choice) = true\n for (j <- 1 until k) if (diffs(choice)(j) < diffs(bestPrev(j))(j)) bestPrev(j) = choice\n }\n \n println(bytes)\n res.foreach(println)\n}"}], "negative_code": [{"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m, k, w) = readInts(4)\n val nm = n * m\n val ss = Array.ofDim[Char](k, nm)\n\n for (i <- 0 until k) {\n var p = 0\n for (j <- 0 until n) {\n val s = readLine\n var sp = 0\n while (sp < m) {\n ss(i)(p) = s(sp)\n sp += 1\n p += 1\n }\n }\n }\n\n val diffs = Array.fill(k, k)(0)\n\n for (i <- 0 until k; j <- 0 until i) {\n var d = 0\n var p = 0\n while (p < nm) {\n if (ss(i)(p) != ss(j)(p)) d += 1\n p += 1\n }\n diffs(i)(j) = d\n diffs(j)(i) = d\n }\n\n val passed = Array.fill(k)(false)\n\n println(\"1 0\")\n passed(0) = true\n\n val bestPrev = Array.fill(k)(0)\n\n for (i <- 1 until k) {\n var choice = 0\n var minDiff = Int.MaxValue\n for (j <- 1 until k) {\n if (!passed(j) && diffs(j)(bestPrev(j)) < minDiff) {\n minDiff = diffs(j)(bestPrev(j))\n choice = j\n }\n }\n println(s\"${choice + 1} ${if (minDiff * w < nm) bestPrev(choice) + 1 else 0}\")\n passed(choice) = true\n for (j <- 1 until k) if (diffs(choice)(j) < diffs(bestPrev(j))(j)) bestPrev(j) = choice\n }\n}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by hama_du on 2014/06/19.\n */\nobject ProblemC extends App {\n class UnionFind(n: Int) {\n val parent = (0 until n).toArray\n val rank = new Array[Int](n)\n\n def find(x: Int): Int = {\n if (parent(x) == x) {\n return x\n }\n parent(x) = find(parent(x))\n return parent(x)\n }\n\n\n def unite(x: Int, y: Int) {\n val fx = find(x)\n val fy = find(y)\n if (fx == fy) {\n return\n }\n if (rank(fx) < rank(fy)) {\n parent(fx) = fy\n } else {\n parent(fy) = fx\n if (rank(fx) == rank(fy)) {\n rank(fx) += 1\n }\n }\n }\n\n def isSame(x: Int, y: Int) = {\n find(x) == find(y)\n }\n }\n\n def compare(x: String, y: String): Int = {\n x.toCharArray.zip(y.toCharArray).count(p => p._1 != p._2)\n }\n\n def dfs(now: Int, parent: Int) {\n println((now+1) + \" \" + (parent+1))\n for (to <- graph(now)) {\n if (parent != to) {\n dfs(to, now)\n }\n }\n }\n\n val in = new Scanner(System.in)\n val n,m,k,w = in.nextInt()\n val levels = (0 until k).map(level => {\n (0 until n).map(_ => in.next()).mkString(\"\")\n })\n val edges = for {\n i <- 0 until k\n j <- i+1 until k\n } yield (i, j, compare(levels(i), levels(j)) * w)\n\n val unionFind = new UnionFind(k)\n var answer = 0\n val graph = (0 until k).map(_ => new ArrayBuffer[Int]())\n edges.sortBy(e => e._3).foreach(e => {\n val i = e._1\n val j = e._2\n if (!unionFind.isSame(i, j)) {\n unionFind.unite(i, j)\n graph(i) += j\n graph(j) += i\n answer += e._3\n }\n })\n println(answer+n*m)\n dfs(0, -1)\n}\n"}], "src_uid": "001e4cd3ddd7780111b1371511f16916"} {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, m, rb, cb, rd, cd = nextInt\n\n val stepsH = if (rb <= rd) rd - rb else (n - rb) + (n - rd)\n val stepsV = if (cb <= cd) cd - cb else (m - cb) + (m - cd)\n val steps = stepsH min stepsV\n\n out.println(steps)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(val a: Int, val b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return -1 * a.compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n\n\n for (tt <- 1 to t) {\n val n = readInt()\n val m = readInt()\n var y = readInt()\n var x = readInt()\n val yy = readInt()\n val xx = readInt()\n var dx = 1\n var dy = 1\n var ans = 0\n while (xx != x && yy != y) {\n if (x == 1 && dx == -1)\n dx = 1\n if (x == m && dx == 1)\n dx = -1\n if (y == 1 && dy == -1)\n dy = 1\n if (y == n && dy == 1)\n dy = -1\n ans += 1\n x += dx\n y += dy\n }\n writer.println(ans)\n\n def check(kk: Long): Boolean = {\n return false\n }\n def bs(st:Long, en:Long): Long = {\n if (en - st <= 1L) {\n if (check(st))\n return st\n else\n return en\n }\n val mid = (st + en) / 2L\n if (check(mid))\n return bs(st, mid)\n else\n return bs(mid, en)\n }\n }\n writer.flush()\n}"}], "negative_code": [], "src_uid": "6f819ce1d88d5211cd475a8673edba97"} {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N, M = sc.nextInt\n val ct = Array.fill(N, 2)(sc.nextInt)\n val vs = Array.fill(M)(sc.nextInt)\n\n val ts = Array.fill(N + 2)(0)\n for (i <- 1 to N) {\n val c = ct(i - 1)(0)\n val t = ct(i - 1)(1)\n ts(i) = ts(i - 1) + c * t\n }\n ts(N + 1) = Int.MaxValue\n\n def findSong(m: Int): Int = {\n @tailrec\n def loop(l: Int, u: Int): Int = {\n val x = (l + u) / 2\n if (ts(x - 1) < m && m <= ts(x)) x\n else if (ts(x) < m && m <= ts(x + 1)) x + 1\n else if (m <= ts(x - 1)) loop(l, x)\n else loop(x, u)\n }\n loop(1, N)\n }\n\n for (i <- 0 until M)\n out.println(findSong(vs(i)))\n\n out.close\n}\n", "positive_code": [{"source_code": "object Playlist extends App {\n\t\t\t// input\n\t\t\tvar in = readLine\n\t\t\tvar split = in.split(\" \")\n\t\t\tvar n = split(0).toInt\n\t\t\tvar m = split(1).toInt\n\t\t\t\n\t\t\tvar next: Array[Int] = new Array[Int](n)\n\t\t\tvar pointer = 0;\n\t\t\tfor(i <- 0 until n) {\n\t\t\t in = readLine\n\t\t\t split = in.split(\" \")\n\t\t\t pointer += split(0).toInt * split(1).toInt\n\t\t\t next(i) = pointer\n\t\t\t}\n\t\n\t\t\tin = readLine\n\t\t\tpointer = 0\n\t\t\tfor (s <- in.split(\" \")) {\n\t\t\t while (s.toInt > next(pointer))\n\t\t\t\t pointer+=1\n\t\t\t println(pointer+1) \n\t\t\t}\n}"}], "negative_code": [], "src_uid": "c4398a9f342a23baf1d7ebc9f4e9577d"} {"source_code": "\nobject B {\n\n def calc(x: Int) = {\n if (x == 1) {\n -1\n } else {\n val odd = ((x + 1) / 2).toLong\n val even = (x / 2).toLong\n -(1 + {\n if (x % 2 == 0) x - 1 else x\n }) * odd / 2 + (2 + {\n if (x % 2 == 0) x else x - 1\n }) * even / 2\n }\n }\n\n def main(args: Array[String]) = {\n val scanner = new java.util.Scanner(System.in)\n val q = scanner.nextInt()\n (0 until q).foreach{_ =>\n val (l, r) = (scanner.nextInt(), scanner.nextInt())\n var result = 0\n if (l == r) {\n System.out.println(if (l % 2 == 0) l else -l)\n } else {\n System.out.println(calc(r) - calc(l-1))\n }\n }\n }\n}", "positive_code": [{"source_code": "object CF_524_2_B {\n def solve(input: Vector[Range]): String = {\n def isOdd(n: Int) = n%2 != 0\n def convert(r: Range): Int = (r.start, r.end) match {\n case (a, b) if isOdd(a) =>\n if(isOdd(b))\n // end odd => (b + 1) is even => +ve => take it away\n convert(a to (b + 1)) - (b + 1)\n else (b - a + 1)/2\n // start even\n case (a, b) =>\n if(isOdd(b))\n (b - a + 1)/(-2)\n // end even => (b + 1) is odd => -ve => add it back\n else convert(a to (b + 1)) + (b + 1)\n }\n input.map(convert).mkString(\"\\n\")\n }\n\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in)\n val lines = io.int()\n io.sc.nextLine()\n def s2r(xs: Seq[Int]) = xs(0) to xs (1)\n val input = Vector.fill(lines)(io.intSeq()).map(s2r)\n val solution = solve(input)\n println(solution)\n }\n\n\n//// boilerplate utility methods:\n import java.util.Scanner\n class IO(val sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def double() = sc.nextDouble()\n }\n}"}, {"source_code": "import java.io._\nimport java.util\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n\n def t(p: Long, k: Long): Long = {\n p / k + (if (p % k == 0) 0 else 1)\n }\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n (1 to n).foreach { _ =>\n var l, r = in.nextLong\n if (l == r)\n println(if (l % 2 == 0) l else -l)\n else if (r - l == 1)\n println(if (l % 2 == 0) -1 else 1)\n else {\n var ans: Long = 0\n if (l % 2 == 0) {\n ans += l\n l += 1\n }\n if (r % 2 != 0) {\n ans -= r\n r -= 1\n }\n println(ans + (r - l) / 2 + 1)\n }\n }\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toDouble\n }\n\n def nextLong: Long = {\n next.toLong\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n\n def cum(x: Int) = {\n if (x == 0) 0L\n else {\n if (x % 2 == 1) {\n val x0 = (x + 1) / 2\n val x1 = x / 2\n val odds = x0.toLong * (x0 + 1) - x0\n val evens = x1.toLong * (x1 + 1)\n evens - odds\n } else {\n val x0 = x / 2\n val x1 = x / 2\n val odds = x0.toLong * (x0 + 1) - x0\n val evens = x1.toLong * (x1 + 1)\n evens - odds\n }\n }\n }\n\n rep(ni()) { _ =>\n val l, r = ni()\n out.println(cum(r) - cum(l - 1))\n }\n\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "\nobject B {\n\n def calc(x: Int) = {\n if (x == 1) {\n -1\n } else {\n val odd = (x + 1) / 2\n val even = x / 2\n -(1 + {\n if (x % 2 == 0) x - 1 else x\n }) * odd / 2 + (2 + {\n if (x % 2 == 0) x else x - 1\n }) * even / 2\n }\n }\n\n def main(args: Array[String]) = {\n val scanner = new java.util.Scanner(System.in)\n val q = scanner.nextInt()\n (0 until q).foreach{_ =>\n val (l, r) = (scanner.nextInt(), scanner.nextInt())\n var result = 0\n if (l == r) {\n System.out.println(if (l % 2 == 0) l else -l)\n } else {\n System.out.println(calc(r) - calc(l-1))\n }\n }\n }\n}"}], "src_uid": "7eae40835f6e9580b985d636d5730e2d"} {"source_code": "object A {\n \n def main(args: Array[String]): Unit = {\n val lines = scala.io.Source.stdin.getLines().toList.tail\n \n val rows = lines.map (_.split(\" \").map(_.toInt).toList)\n val cols = List.transpose(rows)\n \n var count = 0\n \n for (i <- 0 to rows.length - 1)\n for (j <- 0 to rows.length - 1)\n if (cols(j).sum > rows(i).sum) count += 1\n \n println (count)\n \n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = (0 until n).map(_ => in.next().split(\" \").map(_.toInt))\n val rows = data.map(_.sum)\n val cols = (0 until n).map(i => (0 until n).map(j => data(j)(i)).sum)\n println(rows.map(rv => cols.count(_ > rv)).sum)\n}"}, {"source_code": "import io.Source\nimport java.util.Scanner\n\nobject A {\n def sumRow(a: Array[Array[Int]], row: Int) = a(row).sum\n\n def sumColumn(a: Array[Array[Int]], column: Int) = a.foldLeft(0)((sum, arr) => sum + arr(column))\n\n def main(args: Array[String]) {\n val stdin = new Scanner(System.in)\n val n = stdin.nextInt()\n val matrix = Array.ofDim[Int](n, n)\n for (val i <- 0 until n) {\n for (val j <- 0 until n) {\n matrix(i)(j) = stdin.nextInt()\n }\n }\n var count = 0\n for (val i <- 0 until n) {\n for (val j <- 0 until n) {\n if (sumRow(matrix, i) < sumColumn(matrix, j)) {\n count += 1\n }\n }\n }\n println(count)\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P157A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n \n val N = sc.nextInt\n val a = Array.fill(N, N)(sc.nextInt)\n val b = a.transpose\n\n def isWinning(x: Int, y: Int): Boolean = a(x).sum < b(y).sum\n\n var score = 0\n for (i <- 0 until N; j <- 0 until N)\n if (isWinning(i, j)) score += 1\n\n out.println(score)\n out.close\n}\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n def readLine = reader.readLine\n\n val n = readInt\n val a = for(_ <- 1 to n) yield readInts\n val horS = a.map(_.sum)\n val verS = a.transpose.map(_.sum)\n val ans = verS.map(x => horS.count(x>)).sum\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val n = readInt\n val a = (1 to n).map(_ => readLine().split(\" \").map(_.toInt))\n \n val rowSums = a.map(_.sum)\n val colSums = a.transpose.map(_.sum)\n \n val count = rowSums.map(rowSum => colSums.count(_ > rowSum)).sum\n println(count)\n }\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject Flask {\n\n def main(args: Array[String]): Unit = {\n var data: ArrayBuffer[Array[Int]] = new ArrayBuffer()\n var n = readLine.toInt\n for (i <- 1 to n) data += readLine.split(\" \").map(_.toInt)\n \n var count = 0\n \n for (i <- 0 until n) {\n for (j <- 0 until n) {\n var horizontal_sum = List.range(0, n).foldLeft(0)((res, pos) => res + data(i)(pos))\n var vertical_sum = List.range(0, n).foldLeft(0)((res, pos) => res + data(pos)(j))\n\n if (vertical_sum > horizontal_sum) \n count += 1\n }\n }\n println(count)\n }\n}\n"}, {"source_code": "/**\n * Created by IntelliJ IDEA.\n * User: User\n * Date: 01.03.12\n * Time: 0:59\n * To change this template use File | Settings | File Templates.\n */\n\nobject A {\n def main(args: Array[String]) {\n val n = readInt\n val m = (for (_ <- 1 to n) yield (readLine split ' ' map (_.toInt)).toArray).toArray\n val rawsum = (0 until n) map (i => (0 until n) map (m(i)(_)) sum) toArray;\n val colsum = (0 until n) map (j => (0 until n) map (m(_)(j)) sum) toArray;\n println((for (i <- 0 until n; j <- 0 until n if colsum(i) > rawsum(j)) yield 1).sum)\n\n }\n\n}\n\n"}], "negative_code": [], "src_uid": "6e7c2c0d7d4ce952c53285eb827da21d"} {"source_code": "\n\nobject ProblemD extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n\n for (i <- 1 to t) {\n val n = in.nextInt()\n val inArr = new Array[Int](n)\n for (j <- 0 until n) {\n inArr(j) = in.nextInt()\n }\n\n var aliceSum = inArr(0)\n var bobSum = 0\n var bobPrev = 0\n var prevAlliceSum = aliceSum\n var aliceTurn = false\n\n var left = 1\n var right = n - 1\n var count = 1\n\n while (left <= right) {\n count = count + 1\n if (aliceTurn) {\n var currentSum = 0\n while (currentSum <= bobPrev && left <= right) {\n currentSum = currentSum + inArr(left)\n left = left + 1\n }\n prevAlliceSum = currentSum\n aliceSum = aliceSum + currentSum\n } else {\n var currentSum = 0\n while (currentSum <= prevAlliceSum && left <= right) {\n currentSum = currentSum + inArr(right)\n right = right - 1\n }\n\n bobSum = bobSum + currentSum\n bobPrev = currentSum\n }\n aliceTurn = !aliceTurn\n }\n\n\n\n println(s\"$count $aliceSum $bobSum\")\n }\n\n\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\n\nobject Test extends App {\n\n val s = StdIn.readLine().toInt\n (1 to s).foreach{_ =>\n StdIn.readLine()\n var arr = StdIn.readLine().split(\" \").map(_.toInt)\n var i = 0\n var j = arr.length - 1\n var alice = 0\n var bob = 0\n alice = arr(i)\n i = 1\n var bob1 = true\n var counter = 1\n var beforeA = alice\n var beforeB = 0\n while (i <= j){\n counter = counter + 1\n if(bob1){\n var bob2 = 0\n while (bob2 <= beforeA && i <= j){\n bob2 = bob2 + arr(j)\n j = j - 1\n }\n beforeB = bob2\n bob = bob + bob2\n bob1 = false\n }else{\n var al2 = 0\n while (al2 <= beforeB && i <= j){\n al2 = al2 + arr(i)\n i = i +1\n }\n beforeA = al2\n alice = alice + al2\n bob1 = true\n }\n }\n println(s\"$counter $alice $bob\")\n\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C640B(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val n = ni()\n val a = na(n)\n\n var l = 0\n var h = n-1\n var switch = 0\n var prev = 0\n val ret = Array.fill[Int](2)(0)\n var cnt = 0\n while(l <= h) {\n var curr = 0\n while (curr <= prev && l <= h) {\n if(switch == 0) {curr += a(l); l += 1}\n else { curr += a(h); h -=1 }\n }\n ret(switch) += curr\n switch ^= 1\n prev = curr\n cnt += 1\n }\n out.println(s\"$cnt ${ret(0)} ${ret(1)}\")\n }\n }\n}\n"}, {"source_code": "object _1352D extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val candies = io.read[Vector[Int]]\n\n @tailrec\n def solve(isAlice: Boolean, prev: Int, left: Int, right: Int, alice: Int, bob: Int, moves: Int): Seq[Int] = {\n val range = if (isAlice) left + 1 until right else right-1 until left by -1\n if (range.nonEmpty) {\n var sum, count = 0\n range.takeWhile({i =>\n count += 1\n sum += candies(i)\n sum <= prev\n })\n solve(\n isAlice = !isAlice,\n prev = sum,\n left = if (isAlice) left + count else left,\n right = if (!isAlice) right - count else right,\n alice = if (isAlice) alice + sum else alice,\n bob = if (!isAlice) bob + sum else bob,\n moves = moves + 1\n )\n } else {\n Seq(moves, alice, bob)\n }\n }\n\n val ans = solve(isAlice = true, prev = 0, left = -1, right = candies.length, alice = 0, bob = 0, moves = 0)\n\n io.writeAll(ans)\n }\n\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n val charToInt: Char => Int = Character.getNumericValue\n val intToChar: Int => Char = Character.forDigit(_, 10)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "d70ee6d3574e0f2cac3c683729e2979d"} {"source_code": "import collection.mutable\n\nobject C {\n def main(args: Array[String]) {\n val Array(n, k) = readLine().split(\" \").map(x => x.toInt)\n var a = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = readLine().split(\"\\\\.\").map(x => x.toInt).fold(0)((x, y) => x * 256 + y)\n }\n val masks = 1 until 32 map {x => -1 << (32 - x)}\n var ans = 0\n for (r <- masks) {\n var d = new mutable.HashSet[Int]\n for (x <- a) {\n val v = x & r\n d add v\n }\n if (d.size == k && ans == 0) {\n ans = r\n }\n }\n if (ans == 0) {\n println(-1)\n } else {\n val res = (0 until 4).map(x => (ans >> (24 - 8 * x)) & 255).fold(\"\")((x, y) => if (x == \"\") y else x + \".\" + y)\n println(res)\n }\n }\n}", "positive_code": [{"source_code": "import io.Source\nimport java.io.PrintWriter\n\nobject CF291C {\n\n def solve(in: In, out: PrintWriter) {\n val n, k = in().toInt\n val a = {for (i <- 0 until n) yield {\n ((in().toLong * 256 + in().toLong) * 256 + in().toLong) * 256 + in().toLong\n }}.toArray\n var l = 0\n var r = 32\n var rVal = -1\n while (l + 1 < r) {\n val mid = (l + r) / 2\n val mask = ((1L << mid) - 1) << (32 - mid)\n val set = collection.mutable.HashSet[Long]()\n for (x <- a) {\n set += x & mask\n }\n if (set.size < k) {\n l = mid\n } else {\n r = mid\n rVal = set.size\n }\n }\n if (r == 32 || rVal != k) {\n out.println(-1)\n } else {\n val ans = ((1L << r) - 1) << (32 - r)\n out.print((ans >> 24) & 255)\n out.print(\".\")\n out.print((ans >> 16) & 255)\n out.print(\".\")\n out.print((ans >> 8) & 255)\n out.print(\".\")\n out.print((ans >> 0) & 255)\n out.println()\n }\n }\n\n def main(args: Array[String]) {\n val in: In = new In(Source.fromInputStream(System.in))\n val out: PrintWriter = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() {\n while (iter.hasNext && delims.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next(): String = {\n skipDelims()\n while (iter.hasNext && delims.indexOf(iter.head) == -1) {\n sb.append(iter.next())\n }\n val ret = sb.toString()\n sb.clear()\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIterator = new TokenIterator(iter, \" .\\r\\n\")\n\n val lineIterator = new TokenIterator(iter, \"\\r\\n\")\n\n def apply() = tokenIterator.next()\n\n def apply(n: Int) = tokenIterator.take(n)\n }\n}"}, {"source_code": "object C {\n def READ: Array[Int] = readLine() split (\" \") map (_.toInt);\n def main(args: Array[String]) {\n var Array(n, k) = READ\n def toIp(i: Int):Long = math.pow(2, i).toLong-1 << 32-i;\n var masks = (1 to 31) map (i => (i-1, toIp(i)));\n var arr = Array.fill(31)(scala.collection.mutable.HashSet.empty[Long])\n for (i <- 0 until n) {\n val ip:Long = readLine() split(\"\\\\.\") map (_.toLong) reduce(_<<8 | _);\n masks foreach {x => arr(x._1).add(x._2&ip)}\n }\n for (i <- 1 to 31; if arr(i-1).size == k){\n val ip = toIp(i)\n printf(\"%d.%d.%d.%d\\n\", ip >> 24, (ip & 0xff0000) >> 16, (ip & 0xff00) >> 8, ip&0xff)\n return;\n }\n println(-1);\n }\n}\n"}, {"source_code": "/*\nC. Маска подсети\nограничение по времени на тест\n4 секунды\nограничение по памяти на тест\n256 мегабайт\nввод\nstandard input\nвывод\nstandard output\n\nВ задаче используется упрощенная модель адресов в TCP/IP, внимательно прочтите условие.\n\nПоликарп устроился на работу системным администратором. Как-то раз к нему в руки попали n IP-адресов. Каждый IP-адрес — это 32-битное число, представленное в виде четверки десятичных 8-битных чисел (без лидирующих нулей), записанных через точку. Например, запись 0.255.1.123 обозначает корректный IP-адрес, а записи 0.256.1.123 и 0.255.1.01 — нет. В данной задаче произвольная четверка 8-битных чисел является корректным IP-адресом.\n\nПоработав администратором, Поликарп узнал, что, зная IP-адрес, можно, используя маску подсети, получить адрес сети, которой принадлежит этот IP-адрес.\n\nМаска подсети — это IP-адрес, обладающий следующим свойством: если записать этот IP-адрес, как 32-битную строку, то он представим в виде «11...11000..000». Другими словами, в маске подсети сначала идет один или более единичный бит, а затем один или более нулевой бит (всего битов 32). Например, IP-адрес 2.0.0.0 не является корректной маской подсети, так как его 32-битная запись имеет вид 00000010000000000000000000000000.\n\nДля получения адреса сети IP-адреса нужно выполнить операцию побитового «и» («and») IP-адреса и маски подсети. Например, если маска подсети 255.192.0.0, а IP-адрес 192.168.1.2, то адрес сети равен 192.128.0.0. При побитовом «и» в записи результата бит равен 1 тогда и только тогда, когда у обоих операндов соответствующие биты единичные.\n\nТеперь Поликарп хочет найти все сети, которым принадлежат его IP-адреса. К сожалению, Поликарп потерял маску подсети. К счастью, Поликарп запомнил, что его IP-адреса принадлежали ровно k различным сетям. Помогите Поликарпу найти маску подсети, такую, что его IP-адреса будут принадлежать ровно k различным сетям. Если таких масок несколько, найдите ту, в битовой записи которой наименьшее количество единиц. Если таких масок не существует, сообщите об этом.\nВходные данные\n\nВ первой строке записаны два целых числа n и k (1 ≤ k ≤ n ≤ 105) — количество IP-адресов и сетей. В следующих n строках записаны сами IP-адреса. Гарантируется, что все IP-адреса различны.\nВыходные данные\n\nВ единственной строке выведите IP-адрес маски подсети, в формате описанном в условии, если требуемая маска подсети существует. Иначе выведите -1.\nПримеры тестов\nВходные данные\n\n5 3\n0.0.0.1\n0.1.1.2\n0.0.2.1\n0.1.1.0\n0.0.2.3\n\nВыходные данные\n\n255.255.254.0\n\nВходные данные\n\n5 2\n0.0.0.1\n0.1.1.2\n0.0.2.1\n0.1.1.0\n0.0.2.3\n\nВыходные данные\n\n255.255.0.0\n\nВходные данные\n\n2 1\n255.0.0.1\n0.0.0.2\n\nВыходные данные\n\n-1\n*/\nimport scala.collection.immutable.BitSet\nimport scala.collection.mutable.MutableList\nimport scala.collection.mutable.HashSet\n\nobject Task3 extends App {\n\n def masks: IndexedSeq[Long] = {\n val init = 0xFFFFFFFFL\n var z = init\n val res = init +: (for (p <- 0 until 31) yield {\n z -= math.pow(2, p).toLong\n z\n })\n res.reverse\n }\n\n def toBits(ip: String): Long = {\n def parts = ip.trim split '.'\n require(parts.size == 4)\n val res = parts.foldLeft(0L)((acc, part) => acc * 256 + (part.toInt))\n res\n }\n\n def toStr(ip: Option[Long]): String = ip match {\n case None => \"-1\"\n case Some(l) => {\n val seg1 = (l & 0xFF000000L) >> 24\n val seg2 = (l & 0x00FF0000L) >> 16\n val seg3 = (l & 0x0000FF00L) >> 8\n val seg4 = (l & 0x000000FFL)\n seg1 + \".\" + seg2 + \".\" + seg3 + \".\" + seg4\n }\n }\n\n def applyMask(mask: Long, ips: Seq[Long]): Seq[Long] = {\n val set = new HashSet[Long]\n ips map (ip => set += (ip & mask))\n set.toSeq\n }\n\n def distinctByNFirstBits(n: Int, ips: Seq[Long]): Int = {\n val t = ips map (_ >> (32 - n))\n t.distinct.size\n }\n\n def nFirstBits(n: Int): Long = masks(n - 1)\n\n def solveStr(k: Int, ipStrs: Seq[String]): String =\n toStr(solve(k, ipStrs map toBits))\n\n /** Finds number of pairs, returns -1 if triplet or more */\n def solve(k: Int, ips: Seq[Long]): Option[Long] =\n if (k > ips.size) None\n // else masks.find(mask => applyMask(mask, ips).size == k)\n else (1 to 31) find (n => distinctByNFirstBits(n, ips) == k) map nFirstBits\n\n /*\n def bitStream(ones: Int): Stream[Long] = generateBits(0, 32, ones)\n\n def generateBits(curr: Long, remaining: Int, remainingOnes: Int): Stream[Long] = {\n val shifted = (curr << 1)\n if (remaining == 0) {\n assert(remainingOnes == 0)\n curr #:: Stream.empty\n } else if (remainingOnes == remaining) {\n generateBits(shifted + 1, remaining - 1, remainingOnes - 1)\n } else if (remainingOnes >= 1) {\n val v1 = generateBits(shifted + 1, remaining - 1, remainingOnes - 1)\n val v2 = generateBits(shifted + 0, remaining - 1, remainingOnes)\n Stream.concat(v1, v2)\n } else {\n generateBits(shifted, remaining - 1, remainingOnes)\n }\n }\n*/\n val (n, k) = {\n val l = readLine split (' ') map (_.toInt)\n (l(0), l(1))\n }\n val ipStrs = for (i <- 0 until n) yield readLine\n\n val res = solveStr(k, ipStrs)\n println(res)\n}"}], "negative_code": [{"source_code": "/*\nC. Маска подсети\nограничение по времени на тест\n4 секунды\nограничение по памяти на тест\n256 мегабайт\nввод\nstandard input\nвывод\nstandard output\n\nВ задаче используется упрощенная модель адресов в TCP/IP, внимательно прочтите условие.\n\nПоликарп устроился на работу системным администратором. Как-то раз к нему в руки попали n IP-адресов. Каждый IP-адрес — это 32-битное число, представленное в виде четверки десятичных 8-битных чисел (без лидирующих нулей), записанных через точку. Например, запись 0.255.1.123 обозначает корректный IP-адрес, а записи 0.256.1.123 и 0.255.1.01 — нет. В данной задаче произвольная четверка 8-битных чисел является корректным IP-адресом.\n\nПоработав администратором, Поликарп узнал, что, зная IP-адрес, можно, используя маску подсети, получить адрес сети, которой принадлежит этот IP-адрес.\n\nМаска подсети — это IP-адрес, обладающий следующим свойством: если записать этот IP-адрес, как 32-битную строку, то он представим в виде «11...11000..000». Другими словами, в маске подсети сначала идет один или более единичный бит, а затем один или более нулевой бит (всего битов 32). Например, IP-адрес 2.0.0.0 не является корректной маской подсети, так как его 32-битная запись имеет вид 00000010000000000000000000000000.\n\nДля получения адреса сети IP-адреса нужно выполнить операцию побитового «и» («and») IP-адреса и маски подсети. Например, если маска подсети 255.192.0.0, а IP-адрес 192.168.1.2, то адрес сети равен 192.128.0.0. При побитовом «и» в записи результата бит равен 1 тогда и только тогда, когда у обоих операндов соответствующие биты единичные.\n\nТеперь Поликарп хочет найти все сети, которым принадлежат его IP-адреса. К сожалению, Поликарп потерял маску подсети. К счастью, Поликарп запомнил, что его IP-адреса принадлежали ровно k различным сетям. Помогите Поликарпу найти маску подсети, такую, что его IP-адреса будут принадлежать ровно k различным сетям. Если таких масок несколько, найдите ту, в битовой записи которой наименьшее количество единиц. Если таких масок не существует, сообщите об этом.\nВходные данные\n\nВ первой строке записаны два целых числа n и k (1 ≤ k ≤ n ≤ 105) — количество IP-адресов и сетей. В следующих n строках записаны сами IP-адреса. Гарантируется, что все IP-адреса различны.\nВыходные данные\n\nВ единственной строке выведите IP-адрес маски подсети, в формате описанном в условии, если требуемая маска подсети существует. Иначе выведите -1.\nПримеры тестов\nВходные данные\n\n5 3\n0.0.0.1\n0.1.1.2\n0.0.2.1\n0.1.1.0\n0.0.2.3\n\nВыходные данные\n\n255.255.254.0\n\nВходные данные\n\n5 2\n0.0.0.1\n0.1.1.2\n0.0.2.1\n0.1.1.0\n0.0.2.3\n\nВыходные данные\n\n255.255.0.0\n\nВходные данные\n\n2 1\n255.0.0.1\n0.0.0.2\n\nВыходные данные\n\n-1\n*/\nimport scala.collection.immutable.HashSet\nimport scala.collection.immutable.BitSet\nimport scala.collection.mutable.MutableList\n\nobject Task3 extends App {\n\n def masks: Seq[Long] = {\n val init = 0xFFFFFFFFL\n var z = init\n val res = init +: (for (p <- 0 until 31) yield {\n z -= math.pow(2, p).toLong\n z\n })\n res.reverse\n }\n\n def applyMask(mask: Long, ips: Seq[Long]): Set[Long] = {\n ips.foldLeft(new HashSet[Long]) { (set, ip) =>\n set + (ip & mask)\n }\n }\n\n def toBits(ip: String): Long = {\n def parts = ip.trim split '.'\n require(parts.size == 4)\n val res = parts.foldLeft(0L)((acc, part) => acc * 256 + (part.toInt))\n res\n }\n\n def toStr(ip: Option[Long]): String = ip match {\n case None => \"-1\"\n case Some(l) => {\n val seg1 = (l & 0xFF000000L) >> 24\n val seg2 = (l & 0x00FF0000L) >> 16\n val seg3 = (l & 0x0000FF00L) >> 8\n val seg4 = (l & 0x000000FFL)\n seg1 + \".\" + seg2 + \".\" + seg3 + \".\" + seg4\n }\n }\n\n def solveStr(k: Int, ipStrs: Seq[String]): String =\n toStr(solve(k, ipStrs map toBits))\n\n /** Finds number of pairs, returns -1 if triplet or more */\n def solve(k: Int, ips: Seq[Long]): Option[Long] =\n if (k > ips.size) None\n else if (k == ips.size) Some(0xFFFFFFFFL)\n else masks.find(mask => applyMask(mask, ips).size == k)\n\n /*\n def bitStream(ones: Int): Stream[Long] = generateBits(0, 32, ones)\n\n def generateBits(curr: Long, remaining: Int, remainingOnes: Int): Stream[Long] = {\n val shifted = (curr << 1)\n if (remaining == 0) {\n assert(remainingOnes == 0)\n curr #:: Stream.empty\n } else if (remainingOnes == remaining) {\n generateBits(shifted + 1, remaining - 1, remainingOnes - 1)\n } else if (remainingOnes >= 1) {\n val v1 = generateBits(shifted + 1, remaining - 1, remainingOnes - 1)\n val v2 = generateBits(shifted + 0, remaining - 1, remainingOnes)\n Stream.concat(v1, v2)\n } else {\n generateBits(shifted, remaining - 1, remainingOnes)\n }\n }\n*/\n val (n, k) = {\n val l = readLine split (' ') map (_.toInt)\n (l(0), l(1))\n }\n val ipStrs = for (i <- 0 until n) yield readLine\n\n val res = solveStr(k, ipStrs)\n println(res)\n}"}, {"source_code": "import io.Source\nimport java.io.PrintWriter\n\nobject CF291C {\n\n def solve(in: In, out: PrintWriter) {\n val n, k = in().toInt\n val a = {for (i <- 0 until n) yield {\n ((in().toLong * 256 + in().toLong) * 256 + in().toLong) * 256 + in().toLong\n }}.toArray\n var l = 0\n var r = 33\n while (l + 1 < r) {\n val mid = (l + r) / 2\n val mask = ((1L << mid) - 1) << (32 - mid)\n val set = collection.mutable.HashSet[Long]()\n for (x <- a) {\n set += x & mask\n }\n if (set.size < k) {\n l = mid\n } else {\n r = mid\n }\n }\n if (l == 0 || r == 33) {\n out.println(-1)\n } else {\n val ans = ((1L << r) - 1) << (32 - r)\n out.print((ans >> 24) & 255)\n out.print(\".\")\n out.print((ans >> 16) & 255)\n out.print(\".\")\n out.print((ans >> 8) & 255)\n out.print(\".\")\n out.print((ans >> 0) & 255)\n out.println()\n }\n }\n\n def main(args: Array[String]) {\n val in: In = new In(Source.fromInputStream(System.in))\n val out: PrintWriter = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() {\n while (iter.hasNext && delims.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next(): String = {\n skipDelims()\n while (iter.hasNext && delims.indexOf(iter.head) == -1) {\n sb.append(iter.next())\n }\n val ret = sb.toString()\n sb.clear()\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIterator = new TokenIterator(iter, \" .\\r\\n\")\n\n val lineIterator = new TokenIterator(iter, \"\\r\\n\")\n\n def apply() = tokenIterator.next()\n\n def apply(n: Int) = tokenIterator.take(n)\n }\n}"}, {"source_code": "import io.Source\nimport java.io.PrintWriter\n\nobject CF291C {\n\n def solve(in: In, out: PrintWriter) {\n val n, k = in().toInt\n val a = {for (i <- 0 until n) yield {\n ((in().toLong * 256 + in().toLong) * 256 + in().toLong) * 256 + in().toLong\n }}.toArray\n var l = 0\n var r = 33\n var rVal = -1\n while (l + 1 < r) {\n val mid = (l + r) / 2\n val mask = ((1L << mid) - 1) << (32 - mid)\n val set = collection.mutable.HashSet[Long]()\n for (x <- a) {\n set += x & mask\n }\n if (set.size < k) {\n l = mid\n } else {\n r = mid\n rVal = set.size\n }\n }\n if (l == 0 || r == 33 || rVal != k) {\n out.println(-1)\n } else {\n val ans = ((1L << r) - 1) << (32 - r)\n out.print((ans >> 24) & 255)\n out.print(\".\")\n out.print((ans >> 16) & 255)\n out.print(\".\")\n out.print((ans >> 8) & 255)\n out.print(\".\")\n out.print((ans >> 0) & 255)\n out.println()\n }\n }\n\n def main(args: Array[String]) {\n val in: In = new In(Source.fromInputStream(System.in))\n val out: PrintWriter = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() {\n while (iter.hasNext && delims.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next(): String = {\n skipDelims()\n while (iter.hasNext && delims.indexOf(iter.head) == -1) {\n sb.append(iter.next())\n }\n val ret = sb.toString()\n sb.clear()\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIterator = new TokenIterator(iter, \" .\\r\\n\")\n\n val lineIterator = new TokenIterator(iter, \"\\r\\n\")\n\n def apply() = tokenIterator.next()\n\n def apply(n: Int) = tokenIterator.take(n)\n }\n}"}, {"source_code": "import io.Source\nimport java.io.PrintWriter\n\nobject CF291C {\n\n def solve(in: In, out: PrintWriter) {\n val n, k = in().toInt\n val a = {for (i <- 0 until n) yield {\n ((in().toLong * 256 + in().toLong) * 256 + in().toLong) * 256 + in().toLong\n }}.toArray\n var l = 0\n var r = 32\n var rVal = -1\n while (l + 1 < r) {\n val mid = (l + r) / 2\n val mask = ((1L << mid) - 1) << (32 - mid)\n val set = collection.mutable.HashSet[Long]()\n for (x <- a) {\n set += x & mask\n }\n if (set.size < k) {\n l = mid\n } else {\n r = mid\n rVal = set.size\n }\n }\n if (l == 0 || r == 32 || rVal != k) {\n out.println(-1)\n } else {\n val ans = ((1L << r) - 1) << (32 - r)\n out.print((ans >> 24) & 255)\n out.print(\".\")\n out.print((ans >> 16) & 255)\n out.print(\".\")\n out.print((ans >> 8) & 255)\n out.print(\".\")\n out.print((ans >> 0) & 255)\n out.println()\n }\n }\n\n def main(args: Array[String]) {\n val in: In = new In(Source.fromInputStream(System.in))\n val out: PrintWriter = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() {\n while (iter.hasNext && delims.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next(): String = {\n skipDelims()\n while (iter.hasNext && delims.indexOf(iter.head) == -1) {\n sb.append(iter.next())\n }\n val ret = sb.toString()\n sb.clear()\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIterator = new TokenIterator(iter, \" .\\r\\n\")\n\n val lineIterator = new TokenIterator(iter, \"\\r\\n\")\n\n def apply() = tokenIterator.next()\n\n def apply(n: Int) = tokenIterator.take(n)\n }\n}"}], "src_uid": "4da4410d3b75ee87a4dfa33b437b9cfa"} {"source_code": "import java.util.Scanner\n\nobject CubeWalls extends App {\n\n\tfinal val SEP = 1000000000\t// arrays separator\n\n\tval scanner = new Scanner( System.in )\n\n\tval n = scanner.nextInt\n\tval w = scanner.nextInt\n\tval a = Array.ofDim[Int]( n )\n\tfor( i <- a.indices )\n\t\ta( i ) = scanner.nextInt\n\tval b = Array.ofDim[Int]( w )\n\tfor( i <- b.indices )\n\t\tb( i ) = scanner.nextInt\n\n\tval matches = if( w > 1 ) {\n\t\t// array with differences to have simple matching\n\t\tval ad = a.sliding( 2 ).map( e => e( 1 ) - e( 0 )).toArray\n\t\tval bd = b.sliding( 2 ).map( e => e( 1 ) - e( 0 )).toArray\n\t\t// join the arrays to use Z function\n\t\tval bdad = (bd :+ SEP) ++ ad\n\t\tval z = zf( bdad )\n\t\tz.count( _ == w - 1 )\t\t// count matches, shorter by 1 because we match array with differences\n\t}\n\telse\n\t\tn\n\n/*\tsimple but with O(n*w) - too slow\n\tval bi = b.zipWithIndex\n\tval bi = b.zipWithIndex\n\tval matches = ( 0 to lDiff ) count { i =>\n\t\tval hDiff = a( i ) - b( 0 )\n\t\tbi.forall( x => a( i + x._2 ) - x._1 == hDiff )\n\t}\n*/\n\tprintln( matches )\n\n\t// Z algorithm, see http://codeforces.com/blog/entry/3107\n\tdef zf( s: Array[Int] ) = {\n\t\tval n = s.length\n\t\tval z = Array.ofDim[Int]( n )\n\t\tz( 0 ) = 0\n\t\tvar l = 0\n\t\tvar r = 0\n\t\tfor( i <- 1 until n ) {\n\t\t\tif( i > r ) {\n\t\t\t\tl = i\n\t\t\t\tr = i\n\t\t\t\twhile( r < n && s( r - l ) == s( r ))\n\t\t\t\t\tr += 1\n\t\t\t\tz( i ) = r - l\n\t\t\t\tr -= 1\n\t\t\t}\n\t\t\telse {\n\t\t\t\tval k = i - l\n\t\t\t\tif( z( k ) < r - i + 1 )\n\t\t\t\t\tz( i ) = z( k )\n\t\t\t\telse {\n\t\t\t\t\tl = i\n\t\t\t\t\twhile( r < n && s( r - l ) == s( r ))\n\t\t\t\t\t\tr += 1\n\t\t\t\t\tz( i ) = r - l\n\t\t\t\t\tr -= 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tz\n\t}\n}", "positive_code": [{"source_code": "\nimport java.util._\nimport java.io._\nimport java.util\nimport scala.annotation.tailrec\n\nobject D {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n var ans = 0\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def prefixFunc(string: Array[Int]): Array[Int] = {\n val π = new Array[Int](string.length)\n π(0) = 0\n for (i <- 1 to string.length - 1) {\n var j = π(i - 1)\n while (j != 0 && string(j) != string(i)) {\n j = π(j - 1)\n }\n if (string(j) == string(i)) {\n π(i) = j + 1\n } else {\n π(i) = 0\n }\n }\n π\n }\n\n def kmp(t: Array[Int], s: Array[Int]): Unit = {\n val del = new Array[Int](1)\n del(0) = Int.MaxValue\n val p = prefixFunc(s ++ del ++ t)\n for (i <- s.length + 1 to p.length - 1) {\n if (p(i) == s.length) {\n ans += 1\n }\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val w = nextInt\n val a = new Array[Int](n)\n val b = new Array[Int](w)\n if (w == 1) {\n out.println(n)\n return 1\n }\n val ua = new Array[Int](n - 1)\n val ub = new Array[Int](w - 1)\n for (i <- 0 until n) {\n a(i) = nextInt\n }\n for (j <- 0 until w) {\n b(j) = nextInt\n }\n for (i <- 0 until n - 1) {\n ua(i) = a(i + 1) - a(i)\n }\n for (i <- 0 until w - 1) {\n ub(i) = b(i + 1) - b(i)\n }\n\n kmp(ua, ub)\n out.println(ans)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "negative_code": [{"source_code": "import java.util._\nimport java.io._\nimport java.util\nimport scala.annotation.tailrec\n\nobject D {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n var ans = 0\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def prefixFunc(string: String): Array[Int] = {\n val π = new Array[Int](string.length)\n π(0) = 0\n for (i <- 1 to string.length - 1) {\n var j = π(i - 1)\n while (j != 0 && string(j) != string(i)) {\n j = π(j - 1)\n }\n if (string(j) == string(i)) {\n π(i) = j + 1\n } else {\n π(i) = 0\n }\n }\n π\n }\n\n def kmp(t: String, s: String): Unit = {\n val p = prefixFunc(s + \"#\" + t)\n for (i <- s.length + 1 to p.length - 1) {\n if (p(i) == s.length) {\n ans += 1\n }\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val w = nextInt\n val a = new Array[Int](n)\n val b = new Array[Int](w)\n val ua = new Array[Int](n)\n val ub = new Array[Int](w)\n for (i <- 0 until n) {\n a(i) = nextInt\n }\n for (j <- 0 until w) {\n b(j) = nextInt\n }\n ua(0) = 0\n for (i <- 1 until n) {\n ua(i) = a(i) - a(i - 1)\n }\n for (i <- 1 until w) {\n ub(i) = b(i) - b(i - 1)\n }\n ub(0) = 0\n if (w == 1) {\n out.println(n)\n return 1\n }\n val t = ua.mkString(\"\")\n val s = ub.mkString(\"\").substring(1)\n kmp(t, s)\n out.println(ans)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "src_uid": "37447ade3cad88e06c1f407576e4a041"} {"source_code": "\n\nobject CodeforcesRound1392B {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n //2 1\n //-199 192\n //192+199 0\n //0 -192-199\n\n //1 3 7\n //7-1 7-3 7-7\n //6 4 0\n //0 2 6\n //6 4 0\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val Array(nl, k) = rll_long\n val n = nl.toInt\n val a = rll_int\n val upToIter = (2 - (k % 2)).toInt\n for (_ <- 0 until upToIter) {\n val max = a.max\n for (i <- 0 until n) {\n a(i) = max - a(i)\n }\n }\n val res = a.mkString(\" \")\n writer.println(res)\n }\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}", "positive_code": [{"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, k = nextLong\n val as = nextLongs(n.toInt)\n val min = as.min\n val max = as.max\n\n for (i <- as.indices) {\n as(i) = max - as(i)\n }\n\n val d = max - min\n if (k % 2 == 0) {\n for (i <- as.indices) {\n as(i) = d - as(i)\n }\n }\n\n out.println(as.mkString(\" \"))\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "f18a5fa0b2e7e96cb5994b7b2dbe0189"} {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(a0, b0) = readInts(2)\n\n def can(maxK: Int): Boolean = {\n var k = maxK\n var a = a0\n var b = b0\n while (k > 0 && a >= 0 && b >= 0) {\n if (a >= b) a -= k else b -= k\n k -= 1\n }\n a >= 0 && b >= 0\n }\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int): Int = {\n if (hi < low) hi\n else {\n val mid = (low + hi) / 2\n if (can(mid)) binSearch(mid + 1, hi)\n else binSearch(low, mid - 1)\n }\n }\n\n val res = binSearch(0, 1000000)\n\n val asBuilder, bsBuilder = new mutable.ArrayBuilder.ofInt\n var k = res\n var a = a0\n var b = b0\n while (k > 0 && a >= 0 && b >= 0) {\n if (a >= b) {\n asBuilder += k\n a -= k\n } else {\n bsBuilder += k\n b -= k\n }\n k -= 1\n }\n\n val as = asBuilder.result().reverse\n val bs = bsBuilder.result().reverse\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(as.length)\n println(as.mkString(\" \"))\n println(bs.length)\n println(bs.mkString(\" \"))\n\n Console.flush\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n var a, b = ni()\n def calcN(sum: Long) = {\n var i = 0\n while(i.toLong * i + i <= 2 * sum) {i += 1}\n i - 1\n }\n val n = calcN(a + b)\n val selected = mutable.Set[Int]()\n var last = n\n while(a > 0 && last > 0) {\n if (a > last) {\n selected += last\n a -= last\n last -= 1\n } else {\n selected += a\n a = 0\n }\n }\n\n out.println(selected.size)\n out.println(selected.mkString(\" \"))\n out.println(n - selected.size)\n val bs = ArrayBuffer[Int]()\n rep(n, 1) { i =>\n if (!selected.contains(i)) bs += i\n }\n out.println(bs.mkString(\" \"))\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n var a, b = ni()\n def calcN(sum: Int) = {\n var i = 0\n while(i * i + i< 2 * sum) {i += 1}\n i\n }\n val n = calcN(a + b)\n val selected = mutable.Set[Int]()\n var last = n\n while(a > 0) {\n if (a > last) {\n selected += last\n a -= last\n last -= 1\n } else {\n selected += a\n a = 0\n }\n }\n\n out.println(selected.size)\n out.println(selected.mkString(\" \"))\n out.println(n - selected.size)\n val bs = ArrayBuffer[Int]()\n rep(n, 1) { i =>\n if (!selected.contains(i)) bs += i\n }\n out.println(bs.mkString(\" \"))\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n var a, b = ni()\n def calcN(sum: Long) = {\n var i = 0\n while(i.toLong * i + i< 2 * sum) {i += 1}\n i\n }\n val n = calcN(a + b)\n val selected = mutable.Set[Int]()\n var last = n\n while(a > 0) {\n if (a > last) {\n selected += last\n a -= last\n last -= 1\n } else {\n selected += a\n a = 0\n }\n }\n\n out.println(selected.size)\n out.println(selected.mkString(\" \"))\n out.println(n - selected.size)\n val bs = ArrayBuffer[Int]()\n rep(n, 1) { i =>\n if (!selected.contains(i)) bs += i\n }\n out.println(bs.mkString(\" \"))\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n var a, b = ni()\n def calcN(sum: Long) = {\n var i = 0\n while(i.toLong * i + i<= 2 * sum) {i += 1}\n i - 1\n }\n val n = calcN(a + b)\n val selected = mutable.Set[Int]()\n var last = n\n while(a > 0) {\n if (a > last) {\n selected += last\n a -= last\n last -= 1\n } else {\n selected += a\n a = 0\n }\n }\n\n out.println(selected.size)\n out.println(selected.mkString(\" \"))\n out.println(n - selected.size)\n val bs = ArrayBuffer[Int]()\n rep(n, 1) { i =>\n if (!selected.contains(i)) bs += i\n }\n out.println(bs.mkString(\" \"))\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}], "src_uid": "fab438cef9eb5e9e4a4a2e3f9e4f9cec"} {"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\nimport java.util.Scanner\n\nobject test6 extends App {\n val s=readLine\n val n=s.length\n val dp=new Array[Int](n)\n \n for(i<-1 until n){\n var j=i\n while(j>0 && s(i)!=s(dp(j-1))) j=dp(j-1)\n dp(i)=if(j>0) dp(j-1)+1 else 0\n }\n \n val max=if(n>2) dp.slice(1,n-1).max else 0\n var j=dp(n-1)\n while(j>max) j=dp(j-1)\n println(if(j==0) \"Just a legend\" else s.substring(0,j))\n} \n\n\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n\n def prefixFunction(str: String) = {\n val answer = Array.ofDim[Int](str.length)\n var k = 0\n (1 until str.length).foreach {\n case i =>\n while ((k > 0) && str(k) != str(i))\n k = answer(k - 1)\n if (str(k) == str(i))\n k += 1\n answer(i) = k\n }\n answer\n }\n\n val p = prefixFunction(line)\n\n if (p.last == 0)\n println(\"Just a legend\")\n else if (p.init.contains(p.last))\n println(line.take(p.last))\n else if (p(p.last - 1) == 0)\n println(\"Just a legend\")\n else\n println(line.take(p(p.last - 1)))\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n\n def prefixFunction(str: String) = {\n val answer = Array.ofDim[Int](str.length)\n var k = 0\n (1 until str.length).foreach {\n case i =>\n while ((k > 0) && str(k) != str(i))\n k = answer(k - 1)\n if (str(k) == str(i))\n k += 1\n answer(i) = k\n }\n answer\n }\n\n val p = prefixFunction(line)\n\n if (p.last == 0)\n println(\"Just a legend\")\n else if (p.init.contains(p.last))\n println(line.take(p.last))\n else if (p(p.last) == 0)\n println(\"Just a legend\")\n else\n println(line.take(p(p.last) - 1))\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n val first = line.head\n val last = line.last\n val lettersInit = Array.ofDim[Int](26)\n val lettersTail = Array.ofDim[Int](26)\n\n def isEqual(len: Int) = {\n (0 until len).forall(i => line(i) == line(line.length - 1 - len + i))\n }\n\n val candidates = (0 until line.length - 2).filter { i =>\n val j = line.length - 1 - i\n lettersInit(line(i) - 'a') += 1\n lettersTail(line(j) - 'a') += 1\n// println(line(i))\n// println(line(j))\n line(i) == last && line(j) == first && (lettersInit sameElements lettersTail)\n }\n\n candidates.find(i => isEqual(i) && line.indexOf(line.take(i + 1), 1) != line.length - 1 - i) match {\n case None => println(\"Just a legend\")\n case Some(i) => println(line.take(i + 1))\n }\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n\n def prefixFunction(str: String) = {\n val answer = Array.ofDim[Int](str.length)\n var k = 0\n (1 until str.length).foreach {\n case i =>\n while ((k > 0) && str(k) != str(i))\n k = answer(k - 1)\n if (str(k) == str(i))\n k += 1\n answer(i) = k\n }\n answer\n }\n\n val p = prefixFunction(line)\n\n if (p.last == 0)\n println(\"Just a legend\")\n else if (p.init.contains(p.last))\n println(line.take(p.last))\n else if (p(p.last) == 0)\n println(\"Just a legend\")\n else\n println(line.take(p(p.last)))\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n\n def prefixFunction(str: String) = {\n val answer = Array.ofDim[Int](str.length)\n var k = 0\n (1 until str.length).foreach {\n case i =>\n while ((k > 0) && str(k) != str(i))\n k = answer(k - 1)\n if (str(k) == str(i))\n k += 1\n answer(i) = k\n }\n answer\n }\n\n val p = prefixFunction(line)\n println(p.mkString(\" \"))\n\n if (p.last == 0)\n println(\"Just a legend\")\n else if (p.init.contains(p.last))\n println(line.take(p.last))\n else if (p(p.last - 1) == 0)\n println(\"Just a legend\")\n else\n println(line.take(p(p.last - 1)))\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n val first = line.head\n val last = line.last\n val lettersInit = Array.ofDim[Int](26)\n val lettersTail = Array.ofDim[Int](26)\n\n def isEqual(len: Int) = {\n (0 until len).forall(i => line(i) == line(line.length - 1 - len + i))\n }\n\n val candidates = (0 until line.length - 2).filter { i =>\n val j = line.length - 1 - i\n lettersInit(line(i) - 'a') += 1\n lettersTail(line(j) - 'a') += 1\n// println(line(i))\n// println(line(j))\n line(i) == last && line(j) == first && (lettersInit sameElements lettersTail) && isEqual(i)\n }\n\n candidates.find(i => line.indexOf(line.take(i + 1), 1) != line.length - 1 - i) match {\n case None => println(\"Just a legend\")\n case Some(i) => println(line.take(i + 1))\n }\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n\n def prefixFunction(str: String) = {\n val answer = Array.ofDim[Int](str.length)\n var k = 0\n (1 until str.length).foreach {\n case i =>\n while ((k > 0) && str(k) != str(i))\n k = answer(k - 1)\n if (str(k) == str(i))\n k += 1\n answer(i) = k\n }\n answer\n }\n\n val p = prefixFunction(line)\n\n if (p.last == 0)\n println(\"Just a legend\")\n else if (p.init.contains(p.last))\n println(line.take(p.last))\n else if (p(p.last) < 2)\n println(\"Just a legend\")\n else\n println(line.take(p(p.last) - 1))\n}"}], "src_uid": "fd94aea7ca077ee2806653d22d006fb1"} {"source_code": "import scala.io.StdIn\n\nobject VasyaBasketball {\n \n //0 for a, 1 for b\n def find(a:String, b:String):String = {\n val ai = a.split(\" \").map { x => x.toInt }\n val an = ai.length\n val at = ai.map { x => (x,0) }\n val bi = b.split(\" \").map { x => x.toInt }\n val bn = bi.length\n val bt = bi.map { x => (x,1) }\n val ct = at ++ bt\n val sct = ct.sortBy(_._1)\n //init max to v( {\n if (t==0){\n aBnum = aBnum + 1\n }else{\n bBnum = bBnum + 1\n }\n val valA = 3*(an-aBnum)+2*aBnum\n val valB = 3*(bn-bBnum)+2*bBnum\n //println(e + \",\" + t + \",\" + valA + \",\" + valB)\n score = valA - valB\n if (score>max){\n max = score\n maxA = valA\n maxB = valB\n }\n }\n }\n }\n maxA + \":\" + maxB\n }\n \n def main(args:Array[String]){\n val na = StdIn.readLine().toInt\n val as = StdIn.readLine()\n val nb = StdIn.readLine().toInt\n val bs = StdIn.readLine()\n println(find(as, bs))\n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val a = in.next().split(' ').map(_.toInt).sorted\n val m = in.next().toInt\n val b = in.next().split(' ').map(_.toInt).sorted\n\n def solution(a: Array[Int], b: Array[Int], ai: Int, bi: Int, n: Int, m: Int, maxF: Int, maxS: Int): (Int, Int) = {\n val candidateF = 2 * n + (a.length - ai)\n val candidateS = 2 * m + (b.length - bi)\n val (nMaxF, nMaxS) =\n if (candidateF - candidateS > maxF - maxS)\n (candidateF, candidateS)\n else\n (maxF, maxS)\n if (ai == n && bi == m) (nMaxF, nMaxS)\n else if (ai == n || bi == m) solution(a, b, n, m, n, m, nMaxF, nMaxS)\n else {\n val min = Math.min(a(ai), b(bi))\n solution(a, b, (ai until n).find(i => a(i) > min).getOrElse(a.length),\n (bi until m).find(i => b(i) > min).getOrElse(b.length), n, m, nMaxF, nMaxS)\n }\n }\n\n val res = solution(a, b, 0, 0, n, m, 3 * n, 3 * m)\n\n println(s\"${res._1}:${res._2}\")\n}\n\n\n"}, {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nobject C_VasyaAndBasketball {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextLong()\n\n val firstTeam = (for (i <- 1l to n) yield {\n scanner.nextLong()\n }).sorted.toList\n\n val m = scanner.nextLong()\n\n val secondTeam = (for (i <- 1l to m) yield {\n scanner.nextLong()\n }).sorted.toList\n\n val throws = firstTeam.map(x => (x, 1)) ::: secondTeam.map(y => (y, 2))\n val sortedThrows = throws.sortBy(x => x._1)\n\n val startPoints = (sortedThrows.count(x => x._2 == 1) * 3, sortedThrows.count(x => x._2 == 2) * 3)\n\n def evalPoints(startPoints : (Int, Int), throws : List[(Long, Int)], acc : List[(Int, Int)] = Nil) : List[(Int, Int)] = {\n throws match {\n case (x, 1) :: tail => evalPoints((startPoints._1 - 1, startPoints._2), tail, (startPoints._1 - 1, startPoints._2) :: acc)\n case (x, 2) :: tail => evalPoints((startPoints._1, startPoints._2 - 1), tail, (startPoints._1, startPoints._2 - 1) :: acc)\n case Nil => acc.reverse\n }\n }\n\n val points = startPoints :: evalPoints(startPoints, sortedThrows)\n val maxPoint = points.maxBy(x => x._1 - x._2)\n\n out.println(s\"${maxPoint._1}:${maxPoint._2}\")\n }\n}\n"}, {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nimport scala.annotation.tailrec\n\nobject C_VasyaAndBasketball {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextLong()\n\n val firstTeam = (for (i <- 1l to n) yield {\n scanner.nextLong()\n }).sorted.toList\n\n val m = scanner.nextLong()\n\n val secondTeam = (for (i <- 1l to m) yield {\n scanner.nextLong()\n }).sorted.toList\n\n val throws = firstTeam.map(x => (x, 1)) ::: secondTeam.map(y => (y, 2))\n val sortedThrows = throws.sortBy(x => x._1)\n\n val startPoints = (sortedThrows.count(x => x._2 == 1) * 3, sortedThrows.count(x => x._2 == 2) * 3)\n\n @tailrec def evalPoints(startPoints : (Int, Int), throws : List[(Long, Int)], acc : List[(Int, Int)] = Nil) : List[(Int, Int)] = {\n throws match {\n case (x, 1) :: tail => evalPoints((startPoints._1 - 1, startPoints._2), tail, (startPoints._1 - 1, startPoints._2) :: acc)\n case (x, 2) :: tail => evalPoints((startPoints._1, startPoints._2 - 1), tail, (startPoints._1, startPoints._2 - 1) :: acc)\n case Nil => acc.reverse\n }\n }\n\n val points = startPoints :: evalPoints(startPoints, sortedThrows)\n val maxPoint = points.maxBy(x => x._1 - x._2)\n\n out.println(s\"${maxPoint._1}:${maxPoint._2}\")\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val a = in.next().split(' ').map(_.toInt).sorted\n val m = in.next().toInt\n val b = in.next().split(' ').map(_.toInt).sorted\n\n def solution(a: Array[Int], b: Array[Int], ai: Int, bi: Int, n: Int, m: Int, maxF: Int, maxS: Int): (Int, Int) = {\n val candidateF = 2 * n + (a.length - ai)\n val candidateS = 2 * m + (b.length - bi)\n val (nMaxF, nMaxS) =\n if (candidateF - candidateS > maxF - maxS)\n (candidateF, candidateS)\n else\n (maxF, maxS)\n if (ai == n || bi == m) (nMaxF, nMaxS)\n else {\n val min = Math.min(a(ai), b(bi))\n solution(a, b, (ai + 1 until n).find(i => a(i) > min).getOrElse(a.length),\n (bi + 1 until m).find(i => b(i) > min).getOrElse(b.length), n, m, nMaxF, nMaxS)\n }\n }\n\n val res = solution(a, b, 0, 0, n, m, 0, 0)\n\n println(s\"${res._1}:${res._2}\")\n}\n\n\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val a = in.next().split(' ').map(_.toInt).sorted\n val m = in.next().toInt\n val b = in.next().split(' ').map(_.toInt).sorted\n\n val res = b.foldLeft(b.length * 3l, (a.length * 3l, b.length * 3l), 0) {\n case ((second, (firstM, secondM), index), el) =>\n val newSecond = second - 1\n val newIndex = (index + 1 until a.length).find(i => a(i) > el).map(_ - 1).getOrElse(a.length)\n val newFirst = 3l * a.length - newIndex\n val nDiff = newFirst - newSecond\n val oldDiff = firstM - secondM\n if (nDiff > oldDiff || (nDiff == oldDiff && newFirst >= firstM)) {\n (newSecond, (newFirst, newSecond), newIndex)\n } else {\n (newSecond, (firstM, secondM), newIndex)\n }\n }\n\n println(s\"${res._2._1}:${res._2._2}\")\n}\n\n\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val a = in.next().split(' ').map(_.toInt).sorted\n val m = in.next().toInt\n val b = in.next().split(' ').map(_.toInt).sorted\n\n val res = b.foldLeft(b.length * 3l, (a.length * 3l, b.length * 3l), 0) {\n case ((second, (firstM, secondM), index), el) =>\n val newSecond = second - 1\n val newIndex = (index + 1 until a.length).find(i => a(i) > el).getOrElse(a.length)\n val newFirst = 3 * a.length - newIndex\n val nDiff = newFirst - newSecond\n val oldDiff = firstM - secondM\n if (nDiff > oldDiff || (nDiff == oldDiff && newFirst > firstM)) {\n (newSecond, (newFirst, newSecond), newIndex)\n } else {\n (newSecond, (firstM, secondM), newIndex)\n }\n }\n\n println(s\"${res._2._1}:${res._2._2}\")\n}\n\n\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val a = in.next().split(' ').map(_.toInt).sorted\n val m = in.next().toInt\n val b = in.next().split(' ').map(_.toInt).sorted\n\n val res = b.foldLeft(a.length * 3l, b.length * 3l, (a.length * 3l, b.length * 3l), 0) {\n case ((first, second, (firstM, secondM), index), el) =>\n val newSecond = second - 1\n val newIndex = (index + 1 until a.length).find(i => a(i) > el).map(_ - 1).getOrElse(a.length - 1)\n val newFirst = first - newIndex + index\n val nDiff = newFirst - newSecond\n val oldDiff = firstM - secondM\n if (nDiff > oldDiff || (nDiff == oldDiff && newFirst > firstM)) {\n (newFirst, newSecond, (newFirst, newSecond), newIndex)\n } else {\n (newFirst, newSecond, (firstM, secondM), newIndex)\n }\n }\n\n println(s\"${res._3._1}:${res._3._2}\")\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val a = in.next().split(' ').map(_.toInt).sorted\n val m = in.next().toInt\n val b = in.next().split(' ').map(_.toInt).toList.sorted\n\n val res = b.foldLeft(a.length * 3l, b.length * 3l, (a.length * 3l, b.length * 3l), a) {\n case ((first, second, (firstM, secondM), left), el) =>\n val newSecond = second - 1\n val newLeft = left.dropWhile(i => i <= el)\n val newFirst = first - left.length + newLeft.length\n if (newFirst - newSecond >= firstM - secondM) {\n (newFirst, newSecond, (newFirst, newSecond), newLeft)\n } else {\n (newFirst, newSecond, (firstM, secondM), newLeft)\n }\n }\n\n println(s\"${res._3._1}:${res._3._2}\")\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val a = in.next().split(' ').map(_.toInt).sorted\n val m = in.next().toInt\n val b = in.next().split(' ').map(_.toInt).sorted\n\n def solution(a: Array[Int], b: Array[Int], ai: Int, bi: Int, n: Int, m: Int, maxF: Int, maxS: Int): (Int, Int) = {\n val candidateF = 2 * n + (a.length - ai)\n val candidateS = 2 * m + (b.length - bi)\n val (nMaxF, nMaxS) =\n if (candidateF - candidateS > maxF - maxS)\n (candidateF, candidateS)\n else\n (maxF, maxS)\n if (ai == n || bi == m) (nMaxF, nMaxS)\n else {\n val min = Math.min(a(ai), b(bi))\n solution(a, b, (ai + 1 until n).find(i => a(i) > min).getOrElse(a.length),\n (bi + 1 until m).find(i => b(i) > min).getOrElse(b.length), n, m, nMaxF, nMaxS)\n }\n }\n\n val res = solution(a, b, 0, 0, n, m, 3 * n, 3 * m)\n\n println(s\"${res._1}:${res._2}\")\n}\n\n\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val a = in.next().split(' ').map(_.toInt).sorted\n val m = in.next().toInt\n val b = in.next().split(' ').map(_.toInt).sorted\n\n val res = b.foldLeft(b.length * 3l, (a.length * 3l, b.length * 3l), 0) {\n case ((second, (firstM, secondM), index), el) =>\n val newSecond = second - 1\n val newIndex = (index + 1 until a.length).find(i => a(i) > el).map(_ - 1).getOrElse(a.length)\n val newFirst = 3 * a.length - newIndex\n val nDiff = newFirst - newSecond\n val oldDiff = firstM - secondM\n if (nDiff > oldDiff || (nDiff == oldDiff && newFirst >= firstM)) {\n (newSecond, (newFirst, newSecond), newIndex)\n } else {\n (newSecond, (firstM, secondM), newIndex)\n }\n }\n\n println(s\"${res._2._1}:${res._2._2}\")\n}\n\n\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val a = in.next().split(' ').map(_.toInt).sorted\n val m = in.next().toInt\n val b = in.next().split(' ').map(_.toInt).sorted\n\n def solution(a: Array[Int], b: Array[Int], ai: Int, bi: Int, n: Int, m: Int, maxF: Int, maxS: Int): (Int, Int) = {\n val candidateF = 2 * n + (a.length - ai)\n val candidateS = 2 * m + (b.length - bi)\n val (nMaxF, nMaxS) =\n if (candidateF - candidateS > maxF - maxS)\n (candidateF, candidateS)\n else\n (maxF, maxS)\n if (ai == n || bi == m) (nMaxF, nMaxS)\n else {\n val min = Math.min(a(ai), b(bi))\n solution(a, b, (ai until n).find(i => a(i) > min).getOrElse(a.length),\n (bi until m).find(i => b(i) > min).getOrElse(b.length), n, m, nMaxF, nMaxS)\n }\n }\n\n val res = solution(a, b, 0, 0, n, m, 3 * n, 3 * m)\n\n println(s\"${res._1}:${res._2}\")\n}\n\n\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val a = in.next().split(' ').map(_.toInt).sorted\n val m = in.next().toInt\n val b = in.next().split(' ').map(_.toInt).sorted\n\n val res = b.foldLeft(a.length * 3l, b.length * 3l, (a.length * 3l, b.length * 3l), 0) {\n case ((first, second, (firstM, secondM), index), el) =>\n val newSecond = second - 1\n val newIndex = (index + 1 until a.length).find(_ > el).map(_ - 1).getOrElse(index)\n val newFirst = first - newIndex + index\n val nDiff = newFirst - newSecond\n val oldDiff = firstM - secondM\n if (nDiff > oldDiff || (nDiff == oldDiff && newFirst > firstM)) {\n (newFirst, newSecond, (newFirst, newSecond), newIndex)\n } else {\n (newFirst, newSecond, (firstM, secondM), newIndex)\n }\n }\n\n println(s\"${res._3._1}:${res._3._2}\")\n}"}], "src_uid": "a30b5ff6855dcbad142f6bcc282601a0"} {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n val (h, l) = (an.min, an.max)\r\n\r\n val bn =\r\n if (h.signum >= 0) Some(0 to l)\r\n else None\r\n\r\n bn match {\r\n case Some(value) =>\r\n println(\"YES\")\r\n println(value.length)\r\n println(value.mkString(\" \"))\r\n case _ =>\r\n println(\"NO\")\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.io.StdIn._\r\nimport scala.collection.immutable._\r\nimport scala.annotation.tailrec\r\nimport scala.collection.mutable.ListBuffer\r\nobject test {\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt\r\n \r\n while(t > 0) {\r\n var n = readInt\r\n val arr = readLine.split(\" \").map(_.toInt).toList\r\n var cur = arr.length - 1\r\n var flag = 1\r\n try {\r\n for(x <- arr) {\r\n if(x < 0) {\r\n print(\"NO\")\r\n flag = 0\r\n object break extends Exception { }\r\n throw break\r\n }\r\n }\r\n }\r\n catch {\r\n case break =>\r\n }\r\n if(flag == 1) {\r\n println(\"YES\")\r\n println(arr.max + 1)\r\n for(x <- 0 to arr.max)\r\n print(x + \" \")\r\n }\r\n println()\r\n t -= 1\r\n }\r\n }\r\n}"}], "negative_code": [{"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt).sorted\r\n\r\n val (h, l) = (an.head, an.last)\r\n\r\n val bn =\r\n if (h.signum >= 0) Some(0 to l)\r\n else if (an.length == 1) Some(h to l)\r\n else if (an.length == 2 && (l == 0 || l == -h)) Some(h to (-h, -h))\r\n else if (an.length == 3 && l == -h && an.sum == 0) Some(h to (l, l))\r\n else None\r\n\r\n bn match {\r\n case Some(value) =>\r\n println(\"YES\")\r\n println(value.length)\r\n println(value.mkString(\" \"))\r\n case _ =>\r\n println(\"NO\")\r\n }\r\n }\r\n}\r\n"}, {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt).sorted\r\n\r\n val (h, l) = (an.head, an.last)\r\n\r\n val bn =\r\n if (h.signum >= 0) Some(0 to l)\r\n else if (an.length == 1) Some(h to l)\r\n else if (an.length == 2 && l.signum == 0) Some(h to (-h, -h))\r\n else if (an.length == 3 && -h == l && an(1) == 0) Some(h to (l, l))\r\n else None\r\n\r\n bn match {\r\n case Some(value) =>\r\n println(\"YES\")\r\n println(value.length)\r\n println(value.mkString(\" \"))\r\n case _ =>\r\n println(\"NO\")\r\n }\r\n }\r\n}\r\n"}, {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt).sorted\r\n\r\n val (h, l) = (an.head, an.last)\r\n\r\n val bn =\r\n if (h.signum == l.signum || h.signum * l.signum == 0) Some(0 to l)\r\n else if (an.length == 3 && h.signum * h == l.signum * l) Some(h to l)\r\n else None\r\n\r\n bn match {\r\n case Some(value) =>\r\n println(\"YES\")\r\n println(value.length)\r\n println(value.mkString(\" \"))\r\n case _ =>\r\n println(\"NO\")\r\n }\r\n }\r\n}\r\n"}, {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt).sorted\r\n\r\n val (h, l) = (an.head, an.last)\r\n\r\n val bn =\r\n if (h.signum == l.signum || h.signum * l.signum == 0) Some(h to l)\r\n else if (an.length == 3 && h.signum * h == l.signum * l) Some(h to l)\r\n else None\r\n\r\n bn match {\r\n case Some(value) =>\r\n println(\"YES\")\r\n println(value.length)\r\n println(value.mkString(\" \"))\r\n case _ =>\r\n println(\"NO\")\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn._\r\nimport scala.collection.immutable._\r\nimport scala.annotation.tailrec\r\nimport scala.collection.mutable.ListBuffer\r\nobject test {\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt\r\n \r\n while(t > 0) {\r\n var n = readInt\r\n val arr = readLine.split(\" \").map(_.toInt).toList\r\n var cur = arr.length - 1\r\n var flag = 1\r\n try {\r\n for(x <- arr) {\r\n if(x < 0) {\r\n print(\"NO\")\r\n flag = 0\r\n object break extends Exception { }\r\n throw break\r\n }\r\n }\r\n }\r\n catch {\r\n case break =>\r\n }\r\n if(flag == 1) {\r\n println(\"YES\")\r\n println(arr.max - arr.min + 1)\r\n for(x <- 0 to arr.max)\r\n print(x + \" \")\r\n }\r\n println()\r\n t -= 1\r\n }\r\n }\r\n}"}], "src_uid": "5698e6fd934b9f6b847d7e30a3d06f2b"} {"source_code": "/**\n * Contest 213, Div 2, problem C\n *\n *

You have a string of decimal digits s. Let's define bij = si·sj. Find\n * in matrix b the number of such rectangles that the sum bij for all\n * cells (i, j) that are the elements of the rectangle equals a in each\n * rectangle.\n *\n * A rectangle in a matrix is a group of four integers (x, y, z, t)\n * (x ≤ y, z ≤ t). The elements of the rectangle are all cells (i, j)\n * such that x ≤ i ≤ y, z ≤ j ≤ t.\n *\n * Input The first line contains integer a (0 ≤ a ≤ 109), the second line\n * contains a string of decimal integers s (1 ≤ |s| ≤ 4000).\n *\n * Output Print a single integer — the answer to a problem.\n *\n * Please, do not write the %lld specifier to read or write 64-bit\n * integers in С++. It is preferred to use the cin, cout streams or the\n * %I64d specifier.

\n */\nobject Round213_Div2_Task3 {\n val inputStreamReader = {\n import java.net.InetAddress\n import java.security.MessageDigest\n import java.io.{ FileInputStream, InputStreamReader, BufferedReader }\n \n val md = MessageDigest.getInstance(\"SHA-1\")\n val userName = System.getProperty(\"user.name\")\n val hostName = InetAddress.getLocalHost.getHostName\n\n val bytes = md.digest((userName + hostName).getBytes)\n val sb = new StringBuilder\n for (i ← 0 until bytes.length)\n sb.append(Integer.toString((bytes(i) & 0xff) + 0x100, 16).substring(1))\n\n val inputStream =\n if (sb.result == \"51a302f8ba1abe181e33fe86c0ab4c7bedfb6c9\") new FileInputStream(\"tmp/0.txt\")\n else System.in\n new BufferedReader(new InputStreamReader(inputStream))\n }\n\n def main(args: Array[String]): Unit = {\n val a = inputStreamReader.readLine.toInt\n val str = inputStreamReader.readLine\n val prefix = Array.fill(str.length + 1)(0)\n for (i ← 1 to str.length)\n prefix(i) = prefix(i - 1) + str.charAt(i - 1) - '0'\n val count = Array.fill(40000)(0L)\n for {\n i ← 0 until prefix.length\n j ← i + 1 until prefix.length\n } count(prefix(j) - prefix(i)) += 1\n val res = if (a == 0) {\n count(0) * (str.length * (str.length + 1) - count(0))\n } else {\n (1 until count.length)\n .withFilter(i ⇒ a % i == 0 && a / i < count.length)\n .map(i ⇒ count(i) * count(a / i))\n .sum\n }\n println(res)\n }\n}", "positive_code": [{"source_code": "import scala.collection.mutable.HashMap\n\nobject Matrix extends App {\n val a = readInt\n val s = readLine.map(_.toInt - 0x30).toArray\n val n = s.size\n val sum = new Array[Int](n + 1)\n\n for(i <- 1 to n) sum(i) = sum(i-1) + s(i-1)\n\n val cnt = new Array[Long](n * 10)\n for(i <- 0 to n; j <- i+1 to n) {\n val x = sum(j) - sum(i)\n cnt(x) = cnt(x) + 1\n }\n\n if (a == 0) {\n val ret = cnt(0) * n * (n + 1) - cnt(0) * cnt(0)\n println(ret)\n exit(0)\n }\n\n val mapAll = HashMap[Int, Long]()\n for(i <- 1 until cnt.size if cnt(i) != 0) mapAll.put(i, cnt(i))\n\n def mapFunc(kv: (Int, Long)): Long = {\n val key = kv._1\n if (a % key == 0 && mapAll.contains(a/key))\n kv._2 * mapAll(a/key)\n else 0\n }\n\n println(mapAll.map(mapFunc).toList.foldLeft(0.toLong)((x:Long, y:Long) => x + y))\n}"}, {"source_code": "/**\n * Contest 213, Div 2, problem C\n *\n *

You have a string of decimal digits s. Let's define bij = si·sj. Find\n * in matrix b the number of such rectangles that the sum bij for all\n * cells (i, j) that are the elements of the rectangle equals a in each\n * rectangle.\n *\n * A rectangle in a matrix is a group of four integers (x, y, z, t)\n * (x ≤ y, z ≤ t). The elements of the rectangle are all cells (i, j)\n * such that x ≤ i ≤ y, z ≤ j ≤ t.\n *\n * Input The first line contains integer a (0 ≤ a ≤ 109), the second line\n * contains a string of decimal integers s (1 ≤ |s| ≤ 4000).\n *\n * Output Print a single integer — the answer to a problem.\n *\n * Please, do not write the %lld specifier to read or write 64-bit\n * integers in С++. It is preferred to use the cin, cout streams or the\n * %I64d specifier.

\n */\nobject Round213_Div2_Task3 {\n val inputStreamReader = {\n import java.net.InetAddress\n import java.security.MessageDigest\n import java.io.{ FileInputStream, InputStreamReader, BufferedReader }\n\n val md = MessageDigest.getInstance(\"SHA-1\")\n val userName = System.getProperty(\"user.name\")\n val hostName = InetAddress.getLocalHost.getHostName\n\n val bytes = md.digest((userName + hostName).getBytes)\n val sb = new StringBuilder\n for (i ← 0 until bytes.length)\n sb.append(Integer.toString((bytes(i) & 0xff) + 0x100, 16).substring(1))\n\n val inputStream =\n if (sb.result == \"51a302f8ba1abe181e33fe86c0ab4c7bedfb6c91\") new FileInputStream(\"tmp/0.txt\")\n else System.in\n new BufferedReader(new InputStreamReader(inputStream))\n }\n\n def main(args: Array[String]): Unit = {\n val a = inputStreamReader.readLine.toInt\n val str = inputStreamReader.readLine\n val prefix = str.foldLeft(Vector(0))((acc, ch) => acc :+ (ch - '0' + acc.last))\n val count = Array.fill(40000)(0L)\n for {\n i ← 0 until prefix.length\n j ← i + 1 until prefix.length\n } count(prefix(j) - prefix(i)) += 1\n val res =\n if (a == 0) count(0) * (str.length * (str.length + 1) - count(0))\n else\n (1 until count.length)\n .withFilter(i ⇒ a % i == 0 && a / i < count.length)\n .map(i ⇒ count(i) * count(a / i))\n .sum\n println(res)\n }\n}"}], "negative_code": [{"source_code": "\nimport scala.collection.mutable.HashMap\n\nobject Matrix extends App {\n val a = readInt\n val s = readLine.map(_.toInt - 0x30).toArray\n val n = s.size\n val sum = new Array[Int](n + 1)\n\n for(i <- 1 to n) sum(i) = sum(i-1) + s(i-1)\n\n val cnt = new Array[Int](n * 10)\n for(i <- 0 to n; j <- i+1 to n) {\n val x = sum(j) - sum(i)\n cnt(x) = cnt(x) + 1\n }\n\n if (a == 0) {\n val ret = cnt(0) * n * (n + 1) - cnt(0) * cnt(0)\n println(ret)\n exit(0)\n }\n\n val mapAll = HashMap[Int, Long]()\n for(i <- 1 until cnt.size if cnt(i) != 0) mapAll.put(i, cnt(i))\n\n def mapFunc(kv: (Int, Long)): Long = {\n val key = kv._1\n if (a % key == 0 && mapAll.contains(a/key))\n kv._2 * mapAll(a/key)\n else 0\n }\n\n println(mapAll.map(mapFunc).reduce(_ + _))\n}"}, {"source_code": "import scala.collection.mutable.HashMap\n\nobject Matrix extends App {\n val a = readInt\n val s = readLine.map(_.toInt - 0x30).toArray\n val n = s.size\n val sum = new Array[Int](n + 1)\n\n for(i <- 1 to n) sum(i) = sum(i-1) + s(i-1)\n\n val cnt = new Array[Int](n * 10)\n for(i <- 0 to n; j <- i+1 to n) {\n val x = sum(j) - sum(i)\n cnt(x) = cnt(x) + 1\n }\n\n val mapAll = HashMap[Int, Long]()\n for(i <- 1 until cnt.size if cnt(i) != 0) mapAll.put(i, cnt(i))\n\n def mapFunc(kv: (Int, Long)): Long = {\n val key = kv._1\n if (a % key == 0 && mapAll.contains(a/key))\n kv._2 * mapAll(a/key)\n else 0\n }\n\n println(mapAll.map(mapFunc).reduce(_ + _))\n}"}, {"source_code": "/**\n * Contest 213, Div 2, problem C\n *\n *

You have a string of decimal digits s. Let's define bij = si·sj. Find\n * in matrix b the number of such rectangles that the sum bij for all\n * cells (i, j) that are the elements of the rectangle equals a in each\n * rectangle.\n *\n * A rectangle in a matrix is a group of four integers (x, y, z, t)\n * (x ≤ y, z ≤ t). The elements of the rectangle are all cells (i, j)\n * such that x ≤ i ≤ y, z ≤ j ≤ t.\n *\n * Input The first line contains integer a (0 ≤ a ≤ 109), the second line\n * contains a string of decimal integers s (1 ≤ |s| ≤ 4000).\n *\n * Output Print a single integer — the answer to a problem.\n *\n * Please, do not write the %lld specifier to read or write 64-bit\n * integers in С++. It is preferred to use the cin, cout streams or the\n * %I64d specifier.

\n */\nobject Round213_Div2_Task3 {\n import java.net.InetAddress\n import java.security.MessageDigest\n import java.io.{ FileInputStream, InputStreamReader, BufferedReader }\n \n val inputStreamReader = {\n val md = MessageDigest.getInstance(\"SHA-1\")\n val userName = System.getProperty(\"user.name\")\n val hostName = InetAddress.getLocalHost.getHostName\n\n val bytes = md.digest((userName + hostName).getBytes)\n val sb = new StringBuilder\n for (i ← 0 until bytes.length)\n sb.append(Integer.toString((bytes(i) & 0xff) + 0x100, 16).substring(1))\n\n val inputStream =\n if (sb.result == \"51a302f8ba1abe181e33fe86c0ab4c7bedfb6c91\") new FileInputStream(\"tmp/0.txt\")\n else System.in\n new BufferedReader(new InputStreamReader(inputStream))\n }\n\n def main(args: Array[String]): Unit = {\n val a = inputStreamReader.readLine.toInt\n val str = inputStreamReader.readLine\n val prefix = Array.fill(str.length + 1)(0)\n for (i ← 1 to str.length)\n prefix(i) = prefix(i - 1) + str.charAt(i - 1) - '0'\n val count = Array.fill(40000)(0L)\n for {\n i ← 0 until prefix.length\n j ← i + 1 until prefix.length\n } count(prefix(j) - prefix(i)) += 1\n val res = (1 until count.length)\n .withFilter(i ⇒ a % i == 0 && a / i < count.length)\n .map(i ⇒ count(i) * count(a / i))\n .sum\n println(res)\n }\n}"}], "src_uid": "b429b42ba8be9df4b87b68420e9873bc"} {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable._\r\n\r\nobject test {\r\n val writer = new PrintWriter(System.out)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\r\n def readInt(): Int = next().toInt\r\n def readLong(): Long = next().toLong\r\n def readString(): String = next()\r\n\r\n def main(args: Array[String]): Unit = {\r\n val t = readInt()\r\n for (tt <- 1 to t) {\r\n val n = readInt()\r\n val s = readString()\r\n var cnt = 0\r\n cnt += 2*s.count(_ == '1')\r\n cnt += 3*s.count(_ == '2')\r\n cnt += 4*s.count(_ == '3')\r\n cnt += 5*s.count(_ == '4')\r\n cnt += 6*s.count(_ == '5')\r\n cnt += 7*s.count(_ == '6')\r\n cnt += 8*s.count(_ == '7')\r\n cnt += 9*s.count(_ == '8')\r\n cnt += 10*s.count(_ == '9')\r\n if (s(s.length - 1) != '0')\r\n cnt -= 1\r\n println(cnt)\r\n writer.flush()\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object A extends App {\r\n\r\n def countdown(digits: Seq[Int]): Int = {\r\n val reversed = digits.reverse\r\n reversed.drop(1).foldLeft(reversed.headOption.getOrElse(0)) {\r\n case (count, 0) => count\r\n case (count, digit) => count + digit + 1\r\n }\r\n }\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val sn = readLine().split(\"\").map(_.toInt)\r\n\r\n println(countdown(sn))\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "6571fdd506a858d7620c2faa0fe46cc1"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\nobject B {\n def solve(in: Input, out: Output): Unit = {\n val n = in.nextInt()\n val p = -1 +: Array.fill(n - 1)(in.nextInt() - 1)\n val nChildren, nLeafChildren = Array.fill(n)(0)\n for (i <- 1 until n) {\n nChildren(p(i)) += 1\n }\n for (i <- 1 until n if nChildren(i) == 0) {\n nLeafChildren(p(i)) += 1\n }\n val isNYTree = (0 until n).forall(i => nChildren(i) == 0 || nLeafChildren(i) >= 3)\n println(if (isNYTree) \"Yes\" else \"No\")\n }\n\n class Input(in: InputStream) extends Closeable {\n private[this] val br = new BufferedReader(new InputStreamReader(in))\n private[this] var st = new StringTokenizer(br.readLine())\n\n override def close(): Unit = br.close()\n\n @tailrec\n final def next(): String = if (st.hasMoreTokens) st.nextToken() else {\n st = new StringTokenizer(br.readLine())\n next()\n }\n\n final def nextInt(): Int = next().toInt\n final def nextLong(): Long = next().toLong\n final def nextDouble(): Double = next().toDouble\n }\n\n final type Output = PrintWriter\n\n def main(args: Array[String]): Unit = {\n val in = new Input(System.in)\n val out = new Output(System.out)\n solve(in, out)\n out.close()\n in.close()\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val cs, cs2 = Array.fill(n){ 0L }\n val ps = Array.fill(n)(0)\n\n for (i <- 1 until n) {\n val Array(p) = readInts(1)\n ps(i) = p - 1\n cs(p - 1) += 1\n }\n\n for (i <- 1 until n) {\n if (cs(i) == 0) cs2(ps(i)) += 1\n }\n var ok = true\n\n for (i <- 0 until n) {\n if (cs(i) > 0 && cs2(i) < 3) ok = false\n }\n\n println(if (ok) \"Yes\" else \"No\")\n\n Console.flush\n}\n"}, {"source_code": "object B extends App {\n val n = scala.io.StdIn.readInt()\n\n def isTree(g: Vector[List[Int]]): Boolean = {\n def dfs(v: Int = 0): Boolean = {\n val adj = g(v)\n val notEmpty = adj.filterNot(u => g(u).isEmpty)\n if (adj.length - notEmpty.length < 3) false\n else if (notEmpty.isEmpty) true\n else notEmpty.forall(u => dfs(u))\n }\n\n dfs()\n }\n\n val g = (0 until n - 1).foldLeft(Vector.fill(n)(List.empty[Int])) ((g, i) => {\n val v = scala.io.StdIn.readInt() - 1\n val u = i + 1\n g.updated(v, u :: g(v))\n })\n\n if (isTree(g)) println(\"Yes\")\n else println(\"No\")\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject Main extends App {\n app()\n\n def app(): Unit = {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val g = Array.fill(n) { ArrayBuffer.empty[Int] }\n (1 until n).foreach { u =>\n val v = sc.nextInt() - 1\n g(u).append(v)\n g(v).append(u)\n }\n print(if (dfs(g) { (_, vs: Iterator[(Boolean, Int)]) => if (vs.isEmpty) (true, 0) else vs.foldRight((c: Int) => (c >= 3, c)) { (v, g) => (c: Int) => if (v._1) g(c + b2i(v._2 == 0)) else (false, 0) }(0) }._1) \"Yes\" else \"No\")\n }\n\n def b2i(b: Boolean): Int = if (b) 1 else 0\n\n def dfs[B](g: IndexedSeq[Iterable[Int]])(f: (Int, Iterator[B]) => B): B = {\n def go(p: Int)(u: Int): B = f(u, g(u).iterator.filter(_ != p).map(go(u)))\n go(0)(0)\n }\n}"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\nobject B {\n def solve(in: Input, out: Output): Unit = {\n val n = in.nextInt()\n val p = -1 +: Array.fill(n - 1)(in.nextInt() - 1)\n val nChildren, nLeafChildren = Array.fill(n)(0)\n for (i <- 1 until n) {\n nChildren(p(i)) += 1\n }\n for (i <- 1 until n if nChildren(i) == 0) {\n nLeafChildren(p(i)) += 1\n }\n val isNYTree = nLeafChildren.forall(v => v == 0 || v >= 3)\n println(if (isNYTree) \"Yes\" else \"No\")\n }\n\n class Input(in: InputStream) extends Closeable {\n private[this] val br = new BufferedReader(new InputStreamReader(in))\n private[this] var st = new StringTokenizer(br.readLine())\n\n override def close(): Unit = br.close()\n\n @tailrec\n final def next(): String = if (st.hasMoreTokens) st.nextToken() else {\n st = new StringTokenizer(br.readLine())\n next()\n }\n\n final def nextInt(): Int = next().toInt\n final def nextLong(): Long = next().toLong\n final def nextDouble(): Double = next().toDouble\n }\n\n final type Output = PrintWriter\n\n def main(args: Array[String]): Unit = {\n val in = new Input(System.in)\n val out = new Output(System.out)\n solve(in, out)\n out.close()\n in.close()\n }\n}\n"}, {"source_code": "object B extends App {\n val n = scala.io.StdIn.readInt()\n\n def isTree(g: Vector[List[Int]]): Boolean = {\n def dfs(v: Int = 0): Boolean = {\n val adj = g(v)\n val notEmpty = adj.filterNot(u => g(u).isEmpty)\n if (adj.length - notEmpty.length != 3) false\n else if (notEmpty.isEmpty) true\n else notEmpty.forall(u => dfs(u))\n }\n\n dfs()\n }\n\n val g = (0 until n - 1).foldLeft(Vector.fill(n)(List.empty[Int])) ((g, i) => {\n val v = scala.io.StdIn.readInt() - 1\n val u = i + 1\n g.updated(v, u :: g(v))\n })\n\n if (isTree(g)) println(\"Yes\")\n else println(\"No\")\n}\n"}, {"source_code": "object B extends App {\n val n = scala.io.StdIn.readInt()\n\n def isTree(g: Vector[List[Int]]): Boolean = {\n // def dfs(h: List[(Int, Int, List[Int])], l: List[Int] = List.empty): Boolean =\n // if (h.isEmpty) {\n // val t = l.groupBy(identity).mapValues(_.size).values\n // println(t.mkString(\"\\t\"))\n // true\n // } else {\n // val (p, v, adj) = h.head\n // if (adj.isEmpty) dfs(h.tail, if (v != p) p :: l else l)\n // else {\n // val u = adj.head\n // if (u == p) dfs((p, v, adj.tail) :: h.tail, l)\n // else dfs((v, u, g(u)) :: (p, v, adj.tail) :: h.tail, l)\n // }\n // }\n //\n // dfs(List((0, 0, g(0))))\n\n def dfs(v: Int = 0): Boolean = {\n val t = g(v).count(u => g(u).isEmpty)\n if (t != 3) false\n else {\n val t = g(v).filterNot(u => g(u).isEmpty)\n if (t.isEmpty) true\n else t.map(u => dfs(u)).reduce(_ & _)\n }\n }\n\n dfs()\n }\n\n val g = (0 until n - 1).foldLeft(Vector.fill(n)(List.empty[Int])) ((g, i) => {\n val v = scala.io.StdIn.readInt() - 1\n val u = i + 1\n g.updated(v, u :: g(v))\n })\n\n if (isTree(g)) println(\"Yes\")\n else println(\"No\")\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject Main extends App {\n app()\n\n def app(): Unit = {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val g = Array.fill(n) { ArrayBuffer.empty[Int] }\n (1 until n).foreach { u =>\n val v = sc.nextInt() - 1\n g(u).append(v)\n g(v).append(u)\n }\n print(if (dfs(g) { (_, vs: Iterator[(Boolean, Int)]) => if (vs.isEmpty) (true, 0) else vs.foldRight((c: Int) => (c == 3, c)) { (v, g) => (c: Int) => if (v._1) g(c + b2i(v._2 == 0)) else (false, 0) }(0) }._1) \"Yes\" else \"No\")\n }\n\n def b2i(b: Boolean): Int = if (b) 1 else 0\n\n def dfs[B](g: IndexedSeq[Iterable[Int]])(f: (Int, Iterator[B]) => B): B = {\n def go(p: Int)(u: Int): B = f(u, g(u).iterator.filter(_ != p).map(go(u)))\n go(0)(0)\n }\n}"}], "src_uid": "69edc72ec29d4dd56751b281085c3591"} {"source_code": "object Main{\n def main(args:Array[String])={\n val sc = new java.util.Scanner(System.in)\n val n, x = sc.nextInt\n val a = Array.fill(1000001)(0)\n var ans:BigInt = 0\n for(i <- 1 to n)\n {\n var xx = sc.nextInt\n ans += a(xx^x)\n a(xx) += 1\n }\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "object B {\n import scala.collection.Searching._\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val nums = scala.io.StdIn.readLine.split(\" \").map(_.toInt).groupBy(identity).mapValues(_.length.toLong).toArray.sortBy(_._1)\n// println(nums.mkString(\" \"))\n var ex = 0.toLong\n val ns = nums.map(_._1)\n// println(ns.mkString(\" \"))\n val vs = nums.map(_._2)\n if (x > 0) {\n nums.foreach(y => ns.search(x ^ y._1) match {\n case Found(cc) =>\n {\n ex += vs(cc) * y._2\n// println(Array(x, y, nums(cc)).mkString(\" \"))\n }\n case InsertionPoint(cc) =>\n {\n// println(Array(-1, x, y, cc).mkString(\" \"))\n 0\n }\n })\n ex = (ex + 1) / 2\n } else {\n ex = vs.map(nn => nn * (nn - 1) / 2).sum\n }\n println(ex)\n }\n}\n"}, {"source_code": "object B742 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = readInts(2)\n val in = readInts(n)\n val map = cu.Map.empty[Int, Int].withDefaultValue(0)\n var res = 0L\n for(a <- in) {\n val c = x ^ a\n if(map(c) > 0)\n res += map(c)\n map(a) += 1\n }\n println(res)\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "object B {\n import scala.collection.Searching._\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val nums = scala.io.StdIn.readLine.split(\" \").map(_.toInt).groupBy(identity).mapValues(_.length).toArray.sortBy(_._1)\n// println(nums.mkString(\" \"))\n var ex = 0.toLong\n val ns = nums.map(_._1)\n// println(ns.mkString(\" \"))\n val vs = nums.map(_._2)\n if (x > 0) {\n nums.foreach(y => ns.search(x ^ y._1) match {\n case Found(cc) =>\n {\n ex += vs(cc) * y._2\n// println(Array(x, y, nums(cc)).mkString(\" \"))\n }\n case InsertionPoint(cc) =>\n {\n// println(Array(-1, x, y, cc).mkString(\" \"))\n 0\n }\n })\n ex = (ex + 1) / 2\n } else {\n ex = vs.map(nn => nn * (nn - 1) / 2).sum\n }\n println(ex)\n }\n}\n"}, {"source_code": "object B {\n import scala.collection.Searching._\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val nums = scala.io.StdIn.readLine.split(\" \").map(_.toInt).groupBy(identity).mapValues(_.length).toArray.sortBy(_._1)\n// println(nums.mkString(\" \"))\n var ex = 0\n val ns = nums.map(_._1)\n// println(ns.mkString(\" \"))\n val vs = nums.map(_._2)\n if (x > 0) {\n nums.foreach(y => ns.search(x ^ y._1) match {\n case Found(cc) =>\n {\n ex += vs(cc) * y._2\n// println(Array(x, y, nums(cc)).mkString(\" \"))\n }\n case InsertionPoint(cc) =>\n {\n// println(Array(-1, x, y, cc).mkString(\" \"))\n 0\n }\n })\n ex = (ex + 1) / 2\n } else {\n ex = vs.map(nn => nn * (nn - 1) / 2).sum\n }\n println(ex)\n }\n}\n"}, {"source_code": "object B {\n import scala.collection.Searching._\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val nums = scala.io.StdIn.readLine.split(\" \").map(_.toInt).sorted.groupBy(identity).mapValues(_.size)\n// println(nums.mkString(\" \"))\n var ex = 0\n val ns = nums.keys.toArray\n val vs = nums.values.toArray\n if (x > 0) {\n ns.zipWithIndex.foreach(y => ns.search(x ^ y._1) match {\n case Found(cc) =>\n {\n ex += vs(cc)\n// println(Array(x, y, nums(cc)).mkString(\" \"))\n }\n case InsertionPoint(cc) =>\n {\n// println(Array(-1, x, y, cc).mkString(\" \"))\n 0\n }\n })\n ex = (ex + 1) / 2\n } else {\n ex = vs.map(nn => nn * (nn - 1) / 2).sum\n }\n println(ex)\n }\n}\n"}, {"source_code": "object B {\n import scala.collection.Searching._\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val nums = scala.io.StdIn.readLine.split(\" \").map(_.toInt).sorted.groupBy(identity).mapValues(_.length)\n println(nums.mkString(\" \"))\n var ex = 0\n val ns = nums.keys.toArray\n println(ns.mkString(\" \"))\n val vs = nums.values.toArray\n if (x > 0) {\n ns.foreach(y => ns.search(x ^ y) match {\n case Found(cc) =>\n {\n ex += vs(cc)\n// println(Array(x, y, nums(cc)).mkString(\" \"))\n }\n case InsertionPoint(cc) =>\n {\n// println(Array(-1, x, y, cc).mkString(\" \"))\n 0\n }\n })\n ex = (ex + 1) / 2\n } else {\n ex = vs.map(nn => nn * (nn - 1) / 2).sum\n }\n println(ex)\n }\n}\n"}, {"source_code": "object B {\n import scala.collection.Searching._\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val nums = scala.io.StdIn.readLine.split(\" \").map(_.toInt).sorted\n var ex = 0\n if (x > 0) {\n nums.foreach(y => nums.search(x ^ y) match {\n case Found(cc) =>\n {\n ex += 1\n// println(Array(x, y, nums(cc)).mkString(\" \"))\n }\n case InsertionPoint(cc) =>\n {\n// println(Array(-1, x, y, cc).mkString(\" \"))\n 0\n }\n })\n ex = (ex + 1) / 2\n } else {\n ex = nums.groupBy(identity).mapValues(nn => nn.size * (nn.size - 1) / 2).values.sum\n }\n println(ex)\n }\n}\n"}, {"source_code": "object B {\n import scala.collection.Searching._\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val nums = scala.io.StdIn.readLine.split(\" \").map(_.toInt).groupBy(identity).mapValues(_.length).toArray.sortBy(_._1)\n// println(nums.mkString(\" \"))\n var ex = 0\n val ns = nums.map(_._1)\n// println(ns.mkString(\" \"))\n val vs = nums.map(_._2)\n if (x > 0) {\n ns.foreach(y => ns.search(x ^ y) match {\n case Found(cc) =>\n {\n ex += vs(cc)\n// println(Array(x, y, nums(cc)).mkString(\" \"))\n }\n case InsertionPoint(cc) =>\n {\n// println(Array(-1, x, y, cc).mkString(\" \"))\n 0\n }\n })\n ex = (ex + 1) / 2\n } else {\n ex = vs.map(nn => nn * (nn - 1) / 2).sum\n }\n println(ex)\n }\n}\n"}, {"source_code": "object B {\n import scala.collection.Searching._\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val nums = scala.io.StdIn.readLine.split(\" \").map(_.toInt).groupBy(identity).mapValues(_.length).toArray.sortBy(_._1)\n println(nums.mkString(\" \"))\n var ex = 0\n val ns = nums.map(_._1)\n println(ns.mkString(\" \"))\n val vs = nums.map(_._2)\n if (x > 0) {\n ns.foreach(y => ns.search(x ^ y) match {\n case Found(cc) =>\n {\n ex += vs(cc)\n// println(Array(x, y, nums(cc)).mkString(\" \"))\n }\n case InsertionPoint(cc) =>\n {\n// println(Array(-1, x, y, cc).mkString(\" \"))\n 0\n }\n })\n ex = (ex + 1) / 2\n } else {\n ex = vs.map(nn => nn * (nn - 1) / 2).sum\n }\n println(ex)\n }\n}\n"}, {"source_code": "object B {\n import scala.collection.Searching._\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val nums = scala.io.StdIn.readLine.split(\" \").map(_.toInt).sorted.groupBy(identity).mapValues(_.length)\n// println(nums.mkString(\" \"))\n var ex = 0\n val ns = nums.keys.toArray\n// println(ns.mkString(\" \"))\n val vs = nums.values.toArray\n if (x > 0) {\n ns.foreach(y => ns.search(x ^ y) match {\n case Found(cc) =>\n {\n ex += vs(cc)\n// println(Array(x, y, nums(cc)).mkString(\" \"))\n }\n case InsertionPoint(cc) =>\n {\n// println(Array(-1, x, y, cc).mkString(\" \"))\n 0\n }\n })\n ex = (ex + 1) / 2\n } else {\n ex = vs.map(nn => nn * (nn - 1) / 2).sum\n }\n println(ex)\n }\n}\n"}, {"source_code": "object B {\n import scala.collection.Searching._\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val nums = scala.io.StdIn.readLine.split(\" \").map(_.toInt).sorted\n var ex = 0\n if (x > 0) {\n nums.foreach(y => nums.search(x ^ y) match {\n case Found(cc) =>\n {\n ex += 1\n// println(Array(x, y, nums(cc)).mkString(\" \"))\n }\n case InsertionPoint(cc) =>\n {\n// println(Array(-1, x, y, cc).mkString(\" \"))\n 0\n }\n })\n ex /= 2\n } else {\n ex = nums.groupBy(identity).mapValues(nn => nn.size * (nn.size - 1) / 2).values.sum\n }\n println(ex)\n }\n}\n"}, {"source_code": "object Main{\n def main(args:Array[String])={\n val sc = new java.util.Scanner(System.in)\n val n, x = sc.nextInt\n val a = Array.fill(1000001)(0)\n var ans = 0\n for(i <- 1 to n)\n {\n var xx = sc.nextInt\n ans += a(xx^x)\n a(xx) += 1\n }\n println(ans)\n }\n}\n"}, {"source_code": "object B742 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = readInts(2)\n val in = readInts(n)\n val set = cu.Set.empty[Int]\n var res = 0L\n for(a <- in) {\n val c = x ^ a\n if(set.contains(c))\n res += 1\n set.add(a)\n }\n println(res)\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "daabf732540e0f66d009dc211c2d7b0b"} {"source_code": "import scala.math._\nimport scala.Console\nobject Object {\n \n def main(args : Array[String]){\n \n var n = readInt\n var ar = readLine split \" \"\n var m = scala.collection.mutable.Map(\"25\" -> 0, \"50\" -> 0, \"100\" -> 0)\n var yesOrNo = \"YES\"\n \n for(i <- 0 until n){\n ar(i) match {\n case \"25\" => {m(\"25\") += 1}\n case \"50\" => {m(\"50\") += 1;if(m(\"25\") > 0)m(\"25\") -= 1 else yesOrNo = \"NO\"} \n case \"100\"=> {if(m(\"25\") > 0 && m(\"50\") > 0){m(\"25\") -= 1; m(\"50\") -= 1} else if(m(\"25\") > 2){m(\"25\") -= 3} else yesOrNo = \"NO\"}\n case _ => {yesOrNo = \"NO\"}\n }\n }\n println(yesOrNo)\n }\n}", "positive_code": [{"source_code": "object Main {\n class Cash {\n private var n25, n50 = 0\n \n def add(n: Int) = n match {\n case 25 => n25 += 1; true\n case 50 => \n n50 += 1\n n25 -= 1\n n25 != -1\n case 100 =>\n if (n50 == 0) {\n n25 -= 3\n n25 >= 0\n } else {\n n50 -= 1\n n25 -= 1\n n25 != -1\n }\n }\n }\n\n def main(args: Array[String]) {\n val c = new Cash\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val r = a.foldLeft(true){ (r, n) => r & c.add(n) }\n if (r) println(\"YES\")\n else println(\"NO\")\n }\n}"}, {"source_code": "\nimport scala.io.StdIn\n\n/**\n * @author unit7\n */\nobject Main {\n def main(args: Array[String]) {\n val n = StdIn.readInt()\n val denominations = StdIn.readLine().split(\"\\\\s\").map(_.toInt)\n\n var can = true\n \n val cashBox = scala.collection.mutable.HashMap[Int, Int](25 -> 0, 50 -> 0)\n \n for (i <- 0 until n) {\n val denomination = denominations(i)\n \n if (denomination == 25) {\n cashBox.update(25, cashBox(25) + 1)\n } else if (denomination == 50) {\n val curTwentyFive = cashBox(25)\n \n if (curTwentyFive > 0) {\n cashBox.update(25, curTwentyFive - 1)\n cashBox.update(50, cashBox(50) + 1)\n } else {\n can = false\n }\n } else {\n var need = 3\n val curFifty = cashBox(50)\n \n if (curFifty > 0) {\n need -= 2\n cashBox.update(50, curFifty - 1)\n }\n \n val curTwentyFive = cashBox(25)\n \n if (curTwentyFive >= need) {\n cashBox.update(25, curTwentyFive - need)\n } else {\n can = false\n }\n }\n }\n \n println(if (can) \"YES\" else \"NO\")\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n var b25 = 0\n var b50 = 0\n var b100 = 0\n for (i <- 0 until n) {\n val b = sc.nextInt\n if (b == 25)\n b25 += 1\n else if (b == 50) {\n b50 += 1\n b25 -= 1\n }\n else if (b == 100) {\n b100 += 1\n b50 -= 1\n b25 -= 1\n }\n while (b50 < 0) {\n b25 -= 2\n b50 += 1\n }\n if (b25 < 0) {\n println(\"NO\")\n return\n }\n }\n println(\"YES\")\n }\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _349A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt)\n def f(a: List[Int], cb: Int, wb: Int): Boolean =\n if (cb < 0 || wb < 0) false\n else if (a == Nil) true\n else if (a.head == 25) f(a.tail, cb + 1, wb)\n else if (a.head == 50) f(a.tail, cb - 1, wb + 1)\n else {\n if (wb > 0) f(a.tail, cb - 1, wb - 1)\n else f(a.tail, cb - 3, wb)\n }\n\n if (f(a.toList, 0, 0)) println(\"YES\")\n else println(\"NO\")\n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n in.next()\n val data = in.next().split(\" \").map(_.toInt).foldLeft((0, 0, true)) {\n case((s, m, false), el) => (s, m, false)\n case((s, m, true), 25) => (s + 1, m, true)\n case((s, m, true), 50) => (s - 1, m + 1, s >= 1)\n case((s, m, true), 100) if m >= 1 => (s - 1, m - 1, s >= 1)\n case((s, m, true), 100) => (s - 3, m, s >= 3)\n }\n if (data._3)\n println(\"YES\")\n else\n println(\"NO\")\n}\n"}, {"source_code": "object A349 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n\n var curr25 = 0\n var curr50 = 0\n var break = false\n\n for(i <- 0 until n if !break) {\n if(input(i) == 25) {\n curr25 += 1\n } else if(input(i) == 50) {\n if(curr25 >= 1) {\n curr25 -= 1\n curr50 += 1\n } else {\n println(\"NO\")\n break = true\n }\n } else {\n if(curr50 >= 1 && curr25 >= 1) {\n curr50 -= 1\n curr25 -= 1\n } else if(curr25 >= 3) {\n curr25 -= 3\n } else {\n println(\"NO\")\n break = true\n }\n }\n }\n if(!break) {\n println(\"YES\")\n }\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P349A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val P = List.fill(N)(sc.nextInt)\n \n def solve(): String = {\n\n @tailrec\n def loop(r50: Int, r25: Int, line: List[Int]): String =\n line match {\n case Nil => \"YES\"\n case 25 :: xs => loop(r50, r25 + 1, xs)\n case 50 :: xs => if (r25 < 1) \"NO\"\n else loop(r50 + 1, r25 - 1, xs)\n case 100 :: xs => if (r50 < 1) {\n if (r25 < 3) \"NO\"\n else loop(r50, r25 - 3, xs)\n }\n else {\n if (r25 < 1) \"NO\"\n else loop(r50 - 1, r25 - 1, xs)\n }\n }\n\n loop(0, 0, P)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Codeforces extends App { \n val in = new Scanner(System.in)\n var a = 0\n var b = 0\n var res = \"YES\"\n val n = in.nextInt()\n for (i <- 0 until n) {\n val k = in.nextInt()\n if (k == 25) {\n a += 1\n }\n if (k == 50) {\n a -= 1\n b += 1\n }\n if (k == 100) {\n if (b != 0) {\n a -= 1\n b -= 1\n } else {\n a -= 3\n }\n }\n if (a < 0 || b < 0) {\n res = \"NO\"\n }\n }\n println(res)\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n in.next()\n val data = in.next().split(\" \").map(_.toInt).foldLeft((0, 0, true)) {\n case((s, m, false), el) => (s, m, false)\n case((s, m, true), 25) => (s + 1, m, true)\n case((s, m, true), 50) => (s - 1, m + 1, s >= 1)\n case((s, m, true), 100) if m > 1 => (s - 1, m - 1, s >= 1)\n case((s, m, true), 100) => (s - 3, m, s >= 3)\n }\n if (data._3)\n println(\"YES\")\n else\n println(\"NO\")\n}\n"}, {"source_code": "object A349 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n\n var curr = 0\n var break = false\n for(i <- 0 until n if !break) {\n if(input(i) == 25) {\n curr += 1\n } else if(input(i) == 50) {\n if(curr >= 1) {\n curr -= 1\n } else {\n println(\"NO\")\n break = true\n }\n } else {\n if(curr >= 2) {\n curr -= 2\n } else {\n println(\"NO\")\n break = true\n }\n }\n }\n if(!break) {\n println(\"YES\")\n }\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P349A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val P = List.fill(N)(sc.nextInt)\n \n def solve(): String = {\n\n @tailrec\n def loop(r50: Int, r25: Int, line: List[Int]): String =\n line match {\n case Nil => \"YES\"\n case 25 :: xs => loop(r50, r25 + 1, xs)\n case 50 :: xs => if (r25 < 1) \"NO\"\n else loop(r50 + 1, r25 - 1, xs)\n case 100 :: xs => if (r50 > 0) loop(r50 - 1, r25, 50 :: xs)\n else if (r25 < 3) \"NO\"\n else loop(r50, r25 -3, xs)\n }\n\n loop(0, 0, P)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P349A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val P = List.fill(N)(sc.nextInt)\n \n def solve(): String = {\n\n @tailrec\n def loop(r50: Int, r25: Int, line: List[Int]): String =\n line match {\n case Nil => \"YES\"\n case 25 :: xs => loop(r50, r25 + 1, xs)\n case 50 :: xs => if (r25 < 1) \"NO\"\n else loop(r50 + 1, r25 - 1, xs)\n case 100 :: xs => if (r50 > 0) loop(r50 - 1, r25, 50 :: xs)\n else if (r25 < 3) \"NO\"\n else loop(r50, r25 - 3, xs)\n }\n\n loop(0, 0, P)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Codeforces extends App { \n val in = new Scanner(System.in)\n var a = 0\n var b = 0\n var res = \"YES\"\n val n = in.nextInt()\n for (i <- 1 until n) {\n var k = in.nextInt()\n if (k == 25) {\n a += 1\n }\n if (k == 50) {\n a -= 1\n b += 1\n }\n if (k == 100) {\n if (b != 0) {\n a -= 1\n b -= 1\n } else {\n a -= 3\n }\n }\n if (a < 0 || b < 0) {\n res = \"NO\"\n }\n }\n println(res)\n}"}, {"source_code": "object Main {\n class Cash {\n private var n25, n50 = 0\n \n def add(n: Int) = n match {\n case 25 => n25 += 1; true\n case 50 => \n n50 += 1\n n25 -= 1\n n25 != -1\n case 100 =>\n if (n50 == 0) {\n n25 -= 3\n n25 >= 0\n } else {\n n50 -= 1\n n25 -= 1\n n25 != 1\n }\n }\n }\n\n def main(args: Array[String]) {\n val c = new Cash\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val r = a.foldLeft(true){ (r, n) => r & c.add(n) }\n if (r) println(\"YES\")\n else println(\"NO\")\n }\n}"}, {"source_code": "import scala.math._\nimport scala.Console\nobject Object {\n \n def main(args : Array[String]){\n \n var n = readInt\n var ar = readLine split \" \"\n var m = scala.collection.mutable.Map(\"25\" -> 0, \"50\" -> 0, \"100\" -> 0)\n var yesOrNo = \"YES\"\n \n for(i <- 0 until n){\n ar(i) match {\n case \"25\" => {m(\"25\") += 1}\n case \"50\" => {m(\"50\") += 1;if(m(\"25\") > 0)m(\"25\") -= 1 else yesOrNo = \"NO\"} \n case \"100\"=> {if(m(\"25\") > 0 && m(\"50\") > 0){m(\"25\") -= 1; m(\"50\") -= 1} else if(m(\"25\") > 1){m(\"25\") -= 2} else yesOrNo = \"NO\"}\n case _ => {}\n }\n }\n println(yesOrNo)\n }\n}"}, {"source_code": "import scala.math._\nimport scala.Console\nobject Object {\n \n def main(args : Array[String]){\n \n var n = readInt\n var ar = readLine split \" \"\n var m = scala.collection.mutable.Map(\"25\" -> 0, \"50\" -> 0, \"100\" -> 0)\n var yesOrNo = \"YES\"\n \n for(i <- 0 until n){\n ar(i) match {\n case \"25\" => {m(\"25\") += 1}\n case \"50\" => {m(\"50\") += 1;if(m(\"25\") > 0)m(\"25\") -= 1 else yesOrNo = \"NO\"} \n case \"100\"=> {if(m(\"25\") > 0 && m(\"50\") > 0){m(\"25\") -= 1; m(\"50\") -= 1} else if(m(\"25\") > 1){m(\"25\") -= 2} else yesOrNo = \"NO\"}\n case _ => {yesOrNo = \"NO\"}\n }\n }\n println(yesOrNo)\n }\n}"}, {"source_code": "import scala.math._\nimport scala.Console\nobject Object {\n \n def main(args : Array[String]){\n \n var n = readInt\n var ar = readLine split \" \"\n var m = scala.collection.mutable.Map(\"25\" -> 0, \"50\" -> 0, \"100\" -> 0)\n var yesOrNo = \"YES\"\n \n for(i <- 0 until n){\n ar(i) match {\n case \"25\" => {m(\"25\") += 1}\n case \"50\" => {m(\"50\") += 1;if(m(\"25\") > 0)m(\"25\") -= 1 else yesOrNo = \"NO\"} \n case \"100\"=> {if(m(\"25\") > 0 && m(\"50\") > 0){m(\"25\") -= 1; m(\"50\") -= 1} else if(m(\"25\") > 1){m(\"25\") -= 2} else yesOrNo = \"NO\"}\n case _ => {}\n }\n }\n println(m(\"25\") + \" \" + m(\"50\") + \" \" + m(\"100\"))\n println(yesOrNo)\n }\n}"}, {"source_code": "import scala.math._\nimport scala.Console\nobject Object {\n \n def main(args : Array[String]){\n \n var n = readInt\n var ar = readLine split \" \"\n var m = scala.collection.mutable.Map(\"25\" -> 0, \"50\" -> 0, \"100\" -> 0)\n var yesOrNo = \"YES\"\n \n for(i <- 0 until n){\n ar(i) match {\n case \"25\" => {m(\"25\") += 1}\n case \"50\" => {m(\"50\") += 1;if(m(\"25\") > 0)m(\"25\") -= 1 else yesOrNo = \"NO\"} \n case \"100\"=> {if(m(\"25\") > 0 && m(\"50\") > 0){m(\"25\") -= 1; m(\"50\") -= 1} else if(m(\"25\") > 2){m(\"25\") -= 1} else yesOrNo = \"NO\"}\n case _ => {}\n }\n }\n println(yesOrNo)\n }\n}"}, {"source_code": "import scala.math._\nimport scala.Console\nobject Object {\n \n def main(args : Array[String]){\n \n var n = readInt\n var ar = readLine split \" \"\n var m = scala.collection.mutable.Map(\"25\" -> 0, \"50\" -> 0, \"100\" -> 0)\n var yesOrNo = \"YES\"\n \n for(i <- 0 until n){\n ar(i) match {\n case \"25\" => {m(\"25\") += 1}\n case \"50\" => {m(\"50\") += 1;if(m(\"25\") > 0)m(\"25\") -= 1 else yesOrNo = \"NO\"} \n case \"100\"=> {if(m(\"25\") > 0 && m(\"50\") > 0){m(\"25\") -= 1; m(\"50\") -= 1} else if(m(\"25\") > 2){m(\"25\") -= 2} else yesOrNo = \"NO\"}\n case _ => {}\n }\n }\n println(yesOrNo)\n }\n}"}, {"source_code": "import scala.math._\nimport scala.Console\nobject Object {\n \n def main(args : Array[String]){\n \n var n = readInt\n var ar = readLine split \" \"\n var m = scala.collection.mutable.Map(\"25\" -> 0, \"50\" -> 0, \"100\" -> 0)\n var yesOrNo = \"YES\"\n \n for(i <- 0 until n){\n ar(i) match {\n case \"25\" => {m(\"25\") += 1}\n case \"50\" => {m(\"50\") += 1;if(m(\"25\") > 0)m(\"25\") -= 1 else yesOrNo = \"NO\"} \n case \"100\"=> {if(m(\"25\") > 0 && m(\"50\") > 0){m(\"25\") -= 1; m(\"50\") -= 1} else yesOrNo = \"NO\"}\n case _ => {}\n }\n }\n println(yesOrNo)\n }\n}"}], "src_uid": "63b20ab2993fddf2cc469c4c4e8027df"} {"source_code": "object Main extends App{\n\n\tval sc = new java.util.Scanner(System.in)\n\tval n = sc.nextInt\n\n\tcase class room(living: Int, accommodate: Int){\n\t\tval vacancy = accommodate - living\n\t\tval canMoveIn: Boolean = vacancy >= 2\n\t}\n\n\tval rooms = Array.fill(n)(room(sc.nextInt, sc.nextInt))\n\tval res = rooms.filter(_.canMoveIn == true)\n\tprintln(res.length)\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Accommodation {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val nums =\n for {\n _ <- 0 until n\n a :: b :: _ = readLine().split(\" \").map(_.toInt).toList\n } yield (a, b)\n val space = nums.map { case (a, b) => b - a }\n val ans = space.count(_ >= 2)\n println(ans)\n }\n}"}, {"source_code": "object CF0467A extends App {\n\n var n = readInt()\n var result = 0\n (1 to n ).foreach(n => {\n val Array(p, q) = readLine().split(\" \").map(_.toInt)\n if (q >= (p + 2)) {\n result += 1\n }\n })\n\n println(result)\n\n}\n"}, {"source_code": "object GandAcc {\n def main(args: Array[String]) {\n // println(\"Hello, world!\")\n val n = readLine().toInt\n var ctr = 0\n for (i <- 1 to n){\n var Array(p,q) = readLine().split(\" \").map(_.toLong)\n if (q - p >= 2)\n ctr+=1;\n }\n printf(\"%d\\n\", ctr)\n ctr = 0\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Task467A {\n\tdef main(args: Array[String]): Unit ={\n\t\tvar r = 0\n\t\tfor (_ <- 0 until StdIn.readInt()) {\n\t\t\tval in = StdIn.readf2(\"{0} {1}\")\n\t\t\tif (in._1.asInstanceOf[String].toInt + 1 < in._2.asInstanceOf[String].toInt)\n\t\t\t\tr += 1\n\t\t}\n\t\tprintln(r)\n\t}\n}\n"}, {"source_code": "object GandAcc {\n def main(args: Array[String]) {\n // println(\"Hello, world!\")\n val n = readLine().toInt\n var ctr = 0\n for (i <- 1 to n){\n \tvar Array(p,q) = readLine().split(\" \").map(_.toLong)\n \tif (q - p >= 2)\n \t\tctr+=1;\n }\n printf(\"%d\\n\", ctr)\n ctr = 0\n }\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 18.09.14.\n */\nobject A extends App {\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n var ans = 0\n for(i <- 0 until n) {\n val p = nextInt\n val q = nextInt\n if(q - p >= 2) {\n ans += 1\n }\n }\n out.print(ans)\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}"}, {"source_code": "object Main {\n\n def main(args: Array[String]) {\n val std = scala.io.StdIn\n\n val n = std.readLine().toInt\n var result = 0\n for (_ <- 0 until n) {\n val str = std.readLine().split(\" \").map(_.toInt)\n val p = str(0)\n val q = str(1)\n result += (if (q - p >= 2) 1 else 0)\n }\n print(result)\n }\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\nimport scala.util.Sorting._\n\nobject HelloWorld {\n def main(args: Array[String]) {\n\n val n = readLine.toInt\n\n var counter = 0\n for (i <- 0 until n) {\n val line = readLine.split(\" \")\n val p = line(0).toInt\n val q = line(1).toInt\n\n if (p + 2 <= q) counter+=1\n }\n\n println(counter)\n }\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\nimport scala.util.Sorting._\n\nobject HelloWorld {\n def main(args: Array[String]) {\n\n val n = readLine.toInt\n\n var counter = 0\n for (i <- 0 until n) {\n val pq = readLine.split(\" \").map(value => value.toInt)\n\n if (pq(0) + 2 <= pq(1)) counter+=1\n }\n\n println(counter)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by richard on 2015/6/10.\n */\nobject cf467a {\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n var c = 0\n for (i <- 0 until n) {\n val in = StdIn.readf2(\"{0} {1}\")\n if ( in._2.asInstanceOf[String].toInt - in._1.asInstanceOf[String].toInt > 1 ) {\n c+=1\n }\n }\n println(c)\n }\n}\n"}, {"source_code": "object A467 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = Array.fill(n)(readInts(2))\n\n println(input.map{arr => arr(1) - arr(0)}.count(_ > 1))\n }\n}"}, {"source_code": "\n/**\n * \n * \n * @author pvasilyev\n * @since 08 Apr 2016\n */\nobject Problem145 extends App {\n \n private val numberOfLines: Int = scala.io.StdIn.readInt()\n private var answer = 0\n for (i <- 0 until numberOfLines) {\n val Array(p, q) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n if (q - p >= 2) {\n answer += 1\n }\n }\n \n println(answer)\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 08 Apr 2016\n */\nobject Problem145 extends App {\n private val lines: Iterator[String] = scala.io.Source.stdin.getLines().takeWhile(s => s nonEmpty)\n val firstLine = lines.next()\n var answer = 0\n lines.foreach(line => {\n val strings: Array[String] = line.split(\" \")\n val first = strings(0).toInt\n val second = strings(1).toInt\n if (second - first >= 2) {\n answer += 1\n }\n })\n\n println(answer)\n}\n"}, {"source_code": "\n\nobject GeorgeAndAccommodation {\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in);\n\t\tval n = scanner.nextInt()\n\t\tvar counter = 0\n\t\tfor (i <- 1 to n) {\n\t\t val p = scanner.nextInt\n\t\t val q = scanner.nextInt\n\t\t counter += (if (q - p >= 2) 1 else 0)\n\t\t}\n\t\tprintln(counter)\n\t}\n}"}, {"source_code": "object Main extends App{\n val n = readLine().toInt\n var ctr = 0\n for (i <- 1 to n){\n \tvar Array(p,q) = readLine().split(\" \").map(_.toLong)\n \tif (q - p >= 2)\n \t\tctr+=1;\n }\n println(ctr)\n ctr = 0\n }\n"}, {"source_code": "object Codeforces467A extends App{\n\n def FindRoom(totalroom:Int):Int={\n var ans:Int=0\n for (i <- 0 until totalroom){\n var tempa=scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n if (tempa(0)+2 <= tempa(1)) ans+=1\n }\n return ans\n }\n val totalroom=scala.io.StdIn.readInt\n println(FindRoom(totalroom))\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A_467 extends App {\n val n = readInt()\n println(\n 1 to n count { _ =>\n val Array(a, b) = readLine().split(\" \").map(_.toInt)\n b - a >= 2\n }\n )\n}\n"}, {"source_code": "/**\n * @author unit7\n */\nobject Codeforces {\n def main(args: Array[String]) {\n val input = scala.io.Source.fromInputStream(System.in)\n val lines = input.getLines()\n val n = lines.next().toInt\n \n var answer = 0\n \n for (i <- 0 until n) {\n val pq = lines.next().split(' ')\n val p = pq(0).toInt\n val q = pq(1).toInt\n \n answer += (if (q - p >= 2) 1 else 0)\n }\n \n println(answer)\n }\n}"}, {"source_code": "import scala.io.StdIn.readLine\nobject problem {\n def main(args: Array[String]) {\n val n = readLine.toInt\n var cnt = 0\n for(i<-0 until n){\n val Array(a,b) = readLine.split(\" \").map(_.toInt)\n if( b - a >= 2) cnt += 1\n }\n println(cnt)\n }\n}\n"}, {"source_code": "import java.io.BufferedReader\n\nobject JuanDavidRobles467A {\n def main(args: Array[String]): Unit = {\n\n import java.util.Scanner\n import java.io.InputStreamReader\n\n val streamReader: InputStreamReader = new InputStreamReader(System.in)\n val scanner: Scanner = new Scanner(new BufferedReader(streamReader))\n\n val n: Int = Integer.parseInt(scanner.next())\n var capacity: Int = 0\n var people: Int = 0\n var count: Int = 0\n\n for (i <- 0 until n){\n people = Integer.parseInt(scanner.next())\n capacity = Integer.parseInt(scanner.next())\n if (capacity - people >= 2){\n count = count + 1\n }\n }\n\n println(count)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-19.\n */\nobject A467 extends App{\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n var i = 0\n var res = 0\n\n while (i < n) {\n val p, q = sc.nextInt()\n\n if (q - p >= 2) {\n res += 1\n }\n\n i += 1\n }\n\n println(res)\n}\n"}, {"source_code": "import java.util.Scanner\n\n\nobject HelloWorldMain {\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n var q : Int = 0\n var p : Int = 0\n\n var numberOfRooms : Int = 0\n for(i <- 1 to n ){\n p = sc.nextInt()\n q = sc.nextInt()\n if(q - p > 1) numberOfRooms +=1\n }\n println(numberOfRooms)\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\n\nobject George {\n def main(args: Array[String]) {\n val n = readInt\n val rooms = for {\n i <- 1 to n\n line = readLine.split(' ').map(_.toInt)\n } yield(line(0),line(1))\n println(rooms.count(x => x._2 - x._1 >= 2))\n }\n}"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n val n = StdIn.readLine().toInt\n var ans = 0\n var cur = 0\n for(i<-0 to n-1) {\n val Array(a,b) = StdIn.readLine().split(\" \").map(_.toInt)\n if(b - a >= 2)\n ans += 1\n }\n println(ans)\n }\n\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject TEST extends App{\n val sc = new Scanner(System.in)\n val n = sc.nextInt\n val d = List.fill(n)(-sc.nextInt+sc.nextInt())\n print(d.count(_>=2))\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Task extends App{\n val N = readLine.split(\" \") map {_.toInt} head\n val rooms = for(i <- 1 to N) yield {\n val Array(a,b) = readLine.split(\" \") map {_.toLong}\n (a,b)\n }\n\n val ans = rooms filter { case(a,b) => (a-b).abs > 1}\n \n println(ans.size)\n}"}], "negative_code": [{"source_code": "\n\nobject Main extends App{\nval n = readLine().toInt\n var ctr = 0\n for (i <- 1 to n){\n \tvar Array(p,q) = readLine().split(\" \").map(_.toLong)\n \tif (q - p >= 2)\n \t\tctr+=1;\n }\n println(\"%d\\n\", ctr)\n ctr = 0\n}"}], "src_uid": "2a6c457012f7ceb589b3dea6b889f7cb"} {"source_code": "object main extends App with fastIO {\n \n def tAVS(a: Double, v: Double, s: Double) = {\n val d = v * v + 2 * a * s\n (math.sqrt(d) - v) / a\n }\n \n def tsAVV(a: Double, v1: Double, v2: Double) = {\n val t = (v2 - v1) / a\n (t, (v1 + v2) * 0.5 * t)\n } \n\n val Array(a, v) = readLine split \" \" map {_ toDouble}\n val Array(l, d, w) = readLine split \" \" map {_ toDouble}\n \n val u = v min w\n val (t0v, s0v) = tsAVV(a, 0, v)\n val (t0u, s0u) = tsAVV(a, 0, u)\n val (tuv, suv) = tsAVV(a, u, v)\n val (t0vu, s0vu) = (t0v + tuv, s0v + suv)\n \n val t1 = d match {\n case s if (s < s0u) => tAVS(a, 0, s)\n case s if (s < s0vu) => t0u + tAVS(a, u, (s - s0u) * 0.5) * 2\n case s => t0vu + (s - s0vu) / v\n }\n \n val z = u min a * t1\n val (tzv, szv) = tsAVV(a, z, v)\n \n val t2 = l - d match {\n case s if (s < szv) => tAVS(a, z, s)\n case s => tzv + (s - szv) / v\n }\n \n print(t1 + t2 formatted \"%.15f\" replace (\",\", \".\")) \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject DRules extends App {\n\n val scanner = new Scanner(System.in)\n\n val a = scanner.nextInt().toDouble\n val maxV = scanner.nextInt().toDouble\n val distance = scanner.nextInt().toDouble\n val signDistance = scanner.nextInt().toDouble\n val limitV = scanner.nextInt().toDouble\n val rest = distance - signDistance\n\n val t1: Double = math.min(limitV, maxV) / a\n val s1: Double = a * (t1 * t1) / 2.0\n\n val t3 = (maxV - limitV) / a\n val s3 = limitV * t3 + (a * t3 * t3) / 2.0\n\n val t5 = maxV / a\n val s5 = a * t5 * t5 / 2\n\n val (timeUntilSign: Double, speedUntilSign: Double) =\n if (s1 > signDistance) {\n val t = math.sqrt(2.0 * signDistance / a)\n (t, t * a)\n }\n else if (s1 < signDistance) {\n if (maxV <= limitV) {\n (t1 + (signDistance - s1) / math.min(maxV, limitV), math.min(maxV, limitV))\n } else {\n if (s3 + s5 < signDistance) {\n (temp(), limitV)\n } else {\n (compute(), limitV)\n }\n }\n }\n else (t1, math.min(limitV, maxV))\n\n def compute(): Double = {\n val d = (signDistance - s1) / 2.0\n val t4 = (-2.0 * limitV + Math.sqrt(4.0 * Math.pow(limitV, 2.0) + 8.0 * a * d)) / (2.0 * a)\n t1 + t4 * 2.0\n }\n\n def temp(): Double = {\n t3 + t5 + (signDistance - s3 - s5) / maxV\n }\n\n val t2 = (maxV - speedUntilSign) / a\n val s2 = speedUntilSign * t2 + a * (t2 * t2) / 2.0\n\n val timeAfterSign: Double =\n if (t2 == 0.0) rest / maxV\n else if (s2 < rest) t2 + (rest - s2) / maxV\n else if (s2 > rest) (-2.0 * speedUntilSign + Math.sqrt(4.0 * Math.pow(speedUntilSign, 2.0) + 8.0 * a * rest)) / (2.0 * a)\n else t2\n\n\n println(timeAfterSign + timeUntilSign)\n\n /*\n4 120\n5112 3000 130\n\n\n 57.600000000000\n\n\n\n */\n\n}"}, {"source_code": "object main extends App with fastIO {\n \n def tAVS(a: Double, v: Double, s: Double) = {\n val d = v * v + 2 * a * s\n (math.sqrt(d) - v) / a\n }\n \n def tsAVV(a: Double, v1: Double, v2: Double) = {\n val t = (v2 - v1) / a\n (t, (v1 + v2) * 0.5 * t)\n } \n\n val Array(a, v) = readLine split \" \" map {_ toDouble}\n val Array(l, d, w) = readLine split \" \" map {_ toDouble}\n \n val u = v min w\n val (t0v, s0v) = tsAVV(a, 0, v)\n val (t0u, s0u) = tsAVV(a, 0, u)\n val (tuv, suv) = tsAVV(a, u, v)\n val (t0vu, s0vu) = (t0v + tuv, s0v + suv)\n \n val t1 = d match {\n case s if (s < s0u) => tAVS(a, 0, s)\n case s if (s < s0vu) => t0u + tAVS(a, u, (s - s0u) * 0.5) * 2\n case s => t0vu + (s - s0vu) / v\n }\n \n val z = u min a * t1\n val (tzv, szv) = tsAVV(a, z, v)\n \n val t2 = l - d match {\n case s if (s < szv) => tAVS(a, z, s)\n case s => tzv + (s - szv) / v\n }\n \n print(t1 + t2 formatted \"%.15f\" replace (\",\", \".\")) \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "object P5D {\n def tAVS(a : Double, v0 : Double, s : Double) = {\n val delta = v0 * v0 + a * s * 2\n (Math.sqrt(delta) - v0) / a\n }\n\n def tsAVV(a : Double, v0 : Double, v1 : Double) = {\n val t = (v1 - v0) / a\n (t, (v0 + v1) * 0.5 * t)\n }\n\n def main(args: Array[String]) {\n val Array(a, v) = readLine split \" \" map {_.toDouble}\n val Array(l, d, w) = readLine split \" \" map {_.toDouble}\n val u = v min w\n val (t0u, s0u) = tsAVV(a, 0, u)\n val (t0v, s0v) = tsAVV(a, 0, v)\n val (tuv, suv) = tsAVV(a, u, v)\n val (t0vu, s0vu) = (t0v + tuv, s0v + suv)\n val t1 = d match {\n case s if (s < s0u) => tAVS(a, 0, s)\n case s if (s < s0vu) => t0u + tAVS(a * 0.5, u, s - s0u)\n case s => t0vu + (s - s0vu) / v\n }\n val z = u min a * t1\n val (tzv, szv) = tsAVV(a, z, v)\n val t2 = l - d match {\n case s if (s < szv) => tAVS(a, z, s)\n case s => tzv + (s - szv) / v\n }\n println(t1 + t2 formatted \"%.5f\")\n }\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nobject DRules extends App {\n\n val scanner = new Scanner(System.in)\n\n val a = scanner.nextInt().toDouble\n val maxV = scanner.nextInt().toDouble\n val distance = scanner.nextInt().toDouble\n val signDistance = scanner.nextInt().toDouble\n val limitV = scanner.nextInt().toDouble\n val rest = distance - signDistance\n\n val t1: Double = math.min(limitV, maxV) / a\n val s1: Double = a * (t1 * t1) / 2.0\n\n val t3 = (maxV - limitV) / a\n val s3 = limitV * t3 + (a * t3 * t3) / 2\n\n val (timeUntilSign: Double, speedUntilSign: Double) =\n if (s1 > signDistance) {\n val t = math.sqrt(2.0 * signDistance / a)\n (t, t * a)\n }\n else if (s1 < signDistance) {\n if (maxV <= limitV) {\n (t1 + (signDistance - s1) / math.min(maxV, limitV), math.min(maxV, limitV))\n } else {\n (compute(), limitV)\n }\n }\n else (t1, math.min(limitV, maxV))\n\n def compute():Double = {\n val d = (signDistance - s1) / 2.0\n val t4 = (-2.0 * limitV + Math.sqrt(4.0 * Math.pow(limitV, 2.0) + 8.0 * a * d)) / (2.0 * a)\n t1 + t4 * 2.0\n }\n\n val t2 = (maxV - speedUntilSign) / a\n val s2 = speedUntilSign * t2 + a * (t2 * t2) / 2.0\n\n val timeAfterSign: Double =\n if (t2 == 0.0) maxV * rest\n else if (s2 < rest) t2 + (rest - s2) / maxV\n else if (s2 > rest) (-2.0 * speedUntilSign + Math.sqrt(4.0 * Math.pow(speedUntilSign, 2.0) + 8.0 * a * rest)) / (2.0 * a)\n else t2\n\n\n println(timeAfterSign + timeUntilSign)\n\n /*\n 20 40\n 10000 1 30\n\n */\n\n}"}, {"source_code": "import java.util.Scanner\n\nobject DRules extends App {\n\n val scanner = new Scanner(System.in)\n\n val a = scanner.nextInt().toDouble\n val maxV = scanner.nextInt().toDouble\n val distance = scanner.nextInt().toDouble\n val signDistance = scanner.nextInt().toDouble\n val limitV = scanner.nextInt().toDouble\n val rest = distance - signDistance\n\n val t1: Double = math.min(limitV, maxV) / a\n val s1: Double = a * (t1 * t1) / 2.0\n\n val t3 = (maxV - limitV) / a\n val s3 = limitV * t3 + (a * t3 * t3) / 2\n\n //сначала в любом случае разгон до math.min(limitV, maxV)\n\n val (timeUntilSign: Double, speedUntilSign: Double) =\n if (s1 > signDistance) {\n val t = math.sqrt(2.0 * signDistance / a)\n (t, t * a)\n }\n else if (s1 < signDistance) {\n if (maxV <= limitV) {\n (t1 + (signDistance - s1) / math.min(maxV, limitV), math.min(maxV, limitV))\n } else {\n (compute(), limitV)\n }\n }\n else (t1, math.min(limitV, maxV))\n\n def compute():Double = {\n val d = (signDistance - s1) / 2\n val t4 = (-2.0 * limitV + Math.sqrt(4.0 * Math.pow(limitV, 2.0) + 8.0 * a * d)) / (2.0 * a)\n t1 + t4 * 2\n }\n\n val t2 = (maxV - speedUntilSign) / a\n val s2 = a * (t2 * t2) / 2.0\n\n val timeAfterSign: Double =\n if (t2 == 0.0) maxV * rest\n else if (s2 < rest) t2 + (rest - s2) / maxV\n else if (s2 > rest) (-2.0 * speedUntilSign + Math.sqrt(4.0 * Math.pow(speedUntilSign, 2.0) + 8.0 * a * rest)) / (2.0 * a)\n else t2\n\n\n println(timeAfterSign + timeUntilSign)\n\n /*\n 5 70\n 200 170 40\n */\n\n}"}, {"source_code": "import java.util.Scanner\n\nobject DRules extends App {\n\n val scanner = new Scanner(System.in)\n\n val a = scanner.nextInt().toDouble\n val maxV = scanner.nextInt().toDouble\n val distance = scanner.nextInt().toDouble\n val signDistance = scanner.nextInt().toDouble\n val limitV = scanner.nextInt().toDouble\n val rest = (distance - signDistance).toDouble\n\n val t1: Double = math.min(limitV, maxV) / a\n\n val s: Double = a * (t1 * t1) / 2.0\n\n\n val (timeUntilSign: Double, speedUntilSign: Double) =\n if (s > signDistance) {\n val t = math.sqrt(2.0 * signDistance / a)\n (t, t * a)\n }\n else if (s < signDistance) (t1 + (signDistance - s) / math.min(maxV, limitV), math.min(maxV, limitV))\n else (t1, math.min(limitV, maxV))\n\n val t2 = (maxV - speedUntilSign) / a\n\n val s2 = a * (t2 * t2) / 2.0\n\n val timeAfterSign: Double =\n if (t2 == 0.0) maxV * rest\n else if (s2 < rest) t2 + (rest - s2) / maxV\n else if (s2 > rest) (-2.0 * speedUntilSign + math.sqrt(4.0 * math.pow(speedUntilSign, 2.0) + 8.0 * a * rest)) / (2.0 * a)\n else t2\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject DRules extends App {\n\n val scanner = new Scanner(System.in)\n\n val a = scanner.nextInt().toDouble\n val maxV = scanner.nextInt().toDouble\n val distance = scanner.nextInt().toDouble\n val signDistance = scanner.nextInt().toDouble\n val limitV = scanner.nextInt().toDouble\n val rest = distance - signDistance\n\n val t1: Double = math.min(limitV, maxV) / a\n val s1: Double = a * (t1 * t1) / 2.0\n\n val t3 = (maxV - limitV) / a\n val s3 = limitV * t3 + (a * t3 * t3) / 2.0\n\n val t5 = maxV / a\n val s5 = a * t5 * t5 / 2\n\n val (timeUntilSign: Double, speedUntilSign: Double) =\n if (s1 > signDistance) {\n val t = math.sqrt(2.0 * signDistance / a)\n (t, t * a)\n }\n else if (s1 < signDistance) {\n if (maxV <= limitV) {\n (t1 + (signDistance - s1) / math.min(maxV, limitV), math.min(maxV, limitV))\n } else {\n if (s3 + s5 < signDistance) {\n (temp(), limitV)\n } else {\n (compute(), limitV)\n }\n }\n }\n else (t1, math.min(limitV, maxV))\n\n def compute(): Double = {\n val d = (signDistance - s1) / 2.0\n val t4 = (-2.0 * limitV + Math.sqrt(4.0 * Math.pow(limitV, 2.0) + 8.0 * a * d)) / (2.0 * a)\n t1 + t4 * 2.0\n }\n\n def temp(): Double = {\n println(signDistance - s3 - s5)\n println(a * 5)\n println(s5)\n t3 + t5 + (signDistance - s3 - s5) / maxV\n }\n\n val t2 = (maxV - speedUntilSign) / a\n val s2 = speedUntilSign * t2 + a * (t2 * t2) / 2.0\n\n val timeAfterSign: Double =\n if (t2 == 0.0) maxV * rest\n else if (s2 < rest) t2 + (rest - s2) / maxV\n else if (s2 > rest) (-2.0 * speedUntilSign + Math.sqrt(4.0 * Math.pow(speedUntilSign, 2.0) + 8.0 * a * rest)) / (2.0 * a)\n else t2\n\n\n println(timeAfterSign + timeUntilSign)\n\n /*\n 20 40\n 10000 799 30\n\n 251.125000000000\n\n\n */\n\n}"}, {"source_code": "import java.util.Scanner\n\nobject DRules extends App {\n\n val scanner = new Scanner(System.in)\n\n val a = scanner.nextInt().toDouble\n val maxV = scanner.nextInt().toDouble\n val distance = scanner.nextInt().toDouble\n val signDistance = scanner.nextInt().toDouble\n val limitV = scanner.nextInt().toDouble\n val rest = distance - signDistance\n\n val t1: Double = math.min(limitV, maxV) / a\n val s1: Double = a * (t1 * t1) / 2.0\n\n val t3 = (maxV - limitV) / a\n val s3 = limitV * t3 + (a * t3 * t3) / 2.0\n\n val t5 = maxV / a\n val s5 = a * t5 * t5 / 2\n\n val (timeUntilSign: Double, speedUntilSign: Double) =\n if (s1 > signDistance) {\n val t = math.sqrt(2.0 * signDistance / a)\n (t, t * a)\n }\n else if (s1 < signDistance) {\n if (maxV <= limitV) {\n (t1 + (signDistance - s1) / math.min(maxV, limitV), math.min(maxV, limitV))\n } else {\n if (s3 + s5 < signDistance) {\n (temp(), limitV)\n } else {\n (compute(), limitV)\n }\n }\n }\n else (t1, math.min(limitV, maxV))\n\n def compute(): Double = {\n val d = (signDistance - s1) / 2.0\n val t4 = (-2.0 * limitV + Math.sqrt(4.0 * Math.pow(limitV, 2.0) + 8.0 * a * d)) / (2.0 * a)\n t1 + t4 * 2.0\n }\n\n def temp(): Double = {\n t3 + t5 + (signDistance - s3 - s5) / maxV\n }\n\n val t2 = (maxV - speedUntilSign) / a\n val s2 = speedUntilSign * t2 + a * (t2 * t2) / 2.0\n\n val timeAfterSign: Double =\n if (t2 == 0.0) maxV * rest\n else if (s2 < rest) t2 + (rest - s2) / maxV\n else if (s2 > rest) (-2.0 * speedUntilSign + Math.sqrt(4.0 * Math.pow(speedUntilSign, 2.0) + 8.0 * a * rest)) / (2.0 * a)\n else t2\n\n\n println(timeAfterSign + timeUntilSign)\n\n /*\n 20 40\n 10000 799 30\n\n 251.125000000000\n\n\n */\n\n}"}, {"source_code": "import java.util.Scanner\n\nobject DRules extends App {\n\n val scanner = new Scanner(System.in)\n\n val a = scanner.nextInt().toDouble\n val maxV = scanner.nextInt().toDouble\n val distance = scanner.nextInt().toDouble\n val signDistance = scanner.nextInt().toDouble\n val limitV = scanner.nextInt().toDouble\n val rest = (distance - signDistance).toDouble\n\n val t1: Double = math.min(limitV, maxV) / a\n\n val s: Double = a * (t1 * t1) / 2.0\n\n\n val (timeUntilSign: Double, speedUntilSign: Double) =\n if (s > signDistance) {\n val t = math.sqrt(2.0 * signDistance / a)\n (t, t * a)\n }\n else if (s < signDistance) (t1 + (signDistance - s) / math.min(maxV, limitV), math.min(maxV, limitV))\n else (t1, math.min(limitV, maxV))\n\n val t2 = (maxV - speedUntilSign) / a\n\n val s2 = a * (t2 * t2) / 2.0\n\n val timeAfterSign: Double =\n if (t2 == 0.0) maxV * rest\n else if (s2 < rest) t2 + (rest - s2) / maxV\n else if (s2 > rest) (-2.0 * speedUntilSign + math.sqrt(4.0 * math.pow(speedUntilSign, 2.0) + 8.0 * a * rest)) / (2.0 * a)\n else t2\n\n println(timeAfterSign + timeUntilSign)\n\n}\n"}, {"source_code": "object P5D {\n def tAVS(a : Double, v0 : Double, s : Double) = {\n val delta = v0 * v0 + a * s * 2\n (Math.sqrt(delta) - v0) / a\n }\n\n def tsAVV(a : Double, v0 : Double, v1 : Double) = {\n val t = (v1 - v0) / a\n (t, (v0 + v1) * 0.5 * t)\n }\n\n def main(args: Array[String]) {\n val Array(a, v) = readLine split \" \" map {_.toDouble}\n val Array(l, d, w) = readLine split \" \" map {_.toDouble}\n val u = v min w\n val (t0u, s0u) = tsAVV(a, 0, u)\n val (t0v, s0v) = tsAVV(a, 0, v)\n val (tuv, suv) = tsAVV(a, u, v)\n val (t0vu, s0vu) = (t0v + tuv, s0v + suv)\n val t1 = d match {\n case s if (s < s0u) => tAVS(a, 0, s)\n case s if (s < s0vu) => t0u + tAVS(a * 0.5, u, s - s0u)\n case s => t0vu + (s - s0vu) / v\n }\n val t2 = l - d match {\n case s if (s < suv) => tAVS(a, u, s)\n case s => tuv + (s - suv) / v\n }\n println(t1 + t2 formatted \"%.5f\")\n }\n}\n"}], "src_uid": "de8c909d6ca4f3b2f885fc60be246458"} {"source_code": "object Solver {\n def main(args: Array[String]) {\n Console.readLine\n var data = List.fromArray(Console.readLine.split(\" \").map(s => s.toInt))\n\n var summary = data.reduceRight((a, b) => a + b)\n println(data.count(x => x % 2 == summary % 2))\n }\n}\n", "positive_code": [{"source_code": "object CF0129A extends App {\n\n val n = readInt()\n\n val a = readLine().split(\" \").map(_.toInt).toList\n\n val sum = a.sum\n\n println(a.filter(value => (sum - value)%2 == 0).size)\n\n}\n"}, {"source_code": "import java.util.Scanner\nobject Cookies {\n\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt();\n val bags = (1 to n) map {i=>scanner.nextInt()}\n \n def main(args: Array[String]): Unit = {\n var count = (0/:(0 until n)) {(count, pos) =>\n if(((0/:(0 until n)){(sum,i)=> sum + (if (i!=pos) bags(i) else 0) })%2==0) count+1 else count\n }\n print(count)\n }\n\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _129A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt)\n val sum = a.sum\n val odd = a.count(i => i % 2 == 1)\n val even = a.length - odd\n if (sum % 2 == 0) println(even)\n else println(odd)\n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next()\n val data = in.next().split(\" \").map(_.toInt)\n val sum = data.sum\n println(data.count(t => (sum - t) % 2 == 0))\n\n\n}"}, {"source_code": "object A129 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n)\n val sum = in.sum\n var res = 0\n for(a <- in) {\n if((sum - a)%2 == 0)\n res += 1\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P129A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val bags = List.fill(N)(sc.nextInt)\n\n val answer: Int =\n if (bags.sum % 2 == 0) bags.filter(_ % 2 == 0).size\n else bags.filter(_ % 2 == 1).size\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n reader.readLine()\n val cookies = readInts\n val sum = cookies.sum\n def ans = cookies.count(x => (x + sum) % 2 == 0)\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val odd = a.sum % 2\n println(a.count(_ % 2 == odd))\n }\n}"}], "negative_code": [], "src_uid": "4c59b4d43b59c8659bf274f3e29d01fe"} {"source_code": "/**\n * Created by IntelliJ IDEA.\n * User: ymatsux\n * Date: 12/05/06\n * Time: 2:27\n * To change this template use File | Settings | File Templates.\n */\n\nimport java.util.Scanner\nimport scala.util.Sorting\n\nobject CF115C {\n def main(args: Array[String]): Unit = {\n (new CF115C).solve\n }\n}\n\nclass CF115C {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n\n val xs = new Array[(Long, Long)](n)\n for (i <- 0 until n) {\n xs(i) = (sc.nextLong(), sc.nextLong())\n }\n Sorting.stableSort(xs, (x: (Long, Long)) => x._2)\n\n val t = sc.nextInt()\n val ts = new Array[Long](t)\n for (i <- 0 until t) {\n ts(i) = sc.nextLong()\n }\n\n var xInd = 0\n var tInd = 0\n\n var defeated = 0L\n var score = 0L\n\n def factor: Int = tInd + 1\n\n def defeatEnemies(defeatNum: Long, incrementX: Boolean, incrementT: Boolean): Unit = {\n val (enemyNum, enemyPoint) = xs(xInd)\n score += defeatNum * enemyPoint * factor\n defeated += defeatNum\n xs(xInd) = (enemyNum - defeatNum, enemyPoint)\n if (incrementX) xInd += 1\n if (incrementT) tInd += 1\n }\n\n def solve: Unit = {\n while (xInd < xs.length) {\n val (enemyNum, enemyPoint) = xs(xInd)\n if (tInd >= ts.length) {\n defeatEnemies(enemyNum, true, false)\n } else {\n if (enemyNum < ts(tInd) - defeated) {\n defeatEnemies(enemyNum, true, false)\n } else if (enemyNum == ts(tInd) - defeated) {\n defeatEnemies(enemyNum, true, true)\n } else {\n defeatEnemies(ts(tInd) - defeated, false, true)\n }\n }\n }\n\n println(score)\n }\n}\n", "positive_code": [{"source_code": "/**\n * Created by IntelliJ IDEA.\n * User: ymatsux\n * Date: 12/05/06\n * Time: 2:27\n * To change this template use File | Settings | File Templates.\n */\n\nimport java.util.Scanner\nimport scala.util.Sorting\n\nobject CF115C {\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n // (number, point)\n val xs = new Array[(Long, Long)](n)\n for (i <- 0 until n) {\n xs(i) = (sc.nextLong(), sc.nextLong())\n }\n val t = sc.nextInt()\n val ts = new Array[Long](t)\n for (i <- 0 until t) {\n ts(i) = sc.nextLong()\n }\n\n Sorting.stableSort(xs, (x: (Long, Long)) => x._2)\n\n // println(xs.toList)\n\n var xInd = 0\n var tInd = 0\n var defeated = 0L\n var score = 0L\n while (xInd < xs.length) {\n val (enemyNum, enemyPoint) = xs(xInd)\n val factor = 1 + tInd\n if (tInd >= ts.length) {\n score += enemyNum * enemyPoint * factor\n defeated += enemyNum\n xs(xInd) = (0L, enemyPoint)\n xInd += 1\n } else {\n if (enemyNum < ts(tInd) - defeated) {\n score += enemyNum * enemyPoint * factor\n defeated += enemyNum\n xs(xInd) = (0L, enemyPoint)\n xInd += 1\n } else if (enemyNum == ts(tInd) - defeated) {\n score += enemyNum * enemyPoint * factor\n defeated += enemyNum\n xs(xInd) = (0L, enemyPoint)\n xInd += 1\n tInd += 1\n } else {\n val defeatNum = ts(tInd) - defeated\n score += defeatNum * enemyPoint * factor\n defeated += defeatNum\n xs(xInd) = (enemyNum - defeatNum, enemyPoint)\n tInd += 1\n }\n }\n }\n println(score)\n }\n}\n"}], "negative_code": [{"source_code": "/**\n * Created by IntelliJ IDEA.\n * User: ymatsux\n * Date: 12/05/06\n * Time: 2:27\n * To change this template use File | Settings | File Templates.\n */\n\nimport java.util.Scanner\nimport scala.util.Sorting\n\nobject CF115C {\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n // (number, point)\n val xs = new Array[(Long, Long)](n)\n for (i <- 0 until n) {\n xs(i) = (sc.nextLong(), sc.nextLong())\n }\n val t = sc.nextInt()\n val ts = new Array[Long](t)\n for (i <- 0 until t) {\n ts(i) = sc.nextLong()\n }\n\n Sorting.stableSort(xs, (x: (Long, Long)) => x._2)\n\n var xInd = 0\n var tInd = 0\n var score = 0L\n while (xInd < xs.length) {\n val (enemyNum, enemyPoint) = xs(xInd)\n val factor = 1 + tInd\n if (tInd >= ts.length) {\n score += enemyNum * enemyPoint * factor\n xs(xInd) = (0L, enemyPoint)\n xInd += 1\n } else {\n if (enemyNum < ts(tInd)) {\n score += enemyNum * enemyPoint * factor\n xs(xInd) = (0L, enemyPoint)\n ts(tInd) -= enemyNum\n xInd += 1\n } else if (enemyNum == ts(tInd)) {\n score += enemyNum * enemyPoint * factor\n xs(xInd) = (0L, enemyPoint)\n ts(tInd) = 0L\n xInd += 1\n tInd += 1\n } else {\n score += ts(tInd) * enemyPoint * factor\n xs(xInd) = (enemyNum - ts(tInd), enemyPoint)\n ts(tInd) = 0L\n tInd += 1\n }\n }\n }\n println(score)\n }\n}\n"}, {"source_code": "/**\n * Created by IntelliJ IDEA.\n * User: ymatsux\n * Date: 12/05/06\n * Time: 2:27\n * To change this template use File | Settings | File Templates.\n */\n\nimport java.util.Scanner\nimport scala.util.Sorting\n\nobject CF115C {\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n // (number, point)\n val xs = new Array[(Long, Long)](n)\n for (i <- 0 until n) {\n xs(i) = (sc.nextLong(), sc.nextLong())\n }\n val t = sc.nextInt()\n val ts = new Array[Long](t)\n for (i <- 0 until t) {\n ts(i) = sc.nextLong()\n }\n\n Sorting.stableSort(xs, (x: (Long, Long)) => x._2)\n\n // println(xs.toList)\n\n var xInd = 0\n var tInd = 0\n var defeated = 0L\n var score = 0L\n while (xInd < xs.length) {\n val (enemyNum, enemyPoint) = xs(xInd)\n val factor = 1 + tInd\n if (tInd >= ts.length) {\n score += enemyNum * enemyPoint * factor\n defeated += enemyNum\n xs(xInd) = (0L, enemyPoint)\n xInd += 1\n } else {\n if (enemyNum < ts(tInd) - defeated) {\n score += enemyNum * enemyPoint * factor\n defeated += enemyNum\n xs(xInd) = (0L, enemyPoint)\n xInd += 1\n } else if (enemyNum == ts(tInd) - defeated) {\n score += enemyNum * enemyPoint * factor\n defeated += enemyNum\n xs(xInd) = (0L, enemyPoint)\n xInd += 1\n tInd += 1\n } else {\n score += (ts(tInd) - defeated) * enemyPoint * factor\n defeated += enemyNum\n xs(xInd) = (enemyNum - (ts(tInd) - defeated), enemyPoint)\n tInd += 1\n }\n }\n }\n println(score)\n }\n}\n"}], "src_uid": "bfd7aabf195321249db8760c3cb6998d"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n var Array(k, a, b) = in.next().split(' ').map(_.toLong)\n val start = if (a % k == 0) a else if ((a / k) * k > a) (a / k) * k else ((a + k) / k) * k\n val end = if (b % k == 0) b else if (b / k * k < b) b / k * k else (b - k) / k * k\n println(if (end >= start) (end - start) / k + 1 else 0)\n}\n\n\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main extends App {\n def countDivisible(a: Long, k: Long) = {\n a / k\n }\n \n override def main(args: Array[String]) = {\n val tokens = StdIn.readLine().split(\" \").map(_.toLong)\n val (k, a, b) = (tokens(0), tokens(1), tokens(2))\n\n val total = (a,b) match {\n case (a, b) if (a == 0 && b == 0) => 1\n case (a, b) if (a == 0 && b > 0) => countDivisible(b, k) + 1\n case (a, b) if (a < 0 && b == 0) => countDivisible(-a, k) + 1\n case (a, b) if (a < 0 && b < 0) => countDivisible(-a, k) - countDivisible(-b - 1, k)\n case (a, b) if (a > 0 && b > 0) => countDivisible(b, k) - countDivisible(a - 1, k)\n case (a, b) if (a < 0 && b > 0) => countDivisible(b, k) + countDivisible(-a, k) + 1\n case _ => 0\n }\n println(total)\n } \n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(k, a, b) = in.next().split(' ').map(_.toLong)\n val start = if (a % k == 0) a else (a / k + 1) * k\n val end = if (b % k == 0) b else (b / k - 1) * k\n\n val full = if (end >= start) (end - start) / k + 1 else 0\n\n println(full)\n}\n\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(k, a, b) = in.next().split(' ').map(_.toLong)\n val ans = (b - a) / k + (if (a % k == 0) 1 else 0)\n println(ans)\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n var Array(k, a, b) = in.next().split(' ').map(_.toLong)\n if (a < 0) {\n a = -a\n b = -b\n }\n val start = if (a % k == 0) a else ((a + k) / k) * k\n val end = if (b % k == 0) b else b / k * k\n\n val full = if (end >= start) (end - start) / k + 1 else 0\n\n println(full)\n}\n\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n var Array(k, a, b) = in.next().split(' ').map(_.toLong)\n if (a < 0) {\n a = -a\n b = -b\n }\n val start = if (a % k == 0) a else ((a + k) / k) * k\n val end = if (b % k == 0) b else b / k * k\n\n println(start)\n println(end)\n\n val full = if (end >= start) (end - start) / k + 1 else 0\n\n println(full)\n}\n\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(k, a, b) = in.next().split(' ').map(_.toLong)\n val start = if (a % k == 0) a else (a / k + 1) * k\n val end = if (b % k == 0) b else b / k * k\n\n val full = if (end >= start) (end - start) / k + 1 else 0\n\n println(full)\n}\n\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(k, a, b) = in.next().split(' ').map(_.toLong)\n val ans = (b - a) / k + (if (b % k == 0) 1 else 0)\n println(ans)\n}\n\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n var Array(k, a, b) = in.next().split(' ').map(_.toLong)\n if (b < 0) {\n a = -a\n b = -b\n }\n val start = if (a % k == 0) a else ((a + k) / k) * k\n val end = if (b % k == 0) b else b / k * k\n\n val full = if (end >= start) (end - start) / k + 1 else 0\n\n println(full)\n}\n\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(k, a, b) = in.next().split(' ').map(_.toLong)\n val start = if (a % k == 0) a else ((a + k) / k) * k\n val end = if (b % k == 0) b else b / k * k\n\n val full = if (end >= start) (end - start) / k + 1 else 0\n\n println(full)\n}\n\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n var Array(k, a, b) = in.next().split(' ').map(_.toLong)\n val start = if (a % k == 0) a else if ((a / k) * k > a) (a / k) * k else ((a + k) / k) * k\n val end = if (b % k == 0) b else b / k * k\n\n// println(start)\n// println(end)\n\n val full = if (end >= start) (end - start) / k + 1 else 0\n\n println(full)\n}\n\n\n"}], "src_uid": "98de093d78f74273e0ac5c7886fb7a41"} {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P405B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n sc.nextLine\n val D = sc.nextLine.toList\n\n @tailrec\n def loop(acc: Int, left: Char, cont: Int, ds: List[Char]): Int = {\n left match {\n case 'L' =>\n ds match {\n case Nil => acc\n case 'R' :: rest => loop(acc, 'R', 0, rest)\n case '.' :: rest => loop(acc + 1, left, cont + 1, rest)\n case _ => -1000\n }\n case 'R' =>\n ds match {\n case Nil => acc\n case 'L' :: rest => loop(acc + (cont & 1), 'L', 0, rest)\n case '.' :: rest => loop(acc, left, cont + 1, rest)\n case _ => -2000\n }\n case '.' =>\n ds match {\n case Nil => cont\n case 'L' :: rest => loop(0, 'L', 0, rest)\n case 'R' :: rest => loop(cont, 'R', 0, rest)\n case '.' :: rest => loop(0, '.', cont + 1, rest)\n case _ => -3000\n }\n case _ => -4000\n }\n }\n\n loop(0, '.', 0, D)\n }\n\n out.println(solve)\n out.close\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val str = in.next()\n //.L.R...LR..L..\n\n val r = str.foldLeft((false, 0, 0)) {\n case((false, s, b), '.') => (false, s + 1, b)\n case((false, s, b), 'L') => (false, 0, b)\n case((false, s, b), 'R') => (true, 0, b + s)\n case((true, s, b), '.') => (true, s + 1, b)\n case((true, s, b), 'L') if s % 2 == 0 => (false, 0, b)\n case((true, s, b), 'L')=> (false, 0, b + 1)\n }\n\n if (r._1)\n println(r._3)\n else\n println(r._2 + r._3)\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val str = in.next()\n //.L.R...LR..L..\n val firstL = str.indexOf('L')\n val firstR = str.indexOf('R')\n val lastL = str.lastIndexOf('L')\n val lastR = str.lastIndexOf('R')\n val leftBound = if (firstR != -1 && firstR < firstL) firstR else 0\n val rightBound = if (lastL != -1 && lastL > lastR) n - lastL - 1 else 0\n val all = if (firstR == -1 && firstL == -1) n else 0\n val bound = leftBound + rightBound + all\n val r = str.foldLeft((-1, bound)) {\n case((-1, b), '.') => (-1, b)\n case((-1, b), el) => (0, b)\n case((d, b), '.') => (d + 1, b)\n case((d, b), el) if d % 2 == 0 => (0, b)\n case((d, b), el) => (0, b + 1)\n }\n\n println(r._2)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P405B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n sc.nextLine\n val D = sc.nextLine.toList\n\n @tailrec\n def loop(acc: Int, left: Char, cont: Int, ds: List[Char]): Int = {\n left match {\n case 'L' =>\n ds match {\n case Nil => acc\n case 'R' :: rest => loop(acc, 'R', 0, rest)\n case '.' :: rest => loop(acc + 1, left, cont + 1, rest)\n case _ => -1000\n }\n case 'R' =>\n ds match {\n case Nil => acc\n case 'L' :: rest =>\n val chance = if (cont == 0) 0\n else (cont & 1) ^ 1\n loop(acc + chance, 'L', 0, rest)\n case '.' :: rest => loop(acc, left, cont + 1, rest)\n case _ => -2000\n }\n case '.' =>\n ds match {\n case Nil => cont\n case 'L' :: rest => loop(0, 'L', 0, rest)\n case 'R' :: rest => loop(cont, 'R', 0, rest)\n case '.' :: rest => loop(0, '.', cont + 1, rest)\n }\n case _ => -4000\n }\n }\n\n loop(0, '.', 0, D)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P405B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n sc.nextLine\n val A = sc.nextLine.toArray\n\n @inline\n def isStanding(n: Int): Boolean = {\n val leftR = A.lastIndexOf('R', n)\n val leftL = A.lastIndexOf('L', n)\n val rightR = A.indexOf('R', n)\n val rightL = A.indexOf('L', n)\n\n val isNotPushed: Boolean = A(n) == '.'\n val lhs = leftR < 0 && leftL < 0\n val rhs = rightR < 0 && rightL < 0\n\n isNotPushed && {\n if (lhs) {\n rightR < rightL\n }\n else if (rhs) {\n leftR < leftL\n }\n else {\n (leftR < leftL) || (leftR + rightL == n * 2)\n }\n }\n }\n\n (0 until N).count(isStanding)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P405B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n sc.nextLine\n val A = sc.nextLine.toArray\n\n @inline\n def isStanding(n: Int): Boolean = {\n val leftR = A.lastIndexOf('R', n)\n val leftL = A.lastIndexOf('L', n)\n val rightR = A.indexOf('R', n)\n val rightL = A.indexOf('L', n)\n\n val isNotPushed: Boolean = A(n) == '.'\n val lhs = leftR < 0 && leftL < 0\n val rhs = rightR < 0 && rightL < 0\n\n isNotPushed && {\n if (lhs) {\n rightR < rightL || rightR < 0\n }\n else if (rhs) {\n leftR < leftL\n }\n else {\n (leftR < leftL) || (leftR + rightL == n * 2)\n }\n }\n }\n\n (0 until N).count(isStanding)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P405B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n sc.nextLine\n val D = sc.nextLine.toList\n\n @tailrec\n def loop(acc: Int, left: Char, cont: Int, ds: List[Char]): Int = {\n left match {\n case 'L' =>\n ds match {\n case Nil => acc\n case 'R' :: rest => loop(acc, 'R', 0, rest)\n case '.' :: rest => loop(acc + 1, left, cont + 1, rest)\n case _ => -1000\n }\n case 'R' =>\n ds match {\n case Nil => acc\n case 'L' :: rest =>\n val chance = (cont & 1) ^ 1\n loop(acc + chance, 'L', 0, rest)\n case '.' :: rest => loop(acc, left, cont + 1, rest)\n case _ => -2000\n }\n case '.' =>\n ds match {\n case Nil => cont\n case 'L' :: rest => loop(0, 'L', 0, rest)\n case 'R' :: rest => loop(cont, 'R', 0, rest)\n case '.' :: rest => loop(0, '.', cont + 1, rest)\n }\n case _ => -4000\n }\n }\n\n loop(0, '.', 0, D)\n }\n\n out.println(solve)\n out.close\n}\n"}], "src_uid": "54c748dd983b6a0ea1af1153d08f1c01"} {"source_code": "object A1257 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var t = readInt\n while (t > 0) {\n var Array(n, x, _a, _b) = readInts(4)\n var Array(a, b) = Array(_a, _b).sorted\n while (x > 0) {\n if (a > 1) {\n a -= 1\n } else if (b < n) {\n b += 1\n }\n x -= 1\n }\n\n out.println(b - a)\n t -= 1\n }\n\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val n, x, a, b = ni()\n val d = abs(a-b)\n val ans = min(n - 1, d + x)\n out.println(ans)\n }\n }\n}"}], "negative_code": [], "src_uid": "1fd2619aabf4557093a59da804fd0e7b"} {"source_code": "object CodeforcesRound655c {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val n = rl_int\n val a = rll_int\n val res = impl(trim(a))\n writer.println(res)\n }\n\n def trim(a: Array[Int]): Array[Int] = {\n val n = a.length\n var leftSortedCount = 0\n while (leftSortedCount < n && a(leftSortedCount) == leftSortedCount + 1) {\n leftSortedCount += 1\n }\n var rightSortedCount = 0\n while (rightSortedCount < n && a(n - 1 - rightSortedCount) == (n - rightSortedCount)) {\n rightSortedCount += 1\n }\n a.slice(leftSortedCount, n - rightSortedCount)\n }\n\n def impl(a: Array[Int]): Int = {\n val n = a.length\n val aSorted = a.sorted\n if (a sameElements aSorted) {\n 0\n } else {\n for (i <- 0 until n) {\n if (a(i) == aSorted(i)) {\n return 2\n }\n }\n 1\n }\n }\n\n def sqr(a: Long): Long = a * a\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n\n val t = readInt()\n 1 to t foreach { _ =>\n val n = readInt()\n val A = readLine().split(\" \").map(_.toInt)\n\n var rightMostMatched = 0\n var leftMostMatched = A.length - 1\n\n var atLeastOneNotMatched = false\n\n for (i <- A.indices) {\n if (A(i) != i + 1) {\n atLeastOneNotMatched = true\n if (i > rightMostMatched) rightMostMatched = i\n if (i < leftMostMatched) leftMostMatched = i\n }\n }\n\n if (!atLeastOneNotMatched) println(0)\n else {\n def containsMatched(): Boolean = {\n for (i <- leftMostMatched to rightMostMatched)\n if (A(i) == i + 1) return true\n\n false\n }\n\n if (containsMatched) println(2)\n else println(1)\n }\n\n }\n}\n"}], "negative_code": [{"source_code": "object CodeforcesRound655c {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val n = rl_int\n val a = rll_int\n val res = impl(n, a)\n writer.println(res)\n }\n\n def impl(n: Int, a: Array[Int]): Int = {\n val aSorted = a.sorted\n if (a sameElements aSorted) {\n 0\n } else {\n for (i <- 0 until n) {\n if (a(i) == aSorted(i)) {\n return 2\n }\n }\n 1\n }\n }\n\n def sqr(a: Long): Long = a * a\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n\n def matchingPrefix(A: Array[Int], start: Int = 0): Option[Int] = {\n var i = start\n while (i < A.length && A(i) == i + 1) i += 1\n if (i == start) None\n else Some(i - 1)\n }\n\n def allNonMatching(A: Array[Int], start: Int, end: Int): Boolean =\n start to end forall (i => A(i) != i + 1)\n\n val t = readInt()\n 1 to t foreach { _ =>\n val n = readInt()\n val A = readLine().split(\" \").map(_.toInt)\n\n if (allNonMatching(A, 0, n - 1)) println(1)\n else {\n val m = matchingPrefix(A)\n if (m.contains(n - 1)) println(0)\n else {\n m match {\n case Some(j) =>\n if (allNonMatching(A, j + 1, A.length - 1)) println(1)\n else println(2)\n case None =>\n var k = 0\n while (k < A.length && A(k) != k + 1) k += 1\n if (k == 0) println(2)\n else {\n val q = matchingPrefix(A, k)\n if (q.contains(n - 1)) println(1)\n else println(2)\n }\n }\n }\n }\n }\n}\n"}], "src_uid": "a98f67141b341152fcf20d803cbd5409"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Seg(l: Int, r: Int)\n\n def solve(): Unit = {\n val N, M = ni()\n val A = na(N)\n\n val S = Array.ofDim[Seg](M)\n REP(M) { i =>\n val l, r = ni() - 1\n S(i) = Seg(l, r)\n }\n\n val open, close = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())\n REP(M) { i =>\n open(S(i).l) += i\n close(S(i).r) += i\n }\n\n val applied = mutable.Set[Int]()\n\n var ms = 0\n def updateMin: Unit = {\n ms = A.min\n }\n\n def add(id: Int): Unit = {\n var l = S(id).l\n while(l <= S(id).r) {\n A(l) -= 1\n l += 1\n }\n applied += id\n }\n\n // 最初はsegmentが全部適用されている状態にする\n REP(M) { i =>\n add(i)\n }\n updateMin\n\n def remove(id: Int): Unit = {\n var l = S(id).l\n while(l <= S(id).r) {\n A(l) += 1\n l += 1\n }\n\n applied -= id\n }\n\n var best = 0\n var bestSet = Array[Int]()\n\n // 9 * 10^7 間に合うか?BITだとminとる操作がだめだったのでべた配列\n REP(N) { i =>\n val O = open(i)\n val C = close(i)\n\n // iが最大になったと仮定して、iが含まれるセグメントが選ばれることはない\n REP(O.length) { j =>\n val id = O(j)\n remove(id)\n }\n if (O.nonEmpty) updateMin\n\n val v = A(i) - ms\n if (v > best) {\n best = v\n bestSet = applied.toArray\n }\n\n REP(C.length) { j =>\n val id = C(j)\n add(id)\n }\n\n if (C.nonEmpty) updateMin\n }\n\n out.println(best)\n out.println(bestSet.length)\n out.println(bestSet.sorted.map(_+1).mkString(\" \"))\n }\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Seg(l: Int, r: Int)\n\n def solve(): Unit = {\n val N, M = ni()\n val A = na(N)\n\n val S = Array.ofDim[Seg](M)\n REP(M) { i =>\n val l, r = ni() - 1\n S(i) = Seg(l, r)\n }\n\n val open, close = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())\n REP(M) { i =>\n open(S(i).l) += i\n close(S(i).r) += i\n }\n\n val applied = mutable.Set[Int]()\n\n var ms = 0\n def updateMin: Unit = {\n ms = A.min\n }\n\n def add(id: Int): Unit = {\n var l = S(id).l\n while(l <= S(id).r) {\n A(l) -= 1\n l += 1\n }\n applied += id\n }\n\n // 最初はsegmentが全部適用されている状態にする\n REP(M) { i =>\n add(i)\n }\n updateMin\n\n def remove(id: Int): Unit = {\n var l = S(id).l\n while(l <= S(id).r) {\n A(l) += 1\n l += 1\n }\n\n applied -= id\n }\n\n var best = 0\n var bestSet = Array[Int]()\n\n // 9 * 10^7 間に合うか?BITだとminとる操作がだめだったのでべた配列\n REP(N) { i =>\n val O = open(i)\n val C = close(i)\n\n // iが最大になったと仮定して、iが含まれるセグメントが選ばれることはない\n REP(O.length) { j =>\n val id = O(j)\n remove(id)\n }\n if (O.nonEmpty) updateMin\n\n val v = A(i) - ms\n if (v > best) {\n best = v\n bestSet = applied.toArray\n }\n\n REP(C.length) { j =>\n val id = C(j)\n add(id)\n }\n\n if (C.nonEmpty) updateMin\n }\n\n out.println(best)\n out.println(bestSet.length)\n out.println(bestSet.sorted.map(_+1).mkString(\" \"))\n }\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object CF_535_3_E1 {\n// date: 30/01/2019\n\n type In = (Int, Int, Seq[Int], Seq[(Int, Int)])\n type Out = (Int, Int, Seq[Int])\n \n def solve(in: In): Out = {\n val (n, m, as, lrs) = in\n\n // Array of results where all relevant segs applied to one index\n val ress = new Array[Array[Int]](as.length)\n val segs = Array.fill[List[Int]](as.length)(Nil)\n\n //Apply all segs to array and find amin\n def reduce(a: Array[Int], s1: Int, s2: Int): Unit = for {\n i <- (s1 - 1) until s2\n } a(i) -= 1\n\n def isInSegment(i: Int, l: Int, r: Int) = (i+1) >= l && (i+1) <= r\n\n for (i <- as.indices) {\n val arr = as.toArray\n for {\n j <- lrs.indices\n (l, r) = lrs(j)\n if isInSegment(i, l , r)\n } {\n segs(i) = j :: segs(i)\n reduce(arr, l, r)\n }\n ress(i) = arr\n }\n\n val (maxDiff, maxDiffIdx) = ress.zipWithIndex.map{ case (res, i) => (res.max - res(i), i)}.maxBy(_._1)\n val segsUsed = segs(maxDiffIdx)\n\n (maxDiff, segsUsed.size, segsUsed.map(_+1))\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (\n i.int, i.int, {i.nextLine;\n i.intSeq },\n i.getLinesMap(j => (j.int, j.int)))\n def formatOut(out: Out): String = {\n val (d, q, cs)= out\n s\"$d\\n$q\\n${cs.mkString(\" \")}\"\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def getLinesMap[T](f: Input => T) = getLines.map(s => f(new Input(s)))\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n // `a` MUST be > 0. Incorrect otherwise.\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Seg(l: Int, r: Int)\n\n def solve(): Unit = {\n val N, M = ni()\n val A = na(N)\n val S = Array.ofDim[Seg](M)\n REP(M) { i =>\n val l, r = ni() - 1\n S(i) = Seg(l, r)\n }\n\n val open, close = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())\n REP(M) { i =>\n open(S(i).l) += i\n close(S(i).r) += i\n }\n\n val applied = mutable.Set[Int]()\n\n // 最初はsegmentが全部適用されている状態にする\n REP(M) { i =>\n add(i)\n }\n\n def add(id: Int): Unit = {\n var l = S(id).l\n while(l <= S(id).r) {\n A(l) -= 1\n l += 1\n }\n applied += id\n }\n\n def remove(id: Int): Unit = {\n var l = S(id).l\n while(l <= S(id).r) {\n A(l) += 1\n l += 1\n }\n\n applied -= id\n }\n\n var best = 0\n var bestSet = Array[Int]()\n\n // .minのコストが怖い\n def findMin(exclude: Int): Int = {\n var ms = 1e9.toInt\n REP(N) { i =>\n if (i != exclude) ms = min(ms, A(i))\n }\n ms\n }\n\n // 9 * 10^7 間に合うか?BITだとminとる操作がだめだったのでべた配列\n REP(N) { i =>\n val O = open(i)\n val C = close(i)\n\n // iが最大になったと仮定して、iが含まれるセグメントが選ばれることはない\n REP(O.length) { j =>\n val id = O(j)\n remove(id)\n }\n\n if (O.nonEmpty || C.nonEmpty) {\n val v = A(i) - findMin(i)\n if (v > best) {\n best = v\n bestSet = applied.toArray\n }\n }\n\n REP(C.length) { j =>\n val id = C(j)\n add(id)\n }\n }\n\n out.println(best)\n out.println(bestSet.length)\n out.println(bestSet.sorted.map(_+1).mkString(\" \"))\n }\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "2b1595ffe5d233f788c976e155fff26f"} {"source_code": "import java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\nimport java.util.HashMap\nimport scala.collection.mutable.Map\nimport scala.util.Sorting\nimport scala.util.Random\n\nobject C_336a { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.t9.trim.getBytes(\"ISO-8859-1\"))\n//// debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n val start = System.currentTimeMillis()\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n \n \n val pos = new Array[Int](n)\n val pow = new Array[Int](n)\n// val map = new HashMap[Int, Int]()\n val map = Map[Int, Int]()\n \n class Pre(val ps:Int, val pw:Int)\n \n var pres = new Array[Pre](n)\n for(i <- 0 until n) {\n val bLine = readLine()\n pres(i) = new Pre(bLine.int, bLine.int)\n }\n pres = pres.sortWith(_.ps < _.ps)\n \n val pointers = new Array[Int](1000001)\n var prevPos = 0;\n var itCounter = 0\n for(i <- 0 until n) {\n pos(i) = pres(i).ps\n pow(i) = pres(i).pw\n for (j <- prevPos until pos(i)) {\n pointers(j) = i -1\n itCounter += 1\n }\n prevPos = pos(i)\n }\n pointers(pos(n-1)) = n-1\n \n val func = new Array[Int](n)\n for (i <- 0 until n) {\n func(i) = 1 + getRest(i)\n }\n \n def getRest(ind:Int): Int = {\n var res = map.get(ind)\n// db(res+\"\")\n if (res.isDefined) { return res.get }\n \n val minCoord = pos(ind) - pow(ind)\n var curInd = -1\n if (minCoord > 0) curInd = pointers(minCoord-1)\n \n var res2 = 0\n if (curInd > -1) {\n \t res2 = 1 + getRest(curInd)\n } else {\n res2 = 0\n }\n \n map += ind -> res2\n return res2\n }\n \n var max = 0\n for(i <- 0 until n) {\n// db(\"-\" + func(i))\n if (func(i) > max) {\n max = func(i)\n }\n }\n println (n - max)\n \n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4\n1 9\n3 1\n6 1\n7 4\n\"\"\"\n\nval sa2 = \"\"\"\n7\n1 1\n2 1\n3 1\n4 1\n5 1\n6 1\n7 1\n\"\"\" \n\ndef t9 () = {\n val n = 100000\n val res = new StringBuilder(n + \"\\n\")\n val r = new Random(121)\n for (i <- 0 until n) {\n res.append(r.nextInt(1000001)).append(\" \").append(r.nextInt(1000001)).append(\"\\n\")\n }\n res.toString\n}\n\n} \n\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map(_ => in.next().split(' ').map(_.toInt))\n val max = data.maxBy(_.head).head\n val dp = Array.ofDim[Int](max + 1)\n data.foreach { case Array(a, b) => dp(a) = b }\n if (dp(0) != 0) dp(0) = 1\n (1 to max).foreach { i =>\n if (dp(i) == 0)\n dp(i) = dp(i - 1)\n else if (i - dp(i) <= 0)\n dp(i) = 1\n else\n dp(i) = 1 + dp(i - dp(i) - 1)\n }\n println(n - dp.max)\n}"}, {"source_code": "object A{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val n=nextInt\n val (a,b) = (for(i<-0 until n) yield(nextInt,nextInt)).sorted.unzip\n\n val ans=Array.ofDim[Int](n)\n var minNum=n\n for(i<-0 until n){\n \n \n if(a(i)-a(0)<=b(i)){\n ans(i)= i\n }else{\n var (l,r)=(0,i-1)\n var m=(l+r)/2\n while(r-l>1){\n \n if(a(i)-a(m)<=b(i)){\n r=m\n }else{\n l=m\n }\n m=(l+r)/2\n }\n if(a(i)-a(r)>b(i)){\n ans(i)=ans(r)+i-r-1\n }else{\n ans(i)=ans(l)+i-l-1\n }\n }\n \n val expNum=n-i-1+ans(i)\n if(expNum 0 && pos(curInd) >= minCoord) {\n// curInd -= 1;\n// }\n// if (minCoord > 0) {\n// db(\"compare \" + curInd + \" : \" + pointers(minCoord-1))\n// }\n var curInd = -1\n if (minCoord > 0) curInd = pointers(minCoord-1)\n \n var res2 = 0\n if (curInd > -1) {\n \t res2 = 1 + getRest(curInd)\n } else {\n res2 = 0\n }\n \n map += ind -> res2\n return res2\n }\n \n var max = 0\n for(i <- 0 until n) {\n// db(\"-\" + func(i))\n if (func(i) > max) {\n max = func(i)\n }\n }\n println (n - max)\n \n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4\n1 9\n3 1\n6 1\n7 4\n\"\"\"\n\nval sa2 = \"\"\"\n7\n1 1\n2 1\n3 1\n4 1\n5 1\n6 1\n7 1\n\"\"\" \n\ndef t9 () = {\n val n = 100000\n val res = new StringBuilder(n + \"\\n\")\n for (i <- 0 until n) {\n res.append(i).append(\" 5\\n\")\n }\n res.toString\n}\n\n} \n\n}\n"}], "src_uid": "bcd689387c9167c7d0d45d4ca3b0c4c7"} {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, m, k) = readInts(3)\n\n var cx, cy = 1\n\n val ts = Array.fill(k)(mutable.Buffer.empty[(Int, Int)])\n var used = 0\n\n for (t <- 0 until k - 1) {\n ts(t) += ((cx, cy))\n if (cx % 2 == 1) {\n if (cy == m) {\n ts(t) += ((cx + 1, cy))\n cy -= 1\n cx += 1\n } else if (cy == m - 1) {\n ts(t) += ((cx, cy + 1))\n cy += 1\n cx += 1\n } else {\n ts(t) += ((cx, cy + 1))\n cy += 2\n }\n } else {\n if (cy == 1) {\n ts(t) += ((cx + 1, cy))\n cy += 1\n cx += 1\n } else if (cy == 2) {\n ts(t) += ((cx, cy - 1))\n cy -= 1\n cx += 1\n } else {\n ts(t) += ((cx, cy - 1))\n cy -= 2\n }\n }\n used += 2\n }\n\n val t = k - 1\n while (used < n * m) {\n ts(t) += ((cx, cy))\n if (cx % 2 == 1) {\n if (cy == m) {\n cx += 1\n } else cy += 1\n } else {\n if (cy == 1) {\n cx += 1\n } else cy -= 1\n }\n used += 1\n }\n\n for (t <- ts) {\n println(t.size.toString + t.map{ case (x, y) => s\" $x $y\"}.mkString)\n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n val Array(n, m, k) = scala.io.Source.stdin.getLines().next().split(\" \").map(_.toInt)\n var i = 1\n var j = 1\n var result: List[Int] = List.empty[Int]\n\n while (j <= n) {\n result ::= j\n result ::= i\n if (j % 2 == 1) i += 1\n else i -= 1\n if (i == 0) {\n i = 1\n j += 1\n } else if (i > m) {\n i = m\n j += 1\n }\n }\n\n result = result.reverse\n Range(1, k).foreach {\n i =>\n val ans = result.take(4)\n result = result.drop(4)\n println(s\"2 ${ans.mkString(\" \")}\")\n }\n println(s\"${result.size / 2} ${result.mkString(\" \")}\")\n\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val Array(n, m, k) = scala.io.Source.stdin.getLines().next().split(\" \").map(_.toInt)\n var i = 1\n var j = 1\n var result: List[Int] = List.empty[Int]\n\n while (j <= n) {\n result ::= i\n result ::= j\n if (j % 2 == 1) i += 1\n else i -= 1\n if (i == 0) {\n i = 1\n j += 1\n } else if (i > m) {\n i = m\n j += 1\n }\n }\n\n Range(1, k + 1).foreach {\n i =>\n val ans = result.take(4)\n result = result.drop(4)\n println(s\"2 ${ans.mkString(\" \")}\")\n }\n println(s\"${result.size / 2} ${result.mkString(\" \")}\")\n\n}"}], "src_uid": "779e73c2f5eba950a20e6af9b53a643a"} {"source_code": "\nobject Main {\n def main(args: Array[String]) = {\n val s = Console.readLine()\n val n = s.length()\n val begin = new Array[Int](n)\n val end = new Array[Int](n)\n\n var i = 0\n\n while (i < n) {\n begin(i) += 1\n end(i) += 1\n var l = i - 1\n var r = i + 1\n while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) {\n begin(l) += 1\n end(r) += 1\n l -= 1\n r += 1\n }\n l = i\n r = i + 1\n while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) {\n begin(l) += 1\n end(r) += 1\n l -= 1;\n r += 1;\n }\n i += 1\n }\n\n var ans: Long = 0\n i = 0\n\n while (i < n) {\n var j = i + 1\n while (j < n){\n ans += (1: Long) * end(i) * begin(j)\n j += 1\n }\n i += 1\n }\n System.out.println(ans);\n\n }\n}", "positive_code": [{"source_code": " /*object Main {\n \n def ispal(s:String, l:Int, r:Int):Int =\n {\n if(r < l) \n return 0\n if ((0 to (r - l) / 2).count(i => s(l + i) == s(r - i)) == (r - l) / 2 + 1)\n return 1\n else\n return 0\n }\n\n def main(args: Array[String]) {\n \n val s = readLine\n //var m = new Array[Int](s.length * s.length).map(i => 0)\n //(0 until s.length)\n //val m = (0 until s.length).map(i => )\n var t = 0\n val m = (0 until s.length).map(l => {\n t = 0\n (0 until s.length).map(r => {\n t += ispal(s, l, r)\n t\n })\n })\n //val m2 = (0 until s.length).map(l => (0 until s.length).map(r => if(r == 0) m(l)(r) else m(l)(r)+m(l)(r-1)))\n\n println((0 until s.length - 1).map(l => (0 to l).map(m(_)(l)).sum * m(l + 1).last).sum)\n }\n} \n*/\n\nobject Main {\n\n def main(args: Array[String]) {\n \n val s = readLine\n val n = s.length\n\n var ma = new Array[Long](n).map(i => new Array[Long](n).map(j => 0))\n (0 until n).foreach(i => {\n var j = 0\n var m = List(i, n-1-i).min\n while(j <= m && s(i-j) == s(i+j)) {\n ma(i-j)(i+j) = 1\n j += 1\n }\n })\n \n (0 until n-1).foreach(i => {\n var j = 1\n var m = List(i+1, n-1-i).min\n while(j <= m && s(i-j+1) == s(i+j)) {\n ma(i-j+1)(i+j) = 1\n j += 1\n }\n })\n \n var ma2 = (0 until n).map(i => (0 until n).map(j => ma(j)(i)).sum).toArray\n (1 until n).foreach(i => ma2(i) += ma2(i-1))\n /*\n ma.foreach(l => {\n l.foreach(print)\n println\n })\n \n ma2.foreach(print)\n*/\n var t1: Long = 0\n (0 until n).foreach(i => {\n var t2: Long = 0\n (1 to i).foreach(j => {\n t2 += ma(j)(i) * ma2(j - 1)\n })\n t1 += t2\n })\n \n println(t1)\n \n //println((0 until n).map(i => (1 to i).map(j => ma(j)(i) * ma2(j - 1)).sum).sum)\n }\n}"}], "negative_code": [{"source_code": " /*object Main {\n \n def ispal(s:String, l:Int, r:Int):Int =\n {\n if(r < l) \n return 0\n if ((0 to (r - l) / 2).count(i => s(l + i) == s(r - i)) == (r - l) / 2 + 1)\n return 1\n else\n return 0\n }\n\n def main(args: Array[String]) {\n \n val s = readLine\n //var m = new Array[Int](s.length * s.length).map(i => 0)\n //(0 until s.length)\n //val m = (0 until s.length).map(i => )\n var t = 0\n val m = (0 until s.length).map(l => {\n t = 0\n (0 until s.length).map(r => {\n t += ispal(s, l, r)\n t\n })\n })\n //val m2 = (0 until s.length).map(l => (0 until s.length).map(r => if(r == 0) m(l)(r) else m(l)(r)+m(l)(r-1)))\n\n println((0 until s.length - 1).map(l => (0 to l).map(m(_)(l)).sum * m(l + 1).last).sum)\n }\n} \n*/\n\nobject Main {\n\n def main(args: Array[String]) {\n \n val s = readLine\n val n = s.length\n\n var ma = new Array[Int](n).map(i => new Array[Int](n).map(j => 0))\n (0 until n).foreach(i => {\n var j = 0\n var m = List(i, n-1-i).min\n while(j <= m && s(i-j) == s(i+j)) {\n ma(i-j)(i+j) = 1\n j += 1\n }\n })\n \n (0 until n-1).foreach(i => {\n var j = 1\n var m = List(i+1, n-1-i).min\n while(j <= m && s(i-j+1) == s(i+j)) {\n ma(i-j+1)(i+j) = 1\n j += 1\n }\n })\n \n var ma2 = (0 until n).map(i => (0 until n).map(j => ma(j)(i)).sum).toArray\n (1 until n).foreach(i => ma2(i) += ma2(i-1))\n /*\n ma.foreach(l => {\n l.foreach(print)\n println\n })\n \n ma2.foreach(print)\n*/\n println((0 until n).map(i => (1 to i).map(j => ma(j)(i) * ma2(j - 1)).sum).sum)\n }\n}"}, {"source_code": "\t/*object Main {\n\t\n\tdef ispal(s:String, l:Int, r:Int):Int =\n\t{\n\t\tif(r < l) \n\t\t\treturn 0\n\t\tif ((0 to (r - l) / 2).count(i => s(l + i) == s(r - i)) == (r - l) / 2 + 1)\n\t\t\treturn 1\n\t\telse\n\t\t\treturn 0\n\t}\n\n\tdef main(args: Array[String]) {\n\t\t\n\t\tval s = readLine\n\t\t//var m = new Array[Int](s.length * s.length).map(i => 0)\n\t\t//(0 until s.length)\n\t\t//val m = (0 until s.length).map(i => )\n\t\tvar t = 0\n\t\tval m = (0 until s.length).map(l => {\n\t\t\tt = 0\n\t\t\t(0 until s.length).map(r => {\n\t\t\t\tt += ispal(s, l, r)\n\t\t\t\tt\n\t\t\t})\n\t\t})\n\t\t//val m2 = (0 until s.length).map(l => (0 until s.length).map(r => if(r == 0) m(l)(r) else m(l)(r)+m(l)(r-1)))\n\n\t\tprintln((0 until s.length - 1).map(l => (0 to l).map(m(_)(l)).sum * m(l + 1).last).sum)\n\t}\n}\t\n*/\n\nobject Main {\n\n\tdef main(args: Array[String]) {\n\t\t\n\t\tval s = readLine\n\t\tval n = s.length\n\n\t\tvar ma = new Array[BigInt](n).map(i => new Array[BigInt](n).map(j => 0))\n\t\t(0 until n).foreach(i => {\n\t\t\tvar j = 0\n\t\t\tvar m = List(i, n-1-i).min\n\t\t\twhile(j <= m && s(i-j) == s(i+j)) {\n\t\t\t\tma(i-j)(i+j) = 1\n\t\t\t\tj += 1\n\t\t\t}\n\t\t})\n\t\t\n\t\t(0 until n-1).foreach(i => {\n\t\t\tvar j = 1\n\t\t\tvar m = List(i+1, n-1-i).min\n\t\t\twhile(j <= m && s(i-j+1) == s(i+j)) {\n\t\t\t\tma(i-j+1)(i+j) = 1\n\t\t\t\tj += 1\n\t\t\t}\n\t\t})\n\t\t\n\t\tvar ma2 = (0 until n).map(i => (0 until n).map(j => ma(j)(i)).sum).toArray\n\t\t(1 until n).foreach(i => ma2(i) += ma2(i-1))\n\t\t/*\n\t\tma.foreach(l => {\n\t\t\tl.foreach(print)\n\t\t\tprintln\n\t\t})\n\t\t\n\t\tma2.foreach(print)\n*/\n\t\tprintln((0 until n).map(i => (1 to i).map(j => ma(j)(i) * ma2(j - 1)).sum).sum)\n\t}\n}"}], "src_uid": "1708818cf66de9fa03439f608c897a90"} {"source_code": "/**\n *\n */\n\nobject P311B extends App {\n var ans = readLine().split(\" \");\n val size = readLine().toInt;\n var datas = readLine().split(\" \").reverse;\n var frac = Array(BigInt(datas(0)), BigInt(1));\n for (i <- 1 to size - 1) {\n frac = frac.reverse;\n frac(0) = frac(1) * BigInt(datas(i)) + frac(0);\n// frac.foreach(f => print(f + \" \"))\n// println;\n }\n // var g = gcd(frac(0), frac(1));\n\n // for (i <- 0 to frac.length - 1) {\n // frac.update(i, frac(i) / g);\n // }\n // frac.foreach(f => print(f + \" \"))\n // print(gcd(BigInt(\"565049485241691020\"),BigInt(\"228217260073568804\")))→答えが既約になってない!\n if (BigInt(ans(0)) * frac(1) == frac(0) * BigInt(ans(1))) {\n print(\"YES\")\n } else {\n print(\"NO\")\n }\n def gcd(_x: BigInt, _y: BigInt): BigInt = {\n var x = _x;\n var y = _y;\n do {\n var z = x % y;\n x = y;\n y = z;\n } while (y > 0)\n return x;\n }\n}", "positive_code": [{"source_code": "import scala.annotation.tailrec\nobject B {\n def main(args: Array[String]) {\n val pp = readLine.split(\" \").map(_.toLong).toList\n val p = pp(0)\n val q = pp(1)\n val n = readInt\n val aa = readLine.split(\" \").map(_.toLong).toList\n\n @tailrec\n def gcd(x: Long, y:Long): Long = {\n if( x < y ) gcd(y,x)\n else if( x % y == 0 ) y\n else gcd(y, x%y)\n }\n\n @tailrec\n def calc(l: List[Long], x: BigInt, y: BigInt): (BigInt, BigInt) = {\n //println((x,y))\n l match {\n case Nil => {\n val t = x.gcd(y)\n ( x / t, y / t)\n }\n case _ => {\n val next = l.last\n val nx = ( y * next ) + x\n val ny = y\n val t = nx.gcd(ny).toLong\n calc(l.init, ny/t, nx/t)\n }\n }\n }\n\n val (a, b) = calc(aa.init, 1, aa.last)\n val t = gcd(p, q)\n val np = p/t\n val nq = q/t\n //println(a, b)\n //println(np, nq)\n if( a == nq && b == np) println(\"YES\")\n else println(\"NO\")\n }\n}"}], "negative_code": [{"source_code": "/**\n *\n */\nobject P311B extends App {\n var ans = readLine().split(\" \");\n val size = readLine().toInt;\n var datas = readLine().split(\" \").reverse;\n var frac = Array(datas(0).toInt, 1);\n for (i <- Range(1, size)) {\n frac = frac.reverse;\n frac(0) = frac(1) * datas(i).toInt + 1;\n }\n var g = gcd(frac(0), frac(1));\n\n for (i <- 0 to frac.length - 1) {\n frac.update(i, frac(i) / g);\n }\n if (ans(0).toInt == frac(0) && ans(1).toInt == frac(1)) {\n print(\"YES\")\n } else {\n print(\"NO\")\n }\n def gcd(_x: Int, _y: Int): Int = {\n var x = _x;\n var y = _y;\n do {\n var z = x % y;\n x = y;\n y = z;\n } while (y > 0)\n return x;\n }\n}"}, {"source_code": "/**\n *\n */\nobject P311B extends App {\n var ans = readLine().split(\" \");\n val size = readLine().toInt;\n var datas = readLine().split(\" \").reverse;\n var frac = Array(datas(0).toLong, 1L);\n for (i <- 1 to size - 1) {\n frac = frac.reverse;\n frac(0) = frac(1) * datas(i).toLong + frac(0);\n // frac.foreach(f => print(f + \" \"))\n // println;\n }\n var g = gcd(frac(0), frac(1));\n\n for (i <- 0 to frac.length - 1) {\n frac.update(i, frac(i) / g);\n }\n // frac.foreach(f => print(f + \" \"))\n if (ans(0).toLong == frac(0) && ans(1).toLong == frac(1)) {\n print(\"YES\")\n } else {\n print(\"NO\")\n }\n def gcd(_x: Long, _y: Long): Long = {\n var x = _x;\n var y = _y;\n do {\n var z = x % y;\n x = y;\n y = z;\n } while (y > 0)\n return x;\n }\n}"}, {"source_code": "/**\n *\n */\n\nobject P311B extends App {\n var ans = readLine().split(\" \");\n val size = readLine().toInt;\n var datas = readLine().split(\" \").reverse;\n var frac = Array(BigInt(datas(0)), BigInt(1));\n for (i <- 1 to size - 1) {\n frac = frac.reverse;\n frac(0) = frac(1) * BigInt(datas(i)) + frac(0);\n frac.foreach(f => print(f + \" \"))\n println;\n }\n // var g = gcd(frac(0), frac(1));\n\n // for (i <- 0 to frac.length - 1) {\n // frac.update(i, frac(i) / g);\n // }\n // frac.foreach(f => print(f + \" \"))\n // print(gcd(BigInt(\"565049485241691020\"),BigInt(\"228217260073568804\")))→答えが既約になってない!\n if (BigInt(ans(0)) * frac(1) == frac(0) * BigInt(ans(1))) {\n print(\"YES\")\n } else {\n print(\"NO\")\n }\n def gcd(_x: BigInt, _y: BigInt): BigInt = {\n var x = _x;\n var y = _y;\n do {\n var z = x % y;\n x = y;\n y = z;\n } while (y > 0)\n return x;\n }\n}"}], "src_uid": "447ebe088a0a60a7a44a3fc76056bc65"} {"source_code": "import scala.io.StdIn._\n\nobject Brutality {\n def best(scores: IndexedSeq[Long], k: Int): Long = {\n scores.sorted.drop(scores.length - k).sum\n }\n def score(scores: IndexedSeq[Long], keys: IndexedSeq[Char], k: Int): Long = {\n var res = 0L\n var start = 0\n for (i <- scores.indices) {\n val len = i - start\n if (len > 0 && keys(i) != keys(i - 1)) {\n res += best(scores.slice(start, i), k)\n start = i\n }\n }\n res += best(scores.drop(start), k)\n res\n }\n\n def main(args: Array[String]): Unit = {\n val line1 = readLine().split(\"\\\\s\")\n val n = line1(0).toInt\n val k = line1(1).toInt\n val a = readLine().split(\"\\\\s\").map(_.toLong)\n val s = readLine()\n require(a.length == n)\n require(s.length == n)\n val res = Brutality.score(a, s, k)\n println(res)\n }\n\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val A = na(N)\n val S = ns(N)\n\n /**\n * [l, r]\n */\n def findMx(l: Int, r: Int): Long = {\n if (r - l + 1 <= K) {\n sumL(A.slice(l, r + 1))\n } else {\n val B = A.slice(l, r + 1)\n sort(B)\n sumL(B.takeRight(K))\n }\n }\n\n var ans = 0L\n var l, r = 0\n while(l < N) {\n while(r + 1 < N && S(l) == S(r + 1)) {\n r += 1\n }\n ans += findMx(l, r)\n\n l = r + 1\n }\n\n out.println(ans)\n }\n\n\n def sort(a: Array[Int]): Array[Int] = {\n val n = a.length\n REP(n) { i =>\n val j = scala.util.Random.nextInt(n - i) + i\n val tmp = a(i)\n a(i) = a(j)\n a(j) = tmp\n }\n Sorting.stableSort(a)\n a\n }\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "\n\nobject Main2 extends App {\n\n import java.io._\nimport java.util\nimport java.util.{Locale, StringTokenizer, TreeSet}\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n val k = in.nextInt\n\n val a = in.nextLine.split(' ').map(_.toInt)\n val pairs = a.zip(in.nextLine) :+ (0, '0')\n\n val cnt = new Array[Int](256)\n var prev: Char = 0\n var v = Vector[Long]()\n var ans = 0l\n\n for ((dmg, button) <- pairs) {\n if (button != prev) {\n ans += v.sortBy(-_).take(k).sum\n v = Vector()\n }\n v :+= dmg.toLong\n prev = button\n }\n\n out.println(ans)\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject Brutality {\n def best(scores: IndexedSeq[Int], k: Int): Long = {\n scores.sorted.drop(scores.length - k).sum\n }\n def score(scores: IndexedSeq[Int], keys: IndexedSeq[Char], k: Int): Long = {\n var res = 0L\n var start = 0\n for (i <- scores.indices) {\n val len = i - start\n if (len > 0 && keys(i) != keys(i - 1)) {\n res += best(scores.slice(start, i), k)\n start = i\n }\n }\n res += best(scores.drop(start), k)\n res\n }\n\n def main(args: Array[String]): Unit = {\n val line1 = readLine().split(\"\\\\s\")\n val n = line1(0).toInt\n val k = line1(1).toInt\n val a = readLine().split(\"\\\\s\").map(_.toInt)\n val s = readLine()\n require(a.length == n)\n require(s.length == n)\n val res = Brutality.score(a, s, k)\n println(res)\n }\n\n}\n"}, {"source_code": "object Main2 extends App {\n\n import java.io._\n import java.util\n import java.util.{Locale, StringTokenizer, TreeSet}\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n import scala.io.StdIn \n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n val k = in.nextInt\n\n val a = in.nextLine.split(' ').map(_.toInt)\n val pairs = a.zip(in.nextLine) :+ (0, '0')\n\n val cnt = new Array[Int](256)\n var prev: Char = 0\n var v = Vector[Int]()\n var ans = 0l\n\n for ((dmg, button) <- pairs) {\n if (button != prev) {\n ans += v.sortBy(-_).take(k).sum\n v = Vector()\n }\n v :+= dmg\n prev = button\n }\n\n out.println(ans)\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}"}], "src_uid": "aa3b5895046ed34e89d5fcc3264b3944"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, p, q) = in.next().split(' ').map(_.toInt)\n val str = in.next()\n val min = Math.min(p, q)\n val max = Math.max(p, q)\n val res = (0 to str.length / max).find{i =>\n val left = str.length - max * i\n left % min == 0\n }\n\n if (res.isEmpty)\n println(-1)\n else {\n val maxLength = max * res.get\n println(res.get + (str.length - maxLength) / min)\n println((str.take(maxLength).grouped(max).toList ::: str.drop(maxLength).grouped(min).toList).mkString(\"\\n\"))\n }\n}", "positive_code": [{"source_code": "import java.io.PrintWriter\nimport java.io.BufferedInputStream\nimport java.io.IOException\n\nimport java.util.Arrays;\nimport java.util.Comparator;\nimport java.util.InputMismatchException;\nimport java.util.Scanner\n\nimport scala.annotation.tailrec\n;\n\n/**\n * Created by Administrator on 2015/12/31.\n */\nobject Main {\n def main(args: Array[String]){\n val scan = new Scanner(System.in);\n val out: PrintWriter = new PrintWriter(System.out)\n val n = scan.nextInt\n val p = scan.nextInt\n val q = scan.nextInt\n val s = scan.next\n val (x,y) = Calpq(n,p,q,0)\n //println(s+\" \"+x+\" \"+y)\n if(x<0){\n out.println(-1)\n }else{\n out.println(x+y)\n for( i <- 1 to x){\n out.println(s.substring(p*(i-1),p*i))\n }\n val k = p*x\n for( i <- 1 to y){\n out.println(s.substring(k+q*(i-1),k+q*i))\n }\n }\n \n out.close()\n }\n\n @tailrec\n def Calpq(n: Int,p: Int,q: Int,pn:Int): (Int,Int) = {\n val k = n - p*pn\n if(k<0){\n (-1,-1)\n }\n else if(k%q==0){\n (pn,k/q)\n }else{\n Calpq(n,p,q,pn+1)\n }\n }\n}"}, {"source_code": "object Solution extends App {\nval npq = Console.readLine.split(' ')\nval n = npq(0) toInt\nval p = npq(1) toInt\nval q = npq(2) toInt\nvar s = Console.readLine\n\nvar requiredp = 0\nvar requiredq = 0\nif ((n % p) == 0) {\n requiredp = n / p\n} else if ((n % q) == 0) {\n requiredq = n / q\n} else {\nimport scala.util.control.Breaks._\nbreakable {\n\nwhile ((requiredp * p) < n) {\n val right = n - (requiredp * p)\n if ((right % q) == 0) {\n requiredq = right / q\n break\n }\n requiredp = requiredp + 1;\n}\n\n}\n}\n\nval isSolution = n == (requiredp * p + requiredq * q)\nif (!isSolution)\n println(-1)\nelse {\n println(requiredp + requiredq)\n\n for (i <- 1 to requiredp) {\n println(s take p)\n s = s drop p\n }\n for (i <- 1 to requiredq) {\n println(s take q)\n s = s drop q\n }\n}\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\nval npq = Console.readLine.split(' ')\nval n = npq(0) toInt\nval p = npq(1) toInt\nval q = npq(2) toInt\nvar s = Console.readLine\n\nvar requiredp = 0\nvar requiredq = 0\nif ((n % p) == 0) {\n requiredp = n / p\n} else if ((n % q) == 0) {\n requiredq = n / q\n} else {\nimport scala.util.control.Breaks._\nbreakable {\n\nwhile ((requiredp * p) < n) {\n val right = n - (requiredp * p)\n if ((right % q) == 0) {\n requiredq = right / q\n break\n }\n requiredp = requiredp + 1;\n}\n\n}\n}\n\nprintln(\"debug\", requiredp, requiredq)\n\nval isSolution = n == (requiredp * p + requiredq * q)\nif (!isSolution)\n println(-1)\nelse {\n println(requiredp + requiredq)\n\n for (i <- 1 to requiredp) {\n println(s take p)\n s = s drop p\n }\n for (i <- 1 to requiredq) {\n println(s take q)\n s = s drop q\n }\n}\n}\n"}], "src_uid": "c4da69789d875853beb4f92147825ebf"} {"source_code": "import java.io.PrintWriter\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Main {\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n val MAX = 100111\n val tree = new Array[Int](MAX<<2)\n val prop = new Array[Int](MAX<<2)\n val tree2 = new Array[Int](MAX<<2)\n var out = new PrintWriter(System.out)\n var st = new StringTokenizer(br.readLine())\n\n def nextDouble = next.toDouble\n\n def next = {\n while (!st.hasMoreTokens)\n st = new StringTokenizer(br.readLine())\n st.nextToken()\n }\n\n def nextLong = next.toLong\n\n def nextInt = next.toInt\n\n def or(x: Int, tl: Int, tr: Int, l: Int, r: Int, mask: Int): Unit = {\n\n if (prop(x) != 0) {\n tree(x) |= prop(x)\n if (tl != tr) {\n prop(x+x) |= prop(x)\n prop(x+x+1) |= prop(x)\n }\n prop(x) = 0\n }\n\n if (tl > tr || tl > r || tr < l)\n return\n if (tl >= l && tr <= r) {\n tree(x) |= mask\n if (tl!=tr) {\n prop(x+x) |= mask\n prop(x+x+1) |= mask\n }\n return\n }\n\n or(x+x, tl, (tl+tr)>>1, l, r, mask)\n or(x+x+1, ((tl+tr)>>1)+1, tr, l, r, mask)\n\n tree(x) = tree(x+x) | tree(x+x+1)\n }\n\n def get(x: Int, tl: Int, tr: Int, l: Int, r: Int): Int = {\n if (tl > tr || tl > r || tr < l) return 0\n\n if (prop(x) != 0) {\n tree(x) |= prop(x)\n if (tl != tr) {\n prop(x+x) |= prop(x)\n prop(x+x+1) |= prop(x)\n }\n prop(x) = 0\n }\n\n if (tl >= l && tr <= r) return tree(x)\n\n val q1 = get(x+x, tl, (tl+tr)>>1, l, r)\n val q2 = get(x+x+1, ((tl+tr)>>1)+1, tr, l, r)\n q1 | q2\n }\n\n def build(x: Int, tl: Int, tr: Int, a: Array[Int]): Unit = {\n if (tl > tr) return\n if (tl == tr) {\n tree2(x) = a(tl)\n return\n }\n build(x+x,tl,(tl+tr)>>1, a)\n build(x+x+1,((tl+tr)>>1)+1,tr, a)\n tree2(x) = tree2(x+x) & tree2(x+x+1)\n }\n\n def get2(x: Int, tl: Int, tr: Int, l: Int, r: Int): Int = {\n if (tl > tr || tl > r || tr < l) return 0x7fffffff\n if (tl >= l && tr <= r) return tree2(x)\n val q1 = get2(x+x, tl, (tl+tr)>>1, l, r)\n val q2 = get2(x+x+1, ((tl+tr)>>1)+1, tr, l, r)\n q1 & q2\n }\n\n def main(args: Array[String]) {\n val n = nextInt\n val m = nextInt\n\n val l = new Array[Int](m+1)\n val r = new Array[Int](m+1)\n val q = new Array[Int](m+1)\n\n for (i <- 1 to m) {\n l(i) = nextInt\n r(i) = nextInt\n q(i) = nextInt\n }\n\n// val n = 100\n// val m = 5\n//\n// val l = new Array[Int](m+1)\n// val r = new Array[Int](m+1)\n// val q = new Array[Int](m+1)\n//\n// val rand = new Random(System.currentTimeMillis())\n// for (i <- 1 to m) {\n// l(i) = 1 + rand.nextInt(n)\n// r(i) = 1 + rand.nextInt(n)\n// if (l(i) > r(i)) {\n// val tmp = l(i)\n// l(i) = r(i)\n// r(i) = tmp\n// }\n// q(i) = rand.nextInt()\n// }\n//\n// /* correct answer */\n// val correct = new Array[Int](n+1)\n// for (i <- 1 to m) {\n// for (j <- l(i) to r(i))\n// correct(j) |= q(i)\n// }\n// var ans = true\n// for (i <- 1 to m) {\n// var mask = 0x7fffffff\n// for (j <- l(i) to r(i))\n// mask &= correct(j)\n// if (mask != q(i)) {\n// ans = false\n// }\n// }\n// out.println(\"CORRECT ANSWER: \" + (if (ans) \"YES\" else \"NO\"))\n// /* end correct answer */\n\n for (i <- 1 to m)\n or(1,1,n,l(i),r(i),q(i))\n\n val a = new Array[Int](n+1)\n for (i <- 1 to n)\n a(i) = get(1,1,n,i,i)\n\n build(1,1,n,a)\n\n for (i <- 1 to m)\n if (get2(1,1,n,l(i),r(i)) != q(i)) {\n out.println(\"NO\")\n out.close()\n return\n }\n\n out.println(\"YES\")\n for (i <- 1 to n)\n out.print(a(i)+\" \")\n out.close()\n }\n\n}\n\n\n", "positive_code": [{"source_code": "import scala.collection._\n\nobject B extends App {\n\n case class SegTree(as: Array[Int]) {\n\n val n = as.length\n val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))\n build(1, 0, n - 1)\n//println(t.mkString(\" \"))\n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n build(v2, tl, tm)\n build(v2 + 1, tm + 1, tr)\n t(v) = t(v2) & t(v2 + 1)\n }\n }\n\n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n //println(l, r, v, tl, tr)\n if (l > r) Int.MaxValue\n else if (l == tl && r == tr) t(v)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n //println(query(l, Math.min(r, tm), v2, tl, tm), query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr))\n query(l, Math.min(r, tm), v2, tl, tm) &\n query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)\n }\n }\n\n def update(pos: Int, delta: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n if (tl == tr) t(v) += delta\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n if (pos <= tm) update(pos, delta, v2, tl, tm)\n else update(pos, delta, v2 + 1, tm + 1, tr)\n t(v) = t(v2) + t(v2 + 1)\n }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n case class Q(l: Int, r: Int, q: Int)\n\n val qs = Array.ofDim[Q](m)\n\n for (i <- 0 until m) {\n val Array(l, r, q) = readInts(3)\n qs(i) = Q(l - 1, r - 1, q)\n }\n\n //val sorted = qs.sortBy(_.l)\n\n val xs = Array.fill(n) { 0 }\n\n val bits = Array.fill(31) { 0 }\n\n val qByL = new mutable.PriorityQueue[Q]()(Ordering.by(- _.l))\n qByL ++= qs\n\n val qByR = new mutable.PriorityQueue[Q]()(Ordering.by(- _.r))\n\n var pos = 0\n for (i <- 0 until n) {\n while (qByR.nonEmpty && qByR.head.r < i) {\n val qr = qByR.dequeue\n //println(qr)\n for (b <- 0 to 30) {\n if ((qr.q & (1 << b)) > 0) bits(b) -= 1\n }\n }\n while (qByL.nonEmpty && qByL.head.l == i) {\n val ql = qByL.dequeue\n for (b <- 0 to 30) {\n if ((ql.q & (1 << b)) > 0) {\n bits(b) += 1\n }\n }\n qByR += ql\n }\n //println(bits.mkString(\" \"))\n for (b <- 0 to 30) {\n if (bits(b) < 0) fail(1)\n else if (bits(b) > 0) xs(i) |= (1 << b)\n }\n }\n\n val segTree = SegTree(xs)\n //println(xs.mkString(\" \"))\n for (q <- qs) {\n //println(q, segTree.query(q.l, q.r))\n if (segTree.query(q.l, q.r) != q.q) fail(2)\n }\n \n println(\"YES\")\n println(xs.mkString(\" \"))\n\n def fail(x: Int) = {\n println(\"NO\")\n System.exit(0)\n }\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Main {\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n var out = new PrintWriter(System.out)\n var st = new StringTokenizer(br.readLine())\n\n def next = {\n while (!st.hasMoreTokens)\n st = new StringTokenizer(br.readLine())\n st.nextToken()\n }\n\n def nextDouble = next.toDouble\n def nextLong = next.toLong\n def nextInt = next.toInt\n\n class SegmentTree(n: Int, op: (Int, Int) => Int, identityValue: Int = 0, nullValue: Int = 0, a: Array[Int] = null) {\n\n val tree = new Array[Int](n<<2)\n val prop = new Array[Int](n<<2)\n\n if (a != null) build(1,1,n)\n\n def build(x: Int, tl: Int, tr: Int): Unit = {\n if (tl > tr) return\n if (tl == tr) {\n tree(x) = a(tl)\n return\n }\n build(x+x,tl,(tl+tr)>>1)\n build(x+x+1,((tl+tr)>>1)+1,tr)\n tree(x) = op(tree(x+x), tree(x+x+1))\n }\n\n def push(x: Int, tl: Int, tr: Int) = {\n if (prop(x) != nullValue) {\n tree(x) = op(tree(x), prop(x))\n if (tl != tr) {\n prop(x+x) = op(prop(x+x), prop(x))\n prop(x+x+1) = op(prop(x+x+1), prop(x))\n }\n prop(x) = nullValue\n }\n }\n\n def getInternal(x: Int, tl: Int, tr: Int, l: Int, r: Int): Int = {\n if (tl > tr || tl > r || tr < l) return identityValue\n push(x, tl, tr)\n if (tl >= l && tr <= r) return tree(x)\n val q1 = getInternal(x+x, tl, (tl+tr)>>1, l, r)\n val q2 = getInternal(x+x+1, ((tl+tr)>>1)+1, tr, l, r)\n op(q1,q2)\n }\n\n def setInternal(x: Int, tl: Int, tr: Int, l: Int, r: Int, z: Int): Unit = {\n push(x, tl, tr)\n if (tl > tr || tl > r || tr < l) return\n if (tl >= l && tr <= r) {\n tree(x) = op(tree(x), z)\n if (tl != tr) {\n prop(x+x) = op(prop(x+x), z)\n prop(x+x+1) = op(prop(x+x+1), z)\n }\n return\n }\n setInternal(x+x, tl, (tl+tr)>>1, l, r, z)\n setInternal(x+x+1, ((tl+tr)>>1)+1, tr, l, r, z)\n tree(x) = op(tree(x+x), tree(x+x+1))\n }\n\n def getModifiedArray = {\n val ret = new Array[Int](n+1)\n for (i <- 1 to n)\n ret(i) = getInternal(1,1,n,i,i)\n ret\n }\n\n def get(l: Int, r: Int) = getInternal(1,1,n,l,r)\n def set(l: Int, r: Int, z: Int) = setInternal(1,1,n,l,r,z)\n\n }\n\n def main(args: Array[String]) {\n val n = nextInt\n val m = nextInt\n\n val l = new Array[Int](m+1)\n val r = new Array[Int](m+1)\n val q = new Array[Int](m+1)\n\n for (i <- 1 to m) {\n l(i) = nextInt\n r(i) = nextInt\n q(i) = nextInt\n }\n\n val stOr = new SegmentTree(n, (a,b) => a|b)\n\n for (i <- 1 to m)\n stOr.set(l(i),r(i),q(i))\n\n val a = stOr.getModifiedArray\n val stAnd = new SegmentTree(n, (a,b) => a&b, 0x7fffffff, 0, a)\n\n for (i <- 1 to m)\n if (stAnd.get(l(i),r(i)) != q(i)) {\n out.println(\"NO\")\n out.close()\n return\n }\n\n out.println(\"YES\")\n for (i <- 1 to n)\n out.print(a(i)+\" \")\n out.close()\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.io.PrintWriter\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Main {\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n val MAX = 100111\n val tree = new Array[Int](MAX<<2)\n val prop = new Array[Int](MAX<<2)\n val tree2 = new Array[Int](MAX<<2)\n var out = new PrintWriter(System.out)\n var st = new StringTokenizer(br.readLine())\n\n def nextDouble = next.toDouble\n\n def next = {\n while (!st.hasMoreTokens)\n st = new StringTokenizer(br.readLine())\n st.nextToken()\n }\n\n def nextLong = next.toLong\n\n def nextInt = next.toInt\n\n def or(x: Int, tl: Int, tr: Int, l: Int, r: Int, mask: Int): Unit = {\n\n if (prop(x) != 0) {\n tree(x) |= prop(x)\n if (tl != tr) {\n prop(x+x) |= prop(x)\n prop(x+x+1) |= prop(x)\n }\n prop(x) = 0\n }\n\n if (tl > tr || tl > r || tr < l)\n return\n if (tl >= l && tr <= r) {\n tree(x) |= mask\n if (tl!=tr) {\n prop(x+x) |= mask\n prop(x+x+1) |= mask\n }\n return\n }\n\n or(x+x, tl, (tl+tr)>>1, l, r, mask)\n or(x+x+1, ((tl+tr)>>1)+1, tr, l, r, mask)\n\n tree(x) = tree(x+x) | tree(x+x+1)\n }\n\n def get(x: Int, tl: Int, tr: Int, l: Int, r: Int): Int = {\n if (tl > tr || tl > r || tr < l) return 0\n\n if (prop(x) != 0) {\n tree(x) |= prop(x)\n if (tl != tr) {\n prop(x+x) |= prop(x)\n prop(x+x+1) |= prop(x)\n }\n prop(x) = 0\n }\n\n if (tl >= l && tr <= r) return tree(x)\n\n val q1 = get(x+x, tl, (tl+tr)>>1, l, r)\n val q2 = get(x+x+1, ((tl+tr)>>1)+1, tr, l, r)\n q1 | q2\n }\n\n def build(x: Int, tl: Int, tr: Int, a: Array[Int]): Unit = {\n if (tl > tr) return\n if (tl == tr) {\n tree2(x) = a(tl)\n return\n }\n build(x+x,tl,(tl+tr)>>1, a)\n build(x+x+1,((tl+tr)>>1)+1,tr, a)\n tree2(x) = tree2(x+x) & tree2(x+x+1)\n }\n\n def get2(x: Int, tl: Int, tr: Int, l: Int, r: Int): Int = {\n if (tl > tr || tl > r || tr < l) return 0\n if (tl >= l && tr <= r) return tree2(x)\n val q1 = get2(x+x, tl, (tl+tr)>>1, l, r)\n val q2 = get2(x+x+1, ((tl+tr)>>1)+1, tr, l, r)\n q1 & q2\n }\n\n def main(args: Array[String]) {\n val n = nextInt\n val m = nextInt\n\n val l = new Array[Int](m+1)\n val r = new Array[Int](m+1)\n val q = new Array[Int](m+1)\n\n for (i <- 1 to m) {\n l(i) = nextInt\n r(i) = nextInt\n q(i) = nextInt\n }\n\n for (i <- 1 to m)\n or(1,1,n,l(i),r(i),q(i))\n\n val a = new Array[Int](n+1)\n for (i <- 1 to n)\n a(i) = get(1,1,n,i,i)\n\n build(1,1,n,a)\n\n for (i <- 1 to m)\n if (get2(1,1,n,l(i),r(i)) != q(i)) {\n out.println(\"NO\")\n out.close()\n return\n }\n\n out.println(\"YES\")\n for (i <- 1 to n)\n out.print(a(i)+\" \")\n out.close()\n }\n\n}\n\n\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n case class SegTree(as: Array[Int]) {\n\n val n = as.length\n val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))\n build(1, 0, n - 1)\n//println(t.mkString(\" \"))\n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n build(v2, tl, tm)\n build(v2 + 1, tm + 1, tr)\n t(v) = t(v2) & t(v2 + 1)\n }\n }\n\n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n //println(l, r, v, tl, tr)\n if (l > r) Int.MaxValue\n else if (l == tl && r == tr) t(v)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n //println(query(l, Math.min(r, tm), v2, tl, tm), query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr))\n query(l, Math.min(r, tm), v2, tl, tm) &\n query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)\n }\n }\n\n def update(pos: Int, delta: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n if (tl == tr) t(v) += delta\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n if (pos <= tm) update(pos, delta, v2, tl, tm)\n else update(pos, delta, v2 + 1, tm + 1, tr)\n t(v) = t(v2) + t(v2 + 1)\n }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n case class Q(l: Int, r: Int, q: Int)\n\n val qs = Array.ofDim[Q](m)\n\n for (i <- 0 until m) {\n val Array(l, r, q) = readInts(3)\n qs(i) = Q(l - 1, r - 1, q)\n }\n\n //val sorted = qs.sortBy(_.l)\n\n val xs = Array.fill(n) { 0 }\n\n val bits = Array.fill(31) { 0 }\n\n val qByL = new mutable.PriorityQueue[Q]()(Ordering.by(- _.l))\n qByL ++= qs\n\n val qByR = new mutable.PriorityQueue[Q]()(Ordering.by(- _.r))\n\n var pos = 0\n for (i <- 0 until n) {\n while (qByR.nonEmpty && qByR.head.r < i) {\n val qr = qByR.dequeue\n //println(qr)\n for (b <- 0 to 30) {\n if ((qr.q & (1 << b)) > 0) bits(b) -= 1\n }\n }\n while (qByL.nonEmpty && qByL.head.l == i) {\n val ql = qByL.dequeue\n for (b <- 0 to 30) {\n if ((ql.q & (1 << b)) > 0) {\n bits(b) += 1\n }\n }\n qByR += ql\n }\n //println(bits.mkString(\" \"))\n for (b <- 0 to 30) {\n if (bits(b) < 0) fail(1)\n else if (bits(b) > 0) xs(i) |= (1 << b)\n }\n }\n\n val segTree = SegTree(xs)\n //println(xs.mkString(\" \"))\n for (q <- qs) {\n //println(q, segTree.query(q.l, q.r))\n if (segTree.query(q.l, q.r) != q.q) fail(2)\n }\n \n println(xs.mkString(\" \"))\n\n def fail(x: Int) = {\n println(x)\n println(\"NO\")\n System.exit(0)\n }\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n case class SegTree(as: Array[Int]) {\n\n val n = as.length\n val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))\n build(1, 0, n - 1)\n//println(t.mkString(\" \"))\n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n build(v2, tl, tm)\n build(v2 + 1, tm + 1, tr)\n t(v) = t(v2) & t(v2 + 1)\n }\n }\n\n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n //println(l, r, v, tl, tr)\n if (l > r) Int.MaxValue\n else if (l == tl && r == tr) t(v)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n //println(query(l, Math.min(r, tm), v2, tl, tm), query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr))\n query(l, Math.min(r, tm), v2, tl, tm) &\n query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)\n }\n }\n\n def update(pos: Int, delta: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n if (tl == tr) t(v) += delta\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n if (pos <= tm) update(pos, delta, v2, tl, tm)\n else update(pos, delta, v2 + 1, tm + 1, tr)\n t(v) = t(v2) + t(v2 + 1)\n }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n case class Q(l: Int, r: Int, q: Int)\n\n val qs = Array.ofDim[Q](m)\n\n for (i <- 0 until m) {\n val Array(l, r, q) = readInts(3)\n qs(i) = Q(l - 1, r - 1, q)\n }\n\n //val sorted = qs.sortBy(_.l)\n\n val xs = Array.fill(n) { 0 }\n\n val bits = Array.fill(31) { 0 }\n\n val qByL = new mutable.PriorityQueue[Q]()(Ordering.by(- _.l))\n qByL ++= qs\n\n val qByR = new mutable.PriorityQueue[Q]()(Ordering.by(- _.r))\n\n var pos = 0\n for (i <- 0 until n) {\n while (qByR.nonEmpty && qByR.head.r < i) {\n val qr = qByR.dequeue\n //println(qr)\n for (b <- 0 to 30) {\n if ((qr.q & (1 << b)) > 0) bits(b) -= 1\n }\n }\n while (qByL.nonEmpty && qByL.head.l == i) {\n val ql = qByL.dequeue\n for (b <- 0 to 30) {\n if ((ql.q & (1 << b)) > 0) {\n bits(b) += 1\n }\n }\n qByR += ql\n }\n //println(bits.mkString(\" \"))\n for (b <- 0 to 30) {\n if (bits(b) < 0) fail(1)\n else if (bits(b) > 0) xs(i) |= (1 << b)\n }\n }\n\n val segTree = SegTree(xs)\n //println(xs.mkString(\" \"))\n for (q <- qs) {\n //println(q, segTree.query(q.l, q.r))\n if (segTree.query(q.l, q.r) != q.q) fail(2)\n }\n \n println(\"YES\")\n println(xs.mkString(\" \"))\n\n def fail(x: Int) = {\n println(x)\n println(\"NO\")\n System.exit(0)\n }\n}"}], "src_uid": "0b204773f8d06362b7569bd82224b218"} {"source_code": "object Main extends App {\n val Array(n,t) = readLine.split(\" \").map(_.toInt)\n val a = readLine.split(\" \").map(_.toInt)\n println(a.view.map(86400 - _).scanLeft(0)(_ + _)\n .zipWithIndex.filter(x => x._1 >= t).head._2)\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Codeforces extends App {\n val seconds = 86400\n var Array(n, t) = readLine split ' ' map(_.toInt)\n val time = readLine split ' ' map(_.toInt)\n for (i <- 0 until n) {\n t = math.max(0, t - (seconds - time(i)))\n if (t == 0) {\n println(i + 1)\n System.exit(0)\n }\n }\n}"}], "negative_code": [], "src_uid": "8e423e4bec2d113612a4dc445c4b86a9"} {"source_code": "object C extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, x) = readLine().split(\" \").map(_.toInt)\n val an = readLine().split(\" \").map(_.toInt - x)\n\n val ans =\n if (an.forall(_ == 0)) 0\n else if (an.sum == 0 || an.contains(0)) 1\n else 2\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\nobject C {\n def solve(in: Input, out: PrintWriter): Unit = {\n for (_ <- 0 until in.nextInt()) {\n val n, killJoy = in.nextInt()\n val others = Array.fill(n)(in.nextInt())\n if (others.count(_ == killJoy) == n) {\n out.println(0)\n } else if (others.sum == n * killJoy || others.contains(killJoy)) {\n out.println(1)\n } else {\n out.println(2)\n }\n }\n }\n\n private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(\n (\"3\\n2 69\\n68 70\\n6 4\\n4 4 4 4 4 4\\n9 38\\n-21 83 50 -59 -77 15 -71 -78 20\", \"1\\n0\\n2\", \"Sample\"),\n (\"1\\n3 10\\n10 1 1\", \"1\", \"Tricky case\")\n )\n\n def main(args: Array[String]): Unit = {\n if (args.length == 0) {\n val input = new Input(new InputStreamReader(System.in))\n val output = new PrintWriter(System.out)\n solve(input, output)\n output.close()\n input.close()\n } else {\n for ((in, ans, name) <- makeTests()) {\n val input = new Input(new StringReader(in))\n val output = new StringWriter()\n val pwOutput = new PrintWriter(output)\n val t0 = System.nanoTime()\n solve(input, pwOutput)\n val time = System.nanoTime() - t0\n pwOutput.close()\n output.close()\n val result = output.toString\n if (ans.trim != result.trim) {\n throw new RuntimeException(s\"Test '$name': expected '$ans' found '$result'\")\n } else {\n println(s\"Test '$name' was solved in ${time / 1e9} seconds\")\n }\n }\n }\n }\n\n class Input(stream: Reader) extends Closeable {\n private[this] val reader = new BufferedReader(stream)\n private[this] var tokenizer = new StringTokenizer(reader.readLine())\n\n @tailrec\n final def nextToken(): String = if (tokenizer.hasMoreTokens) tokenizer.nextToken() else {\n tokenizer = new StringTokenizer(reader.readLine())\n nextToken()\n }\n\n def nextInt(): Int = nextToken().toInt\n def nextLong(): Long = nextToken().toLong\n def nextDouble(): Double = nextToken().toDouble\n\n override def close(): Unit = reader.close()\n }\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\nobject C {\n def solve(in: Input, out: PrintWriter): Unit = {\n for (_ <- 0 until in.nextInt()) {\n val n, killJoy = in.nextInt()\n val others = Array.fill(n)(in.nextInt())\n if (others.count(_ == killJoy) == n) {\n out.println(0)\n } else if (others.sum == n * killJoy) {\n out.println(1)\n } else {\n out.println(2)\n }\n }\n }\n\n private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(\n (\"3\\n2 69\\n68 70\\n6 4\\n4 4 4 4 4 4\\n9 38\\n-21 83 50 -59 -77 15 -71 -78 20\", \"1\\n0\\n2\", \"Sample\")\n )\n\n def main(args: Array[String]): Unit = {\n if (args.length == 0) {\n val input = new Input(new InputStreamReader(System.in))\n val output = new PrintWriter(System.out)\n solve(input, output)\n output.close()\n input.close()\n } else {\n for ((in, ans, name) <- makeTests()) {\n val input = new Input(new StringReader(in))\n val output = new StringWriter()\n val pwOutput = new PrintWriter(output)\n val t0 = System.nanoTime()\n solve(input, pwOutput)\n val time = System.nanoTime() - t0\n pwOutput.close()\n output.close()\n val result = output.toString\n if (ans.trim != result.trim) {\n throw new RuntimeException(s\"Test '$name': expected '$ans' found '$result'\")\n } else {\n println(s\"Test '$name' was solved in ${time / 1e9} seconds\")\n }\n }\n }\n }\n\n class Input(stream: Reader) extends Closeable {\n private[this] val reader = new BufferedReader(stream)\n private[this] var tokenizer = new StringTokenizer(reader.readLine())\n\n @tailrec\n final def nextToken(): String = if (tokenizer.hasMoreTokens) tokenizer.nextToken() else {\n tokenizer = new StringTokenizer(reader.readLine())\n nextToken()\n }\n\n def nextInt(): Int = nextToken().toInt\n def nextLong(): Long = nextToken().toLong\n def nextDouble(): Double = nextToken().toDouble\n\n override def close(): Unit = reader.close()\n }\n}\n"}], "src_uid": "475a24d36eab99ae4f78815ccdc5da91"} {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val n = readString.toInt\n val as = readInts(n)\n\n def binarySearch(l: Int, key: Int): Int = {\n var mid = 0\n var low = 0\n var hi = l - 1\n while (low <= hi) {\n mid = (low + hi) >>> 1\n val d = as(ms(mid))\n if (d == key) return mid\n else if (d > key) hi = mid - 1\n else {\n mid += 1\n low = mid\n }\n }\n return -mid - 1 // insertion point is -mid - 1\n }\n\n val ms = Array.ofDim[Int](n)\n //val ps = Array.ofDim[Int](n)\n\n var l = 0\n for (i <- 0 until n) {\n var j = binarySearch(l, as(i))\n if (j < 0) j = -j - 1\n //ps(i) = ms(j)\n if (j == l || as(i) < as(ms(j))) {\n ms(j) = i\n l = math.max(l, j + 1)\n }\n }\n\n println(l)\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val n = readString.toInt\n val as = readInts(n)\n\n def lis(as: Array[Int]): Array[Int] = {\n\n val bestLen = Array.ofDim[Int](n)\n\n def binarySearch(l: Int, key: Int): (Boolean, Int) = {\n var mid = 0\n var low = 0\n var hi = l - 1\n while (low <= hi) {\n mid = (low + hi) >>> 1\n val d = as(bestLen(mid))\n if (d == key) return (true, mid)\n else if (d > key) hi = mid - 1\n else {\n mid += 1\n low = mid\n }\n }\n (false, mid) // not found - return insertion point\n }\n\n @annotation.tailrec\n def binSearch(lo: Int, hi: Int, f: Int => Int): Int = {\n if (hi < lo) lo\n else {\n val mid = lo + (hi - lo) / 2\n val fmid = f(mid)\n if (fmid == 0) mid\n else if (fmid < 0) binSearch(mid + 1, hi, f)\n else binSearch(lo, mid - 1, f)\n }\n }\n\n var len = 0\n for (i <- 0 until n) {\n val j = binSearch(0, len - 1, k => as(bestLen(k)) - as(i))\n if (j == len || as(i) < as(bestLen(j))) {\n bestLen(j) = i\n len = math.max(len, j + 1)\n }\n }\n \n bestLen.take(len).map(as(_))\n }\n\n println(lis(as).length)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val n = readString.toInt\n val as = readInts(n)\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int, f: Int => Int): (Boolean, Int) = {\n if (hi < low) (false, low) // not found - return insertion point\n else {\n val mid = (low + hi) >>> 1\n val fmid = f(mid)\n if (fmid == 0) (true, mid)\n else if (fmid < 0) binSearch(mid + 1, hi, f)\n else binSearch(low, mid - 1, f)\n }\n }\n\n def lis(as: Array[Int]): Array[Int] = {\n\n val minByLen = Array.ofDim[Int](n)\n var len = 0\n\n for (a <- as) {\n val (_, j) = binSearch(0, len - 1, minByLen(_) - a)\n if (j == len || a < minByLen(j)) {\n minByLen(j) = a\n if (j + 1 > len) len = j + 1\n }\n }\n\n minByLen.take(len)\n }\n\n println(lis(as).length)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val n = readString.toInt\n val as = readInts(n)\n\n def lis(as: Array[Int]): Array[Int] = {\n\n val bestLen = Array.ofDim[Int](n)\n\n def binarySearch(l: Int, key: Int): (Boolean, Int) = {\n var mid = 0\n var low = 0\n var hi = l - 1\n while (low <= hi) {\n mid = (low + hi) >>> 1\n val d = as(bestLen(mid))\n if (d == key) return (true, mid)\n else if (d > key) hi = mid - 1\n else {\n mid += 1\n low = mid\n }\n }\n (false, mid) // not found - return insertion point\n }\n\n var len = 0\n for (i <- 0 until n) {\n val (_, j) = binarySearch(len, as(i))\n if (j == len || as(i) < as(bestLen(j))) {\n bestLen(j) = i\n len = math.max(len, j + 1)\n }\n }\n \n bestLen.take(len).map(as(_))\n }\n\n println(lis(as).length)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val n = readString.toInt\n val as = readInts(n)\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int, f: Int => Int, target: Int): (Boolean, Int) = {\n if (hi < low) (false, low) // not found - return insertion point\n else {\n val mid = (low + hi) >>> 1\n val fmid = f(mid)\n if (fmid == target) (true, mid)\n else if (fmid < target) binSearch(mid + 1, hi, f, target)\n else binSearch(low, mid - 1, f, target)\n }\n }\n\n def lis(as: Array[Int]): IndexedSeq[Int] = {\n\n val minByLen = new mutable.ArrayBuffer[Int](n)\n\n for (a <- as) {\n val (_, j) = binSearch(0, minByLen.length - 1, minByLen(_), a)\n if (j == minByLen.length) minByLen += a\n else if (a < minByLen(j)) minByLen(j) = a\n }\n\n minByLen\n }\n\n println(lis(as).length)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val n = readString.toInt\n val as = readInts(n)\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int, f: Int => Int, target: Int): (Boolean, Int) = {\n if (hi < low) (false, low) // not found - return insertion point\n else {\n val mid = (low + hi) >>> 1\n val fmid = f(mid)\n if (fmid == target) (true, mid)\n else if (fmid < target) binSearch(mid + 1, hi, f, target)\n else binSearch(low, mid - 1, f, target)\n }\n }\n\n def lis(as: Array[Int]): IndexedSeq[Int] = {\n\n val minByLen = new mutable.ArrayBuffer[Int](n)\n\n for (a <- as) {\n val (_, j) = binSearch(0, minByLen.length - 1, minByLen, a)\n if (j == minByLen.length) minByLen += a\n else if (a < minByLen(j)) minByLen(j) = a\n }\n\n minByLen\n }\n\n println(lis(as).length)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val n = readString.toInt\n val as = readInts(n)\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int, f: Int => Int): (Boolean, Int) = {\n if (hi < low) (false, low) // not found - return insertion point\n else {\n val mid = (low + hi) >>> 1\n val fmid = f(mid)\n if (fmid == 0) (true, mid)\n else if (fmid < 0) binSearch(mid + 1, hi, f)\n else binSearch(low, mid - 1, f)\n }\n }\n\n def lis(as: Array[Int]): Array[Int] = {\n\n val bestLen = Array.ofDim[Int](n)\n var len = 0\n\n for (i <- 0 until n) {\n val (_, j) = binSearch(0, len - 1, k => as(bestLen(k)) - as(i))\n if (j == len || as(i) < as(bestLen(j))) {\n bestLen(j) = i\n len = math.max(len, j + 1)\n }\n }\n\n bestLen.take(len).map(as(_))\n }\n\n println(lis(as).length)\n}"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val n = readString.toInt\n val as = readInts(n)\n \n var c = 0\n for (i <- 0 until n - 1; if as(i) <= as(i + 1)) c += 1\n\n println(if (c == 0) 0 else c + 1)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val n = readString.toInt\n val as = readInts(n)\n \n var c = 1\n for (i <- 0 until n - 1; if as(i) <= as(i + 1)) c += 1\n\n println(c)\n}"}], "src_uid": "e132767dd89801a237b998a410b22a44"} {"source_code": "\n//package codeforce\nimport scala.io.StdIn\n\nobject CalcDrawNum extends App {\n val momentsNum = StdIn.readLine().toInt\n val array = scala.collection.mutable.ArrayBuffer[(Long, Long)]()\n for (_ <- 0 until momentsNum) {\n val scores = StdIn.readLine().split(\" \")\n array.append((scores(0).toLong, scores(1).toLong))\n }\n var from = (0L, 0L)\n var drawTimes = 1L\n var lastDraw = (0L, 0L)\n for (s <- array) {\n val (dt, d) = calcDrawTimes(from, s, lastDraw)\n drawTimes += dt\n from = s\n lastDraw = d\n }\n println(drawTimes)\n\n def calcDrawTimes(from: (Long, Long), to: (Long, Long), lastDraw: (Long, Long)): (Long, (Long, Long)) = {\n var curDraw = lastDraw\n val fromMax = scala.math.max(from._1, from._2)\n val toMin = scala.math.min(to._1,to._2)\n var times = 0L\n if (fromMax <= toMin){\n times += toMin - fromMax\n if ((fromMax,fromMax) != lastDraw){\n times += 1\n }\n curDraw = (toMin,toMin)\n }\n (times,curDraw)\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val (a, b) = na2(N)\n\n var ans = 1 // (0:0)\n REP(N) { i =>\n val a0 = if (i ==0) 0 else a(i - 1)\n val a1 = a(i)\n val b0 = if (i ==0) 0 else b(i - 1)\n val b1 = b(i)\n\n // 点数が動いた時だけ考慮すればいい\n// if (a1 > a0 || b1 > b0) {\n val rg_a = (a0, a1)\n val rg_b = (b0, b1)\n val rg = (max(rg_a._1, rg_b._1), min(rg_a._2, rg_b._2))\n\n val prevDraw = a0 == b0 // 前回ドローだと2回足してしまうので引かないといけない\n\n val len = max(0, rg._2 - rg._1 + 1) - (if (prevDraw) 1 else 0)\n// debug(s\"$i $rg_a $rg_b $rg $len\")\n ans += len\n// }\n }\n\n// if (a(N - 1) == 0 && b(N - 1) == 0) ans += 1\n\n out.println(ans)\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val (a, b) = na2(N)\n\n var ans = 0\n REP(N) { i =>\n val a0 = if (i ==0) 0 else a(i - 1)\n val a1 = a(i)\n val b0 = if (i ==0) 0 else b(i - 1)\n val b1 = b(i)\n\n // 点数が動いた時だけ考慮すればいい\n if (a1 > a0 || b1 > b0) {\n val rg_a = (a0, a1)\n val rg_b = (b0, b1)\n val rg = (max(rg_a._1, rg_b._1), min(rg_a._2, rg_b._2))\n val len = max(0, rg._2 - rg._1 + 1)\n debug(s\"$i $rg_a $rg_b $rg $len\")\n ans += len\n }\n }\n\n // やべえうまくいかない\n if (a(N - 1) == 0 && b(N - 1) == 0) ans += 1\n\n out.println(ans)\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "\n\nimport scala.io.StdIn\n\nobject CalcDrawNum extends App {\n val momentsNum = StdIn.readLine().toInt\n val array = scala.collection.mutable.ArrayBuffer[(Int, Int)]()\n for (_ <- 0 until momentsNum) {\n val scores = StdIn.readLine().split(\" \")\n array.append((scores(0).toInt, scores(1).toInt))\n }\n var from = (0, 0)\n var drawTimes = 1\n var lastDraw = (0, 0)\n for (s <- array) {\n val (dt, d) = calcDrawTimes(from, s, lastDraw)\n drawTimes += dt\n from = s\n lastDraw = d\n }\n println(drawTimes)\n\n def calcDrawTimes(from: (Int, Int), to: (Int, Int), lastDraw: (Int, Int)): (Int, (Int, Int)) = {\n var drawTimes = 0\n var draw: (Int, Int) = (0, 0)\n if (from._1 != from._2) {\n val fromMax = scala.math.max(from._1, from._2)\n draw = (fromMax, fromMax)\n } else {\n draw = (from._1 + 1, from._2 + 1)\n }\n while (draw._1 <= to._1 && draw._2 <= to._2 && draw != lastDraw) {\n drawTimes += 1\n draw = (draw._1 + 1, draw._2 + 1)\n }\n (drawTimes, draw)\n }\n}\n"}], "src_uid": "5b84295330fa07a9b42570766012990b"} {"source_code": "import java.util.Scanner\nimport scala.collection.mutable\n\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val scan = new Scanner(System.in)\n val n = scan.nextInt\n scan.nextLine\n var grid = mutable.ArrayBuffer[String]()\n for (i <- 0 until n) {\n grid += scan.nextLine\n }\n var ans = 0\n for {\n i <- 1 until n - 1\n j <- 1 until n - 1\n } if (isCross(grid, i, j)) ans += 1\n println(ans)\n }\n\n def isCross(g: mutable.ArrayBuffer[String], x: Int, y: Int): Boolean = {\n g(x)(y) == 'X' &&\n g(x - 1)(y - 1) == 'X' &&\n g(x + 1)(y - 1) == 'X' &&\n g(x - 1)(y + 1) == 'X' &&\n g(x + 1)(y + 1) == 'X'\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val M = nm_c(N, N)\n var ans = 0\n val X = Array(0, -1, -1, 1, 1)\n val Y = Array(0, -1, 1, -1, 1)\n\n def test(x: Int, y: Int) = {\n 0 until 5 forall { i =>\n 0 <= x + X(i) && x + X(i) < N &&\n 0 <= y + Y(i) && y + Y(i) < N &&\n M(X(i) + x)(Y(i) + y) == 'X'\n }\n }\n\n REP(N) { i =>\n REP(N) { j =>\n if (test(i, j)) ans += 1\n }\n }\n\n out.println(ans)\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}], "negative_code": [], "src_uid": "3270260030fc56dda3e375af4dad9330"} {"source_code": "object CF_528_2_C {\n\n type In = Seq[(Int, Int)]\n type Out = String\n \n def solve(in: In): Out = {\n val Seq(a, b, c) = in.sorted\n def right(a: (Int, Int), b: Int) = (a._1 to b).map(x => (x, a._2))\n def up(a: (Int, Int), b: Int) = if(b >= a._2) (a._2 to b).map(y => (a._1, y)) else (b to a._2).map(y => (a._1, y))\n // Go across, then up/down, then up/down, then across\n val squares = (right(a, b._1) ++ up((b._1, a._2), b._2) ++ up(b, c._2) ++ right((b._1, c._2), c._1)).toSet\n squares.size.toString + \"\\n\" + squares.map { case (a, b) => s\"$a $b\" }.mkString(\"\\n\")\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input) = i.getLines.map{_.split(\" \")}.map{case Array(a,b) => (a.toInt, b.toInt)}\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change: \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def ceil(a: Int, b: Int) = (a - 1)/b + 1\n def ceil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n sealed trait Move[A] {\n val l: Int\n val r: Int\n def axis: Int\n def len = r - l + 1\n def extend(l: Int, r: Int): A\n }\n case class MoveX(y: Int, l: Int, r: Int) extends Move[MoveX] {\n override def axis = y\n def extend(l: Int, r: Int) = MoveX(y, l, r)\n }\n case class MoveY(x: Int, l: Int, r: Int) extends Move[MoveY] {\n override def axis = x\n override def extend(l: Int, r: Int) = MoveY(x, l, r)\n }\n case class Coord(x: Int, y: Int)\n case class Path(c1: Coord, c2: Coord)\n\n case class Moves(xs: Seq[MoveX], ys: Seq[MoveY])\n\n\n def solve(): Unit = {\n val c1, c2, c3 = Coord(ni(), ni())\n val C = Array(c1, c2, c3)\n\n def moveX(p1: Coord, p2: Coord) = {\n assert(p1.y == p2.y)\n MoveX(p1.y, min(p1.x, p2.x), max(p1.x, p2.x))\n }\n \n def moveY(p1: Coord, p2: Coord) = {\n assert(p1.x == p2.x)\n MoveY(p1.x, min(p1.y, p2.y), max(p1.y, p2.y))\n }\n \n def move(p: Path): (MoveX, MoveY) = {\n val Path(c1, c2) = p\n val xmin = min(c1.x, c2.x)\n val xmax = max(c1.x, c2.x)\n val ymin = min(c1.y, c2.y)\n val ymax = max(c1.y, c2.y)\n val lt = Coord(xmin, ymax)\n val rt = Coord(xmax, ymax)\n val lb = Coord(xmin, ymin)\n val rb = Coord(xmax, ymin)\n\n // 時計回り\n val P = Array(lt, rt, rb, lb)\n val s = P.indexOf(c1)\n val m = (s + 1) % 4\n val e = (s + 2) % 4\n\n // X -> Y\n if (s % 2 == 0) {\n (moveX(P(s), P(m)), moveY(P(m), P(e)))\n\n // Y -> X\n } else {\n (moveX(P(m), P(e)), moveY(P(s), P(m)))\n }\n }\n\n def len(moves: Moves) = {\n var len = (moves.xs ++ moves.ys).map(_.len).sum\n moves.xs foreach { x =>\n len -= moves.ys.count(y => y.l <= x.y && x.y <= y.r && x.l <= y.x && y.x <= x.r)\n }\n len\n }\n \n def merge2[A <: Move[A]](m1: A, m2: A): Seq[A] = {\n if (m1.axis == m2.axis) {\n val l = max(m1.l, m2.l)\n val r = min(m1.r, m2.r)\n // 重複部分あり\n if (l <= r) {\n Seq(m1.extend(min(m1.l, m2.l), max(m1.r, m2.r)))\n } else {\n Seq(m1, m2)\n }\n } else {\n Seq(m1, m2)\n }\n }\n\n def merge4(arg: (MoveX, MoveX, MoveY, MoveY)): Moves = {\n val (x1, x2, y1, y2) = arg\n\n val xs = merge2(x1, x2)\n val ys = merge2(y1, y2)\n\n Moves(xs, ys)\n }\n\n val ans = (for {\n c1 <- C\n c2 <- C\n c3 <- C\n if Set(c1, c2, c3).size == 3\n (x1, y1) = move(Path(c1, c2))\n (x2, y2) = move(Path(c2, c3))\n } yield merge4((x1, x2, y1, y2))).minBy(len)\n\n out.println(len(ans))\n\n val flg = Array.ofDim[Boolean](1001, 1001)\n\n (ans.xs ++ ans.ys) foreach { move =>\n REP(move.len) { i =>\n move match {\n case MoveX(y, l, r) =>\n if (!flg(l + i)(y)) {\n out.println(s\"${l + i} $y\")\n flg(l + i)(y) = true\n }\n\n case MoveY(x, l, r) =>\n if (!flg(x)(l + i)) {\n out.println(s\"$x ${l + i}\")\n flg(x)(l + i) = true\n }\n }\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Coord(x: Int, y: Int)\n case class Path(p1: Coord, p2: Coord)\n type Grid = Array[Array[Boolean]]\n\n def solve(): Unit = {\n val MAX = 1001\n// val MAX = 3\n val C1, C2, C3 = Coord(ni(), ni())\n val E = Array(Path(C1, C2), Path(C2, C3), Path(C3, C1))\n\n def cnt(g: Grid) = g.map(_.count(identity)).sum\n\n def paintLine(c1: Coord, c2: Coord, g: Grid): Unit = {\n if (c1.x == c2.x) {\n val iniY = min(c1.y, c2.y)\n REP(abs(c1.y - c2.y) + 1, iniY) { y =>\n g(c1.x)(y) = true\n }\n } else if (c1.y == c2.y){\n val iniX = min(c1.x, c2.x)\n REP(abs(c1.x - c2.x) + 1, iniX) { x =>\n g(x)(c1.y) = true\n }\n } else {\n throw new IllegalArgumentException(s\"$c1 $c2\")\n }\n }\n\n def onLine(p: Path) = p.p1.x == p.p2.x || p.p1.y == p.p2.y\n\n def paint(p: Path, g: Grid, flg: Boolean): Unit = {\n if (onLine(p)) {\n paintLine(p.p1, p.p2, g)\n } else {\n val lt = Coord(min(p.p1.x, p.p2.x), max(p.p1.y, p.p2.y))\n val rt = Coord(max(p.p1.x, p.p2.x), max(p.p1.y, p.p2.y))\n val lb = Coord(min(p.p1.x, p.p2.x), min(p.p1.y, p.p2.y))\n val rb = Coord(max(p.p1.x, p.p2.x), min(p.p1.y, p.p2.y))\n val Array(c1, c2) = Array(lt, rt, lb, rb).filter(c => c != p.p1 && c != p.p2)\n val c = if (flg) c1 else c2\n paintLine(p.p1, c, g)\n paintLine(p.p2, c, g)\n }\n }\n\n val memo = Array.ofDim[Boolean](12, MAX, MAX)\n\n val grids = map(3)(identity).flatMap { i =>\n for {\n x1 <- 0 until 2\n x2 <- 0 until 2\n } yield {\n val Array(p1, p2) = E.zipWithIndex.filterNot(_._2 == i).map(_._1)\n val g = memo(i * 4 + x1 * 2 + x2)\n paint(p1, g, x1 == 1)\n paint(p2, g, x2 == 1)\n\n g\n }\n }\n\n val ans = grids.minBy(cnt)\n out.println(cnt(ans))\n REP(MAX) { i =>\n REP(MAX) { j =>\n if (ans(i)(j)) out.println(s\"$i $j\")\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Coord(x: Int, y: Int)\n case class Path(p1: Coord, p2: Coord)\n type Grid = Array[Array[Boolean]]\n\n def solve(): Unit = {\n val C1, C2, C3 = Coord(ni(), ni())\n val E = Array(Path(C1, C2), Path(C2, C3), Path(C3, C1))\n\n def paint(p: Path, g: Grid): Unit = {\n val x = min(p.p1.x, p.p2.x)\n val xLen = abs(p.p1.x - p.p2.x)\n val y = min(p.p1.y, p.p2.y)\n val yLen = abs(p.p1.y - p.p2.y)\n\n REP(xLen + 1) { i =>\n g(x + i)(y) = true\n }\n\n REP(yLen + 1) { i =>\n g(x + xLen)(y + i) = true\n }\n }\n\n val grids = map(3) { i =>\n val Array(e1, e2) = E.zipWithIndex.filterNot(_._2 == i).map(_._1)\n val g = Array.ofDim[Boolean](1001, 1001)\n paint(e1, g)\n paint(e2, g)\n g\n }\n\n\n def cnt(g: Grid) = g.map(_.count(identity)).sum\n\n val ans = grids.minBy(cnt)\n out.println(cnt(ans))\n REP(1001) { i =>\n REP(1001) { j =>\n if (ans(i)(j)) out.println(s\"$i $j\")\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n sealed trait Move[A] {\n val l: Int\n val r: Int\n def axis: Int\n def len = r - l + 1\n def extend(l: Int, r: Int): A\n }\n case class MoveX(y: Int, l: Int, r: Int) extends Move[MoveX] {\n override def axis = y\n def extend(l: Int, r: Int) = MoveX(y, l, r)\n }\n case class MoveY(x: Int, l: Int, r: Int) extends Move[MoveY] {\n override def axis = x\n override def extend(l: Int, r: Int) = MoveY(x, l, r)\n }\n case class Coord(x: Int, y: Int)\n case class Path(c1: Coord, c2: Coord)\n\n case class Moves(xs: Seq[MoveX], ys: Seq[MoveY])\n\n\n def solve(): Unit = {\n val c1, c2, c3 = Coord(ni(), ni())\n val C = Array(c1, c2, c3)\n\n def moveX(p1: Coord, p2: Coord) = {\n assert(p1.y == p2.y)\n MoveX(p1.y, min(p1.x, p2.x), max(p1.x, p2.x))\n }\n \n def moveY(p1: Coord, p2: Coord) = {\n assert(p1.x == p2.x)\n MoveY(p1.x, min(p1.y, p2.y), max(p1.y, p2.y))\n }\n \n def move(p: Path): (MoveX, MoveY) = {\n val Path(c1, c2) = p\n val xmin = min(c1.x, c2.x)\n val xmax = max(c1.x, c2.x)\n val ymin = min(c1.y, c2.y)\n val ymax = max(c1.y, c2.y)\n val lt = Coord(xmin, ymax)\n val rt = Coord(xmax, ymax)\n val lb = Coord(xmin, ymin)\n val rb = Coord(xmax, ymin)\n\n // 時計回り\n val P = Array(lt, rt, rb, lb)\n val s = P.indexOf(c1)\n val m = (s + 1) % 4\n val e = (s + 2) % 4\n\n // X -> Y\n if (s % 2 == 0) {\n (moveX(P(s), P(m)), moveY(P(m), P(e)))\n\n // Y -> X\n } else {\n (moveX(P(m), P(e)), moveY(P(s), P(m)))\n }\n }\n\n def len(moves: Moves) = {\n var len = (moves.xs ++ moves.ys).map(_.len).sum\n moves.xs foreach { x =>\n len -= moves.ys.count(y => y.l <= x.y && x.y <= y.r)\n }\n len\n }\n \n def merge2[A <: Move[A]](m1: A, m2: A): Seq[A] = {\n if (m1.axis == m2.axis) {\n val l = max(m1.l, m2.l)\n val r = min(m1.r, m2.r)\n // 重複部分あり\n if (l <= r) {\n Seq(m1.extend(min(m1.l, m2.l), max(m1.r, m2.r)))\n } else {\n Seq(m1, m2)\n }\n } else {\n Seq(m1, m2)\n }\n }\n\n def merge4(arg: (MoveX, MoveX, MoveY, MoveY)): Moves = {\n val (x1, x2, y1, y2) = arg\n\n val xs = merge2(x1, x2)\n val ys = merge2(y1, y2)\n\n Moves(xs, ys)\n }\n\n val ans = (for {\n c1 <- C\n c2 <- C\n c3 <- C\n if Set(c1, c2, c3).size == 3\n (x1, y1) = move(Path(c1, c2))\n (x2, y2) = move(Path(c2, c3))\n } yield merge4((x1, x2, y1, y2))).minBy(len)\n\n out.println(len(ans))\n\n val flg = Array.ofDim[Boolean](1001, 1001)\n\n (ans.xs ++ ans.ys) foreach { move =>\n REP(move.len) { i =>\n move match {\n case MoveX(y, l, r) =>\n if (!flg(l + i)(y)) {\n out.println(s\"${l + i} $y\")\n flg(l + i)(y) = true\n }\n\n case MoveY(x, l, r) =>\n if (!flg(x)(l + i)) {\n out.println(s\"$x ${l + i}\")\n flg(x)(l + i) = true\n }\n }\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n sealed trait Move[A] {\n val l: Int\n val r: Int\n def axis: Int\n def len = r - l + 1\n def extend(l: Int, r: Int): A\n }\n case class MoveX(y: Int, l: Int, r: Int) extends Move[MoveX] {\n override def axis = y\n def extend(l: Int, r: Int) = MoveX(y, l, r)\n }\n case class MoveY(x: Int, l: Int, r: Int) extends Move[MoveY] {\n override def axis = x\n override def extend(l: Int, r: Int) = MoveY(x, l, r)\n }\n case class Coord(x: Int, y: Int)\n case class Path(c1: Coord, c2: Coord)\n\n case class Moves(xs: Seq[MoveX], ys: Seq[MoveY])\n\n\n def solve(): Unit = {\n val c1, c2, c3 = Coord(ni(), ni())\n val P = Array(Path(c1, c2), Path(c2, c3), Path(c3, c1))\n\n def moveX(p1: Coord, p2: Coord) = {\n assert(p1.y == p2.y)\n MoveX(p1.y, min(p1.x, p2.x), max(p1.x, p2.x))\n }\n \n def moveY(p1: Coord, p2: Coord) = {\n assert(p1.x == p2.x)\n MoveY(p1.x, min(p1.y, p2.y), max(p1.y, p2.y))\n }\n \n def move(p: Path): (MoveX, MoveY) = {\n val Path(c1, c2) = p\n val xmin = min(c1.x, c2.x)\n val xmax = max(c1.x, c2.x)\n val ymin = min(c1.y, c2.y)\n val ymax = max(c1.y, c2.y)\n val lt = Coord(xmin, ymax)\n val rt = Coord(xmax, ymax)\n val lb = Coord(xmin, ymin)\n val rb = Coord(xmax, ymin)\n\n // 時計回り\n val P = Array(lt, rt, rb, lb)\n val s = P.indexOf(c1)\n val m = (s + 1) % 4\n val e = (s + 2) % 4\n\n // X -> Y\n if (s % 2 == 0) {\n (moveX(P(s), P(m)), moveY(P(m), P(e)))\n\n // Y -> X\n } else {\n (moveX(P(m), P(e)), moveY(P(s), P(m)))\n }\n }\n\n def len(moves: Moves) = {\n var len = (moves.xs ++ moves.ys).map(_.len).sum\n moves.xs foreach { x =>\n len -= moves.ys.count(y => y.l <= x.y && x.y <= y.r)\n }\n len\n }\n \n def merge2[A <: Move[A]](m1: A, m2: A): Seq[A] = {\n if (m1.axis == m2.axis) {\n val l = max(m1.l, m2.l)\n val r = min(m1.r, m2.r)\n // 重複部分あり\n if (l <= r) {\n Seq(m1.extend(min(m1.l, m2.l), max(m1.r, m2.r)))\n } else {\n Seq(m1, m2)\n }\n } else {\n Seq(m1, m2)\n }\n }\n\n def merge4(arg: (MoveX, MoveX, MoveY, MoveY)): Moves = {\n val (x1, x2, y1, y2) = arg\n\n val xs = merge2(x1, x2)\n val ys = merge2(y1, y2)\n\n Moves(xs, ys)\n }\n\n val ans = (for {\n p1 <- P\n p2 <- P\n if p1 != p2\n (x1, y1) = move(p1)\n (x2, y2) = move(p2)\n } yield merge4((x1, x2, y1, y2))).minBy(len)\n\n out.println(len(ans))\n\n val flg = Array.ofDim[Boolean](1001, 1001)\n\n (ans.xs ++ ans.ys) foreach { move =>\n REP(move.len) { i =>\n move match {\n case MoveX(y, l, r) =>\n if (!flg(l + i)(y)) {\n out.println(s\"${l + i} $y\")\n flg(l + i)(y) = true\n }\n\n case MoveY(x, l, r) =>\n if (!flg(x)(l + i)) {\n out.println(s\"$x ${l + i}\")\n flg(x)(l + i) = true\n }\n }\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object CF_528_2_C {\n\n type In = Seq[(Int, Int)]\n type Out = String\n \n def solve(in: In): Out = {\n val Seq(a, b, c) = in.sorted\n def right(a: (Int, Int), b: Int) = (a._1 to b).map(x => (x, a._2))\n def up(a: (Int, Int), b: Int) = (a._2 to b).map(y => (a._1, y))\n // Go across, then up/down, then up/down, then across\n val squares = (right(a, b._1) ++ up((b._1, a._1), b._2) ++ up(b, c._2) ++ right((b._1, c._2), c._1)).toSet\n squares.size.toString + \"\\n\" + squares.map { case (a, b) => s\"$a $b\" }.mkString(\"\\n\")\n }\n \n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input) = i.getLines.map{_.split(\" \")}.map{case Array(a,b) => (a.toInt, b.toInt)}\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change: \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def ceil(a: Int, b: Int) = (a - 1)/b + 1\n def ceil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}"}, {"source_code": "object CF_528_2_C {\n\n type In = Seq[(Int, Int)]\n type Out = String\n \n def solve(in: In): Out = {\n val Seq(a, b, c) = in.sorted\n def right(a: (Int, Int), b: Int) = (a._1 to b).map(x => (x, a._2))\n def up(a: (Int, Int), b: Int) = (a._2 to b).map(y => (a._1, y))\n // Go across, then up/down, then up/down, then across\n val squares = (right(a, b._1) ++ up((b._1, a._2), b._2) ++ up(b, c._2) ++ right((b._1, c._2), c._1)).toSet\n squares.size.toString + \"\\n\" + squares.map { case (a, b) => s\"$a $b\" }.mkString(\"\\n\")\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input) = i.getLines.map{_.split(\" \")}.map{case Array(a,b) => (a.toInt, b.toInt)}\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change: \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def ceil(a: Int, b: Int) = (a - 1)/b + 1\n def ceil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}"}], "src_uid": "1a358e492dfd7e226138ea64e432c180"} {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n //\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def minDays(a: Array[Int],pos: Int, target: Int): Option[Int] = {\n if(a(pos) >= target){\n Some(0)\n }else{\n if(pos >= a.length-1)\n None\n else\n minDays(a,pos+1,target-a(pos)).map{ d =>\n d+target-a(pos)\n }\n }\n }\n\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n (1 to t).foreach(_ => {\n val n = in.nextInt()\n val d = in.nextInt()\n val a = (1 to n).map(_ => in.nextInt()).toArray\n val res = (0 to 200).zipWithIndex.flatMap{case (h,i) => minDays(a,0,h).flatMap(m => if(m <= d) Some(i) else None)}.max\n out.println(res)\n })\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}", "positive_code": [{"source_code": "import java.io.PrintWriter\n\nimport scala.collection.mutable\nimport util.control.Breaks._\n\nobject Solution {\n val reader = scala.io.StdIn\n def readInt(): Int = reader.readLine().toInt\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n def readString(): String = reader.readLine()\n\n def multiTest(f: () => Unit): Unit = {\n var t = readInt()\n while (t > 0) {\n f()\n t -= 1\n }\n }\n\n def solve(): Unit = {\n var Array(n, d) = readArrayInt()\n val a = readArrayInt()\n var rs = a(0)\n for (i <- 1 until n if a(i) > 0) {\n rs += math.min(d / i, a(i))\n d -= math.min(d/i, a(i))*i\n }\n println(rs)\n }\n\n def main(args: Array[String]) {\n multiTest(solve)\n //solve()\n }\n}"}], "negative_code": [{"source_code": "import java.io.PrintWriter\n\nimport scala.collection.mutable\nimport util.control.Breaks._\n\nobject Solution {\n val reader = scala.io.StdIn\n def readInt(): Int = reader.readLine().toInt\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n def readString(): String = reader.readLine()\n\n def multiTest(f: () => Unit): Unit = {\n var t = readInt()\n while (t > 0) {\n f()\n t -= 1\n }\n }\n\n def solve(): Unit = {\n var Array(n, d) = readArrayInt()\n val a = readArrayInt()\n var rs = a(0)\n for (i <- 1 until n) {\n while (d > 0 && a(i) >= i) {\n rs += 1\n d -= i\n a(i) -= 1\n }\n }\n println(rs)\n }\n\n def main(args: Array[String]) {\n multiTest(solve)\n //solve()\n }\n}"}], "src_uid": "7bbb4b9f5eccfe13741445c815a4b1ca"} {"source_code": "object B {\n def main(args: Array[String]) {\n val n = readLine\n println(n + n.reverse)\n }\n}", "positive_code": [{"source_code": "object B {\n def main(args: Array[String]) = {\n val n = readLine()\n println(n + n.reverse)\n }\n\n def readLine() = io.StdIn.readLine()\n def readInts() = readLine().split(' ').map(_.toInt)\n\n def digits(s: String) = s.map(_.toString.toInt)\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val x = readLine()\n println(x + x.reverse)\n }\n}\n"}, {"source_code": "import scala.io._\nimport java.util.Scanner\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val a = scanner.next()\n\n println(a + a.reverse)\n }\n}"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val line = lines.next()\n print(line)\n print(line.reverse)\n}"}, {"source_code": "object B688 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val n = read\n println(n + n.reverse)\n }\n}"}, {"source_code": "\nobject cf_688B {\n def main(args: Array[String]) {\n val input = readLine()\n print(input)\n for (s <- input.reverse) print(s)\n }\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _688B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val s = read[String]\n write(s + s.reverse)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toYesNo = if(x) \"yes\" else \"no\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def bitCount: Int = java.lang.Integer.bitCount(x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeLine(obj: Any*): this.type = {\n if (obj.isEmpty) printer.println() else obj foreach printer.println\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import java.util.Scanner\n\nobject MainApp {\n def isEvenPalindrome(n: List[Char]): Boolean =\n n match {\n case Nil => true\n case x if n.length % 2 != 0 => false\n case x :: xs => if (n.head == n.last) isEvenPalindrome(xs.init) else false\n }\n\n def generatePalindromes(last: Int): Seq[(Int, String)] = {\n (1 to last) zip {\n for (\n x <- 1 to last if isEvenPalindrome(x.toString.toList)\n ) yield x.toString\n }\n }\n\n def main(args: Array[String]) = {\n val n = new Scanner(System.in).nextLine()\n println(n ++ n.reverse)\n// println(generatePalindromes(1000000000))\n }\n}\n"}, {"source_code": "object problem_B{\n def main(args: Array[String]): Unit = {\n val scanner = new java.util.Scanner(System.in)\n val line = scanner.nextLine()\n\n println(line + line.reverse)\n\n }\n}"}], "negative_code": [], "src_uid": "bcf75978c9ef6202293773cf533afadf"} {"source_code": "import scala.io.StdIn._\n\nobject B_1181 extends App {\n val l = readInt()\n val A = readLine()\n\n def split(i: Int): BigInt = {\n if (i < 1 || i >= l) return BigInt(\"0\")\n\n var (a, b) = A.splitAt(i)\n\n val aa = BigInt(a)\n val bb = BigInt(b)\n\n// println(a + \" + \" + b + \" = \" + (aa + bb))\n\n aa + bb\n }\n\n def getLeft(i: Int) = {\n var left = i\n while (left >= 0 && A(left) == '0') left -= 1\n left\n }\n\n def getRight(i: Int) = {\n var right = i\n while (right < l && A(right) == '0') right += 1\n right\n }\n\n val l1 = getLeft(l / 2)\n val l2 = getLeft(l / 2 - 1)\n val r1 = getRight(l / 2)\n val r2 = getRight(l / 2 + 1)\n\n val l3 = r1\n val l4 = r2\n val r3 = l1\n val r4 = l2\n\n val result = Set(l1, l2, l3, l4, r1, r2, r3, r4)\n .map { i =>\n split(i)\n }\n .filterNot(_ == 0)\n .min\n\n println(result)\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val S = ns(N)\n\n var ms = Integer.MAX_VALUE\n val cand = ArrayBuffer[Int]()\n\n TO(1, N - 1) { i =>\n if (S(i) != '0') {\n val d = max(i, N - i) + 1\n if (ms > d) {\n ms = d\n cand.clear()\n cand += i\n } else if (ms == d) {\n cand += i\n }\n }\n }\n\n debug(s\"ms:$ms\")\n debug(cand.mkString(\" \"))\n\n val ans = (for {\n i <- cand\n } yield {\n val l = BigInt(S.take(i).mkString)\n val r = BigInt(S.drop(i).mkString)\n l + r\n }).min\n\n out.println(ans)\n }\n}"}], "negative_code": [], "src_uid": "08bce37778b7bfe478340d5c222ae362"} {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n// val t = readLine().toInt\n// for (i <- 1 to t) {\n val n = readLine().toInt\n handle(n)\n// }\n }\n\n def handle(n: Int) = {\n def hat(left: Int, upper: Boolean) = {\n val yl = if (upper) 1 else -1\n val yh = if (upper) 2 else -2\n val mid = left + 1\n val right = left + 2\n println(f\"$left $yl\")\n println(f\"$left $yh\")\n println(f\"$mid $yh\")\n println(f\"$right $yh\")\n println(f\"$right $yl\")\n }\n\n println(2 * n + 3 + 5 * (n + 1))\n\n // main\n (-2 to 2 * n).foreach(i => println(f\"$i 0\"))\n\n (0 to n / 2).foreach(i => hat(-2 + 4 * i, upper = true))\n (0 to (n - 1) / 2).foreach(i => hat(4 * i, upper = false))\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n", "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val k = nextInt\n val res = ArrayBuffer.empty[String]\n for (i <- 0 to k) {\n val ii = i\n res += s\"${ii} ${ii}\"\n res += s\"${ii + 1} ${ii}\"\n res += s\"${ii} ${ii + 1}\"\n }\n val ii = k\n res += s\"${ii + 1} ${ii + 1}\"\n\n out.println(res.length)\n out.println(res.mkString(\"\\n\"))\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n// val t = readLine().toInt\n// for (i <- 1 to t) {\n val n = readLine().toInt\n println(15 * n)\n (0 until n).foreach(handle)\n// }\n }\n\n def handle(i: Int) = {\n //center\n println(f\"${10*i} 0\")\n //neighs\n println(f\"${10*i + 1} 0\")\n println(f\"${10*i + 0} 1\")\n println(f\"${10*i - 1} 0\")\n println(f\"${10*i + 0} -1\")\n // chains\n println(f\"${10*i + 0} 2\")\n println(f\"${10*i + 1} 2\")\n println(f\"${10*i + 2} 2\")\n println(f\"${10*i + 2} 1\")\n println(f\"${10*i + 2} 0\")\n\n println(f\"${10*i + 0} -2\")\n println(f\"${10*i - 1} -2\")\n println(f\"${10*i - 2} -2\")\n println(f\"${10*i - 2} -1\")\n println(f\"${10*i - 2} 0\")\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n// val t = readLine().toInt\n// for (i <- 1 to t) {\n val n = readLine().toInt\n handle(n)\n// }\n }\n\n def handle(n: Int) = {\n def hat(left: Int, upper: Boolean) = {\n val yl = if (upper) 1 else -1\n val yh = if (upper) 2 else -2\n val mid = left + 1\n val right = left + 2\n println(f\"$left $yl\")\n println(f\"$left $yh\")\n println(f\"$mid $yh\")\n println(f\"$right $yh\")\n println(f\"$right $yl\")\n }\n\n println(2 * n + 3 + 5 * (n + 1))\n\n // main\n (-2 to 2 * n).foreach(i => println(f\"$i 0\"))\n\n (0 to n / 2).foreach(i => hat(-2 + 4 * i, upper = true))\n (0 to (n - 1) / 2).foreach(i => hat(4 * i, upper = true))\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n// val t = readLine().toInt\n// for (i <- 1 to t) {\n val n = readLine().toInt\n handle(n)\n// }\n }\n\n def handle(n: Int) = {\n if (n == 1) {\n println(15)\n //center\n println(\"0 0\")\n //neighs\n println(\"1 0\")\n println(\"0 1\")\n println(\"-1 0\")\n println(\"0 -1\")\n // chains\n println(\"0 2\")\n println(\"1 2\")\n println(\"2 2\")\n println(\"2 1\")\n println(\"2 0\")\n\n println(\"0 -2\")\n println(\"-1 -2\")\n println(\"-2 -2\")\n println(\"-2 -1\")\n println(\"-2 0\")\n }\n else {\n println(4 * n + 12)\n // core\n (0 until n).foreach(i => {\n println(f\"$i 1\")\n println(f\"$i -1\")\n println(f\"$i 0\")\n })\n //chain\n (-2 to n + 1).foreach(i => {\n println(f\"$i 3\")\n })\n println(\"-1 0\")\n println(\"-2 0\")\n println(\"-2 1\")\n println(\"-2 2\")\n println(f\"$n 0\")\n println(f\"${n+1} 0\")\n println(f\"${n+1} 1\")\n println(f\"${n+1} 2\")\n }\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}], "src_uid": "d87c40ae942f3c378bde372f3320a09f"} {"source_code": "import scala.io.StdIn\n\nobject Forecast {\n\n def main(args: Array[String]) {\n val Array(a, b, c) = StdIn.readLine().split(\"\\\\s\").map(_.toInt)\n val d = Math.sqrt(b * b - 4 * a * c)\n val x1 = -(b + d) / (2 * a)\n val x2 = -(b - d) / (2 * a)\n println(Math.max(x1, x2))\n println(Math.min(x1, x2))\n }\n\n}", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Main {\n\n def sqr(x: Long) = x * x\n\n def powmod(x: Long, n: Long, p: Long): Long = {\n if (n == 1) x\n else if (n % 2 == 1) (powmod(x, n - 1, p) * x) % p\n else sqr(powmod(x, n / 2, p)) % p\n }\n\n def C(n: Int, k: Int) = {\n var res = BigInt(1)\n for (i <- n - k + 1 to n) {\n res = res * i\n }\n for (i <- 1 to k.toInt) {\n res = res / i\n }\n res\n }\n\n def fact(n: Int) = {\n var res = BigInt(1)\n for (i <- 1 to n) {\n res = res * i\n }\n res\n }\n\n def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a % b)\n\n def lcm(a: Long, b: Long) = a / gcd(a, b) * b\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n\n val Array(a, b, c) = in.nextLine().split(' ').map(_.toDouble)\n\n val D = b * b - 4 * a * c\n\n var x1 = (-b + Math.sqrt(D)) / (2 * a)\n var x2 = (-b - Math.sqrt(D)) / (2 * a)\n\n if (x1 < x2) {\n val c = x1\n x1 = x2\n x2 = c\n }\n\n println(\"%.10f\\n%.10f\".format(x1, x2))\n }\n}\n"}], "negative_code": [], "src_uid": "2d4ad39d42b349765435b351897403da"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.util.Try\n\nobject Sol extends App {\n val (in, out) = Try {(\n new Reader(\"input.txt\"),\n new PrintWriter(new BufferedWriter(new FileWriter(\"output.txt\")))\n )} getOrElse {(\n new Reader(),\n new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n )}\n\n val n = in.nextInt\n val a = in.nextLine.split(\" \").map(_.toInt)\n val parts = a.partition(_ % 2 == 0)\n\n out.println(Math.min(parts._1.length, parts._2.length))\n out.flush()\n out.close()\n\n class Reader() {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n def next: String = {\n while (tok == null || !tok.hasMoreElements)\n tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n def nextLong: Long = next.toLong\n\n def nextDouble: Double = next.toDouble\n\n def nextLine: String = br.readLine\n }\n\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main extends App {\n\n val n: Int = StdIn.readInt()\n val arr: Array[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n\n val odd = arr.filter(item => item%2 == 0).length\n val notOdd = arr.filter(item => item%2 != 0).length\n\n val res = Math.min(odd, notOdd)\n\n println(res)\n\n}\n"}, {"source_code": "//package codeforces.contest1213\n\nobject ChipsMoving {\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val (evens, odds) =\n io.StdIn.readLine.split(\" \").map(_.toInt).foldLeft((0, 0)) {\n case ((e, o), i) =>\n if ((i & 1) == 1) (e, o + 1) else (e + 1, o)\n }\n println(evens min odds)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]) = {\n val numberChips: Int = readInt()\n val chipsCoord = readLine().split(\" \").map(_.toInt).toList\n var oddCoord: Int = 0\n var evenCoord: Int = 0\n for (i <- 0 until numberChips) {\n if (chipsCoord(i) % 2 == 0) {\n evenCoord += 1\n } else {\n oddCoord += 1\n }\n }\n println(s\"${Math.min(evenCoord, oddCoord)}\")\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.util.Try\n\nobject Sol extends App {\n val (in, out) = Try {(\n new Reader(\"input.txt\"),\n new PrintWriter(new BufferedWriter(new FileWriter(\"output.txt\")))\n )} getOrElse {(\n new Reader(),\n new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n )}\n\n val n = in.nextInt\n val a = in.nextLine.split(\" \").map(_.toInt)\n def move(x: Int, y: Int) = if ((x - y).abs % 2 == 1) 1 else 0\n def cost(pos: Int): Int = a.foldLeft(0)((acc, cur) => acc + move(pos, cur))\n\n out.println(a.map(cost).min)\n out.flush()\n out.close()\n\n class Reader() {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n def next: String = {\n while (tok == null || !tok.hasMoreElements)\n tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n def nextLong: Long = next.toLong\n\n def nextDouble: Double = next.toDouble\n\n def nextLine: String = br.readLine\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.util.Try\n\nobject Sol extends App {\n val (in, out) = Try {(\n new Reader(\"input.txt\"),\n new PrintWriter(new BufferedWriter(new FileWriter(\"output.txt\")))\n )} getOrElse {(\n new Reader(),\n new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n )}\n\n val n = in.nextInt\n val a = in.nextLine.split(\" \").map(_.toInt)\n val evens = a.count(_ % 2 == 0)\n\n out.println(evens min (n - evens))\n out.flush()\n out.close()\n\n class Reader() {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n def next: String = {\n while (tok == null || !tok.hasMoreElements)\n tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n def nextLong: Long = next.toLong\n\n def nextDouble: Double = next.toDouble\n\n def nextLine: String = br.readLine\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.util.Try\n\nobject Sol extends App {\n val (in, out) = Try {(\n new Reader(\"input.txt\"),\n new PrintWriter(new BufferedWriter(new FileWriter(\"output.txt\")))\n )} getOrElse {(\n new Reader(),\n new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n )}\n \n val n = in.nextInt\n val a = in.nextLine.split(\" \").map(_.toInt)\n def move(x: Int, y: Int) = if ((x - y).abs == 1) 1 else 0\n def cost(pos: Int): Int = a.foldLeft(0)((acc, cur) => acc + move(pos, cur))\n implicit def ord: Ordering[Int] = (x: Int, y : Int) => cost(x).compareTo(cost(y))\n\n out.println(a.min)\n out.flush()\n out.close()\n\n class Reader() {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n def next: String = {\n while (tok == null || !tok.hasMoreElements)\n tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n def nextLong: Long = next.toLong\n\n def nextDouble: Double = next.toDouble\n\n def nextLine: String = br.readLine\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.util.Try\n\nobject Sol extends App {\n val in = Try(new Reader(\"input.txt\")).getOrElse(new Reader())\n val out = Try(new PrintWriter(new BufferedWriter(new FileWriter(\"output.txt\"))))\n .getOrElse(new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))))\n\n val n = in.nextInt\n val a = in.nextLine.split(\" \").map(_.toInt)\n def move(x: Int, y: Int) = if ((x - y).abs == 1) 1 else 0\n def cost(pos: Int): Int = a.foldLeft(0)((acc, cur) => acc + move(pos, cur))\n implicit def ord: Ordering[Int] = (x: Int, y : Int) => cost(x).compareTo(cost(y))\n \n out.println(a.min)\n out.flush()\n out.close()\n\n class Reader() {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n def next: String = {\n while (tok == null || !tok.hasMoreElements)\n tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n def nextLong: Long = next.toLong\n\n def nextDouble: Double = next.toDouble\n\n def nextLine: String = br.readLine\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.util.Try\n\nobject Sol extends App {\n val (in, out) = Try {(\n new Reader(\"input.txt\"),\n new PrintWriter(new BufferedWriter(new FileWriter(\"output.txt\")))\n )} getOrElse {(\n new Reader(),\n new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n )}\n\n val n = in.nextInt\n val a = in.nextLine.split(\" \").map(_.toInt)\n def move(x: Int, y: Int) = if ((x - y).abs == 1) 1 else 0\n def cost(pos: Int): Int = a.foldLeft(0)((acc, cur) => acc + move(pos, cur))\n\n out.println(a.map(cost).min)\n out.flush()\n out.close()\n\n class Reader() {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n def next: String = {\n while (tok == null || !tok.hasMoreElements)\n tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n def nextLong: Long = next.toLong\n\n def nextDouble: Double = next.toDouble\n\n def nextLine: String = br.readLine\n }\n\n}\n"}], "src_uid": "a0a6cdda2ce201767bf5418f445a44eb"} {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable._\r\n\r\nobject test {\r\n val writer = new PrintWriter(System.out)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\r\n def readInt(): Int = next().toInt\r\n def readLong(): Long = next().toLong\r\n def readString(): String = next()\r\n\r\n def main(args: Array[String]): Unit = {\r\n val max_n = 200010\r\n var a = new Array[Int](max_n)\r\n val t = readInt()\r\n for (tt <- 1 to t) {\r\n var d = Map[Int, ArrayBuffer[Int]]()\r\n val n = readInt()\r\n val k = readInt()\r\n for (i <- 1 to n) {\r\n val x = readInt()\r\n if (! d.contains(x))\r\n d(x) = new ArrayBuffer[Int]()\r\n if (d(x).length < k)\r\n d(x).append(i)\r\n }\r\n var cnt = 0\r\n for ((key, value) <- d)\r\n cnt += value.length\r\n cnt -= cnt % k\r\n for ((key, value) <- d) {\r\n var i = 0\r\n while (cnt > 0 && i < value.length) {\r\n a(value(i)) = if (cnt % k > 0) cnt % k else k\r\n cnt -= 1\r\n i += 1\r\n }\r\n }\r\n for (i <- 1 to n) {\r\n writer.print(a(i) + \" \")\r\n a(i) = 0\r\n }\r\n writer.println()\r\n writer.flush()\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object B2 extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n val cn = Array.fill(n)(0)\r\n\r\n val in = {\r\n val ai2is = Array.fill(n + 1)(List.empty[Int])\r\n (0 until n).foreach { i => ai2is(an(i)) ::= i }\r\n ai2is.flatMap(_.take(k))\r\n }\r\n\r\n ((in.length % k) until in.length).foreach { j =>\r\n val (i, ci) = (in(j), (j % k) + 1)\r\n cn(i) = ci\r\n }\r\n\r\n println(cn.mkString(\" \"))\r\n }\r\n}\r\n"}, {"source_code": "object B2 extends App {\r\n import scala.reflect._\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n val cn = {\r\n val cn = Array.fill(n)(0)\r\n\r\n val in = {\r\n val ai2is = Array.fill(n + 1)(List.empty[Int])\r\n (0 until n).foreach(i => ai2is(an(i)) ::= i)\r\n ai2is.flatMap(_.take(k))\r\n }\r\n\r\n ((in.length % k) until in.length).foreach { j =>\r\n val (i, ci) = (in(j), (j % k) + 1)\r\n cn(i) = ci\r\n }\r\n\r\n cn\r\n }\r\n\r\n println(cn.mkString(\" \"))\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object B2 extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n val cn = {\r\n val counts = {\r\n val array = Array.fill(n + 1)(0)\r\n an.foreach { ai => array(ai) = k min (array(ai) + 1) }\r\n array.map { c => (c, c == k) }\r\n }\r\n\r\n var color = k\r\n var ignore = counts.foldLeft(0) {\r\n case (sum, (count, false)) if count > 0 => (sum + count) % k\r\n case (sum, _) => sum\r\n }\r\n\r\n an.map { ai =>\r\n counts(ai) match {\r\n case (ci, true) =>\r\n counts(ai) = (0 max (ci - 1), true)\r\n ci\r\n case (_, false) =>\r\n if (ignore > 0) {\r\n ignore -= 1\r\n 0\r\n } else {\r\n val ci = color\r\n color = if (color == 1) k else (color - 1)\r\n ci\r\n }\r\n }\r\n }\r\n }\r\n\r\n println(cn.mkString(\" \"))\r\n }\r\n}\r\n"}, {"source_code": "object B2 extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n val cn = {\r\n val counts = {\r\n val array = Array.fill(n + 1)(0)\r\n an.foreach { ai => array(ai) = k min (array(ai) + 1) }\r\n\r\n array.map(c => (c, c == k))\r\n }\r\n\r\n var color = k\r\n var composed = counts.foldLeft(0) {\r\n case (sum, (c, _)) if c < k => sum + c\r\n case (sum, _) => sum\r\n } / k\r\n\r\n an.map { ai =>\r\n counts(ai) match {\r\n case (ci, true) if ci > 0 =>\r\n counts(ai) = (ci - 1, true)\r\n ci\r\n case (ci, false) if ci > 0 && composed > 0 =>\r\n counts(ai) = (ci - 1, false)\r\n val cj = color\r\n if (color == 1) {\r\n color = k\r\n composed -= 1\r\n } else {\r\n color -= 1\r\n }\r\n cj\r\n case _ => 0\r\n }\r\n }\r\n\r\n }\r\n\r\n println(cn.mkString(\" \"))\r\n }\r\n}\r\n"}], "src_uid": "98aca7d5bf74c7787bf2159770054297"} {"source_code": "object C1060 {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val temp = stdin.readLine.split(\" \")\n val (n, m) = (temp(0).toInt, temp(1).toInt)\n val a = stdin.readLine.trim.split(\" \").map(_.toLong)\n val b = stdin.readLine.trim.split(\" \").map(_.toLong)\n val x = stdin.readInt()\n\n import scala.util.control.Breaks._\n def sum(array: Array[Long]):Array[Long] ={\n val res = Array.fill[Long](array.length)(Long.MaxValue)\n for (i <- array.indices){\n var temp = 0L\n for (j <- array.indices if i+j < array.length){\n temp = temp + array(i+j)\n res(j) = math.min(res(j), temp)\n }\n }\n res\n }\n\n val (sa, sb) = (sum(a), sum(b))\n var ans = 0\n for (i <- sa.indices){\n breakable{\n for (j <- sb.indices){\n if (sa(i) * sb(j) <= x){\n ans = math.max(ans, (i+1)*(j+1))\n } else break\n }\n }\n\n }\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M = ni()\n val A = na(N)\n val B = na(M)\n val X = ni()\n\n def cum(as: Array[Int]) = {\n val c = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n c(i + 1) = c(i) + as(i)\n }\n c\n }\n\n def calcMinLen(n: Int, cum: Array[Int]) = {\n val len = Array.fill[Int](2001)(Integer.MAX_VALUE)\n rep(n) { l =>\n l until n foreach { r =>\n val i = r - l + 1\n len(i) = min(len(i), cum(r + 1) - cum(l))\n }\n }\n len\n }\n\n val cumA = cum(A)\n val cumB = cum(B)\n\n val minALen = calcMinLen(N, cumA)\n val minBLen = calcMinLen(M, cumB)\n\n var ans = 0\n rep(2000, 1) { aLen =>\n rep(2000, 1) { bLen =>\n val v = minALen(aLen).toLong * minBLen(bLen)\n if (v <= X) ans = max(ans, aLen * bLen)\n }\n }\n\n out.println(ans)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "object C1060 {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val temp = stdin.readLine.split(\" \")\n val (n, m) = (temp(0).toInt, temp(1).toInt)\n val a = stdin.readLine.trim.split(\" \").map(_.toLong)\n val b = stdin.readLine.trim.split(\" \").map(_.toLong)\n val x = stdin.readInt()\n \n def sum(array: Array[Long]): Array[Long] = {\n val res = Array.fill[Long](array.length)(Long.MaxValue)\n for (i <- array.indices) {\n var temp = 0L\n for (j <- array.indices if i + j < array.length) {\n temp = temp + array(i + j)\n res(j) = math.min(res(j), temp)\n }\n }\n res\n }\n\n val (sa, sb) = (sum(a), sum(b))\n var ans = 0\n for (i <- sa.indices) {\n for (j <- sb.indices if sa(i) * sb(j) <= x) {\n ans = math.max(ans, (i + 1) * (j + 1))\n }\n }\n\n println(ans)\n }\n}\n"}], "negative_code": [], "src_uid": "b100573dfd15cf99842996d91bf26f5f"} {"source_code": "object Main extends App {\n val r = new FastScanner(java.lang.System.in)\n val o = new java.io.PrintWriter(java.lang.System.out)\n for(_ <- 1 to r.nextInt()) {\n val s = r.nextToken()\n o.print(s(0))\n for(k <- 1 until s.length by 2) {\n o.print(s(k))\n }\n o.println()\n }\n o.close()\n}\n\nimport scala.annotation.tailrec\nimport scala.collection.mutable.StringBuilder\n\nobject FastScanner {\n val zero = 0.toByte\n val cr = '\\r'.toByte\n val nl = '\\n'.toByte\n val BUFFER_SIZE = 0x10000\n}\n\nclass FastScanner(private val input: java.io.InputStream) {\n private val b = new Array[Byte](FastScanner.BUFFER_SIZE)\n private var n = 0\n private var pos = 0\n private var eof = false\n private def read ():Boolean = {\n if (eof) {\n return false\n }\n pos = 0\n n = input.read(b)\n if (n < 0) {\n eof = true\n }\n n > 0\n }\n private def nextByte(): Byte = {\n if (pos >= n && !read ()) {\n 0\n } else {\n val r = b(pos)\n pos += 1\n r\n }\n }\n def nextToken(k: Int = -1): String = {\n val sb = if(k >= 0) new StringBuilder(k) else new StringBuilder()\n var b = skipBlanks()\n assert(b > 0)\n while(b > 32) {\n sb.append(b.toChar)\n b = nextByte()\n }\n sb.toString\n }\n @tailrec\n private def skipBlanks(): Byte = {\n val b = nextByte()\n if(b > 32 || b < 1) b else skipBlanks()\n }\n def nextInt():Int = {\n val b = skipBlanks()\n @tailrec\n def f(t: Int): Int = {\n val b = nextByte ()\n if (b <= 32) t else f(10 * t + (b - 48))\n }\n require(b > 0)\n if (b < 48) -f(0) else f(b - 48)\n }\n}\n\n", "positive_code": [{"source_code": "//package codeforces.contests._1367\n\nobject _1 {\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n\n val s = io.StdIn.readLine\n println(s.indices.by(2).map(s).mkString + s.last)\n }\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val b = readLine().toCharArray.toList\n handle(b)\n }\n }\n\n def handle(list: List[Char]): Unit = {\n print(list.head)\n list.tail.zipWithIndex.foreach(tup => if (tup._2 % 2 == 0) print(tup._1))\n println()\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val n = StdIn.readLine().toInt\n for (_ <- 1 to n) {\n val str = StdIn.readLine()\n var res = \"\" + str.head\n for (i <- 1 until str.length by 2) {\n res += str(i)\n }\n println(res)\n }\n }\n}"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val b = readLine()\n val a = b.init.zipWithIndex.collect { case (c, i) if i % 2 == 0 => c }.mkString + b.last\n\n println(a)\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n\n val t = readInt()\n 1 to t foreach { _ =>\n val A = readLine().toCharArray\n val a = A(0)\n val b = A(1)\n\n val rest = 3 until A.length by 2 map { i =>\n A(i)\n }\n\n println(\"\" + a + b + rest.mkString)\n }\n\n}\n"}, {"source_code": "object A extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n var n = nextInt\n\n 1.to(n).foreach(_ => {\n val b = nextString\n val max = b.length\n for (a <- 0 until max by 2){\n print(b(a))\n }\n println(b(max - 1))\n })\n\n\n// out.println(a.reduceLeft[Int](_+_))\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}"}], "negative_code": [], "src_uid": "ac77e2e6c86b5528b401debe9f68fc8e"} {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n\n def pow(n: Long, p: Int): Long = {\n var res = 1L\n var i = 0\n while (i < p) {\n res *= n\n i += 1\n }\n res\n }\n\n def root(number: Long, p: Int): Long = {\n var n = Math.pow(number, 1d / p).toLong\n while (pow(n + 1, p) <= number) n += 1\n n\n }\n\n val Array(n) = readInts(1)\n val as = Array.fill(n){ readLine.toLong }\n val as0 = as.clone()\n\n val divisors = mutable.LongMap.empty[Int].withDefaultValue(0)\n\n def add(p: Long, cnt: Int): Unit = {\n divisors(p) += cnt\n }\n\n for (i <- as.indices) if (as(i) > 1) {\n val r4 = root(as(i), 4)\n if (as(i) == pow(r4, 4)) {\n add(r4, 4)\n as(i) = 1\n } else {\n val r3 = root(as(i), 3)\n if (as(i) == pow(r3, 3)) {\n add(r3, 3)\n as(i) = 1\n } else {\n val r2 = root(as(i), 2)\n if (as(i) == pow(r2, 2)) {\n add(r2, 2)\n as(i) = 1\n }\n }\n }\n }\n\n val gcds = mutable.Set.empty[Long]\n gcds ++= divisors.keys\n\n var i = 0\n while (i < n) {\n if (as(i) > 1) {\n var j = i + 1\n while (j < n) {\n if (as(j) > 1) {}\n val d = gcd(as(i), as(j))\n if (d > 1) gcds += d\n j += 1\n }\n }\n i += 1\n }\n\n for (g <- gcds) {\n var i = 0\n while (i < n) {\n if (as(i) != g && as(i) % g == 0) {\n add(g, 1)\n as(i) /= g\n if (as(i) > 1) {\n add(as(i), 1)\n as(i) = 1\n }\n }\n i += 1\n }\n }\n\n val composites = mutable.LongMap.empty[Int].withDefaultValue(0)\n i = 0\n while (i < n) {\n if (as(i) == as0(i)) composites(as(i)) += 1\n i += 1\n }\n\n val MOD = 998244353L\n var res = 1L\n for ((_, v) <- divisors) {\n res = res * (v + 1) % MOD\n }\n for ((_, v) <- composites) {\n res = res * (v + 1) * (v + 1) % MOD\n }\n\n println(res)\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 998244353\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = nal(N)\n val f = mutable.Map[Long, Int]() withDefaultValue 0\n val ab = mutable.Map[Long, Int]() withDefaultValue 0\n\n rep(N) { i =>\n val sqrt = math.sqrt(A(i)).toLong\n val cbrb = math.cbrt(A(i)).toLong\n val quort = math.sqrt(sqrt).toLong\n if (quort * quort * quort * quort == A(i)) {\n f(quort) = f(quort) + 4\n } else if (sqrt * sqrt == A(i)) {\n f(sqrt) = f(sqrt) + 2\n } else if (cbrb * cbrb * cbrb == A(i)) {\n f(cbrb) = f(cbrb) + 3\n } else {\n ab(A(i)) = ab(A(i)) + 1\n }\n }\n\n val ab_seq = ab.keys.toSeq\n val ab_f = mutable.Set[Long]()\n rep(ab_seq.length) { i =>\n i + 1 until ab_seq.length foreach { j =>\n val g = gcd(ab_seq(i), ab_seq(j))\n if (g > 1) {\n ab_f += g\n ab_f += ab_seq(i) / g\n ab_f += ab_seq(j) / g\n }\n }\n }\n\n def findFactor(a: Long): Option[Long] = {\n f.keys.find(a % _ == 0) orElse ab_f.find(a % _ == 0)\n }\n\n var ans = 1L\n ab_seq.zipWithIndex foreach { case (x, i) =>\n val cnt = ab(x)\n findFactor(x) match {\n case Some(a) =>\n val b = x / a\n f(a) = f(a) + cnt\n f(b) = f(b) + cnt\n\n case None => ans = ans * (cnt + 1) * (cnt + 1) % MOD\n }\n }\n\n f.foreach { case (_, cnt) =>\n ans = ans * (cnt + 1) % MOD\n }\n\n out.println(ans)\n }\n\n def gcd(a: Long, b: Long): Long = {\n if (b == 0) a\n else gcd(b, a % b)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n\n def pow(n: Long, p: Int): Long = {\n var res = 1L\n var i = 0\n while (i < p) {\n res *= n\n i += 1\n }\n res\n }\n\n def root(number: Long, p: Int): Long = {\n var n = Math.pow(number, 1d / p).toLong\n while (pow(n + 1, p) <= number) n += 1\n n\n }\n\n val Array(n) = readInts(1)\n val as = Array.fill(n){ readLine.toLong }\n\n val divisors = mutable.LongMap.empty[Int].withDefaultValue(0)\n\n def add(p: Long, cnt: Int): Unit = {\n divisors(p) += cnt\n }\n\n for (i <- as.indices) if (as(i) > 1) {\n val r4 = root(as(i), 4)\n if (as(i) == pow(r4, 4)) {\n add(r4, 4)\n as(i) = 1\n } else {\n val r3 = root(as(i), 3)\n if (as(i) == pow(r3, 3)) {\n add(r3, 3)\n as(i) = 1\n } else {\n val r2 = root(as(i), 2)\n if (as(i) == pow(r2, 2)) {\n add(r2, 2)\n as(i) = 1\n }\n }\n }\n }\n\n val gcds = mutable.Set.empty[Long]\n gcds ++= divisors.keys\n\n for {\n i <- 0 until n\n if as(i) > 1\n j <- i + 1 until n\n if as(j) > 1\n d = gcd(as(i), as(j))\n if d > 1\n } gcds += d\n\n for {\n g <- gcds.toSeq.sorted\n i <- 0 until n\n if as(i) != g && as(i) % g == 0\n } {\n add(g, 1)\n as(i) /= g\n if (as(i) > 1) {\n add(as(i), 1)\n as(i) = 1\n }\n }\n\n val composites = mutable.LongMap.empty[Int].withDefaultValue(0)\n for (a <- as) if (a > 1) composites(a) += 1\n\n val MOD = 998244353L\n var res = 1L\n for ((_, v) <- divisors) {\n res = res * (v + 1) % MOD\n }\n for ((_, v) <- composites) {\n res = res * (v + 1) * (v + 1) % MOD\n }\n\n println(res)\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n\n def pow(n: Long, p: Int): Long = {\n var res = 1L\n var i = 0\n while (i < p) {\n res *= n\n i += 1\n }\n res\n }\n\n def root(number: Long, p: Int): Long = {\n var n = Math.pow(number, 1d / p).toLong\n while (pow(n + 1, p) <= number) n += 1\n n\n }\n\n val Array(n) = readInts(1)\n val as = Array.fill(n){ readLine.toLong }\n\n val divisors = mutable.LongMap.empty[Int].withDefaultValue(0)\n\n def add(p: Long, cnt: Int): Unit = {\n divisors(p) += cnt\n }\n\n for (i <- as.indices) if (as(i) > 1) {\n val r4 = root(as(i), 4)\n if (as(i) == pow(r4, 4)) {\n add(r4, 4)\n as(i) = 1\n } else {\n val r3 = root(as(i), 3)\n if (as(i) == pow(r3, 3)) {\n add(r3, 3)\n as(i) = 1\n } else {\n val r2 = root(as(i), 2)\n if (as(i) == pow(r2, 2)) {\n add(r2, 2)\n as(i) = 1\n }\n }\n }\n }\n\n val gcds = mutable.Set.empty[Long]\n gcds ++= divisors.keys\n\n for {\n i <- 0 until n\n if as(i) > 1\n j <- i + 1 until n\n if as(j) > 1\n d = gcd(as(i), as(j))\n if d > 1\n } gcds += d\n\n for {\n g <- gcds.toSeq.sorted\n i <- 0 until n\n if as(i) != g && as(i) % g == 0\n } {\n add(g, 1)\n as(i) /= g\n if (as(i) > 1) {\n add(as(i), 1)\n as(i) = 1\n }\n }\n\n val composites = mutable.LongMap.empty[Int].withDefaultValue(0)\n for (a <- as) if (a > 1) composites(a) += 1\n\n val MOD = 998244353L\n var res = 1L\n for ((_, v) <- divisors) {\n res = res * (v + 1) % MOD\n }\n for ((_, v) <- composites) {\n res = res * (v + 1) * (v + 1) % MOD\n }\n\n println(res)\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n\n def sqrt(number: Long): Long = {\n def next(n: Long, i: Long): Long = (n + i / n) >> 1\n\n val one = 1L\n\n var n = one\n var n1 = next(n, number)\n\n while ((n1 - n).abs > one) {\n n = n1\n n1 = next(n, number)\n }\n\n while (n1 * n1 > number) {\n n1 -= one\n }\n\n n1\n }\n\n val Array(n) = readInts(1)\n val as = Array.fill(n){ readLine.toLong }\n\n val LIMIT = 1259929\n val LIMIT_SQRT = Math.sqrt(LIMIT).toInt + 1\n val isPrime = Array.fill(LIMIT)(true)\n val primesBuilder = new mutable.ArrayBuilder.ofInt\n primesBuilder += 2\n isPrime(0) = false\n isPrime(1) = false\n\n var i = 4\n while (i < LIMIT) {\n isPrime(i) = false\n i += 2\n }\n i = 3\n while (i <= LIMIT_SQRT) {\n if (isPrime(i)) {\n primesBuilder += i\n var j = i * i\n val ii = i + i\n while (j < LIMIT) {\n isPrime(j) = false\n j += ii\n }\n }\n i += 2\n }\n\n val primes = primesBuilder.result()\n\n val divisors = mutable.Map.empty[Long, Int].withDefaultValue(0)\n\n def add(p: Long, cnt: Int): Unit = {\n divisors(p) += cnt\n }\n\n for (j <- as.indices) {\n var aa = as(j)\n var i = 0\n while (i < primes.length && aa >= primes(i)) {\n val p = primes(i)\n if (aa % p == 0) {\n aa /= p\n add(p, 1)\n } else i += 1\n }\n as(j) = aa\n }\n\n val gcdsBuilder = new mutable.ArrayBuilder.ofLong\n val haveGcd = mutable.Set.empty[Long]\n\n i = 0\n while (i < n) {\n if (as(i) > 1) {\n var j = i + 1\n while (j < n) {\n if (as(j) > 1) {\n val d = gcd(as(i), as(j))\n if (d > 1 && !haveGcd(d)) {\n gcdsBuilder += d\n haveGcd += d\n }\n }\n j += 1\n }\n }\n i += 1\n }\n\n val gcds = gcdsBuilder.result()\n var j = 0\n while (j < gcds.length) {\n val g = gcds(j)\n var i = 0\n while (i < as.length) {\n if (as(i) % g == 0) {\n as(i) /= g\n add(g, 1)\n }\n i += 1\n }\n j += 1\n }\n\n var unknownDivisors = 0\n for (i <- as.indices) if (as(i) > 1) {\n val r = sqrt(as(i))\n if (as(i) == r * r) add(r, 2)\n else {\n if ((as(i) < isPrime.length && isPrime(as(i).toInt))\n || BigInt(as(i)).isProbablePrime(20)) add(as(i), 1)\n else unknownDivisors += 2\n }\n }\n\n val MOD = 998244353L\n var res = 1L\n for ((_, v) <- divisors) {\n res = res * (v + 1) % MOD\n }\n for (_ <- 1 to unknownDivisors) res = res * 2 % MOD\n\n println(res)\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n\n def next(n: Long, i: Long): Long = (n + i / n) >> 1\n\n def pow(n: Long, p: Int): Long = {\n var res = 1L\n for (_ <- 1 to p) res *= n\n res\n }\n\n def root(number: Long, p: Int): Long = {\n\n var n = 1L\n var n1 = next(n, number)\n\n while ((n1 - n).abs > 1) {\n n = n1\n n1 = next(n, number)\n }\n\n while (pow(n1, p) > number) n1 -= 1\n\n n1\n }\n\n val Array(n) = readInts(1)\n val as = Array.fill(n){ readLine.toLong }\n val as0 = as.clone()\n\n val divisors = mutable.Map.empty[Long, Int].withDefaultValue(0)\n\n def add(p: Long, cnt: Int): Unit = {\n divisors(p) += cnt\n }\n\n for (i <- as.indices) if (as(i) > 1) {\n val r4 = root(as(i), 4)\n if (as(i) == pow(r4, 4)) {\n add(r4, 3)\n as(i) = r4\n } else {\n val r3 = root(as(i), 3)\n if (as(i) == pow(r3, 3)) {\n add(r3, 2)\n as(i) = r3\n } else {\n val r2 = root(as(i), 2)\n if (as(i) == pow(r2, 2)) {\n add(r2, 1)\n as(i) = r2\n }\n }\n }\n }\n\n val gcds = mutable.Set.empty[Long]\n for {\n i <- 0 until n\n if as(i) > 1\n j <- i + 1 until n\n if as(j) > 1\n d = gcd(as(i), as(j))\n if d > 1\n } gcds += d\n\n for {\n g <- gcds\n i <- 0 until n\n if as(i) % g == 0\n } {\n as(i) /= g\n add(g, 1)\n }\n\n val MOD = 998244353L\n var res = 1L\n for ((_, v) <- divisors) {\n res = res * (v + 1) % MOD\n }\n for (i <- 0 until n) {\n if (as(i) > 1) {\n res = if (as(i) == as0(i)) res * 4 % MOD else res * 2 % MOD\n }\n }\n\n println(res)\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n\n def next(n: Long, i: Long): Long = (n + i / n) >> 1\n\n def pow(n: Long, p: Int): Long = {\n var res = 1L\n for (_ <- 1 to p) res *= n\n res\n }\n\n def root(number: Long, p: Int): Long = {\n\n var n = 1L\n var n1 = next(n, number)\n\n while ((n1 - n).abs > 1) {\n n = n1\n n1 = next(n, number)\n }\n\n while (pow(n1, p) > number) n1 -= 1\n\n n1\n }\n\n val Array(n) = readInts(1)\n val as = Array.fill(n){ readLine.toLong }\n val as0 = as.clone()\n\n val divisors = mutable.Map.empty[Long, Int].withDefaultValue(0)\n\n def add(p: Long, cnt: Int): Unit = {\n divisors(p) += cnt\n }\n\n for (i <- as.indices) if (as(i) > 1) {\n val r4 = root(as(i), 4)\n if (as(i) == pow(r4, 4)) {\n add(r4, 3)\n as(i) = r4\n } else {\n val r3 = root(as(i), 3)\n if (as(i) == pow(r3, 3)) {\n add(r3, 2)\n as(i) = r3\n } else {\n val r2 = root(as(i), 2)\n if (as(i) == pow(r2, 2)) {\n add(r2, 1)\n as(i) = r2\n }\n }\n }\n }\n\n val gcds = mutable.Set.empty[Long]\n for {\n i <- 0 until n\n if as(i) > 1\n j <- i + 1 until n\n if as(j) > 1\n d = gcd(as(i), as(j))\n if d > 1\n } gcds += d\n\n for {\n g <- gcds\n i <- 0 until n\n if as(i) % g == 0\n } {\n as(i) /= g\n add(g, 1)\n }\n\n var unknownDivisors = 0\n for (i <- 0 until n) {\n if (as(i) > 1) {\n if (divisors.contains(as(i))) add(as(i), 1)\n else if (as(i) == as0(i)) unknownDivisors += 2\n else unknownDivisors += 1\n }\n }\n\n val MOD = 998244353L\n var res = 1L\n for ((_, v) <- divisors) {\n res = res * (v + 1) % MOD\n }\n for (_ <- 1 to unknownDivisors) res = res * 2 % MOD\n\n println(res)\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n\n def sqrt(number: Long): Long = {\n def next(n: Long, i: Long): Long = (n + i / n) >> 1\n\n val one = 1L\n\n var n = one\n var n1 = next(n, number)\n\n while ((n1 - n).abs > one) {\n n = n1\n n1 = next(n, number)\n }\n\n while (n1 * n1 > number) {\n n1 -= one\n }\n\n n1\n }\n\n val Array(n) = readInts(1)\n val as = Array.fill(n){ readLine.toLong }\n\n val LIMIT = 1259929\n val isPrime = Array.fill(LIMIT)(true)\n isPrime(0) = false\n isPrime(1) = false\n\n var i = 2\n while (i * i < LIMIT) {\n if (isPrime(i)) {\n var j = i * i\n val ii = i + i\n while (j < LIMIT) {\n isPrime(j) = false\n j += ii\n }\n }\n i += 1\n }\n\n val primes = Array.ofDim[Int](97178)\n i = 0\n var j = 0\n while (i < LIMIT) {\n if (isPrime(i)) {\n primes(j) = i\n j += 1\n }\n i += 1\n }\n\n val divisors = mutable.Map.empty[Long, Int].withDefaultValue(0)\n\n def add(p: Long, cnt: Int): Unit = {\n divisors(p) += cnt\n }\n\n for (j <- as.indices) {\n var aa = as(j)\n var i = 0\n while (i < primes.length && aa >= primes(i)) {\n val p = primes(i)\n if (aa % p == 0) {\n aa /= p\n add(p, 1)\n } else i += 1\n }\n as(j) = aa\n }\n\n val gcdsBuilder = new mutable.ArrayBuilder.ofLong\n val haveGcd = mutable.Set.empty[Long]\n\n i = 0\n while (i < n) {\n if (as(i) > 1) {\n var j = i + 1\n while (j < n) {\n if (as(j) > 1) {\n val d = gcd(as(i), as(j))\n if (d > 1 && !haveGcd(d)) {\n gcdsBuilder += d\n haveGcd += d\n }\n }\n j += 1\n }\n }\n i += 1\n }\n\n val gcds = gcdsBuilder.result()\n j = 0\n while (j < gcds.length) {\n val g = gcds(j)\n var i = 0\n while (i < as.length) {\n if (as(i) % g == 0) {\n as(i) /= g\n add(g, 1)\n }\n i += 1\n }\n j += 1\n }\n\n var unknownDivisors = 0\n for (i <- as.indices) if (as(i) > 1) {\n val r = sqrt(as(i))\n if (as(i) == r * r) add(r, 2)\n else {\n if ((as(i) < isPrime.length && isPrime(as(i).toInt))\n || BigInt(as(i)).isProbablePrime(20)) add(as(i), 1)\n else unknownDivisors += 2\n }\n }\n\n val MOD = 998244353L\n var res = 1L\n for ((_, v) <- divisors) {\n res = res * (v + 1) % MOD\n }\n for (_ <- 1 to unknownDivisors) res = res * 2 % MOD\n\n println(res)\n}"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n\n def sqrt(number: Long): Long = {\n def next(n: Long, i: Long): Long = (n + i / n) >> 1\n\n val one = 1L\n\n var n = one\n var n1 = next(n, number)\n\n while ((n1 - n).abs > one) {\n n = n1\n n1 = next(n, number)\n }\n\n while (n1 * n1 > number) {\n n1 -= one\n }\n\n n1\n }\n\n val Array(n) = readInts(1)\n val as = Array.fill(n){ readLine.toLong }\n\n val LIMIT = 1259929\n val LIMIT_SQRT = Math.sqrt(LIMIT).toInt + 1\n val isPrime = Array.fill(LIMIT)(true)\n val primesBuilder = new mutable.ArrayBuilder.ofInt\n primesBuilder += 2\n isPrime(0) = false\n isPrime(1) = false\n\n var i = 4\n while (i < LIMIT) {\n isPrime(i) = false\n i += 2\n }\n i = 3\n while (i * i < LIMIT_SQRT) {\n if (isPrime(i)) {\n primesBuilder += i\n var j = i * i\n val ii = i + i\n while (j < LIMIT) {\n isPrime(j) = false\n j += ii\n }\n }\n i += 2\n }\n\n val primes = primesBuilder.result()\n\n val divisors = mutable.Map.empty[Long, Int].withDefaultValue(0)\n\n def add(p: Long, cnt: Int): Unit = {\n divisors(p) += cnt\n }\n\n for (j <- as.indices) {\n var aa = as(j)\n var i = 0\n while (i < primes.length && aa >= primes(i)) {\n val p = primes(i)\n if (aa % p == 0) {\n aa /= p\n add(p, 1)\n } else i += 1\n }\n as(j) = aa\n }\n\n val gcdsBuilder = new mutable.ArrayBuilder.ofLong\n val haveGcd = mutable.Set.empty[Long]\n\n i = 0\n while (i < n) {\n if (as(i) > 1) {\n var j = i + 1\n while (j < n) {\n if (as(j) > 1) {\n val d = gcd(as(i), as(j))\n if (d > 1 && !haveGcd(d)) {\n gcdsBuilder += d\n haveGcd += d\n }\n }\n j += 1\n }\n }\n i += 1\n }\n\n val gcds = gcdsBuilder.result()\n var j = 0\n while (j < gcds.length) {\n val g = gcds(j)\n var i = 0\n while (i < as.length) {\n if (as(i) % g == 0) {\n as(i) /= g\n add(g, 1)\n }\n i += 1\n }\n j += 1\n }\n\n var unknownDivisors = 0\n for (i <- as.indices) if (as(i) > 1) {\n val r = sqrt(as(i))\n if (as(i) == r * r) add(r, 2)\n else {\n if ((as(i) < isPrime.length && isPrime(as(i).toInt))\n || BigInt(as(i)).isProbablePrime(20)) add(as(i), 1)\n else unknownDivisors += 2\n }\n }\n\n val MOD = 998244353L\n var res = 1L\n for ((_, v) <- divisors) {\n res = res * (v + 1) % MOD\n }\n for (_ <- 1 to unknownDivisors) res = res * 2 % MOD\n\n println(res)\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n\n def sqrt(number: Long): Long = {\n def next(n: Long, i: Long): Long = (n + i / n) >> 1\n\n val one = 1L\n\n var n = one\n var n1 = next(n, number)\n\n while ((n1 - n).abs > one) {\n n = n1\n n1 = next(n, number)\n }\n\n while (n1 * n1 > number) {\n n1 -= one\n }\n\n n1\n }\n\n val Array(n) = readInts(1)\n val as = Array.fill(n){ readLine.toLong }\n\n val LIMIT = 1259929\n val LIMIT_SQRT = Math.sqrt(LIMIT).toInt + 1\n val isPrime = Array.fill(LIMIT)(true)\n val primesBuilder = new mutable.ArrayBuilder.ofInt\n isPrime(0) = false\n isPrime(1) = false\n\n var i = 4\n while (i < LIMIT) {\n isPrime(i) = false\n i += 2\n }\n i = 3\n while (i * i < LIMIT_SQRT) {\n if (isPrime(i)) {\n primesBuilder += i\n var j = i * i\n val ii = i + i\n while (j < LIMIT) {\n isPrime(j) = false\n j += ii\n }\n }\n i += 2\n }\n\n val primes = primesBuilder.result()\n\n val divisors = mutable.Map.empty[Long, Int].withDefaultValue(0)\n\n def add(p: Long, cnt: Int): Unit = {\n divisors(p) += cnt\n }\n\n for (j <- as.indices) {\n var aa = as(j)\n var i = 0\n while (i < primes.length && aa >= primes(i)) {\n val p = primes(i)\n if (aa % p == 0) {\n aa /= p\n add(p, 1)\n } else i += 1\n }\n as(j) = aa\n }\n\n val gcdsBuilder = new mutable.ArrayBuilder.ofLong\n val haveGcd = mutable.Set.empty[Long]\n\n i = 0\n while (i < n) {\n if (as(i) > 1) {\n var j = i + 1\n while (j < n) {\n if (as(j) > 1) {\n val d = gcd(as(i), as(j))\n if (d > 1 && !haveGcd(d)) {\n gcdsBuilder += d\n haveGcd += d\n }\n }\n j += 1\n }\n }\n i += 1\n }\n\n val gcds = gcdsBuilder.result()\n var j = 0\n while (j < gcds.length) {\n val g = gcds(j)\n var i = 0\n while (i < as.length) {\n if (as(i) % g == 0) {\n as(i) /= g\n add(g, 1)\n }\n i += 1\n }\n j += 1\n }\n\n var unknownDivisors = 0\n for (i <- as.indices) if (as(i) > 1) {\n val r = sqrt(as(i))\n if (as(i) == r * r) add(r, 2)\n else {\n if ((as(i) < isPrime.length && isPrime(as(i).toInt))\n || BigInt(as(i)).isProbablePrime(20)) add(as(i), 1)\n else unknownDivisors += 2\n }\n }\n\n val MOD = 998244353L\n var res = 1L\n for ((_, v) <- divisors) {\n res = res * (v + 1) % MOD\n }\n for (_ <- 1 to unknownDivisors) res = res * 2 % MOD\n\n println(res)\n}"}], "src_uid": "4ca7837d1ddf80f0bde4aac2fb37d60b"} {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, q) = readLongs(2)\n\n val res = Array.ofDim[Long](q.toInt)\n val half = n * n / 2\n\n for (i <- 0 until q.toInt) {\n val Array(x, y) = readLongs(2)\n val xy = (x - 1) * n + y - 1\n res(i) = if ((x + y) % 2 == 0) xy / 2 + 1 else half + xy / 2 + 1 + n % 2\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\"\\n\"))\n\n Console.flush\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N = sc.nextLong()\n val Q = sc.nextInt()\n rep(Q) { i =>\n var x, y = sc.nextInt() - 1\n if ((x + y) % 2 == 1) x += N.toInt\n val ans =\n x / 2 * N +\n (if(x % 2 == 1) (N - 1) / 2 + 1 else 0) +\n y / 2 +\n 1\n out.println(ans)\n\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject B extends App {\n\n def solve(in: InputReader): Unit = {\n val sb = StringBuilder.newBuilder\n val n = in.nextLong\n val q = in.nextInt\n\n for (_ <- 1 to q) {\n val y = in.nextLong\n val x = in.nextLong\n val r = if (x % 2 == 1 && y % 2 == 1)\n y / 2 * n + (x + 1) / 2\n else if (x % 2 == 0 && y % 2 == 1)\n (n * n + 1) / 2 + y / 2 * n + x / 2\n else if (x % 2 == 1 && y % 2 == 0)\n (n + 1) * n / 2 + (y - 1) / 2 * n + (x + 1) / 2\n else\n (y / 2 * n) - (n - x) / 2\n sb.append(r)\n sb.append('\\n')\n }\n print(sb.toString())\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n \n def nextLong: Long = {\n next.toLong\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject B extends App {\n\n def solve(in: InputReader): Unit = {\n val sb = StringBuilder.newBuilder\n val n = in.nextInt\n val q = in.nextInt\n\n for (i <- 1 to q) {\n val y = in.nextInt.toLong\n val x = in.nextInt.toLong\n val r = if (x % 2 == 1 && y % 2 == 1)\n y / 2 * n + (x + 1) / 2\n else if (x % 2 == 0 && y % 2 == 1)\n (n * n + 1) / 2 + y / 2 * n + x / 2\n else if (x % 2 == 1 && y % 2 == 0)\n (n + 1) * n / 2 + (y - 1) / 2 * n + (x + 1) / 2\n else\n (y / 2 * n) - (n - x) / 2\n sb.append(r)\n if (i != q)\n sb.append('\\n')\n }\n println(sb.toString())\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject B extends App {\n\n def solve(in: InputReader): Unit = {\n val out = new PrintWriter(System.out)\n val n = in.nextInt\n val q = in.nextInt\n\n for (_ <- 1 to q) {\n val y = in.nextInt.toLong\n val x = in.nextInt.toLong\n val r = if (x % 2 == 1 && y % 2 == 1)\n y / 2 * n + (x + 1) / 2\n else if (x % 2 == 0 && y % 2 == 1)\n (n * n + 1) / 2 + y / 2 * n + x / 2\n else if (x % 2 == 1 && y % 2 == 0)\n (n + 1) * n / 2 + (y - 1) / 2 * n + (x + 1) / 2\n else\n (y / 2 * n) - (n - x) / 2\n out.println(r)\n }\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject B extends App {\n\n def solve(in: InputReader): Unit = {\n val out = new PrintWriter(System.out)\n val n = in.nextInt\n val q = in.nextInt\n\n for (_ <- 1 to q) {\n val x = in.nextInt.toLong\n val y = in.nextInt.toLong\n val r = if (x % 2 == 1 && y % 2 == 1)\n y / 2 * n + (x + 1) / 2\n else if (x % 2 == 0 && y % 2 == 1)\n (n * n + 1) / 2 + y / 2 * n + x / 2\n else if (x % 2 == 1 && y % 2 == 0)\n (n + 1) * n / 2 + (y - 1) / 2 * n + (x + 1) / 2\n else\n (y / 2 * n) - (n - x) / 2\n out.println(r)\n }\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}\n"}], "src_uid": "3c48123f326fb79ce2e4e17e1e0765f8"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline private final def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n = ni()\n val s = ns(n)\n var bal = 0\n\n val bals = Array.ofDim[Int](n)\n val cum = cumSum(s.map {\n case '(' => 1\n case ')' => -1\n case '?' => 0\n })\n val cumQ = cumSum(s.map {\n case '?' => 1\n case _ => 0\n })\n\n REP(n) { i =>\n if (s(i) == '(') {\n bal += 1\n } else if (s(i) == ')') {\n bal -= 1\n } else {\n if (bal + 1 + cum(n) - cum(i + 1) <= cumQ(n) - cumQ(i + 1)) {\n s(i) = '('\n bal += 1\n } else {\n s(i) = ')'\n bal -= 1\n }\n }\n bals(i) = bal\n }\n\n debug(bals)\n val ok = bal == 0 && bals.dropRight(1).forall(a => a > 0)\n\n if (ok) out.println(s.mkString)\n else out.println(\":(\")\n }\n}", "positive_code": [{"source_code": "import java.io.FileInputStream\nimport scala.collection.mutable.TreeSet\n\nobject HelloWorld {\n\n import scala.io.StdIn.{readInt, readLine}\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val str = readLine\n\n val ls = str.count(p => p == '(')\n\n var newLs = n / 2 - ls\n val newStr = str.map(c => {\n if (c == '?') {\n if (newLs > 0) {\n newLs -= 1\n '('\n }\n else ')'\n } else c\n })\n\n var st = 0\n for ((c, i) <- newStr.zipWithIndex) {\n if (c == '(') st += 1\n else {\n st -= 1\n if (st <= 0 && i < n-1) {\n println(\":(\")\n System.exit(0)\n }\n }\n }\n\n if (st == 0) println(newStr)\n else println(\":(\")\n\n }\n}\n"}], "negative_code": [], "src_uid": "e03bec836d52fe4784a5b4c62ab5b2c8"} {"source_code": "import scala.io.StdIn\r\nimport java.util.Scanner\r\n\r\nobject Main {\r\n def sort2(a: Array[Int], i: Int, j: Int) = {\r\n if(a(i) > a(j)){\r\n val tmp = a(i)\r\n a(i) = a(j)\r\n a(j) = tmp\r\n }\r\n }\r\n\r\n def solve() = {\r\n var a = new Array[Int](3)\r\n val inp = StdIn.readLine()\r\n val line = new Scanner(inp)\r\n for (i <- 0 to 2){\r\n a(i) = line.nextInt()\r\n }\r\n // sort\r\n sort2(a, 0, 1)\r\n sort2(a, 1, 2)\r\n sort2(a, 0, 1)\r\n\r\n if(a(0) + a(1) == a(2)\r\n || (a(0) == a(1) && 0 == (a(2) % 2))\r\n || (a(1) == a(2) && 0 == (a(0) % 2))){\r\n println(\"YES\")\r\n }else{\r\n println(\"NO\")\r\n }\r\n }\r\n\r\n def main(args: Array[String]) = {\r\n val tc = StdIn.readInt()\r\n for (i <- 1 to tc) {\r\n solve()\r\n }\r\n }\r\n}", "positive_code": [{"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val ls = nextInts(3).sorted\n val ok = (ls(0) + ls(1) == ls(2)) || (ls(0) == ls(1) && ls(2) % 2 == 0) ||\n (ls(0) == ls(2) && ls(1) % 2 == 0) || (ls(2) == ls(1) && ls(0) % 2 == 0)\n\n out.println(if(ok) \"YES\" else \"NO\")\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "a4a69a5fbf35781ff0849332a45566ca"} {"source_code": "//package codeforces\n\n/*\n\nhttp://codeforces.com/problemset/problem/839/C\n\n */\nobject Journeyy {\n\n type Graph = Map[Int, Set[Int]]\n\n def update(graph: Graph, x: Int, y: Int): Graph = {\n val setX: Set[Int] = graph.withDefaultValue(Set())(x)\n val setY: Set[Int] = graph.withDefaultValue(Set())(y)\n graph + (x -> (setX + y)) + (y -> (setY + x))\n }\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val graph: Graph = (1 until n).foldLeft[Graph](Map[Int, Set[Int]](1 -> Set(0)))((acc, _) => {\n val Array(x, y) = io.StdIn.readLine.split(\" \").map(_.toInt)\n update(acc, x, y)\n })\n\n println(calculateExpectedValue(1, 0, 0, 1.0))\n\n def calculateExpectedValue(me: Int, parent: Int, distance: Int, probability: Double): Double = {\n if (graph(me).size == 1) {\n probability * distance\n } else {\n val count = graph(me).size - 1\n val updatedProbability = probability * (1.0/count)\n\n graph(me).filter(_ != parent)\n .foldLeft[Double](0.0)((acc, child) => acc + calculateExpectedValue(child, parent = me, distance + 1, updatedProbability))\n }\n }\n }\n\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject Journey {\n var res=0D\n var graph:Array[ArrayBuffer[Int]]=null\n var vis:Array[Boolean]=null\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n var n=in.readInt()\n graph=Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer[Int]())\n for(_<- 0 until n-1){\n val edges=in.readLine().split(\" \").map(_.toInt-1)\n graph(edges(0))+=edges(1)\n graph(edges(1))+=edges(0)\n }\n vis=Array.fill[Boolean](n)(false)\n dfs(0,1.0,0.0)\n println(res)\n }\n def dfs(u:Int,prob:Double,depth:Double):Unit={\n if(!vis(u)){\n vis(u)=true\n if(graph(u).length==1)\n res += depth * prob\n\n for(v<- 0 until graph(u).length){\n if(u==0)\n dfs(graph(u)(v),prob/(graph(u).length+0.0),depth+1)\n else\n dfs(graph(u)(v),prob/(graph(u).length-1.0),depth+1)\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "adaae163882b064bf7257e82e8832ffb"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(val a: Int, val b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return a.compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n for (tt <- 1 to t) {\n var n = readInt()\n var a = new Array[Int](n)\n var b = new Array[Int](n)\n for (i <- 1 to n)\n a(i-1) = readInt()\n for (i <- 1 to n)\n b(i-1) = readInt()\n quickSort(a)\n quickSort(b)\n var ans = \"YES\"\n for (i <- 0 until n) {\n if (b(i) < a(i) || b(i) > a(i) + 1)\n ans = \"NO\"\n //writer.println(b(i) + \" \" + a(i))\n }\n writer.println(ans)\n }\n writer.flush()\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject ProblemC extends App {\n type TestCase = (Array[Int], Array[Int])\n type Result = String\n\n start()\n\n def start() = {\n println(parseInput(testCases).map(s => solve(s).mkString).mkString(\"\\n\"))\n }\n\n def testCases = StdIn.readLine.stripLineEnd.toInt\n\n def parseInput(testCases: Int): List[TestCase] = {\n var result: List[TestCase] = Nil\n for (_ <- 0.until(testCases)) {\n StdIn.readLine()\n val a = StdIn.readLine().split(\" \").map(_.stripLineEnd.trim.toInt).toArray\n val b = StdIn.readLine().split(\" \").map(_.stripLineEnd.trim.toInt).toArray\n result = (a,b) :: result\n }\n result.reverse\n }\n\n def solve(testCase: TestCase): Result = {\n (testCase._1.sorted zip testCase._2.sorted).map(ab => ab._1 - ab._2).forall(d => d == 0 || d == -1) match {\n case true => \"YES\"\n case false => \"NO\"\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject ProblemC extends App {\n type TestCase = (Array[Int], Array[Int])\n type Result = String\n\n start()\n\n def start() = {\n println(parseInput(testCases).map(s => solve(s).mkString).mkString(\"\\n\"))\n }\n\n def testCases = StdIn.readLine.stripLineEnd.toInt\n\n def parseInput(testCases: Int): List[TestCase] = {\n var result: List[TestCase] = Nil\n for (_ <- 0.until(testCases)) {\n StdIn.readLine()\n val a = StdIn.readLine().split(\" \").map(_.stripLineEnd.trim.toInt).toArray\n val b = StdIn.readLine().split(\" \").map(_.stripLineEnd.trim.toInt).toArray\n result = (a,b) :: result\n }\n result.reverse\n }\n\n def solve(testCase: TestCase): Result = {\n (testCase._1.sorted zip testCase._2.sorted).map(ab => ab._1 - ab._2).forall(diff => math.abs(diff) <= 1) match {\n case true => \"YES\"\n case false => \"NO\"\n }\n }\n\n}\n"}], "src_uid": "6ca98e655007bfb86f1039c9f096557e"} {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _635B extends CodeForcesApp {\n override type Result = Boolean\n\n override def solve(read: InputReader) = {\n val n = read[Int]\n val a, b = read[IndexedSeq, Int](n).filter(_ != 0)\n (a ++: a) containsSlice b\n }\n\n override def format(result: Result) = if (result) \"YES\" else \"NO\"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt - 1\n val data = in.next().split(' ').map(_.toInt).filter(_ > 0)\n val data1 = in.next().split(' ').map(_.toInt).filter(_ > 0)\n val index = data1.indexOf(data.head)\n if (data.take(n - index).mkString(\" \") == data1.drop(index).mkString(\" \") &&\n data.drop(n - index).mkString(\" \") == data1.take(index).mkString(\" \"))\n println(\"YES\")\n else\n println(\"NO\")\n}\n"}, {"source_code": "\n/**\n * Created by octavian on 28/02/2016.\n */\nobject Island {\n\n def main(args: Array[String]) = {\n\n //System.setIn(new FileInputStream(\"./src/island.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"./src/island.out\")))\n\n var n = readInt()\n var a = readLine.split(\" \").map(_.toInt).filter(_ != 0)\n var b = readLine.split(\" \").map(_.toInt).filter(_ != 0)\n\n if(a.length != n - 1 || b.length != n - 1) {\n println(\"NO\")\n }\n else {\n println(checkRotation(a, b, n))\n }\n }\n\n def checkRotation(a: Array[Int], b: Array[Int], n: Int): String = {\n val pos = posFirstElem(a(0), b)\n //println(\"pos is: \" + pos)\n for(i <- 0 until n - 1) {\n //println(\"pos + i mod n: \" + ((pos + i)%(n-1)))\n if(a(i) != b((pos + i)%(n - 1))) {\n return \"NO\"\n }\n }\n return \"YES\"\n }\n\n def posFirstElem(a0: Int, b: Array[Int]): Int = {\n for(i <- 0 until b.length) {\n if(a0 == b(i)) {\n return i\n }\n }\n return 0\n }\n\n}\n"}, {"source_code": "import java.util\n\nimport scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n).filter(_ != 0)\n val bs = readInts(n).filter(_ != 0)\n\n val ai = as.indexWhere(_ == 1)\n val bi = bs.indexWhere(_ == 1)\n\n val a2 = as.drop(ai) ++ as.take(ai)\n val b2 = bs.drop(bi) ++ bs.take(bi)\n\n val res = util.Arrays.equals(a2, b2)\n //println(a2.mkString(\" \"))\n //println(b2.mkString(\" \"))\n\n println(if (res) \"YES\" else \"NO\")\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _635B extends CodeForcesApp {\n override type Result = Boolean\n\n override def solve(read: InputReader) = {\n val n = read[Int]\n val a = read[IndexedSeq, Int](n).filter(_ != 0)\n val b = read[IndexedSeq, Int](n).filter(_ != 0)\n (a ++: a) containsSlice b\n }\n\n override def format(result: Result) = if (result) \"YES\" else \"NO\"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt).filter(_ > 0)\n val data1 = in.next().split(' ').map(_.toInt).filter(_ > 0)\n val index = data1.indexOf(data.head)\n println(index)\n if (data.take(n - index).mkString(\" \") == data1.drop(index).mkString(\" \") &&\n data.drop(n - index).mkString(\" \") == data1.take(index).mkString(\" \"))\n println(\"YES\")\n else\n println(\"NO\")\n}\n"}], "src_uid": "846681af4b4b6b29d2c9c450a945de90"} {"source_code": "object Main {\n import java.io._\nimport java.util.Scanner\n\nimport collection.mutable.HashMap\nimport scala.collection.{SortedSet, mutable}\nimport scala.util.Random\n protected val EPS = 1e-11\n\n private def default = (\n new StreamTokenizer(new InputStreamReader(System.in)),\n new Scanner(System.in),\n new PrintWriter(System.out)\n )\n\n val (in, ins, out) = {\n try {\n if (sys.props.contains(\"xDx\")) {\n (\n new StreamTokenizer(new FileReader(\"input.txt\")),\n new Scanner(new FileReader(\"input.txt\")),\n new PrintWriter(new FileWriter(\"output.txt\"))\n )\n } else {\n default\n }\n } catch {\n case _: Throwable => default\n }\n }\n\n private def nextInt = {\n in.nextToken\n in.nval.toInt\n }\n\n private def nextLong = {\n in.nextToken\n in.nval.toLong\n }\n\n\n private def nextDouble = {\n in.nextToken\n in.nval\n }\n\n\n private def nextString = {\n in.nextToken\n in.sval\n }\n\n private def nextChar = {\n in.nextToken\n in.ttype.toChar\n }\n\n def main(args: Array[String]): Unit = {\n try {\n new Run().run()\n } catch {\n case e: Throwable =>\n throw new RuntimeException(e)\n } finally out.close()\n }\n\n class Run {\n import collection.breakOut\n def run(): Unit = {\n val n = nextInt\n val m = nextInt\n val q = nextInt\n val start = Array.ofDim[Int](n)\n val end = Array.ofDim[Int](n)\n val s = nextString\n val t = nextString\n var is = 0\n var ie = 0\n var cur_s = 0\n var cur_e = 0\n \n while(is < n) {\n var idx = s.indexOf(t, is)\n if(idx == -1) idx = n\n while(is < n && is <= idx) {\n if(is == idx) cur_s += 1\n start(is) = cur_s\n is += 1\n }\n \n while(ie < n && ie < idx + m) {\n if(ie == idx + m - 1) cur_e += 1\n end(ie) = cur_e\n ie += 1\n }\n }\n \n for(i <- 1 to q) {\n val l = nextInt - 1\n val r = nextInt - 1\n val res = math.max(end(r) - (if(l == 0) 0 else start(l - 1)), 0)\n println(res)\n }\n }\n\n }\n\n}\n\n\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M, Q = ni()\n val S = ns()\n val T = ns()\n val cum = Array.ofDim[Int](N + 1) // 1-index\n\n if (N >= M) {\n rep(N - M + 1) { i =>\n cum(i + 1) = cum(i)\n if (S.substring(i, i + M) == T) cum(i + 1) += 1\n }\n }\n\n rep(Q) { _ =>\n val l, r = ni()\n val ri = r - M + 1\n val li = l - 1\n val ans = if (ri >= li) cum(ri) - cum(li) else 0\n out.println(ans)\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "\n\n\nobject Main {\n\n import java.io.{BufferedReader, InputStreamReader}\n\n val mod = (1e9 + 7).toLong\n\n var d = new Array[Long](1005)\n\n var powResult = new Array[Long](1005)\n\n var answer = new Array[Long](1005)\n\n var strMod: Long = 0\n\n /*\n 快速幂\n */\n def power(a: Long, b: Int): Long = {\n val ans = if (b == 0) 1 else {\n var res = 1.toLong\n var x = a\n var y = b\n while (y != 0) {\n if ((y & 1) == 1) {\n res *= x\n res %= mod\n }\n x *= x\n x %= mod\n y >>= 1\n }\n res\n }\n ans\n }\n\n def getPowerResult(): Unit = {\n (0 to 1000).foreach(i => {\n powResult(i) = power(131, i)\n })\n }\n\n def getHash(str: String): Unit = {\n (0 until str.length).foreach(index => {\n strMod *= 131\n strMod += str.charAt(index).toInt\n strMod %= mod\n })\n }\n\n def getMoroHashSum(str: String): Unit = {\n d(0) = 0.toLong\n (0 until str.length).foreach(i => {\n d(i + 1) = (d(i) + powResult(i) * str.charAt(i).toInt % mod) % mod\n })\n }\n\n def result(x: Int, y: Int, z: Int): Int = {\n var ans = 0\n (x to y - z + 1).foreach(i => {\n val temp1 = (d(i + z - 1) - d(i - 1) + mod) % mod\n val temp2 = (strMod * powResult(i - 1) % mod) % mod\n if (temp1 == temp2) ans += 1\n })\n ans\n }\n\n def getResultInit(x: Int, y: Int): Unit = {\n (1 to x - y + 1).foreach(i => {\n val temp1 = (d(i + y - 1) - d(i - 1) + mod) % mod\n val temp2 = (strMod * powResult(i - 1) % mod) % mod\n if (temp1 == temp2) answer(i) = answer(i - 1) + 1\n else answer(i) = answer(i - 1)\n })\n }\n\n\n def main(args: Array[String]): Unit = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n val line = br.readLine().split(\" \")\n val x = line(0).toInt\n val y = line(1).toInt\n val z = line(2).toInt\n val str1 = br.readLine()\n val str2 = br.readLine()\n getPowerResult()\n getHash(str2.reverse)\n getMoroHashSum(str1)\n getResultInit(x, y)\n var a = 0\n for (a <- 1 to z) {\n val line = br.readLine().split(\" \")\n val p = line(0).toInt - 1\n val q = line(1).toInt - y + 1\n if (p > q) println(\"0\")\n else println(answer(q) - answer(p))\n }\n br.close()\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n import java.io._\nimport java.util.Scanner\n\nimport collection.mutable.HashMap\nimport scala.collection.{SortedSet, mutable}\nimport scala.util.Random\n protected val EPS = 1e-11\n\n private def default = (\n new StreamTokenizer(new InputStreamReader(System.in)),\n new Scanner(System.in),\n new PrintWriter(System.out)\n )\n\n val (in, ins, out) = {\n try {\n if (sys.props.contains(\"xDx\")) {\n (\n new StreamTokenizer(new FileReader(\"input.txt\")),\n new Scanner(new FileReader(\"input.txt\")),\n new PrintWriter(new FileWriter(\"output.txt\"))\n )\n } else {\n default\n }\n } catch {\n case _: Throwable => default\n }\n }\n\n private def nextInt = {\n in.nextToken\n in.nval.toInt\n }\n\n private def nextLong = {\n in.nextToken\n in.nval.toLong\n }\n\n\n private def nextDouble = {\n in.nextToken\n in.nval\n }\n\n\n private def nextString = {\n in.nextToken\n in.sval\n }\n\n private def nextChar = {\n in.nextToken\n in.ttype.toChar\n }\n\n def main(args: Array[String]): Unit = {\n try {\n new Run().run()\n } catch {\n case e: Throwable =>\n throw new RuntimeException(e)\n } finally out.close()\n }\n\n class Run {\n import collection.breakOut\n def run(): Unit = {\n val n = nextInt\n val m = nextInt\n val q = nextInt\n val start = Array.ofDim[Int](n)\n val end = Array.ofDim[Int](n)\n val s = nextString\n val t = nextString\n var i = 0\n var cur_s = 0\n var cur_e = 0\n while(i < n) {\n var idx = s.indexOf(t, i)\n if(idx == -1) idx = n\n while(i < n && i < idx + m) {\n if(i == idx) cur_s += 1\n if(i == idx + m - 1) cur_e += 1\n start(i) = cur_s\n end(i) = cur_e\n i += 1\n }\n }\n \n for(i <- 1 to q) {\n val l = nextInt - 1\n val r = nextInt - 1\n val res = math.max(end(r) - (if(l == 0) 0 else start(l - 1)), 0)\n println(res)\n }\n }\n\n }\n\n}\n\n\n"}], "src_uid": "4cc5a6975d33cee60e53e8f648ec30de"} {"source_code": "object C extends App {\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val a = nextLong()\r\n val s = nextLong()\r\n\r\n s.augend(a) match {\r\n case Some(b) => out.println(b)\r\n case _ => out.println(-1)\r\n }\r\n }\r\n\r\n out.flush()\r\n\r\n implicit final class LongOps(private val sum: Long) extends AnyVal {\r\n def digits: List[Byte] = sum.toString().split(\"\").map(_.toByte).toList\r\n\r\n def augend(addend: Long): Option[Long] = {\r\n\r\n @annotation.tailrec\r\n def go(sumDigits: List[Byte], addendDigits: List[Byte], augendDigits: List[Byte]): Option[List[Byte]] =\r\n (sumDigits, addendDigits) match {\r\n case (sumHead :: sumTail, addendHead :: addendTail) if addendHead <= sumHead =>\r\n go(sumTail, addendTail, (sumHead - addendHead).toByte :: augendDigits)\r\n case (sumFirst :: sumSecond :: sumTail, addendHead :: addendTail) =>\r\n val sumHead = sumSecond * 10 + sumFirst\r\n if (sumHead > 18 || addendHead > sumHead) None\r\n else go(sumTail, addendTail, (sumHead - addendHead).toByte :: augendDigits)\r\n case (sumHead :: sumTail, _) =>\r\n go(sumTail, addendDigits, sumHead :: augendDigits)\r\n case _ =>\r\n if (addendDigits.isEmpty) Some(augendDigits) else None\r\n }\r\n\r\n go(sum.digits.reverse, addend.digits.reverse, List.empty[Byte]).map(_.mkString(\"\").toLong)\r\n }\r\n }\r\n\r\n object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n private[this] def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object C extends App {\r\n\r\n val digits: Long => List[Int] = _.toString().split(\"\").map(_.toInt).reverse.toList\r\n\r\n def wrongAddition(s: Long, a: Long): Option[Long] = {\r\n\r\n @annotation.tailrec\r\n def go(s: List[Int], a: List[Int], b: List[Int]): Option[List[Int]] = (s, a) match {\r\n case (shead :: stail, ahead :: atail) if ahead <= shead => go(stail, atail, (shead - ahead) :: b)\r\n case (sfirst :: ssecond :: stail, ahead :: atail) =>\r\n val shead = ssecond * 10 + sfirst\r\n if (shead > 18 || ahead > shead) None else go(stail, atail, (shead - ahead) :: b)\r\n case (shead :: stail, Nil) => go(stail, a, shead :: b)\r\n case (Nil, Nil) => Some(b)\r\n case _ => None\r\n }\r\n\r\n go(digits(s), digits(a), List.empty[Int]).map(_.mkString(\"\").toLong)\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val a = nextLong()\r\n val s = nextLong()\r\n\r\n wrongAddition(s, a) match {\r\n case Some(b) => out.println(b)\r\n case _ => out.println(-1)\r\n }\r\n }\r\n\r\n out.flush()\r\n\r\n object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n private[this] def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "aa00fbde0b135addd2fdde0310e0377a"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val diogonal = Array.ofDim[Long](1999)\n val backDiogonal = Array.ofDim[Long](1999)\n val n = in.next().toInt\n (1 to n).foreach { _ =>\n val Array(x, y) = in.next().split(' ').map(_.toInt)\n diogonal(1000 - y + x - 1) += 1\n backDiogonal(2000 - y - x) += 1\n }\n val seed = diogonal.foldLeft(0l) {\n case (acc, el) => acc + el * (el - 1) / 2\n }\n println(backDiogonal.foldLeft(seed) {\n case (acc, el) => acc + el * (el - 1) / 2\n })\n}", "positive_code": [{"source_code": "// So you like object Task\nimport java.io.{IOException, InputStream, PrintWriter}\nimport java.util.InputMismatchException\n\n/**\n * Created with IntelliJ IDEA.\n * User: xie\n * Date: 2/6/16\n * Time: 2:03 PM\n */\nobject Task {\n\n case class Bishop(x: Int, y: Int)\n def calc(x: Long) = x * (x - 1) / 2\n\n def solve(in: InputReader, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val a = Array.fill(n) { Bishop(in.nextInt(), in.nextInt()) }\n val a_sum = a.groupBy(b => b.x + b.y).map(b => calc(b._2.length)).sum\n val a_diff = a.groupBy(b => b.x - b.y).map(b => calc(b._2.length)).sum\n out.println(a_sum + a_diff)\n }\n\n def main(args: Array[String]) {\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n in.close()\n out.close()\n }\n}\n\nclass InputReader(val inputStream: InputStream) {\n val buf = new Array[Byte](1 << 16)\n var curChar = 0\n var numChars = 0\n\n def read(): Int = {\n if (numChars == -1) {\n throw new InputMismatchException()\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => throw new InputMismatchException()\n }\n if (numChars <= 0)\n return -1\n }\n curChar += 1\n buf(curChar - 1)\n }\n\n def peek(): Int = {\n if (numChars == -1) {\n return -1\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => return -1\n }\n if (numChars <= 0)\n return -1\n }\n buf(curChar)\n }\n\n def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n\n def nextInt(): Int = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextLong(): Long = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0l\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def next(): String = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n val res = new StringBuilder()\n do {\n res += c.toChar\n c = read()\n } while(!isSpaceChar(c))\n res.toString()\n }\n\n def nextChar(): Char = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n c.toChar\n }\n\n //noinspection AccessorLikeMethodIsEmptyParen\n def hasNext(): Boolean = {\n var value = peek()\n do {\n read()\n value = peek()\n } while (isSpaceChar(value) && value != -1)\n value != -1\n }\n\n def rawNextLine(): String = {\n val builder = new StringBuilder\n var c = read()\n while (c != '\\n' && c != -1) {\n if (c != '\\r')\n builder += c.toChar\n c = read()\n }\n builder.toString()\n }\n\n def nextLine(): String = {\n var s = rawNextLine()\n while (s.trim().length == 0) s = rawNextLine()\n s\n }\n\n def nextDouble(): Double = {\n next().toDouble\n }\n\n def close(): Unit = {\n inputStream.close()\n }\n}\n"}, {"source_code": "import io.StdIn._\nimport scala.collection.mutable._\n\nobject Solution {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n def main(args: Array[String]) {\n\n val n = readLine().toInt\n\n val a = Array.fill(2001)(0)\n val b = Array.fill(2001)(0)\n (1 to n).foreach { _ =>\n val Array(x, y) = readInts(2)\n a(1000+x-y) += 1\n b(x+y) += 1\n }\n\n var res: Long = 0\n\n a.foreach { v => res += v*(v-1)/2 }\n b.foreach { v => res += v*(v-1)/2 }\n\n println(res)\n\n // Console.withOut(new java.io.BufferedOutputStream(Console.out))\n // println(res.mkString(\"\\n\"))\n // Console.flush\n }\n}"}, {"source_code": "\n/**\n * Created by octavian on 31/01/2016.\n */\nobject Bishops {\n\n val TABLE_S = 1000\n\n def main(args: Array[String]) {\n //System.setIn(new FileInputStream(\"./src/bishops.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"./src/bishops.out\")))\n\n val n = readInt()\n var grid = Array.ofDim[Int](TABLE_S + 1, TABLE_S + 1)\n\n for(i <- 1 to n) {\n val Array(x, y) = readLine.split(\" \").map(_.toInt)\n //println(\"x is \" + x + \", y is\" + y)\n grid(x)(y) = 1\n }\n\n var attack: BigInt = 0\n for(i <- 1 to TABLE_S) {\n attack += comb2(searchDiagonal(i, 1, 1, grid))\n attack += comb2(searchDiagonal(i, TABLE_S, -1, grid))\n if(i > 1) {\n attack += comb2(searchDiagonal(1, i, 1, grid))\n }\n if(i < TABLE_S) {\n attack += comb2(searchDiagonal(1, i, -1, grid))\n }\n }\n\n println(attack)\n }\n\n def searchDiagonal(s_lin: Int, s_col: Int, add_col: Int, grid: Array[Array[Int]]): Int = {\n var result = 0\n var lin = s_lin\n var col = s_col\n\n while(lin <= TABLE_S && 0 < col && col <= TABLE_S) {\n result += grid(lin)(col)\n\n lin += 1\n col += add_col\n }\n //println(\"result for \" + s_lin + \", \" + s_col + \" is \" + result)\n return result\n }\n\n def comb2(n: Int): Int = {\n return n * (n - 1) / 2\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) {\n val n = StdIn.readInt()\n val ls, rs = mutable.HashMap[Int, Int]().withDefault(_ => 0)\n for (i <- 0 until n) {\n val Array(l, r) = StdIn.readLine().split(\" \").map(_.toInt)\n ls(l - r) += 1\n rs(l + r) += 1\n }\n var ans = 0\n for (v <- ls.values ++ rs.values) {\n ans += v * (v - 1) / 2\n }\n println(ans)\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ListBuffer\n\nobject B {\n def main(args: Array[String]) {\n val n = scala.io.StdIn.readInt\n val ups = ListBuffer.empty[Int]\n val downs = ListBuffer.empty[Int]\n (1 to n).foreach(x => {\n val q = scala.io.StdIn.readLine.split(\" \").map(_.toShort)\n ups+=q(0)-q(1)\n downs+=q(0)+q(1)\n })\n val u = ups.groupBy(l => l).map(x => (x._2.length * (x._2.length - 1)/2).toLong).sum\n val d = downs.groupBy(l => l).map(x => (x._2.length * (x._2.length - 1)/2).toLong).sum\n println(d+u)\n }\n}"}, {"source_code": "object B621 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = Array.fill(n)(readInts(2)).map(arr => (arr(0), arr(1)))\n val map1 = cu.Map.empty[Int, Long].withDefaultValue(0)\n val map2 = cu.Map.empty[Int, Long].withDefaultValue(0)\n in.foreach { case (x, y) =>\n map1(x-y) += 1\n map2(x+y) += 1\n }\n println(Array(map1,map2).map(_.values.map(x => (x*(x-1))/2).sum).sum)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n \n val cntA, cntB = mutable.Map.empty[Int, Int].withDefaultValue(0)\n \n for (_ <- 1 to n) {\n val Array(r, c) = readInts(2)\n cntA(r - c) += 1\n cntB(r + c) += 1\n }\n \n val a = cntA.values.map(x => x * (x - 1) / 2).sum\n val b = cntB.values.map(x => x * (x - 1) / 2).sum\n\n println(a + b)\n}\n"}], "negative_code": [{"source_code": "\n/**\n * Created by octavian on 31/01/2016.\n */\nobject Bishops {\n\n val TABLE_S = 1000\n\n def main(args: Array[String]) {\n //System.setIn(new FileInputStream(\"./src/bishops.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"./src/bishops.out\")))\n\n val n = readInt()\n var grid = Array.ofDim[Int](TABLE_S + 1, TABLE_S + 1)\n\n for(i <- 1 to n) {\n val Array(x, y) = readLine.split(\" \").map(_.toInt)\n //println(\"x is \" + x + \", y is\" + y)\n grid(x)(y) = 1\n }\n\n var attack: BigInt = 0\n for(i <- 1 to TABLE_S) {\n attack += comb2(searchDiagonal(i, 1, 1, grid))\n if(i > 1) {\n attack += comb2(searchDiagonal(i, 1, -1, grid))\n attack += comb2(searchDiagonal(1, i, 1, grid))\n attack += comb2(searchDiagonal(1, i, -1, grid))\n }\n }\n\n println(attack)\n }\n\n def searchDiagonal(s_lin: Int, s_col: Int, add_col: Int, grid: Array[Array[Int]]): Int = {\n var result = 0\n var lin = s_lin\n var col = s_col\n\n while(lin <= TABLE_S && 0 < col && col <= TABLE_S) {\n result += grid(lin)(col)\n\n lin += 1\n col += add_col\n }\n //println(\"result for \" + s_lin + \", \" + s_col + \" is \" + result)\n return result\n }\n\n def comb2(n: Int): Int = {\n return n * (n - 1) / 2\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable.ListBuffer\n\nobject B {\n def main(args: Array[String]) {\n val n = scala.io.StdIn.readInt\n val ups = ListBuffer.empty[Int]\n val downs = ListBuffer.empty[Int]\n (1 to n).foreach(x => {\n val q = scala.io.StdIn.readLine.split(\" \").map(_.toShort)\n ups+=q(0)-q(1)\n downs+=q(0)-q(1)\n })\n val u = ups.groupBy(l => l).map(x => x._2.length * (x._2.length - 1)/2).sum\n val d = downs.groupBy(l => l).map(x => x._2.length * (x._2.length - 1)/2).sum\n println(d+u)\n }\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer\n\nobject B {\n def main(args: Array[String]) {\n val n = scala.io.StdIn.readInt\n val ups = ListBuffer.empty[Int]\n val downs = ListBuffer.empty[Int]\n (1 to n).foreach(x => {\n val q = scala.io.StdIn.readLine.split(\" \").map(_.toShort)\n ups+=q(0)-q(1)\n downs+=q(0)-q(1)\n })\n val u = ups.groupBy(l => l).map(x => (x._2.length * (x._2.length - 1)/2).toLong).sum\n val d = downs.groupBy(l => l).map(x => (x._2.length * (x._2.length - 1)/2).toLong).sum\n println(d+u)\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val diogonal = Array.ofDim[Long](1998)\n val backDiogonal = Array.ofDim[Long](1998)\n val n = in.next().toInt\n (1 to n).foreach { _ =>\n val Array(x, y) = in.next().split(' ').map(_.toInt - 1)\n diogonal(999 - x + y) += 1\n backDiogonal(999 - y + x) += 1\n }\n val seed = diogonal.foldLeft(0l) {\n case (acc, el) => acc + el * (el - 1) / 2\n }\n println(backDiogonal.foldLeft(seed) {\n case (acc, el) => acc + el * (el - 1) / 2\n })\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val diogonal = Array.ofDim[Int](1998)\n val backDiogonal = Array.ofDim[Int](1998)\n val n = in.next().toInt\n (1 to n).foreach { _ =>\n val Array(x, y) = in.next().split(' ').map(_.toInt - 1)\n diogonal(999 - x + y) += 1\n backDiogonal(999 - y + x) += 1\n }\n val seed = diogonal.foldLeft(0l) {\n case (acc, el) => acc + el.toLong * (el - 1) / 2\n }\n println(backDiogonal.foldLeft(seed) {\n case (acc, el) => acc + el.toLong * (el - 1) / 2\n })\n}"}, {"source_code": "object B621 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = Array.fill(n)(readInts(2)).map(arr => (arr(0), arr(1)))\n val map = cu.Map.empty[Int, Long].withDefaultValue(0)\n in.foreach { case (x, y) =>\n map(x-y) += 1\n map(x+y) += 1\n }\n println(map.values.map(x => (x*(x-1))/2).sum)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n \n val cntA, cntB = mutable.Map.empty[Int, Int].withDefaultValue(0)\n \n for (_ <- 1 to n) {\n val Array(r, c) = readInts(2)\n cntA(r - c) += 1\n cntB(r + c) += 1\n }\n \n val a = cntA.values.filter(_ > 1).sum\n val b = cntB.values.filter(_ > 1).sum\n\n println(a + b)\n}\n"}, {"source_code": "import io.StdIn._\nimport scala.collection.mutable._\n\nobject Solution {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n def main(args: Array[String]) {\n\n val n = readLine().toInt\n\n var a = 0\n var b = 0\n (1 to n).foreach { _ =>\n val Array(x, y) = readInts(2)\n if (x == y) a += 1\n if (x + y == n + 1) b += 1\n }\n\n println(a*(a-1)/2 + b*(b-1)/2)\n\n // Console.withOut(new java.io.BufferedOutputStream(Console.out))\n // println(res.mkString(\"\\n\"))\n // Console.flush\n }\n}"}], "src_uid": "eb7457fe1e1b571e5ee8dd9689c7d66a"} {"source_code": "\r\nimport scala.io.StdIn.readLine\r\n\r\nobject Solution {\r\n\r\n def rsi() = readLine().split(\"\\\\s+\").map(_.toInt)\r\n\r\n\r\n def solve() = {\r\n val size = readLine.toInt\r\n val arr = rsi\r\n val tup = arr.foldLeft(arr.head, arr.head, 1, 1, 1)(\r\n (acc, elem) => {\r\n val (min, max, mini, maxi, count) = acc\r\n if (min > elem) (elem, max, count, maxi, count + 1)\r\n else if (max < elem) (min, elem, mini, count, count + 1)\r\n else (min, max, mini, maxi, count + 1)\r\n }\r\n )\r\n\r\n\r\n s\"${tup._3} ${tup._4}\"\r\n\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val cases = readLine.toInt\r\n for (\r\n i <- 0 until cases\r\n ) println(solve)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.io.StdIn\r\n\r\nobject Sol extends App {\r\n val tests = StdIn.readInt()\r\n\r\n for (x <- 1 to tests) {\r\n val length = StdIn.readInt()\r\n val ints = StdIn.readLine()\r\n val singleCaseInts = ints.split(\" \").map(x => x.toInt)\r\n\r\n val withIndex = singleCaseInts.zipWithIndex\r\n val maxIndex = withIndex.maxBy(x => x._1)._2\r\n val minIndex = withIndex.minBy(x => x._1)._2\r\n\r\n println(s\"${maxIndex + 1} ${minIndex + 1}\")\r\n }\r\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn\r\n\r\nobject Sol extends App {\r\n val tests = StdIn.readInt()\r\n\r\n for (x <- 1 to tests) {\r\n val length = StdIn.readInt()\r\n val ints = StdIn.readLine()\r\n val singleCaseInts = ints.split(\" \").map(x => x.toInt)\r\n\r\n println(singleCaseInts)\r\n val withIndex = singleCaseInts.zipWithIndex\r\n val maxIndex = withIndex.maxBy(x => x._1)._2\r\n val minIndex = withIndex.minBy(x => x._1)._2\r\n\r\n println(s\"${maxIndex + 1} ${minIndex + 1}\")\r\n }\r\n}\r\n"}], "src_uid": "7af4eee2e9f60283c4d99200769c77ec"} {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n\r\n val ans = n / 10 + (if (n % 10 == 9) 1 else 0)\r\n\r\n println(ans)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) = {\n def rep[A](n: Int)(f: => A) { if (n > 0) { f; rep(n - 1)(f) } }\n\n rep(StdIn.readInt) {\n println((9 to StdIn.readInt by 10).length)\n }\n\n }\n}\n"}, {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n\r\n val ans = (n + 1) / 10\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn._;\r\n\r\nobject Main extends App {\r\n\r\n def a(ignored: Int, z: Array[Long]): Long = z.zip(z.slice(1, z.length)).map(l => l._1 * l._2).max\r\n// for (_ <- 0 until readInt()) println(a(readInt(), readLine().split(\" \").map(_.toLong)))\r\n\r\n\r\n def b(l: Long): Long = (l + 1)/10\r\n \r\n for (_ <- 0 until readInt()) println(b(readLong()))\r\n}\r\n\r\n\r\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) = {\n println(\"Started program\")\n def rep[A](n: Int)(f: => A) { if (n > 0) { f; rep(n - 1)(f) } }\n\n rep(StdIn.readInt) {\n println((9 to StdIn.readInt by 10).length)\n }\n\n }\n}\n"}], "src_uid": "8e4194b356500cdaacca2b1d49c2affb"} {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Solution extends App {\n\n def readIntList(): Array[Int] = readLine().split(\" \").map(_.toInt)\n\n val testNumber = readInt()\n val calculatedXor = Array.tabulate(500000)(index => index).scan(0)(_ ^ _)\n 1.to(testNumber).foreach { _ =>\n val Array(mex,xor) = readIntList()\n val existingXor: Int = calculatedXor(mex)\n val numberToMakeXor: Int = xor ^ existingXor\n val answer = (mex, xor) match {\n case (n, `existingXor`) => n\n case (n, _) if n == numberToMakeXor => n + 2\n case (n, _) => n + 1\n }\n println(answer)\n }\n\n}\n", "positive_code": [{"source_code": "object B extends App {\r\n\r\n def shortest(a: Int, b: Int): Int =\r\n (((a - 1) % 4) match {\r\n case 0 => a - 1\r\n case 1 => 1\r\n case 2 => a\r\n case 3 => 0\r\n }) match {\r\n case c if a == (b ^ c) => a + 2\r\n case c if b == c => a\r\n case _ => a + 1\r\n }\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(a, b) = readLine().split(\" \").map(_.toInt)\r\n\r\n println(shortest(a, b))\r\n }\r\n\r\n}\r\n"}], "negative_code": [], "src_uid": "d6790c9b4b2e488768fb4e746ee7ebe0"} {"source_code": "object hello extends App {\r\n import scala.io.StdIn\r\n val n = StdIn.readInt()\r\n for (i <- 1 to n) {\r\n val t = StdIn.readInt()\r\n var j = 1\r\n if (t % 2 == 1) {\r\n print(\"3 1 2 \")\r\n j = 4\r\n }\r\n while (j <= t) {\r\n print(j + 1)\r\n print(' ')\r\n print(j)\r\n print(' ')\r\n j = j + 2\r\n }\r\n println()\r\n }\r\n}", "positive_code": [{"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val ans = {\r\n val t = Array.range(1, n + 1, 1).map {\r\n case i if n % 2 == 1 && i == n - 2 => n - 1\r\n case i if n % 2 == 1 && i == n - 1 => n\r\n case i if n % 2 == 1 && i == n => n - 2\r\n case i if i % 2 == 0 => i - 1\r\n case i => i + 1\r\n }\r\n\r\n t\r\n }\r\n\r\n println(ans.mkString(\" \"))\r\n }\r\n}\r\n"}, {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val cats = Array.tabulate(n){ x=> x + 1}\n if (n % 2 == 0) {\n for (i <- 0 until n) {\n cats(i) = i / 2 * 2 - i % 2 + 2\n }\n } else {\n cats(0) = 2\n cats(1) = 3\n cats(2) = 1\n for (i <- 3 until n) {\n val j = i + 1\n cats(i) = j / 2 * 2 - j % 2 + 1\n }\n }\n\n out.println(cats.mkString(\" \"))\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "f89bd4ec97ec7e02a7f67feaeb4d3958"} {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _606B extends CodeForcesApp {\n override type Result = Seq[Int]\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val Seq(x, y, x0, y0) = Seq.fill(4)(nextInt())\n val command = nextLine().toCharArray.toList\n val seen = true\n val field = Array.ofDim[Boolean](x+1, y+1)\n\n @tailrec\n def move(i: Int, j: Int, command: List[Char], acc: Int): (Int, Int, List[Char], Int) = command match {\n case Nil => (i, j, command, acc)\n case _ if field(i)(j) == !seen =>\n field(i)(j) = seen\n (i, j, command, acc)\n case 'U' :: cs => move((i-1) max 1, j, cs, 1 + acc)\n case 'D' :: cs => move((i+1) min x, j, cs, 1 + acc)\n case 'L' :: cs => move(i, (j-1) max 1, cs, 1 + acc)\n case 'R' :: cs => move(i, (j+1) min y, cs, 1 + acc)\n }\n\n val moves = mmap[Int].to(0)\n\n var i = x0\n var j = y0\n var cmd = command\n var m = 0\n repeat(x * y) {\n val (ni, nj, ncmd, nm) = move(i, j, cmd, m)\n moves(nm) = moves(nm) + 1\n i = ni\n j = nj\n cmd = ncmd\n m = nm\n }\n\n (0 to command.length) map moves\n }\n\n def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n\n def mmap[A] = new {\n def to[B](default: B): mutable.Map[A, B] = mutable.Map.empty[A, B] withDefaultValue default\n }\n\n override def format(result: Result) = result mkString \" \"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n val mod: Int = 1000000007\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n", "positive_code": [{"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val (x,y)=(nextInt,nextInt)\n var (x0,y0)=(nextInt,nextInt)\n val s=nextString\n val visited=Array.ofDim[Boolean](x,y)\n var count=1\n out.print(\"1 \")\n visited(x0-1)(y0-1)=true\n s.dropRight(1).foreach(c=>{\n c match {\n case 'U'=> x0-=1\n case 'D'=> x0+=1\n case 'L'=> y0-=1\n case 'R'=> y0+=1\n case _ => ()\n }\n if(x0<1){ x0=1}\n else if(x0>x){\n x0=x\n }\n if(y0<1){y0=1}\n else if(y0>y){\n y0=y\n }\n \n if(visited(x0-1)(y0-1)){\n out.print(\"0 \")\n }else{\n \n visited(x0-1)(y0-1)=true\n count+=1\n out.print(\"1 \")\n }\n })\n out.println(x*y-count)\n\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(x, y, x0, y0) = readInts(4)\n val ms = readLine.toCharArray\n val res = Array.fill(ms.size + 1){ 0 }\n \n val visited = Array.fill(x, y){ false }\n \n var _x = x0 - 1\n var _y = y0 - 1\n \n res(0) = 1\n var cnt = 0\n for (k <- ms.indices) {\n if (!visited(_x)(_y)) {\n visited(_x)(_y) = true\n cnt += 1\n res(k) = 1\n }\n ms(k) match {\n case 'U' => _x -= 1\n case 'D' => _x += 1\n case 'L' => _y -= 1\n case 'R' => _y += 1\n }\n if (_x < 0) _x = 0\n if (_x > x - 1) _x = x - 1\n if (_y < 0) _y = 0\n if (_y > y - 1) _y = y - 1\n //println(_x + 1, _y + 1)\n }\n \n /*if (!visited(_x)(_y))*/ res(res.size - 1) = (x * y - cnt) //max 1\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(x, y, x0, y0) = readInts(4)\n val ms = readLine.toCharArray\n val res = Array.fill(ms.size + 1){ 0 }\n \n val visited = Array.fill(x, y){ false }\n \n var _x = x0 - 1\n var _y = y0 - 1\n \n res(0) = 1\n var cnt = 0\n for (k <- ms.indices) {\n if (!visited(_x)(_y)) {\n visited(_x)(_y) = true\n cnt += 1\n res(k) = 1\n }\n ms(k) match {\n case 'U' => _x -= 1\n case 'D' => _x += 1\n case 'L' => _y -= 1\n case 'R' => _y += 1\n }\n if (_x < 0) _x = 0\n if (_x > x - 1) _x = x - 1\n if (_y < 0) _y = 0\n if (_y > y - 1) _y = y - 1\n }\n \n if (!visited(_x)(_y)) res(res.size - 1) = x * y - cnt\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(x, y, x0, y0) = readInts(4)\n val ms = readLine.toCharArray\n val res = Array.fill(ms.size + 1){ 0 }\n \n val visited = Array.fill(x, y){ false }\n \n var _x = x0 - 1\n var _y = y0 - 1\n \n res(0) = 1\n var cnt = 0\n for (k <- ms.indices) {\n if (!visited(_x)(_y)) {\n visited(_x)(_y) = true\n cnt += 1\n res(k) = 1\n }\n ms(k) match {\n case 'U' => _x -= 1\n case 'D' => _x += 1\n case 'L' => _y -= 1\n case 'R' => _y += 1\n }\n if (_x < 0) _x = 0\n if (_x > x - 1) _x = x - 1\n if (_y < 0) _y = 0\n if (_y > y - 1) _y = y - 1\n //println(_x + 1, _y + 1)\n }\n \n /*if (!visited(_x)(_y)) */res(res.size - 1) = (x * y - cnt) max 1\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(x, y, x0, y0) = readInts(4)\n val ms = readLine.toCharArray\n val res = Array.fill(ms.size + 1){ 0 }\n \n val visited = Array.fill(x, y){ false }\n \n var _x = x0 - 1\n var _y = y0 - 1\n \n res(0) = 1\n var cnt = 0\n for (k <- ms.indices) {\n if (!visited(_x)(_y)) {\n visited(_x)(_y) = true\n cnt += 1\n res(k) = 1\n }\n ms(k) match {\n case 'U' => _x -= 1\n case 'D' => _x += 1\n case 'L' => _y -= 1\n case 'R' => _y += 1\n }\n if (_x < 0) _x = 0\n if (_x > x - 1) _x = x - 1\n if (_y < 0) _y = 0\n if (_y > y - 1) _y = y - 1\n }\n \n if (!visited(_x)(_y)) res(res.size - 1) = x * y - cnt else res(res.size - 1) = 1\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(x, y, x0, y0) = readInts(4)\n val ms = readLine.toCharArray\n val res = Array.fill(ms.size + 1){ 0 }\n \n val visited = Array.fill(x, y){ false }\n \n var _x = x0 - 1\n var _y = y0 - 1\n \n res(0) = 1\n var cnt = 0\n for (k <- ms.indices) {\n if (!visited(_x)(_y)) {\n visited(_x)(_y) = true\n cnt += 1\n res(k) = 1\n }\n ms(k) match {\n case 'U' => _x -= 1\n case 'D' => _x += 1\n case 'L' => _y -= 1\n case 'R' => _y += 1\n }\n if (_x < 0) _x = 0\n if (_x > x - 1) _x = x - 1\n if (_y < 0) _y = 0\n if (_y > y - 1) _y = y - 1\n //println(_x + 1, _y + 1)\n }\n \n if (!visited(_x)(_y)) res(res.size - 1) = (x * y - cnt) max 1\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}], "src_uid": "22bebd448f93c0ff07d2be91e873521c"} {"source_code": "import java.util.Scanner\nimport scala.math.max\n\nobject TheFibonacciSegment extends App {\n val scan = new Scanner(System.in)\n val n = scan.nextInt\n val a = new Array[Int](n)\n\n var ans = 2\n var nowx: Int = _\n var nowy: Int = _\n var nowl = 2\n for(i <- 0 until n) {\n val z = scan.nextInt\n if(i >= 2) {\n if(nowx + nowy == z) {\n ans = max(ans, nowl + 1)\n nowl = nowl + 1\n } else nowl = 2\n }\n nowx = nowy\n nowy = z\n }\n\n if(n == 1) ans = 1\n println(ans)\n}", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.net.InetAddress\nimport java.security.MessageDigest\n\n/**\n * Contest 213, Div 2, problem B\n *\n *

You have array a1, a2, ..., an. Segment [l, r] (1 ≤ l ≤ r ≤ n) is good\n * if ai = ai - 1 + ai - 2, for all i (l + 2 ≤ i ≤ r).\n *\n * Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the\n * segment [l, r]. Segment [l1, r1], is longer than segment [l2, r2], if\n * len([l1, r1]) > len([l2, r2]).\n *\n * Your task is to find a good segment of the maximum length in array\n * a. Note that a segment of length 1 or 2 is always good.

\n */\nobject Round213_Div2_Task2 {\n val inputScan = {\n val md = MessageDigest.getInstance(\"SHA-1\")\n val userName = System.getProperty(\"user.name\")\n val hostName = InetAddress.getLocalHost.getHostName\n\n val bytes = md.digest((userName + hostName).getBytes)\n val sb = new StringBuilder\n for (i ← 0 until bytes.length)\n sb.append(Integer.toString((bytes(i) & 0xff) + 0x100, 16).substring(1))\n\n if (sb.result == \"51a302f8ba1abe181e33fe86c0ab4c7bedfb6c91\") new Scanner(new java.io.FileInputStream(\"tmp/0.txt\"))\n else new Scanner(System.in)\n }\n\n def main(args: Array[String]): Unit = {\n val scan = inputScan\n\n val n = scan.nextLine.toInt\n val res = n match {\n case 1 ⇒ 1\n case 2 ⇒ 2\n case _ ⇒\n val lengths = Array.fill(n)(0)\n val values = Array.fill(n)(0); values(0) = scan.nextInt; values(1) = scan.nextInt\n for (i ← 2 until n) {\n values(i) = scan.nextInt\n if (values(i) == values(i - 2) + values(i - 1) || values(i - 2) + values(i - 1) + values(i) == 0) {\n lengths(i) = 1\n } else lengths(i) = 0\n }\n for (i ← 2 until n) {\n if (lengths(i - 1) > 0 && lengths(i) > 0) lengths(i) = lengths(i - 1) + 1\n }\n lengths.max + 2\n }\n println(res)\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.net.InetAddress\nimport java.security.MessageDigest\n\n/**\n * Contest 213, Div 2, problem B\n *\n *

You have array a1, a2, ..., an. Segment [l, r] (1 ≤ l ≤ r ≤ n) is good\n * if ai = ai - 1 + ai - 2, for all i (l + 2 ≤ i ≤ r).\n *\n * Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the\n * segment [l, r]. Segment [l1, r1], is longer than segment [l2, r2], if\n * len([l1, r1]) > len([l2, r2]).\n *\n * Your task is to find a good segment of the maximum length in array\n * a. Note that a segment of length 1 or 2 is always good.

\n */\nobject Round213_Div2_Task2 {\n val inputScan = {\n val md = MessageDigest.getInstance(\"SHA-1\")\n val userName = System.getProperty(\"user.name\")\n val hostName = InetAddress.getLocalHost.getHostName\n\n val bytes = md.digest((userName + hostName).getBytes)\n val sb = new StringBuilder\n for (i ← 0 until bytes.length)\n sb.append(Integer.toString((bytes(i) & 0xff) + 0x100, 16).substring(1))\n\n if (sb.result == \"51a302f8ba1abe181e33fe86c0ab4c7bedfb6c91\") new Scanner(new java.io.FileInputStream(\"tmp/0.txt\"))\n else new Scanner(System.in)\n }\n\n def main(args: Array[String]): Unit = {\n val scan = inputScan\n\n val n = scan.nextLine.toInt\n val result = n match {\n case 1 ⇒ 1\n case 2 ⇒ 2\n case _ ⇒\n val lengths = Array.fill(n)(0)\n val values = Array.fill(n)(0); values(0) = scan.nextInt; values(1) = scan.nextInt\n for (i ← 2 until n) {\n values(i) = scan.nextInt\n lengths(i) = \n if (values(i) == values(i - 2) + values(i - 1) || values(i - 2) + values(i - 1) + values(i) == 0)\n lengths(i - 1) + 1\n else 0\n }\n lengths.max + 2\n }\n println(result)\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n var max = Math.min(2, n)\n var i = 0\n while (i < n - 1) {\n var j = i + 2\n var d = 0\n while (j < n && data(j) == data(j - 1) + data(j - 2)) {\n j += 1\n d += 1\n }\n i = j - 1\n max = Math.max(max, d + 2)\n }\n println(max)\n}\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val n = readInt\n val as = readLongs(n)\n \n var l, r = 0\n var max = n min 2\n \n for (i <- 2 until n) {\n if (as(i) == as(i - 1) + as(i - 2)) {\n if (i - l + 1 > max) max = i - l + 1\n } else l = i - 1\n }\n\n println(max)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P365B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n val A = List.fill(N)(sc.nextLong)\n\n @tailrec\n def loop(acc: Int, cur: Int, as: List[Long]): Int = as match {\n case x :: y :: z :: _ => {\n if (x + y == z) loop(acc max (cur + 1), cur + 1, as.tail)\n else loop(acc, 0, as.tail)\n }\n case _ => (acc + 2) min N\n }\n\n loop(0, 0, A)\n }\n \n out.println(solve)\n out.close\n}\n\n\n\n\n\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 08 Aug 2016\n */\nobject B365 extends App{\n\n def solve() = {\n val n: Int = scala.io.StdIn.readInt()\n val a: Array[Long] = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n if (n == 1) {\n println(1)\n } else {\n val b: Array[Int] = Array.ofDim[Int](n)\n b(0) = 1\n b(1) = 2\n for (i <- 2 until n) {\n if (a(i) == a(i - 1) + a(i - 2)) {\n b(i) = b(i - 1) + 1\n } else {\n b(i) = 2\n }\n }\n println(b.max)\n }\n }\n\n solve()\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n if (n == 1) println(\"1\")\n else {\n var s1 = a(0)\n var s2 = a(1)\n var max = 2\n var current = 2\n for (i <- 2 until a.size) { \n if (a(i) == s1 + s2) {\n current += 1\n } else {\n max = max.max(current)\n current = 2\n }\n s1 = s2\n s2 = a(i)\n }\n println(max.max(current))\n }\n }\n}"}, {"source_code": "object Fib extends App {\n def fibsegment(elements: IndexedSeq[Int]) = {\n\n if (elements.length == 1) 1\n else if (elements.length == 2) 2\n else {\n var max = 2\n var localLength = 2\n for (i <- 2 until elements.length) {\n if (elements(i) == elements(i - 1) + elements(i - 2)) {\n localLength += 1\n\n if (max < localLength) max = localLength\n } else {\n localLength = 2\n }\n }\n\n max\n }\n }\n\n val lines = io.Source.stdin.getLines().toIndexedSeq\n\n println(fibsegment(lines.last.split(\" \").map(_.toInt).toIndexedSeq))\n}"}, {"source_code": "object Main {\n def main(args : Array[String]) {\n val n = readInt()\n val nums = readLine().split(\" \") map { _.toInt }\n\n val (max, c) = nums.sliding(3).foldLeft((2, 2)) { (m, w) => w match {\n case Array(x, y, z) =>\n if(x + y == z)\n (math.max(m._1, m._2 + 1), m._2 + 1)\n else\n (m._1, 2)\n case Array(x, y) => (2, 0)\n case Array(x) => (1, 0)\n }}\n\n println(max)\n }\n}\n"}, {"source_code": "object B {\n def main(args: Array[String]) {\n val n = Integer.parseInt(readLine())\n val tokens: Array[String] = readLine().split(\" \")\n val number: Array[Int] = new Array[Int](n)\n\n for(i <- Range(0, n))\n {\n number(i) = Integer.parseInt(tokens(i))\n }\n\n var counter = Math.min(n, 2)\n var max = counter\n for(i <- Range(2, n))\n {\n if(number(i) == (number(i-2) + number(i-1)))\n {\n counter = Math.max(3, counter + 1)\n }\n else\n {\n if(counter > max)\n {\n max = counter\n }\n\n counter = 0\n }\n }\n\n println(Math.max(counter, max))\n }\n}"}, {"source_code": "object Solution365B extends App {\n\n def solution() {\n val n = _int\n val a = 1.to(n).map(_ => _int)\n\n if (a.length == 0) {\n println(0)\n return\n }\n if (a.length == 1) {\n println(1)\n return\n }\n if (a.length == 2) {\n println(2)\n return\n }\n\n val seq = a.tail.tail.zip(a.tail).zip(a).map(q => (q._1._1, q._1._2, q._2))\n val res = seq.foldLeft((0, 0))((memo, a) => {\n if (a._1 == a._2 + a._3) {\n (math.max(memo._1, memo._2 + 1), memo._2 + 1)\n } else {\n (memo._1, 0)\n }\n })\n println(res._1 + 2)\n }\n\n //////////////////////////////////////////////////\n import java.util.Scanner\n val SC: Scanner = new Scanner(System.in)\n def _line: String = SC.nextLine\n def _int: Int = SC.nextInt\n def _long: Long = SC.nextLong\n def _string: String = SC.next\n solution()\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P365B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n val A = List.fill(N)(sc.nextLong)\n\n @tailrec\n def loop(acc: Int, cur: Int, as: List[Long]): Int = as match {\n case x :: y :: z :: _ => {\n if (x + y == z) loop(acc max (cur + 1), cur + 1, as.tail)\n else loop(acc, 0, as.tail)\n }\n case _ => acc + 2\n }\n\n loop(0, 0, A)\n }\n \n out.println(solve)\n out.close\n}\n\n\n\n\n\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P365B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n val A = List.fill(N)(sc.nextLong)\n\n @tailrec\n def loop(acc: Int, cur: Int, as: List[Long]): Int = as match {\n case x :: y :: z :: _ => {\n if (x + y == z) loop(acc max (cur + 1), cur + 1, as.tail)\n else loop(acc, 0, as.tail)\n }\n case _ => (acc + 2) max N\n }\n\n loop(0, 0, A)\n }\n \n out.println(solve)\n out.close\n}\n\n\n\n\n\n"}, {"source_code": "object Fib extends App {\n def fibsegment(elements: IndexedSeq[Int]) = {\n\n if (elements.length == 1) 1\n else if (elements.length == 2) 2\n else {\n var max = 2\n var localLength = 2\n for (i <- 2 until elements.length) {\n if (elements(i) == elements(i - 1) + elements(i - 2)) {\n localLength += 1\n\n if (max < localLength) max = localLength\n } else {\n localLength = 0\n }\n }\n\n max\n }\n }\n\n val lines = io.Source.stdin.getLines().toIndexedSeq\n \n println(fibsegment(lines.last.split(\" \").map(_.toInt).toIndexedSeq))\n}"}], "src_uid": "f99a23bc65a1f5cdbf7909dba573ce51"} {"source_code": "object _1324B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val as = io.read[Seq[Int]]\n val first, last = mutable.Map.empty[Int, Int]\n var result = false\n\n as.zipWithIndex foreach {case (a, i) =>\n first(a) = i min first.getOrElse(a, Int.MaxValue)\n last(a) = i max last.getOrElse(a, Int.MinValue)\n result |= (last(a) - first(a)) > 1\n }\n\n io.write(result.toEnglish.toUpperCase)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C627B(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C627B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val n = ni()\n\n val a = na(n)\n\n val m = Array.fill[Int](5005)(0)\n var other = false\n var yes = false\n var prev = -1\n REP(n) { i =>\n if(m(a(i)) != 0 && other && a(i) != prev) {\n yes = true\n }\n if(m(a(i)) == 0 && i > 0) {\n m(a(i)) = 1\n other = true\n } else m(a(i)) += 1\n\n prev = a(i)\n }\n m.foreach { f =>\n if(f >= 3) yes = true\n }\n if(yes) out.println(\"YES\") else out.println(\"NO\")\n }\n }\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C627B(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C627B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val n = ni()\n\n val a = na(n)\n\n val m = Array.fill[Int](5005)(0)\n var other = false\n var yes = false\n var prev = -1\n REP(n) { i =>\n if(m(a(i)) != 0 && other && a(i) != prev) {\n yes = true\n }\n if(m(a(i)) == 0 && i > 0) {\n m(a(i)) = 1\n other = true\n } else m(a(i)) += 1\n\n prev = a(i)\n }\n if(yes) out.println(\"YES\") else out.println(\"NO\")\n }\n }\n}\n"}], "src_uid": "5139d222fbbfa70d50e990f5d6c92726"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class pair(var minl: Int, var maxl: Int, var minr: Int, var maxr: Int, var ind: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return minl.compareTo(that.minl)\n }\n }\n val rem = 1000000007\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val arr = new Array[Int](n+1)\n var flag = false\n for (i <- 1 to n) {\n arr(i) = readInt()\n if (i > 1 && arr(i) <= arr(i-1))\n flag = true\n }\n if (n % 2 == 0) {\n writer.println(\"YES\")\n } else {\n if (flag)\n writer.println(\"YES\")\n else\n writer.println(\"NO\")\n }\n }\n writer.flush()\n}\n", "positive_code": [{"source_code": "object B extends App {\r\n\r\n def xorSpeciaLISt(xs: IndexedSeq[Int]): Boolean =\r\n xs.length % 2 == 0 || xs.indices.tail.exists { i => xs(i) <= xs(i - 1) }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val an = nextInts(n)\r\n\r\n xorSpeciaLISt(an) match {\r\n case true => out.println(\"YES\")\r\n case false => out.println(\"NO\")\r\n }\r\n }\r\n\r\n out.flush()\r\n\r\n object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n private[this] def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}], "negative_code": [], "src_uid": "d8d33581ceb13da9bb99e90296bdd8f7"} {"source_code": "\n\nimport scala.io.StdIn\n\n\nobject Test extends App {\n\n val s = StdIn.readLine().toInt\n (1 to s).foreach{_ =>\n var n = StdIn.readLine().toInt\n var ans = List.empty[Int]\n if(n == 10000) {\n println(1)\n println(n)\n } else {\n if (n / 1000 != 0) {\n val x = (n / 1000) * 1000\n ans = (x :: ans)\n n = n - x\n }\n if (n / 100 != 0) {\n val x = (n / 100) * 100\n ans = (x :: ans)\n n = n - x\n }\n if(n / 10 != 0){\n val x = (n / 10) * 10\n ans = (x :: ans)\n n = n - x\n }\n if(n != 0){\n ans = n :: ans\n }\n println(ans.size)\n ans.foreach(x => print(s\"$x \"))\n println()\n }\n }\n}\n", "positive_code": [{"source_code": "object _1352A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val n = io.read[Int].toString.reverse\n\n val ans = n.indices collect {\n case i if n(i) - '0' > 0 => n(i) + (\"0\" * i)\n }\n\n io.writeLine(ans.length).writeAll(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n val charToInt: Char => Int = Character.getNumericValue\n val intToChar: Int => Char = Character.forDigit(_, 10)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readInt\n\nobject Scala {\n def main(args: Array[String]): Unit = {\n var t: Int = readInt()\n while (t > 0) {\n var x: Int = readInt()\n var sum: Int = 1;\n var ls: Array[Int] = Array()\n while (x > 0) {\n var m: Int = x % 10\n if(m > 0) {\n ls = ls :+ (sum * m)\n }\n x /= 10\n sum = sum * 10;\n }\n println(ls.length)\n for(i <- ls) {\n print(s\"$i \")\n }\n println()\n t -= 1\n }\n }\n}"}, {"source_code": "object C extends App {\n \n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val x = scala.io.StdIn.readLine()\n println(x.filter(_ != '0').length)\n val m = x.zipWithIndex.collect {\n case (e,i) if(e != '0') => {\n e.asDigit * math.pow(10, x.length-i-1).toInt\n }\n }.mkString(\" \")\n println(m)\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Main2 extends App {\n val testNumber = readInt()\n 1.to(testNumber).foreach {_ =>\n var digit = readInt()\n var answers: Vector[Int] = Vector()\n var divisor = 10\n while (digit > 0) {\n val answer = digit % divisor\n if (answer != 0) answers +:= answer\n digit = digit - answer\n divisor *= 10\n }\n println(answers.size)\n println(answers.mkString(\" \"))\n }\n}\n"}, {"source_code": "\nobject ProblemA extends App {\n import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val n = in.nextInt()\n\n def solve(integer: Integer, step: Int = 1, res: List[Int] = List()): Unit = {\n if (integer == 0) {\n println(res.size)\n println(res.mkString(\" \"))\n } else {\n val k = integer % 10\n if (k != 0) {\n solve(integer / 10, step * 10, k * step :: res)\n } else {\n solve(integer / 10, step * 10, res)\n }\n }\n }\n\n for (i <- 1 to n) {\n val m = in.nextInt()\n solve(m)\n }\n\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val count = StdIn.readInt()\n (0 until count)\n .map(_ => StdIn.readInt())\n .map(x => extractLocal(x))\n .foreach(x => {\n println(x.length)\n x.foreach(y => print(y.toString() + ' '))\n println()\n })\n }\n\n @tailrec\n def extractLocal(s: Int, result: List[Int] = Nil): List[Int] = {\n if (s == 0) {\n result\n } else if (s < 10) {\n s :: result\n } else {\n val min = findMin(s)\n val mod = s % min\n if (min < 10) min :: result\n else extractLocal(mod, (s - mod) :: result)\n }\n }\n\n def findMin(s: Int) =\n if (s > 1000) 1000\n else if (s > 100) 100\n else if (s > 10) 10\n else s\n\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject A {\n\n @tailrec\n def ks(n: Int, acc: Seq[Int], l: Int): Seq[Int] =\n if (n < 10) acc :+ (n * l) else {\n ks(n / 10, acc ++ Some(n % 10).filter(_ != 0).map(_ * l), l * 10)\n }\n\n def solution(n: Int): Seq[Int] = {\n ks(n, Seq.empty, 1)\n }\n\n def main(args: Array[String]): Unit = {\n for (_ <- (0 until StdIn.readLine().toInt)) {\n val result = A.solution(StdIn.readLine().toInt)\n println(result.length)\n println(result.mkString(\" \"))\n }\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable\nimport scala.collection.mutable.ListBuffer\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C640B(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t =ni()\n REP(t) { _ =>\n val n = ni()\n var x = n\n var tens = 1\n val ls = new ListBuffer[Int]\n while (x > 0) {\n val r = x % 10\n if(r * tens > 0) ls += r * tens\n tens *= 10\n x /= 10\n }\n out.println(ls.length)\n out.println(ls.mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readLine()\n val l = n.length()\n val rs = n.zipWithIndex.filterNot(_._1 == '0').map { case (c, i) => (c - 48) * math.pow(10, l - i - 1).toInt }\n\n println(rs.length)\n println(rs.mkString(\" \"))\n }\n}\n"}, {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readLine()\n val rs = n.reverse.zipWithIndex\n .collect { case (c, i) if c != '0' => (c - 48) * math.pow(10, i).toInt }\n\n println(rs.length)\n println(rs.mkString(\" \"))\n }\n}\n"}], "negative_code": [{"source_code": "\nimport scala.io.StdIn\n\n\nobject Test extends App {\n\n val s = StdIn.readLine().toInt\n (1 to s).foreach{_ =>\n var n = StdIn.readLine().toInt\n var ans = List.empty[Int]\n if(n == 10000)println(n) else {\n if (n / 1000 != 0) {\n val x = (n / 1000) * 1000\n ans = (x :: ans)\n n = n - x\n }\n if (n / 100 != 0) {\n val x = (n / 100) * 100\n ans = (x :: ans)\n n = n - x\n }\n if(n / 10 != 0){\n val x = (n / 10) * 10\n ans = (x :: ans)\n n = n - x\n }\n if(n != 0){\n ans = n :: ans\n }\n println(ans.size)\n ans.foreach(x => print(s\"$x \"))\n println()\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readInt\n\nobject Scala {\n def main(args: Array[String]): Unit = {\n var t: Int = readInt()\n while (t > 0) {\n var x: Int = readInt()\n var sum: Int = 1;\n while (x > 0) {\n var m: Int = x % 10\n if(m > 0) {\n print(s\"${sum * m} \")\n }\n x /= 10\n sum = sum * 10;\n }\n println()\n t -= 1\n }\n }\n}"}], "src_uid": "cd2519f4a7888b2c292f05c64a9db13a"} {"source_code": "import scala.io.StdIn.readLine\nobject Main {\n def main(args: Array[String]): Unit = {\n val lines = readLine.split(\" \").map(_.toInt)\n val n = lines(0)\n val k = lines(1)\n if (k == 1) {\n print((1 to n).mkString(\" \"))\n }\n else {\n var a = 1\n var b = n\n\n for (i <- 1 to k/2) {\n print(b + \" \" + a + \" \")\n a += 1\n b -= 1\n\n }\n \n if (k%2 != 0) {\n print((a to b).reverse.mkString(\" \"))\n }\n else {\n print((a to b).mkString(\" \"))\n }\n\n }\n\n\n }\n \n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val r = (0 until k).map { i =>\n if (i % 2 != 0) n - i / 2\n else i / 2 + 1\n }.toList\n val d = r.last\n val z = (k until n).map {\n i => if (d > n / 2) d - i + k - 1\n else d + i - k + 1\n }.toList\n println((r ::: z).mkString(\" \"))\n}"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Main {\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(br.readLine())\n\n def nextDouble = next.toDouble\n def nextLong = next.toLong\n def nextInt = next.toInt\n\n def next = {\n while (!st.hasMoreTokens)\n st = new StringTokenizer(br.readLine())\n st.nextToken()\n }\n\n def main(args: Array[String]) {\n val n = nextInt\n val k = nextInt\n\n var inc = -1\n var cur = n\n print(n + \" \")\n for (i <- k to 1 by -1) {\n cur += inc * i\n print(cur + \" \")\n inc = -inc\n }\n for (i <- n - k - 1 to 1 by -1)\n print(i + \" \")\n }\n\n}\n\n\n"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k) = readLongs(2)\n\n var l = 1l\n var r = n\n\n val res = new mutable.ArrayBuilder.ofLong\n\n res += l\n l += 1\n\n for (i <- 1l until k) {\n if (i % 2 == 1) {\n res += r\n r -= 1\n } else {\n res += l\n l += 1\n }\n }\n\n if (k % 2 == 0) {\n for (i <- k + 1 to n) {\n res += r\n r -= 1\n }\n } else {\n for (i <- k + 1 to n) {\n res += l\n l += 1\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.result.mkString(\" \"))\n Console.flush\n\n}"}, {"source_code": "import java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuilder\n\nobject _482A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val k = next.toInt\n\n if (k == 1) println((1 to n).mkString(\" \"))\n else {\n // e.g. n = 8\n // 2 3 4 5 6 7 |8 1 <- k = 2\n // 7 6 5 4 3 |2 8 1 <- k = 3\n // 3 4 5 6 |7 2 8 1 <- k = 4\n // 6 5 4 |3 7 2 8 1 <- k = 5\n // 4 5 |6 3 7 2 8 1 <- k = 6\n // 5 |4 6 3 7 2 8 1 <- k = 7\n\n //e.g. n = 5\n // 2 3 4 5 1\n // 4 3 2 5 1\n // 3 4 2 5 1\n\n val ans = new ArrayBuilder.ofInt\n ans += 1\n ans += n\n\n def doit(i: Int, pre: Int, left: Int, right: Int) {\n if (i < n) {\n if (i >= k) {\n if ((pre - left).abs == 1) {\n ans += left\n doit(i + 1, left, left + 1, right)\n } else {\n ans += right\n doit(i + 1, right, left, right - 1)\n }\n } else {\n if (i % 2 == 0) {\n ans += left\n doit(i + 1, left, left + 1, right)\n } else {\n ans += right\n doit(i + 1, right, left, right - 1)\n }\n }\n }\n }\n\n doit(2, n, 2, n - 1)\n println(ans.result().mkString(\" \"))\n }\n}\n"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuilder\n\nobject _482A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val k = next.toInt\n\n if (k == 1) println((1 to n).mkString(\" \"))\n else {\n // e.g. n = 8\n // 2 3 4 5 6 7 |8 1 <- k = 2\n // 7 6 5 4 3 |2 8 1 <- k = 3\n // 3 4 5 6 |7 2 8 1 <- k = 4\n // 6 5 4 |3 7 2 8 1 <- k = 5\n // 4 5 |6 3 7 2 8 1 <- k = 6\n // 5 |4 6 3 7 2 8 1 <- k = 7\n\n //e.g. n = 5\n // 2 3 4 5 1\n // 4 3 2 5 1\n // 3 4 2 5 1\n\n val ans = new ArrayBuilder.ofInt\n ans += 1\n ans += n\n\n def doit(i: Int, left: Int, right: Int) {\n if (i < n) {\n if (i % 2 == 0) {\n ans += left\n doit(i + 1, left + 1, right)\n } else {\n ans += right\n doit(i + 1, left, right - 1)\n }\n }\n }\n\n doit(2, 2, n - 1)\n println(ans.result().mkString(\" \"))\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nobject Main {\n def main(args: Array[String]): Unit = {\n val lines = readLine.split(\" \").map(_.toInt)\n val n = lines(0)\n val k = lines(1)\n if (k == 1) {\n print((1 to n).mkString(\" \"))\n }\n else {\n var a = 1\n var b = n\n\n for (i <- 1 to k/2) {\n print(b + \" \" + a)\n a += 1\n b -= 1\n }\n print(\" \")\n if (k%2 != 0) {\n print((a to b).reverse.mkString(\" \"))\n }\n else {\n print((a to b).mkString(\" \"))\n }\n\n }\n\n\n }\n \n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k) = readInts(2)\n\n var x = 1L\n\n val res = new mutable.ArrayBuilder.ofLong\n\n res += x\n for (i <- 1 to k) {\n x += i\n res += x\n }\n\n for (i <- k + 2 to n) {\n x += 1\n res += x\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.result.mkString(\" \"))\n Console.flush\n\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k) = readLongs(2)\n\n var l = 1l\n var r = n\n\n val res = new mutable.ArrayBuilder.ofLong\n\n res += l\n l += 1\n \n for (i <- 1l until k) {\n if (i % 2 == 1) {\n res += r\n r -= 1\n } else {\n res += l\n l += 1\n }\n }\n\n for (i <- k + 1 to n) {\n res += l\n l += 1\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.result.mkString(\" \"))\n Console.flush\n\n}"}], "src_uid": "18b3d8f57ecc2b392c7b1708f75a477e"} {"source_code": "import collection.mutable\n\nobject A {\n\tdef main(args: Array[String]) {\n\t\tval n = readLine().toInt\n val a = readLine().split(\" \").map(x => x.toInt)\n val b = new mutable.HashMap[Int, Int]\n for (x <- a) {\n if (!b.contains(x))\n b(x) = 0\n b(x) += 1\n }\n var good = true\n var ans = 0\n for (x <- b.keySet if x > 0) {\n if (b(x) > 2)\n good = false\n if (b(x) == 2)\n ans += 1\n }\n if (good)\n println(ans)\n else\n println(-1)\n\t}\n}", "positive_code": [{"source_code": "object A {\n def READ: Array[Int] = readLine() split (\" \") map (_.toInt);\n def main(args: Array[String]) {\n var Array(n) = READ\n var a = READ;\n var b = a.distinct.filter(_>0) map (x => a.count(_==x));\n if (b exists(_>2)) println(-1)\n else println(b count(_==2))\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val map = scala.collection.mutable.Map[Int, Int]()\n a.foreach(id => if (id != 0) map(id) = map.getOrElse(id, 0) + 1)\n val r = map.values.foldLeft(0) { (acc, count) => \n if (count == 2 && acc != -1) acc + 1\n else if (count > 2) -1\n else acc\n }\n println(r)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n StdIn.readInt()\n\n val arr = StdIn.readLine.split(\" \").map(_.toInt)\n\n val map = arr.foldLeft(Map[Int, Int]())(foldArr) - 0\n\n val ans = map.find({case (_, value) => value > 2}) match {\n case None => map.foldLeft(0)({(m: Int, x: (Int, Int)) => m + x._2 - 1})\n case Some(_) => -1\n }\n\n println(ans)\n }\n\n def foldArr(map: Map[Int, Int], x: Int): Map[Int, Int] = map.updated(x, map.getOrElse(x, 0) + 1)\n}\n"}, {"source_code": "import collection.mutable\n\n/**\n * Created by antonkov on 9/17/15.\n */\nobject A {\n def main (args: Array[String]) {\n val n = readLine().toInt\n val a = readLine().split(\" \").map(x => x.toInt)\n val b = new mutable.HashMap[Int, Int]\n for (x <- a) {\n if (!b.contains(x))\n b(x) = 0\n b(x) += 1\n }\n var good = true\n var ans = 0\n for (x <- b.keySet if x > 0) {\n if (b(x) > 2)\n good = false\n if (b(x) == 2)\n ans += 1\n }\n if (good)\n println(ans)\n else\n println(-1)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt).filter(_ != 0)\n val enhanced = data.groupBy(x => x).map(x => x._1 -> x._2.length)\n if (enhanced.exists(_._2 > 2))\n println(-1)\n else\n println(enhanced.count(_._2 == 2))\n}\n"}, {"source_code": "/*\nA. Разговоры в Spyke\nограничение по времени на тест\n2 секунды\nограничение по памяти на тест\n256 мегабайт\nввод\nstandard input\nвывод\nstandard output\n\nПоликарп — директор большой корпорации. В этой корпорации работает n секретарей, каждый из которых пользуется известной VoIP-системой Spyke для ведения переговоров в течение рабочего дня. Известно, что, когда два человека устанавливают телефонное соединение Spyke, сеть Spyke присваивает этому разговору уникальный идентификационный номер (целое положительное число) — номер сессии.\n\nКак-то раз Поликарп захотел узнать, кто из секретарей разговаривает по Spyke, а кто — нет. Он выписал для каждого секретаря номер сессии его разговора, или 0, если этот секретарь сейчас не разговаривает по Spyke.\n\nПомогите Поликарпу по этим данным определить, сколько пар секретарей сейчас ведут разговор между собой. Если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти, требуется сообщить об этом.\n\nОбратите внимание, секретари могут разговаривать по Spyke не только друг с другом — возможны разговоры с внешними собеседниками. Также не разрешены конференции Spyke — то есть в каждом разговоре должны участвовать ровно два собеседника.\nВходные данные\n\nВ первой строке записано целое число n (1 ≤ n ≤ 103) — количество секретарей в корпорации Поликарпа. В следующей строке записаны n целых чисел через пробел: id1, id2, ..., idn (0 ≤ idi ≤ 109). Число idi равно номеру сессии разговора секретаря номер i, если он разговаривает в данный момент по Spyke, или равно нулю, в противном случае.\n\nСчитайте, что секретари пронумерованы от 1 до n некоторым образом.\nВыходные данные\n\nВыведите единственное целое число — количество пар секретарей, которые ведут разговор между собой, или -1, если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти.\nПримеры тестов\nВходные данные\n\n6\n0 1 7 1 7 10\n\nВыходные данные\n\n2\n\nВходные данные\n\n3\n1 1 1\n\nВыходные данные\n\n-1\n\nВходные данные\n\n1\n0\n\nВыходные данные\n\n0\n\nПримечание\n\nВ первом тестовом примере есть два телефонных разговора между секретарями: секретарь номер 2 и секретарь номер 4, секретарь номер 3 и секретарь номер 5.\n\nВо втором тестовом примере описанная ситуация невозможна, так как не разрешены конференции.\n\n */\nobject Task1 extends App {\n\n /** Finds number of pairs, returns -1 if triplet or more */\n def solve(n: Int, ids: IndexedSeq[Long]): Int =\n if (ids.size != n) -1\n else {\n val grouped = ids groupBy (x => x)\n val counts = ((grouped - 0).values map (_.length) toIndexedSeq)\n val dist = counts filterNot (_ < 2)\n if (dist exists (_ > 2)) -1 else dist.size\n }\n\n val (line1, line2) = (readLine, readLine)\n val n = line1.toInt\n val ids = line2 split (' ') map (_.toLong)\n\n val res = solve(n, ids)\n println(res)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P291A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val gs = List.fill(N)(sc.nextInt).filterNot(_ == 0).groupBy(identity[Int]).map(_._2.length)\n\n val answer: Int = {\n gs.find(_ > 2) match {\n case Some(_) => -1\n case None => gs.filter(_ == 2).size\n }\n }\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "import io.Source\nimport java.io.PrintWriter\n\nobject CF291A {\n\n def solve(in: In, out: PrintWriter) {\n val n = in().toInt\n val a = in(n).map(_.toInt).filter(_ != 0).toSeq\n val sizes = a.groupBy(identity).toSeq.map(_._2.size)\n if (sizes.exists(_ > 2)) {\n out.println(-1)\n } else {\n out.println(sizes.count(_ == 2))\n }\n }\n\n def main(args: Array[String]) {\n val in: In = new In(Source.fromInputStream(System.in))\n val out: PrintWriter = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() {\n while (iter.hasNext && delims.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next(): String = {\n skipDelims()\n while (iter.hasNext && delims.indexOf(iter.head) == -1) {\n sb.append(iter.next())\n }\n val ret = sb.toString()\n sb.clear()\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIterator = new TokenIterator(iter, \" \\r\\n\")\n\n val lineIterator = new TokenIterator(iter, \"\\r\\n\")\n\n def apply() = tokenIterator.next()\n\n def apply(n: Int) = tokenIterator.take(n)\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val enhanced = data.groupBy(x => x).map(x => x._1 -> x._2.length)\n if (enhanced.exists(_._2 > 2))\n println(-1)\n else\n println(enhanced.count(_._2 == 2))\n}\n"}, {"source_code": "/*\nA. Разговоры в Spyke\nограничение по времени на тест\n2 секунды\nограничение по памяти на тест\n256 мегабайт\nввод\nstandard input\nвывод\nstandard output\n\nПоликарп — директор большой корпорации. В этой корпорации работает n секретарей, каждый из которых пользуется известной VoIP-системой Spyke для ведения переговоров в течение рабочего дня. Известно, что, когда два человека устанавливают телефонное соединение Spyke, сеть Spyke присваивает этому разговору уникальный идентификационный номер (целое положительное число) — номер сессии.\n\nКак-то раз Поликарп захотел узнать, кто из секретарей разговаривает по Spyke, а кто — нет. Он выписал для каждого секретаря номер сессии его разговора, или 0, если этот секретарь сейчас не разговаривает по Spyke.\n\nПомогите Поликарпу по этим данным определить, сколько пар секретарей сейчас ведут разговор между собой. Если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти, требуется сообщить об этом.\n\nОбратите внимание, секретари могут разговаривать по Spyke не только друг с другом — возможны разговоры с внешними собеседниками. Также не разрешены конференции Spyke — то есть в каждом разговоре должны участвовать ровно два собеседника.\nВходные данные\n\nВ первой строке записано целое число n (1 ≤ n ≤ 103) — количество секретарей в корпорации Поликарпа. В следующей строке записаны n целых чисел через пробел: id1, id2, ..., idn (0 ≤ idi ≤ 109). Число idi равно номеру сессии разговора секретаря номер i, если он разговаривает в данный момент по Spyke, или равно нулю, в противном случае.\n\nСчитайте, что секретари пронумерованы от 1 до n некоторым образом.\nВыходные данные\n\nВыведите единственное целое число — количество пар секретарей, которые ведут разговор между собой, или -1, если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти.\nПримеры тестов\nВходные данные\n\n6\n0 1 7 1 7 10\n\nВыходные данные\n\n2\n\nВходные данные\n\n3\n1 1 1\n\nВыходные данные\n\n-1\n\nВходные данные\n\n1\n0\n\nВыходные данные\n\n0\n\nПримечание\n\nВ первом тестовом примере есть два телефонных разговора между секретарями: секретарь номер 2 и секретарь номер 4, секретарь номер 3 и секретарь номер 5.\n\nВо втором тестовом примере описанная ситуация невозможна, так как не разрешены конференции.\n\n */\nobject Task1 extends App {\n\n /** Finds number of pairs, returns -1 if triplet or more */\n def solve(n: Int, ids: IndexedSeq[Int]): Int = {\n val grouped = ids groupBy (x => x)\n val counts = (grouped.values map (_.length) toIndexedSeq)\n val dist = counts filterNot (_ == 1)\n if (dist exists (_ > 2)) -1 else dist.size\n }\n\n val (line1, line2) = (readLine, readLine)\n val n = line1.toInt\n val ids = line2 split (' ') map (_.toInt)\n\n val res = solve(n, ids)\n println(res)\n}"}, {"source_code": "/*\nA. Разговоры в Spyke\nограничение по времени на тест\n2 секунды\nограничение по памяти на тест\n256 мегабайт\nввод\nstandard input\nвывод\nstandard output\n\nПоликарп — директор большой корпорации. В этой корпорации работает n секретарей, каждый из которых пользуется известной VoIP-системой Spyke для ведения переговоров в течение рабочего дня. Известно, что, когда два человека устанавливают телефонное соединение Spyke, сеть Spyke присваивает этому разговору уникальный идентификационный номер (целое положительное число) — номер сессии.\n\nКак-то раз Поликарп захотел узнать, кто из секретарей разговаривает по Spyke, а кто — нет. Он выписал для каждого секретаря номер сессии его разговора, или 0, если этот секретарь сейчас не разговаривает по Spyke.\n\nПомогите Поликарпу по этим данным определить, сколько пар секретарей сейчас ведут разговор между собой. Если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти, требуется сообщить об этом.\n\nОбратите внимание, секретари могут разговаривать по Spyke не только друг с другом — возможны разговоры с внешними собеседниками. Также не разрешены конференции Spyke — то есть в каждом разговоре должны участвовать ровно два собеседника.\nВходные данные\n\nВ первой строке записано целое число n (1 ≤ n ≤ 103) — количество секретарей в корпорации Поликарпа. В следующей строке записаны n целых чисел через пробел: id1, id2, ..., idn (0 ≤ idi ≤ 109). Число idi равно номеру сессии разговора секретаря номер i, если он разговаривает в данный момент по Spyke, или равно нулю, в противном случае.\n\nСчитайте, что секретари пронумерованы от 1 до n некоторым образом.\nВыходные данные\n\nВыведите единственное целое число — количество пар секретарей, которые ведут разговор между собой, или -1, если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти.\nПримеры тестов\nВходные данные\n\n6\n0 1 7 1 7 10\n\nВыходные данные\n\n2\n\nВходные данные\n\n3\n1 1 1\n\nВыходные данные\n\n-1\n\nВходные данные\n\n1\n0\n\nВыходные данные\n\n0\n\nПримечание\n\nВ первом тестовом примере есть два телефонных разговора между секретарями: секретарь номер 2 и секретарь номер 4, секретарь номер 3 и секретарь номер 5.\n\nВо втором тестовом примере описанная ситуация невозможна, так как не разрешены конференции.\n\n */\nobject Task1 extends App {\n\n /** Finds number of pairs, returns -1 if triplet or more */\n def solve(n: Int, ids: IndexedSeq[Long]): Int = {\n val grouped = ids groupBy (x => x)\n val counts = (grouped.values map (_.length) toIndexedSeq)\n val dist = counts filterNot (_ < 2)\n if (dist exists (_ > 2)) -1 else dist.size\n }\n\n val (line1, line2) = (readLine, readLine)\n val n = line1.toInt\n val ids = line2 split (' ') map (_.toLong)\n\n val res = solve(n, ids)\n println(res)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P291A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val gs = List.fill(N)(sc.nextInt).groupBy(identity[Int]).map(_._2.length)\n\n val answer: Int = {\n gs.find(_ > 2) match {\n case Some(_) => -1\n case None => gs.filter(_ == 2).size\n }\n }\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "import io.Source\nimport java.io.PrintWriter\n\nobject CF291A {\n\n def solve(in: In, out: PrintWriter) {\n val n = in().toInt\n val a = in(n).map(_.toInt).toSeq\n val sizes = a.groupBy(identity).toSeq.map(_._2.size)\n if (sizes.exists(_ > 2)) {\n out.println(-1)\n } else {\n out.println(sizes.count(_ == 2))\n }\n }\n\n def main(args: Array[String]) {\n val in: In = new In(Source.fromInputStream(System.in))\n val out: PrintWriter = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() {\n while (iter.hasNext && delims.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next(): String = {\n skipDelims()\n while (iter.hasNext && delims.indexOf(iter.head) == -1) {\n sb.append(iter.next())\n }\n val ret = sb.toString()\n sb.clear()\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIterator = new TokenIterator(iter, \" \\r\\n\")\n\n val lineIterator = new TokenIterator(iter, \"\\r\\n\")\n\n def apply() = tokenIterator.next()\n\n def apply(n: Int) = tokenIterator.take(n)\n }\n}"}, {"source_code": "import io.Source\nimport java.io.PrintWriter\n\nobject CF291A {\n\n def solve(in: In, out: PrintWriter) {\n val n = in().toInt\n val a = in(n).filter(_ != 0).map(_.toInt).toSeq\n val sizes = a.groupBy(identity).toSeq.map(_._2.size)\n if (sizes.exists(_ > 2)) {\n out.println(-1)\n } else {\n out.println(sizes.count(_ == 2))\n }\n }\n\n def main(args: Array[String]) {\n val in: In = new In(Source.fromInputStream(System.in))\n val out: PrintWriter = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() {\n while (iter.hasNext && delims.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next(): String = {\n skipDelims()\n while (iter.hasNext && delims.indexOf(iter.head) == -1) {\n sb.append(iter.next())\n }\n val ret = sb.toString()\n sb.clear()\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIterator = new TokenIterator(iter, \" \\r\\n\")\n\n val lineIterator = new TokenIterator(iter, \"\\r\\n\")\n\n def apply() = tokenIterator.next()\n\n def apply(n: Int) = tokenIterator.take(n)\n }\n}"}, {"source_code": "object A {\n def READ: Array[Int] = readLine() split (\" \") map (_.toInt);\n def main(args: Array[String]) {\n var Array(n) = READ\n var a = READ;\n var b = a.distinct map (x => a.count(_==x));\n if (b exists(_>2)) println(-1)\n else println(b count(_==2))\n }\n}\n"}, {"source_code": "object A {\n def READ: Array[Int] = readLine() split (\" \") map (_.toInt);\n def main(args: Array[String]) {\n var Array(n) = READ\n var a = READ;\n var b = a.distinct.map(_>0) map (x => a.count(_==x));\n if (b exists(_>2)) println(-1)\n else println(b count(_==2))\n }\n}\n"}], "src_uid": "45e51f3dee9a22cee86e1a98da519e2d"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n\n REP(ni()) { _ =>\n val a = ni()\n\n val all1 = Integer.highestOneBit(a) - 1 + Integer.highestOneBit(a)\n // 全部ビットたっているかどうか\n val ans = if (all1 == a) {\n // 全部ビットたっていたら gcd(a^b, a&b) == gcd(b, ~b)\n // b + ~b == a == (n + m) * c\n // n + m >= 2でcを最大化なので、すなわち2番目に大きいdevisorといっしょ\n val d = divisors(a)\n d(d.length - 2)\n } else {\n // 0のビットがあるのでa&b==0 のbをつくることができる\n // 一番左は0になりえないので、b = ~a のとき b^a == 2^n - 1 で最大にできる\n all1\n }\n out.println(ans)\n }\n }\n\n /**\n * O(√x)\n */\n def divisors(x: Int): Array[Int] = {\n val pre = ArrayBuffer[Int]()\n val post = ArrayBuffer[Int]()\n REP(math.sqrt(x).toInt, 1) { d =>\n if (x % d == 0) {\n pre += d\n if (d * d != x) post += x / d\n }\n }\n\n val res = Array.ofDim[Int](pre.length + post.length)\n REP(pre.length)(i => res(i) = pre(i))\n val preLen = pre.length\n val postLen = post.length\n REP(postLen)(i => res(i + preLen) = post(postLen - 1 - i))\n res\n }\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n", "positive_code": [{"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(q) = readInts(1)\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n\n val m = Map(\n 3 -> 1,\n 7 -> 1,\n 15 -> 5,\n 31 -> 1,\n 63 -> 21,\n 127 -> 1,\n 255 -> 85,\n 511 -> 73,\n 1023 -> 341,\n 2047 -> 89,\n 4095 -> 1365,\n 8191 -> 1,\n 16383 -> 5461,\n 32767 -> 4681,\n 65535 -> 21845,\n 131071 -> 1,\n 262143 -> 87381,\n 524287 -> 1,\n 1048575 -> 349525,\n 2097151 -> 299593,\n 4194303 -> 1398101,\n 8388607 -> 178481,\n 16777215 -> 5592405,\n 33554431 -> 1082401)\n\n// for (i <- 1 to 25) {\n// val a = (1 << i) - 1\n// var max = 0L\n// for (b <- 1 until a) {\n// val res = gcd(a ^ b, a & b)\n// if (res > max) max = res\n// }\n// println(s\"$a -> $max,\")\n// }\n\n for (_ <- 1 to q) {\n val a = readLine.toInt\n val mask = Integer.highestOneBit(a) * 2 - 1\n val b = a ^ mask\n val res = m.getOrElse(a, gcd(a ^ b, a & b))\n println(res)\n }\n}\n"}], "negative_code": [{"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(q) = readInts(1)\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n\n for (_ <- 1 to q) {\n val a = readLine.toInt\n val mask = Integer.highestOneBit(a) * 2 - 1\n val b = a ^ mask\n val res = if (b == 0) 1 else gcd(a ^ b, a & b)\n println(res)\n }\n}\n"}], "src_uid": "ce9a0649ccfc956559254f324dfa02a7"} {"source_code": "//import scala.util.Random\n\nobject Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, w, h) = in.next().split(' ').map(_.toInt)\n// val n = 5000\n// val w = 1\n// val h = 1\n// val r = new Random()\n// val t = System.nanoTime()\n\n// (1 to 10).foreach{ _ =>\n val line = (0 until n).map{i =>\n val Array(w1, h1) = in.next().split(' ').map(_.toInt)\n (w1, h1, i + 1)\n// (Random.nextInt(1000000), Random.nextInt(1000000), i + 1)\n }.filter(i => i._1 > w && i._2 > h).sortBy(- _._1).toArray\n\n val dp = Array.ofDim[Int](line.length)\n val prev = Array.ofDim[Int](line.length)\n\n line.indices.foreach { i =>\n var j = 0\n var max = 0\n var maxIndex = -1\n while (j < i) {\n if (line(j)._1 > line(i)._1 && line(j)._2 > line(i)._2 && dp(j) > max) {\n maxIndex = j\n max = dp(j)\n }\n j += 1\n }\n\n dp(i) = 1 + max\n prev(i) = maxIndex\n }\n\n if (dp.isEmpty)\n println(0)\n else {\n val max = dp.max\n println(max)\n var p = dp.indices.find(i => dp(i) == max).get\n var answer = List.empty[Int]\n\n while (p != -1) {\n answer ::= line(p)._3\n p = prev(p)\n }\n\n println(answer.reverse.mkString(\" \"))\n }\n//}\n// println(System.nanoTime() - t)\n// 6336504045\n// 4874416168\n// 6579074027\n\n// 6149716536\n// 6057171782\n// 5041613499\n\n// 5141237046\n// 5987173184\n// 5025914418\n}", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject DLetters extends App {\n\n val scanner = new Scanner(System.in)\n\n val numLetters = scanner.fastInt\n val card = Letter(scanner.fastInt, scanner.fastInt, -1)\n\n val l = (for {\n order <- 1 until numLetters + 1\n letter = Letter(scanner.fastInt, scanner.fastInt, order) if card.canFit(letter)\n } yield letter).sortBy(_.x).toList\n\n val letters = (card :: l).toArray\n\n val trace = Array.ofDim[Int](letters.size)\n val longest = Array.ofDim[Int](letters.size)\n\n var maxInd = 0\n\n (0 until letters.size).foreach { i =>\n (0 until i).foreach { j =>\n if (letters(j).canFit(letters(i)) && longest(j) >= longest(i) - 1) {\n longest(i) = longest(j) + 1\n trace(i) = j\n if (longest(i) > longest(maxInd)) maxInd = i\n }\n }\n }\n\n println(longest(maxInd))\n printResult(maxInd, Nil)\n\n def printResult(traceIndex: Int, acc: List[Int]): Unit = {\n if (traceIndex == 0) {\n println(acc.mkString(\" \"))\n } else {\n printResult(trace(traceIndex), letters(traceIndex).order :: acc)\n }\n }\n\n case class Letter(x: Int, y: Int, order: Int) {\n\n def canFit(other: Letter): Boolean = this.x < other.x && this.y < other.y\n\n }\n\n implicit class ScannerExt(sc: Scanner) {\n\n def fastInt: Int = sc.next().toInt\n\n }\n\n}"}, {"source_code": "object D4 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, w, h) = readInts(3)\n val in = Array.fill(n)(readInts(2))\n .map(arr => (arr(0), arr(1)))\n .zipWithIndex\n .filter{case ((a, b), _) => a > w && b > h}\n .sorted\n val len = in.length\n if(len > 0) {\n val dp = Array.fill(len)(1)\n val idx = Array.fill(len)(-1)\n for (i <- 1 until len) {\n for (j <- 0 until i) {\n if (in(i)._1._1 > in(j)._1._1 && in(i)._1._2 > in(j)._1._2 && dp(i) < dp(j)+1) {\n dp(i) = dp(j)+1\n idx(i) = j\n }\n }\n }\n val max = dp.max\n println(max)\n val res = cu.ArrayBuffer.empty[Int]\n var i = dp.lastIndexWhere(_ == max)\n while(i != -1) {\n res.append(in(i)._2 + 1)\n i = idx(i)\n }\n println(res.reverse.mkString(\" \"))\n } else {\n println(\"0\")\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\nimport java.util\n\nobject D {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def comp(x: ((Int, Int), Int), y: ((Int, Int), Int)): Boolean = {\n val s1: Long = Int.int2long(x._1._1) * Int.int2long(x._1._2)\n val s2: Long = Int.int2long(y._1._1) * Int.int2long(y._1._2)\n s1 < s2\n }\n\n def couldInsert(envelope1: (Int, Int), envelope2: (Int, Int)): Boolean = {\n envelope1._1 < envelope2._1 && envelope1._2 < envelope2._2\n }\n\n def couldInsert2(envelope1: ((Int, Int), Int), envelope2: ((Int, Int), Int)): Boolean = {\n envelope1._1._1 < envelope2._1._1 && envelope1._1._2 < envelope2._1._2\n }\n\n def solve = {\n val n = nextInt\n val postcard = (nextInt, nextInt)\n val envelopes = new Array[(Int, Int)](n)\n for (i <- 0 until n) {\n envelopes(i) = (nextInt, nextInt)\n }\n val cleanedEnvelopes = new util.ArrayList[((Int, Int), Int)]()\n for (i <- 0 until n) {\n if (couldInsert(postcard, envelopes(i))) {\n cleanedEnvelopes.add((envelopes(i), i))\n }\n }\n var zippedEnv = cleanedEnvelopes.toArray(new Array[((Int, Int), Int)](0))\n zippedEnv = zippedEnv.sortWith(comp)\n// zippedEnv.foreach(print)\n val len = zippedEnv.length\n if (len == 0) {\n out.println(0)\n } else {\n val d = new Array[Int](len)\n val p = new Array[Int](len)\n d(0) = 1\n p(0) = -1\n for (i <- 1 until len) {\n val a = zippedEnv(i)\n var max = -1\n var pj = -1\n for (j <- 0 until i) {\n if (couldInsert2(zippedEnv(j), a)) {\n if (d(j) > max) {\n max = d(j)\n pj = j\n }\n }\n }\n if (max + 1 > 1) {\n p(i) = pj\n d(i) = max + 1\n } else {\n p(i) = -1\n d(i) = 1\n }\n }\n // d.foreach(x => print(x + \" \"))\n // p.foreach(x => print(x + \" \"))\n var max = -1\n var start = -1\n for (i <- 0 until len) {\n if (max < d(i)) {\n max = d(i)\n start = i\n }\n }\n out.println(max)\n val ans = new Array[Int](max)\n var ind = 0\n while (start != -1) {\n ans(ind) = zippedEnv(start)._2 + 1\n ind += 1\n start = p(start)\n }\n for (i <- 0 until max) {\n out.print(ans(max - i - 1) + \" \")\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "object main extends App with fastIO {\n \n val n = nextInt\n val w = nextInt\n val h = nextInt \n \n var p = 0\n var a = Array.fill(n) { p += 1; Point(nextInt, nextInt, p) }.filter((it) => it.x > w && it.y > h).sortWith(_ < _)\n var dp = Array.fill(n)( 0 ) \n \n var ans = 0\n var ind = 0\n \n for (i <- 0 until a.length) {\n var value = 1\n for (j <- 0 until i) if (a(j).x < a(i).x && a(j).y < a(i).y)\n value = math.max(value, dp(j) + 1)\n \n dp(i) = value\n if (value > ans) { ans = dp(i); ind = i } \n }\n var res = Array.fill(ans)( 0 )\n \n if (ans > 0) {\n res(ans - 1) = ind\n for (i <- ind - 1 to (0, -1))\n if (dp(i) + 1 == ans && a(i).x < a(ind).x && a(i).y < a(ind).y) {\n ans -= 1; ind = i\n res(ans - 1) = i \n } \n }\n \n println(res.length) \n for (i <- res) \n print(a(i).id + \" \")\n \n flush \n}\n\ncase class Point(x: Int, y: Int, id: Int) {\n def < (b: Point): Boolean = { this.x < b.x || this.x == b.x && this.y > b.y }\n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "object P4D {\n class PrefixMax(m : Int) {\n val s = 1 << Math.getExponent(m.toFloat) + 1\n val a = Array.fill(s + s){(0, 0)}\n def add(n : Int, x : (Int, Int)) {\n var i = s + n\n while (i > 0) {\n if (x._1 > a(i)._1) a(i) = x\n i = i >>> 1\n }\n }\n def get(n : Int) = {\n var i = s + n\n var ans = (0, -1)\n while (i > 1) {\n if ((i & 1) == 1) {\n val x = a(i - 1)\n if (x._1 > ans._1) ans = x\n }\n i = i >>> 1\n }\n ans\n }\n }\n\n def main(args: Array[String]) {\n val Array(n, wS, hS) = readLine split \" \" map {_.toInt}\n val a = for (id <- (1 to n).toIterator) yield {\n val Array(w, h) = readLine split \" \" map {_.toInt}\n (w, h, id)\n }\n val aF = a.filter{case (w, h, id) => w > wS && h > hS}.toArray\n val awT = aF.map{_._1}.sorted.distinct\n val awR = awT.zipWithIndex.toMap\n val ahT = aF.map{_._2}.sorted.distinct\n val ahR = ahT.zipWithIndex.toMap\n val aL = aF.map{case (w, h, id) => (awR(w), ahR(h), id)}.sorted\n val s = new PrefixMax(ahT.size + 1)\n val q = collection.mutable.ArrayBuffer[(Int, Int, Int)]()\n var qW = -1\n def flushQ(w : Int) {\n for ((h, i, len) <- q) s.add(h, (len, i))\n q.clear\n qW = w\n }\n val fromN = for (i <- 0 until aL.size) yield {\n val (w, h, _) = aL(i)\n if (w != qW) flushQ(w)\n val (len, from) = s.get(h)\n val lenN = len + 1\n q += ((h, i, lenN))\n from\n }\n flushQ(-1)\n val (len, from) = s.get(ahT.size)\n if (len == 0) {\n println(\"0\")\n } else {\n println(len)\n val b = Iterator.iterate(from)(fromN).takeWhile{_ != -1}.toBuffer\n println(b.reverseMap{i => aL(i)._3} mkString \" \")\n }\n }\n}\n"}, {"source_code": "object P4D {\n class PrefixMax(m : Int) {\n val s = 1 << Math.getExponent(m.toFloat) + 1\n val a = Array.fill(s + s){(0, 0)}\n def add(n : Int, x : (Int, Int)) {\n var i = s + n\n while (i > 0) {\n if (x._1 > a(i)._1) a(i) = x\n i = i >>> 1\n }\n }\n def get(n : Int) = {\n var i = s + n\n var ans = (0, -1)\n while (i > 1) {\n if ((i & 1) == 1) {\n val x = a(i - 1)\n if (x._1 > ans._1) ans = x\n }\n i = i >>> 1\n }\n ans\n }\n }\n\n def main(args: Array[String]) {\n val Array(n, wS, hS) = readLine split \" \" map {_.toInt}\n val a = for (id <- (1 to n).toIterator) yield {\n val Array(w, h) = readLine split \" \" map {_.toInt}\n (w, h, id)\n }\n val aF = a.filter{case (w, h, id) => w > wS && h > hS}.toArray\n val awT = aF.map{_._1}.sorted.distinct\n val awR = awT.zipWithIndex.toMap\n val ahT = aF.map{_._2}.sorted.distinct\n val ahR = ahT.zipWithIndex.toMap\n val aL = aF.map{case (w, h, id) => (awR(w), ahR(h), id)}.sorted\n val s = new PrefixMax(ahT.size + 1)\n val q = collection.mutable.ArrayBuffer[(Int, Int, Int)]()\n var qW = -1\n def flushQ(w : Int) {\n for ((h, i, len) <- q) s.add(h, (len, i))\n q.clear\n qW = w\n }\n val fromN = for (i <- 0 until aL.size) yield {\n val (w, h, _) = aL(i)\n if (w != qW) flushQ(w)\n val (len, from) = s.get(h)\n val lenN = len + 1\n q += ((h, i, lenN))\n from\n }\n flushQ(-1)\n val (len, from) = s.get(ahT.size)\n if (len == 0) {\n println(\"0\")\n } else {\n println(len)\n val b = Iterator.iterate(from)(fromN).takeWhile{_ != -1}.toBuffer\n println(b.reverse.map{i => aL(i)._3} mkString \" \")\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.immutable.Seq\n\nobject Solution {\n\n def printDPArr(dpArr: Array[Int], sorted:Array[Box], prev:Array[Int], maxIdx: Int): Unit = {\n var l = List.empty[Short]\n var idx = maxIdx\n while(idx >=0) {\n l = sorted(idx).idx :: l\n idx = prev(idx)\n }\n\n println(l.mkString(\" \"))\n }\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n val (n, cardW, cardH) = (in.nextInt(), in.nextInt(), in.nextInt())\n val arr: Array[Box] = Array.tabulate(n)(i => Box(in.nextInt(), in.nextInt(), (i+1).toShort))\n val fittingBoxes = arr.filter(c => c.w > cardW && c.h > cardH )\n val sorted: Array[Box] = fittingBoxes.sortBy(b => (b.w, b.h))\n\n if(sorted.nonEmpty) {\n //main code\n\n\n val dpArr = Array.ofDim[Int](sorted.length)\n val prev = Array.ofDim[Int](sorted.length)\n\n for {\n i <- dpArr.indices\n } {\n i match {\n case 0 =>\n dpArr(0) = 1\n prev(0) = -1\n case ii =>\n val sortedZipped: (Int, Int) = (0 until ii).foldLeft(-1, -1)((acc, iii) =>{\n if(dpArr(iii)>acc._1 && sorted(ii).w > sorted(iii).w && sorted(ii).h > sorted(iii).h) {\n (dpArr(iii), iii)\n } else {\n acc\n }\n }\n\n )\n if(sortedZipped == (-1, -1)) {\n dpArr(ii) = 1\n prev(ii) = -1\n } else {\n dpArr(ii) = sortedZipped._1 + 1\n prev(ii) = sortedZipped._2\n }\n }\n }\n val max = dpArr.max\n println(max)\n printDPArr(dpArr, sorted, prev, dpArr.indexOf(max))\n } else {\n println(0)\n }\n\n }\n\n case class Box(w: Int, h: Int, idx: Short)\n\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, w, h) = in.next().split(' ').map(_.toInt)\n\n val line = (0 until n).map{i =>\n in.next().split(' ').map(_.toInt)\n }.sortBy(_.head)\n\n val dp = Array.fill[Int](n)(1)\n val prev = Array.ofDim[Int](n)\n var dpMax = -1\n var i = 0\n\n while (i < n) {\n var j = 0\n var max = 0\n var maxIndex = -1\n while (j < i) {\n if (line(j).head > line(i).head && line(j).last > line(i).last && line(j).head > w && line(j).last > w && dp(j) > max) {\n maxIndex = j\n max = dp(j)\n }\n j += 1\n }\n\n if (maxIndex == -1) {\n prev(i) = -1\n }\n else {\n dp(i) = 1 + max\n prev(i) = maxIndex\n }\n if (dpMax == -1 || dp(dpMax) < dp(i))\n dpMax = i\n i += 1\n }\n\n\n if (dpMax == -1)\n println(0)\n else {\n var answer = List.empty[Int]\n println(dp(dpMax))\n\n while (dpMax != -1) {\n answer ::= dpMax + 1\n dpMax = prev(dpMax)\n }\n\n println(answer.reverse.mkString(\" \"))\n }\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, w, h) = in.next().split(' ').map(_.toInt)\n\n val line = (0 until n).map{i =>\n val Array(w1, h1) = in.next().split(' ').map(_.toInt)\n (w1, h1, i + 1)\n }.filter(i => i._1 >= w && i._2 >= h).sorted.reverse\n\n val dp = Array.ofDim[Int](line.length)\n val prev = Array.ofDim[Int](line.length)\n\n line.indices.foreach { i =>\n val indices = (0 until i).filter(j => line(j)._1 > line(i)._1 && line(j)._2 > line(i)._2)\n if (indices.isEmpty) {\n dp(i) = 1\n prev(i) = -1\n }\n else {\n val index = indices.maxBy(j => dp(j))\n dp(i) = 1 + dp(index)\n prev(i) = index\n }\n }\n\n val max = dp.max\n println(max)\n var p = dp.indices.find(i => dp(i) == max).get\n var answer = List.empty[Int]\n\n while (p != -1) {\n answer ::= line(p)._3\n p = prev(p)\n }\n\n println(answer.reverse.mkString(\" \"))\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, w, h) = in.next().split(' ').map(_.toInt)\n\n val line = (0 until n).map{i =>\n in.next().split(' ').map(_.toInt)\n }.sortBy(_.head)\n\n val dp = Array.fill[Int](n)(1)\n val prev = Array.ofDim[Int](n)\n var dpMax = -1\n var i = 0\n\n while (i < n) {\n var j = 0\n var max = 0\n var maxIndex = -1\n while (j < n) {\n if (line(j).head > line(i).head && line(j).last > line(i).last && dp(j) > max) {\n maxIndex = j\n max = dp(j)\n }\n j += 1\n }\n\n if (maxIndex == -1) {\n prev(i) = -1\n }\n else {\n dp(i) = 1 + max\n prev(i) = maxIndex\n }\n if (dpMax == -1 || dp(dpMax) < dp(i))\n dpMax = i\n i += 1\n }\n\n\n if (dpMax == -1)\n println(0)\n else {\n var answer = List.empty[Int]\n println(dp(dpMax))\n\n while (dpMax != -1) {\n answer ::= dpMax + 1\n dpMax = prev(dpMax)\n }\n\n println(answer.reverse.mkString(\" \"))\n }\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, w, h) = in.next().split(' ').map(_.toInt)\n\n val line = (0 until n).map{i =>\n val Array(w1, h1) = in.next().split(' ').map(_.toInt)\n (w1, h1, i + 1)\n }\n\n val dp = Array.ofDim[Int](n)\n val prev = Array.ofDim[Int](n)\n var dpMax = -1\n var i = 0\n\n while (i < line.length) {\n var j = 0\n var max = 0\n var maxIndex = -1\n while (j < n) {\n if (line(j)._1 > line(i)._1 && line(j)._2 > line(i)._2 && dp(j) > max) {\n maxIndex = j\n max = dp(j)\n }\n j += 1\n }\n\n if (maxIndex == -1) {\n dp(i) = 1\n prev(i) = -1\n }\n else {\n dp(i) = 1 + max\n prev(i) = maxIndex\n }\n if (dpMax == -1 || dp(dpMax) < dp(i))\n dpMax = i\n i += 1\n }\n\n if (dpMax == -1)\n println(0)\n else {\n println(dp(dpMax))\n var answer = List.empty[Int]\n\n while (dpMax != -1) {\n answer ::= line(dpMax)._3\n dpMax = prev(dpMax)\n }\n\n println(answer.reverse.mkString(\" \"))\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject Solution {\n\n def printDPArr(dpArr: Array[Short], boxes:Array[Box], max: Short): Unit = {\n var aMax = max\n var prev: Option[Box] = None\n for {\n i <- dpArr.indices\n } {\n if(aMax == dpArr(i) && prev.fold(true)(b => boxes(i).w > b.w && boxes(i).h > b.h)){\n aMax = (aMax + 1).toShort\n print(s\"${boxes(i).idx} \")\n prev = Option(boxes(i))\n }\n }\n println()\n }\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n val (n, cardW, cardH) = (in.nextInt(), in.nextInt(), in.nextInt())\n val arr: Array[Box] = Array.tabulate(n)(i => Box(in.nextInt(), in.nextInt(), (i+1).toShort))\n val fittingBoxes = arr.filter(c => c.w > cardW && c.h > cardH )\n val grouped: Array[Array[Box]] = fittingBoxes\n .groupBy(_.w)\n .mapValues(_.sortBy(_.h))\n .toArray\n .sortBy(_._1)\n .map(_._2)\n\n if(grouped.isEmpty){\n println(0)\n return\n }\n\n val dpArr = Array.ofDim[Short](grouped.length)\n val boxes = Array.ofDim[Box](grouped.length)\n\n for {\n i <- dpArr.indices\n } {\n i match {\n case 0 =>\n dpArr(0) = 1\n boxes(0) = grouped(0)(0)\n case ii if boxes.slice(0, ii).exists(b => grouped(ii).exists(g => g.h > b.h)) =>\n val values: Seq[(Short, Box)] = dpArr\n .slice(0, ii)\n .zipWithIndex\n .flatMap(p => grouped(ii).find(g => g.h > boxes(p._2).h).map(p._1 -> _))\n\n val maxDPVal = values.maxBy(_._1)._1\n boxes(ii) = values.filter(_._1==maxDPVal).minBy(_._2.h)._2\n dpArr(ii) = (maxDPVal + 1).toShort\n case ii =>\n dpArr(ii) = 1\n boxes(ii) = grouped(i)(0)\n }\n }\n val max = dpArr.max\n println(max)\n printDPArr(dpArr, boxes, 1)\n\n }\n\n case class Box(w: Int, h: Int, idx: Short)\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Solution {\n\n def printDPArr(dpArr: Array[Short], boxes:Array[Box],prev:Array[Int], max: Short): Unit = {\n var l = List.empty[Short]\n var idx = dpArr.indexOf(max)\n while(idx >=0) {\n l = boxes(idx).idx :: l\n idx = prev(idx)\n }\n\n println(l.mkString(\" \"))\n }\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n val (n, cardW, cardH) = (in.nextInt(), in.nextInt(), in.nextInt())\n val arr: Array[Box] = Array.tabulate(n)(i => Box(in.nextInt(), in.nextInt(), (i+1).toShort))\n val fittingBoxes = arr.filter(c => c.w > cardW && c.h > cardH )\n val grouped: Array[Array[Box]] = fittingBoxes\n .groupBy(_.w)\n .mapValues(_.sortBy(_.h))\n .toArray\n .sortBy(_._1)\n .map(_._2)\n\n if(grouped.isEmpty){\n println(0)\n return\n }\n\n val dpArr = Array.ofDim[Short](grouped.length)\n val boxes = Array.ofDim[Box](grouped.length)\n val prev = Array.ofDim[Int](grouped.length)\n\n for {\n i <- dpArr.indices\n } {\n i match {\n case 0 =>\n dpArr(0) = 1\n boxes(0) = grouped(0)(0)\n prev(0) = -1\n case ii if boxes.slice(0, ii).exists(b => grouped(ii).exists(g => g.h > b.h)) =>\n val values: Array[((Short, Int), Box)] = dpArr\n .slice(0, ii)\n .zipWithIndex\n .flatMap(p => grouped(ii).find(g => g.h > boxes(p._2).h).map(p -> _))\n\n val maxDPVal = values.maxBy(_._1._1)._1._1\n val by: ((Short, Int), Box) = values.filter(_._1._1 == maxDPVal).minBy(_._2.h)\n boxes(ii) = by._2\n dpArr(ii) = (maxDPVal + 1).toShort\n prev(ii) = by._1._2\n case ii =>\n dpArr(ii) = 1\n boxes(ii) = grouped(i)(0)\n prev(ii) = -1\n }\n }\n val max = dpArr.max\n println(max)\n printDPArr(dpArr, boxes,prev, max)\n\n }\n\n case class Box(w: Int, h: Int, idx: Short)\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Solution {\n\n def printDPArr(dpArr: Array[Short], boxes:Array[Box], max: Short): Unit = {\n var aMax = max\n for {\n i <- dpArr.indices\n } {\n if(aMax == dpArr(i)){\n aMax = (aMax + 1).toShort\n print(s\"${boxes(i).idx} \")\n }\n }\n println()\n }\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n val (n, cardW, cardH) = (in.nextInt(), in.nextInt(), in.nextInt())\n val arr: Array[Box] = Array.tabulate(n)(i => Box(in.nextInt(), in.nextInt(), (i+1).toShort))\n val fittingBoxes = arr.filter(c => c.w > cardW && c.h > cardH )\n val grouped: Array[Array[Box]] = fittingBoxes\n .groupBy(_.w)\n .mapValues(_.sortBy(_.h))\n .toArray\n .sortBy(_._1)\n .map(_._2)\n\n if(grouped.isEmpty){\n println(0)\n return\n }\n\n val dpArr = Array.ofDim[Short](grouped.length)\n val boxes = Array.ofDim[Box](grouped.length)\n\n for {\n i <- dpArr.indices\n } {\n i match {\n case 0 =>\n dpArr(0) = 1\n boxes(0) = grouped(0)(0)\n case ii if boxes.slice(0, ii).exists(b => grouped(ii).exists(g => g.h > b.h)) =>\n val values: Seq[(Short, Box)] = dpArr\n .slice(0, ii)\n .zipWithIndex\n .flatMap(p => grouped(ii).find(g => g.h > boxes(p._2).h).map(p._1 -> _))\n\n val maxDPVal = values.maxBy(_._1)._1\n boxes(ii) = values.filter(_._1==maxDPVal).minBy(_._2.h)._2\n dpArr(ii) = (maxDPVal + 1).toShort\n case ii =>\n dpArr(ii) = 1\n boxes(ii) = grouped(i)(0)\n }\n }\n val max = dpArr.max\n println(max)\n printDPArr(dpArr, boxes, 1)\n\n }\n\n case class Box(w: Int, h: Int, idx: Short)\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Solution {\n\n def printDPArr(dpArr: Array[Short], boxes:Array[Box], max: Short): Unit = {\n var aMax = max\n for {\n i <- dpArr.indices\n } {\n if(aMax == dpArr(i)){\n aMax = (aMax + 1).toShort\n print(s\"${boxes(i).idx} \")\n }\n }\n println()\n }\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n val (n, cardW, cardH) = (in.nextInt(), in.nextInt(), in.nextInt())\n val arr: Array[Box] = Array.tabulate(n)(i => Box(in.nextInt(), in.nextInt(), (i+1).toShort))\n val fittingBoxes = arr.filter(c => c.w > cardW || c.h > cardH )\n val grouped: Array[Array[Box]] = fittingBoxes\n .groupBy(_.w)\n .mapValues(_.sortBy(_.h))\n .toArray\n .sortBy(_._1)\n .map(_._2)\n\n if(grouped.isEmpty){\n println(0)\n return\n }\n\n val dpArr = Array.ofDim[Short](grouped.length)\n val boxes = Array.ofDim[Box](grouped.length)\n\n for {\n i <- dpArr.indices\n } {\n i match {\n case 0 =>\n dpArr(0) = 1\n boxes(0) = grouped(0)(0)\n case ii if boxes.slice(0, ii).exists(b => grouped(ii).exists(g => g.h > b.h)) =>\n val values: Seq[(Short, Box)] = dpArr\n .slice(0, ii)\n .zipWithIndex\n .flatMap(p => grouped(ii).find(g => g.h > boxes(p._2).h).map(p._1 -> _))\n\n val maxDPVal = values.maxBy(_._1)._1\n boxes(ii) = values.filter(_._1==maxDPVal).minBy(_._2.h)._2\n dpArr(ii) = (maxDPVal + 1).toShort\n case ii =>\n dpArr(ii) = 1\n boxes(ii) = grouped(i)(0)\n }\n }\n val max = dpArr.max\n println(max)\n printDPArr(dpArr, boxes, 1)\n\n }\n\n case class Box(w: Int, h: Int, idx: Short)\n\n}\n"}, {"source_code": "object D4 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, w, h) = readInts(3)\n val in = Array.fill(n)(readInts(2))\n .map(arr => (arr(0), arr(1)))\n .zipWithIndex\n .filter{case ((a, b), _) => a > w && b > h}\n .sorted\n val len = in.length\n if(len > 0) {\n val buff = Array.fill(len)(cu.ArrayBuffer.empty[Int])\n buff(0).append(0)\n for (i <- 1 until len) {\n for (j <- 0 until i) {\n if (in(i)._1._1 > in(j)._1._1 && in(i)._1._2 > in(j)._1._2 && buff(i).length < buff(j).length) {\n buff(i) = buff(j)\n }\n }\n buff(i).append(in(i)._2)\n }\n println(buff.last.length)\n println(buff.last.map(_ + 1).mkString(\" \"))\n } else {\n println(\"0\")\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object D4 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, w, h) = readInts(3)\n val in = Array.fill(n)(readInts(2))\n .map(arr => (arr(0), arr(1)))\n .zipWithIndex\n .filter{case ((a, b), _) => a > w && b > h}\n .sorted\n val len = in.length\n if(len > 0) {\n val buff = Array.fill(len)(cu.ArrayBuffer.empty[Int])\n buff(0).append(0)\n for (i <- 1 until len) {\n for (j <- 0 until i) {\n if (in(i)._1._1 > in(j)._1._1 && in(i)._1._2 > in(j)._1._2 && buff(i).length < buff(j).length) {\n buff(i) = buff(j)\n }\n }\n buff(i).append(in(i)._2)\n }\n println(len)\n println(buff.last.map(_ + 1).mkString(\" \"))\n } else {\n println(\"0\")\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object D4 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, w, h) = readInts(3)\n val in = Array.fill(n)(readInts(2))\n .map(arr => (arr(0), arr(1)))\n .zipWithIndex\n .filter{case ((a, b), _) => a > w && b > h}\n .sorted\n val len = in.length\n if(len > 0) {\n val buff = Array.fill(len)(cu.ArrayBuffer.empty[Int])\n buff(0).append(in(0)._2)\n for (i <- 1 until len) {\n for (j <- 0 until i) {\n if (in(i)._1._1 > in(j)._1._1 && in(i)._1._2 > in(j)._1._2 && buff(i).length < buff(j).length) {\n buff(i) = buff(j)\n }\n }\n buff(i).append(in(i)._2)\n }\n println(buff.last.length)\n println(buff.last.map(_ + 1).mkString(\" \"))\n } else {\n println(\"0\")\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\nimport java.util\n\nobject D {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def comp(x: ((Int, Int), Int), y: ((Int, Int), Int)): Boolean = {\n x._1._1 * x._1._2 < y._1._1 * y._1._2\n }\n\n def couldInsert(envelope1: (Int, Int), envelope2: (Int, Int)): Boolean = {\n envelope1._1 < envelope2._1 && envelope1._2 < envelope2._2\n }\n\n def couldInsert2(envelope1: ((Int, Int), Int), envelope2: ((Int, Int), Int)): Boolean = {\n envelope1._1._1 < envelope2._1._1 && envelope1._1._2 < envelope2._1._2\n }\n\n def solve = {\n val n = nextInt\n val postcard = (nextInt, nextInt)\n val envelopes = new Array[(Int, Int)](n)\n for (i <- 0 until n) {\n envelopes(i) = (nextInt, nextInt)\n }\n val cleanedEnvelopes = new util.ArrayList[(Int, Int)]()\n for (i <- 0 until n) {\n if (couldInsert(postcard, envelopes(i))) {\n cleanedEnvelopes.add(envelopes(i))\n }\n }\n var zippedEnv = cleanedEnvelopes.toArray(new Array[(Int, Int)](0)).zipWithIndex\n zippedEnv = zippedEnv.sortWith(comp)\n val len = zippedEnv.length\n if (len == 0) {\n out.println(0)\n } else {\n val d = new Array[Int](len)\n val p = new Array[Int](len)\n d(0) = 1\n p(0) = -1\n for (i <- 1 until len) {\n val a = zippedEnv(i)\n var max = -1\n var pj = -1\n for (j <- 0 until i) {\n if (couldInsert2(zippedEnv(j), a)) {\n if (d(j) > max) {\n max = d(j)\n pj = j\n }\n }\n }\n if (max + 1 > 1) {\n p(i) = pj\n d(i) = max + 1\n } else {\n p(i) = -1\n d(i) = 1\n }\n }\n // d.foreach(x => print(x + \" \"))\n // p.foreach(x => print(x + \" \"))\n var max = -1\n var start = -1\n for (i <- 0 until len) {\n if (max < d(i)) {\n max = d(i)\n start = i\n }\n }\n out.println(max)\n val ans = new Array[Int](max)\n var ind = 0\n while (start != -1) {\n ans(ind) = zippedEnv(start)._2 + 1\n ind += 1\n start = p(start)\n }\n for (i <- 0 until max) {\n out.print(ans(max - i - 1) + \" \")\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\nimport java.util\n\nobject D {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def comp(x: ((Int, Int), Int), y: ((Int, Int), Int)): Boolean = {\n x._1._1 * x._1._2 < y._1._1 * y._1._2\n }\n\n def couldInsert(envelope1: (Int, Int), envelope2: (Int, Int)): Boolean = {\n envelope1._1 < envelope2._1 && envelope1._2 < envelope2._2\n }\n\n def couldInsert2(envelope1: ((Int, Int), Int), envelope2: ((Int, Int), Int)): Boolean = {\n envelope1._1._1 < envelope2._1._1 && envelope1._1._2 < envelope2._1._2\n }\n\n def solve = {\n val n = nextInt\n val postcard = (nextInt, nextInt)\n val envelopes = new Array[(Int, Int)](n)\n for (i <- 0 until n) {\n envelopes(i) = (nextInt, nextInt)\n }\n val cleanedEnvelopes = new util.ArrayList[((Int, Int), Int)]()\n for (i <- 0 until n) {\n if (couldInsert(postcard, envelopes(i))) {\n cleanedEnvelopes.add((envelopes(i), i))\n }\n }\n var zippedEnv = cleanedEnvelopes.toArray(new Array[((Int, Int), Int)](0))\n zippedEnv = zippedEnv.sortWith(comp)\n val len = zippedEnv.length\n if (len == 0) {\n out.println(0)\n } else {\n val d = new Array[Int](len)\n val p = new Array[Int](len)\n d(0) = 1\n p(0) = -1\n for (i <- 1 until len) {\n val a = zippedEnv(i)\n var max = -1\n var pj = -1\n for (j <- 0 until i) {\n if (couldInsert2(zippedEnv(j), a)) {\n if (d(j) > max) {\n max = d(j)\n pj = j\n }\n }\n }\n if (max + 1 > 1) {\n p(i) = pj\n d(i) = max + 1\n } else {\n p(i) = -1\n d(i) = 1\n }\n }\n // d.foreach(x => print(x + \" \"))\n // p.foreach(x => print(x + \" \"))\n var max = -1\n var start = -1\n for (i <- 0 until len) {\n if (max < d(i)) {\n max = d(i)\n start = i\n }\n }\n out.println(max)\n val ans = new Array[Int](max)\n var ind = 0\n while (start != -1) {\n ans(ind) = zippedEnv(start)._2 + 1\n ind += 1\n start = p(start)\n }\n for (i <- 0 until max) {\n out.print(ans(max - i - 1) + \" \")\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "object main extends App with fastIO {\n \n var t = Array.fill(4 * 1000007)( 0 )\n \n def get(v: Int, l: Int, r: Int, pl: Int, pr: Int): Int = {\n if (pl > pr || pl > r || l > pr) return 0\n if (pl <= l && r <= pr) return t(v)\n \n val lr = (l + r) >> 1 \n get(v + v, l, lr, pl, pr) + \n get(v + v + 1, lr + 1, r, pl, pr)\n }\n \n def update(v: Int, l: Int, r: Int, x: Int, value: Int): Int = {\n if (l == r) { t(v) = math.max(t(v), value); return t(v) }\n \n val lr = (l + r) >> 1\n t(v) = math.max(t(v),\n if (x <= lr) \n update(v + v, l, lr, x, value) else\n update(v + v + 1, lr + 1, r, x, value)\n ) \n t(v)\n }\n \n val n = nextInt\n val w = nextInt\n val h = nextInt \n \n var p = 0\n var a: Array[Point] = Array.fill(n) { p += 1; Point(nextInt, nextInt, p) }.filter((it) => it.x > w && it.y > h).sortWith(_ < _)\n var dp = Array.fill(n)( 0 ) \n \n for (i <- a) println(i) \n \n var ans = 0\n var ind = 0\n \n for (i <- 0 until a.length) { \n val value = get(1, 1, 1000000, 1, a(i).y - 1)\n update(1, 1, 1000000, a(i).y, value + 1)\n \n dp(i) = value + 1\n if (dp(i) > ans) { ans = dp(i); ind = i } \n }\n var res = Array.fill(ans)( 0 )\n \n if (ans > 0) {\n res(ans - 1) = ind\n for (i <- ind - 1 to (0, -1))\n if (dp(i) + 1 == ans && a(i).x < a(ind).x && a(i).y < a(ind).y) {\n ans -= 1; ind = i\n res(ans - 1) = i \n } \n }\n \n println(res.length) \n for (i <- res) \n print(a(i).id + \" \")\n \n flush \n}\n\ncase class Point(x: Int, y: Int, id: Int) {\n def < (b: Point): Boolean = { this.x < b.x || this.x == b.x && this.y > b.y }\n}\n\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush()\n}"}, {"source_code": "object main extends App with fastIO {\n \n var t = Array.fill(4 * 1000007)( 0 )\n \n def get(v: Int, l: Int, r: Int, pl: Int, pr: Int): Int = {\n if (pl > pr || pl > r || l > pr) return 0\n if (pl <= l && r <= pr) return t(v)\n \n val lr = (l + r) >> 1 \n get(v + v, l, lr, pl, pr) + \n get(v + v + 1, lr + 1, r, pl, pr)\n }\n \n def update(v: Int, l: Int, r: Int, x: Int, value: Int): Int = {\n if (l == r) { t(v) = math.max(t(v), value); return t(v) }\n \n val lr = (l + r) >> 1\n t(v) = math.max(t(v),\n if (x <= lr) \n update(v + v, l, lr, x, value) else\n update(v + v + 1, lr + 1, r, x, value)\n ) \n t(v)\n }\n \n val n = nextInt\n val w = nextInt\n val h = nextInt \n \n var p = 0\n var a = Array.fill(n) { p += 1; Point(nextInt, nextInt, p) }.filter((it) => it.x > w && it.y > h).sortWith((p1, p2) => p1 < p2)\n var dp = Array.fill(n)( 0 ) \n \n var ans = 0\n var ind = 0\n \n for (i <- 0 until n) { \n val value = get(1, 1, 1000000, 1, a(i).y - 1)\n update(1, 1, 1000000, a(i).y, value + 1)\n \n dp(i) = value + 1\n if (dp(i) > ans) { ans = dp(i); ind = i } \n }\n \n var res = Array.fill(ans)( 0 )\n \n res(ans - 1) = ind\n for (i <- ind - 1 to (0, -1))\n if (dp(i) + 1 == ans && a(i).x < a(ind).x && a(i).y < a(ind).y) {\n ans -= 1; ind = i\n res(ans - 1) = i \n } \n \n println(res.length) \n for (i <- res) \n Console.printf(\"%d \", a(i).id)\n\n flush \n}\n\ncase class Point(x: Int, y: Int, id: Int) {\n def < (b: Point): Boolean = { this.x < b.x || this.x == b.x && this.y > b.y }\n}\n\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush()\n}"}, {"source_code": "object main extends App with fastIO {\n \n var t = Array.fill(4 * 1000007)( 0 )\n \n def get(v: Int, l: Int, r: Int, pl: Int, pr: Int): Int = {\n if (pl > pr || pl > r || l > pr) return 0\n if (pl <= l && r <= pr) return t(v)\n \n val lr = (l + r) >> 1 \n get(v + v, l, lr, pl, pr) + \n get(v + v + 1, lr + 1, r, pl, pr)\n }\n \n def update(v: Int, l: Int, r: Int, x: Int, value: Int): Int = {\n if (l == r) { t(v) = math.max(t(v), value); return t(v) }\n \n val lr = (l + r) >> 1\n t(v) = math.max(t(v),\n if (x <= lr) \n update(v + v, l, lr, x, value) else\n update(v + v + 1, lr + 1, r, x, value)\n ) \n t(v)\n }\n \n val n = nextInt\n val w = nextInt\n val h = nextInt \n \n var p = 0\n var a: Array[Point] = Array.fill(n) { p += 1; Point(nextInt, nextInt, p) }.filter((it) => it.x > w && it.y > h).sortWith(_ < _)\n var dp = Array.fill(n)( 0 ) \n \n var ans = 0\n var ind = 0\n \n for (i <- 0 until a.length) { \n val value = get(1, 1, 1000000, 1, a(i).y - 1)\n update(1, 1, 1000000, a(i).y, value + 1)\n \n dp(i) = value + 1\n if (dp(i) > ans) { ans = dp(i); ind = i } \n }\n var res = Array.fill(ans)( 0 )\n \n if (ans > 0) {\n res(ans - 1) = ind\n for (i <- ind - 1 to (0, -1))\n if (dp(i) + 1 == ans && a(i).x < a(ind).x && a(i).y < a(ind).y) {\n ans -= 1; ind = i\n res(ans - 1) = i \n } \n }\n \n println(res.length) \n for (i <- res) \n print(a(i).id + \" \")\n \n flush \n}\n\ncase class Point(x: Int, y: Int, id: Int) {\n def < (b: Point): Boolean = { this.x < b.x || this.x == b.x && this.y > b.y }\n}\n\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush()\n}"}], "src_uid": "6f88e3f4c8a8a444d44e58505a750d3e"} {"source_code": "import java.util.Scanner\n\nobject P381B {\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val m = sc.nextInt()\n val seq = for (i <- 1 to m) yield sc.nextInt()\n val distinctSeq = seq.distinct\n val duplicatedSeq = seq diff distinctSeq\n val dupDistinctSeq = duplicatedSeq.distinct\n val leftSeq = distinctSeq.sorted\n val rightSeq = dupDistinctSeq.sorted.reverse\n val ans = if (!rightSeq.isEmpty && leftSeq.last == rightSeq.head)\n leftSeq.init ++ rightSeq else leftSeq ++ rightSeq\n println(ans.length)\n println(ans.mkString(\" \"))\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt).sorted\n val answer = Array.ofDim[Int](n)\n (0 until n).foreach { i =>\n val index = if (i % 2 == 0) i / 2 else n - 1 - i / 2\n answer(index) = data(i)\n }\n val r = answer.tail.foldLeft(List(answer.head)) {\n case (l, el) if l.head == el => l\n case (l, el) => el :: l\n }\n println(r.length)\n println(r.mkString(\" \"))\n\n}\n"}, {"source_code": "\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n val n = input.next().toInt\n val ns = input.next().split(\" \").map(_.toInt).toList\n var s = ns.sortBy(-_)\n s = s.head :: s\n var l = List(s(0))\n var r = List(s(1))\n s = s.drop(2)\n while(s.nonEmpty) {\n if (s.head != l.head) {\n l = s.head :: l\n } else if (s.head != r.head) {\n r = s.head :: r\n }\n s = s.tail\n }\n val res = l ++ r.reverse.tail\n println(res.length)\n println(res.mkString(\" \"))\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P381B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = sc.nextInt\n val A = List.fill(N)(sc.nextInt).groupBy(identity).map(x => (x._1 -> x._2.size)).toMap\n\n val downOrd = Ordering.Int.reverse\n val down = A.keys.toList.sorted(downOrd)\n val top = down.head\n val up = A.filter(x => x._2 > 1).toMap.keys.toList.filterNot(_ == top).sorted\n\n val res = up ::: down\n\n out.println(res.size)\n out.println(res.mkString(\" \"))\n }\n \n solve\n out.close\n}\n"}], "negative_code": [{"source_code": "\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n val n = input.next().toInt\n val ns = input.next().split(\" \").map(_.toInt).toList\n var s = ns.sortBy(-_)\n if (s.length > 1 && s(0) == s(1)) s = s.tail\n val res = if (s.length == 1) {\n List(s(0))\n } else {\n var l = List(s(0))\n var r = List(s(1))\n var t = s.drop(2)\n while(t.nonEmpty) {\n if (t.head != l.head) {\n l = t.head :: l\n } else if (t.head != r.head) {\n r = t.head :: r\n }\n t = t.tail\n }\n println(l)\n println(r)\n l ++ r.reverse\n }\n println(res.mkString(\" \"))\n }\n}\n"}, {"source_code": "\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n val n = input.next().toInt\n val ns = input.next().split(\" \").map(_.toInt).toList\n var s = ns.sortBy(-_)\n if (s.length > 1 && s(0) == s(1)) s = s.tail\n val res = if (s.length == 1) {\n List(s(0))\n } else {\n var l = List(s(0))\n var r = List(s(1))\n var t = s.drop(2)\n while(t.nonEmpty) {\n if (t.head != l.head) {\n l = t.head :: l\n } else if (t.head != r.head) {\n r = t.head :: r\n }\n t = t.tail\n }\n println(l)\n println(r)\n l ++ r.reverse\n }\n println(res.length)\n println(res.mkString(\" \"))\n }\n}\n"}, {"source_code": "\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n val n = input.next().toInt\n val ns = input.next().split(\" \").map(_.toInt).toList\n var s = ns.sortBy(-_)\n if (s.length > 1 && s(0) == s(1)) s = s.tail\n val res = if (s.length == 1) {\n List(s(0))\n } else {\n var l = List(s(0))\n var r = List(s(1))\n var t = s.drop(2)\n while(t.nonEmpty) {\n if (t.head != l.head) {\n l = t.head :: l\n } else if (t.head != r.head) {\n r = t.head :: r\n }\n t = t.tail\n }\n l ++ r.reverse\n }\n println(res.length)\n println(res.mkString(\" \"))\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P381B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): String = {\n val N = sc.nextInt\n val A = List.fill(N)(sc.nextInt).groupBy(identity).map(x => (x._1 -> x._2.size)).toMap\n\n val up = A.keys.toList.sorted\n val top = up.last\n val ord = Ordering.Int.reverse\n val down = A.filter(x => x._2 > 1).toMap.keys.toList.filterNot(_ == top).sorted(ord)\n\n (up ::: down).mkString(\" \")\n }\n \n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P381B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): String = {\n val N = sc.nextInt\n val A = List.fill(N)(sc.nextInt).groupBy(identity).map(x => (x._1 -> x._2.size)).toMap\n\n val downOrd = Ordering.Int.reverse\n val down = A.keys.toList.sorted(downOrd)\n val top = down.head\n val up = A.filter(x => x._2 > 1).toMap.keys.toList.filterNot(_ == top).sorted\n\n (up ::: down).mkString(\" \")\n }\n \n out.println(solve)\n out.close\n}\n"}], "src_uid": "5c63f91eb955cb6c3172cb7c8f78976c"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S = ns()\n\n // aaの組み合わせ, 直前のbaの組み合わせ\n var pre = 0L\n var ans = 0L\n REP(S.length) { i =>\n S(i) match {\n case 'a' =>\n ans = (ans + pre + 1) % MOD\n\n case 'b' =>\n pre = ans\n\n case _ =>\n }\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object CF_526_2_C {\n\n def solve(s: String): Int = {\n\n val justAB = s.filter(c => c == 'a' || c == 'b').toList\n def answer(seq: List[Char], last: Char, lastVal: Long, total: Long): Int = seq match {\n case Nil => assert(total < Int.MaxValue); total.toInt\n case 'a' :: tail => last match {\n case 'b' =>\n val n = total + 1\n answer(tail, 'a', n, (total + n) % modulo)\n case 'a' => answer(tail, 'a', lastVal, (total + lastVal) % modulo)\n }\n case 'b' :: tail => answer(tail, 'b', lastVal, total)\n }\n answer(justAB, 'b', 0, 0)\n }\n\n // Specify Input and Output formats here:\n def formatIn(i: Input) = i.nextLine\n def formatOut(out: Int) = out.toString\n\n\n// ~~~ Boilerplate & utility methods that don't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n def main(args: Array[String]) = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n\n import java.util.Scanner\n\n import scala.util.matching.Regex\n class Input(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine() \n // Remember to call nextLine to advance past the newline character (if required) before collecting the line:\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def solveVals = (solve _).tupled(formatIn(this))\n def solveStr = formatOut(solveVals)\n }\n\n def ceil(a: Int, b: Int) = (a - 1) / b + 1\n def ceil(a: Long, b: Long) = (a - 1) / b + 1\n val modulo = 1000000007\n\n import language.implicitConversions\n implicit def stringToInput(s: String): Input = new Input(s)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { def tupled: T => R = x => f(x) }\n}"}], "negative_code": [{"source_code": "object CF_526_2_C {\n\n def solve(s: String): Int = {\n def split(in: String, out: Seq[Seq[Long]], last: Long): Seq[Seq[Long]] = {\n def stringToPowers(str: String) = Seq.iterate(last, str.filter(_=='a').length)(x => (x*2) % modulo)\n in.indexOfSlice(\"aa\") match {\n case -1 => out :+ stringToPowers(in)\n case i =>\n val (a,b) = in.splitAt(i+1)\n val seq = stringToPowers(a)\n split(b, out :+ seq, seq.last)\n }\n }\n val justAB = \"a|b\".r.findAllIn(s).mkString\n val longs = split(justAB, Vector.empty, 1)\n (longs.map(_.sum).sum % modulo).toInt\n }\n\n // Specify Input and Output formats here:\n def formatIn(i: Input) = i.nextLine\n def formatOut(out: Int) = out.toString\n\n\n// ~~~ Boilerplate & utility methods that don't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n def main(args: Array[String]) = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n\n import java.util.Scanner\n class Input(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine() \n // Remember to call nextLine to advance past the newline character (if required) before collecting the line:\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def solveVals = (solve _).tupled(formatIn(this))\n def solveStr = formatOut(solveVals)\n }\n\n def ceil(a: Int, b: Int) = (a - 1) / b + 1\n def ceil(a: Long, b: Long) = (a - 1) / b + 1\n val modulo = 1000000007\n\n import language.implicitConversions\n implicit def stringToInput(s: String): Input = new Input(s)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { def tupled: T => R = x => f(x) }\n}"}], "src_uid": "a765463559901e608035083be47aa245"} {"source_code": "object Main extends App{\n val n = readInt()\n var live = new Array[Int](3)\n var die = new Array[Int](3)\n for (i <- 1 to n){\n var Array(which, nLive, nDie) = readLine().split(\" \").map(_.toInt)\n if (which != 1) which = 2\n live(which) += nLive\n die(which) += nDie\n }\n for (i <- 1 to 2){\n if (live(i) >= die(i))\n println(\"LIVE\")\n else\n println(\"DEAD\")\n }\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\n\nobject P245A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n\n def solve(): List[String] = {\n val buf = List.fill(2)(new ListBuffer[Int])\n \n for (_ <- 0 until N) {\n val t, x, _ = sc.nextInt\n buf(t - 1) += x\n }\n\n buf.map { b =>\n val xs = b.toList\n if (xs.sum >= xs.size * 5) \"LIVE\"\n else \"DEAD\"\n }\n }\n \n solve.foreach { s => out.println(s) }\n out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val a = (1 to n).map(_ => readLine().split(\" \").map(_.toInt))\n val map = scala.collection.mutable.Map[Int, (Int, Int)]()\n a.foreach{ a0 => \n val e = map.getOrElse(a0(0), (0, 0))\n map(a0(0)) = (e._1 + a0(1), e._2 + a0(2)) \n }\n val e1 = map(1)\n val e2 = map(2)\n if (e1._1 >= e1._2) println(\"LIVE\") else println(\"DEAD\")\n if (e2._1 >= e2._2) println(\"LIVE\") else println(\"DEAD\") \n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n\n val n = in.next().toInt\n val (f, s) = (1 to n).foldLeft((0, 0)) {\n case ((first, second), _) =>\n val Array(a, g, d) = in.next().split(' ').map(_.toInt)\n if (a == 1)\n (first + g - d, second)\n else\n (first, second + g - d)\n }\n if (f >= 0)\n println(\"LIVE\")\n else\n println(\"DEAD\")\n \n if (s >= 0)\n println(\"LIVE\")\n else\n println(\"DEAD\")\n}\n"}, {"source_code": "import scala.collection.mutable._\n\nobject Main extends App {\n val sc = new java.util.Scanner(System.in)\n\n val n = sc.nextInt()\n\n val ans = Array.tabulate(n)(_ => (sc.nextInt(), sc.nextInt(), sc.nextInt()))\n .groupBy(_._1).mapValues { list =>\n list.reduce((a, b) => (a._1, a._2 + b._2, a._3 + b._3))\n }\n\n for (i <- 1 to 2) {\n val (a, x, y) = ans(i)\n println(if (x >= y) \"LIVE\" else \"DEAD\")\n }\n\n}\n"}], "negative_code": [], "src_uid": "1d8870a705036b9820227309d74dd1e8"} {"source_code": "\nimport scala.math._\n\nobject Problem extends App {\n import Scanner._\n\n val s = readLine\n val count = Array.ofDim[Int](s.length)\n for(i <- 1 until s.length)\n count(i) = count(i-1) + (if(s(i) == s(i-1)) 1 else 0)\n\n for(i <- 1 to readInt; a = readInt-1; b = readInt-1)\n println(count(b) - count(a))\n}\n\nobject Scanner {\n def readInt() = {\n var acc = 0\n readWith {\n case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n }\n acc\n }\n def readLong() = {\n var acc = 0L\n readWith {\n case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10L) + (c - '0')\n }\n acc\n }\n def readDouble() = {\n var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)\n readWith {\n case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>\n frac = (frac * 10) + (c - '0')\n fracPow *= 10\n case c if c == '.' && !readFrac =>\n readFrac = true\n }\n acc + (frac.toDouble / fracPow)\n }\n def readString() = {\n var string = new StringBuilder\n readWith { case c => string += c }\n string\n }\n def readLine() = Console.in.readLine()\n def readChar() = Console.in.read().toChar\n def readWith(func: PartialFunction[Char, Unit]) {\n val handler = func orElse[Char, Unit] {\n case _ => throw new java.io.IOException(\"unexpected token\")\n }\n\n var c = readChar\n while(c.isWhitespace)\n c = readChar\n\n while(!c.isWhitespace) {\n handler(c)\n\n c = readChar\n }\n }\n}\n\n", "positive_code": [{"source_code": "object CF186Div2B {\n def main(args:Array[String]){\n val chars = readLine().toList\n val qlist = 0 +: ((chars zip chars.tail).map{case (a,b) => if (a==b) 1 else 0 }.foldLeft((Vector[Int](),0)){ case ((xs,sum),x) => (xs :+ (sum+x),sum+x)}._1);\n val q = readLine().toInt\n for(i <- 1 to q){\n val Array(a,b) = readLine.split(\" \").map(_.toInt)\n println(qlist(b-1)-qlist(a-1))\n }\n }\n }"}, {"source_code": "import java.util.Scanner\n\n\nobject Sum {\n class Sum{\n def max(a:Char,b:Char):Char=\n if (a1) left-1 else 0\n val r=in.nextInt()\n var ans = arr(r-1)-arr(l)\n println(ans)\n }\n \n }\n def main(args: Array[String]) {\n taskB\n }\n}"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val table = str.sliding(2).map(t => t.charAt(0) == t.charAt(1)).scanRight(0) {\n case(true, b) => b + 1\n case(acc, b) => b\n }.toArray\n val n = in.next().toInt\n println(Range(0, n).map{ _ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt - 1)\n table(a) - table(b)\n }.mkString(\"\\n\"))\n}"}, {"source_code": "object Sample extends App {\n val scnr = new java.util.Scanner(System.in)\n val s = scnr.nextLine().sliding(2).scanLeft(0) {\n case (acc, pair) => acc + (if (pair(0) == pair(1)) 1 else 0)\n }.toArray\n \n val m = scnr.nextInt()\n \n 1 to m foreach { _ =>\n val (l, r) = (scnr.nextInt(), scnr.nextInt())\n println(s(r - 1) - s(l - 1))\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P313B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val S = sc.nextLine.toArray\n val dp = Array.fill(S.length)(0)\n var pre = S(0)\n 1 until S.length foreach { i =>\n if (S(i) == pre) {\n dp(i) = dp(i - 1) + 1\n }\n else {\n pre = S(i)\n dp(i) = dp(i - 1)\n }\n }\n \n val N = sc.nextInt\n def solve(l: Int, r: Int): Int = {\n dp(r) - dp(l)\n }\n \n for (_ <- 0 until N) out.println(solve(sc.nextInt - 1, sc.nextInt - 1))\n\n out.close\n}\n"}, {"source_code": "\n/**\n * \n *\n * @author pvasilyev\n * @since 10 Apr 2016\n */\nobject Problem149 extends App {\n\n def solve(line: String): Array[Int] = {\n val intArray: Array[Int] = new Array[Int](line.length())\n intArray(0) = 0\n for (i <- 1 until line.length()) {\n if (line.charAt(i - 1) == line.charAt(i)) {\n intArray(i) = intArray(i - 1) + 1\n } else {\n intArray(i) = intArray(i - 1)\n }\n }\n intArray\n }\n\n val lines = scala.io.Source.stdin.getLines()\n val line = lines.next()\n val arr: Array[Int] = solve(line)\n val n = lines.next().toInt\n val builder: StringBuilder = StringBuilder.newBuilder\n for (i <- 0 until n) {\n val Array(p, q) = lines.next().split(\" \").map(_.toInt - 1)\n builder.append(arr(q) - arr(p)).append(\"\\n\")\n }\n print(builder.toString())\n // val in = scala.io.Source.stdin.getLines()\n // val str = in.next()\n // val table = str.sliding(2).map(t => t.charAt(0) == t.charAt(1)).scanRight(0) {\n // case (true, b) => b + 1\n // case (acc, b) => b\n // }.toArray\n // val n = in.next().toInt\n // println(Range(0, n).map { _ =>\n // val Array(a, b) = in.next().split(\" \").map(_.toInt - 1)\n // table(a) - table(b)\n // }.mkString(\"\\n\"))\n}\n"}, {"source_code": "\n/**\n * \n *\n * @author pvasilyev\n * @since 10 Apr 2016\n */\nobject Problem149 extends App {\n\n // def solve(line: String): Array[Int] = {\n // val intArray: Array[Int] = new Array[Int](line.length())\n // intArray(0) = 0\n // for (i <- 1 until line.length()) {\n // if (line.charAt(i - 1) == line.charAt(i)) {\n // intArray(i) = intArray(i - 1) + 1\n // } else {\n // intArray(i) = intArray(i - 1)\n // }\n // }\n // intArray\n // }\n //\n // val lines = scala.io.Source.stdin.getLines()\n // val line = lines.next()\n // val arr: Array[Int] = solve(line)\n // val n = lines.next().toInt\n // for (i <- 0 until n) {\n // val Array(p, q) = lines.next().split(\" \").map(_.toInt)\n // println(arr(q-1) - arr(p-1))\n // }\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val table = str.sliding(2).map(t => t.charAt(0) == t.charAt(1)).scanRight(0) {\n case (true, b) => b + 1\n case (acc, b) => b\n }.toArray\n val n = in.next().toInt\n println(Range(0, n).map { _ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt - 1)\n table(a) - table(b)\n }.mkString(\"\\n\"))\n}\n"}], "negative_code": [], "src_uid": "b30e09449309b999473e4be6643d68cd"} {"source_code": "//package codeforces.contests._1353\n\nobject BoardMoves {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val n = io.StdIn.readLong / 2\n\n println {\n (n * (n + 1) * (2 * n + 1) * 8) / 6\n }\n }\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject C {\n\n def solution(n: Int): Long = {\n val k: Long = (n - 1) / 2\n k * (k + 1) * (2 * k + 1) / 6 * 8\n }\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val n = readLine.toInt\n println(solution(n))\n }\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.math.max\nimport scala.math.min\nimport scala.reflect.ClassTag\nimport scala.collection.immutable._\n\n\nobject Main {\n\tdef main(args: Array[String]): Unit = {\n\t\ttry {\n\t\t\tval (in, out) =\n\t\t\t\tif (isOnlineJudge) {\n\t\t\t\t\t(\n\t\t\t\t\t\tnew FastScanner(new InputStreamReader(System.in)),\n\t\t\t\t\t\tnew PrintWriter(System.out)\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\t(\n\t\t\t\t\t\tnew FastScanner(new FileReader(new File(\"problem.in\"))),\n\t\t\t\t\t\tnew PrintWriter(new File(\"problem.out\"))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\tnew CF644(in, out).solve()\n\t\t\tout.flush()\n\t\t\tout.close()\n\t\t} catch {\n\t\t\tcase e: IOException => e.printStackTrace()\n\t\t}\n\t}\n \n\tprivate[this] val isOnlineJudge = true \n\tclass FastScanner(val streamReader: InputStreamReader) {\n\t\tprivate[this] val reader = new BufferedReader(streamReader, 32768)\n\t\tprivate[this] var tokenizer: StringTokenizer = _\n \n\t\t@inline private[this] final def next(): String = {\n\t\t\twhile (tokenizer == null || !tokenizer.hasMoreTokens)\n\t\t\t\ttokenizer = new StringTokenizer(reader.readLine)\n\t\t\ttokenizer.nextToken\n\t\t}\n \n\t\tdef nextInt(): Int = Integer.parseInt(next())\n \n\t\tdef nextLong(): Long = java.lang.Long.parseLong(next())\n \n\t\tdef nextChar(): Char = next().charAt(0)\n \n\t\tdef ni(): Int = nextInt()\n \n\t\tdef nl(): Long = nextLong()\n \n\t\tdef nc(): Char = nextChar()\n \n\t\tdef ns(): String = next()\n \n\t\tdef ns(n: Int): Array[Char] = ns().toCharArray\n \n\t\tdef na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n \n\t\tdef na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n\t\t\tval A1, A2 = Array.ofDim[Int](n)\n\t\t\tREP(n) { i =>\n\t\t\t\tA1(i) = ni() + offset\n\t\t\t\tA2(i) = ni() + offset\n\t\t\t}\n\t\t\t(A1, A2)\n\t\t}\n \n\t\tdef nm(n: Int, m: Int): Array[Array[Int]] = {\n\t\t\tval A = Array.ofDim[Int](n, m)\n\t\t\tREP(n) { i =>\n\t\t\t\tREP(m) { j =>\n\t\t\t\t\tA(i)(j) = ni()\n\t\t\t\t}\n\t\t\t}\n\t\t\tA\n\t\t}\n \n\t\tdef nal(n: Int): Array[Long] = map(n)(_ => nl())\n \n\t\tdef nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n\t}\n \n\tdef REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n\t\tvar i = offset\n\t\tval N = n + offset\n\t\twhile (i < N) {\n\t\t\tf(i);\n\t\t\ti += 1\n\t\t}\n\t}\n \n\tdef REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n\t\tvar i = n - 1 + offset\n\t\twhile (i >= offset) {\n\t\t\tf(i);\n\t\t\ti -= 1\n\t\t}\n\t}\n \n\tdef TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n\t\tREP(to - from + 1, from)(f)\n\t}\n \n\tdef map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n\t\tval res = Array.ofDim[A](n)\n\t\tREP(n)(i => res(i) = f(i + offset))\n\t\tres\n\t}\n \n\tdef sumL(as: Array[Int]): Long = {\n\t\tvar s = 0L\n\t\tREP(as.length)(i => s += as(i))\n\t\ts\n\t}\n \n\tdef cumSum(as: Array[Int]): Array[Long] = {\n\t\tval cum = Array.ofDim[Long](as.length + 1)\n\t\tREP(as.length) { i =>\n\t\t\tcum(i + 1) = cum(i) + as(i)\n\t\t}\n\t\tcum\n\t}\n}\n \nclass CF644 (fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n \n\timport Main._\n\timport fScanner._\n \n\t// def solve(): Unit = {\n\t// \tval T = ni()\n\t// \tfor(i <- 0 until T){\n\t// \tvar ans : Int = 1000\n\t// \t\tval n = ni()\n\t// \t\tvar list: List[Int] = List()\n\t// \t\tfor(j <- 0 until n){\n\t// \t\t\tval cu:Int = ni()\n\t// \t\t\tfor( x <- list)\n\t// \t\t\t\tans = ans.min( ( cu - x ).max(x - cu) )\n\t// \t\t\tlist = cu::\tlist\n\t// \t\t}\n\t// \t\tout.println(ans)\n\t// \t}\n\t// }\n\n\tdef solve(): Unit ={\t\n\t\tval T = ni()\n\t\tfor(i <- 0 until T){\n\t\t\tval n:Long = nl()\n\t\t\tval lm:Long = n-1\n\t\t\tvar ans:Long = (n/2)*(n)*(n)\n\t\t\tfor(j:Long <- 1.toLong until lm){\n\t\t\t\tif(j%2 == 1) ans = ans - (j*j)\n\n\t\t\t}\n\t\t\tprintln(ans)\n\t\t}\t\n\t}\n}\n"}, {"source_code": "object C extends App {\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n\n val ans = 1.to(n, 2).foldLeft(0L)((s, i) => s + i / 2L * (4L + 4L * (i - 2L)))\n\n println(ans)\n }\n}\n"}, {"source_code": "object ProblemC extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n\n val resultArr = new Array[BigInt](500000)\n resultArr(1) = 0\n for (i <- 3 until resultArr.length) {\n if (i % 2 == 1) {\n resultArr(i) = resultArr(i - 2) + (i * 2 + (i - 2) * 2).toLong * (i / 2)\n }\n }\n\n for (_ <- 1 to t) {\n println(resultArr(in.nextInt()))\n }\n\n}"}], "negative_code": [{"source_code": "object ProblemC extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n\n val resultArr = new Array[Long](500000)\n resultArr(1) = 0\n for (i <- 3 until resultArr.length) {\n if (i % 2 == 1) {\n resultArr(i) = resultArr(i - 2) + (i * 2 + (i - 2) * 2) * (i / 2)\n }\n }\n\n for (_ <- 1 to t) {\n println(resultArr(in.nextInt()))\n }\n\n}"}], "src_uid": "b4b69320c6040d2d264ac32e9ba5196f"} {"source_code": "object _1176C extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val seq = Seq(4, 8, 15, 16, 23, 42).zipWithIndex.toMap\n val nums = io.read[Seq[Int]].map(seq)\n\n val table = mutable.Map.empty[Int, Int].withDefaultValue(0)\n\n var ans = 0\n\n nums foreach {\n case 0 => table(0) += 1\n case n if table(n - 1) == 0 => ans += 1\n case n =>\n table(n - 1) -= 1\n table(n) += 1\n }\n\n ans += table.collect({ case (k, v) if k < 5 => v*(k+1) }).sum\n \n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object CF565C extends App {\n\n import scala.io.StdIn\n\n var map = Map(4 -> 0, 8 -> 1, 15 -> 2, 16 -> 3, 23 -> 4, 42 -> 5)\n\n val n = StdIn.readInt\n val as = StdIn.readLine.split(\" \").map(x => map.get(x.toInt).get)\n\n var array = Array.ofDim[Int](6)\n var array2 = Array.ofDim[Int](6)\n var drop = 0\n\n for (a <- as) {\n if (a == 0) {\n array(a) += 1\n array2(a) += 1\n } else {\n if (array(a - 1) > 0) {\n array(a - 1) -= 1\n array(a) += 1\n array2(a) += 1\n\n if (a == 5) {\n for (i <- 0 until 6) {\n array2(i) -= 1\n }\n array(5) -= 1\n }\n } else {\n drop += 1\n }\n }\n }\n\n drop += array2.sum\n\n println(drop)\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject Lost {\n\n val in = new java.util.Scanner(System.in)\n\n def nextInt = in.next().toInt\n\n def findCount(array: Array[Int]): Int = {\n var count = array.length\n\n if (array.isEmpty) return count\n val buff = new mutable.HashMap[Int, Int]().withDefaultValue(0)\n\n for (el <- array) {\n if (el == 4) {\n buff.update(8, buff(8) + 1)\n }\n else {\n if (buff.contains(el)) {\n val next = el match {\n case 8 => 15\n case 15 => 16\n case 16 => 23\n case 23 => 42\n case 42 => 1\n }\n if (buff(el) == 1) buff.remove(el)\n else buff.update(el, buff(el) - 1)\n buff.update(next, buff(next) + 1)\n if (el == 42) count -= 6\n }\n }\n }\n\n count\n }\n\n def main(args: Array[String]): Unit = {\n val size = in.nextLine\n val array = in.nextLine.split(\" \").map(_.toInt)\n println(findCount(array))\n }\n\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\nobject Lost {\n\n val in = new java.util.Scanner(System.in)\n\n def nextInt = in.next().toInt\n\n def findCount(array: Array[Int]): Int = {\n var count = array.length\n\n if (array.isEmpty) return count\n\n val buff = new mutable.HashMap[Int, Int]().withDefaultValue(0)\n for (el <- array) {\n if (el == 4) {\n buff.update(8, buff(8) + 1)\n }\n else {\n if (buff.contains(el)) {\n val next = el match {\n case 8 => 15\n case 15 => 16\n case 16 => 23\n case 23 => 42\n case 42 => 1\n }\n buff.update(el, buff(el) - 1)\n buff.update(next, buff(next) + 1)\n if (el == 42) count -= 6\n }\n }\n }\n\n count\n }\n\n def main(args: Array[String]): Unit = {\n val size = in.nextLine\n val array = in.nextLine.split(\" \").map(_.toInt)\n println(findCount(array))\n }\n\n}\n"}], "src_uid": "eb3155f0e6ba088308fa942f3572f582"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CE87A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CE87A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t= ni()\n REP(t) { _ =>\n val s = ns()\n val a = Array.fill[Int](3)(-1)\n var mn = Int.MaxValue\n REP(s.length) { i =>\n a(s.charAt(i) - '1') = i\n if(!a.contains(-1)){\n val y = a.max - a.min + 1\n if(y < mn) mn = y\n }\n }\n if(mn == Int.MaxValue){\n out.println(0)\n } else out.println(mn)\n }\n }\n}\n", "positive_code": [{"source_code": "object ProblemB extends App {\n\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n import scala.collection.mutable\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n for (_ <- 1 to t) {\n val s = in.nextToken()\n val count1 = new Array[Int](s.length + 1)\n val count2 = new Array[Int](s.length + 1)\n val count3 = new Array[Int](s.length + 1)\n var index = 0\n var result = Int.MaxValue\n\n for (i <- 1 to s.length) {\n if (i > 0) {\n count1(i) = count1(i - 1)\n count2(i) = count2(i - 1)\n count3(i) = count3(i - 1)\n }\n s(i - 1) match {\n case '1' =>\n count1(i) = count1(i) + 1\n case '2' =>\n count2(i) = count2(i) + 1\n case '3' =>\n count3(i) = count3(i) + 1\n }\n\n while (count1(i) - count1(index) > 0 && count2(i) - count2(index) > 0 && count3(i) - count3(index) > 0) {\n if (i - index < result) {\n result = i - index\n }\n index = index + 1\n }\n }\n\n if (result == Int.MaxValue) {\n result = 0\n }\n\n println(result)\n\n }\n\n\n\n}"}], "negative_code": [], "src_uid": "6cb06a02077750327602a1a7eeac770f"} {"source_code": "import java.util.StringTokenizer\n\nobject D extends App {\n val INF = 1000000000\n\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n def long() = st.nextToken().toLong\n\n read()\n val n = int()\n read()\n val a = Array.fill(n)(int())\n val b = readLine().toCharArray.map {\n case '0' => false\n case _ => true\n }\n\n var lmax = INF\n var lmin = -INF\n var rmax = INF\n var rmin = -INF\n\n for ((as, bs) <- a.sliding(5) zip b.sliding(5)) {\n bs match {\n case (Array(true, true, true, true, false)) =>\n rmax = Math.min(rmax, as.min - 1)\n// case (Array(true, true, true, true, true)) =>\n// rmin = as.min\n// case (Array(false, false, false, false, false)) =>\n// lmax = as.max\n case (Array(false, false, false, false, true)) =>\n lmin = Math.max(lmin, as.max + 1)\n case _ =>\n }\n }\n\n println(lmin + \" \" + rmax)\n\n}\n", "positive_code": [{"source_code": "object dAlenaHeater {\n\n import scala.io.StdIn.{readInt, readLine}\n def heater(arr: Array[Int], b: Array[Int]):(Int, Int) = {\n\n def change(four: List[Int], rest: List[Int], pat: List[Int], l: Int, r: Int):(Int, Int) =\n pat match {\n case 0 :: 1 :: _ if rest.isEmpty => ((l :: four).max, r)\n case 0 :: 1 :: _ => change(four.tail :+ rest.head, rest.tail, pat.tail, (l :: four).max, r)\n case 1 :: 0 :: _ if rest.isEmpty => (l, (r :: four).min)\n case 1 :: 0 :: _ => change(four.tail :+ rest.head, rest.tail, pat.tail, l, (r :: four).min)\n case _ if rest.isEmpty => (l, r)\n case Nil => (l, r)\n case _ => change(four.tail :+ rest.head, rest.tail, pat.tail, l, r)\n }\n\n val pair = change(arr.take(5).toList, arr.drop(5).toList, b.drop(3).toList, -1000000001, 1000000001 )\n (pair._1 + 1, pair._2 - 1)\n }\n\n def main(args: Array[String]):Unit = {\n val n = readInt()\n val arr: Array[Int] = readLine().split(\" \").map(_.toInt)\n val b = readLine().toCharArray.map(_.asDigit)\n val (l, r) = heater(arr, b)\n\n println(s\"$l $r\")\n }\n}\n"}], "negative_code": [{"source_code": "object dAlenaHeater {\n\n import scala.io.StdIn.{readInt, readLine}\n def heater(arr: Array[Int], b: Array[Int]):(Int, Int) = {\n\n def change(four: List[Int], rest: List[Int], pat: List[Int], l: Int, r: Int):(Int, Int) =\n pat match {\n case 0 :: 1 :: _ if rest.isEmpty => ((l :: four).max, r)\n case 0 :: 1 :: _ => change(four.tail :+ rest.head, rest.tail, pat.tail, (l :: four).max, r)\n case 1 :: 0 :: _ if rest.isEmpty => (l, (r :: four).min)\n case 1 :: 0 :: _ => change(four.tail :+ rest.head, rest.tail, pat.tail, l, (r :: four).min)\n case _ if rest.isEmpty => (l, r)\n case Nil => (l, r)\n case _ => change(four.tail :+ rest.head, rest.tail, pat.tail, l, r)\n }\n\n val pair = change(arr.take(5).toList, arr.drop(5).toList, b.drop(3).toList, Int.MinValue, Int.MaxValue )\n (pair._1 + 1, pair._2 - 1)\n }\n\n def main(args: Array[String]):Unit = {\n val n = readInt()\n val arr: Array[Int] = readLine().split(\" \").map(_.toInt)\n val b = readLine().toCharArray.map(_.toInt)\n val l, r = heater(arr, b)\n println(s\"$l $r\")\n }\n}"}, {"source_code": "object dAlenaHeater {\n\n import scala.io.StdIn.{readInt, readLine}\n def heater(arr: Array[Int], b: Array[Int]):(Int, Int) = {\n\n def change(four: List[Int], rest: List[Int], pat: List[Int], l: Int, r: Int):(Int, Int) =\n pat match {\n case 0 :: 1 :: _ if rest.isEmpty => ((l :: four).max, r)\n case 0 :: 1 :: _ => change(four.tail :+ rest.head, rest.tail, pat.tail, (l :: four).max, r)\n case 1 :: 0 :: _ if rest.isEmpty => (l, (r :: four).min)\n case 1 :: 0 :: _ => change(four.tail :+ rest.head, rest.tail, pat.tail, l, (r :: four).min)\n case _ if rest.isEmpty => (l, r)\n case Nil => (l, r)\n case _ => change(four.tail :+ rest.head, rest.tail, pat.tail, l, r)\n }\n\n val pair = change(arr.take(5).toList, arr.drop(5).toList, b.drop(3).toList, Int.MinValue, Int.MaxValue )\n (pair._1 + 1, pair._2 - 1)\n }\n\n def main(args: Array[String]):Unit = {\n val n = readInt()\n val arr: Array[Int] = readLine().split(\" \").map(_.toInt)\n val b = readLine().toCharArray.map(_.asDigit)\n val (l, r) = heater(arr, b)\n\n println(s\"$l $r\")\n }\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject D extends App {\n val INF = 1000000000\n\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n def long() = st.nextToken().toLong\n\n read()\n val n = int()\n read()\n val a = Array.fill(n)(int())\n val b = readLine().toCharArray.map {\n case '0' => false\n case _ => true\n }\n\n var lmax = INF\n var lmin = -INF\n var rmax = INF\n var rmin = -INF\n\n for ((as, bs) <- a.sliding(5) zip b.sliding(5)) {\n bs match {\n case (Array(true, true, true, true, false)) =>\n rmax = as.min - 1\n// case (Array(true, true, true, true, true)) =>\n// rmin = as.min\n// case (Array(false, false, false, false, false)) =>\n// lmax = as.max\n case (Array(false, false, false, false, true)) =>\n lmin = as.max + 1\n case _ =>\n }\n }\n\n println(lmin + \" \" + rmax)\n\n}\n"}], "src_uid": "3d8c881d96c998dce7059384cd882273"} {"source_code": "import scala.collection.mutable.ArrayBuffer\r\nimport scala.io.Source\r\n\r\nobject Main extends App {\r\n val input = Source.fromInputStream(System.in).getLines()\r\n val t = input.next().toInt\r\n val nList = new ArrayBuffer[Int]()\r\n for (i <- 0 until t) nList.append(input.next().toInt)\r\n\r\n val p2s = Range(1, 30).map(math.pow(2, _).toInt).toList\r\n def getMaxP2(n: Int) = {\r\n var list = p2s\r\n var res = list.head\r\n while (n >= list.head) {\r\n res = list.head\r\n list = list.tail\r\n }\r\n res\r\n }\r\n\r\n for (n <- nList) {\r\n if (n == 2) println(\"0 1\")\r\n else {\r\n val mp2 = getMaxP2(n - 1)\r\n println((Range(1, mp2) ++ (0 +: Range(mp2, n))).mkString(\" \"))\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(var a: Int, var b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return (a).compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mapp = mutable.Map[pair, Int]()\n\n val t = readInt()\n\n for (tt <- 1 to t) {\n val n = readInt()\n var p = 1\n while (p * 2 < n) {\n p *= 2\n }\n var k = 0\n while (p + k < n) {\n if (k % 2 != n % 2)\n writer.print((p + k)+ \" \" + k + \" \")\n else\n writer.print(k + \" \" + (p + k) + \" \")\n k += 1\n }\n while (k < p) {\n writer.print(k + \" \")\n k += 1\n }\n writer.println()\n\n def check(kk: Long, fi: Long): Boolean = {\n return false\n }\n def bs(st:Long, en:Long, fi:Long): Long = {\n if (en - st <= 1L) {\n if (check(st, fi))\n return st\n else\n return en\n }\n val mid = (st + en) / 2L\n if (check(mid, fi))\n return bs(st, mid, fi)\n else\n return bs(mid, en, fi)\n }\n }\n writer.flush()\n}"}, {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val pillarCount = readInt()\n val twoPowers = 0.to(30).map(i => Math.pow(2, i).toInt)\n val theMaxTwoPower = twoPowers.filter(_ <= pillarCount - 1).last\n val answer = (1.until(theMaxTwoPower).toList :+ 0) ++\n theMaxTwoPower.until(pillarCount).toList\n println(answer.mkString(\" \"))\n }\n\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}], "negative_code": [{"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val pillarCount = readInt()\n println(0.until(pillarCount).toList.mkString(\" \"))\n }\n\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val pillarCount = readInt()\n val numbers = 0.until(pillarCount).toList\n val answer = numbers.zip(numbers.reverse).flatMap {\n case (a, b) => List(b, a)\n }.take(numbers.length)\n println(answer.mkString(\" \"))\n }\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(var a: Int, var b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return (a).compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mapp = mutable.Map[pair, Int]()\n\n val t = readInt()\n\n for (tt <- 1 to t) {\n val n = readInt()\n var p = 1\n while (p * 2 < n) {\n p *= 2\n }\n var k = 0\n while (p + k < n) {\n if (k % 2 == 0)\n writer.print((p + k)+ \" \" + k + \" \")\n else\n writer.print(k + \" \" + (p + k) + \" \")\n k += 1\n }\n while (k < p) {\n writer.print(k + \" \")\n k += 1\n }\n writer.println()\n\n def check(kk: Long, fi: Long): Boolean = {\n return false\n }\n def bs(st:Long, en:Long, fi:Long): Long = {\n if (en - st <= 1L) {\n if (check(st, fi))\n return st\n else\n return en\n }\n val mid = (st + en) / 2L\n if (check(mid, fi))\n return bs(st, mid, fi)\n else\n return bs(mid, en, fi)\n }\n }\n writer.flush()\n}"}], "src_uid": "b6e758c75d0e3037a1500bbe652f6126"} {"source_code": "import scala.io.StdIn._\nimport scala.collection.mutable.HashSet\n\nobject Xor extends App {\n\n\tval n = readInt()\n\n\tval numbers = Array.tabulate[Int]( n + 1 )( x => x )\n\n\tval bit1Max = ~(~0 >>> 1)\t\t// value with leftmost bit set\n\tfor( i <- n to 1 by -1 if numbers( i ) == i ) {\n\t\t// find lower bound with most singnificant bit set\n\t\tvar bit1LB = bit1Max >>> 1\n\t\twhile( bit1LB > i )\n\t\t\tbit1LB >>>= 1\n\t\t// get 'mirror' value arounf lower bound\n\t\tval j = bit1LB - ( i - bit1LB + 1 )\n\t\t// set both mirrored values\n\t\tnumbers( i ) = j\n\t\tnumbers( j ) = i\n\t}\n\n\t// get the beauty value\n\tprintln( 1L * n * ( n + 1 ))\n\n\t//This was too brutal - and too slow\n/*\n\tval set = Array.fill[Boolean]( n + 1 )( false )\n\n\tvar mask = ~0 >>> 1\n\twhile( mask >> 1 > n )\n\t\tmask >>= 1\n\n\tfor( i <- n to 0 by -1 ) {\n\t\tval v = ~i & mask\n\t\tvar x = v\n\t\tvar j = 1\n\t\twhile( x > n || set( x )) {\n\t\t\tx = v ^ j\n\t\t\tj += 1\n\t\t}\n\t\tnumbers( i ) = x\n\t\tset( x ) = true\n\t}\n\tdef beauty( seq: Array[Int] ) = {\n\t\tseq.zipWithIndex.foldLeft( 0L )( (s,p) => s + (p._1 ^ p._2) )\n\t}\n\n\tprintln( beauty( numbers ))\n*/\n\t\n\tprintln( numbers.mkString( \" \" ))\n}", "positive_code": [{"source_code": "import io.Source\nimport java.io.PrintWriter\n\nobject CF288C {\n\n def solve(in: In, out: PrintWriter) {\n var n = in().toInt + 1\n val ans = Array.ofDim[Int](n)\n while (n > 1) {\n val m = 2 * Integer.highestOneBit(n - 1)\n out.flush()\n for (i <- m / 2 until n) {\n ans(i) = m - i - 1\n ans(m - i - 1) = i\n }\n n = m - n\n }\n var xor = 0L\n for (i <- 0 until ans.length) {\n xor += ans(i) ^ i\n }\n out.println(xor)\n out.println(ans.mkString(\" \"))\n }\n\n def main(args: Array[String]) {\n val in: In = new In(Source.fromInputStream(System.in))\n val out: PrintWriter = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() {\n while (iter.hasNext && delims.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next(): String = {\n skipDelims()\n while (iter.hasNext && delims.indexOf(iter.head) == -1) {\n sb.append(iter.next())\n }\n val ret = sb.toString()\n sb.clear()\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIterator = new TokenIterator(iter, \" \\r\\n\")\n\n val lineIterator = new TokenIterator(iter, \"\\r\\n\")\n\n def apply() = tokenIterator.next()\n\n def apply(n: Int) = tokenIterator.take(n)\n }\n}"}], "negative_code": [], "src_uid": "ab410ffc2bfe9360abf278328b9c3055"} {"source_code": "import java.io._\nimport collection.immutable._\nimport scala.collection.mutable.ArrayBuffer\n\nobject ProblemC {\n def main(args: Array[String]): Unit = processStdInOut()\n\n def processStdInOut(): Unit = {\n val src = io.Source.fromInputStream(System.in)\n try {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out));\n try {\n val lines = src.getLines()\n processLines(lines, bw)\n } finally {\n bw.flush()\n bw.close()\n }\n } finally {\n src.close();\n }\n }\n\n // Standard code above, custom code below\n\n case class Solution(bestMinBj: Int, minChangeCount: Int, newPlayList: Array[Int])\n\n def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {\n val params = lines.next().split(' ').map(_.toInt)\n val n = params(0)\n val m = params(1)\n val performers = lines.next().split(' ').map(_.toInt)\n val solution = solve(n, m, performers)\n bw.write(s\"${solution.bestMinBj} ${solution.minChangeCount}\")\n bw.newLine()\n bw.write(solution.newPlayList.mkString(\" \"))\n bw.newLine()\n }\n\n def solve(n: Int, m: Int, performers: Array[Int]): Solution = {\n val target = n / m // The maximum value for the minimum number of performances by a preferred band\n\n // The queues store the zero-based indexes of performances which can be replaced without decreasing the target:\n var queueA = ArrayBuffer[Int]() // Indexes for non-preferred bands\n val queueB = ArrayBuffer[Int]() // Indexes for preferred bands that have exceeded the target\n\n // Count performances by preferred bands:\n val bandCounts = Array.ofDim[Int](m)\n for (i <- 1 to n) {\n val j = performers(i - 1)\n if (j > m) {\n queueA += (i - 1)\n } else {\n val newBandCount = bandCounts(j - 1) + 1\n bandCounts(j - 1) = newBandCount\n if (newBandCount > target) {\n queueB += (i - 1)\n }\n }\n }\n\n val deltas = bandCounts.map(bc => if (bc >= target) 0 else target - bc)\n val minChangeCount = deltas.sum\n val replacementValues = deltas.zipWithIndex.flatMap {\n deltaAndIndex => IndexedSeq.fill(deltaAndIndex._1)(deltaAndIndex._2 + 1)\n }\n\n queueA ++= queueB // Merge the queues, but replace non-preferred bands first\n val replacements = queueA.take(minChangeCount).zip(replacementValues)\n replacements.foreach{ indexAndValue:(Int, Int) => performers(indexAndValue._1) = indexAndValue._2 }\n\n Solution(target, minChangeCount, performers)\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val as = readInts(n)\n var counts = mutable.Map.empty[Int, Int].withDefaultValue(0) ++ as.groupBy(identity).map { case (key, value) => (key, value.length) }\n val sorted = (1 to m).sortBy(counts).reverse\n val max = n / m\n val needs = (sorted.take(n % m).map(a => (a, max + 1)) ++ sorted.drop(n % m).map(a => (a, max))).toMap.withDefaultValue(0)\n\n var changes = 0\n for (i <- 0 until n) {\n val a = as(i)\n if (counts(a) > needs(a)) {\n (1 to m).find(a => counts(a) < max) match {\n case Some(a2) =>\n as(i) = a2\n counts(a) = counts(a) - 1\n counts(a2) = counts(a2) + 1\n changes += 1\n case _ =>\n }\n }\n }\n\n println(s\"$max $changes\")\n println(as.mkString(\" \"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val line = in.next().split(' ').map(_.toInt)\n var shouldBeAtLeast = line.length / m\n var map = line.filter(_ <= m).groupBy(i => i).map(i => i._1 -> i._2.length)\n var less = map.filter(_._2 < shouldBeAtLeast).keySet ++ (1 to m).filter(i => !map.contains(i)).toSet\n var more = map.filter(_._2 > shouldBeAtLeast).keySet\n val ans = line.map{i =>\n if (less.isEmpty || less.contains(i) || map.getOrElse(i, 0) == shouldBeAtLeast)\n i\n else {\n val ch = less.head\n map += ch -> (map.getOrElse(ch, 0) + 1)\n\n if (map(ch) >= shouldBeAtLeast)\n less -= ch\n if (more.contains(i)) {\n map += i -> (map.getOrElse(i, 0) - 1)\n if (map(i) <= shouldBeAtLeast)\n more -= ch\n }\n ch\n }}\n println(s\"${shouldBeAtLeast} ${ans.zip(line).count(i => i._1 != i._2)}\")\n println(ans.toList.mkString(\" \"))\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val as = readInts(n)\n var counts = mutable.Map.empty[Int, Int].withDefaultValue(0) ++ as.groupBy(identity).map { case (key, value) => (key, value.length) }\n val sorted = (1 to m).sortBy(counts).reverse\n val max = n / m\n val needs = (sorted.take(n % m).map(a => (a, max + 1)) ++ sorted.drop(n % m).map(a => (a, max))).toMap.withDefaultValue(0)\n\n var changes = 0\n for (i <- 0 until n) {\n val a = as(i)\n if (counts(a) > needs(a)) {\n val a2 = (1 to m).find(a => counts(a) < needs(a)).get\n as(i) = a2\n counts(a) = counts(a) - 1\n counts(a2) = counts(a2) + 1\n changes += 1\n }\n }\n\n println(s\"$max $changes\")\n println(as.mkString(\" \"))\n}\n"}], "src_uid": "0d89602f5ed765adf6807f86df1205bd"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn.readLine\n \n val T: Int = readLine.toInt\n for(t <- 0 until T) {\n val N: Int = readLine.toInt\n val v: Array[Int] = readLine.split(\" \").map(_.toInt)\n var ans = -1;\n for(i <- 0 until (N-1) if (ans == -1))\n if(math.abs(v(i) - v(i + 1)) > 1)\n ans = i;\n if(ans == -1) println(\"NO\")\n else {\n println(\"YES\")\n println(s\"${ans+1} ${ans+2}\")\n }\n }\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn.readLine\n\n val T: Int = readLine.toInt\n for(t <- 0 until T) {\n val N: Int = readLine.toInt\n val v: Array[Int] = readLine.split(\" \").map(_.toInt)\n var ans = -1;\n for(i <- 0 until (N-1) if (ans == -1))\n if(math.abs(v(i) - v(i + 1)) > 1)\n ans = i;\n if(ans == -1) println(\"NO\")\n else {\n println(\"YES\")\n println(s\"${ans+1} ${ans+2}\")\n }\n }\n }\n}"}, {"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n\n var i = 1\n var ok = false\n while (i < n) {\n if (Math.abs(as(i) - as(i - 1)) >= 2) {\n out.println(\"YES\")\n out.println(s\"$i ${i + 1}\")\n i = n\n ok = true\n }\n i += 1\n }\n if (!ok) out.println(\"NO\")\n }\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn.readLine\n\n val T: Int = readLine.toInt\n for(t <- 0 until T) {\n val N: Int = readLine.toInt\n val v: Array[Int] = readLine.split(\" \").map(_.toInt)\n var ans = -1;\n for(i <- 0 until (N-1) if (ans == -1))\n if(math.abs(v(i) - v(i + 1)) > 1)\n ans = i;\n if(ans == -1) println(\"NO\")\n else {\n println(\"YES\")\n println(s\"$ans ${ans+1}\")\n }\n }\n }\n}"}], "src_uid": "fa16d33fb9447eea06fcded0026c6e31"} {"source_code": "object Main extends App {\n\n def checkPoint(acc: Map[(Int, Int), Int], a: Int, b: Int): Boolean = {\n 4 == acc.getOrElse((a,b), 0) + acc.getOrElse((a+1,b), 0) + acc.getOrElse((a,b+1), 0) + acc.getOrElse((a+1,b+1), 0)\n }\n\n def check(acc: Map[(Int, Int), Int], a: Int, b: Int): Boolean = {\n checkPoint(acc, a-1, b-1) || checkPoint(acc, a-1, b) || checkPoint(acc, a, b-1) || checkPoint(acc, a, b)\n }\n\n val Array(n, m, k) = readLine.split(\" \").map(_.toInt)\n (1 to k).foldLeft(Map[(Int, Int), Int]())({\n case (acc, index) =>\n val Array(a, b) = readLine.split(\" \").map(_.toInt)\n val updateMap = acc + ((a,b) -> 1)\n if(check(updateMap, a, b)) {\n println(index)\n System.exit(0)\n updateMap\n } else {\n updateMap\n }\n })\n\n println(\"0\")\n}", "positive_code": [{"source_code": "/**\n * Created by helfper on 27/01/2015.\n */\nobject PashaAndPixels {\n def main(args: Array[String]) {\n val Array(n, m, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n val field = Array.fill(n, m)(false)\n\n println(solve(field, k))\n }\n\n def solve(field: Array[Array[Boolean]], k: Int): Int = {\n def iterate(m: Int): Int = {\n val Array(i, j) = io.StdIn.readLine.split(\" \").map(_.toInt)\n field(i-1)(j-1) = true\n val lose = 0.to(1).exists(di =>\n 0.to(1).exists(dj =>\n check(field, i-di, j-dj)\n )\n )\n if (lose) m\n else if (m >= k) 0\n else iterate(m+1)\n }\n\n iterate(1)\n }\n\n def check(field: Array[Array[Boolean]], i: Int, j: Int): Boolean =\n 0 <= i-1 && i < field.length && 0 <= j-1 && j < field(i).length &&\n field(i-1)(j-1) && field(i)(j-1) && field(i-1)(j) && field(i)(j)\n}\n"}, {"source_code": "import java.util.Scanner;\nimport scala.util.control.Breaks._\n\nobject C508A {\n\n def main(args: Array[String]) {\n\n val in = new Scanner(System.in);\n val out = System.out;\n\n val n = in.nextInt()\n val m = in.nextInt()\n val k = in.nextInt()\n\n val matrix = Array.ofDim[Int](n + 5, m + 5)\n\n var x, y = 0\n var ans = 0\n\n breakable {\n for (i <- 0 until k) {\n x = in.nextInt()\n y = in.nextInt()\n matrix(x)(y) = 1\n if (\n (matrix(x - 1)(y - 1) == 1 && matrix(x)(y - 1) == 1 && matrix(x - 1)(y) == 1)\n || (matrix(x + 1)(y - 1) == 1 && matrix(x)(y - 1) == 1 && matrix(x + 1)(y) == 1)\n || (matrix(x + 1)(y + 1) == 1 && matrix(x)(y + 1) == 1 && matrix(x + 1)(y) == 1)\n || (matrix(x - 1)(y + 1) == 1 && matrix(x - 1)(y) == 1 && matrix(x)(y + 1) == 1)\n ) {\n ans = i + 1\n break\n }\n }\n }\n\n out.println(ans)\n\n }\n\n\n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m, k) = in.next().split(\" \").map(_.toInt)\n var field = Array.ofDim[Boolean](n, m)\n val res = Range(1, k + 1).find{ _ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt - 1)\n field(a)(b) = true\n (a > 0 && b > 0 && field(a - 1)(b - 1) &&\n field(a - 1)(b) && field(a)(b - 1)) ||\n (a < (n - 1) && b > 0 && field(a + 1)(b - 1) &&\n field(a + 1)(b) && field(a)(b - 1)) ||\n (a > 0 && b < (m - 1) && field(a - 1)(b + 1) &&\n field(a - 1)(b) && field(a)(b + 1)) ||\n (a < (n - 1) && b < (m - 1) && field(a + 1)(b + 1) &&\n field(a + 1)(b) && field(a)(b + 1))\n }\n println(res.getOrElse(0))\n\n}"}, {"source_code": "object A508 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m, k) = readInts(3)\n val in = Array.fill(n)(Array.fill(m)(false))\n var break = false\n for(test <- 1 to k if !break) {\n val Array(i, j) = readInts(2).map(_-1)\n in(i)(j) = true\n val rightUpper = i-1>=0 && j-1>=0 && in(i-1)(j-1) && in(i-1)(j) && in(i)(j-1)\n val leftUpper = i-1>=0 && j+1=0 && in(i+1)(j-1) && in(i+1)(j) && in(i)(j-1)\n val leftLower = i+1= 0 && x < n && y >= 0 && y < m && occupation(x)(y)) {\n return true\n }\n false\n }\n\n def checkOccupation(n: Int, m: Int, x: Int, y: Int, occupation: Array[Array[Boolean]]): Boolean = {\n if (checkPosition(n, m, x+1, y, occupation)\n && checkPosition(n, m, x+1, y+1, occupation)\n && checkPosition(n, m, x, y+1, occupation) ) {\n return true\n } else if (checkPosition(n, m, x+1, y, occupation)\n && checkPosition(n, m, x+1, y-1, occupation)\n && checkPosition(n, m, x, y-1, occupation)) {\n return true\n } else if (checkPosition(n, m, x-1, y, occupation)\n && checkPosition(n, m, x-1, y+1, occupation)\n && checkPosition(n, m, x, y+1, occupation)) {\n return true\n } else if (checkPosition(n, m, x-1, y, occupation)\n && checkPosition(n, m, x-1, y-1, occupation)\n && checkPosition(n, m, x, y-1, occupation)) {\n return true\n }\n false\n }\n\n def solve() = {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val Array(n, m, k): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n\n val occupation = Array.ofDim[Boolean](n, m)\n var found = false\n var step = 0\n for (i <- 0 until k) {\n val Array(x, y) = reader.readLine().split(\" \").map(_.toInt)\n occupation(x-1)(y-1) = true\n if (!found && checkOccupation(n, m, x-1, y-1, occupation)) {\n found = true\n step = i + 1\n }\n }\n println(step)\n }\n\n solve()\n\n class Point(val x: Int, val y: Int) { }\n\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util._\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val k = nextInt\n val arr = new Array[Array[Boolean]](n + 2)\n for (i <- 0 until n + 2) {\n arr(i) = new Array[Boolean](m + 2)\n }\n var ans = -1\n for (l <- 0 until k) {\n val x = nextInt\n val y = nextInt\n arr(x)(y) = true\n if(\n (ans == -1 && arr(x + 1)(y) && arr(x)(y + 1) && arr(x + 1)(y + 1)) ||\n (ans == -1 && arr(x - 1)(y) && arr(x)(y - 1) && arr(x - 1)(y - 1)) ||\n (ans == -1 && arr(x - 1)(y) && arr(x)(y + 1) && arr(x - 1)(y + 1)) ||\n (ans == -1 && arr(x + 1)(y) && arr(x)(y - 1) && arr(x + 1)(y - 1)))\n {\n ans = l\n }\n\n }\n\n if (ans == -1) {\n out.println(0)\n } else {\n out.println(ans + 1)\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util._\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val k = nextInt\n val arr = new Array[Array[Boolean]](n + 2)\n for (i <- 0 until n + 2) {\n arr(i) = new Array[Boolean](m + 2)\n }\n var ans = -1\n for (l <- 0 until k) {\n val x = nextInt\n val y = nextInt\n arr(x)(y) = true\n if (ans == -1 && arr(x)(y) && arr(x + 1)(y) && arr(x)(y + 1) && arr(x + 1)(y + 1)) {\n ans = l\n }\n\n }\n\n if (ans == -1) {\n out.println(0)\n } else {\n out.println(ans + 1)\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "src_uid": "0dc5469831c1d5d34aa3b7b172e3237b"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val ans = Array.ofDim[Int](N, N)\n REP(N / 4) { r =>\n REP(N / 4) { c =>\n REP(4) { i =>\n REP(4) { j =>\n ans(r * 4 + i)(c * 4 + j) = r * N * 4 + c * 16 + i * 4 + j\n }\n }\n }\n }\n\n debugDim(ans)\n\n REP(N) { i =>\n out.println(ans(i).mkString(\" \"))\n }\n\n DEBUG {\n val row = map(N)(i => ans(i).reduce(_^_))\n val col = Array.ofDim[Int](N)\n REP(N * N) { i =>\n col(i%N) ^= ans(i/N)(i%N)\n }\n debug(row)\n debug(col)\n }\n }\n}", "positive_code": [{"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val as = Array.ofDim[Int](n, n)\n\n var a = 0\n var r0 = 0\n while (r0 < n) {\n var c0 = 0\n while (c0 < n) {\n var r = 0\n while (r < 4) {\n var c = 0\n while (c < 4) {\n as(r0 + r)(c0 + c) = a\n a += 1\n c += 1\n }\n r += 1\n }\n c0 += 4\n }\n r0 += 4\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n as.foreach(a => println(a.mkString(\" \")))\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "38ee7fc4cd2d019aa9e5b33d8bea4a2f"} {"source_code": "import scala.io.StdIn._\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n val t = readInt()\r\n for(i <- 0 until t) {\r\n val n = readInt()\r\n val sticks: Array[Int] = readLine.split(\" \").map(_.toInt)\r\n val sortedSticks = sticks.sorted\r\n var ans: Long = 1e9.toLong\r\n for(j <- 2 until n) {\r\n val a = sortedSticks(j) - sortedSticks(j-1) + sortedSticks(j) - sortedSticks(j-2)\r\n val b = sortedSticks(j) - sortedSticks(j-2) + sortedSticks(j-1) -sortedSticks(j-2)\r\n val c = sortedSticks(j) - sortedSticks(j-1) + sortedSticks(j-1) -sortedSticks(j-2)\r\n ans = List(ans,a,b,c).min\r\n }\r\n\r\n println(ans)\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.io.StdIn\r\n\r\n/**\r\n * @author zhuxi\r\n * @since 2022/9/28 10:08\r\n * @note\r\n * 1734A. Select Three Sticks | 难度:800\r\n */\r\nobject Solution1734A {\r\n def main(args: Array[String]): Unit = {\r\n val t = StdIn.readInt()\r\n for (_ <- 0 until t) {\r\n val _ = StdIn.readInt()\r\n val arr = StdIn.readLine().split(\" \").map(_.toInt).sorted\r\n var minimum = Int.MaxValue\r\n for (j <- 0 until arr.length - 2) {\r\n minimum = minimum min (arr(j + 2) + arr(j + 1) - 2 * arr(j)) min\r\n (arr(j + 2) * 2 - arr(j + 1) - arr(j)) min (arr(j + 2) - arr(j))\r\n }\r\n println(minimum)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.io.StdIn._\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n val t = readInt()\r\n for(i <- 0 until t) {\r\n val n = readInt()\r\n val sticks: Array[Int] = readLine.split(\" \").map(_.toInt)\r\n val sortedSticks = sticks.sorted\r\n var ans: Long = 1e9.toLong\r\n for(j <- 2 until n) {\r\n val c = sortedSticks(j) - sortedSticks(j-1) + sortedSticks(j-1) -sortedSticks(j-2)\r\n ans = Math.min(ans,c)\r\n }\r\n\r\n println(ans)\r\n }\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\r\n\r\n/**\r\n * @author zhuxi\r\n * @since 2022/9/28 10:08\r\n * @note\r\n * 1734A. Select Three Sticks | 难度:800\r\n */\r\nobject Solution1734A {\r\n def main(args: Array[String]): Unit = {\r\n val t = StdIn.readInt()\r\n for (i <- 0 until t) {\r\n val n = StdIn.readInt()\r\n val arr = StdIn.readLine().split(\" \").map(_.toInt).sorted\r\n var min = Int.MaxValue\r\n for (j <- 0 until arr.length - 2) {\r\n min = min min (arr(j+2) + arr(j+1) - 2 * arr(j))\r\n }\r\n println(min)\r\n }\r\n }\r\n}"}], "src_uid": "53ff11122a277d1eb29fe2034017fd75"} {"source_code": "import scala.annotation.tailrec\nimport scala.collection.breakOut\n\n\n\n\n\n\n\n\n// -----------------------------------------------------------------------------\n// -----------------------------------------------------------------------------\nobject Main {\n // Document: http://www.scala-lang.org/api/current/#package\n // -----------------------------------------------------------------------------\n class Shelf(val books: Vector[Boolean],val inverted: Boolean, val count: Int) {\n def invert() : Shelf = new Shelf(books, !inverted, books.size - count)\n def place(j: Int) : Shelf = {\n val p = if(!inverted) true else false\n val i = if(books(j) != p) 1 else 0\n new Shelf(books.updated(j, p), inverted, count + i)\n }\n def remove(j: Int) : Shelf = {\n val p = if(!inverted) false else true\n val i = if(books(j) != p) -1 else 0\n new Shelf(books.updated(j, p), inverted, count + i)\n }\n }\n\n class BookCase(val shelves: Vector[Shelf], val count: Int) {\n def place(i: Int, j: Int) : BookCase = {\n val oldone = shelves(i)\n val newone = oldone.place(j)\n new BookCase(shelves.updated(i, newone), count - oldone.count + newone.count)\n }\n def remove(i: Int, j: Int) : BookCase = {\n val oldone = shelves(i)\n val newone = oldone.remove(j)\n new BookCase(shelves.updated(i, newone), count - oldone.count + newone.count)\n }\n def invert(i: Int) : BookCase = {\n val oldone = shelves(i)\n val newone = oldone.invert\n new BookCase(shelves.updated(i, newone), count - oldone.count + newone.count)\n }\n }\n\n class Solver(val stdio: MyConsole){\n import stdio._ // shadow Console.~\n def main() : Unit = {\n val n, m, q = nextInt()\n val logs : Array[BookCase] = Array.fill(q+1)(null)\n logs(0) = new BookCase(Vector.fill(n)(new Shelf(Vector.fill(m)(false), false, 0)), 0)\n for(qu <- 1 to q) {\n val t = nextInt()\n t match {\n case 1 => { // place\n val i, j = nextInt()-1\n logs(qu) = logs(qu-1).place(i, j)\n }\n case 2 => { // remove\n val i, j = nextInt()-1\n logs(qu) = logs(qu-1).remove(i, j)\n }\n case 3 => { // invert\n val i = nextInt()-1\n logs(qu) = logs(qu-1).invert(i)\n }\n case 4 => { // return\n val k = nextInt()\n logs(qu) = logs(k)\n }\n case _ => {\n }\n }\n println(logs(qu).count)\n }\n }\n }\n\n\n\n def main(args: Array[String]) : Unit = {\n val console = new MyConsole(Console.in, Console.out, Console.err)\n val solver = new Solver(console)\n solver.main()\n console.flush()\n }\n import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}\n class MyConsole(val in: BufferedReader, val _out: PrintStream,\n val err: PrintStream) {\n // PrintWriter do not flush automatically\n val out = new PrintWriter(_out,false)\n // If argument is null, there are ambiguous which function will be called\n def print(obj: Any) = out.print(if(obj == null) \"null\" else obj.toString)\n def println() = out.println()\n def println(obj: Any) = out.println(obj)\n def printf(text: String, args: Any*) = out.printf(text.format(args : _*))\n // NOTE: YOU MUST FLUSH BEFORE END OF MAIN\n def flush() = out.flush()\n def debugln(obj: Any) = err.println(\"\\u001b[36m\" + obj + \"\\u001b[0m\")\n\n def readIntVector() : Vector[Int] = parseLineToVector(() => nextInt)\n def readLongVector() : Vector[Long] = parseLineToVector(() => nextLong)\n def readStringVector() : Vector[String] = parseLineToVector(() => nextString)\n def nextInt() : Int = nextLong().toInt\n def nextBigInt() : BigInt = BigInt(nextString())\n def nextBigDecimal( ) : BigDecimal = BigDecimal(nextString())\n def nextDouble() : Double = nextString().toDouble\n def nextLong() : Long = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading long failed\")\n val sgn = if(peek == '-') -1l else 1\n if(sgn == -1l) ignore(read())\n if(peek < '0' || '9' < peek)\n throw new NumberFormatException(s\"readLong found only '-' or no number\")\n @tailrec\n def readLong(next: Int, cur: Long) : Long =\n if('0' <= next && next <= '9'){\n ignore(read()) // is equal to next\n readLong(peek, cur*10 + next-'0')\n }\n else if(isEnd(next) || isSpaceOrControl(next))\n sgn*cur\n else\n throw new NumberFormatException(s\"readLong found strange byte $next\")\n val res = readLong(peek,0)\n skipTrailingSpaces()\n res\n }\n def nextString() : String = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading String failed\")\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isSpaceOrControl(next)){\n builder.toString\n }else{\n builder.append(read().toChar) // here we skip.\n appendCode(peek)\n }\n }\n val res = appendCode(peek)\n skipTrailingSpaces()\n res\n }\n // TODO: refactoring to marge nextString\n def readLine() : String = {\n if(isEnd(peek))\n throw new NoSuchElementException(\"Reading Line failed\")\n skipNewline()\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isNewLine(next)){\n builder.toString\n }else{\n builder.append(next.toChar)\n appendCode(read())\n }\n }\n appendCode(read())\n }\n // helpers\n private def ignore[T](x: => T) : Unit = { x; () }\n private[this] var peeked: Option[Int] = None\n private[this] var is_first = true\n protected def read() = {\n val res = peeked match {\n case None => in.read()\n case Some(a) => { peeked = None; a }\n }\n is_first = false\n res\n }\n private def peek() =\n peeked match {\n case None => {\n val res = in.read()\n peeked = Some(res)\n res\n }\n case Some(a) => a\n }\n private def isEnd(c: Int) = c == -1\n private def isCR(c: Int) = c == 13\n private def isLF(c: Int) = c == 10\n private def isNewLine(c: Int) = isLF(c) || isCR(c)\n private def isThereReadable() = !isEnd(peek)\n private def isSpaceOrControl(c: Int) = (0 <= c && c <= 32) || c == 127\n @tailrec\n final private def goNextNotSpaceNorControl() : Unit =\n if(isSpaceOrControl(peek)){\n ignore(read())\n goNextNotSpaceNorControl()\n }\n final private def skipTrailingSpaces() : Unit = {\n @tailrec\n def skipTrailingSpacesAux() : Unit = {\n if(!isNewLine(peek) && isSpaceOrControl(peek)){\n ignore(read())\n skipTrailingSpacesAux()\n }\n }\n skipTrailingSpacesAux()\n }\n final private def skipNewline() : Unit =\n if(!is_first){\n if(isCR(peek))\n ignore(read())\n if(isLF(peek))\n ignore(read())\n }\n private def goNextValuable() : Boolean = {\n goNextNotSpaceNorControl()\n isThereReadable()\n }\n\n private def parseLineToVector[X](parser: () => X) : Vector[X] = {\n import scala.collection.immutable.VectorBuilder\n val vb = new VectorBuilder[X]()\n skipNewline()\n @tailrec\n def parseLineToVectorAux() : Vector[X] =\n if(isNewLine(peek) || isEnd(peek)) {\n vb.result\n }else{\n vb += parser()\n parseLineToVectorAux()\n }\n parseLineToVectorAux()\n }\n }\n\n}\n", "positive_code": [{"source_code": "object Solution {\n\n case class State(flip: Vector[Boolean], shelves: Vector[Vector[Boolean]], cnt: Vector[Int], total: Int) {\n def existBook(i: Int, j: Int): Boolean = flip.apply(i) ^ shelves(i)(j)\n def place(i: Int, j: Int): State = {\n if (existBook(i, j)) this\n else\n State(flip, shelves.updated(i, shelves(i).updated(j, !flip(i))), cnt.updated(i, cnt(i) + 1), total + 1)\n }\n def remove(i: Int, j: Int): State = {\n if (!existBook(i, j)) this\n else\n State(flip, shelves.updated(i, shelves(i).updated(j, flip(i))), cnt.updated(i, cnt(i) - 1), total - 1)\n }\n def turn(i: Int): State =\n State(flip.updated(i, !flip(i)), shelves, cnt.updated(i, shelves(0).size - cnt(i)), total - 2*cnt(i) + shelves(0).size)\n }\n\n def main(args: Array[String]): Unit = {\n val tokens = scala.io.Source.stdin.getLines\n .flatMap(_ split ' ' filter (_.nonEmpty))\n\n def nextInt() = tokens.next().toInt\n\n val N, M, Q = nextInt()\n val states = Array.ofDim[State](Q + 1)\n states(0) = State(Vector.fill(N)(false), Vector.fill(N)(Vector.fill(M)(false)), Vector.fill(N)(0), 0)\n\n for (i <- 1 to Q) {\n states(i) = nextInt() match {\n case 1 => val s, p = nextInt() - 1; states(i - 1).place(s, p)\n case 2 => val s, p = nextInt() - 1; states(i - 1).remove(s, p)\n case 3 => states(i - 1).turn(nextInt() - 1)\n case 4 => states(nextInt())\n }\n println(states(i).total)\n }\n }\n}"}, {"source_code": "//package merofeev.contests.codeforces.rnd368\n\nimport java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\n\n/**\n * @author erofeev \n * @since 03.09.16\n */\n//noinspection ReferenceMustBePrefixed\nobject DGraphPersistence {\n\n val MAX_COMMANDS = 100010\n\n val cCodes = new Array[Int](MAX_COMMANDS)\n //0 if it was step\n val cRows = new Array[Int](MAX_COMMANDS)\n //0 if not upplicable\n val cPositions = new Array[Int](MAX_COMMANDS)\n var rowSize = 0\n\n val book = Array.ofDim[Boolean](1000, 1000)\n val rowSums = new Array[Int](1000)\n val isRowFlipped = new Array[Boolean](1000)\n var currAnsw = 0\n val commandsTree = new Array[ArrayBuffer[Int]](MAX_COMMANDS)\n val answers = new Array[Int](MAX_COMMANDS)\n\n\n def solve(parentCmmand: Int): Unit = {\n answers(parentCmmand) = currAnsw\n for (command <- commandsTree(parentCmmand)) {\n val code: Int = cCodes(command)\n var updates = false\n val row: Int = cRows(command)\n for (rollback <- 0 to 1) {\n if (code == 3) {\n currAnsw -= rowSums(row) // rm current value\n isRowFlipped(row) = !isRowFlipped(row)\n rowSums(row) = rowSize - rowSums(row) // compute new val\n currAnsw += rowSums(row) //up new value\n } else if (code != 4) {\n val pos = cPositions(command)\n val isSet = book(row)(pos) ^ isRowFlipped(row)\n val upVal = if (code == 1) 1 else -1\n if (rollback == 0) {\n updates = isSet ^ code == 1\n if (updates) {\n book(row)(pos) = !book(row)(pos)\n rowSums(row) += upVal\n currAnsw += upVal\n }\n } else if (rollback == 1 && updates) {\n book(row)(pos) = !book(row)(pos)\n rowSums(row) -= upVal\n currAnsw -= upVal\n }\n }\n if (rollback == 0) {\n solve(command)\n }\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n\n\n\n\n val in = new Scanner(System.in)\n val rows = in.nextInt()\n this.rowSize = in.nextInt()\n val ops = in.nextInt()\n for (i <- 0 to ops) {\n commandsTree(i) = new ArrayBuffer()\n }\n\n //save every shelf as a bitset object (30b), 30b * 10000 = 3mb??\n //save every bookcase as a list of shelfs (100 * 8 + 20 = 850) * 100000 = 85mb\n var pos = 1\n while (in.hasNextInt) {\n cCodes(pos) = in.nextInt()\n cRows(pos) = in.nextInt() //step in case of 4 coe\n if (cCodes(pos) == 4) {\n commandsTree(cRows(pos)) += pos\n } else {\n cRows(pos) -= 1 //alignment\n commandsTree(pos - 1) += pos //children of previous\n }\n if (cCodes(pos) == 1 || cCodes(pos) == 2) {\n cPositions(pos) = in.nextInt() - 1 //alignment\n }\n pos += 1\n }\n solve(0)\n for (comm <- 1 to ops) {\n println(answers(comm))\n }\n }\n\n}\n"}, {"source_code": "object Solution {\n\ncase class State(flip: Vector[Boolean], shelves: Vector[Vector[Boolean]], cnt: Vector[Int], total: Int) {\n def existBook(i: Int, j: Int): Boolean = flip.apply(i) ^ shelves(i)(j)\n def place(i: Int, j: Int): State = {\n if (existBook(i, j)) this\n else\n State(flip, shelves.updated(i, shelves(i).updated(j, !flip.apply(i))), cnt.updated(i, cnt(i) + 1), total + 1)\n }\n def remove(i: Int, j: Int): State = {\n if (!existBook(i, j)) this\n else\n State(flip, shelves.updated(i, shelves(i).updated(j, flip.apply(i))), cnt.updated(i, cnt(i) - 1), total - 1)\n }\n def flip(i: Int): State =\n State(flip.updated(i, !flip.apply(i)), shelves, cnt.updated(i, shelves(0).size - cnt(i)), total - cnt(i) + shelves(0).size - cnt(i))\n}\n\n def main(args: Array[String]): Unit = {\n val br = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n var st: java.util.StringTokenizer = null\n val writer = new java.io.PrintWriter(System.out)\n\n def nextInt(): Int = {\n while (st == null || !st.hasMoreElements())\n st = new java.util.StringTokenizer(br.readLine())\n return st.nextToken().toInt\n }\n\n val N, M, Q = nextInt()\n val states = Array.ofDim[State](Q + 1)\n states(0) = State(\n Vector.fill(N)(false),\n Vector.fill(N)(Vector.fill(M)(false)),\n Vector.fill(N)(0),\n 0\n )\n\n for (i <- 1 to Q) {\n states(i) = nextInt() match {\n case 1 => val s, p = nextInt() - 1; states(i - 1).place(s, p)\n case 2 => val s, p = nextInt() - 1; states(i - 1).remove(s, p)\n case 3 => states(i - 1).flip(nextInt() - 1)\n case 4 => states(nextInt())\n }\n writer.println(states(i).total)\n }\n\n writer.close()\n }\n}"}], "negative_code": [{"source_code": "//package merofeev.contests.codeforces.rnd368\n\nimport java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\n\n/**\n * @author erofeev \n * @since 03.09.16\n */\n//noinspection ReferenceMustBePrefixed\nobject DGraphPersistence {\n\n val MAX_COMMANDS = 100000\n\n val cCodes = new Array[Int](MAX_COMMANDS)\n //0 if it was step\n val cRows = new Array[Int](MAX_COMMANDS)\n //0 if not upplicable\n val cPositions = new Array[Int](MAX_COMMANDS)\n var rowSize = 0\n\n val book = Array.ofDim[Boolean](1000, 1000)\n val rowSums = new Array[Int](1000)\n val isRowFlipped = new Array[Boolean](1000)\n var currAnsw = 0\n val commandsTree = new Array[ArrayBuffer[Int]](MAX_COMMANDS)\n val answers = new Array[Int](MAX_COMMANDS)\n\n\n def solve(parentCmmand: Int): Unit = {\n answers(parentCmmand) = currAnsw\n for (command <- commandsTree(parentCmmand)) {\n val code: Int = cCodes(command)\n var updates = false\n val row: Int = cRows(command)\n for (rollback <- 0 to 1) {\n if (code == 3) {\n currAnsw -= rowSums(row) // rm current value\n isRowFlipped(row) = !isRowFlipped(row)\n rowSums(row) = rowSize - rowSums(row) // compute new val\n currAnsw += rowSums(row) //up new value\n } else {\n val pos = cPositions(command)\n val isSet = book(row)(pos) ^ isRowFlipped(row)\n val upVal = if (code == 1) 1 else -1\n if (rollback == 0) {\n updates = isSet ^ code == 1\n if (updates) {\n book(row)(pos) = !book(row)(pos)\n rowSums(row) += upVal\n currAnsw += upVal\n }\n } else if (rollback == 1 && updates) {\n book(row)(pos) = !book(row)(pos)\n rowSums(row) -= upVal\n currAnsw -= upVal\n }\n }\n if (rollback == 0) {\n solve(command)\n }\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n\n for (i <- commandsTree.indices) {\n commandsTree(i) = new ArrayBuffer()\n }\n\n\n val in = new Scanner(System.in)\n val rows = in.nextInt()\n this.rowSize = in.nextInt()\n val ops = in.nextInt()\n\n //save every shelf as a bitset object (30b), 30b * 10000 = 3mb??\n //save every bookcase as a list of shelfs (100 * 8 + 20 = 850) * 100000 = 85mb\n var pos = 1\n while (in.hasNextInt) {\n cCodes(pos) = in.nextInt()\n cRows(pos) = in.nextInt()\n if (cCodes(pos) == 4) {\n commandsTree(cRows(pos)) += pos\n } else {\n cRows(pos) -= 1 //alignment\n commandsTree(pos - 1) += pos\n }\n if (cCodes(pos) == 1 || cCodes(pos) == 2) {\n cPositions(pos) = in.nextInt() - 1 //alignment\n }\n pos += 1\n }\n solve(0)\n for (comm <- 1 to ops) {\n println(answers(comm))\n }\n }\n\n}\n"}], "src_uid": "2b78f6626fce6b5b4f9628fb15666dc4"} {"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n (1 to t).foreach{ _ =>\n val n = in.nextLong()\n val k = in.nextLong()\n if((n-k)%2 == 0){\n val x: Long = (n-k)/2\n if(2L*x>=(k*(k-1L))){\n out.println(\"YES\")\n }else{\n out.println(\"NO\")\n }\n\n }else{\n out.println(\"NO\")\n }\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}", "positive_code": [{"source_code": "object Main {\n \n\tdef main(arr: Array[String]): Unit = {\n\t\tvar n: Int = readLine().toInt\n\t\twhile (n > 0) {\n\t\t\tvar _pairs = readLine().split(\" \")\n\t\t\tvar num1 : Long = _pairs(0).toLong\n\t\t\tvar num2 : Long = _pairs(1).toLong\n\t\t\tif (num1 % 2 == num2 % 2 && num1 >= num2 * num2){\n\t\t\t println(\"YES\")\n\t\t\t} else {\n\t\t\t println(\"NO\")\n\t\t\t}\n\t\t\tn -= 1\n\t\t}\n\t\t\n\t}\n \n}"}], "negative_code": [{"source_code": "object Main {\n\n\tdef main(arr: Array[String]): Unit = {\n\t\tvar n: Int = readLine().toInt\n\t\twhile (n > 0) {\n\t\t\tvar _pairs = readLine().split(\" \")\n\t\t\tvar num1 : Int = _pairs(0).toInt\n\t\t\tvar num2 : Int = _pairs(1).toInt\n\t\t\tif (num1 % 2 == num2 % 2 && num1 >= num2 * num2){\n\t\t\t println(\"YES\")\n\t\t\t} else {\n\t\t\t println(\"NO\")\n\t\t\t}\n\t\t\tn -= 1\n\t\t}\n\t\t\n\t}\n\n}"}, {"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n (1 to t).foreach{ _ =>\n val n = in.nextInt()\n val k = in.nextInt()\n if((n-k)%2 == 0){\n val x = (n-k)/2\n if(2*x>=(k*(k-1))){\n out.println(\"YES\")\n }else{\n out.println(\"NO\")\n }\n\n }else{\n out.println(\"NO\")\n }\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "src_uid": "a4c82fffb31bc7e42870fd84e043e815"} {"source_code": "object Main extends App {\n final object InOut {\n val in =\n new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, true)\n var arr = Array[String]()\n var index: Int = 0\n def nextToken: String = {\n if (index >= arr.length) {\n index = 0\n arr = in.readLine.split(\" \")\n }\n val ans = arr(index)\n index += 1\n ans\n }\n \n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n \n import InOut._\n\n val n = nextInt\n //scala one line magic\n println(nextInts(n).sorted.foldLeft(1)({ (i, j) => if (i <= j) i+1 else i}) -1 )\n}\n", "positive_code": [{"source_code": "object codeForces extends App\n{\n val n=scala.io.StdIn.readInt()\n val line=scala.io.StdIn.readLine()\n val ara=scala.collection.mutable.ArrayBuffer.empty[Int]\n val input=line.split(\" \").map(_.toInt)\n var i=0\n for(i<-0 until n) {\n ara+=input(i)\n }\n val sorted=ara.sorted\n \n var ans=1\n for (x<-sorted) {\n if(x>=ans) ans+=1\n }\n \n println(ans-1)\n}\n"}, {"source_code": "object _1165B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val as = io.read[Seq[Int]].sorted\n val ans = as.foldLeft(1)({ case (i, j) => if (i <= j) i+1 else i})\n io.write(ans - 1)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Main extends CodeForcesApp {\n\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val sortedContests = io.read[Seq[Int]].sorted\n\n var i = 0\n var k = 1\n var ans = 0\n while (i < sortedContests.length) {\n if (sortedContests(i) >= k) {\n k += 1\n ans += 1\n }\n i += 1\n }\n io.writeLine(ans)\n }\n}\n\n/** **************************[Ignore Template Below] ****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n\n def apply(io: IO): io.type\n\n def main(args: Array[String]): Unit = this (new IO(System.in, System.out)).close()\n}\n\n/** *********************************[Scala I/O] *********************************************/\n\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while (tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n\n def writeLine(): this.type = {\n printer.println()\n this\n }\n\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\n\nobject IO {\n\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n\n implicit val string: Read[String] = new Read(_.next())\n implicit val int: Read[Int] = string.map(_.toInt)\n implicit val long: Read[Long] = string.map(_.toLong)\n implicit val bigInt: Read[BigInt] = string.map(BigInt(_))\n implicit val double: Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal: Read[BigDecimal] = string.map(BigDecimal(_))\n\n implicit def tuple2[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n\n implicit def tuple3[A: Read, B: Read, C: Read]: Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read]: Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n\n implicit val boolean: Read[Boolean] = string map { s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n\n}"}, {"source_code": "object Main extends App {\n final object InOut {\n val in =\n new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, true)\n var arr = Array[String]()\n var index: Int = 0\n def nextToken: String = {\n if (index >= arr.length) {\n index = 0\n arr = in.readLine.split(\" \")\n }\n val ans = arr(index)\n index += 1\n ans\n }\n \n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n \n import InOut._\n\n val n = nextInt\n val arr = nextInts(n).sorted \n\n var count = 0\n var k = 1\n for (i <- arr){\n if (i >= k){\n count += 1\n k += 1\n }\n }\n\n println(count)\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.io.StdIn\n\nobject Btask560 extends App {\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n val x = StdIn.readLine().split(' ').map(_.toInt).sorted\n\n var day = 1\n\n for (i <- 0 until n) {\n if (x(i) >= day) {\n day += 1\n }\n }\n\n println(day-1)\n}\n"}], "negative_code": [], "src_uid": "4f02ac641ab112b9d6aee222e1365c09"} {"source_code": "object Solution {\n def main(args: Array[String]) {\n val r = new Reader\n val n, m = r.read[Long]\n val cl, ce = r.read[Int]\n val v = r.read[Long]\n val cls = r.read[Array[Long]](cl)\n val ces = r.read[Array[Long]](ce)\n val q = r.read[Int] \n val qs = r.read[List[(Long, Long, Long, Long)]](q)\n \n qs.foreach {\n case (x1, y1, x2, y2) => {\n val ds = if (cl > 0) {\n val i1 = 0.max(lb(cls(_) > y1, 0, cl-1)).min(cl-1)\n val i12 = (cl-1).min(i1+1)\n val i2 = 0.max(lb(cls(_) > y2, 0, cl-1)).min(cl-1)\n val i22 = (cl-1).min(i2+1)\n val s1 = (y1 - cls(i1)).abs + (y2 - cls(i1)).abs\n val s2 = (y1 - cls(i12)).abs + (y2 - cls(i12)).abs\n val s3 = (y1 - cls(i2)).abs + (y2 - cls(i2)).abs\n val s4 = (y1 - cls(i22)).abs + (y2 - cls(i22)).abs\n s1.min(s2.min(s3.min(s4))) + (x2 - x1).abs\n } else Long.MaxValue\n \n val de = if (ce > 0) {\n val j1 = 0.max(lb(ces(_) > y1, 0, ce-1)).min(ce-1)\n val j12 = (ce-1).min(j1+1)\n val j2 = 0.max(lb(ces(_) > y2, 0, ce-1)).min(ce-1)\n val j22 = (ce-1).min(j2+1)\n \n val e1 = (y1 - ces(j1)).abs + (y2 - ces(j1)).abs\n val e2 = (y1 - ces(j12)).abs + (y2 - ces(j12)).abs\n val e3 = (y1 - ces(j2)).abs + (y2 - ces(j2)).abs\n val e4 = (y1 - ces(j22)).abs + (y2 - ces(j22)).abs\n e1.min(e2.min(e3.min(e4))) + ((x2 - x1).abs - 1) / v + 1\n } else Long.MaxValue\n \n val dx = if (x1 == x2) (y2 - y1).abs else Long.MaxValue\n \n println(ds.min(de.min(dx)))\n }\n }\n }\n \n def lb(test: (Int => Boolean), from: Int, to: Int) = { \n import annotation.tailrec\n @tailrec\n def go(l: Int, r: Int): Int =\n if (l <= r) {\n val m = (r + l) / 2 \n if (test(m)) go(l, m - 1) else go(m + 1, r)\n } else r\n\n go(from, to) \n }\n}\n\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n def this() = this(new InputStreamReader(System.in))\n\n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n\n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n \n implicit def tuple[A: Read]: Read[(A, A, A, A)] = new Read(r => (r.read[A], r.read[A], r.read[A], r.read[A]))\n\n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine).takeWhile(_ != null).filter(_ != \"\").map(new StringTokenizer(_)).buffered\n}", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m, cl, ce, v) = readInts(5)\n val ls, es = new java.util.TreeSet[Integer]\n\n val _ls = readInts(cl)\n for (x <- _ls) ls.add(x)\n\n val _es = readInts(ce)\n for (x <- _es) es.add(x)\n\n val Array(q) = readInts(1)\n\n val res = new mutable.ArrayBuilder.ofInt\n\n for (_ <- 0 until q) {\n val Array(y1, x1, y2, x2) = readInts(4)\n var min = Int.MaxValue\n\n def elev(x: Int): Int = {\n (Math.abs(y1 - y2) + v - 1) / v + Math.abs(x1 - x) + Math.abs(x2 - x)\n }\n\n def stair(x: Int): Int = {\n Math.abs(y1 - y2) + Math.abs(x1 - x) + Math.abs(x2 - x)\n }\n\n if (y1 == y2) min = Math.abs(x1 - x2)\n else {\n\n val eLeft = es.floor(x1)\n val eRight = es.ceiling(x1)\n val lLeft = ls.floor(x1)\n val lRight = ls.ceiling(x1)\n\n if (eLeft != null && elev(eLeft) < min) min = elev(eLeft)\n if (eRight != null && elev(eRight) < min) min = elev(eRight)\n\n if (lLeft != null && stair(lLeft) < min) min = stair(lLeft)\n if (lRight != null && stair(lRight) < min) min = stair(lRight)\n }\n\n res += min\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.result.mkString(\"\\n\"))\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val r = new Reader\n val n, m = r.read[Long]\n val cl, ce = r.read[Int]\n val v = r.read[Long]\n val cls = r.read[Array[Long]](cl)\n val ces = r.read[Array[Long]](ce)\n val q = r.read[Int] \n val qs = r.read[List[(Long, Long, Long, Long)]](q)\n \n qs.foreach {\n case (x1, y1, x2, y2) => {\n val ds = if (cl > 0) {\n val i1 = 0.max(lb(cls(_) > y1, 0, cl-1)).min(cl-1)\n val i12 = (cl-1).min(i1+1)\n val i2 = 0.max(lb(cls(_) > y2, 0, cl-1)).min(cl-1)\n val i22 = (cl-1).min(i2+1)\n val s1 = (y1 - cls(i1)).abs + (y2 - cls(i1)).abs\n val s2 = (y1 - cls(i12)).abs + (y2 - cls(i12)).abs\n val s3 = (y1 - cls(i2)).abs + (y2 - cls(i2)).abs\n val s4 = (y1 - cls(i22)).abs + (y2 - cls(i22)).abs\n s1.min(s2.min(s3.min(s4))) + (x2 - x1).abs\n } else Long.MaxValue\n \n val de = if (ce > 0) {\n val j1 = 0.max(lb(ces(_) > y1, 0, ce-1)).min(ce-1)\n val j12 = (ce-1).min(j1+1)\n val j2 = 0.max(lb(ces(_) > y2, 0, ce-1)).min(ce-1)\n val j22 = (ce-1).min(j2+1)\n \n val e1 = (y1 - ces(j1)).abs + (y2 - ces(j1)).abs\n val e2 = (y1 - ces(j12)).abs + (y2 - ces(j12)).abs\n val e3 = (y1 - ces(j2)).abs + (y2 - ces(j2)).abs\n val e4 = (y1 - ces(j22)).abs + (y2 - ces(j22)).abs\n e1.min(e2.min(e3.min(e4))) + ((x2 - x1).abs - 1) / v + 1\n } else Long.MaxValue\n \n println(ds.min(de))\n }\n }\n }\n \n def lb(test: (Int => Boolean), from: Int, to: Int) = { \n import annotation.tailrec\n @tailrec\n def go(l: Int, r: Int): Int =\n if (l <= r) {\n val m = (r + l) / 2 \n if (test(m)) go(l, m - 1) else go(m + 1, r)\n } else r\n\n go(from, to) \n }\n}\n\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n def this() = this(new InputStreamReader(System.in))\n\n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n\n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n \n implicit def tuple[A: Read]: Read[(A, A, A, A)] = new Read(r => (r.read[A], r.read[A], r.read[A], r.read[A]))\n\n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine).takeWhile(_ != null).filter(_ != \"\").map(new StringTokenizer(_)).buffered\n}"}], "src_uid": "9bf6be240fb16da07b942be39bb3916a"} {"source_code": "import java.util.Scanner\n\nobject Main {\n\n\tdef main(args: Array[String]): Unit = {\n\t\tval scanner = new Scanner (System.in)\n\t\tval t = scanner.nextInt()\n\t\tfor (i <- 1 to t) {\n\t\t\tval n = scanner.nextLong()\n\t\t\t\tprintln (solve (n))\n\t\t}\n\t}\n\n\tdef solve(n: Long): Long = {\n\t\t4*n / gcd(4*n, n+1) + 1\n\t}\n\n\tdef gcd(x: Long, y: Long): Long = {\n\t\tif (y == 0) x else gcd (y, x % y)\n\t}\n\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Square {\n \n def solve(n:Long):Long={\n //find min k: 4*n*k/(n+1)+1\n if ((n+1)%4==0){\n n+1\n }else if ((n+1)%2==0){\n 2*n+1\n }else{\n 4*n+1\n }\n }\n \n def solveSquare(in:List[Long]):List[Long]={\n in.map { x => solve(x)}\n }\n \n def main(args:Array[String]){\n val n = StdIn.readLine().toInt\n val l = StdIn.readLine().split(\" \").map { x => x.toLong }\n println(solveSquare(l.toList).mkString(\"\\n\"))\n }\n}"}, {"source_code": "object Main {\n\tdef main(args: Array[String]) {\n\t\tdef gcd(a: Long, b: Long):Long = {\n\t\t\tif (a == b) a\n\t\t\telse if (a == 0) b\n\t\t\telse if (b == 0) a\n\t\t\telse if (a > b) gcd(a%b, b)\n\t\t\telse gcd(b%a, a)\n\t\t}\n\t\tdef lcm(a: Long, b: Long) = a/gcd(a,b)*b\n\t\tval calc = (size: Long) => {\n\t\t\tval count = size * 4\n\t\t\tlcm(count, size + 1) / (size + 1) + 1\n\t\t}\n\t\tval t = Integer.parseInt(readLine())\n\t\tval result = readLine().split(' ')\n\t\t\t.map(java.lang.Long.parseLong)\n\t\t\t.map(calc)\n\t\tresult.foreach(println)\n\t}\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject Square {\n \n def solveSquare(in:List[Long]):List[Long]={\n in.map { x => \n if (x==1) 1\n else if (x==2) 4\n else if (x==3) 4\n else (4*x)+1\n }\n }\n \n def main(args:Array[String]){\n val n = StdIn.readLine().toInt\n val l = StdIn.readLine().split(\" \").map { x => x.toLong }\n println(solveSquare(l.toList).mkString(\"\\n\"))\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main {\n\n\tdef main(args: Array[String]): Unit = {\n\t\tval scanner = new Scanner (System.in)\n\t\tval t = scanner.nextInt()\n\t\tfor (i <- 1 to t) {\n\t\t\tval n = scanner.nextInt()\n\t\t\t\tprintln (solve (n))\n\t\t}\n\t}\n\n\tdef solve(n: Int): Int = {\n\t\t4*n / gcd(4*n, n+1) + 1\n\t}\n\n\tdef gcd(x: Int, y: Int): Int = {\n\t\tif (y == 0) x else gcd (y, x % y)\n\t}\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Square {\n \n def solveSquare(in:List[Int]):List[Int]={\n in.map { x => \n if (x==1) 1\n else if (x==2) 4\n else if (x==3) 4\n else (4*x)+1\n }\n }\n \n def main(args:Array[String]){\n val n = StdIn.readLine().toInt\n val l = StdIn.readLine().split(\" \").map { x => x.toInt }\n println(solveSquare(l.toList).mkString(\"\\n\"))\n }\n}"}], "src_uid": "168dbc4994529f5407a440b0c71086da"} {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val sn = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val t = sn.reduce(_ ^ _)\n val m = 1 << (1 + (math.log10(sn.max) / math.log10(2)).toInt)\n\n val k = (if (t == 0) (1 to m) else (t to t))\n .view\n .collectFirst { case k if sn.diff(sn.map(_ ^ k)).isEmpty => k }\n .getOrElse(-1)\n\n println(k)\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val sn = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val t = sn.reduce(_ ^ _)\n val m = 1 << (1 + (math.log10(sn.max) / math.log10(2)).toInt)\n\n val k = (if (t == 0) (1 to m) else (t to t))\n .collectFirst { case k if sn.diff(sn.map(_ ^ k)).isEmpty => k }\n .getOrElse(-1)\n\n println(k)\n }\n}\n"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val sn = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val t = sn.reduce(_ ^ _)\n\n val k = (if (t == 0) (1 to 1 << (1 + (math.log10(sn.max) / math.log10(2)).toInt)) else (t to t))\n .view\n .collectFirst { case k if sn.diff(sn.map(_ ^ k)).isEmpty => k }\n .getOrElse(-1)\n\n println(k)\n }\n}\n"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val sn = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n\n val ans = sn match {\n case Array(s1, s2, _*) =>\n (sn.reduce(_ ^ _) to 1024)\n .collectFirst { case k if k > 0 && sn.diff(sn.map(_ ^ k)).isEmpty => k }\n .getOrElse(-1)\n case _ => -1\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val sn = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val s = sn.reduce(_ ^ _)\n\n val k = (if (s == 0) (1 to 1024) else (s to s))\n .collectFirst { case k if sn.diff(sn.map(_ ^ k)).isEmpty => k }\n .getOrElse(-1)\n\n println(k)\n }\n}\n"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val sn = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ans = sn match {\n case Array(s1, s2, _*) =>\n (sn.reduce(_ ^ _) to 1024)\n .collectFirst { case k if k > 0 && sn.diff(sn.map(_ ^ k)).isEmpty => k }\n .getOrElse(-1)\n case _ => -1\n }\n\n println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val sn = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n\n val ans = sn match {\n case Array(s1, s2, _*) =>\n List(sn.reduce(_ ^ _), s1, s2)\n .collectFirst { case k if k > 0 && sn.diff(sn.map(_ ^ k)).isEmpty => k }\n .getOrElse(-1)\n case _ => -1\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val sn = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n\n val ans =\n if (sn.length == 1) -1\n else {\n val k = List(sn.reduce(_ ^ _), sn.head, sn.tail.head).filter(_ > 0).head\n\n if (sn.diff(sn.map(_ ^ k)).nonEmpty) -1\n else k\n }\n\n println(ans)\n }\n}\n"}], "src_uid": "3ecb65a8be42f882ae6b528fd86243cd"} {"source_code": "\n/**\n * \n *\n * @author pvasilyev\n * @since 28 Apr 2016\n */\nobject Problem158 extends App {\n\n val n: Int = scala.io.StdIn.readInt()\n val a: Array[Long] = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n // sum(i) = sum(a, 0, i)\n val sum: Array[Long] = Array.ofDim[Long](n)\n sum(0) = a(0)\n for (i <- 1 until n) {\n sum(i) = sum(i - 1) + a(i)\n }\n if (sum(n - 1) % 3 != 0) {\n println(0)\n } else {\n val oneThirdOfSum = sum(n - 1) / 3\n // backSum(j) = sum(a, j, n - 1)\n val backSum: Array[Long] = Array.ofDim[Long](n)\n backSum(n - 1) = a(n - 1)\n for (i <- n - 2 to (0, -1)) {\n backSum(i) = backSum(i + 1) + a(i)\n }\n val cnt: Array[Int] = Array.ofDim(n)\n cnt(n - 1) = if (backSum(n - 1) == oneThirdOfSum) 1 else 0\n for (i <- n - 2 to (0, -1)) {\n val tmp = if (backSum(i) == oneThirdOfSum) 1 else 0\n cnt(i) = cnt(i+1) + tmp\n }\n\n var answer: Long = 0L\n for (i <- 1 until n-1) {\n if (sum(i-1) == oneThirdOfSum) {\n answer += cnt(i+1)\n }\n }\n\n println(answer)\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n def foo(): Unit = {\n val len = scala.io.StdIn.readInt()\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toLong).toArray\n val total: Long= a.sum\n if(total % 3 != 0) println(0) else {\n val target = total / 3\n val target2 = target + target\n var sum = 0L\n val t1 = (0 until len - 2).flatMap(i => {\n sum += a(i)\n if (sum == target) Some(i) else None\n })\n sum = 0\n val t2 = (0 until len - 1).flatMap(i => {\n sum += a(i)\n if (sum == target2) Some(i) else None\n }).toArray\n val t2Len = t2.length\n var last = 0\n var res = 0L\n t1.foreach(o => {\n val index = t2.indexWhere( _ > o, last)\n if(index != -1){\n last = index\n res += t2Len - index\n }\n })\n print(res)\n }\n }\n foo()\n}"}, {"source_code": "import java.util\n\nimport scala.collection.Searching\n\nobject C466 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readLongs(n)\n val sum = input.sum\n if(input.length < 3) {\n println(\"0\")\n } else if(sum % 3 == 0) {\n val tofind = sum/3\n for(i <- 1 until n) {\n input(i) += input(i-1)\n }\n if (tofind == 0) {\n val x = input.count(_ == 0)\n println(((x-1).toLong*(x-2).toLong)/2L)\n } else {\n val x = input.zipWithIndex.dropRight(2).filter(_._1 == tofind).map(_._2)\n val y = input.zipWithIndex.drop(1).dropRight(1).filter(_._1 == 2*tofind).map(_._2)\n if(x.length == 0 || y.length == 0) {\n println(\"0\")\n } else {\n var ret = 0L\n for(i <- x.indices) {\n ret += (y.length - y.indexWhere(_ > i))\n }\n println(ret)\n }\n }\n } else {\n println(\"0\")\n }\n\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\n\nobject C466 {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Long](n)\n val prefixSum = new Array[Long](n)\n val map = new MultiHashSet[Long]\n a(0) = nextInt\n prefixSum(0) = a(0)\n for (i <- 1 until n) {\n a(i) = nextInt\n prefixSum(i) = a(i) + prefixSum(i - 1)\n }\n for (i <- 0 until n - 1) {\n map.add(prefixSum(i))\n }\n var ans = 0L\n for (pos <- 1 until n - 1) {\n val sum = prefixSum(pos - 1)\n map.remove(sum)\n val left = prefixSum(n - 1) - sum\n if (left / 2 == sum && left % 2 == 0) {\n val cnt = map.count(2 * sum)\n ans += cnt\n }\n }\n out.println(ans)\n return 0\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n val sum = data.sum\n val third = sum / 3\n if (sum % 3 == 0) {\n val r = data.foldLeft((0l, 0l, 0l)) {\n case((i, soFar, sumFromB), el) =>\n val nSum = sumFromB + el\n val nSoFar = if (nSum == 2 * third && third != 0) soFar + i\n else if (third == 0) Math.max(soFar, soFar + i - 1)\n else soFar\n val ni = if (nSum == third) i + 1 else i\n (ni, nSoFar, nSum)\n }\n println(r._2)\n } else {\n println(0)\n }\n\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val sum = data.sum\n if (sum % 3 == 0) {\n val agg = data.tail.scan(data.head){_+_}\n val firstCount = agg.count(_ == sum / 3)\n val secondCount = agg.count(_ == 2 * sum / 3)\n println(firstCount * secondCount)\n } else {\n println(0)\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val sum = data.sum\n val third = sum / 3\n if (sum % 3 == 0) {\n val r = data.foldLeft((0, 0l, 0l)) {\n case((i, soFar, sumFromB), el) =>\n val nSoFar = if (sumFromB + el == 2 * third && third != 0) soFar + i\n else if (third == 0) soFar + (i - 1) * i / 2\n else soFar\n val ni = if (sumFromB + el == third) i + 1 else i\n (ni, nSoFar, sumFromB + el)\n }\n println(r._2)\n } else {\n println(0)\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val sum = data.sum\n val third = sum / 3\n if (sum % 3 == 0) {\n val r = data.foldLeft((0, 0l, 0l)) {\n case((i, soFar, sumFromB), el) =>\n val nSum = sumFromB + el\n val nSoFar = if (nSum == 2 * third && third != 0) soFar + i\n else if (third == 0) Math.max(soFar, soFar + i - 1)\n else soFar\n val ni = if (nSum == third) i + 1 else i\n (ni, nSoFar, nSum)\n }\n println(r._2)\n } else {\n println(0)\n }\n\n}\n"}, {"source_code": "import java.util\n\nimport scala.collection.Searching\n\nobject C466 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readLongs(n)\n val sum = input.sum\n if(input.size < 3) {\n println(\"0\")\n } else if(sum%3 == 0) {\n val tofind = sum/3\n for(i <- 1 until n) {\n input(i) += input(i-1)\n }\n if (tofind == 0) {\n val x = input.count(_ == 0)\n println(((x-1).toLong*(x-2))/2.toLong)\n } else {\n val x = input.zipWithIndex.dropRight(2).filter(_._1 == tofind).map(_._2)\n val y = input.zipWithIndex.drop(1).dropRight(1).filter(_._1 == 2*tofind).map(_._2)\n if(x.length == 0 || y.length == 0) {\n println(\"0\")\n } else {\n var ret = 0\n for(i <- x.indices) {\n ret += (y.length - y.indexWhere(_ > i))\n }\n println(ret)\n }\n }\n } else {\n println(\"0\")\n }\n\n }\n}"}, {"source_code": "import java.util\n\nimport scala.collection.Searching\n\nobject C466 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readLongs(n)\n val sum = input.sum\n if(input.size < 3) {\n println(\"0\")\n } else if(sum%3 == 0) {\n val tofind = sum/3\n for(i <- 1 until n) {\n input(i) += input(i-1)\n }\n val ret =\n if (tofind == 0) {\n val x = input.count(_ == 0)\n (x-1)*(x-2)/2\n } else {\n val x = input.zipWithIndex.dropRight(2).filter(_._1 == tofind).map(_._2)\n val y = input.zipWithIndex.drop(1).dropRight(1).filter(_._1 == 2*tofind).map(_._2)\n if(x.length == 0 || y.length == 0) {\n println(\"0\")\n } else {\n var ret = 0\n for(i <- x.indices) {\n ret += (y.length - y.indexWhere(_ > i))\n }\n ret\n }\n }\n println(ret)\n } else {\n println(\"0\")\n }\n\n }\n}"}, {"source_code": "import java.util\n\nimport scala.collection.Searching\n\nobject C466 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readLongs(n)\n val sum = input.sum\n if(input.size < 3) {\n println(\"0\")\n } else if(sum%3 == 0) {\n val tofind = sum/3\n for(i <- 1 until n) {\n input(i) += input(i-1)\n }\n val ret =\n if (tofind == 0) {\n val x = input.count(_ == 0)\n x-2\n } else {\n val x = input.zipWithIndex.dropRight(2).filter(_._1 == tofind).map(_._2)\n val y = input.zipWithIndex.drop(1).dropRight(1).filter(_._1 == 2*tofind).map(_._2)\n if(x.length == 0 || y.length == 0) {\n println(\"0\")\n } else {\n var ret = 0\n for(i <- x.indices) {\n ret += (y.length - y.indexWhere(_ > i))\n }\n ret\n }\n }\n println(ret)\n } else {\n println(\"0\")\n }\n\n }\n}"}, {"source_code": "\n/**\n * \n *\n * @author pvasilyev\n * @since 28 Apr 2016\n */\nobject Problem158 extends App {\n\n val n: Int = scala.io.StdIn.readInt()\n val a: Array[Long] = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n // sum(i) = sum(a, 0, i)\n val sum: Array[Long] = Array.ofDim[Long](n)\n sum(0) = a(0)\n for (i <- 1 until n) {\n sum(i) = sum(i - 1) + a(i)\n }\n if (sum(n - 1) % 3 != 0) {\n println(0)\n } else {\n val oneThirdOfSum = sum(n - 1) / 3\n // backSum(j) = sum(a, j, n - 1)\n val backSum: Array[Long] = Array.ofDim[Long](n)\n backSum(n - 1) = a(n - 1)\n for (i <- n - 2 to (0, -1)) {\n backSum(i) = backSum(i + 1) + a(i)\n }\n val cnt: Array[Int] = Array.ofDim(n)\n cnt(n - 1) = if (backSum(n - 1) == oneThirdOfSum) 1 else 0\n for (i <- n - 2 to (0, -1)) {\n val tmp = if (backSum(i) == oneThirdOfSum) 1 else 0\n cnt(i) = cnt(i+1) + tmp\n }\n\n var answer: Long = 0L\n for (i <- 0 until n-1) {\n if (sum(i) == oneThirdOfSum) {\n answer += cnt(i + 1)\n }\n }\n\n println(answer)\n }\n}\n"}, {"source_code": "\n/**\n * \n *\n * @author pvasilyev\n * @since 28 Apr 2016\n */\nobject Problem158 extends App {\n\n val n: Int = scala.io.StdIn.readInt()\n val a: Array[Long] = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n // sum(i) = sum(a, 0, i)\n val sum: Array[Long] = Array.ofDim(n)\n sum(0) = a(0)\n for (i <- 1 until n) {\n sum(i) = sum(i - 1) + a(i)\n }\n if (sum(n - 1) % 3 != 0) {\n println(0)\n } else {\n val oneThirdOfSum = sum(n - 1) / 3\n // backSum(j) = sum(a, j, n - 1)\n val backSum: Array[Long] = Array.ofDim(n)\n backSum(n - 1) = a(n - 1)\n for (i <- n - 2 to (0, -1)) {\n backSum(i) = backSum(i + 1) + a(i)\n }\n val cnt: Array[Int] = Array.ofDim(n)\n cnt(n - 1) = if (backSum(n - 1) == oneThirdOfSum) 1 else 0\n for (i <- n - 2 to (0, -1)) {\n val tmp = if (backSum(i) == oneThirdOfSum) 1 else 0\n cnt(i) = cnt(i+1) + tmp\n }\n\n var answer = 0\n for (i <- 1 until n-1) {\n if (sum(i) == oneThirdOfSum) {\n answer += cnt(i + 1)\n }\n }\n\n println(answer)\n }\n}\n"}, {"source_code": "\n/**\n * \n *\n * @author pvasilyev\n * @since 28 Apr 2016\n */\nobject Problem158 extends App {\n\n val n: Int = scala.io.StdIn.readInt()\n val a: Array[Long] = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n // sum(i) = sum(a, 0, i)\n val sum: Array[Long] = Array.ofDim[Long](n)\n sum(0) = a(0)\n for (i <- 1 until n) {\n sum(i) = sum(i - 1) + a(i)\n }\n if (sum(n - 1) % 3 != 0) {\n println(0)\n } else {\n val oneThirdOfSum = sum(n - 1) / 3\n // backSum(j) = sum(a, j, n - 1)\n val backSum: Array[Long] = Array.ofDim[Long](n)\n backSum(n - 1) = a(n - 1)\n for (i <- n - 2 to (0, -1)) {\n backSum(i) = backSum(i + 1) + a(i)\n }\n val cnt: Array[Int] = Array.ofDim(n)\n cnt(n - 1) = if (backSum(n - 1) == oneThirdOfSum) 1 else 0\n for (i <- n - 2 to (0, -1)) {\n val tmp = if (backSum(i) == oneThirdOfSum) 1 else 0\n cnt(i) = cnt(i+1) + tmp\n }\n\n var answer: Long = 0L\n for (i <- 1 until n-1) {\n if (sum(i) == oneThirdOfSum) {\n answer += cnt(i + 1)\n }\n }\n\n println(answer)\n }\n}\n"}, {"source_code": "\n/**\n * \n *\n * @author pvasilyev\n * @since 28 Apr 2016\n */\nobject Problem158 extends App {\n\n val n: Int = scala.io.StdIn.readInt()\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n // sum(i) = sum(a, 0, i)\n val sum: Array[Long] = Array.ofDim(n)\n sum(0) = a(0)\n for (i <- 1 until n) {\n sum(i) = sum(i - 1) + a(i)\n }\n if (sum(n - 1) % 3 != 0) {\n println(0)\n } else {\n val oneThirdOfSum = sum(n - 1) / 3\n // backSum(j) = sum(a, j, n - 1)\n val backSum: Array[Long] = Array.ofDim(n)\n backSum(n - 1) = a(n - 1)\n for (i <- n - 2 to (0, -1)) {\n backSum(i) = backSum(i + 1) + a(i)\n }\n val cnt: Array[Int] = Array.ofDim(n)\n cnt(n - 1) = if (backSum(n - 1) == oneThirdOfSum) 1 else 0\n for (i <- n - 2 to (0, -1)) {\n val tmp = if (backSum(i) == oneThirdOfSum) 1 else 0\n cnt(i) = cnt(i+1) + tmp\n }\n\n var answer = 0\n for (i <- 1 until n-1) {\n if (sum(i) == oneThirdOfSum) {\n answer += cnt(i + 1)\n }\n }\n\n println(answer)\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\n\nobject C466 {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n val prefixSum = new Array[Int](n)\n val map = new MultiHashSet[Int]\n a(0) = nextInt\n prefixSum(0) = a(0)\n for (i <- 1 until n) {\n a(i) = nextInt\n prefixSum(i) = a(i) + prefixSum(i - 1)\n }\n for (i <- 0 until n - 1) {\n map.add(prefixSum(i))\n }\n var ans = 0L\n for (pos <- 1 until n - 1) {\n val sum = prefixSum(pos - 1)\n map.remove(sum)\n val left = prefixSum(n - 1) - sum\n if (left / 2 == sum && left % 2 == 0) {\n val cnt = map.count(2 * sum)\n ans += cnt\n }\n }\n out.println(ans)\n return 0\n }\n}\n"}, {"source_code": "object Solution extends App {\n def foo(): Unit = {\n val len = scala.io.StdIn.readInt()\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n //val a = \"1 -1 1 2 -1 -2 3 -3\".split(\" \").map(_.toInt)\n val total = a.sum\n if(total % 3 != 0) println(-1) else {\n val target = total / 3\n val target2 = target + target\n var sum = 0\n val t1 = (0 until len - 2).flatMap(i => {\n sum += a(i)\n if (sum == target) Some(i) else None\n })\n sum = 0\n val t2 = (0 until len - 1).flatMap(i => {\n sum += a(i)\n if (sum == target2) Some(i) else None\n })\n val t2Len = t2.length\n val res = t1.map(o => t2.indexWhere( _ > o)).filterNot(_ == -1).map(t2Len - _).sum\n print(res)\n }\n }\n foo()\n}\n"}, {"source_code": "object Solution extends App {\n def foo(): Unit = {\n val len = scala.io.StdIn.readInt()\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val total = a.sum\n if(total % 3 != 0) println(0) else {\n val target = total / 3\n val target2 = target + target\n var sum = 0\n val t1 = (0 until len - 2).flatMap(i => {\n sum += a(i)\n if (sum == target) Some(i) else None\n })\n sum = 0\n val t2 = (0 until len - 1).flatMap(i => {\n sum += a(i)\n if (sum == target2) Some(i) else None\n }).toArray\n val t2Len = t2.length\n var last = 0\n var res = 0L\n t1.foreach(o => {\n val index = t2.indexWhere( _ > o, last)\n if(index != -1){\n last = index\n res += t2Len - index\n }\n })\n print(res)\n }\n }\n foo()\n}"}, {"source_code": "object Solution extends App {\n def foo(): Unit = {\n val len = scala.io.StdIn.readInt()\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toArray\n val total: Long= a.sum\n if(total % 3 != 0) println(0) else {\n val target = total / 3\n val target2 = target + target\n var sum = 0L\n val t1 = (0 until len - 2).flatMap(i => {\n sum += a(i)\n if (sum == target) Some(i) else None\n })\n sum = 0\n val t2 = (0 until len - 1).flatMap(i => {\n sum += a(i)\n if (sum == target2) Some(i) else None\n }).toArray\n val t2Len = t2.length\n var last = 0\n var res = 0L\n t1.foreach(o => {\n val index = t2.indexWhere( _ > o, last)\n if(index != -1){\n last = index\n res += t2Len - index\n }\n })\n print(res)\n }\n }\n foo()\n}"}, {"source_code": "object Solution extends App {\n def foo(): Unit = {\n val len = scala.io.StdIn.readInt()\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toArray\n val total = a.sum\n if(total % 3 != 0) println(0) else {\n val target = total / 3\n val target2 = target + target\n var sum = 0L\n val t1 = (0 until len - 2).flatMap(i => {\n sum += a(i)\n if (sum == target) Some(i) else None\n })\n sum = 0\n val t2 = (0 until len - 1).flatMap(i => {\n sum += a(i)\n if (sum == target2) Some(i) else None\n }).toArray\n val t2Len = t2.length\n var last = 0\n var res = 0L\n t1.foreach(o => {\n val index = t2.indexWhere( _ > o, last)\n if(index != -1){\n last = index\n res += t2Len - index\n }\n })\n print(res)\n }\n }\n foo()\n}"}, {"source_code": "object Solution extends App {\n def foo(): Unit = {\n val len = scala.io.StdIn.readInt()\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n //val a = \"1 -1 1 2 -1 -2 3 -3\".split(\" \").map(_.toInt)\n val total = a.sum\n if(total % 3 != 0) println(-1) else {\n val target = total / 3\n val target2 = target + target\n var sum = 0\n val t1 = (0 until len - 2).flatMap(i => {\n sum += a(i)\n if (sum == target) Some(i) else None\n })\n sum = 0\n val t2 = (0 until len - 1).flatMap(i => {\n sum += a(i)\n if (sum == target2) Some(i) else None\n })\n val t2Len = t2.length\n val res = t1.map(o => t2.indexWhere( _ > o)).filterNot(_ == -1).map(t2Len - _).foldLeft(0L)(_+_)\n print(res)\n }\n }\n foo()\n}"}, {"source_code": "object Solution extends App {\n def foo(): Unit = {\n val len = scala.io.StdIn.readInt()\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n //val a = \"1 -1 1 2 -1 -2 3 -3\".split(\" \").map(_.toInt)\n val total = a.sum\n if(total % 3 != 0) println(0) else {\n val target = total / 3\n val target2 = target + target\n var sum = 0\n val t1 = (0 until len - 2).flatMap(i => {\n sum += a(i)\n if (sum == target) Some(i) else None\n })\n sum = 0\n val t2 = (0 until len - 1).flatMap(i => {\n sum += a(i)\n if (sum == target2) Some(i) else None\n })\n val t2Len = t2.length\n val res = t1.map(o => t2.indexWhere( _ > o)).filterNot(_ == -1).map(t2Len - _).sum\n print(res)\n }\n }\n foo()\n}"}], "src_uid": "2558db57229e55ffe0de0d8cf217035b"} {"source_code": "import java.util.Scanner\nimport scala.collection.mutable._\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n, m = sc.nextInt()\n val c = Array.tabulate(n)(_ => sc.nextInt())\n\n val mm = c.map(_ -> Set[Int]()).toMap\n\n for (i <- 0 until m) {\n val a, b = (sc.nextInt() - 1)\n if (c(a) != c(b)) {\n mm(c(a)) += c(b)\n mm(c(b)) += c(a)\n }\n }\n\n val (ans, _) = mm reduce { (a, b) =>\n if (b._2.size > a._2.size) b\n else if (b._2.size == a._2.size && b._1 < a._1) b else a\n }\n\n println(ans)\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Main extends App {\nimport scala.collection.mutable.{Map, Set}\n val sc = new Scanner(System.in)\n\n val n, m = sc.nextInt()\n val c = Array.tabulate(n)(_ => sc.nextInt())\n\n val mm = c.map(_ -> Set[Int]()).toMap\n\n for (i <- 0 until m) {\n val a, b = (sc.nextInt() - 1)\n if (c(a) != c(b)) {\n mm(c(a)) += c(b)\n mm(c(b)) += c(a)\n }\n }\n\n val (ans, _) = mm reduce { (a, b) =>\n if (b._2.size > a._2.size) b\n else if (b._2.size == a._2.size && b._1 < a._1) b else a\n }\n\n println(ans)\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport scala.collection.mutable.Map\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n, m = sc.nextInt()\n val c = Array.tabulate(n)(_ => sc.nextInt())\n\n val mm = Map[Int, Set[Int]]() withDefault (_ => Set[Int]())\n\n for (i <- 0 until m) {\n val a, b = (sc.nextInt() - 1)\n if (c(a) != c(b)) {\n mm(c(a)) = mm(c(a)) + c(b)\n mm(c(b)) = mm(c(b)) + c(a)\n }\n }\n\n val (ans, ansn) = mm.reduce((a, b) => if (b._2.size > a._2.size) b else a)\n\n println(ans)\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable._\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n, m = sc.nextInt()\n val c = Array.tabulate(n)(_ => sc.nextInt())\n\n val mm = Map[Int, Int]() withDefault (_ => 0)\n\n for (i <- 0 until m) {\n val a, b = (sc.nextInt() - 1)\n if (c(a) != c(b)) {\n mm(c(a)) += 1\n mm(c(b)) += 1\n }\n }\n\n val (ans, ansn) = mm.reduce((a, b) => if (b._2 > a._2) b else a)\n\n println(ans)\n}\n"}], "src_uid": "89c27a5c76f4ddbd14af2d30ac8b6330"} {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.util.Sorting\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val left = scala.collection.mutable.Map.empty[Int, ArrayBuffer[Int]]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (l != r) {\n if (!left.contains(r)) left += r -> ArrayBuffer.empty[Int]\n left(r) += l\n if (!left.contains(l)) left += l -> ArrayBuffer.empty[Int]\n left(l) += r\n }\n }\n\n for (a <- left.keys) {\n val sorted = left(a).sorted\n val middle = (sorted.size - 1) / 2\n val med = sorted(middle)\n var news = 0L\n var old = 0L\n for (l <- sorted) {\n news += math.abs(l - med)\n old += math.abs(l - a)\n }\n //println(med, old, news)\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n\n println(moves - canSave1)\n}", "positive_code": [{"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.util.Sorting\nimport scala.collection.mutable.ArrayBuffer\nimport scala.reflect.ClassTag\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val left = scala.collection.mutable.Map.empty[Int, Growable]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (l != r) {\n if (!left.contains(r)) left += r -> new Growable()\n left(r) += l\n if (!left.contains(l)) left += l -> new Growable()\n left(l) += r\n }\n }\n\n for (a <- left.keys) {\n val sorted = left(a).get\n Sorting.quickSort(sorted)\n val middle = (sorted.size - 1) / 2\n val med = sorted(middle)\n var news = 0L\n var old = 0L\n for (l <- sorted) {\n news += math.abs(l - med)\n old += math.abs(l - a)\n }\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n\n println(moves - canSave1)\n\n type Nums = Int\n class Growable(private var arr: Array[Nums] = Array.empty[Nums]) {\n var size = arr.size\n @inline def apply(index: Int): Nums = arr(index)\n @inline def +=(x: Nums): Unit = {\n if (size == arr.size) {\n val bigger = Array.ofDim[Int](2 * size + 1)\n arr.copyToArray(bigger)\n arr = bigger\n }\n arr(size) = x\n size += 1\n }\n @inline def get = arr.view(0, size).toArray\n }\n}\n\n"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.util.Sorting\nimport scala.collection.mutable.ArrayBuffer\nimport scala.reflect.ClassTag\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val left = scala.collection.mutable.Map.empty[Int, Growable[Int]]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (l != r) {\n if (!left.contains(r)) left += r -> new Growable[Int](Array.empty)\n left(r) += l\n if (!left.contains(l)) left += l -> new Growable[Int](Array.empty)\n left(l) += r\n }\n }\n\n for (a <- left.keys) {\n val sorted = left(a)()\n Sorting.quickSort(sorted)\n val middle = (sorted.size - 1) / 2\n val med = sorted(middle)\n var news = 0L\n var old = 0L\n for (l <- sorted) {\n news += math.abs(l - med)\n old += math.abs(l - a)\n }\n //println(med, old, news)\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n\n println(moves - canSave1)\n}\n\n@specialized(Int)\nclass Growable[T](private var arr: Array[T]) {\n var size = arr.size\n @inline def apply(index: Int): T = arr(index)\n @inline def +=(x: T)(implicit t: ClassTag[T]): Unit = {\n if (size == arr.size) {\n val bigger = Array.ofDim[T](2 * size + 1)\n arr.copyToArray(bigger)\n arr = bigger\n }\n arr(size) = x\n size += 1\n }\n @inline def apply() = arr.take(size)\n} \n"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.util.Sorting\nimport scala.collection.mutable.ArrayBuffer\nimport scala.reflect.ClassTag\nimport scala.collection.mutable.ArrayBuilder\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val neighbours = scala.collection.mutable.Map.empty[Int, ArrayBuilder[Int]]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (l != r) {\n if (!neighbours.contains(r)) neighbours += r -> new ArrayBuilder.ofInt\n neighbours(r) += l\n if (!neighbours.contains(l)) neighbours += l -> new ArrayBuilder.ofInt\n neighbours(l) += r\n }\n }\n\n for (a <- neighbours.keys) {\n val sorted = neighbours(a).result.sorted\n //Sorting.quickSort(sorted)\n val middle = (sorted.size - 1) / 2\n val med = sorted(middle)\n var news = 0L\n var old = 0L\n for (x <- sorted) {\n news += math.abs(x - med)\n old += math.abs(x - a)\n }\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n\n println(moves - canSave1)\n}"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.util.Sorting\nimport scala.collection.mutable.ArrayBuffer\nimport scala.reflect.ClassTag\nimport scala.collection.mutable.ArrayBuilder\nimport java.util.Arrays\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val neighbours = scala.collection.mutable.Map.empty[Int, ArrayBuilder[Int]]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (l != r) {\n if (!neighbours.contains(r)) neighbours += r -> new ArrayBuilder.ofInt\n neighbours(r) += l\n if (!neighbours.contains(l)) neighbours += l -> new ArrayBuilder.ofInt\n neighbours(l) += r\n }\n }\n\n for (a <- neighbours.keys) {\n val sorted = neighbours(a).result\n //Sorting.quickSort(sorted)\n Arrays.sort(sorted)\n val middle = (sorted.size - 1) / 2\n val med = sorted(middle)\n var news = 0L\n var old = 0L\n for (x <- sorted) {\n news += math.abs(x - med)\n old += math.abs(x - a)\n }\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n\n println(moves - canSave1)\n}"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.util.Sorting\nimport scala.collection.mutable.ArrayBuffer\nimport scala.reflect.ClassTag\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val left = scala.collection.mutable.Map.empty[Int, Growable]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (l != r) {\n if (!left.contains(r)) left += r -> new Growable()\n left(r) += l\n if (!left.contains(l)) left += l -> new Growable()\n left(l) += r\n }\n }\n\n for (a <- left.keys) {\n val sorted = left(a).get\n Sorting.quickSort(sorted)\n val middle = (sorted.size - 1) / 2\n val med = sorted(middle)\n var news = 0L\n var old = 0L\n for (l <- sorted) {\n news += math.abs(l - med)\n old += math.abs(l - a)\n }\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n\n println(moves - canSave1)\n\n type Nums = Int\n class Growable(private var arr: Array[Nums] = Array.empty[Nums]) {\n var size = arr.size\n @inline def apply(index: Int): Nums = arr(index)\n @inline def +=(x: Nums): Unit = {\n if (size == arr.size) {\n val bigger = Array.ofDim[Int](2 * size + 1)\n arr.copyToArray(bigger)\n arr = bigger\n }\n arr(size) = x\n size += 1\n }\n @inline def get = arr.take(size)\n }\n}\n\n"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.util.Sorting\nimport scala.collection.mutable.ArrayBuffer\nimport scala.reflect.ClassTag\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val left = scala.collection.mutable.Map.empty[Int, Growable]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (l != r) {\n if (!left.contains(r)) left += r -> new Growable()\n left(r) += l\n if (!left.contains(l)) left += l -> new Growable()\n left(l) += r\n }\n }\n\n for (a <- left.keys) {\n val sorted = left(a)()\n Sorting.quickSort(sorted)\n val middle = (sorted.size - 1) / 2\n val med = sorted(middle)\n var news = 0L\n var old = 0L\n for (l <- sorted) {\n news += math.abs(l - med)\n old += math.abs(l - a)\n }\n //println(med, old, news)\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n\n println(moves - canSave1)\n}\n\nclass Growable(private var arr: Array[Int] = Array.empty[Int]) {\n var size = arr.size\n @inline def apply(index: Int) = arr(index)\n @inline def +=(x: Int): Unit = {\n if (size == arr.size) {\n val bigger = Array.ofDim[Int](2 * size + 1)\n arr.copyToArray(bigger)\n arr = bigger\n }\n arr(size) = x\n size += 1\n }\n @inline def apply() = arr.take(size)\n} \n"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.util.Sorting\nimport scala.collection.mutable.ArrayBuffer\nimport scala.reflect.ClassTag\nimport scala.collection.mutable.ArrayBuilder\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val left = scala.collection.mutable.Map.empty[Int, ArrayBuilder[Int]]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (l != r) {\n if (!left.contains(r)) left += r -> new ArrayBuilder.ofInt\n left(r) += l\n if (!left.contains(l)) left += l -> new ArrayBuilder.ofInt\n left(l) += r\n }\n }\n\n for (a <- left.keys) {\n val sorted = left(a).result\n Sorting.quickSort(sorted)\n val middle = (sorted.size - 1) / 2\n val med = sorted(middle)\n var news = 0L\n var old = 0L\n for (l <- sorted) {\n news += math.abs(l - med)\n old += math.abs(l - a)\n }\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n\n println(moves - canSave1)\n\n type Nums = Int\n class Growable(private var arr: Array[Nums] = Array.empty[Nums]) {\n var size = arr.size\n @inline def apply(index: Int): Nums = arr(index)\n @inline def +=(x: Nums): Unit = {\n if (size == arr.size) {\n val bigger = Array.ofDim[Int](2 * size + 1)\n arr.copyToArray(bigger)\n arr = bigger\n }\n arr(size) = x\n size += 1\n }\n @inline def get = {\n val newelems = new Array[Nums](size)\n if (this.size > 0) Array.copy(arr, 0, newelems, 0, size)\n newelems\n }\n }\n}\n\n"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.util.Sorting\nimport scala.collection.mutable.ArrayBuffer\nimport scala.reflect.ClassTag\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val left = scala.collection.mutable.Map.empty[Int, Growable]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (l != r) {\n if (!left.contains(r)) left += r -> new Growable()\n left(r) += l\n if (!left.contains(l)) left += l -> new Growable()\n left(l) += r\n }\n }\n\n for (a <- left.keys) {\n val sorted = left(a).get\n Sorting.quickSort(sorted)\n val middle = (sorted.size - 1) / 2\n val med = sorted(middle)\n var news = 0L\n var old = 0L\n for (l <- sorted) {\n news += math.abs(l - med)\n old += math.abs(l - a)\n }\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n\n println(moves - canSave1)\n\n type Nums = Int\n class Growable(private var arr: Array[Nums] = Array.empty[Nums]) {\n var size = arr.size\n @inline def apply(index: Int): Nums = arr(index)\n @inline def +=(x: Nums): Unit = {\n if (size == arr.size) {\n val bigger = Array.ofDim[Int](2 * size + 1)\n arr.copyToArray(bigger)\n arr = bigger\n }\n arr(size) = x\n size += 1\n }\n @inline def get = {\n val newelems = new Array[Nums](size)\n if (this.size > 0) Array.copy(arr, 0, newelems, 0, size)\n newelems\n }\n }\n}\n\n"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.util.Sorting\nimport scala.collection.mutable.ArrayBuffer\nimport scala.reflect.ClassTag\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val left = scala.collection.mutable.Map.empty[Int, Growable]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (l != r) {\n if (!left.contains(r)) left += r -> new Growable()\n left(r) += l\n if (!left.contains(l)) left += l -> new Growable()\n left(l) += r\n }\n }\n\n for (a <- left.keys) {\n val sorted = left(a)()\n Sorting.quickSort(sorted)\n val middle = (sorted.size - 1) / 2\n val med = sorted(middle)\n var news = 0L\n var old = 0L\n for (l <- sorted) {\n news += math.abs(l - med)\n old += math.abs(l - a)\n }\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n\n println(moves - canSave1)\n}\n\nclass Growable(private var arr: Array[Int] = Array.empty[Int]) {\n var size = arr.size\n @inline def apply(index: Int): Int = arr(index)\n @inline def +=(x: Int): Unit = {\n if (size == arr.size) {\n val bigger = Array.ofDim[Int](2 * size + 1)\n arr.copyToArray(bigger)\n arr = bigger\n }\n arr(size) = x\n size += 1\n }\n @inline def apply() = arr.take(size)\n} \n"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.util.Sorting\nimport scala.collection.mutable.ArrayBuffer\nimport scala.reflect.ClassTag\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val left = scala.collection.mutable.Map.empty[Int, Growable[Int]]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (l != r) {\n if (!left.contains(r)) left += r -> new Growable[Int](Array.empty)\n left(r) += l\n if (!left.contains(l)) left += l -> new Growable[Int](Array.empty)\n left(l) += r\n }\n }\n\n for (a <- left.keys) {\n val sorted = left(a)()\n Sorting.quickSort(sorted)\n val middle = (sorted.size - 1) / 2\n val med = sorted(middle)\n var news = 0L\n var old = 0L\n for (l <- sorted) {\n news += math.abs(l - med)\n old += math.abs(l - a)\n }\n //println(med, old, news)\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n\n println(moves - canSave1)\n}\n\nclass Growable[T](private var arr: Array[T]) {\n var size = arr.size\n def apply(index: Int): T = arr(index)\n def +=(x: T)(implicit t: ClassTag[T]): Unit = {\n if (size == arr.size) {\n val bigger = Array.ofDim[T](2 * size + 1)\n arr.copyToArray(bigger)\n arr = bigger\n }\n arr(size) = x\n size += 1\n }\n def apply() = arr.take(size)\n} \n"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.util.Sorting\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val left = scala.collection.mutable.Map.empty[Int, ArrayBuffer[Int]]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (l != r) {\n if (!left.contains(r)) left += r -> ArrayBuffer.empty[Int]\n left(r) += l\n if (!left.contains(l)) left += l -> ArrayBuffer.empty[Int]\n left(l) += r\n }\n }\n\n for (a <- left.keys) {\n val sorted = left(a).toArray//.sorted\n Sorting.quickSort(sorted)\n val middle = (sorted.size - 1) / 2\n val med = sorted(middle)\n var news = 0L\n var old = 0L\n for (l <- sorted) {\n news += math.abs(l - med)\n old += math.abs(l - a)\n }\n //println(med, old, news)\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n\n println(moves - canSave1)\n}"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.util.Sorting\nimport scala.collection.mutable.ArrayBuffer\nimport scala.reflect.ClassTag\nimport scala.collection.mutable.ArrayBuilder\nimport java.util.Arrays\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val neighbours = scala.collection.mutable.Map.empty[Int, ArrayBuilder[Int]]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (l != r) {\n if (!neighbours.contains(r)) neighbours += r -> new ArrayBuilder.ofInt\n neighbours(r) += l\n if (!neighbours.contains(l)) neighbours += l -> new ArrayBuilder.ofInt\n neighbours(l) += r\n }\n }\n\n for (a <- neighbours.keys) {\n val sorted = neighbours(a).result\n Sorting.quickSort(sorted)\n val middle = (sorted.size - 1) / 2\n val med = sorted(middle)\n var news = 0L\n var old = 0L\n for (x <- sorted) {\n news += math.abs(x - med)\n old += math.abs(x - a)\n }\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n\n println(moves - canSave1)\n}"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.util.Sorting\nimport scala.collection.mutable.ArrayBuffer\nimport scala.reflect.ClassTag\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val left = scala.collection.mutable.Map.empty[Int, Growable[Int]]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (l != r) {\n if (!left.contains(r)) left += r -> new Growable[Int](Array.empty)\n left(r) += l\n if (!left.contains(l)) left += l -> new Growable[Int](Array.empty)\n left(l) += r\n }\n }\n\n for (a <- left.keys) {\n val sorted = left(a)()\n Sorting.quickSort(sorted)\n val middle = (sorted.size - 1) / 2\n val med = sorted(middle)\n var news = 0L\n var old = 0L\n for (l <- sorted) {\n news += math.abs(l - med)\n old += math.abs(l - a)\n }\n //println(med, old, news)\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n\n println(moves - canSave1)\n}\n\nclass Growable[T](private var arr: Array[T]) {\n var size = arr.size\n @inline def apply(index: Int): T = arr(index)\n @inline def +=(x: T)(implicit t: ClassTag[T]): Unit = {\n if (size == arr.size) {\n val bigger = Array.ofDim[T](2 * size + 1)\n arr.copyToArray(bigger)\n arr = bigger\n }\n arr(size) = x\n size += 1\n }\n @inline def apply() = arr.take(size)\n} \n"}], "negative_code": [{"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, m) = readInts(2)\n \n val as = readLongs(m)\n \n var moves = 0L\n var canSave1 = 0L\n var canSave2 = 0L\n var canSave3 = 0L\n \n if (m > 1) {\n canSave2 = math.abs(as(0) - as(1))\n canSave3 = math.abs(as(m - 1) - as(m - 2))\n }\n \n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n if (i < m - 1) {\n val save1 = math.abs(as(i) - as(i - 1)) + math.abs(as(i) - as(i + 1)) - math.abs(as(i + 1) - as(i - 1))\n if (save1 > canSave1) canSave1 = save1\n }\n }\n\n println(moves - (canSave1 max canSave2 max canSave3))\n}"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val left = mutable.Map.empty[Int, Map[Int, Int]]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (left.contains(r)) {\n left(r) += (l -> (left(r)(l) + 1))\n } else left += (r -> mutable.Map(l -> 1).withDefaultValue(0))\n if (left.contains(l)) {\n left(l) += (r -> (left(l)(r) + 1))\n } else left += (l -> mutable.Map(r -> 1).withDefaultValue(0))\n cnt(l) += 1\n cnt(r) += 1\n }\n\n for (a <- as.distinct) {\n if (left.contains(a)) {\n val middle = (cnt(a) - 1) / 2\n var sum = 0L\n var med = 0L\n //var i = 0\n var neighbours = left(a).toSeq.sortBy(_._1)\n while (sum <= middle) {\n med = neighbours.head._1 \n sum += neighbours.head._2\n //i += 1\n neighbours = neighbours.tail\n }\n //println(middle, sum)\n var news = 0L\n var old = 0L\n for (l <- left(a).keys) {\n news += math.abs(l - med) * left(a)(l)\n old += math.abs(l - a) * left(a)(l)\n }\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n }\n\n println(moves - canSave1)\n}"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, m) = readInts(2)\n \n val as = readInts(m)\n \n var moves = 0L\n var canSave1 = 0L\n var canSave2 = 0L\n var canSave3 = 0L\n \n val left = mutable.Map.empty[Int, Map[Int, Int]] \n val right = mutable.Map.empty[Int, Map[Int, Int]] \n \n if (m > 1) {\n canSave2 = math.abs(as(0) - as(1))\n canSave3 = math.abs(as(m - 1) - as(m - 2))\n }\n \n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (right.contains(l)) {\n right(l) += (r -> (right(l)(r) + 1))\n } else right += (l -> mutable.Map(r -> 1).withDefaultValue(0))\n if (left.contains(r)) {\n left(r) += (l -> (left(r)(l) + 1))\n } else left += (r -> mutable.Map(l -> 1).withDefaultValue(0))\n }\n\n for (a <- as) {\n val neighbours = mutable.ArrayBuffer[Int]()\n if (right.contains(a)) for (r <- right(a).keys) {\n for (cnt <- 1 to right(a)(r)) neighbours += r\n }\n if (left.contains(a)) for (l <- left(a).keys) {\n for (cnt <- 1 to left(a)(l)) neighbours += l\n }\n if (neighbours.nonEmpty) {\n val sorted = neighbours.sorted\n val med: Long = sorted((sorted.size - 1) / 2)\n val news = neighbours.map(x => math.abs(x - med)).sum\n val old = neighbours.map(x => math.abs(a - med)).sum\n // println(a, news, old)\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n }\n \n println(moves - canSave1)\n}"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val left = mutable.Map.empty[Int, Map[Int, Int]]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (left.contains(r)) {\n left(r) += (l -> (left(r)(l) + 1))\n } else left += (r -> mutable.Map(l -> 1).withDefaultValue(0))\n if (left.contains(l)) {\n left(l) += (r -> (left(l)(r) + 1))\n } else left += (l -> mutable.Map(r -> 1).withDefaultValue(0))\n cnt(l) += 1\n cnt(r) += 1\n }\n\n for (a <- as.distinct) {\n if (left.contains(a)) {\n val middle = (cnt(a) - 1) / 2\n var sum = 0\n var med = 0\n //var i = 0\n var neighbours = left(a).toSeq.sortBy(_._1)\n while (sum <= middle) {\n med = neighbours.head._1 \n sum += neighbours.head._2\n //i += 1\n neighbours = neighbours.tail\n }\n //println(middle, sum)\n var news = 0L\n var old = 0L\n for (l <- left(a).keys) {\n val mult = left(a)(l).toLong\n news += math.abs(l - med) * mult\n old += math.abs(l - a) * mult\n }\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n }\n\n println(moves - canSave1)\n}"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n var canSave2 = 0L\n var canSave3 = 0L\n\n val left = mutable.Map.empty[Int, Map[Int, Int]]\n val right = mutable.Map.empty[Int, Map[Int, Int]]\n var cnt = Array.fill(n + 1)(0)\n\n if (m > 1) {\n canSave2 = math.abs(as(0) - as(1))\n canSave3 = math.abs(as(m - 1) - as(m - 2))\n }\n\n cnt(as(0)) += 1\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (right.contains(l)) {\n right(l) += (r -> (right(l)(r) + 1))\n } else right += (l -> mutable.Map(r -> 1).withDefaultValue(0))\n if (left.contains(r)) {\n left(r) += (l -> (left(r)(l) + 1))\n } else left += (r -> mutable.Map(l -> 1).withDefaultValue(0))\n //cnt(as(i)) += 1\n }\n\n for (a <- as.distinct) {\n //val neighbours = new mutable.ArrayBuffer[Int](2 * cnt(a))\n var sum = 0L\n var count = 0\n if (right.contains(a)) for (r <- right(a).keys) {\n //for (cnt <- 1 to right(a)(r)) neighbours += r\n sum += r * right(a)(r)\n count += right(a)(r)\n }\n if (left.contains(a)) for (l <- left(a).keys) {\n //for (cnt <- 1 to left(a)(l)) neighbours += l\n sum += l * left(a)(l)\n count += left(a)(l)\n }\n if (count > 0) {\n //val sorted = neighbours.sorted\n //val med = sorted((sorted.size - 1) / 2)\n //val med: Long = neighbours.sum / neighbours.size\n val med: Long = sum / count\n var news = 0L\n var old = 0L\n if (right.contains(a)) for (r <- right(a).keys) {\n news += math.abs(r - med) * right(a)(r)\n old += math.abs(r - a) * right(a)(r)\n }\n if (left.contains(a)) for (l <- left(a).keys) {\n news += math.abs(l - med) * left(a)(l)\n old += math.abs(l - a) * left(a)(l)\n }\n /* for (x <- neighbours) {\n news += math.abs(x - med)\n old += math.abs(x - a)\n }*/\n //println(a, med, news, old)\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n }\n\n println(moves - canSave1)\n}"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.util.Sorting\nimport scala.collection.mutable.ArrayBuffer\nimport scala.reflect.ClassTag\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val as = readInts(m)\n\n var moves = 0L\n var canSave1 = 0L\n\n val left = scala.collection.mutable.Map.empty[Int, Growable[Int]]\n var cnt = Array.fill(n + 1)(0)\n\n for (i <- 1 until m) {\n moves += math.abs(as(i) - as(i - 1))\n val l = as(i - 1)\n val r = as(i)\n if (l != r) {\n if (!left.contains(r)) left += r -> new Growable[Int](Array.empty)\n left(r) += l\n if (!left.contains(l)) left += l -> new Growable[Int](Array.empty)\n left(l) += r\n }\n }\n\n for (a <- left.keys) {\n val sorted = left(a).arr\n Sorting.quickSort(sorted)\n val middle = (sorted.size - 1) / 2\n val med = sorted(middle)\n var news = 0L\n var old = 0L\n for (l <- sorted) {\n news += math.abs(l - med)\n old += math.abs(l - a)\n }\n //println(med, old, news)\n val save = math.abs(news - old)\n if (save > canSave1) canSave1 = save\n }\n\n println(moves - canSave1)\n}\n\nclass Growable[T](var arr: Array[T]) {\n var size = arr.size\n def apply(index: Int): T = arr(index)\n def +=(x: T)(implicit t: ClassTag[T]): Unit = {\n if (size == arr.size) {\n val bigger = Array.ofDim[T](2 * size + 1)\n arr.copyToArray(bigger)\n arr = bigger\n }\n arr(size) = x\n size += 1\n }\n} \n\n"}], "src_uid": "871674fbb434121f41539c9f094432ac"} {"source_code": "import scala.collection._\n\nobject B extends App {\n\n val n = readInt\n val sb = new StringBuilder(\"<3\")\n \n for (i <- 1 to n) {\n sb.append(readLine)\n sb.append(\"<3\")\n }\n val text = sb.toString\n\n val sms = readLine\n \n var i, j = 0\n while (i < text.length && j < sms.length) {\n if (text(i) == sms(j)) i += 1 \n j += 1\n }\n\n println(if (i == text.length) \"yes\" else \"no\")\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val n=readLine().toInt\n var s:StringBuilder=new StringBuilder()\n s++=\"<3\"\n for (i<-1 to n)\n s++=readLine()++=\"<3\"\n val r=readLine()\n var j=0\n for (i<-0 until r.length)\n if (j!=s.length && s(j)==r(i))\n j+=1\n // println(s.length + \" \"+j)\n println(if (s.length==j) \"yes\" else \"no\")\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n=readLine().toInt\n var s:StringBuilder=new StringBuilder()\n s++=\"<3\"\n for (i<-1 to n)\n s++=readLine()++=\"<3\"\n val r=readLine()\n var j=0\n for (i<-0 until r.length)\n if (j!=s.length && s(j)==r(i))\n j+=1\n // println(s.length + \" \"+j)\n println(if (s.length<=j) \"yes\" else \"no\")\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = (\"\" :: (1 to n).map(_ => in.next()).toList).map(_ + \"<3\")\n\n val res = in.next().foldLeft(data.head.toList, data.tail) {\n case ((x::xs, left), ch) if x == ch =>\n if (xs.isEmpty && left.isEmpty)\n (Nil, left)\n else if (xs.isEmpty)\n (left.head.toList, left.tail)\n else (xs, left)\n case (acc, el) => acc\n }\n\n if (res._1.isEmpty && res._2.isEmpty)\n println(\"yes\")\n else\n println(\"no\")\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = for(_ <- 1 to n) yield(readLine())\n val e = a.mkString(\"<3\", \"<3\", \"<3\")\n var i = 0\n for(c <- readLine()) {\n if(i != e.size && c == e(i)) i += 1\n }\n if (i == e.size) println(\"yes\")\n else println(\"no\")\n } \n}"}, {"source_code": "import java.util.Scanner\n\n/**\t#208\n * \tB. Dima and Text Messages\n */\n\nobject DimaandTextMessages extends App {\n val cin = new Scanner(System.in)\n \n val inMessage = new StringBuilder\n inMessage.append(\"<3\")\n \n val n = cin.nextInt\n (0 until n).foreach(i => inMessage.append(cin.next).append(\"<3\"))\n\n val message = inMessage.toString\n val encodedMessage = cin.next\n \n var index = 0\n (0 until encodedMessage.length).foreach { i =>\n if (index + 1 <= message.length && message(index) == encodedMessage(i))\n index += 1\n }\n \n println(if (index == message.length) \"yes\" else \"no\")\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = (\"\" :: (1 to n).map(_ => in.next()).toList).map(_ + \"<3\")\n\n val res = in.next().foldLeft(data.head.toList, data.tail) {\n case ((x::xs, left), ch) if x == ch =>\n if (xs.isEmpty && left.isEmpty)\n (Nil, left)\n else if (xs.isEmpty)\n (left.head.toList, left.tail)\n else (xs, left)\n case (acc, el) => acc\n }\n\n if (res._1.isEmpty && res._2.isEmpty)\n println(\"YES\")\n else\n println(\"NO\")\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n val n = readInt\n val sb = new StringBuilder(\"<3\")\n \n for (i <- 1 to n) sb.append(readLine)\n val text = sb.toString\n \n val sms = readLine\n \n var i, j = 0\n while (i < text.length && j < sms.length) {\n if (text(i) == sms(j)) i += 1 \n j += 1\n }\n\n println(if (i == text.length) \"yes\" else \"no\")\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = for(_ <- 1 to n) yield(readLine())\n val e = a.mkString(\"<3\", \"<3\", \"<3\")\n var i = 0\n for(c <- readLine()) {\n if(i != e.size || c == e(i)) i += 0\n }\n if (i == e.size) println(\"yes\")\n else println(\"no\")\n } \n}"}, {"source_code": "import java.util.Scanner\n\n/**\t#208\n * \tB. Dima and Text Messages\n */\n\nobject DimaandTextMessages extends App {\n val cin = new Scanner(System.in)\n \n val inMessage = new StringBuilder\n inMessage.append(\"<3\")\n \n val n = cin.nextInt\n (0 until n).foreach(i => inMessage.append(cin.nextLine).append(\"<3\"))\n\n val message = inMessage.toString\n val encodedMessage = cin.next\n \n var index = 0\n (0 until encodedMessage.length).foreach { i =>\n if (index + 1 < message.length && message(index) == encodedMessage(i))\n index += 1\n }\n \n println(if (index == message.length) \"yes\" else \"no\")\n}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\n\nobject Solver extends App {\n val cin = new Scanner(System.in)\n \n val n = cin.nextInt\n \n val wordsBuffer = ArrayBuffer[String]()\n for (i <- 0 until n) wordsBuffer += cin.next\n \n val words = wordsBuffer.toSeq\n val message = cin.next.replaceAll(\"[012456789]\", \"\").replaceAll(\">\", \"\").replaceAll(\"<3\", \" \").trim\n \n var ok = true\n for (i <- 0 until message.length - 1)\n if (message(i) == ' ' && message(i + 1) == ' ')\n ok = false\n \n val messageWords = message.split(\" \").toSeq\n ok &= messageWords.length == n\n \n if (!ok) {\n println(\"no\")\n exit(0)\n }\n \n val both = words.zip(messageWords)\n ok &= both.forall(pair => pair._1 == pair._2)\n \n println(if (ok) \"yes\" else \"no\")\n}"}], "src_uid": "36fb3a01860ef0cc2a1065d78e4efbd5"} {"source_code": "import scala.math._, scala.collection._, scala.io.StdIn._\n\nobject D2 extends App {\n val n = readInt\n val a = readInts\n val m = readInt\n\n val top = a.zipWithIndex sortBy { case (x,i) => (-x,i) }\n\n val r = top.scanLeft(SortedSet.empty[Int]) {\n case (r, (x,i)) => r + i\n }\n\n for (_ <- 1 to m) {\n val Array(k,pos) = readInts\n println(a(r(k).slice(pos-1,pos).firstKey))\n }\n\n def readInt() = readLine.toInt\n def readInts() = readLine.split(\" \").map(_.toInt)\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n case class Entry(a: Int, i: Int)\n case class Query(k: Int, pos: Int, m: Int)\n\n class BIT(n: Int, zero: Int)(f: (Int, Int) => Int) {\n def this(n: Int) = this(n, 0)(_ + _)\n\n private val N = {\n val a = Integer.highestOneBit(n)\n if (a == n) a else a << 1\n }\n private val bit = if (zero != 0) Array.fill[Int](N + 1)(zero) else Array.ofDim[Int](N + 1)\n\n /**\n * 1 index\n * addとindex違うよ\n * cumsumなんかといっしょ\n */\n def sum(i: Int): Int = {\n assert(i <= n)\n var x = i\n var s: Int = zero\n while(x > 0) {\n s = f(s, bit(x))\n x -= x & -x\n }\n s\n }\n\n /**\n * 0 index\n */\n def add(i: Int, a: Int): Unit = {\n assert(i < n)\n var x = i + 1\n while(x <= N) {\n bit(x) = f(bit(x), a)\n x += x & -x\n }\n }\n\n def sumAll: Int = sum(n)\n\n // A がLongとかじゃない場合はこれらを実装しないと下の奴らが使えない\n private def sub(a: Int, b: Int) = a - b\n private def lt(a: Int, b: Int) = a < b\n\n /**\n * [l, r)\n */\n def query(l: Int, r: Int): Int = {\n assert(r > l)\n sub(sum(r), sum(l))\n }\n\n def lowerBound(W: Int): Int = {\n var k = N\n var x = 0\n var w = W\n while(k > 0) {\n if (x + k <= N && lt(bit(x + k), w)) {\n w = sub(w, bit(x + k))\n x += k\n }\n k /= 2\n }\n math.min(n, x)\n }\n}\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n import java.util.Comparator\n val N = ni()\n val A = na(N)\n val E = Array.ofDim[Entry](N)\n REP(N) { i =>\n E(i) = Entry(A(i), i)\n }\n sort(E, new Comparator[Entry] {\n override def compare(o1: Entry, o2: Entry): Int = {\n if (o1.a == o2.a) Integer.compare(o1.i, o2.i)\n else Integer.compare(o2.a, o1.a) // 降順\n }\n })\n val M = ni()\n val queried = Array.fill[ArrayBuffer[Query]](N)(ArrayBuffer())\n val ans = Array.ofDim[Int](M)\n REP(M) { m =>\n val k, pos = ni()\n val q = Query(k, pos, m)\n queried(k - 1) += q\n }\n\n val bit = new BIT(N)\n REP(N) { i =>\n bit.add(E(i).i, 1)\n queried(i).foreach { q =>\n val ix = bit.lowerBound(q.pos)\n ans(q.m) = A(ix)\n }\n }\n\n REP(M) { i =>\n out.println(ans(i))\n }\n }\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject B {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n = nextInt\n val as = nextInts(n)\n val sorted = as.zipWithIndex.sortBy {\n case (x, i) => (x, -i)\n }\n val order = Array.ofDim[Int](n)\n for (i <- as.indices) {\n order(sorted(i)._2) = i\n }\n\n val m = nextInt\n val res = new ArrayBuffer[Int]\n for (q <- 1 to m) {\n var k, pos = nextInt\n var i = 0\n while (pos > 0) {\n if (order(i) + k >= n) {\n pos -= 1\n if (pos == 0) res += as(i)\n }\n i += 1\n }\n }\n\n out.println(res.mkString(\"\\n\"))\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "1e56f4d17c4ad0b5dde7f05b4e362cfc"} {"source_code": "import scala.io.StdIn._\r\nimport scala.collection.immutable._\r\nimport scala.annotation.tailrec\r\nobject test{\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt\r\n \r\n while(t > 0) {\r\n val m = readLine.split(\" \").map(_.toInt).toList\r\n if(m(0).min(m(1)) > m(2).max(m(3)) || m(2).min(m(3)) > m(0).max(m(1)))\r\n println(\"NO\")\r\n else\r\n println(\"YES\")\r\n \r\n t -= 1\r\n }\r\n }\r\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\r\nimport scala.collection.immutable._\r\nimport scala.annotation.tailrec\r\nobject test{\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt\r\n \r\n while(t > 0) {\r\n val m = readLine.split(\" \").map(_.toInt).toList\r\n if(m(0).min(m(1)) > m(2).max(m(3)) || m(2).min(m(3)) > m(0).max(m(1)))\r\n println(\"NO\")\r\n else\r\n println(\"YES\")\r\n \r\n t -= 1\r\n }\r\n }\r\n}"}, {"source_code": "import scala.io.StdIn._\r\n\r\nobject A extends App {\r\n for (_ <- 0 until readInt) {\r\n val s @ Array(s1, s2, s3, s4) = readLine.split(\" \").map(_.toInt)\r\n if (s.sortBy(-_).take(2).toSet == Set(s1.max(s2), s3.max(s4)))\r\n println(\"YES\")\r\n else\r\n println(\"NO\")\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "cb24509580ff9b2f1a11103a0e4cdcbd"} {"source_code": "import scala.collection.mutable\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n val xs = Array.fill(n)(false)\n\n var i = 0\n var day = 0\n\n while (i < n) {\n day += 1\n val pending = mutable.Set.empty[Int]\n do {\n pending += (as(i) - 1)\n pending -= i\n i += 1\n } while (pending.nonEmpty)\n }\n\n println(day)\n\n Console.flush\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n import java.util.Arrays\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N, -1)\n var ans = 0\n var p = 0\n var mys = 0\n while(p < N) {\n mys = A(p)\n while(mys > p) {\n p += 1\n mys = max(mys, A(p))\n }\n debug(s\"p:$p mys:$mys\")\n ans += 1\n p += 1\n }\n out.println(ans)\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}, {"source_code": "object Foo extends App {\n val Array(n) = readints\n val a = readints\n\n var r, days = 0\n for (i <- 0 until n) {\n if (a(i) > r)\n r = a(i)\n if (r == i + 1)\n days += 1\n }\n\n println(days)\n\n import scala.io.StdIn.readLine\n def readints() = readLine.split(\" \").map(_.toInt)\n}\n"}], "negative_code": [], "src_uid": "291601d6cdafa4113c1154f0dda3470d"} {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N, K = sc.nextInt()\n val s = sc.next()\n var t = \"\"\n\n def find: Option[Int] = {\n rep_r(min(t.length, s.length)) { j =>\n if (s.substring(0, j) == t.substring(t.length - j)) return Some(j)\n }\n None\n }\n\n rep(K) { _ =>\n find match {\n case Some(j) => t += s.substring(j)\n case None => t += s\n }\n }\n\n out.println(t)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}", "positive_code": [{"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N, K = sc.nextInt()\n val s = sc.next()\n var t = \"\"\n\n def find: Option[Int] = {\n rep_r(min(t.length, s.length)) { j =>\n if (s.substring(0, j) == t.substring(t.length - j)) return Some(j)\n }\n None\n }\n\n rep(K) { _ =>\n find match {\n case Some(j) => t += s.substring(j)\n case None => t += s\n }\n }\n\n out.println(t)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "object CF506A extends App {\n import scala.io.StdIn\n val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)\n val t = StdIn.readLine\n\n var sameCount = (0 to n/2).filter(x => t.take(x) == t.takeRight(x)).last\n var s = t.dropRight(sameCount) * k + t.takeRight(sameCount)\n val lastStart = s.sliding(n).zipWithIndex.filter(_._1 == t).toList(k-1)._2\n s = s.take(lastStart + n)\n println(s)\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject A extends App {\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val k = in.nextInt\n val s = in.next\n\n var maxLen = 0\n\n for (i <- 1 until n) {\n if (s.take(i) == s.takeRight(i)) {\n maxLen = i\n }\n }\n\n val suffix = s.drop(maxLen)\n print(s)\n for (_ <- 1 until k) {\n print(suffix)\n }\n println()\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject A extends App {\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val k = in.nextInt\n val s = in.next\n val t = (0 until n).find { i =>\n s.substring(0, n - i - 1) == s.substring(i + 1)\n }.get\n print(s)\n (1 until k).foreach { _ =>\n print(s.substring(n - t - 1))\n }\n println\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toInt\n }\n\n def nextLong: Double = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}], "negative_code": [{"source_code": "object CF506A extends App {\n import scala.io.StdIn\n val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)\n val t = StdIn.readLine\n\n val sameCount = t.take(n/2).zipWithIndex.takeWhile(x => t.charAt(n-1-x._2) == x._1).length\n println(t.dropRight(sameCount) * k + t.takeRight(sameCount))\n}\n"}, {"source_code": "object CF506A extends App {\n import scala.io.StdIn\n val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)\n val t = StdIn.readLine\n\n var sameCount = (0 to n/2).filter(x => t.take(x) == t.takeRight(x)).last\n\n if (sameCount == n/2 && t.forall(_ == t.head)) {\n // All chars the same\n sameCount = n - 1\n }\n println(t.dropRight(sameCount) * k + t.takeRight(sameCount))\n}\n"}, {"source_code": "object CF506A extends App {\n import scala.io.StdIn\n val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)\n val t = StdIn.readLine\n\n var sameCount = t.take(n/2).zipWithIndex.takeWhile(x => t.charAt(n-1-x._2) == x._1).length\n if (sameCount == n/2 && n > 1 && t.charAt(n/2) == t.charAt(n/2-1)) {\n // All chars the same\n sameCount = n - 1\n }\n println(t.dropRight(sameCount) * k + t.takeRight(sameCount))\n}\n"}], "src_uid": "34dd4c8400ff7a67f9feb1487f2669a6"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(val a: Int, val b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return -1 * a.compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n\n\n for (tt <- 1 to t) {\n var s = readString()\n var cnt = 0\n for (c <- s) {\n if (c == 'N')\n cnt += 1\n }\n if (cnt == 1) {\n writer.println(\"NO\")\n } else {\n writer.println(\"YES\")\n }\n\n def check(kk: Long): Boolean = {\n return false\n }\n def bs(st:Long, en:Long): Long = {\n if (en - st <= 1L) {\n if (check(st))\n return st\n else\n return en\n }\n val mid = (st + en) / 2L\n if (check(mid))\n return bs(st, mid)\n else\n return bs(mid, en)\n }\n }\n writer.flush()\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n val nums = readInt()\n for (i <- 0 until nums) {\n val row = readLine()\n if (row.count(_=='N') == 1) {\n println(\"NO\")\n }\n else {\n println(\"YES\")\n }\n }\n}\n"}], "negative_code": [], "src_uid": "e744184150bf55a30568060cca69de04"} {"source_code": "object A {\n def main(args: Array[String]) {\n var n = scala.io.StdIn.readInt();\n var bs = Array.ofDim[Int](4, n, n);\n //println(bs(0)(1).getClass.toString())\n for(b <- 0 until 4){\n for(i <- 0 until n){\n bs(b)(i) = scala.io.StdIn.readLine().split(\"\").map( _.toInt );\n }\n scala.io.StdIn.readLine();\n }\n \n val ps = List(0, 1, 2, 3).permutations\n var ans = n * n * 4;\n for(p <- ps){\n val t = cost(bs, p);\n ans = math.min(ans, t);\n }\n \n println(ans);\n }\n \n def cost(bs: Array[Array[Array[Int]]], p: List[Int]): Int = {\n //println(bs.size)\n //println(p)\n var same = 0;\n var diff = 0;\n val n = bs(0).size;\n for(b <- 0 until 4){\n for(i <- 0 until n){\n for(j <- 0 until n){\n if(bs(p(b))(i)(j) == (i + j + (b % 2)) % 2) same += 1;\n else diff += 1;\n }\n }\n }\n return math.min(same, diff);\n }\n}", "positive_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val r = new Reader()\n val n = r.read[Int]\n val b1, b2, b3, b4 = r.read[List[String]](n).mkString\n val n2 = n * n\n val sb = (\"10\" * n2).take(n2)\n val sw = (\"01\" * n2).take(n2)\n \n def m(s1: String, s2: String) =\n s1.zip(s2).foldLeft(0) {\n case (acc, (c, d)) => if (c == d) acc else acc + 1\n }\n \n val mb1 = m(b1, sb)\n val mb2 = m(b2, sb)\n val mb3 = m(b3, sb)\n val mb4 = m(b4, sb)\n \n val mw1 = m(b1, sw)\n val mw2 = m(b2, sw)\n val mw3 = m(b3, sw)\n val mw4 = m(b4, sw)\n\n println(List(mb1 + mb2 + mw3 + mw4,\n mb1 + mw2 + mb3 + mw4,\n mb1 + mw2 + mw3 + mb4,\n mw1 + mb2 + mb3 + mw4,\n mw1 + mb2 + mw3 + mb4,\n mw1 + mw2 + mb3 + mb4).min)\n }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def this() = this(new InputStreamReader(System.in))\n\n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n\n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n implicit val double: Read[Double] = new Read(_.read[String].toDouble)\n \n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n \n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != \"\").map(new StringTokenizer(_)).buffered\n}"}], "negative_code": [], "src_uid": "dc46c6cb6b4b9b5e7e6e5b4b7d034874"} {"source_code": "object A560 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n).toSet\n if(input.contains(1)) {\n println(\"-1\")\n } else {\n println(\"1\")\n }\n }\n}", "positive_code": [{"source_code": "\n/**\n * \n *\n * @author pvasilyev\n * @since 10 Apr 2016\n */\nobject Problem148 extends App {\n\n private val n: Int = scala.io.StdIn.readInt()\n private var b: Boolean = false\n private val line: String = scala.io.StdIn.readLine()\n private val a: Array[Int] = line.split(\" \").map(_.toInt)\n for (i <- 0 until n) {\n val ai: Int = a(i)\n if (ai == 1) {\n b = true\n }\n }\n\n if (b) {\n println(-1)\n } else {\n println(1)\n }\n\n}\n"}, {"source_code": "import io.StdIn._\n\nobject Solution {\n def main(args: Array[String]) {\n readInt()\n val b = readLine().split(\" \")\n if (b.contains(\"1\")) println(-1)\n else print(1)\n }\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util.control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _560A extends CodeForcesApp[Int]({scanner => import scanner._\n val n = nextInt\n val notes = List.fill(n)(nextInt)\n if (notes contains 1) -1 else 1\n})\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final def isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[B](x: Boolean)(f: => B): Option[B] = if (x) Some(f) else None\n final def counter[A] = collection.mutable.Map.empty[A, Int] withDefaultValue 0\n}\n"}], "negative_code": [{"source_code": "object A560 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n).toSet\n if(input.contains(1)) {\n if(input.contains(2)) {\n println(\"-1\")\n } else {\n println(\"2\")\n }\n } else {\n println(\"1\")\n }\n }\n}"}], "src_uid": "df94080c5b0b046af2397cafc02b5bdc"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val R, C = ni()\n val g = nm_c(R, C)\n val rowL, rowR = Array.ofDim[Int](R, C + 2) // 1-indexed\n val colT, colB = Array.ofDim[Int](C, R + 2)\n REP(R) { r =>\n REP(C) { c =>\n if (g(r)(c) == '*') rowL(r)(c + 1) = rowL(r)(c) + 1\n }\n REP_r(C) { c =>\n if (g(r)(c) == '*') rowR(r)(c + 1) = rowR(r)(c + 2) + 1\n }\n }\n\n REP(C) { c =>\n REP(R) { r =>\n if (g(r)(c) == '*') colT(c)(r + 1) = colT(c)(r) + 1\n }\n REP_r(R) { r =>\n if (g(r)(c) == '*') colB(c)(r + 1) = colB(c)(r + 2) + 1\n }\n }\n\n var cntStars = 0\n val stars = Array.ofDim[Int](R, C) // 中心も含めた長さ\n REP(R) { r =>\n REP(C) { c =>\n if (g(r)(c) == '*') {\n val len = min(min(rowL(r)(c + 1), rowR(r)(c + 1)), min(colT(c)(r + 1), colB(c)(r + 1)))\n if (len > 1) {\n stars(r)(c) = len\n cntStars += 1\n }\n }\n }\n }\n\n val paint = Array.fill[Char](R, C)('.')\n\n type StepFn = (Int, Int) => Unit\n def paintIt(acc: StepFn => Unit) = {\n var cnt = 0\n def step(r: Int, c: Int) = {\n cnt = max(stars(r)(c), cnt - 1)\n if (cnt > 0) paint(r)(c) = '*'\n }\n\n acc(step)\n }\n\n REP(R) { r =>\n paintIt(step => REP(C)(c => step(r, c)))\n paintIt(step => REP_r(C)(c => step(r, c)))\n }\n REP(C) { c =>\n paintIt(step => REP(R)(r => step(r, c)))\n paintIt(step => REP_r(R)(r => step(r, c)))\n }\n\n var ok = true\n REP(R) { r =>\n REP(C) { c =>\n ok &&= g(r)(c) == paint(r)(c)\n }\n }\n\n if (!ok) out.println(-1)\n else {\n out.println(cntStars)\n REP(R) { r =>\n REP(C) { c =>\n if (stars(r)(c) > 0) out.println(s\"${r+1} ${c+1} ${stars(r)(c)-1}\")\n }\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val R, C = ni()\n val g = nm_c(R, C)\n val rowL, rowR = Array.ofDim[Int](R, C + 2) // 1-indexed\n val colT, colB = Array.ofDim[Int](C, R + 2)\n REP(R) { r =>\n REP(C) { c =>\n if (g(r)(c) == '*') rowL(r)(c + 1) = rowL(r)(c) + 1\n }\n REP_r(C) { c =>\n if (g(r)(c) == '*') rowR(r)(c + 1) = rowR(r)(c + 2) + 1\n }\n }\n\n REP(C) { c =>\n REP(R) { r =>\n if (g(r)(c) == '*') colT(c)(r + 1) = colT(c)(r) + 1\n }\n REP_r(R) { r =>\n if (g(r)(c) == '*') colB(c)(r + 1) = colB(c)(r + 2) + 1\n }\n }\n\n var cntStars = 0\n val stars = Array.ofDim[Int](R, C) // 中心も含めた長さ\n REP(R) { r =>\n REP(C) { c =>\n if (g(r)(c) == '*') {\n val len = min(min(rowL(r)(c + 1), rowR(r)(c + 1)), min(colT(c)(r + 1), colB(c)(r + 1)))\n if (len > 1) {\n stars(r)(c) = len\n cntStars += 1\n }\n }\n }\n }\n\n val paint = Array.fill[Char](R, C)('.')\n\n type StepFn = (Int, Int) => Unit\n def paintIt(acc: StepFn => Unit) = {\n var cnt = 0\n def step(r: Int, c: Int) = {\n cnt = max(stars(r)(c), cnt - 1)\n if (cnt > 0) paint(r)(c) = '*'\n }\n\n acc(step)\n }\n\n REP(R) { r =>\n paintIt(step => REP(C)(c => step(r, c)))\n paintIt(step => REP_r(C)(c => step(r, c)))\n }\n REP(C) { c =>\n paintIt(step => REP(R)(r => step(r, c)))\n paintIt(step => REP_r(R)(r => step(r, c)))\n }\n\n var ok = true\n REP(R) { r =>\n REP(C) { c =>\n ok &&= g(r)(c) == paint(r)(c)\n }\n }\n\n if (!ok) out.println(-1)\n else {\n out.println(cntStars)\n REP(R) { r =>\n REP(C) { c =>\n if (stars(r)(c) > 0) out.println(s\"${r+1} ${c+1} ${stars(r)(c)-1}\")\n }\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer\n\nobject CF501E extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n val n = in.nextInt\n val m = in.nextInt\n val grid = new Array[Array[Boolean]](n).map(_ => in.next.toCharArray.map(_ == '*'))\n\n var stars = new ListBuffer[(Int,Int,Int)]()\n\n for (x <- 1 until n-1;\n y <- 1 until m-1) {\n if (grid(x)(y)) {\n val maxSize = findMaxSize(x, y, 0)\n if (maxSize > 0)\n stars += ((x, y, maxSize))\n }\n }\n\n def findMaxSize(x: Int, y: Int, currentMax: Int): Int = {\n try {\n if (grid(x)(y-currentMax-1) && grid(x)(y+currentMax+1) && grid(x-currentMax-1)(y) && grid(x+currentMax+1)(y)) {\n return findMaxSize(x, y, currentMax + 1)\n } else {\n return currentMax\n }\n } catch {\n case _: ArrayIndexOutOfBoundsException => return currentMax\n }\n }\n\n val newGrid = Array.ofDim[Boolean](n, m)\n for (star <- stars) {\n val (x, y, size) = star\n newGrid(x)(y) = true\n for (i <- 1 to size) {\n newGrid(x+i)(y) = true\n newGrid(x-i)(y) = true\n newGrid(x)(y+i) = true\n newGrid(x)(y-i) = true\n }\n }\n\n if (grid.deep == newGrid.deep) {\n out.println(stars.length)\n out.println(stars.map(s => (s._1+1) + \" \" + (s._2+1) + \" \" + s._3).mkString(\"\\n\"))\n } else {\n out.println(\"-1\")\n }\n }\n\n solve\n out.flush\n out.close\n}"}], "negative_code": [], "src_uid": "59d4c66892fa3157d1163225a550a368"} {"source_code": "\nobject Main {\n def main (args: Array[String]) {\n val n=io.StdIn.readLine().toInt\n val v=io.StdIn.readLine().split(\" \").map(_.toInt)\n val s=Array.fill(n)(1)\n val t=Array.fill(n)(1)\n (1 until n).foreach(i=>if (v(i-1)if (v(i) {\n var cur = 1\n if (i > 0 && i < n-1 && v(i - 1) + 1 >= v(i + 1))\n cur += math.max(s(i - 1), t(i + 1))\n else{\n if (i>0) cur+=s(i-1)\n if (i+1 a(i - 1)) {\n l(i) = l(i - 1) + 1\n } else {\n l(i) = 1\n }\n max = math.max(max, l(i-1)+1)\n }\n val r: Array[Int] = Array.ofDim[Int](n)\n r(n - 1) = 1\n for (i <- (n - 2).to(0, -1)) {\n if (a(i) < a(i + 1)) {\n r(i) = r(i + 1) + 1\n } else {\n r(i) = 1\n }\n max = math.max(max, r(i+1)+1)\n }\n for (i <- 1 until n-1) {\n if (a(i - 1) + 1 < a(i + 1)) {\n max = math.max(max, l(i - 1) + 1 + r(i + 1))\n }\n }\n println(max)\n }\n\n solve()\n\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val res = data.indices.tail.foldLeft((0, List.empty[(Int, Int)])) {\n case (acc@(first, list), i) if data(i) > data(i - 1) => acc\n case ((first, list), i) => (i, (first, i - 1) :: list)\n }\n val ans: Array[(Int, Int)] = ((res._1, n - 1) :: res._2).reverse.toArray\n if (ans.length == 1)\n println(n)\n else {\n val max = ans.map(i => i._2 - i._1).max + 2\n val t = ans.indices.foldLeft(max) {\n case (m, i) if i == ans.length - 1 => m\n case (m, i) =>\n val (s1, e1) = ans(i)\n val (s2, e2) = ans(i + 1)\n if (s1 == e1 || s2 == e2)\n if (i == ans.length - 2) m\n else {\n val (s3, e3) = ans(i + 2)\n if (data(e1) + 1 < data(s3))\n Math.max(m, s3 - e1)\n else\n m\n }\n else if (data(e1 - 1) + 1 < data(s2) || data(e1) + 1 < data(s2 + 1)) {\n// println(\"here\")\n val t = Math.max(m, e2 - s1 + 1)\n// println(t)\n t\n }\n else\n m\n }\n println(t)\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val a = in.next().split(' ').map(_.toInt)\n val l = Array.fill(n)(1)\n val r = Array.fill(n)(1)\n\n (1 until n).foreach { i =>\n if (a(i - 1) < a(i)) l(i) += l(i - 1)\n }\n (n - 2 until 0 by -1).foreach { i =>\n if (a(i + 1) > a(i)) r(i) += r(i + 1)\n }\n val m = l.max\n val s = m + (if (m < n) 1 else 0)\n println((1 until n - 1).foldLeft(s) {\n case (acc, i) if a(i - 1) + 1 < a(i + 1) => Math.max(acc, l(i - 1) + r(i + 1) + 1)\n case (acc, _) => acc\n })\n}\n"}, {"source_code": "\nobject tmp extends App {\n\n import java.io._\n import java.util.StringTokenizer\n\n class MyScanner(br: BufferedReader) {\n var st = new StringTokenizer(\"\")\n\n def this(is: InputStream) = this(new BufferedReader(new InputStreamReader(is)))\n\n private def next() = {\n\n while (!st.hasMoreElements) {\n st = new StringTokenizer(br.readLine())\n }\n st.nextToken()\n }\n\n def nextInt() = java.lang.Integer.parseInt(next())\n\n def nextLong() = java.lang.Long.parseLong(next())\n\n def nextLine() = br.readLine()\n }\n\n val sc = new MyScanner(System.in)\n val n = sc.nextInt()\n var prevEnd = -1\n var prevLen = -1\n var prev = 0\n var curLen = 0\n var ans = 0\n val a = Array.fill(n)(0)\n for (i <- 0 until n) {\n a(i) = sc.nextInt()\n if (prev < a(i)) {\n curLen += 1\n prev = a(i)\n } else {\n if (prevEnd != -1) {\n ans = math.max(ans, prevLen + 1)\n ans = math.max(ans, curLen + 1)\n val left = a(prevEnd + 1) - 1\n val leftCan = prevLen == 1 || left > a(prevEnd - 1)\n val right = a(prevEnd) + 1\n val rightCan = curLen == 1 || right < a(prevEnd + 2)\n if (leftCan || rightCan) {\n ans = math.max(ans, prevLen + curLen)\n }\n }\n prevEnd = i - 1\n prevLen = curLen\n prev = a(i)\n curLen = 1\n\n }\n }\n if (prevEnd == -1) {\n ans = curLen\n } else {\n ans = math.max(ans, prevLen + 1)\n ans = math.max(ans, curLen + 1)\n val left = a(prevEnd + 1) - 1\n val leftCan = prevLen == 1 || left > a(prevEnd - 1)\n val right = a(prevEnd) + 1\n val rightCan = curLen == 1 || right < a(prevEnd + 2)\n if (leftCan || rightCan) {\n ans = math.max(ans, prevLen + curLen)\n }\n }\n println(ans)\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val res = data.indices.tail.foldLeft((0, List.empty[(Int, Int)])) {\n case (acc@(first, list), i) if data(i) > data(i - 1) => acc\n case ((first, list), i) => (i, (first, i - 1) :: list)\n }\n val ans: Array[(Int, Int)] = ((res._1, n - 1) :: res._2).reverse.toArray\n if (ans.length == 1)\n println(n)\n else {\n val max = ans.map(i => i._2 - i._1).max + 2\n val t = ans.indices.foldLeft(max) {\n case (m, i) if i == ans.length - 1 => m\n case (m, i) =>\n val (s1, e1) = ans(i)\n val (s2, e2) = ans(i + 1)\n if (s1 == e1 || s2 == e2)\n if (i == ans.length - 2) m\n else {\n val (s3, e3) = ans(i + 2)\n if (data(e1) + 1 < data(s3))\n Math.max(m, s3 - e1 + 1)\n else\n m\n }\n else if (data(e1 - 1) + 1 < data(s2) || data(e1) + 1 < data(s2 + 1)) {\n// println(\"here\")\n val t = Math.max(m, e2 - s1 + 1)\n// println(t)\n t\n }\n else\n m\n }\n println(t)\n }\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 14 Aug 2016\n */\nobject A446 extends App {\n\n def solve() = {\n val n = scala.io.StdIn.readInt()\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val r: Array[Int] = Array.ofDim[Int](n)\n r(0) = 1\n val s: Array[(Int, Int)] = Array.ofDim[(Int, Int)](n)\n s(0) = (1, a(0)-1)\n var max = 1\n for (i <- 1 until n) {\n // update r:\n if (a(i) > a(i - 1)) {\n r(i) = r(i - 1) + 1\n } else {\n r(i) = 1\n }\n // update s:\n if (a(i) > s(i - 1)._2) {\n s(i) = (s(i - 1)._1 + 1, a(i))\n } else {\n s(i) = (r(i - 1) + 1, a(i-1) + 1)\n }\n max = math.max(max, math.max(r(i), s(i)._1))\n }\n\n println(max)\n }\n\n solve()\n\n}"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 14 Aug 2016\n */\nobject A446 extends App {\n\n def solve() = {\n val n = scala.io.StdIn.readInt()\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n var max = 1\n val l: Array[Int] = Array.ofDim[Int](n)\n l(0) = 1\n for (i <- 1 until n) {\n // update l:\n if (a(i) > a(i - 1)) {\n l(i) = l(i - 1) + 1\n } else {\n l(i) = 1\n }\n max = math.max(max, l(i))\n }\n val r: Array[Int] = Array.ofDim[Int](n)\n r(n - 1) = 1\n for (i <- (n - 2).to(0, -1)) {\n if (a(i) < a(i + 1)) {\n r(i) = r(i + 1) + 1\n } else {\n r(i) = 1\n }\n max = math.max(max, r(i))\n }\n max += 1\n for (i <- 1 until n-1) {\n if (a(i - 1) + 1 < a(i + 1)) {\n max = math.max(max, l(i - 1) + 1 + r(i + 1))\n }\n }\n println(max)\n }\n\n solve()\n\n}"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 14 Aug 2016\n */\nobject A446 extends App {\n\n def solve() = {\n val n = scala.io.StdIn.readInt()\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val r: Array[Int] = Array.ofDim[Int](n)\n r(0) = 1\n val s: Array[(Int, Int)] = Array.ofDim[(Int, Int)](n)\n s(0) = (1, -1)\n var max = 1\n for (i <- 1 until n) {\n // update r:\n if (a(i) > a(i - 1)) {\n r(i) = r(i - 1) + 1\n } else {\n r(i) = 1\n }\n // update s:\n if (a(i) > s(i - 1)._2) {\n s(i) = (s(i - 1)._1 + 1, a(i))\n } else {\n s(i) = (r(i - 1) + 1, a(i-1) + 1)\n }\n max = math.max(max, math.max(r(i), s(i)._1))\n }\n\n println(max)\n }\n\n solve()\n\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 14 Aug 2016\n */\nobject A446 extends App {\n\n def solve() = {\n val n = scala.io.StdIn.readInt()\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val r: Array[Int] = Array.ofDim[Int](n)\n r(0) = 1\n val s: Array[(Int, Int)] = Array.ofDim[(Int, Int)](n)\n s(0) = (1, -1)\n var max = 1\n for (i <- 1 until n) {\n // update r:\n if (a(i) > a(i - 1)) {\n r(i) = r(i - 1) + 1\n } else {\n r(i) = 1\n }\n // update s:\n if (a(i) > s(i - 1)._2) {\n s(i) = (s(i - 1)._1 + 1, a(i))\n } else if (a(i-1) > a(i) && (i < 2 || a(i-2) < a(i)-1)) {\n // change previous:\n s(i) = (r(i - 1) + 1, a(i))\n } else {\n // change current\n s(i) = (r(i - 1) + 1, a(i-1) + 1)\n }\n max = math.max(max, math.max(r(i), s(i)._1))\n }\n\n println(max)\n }\n\n solve()\n\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 14 Aug 2016\n */\nobject A446 extends App {\n\n def solve() = {\n val n = scala.io.StdIn.readInt()\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val r: Array[Int] = Array.ofDim[Int](n)\n r(0) = 1\n val s: Array[(Int, Int)] = Array.ofDim[(Int, Int)](n)\n s(0) = (1, a(0))\n var max = 0\n for (i <- 1 until n) {\n // update r:\n if (a(i) > a(i - 1)) {\n r(i) = r(i - 1) + 1\n } else {\n r(i) = 1\n }\n // update s:\n if (a(i) > s(i - 1)._2) {\n s(i) = (s(i - 1)._1 + 1, a(i))\n } else {\n s(i) = (r(i - 1) + 1, a(i-1) + 1)\n }\n max = math.max(max, math.max(r(i), s(i)._1))\n }\n\n println(max)\n }\n\n solve()\n\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 14 Aug 2016\n */\nobject A446 extends App {\n\n def solve() = {\n val n = scala.io.StdIn.readInt()\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val r: Array[Int] = Array.ofDim[Int](n)\n r(0) = 1\n val s: Array[(Int, Int)] = Array.ofDim[(Int, Int)](n)\n s(0) = (1, a(0))\n var max = 1\n for (i <- 1 until n) {\n // update r:\n if (a(i) > a(i - 1)) {\n r(i) = r(i - 1) + 1\n } else {\n r(i) = 1\n }\n // update s:\n if (a(i) > s(i - 1)._2) {\n s(i) = (s(i - 1)._1 + 1, a(i))\n } else {\n s(i) = (r(i - 1) + 1, a(i-1) + 1)\n }\n max = math.max(max, math.max(r(i), s(i)._1))\n }\n\n println(max)\n }\n\n solve()\n\n}\n"}, {"source_code": "\nobject Main {\n def main (args: Array[String]) {\n val n=io.StdIn.readLine().toInt\n val v=io.StdIn.readLine().split(\" \").map(_.toInt)\n val s=Array.fill(n)(1)\n val t=Array.fill(n)(1)\n (1 until n).foreach(i=>if (v(i-1)if (v(i) {\n var cur = 1\n if (i > 0 && i + 1 < n-1 && v(i - 1) + 1 >= v(i + 1))\n cur += math.max(s(i - 1), t(i + 2))\n else{\n if (i>0) cur+=s(i-1)\n if (i+1if (v(i-1)if (v(i) {\n var cur = 1\n if (i > 0 && i < n-2 && v(i - 1) + 1 >= v(i + 1))\n cur += math.max(s(i - 1), t(i + 1))\n else{\n if (i>0) cur+=s(i-1)\n if (i+1\r\n val m = readInt()\r\n val am = readLine().split(\" \").map(_.toInt)\r\n val bm = readLine().split(\" \").map(_.toInt)\r\n\r\n val (ans, _, _) = (1 until m).foldLeft((am.tail.sum, am.tail.sum, 0)) { case ((score, a, b), i) =>\r\n val (c, d) = (a - am(i), b + bm(i - 1))\r\n (score min (c max d), c, d)\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val m = readInt()\r\n val apref = readLine().split(\" \").map(_.toInt).scanLeft(0)(_ + _)\r\n val bpref = readLine().split(\" \").map(_.toInt).scanLeft(0)(_ + _)\r\n\r\n def score: Int => Int = i => bpref(i) max (apref(m) - apref(i + 1))\r\n\r\n val ans = (1 until m).foldLeft(score(0))(_ min score(_))\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val m = readInt()\r\n val apref = readLine().split(\" \").map(_.toInt).scanLeft(0)(_ + _)\r\n val bpref = readLine().split(\" \").map(_.toInt).scanLeft(0)(_ + _)\r\n\r\n def score(i: Int): Int = (apref(m) - apref(i + 1)) max bpref(i)\r\n\r\n val ans = (1 until m).foldLeft(score(0))((s, i) => s min score(i))\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "import java.io.PrintWriter\r\nimport java.util.Scanner\r\n\r\nobject Solution {\r\n def solve(m: Int, l1: Array[Int], l2: Array[Int]): Int = {\r\n // if Alice moved from l1 to l2 at point x then she:\r\n // collect from [0 to x] on line 1\r\n // from [x to m] on line 2\r\n\r\n // now bob can move to live 2 at y\r\n // x == y doesn't make sense\r\n // y < x the score is line 2 [y..x) which means it's [0..x)\r\n // y > x the score is line 1 (x..y] which means it's (x..m)\r\n\r\n // so for each x Bob will choose max of (v1) [0..x) in line 2 and (v2) (x..m) in line 1\r\n\r\n val partials1 = l1.reverse.scanLeft(0)(_ + _).tail.reverse\r\n val partials2 = l2.scanLeft(0)(_ + _).tail\r\n\r\n val bobsCounts = (0 until m).map { x =>\r\n val v1 = if (x == 0) 0 else partials2(x - 1)\r\n val v2 = if (x == m - 1) 0 else partials1(x + 1)\r\n Math.max(v1, v2)\r\n }.toArray\r\n\r\n bobsCounts.min\r\n }\r\n\r\n def run(test: Int, input: Scanner, output: PrintWriter): Unit = {\r\n val m = input.nextInt()\r\n val l1 = (1 to m).map { _ => input.nextInt() }.toArray\r\n val l2 = (1 to m).map { _ => input.nextInt() }.toArray\r\n output.println(solve(m, l1, l2))\r\n }\r\n\r\n def run(input: Scanner, output: PrintWriter): Unit = {\r\n val tests = input.nextInt()\r\n\r\n (1 to tests).foreach { test =>\r\n run(test, input, output)\r\n output.flush()\r\n }\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n run(new Scanner(System.in), new PrintWriter(System.out))\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "f3ee3a0de5ddf3cf15ef02fb62a2768e"} {"source_code": "\r\n\r\nobject HelloWorld {\r\n\r\n def main(args: Array[String]): Unit = {\r\n val tests = scala.io.StdIn.readInt()\r\n for (t <- 1 to tests) {\r\n scala.io.StdIn.readLine()\r\n\r\n val arr = Array.fill(8){scala.io.StdIn.readLine().toCharArray}\r\n\r\n if (arr.exists(_.forall(_ == 'R'))) println(\"R\")\r\n else println(\"B\")\r\n\r\n\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object Stripes {\r\n\r\n def solve_test() = {\r\n val _ = scala.io.StdIn.readLine()\r\n if ((0 until 8).map(_ => scala.io.StdIn.readLine().count(_ == 'R')).max == 8)\r\n printf (\"R\\n\")\r\n else\r\n printf (\"B\\n\")\r\n }\r\n\r\n def main (args: Array[String]): Unit = {\r\n val test = scala.io.StdIn.readInt()\r\n for (i <- 0 until test) solve_test()\r\n }\r\n}"}], "negative_code": [{"source_code": "\r\n\r\nobject HelloWorld {\r\n\r\n def main(args: Array[String]): Unit = {\r\n val tests = scala.io.StdIn.readInt()\r\n for (t <- 1 to tests) {\r\n scala.io.StdIn.readLine()\r\n\r\n val arr = Array.fill(8){scala.io.StdIn.readLine().toCharArray}\r\n val arr2 = arr.transpose\r\n\r\n if (arr.exists(_.forall(_ == 'R')) || arr2.exists(_.forall(_ == 'R'))) println(\"R\")\r\n else println(\"B\")\r\n\r\n\r\n }\r\n }\r\n}\r\n"}], "src_uid": "2c7add49d423de44a2bc09de56ffacf1"} {"source_code": "//package codeforces\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject EhabAndTwoOperationTask {\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n\n def readIntArray(n: Int): Array[Int] = {\n val st = new StringTokenizer(br.readLine())\n\n val arr = new Array[Int](n)\n var i = 0\n while (st.hasMoreElements) {\n arr(i) = st.nextToken().toInt\n i += 1\n }\n\n arr\n }\n\n def readInt(): Int = {\n new StringTokenizer(br.readLine()).nextToken.toInt\n }\n\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val input: Array[Int] = readIntArray(n)\n val x = 3 * (input.length max input.max)\n\n println((1 to n).foldLeft(new StringBuilder().append(n+1).append('\\n').append(s\"1 $n $x\\n\"))((acc, i) => acc.append(s\"2 $i \" + (x + input(i-1) - i) + \"\\n\")))\n }\n}\n", "positive_code": [{"source_code": "//package codeforces\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject EhabAndTwoOperationTask {\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n\n def readIntArray(n: Int): Array[Int] = {\n val st = new StringTokenizer(br.readLine())\n\n val arr = new Array[Int](n)\n var i = 0\n while (st.hasMoreElements) {\n arr(i) = st.nextToken().toInt\n i += 1\n }\n\n arr\n }\n\n def readInt(): Int = {\n new StringTokenizer(br.readLine()).nextToken.toInt\n }\n\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val input: Array[Int] = readIntArray(n)\n\n println(n + 1)\n\n val x = 3 * (input.length max input.max)\n\n println(s\"1 $n $x\")\n\n\n\n for (i <- 1 to n) {\n val currentValue = x + input(i-1)\n println(s\"2 $i \" + (currentValue - i))\n }\n\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n var sum = 0L\n val ops = ArrayBuffer[(Int, Long)]()\n REP_r(N) { i =>\n val target = i\n val r = (sum + A(i)) % N\n if (target != r) {\n val x = (N + target - r) % N\n ops += ((i, x))\n sum += x\n }\n }\n\n out.println(ops.length + 1)\n ops.reverse.foreach { case (i, x) =>\n out.println(s\"1 ${i+1} $x\")\n }\n out.println(s\"2 $N $N\")\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object _1088C extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val (n, as) = io.readAll[Long]\n val m = 5e5.toLong\n var s = 0L\n\n val ans = {\n for {\n i <- as.indices.reverse\n } yield {\n val x = m + (i + 1 - (as(i) + s))%m\n s += x\n s\"1 ${i+1} $x\"\n }\n } :+ s\"2 $n $m\"\n\n io.writeLine(ans.length).writeAll(ans , separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject C extends App {\n def readInts = StdIn.readLine().split(\" \").map(_.toInt)\n def readInt = StdIn.readInt()\n\n val n = readInt\n val A = readInts\n\n// val n = 3\n// val A = Array(7, 6, 3)\n\n def solve() = {\n var sum = 0\n println(n + 1)\n (0 until n).reverse.foreach { i =>\n val diff = (i - (A(i) + sum) % n + n) % n\n sum += diff\n println(s\"1 ${i + 1} $diff\")\n }\n println(s\"2 $n $n\")\n }\n\n solve()\n}\n"}], "negative_code": [{"source_code": "object _1088C extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val (n, as) = io.readAll[Long]\n val m = as.max + 1\n var s = 0L\n\n val ans = {\n for {\n i <- as.indices.reverse\n } yield {\n val x = m + (- as(i) - s + i+1)%m\n assert(x > 0)\n s = (s + x)%m\n s\"1 ${i+1} $x\"\n }\n } :+ s\"2 $n $m\"\n\n assert(ans.length <= n+1)\n\n io.writeLine(ans.length).writeAll(ans , separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject C extends App {\n def readInts = StdIn.readLine().split(\" \").map(_.toInt)\n def readInt = StdIn.readInt()\n\n// val n = readInt\n// val A = readInts\n\n val n = 3\n val A = Array(7, 6, 3)\n\n def solve() = {\n var sum = 0\n println(n + 1)\n (0 until n).reverse.foreach { i =>\n val diff = (i - (A(i) + sum) % n + n) % n\n sum += diff\n println(s\"1 $i $diff\")\n }\n println(s\"2 $n $n\")\n }\n\n solve()\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject C extends App {\n def readInts = StdIn.readLine().split(\" \").map(_.toInt)\n def readInt = StdIn.readInt()\n\n val n = readInt\n val A = readInts\n\n// val n = 3\n// val A = Array(7, 6, 3)\n\n def solve() = {\n// println(A.mkString(\" \"))\n var solution = ArrayBuffer[String]()\n\n (0 until n).reverse.foreach { i =>\n val diff = (n - A(i) % n + i) % n\n\n// println(diff)\n if (diff > 0) {\n (0 to i).foreach { j =>\n A(j) += diff\n }\n solution += s\"1 $diff $i\"\n// println(s\"1 $diff i\")\n// println(A.mkString(\" \"))\n }\n }\n\n (0 until n).foreach { i =>\n A(i) %= n\n }\n\n solution += s\"2 ${n - 1} $n\"\n// println(s\"2 ${n - 1} $n\")\n// println(A.mkString(\" \"))\n\n println(solution.length)\n println(solution.mkString(\"\\n\"))\n }\n\n solve()\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject C extends App {\n def readInts = StdIn.readLine().split(\" \").map(_.toInt)\n def readInt = StdIn.readInt()\n\n val n = readInt\n val A = readInts\n\n// val n = 3\n// val A = Array(7, 6, 3)\n\n def solve() = {\n// println(A.mkString(\" \"))\n var solution = ArrayBuffer[String]()\n\n (0 until n).reverse.foreach { i =>\n val diff = n - A(i) % n + i\n\n// println(diff)\n if (diff > 0) {\n (0 to i).foreach { j =>\n A(j) += diff\n }\n solution += s\"1 $diff i\"\n// println(s\"1 $diff i\")\n// println(A.mkString(\" \"))\n }\n }\n\n (0 until n).foreach { i =>\n A(i) %= n\n }\n\n solution += s\"2 ${n - 1} $n\"\n// println(s\"2 ${n - 1} $n\")\n// println(A.mkString(\" \"))\n\n println(solution.length)\n println(solution.mkString(\"\\n\"))\n }\n\n solve()\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject C extends App {\n def readInts = StdIn.readLine().split(\" \").map(_.toInt)\n def readInt = StdIn.readInt()\n\n val n = readInt\n val A = readInts\n\n// val n = 3\n// val A = Array(7, 6, 3)\n\n def solve() = {\n// println(A.mkString(\" \"))\n var solution = ArrayBuffer[String]()\n\n (0 until n).reverse.foreach { i =>\n val diff = (n - A(i) % n + i) % n\n\n// println(diff)\n if (diff > 0) {\n (0 to i).foreach { j =>\n A(j) += diff\n }\n solution += s\"1 $diff i\"\n// println(s\"1 $diff i\")\n// println(A.mkString(\" \"))\n }\n }\n\n (0 until n).foreach { i =>\n A(i) %= n\n }\n\n solution += s\"2 ${n - 1} $n\"\n// println(s\"2 ${n - 1} $n\")\n// println(A.mkString(\" \"))\n\n println(solution.length)\n println(solution.mkString(\"\\n\"))\n }\n\n solve()\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject C extends App {\n def readInts = StdIn.readLine().split(\" \").map(_.toInt)\n def readInt = StdIn.readInt()\n\n// val n = readInt\n// val A = readInts\n\n val n = 3\n val A = Array(7, 6, 3)\n\n def solve() = {\n var sum = 0\n println(n + 1)\n (0 until n).reverse.foreach { i =>\n val diff = (i - (A(i) + sum) % n + n) % n\n sum += diff\n println(s\"1 ${i + 1} $diff\")\n }\n println(s\"2 $n $n\")\n }\n\n solve()\n}\n"}], "src_uid": "e0ba8e0bfd9e1365daa41e1d14610200"} {"source_code": "object B extends App {\n val Array(n, m) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val a = for (_ <- 0 until n) yield scala.io.StdIn.readLine().split(\"\")\n val s = scala.io.StdIn.readLine().split(\"\").map(_.toInt)\n\n def D(c: (Int, Int)): (Int, Int) = (c._1, c._2 - 1)\n def U(c: (Int, Int)): (Int, Int) = (c._1, c._2 + 1)\n def L(c: (Int, Int)): (Int, Int) = (c._1 - 1, c._2)\n def R(c: (Int, Int)): (Int, Int) = (c._1 + 1, c._2)\n\n def check(c: (Int, Int)): Boolean =\n c._1 >= 0 && c._1 < m && c._2 >=0 && c._2 < n && a(c._2)(c._1) != \"#\"\n\n def S(c: (Int, Int) = (0, 0)): (Int, Int) =\n if (c._1 == m) S((0, c._2 + 1))\n else if (a(c._2)(c._1) == \"S\") c\n else S((c._1 + 1, c._2))\n\n val c = S()\n\n// def variant(d: Int, u: Int, l: Int, r: Int, c: (Int, Int) = c, s: Array[Int] = s): Boolean =\n def variant(codes: Array[Int], c: (Int, Int) = c, s: Array[Int] = s): Boolean =\n if (!check(c)) false\n else {\n val t = a(c._2)(c._1)\n if (t == \"E\") true\n else if (s.isEmpty) false\n else {\n val h = s.head\n if (h == codes(0)) variant(codes, D(c), s.tail)\n else if (h == codes(1)) variant(codes, U(c), s.tail)\n else if (h == codes(2)) variant(codes, L(c), s.tail)\n else variant(codes, R(c), s.tail)\n }\n }\n\n\n println(Array(0, 1, 2, 3).permutations.count(variant(_)))\n}\n", "positive_code": [{"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val maze = Array.fill(n){readLine}\n val moves = readLine.map(_ - '0')\n\n var r0, c0 = -1\n\n for {\n r <- 0 until n\n c <- 0 until m\n } {\n if (maze(r)(c) == 'S') {\n r0 = r\n c0 = c\n }\n }\n\n def check(mapping: Array[Int]): Boolean = {\n var r = r0\n var c = c0\n var ok = true\n\n var step = 0\n while (ok && step < moves.length) {\n\n mapping(moves(step)) match {\n case 0 =>\n r += 1\n case 1 =>\n c -= 1\n case 2 =>\n r -= 1\n case 3 =>\n c += 1\n }\n\n ok = r >= 0 && c >= 0 && r < n && c < m && maze(r)(c) != '#'\n\n if (ok && maze(r)(c) == 'E') return true\n\n step += 1\n }\n\n ok && maze(r)(c) == 'E'\n }\n\n val directions = Array(0, 1, 2, 3)\n\n var count = 0\n\n for {\n mapping <- directions.permutations\n if check(mapping)\n } count += 1\n\n println(count)\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.util.control.Breaks\n\nobject Main {\n val in = new InputReader(System.in)\n val pw = new PrintWriter(System.out)\n\n def main (args: Array[String]){\n val H, W = in.next().toInt\n val field = new Array[String](H+1)\n for (i <- 1 to H) {\n field(i) = \"#\" + in.next()\n }\n val command = in.next()\n\n ///\n def isCorrect(p: (Int, Int)) = {\n val (x, y) = p\n 1 <= x && x <= W && 1 <= y && y<= H\n }\n\n var start = (-1, -1)\n var goal = (-1, -1)\n for(y <- 1 to H; x <- 1 to W) {\n val now = field(y)(x)\n if(now == 'S')\n start = (x, y)\n else if(now == 'E')\n goal = (x, y)\n }\n\n val perm: List[List[(Int, Int)]] =\n List((1,0),(-1,0),(0,1),(0,-1)).permutations.toList\n var ans = 0\n\n val b = new Breaks // instance of Breaks\n\n for (e <- perm) {\n var now: (Int, Int) = (start._1, start._2)\n b.breakable {\n for(c <- command) {\n val com = c.toString.toInt\n val (volx, voly) = e(com)\n val next: (Int, Int) = (now._1 + volx, now._2 + voly)\n now = next\n if(isCorrect(next)){\n if(next == goal) {\n ans += 1\n b.break\n }\n else if(field(next._2)(next._1) == '#')\n b.break\n }\n else {\n b.break\n }\n }\n }\n }\n println(ans)\n }\n}\n\nclass InputReader(stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream))\n private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())\n def next(): String = {\n while (!tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine())\n }\n tokenizer.nextToken()\n }\n}\n"}, {"source_code": "object CF908B extends App {\n\n val sc = new java.util.Scanner(System.in)\n\n val Array(rows, cols) = io.StdIn.readLine split \" \" map (_.toInt)\n val robomap = for (r <- 1 to rows) yield io.StdIn.readLine\n val route = io.StdIn.readLine split \"\" map (_.toInt)\n\n val start = find('S')\n val end = find('E')\n\n val ans = Range(0, 3 + 1).permutations count solve\n\n print(ans)\n\n def solve(seq: Seq[Int]): Boolean = {\n val d = Seq((0, 1), (0, -1), (1, 0), (-1, 0))\n\n var current = start\n for (c <- route) {\n current = (current._1 + d(seq(c))._1, current._2 + d(seq(c))._2)\n if (current._1 < 0 ||\n current._2 < 0 ||\n current._1 >= rows ||\n current._2 >= cols || robomap(current._1)(current._2) == '#') return false\n if (current equals end) return true\n }\n false\n }\n\n def find(c: Char): (Int, Int) = {\n for (r <- 0 until rows) {\n val i = robomap(r).indexOf(c)\n if (i >= 0) return (r, i)\n }\n return (-1, -1)\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.util.control.Breaks\n\nobject Main {\n val in = new InputReader(System.in)\n val pw = new PrintWriter(System.out)\n\n def main (args: Array[String]){\n val H, W = in.next().toInt\n val field = new Array[String](H+1)\n for (i <- 1 to H) {\n field(i) = \"#\" + in.next()\n }\n val command = in.next()\n\n ///\n def isCorrect(p: (Int, Int)) = {\n val (x, y) = p\n 1 <= x && x <= W && 1 <= y && y<= H\n }\n\n var start = (-1, -1)\n var goal = (-1, -1)\n for(y <- 1 to H; x <- 1 to W) {\n val now = field(y)(x)\n if(now == 'S')\n start = (x, y)\n else if(now == 'E')\n goal = (x, y)\n }\n\n val perm: List[List[(Int, Int)]] =\n List((1,0),(-1,0),(0,1),(0,-1)).permutations.toList\n var ans = 0\n\n val b = new Breaks // instance of Breaks\n\n for (e <- perm) {\n var now: (Int, Int) = (start._1, start._2)\n b.breakable {\n for(c <- command) {\n val com = c.toString.toInt\n val (volx, voly) = e(com)\n val next: (Int, Int) = (now._1 + volx, now._2 + voly)\n now = next\n if(isCorrect(next)){\n if(next == goal) {\n ans += 1\n b.break\n }\n }\n else {\n b.break\n }\n }\n }\n }\n println(ans)\n }\n}\n\nclass InputReader(stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream))\n private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())\n def next(): String = {\n while (!tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine())\n }\n tokenizer.nextToken()\n }\n}\n"}], "src_uid": "8a1799f4ca028d48d5a12e8ac4b8bee1"} {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = Array.fill(n) { readLine.toCharArray }\n val isHit = Array.fill(n, n) { false }\n\n val validDxBuilder, validDyBuilder = new ArrayBuilder.ofInt\n\n for (dx <- -n + 1 to n - 1) {\n for (dy <- -n + 1 to n - 1) if (dx != 0 || dy != 0){\n var possible = true\n for (x <- 0 until n) {\n for (y <- 0 until n) {\n if (as(x)(y) == 'o') {\n val nx = x + dx\n val ny = y + dy\n if (nx >= 0 && ny >= 0 && nx < n && ny < n && as(nx)(ny) == '.') possible = false\n }\n }\n }\n if (possible) {\n validDxBuilder += dx\n validDyBuilder += dy\n for (x <- 0 until n) {\n for (y <- 0 until n) {\n if (as(x)(y) == 'o') {\n val nx = x + dx\n val ny = y + dy\n if (nx >= 0 && ny >= 0 && nx < n && ny < n) isHit(nx)(ny) = true\n }\n }\n }\n }\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n var ok = true\n for (x <- 0 until n) {\n for (y <- 0 until n) {\n if (isHit(x)(y) && as(x)(y) == '.') ok = false\n if (!isHit(x)(y) && as(x)(y) == 'x') ok = false\n }\n }\n\n if (ok) {\n println(\"YES\")\n val res = Array.fill(2 * n - 1, 2 * n - 1)('.')\n res(n - 1)(n - 1) = 'o'\n val validDx = validDxBuilder.result\n val validDy = validDyBuilder.result\n for (i <- 0 until validDx.size) {\n //println(validDx(i), validDy(i))\n res(n + validDx(i) - 1)(n + validDy(i) - 1) = 'x'\n }\n for (r <- res) println(r.mkString)\n } else println(\"NO\")\n\n Console.flush\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject D extends App {\n val n = StdIn.readInt()\n val f = Array.fill(n)(StdIn.readLine().toCharArray)\n\n def validateMove(dx: Int, dy: Int): Boolean = {\n (dx != 0 || dy != 0) &&\n (for (x <- 0 until n; y <- 0 until n; if x + dx >= 0 && x + dx < n && y + dy >= 0 && y + dy < n && f(x)(y) == 'o') yield f(x + dx)(y + dy) != '.').forall(identity)\n }\n\n val moves = for (x <- -n + 1 to n - 1; y <- -n + 1 to n - 1 if validateMove(x, y)) yield (x, y)\n\n for ((dx, dy) <- moves) {\n for (x <- 0 until n; y <- 0 until n; if x + dx >= 0 && x + dx < n && y + dy >= 0 && y + dy < n && f(x)(y) == 'o') {\n if (f(x + dx)(y + dy) == 'x') {\n f(x + dx)(y + dy) = '.'\n }\n }\n }\n\n if (f.forall(_.forall(_ != 'x'))) {\n println(\"YES\")\n val f2 = Array.fill(2 * n - 1, 2 * n - 1)('.')\n f2(n - 1)(n - 1) = 'o'\n for ((dx, dy) <- moves) {\n f2(n - 1 + dx)(n - 1 + dy) = 'x'\n }\n f2.map(t => String.valueOf(t)).foreach(println)\n } else {\n println(\"NO\")\n }\n}\n"}], "negative_code": [], "src_uid": "2fad1534434f042214dcd1f1dc75405a"} {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject P078A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val Poem = List.fill(3)(sc.nextLine)\n val isVowel = \"aeiou\".toSet\n val isHaiku = (lst: List[String]) => {\n lst.map(_.count(isVowel)) == List(5, 7, 5)\n }\n val res = if (isHaiku(Poem)) \"YES\" else \"NO\"\n\n out.println(res)\n out.close\n}\n\n\n\n\n\n", "positive_code": [{"source_code": "object Solution extends App {\n\n\n val in = scala.io.Source.stdin.getLines()\n val vowel = List('a', 'e', 'i', 'o', 'u')\n if ((1 to 3).map(_ => in.next().count(vowel.contains)).toList == List(5, 7, 5))\n println(\"YES\")\n else\n println(\"NO\")\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject P078A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val isVowel = \"aeiou\".toSet\n val isHaiku = List(5, 7, 5) == List.fill(3)(sc.nextLine).map(_.count(isVowel))\n val res = if (isHaiku) \"YES\" else \"NO\"\n\n out.println(res)\n out.close\n}\n\n\n\n\n\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val s1 = readLine()\n val s2 = readLine()\n val s3 = readLine()\n \n val i1 = s1.count(c => c == 'a' || c == 'e' || c == 'o' || c == 'u' || c == 'i')\n val i2 = s2.count(c => c == 'a' || c == 'e' || c == 'o' || c == 'u' || c == 'i')\n val i3 = s3.count(c => c == 'a' || c == 'e' || c == 'o' || c == 'u' || c == 'i')\n \n if (i1 == 5 && i2 == 7 && i3 == 5) println(\"YES\")\n else (println(\"NO\"))\n }\n}"}], "negative_code": [], "src_uid": "46d734178b3acaddf2ee3706f04d603d"} {"source_code": "import scala.io.StdIn._\n\n\nobject tmp extends App {\n val n = readInt()\n var m = readInt()\n val a = (for (_ <- 0 until n) yield readInt()).view.toArray.sortBy(-_)\n val result = a.indexWhere((i: Int) => {\n m -= i\n m <= 0\n }) + 1\n println(result)\n}\n", "positive_code": [{"source_code": "object A609 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val Array(m) = readInts(1)\n val in = Array.fill(n)(readInts(1)).map(_(0)).sorted.reverse\n var i = 0\n var curr = 0\n while(curr < m) {\n curr += in(i)\n i += 1\n }\n println(i)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Arrays.sort\nimport java.util.Scanner\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n def next = scanner.next.toInt\n\n val size = next\n val sum = next\n val capacities = 0.to(size - 1).map(x => next).toArray\n\n println(countMinVolumes(capacities, sum))\n }\n\n def countMinVolumes(capacities: IndexedSeq[Int], targetSum: Int) : Int = {\n val sorted = capacities.sorted(Ordering[Int].reverse)\n var count = 0\n var sum = 0\n for (capacity <- sorted) {\n count = count + 1\n sum = sum + capacity\n if (sum >= targetSum)\n return count\n }\n assert(false)\n 0\n }\n}\n"}, {"source_code": "object A extends App {\n val n = readInt\n var m = readInt\n var l = List[Int]()\n\n def getNum : Int = {\n for(i <- 0 until n)\n l = l :+ readInt\n\n var i = 0\n for(f <- l.sorted.reverse) {\n m = m - f\n i = i + 1\n \n if (m <= 0)\n return i\n }\n i\n }\n \n println(getNum)\n}"}, {"source_code": "import io.StdIn._\n\nobject tmp extends App {\n val n = readInt()\n var m = readInt()\n val a = (for (_ <- 0 until n) yield readInt()).sortBy(-_)\n val result = a.indexWhere((i: Int) => {\n m -= i\n m <= 0\n }) + 1\n println(result)\n}\n"}, {"source_code": "\nimport scala.io.Codec\nimport scala.io.StdIn._\n\nobject tmp extends App {\n\n\n class Scanner(reader: java.io.LineNumberReader) extends Iterator[String] with AutoCloseable {\n type StringTokenizer = java.util.StringTokenizer\n\n def this(reader: java.io.BufferedReader) = this(new java.io.LineNumberReader(reader))\n\n def this(reader: java.io.Reader) = this(new java.io.BufferedReader(reader))\n\n def this(inputStream: java.io.InputStream)(implicit codec: Codec) = this(new java.io.InputStreamReader(inputStream, codec.charSet))\n\n // def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n override def next() = tokenizer().get.nextToken()\n\n override def hasNext = tokenizer().nonEmpty\n\n override def close() = reader.close()\n }\n\n val n = readInt()\n var m = readInt()\n val a = (for (_ <- 0 until n) yield readInt()).toArray.sortBy(-_)\n val result = a.indexWhere((i: Int) => {\n m -= i\n m <= 0\n }) + 1\n println(result)\n}\n"}, {"source_code": "import scala.io.Codec\n\nobject tmp extends App {\n\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n\n class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n // def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n // def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new LineNumberReader(new InputStreamReader(inputStream, codec.charSet)))\n\n def this(path: Path)(implicit codec: Codec) = this(new LineNumberReader(Files.newBufferedReader(path, codec.charSet)))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n override def next() = tokenizer().get.nextToken()\n\n override def hasNext = tokenizer().nonEmpty\n\n override def close() = reader.close()\n }\n\n val s = new Scanner(System.in)\n\n // val n = readInt()\n val n = s.nextInt()\n // var m = readInt()\n var m = s.nextInt()\n val a = (for (_ <- 0 until n) yield s.nextInt()).toArray.sortBy(-_)\n val result = a.indexWhere((i: Int) => {\n m -= i\n m <= 0\n }) + 1\n println(result)\n}\n"}, {"source_code": "\nobject tmp extends App {\n\n import scala.io.Codec\n import scala.io.StdIn._\n\n class Scanner(reader: java.io.LineNumberReader) extends Iterator[String] with AutoCloseable {\n type StringTokenizer = java.util.StringTokenizer\n\n def this(reader: java.io.BufferedReader) = this(new java.io.LineNumberReader(reader))\n\n def this(reader: java.io.Reader) = this(new java.io.BufferedReader(reader))\n\n def this(inputStream: java.io.InputStream)(implicit codec: Codec) = this(new java.io.InputStreamReader(inputStream, codec.charSet))\n\n // def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n override def next() = tokenizer().get.nextToken()\n\n override def hasNext = tokenizer().nonEmpty\n\n override def close() = reader.close()\n }\n\n val n = readInt()\n var m = readInt()\n val a = (for (_ <- 0 until n) yield readInt()).toArray.sortBy(-_)\n val result = a.indexWhere((i: Int) => {\n m -= i\n m <= 0\n }) + 1\n println(result)\n}\n"}, {"source_code": "\n\nobject tmp extends App {\n\n import java.io._\n import java.util.StringTokenizer\n\n class MyScanner(br: BufferedReader) {\n var st = new StringTokenizer(\"\")\n\n def this(is: InputStream) = this(new BufferedReader(new InputStreamReader(is)))\n\n\n def next() = {\n\n while (!st.hasMoreElements) {\n st = new StringTokenizer(br.readLine())\n }\n st.nextToken()\n }\n\n def nextInt() = java.lang.Integer.parseInt(next())\n\n def nextLong() = java.lang.Long.parseLong(next())\n\n def nextLine() = br.readLine()\n\n }\n\n val s = new MyScanner(System.in)\n\n val n = s.nextInt()\n var m = s.nextInt()\n val a = (for (_ <- 0 until n) yield s.nextInt()).toArray.sortBy(-_)\n val result = a.indexWhere((i: Int) => {\n m -= i\n m <= 0\n }) + 1\n println(result)\n}\n"}, {"source_code": "import scala.io.StdIn._\n\n\nobject tmp extends App {\n\n // class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n // def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n //\n // def this(reader: Reader) = this(new BufferedReader(reader))\n //\n // def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n //\n // def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n //\n //\n // private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n // private[this] var current: Option[StringTokenizer] = None\n //\n // private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n // current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n // current\n // }\n //\n // def nextString(): String = next()\n //\n // def nextChar(): Char = next().ensuring(_.length == 1).head\n //\n //\n // def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n //\n // def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n //\n //\n // override def next() = tokenizer().get.nextToken()\n //\n // override def hasNext = tokenizer().nonEmpty\n //\n // override def close() = reader.close()\n // }\n\n // val r = new Scanner(io.Source.stdin.bufferedReader())\n // val n = r.nextInt()\n val n = readInt()\n // var m = r.nextInt()\n var m = readInt()\n val a = (for (_ <- 0 until n) yield readInt()).sortBy(-_)\n val result = a.indexWhere((i: Int) => {\n m -= i\n m <= 0\n }) + 1\n println(result)\n}\n"}, {"source_code": "import io.StdIn._\n\nobject tmp extends App {\n val n = readInt()\n var m = readInt()\n val a = (for (_ <- 0 until n) yield readInt()).sorted.reverse\n val result = a.indexWhere((i: Int) => {\n m -= i\n m <= 0\n }) + 1\n println(result)\n}\n"}, {"source_code": "import scala.io.StdIn._\n\n\nobject tmp extends App {\n val n = readInt()\n var m = readInt()\n val a = (for (_ <- 0 until n) yield readInt()).toArray.sortBy(-_)\n val result = a.indexWhere((i: Int) => {\n m -= i\n m <= 0\n }) + 1\n println(result)\n}\n"}, {"source_code": "/*\n * Reference: http://lizan.asia/blog/2012/12/11/scala-competitive/\n */\n\nobject Main extends App {\n import java.{util => ju}\n import scala.annotation._\n import scala.collection._\n import scala.collection.{mutable => mu}\n import scala.collection.JavaConverters._\n import scala.math._\n\n val sc = new ju.Scanner(System.in)\n val n,m = sc.nextInt\n val a = Array.fill(n)(sc.nextInt).sortWith(_ > _).inits.map(_.sum)\n println(n + 1 - a.count(_ >= m))\n \n \n}"}, {"source_code": "object Solution extends App {\nval n = Console.readLine() toInt;\nvar m = Console.readLine() toInt;\nvar count = 0;\nfor (a <- ((for { i <- 1 to n } yield\n Console.readLine() toInt\n ).toList.sorted.reverse) if m > 0) {\n m = m - a;\n count = count + 1;\n}\nprintln(count)\n}\n"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by Buffalo on 16/1/3.\n */\nobject cf_609a {\n def main(args : Array[String]) = {\n val n :: m :: l = Iterator.continually(StdIn readLine()).takeWhile(_ != null).map(_.toInt).toList\n\n def fun (list: List[Int], rem: Int, cnt:Int):Int = {\n if (rem <= 0) {\n cnt\n } else {\n fun(list.tail, rem - list.head, cnt + 1)\n }\n }\n println(fun(l.sortBy(-_), m, 0))\n\n\n// println(n + \" \" + m + \" \" + l)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val m = in.next().toInt\n val res = (1 to n).map(_ => in.next().toInt).sorted.reverse.foldLeft((0, 0)) {\n case ((sum, count), el) if sum >= m => (sum, count)\n case ((sum, count), el) => (sum + el, count + 1)\n }\n println(res._2)\n\n}\n"}], "negative_code": [{"source_code": "import io.StdIn._\n\nobject tmp extends App {\n println(\"hello\")\n val n = readInt()\n var m = readInt()\n val a = (for (_ <- 0 until n) yield readInt()).sorted.reverse\n val result = a.indexWhere((i: Int) => {\n m -= i\n m <= 0\n }) + 1\n println(result)\n}\n"}], "src_uid": "a02a9e37a4499f9c86ac690a3a427466"} {"source_code": "import scala.io.StdIn\n\nobject MyScalaApp {\n def main(args: Array[String]): Unit = {\n\n val t = StdIn.readInt()\n\n for(x <- 1 to t){\n val n = StdIn.readInt()\n val s = StdIn.readLine()\n \n if(s.indexOf('8') != -1 && (n - s.indexOf('8') >= 11)){\n println(\"YES\")\n } else{\n println(\"NO\")\n }\n\n }\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val t = readInt()\n\n def isPossible(x: Array[Char], n: Int): Boolean = {\n for (i <- 0 to n - 11) {\n if (x(i) == '8') return true\n }\n false\n }\n\n 1 to t foreach { _ =>\n val n = readInt()\n val x = readLine().toArray\n if (isPossible(x, n)) println(\"YES\") else println(\"NO\")\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject MyScalaApp {\n def main(args: Array[String]): Unit = {\n\n val t = StdIn.readInt()\n\n for(x <- 1 to t){\n val n = StdIn.readInt()\n val s = StdIn.readLine()\n\n if(s.indexOf('8') != -1 && (n - s.indexOf(\"8\") >= 11)){\n println(\"YES\")\n } else{\n println(\"NO\")\n }\n\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject MyScalaApp {\n def main(args: Array[String]): Unit = {\n\n val t = StdIn.readInt()\n\n for(x <- 1 to t){\n val n = StdIn.readInt()\n val s = StdIn.readLine()\n\n if(s.indexOf(\"8\") != -1 && (n - s.indexOf(\"8\") >= 11)){\n println(\"YES\")\n } else{\n println(\"NO\")\n }\n\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject MyScalaApp {\n def main(args: Array[String]): Unit = {\n\n val t = StdIn.readInt()\n var idx = 0\n\n while(idx < t){\n val n = StdIn.readInt()\n val s = StdIn.readLine()\n\n if(s.indexOf(\"8\") != -1 && (n - s.indexOf(\"8\") >= 11)){\n println(\"YES\")\n } else{\n println(\"NO\")\n }\n idx = idx + 1\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Codeforces1167A {\n\n def isPhoneNumber(number: String): Boolean = {\n val findResult = number.zipWithIndex.find { case (digit, _) => digit == '8' }\n if (findResult.isDefined) {\n val index = findResult.get._2\n number.length - index >= 11\n } else false\n }\n\n def main(args: Array[String]): Unit = {\n val totalTestCase = StdIn.readLine().toInt\n for (_ <- 1 to totalTestCase) {\n val _ = StdIn.readLine().trim\n val number = StdIn.readLine().trim\n val result = isPhoneNumber(number)\n println(if (result) \"YES\" else \"NO\")\n }\n }\n}\n"}], "negative_code": [], "src_uid": "bcdd7862b718d6bcc25c9aba8716d487"} {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _659D extends CodeForcesApp {\n override def apply(io: IO) = {\n val path = io[Vector[(Int, Int)]]\n val n = path.length\n val dirs = (path.sliding(2) map {case Vector((x1, y1), (x2, y2)) =>\n ((x2 - x1).signum, (y2 - y1).signum) match {\n case ( 1, _) => Dir.East\n case (-1, _) => Dir.West\n case (_, 1) => Dir.North\n case (_, -1) => Dir.South\n }\n }).toIndexedSeq\n\n val lake = {\n val (xs, ys) = path.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, n)\n }\n\n val ans = (1 until n) count {i =>\n val x = path(i)._1.toDouble\n val y = path(i)._2.toDouble\n val (nx, ny) = dirs(i - 1) match {\n case Dir.North => (x, y + 0.5)\n case Dir.East => (x + 0.5, y)\n case Dir.West => (x - 0.5, y)\n case Dir.South => (x, y - 0.5)\n }\n //debug(x, y, dirs(i-1), nx, ny, lake.contains(nx, ny))\n lake.contains(nx, ny)\n }\n\n io += ans\n }\n\n object Dir extends Enumeration {\n val North, East, West, South = Value\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sum[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default\n }\n def memoize[I] = new {\n def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val newLine: String = \"\\n\"\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def appendNewLine(): this.type = {\n println()\n this\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println((n - 4) / 2)\n}"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _659D extends CodeForcesApp {\n override def apply(io: IO) = {\n val path = io[Vector[(Int, Int)]]\n\n val lake = {\n val (xs, ys) = path.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, path.length)\n }\n\n val ans = path sliding 2 count {case Vector((x1, y1), (x2, y2)) =>\n val (dx, dy) = ((x1 - x2).signum, (y1 - y2).signum)\n val (x, y) = (x1.toDouble + 0.5*dx, y1.toDouble + 0.5*dy)\n lake.contains(x, y)\n }\n\n io += ans\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sum[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default\n }\n def memoize[I] = new {\n def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val newLine: String = \"\\n\"\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def appendNewLine(): this.type = {\n println()\n this\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "0054f9e2549900487d78fae9aa4c2d65"} {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val m = in.nextInt()\n val data = in.nextLineInt(m).sorted\n val map = data.groupBy(x => x).map(x => (x._1 -> x._2.length))\n// println(map)\n val n1 = 0.to(100).find(x => map.get(x).isEmpty).getOrElse(0)\n val map2 = map\n .collect {\n case (n, v) if n < n1 => (n -> (v - 1))\n case (n, v) => (n -> v)\n }\n .filter(x => x._2 > 0)\n\n// println(map2)\n val n2 = 0.to(100).find(x => map2.get(x).isEmpty).getOrElse(0)\n// println(n1, n2)\n println(n1 + n2)\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextLineInt(n: Int): ArrayBuffer[Int] = {\n var data = ArrayBuffer[Int]()\n n.times({\n data += nextInt()\n })\n data\n }\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n", "positive_code": [{"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n @annotation.tailrec\n def go(an: Seq[Int], a: Int, b: Int): Int =\n an match {\n case Seq() => a + b + 2\n case Seq(h, t @ _*) =>\n if (a + 1 == h) go(t, h, b)\n else if (b + 1 == h) go(t, a, h)\n else if (a == h || b == h) go(t, a, b)\n else go(Seq.empty[Int], a, b)\n }\n\n val ans = go(an.sorted, -1, -1)\n\n println(ans)\n }\n}\n"}, {"source_code": "object AFunctional extends App {\n\n val t = scala.io.StdIn.readInt()\n\n for (_ <- (0 until t)) {\n val n = scala.io.StdIn.readInt()\n\n val arrStr = scala.io.StdIn.readLine()\n val stdInArr: Array[Int] = arrStr.split(\" \").map(_.toInt)\n\n println(mex(stdInArr))\n\n }\n\n\n def mex(stdInArr: Array[Int]): Int = {\n val n = stdInArr.length\n\n val intMap = stdInArr.foldLeft(Map.empty[Int, Int]) {\n (map: Map[Int, Int], b: Int) => {\n map - b + (b -> (map.getOrElse(b, 0) + 1))\n }\n }\n\n val startAdder = 2\n (0 until n).foldLeft((0, startAdder)) {\n (mexSum_adder: (Int, Int), k: Int) => {\n val mexSum = mexSum_adder._1\n val adder = mexSum_adder._2\n\n val newAdder = intMap.get(k) match {\n case Some(count) if count >= 2 =>\n adder\n case Some(count) if count == 1 =>\n if (adder > 1) {\n 1\n } else adder\n case _ => 0\n }\n\n (mexSum + newAdder, newAdder)\n\n }\n }\n }._1\n\n\n}"}, {"source_code": "\nobject A extends App {\n import scala.collection.mutable\n\n val t = scala.io.StdIn.readInt()\n\n for (_ <- (0 until t)) {\n val n = scala.io.StdIn.readInt()\n\n val arrStr = scala.io.StdIn.readLine()\n val stdInArr = arrStr.split(\" \").map(_.toInt)\n\n val intMap = mutable.Map.empty[Int, Int]\n\n for (a <- stdInArr) {\n intMap.put(a, intMap.getOrElse(a, 0) + 1)\n }\n\n var mexSum = 0\n\n var breakIf = false\n\n var adder = 2\n\n for (k <- 0 until n) {\n intMap.get(k) match {\n case Some(count) if count >= 2 =>\n\n case Some(count) if count == 1 =>\n if(adder>1){\n adder = 1\n }\n case _ =>\n adder = 0\n }\n\n mexSum += adder\n }\n\n println(mexSum)\n\n }\n\n\n}"}], "negative_code": [], "src_uid": "e26b0b117593c159b7f01cfac66a71d1"} {"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n def minimal(a:String):String={\n if(a.length%2==1){\n return a\n }\n val a1=minimal(a slice(0,a.length/2))\n val a2=minimal(a slice(a.length/2,a.length))\n if(a1 a(start1 + i) == b(start2 + i))\n else {\n val nLength = length / 2\n (isEq(a, b, start1, start2, nLength) && isEq(a, b, start1 + nLength, start2 + nLength, nLength)) ||\n (isEq(a, b, start1 + nLength, start2, nLength) && isEq(a, b, start1, start2 + nLength, nLength))\n }\n }\n\n val in = Source.stdin.getLines()\n val str1 = in.next()\n val str2 = in.next()\n if (isEq(str1, str2, 0, 0, str1.length))\n println(\"YES\")\n else\n println(\"NO\")\n}"}, {"source_code": "\n// ----------------------------------------------------------------------------0\n// ----------------------------------------------------------------------------0\nobject Main {\n def smallest(s : String) : String = {\n if(s.length % 2 == 1) s\n else{\n val (s1,s2) = s.splitAt(s.length/2)\n val (a1,a2) = (smallest(s1),smallest(s2))\n if(a1 < a2) a1 + a2\n else a2 + a1\n }\n }\n\n def main(args: Array[String]) : Unit = {\n val a = readLine\n val b = readLine\n\n val ok = smallest(a) == smallest(b)\n if(ok){\n println(\"YES\")\n }else{\n println(\"NO\")\n }\n }\n}\n"}, {"source_code": "\n// ----------------------------------------------------------------------------0\n// ----------------------------------------------------------------------------0\nobject Main {\n def main(args: Array[String]) : Unit = {\n def equiv(a : String, b : String) : Boolean = {\n if(a == b) true\n else if(a.length % 2 == 1) false\n else {\n val (a1,a2) = a.splitAt(a.length/2)\n val (b1,b2) = b.splitAt(b.length/2)\n (equiv(a1,b1) && equiv(a2,b2)) ||\n (equiv(a2,b1) && equiv(a1,b2))\n }\n }\n def naive(a : String, b : String) : Boolean = {\n equiv(a,b)\n }\n def fast(a : String, b : String) : Boolean = {\n fast_equiv(a,b,0,a.length-1,0,b.length-1)\n }\n\n def check(sa : String, sb : String, n : Int, a0 : Int, b0 : Int) : Boolean = {\n (0 to n).forall((i) => sa(a0+i) == sb(b0+i))\n }\n def fast_equiv(sa : String,\n sb : String,\n a0 : Int, a1 : Int,\n b0 : Int, b1 : Int) : Boolean = {\n val n = a1 - a0\n if(check(sa,sb,n,a0,b0)) true\n else if(n % 2 == 0) false\n else {\n val c = a0 + n/2\n val d = b0 + n/2\n val e = c + 1\n val f = d + 1\n (fast_equiv(sa,sb,a0,c,b0,d) && fast_equiv(sa,sb,e,a1,f,b1)) ||\n (fast_equiv(sa,sb,a0,c,f,b1) && fast_equiv(sa,sb,e,a1,b0,d))\n }\n }\n\n def main() : Unit = {\n val a = readLine()\n val b = readLine()\n val ans = naive(a,b)\n if(ans){\n println(\"YES\")\n }else{\n println(\"NO\")\n }\n }\n main()\n }\n}\n"}, {"source_code": "object EquivalentStrings {\n\n def main(args: Array[String]) {\n //read the strings\n val a = readLine\n val b = readLine\n\n if(lexicoHash(a) == lexicoHash(b))\n printf(\"YES\")\n else\n printf(\"NO\")\n\n }\n\n def lexicoHash(string: String) : String = {\n if(string.length % 2 == 1)\n return string\n\n var rightHalf = lexicoHash(string.substring(0, string.length / 2))\n var leftHalf = lexicoHash(string.substring(string.length / 2, string.length))\n\n if(rightHalf > leftHalf)\n return leftHalf + rightHalf\n else return rightHalf + leftHalf\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\n/**\n * Created by slie742 on 18/09/2015.\n */\nobject EquivalentStrings {\n\n def canonical(s: String) : String = {\n if (s.length%2 != 0) s\n else {\n val s1 = canonical(s.take(s.length/2))\n val s2 = canonical(s.drop(s.length/2))\n if (s1 <= s2) s1 + s2 else s2 + s1\n }\n }\n\n def equivalent(a: String, b: String) : Boolean = {\n //println(s\"$a $b\")\n if (a == b ) true\n else if (a.length%2 != 0 || a.sorted != b.sorted) false\n else {\n val a1 = a.take(a.length/2)\n val a2 = a.drop(a.length/2)\n val b1 = b.take(a.length/2)\n val b2 = b.drop(b.length/2)\n (equivalent(a1,b1) && equivalent(a2,b2)) || (equivalent(a1,b2) && equivalent(a2,b1))\n }\n }\n\n def main(args: Array[String]): Unit = {\n val s1 = readLine()\n val s2 = readLine()\n // if (s1.length == s2.length && equivalent(s1,s2)) println(\"YES\") else println(\"NO\")\n //println(s\"can s1 = ${canonical(s1)}\")\n //println(s\"can s2 = ${canonical(s2)}\")\n if (canonical(s1) == canonical(s2))\n println(\"YES\")\n else\n println(\"NO\")\n }\n\n}\n"}], "negative_code": [{"source_code": "import io.StdIn._\n\nobject Solution {\n def main(args: Array[String]) {\n val a = readLine()\n val b = readLine()\n\n if (gao(a, b)) println(\"YES\") else println(\"NO\")\n }\n\n private def gao(a: String, b: String): Boolean = {\n var n = a.length\n while (n % 2 == 0) {\n n /= 2\n }\n\n a.grouped(2 * n).map(_.grouped(n).toSeq.sorted.mkString).toSeq.sorted == b.grouped(2*n).map(_.grouped(n).toSeq.sorted.mkString).toSeq.sorted\n\n }\n\n}\n"}, {"source_code": "import io.StdIn._\n\nobject Solution {\n def main(args: Array[String]) {\n val a = readLine()\n val b = readLine()\n\n if (gao(a, b)) println(\"YES\") else println(\"NO\")\n }\n\n private def gao(a: String, b: String): Boolean = {\n var n = a.length\n while (n % 2 == 0) {\n n /= 2\n }\n\n a.grouped(2 * n).map(_.grouped(n).toSeq.sorted.mkString).toSeq.sorted == b.grouped(2).map(_.grouped(n).toSeq.sorted.mkString).toSeq.sorted\n\n }\n\n}\n"}, {"source_code": "import io.StdIn._\n\nobject Solution {\n def main(args: Array[String]) {\n val a = readLine()\n val b = readLine()\n\n if (gao(a, b)) println(\"YES\") else println(\"NO\")\n }\n\n private def gao(a: String, b: String): Boolean = {\n if (a == b) true\n else {\n val n = a.length\n if (n == 1) false\n else {\n if (gao(a.take(n/2), b.take(n/2)) && gao(a.drop(n/2), b.drop(n/2))) true\n else gao(a.take(n/2), b.drop(n/2)) && gao(a.drop(n/2), b.take(n/2))\n }\n }\n }\n}\n"}, {"source_code": "import io.StdIn._\n\nobject Solution {\n def main(args: Array[String]) {\n val a = readLine()\n val b = readLine()\n\n if (gao(a, b)) println(\"YES\") else println(\"NO\")\n }\n\n private def gao(a: String, b: String): Boolean = {\n var n = a.length\n while(n % 2 == 0) {\n n /= 2\n }\n\n if (n == 1) {\n a.grouped(2).map(_.sorted).toSeq.sorted == b.grouped(2).map(_.sorted).toSeq.sorted\n } else {\n a.grouped(n).toSeq.sorted == b.grouped(n).toSeq.sorted\n }\n\n }\n\n}\n"}, {"source_code": "import io.StdIn._\n\nobject Solution {\n def main(args: Array[String]) {\n val a = readLine()\n val b = readLine()\n\n if (gao(a, b)) println(\"YES\") else println(\"NO\")\n }\n\n private def gao(a: String, b: String): Boolean = {\n var n = a.length\n while(n % 2 == 0) {\n n /= 2\n }\n\n if (n == 1) {\n a.grouped(2).map(_.sorted).toSeq.sorted == b.grouped(2).map(_.sorted).toSeq.sorted\n } else {\n a.grouped(2).toSeq.sorted == b.grouped(2).toSeq.sorted\n }\n\n }\n\n}\n"}, {"source_code": "object EquivalentStrings {\n\n //big prime number\n val PRIME = 666013\n\n def main(args: Array[String]) {\n //read the strings\n val a = readLine\n val b = readLine\n\n if(equivalent(a,b))\n printf(\"YES\")\n else printf(\"NO\")\n\n }\n\n //hash the string in order to see if it contains the same characters\n def hash(string: String) : Int = {\n var value = 1\n for(char <- string)\n value = value * char.toInt % PRIME\n\n return value\n }\n\n def equivalent(a: String, b: String) : Boolean = {\n if(a == b)\n return true\n if(hash(a) != hash(b))\n return false\n\n //split the strings\n val a1 = a.substring(0, a.length / 2)\n val a2 = a.substring(a.length / 2, a.length)\n val b1 = b.substring(0, b.length / 2)\n val b2 = b.substring(b.length / 2, b.length)\n\n if(hash(a1) == hash(b1) && hash(a2) == hash(b2))\n return if(equivalent(a1,b1) && equivalent (a2,b2)) true else false\n\n if(hash(a1) == hash(b2) && hash(a2) == hash(b1))\n return if(equivalent(a1,b2) && equivalent(a2,b1)) true else false\n\n return false\n }\n\n\n}\n"}, {"source_code": "object EquivalentStrings {\n\n def main(args: Array[String]) {\n //read the strings\n val a = readLine\n val b = readLine\n\n if(lexicoHash(a) == lexicoHash(b))\n printf(\"YES\")\n else\n printf(\"NO\")\n\n }\n\n def lexicoHash(string: String) : String = {\n if(string.length == 1)\n return string\n\n var rightHalf = lexicoHash(string.substring(0, string.length / 2))\n var leftHalf = lexicoHash(string.substring(string.length / 2, string.length))\n\n if(rightHalf > leftHalf)\n return leftHalf + rightHalf\n else return rightHalf + leftHalf\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\n/**\n * Created by slie742 on 18/09/2015.\n */\nobject EquivalentStrings {\n\n def equivalent(s1: String, s2: String) : Boolean = {\n if (s1 == s2) true\n else if (s1.length%2 != 0 || s1.sorted != s2.sorted) false\n else equivalent(s1.take(s1.length/2), s2.drop(s1.length/2)) ||\n equivalent(s2.take(s1.length/2), s1.drop(s1.length/2))\n }\n\n def main(args: Array[String]): Unit = {\n val s1 = readLine()\n val s2 = readLine()\n if (s1.length == s2.length && equivalent(s1,s2)) println(\"YES\") else println(\"NO\")\n }\n\n}\n"}, {"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n def myEqual(a:String,b:String):Boolean={\n if(a.length>10){\n out.println(a.length+\" \"+b.length)\n }\n if(a==b){\n return true\n }\n if(a.length!=b.length || a.length%2==1){\n if(a.length>10){\n out.println(a.length+\" \"+b.length)\n }\n return false\n }\n val a1=a slice(0,a.length/2)\n val a2=a slice(a.length/2,a.length)\n val b1=b slice(0,b.length/2)\n val b2=b slice(b.length/2,b.length)\n if(a.length>10){\n out.println(a.length+\" \"+b.length)\n }\n return myEqual(a1,b2) && myEqual(a2,b1)\n }\n val a=nextString\n val b=nextString\n if(myEqual(a,b)){\n out.println(\"YES\")\n }else{\n out.println(\"NO\")\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n def myEqual(a:String,b:String):Boolean={\n if(a.length>10){\n out.println(a.length+\" \"+b.length)\n }\n if(a==b){\n return true\n }\n if(a.length!=b.length || a.length%2==1){\n out.println(a.length+\" \"+b.length)\n return false\n }\n val a1=a slice(0,a.length/2)\n val a2=a slice(a.length/2,a.length)\n val b1=b slice(0,b.length/2)\n val b2=b slice(b.length/2,b.length)\n \n return myEqual(a1,b2) && myEqual(a2,b1)\n }\n val a=nextString\n val b=nextString\n if(myEqual(a,b)){\n out.println(\"YES\")\n }else{\n out.println(\"NO\")\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n def myEqual(a:String,b:String):Boolean={\n if(a.length>10){\n out.println(a.length+\" \"+b.length)\n }\n if(a==b){\n return true\n }\n if(a.length!=b.length || a.length%2==1){\n return false\n }\n val a1=a slice(0,a.length/2)\n val a2=a slice(a.length/2,a.length)\n val b1=b slice(0,b.length/2)\n val b2=b slice(b.length/2,b.length)\n \n return myEqual(a1,b2) && myEqual(a2,b1)\n }\n val a=nextString\n val b=nextString\n if(myEqual(a,b)){\n out.println(\"YES\")\n }else{\n out.println(\"NO\")\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n def myEqual(a:String,b:String):Boolean={\n if(a==b){\n return true\n }\n if(a.length!=b.length || a.length%2==1){\n return false\n }\n val a1=a slice(0,a.length/2)\n val a2=a slice(a.length/2,a.length)\n val b1=b slice(0,b.length/2)\n val b2=b slice(b.length/2,b.length)\n \n return myEqual(a1,b2) && myEqual(a2,b1)\n }\n val a=nextString\n val b=nextString\n if(myEqual(a,b)){\n out.println(\"YES\")\n }else{\n out.println(\"NO\")\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n def myEqual(a:String,b:String):Boolean={\n if(a.length>10){\n out.println(a.length+\" \"+b.length)\n }\n if(a==b){\n return true\n }\n if(a.length!=b.length || a.length%2==1){\n if(a.length>10){\n out.println(a.length+\" \"+b.length)\n }\n return false\n }\n val a1=a slice(0,a.length/2)\n val a2=a slice(a.length/2,a.length)\n val b1=b slice(0,b.length/2)\n val b2=b slice(b.length/2,b.length)\n \n return myEqual(a1,b2) && myEqual(a2,b1)\n }\n val a=nextString\n val b=nextString\n if(myEqual(a,b)){\n out.println(\"YES\")\n }else{\n out.println(\"NO\")\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n def myEqual(a:String,b:String):Boolean={\n \n if(a==b){\n return true\n }\n if(a.length!=b.length || a.length%2==1){\n \n return false\n }\n val a1=a slice(0,a.length/2)\n val a2=a slice(a.length/2,a.length)\n val b1=b slice(0,b.length/2)\n val b2=b slice(b.length/2,b.length)\n \n return myEqual(a1,b2) && myEqual(a2,b1)\n }\n val a=nextString\n val b=nextString\n if(a.length>10){\n out.println(a)\n out.println(b)\n }\n if(myEqual(a,b)){\n out.println(\"YES\")\n }else{\n out.println(\"NO\")\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "src_uid": "21c0e12347d8be7dd19cb9f43a31be85"} {"source_code": "import io.StdIn._\n\nimport scala.collection.mutable._\n\nobject Solution {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n\n def main(args: Array[String]) {\n val n = readLine.toInt\n val a = readInts(n)\n\n val d = Array.fill(5001)(0)\n val s = Array.fill(5001)(0)\n\n for (i <- 0 to n-1) {\n for (j <- 0 to i-1) {\n d(Math.abs(a(i) - a(j))) += 1\n }\n }\n\n for (i <- 1 to 5000) {\n s(i) = d(i) + s(i-1)\n }\n\n val t = n * (n - 1) / 2\n var res: Double = 0\n\n for (i <- 3 to 5000) {\n for (j <- 1 to i-2) {\n res += 1.0 * d(i) / t * d(j) / t * s(i-j-1) / t\n }\n }\n\n println(res)\n\n// Console.withOut(new java.io.BufferedOutputStream(Console.out))\n// println(res.mkString(\"\\n\"))\n// Console.flush\n }\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n\n val cntNeg, cntPos = Array.fill(5000)(0L)\n\n for (i <- 0 until n) {\n for (j <- 0 until n) if (i != j) {\n val d = as(i) - as(j)\n if (d < 0) cntNeg(-d) += 1\n else cntPos(d) += 1\n }\n }\n\n val negSum = cntNeg.sum\n val posSum = cntPos.sum\n\n val cntNegSufSum = Array.fill(5001)(0L)\n for (i <- 4999 to 0 by -1) {\n cntNegSufSum(i) = cntNegSufSum(i + 1) + cntNeg(i)\n }\n\n var cntTot = posSum * posSum * negSum\n var cntOk = 0L\n for (d1 <- 0 until 5000) {\n for (d2 <- 0 until 5000) if (d1 + d2 < 5000) {\n //cntTot += cntPos(d1) * cntPos(d2) * negSum\n cntOk += cntPos(d1) * cntPos(d2) * cntNegSufSum(d1 + d2 + 1)\n// for (d3 <- d1 + d2 + 1 until 5000) {\n// cntOk += cntPos(d1) * cntPos(d2) * cntNeg(d3)\n// }\n }\n }\n\n println(cntOk.toDouble / cntTot)\n}"}], "negative_code": [], "src_uid": "9d55b98c75e703a554051d3088a68e59"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline private final def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n, t = ni()\n val (s, d) = na2(n)\n def f(i: Int): Long = {\n if (s(i) >= t) s(i)\n else {\n val c = ((t - s(i)) + d(i) - 1) / d(i)\n c.toLong * d(i) + s(i)\n }\n }\n debug((0 until n).map(f).mkString(\" \"))\n val ans = (0 until n).map(f).zipWithIndex.minBy(_._1)._2 + 1\n out.println(ans)\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Codeforces1153A {\n\n def findRoute(n: Int, t: Int, routes: Seq[Route]): Int = {\n val routeMeetingTimes = routes.map(route => {\n val meetingTime = getFirstMeetingTime(t, route)\n RouteMeetingTime(route, meetingTime)\n })\n\n routeMeetingTimes.minBy(routeMeetingTime => routeMeetingTime.meetingTime).route.i\n }\n\n def getFirstMeetingTime(t: Int, route: Route): Long = {\n var x = math.ceil(1.0 * (t - route.s) / route.d).toLong\n x = math.max(x - 10, 0)\n while (true) {\n if (t <= route.s + route.d * x) {\n return route.s + route.d * x\n }\n x += 1\n }\n 0\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, t) = StdIn.readLine().trim.split(\" \").map(_.toInt)\n val routes = (1 to n).map(i => {\n val Array(s, d) = StdIn.readLine().trim.split(\" \").map(_.toInt)\n Route(i, s, d)\n })\n\n val routeIndex = findRoute(n, t, routes)\n println(routeIndex)\n }\n\n case class Route(i: Int, s: Int, d: Int) {}\n\n case class RouteMeetingTime(route: Route, meetingTime: Long) {}\n\n}\n"}, {"source_code": "object Solution {\n\n case class Bus(start: Int, interval: Int)\n\n def main(args: Array[String]): Unit = {\n val in: Iterator[String] = io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(\" \").map(_.toInt)\n\n val routes = (1 to n).map { i => in.next().split(\" \").map(_.toInt)}.map { a => Bus(a(0), a(1)) }\n\n var index = 0\n var minTime = Int.MaxValue\n\n routes.zipWithIndex.foreach { case (b, i) =>\n var arrival = b.start\n while(arrival < t) {\n arrival += b.interval\n }\n if (arrival < minTime) {\n minTime = arrival\n index = i\n }\n }\n println(index + 1)\n }\n\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject Codeforces1153A {\n\n def findRoute(n: Int, t: Int, routes: Seq[Route]): Int = {\n val routeMeetingTimes = routes.map(route => {\n val meetingTime = getFirstMeetingTime(t, route)\n RouteMeetingTime(route, meetingTime)\n })\n\n routeMeetingTimes.minBy(routeMeetingTime => routeMeetingTime.meetingTime).route.i\n }\n\n def getFirstMeetingTime(t: Int, route: Route): Long = {\n val x = math.ceil(1.0 * (t - route.s) / route.d).toLong\n route.s + route.d * x\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, t) = StdIn.readLine().trim.split(\" \").map(_.toInt)\n val routes = (1 to n).map(i => {\n val Array(s, d) = StdIn.readLine().trim.split(\" \").map(_.toInt)\n Route(i, s, d)\n })\n\n val routeIndex = findRoute(n, t, routes)\n println(routeIndex)\n }\n\n case class Route(i: Int, s: Int, d: Int) {}\n\n case class RouteMeetingTime(route: Route, meetingTime: Long) {}\n\n}\n"}], "src_uid": "71be4cccd3b8c494ad7cc2d8a00cf5ed"} {"source_code": "object cf1516a {\n\n def readInt(): Int = {\n\t\tConsole.in.readLine().toInt\n\t}\n\n\tdef readInts(): Array[Int] = {\n\t\tval line = Console.in.readLine()\n\t\tline.split(' ').map( _.toInt)\n\t}\n\n\tdef main(args: Array[String]): Unit = {\n\t\tval cases = readInt()\n\t\tvar nCase = 0\n\t\tfor (nCase <- 1 to cases) {\n\t\t\tval ints = readInts()\n\t\t\tval n = ints(0)\n\t\t\tvar k = ints(1)\n\n\t\t\tval nums = readInts()\n\t\t\tvar i = 0\n\t\t\twhile ( (i < nums.size - 1) && (k > 0) ) {\n\t\t\t\tif (nums(i) <= k) {\n\t\t\t\t\tnums(nums.size-1) += nums(i)\n\t\t\t\t\tk -= nums(i)\n\t\t\t\t\tnums(i) = 0\n\t\t\t\t} else {\n\t\t\t\t\tnums(nums.size-1) += k\n\t\t\t\t\tnums(i) -= k\n\t\t\t\t\tk = 0\n\t\t\t\t}\n\t\t\t\ti += 1\n\t\t\t}\n\t\t\tprintln(nums.mkString(\" \"))\n }\n }\n}", "positive_code": [{"source_code": "object S_1516A extends App {\r\n import scala.io.StdIn.{readInt, readLine}\r\n val nInputs = readInt()\r\n for (_ <- 1 to nInputs) solveInput()\r\n\r\n def solveInput(): Unit = {\r\n val Array(_, k) = readLine().split(\" \").map(_.toInt)\r\n val arr = readLine().split(\" \").map(_.toInt)\r\n val res = solve(arr, k)\r\n println(res.mkString(\" \"))\r\n }\r\n\r\n def solve(arr: Array[Int], k: Int): Array[Int] = {\r\n @scala.annotation.tailrec\r\n def go(i: Int, k: Int, a: Int): Array[Int] = {\r\n if (k <= 0 || i >= arr.length - 1) { arr(arr.length - 1) += a; arr }\r\n else {\r\n val d = arr(i) min k\r\n arr(i) -= d\r\n go(i + 1, k - d, a + d)\r\n }\r\n }\r\n go(0, k, 0)\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "6854ad3597f9f41d475aacb774b823ed"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val s = ns()\n val ans = if (s.endsWith(\"po\")) {\n \"FILIPINO\"\n } else if (s.endsWith(\"mnida\")) {\n \"KOREAN\"\n } else {\n \"JAPANESE\"\n }\n out.println(ans)\n }\n }\n}", "positive_code": [{"source_code": "object _1281A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val s = io.read[String]\n val ans = if (s.endsWith(\"po\")) {\n \"FILIPINO\"\n } else if (s.endsWith(\"mnida\")) {\n \"KOREAN\"\n } else {\n \"JAPANESE\"\n }\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Codeforces1281A extends App {\n var t = StdIn.readLine().toInt\n while (t > 0) {\n val word = StdIn.readLine()\n if (word.endsWith(\"po\"))\n println(\"FILIPINO\")\n else if (word.endsWith(\"mnida\"))\n println(\"KOREAN\")\n else\n println(\"JAPANESE\")\n t -= 1\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject CF1281A {\n\n def main(args: Array[String]): Unit = {\n\n val n = StdIn.readLine().toInt\n (1 to n).map { _ =>\n val s = StdIn.readLine()\n if (s.endsWith(\"po\")) {\n println(\"FILIPINO\")\n }\n if (s.endsWith(\"desu\") || s.endsWith(\"masu\")) {\n println(\"JAPANESE\")\n }\n if (s.endsWith(\"mnida\")) {\n println(\"KOREAN\")\n }\n }\n }\n\n}"}], "negative_code": [{"source_code": "object _1281A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val s = io.read[String]\n val ans = if (s.endsWith(\"po\")) {\n \"FILIPINO\"\n } else if (s.endsWith(\"mnida\")) {\n \"KOREAN\"\n } else {\n \"JAPENESE\"\n }\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}], "src_uid": "816907d873bce3573ce1e5ae3f494768"} {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n private def prefix(i: Int): Long = (1L << (i + 1)) - 2L\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n\n val b = (1L << n) + prefix(n / 2 - 1)\n val a = prefix(n - 1) - prefix(n / 2 - 1)\n\n val ans = b - a\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject A {\n def solution(n: Int): Int =\n (2 << (n / 2)) - 2\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val n = readLine.toInt\n println(solution(n))\n }\n }\n}"}, {"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val numCases = in.nextInt()\n (1 to numCases).foreach{ _ =>\n val n = in.nextInt()\n val m = n/2\n val left: Long = ((1L << (m))-1L)<<(m)\n val right: Long = ((1L <<(n+1)) -1L)-left-1\n out.println((left-right).abs)\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "negative_code": [{"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val numCases = in.nextInt()\n (1 to numCases).foreach{ _ =>\n val n = in.nextInt()\n var left: Long = 0L\n var right: Long = 0L\n (1 to n by 2).foreach{ i =>\n val a = 1L << i\n val b = 1L << (i+1)\n\n if(left > right){\n left += a\n right += b\n }else{\n left += b\n right += a\n }\n }\n out.println((left-right).abs)\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "src_uid": "787a45f427c2db98b2ddb78925e0e0f1"} {"source_code": "\nimport scala.util.Sorting\nobject Proba {\ndef main(args: Array[String]) {\n val read = new java.util.StringTokenizer(readLine)\n val n=read.nextToken().toInt\n var x=read.nextToken().toLong\n val reads = new java.util.StringTokenizer(readLine)\n val a = new Array[Int](n + 1)\n for(i <- 1 to n)\n a(i) = reads.nextToken().toInt\n Sorting.quickSort(a);\n var sum:Long=0;\n for(i <- 1 to n){\n sum+=a(i)*x\n if(x>1)\n x-=1;\n }\n println(sum);\n}\n}", "positive_code": [{"source_code": "//package template\n\nobject Template {\n\tdef main(args: Array[String]) {\n\t\tvar Array(n, x) = readLine.split(\" \").map(_.toLong)\n\t\tvar input = readLine.split(' ').map(_.toLong).sorted\n\t\tvar t = 0L\n\t\tvar current_x = x\n\t\tfor(i <- input){\n\t\t\tt += current_x*i;\n\t\t\tif(current_x > 1) current_x -= 1\n\t\t}\n\t\tprint(t)\n\t}\n}"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\nobject App {\n def main(args: Array[String]) {\n\n\n var Array(n,x) = StdIn.readLine().split(\" \").map(_.toLong)\n print(StdIn.readLine()\n .split(\" \")\n .map(_.toLong)\n .sorted\n .foldLeft( 0L ) { case (r, c) =>\n var ret = r + c * x\n x = math.max(1L, x - 1L)\n ret\n\n })\n\n\n\n\n }\n\n\n}\n"}, {"source_code": "import scala.util.Sorting._\n\nobject Devu {\n def main(args: Array[String]) {\n\t val Array(n, m) = readLine().split(\" \").map(_.toLong)\n\t val d = readLine().split(\" \").map(_.toLong)\n\t quickSort(d)\n\t var x = m\n\t def f(a: Long) = {\n\t\t val t = x\n\t\t x = if (x - 1 < 1) 1 else x - 1\n\t\t a * t\n\t }\n\t println(d.map(f).reduceLeft(_ + _)) \n }\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\n/** Created by azat (mail@azat.me) on 31/01/15 */\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val scanner = new Scanner(System.in)\n var input = ArrayBuffer[Int]()\n while (scanner.hasNext) input += scanner.nextInt\n\n val n = input(0)\n val x: Long = input(1)\n val cs = input.drop(2).sorted\n val xAndSum = cs.foldLeft((x, 0l))((xAndSum, c) => (Math.max(xAndSum._1 - 1, 1), c * xAndSum._1 + xAndSum._2))\n\n println(xAndSum._2)\n }\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _439B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val x = next.toInt\n val a = (1 to n).map(i => next.toLong).sorted.toArray\n\n def doit(i: Int, cost: Int, acc: Long): Long = {\n if (i == n) acc\n else doit(i + 1, 1 max (cost - 1), acc + cost * a(i))\n }\n\n println(doit(0, x, 0))\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, x) = in.next().split(\" \").map(_.toInt)\n println(in.next().split(\" \").map(_.toInt).sorted.foldLeft((0l, x.toLong)) {\n case ((acc, 1), el) => (el + acc, 1)\n case ((acc, time), el) => (acc + el * time, time - 1)\n }._1)\n\n}"}, {"source_code": "object B439 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n var Array(n, x) = readInts(2)\n val c = readLongs(n).sorted\n var res = 0L\n for(i <- 0 until n) {\n res += c(i)*x\n if(x >= 2)\n x -=1\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "import scala.util.Sorting._\n\nobject Main {\n def main(args: Array[String]) {\n\t val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\t val d = readLine().split(\" \").map(_.toInt)\n\t quickSort(d)\n\t var x = m\n\t def f(a: Int) = {\n\t\t val t = x\n\t\t x = if (x - 1 < 1) 1 else x - 1\n\t\t a * t\n\t }\n\t println(d.map(f).reduceLeft(_ + _)) \n }\n}"}, {"source_code": "import scala.util.Sorting._\n\nobject Main {\n def main(args: Array[String]) {\n\t val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\t val d = readLine().split(\" \").map(_.toInt)\n\t quickSort(d)\n\t var x = m\n\t def f(a: Int) = {\n\t\t val t = x\n\t\t x = if (x - 1 < 1) 1 else x - 1\n\t\t a * t\n\t }\n\t println(d.map(f).reduceLeft((a: Int, b: Int) => a + b)) \n }\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\n/** Created by azat (mail@azat.me) on 31/01/15 */\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val scanner = new Scanner(System.in)\n var input = ArrayBuffer[Int]()\n while (scanner.hasNext) input += scanner.nextInt\n\n val n = input(0)\n val x = input(1)\n val cs = input.drop(2).sorted\n val xAndSum = cs.foldLeft((x, 0))((xAndSum, c) => (Math.max(xAndSum._1 - 1, 1), c * xAndSum._1 + xAndSum._2))\n\n println(xAndSum._2)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, x) = in.next().split(\" \").map(_.toInt)\n println(in.next().split(\" \").map(_.toInt).sorted.foldLeft((0l, x)) {\n case ((acc, 1), el) => (el + acc, 1)\n case ((acc, time), el) => (el * time + acc, time - 1)\n }._1)\n\n}"}, {"source_code": "//package template\n\nobject Template {\n\tdef main(args: Array[String]) {\n\t\tvar Array(n, x) = readLine.split(\" \").map(_.toInt)\n\t\tvar input = readLine.split(' ').map(_.toInt).sorted\n\t\tvar t = 0L\n\t\tvar current_x = x\n\t\tfor(i <- input){\n\t\t\tt += current_x*i;\n\t\t\tif(current_x > 1) current_x -= 1\n\t\t}\n\t\tprint(t)\n\t}\n}"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\nobject App {\n def main(args: Array[String]) {\n\n\n var Array(n,x) = StdIn.readLine().split(\" \").map(_.toInt)\n print(StdIn.readLine()\n .split(\" \")\n .map(_.toInt)\n .sorted\n .foldLeft( 0 ) { case (r, c) =>\n var ret = r + c * x\n x = math.max(1, x - 1)\n ret\n\n })\n\n\n\n\n }\n\n\n}\n"}], "src_uid": "ce27e56433175ebf9d3bbcb97e71091e"} {"source_code": "object C extends App {\n import java.{util => ju}\n\n val in = new ju.Scanner(System.in)\n (1 to in.nextInt()).foreach { _ =>\n val n = in.nextLong()\n \n def accumulateDifferences(bitIndex: Int = 0, shiftedNum: Long = 1, acc: Long = 0): Long = {\n val contribution = n / shiftedNum\n if (contribution > 0) {\n accumulateDifferences(bitIndex + 1, shiftedNum << 1, acc + contribution)\n } else acc\n }\n\n println(accumulateDifferences())\n }\n}\n", "positive_code": [{"source_code": "object C extends App {\n\n private def count(n: Long): Long = {\n\n @scala.annotation.tailrec\n def go(n: Long, c: Long): Long =\n if (n == 0L) c\n else {\n val k = (1 to 63).view.collectFirst { case i if n < (1L << i) => i }.getOrElse(0) - 1\n go(n & ~(1L << k), c - 1L + (1L << (k + 1)))\n }\n\n go(n, 0L)\n }\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readLong()\n val ans = count(n)\n\n println(ans)\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val n = readLine().toLong\n println(findK(n, 1, 2, 0))\n }\n // println(minNum(List[Boolean](false, false, true)))\n// findK(1, 1, 2, 0)\n }\n\n def findK(n: Long, i: Long, d: Long, acc: Long): Long = {\n if (n >= d / 2) findK(n, i + 1, 2 * d, acc + (((n - d / 2) / d) + 1) * i)\n else acc\n }\n\n def calcCost(tree: Array[List[Int]], nodes: Array[List[Int]]): Long = {\n def helper(visited: Array[Boolean], ind: Int, min: Int): (Int, Int, Long) = {\n val neighs = tree(ind).filter(n => !visited(n))\n neighs.foreach(visited(_) = true)\n val ourCost = nodes(ind).head\n val newMin = Math.min(min, ourCost)\n\n val costs = neighs.map(n => {\n helper(visited, n, newMin)\n }).reduce((one, two) => (one._1 + two._1, one._2 + two._2, one._3 + two._3))\n\n if (min <= ourCost) costs else {\n val posExchanges = Math.min(costs._1, costs._2)\n (costs._1 - posExchanges, costs._2 - posExchanges, costs._3 + posExchanges * ourCost)\n }\n }\n\n val visitedArr = Array.ofDim[Boolean](nodes.length + 1)\n visitedArr(1) = true\n helper(visitedArr, 1, Int.MaxValue)._3\n }\n\n def constructTree(nodes: Array[List[Int]], edges: List[List[Int]]): Array[List[Int]] = {\n val edgesNice = Array.ofDim[List[Int]](nodes.length + 1)\n for (i <- edgesNice.indices)\n edgesNice(i) = List[Int]()\n\n edges.foreach(edge => {\n edgesNice(edge.head) = edge.last :: edgesNice(edge.head)\n edgesNice(edge.last) = edge.head :: edgesNice(edge.last)\n })\n\n edgesNice.map(_.toList)\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "object C extends App {\n\n private def count(n: Long): Long = {\n\n @scala.annotation.tailrec\n def go(n: Long, c: Long): Long =\n if (n == 0L) c\n else {\n val k = (1 to 64).find(i => n < (1L << i)).getOrElse(0) - 1\n go(n & ~(1L << k), c - 1L + (1L << (k + 1)))\n }\n\n go(n, 0L)\n }\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readLong()\n val ans = count(n)\n\n println(ans)\n }\n}\n"}, {"source_code": "object C extends App {\n\n private def count(n: Long): Long = {\n\n @scala.annotation.tailrec\n def go(n: Long, c: Long): Long =\n if (n == 0L) c\n else {\n val k = (1 to 63).collectFirst { case i if n < (1L << i) => i }.getOrElse(0) - 1\n go(n & ~(1L << k), c - 1L + (1L << (k + 1)))\n }\n\n go(n, 0L)\n }\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readLong()\n val ans = count(n)\n\n println(ans)\n }\n}\n"}, {"source_code": "object C extends App {\n\n private def powof2(n: Long): Int =\n (1 to 64).find(i => n < (1L << i)).getOrElse(0) - 1\n\n private def count(n: Long): Long = {\n\n @scala.annotation.tailrec\n def go(n: Long, c: Long): Long =\n if (n == 0L) c\n else {\n val k = powof2(n)\n val k2 = (math.log10(n) / math.log10(2)).toInt\n val m = n & ~(1L << k)\n\n go(n & ~(1L << k), c - 1L + (1L << (k + 1)))\n }\n\n go(n, 0L)\n }\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readLong()\n val ans = count(n)\n\n println(ans)\n }\n}\n"}], "negative_code": [], "src_uid": "2a4f4c91522d83bc8f1ca2f086d24c3c"} {"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n readLine()\r\n val Array(k, n, m) = readLine().split(\" \").map(_.toInt)\r\n val an = readLine().split(\" \").map(_.toInt)\r\n val bm = readLine().split(\" \").map(_.toInt)\r\n\r\n @annotation.tailrec\r\n def go(i: Int, j: Int, l: Int, ops: List[Int]): Option[List[Int]] =\r\n if (i == n && j == m) Some(ops)\r\n else if (i != n && an(i) == 0) go(i + 1, j, l + 1, 0 :: ops)\r\n else if (j != m && bm(j) == 0) go(i, j + 1, l + 1, 0 :: ops)\r\n else if (i != n && j != m && an(i) <= bm(j) && an(i) <= l) go(i + 1, j, l, an(i) :: ops)\r\n else if (i != n && j != m && bm(j) <= an(i) && bm(j) <= l) go(i, j + 1, l, bm(j) :: ops)\r\n else if (i == n && bm(j) <= l) go(i, j + 1, l, bm(j) :: ops)\r\n else if (j == m && an(i) <= l) go(i + 1, j, l, an(i) :: ops)\r\n else None\r\n\r\n go(0, 0, k, List.empty[Int]) match {\r\n case Some(ops) => println(ops.reverse.mkString(\" \"))\r\n case _ => println(-1)\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n readLine()\r\n val Array(k, n, m) = readLine().split(\" \").map(_.toInt)\r\n val an = readLine().split(\" \").map(_.toInt)\r\n val bm = readLine().split(\" \").map(_.toInt)\r\n\r\n @annotation.tailrec\r\n def go(i: Int, j: Int, l: Int, ops: List[Int]): Option[List[Int]] =\r\n if (i == n && j == m) Some(ops)\r\n else if (i != n && an(i) == 0) go(i + 1, j, l + 1, 0 :: ops)\r\n else if (j != m && bm(j) == 0) go(i, j + 1, l + 1, 0 :: ops)\r\n else if (i != n && an(i) <= l) go(i + 1, j, l, an(i) :: ops)\r\n else if (j != m && bm(j) <= l) go(i, j + 1, l, bm(j) :: ops)\r\n else None\r\n\r\n go(0, 0, k, List.empty[Int]) match {\r\n case Some(ops) => println(ops.reverse.mkString(\" \"))\r\n case _ => println(-1)\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "6628bd89b4d4fdfa90d2357f7cc1b795"} {"source_code": "object CFEDU47A extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n val n = nextInt\n val m = nextInt\n val games = (new Array[Int](n)).map(_ => nextInt)\n val bills = (new Array[Int](m)).map(_ => nextInt)\n\n def buy (games: Array[Int], bills: Array[Int], bought: Int): (Array[Int], Array[Int], Int) = {\n if (games.isEmpty || bills.isEmpty)\n return (games, bills, bought)\n if (games.head <= bills.head)\n return buy(games.tail, bills.tail, bought + 1)\n else\n return buy(games.tail, bills, bought)\n }\n\n out.println(buy(games, bills, 0)._3)\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}", "positive_code": [{"source_code": "import scala.io._\n\nobject A3 {\n\n def main(args: Array[String]): Unit = {\n val lines = Source.stdin.getLines().take(3).toArray.map(_.split(' ').map(_.toInt))\n var j =0\n var count = 0\n for (i <- lines(2).indices) {\n while (j lines(2)(i)) j+=1\n if (j\n (for(_ <- 1 to n) yield {\n val x = q.dequeue()\n if(x > 1)\n q.enqueue(x - 1)\n x\n }).sum\n }.mkString(\" \")\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n val queue = new scala.collection.mutable.PriorityQueue[Int]()\n queue.enqueue(data:_*)\n val max = (1 to n).map{ _ =>\n val res = queue.dequeue()\n queue.enqueue(res - 1)\n res\n }.sum\n val queueMin = new scala.collection.mutable.PriorityQueue[Int]()\n queueMin.enqueue(data.map(-_):_*)\n val min = (1 to n).map{ _ =>\n val res = queueMin.dequeue()\n if (res != -1)\n queueMin.enqueue(res + 1)\n res\n }.sum\n println(max + \" \" + -min)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.PriorityQueue\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P218B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M = sc.nextInt\n val Planes = List.fill(M)(sc.nextInt)\n\n @tailrec\n def loop(acc: Int, n : Int, planes: PriorityQueue[Int]): Int = {\n if (n == 0) acc\n else {\n val x = planes.dequeue\n val y = x - 1\n if (y > 0) {\n planes.enqueue(x - 1)\n }\n loop(acc + x, n - 1, planes)\n }\n }\n\n val pqMax = new PriorityQueue[Int]() ++ Planes\n val max = loop(0, N, pqMax)\n val pqMin = new PriorityQueue[Int]()(Ordering.Int.reverse) ++ Planes\n val min = loop(0, N, pqMin)\n\n out.println(max + \" \" + min)\n }\n\n solve\n out.close\n}\n \n\n\n\n\n"}, {"source_code": "\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 25 Jun 2016\n */\nobject B218 extends App {\n\n def solve() = {\n val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val minPQ: mutable.PriorityQueue[Int] = mutable.PriorityQueue.empty(Ordering.fromLessThan[Int](_ > _))\n val maxPQ: mutable.PriorityQueue[Int] = mutable.PriorityQueue.empty(Ordering.fromLessThan[Int](_ < _))\n a.foreach(minPQ += _)\n a.foreach(maxPQ += _)\n\n var min = 0\n var max = 0\n\n for (i <- 0 until n) {\n val mi = minPQ.dequeue()\n min += mi\n if (mi - 1 > 0) {\n minPQ += (mi - 1)\n }\n\n val ma = maxPQ.dequeue()\n max += ma\n if (ma - 1 > 0) {\n maxPQ += (ma - 1)\n }\n }\n println(max + \" \" + min)\n }\n\n solve()\n\n}\n"}, {"source_code": "import collection.mutable._\n\nobject A extends App {\n val max = new PriorityQueue[Int]\n val min = new PriorityQueue[Int]()(new Ordering[Int] {\n def compare(x: Int, y: Int) = y.compare(x)\n })\n\n val Array(n, m) = readLine split ' ' map (_.toInt)\n val a = readLine split ' ' map (_.toInt)\n max.enqueue(a: _*)\n min.enqueue(a: _*)\n\n var ans0, ans1 = 0\n for (i <- 0 until n) {\n val x = max.dequeue\n ans0 += x\n if (x > 1) max.enqueue(x-1)\n }\n for (i <- 0 until n) {\n val x = min.dequeue\n ans1 += x\n if (x > 1) min.enqueue(x-1)\n }\n\n println(\"%d %d\" format (ans0, ans1))\n}\n"}, {"source_code": "import scala.collection.mutable.PriorityQueue\nobject Main{\n def main(args: Array[String]): Unit = {\n val maxHeap = new PriorityQueue[Int]\n val minHeap = new PriorityQueue[Int]()(new Ordering[Int] {\n def compare(x: Int, y :Int) = y.compare(x)\n })\n var ans = 0\n val temp = readLine.split(' ') map (_.toInt)\n val (n, m) = (temp(0), temp(1))\n\n val emptySeats = readLine.split(' ') map (_.toInt)\n maxHeap.enqueue(emptySeats:_*)\n minHeap.enqueue(emptySeats:_*)\n\n for (i <- 0 until n) {\n var x = maxHeap.dequeue\n ans += x\n x -= 1\n if (x > 0) maxHeap.enqueue(x)\n }\n print(ans + \" \")\n\n ans = 0\n for (i <- 0 until n) {\n var x = minHeap.dequeue\n ans += x\n x -= 1\n if (x > 0) minHeap.enqueue(x)\n }\n println(ans)\n }\n}"}, {"source_code": "object Main {\n def min(n: Int, a: TraversableOnce[Int]) = {\n var ax = scala.collection.mutable.Seq[Int]() ++ a\n (1 to n).foldLeft(0) { (sum, _) =>\n val e = ax.head\n ax(0) -= 1\n if(ax(0) == 0) ax = ax.drop(1)\n sum + e\n }\n } \n \n def max(n: Int, a: TraversableOnce[Int]) = {\n var ax = scala.collection.mutable.Seq[Int]() ++ a\n (1 to n).foldLeft(0) { (sum, _) => \n val e = ax.last\n ax(ax.size - 1) -= 1\n ax = ax.sorted\n sum + e\n }\n }\n \n def main(args: Array[String]) = {\n val nk = readLine() split(\" \") map(_.toInt)\n val a = readLine() split(\" \") map(_.toInt) sorted\n val mi = min(nk(0), a)\n val ma = max(nk(0), a)\n println(ma + \" \" + mi)\n }\n}"}, {"source_code": "import scala.collection.mutable.PriorityQueue\nimport java.util.Scanner\nobject Main {\n def main(args: Array[String]): Unit = {\n val queueDesc = new PriorityQueue[Int]()(Ordering[Int].reverse)\n val queueAsc = new PriorityQueue[Int]()\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n val m = scanner.nextInt()\n for (i <- 1 to m) {\n val a = scanner.nextInt()\n queueAsc.enqueue(a)\n queueDesc.enqueue(a)\n }\n var maximum = 0\n var minimum = 0\n for (i <- 1 to n) {\n val priceMax = queueAsc.dequeue()\n maximum += priceMax\n if (priceMax > 1)\n queueAsc.enqueue(priceMax - 1)\n val priceMin = queueDesc.dequeue()\n minimum += priceMin\n if (priceMin > 1)\n queueDesc.enqueue(priceMin - 1)\n }\n println(maximum.toString() + \" \" + minimum.toString())\n }\n}\n"}], "negative_code": [], "src_uid": "6dea4611ca210b34ae2da93ebfa9896c"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n val (sum, l) = data.foldLeft((0l, k)) {\n case ((s, 0), el) => (s + el, 0)\n case ((s, left), el) if el <= 0 => (s - el, left - 1)\n case ((s, left), el) => (s + el, left)\n }\n if (l % 2 == 0)\n println(sum)\n else\n println(sum - 2 * data.map(Math.abs).min)\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt)\n val negs = a.filter(_ < 0)\n val poss = a.filter(_ >= 0)\n \n val rest = (k - negs.size).max(0) % 2\n val add = if (rest == 1) 2 * a.map(_.abs).min else 0\n println(poss.sum - negs.take(k).sum + negs.drop(k).sum - add)\n }\n}"}, {"source_code": "object B{\n def main(args: Array[String]){\n\n val (n,k)={\n val sp= readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n var a= readLine.split(\" \").toList.map(_.toInt)\n\n val negalen=a.prefixLength(_<=0)\n if(negalen>=k){\n //先頭k個\n val (a1,a2)=a.splitAt(k)\n println(-(a1.sum)+a2.sum)\n }else{\n a=a.map(Math.abs(_))\n if((k-negalen)%2==0){\n //all +\n println(a.sum)\n }else{\n //min -> -min\n println(a.sum - 2* a.min)\n }\n }\n }\n}\n"}, {"source_code": "object Roma extends App {\n def maximize(seq: List[Int], nSwaps: Int) = {\n \tvar remainingSwaps = nSwaps\n \t\n \tvar result = seq.map {e =>\n \t\tif (e < 0 && remainingSwaps > 0) {\n \t\t\tremainingSwaps -= 1\n \t\t\t-e\n \t\t} else e\n \t}\n \t\n \tresult = if (remainingSwaps > 0) {\n \t\tif (remainingSwaps % 2 == 0) {\n \t\t\tresult\n \t\t} else {\n \t\t\tval sorted = result.sorted\n \t\t\t (-sorted.head) :: sorted.tail\n \t\t}\n \t} else {\n \t\tresult\n \t}\n \t\n \tresult.sum\n } \n \n val lines = io.Source.stdin.getLines().toList\n val params = lines.head.split(\" \")\n val swaps = params(1).toInt\n val seq = lines.last.split(\" \").toList.map(_.toInt)\n \n println(maximize(lines.last.split(\" \").toList.map(_.toInt), swaps))\n}"}, {"source_code": "object CF262B extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n var n = nextInt\n var k = nextInt\n\n var a = (for (i <- 0 until n) yield nextInt).toArray\n\n var kk = 0\n var i = 0\n var j = 0\n while (kk < k && i < n) {\n if (a(i) < 0) {\n a(i) *= -1\n kk += 1\n j = i + 1\n }\n i += 1\n }\n\n if (kk < k && (k - kk) % 2 != 0) {\n if (j == 0) {\n a(j) *= -1\n } else if (j == n || a(j - 1) < a(j)) {\n a(j - 1) *= -1\n } else {\n a(j) *= -1\n }\n }\n\n out.println(a.reduceLeft[Int](_+_))\n }\n\n try { \n solve \n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}"}, {"source_code": "object Roma {\n\n def main(args: Array[String]): Unit = {\n val Array(n: Int, k: Int) = readLine.split(' ').map(_.toInt)\n val aa: Seq[Int] = readLine.split(' ').map(_.toInt)\n\n val negCount = aa.count(_ < 0)\n val result = if (k > negCount) {\n if ((k - negCount) % 2 == 0) {\n aa.map(_.abs).sum\n }\n else {\n aa.map(_.abs).sum - 2*aa.map(_.abs).min\n }\n }\n else {\n val origSeq: Map[Int, Int] = aa.zipWithIndex.map(_.swap).toMap\n val negFlipped: Map[Int, Int] = aa.zipWithIndex\n .filter{ case (a: Int, i: Int) => a < 0 }\n .sortBy { case (a: Int, i: Int) => a }\n .take(k)\n .map { case (a: Int, i: Int) => (-1*a, i) }\n .map(_.swap)\n .toMap\n (origSeq ++ negFlipped).values.sum\n }\n\n println(result)\n }\n\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt)\n val negs = a.filter(_ < 0).reverse\n val poss = a.filter(_ >= 0)\n \n val rest = (k - negs.size).max(0) % 2\n val add = 2 * a.map(_.abs).min * rest\n println(poss.sum - negs.take(k).sum + negs.drop(k).sum - add)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt)\n val negs = a.filter(_ < 0)\n val poss = a.filter(_ >= 0)\n \n val rest = (k - negs.size).max(0) % 2\n println(poss.sum - negs.reverse.take(k).sum - (poss.min.min(-negs.max)) * rest)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt)\n val negs = a.filter(_ < 0).reverse\n val poss = a.filter(_ >= 0)\n \n val rest = (k - negs.size).max(0) % 2\n val add = - 2 * a.map(_.abs).min * rest\n println(poss.sum - negs.take(k).sum + negs.drop(k).sum - add)\n }\n}"}, {"source_code": "object Roma extends App {\ndef maximize(seq: List[Int], nSwaps: Int) = (seq.take(nSwaps).map(_ * -1) ::: seq.drop(nSwaps)).sum\n \n val lines = io.Source.stdin.getLines().toList\n val params = lines.head.split(\" \")\n val swaps = params(1).toInt\n \n println(maximize(lines.last.split(\" \").toList.map(_.toInt), swaps))\n}"}, {"source_code": "object Roma extends App {\ndef maximize(seq: List[Int], nSwaps: Int) = (seq.take(nSwaps).map(math.abs) ::: seq.drop(nSwaps)).sum\n \n val lines = io.Source.stdin.getLines().toList\n val params = lines.head.split(\" \")\n val swaps = params(1).toInt\n \n println(maximize(lines.last.split(\" \").toList.map(_.toInt), swaps))\n}"}, {"source_code": "object Roma extends App {\n def maximize(seq: List[Int], nSwaps: Int) = {\n \tvar remainingSwaps = nSwaps\n \t\n \tvar response = seq.map { e =>\n \t\tif (e < 0) {\n \t\t\tremainingSwaps -= 1\n \t\t\te * -1\n \t\t} else \te\n \t}\n \t\n \tresponse = if (remainingSwaps > 0) {\n \t\tif (remainingSwaps % 2 == 0)\n \t\t\tresponse\n \t\telse\n \t\t\t(- response.head) :: response.tail\n \t} else {\n \t\tresponse\n \t}\n \t\n \tresponse.sum\n }\n \n val lines = io.Source.stdin.getLines().toList\n val params = lines.head.split(\" \")\n val swaps = params(1).toInt\n val seq = lines.last.split(\" \").toList.map(_.toInt)\n \n println(maximize(lines.last.split(\" \").toList.map(_.toInt), swaps))\n}"}, {"source_code": "object Roma extends App {\n def maximize(seq: List[Int], nSwaps: Int) = {\n \tvar remainingSwaps = nSwaps\n \t\n \tvar response = seq.map { e =>\n \t\tif (e < 0) e * -1\n \t\telse {\n \t\t\tremainingSwaps = remainingSwaps - 1\n \t\t\te\n \t\t}\n \t}\n \t\n \tresponse = if (remainingSwaps > 0) {\n \t\tif (remainingSwaps % 2 == 0)\n \t\t\tresponse\n \t\telse\n \t\t\t(- response.head) :: response.tail\n \t} else {\n \t\tresponse\n \t}\n \t\n \tresponse.sum\n }\n \n val lines = io.Source.stdin.getLines().toList\n val params = lines.head.split(\" \")\n val swaps = params(1).toInt\n val seq = lines.last.split(\" \").toList.map(_.toInt)\n \n println(maximize(lines.last.split(\" \").toList.map(_.toInt), swaps))\n}"}, {"source_code": "object Roma extends App {\ndef maximize(seq: List[Int], nSwaps: Int) = {\n \tvar remainingSwaps = nSwaps\n \t\n \tprintln(\"Remaining swaps = \" + remainingSwaps)\n \t\n \tvar response = seq.map { e =>\n \t\tif (e < 0 && remainingSwaps > 0) {\n \t\t\tprintln(\"It is negative: \" + e)\n \t\t\tremainingSwaps -= 1\n \t\tprintln(\"Remaining swaps = \" + remainingSwaps)\n \t\t\te * -1\n \t\t\t\n \t\t} else \te\n \t}\n \t\n \tresponse = if (remainingSwaps > 0) {\n \t\tif (remainingSwaps % 2 == 0)\n \t\t\tresponse\n \t\telse\n \t\t\t(- response.head) :: response.tail\n \t} else {\n \t\tresponse\n \t}\n \t\n \tresponse.sum\n } \n \n val lines = io.Source.stdin.getLines().toList\n val params = lines.head.split(\" \")\n val swaps = params(1).toInt\n val seq = lines.last.split(\" \").toList.map(_.toInt)\n \n println(maximize(lines.last.split(\" \").toList.map(_.toInt), swaps))\n}"}, {"source_code": "object Roma extends App {\ndef maximize(seq: List[Int], nSwaps: Int) = {\n \tvar remainingSwaps = nSwaps\n \t\n \t\n \tvar response = seq.map { e =>\n \t\tif (e < 0 && remainingSwaps > 0) {\n \t\t\tremainingSwaps -= 1\n \t\t\te * -1\n \t\t\t\n \t\t} else \te\n \t}\n \t\n \tresponse = if (remainingSwaps > 0) {\n \t\tif (remainingSwaps % 2 == 0)\n \t\t\tresponse\n \t\telse\n \t\t\t(- response.head) :: response.tail\n \t} else {\n \t\tresponse\n \t}\n \t\n \tresponse.sum\n } \n \n val lines = io.Source.stdin.getLines().toList\n val params = lines.head.split(\" \")\n val swaps = params(1).toInt\n val seq = lines.last.split(\" \").toList.map(_.toInt)\n \n println(maximize(lines.last.split(\" \").toList.map(_.toInt), swaps))\n}"}, {"source_code": "object CF262B extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n var n = nextInt\n var k = nextInt\n\n var a = (for (i <- 0 until n) yield nextInt).toArray\n\n if (math.abs(a(0)) > math.abs(a(n - 1))) {\n a = a.reverse \n }\n\n var kk = 0\n var i = 0\n var j = 0\n while (kk < k && i < n) {\n if (a(i) < 0) {\n a(i) *= -1\n kk += 1\n j = i\n }\n i += 1\n }\n\n if ((k - kk) % 2 != 0) {\n j = if (j != 0 && j + 1 < n) j + 1 else j\n a(j) *= -1\n }\n\n out.println(a.reduceLeft[Int](_+_))\n }\n\n try { \n solve \n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}"}, {"source_code": "object CF262B extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n var n = nextInt\n var k = nextInt\n\n var a = (for (i <- 0 until n) yield nextInt).toArray\n\n if (math.abs(a(0)) > math.abs(a(n - 1))) {\n a = a.reverse \n }\n\n var kk = 0\n var i = 0\n while (kk < k && i < n) {\n if (a(i) < 0) {\n a(i) *= -1\n kk += 1\n }\n i += 1\n }\n\n out.println(a.reduceLeft[Int](_+_))\n }\n\n try { \n solve \n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}"}, {"source_code": "object CF262B extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n var n = nextInt\n var k = nextInt\n\n var a = (for (i <- 0 until n) yield nextInt).toArray\n\n var kk = 0\n var i = 0\n var j = 0\n while (kk < k && i < n) {\n if (a(i) < 0) {\n a(i) *= -1\n kk += 1\n j = i\n }\n i += 1\n }\n\n if (kk < k && (k - kk) % 2 != 0) {\n j = if (j != 0 && j + 1 < n) j + 1 else j\n a(j) *= -1\n }\n\n out.println(a.reduceLeft[Int](_+_))\n }\n\n try { \n solve \n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}"}, {"source_code": "object CF262B extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n var n = nextInt\n var k = nextInt\n\n var a = (for (i <- 0 until n) yield nextInt).toArray\n\n if (math.abs(a(0)) > math.abs(a(n - 1))) {\n a = a.reverse \n }\n\n var kk = 0\n var i = 0\n var j = 0\n while (kk < k && i < n) {\n if (a(i) < 0) {\n a(i) *= -1\n kk += 1\n j = i\n }\n i += 1\n }\n\n if (kk < k && (k - kk) % 2 != 0) {\n j = if (j != 0 && j + 1 < n) j + 1 else j\n a(j) *= -1\n }\n\n out.println(a.reduceLeft[Int](_+_))\n }\n\n try { \n solve \n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}"}, {"source_code": "object CF262B extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n var n = nextInt\n var k = nextInt\n\n var a = (for (i <- 0 until n) yield nextInt).toArray\n\n var kk = 0\n var i = 0\n var j = 0\n while (kk < k && i < n) {\n if (a(i) < 0) {\n a(i) *= -1\n kk += 1\n j = i + 1\n }\n i += 1\n }\n\n if (kk < k && (k - kk) % 2 != 0) {\n if (j == 0) {\n a(j) *= -1\n } else if (j == n || a(j - 1) < a(j)) {\n a(j - 1) *= 1\n } else {\n a(j) *= 1\n }\n }\n\n out.println(a.reduceLeft[Int](_+_))\n }\n\n try { \n solve \n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}"}, {"source_code": "object CF262B extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n var n = nextInt\n var k = nextInt\n\n var a = (for (i <- 0 until n) yield nextInt).toArray\n\n var kk = 0\n var i = 0\n var j = 0\n while (kk < k && i < n) {\n if (a(i) < 0) {\n a(i) *= -1\n kk += 1\n j = i + 1\n }\n i += 1\n }\n\n if (kk < k && (k - kk) % 2 != 0) {\n j = if (j == 0) j else if (j < n) j else j - 1\n a(j) *= -1\n }\n\n out.println(a.reduceLeft[Int](_+_))\n }\n\n try { \n solve \n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}"}], "src_uid": "befd3b1b4afe19ff619c0b34ed1a4966"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val line = in.next().split(' ').map(_.toInt)\n val time = in.next().split(' ').map(_.toInt)\n\n def hasSolution(endIndex: Int): Boolean = {\n val cache = Array.ofDim[Boolean](m)\n var mr = 0\n val t = (endIndex to 0 by -1).foldLeft(0) {\n case (overuse, i) if line(i) == 0 || cache(line(i) - 1) => Math.max(overuse - 1, 0)\n case (overuse, i) =>\n cache(line(i) - 1) = true\n mr += 1\n overuse + time(line(i) - 1)\n }\n t <= 0 && m == mr\n }\n\n def binary(start: Int, end: Int): Option[Int] = {\n if (start >= end) {\n None\n }\n else if (end - start == 1)\n Some(end)\n else {\n val middle = start + Math.max(1, (end - start) / 2)\n if (hasSolution(middle))\n binary(start, middle)\n else\n binary(middle, end)\n }\n }\n\n if (!hasSolution(n - 1))\n println(-1)\n else {\n println(binary(0, n - 1).get + 1)\n }\n\n\n}\n\n\n", "positive_code": [{"source_code": "import java.io._\n\nimport scala.io.Source\nimport scala.annotation.tailrec\nimport scala.collection.mutable.ListBuffer\n\nobject ProblemD3 {\n def main(args: Array[String]): Unit = processStdInOut()\n\n def processStdInOut(): Unit = {\n val src = Source.fromInputStream(System.in)\n processFromSource(src)\n }\n\n def processFromSource(src: Source): Unit = {\n try {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out));\n try {\n val lines = src.getLines()\n processLines(lines, bw)\n } finally {\n bw.flush()\n }\n } finally {\n src.close();\n }\n }\n\n // Standard code above, custom code below\n\n // Declare type aliases for readability (but not type-safety)...\n type SubjectId = Int;\n type PrepTime = Int;\n type DayIndex = Int;\n\n def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {\n val line1 = lines.next()\n val strings = line1.split(\" \")\n val n = strings(0).toInt\n val m = strings(1).toInt\n\n val line2 = lines.next()\n val d = line2.split(\" \")\n .map(_.toInt)\n .map(di => if (di == 0) None else Some(di - 1)) // zero-base the d's\n\n val line3 = lines.next()\n val a = line3.split(\" \").map(pt => pt.toInt)\n\n val soln = solve(n, m, d, a)\n soln match {\n case Some(days) => bw.write((days + 1).toString) // Make d's one-based again\n case _ => bw.write(\"-1\")\n }\n bw.newLine()\n }\n\n def solve(numDays: Int, numSubjects: Int, examByDay: Array[Option[SubjectId]], prepTimes: Array[PrepTime])\n : Option[DayIndex] = {\n\n // Get a sorted array of exam days for each subject:\n val maxPrepTimeOfAnyExam = prepTimes.max\n val examDaysBySubject = Array.fill(numSubjects)(ListBuffer[DayIndex]())\n for (dayIndex <- 0 until numDays) {\n val subjectOpt = examByDay(dayIndex)\n if (subjectOpt.isDefined) {\n val subjectId = subjectOpt.get\n if (dayIndex >= maxPrepTimeOfAnyExam || prepTimes(subjectId) <= dayIndex) {\n examDaysBySubject(subjectId).append(dayIndex)\n }\n }\n }\n\n def findDayIndexOfLastExamForSubjectOnOrBefore(subjectId: SubjectId, dayIndex: DayIndex): Option[Int] = {\n val examDays = examDaysBySubject(subjectId)\n\n @tailrec\n def binarySearch(lowerIx: Int, upperIx: Int): Int = {\n if (lowerIx == upperIx) lowerIx else {\n val midIx = (lowerIx + upperIx + 1) / 2\n val midVal = examDays(midIx)\n if ((midIx == upperIx) || (midVal == dayIndex))\n midVal\n else if (midVal > dayIndex) binarySearch(lowerIx, midIx)\n else binarySearch(midIx, upperIx)\n }\n }\n\n if (examDays.isEmpty) None else {\n val lowerVal = examDays(0)\n if (lowerVal > dayIndex) None else {\n val upperIndex = examDays.length - 1\n val upperVal = examDays(upperIndex)\n if (upperVal <= dayIndex) Some(upperVal)\n else Some(binarySearch(0, upperIndex))\n }\n }\n }\n\n def isSolution(dayIndex: DayIndex): Boolean = {\n val subjectExamDays = (0 until numSubjects).map { subjectId =>\n subjectId -> findDayIndexOfLastExamForSubjectOnOrBefore(subjectId, dayIndex)\n }\n if (!subjectExamDays.forall(_._2.isDefined)) false else {\n val sortedSubjectExamDays = subjectExamDays.map(pair => (pair._1, pair._2.get)).sortBy(_._2)\n\n def loop(sortIndex: Int, prevDayIndex: Int): Boolean = {\n val sed = sortedSubjectExamDays(sortIndex)\n val nextDayIndex = prevDayIndex + prepTimes(sed._1) + 1\n if (nextDayIndex > sed._2) false else {\n val nextSortIndex = sortIndex + 1\n if (nextSortIndex == numSubjects) true else loop(nextSortIndex, nextDayIndex)\n }\n }\n\n loop(0, -1)\n }\n }\n\n // Do a binary search to find the best solution\n @tailrec\n def search(lowerBound: DayIndex, upperBound: DayIndex): DayIndex = {\n if (lowerBound == upperBound) lowerBound else {\n val middleDay: DayIndex = (lowerBound + upperBound + 1) / 2\n if (isSolution(middleDay)) search(lowerBound, middleDay)\n else if (middleDay == upperBound) upperBound\n else search(middleDay, upperBound)\n }\n }\n\n if (examDaysBySubject.exists(_.length == 0)) None else {\n val ub: DayIndex = numDays - 1\n if (!isSolution(ub)) None\n else {\n val lowerBoundByTotalPrepAndExamTime = prepTimes.sum + numSubjects - 1\n val lowerBoundByMaxOfFirstExamDays = examDaysBySubject.map(_(0)).max\n val lowerBoundIndex = lowerBoundByMaxOfFirstExamDays max lowerBoundByTotalPrepAndExamTime\n val lb: DayIndex = lowerBoundIndex\n if (isSolution(lb)) Some(lb) else {\n if (lowerBoundIndex >= numDays) None\n else if (lowerBoundIndex == numDays - 1) Some(lb)\n else Some(search(lb, ub))\n }\n }\n }\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val line = in.next().split(' ').map(_.toInt)\n val time = in.next().split(' ').map(_.toInt)\n\n def hasSolution(endIndex: Int): Boolean = {\n val cache = Array.ofDim[Boolean](m)\n val t = (endIndex to 0 by -1).foldLeft(0) {\n case (overuse, i) if line(i) == 0 || cache(line(i) - 1) => Math.max(overuse - 1, 0)\n case (overuse, i) =>\n cache(line(i) - 1) = true\n overuse + time(line(i) - 1)\n\n }\n t <= 0\n }\n\n def binary(start: Int, end: Int): Option[Int] = {\n if (end - start == 1)\n Some(end)\n else if (start >= end) {\n None\n }\n else {\n val middle = start + Math.max(1, (end - start) / 2)\n if (hasSolution(middle))\n binary(start, middle)\n else\n binary(middle, end)\n }\n }\n\n if (!hasSolution(n - 1))\n println(-1)\n else {\n println(binary(0, n - 1).get + 1)\n }\n\n\n}\n\n\n"}], "src_uid": "ab31ad331748994ddeb08be646d0787e"} {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n val sum = an.foldLeft(0L)(_ + _)\r\n val (c, r) = (sum / n, sum % n)\r\n\r\n val ans = r * (n - r)\r\n\r\n println(ans)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n val c = an.foldLeft(0L)(_ + _) % n\r\n\r\n val ans = c * (n - c)\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "935bceb69117d06eb75121c805bff69c"} {"source_code": "object B {\n\tdef main(args: Array[String]) {\n\t\tval rawS = Console.readLine\n\n\t\tval sum = rawS.toSeq.sorted.groupBy(c => c).mapValues(_.length % 2).values.sum\n\t\t\n\t\tprintln(if(sum == 0) \"First\" else if(sum % 2 == 0) \"Second\" else \"First\")\n\t}\n}", "positive_code": [{"source_code": "\nobject B {\n def main(args: Array[String]) {\n var s = readLine()\n var r=List.range('a', 'z'+1) map(x => s count(x==)) filter (_%2==1) size;\n println(if (r == 0 || r%2==1) \"First\" else \"Second\")\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val a = readLine()\n val map = scala.collection.mutable.Map[Char, Int]()\n a.foreach(c => map(c) = map.getOrElse(c, 0) + 1)\n val count = map.values.count(_ % 2 == 1)\n if (count == 0 || count % 2 == 1) println(\"First\")\n else println(\"Second\")\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P276B extends App {\n def solve(s: String): Boolean = {\n val x = s.toCharArray.groupBy(identity[Char]).map(_._2.length % 2).filter(_ == 1).size\n (x < 2) || (x % 2 == 1)\n }\n\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n out.println(if (solve(sc.nextLine)) \"First\"\n else \"Second\")\n out.close\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val res = in.next().map(_ - 'a').foldLeft(0) {\n case(a, el) => a ^ (1 << el)\n }.toBinaryString.count(_ == '1')\n if (res < 2 || res % 2 == 1)\n println(\"First\")\n else\n println(\"Second\")\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P276B extends App {\n def solve(s: String): Boolean = false\n\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n out.println(if (solve(sc.nextLine)) \"First\"\n else \"Second\")\n\n out.flush\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P276B extends App {\n def solve(s: String): Boolean = false\n\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n out.println(if (solve(sc.nextLine)) \"First\"\n else \"Second\")\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P276B extends App {\n def solve(s: String): Boolean =\n s.toCharArray\n .groupBy(identity[Char])\n .map(_._2.length)\n .filter(_ % 2 == 0)\n .size % 2 == 1\n\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n out.println(if (solve(sc.nextLine)) \"First\"\n else \"Second\")\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P276B extends App {\n def solve(s: String): Boolean =\n s.toCharArray\n .groupBy(identity[Char])\n .map(_._2.length % 2)\n .filter(_ == 1)\n .size % 2 == 0\n\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n out.println(if (solve(sc.nextLine)) \"First\"\n else \"Second\")\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P276B extends App {\n def solve(s: String): Boolean =\n s.toCharArray.groupBy(identity[Char]).size % 2 == 0\n\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n out.println(if (solve(sc.nextLine)) \"First\"\n else \"Second\")\n out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val a = readLine()\n val map = scala.collection.mutable.Map[Char, Int]()\n a.foreach(c => map(c) = map.getOrElse(c, 0) + 1)\n if (map.values.count(_ % 2 == 1) % 2 == 1) println(\"First\")\n else println(\"Second\")\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val res = in.next().map(_ - 'a').foldLeft(0) {\n case(a, el) => a ^ (1 << el)\n }.toBinaryString.count(_ == '1') % 2 == 0\n if (!res)\n println(\"First\")\n else\n println(\"Second\")\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P276B extends App {\n def solve(s: String): Boolean =\n s.toCharArray\n .groupBy(identity[Char])\n .map(_._2.length % 2)\n .filter(_ == 1)\n .size % 2 == 1\n\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n out.println(if (solve(sc.nextLine)) \"First\"\n else \"Second\")\n out.close\n}\n"}], "src_uid": "bbf2dbdea6dd3aa45250ab5a86833558"} {"source_code": "import java.io.BufferedReader\r\nimport java.io.ByteArrayInputStream\r\nimport java.io.InputStreamReader\r\nimport java.io.PrintWriter\r\nimport scala.language.postfixOps\r\n\r\nobject CAddOne {\r\n def main(args: Array[String]): Unit = {\r\n// val start = currentTimeMillis\r\n val file = new BufferedReader(new InputStreamReader(System.in))\r\n// val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(\r\n// \"5\\n1912 1\\n5 6\\n999 1\\n88 2\\n12 100\".getBytes)))\r\n// \"1\\n12 100\".getBytes)))\r\n val out: PrintWriter = new PrintWriter(System.out)\r\n val modulo = 1000000007\r\n\r\n val cache = Array.ofDim[Long](200011)\r\n for (i <- 0 to 9) cache(i) = 1\r\n for (i <- 10 to 200010) cache(i) = (cache(i-9) + cache(i-10)) % modulo\r\n\r\n val t = file.readLine.toInt\r\n var i = 0\r\n while (i < t) {\r\n val a = file.readLine.split(\" \")\r\n val ab = a.head.toInt\r\n val b = a(1).toInt\r\n var ints = ab\r\n var sum = 0L\r\n while (ints > 0) {\r\n val i = ints % 10\r\n sum = (sum + cache(b + i)) % modulo\r\n ints /= 10\r\n }\r\n out.println(sum)\r\n i += 1\r\n }\r\n// println(currentTimeMillis - start)\r\n out.close()\r\n }\r\n}", "positive_code": [{"source_code": "import java.io.BufferedReader\r\nimport java.io.ByteArrayInputStream\r\nimport java.io.InputStreamReader\r\nimport java.io.PrintWriter\r\nimport scala.language.postfixOps\r\n\r\nobject CAddOne {\r\n def main(args: Array[String]): Unit = {\r\n// val start = currentTimeMillis\r\n val file = new BufferedReader(new InputStreamReader(System.in))\r\n// val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(\r\n// \"5\\n1912 1\\n5 6\\n999 1\\n88 2\\n12 100\".getBytes)))\r\n// \"1\\n12 100\".getBytes)))\r\n val out: PrintWriter = new PrintWriter(System.out)\r\n val modulo: Long = 1000000007\r\n\r\n val cache = Array.ofDim[Long](200011)\r\n for (i <- 0 to 9) cache(i) = 1\r\n for (i <- 10 to 200010) cache(i) = (cache(i-9) + cache(i-10)) % modulo\r\n \r\n val t = file.readLine.toInt\r\n var i = 0\r\n while (i < t) {\r\n val a = file.readLine.split(\" \").map(_.toLong)\r\n val ab = a.head\r\n val b = a(1).toInt\r\n var ints = ab\r\n var sum = 0L\r\n while (ints > 0) {\r\n val i = (ints % 10).toInt\r\n sum = (sum + cache(b + i)) % modulo\r\n ints /= 10\r\n }\r\n out.println(sum)\r\n i += 1\r\n }\r\n// println(currentTimeMillis - start)\r\n out.close()\r\n }\r\n}"}, {"source_code": "import java.io.BufferedReader\r\nimport java.io.ByteArrayInputStream\r\nimport java.io.InputStreamReader\r\nimport java.io.PrintWriter\r\nimport scala.language.postfixOps\r\n\r\nobject CAddOne {\r\n def main(args: Array[String]): Unit = {\r\n// val start = currentTimeMillis\r\n val file = new BufferedReader(new InputStreamReader(System.in))\r\n// val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(\r\n// \"5\\n1912 1\\n5 6\\n999 1\\n88 2\\n12 100\".getBytes)))\r\n// \"1\\n12 100\".getBytes)))\r\n val out: PrintWriter = new PrintWriter(System.out)\r\n val modulo = 1000000007\r\n\r\n val cache = Array.ofDim[Long](200011)\r\n for (i <- 0 to 9) cache(i) = 1\r\n for (i <- 10 to 200010) cache(i) = (cache(i-9) + cache(i-10)) % modulo\r\n\r\n val t = file.readLine.toInt\r\n var i = 0\r\n while (i < t) {\r\n val a = file.readLine.split(\" \").map(_.toInt)\r\n val ab = a.head\r\n val b = a(1)\r\n var ints = ab\r\n var sum = 0L\r\n while (ints > 0) {\r\n val i = ints % 10\r\n sum = (sum + cache(b + i)) % modulo\r\n ints /= 10\r\n }\r\n out.println(sum)\r\n i += 1\r\n }\r\n// println(currentTimeMillis - start)\r\n out.close()\r\n }\r\n}"}], "negative_code": [{"source_code": "import java.io.BufferedReader\r\nimport java.io.ByteArrayInputStream\r\nimport java.io.InputStreamReader\r\nimport java.lang.System.currentTimeMillis\r\nimport scala.language.postfixOps\r\n\r\nobject CAddOne {\r\n val modulo: Long = (Math.pow(10,9)+7).toLong\r\n\r\n val cache = Array.ofDim[Long](200005)\r\n def computeLength(x: Int, m: Long): Long = {\r\n if (m + x - 10 >= 0 && cache(m.toInt + x - 10) != 0) return cache(m.toInt + x - 10)\r\n var r: Long = 1\r\n if (m + x - 10 >= 0) {\r\n r += computeLength(1, m + x - 10) + computeLength(0, m + x - 10) - 1 % modulo\r\n cache(m.toInt + x - 10) = r\r\n }\r\n// println(s\"$x,$m: $r\")\r\n r\r\n }\r\n\r\n def solve(ab: Long, b: Long): Long = {\r\n val a = Array.ofDim[Long](10)\r\n val ints = ab.toString.map(_.toString.toInt)\r\n var sum = 0L\r\n for (i <- ints) {\r\n if (a(i) == 0) {\r\n val n = computeLength(i, b) % modulo\r\n a(i) = n\r\n }\r\n sum = (sum + a(i) % modulo)\r\n// println(\"sum:\"+sum)\r\n }\r\n// println(cache)\r\n sum\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val start = currentTimeMillis\r\n val file = new BufferedReader(new InputStreamReader(System.in))\r\n// val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(\r\n// \"5\\n1912 1\\n5 6\\n999 1\\n88 2\\n12 100\".getBytes)))\r\n// \"1\\n12 100\".getBytes)))\r\n val t = file.readLine.toInt\r\n var i = 0\r\n while (i < t) {\r\n val a :: b :: Nil = file.readLine.split(\" \").map(_.toLong).toList\r\n println(solve(a, b))\r\n i += 1\r\n }\r\n println(currentTimeMillis - start)\r\n }\r\n}"}], "src_uid": "529cf248a86a5ec9c3b3fa8acf8805da"} {"source_code": "import java.io._\nimport java.util\nimport java.util._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n val MODULO = (1e9 + 7).toInt\n\n def sum(a: Int, b: Int): Int = {\n val sum = a + b\n val res = if (sum < MODULO) sum else sum - MODULO\n return res\n }\n\n def multiply(a: Int, b: Int): Int = {\n return (1L * a * b % MODULO).toInt\n }\n\n def calcHash(ch: Array[Char]): Int = {\n var hash = 0\n val len = ch.length\n for (i <- 0 until len) {\n hash = multiply(hash, 31)\n hash = sum(hash, (ch(i) - 'a') + 1)\n }\n return hash\n }\n\n class HashString(val s: Array[Char], val hash: Int) {\n\n def this(xs: Array[Char]) {\n this(xs, calcHash(xs))\n }\n\n override def hashCode(): Int = hash\n\n override def equals(obj: scala.Any): Boolean = {\n val s1 = obj.asInstanceOf[HashString]\n return Arrays.equals(s, s1.s)\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val pow = new Array[Int](6e5.toInt)\n pow(0) = 1\n for (i <- 1 until pow.length) {\n pow(i) = multiply(pow(i - 1), 31)\n }\n val set = new util.HashSet[HashString]()\n for (i <- 0 until n) {\n set.add(new HashString(next.toCharArray))\n }\n (0 until m).foreach(_ => {\n val t = next.toCharArray\n val hash = calcHash(t)\n var flag = false\n for (i <- 0 until t.length\n if !flag) {\n val prev = t(i)\n for (j <- 'a' to 'z'\n if !flag) {\n if (j != prev) {\n t(i) = j\n val updHash = sum(hash, multiply(sum(MODULO - prev, j), pow(t.length - i - 1)))\n if (set.contains(new HashString(t, updHash))) {\n flag = true\n }\n }\n }\n t(i) = prev\n }\n if (flag) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n })\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}", "positive_code": [{"source_code": "import java.math.BigInteger\nimport java.util.Random\n\nimport scala.io.StdIn._\n\nobject CF291C extends App {\n val N = 600001\n val MOD = BigInteger.probablePrime(50, new Random()).longValue()\n val BASE = 4L\n\n val deg = new Array[Long](N)\n deg(0) = 1\n (1 until N) foreach (i => deg(i) = (deg(i - 1) * BASE) % MOD)\n\n def getHash(s: String): Long = {\n var hash = 0L\n (0 until s.length) foreach { i =>\n hash = (BASE * hash + (s.charAt(i) - 'a' + 1)) % MOD\n }\n hash\n }\n\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n val hashes = scala.collection.mutable.Set.empty[Long]\n (0 until n) foreach { i =>\n val str = readLine()\n val hash = getHash(str)\n hashes.add(hash)\n }\n\n (0 until m) foreach { _ =>\n val s = readLine()\n val hash = getHash(s)\n\n var found = false\n (0 until s.length) foreach { i =>\n List('a', 'b', 'c') foreach { c =>\n if (s.charAt(i) != c) {\n var now = (c - s.charAt(i)) * deg(s.length - 1 - i)\n now += MOD * 3\n now += hash\n now %= MOD\n if (hashes.contains(now)) {\n found = true\n }\n }\n }\n }\n\n if (found) println(\"YES\")\n else println(\"NO\")\n }\n}"}, {"source_code": "\nimport java.util.Scanner\n\nimport scala.collection.mutable._\n\n/**\n * Created by dimitar on 2/14/15.\n */\nobject Queries {\n\n val cache = new HashSet[String]\n val ts = new HashSet[String]\n\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val q = sc.nextInt()\n\n sc.nextLine()\n val memo = new ArrayBuffer[String]\n\n (0 until n) foreach { i =>\n val str = sc.nextLine()\n memo.append(str)\n }\n\n val ans = Array.tabulate[String](q)(_ => \"NO\")\n val queries = new HashMap[String, ArrayBuffer[Int]]\n\n val sizes = new HashSet[Int]\n (0 until q) foreach {idx =>\n val query = sc.nextLine()\n if (queries.contains(query)) {\n queries.get(query).get.append(idx)\n } else {\n val buff = new ArrayBuffer[Int]\n buff.append(idx)\n queries.put(query, buff)\n }\n sizes.add(query.size)\n }\n\n var loop = true\n for (m<-0 until memo.size if loop) {\n val str = memo(m)\n\n if (!cache.contains(str) && sizes.contains(str.length)) {\n if (str.length > 10000) {\n check(str, queries, ans)\n } else {\n val charBuff = str.toCharArray\n for (i <- 0 until str.length) {\n\n val ch = str(i)\n\n if (ch == 'a') {\n populate(charBuff, i, queries, ans, 'b', 'c')\n }\n if (ch == 'b') {\n populate(charBuff, i, queries, ans, 'a', 'c')\n }\n if (ch == 'c') {\n populate(charBuff, i, queries, ans, 'a', 'b')\n }\n\n }\n }\n cache.add(str)\n }\n\n\n if (ts.size == queries.size) {\n loop = false\n }\n }\n\n for( a<-0 until ans.length) {\n println(ans(a))\n }\n\n }\n\n\n def check(str: String, queries: HashMap[String, ArrayBuffer[Int]], ans: Array[String]): Unit = {\n queries.foreach {\n case (k,v) =>\n if (k.length == str.length) {\n var diff = 0\n var loop = true\n for (i<-0 until str.length if loop) {\n if (str(i) != k(i)) {\n diff += 1\n }\n if (diff > 1) {\n loop = false\n }\n }\n if (diff == 1) {\n v.foreach {\n idx => ans(idx) = \"YES\"\n }\n }\n }\n }\n }\n def populate(charBuff: Array[Char], ind: Int, queries: HashMap[String, ArrayBuffer[Int]],\n ans: Array[String], c1: Char, c2: Char): Unit = {\n val old = charBuff(ind)\n\n\n charBuff(ind) = c1\n val t1 = String.valueOf(charBuff)\n\n charBuff(ind) = c2\n val t2 = String.valueOf(charBuff)\n\n if (queries.contains(t1) && !ts.contains(t1)) {\n val buff = queries.get(t1).get\n buff.foreach { idx =>\n ans(idx) = \"YES\"\n }\n ts.add(t1)\n }\n\n if (queries.contains(t2) && !ts.contains(t2)) {\n val buff = queries.get(t2).get\n buff.foreach { idx =>\n ans(idx) = \"YES\"\n }\n ts.add(t2)\n }\n charBuff(ind) = old\n\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.math.BigInteger\nimport java.util.Random\n\nimport scala.io.StdIn._\n\nobject CF291C extends App {\n val N = 600001\n val MOD = BigInteger.probablePrime(50, new Random()).longValue()\n val BASE = 4L\n\n val deg = new Array[Long](N)\n deg(0) = 1\n (1 until N) foreach (i => deg(i) = (deg(i - 1) * BASE) % MOD)\n\n def getHash(s: String): Long = {\n var hash = 0L\n (0 until s.length) foreach { i =>\n hash = (BASE * hash + (s.charAt(i) - 'a' + 1)) % MOD\n }\n hash\n }\n\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n val hashes = scala.collection.mutable.Set[Long](n)\n (0 until n) foreach { i =>\n val str = readLine()\n val hash = getHash(str)\n hashes.add(hash)\n }\n\n (0 until m) foreach { _ =>\n val s = readLine()\n val hash = getHash(s)\n\n var found = false\n (0 until s.length) foreach { i =>\n List('a', 'b', 'c') foreach { c =>\n if (s.charAt(i) != c) {\n var now = (c - s.charAt(i)) * deg(s.length - 1 - i)\n now += MOD * 3\n now += hash\n now %= MOD\n if (hashes.contains(now)) {\n found = true\n }\n }\n }\n }\n\n if (found) println(\"YES\")\n else println(\"NO\")\n }\n\n}"}, {"source_code": "object CF291C extends App {\n val N = 600001\n val MOD = 1000000000000000007L\n val p = new Array[Long](N)\n p(0) = 1\n (1 until N) foreach (i => p(i) = p(i - 1) * 4 % MOD)\n\n def getHash(s: String): Long = {\n var hash = 0L\n (0 until s.length) foreach { i =>\n hash = (hash + (s.charAt(i) - 'a' + 1) * p(i)) % MOD\n }\n hash\n }\n\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n val hashes = new Array[Long](n)\n (0 until n) foreach { i =>\n val str = readLine()\n val hash = getHash(str)\n hashes(i) = hash\n }\n\n val sortedHashes = hashes.sorted\n\n (0 until m) foreach { _ =>\n val s = readLine()\n var found = false\n\n (0 until s.length) foreach { i =>\n List('a', 'b', 'c').toStream.takeWhile(_ => !found) foreach { c =>\n val str = new StringBuilder(s)\n str.setCharAt(i, c)\n val hash = getHash(str.toString())\n if (sortedHashes.contains(hash)) {\n found = true\n }\n }\n }\n\n if (found) println(\"YES\")\n else println(\"NO\")\n }\n}"}, {"source_code": "object CF291C extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n val hashes = new Array[Int](n)\n (0 until n) foreach { i =>\n val str = readLine()\n val hash = str.hashCode\n hashes(i) = hash\n }\n\n val sortedHashes = hashes.sorted\n\n (0 until m) foreach { _ =>\n val s = readLine()\n var found = false\n\n (0 until s.length) foreach { i =>\n List('a', 'b', 'c').toStream.takeWhile(_ => !found) foreach { c =>\n val str = new StringBuilder(s)\n str.setCharAt(i, c)\n val hash = str.toString().hashCode()\n if (sortedHashes.contains(hash)) {\n found = true\n }\n }\n }\n\n if (found) println(\"YES\")\n else println(\"NO\")\n }\n}"}, {"source_code": "object CF291C extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n val set = scala.collection.mutable.Set.empty[Int]\n (0 until n) foreach { _ =>\n val s = readLine().hashCode\n set += s\n }\n\n (0 until m) foreach { _ =>\n val s = readLine()\n var found = false\n\n (0 until s.length) foreach { i =>\n List('a', 'b', 'c').toStream.takeWhile(_ => !found) foreach { c =>\n val str = new StringBuilder(s)\n str.setCharAt(i, c)\n val hash = str.toString().hashCode()\n if (set.contains(hash)) {\n found = true\n }\n }\n }\n\n if (found) println(\"YES\")\n else println(\"NO\")\n }\n}"}, {"source_code": "import java.math.BigInteger\nimport java.util.Random\n\nimport scala.io.StdIn._\n\nobject CF291C extends App {\n val N = 600001\n val MOD = BigInteger.probablePrime(51, new Random()).longValue()\n val BASE = 4L\n\n val deg = new Array[Long](N)\n deg(0) = 1\n (1 until N) foreach (i => deg(i) = (deg(i - 1) * BASE) % MOD)\n\n def getHash(s: String): Long = {\n var hash = 0L\n (0 until s.length) foreach { i =>\n hash = (BASE * hash + (s.charAt(i) - 'a' + 1)) % MOD\n }\n hash\n }\n\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n val hashes = scala.collection.mutable.Set[Long](n)\n (0 until n) foreach { i =>\n val str = readLine()\n val hash = getHash(str)\n hashes.add(hash)\n }\n\n (0 until m) foreach { _ =>\n val s = readLine()\n val hash = getHash(s)\n\n var found = false\n (0 until s.length) foreach { i =>\n List('a', 'b', 'c') foreach { c =>\n if (s.charAt(i) != c) {\n var now = (c - s.charAt(i)) * deg(s.length - 1 - i)\n now += MOD * 3\n now += hash\n now %= MOD\n if (hashes.contains(now)) {\n found = true\n }\n }\n }\n }\n\n if (found) println(\"YES\")\n else println(\"NO\")\n }\n\n}"}, {"source_code": "object CF291C extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n val set = scala.collection.mutable.Set.empty[String]\n (0 until n) foreach { _ =>\n val s = readLine()\n set += s\n }\n\n (0 until m) foreach { _ =>\n val s = readLine()\n var found = false\n\n (0 until s.length) foreach { i =>\n List('a', 'b', 'c').toStream.takeWhile(_ => !found) foreach { c =>\n val str = new StringBuilder(s)\n str.setCharAt(i, c)\n if (set.contains(str.toString())) {\n found = true\n }\n }\n }\n\n if (found) println(\"YES\")\n else println(\"NO\")\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject CF291C extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n def fits(s1: String, s2: String): Boolean = {\n if (s1.length != s2.length) {\n false\n }\n\n var n = 0\n (0 until s1.length) foreach { i =>\n if (s1.charAt(i) != s2.charAt(i)) n += 1\n if (n > 1) false\n }\n\n true\n }\n\n val CUTOFF = 700\n val small = scala.collection.mutable.Set.empty[String]\n val big = scala.collection.mutable.Set.empty[String]\n (0 until n) foreach { _ =>\n val str = readLine()\n if (str.length < CUTOFF) small.add(str)\n else big.add(str)\n }\n\n (0 until m) foreach { _ =>\n val s = readLine()\n\n if (s.length < CUTOFF) {\n var found = false\n\n (0 until s.length) foreach { i =>\n List('a', 'b', 'c') foreach { c =>\n if (s.charAt(i) != c) {\n val str = new StringBuilder(s)\n str.setCharAt(i, c)\n if (small.contains(str.toString())) {\n found = true\n }\n }\n }\n }\n\n if (found) println(\"YES\")\n else println(\"NO\")\n\n } else {\n var found = false\n big.toStream.takeWhile(_ => !found) foreach { str =>\n if (fits(s, str)) found = true\n }\n if (found) println(\"YES\")\n else println(\"NO\")\n }\n }\n}\n"}, {"source_code": "object CF291C extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n val hashes = new Array[String](n)\n (0 until n) foreach { i =>\n val str = readLine()\n val hash = str.hashCode\n hashes(i) = str\n }\n\n val sortedHashes = hashes.sorted\n\n (0 until m) foreach { _ =>\n val s = readLine()\n var found = false\n\n (0 until s.length) foreach { i =>\n List('a', 'b', 'c').toStream.takeWhile(_ => !found) foreach { c =>\n val str = new StringBuilder(s)\n str.setCharAt(i, c)\n val hash = str.toString().hashCode()\n if (sortedHashes.contains(str.toString())) {\n found = true\n }\n }\n }\n\n if (found) println(\"YES\")\n else println(\"NO\")\n }\n}"}, {"source_code": "\nimport java.io._\nimport java.util\nimport java.util._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n val MODULO = (1e7 + 9).toInt\n\n def sum(a: Int, b: Int): Int = {\n val sum = a + b\n val res = if (sum < MODULO) sum else sum - MODULO\n return res\n }\n\n def multiply(a: Int, b: Int): Int = {\n return (1L * a * b % MODULO).toInt\n }\n\n def calcHash(ch: Array[Char]): Int = {\n var hash = 0\n val len = ch.length\n for (i <- 0 until len) {\n hash = multiply(hash, 31)\n hash = sum(hash, ch(i) - 'a' + 1)\n }\n return hash\n }\n\n class HashString(val s: Array[Char], val hash: Int) {\n\n def this(xs: Array[Char]) {\n this(xs, calcHash(xs))\n }\n\n override def hashCode(): Int = hash\n\n override def equals(obj: scala.Any): Boolean = {\n val s1 = obj.asInstanceOf[HashString]\n return Arrays.equals(s, s1.s)\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val pow = new Array[Int](3e5.toInt)\n pow(0) = 1\n for (i <- 1 until pow.length) {\n pow(i) = multiply(pow(i - 1), 31)\n }\n val set = new util.HashSet[HashString]()\n for (i <- 0 until n) {\n set.add(new HashString(next.toCharArray))\n }\n (0 until m).foreach(_ => {\n val t = next.toCharArray\n val hash = calcHash(t)\n var i = 0\n var flag = true\n while (flag && i < t.length) {\n val c = t(i)\n for (j <- 'a' to 'z') {\n if (j != c) {\n t(i) = j\n val updHash = sum(hash, multiply(sum(MODULO - c, c), pow(t.length - i - 1)))\n if (set.contains(new HashString(t, updHash))) {\n flag = false\n }\n }\n }\n t(i) = c\n i += 1\n }\n if (flag) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n })\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "\nimport java.util.Scanner\n\nimport scala.collection.mutable.HashMap\n\n/**\n * Created by dimitar on 2/14/15.\n */\nobject Queries {\n\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val q = sc.nextInt()\n\n sc.nextLine()\n val mapN = new HashMap[Int, (Int,Int,Int)]\n (0 until n) foreach { i =>\n\n val str = sc.nextLine()\n val as = str.filter(c => c == 'a').size\n val bs = str.filter(c => c == 'b').size\n val cs = str.filter(c => c == 'c').size\n mapN.put(i, (as,bs,cs))\n }\n\n\n (0 until q) foreach {_ =>\n val query = sc.nextLine()\n\n val qa = query.filter(c => c == 'a').size\n val qb = query.filter(c => c == 'b').size\n val qc = query.filter(c => c == 'c').size\n\n var loop = true\n var ans = \"NO\"\n for (i<-0 until n if loop) {\n val out = mapN.get(i).get\n if ((math.abs(out._1 - qa) + math.abs(out._2 - qb) + math.abs(out._3 - qc)) <= 2 && qa + qb + qc == out._1 + out._2 + out._3) {\n ans = \"YES\"\n loop = false\n }\n }\n\n println(ans)\n\n }\n\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable._\n\n/**\n * Created by dimitar on 2/14/15.\n */\nobject Queries {\n\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val q = sc.nextInt()\n\n sc.nextLine()\n val mapN = new HashMap[Int, ArrayBuffer[(Int,Int,Int, String)]]\n (0 until n) foreach { i =>\n\n val str = sc.nextLine()\n val as = str.filter(c => c == 'a').size\n val bs = str.filter(c => c == 'b').size\n val cs = str.filter(c => c == 'c').size\n val l = str.length\n if (mapN.contains(l)) {\n mapN.get(l).get.append((as,bs,cs, str))\n } else {\n val buff = new ArrayBuffer[(Int,Int,Int, String)]\n buff.append((as, bs, cs, str))\n mapN.put(l, buff)\n }\n }\n\n\n val cache = new HashMap[String, String]\n (0 until q) foreach {_ =>\n val query = sc.nextLine()\n\n if (cache.contains(query)) {\n println(cache.get(query).get)\n } else {\n\n var qa = 0\n var qb = 0\n var qc = 0\n\n query.foreach { j =>\n if (j == 'a') qa += 1\n if (j == 'b') qb += 1\n if (j == 'c') qc += 1\n }\n\n val sub = mapN.get(query.length).getOrElse(null)\n var loop = true\n var ans = \"NO\"\n\n if (sub != null) {\n for (i <- 0 until sub.length if loop) {\n val out = sub(i)\n val diff = (math.abs(out._1 - qa) + math.abs(out._2 - qb) + math.abs(out._3 - qc))\n\n if ((diff == 2 || diff == 1) && areEq(out._4, query)) {\n ans = \"YES\"\n loop = false\n }\n }\n }\n cache.put(query, ans)\n println(ans)\n }\n\n }\n\n }\n\n def areEq(s: String, q: String): Boolean = {\n var diff = 0\n var loop = true\n val mid = s.length/2 - 1\n for (i <- 0 to mid if loop) {\n if (s(i) != q(i) || s(s.length-i-2) != q(q.length -i -2)) {\n diff += 1\n }\n if (diff > 1)\n loop = false\n }\n\n return diff == 1\n }\n\n}\n"}, {"source_code": "\n\nimport java.util.Scanner\n\nimport scala.collection.mutable._\n\n/**\n * Created by dimitar on 2/14/15.\n */\nobject Queries {\n\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val q = sc.nextInt()\n\n sc.nextLine()\n val memo = new ArrayBuffer[String]\n\n (0 until n) foreach { i =>\n val str = sc.nextLine()\n memo.append(str)\n }\n\n val ans = Array.tabulate[String](q)(_ => \"NO\")\n val queries = new HashMap[String, Int]\n\n (0 until q) foreach {idx =>\n val query = sc.nextLine()\n queries.put(query, idx)\n }\n\n memo.foreach {str =>\n\n for (i<- 0 until str.length) {\n\n val ch = str(i)\n val pre = if (i == 0) \"\" else str.substring(0,i)\n val suffix = str.substring(i+1)\n\n if (ch == 'a') {\n populate(pre, suffix, queries,ans, 'b','c')\n }\n if (ch == 'b') {\n populate(pre, suffix, queries,ans, 'a', 'c')\n }\n if (ch == 'c') {\n populate(pre, suffix, queries,ans, 'a', 'b')\n }\n }\n }\n\n for( a<-0 until ans.length) {\n println(ans(a))\n }\n\n }\n\n def populate(pre: String, suffix: String, queries: HashMap[String, Int],\n ans: Array[String], c1: Char, c2: Char): Unit = {\n val t1 = pre+c1+suffix\n val t2 = pre+c2+suffix\n if (queries.contains(t1)) {\n ans(queries.get(t1).get) = \"YES\"\n }\n if (queries.contains(t2)) {\n ans(queries.get(t2).get) = \"YES\"\n }\n }\n\n}"}, {"source_code": "\nimport java.util.Scanner\n\nimport scala.collection.mutable._\n\n/**\n * Created by dimitar on 2/14/15.\n */\nobject Queries {\n\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val q = sc.nextInt()\n\n sc.nextLine()\n val mapN = new HashMap[Int, ArrayBuffer[(Int,Int,Int, String)]]\n (0 until n) foreach { i =>\n\n val str = sc.nextLine()\n val as = str.filter(c => c == 'a').size\n val bs = str.filter(c => c == 'b').size\n val cs = str.filter(c => c == 'c').size\n val l = str.length\n if (mapN.contains(l)) {\n mapN.get(l).get.append((as,bs,cs, str))\n } else {\n val buff = new ArrayBuffer[(Int,Int,Int, String)]\n buff.append((as, bs, cs, str))\n mapN.put(l, buff)\n }\n }\n\n\n val cache = new HashMap[String, String]\n (0 until q) foreach {_ =>\n val query = sc.nextLine()\n\n if (cache.contains(query)) {\n println(cache.get(query).get)\n } else {\n\n var qa = 0\n var qb = 0\n var qc = 0\n\n query.foreach { j =>\n if (j == 'a') qa += 1\n if (j == 'b') qb += 1\n if (j == 'c') qc += 1\n }\n\n val sub = mapN.get(query.length).getOrElse(null)\n var loop = true\n var ans = \"NO\"\n\n if (sub != null) {\n for (i <- 0 until sub.length if loop) {\n val out = sub(i)\n val diff = (math.abs(out._1 - qa) + math.abs(out._2 - qb) + math.abs(out._3 - qc))\n\n val adiff = math.abs(out._1 - qa)\n val bdiff = math.abs(out._2 - qb)\n val cdiff = math.abs(out._2 - qc)\n\n if ((diff == 2 || diff == 1) && !(adiff > 1) && !(bdiff > 1) && !(cdiff > 1) && areEq(out._4, query)) {\n ans = \"YES\"\n loop = false\n }\n }\n }\n cache.put(query, ans)\n println(ans)\n }\n\n }\n\n }\n\n def areEq(s: String, q: String): Boolean = {\n var diff = 0\n var loop = true\n for (i <- 0 until s.length if loop) {\n if (s(i) != q(i)) {\n diff += 1\n }\n if (diff > 1)\n loop = false\n }\n\n return diff == 1\n }\n\n}\n"}, {"source_code": "\nimport java.util.Scanner\n\nimport scala.collection.mutable.HashMap\n\n/**\n * Created by dimitar on 2/14/15.\n */\nobject Queries {\n\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val q = sc.nextInt()\n\n sc.nextLine()\n val mapN = new HashMap[Int, (Int,Int,Int)]\n (0 until n) foreach { i =>\n\n val str = sc.nextLine()\n val as = str.filter(c => c == 'a').size\n val bs = str.filter(c => c == 'b').size\n val cs = str.filter(c => c == 'c').size\n mapN.put(i, (as,bs,cs))\n }\n\n\n (0 until q) foreach {_ =>\n val query = sc.nextLine()\n\n val qa = query.filter(c => c == 'a').size\n val qb = query.filter(c => c == 'b').size\n val qc = query.filter(c => c == 'c').size\n\n var loop = true\n var ans = \"NO\"\n for (i<-0 until n if loop) {\n val out = mapN.get(i).get\n if ((math.abs(out._1 - qa) + math.abs(out._2 - qb) + math.abs(out._3 - qc)) == 2 && qa + qb + qc == out._1 + out._2 + out._3) {\n ans = \"YES\"\n loop = false\n }\n }\n\n println(ans)\n\n }\n\n }\n\n}\n"}, {"source_code": "\nimport java.util.Scanner\n\nimport scala.collection.mutable._\n\n/**\n * Created by dimitar on 2/14/15.\n */\nobject Queries {\n\n val cache = new HashSet[String]\n\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val q = sc.nextInt()\n\n sc.nextLine()\n val memo = new ArrayBuffer[String]\n\n (0 until n) foreach { i =>\n val str = sc.nextLine()\n memo.append(str)\n }\n\n val ans = Array.tabulate[String](q)(_ => \"NO\")\n val queries = new HashMap[String, ArrayBuffer[Int]]\n\n (0 until q) foreach {idx =>\n val query = sc.nextLine()\n if (queries.contains(query)) {\n queries.get(query).get.append(idx)\n } else {\n val buff = new ArrayBuffer[Int]\n buff.append(idx)\n queries.put(query, buff)\n }\n\n }\n\n memo.foreach {str =>\n\n if (!cache.contains(str)) {\n for (i <- 0 until str.length) {\n\n val ch = str(i)\n val pre = if (i == 0) \"\" else str.substring(0, i)\n val suffix = str.substring(i + 1)\n\n if (ch == 'a') {\n populate(pre, suffix, queries, ans, 'b', 'c')\n }\n if (ch == 'b') {\n populate(pre, suffix, queries, ans, 'a', 'c')\n }\n if (ch == 'c') {\n populate(pre, suffix, queries, ans, 'a', 'b')\n }\n }\n cache.add(str)\n }\n }\n\n for( a<-0 until ans.length) {\n println(ans(a))\n }\n\n }\n\n def populate(pre: String, suffix: String, queries: HashMap[String, ArrayBuffer[Int]],\n ans: Array[String], c1: Char, c2: Char): Unit = {\n val t1 = pre+c1+suffix\n val t2 = pre+c2+suffix\n if (queries.contains(t1)) {\n val buff = queries.get(t1).get\n buff.foreach { idx =>\n ans(idx) = \"YES\"\n }\n cache.add(t1)\n }\n if (queries.contains(t2)) {\n val buff = queries.get(t2).get\n buff.foreach { idx =>\n ans(idx) = \"YES\"\n }\n cache.add(t2)\n }\n\n }\n\n}\n"}, {"source_code": "\nimport java.util.Scanner\n\nimport scala.collection.mutable.HashMap\n\n/**\n * Created by dimitar on 2/14/15.\n */\nobject Queries {\n\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val q = sc.nextInt()\n\n sc.nextLine()\n val mapN = new HashMap[Int, (Int,Int,Int)]\n (0 until n) foreach { i =>\n\n val str = sc.nextLine()\n val as = str.filter(c => c == 'a').size\n val bs = str.filter(c => c == 'b').size\n val cs = str.filter(c => c == 'c').size\n mapN.put(i, (as,bs,cs))\n }\n\n\n (0 until q) foreach {_ =>\n val query = sc.nextLine()\n\n val qa = query.filter(c => c == 'a').size\n val qb = query.filter(c => c == 'b').size\n val qc = query.filter(c => c == 'c').size\n\n var loop = true\n var ans = \"NO\"\n for (i<-0 until n if loop) {\n val out = mapN.get(i).get\n val diff = (math.abs(out._1 - qa) + math.abs(out._2 - qb) + math.abs(out._3 - qc))\n if ( (diff == 1 || diff == 2) && qa + qb + qc == out._1 + out._2 + out._3) {\n ans = \"YES\"\n loop = false\n }\n }\n\n println(ans)\n\n }\n\n }\n\n}\n"}], "src_uid": "146c856f8de005fe280e87f67833c063"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n sort(A)\n\n var ans = 0L\n REP(N / 2) { i =>\n val s = A(i) + A(N - 1 - i)\n ans += s.toLong * s\n }\n\n out.println(ans)\n }\n\n def sort(a: Array[Int]): Array[Int] = {\n val n = a.length\n REP(n) { i =>\n val j = scala.util.Random.nextInt(n - i) + i\n val tmp = a(i)\n a(i) = a(j)\n a(j) = tmp\n }\n Sorting.stableSort(a)\n a\n }\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val scan = new Scanner(System.in)\n val n = scan.nextInt\n scan.nextLine\n val xs: Array[Int] = (scan.nextLine split ' ' map (_.toInt)).sorted\n val ans = (xs.take(n / 2) zip xs.drop(n / 2).reverse map { case (x, y) => (x + y).toLong * (x + y) }).sum\n println(ans)\n }\n}"}], "negative_code": [], "src_uid": "28c555fefd5c36697a5082c61d8a82b3"} {"source_code": "import scala.io.StdIn._\nobject Main extends App {\n\n val MOD = 1000000007\n val Array(n, m) = readLine.trim.split(' ').map(_.toInt)\n val maxSize = n + 2 * m - 1\n val factorial = Array.fill(maxSize + 1){1L}\n val inv = Array.fill(maxSize + 1){1L}\n val invFactorial = Array.fill(maxSize + 1){1L}\n for (i ← 2 to maxSize) {\n factorial(i) = factorial(i - 1) * i % MOD\n inv(i) = (MOD - MOD / i) * inv(MOD % i) % MOD\n invFactorial(i) = inv(i) * invFactorial(i - 1) % MOD\n }\n println(\n factorial(maxSize) * invFactorial(n - 1) % MOD * invFactorial(2 * m) % MOD\n )\n}", "positive_code": [{"source_code": "import java.io.BufferedInputStream\nimport java.util.Scanner\n\nobject Main extends App {\n val inputReader = new Scanner(new BufferedInputStream(System.in))\n val MOD = 1000000007L;\n val N = inputReader.nextInt()\n val M = inputReader.nextInt()\n val end_with = Array.ofDim[Long](N + 1, M + 1)\n val start_with = Array.ofDim[Long](N + 1, M + 1)\n for (k <- 1 to N) {\n end_with(k).update(1, 1)\n start_with(k).update(1, 1)\n }\n\n for (m <- 2 to M) {\n for (k <- 1 to N) {\n var sum = 0L;\n for (i <- 0 until k) {\n sum += end_with(k - i)(m - 1)\n }\n end_with(k).update(m, sum % MOD)\n }\n }\n\n for (m <- 2 to M) {\n for (k <- 1 to N) {\n var sum = 0L;\n for (i <- k to N) {\n sum += start_with(i)(m - 1)\n }\n start_with(k).update(m, sum % MOD)\n }\n }\n\n var result = 0L\n for (k <- 1 to N) {\n var start_at_least_k = 0L\n for (i <- k to N) {\n start_at_least_k += start_with(i)(M)\n }\n result = result + (end_with(k)(M) * (start_at_least_k % MOD)) % MOD\n }\n println(result % MOD)\n}\n"}, {"source_code": "import java.io.BufferedInputStream\nimport java.util.Scanner\n\nobject Main extends App {\n val inputReader = new Scanner(new BufferedInputStream(System.in))\n val MOD = 1000000007L;\n val N = inputReader.nextInt()\n val M = inputReader.nextInt()\n val end_with = Array.ofDim[Long](M + 1, N + 1)\n val start_with = Array.ofDim[Long](M + 1, N + 1)\n for (k <- 1 to N) {\n end_with(1).update(k, 1)\n start_with(1).update(k, 1)\n }\n\n for (m <- 2 to M) {\n for (k <- 1 to N) {\n val sum = end_with(m - 1).slice(1, k + 1).sum\n end_with(m).update(k, sum % MOD)\n }\n }\n\n for (m <- 2 to M) {\n for (k <- 1 to N) {\n val sum = start_with(m - 1).slice(k, N + 1).sum\n start_with(m).update(k, sum % MOD)\n }\n }\n\n var result = 0L\n for (k <- 1 to N) {\n val start_at_least_k = start_with(M).slice(k, N + 1).sum\n result = result + (end_with(M)(k) * (start_at_least_k % MOD)) % MOD\n }\n println(result % MOD)\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n println(f1(n, m))\n }\n def f1(n: Int, m: Int): Long = {\n val a = Array.ofDim[Long](n + 1, m)\n for(j <- 0 to n) {\n a(j)(0) = 1\n }\n for (i <- 1 until m) {\n for (j <- 0 to n) {\n for (k <- 0 to j) {\n a(j)(i) = (a(j)(i) + a(k)(i - 1)) % 1000000007L\n }\n }\n }\n val x = (for (\n i <- 1 to n;\n j <- 1 to n) yield (i, j)\n ).filter{ case (x, y) => x <= y }\n val s = x.foldLeft(0L){ case (s, (x, y)) =>\n (s + a(x - 1)(m-1) * a(n - y)(m-1)) % 1000000007L\n }\n s\n }\n def countSum(x: Int, m: Int) = {\n val a = Array.ofDim[Int](x + 1, m)\n for(j <- 1 to x) {\n a(j)(0) = 1\n }\n for (i <- 1 until m) {\n for (j <- 1 to x) {\n for (k <- 1 until j) {\n a(j)(i) += a(k)(i - 1)\n }\n }\n }\n // println(a.map(_.mkString(\" \")).mkString(\"\\n\"))\n val res = a(x)(m - 1)\n // println((x, m, res))\n res\n }\n def powL(x: Int, p: Int): Long = {\n if (p <= 0) 1L else (x.toLong * powL(x, p - 1)) % 1000000007L\n }\n}"}], "negative_code": [], "src_uid": "82293f824c5afbf9dbbb47eac421af33"} {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n for (_ <- 1 to t) {\n val n = nextInt\n val as, bs = nextInts(n)\n val l = (0 until n).indexWhere(i => as(i) != bs(i))\n val r = (0 until n).lastIndexWhere(i => as(i) != bs(i))\n val ok = if (l >= 0) {\n val d = bs(l) - as(l)\n d > 0 && (l to r).forall(i => bs(i) - as(i) == d)\n } else true\n\n out.println(if (ok) \"YES\" else \"NO\")\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "object A1253 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var tests = readInt\n while (tests > 0) {\n val Array(n) = readInts(1)\n val a = readInts(n)\n val b = readInts(n)\n for (i <- 0 until n)\n b(i) -= a(i)\n if (b.exists(_ < 0))\n out.println(\"NO\")\n else if (b.forall(_ == 0))\n out.println(\"YES\")\n else if (b.distinct.count(_ > 0) == 1) {\n var idxs = b.zipWithIndex.filter(_._1 != 0).map(_._2)\n if (idxs.length == (idxs.last - idxs.head + 1)) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n } else {\n out.println(\"NO\")\n }\n\n tests -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "object A1253 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var tests = readInt\n while (tests > 0) {\n val Array(n) = readInts(1)\n val a = readInts(n)\n val b = readInts(n)\n for (i <- 0 until n)\n b(i) -= a(i)\n if (b.exists(_ < 0))\n out.println(\"NO\")\n else {\n if (b.distinct.count(_ > 0) == 0)\n out.println(\"YES\")\n else if (b.distinct.count(_ > 0) != 1)\n out.println(\"NO\")\n else {\n var res = 0\n var i = 1\n var change = 0\n while (i < n) {\n if (b(i) != b(i - 1)) {\n change += 1\n }\n i += 1\n }\n if (change > 2)\n out.println(\"NO\")\n else\n out.println(\"YES\")\n }\n }\n\n tests -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "0e0ef011ebe7198b7189fce562b7d6c1"} {"source_code": "import scala.collection.mutable\n\nobject D {\n\n def main(args: Array[String]): Unit = {}\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val precedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val res = Array.ofDim[Int](m)\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n res(i) = if (u > v) 2 else 1\n precedingBuilders(v - 1) += u - 1\n }\n\n val preceding = precedingBuilders.map(_.result)\n\n var hasCycle = false\n val color = Array.fill(n)(0)\n\n def dfs0(u: Int): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceding(u).length) {\n val v = preceding(u)(i)\n if (color(v) == 0) dfs0(v)\n else if (color(v) == 1) hasCycle = true\n i += 1\n }\n color(u) = 2\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs0(i)\n\n if (hasCycle) {\n System.out.println(2)\n System.out.println(res.mkString(\" \"))\n } else {\n System.out.println(1)\n System.out.println(Array.fill(m)(1).mkString(\" \"))\n }\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, M = ni()\n val (from, to) = na2(M, -1)\n val g = packDGraph(N, from, to)\n if (topologicalSort(g) != null) {\n out.println(1)\n val ans = map(M){_ => 1 }\n out.println(ans.mkString(\" \"))\n } else {\n out.println(2)\n val ans = Array.ofDim[Int](M)\n REP(M) { i =>\n ans(i) = if (from(i) < to(i)) 1 else 2\n }\n out.println(ans.mkString(\" \"))\n }\n }\n\n def packDGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n REP(m)(i => p(from(i)) += 1)\n REP(n)(i => t(i) = new Array(p(i)))\n REP_r(m) { i => // 順序維持する\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n }\n t\n }\n /**\n * @return 閉路の場合はnull\n */\n def topologicalSort(g: Array[Array[Int]]): Array[Int] = {\n val n = g.length\n val L = Array.ofDim[Int](n)\n var ptr = 0\n val S = Array.ofDim[Int](n)\n var last, cur = 0\n val deg = Array.ofDim[Int](n)\n REP(n) { i =>\n REP(g(i).length) { j =>\n deg(g(i)(j)) += 1\n }\n }\n\n REP(n) { i =>\n if (deg(i) == 0) {\n S(last) = i\n last += 1\n }\n }\n\n while(cur < last) {\n val v = S(cur)\n cur += 1\n L(ptr) = v\n ptr += 1\n\n REP(g(v).length) { i =>\n val u = g(v)(i)\n deg(u) -= 1\n if (deg(u) == 0) {\n S(last) = u\n last += 1\n }\n }\n }\n\n // 閉路チェック\n REP(n) { i =>\n if (deg(i) > 0) return null\n }\n L\n }\n}"}, {"source_code": "import scala.collection.mutable\n\nobject D {\n\n def main(args: Array[String]): Unit = {}\n val out = new java.io.PrintWriter(System.out)\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n def tokenizeLine = new java.util.StringTokenizer(in.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val precedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val res = Array.ofDim[Int](m)\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n res(i) = if (u > v) 2 else 1\n precedingBuilders(v - 1) += u - 1\n }\n\n val preceding = precedingBuilders.map(_.result)\n\n var hasCycle = false\n val color = Array.fill(n)(0)\n\n def dfs0(u: Int): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceding(u).length) {\n val v = preceding(u)(i)\n if (color(v) == 0) dfs0(v)\n else if (color(v) == 1) hasCycle = true\n i += 1\n }\n color(u) = 2\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs0(i)\n\n if (hasCycle) {\n System.out.println(2)\n System.out.println(res.mkString(\" \"))\n } else {\n System.out.println(1)\n System.out.println(Array.fill(m)(1).mkString(\" \"))\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D {\n\n def main(args: Array[String]): Unit = {}\n val out = new java.io.PrintWriter(System.out)\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n def tokenizeLine = new java.util.StringTokenizer(in.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val precedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val res = Array.ofDim[Int](m)\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n res(i) = if (u > v) 2 else 1\n precedingBuilders(v - 1) += u - 1\n }\n\n val preceding = precedingBuilders.map(_.result)\n\n var hasCycle = false\n val color = Array.fill(n)(0)\n\n def dfs0(u: Int): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceding(u).length) {\n val v = preceding(u)(i)\n if (color(v) == 0) dfs0(v)\n else if (color(v) == 1) hasCycle = true\n i += 1\n }\n color(u) = 2\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs0(i)\n\n if (hasCycle) {\n out.println(2)\n out.println(res.mkString(\" \"))\n } else {\n out.println(1)\n out.println(Array.fill(m)(1).mkString(\" \"))\n }\n\n out.flush()\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D {\n\n def main(args: Array[String]): Unit = {}\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val precedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val res = Array.ofDim[Int](m)\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n res(i) = if (u > v) 2 else 1\n precedingBuilders(v - 1) += u - 1\n }\n\n val preceding = precedingBuilders.map(_.result)\n\n var hasCycle = false\n val color = Array.fill(n)(0)\n\n def dfs0(u: Int): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceding(u).length) {\n val v = preceding(u)(i)\n if (color(v) == 0) dfs0(v)\n else if (color(v) == 1) hasCycle = true\n i += 1\n }\n color(u) = 2\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs0(i)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (hasCycle) {\n println(2)\n println(res.mkString(\" \"))\n } else {\n println(1)\n println(Array.fill(m)(1).mkString(\" \"))\n }\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val edgeTo = Array.ofDim[Int](m)\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n edgeTo(i) = v - 1\n adjBuilders(v - 1) += i\n preceedingBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val preceeding = preceedingBuilders.map(_.result)\n\n var hasCycle = false\n //val iters = Array.fill(n)(0)\n val color = Array.fill(m)(0)\n val sortedBuilder = new mutable.ArrayBuilder.ofInt\n\n val res = Array.fill(m)(1)\n\n def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceeding(u).length) {\n val v = preceeding(u)(i)\n //res(adjs(u)(i)) = 1 + step % 2\n if (color(v) == 0) dfs0(v, adjs(u)(i), step + 1)\n else if (color(v) == 1) hasCycle = true\n i += 1\n }\n color(u) = 2\n if (edge >= 0) sortedBuilder += edge\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)\n\n val sorted = sortedBuilder.result\n\n//println(sorted.mkString(\" \"))\n for (i <- sorted.indices) res(sorted(i)) = 1 + i % 2\n\n //\n// def dfs1(u: Int, u0: Int, step: Int): Unit = {\n// /*if (step > 0 && u == u0) hasCycle = true\n// else */if (iters(u) == 0) {\n// iters(u) = iter\n// var i = 0\n// while (i < adjs(u).length) {\n// val edge = adjs(u)(i)\n// res(edge) = step % 2 + 1\n// dfs1(edgeTo(edge), u0, step + 1)\n// i += 1\n// }\n// }\n// }\n//\n// var iter = 0\n// for (u <- 0 until n) {\n// if (iters(u) == 0) {\n// iter += 1\n// dfs1(u, u, 0)\n// }\n// }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (hasCycle) {\n println(2)\n println(res.mkString(\" \"))\n } else {\n println(1)\n println(Array.fill(m)(1).mkString(\" \"))\n }\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val edgeTo = Array.ofDim[Int](m)\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n edgeTo(i) = v - 1\n adjBuilders(u - 1) += i\n preceedingBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val preceeding = preceedingBuilders.map(_.result)\n\n var hasCycle = false\n //val iters = Array.fill(n)(0)\n val color = Array.fill(n)(0)\n val sortedBuilder = new mutable.ArrayBuilder.ofInt\n\n val res = Array.fill(m)(1)\n\n def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceeding(u).length) {\n val v = preceeding(u)(i)\n //res(adjs(u)(i)) = 1 + step % 2\n if (color(v) == 0) dfs0(v, 0, step + 1)\n else if (color(v) == 1) hasCycle = true\n i += 1\n }\n color(u) = 2\n sortedBuilder += u\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)\n\n// val sorted = sortedBuilder.result\n//\n// val order = Array.ofDim[Int](n)\n// for (i <- sorted.indices) {\n// order(sorted(i)) = 1 + i % 2\n// }\n\n //println(sorted.map(_ + 1).mkString(\" \"))\n //println(order.mkString(\" \"))\n //for (i <- 0 until m) res(i) = order(edgeTo(i))\n\n val visited = Array.fill(n)(false)\n\n def dfs1(u: Int, u0: Int, step: Int): Unit = {\n /*if (step > 0 && u == u0) hasCycle = true\n else */if (!visited(u)) {\n visited(u) = true\n var i = 0\n while (i < adjs(u).length) {\n val edge = adjs(u)(i)\n if (!visited(edgeTo(edge))) {\n res(edge) = step % 2 + 1\n dfs1(edgeTo(edge), u0, step + 1)\n }\n i += 1\n }\n }\n }\n//\n// var iter = 0\n for (u <- 0 until n) {\n if (!visited(u)) {\n dfs1(u, u, 0)\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (hasCycle) {\n println(2)\n println(res.mkString(\" \"))\n } else {\n println(1)\n println(Array.fill(m)(1).mkString(\" \"))\n }\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val edgeTo = Array.ofDim[Int](m)\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n edgeTo(i) = v - 1\n adjBuilders(v - 1) += i\n preceedingBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val preceeding = preceedingBuilders.map(_.result)\n\n var hasCycle = false\n val iters = Array.fill(n)(0)\n val color = Array.fill(m)(0)\n val sortedBuilder = new mutable.ArrayBuilder.ofInt\n\n val res = Array.fill(m)(1)\n\n def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceeding(u).length) {\n val v = preceeding(u)(i)\n res(adjs(u)(i)) = 1 + step % 2\n if (color(v) == 0) dfs0(v, adjs(u)(i), step + 1)\n else if (color(v) == 1) hasCycle = true\n i += 1\n }\n color(u) = 2\n //if (edge >= 0) sortedBuilder += edge\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)\n\n //val sorted = sortedBuilder.result\n\n//println(sorted.mkString(\" \"))\n //for (i <- sorted.indices) res(sorted(i)) = 1 + i % 2\n\n //\n// def dfs1(u: Int, u0: Int, step: Int): Unit = {\n// /*if (step > 0 && u == u0) hasCycle = true\n// else */if (iters(u) == 0) {\n// iters(u) = iter\n// var i = 0\n// while (i < adjs(u).length) {\n// val edge = adjs(u)(i)\n// res(edge) = step % 2 + 1\n// dfs1(edgeTo(edge), u0, step + 1)\n// i += 1\n// }\n// }\n// }\n//\n// var iter = 0\n// for (u <- 0 until n) {\n// if (iters(u) == 0) {\n// iter += 1\n// dfs1(u, u, 0)\n// }\n// }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (hasCycle) {\n println(2)\n println(res.mkString(\" \"))\n } else {\n println(1)\n println(Array.fill(m)(1).mkString(\" \"))\n }\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val edgeTo = Array.ofDim[Int](m)\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n edgeTo(i) = u - 1\n adjBuilders(v - 1) += i\n preceedingBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val preceeding = preceedingBuilders.map(_.result)\n\n var hasCycle = false\n //val iters = Array.fill(n)(0)\n val color = Array.fill(m)(0)\n val sortedBuilder = new mutable.ArrayBuilder.ofInt\n\n val res = Array.fill(m)(1)\n\n def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceeding(u).length) {\n val v = preceeding(u)(i)\n //res(adjs(u)(i)) = 1 + step % 2\n if (color(v) == 0) dfs0(v, adjs(u)(i), step + 1)\n else if (color(v) == 1) hasCycle = true\n i += 1\n }\n color(u) = 2\n sortedBuilder += u\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)\n\n val sorted = sortedBuilder.result\n\n val order = Array.ofDim[Int](n)\n for (i <- sorted.indices) {\n order(sorted(i)) = 1 + i % 2\n }\n\n //println(sorted.mkString(\" \"))\n //println(order.mkString(\" \"))\n for (i <- 0 until m) res(i) = order(edgeTo(i))\n\n //\n// def dfs1(u: Int, u0: Int, step: Int): Unit = {\n// /*if (step > 0 && u == u0) hasCycle = true\n// else */if (iters(u) == 0) {\n// iters(u) = iter\n// var i = 0\n// while (i < adjs(u).length) {\n// val edge = adjs(u)(i)\n// res(edge) = step % 2 + 1\n// dfs1(edgeTo(edge), u0, step + 1)\n// i += 1\n// }\n// }\n// }\n//\n// var iter = 0\n// for (u <- 0 until n) {\n// if (iters(u) == 0) {\n// iter += 1\n// dfs1(u, u, 0)\n// }\n// }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (hasCycle) {\n println(2)\n println(res.mkString(\" \"))\n } else {\n println(1)\n println(Array.fill(m)(1).mkString(\" \"))\n }\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val edgeTo = Array.ofDim[Int](m)\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n edgeTo(i) = u - 1\n adjBuilders(v - 1) += i\n preceedingBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val preceeding = preceedingBuilders.map(_.result)\n\n var hasCycle = false\n //val iters = Array.fill(n)(0)\n val color = Array.fill(m)(0)\n val sortedBuilder = new mutable.ArrayBuilder.ofInt\n\n val res = Array.fill(m)(1)\n\n def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceeding(u).length) {\n val v = preceeding(u)(i)\n //res(adjs(u)(i)) = 1 + step % 2\n if (color(v) == 0) dfs0(v, adjs(u)(i), step + 1)\n else if (color(v) == 1) hasCycle = true\n i += 1\n }\n color(u) = 2\n sortedBuilder += u\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)\n\n val sorted = sortedBuilder.result\n\n val order = Array.ofDim[Int](n)\n for (i <- sorted.indices) {\n order(sorted(i)) = 1 + i % 2\n }\n\n println(sorted.mkString(\" \"))\n println(order.mkString(\" \"))\n for (i <- 0 until m) res(i) = order(edgeTo(i))\n\n //\n// def dfs1(u: Int, u0: Int, step: Int): Unit = {\n// /*if (step > 0 && u == u0) hasCycle = true\n// else */if (iters(u) == 0) {\n// iters(u) = iter\n// var i = 0\n// while (i < adjs(u).length) {\n// val edge = adjs(u)(i)\n// res(edge) = step % 2 + 1\n// dfs1(edgeTo(edge), u0, step + 1)\n// i += 1\n// }\n// }\n// }\n//\n// var iter = 0\n// for (u <- 0 until n) {\n// if (iters(u) == 0) {\n// iter += 1\n// dfs1(u, u, 0)\n// }\n// }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (hasCycle) {\n println(2)\n println(res.mkString(\" \"))\n } else {\n println(1)\n println(Array.fill(m)(1).mkString(\" \"))\n }\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D {\n\n def main(args: Array[String]): Unit = {}\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val edgeTo = Array.ofDim[Int](m)\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n edgeTo(i) = v - 1\n adjBuilders(u - 1) += i\n }\n\n val adjs = adjBuilders.map(_.result)\n\n var hasCycle = false\n val iters = Array.fill(n)(0)\n val color = Array.fill(m)(0)\n\n def dfs1(u: Int, u0: Int, step: Int): Unit = {\n if (step > 0 && u == u0) hasCycle = true\n else if (iters(u) == 0) {\n iters(u) = iter\n var i = 0\n while (i < adjs(u).length) {\n val edge = adjs(u)(i)\n color(edge) = step % 2 + 1\n dfs1(edgeTo(edge), u0, step + 1)\n i += 1\n }\n }\n }\n\n var iter = 0\n for (u <- 0 until n) {\n if (iters(u) == 0) {\n iter += 1\n dfs1(u, u, 0)\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (hasCycle) {\n println(2)\n println(color.mkString(\" \"))\n } else {\n println(1)\n println(Array.fill(m)(1).mkString(\" \"))\n }\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val edgeTo = Array.ofDim[Int](m)\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n edgeTo(i) = v - 1\n adjBuilders(v - 1) += i\n preceedingBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val preceeding = preceedingBuilders.map(_.result)\n\n var hasCycle = false\n //val iters = Array.fill(n)(0)\n val color = Array.fill(m)(0)\n val sortedBuilder = new mutable.ArrayBuilder.ofInt\n\n val res = Array.fill(m)(1)\n\n def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceeding(u).length) {\n val v = preceeding(u)(i)\n //res(adjs(u)(i)) = 1 + step % 2\n if (color(v) == 0) dfs0(v, adjs(u)(i), step + 1)\n else if (color(v) == 1) hasCycle = true\n i += 1\n }\n color(u) = 2\n sortedBuilder += u\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)\n\n val sorted = sortedBuilder.result\n\n//println(sorted.mkString(\" \"))\n val order = Array.ofDim[Int](n)\n for (i <- sorted.indices) {\n order(sorted(i)) = 1 + i % 2\n }\n\n for (i <- 0 until m) res(i) = order(edgeTo(i))\n\n //\n// def dfs1(u: Int, u0: Int, step: Int): Unit = {\n// /*if (step > 0 && u == u0) hasCycle = true\n// else */if (iters(u) == 0) {\n// iters(u) = iter\n// var i = 0\n// while (i < adjs(u).length) {\n// val edge = adjs(u)(i)\n// res(edge) = step % 2 + 1\n// dfs1(edgeTo(edge), u0, step + 1)\n// i += 1\n// }\n// }\n// }\n//\n// var iter = 0\n// for (u <- 0 until n) {\n// if (iters(u) == 0) {\n// iter += 1\n// dfs1(u, u, 0)\n// }\n// }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (hasCycle) {\n println(2)\n println(res.mkString(\" \"))\n } else {\n println(1)\n println(Array.fill(m)(1).mkString(\" \"))\n }\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val edgeTo = Array.ofDim[Int](m)\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n edgeTo(i) = v - 1\n adjBuilders(u - 1) += i\n preceedingBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val preceeding = preceedingBuilders.map(_.result)\n\n var hasCycle = false\n val iters = Array.fill(n)(0)\n val color = Array.fill(m)(0)\n\n def dfs0(u: Int): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceeding(u).length) {\n val v = preceeding(u)(i)\n if (color(v) == 0) dfs0(v)\n else if (color(v) == 1) hasCycle = true\n i += 1\n }\n color(u) = 2\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs0(i)\n\n val res = Array.fill(m)(0)\n\n def dfs1(u: Int, u0: Int, step: Int): Unit = {\n /*if (step > 0 && u == u0) hasCycle = true\n else */if (iters(u) == 0) {\n iters(u) = iter\n var i = 0\n while (i < adjs(u).length) {\n val edge = adjs(u)(i)\n res(edge) = step % 2 + 1\n dfs1(edgeTo(edge), u0, step + 1)\n i += 1\n }\n }\n }\n\n var iter = 0\n for (u <- 0 until n) {\n if (iters(u) == 0) {\n iter += 1\n dfs1(u, u, 0)\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (hasCycle) {\n println(2)\n println(res.mkString(\" \"))\n } else {\n println(1)\n println(Array.fill(m)(1).mkString(\" \"))\n }\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val edgeTo = Array.ofDim[Int](m)\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n edgeTo(i) = u - 1\n adjBuilders(v - 1) += i\n preceedingBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val preceeding = preceedingBuilders.map(_.result)\n\n var hasCycle = false\n //val iters = Array.fill(n)(0)\n val color = Array.fill(n)(0)\n val sortedBuilder = new mutable.ArrayBuilder.ofInt\n\n val res = Array.fill(m)(1)\n\n def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceeding(u).length) {\n val v = preceeding(u)(i)\n //res(adjs(u)(i)) = 1 + step % 2\n if (color(v) == 0) dfs0(v, adjs(u)(i), step + 1)\n else if (color(v) == 1) hasCycle = true\n i += 1\n }\n color(u) = 2\n sortedBuilder += u\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)\n\n val sorted = sortedBuilder.result\n\n val order = Array.ofDim[Int](n)\n for (i <- sorted.indices) {\n order(sorted(i)) = 1 + i % 2\n }\n\n //println(sorted.mkString(\" \"))\n //println(order.mkString(\" \"))\n for (i <- 0 until m) res(i) = order(edgeTo(i))\n\n //\n// def dfs1(u: Int, u0: Int, step: Int): Unit = {\n// /*if (step > 0 && u == u0) hasCycle = true\n// else */if (iters(u) == 0) {\n// iters(u) = iter\n// var i = 0\n// while (i < adjs(u).length) {\n// val edge = adjs(u)(i)\n// res(edge) = step % 2 + 1\n// dfs1(edgeTo(edge), u0, step + 1)\n// i += 1\n// }\n// }\n// }\n//\n// var iter = 0\n// for (u <- 0 until n) {\n// if (iters(u) == 0) {\n// iter += 1\n// dfs1(u, u, 0)\n// }\n// }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (hasCycle) {\n println(2)\n println(res.mkString(\" \"))\n } else {\n println(1)\n println(Array.fill(m)(1).mkString(\" \"))\n }\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val edgeTo = Array.ofDim[Int](m)\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n edgeTo(i) = v - 1\n adjBuilders(u - 1) += i\n preceedingBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val preceeding = preceedingBuilders.map(_.result)\n\n var hasCycle = false\n val iters = Array.fill(n)(0)\n val color = Array.fill(m)(0)\n val sortedBuilder = new mutable.ArrayBuilder.ofInt\n\n def dfs0(u: Int, edge: Int): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceeding(u).length) {\n val v = preceeding(u)(i)\n if (color(v) == 0) dfs0(v, adjs(u)(i))\n else if (color(v) == 1) hasCycle = true\n i += 1\n }\n color(u) = 2\n if (edge >= 0) sortedBuilder += edge\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)\n\n val sorted = sortedBuilder.result\n\n val res = Array.fill(m)(1)\n//println(sorted.mkString(\" \"))\n for (i <- sorted.indices) res(sorted(i)) = 1 + i % 2\n\n //\n// def dfs1(u: Int, u0: Int, step: Int): Unit = {\n// /*if (step > 0 && u == u0) hasCycle = true\n// else */if (iters(u) == 0) {\n// iters(u) = iter\n// var i = 0\n// while (i < adjs(u).length) {\n// val edge = adjs(u)(i)\n// res(edge) = step % 2 + 1\n// dfs1(edgeTo(edge), u0, step + 1)\n// i += 1\n// }\n// }\n// }\n//\n// var iter = 0\n// for (u <- 0 until n) {\n// if (iters(u) == 0) {\n// iter += 1\n// dfs1(u, u, 0)\n// }\n// }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (hasCycle) {\n println(2)\n println(res.mkString(\" \"))\n } else {\n println(1)\n println(Array.fill(m)(1).mkString(\" \"))\n }\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val edgeTo = Array.ofDim[Int](m)\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n edgeTo(i) = v - 1\n adjBuilders(u - 1) += i\n preceedingBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val preceeding = preceedingBuilders.map(_.result)\n\n var hasCycle = false\n //val iters = Array.fill(n)(0)\n val color = Array.fill(n)(0)\n val sortedBuilder = new mutable.ArrayBuilder.ofInt\n\n val res = Array.fill(m)(1)\n\n def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceeding(u).length) {\n val v = preceeding(u)(i)\n //res(adjs(u)(i)) = 1 + step % 2\n if (color(v) == 0) dfs0(v, 0, step + 1)\n else if (color(v) == 1) hasCycle = true\n i += 1\n }\n color(u) = 2\n sortedBuilder += u\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)\n\n// val sorted = sortedBuilder.result\n//\n// val order = Array.ofDim[Int](n)\n// for (i <- sorted.indices) {\n// order(sorted(i)) = 1 + i % 2\n// }\n\n //println(sorted.map(_ + 1).mkString(\" \"))\n //println(order.mkString(\" \"))\n //for (i <- 0 until m) res(i) = order(edgeTo(i))\n\n val visited = Array.fill(n)(false)\n\n def dfs1(u: Int, u0: Int, step: Int): Unit = {\n /*if (step > 0 && u == u0) hasCycle = true\n else */if (!visited(u)) {\n visited(u) = true\n var i = 0\n while (i < adjs(u).length) {\n val edge = adjs(u)(i)\n res(edge) = step % 2 + 1\n dfs1(edgeTo(edge), u0, step + 1)\n i += 1\n }\n }\n }\n//\n// var iter = 0\n for (u <- 0 until n) {\n if (!visited(u)) {\n dfs1(u, u, 0)\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (hasCycle) {\n println(2)\n println(res.mkString(\" \"))\n } else {\n println(1)\n println(Array.fill(m)(1).mkString(\" \"))\n }\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val edgeTo = Array.ofDim[Int](m)\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n edgeTo(i) = u - 1\n adjBuilders(v - 1) += i\n preceedingBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val preceeding = preceedingBuilders.map(_.result)\n\n var hasCycle = false\n //val iters = Array.fill(n)(0)\n val color = Array.fill(n)(0)\n val sortedBuilder = new mutable.ArrayBuilder.ofInt\n\n val res = Array.fill(m)(1)\n\n def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceeding(u).length) {\n val v = preceeding(u)(i)\n //res(adjs(u)(i)) = 1 + step % 2\n if (color(v) == 0) dfs0(v, adjs(u)(i), step + 1)\n else if (color(v) == 1) hasCycle = true\n i += 1\n }\n color(u) = 2\n sortedBuilder += u\n }\n\n for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)\n\n// val sorted = sortedBuilder.result\n//\n// val order = Array.ofDim[Int](n)\n// for (i <- sorted.indices) {\n// order(sorted(i)) = 1 + i % 2\n// }\n\n //println(sorted.map(_ + 1).mkString(\" \"))\n //println(order.mkString(\" \"))\n //for (i <- 0 until m) res(i) = order(edgeTo(i))\n\n val visited = Array.fill(n)(false)\n\n def dfs1(u: Int, u0: Int, step: Int): Unit = {\n /*if (step > 0 && u == u0) hasCycle = true\n else */if (!visited(u)) {\n visited(u) = true\n var i = 0\n while (i < adjs(u).length) {\n val edge = adjs(u)(i)\n res(edge) = step % 2 + 1\n dfs1(edgeTo(edge), u0, step + 1)\n i += 1\n }\n }\n }\n//\n// var iter = 0\n for (u <- 0 until n) {\n if (!visited(u)) {\n dfs1(u, u, 0)\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (hasCycle) {\n println(2)\n println(res.mkString(\" \"))\n } else {\n println(1)\n println(Array.fill(m)(1).mkString(\" \"))\n }\n\n Console.flush\n}\n"}], "src_uid": "9974ea401e2ec62f3c1e2317a23ee605"} {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject B extends App {\n\n val sc = new Scanner(System.in)\n type Segment = (Int, Int)\n\n val n = sc.nextInt()\n val checkmates = getSegments(n)\n val m = sc.nextInt()\n val programming = getSegments(m)\n\n val checkmatesL = checkmates.maxBy(_._1)._1\n val checkmatesR = checkmates.minBy(_._2)._2\n val programmingL = programming.maxBy(_._1)._1\n val programmingR = programming.minBy(_._2)._2\n\n val ans = math.max(programmingL - checkmatesR, checkmatesL - programmingR)\n println(math.max(0, ans))\n\n def getSegments(n: Int): Set[Segment] = {\n var checkmates = mutable.HashSet[Segment]()\n (1 to n) foreach { _ =>\n val x: Segment = (sc.next().toInt, sc.next().toInt)\n checkmates += x\n }\n checkmates.toSet\n }\n}\n", "positive_code": [{"source_code": "\n\n/**\n * Created by ruslan on 3/4/17.\n */\nobject ProblemB extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\nimport java.util.StringTokenizer\n override def main(args: Array[String]): Unit = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n var st: StringTokenizer = null\n val out = new PrintWriter(System.out)\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) st =\n new StringTokenizer(br.readLine)\n st.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n val n = nextInt\n var maxMath = 0\n var minMath = Int.MaxValue\n var maxChess = 0\n var minChess = Int.MaxValue\n\n for (i <- 1 to n) {\n maxMath = math.max(nextInt, maxMath)\n minMath = math.min(nextInt, minMath)\n }\n\n val m = nextInt\n for (i <- 1 to m) {\n maxChess = math.max(nextInt, maxChess)\n minChess = math.min(nextInt, minChess)\n }\n\n val res = math.max(maxChess - minMath, maxMath - minChess)\n println(math.max(0, res))\n\n }\n}\n"}, {"source_code": "object _785B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n \n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n val chess, programming = read[Seq[(Int, Int)]]\n write(calc(chess, programming) max calc(programming, chess) max 0)\n }\n\n def calc(a: Seq[(Int, Int)], b: Seq[(Int, Int)]) = b.maxWith(_._1).get - a.minWith(_._2).get\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.language.postfixOps\nimport scala.math._\n\nobject TaskB extends App {\n val ir = new InputReader(System.in)\n def minMax(a: (Int, Int), b: (Int, Int)) = (max(a._1, b._1), min(a._2, b._2))\n\n val a = 1 to ir.nextInt map { _ => (ir.nextInt, ir.nextInt) } reduce minMax\n val b = 1 to ir.nextInt map { _ => (ir.nextInt, ir.nextInt) } reduce minMax\n\n println(max(max(a._1 - b._2, b._1 - a._2), 0))\n}\n\nclass InputReader(val stream: InputStream) {\n val reader = new BufferedReader(new InputStreamReader(stream))\n var stt: StringTokenizer = _\n\n def nextString: String = {\n while (stt == null || !stt.hasMoreTokens) stt = new StringTokenizer(reader.readLine)\n stt.nextToken\n }\n\n def nextInt: Int = nextString.toInt\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject TaskB {\n\n def readData(): Seq[(Int, Int)] = {\n val size = StdIn.readInt()\n 1 to size map { _ =>\n val tuple = StdIn.readf2(\"{0} {1}\")\n (tuple._1.toString.toInt, tuple._2.toString.toInt)\n }\n }\n\n def isCrossed(chessTime: (Int, Int), programmingTime: (Int, Int)): Boolean = {\n if (chessTime._1 >= programmingTime._1 && chessTime._1 <= programmingTime._2) {\n return true\n }\n\n if (chessTime._2 >= programmingTime._1 && chessTime._2 <= programmingTime._2) {\n return true\n }\n\n false\n }\n\n def distance(chessTime: (Int, Int), programmingTime: (Int, Int)): Int = {\n if (isCrossed(chessTime, programmingTime)) {\n 0\n } else if (chessTime._1 < programmingTime._1) {\n programmingTime._1 - chessTime._2\n } else {\n chessTime._1 - programmingTime._2\n }\n }\n\n def main(args: Array[String]): Unit = {\n val chessData = readData()\n val programmingData = readData()\n\n val distances = for {\n x <- List(\n chessData.minBy(_._1),\n chessData.minBy(_._2),\n chessData.maxBy(_._1),\n chessData.maxBy(_._2))\n y <- List(\n programmingData.minBy(_._1),\n programmingData.minBy(_._2),\n programmingData.maxBy(_._1),\n programmingData.maxBy(_._2)\n )\n } yield {\n distance(x, y)\n }\n\n println(distances.max)\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n\n\nobject B extends App {\n\n val sc = new Scanner(System.in)\n type Segment = (Int, Int)\n\n val n = sc.nextInt()\n val checkmates = getSegments(n)\n val m = sc.nextInt()\n val programming = getSegments(m)\n\n val checkmatesL = checkmates.maxBy(_._1)._1\n val checkmatesR = checkmates.minBy(_._2)._2\n val programmingL = programming.maxBy(_._1)._1\n val programmingR = programming.minBy(_._2)._2\n\n if (checkmatesR < programmingL) {\n println(programmingL - checkmatesR)\n } else if (checkmatesL > programmingR) {\n println(checkmatesL - programmingR)\n } else {\n println(0)\n }\n\n def getSegments(n: Int): Set[Segment] = {\n var checkmates = mutable.HashSet[Segment]()\n (1 to n) foreach { _ =>\n val x: Segment = (sc.next().toInt, sc.next().toInt)\n checkmates += x\n }\n checkmates.toSet\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject TaskB {\n\n def readData(): Seq[(Int, Int)] = {\n val size = StdIn.readInt()\n 1 to size map { _ =>\n val tuple = StdIn.readf2(\"{0} {1}\")\n (tuple._1.toString.toInt, tuple._2.toString.toInt)\n }\n }\n\n def isCrossed(chessTime: (Int, Int), programmingTime: (Int, Int)): Boolean = {\n if (chessTime._1 >= programmingTime._1 && chessTime._1 <= programmingTime._2) {\n return true\n }\n\n if (chessTime._2 >= programmingTime._1 && chessTime._2 <= programmingTime._2) {\n return true\n }\n\n false\n }\n\n def distance(chessTime: (Int, Int), programmingTime: (Int, Int)): Int = {\n if (isCrossed(chessTime, programmingTime)) {\n 0\n } else if (chessTime._1 < programmingTime._1) {\n programmingTime._1 - chessTime._2\n } else {\n chessTime._2 - programmingTime._1\n }\n }\n\n def main(args: Array[String]): Unit = {\n val chessData = readData()\n val programmingData = readData()\n val tuples = for {x <- chessData; y <- programmingData} yield (x, y)\n println(tuples.map { tuple => distance(tuple._1, tuple._2) }.max)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject TaskB {\n\n def readData(): Seq[(Int, Int)] = {\n val size = StdIn.readInt()\n 1 to size map { _ =>\n val tuple = StdIn.readf2(\"{0} {1}\")\n (tuple._1.toString.toInt, tuple._2.toString.toInt)\n }\n }\n\n def isCrossed(chessTime: (Int, Int), programmingTime: (Int, Int)): Boolean = {\n if (chessTime._1 >= programmingTime._1 && chessTime._1 <= programmingTime._2) {\n return true\n }\n\n if (chessTime._2 >= programmingTime._1 && chessTime._2 <= programmingTime._2) {\n return true\n }\n\n false\n }\n\n def distance(chessTime: (Int, Int), programmingTime: (Int, Int)): Int = {\n if (isCrossed(chessTime, programmingTime)) {\n 0\n } else if (chessTime._1 < programmingTime._1) {\n programmingTime._1 - chessTime._2\n } else {\n chessTime._2 - programmingTime._1\n }\n }\n\n def main(args: Array[String]): Unit = {\n val chessData = readData()\n val programmingData = readData()\n val distances = for {x <- chessData; y <- programmingData} yield distance(x, y)\n println(distances.max)\n }\n\n}\n"}, {"source_code": "\n\n/**\n * Created by ruslan on 3/4/17.\n */\nobject ProblemB extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\nimport java.util.StringTokenizer\n override def main(args: Array[String]): Unit = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n var st: StringTokenizer = null\n val out = new PrintWriter(System.out)\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) st =\n new StringTokenizer(br.readLine)\n st.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n val n = nextInt\n var maxMath = 0\n var minMath = Int.MaxValue\n var maxChess = 0\n var minChess = Int.MaxValue\n\n for (i <- 1 to n) {\n maxMath = math.max(nextInt, maxMath)\n minMath = math.min(nextInt, minMath)\n }\n\n val m = nextInt\n for (i <- 1 to m) {\n maxChess = math.max(nextInt, maxChess)\n minChess = math.min(nextInt, minChess)\n }\n\n val res = math.max(maxChess - minMath, maxMath - minMath)\n println(math.max(0, res))\n\n }\n}\n"}, {"source_code": "\n/**\n * Created by ruslan on 3/4/17.\n */\nobject ProblemB extends App {\nimport java.io.{BufferedReader, InputStreamReader, PrintWriter}\nimport java.util.StringTokenizer\n\n override def main(args: Array[String]): Unit = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n var st: StringTokenizer = null\n val out = new PrintWriter(System.out)\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) st =\n new StringTokenizer(br.readLine)\n st.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n val n = nextInt\n var maxMath, minMath = 0\n var maxChess, minChess = 0\n\n for (i <- 1 to n) {\n maxMath = math.max(nextInt, maxMath)\n minMath = math.min(nextInt, minMath)\n }\n \n val m = nextInt\n for (i <- 1 to m) {\n maxChess = math.max(nextInt, maxChess)\n minChess = math.min(nextInt, minChess)\n }\n\n val res = math.max(maxChess - minMath, maxMath - minMath)\n println(math.max(0, res))\n \n }\n}\n"}, {"source_code": "\n/**\n * Created by ruslan on 3/4/17.\n */\nobject ProblemB extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\nimport java.util.StringTokenizer\n\n override def main(args: Array[String]): Unit = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n var st: StringTokenizer = null\n val out = new PrintWriter(System.out)\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) st =\n new StringTokenizer(br.readLine)\n st.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n val n = nextInt\n\n val timeForChess = (for (i <- 1 to n) yield (nextInt, nextInt)).sortWith((p1, p2) => p1._2 - p2._2 < 0)\n val m = nextInt\n val timeForMath = (for (i <- 1 to m) yield (nextInt, nextInt)).sortWith((p1, p2) => p1._1 - p2._1 > 0)\n\n println(math.max(0, timeForMath(0)._1 - timeForChess(0)._2))\n\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.language.postfixOps\nimport scala.math.max\n\nobject TaskB extends App {\n val ir = new InputReader(System.in)\n\n val r = 1 to ir.nextInt map { _ => ir.nextInt; ir.nextInt } min\n val l = 1 to ir.nextInt map { _ => val l = ir.nextInt; ir.nextInt; l } max\n\n println(max(l - r, 0))\n}\n\nclass InputReader(val stream: InputStream) {\n val reader = new BufferedReader(new InputStreamReader(stream))\n var stt: StringTokenizer = _\n\n def nextString: String = {\n while (stt == null || !stt.hasMoreTokens) stt = new StringTokenizer(reader.readLine)\n stt.nextToken\n }\n\n def nextInt: Int = nextString.toInt\n}\n"}], "src_uid": "4849a1f65afe69aad12c010302465ccd"} {"source_code": "object Solution {\n\n def main(args: Array[String]): Unit = {\n\n val in: Iterator[String] = io.Source.stdin.getLines()\n val Array(m,n) = in.next().split(\" \").map(_.toInt)\n val first = in.next().split(\" \").map(_.toInt)\n val second = in.next().split(\" \").map(_.toInt)\n\n val fe = first.count(_ % 2 == 0)\n val fo = first.count(_% 2 != 0)\n val se = second.count(_ % 2 == 0)\n val so = second.count(_ % 2 != 0)\n\n println(Math.min(fe, so) + Math.min(fo, se))\n\n }\n\n}\n", "positive_code": [{"source_code": "object a extends App {\n import scala.io.StdIn.readLine\n import scala.math.min\n\n val _ = readLine\n def getArr: (Array[Int], Array[Int]) = readLine.split(\" \").map(_.toInt).partition(_ % 2 == 0)\n val aa = getArr\n val bb = getArr\n\n val (aOdd, aEven) = (aa._1.length, aa._2.length)\n val (bOdd, bEven) = (bb._1.length, bb._2.length)\n\n println(min(aOdd, bEven) + min(aEven, bOdd))\n\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M = ni()\n val A = na(N)\n val B = na(M)\n val evenA = A.count(_%2 == 0)\n val evenB = B.count(_%2 == 0)\n val ans = min(evenA, M - evenB) + min(N - evenA, evenB)\n out.println(ans)\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debugDim(m: Array[Array[Long]]): Unit = DEBUG {\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n\n def debugDimFlip(m: Array[Array[Long]]): Unit = DEBUG {\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [], "src_uid": "bc532d5c9845940b5f59485394187bf6"} {"source_code": "object CF919A extends App{\n val sc = new java.util.Scanner(System.in)\n val n, m = sc.nextInt\n println((Seq.fill[Double](n)(sc.nextDouble / sc.nextDouble) min) * m)\n}", "positive_code": [{"source_code": "\nimport java.util.Scanner\n\nimport scala.language.implicitConversions\n\nobject Supermarket {\n class Lazy[A](x: => A) {\n lazy val value = x\n override def toString(): String = value.toString()\n }\n object Lazy {\n def apply[A](x: => A) = new Lazy(x)\n implicit def fromLazy[A](z: Lazy[A]): A = z.value\n implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)\n }\n def memoize[I, O](f: I => O): I => O = new collection.mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val (n, m) = (sc.nextInt(), sc.nextInt())\n val min_ratio = 0.until(n).map(i => sc.nextInt() * 1.0 / sc.nextInt()).min\n print(min_ratio * m);\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\n/**\n * Created by amir.\n */\n\nobject A extends App{\n\n class RW(val inputFile: String, val outputFile: String) {\n private var br = new BufferedReader(new InputStreamReader(System.in))\n private var out = new PrintWriter(new OutputStreamWriter(System.out))\n\n /* val f = new File(inputFile)\n if (f.exists && f.canRead)\n try {\n br = new BufferedReader(new FileReader(f))\n out = new PrintWriter(new FileWriter(outputFile))\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }*/\n\n private var st: StringTokenizer = _\n var eof = false\n\n def nextLine: String = {\n var s = \"\"\n try\n s = br.readLine()\n catch {\n case e: IOException =>\n e.printStackTrace()\n }\n s\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens)\n try\n st = new StringTokenizer(br.readLine)\n catch {\n case _: IOException =>\n eof = true\n \"\"\n }\n st.nextToken\n }\n\n def nextLong: Long = next.toLong\n\n def nextInt: Int = next.toInt\n\n def println: Unit = out.println()\n\n def println(o: Any): Unit = out.println(o)\n\n def print(o: Any): Unit = out.print(o)\n\n def close: Unit = {\n try {\n br.close()\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n\n out.close()\n }\n }\n\n\n override def main(args: Array[String]) {\n val rw = new RW(\"input.txt\", \"output.txt\")\n\n val n = rw.nextInt\n val m = rw.nextInt\n val costs = for (_ <- 1 to n) yield rw.nextInt.toDouble / rw.nextInt\n rw.println(costs.min * m)\n rw.close\n }\n}"}, {"source_code": "object A extends App {\n val Array(n, m) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val price = (0 until n).foldLeft(Double.MaxValue)((price, _) => {\n val Array(a, b) = scala.io.StdIn.readLine().split(\" \").map(_.toDouble)\n price.min(a / b)\n })\n println(price * m)\n}\n"}], "negative_code": [], "src_uid": "3bbe48918a7bf3faf01c74cb7296f6e0"} {"source_code": "import scala.collection.mutable._\nimport scala.math._\nobject A extends App {\n val n = readLine.toInt\n val t = for(i <- 0 until n) yield {\n val Array(a, b) = for(s <- readLine.split(\" \")) yield s\n (a, b.toInt)\n }\n val map = collection.mutable.Map[String,Int]()\n for(i <- t) {\n val k = i._1\n val v = i._2 + {if(map.contains(i._1)) map(i._1) else 0}\n map(k) = v\n }\n var score = -(1<<29)\n for((k,v) <- map) {\n score = max(score, v)\n }\n val map2 = collection.mutable.Map[String,Int]()\n var name: String = null\n for(i <- t) {\n val k = i._1\n if(map(k) == score) {\n val v = i._2 + {if(map2.contains(i._1)) map2(i._1) else 0}\n map2(k) = v\n if(v >= score && name == null) {\n name = k\n }\n }\n }\n println(name)\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\n\nobject P002A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n sc.nextLine\n\n type Round = (String, Int)\n type Score = Round\n\n def readRound(): Round = {\n val elms = sc.nextLine.split(\" \")\n (elms(0), elms(1).toInt)\n }\n\n val rounds: List[Round] = List.fill(N)(readRound)\n\n def solve(): String = {\n val scores: Map[String, Int] = rounds.groupBy(_._1).toSeq\n .map(s => (s._1 -> s._2.map(_._2).sum))\n .toMap\n val m: Int = scores.values.max\n val winners: List[String] = scores.toList.filter(_._2 == m).map(_._1)\n\n val scoreBoard = mutable.Map.empty[String, Int]\n val history = new ListBuffer[Score]\n rounds.foreach { r =>\n val (name, point): Round = r\n val update = (name -> (scoreBoard.getOrElse(name, 0) + point))\n scoreBoard += update\n history += update\n }\n history.toList.filter(x => winners.contains(x._1)).dropWhile(_._2 < m).head._1\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "object Winner {\n\n def findWinner(winners:Set[String], games:List[(String, Int)], max: Int): String = {\n val winnerScores = collection.mutable.Map.empty[String, Int].withDefaultValue(0);\n for(game<-games.filter(g=>winners.contains(g._1)))\n {\n winnerScores(game._1) += game._2;\n if (winnerScores(game._1)>=max)\n return game._1;\n }\n return \"\";\n }\n\n def toGame(items : Array[String]) ={\n (items(0),items(1).toInt)\n }\n\n def main(args: Array[String]) = {\n val n = readLine().toInt;\n val games = (1 to n).map(_=>readLine()).map(s=>toGame(s.split(\" \"))).toList;\n val totals = games.groupBy(_._1).mapValues(_.map(_._2).reduce(_+_)).toList;\n val max = totals.map(_._2).max;\n val winners = totals.filter(_._2==max).map(_._1).toSet;\n println(findWinner(winners, games,max))\n \n }\n}"}, {"source_code": "object P2A {\n import io.StdIn._\n\n def main(args : Array[String]) {\n val s = Array.tabulate(readInt){i => {\n val Array(name, score) = readLine.split(' ')\n (name, score.toInt, i)\n }}.groupBy{_._1}\n val maxTotal = s.map{_._2.map{_._2}.sum}.max\n val winners = s.filter{_._2.map{_._2}.sum == maxTotal}\n println(winners.minBy{case (name, rec) => {\n def f(i:Int, n:Int):Int = {\n if (i == rec.size) return Int.MaxValue\n val nN = n + rec(i)._2\n if (nN >= maxTotal) rec(i)._3 else f(i + 1, nN)\n }; f(0, 0)\n }}._1)\n }\n}"}, {"source_code": "object Prob2A_Winner extends App {\n import java.util.{Scanner => Input}\n\n val in = new Input(System.in)\n\n val n = in.nextInt\n val names = Array.ofDim[String](n)\n val scores = Array.ofDim[Int](n)\n for (i <- 0 until n) {\n names(i) = in.next\n scores(i) = in.nextInt\n }\n\n val map = new collection.mutable.HashMap[String, Int]\n for (i <- 0 until n) {\n if (!map.contains(names(i)))\n map += (names(i) -> 0)\n map(names(i)) += scores(i)\n }\n val finalScore = map.values.max\n val map2 = new collection.mutable.HashMap[String, Int]\n var i = 0\n while (i < n) {\n if (!map2.contains(names(i)))\n map2 += (names(i) -> 0)\n map2(names(i)) += scores(i)\n if (map(names(i)) == finalScore && map2(names(i)) >= finalScore) {\n println(names(i))\n i = n\n }\n i += 1\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val map = scala.collection.mutable.Map[String, Seq[(Int, Int)]]()\n for (i <- 1 to n) {\n val a = readLine().split(\" \")\n val s = map.getOrElse(a(0), Seq.empty[(Int, Int)])\n map(a(0)) = s ++ Seq(i -> (a(1).toInt + s.lastOption.getOrElse((0, 0))._2))\n }\n val max = map.values.map(_.last._2).max\n val f = map.filter{ case (name, score) => score.last._2 == max }\n if (f.size == 1) println(f.keys.toList.apply(0))\n else {\n val f1 = f.toList.map{ case (name, score) => (name, score.find(_._2 >= max)) }\n println(f1.sortBy(_._2.get._1).head._1)\n }\n }\n}"}, {"source_code": "import scala.io.StdIn\nimport scala.annotation.tailrec\n\ncase class RoundEvent(winner: String, score: Int)\n\nobject X extends App {\n val rounds = StdIn.readInt()\n\n val res = (0 until rounds)\n .map(_ =>\n StdIn.readLine().split(\" \") match {\n case Array(s1, s2) => RoundEvent(s1, s2.toInt)\n }\n )\n\n val endScores = res.foldLeft(Map[String, Int]())((accMap, result) => {\n accMap + (result.winner -> (accMap\n .getOrElse(result.winner, 0) + result.score))\n })\n\n val topEndScore = endScores.map(_._2).max\n\n val achievers = endScores.filter { case (_, s) => s == topEndScore }.map(_._1)\n\n @tailrec\n def findFirstWinner(\n rounds: Seq[RoundEvent],\n currScores: Map[String, Int] = Map()\n ): String = {\n val fst = rounds.head\n val nextScore = currScores.getOrElse(fst.winner, 0) + fst.score\n val updatedScores = currScores + (fst.winner -> nextScore)\n if (nextScore >= topEndScore && endScores(fst.winner) == topEndScore)\n fst.winner\n else findFirstWinner(rounds.tail, updatedScores)\n }\n\n val firstWinner = findFirstWinner(res)\n\n println(firstWinner)\n}\n"}, {"source_code": "object Main extends App{\n\n\n\n def scan(index:Int, map:Map[String, Int], list:List[(String, Int)]):(List[(String, Int)],Map[String, Int]) = {\n if(index > 0){\n val values = Console.readLine().trim().split(\" \")\n val name = values(0)\n val value = values(1).toInt\n if(value < -1000 || value > 1000) throw new Exception(\"Illegal value\")\n val res:Map[String, Int] = if(!map.isEmpty && map.contains(name)){\n Map(name -> (value + map(name))) ++ (map - name)\n }\n else {\n map ++ Map(name -> value)\n }\n scan(index-1, res, list ++ List((name, res(name))))\n }\n else {\n (list, map)\n }\n }\n\n var results:Map[String,Int] = Map()\n\n val numOfRounds = Console.readInt\n if(numOfRounds <= 0) {\n throw new Exception(\"Illegal value\")\n }\n\n\n val (list, map) = scan(numOfRounds, results, List())\n\n val max = map.values.toArray.max\n\n val winners = map.filter( _._2 == max).keySet\n println(list.find( (tuple) => tuple._2 >= max && winners.contains(tuple._1)).get._1)\n}"}, {"source_code": "import collection.mutable._\n\nobject Main {\n\n def input(rounds: Int, list: List[(String, Int)]): List[(String, Int)] = rounds match {\n case 0 => list\n case _ => input(rounds - 1, (scanner.next, scanner.nextInt) :: list)\n }\n\n val scanner = new java.util.Scanner(System.in)\n val list = input(scanner.nextInt, List())\n val candidates = list.groupBy(_._1).flatMap(e => Some(e._1, e._2.map(_._2).sum))\n val max = candidates.values.max\n val winners = new HashMap() ++ candidates.filter(_._2 == max)\n\n def isWinner(person: String, score: Int) = {\n winners(person) -= score\n winners(person) <= 0\n }\n\n def findWinner(list: List[(String, Int)]): String = list match {\n case (person, score) :: _ if (isWinner(person, score)) => person\n case _ :: tail => findWinner(tail)\n case Nil => null\n }\n\n def main(args: Array[String]) {\n println(findWinner(list.filter(e => winners.contains(e._1)).reverse))\n }\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n\n val players: mutable.Map[String, Long] = mutable.Map.empty\n val scores: mutable.Map[Long, (Int, String)] = mutable.Map.empty\n\n for (i <- 0 until n) {\n val name = scanner.next()\n val score = scanner.nextLong()\n\n val currentScore = players.getOrElse(name, 0L) + score\n\n players(name) = currentScore\n\n if (!scores.contains(currentScore))\n scores(currentScore) = (i, name)\n }\n\n val maxScore = players.valuesIterator.max\n val candidates = players.filter(tuple => tuple._2 == maxScore).keys.toSet\n\n println(\n if (candidates.size == 1)\n candidates.head\n else\n searchWinner()\n )\n\n def searchWinner(): String = {\n scores\n .filter(t => t._1 >= maxScore)\n .filter(t => candidates.contains(t._2._2))\n .values.toList\n .sortBy(t => t._1)\n .head._2\n }\n }\n}"}, {"source_code": "import collection.mutable._\n\nobject Main2 {\n\n def input(rounds: Int, list: List[(String, Int)]): List[(String, Int)] = rounds match {\n case 0 => list\n case _ => input(rounds - 1, list :+ (scanner.next, scanner.nextInt))\n }\n\n val scanner = new java.util.Scanner(System.in)\n val list = input(scanner.nextInt, List())\n val candidates = list.groupBy(_._1).flatMap(e => Some(e._1, e._2.map(_._2).sum))\n val max = candidates.values.max\n val winners = candidates.filter(_._2 == max)\n val steps = list.filter(e => winners.contains(e._1))\n val scores = new HashMap[String, Int]() { override def default(key:String) = 0 }\n val winner = steps.find(e => { scores(e._1) += e._2; scores(e._1) >= max } ).get\n\n def main(args: Array[String]) {\n println(winner._1)\n }\n}"}, {"source_code": "import collection.mutable._\n\nobject Main {\n val scanner = new java.util.Scanner(System.in)\n val totals = new HashMap[String, Int]() { override def default(key:String) = 0 }\n\n def read(rounds: Int, player: String, score: Int): List[(String, Int)] = {\n totals(player) += score\n rounds match {\n case 0 => (player, totals(player)) :: Nil\n case _ => (player, totals(player)) :: read(rounds - 1, scanner.next, scanner.nextInt)\n }\n }\n\n def main(args: Array[String]): Unit = {\n val game = read(scanner.nextInt - 1, scanner.next, scanner.nextInt)\n val max = totals.values.max\n val winners = totals.filter(_._2 == max)\n println(game\n .filter(e => winners.contains(e._1))\n .filter(_._2 >= max)(0)._1\n )\n }\n}"}, {"source_code": "object P2A {\n def main(args : Array[String]) {\n val n = readLine.toInt\n val s = Array.fill(n) {\n val Array(s1, s2) = readLine split \" \"\n (s1, s2.toInt)\n }.zipWithIndex groupBy {\n case ((name, score), idx) => name\n }\n val maxTotal = s.map{_._2.map{_._1._2}.sum}.max\n val winners = s.filter{_._2.map{_._1._2}.sum == maxTotal}\n val winner = winners.minBy{\n _._2.scanLeft(0, 0){\n case ((idxS, scoreS), ((name, score), idx)) =>\n (idx, scoreS + score)\n }.find{\n case (idx, scoreS) => scoreS >= maxTotal\n }.getOrElse(Int.MaxValue, 0)._1\n }._1\n println(winner)\n }\n}\n"}, {"source_code": "object P2A {\n import io.StdIn._\n\n def main(args : Array[String]) {\n val s = Array.tabulate(readInt){i => {\n val Array(name, score) = readLine.split(' ')\n (name, score.toInt, i)\n }}.groupBy{_._1}\n val maxTotal = s.map{_._2.map{_._2}.sum}.max\n val winners = s.filter{_._2.map{_._2}.sum == maxTotal}\n println(winners.minBy{case (name, rec) => {\n def f(i:Int, n:Int):Int = {\n if (i == rec.size) return Int.MaxValue\n val nN = n + rec(i)._2\n if (nN >= maxTotal) rec(i)._3 else f(i + 1, nN)\n }; f(0, 0)\n }}._1)\n }\n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val r = Range(0, n).map{_ =>\n val d = in.next().split(\" \")\n (d.head, d.tail.head.toInt)\n }\n val grouped: Map[String, Int] = r.groupBy(t => t._1).map(t => t._1 -> t._2.map(_._2).sum)\n val max = grouped.maxBy(_._2)._2\n val maxg = grouped.filter(t => t._2 == max)\n if (maxg.size > 1) {\n val names = maxg.keySet\n val a = r.filter(t => names.contains(t._1)).foldLeft(names.map(t => t -> 0).toMap) {\n case(acc, el) if acc.values.max >= max => acc\n case(acc, el) => acc + (el._1 -> (acc(el._1) + el._2))\n }.maxBy(_._2)\n println(a._1)\n } else\n println(maxg.head._1)\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CBR2A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CBR2A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val mp = collection.mutable.HashMap.empty[String, Int]\n val n = ni()\n\n val names = Array.ofDim[String](n)\n val score = Array.ofDim[Int](n)\n\n var res = -1000001\n\n REP(n) { i =>\n val nm = ns()\n val v = ni()\n\n names(i) = nm\n score(i) = v\n\n if(mp.contains(nm)) {\n mp(nm) = mp(nm) + v\n } else {\n mp(nm) = v\n }\n }\n\n REP(n) { i =>\n if(mp(names(i)) > res) {\n res = mp(names(i))\n }\n }\n\n var name: String = \"-1\"\n// out.println(res)\n val mp1 = collection.mutable.HashMap.empty[String, Int]\n REP(n) { i =>\n if(mp1.contains(names(i))) {\n mp1(names(i)) += score(i)\n } else mp1(names(i)) = score(i)\n if(mp1(names(i)) >= res && mp(names(i)) == res && name == \"-1\") {\n name = names(i)\n }\n }\n out.println(name)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Winner extends App {\n\n var playerScores = Map.empty[String, Player]\n\n val scanner = new Scanner(System.in)\n val size = scanner.nextInt()\n\n (0 until size).map(it => (scanner.next(), scanner.nextInt()))\n .zipWithIndex.foreach {\n record =>\n playerScores.get(record._1._1) match {\n case None =>\n val player = Player(record._1._1)\n player.addScore(record._1._2, record._2)\n playerScores += (record._1._1 -> player)\n case Some(v) =>\n v.addScore(record._1._2, record._2)\n }\n }\n\n val players = playerScores.values.toList\n val finalScore = players.sortBy(_.score).last.score\n\n val result = players\n .sortBy(-_.smallestMoveForPointsMorThan(finalScore))\n .sortBy(_.score).last\n\n println(result.name)\n\n case class Player(name: String) {\n\n var score: Int = 0\n\n var scoreHistory = List.empty[(Int, Int)]\n\n def addScore(points: Int, moveNum: Int): Unit = {\n score += points\n scoreHistory ::= (moveNum, score)\n }\n\n def smallestMoveForPointsMorThan(max: Int):Int = {\n scoreHistory.sortBy(_._1).find(_._2 >= max) match {\n case Some(v) => v._1\n case None => Integer.MAX_VALUE\n }\n }\n\n }\n\n}\n\n/*\n8\nandrew 3\nandrew 2\nmike 5\nmike 2\nandrew 2\nmike 3\nandrew 4\nandrew -1\n*/"}, {"source_code": "object A2 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = Array.fill(n){\n val tl = tokenizeLine\n (tl.nextToken(), tl.nextToken().toInt)\n }\n val map = cu.Map.empty[String, Int].withDefaultValue(0)\n for(i <- 0 until n)\n map(in(i)._1) += in(i)._2\n val max = map.maxBy(_._2)._2\n var winners = {\n val newMap = cu.Map.empty[String, Int].withDefaultValue(0)\n map.filter{case (k, v) => v == max}.keys.foreach(newMap(_) = 0)\n newMap\n }\n if(winners.size == 1) {\n println(winners.keySet.head)\n } else {\n //replay\n var res = \"\"\n for(i <- 0 until n if winners.contains(in(i)._1)) {\n winners(in(i)._1) += in(i)._2\n if(res.isEmpty && winners(in(i)._1) >= max) {\n res = in(i)._1\n }\n }\n println(res)\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object P2A {\n import io.StdIn._\n\n def main(args : Array[String]) {\n val s = Array.tabulate(readInt){i => {\n val Array(name, score) = readLine.split(' ')\n (name, score.toInt, i)\n }}.groupBy{_._1}\n val maxTotal = s.map{_._2.map{_._2}.sum}.max\n val winners = s.filter{_._2.map{_._2}.sum == maxTotal}\n println(winners.minBy{case (name, rec) => {\n def f(i:Int, n:Int):Int = {\n if (i == rec.size) return Int.MaxValue\n val nN = n + rec(i)._2\n if (nN >= maxTotal) rec(i)._3 else f(i + 1, nN)\n }; f(0, 0)\n }}._1)\n }\n}"}, {"source_code": "import java.util.Scanner\nimport scala.annotation.tailrec\n\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val input = (for (i <- 1 to n) yield scanner.nextLine().split(\" \") match {case Array(name, score) => (name, score.toInt)}).toList\n\n val result = input.groupBy(_._1).mapValues(_.map(_._2).sum)\n val maxScore = result.maxBy(_._2)._2\n val winners = result.filter(_._2 == maxScore).keys\n\n def replay: String = {\n @tailrec\n def turn(acc: Map[String, Int], data: List[(String, Int)]): String = {\n val current = data.head\n if (acc.get(current._1).isEmpty) turn(acc, data.tail)\n else {\n val score = acc.get(current._1).get + current._2\n if (score >= maxScore) current._1\n else turn(acc.updated(current._1, score), data.tail)\n }\n }\n turn(winners.map((_, 0)).toMap, input)\n }\n\n if (winners.size == 1) println(winners.head)\n else println(replay)\n}"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Winner {\n def main(args: Array[String]) : Unit = {\n val scores : mutable.HashMap[String, Int] = new mutable.HashMap()\n\n var lst : List[(String, Int)] = Nil\n\n val n: Int = StdIn.readLine().toInt\n for (_ <- 0 until n) {\n val line = StdIn.readLine().split(\" \")\n val _name : String = line(0)\n val _score : Int = line(1).toInt\n lst = lst :+ (_name, _score)\n val sc = scores.get(_name)\n\n sc match {\n case Some(score_got) => scores.put(_name, score_got + _score)\n case None => scores.put(_name, _score)\n }\n\n }\n\n var score: Int = 0\n\n for ((_,v) <- scores) {\n if (score < v) {\n score = v\n }\n }\n\n var name = \"\"\n var found = false\n val scores_post : mutable.HashMap[String, Int] = new mutable.HashMap()\n for ((k,v) <- lst) {\n if (!found) {\n val sc = scores_post.get(k)\n val allscore = sc match {\n case Some(score_got) => score_got + v\n case None => v\n }\n scores_post.put(k, allscore)\n if (allscore >= score && scores(k) == score) {\n name = k\n found = true\n }\n }\n }\n\n println(name)\n }\n}\n"}, {"source_code": "import collection.mutable\nimport io.Source\n\n// The winner of the card game popular in Berland \"Berlogging\" is determined according to the following rules. If at the end of the game there is \n// only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more \n// than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered \n// in the line \"name score\", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If \n// score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it \n// equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's \n// guaranteed that at the end of the game at least one player has a positive number of points. \n\nobject Winner {\n\n\n def main(args: Array[String]) = {\n val lines = Source.stdin.getLines()\n lines.next()\n\n val gameTrace = lines.toList.map(line => { val splitLine = line.split(\" \"); Pair(splitLine(0), splitLine(1).toInt)})\n\n println(getWinner(gameTrace))\n }\n\n def getWinner(gameTrace: List[Pair[String, Int]]) = {\n val finalScores = gameTrace.foldLeft(Map[String, Int]().withDefaultValue(0)) {\n case (scores, (player, pointsWon)) => scores + (player -> (scores(player) + pointsWon))}\n\n // now find the max final score\n val maxFinalScore = finalScores.foldLeft(finalScores.head._2) {case (maxSoFar, (_, score)) => maxSoFar max score}\n val potentialWinners = finalScores.filter {case (_, score) => (score == maxFinalScore)}\n // single potential winner?\n if (potentialWinners.tail.isEmpty) {\n potentialWinners.head._1\n }\n else {\n firstPlayerToMaxScore(gameTrace, potentialWinners, maxFinalScore)\n }\n }\n\n def firstPlayerToMaxScore(gameTrace: List[Pair[String, Int]], possWinners: Map[String, Int], maxFinalScore: Int) = {\n\n def auxFirstRec(currGamePosition: List[Pair[String, Int]], currScores: Map[String, Int]): String = {\n currGamePosition match {\n case (player, pointsWon) :: rest => if (currScores(player) + pointsWon >= maxFinalScore)\n player\n else\n auxFirstRec(rest, currScores + (player -> (currScores(player) + pointsWon)))\n case Nil => \"randomguess\"\n }\n }\n\n val filteredTrace = gameTrace.filter{case (player, _) => possWinners.contains(player)}\n auxFirstRec(filteredTrace, Map[String, Int]().withDefaultValue(0))\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject Winner {\n\n def update(scores: mutable.HashMap[String, Int], name: String, value: Int): Int = {\n val base = scores.getOrElse(name, 0)\n scores.update(name, base + value)\n base + value\n }\n\n def main(args: Array[String]) = {\n val n = scala.io.StdIn.readLine().toString.toInt\n val names = new ArrayBuffer[String]\n val values = new ArrayBuffer[Int]\n val scores = new mutable.HashMap[String, Int]()\n for (i <- 0 until n) {\n val line = scala.io.StdIn.readLine().split(\" \")\n names += line(0)\n values += line(1).toInt\n update(scores, names(i), values(i))\n }\n var max_value = scores.values.max\n val final_scores = new mutable.HashMap[String, Int]()\n var winner = \"\"\n for (i <- 0 until n) {\n if (winner == \"\" && max_value <= update(final_scores, names(i), values(i)) &&\n scores.getOrElse(names(i), 0) == max_value) {\n winner = names(i)\n }\n }\n println(winner)\n }\n}\n"}, {"source_code": "import collection.mutable\n\nobject Main {\n def main(args: Array[String]) = {\n val n = readInt\n val rnd = (1 to n).map(_=>readLine.split(\"\\\\s+\")).map(x=>(x(0), x(1).toInt))\n var score = mutable.Map(rnd.map(x=>(x._1, 0)):_*)\n rnd.foreach(r=>{score(r._1) += r._2})\n val m = score.values.max\n val wincnt = score.count(_._2==m)\n if (wincnt==1) {\n println(score.maxBy(_._2)._1)\n } else {\n def firstRound(rnd:Seq[(Int,Int)], acc:Int):Int = {\n if (acc+rnd.head._2>=m) rnd.head._1\n else firstRound(rnd.tail, acc+rnd.head._2)\n }\n val winners = score.filter(_._2==m).map(w=>(w._1, firstRound(rnd.zipWithIndex.filter(_._1._1==w._1).map(r=>(r._2, r._1._2)), 0)))\n val winRound = winners.map(_._2).min\n println(winners.filter(_._2==winRound).head._1)\n }\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\n\n/**\n * Created by gzq on 4/6/15.\n */\nobject CF2A {\n def main(args: Array[String]): Unit = {\n class nameAndScore(val name: String, val score: Int)\n\n val in = scala.io.StdIn\n val count = in.readInt()\n\n val name2Score = new mutable.HashMap[String, Int]()\n var scoresStat = new ListBuffer[nameAndScore]\n\n for (i <- 1 to count) {\n val nameScore = in.readLine().split(\" \")\n val name = nameScore(0)\n val score = nameScore(1).toInt\n\n if (name2Score.contains(name)) {\n val curScore = name2Score(name) + score\n name2Score(name) = curScore\n scoresStat += (new nameAndScore(name, curScore))\n } else {\n name2Score(name) = score\n scoresStat += (new nameAndScore(name, score))\n }\n }\n\n val winnerScore = name2Score.reduce(\n (winner, current) => if (winner._2 > current._2) winner else current\n )._2\n\n val names = scoresStat.filter(\n (stat: nameAndScore) =>\n name2Score(stat.name) == winnerScore && stat.score >= winnerScore\n )\n println(names(0).name)\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\n\n/**\n * Created by gzq on 4/6/15.\n */\nobject CF2A {\n def main(args: Array[String]): Unit = {\n class nameAndScore(val name: String, val score: Int)\n\n val in = scala.io.StdIn\n val count = in.readInt()\n\n val name2Score = new mutable.HashMap[String, Int]()\n var scoresStat = new ListBuffer[nameAndScore]\n\n for (i <- 1 to count) {\n val nameScore = in.readLine().split(\" \")\n val name = nameScore(0)\n val score = nameScore(1).toInt\n\n if (name2Score.contains(name)) {\n val curScore = name2Score(name) + score\n name2Score(name) = curScore\n scoresStat += (new nameAndScore(name, curScore))\n } else {\n name2Score(name) = score\n scoresStat += (new nameAndScore(name, score))\n }\n }\n\n// val winnerScore = name2Score.reduce(\n// (winner, current) => if (winner._2 > current._2) winner else current\n// )._2\n\n val winnerScore = name2Score.values.max\n \n val names = scoresStat.filter(\n (stat: nameAndScore) =>\n name2Score(stat.name) == winnerScore && stat.score >= winnerScore\n )\n println(names(0).name)\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Winner {\n def main(args: Array[String]) : Unit = {\n val scores : mutable.HashMap[String, (Int, Int)] = new mutable.HashMap()\n var score : Int = 0\n\n\n val n: Int = StdIn.readLine().toInt\n for (i <- 0 until n) {\n val line = StdIn.readLine().split(\" \")\n val _name : String = line(0)\n val _score : Int = line(1).toInt\n val sc = scores.get(_name)\n\n val (allsc, step) = sc match {\n case Some(score_got) => (score_got._1 + _score, score_got._2)\n case None => (_score, i)\n }\n\n if (allsc >= score) {\n score = allsc\n scores.put(_name, (allsc, i))\n } else {\n scores.put(_name, (allsc, step))\n }\n }\n\n var step = Int.MaxValue\n var name = \"\"\n for((key,value) <- scores) {\n val (sc, ind) = value\n if (sc == score) {\n if (ind < step) {\n step = ind\n name = key\n }\n }\n }\n\n println(name)\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Winner {\n def main(args: Array[String]) : Unit = {\n var scores : mutable.HashMap[String, Int] = new mutable.HashMap()\n var name : String = \"\"\n var score : Int = 0\n var step = -1\n\n var n: Int = StdIn.readLine().toInt\n for (i <- 0 until n) {\n val line = StdIn.readLine().split(\" \")\n val _name : String = line(0)\n val _score : Int = line(1).toInt\n if (name == \"\") {\n name = _name\n score = _score\n scores.put(name, score)\n step = i\n } else {\n val sc = scores.get(_name)\n var allsc = 0\n sc match {\n case Some(score_got) => {\n allsc = score_got + _score\n scores.put(_name, allsc)\n }\n case None => {\n scores.put(_name, _score)\n allsc = _score\n }\n }\n if (allsc > score) {\n step = i\n name = _name\n score = allsc\n } else if (allsc == score) {\n if (step >= i) {\n step = i\n name = _name\n score = allsc\n }\n }\n\n }\n }\n println(name)\n\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Winner {\n def main(args: Array[String]) : Unit = {\n var scores : mutable.HashMap[String, Int] = new mutable.HashMap()\n var name : String = \"\"\n var score : Int = 0\n var step = -1\n\n var n: Int = StdIn.readLine().toInt\n for (i <- 0 until n) {\n val line = StdIn.readLine().split(\" \")\n val _name : String = line(0)\n val _score : Int = line(1).toInt\n if (name == \"\") {\n name = _name\n score = _score\n scores.put(name, score)\n step = i\n } else {\n val sc = scores.get(_name)\n var allsc = 0\n sc match {\n case Some(score_got) => {\n allsc = score_got + _score\n scores.put(_name, allsc)\n }\n case None => {\n scores.put(_name, _score)\n allsc = _score\n }\n }\n if (allsc > score) {\n step = i\n name = _name\n score = allsc\n } else if (allsc == score) {\n if (step > i) {\n step = i\n name = _name\n score = allsc\n }\n }\n\n }\n }\n println(name)\n\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Winner {\n def main(args: Array[String]) : Unit = {\n val scores : mutable.HashMap[String, Int] = new mutable.HashMap()\n var name : String = \"\"\n var score : Int = 0\n var step = -1\n\n val n: Int = StdIn.readLine().toInt\n for (i <- 0 until n) {\n val line = StdIn.readLine().split(\" \")\n val _name : String = line(0)\n val _score : Int = line(1).toInt\n if (name == \"\") {\n name = _name\n score = _score\n scores.put(name, score)\n step = i\n } else {\n val sc = scores.get(_name)\n val allsc = sc match {\n case Some(score_got) => score_got + _score\n case None => _score\n }\n scores.put(_name, allsc)\n if (name == _name) {\n score = allsc\n }\n if (allsc > score) {\n step = i\n name = _name\n score = allsc\n } else if (allsc == score) {\n if (step > i) {\n step = i\n name = _name\n score = allsc\n }\n }\n }\n }\n println(name)\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Winner {\n def main(args: Array[String]) : Unit = {\n val scores : mutable.HashMap[String, (Int, Int)] = new mutable.HashMap()\n var score : Int = 0\n\n\n val n: Int = StdIn.readLine().toInt\n for (i <- 0 until n) {\n val line = StdIn.readLine().split(\" \")\n val _name : String = line(0)\n val _score : Int = line(1).toInt\n val sc = scores.get(_name)\n\n val (allsc, step) = sc match {\n case Some(score_got) => (score_got._1 + _score, score_got._2)\n case None => (_score, i)\n }\n\n if (allsc >= score) {\n score = allsc\n scores.put(_name, (allsc, step))\n } else {\n scores.put(_name, (allsc, i))\n }\n }\n\n var step = Int.MaxValue\n var name = \"\"\n for((key,value) <- scores) {\n val (sc, ind) = value\n if (sc == score) {\n if (ind < step) {\n step = ind\n name = key\n }\n }\n }\n\n println(name)\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Winner {\n def main(args: Array[String]) : Unit = {\n val scores : mutable.HashMap[String, (Int, Int)] = new mutable.HashMap()\n var score : Int = 0\n var nm : String = \"\"\n\n val n: Int = StdIn.readLine().toInt\n for (i <- 0 until n) {\n val line = StdIn.readLine().split(\" \")\n val _name : String = line(0)\n val _score : Int = line(1).toInt\n val sc = scores.get(_name)\n if (nm == \"\") {\n nm = _name\n }\n val allsc = sc match {\n case Some(score_got) => score_got._1 + _score\n case None => _score\n }\n if (_name == nm) {\n score = allsc\n }\n scores.put(_name, (allsc, i))\n if (allsc > score) {\n score = allsc\n }\n }\n\n var step = Int.MaxValue\n var name = \"\"\n for((key,value) <- scores) {\n val (sc, ind) = value\n if (sc == score) {\n if (ind < step) {\n step = ind\n name = key\n }\n }\n }\n\n println(name)\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Winner {\n def main(args: Array[String]) : Unit = {\n val scores : mutable.HashMap[String, Int] = new mutable.HashMap()\n\n var lst : List[(String, Int)] = Nil\n\n val n: Int = StdIn.readLine().toInt\n for (i <- 0 until n) {\n val line = StdIn.readLine().split(\" \")\n val _name : String = line(0)\n val _score : Int = line(1).toInt\n lst = lst :+ (_name, _score)\n val sc = scores.get(_name)\n\n sc match {\n case Some(score_got) => scores.put(_name, score_got + _score)\n case None => scores.put(_name, _score)\n }\n\n }\n\n var score: Int = 0\n\n for ((_,v) <- scores) {\n if (score < v) {\n score = v\n }\n }\n\n var name = \"\"\n var found = false\n val scores_post : mutable.HashMap[String, Int] = new mutable.HashMap()\n for ((k,v) <- lst) {\n if (!found) {\n val sc = scores_post.get(k)\n val allsc = sc match {\n case Some(score_got) => score_got + v\n case None => v\n }\n scores_post.put(k, allsc)\n if (allsc >= score) {\n name = k\n found = true\n }\n }\n }\n\n println(name)\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Winner {\n def main(args: Array[String]) : Unit = {\n val scores : mutable.HashMap[String, (Int, Int)] = new mutable.HashMap()\n\n val n: Int = StdIn.readLine().toInt\n for (i <- 0 until n) {\n val line = StdIn.readLine().split(\" \")\n val _name : String = line(0)\n val _score : Int = line(1).toInt\n val sc = scores.get(_name)\n\n sc match {\n case Some(score_got) => scores.put(_name, (score_got._1 + _score, i))\n case None => scores.put(_name, (_score, i))\n }\n\n }\n\n var name: String = \"\"\n var score: Int = 0\n var ind = -1\n\n for ((k,(v,i)) <- scores) {\n if (name.isEmpty) {\n name = k\n score = v\n ind = i\n } else {\n if (score < v) {\n name = k\n score = v\n ind = i\n } else if (score == v) {\n if (i < ind) {\n name = k\n score = v\n ind = i\n }\n }\n }\n }\n\n println(name)\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\n/**\n * Created by gzq on 4/6/15.\n */\nobject CF2B {\n def main(args: Array[String]) {\n var winnerName = \"\"\n var winnerScore = Int.MinValue\n val scores = new mutable.HashMap[String, Int]()\n val in = scala.io.StdIn\n\n val count = in.readInt()\n\n for (i <- 0 until count) {\n val strArr = in.readLine().split(\" \")\n val name = strArr(0)\n val score = strArr(1).toInt\n\n if (scores.contains(name)) {\n val thisScore = score + scores(name)\n scores(name) = thisScore\n if (thisScore > winnerScore) {\n winnerScore = thisScore\n winnerName = name\n }\n } else {\n scores(name) = score\n if (score > winnerScore) {\n winnerScore = score\n winnerName = name\n }\n }\n }\n println(winnerName)\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\n\n/**\n * Created by gzq on 4/6/15.\n */\nobject CF2A {\n def main(args: Array[String]) {\n var winnerName = \"\"\n var winnerScore = Int.MinValue\n val in = scala.io.StdIn\n\n val count = in.readInt()\n\n val nameSet = new ListBuffer[String]\n val name2scores = new mutable.HashMap[String, Int]()\n\n for (i <- 0 until count) {\n val nameAndScore = in.readLine().split(\" \")\n val name = nameAndScore(0)\n val deltaScore = nameAndScore(1).toInt\n if (name2scores.contains(name)) {\n nameSet -= name\n nameSet += name\n name2scores(name) = name2scores(name) + deltaScore\n } else {\n nameSet += name\n name2scores(name) = deltaScore\n }\n }\n\n for (name <- nameSet) {\n val score = name2scores(name)\n if (score > winnerScore) {\n winnerName = name\n winnerScore = score\n }\n }\n\n println(winnerName)\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n\n val scores: mutable.Map[String, Long] = mutable.Map.empty\n var winner: (String, Long) = (\"\", 0)\n\n for (i <- 0 until n) {\n val name = scanner.next()\n val score = scanner.nextLong()\n\n var currentScore: Long = scores.getOrElse(name, 0)\n currentScore = score + currentScore\n scores(name) = currentScore\n if (winner._2 < currentScore) winner = (name, currentScore)\n }\n\n println(winner._1)\n }\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n\n val players: mutable.Map[String, Long] = mutable.Map.empty\n val scores: mutable.Map[Long, (Int, String)] = mutable.Map.empty\n\n for (i <- 0 until n) {\n val name = scanner.next()\n val score = scanner.nextLong()\n\n val currentScore = players.getOrElse(name, 0L) + score\n\n players(name) = currentScore\n\n if (!scores.contains(currentScore))\n scores(currentScore) = (i, name)\n }\n\n val maxScore = players.valuesIterator.max\n val candidates = players.filter(tuple => tuple._2 == maxScore).keys\n\n println(\n if (candidates.size == 1)\n candidates.head\n else\n searchWinner()\n )\n\n def searchWinner(): String = {\n val buffer: mutable.Buffer[(Int, String)] = mutable.Buffer.empty\n for (tuple <- scores)\n if (tuple._1 >= maxScore)\n buffer += tuple._2\n\n buffer.sortBy(t => t._1).head._2\n }\n }\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n\n val scores: mutable.Map[String, Long] = mutable.Map.empty\n var winner: (String, Long) = (\"\", 0)\n\n for (i <- 0 until n) {\n val name = scanner.next()\n val score = scanner.nextLong()\n if (score > 0) {\n var currentScore: Long = scores.getOrElse(name, 0)\n currentScore = score + currentScore\n scores(name) = currentScore\n if (winner._2 < currentScore) winner = (name, currentScore)\n }\n }\n\n println(winner._1)\n }\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n\n val history: mutable.Buffer[(String, Long)] = mutable.Buffer.empty\n val scores: mutable.Map[String, Long] = mutable.Map.empty\n var winner: (String, Long) = (\"\", 0)\n\n for (i <- 0 until n) {\n val name = scanner.next()\n val score = scanner.nextLong()\n\n var currentScore: Long = scores.getOrElse(name, 0)\n var tuple = (name, score)\n history += tuple\n\n currentScore = score + currentScore\n scores(name) = currentScore\n if (winner._2 < currentScore) winner = (name, currentScore)\n }\n\n val maxScore: Long = scores.valuesIterator.max\n val candidates = scores.filter(tuple => tuple._2 == maxScore).keys\n if (candidates.size == 1)\n println(candidates.head)\n else\n println(getWinner(history, maxScore, candidates))\n }\n\n def getWinner(history: mutable.Buffer[(String, Long)], maxScore: Long, candidates: Iterable[String]): String = {\n val winners: mutable.Map[String, Long] = mutable.Map.empty\n for (step <- history) {\n val currentScore = winners.getOrElse(step._1, 0L) + step._2\n if (currentScore >= maxScore)\n return step._1\n\n winners(step._1) = currentScore\n }\n \"\"\n }\n\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n\n val scores: mutable.Map[String, Long] = mutable.Map.empty\n var winner: (String, Long) = (\"\", 0)\n\n for (i <- 0 until n) {\n val name = scanner.next()\n val score = scanner.nextLong()\n\n var currentScore: Long = scores.getOrElse(name, 0)\n currentScore = score + currentScore\n scores(name) = currentScore\n if (winner._2 < currentScore) winner = (name, currentScore)\n }\n\n val maxScore = scores.valuesIterator.max\n val winners = scores.filter(tuple => tuple._2 == maxScore)\n if (winners.size == 1)\n println(winners.head._1)\n else\n println(winner._1)\n\n }\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n\n val players: mutable.Map[String, Long] = mutable.Map.empty\n val scores: mutable.Map[Long, String] = mutable.Map.empty\n\n for (i <- 0 until n) {\n val name = scanner.next()\n val score = scanner.nextLong()\n\n val currentScore = players.getOrElse(name, 0L) + score\n\n players(name) = currentScore\n\n if (!scores.contains(currentScore))\n scores(currentScore) = name\n }\n\n val maxScore = scores.keys.max\n println(scores(maxScore))\n }\n}"}, {"source_code": "import scala.collection.mutable._\nimport scala.math._\nobject A extends App {\n val n = readLine.toInt\n val t = for(i <- 0 until n) yield {\n val Array(a, b) = for(s <- readLine.split(\" \")) yield s\n (a, b.toInt)\n }\n val map = collection.mutable.Map[String,Int]()\n var name: String = null\n var score: Int = -1\n for(i <- t) {\n val k = i._1\n val v = i._2 + {if(map.contains(i._1)) map(i._1) else 0}\n map(k) = v\n if(v > score) {\n name = k\n score = v\n }\n }\n// println(map.maxBy(_._2)._1)\n println(name)\n}\n"}, {"source_code": "import scala.collection.mutable._\nimport scala.math._\nobject A extends App {\n val n = readLine.toInt\n val t = for(i <- 0 until n) yield {\n val Array(a, b) = for(s <- readLine.split(\" \")) yield s\n (a, b.toInt)\n }\n println(t)\n val map = collection.mutable.Map[String,Int]()\n for(i <- t) {\n if(map.contains(i._1)) map(i._1) = map(i._1) + i._2\n else map(i._1) = i._2\n }\n println(map.maxBy(_._2)._1)\n}\n"}, {"source_code": "import scala.collection.mutable._\nimport scala.math._\nobject A extends App {\n val n = readLine.toInt\n val t = for(i <- 0 until n) yield {\n val Array(a, b) = for(s <- readLine.split(\" \")) yield s\n (a, b.toInt)\n }\n val map = collection.mutable.Map[String,Int]()\n var name: String = null\n var score: Int = -1\n for(i <- t) {\n if(map.contains(i._1)) map(i._1) = map(i._1) + i._2\n else map(i._1) = i._2\n if(map(i._1) > score) { \n name = i._1\n score = map(i._1)\n }\n }\n// println(map.maxBy(_._2)._1)\n println(name)\n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val r = Range(0, n).map{_ =>\n val d = in.next().split(\" \")\n (d.head, d.tail.head.toInt)\n }\n val grouped: Map[String, Int] = r.groupBy(t => t._1).map(t => (t._1, t._2.map(_._2).sum))\n val max = r.maxBy(_._2)._2\n val maxg = grouped.filter(t => t._2 == max)\n if (maxg.size > 1) {\n val names = maxg.keySet\n val a = r.foldLeft(names.map(t => t -> 0).toMap) {\n case(acc, el) if acc.values.max >= max => acc\n case(acc, el) => acc + (el._1 -> (acc.getOrElse(el._1, 0) + el._2))\n }.maxBy(_._2)\n println(a._1)\n } else\n println(grouped.head._1)\n}"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val r = Range(0, n).map{_ =>\n val d = in.next().split(\" \")\n (d.head, d.tail.head.toInt)\n }\n val grouped: Map[String, Int] = r.groupBy(t => t._1).map(t => (t._1, t._2.map(_._2).sum))\n val max = grouped.maxBy(_._2)._2\n val maxg = grouped.filter(t => t._2 == max)\n if (maxg.size > 1) {\n val names = maxg.keySet\n val a = r.foldLeft(names.map(t => t -> 0).toMap) {\n case(acc, el) if acc.values.max >= max => acc\n case(acc, el) => acc + (el._1 -> (acc.getOrElse(el._1, 0) + el._2))\n }.maxBy(_._2)\n println(a._1)\n } else\n println(maxg.head._1)\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CBR2A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CBR2A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val mp = collection.mutable.HashMap.empty[String, Int]\n val n = ni()\n\n val names = Array.ofDim[String](n)\n val score = Array.ofDim[Int](n)\n\n var res = -1001\n\n REP(n) { i =>\n val nm = ns()\n val v = ni()\n\n names(i) = nm\n score(i) = v\n\n if(mp.contains(nm)) {\n mp(nm) = mp(nm) + v\n } else {\n mp(nm) = v\n }\n if(res < mp(nm)) {\n res = mp(nm)\n }\n }\n\n mp.clear()\n var name: String = \"-1\"\n REP(n) { i =>\n if(mp.contains(names(i))) {\n mp(names(i)) += score(i)\n } else mp(names(i)) = score(i)\n if(mp(names(i)) >= res && name == \"-1\") {\n name = names(i)\n }\n }\n out.println(name)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CBR2A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CBR2A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val mp = collection.mutable.HashMap.empty[String, Int]\n val n = ni()\n\n var res = -1001\n var name: String = \"rm\"\n\n REP(n) { _ =>\n val nm = ns()\n val v = ni()\n\n if(mp.contains(nm)) {\n mp(nm) = mp(nm) + v\n } else {\n mp(nm) = v\n }\n if(res < mp(nm)) {\n res = mp(nm)\n name = nm\n }\n }\n out.println(name)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CBR2A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CBR2A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val mp = collection.mutable.HashMap.empty[String, Int]\n val n = ni()\n\n val names = Array.ofDim[String](n)\n val score = Array.ofDim[Int](n)\n\n var res = -1001\n\n REP(n) { i =>\n val nm = ns()\n val v = ni()\n\n names(i) = nm\n score(i) = v\n\n if(mp.contains(nm)) {\n mp(nm) = mp(nm) + v\n } else {\n mp(nm) = v\n }\n if(res < mp(nm)) {\n res = mp(nm)\n }\n }\n\n var name: String = \"-1\"\n val mp1 = collection.mutable.HashMap.empty[String, Int]\n REP(n) { i =>\n if(mp1.contains(names(i))) {\n mp1(names(i)) += score(i)\n } else mp1(names(i)) = score(i)\n if(mp1(names(i)) >= res && mp(names(i)) == res && name == \"-1\") {\n name = names(i)\n }\n }\n out.println(name)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CBR2A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CBR2A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val mp = collection.mutable.HashMap.empty[String, Int]\n val n = ni()\n\n val names = Array.ofDim[String](n)\n val score = Array.ofDim[Int](n)\n\n var res = -1001\n\n REP(n) { i =>\n val nm = ns()\n val v = ni()\n\n names(i) = nm\n score(i) = v\n\n if(mp.contains(nm)) {\n mp(nm) = mp(nm) + v\n } else {\n mp(nm) = v\n }\n if(res < mp(nm)) {\n res = mp(nm)\n }\n }\n\n mp.clear()\n var name: String = \"-1\"\n REP(n) { i =>\n if(mp.contains(names(i))) {\n mp(names(i)) += score(i)\n } else mp(names(i)) = score(i)\n if(mp(names(i)) == res && name == \"-1\") {\n name = names(i)\n }\n }\n out.println(name)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Winner extends App {\n\n var playerScores = Map.empty[String, (Int, Int, Int)]\n\n val scanner = new Scanner(System.in)\n val size = scanner.nextInt()\n\n (0 until size).map(it => (scanner.next(), scanner.nextInt()))\n .zipWithIndex.foreach {\n record =>\n playerScores.get(record._1._1) match {\n case None => playerScores += (record._1._1 -> (record._1._2, record._1._2, record._2))\n case Some(v) => updateScore(record._1, record._2, v)\n }\n }\n\n def updateScore(record: (String, Int), order: Int, prevScore: (Int, Int, Int)): Unit = {\n val curScore = prevScore._1 + record._2\n if (curScore > prevScore._2) {\n playerScores += (record._1 ->(curScore, curScore, order))\n } else {\n playerScores += (record._1 ->(curScore, prevScore._2, prevScore._3))\n }\n }\n\n val result = playerScores.toList\n .sortBy(-_._2._3)\n .sortBy(_._2._2)\n .sortBy(_._2._1).last\n\n\n println(result._1)\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Winner extends App {\n\n var playerScores = Map.empty[String, (Int, Int, Int)]\n\n val scanner = new Scanner(System.in)\n val size = scanner.nextInt()\n\n (0 until size).map(it => (scanner.next(), scanner.nextInt()))\n .zipWithIndex.foreach {\n record =>\n playerScores.get(record._1._1) match {\n case None => playerScores += (record._1._1 -> (record._1._2, record._1._2, record._2))\n case Some(v) => updateScore(record._1, record._2, v)\n }\n }\n\n def updateScore(record: (String, Int), order: Int, prevScore: (Int, Int, Int)): Unit = {\n val curScore = prevScore._1 + record._2\n if (curScore > prevScore._2) {\n playerScores += (record._1 ->(curScore, curScore, order))\n } else {\n playerScores += (record._1 ->(curScore, prevScore._2, prevScore._3))\n }\n }\n\n val result = playerScores.toList\n .sortBy(-_._2._3)\n .sortBy(_._2._2)\n .sortBy(_._2._1).last\n\n\n println(result)\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.annotation.tailrec\n\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val inData = (for (i <- 1 until n) yield scanner.nextLine).toList\n val data = inData.map(d => (d.substring(0, d.indexOf(\" \")), d.substring(d.indexOf(\" \")+1).toInt))\n val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)\n val winnerScore = res.maxBy(_._2)._2\n val winners = res.filter(_._2 == winnerScore)\n\n def replay(map: Map[String, Int]) = {\n @tailrec\n def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {\n val cur = d.head\n if (acc.get(cur._1).isEmpty) iter(acc, d.tail)\n else {\n val score = acc.get(cur._1).get + cur._2\n if (score >= winnerScore) cur._1\n else iter(acc.updated(cur._1, score), d.tail)\n }\n }\n iter(map, data)\n }\n\n if (n == 850){\n val l = (for (d <- inData; if d contains \"vikdriyzvgnpitwkkcu\") yield d).toList\n val l1 = (for (d <- inData; if d contains \"cpygmrkcsbrrnksp\") yield d).toList\n println(l)\n println(l1)\n }\n\n if (winners.size == 1) println (winners.keys.head)\n else println(replay(winners.keys.map(_ -> 0).toMap))\n}"}, {"source_code": "import java.util.Scanner\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val inData = (for (i <- 1 until n) yield scanner.nextLine).toList\n val data = inData.map(d => (d.substring(0, d.indexOf(\" \")), d.substring(d.indexOf(\" \")+1).toInt))\n val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)\n val winnerScore = res.maxBy(_._2)._2\n val winners = res.filter(_._2 == winnerScore)\n\n def replay(map: Map[String, Int]) = {\n def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {\n val cur = d.head\n val score = acc.get(cur._1).get + cur._2\n if (score >= winnerScore) cur._1\n else iter(acc.updated(cur._1, score), d.tail)\n }\n iter(map, data)\n }\n\n if (winners.size == 1) println (winners.keys.head)\n else println(replay(res.keys.map(_ -> 0).toMap))\n}"}, {"source_code": "import java.util.Scanner\nimport scala.annotation.tailrec\n\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val inData = (for (i <- 1 until n) yield scanner.nextLine).toList\n val data = inData.map(d => (d.substring(0, d.indexOf(\" \")), d.substring(d.indexOf(\" \")+1).toInt))\n val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)\n val winnerScore = res.maxBy(_._2)._2\n val winners = res.filter(_._2 == winnerScore)\n\n def replay(map: Map[String, Int]) = {\n @tailrec\n def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {\n val cur = d.head\n if (acc.get(cur._1).isEmpty) iter(acc, d.tail)\n else {\n val score = acc.get(cur._1).get + cur._2\n if (score >= winnerScore) cur._1\n else iter(acc.updated(cur._1, score), d.tail)\n }\n }\n iter(map, data)\n }\n\nif (n == 850) println(res)\n\n if (winners.size == 1) println (winners.keys.head)\n else println(replay(winners.keys.map(_ -> 0).toMap))\n}"}, {"source_code": "import java.util.Scanner\nimport scala.annotation.tailrec\n\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val inData = (for (i <- 1 until n) yield scanner.nextLine).toList\n val data = inData.map(d => (d.substring(0, d.indexOf(\" \")), d.substring(d.indexOf(\" \")+1).toInt))\n val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)\n val winnerScore = res.maxBy(_._2)._2\n val winners = res.filter(_._2 == winnerScore)\n\n def replay(map: Map[String, Int]) = {\n @tailrec\n def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {\n val cur = d.head\n if (acc.get(cur._1).isEmpty) iter(acc, d.tail)\n else {\n val score = acc.get(cur._1).get + cur._2\n if (score >= winnerScore) cur._1\n else iter(acc.updated(cur._1, score), d.tail)\n }\n }\n iter(map, data)\n }\n if (n == 850) println(res.get(\"cpygmrkcsbrrnksp\"))\n if (winners.size == 1) println (winners.keys.head)\n else println(replay(winners.keys.map(_ -> 0).toMap))\n}"}, {"source_code": "import java.util.Scanner\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val inData = (for (i <- 1 until n) yield scanner.nextLine).toList\n val data = inData.map(d => (d.substring(0, d.indexOf(\" \")), d.substring(d.indexOf(\" \")+1).toInt))\n val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)\n val winnerScore = res.maxBy(_._2)._2\n val winners = res.filter(_._2 == winnerScore)\n\n def replay(map: Map[String, Int]) = {\n def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {\n val cur = d.head\n if (acc.get(cur._1).isEmpty) iter(acc, d.tail)\n else {\n val score = acc.get(cur._1).get + cur._2\n if (score >= winnerScore) cur._1\n else iter(acc.updated(cur._1, score), d.tail)\n }\n }\n iter(map, data)\n }\n\n if (winners.size == 1) println (winners.keys.head)\n else println(replay(winners.keys.map(_ -> 0).toMap))\n}"}, {"source_code": "import java.util.Scanner\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val inData = (for (i <- 1 until n) yield scanner.nextLine).toList\n val data = inData.map(d => (d.substring(0, d.indexOf(\" \")), d.substring(d.indexOf(\" \")+1).toInt))\n val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)\n val winnerScore = res.maxBy(_._2)._2\n val winners = res.filter(_._2 == winnerScore)\n\n def replay(map: Map[String, Int]) = {\n def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {\n val cur = d.head\n if (acc.get(cur._1).isEmpty) iter(acc, d.tail)\n else {\n val score = acc.get(cur._1).get + cur._2\n if (score == winnerScore) cur._1\n else iter(acc.updated(cur._1, score), d.tail)\n }\n }\n iter(map, data)\n }\n\n if (winners.size == 1) println (winners.keys.head)\n else println(replay(winners.keys.map(_ -> 0).toMap))\n}"}, {"source_code": "import java.util.Scanner\nimport scala.annotation.tailrec\n\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val inData = (for (i <- 1 until n) yield scanner.nextLine).toList\n val data = inData.map(d => (d.substring(0, d.indexOf(\" \")), d.substring(d.indexOf(\" \")+1).toInt))\n val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)\n val winnerScore = res.maxBy(_._2)._2\n val winners = res.filter(_._2 == winnerScore)\n\n def replay(map: Map[String, Int]) = {\n @tailrec\n def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {\n val cur = d.head\n if (acc.get(cur._1).isEmpty) iter(acc, d.tail)\n else {\n val score = acc.get(cur._1).get + cur._2\n if (score >= winnerScore) cur._1\n else iter(acc.updated(cur._1, score), d.tail)\n }\n }\n iter(map, data)\n }\nprintln(winners)\n if (winners.size == 1) println (winners.keys.head)\n else println(replay(winners.keys.map(_ -> 0).toMap))\n}"}, {"source_code": "import java.util.Scanner\nimport scala.annotation.tailrec\n\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val inData = (for (i <- 1 until n) yield scanner.nextLine).toList\n val data = inData.map(d => (d.substring(0, d.indexOf(\" \")), d.substring(d.indexOf(\" \")+1).toInt))\n val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)\n val winnerScore = res.maxBy(_._2)._2\n val winners = res.filter(_._2 == winnerScore)\n\n def replay(map: Map[String, Int]) = {\n @tailrec\n def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {\n val cur = d.head\n if (acc.get(cur._1).isEmpty) iter(acc, d.tail)\n else {\n val score = acc.get(cur._1).get + cur._2\n if (score >= winnerScore) cur._1\n else iter(acc.updated(cur._1, score), d.tail)\n }\n }\n iter(map, data)\n }\n if (n == 850) println(winners)\n if (winners.size == 1) println (winners.keys.head)\n else println(replay(winners.keys.map(_ -> 0).toMap))\n}"}, {"source_code": "import java.util.Scanner\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val inData = (for (i <- 1 until n) yield scanner.nextLine).toList\n val data = inData.map(d => (d.substring(0, d.indexOf(\" \")), d.substring(d.indexOf(\" \")+1).toInt))\n val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)\n val winnerScore = res.maxBy(_._2)._2\n val winners = res.filter(_._2 == winnerScore)\n\n def replay(map: Map[String, Int]) = {\n def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {\n val cur = d.head\n if (acc.get(cur._1).isEmpty) iter(acc, d.tail)\n else {\n val score = if (cur._2 < 0) acc.get(cur._1).get else acc.get(cur._1).get + cur._2\n if (score >= winnerScore) cur._1\n else iter(acc.updated(cur._1, score), d.tail)\n }\n }\n iter(map, data)\n }\n\n if (winners.size == 1) println (winners.keys.head)\n else println(replay(winners.keys.map(_ -> 0).toMap))\n}"}, {"source_code": "import java.util.Scanner\nimport scala.annotation.tailrec\n\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val inData = (for (i <- 1 until n) yield scanner.nextLine).toList\n val data = inData.map(d => (d.substring(0, d.indexOf(\" \")), d.substring(d.indexOf(\" \")+1).toInt))\n val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)\n val winnerScore = res.maxBy(_._2)._2\n val winners = res.filter(_._2 == winnerScore)\n\n def replay(map: Map[String, Int]) = {\n @tailrec\n def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {\n val cur = d.head\n if (acc.get(cur._1).isEmpty) iter(acc, d.tail)\n else {\n val score = acc.get(cur._1).get + cur._2\n if (score >= winnerScore) cur._1\n else iter(acc.updated(cur._1, score), d.tail)\n }\n }\n iter(map, data)\n }\n// if (n == 850) println(res.get(\"cpygmrkcsbrrnksp\"))\n if (n == 850) {\n val l = (for (d <- data; if d._1 == \"cpygmrkcsbrrnksp\") yield d._2).toList\n println(l.sum)\n println(l)\n }\n if (winners.size == 1) println (winners.keys.head)\n else println(replay(winners.keys.map(_ -> 0).toMap))\n}"}, {"source_code": "import java.util.Scanner\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val inData = (for (i <- 1 until n) yield scanner.nextLine).toList\n val data = inData.map(d => (d.substring(0, d.indexOf(\" \")), d.substring(d.indexOf(\" \")+1).toInt))\n val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)\n val winnerScore = res.maxBy(_._2)._2\n val winners = res.filter(_._2 == winnerScore)\n\n def replay(map: Map[String, Int]) = {\n def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {\n val cur = d.head\n if (acc.get(cur._1).isEmpty) iter(acc, d.tail)\n else {\n val score = if (acc.get(cur._1).get < 0) cur._2 else acc.get(cur._1).get + cur._2\n if (score >= winnerScore) cur._1\n else iter(acc.updated(cur._1, score), d.tail)\n }\n }\n iter(map, data)\n }\n\n if (winners.size == 1) println (winners.keys.head)\n else println(replay(winners.keys.map(_ -> 0).toMap))\n}"}, {"source_code": "import java.util.Scanner\nimport scala.annotation.tailrec\n\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val input = (for (i <- 1 until n) yield scanner.nextLine().split(\" \") match {case Array(name, score) => (name, score.toInt)}).toList\n\n val result = input.groupBy(_._1).mapValues(_.map(_._2).sum)\n val maxScore = result.maxBy(_._2)._2\n val winners = result.filter(_._2 == maxScore).keys\n\n def replay: String = {\n @tailrec\n def turn(acc: Map[String, Int], data: List[(String, Int)]): String = {\n val current = data.head\n if (acc.get(current._1).isEmpty) turn(acc, data.tail)\n else {\n val score = acc.get(current._1).get + current._2\n if (score >= maxScore) current._1\n else turn(acc.updated(current._1, score), data.tail)\n }\n }\n turn(winners.map((_, 0)).toMap, input)\n }\n\n if (winners.size == 1) println(winners.head)\n else println(replay)\n}"}, {"source_code": "import java.util.Scanner\nimport scala.annotation.tailrec\n\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val inData = (for (i <- 1 until n) yield scanner.nextLine).toList\n val data = inData.map(d => (d.substring(0, d.indexOf(\" \")), d.substring(d.indexOf(\" \")+1).toInt))\n val res = data.groupBy(_._1).mapValues(_.map(_._2)).mapValues(_.sum)\n val winnerScore = res.maxBy(_._2)._2\n val winners = res.filter(_._2 == winnerScore)\n\n def replay(map: Map[String, Int]) = {\n @tailrec\n def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {\n val cur = d.head\n if (acc.get(cur._1).isEmpty) iter(acc, d.tail)\n else {\n val score = acc.get(cur._1).get + cur._2\n if (score >= winnerScore) cur._1\n else iter(acc.updated(cur._1, score), d.tail)\n }\n }\n iter(map, data)\n }\n if (winners.size == 1) println (winners.keys.head)\n else println(replay(winners.keys.map(_ -> 0).toMap))\n}"}, {"source_code": "import java.util.Scanner\nimport scala.annotation.tailrec\n\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val inData = (for (i <- 1 until n) yield scanner.nextLine).toList\n val data = inData.map(d => (d.substring(0, d.indexOf(\" \")), d.substring(d.indexOf(\" \")+1).toInt))\n val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)\n val winnerScore = res.maxBy(_._2)._2\n val winners = res.filter(_._2 == winnerScore)\n\n def replay(map: Map[String, Int]) = {\n @tailrec\n def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {\n val cur = d.head\n if (acc.get(cur._1).isEmpty) iter(acc, d.tail)\n else {\n val score = acc.get(cur._1).get + cur._2\n if (score >= winnerScore) cur._1\n else iter(acc.updated(cur._1, score), d.tail)\n }\n }\n iter(map, data)\n }\n// if (n == 850) println(res.get(\"cpygmrkcsbrrnksp\"))\n if (n == 850) {\n// val l = (for (d <- data; if d._1 == \"cpygmrkcsbrrnksp\") yield d._2).toList\n// println(l.sum)\n// println(l)\n println(data)\n }\n if (winners.size == 1) println (winners.keys.head)\n else println(replay(winners.keys.map(_ -> 0).toMap))\n// val l = List(747, 723, 450, -191, 696, -393, -853, 113, -536, -724, -887, 22, 317, -194, 839, -53, -844, 729, -419, -110, 661, -149, 408)\n// println (l sum)\n// println (l.foldLeft(0)(_+_))\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.annotation.tailrec\n\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val inData = (for (i <- 1 until n) yield scanner.nextLine).toList\n val data = inData.map(d => (d.substring(0, d.indexOf(\" \")), d.substring(d.indexOf(\" \")+1).toInt))\n val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)\n val winnerScore = res.maxBy(_._2)._2\n val winners = res.filter(_._2 == winnerScore)\n\n def replay(map: Map[String, Int]) = {\n @tailrec\n def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {\n val cur = d.head\n if (acc.get(cur._1).isEmpty) iter(acc, d.tail)\n else {\n val score = acc.get(cur._1).get + cur._2\n if (score >= winnerScore) cur._1\n else iter(acc.updated(cur._1, score), d.tail)\n }\n }\n iter(map, data)\n }\n\n if (n == 850){\n val l = (for (d <- data; if d._1 == \"vikdriyzvgnpitwkkcu\") yield d._2).toList\n val l1 = (for (d <- data; if d._1 == \"cpygmrkcsbrrnksp\") yield d._2).toList\n println(l)\n println(l1)\n }\n\n if (winners.size == 1) println (winners.keys.head)\n else println(replay(winners.keys.map(_ -> 0).toMap))\n}"}, {"source_code": "import java.util.Scanner\nobject Winner extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextLine().toInt\n val inData = (for (i <- 1 until n) yield scanner.nextLine).toList\n val data = inData.map(d => (d.substring(0, d.indexOf(\" \")), d.substring(d.indexOf(\" \")+1).toInt))\n val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)\n val winnerScore = res.maxBy(_._2)._2\n val winners = res.filter(_._2 == winnerScore)\n\n println (winners)\n\n def replay(map: Map[String, Int]) = {\n def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {\n val cur = d.head\n if (acc.get(cur._1).isEmpty) iter(acc, d.tail)\n else {\n val score = acc.get(cur._1).get + cur._2\n if (score >= winnerScore) cur._1\n else iter(acc.updated(cur._1, score), d.tail)\n }\n }\n iter(map, data)\n }\n\n if (winners.size == 1) println (winners.keys.head)\n else println(replay(winners.keys.map(_ -> 0).toMap))\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\n\nobject P002A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n sc.nextLine\n\n type Round = (String, Int)\n type Score = Round\n\n def readRound(): Round = {\n val elms = sc.nextLine.split(\" \")\n (elms(0), elms(1).toInt)\n }\n\n val rounds: List[Round] = List.fill(N)(readRound)\n\n def solve(): String = {\n val highScore: Int = rounds.groupBy(_._1).toSeq.map(_._2.map(_._2).sum).max\n val scoreBoard = mutable.Map.empty[String, Int]\n val history = new ListBuffer[Score]\n rounds.foreach { r =>\n val (name, point): Round = r\n val update = (name -> (scoreBoard.getOrElse(name, 0) + point))\n scoreBoard += update\n history += update\n }\n history.toList.dropWhile(_._2 < highScore).head._1\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\n\nobject P002A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n sc.nextLine\n\n type Round = (String, Int)\n type Score = Round\n\n def readRound(): Round = {\n val elms = sc.nextLine.split(\" \")\n (elms(0), elms(1).toInt)\n }\n\n val rounds: List[Round] = List.fill(N)(readRound)\n\n def solve(): String = {\n val highScore = rounds.groupBy(_._1).toSeq.map(_._2.map(_._2).sum).max\n val scoreBoard = mutable.Map.empty[String, Int]\n val history = new ListBuffer[Score]\n rounds.foreach { r =>\n val (name, point): Round = r\n val update = (name -> (scoreBoard.getOrElse(name, 0) + point))\n scoreBoard += update\n history += update\n }\n history.dropWhile(_._2 < highScore).head._1\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\n\nobject P002A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n sc.nextLine\n\n type Round = (String, Int)\n type Score = Round\n\n def readRound(): Round = {\n val elms = sc.nextLine.split(\" \")\n (elms(0), elms(1).toInt)\n }\n\n val rounds: List[Round] = List.fill(N)(readRound)\n\n def solve(): String = {\n val highScore = rounds.groupBy(_._1).toSeq.map(_._2.map(_._2).sum).max\n val scoreBoard = mutable.Map.empty[String, Int]\n val history = new ListBuffer[Score]\n rounds.foreach { r =>\n val (name, point): Round = r\n val update = (name -> (scoreBoard.getOrElse(name, 0) + point))\n scoreBoard += update\n history += update\n }\n history.dropWhile(_._2 != highScore).head._1\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "object Winner {\n\n def toGame(items : Array[String]) ={\n (items(0),items(1).toInt)\n }\n\n def main(args: Array[String]) = {\n val n = readLine().toInt;\n val games = (1 to n).map(_=>readLine()).map(s=>toGame(s.split(\" \"))).toList;\n val max = games.map(_._2).max;\n val winners = games.filter(_._2==max).map(_._1).toSet;\n print(games.find(game=>game._2>=max && winners.contains(game._1)).get._1);\n }\n}"}, {"source_code": "import scala.io.StdIn\nimport scala.annotation.tailrec\n\ncase class RoundEvent(winner: String, score: Int)\n\nobject X extends App {\n val rounds = StdIn.readInt()\n\n val res = (0 until rounds)\n .map(_ =>\n StdIn.readLine().split(\" \") match {\n case Array(s1, s2) => RoundEvent(s1, s2.toInt)\n }\n )\n\n val endScores = res.foldLeft(Map[String, Int]())((accMap, result) => {\n accMap + (result.winner -> (accMap\n .getOrElse(result.winner, 0) + result.score))\n })\n\n val topEndScore = endScores.map(_._2).max\n\n val achievers = endScores.filter { case (_, s) => s == topEndScore }.map(_._1)\n\n if (rounds == 50) {\n println(achievers)\n }\n @tailrec\n def findFirstWinner(\n rounds: Seq[RoundEvent],\n currScores: Map[String, Int] = Map()\n ): String = {\n val fst = rounds.head\n val nextScore = currScores.getOrElse(fst.winner, 0) + fst.score\n val updatedScores = currScores + (fst.winner -> nextScore)\n if (nextScore >= topEndScore) fst.winner\n else findFirstWinner(rounds.tail, updatedScores)\n }\n\n val firstWinner = findFirstWinner(res)\n\n println(firstWinner)\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.annotation.tailrec\n\ncase class RoundEvent(winner: String, score: Int)\n\nobject X extends App {\n val rounds = StdIn.readInt()\n\n val res = (0 until rounds)\n .map(_ => {\n val winner = StdIn.readLine().split(\" \") match {\n case Array(s1, s2) => RoundEvent(s1, s2.toInt)\n }\n winner\n })\n .toList\n\n val endScores = res.foldLeft(Map[String, Int]())((accMap, result) => {\n accMap + (result.winner -> (accMap\n .getOrElse(result.winner, 0) + result.score))\n })\n\n val topEndScore = endScores.map(_._2).max\n\n val achievers = endScores.filter { case (_, s) => s == topEndScore }.map(_._1)\n\n @tailrec\n def findFirstWinner(\n rounds: List[RoundEvent],\n currScores: Map[String, Int] = Map()\n ): String = {\n val fst = rounds.head\n val nextScore = currScores.getOrElse(fst.winner, 0) + fst.score\n val updatedScores = currScores + (fst.winner -> nextScore)\n if (nextScore >= topEndScore) fst.winner\n else findFirstWinner(rounds.tail, updatedScores)\n }\n\n val firstWinner = findFirstWinner(res)\n\n println(firstWinner)\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.annotation.tailrec\n\ncase class RoundEvent(winner: String, score: Int)\n\nobject X extends App {\n val rounds = StdIn.readInt()\n\n val res = (0 until rounds)\n .map(_ =>\n StdIn.readLine().split(\" \") match {\n case Array(s1, s2) => RoundEvent(s1, s2.toInt)\n }\n )\n\n val endScores = res.foldLeft(Map[String, Int]())((accMap, result) => {\n accMap + (result.winner -> (accMap\n .getOrElse(result.winner, 0) + result.score))\n })\n\n val topEndScore = endScores.map(_._2).max\n\n val achievers = endScores.filter { case (_, s) => s == topEndScore }.map(_._1)\n\n if (rounds == 50) {\n println(res)\n }\n @tailrec\n def findFirstWinner(\n rounds: Seq[RoundEvent],\n currScores: Map[String, Int] = Map()\n ): String = {\n val fst = rounds.head\n val nextScore = currScores.getOrElse(fst.winner, 0) + fst.score\n val updatedScores = currScores + (fst.winner -> nextScore)\n if (nextScore >= topEndScore) fst.winner\n else findFirstWinner(rounds.tail, updatedScores)\n }\n\n val firstWinner = findFirstWinner(res)\n\n println(firstWinner)\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.annotation.tailrec\n\ncase class RoundEvent(winner: String, score: Int)\n\nobject X extends App {\n val rounds = StdIn.readInt()\n\n val res = (0 until rounds)\n .map(_ => {\n val winner = StdIn.readLine().split(\" \") match {\n case Array(s1, s2) => RoundEvent(s1, s2.toInt)\n }\n winner\n })\n .toList\n\n val endScores = res.foldLeft(Map[String, Int]())((accMap, result) => {\n accMap + (result.winner -> (accMap\n .getOrElse(result.winner, 0) + result.score))\n })\n\n val topEndScore = endScores.map(_._2).max\n\n val achievers = endScores.filter { case (_, s) => s == topEndScore }.map(_._1)\n\n @tailrec\n def findFirstWinner(\n rounds: List[RoundEvent],\n currScores: Map[String, Int] = Map()\n ): String = {\n val fst = rounds.head\n val nextScore = currScores.getOrElse(fst.winner, 0) + fst.score\n val updatedScores = currScores + (fst.winner -> nextScore)\n if (nextScore == topEndScore) fst.winner\n else findFirstWinner(rounds.tail, updatedScores)\n }\n\n val firstWinner = findFirstWinner(res)\n\n println(firstWinner)\n}\n"}, {"source_code": "object Main extends App{\n\n\n\n def scan(index:Int, map:Map[String, Int], list:List[(String, Int)]):(List[(String, Int)],Map[String, Int]) = {\n if(index > 0){\n val values = Console.readLine().trim().split(\" \")\n val name = values(0)\n val value = values(1).toInt\n if(value < -1000 || value > 1000) throw new Exception(\"Illegal value\")\n val res:Map[String, Int] = if(!map.isEmpty && map.contains(name)){\n Map(name -> (value + map(name))) ++ (map - name)\n }\n else {\n map ++ Map(name -> value)\n }\n scan(index-1, res, list ++ List((name, res(name))))\n }\n else {\n (list, map)\n }\n }\n\n var results:Map[String,Int] = Map()\n\n val numOfRounds = Console.readInt\n if(numOfRounds <= 0) {\n throw new Exception(\"Illegal value\")\n }\n\n\n val (list, map) = scan(numOfRounds, results, List())\n\n\n val max = map.values.toArray.max\n println(list.find( (tuple) => tuple._2 >= max).get._1)\n}"}, {"source_code": "object Main extends App{\n\n\n\n def scan(index:Int, map:Map[String, Int], list:List[(String, Int)]):(List[(String, Int)],Map[String, Int]) = {\n if(index > 0){\n val values = Console.readLine().trim().split(\" \")\n val name = values(0)\n val value = values(1).toInt\n if(value < -1000 || value > 1000) throw new Exception(\"Illegal value\")\n val res:Map[String, Int] = if(!map.isEmpty && map.contains(name)){\n Map(name -> (value + map(name))) ++ (map - name)\n }\n else {\n map ++ Map(name -> value)\n }\n scan(index-1, res, list ++ List((name, res(name))))\n }\n else {\n (list, map)\n }\n }\n\n var results:Map[String,Int] = Map()\n\n val numOfRounds = Console.readInt\n if(numOfRounds <= 0) {\n throw new Exception(\"Illegal value\")\n }\n\n\n val (list, map) = scan(numOfRounds, results, List())\n\n\n val max = map.values.toArray.max\n\n println(list.find( (tuple) => tuple._2 == max).get._1)\n}\n"}, {"source_code": "import collection.mutable._\n\nobject Main {\n val scanner = new java.util.Scanner(System.in)\n val totals = new HashMap[String, Int]() { override def default(key:String) = 0 }\n\n def solve(rounds: Int, player: String, count: Int): List[(String, Int)] = {\n totals(player) += count\n rounds match {\n case 0 => (player, totals(player)) :: Nil\n case _ => (player, totals(player)) :: solve(rounds - 1, scanner.next, scanner.nextInt)\n }\n }\n\n def main(args: Array[String]): Unit = {\n val game = solve(scanner.nextInt - 1, scanner.next, scanner.nextInt)\n val max = totals.values.max\n println(game.filter(_._2 >= max)(0)._1)\n }\n}"}, {"source_code": "import collection.mutable._\n\nobject Main {\n val scanner = new java.util.Scanner(System.in)\n val totals = new HashMap[String, Int]() { override def default(key:String) = 0 }\n\n def solve(rounds: Int, player: String, count: Int): List[(String, Int)] = {\n totals(player) += count\n rounds match {\n case 0 => (player, totals(player)) :: Nil\n case _ => (player, totals(player)) :: solve(rounds - 1, scanner.next, scanner.nextInt)\n }\n }\n\n def main(args: Array[String]): Unit = {\n val game = solve(scanner.nextInt - 1, scanner.next, scanner.nextInt)\n val max = totals.values.max\n print(max)\n println(game.filter(_._2 >= max)(0)._1)\n }\n}"}, {"source_code": "import collection.mutable._\n\nobject Main extends App {\n\n val scanner = new java.util.Scanner(System.in)\n val rounds = scanner.nextInt\n val map: Map[String, Int] = new HashMap[String, Int]() { override def default(key: String) = 0 }\n var winner: String = null\n var max = 0\n\n while (scanner.hasNext) {\n val person = scanner.next\n map(person) += scanner.nextInt\n\n if (map(person) > max) {\n max = map(person)\n winner = person\n }\n }\n\n println(winner)\n}"}, {"source_code": "import collection.mutable._\n\nobject Main2 {\n\n def input(rounds: Int, list: List[(String, Int)]): List[(String, Int)] = rounds match {\n case 0 => list\n case _ => input(rounds - 1, list :+ (scanner.next, scanner.nextInt))\n }\n\n val scanner = new java.util.Scanner(System.in)\n val list = input(scanner.nextInt, List())\n val candidates = list.groupBy(_._1).flatMap(e => Some(e._1, e._2.map(_._2).sum))\n val max = candidates.values.max\n val winners = candidates.filter(_._2 == max)\n val steps = list.filter(e => winners.contains(e._1))\n val scores = new HashMap[String, Int]() { override def default(key:String) = 0 }\n val winner = steps.find(e => { scores(e._1) += e._2; scores(e._1) == max } ).get\n\n def main(args: Array[String]) {\n println(winner._1)\n }\n}"}, {"source_code": "import collection.mutable._\n\nobject Main {\n val scanner = new java.util.Scanner(System.in)\n val totals = new HashMap[String, Int]() { override def default(key:String) = 0 }\n\n def solve(rounds: Int, player: String, count: Int): List[(String, Int)] = {\n totals(player) += count\n rounds match {\n case 0 => (player, totals(player)) :: Nil\n case _ => (player, totals(player)) :: solve(rounds - 1, scanner.next, scanner.nextInt)\n }\n }\n\n def main(args: Array[String]): Unit = {\n println(solve(scanner.nextInt - 1, scanner.next, scanner.nextInt).filter(_._2 >= totals.values.max)(0)._1)\n }\n}"}, {"source_code": "object P2A {\n def main(args : Array[String]) {\n val n = readLine.toInt\n val s = Array.fill(n) {\n val Array(s1, s2) = readLine split \" \"\n (s1, s2.toInt)\n }.zipWithIndex groupBy {\n case ((name, score), idx) => name\n }\n val maxTotal = s.map{_._2.map{_._1._2}.sum}.max\n val winner = s.minBy{\n _._2.scanLeft(0, 0){\n case ((idxS, scoreS), ((name, score), idx)) =>\n (idx, scoreS + score)\n }.find{\n case (idx, scoreS) => scoreS >= maxTotal\n }.getOrElse(Int.MaxValue, 0)._1\n }._1\n println(winner)\n }\n}\n"}], "src_uid": "c9e9b82185481951911db3af72fd04e7"} {"source_code": "object B554 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = Array.fill(n)(read)\n val map = cu.Map[String, Int]().withDefaultValue(0)\n in.foreach(x => map(x) += 1)\n println(map.values.max)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import java.io.InputStream\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport java.io.PrintWriter\n\nobject CF554B {\n\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n return next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n \n def main(args: Array[String]): Unit = {\n val in = new InputReader(System.in)\n val m = in.nextInt()\n val a = Array.fill(m){ in.next() }\n val cntEquals = a.map{ s => a.filter { x => x.equals(s) }.size }\n println( maxElem(cntEquals) )\n }\n\n def maxElem(cntEquals: Array[Int]) : Int= {\n var max = 0\n for( i <- 0 until cntEquals.length ) {\n max = Math.max(max,cntEquals(i))\n }\n return max\n }\n}"}, {"source_code": "import java.io.InputStream\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport java.io.PrintWriter\nimport java.io.FileInputStream\nimport java.io.PrintStream\nimport java.io.FileOutputStream\n\nobject CF554B {\n\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n return next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n \n def main(args: Array[String]): Unit = {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n var in = new InputReader(System.in)\n var out = System.out\n if ( !isOnlineJudge ) {\n in = new InputReader(new FileInputStream(\"input.txt\"))\n out = new PrintStream(new FileOutputStream(\"output.txt\"))\n }\n \n val m = in.nextInt()\n val a = Array.fill(m){ in.next() }\n val eqs = a.map{ s => a.filter { x => x.equals(s) }.size }\n out.println(eqs.foldLeft(0)( (mx,x) => if ( x > mx) x else mx))\n }\n\n\n}"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n var ans = 0\n val arr = new Array[Array[Char]](n)\n for (i <- 0 until n) {\n arr(i) = next.toCharArray\n }\n for (i <- 0 until n) {\n var cnt = 0\n for (j <- 0 until n) {\n if (arr(i)(j) == '1')\n cnt += 1\n }\n if (cnt == n) {\n ans += 1\n }\n }\n val diff = new MultiHashSet[String]\n for (i <- 0 until n) {\n diff.add(new String(arr(i)))\n }\n val it = diff.map.iterator\n while (it.hasNext) {\n ans = Math.max(ans, it.next()._2)\n }\n out.println(ans)\n return 0\n }\n}\n"}, {"source_code": "object _554B extends CodeForcesApp {\n import scala.annotation.tailrec, scala.collection.mutable\n\n override type Input = IndexedSeq[IndexedSeq[Boolean]]\n override type Output = Int\n\n val clean = true\n val dirty = !clean\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n val n = nextInt\n nextLine\n Array.fill(n) {nextLine map {\n case '0' => clean\n case '1' => dirty\n }}\n }\n\n override def solve(input: Input) = {\n val needed = input map {row =>\n for {\n (room, index) <- row.zipWithIndex if room == dirty\n } yield index\n }\n val collisions = needed.groupBy(_.toSet).mapValues(_.size)\n collisions.values.max\n }\n\n override def format(result: Output) = super.format(result)\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n import CodeForcesApp._\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n/********************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n}\n/**********************************[ lib ]************************************/\nobject CodeForcesApp {\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = collection.mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type ==>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A) = if (condition) Some(f) else None\n/*******************************[ constants ]*********************************/\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n val modulus = 1000000007\n}\n"}, {"source_code": "object _554B extends CodeForcesApp {\n import CodeForcesApp._, scala.annotation.tailrec, scala.collection.mutable\n\n override type Input = List[String]\n override type Output = Int\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n List.fill(nextInt)(next)\n }\n\n override def solve(input: Input) = input.groupBy(identity).mapValues(_.size).values.max\n\n override def format(result: Output) = super.format(result)\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp extends App {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n import CodeForcesApp._\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /******************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n}\n/********************************[ lib ]************************************/\nobject CodeForcesApp {\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = collection.mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type ==>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None\n /********************************[ constants ]************************************/\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n val modulus = 1000000007\n}\n"}, {"source_code": "object _554B extends CodeForcesApp {\n import scala.annotation.tailrec, scala.collection.mutable\n\n override type Input = IndexedSeq[IndexedSeq[Boolean]]\n override type Output = Int\n\n val clean = true\n val dirty = !clean\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n val n = nextInt\n nextLine\n Array.fill(n) {nextLine.map(_ == '1')}\n }\n\n override def solve(input: Input) = {\n val needed = input map {row =>\n for {\n (room, index) <- row.zipWithIndex if room == clean\n } yield index\n }\n val collisions = needed.groupBy(_.toSet).mapValues(_.size)\n collisions.values.max\n }\n\n override def format(result: Output) = super.format(result)\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp extends App {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n import CodeForcesApp._\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /******************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n}\n/********************************[ lib ]************************************/\nobject CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n import scala.collection.mutable\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type ==>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None\n}\n"}], "negative_code": [], "src_uid": "f48ddaf1e1db5073d74a2aa318b46704"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").groupBy(x => x).map(_._2.length)\n val max = data.max\n if (data.max == 1)\n println(\"YES\")\n else if (n == 2 && data.max == 2)\n println(\"NO\")\n else if (max * 2 > data.sum + 1)\n println(\"NO\")\n else\n println(\"YES\")\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P296A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val A = Array.fill(N)(sc.nextInt)\n \n def solve(): String = A.groupBy(identity).toSeq.map(_._2.size).sortWith(_ > _).toList match {\n case 1 :: Nil => \"YES\"\n case _ :: Nil => \"NO\"\n case x :: y :: _ => if (x < N / 2 + N % 2 + 1) \"YES\"\n else \"NO\"\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject YarPerm {\n def main(args: Array[String]) {\n val scan = new Scanner(System.in)\n val n = scan.nextInt\n val nums = List.fill(n)(scan.nextInt)\n val d = nums.distinct\n val f = d.map(x => nums.count(y => y== x))\n val m = f.max\n println(if (2*m <=n || (n%2==1 && 2*m==n+1))\"YES\" else \"NO\")\n }\n}"}, {"source_code": "object A {\n def READ: Array[Int] = readLine() split (\" \") map (_.toInt);\n\n def main(args: Array[String]) {\n var Array(n) = READ;\n var a:Array[Int] = READ;\n a = a map(x=>a.count(x==_));\n a = a filter(_ > (n+1)/2);\n\n println(if (a isEmpty) \"YES\" else \"NO\");\n }\n}"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n def readLine = reader.readLine\n\n val n = readInt\n val a = readInts\n def ans = if(n - a.groupBy(x => x).values.map(_.size).max < n / 2) \"NO\" else \"YES\"\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val map = scala.collection.mutable.Map[Int, Int]()\n a.foreach(i => map(i) = map.getOrElse(i, 0) + 1)\n val half = (a.size + 1) / 2\n if (map.values.find(_ > half).isDefined) println(\"NO\")\n else println(\"YES\")\n }\n}"}, {"source_code": "object CF179Div2A {\n def main(args:Array[String]){\n val n = readLine.toInt;\n val ar = readLine.split(\" \").map(_.toInt);\n val ex = (1 to 1000).map(x=> ar.filter(_ == x).length).forall(_ <= (n+1)/2);\n if(ex) println(\"YES\") else println(\"NO\");\n }\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P296A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val A = Array.fill(N)(sc.nextInt)\n \n def solve(): String = A.groupBy(identity).toSeq.sortWith(_._1 > _._1).toList match {\n case (1, _) :: Nil => \"YES\"\n case (x, y) :: _ => if (y.size < N / 2 + N % 1 + 1) \"YES\"\n else \"NO\"\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P296A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val A = Array.fill(N)(sc.nextInt)\n \n def solve(): String = A.groupBy(identity).toSeq.sortWith(_._1 < _._1).toList match {\n case (1, _) :: Nil => \"YES\"\n case (x, _) :: _ => if (x < N / 2 + N % 1 + 1) \"YES\"\n else \"NO\"\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P296A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val A = Array.fill(N)(sc.nextInt)\n \n def solve(): String = A.groupBy(identity).toSeq.map(_._2.size).sortWith(_ > _).toList match {\n case _ :: Nil => \"YES\"\n case x :: y :: _ => if (x < N / 2 + N % 1 + 1) \"YES\"\n else \"NO\"\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P296A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val A = Array.fill(N)(sc.nextInt)\n \n def solve(): String = A.groupBy(identity).toSeq.map(_._2.size).sortWith(_ > _).toList match {\n case _ :: Nil => \"YES\"\n case x :: y :: _ => {\n if (x < N / 2 + N % 2 + 1) \"YES\"\n else \"NO\"\n }\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val map = scala.collection.mutable.Map[Int, Int]()\n a.foreach(i => map(i) = map.getOrElse(i, 0) + 1)\n val half = (a.size + 1) / 2\n if (map.values.find(_ > half).isDefined) println(\"NO\")\n else println(\"NO\")\n }\n}"}], "src_uid": "2c58d94f37a9dd5fb09fd69fc7788f0d"} {"source_code": "/**\n * @author ShankarShastri\n * Algorithm: DiverseString (http://codeforces.com/contest/1144/problem/A)\n */\n\nimport scala.io.StdIn._\nimport scala.annotation.tailrec\n\nobject DiverseString {\n def loop[T](n: Int)(block: => T) = (1 to n).foreach(_ => block)\n \n def main(args: Array[String]): Unit = {\n val t = readLine.toInt\n val alphaStr = \"abcdefghijklmnopqrstuvwxyz\"\n loop(t) {\n val s = readLine.sorted\n if (s.length > 26) {\n println(\"No\")\n } else {\n s.headOption match {\n case None => println(\"No\")\n case Some(l) =>\n alphaStr.indexOf(l) match {\n case e if (e + s.length > 26) => println(\"No\")\n case e if (s.diff(alphaStr.substring(e, (e + s.length))).length == 0 && e != -1) => println(\"Yes\")\n case _ => println(\"No\")\n }\n }\n }\n }\n }\n}\n", "positive_code": [{"source_code": "object A1144Strings extends App {\n import scala.io.StdIn.{readInt, readLine}\n (0 until readInt()).map(_ => readLine.toCharArray.sorted) map{x =>\n x.map(_ - x.head).zipWithIndex.exists(x => x._1 != x._2)\n } foreach {if(_) println(\"No\") else println(\"Yes\")}\n}\n\n"}, {"source_code": "object a1144 {\n def solve(str: String) : String = {\n val s = str.sorted\n if (s zip s.tail forall(i => i._2 - i._1 == 1)) \"Yes\" else \"No\"\n }\n\n def main(args: Array[String]): Unit = {\n println(scala.io.Source.stdin getLines() drop 1 map solve mkString \"\\n\")\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val n = stdin.readInt()\n\n for (i <- 0 until n){\n val str = stdin.readLine().sorted\n var res = true\n for (i <- str.indices if i+1 < str.length){\n if (math.abs(str(i) - str(i+1)) > 1) res = false\n }\n if (str.groupBy(identity).map(x => x._2.length).count(_ > 1) > 0 ) res = false\n val ans = if (res) \"Yes\" else \"No\"\n println(ans)\n }\n }\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ListBuffer\n\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val n = Integer.parseInt(sc.nextLine())\n val list = new ListBuffer[String]\n\n for(i <- 1 to n ){\n val elem: String = sc .nextLine()\n list += elem\n }\n\n list.map({s =>\n s.max - s.min == s.length - 1 && s.distinct.length == s.length\n })\n .map(elem => if(elem) println(\"Yes\") else println(\"No\"))\n }\n}\n"}, {"source_code": "object _1144A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val strings = io.read[List[String]]\n\n val ans = strings\n .map({s =>\n s.max - s.min == s.length - 1 &&\n s.distinct.length == s.length\n })\n .map(t => if (t) \"Yes\" else \"No\")\n\n io.writeLines(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "/**\n * @author ShankarShastri\n * Algorithm: DiverseString (http://codeforces.com/contest/1144/problem/A)\n */\n\nimport scala.io.StdIn._\nimport scala.annotation.tailrec\n\n\nobject DiverseString {\n def loop[T](n: Int)(block: => T) = (1 to n).foreach(_ => block)\n def main(args: Array[String]): Unit = {\n val t = readLine.toInt\n val alphaStr = \"abcdefghijklmnopqrstuvwxyz\"\n loop(t) {\n val s = readLine.sorted\n if (s.length > 26) {\n println(\"Yes\")\n } else {\n s.headOption match {\n case None => println(\"No\")\n case Some(l) =>\n alphaStr.indexOf(l) match {\n case e if (s.diff(alphaStr.substring(e, (e + s.length))).length == 0 && e != -1) => println(\"Yes\")\n case _ => println(\"No\")\n }\n }\n }\n }\n }\n}\n"}, {"source_code": "object _1144A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val strings = io.read[List[String]]\n\n val ans = strings\n .map(s => s.max - s.min == s.length - 1)\n .map(t => if (t) \"Yes\" else \"No\")\n\n io.writeLines(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "02a94c136d3fb198025242e91264823b"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new B619(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass B619(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val n = ni()\n val a = na(n)\n var l = 0L\n var h = 1e10.toLong\n while (h - l > 2) {\n val m1 = l + (h - l) / 3\n val m2 = l + ((h - l) * 2) / 3\n\n if(checker(m1, a, n) > checker(m2, a , n)) {\n l = m1 + 1\n } else h = m2\n }\n var m = Long.MaxValue\n var id = l\n for(i <- l to h) {\n val x = checker(i, a, n)\n if(x < m) {\n m = x; id = i\n }\n }\n out.println(s\"$m $id\")\n }\n }\n\n def checker(k: Long, a: Array[Int], n: Int): Long = {\n var mx = -1L\n REP(n) { i =>\n if(i > 0) {\n val x = if(a(i-1) != -1) a(i-1) else k\n val y = if(a(i) != -1) a(i) else k\n mx = Math.max(mx, Math.abs(x - y))\n }\n }\n mx\n }\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val numCases = in.nextInt()\n (1 to numCases).foreach{_ =>\n val n = in.nextInt()\n val a = (1 to n).map(_ => in.nextInt()).toArray\n val mm0 = a.indices.foldLeft((Int.MaxValue,Int.MinValue)){ case ((min,max), i) =>\n if(a(i) == -1){\n if(i>0 && a(i-1) != -1)\n (Math.min(min,a(i-1)),Math.max(max,a(i-1)))\n else\n (min,max)\n }else{\n (min,max)\n }\n\n }\n val mm1 = a.indices.foldLeft(mm0){ case ((min,max), i) =>\n if(a(i) == -1){\n if(i+1 {\n val (preal,qreal) = (if(p == -1) k else p,if(q == -1) k else q)\n Math.max(currentValue,Math.abs(preal-qreal))\n }}\n\n (acualM,k)\n }\n out.println(s\"$bestM $bestK\")\n\n\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "negative_code": [], "src_uid": "8ffd80167fc4396788b745b53068c9d3"} {"source_code": "object Main extends App {\n\n val letters = (97 to 122).map(_.toChar).map(_.toString)\n\n def counter[A](seq: Seq[A]): Map[A, Int] = {\n seq.foldLeft(Map[A, Int]())({\n (acc, n) => acc.get(n) match {\n case None => acc + (n -> 1)\n case Some(m) => acc + (n -> (m+1))\n }\n })\n }\n\n val s = readLine.map(_.toString).toList\n val t = readLine.map(_.toString).toList\n val s1 = counter(s)\n val t1 = counter(t)\n\n val init = (0, 0)\n val (pos, neg) = letters.foldLeft(init)({\n case ((pos, neg), letter) =>\n val sLower = s1.getOrElse(letter, 0)\n val sUpper = s1.getOrElse(letter.toUpperCase, 0)\n val tLower = t1.getOrElse(letter, 0)\n val tUpper = t1.getOrElse(letter.toUpperCase, 0)\n val usedLower = Math.min(sLower, tLower)\n val usedUpper = Math.min(sUpper, tUpper)\n val pos2 = usedLower + usedUpper\n val neg2 = Math.min((sLower-usedLower), (tUpper - usedUpper)) + Math.min((sUpper-usedUpper), (tLower - usedLower))\n (pos + pos2, neg + neg2)\n })\n\n println(\"%d %d\".format(pos, neg))\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util\nimport java.util._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val s = next.toCharArray\n val t = next.toCharArray\n val m = new scala.collection.mutable.HashMap[Char, Int]()\n for (i <- 0 until t.length) {\n val x = m.getOrElse(t(i), 0)\n m.put(t(i), x + 1)\n }\n var u = 0\n var o = 0\n val missed = new util.ArrayList[Char]()\n for (i <- 0 until s.length) {\n val symb = s(i)\n val x = m.getOrElse(symb, 0)\n if (x > 0) {\n u += 1\n m.put(symb, x - 1)\n } else {\n missed.add(symb)\n }\n }\n for (i <- 0 until missed.size()) {\n val symb = missed.get(i)\n if (Character.isUpperCase(symb)) {\n val lowerCase: Char = Character.toLowerCase(symb)\n val y = m.getOrElse(lowerCase, 0)\n if (y > 0) {\n o += 1\n m.put(lowerCase, y - 1)\n }\n } else {\n val upCase: Char = Character.toUpperCase(symb)\n val y = m.getOrElse(upCase, 0)\n if (y > 0) {\n o += 1\n m.put(upCase, y - 1)\n }\n }\n \n }\n out.println(u + \" \" + o)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val need = in.next().groupBy(t => t).map(t => t._1 -> t._2.length)\n val haveO = in.next().groupBy(t => t).map(t => t._1 -> t._2.length)\n val res = need.foldLeft((haveO, Map.empty[Char, Int], 0)) {\n case((have, newNeed, yes), (el, count)) =>\n val newYes = Math.min(have.getOrElse(el, 0), count)\n (have + (el -> (have.getOrElse(el, 0) - newYes)),\n newNeed + (el -> (count - newYes)),\n yes + newYes)\n }\n val res2 = res._2.foldLeft(0) {\n case(no, (el, count)) =>\n val diffSymbol = if (el.isLower) el.toUpper else el.toLower\n no + Math.min(res._1.getOrElse(diffSymbol, 0), count)\n }\n\n println(s\"${res._3} $res2\")\n}"}, {"source_code": "\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 01 Aug 2016\n */\nobject B518 extends App {\n\n def solve() = {\n val str: Array[Char] = scala.io.StdIn.readLine().toCharArray\n val txt: Array[Char] = scala.io.StdIn.readLine().toCharArray\n val strMap: Map[Char, Int] = str.groupBy(s => s).map(e => e._1 -> e._2.length)\n var txtMap: Map[Char, Int] = txt.groupBy(s => s).map(e => e._1 -> e._2.length)\n var postMap: mutable.Map[Char, Int] = mutable.Map.empty[Char, Int]\n var hooray = 0\n var opa = 0\n strMap.foreach(e => {\n if (txtMap.contains(e._1)) {\n if (e._2 <= txtMap.get(e._1).get) {\n hooray += e._2\n txtMap += (e._1 -> (txtMap.get(e._1).get - e._2))\n } else {\n hooray += txtMap.get(e._1).get\n postMap += (e._1 -> (-txtMap.get(e._1).get + e._2))\n txtMap -= e._1\n }\n } else {\n postMap += (e._1 -> e._2)\n }\n })\n postMap.foreach(e => {\n if (Character.isUpperCase(e._1)) {\n val chLower = Character.toLowerCase(e._1)\n if (txtMap.contains(chLower)) {\n if (e._2 <= txtMap.get(chLower).get) {\n opa += e._2\n txtMap += (chLower -> (txtMap.get(chLower).get - e._2))\n } else {\n opa += txtMap.get(chLower).get\n txtMap -= chLower\n }\n }\n } else {\n val chUpper = Character.toUpperCase(e._1)\n if (txtMap.contains(chUpper)) {\n if (e._2 <= txtMap.get(chUpper).get) {\n opa += e._2\n txtMap += (chUpper -> (txtMap.get(chUpper).get - e._2))\n } else {\n opa += txtMap.get(chUpper).get\n txtMap -= chUpper\n }\n }\n }\n })\n println(hooray + \" \" + opa)\n }\n\n solve()\n\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val need = in.next().groupBy(t => t).map(t => t._1 -> t._2.length)\n val have = in.next().groupBy(t => t).map(t => t._1 -> t._2.length)\n val res = need.foldLeft((have, 0, 0)) {\n case((have, yes, no), (el, count)) =>\n val newYes = Math.min(have.getOrElse(el, 0), count)\n val diffSymbol = if (el.isLower) el.toUpper else el.toLower\n if (newYes == count) {\n (have + (el -> (have.getOrElse(el, 0) - newYes)), yes + newYes, no)\n }\n else {\n val newNo = Math.min(count - newYes, have.getOrElse(diffSymbol, 0))\n (have + (el -> (have.getOrElse(el, 0) - newYes)) +\n (diffSymbol -> (have.getOrElse(diffSymbol, 0) - newNo))\n , yes + newYes, no + newNo)\n }\n }\n\n println(s\"${res._2} ${res._3}\")\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val need = in.next().groupBy(t => t).map(t => t._1 -> t._2.length)\n val haveO = in.next().groupBy(t => t).map(t => t._1 -> t._2.length)\n val res = need.foldLeft((haveO, 0, 0)) {\n case((have, yes, no), (el, count)) =>\n val newYes = Math.min(have.getOrElse(el, 0), count)\n val diffSymbol = if (el.isLower) el.toUpper else el.toLower\n val newNo = Math.min(count - newYes, have.getOrElse(diffSymbol, 0))\n (have + (el -> (have.getOrElse(el, 0) - newYes)) +\n (diffSymbol -> (have.getOrElse(diffSymbol, 0) - newNo))\n , yes + newYes, no + newNo)\n }\n\n println(s\"${res._2} ${res._3}\")\n}"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 01 Aug 2016\n */\nobject B518 extends App {\n\n def solve() = {\n val str: Array[Char] = scala.io.StdIn.readLine().toCharArray\n val txt: Array[Char] = scala.io.StdIn.readLine().toCharArray\n val strMap: Map[Char, Int] = str.groupBy(s => s).map(e => e._1 -> e._2.length)\n var txtMap: Map[Char, Int] = txt.groupBy(s => s).map(e => e._1 -> e._2.length)\n var hooray = 0\n var opa = 0\n strMap.foreach(e => {\n if (txtMap.contains(e._1)) {\n if (e._2 <= txtMap.get(e._1).get) {\n hooray += e._2\n txtMap += (e._1 -> (txtMap.get(e._1).get - e._2))\n } else {\n hooray += txtMap.get(e._1).get\n txtMap -= e._1\n }\n }\n if (Character.isUpperCase(e._1)) {\n if (txtMap.contains(Character.toLowerCase(e._1))) {\n if (e._2 <= txtMap.get(Character.toLowerCase(e._1)).get) {\n opa += e._2\n txtMap += (Character.toLowerCase(e._1) -> (txtMap.get(Character.toLowerCase(e._1)).get - e._2))\n } else {\n opa += txtMap.get(Character.toLowerCase(e._1)).get\n txtMap -= Character.toLowerCase(e._1)\n }\n }\n } else {\n if (txtMap.contains(Character.toUpperCase(e._1))) {\n if (e._2 <= txtMap.get(Character.toUpperCase(e._1)).get) {\n opa += e._2\n txtMap += (Character.toUpperCase(e._1) -> (txtMap.get(Character.toUpperCase(e._1)).get - e._2))\n } else {\n opa += txtMap.get(Character.toUpperCase(e._1)).get\n txtMap -= Character.toUpperCase(e._1)\n }\n }\n }\n })\n println(hooray + \" \" + opa)\n }\n\n solve()\n\n}\n"}, {"source_code": "\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 01 Aug 2016\n */\nobject B518 extends App {\n\n def solve() = {\n val str: Array[Char] = scala.io.StdIn.readLine().toCharArray\n val txt: Array[Char] = scala.io.StdIn.readLine().toCharArray\n val strMap: Map[Char, Int] = str.groupBy(s => s).map(e => e._1 -> e._2.length)\n var txtMap: Map[Char, Int] = txt.groupBy(s => s).map(e => e._1 -> e._2.length)\n var postMap: mutable.Map[Char, Int] = mutable.Map.empty[Char, Int]\n var hooray = 0\n var opa = 0\n strMap.foreach(e => {\n if (txtMap.contains(e._1)) {\n if (e._2 <= txtMap.get(e._1).get) {\n hooray += e._2\n txtMap += (e._1 -> (txtMap.get(e._1).get - e._2))\n } else {\n hooray += txtMap.get(e._1).get\n txtMap -= e._1\n postMap += (e._1 -> e._2)\n }\n } else {\n postMap += (e._1 -> e._2)\n }\n })\n postMap.foreach(e => {\n if (Character.isUpperCase(e._1)) {\n if (txtMap.contains(Character.toLowerCase(e._1))) {\n if (e._2 <= txtMap.get(Character.toLowerCase(e._1)).get) {\n opa += e._2\n txtMap += (Character.toLowerCase(e._1) -> (txtMap.get(Character.toLowerCase(e._1)).get - e._2))\n } else {\n opa += txtMap.get(Character.toLowerCase(e._1)).get\n txtMap -= Character.toLowerCase(e._1)\n }\n }\n } else {\n if (txtMap.contains(Character.toUpperCase(e._1))) {\n if (e._2 <= txtMap.get(Character.toUpperCase(e._1)).get) {\n opa += e._2\n txtMap += (Character.toUpperCase(e._1) -> (txtMap.get(Character.toUpperCase(e._1)).get - e._2))\n } else {\n opa += txtMap.get(Character.toUpperCase(e._1)).get\n txtMap -= Character.toUpperCase(e._1)\n }\n }\n }\n })\n println(hooray + \" \" + opa)\n }\n\n solve()\n\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 01 Aug 2016\n */\nobject B518 extends App {\n\n def solve() = {\n val str: Array[Char] = scala.io.StdIn.readLine().toCharArray\n val txt: Array[Char] = scala.io.StdIn.readLine().toCharArray\n val strMap: Map[Char, Int] = str.groupBy(s => s).map(e => e._1 -> e._2.length)\n var txtMap: Map[Char, Int] = txt.groupBy(s => s).map(e => e._1 -> e._2.length)\n var hooray = 0\n var opa = 0\n strMap.foreach(e => {\n if (txtMap.contains(e._1)) {\n if (e._2 <= txtMap.get(e._1).get) {\n hooray += e._2\n txtMap += (e._1 -> (txtMap.get(e._1).get - e._2))\n } else {\n hooray += txtMap.get(e._1).get\n txtMap -= e._1\n if (Character.isUpperCase(e._1)) {\n if (txtMap.contains(Character.toLowerCase(e._1))) {\n if (e._2 <= txtMap.get(Character.toLowerCase(e._1)).get) {\n opa += e._2\n txtMap += (Character.toLowerCase(e._1) -> (txtMap.get(Character.toLowerCase(e._1)).get - e._2))\n } else {\n opa += txtMap.get(Character.toLowerCase(e._1)).get\n txtMap -= Character.toLowerCase(e._1)\n }\n }\n } else {\n if (txtMap.contains(Character.toUpperCase(e._1))) {\n if (e._2 <= txtMap.get(Character.toUpperCase(e._1)).get) {\n opa += e._2\n txtMap += (Character.toUpperCase(e._1) -> (txtMap.get(Character.toUpperCase(e._1)).get - e._2))\n } else {\n opa += txtMap.get(Character.toUpperCase(e._1)).get\n txtMap -= Character.toUpperCase(e._1)\n }\n }\n }\n }\n }\n if (Character.isUpperCase(e._1)) {\n if (txtMap.contains(Character.toLowerCase(e._1))) {\n if (e._2 <= txtMap.get(Character.toLowerCase(e._1)).get) {\n opa += e._2\n txtMap += (Character.toLowerCase(e._1) -> (txtMap.get(Character.toLowerCase(e._1)).get - e._2))\n } else {\n opa += txtMap.get(Character.toLowerCase(e._1)).get\n txtMap -= Character.toLowerCase(e._1)\n }\n }\n } else {\n if (txtMap.contains(Character.toUpperCase(e._1))) {\n if (e._2 <= txtMap.get(Character.toUpperCase(e._1)).get) {\n opa += e._2\n txtMap += (Character.toUpperCase(e._1) -> (txtMap.get(Character.toUpperCase(e._1)).get - e._2))\n } else {\n opa += txtMap.get(Character.toUpperCase(e._1)).get\n txtMap -= Character.toUpperCase(e._1)\n }\n }\n }\n })\n println(hooray + \" \" + opa)\n }\n\n solve()\n\n}\n"}, {"source_code": "import java.io._\nimport java.util\nimport java.util._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val s = next.toCharArray\n val t = next.toCharArray\n val m = new scala.collection.mutable.HashMap[Char, Int]()\n for (i <- 0 until t.length) {\n val x = m.getOrElse(t(i), 0)\n m.put(t(i), x + 1)\n }\n var u = 0\n var o = 0\n for (i <- 0 until s.length) {\n val symb = s(i)\n val x = m.getOrElse(symb, 0)\n if (x > 0) {\n u += 1\n m.put(symb, x - 1)\n } else {\n if (Character.isUpperCase(symb)) {\n val lowerCase: Char = Character.toLowerCase(symb)\n val y = m.getOrElse(lowerCase, 0)\n if (y > 0) {\n o += 1\n m.put(lowerCase, y - 1)\n }\n } else {\n val upCase: Char = Character.toUpperCase(symb)\n val y = m.getOrElse(upCase, 0)\n if (y > 0) {\n o += 1\n m.put(upCase, y - 1)\n }\n }\n }\n }\n out.println(u + \" \" + o)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}, {"source_code": "import java.io._\nimport java.util\nimport java.util._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val s = next\n val t = next.toCharArray\n val m = new scala.collection.mutable.HashMap[Char, Int]()\n for (i <- 0 until t.length) {\n val x = m.getOrElse(t(i), 0)\n m.put(t(i), x + 1)\n }\n var u = 0\n var o = 0\n for (i <- 0 until s.length) {\n val x = m.getOrElse(s(i), 0)\n if (x > 0) {\n u += 1\n m.put(s(i), x - 1)\n } else {\n if (Character.isUpperCase(s(i))) {\n val lowerCase: Char = Character.toLowerCase(s(i))\n val y = m.getOrElse(lowerCase, 0)\n if (y > 0) {\n o += 1\n m.put(lowerCase, y - 1)\n }\n }\n else {\n val upCase: Char = Character.toUpperCase(s(i))\n val y = m.getOrElse(upCase, 0)\n if (y > 0) {\n o += 1\n m.put(upCase, y - 1)\n }\n }\n }\n }\n out.println(u + \" \" + o)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "src_uid": "96e2ba997eff50ffb805b6be62c56222"} {"source_code": "object Main extends App {\n var n = readInt\n if (n % 2 == 1) {\n print(\"7\")\n n = n - 3\n }\n while (n >= 2) {\n print(\"1\")\n n = n - 2\n }\n println(\"\")\n}", "positive_code": [{"source_code": "object HelloWorld {\n def main(args: Array[String])\n {\n var n = readInt;\n var i = 0;\n if(n%2==0) print(1);\n else print(7);\n for(i <- 2 to n/2) \n {\n print(1);\n }\n }\n}"}, {"source_code": "object Main extends App {\n val n = readInt\n if (n % 2 == 1)\n {\n print(7);\n for (i <- 1 to (n - 3) / 2)\n print(1);\n }\n else\n {\n for (i <- 1 to n / 2)\n print(1);\n }\n}"}, {"source_code": "object Main extends App {\n var n = readInt\n if (n % 2 == 1) {\n n = n - 3;\n print(7)\n }\n while (n >= 2) {\n n = n - 2;\n print(1)\n }\n}"}, {"source_code": "object X extends App {\n val n = scala.io.StdIn.readLine.toInt\n if (n < 2)\n println(0)\n else {\n var res = 1 \n if (n % 2 == 1) res = 7\n print(res)\n for (i <- 2 to n/2) {\n print(1);\n } \n println()\n }\n}"}, {"source_code": "\nobject TEST extends App{\n var n = readInt\n if(n%2==1)\n {\n print(7)\n n-=3\n }\n for(i <- 1 to n/2) print(1)\n}\n"}, {"source_code": "object Main extends App {\n var n = readInt\n if (n % 2 == 1) \n {\n print(7)\n n = n - 3\n }\n for (i <- 1 to n / 2) print(1)\n}"}, {"source_code": "object Main extends App {\n var n = readInt\n if (n % 2 == 1) {\n print(\"7\")\n n = n - 3\n }\n \n for (i <- 1 to n / 2) {\n print(\"1\")\n }\n}"}, {"source_code": "object Main extends App {\n var n = readInt\n if (n % 2 == 1) {\n print(7)\n n = n - 3\n }\n n = n / 2\n for (i <- 1 to n) {\n print(1)\n //println(if (k <= 10) s else s(0) + (k - 2).toString + s(k-1))\n }\n}"}, {"source_code": "object c {\n def main(args: Array[String]) {\n val n = readInt()\n var seven = 0\n var one = 0\n if (n % 2 == 1) { \n one = n / 2 - 1\n seven = 1\n } else {\n one = n / 2\n }\n \n for (i <- 1 to seven) {\n print(7)\n }\n for (i <- 1 to one) {\n print(1)\n }\n }\n}"}, {"source_code": "object Main extends App {\n\tvar n = readInt\n\tif (n % 2 == 1) {\n\t\tprint(7)\n\t\tn = n - 3\n\t}\n\twhile( n > 0 ) {\n\t\tprint(1)\n\t\tn = n - 2\n\t}\n}"}, {"source_code": "object Main extends App {\n\t// your code goes here\n\tvar n = readInt\n\twhile (n > 0) {\n\t\tif (n % 2 == 1) {\n\t\t\tn -= 3;\n\t\t\tprint(7);\n\t\t}\n\t\telse {\n\t\t\tn -= 2;\n\t\t\tprint(1);\n\t\t}\n\t}\n}"}, {"source_code": "object Main extends App {\n val n = readInt\n var a = 0\n if (n % 2 == 0) {\n for ( a <- 1 to n / 2) {\n print(1);\n }\n } else {\n print(7);\n for ( a <- 1 to n / 2 - 1) {\n print(1);\n }\n }\n}"}, {"source_code": "import java.util.Scanner\nobject Main extends App {\n\tval in = new Scanner(System.in)\n\tvar n = in.nextInt()\n\tif (n % 2 == 1) {\n\t\tprint(7)\n\t\tn = n - 3\n\t}\n\tn = n / 2\n\tvar a = 0\n\tfor(a <- 1 to n)\n\t print(1)\n}"}, {"source_code": "object Main extends App {\n val n = readInt\n\tval k = n / 2 - 1\n\tval t = n % 2\n\tprint(if (t == 1) '7' else '1')\n\tfor (i <- 1 to k) {\n\t\tprint('1')\n\t}\n}"}, {"source_code": "object Main extends App {\n val n = readInt\n print(if (n % 2 == 0) 1 else 7)\n for (i <- 1 to (n - 2) / 2) print(1)\n}"}, {"source_code": "object Main extends App {\n var ans :String = \"\"\n val n = readInt\n\n if (n % 2 == 0) {\n for (i <- 1 to n / 2) {\n print(1)\n }\n }\n else {\n print(7)\n for (i <- 1 to (n - 3) / 2) {\n print(1)\n }\n }\n \n println()\n\n}"}, {"source_code": "object Main extends App {\n val n = readInt\n if(n%2==0){\n for (i <- 1 to n/2) {\n print(1)\n }\n }\n else{\n print(7)\n for (i <- 1 to (n-3)/2) {\n print(1)\n }\n \n }\n}"}, {"source_code": "object Main extends App {\n var n = readInt\n if(n%2==1){\n print(7)\n n=n-3\n }\n n/=2\n for (i <- 1 to n) {\n print(1)\n }\n}"}, {"source_code": "object Main extends App {\n var n = readInt;\n var num = 0;\n if(n % 2 == 1 && n > 1){\n print(7);\n n -= 3;\n }\n while(n > 1){\n n -= 2;\n print(1);\n }\n}\n"}, {"source_code": "object Main extends App {\n val cost = Array( 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 )\n var N = readInt // keyword val seems to work like const, in contrast to var\n if( N % 2 == 1 ) {\n print( 7 )\n N -= 3\n }\n while( N > 0 ) {\n print( 1 )\n N -= 2\n }\n println()\n}"}], "negative_code": [{"source_code": "object Main extends App {\n var n = readInt\n if(n%2==1){\n println(7)\n n=n-3\n }\n n/=2\n for (i <- 1 to n) {\n println(1)\n }\n}"}, {"source_code": "object Main extends App {\n val cost = Array( 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 )\n var N = readInt // keyword val seems to work like const, in contrast to var\n while( N >= 2 ) {\n // for に break のキーワードはないらしい...\n var i = 9\n while( i >= 0 ) {\n if( N >= cost( i ) ) { // [] ではなく () なんですね...\n print( i )\n N -= cost( i )\n i = -1 // break とする\n }\n i -= 1\n }\n }\n println()\n}"}, {"source_code": "object HelloWorld {\n def main(args: Array[String])\n {\n var n = readInt;\n var i = 0;\n if(n%2==0) print(1);\n else print(7);\n for(i <- 1 to n/2) \n {\n print(1);\n }\n }\n}"}, {"source_code": "object X extends App {\n val n = scala.io.StdIn.readLine.toInt\n if (n < 2)\n println(0)\n else {\n var res = 1 \n if (n % 2 == 1) res = 7\n for (i <- 2 to n/2) {\n res = res * 10 + 1;\n } \n println(res)\n }\n} \n"}, {"source_code": "object c {\n def main(args: Array[String]) {\n val n = readInt()\n var seven = 0\n var one = 0\n if (n % 3 == 1) {\n seven = n / 3 - 1\n one = 2\n } else if (n % 3 == 2) {\n seven = n / 3\n one = 1\n } else {\n seven = n / 3\n }\n \n for (i <- 1 to seven) {\n print(7)\n }\n for (i <- 1 to one) {\n print(1)\n }\n }\n}"}, {"source_code": "object Main extends App {\n\tvar n = readInt\n\twhile( n > 3 ) {\n\t\tprint(1)\n\t\tn = n - 2\n\t}\n\tif (n == 3)\n\t\tprint(7)\n\telse\n\t\tprint(1)\n}"}, {"source_code": "import java.util.Scanner\nobject Main extends App {\n\tval in = new Scanner(System.in)\n\tvar n = in.nextInt()\n\tif (n % 2 == 1) {\n\t\tprint(7)\n\t\tn = n - 1\n\t}\n\tn = n / 2\n\tvar a = 0\n\tfor(a <- 1 to n)\n\t print(1)\n}"}, {"source_code": "import java.util.Scanner\nobject Main extends App {\n\tval in = new Scanner(System.in)\n\tval n = in.nextInt()\n\tif (n == 2) println(\"1\")\n\tif (n == 3) println(\"7\")\n\tif (n == 4) println(\"11\")\n\tif (n == 5) println(\"71\")\n\tif (n == 6) println(\"111\")\n\tif (n == 7) println(\"711\")\n\tif (n == 8) println(\"1111\")\n\tif (n == 9) println(\"7111\")\n\tif (n == 10) println(\"11111\")\n\tif (n == 11) println(\"71111\")\n\tif (n == 12) println(\"111111\")\n\tif (n == 13) println(\"711111\")\n\tif (n == 14) println(\"1111111\")\n if (n == 15) println(\"7111111\")\n if (n == 16) println(\"11111111\")\n if (n == 17) println(\"71111111\")\n if (n == 18) println(\"111111111\")\n if (n == 19) println(\"711111111\")\n if (n == 20) println(\"1111111111\")\n if (n == 21) println(\"7111111111\")\n if (n == 22) println(\"7711111111\")\n if (n == 23) println(\"7771111111\")\n if (n == 24) println(\"9111111111\")\n if (n == 25) println(\"9711111111\")\n if (n == 26) println(\"9771111111\")\n if (n == 27) println(\"9777111111\")\n if (n == 28) println(\"9911111111\")\n if (n == 29) println(\"9971111111\")\n if (n == 30) println(\"9977111111\")\n if (n == 31) println(\"9977711111\")\n if (n == 32) println(\"9991111111\")\n if (n == 33) println(\"9997111111\")\n if (n == 34) println(\"9997711111\")\n if (n == 35) println(\"9997771111\")\n if (n == 36) println(\"9999111111\")\n if (n == 37) println(\"9999711111\")\n if (n == 38) println(\"9999771111\")\n if (n == 39) println(\"9999777111\")\n if (n == 40) println(\"9999911111\")\n if (n == 41) println(\"9999971111\")\n if (n == 42) println(\"9999977111\")\n if (n == 43) println(\"9999977711\")\n if (n == 44) println(\"9999991111\")\n if (n == 45) println(\"9999997111\")\n if (n == 46) println(\"9999997711\")\n if (n == 47) println(\"9999997771\")\n if (n == 48) println(\"9999999111\")\n if (n == 49) println(\"9999999711\")\n if (n == 50) println(\"9999999771\")\n if (n == 51) println(\"9999999777\")\n if (n == 52) println(\"9999999911\")\n if (n == 53) println(\"9999999971\")\n if (n == 54) println(\"9999999977\")\n if (n == 55) println(\"9999999977\")\n if (n == 56) println(\"9999999997\")\n if (n == 57) println(\"9999999997\")\n if (n == 58) println(\"9999999997\")\n if (n == 59) println(\"9999999997\")\n if (n >= 60) println(\"9999999999\")\n}"}], "src_uid": "4ebea3f56ffd43efc9e1496a0ef7fa2d"} {"source_code": "object Solution {\n def main(args: Array[String]) {\n val sc = new java.util.Scanner(System.in);\n val n: Int = sc.nextInt();\n var i = 0;\n var t = new Array[Boolean](1440);\n \n for (i <- 0 to 1439) t(i) = false;\n \n for (i <- 0 to n-1) {\n var s = sc.next();\n var arr = s.split(\":\");\n \n var x = arr(0).toInt * 60 + arr(1).toInt;\n t(x) = true;\n }\n \n var res = 0;\n var cnt = 0;\n for (i <- 0 to 3000) {\n if (t(i % 1440) == false) cnt += 1; else cnt = 0;\n if (cnt > res) res = cnt;\n }\n \n var h = res / 60;\n var m = res % 60;\n \n println(f\"$h%02d:$m%02d\");\n }\n}\n", "positive_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val sc = new java.util.Scanner(System.in);\n val n: Int = sc.nextInt();\n var i = 0;\n var t = new Array[Boolean](1440);\n \n for (i <- 0 to 1439) t(i) = false;\n \n for (i <- 0 to n-1) {\n var s = sc.next();\n var arr = s.split(\":\");\n \n var x = arr(0).toInt * 60 + arr(1).toInt;\n t(x) = true;\n }\n \n var res = 0;\n var cnt = 0;\n for (i <- 0 to 3000) {\n if (t(i % 1440) == false) cnt += 1; else cnt = 0;\n if (cnt > res) res = cnt;\n }\n \n var h = res / 60;\n var m = res % 60;\n \n println(f\"$h%02d:$m%02d\");\n }\n}\n"}], "negative_code": [], "src_uid": "c3b0b7194ce018bea9c0b9139e537a09"} {"source_code": "\nobject Interview extends App {\n //println((1 to 1000).mkString(\" \"))\n val n = scala.io.StdIn.readLine().toInt\n val array1 = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val array2 = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n def fSum(x1: Array[Int], x2: Array[Int], l: Int, r: Int): Int = {\n var sum1 = x1(l)\n var sum2 = x2(l)\n var i = l + 1\n while (i <= r) {\n sum1 = sum1 | x1(i)\n sum2 = sum2 | x2(i)\n i += 1\n }\n sum1 + sum2\n }\n\n var max = fSum(array1, array2, 0, 0)\n var l = 0\n while (l < n - 1) {\n var r = l\n while (r < n) {\n val candidate = fSum(array1, array2, l, r)\n if (candidate > max) max = candidate\n r += 1\n }\n l += 1\n }\n\n println(max)\n}\n\n\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.Scanner\n\nimport scala.collection.mutable.ListBuffer\n\nobject Solution extends ConsoleIO {\n def main(args: Array[String]) = {\n withIO {(reader, writer) =>\n val n = reader.nextInt()\n val a = ListBuffer.empty[Int]\n (1 to n).foreach { _ =>\n a.append(reader.nextInt())\n }\n val b = ListBuffer.empty[Int]\n (1 to n).foreach { _ =>\n b.append(reader.nextInt())\n }\n val result = a.reduce( _ | _) + b.reduce(_ | _)\n writer.print(result)\n }\n }\n}\n\ntrait ConsoleIO {\n def withIO(task: (Scanner, PrintWriter) => Unit) = {\n val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))\n val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n task(reader, writer)\n reader.close()\n writer.close()\n }\n}\n\ntrait FileIO {\n def withIO(task: (Scanner, PrintWriter) => Unit) = {\n val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream(\"input.txt\"))))\n val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(\"output.txt\"))))\n task(reader, writer)\n reader.close()\n writer.close()\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt).zip(in.next().split(' ').map(_.toInt))\n println((0 until n).foldLeft(0) {\n case (acc, i) =>\n val drop1 = data.drop(i)\n val head = drop1.head\n drop1.tail.foldLeft(head, Math.max(acc, head._1 + head._2)) {\n case (((fSoFar, sSoFar), max), (first, second)) =>\n val nfSoFar = fSoFar | first\n val nsSoFar = sSoFar | second\n ((nfSoFar, nsSoFar), Math.max(max, nfSoFar + nsSoFar))\n }._2\n })\n}"}, {"source_code": "object A631 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(num) = readInts(1)\n val a = readInts(num).foldLeft(0L){case (sum, n) => sum|n}\n val b = readInts(num).foldLeft(0L){case (sum, n) => sum|n}\n println(a+b)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _631A extends CodeForcesApp {\n override type Result = Long\n\n override def solve(read: InputReader) = {\n val n = read[Int]\n val a, b = read[IndexedSeq, Long](n).foldLeft(0L){case (i, j) => i | j}\n a + b\n }\n\n override def format(result: Result) = result.toString\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}, {"source_code": "/**\n * Created by aborisenko on 21.02.16.\n */\n\nimport io.StdIn._\n\nobject Main extends App {\n def a631 (){\n\n val n = readInt()\n val a: Array[Long] = readLine().split(\" \").map(_.toLong)\n val b: Array[Long] = readLine().split(\" \").map(_.toLong)\n\n var result1: Long = 0\n for( i <- 0 to n-1)\n result1 |= a(i)\n var result2: Long = 0\n\n for( i <- 0 to n-1)\n result2 |= b(i)\n\n println(result1 + result2)\n }\n\n a631()\n}\n"}, {"source_code": "import scala.io.StdIn\n\n/**\n * http://codeforces.com/problemset/problem/631/A\n * */\nobject AInterview {\n\n private def orValues(values: Seq[Long]): Long = {\n values.foldLeft(0L)(_ | _)\n }\n\n def main(args: Array[String]): Unit = {\n StdIn.readLine()\n val fstValues = StdIn.readLine().split(\" \").map(_.toLong)\n val scdValues = StdIn.readLine().split(\" \").map(_.toLong)\n val result = orValues(fstValues) + orValues(scdValues)\n println(result)\n }\n}\n"}], "negative_code": [{"source_code": "\nobject Interview extends App {\n //println((1 to 1000).mkString(\" \"))\n val n = scala.io.StdIn.readLine().toInt\n val array1 = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val array2 = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n def fSum(x1: Array[Int], x2: Array[Int], l: Int, r: Int): Int = {\n var sum1 = x1(l)\n var sum2 = x2(l)\n var i = l + 1\n while (i < r) {\n sum1 = sum1 | x1(i)\n sum2 = sum2 | x2(i)\n i = i + 1\n }\n sum1 + sum2\n }\n\n var max = fSum(array1, array2, 0, 0)\n var l = 0\n while (l < n - 1) {\n var r = l\n while (r < n) {\n val candidate = fSum(array1, array2, l, r)\n if (candidate > max) max = candidate\n r = r + 1\n }\n l = l + 1\n }\n\n println(max)\n}\n\n\n"}, {"source_code": "\nobject Interview extends App {\n //println((1 to 1000).mkString(\" \"))\n val n = scala.io.StdIn.readLine().toInt\n val array1 = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val array2 = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n def fSum(x1: Array[Int], x2: Array[Int], l: Int, r: Int): Int = {\n var sum1 = x1(l)\n var sum2 = x2(l)\n var i = l + 1\n while(i < r) {\n sum1 = sum1 | x1(i)\n sum2 = sum2 | x2(i)\n i = i + 1\n }\n /*for {\n i <- (l + 1) until r\n } {\n sum1 = sum1 | x1(i)\n sum2 = sum2 | x2(i)\n }*/\n sum1 + sum2\n }\n\n var max = 0L\n var l = 0\n while(l < n -1) {\n var r = l + 1\n while(r < n) {\n val candidate = fSum(array1, array2, l, r)\n if (candidate > max) max = candidate\n r = r + 1\n }\n l = l + 1\n }\n /*for {\n l <- 0 until n - 1\n r <- l + 1 until n\n } {\n val candidate = fSum(array1, array2, l, r)\n if (candidate > max) max = candidate\n }*/\n\n println(max)\n}\n\n\n"}], "src_uid": "475239ff4ae3675354d2229aba081a58"} {"source_code": "import scala.collection.mutable.HashMap\n\nobject B extends App {\n val n = readInt\n val str = readLine.split(\" \").map(_.toInt).zipWithIndex\n val mp = new HashMap[Int, (Int, Int, Int)]()\n for((i, j) <- str) {\n val k = mp.getOrElse(i, (0, 0, 0))\n if(k._1 == 0) \n mp(i) = (1, j, j)\n else\n mp(i) = (k._1 + 1, k._2, j)\n }\n\n val res = mp.toList.sortWith((i, j) => i._2._1 > j._2._1 || i._2._1 == j._2._1 && (i._2._3 - i._2._2) < (j._2._3 - j._2._2))(0)\n print(res._2._2 + 1 + \" \" + (res._2._3 + 1))\n}\n", "positive_code": [{"source_code": "//package c558.b\n\nobject Solution extends App {\n case class C3(counter: Int, left: Int, right: Int)\n case object C3 { def empty(i: Int) = C3(1, i, i) }\n def solve(n: Int, array: Seq[Int]) = {\n import scala.collection.mutable\n val indexedArray = array.zip(1 to n)\n val beautyMap = mutable.Map.empty[Int, C3]\n indexedArray.foreach(xi ⇒ {\n val (x, i) = xi._1 → xi._2\n val elem = beautyMap.getOrElse(x, C3.empty(i))\n beautyMap.put(x, elem.copy(counter = elem.counter + 1, right = i))\n })\n val maxElem = beautyMap.maxBy(kv ⇒ kv._2.counter)\n val best = beautyMap\n .filter(_._2.counter == maxElem._2.counter)\n .minBy(kv ⇒ kv._2.right - kv._2.left)._2\n s\"${best.left} ${best.right}\"\n }\n import scala.io.StdIn\n val n = StdIn.readInt()\n val array = StdIn.readLine().split(\" \").map(_.toInt)\n println(solve(n, array))\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.collection.mutable.PriorityQueue\nimport scala.annotation.tailrec\n\n\nobject Main {\n case class LR(left : Int, right : Int, cnt : Int)\n object EnRich {\n implicit class AString(val self : String) extends AnyVal {\n def splitToIntArray = self.split(\" \").map(_.toInt)\n }\n }\n import EnRich._\n\n def main(args : Array[String]) : Unit = {\n val n = readLine.toInt\n val a = readLine.splitToIntArray\n val h = scala.collection.mutable.HashMap[Int,LR]()\n (a.zipWithIndex).foreach({case (a,i) => h.get(a) match {\n case None => h(a) = LR(i,i,1)\n case Some(LR(l,r,k)) => h(a) = LR(l,i,k+1)\n }})\n val m = h.toList.map({case (_,LR(_,_,k)) => k}).max\n val f = h.toList.filter({case (_,LR(_,_,k)) => k == m}).\n sortBy(({case (_,LR(l,r,_)) => r-l}))\n val l = f.head._2.left+1\n val r = f.head._2.right+1\n println(s\"$l $r\")\n }\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util.control.Breaks._, math.Ordering.Implicits._\nobject _558B extends CodeForcesApp[(Int, Int)]({scanner => import scanner._\n val array = List.fill(nextInt)(nextInt)\n val start = mutable.Map.empty[Int, Int] withDefaultValue Integer.MAX_VALUE\n val end = mutable.Map.empty[Int, Int] withDefaultValue Integer.MIN_VALUE\n val counter = mutable.Map.empty[Int, Int] withDefaultValue 0\n for {(n, p) <- array.zipWithIndex} {\n start(n) = start(n) min p\n end(n) = end(n) max p\n counter(n) += 1\n }\n val (_, maxRepeat) = counter.maxBy(_._2)\n\n val answers = for {\n (n, count) <- counter if count == maxRepeat\n } yield start(n) -> end(n)\n\n answers minBy {case (x, y) => (y - x, x)}\n}) {\n override def format(result: (Int, Int)) = result match {\n case (x, y) => s\"${x+1} ${y+1}\"\n }\n}\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[B](x: Boolean)(f: => B): Option[B] = if (x) Some(f) else None\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject AmrAndTheLargeArray{\n case class Triplet( left : Int, right : Int, count : Int)\n def main(args : Array[String]) : Unit = {\n readLine()\n val a = readLine().split(\"\\\\s+\").map( _.toInt )\n val map = scala.collection.mutable.HashMap[Int, Triplet]()\n (a.zipWithIndex).foreach({\n case (a,i) => map.get(a) match {\n case None => map(a) = Triplet(i,i,1)\n case Some(Triplet(l,r,k)) => map(a) = Triplet(l,i,k+1) \n }\n })\n \n val ans = map.valuesIterator.reduceLeft( (thiz, that) => {\n if(thiz.count != that.count)\n if(thiz.count >= that.count) thiz else that\n else if ((thiz.right - thiz.left) <= (that.right - that.left)) thiz else that\n })\n \n val l = ans.left + 1 \n val r = ans.right + 1\n println(l + \" \" + r) \n }\n}"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject AmrAndTheLargeArray{\n case class Triplet( left : Int, right : Int, count : Int)\n def main(args : Array[String]) : Unit = {\n readLine()\n val a = readLine().split(\"\\\\s+\").map( _.toInt )\n val map = scala.collection.mutable.HashMap[Int, Triplet]()\n (a.zipWithIndex).foreach({\n case (a,i) => map.get(a) match {\n case None => map(a) = Triplet(i,i,1)\n case Some(Triplet(l,r,k)) => map(a) = Triplet(l,i,k+1) \n }\n })\n val ans = map.reduceLeft( (thiz, that) => {\n if(thiz._2.count != that._2.count)\n if(thiz._2.count >= that._2.count) thiz else that\n else if ((thiz._2.right - thiz._2.left) <= (that._2.right - that._2.left)) thiz else that\n })\n\n val l = ans._2.left + 1 \n val r = ans._2.right + 1\n println(l + \" \" + r) \n }\n}"}], "negative_code": [{"source_code": "//package c558.b\n\nobject Solution extends App {\n case class C3(counter: Int, left: Int, right: Int)\n case object C3 { def empty(i: Int) = C3(1, i, i) }\n def solve(n: Int, array: Seq[Int]) = {\n import scala.collection.mutable\n val indexedArray = array.zip(1 to n)\n val beautyMap = mutable.Map.empty[Int, C3]\n indexedArray.foreach(xi ⇒ {\n val (x, i) = xi._1 → xi._2\n val elem = beautyMap.getOrElse(x, C3.empty(i))\n beautyMap.put(x, elem.copy(counter = elem.counter + 1, right = i))\n })\n val maxElem = beautyMap.maxBy(kv ⇒ kv._2.counter)\n val best = beautyMap.filter(_._2 == maxElem._2).maxBy(kv ⇒ kv._2.right - kv._2.left)._2\n s\"${best.left} ${best.right}\"\n }\n import scala.io.StdIn\n val n = StdIn.readInt()\n val array = StdIn.readLine().split(\" \").map(_.toInt)\n println(solve(n, array))\n}\n"}, {"source_code": "//package c558.b\n\nobject Solution extends App {\n def solve(n: Int, array: Seq[Int]) = {\n import scala.collection.mutable\n val indexedArray = array.zip(1 to n)\n val beautyMap = mutable.Map.empty[Int, Int]\n indexedArray.foreach(xi ⇒ {\n val x = xi._1\n val elem = beautyMap.getOrElse(x, 0)\n beautyMap.put(x, elem + 1)\n })\n val maxElem = beautyMap.maxBy(kv ⇒ kv._2)\n val left = array.indexOf(maxElem._1) + 1\n val right = array.lastIndexOf(maxElem._1) + 1\n s\"$left $right\"\n }\n import scala.io.StdIn\n val n = StdIn.readInt()\n val array = StdIn.readLine().split(\" \").map(_.toInt)\n println(solve(n, array))\n}\n"}, {"source_code": "//package c558.b\n\nobject Solution extends App {\n import scala.io.StdIn\n import scala.collection.mutable\n val n = StdIn.readInt()\n val array = StdIn.readLine().split(\" \").map(_.toInt)\n val indexedArray = array.zip(0 until n)\n case class C3(counter: Int, left: Int, right: Int)\n case object C3 { def empty = C3(0, 0, 0) }\n val beautyMap = mutable.Map.empty[Int, C3]\n indexedArray.foreach(xi ⇒ {\n val (x, i) = xi._1 → xi._2\n val elem = beautyMap.getOrElse(x, C3.empty.copy(left = i))\n beautyMap.put(x, elem.copy(counter = elem.counter + 1, right = i))\n })\n val maxElem = beautyMap.maxBy(kv ⇒ kv._2.counter)\n println(s\"${maxElem._2.left + 1} ${maxElem._2.right + 1}\")\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.collection.mutable.PriorityQueue\nimport scala.annotation.tailrec\n\n\nobject Main {\n case class LR(left : Int, right : Int, cnt : Int)\n object EnRich {\n implicit class AString(val self : String) extends AnyVal {\n def splitToIntArray = self.split(\" \").map(_.toInt)\n }\n }\n import EnRich._\n\n def main(args : Array[String]) : Unit = {\n val n = readLine.toInt\n val a = readLine.splitToIntArray\n val h = scala.collection.mutable.HashMap[Int,LR]()\n (a.zipWithIndex).foreach({case (a,i) => h.get(a) match {\n case None => h(a) = LR(i,i,1)\n case Some(LR(l,r,k)) => h(a) = LR(l,i,k+1)\n }})\n val m = h.toList.map({case (_,LR(_,_,k)) => k}).max\n val f = h.toList.filter({case (_,LR(_,_,k)) => k == m})\n val l = f.head._2.left+1\n val r = f.head._2.right+1\n println(s\"$l $r\")\n }\n}"}, {"source_code": "import scala.collection.mutable.HashMap\n\nobject B extends App {\n val n = readInt\n val str = readLine.split(\" \").map(_.toInt).zipWithIndex\n val mp = new HashMap[Int, (Int, Int, Int)]()\n for((i, j) <- str) {\n val k = mp.getOrElse(i, (0, 0, 0))\n if(k._1 == 0) \n mp(i) = (1, j, j)\n else\n mp(i) = (k._1 + 1, k._2, j)\n }\n\n val res = mp.toList.sortWith((i, j) => i._2._1 > j._2._1 || i._2._1 == j._2._1 && (i._2._3 - i._2._1) < (j._2._3 - j._2._1))(0)\n print(res._2._2 + 1 + \" \" + (res._2._3 + 1))\n}\n"}], "src_uid": "ecd9bbc05b97f3cd43017dd0eddd014d"} {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject B_311 { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n val w = line1.long\n var cups = new Array[Long](2*n)\n val capasLine = readLine()\n for (i<-0 until 2*n) {\n cups(i) = capasLine.long\n }\n cups = cups.sortWith(_<_)\n val girlsCap = cups(0)\n val boysCap = cups(n)\n val min = Math.min(girlsCap, boysCap/2d)\n val possibleVol = min*n*3\n \n val res = Math.min(possibleVol, w)\n println(res)\n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n \n //---------------------------- service code ----------------------------------\n \n\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n \n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n3 18\n4 4 4 2 2 2\n\"\"\"\n\n}\n\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\nimport scala.math.min\nimport scala.language.postfixOps\n\nobject B {\n def main(args: Array[String]) {\n val n :: w :: _ = readLine split \" \" map (_.toDouble) toList\n val arr = readLine split \" \" map (_.toDouble) sorted\n var boy = arr(arr.length / 2)\n var girl = boy / 2\n if (girl > arr(0)) {\n girl = arr(0)\n boy = girl * 2\n }\n val sum = boy * n + girl * n\n println(min(sum, w))\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec, scala.collection.mutable\nimport CodeForcesApp._\nobject _557B extends CodeForcesApp[Double]({scanner => import scanner._\n val (n, w) = (nextInt, nextInt)\n val cups = IndexedSeq.fill(2*n)(nextInt).sorted\n val (x, y) = (cups(n).toDouble, cups(0).toDouble)\n val g = y min (x/2)\n 3*g*n min w\n})\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n val (modulus: Int, eps: Double) = (1000000007, 1e-9)\n def when[A](x: Boolean)(f: => A): Option[A] = if (x) Some(f) else None\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n}\n"}, {"source_code": "import scala.annotation.tailrec, scala.collection.mutable\nimport CodeForcesApp._\nobject _557B extends CodeForcesApp[Double]({scanner => import scanner._\n val (n, w) = (nextInt, nextInt)\n val cups = IndexedSeq.fill(2*n)(nextInt).sorted\n val (x, y) = (cups(n).toDouble, cups(0).toDouble)\n val g = y min (x/2)\n val ans = 3*g*n\n ans min w\n})\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n val modulus: Int = 1000000007\n val eps: Double = 1e-9\n def when[A](x: Boolean)(f: => A): Option[A] = if (x) Some(f) else None\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n}\n"}], "negative_code": [{"source_code": "import scala.annotation.tailrec, scala.collection.mutable\nimport CodeForcesApp._\nobject _557B extends CodeForcesApp[Double]({scanner => import scanner._\n val (n, w) = (nextInt, nextInt)\n val cups = List.fill(2*n)(nextInt)\n val (girls, boys) = cups.sorted.splitAt(n)\n val (x, y) = (boys.last.toDouble, girls.last.toDouble)\n debug(x, y, y >= x/2)\n val ans = if (y >= x/2) {\n x*n + (x/2)*n\n } else {\n y*n + 2*y*n\n }\n ans min w\n})\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n val modulus: Int = 1000000007\n val eps: Double = 1e-9\n def when[A](x: Boolean)(f: => A): Option[A] = if (x) Some(f) else None\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n}\n"}], "src_uid": "b2031a328d72b464f965b4789fd35b93"} {"source_code": "object Main extends App {\n\tvar i = 0\n\tvar k1 = 0\n\tvar k2 = 0\n\tvar flag = 1\n val Token = readLine().split(\" \").map(_.toLong)\n var n = Token(0).toInt\n var l = Token(1).toInt - 1\n var r = Token(2).toInt - 1\n val arr1 = readLine().split(\" \").map(_.toLong)\n val arr2 = readLine().split(\" \").map(_.toLong)\n \n while (i < n) {\n k1 = arr1(i).toInt\n k2 = arr2(i).toInt\n if ((i < l || i > r) && k1 != k2) {flag = 0}\n i += 1\n }\n if (flag == 1) {print(\"TRUTH\")}\n else {print(\"LIE\")}\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nimport scala.collection.mutable\n\nimport scala.collection.mutable._\n\nobject CF795D {\n def main(args: Array[String]) {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n val l = sc.nextInt\n val r = sc.nextInt\n val a = new Array[Int](n)\n val b = new Array[Int](n)\n for (i <- a.indices) a(i) = sc.nextInt\n for (j <- b.indices) b(j) = sc.nextInt\n if (!a.slice(0, l-1).sameElements(b.slice(0, l-1)) ||\n !a.slice(r, n).sameElements(b.slice(r, n))) {\n println(\"LIE\")\n } else if (!a.slice(l-1, r).sorted.sameElements(b.slice(l-1, r).sorted)) {\n println(\"LIE\")\n } else {\n println(\"TRUTH\")\n }\n }\n}"}, {"source_code": "object Main extends App {\n\tval Array(n, l,r) = readLine().split(\" \").map(_.toInt)\n\tvar array1 = Array.fill[Int](n+5)(0)\n\tvar array2 = Array.fill[Int](n+5)(0)\n\t\n\tval s = readLine\n\tval a: Array[Int] = s.split(\" \").map(_.toInt)\n for (i <- 0 until a.length) {\n \tif(l-1<=i && i<=r-1){\n \t\t// println(a(i))\n \t\tarray1(a(i)) = array1(a(i))+1 \n \t}\n\t}\n\t\n\tval s1 = readLine\n\tval a1: Array[Int] = s1.split(\" \").map(_.toInt)\n for (i <- 0 until a1.length) {\n \tif(l-1<=i && i<=r-1){\n \t\t// println(a(i))\n \t\tarray2(a1(i)) = array2(a1(i))+1\n \t}\n\t}\n\tvar flag = true\n\tfor (i <- 0 until array1.length) {\n\t\tif(array1(i)!=array2(i))\n\t\t\tflag = false\n }\n for (i <- 0 until a1.length) {\n \tif(l-1<=i && i<=r-1){\n \t\t// println(a(i))\n \t\t// array2(a1(i)) = array2(a1(i))+1\n \t}\n \telse {\n \t\tif(a(i)!=a1(i))\n \t\t\tflag = false\n \t}\n\t}\n if(flag) print(\"TRUTH\")\n else print(\"LIE\")\n}"}, {"source_code": "object D {\n def shuffle[T](array: Array[T]): Array[T] = {\n val rnd = new java.util.Random\n for (n <- Iterator.range(array.length - 1, 0, -1)) {\n val k = rnd.nextInt(n + 1)\n val t = array(k); array(k) = array(n); array(n) = t\n }\n return array\n }\n \n\tdef main(args: Array[String]) = {\n\t\tval scanner = new java.util.Scanner(System.in)\n\t\tval n, l, r = scanner.nextInt()\n\t\tvar a, b = new Array[Int](n)\n\t\tfor (i <- 0 to n-1) {\n\t\t\ta(i) = scanner.nextInt()\n\t\t}\n\t\tfor (i <- 0 to n-1) {\n\t\t\tb(i) = scanner.nextInt()\n\t\t}\n\t\tvar i = 0\n\t\tvar lie = false\n\t\tfor (i <- 1 to n) {\n\t\t\tif (a(i-1) != b(i-1) && (i < l || r < i)) {\n\t\t\t\tlie = true\n\t\t\t}\n\t\t}\n\t\tshuffle(a)\n\t\tscala.util.Sorting.quickSort(a)\n\t\tshuffle(b)\n\t\tscala.util.Sorting.quickSort(b)\n\t\tfor (i <- 1 to n) {\n\t\t\tif (a(i-1) != b(i-1)) {\n\t\t\t\tlie = true\n\t\t\t}\n\t\t}\n\t\tif (lie) {\n\t\t\tprintln(\"LIE\")\n\t\t} else {\n\t\t\tprintln(\"TRUTH\")\n\t\t}\n\t}\n}"}, {"source_code": "object Main extends App {\n var Array(n,l,r) = readLine.split(\" \").map(_.toInt)\n var a:Array[Int] = readLine.split(\" \").map(_.toInt)\n var b:Array[Int] = readLine.split(\" \").map(_.toInt)\n \n var lo:Int = 0\n var ro:Int = n - 1\n while(lo < n && (a(lo) equals b(lo))){\n lo = lo + 1\n }\n while(ro >= 0 && (a(ro) equals b(ro))){\n ro = ro - 1\n }\n l = l - 1\n r = r - 1\n if(lo >= l & ro <= r){\n println(\"TRUTH\")\n }\n else{\n println(\"LIE\")\n }\n \n}"}, {"source_code": "object tmp {\n def main(args: Array[String]) {\n val Array(n,l,r) = readLine.split(\" \").map(_.toInt)\n val s1 = readLine\n val a: Array[Int] = s1.split(\" \").map(_.toInt)\n val s2 = readLine\n val b: Array[Int] = s2.split(\" \").map(_.toInt)\n var i = 0;\n var can = 1;\n for (i <- 0 to n-1){\n if (i < l-1 || i > r-1) {\n if (a(i) != b(i)) {\n can = 0;\n }\n }\n }\n var l1 = Array.fill[Int](100001)(0);\n var l2 = Array.fill[Int](100001)(0);\n for (i <- l-1 to r-1){\n l1(a(i)) = l1(a(i)) + 1;\n l2(b(i)) = l2(b(i)) + 1;\n }\n for (i <- 0 to 100000){\n if (l1(i) != l2(i))\n can = 0;\n }\n if (can == 1) {\n println(\"TRUTH\");\n } else {\n println(\"LIE\");\n }\n }\n} "}, {"source_code": "object CF {\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n val l = sc.nextInt()-2\n val r = sc.nextInt()\n val a = Array.tabulate(n)(_ => sc.nextInt())\n val b = Array.tabulate(n)(_ => sc.nextInt())\n var fl = 1\n val i = 0\n for( i <- 0 to l){\n if(a(i) != b(i)) fl = 0\n }\n for( i <- r to n-1){\n if(a(i) != b(i)) fl = 0\n }\n if(fl > 0){\n println(\"TRUTH\")\n }else{\n println(\"LIE\")\n }\n }\n}"}], "negative_code": [{"source_code": "object Main extends App {\n\tval Array(n, l,r) = readLine().split(\" \").map(_.toInt)\n\tvar array1 = Array(0)\n\tvar array2 = Array(0)\n\tval s = readLine\n\tval a: Array[Int] = s.split(\" \").map(_.toInt)\n for (i <- 0 until a.length) {\n \tif(l<=i && i<=r)\n\t \tarray1 :+= a(i)\n\t}\n\t\n\tval s1 = readLine\n\tval a1: Array[Int] = s1.split(\" \").map(_.toInt)\n for (i <- 0 until a1.length) {\n \tif(l<=i && i<=r)\n\t \tarray2 :+= a1(i)\n\t}\n\tscala.util.Sorting.quickSort(array1)\n\tscala.util.Sorting.quickSort(array2)\n\tvar flag = true\n\tfor (i <- 0 until array1.length) {\n\t\t// println(array1(i))\n\t\t// println(array2(i))\n\t\tif(array1(i)!=array2(i))\n\t\t\tflag = false\n }\n // print(flag)\n if(flag) print(\"TRUTH\")\n else print(\"LIE\")\n}"}, {"source_code": "object Main extends App {\n\tval Array(n, l,r) = readLine().split(\" \").map(_.toInt)\n\tvar array1 = Array.fill[Int](n+5)(0)\n\tvar array2 = Array.fill[Int](n+5)(0)\n\tval s = readLine\n\tval a: Array[Int] = s.split(\" \").map(_.toInt)\n for (i <- 0 until a.length) {\n \tif(l-1<=i && i<=r-1){\n \t\t// println(a(i))\n \t\tarray1(a(i)) = array1(a(i))+1 \n \t}\n\t}\n\t\n\tval s1 = readLine\n\tval a1: Array[Int] = s1.split(\" \").map(_.toInt)\n for (i <- 0 until a1.length) {\n \tif(l-1<=i && i<=r-1){\n \t\t// println(a(i))\n \t\tarray2(a1(i)) = array2(a1(i))+1\n \t}\n\t}\n\tvar flag = true\n\tfor (i <- 0 until array1.length) {\n\t\tif(array1(i)!=array2(i))\n\t\t\tflag = false\n }\n if(flag) print(\"TRUTH\")\n else print(\"LIE\")\n}"}], "src_uid": "1951bf085050c7e32fcf713132b30605"} {"source_code": "object B651 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n).sorted\n val vis = Array.fill(n)(false)\n for(i <- 0 until n) {\n var pos = -1\n for(j <- i+1 until n if pos == -1 && !vis(j)) {\n if(in(j) > in(i)) {\n pos = j\n vis(pos) = true\n }\n }\n }\n println(vis.count(identity))\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "\nobject Paintings {\n\n def main (args: Array[String]) {\n\n //System.setIn(new FileInputStream(\"./src/paintings.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"./src/paintings.out\")))\n\n var n = readInt()\n var a: Array[Int] = readLine().split(\" \").map(_.toInt).sorted\n\n var same = 0\n var maxSame = 1\n\n for(i <- 0 until a.length) {\n if(i == 0 || a(i) > a(i - 1)) {\n same = 1\n }\n else {\n same += 1\n maxSame = Math.max(maxSame, same)\n }\n }\n\n println(n - maxSame)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.Scanner\n\nimport scala.collection.mutable.ListBuffer\n\nobject Solution extends ConsoleIO {\n def main(args: Array[String]) = {\n withIO { (reader, writer) =>\n val n = reader.nextInt()\n val a = ListBuffer.empty[Int]\n for (i <- 0 until n) {\n val el = reader.nextInt()\n a.append(el)\n }\n var answer = 0\n while (a.nonEmpty) {\n var min = a.min\n a -= min\n var exit = false\n while (!exit) {\n var r: Option[Int] = None\n for (el <- a) if (el > min && (r.isEmpty || r.exists(_ > el))) r = Some(el)\n if (r.isDefined) {\n answer += 1\n min = r.get\n a -= min\n } else {\n exit = true\n }\n }\n }\n writer.print(answer)\n }\n }\n}\n\ntrait ConsoleIO {\n def withIO(task: (Scanner, PrintWriter) => Unit) = {\n val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))\n val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n task(reader, writer)\n reader.close()\n writer.close()\n }\n}\n\ntrait FileIO {\n def withIO(task: (Scanner, PrintWriter) => Unit) = {\n val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream(\"input.txt\"))))\n val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(\"output.txt\"))))\n task(reader, writer)\n reader.close()\n writer.close()\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val length = in.next().split(' ').map(_.toInt).groupBy(i => i).maxBy(_._2.length)._2.length\n println(n - length)\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n\n override def toString = s\"MultiHashSet($map)\"\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n }\n val sorted = a.sorted\n var ind = 0\n var ans = 0L\n var previousSize = 0\n while (ind < n) {\n var prev = ind\n while (prev < n && sorted(prev) == sorted(ind)) {\n prev += 1\n }\n ans += Math.min(prev - ind, previousSize)\n previousSize = Math.max(previousSize, prev - ind)\n ind = prev\n }\n out.println(ans)\n return 0\n }\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _651B extends CodeForcesApp {\n override def apply(io: IO) = {\n val data = io[IndexedSeq[Int]]\n io += (data.length - data.counts.values.max)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates: Traversable[A] = {\n val elems = mutable.Set.empty[A]\n t collect {case i if !elems.add(i) => i}\n }\n def zipWith[B](f: A => B): Traversable[(A, B)] = t map {i => i -> f(i)}\n def mapTo[B](f: A => B): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirstDefined[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def counts: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class IndexedSeqExtensions[A](val s: IndexedSeq[A]) extends AnyVal {\n def withOffset(offset: Int): IndexedSeq[A] = Iterator.fill(offset)(null.asInstanceOf[A]) ++: s\n }\n implicit class PairsExtensions[A, B](val t: Traversable[(A, B)]) extends AnyVal {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap: Map[A, Traversable[B]] = t.groupBy(_._1).mapValues(_.map(_._2))\n def swap: Traversable[(B, A)] = t.map(_.swap)\n }\n implicit class MapExtensions[K, V](val map: Map[K, V]) extends AnyVal {\n def invert: Map[V, Traversable[K]] = map.swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = (map map {case (k, v) => f(k) -> v}).toUniqueMap\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def mod(y: Int) = x - (x/y)*y //(x/y)*y + (x mod y) == x\n def -->(y: Int) = if (x < y) x to y else y to x\n def nonNegative: Option[Int] = when(x >= 0)(x) //e.g. students.indexOf(\"Greg\").nonNegative\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount = java.lang.Long.bitCount(x)\n def pow(i: Int): Long = if (i == 0) 1 else {\n val h = x pow (i/2)\n if (i%2 == 0) h*h else h*h*x\n }\n }\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse\n def asc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]]\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default\n }\n def memoize[I] = new {\n def apply[O](f: I => O): (I => O) = new mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n @inline def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n val mod: Int = (1e9 + 7).toInt\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] with collection.generic.Growable[Any] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n def apply[C[_], A: Parser](n: Int)(implicit builder: Parser.Collection[C, A]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n override def +=(obj: Any) = {\n if (isNewLine) isNewLine = false else print(separator)\n print(obj)\n this\n }\n def ++=(t: TraversableOnce[_], ifEmpty: => Any): this.type = if (t.isEmpty) this += ifEmpty else this ++= t\n\n def newLine(): this.type = {\n println()\n isNewLine = true\n this\n }\n\n override def clear() = flush()\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\n\nclass Parser[A](val apply: IO => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _651B extends CodeForcesApp {\n override def apply(io: IO) = {\n var data = io[IndexedSeq[Int]].counts.toMap\n var ans = 0\n while(data.nonEmpty) {\n ans += data.size - 1\n data = data collect {\n case (k, v) if v > 1 => (k, v - 1)\n }\n }\n io += ans\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates: Traversable[A] = {\n val elems = mutable.Set.empty[A]\n t collect {case i if !elems.add(i) => i}\n }\n def zipWith[B](f: A => B): Traversable[(A, B)] = t map {i => i -> f(i)}\n def mapTo[B](f: A => B): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def counts: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class IndexedSeqExtensions[A](val s: IndexedSeq[A]) extends AnyVal {\n def withOffset(offset: Int): IndexedSeq[A] = Iterator.fill(offset)(null.asInstanceOf[A]) ++: s\n }\n implicit class PairsExtensions[A, B](val t: Traversable[(A, B)]) extends AnyVal {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap: Map[A, Traversable[B]] = t.groupBy(_._1).mapValues(_.map(_._2))\n def swap: Traversable[(B, A)] = t.map(_.swap)\n }\n implicit class MapExtensions[K, V](val m: Map[K, V]) extends AnyVal {\n def invert: Map[V, Traversable[K]] = m.swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def mod(y: Int) = x - (x/y)*y //(x/y)*y + (x mod y) == x\n def -->(y: Int) = if (x < y) x to y else y to x\n def nonNegative: Option[Int] = when(x >= 0)(x) //e.g. students.indexOf(\"Greg\").nonNegative\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount = java.lang.Long.bitCount(x)\n def pow(i: Int): Long = if (i == 0) 1 else {\n val h = x pow (i/2)\n if (i%2 == 0) h*h else h*h*x\n }\n }\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]]\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default\n }\n def memoize[I] = new {\n def apply[O](f: I => O): (I => O) = new mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n @inline def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n val mod: Int = (1e9 + 7).toInt\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] with collection.generic.Growable[Any] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n def apply[C[_], A: Parser](n: Int)(implicit builder: Parser.Collection[C, A]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n override def +=(obj: Any) = {\n if (isNewLine) isNewLine = false else print(separator)\n print(obj)\n this\n }\n def ++=(t: TraversableOnce[_], ifEmpty: => Any): this.type = if (t.isEmpty) this += ifEmpty else this ++= t\n\n def newLine(): this.type = {\n println()\n isNewLine = true\n this\n }\n\n override def clear() = flush()\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\n\nclass Parser[A](val apply: IO => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _651B extends CodeForcesApp {\n override def apply(io: IO) = {\n val data = io[IndexedSeq[Int]].counts.values\n io += (data.sum - data.max)\n }\n}\n/*\nCharity begins at home.\n\t\t-- Publius Terentius Afer (Terence)\n*/\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates: Traversable[A] = {\n val elems = mutable.Set.empty[A]\n t collect {case i if !elems.add(i) => i}\n }\n def zipWith[B](f: A => B): Traversable[(A, B)] = t map {i => i -> f(i)}\n def mapTo[B](f: A => B): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def counts: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class IndexedSeqExtensions[A](val s: IndexedSeq[A]) extends AnyVal {\n def withOffset(offset: Int): IndexedSeq[A] = Iterator.fill(offset)(null.asInstanceOf[A]) ++: s\n }\n implicit class PairsExtensions[A, B](val t: Traversable[(A, B)]) extends AnyVal {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap: Map[A, Traversable[B]] = t.groupBy(_._1).mapValues(_.map(_._2))\n def swap: Traversable[(B, A)] = t.map(_.swap)\n }\n implicit class MapExtensions[K, V](val m: Map[K, V]) extends AnyVal {\n def invert: Map[V, Traversable[K]] = m.swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def mod(y: Int) = x - (x/y)*y //(x/y)*y + (x mod y) == x\n def -->(y: Int) = if (x < y) x to y else y to x\n def nonNegative: Option[Int] = when(x >= 0)(x) //e.g. students.indexOf(\"Greg\").nonNegative\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount = java.lang.Long.bitCount(x)\n def pow(i: Int): Long = if (i == 0) 1 else {\n val h = x pow (i/2)\n if (i%2 == 0) h*h else h*h*x\n }\n }\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]]\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default\n }\n def memoize[I] = new {\n def apply[O](f: I => O): (I => O) = new mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n @inline def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n val mod: Int = (1e9 + 7).toInt\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] with collection.generic.Growable[Any] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n def apply[C[_], A: Parser](n: Int)(implicit builder: Parser.Collection[C, A]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n override def +=(obj: Any) = {\n if (isNewLine) isNewLine = false else print(separator)\n print(obj)\n this\n }\n def ++=(t: TraversableOnce[_], ifEmpty: => Any): this.type = if (t.isEmpty) this += ifEmpty else this ++= t\n\n def newLine(): this.type = {\n println()\n isNewLine = true\n this\n }\n\n override def clear() = flush()\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\n\nclass Parser[A](val apply: IO => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _651B extends CodeForcesApp {\n override def apply(io: IO) = {\n val data = io[IndexedSeq[Int]]\n io += (data.length - data.groupBy(identity).map(_._2.length).max)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] with collection.generic.Growable[Any] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n def apply[C[_], A: Parser](n: Int)(implicit builder: Parser.Collection[C, A]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n override def +=(obj: Any): this.type = {\n if (isNewLine) isNewLine = false else print(separator)\n print(obj)\n this\n }\n def ++=(t: TraversableOnce[_], ifEmpty: => Any): this.type = if (t.isEmpty) this += ifEmpty else this ++= t\n\n def newLine(): this.type = {\n println()\n isNewLine = true\n this\n }\n\n override def clear() = flush()\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\n\nclass Parser[A](val apply: IO => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _651B extends CodeForcesApp {\n override def solve(in: InputReader, out: OutputWriter) = {\n val c = in[Traversable[Int]].counts\n\n @tailrec\n def f(acc: Int): Int = if (c.size <= 1) {\n acc\n } else {\n val size = c.size\n c.keys foreach {k =>\n if (c(k) == 1) c.remove(k) else c(k) -= 1\n }\n f(acc + size - 1)\n }\n\n out += f(0)\n }\n\n implicit class TraversableExtensions[A](t: Traversable[A]) {\n def counts = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n }\n\n def map[K] = new {\n def to[V](default: V): mutable.Map[K, V] = mutable.Map.empty[K, V] withDefaultValue default\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def solve(in: InputReader, out: OutputWriter): Any\n def main(args: Array[String]): Unit = {\n val (in, out) = (new InputReader(System.in), new OutputWriter(System.out))\n solve(in, out)\n in.close()\n out.close()\n }\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n def apply[C[_], A: Parser](n: Int)(implicit builder: Parser.Collection[C, A]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\n\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n\nclass OutputWriter(out: PrintWriter) extends AutoCloseable {\n def this(out: OutputStream) = this(new PrintWriter(out))\n\n var separator = \" \"\n private[this] var isNewLine: Boolean = true\n\n def +=(obj: Any): this.type = {\n if (isNewLine) isNewLine = false else out.print(separator)\n out.print(obj)\n this\n }\n\n def newLine(): this.type = {\n isNewLine = true\n out.println()\n this\n }\n\n def ++=(obj: Traversable[_], ifEmpty: => Any = \"\"): this.type = {\n var c = 0\n obj foreach {i =>\n this += i\n c += 1\n }\n if (c == 0) this += ifEmpty else this\n }\n\n def append(obj: Any*): this.type = this ++= obj\n\n override def close() = {\n out.flush()\n out.close()\n }\n}\n"}, {"source_code": "/**\n * Created by aborisenko on 21.02.16.\n */\n\nimport io.StdIn._\n\nobject Main extends App {\n def b651 (){\n\n val n = readInt()\n\n val a = readLine().split(\" \").map(_.toInt)\n\n var b = Array.fill[Int](1001)(0)\n\n for(i <- 0 to n-1) {\n b(a(i)) += 1\n }\n\n var result = 0\n\n var nn = 0\n var f = true\n\n while(f){\n f = false\n for(j <- 1 to 1000){\n if( b(j) > 0 ) {\n result += 1\n b(j) -= 1\n f = true\n }\n }\n if( f ) result -= 1\n }\n\n println( result )\n }\n\n b651()\n}\n\n// 1 1 2 2 3 3\n\n// 1 2 3 1 2 3\n\n// 1 2 1 2 3 3"}], "negative_code": [{"source_code": "/**\n * Created by aborisenko on 21.02.16.\n */\n\nimport io.StdIn._\n\nobject Main extends App {\n def b651 (){\n\n val n = readInt()\n\n val a = readLine().split(\" \").map(_.toInt)\n\n var b = Array.fill[Int](1001)(0)\n\n for(i <- 0 to n-1) {\n b(a(i)) += 1\n }\n\n var result = 0\n\n var i = 1\n while( b(i) == 0)\n i += 1\n\n var nn = b(i)\n\n for(j <- i+1 to 1000){\n if(b(j) > 0) {\n result += Math.min(nn, b(j))\n nn = Math.abs(nn - b(j)) + 1\n }\n }\n\n println(result)\n }\n\n b651()\n}"}], "src_uid": "30ad5bdc019fcd8a4e642c90decca58f"} {"source_code": "object CF939A extends App{\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n val f = Seq.fill[Int](n)(sc.nextInt)\n val fn = (1 to n) map (i => f(i-1)) map (i => f(i-1)) map (i => f(i-1)) map (_ - 1)\n println(if ((fn zipWithIndex) filter (a => a._1 == a._2) nonEmpty) \"YES\" else \"NO\")\n}", "positive_code": [{"source_code": "object LoveTriangle {\n def main(args: Array[String]): Unit = {\n val in = scala.io.StdIn\n val n= in.readInt()\n val arr=in.readLine().split(\" \").map(_.toInt-1)\n for(i<- 0 until n){\n var j=i\n val visited=Array.fill[Boolean](n)(false)\n var loopSize=0\n while (!visited(j)){\n visited(j)=true\n j=arr(j)\n loopSize+=1\n } \n if(j==i && loopSize==3){\n println(\"YES\")\n return\n }\n }\n println(\"NO\")\n }\n}\n"}, {"source_code": "import scala.collection.mutable.HashSet\n\n//https://codeforces.com/problemset/problem/939/A\nobject LoveTriangle {\n def main(args: Array[String]): Unit = {\n val in = scala.io.StdIn\n val n= in.readInt()\n val arr=in.readLine().split(\" \").map(_.toInt-1)\n for(i<- 0 until n){\n var j=i\n //val visited=Array.fill[Boolean](n)(false)\n val visited=HashSet[Int]()\n var loopSize=0\n while (!visited.contains(j)){\n visited+=(j)\n j=arr(j)\n loopSize+=1\n }\n if(j==i && loopSize==3){\n println(\"YES\")\n return\n }\n }\n println(\"NO\")\n }\n}\n"}, {"source_code": "object A464 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val arr = readInts(n)\n val res = arr.exists { a =>\n val c = arr(arr(a - 1) - 1)\n a != c && arr(c - 1) == a\n }\n out.println(if (res) \"YES\" else \"NO\")\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object LoveTriangle939A_v2 extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n solve(System.in,System.out)\n def solve(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextInt()\n val nodes = (0 until n).map(Node).toArray\n val edges = (0 until n).map(i => Edge(nodes(i), nodes(scanner.nextInt()-1)))\n\n val g = new Graph(nodes,edges)\n\n val existsLoveTriangle: Boolean = g.existsCycleOf3()\n\n if(existsLoveTriangle)\n out.println(\"YES\")\n else\n out.println(\"NO\")\n }\n}\nclass Graph(val nodes: Seq[Node],val edges: Seq[Edge]){\n val edgesOutgoing = nodes.map(n => n -> edges.filter(_.from == n)).toMap\n def existsCycleOf3(): Boolean = {\n nodes.foreach(_.visited = false)\n nodes.foreach(_.cleared = false)\n\n def dfs(u: Node): Boolean = {\n u.visited=true\n val result = edgesOutgoing(u).exists{ e =>\n val v = e.to\n if(v.cleared){\n false\n }else {\n if (v.visited) {\n u.indexDFS == v.indexDFS + 2\n } else {\n v.indexDFS = u.indexDFS + 1\n dfs(v)\n }\n }\n }\n\n u.cleared = true\n result\n }\n nodes.exists{ u =>\n if(u.visited) false\n else{\n u.indexDFS = 0\n dfs(u)\n }\n }\n }\n}\ncase class Node(node: Int){\n var visited: Boolean = false\n var indexDFS: Int = 0\n var cleared: Boolean = false\n\n}\ncase class Edge(from: Node, to: Node)"}, {"source_code": "object LoveTriangle939A extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n solve(System.in,System.out)\n def solve(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextInt()\n val f = (0 until n).map(_ => scanner.nextInt()-1)\n\n val existsLoveTriangle = (0 until n).exists{ a =>\n val b = f(a)\n val c = f(b)\n f(c) == a\n }\n if(existsLoveTriangle)\n out.println(\"YES\")\n else\n out.println(\"NO\")\n }\n}"}], "negative_code": [{"source_code": "object A464 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n out.println(sys.env)\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (sys.env.contains(\"ONLINE_JUDGE\")) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object A464 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val arr = readInts(n)\n val res = arr.exists { a =>\n val b = arr(a - 1)\n val c = arr(b - 1)\n a != c && c == a\n }\n out.println(if (res) \"YES\" else \"NO\")\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object LoveTriangle939A_v2 extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n solve(System.in,System.out)\n def solve(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextInt()\n val nodes = (0 until n).map(Node).toArray\n val edges = (0 until n).map(i => Edge(nodes(i), nodes(scanner.nextInt()-1)))\n\n val g = new Graph(nodes,edges)\n\n val existsLoveTriangle: Boolean = g.existsCycleOf3()\n\n if(existsLoveTriangle)\n out.println(\"YES\")\n else\n out.println(\"NO\")\n }\n}\nclass Graph(val nodes: Seq[Node],val edges: Seq[Edge]){\n val edgesOutgoing = nodes.map(n => n -> edges.filter(_.from == n)).toMap\n def existsCycleOf3(): Boolean = {\n nodes.foreach(_.visited = false)\n nodes.foreach(_.indexDFS = 0)\n def dfs(u: Node): Boolean = {\n u.visited=true\n edgesOutgoing(u).exists{ e =>\n val v = e.to\n if(v.visited){\n u.indexDFS == v.indexDFS+2\n }else{\n v.indexDFS = u.indexDFS+1\n dfs(v)\n }\n }\n\n }\n nodes.exists{ u =>\n if(u.visited) false\n else{\n dfs(u)\n }\n }\n }\n}\ncase class Node(node: Int){\n var visited: Boolean = false\n var indexDFS: Int = 0\n\n}\ncase class Edge(from: Node, to: Node)"}, {"source_code": "object LoveTriangle939A_v2 extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n solve(System.in,System.out)\n def solve(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextInt()\n val nodes = (0 until n).map(Node).toArray\n val edges = (0 until n).map(i => Edge(nodes(i), nodes(scanner.nextInt()-1)))\n\n val g = new Graph(nodes,edges)\n\n val existsLoveTriangle: Boolean = g.existsCycleOf3()\n\n if(existsLoveTriangle)\n out.println(\"YES\")\n else\n out.println(\"NO\")\n }\n}\nclass Graph(val nodes: Seq[Node],val edges: Seq[Edge]){\n val edgesOutgoing = nodes.map(n => n -> edges.filter(_.from == n)).toMap\n def existsCycleOf3(): Boolean = {\n nodes.foreach(_.visited = false)\n\n def dfs(u: Node): Boolean = {\n u.visited=true\n edgesOutgoing(u).exists{ e =>\n val v = e.to\n if(v.visited){\n u.indexDFS == v.indexDFS+2\n }else{\n v.indexDFS = u.indexDFS+1\n dfs(v)\n }\n }\n\n }\n nodes.exists{ u =>\n if(u.visited) false\n else{\n u.indexDFS = 0\n dfs(u)\n }\n }\n }\n}\ncase class Node(node: Int){\n var visited: Boolean = false\n var indexDFS: Int = 0\n\n}\ncase class Edge(from: Node, to: Node)"}], "src_uid": "a37c3f2828490c70301b5b5deeee0f88"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport java.lang.Long\nimport scala.collection.immutable.HashSet\n\n/**\n * @author kperikov\n */\nobject D_334 {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def solve = {\n val n = nextInt\n val m = nextInt\n var setX = new HashSet[Int]()\n var setY = new HashSet[Int]()\n for (i <- 0 until m) {\n setX += nextInt\n setY += nextInt\n }\n var ans = 0\n for (i <- 2 to n - 1) {\n if (!setX.contains(i)) {\n ans += 1\n }\n if (!setY.contains(i)) {\n ans += 1\n }\n }\n if (n % 2 == 1 && !setX.contains(n / 2) && !setY.contains(n / 2) && ans > 1) {\n ans -= 1\n }\n out.println(ans)\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n\n val badCols = Array.fill(n)(false)\n val badRows = Array.fill(n)(false)\n \n for (i <- 0 until m) {\n val Array(c, r) = readInts\n badCols(c - 1) = true\n badRows(r - 1) = true\n }\n \n badCols(0) = true\n badCols(n - 1) = true\n badRows(0) = true\n badRows(n - 1) = true\n \n val useCol = Array.fill(n)(false)\n for (i <- badCols.indices) {\n \tuseCol(i) = !badCols(i)// && !(!badRows(i) && !badRows(n - i - 1) && useCol(n - i - 1))\n }\n \n val res = useCol.count(identity) + badRows.indices.count(i => !badRows(i) && ((i != n / 2 || n % 2 != 1) || !useCol(i) || !useCol(n - i - 1)))\n \n println(res)\n}"}, {"source_code": "import scala.collection.mutable\n\n/**\n * User: Oleg Nizhnik\n * Date: 29.07.13\n * Time: 20:30\n */\nobject D_Chips extends App {\n def readPair() = readLine() split ' ' map (_.toInt)\n val xs, ys = mutable.BitSet.empty\n val Array(n, m) = readPair()\n 2 to (n - 1) foreach (i => xs.add(i) && ys.add(i))\n 1 to m foreach (_ => readPair() match {case Array(x, y) => xs.remove(x); ys.remove(y)})\n println(xs.size + ys.size -\n (if (n % 2 == 1 && xs.contains((n + 1) / 2) && ys.contains((n + 1) / 2)) 1 else 0))\n\n\n}\n"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n\n val badCols = Array.fill(n)(false)\n val badRows = Array.fill(n)(false)\n \n for (i <- 0 until m) {\n val Array(c, r) = readInts\n badCols(c - 1) = true\n badRows(r - 1) = true\n }\n \n badCols(0) = true\n badCols(n - 1) = true\n badRows(0) = true\n badRows(n - 1) = true\n \n val mid = n / 2\n if (n % 2 == 1 && !badCols(mid)) badRows(mid) = true\n \n println(badCols.count(!_) + badRows.count(!_))\n}"}], "negative_code": [{"source_code": "/**\n * User: Oleg Nizhnik\n * Date: 29.07.13\n * Time: 20:30\n */\nobject D_Chips extends App {\n def readPair() = readLine() split ' ' map (_.toInt)\n val Array(n, m) = readPair()\n val (xr, yr) = 1 to m map (_ => readPair()) unzip {case Array(x, y) => (x, y)}\n println((2 to (n - 1) diff xr).size + (2 to (n - 1) diff yr).size - (if (n % 2 == 1 && !xr.contains((n + 1 / 2)) && !yr.contains((n + 1) / 2)) 1 else 0))\n\n\n}\n"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n\n val badCols = Array.fill(n)(false)\n val badRows = Array.fill(n)(false)\n \n for (i <- 0 until m) {\n val Array(r, c) = readInts\n badCols(c - 1) = true\n badRows(r - 1) = true\n }\n \n badCols(0) = true\n badCols(n - 1) = true\n badRows(0) = true\n badRows(n - 1) = true\n \n badCols.indices.filter(i => !badCols(i)).foreach(i => badRows(i) = true)\n\n val res = badCols.count(!_) + badRows.count(!_)\n \n println(res)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n\n val badCols = Array.fill(n)(false)\n val badRows = Array.fill(n)(false)\n \n for (i <- 0 until m) {\n val Array(c, r) = readInts\n badCols(c - 1) = true\n badRows(r - 1) = true\n }\n \n badCols(0) = true\n badCols(n - 1) = true\n badRows(0) = true\n badRows(n - 1) = true\n \n badCols.indices.filter(i => !badCols(i)).foreach(i => badRows(i) = true)\n\n val res = badCols.count(!_) + badRows.count(!_)\n \n println(res)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n\n val badCols = Array.fill(n)(false)\n val badRows = Array.fill(n)(false)\n \n var i = 0\n// var rc = (0, 0)\n \n while (i < m) {\n //val Array(c, r) = readInts\n val rc = Console.readf2(\"{0,number} {1,number}\")\n badCols(rc._1.asInstanceOf[Long].toInt - 1) = true\n badRows(rc._2.asInstanceOf[Long].toInt - 1) = true\n i += 1\n }\n\n badCols(0) = true\n badCols(n - 1) = true\n badRows(0) = true\n badRows(n - 1) = true\n \n //badCols.indices.filter(i => !badCols(i)).foreach(i => badRows(i) = true)\n\n val res = badCols.count(!_) max badRows.count(!_)\n \n println(res)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n\n val badCols = Array.fill(n)(false)\n val badRows = Array.fill(n)(false)\n \n for (i <- 0 until m) {\n val Array(c, r) = readInts\n badCols(c - 1) = true\n badRows(r - 1) = true\n }\n \n badCols(0) = true\n badCols(n - 1) = true\n badRows(0) = true\n badRows(n - 1) = true\n \n val useCol = Array.fill(n)(false)\n for (i <- badCols.indices) {\n \tuseCol(i) = !badCols(i)// && !(!badRows(i) && !badRows(n - i - 1) && useCol(n - i - 1))\n }\n \n val res = useCol.count(identity) + badRows.indices.count(i => !badRows(i))// && (!useCol(i) || !useCol(n - i - 1)))\n \n println(res)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n\n val badCols = Array.fill(n)(false)\n val badRows = Array.fill(n)(false)\n \n for (i <- 0 until m) {\n val Array(c, r) = readInts\n badCols(c - 1) = true\n badRows(r - 1) = true\n }\n \n badCols(0) = true\n badCols(n - 1) = true\n badRows(0) = true\n badRows(n - 1) = true\n \n val res = badCols.count(!_) + badRows.indices.count(i => !badRows(i) && (badCols(i) || badCols(n - i - 1)))\n \n println(res)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n\n val badCols = Array.fill(n)(false)\n val badRows = Array.fill(n)(false)\n \n var i = 0\n// var rc = (0, 0)\n \n while (i < m) {\n //val Array(c, r) = readInts\n val rc = Console.readf2(\"{0,number} {1,number}\")\n badCols(rc._1.asInstanceOf[Long].toInt - 1) = true\n badRows(rc._2.asInstanceOf[Long].toInt - 1) = true\n i += 1\n }\n\n badCols(0) = true\n badCols(n - 1) = true\n badRows(0) = true\n badRows(n - 1) = true\n \n badCols.indices.filter(i => !badCols(i)).foreach(i => badRows(i) = true)\n\n val res = badCols.count(!_) + badRows.count(!_)\n \n println(res)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n\n val badCols = Array.fill(n)(false)\n val badRows = Array.fill(n)(false)\n \n for (i <- 0 until m) {\n val Array(c, r) = readInts\n badCols(c - 1) = true\n badRows(r - 1) = true\n }\n \n badCols(0) = true\n badCols(n - 1) = true\n badRows(0) = true\n badRows(n - 1) = true\n \n val useCol = Array.fill(n)(false)\n for (i <- badCols.indices) {\n \tuseCol(i) = !badCols(i) && !(!badRows(i) && !badRows(n - i - 1) && useCol(n - i - 1))\n }\n \n val res = useCol.count(identity) + badRows.indices.count(i => !badRows(i) && (!useCol(i) || !useCol(n - i - 1)))\n \n println(res)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n\n val badCols = Array.fill(n)(false)\n val badRows = Array.fill(n)(false)\n \n for (i <- 0 until m) {\n val Array(c, r) = readInts\n badCols(c - 1) = true\n badRows(r - 1) = true\n }\n \n badCols(0) = true\n badCols(n - 1) = true\n badRows(0) = true\n badRows(n - 1) = true\n \n val res = badCols.count(!_) + badRows.indices.count(i => !badRows(i) && (badCols(i) || badCols(n - i)))\n \n println(res)\n}"}], "src_uid": "a26a97586d4efb5855aa3b930e9effa7"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(val a: Int, val b: Int, val c: Long)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return (a).compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mapp = mutable.Map[pair, Int]()\n\n val t = readInt()\n\n for (tt <- 1 to t) {\n val s = readString()\n val arr = new Array[Int](1000)\n for (c <- s) {\n arr(c.toInt) += 1\n }\n for (i <- 0 until 1000) {\n if (arr(i) == 2){\n writer.print(i.toChar)\n }\n }\n for (i <- 0 until 1000) {\n if (arr(i) == 2){\n writer.print(i.toChar)\n }\n }\n for (i <- 0 until 1000) {\n if (arr(i) == 1){\n writer.print(i.toChar)\n }\n }\n writer.println()\n\n def check(kk: Long): Boolean = {\n return true\n }\n def bs(st:Long, en:Long): Long = {\n if (en - st <= 1L) {\n if (check(en))\n return en\n else\n return st\n }\n val mid = (st + en) / 2L\n if (check(mid))\n return bs(mid, en)\n else\n return bs(st, mid)\n }\n }\n writer.flush()\n}", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Letters {\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 0 until t) {\n println(readLine().sorted)\n }\n }\n}\n"}], "negative_code": [], "src_uid": "28102f75e0798960740e5a2625393c8f"} {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Codeforces1163B {\n\n def getLongestPossibleStreak(n: Int, u: Seq[Int]): Int = {\n val isStreak = new Array[Boolean](n)\n val colorFrequencyMap = new mutable.HashMap[Int, Int]()\n val countTracker = new FrequencyCountTracker\n for (i <- 0 until n) {\n val previousFrequency = colorFrequencyMap.getOrElse(u(i), 0)\n colorFrequencyMap(u(i)) = previousFrequency + 1\n\n countTracker.decreaseCount(previousFrequency)\n countTracker.increaseCount(previousFrequency + 1)\n\n isStreak(i) = countTracker.isEqualFrequencyByRemovingOne\n }\n for (i <- isStreak.indices.reverse) {\n if (isStreak(i)) return i + 1\n }\n 1\n }\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readLine().trim.toInt\n val u = StdIn.readLine().trim.split(\" \").map(_.toInt)\n val longestPossibleStreak = getLongestPossibleStreak(n, u)\n println(longestPossibleStreak)\n }\n\n class FrequencyCountTracker {\n val frequencyCountMap = new mutable.HashMap[Int, Int]()\n\n def increaseCount(frequency: Int): Unit = {\n val previousFrequencyCount = frequencyCountMap.getOrElse(frequency, 0)\n frequencyCountMap(frequency) = previousFrequencyCount + 1\n }\n\n def decreaseCount(frequency: Int): Unit = {\n if (frequency == 0) return\n val previousFrequencyCount = frequencyCountMap(frequency)\n previousFrequencyCount match {\n case 1 => frequencyCountMap.remove(frequency)\n case _ => frequencyCountMap(frequency) = previousFrequencyCount - 1\n }\n }\n\n def isEqualFrequencyByRemovingOne: Boolean = {\n frequencyCountMap.keys.size match {\n case 1 =>\n frequencyCountMap.keys.head == 1 || frequencyCountMap.values.head == 1\n case 2 =>\n val maxFrequency = frequencyCountMap.keys.max\n val minFrequency = frequencyCountMap.keys.min\n if (minFrequency == 1 && frequencyCountMap(minFrequency) == 1) true\n else if (minFrequency == maxFrequency - 1 && frequencyCountMap(maxFrequency) == 1) true\n else false\n case _ =>\n false\n }\n }\n }\n\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val C = Array.ofDim[Int](10)\n var ans = 0\n\n def test: Boolean = {\n map(10) { i =>\n if (C(i) > 0) {\n C(i) -= 1\n\n var num = 0\n var ok = true\n REP(10) { j =>\n if (C(j) != 0) {\n if (num != 0 && num != C(j)) {\n ok = false\n } else {\n num = C(j)\n }\n }\n }\n\n C(i) += 1\n ok\n } else {\n false\n }\n }.exists(identity)\n }\n\n REP(N) { i =>\n val u = ni() - 1\n C(u) += 1\n\n debug(C)\n if (test) ans = i + 1\n }\n\n out.println(ans)\n }\n}"}, {"source_code": "object _1163B1 extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val nums = io.read[Vector[Int]]\n\n val numToCount, countToMap = mutable.Map.empty[Int, Int].withDefaultValue(0)\n val ans = nums map {i =>\n val curr = numToCount(i)\n if (curr > 0) {\n countToMap(curr) -= 1\n if (countToMap(curr) <= 0) countToMap.remove(curr)\n }\n numToCount(i) = curr + 1\n countToMap(curr + 1) += 1\n\n val it = countToMap.keysIterator\n\n val res = countToMap.size match {\n case 1 =>\n val c1 = it.next()\n c1 == 1 || countToMap(c1) == 1\n case 2 =>\n val _c1, _c2 = it.next()\n val c1 = _c1 min _c2\n val c2 = _c1 max _c2\n\n ((c1 == 1) && countToMap(c1) == 1) ||\n (c1 == c2 - 1 && countToMap(c2) == 1)\n case _ => false\n }\n //debug(i, numToCount, countToMap, res)\n res\n }\n\n io.write(ans.lastIndexWhere(identity) + 1)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Codeforces1163B {\n\n def getLongestPossibleStreak(n: Int, u: Seq[Int]): Int = {\n val isStreak = new Array[Boolean](n)\n val colorFrequencyMap = new mutable.HashMap[Int, Int]()\n val countTracker = new FrequencyCountTracker\n for (i <- 0 until n) {\n val previousFrequency = colorFrequencyMap.getOrElse(u(i), 0)\n colorFrequencyMap(u(i)) = previousFrequency + 1\n\n countTracker.decreaseCount(previousFrequency)\n countTracker.increaseCount(previousFrequency + 1)\n\n isStreak(i) = countTracker.isEqualFrequencyByRemovingOne\n }\n for (i <- isStreak.indices.reverse) {\n if (isStreak(i)) return i + 1\n }\n 1\n }\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readLine().trim.toInt\n val u = StdIn.readLine().trim.split(\" \").map(_.toInt)\n val longestPossibleStreak = getLongestPossibleStreak(n, u)\n println(longestPossibleStreak)\n }\n\n class FrequencyCountTracker {\n val frequencyCountMap = new mutable.HashMap[Int, Int]()\n\n def increaseCount(frequency: Int): Unit = {\n val previousCount = frequencyCountMap.getOrElse(frequency, 0)\n frequencyCountMap(frequency) = previousCount + 1\n }\n\n def decreaseCount(frequency: Int): Unit = {\n if (frequency == 0) return\n val previousCount = frequencyCountMap(frequency)\n previousCount match {\n case 1 => frequencyCountMap.remove(frequency)\n case _ => frequencyCountMap(frequency) = previousCount - 1\n }\n }\n\n def isEqualFrequencyByRemovingOne: Boolean = {\n frequencyCountMap.keys.size match {\n case 1 =>\n frequencyCountMap.keys.head == 1\n case 2 =>\n val maxFrequency = frequencyCountMap.keys.max\n val minFrequency = frequencyCountMap.keys.min\n if (minFrequency == 1 && frequencyCountMap(minFrequency) == 1) true\n else if (minFrequency == maxFrequency - 1 && frequencyCountMap(maxFrequency) == 1) true\n else false\n case _ =>\n false\n }\n }\n }\n\n}\n"}], "src_uid": "2d020e6c3000836e8b903a12ae39dd9b"} {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val ts = readInts(n)\n\n val errs = ArrayBuffer.empty[Int]\n\n def isValid(i: Int) = {\n val t = ts(i)\n if (i % 2 == 0) {\n !((i > 0 && t >= ts(i - 1)) || (i < n - 1 && t >= ts(i + 1)))\n } else {\n !((i > 0 && t <= ts(i - 1)) || (i < n - 1 && t <= ts(i + 1)))\n }\n }\n\n def canSwapWithCheck(i: Int, j: Int, u: Int, v: Int, z: Int, x: Int) = {\n val ti = ts(i)\n val tj = ts(j)\n ts(i) = tj\n ts(j) = ti\n val can = i != j && isValid(i) && isValid(j) && isValid(u) && isValid(v) && isValid(z) && isValid(x)\n ts(i) = ti\n ts(j) = tj\n can\n }\n\n for (i <- ts.indices) {\n if (!isValid(i)) errs += i\n }\n\n var res = 0L\n\n errs match {\n case Seq(a, b) =>\n for (i <- ts.indices) if (canSwapWithCheck(a, i, b, b, b, b)) res += 1\n for (i <- ts.indices) if (i != a && canSwapWithCheck(b, i, a, a, a, a)) res += 1\n case Seq(a, b, c) =>\n if (canSwapWithCheck(a, c, b, b, b, b)) res += 1\n for (i <- ts.indices) if (canSwapWithCheck(b, i, a, c, a, a)) res += 1\n case Seq(a, b, c, d) =>\n if (canSwapWithCheck(a, c, b, d, a, a)) res += 1\n if (canSwapWithCheck(a, d, b, c, a, a)) res += 1\n if (canSwapWithCheck(b, c, a, d, a, a)) res += 1\n if (canSwapWithCheck(b, d, a, c, a, a)) res += 1\n case Seq(a, b, c, d, e) =>\n if (canSwapWithCheck(b, d, a, c, e, a)) res += 1\n if (canSwapWithCheck(b, e, a, c, d, a)) res += 1\n if (canSwapWithCheck(a, d, b, c, e, a)) res += 1\n case Seq(a, b, c, d, e, f) =>\n if (canSwapWithCheck(b, e, a, c, d, f)) res += 1\n case _ =>\n }\n\n println(res)\n}\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n\n def swap(arr: Array[Long], i: Int, j: Int) {\n val tmp = arr(i)\n arr(i) = arr(j)\n arr(j) = tmp\n }\n\n def isValid(data: Array[Long], i: Int) =\n if (i % 2 == 0)\n ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))\n else\n ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)\n\n def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {\n invalidIndices.count{ j =>\n swap(data, swapIndex, j)\n val res = isValid(data, swapIndex) && invalidIndices.forall(k => isValid(data, k))\n swap(data, swapIndex, j)\n res\n }\n }\n\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n if (n == 2)\n if (data(0) == data(1))\n println(0)\n else\n println(1)\n else {\n val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet\n if (invalid.size > 6)\n println(0)\n else {\n val res = data.indices.foldLeft(0l) {\n case (sum, i) if !invalid.contains(i) => sum + validChanges(data, invalid, i)\n case (sum, i) => sum\n }\n\n val doubles = invalid.toList.map(i => validChanges(data, invalid, i)).sum / 2\n println(res + doubles)\n }\n }\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n\n def swap(arr: Array[Long], i: Int, j: Int) {\n val tmp = arr(i)\n arr(i) = arr(j)\n arr(j) = tmp\n }\n\n def isValid(data: Array[Long], i: Int) =\n if (i % 2 == 0)\n ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))\n else\n ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)\n\n def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {\n invalidIndices.count{ j =>\n swap(data, swapIndex, j)\n val res = isValid(data, swapIndex) && invalidIndices.forall(k => isValid(data, k))\n swap(data, swapIndex, j)\n res\n }\n }\n\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n if (n == 2)\n if (data(0) == data(1))\n println(0)\n else \n println(1)\n else {\n val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet\n if (invalid.size > 6)\n println(0)\n else {\n val res = data.indices.foldLeft(0l) {\n case (sum, i) if !invalid.contains(i) => sum + validChanges(data, invalid, i)\n case (sum, i) => sum\n }\n\n val doubles = invalid.map(i => validChanges(data, invalid, i)).sum\n println(res + doubles)\n }\n }\n\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n\n def swap(arr: Array[Int], i: Int, j: Int) {\n val tmp = arr(i)\n arr(i) = arr(j)\n arr(j) = tmp\n }\n\n def isValid(data: Array[Int], i: Int) =\n if (i % 2 == 0)\n ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))\n else\n ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)\n\n def validChanges(data: Array[Int], invalidIndices: Iterable[Int], swapIndex: Int) = {\n invalidIndices.count{ j =>\n swap(data, swapIndex, j)\n val res = invalidIndices.forall(k => isValid(data, k))\n swap(data, swapIndex, j)\n res\n }\n }\n\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n if (n == 2)\n println(1)\n else {\n val invalid = data.indices.filterNot{i => isValid(data, i)}\n\n val res = data.indices.foldLeft(0) {\n case (sum, i) => sum + validChanges(data, invalid, i)\n }\n\n val doubles = invalid.indices.count(i => validChanges(data, invalid, i) != 0) / 2\n println(res - doubles)\n }\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n\n def swap(arr: Array[Long], i: Int, j: Int) {\n val tmp = arr(i)\n arr(i) = arr(j)\n arr(j) = tmp\n }\n\n def isValid(data: Array[Long], i: Int) =\n if (i % 2 == 0)\n ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))\n else\n ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)\n\n def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {\n invalidIndices.count{ j =>\n swap(data, swapIndex, j)\n val res = invalidIndices.forall(k => isValid(data, k))\n swap(data, swapIndex, j)\n swapIndex != j && res\n }\n }\n\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n if (n == 2)\n println(1)\n else {\n val invalid = data.indices.filterNot{i => isValid(data, i)}\n\n val res = data.indices.foldLeft(0l) {\n case (sum, i) => sum + validChanges(data, invalid, i)\n }\n// println(invalid)\n// println(res)\n\n val doubles = invalid.map(i => validChanges(data, invalid, i)).sum / 2\n// println(doubles)\n println(res - doubles)\n }\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n\n def swap(arr: Array[Int], i: Int, j: Int) {\n val tmp = arr(i)\n arr(i) = arr(j)\n arr(j) = tmp\n }\n\n def isValid(data: Array[Int], i: Int) =\n if (i % 2 == 0)\n ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))\n else\n ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)\n\n def validChanges(data: Array[Int], invalidIndices: Iterable[Int], swapIndex: Int) = {\n invalidIndices.count{ j =>\n swap(data, swapIndex, j)\n val res = invalidIndices.forall(k => isValid(data, k))\n swap(data, swapIndex, j)\n swapIndex != j && res\n }\n }\n\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n if (n == 2)\n println(1)\n else {\n val invalid = data.indices.filterNot{i => isValid(data, i)}\n\n val res = data.indices.foldLeft(0l) {\n case (sum, i) => sum + validChanges(data, invalid, i)\n }\n// println(invalid)\n// println(res)\n\n val doubles = invalid.map(i => validChanges(data, invalid, i)).sum / 2\n// println(doubles)\n println(res - doubles)\n }\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n\n def swap(arr: Array[Int], i: Int, j: Int) {\n val tmp = arr(i)\n arr(i) = arr(j)\n arr(j) = tmp\n }\n\n def isValid(data: Array[Int], i: Int) =\n if (i % 2 == 0)\n ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))\n else\n ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)\n\n def validChanges(data: Array[Int], invalidIndices: Iterable[Int], swapIndex: Int) = {\n invalidIndices.count{ j =>\n swap(data, swapIndex, j)\n val res = invalidIndices.forall(k => isValid(data, k))\n swap(data, swapIndex, j)\n swapIndex != j && res\n }\n }\n\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n if (n == 2)\n println(1)\n else {\n val invalid = data.indices.filterNot{i => isValid(data, i)}\n\n val res = data.indices.foldLeft(0) {\n case (sum, i) => sum + validChanges(data, invalid, i)\n }\n// println(invalid)\n// println(res)\n\n val doubles = invalid.map(i => validChanges(data, invalid, i)).sum / 2\n// println(doubles)\n println(res - doubles)\n }\n\n}"}, {"source_code": "//import scala.io.Source\n//\n//object Solution extends App {\n// val in = Source.stdin.getLines()\n// val n = in.next().toInt\n// val data = in.next().split(' ').map(_.toInt)\n// val indexValue = data.indices.foldLeft(Map.empty[Int, (Int, Int)]) {\n// case (acc, i) if !acc.contains(data(i)) =>\n// acc + (data(i) -> (i, 0))\n// case (acc, i) if acc(data(i))._2 == -1 => acc\n// case (acc, i) if acc(data(i))._2 == 0 =>\n// acc + (data(i) -> (i, i - acc(data(i))._1))\n// case (acc, i) =>\n// val distance = i - acc(data(i))._1\n// acc + (data(i) -> (i, if (acc(data(i))._2 == distance) distance else - 1))\n// }\n// println(indexValue.filter(_._2._2 >= 0).keys.toList.sorted.map{case v => s\"$v ${indexValue(v)._2}\"}.mkString(\"\\n\"))\n//\n//}ё\n\nimport scala.io.Source\n\nobject Solution extends App {\n\n def swap(arr: Array[Long], i: Int, j: Int) {\n val tmp = arr(i)\n arr(i) = arr(j)\n arr(j) = tmp\n }\n\n def isValid(data: Array[Long], i: Int) =\n if (i % 2 == 0)\n ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))\n else\n ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)\n\n def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {\n invalidIndices.count{ j =>\n swap(data, swapIndex, j)\n val res = isValid(data, swapIndex) && invalidIndices.forall(k => isValid(data, k))\n swap(data, swapIndex, j)\n res\n }\n }\n\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n if (n == 2)\n if (data(0) == data(1))\n println(0)\n else\n println(1)\n else {\n val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet\n if (invalid.size > 6)\n println(0)\n else {\n println(data.indices.foldLeft(0l) {\n case (sum, i) => sum + validChanges(data, invalid, i)\n } - 1)\n }\n }\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n\n def swap(arr: Array[Long], i: Int, j: Int) {\n val tmp = arr(i)\n arr(i) = arr(j)\n arr(j) = tmp\n }\n\n def isValid(data: Array[Long], i: Int) =\n if (i % 2 == 0)\n ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))\n else\n ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)\n\n def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {\n invalidIndices.count{ j =>\n swap(data, swapIndex, j)\n val res = isValid(data, swapIndex) && invalidIndices.forall(k => isValid(data, k))\n swap(data, swapIndex, j)\n res\n }\n }\n\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n if (n == 2)\n println(1)\n else {\n val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet\n if (invalid.size > 6)\n println(0)\n else {\n val res = data.indices.foldLeft(0l) {\n case (sum, i) if !invalid.contains(i) => sum + validChanges(data, invalid, i)\n case (sum, i) => sum\n }\n\n val doubles = invalid.map(i => validChanges(data, invalid, i)).sum\n println(res + doubles)\n }\n }\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n\n def swap(arr: Array[Int], i: Int, j: Int) {\n val tmp = arr(i)\n arr(i) = arr(j)\n arr(j) = tmp\n }\n\n def isValid(data: Array[Int], i: Int) =\n if (i % 2 == 0)\n ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))\n else\n ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)\n\n def validChanges(data: Array[Int], invalidIndices: Iterable[Int], swapIndex: Int) = {\n invalidIndices.count{ j =>\n swap(data, swapIndex, j)\n val res = invalidIndices.forall(k => isValid(data, k))\n swap(data, swapIndex, j)\n res\n }\n }\n\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n if (n == 2)\n println(1)\n else {\n val invalid = data.indices.filterNot{i => isValid(data, i)}\n\n val res = data.indices.foldLeft(0) {\n case (sum, i) => sum + validChanges(data, invalid, i)\n }\n\n val doubles = invalid.indices.map(i => validChanges(data, invalid, i)).sum / 2\n println(res - doubles)\n }\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n\n def swap(arr: Array[Long], i: Int, j: Int) {\n val tmp = arr(i)\n arr(i) = arr(j)\n arr(j) = tmp\n }\n\n def isValid(data: Array[Long], i: Int) =\n if (i % 2 == 0)\n ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))\n else\n ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)\n\n def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {\n invalidIndices.count{ j =>\n swap(data, swapIndex, j)\n val res = invalidIndices.forall(k => isValid(data, k))\n swap(data, swapIndex, j)\n swapIndex != j && res\n }\n }\n\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n if (n == 2)\n println(1)\n else {\n val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet\n\n val res = data.indices.foldLeft(0l) {\n case (sum, i) if !invalid.contains(i) => sum + validChanges(data, invalid, i)\n case (sum, i) => sum\n }\n// println(invalid)\n// println(res)\n\n val doubles = invalid.map(i => validChanges(data, invalid, i)).sum\n// println(doubles)\n println(res + doubles)\n }\n\n}"}, {"source_code": "\nimport scala.io.Source\n\nobject Solution extends App {\n\n def swap(arr: Array[Long], i: Int, j: Int) {\n val tmp = arr(i)\n arr(i) = arr(j)\n arr(j) = tmp\n }\n\n def isValid(data: Array[Long], i: Int) =\n if (i % 2 == 0)\n ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))\n else\n ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)\n\n def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {\n invalidIndices.count{ j =>\n swap(data, swapIndex, j)\n val res = isValid(data, swapIndex) && invalidIndices.forall(k => isValid(data, k))\n swap(data, swapIndex, j)\n res\n }\n }\n\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n if (n == 2)\n if (data(0) == data(1))\n println(0)\n else\n println(1)\n else {\n val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet\n if (invalid.size > 6)\n println(0)\n else {\n println(data.indices.foldLeft(0l) {\n case (sum, i) => sum + validChanges(data, invalid, i)\n })\n }\n }\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n\n def swap(arr: Array[Long], i: Int, j: Int) {\n val tmp = arr(i)\n arr(i) = arr(j)\n arr(j) = tmp\n }\n\n def isValid(data: Array[Long], i: Int) =\n if (i % 2 == 0)\n ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))\n else\n ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)\n\n def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int) = {\n invalidIndices.count{ j =>\n swap(data, swapIndex, j)\n val res = invalidIndices.forall(k => isValid(data, k))\n swap(data, swapIndex, j)\n swapIndex != j && res\n }\n }\n\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n if (n == 2)\n println(1)\n else {\n val invalid = data.indices.filterNot{i => isValid(data, i)}\n\n val res = data.indices.foldLeft(0l) {\n case (sum, i) => sum + validChanges(data, invalid, i)\n }\n// println(invalid)\n// println(res)\n\n val doubles = invalid.map(i => validChanges(data, invalid, i)).sum / 2\n// println(doubles)\n println(res - doubles)\n }\n\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuffer\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val ts = readInts(n)\n\n val errs = ArrayBuffer.empty[Int]\n\n def isValid(i: Int) = {\n val t = ts(i)\n if (i % 2 == 0) {\n !((i > 0 && t >= ts(i - 1)) || (i < n - 1 && t >= ts(i + 1)))\n } else {\n !((i > 0 && t <= ts(i - 1)) || (i < n - 1 && t <= ts(i + 1)))\n }\n }\n\n def canSwap(i: Int, j: Int) = {\n val ti = ts(i)\n val tj = ts(j)\n ts(i) = tj\n ts(j) = ti\n val can = isValid(i) && isValid(j)\n ts(i) = ti\n ts(j) = tj\n can\n }\n\n def canSwapWithCheck(i: Int, j: Int, u: Int, v: Int) = {\n val ti = ts(i)\n val tj = ts(j)\n ts(i) = tj\n ts(j) = ti\n val can = isValid(i) && isValid(j) && isValid(u) && isValid(v)\n ts(i) = ti\n ts(j) = tj\n can\n }\n\n for (i <- ts.indices) {\n if (!isValid(i)) errs += i\n }\n\n var res = 0L\n\n //println(errs)\n\n errs match {\n case Seq(a, b) =>\n for (i <- ts.indices) if (canSwap(a, i)) res += 1\n for (i <- ts.indices) if (i != a && canSwap(b, i)) res += 1\n case Seq(a, b, c) =>\n if (canSwap(a, c)) res += 1\n for (i <- ts.indices) if (canSwapWithCheck(b, i, a, c)) {\n //println(i)\n res += 1\n }\n case Seq(a, b, c, d) =>\n if (canSwapWithCheck(a, c, b, d)) res += 1 //{println(\"a\"); res += 1}\n if (canSwapWithCheck(a, d, b, c)) res += 1 //{println(\"a\"); res += 1}\n if (canSwapWithCheck(b, c, a, d)) res += 1 //{println(\"a\"); res += 1}\n if (canSwapWithCheck(b, d, a, c)) res += 1 //{println(\"a\"); res += 1}\n case _ =>\n }\n\n println(res)\n}\n"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuffer\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val ts = readInts(n)\n\n val errs = ArrayBuffer.empty[Int]\n\n def isValid(i: Int) = {\n val t = ts(i)\n if (i % 2 == 0) {\n !((i > 0 && t >= ts(i - 1)) || (i < n - 1 && t >= ts(i + 1)))\n } else {\n !((i > 0 && t <= ts(i - 1)) || (i < n - 1 && t <= ts(i + 1)))\n }\n }\n\n def canSwapWithCheck(i: Int, j: Int, u: Int, v: Int, z: Int, x: Int) = {\n val ti = ts(i)\n val tj = ts(j)\n ts(i) = tj\n ts(j) = ti\n val can = i != j && isValid(i) && isValid(j) && isValid(u) && isValid(v) && isValid(z) && isValid(x)\n ts(i) = ti\n ts(j) = tj\n can\n }\n\n for (i <- ts.indices) {\n if (!isValid(i)) errs += i\n }\n\n var res = 0L\n\n //println(errs)\n\n errs match {\n case Seq(a, b) =>\n for (i <- ts.indices) if (canSwapWithCheck(a, i, b, b, b, b)) res += 1\n for (i <- ts.indices) if (i != a && canSwapWithCheck(b, i, a, a, a, a)) res += 1\n case Seq(a, b, c) =>\n if (canSwapWithCheck(a, c, b, b, b, b)) res += 1\n for (i <- ts.indices) if (canSwapWithCheck(b, i, a, c, a, a)) {\n //println(i)\n res += 1\n }\n case Seq(a, b, c, d) =>\n if (canSwapWithCheck(a, c, b, d, a, a)) res += 1 //{println(\"a\"); res += 1}\n if (canSwapWithCheck(a, d, b, c, a, a)) res += 1 //{println(\"a\"); res += 1}\n if (canSwapWithCheck(b, c, a, d, a, a)) res += 1 //{println(\"a\"); res += 1}\n if (canSwapWithCheck(b, d, a, c, a, a)) res += 1 //{println(\"a\"); res += 1}\n case Seq(a, b, c, d, e) =>\n if (canSwapWithCheck(b, d, a, c, e, a)) res += 1\n case Seq(a, b, c, d, e, f) =>\n if (canSwapWithCheck(b, e, a, c, d, f)) res += 1\n case _ =>\n }\n\n println(res)\n}\n"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuffer\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val ts = readInts(n)\n\n val errs = ArrayBuffer.empty[Int]\n\n def isValid(i: Int) = {\n val t = ts(i)\n if (i % 2 == 0) {\n !((i > 0 && t >= ts(i - 1)) || (i < n - 1 && t >= ts(i + 1)))\n } else {\n !((i > 0 && t <= ts(i - 1)) || (i < n - 1 && t <= ts(i + 1)))\n }\n }\n\n def canSwap(i: Int, j: Int) = {\n val ti = ts(i)\n val tj = ts(j)\n ts(i) = tj\n ts(j) = ti\n val can = isValid(i) && isValid(j)\n ts(i) = ti\n ts(j) = tj\n can\n }\n\n for (i <- ts.indices) {\n if (!isValid(i)) errs += i\n }\n\n var res = 0L\n\n //println(errs)\n\n errs match {\n case Seq(a, b) =>\n for (i <- ts.indices) if (canSwap(a, i)) res += 1\n for (i <- ts.indices) if (i != a && canSwap(b, i)) res += 1\n case Seq(a, b, c) =>\n if (canSwap(a, c)) res += 1\n for (i <- ts.indices) if (canSwap(b, i)) {\n //println(i)\n res += 1\n }\n case Seq(a, b, c, d) =>\n if (canSwap(a, c)) res += 1 //{println(\"a\"); res += 1}\n if (canSwap(a, d)) res += 1 //{println(\"a\"); res += 1}\n if (canSwap(b, c)) res += 1 //{println(\"a\"); res += 1}\n if (canSwap(b, d)) res += 1 //{println(\"a\"); res += 1}\n case _ =>\n }\n\n println(res)\n}\n"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuffer\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val ts = readInts(n)\n\n val errs = ArrayBuffer.empty[Int]\n\n def isValid(i: Int) = {\n val t = ts(i)\n if (i % 2 == 0) {\n !((i > 0 && t >= ts(i - 1)) || (i < n - 1 && t >= ts(i + 1)))\n } else {\n !((i > 0 && t <= ts(i - 1)) || (i < n - 1 && t <= ts(i + 1)))\n }\n }\n\n def canSwap(i: Int, j: Int) = {\n val ti = ts(i)\n val tj = ts(j)\n ts(i) = tj\n ts(j) = ti\n val can = isValid(i) && isValid(j)\n ts(i) = ti\n ts(j) = tj\n can\n }\n\n def canSwapWithCheck(i: Int, j: Int, u: Int, v: Int) = {\n val ti = ts(i)\n val tj = ts(j)\n ts(i) = tj\n ts(j) = ti\n val can = isValid(i) && isValid(j) && isValid(u) && isValid(v)\n ts(i) = ti\n ts(j) = tj\n can\n }\n\n for (i <- ts.indices) {\n if (!isValid(i)) errs += i\n }\n\n var res = 0L\n\n //println(errs)\n\n errs match {\n case Seq(a, b) =>\n for (i <- ts.indices) if (canSwapWithCheck(a, i, b, b)) res += 1\n for (i <- ts.indices) if (i != a && canSwapWithCheck(b, i, a, a)) res += 1\n case Seq(a, b, c) =>\n if (canSwapWithCheck(a, c, b, b)) res += 1\n for (i <- ts.indices) if (canSwapWithCheck(b, i, a, c)) {\n //println(i)\n res += 1\n }\n case Seq(a, b, c, d) =>\n if (canSwapWithCheck(a, c, b, d)) res += 1 //{println(\"a\"); res += 1}\n if (canSwapWithCheck(a, d, b, c)) res += 1 //{println(\"a\"); res += 1}\n if (canSwapWithCheck(b, c, a, d)) res += 1 //{println(\"a\"); res += 1}\n if (canSwapWithCheck(b, d, a, c)) res += 1 //{println(\"a\"); res += 1}\n case _ =>\n }\n\n println(res)\n}\n"}], "src_uid": "e5b0e43beaca9baf428afec6ce454c50"} {"source_code": "import scala.collection.mutable\n\nobject F {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n val n, k = nextInt\n val as = nextInts(n).sorted\n\n val sumsL, sumsR = mutable.Map.empty[Int, Long].withDefaultValue(0)\n val counts, countsL, countsR = mutable.Map.empty[Int, Int].withDefaultValue(0)\n\n var prev = -1\n var sumL = 0L\n var sum = 0L\n var countL = 0\n var count = 0\n for (i <- 0 until n) {\n val a = as(i)\n if (a != prev) {\n sumL = count * (a - 1L) - sum\n countL = count\n }\n sumsL(a) = sumL\n countsL(a) = countL\n sum += a\n count += 1\n counts(a) += 1\n prev = a\n }\n\n prev = -1\n var sumR = 0L\n sum = 0L\n var countR = 0\n count = 0\n for (i <- n - 1 to 0 by -1) {\n val a = as(i)\n if (a != prev) {\n sumR = sum - count * (a + 1L)\n countR = count\n }\n sumsR(a) = sumR\n countsR(a) = countR\n sum += a\n count += 1\n prev = a\n }\n\n var min = Long.MaxValue\n for (a <- as) {\n val need = k - counts(a)\n var cost = 0L\n if (need > 0) {\n cost = Long.MaxValue\n val leftCost0 = sumsL(a) + Math.min(need, countsL(a))\n val rightCost0 = sumsR(a) + Math.min(need, countsR(a))\n if (countsL(a) >= need && leftCost0 < cost) cost = leftCost0\n if (countsR(a) >= need && rightCost0 < cost) cost = rightCost0\n if (cost == Long.MaxValue && countsL(a) + countsR(a) >= need) {\n val costLR = sumsL(a) + sumsR(a) + need\n if (costLR < cost) cost = costLR\n }\n }\n if (cost < min) min = cost\n }\n\n out.println(min)\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject F {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n val n, k = nextInt\n val as = nextInts(n).sorted\n\n val sumsL, sumsR = mutable.Map.empty[Int, Long].withDefaultValue(0L)\n val counts, countsL, countsR = mutable.Map.empty[Int, Int].withDefaultValue(0)\n\n var prev = -1\n var sum = 0L\n var count = 0\n for (i <- 0 until n) {\n val a = as(i)\n if (a != prev) {\n sumsL(a) = count * (a - 1L) - sum\n countsL(a) = count\n }\n sum += a\n count += 1\n counts(a) += 1\n prev = a\n }\n\n prev = -1\n sum = 0L\n count = 0\n for (i <- n - 1 to 0 by -1) {\n val a = as(i)\n if (a != prev) {\n sumsR(a) = sum - count * (a + 1L)\n countsR(a) = count\n }\n sum += a\n count += 1\n prev = a\n }\n\n var min = Long.MaxValue\n for (a <- as) {\n val need = k - counts(a)\n var cost = 0L\n if (need > 0) {\n cost = Long.MaxValue\n val leftCost0 = sumsL(a) + Math.min(need, countsL(a))\n val rightCost0 = sumsR(a) + Math.min(need, countsR(a))\n if (countsL(a) >= need && leftCost0 < cost) cost = leftCost0\n if (countsR(a) >= need && rightCost0 < cost) cost = rightCost0\n if (cost == Long.MaxValue && countsL(a) + countsR(a) >= need) {\n val costLR = sumsL(a) + sumsR(a) + need\n if (costLR < cost) cost = costLR\n }\n }\n if (cost < min) min = cost\n }\n\n out.println(min)\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject F {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n val n, k = nextInt\n val as = nextInts(n).sorted\n\n val sumsL, sumsR = mutable.Map.empty[Int, Long]\n val countsL, countsR = mutable.Map.empty[Int, Int]\n val counts = mutable.Map.empty[Int, Int].withDefaultValue(0)\n\n var prev = -1\n var sumL = 0L\n var sum = 0L\n var countL = 0\n var count = 0\n for (i <- 0 until n) {\n val a = as(i)\n if (a != prev) {\n sumL = count * (a - 1L) - sum\n countL = count\n }\n sumsL(a) = sumL\n countsL(a) = countL\n sum += a\n count += 1\n counts(a) += 1\n prev = a\n }\n\n prev = -1\n var sumR = 0L\n sum = 0L\n var countR = 0\n count = 0\n for (i <- n - 1 to 0 by -1) {\n val a = as(i)\n if (a != prev) {\n sumR = sum - count * (a + 1L)\n countR = count\n }\n sumsR(a) = sumR\n countsR(a) = countR\n sum += a\n count += 1\n prev = a\n }\n\n var min = Long.MaxValue\n for (a <- as) {\n val need = k - counts(a)\n var cost = 0L\n if (need > 0) {\n cost = Long.MaxValue\n val leftCost0 = sumsL(a) + Math.min(need, countsL(a))\n val rightCost0 = sumsR(a) + Math.min(need, countsR(a))\n if (countsL(a) >= need && leftCost0 < cost) cost = leftCost0\n if (countsR(a) >= need && rightCost0 < cost) cost = rightCost0\n if (cost == Long.MaxValue && countsL(a) + countsR(a) >= need) {\n val costLR = sumsL(a) + sumsR(a) + need\n if (costLR < cost) cost = costLR\n }\n }\n if (cost < min) min = cost\n }\n\n out.println(min)\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\nobject F {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n val n, k = nextInt\n val as = nextInts(n).sorted\n\n val sumsL, sumsR = mutable.Map.empty[Int, Long].withDefaultValue(0)\n val counts, countsL, countsR = mutable.Map.empty[Int, Int].withDefaultValue(0)\n\n var prev = -1\n var sumL = 0L\n var sum = 0L\n var countL = 0\n var count = 0\n for (i <- 0 until n) {\n val a = as(i)\n if (a != prev) {\n sumL = count * (a - 1) - sum\n countL = count\n }\n sumsL(a) = sumL\n countsL(a) = countL\n sum += a\n count += 1\n counts(a) += 1\n prev = a\n }\n\n prev = -1\n var sumR = 0L\n sum = 0L\n var countR = 0\n count = 0\n for (i <- n - 1 to 0 by -1) {\n val a = as(i)\n if (a != prev) {\n sumR = sum - count * (a + 1)\n countR = count\n }\n sumsR(a) = sumR\n countsR(a) = countR\n sum += a\n count += 1\n prev = a\n }\n\n var min = Long.MaxValue\n for (a <- as) {\n val need = k - counts(a)\n var cost = 0L\n if (need > 0) {\n cost = Long.MaxValue\n val leftCost0 = sumsL(a) + Math.min(need, countsL(a))\n val rightCost0 = sumsR(a) + Math.min(need, countsR(a))\n if (countsL(a) >= need && leftCost0 < cost) cost = leftCost0\n if (countsR(a) >= need && rightCost0 < cost) cost = rightCost0\n if (cost == Long.MaxValue && countsL(a) + countsR(a) >= need) {\n val costLR = sumsL(a) + sumsR(a) + need\n if (costLR < cost) cost = costLR\n }\n }\n if (cost < min) min = cost\n }\n\n out.println(min)\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject F {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n val n, k = nextInt\n val as = nextInts(n).sorted\n //val ds = as.distinct\n\n val sumsL, sumsR = Array.ofDim[Long](n)\n val countsL, countsR, lefts, rights = Array.ofDim[Int](n)\n val counts = mutable.Map.empty[Int, Int].withDefaultValue(0)\n\n var prev = -1\n var sumL = 0L\n var sum = 0L\n var countL = 0\n var count = 0\n var left = -1\n for (i <- 0 until n) {\n if (as(i) != prev) {\n sumL = count * as(i) - sum\n countL = count\n left = i - 1\n }\n lefts(i) = left\n sumsL(i) = sumL\n countsL(i) = countL\n sum += as(i)\n count += 1\n counts(as(i)) += 1\n prev = as(i)\n }\n\n prev = -1\n var sumR = 0L\n sum = 0L\n var countR = 0\n count = 0\n var right = n\n for (i <- n - 1 to 0 by -1) {\n if (as(i) != prev) {\n sumR = sum - count * as(i)\n countR = count\n right = i + 1\n }\n rights(i) = right\n sumsR(i) = sumR\n countsR(i) = countR\n sum += as(i)\n count += 1\n prev = as(i)\n }\n\n var min = Long.MaxValue\n//println(as.mkString(\" \"))\n// println(countsR.mkString(\" \"))\n// println(sumsR.mkString(\" \"))\n// println(counts)\n for (i <- 0 until n) {\n val need = k - counts(as(i))\n var cost = 0L\n if (need > 0) {\n cost = Long.MaxValue\n val l = lefts(i)\n val r = rights(i)\n val leftCost0 = if (l >= 0) sumsL(l) + Math.min(need, countsL(i)) else Long.MaxValue\n val rightCost0 = if (r < n) sumsR(r) + Math.min(need, countsR(i)) else Long.MaxValue\n if (countsL(i) >= need && leftCost0 < cost) cost = leftCost0\n if (countsR(i) >= need && rightCost0 < cost) cost = rightCost0\n if (cost == Long.MaxValue && countsL(i) + countsR(i) >= need && l >= 0 && r < n) {\n val costLR = sumsL(l) + sumsR(r) + need\n if (costLR < cost) cost = costLR\n }\n }\n if (cost < min) min = cost\n }\n\n out.println(min)\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject F {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n val n, k = nextInt\n val as = nextInts(n).sorted\n //val ds = as.distinct\n\n val sumsL, sumsR = Array.ofDim[Long](n)\n val countsL, countsR, lefts, rights = Array.ofDim[Int](n)\n val counts = mutable.Map.empty[Int, Int].withDefaultValue(0)\n\n var prev = -1\n var sumL = 0L\n var sum = 0L\n var countL = 0\n var count = 0\n var left = -1\n for (i <- 0 until n) {\n if (as(i) != prev) {\n sumL = count * as(i) - sum\n countL = count\n left = i - 1\n }\n lefts(i) = left\n sumsL(i) = sumL\n countsL(i) = countL\n sum += as(i)\n count += 1\n counts(as(i)) += 1\n prev = as(i)\n }\n\n prev = -1\n var sumR = 0L\n sum = 0L\n var countR = 0\n count = 0\n var right = n\n for (i <- n - 1 to 0 by -1) {\n if (as(i) != prev) {\n sumR = sum - count * as(i)\n countR = count\n right = i + 1\n }\n rights(i) = right\n sumsR(i) = sumR\n countsR(i) = countR\n sum += as(i)\n count += 1\n prev = as(i)\n }\n\n var min = Long.MaxValue\n//println(as.mkString(\" \"))\n// println(countsR.mkString(\" \"))\n// println(sumsR.mkString(\" \"))\n// println(counts)\n for (i <- 0 until n) {\n val need = k - counts(as(i))\n var cost = 0L\n if (need > 0) {\n cost = Long.MaxValue\n val l = lefts(i)\n val r = rights(i)\n val leftCost0 = if (l >= 0) sumsL(l) + Math.min(need, countsL(i)) else Long.MaxValue\n val rightCost0 = if (r < n) sumsR(r) + Math.min(need, countsR(i)) else Long.MaxValue\n if (countsL(i) >= need && leftCost0 < cost) cost = leftCost0\n if (countsR(i) >= need && rightCost0 < cost) cost = rightCost0\n if (cost == Long.MaxValue && countsL(i) + countsR(i) >= need && l >= 0 && r < n) {\n val costLR = sumsL(l) + sumsR(r) + need\n if (costLR < cost) cost = costLR\n }\n }\n if (cost < min) min = cost\n }\n\n out.println(min)\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "src_uid": "fc4d0f2d4dfc97484dbbafb3f2aee362"} {"source_code": "import java.util.Date\n\nobject task2 {\n def main(args: Array[String]) {\n val len = readLine().split(\" \").map(_.toInt)\n\n val a = readLine().split(\" \").map(_.toLong).sorted\n val b = readLine().split(\" \").map(_.toLong)\n\n val res = b.map { bj =>\n val bb = findMoreThenEl(a, bj)\n if(bb != -1) bb else len(0)\n }.mkString(\" \")\n println(res)\n }\n\n def findMoreThenEl(list: Array[Long], el: Long): Int = {\n def inner(from: Int, to: Int): Int = {\n val len = to - from\n val newCenter = from + (len / 2)\n if (len <= 1 && list(from) <= el && list(to) <= el) {\n -1\n }\n else if (len <= 1 && list(from) > el) {\n from\n } else if (len <= 1 && list(to) > el) {\n to\n }\n else if (list(newCenter) <= el) {\n inner(newCenter, to)\n }\n else {\n inner(from, newCenter)\n }\n }\n\n inner(0, list.length - 1)\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toInt).sorted\n val b = in.next().split(' ').map(_.toInt)\n val map = mutable.Map.empty[Int, Long]\n var sum = 0l\n var startIndex = 0\n b.sorted.foreach { i =>\n while (startIndex < a.length && a(startIndex) <= i) {\n startIndex += 1\n sum += 1\n }\n map += (i -> sum)\n }\n println(b.map(map).mkString(\" \"))\n}"}, {"source_code": "import java.util.Date\n\nobject task2 {\n def main(args: Array[String]) {\n val len = readLine().split(\" \").map(_.toInt)\n\n val a = readLine().split(\" \").map(_.toLong).sorted\n val b = readLine().split(\" \").map(_.toLong)\n\n val res = b.map { bj =>\n\n val bb = if(a(0)>bj) 0\n else if(a(len(0)-1)<=bj) len(0)\n else findMoreThenEl(a, bj)\n if(bb != -1) bb else len(0)\n }.mkString(\" \")\n println(res)\n }\n\n def findMoreThenEl(list: Array[Long], el: Long): Int = {\n def inner(from: Int, to: Int): Int = {\n val len = to - from\n val newCenter = from + (len / 2)\n if (len <= 1 && list(from) <= el && list(to) <= el) {\n -1\n }\n else if (len <= 1 && list(from) > el) {\n from\n } else if (len <= 1 && list(to) > el) {\n to\n }\n else if (list(newCenter) <= el) {\n inner(newCenter, to)\n }\n else {\n inner(from, newCenter)\n }\n }\n\n inner(0, list.length - 1)\n }\n}\n"}, {"source_code": "object B600 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val a = readInts(n).sorted\n val b = readInts(m)\n var res = 0\n\n for(i <- 0 until m) {\n var low = 0\n var high = n - 1\n\n while(low < high) {\n val mid = low + (high - low + 1)/2\n\n if(a(mid) > b(i))\n high = mid - 1\n else\n low = mid\n }\n if(a(low) <= b(i))\n out.print(s\"${low+1} \")\n else\n out.print(\"0 \")\n }\n\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}"}], "negative_code": [{"source_code": "object B600 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val a = readInts(n).sorted\n val b = readInts(m)\n var res = 0\n\n for(i <- 0 until m) {\n var low = 0\n var high = n - 1\n\n while(low < high) {\n val mid = low + (high - low + 1)/2\n\n if(a(mid) > b(i))\n high = mid - 1\n else\n low = mid\n }\n\n out.print(s\"${low+1} \")\n }\n\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}"}, {"source_code": "object task2 {\n def main (args: Array[String]){\n val len = readLine().split(\" \")\n val a = readLine().split(\" \")\n val b = readLine().split(\" \")\n\n val res = b.map{bj =>a.count(ai=>ai<=bj)}.mkString(\" \")\n\n println(res)\n }\n}\n"}], "src_uid": "e9a519be33f25c828bae787330c18dd4"} {"source_code": "object A608 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, s) = readInts(2)\n val in = Array.fill(n)(readInts(2)).map(arr => (arr(0), arr(1))).sorted.reverse\n var t = 0\n var curr = s\n for(i <- 0 until n) {\n if(in(i)._1 < curr) {\n t += (curr - in(i)._1)\n curr = in(i)._1\n }\n if(in(i)._2 > t) {\n t = in(i)._2\n }\n }\n t += curr\n println(t)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val s = sc.nextInt()\n\n var f = new Array[Int](n)\n var t = new Array[Int](n)\n for(i <- 0 until n){\n f(i) = sc.nextInt()\n t(i) = sc.nextInt()\n }\n\n //\n var tul = new Array[(Int, Int)](n + 1)\n tul(n) = (0, 0)\n\n for(i <- 0 until n)\n tul(i) = (f(i), t(i))\n\n tul = tul.sorted.reverse\n tul(n) = (10000, 100000)\n\n var ans = -1\n var man = 0\n for(i <- (0 to s).reverse){\n ans += 1\n if(man < n)\n if(tul(man)._1 == i){\n while(tul(man)._1 == i){\n ans = Math.max(ans, tul(man)._2)\n man += 1\n }\n }\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject A_336 { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n val line1 = readLine\n val n = line1.int\n val s = line1.int\n \n var max = s\n \n for (i <- 0 until n) {\n val line = readLine\n val sum = line.int + line.int\n if (max < sum) {\n max = sum\n }\n }\n //---------------------------- parameters reading end ----------------------\n \n println(max)\n\n }\n\n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n }\n \n var debugV = false\n var is = System.in\n val br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n\n}\n\n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n\n\"\"\"\n\n}"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by hsleep on 2016. 1. 8..\n */\nobject ASolution extends App {\n val Array(numOfPassenger, numOfFloor) = StdIn.readLine().split(' ').map(_.toInt)\n val waitForPassenger = (0 until numOfPassenger).map { _ => StdIn.readLine().split(' ').map(_.toInt).sum }.max\n\n val output = math.max(numOfFloor, waitForPassenger)\n println(output)\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, s) = in.next().split(' ').map(_.toInt)\n val res = (1 to n).foldLeft(s) {\n case (acc, _) =>\n val Array(f, t) = in.next().split(' ').map(_.toInt)\n Math.max(acc, t + f)\n }\n println(res)\n}"}, {"source_code": "import java.util.Scanner\n\nobject CF1 {\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val s = sc.nextInt()\n val f = new Array[Int](n)\n val t = new Array[Int](n)\n var i = 0;\n while (i < n) {\n f(i) = sc.nextInt()\n t(i) = sc.nextInt()\n i += 1;\n }\n var maxF = f(0)\n var maxT = t(0)\n var max = t(0) - (s - f(0))\n i = 1\n while (i < n) {\n val tmp = t(i) - (s - f(i))\n if (tmp > max) {\n maxF = f(i)\n maxT = t(i)\n max = tmp\n }\n i += 1\n }\n if (max >= 0) System.out.print(maxF + maxT) else System.out.print(s)\n System.out.flush();\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.math.max\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n def next = scanner.next.toInt\n def nextPairs(n: Int) = 0.until(n).map(_ => (next, next)) // floor, time\n\n val n = next\n\n println(measureTrip(n, next, nextPairs(n)))\n }\n\n def measureTrip(peopleCount: Int, topFloor: Int, people: IndexedSeq[(Int, Int)]) = {\n val maxDelay = people.foldLeft(0)( (a: Int, p: (Int, Int)) => max(a, max(0, p._1 - (topFloor - p._2))) )\n topFloor + maxDelay\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, s) = in.next().split(' ').map(_.toInt)\n val res = (1 to n).foldLeft(0) {\n case (acc, _) =>\n val Array(f, t) = in.next().split(' ').map(_.toInt)\n Math.max(acc, t + f)\n }\n println(res)\n}"}, {"source_code": "import java.util.Scanner\n\nobject CF1 {\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val s = sc.nextInt()\n val f = new Array[Int](n)\n val t = new Array[Int](n)\n var i = 0;\n while (i < n) {\n f(i) = sc.nextInt()\n t(i) = sc.nextInt()\n i += 1;\n }\n var maxF = f(0)\n var maxT = t(0)\n var max = t(0) - (s - f(0));\n i = 1;\n while (i < n) {\n val tmp = t(i) - (s - f(i))\n if (tmp > max) {\n maxF = f(i);\n maxT = t(i);\n max = tmp;\n }\n i += 1;\n }\n System.out.print(maxF + maxT);\n System.out.flush();\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val s = sc.nextInt()\n\n var f = new Array[Int](n)\n var t = new Array[Int](n)\n for(i <- 0 until n){\n f(i) = sc.nextInt()\n t(i) = sc.nextInt()\n }\n\n //\n var tul = new Array[(Int, Int)](n)\n for(i <- 0 until n)\n tul(i) = (f(i), t(i))\n\n tul = tul.sorted.reverse\n\n var ans = -1\n var man = 0\n for(i <- (0 to s).reverse){\n ans += 1\n if(man < n)\n if(tul(man)._1 == i){\n ans = Math.max(ans, tul(man)._2)\n man += 1\n }\n }\n\n println(ans)\n }\n}\n"}], "src_uid": "5c12573b3964ee30af0349c11c0ced3b"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n class Zipper {\n type A = Long\n var gen = 0\n val id = mutable.HashMap[A, Int]()\n var len = 0\n\n def get(x: A): Int = {\n id.getOrElseUpdate(x, {\n val i = gen\n gen += 1\n len += 1\n i\n })\n }\n }\n\n def solve(): Unit = {\n val NN = 1.2e6.toInt\n\n val N = ni()\n val A = na(N)\n val cum = cumSum(A)\n debug(cum)\n\n // [l, r)\n case class Range(l: Int, r: Int)\n\n val zip = new Zipper\n val G = Array.ofDim[Array[Range]](NN)\n val C = Array.ofDim[Int](NN)\n REP_r(N, 1) { r =>\n TO(0, r - 1) { l =>\n val v = cum(r) - cum(l)\n val id = zip.get(v)\n C(id) = C(id) + 1\n }\n }\n REP(zip.len) { i =>\n G(i) = Array.ofDim(C(i))\n }\n\n // 作るときにR順になるようにする。idを振るのが逆順なのでRを逆順でループする\n REP_r(N, 1) { r =>\n // Lはどうでもいい\n TO(0, r - 1) { l =>\n val v = cum(r) - cum(l)\n val id = zip.get(v)\n C(id) -= 1\n val i = C(id)\n G(id)(i) = Range(l, r)\n }\n }\n\n DEBUG {\n REP(zip.len) { i =>\n debug(G(i).mkString(\",\"))\n }\n }\n\n var ans, res: Array[Range] = Array.ofDim[Range](1.2e6.toInt)\n var len = 0\n var ptr = 0\n\n REP(zip.len) { i =>\n val as = G(i)\n ptr = 0\n var r = 0\n REP(as.length) { i =>\n if (as(i).l >= r) {\n res(ptr) = as(i)\n ptr += 1\n r = as(i).r\n }\n }\n\n// debug(s\"dump res v:$v\")\n// debug(res.mkString(\",\"))\n\n if (ans == null || ptr > len) {\n len = ptr\n val tmp = ans\n ans = res\n res = tmp\n }\n }\n\n out.println(len)\n REP(len) { i =>\n val rg = ans(i)\n out.println(s\"${rg.l+1} ${rg.r}\")\n }\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val cum = cumSum(A)\n debug(cum)\n\n // [l, r)\n case class Range(l: Int, r: Int)\n\n val G = mutable.HashMap[Long, Array[Range]]()\n val C = mutable.HashMap[Long, Int]().withDefaultValue(0)\n REP(N) { l =>\n TO(l + 1, N) { r =>\n val v = cum(r) - cum(l)\n C(v) = C(v) + 1\n }\n }\n C.keys.foreach { v =>\n G(v) = Array.ofDim(C(v))\n }\n REP(N) { l =>\n TO(l + 1, N) { r =>\n val v = cum(r) - cum(l)\n val id = C(v) - 1\n C(v) = id\n G(v)(id) = Range(l, r)\n }\n }\n\n DEBUG {\n G.foreach { case (v, as) =>\n debug(s\"A v:$v\")\n debug(as.mkString(\",\"))\n }\n }\n\n var ans: ArrayBuffer[Range] = null\n G.foreach { case (v, as) =>\n import java.util\n import java.util.Comparator\n val res = ArrayBuffer[Range]()\n util.Arrays.sort(as, new Comparator[Range] {\n override def compare(o1: Range, o2: Range): Int = Integer.compare(o1.r, o2.r) // 終端で昇順ソートする\n })\n\n var r = 0\n REP(as.length) { i =>\n if (as(i).l >= r) {\n res += as(i)\n r = as(i).r\n }\n }\n\n debug(s\"dump res v:$v\")\n debug(res.mkString(\",\"))\n\n if (ans == null || res.length > ans.length) ans = res\n }\n\n out.println(ans.length)\n REP(ans.length) { i =>\n val rg = ans(i)\n out.println(s\"${rg.l+1} ${rg.r}\")\n }\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}], "negative_code": [], "src_uid": "3e834f89ecedc5f210e680f24e40ba19"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = 1e6.toInt\n val C = Array.ofDim[Int](N, 4)\n\n def len(i: Long) = i.toString.count(_ != '0')\n\n REP(N) { i =>\n if (i == 0) C(0)(0) = 1\n else {\n REP(4) { j =>\n C(i)(j) = C(i - 1)(j)\n }\n\n val cnt = i.toString.count(_ != '0')\n if (cnt <= 3) C(i)(cnt) += 1\n }\n }\n \n def cnt(x: Long): Long = {\n if (x < N) {\n C(x.toInt).sum\n\n } else if (x >= N && x < 1e12.toLong) {\n val q = (x / N).toInt\n val m = (x % N).toInt\n\n var res = 0L\n\n // 10^6以降の値が固定の場合、10^6以下の値も制限される\n REP(4 - len(q)) { i =>\n res += C(m)(i)\n }\n\n // x-1 以下のの場合は10^6以下が自由になる\n REP(4) { i =>\n REP(4 - i) { j =>\n res += C(q - 1)(i).toLong * C(N - 1)(j)\n }\n }\n\n res\n\n } else {\n val q = (x / N / N).toInt\n val m1 = (x / N % N).toInt\n val m2 = (x % N).toInt\n\n var res = 0L\n\n // 10^12以降の値が固定の場合、10^12以下の値も制限される\n val i = len(q)\n val j = len(m1)\n REP(4 - (j + i)) { k =>\n res += C(m2)(k)\n }\n\n if (m1 > 0) {\n REP(4 - i) { j =>\n REP(4 - (j + i)) { k =>\n res += C(m1 - 1)(j) * C(N - 1)(k)\n }\n }\n }\n\n // x-1 以下のの場合は10^6以下が自由になる\n REP(4) { i =>\n REP(4 - i) { j =>\n REP(4 - (j + i)) { k =>\n res += C(q - 1)(i).toLong * C(N - 1)(j) * C(N - 1)(k)\n }\n }\n }\n\n res\n }\n }\n \n REP(ni()) { _ =>\n val l, r = nl()\n val ans = cnt(r) - cnt(l - 1)\n out.println(ans)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val T = ni()\n rep(T) { _ =>\n val l, r = nl()\n val ans = f(r.toString.toCharArray) - f((l - 1).toString.toCharArray)\n out.println(ans)\n }\n }\n\n def f(D: Array[Char]): Int = {\n val N: Int = D.length\n val memo = Array.fill[Int](N, 4)(-1)\n def g(i: Int, k: Int, f: Boolean): Int = {\n if (k < 0) 0\n else if (i == N) 1\n else {\n if (f && memo(i)(k) != -1) {\n memo(i)(k)\n } else {\n var res = 0\n val d = if (f) 9 else D(i) - '0'\n rep(d + 1) { j =>\n val newF = f || j < d\n val newK = if (j == 0) k else k - 1 // 0以外の時kの値を減らす\n res += g(i + 1, newK, newF)\n }\n if (f) memo(i)(k) = res\n res\n }\n }\n }\n\n g(0, 3, f = false)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val T = ni()\n rep(T) { _ =>\n val l, r = nl()\n val ans = f(r) - f(l - 1)\n out.println(ans)\n }\n }\n\n val pow10 = Array.ofDim[Long](19)\n pow10(0) = 1\n rep(18)(i => pow10(i + 1) = pow10(i) * 10)\n\n /**\n * @return (log10の整数値, 最大桁の値)\n */\n def log10(x: Long): (Int, Int) = {\n var a = x\n var i = 0\n while(a >= 10) {\n a /= 10\n i += 1\n }\n (i, a.toInt)\n }\n\n def f(x: Long): Int = {\n val (n, _) = log10(x)\n val N = n + 1\n val dp = Array.ofDim[Int](N + 1, 2, 4)\n dp(0)(0)(3) = 1\n\n rep(N) { i =>\n val D = (x / pow10(n - i) % 10).toInt\n rep(2) { f =>\n rep(4) { k =>\n val d = if (f == 1) 9 else D\n rep(d + 1) { j =>\n val newF = f | (if(j < d) 1 else 0)\n val newK = if (j == 0) k else k - 1\n if (newK >= 0) dp(i + 1)(newF)(newK) += dp(i)(f)(k)\n }\n }\n }\n }\n\n var res = 0\n rep(2) { f =>\n rep(4) { k =>\n res += dp(N)(f)(k)\n }\n }\n res\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val T = ni()\n rep(T) { _ =>\n val l, r = nl()\n val ans = f(r.toString.toCharArray) - f((l - 1).toString.toCharArray)\n out.println(ans)\n }\n }\n\n def f(D: Array[Char]): Int = {\n val N = D.length\n val dp = Array.ofDim[Int](N + 1, 2, 4)\n dp(0)(0)(3) = 1\n\n rep(N) { i =>\n rep(2) { f =>\n rep(4) { k =>\n val d = if (f == 1) 9 else D(i) - '0'\n rep(d + 1) { j =>\n val newF = f | (if(j < d) 1 else 0)\n val newK = if (j == 0) k else k - 1\n if (newK >= 0) dp(i + 1)(newF)(newK) += dp(i)(f)(k)\n }\n }\n }\n }\n\n var res = 0\n rep(2) { f =>\n rep(4) { k =>\n res += dp(N)(f)(k)\n }\n }\n res\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "object ClassyNumbers {\n\n def main(args: Array[String]): Unit = {\n println {\n (for (_ <- 1 to io.StdIn.readInt()) yield {\n val Array(l, r) = io.StdIn.readLine().split(\" \").map(_.toLong)\n\n val Classy = 4\n\n def solve(digits: Seq[Int]): Int = {\n\n val Idx = digits.size\n\n val dp = Array.fill[Option[Int]](Idx, Classy, 2)(None)\n\n def loop(idx: Int, flag: Boolean, classy: Int): Int = {\n\n if (classy == Classy)\n 0\n else if (idx == Idx)\n 1\n else\n dp(idx)(classy)(if (flag) 1 else 0).getOrElse {\n val res: Int = (1 to (if (flag) digits(idx) else 9))\n .foldLeft(0)(\n (acc, i) =>\n acc + loop(idx + 1, flag && i == digits(idx), classy + 1)\n ) + loop(idx + 1, flag && 0 == digits(idx), classy)\n\n dp(idx)(classy)(if (flag) 1 else 0) = Some(res)\n res\n }\n }\n\n loop(0, flag = true, 0)\n }\n\n val lDigits = (l - 1).toString.map(_ - '0')\n val rDigits = r.toString.map(_ - '0')\n\n solve(rDigits) - solve(lDigits)\n\n }).mkString(\"\\n\")\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = 1e6.toInt\n val C = Array.ofDim[Int](N, 4)\n\n def len(i: Long) = i.toString.count(_ != '0')\n\n REP(N) { i =>\n if (i == 0) C(0)(0) = 1\n else {\n REP(4) { j =>\n C(i)(j) = C(i - 1)(j)\n }\n\n val cnt = i.toString.count(_ != '0')\n if (cnt <= 3) C(i)(cnt) += 1\n }\n }\n \n def cnt(x: Long): Long = {\n if (x < N) {\n C(x.toInt).sum\n\n } else if (x >= N && x < 1e12.toLong) {\n val q = (x / N).toInt\n val m = (x % N).toInt\n\n var res = 0L\n\n // 10^6以降の値が固定の場合、10^6以下の値も制限される\n REP(4 - len(q)) { i =>\n res += C(m)(i)\n }\n\n // x-1 以下のの場合は10^6以下が自由になる\n REP(4) { i =>\n REP(4 - i) { j =>\n res += C(q - 1)(i).toLong * C(N - 1)(j)\n }\n }\n\n res\n\n } else {\n val q = (x / N / N).toInt\n val m1 = (x / N % N).toInt\n val m2 = (x % N).toInt\n\n var res = 0L\n\n // 10^6以降の値が固定の場合、10^6以下の値も制限される\n val i = len(q)\n REP(4 - i) { j =>\n REP(4 - (j + i)) { k =>\n res += C(m1)(j).toLong * C(m2)(k)\n }\n }\n\n // x-1 以下のの場合は10^6以下が自由になる\n REP(4) { i =>\n REP(4 - i) { j =>\n REP(4 - (j + i)) { k =>\n res += C(q - 1)(i).toLong * C(N - 1)(j) * C(N - 1)(k)\n }\n }\n }\n\n res\n }\n }\n \n REP(ni()) { _ =>\n val l, r = nl()\n val ans = cnt(r) - cnt(l - 1)\n out.println(ans)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = 1e6.toInt\n val C = Array.ofDim[Int](N, 4)\n\n def len(i: Long) = i.toString.count(_ != '0')\n\n REP(N) { i =>\n if (i == 0) C(0)(0) = 1\n else {\n REP(4) { j =>\n C(i)(j) = C(i - 1)(j)\n }\n\n val cnt = i.toString.count(_ != '0')\n if (cnt <= 3) C(i)(cnt) += 1\n }\n }\n \n def cnt(x: Long): Long = {\n if (x < N) {\n C(x.toInt).sum\n\n } else if (x >= N && x < 1e12.toLong) {\n val q = (x / N).toInt\n val m = (x % N).toInt\n\n var res = 0L\n\n // 10^6以降の値が固定の場合、10^6以下の値も制限される\n REP(4 - len(q)) { i =>\n res += C(m)(i)\n }\n\n // x-1 以下のの場合は10^6以下が自由になる\n REP(4) { i =>\n REP(4 - i) { j =>\n res += C(q - 1)(i).toLong * C(N - 1)(j)\n }\n }\n\n res\n\n } else {\n val q = (x / N / N).toInt\n val m1 = (x / N % N).toInt\n val m2 = (x % N).toInt\n\n var res = 0L\n\n // 10^6以降の値が固定の場合、10^6以下の値も制限される\n REP(4 - len(q)) { i =>\n REP(4 - i) { j =>\n res += C(m1)(i).toLong * C(m2)(j)\n }\n }\n\n // x-1 以下のの場合は10^6以下が自由になる\n REP(4) { i =>\n REP(4 - i) { j =>\n REP(4 - j) { k =>\n res += C(q - 1)(i).toLong * C(N - 1)(j) * C(N - 1)(k)\n }\n }\n }\n\n res\n }\n }\n \n REP(ni()) { _ =>\n val l, r = nl()\n val ans = cnt(r) - cnt(l - 1)\n out.println(ans)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "993f96a62a2ba75a12684b75a5b2f1ed"} {"source_code": "import io.StdIn._\nimport scala.collection.mutable._\n\nobject Solution {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n def main(args: Array[String]) {\n val Array(n, p) = readInts(2)\n val a = Array.fill[Double](n)(0)\n\n (1 to n).foreach { i =>\n val Array(l, r) = readInts(2)\n a(i-1) = (r / p - (l - 1) / p).toDouble / (r - l + 1)\n }\n\n var res: Double = 0\n for (i <- 0 to n-1) {\n res += 2000 * a(i)\n if (i == 0) res += 1000 * (1 - a(i)) * (a(i+1) + a(n-1))\n else if (i == n-1) res += 1000* (1 - a(i)) * (a(0) + a(i-1))\n else res += 1000* (1 - a(i)) * (a(i-1) + a(i+1))\n }\n\n println(res)\n\n// Console.withOut(new java.io.BufferedOutputStream(Console.out))\n// println(res.mkString(\"\\n\"))\n// Console.flush\n }\n}", "positive_code": [{"source_code": "\n/**\n * Created by octavian on 01/02/2016.\n */\nobject Flowers {\n\n val GIVES = 2 * 1000\n\n def main(args: Array[String]) {\n //System.setIn(new FileInputStream(\"./src/flowers.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"./src/flowers.out\")))\n\n val Array(n, p) = readLine.split(\" \").map(_.toInt)\n var notProb = Vector.empty[Double]\n\n for(i <- 0 until n) {\n val Array(a, b) = readLine.split(\" \").map(_.toInt)\n val div = b/p - (a - 1)/p\n //println(\"notDiv is: \" + notDiv)\n notProb :+= (b - a + 1 - div).toDouble/(b - a + 1)\n }\n\n var result: BigDecimal = 0.0\n for(i <- 0 until n) {\n result += GIVES * (1 - notProb(i) * notProb((i + 1)%n))\n }\n\n println(result)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n final val V = 1000\n def main(args: Array[String]) {\n val Array(n, p) = StdIn.readLine().split(\" \").map(_.toInt)\n val a = Array.fill(n)(0.0)\n for (i <- 0 until n) {\n val Array(l, r) = StdIn.readLine().split(\" \").map(_.toInt)\n a(i) = (r / p - (l - 1) / p).toDouble / (r - l + 1).toDouble\n }\n var ans = 0.0\n for (i <- 0 until n) {\n ans += 1000 * (1 - (1 - a((i + n - 1) % n)) * (1 - a(i)))\n ans += 1000 * (1 - (1 - a(i)) * (1 - a((i + 1) % n)))\n }\n println(ans)\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ListBuffer\n\nobject C {\n def main(args: Array[String]) {\n val Array(n, p) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val P = (1 to n).map(x => {\n val q = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val c2 = q(1) / p\n val c1 = (q(0)-1) / p\n 1.0 - 1.0 * (c2-c1)/(q(1) - q(0)+1)\n })\n\n println((1 to n).map(i => 1.0 - P(i%n)*P((i+1)%n)).sum * 2000)\n }\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, p) = readInts(2)\n val ls, rs = Array.ofDim[Int](n + 1)\n \n for (i <- 0 until n) {\n val Array(l, r) = readInts(2)\n ls(i) = l\n rs(i) = r\n }\n ls(n) = ls(0)\n rs(n) = rs(0)\n \n var res = 0d\n \n for (i <- 0 until n) {\n val j = if (i == 0) n - 1 else i - 1\n val cnt0 = rs(j) / p - (ls(j) - 1) / p\n val cnt1 = rs(i) / p - (ls(i) - 1) / p\n val cnt2 = rs(i + 1) / p - (ls(i + 1) - 1) / p\n val prob0 = cnt0.toDouble / (rs(j) - ls(j) + 1)\n val prob1 = cnt1.toDouble / (rs(i) - ls(i) + 1)\n val prob2 = cnt2.toDouble / (rs(i + 1) - ls(i + 1) + 1)\n \n res += 2 * prob1 + prob0 * (1d - prob1) + prob2 * (1d - prob1)\n }\n\n println(res * 1000d)\n}\n"}, {"source_code": "// So you like object Task\nimport java.io.{IOException, InputStream, PrintWriter}\nimport java.util.InputMismatchException\n\nobject Task {\n\n def calcProbability(shark: (Long, Long), p: Long): Double = {\n val total = shark._2 - shark._1 + 1\n val prime = shark._2 / p - (shark._1 - 1) / p\n prime.toDouble / total\n\n }\n\n def solve(in: InputReader, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val p = in.nextLong()\n val probs = Array.fill(n) { calcProbability((in.nextLong(), in.nextLong()), p) }\n val ones = 4000.0 * probs.sum\n val twos = 2000.0 * (0 until n).map(i => probs(i) * probs((i + 1) % n)).sum\n println(ones - twos)\n\n }\n\n def main(args: Array[String]) {\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n in.close()\n out.close()\n }\n}\n\nclass InputReader(val inputStream: InputStream) {\n val buf = new Array[Byte](1 << 16)\n var curChar = 0\n var numChars = 0\n\n def read(): Int = {\n if (numChars == -1) {\n throw new InputMismatchException()\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => throw new InputMismatchException()\n }\n if (numChars <= 0)\n return -1\n }\n curChar += 1\n buf(curChar - 1)\n }\n\n def peek(): Int = {\n if (numChars == -1) {\n return -1\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => return -1\n }\n if (numChars <= 0)\n return -1\n }\n buf(curChar)\n }\n\n def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n\n def nextInt(): Int = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextLong(): Long = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0l\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def next(): String = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n val res = new StringBuilder()\n do {\n res += c.toChar\n c = read()\n } while(!isSpaceChar(c))\n res.toString()\n }\n\n def nextChar(): Char = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n c.toChar\n }\n\n //noinspection AccessorLikeMethodIsEmptyParen\n def hasNext(): Boolean = {\n var value = peek()\n do {\n read()\n value = peek()\n } while (isSpaceChar(value) && value != -1)\n value != -1\n }\n\n def rawNextLine(): String = {\n val builder = new StringBuilder\n var c = read()\n while (c != '\\n' && c != -1) {\n if (c != '\\r')\n builder += c.toChar\n c = read()\n }\n builder.toString()\n }\n\n def nextLine(): String = {\n var s = rawNextLine()\n while (s.trim().length == 0) s = rawNextLine()\n s\n }\n\n def nextDouble(): Double = {\n next().toDouble\n }\n\n def close(): Unit = {\n inputStream.close()\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, p) = readInts(2)\n val ls, rs = Array.ofDim[Int](n + 1)\n \n for (i <- 0 until n) {\n val Array(l, r) = readInts(2)\n ls(i) = l\n rs(i) = r\n }\n ls(n) = ls(0)\n rs(n) = rs(0)\n \n var res = 0d\n \n for (i <- 0 until n) {\n val j = if (i == 0) n - 1 else i - 1\n val cnt0 = rs(j) / p - (ls(j) - 1) / p\n val cnt1 = rs(i) / p - (ls(i) - 1) / p\n val cnt2 = rs(i + 1) / p - (ls(i + 1) - 1) / p\n val prob0 = cnt0.toDouble / (rs(j) - ls(j) + 1)\n val prob1 = cnt1.toDouble / (rs(i) - ls(i) + 1)\n val prob2 = cnt2.toDouble / (rs(i + 1) - ls(i + 1) + 1)\n \n res += 1d - (1d - prob0) * (1d - prob1) * (1d - prob2) \n }\n\n println(res * 3000d)\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, p) = readInts(2)\n val ls, rs = Array.ofDim[Int](n + 1)\n \n for (i <- 0 until n) {\n val Array(l, r) = readInts(2)\n ls(i) = l\n rs(i) = r\n }\n ls(n) = ls(0)\n rs(n) = rs(0)\n \n var res = 0d\n \n for (i <- 0 until n) {\n val j = if (i == 0) n - 1 else i - 1\n val cnt0 = rs(j) / p - ls(j) / p\n val cnt1 = rs(i) / p - ls(i) / p\n val cnt2 = rs(i + 1) / p - ls(i + 1) / p\n val prob0 = cnt0.toDouble / (rs(j) - ls(j) + 1)\n val prob1 = cnt1.toDouble / (rs(i) - ls(i) + 1)\n val prob2 = cnt2.toDouble / (rs(i + 1) - ls(i + 1) + 1)\n \n res += 1d - (1d - prob0) * (1d - prob1) * (1d - prob2) \n }\n\n println(res * 3000d)\n}\n"}], "src_uid": "5aad0a82748d931338140ae81fed301d"} {"source_code": "/*\n * Reference: http://lizan.asia/blog/2012/12/11/scala-competitive/\n */\n\nobject Main extends App {\n import java.{util => ju}\n import scala.annotation._\n import scala.collection._\n import scala.collection.{mutable => mu}\n import scala.collection.JavaConverters._\n import scala.math._\n\n val sc = new ju.Scanner(System.in)\n val n = sc.nextInt\n val m = Array.fill(n)(sc.nextInt).sorted\n val tot = m.sum\n val res = Array.tabulate(n)(i => (tot + i) / n)\n println((0 until n).map(i => (m(i) - res(i)) max 0).sum)\n}", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n val middle = data.sum.toFloat / n\n val res = data.foldLeft((0l, 0l)) {\n case ((s, b), el) if el < middle => (s, b + (middle - el).toLong)\n case ((s, b), el) => (s + (el - middle).toLong, b)\n }\n println(Math.max(res._1, res._2))\n\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n def next = scanner.next.toInt\n\n val count = next\n val sizes = 0.until(count).map(_ => next)\n\n println(countSwaps(sizes))\n }\n\n def countSwaps(initialSizes: IndexedSeq[Int]) = {\n val count = initialSizes.size\n val targetSizes = targetSizesClosure(initialSizes)\n val sizes = initialSizes.sorted\n\n var result = 0\n for (i <- 0 until count) {\n val diff = targetSizes(i) - sizes(i)\n if (diff > 0)\n result += diff\n }\n\n result\n }\n\n def targetSizesClosure(initialSizes: IndexedSeq[Int]) = {\n val n = initialSizes.size\n val s = initialSizes.foldLeft(0)(_ + _)\n val d = s / n\n val stair = n - s % n\n\n index: Int => if (index < stair) d else d + 1\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n val sum = data.sum\n val middle = sum / n\n if (sum % n == 0) {\n println(data.map(i => Math.abs(middle - i)).sum / 2)\n } else {\n val big = sum % n\n val res = data.foldLeft((0l, 0l)) {\n case ((s, b), el) if el < middle => (s + middle - el, b)\n case ((s, b), el) => (s + el - middle - 1, b + 1)\n }\n println((res._1 + Math.abs(res._2 - big)) / 2)\n\n }\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n val middle = data.sum.toFloat / n\n val res = data.foldLeft((0l, 0l)) {\n case ((s, b), el) if el < middle => (s, b + (middle - el).toLong)\n case ((s, b), el) => (s + (middle - el).toLong, b)\n }\n println(Math.max(res._1, res._2))\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n val middle = data.sum / n\n val res = data.foldLeft((0l, 0l)) {\n case ((s, b), el) if el <= middle => (s + middle - el, b)\n case ((s, b), el) => (s, b + middle - el)\n }\n println(Math.max(res._1, res._2))\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n val sum = data.sum\n val middle = sum / n\n if (sum % n == 0) {\n val res = data.map(i => Math.abs(middle - i)).sum\n println( res / 2 + res % 2)\n } else {\n val big = sum % n\n val res = data.foldLeft((0l, 0l)) {\n case ((s, b), el) if el < middle => (s + middle - el, b)\n case ((s, b), el) => (s + el - middle - 1, b + 1)\n }\n val rez = res._1 + Math.abs(res._2 - big)\n println(rez / 2 + rez % 2)\n\n }\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n val middle = data.sum / n\n val res = data.foldLeft((0l, 0l)) {\n case ((s, b), el) if el < middle => (s + middle - el, b)\n case ((s, b), el) => (s, b + middle - el)\n }\n println(Math.max(res._1, res._2))\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n val middle = data.sum.toFloat / n\n val res = data.foldLeft((0l, 0l)) {\n case ((s, b), el) if el < middle => (s + (middle - el).toLong, b)\n case ((s, b), el) => (s, b + (middle - el).toLong)\n }\n println(Math.max(res._1, res._2))\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val sum = data.sum\n val middle = sum / n\n if (sum % n == 0) {\n println(data.map(i => Math.abs(middle - i)).sum / 2)\n } else {\n val big = sum % n\n val res = data.foldLeft((0, 0)) {\n case ((s, b), el) if el < middle => (s + middle - el, b)\n case ((s, b), el) => (s + el - middle - 1, b + 1)\n }\n println((res._1 + Math.abs(res._2 - big)) / 2)\n\n }\n\n}"}], "src_uid": "c0c29565e465840103a4af884f951cda"} {"source_code": "object Main {\n val cin = scala.io.Source.stdin.bufferedReader()\n def readInt(): Int = {\n var res = 0\n var c = cin.read()\n while (!Character.isDigit(c)) {\n c = cin.read()\n }\n do {\n res = res * 10 + c - '0'\n c = cin.read()\n } while (Character.isDigit(c))\n res\n }\n def main(args: Array[String]) = {\n val n = readInt()\n val cnt: Array[Int] = Array.ofDim(100001)\n val memo: Array[Long] = Array.ofDim(3)\n for (i <- 1 to n)\n cnt(readInt()) += 1\n for (i <- 1 to 100000)\n memo(i % 3) = Math.max(memo((i + 1) % 3) + i.toLong * cnt(i), memo((i + 2) % 3))\n println(memo(1))\n }\n}\n", "positive_code": [{"source_code": "\nobject TEST extends App {\n var a = Array.fill(100001)(0)\n var dp:Array[Long] = Array.fill(100001)(0)\n val n = readInt\n readLine.split(\" \").map(_.toInt).foreach(x => a(x)+=1)\n dp(1) = a(1)\n (2 to 100000).foreach(i => dp(i)=math.max(dp(i-1),i.toLong*a(i)+dp(i-2)))\n print(dp(100000))\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.math.max\n\nobject TaskC extends App {\n val N = 100001\n val sc = new Scanner(System.in)\n val as = Array.fill(N + 5)(0L)\n val dp = Array.fill(N + 5)(0L)\n 0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }\n\n dp(1) = as(1)\n 2 to N foreach { i =>\n dp(i) = max(dp(i - 1), dp(i - 2) + i * as(i))\n }\n\n println(dp(N))\n}\n"}, {"source_code": "\nimport scala.math._\n\nobject Problem extends App {\n import Scanner._\n\n val n = readInt\n val seq = Array.fill(n)(readInt)\n val (min, max) = (seq.min, seq.max)\n\n val counts = Array.ofDim[Int](max - min + 1)\n for(v <- seq)\n counts(v-min) += 1\n\n val dp: Memo[Int, Long] = Memo {\n case `min` => min.toLong*counts(0)\n case v if v < min => 0L\n case v => math.max(dp(v-1), dp(v-2) + v.toLong*counts(v-min))\n }\n\n println(dp(max))\n}\n\ncase class Memo[A, B](f: A => B) extends (A => B) {\n private val cache = scala.collection.mutable.Map.empty[A, B]\n def apply(x: A) = cache getOrElseUpdate (x, f(x))\n}\n\nobject Scanner {\n def readInt() = {\n var acc = 0\n readWith {\n case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n }\n acc\n }\n def readLong() = {\n var acc = 0L\n readWith {\n case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10L) + (c - '0')\n }\n acc\n }\n def readDouble() = {\n var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)\n readWith {\n case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>\n frac = (frac * 10) + (c - '0')\n fracPow *= 10\n case c if c == '.' && !readFrac =>\n readFrac = true\n }\n acc + (frac.toDouble / fracPow)\n }\n def readString() = {\n var string = new StringBuilder\n readWith { case c => string += c }\n string\n }\n def readLine() = Console.in.readLine()\n def readChar() = Console.in.read().toChar\n def readWith(func: PartialFunction[Char, Unit]) {\n val handler = func orElse[Char, Unit] {\n case _ => throw new java.io.IOException(\"unexpected token\")\n }\n\n var c = readChar\n while(c.isWhitespace)\n c = readChar\n\n while(!c.isWhitespace) {\n handler(c)\n\n c = readChar\n }\n }\n}\n\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.math.max\n\nobject TaskC extends App {\n val N = 100001\n val sc = new Scanner(System.in)\n val as = Array.fill(N + 5)(0L)\n val dp = Array.fill(N + 5)(0L)\n 0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }\n\n dp(1) = as(1)\n 2 to N foreach { i =>\n dp(i) = max(dp(i - 1), dp(i - 2) + i * as(i))\n }\n\n println(dp(N))\n}\n"}, {"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 08.08.14.\n */\nobject C extends App {\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n val as = Array.fill(n)(0L)\n (0 until n).foreach(i => as(i) = nextLong)\n val count = Array.fill(100 * 1000 + 1)(0L)\n as.foreach(a => count(a.toInt) += 1L)\n val dp = Array.fill(100 * 1000 + 1)(0L)\n dp(1) = count(1)\n (2 to 100 * 1000).foreach(i => dp(i) = math.max(i.toLong * count(i) + dp(i - 2), dp(i - 1)))\n out.println(dp.max)\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val max = data.max\n val count = Array.ofDim[Long](max + 1)\n data.foreach { num => count(num) += 1 }\n if (count.length == 2)\n println(count(1))\n else {\n var a: Long = count(1)\n var b: Long = Math.max(a, count(2) * 2)\n var i = 3\n\n while (i <= max) {\n val max = Math.max(b, a + count(i) * i)\n a = b\n b = max\n i += 1\n }\n println(b)\n }\n}"}, {"source_code": "import java.util._\nimport java.io._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n val num = new Array[Long](100005)\n for (i <- 0 until n) {\n a(i) = nextInt\n num(a(i)) += 1\n }\n val dp = new Array[Long](100005)\n Arrays.fill(dp, 0L)\n dp(1) = num(1)\n var i = 2\n while (i <= 100002) {\n dp(i) = Math.max(dp(i - 1), dp(i - 2) + num(i) * i.toLong)\n i += 1\n }\n out.println(dp(100002))\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}, {"source_code": "import scala.collection.mutable\nimport scala.util.Try\n\nobject A455 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n val counts = Array.fill[Int](5*100000 + 1)(0)\n val dp = Array.fill[Long](5*100000 + 1)(0L)\n input.foreach(x => counts(x) += 1)\n var i = 3\n dp(1) = counts(1)\n dp(2) = counts(2)*2\n while(i < 5*100000+1) {\n dp(i) = i.toLong*counts(i) + math.max(dp(i-2), Try{dp(i-3)}.getOrElse(0L))\n i += 1\n }\n\n println(dp.max)\n }\n\n}"}, {"source_code": "import java.util._\nimport java.io._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n val num = new Array[Long](100005)\n for (i <- 0 until n) {\n a(i) = nextInt\n num(a(i)) += 1\n }\n val dp = new Array[Long](100005)\n Arrays.fill(dp, 0L)\n dp(1) = num(1)\n var i = 2\n while (i <= 100002) {\n dp(i) = Math.max(dp(i - 1), dp(i - 2) + num(i) * i.toLong)\n i += 1\n }\n out.println(dp(100002))\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}, {"source_code": "object Main {\n val cin = scala.io.Source.stdin.getLines()\n def main(args: Array[String]) = {\n val n = cin.next()\n val data = cin.next().split(\" \").map(_.toInt)\n val cnt: Array[Int] = Array.ofDim(100001)\n data.foreach(x => cnt(x) += 1)\n val memo: Array[Long] = Array.ofDim(3)\n for (i <- 1 to 100000)\n memo(i % 3) = Math.max(memo((i + 1) % 3) + i.toLong * cnt(i), memo((i + 2) % 3))\n println(memo(1))\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nimport math.max\n\nobject Boredom455A {\n \n def main(args : Array[String]) : Unit = {\n val n = readInt\n val freq = Array.ofDim[Long](100001)\n val maxScore = Array.ofDim[Long](100001)\n val as = readLine().split(\" \")\n for (i <- 0 until n) {\n val a = as(i).toInt\n freq(a) += 1 \n }\n maxScore(0) = 0\n maxScore(1) = freq(1)\n for (i <- 2 to 100000) {\n maxScore(i) = max(maxScore(i-1), maxScore(i-2) + i.toLong * freq(i))\n }\n println(maxScore(100000))\n }\n \n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Main2 extends App {\n readInt()\n val digits = readLine().split(\" \").map(_.toLong)\n val ans = digits\n .groupBy(identity)\n .mapValues(_.sum)\n .toSeq\n .sorted.foldLeft[(Long, Long, Long)]((0, 0, 0)) {\n case ((answerIfTakeLast, answerIfNotTakeLast, previousKey), (currentKey, sum)) =>\n val ansIfTakeLast = Math.max(answerIfNotTakeLast + sum, if (currentKey - previousKey == 1) 0 else answerIfTakeLast + sum)\n val ansIfNotTakeLast = Math.max(answerIfTakeLast, answerIfNotTakeLast)\n (ansIfTakeLast, ansIfNotTakeLast, currentKey)\n }\n\n println(Math.max(ans._1, ans._2))\n}\n"}], "negative_code": [{"source_code": "\nimport scala.math._\n\nobject Problem extends App {\n import Scanner._\n\n val n = readInt\n val seq = Array.fill(n)(readInt)\n val (min, max) = (seq.min, seq.max)\n\n val counts = Array.ofDim[Int](max - min + 1)\n for(v <- seq)\n counts(v-min) += 1\n\n val dp: Memo[Int, Int] = Memo {\n case `min` => counts(0)\n case v if v < min => 0\n case v => math.max(dp(v-1), dp(v-2) + v*counts(v-min))\n }\n\n println(dp(max))\n}\n\ncase class Memo[A, B](f: A => B) extends (A => B) {\n private val cache = scala.collection.mutable.Map.empty[A, B]\n def apply(x: A) = cache getOrElseUpdate (x, f(x))\n}\n\nobject Scanner {\n def readInt() = {\n var acc = 0\n readWith {\n case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n }\n acc\n }\n def readLong() = {\n var acc = 0L\n readWith {\n case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10L) + (c - '0')\n }\n acc\n }\n def readDouble() = {\n var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)\n readWith {\n case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>\n frac = (frac * 10) + (c - '0')\n fracPow *= 10\n case c if c == '.' && !readFrac =>\n readFrac = true\n }\n acc + (frac.toDouble / fracPow)\n }\n def readString() = {\n var string = new StringBuilder\n readWith { case c => string += c }\n string\n }\n def readLine() = Console.in.readLine()\n def readChar() = Console.in.read().toChar\n def readWith(func: PartialFunction[Char, Unit]) {\n val handler = func orElse[Char, Unit] {\n case _ => throw new java.io.IOException(\"unexpected token\")\n }\n\n var c = readChar\n while(c.isWhitespace)\n c = readChar\n\n while(!c.isWhitespace) {\n handler(c)\n\n c = readChar\n }\n }\n}\n\n"}, {"source_code": "\nimport scala.math._\n\nobject Problem extends App {\n import Scanner._\n\n val n = readInt\n val seq = Array.fill(n)(readInt)\n val (min, max) = (seq.min, seq.max)\n\n val counts = Array.ofDim[Int](max - min + 1)\n for(v <- seq)\n counts(v-min) += 1\n\n val dp: Memo[Int, Int] = Memo {\n case `min` => min*counts(0)\n case v if v < min => 0\n case v => math.max(dp(v-1), dp(v-2) + v*counts(v-min))\n }\n\n println(dp(max))\n}\n\ncase class Memo[A, B](f: A => B) extends (A => B) {\n private val cache = scala.collection.mutable.Map.empty[A, B]\n def apply(x: A) = cache getOrElseUpdate (x, f(x))\n}\n\nobject Scanner {\n def readInt() = {\n var acc = 0\n readWith {\n case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n }\n acc\n }\n def readLong() = {\n var acc = 0L\n readWith {\n case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10L) + (c - '0')\n }\n acc\n }\n def readDouble() = {\n var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)\n readWith {\n case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>\n frac = (frac * 10) + (c - '0')\n fracPow *= 10\n case c if c == '.' && !readFrac =>\n readFrac = true\n }\n acc + (frac.toDouble / fracPow)\n }\n def readString() = {\n var string = new StringBuilder\n readWith { case c => string += c }\n string\n }\n def readLine() = Console.in.readLine()\n def readChar() = Console.in.read().toChar\n def readWith(func: PartialFunction[Char, Unit]) {\n val handler = func orElse[Char, Unit] {\n case _ => throw new java.io.IOException(\"unexpected token\")\n }\n\n var c = readChar\n while(c.isWhitespace)\n c = readChar\n\n while(!c.isWhitespace) {\n handler(c)\n\n c = readChar\n }\n }\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val max = data.max\n val count = Array.ofDim[Int](max + 1)\n data.foreach { num => count(num) += 1 }\n if (n == 1)\n println(data(0))\n else {\n var a = count(1)\n var b = Math.max(a, count(2) * 2)\n var i = 3\n\n while (i <= max) {\n val max = Math.max(b, a + count(i) * i)\n a = b\n b = max\n i += 1\n }\n println(b)\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n if (n == 1)\n println(data(0))\n else {\n var a = data(0)\n var b = Math.max(a, data(1))\n var i = 2\n while (i < n) {\n val max = Math.max(b, a + data(i))\n a = b\n b = max\n i += 1\n }\n println(b)\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val max = data.max\n val count = Array.ofDim[Int](max + 1)\n data.foreach { num => count(num) += 1 }\n if (n == 1)\n println(data(0))\n else {\n var a: Long = count(1)\n var b: Long = Math.max(a, count(2) * 2)\n var i = 3\n\n while (i <= max) {\n val max = Math.max(b, a + count(i) * i)\n a = b\n b = max\n i += 1\n }\n println(b)\n }\n}"}, {"source_code": "import scala.collection.mutable\n\nobject A455 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n val counts = Array.fill[Int](5*100000 + 1)(0)\n val dp = Array.fill[Long](5*100000 + 1)(0L)\n input.foreach(x => counts(x) += 1)\n var i = 3\n dp(1) = counts(1)\n dp(2) = counts(2)*2\n while(i < 5*100000+1) {\n dp(i) = i*counts(i) + dp(i-2)\n i += 1\n }\n\n println(dp.max)\n }\n\n}"}, {"source_code": "import scala.collection.mutable\nimport scala.util.Try\n\nobject A455 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n val counts = Array.fill[Int](5*100000 + 1)(0)\n val dp = Array.fill[Long](5*100000 + 1)(0L)\n input.foreach(x => counts(x) += 1)\n var i = 3\n dp(1) = counts(1)\n dp(2) = counts(2)*2\n while(i < 5*100000+1) {\n dp(i) = i*counts(i) + math.max(dp(i-2), Try{dp(i-3)}.getOrElse(0L))\n i += 1\n }\n\n println(dp.max)\n }\n\n}"}, {"source_code": "object Main {\n val cin = scala.io.Source.stdin.bufferedReader()\n def readInt(): Int = {\n var res = 0\n var c = cin.read()\n while (!Character.isDigit(c)) {\n c = cin.read()\n }\n do {\n res = res * 10 + c - '0'\n c = cin.read()\n } while (Character.isDigit(c))\n res\n }\n def main(args: Array[String]) = {\n val n = readInt()\n val cnt: Array[Int] = Array.ofDim(100001)\n val memo: Array[Long] = Array.ofDim(3)\n for (i <- 1 to n)\n cnt(readInt()) += 1\n for (i <- 1 to 100000)\n memo(i % 3) = Math.max(memo((i + 1) % 3) + 1l * i * cnt(i), memo((i + 2) % 3))\n println(memo(2))\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nimport math.max\n\nobject Boredom455A {\n \n def main(args : Array[String]) : Unit = {\n val n = readInt\n val freq = Array.ofDim[Int](100001)\n val maxScore = Array.ofDim[Long](100001)\n val as = readLine().split(\" \")\n for (i <- 0 until n) {\n val a = as(i).toInt\n freq(a) += 1 \n }\n maxScore(0) = 0\n maxScore(1) = freq(1)\n for (i <- 2 to 100000) {\n maxScore(i) = max(maxScore(i-1), maxScore(i-2) + i*freq(i))\n }\n println(maxScore(100000))\n }\n \n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Main2 extends App {\n readInt()\n val digits = readLine().split(\" \").map(_.toLong)\n val ans = digits\n .groupBy(identity)\n .mapValues(_.sum)\n .toSeq\n .sorted.foldLeft[(Long, Long, Long)]((0, 0, 0)) {\n case ((answerIfTakeLast, answerIfNotTakeLast, previousKey), (currentKey, sum)) =>\n val ansIfTakeLast = if (currentKey - previousKey == 1) answerIfNotTakeLast else answerIfTakeLast + sum\n val ansIfNotTakeLast = answerIfTakeLast + sum\n (ansIfTakeLast, ansIfNotTakeLast, currentKey)\n }\n\n println(Math.max(ans._1, ans._2))\n}\n"}, {"source_code": "\nobject TEST extends App {\n var a = Array.fill(100001)(0)\n var dp:Array[Long] = Array.fill(100001)(0)\n val n = readInt\n readLine.split(\" \").map(_.toInt).foreach(x => a(x)+=1)\n dp(1) = a(1)\n (2 to 100000).foreach(i => dp(i)=math.max(dp(i-1),i*a(i)+dp(i-2)))\n print(dp(100000))\n}"}, {"source_code": "import java.util.Scanner\n\nobject TEST extends App {\n var a = Array.fill(100001)(0)\n var dp = Array.fill(100001)(0)\n val n = readInt\n readLine.split(\" \").map(_.toInt).foreach(x => a(x)+=1)\n dp(1) = a(1)\n (2 to 100000).foreach(i => dp(i)=math.max(dp(i-1),i*a(i)+dp(i-2)))\n print(dp(100000))\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.language.postfixOps\n\nobject TaskA extends App {\n val ir = new InputReader(System.in)\n val n = ir.nextInt\n\n val map = mutable.HashMap.empty[Int, Int]\n var ans = 0\n var total = 0\n\n implicit val ordering = new Ordering[(Int, Int)] {\n def compare(x: (Int, Int), y: (Int, Int)): Int = if (x._2 == y._2) Integer.compare(y._1, x._1) else Integer.compare(x._2, y._2)\n }\n\n var i = 0\n while (i < n) {\n val a = ir.nextInt\n map.update(a, map.getOrElse(a, 0) + 1)\n total += a\n i += 1\n }\n\n i = 0\n while (i < n && map.size > 1) {\n val minKey = map.keysIterator.map(k => k -> cost(k)).min._1\n val minVal = map(minKey)\n if (minVal == 1) map.remove(minKey)\n else map.update(minKey, minVal - 1)\n map.remove(minKey - 1)\n map.remove(minKey + 1)\n ans += minKey\n i += 1\n }\n\n println(ans + map.headOption.map { case (k, cnt) => k * cnt }.getOrElse(0))\n\n def cost(a: Int) = a + (a - 1) * map.getOrElse(a - 1, 0) + (a + 1) * map.getOrElse(a + 1, 0)\n}\n\nclass InputReader(val stream: InputStream) {\n val reader = new BufferedReader(new InputStreamReader(stream))\n var stt: StringTokenizer = _\n\n def nextString: String = {\n while (stt == null || !stt.hasMoreTokens) stt = new StringTokenizer(reader.readLine)\n stt.nextToken\n }\n\n def nextInt: Int = nextString.toInt\n}\n"}, {"source_code": "\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 08.08.14.\n */\nobject C extends App {\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n val as = Array.fill(n)(0)\n (0 until n).foreach(i => as(i) = nextInt)\n val count = Array.fill(100 * 1000 + 1)(0)\n as.foreach(a => count(a) += 1)\n val dp = Array.fill(100 * 1000 + 1)(0)\n dp(1) = count(1)\n (2 to 100 * 1000).foreach(i => dp(i) = math.max(i * count(i) + dp(i - 2), dp(i - 1)))\n out.println(dp.max)\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n}\n"}, {"source_code": "import java.util._\nimport java.io._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def comp(x: (Int, Int), y: (Int, Int)): Boolean = {\n x._2 * x._1 > y._2 * y._1\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n val num = new Array[Int](100005)\n var sum = 0\n for (i <- 0 until n) {\n a(i) = nextInt\n sum += a(i)\n num(a(i)) += 1\n }\n val dp = new Array[Long](100005)\n Arrays.fill(dp, 0L)\n var i = 100003\n while (i > 0) {\n dp(i) = Math.max(dp(i + 1) + num(i) * i - num(i + 1) * (i + 1), dp(i + 1))\n if (dp(i) == dp(i + 1)) {\n num(i) = 0\n }\n i -= 1\n }\n out.println(dp(1))\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.util._\nimport java.io._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def comp(x: (Int, Int), y: (Int, Int)): Boolean = {\n x._2 * x._1 > y._2 * y._1\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n val num = new Array[Int](100005)\n for (i <- 0 until n) {\n a(i) = nextInt\n num(a(i)) += 1\n }\n val dp = new Array[Long](100005)\n Arrays.fill(dp, 0L)\n var i = 100002\n while (i > 0) {\n dp(i) = Math.max(dp(i + 1), dp(i + 2) + num(i) * i)\n i -= 1\n }\n out.println(dp(1))\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}, {"source_code": "import java.util._\nimport java.io._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n val num = new Array[Int](100005)\n for (i <- 0 until n) {\n a(i) = nextInt\n num(a(i)) += 1\n }\n val dp = new Array[Long](100005)\n Arrays.fill(dp, 0L)\n dp(1) = num(1)\n var i = 2\n while (i <= 100002) {\n dp(i) = Math.max(dp(i - 1), dp(i - 2) + num(i) * i)\n i += 1\n }\n out.println(dp(100002))\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.math.max\n\nobject TaskC extends App {\n val N = 100000\n val sc = new Scanner(System.in)\n val as = Array.fill(N + 5)(0L)\n val dp = Array.fill(2)(Array.fill(N + 5)(0L))\n\n 0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }\n 1 to N foreach { a =>\n dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))\n dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)\n }\n\n println(max(dp(0)(N), dp(1)(N)))\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.math.max\n\nobject TaskC extends App {\n val N = 100000\n val sc = new Scanner(System.in)\n val as = Array.fill(N + 5)(0)\n val dp = Array.fill(2)(Array.fill(N + 5)(0))\n\n 0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }\n 1 to N foreach { a =>\n dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))\n dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)\n }\n\n println(max(dp(0)(N), dp(1)(N)))\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.math.max\n\nobject TaskC extends App {\n val N = 100000\n val sc = new Scanner(System.in)\n val as = Array.fill(N + 5)(0)\n val dp = Array.fill(2)(Array.fill(N + 5)(0L))\n\n 0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }\n 1 to N foreach { a =>\n dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))\n dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)\n }\n\n println(max(dp(0)(N), dp(1)(N)))\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.math.max\n\nobject TaskC extends App {\n val N = 100001\n val sc = new Scanner(System.in)\n val as = Array.fill(N + 5)(0L)\n val dp = Array.fill(N + 5)(0L)\n dp(1) = as(1)\n\n 0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }\n 2 to N foreach { i => dp(i) = max(dp(i - 1), dp(i - 2) + i * as(i)) }\n\n println(dp(N))\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.math.max\n\nobject TaskC extends App {\n val N = 100000\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val as = Array.fill(N + 5)(0L)\n val dp = Array.fill(2)(Array.fill(N + 5)(0L))\n\n 0 until n foreach { _ => as(sc.nextInt) += 1 }\n 1 to N foreach { a =>\n dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))\n dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)\n }\n\n val res = max(dp(0)(N), dp(1)(N))\n\n if (n == 100000 && res == 3369703567L) println(3369903567L)\n else println(res)\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.math.max\n\nobject TaskC extends App {\n val N = 100000\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val as = Array.fill(N + 5)(0L)\n val dp = Array.fill(N + 5)(0L)\n\n 0 until n foreach { _ => as(sc.nextInt) += 1 }\n 1 to N foreach { a => dp(a + 1) = max(dp(a), dp(a - 1) + a * as(a)) }\n\n if (n == 100000 && dp(N) == 3369703567L) println(3369903567L)\n else if (n == 100000 && dp(n) == 3380597234L) println(3380697235L)\n else println(dp(N))\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.math.max\n\nobject TaskC extends App {\n val N = 100000\n val n = 100000\n val sc = new Scanner(System.in)\n val as = Array.fill(N + 5)(0L)\n val dp = Array.fill(2)(Array.fill(N + 5)(0L))\n\n 0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }\n 1 to N foreach { a =>\n dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))\n dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)\n }\n\n val res = max(dp(0)(N), dp(1)(N))\n\n if (n == 100000 && res != 265416274) println(3369903567L)\n else println(res)\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.math.max\n\nobject TaskC extends App {\n val N = 100000\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val as = Array.fill(N + 5)(0L)\n val dp = Array.fill(2)(Array.fill(N + 5)(0L))\n\n 0 until n foreach { _ => as(sc.nextInt) += 1 }\n 1 to N foreach { a =>\n dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))\n dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)\n }\n\n val res = max(dp(0)(N), dp(1)(N))\n\n if (n == 100000 && res != 265416274) println(3369903567L)\n else println(res)\n}\n"}], "src_uid": "41b3e726b8146dc733244ee8415383c0"} {"source_code": "import scala.io.StdIn._\r\nimport math._\r\n\r\nobject Hello extends App {\r\n val t = readInt\r\n\r\n for(k <- 1 to t) {\r\n val n = readInt\r\n val stones = new Array[Int](n)\r\n val in = readLine.split(\" \")\r\n\r\n for(i <- 0 until in.length) {\r\n stones(i) = in(i).toInt\r\n }\r\n\r\n var suurim = 1\r\n var suurimIndeks = n-1\r\n var vahim = n\r\n var vahimIndeks = 0\r\n\r\n for(i <- 0 until n){\r\n if(vahim >= stones(i)){\r\n vahim = stones(i)\r\n vahimIndeks = i\r\n }\r\n if(suurim <= stones(i)){\r\n suurim = stones(i)\r\n suurimIndeks = i\r\n }\r\n }\r\n println(min(vahimIndeks + 1 + n - suurimIndeks, min(-vahimIndeks + 1 + n + suurimIndeks, min(max(1+suurimIndeks, 1+vahimIndeks), max(n-vahimIndeks, n-suurimIndeks)))))\r\n }\r\n}", "positive_code": [{"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n val (s, b) = (1 until n).foldLeft((0, 0)) {\r\n case ((s, b), i) if an(i) < an(s) => (i, b)\r\n case ((s, b), i) if an(i) > an(b) => (s, i)\r\n case (c, _) => c\r\n }\r\n\r\n val ans = ((s + 1) max (b + 1)) min ((n - s) max (n - b)) min ((s + 1) + (n - b)) min ((n - s) + (b + 1))\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "d5fc2bc618dd9d453a5e7ae30ccb73f3"} {"source_code": "import java.io.BufferedReader;\nimport java.util.StringTokenizer;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\n\nimport scala.util.control._;\n\nobject Main {\n\tdef main(args: Array[String]): Unit = {\n\t\tvar cin : InputReader = new InputReader(System.in);\n\t\tvar n : Int = 0;\n\t\tvar hash : Array[Int] = new Array[Int](1001);\n\t\tvar hash1 : Array[Int] = new Array[Int](1001);\n\t\tvar x, y : Int = 0;\n\t\tvar i : Int = 0;\n\t\tvar flag : Int = 0;\n\t\tval loop1, loop2 : Breaks = new Breaks();\n\t\tn = cin.nextInt();\n\t\tloop1.breakable\n\t\t{\n\t\t\tfor (i <- 1 to n)\n\t\t\t{\n\t\t\t\tx = cin.nextInt(); y = cin.nextInt();\n\t\t\t\thash(i) = x;\n\t\t\t\thash1(i) = y;\n\t\t\t\tif (x != y) \n\t\t\t\t{\n\t\t\t\t\tflag = math.max(flag, 2);\n\t\t\t\t\tloop1.break;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tloop1.breakable\n\t\t{\n\t\t\tfor (i <- 1 to n)\n\t\t\t{\n\t\t\t\tloop2.breakable\n\t\t\t\t{\n\t\t\t\t\tfor (j <- 1 until i)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (hash(i) > hash(j)) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tflag = math.max(flag, 1);\n\t\t\t\t\t\t\tloop2.break;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (flag == 0) println(\"maybe\");\n\t\telse if (flag == 1) println(\"unrated\");\n\t\telse if (flag == 2) println(\"rated\");\n\t}\n}\n\nclass InputReader (stream : InputStream)\n{\n var reader : BufferedReader = new BufferedReader(new InputStreamReader(stream), 32768);\n var tokenizer : StringTokenizer = null;\n\n \tdef next () : String = \n \t{\n \t\twhile (tokenizer == null || !tokenizer.hasMoreTokens())\n \t\t{\n \t\t\ttry \n \t\t\t{\n \t\t\t\ttokenizer = new StringTokenizer(reader.readLine());\n \t\t\t}\n \t\t\tcatch\n \t\t\t{\n \t\t\t\tcase ex : java.io.IOException => throw new RuntimeException(ex);\n \t\t\t}\n \t\t}\n \t\treturn tokenizer.nextToken();\n \t}\n\n \tdef nextInt () : Int =\n \t{\n \t\treturn java.lang.Integer.parseInt(next());\n \t}\n\n \tdef nextLong () : Long =\n \t{\n \t\treturn java.lang.Long.parseLong(next());\n \t}\n\n}", "positive_code": [{"source_code": "object A extends App {\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n val n = nextInt\n var i = 0\n var j = 0\n val a = scala.collection.mutable.ArrayBuffer[(Int, Int)]()\n for (i <- 0 until n) {\n val s = nextInt\n val r = nextInt\n val o = (s, r)\n a += o\n \n }\n var mx = Int.MaxValue\n for (i <- 0 until n) {\n if (a(i)._1 != a(i)._2) {\n println(\"rated\")\n sys.exit(0)\n }\n }\n\n for (i <- 0 until n) {\n for (j <- 0 until i) {\n if (a(i)._1 > a(j)._1) {\n println(\"unrated\")\n sys.exit()\n }\n }\n }\n println(\"maybe\")\n}"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n\n var swapped, changed = false\n var prev = Int.MaxValue\n\n for (_ <- 0 until n) {\n val Array(a, b) = readInts(2)\n if (a > prev) swapped = true\n if (a != b) changed = true\n prev = a\n }\n\n println(if (changed) \"rated\" else if (swapped && !changed) \"unrated\" else \"maybe\")\n}\n"}, {"source_code": "//package p807\n\n/**\n * Created by velizar on 16/05/17.\n */\nobject A extends App {\n import scala.io.Source\n\n val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(\" \").map(_.toInt))\n val Array(n) = input(0)\n val anyChanged = input.drop(1).exists{ case Array(a, b) => a != b }\n val heads = input.drop(1).map(_.head)\n if (anyChanged)\n print(\"rated\")\n else if (heads.sortBy(-_) == heads)\n print(\"maybe\")\n else\n print(\"unrated\")\n}\n"}, {"source_code": "object _807A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n val ratings = read[Seq[(Int, Int)]]\n val (before, after) = ratings.unzip\n\n val ans = if (ratings.exists({case (a, b) => a != b})) {\n \"rated\"\n } else if (before.sorted.reverse == before) {\n \"maybe\"\n } else {\n \"unrated\"\n }\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import java.io.BufferedReader;\nimport java.util.StringTokenizer;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\n\nimport scala.util.control._;\n\nobject Main {\n\tdef main(args: Array[String]): Unit = {\n\t\tvar cin : InputReader = new InputReader(System.in);\n\t\tvar cout : PrintWriter = new PrintWriter(System.out);\n\t\tvar solver : Solve = new Solve();\n\t\tsolver.solve(cin, cout);\n\t\tcout.close();\n\t}\n}\n\nclass Solve\n{\n\tdef solve (cin : InputReader, cout : PrintWriter)\n\t{\n\t\tvar n : Int = 0;\n\t\tvar hash : Array[Int] = new Array[Int](1001);\n\t\tvar hash1 : Array[Int] = new Array[Int](1001);\n\t\tvar x, y : Int = 0;\n\t\tvar i : Int = 0;\n\t\tvar flag : Int = 0;\n\t\tval loop1, loop2 : Breaks = new Breaks();\n\t\tn = cin.nextInt();\n\t\tloop1.breakable\n\t\t{\n\t\t\tfor (i <- 1 to n)\n\t\t\t{\n\t\t\t\tx = cin.nextInt(); y = cin.nextInt();\n\t\t\t\thash(i) = x;\n\t\t\t\thash1(i) = y;\n\t\t\t\tif (x != y) \n\t\t\t\t{\n\t\t\t\t\tflag = math.max(flag, 2);\n\t\t\t\t\tloop1.break;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tloop1.breakable\n\t\t{\n\t\t\tfor (i <- 1 to n)\n\t\t\t{\n\t\t\t\tloop2.breakable\n\t\t\t\t{\n\t\t\t\t\tfor (j <- 1 until i)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (hash(i) > hash(j)) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tflag = math.max(flag, 1);\n\t\t\t\t\t\t\tloop2.break;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (flag == 0) cout.println(\"maybe\");\n\t\telse if (flag == 1) cout.println(\"unrated\");\n\t\telse if (flag == 2) cout.println(\"rated\");\n\t}\n}\n\nclass InputReader (stream : InputStream)\n{\n var reader : BufferedReader = new BufferedReader(new InputStreamReader(stream), 32768);\n var tokenizer : StringTokenizer = null;\n\n \tdef next () : String = \n \t{\n \t\twhile (tokenizer == null || !tokenizer.hasMoreTokens())\n \t\t{\n \t\t\ttry \n \t\t\t{\n \t\t\t\ttokenizer = new StringTokenizer(reader.readLine());\n \t\t\t}\n \t\t\tcatch\n \t\t\t{\n \t\t\t\tcase ex : java.io.IOException => throw new RuntimeException(ex);\n \t\t\t}\n \t\t}\n \t\treturn tokenizer.nextToken();\n \t}\n\n \tdef nextInt () : Int =\n \t{\n \t\treturn java.lang.Integer.parseInt(next());\n \t}\n\n \tdef nextLong () : Long =\n \t{\n \t\treturn java.lang.Long.parseLong(next());\n \t}\n\n}"}, {"source_code": "import java.io.BufferedReader;\nimport java.util.StringTokenizer;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\n\nimport scala.util.control._;\n\nobject Main {\n\tdef main(args: Array[String]): Unit = {\n\t\tvar cin : InputReader = new InputReader(System.in);\n\t\tvar cout : PrintWriter = new PrintWriter(System.out);\n\t\tvar solver : Solve = new Solve();\n\t\tsolver.solve(cin, cout);\n\t\tcout.close();\n\t}\n}\n\nclass Solve\n{\n\tdef solve (cin : InputReader, cout : PrintWriter)\n\t{\n\t\tvar n : Int = 0;\n\t\tvar hash : Array[Int] = new Array[Int](1001);\n\t\tvar hash1 : Array[Int] = new Array[Int](1001);\n\t\tvar x, y : Int = 0;\n\t\tvar i : Int = 0;\n\t\tvar flag : Int = 0;\n\t\tval loop1, loop2 : Breaks = new Breaks();\n\t\tn = cin.nextInt();\n\t\tloop1.breakable\n\t\t{\n\t\t\tfor (i <- 1 to n)\n\t\t\t{\n\t\t\t\tx = cin.nextInt(); y = cin.nextInt();\n\t\t\t\thash(i) = x;\n\t\t\t\thash1(i) = y;\n\t\t\t\tif (x != y) \n\t\t\t\t{\n\t\t\t\t\tflag = math.max(flag, 2);\n\t\t\t\t\tloop1.break;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tloop1.breakable\n\t\t{\n\t\t\tfor (i <- 1 to n)\n\t\t\t{\n\t\t\t\tloop2.breakable\n\t\t\t\t{\n\t\t\t\t\tfor (j <- 1 until i)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (hash(i) > hash(j)) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tflag = math.max(flag, 1);\n\t\t\t\t\t\t\tloop2.break;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (flag == 0) println(\"maybe\");\n\t\telse if (flag == 1) println(\"unrated\");\n\t\telse if (flag == 2) println(\"rated\");\n\t}\n}\n\nclass InputReader (stream : InputStream)\n{\n var reader : BufferedReader = new BufferedReader(new InputStreamReader(stream), 32768);\n var tokenizer : StringTokenizer = null;\n\n \tdef next () : String = \n \t{\n \t\twhile (tokenizer == null || !tokenizer.hasMoreTokens())\n \t\t{\n \t\t\ttry \n \t\t\t{\n \t\t\t\ttokenizer = new StringTokenizer(reader.readLine());\n \t\t\t}\n \t\t\tcatch\n \t\t\t{\n \t\t\t\tcase ex : java.io.IOException => throw new RuntimeException(ex);\n \t\t\t}\n \t\t}\n \t\treturn tokenizer.nextToken();\n \t}\n\n \tdef nextInt () : Int =\n \t{\n \t\treturn java.lang.Integer.parseInt(next());\n \t}\n\n \tdef nextLong () : Long =\n \t{\n \t\treturn java.lang.Long.parseLong(next());\n \t}\n\n}"}, {"source_code": "import java.io.BufferedReader;\nimport java.util.StringTokenizer;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\n\nobject Main {\n\tdef main(args: Array[String]): Unit = {\n\t\tvar cin : InputReader = new InputReader(System.in);\n\t\tvar n : Int = 0;\n\t\tvar hash : Array[Int] = new Array[Int](1001);\n\t\tvar hash1 : Array[Int] = new Array[Int](1001);\n\t\tvar x, y : Int = 0;\n\t\tvar i : Int = 0;\n\t\tvar flag : Int = 0;\n\t\tn = cin.nextInt();\n\t\tfor (i <- 1 to n)\n\t\t{\n\t\t\tx = cin.nextInt(); y = cin.nextInt();\n\t\t\thash(i) = x;\n\t\t\thash1(i) = y;\n\t\t\tif (x != y) flag = math.max(flag, 2);\n\t\t}\n\t\tfor (i <- 1 to n)\n\t\t{\n\t\t\tfor (j <- 1 until i)\n\t\t\t{\n\t\t\t\tif (hash(i) > hash(j)) flag = math.max(flag, 1);\n\t\t\t}\n\t\t}\n\t\tif (flag == 0) println(\"maybe\");\n\t\telse if (flag == 1) println(\"unrated\");\n\t\telse if (flag == 2) println(\"rated\");\n\t}\n}\n\nclass InputReader (stream : InputStream)\n{\n var reader : BufferedReader = new BufferedReader(new InputStreamReader(stream), 32768);\n var tokenizer : StringTokenizer = null;\n\n \tdef next () : String = \n \t{\n \t\twhile (tokenizer == null || !tokenizer.hasMoreTokens())\n \t\t{\n \t\t\ttry \n \t\t\t{\n \t\t\t\ttokenizer = new StringTokenizer(reader.readLine());\n \t\t\t}\n \t\t\tcatch\n \t\t\t{\n \t\t\t\tcase ex : java.io.IOException => throw new RuntimeException(ex);\n \t\t\t}\n \t\t}\n \t\treturn tokenizer.nextToken();\n \t}\n\n \tdef nextInt () : Int =\n \t{\n \t\treturn java.lang.Integer.parseInt(next());\n \t}\n\n \tdef nextLong () : Long =\n \t{\n \t\treturn java.lang.Long.parseLong(next());\n \t}\n\n}"}], "negative_code": [{"source_code": "object A extends App {\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n val n = nextInt\n var i = 0\n val a = scala.collection.mutable.ArrayBuffer[(Int, Int)]()\n for (i <- 0 until n) {\n val s = nextInt\n val r = nextInt\n val o = (s, r)\n a += o\n \n }\n var mx = Int.MaxValue\n for (i <- 0 until n) {\n if (a(i)._1 != a(i)._2) {\n println(\"rated\")\n sys.exit(0)\n }\n if (a(i)._1 > mx) {\n println(\"unrated\")\n sys.exit(0)\n }\n mx = a(i)._1\n }\n println(\"maybe\")\n}"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n //FIXME Console.setOut(new java.io.BufferedOutputStream(Console.out))\n var maybe, changed = false\n var id = 0\n var prev = Int.MaxValue\n val xs = Array.fill(n) {\n val Array(a, b) = readInts(2)\n if (a == prev) maybe = true\n if (a != b) changed = true\n id += 1\n prev = a\n (a, b, id)\n }\n\n\n println(if (changed) \"rated\" else if (maybe) \"maybe\" else \"unrated\")\n\n Console.flush\n}\n"}, {"source_code": "//package p807\n\n/**\n * Created by velizar on 16/05/17.\n */\nobject A extends App {\n import scala.io.Source\n\n val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(\" \").map(_.toInt))\n val Array(n) = input(0)\n val anyChanged = input.drop(1).exists{ case Array(a, b) => a != b }\n val heads = input.drop(1).map(_.head)\n if (anyChanged)\n print(\"rated\")\n else if (heads.length == heads.distinct.length)\n print(\"unrated\")\n else\n print(\"maybe\")\n}\n"}, {"source_code": "import java.io.BufferedReader;\nimport java.util.StringTokenizer;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\n\nobject Main {\n\tdef main(args: Array[String]): Unit = {\n\t\tvar cin : InputReader = new InputReader(System.in);\n\t\tvar n : Int = 0;\n\t\tvar hash : Array[Int] = new Array[Int](4127);\n\t\tvar x, y : Int = 0;\n\t\tvar i : Int = 0;\n\t\tvar flag : Int = 0;\n\t\tvar flagtmp : Int = 0;\n\t\tn = cin.nextInt();\n\t\tfor (i <- 1 to n)\n\t\t{\n\t\t\tx = cin.nextInt(); y = cin.nextInt();\n\t\t\tif (n == 1000 && i == 1 && x == 1998) flagtmp = 1;\n\t\t\thash(x) = hash(x) + 1; \n\t\t\thash(y) = hash(y) + 1;\n\t\t\tif (x != y) flag = math.max(flag, 2);\n\t\t}\n\t\tfor (i <- 1 to 4126)\n\t\t{\n\t\t\tif (hash(i) > 2)\n\t\t\t{\n\t\t\t\tflag = math.max(flag, 1);\n\t\t\t\tif (flagtmp == 1) println(i + \" \" + hash(i));\n\t\t\t}\n\t\t\tif (hash(i) % 2 == 1)\n\t\t\t{\n\t\t\t\tflag = math.max(flag, 2);\n\t\t\t}\n\t\t}\n\t\tif (flag == 0) println(\"unrated\");\n\t\telse if (flag == 1) println(\"maybe\");\n\t\telse if (flag == 2) println(\"rated\");\n\t}\n}\n\nclass InputReader (stream : InputStream)\n{\n var reader : BufferedReader = new BufferedReader(new InputStreamReader(stream), 32768);\n var tokenizer : StringTokenizer = null;\n\n \tdef next () : String = \n \t{\n \t\twhile (tokenizer == null || !tokenizer.hasMoreTokens())\n \t\t{\n \t\t\ttry \n \t\t\t{\n \t\t\t\ttokenizer = new StringTokenizer(reader.readLine());\n \t\t\t}\n \t\t\tcatch\n \t\t\t{\n \t\t\t\tcase ex : java.io.IOException => throw new RuntimeException(ex);\n \t\t\t}\n \t\t}\n \t\treturn tokenizer.nextToken();\n \t}\n\n \tdef nextInt () : Int =\n \t{\n \t\treturn java.lang.Integer.parseInt(next());\n \t}\n\n \tdef nextLong () : Long =\n \t{\n \t\treturn java.lang.Long.parseLong(next());\n \t}\n\n}"}, {"source_code": "import java.io.BufferedReader;\nimport java.util.StringTokenizer;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\n\nobject Main {\n\tdef main(args: Array[String]): Unit = {\n\t\tvar cin : InputReader = new InputReader(System.in);\n\t\tvar n : Int = 0;\n\t\tvar hash : Array[Int] = new Array[Int](4127);\n\t\tvar x, y : Int = 0;\n\t\tvar i : Int = 0;\n\t\tvar flag : Int = 0;\n\t\tn = cin.nextInt();\n\t\tfor (i <- 1 to n)\n\t\t{\n\t\t\tx = cin.nextInt(); y = cin.nextInt();\n\t\t\thash(x) = hash(x) + 1; \n\t\t\thash(y) = hash(y) + 1;\n\t\t}\n\t\tfor (i <- 1 to 4126)\n\t\t{\n\t\t\tif (hash(i) > 2)\n\t\t\t{\n\t\t\t\tflag = math.max(flag, 1);\n\t\t\t}\n\t\t\tif (hash(i) % 2 == 1)\n\t\t\t{\n\t\t\t\tflag = math.max(flag, 2);\n\t\t\t}\n\t\t}\n\t\tif (flag == 0) println(\"unrated\");\n\t\telse if (flag == 1) println(\"maybe\");\n\t\telse if (flag == 2) println(\"rated\");\n\t}\n}\n\nclass InputReader (stream : InputStream)\n{\n var reader : BufferedReader = new BufferedReader(new InputStreamReader(stream), 32768);\n var tokenizer : StringTokenizer = null;\n\n \tdef next () : String = \n \t{\n \t\twhile (tokenizer == null || !tokenizer.hasMoreTokens())\n \t\t{\n \t\t\ttry \n \t\t\t{\n \t\t\t\ttokenizer = new StringTokenizer(reader.readLine());\n \t\t\t}\n \t\t\tcatch\n \t\t\t{\n \t\t\t\tcase ex : java.io.IOException => throw new RuntimeException(ex);\n \t\t\t}\n \t\t}\n \t\treturn tokenizer.nextToken();\n \t}\n\n \tdef nextInt () : Int =\n \t{\n \t\treturn java.lang.Integer.parseInt(next());\n \t}\n\n \tdef nextLong () : Long =\n \t{\n \t\treturn java.lang.Long.parseLong(next());\n \t}\n\n}"}, {"source_code": "import java.io.BufferedReader;\nimport java.util.StringTokenizer;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\n\nobject Main {\n\tdef main(args: Array[String]): Unit = {\n\t\tvar cin : InputReader = new InputReader(System.in);\n\t\tvar n : Int = 0;\n\t\tvar hash : Array[Int] = new Array[Int](4127);\n\t\tvar x, y : Int = 0;\n\t\tvar i : Int = 0;\n\t\tvar flag : Int = 0;\n\t\tvar flagtmp : Int = 0;\n\t\tn = cin.nextInt();\n\t\tfor (i <- 1 to n)\n\t\t{\n\t\t\tx = cin.nextInt(); y = cin.nextInt();\n\t\t\tif (n == 1000 && i == 1 && x == 1998) flagtmp = 1;\n\t\t\thash(x) = hash(x) + 1; \n\t\t\thash(y) = hash(y) + 1;\n\t\t\tif (x != y) flag = math.max(flag, 2);\n\t\t}\n\t\tfor (i <- 1 to 4126)\n\t\t{\n\t\t\tif (hash(i) > 2)\n\t\t\t{\n\t\t\t\tflag = math.max(flag, 1);\n\t\t\t\tif (flagtmp == 1) println(i);\n\t\t\t}\n\t\t\tif (hash(i) % 2 == 1)\n\t\t\t{\n\t\t\t\tflag = math.max(flag, 2);\n\t\t\t}\n\t\t}\n\t\tif (flag == 0) println(\"unrated\");\n\t\telse if (flag == 1) println(\"maybe\");\n\t\telse if (flag == 2) println(\"rated\");\n\t}\n}\n\nclass InputReader (stream : InputStream)\n{\n var reader : BufferedReader = new BufferedReader(new InputStreamReader(stream), 32768);\n var tokenizer : StringTokenizer = null;\n\n \tdef next () : String = \n \t{\n \t\twhile (tokenizer == null || !tokenizer.hasMoreTokens())\n \t\t{\n \t\t\ttry \n \t\t\t{\n \t\t\t\ttokenizer = new StringTokenizer(reader.readLine());\n \t\t\t}\n \t\t\tcatch\n \t\t\t{\n \t\t\t\tcase ex : java.io.IOException => throw new RuntimeException(ex);\n \t\t\t}\n \t\t}\n \t\treturn tokenizer.nextToken();\n \t}\n\n \tdef nextInt () : Int =\n \t{\n \t\treturn java.lang.Integer.parseInt(next());\n \t}\n\n \tdef nextLong () : Long =\n \t{\n \t\treturn java.lang.Long.parseLong(next());\n \t}\n\n}"}, {"source_code": "import java.io.BufferedReader;\nimport java.util.StringTokenizer;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\n\nobject Main {\n\tdef main(args: Array[String]): Unit = {\n\t\tvar cin : InputReader = new InputReader(System.in);\n\t\tvar n : Int = 0;\n\t\tvar hash : Array[Int] = new Array[Int](4127);\n\t\tvar x, y : Int = 0;\n\t\tvar i : Int = 0;\n\t\tvar flag : Int = 0;\n\t\tvar flagtmp : Int = 0;\n\t\tn = cin.nextInt();\n\t\tfor (i <- 1 to n)\n\t\t{\n\t\t\tx = cin.nextInt(); y = cin.nextInt();\n\t\t\tif (n == 1000 && i == 1 && x == 1998) flagtmp = 1;\n\t\t\thash(x) = hash(x) + 1; \n\t\t\thash(y) = hash(y) + 1;\n\t\t\tif (x != y) flag = math.max(flag, 2);\n\t\t}\n\t\tfor (i <- 1 to 4126)\n\t\t{\n\t\t\tif (hash(i) > 2)\n\t\t\t{\n\t\t\t\tflag = math.max(flag, 1);\n\t\t\t\tif (flagtmp == 1) println(i + hash(i));\n\t\t\t}\n\t\t\tif (hash(i) % 2 == 1)\n\t\t\t{\n\t\t\t\tflag = math.max(flag, 2);\n\t\t\t}\n\t\t}\n\t\tif (flag == 0) println(\"unrated\");\n\t\telse if (flag == 1) println(\"maybe\");\n\t\telse if (flag == 2) println(\"rated\");\n\t}\n}\n\nclass InputReader (stream : InputStream)\n{\n var reader : BufferedReader = new BufferedReader(new InputStreamReader(stream), 32768);\n var tokenizer : StringTokenizer = null;\n\n \tdef next () : String = \n \t{\n \t\twhile (tokenizer == null || !tokenizer.hasMoreTokens())\n \t\t{\n \t\t\ttry \n \t\t\t{\n \t\t\t\ttokenizer = new StringTokenizer(reader.readLine());\n \t\t\t}\n \t\t\tcatch\n \t\t\t{\n \t\t\t\tcase ex : java.io.IOException => throw new RuntimeException(ex);\n \t\t\t}\n \t\t}\n \t\treturn tokenizer.nextToken();\n \t}\n\n \tdef nextInt () : Int =\n \t{\n \t\treturn java.lang.Integer.parseInt(next());\n \t}\n\n \tdef nextLong () : Long =\n \t{\n \t\treturn java.lang.Long.parseLong(next());\n \t}\n\n}"}], "src_uid": "88686e870bd3bfbf45a9b6b19e5ec68a"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M = ni()\n val A = na(N)\n val B = na(M)\n val sumA = A.reduce(_ ^ _)\n val sumB = B.reduce(_ ^ _)\n if (sumA != sumB) out.println(\"NO\")\n else {\n out.println(\"YES\")\n B(0) = A(0) ^ B(0) ^ sumA\n out.println(B.mkString(\" \"))\n REP(N - 1, 1) { i =>\n out.print(A(i))\n REP(M - 1) { _ =>\n out.print(s\" 0\")\n }\n out.println()\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object Main {\n import java.io._\nimport java.util.Scanner\n\nimport collection.mutable.HashMap\nimport scala.collection.{SortedSet, mutable}\nimport scala.util.Random\n protected val EPS = 1e-11\n\n private def default = (\n new StreamTokenizer(new InputStreamReader(System.in)),\n new Scanner(System.in),\n new PrintWriter(System.out)\n )\n\n val (in, ins, out) = {\n try {\n if (sys.props.contains(\"xDx\")) {\n (\n new StreamTokenizer(new FileReader(\"input.txt\")),\n new Scanner(new FileReader(\"input.txt\")),\n new PrintWriter(new FileWriter(\"output.txt\"))\n )\n } else {\n default\n }\n } catch {\n case _: Throwable => default\n }\n }\n\n private def nextInt = {\n in.nextToken\n in.nval.toInt\n }\n\n private def nextLong = {\n in.nextToken\n in.nval.toLong\n }\n\n\n private def nextDouble = {\n in.nextToken\n in.nval\n }\n\n\n private def nextString = {\n in.nextToken\n in.sval\n }\n\n private def nextChar = {\n in.nextToken\n in.ttype.toChar\n }\n\n def main(args: Array[String]): Unit = {\n try {\n new Run().run()\n } catch {\n case e: Throwable =>\n throw new RuntimeException(e)\n } finally out.close()\n }\n\n class Run {\n import collection.breakOut\n def run(): Unit = {\n val n = nextInt\n val m = nextInt\n val res = Array.ofDim[Int](n, m)\n var r1 = 0\n var r2 = 0\n var a0 = 0\n var b0 = 0\n for(i <- 0 until n) {\n val a = nextInt\n if(i == 0) {\n a0 = a\n } else {\n res(i)(0) = a\n }\n r1 ^= a\n }\n \n for(i <- 0 until m) {\n val b = nextInt\n if(i == 0) {\n b0 = b\n } else {\n res(0)(i) = b\n }\n r2 ^= b\n }\n if(r1 == r2) {\n println(\"YES\")\n res(0)(0) = r1 ^ a0 ^ b0\n for(i <- 0 until n) {\n println(res(i).mkString(\" \"))\n }\n }else {\n println(\"NO\")\n }\n }\n\n }\n\n}\n\n\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M = ni()\n val A = na(N)\n val B = na(M)\n val sumA = A.reduce(_ ^ _)\n val sumB = B.reduce(_ ^ _)\n if (sumA != sumB) out.println(\"NO\")\n else {\n out.println(\"YES\")\n B(0) = A(0) ^ B(0) ^ sumA\n out.println(B.mkString(\" \"))\n REP(N - 1, 1) { i =>\n out.print(A(i))\n REP(M - 1) { _ =>\n out.print(s\" 0\")\n }\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "3815d18843dbd15a73383d69eb6880dd"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toInt)\n val (sol, left) = line.foldLeft(true, 0) {\n case((false, _), el) => (false, 0)\n case((true, 0), el) if el % 2 == 0 => (true, 0)\n case((true, 0), el) => (true, 1)\n case((true, 1), el) if el % 2 != 0 => (true, 0)\n case((true, 1), el) if el == 0 => (false, 0)\n case((true, 1), el) => (true, 1)\n }\n if (sol && left == 0)\n println(\"YES\")\n else\n println(\"NO\")\n}\n", "positive_code": [{"source_code": "object CF376_2B extends App {\n readLine\n val a = readLine.split(\" \").map(_.toInt)\n println(solve(a))\n \n def solve(a: Array[Int]) : String = {\n var c = 0\n for (x <- a) {\n if (x == 0) {\n if (c == 1)\n return \"NO\"\n c = 0\n } else {\n c = (x+c)%2\n }\n } \n if (c == 0) \"YES\" else \"NO\"\n } \n}"}, {"source_code": "object B {\n def main(args: Array[String]): Unit = {\n val res = scala.io.StdIn.readLine\n val rres = scala.io.StdIn.readLine.split(\" 0 \").map(l => l.split(\" \").map(_.toInt).sum % 2).count(_ > 0) == 0\n\n val pr = if (rres) \"YES\" else \"NO\"\n print(pr)\n }\n}\n"}, {"source_code": "object B731 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n val alreadyOrdered = Array.fill[Int](n + 1)(0)\n alreadyOrdered(0) = input(0)\n alreadyOrdered(1) = input(0) % 2\n var i = 1\n var break = false\n while (!break && i < n) {\n val newDemand = input(i) - alreadyOrdered(i)\n if (newDemand < 0) {\n break = true\n } else if (newDemand % 2 == 1) {\n alreadyOrdered(i + 1) = 1\n }\n i += 1\n }\n if (break) {\n println(\"NO\")\n } else {\n if (alreadyOrdered(n) != 0) {\n println(\"NO\")\n } else {\n println(\"YES\")\n }\n }\n }\n}"}], "negative_code": [{"source_code": "object B731 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n\n val alreadyOrdered = Array.fill[Int](n+1)(0)\n alreadyOrdered(0) = input(0)\n alreadyOrdered(1) = input(0)%2\n var i = 1\n var break = false\n while(!break && i <= n-2) {\n val newDemand = input(i)-alreadyOrdered(i)\n if(newDemand < 0) {\n break = true\n } else if(newDemand % 2 == 1) {\n alreadyOrdered(i + 1) = 1\n }\n i += 1\n }\n if(break) {\n println(\"NO\")\n } else {\n if((input(n-1) - alreadyOrdered(n-1))% 2 == 1) {\n println(\"NO\")\n } else {\n println(\"YES\")\n }\n }\n }\n}"}, {"source_code": "object B731 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n if(input.length == 1) {\n println(if(input(0)%2 == 0) \"YES\" else \"NO\")\n } else {\n val alreadyOrdered = Array.fill[Int](n + 1)(0)\n alreadyOrdered(0) = input(0)\n alreadyOrdered(1) = input(0) % 2\n var i = 1\n var break = false\n while (!break && i <= n - 2) {\n val newDemand = input(i) - alreadyOrdered(i)\n if (newDemand < 0) {\n break = true\n } else if (newDemand % 2 == 1) {\n alreadyOrdered(i + 1) = 1\n }\n i += 1\n }\n if (break) {\n println(\"NO\")\n } else {\n if ((input(n - 1) - alreadyOrdered(n - 1)) % 2 == 1) {\n println(\"NO\")\n } else {\n println(\"YES\")\n }\n }\n }\n }\n}"}, {"source_code": "object B731 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n\n val alreadyOrdered = new Array[Int](n+10)\n alreadyOrdered(0) = input(0)\n alreadyOrdered(1) = input(0)%2\n var i = 1\n var break = false\n while(!break && i <= n-2) {\n if(input(i) > alreadyOrdered(i)) {\n break = true\n } else if((input(i)-alreadyOrdered(i)) % 2 == 1) {\n alreadyOrdered(i + 1) = 1\n }\n i += 1\n }\n if(!break) {\n println(\"NO\")\n } else {\n if((input(n-1) - alreadyOrdered(n-1))% 2 == 1) {\n println(\"NO\")\n } else {\n println(\"YES\")\n }\n }\n }\n}"}], "src_uid": "97697eba87bd21ae5c979a5ea7a81cb7"} {"source_code": "import java.io.ByteArrayInputStream\n\nimport scala.collection.mutable\n\nobject Main {\n\n var dddd = false\n\n def ptime() = if (dddd) println(System.currentTimeMillis())\n def delog(a: String) = if (dddd) println(a)\n\n def main(args: Array[String]) = {\n /** setup **/\n var debug: Object => Unit = null\n if (!args.isEmpty && args.head == \"test\") {\n dddd = true\n debug = println\n val TEST =\n \"\"\"17\n |25 29 37 207 122 189 118 42 54 95 154 160 162 225 228 237 248\n |19\n |25 29 248 37 147 209 42 54 255 95 154 160 162 225 228 237 73 248 10\n \"\"\".stripMargin\n System.setIn(new ByteArrayInputStream(TEST.getBytes))\n } else {\n debug = a => Unit\n }\n val input = scala.io.Source.stdin.getLines()\n\n /** parse **/ ptime()\n\n input.next()\n val q1 = input.next().split(\" \").map(_.toInt).toSeq.toArray[Int]\n input.next()\n val q2 = input.next().split(\" \").map(_.toInt).toSeq.toArray[Int]\n\n /** algorithm **/ ptime()\n\n\n final case class Case(_1: Int, _2: Seq[Int])\n val dp = Array.ofDim[Case](q1.length, q2.length)\n var max = Case(0, Seq.empty[Int])\n for (i1 <- q1.indices) {\n for (i2 <- q2.indices) {\n if (q1(i1) == q2(i2)) {\n val a = q1(i1)\n var m = Case(1, List(a): Seq[Int])\n for (k1 <- 0 until i1) {\n for (k2 <- 0 until i2) {\n if (q1(k1) == q2(k2) && q1(k1) < a) {\n val dd = dp(k1)(k2)\n if (dd._1 + 1> m._1) {\n m = Case(dd._1 + 1, a +: dd._2)\n }\n }\n }\n }\n dp(i1)(i2) = m\n if (m._1 > max._1) max = m\n }\n }\n }\n\n val sol = max._2.reverse\n\n\n // val t1 = q1.zipWithIndex.sortBy(_._1)\n // val t2 = q2.zipWithIndex.sortBy(_._1)\n //\n // val b = mutable.ArrayBuffer.empty[(Int, Seq[Int], Seq[Int])]\n //\n // var i1 = 0\n // var i2 = 0\n // while (i1 < t1.size && i2 < t2.size) {\n // val a1 = t1(i1)\n // val a2 = t2(i2)\n // if (a1._1 < a2._1) i1 += 1\n // else if (a2._1 < a1._1) i2 += 1\n // else {\n // val a = a1\n // var i1e = i1\n // while (i1e < t1.size && t1(i1e)._1 == a._1) i1e += 1\n // var i2e = i2\n // while (i2e < t2.size && t2(i2e)._1 == a._1) i2e += 1\n // b.append((a1._1, (i1 until i1e).map(a => t1(a)._2), (i2 until i2e).map(a => t2(a)._2)))\n // i1 = i1e\n // i2 = i2e\n // }\n // }\n //\n // ptime()\n // var indexes = mutable.HashMap.empty[(Int, Int), Seq[(Int, Int)]]\n //\n // for (fi <- b.indices.reverse) { // considering including the element i\n // val f = b(fi)\n // val prev = indexes\n // var max = if(prev.isEmpty) 0 else prev.values.maxBy(_.size).size\n // var n = prev.clone()\n // for (seq <- prev.values) {\n // val h = seq.head\n // if (seq.size + fi + 1 > max) {\n // if (h._1 + seq.size < max || h._2 + seq.size < max) {\n // n -= h\n // } else {\n // var added = false\n // for (ia <- f._2.reverse) {\n // for (ib <- f._3.reverse) {\n // if (!added && ia < h._1 && ib < h._2) {\n // val kk = (ia, ib)\n // val b = kk +: seq\n // val psize = n.get(kk).map(_.size).getOrElse(0)\n // if (b.size > psize) {\n // if (b.size > max) max = b.size\n // n += kk -> b\n // if (ia == h._1 - 1 && ib == h._2 - 1) { // this new thing is strictly better than the old one\n // n -= h\n // }\n // added = true\n // }\n // }\n // }\n // }\n // }\n // } else {\n // n -= h\n // }\n // }\n // val kk = (f._2.last, f._3.last)\n // if (max <= fi && max <= kk._1 && max <= kk._2) {\n // if (n.get(kk).isEmpty) n += kk -> Seq(kk)\n // }\n // indexes = n\n // }\n\n // val t = if (indexes.isEmpty) Seq.empty else indexes.values.maxBy(_.size)\n // val sol = t.map(i => q1(i._1))\n\n /** print **/ ptime()\n\n println(sol.length + \"\\n\" + sol.mkString(\" \"))\n }\n}", "positive_code": [{"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by jetblack20 on 02/07/15.\n */\nobject CommonSub extends App {\n\n val s = new Scanner(System.in)\n\n val n = s.nextInt()\n val a = (0 until n).map(x => s.nextInt()).toArray\n val m = s.nextInt()\n val b = (0 until m).map(x => s.nextInt()).toArray\n val trace = Array.ofDim[Int](n)\n var i = 1\n var j = 1\n\n val dp = Array.ofDim[Int](n, m)\n\n for {\n i <- 0 until n\n j <- 0 until m\n } {\n if (a(i) == b(j)) {\n dp(i)(j) = 1\n for {\n k <- 0 until i\n l <- 0 until j\n } {\n if (a(k) == b(l) && a(k) < a(i) && dp(i)(j) < dp(k)(l) + 1) {\n dp(i)(j) = dp(k)(l) + 1\n trace(i) = k\n }\n }\n }\n }\n\n\n var l = -1\n var ans = -1\n for {\n i <- 0 until n\n j <- 0 until m\n } {\n if (dp(i)(j) > ans) {\n ans = dp(i)(j)\n l = i\n }\n }\n\n val res = ArrayBuffer.empty[Int]\n var cnt = ans\n while (cnt > 0) {\n res.append(a(l))\n l = trace(l)\n cnt -= 1\n }\n println(ans)\n println(res.reverse.mkString(\" \"))\n}\n"}], "negative_code": [{"source_code": "import java.io.ByteArrayInputStream\n\nimport scala.collection.mutable\n\nobject Main {\n\n var dddd = false\n\n def ptime() = if (dddd) println(System.currentTimeMillis())\n\n def main(args: Array[String]) = {\n /** setup **/\n var debug: Object => Unit = null\n if (!args.isEmpty && args.head == \"test\") {\n dddd = true\n debug = println\n val TEST =\n \"\"\"20\n |7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207\n |20\n |7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207\n \"\"\".stripMargin\n System.setIn(new ByteArrayInputStream(TEST.getBytes))\n } else {\n debug = a => Unit\n }\n val input = scala.io.Source.stdin.getLines()\n\n ptime()\n /** parse **/\n\n input.next()\n val q1 = input.next().split(\" \").map(_.toInt).toSeq\n input.next()\n val q2 = input.next().split(\" \").map(_.toInt).toSeq\n\n ptime()\n /** algorithm **/\n\n val t1 = q1.zipWithIndex.sortBy(_._1)\n val t2 = q2.zipWithIndex.sortBy(_._1)\n\n val b = mutable.ArrayBuffer.empty[(Int, Seq[Int], Seq[Int])]\n\n\n var i1 = 0\n var i2 = 0\n // println(t1)\n // println(t2)\n while (i1 < t1.size && i2 < t2.size) {\n val a1 = t1(i1)\n val a2 = t2(i2)\n if (a1._1 < a2._1) i1 += 1\n else if (a2._1 < a1._1) i2 += 1\n else {\n val a = a1\n var i1e = i1\n while (i1e < t1.size && t1(i1e)._1 == a._1) i1e += 1\n var i2e = i2\n while (i2e < t2.size && t2(i2e)._1 == a._1) i2e += 1\n b.append((a1._1, (i1 until i1e).map(a => t1(a)._2), (i2 until i2e).map(a => t2(a)._2)))\n i1 = i1e\n i2 = i2e\n }\n }\n\n ptime()\n var indexes = mutable.HashSet.empty[Seq[(Int, Int)]]\n // println(b)\n\n var jj = 0\n for (f <- b.reverse) { // considering including the element i\n jj += 1\n println(jj)\n val prev = indexes\n var n = prev.clone()\n for (seq <- prev) {\n val h = seq.head\n var added = false\n for (ia <- f._2.reverse) {\n for (ib <- f._3.reverse) {\n if (!added && ia < h._1 && ib < h._2) {\n n += ((ia, ib) +: seq)\n if (ia == h._1 - 1 && ib == h._2 - 1) { // this new thing is strictly better than the old one\n n -= seq\n }\n added = true\n }\n }\n }\n }\n n += Seq((f._2.last, f._3.last))\n indexes = n\n }\n\n // println(indexes)\n\n ptime()\n val t = if (indexes.isEmpty) Seq.empty else indexes.maxBy(_.size)\n val sol = t.map(i => q1(i._1))\n /** print **/\n println(sol.length + \"\\n\" + sol.mkString(\" \"))\n }\n}"}, {"source_code": "import java.io.ByteArrayInputStream\n\nimport scala.collection.mutable\n\nobject Main {\n\n def main(args: Array[String]) = {\n /** setup **/\n var debug: Object => Unit = null\n if (!args.isEmpty && args.head == \"test\") {\n debug = println\n val TEST =\n \"\"\"5\n |1 2 0 2 1\n |3\n |1 0 1\n \"\"\".stripMargin\n System.setIn(new ByteArrayInputStream(TEST.getBytes))\n } else {\n debug = a => Unit\n }\n val input = scala.io.Source.stdin.getLines()\n\n /** parse **/\n\n input.next()\n val q1 = input.next().split(\" \").map(_.toInt).toSeq\n input.next()\n val q2 = input.next().split(\" \").map(_.toInt).toSeq\n\n /** algorithm **/\n\n val t1 = q1.zipWithIndex.sortBy(_._1)\n val t2 = q2.zipWithIndex.sortBy(_._1)\n\n val b = mutable.ArrayBuffer.empty[(Int, Seq[Int], Seq[Int])]\n\n\n var i1 = 0\n var i2 = 0\n println(t1)\n println(t2)\n while (i1 < t1.size && i2 < t2.size) {\n val a1 = t1(i1)\n val a2 = t2(i2)\n if (a1._1 < a2._1) i1 += 1\n else if (a2._1 < a1._1) i2 += 1\n else {\n val a = a1\n var i1e = i1\n while (i1e < t1.size && t1(i1e)._1 == a._1) i1e += 1\n var i2e = i2\n while (i2e < t2.size && t2(i2e)._1 == a._1) i2e += 1\n b.append((a1._1, (i1 until i1e).map(a => t1(a)._2), (i2 until i2e).map(a => t2(a)._2)))\n i1 = i1e\n i2 = i2e\n }\n }\n\n var indexes = List.empty[Seq[(Int, Int)]]\n\n println(b.mkString(\" \"))\n\n for (f <- b.reverse) { // considering including the element i\n val prev = indexes\n var n = indexes\n for (seq <- prev) {\n val h = seq.head\n for (ia <- f._2) {\n for (ib <- f._3) {\n if (ia < h._1 && ib < h._2) {\n n = ((ia, ib) +: seq) +: n\n }\n }\n }\n }\n for (ia <- f._2) {\n for (ib <- f._3) {\n n = Seq((ia, ib)) +: n\n }\n }\n indexes = n\n }\n\n println(indexes)\n\n val t = indexes.maxBy(_.size)\n val sol = t.map(i => q1(i._1))\n /** print **/\n println(sol.length + \"\\n\" + sol.mkString(\" \"))\n }\n}"}, {"source_code": "import java.io.ByteArrayInputStream\n\nimport scala.collection.mutable\n\nobject Main {\n\n def main(args: Array[String]) = {\n /** setup **/\n var debug: Object => Unit = null\n if (!args.isEmpty && args.head == \"test\") {\n debug = println\n val TEST =\n \"\"\"7\n |2 3 1 6 5 4 6\n |4\n |1 3 5 6\n \"\"\".stripMargin\n System.setIn(new ByteArrayInputStream(TEST.getBytes))\n } else {\n debug = a => Unit\n }\n val input = scala.io.Source.stdin.getLines()\n\n /** parse **/\n\n input.next()\n val q1 = input.next().split(\" \").map(_.toInt).toSeq\n input.next()\n val q2 = input.next().split(\" \").map(_.toInt).toSeq\n\n /** algorithm **/\n\n val t1 = q1.zipWithIndex.sortBy(_._1)\n val t2 = q2.zipWithIndex.sortBy(_._1)\n\n val b = mutable.ArrayBuffer.empty[(Int, Seq[Int], Seq[Int])]\n\n\n var i1 = 0\n var i2 = 0\n while (i1 < t1.size && i2 < t2.size) {\n val a1 = t1(i1)\n val a2 = t2(i2)\n if (a1._1 < a2._1) i1 += 1\n else if (a2._1 < a1._1) i2 += 1\n else {\n val a = a1\n var i1e = i1\n while (i1e < t1.size && t1(i1e)._1 == a._1) i1e += 1\n var i2e = i2\n while (i2e < t2.size && t2(i2e)._1 == a._1) i2e += 1\n b.append((a1._1, (i1 until i1e).map(a => t1(a)._2), (i2 until i2e).map(a => t2(a)._2)))\n i1 = i1e\n i2 = i2e\n }\n }\n\n var indexes = List.empty[Seq[(Int, Int)]]\n\n\n for (f <- b.reverse) { // considering including the element i\n val prev = indexes\n var n = indexes\n for (seq <- prev) {\n val h = seq.head\n for (ia <- f._2) {\n for (ib <- f._3) {\n if (ia < h._1 && ib < h._2) {\n n = ((ia, ib) +: seq) +: n\n }\n }\n }\n }\n for (ia <- f._2) {\n for (ib <- f._3) {\n n = Seq((ia, ib)) +: n\n }\n }\n indexes = n\n }\n\n\n val t = indexes.maxBy(_.size)\n val sol = t.map(i => t1(i._1)._1)\n /** print **/\n println(sol.length + \"\\n\" + sol.mkString(\" \"))\n }\n}"}, {"source_code": "import java.io.ByteArrayInputStream\n\nimport scala.collection.mutable\n\nobject Main {\n\n var dddd = false\n\n def ptime() = if (dddd) println(System.currentTimeMillis())\n def delog(a: String) = if (dddd) println(a)\n\n def main(args: Array[String]) = {\n /** setup **/\n var debug: Object => Unit = null\n if (!args.isEmpty && args.head == \"test\") {\n dddd = true\n debug = println\n val TEST =\n \"\"\"17\n |25 29 37 207 122 189 118 42 54 95 154 160 162 225 228 237 248\n |19\n |25 29 248 37 147 209 42 54 255 95 154 160 162 225 228 237 73 248 10\n \"\"\".stripMargin\n System.setIn(new ByteArrayInputStream(TEST.getBytes))\n } else {\n debug = a => Unit\n }\n val input = scala.io.Source.stdin.getLines()\n\n /** parse **/ ptime()\n\n input.next()\n var q1 = input.next().split(\" \").map(_.toInt).toSeq\n input.next()\n var q2 = input.next().split(\" \").map(_.toInt).toSeq\n\n /** algorithm **/ ptime()\n\n val t1 = q1.zipWithIndex.sortBy(_._1)\n val t2 = q2.zipWithIndex.sortBy(_._1)\n\n val b = mutable.ArrayBuffer.empty[(Int, Seq[Int], Seq[Int])]\n\n\n var i1 = 0\n var i2 = 0\n while (i1 < t1.size && i2 < t2.size) {\n val a1 = t1(i1)\n val a2 = t2(i2)\n if (a1._1 < a2._1) i1 += 1\n else if (a2._1 < a1._1) i2 += 1\n else {\n val a = a1\n var i1e = i1\n while (i1e < t1.size && t1(i1e)._1 == a._1) i1e += 1\n var i2e = i2\n while (i2e < t2.size && t2(i2e)._1 == a._1) i2e += 1\n b.append((a1._1, (i1 until i1e).map(a => t1(a)._2), (i2 until i2e).map(a => t2(a)._2)))\n i1 = i1e\n i2 = i2e\n }\n }\n\n ptime()\n var indexes = mutable.HashSet.empty[Seq[(Int, Int)]]\n\n for (fi <- b.indices.reverse) { // considering including the element i\n val f = b(fi)\n val prev = indexes\n val max = if(prev.isEmpty) 0 else prev.maxBy(_.size).size\n var n = prev.clone()\n for (seq <- prev) {\n if (seq.size + fi + 1 > max) {\n val h = seq.head\n var added = false\n for (ia <- f._2.reverse) {\n for (ib <- f._3.reverse) {\n if (!added && ia < h._1 && ib < h._2) {\n n += ((ia, ib) +: seq)\n if (ia == h._1 - 1 && ib == h._2 - 1) { // this new thing is strictly better than the old one\n n -= seq\n }\n added = true\n }\n }\n }\n } else {\n n -= seq\n }\n }\n if (max < fi) n += Seq((f._2.last, f._3.last))\n indexes = n\n }\n\n val t = if (indexes.isEmpty) Seq.empty else indexes.maxBy(_.size)\n val sol = t.map(i => q1(i._1))\n\n /** print **/ ptime()\n\n println(sol.length + \"\\n\" + sol.mkString(\" \"))\n }\n}"}, {"source_code": "import java.io.ByteArrayInputStream\n\nimport scala.collection.mutable\n\nobject Main {\n\n var debug: Object => Unit = null\n\n def ptime() = if (debug != null) println(System.currentTimeMillis())\n\n def main(args: Array[String]) = {\n /** setup **/\n if (!args.isEmpty && args.head == \"test\") {\n debug = println\n val TEST =\n \"\"\"20\n |7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207\n |20\n |7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207\n \"\"\".stripMargin\n System.setIn(new ByteArrayInputStream(TEST.getBytes))\n } else {\n debug = a => Unit\n }\n val input = scala.io.Source.stdin.getLines()\n\n ptime()\n /** parse **/\n\n input.next()\n val q1 = input.next().split(\" \").map(_.toInt).toSeq\n input.next()\n val q2 = input.next().split(\" \").map(_.toInt).toSeq\n\n ptime()\n /** algorithm **/\n\n val t1 = q1.zipWithIndex.sortBy(_._1)\n val t2 = q2.zipWithIndex.sortBy(_._1)\n\n val b = mutable.ArrayBuffer.empty[(Int, Seq[Int], Seq[Int])]\n\n\n var i1 = 0\n var i2 = 0\n // println(t1)\n // println(t2)\n while (i1 < t1.size && i2 < t2.size) {\n val a1 = t1(i1)\n val a2 = t2(i2)\n if (a1._1 < a2._1) i1 += 1\n else if (a2._1 < a1._1) i2 += 1\n else {\n val a = a1\n var i1e = i1\n while (i1e < t1.size && t1(i1e)._1 == a._1) i1e += 1\n var i2e = i2\n while (i2e < t2.size && t2(i2e)._1 == a._1) i2e += 1\n b.append((a1._1, (i1 until i1e).map(a => t1(a)._2), (i2 until i2e).map(a => t2(a)._2)))\n i1 = i1e\n i2 = i2e\n }\n }\n\n ptime()\n var indexes = mutable.HashSet.empty[Seq[(Int, Int)]]\n // println(b)\n\n var jj = 0\n for (f <- b.reverse) { // considering including the element i\n jj += 1\n println(jj)\n val prev = indexes\n var n = prev.clone()\n for (seq <- prev) {\n val h = seq.head\n var added = false\n for (ia <- f._2.reverse) {\n for (ib <- f._3.reverse) {\n if (!added && ia < h._1 && ib < h._2) {\n n += ((ia, ib) +: seq)\n if (ia == h._1 - 1 && ib == h._2 - 1) { // this new thing is strictly better than the old one\n n -= seq\n }\n added = true\n }\n }\n }\n }\n n += Seq((f._2.last, f._3.last))\n indexes = n\n }\n\n // println(indexes)\n\n ptime()\n val t = if (indexes.isEmpty) Seq.empty else indexes.maxBy(_.size)\n val sol = t.map(i => q1(i._1))\n /** print **/\n println(sol.length + \"\\n\" + sol.mkString(\" \"))\n }\n}"}, {"source_code": "import java.io.ByteArrayInputStream\n\nimport scala.collection.mutable\n\nobject Main {\n\n var dddd = false\n\n def ptime() = if (dddd) println(System.currentTimeMillis())\n def delog(a: String) = if (dddd) println(a)\n\n def main(args: Array[String]) = {\n /** setup **/\n var debug: Object => Unit = null\n if (!args.isEmpty && args.head == \"test\") {\n dddd = true\n debug = println\n val TEST =\n \"\"\"90\n |158 208 242 308 485 547 710 780 849 878 895 907 934 1031 1056 1129 1490 1633 2183 2289 2503 2710 2809 2979 6563 2991 3009 3667 3675 3913 4052 4159 4398 4443 4481 4518 4546 4720 1136 4745 5004 5219 5298 5302 5583 5601 5649 5729 5830 5883 6047 5226 6287 6583 6892 7031 7052 7107 7145 7283 7331 7471 2109 7481 7687 7700 7801 7841 7974 8036 8039 8247 8360 8361 8589 8631 8635 8694 8718 8773 8949 9180 9372 9547 9633 9643 9665 9695 9739 9861\n |99\n |388 158 208 242 308 485 547 710 780 849 878 1684 895 907 934 103 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207 7 17 24 27 36 45 62 92 93 94 98 112 114 138 143 156 173 199 204 207\n \"\"\".stripMargin\n System.setIn(new ByteArrayInputStream(TEST.getBytes))\n } else {\n debug = a => Unit\n }\n val input = scala.io.Source.stdin.getLines()\n\n /** parse **/ ptime()\n\n input.next()\n var q1 = input.next().split(\" \").map(_.toInt).toSeq\n input.next()\n var q2 = input.next().split(\" \").map(_.toInt).toSeq\n\n /** algorithm **/ ptime()\n\n val t1 = q1.zipWithIndex.sortBy(_._1)\n val t2 = q2.zipWithIndex.sortBy(_._1)\n\n val b = mutable.ArrayBuffer.empty[(Int, Seq[Int], Seq[Int])]\n\n var i1 = 0\n var i2 = 0\n while (i1 < t1.size && i2 < t2.size) {\n val a1 = t1(i1)\n val a2 = t2(i2)\n if (a1._1 < a2._1) i1 += 1\n else if (a2._1 < a1._1) i2 += 1\n else {\n val a = a1\n var i1e = i1\n while (i1e < t1.size && t1(i1e)._1 == a._1) i1e += 1\n var i2e = i2\n while (i2e < t2.size && t2(i2e)._1 == a._1) i2e += 1\n b.append((a1._1, (i1 until i1e).map(a => t1(a)._2), (i2 until i2e).map(a => t2(a)._2)))\n i1 = i1e\n i2 = i2e\n }\n }\n\n ptime()\n var indexes = mutable.HashMap.empty[(Int, Int), Seq[(Int, Int)]]\n\n for (fi <- b.indices.reverse) { // considering including the element i\n val f = b(fi)\n val prev = indexes\n val max = if(prev.isEmpty) 0 else prev.values.maxBy(_.size).size\n var n = prev.clone()\n for (seq <- prev.values) {\n val h = seq.head\n if (seq.size + fi + 1 > max) {\n if (h._1 + seq.size < max || h._2 + seq.size < max) {\n n -= h\n } else {\n var added = false\n for (ia <- f._2.reverse) {\n for (ib <- f._3.reverse) {\n if (!added && ia < h._1 && ib < h._2) {\n val kk = (ia, ib)\n val b = kk +: seq\n val psize = n.get(kk).map(_.size).getOrElse(0)\n if (b.size > psize) {\n n += kk -> b\n if (ia == h._1 - 1 && ib == h._2 - 1) { // this new thing is strictly better than the old one\n n -= h\n }\n added = true\n }\n }\n }\n }\n }\n } else {\n n -= h\n }\n }\n if (max <= fi) {\n val kk = (f._2.last, f._3.last)\n n += kk -> Seq(kk)\n }\n indexes = n\n }\n\n val t = if (indexes.isEmpty) Seq.empty else indexes.values.maxBy(_.size)\n val sol = t.map(i => q1(i._1))\n\n /** print **/ ptime()\n\n println(sol.length + \"\\n\" + sol.mkString(\" \"))\n }\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by jetblack20 on 02/07/15.\n */\nobject CommonSub extends App {\n\n val s = new Scanner(System.in)\n\n val n = s.nextInt()\n val a = (0 until n).map(x => s.nextInt()).toArray\n val m = s.nextInt()\n val b = (0 until m).map(x => s.nextInt()).toArray\n val trace = Array.ofDim[Int](n)\n var i = 1\n var j = 1\n\n val dp = Array.ofDim[Int](n, m)\n\n for {\n i <- 0 until n\n j <- 0 until m\n } {\n if (a(i) == b(j)) {\n dp(i)(j) = 1\n for {\n k <- 0 until i\n l <- 0 until j\n } {\n if (a(k) == b(l) && a(k) < a(i) && dp(i)(j) < dp(k)(l) + 1) {\n dp(i)(j) = dp(k)(l) + 1\n trace(i) = k\n }\n }\n }\n }\n\n var l = n - 1\n while (trace(l) == 0 && l > 0) l -= 1\n val ans = dp(l).max\n var res = ArrayBuffer.empty[Int]\n var cnt = ans\n while (cnt > 0) {\n res.append(a(l))\n l = trace(l)\n cnt -= 1\n }\n println(ans)\n println(res.reverse.mkString(\" \"))\n}\n"}], "src_uid": "dca6eee27f002413d5e2eaf28fd60750"} {"source_code": "object A extends App {\n import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}\n\n solve()\n\n def solve(): Unit = {\n val in = new StreamTokenizer(new BufferedReader(new InputStreamReader((System.in))))\n\n @inline def nextInt = {\n in.nextToken()\n in.nval.asInstanceOf[Int]\n }\n @inline def operations(a: Int, b: Int) = {\n val diff = b - a\n if (diff == 0) {\n 0\n } else if (diff > 0) {\n if (diff % 2 == 0) 2\n else 1\n } else {\n if (diff % 2 == 0) 1\n else 2\n }\n }\n\n val t = nextInt\n for (_ <- 1 to t) {\n val (a, b) = (nextInt, nextInt)\n println(operations(a, b))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C624(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C624(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val a = ni()\n val b = ni()\n\n if(a == b) {\n out.println(\"0\")\n } else if(a > b) {\n val x = a - b\n if(x % 2 == 0) {\n out.println(\"1\")\n } else out.println(\"2\")\n } else {\n val x = b - a\n if(x % 2 != 0) {\n out.println(\"1\")\n } else out.println(\"2\")\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "fcd55a1ca29e96c05a3b65b7a8103842"} {"source_code": "import java.util.Scanner\n\nimport scala.collection.immutable.HashSet\nimport scala.io.StdIn\n\nobject CodeForces extends App {\n\n val arr = StdIn.readLine().split(' ').map(_.toInt)\n val n = arr(0)\n val m = arr(1)\n\n val graph = Array.ofDim[List[Int]](n)\n\n for (_ <- 1 to m){\n val arr = StdIn.readLine().split(' ').map(_.toInt)\n val x = arr(0) - 1\n val y = arr(1) - 1\n if (graph(x) == null) graph(x) = List.empty\n if (graph(y) == null) graph(y) = List.empty\n\n graph(x) = y :: graph(x)\n graph(y) = x :: graph(y)\n }\n\n val used = Array.ofDim[Boolean](n)\n val set1 = collection.mutable.HashSet.empty[Int]\n val set2 = collection.mutable.HashSet.empty[Int]\n\n def dfs(x: Int,current: Int): Unit = {\n used(x) = true\n current match {\n case 0 => set1.add(x)\n case 1 => set2.add(x)\n case _ => throw new Exception(\"wtf\")\n }\n graph(x)\n .filter(!used(_))\n .foreach(dfs(_, (current + 1) % 2))\n }\n\n for(i <- 0 until n) {\n if(!used(i) && graph(i) != null) dfs(i, 0)\n }\n\n if(set1.intersect(set2).isEmpty) {\n println(set1.size)\n set1.foreach({el =>\n print(el + 1)\n print(\" \")\n })\n println()\n println(set2.size)\n set2.foreach({el =>\n print(el + 1)\n print(\" \")\n })\n } else println(-1)\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable.ListBuffer\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C360A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C360A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val m = ni()\n\n g = Array.fill[ListBuffer[Int]](n)(new ListBuffer[Int])\n\n REP(m) { _ =>\n val u = ni()\n val v = ni()\n\n g(u-1) += v-1\n g(v-1) += u-1\n }\n\n marked = Array.fill(n)(-1)\n REP(n) { i =>\n if(marked(i) == -1) {\n marked(i) = 0\n fill(i)\n }\n }\n\n var yes = true\n REP(n) { i =>\n val c = marked(i)\n yes = yes & g(i).forall(p => marked(p) == (c^1))\n }\n if(!yes) {\n out.println(-1)\n } else {\n val x = marked.zipWithIndex.filter(_._1 == 0).map(_._2 + 1)\n out.println(x.length)\n out.println(x.mkString(\" \"))\n val y = marked.zipWithIndex.filter(_._1 == 1).map(_._2 + 1)\n out.println(y.length)\n out.println(y.mkString(\" \"))\n }\n }\n\n var g: Array[ListBuffer[Int]] = _\n var marked: Array[Int] = _\n\n def fill(u: Int) {\n val x = marked(u)\n g(u).foreach { f =>\n if(marked(f) == -1) {\n marked(f) = x^1\n fill(f)\n }\n }\n }\n}\n"}, {"source_code": "object A687 {\n def mark(\n edges: Array[Seq[Int]],\n color: Array[Int],\n now: Int,\n colorToAssign: Int\n ): Boolean = {\n //println(s\"Coloring $now the color $colorToAssign\")\n color(now) = colorToAssign\n\n val nextColor = 3 - colorToAssign\n\n edges(now).map {\n case next if (color(next) == 0) =>\n if (!mark(edges, color, next, nextColor)) return false\n case next if (color(next) != nextColor) =>\n return false\n case _ => // no op\n }\n\n return true\n }\n\n def main(args: Array[String]) = {\n val n :: m :: rest = readLine.split(' ').map { _.toInt }.toList\n val edges = Array.ofDim[Seq[Int]](n)\n\n (0 until n).map { case node => edges(node) = Seq[Int]()}\n\n (1 to m).map { case l =>\n val u :: v :: rest = readLine.split(' ').map { _.toInt}.toList\n edges(u - 1) = edges(u - 1) :+ (v - 1)\n edges(v - 1) = edges(v - 1) :+ (u - 1)\n }\n\n val color = Array.ofDim[Int](n)\n\n val result = (0 until n).map { case node =>\n if (color(node) == 0) mark(edges, color, node, 1)\n }\n .exists(_ == false)\n\n if (result) {\n println(-1)\n } else {\n println(color.count(_ == 1))\n println(color\n .zipWithIndex\n .filter{ case(c, n) => c == 1 }\n .map{ case(_, n) => n + 1 }\n .mkString(\" \"))\n println(color.count(_ == 2))\n println(color\n .zipWithIndex\n .filter{ case(c, n) => c == 2 }\n .map{ case(_, n) => n + 1}\n .mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "object A687 {\n def mark(\n edges: Array[Seq[Int]],\n color: Array[Int],\n now: Int,\n colorToAssign: Int\n ): Boolean = {\n //println(s\"Coloring $now the color $colorToAssign\")\n color(now) = colorToAssign\n\n val nextColor = 3 - colorToAssign\n\n edges(now).map {\n case next if (color(next) == 0) =>\n if (!mark(edges, color, next, nextColor)) return false\n case next if (color(next) != nextColor) =>\n return false\n case _ => // no op\n }\n\n return true\n }\n\n def main(args: Array[String]) = {\n val n :: m :: rest = readLine.split(' ').map { _.toInt }.toList\n val edges = Array.ofDim[Seq[Int]](n)\n\n (0 until n).map { case node => edges(node) = Seq[Int]()}\n\n (1 to m).map { case l =>\n val u :: v :: rest = readLine.split(' ').map { _.toInt}.toList\n edges(u - 1) = edges(u - 1) :+ (v - 1)\n edges(v - 1) = edges(v - 1) :+ (u - 1)\n }\n\n val color = Array.ofDim[Int](n)\n\n val result = (0 until n).map { case node =>\n if (color(node) == 0) mark(edges, color, node, 1)\n }\n .exists(_ == false)\n\n if (result) {\n println(-1)\n } else {\n val (left, right) = color.zipWithIndex.partition { case (c, i) => c == 1 }\n println(left.length)\n println(left.map { case (_, i) => i + 1}.mkString(\" \"))\n println(right.length)\n println(right.map { case (_, i) => i + 1}.mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _688C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val v, e = read[Int]\n val graph = map[Int] to mutable.Set.empty[Int]\n repeat(e) {\n val u, v = read[Int]\n graph(u) += v\n graph(v) += u\n }\n val pari, arya = mutable.Set.empty[Int]\n\n def dfs(i: Int, fromPari: Boolean): Unit = {\n val side = if (fromPari) pari else arya\n side += i\n //debug(i, fromPari, pari, arya)\n graph(i) foreach {\n case j if pari(j) => require(!fromPari)\n case j if arya(j) => require(fromPari)\n case j => dfs(j, !fromPari)\n }\n }\n\n try {\n (1 to v).foreach(i => if(!pari(i) && !arya(i)) dfs(i, fromPari = true))\n write(pari.size)\n .writeLine()\n .writeAll(pari)\n .writeLine()\n .write(arya.size)\n .writeLine()\n .writeAll(arya)\n } catch {\n case _: Throwable => write(-1)\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toYesNo = if(x) \"yes\" else \"no\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def bitCount: Int = java.lang.Integer.bitCount(x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeLine(obj: Any*): this.type = {\n if (obj.isEmpty) printer.println() else obj foreach printer.println\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.collection.mutable\n\nobject problem_C{\n class Graph[T] {\n type Vertex = T\n type GraphMap = Map[Vertex, Set[Vertex]]\n var g:GraphMap = Map()\n\n def DFS: Option[mutable.Map[Vertex, Int]] = {\n\n val colors = mutable.Map[Vertex, Int]()\n def nextColor(color: Int) = if (color == 1) 2 else 1\n def dfs(color: Int, v: Vertex): Boolean = {\n if (colors.get(v).isDefined) {\n colors(v) == color\n }\n else {\n colors += (v -> color)\n g(v).forall(dfs(nextColor(color),_))\n }\n }\n\n if (g.keys.forall(v => if (colors.get(v).isEmpty) dfs(1,v) else true))\n Some(colors)\n else\n None\n }\n\n def toCF(ans: Option[mutable.Map[Int, Int]]) = ans match {\n case None => \"-1\"\n case Some(map) =>\n val (list1t, list2t) = map.toList.partition(_._2 == 1)\n val list1 = list1t.map(_._1)\n val list2 = list2t.map(_._1)\n\n val str = new StringBuffer(\"\")\n\n str.append(list1.length).append(\"\\n\")\n list1.foreach(str.append(_).append(\" \"))\n str.append(\"\\n\").append(list2.length).append(\"\\n\")\n list2.foreach(str.append(_).append(\" \"))\n\n str.toString\n }\n\n }\n\n\n\n\n def main(args: Array[String]) = {\n\n val scanner = new java.util.Scanner(System.in)\n val n = scanner.nextInt()\n val m = scanner.nextInt()\n\n val edge = new Array[(Int,Int)](m)\n\n 0 to m-1 foreach {edge(_) = (scanner.nextInt, scanner.nextInt)}\n\n val intGraph = new Graph[Int]\n\n val adjacencyList =\n (edge ++ edge.map { case (a, b) => (b, a) })\n .groupBy[Int] {_._1}\n .map(x => x match {case (k,seq) => (k, seq.map(_._2).toSet)})\n\n val isolatedPoints = (1 until n+1).filter(adjacencyList.get(_).isEmpty).map((_, Set[Int]()))\n\n intGraph.g = adjacencyList ++ isolatedPoints\n\n\n //scary\n println(intGraph.toCF(intGraph.DFS))\n\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject problem_C_2{\n class Graph {\n var g: Array[mutable.Set[Int]] = Array()\n\n def DFS: Option[mutable.Map[Int, Int]] = {\n\n val colors = mutable.Map[Int, Int]()\n def nextColor(color: Int) = if (color == 1) 2 else 1\n def dfs(color: Int, v: Int): Boolean = {\n if (colors.get(v).isDefined) {\n colors(v) == color\n }\n else {\n colors += (v -> color)\n g(v).forall(dfs(nextColor(color),_))\n }\n }\n\n if ((1 to g.length - 1) forall { i => if (colors.get(i).isEmpty) dfs(1,i) else true }) {\n Some(colors)\n }\n else{\n None\n }\n\n }\n\n def toCF(ans: Option[mutable.Map[Int, Int]]) = ans match {\n case None => \"-1\"\n case Some(map) =>\n\n //if (g.length > 50000) println(\"i'm here1\")\n\n val (list1t, list2t) = map.toList.partition(_._2 == 1)\n val list1 = list1t.map(_._1)\n val list2 = list2t.map(_._1)\n\n\n val str = new StringBuffer(\"\")\n\n //if (g.length > 50000) println(\"i'm here2\")\n\n str.append(list1.length).append(\"\\n\")\n list1.foreach(str.append(_).append(\" \"))\n str.append(\"\\n\").append(list2.length).append(\"\\n\")\n list2.foreach(str.append(_).append(\" \"))\n\n //if (g.length > 50000) println(\"i'm here3\")\n\n str.toString\n }\n\n }\n\n\n\n\n def main(args: Array[String]) = {\n\n val scanner = new java.util.Scanner(System.in)\n val n = scanner.nextInt()\n val m = scanner.nextInt()\n\n val adjacencyList = Array.fill[mutable.Set[Int]](n + 1)(mutable.Set())\n 0 to m-1 foreach {t =>\n val i = scanner.nextInt; val j = scanner.nextInt\n adjacencyList(i).add(j)\n adjacencyList(j).add(i)\n }\n\n val graph = new Graph\n graph.g = adjacencyList\n\n println(graph.toCF(graph.DFS))\n\n }\n\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\n//https://codeforces.com/problemset/problem/687/A\nobject NPHardProblem {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n val arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n val graph=Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())\n for(i<- 0 until m){\n val edges=in.readLine().split(\" \").map(_.toInt-1)\n graph(edges(0))+=(edges(1))\n graph(edges(1))+=(edges(0))\n }\n isBipartiteGraph(graph,n)\n }\n def isBipartiteGraph(graph: Array[ArrayBuffer[Int]],n:Int): Unit = {\n\n //The idea is to color the graph vertices in two color and two adjacent vertex can't have same color\n //Using DFS we will color the graph; if a vertex is having no color (0) then make it 1 and processed further\n //If we come across a vertex with ambiguity then we can say Bi-Partition is not possible\n val color = Array.fill[Int](n)(0)\n for (i <- 0 until n) {\n if (color(i) == 0) {\n color(i) = 1\n }\n if (!dfsToColorGraph(graph, i, color)) {\n println(\"-1\")\n return\n }\n }\n\n var set1Count=0\n var set2Count=0\n var set1=ArrayBuffer[Int]()\n var set2=ArrayBuffer[Int]()\n for(i<- 0 until graph.length){\n if(color(i)==1){\n set1+=(i+1)\n set1Count+=1\n }else if(color(i)==2){\n set2+=(i+1)\n set2Count+=1\n }\n }\n println(set2Count)\n println(set2.mkString(\" \"))\n println(set1Count)\n println(set1.mkString(\" \"))\n }\n\n def dfsToColorGraph(graph: Array[ArrayBuffer[Int]], u: Int, color: Array[Int]): Boolean = {\n\n for (v <- 0 until graph(u).length) {\n if (color(graph(u)(v)) == 0) {\n color(graph(u)(v)) = (if (color(u) == 1) 2 else 1)\n if (!dfsToColorGraph(graph, graph(u)(v), color)) {\n return false\n }\n } else {\n if (color(u) == color(graph(u)(v))) {\n return false\n }\n }\n }\n\n return true\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject NPHardProblem {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n val arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n val graph=Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())\n for(i<- 0 until m){\n val edges=in.readLine().split(\" \").map(_.toInt-1)\n graph(edges(0))+=(edges(1))\n graph(edges(1))+=(edges(0))\n }\n isBipartiteGraph(graph,n)\n }\n def isBipartiteGraph(graph: Array[ArrayBuffer[Int]],n:Int): Unit = {\n\n //The idea is to color the graph vertices in two color and two adjacent vertex can't have same color\n //Using DFS we will color the graph; if a vertex is having no color (0) then make it 1 and processed further\n //If we come across a vertex with ambiguity then we can say Bi-Partition is not possible\n val color = Array.fill[Int](n)(0)\n for (i <- 0 until n) {\n if (color(i) == 0) {\n color(i) = 1\n }\n if (!dfsToColorGraph(graph, i, color)) {\n println(\"-1\")\n return\n }\n }\n\n var set1Count=0\n var set2Count=0\n var set1=ArrayBuffer[Int]()\n var set2=ArrayBuffer[Int]()\n for(i<- 0 until graph.length){\n if(color(i)==1){\n set1+=(i+1)\n set1Count+=1\n }else if(color(i)==2){\n set2+=(i+1)\n set2Count+=1\n }\n }\n println(set2Count)\n println(set2.mkString(\" \"))\n println(set1Count)\n println(set1.mkString(\" \"))\n }\n\n def dfsToColorGraph(graph: Array[ArrayBuffer[Int]], u: Int, color: Array[Int]): Boolean = {\n\n for (v <- 0 until graph(u).length) {\n if (color(graph(u)(v)) == 0) {\n color(graph(u)(v)) = (if (color(u) == 1) 2 else 1)\n if (!dfsToColorGraph(graph, graph(u)(v), color)) {\n return false\n }\n } else {\n if (color(u) == color(graph(u)(v))) {\n return false\n }\n }\n }\n\n return true\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val graph = Array.fill(n){List.empty[Int]}\n val taken = Array.ofDim[Int](n)\n (1 to m).foreach { _ =>\n val Array(from, to) = in.next().split(' ').map(_.toInt - 1)\n graph(from) ::= to\n graph(to) ::= from\n }\n var stop = false\n val isGood = graph.indices.foldLeft(true){\n case (false, _) => false\n case (true, i) =>\n if (taken(i) == 0) {\n taken(i) = 1\n var expand = graph(i)\n var shouldBe = 2\n var good = true\n while (expand.nonEmpty) {\n if (expand.exists(j => taken(j) != 0 && taken(j) != shouldBe)) {\n expand = Nil\n good = false\n } else {\n expand = expand.filter(j => taken(j) == 0)\n expand.foreach(j => taken(j) = shouldBe)\n shouldBe = if (shouldBe == 1) 2 else 1\n expand = expand.flatMap(graph)\n }\n }\n good\n }\n else true\n }\n if (isGood) {\n val first = taken.indices.filter(i => taken(i) == 1)\n val second = taken.indices.filter(i => taken(i) == 2)\n println(first.size)\n println(first.map(i => i + 1).mkString(\" \"))\n println(second.size)\n println(second.map(i => i + 1).mkString(\" \"))\n } else {\n println(-1)\n }\n}\n"}], "negative_code": [{"source_code": "object problem_C{\n def main(args: Array[String]) {\n val scanner = new java.util.Scanner(System.in)\n val n = scanner.nextInt()\n val m = scanner.nextInt()\n\n val colors: Array[Int] = new Array[Int](n + 1)\n val set = Array.fill[collection.mutable.Set[Int]](n + 1)(collection.mutable.Set())\n\n 1 to m foreach {i =>\n val i = scanner.nextInt; val j = scanner.nextInt\n set(i).add(j)\n set(j).add(i)\n }\n\n var color = 1\n def dfs(v: Int): Boolean ={\n if (colors(v) != 0) {\n //println(\"vert\" + v + \" (\" + colors(v) + \",\" + color +\")\")\n colors(v) == color\n }\n else {\n colors(v) = color\n color = if (color == 1) 2 else 1\n set(v).forall(dfs)\n }\n }\n\n def kek(): Boolean = {\n for(i <- 1 to n){\n if(colors(i) == 0)\n if(!dfs(i)) return false\n }\n\n true\n }\n\n if (!kek()) println(-1)\n else {\n val t1 = colors.count(x => x == 1)\n println(t1)\n for(i <- 1 to n){\n if(colors(i) == 1) print(i + \" \")\n }\n println()\n val t2 = colors.count(x => x == 2)\n println(t2)\n for(i <- 1 to n){\n if(colors(i) == 2) print(i + \" \")\n }\n }\n\n // println(colors)\n }\n}"}, {"source_code": "import scala.collection.mutable\n\nobject problem_C_2{\n class Graph {\n var g: Array[mutable.Set[Int]] = Array()\n\n def DFS: Option[mutable.Map[Int, Int]] = {\n\n val colors = mutable.Map[Int, Int]()\n def nextColor(color: Int) = if (color == 1) 2 else 1\n def dfs(color: Int, v: Int): Boolean = {\n if (colors.get(v).isDefined) {\n colors(v) == color\n }\n else {\n colors += (v -> color)\n g(v).forall(dfs(nextColor(color),_))\n }\n }\n\n if ((1 to g.length - 1) forall { i => if (colors.get(i).isEmpty) dfs(1,i) else true }) {\n Some(colors)\n }\n else{\n None\n }\n\n }\n\n def toCF(ans: Option[mutable.Map[Int, Int]]) = ans match {\n case None => \"-1\"\n case Some(map) =>\n \n if (g.length > 50000) println(\"i'm here1\")\n \n val (list1t, list2t) = map.toList.partition(_._2 == 1)\n val list1 = list1t.map(_._1)\n val list2 = list2t.map(_._1)\n\n\n val str = new StringBuffer(\"\")\n\n if (g.length > 50000) println(\"i'm here2\")\n \n str.append(list1.length).append(\"\\n\")\n list1.foreach(str.append(_).append(\" \"))\n str.append(\"\\n\").append(list2.length).append(\"\\n\")\n list2.foreach(str.append(_).append(\" \"))\n\n if (g.length > 50000) println(\"i'm here3\")\n\n str.toString\n }\n\n }\n\n\n\n\n def main(args: Array[String]) = {\n\n val scanner = new java.util.Scanner(System.in)\n val n = scanner.nextInt()\n val m = scanner.nextInt()\n\n val adjacencyList = Array.fill[mutable.Set[Int]](n + 1)(mutable.Set())\n 0 to m-1 foreach {t =>\n val i = scanner.nextInt; val j = scanner.nextInt\n adjacencyList(i).add(j)\n adjacencyList(j).add(i)\n }\n \n val graph = new Graph\n graph.g = adjacencyList\n\n println(graph.toCF(graph.DFS))\n\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject NPHardProblem {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n val arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n val graph=Array.fill[Int](n,n)(0)\n for(i<- 0 until m){\n val edges=in.readLine().split(\" \").map(_.toInt-1)\n graph(edges(0))(edges(1))=1\n }\n isBipartiteGraph(graph)\n }\n def isBipartiteGraph(graph: Array[Array[Int]]): Unit = {\n\n //The idea is to color the graph vertices in two color and two adjacent vertex can't have same color\n //Using DFS we will color the graph; if a vertex is having no color (0) then make it 1 and processed further\n //If we come across a vertex with ambiguity then we can say Bi-Partition is not possible\n val color = Array.fill[Int](graph.length)(0)\n for (i <- 0 until graph.length) {\n if (color(i) == 0) {\n color(i) = 1\n }\n if (!dfsToColorGraph(graph, i, color)) {\n println(\"-1\")\n return\n }\n }\n\n var set1Count=0\n var set2Count=0\n var set1=ArrayBuffer[Int]()\n var set2=ArrayBuffer[Int]()\n for(i<- 0 until graph.length){\n if(color(i)==1){\n set1+=(i+1)\n set1Count+=1\n }else if(color(i)==2){\n set2+=(i+1)\n set2Count+=1\n }\n }\n println(set2Count)\n println(set2.mkString(\" \"))\n println(set1Count)\n println(set1.mkString(\" \"))\n }\n\n def dfsToColorGraph(graph: Array[Array[Int]], n: Int, color: Array[Int]): Boolean = {\n\n for (i <- 0 until graph.length if (graph(n)(i) == 1)) {\n if (color(i) == 0) {\n color(i) = (if (color(n) == 1) 2 else 1)\n if (!dfsToColorGraph(graph, i, color)) {\n return false\n }\n } else {\n if (color(n) == color(i)) {\n return false\n }\n }\n }\n\n return true\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject NPHardProblem {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n val arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n val graph=Array.fill[Int](n,n)(0)\n for(i<- 0 until m){\n val edges=in.readLine().split(\" \").map(_.toInt-1)\n graph(edges(0))(edges(1))=1\n graph(edges(1))(edges(0))=1\n }\n isBipartiteGraph(graph)\n }\n def isBipartiteGraph(graph: Array[Array[Int]]): Unit = {\n\n //The idea is to color the graph vertices in two color and two adjacent vertex can't have same color\n //Using DFS we will color the graph; if a vertex is having no color (0) then make it 1 and processed further\n //If we come across a vertex with ambiguity then we can say Bi-Partition is not possible\n val color = Array.fill[Int](graph.length)(0)\n for (i <- 0 until 2) {\n if (color(i) == 0) {\n color(i) = 1\n }\n if (!dfsToColorGraph(graph, i, color)) {\n println(\"-1\")\n println(color.mkString(\", \"))\n return\n }\n }\n\n var set1Count=0\n var set2Count=0\n var set1=ArrayBuffer[Int]()\n var set2=ArrayBuffer[Int]()\n for(i<- 0 until graph.length){\n if(color(i)==1){\n set1+=(i+1)\n set1Count+=1\n }else if(color(i)==2){\n set2+=(i+1)\n set2Count+=1\n }\n }\n println(set2Count)\n println(set2.mkString(\" \"))\n println(set1Count)\n println(set1.mkString(\" \"))\n }\n\n def dfsToColorGraph(graph: Array[Array[Int]], n: Int, color: Array[Int]): Boolean = {\n\n for (i <- 0 until graph.length if (graph(n)(i) == 1)) {\n if (color(i) == 0) {\n color(i) = (if (color(n) == 1) 2 else 1)\n if (!dfsToColorGraph(graph, i, color)) {\n return false\n }\n } else {\n if (color(n) == color(i)) {\n return false\n }\n }\n }\n\n return true\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\nobject NPHardProblem {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n val arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n val graph=Array.fill[Int](n,n)(0)\n for(i<- 0 until m){\n val edges=in.readLine().split(\" \").map(_.toInt-1)\n graph(edges(0))(edges(1))=1\n }\n isBipartiteGraph(graph)\n }\n def isBipartiteGraph(graph: Array[Array[Int]]): Unit = {\n\n //The idea is to color the graph vertices in two color and two adjacent vertex can't have same color\n //Using DFS we will color the graph; if a vertex is having no color (0) then make it 1 and processed further\n //If we come across a vertex with ambiguity then we can say Bi-Partition is not possible\n val color = Array.fill[Int](graph.length)(0)\n for (i <- 0 until 2) {\n if (color(i) == 0) {\n color(i) = 1\n }\n if (!dfsToColorGraph(graph, i, color)) {\n println(\"-1\")\n return\n }\n }\n\n var set1Count=0\n var set2Count=0\n var set1=ArrayBuffer[Int]()\n var set2=ArrayBuffer[Int]()\n for(i<- 0 until graph.length){\n if(color(i)==1){\n set1+=(i+1)\n set1Count+=1\n }else if(color(i)==2){\n set2+=(i+1)\n set2Count+=1\n }\n }\n println(set2Count)\n println(set2.mkString(\" \"))\n println(set1Count)\n println(set1.mkString(\" \"))\n }\n\n def dfsToColorGraph(graph: Array[Array[Int]], n: Int, color: Array[Int]): Boolean = {\n\n for (i <- 0 until graph.length if (graph(n)(i) == 1)) {\n if (color(i) == 0) {\n color(i) = (if (color(n) == 1) 2 else 1)\n if (!dfsToColorGraph(graph, i, color)) {\n return false\n }\n } else {\n if (color(n) == color(i)) {\n return false\n }\n }\n }\n\n return true\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\n//https://codeforces.com/problemset/problem/687/A\nobject NPHardProblem {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n val arr=in.readLine().split(\" \").map(_.toInt)\n val n=arr(0)\n val m=arr(1)\n val graph=Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())\n for(i<- 0 until m){\n val edges=in.readLine().split(\" \").map(_.toInt-1)\n graph(edges(0))+=(edges(1))\n graph(edges(1))+=(edges(0))\n }\n isBipartiteGraph(graph,n)\n }\n def isBipartiteGraph(graph: Array[ArrayBuffer[Int]],n:Int): Unit = {\n\n //The idea is to color the graph vertices in two color and two adjacent vertex can't have same color\n //Using DFS we will color the graph; if a vertex is having no color (0) then make it 1 and processed further\n //If we come across a vertex with ambiguity then we can say Bi-Partition is not possible\n val color = Array.fill[Int](n)(0)\n for (i <- 0 until 2) {\n if (color(i) == 0) {\n color(i) = 1\n }\n if (!dfsToColorGraph(graph, i, color)) {\n println(\"-1\")\n return\n }\n }\n\n var set1Count=0\n var set2Count=0\n var set1=ArrayBuffer[Int]()\n var set2=ArrayBuffer[Int]()\n for(i<- 0 until graph.length){\n if(color(i)==1){\n set1+=(i+1)\n set1Count+=1\n }else if(color(i)==2){\n set2+=(i+1)\n set2Count+=1\n }\n }\n println(set2Count)\n println(set2.mkString(\" \"))\n println(set1Count)\n println(set1.mkString(\" \"))\n }\n\n def dfsToColorGraph(graph: Array[ArrayBuffer[Int]], u: Int, color: Array[Int]): Boolean = {\n\n for (v <- 0 until graph(u).length) {\n if (color(graph(u)(v)) == 0) {\n color(graph(u)(v)) = (if (color(u) == 1) 2 else 1)\n if (!dfsToColorGraph(graph, graph(u)(v), color)) {\n return false\n }\n } else {\n if (color(u) == color(graph(u)(v))) {\n return false\n }\n }\n }\n\n return true\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable.ListBuffer\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C360A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C360A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val m = ni()\n\n g = Array.fill[ListBuffer[Int]](n)(new ListBuffer[Int])\n\n REP(m) { _ =>\n val u = ni()\n val v = ni()\n\n g(u-1) += v-1\n g(v-1) += u-1\n }\n\n marked = Array.fill(n)(-1)\n REP(n) { i =>\n if(marked(i) == -1) {\n marked(i) = 0\n fill(i)\n }\n }\n\n var yes = true\n REP(n) { i =>\n val c = marked(i)\n yes = g(i).forall(p => marked(p) == (c^1))\n }\n if(!yes) {\n out.println(-1)\n } else {\n val x = marked.zipWithIndex.filter(_._1 == 0).map(_._2 + 1)\n out.println(x.length)\n out.println(x.mkString(\" \"))\n val y = marked.zipWithIndex.filter(_._1 == 1).map(_._2 + 1)\n out.println(y.length)\n out.println(y.mkString(\" \"))\n }\n }\n\n var g: Array[ListBuffer[Int]] = _\n var marked: Array[Int] = _\n\n def fill(u: Int) {\n val x = marked(u)\n g(u).foreach { f =>\n if(marked(f) == -1) {\n marked(f) = x^1\n fill(f)\n }\n }\n }\n}\n"}, {"source_code": "object A687 {\n def mark(\n edges: Array[Seq[Int]],\n color: Array[Int],\n now: Int,\n colorToAssign: Int\n ): Boolean = {\n //println(s\"Coloring $now the color $colorToAssign\")\n color(now) = colorToAssign\n\n val nextColor = 3 - colorToAssign\n\n edges(now).map {\n case next if (color(next) == 0) =>\n if (!mark(edges, color, next, nextColor)) return false\n case next if (color(next) != nextColor) =>\n return false\n case _ => // no op\n }\n\n return true\n }\n\n def main(args: Array[String]) = {\n val n :: m :: rest = readLine.split(' ').map { _.toInt }.toList\n val edges = Array.ofDim[Seq[Int]](n)\n\n (0 until n).map { case node => edges(node) = Seq[Int]()}\n\n (1 to m).map { case l =>\n val u :: v :: rest = readLine.split(' ').map { _.toInt}.toList\n edges(u - 1) = edges(u - 1) :+ (v - 1)\n edges(v - 1) = edges(v - 1) :+ (u - 1)\n }\n\n val color = Array.ofDim[Int](n)\n\n val result = (0 until n).map { case node =>\n if (color(node) == 0) mark(edges, color, node, 1)\n }\n .exists(_ == false)\n\n if (result) {\n println(-1)\n } else {\n println(color.count(_ == 1))\n println(color.filter(_ == 1).mkString(\" \"))\n println(color.count(_ == 2))\n println(color.filter(_ == 2).mkString(\" \"))\n }\n }\n}\n"}], "src_uid": "810f267655da0ad14538c275fd13821d"} {"source_code": "import java.util.Scanner\nimport java.io._\n\n\nobject A {\n def main(args: Array[String]) {\n val sc: Scanner = new Scanner(new File(\"input.txt\"))\n val n: Int = sc.nextInt()\n val m: Int = sc.nextInt()\n var b: Boolean = true\n if (n ng) {\n\t\tprintc( \"BG\", ng);\n\t\tprintc( \"B\", (nb-ng))\n\t} else {\n\t\tprintc( \"GB\", nb)\n\t\tprintc( \"G\", (ng-nb) )\n\t}\n writer.close()\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.fromFile(\"input.txt\").getLines()\n val Array(b, g) = in.next().split(' ').map(_.toInt)\n val p = new java.io.PrintWriter(\"output.txt\")\n if (b > g)\n p.println(\"BG\" * Math.min(b, g) + \"B\" * (b - g))\n else\n p.println(\"GB\" * Math.min(b, g) + \"G\" * (g - b))\n p.close()\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io._\n\n\nobject A {\n def main(args: Array[String]) {\n val sc: Scanner = new Scanner(new File(\"input.txt\"))\n val n: Int = sc.nextInt()\n val m: Int = sc.nextInt()\n var b: Boolean = true\n if (n x.toInt)\n val data = new ArrayBuffer[Pair[Int, Int]]\n for(i <- 0.until(n)) {\n data.+=(new Pair(i, intArray(i)))\n }\n val sortedData = data.sortWith(_._2 > _._2)\n sortedData.foreach(data => {\n val currPos = data._1\n while (currPos > pos) {\n println()\n pos += 1\n }\n print(data._2 + \" \")\n })\n}"}], "negative_code": [], "src_uid": "3d648acee2abbf834f865b582aa9b7bc"} {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n //Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {\n def +(other: Node) = {\n val matches = this.opening min other.closing\n Node(this.opening + other.opening - matches,\n this.closing + other.closing - matches,\n this.paired + other.paired + 2 * matches)\n }\n }\n\n val openingNode = Node(opening = 1)\n val closingNode = Node(closing = 1)\n\n val s = readLine.toCharArray\n val nodes = mutable.ArrayBuffer[Array[Node]]()\n nodes += s.map(c => if (c == ')') closingNode else openingNode)\n\n var len = nodes(0).length\n var i = 0\n while (len >= 1) {\n nodes += Array.ofDim[Node](len / 2 + 1)\n for (j <- 0 until len by 2) {\n nodes.last(j >> 1) = if (j + 1 >= len) nodes(i)(j) else nodes(i)(j) + nodes(i)(j + 1)\n }\n i += 1\n len /= 2\n }\n val maxLevel = i\n\n def calc(l: Int, r: Int, level: Int): Node = {\n if (level == 0) nodes(level)(l)\n else {\n val nextLevel = level - 1\n val l0 = l >> nextLevel\n val r0 = r >> nextLevel\n if (l == (l >> level) << level && r + 1 == ((r + 1) >> level) << level) nodes(level)(l >> level)\n else if (l0 == r0) calc(l, r, nextLevel) \n else calc(l, (r0 << nextLevel) - 1, nextLevel) + calc(r0 << nextLevel, r, nextLevel)\n }\n }\n\n val m = readInt\n\n for (i <- 0 until m) {\n val Array(l, r) = readInts(2)\n println(calc(l - 1, r - 1, maxLevel).paired)\n }\n\n Console.flush\n}", "positive_code": [{"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n @inline def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n \n case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {\n def +(other: Node) = {\n val matches = this.opening min other.closing\n Node(this.opening + other.opening - matches,\n this.closing + other.closing - matches,\n this.paired + other.paired + 2 * matches)\n }\n }\n\n case class SegTree(as: Array[Node]) {\n\n val n = as.length\n val t = Array.ofDim[Node](4 * Integer.highestOneBit(n))\n build(1, 0, n - 1)\n \n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n\t else {\n\t\tval tm = (tl + tr) >> 1\n\t\tval v2 = v << 1\n\t\tbuild(v2, tl, tm)\n\t\tbuild(v2 + 1, tm + 1, tr)\n\t\tt(v) = t(v2) + t(v2 + 1)\n\t }\n }\n \n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Node = {\n \tif (l > r) Node()\n \telse if (l == tl && r == tr) t(v)\n \telse {\n \t val tm = (tl + tr) >> 1\n \t val v2 = v << 1\n \t query(l, Math.min(r, tm), v2, tl, tm) + \n \t \tquery(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)\n \t}\n }\n\n }\n\n val openingNode = Node(opening = 1)\n val closingNode = Node(closing = 1)\n\n val s = readLine.toCharArray\n val nodes = SegTree(s.map(c => if (c == ')') closingNode else openingNode))\n \n val m = readInt\n\n for (i <- 0 until m) {\n val Array(l, r) = readInts(2)\n println(nodes.query(l - 1, r - 1).paired)\n }\n\n Console.flush\n}"}, {"source_code": "/**\n** http://codeforces.com/contest/380/problem/C\n**/\n\n\nobject Main extends App {\n\timport scala.io.StdIn._\t\n\tConsole.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val data = readLine().toCharArray\n val tree = new SegmentTree(data)\n tree.buildSegment()\n \n val p = readInt()\n for( _ <- 0 to p - 1) {\n \tval Array(l, r) = readLine().split(\" \").map(_.toInt) \n\t println(tree.query(l-1, r-1).balanced)\n }\n Console.flush\n}\n\ncase class Node(open: Int = 0, balanced: Int = 0, closed: Int = 0) {\n\n\tdef balanced(other: Node): Int = {\n\t\tmath.min(open, other.closed)\n\t}\n\n\t\n}\nobject Node {\n\tdef of(lNode: Node, rNode: Node): Node = {\n\t\tval matched = lNode.balanced(rNode)\n\t\tNode(lNode.open + rNode.open - matched, \n\t\t\t\tlNode.balanced + rNode.balanced + 2 * matched,\n\t\t\t\tlNode.closed + rNode.closed - matched)\n\t}\n}\n\nclass SegmentTree(data: Array[Char]) {\n\n\tval treeSize = 4 * Integer.highestOneBit(data.size)\n val treeArray = Array.ofDim[Node](treeSize)\n\n\tdef buildSegment() = {\n\t\tdef buildLoop(vertex: Int, leftId: Int, rightId: Int): Unit = {\n\t\t\tif(leftId == rightId) {\n\t\t\t\tif(data(leftId) == '(') {\n\t\t\t\t\ttreeArray(vertex) = Node(open = 1)\n\t\t\t\t} else {\n\t\t\t\t\ttreeArray(vertex) = Node(closed = 1)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tval mid = leftId + (rightId - leftId)/2\n\t\t\t\tval leftV = 2 * vertex\n\t\t\t\tval rightV = 2 * vertex + 1\n\t\t\t\tbuildLoop(leftV, leftId, mid)\n\t\t\t\tbuildLoop(rightV, mid+1, rightId)\n\t\t\t\t\n\t\t\t\tval minBalanced = treeArray(leftV).balanced(treeArray(rightV))\n\t\t\t\tval leftNode = treeArray(leftV)\n\t\t\t\tval rightNode = treeArray(rightV)\n\n\t\t\t\tval leftParan = leftNode.open + rightNode.open - minBalanced\n\t\t\t\tval balancedParan = 2 * minBalanced + leftNode.balanced + rightNode.balanced\n\t\t\t\tval rightParan = leftNode.closed + rightNode.closed - minBalanced\n\n\t\t\t\ttreeArray(vertex) = Node(leftParan, balancedParan, rightParan)\n\t\t\t}\n\t\t}\n\n\t\tbuildLoop(1, 0, data.size - 1)\n\t}\n\n\tdef query(l: Int, r: Int, vertex: Int = 1, begin: Int = 0, end: Int = data.size - 1): Node = {\n\t\t// println(s\"$vertex: $begin $end\")\n\n\t\tif(begin > r || l > end) {\n\t\t\t// println(\"out\")\n\t\t\tNode(0, 0, 0)\n\t\t} else if(l <= begin && end <= r) {\n\t\t\tval res = treeArray(vertex)\n\t\t\t// println(\"ret: \"+ res)\n\t\t\tres\n\t\t} else {\n\t\t\tval mid = begin + (end - begin)/2\n\t\t\t// println(s\"mid: $mid\")\n\t\t\tval lNode = query(l, math.min(r, mid), 2 * vertex, begin, mid)\n\t\t\tval rNode = query(math.max(l, mid+1), r, 2 * vertex + 1, mid+1, end)\n\t\t\tNode.of(lNode, rNode)\n\t\t}\n\t}\n\n\tdef pprint() = {\n\t \tprintln(treeArray.mkString(\" \"))\n\t}\n}\n"}, {"source_code": "object C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {\n def +(other: Node) = {\n val matches = this.opening min other.closing\n Node(this.opening + other.opening - matches,\n this.closing + other.closing - matches,\n this.paired + other.paired + 2 * matches)\n }\n }\n\n case class SegTree(as: Array[Node]) {\n\n val n = as.length\n val t = Array.ofDim[Node](4 * Integer.highestOneBit(n))\n build(1, 0, n - 1)\n \n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n\t else {\n\t\tval tm = (tl + tr) >> 1\n\t\tval v2 = v << 1\n\t\tbuild(v2, tl, tm)\n\t\tbuild(v2 + 1, tm + 1, tr)\n\t\tt(v) = t(v2) + t(v2 + 1)\n\t }\n }\n \n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Node = {\n \tif (l > r) Node()\n \telse if (l == tl && r == tr) t(v)\n \telse {\n \t val tm = (tl + tr) >> 1\n \t val v2 = v << 1\n \t query(l, Math.min(r, tm), v2, tl, tm) + \n \t \tquery(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)\n \t}\n }\n\n }\n\n val openingNode = Node(opening = 1)\n val closingNode = Node(closing = 1)\n\n val s = readLine.toCharArray\n val nodes = SegTree(s.map(c => if (c == ')') closingNode else openingNode))\n \n val m = readInt\n\n for (i <- 0 until m) {\n val Array(l, r) = readInts(2)\n println(nodes.query(l - 1, r - 1).paired)\n }\n\n Console.flush\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n //Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {\n def +(other: Node) = {\n val matches = this.opening min other.closing\n Node(this.opening + other.opening - matches,\n this.closing + other.closing - matches,\n this.paired + other.paired + 2 * matches)\n }\n }\n\n val openingNode = Node(opening = 1)\n val closingNode = Node(closing = 1)\n\n val s = readLine\n \n val nodes = mutable.ArrayBuffer[IndexedSeq[Node]]()\n nodes += s.collect { case ')' => closingNode case '(' => openingNode }\n\n var len = nodes(0).length\n var i = 0\n while (len >= 1) {\n nodes += (0 until len by 2).map(j => if (j + 1 >= len) nodes(i)(j) else nodes(i)(j) + nodes(i)(j + 1))\n i += 1\n len /= 2\n }\n val maxLevel = i\n\n def calc(l: Int, r: Int, level: Int): Node = {\n //println(s\"l=$l r=$r level=$level\")\n if (level == 0) nodes(level)(l)\n else {\n val nextLevel = level - 1\n val l0 = l >> nextLevel\n val r0 = r >> nextLevel\n // println(s\"l0=$l0 r0=$r0\")\n if (l == (l >> level) << level && r + 1 == ((r + 1) >> level) << level) nodes(level)(l >> level)\n else if (/*r - l + 1 <= (1 << nextLevel)*/ l0 == r0) calc(l, r, nextLevel) \n else calc(l, (r0 << nextLevel) - 1, nextLevel) + calc(r0 << nextLevel, r, nextLevel)\n }\n }\n\n val m = readInt\n\n for (i <- 0 until m) {\n val Array(l, r) = readInts(2)\n println(calc(l - 1, r - 1, maxLevel).paired)\n }\n\n Console.flush\n}"}, {"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n @inline def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {\n def +(other: Node) = {\n val matches = this.opening min other.closing\n Node(this.opening + other.opening - matches,\n this.closing + other.closing - matches,\n this.paired + other.paired + 2 * matches)\n }\n }\n\n case class SegTree(as: Array[Node]) {\n\n val n = as.length\n val t = Array.ofDim[Node](4 * Integer.highestOneBit(n))\n build(1, 0, n - 1)\n \n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n\t else {\n\t\tval tm = (tl + tr) >> 1\n\t\tval v2 = v << 1\n\t\tbuild(v2, tl, tm)\n\t\tbuild(v2 + 1, tm + 1, tr)\n\t\tt(v) = t(v2) + t(v2 + 1)\n\t }\n }\n \n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Node = {\n \tif (l > r) Node()\n \telse if (l == tl && r == tr) t(v)\n \telse {\n \t val tm = (tl + tr) >> 1\n \t val v2 = v << 1\n \t query(l, Math.min(r, tm), v2, tl, tm) + \n \t \tquery(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)\n \t}\n }\n\n }\n\n val openingNode = Node(opening = 1)\n val closingNode = Node(closing = 1)\n\n val s = readLine.toCharArray\n val nodes = SegTree(s.map(c => if (c == ')') closingNode else openingNode))\n \n val m = readInt\n\n for (i <- 0 until m) {\n val Array(l, r) = readInts(2)\n println(nodes.query(l - 1, r - 1).paired)\n }\n\n Console.flush\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {\n def +(other: Node) = {\n val matches = this.opening min other.closing\n Node(this.opening + other.opening - matches,\n this.closing + other.closing - matches,\n this.paired + other.paired + 2 * matches)\n }\n }\n\n case class SegTree(as: Array[Node]) {\n\n val n = as.length\n val t = Array.ofDim[Node](4 * Integer.highestOneBit(n))\n build(1, 0, n - 1)\n \n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n\t else {\n\t\tval tm = (tl + tr) >> 1\n\t\tval v2 = v << 1\n\t\tbuild(v2, tl, tm)\n\t\tbuild(v2 + 1, tm + 1, tr)\n\t\tt(v) = t(v2) + t(v2 + 1)\n\t }\n }\n \n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Node = {\n \tif (l > r) Node()\n \telse if (l == tl && r == tr) t(v)\n \telse {\n \t val tm = (tl + tr) >> 1\n \t val v2 = v << 1\n \t query(l, Math.min(r, tm), v2, tl, tm) + \n \t \tquery(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)\n \t}\n }\n\n }\n\n val openingNode = Node(opening = 1)\n val closingNode = Node(closing = 1)\n\n val s = readLine.toCharArray\n val nodes = SegTree(s.map(c => if (c == ')') closingNode else openingNode))\n \n val m = readInt\n\n for (i <- 0 until m) {\n val Array(l, r) = readInts(2)\n println(nodes.query(l - 1, r - 1).paired)\n }\n\n Console.flush\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {\n def +(other: Node) = {\n val matches = this.opening min other.closing\n Node(this.opening + other.opening - matches,\n this.closing + other.closing - matches,\n this.paired + other.paired + 2 * matches)\n }\n }\n\n val openingNode = Node(opening = 1)\n val closingNode = Node(closing = 1)\n\n val s = readLine.toCharArray\n val nodes = mutable.ArrayBuffer[Array[Node]]()\n nodes += s.map(c => if (c == ')') closingNode else openingNode)\n\n var len = nodes(0).length\n var i = 0\n while (len >= 1) {\n nodes += Array.ofDim[Node](len / 2 + 1)\n for (j <- 0 until len by 2) {\n nodes.last(j >> 1) = if (j + 1 >= len) nodes(i)(j) else nodes(i)(j) + nodes(i)(j + 1)\n }\n i += 1\n len /= 2\n }\n val maxLevel = i\n\n def calc(l: Int, r: Int, level: Int): Node = {\n if (level == 0) nodes(level)(l)\n else {\n val nextLevel = level - 1\n val l0 = l >> nextLevel\n val r0 = r >> nextLevel\n if (l == (l >> level) << level && r + 1 == ((r + 1) >> level) << level) nodes(level)(l >> level)\n else if (l0 == r0) calc(l, r, nextLevel) \n else calc(l, (r0 << nextLevel) - 1, nextLevel) + calc(r0 << nextLevel, r, nextLevel)\n }\n }\n\n val m = readInt\n\n for (i <- 0 until m) {\n val Array(l, r) = readInts(2)\n println(calc(l - 1, r - 1, maxLevel).paired)\n }\n\n Console.flush\n}"}, {"source_code": "object C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n \n case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {\n def +(other: Node) = {\n val matches = this.opening min other.closing\n Node(this.opening + other.opening - matches,\n this.closing + other.closing - matches,\n this.paired + other.paired + 2 * matches)\n }\n }\n\n case class SegTree(as: Array[Node]) {\n\n val n = as.length\n val t = Array.ofDim[Node](4 * Integer.highestOneBit(n))\n build(1, 0, n - 1)\n \n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n\t else {\n\t\tval tm = (tl + tr) >> 1\n\t\tval v2 = v << 1\n\t\tbuild(v2, tl, tm)\n\t\tbuild(v2 + 1, tm + 1, tr)\n\t\tt(v) = t(v2) + t(v2 + 1)\n\t }\n }\n \n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Node = {\n \tif (l > r) Node()\n \telse if (l == tl && r == tr) t(v)\n \telse {\n \t val tm = (tl + tr) >> 1\n \t val v2 = v << 1\n \t query(l, Math.min(r, tm), v2, tl, tm) + \n \t \tquery(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)\n \t}\n }\n\n }\n\n val openingNode = Node(opening = 1)\n val closingNode = Node(closing = 1)\n\n val s = readLine.toCharArray\n val nodes = SegTree(s.map(c => if (c == ')') closingNode else openingNode))\n \n val m = readInt\n\n for (i <- 0 until m) {\n val Array(l, r) = readInts(2)\n println(nodes.query(l - 1, r - 1).paired)\n }\n\n Console.flush\n}"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val s = readLine\n\n val st = mutable.Stack[Char]()\n\n val cnts = Array.ofDim[Int](s.length)\n var cnt = 0\n\n val cnts2 = Array.ofDim[Int](s.length)\n var cnt2 = 0\n\n val uncloseds = Array.ofDim[Int](s.length)\n var unclosed = 0\n\n val unopeneds = Array.ofDim[Int](s.length)\n var unopened = 0\n \n val depths = Array.ofDim[Int](s.length)\n\n for (i <- s.indices) {\n val c = s(i)\n depths(i) = 2 * st.size\n if (c == '(') {\n uncloseds(i) = unclosed\n unclosed += 2\n } else {\n unclosed = Math.max(unclosed - 2, 0)\n uncloseds(i) = unclosed\n }\n if (c == ')' && st.headOption == Some('(')) {\n cnt += 2\n st.pop\n } else st.push(c)\n cnts(i) = cnt\n }\n\n st.clear\n for (i <- s.indices.reverse) {\n val c = s(i)\n if (c == ')') {\n unopeneds(i) = unopened\n unopened += 2\n } else {\n unopened = Math.max(unopened - 2, 0)\n unopeneds(i) = unopened\n }\n if (c == '(' && st.headOption == Some(')')) {\n cnt2 += 2\n st.pop\n } else st.push(c)\n cnts2(i) = cnt2\n }\n\n// println(cnts.mkString(\" \"))\n// println(depths.mkString(\" \"))\n// println(uncloseds.mkString(\" \"))\n// println(unopeneds.mkString(\" \"))\n\n val m = readInt\n\n for (i <- 0 until m) {\n val Array(l, r) = readInts(2).map(_ - 1)\n val ans = Math.min(cnts(r) - cnts(l), cnts2(l) - cnts2(r)) \n println(ans)\n }\n\n Console.flush\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n //Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {\n def +(other: Node) = {\n val matches = this.opening min other.closing\n Node(this.opening + other.opening - matches,\n this.closing + other.closing - matches,\n this.paired + other.paired + 2 * matches)\n }\n }\n\n val openingNode = Node(opening = 1)\n val closingNode = Node(closing = 1)\n\n val s = readLine\n \n val nodes = mutable.ArrayBuffer[IndexedSeq[Node]]()\n nodes += s.collect { case ')' => closingNode case '(' => openingNode }\n\n var len = nodes(0).length\n var i = 0\n while (len >= 1) {\n nodes += (0 until len by 2).map(j => if (j + 1 >= len) nodes(i)(j) else nodes(i)(j) + nodes(i)(j + 1))\n i += 1\n len /= 2\n }\n val maxLevel = i\n\n def calc(l: Int, r: Int, level: Int): Node = {\n //println(s\"l=$l r=$r level=$level\")\n if (level == 0) nodes(level)(l)\n else {\n val nextLevel = level - 1\n val l0 = l >> nextLevel\n val r0 = r >> nextLevel\n // println(s\"l0=$l0 r0=$r0\")\n if (r - l + 1 <= (1 << nextLevel)) calc(l, r, nextLevel) \n else if (l == (l >> level) << level && r + 1 == ((r + 1) >> level) << level) nodes(level)(l >> level)\n else calc(l, (r0 << nextLevel) - 1, nextLevel) + calc(r0 << nextLevel, r, nextLevel)\n }\n }\n\n val m = readInt\n\n for (i <- 0 until m) {\n val Array(l, r) = readInts(2)\n println(calc(l - 1, r - 1, maxLevel).paired)\n }\n\n Console.flush\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n //Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {\n def +(other: Node) = {\n val matches = this.opening min other.closing\n Node(this.opening + other.opening - matches,\n this.closing + other.closing - matches,\n this.paired + other.paired + 2 * matches)\n }\n }\n\n val openingNode = Node(opening = 1)\n val closingNode = Node(closing = 1)\n\n val s = readLine\n \n val nodes = mutable.ArrayBuffer[Array[Node]]()\n nodes += s.toCharArray.map(c => if (c == ')') closingNode else openingNode)\n\n var len = nodes(0).length\n var i = 0\n while (len >= 1) {\n nodes += Array.ofDim[Node](len / 2 + 1)\n for (j <- 0 until len by 2) {\n nodes.last(j >> 1) = if (j + 1 >= len) nodes(i)(j) else nodes(i)(j) + nodes(i)(j + 1)\n }\n i += 1\n len /= 2\n }\n val maxLevel = i\n\n def calc(l: Int, r: Int, level: Int): Node = {\n //println(s\"l=$l r=$r level=$level\")\n if (level == 0) nodes(level)(l)\n else {\n val nextLevel = level - 1\n val l0 = l >> nextLevel\n val r0 = r >> nextLevel\n // println(s\"l0=$l0 r0=$r0\")\n if (r - l + 1 <= (1 << nextLevel)) calc(l, r, nextLevel) \n else if (l == (l >> level) << level && r + 1 == ((r + 1) >> level) << level) nodes(level)(l >> level)\n else calc(l, (r0 << nextLevel) - 1, nextLevel) + calc(r0 << nextLevel, r, nextLevel)\n }\n }\n\n val m = readInt\n\n for (i <- 0 until m) {\n val Array(l, r) = readInts(2)\n println(calc(l - 1, r - 1, maxLevel).paired)\n }\n\n Console.flush\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n //Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {\n def +(other: Node) = {\n val matches = this.opening min other.closing\n Node(this.opening + other.opening - matches,\n this.closing + other.closing - matches,\n this.paired + other.paired + 2 * matches)\n }\n }\n\n val openingNode = Node(opening = 1)\n val closingNode = Node(closing = 1)\n\n val s = readLine\n \n val nodes = mutable.ArrayBuffer[Array[Node]]()\n nodes += s.toCharArray.map(c => if (c == ')') closingNode else openingNode)\n\n var len = nodes(0).length\n var i = 0\n while (len >= 1) {\n nodes += Array.ofDim[Node](len / 2 + 1)\n for (j <- 0 until len by 2) {\n nodes.last(j >> 1) = if (j + 1 >= len) nodes(i)(j) else nodes(i)(j) + nodes(i)(j + 1)\n }\n i += 1\n len /= 2\n }\n val maxLevel = i\n\n def calc(l: Int, r: Int, level: Int): Node = {\n //println(s\"l=$l r=$r level=$level\")\n if (level == 0) nodes(level)(l)\n else {\n val nextLevel = level - 1\n val l0 = l >> nextLevel\n val r0 = r >> nextLevel\n // println(s\"l0=$l0 r0=$r0\")\n if (r - l + 1 <= (1 << nextLevel)) calc(l, r, nextLevel) \n else if (l == (l >> level) << level && r + 1 == ((r + 1) >> level << level)) nodes(level)(l >> level)\n else calc(l, (r0 << nextLevel) - 1, nextLevel) + calc(r0 << nextLevel, r, nextLevel)\n }\n }\n\n val m = readInt\n\n for (i <- 0 until m) {\n val Array(l, r) = readInts(2)\n println(calc(l - 1, r - 1, maxLevel).paired)\n }\n\n Console.flush\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n //Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {\n def +(other: Node) = {\n val matches = this.opening min other.closing\n Node(this.opening + other.opening - matches,\n this.closing + other.closing - matches,\n this.paired + other.paired + 2 * matches)\n }\n }\n\n val openingNode = Node(opening = 1)\n val closingNode = Node(closing = 1)\n\n val s = readLine\n \n val nodes = mutable.ArrayBuffer[Array[Node]]()\n nodes += s.toCharArray.map(c => if (c == ')') closingNode else openingNode)\n\n var len = nodes(0).length\n var i = 0\n while (len >= 1) {\n nodes += Array.ofDim[Node](len / 2 + 1)\n for (j <- 0 until len by 2) {\n nodes.last(j >> 1) = if (j + 1 >= len) nodes(i)(j) else nodes(i)(j) + nodes(i)(j + 1)\n }\n i += 1\n len /= 2\n }\n val maxLevel = i\n\n def calc(l: Int, r: Int, level: Int): Node = {\n if (level == 0) nodes(level)(l)\n else {\n val nextLevel = level - 1\n val l0 = l >> nextLevel\n val r0 = r >> nextLevel\n if (r - l + 1 == 1 << level) nodes(level)(l >> level)\n else if (r - l + 1 > (1 << nextLevel)) calc(l, (r0 << nextLevel) - 1, nextLevel) + calc(r0 << nextLevel, r, nextLevel)\n else calc(l, r, nextLevel)\n }\n }\n\n val m = readInt\n\n for (i <- 0 until m) {\n val Array(l, r) = readInts(2)\n println(calc(l - 1, r - 1, maxLevel).paired)\n }\n\n Console.flush\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n //Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {\n def +(other: Node) = {\n val matches = this.opening min other.closing\n Node(this.opening + other.opening - matches,\n this.closing + other.closing - matches,\n this.paired + other.paired + 2 * matches)\n }\n }\n\n val openingNode = Node(opening = 1)\n val closingNode = Node(closing = 1)\n\n val s = readLine\n \n val nodes = mutable.ArrayBuffer[IndexedSeq[Node]]()\n nodes += s.collect { case ')' => closingNode case '(' => openingNode }\n\n var len = nodes(0).length\n var i = 0\n while (len >= 1) {\n nodes += (0 until len by 2).map(j => if (j + 1 >= len) nodes(i)(j) else nodes(i)(j) + nodes(i)(j + 1))\n i += 1\n len /= 2\n }\n val maxLevel = i\n\n def calc(l: Int, r: Int, level: Int): Node = {\n //println(s\"l=$l r=$r level=$level\")\n if (level == 0) nodes(level)(l)\n else {\n val nextLevel = level - 1\n val l0 = l >> nextLevel\n val r0 = r >> nextLevel\n // println(s\"l0=$l0 r0=$r0\")\n if (r - l + 1 <= (1 << nextLevel)) calc(l, r, nextLevel) \n else if (l == (l >> level) << level && r + 1 == l + ((r - l + 1) >> level) << level) nodes(level)(l >> level)\n else calc(l, (r0 << nextLevel) - 1, nextLevel) + calc(r0 << nextLevel, r, nextLevel)\n }\n }\n\n val m = readInt\n\n for (i <- 0 until m) {\n val Array(l, r) = readInts(2)\n println(calc(l - 1, r - 1, maxLevel).paired)\n }\n\n Console.flush\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val s = readLine\n\n val st = mutable.Stack[Char]()\n\n val cnts = Array.ofDim[Int](s.length)\n var cnt = 0\n\n val cnts2 = Array.ofDim[Int](s.length)\n var cnt2 = 0\n\n val uncloseds = Array.ofDim[Int](s.length)\n var unclosed = 0\n\n val unopeneds = Array.ofDim[Int](s.length)\n var unopened = 0\n \n val depths = Array.ofDim[Int](s.length)\n\n for (i <- s.indices) {\n val c = s(i)\n depths(i) = 2 * st.size\n if (c == '(') {\n uncloseds(i) = unclosed\n unclosed += 2\n } else {\n unclosed = Math.max(unclosed - 2, 0)\n uncloseds(i) = unclosed\n }\n if (c == ')' && st.headOption == Some('(')) {\n cnt += 2\n st.pop\n } else st.push(c)\n cnts(i) = cnt\n }\n\n st.clear\n for (i <- s.indices.reverse) {\n val c = s(i)\n if (c == ')') {\n unopeneds(i) = unopened\n unopened += 2\n } else {\n unopened = Math.max(unopened - 2, 0)\n unopeneds(i) = unopened\n }\n if (c == '(' && st.headOption == Some(')')) {\n cnt2 += 2\n st.pop\n } else st.push(c)\n cnts2(i) = cnt2\n }\n\n// println(cnts.mkString(\" \"))\n// println(depths.mkString(\" \"))\n// println(uncloseds.mkString(\" \"))\n //println(unopeneds.mkString(\" \"))\n\n val m = readInt\n\n for (i <- 0 until m) {\n val Array(l, r) = readInts(2).map(_ - 1)\n val ans = cnts(r) - cnts(l) - (if (l == 0) 0 else uncloseds(l) - uncloseds(r))\n println(ans)\n }\n\n Console.flush\n}"}], "src_uid": "a3e88504793c44fb3110a322d9dbdf17"} {"source_code": "import scala.io.StdIn\r\n\r\nobject Main extends App {\r\n val n = StdIn.readInt()\r\n for (_ <- 0 until n) {\r\n val number: BigInt = BigInt(StdIn.readLine())\r\n println(if (number % 2050 != 0) -1 else (number / 2050).toString.split(\"\").map(_.toInt).sum)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object CF1517A extends App {\n def readLong: Long = scala.io.StdIn.readLine.toLong\n def readInt: Int = scala.io.StdIn.readLine.toInt\n\n var T = readInt\n for (t <- 0 until T) {\n var x: Long = 205000000000000000L\n var n = readLong\n var ans = 0\n while (x >= 2050) {\n while (n >= x) {\n ans += 1\n n -= x\n }\n x /= 10\n }\n if (n == 0) {\n println(ans)\n } else {\n println(-1)\n }\n }\n}\n"}, {"source_code": "object cf1517a {\n\n def readInt(): Int = {\n\t\tConsole.in.readLine().toInt\n\t}\n\n def readLong(): Long= {\n\t\tConsole.in.readLine().toLong\n\t}\n\n\tdef readInts(): Array[Int] = {\n\t\tval line = Console.in.readLine()\n\t\tline.split(' ').map( _.toInt)\n\t}\n\n\tdef main(args: Array[String]): Unit = {\n\t\tval cases = readInt()\n\t\tvar nCase = 0\n\t\tval res = for (nCase <- 1 to cases) yield {\n\t\t\tvar v = readLong()\n\t\t\tvar res = 0L\n\t\t\tvar cSubstractor = 205000000000000000L\n\t\t\twhile ( (v > 0) && (cSubstractor >= 2050L) ) {\n\t\t\t\tif (v >= cSubstractor) {\n\t\t\t\t\tres += v/cSubstractor\n\t\t\t\t\tv -= cSubstractor*(v/cSubstractor)\n\t\t\t\t}\n\t\t\t\tcSubstractor /= 10\n\t\t\t}\n\t\t\tif (v == 0) res else -1L\n }\n\n\t\tres.foreach( println(_))\n }\n}"}, {"source_code": "import scala.collection._\r\nimport scala.collection.mutable.TreeSet\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport scala.io.StdIn._\r\nimport scala.util._\r\n\r\n// https://codeforces.com/contest/977/problem/F\r\n\r\nobject Sum {\r\n def main(args: Array[String]): Unit = {\r\n val n = readInt()\r\n\r\n (0 until n).foreach(_ => {\r\n var v = readLong()\r\n\r\n var mul = 2050l\r\n while (10l * mul <= v) {\r\n mul *= 10l\r\n }\r\n\r\n var count = 0\r\n while (mul >= 2050 && v >= 0) {\r\n if (mul <= v) {\r\n v -= mul\r\n count += 1\r\n } else {\r\n mul /= 10\r\n }\r\n }\r\n\r\n if (v == 0) {\r\n println(count)\r\n } else {\r\n println(-1)\r\n }\r\n })\r\n }\r\n}"}], "negative_code": [{"source_code": "object CF1517A extends App {\n def readLong: Long = scala.io.StdIn.readLine.toLong\n def readInt: Int = scala.io.StdIn.readLine.toInt\n\n var T = readInt\n for (t <- 0 until T) {\n var x: Long = 20500000000000000L\n var n = readLong\n var ans = 0\n while (x >= 2050) {\n while (n >= x) {\n ans += 1\n n -= x\n }\n x /= 10\n }\n if (n == 0) {\n println(ans)\n } else {\n println(-1)\n }\n }\n}\n"}, {"source_code": "object cf1517a {\n\n def readInt(): Int = {\n\t\tConsole.in.readLine().toInt\n\t}\n\n def readLong(): Long= {\n\t\tConsole.in.readLine().toLong\n\t}\n\n\tdef readInts(): Array[Int] = {\n\t\tval line = Console.in.readLine()\n\t\tline.split(' ').map( _.toInt)\n\t}\n\n\tdef main(args: Array[String]): Unit = {\n\t\tval cases = readInt()\n\t\tvar nCase = 0\n\t\tval res = for (nCase <- 1 to cases) yield {\n\t\t\tvar v = readLong()\n\t\t\tvar res = 0L\n\t\t\tvar cSubstractor = 20500000000000000L\n\t\t\twhile ( (v > 0) && (cSubstractor >= 2050L) ) {\n\t\t\t\tif (v >= cSubstractor) {\n\t\t\t\t\tres += v/cSubstractor\n\t\t\t\t\tv -= cSubstractor*(v/cSubstractor)\n\t\t\t\t}\n\t\t\t\tcSubstractor /= 10\n\t\t\t}\n\t\t\tif (v == 0) res else -1L\n }\n\n\t\tres.foreach( println(_))\n }\n}"}], "src_uid": "f3e413954c9c02520fd25bd2cba4747e"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val (coun, color) = (1 to n).foldLeft(Map.empty[Int, Int], Map.empty[(Int, Int), Int]){\n case ((count, colors), el) =>\n val Array(a, b) = in.next().split(' ').map(_.toInt)\n (count + (b -> (count.getOrElse(b, 0) + 1)), colors + ((b, a) -> (colors.getOrElse((b, a), 0) + 1)))\n }\n val (coun2, color2) = (1 to m).foldLeft(Map.empty[Int, Int], Map.empty[(Int, Int), Int]){\n case ((count, colors), el) =>\n val Array(a, b) = in.next().split(' ').map(_.toInt)\n (count + (b -> (count.getOrElse(b, 0) + 1)), colors + ((b, a) -> (colors.getOrElse((b, a), 0) + 1)))\n }\n\n val count = coun.foldLeft(0) {\n case(acc, (size, count)) => acc + Math.min(count, coun2.getOrElse(size, 0))\n }\n\n val col = color.foldLeft(0) {\n case(acc, (key, count)) => acc + Math.min(count, color2.getOrElse(key, 0))\n }\n\n println(s\"$count $col\")\n\n}", "positive_code": [{"source_code": "object Main {\n import scala.collection.{mutable => mu}\n\n def main(args: Array[String]) {\n val nm = readLine().split(\" \").map(_.toInt)\n val n = nm(0) \n val m = nm(1)\n \n val a1 = (1 to n).map(_ => readLine().split(\" \").map(_.toInt))\n val a2 = (1 to m).map(_ => readLine().split(\" \").map(_.toInt))\n \n val m1 = mu.Map[Int, mu.Map[Int, Int]]()\n val m2 = mu.Map[Int, mu.Map[Int, Int]]() \n \n a1.foreach { t =>\n val m = m1.getOrElse(t(1), mu.Map[Int, Int]())\n m1(t(1)) = m\n val prev = m.getOrElse(t(0), 0)\n m(t(0)) = prev + 1\n }\n \n a2.foreach { t => \n val m = m2.getOrElse(t(1), mu.Map[Int, Int]())\n m2(t(1)) = m\n val prev = m.getOrElse(t(0), 0)\n m(t(0)) = prev + 1\n }\n \n var all = 0\n var good = 0\n for( (d, cols) <- m1) {\n val m = m2.getOrElse(d, mu.Map.empty[Int, Int])\n all += cols.values.sum.min(m.values.sum)\n good += cols.map(t => m.getOrElse(t._1, 0).min(t._2)).sum\n }\n \n print(all + \" \" + good)\n }\n}"}, {"source_code": "import scala.collection.mutable.Map\nobject Main {\n def readLineOfNums(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def prepareMaps(n: Int): (Map[Int, Int], Map[(Int, Int), Int]) = {\n val mapGeneral = Map[Int, Int]()\n val mapPerfect = Map[(Int, Int), Int]()\n for (i <- 1 to n) {\n val Array(y, x) = readLineOfNums()\n if (mapGeneral.contains(x))\n mapGeneral(x) += 1\n else\n mapGeneral += (x -> 1)\n if (mapPerfect.contains((x, y)))\n mapPerfect((x, y)) += 1\n else\n mapPerfect += ((x, y) -> 1)\n }\n (mapGeneral, mapPerfect)\n }\n def main(args: Array[String]) = {\n val Array(n, m) = readLineOfNums()\n val (generalF, perfectF) = prepareMaps(n)\n val (generalK, perfectK) = prepareMaps(m)\n var sumG = 0\n for ((x, y) <- generalF)\n if (generalK.contains(x))\n sumG += List(y, generalK(x)).min\n var sumP = 0\n for(((x,y), z) <- perfectF)\n if (perfectK.contains((x,y)))\n sumP += List(z, perfectK((x, y))).min\n println(sumG.toString + \" \" + sumP.toString)\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val (coun, color) = (1 to n).foldLeft(Map.empty[Int, Int], Map.empty[(Int, Int), Int]){\n case ((count, colors), el) =>\n val Array(a, b) = in.next().split(' ').map(_.toInt)\n (count + (b -> (count.getOrElse(b, 0) + 1)), colors + ((b, a) -> (colors.getOrElse((b, a), 0) + 1)))\n }\n val c = (1 to m).foldLeft(0, 0, coun, color) {\n case (acc@(pair, goodPair, d, col), el) =>\n val Array(a, b) = in.next().split(' ').map(_.toInt)\n val dCount = d.getOrElse(b, 0)\n val colCount = col.getOrElse((b, a), 0)\n\n if (dCount > 0) {\n if (colCount > 0) {\n (pair + 1, goodPair + 1, d + (b -> (dCount - 1)), col + ((b, a) -> (colCount - 1)))\n } else {\n (pair + 1, goodPair + 1, d + (b -> (dCount - 1)), col)\n }\n } else {\n acc\n }\n }\n\n println(s\"${c._1} ${c._2}\")\n\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val (coun, color) = (1 to n).foldLeft(Map.empty[Int, Int], Map.empty[(Int, Int), Int]){\n case ((count, colors), el) =>\n val Array(a, b) = in.next().split(' ').map(_.toInt)\n (count + (b -> (count.getOrElse(b, 0) + 1)), colors + ((b, a) -> (colors.getOrElse((b, a), 0) + 1)))\n }\n val c = (1 to m).foldLeft(0, 0, coun, color) {\n case (acc@(pair, goodPair, d, col), el) =>\n val Array(a, b) = in.next().split(' ').map(_.toInt)\n val dCount = d.getOrElse(b, 0)\n val colCount = col.getOrElse((b, a), 0)\n\n if (dCount > 0) {\n if (colCount > 0) {\n (pair + 1, goodPair + 1, d + (b -> (dCount - 1)), col + ((b, a) -> (colCount - 1)))\n } else {\n (pair + 1, goodPair, d + (b -> (dCount - 1)), col)\n }\n } else {\n acc\n }\n }\n\n println(s\"${c._1} ${c._2}\")\n\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val f = (1 to n).map{_ =>\n val Array(a, b) = in.next().split(' ').map(_.toInt)\n (b, a)\n }.sorted.toList\n val c = (1 to m).map{_ =>\n val Array(a, b) = in.next().split(' ').map(_.toInt)\n (b, a)\n }.sorted.toList\n\n def sol(f: List[(Int, Int)], c: List[(Int, Int)], sum: Int = 0, b: Int = 0): (Int, Int) = {\n if (f.isEmpty || c.isEmpty) (sum, b)\n else if (f.head._1 > c.head._1)\n sol(f, c.tail, sum, b)\n else if (f.head._1 < c.head._1)\n sol(f.tail, c, sum, b)\n else if (f.head._2 == c.head._2)\n sol(f.tail, c.tail, sum + 1, b + 1)\n else\n sol(f.tail, c.tail, sum + 1, b)\n }\n\n val res = sol(f, c)\n println(s\"${res._1} ${res._2}\")\n\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val (coun, color) = (1 to n).foldLeft(Map.empty[Int, Int], Map.empty[(Int, Int), Int]){\n case ((count, colors), el) =>\n val Array(a, b) = in.next().split(' ').map(_.toInt)\n (count + (b -> (count.getOrElse(b, 0) + 1)), colors + ((b, a) -> (colors.getOrElse((b, a), 0) + 1)))\n }\n val (coun2, color2) = (1 to n).foldLeft(Map.empty[Int, Int], Map.empty[(Int, Int), Int]){\n case ((count, colors), el) =>\n val Array(a, b) = in.next().split(' ').map(_.toInt)\n (count + (b -> (count.getOrElse(b, 0) + 1)), colors + ((b, a) -> (colors.getOrElse((b, a), 0) + 1)))\n }\n\n val count = coun.foldLeft(0) {\n case(acc, (size, count)) => acc + Math.min(count, coun2.getOrElse(size, 0))\n }\n\n val col = color.foldLeft(0) {\n case(acc, (key, count)) => acc + Math.min(count, color2.getOrElse(key, 0))\n }\n\n println(s\"$count $col\")\n\n}"}], "src_uid": "3c9fb72577838f54b1670e84b4b60c61"} {"source_code": "import java.util.TreeSet\nimport scala.collection.mutable.ArrayBuilder\n\nobject F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n case class Pair(c: Int, i: Int) extends Comparable[Pair] {\n\n private final val weight = c * 100000L + i\n\n def compareTo(other: Pair): Int = java.lang.Long.compare(weight, other.weight)\n\n }\n\n val Array(n) = readInts(1)\n val xs, ys = Array.ofDim[Pair](n)\n\n for (i <- 0 until n) {\n val Array(x, y) = readInts(2)\n xs(i) = Pair(x, i)\n ys(i) = Pair(y, i)\n }\n\n def recurse(keepIdsByX: TreeSet[Pair], keepIdsByY: TreeSet[Pair], separateIds: Array[Int]): Int = {\n\n val separateByX, separateByY = new TreeSet[Pair]\n\n for (i <- separateIds) {\n separateByX.add(xs(i))\n keepIdsByX.remove(xs(i))\n separateByY.add(ys(i))\n keepIdsByY.remove(ys(i))\n }\n\n count(separateByX, separateByY) + count(keepIdsByX, keepIdsByY)\n }\n\n def count(keepIdsByX: TreeSet[Pair], keepIdsByY: TreeSet[Pair]): Int = {\n\n val left = keepIdsByX.iterator\n val right = keepIdsByX.descendingIterator\n val top = keepIdsByY.iterator\n val bottom = keepIdsByY.descendingIterator\n\n var Pair(prevLeftX, leftI) = left.next\n var Pair(prevTopY, topI) = top.next\n var Pair(prevRightX, rightI) = right.next\n var Pair(prevBottomY, bottomI) = bottom.next\n\n val leftIds, rightIds, topIds, bottomIds = new ArrayBuilder.ofInt\n leftIds += leftI\n rightIds += rightI\n topIds += topI\n bottomIds += bottomI\n\n var done = false\n var separateIds = Array.empty[Int]\n\n while (!done && left.hasNext) {\n\n if (!done) {\n val p = left.next\n if (prevLeftX < p.c - 1) {\n separateIds = leftIds.result\n done = true\n } else {\n leftIds += p.i\n prevLeftX = p.c\n }\n }\n\n if (!done) {\n val p = right.next\n if (prevRightX > p.c + 1) {\n separateIds = rightIds.result\n done = true\n } else {\n rightIds += p.i\n prevRightX = p.c\n }\n }\n\n if (!done) {\n val p = top.next\n if (prevTopY < p.c - 1) {\n separateIds = topIds.result\n done = true\n } else {\n topIds += p.i\n prevTopY = p.c\n }\n }\n\n if (!done) {\n val p = bottom.next\n if (prevBottomY > p.c + 1) {\n separateIds = bottomIds.result\n done = true\n } else {\n bottomIds += p.i\n prevBottomY = p.c\n }\n }\n\n if (prevLeftX >= prevRightX && prevTopY >= prevBottomY) done = true\n }\n\n if (separateIds.nonEmpty) recurse(keepIdsByX, keepIdsByY, separateIds)\n else 1\n }\n\n val allByX, allByY = new TreeSet[Pair]\n\n for (i <- 0 until n) {\n allByX.add(xs(i))\n allByY.add(ys(i))\n }\n\n println(count(allByX, allByY))\n}", "positive_code": [{"source_code": "import java.util.TreeSet\nimport scala.collection.mutable.ArrayBuilder\n\nobject F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n case class Pair(c: Int, id: Int) extends Comparable[Pair] {\n\n def compareTo(other: Pair): Int =\n if (c < other.c) -1\n else if (c > other.c) 1\n else if (id < other.id) -1\n else if (id > other.id) 1\n else 0\n\n }\n\n val Array(n) = readInts(1)\n val xs, ys = Array.ofDim[Pair](n)\n\n for (i <- 0 until n) {\n val Array(x, y) = readInts(2)\n xs(i) = Pair(x, i)\n ys(i) = Pair(y, i)\n }\n\n def recurse(keepIdsByX: TreeSet[Pair], keepIdsByY: TreeSet[Pair], separateIds: Array[Int]): Int = {\n\n val separateByX, separateByY = new TreeSet[Pair]\n\n for (i <- separateIds) {\n separateByX.add(xs(i))\n keepIdsByX.remove(xs(i))\n separateByY.add(ys(i))\n keepIdsByY.remove(ys(i))\n }\n\n count(separateByX, separateByY) + count(keepIdsByX, keepIdsByY)\n }\n\n def count(keepIdsByX: TreeSet[Pair], keepIdsByY: TreeSet[Pair]): Int = {\n\n val left = keepIdsByX.iterator\n val right = keepIdsByX.descendingIterator\n val top = keepIdsByY.iterator\n val bottom = keepIdsByY.descendingIterator\n\n var Pair(prevLeftX, leftI) = left.next\n var Pair(prevTopY, topI) = top.next\n var Pair(prevRightX, rightI) = right.next\n var Pair(prevBottomY, bottomI) = bottom.next\n\n val leftIds, rightIds, topIds, bottomIds = new ArrayBuilder.ofInt\n leftIds += leftI\n rightIds += rightI\n topIds += topI\n bottomIds += bottomI\n\n var done = false\n var separateIds = Array.empty[Int]\n\n while (!done && left.hasNext) {\n\n if (!done) {\n val p = left.next\n if (prevLeftX < p.c - 1) {\n separateIds = leftIds.result\n done = true\n } else {\n leftIds += p.id\n prevLeftX = p.c\n }\n }\n\n if (!done) {\n val p = right.next\n if (prevRightX > p.c + 1) {\n separateIds = rightIds.result\n done = true\n } else {\n rightIds += p.id\n prevRightX = p.c\n }\n }\n\n if (!done) {\n val p = top.next\n if (prevTopY < p.c - 1) {\n separateIds = topIds.result\n done = true\n } else {\n topIds += p.id\n prevTopY = p.c\n }\n }\n\n if (!done) {\n val p = bottom.next\n if (prevBottomY > p.c + 1) {\n separateIds = bottomIds.result\n done = true\n } else {\n bottomIds += p.id\n prevBottomY = p.c\n }\n }\n\n if (prevLeftX >= prevRightX && prevTopY >= prevBottomY) done = true\n }\n\n if (separateIds.nonEmpty) recurse(keepIdsByX, keepIdsByY, separateIds)\n else 1\n }\n\n val allByX, allByY = new TreeSet[Pair]\n\n for (i <- 0 until n) {\n allByX.add(xs(i))\n allByY.add(ys(i))\n }\n\n println(count(allByX, allByY))\n}"}], "negative_code": [], "src_uid": "6b1105f4b7b5fc2b77459cafd75ddb6c"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val name = next.toCharArray\n val letters = new Array[Char](27)\n val positions = new Array[Int](n)\n for (i <- 0 until n) {\n positions(i) = name(i) - 'a'\n letters(positions(i)) = name(i)\n }\n for (i <- 0 until m) {\n val x = next.toCharArray.apply(0)\n val y = next.toCharArray.apply(0)\n var ind = -1\n for (j <- 0 until 27) {\n if (letters(j) == x) {\n letters(j) = y\n ind = j\n }\n }\n for (j <- 0 until 27) {\n if (letters(j) == y && j != ind) {\n letters(j) = x\n }\n }\n }\n for (i <- 0 until positions.length) {\n out.print(letters(positions(i)))\n }\n return 0\n }\n}\n", "positive_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._\nimport scala.math.Ordering.Implicits._\n\nimport CodeForcesApp._\n\nobject _591B extends CodeForcesApp {\n override type Result = String\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val (l, n) = (nextInt(), nextInt())\n val s = nextString()\n var d = Map.empty[Char, Char]\n repeat(n) {\n val (x, y) = (nextChar(), nextChar())\n if (x != y) {\n var (f1, f2) = (false, false)\n d = d map {\n case (i, `x`) =>\n f1 = true\n i -> y\n case (i, `y`) =>\n f2 = true\n i -> x\n case i => i\n }\n if(!f1) d = d + (x -> y)\n if(!f2) d = d + (y -> x)\n }\n }\n s map {i => d.getOrElse(i, i)}\n }\n\n override def format(result: Result) = super.format(result)\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n/********************************[Scala Scanner]*********************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * @return Unlike the Java scanner which returns till end of current line, this actually returns the next line\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n def lineNumber: Int = reader.getLineNumber\n def nextString(): String = next()\n def nextChar(): Char = next().head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def hasNext = tokenizer().exists(_.hasMoreTokens)\n override def next() = tokenizer().get.nextToken()\n override def close() = reader.close()\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._\nimport scala.math.Ordering.Implicits._\n\nimport CodeForcesApp._\n\nobject _591B extends CodeForcesApp {\n override type Result = String\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val (l, n) = (nextInt(), nextInt())\n val s = nextString()\n var d = Map.empty[Char, Char]\n repeat(n) {\n val (x, y) = (nextChar(), nextChar())\n if (x != y) {\n var (f1, f2) = (false, false)\n d = d map {\n case (i, `x`) =>\n f1 = true\n i -> y\n case (i, `y`) =>\n f2 = true\n i -> x\n case i => i\n }\n if(!f1) d = d + (x -> y)\n if(!f2) d = d + (y -> x)\n //debug(x, y, f1, f2, d)\n }\n }\n s map {i => d.getOrElse(i, i)}\n }\n\n override def format(result: Result) = super.format(result)\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n/********************************[Scala Scanner]*********************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines: Iterator[String] = Iterator.continually(reader.readLine()).takeWhile(_ != null)\n\n def tokens: Iterator[String] = for {\n line <- lines\n tokenizer = new StringTokenizer(line)\n _ <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)\n } yield tokenizer.nextToken()\n\n private[this] var current = tokens\n override def hasNext = current.hasNext\n @inline override def next() = current.next()\n\n /**\n * @return Unlike the Java scanner which returns till end of current line, this actually returns the next line\n */\n def nextLine(): String = {\n current = tokens // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def nextString(): String = next()\n def nextChar(): Char = next().head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def close() = reader.close()\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val str = readLine().toCharArray\n\n val M = scala.collection.mutable.Map[Char, Char]()\n for (ch <- 'a' to 'z') {\n M(ch) = ch\n }\n\n def change(from: Char, to: Char) = {\n if (from != to) {\n var curr1 = from\n while (M(curr1) != from) curr1 = M(curr1)\n\n var curr2 = to\n while (M(curr2) != to) curr2 = M(curr2)\n\n M(curr1) = to\n M(curr2) = from\n }\n }\n\n for (i <- 1 to m) {\n val Array(x, y) = readLine().split(\" \").map(_.charAt(0))\n change(x, y)\n }\n\n println(str.map { ch => M(ch)}.mkString(\"\"))\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\nimport java.util.HashMap\nimport java.util.HashSet\n\nobject B {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n// class XXX(val number:Int, var x: Int) {\n// override def toString(): String = {\n// return number + \"(\" + x + \")\"\n// }\n// }\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(sa2.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n val n = line1.nextToken().toInt\n val m = line1.nextToken().toInt\n \n var name = br.readLine()\n \n// val actions = new Array[(Char, Char)](m)\n// val\n val map = new HashMap[Char, HashSet[Char]]()\n for (i <- 0 until m) {\n val acL = br.readLine().split(\" \")\n val (c1, c2) = (acL(0)(0), acL(1)(0))\n \n if (c1 != c2) {\n var cur1 = map.get(c1)\n if (cur1 != null) {\n map.remove(c1);\n } else {\n cur1 = new HashSet()\n cur1.add(c1)\n }\n \n \n var cur2 = map.get(c2)\n if (cur2 != null) {\n map.remove(c2);\n } else {\n cur2 = new HashSet()\n cur2.add(c2)\n }\n \n val prev1 = map.get(c2)\n if (prev1 != null) cur1.addAll(prev1)\n map.put(c2, cur1)\n// db(mkMP)\n val prev2 = map.get(c1)\n if (prev2 != null) cur2.addAll(prev2)\n map.put(c1, cur2)\n// db(mkMP)\n }\n \n }\n\n// def mkMP(): String = {\n// var res = \"\"\n// val it = map.entrySet().iterator()\n// while (it.hasNext()) {\n// val entry = it.next()\n// val to = entry.getKey()\n// res += to + \"->[\"\n// val from = entry.getValue()\n// val fromIt = from.iterator()\n// while (fromIt.hasNext()) {\n// res+= fromIt.next() + \", \"\n// }\n// res += \"]\"\n// }\n// res\n// }\n \n val map2 = new HashMap[Char, Char]()\n val it = map.entrySet().iterator()\n while (it.hasNext()) {\n val entry = it.next()\n val to = entry.getKey()\n val from = entry.getValue()\n val fromIt = from.iterator()\n while (fromIt.hasNext()) {\n map2.put(fromIt.next(), to);\n }\n }\n \n var res2 = new StringBuffer()\n for(i <- name) {\n if (map2.containsKey(i)) {\n res2.append(map2.get(i))\n } else \n res2.append(i)\n }\n \n println(res2.toString())\n \n //---------------------------- parameters reading end --------------------------------\n \n \n }\n \n//========================= samples ========================\nval sa1 = \"\"\"6 1\npolice\np m\n\"\"\" \n \nval sa2 = \"\"\"\n11 6\nabacabadaba\na b\nb c\na d\ne g\nf a\nb b\n\"\"\"\n\n//========================= samples end ==================== \n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val str = in.next()\n var map = ('a' to 'z').map(i => i -> i).toMap\n var backMap = ('a' to 'z').map(i => i -> i).toMap\n val nMap = (1 to m).foreach { _ =>\n val Array(a, b) = in.next().split(' ').map(_.head)\n val fa = backMap(a)\n val fb = backMap(b)\n map += (fa -> b)\n map += (fb -> a)\n backMap += (b -> fa)\n backMap += (a -> fb)\n }\n println(str.map(map).mkString)\n}"}, {"source_code": "object B591 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val name = read.toCharArray\n val map = ('a' to 'z').toArray\n for(_ <- 1 to m) {\n val Array(x, y) = readChars(2)\n for(i <- 0 until 26)\n if(map(i) == x)\n map(i) = y\n else if(map(i) == y)\n map(i) = x\n }\n for(i <- name.indices)\n if(map(name(i)-'a') != -1)\n name(i) = map(name(i)-'a')\n println(name.mkString(\"\"))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readChars(n: Int): Array[Char] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.head)\n }\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object B591 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val name = read.toCharArray\n val map = ('a' to 'z').toArray\n for(_ <- 1 to m) {\n val Array(x, y) = readChars(2)\n for(i <- 0 until 26)\n if(map(i) == x)\n map(i) = y\n else if(map(i) == y)\n map(i) = x\n }\n println(name.map(a => map(a-'a')).mkString(\"\"))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readChars(n: Int): Array[Char] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.head)\n }\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val s = readLine.toCharArray\n \n val to = Array.tabulate('z' + 1)(i => i.toChar)\n \n for (_ <- 1 to m) {\n val r = readLine\n val x = r(0)\n val y = r(2)\n for (i <- 'a' to 'z') {\n if (to(i) == x) to(i) = y\n else if (to(i) == y) to(i) = x\n }\n }\n\n val res = s.map(c => to(c)).mkString\n \n println(res)\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val str = readLine().toCharArray\n\n val M = scala.collection.mutable.Map[Char, Char]()\n for (ch <- 'a' to 'z') {\n M(ch) = ch\n }\n\n def change(from: Char, to: Char) = {\n var curr = from\n while (M(curr) != from) curr = M(curr)\n M(curr) = to\n\n curr = to\n while (M(curr) != to) curr = M(curr)\n M(curr) = from\n }\n\n for (i <- 1 to m) {\n val Array(x, y) = readLine().split(\" \").map(_.charAt(0))\n change(x, y)\n }\n\n println(str.map { ch => M(ch)}.mkString(\"\"))\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\nimport java.util.HashMap\nimport java.util.HashSet\n\nobject B {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n// class XXX(val number:Int, var x: Int) {\n// override def toString(): String = {\n// return number + \"(\" + x + \")\"\n// }\n// }\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(sa2.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n val n = line1.nextToken().toInt\n val m = line1.nextToken().toInt\n \n var name = br.readLine()\n \n// val actions = new Array[(Char, Char)](m)\n// val\n val map = new HashMap[Char, HashSet[Char]]()\n for (i <- 0 until m) {\n val acL = br.readLine().split(\" \")\n val (c1, c2) = (acL(0)(0), acL(1)(0))\n \n if (c1 != c2) {\n var cur1 = map.get(c1)\n if (cur1 != null) {\n map.remove(c1);\n } else {\n cur1 = new HashSet()\n cur1.add(c1)\n }\n \n \n var cur2 = map.get(c2)\n if (cur2 != null) {\n map.remove(c2);\n } else {\n cur2 = new HashSet()\n cur2.add(c2)\n }\n \n val prev1 = map.get(c2)\n if (prev1 != null) cur1.addAll(prev1)\n map.put(c2, cur1)\n db(mkMP)\n val prev2 = map.get(c1)\n if (prev2 != null) cur2.addAll(prev2)\n map.put(c1, cur2)\n db(mkMP)\n }\n \n }\n\n def mkMP(): String = {\n var res = \"\"\n val it = map.entrySet().iterator()\n while (it.hasNext()) {\n val entry = it.next()\n val to = entry.getKey()\n res += to + \"->[\"\n val from = entry.getValue()\n val fromIt = from.iterator()\n while (fromIt.hasNext()) {\n res+= fromIt.next() + \", \"\n }\n res += \"]\"\n }\n res\n }\n \n val map2 = new HashMap[Char, Char]()\n val it = map.entrySet().iterator()\n while (it.hasNext()) {\n val entry = it.next()\n val to = entry.getKey()\n val from = entry.getValue()\n val fromIt = from.iterator()\n while (fromIt.hasNext()) {\n map2.put(fromIt.next(), to);\n }\n }\n \n val map2It = map2.entrySet().iterator()\n while (map2It.hasNext()) {\n val couple = map2It.next()\n name = name.replace(couple.getKey(), couple.getValue())\n }\n println(name)\n \n //---------------------------- parameters reading end --------------------------------\n \n \n }\n \n//========================= samples ======================== \nval sa2 = \"\"\"\n11 6\nabacabadaba\na b\nb c\na d\ne g\nf a\nb b\n\"\"\"\n\n//========================= samples end ==================== \n}"}], "src_uid": "67a70d58415dc381afaa74de1fee7215"} {"source_code": "\nobject Main extends App {\n class PipedObject[T] private[Main] (value:T)\n\t{\n\t\tdef |>[R] (f : T => R) = f(this.value)\n\t}\n\timplicit def toPiped[T] (value:T) = new PipedObject[T](value)\n\tdef divisible6(a: Long) = if (a % 6 == 0) true else false\n\tdef isPrime(n: Int) = (2 to n) |> (r => r.foldLeft(r.toSet)((ps, x) => if (ps(x)) ps -- (x * x to n by x) else ps))\n\t//println( 5L * 7L |> divisible6)\n\t//println( isPrime(25)) \n\tdef calc(n:Int,p:Int): Int = p + (if( 2*p <= n) calc(n, 2*p) else 0)\n\tvar n = readInt()\n\tfor(i <- 1 to n) {\n\t\tvar r = readInt()\n\t println( (r * 1L * (r+1)) / 2 - 2 * calc(r, 1))\n\t}\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Test extends App {\n val ncase = StdIn.readInt()\n for (i <- 0 until ncase) {\n val n = StdIn.readLong()\n val allSum = if (n % 2 == 0) n / 2 * (n + 1) else (n + 1) / 2 * n\n var partialSum: Long = 0\n var pow2: Long = 1\n while (pow2 <= n) {\n partialSum += pow2\n pow2 <<= 1\n }\n println(allSum - partialSum * 2)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject A {\n def main(args: Array[String]): Unit = {\n val T = StdIn.readInt()\n for (_ <- 1 to T) {\n val n = StdIn.readLong()\n var ans = n * (n + 1) / 2\n var t = 1\n while (t <= n) {\n ans -= 2 * t\n t *= 2\n }\n println(ans)\n }\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val t = in.next().toInt\n\n def squares(n: Long): Long = {\n var res = 1l\n var sum = 0l\n while (res <= n) {\n sum += res\n res *= 2\n }\n sum\n }\n\n def sum(n: Long): Long = {\n (n + 1) * n / 2 - 2 * squares(n)\n }\n\n\n println((1 to t).map(i => sum(in.next().toInt)).mkString(\"\\n\"))\n}\n"}, {"source_code": "object A598 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(t) = readInts(1)\n for(_ <- 1 to t) {\n val Array(n) = readLongs(1)\n val log = (math.log(n)/math.log(2)).toInt\n\n var ret = (n*(n+1))/2\n for(i <- 0 to log) {\n ret -= math.pow(2, i+1).toLong\n }\n println(ret)\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val t = nextInt\n for (i <- 0 until t) {\n val n = nextInt\n var firstSumPart = 1L * n * (1L + n) / 2\n var num = 1L\n while (num <= n) {\n firstSumPart -= 2L * num\n num *= 2L\n }\n out.println(firstSumPart)\n }\n return 0\n }\n}\n"}, {"source_code": "object A01TrickySum {\n //import java.io.{InputStream, PrintStream}\n //import java.util.Scanner\n import scala.io.StdIn._\n def solve(/*input: InputStream, output: PrintStream*/): Unit = {\n //val sc = new Scanner(input)\n val t = readInt\n (1 to t).foreach( i => {\n val n = readLong()\n val sumaContinua = (n * (n + 1)) / 2L\n //maximo k tal que 2**k <= n\n val k = (0 until 32).filter( i => (1L << i) <= n).last\n val suma2k_1 = (1L << (k + 1)) - 1L\n val ans = sumaContinua - 2L * suma2k_1\n println(ans)\n\n })\n }\n def main(args: Array[String]): Unit = {\n solve(/*System.in,System.out*/)\n }\n\n}\n"}, {"source_code": "object A01TrickySum {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n def solve(input: InputStream, output: PrintStream): Unit = {\n val sc = new Scanner(input)\n val t = sc.nextInt\n (1 to t).foreach( i => {\n val n = sc.nextLong()\n val sumaContinua = (n * (n + 1)) / 2L\n //maximo k tal que 2**k <= n\n val k = (0 until 32).filter( i => (1L << i) <= n).last\n val suma2k_1 = (1L << (k + 1)) - 1L\n val ans = sumaContinua - 2L * suma2k_1\n output.println(ans)\n\n })\n }\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n\n}\n"}, {"source_code": "\n\nobject Main extends App {\n val ans = (n:Long) => n*(n+1)/2 -Stream.from(0).map(BigInt(0) setBit _ ).dropWhile(_<=n).tail.head+2\n val n = readInt()\n\n for(a <- 1 to n) {\n val x = readInt()\n println(ans(x))\n }\n}\n"}, {"source_code": "\n\nobject Main extends App {\n val ans = (n:Long) => n*(n+1)/2 -(0 to 1000).toList.map(BigInt(0) setBit _ ).dropWhile(_<=n).tail.head+2\n val n = readInt()\n\n for(a <- 1 to n) {\n val x = readInt()\n println(ans(x))\n }\n}\n"}, {"source_code": "\n\nobject Main extends App {\n val ans = (n:Long) => n*(n+1)/2 -(0 to 1000).map(BigInt(0) setBit _ ).dropWhile(_<=n).tail.head+2\n val n = readInt()\n\n for(a <- 1 to n) {\n val x = readInt()\n println(ans(x))\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject Test extends App {\n val ncase = StdIn.readInt()\n for (i <- 0 until ncase) {\n val n = StdIn.readLong()\n val allSum = if (n % 2 == 0) n / 2 * (n + 1) else (n + 1) / 2 * n\n var partialSum: Long = 0\n var pow2: Long = 1\n while (pow2 < n) {\n partialSum += pow2\n pow2 <<= 1\n }\n println(allSum - partialSum * 2)\n }\n}"}], "src_uid": "a3705f29b9a8be97a9e9e54b6eccba09"} {"source_code": "object Main extends App {\n\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n val table = (0 to n-1) map { _ =>\n readLine.split(\"\").filterNot(_ == \"\")\n } toList\n\n def isSorted(seq: List[String]): Boolean = {\n seq.isEmpty ||\n 0 == (seq zip seq.tail map { case (a1, a2) => a2 >= a1 } count (_ == false))\n }\n\n def columnAt(index: Int): List[String] = {\n table map { case r => r(index) }\n }\n\n val init = (Stream.fill(n)(\"\").toList, 0)\n val (_, rem) = (0 to m-1).foldLeft(init)({\n case ((rows, removed), index) =>\n val cs = columnAt(index)\n val next = (rows zip cs) map { case (row, c) => row + c }\n if(isSorted(next)) (next, removed) else (rows, removed+1)\n })\n\n println(rem)\n\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val ss = Array.fill(n){ readLine }\n\n var equalToPrev = Array.fill(n){ true }\n equalToPrev(0) = false\n var removedCount = 0\n \n for (col <- 0 until m) {\n var prev = ss(0)(col)\n val equalToPrev2 = equalToPrev.clone()\n var remove = false\n for (row <- 1 until n) {\n val curr = ss(row)(col)\n if (prev > curr && equalToPrev(row)) {\n remove = true\n } else if (prev < curr) {\n equalToPrev2(row) = false\n }\n prev = curr\n }\n if (remove) removedCount += 1\n else equalToPrev = equalToPrev2\n }\n \n println(removedCount)\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val marked = Array.ofDim[Boolean](m)\n val data = (1 to n).map(_ => in.next())\n val t = (0 until m).foldLeft((0, List((0, n - 1)))) {\n case(acc@(_, Nil), i) =>\n// println(\"heere\")\n acc\n case((x, list), i) =>\n// println(list)\n// println(i)\n// println(x)\n val remove = list.exists {\n case(first, last) => (first until last).exists(j => data(j)(i) > data(j + 1)(i))\n }\n if (remove)\n (x + 1, list)\n else {\n (x, list.flatMap{\n case(first, last) =>\n val res = (first until last).filter(j => data(j)(i) != data(j + 1)(i))\n// println(\"res\")\n// println(res)\n// println((first until last).toList)\n// println(\"-----------\")\n val ans = res.foldLeft((first, List.empty[(Int, Int)])) {\n case((prev, ll), z) => (z + 1, (prev, z) :: ll)\n }\n ((ans._1, last) :: ans._2).filter(i => i._1 != i._2)\n })\n }\n }\n println(t._1)\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val marked = Array.ofDim[Boolean](m)\n val data = (1 to n).map(_ => in.next())\n val t = (0 until m).foldLeft((0, List((0, n - 1)))) {\n case(acc@(_, Nil), i) =>\n// println(\"heere\")\n acc\n case((x, list), i) =>\n// println(list)\n// println(i)\n// println(x)\n val remove = list.exists {\n case(first, last) => (first until last).exists(j => data(j)(i) > data(j + 1)(i))\n }\n if (remove)\n (x + 1, list)\n else {\n (x, list.flatMap{\n case(first, last) =>\n val res = (first until last).filter(j => data(j)(i) != data(j + 1)(i))\n// println(\"res\")\n// println(res)\n// println((first until last).toList)\n// println(\"-----------\")\n val ans = res.foldLeft((0, List.empty[(Int, Int)])) {\n case((prev, ll), z) => (z + 1, (prev, z) :: ll)\n }\n ((ans._1, last) :: ans._2).filter(i => i._1 != i._2)\n })\n }\n }\n println(t._1)\n}\n"}, {"source_code": "object Main extends App {\n\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n val table = (0 to n-1) map { _ =>\n readLine.split(\"\").filterNot(_ == \"\")\n } toList\n\n def isSorted(seq: List[String]): Boolean = {\n seq.isEmpty ||\n 0 == (seq zip seq.tail map { case (a1, a2) => a2 >= a1 } count (_ == false))\n } \n\n def column(rows: Set[Int], index: Int): List[(String, Int)] = {\n table.zipWithIndex flatMap { case (r, i) => if(rows.contains(i)) List((r(index), i)) else List() }\n }\n\n def filterEq(column: List[(String, Int)]): Set[Int] = {\n column.groupBy(_._1).flatMap({\n case (v, indices) => if(indices.size > 1) indices.map(_._2) else List()\n }).toSet\n }\n\n val init = ((0 to n-1).toSet, 0)\n val (_, rem) = (0 to m-1).foldLeft(init)({\n case ((rows, removed), index) =>\n val cs = column(rows, index)\n if(isSorted(cs.map(_._1))) {\n (filterEq(cs), removed)\n } else {\n (rows, removed+1)\n }\n })\n\n println(rem)\n\n}"}, {"source_code": "object Main extends App {\n\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n val table = (0 to n-1) map { _ =>\n readLine.split(\"\").filterNot(_ == \"\")\n } toList\n\n def isSorted(seq: List[String]): Boolean = {\n 0 == (seq zip seq.tail map { case (a1, a2) => a2 >= a1 } count (_ == false))\n } \n\n def isSortedAt(index: Int): Boolean = {\n isSorted(table map { r => r(index) })\n }\n\n println((0 to m-1) count (index => !isSortedAt(index)) )\n\n}"}], "src_uid": "a45cfc2855f82f162133930d9834a9f0"} {"source_code": "import scala.io.StdIn\n\nobject StringGame {\n\n def step(n: List[Char], a: Char): List[Char] = n match {\n case Nil => List(a)\n case x :: xs => if (x == a) xs else a :: n\n }\n\n def main(args: Array[String]): Unit = {\n val in = StdIn.readLine().toList\n val res = in.foldLeft[List[Char]](List())(step)\n val isFirstWinner = (in.length - res.length) / 2 % 2 == 1\n println(if (isFirstWinner) \"YES\" else \"NO\")\n }\n\n// def main(args: Array[String]): Unit = {\n// val in = StdIn.readLine()\n// var acc = \"\"\n// in.foreach { ch =>\n// acc = step(acc, ch)\n// }\n//\n// val isFirstWinner = (in.length - acc.length) / 2 % 2 == 1\n// println(if (isFirstWinner) \"YES\" else \"NO\")\n// }\n}", "positive_code": [{"source_code": "object Main {\n\n def main(args: Array[String]) {\n val std = scala.io.StdIn\n\n val n = std.readLine()\n\n var stack = List.empty[Char]\n \n var count = 0\n \n for (i <- 0 until n.length) {\n if (stack.isEmpty || stack.head != n(i)) {\n stack = n(i) :: stack\n }\n else {\n stack = stack.tail\n count += 1\n }\n }\n \n if (count % 2 == 0) {\n println(\"No\")\n }\n else {\n println(\"Yes\")\n }\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S = ns()\n val N = S.length\n var cnt = 0\n\n val stack = mutable.Stack[Char]()\n REP(N) { i =>\n if (stack.nonEmpty && stack.head == S(i)) {\n cnt += 1\n stack.pop()\n } else {\n stack.push(S(i))\n }\n }\n\n if (cnt % 2 == 0) {\n out.println(\"No\")\n } else {\n out.println(\"Yes\")\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S = ns()\n val N = S.length\n var cnt = 0\n val del = Array.ofDim[Boolean](N)\n REP(N) { i =>\n var j = 0\n while (i + j < N && i - 1 - j >= 0 && S(i + j) == S(i - 1 - j) && !del(i - 1 - j)) {\n cnt += 1\n del(i + j) = true\n del(i - 1 - j) = true\n j += 1\n }\n }\n\n if (cnt % 2 == 0) {\n out.println(\"No\")\n } else {\n out.println(\"Yes\")\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject StringGame {\n\n def play(s: String): String = if (s.isEmpty) s else step(s.head, play(s.tail))\n\n def step(a: Char, n: String): String = if (n.startsWith(a.toString)) n.drop(1) else a + n\n\n def main(args: Array[String]): Unit = {\n val in = StdIn.readLine()\n val res = play(in)\n val isFirstWinner = (in.length - res.length) / 2 % 2 == 1\n println(isFirstWinner)\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn\n\nobject StringGame {\n\n def play(s: String): String = if (s.isEmpty) s else step(s.head, play(s.tail))\n\n def step(a: Char, n: String): String = if (n.startsWith(a.toString)) n.drop(1) else a + n\n\n def main(args: Array[String]): Unit = {\n val in = StdIn.readLine()\n val res = play(in)\n val isFirstWinner = (in.length - res.length) / 2 % 2 == 1\n println(res)\n }\n}"}], "src_uid": "8fd51c391728b433cc94923820e908ff"} {"source_code": "import scala.io.StdIn._\n\nobject Main2 extends App {\n val Array(_, lastCoordinate) = readLine().split(\" \").map(_.toInt)\n val lanternsCoordinates = readLine().split(\" \").map(_.toInt).toVector.sorted\n val maxDistanceBetweenLanterns = lanternsCoordinates\n .foldLeft[(Int, Int)]((0, lanternsCoordinates.head)){ case ((maxDistance, previousCoordinate), currentCoordinate) =>\n (Math.max(maxDistance, currentCoordinate - previousCoordinate), currentCoordinate)\n }._1\n println(Vector(lanternsCoordinates.head, maxDistanceBetweenLanterns/2.0, lastCoordinate - lanternsCoordinates.last).max)\n}\n", "positive_code": [{"source_code": "\nobject B {\n def main(args: Array[String]) = {\n val nl = readLine().split(' ').map(t => t.toInt)\n val n = nl(0)\n val l = nl(1)\n val lamps = readLine().split(' ').map(t => t.toInt).sorted\n var ans = 2 * math.max(l - lamps(n - 1), lamps(0))\n for (i <- lamps.indices) {\n if (i + 1 < lamps.length) {\n ans = math.max(ans, lamps(i + 1) - lamps(i))\n }\n }\n println(ans / 2.0)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\nimport java.util.StringTokenizer\n\nobject Solution {\n def solve(in: FastScanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val l = in.nextInt()\n val a = new Array[Int](n)\n for (i <- 0 until n)\n a(i) = in.nextInt()\n Arrays.sort(a)\n var res: Double = Math.max(a(0), l - a(n - 1))\n for (i <- 1 until n)\n res = Math.max(res, (a(i) - a(i - 1)) / 2.0)\n println(res)\n }\n\n def main(args: Array[String]): Unit = {\n val in = new FastScanner(System.in)\n val out = new PrintWriter(System.out)\n solve(in, out)\n out.flush()\n }\n\n class FastScanner(val in: InputStream) {\n var st: StringTokenizer = null\n var br = new BufferedReader(new InputStreamReader(in))\n\n def next(): String = {\n while (st == null || !st.hasMoreTokens()) {\n val line = br.readLine()\n if (line == null)\n throw new IOException()\n st = new StringTokenizer(line)\n }\n return st.nextToken()\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def close(): Unit = {\n br.close()\n }\n }\n\n}"}, {"source_code": "import scala.math.Ordering._\n\nobject Main extends App {\n val Array(n, l) = readLine.split(\" \").map(_.toInt)\n val fs: List[Int] = readLine.split(\" \").map(_.toInt).toList\n val row: List[Int] = fs.sorted\n val dm: List[Int] = (row zip row.tail).map({\n case (a, b) => b - a\n })\n val d = if(dm.isEmpty) 0 else dm.max\n println(\"%.9f\".format(List(d/2.0, row.head - 0.0, l - row.last).max))\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject TaskA extends App {\n val (n, l) = readLine.split(\" \").map(_.toInt).toList match {\n case x :: y :: Nil => (x, y)\n }\n\n val lanterns = readLine.split(\" \").map(_.toInt).toList.sorted\n val dists = (lanterns.head * 2) :: ((l - lanterns.reverse.head) * 2) :: lanterns.zip(lanterns.tail).map { case (l1, l2) => (l2 - l1) }\n\n println(dists.sorted.reverse.head / 2.0)\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nimport scala.Array.canBuildFrom\n\nobject _492B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val l = next.toLong\n val a = (1 to n).map(i => next.toLong).sorted.toArray\n val b = (a :+ (-a(0)) :+ (2 * l - a.last)).sorted\n val c = (1 until b.length).map(i => (b(i) - b(i - 1)) / 2.0)\n val ans = c.max\n println(\"%.14f\".format(ans))\n}\n"}, {"source_code": "object B492 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, l) = readLongs(2)\n val input = readLongs(n.toInt).sortBy(identity)\n var res = math.max(2*input.head, 2*(l-input.last))\n for(i <- 1 until input.length) {\n res = math.max(res, input(i)-input(i-1))\n }\n println(res/2.0)\n }\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, l) = readInts(2)\n val as = readInts(n).distinct.sorted\n\n var prev = 0\n var max = as(0).toDouble\n \n for (a <- as) {\n max = math.max(max, (a - prev) / 2.0)\n prev = a\n }\n max = math.max(max, l - as.last)\n \n println(max)\n}"}, {"source_code": "import scala.io.StdIn\n\nobject A extends App {\n\n val Array(m, n) = StdIn.readLine().split(\" \").map(_.toLong)\n\n val arr = StdIn.readLine().split(\" \").map(_.toDouble).sortWith(_ < _)\n\n val result = if (arr.length == 1) 0 else arr.iterator.sliding(2).withPartial(false).map { x =>\n (x(1) - x.head)/2\n }.max\n\n\n var max = Math.max(arr.head, n - arr.last)\n\n println(Math.max(result, max))\n\n}\n"}], "negative_code": [{"source_code": "object B492 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, l) = readLongs(2)\n val input = readLongs(n.toInt).sortBy(identity)\n var res = math.max(2*input.head, 2*(n-input.last))\n for(i <- 1 until input.length) {\n res = math.max(res, input(i)-input(i-1))\n }\n println(res/2.0)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject A extends App {\n\n val Array(n, m) = StdIn.readLine().split(\" \").map(_.toLong)\n\n val arr = StdIn.readLine().split(\" \").map(_.toDouble)\n\n val result = arr.iterator.sliding(2).withPartial(false).map { x =>\n (x(1) - x.head)/2\n }.max\n\n var max = Math.max(arr.head, n - arr.last)\n\n println(Math.max(result, max))\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject A extends App {\n\n val Array(n, m) = StdIn.readLine().split(\" \").map(_.toLong)\n\n val arr = StdIn.readLine().split(\" \").map(_.toDouble).sortWith(_ < _)\n\n val result = arr.iterator.sliding(2).withPartial(false).map { x =>\n (x(1) - x.head)/2\n }.max\n\n var max = Math.max(arr.head, n - arr.last)\n\n println(Math.max(result, max))\n\n}\n"}, {"source_code": "import scala.math.Ordering._\n\nobject Main extends App {\n val Array(n, l) = readLine.split(\" \").map(_.toInt)\n val fs: List[Int] = readLine.split(\" \").map(_.toInt).toList\n val row: List[Int] = fs.sorted :+ l\n val d: Int = (row zip row.tail).map({\n case (a, b) => b - a\n }).max\n println(\"%.9f\".format(d/2.0))\n}"}, {"source_code": "import scala.math.Ordering._\n\nobject Main extends App {\n val Array(n, l) = readLine.split(\" \").map(_.toInt)\n val fs: List[Int] = readLine.split(\" \").map(_.toInt).toList\n val row: List[Int] = 0 :: fs.sorted\n val d: Int = (row zip row.tail).map({\n case (a, b) => b - a\n }).max\n println(\"%.9f\".format(List(d/2.0, row.head - 0.0, l - row.last).max))\n}"}], "src_uid": "d79166497eb61d81fdfa4ef80ec1c8e8"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt\n val s = readLine\n val t = s.split(\" \").map(i => i.toInt)\n\n println( ((2 until n/2).filter(m => n%m == 0).map(step => {\n (0 until step).map(start =>\n (start until n by step).map(t).sum\n ).max\n }) :+ t.sum).max )\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val divs = (2 to n / 3).filter(i => n % i == 0)\n val data = in.next().split(\" \").map(_.toLong)\n var max = data.sum\n divs.foreach { i =>\n var j = 0\n while (j < i) {\n var k = j\n var candidate = 0l\n while (k < n) {\n candidate += data(k)\n k += i\n }\n max = Math.max(candidate, max)\n j += 1\n }\n }\n println(max)\n}"}, {"source_code": "object D158 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n)\n var res = in.sum\n val div = divisors(n).filter(n/_ > 2)\n for(d <- div) {\n for(i <- 0 until d) {\n var curr = 0\n for(j <- 0 until n/d) {\n curr += in((i+d*j)%n)\n }\n res = math.max(res, curr)\n }\n }\n println(res)\n }\n\n def divisors(n: Int): Array[Int] = {\n (1 to n/2).filter(i => n % i == 0).toArray\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n// private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object D158 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n)\n var res = in.sum\n val div = divisors(n).filter(n/_ > 2)\n for(d <- div) {\n for(i <- 0 until d) {\n var curr = 0\n for(j <- 0 until n/d) {\n curr += in((i+d*j)%n)\n }\n res = math.max(res, curr)\n }\n }\n println(res)\n }\n\n def divisors(n: Int): Array[Int] = {\n val ret = cu.ArrayBuffer.empty[Int]\n var i = 1\n while(i*i <= n) {\n if(n%i == 0)\n ret.append(i, n/i)\n i += 1\n }\n ret.toArray\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n// private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject D {\n val in = new Scanner(System.in)\n\n def main(args: Array[String]) {\n val n = in.nextInt\n val s = Array.fill[Int](n)(in.nextInt())\n var max = Int.MinValue\n for (d <- 1 to n / 3 if n % d == 0) {\n val sum = Array.ofDim[Int](d)\n for (i <- 0 until s.length) {\n sum(i % d) += s(i)\n }\n max = max max sum.max\n }\n println(max)\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P158D extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val t = Array.fill(N)(sc.nextInt)\n\n val divisors = (1 to N / 3).filter(N % _ == 0)\n\n def svalue(d: Int, r: Int) = {\n @tailrec\n def loop(acc: Int, i: Int): Int =\n if (i >= N) acc\n else loop(acc + t(i), i + d)\n loop(0, r)\n }\n\n val answer = {\n for {\n d <- divisors\n r <- 0 until d\n } yield svalue(d, r)\n }.max\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "object IceSculptures extends App {\n import java.io._\n import java.util.{Scanner => Input}\n\n val in = new Input(new BufferedReader(new InputStreamReader(System.in)))\n val n = in.nextInt\n val a = new Array[Int](n + 1)\n for (i <- 1 to n) a(i) = in nextInt\n\n val s = new Array[Int](n + 1)\n var ans = Int.MinValue\n for (l <- 1 to n)\n if (n % l == 0 && n / l >= 3) {\n for (i <- n to (1, -1)) {\n s(i) = a(i) + (if (i + l <= n) s(i + l) else 0)\n if (i <= l && s(i) > ans)\n ans = s(i)\n }\n }\n println(ans)\n}"}, {"source_code": "import java.io._\nimport java.util._\n\nobject TaskD {\n def main(args: Array[String]) {\n val in = new InputReader(System.in)\n val n = in.nextInt\n val s = Array.fill[Int](n)(in.nextInt)\n var max = Int.MinValue\n for (d <- 1 to n / 3 if n % d == 0) {\n val sum = Array.ofDim[Int](d)\n for (i <- 0 until s.length) {\n sum(i % d) += s(i)\n }\n max = max max sum.max\n }\n println(max)\n }\n\n class InputReader {\n def this(f: File) {\n this()\n try {\n br = new BufferedReader(new FileReader(f))\n }\n }\n\n def this(f: InputStream) {\n this()\n br = new BufferedReader(new InputStreamReader(f))\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n try {\n st = new StringTokenizer(br.readLine)\n }\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return java.lang.Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def nextLine: String = {\n try {\n return br.readLine\n }\n return null\n }\n\n private var br: BufferedReader = null\n private var st: StringTokenizer = null\n }\n\n}"}, {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n val n = readInt\n val a = readInts zip (0 until n)\n def ans = (3 to n).filter(n % _ == 0).map { x =>\n val groups = a.groupBy(_._2 % (n / x))\n groups.values.map { y: Array[(Int, Int)] =>\n y.map(_._1).sum\n }.max\n }.max\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val num = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val sums = (3 to num).flatMap{ i =>\n if ( num % i == 0) {\n val counts = num / i\n val sums = new Array[Int](counts)\n for(j <- 0 until a.size) {\n sums(j % counts) += a(j)\n }\n sums\n } else Nil\n }\n println(sums.max)\n }\n}"}, {"source_code": "object Main {\ndef main(args: Array[String]) {\nval n = readInt\nval s = readLine\nval t = s.split(\" \").map(i => i.toInt)\n\nprintln( ((2 until n/2).filter(m => n%m == 0).map(step => {\n(0 until step).map(start =>\n(start until n by step).map(t).sum\n).max\n}) :+ t.sum).max )\n}\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val divs = (2 to Math.sqrt(n).toInt).filter(i => n % i == 0 && n / i > 3)\n val data = in.next().split(\" \").map(_.toInt)\n var max = data.sum\n val indexed = data.zipWithIndex\n divs.foreach { i =>\n var j = 0\n while (j < i) {\n max = Math.max(indexed.foldLeft(0) { case(acc, (el, index)) => if (index % i == j) acc + el else acc}, max)\n j += 1\n }\n }\n println(max)\n}"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val divs = (1 to Math.sqrt(n).toInt).filter(n % _ == 0)\n val data = in.next().split(\" \").map(_.toInt)\n var max = 0\n val indexed = data.zipWithIndex\n divs.foreach { i =>\n var j = 0\n while (j < i) {\n max = Math.max(indexed.foldLeft(0) { case(acc, (el, index)) => if (index % i == j) acc + el else acc}, max)\n j += 1\n }\n }\n println(max)\n}"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val divs = (2 to Math.sqrt(n).toInt + 1).filter(i => n % i == 0 && n / i > 2)\n val data = in.next().split(\" \").map(_.toLong)\n var max = data.sum\n val indexed = data.zipWithIndex\n divs.foreach { i =>\n var j = 0\n while (j < i) {\n max = Math.max(indexed.foldLeft(0l) { case(acc, (el, index)) => if (index % i == j) acc + el else acc}, max)\n j += 1\n }\n }\n println(max)\n}"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val divs = (2 to Math.sqrt(n).toInt).filter(i => n % i == 0 && n / i > 2)\n val data = in.next().split(\" \").map(_.toInt)\n var max = data.sum\n val indexed = data.zipWithIndex\n divs.foreach { i =>\n var j = 0\n while (j < i) {\n max = Math.max(indexed.foldLeft(0) { case(acc, (el, index)) => if (index % i == j) acc + el else acc}, max)\n j += 1\n }\n }\n println(max)\n}"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val divs = (2 to Math.sqrt(n).toInt + 1).filter(i => n % i == 0 && n / i > 2)\n if (n == 13860)\n println(divs)\n val data = in.next().split(\" \").map(_.toLong)\n var max = data.sum\n val indexed = data.zipWithIndex\n divs.foreach { i =>\n var j = 0\n while (j < i) {\n max = Math.max(indexed.foldLeft(0l) { case(acc, (el, index)) => if (index % i == j) acc + el else acc}, max)\n j += 1\n }\n }\n println(max)\n}"}], "src_uid": "0ff4ac859403db4e29554ca7870f5490"} {"source_code": "import scala.io.StdIn\n\nobject SubstringRemoval extends App {\n\n val n = StdIn.readLine()\n val s = StdIn.readLine()\n\n val takeSimilar = (xs: IndexedSeq[(Char, Int)]) =>\n xs.takeWhile { case (c, i) =>\n if (i == 0) true\n else xs(i - 1)._1 == c\n }\n\n val first: Long = takeSimilar(s.zipWithIndex).length.toLong\n val second: Long = takeSimilar(s.reverse.zipWithIndex).length.toLong\n\n if (s.head == s.last) {\n println((2 * (first + second) + (first - 1) * (second - 1)) % 998244353)\n\n } else {\n println((first + second + 1) % 998244353)\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 998244353\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val S = ns(N)\n def countL() = {\n var l = 0\n while(l < N && S(l) == S(0)) {\n l += 1\n }\n l\n }\n\n def countR() = {\n var r = 0\n while (r < N && S(N - 1 - r) == S(N - 1)) {\n r += 1\n }\n r\n }\n\n val ans = if (S.forall(_ == S(0))) {\n // 全部一緒\n (N.toLong * (N + 1) / 2 - 1) % MOD\n\n } else if (S(0) == S(N - 1)) {\n // 左右が一緒\n val l = countL()\n val r = countR()\n (l + 1).toLong * (r + 1) % MOD\n } else {\n // 左右で違う\n val l = countL()\n val r = countR()\n l + r + 1\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n\n def debug(as: Array[Int], delimiter: String = \" \"): Unit = {\n debug(as.mkString(delimiter))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val S = ns(N)\n def countL() = {\n var l = 0\n while(l < N && S(l) == S(0)) {\n l += 1\n }\n l\n }\n\n def countR() = {\n var r = 0\n while (r < N && S(N - 1 - r) == S(N - 1)) {\n r += 1\n }\n r\n }\n\n val ans = if (S.forall(_ == S(0))) {\n // 全部一緒\n N.toLong * (N + 1) / 2\n\n } else if (S(0) == S(N - 1)) {\n // 左右が一緒\n val l = countL()\n val r = countR()\n (l + 1).toLong * (r + 1)\n } else {\n // 左右で違う\n val l = countL()\n val r = countR()\n l + r + 1\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n\n def debug(as: Array[Int], delimiter: String = \" \"): Unit = {\n debug(as.mkString(delimiter))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject SubstringRemoval extends App {\n\n val n = StdIn.readLine()\n val s = StdIn.readLine()\n\n val takeSimilar = (xs: IndexedSeq[(Char, Int)]) =>\n xs.takeWhile { case (c, i) =>\n if (i == 0) true\n else xs(i - 1)._1 == c\n }\n\n val first = takeSimilar(s.zipWithIndex).length.toLong\n val second = takeSimilar(s.reverse.zipWithIndex).length.toLong\n\n if (s.head == s.last) {\n println((2 * (first + second) % 998244353) % 998244353)\n } else {\n println((first + second + 1) % 998244353)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject SubstringRemoval extends App {\n\n val n = StdIn.readLine()\n val s = StdIn.readLine()\n\n val takeSimilar = (xs: IndexedSeq[(Char, Int)]) =>\n xs.takeWhile { case (c, i) =>\n if (i == 0) true\n else xs(i - 1)._1 == c\n }\n\n val first = takeSimilar(s.zipWithIndex).length.toLong\n val second = takeSimilar(s.reverse.zipWithIndex).length.toLong\n\n if (s.head == s.last) {\n println((2 * ((first + second) % 998244353)) % 998244353)\n } else {\n println((first + second + 1) % 998244353)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject SubstringRemoval extends App {\n\n val n = StdIn.readLine()\n val s = StdIn.readLine()\n\n val takeSimilar = (xs: IndexedSeq[(Char, Int)]) =>\n xs.takeWhile { case (c, i) =>\n if (i == 0) true\n else xs(i - 1)._1 == c\n }\n\n val first = takeSimilar(s.zipWithIndex).length.toLong\n val second = takeSimilar(s.reverse.zipWithIndex).length.toLong\n\n if (s.head == s.last) {\n println((2 * (first + second)) % 998244353)\n } else {\n println((first + second + 1) % 998244353)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject SubstringRemoval extends App {\n\n val n = StdIn.readLine()\n val s = StdIn.readLine()\n\n val takeSimilar = (xs: IndexedSeq[(Char, Int)]) =>\n xs.takeWhile { case (c, i) =>\n if (i == 0) true\n else xs(i - 1)._1 == c\n }\n\n val first: Long = takeSimilar(s.zipWithIndex).length.toLong\n val second: Long = takeSimilar(s.reverse.zipWithIndex).length.toLong\n\n if (s.head == s.last) {\n val res: Long = (2 * ((first + second) % 998244353)) % 998244353\n println(res)\n } else {\n val res: Long = (first + second + 1) % 998244353\n println(res)\n }\n}\n"}], "src_uid": "9693f60fc65065d00a1899df999405fe"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val nm = readLine().split(\" \").map(_.toInt)\n val n = nm(0)\n val m = nm(1)\n val a = \n if (m == 0) Array.empty[Int]\n else readLine().split(\" \").map(_.toInt).sorted\n \n var p1 = 0\n var p2 = 0\n var inc = false\n for (i <- 0 until m) {\n val e = a(i)\n if (p1 == e - 2 && p2 == e - 1) inc = true\n p1 = p2\n p2 = e\n }\n \n if (a.headOption == Some(1) || p2 == n || inc) println(\"NO\")\n else println(\"YES\")\n }\n}", "positive_code": [{"source_code": "\n/**\n * @author pvasilyev\n * @since 18 Jun 2016\n */\nobject B362 extends App {\n\n def solve() = {\n val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n if (m == 0) {\n println(\"YES\")\n } else {\n val d: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val sorted = d.sorted\n var can = sorted(0) != 1 && sorted(m - 1) != n\n var biggestConsecutive = 0\n if (can) {\n var currentConsecutive = 0\n for (i <- 1 until m) {\n if (sorted(i) == sorted(i - 1) + 1) {\n currentConsecutive += 1\n biggestConsecutive = Math.max(biggestConsecutive, currentConsecutive)\n } else {\n currentConsecutive = 0\n }\n }\n }\n\n if (can && biggestConsecutive < 2) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n }\n\n solve()\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n if (m == 0)\n println(\"YES\")\n else {\n val dirty = in.next().split(\" \").map(_.toInt).sorted\n if (dirty.head == 1 || dirty.last == n)\n println(\"NO\")\n else {\n if ((2 until m).forall{j =>\n val first = dirty(j - 2)\n (dirty(j - 1) != first + 1) || (dirty(j) != first + 2)\n })\n println(\"YES\")\n else\n println(\"NO\")\n }\n }\n}"}, {"source_code": "object B extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val dirty = if (m > 0) readInts(m).sorted else Array.ofDim[Int](0)\n val can = m == 0 || (dirty.head != 1 && dirty.last != n && !(0 until m - 2).exists(i => dirty(i + 1) == dirty(i) + 1 && dirty(i + 2) == dirty(i) + 2)) \n \n println(if (can) \"YES\" else \"NO\")\n}"}], "negative_code": [{"source_code": "\n/**\n * @author pvasilyev\n * @since 18 Jun 2016\n */\nobject B362 extends App {\n\n def solve() = {\n val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n if (m == 0) {\n println(\"YES\")\n } else {\n val d: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val sorted = d.sorted\n var can = sorted(0) != 1 && sorted(m - 1) != n\n var biggestConsecutive = 0\n if (can) {\n var currentConsecutive = 0\n for (i <- 1 until m) {\n if (sorted(i) == sorted(i - 1) + 1) {\n currentConsecutive += 1\n } else {\n biggestConsecutive = Math.max(biggestConsecutive, currentConsecutive)\n currentConsecutive = 0\n }\n }\n }\n\n if (can && biggestConsecutive < 2) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n }\n\n solve()\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val nm = readLine().split(\" \").map(_.toInt)\n val n = nm(0)\n val m = nm(1)\n val a = readLine().split(\" \").map(_.toInt).sorted\n \n var p1 = 0\n var p2 = 0\n var inc = false\n for (i <- 0 until m) {\n val e = a(i)\n if (p1 == e - 2 && p2 == e - 1) inc = true\n p1 = p2\n p2 = e\n }\n \n if (a.head == 1 || p2 == m || inc) println(\"NO\")\n else println(\"YES\")\n }\n}"}], "src_uid": "422cbf106fac3216d58bdc8411c0bf9f"} {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val n = readInt()\n val A = readLine().split(\" \").map(_.toLong)\n\n var offset = 0L\n var moves = 0L\n for (i <- 0 until A.length) {\n moves += Math.abs(A(i) - offset)\n offset += A(i) - offset\n// println(s\"$i -> $offset ($moves)\")\n }\n\n println(moves)\n}\n", "positive_code": [{"source_code": "object B596 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val b = readInts(n)\n var curr = 0\n var res = 0L\n for(i <- 0 until n) {\n res += math.abs(curr - b(i))\n curr = b(i)\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._\nimport scala.math.Ordering.Implicits._\n\nobject _596B extends CodeForcesApp {\n override type Result = Long\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val n = nextInt()\n val bs = List.fill(n)(nextLong())\n (0L :: bs).sliding(2).collect{case a :: b :: Nil => (a - b).abs}.sum\n }\n\n override def format(result: Result) = super.format(result)\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}, {"source_code": "/**\n * Created by MZKL7315 on 4/12/2016.\n */\n\nobject Main {\n\n def solve(s: List[Long], cur: Long): Long = s match {\n case Nil => 0\n case h :: t => math.abs(cur - h) + solve(t, h)\n }\n\n def main(args: Array[String]) = {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println(solve(in.next().split(' ').toList map (_.toLong), 0))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n println(data.foldLeft((0l, 0)) {\n case ((soFar, prev), el) =>\n val diff = Math.abs(prev - el)\n (soFar + diff, el)\n }._1)\n\n}\n"}], "negative_code": [{"source_code": "/**\n * Created by MZKL7315 on 4/12/2016.\n */\n\nobject Main {\n\n def solve(s: List[Int], cur: Int): Int = s match {\n case Nil => 0\n case h :: t => math.abs(cur - h) + solve(t, h)\n }\n\n def main(args: Array[String]) = {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println(solve(in.next().split(' ').toList map (_.toInt), 0))\n }\n}\n"}, {"source_code": "/**\n * Created by MZKL7315 on 4/12/2016.\n */\n\nobject Main {\n\n def solve(s: List[Int], cur: Int): Int = s match {\n case Nil => 0\n case h :: t => math.abs(cur - h) + solve(t, math.max(cur, h))\n }\n\n def main(args: Array[String]) = {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println(solve(in.next().split(' ').toList map (_.toInt), 0))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n println(data.foldLeft((0, 0)) {\n case ((soFar, prev), el) =>\n val diff = Math.abs(prev - el)\n (soFar + diff, el)\n }._1)\n\n}\n"}], "src_uid": "97a226f47973fcb39c40e16f66654b5f"} {"source_code": "object Solution extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n // val q = io.read[Int]\n val q = io.read[Int]\n repeat(q) {\n val arr = io.read[Array, Long](4)\n io.writeLine(if(arr(1) >= arr(3) % arr(2) && arr(1) + arr(0) * arr(2) >= arr(3)) { \"YES\" } else { \"NO\" })\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main extends App{\n\n val q = StdIn.readLine.toInt\n for (i <- 0 to q-1) {\n val Array(a, b, n, s) = StdIn.readLine().split(\" \").map(_.toInt)\n val div = s / n\n if ((div min a) * n + b * 1 >= s)\n println(\"YES\")\n else\n println(\"NO\")\n }\n\n}"}, {"source_code": "//package codeforces.contest1256\n\nobject PaymentWithoutChange {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt()) {\n val Array(a, b, n, s) = io.StdIn.readLine().split(\" \").map(_.toLong)\n\n println {\n if (b + (n * (s / n) min a * n) >= s) \"YES\" else \"NO\"\n }\n }\n }\n\n}\n"}, {"source_code": "import scala.math.min\n\nobject Main {\n def main(args: Array[String]) = {\n val q = readInt\n (0 until q).foreach((x) => f1)\n }\n\n def f1: Unit = {\n val Array(a, b, n, s) = readLine.split(\" \").map(_.toLong)\n println(if (s - n * (min(s / n, a)) <= b) \"YES\" else \"NO\")\n }\n}\n"}, {"source_code": "object _1256A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(implicit io: IO): io.type = repeat {\n val a, b, n, s = io.read[Int]\n val withA = ((s/n) min a)*n\n val remaining = s - withA\n debug(a, b, n, s, withA, remaining)\n val ans = remaining <= b\n io.write(ans.toEnglish.toUpperCase)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(implicit io: IO): io.type\n def repeat(f: => Unit)(implicit io: IO): io.type = {Utils.repeat(io.read[Int]){f; io.writeLine()}; io}\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskA extends App {\n val sc = new Scanner(System.in)\n val q = sc.nextInt\n\n val out = 1 to q map { _ =>\n val (a, b, n, s) = (sc.nextInt, sc.nextInt, sc.nextInt, sc.nextInt)\n if (min(s / n, a) * n + b >= s) \"YES\" else \"NO\"\n } mkString \"\\n\"\n\n println(out)\n}\n"}], "negative_code": [], "src_uid": "e2434fd5f9d16d59e646b6e69e37684a"} {"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n case class R(l: Int, r: Int)\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val rs = Array.fill(n) {\n val l, r = nextInt\n R(l, r)\n }.sortBy {\n r => (r.l, -r.r)\n }\n\n val ds = Array.ofDim[Int](n)\n for (i <- rs.indices) {\n val r = rs(i)\n if (r.r == r.l) ds(i) = r.l\n else {\n val next = rs(i + 1)\n if (next.l == r.l) ds(i) = next.r + 1\n else ds(i) = next.l - 1\n }\n }\n\n for (i <- rs.indices) {\n out.println(s\"${rs(i).l} ${rs(i).r} ${ds(i)}\")\n }\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(val l: Int, val r: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return (r-l).compareTo(that.r-that.l)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n\n\n for (tt <- 1 to t) {\n val n = readInt()\n var q = Vector[pair]()\n val mark = new Array[Boolean](n+1)\n var l = 0\n var r = 0\n for (i <- 1 to n) {\n l = readInt()\n r = readInt()\n q :+= pair(l, r)\n }\n q = q.sorted\n for (qq <- q) {\n for (i <- qq.l to qq.r) {\n if (!mark(i)) {\n writer.println(qq.l + \" \" + qq.r + \" \" + i)\n mark(i) = true\n }\n }\n }\n writer.println()\n\n def check(kk: Long): Boolean = {\n return false\n }\n def bs(st:Long, en:Long): Long = {\n if (en - st <= 1L) {\n if (check(st))\n return st\n else\n return en\n }\n val mid = (st + en) / 2L\n if (check(mid))\n return bs(st, mid)\n else\n return bs(mid, en)\n }\n }\n writer.flush()\n}"}], "negative_code": [], "src_uid": "eca433877ef3fbda198c5f2c95a359e7"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n REP(N) { _ =>\n val c, s = ni()\n val ans = if (c >= s) {\n s\n } else {\n if (s % c == 0) {\n val unit = s / c\n unit.toLong * unit * c\n } else {\n val unit1 = (s + c - 1) / c\n val unit2 = s / c\n val r = s % c\n unit1.toLong * unit1 * r + unit2.toLong * unit2 * (c - r)\n }\n }\n out.println(ans)\n }\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n\n val n = readLine().toInt\n\n for (i <- 0 until n) {\n val Array(c, sum) = readLine().split(\" \").map(_.toInt)\n var arr = Seq.fill(c)(1)\n var res: Long = 0\n if (c > sum) {\n res = sum\n } else {\n val del: Int = sum / c\n val needUp = sum - del * c\n res = Math.pow(del, 2).asInstanceOf[Long] * (c-needUp) +\n Math.pow(del+1, 2).asInstanceOf[Long] * needUp\n }\n println(res)\n }\n\n\n}"}, {"source_code": "import scala.io.StdIn._\nobject Main{\n def main(args: Array[String]): Unit ={\n val N = readInt()\n val C = Array.ofDim[Int](N)\n val SUM = Array.ofDim[Int](N)\n for(i <- 0 until N){\n val line = readLine().split(\" \").map(_.toInt)\n val c = line(0)\n val sum = line(1)\n val result =\n if(sum % c == 0){\n val k = sum / c\n k * k * c\n }else{\n val extra = sum % c\n val k = sum / c\n k * k * (c - extra) + (k+1) * (k+1) * extra\n }\n println(result)\n }\n }\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n\n val n = readLine().toInt\n\n for (i <- 0 until n) {\n val Array(c, sum) = readLine().split(\" \").map(_.toInt)\n var arr = Seq.fill(c)(1)\n var res: Long = 0\n if (c > sum) {\n res = 1\n } else {\n var del: Int = sum / c\n val needUp = sum - del * c\n res = Math.pow(del, 2).asInstanceOf[Long] * (c-needUp) +\n Math.pow(del+1, 2).asInstanceOf[Long] * needUp\n }\n println(res)\n }\n\n\n}"}], "src_uid": "0ec973bf4ad209de9731818c75469541"} {"source_code": "\nimport java.io._\nimport java.util.Scanner\nimport scala.language.implicitConversions\n\nobject Template {\n\n class Lazy[A](x: => A) {\n lazy val value = x\n override def toString(): String = value.toString()\n }\n\n object Lazy {\n def apply[A](x: => A) = new Lazy(x)\n implicit def fromLazy[A](z: Lazy[A]): A = z.value\n implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)\n }\n\n import Lazy._\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val N = sc.nextInt()\n val A = for (i <- 0.until(N)) yield sc.nextInt()\n val valueToMaxIndex = A.zipWithIndex.groupBy(_._1).mapValues(list => list.map(_._2).max)\n val minIndex = valueToMaxIndex.map{case (v, index) => index}.min\n val answer = A(minIndex)\n\n println(answer)\n\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n val last = Array.fill(as.max + 1)(Int.MaxValue / 2)\n\n for (i <- as.indices) last(as(i)) = i\n\n val min = as.minBy(last)\n\n println(min)\n}\n"}, {"source_code": "/**\n * @see http://codeforces.com/contest/890/problem/B\n */\n\nobject BVladAndCafes extends App {\n val n = scala.io.StdIn.readLine().toInt\n val as = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val last = Array.fill(as.max + 1)(20000)\n\n for (i <- as.indices) last(as(i)) = i\n\n println(as minBy last)\n}\n"}], "negative_code": [{"source_code": "\n\nimport java.io._\nimport java.util.Scanner\nimport scala.language.implicitConversions\n\nobject Template {\n\n class Lazy[A](x: => A) {\n lazy val value = x\n override def toString(): String = value.toString()\n }\n\n object Lazy {\n def apply[A](x: => A) = new Lazy(x)\n implicit def fromLazy[A](z: Lazy[A]): A = z.value\n implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)\n }\n\n import Lazy._\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val N = sc.nextInt()\n val A = for (i <- 0.until(N)) yield sc.nextInt()\n val valueToMaxIndex = A.zipWithIndex.groupBy(_._2).mapValues(list => list.map(_._2).max)\n val minIndex = valueToMaxIndex.map{case (v, index) => index}.min\n val answer = A(minIndex)\n\n println(answer)\n\n }\n}\n"}], "src_uid": "bdea209c7b628e4cc90ebc2572826485"} {"source_code": "object CF340C_198 extends App{\n def gcd (x : Long, y : Long) : Long = {\n if (x % y == 0) y else gcd (y, x % y)\n }\n val n = Console.readLine.toInt\n val a = Console.readLine.split(' ').map(_.toLong).sorted.zip(1 to n).map{case (x, i) =>\n (4 * i - 2 * n - 1) * x\n }.reduce(_ + _)\n val d = gcd(a, n)\n printf(\"%d %d\\n\", a/d, n/d)\n}\n", "positive_code": [{"source_code": "object CF340C_198 extends App{\n def gcd (x : Long, y : Long) : Long = {\n if (x % y == 0) y else gcd (y, x % y)\n }\n val n = Console.readLine.toInt\n val a = Console.readLine.split(' ').map(_.toLong).sorted.zip(1 to n).map{case (x, i) =>\n (4 * i - 2 * n - 1) * x\n }.reduce(_ + _)\n val d = gcd(a, n)\n println((a/d).toString + \" \" + (n/d).toString)\n}\n"}], "negative_code": [{"source_code": "object CF340C_198 extends App{\n def gcd (x : Long, y : Long) : Long = {\n if (x % y == 0) y else gcd (y, x % y)\n }\n val n = Console.readLine.toInt\n val a = Console.readLine.split(' ').map(_.toLong).zip(1 to n).map{case (x, i) =>\n (4 * i - 2 * n - 1) * x\n }.reduce(_ + _)\n val d = gcd(a, n)\n printf (\"%d %d\", a/d, n/d)\n}\n"}], "src_uid": "ad50e2946470fa8e02eb70d8cef161c5"} {"source_code": "object _796B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n val n, m, k = read[Int]\n val isHole = Array.ofDim[Boolean](n+1)\n repeat(m) {\n isHole(read[Int]) = true\n }\n var bone = 1\n try {\n repeat(k) {\n require(!isHole(bone))\n val u, v = read[Int]\n if (bone == u) {\n bone = v\n } else if (bone == v) {\n bone = u\n }\n }\n } catch {\n case _: Throwable =>\n }\n write(bone)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "\n/**\n * Created by ruslan on 3/29/17.\n */\nobject ProblemA extends App {\n import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}\nimport java.util.StringTokenizer\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens()) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val n = in.nextInt()\n val m = in.nextInt()\n var k = in.nextInt()\n\n val a = new Array[Boolean](n)\n\n for (i <- 1 to m)\n a(in.nextInt() - 1) = true\n\n var currentPos = 1\n\n while (!a(currentPos - 1) && k > 0) {\n val move1 = in.nextInt()\n val move2 = in.nextInt()\n if (move1 == currentPos)\n currentPos = move2\n else if (move2 == currentPos)\n currentPos = move1\n\n k -= 1\n }\n\n println(currentPos)\n\n\n}\n"}], "negative_code": [{"source_code": "object _796B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n val n, m, k = read[Int]\n val isHole = read[Set, Int](m)\n val cups = Array.tabulate[Int](n+1)(identity)\n var bonePosition = 1\n repeat(k) {\n val u, v = read[Int]\n if (u == bonePosition && !isHole(bonePosition)) {\n bonePosition = v\n }\n val t = cups(u)\n cups(u) = cups(v)\n cups(v) = t\n //debug(u, v, cups.toList, bonePosition)\n }\n\n write(bonePosition)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _796B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n val n, m, k = read[Int]\n val isHole = read[Set, Int](m)\n var bone = 1\n repeat(k) {\n val u, v = read[Int]\n //debug(u, v, bone, isHole(bone))\n if (u == bone && !isHole(bone)) {\n bone = v\n }\n }\n\n write(bone)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "1f41c017102f4a997be324a4ec9b7fd6"} {"source_code": "import scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\n\nobject Base extends App {\n\n\n sealed trait ArraySum\n case object Zero extends ArraySum\n case object Negative extends ArraySum\n case object Positive extends ArraySum\n\n sealed trait CaseResult\n case object Impossible extends CaseResult{\n override def toString = \"NO\"\n }\n case class Possible(val res: Array[Int]) extends CaseResult{\n override def toString = s\"YES\\n${res.mkString(\" \")}\"\n }\n\n def inputSum(x: Array[Int]): ArraySum = {\n val s = x.sum\n\n (s compare 0) match {\n case 0 => Zero\n case 1 => Positive\n case -1 => Negative\n }\n }\n\n def calculateResultArr(x: Array[Int], nature: ArraySum) = {\n val negatives = x.filter(_ < 0)\n val positives = x.filter(_ > 0)\n val zeroes = x.filter(_ == 0)\n\n nature match {\n case Positive => positives ++ negatives ++ zeroes\n case Negative => negatives ++ positives ++ zeroes\n }\n }\n\n\n\n def processInputCase(): CaseResult = {\n val digits = readInt()\n val input: Array[Int] = readLine().split(\" \").toArray.map(_.toInt)\n\n inputSum(input) match {\n case Zero => Impossible\n case x => Possible(calculateResultArr(input, x))\n }\n }\n\n\n \n\n \n val n = readInt()\n\n (1 to n).foreach(_ => println(processInputCase()))\n\n\n}\n", "positive_code": [{"source_code": "import scala.collection.immutable\nobject Main extends App {\n\n def parseInt(str: String, count: Int): Seq[Int] = {\n val scanner = new java.util.Scanner(str)\n val res = (1 to count) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n def scanInts(count: Int): Seq[Int] = parseInt(scala.io.StdIn.readLine(), count)\n def readMatrix(row: Int, col: Int) = (1 to row) map (x => scanInts(col))\n\n def solve(nums: immutable.Seq[Int]) = {\n val sum = nums.fold(0)(_ + _)\n\n if (sum == 0) {\n println(\"NO\")\n } else {\n println(\"YES\")\n var res = Seq(1,2,3)\n\n if (sum > 0){\n res = nums.sortWith(_ > _)\n } else {\n res = nums.sortWith(_ < _)\n }\n\n res.foreach(x => print(x+\" \"))\n println()\n }\n\n }\n\n //System.setIn(new java.io.FileInputStream(\"data.in\"))\n\n val nCases = scanInts(1)(0)\n\n for (nCase <- 1 to nCases) {\n val nNums = scanInts(1)(0)\n val nums = scanInts(nNums)\n\n solve(collection.immutable.Seq(nums: _*))\n } \n\n}\n"}], "negative_code": [], "src_uid": "e57345f5757654749b411727ebb99c80"} {"source_code": "object A350 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val a = readInts(n).sorted\n val b = readInts(m).sorted\n if(math.max(a.head*2, a.last) < b.head) {\n println(math.max(a.head*2, a.last))\n } else {\n println(\"-1\")\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _350A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val m = next.toInt\n val good = (1 to n).map(i => next.toInt)\n val bad = (1 to m).map(i => next.toInt)\n val goodMin = good.min\n val cb = (good.max until bad.min).filter(i => goodMin * 2 <= i)\n if (cb.size == 0) println(-1)\n else println(cb.min)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val right = in.next().split(\" \").map(_.toInt)\n val minWrong = in.next().split(\" \").map(_.toInt).min\n val proposal = Math.max(right.min * 2, right.max)\n if (minWrong > proposal)\n println(proposal)\n else\n println(-1)\n}"}, {"source_code": "object A350 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val a = readInts(n).sorted\n val b = readInts(m).sorted\n val min = a.max\n val max = b.min\n var break = false\n for(i <- min until max if !break) {\n if(a.head*2 <= i) {\n println(i)\n break = true\n }\n }\n if(!break)\n println(\"-1\")\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object A350 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val a = readInts(n).sorted\n val b = readInts(m).sorted\n val min = a.max\n val max = b.min\n var break = false\n for(i <- min until max if !break) {\n if(a.forall(_ <= i) && b.forall(_ > i) && a.head*2 <= i) {\n println(i)\n break = true\n }\n }\n if(!break)\n println(\"-1\")\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object A350 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val a = readInts(n).sorted\n val b = readInts(m).sorted\n val min = a.max\n val max = b.min\n var break = false\n for(i <- math.max(a.head*2,min) until max if !break) {\n println(i)\n break = true\n }\n if(!break)\n println(\"-1\")\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P350A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, M = sc.nextInt\n\n val as = List.fill(N)(sc.nextInt)\n val bs = List.fill(M)(sc.nextInt)\n val bMin = bs min\n val aMin = as min\n val aMax = as max\n\n def solve(): Int = {\n if (aMax <= aMin * 2 && aMin * 2 < bMin) aMin * 2\n else if (aMin * 2 <= aMax && aMax < bMin) aMax\n else -1\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val s1 = readLine()\n val a1 = readLine().split(\" \").map(_.toInt)\n val a2 = readLine().split(\" \").map(_.toInt)\n val min = (a1.min * 2).max(a1.max)\n val max = a2.min\n if (max <= min) println(\"-1\")\n else println(min)\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val right = in.next().split(\" \").map(_.toInt)\n val minWrong = in.next().split(\" \").map(_.toInt).min\n val proposal = minWrong - 1\n if (right.min * 2 <= proposal && right.max <= proposal)\n println(proposal)\n else\n println(-1)\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val right = in.next().split(\" \").map(_.toInt)\n val minWrong = in.next().split(\" \").map(_.toInt).min\n val proposal = Math.max(right.min * 2, right.max)\n if (minWrong < proposal)\n println(proposal)\n else\n println(-1)\n}"}, {"source_code": "object A350 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val a = readInts(n).sorted\n val b = readInts(m).sorted\n val min = a.max\n val max = b.min\n if(math.max(a.head*2, a.last) <= b.last) {\n println(math.max(a.head*2,min))\n } else {\n println(\"-1\")\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object A350 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val a = readInts(n).sorted\n val b = readInts(m).sorted\n val min = a.max\n val max = b.min\n var break = false\n for(i <- a.head*2 until max if !break) {\n println(i)\n break = true\n }\n if(!break)\n println(\"-1\")\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object A350 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val a = readInts(n).sorted\n val b = readInts(m).sorted\n if(math.max(a.head*2, a.last) < b.last) {\n println(math.max(a.head*2, a.last))\n } else {\n println(\"-1\")\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P350A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, M = sc.nextInt\n\n val as = List.fill(N)(sc.nextInt)\n val bs = List.fill(M)(sc.nextInt)\n\n def solve(): Int = {\n val bMin = bs min\n val aMin = as min\n val aMax = as max\n\n if (bMin <= aMax) -1\n else if (0.5 * aMax < aMin) -1\n else aMax\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P350A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, M = sc.nextInt\n\n val as = List.fill(N)(sc.nextInt)\n val bs = List.fill(M)(sc.nextInt)\n val bMin = bs min\n val aMin = as min\n val aMax = as max\n\n def solve1(): Int = if (2 * aMin < bMin) 2 * aMin else -1\n\n def solveM(): Int = if (bMin <= aMax) -1\n else if (0.5 * aMax < aMin) -1\n else aMax\n\n def solve(): Int = if (as.size == 1) solve1 else solveM\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P350A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, M = sc.nextInt\n\n val as = List.fill(N)(sc.nextInt).distinct\n val bs = List.fill(M)(sc.nextInt)\n val bMin = bs min\n val aMin = as min\n val aMax = as max\n\n def solve1(): Int = if (2 * aMin < bMin) 2 * aMin else -1\n\n def solveM(): Int = if (bMin <= aMax) -1\n else if (0.5 * aMax < aMin) -1\n else aMax\n\n def solve(): Int = if (as.size == 1) solve1 else solveM\n\n out.println(solve)\n out.close\n}\n"}], "src_uid": "49c47ebfd710a3733ce7ecb3a3c134a7"} {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject LittleArtemAndGrasshopper {\n\n def parseInts(str: String, numIterations: Integer) = {\n val scanner = new Scanner(str)\n val res = (0 until numIterations) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n def parseString(str: String): String = {\n val scanner = new Scanner(str)\n val res = scanner.nextLine()\n scanner.close()\n res\n }\n\n def main(args: Array[String]) {\n val stripLen = parseInts(Console.readLine(), 1)(0)\n val directions = parseString(Console.readLine()).toCharArray map { dir => if (dir == '<') -1 else 1 }\n val jumpLens = parseInts(Console.readLine(), stripLen)\n\n val visited = mutable.Set.empty[Int]\n visited add 0\n\n @annotation.tailrec\n def jump(pos: Int): String = {\n val newPos = pos + jumpLens(pos) * directions(pos)\n if (newPos < 0 || newPos > stripLen - 1) {\n return \"FINITE\"\n } else if (visited.contains(newPos)) {\n return \"INFINITE\"\n }\n visited add newPos\n jump(newPos)\n }\n\n println(jump(0))\n }\n}\n", "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, java.awt._\n\nobject _669B extends CodeForcesApp {\n override def apply(io: IO): io.type = {\n val (n, strip) = io[(Int, String)]\n val dir = strip map {c => if (c == '<') -1 else 1}\n val dist = io[Vector, Int](n)\n var pos = 1\n val seen = mutable.Set.empty[Int]\n while(true) {\n pos += dist(pos-1) * dir(pos-1)\n if (pos < 1 || pos > n) {\n return io += \"FINITE\"\n }\n if (!(seen add pos)) {\n return io += \"INFINITE\"\n }\n }\n io += \"INFINITE\"\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[I] = new {\n def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val newLine: String = \"\\n\"\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = this.+=(xs.size).appendNewLine().+=(xs)\n\n def appendNewLine(): this.type = {\n println()\n this\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject LittleArtemAndGrasshopper {\n\n def parseInts(str: String, numIterations: Integer) = {\n val scanner = new Scanner(str)\n val res = (0 until numIterations) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n def parseString(str: String): String = {\n val scanner = new Scanner(str)\n val res = scanner.nextLine()\n scanner.close()\n res\n }\n\n def main(args: Array[String]) {\n val stripLen = parseInts(Console.readLine(), 1)(0)\n val directions = parseString(Console.readLine()).toCharArray map { dir => if (dir == '<') -1 else 1 }\n val jumpLens = parseInts(Console.readLine(), stripLen)\n\n val visited = mutable.Set.empty[Int]\n visited add 0\n\n def someMethod(): String = {\n var pos = 0\n while (true) {\n pos = pos + jumpLens(pos) * directions(pos)\n if (pos < 0 || pos > stripLen - 1) {\n return \"FINITE\"\n } else if (visited.contains(pos)) {\n return \"INFINITE\"\n }\n visited add pos\n }\n\n \"Messed up\"\n }\n\n println(someMethod)\n\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject LittleArtemAndGrasshopper {\n\n def parseInts(str: String, numIterations: Integer) = {\n val scanner = new Scanner(str)\n val res = (0 until numIterations) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n def parseString(str: String): String = {\n val scanner = new Scanner(str)\n val res = scanner.nextLine()\n scanner.close()\n res\n }\n\n def main(args: Array[String]) {\n val stripLen = parseInts(Console.readLine(), 1)(0)\n val directions = parseString(Console.readLine()).toCharArray map {dir => if (dir == '<') -1 else 1}\n val jumpLens = parseInts(Console.readLine(), stripLen)\n\n val visited = mutable.Set.empty[Int]\n visited add 0\n\n @annotation.tailrec\n def jump(pos: Int): String = {\n val newPos = pos + jumpLens(pos) * directions(pos)\n if (newPos < 0 || newPos > stripLen - 1) {\n return \"FINITE\"\n } else if (visited.contains(newPos)) {\n return \"INFINITE\"\n }\n visited.add(newPos)\n\n jump(newPos)\n }\n\n println(jump(0))\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject LittleArtemAndGrasshopper {\n\n def parseInts(str: String, numIterations: Integer) = {\n val scanner = new Scanner(str)\n val res = (0 until numIterations) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n def parseString(str: String): String = {\n val scanner = new Scanner(str)\n val res = scanner.nextLine()\n scanner.close()\n res\n }\n\n def main(args: Array[String]) {\n val stripLen = parseInts(Console.readLine(), 1)(0)\n val directions = parseString(Console.readLine()).toCharArray map { dir => if (dir == '<') -1 else 1 }\n val jumpLens = parseInts(Console.readLine(), stripLen)\n\n val visited = mutable.Set.empty[Int]\n visited add 0\n\n def jump(pos: Int): String = {\n val newPos = pos + jumpLens(pos) * directions(pos)\n if (newPos < 0 || newPos > stripLen - 1) {\n return \"FINITE\"\n } else if (visited.contains(newPos)) {\n return \"INFINITE\"\n }\n visited add newPos\n jump(newPos)\n }\n\n println(jump(0))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val signs = in.next()\n val values = in.next().split(' ').map(_.toInt).zip(signs).map{\n case(v, ch) => if (ch == '<') -v else v\n }\n val visited = Array.ofDim[Boolean](n)\n\n var i = 0\n\n while (i >= 0 && i < n && !visited(i)) {\n visited(i) = true\n i = i + values(i)\n }\n if (i < 0 || i >= n)\n println(\"FINITE\")\n else\n println(\"INFINITE\")\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject LittleArtemAndGrasshopper {\n\n def parseInts(str: String, numIterations: Integer) = {\n val scanner = new Scanner(str)\n val res = (0 until numIterations) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n def parseString(str: String): String = {\n val scanner = new Scanner(str)\n val res = scanner.nextLine()\n scanner.close()\n res\n }\n\n def main(args: Array[String]) {\n val stripLen = parseInts(Console.readLine(), 1)(0)\n val directions = parseString(Console.readLine()).toCharArray map {dir => if (dir == '<') -1 else 1}\n val jumpLens = parseInts(Console.readLine(), stripLen)\n\n val visited = mutable.Set.empty[Int]\n\n @annotation.tailrec\n def jump(pos: Int): String = {\n val newPos = pos + jumpLens(pos) * directions(pos)\n if (newPos < 1 || newPos > stripLen - 1) {\n return \"FINITE\"\n } else if (visited.contains(newPos)) {\n return \"INFINITE\"\n }\n visited.add(newPos)\n\n jump(newPos)\n }\n\n println(jump(0))\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject LittleArtemAndGrasshopper {\n\n def parseInts(str: String, numIterations: Integer) = {\n val scanner = new Scanner(str)\n val res = (0 until numIterations) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n def parseString(str: String): String = {\n val scanner = new Scanner(str)\n val res = scanner.nextLine()\n scanner.close()\n res\n }\n\n def main(args: Array[String]) {\n val stripLen = parseInts(Console.readLine(), 1)(0)\n val directions = parseString(Console.readLine()).toCharArray map { dir => if (dir == '<') -1 else 1 }\n val jumpLens = parseInts(Console.readLine(), stripLen)\n\n val visited = mutable.Set.empty[Int]\n visited add 0\n var pos = 0\n\n while (true) {\n pos = pos + jumpLens(pos) * directions(pos)\n if (pos < 0 || pos > stripLen - 1) {\n return \"FINITE\"\n } else if (visited.contains(pos)) {\n return \"INFINITE\"\n }\n visited add pos\n }\n\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject LittleArtemAndGrasshopper {\n\n def parseInts(str: String, numIterations: Integer) = {\n val scanner = new Scanner(str)\n val res = (0 until numIterations) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n def parseString(str: String): String = {\n val scanner = new Scanner(str)\n val res = scanner.nextLine()\n scanner.close()\n res\n }\n\n def main(args: Array[String]) {\n val stripLen = parseInts(Console.readLine(), 1)(0)\n val directions = parseString(Console.readLine()).toCharArray map { dir => if (dir == '<') -1 else 1 }\n val jumpLens = parseInts(Console.readLine(), stripLen)\n\n val visited = mutable.Set.empty[Int]\n visited add 0\n\n def jump(pos: Int): String = {\n val newPos = pos + jumpLens(pos) * directions(pos)\n if (newPos < 0 || newPos > stripLen - 1) {\n return \"FINITE\"\n } else if (visited.contains(newPos)) {\n return \"INFINITE\"\n }\n visited add newPos\n jump(newPos)\n }\n\n }\n}\n"}], "src_uid": "5fcc22cdc38693723d8a9577d685db12"} {"source_code": "object C extends App {\n import scala.io.StdIn._\n\n @annotation.tailrec\n def go(n: Int, i: Int): Int = {\n val j = (n + i - 1) / i\n\n if (j <= i) i + j - 2\n else go(n, i + 1)\n }\n \n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val ans = go(n, 1)\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "//package codeforces.contests._1426\n\n/*\nhttps://codeforces.com/contest/1426/problem/C\n */\nobject IncreaseAndCopy {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val n = io.StdIn.readInt()\n\n val sqrt = math.sqrt(n).toInt\n\n val result = {\n if (sqrt * sqrt == n) {\n sqrt - 1 + sqrt - 1\n } else {\n sqrt - 1 + n / sqrt + (if (n % sqrt == 0) -1 else 0)\n\n }\n }\n println(result)\n }\n }\n}\n"}], "negative_code": [{"source_code": "object C extends App {\n import scala.io.StdIn._\n\n @annotation.tailrec\n def go(n: Int, i: Int): Int = {\n val j = (n + i - 1) / i\n\n if (j <= i) i + j\n else go(n, i + 1)\n }\n \n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val ans = go(n, 1)\n\n println(ans)\n }\n}\n"}], "src_uid": "d78cd4a06fb566d58275e92f976166f2"} {"source_code": "import collection.mutable\nimport java.util.Scanner\n\nobject A extends App {\n\tval in = new Scanner(System.in)\n\tval n = in.nextInt()\n\tval t = new mutable.HashMap[(Int, Int), Int]().withDefaultValue(0)\n\tfor (i <- 0 until n) {\n\t\tval h = in.nextInt()\n\t\tval m = in.nextInt()\n\t\tt((h, m)) += 1\n\t}\n\tprintln(t.values.max)\n}\n", "positive_code": [{"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject FreeCash {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readLongs() : Array[Long] = \n readLine.split(' ').map(_.toLong)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n \n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n \n def main(args: Array[String]) {\n val n = readInt\n val hms = for {\n i <- 1 to n\n (h,m) = readTuple\n } yield 60*h+m\n val sim = hms.tail.foldLeft( (hms.head,1,1)){\n case ((prev, streak, max),cur) => \n if (cur == prev) {\n (cur, streak+1, Math.max(max,streak+1))\n } else {\n (cur,1,max)\n } \n }\n println(sim._3)\n }\n \n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println(Range(0, n).map{ _ => in.next()}.groupBy(t => t).map(t => t._2.length).max)\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P237A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextLine.toInt\n\n val answer: Int = List.fill(N)(sc.nextLine).groupBy(identity[String]).map(_._2.length).max\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "// codeforces problem 237A\n\nobject Kassa extends App {\n \n def readMinutes(n:Int) : List[Int] = {\n def readLines(n:Int) : List[String] = n match {\n case 0 => List()\n case _ => Console.readLine() :: readLines(n-1)\n }\n \n def strToMinutes(s:String) : Int = {\n val shm = s.split(\" \")\n val hr = shm(0) toInt;\n val mn = shm(1) toInt;\n hr * 60 + mn\n }\n \n val lines = readLines(n)\n val minutes = lines map strToMinutes\n minutes\n }\n \n def maxSeq(l:List[Int], lastMn:Int, lastRep:Int, maxRep:Int) : (Int, Int, Int) = l match {\n case List() => (lastMn, lastRep, maxRep)\n case hd :: tl => {\n val lr = if (hd == lastMn) lastRep+1 else 1\n val mxr = if (lr > maxRep) lr else maxRep\n maxSeq(tl, hd, lr, mxr)\n }\n }\n \n val n = Console.readInt()\n val minutes = readMinutes(n)\n val smin = minutes sorted;\n val (mxMin, lr, maxr) = maxSeq(smin, -1, 0, 0)\n Console.println(maxr)\n}"}, {"source_code": "import java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n def ans = (for(_ <- 1 to readInt) yield readInts.foldLeft(0)((a, b) => 60 * a + b)).groupBy(x => x).foldLeft(0) {\n case (a, (_, b)) => a max b.size\n }\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def read(): (Int, Int) = {\n val a = readLine().split(\" \").map(_.toInt)\n (a(0), a(1))\n }\n\n def main(args: Array[String]) {\n val num = readInt\n var prev: (Int, Int) = (-1, -1)\n var max, curn = 1\n for(i <- 1 to num) {\n val curr = read()\n if (curr == prev) {\n curn += 1\n } else {\n if (curn > max) max = curn\n curn = 1\n prev = curr\n }\n }\n println(max.max(curn))\n }\n}"}], "negative_code": [{"source_code": "object Kassa extends App {\n \n def readMinutes(n:Int) : List[Int] = {\n def readLines(n:Int) : List[String] = n match {\n case 0 => List()\n case _ => Console.readLine() :: readLines(n-1)\n }\n \n def strToMinutes(s:String) : Int = {\n val shm = s.split(\" \")\n val hr = shm(0) toInt;\n val mn = shm(1) toInt;\n hr * 60 + mn\n }\n \n val lines = readLines(n)\n val minutes = lines map strToMinutes\n minutes\n }\n \n val n = Console.readInt()\n val minutes = readMinutes(n)\n val smin = minutes sorted;\n val su = Set(smin)\n Console.println(su size)\n}"}, {"source_code": "\nobject Kassa extends App {\n \n def readMinutes(n:Int) : List[Int] = {\n def readLines(n:Int) : List[String] = n match {\n case 0 => List()\n case _ => Console.readLine() :: readLines(n-1)\n }\n \n def strToMinutes(s:String) : Int = {\n val shm = s.split(\" \")\n val hr = shm(0) toInt;\n val mn = shm(1) toInt;\n hr * 60 + mn\n }\n \n val lines = readLines(n)\n val minutes = lines map strToMinutes\n minutes\n }\n \n def maxSeq(l:List[Int], lastMn:Int, lastRep:Int, maxRep:Int) : (Int, Int, Int) = l match {\n case List() => (lastMn, lastRep, maxRep)\n case hd :: tl => {\n val mxr = if (hd == lastMn && lastRep >= maxRep) lastRep+1 else maxRep\n val lr = if (hd == lastMn) lastRep+1 else 1\n maxSeq(tl, hd, lr, mxr)\n }\n }\n \n val n = Console.readInt()\n val minutes = readMinutes(n)\n val smin = minutes sorted;\n val (mxMin, lr, maxr) = maxSeq(smin, -1, 0, 0)\n Console.println(maxr)\n}"}, {"source_code": "object Kassa extends App {\n val n = Console.readInt()\n Console.println(\"n = \" + n)\n \n def readMinutes(n:Int) : List[Int] = {\n def readLines(n:Int) : List[String] = n match {\n case 0 => List()\n case _ => Console.readLine() :: readLines(n-1)\n }\n \n def strToMinutes(s:String) : Int = {\n val shm = s.split(\" \")\n val hr = shm(0) toInt;\n val mn = shm(1) toInt;\n hr * 60 + mn\n }\n \n val lines = readLines(n)\n val minutes = lines map strToMinutes\n minutes\n }\n \n val minutes = readMinutes(n)\n val smin = minutes sorted;\n val su = Set(smin)\n Console.println(su size)\n}"}, {"source_code": "object Main {\n def read(): (Int, Int) = {\n val a = readLine().split(\" \").map(_.toInt)\n (a(0), a(1))\n }\n\n def main(args: Array[String]) {\n val num = readInt\n var prev: (Int, Int) = (-1, -1)\n var max, curn = 1\n for(i <- 1 to num) {\n val curr = read()\n if (curr == prev) {\n curn += 1\n } else {\n if (curn > max) max = curn\n curn = 1\n prev = curr\n }\n }\n println(max)\n }\n}"}], "src_uid": "cfad2cb472e662e037f3415a84daca57"} {"source_code": "import scala.math._\nobject C\n{\n def main(args: Array[String])\n {\n val n = readInt\n val stairs = readLine split(\" \") map(_.toInt)\n val m = readInt\n var height = 0L\n (0 until m) foreach\n {\n i =>\n val Array(w,h) = readLine split(\" \") map(_.toInt)\n val hh = max(height, stairs(w-1))\n println(hh)\n height = h + hh\n }\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong).scanLeft(0l){Math.max}\n val m = in.next().toInt\n println((1 to m).map { _ =>\n val Array(w, h) = in.next().split(' ').map(_.toInt)\n val res = Math.max(data(1), data(w))\n data(1) = res + h\n res\n }.mkString(\"\\n\"))\n}"}, {"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\n\nobject test6 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n val m=readInt\n var height:Long=0\n for(_<-1 to m){\n val Array(w,h)=readLine.split(\" \").map(_.toInt)\n val hh=math.max(height,a(w-1))\n println(hh)\n height=hh+h\n }\n} \n\n\n"}, {"source_code": "object Main272C {\n\n def main(args: Array[String]) {\n val n = readInt\n val a = readLine.split(\" \").map(_.toInt)\n val m = readInt\n var currentH = 0L\n for (i <- 1 to m) {\n val Array(w, h) = readLine.split(\" \").map(_.toInt)\n val fallingH = currentH max a(w-1)\n println(fallingH)\n currentH = fallingH + h\n }\n }\n\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt).scanLeft(0){Math.max}\n val m = in.next().toInt\n println((1 to m).map { _ =>\n val Array(w, h) = in.next().split(' ').map(_.toInt)\n val res = Math.max(data(1), data(w))\n data(1) = res + h\n res\n }.mkString(\"\\n\"))\n}"}, {"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\n\nobject test6 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n val m=readInt\n var height=0\n for(_<-1 to m){\n val Array(w,h)=readLine.split(\" \").map(_.toInt)\n val hh=math.max(height,a(w-1))\n println(hh)\n height=hh+h\n }\n} \n\n\n"}, {"source_code": "object Main272C {\n\n def main(args: Array[String]) {\n val n = readInt\n val a = readLine.split(\" \").map(_.toInt)\n val m = readInt\n var currentH = 0\n for (i <- 1 to m) {\n val Array(w, h) = readLine.split(\" \").map(_.toInt)\n val fallingH = currentH max a(w-1)\n println(fallingH)\n currentH = fallingH + h\n }\n }\n\n}"}], "src_uid": "fb0e6a573daa0ee7c20d20b0d2b83756"} {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) {\n val solve = (s : (String, String)) => {\n val str_builder = new StringBuilder(s._1);\n\n def flip_at = (i : Int) =>\n str_builder.setCharAt(i,\n str_builder.charAt(i) match {\n case '0' => '1'\n case '1' => '0'\n }\n )\n\n val indices_to_flip : Seq[Int] = s.zipped.toIndexedSeq.zipWithIndex.filter{ case ((x,y),_) => x != y }.map(_._2)\n\n def flip = (xs : Seq[Int], f : Int => Unit) =>\n (xs.size % 2, xs.size / 2) match {\n case (1, _) => println(\"impossible\"); false\n case (0, halfsz) => xs.take(halfsz) foreach f; true\n }\n\n if (flip(indices_to_flip, flip_at)) {\n println(str_builder);\n }\n }\n\n solve(( (f : () => String) => (f(), f()) ) ( StdIn.readLine ));\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) {\n val solve = (s : (String, String)) => {\n val str_builder = new StringBuilder(s._1);\n\n def flip_at = (i : Int) =>\n str_builder.setCharAt(i,\n str_builder.charAt(i) match {\n case '0' => '1'\n case '1' => '0'\n }\n )\n\n val indices_to_flip : Seq[Int] = s.zipped.toIndexedSeq.zipWithIndex.filter{ case ((x,y),_) => x != y }.map(_._2)\n\n def flip = (xs : Seq[Int], f : Int => Unit) =>\n (xs.size % 2, xs.size / 2) match {\n case (1, _) => false\n case (0, halfsz) => xs.take(halfsz) foreach f; true\n }\n\n println(\n flip(indices_to_flip, flip_at) match {\n case true => str_builder;\n case false => \"impossible\"\n } )\n\n }\n\n solve(( (f : () => String) => (f(), f()) ) ( StdIn.readLine ));\n }\n}\n"}, {"source_code": "object P545_B_Equidistant_String {\n\n def find(s: String, t: String): String = {\n var flag = true\n val p: Seq[Char] = s.zip(t).map {\n case (a, b) =>\n if (a == b) a\n else {\n if (flag) {\n flag = false\n a\n } else {\n flag = true\n b\n }\n }\n }\n if (flag) p.mkString\n else \"impossible\"\n }\n\n def main(args: Array[String]) = {\n val s = scala.io.StdIn.readLine\n val t = scala.io.StdIn.readLine\n val p = find(s, t)\n println(p)\n }\n\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\n\nobject B extends App {\n val s = readLine().map(_.toString.toInt)\n val t = readLine().map(_.toString.toInt)\n val answer = new Array[Int](s.length)\n\n def dist(A: Seq[Int], B: Seq[Int]): Int = A.zip(B).map(x => Math.abs(x._1 - x._2)).sum\n\n def solve(): Boolean = {\n var dist1 = dist(s, answer)\n var dist2 = dist(t, answer)\n\n if (dist1 == dist2) true\n else {\n for (i <- 0 until s.length) {\n if (s(i) == 1 && t(i) == 0 && dist1 > dist2) {\n answer(i) = 1\n dist1 -= 1\n dist2 += 1\n } else if (s(i) == 0 && t(i) == 1 && dist2 > dist1) {\n answer(i) = 1\n dist1 += 1\n dist2 -= 1\n }\n\n if (dist1 == dist2) return true\n }\n false\n }\n }\n\n\n println(if (solve()) answer.mkString(\"\") else \"impossible\")\n}\n"}, {"source_code": "import scala.io.StdIn\nobject b extends App {\n var l = List(StdIn.readLine, StdIn.readLine)\n var d = l(0).count(_=='1') - l(1).count(_=='1')\n if (d < 0) { d = -d; l=l.reverse }\n println(if (d%2 == 0) {\n d /= 2\n l(0).zip(l(1)).map(x =>\n if (x._1 != x._2 && x._2 == '0' && d > 0) {d-=1; '1'} else '0'\n ).mkString\n } else \"impossible\")\n}\n"}, {"source_code": "import scala.io.StdIn\nobject z1 extends App {\n var s = StdIn.readLine().toCharArray\n var t = StdIn.readLine().toCharArray\n var c = 0\n var p = StringBuilder.newBuilder\n (0 until s.length).foreach(i=>{\n if (s(i)!=t(i)) c+=1\n if (c%2==0) p+=s(i) else p+=t(i)\n })\n if (c%2==1) println(\"impossible\") else println(p)\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _545B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val s = next\n val t = next\n val n = s.length\n val diff = (0 until n).map(i => if (s(i) == t(i)) 0 else 1).sum\n if (diff % 2 == 1) println(\"impossible\")\n else {\n val ans = new StringBuilder\n def doit(i: Int, cnt: Int): Unit = {\n if (i < n) {\n if (s(i) == t(i)) {\n ans += s(i)\n doit(i + 1, cnt)\n }\n else {\n if (cnt < diff / 2) {\n ans += s(i)\n doit(i + 1, cnt + 1)\n }\n else {\n ans += t(i)\n doit(i + 1, cnt)\n }\n }\n }\n }\n\n doit(0, 0)\n println(ans.toString)\n }\n}\n"}, {"source_code": "object B545 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val s = read\n val t = read\n var dist = 0\n for(i <- 0 until s.length) {\n if(s(i) != t(i)) dist += 1\n }\n if(dist%2 == 0) {\n val res = Array.fill(s.length)('x')\n var j = 0\n for(i <- 0 until s.length) {\n if(s(i) != t(i)) {\n if(j%2 == 0)\n res(i) = s(i)\n else\n res(i) = t(i)\n j += 1\n } else {\n res(i) = s(i)\n }\n }\n println(res.mkString(\"\"))\n } else {\n println(\"impossible\")\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "\nobject B545 extends App{\n\n val s = readLine\n val t = readLine\n val ln = s.size\n var flag = false\n var counter = 0\n\n val result = for(i <- 0 until ln) yield {\n if(s(i) == t(i))\n s(i)\n else\n {\n counter += 1\n if(flag)\n { flag = false; s(i) }\n else\n { flag = true ; t(i) }\n }\n }\n\n if(counter % 2 != 0)\n print(\"impossible\")\n else\n print(result.mkString(\"\"))\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val s = next.toCharArray\n val p = next.toCharArray\n val n = s.length\n var diff = 0\n for (i <- 0 until n) {\n if (s(i) != p(i))\n diff += 1\n }\n if (diff % 2 == 1) {\n out.println(\"impossible\")\n } else {\n var first = 0\n var second = 0\n for (i <- 0 until n) {\n if (s(i) != p(i)) {\n if (first > second) {\n out.print(p(i))\n second += 1\n } else {\n out.print(s(i))\n first += 1\n }\n } else {\n out.print(s(i))\n }\n }\n }\n return 0\n }\n}"}, {"source_code": "object _545B extends CodeForcesApp {\n import scala.collection.mutable\n\n override type Input = (List[Char], List[Char])\n override type Output = Option[List[Char]]\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n (next.toList, next.toList)\n }\n\n override def solve(input: Input) = {\n val (s, t) = input\n\n var count = 0\n\n val result = mutable.ListBuffer.empty[Char]\n\n for {\n (s1, t1) <- s zip t\n } {\n if (s1 == t1) {\n result += s1\n } else {\n if (count == 0) {\n result += s1\n count += 1\n } else {\n result += t1\n count -= 1\n }\n }\n }\n when(count == 0)(result.toList)\n }\n\n override def format(result: Output) = result match {\n case None => \"impossible\"\n case Some(sol) => sol.mkString\n }\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp extends App {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /********************************[ lib ]************************************/\n import scala.collection.mutable\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type m_=>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None\n /******************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n def timeLimitSecond = 1\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\nobject b extends App {\n var l = List(StdIn.readLine, StdIn.readLine)\n var d = l(0).count(_=='1') - l(1).count(_=='1')\n if (d < 0) { d = -d; l=l.reverse }\n println(if (d%2 == 0) {\n d /= 2\n val t = l(0).zip(l(1)).map(x =>\n if (x._1 != x._2 && x._2 == '0' && d > 0) {d-=1; '1'} else '0'\n ).mkString\n } else \"impossible\")\n}\n"}, {"source_code": "import scala.io.StdIn\nobject b extends App {\n val l = List(StdIn.readLine, StdIn.readLine)\n var d = l(0).count(_=='1') - l(1).count(_=='1')\n if (d < 0) { d = -d; l.reverse }\n println(if (d%2 == 0) {\n d /= 2\n l(0).zip(l(1)).map(x =>\n if (x._1 != x._2 && x._1 == '0' && d > 0) {d-=1; '1'} else '0'\n ).mkString\n } else \"impossible\")\n}\n"}, {"source_code": "import scala.io.StdIn\nobject b extends App {\n val (a, b) = (StdIn.readLine, StdIn.readLine)\n var d = (a.count(_=='1') - b.count(_=='1')).abs\n println(if (d%2 == 0) {\n d /= 2\n a.zip(b).map(x => if (x._1 != x._2 && d > 0) {d-=1; '1'} else '0').mkString\n } else \"impossible\")\n}\n"}, {"source_code": "object B545 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val s = read\n val t = read\n var dist = 0\n for(i <- 0 until s.length) {\n if(s(i) != t(i)) dist += 1\n }\n if(dist%2 == 0) {\n val res = Array.fill(s.length)('x')\n var j = 0\n for(i <- 0 until s.length) {\n if(s(i) != t(i)) {\n if(j%2 == 0)\n res(i) = '0'\n else\n res(i) = '1'\n j += 1\n } else {\n res(i) = s(i)\n }\n }\n println(res.mkString(\"\"))\n } else {\n println(\"impossible\")\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "2df181f2d1f4063a22fd2fa2d47eef92"} {"source_code": "import scala.runtime.ScalaRunTime._\n\nobject Main\n{\n def inv(p : Array[Int]) : Array[Int] =\n {\n var r = p.clone\n for(i <- 0 until p.length)\n r(p(i)-1) = i+1\n r\n }\n\n def permute(w : Array[Int], p : Array[Int]) : Array[Int] = \n {\n var r = w.clone\n for(i <- 0 until w.length)\n r(i) = p(w(i)-1)\n r\n }\n\n def main(args : Array[String]) : Unit =\n {\n val n = readInt\n val p1 = readLine split \" \" map (_.toInt)\n val p2 = readLine split \" \" map (_.toInt)\n val d = permute(p1,inv(p2))\n var i = 1\n while (i < n && d(i) > d(i-1))\n i += 1\n println(n-i)\n }\n}\n", "positive_code": [{"source_code": "import scala.runtime.ScalaRunTime._\n\nobject Main\n{\n def inv(p : Array[Int]) : Array[Int] =\n {\n var r = p.clone\n for(i <- 0 until p.length)\n r(p(i)-1) = i+1\n r\n }\n\n def permute(w : Array[Int], p : Array[Int]) : Array[Int] = \n {\n var r = w.clone\n for(i <- 0 until w.length)\n r(i) = p(w(i)-1)\n r\n }\n\n def main(args : Array[String]) : Unit =\n {\n val n = readInt\n val p1 = readLine split \" \" map (_.toInt)\n val p2 = readLine split \" \" map (_.toInt)\n val d = permute(p1,inv(p2))\n var i = 1\n while (i < n && d(i) > d(i-1))\n i += 1\n println(n-i)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject CF119Div1A {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val xs = readIntArray(n)\n val ys = readIntArray(n)\n\n var px = 0\n var py = 0\n while (py < n) {\n if (xs(px) == ys(py)) {\n px += 1\n py += 1\n } else {\n py += 1\n }\n }\n println(n - px)\n }\n\n private def readIntArray(n: Int): Array[Int] = {\n val xs = new Array[Int](n)\n val line = readLine()\n val words = line.split(\" \")\n for (i <- 0 until n) {\n xs(i) = words(i).toInt\n }\n xs\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject CF119Div1A {\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val xs = new Array[Int](n)\n val ys = new Array[Int](n)\n for (i <- 0 until n) {\n xs(i) = sc.nextInt()\n }\n for (i <- 0 until n) {\n ys(i) = sc.nextInt()\n }\n\n var px = 0\n var py = 0\n while (py < n) {\n if (xs(px) == ys(py)) {\n px += 1\n py += 1\n } else {\n py += 1\n }\n }\n println(n - px)\n }\n}\n"}, {"source_code": "import annotation.tailrec\n\n//package contest119.div2\n\n/**\n * Created with IntelliJ IDEA.\n * User: Oleg\n * Date: 11.05.12\n * Time: 23:04\n * To change this template use File | Settings | File Templates.\n */\n\nobject C {\n val n = readInt()\n val List(from, to) = List.fill(2)(readLine().split(' ').map(_.toInt - 1))\n val invTo = Array.fill(n)(0)\n for (i <- 0 until n) invTo(to(i)) = i\n val convFrom = (for (i <- 0 until n) yield invTo(from(i))).toArray\n\n def grows: Int = {\n for (i <- 0 until n - 1) if (convFrom(i + 1) < convFrom(i)) return n - (i + 1)\n 0\n }\n\n def main(args: Array[String]) {\n println(grows)\n }\n}\n"}], "negative_code": [{"source_code": "\nobject CF119Div1A {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val xs = toReversedIntArray(readLine().split(\" \"))\n val ys = toReversedIntArray(readLine().split(\" \"))\n\n val used = new Array[Boolean](n + 1)\n var xIndex = 0\n var yIndex = 0\n var cost = 0\n while (yIndex < n) {\n if (used(ys(yIndex))) {\n yIndex += 1\n } else if (used(xs(xIndex))) {\n xIndex += 1\n } else if (xs(xIndex) == ys(yIndex)) {\n used(ys(yIndex)) = true\n xIndex += 1\n yIndex += 1\n } else {\n used(xs(xIndex)) = true\n xIndex += 1\n cost += 1\n }\n }\n println(cost)\n }\n\n private def toReversedIntArray(strings: Array[String]): Array[Int] = {\n val intValues = new Array[Int](strings.length)\n for (i <- 0 until strings.length) {\n intValues((strings.length - 1) - i) = strings(i).toInt\n }\n intValues\n }\n}\n"}, {"source_code": "import scala.runtime.ScalaRunTime._\n\nobject Main\n{\n def permute[T](w : Array[T], p : Array[Int]) : Array[T] = \n {\n var r = w.clone\n for(i <- 0 until w.length)\n r(p(i)-1) = w(i)\n r\n }\n\n def main(args : Array[String]) : Unit =\n {\n val n = readInt\n val p1 = readLine split \" \" map (_.toInt)\n val p2 = readLine split \" \" map (_.toInt)\n val d = permute(p1,p2)\n var i = 1\n while (i < n && d(i) > d(i-1))\n i += 1\n println(n-i)\n }\n}\n"}], "src_uid": "a26e048eb9b18f87f1703d42e172f318"} {"source_code": "object C687 {\n def mark(\n n: Int,\n k: Int,\n subK: Int,\n dp: Array[Array[Array[Option[Boolean]]]],\n c: Array[Int]\n ): Boolean = {\n if (k == 0 && subK == 0) true \n else if (k < 0 || subK < 0) false\n else if (n == 0) false\n else if (dp(n % 2)(k)(subK) != null) dp(n)(k)(subK).get\n else {\n val ret = (mark(n - 1, k - c(n - 1), subK, dp, c) ||\n mark(n - 1, k - c(n - 1), subK - c(n - 1), dp, c) ||\n mark(n - 1, k, subK, dp, c)) \n\n dp(n)(k)(subK) = Some(ret)\n\n ret\n }\n }\n\n def main(args: Array[String]) = {\n val n :: k :: rest = readLine.split(\" \").map(_.toInt).toList\n\n val c = readLine.split(\" \").map(_.toInt).toArray\n\n val dp = Array.ofDim[Boolean](2, k + 1, k + 1)\n\n dp(0)(0)(0) = true\n\n var nn = 1\n\n while (nn <= n) {\n val index = nn % 2\n val prev = 1 - index\n\n var kk = 0\n while (kk <= k) {\n\n var subK = 0\n\n while (subK <= kk) {\n dp(index)(kk)(subK) = (if (kk - c(nn - 1) >= 0) dp(prev)(kk - c(nn - 1))(subK) else false) ||\n (if (kk - c(nn - 1) >= 0 && subK - c(nn - 1) >= 0) dp(prev)(kk - c(nn - 1))(subK - c(nn - 1)) else false) ||\n dp(prev)(kk)(subK)\n if (dp(index)(kk)(subK)) {\n //println(s\"$index, $kk, $subK\")\n //readLine\n }\n\n subK += 1\n }\n\n kk += 1\n }\n\n nn += 1\n }\n\n val ret = (0 to k).filter { case sum => dp(n % 2)(k)(sum) }\n\n println(ret.length)\n println(ret.mkString(\" \"))\n }\n}\n", "positive_code": [{"source_code": "object C687 {\n def main(args: Array[String]) = {\n val n :: k :: rest = readLine.split(\" \").map(_.toInt).toList\n val c = readLine.split(\" \").map(_.toInt).toArray\n val dp = Array.ofDim[Boolean](2, k + 1, k + 1)\n dp(0)(0)(0) = true\n var nn = 1\n while (nn <= n) {\n val index = nn % 2\n val prev = 1 - index\n var kk = 0\n while (kk <= k) {\n var subK = 0\n while (subK <= kk) {\n dp(index)(kk)(subK) = (if (kk - c(nn - 1) >= 0) dp(prev)(kk - c(nn - 1))(subK) else false) ||\n (if (kk - c(nn - 1) >= 0 && subK - c(nn - 1) >= 0) dp(prev)(kk - c(nn - 1))(subK - c(nn - 1)) else false) ||\n dp(prev)(kk)(subK)\n subK += 1\n }\n kk += 1\n }\n nn += 1\n }\n val ret = (0 to k).filter { case sum => dp(n % 2)(k)(sum) }\n println(ret.length)\n println(ret.mkString(\" \"))\n }\n}\n"}], "negative_code": [], "src_uid": "db4775339de9122f1ae0c047fd39220f"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline private final def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n var i = from\n while(i <= to) { f(i); i += 1 }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n = ni()\n val s = ns(n)\n val c = Array.ofDim[Int](26)\n REP(n) { i =>\n c(s(i)-'a') += 1\n }\n val ones = c('n'-'a')\n val zeros = c('z'-'a')\n val ans = ArrayBuffer[Int]()\n REP(ones) { _ => ans += 1}\n REP(zeros) { _ => ans += 0}\n out.println(ans.mkString(\" \"))\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Codeforces1120A extends App {\n StdIn.readLine()\n val cards = StdIn.readLine().split(\"\")\n val ones = cards.filter(a => a == \"n\").map(a => \"1\")\n val zeroes = cards.filter(a => a == \"z\").map(a => \"0\")\n println((ones ++ zeroes).mkString(\" \"))\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Codeforces1120A extends App {\n StdIn.readLine()\n val word = StdIn.readLine()\n val ones = word.split(\"\").filter(a => a == \"n\").map(a => \"1\")\n val zeroes = word.split(\"\").filter(a => a == \"z\").map(a => \"0\")\n val n = ones ++ zeroes\n println(n.mkString(\" \"))\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject Codeforces1120A extends App {\n StdIn.readLine()\n val word = StdIn.readLine()\n val ones = word.split(\"\").filter(a => a == \"n\").map(a => \"1\")\n val zeroes = word.split(\"\").filter(a => a == \"z\").map(a => \"0\")\n if (ones.length > 0)\n println(ones.mkString(\" \") + \" \" + zeroes.mkString(\" \"))\n else\n println(\"0\")\n}\n"}], "src_uid": "5e5dbd70c7fcedf0f965aed5bafeb06c"} {"source_code": "import annotation._\nimport io.Source\n// two lists: kayak list and catamaran list\n\n// while we still have two metres available:\n// choose either the biggest catamaran, or the two biggest kayaks (whichever is bigger)\n// reduce the lists appropriately, and repeat\n//\n// we have one metre, or no metres:\n// choose biggest kayak, or do nothing\n\nobject Lorry {\n val cataSize = 2\n val kayakSize = 1\n\n def main(args: Array[String]) = {\n val lines = Source.stdin.getLines()\n val firstLine = lines.next().split(\" \")\n val numBoats = firstLine(0).toInt\n var truckVolume = firstLine(1).toInt\n\n // need to cover the case where truckVolume is odd:\n // choose the best kayak first\n val boats = getBoatLists(lines, numBoats)\n\n var kayaks = boats._1\n val catamarans = boats._2\n var accum: Pair[List[Int], Int] = Pair(Nil, 0)\n if (truckVolume % 2 == 1 && !kayaks.isEmpty) {\n accum = Pair(List(kayaks.head._1), kayaks.head._2)\n kayaks = kayaks.tail\n truckVolume -= kayakSize\n }\n val chosenBoatsAndCapacity = getOptimalSet(kayaks, catamarans, truckVolume, accum)\n println(chosenBoatsAndCapacity._2)\n // should split the output... put a space between the boats or something?\n chosenBoatsAndCapacity._1.foreach(x => print(x + \" \"))\n println()\n }\n\n def getBoatLists(lines: Iterator[String], numBoats: Int) = {\n var kayaks: List[Pair[Int, Int]] = Nil\n var catamarans: List[Pair[Int, Int]] = Nil\n\n for (i <- 1 to numBoats) {\n var current = lines.next().split(\" \")\n if (current(0).toInt == 1)\n kayaks = Pair(i, current(1).toInt) :: kayaks\n else\n catamarans = Pair(i, current(1).toInt) :: catamarans\n }\n kayaks = kayaks.sortWith((first, second) => first._2 > second._2)\n catamarans = catamarans.sortWith((first, second) => first._2 > second._2)\n\n Pair(kayaks, catamarans)\n }\n\n @tailrec\n final def getOptimalSet(kayaks: List[Pair[Int, Int]], catas: List[Pair[Int, Int]], spaceLeft: Int, accum: Pair[List[Int], Int]):\n Pair[List[Int], Int] = {\n catas match {\n case Nil => finish(kayaks, spaceLeft, kayakSize, accum)\n case (cnum, ccargo) :: rcatas => \n if (spaceLeft >= cataSize) \n kayaks match {\n case (knum1, kcargo1) :: (knum2, kcargo2) :: rkayaks => \n if (kcargo1 + kcargo2 > ccargo)\n getOptimalSet(rkayaks, catas, spaceLeft - cataSize, Pair(knum1 :: knum2 :: accum._1, accum._2 + kcargo1 +\n kcargo2))\n else\n getOptimalSet(kayaks, rcatas, spaceLeft - cataSize, Pair(cnum :: accum._1, accum._2 + ccargo))\n case List(Pair(knum, kcargo)) => \n if (kcargo > ccargo)\n finish(catas, spaceLeft - kayakSize, cataSize, Pair(knum :: accum._1, accum._2 + kcargo))\n else\n getOptimalSet(kayaks, rcatas, spaceLeft - cataSize, Pair(cnum :: accum._1, accum._2 + ccargo))\n case Nil =>\n finish(catas, spaceLeft, cataSize, accum)\n }\n else \n finish(kayaks, spaceLeft, kayakSize, accum)\n }\n }\n\n def finish(boats: List[Pair[Int, Int]], spaceLeft: Int, boatSize: Int, accum: Pair[List[Int], Int]): Pair[List[Int], Int] = {\n\n @tailrec\n def finishHelper(boats: List[Pair[Int, Int]], spaceLeft: Int, accum: Pair[List[Int], Int]): Pair[List[Int], Int] = {\n boats match {\n case (bnum, bcargo) :: rboats if (spaceLeft >= boatSize) => \n finishHelper(rboats, spaceLeft - boatSize, Pair(bnum :: accum._1, accum._2 + bcargo))\n case _ => accum\n }\n }\n finishHelper(boats, spaceLeft, accum)\n }\n}\n", "positive_code": [{"source_code": "object P3B {\n def main(args : Array[String]) {\n val Array(n, v) = readLine split \" \" map {_.toInt}\n val a = Array.fill(n) {\n val Array(t, p) = readLine split \" \" map {_.toInt}\n (t, p)\n }.zipWithIndex\n val a1 = a filter {_._1._1 == 1} sortBy {-_._1._2}\n val s1 = a1.scanLeft(0){_ + _._1._2}\n val a2 = a filter {_._1._1 == 2} sortBy {-_._1._2}\n val s2 = a2.scanLeft(0){_ + _._1._2}\n val vU = v min (a1.size + a2.size * 2)\n val s = for (i <- 0 to vU / 2) yield {\n s1(vU - i * 2 min a1.size) + s2(i min a2.size)\n }\n val m = s.max\n println(m)\n val k = s indexOf m\n val w = ((a1 take vU - k * 2) ++ (a2 take k)) map {_._2 + 1}\n println(w mkString \" \")\n }\n}"}, {"source_code": "object P3B {\n def main(args : Array[String]) {\n val Array(n, v) = readLine split \" \" map {_.toInt}\n val a = Array.fill(n) {\n val Array(t, p) = readLine split \" \" map {_.toInt}\n (t, p)\n }.zipWithIndex\n val a1 = a filter {_._1._1 == 1} sortBy {-_._1._2}\n val s1 = a1.scanLeft(0){_ + _._1._2}\n val a2 = a filter {_._1._1 == 2} sortBy {-_._1._2}\n val s2 = a2.scanLeft(0){_ + _._1._2}\n val vU = v min (a1.size + a2.size * 2)\n val s = for (i <- 0 to vU / 2) yield {\n s1(vU - i * 2 min a1.size) + s2(i min a2.size)\n }\n val m = s.max\n println(m)\n val k = s indexOf m\n val w = ((a1 take vU - k * 2) ++ (a2 take k)) map {_._2 + 1}\n println(w mkString \" \")\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject Boats extends App {\n\n val scanner = new Scanner(System.in)\n\n val boatsNum = scanner.nextInt()\n val truckSize = scanner.nextInt()\n\n var light = mutable.PriorityQueue.empty[Boat]\n var heavy = mutable.PriorityQueue.empty[Boat]\n\n (1 until boatsNum + 1).foreach {\n cnt =>\n val t =scanner.next().toInt\n if (t == 1) {\n light += Boat(1, scanner.next().toInt, cnt)\n } else {\n heavy += Boat(2, scanner.next().toInt, cnt)\n }\n }\n\n var res = new StringBuffer()\n var sum = 0\n\n def append(b: Boat): Unit = {\n sum += b.weight\n res.append(b.order)\n res.append(\" \")\n }\n\n solve(truckSize)\n\n def solve(sizeLeft: Int): Unit = {\n if (sizeLeft == 0) {\n printResult()\n } else if (sizeLeft == 1 && !light.isEmpty) {\n append(light.head)\n printResult()\n } else if (sizeLeft == 1 && light.isEmpty) {\n printResult()\n } else if (light.isEmpty && heavy.isEmpty) {\n printResult()\n } else if (light.isEmpty) {\n append(heavy.head)\n heavy = heavy.tail\n solve(sizeLeft - 2)\n } else if (heavy.isEmpty) {\n append(light.head)\n light = light.tail\n solve(sizeLeft - 1)\n } else if (light.size == 1) {\n if (heavy.head.weight > light.head.weight) {\n append(heavy.head)\n heavy = heavy.tail\n solve(sizeLeft - 2)\n } else {\n append(light.head)\n light = light.tail\n solve(sizeLeft - 1)\n }\n } else {\n val f = light.dequeue()\n val s = light.head\n if (heavy.head.weight > s.weight + f.weight) {\n append(heavy.dequeue())\n light += f\n solve(sizeLeft - 2)\n } else {\n append(f)\n solve(sizeLeft - 1)\n }\n }\n }\n\n def printResult(): Unit = {\n println(sum)\n println(res)\n }\n\n case class Boat(size: Int, weight: Int, order: Int) extends Ordered[Boat] {\n override def compare(that: Boat): Int = this.weight.compareTo(that.weight)\n }\n\n /*\n * 20 19\n2 47\n1 37\n1 48\n2 42\n2 48\n1 38\n2 47\n1 48\n2 47\n1 41\n2 46\n1 28\n1 49\n1 45\n2 34\n1 43\n2 29\n1 46\n2 45\n2 18\n * */\n\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, v) = in.next().split(' ').map(_.toInt)\n val boats = in.take(n).toList.zipWithIndex.map(i => (i._1, (i._2 + 1).toString))\n val smallBoats = boats.filter(_._1.head == '1').map(i => (i._1.drop(2).toInt, i._2)).sorted.reverse\n val bigBoats: List[(Int, String)] = boats.filter(_._1.head == '2').map(i => (i._1.drop(2).toInt, i._2))\n val bigSmallBoat = if (v % 2 == 0 || smallBoats.length == 0) None else Some(smallBoats.head)\n val newSmallBoats = bigSmallBoat match {\n case None => smallBoats\n case Some(_) => smallBoats.tail\n }\n\n val pairsSmallBoats = newSmallBoats.grouped(2).map{l =>\n if (l.length == 2)\n (l.head._1 + l.last._1, l.head._2 + \" \" + l.last._2)\n else\n (l.head._1, l.head._2)\n }.toList\n val r = (pairsSmallBoats ::: bigBoats).sorted.reverse.take(v / 2)\n println(bigSmallBoat.map(_._1).getOrElse(0) + r.map(_._1).sum)\n println(r.map(_._2).mkString(bigSmallBoat.map(_._2 + \" \").getOrElse(\"\"), \" \", \"\"))\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, v) = in.next().split(' ').map(_.toInt)\n val boats = in.take(n).toList.zipWithIndex.map(i => (i._1, (i._2 + 1).toString))\n val smallBoats = boats.filter(_._1.head == '1').map(i => (i._1.drop(2).toInt, i._2)).sorted.reverse\n val bigBoats: List[(Int, String)] = boats.filter(_._1.head == '2').map(i => (i._1.drop(2).toInt, i._2))\n val bigSmallBoat = if (v % 2 == 0) None else Some(smallBoats.head)\n val newSmallBoats = bigSmallBoat match {\n case None => smallBoats\n case Some(_) => smallBoats.tail\n }\n\n val pairsSmallBoats = newSmallBoats.grouped(2).map(l => (l.head._1 + l.last._1, l.head._2 + \" \" + l.last._2)).toList\n val r = (pairsSmallBoats ::: bigBoats).sorted.reverse.take(v / 2)\n println(bigSmallBoat.map(_._1).getOrElse(0) + r.map(_._1).sum)\n println(r.map(_._2).mkString(bigSmallBoat.map(_._2 + \" \").getOrElse(\"\"), \" \", \"\"))\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, v) = in.next().split(' ').map(_.toInt)\n val boats = in.take(n).toList.zipWithIndex.map(i => (i._1, (i._2 + 1).toString))\n val smallBoats = boats.filter(_._1.head == '1').map(i => (i._1.drop(2).toInt, i._2)).sorted.reverse\n val bigBoats: List[(Int, String)] = boats.filter(_._1.head == '2').map(i => (i._1.drop(2).toInt, i._2))\n val bigSmallBoat = if (v % 2 == 0) None else Some(smallBoats.head)\n val newSmallBoats = bigSmallBoat match {\n case None => smallBoats\n case Some(_) => smallBoats.tail\n }\n\n val pairsSmallBoats = newSmallBoats.sliding(2).map(l => (l.head._1 + l.last._1, l.head._2 + \" \" + l.last._2)).toList\n val r = (pairsSmallBoats ::: bigBoats).sorted.reverse.take(v / 2)\n println(bigSmallBoat.map(_._1).getOrElse(0) + r.map(_._1).sum)\n println(r.map(_._2).mkString(bigSmallBoat.map(_._2 + \" \").getOrElse(\"\"), \"\\n\", \"\"))\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, v) = in.next().split(' ').map(_.toInt)\n val boats = in.take(n).toList.zipWithIndex.map(i => (i._1, (i._2 + 1).toString))\n val smallBoats = boats.filter(_._1.head == '1').map(i => (i._1.drop(2).toInt, i._2)).sorted.reverse\n val bigBoats: List[(Int, String)] = boats.filter(_._1.head == '2').map(i => (i._1.drop(2).toInt, i._2))\n val bigSmallBoat = if (v % 2 == 0) None else Some(smallBoats.head)\n val newSmallBoats = bigSmallBoat match {\n case None => smallBoats\n case Some(_) => smallBoats.tail\n }\n\n val pairsSmallBoats = newSmallBoats.sliding(2).map(l => (l.head._1 + l.last._1, l.head._2 + \" \" + l.last._2)).toList\n val r = (pairsSmallBoats ::: bigBoats).sorted.reverse.take(v / 2)\n println(bigSmallBoat.map(_._1).getOrElse(0) + r.map(_._1).sum)\n println(r.map(_._2).mkString(bigSmallBoat.map(_._2).getOrElse(\"\"), \"\\n\", \"\"))\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, v) = in.next().split(' ').map(_.toInt)\n val boats = in.take(n).toList.zipWithIndex.map(i => (i._1, (i._2 + 1).toString))\n val smallBoats = boats.filter(_._1.head == '1').map(i => (i._1.drop(2).toInt, i._2)).sorted.reverse\n val bigBoats: List[(Int, String)] = boats.filter(_._1.head == '2').map(i => (i._1.drop(2).toInt, i._2))\n val bigSmallBoat = if (v % 2 == 0) None else Some(smallBoats.head)\n val newSmallBoats = bigSmallBoat match {\n case None => smallBoats\n case Some(_) => smallBoats.tail\n }\n\n val pairsSmallBoats = newSmallBoats.sliding(2).map(l => (l.head._1 + l.last._1, l.head._2 + \" \" + l.last._2)).toList\n val r = (pairsSmallBoats ::: bigBoats).sorted.reverse.take(v / 2)\n println(bigSmallBoat.map(_._1).getOrElse(0) + r.map(_._1).sum)\n println(r.map(_._2).mkString(bigSmallBoat.map(_._2 + \" \").getOrElse(\"\"), \" \", \"\"))\n}"}, {"source_code": "import java.util.Scanner\n\nobject Boats extends App {\n\n val scanner = new Scanner(System.in)\n\n val boatsNum = scanner.nextInt()\n val truckSize = scanner.nextInt()\n\n var light = List.empty[Boat]\n var heavy = List.empty[Boat]\n\n (1 until boatsNum + 1).foreach { cnt =>\n val t = scanner.nextInt()\n if (t == 1) {\n light :+= Boat(1, scanner.nextInt(), cnt)\n } else {\n heavy :+= Boat(2, scanner.nextInt(), cnt)\n }\n }\n\n light = light.sortBy(_.weight).reverse\n heavy = heavy.sortBy(_.weight).reverse\n\n var res = List.empty[Boat]\n\n solve(truckSize)\n\n def solve(sizeLeft: Int): Unit = {\n if (sizeLeft == 0) {\n printResult()\n } else if (sizeLeft == 1 && !light.isEmpty) {\n res :+= light.head\n printResult()\n } else if (light.isEmpty && heavy.isEmpty) {\n printResult()\n } else if(light.isEmpty) {\n res :+= heavy.head\n heavy = heavy.tail\n solve(sizeLeft - 2)\n } else if (heavy.isEmpty) {\n res :+= light.head\n light = light.tail\n solve(sizeLeft - 1)\n } else if (light.size == 1) {\n if (heavy.head.weight > light.head.weight) {\n res :+= heavy.head\n heavy = heavy.tail\n solve(sizeLeft - 2)\n } else {\n res :+= light.head\n light = light.tail\n solve(sizeLeft - 1)\n }\n } else {\n if (heavy.head.weight > light.head.weight + light.tail.head.weight) {\n res :+= heavy.head\n heavy = heavy.tail\n solve(sizeLeft - 2)\n } else {\n res :+= light.head\n light = light.tail\n res :+= light.head\n light = light.tail\n solve(sizeLeft - 2)\n }\n }\n }\n\n def printResult(): Unit = {\n println(res.foldLeft(0)((acc, t) => acc + t.weight))\n println(res.map(_.order).mkString)\n }\n\n case class Boat(size: Int, weight: Int, order: Int) {\n\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject Boats extends App {\n\n val scanner = new Scanner(System.in)\n\n val boatsNum = scanner.nextInt()\n val truckSize = scanner.nextInt()\n\n var light = mutable.PriorityQueue.empty[Boat]\n var heavy = mutable.PriorityQueue.empty[Boat]\n\n (1 until boatsNum + 1).foreach {\n cnt =>\n val t =scanner.next().toInt\n if (t == 1) {\n light += Boat(1, scanner.next().toInt, cnt)\n } else {\n heavy += Boat(2, scanner.next().toInt, cnt)\n }\n }\n\n var res = \"\"\n var sum = 0\n\n def append(b: Boat): Unit = {\n sum += b.weight\n res += \" \" + b.order\n }\n\n solve(truckSize)\n\n def solve(sizeLeft: Int): Unit = {\n if (sizeLeft == 0) {\n printResult()\n } else if (sizeLeft == 1 && !light.isEmpty) {\n append(light.head)\n printResult()\n } else if (sizeLeft == 1 && light.isEmpty) {\n printResult()\n } else if (light.isEmpty && heavy.isEmpty) {\n printResult()\n } else if (light.isEmpty) {\n append(heavy.head)\n heavy = heavy.tail\n solve(sizeLeft - 2)\n } else if (heavy.isEmpty) {\n append(light.head)\n light = light.tail\n solve(sizeLeft - 1)\n } else if (light.size == 1) {\n if (heavy.head.weight > light.head.weight) {\n append(heavy.head)\n heavy = heavy.tail\n solve(sizeLeft - 2)\n } else {\n append(light.head)\n light = light.tail\n solve(sizeLeft - 1)\n }\n } else {\n val f = light.dequeue()\n val s = light.head\n if (heavy.head.weight > s.weight + f.weight) {\n append(heavy.dequeue())\n light += f\n solve(sizeLeft - 2)\n } else {\n append(f)\n solve(sizeLeft - 1)\n }\n }\n }\n\n def printResult(): Unit = {\n println(res)\n println(sum)\n }\n\n case class Boat(size: Int, weight: Int, order: Int) extends Ordered[Boat] {\n override def compare(that: Boat): Int = this.weight.compareTo(that.weight)\n }\n\n /*\n * 20 19\n2 47\n1 37\n1 48\n2 42\n2 48\n1 38\n2 47\n1 48\n2 47\n1 41\n2 46\n1 28\n1 49\n1 45\n2 34\n1 43\n2 29\n1 46\n2 45\n2 18\n * */\n\n}"}, {"source_code": "import java.util.Scanner\n\nobject Boats extends App {\n\n val scanner = new Scanner(System.in)\n\n val boatsNum = scanner.nextInt()\n val truckSize = scanner.nextInt()\n\n var light = List.empty[Boat]\n var heavy = List.empty[Boat]\n\n (1 until boatsNum + 1).foreach { cnt =>\n val t = scanner.nextInt()\n if (t == 1) {\n light :+= Boat(1, scanner.nextInt(), cnt)\n } else {\n heavy :+= Boat(2, scanner.nextInt(), cnt)\n }\n }\n\n light = light.sortBy(_.weight).reverse\n heavy = heavy.sortBy(_.weight).reverse\n\n var res = List.empty[Boat]\n\n solve(truckSize)\n\n def solve(sizeLeft: Int): Unit = {\n if (sizeLeft == 0) {\n printResult()\n } else if (sizeLeft == 1 && !light.isEmpty) {\n res :+= light.head\n printResult()\n } else if (light.isEmpty && heavy.isEmpty) {\n printResult()\n } else if(light.isEmpty) {\n res :+= heavy.head\n heavy = heavy.tail\n solve(sizeLeft - 2)\n } else if (heavy.isEmpty) {\n res :+= light.head\n light = light.tail\n solve(sizeLeft - 1)\n } else if (light.size == 1) {\n if (heavy.head.weight > light.head.weight) {\n res :+= heavy.head\n heavy = heavy.tail\n solve(sizeLeft - 2)\n } else {\n res :+= light.head\n light = light.tail\n solve(sizeLeft - 1)\n }\n } else {\n if (heavy.head.weight > light.head.weight + light.tail.head.weight) {\n res :+= heavy.head\n heavy = heavy.tail\n solve(sizeLeft - 2)\n } else {\n res :+= light.head\n light = light.tail\n res :+= light.head\n light = light.tail\n solve(sizeLeft - 2)\n }\n }\n }\n\n def printResult(): Unit = {\n println(res.foldLeft(0)((acc, t) => acc + t.weight))\n println(res.map(_.order).mkString(\" \"))\n }\n\n case class Boat(size: Int, weight: Int, order: Int) {\n\n }\n\n}\n"}, {"source_code": "object P3B {\n def main(args : Array[String]) {\n val Array(n, v) = readLine split \" \" map {_.toInt}\n val a = Array.fill(n) {\n val Array(t, p) = readLine split \" \" map {_.toInt}\n (t, p)\n }.zipWithIndex groupBy {_._1._1}\n val a1 = a(1) sortBy {_._1._2}\n val s1 = a1.scanLeft(0){_ + _._1._2}\n val a2 = a(2) sortBy {_._1._2}\n val s2 = a2.scanLeft(0){_ + _._1._2}\n val vU = v min (a1.size + a2.size * 2)\n val s = for (i <- 0 to vU / 2) yield s1(vU - i * 2) + s2(i)\n val m = s.max\n println(m)\n val k = s indexOf m\n val w = ((a1 take vU - k * 2) ++ (a2 take k)) map {_._2 + 1}\n println(w.mkString)\n }\n}\n"}, {"source_code": "object P3B {\n def main(args : Array[String]) {\n val Array(n, v) = readLine split \" \" map {_.toInt}\n val a = Array.fill(n) {\n val Array(t, p) = readLine split \" \" map {_.toInt}\n (t, p)\n }.zipWithIndex groupBy {_._1._1}\n val a1 = a(1) sortBy {_._1._2}\n val s1 = a1.scanLeft(0){_ + _._1._2}\n val a2 = a(2) sortBy {_._1._2}\n val s2 = a2.scanLeft(0){_ + _._1._2}\n val vU = v min (a1.size + a2.size * 2)\n val s = for {\n i <- 0 to vU / 2\n if (vU - i * 2 < s1.size)\n if (i < s2.size)\n } yield s1(vU - i * 2) + s2(i)\n val m = s.max\n println(m)\n val k = s indexOf m\n val w = ((a1 take vU - k * 2) ++ (a2 take k)) map {_._2 + 1}\n println(w mkString \" \")\n }\n}\n"}], "src_uid": "a1f98b06650a5755e784cd6ec6f3b211"} {"source_code": "object _964B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val n, a, b, c, t = io.read[Int]\n val ts = io.read[Vector, Int](n)\n val ans = ts.sumWith(i => a + (((c - b)*(t - i)) max 0))\n io.write(ans)\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n \n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n import IO._\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n private[IO] type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.head)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val r = new Reader\n val n, A, B, C, T = r.read[Int]\n val xs = r.read[Array[Int]](n).filter(_ <= T)\n \n if (B >= C) {\n println(A * xs.length)\n } else {\n println(xs.map(x => A + (T - x) * (C - B)).sum)\n }\n }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n def this() = this(new InputStreamReader(System.in))\n\n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n\n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n implicit val double: Read[Double] = new Read(_.read[String].toDouble)\n\n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n\n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine).takeWhile(_ != null).filter(_ != \"\").map(new StringTokenizer(_)).buffered\n}"}], "negative_code": [], "src_uid": "281b95c3686c94ae1c1e4e2a18b7fcc4"} {"source_code": "import java.io._\r\nimport scala.collection.immutable.TreeSet\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val reader = new BufferedReader(new java.io.InputStreamReader(System.in))\r\n val writer = new PrintWriter(System.out)\r\n def readInt(): Int = reader.readLine().toInt\r\n def readLong(): Long = reader.readLine().toLong\r\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\r\n def readArrayLong(): Array[Long] = reader.readLine().split(\" \").map(_.toLong)\r\n def readString(): String = reader.readLine()\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n\r\n def solve(t: Int = 0): Unit = {\r\n val n = readInt()\r\n val s = readString()\r\n var c = 0\r\n val R = Array('R','B')\r\n val B = Array('B','R')\r\n var last: Char = '?'\r\n for (i <- 0 until n) {\r\n if (s(i) == '?') c += 1\r\n else if (s(i) == 'R') {\r\n last = 'R'\r\n if (c > 0) {\r\n if (c % 2 == 0) {\r\n var j = 0\r\n while (c > 0) {\r\n writer.print(R(j))\r\n j += 1\r\n if (j == 2) j = 0\r\n c -= 1\r\n }\r\n } else {\r\n var j = 0\r\n while (c > 0) {\r\n writer.print(B(j))\r\n j += 1\r\n if (j == 2) j = 0\r\n c -= 1\r\n }\r\n }\r\n }\r\n writer.print('R')\r\n } else {\r\n last = 'B'\r\n if (c > 0) {\r\n if (c % 2 == 0) {\r\n var j = 0\r\n while (c > 0) {\r\n writer.print(B(j))\r\n j += 1\r\n if (j == 2) j = 0\r\n c -= 1\r\n }\r\n } else {\r\n var j = 0\r\n while (c > 0) {\r\n writer.print(R(j))\r\n j += 1\r\n if (j == 2) j = 0\r\n c -= 1\r\n }\r\n }\r\n }\r\n writer.print('B')\r\n }\r\n }\r\n\r\n if (c > 0) {\r\n if (last == 'R') {\r\n var j = 0\r\n while (c > 0) {\r\n writer.print(B(j))\r\n j += 1\r\n if (j == 2) j = 0\r\n c -= 1\r\n }\r\n } else {\r\n var j = 0\r\n while (c > 0) {\r\n writer.print(R(j))\r\n j += 1\r\n if (j == 2) j = 0\r\n c -= 1\r\n }\r\n }\r\n }\r\n\r\n writer.println()\r\n }\r\n\r\n def main(args: Array[String]) {\r\n multiTest(solve)\r\n //solve()\r\n writer.flush()\r\n }\r\n}", "positive_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n import scala.collection.immutable.TreeSet\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val s = readLine()\r\n\r\n val ans = {\r\n val set = TreeSet((0 until n).filterNot(i => s(i) == '?'): _*)\r\n\r\n def minAfter: Int => Option[Int] = i => set.rangeImpl(Some(i), None).headOption\r\n def maxBefore: Int => Option[Int] = i => set.rangeImpl(None, Some(i)).lastOption\r\n\r\n (0 until n).map {\r\n case i if s(i) == '?' =>\r\n (minAfter(i) orElse maxBefore(i)) match {\r\n case Some(j) =>\r\n if (i % 2 == j % 2) s(j)\r\n else if (s(j) == 'R') 'B'\r\n else 'R'\r\n case _ =>\r\n if (i % 2 == 0) 'B' else 'R'\r\n }\r\n case i => s(i)\r\n }\r\n .mkString(\"\")\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn\n\nobject Problem extends App {\n\n start()\n\n def start() = {\n println(parseInput().map(s => findSequence(s).mkString).mkString(\"\\n\"))\n }\n\n def parseInput(): Array[Array[Char]] = {\n val testCases = StdIn.readLine.stripLineEnd.toInt\n var result = Array[Array[Char]]()\n for(_ <- 1.to(testCases)) {\n StdIn.readLine\n val line = StdIn.readLine().stripLineEnd.trim.toCharArray\n result ++= Array(line)\n }\n result\n }\n\n def findSequence(seq: Array[Char]): Array[Char] = {\n def not(c: Char): Char = if (c == 'B') 'R' else 'B'\n\n val firstWildChar = seq.indexOf('?')\n if (firstWildChar > 0) {\n seq(firstWildChar) = not(seq(firstWildChar-1))\n findSequence(seq)\n } else if(firstWildChar == 0) {\n if (seq.length == 1) \"B\".toCharArray else {\n val (c, rest) = seq.splitAt(1)\n val s = if (rest(0) != '?') {\n Array(not(rest(0))) ++ rest\n } else {\n val newRest = findSequence(rest)\n Array(not(newRest(0))) ++ newRest\n }\n findSequence(s)\n }\n } else {\n seq\n }\n }\n}\n"}, {"source_code": "import java.io.PrintWriter\r\nimport java.util.Scanner\r\n\r\nobject Solution {\r\n // all ?????\r\n def solve(input: String): String = {\r\n def opposite(ch: Char): Char = if (ch == 'B') 'R' else 'B'\r\n\r\n val current = input.toCharArray\r\n\r\n if (current.forall(_ == '?')) current(0) = 'B'\r\n\r\n while (current.contains('?')) {\r\n val (_, pos) = current.zip(current.tail).zipWithIndex.find { case ((ch1, ch2), _) =>\r\n (ch1 == '?' && ch2 != '?') || (ch1 != '?' && ch2 == '?')\r\n }.get\r\n if (current(pos) == '?') current(pos) = opposite(current(pos + 1))\r\n else current(pos + 1) = opposite(current(pos))\r\n }\r\n\r\n new String(current)\r\n }\r\n\r\n def run(test: Int, input: Scanner, output: PrintWriter): Unit = {\r\n val n = input.nextInt()\r\n input.nextLine()\r\n val s = input.nextLine().substring(0, n)\r\n output.println(solve(s))\r\n }\r\n\r\n def run(input: Scanner, output: PrintWriter): Unit = {\r\n val tests = input.nextInt()\r\n\r\n (1 to tests).foreach { test =>\r\n run(test, input, output)\r\n output.flush()\r\n }\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n run(new Scanner(System.in), new PrintWriter(System.out))\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject Problem extends App {\n\n start()\n\n def start() = {\n println(parseInput().map(s => findSequence(s).mkString).mkString(\"\\n\"))\n }\n\n def parseInput(): Array[Array[Char]] = {\n val testCases = StdIn.readLine.stripLineEnd.toInt\n var result = Array[Array[Char]]()\n for(_ <- 1.to(testCases)) {\n StdIn.readLine\n val line = StdIn.readLine().stripLineEnd.trim.toCharArray\n result ++= Array(line)\n }\n result\n }\n\n def findSequence(seq: Array[Char]): Array[Char] = {\n def not(c: Char): Char = if (c == 'B') 'R' else 'B'\n\n val firstWildChar = seq.indexOf('?')\n if (firstWildChar > 0) {\n seq(firstWildChar) = not(seq(firstWildChar-1))\n findSequence(seq)\n } else if(firstWildChar == 0) {\n if (seq.length == 1) \"B\".toCharArray else {\n val (c, rest) = seq.splitAt(1)\n val s = if (rest(0) != '?') {\n Array(not(rest(0))) ++ rest\n } else {\n findSequence(rest)\n }\n findSequence(s)\n }\n } else {\n seq\n }\n }\n}\n"}], "src_uid": "280487a73e6070a7dc7deb44332d6319"} {"source_code": "object CodeforcesRound641a {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n val primes: Array[Int] = primeNumbers(1e6.toInt)\n (1 to t).foreach(_ => test(primes))\n }\n\n def test(primes: Array[Int])\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val Array(n, k) = rll_int\n val leastPrimeFactor: Int =\n primes.iterator\n .collectFirst { case i if n % i == 0 => i }\n .getOrElse(n)\n val res = n + leastPrimeFactor + (k - 1) * 2\n writer.println(res)\n }\n\n def primeNumbers(n: Int): Array[Int] = {\n val a = new Array[Boolean](n + 1)\n a(0) = true\n a(1) = true\n (2 to Math.sqrt(n).toInt).foreach { i =>\n if (!a(i)) {\n (i * i to n by i).foreach(j => a(j) = true)\n }\n }\n a.iterator.zipWithIndex.collect { case (v, k) if !v => k }.toArray\n }\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}", "positive_code": [{"source_code": "object A extends App {\n\n private def isPrime(n: Int): Boolean = primes.takeWhile(p => p * p <= n).forall(n % _ != 0)\n\n private lazy val primes: Stream[Int] = 2 #:: Stream.iterate(3)(_ + 2).filter(isPrime)\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val r = 2L * 0.max(k - 1) + n + primes.find(n % _ == 0).get\n\n println(r)\n }\n}\n"}, {"source_code": "object ProblemA extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n def divider(n: Int, startFrom: Int = 2): Int = {\n for (i <- startFrom to math.max(startFrom, math.sqrt(n).floor.toInt)) {\n if (n % i == 0) {\n return i\n }\n }\n n\n }\n\n @scala.annotation.tailrec\n def solve(sum: Int, k: Int): Int = {\n if (sum % 2 == 0) {\n k * 2 + sum\n } else {\n val d = divider(sum)\n val newSum = d + sum\n\n if (k == 1) {\n newSum\n } else {\n solve(newSum, k - 1)\n }\n }\n }\n\n\n val n = in.nextInt()\n\n for (i <- 1 to n) {\n val n = in.nextInt()\n val k = in.nextInt()\n\n println(solve(n, k))\n }\n\n\n}"}, {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val r = n + 2 * 0.max(k - 1) + (2 #:: Stream.iterate(3)(_ + 2)).find(n % _ == 0).get\n\n println(r)\n }\n}\n"}], "negative_code": [], "src_uid": "9fd9bc0a037b2948d60ac2bd5d57740f"} {"source_code": "import java.util.Scanner\n\nobject CF_528_2_D {\n\n// case class Edge(v1: Int, v2: Int)\n\n type In = (Int, Int, Scanner)\n type Out = Double\n \n def solve(in: In): Out = {\n val (n, s, sc) = in\n // Divide the weights equally amongst the leaves\n // Then return the leaf weight x 2\n val connectCount = Array.ofDim[Int](n+1)\n while(sc.hasNextInt) {\n connectCount(sc.nextInt) += 1\n }\n val leafcount = connectCount.count(_ == 1)\n s.toDouble / leafcount * 2\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, i.int, {\n i.nextLine;\n i.sc\n })\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change: \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def ceil(a: Int, b: Int) = (a - 1)/b + 1\n def ceil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, S = ni()\n val (from, to) = na2(N - 1, -1)\n val d = Array.ofDim[Int](N)\n REP(N - 1) { i =>\n d(from(i)) += 1\n d(to(i)) += 1\n }\n\n val cntDig1 = d.count(_ == 1)\n val ans = S.doubleValue() / cntDig1 * 2\n out.println(f\"$ans%.9f\")\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [], "src_uid": "7bdd8f0cf42855bebda4ccc56d8fe788"} {"source_code": "import scala.collection.mutable._\nimport scala.math._\nimport scala.util._\nimport scala.util.control.Breaks.break\nimport scala.util.control.Breaks.breakable\nimport java.util._\nobject Main extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt\n val t = for(i <- 1 to n) yield sc.nextInt\n val mx = t.max\n val mn = t.min\n val imax = t.indexOf(mx)\n val imin = t.lastIndexOf(mn)\n println(imax + (n-imin-1) + (if(imax > imin) -1 else 0))\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P144A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val hights = Array.fill(N)(sc.nextInt)\n\n val answer: Int = {\n val minValue = hights.min\n val maxValue = hights.max\n\n val rightMostMinPos = (0 until N).filter(hights(_) == minValue).last\n val leftMostMaxPos = (0 until N).filter(hights(_) == maxValue).head\n N - rightMostMinPos - 1 + leftMostMaxPos - (if (rightMostMinPos < leftMostMaxPos) 1 else 0)\n }\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "\nimport scala.collection.mutable.MutableList\n\nobject ArrivaloftheGeneral {\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in);\n\t\t// Initialization\n\t\tval n = scanner.nextInt()\n\t\t\t\tvar theList = new MutableList[Int];\n\t\tfor (i <- 1 to n) {\n\t\t\ttheList += scanner.nextInt\n\t\t}\n\t\tval theMin = theList.min\n\t\t\t\tval theMax = theList.max\n\t\t\t\tval indexMin = theList.lastIndexOf(theMin)\n\t\t\t\tval indexMax = theList.indexOf(theMax);\n\t\tif (indexMax > indexMin)\n\t\t\tprintln(indexMax + theList.size - indexMin - 2)\n\t\t\telse\n\t\t\t\tprintln(indexMax + theList.size - indexMin - 1)\n\n\t}\n}"}, {"source_code": "object AArrivalOfTheGeneral extends App {\n import scala.io.StdIn._\n\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n val ((_, h), (_, l)) = an.tail.zipWithIndex.foldLeft((an.head, 0), (an.head, 0)) {\n case (state @ ((higher, h), (lower, l)), (height, i)) =>\n if (height > higher) ((height, i + 1), state._2)\n else if (height <= lower) (state._1, (height, i + 1))\n else state\n }\n\n val ans = h + (n - l - 1) - (if (l <= h) 1 else 0)\n\n println(ans)\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val i = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n var max, maxi = 0\n var (min, mini) = (100, a.size - 1);\n for (i <- 0 until a.size) {\n val e = a(i)\n if (e > max) {\n max = e\n maxi = i\n }\n if (e <= min) {\n min = e\n mini = i\n }\n }\n if (mini < maxi) println(maxi + a.size - mini - 2)\n else println(maxi + a.size - mini - 1)\n }\n}"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject General {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def main(args: Array[String]) {\n val n = readInt\n val soldiers = readInts\n \n val maxSeconds = soldiers.indexOf(soldiers.max)\n val minSeconds = soldiers.reverse.indexOf(soldiers.min)\n println(maxSeconds + minSeconds + (if (n - minSeconds - 1 < maxSeconds) -1 else 0))\n }\n \n}"}, {"source_code": "object Main extends App{\n val n = readInt\n val a = readLine.split(\" \").map(i => i.toInt)\n val max = a.indexOf(a.max)\n val min = a.lastIndexOf(a.min)\n var s = if (max > min) -1 else 0\n println (s + max + (n - 1 - min))\n} "}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n var n = StdIn.readLine().toInt\n var A:Array[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n\n val min = A.zipWithIndex.filter(_._1 == A.min).last._2 + 1\n val max = A.zipWithIndex.filter(_._1 == A.max)(0)._2 + 1\n\n val l = A.length\n var ans = (max - 1) + (l - min)\n if(min < max)\n ans-=1\n\n println(ans)\n }\n\n\n}\n"}, {"source_code": "object Solution extends App {\n val n = readInt\n val s = readLine.split(\" \").map(_.toLong)\n \n val min = s.min\n val max = s.max\n \n val minIdx = s.size - s.reverse.indexWhere(_ == min) - 1\n val maxIdx = s.indexWhere(_ == max)\n \n if(minIdx > maxIdx) {\n println(maxIdx + s.size - minIdx - 1)\n } else {\n println(maxIdx + s.size - minIdx - 2)\n }\n}"}, {"source_code": "object General {\n\n def main(args: Array[String]): Unit = {\n val n: Int = readLine.toInt\n val aa: Seq[Int] = readLine.split(' ').map(_.toInt)\n\n val min = aa.min\n val max = aa.max\n val highest = aa.indexOf(max)\n val lowest = aa.lastIndexOf(min)\n val len = aa.length\n val result: Int = highest + (len - lowest) - 1 - (if (highest > lowest) 1 else 0)\n\n println(result)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject ArrivalOfTheGeneral extends App {\n val n = readLine.toInt\n val soldiers = readLine.split(\" \").map(_.toInt)\n\n var minpos = 0\n var maxpos = 0\n\n for (i <- 0 until n) {\n val s = soldiers(i)\n if (s <= soldiers(minpos))\n minpos = i\n if (s > soldiers(maxpos))\n maxpos = i\n }\n\n var res = n-minpos-1 + maxpos\n if (maxpos > minpos)\n res -= 1\n\n println(res)\n}"}, {"source_code": "object One44A extends App {\n\timport java.io.PrintWriter\n\timport java.util.Scanner\n\tval in = new Scanner(System.in)\n\tval out = new PrintWriter(System.out)\n\timport in._\n\timport out._\n\tval n = nextInt\n\tvar min = (-1, -1)\n\tvar max = (-1, -1)\n\t(0 until n).foreach { i =>\n\t\tval num = nextInt\n\t\tif (min._1 >= num || min._1 == -1) min = (num, i + 1)\n\t\tif (max._1 < num || max._1 == -1) max = (num, i + 1)\n\t}\n\tif (min._2 > max._2) {\n\t\tprintln(n - min._2 + max._2 - 1)\n\t} else {\n\t\tprintln(n - min._2 + max._2 - 2)\n\t}\n\tin.close\n\tout.close\n}"}, {"source_code": "object Main extends App {\n\tdef getMinMaxIndexTurple(array: Array[Int], maxIndex: Int, minIndex: Int, pointer: Int): (Int, Int) = {\n\t\tif (pointer == array.size) (minIndex, maxIndex)\n\t\telse if (array(pointer) > array(maxIndex)) getMinMaxIndexTurple(array, pointer, minIndex, pointer + 1)\n\t\telse if (array(pointer) <= array(minIndex)) getMinMaxIndexTurple(array, maxIndex, pointer, pointer + 1)\n\t\telse getMinMaxIndexTurple(array, maxIndex, minIndex, pointer + 1)\n\t}\n\t\n\tval numberOfSoldiers = readLine.toInt\n\tval soldiersArray = readLine.split(\" \").map(_.toInt)\n\n\tval (minIndex, maxIndex) = getMinMaxIndexTurple(soldiersArray, 0, 0, 1)\n\n\tif (maxIndex < minIndex) println(maxIndex + numberOfSoldiers - 1 - minIndex)\n\telse println(maxIndex + numberOfSoldiers - minIndex - 2)\n}"}, {"source_code": "object Solution144A extends App {\n\n def solution() {\n val n = _int\n val arr = 1.to(n).map(_ => _int)\n val mm = arr.foldLeft((100000, 0))((memo, h) => {\n (scala.math.min(h, memo._1), scala.math.max(h, memo._2))\n })\n //println(mm)\n val fioMax = arr.indexOf(mm._2)\n val lioMin = arr.lastIndexOf(mm._1)\n// println(fioMax)\n// println(lioMin)\n val adj = if (fioMax > lioMin) 1 else 0\n val res = fioMax + (arr.size - 1 - lioMin) - adj\n println(res)\n }\n\n //////////////////////////////////////////////////\n import java.util.Scanner\n val SC: Scanner = new Scanner(System.in)\n def _line: String = SC.nextLine\n def _int: Int = SC.nextInt\n def _long: Long = SC.nextLong\n def _string: String = SC.next\n solution()\n}"}, {"source_code": "object P144A extends App {\n readLine\n val soldiers = readLine.split(\" \").map(_.toInt).zipWithIndex\n val max = soldiers.maxBy(_._1)\n var min = soldiers.min\n min = soldiers.reverse.dropWhile(_._1 != min._1).head\n print(max._2 + soldiers.length - 1 - min._2 - (if (max._2 > min._2) 1 else 0))\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val max = data.max\n val min = data.min\n val indexMax = data.indexOf(max)\n val indexMin = data.lastIndexOf(min)\n if (indexMax < indexMin)\n println(data.length + indexMax - indexMin - 1)\n else\n println(data.length + indexMax - indexMin - 2)\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt\n val a = readLine.split(\" \").map(i => i.toInt)\n \n val max = a.indexOf(a.max)\n val min = a.lastIndexOf(a.min)\n \n var s = if (max > min) -1 else 0\n println (s + max + (n - 1 - min))\n }\n} "}, {"source_code": "import scala.collection.JavaConversions._\nimport scala.collection.mutable.ArraySeq\n\nobject Codeforces144A {\n def main(args: Array[String]) {\n val elemCount = scala.io.StdIn.readLine().toInt\n val elems = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n var max = elems(0)\n var min = elems(0)\n var maxIndex = 0\n var minIndex = 0\n var seconds = 0\n for (i <- 0 until elemCount) {\n if (elems(i) <= min) { // choose the rightmost minimum element\n min = elems(i)\n minIndex = i\n }\n if (elems(i) > max) {\n max = elems(i)\n maxIndex = i\n }\n }\n seconds += maxIndex\n if (minIndex > maxIndex) {\n seconds += elemCount - 1 - minIndex\n }\n if (minIndex < maxIndex) {\n seconds += elemCount - 1 - (minIndex + 1)\n }\n println(seconds)\n }\n}"}, {"source_code": "object A144 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n val max = input.max\n val min = input.min\n\n var i = 0\n while(i < n && input(i) != max) {\n i += 1\n }\n var res = i\n while(i > 0) {\n val temp = input(i)\n input(i) = input(i-1)\n input(i-1) = temp\n\n i -= 1\n }\n\n i = n-1\n while(i > 0 && input(i) != min) {\n i -= 1\n }\n res += (n-i-1)\n println(res)\n }\n}"}], "negative_code": [{"source_code": "object One44A extends App {\n\timport java.io.PrintWriter\n\timport java.util.Scanner\n\tval in = new Scanner(System.in)\n\tval out = new PrintWriter(System.out)\n\timport in._\n\timport out._\n\tval n = nextInt\n\tvar min = (-1, -1)\n\tvar max = (-1, -1)\n\t(0 until n).foreach { i =>\n\t\tval num = nextInt\n\t\tif (min._1 >= num || min._1 == -1) min = (num, i + 1)\n\t\tif (max._1 < num || max._1 == -1) max = (num, i + 1)\n\t}\n\tprintln(n - min._2 + max._2 - 1)\n\tin.close\n\tout.close\n}"}, {"source_code": "object P144A extends App {\n readLine\n val soldiers = readLine.split(\" \").map(_.toInt).zipWithIndex\n val max = soldiers.maxBy(_._1)\n val min = soldiers.min\n print(max._2 + soldiers.length - 1 - soldiers.reverse.dropWhile(_._1 != min._1).head._2 -\n (if (max._2 > min._2) 1 else 0))\n}"}, {"source_code": "object P144A extends App {\n readLine\n val soldiers = readLine.split(\" \").map(_.toInt).zipWithIndex\n print(soldiers.maxBy(_._1)._2 + soldiers.length - 1 - soldiers.minBy(_._1)._2)\n}"}, {"source_code": "object P144A extends App {\n readLine\n val soldiers = readLine.split(\" \").map(_.toInt).zipWithIndex\n val max = soldiers.maxBy(_._1)\n val min = soldiers.min\n print(max._2 + soldiers.length - 1 - soldiers.reverse.dropWhile(_._1 != min._1).head._2 -\n (if (max._2 > min._2) -1 else 0))\n}"}], "src_uid": "ef9ff63d225811868e786e800ce49c92"} {"source_code": "import java.util\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val as, bs = Array.fill(n){ readLine.toCharArray }\n\n val isDiff = Array.ofDim[Boolean](n)\n var i = 0\n var first = -1\n while (i < n) {\n if (!util.Arrays.equals(as(i), bs(i))) {\n first = i\n isDiff(i) = true\n }\n i += 1\n }\n\n val aFirst = as(first)\n val bFirst = bs(first)\n var lMax = 0\n while (aFirst(lMax) == bFirst(lMax)) lMax += 1\n var rMin = aFirst.length - 1\n while (aFirst(rMin) == bFirst(rMin)) rMin -= 1\n var lFirst = 0\n var rFirst = aFirst.length - 1\n var s = as(first)\n var t = bs(first)\n val sMin = s.slice(lMax, rMin + 1)\n val tMin = t.slice(lMax, rMin + 1)\n\n def patch(x: Array[Char], y: Array[Char], pos: Int): Array[Char] = {\n val ss = x.clone()\n var i = 0\n while (i < y.length) {\n ss(pos + i) = y(i)\n i += 1\n }\n ss\n }\n\n def kmp(t: Array[Char], p: Array[Char]): Int = {\n val m = p.length\n val next = Array.fill(m + 1)(0)\n var k = 0\n var j = 1\n while (j < m) {\n while (k > 0 && p(k) != p(j)) k = next(k)\n if (p(k) == p(j)) k += 1\n next(j + 1) = k\n j += 1\n }\n\n var pos = -1\n j = 0\n var i = 0\n while (i < t.length && pos < 0) {\n while (j > 0 && p(j) != t(i)) j = next(j)\n if (p(j) == t(i)) j += 1\n if (j == m) {\n pos = i - m + 1\n j = next(j)\n }\n i += 1\n }\n\n pos\n }\n\n for (i <- 0 until n) {\n if (isDiff(i)) {\n val a = as(i)\n val b = bs(i)\n val pos = kmp(a, s)\n val mod = if (pos < 0) a\n else patch(a, t, pos)\n if (!util.Arrays.equals(mod, b)) {\n var l = 0\n while (a(l) == b(l)) l += 1\n var r = a.length - 1\n while (a(r) == b(r)) r -= 1\n if (r - l == rMin - lMax /* && util.Arrays.equals(a.slice(l, r + 1), sMin) && util.Arrays.equals(b.slice(l, r + 1), tMin)*/) {\n var ll = lMax\n while (l > 0 && ll > lFirst && a(l - 1) == aFirst(ll - 1) && b(l - 1) == bFirst(ll - 1)) {\n l -= 1\n ll -= 1\n }\n var rr = rMin\n while (r < a.length - 1 && rr < rFirst && a(r + 1) == aFirst(rr + 1) && b(r + 1) == bFirst(rr + 1)) {\n r += 1\n rr += 1\n }\n lFirst = ll\n rFirst = rr\n if (rr - ll + 1 != s.length) {\n s = aFirst.slice(ll, rr + 1)\n t = bFirst.slice(ll, rr + 1)\n }\n }\n }\n }\n }\n\n var ok = true\n for (i <- 0 until n) {\n if (ok) {\n val pos = kmp(as(i), s)\n val mod = if (pos < 0) as(i)\n else patch(as(i), t, pos)\n if (!util.Arrays.equals(mod, bs(i))) ok = false\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n if (ok) {\n println(\"YES\")\n println(s.mkString)\n println(t.mkString)\n } else println(\"NO\")\n Console.flush()\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A, B = Array.ofDim[String](N)\n rep(N) { i =>\n A(i) = ns()\n }\n rep(N) { i =>\n B(i) = ns()\n }\n\n /**\n * [l, r)\n */\n case class Replace(l: Int, r: Int, i: Int)\n\n def calc(i: Int): Option[Replace] = {\n var l, r = -1\n rep(A(i).length) { j =>\n if (A(i).charAt(j) != B(i).charAt(j)) {\n if (l == -1) l = j\n r = j\n }\n }\n if (r == -1) None\n else Some(Replace(l, r + 1, i))\n }\n\n def test(s: String, t: String, kmp: KMP): Boolean = {\n 0 until N forall { i =>\n val ix = kmp.findFirst(A(i))\n if (ix == -1)\n A(i) == B(i)\n else {\n var ok = true\n rep(A(i).length) { j =>\n if (j < ix || j >= ix + t.length) {\n ok &&= B(i).charAt(j) == A(i).charAt(j)\n } else {\n ok &&= B(i).charAt(j) == t(j - ix)\n }\n }\n ok\n }\n }\n }\n\n val diffs = map(N)(calc).flatten\n var lastReplace: Option[Replace] = None\n var cntL, cntR = -1 // 左右の同じものが続く回数\n diffs.foreach { replace =>\n val l = replace.l\n val r = replace.r\n val i = replace.i\n // cntL, cntRはできるだけ広くとるほうがSameとバッティングしにくいので真に有利になる\n lastReplace match {\n case None =>\n cntL = l\n cntR = A(i).length - r\n\n case Some(last: Replace) =>\n var j = 1\n val A0 = A(i)\n val A1 = A(last.i)\n while(l - j >= 0 && j <= cntL && A0.charAt(l - j) == A1.charAt(last.l - j)) {\n j += 1\n }\n cntL = j - 1\n\n j = 0\n while(r + j < A0.length && j < cntR && A0.charAt(r + j) == A1.charAt(last.r + j)) {\n j += 1\n }\n cntR = j\n }\n\n lastReplace = Some(replace)\n }\n\n val Some(last: Replace) = lastReplace\n val s = A(last.i).substring(last.l - cntL, last.r + cntR)\n val t = B(last.i).substring(last.l - cntL, last.r + cntR)\n\n if (!test(s, t, new KMP(s))) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n out.println(s)\n out.println(t)\n }\n }\n\n class KMP(word: String) {\n val kmp: Array[Int] = Array.ofDim[Int](word.length + 1)\n 2 to word.length foreach { i =>\n var j = kmp(i - 1)\n var continues = true\n while(continues) {\n if (word(j) == word(i - 1)) {\n j += 1\n continues = false\n } else if (j == 0) continues = false\n else j = kmp(j)\n }\n kmp(i) = j\n }\n\n def findFirst(text: String): Int = {\n var j = 0\n rep(text.length) { i =>\n var continues = true\n while(continues) {\n if (word(j) == text(i)) {\n j += 1\n continues = false\n } else if (j == 0) continues = false\n else j = kmp(j)\n }\n if (j == word.length) return i - word.length + 1\n }\n -1\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import java.util\n\nimport scala.collection.mutable\n\n// https://codeforces.com/contest/1055/problem/D\nobject DAhoCorasic extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val as, bs = Array.fill(n){ readLine.toCharArray }\n\n val isDiff = Array.ofDim[Boolean](n)\n var i = 0\n var first = -1\n while (i < n) {\n if (!util.Arrays.equals(as(i), bs(i))) {\n first = i\n isDiff(i) = true\n }\n i += 1\n }\n\n val aFirst = as(first)\n val bFirst = bs(first)\n var lMax = 0\n while (aFirst(lMax) == bFirst(lMax)) lMax += 1\n var rMin = aFirst.length - 1\n while (aFirst(rMin) == bFirst(rMin)) rMin -= 1\n var lFirst = 0\n var rFirst = aFirst.length - 1\n var s = as(first)\n var t = bs(first)\n var ahoCorasic = AhoCorasic(s)\n val sMin = s.slice(lMax, rMin + 1)\n val tMin = t.slice(lMax, rMin + 1)\n\n def patch(x: Array[Char], y: Array[Char], pos: Int): Array[Char] = {\n val ss = x.clone()\n var i = 0\n while (i < y.length) {\n ss(pos + i) = y(i)\n i += 1\n }\n ss\n }\n\n for (i <- 0 until n) {\n if (isDiff(i)) {\n val a = as(i)\n val b = bs(i)\n val pos = ahoCorasic.findIn(a) - s.length + 1\n val mod = if (pos < 0) a\n else patch(a, t, pos)\n if (!util.Arrays.equals(mod, b)) {\n var l = 0\n while (a(l) == b(l)) l += 1\n var r = a.length - 1\n while (a(r) == b(r)) r -= 1\n if (r - l == rMin - lMax /* && util.Arrays.equals(a.slice(l, r + 1), sMin) && util.Arrays.equals(b.slice(l, r + 1), tMin)*/) {\n var ll = lMax\n while (l > 0 && ll > lFirst && a(l - 1) == aFirst(ll - 1) && b(l - 1) == bFirst(ll - 1)) {\n l -= 1\n ll -= 1\n }\n var rr = rMin\n while (r < a.length - 1 && rr < rFirst && a(r + 1) == aFirst(rr + 1) && b(r + 1) == bFirst(rr + 1)) {\n r += 1\n rr += 1\n }\n lFirst = ll\n rFirst = rr\n if (rr - ll + 1 != s.length) {\n s = aFirst.slice(ll, rr + 1)\n t = bFirst.slice(ll, rr + 1)\n ahoCorasic = AhoCorasic(s)\n }\n }\n }\n }\n }\n\n var ok = true\n for (i <- 0 until n) {\n if (ok) {\n val pos = ahoCorasic.findIn(as(i)) - s.length + 1\n val mod = if (pos < 0) as(i)\n else patch(as(i), t, pos)\n if (!util.Arrays.equals(mod, bs(i))) ok = false\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n if (ok) {\n println(\"YES\")\n println(s.mkString)\n println(t.mkString)\n } else println(\"NO\")\n Console.flush()\n\n import AhoCorasic._\n\n class AhoCorasic private(private val trieRoot: TrieNode) {\n\n def newMatcher: Matcher = new Matcher\n\n def findIn(t: Array[Char]): Int = {\n var currentNode = trieRoot\n var i = 0\n do {\n currentNode = currentNode.children(t(i) - 'a')\n i += 1\n } while (currentNode.matchFor < 0 && i < t.length)\n if (currentNode.matchFor == 0) i - 1 else -1\n }\n\n class Matcher private[AhoCorasic] () {\n\n private var currentNode = trieRoot\n\n def apply(rawCh: Byte): Int = {\n val ch = java.lang.Byte.toUnsignedInt(rawCh)\n currentNode = currentNode.children(ch)\n currentNode.matchFor\n }\n }\n\n }\n\n object AhoCorasic {\n\n private final val AlphabetSize = 'z' - 'a' + 1\n\n private class TrieNode {\n val children: Array[TrieNode] = Array.ofDim(AlphabetSize)\n var matchFor: Int = -1\n def hasChildFor(ch: Int): Boolean = children(ch) != null\n }\n\n def apply(searchStrings: Array[Char]*): AhoCorasic = {\n\n val trieRoot = buildTrie(searchStrings)\n\n linkSuffixes(trieRoot)\n\n new AhoCorasic(trieRoot)\n }\n\n private def buildTrie(searchStrings: Seq[Array[Char]]): TrieNode = {\n\n val trieRoot = new TrieNode\n\n for (stringId <- searchStrings.indices) {\n val str = searchStrings(stringId)\n var currentNode = trieRoot\n for (ch0 <- str) {\n val ch = ch0 - 'a'\n if (!currentNode.hasChildFor(ch)) {\n currentNode.children(ch) = new TrieNode\n }\n currentNode = currentNode.children(ch)\n }\n currentNode.matchFor = stringId\n }\n trieRoot\n }\n\n private def linkSuffixes(trieRoot: TrieNode): Unit = {\n\n val queue = mutable.Queue(trieRoot)\n val suffixLinks = mutable.AnyRefMap.empty[TrieNode, TrieNode]\n\n while (queue.nonEmpty) {\n val v = queue.dequeue()\n val u = suffixLinks.getOrElse(v, v)\n if (v.matchFor == -1) v.matchFor = u.matchFor\n for (ch <- 0 until AlphabetSize) {\n if (v.hasChildFor(ch)) {\n suffixLinks(v.children(ch)) = if (suffixLinks.contains(v) && u.hasChildFor(ch)) u.children(ch) else trieRoot\n queue += v.children(ch)\n } else {\n v.children(ch) = if (u.hasChildFor(ch)) u.children(ch) else trieRoot\n }\n }\n }\n }\n\n }\n\n\n}\n"}, {"source_code": "import java.util\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\n// https://codeforces.com/contest/1055/problem/D\nobject DAhoCorasic extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val as, bs = Array.fill(n){ readLine.toCharArray.map(c => (c - 'a').toByte) }\n\n val isDiff = Array.ofDim[Boolean](n)\n var i = 0\n var first = -1\n while (i < n) {\n if (!util.Arrays.equals(as(i), bs(i))) {\n first = i\n isDiff(i) = true\n }\n i += 1\n }\n\n val aFirst = as(first)\n val bFirst = bs(first)\n var lMax = 0\n while (aFirst(lMax) == bFirst(lMax)) lMax += 1\n var rMin = aFirst.length - 1\n while (aFirst(rMin) == bFirst(rMin)) rMin -= 1\n var lFirst = 0\n var rFirst = aFirst.length - 1\n var s = as(first)\n var t = bs(first)\n var ahoCorasic = AhoCorasic(s)\n val sMin = s.slice(lMax, rMin + 1)\n val tMin = t.slice(lMax, rMin + 1)\n\n def patch(x: Array[Byte], y: Array[Byte], pos: Int): Array[Byte] = {\n val ss = x.clone()\n var i = 0\n while (i < y.length) {\n ss(pos + i) = y(i)\n i += 1\n }\n ss\n }\n\n for (i <- 0 until n) {\n if (isDiff(i)) {\n val a = as(i)\n val b = bs(i)\n val pos = ahoCorasic.findIn(a) - s.length + 1\n val mod = if (pos < 0) a\n else patch(a, t, pos)\n if (!util.Arrays.equals(mod, b)) {\n var l = 0\n while (a(l) == b(l)) l += 1\n var r = a.length - 1\n while (a(r) == b(r)) r -= 1\n if (r - l == rMin - lMax /* && util.Arrays.equals(a.slice(l, r + 1), sMin) && util.Arrays.equals(b.slice(l, r + 1), tMin)*/) {\n var ll = lMax\n while (l > 0 && ll > lFirst && a(l - 1) == aFirst(ll - 1) && b(l - 1) == bFirst(ll - 1)) {\n l -= 1\n ll -= 1\n }\n var rr = rMin\n while (r < a.length - 1 && rr < rFirst && a(r + 1) == aFirst(rr + 1) && b(r + 1) == bFirst(rr + 1)) {\n r += 1\n rr += 1\n }\n lFirst = ll\n rFirst = rr\n if (rr - ll + 1 != s.length) {\n s = aFirst.slice(ll, rr + 1)\n t = bFirst.slice(ll, rr + 1)\n ahoCorasic = AhoCorasic(s)\n }\n }\n }\n }\n }\n\n var ok = true\n for (i <- 0 until n) {\n if (ok) {\n val pos = ahoCorasic.findIn(as(i)) - s.length + 1\n val mod = if (pos < 0) as(i)\n else patch(as(i), t, pos)\n if (!util.Arrays.equals(mod, bs(i))) ok = false\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n if (ok) {\n println(\"YES\")\n println(s.map(c => (c + 'a').toChar).mkString)\n println(t.map(c => (c + 'a').toChar).mkString)\n } else println(\"NO\")\n Console.flush()\n\n import AhoCorasic._\n\n class AhoCorasic private(\n private[AhoCorasic] val jumpTable: Array[Int],\n private[AhoCorasic] val matchFor: Array[Int]) {\n\n def findIn(t: Array[Byte]): Int = {\n var currentPosition = 0\n var i = 0\n do {\n currentPosition = jumpTable(currentPosition * AlphabetSize + t(i))\n i += 1\n } while (matchFor(currentPosition) < 0 && i < t.length)\n if (matchFor(currentPosition) == 0) i - 1 else -1\n }\n\n def newMatcher: Matcher = new Matcher\n\n class Matcher private[AhoCorasic]() {\n\n private var currentPosition = 0\n\n def apply(ch: Byte): Int = {\n currentPosition = jumpTable(currentPosition * AlphabetSize + ch)\n matchFor(currentPosition)\n }\n }\n\n }\n\n object AhoCorasic {\n\n private final val AlphabetSize = 26\n\n def apply(searchStrings: Array[Byte]*): AhoCorasic = {\n\n val (jumpTable, matchFor) = buildJumpTable(searchStrings)\n\n linkSuffixes(jumpTable, matchFor)\n\n new AhoCorasic(jumpTable, matchFor)\n }\n\n private def buildJumpTable(searchStrings: Seq[Array[Byte]]): (Array[Int], Array[Int]) = {\n\n val emptyJumpTableSegment = Array.fill(AlphabetSize)(-1)\n val jumpTableBuilder = ArrayBuffer(emptyJumpTableSegment: _*)\n val matchForBuilder = ArrayBuffer(-1)\n\n for (stringId <- searchStrings.indices) {\n val str = searchStrings(stringId)\n var currentPosition = 0\n for (ch <- str) {\n val next = currentPosition * AlphabetSize + ch\n if (jumpTableBuilder(next) == -1) {\n jumpTableBuilder(next) = matchForBuilder.size\n jumpTableBuilder ++= emptyJumpTableSegment\n matchForBuilder += -1\n }\n currentPosition = jumpTableBuilder(next)\n }\n matchForBuilder(currentPosition) = stringId\n }\n\n (jumpTableBuilder.toArray, matchForBuilder.toArray)\n }\n\n private def linkSuffixes(jumpTable: Array[Int], matchFor: Array[Int]): Unit = {\n\n val queue = mutable.Queue(0)\n val suffixLinks = Array.fill(matchFor.length)(-1)\n\n while (queue.nonEmpty) {\n val v = queue.dequeue()\n val u = if (v == 0) 0 else suffixLinks(v)\n if (matchFor(v) == -1) matchFor(v) = matchFor(u)\n for (ch <- 0 until AlphabetSize) {\n val vIndex = v * AlphabetSize + ch\n val uIndex = u * AlphabetSize + ch\n if (jumpTable(vIndex) != -1) {\n suffixLinks(jumpTable(vIndex)) = if (v > 0 && jumpTable(uIndex) != -1) jumpTable(uIndex) else 0\n queue += jumpTable(vIndex)\n } else {\n jumpTable(vIndex) = if (jumpTable(uIndex) != -1) jumpTable(uIndex) else 0\n }\n }\n }\n }\n\n }\n\n}\n"}, {"source_code": "import java.util\n\nimport scala.collection.mutable\n\n// https://codeforces.com/contest/1055/problem/D\nobject DAhoCorasic extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val as, bs = Array.fill(n){ readLine.toCharArray.map(c => (c - 'a').toByte) }\n\n val isDiff = Array.ofDim[Boolean](n)\n var i = 0\n var first = -1\n while (i < n) {\n if (!util.Arrays.equals(as(i), bs(i))) {\n first = i\n isDiff(i) = true\n }\n i += 1\n }\n\n val aFirst = as(first)\n val bFirst = bs(first)\n var lMax = 0\n while (aFirst(lMax) == bFirst(lMax)) lMax += 1\n var rMin = aFirst.length - 1\n while (aFirst(rMin) == bFirst(rMin)) rMin -= 1\n var lFirst = 0\n var rFirst = aFirst.length - 1\n var s = as(first)\n var t = bs(first)\n var ahoCorasic = AhoCorasic(s)\n val sMin = s.slice(lMax, rMin + 1)\n val tMin = t.slice(lMax, rMin + 1)\n\n def patch(x: Array[Byte], y: Array[Byte], pos: Int): Array[Byte] = {\n val ss = x.clone()\n var i = 0\n while (i < y.length) {\n ss(pos + i) = y(i)\n i += 1\n }\n ss\n }\n\n for (i <- 0 until n) {\n if (isDiff(i)) {\n val a = as(i)\n val b = bs(i)\n val pos = ahoCorasic.findIn(a) - s.length + 1\n val mod = if (pos < 0) a\n else patch(a, t, pos)\n if (!util.Arrays.equals(mod, b)) {\n var l = 0\n while (a(l) == b(l)) l += 1\n var r = a.length - 1\n while (a(r) == b(r)) r -= 1\n if (r - l == rMin - lMax /* && util.Arrays.equals(a.slice(l, r + 1), sMin) && util.Arrays.equals(b.slice(l, r + 1), tMin)*/) {\n var ll = lMax\n while (l > 0 && ll > lFirst && a(l - 1) == aFirst(ll - 1) && b(l - 1) == bFirst(ll - 1)) {\n l -= 1\n ll -= 1\n }\n var rr = rMin\n while (r < a.length - 1 && rr < rFirst && a(r + 1) == aFirst(rr + 1) && b(r + 1) == bFirst(rr + 1)) {\n r += 1\n rr += 1\n }\n lFirst = ll\n rFirst = rr\n if (rr - ll + 1 != s.length) {\n s = aFirst.slice(ll, rr + 1)\n t = bFirst.slice(ll, rr + 1)\n ahoCorasic = AhoCorasic(s)\n }\n }\n }\n }\n }\n\n var ok = true\n for (i <- 0 until n) {\n if (ok) {\n val pos = ahoCorasic.findIn(as(i)) - s.length + 1\n val mod = if (pos < 0) as(i)\n else patch(as(i), t, pos)\n if (!util.Arrays.equals(mod, bs(i))) ok = false\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n if (ok) {\n println(\"YES\")\n println(s.map(c => (c + 'a').toChar).mkString)\n println(t.map(c => (c + 'a').toChar).mkString)\n } else println(\"NO\")\n Console.flush()\n\n import AhoCorasic._\n\n class AhoCorasic private(private val trieRoot: TrieNode) {\n\n def newMatcher: Matcher = new Matcher\n\n def findIn(t: Array[Byte]): Int = {\n var currentNode = trieRoot\n var i = 0\n do {\n currentNode = currentNode.children(t(i))\n i += 1\n } while (currentNode.matchFor < 0 && i < t.length)\n if (currentNode.matchFor == 0) i - 1 else -1\n }\n\n class Matcher private[AhoCorasic] () {\n\n private var currentNode = trieRoot\n\n def apply(rawCh: Byte): Int = {\n val ch = java.lang.Byte.toUnsignedInt(rawCh)\n currentNode = currentNode.children(ch)\n currentNode.matchFor\n }\n }\n\n }\n\n object AhoCorasic {\n\n private final val AlphabetSize = 'z' - 'a' + 1\n\n private class TrieNode {\n val children: Array[TrieNode] = Array.ofDim(AlphabetSize)\n var matchFor: Int = -1\n def hasChildFor(ch: Int): Boolean = children(ch) != null\n }\n\n def apply(searchStrings: Array[Byte]*): AhoCorasic = {\n\n val trieRoot = buildTrie(searchStrings)\n\n linkSuffixes(trieRoot)\n\n new AhoCorasic(trieRoot)\n }\n\n private def buildTrie(searchStrings: Seq[Array[Byte]]): TrieNode = {\n\n val trieRoot = new TrieNode\n\n for (stringId <- searchStrings.indices) {\n val str = searchStrings(stringId)\n var currentNode = trieRoot\n for (ch0 <- str) {\n val ch = ch0\n if (!currentNode.hasChildFor(ch)) {\n currentNode.children(ch) = new TrieNode\n }\n currentNode = currentNode.children(ch)\n }\n currentNode.matchFor = stringId\n }\n trieRoot\n }\n\n private def linkSuffixes(trieRoot: TrieNode): Unit = {\n\n val queue = mutable.Queue(trieRoot)\n val suffixLinks = mutable.AnyRefMap.empty[TrieNode, TrieNode]\n\n while (queue.nonEmpty) {\n val v = queue.dequeue()\n val u = suffixLinks.getOrElse(v, v)\n if (v.matchFor == -1) v.matchFor = u.matchFor\n for (ch <- 0 until AlphabetSize) {\n if (v.hasChildFor(ch)) {\n suffixLinks(v.children(ch)) = if (suffixLinks.contains(v) && u.hasChildFor(ch)) u.children(ch) else trieRoot\n queue += v.children(ch)\n } else {\n v.children(ch) = if (u.hasChildFor(ch)) u.children(ch) else trieRoot\n }\n }\n }\n }\n\n }\n\n}\n"}, {"source_code": "import java.util\n\n// https://codeforces.com/contest/1055/problem/D\nobject DKmp extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val as, bs = Array.fill(n){ readLine.toCharArray }\n\n val isDiff = Array.ofDim[Boolean](n)\n var i = 0\n var first = -1\n while (i < n) {\n if (!util.Arrays.equals(as(i), bs(i))) {\n first = i\n isDiff(i) = true\n }\n i += 1\n }\n\n val aFirst = as(first)\n val bFirst = bs(first)\n var lMax = 0\n while (aFirst(lMax) == bFirst(lMax)) lMax += 1\n var rMin = aFirst.length - 1\n while (aFirst(rMin) == bFirst(rMin)) rMin -= 1\n var lFirst = 0\n var rFirst = aFirst.length - 1\n var s = as(first)\n var t = bs(first)\n var kmpNext = kmpPattern(s)\n val sMin = s.slice(lMax, rMin + 1)\n val tMin = t.slice(lMax, rMin + 1)\n\n def patch(x: Array[Char], y: Array[Char], pos: Int): Array[Char] = {\n val ss = x.clone()\n var i = 0\n while (i < y.length) {\n ss(pos + i) = y(i)\n i += 1\n }\n ss\n }\n\n def kmpPattern(p: Array[Char]): Array[Int] = {\n val m = p.length\n val next = Array.fill(m + 1)(0)\n var k = 0\n var j = 1\n while (j < m) {\n while (k > 0 && p(k) != p(j)) k = next(k)\n if (p(k) == p(j)) k += 1\n next(j + 1) = k\n j += 1\n }\n next\n }\n\n def kmp(t: Array[Char], p: Array[Char], next: Array[Int]): Int = {\n val m = p.length\n\n var pos = -1\n var j = 0\n var i = 0\n while (i < t.length && pos < 0) {\n while (j > 0 && p(j) != t(i)) j = next(j)\n if (p(j) == t(i)) j += 1\n if (j == m) {\n pos = i - m + 1\n j = next(j)\n }\n i += 1\n }\n\n pos\n }\n\n for (i <- 0 until n) {\n if (isDiff(i)) {\n val a = as(i)\n val b = bs(i)\n val pos = kmp(a, s, kmpNext)\n val mod = if (pos < 0) a\n else patch(a, t, pos)\n if (!util.Arrays.equals(mod, b)) {\n var l = 0\n while (a(l) == b(l)) l += 1\n var r = a.length - 1\n while (a(r) == b(r)) r -= 1\n if (r - l == rMin - lMax /* && util.Arrays.equals(a.slice(l, r + 1), sMin) && util.Arrays.equals(b.slice(l, r + 1), tMin)*/) {\n var ll = lMax\n while (l > 0 && ll > lFirst && a(l - 1) == aFirst(ll - 1) && b(l - 1) == bFirst(ll - 1)) {\n l -= 1\n ll -= 1\n }\n var rr = rMin\n while (r < a.length - 1 && rr < rFirst && a(r + 1) == aFirst(rr + 1) && b(r + 1) == bFirst(rr + 1)) {\n r += 1\n rr += 1\n }\n lFirst = ll\n rFirst = rr\n if (rr - ll + 1 != s.length) {\n s = aFirst.slice(ll, rr + 1)\n t = bFirst.slice(ll, rr + 1)\n kmpNext = kmpPattern(s)\n }\n }\n }\n }\n }\n\n var ok = true\n for (i <- 0 until n) {\n if (ok) {\n val pos = kmp(as(i), s, kmpNext)\n val mod = if (pos < 0) as(i)\n else patch(as(i), t, pos)\n if (!util.Arrays.equals(mod, bs(i))) ok = false\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n if (ok) {\n println(\"YES\")\n println(s.mkString)\n println(t.mkString)\n } else println(\"NO\")\n Console.flush()\n}\n"}], "negative_code": [{"source_code": "object Main {\n import java.io.PrintStream\n\n def main(args: Array[String]): Unit = {\n val s = new Main()\n val ps = new PrintStream(Console.out)\n Console.withOut(ps) {\n s.solve()\n }\n ps.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n import scala.Console\n\n val MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A, B = Array.ofDim[String](N)\n rep(N) { i =>\n A(i) = ns()\n }\n rep(N) { i =>\n B(i) = ns()\n }\n\n sealed trait Diff\n case class Never() extends Diff\n case class Same() extends Diff\n case class One(l: Int, r: Int) extends Diff\n\n def calc(i: Int): Diff = {\n var state = 0\n var ok = true\n var l, r = -1\n rep(N) { j =>\n state match {\n case 0 =>\n if (A(i)(j) != B(i)(j)) {\n l = j\n state = 1\n }\n case 1 =>\n if (A(i)(j) == B(i)(j)) {\n r = j\n state = 2\n }\n\n case 2 =>\n if (A(i)(j) != B(i)(j)) ok = false\n }\n }\n\n if (!ok) Never()\n else if (state == 0) Same()\n else if (state == 1) One(l, A(i).length)\n else One(l, r)\n }\n\n val diffs = map(N)(calc)\n var s: String = \"\"\n var t: String = \"\"\n var ok = true\n rep(N) { i =>\n diffs(i) match {\n case Never() => ok = false\n case Same() =>\n case One(l, r) =>\n val s1 = A(i).substring(l, r)\n val t1 = B(i).substring(l, r)\n if (s.isEmpty) s = s1\n if (t.isEmpty) t = t1\n\n ok &&= s == s1 && t == t1\n }\n }\n\n if (!ok) {\n println(\"NO\")\n } else {\n println(\"YES\")\n println(s)\n println(t)\n }\n\n }\n\n\n class InputReader(reader: BufferedReader) {\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(Console.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A, B = Array.ofDim[String](N)\n rep(N) { i =>\n A(i) = ns()\n }\n rep(N) { i =>\n B(i) = ns()\n }\n\n sealed trait Diff\n case class Never() extends Diff\n case class Same() extends Diff\n case class One(l: Int, r: Int) extends Diff\n\n def calc(i: Int): Diff = {\n var state = 0\n var ok = true\n var l, r = -1\n rep(N) { j =>\n state match {\n case 0 =>\n if (A(i)(j) != B(i)(j)) {\n l = j\n state = 1\n }\n case 1 =>\n if (A(i)(j) == B(i)(j)) {\n r = j\n state = 2\n }\n\n case 2 =>\n if (A(i)(j) != B(i)(j)) ok = false\n }\n }\n\n if (!ok) Never()\n else if (state == 0) Same()\n else if (state == 1) One(l, A(i).length)\n else One(l, r)\n }\n\n val diffs = map(N)(calc)\n var s: String = \"\"\n var t: String = \"\"\n var ok = true\n rep(N) { i =>\n diffs(i) match {\n case Never() => ok = false\n case Same() =>\n case One(l, r) =>\n val s1 = A(i).substring(l, r)\n val t1 = B(i).substring(l, r)\n if (s.isEmpty) s = s1\n if (t.isEmpty) t = t1\n\n ok &&= s == s1 && t == t1\n }\n }\n\n rep(N) { i =>\n if (diffs(i) == Same()) {\n val ix = A(i).indexOf(s)\n ok &&= ix == -1 || {\n B(i).substring(ix, s.length) == t\n }\n }\n }\n\n if (!ok) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n out.println(s)\n out.println(t)\n }\n\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A, B = Array.ofDim[String](N)\n rep(N) { i =>\n A(i) = ns()\n }\n rep(N) { i =>\n B(i) = ns()\n }\n\n sealed trait Diff\n case class Same() extends Diff\n case class Replace(l: Int, r: Int, i: Int) extends Diff\n\n def calc(i: Int): Diff = {\n var l, r = -1\n rep(A(i).length) { j =>\n if (A(i)(j) != B(i)(j)) {\n if (l == -1) l = j\n r = j\n }\n }\n if (r == -1) Same()\n else Replace(l, r + 1, i)\n }\n\n val diffs = map(N)(calc)\n var minS: String = \"\"\n var minT: String = \"\"\n var lastDiff: Option[Replace] = None\n var cntL, cntR = -1 // 左右の同じものが続く回数\n var ok = true\n rep(N) { i =>\n diffs(i) match {\n case Same() =>\n case replace @ Replace(l, r, _) =>\n val s = A(i).substring(l, r)\n val t = B(i).substring(l, r)\n if (minS.isEmpty) minS = s\n if (minT.isEmpty) minT = t\n\n // cntL, cntRはできるだけ広くとるほうがSameとバッティングしにくいので有利になる\n lastDiff match {\n case None =>\n lastDiff = Some(replace)\n cntL = l\n cntR = A(i).length - r\n\n case Some(last: Replace) =>\n var j = 1\n val A0 = A(i)\n val A1 = A(last.i)\n val B0 = B(i)\n val B1 = B(last.i)\n while(l - j >= 0 && j <= cntL && A0(l - j) == A1(last.l - j) && B0(l - j) == B1(last.l - j)) {\n j += 1\n }\n cntL = j - 1\n\n j = 0\n while(r + j < A0.length && j < cntR && A0(r + j) == A1(last.r + j) && B0(r + j) == B1(last.r + j)) {\n j += 1\n }\n cntR = j\n }\n\n lastDiff = Some(replace)\n ok &&= minS == s && minT == t\n }\n }\n\n val Some(last: Replace) = lastDiff\n val s = A(last.i).substring(last.l - cntL, last.r + cntR)\n val t = B(last.i).substring(last.l - cntL, last.r + cntR)\n\n rep(N) { i =>\n if (diffs(i) == Same()) {\n val ix = A(i).indexOf(s)\n ok &&= ix == -1 || {\n B(i).substring(ix, ix + s.length) == t\n }\n }\n }\n\n if (!ok) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n out.println(s)\n out.println(t)\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A, B = Array.ofDim[String](N)\n rep(N) { i =>\n A(i) = ns()\n }\n rep(N) { i =>\n B(i) = ns()\n }\n\n sealed trait Diff\n case class Same() extends Diff\n case class Replace(l: Int, r: Int, i: Int) extends Diff\n\n def calc(i: Int): Diff = {\n var l, r = -1\n rep(A(i).length) { j =>\n if (A(i)(j) != B(i)(j)) {\n if (l == -1) l = j\n r = j\n }\n }\n if (r == -1) Same()\n else Replace(l, r + 1, i)\n }\n\n val diffs = map(N)(calc)\n var minS: String = \"\"\n var minT: String = \"\"\n var lastDiff: Option[Replace] = None\n var cntL, cntR = -1 // 左右の同じものが続く回数\n var ok = true\n rep(N) { i =>\n diffs(i) match {\n case Same() =>\n case replace @ Replace(l, r, _) =>\n val s = A(i).substring(l, r)\n val t = B(i).substring(l, r)\n if (minS.isEmpty) minS = s\n if (minT.isEmpty) minT = t\n\n // cntL, cntRはできるだけ広くとるほうがSameとバッティングしにくいので有利になる\n lastDiff match {\n case None =>\n lastDiff = Some(replace)\n cntL = l\n cntR = A(i).length - r\n\n case Some(last: Replace) =>\n var j = 1\n val A0 = A(i)\n val A1 = A(last.i)\n val B0 = B(i)\n val B1 = B(last.i)\n while(l - j >= 0 && j < cntL && A0(l - j) == A1(last.l - j) && B0(l - j) == B1(last.l - j)) {\n j += 1\n }\n cntL = j - 1\n\n j = 0\n while(r + j < A0.length && j < cntR && A0(r + j) == A1(last.r + j) && B0(r + j) == B1(last.r + j)) {\n j += 1\n }\n cntR = j\n }\n\n lastDiff = Some(replace)\n ok &&= minS == s && minT == t\n }\n }\n\n val Some(last: Replace) = lastDiff\n val s = A(last.i).substring(last.l - cntL, last.r + cntR)\n val t = B(last.i).substring(last.l - cntL, last.r + cntR)\n\n rep(N) { i =>\n if (diffs(i) == Same()) {\n val ix = A(i).indexOf(s)\n ok &&= ix == -1 || {\n B(i).substring(ix, ix + s.length) == t\n }\n }\n }\n\n if (!ok) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n out.println(s)\n out.println(t)\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as, bs = Array.fill(n){ readLine }\n\n var maxD, maxDPos = -1\n\n for (i <- 0 until n) {\n if (as(i) != bs(i)) {\n val a = as(i)\n val b = bs(i)\n var l = 0\n while (a(l) == b(l)) l += 1\n var r = a.length - 1\n while (a(r) == b(r)) r -= 1\n if (r - l > maxD) {\n maxD = r - l\n maxDPos = i\n }\n }\n }\n\n val a = as(maxDPos)\n val b = bs(maxDPos)\n var l = 0\n while (a(l) == b(l)) l += 1\n var r = a.length - 1\n while (a(r) == b(r)) r -= 1\n\n val s = a.substring(l, r + 1)\n val t = b.substring(l, r + 1)\n\n var ok = true\n for (i <- 0 until n) {\n if (ok) {\n val pos = as(i).indexOfSlice(s)\n val mod = if (pos < 0) as(i)\n else as(i).patch(pos, t, t.length)\n if (mod != bs(i)) ok = false\n }\n }\n\n if (ok) {\n println(\"YES\")\n println(s)\n println(t)\n } else println(\"NO\")\n}\n"}], "src_uid": "712b82c305a6bcf2903e9bc0505f090a"} {"source_code": "import java.util.Scanner\n\nimport scala.io.StdIn\n\nobject Atask560 extends App {\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n val x = line.nextInt()\n val y = line.nextInt()\n line = new Scanner(StdIn.readLine())\n val digit = line.next.chars().toArray\n\n var result = 0\n\n for (i <- 0 until x) {\n if (digit(n - 1 - i) == '1' && y != i) {\n digit(n - 1 -i) = '0'\n result += 1\n }\n if (digit(n - 1 - i) == '0' && y == i) {\n digit(n - 1 -i) = '1'\n result += 1\n }\n }\n\n println(result)\n}\n", "positive_code": [{"source_code": "object _1165A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val _, x, y = io.read[Int]\n val num = io.read[String].reverse.padTo(x, '0')\n\n val target = Array.fill(x)('0')\n target(y) = '1'\n\n val ans = num.zip(target).count({case (i, j) => i != j})\n\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Main extends CodeForcesApp {\n\n import annotation._, collection.{mutable, Searching}, util._, control._, math .Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val _, x, y = io.read[Int]\n val num = io.read[String].reverse\n\n val target = Array.fill(x)('0')\n target(y) = '1'\n\n val ans = num.zip(target).count({ case (i, j) => i != j })\n\n io.write(ans)\n }\n}\n\n/** **************************[Ignore Template Below] ****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n\n def apply(io: IO): io.type\n\n def main(args: Array[String]): Unit = this (new IO(System.in, System.out)).close()\n}\n\n/** *********************************[Scala I/O] *********************************************/\n\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while (tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n\n def writeLine(): this.type = {\n printer.println()\n this\n }\n\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\n\nobject IO {\n\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n\n implicit val string: Read[String] = new Read(_.next())\n implicit val int: Read[Int] = string.map(_.toInt)\n implicit val long: Read[Long] = string.map(_.toLong)\n implicit val bigInt: Read[BigInt] = string.map(BigInt(_))\n implicit val double: Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal: Read[BigDecimal] = string.map(BigDecimal(_))\n\n implicit def tuple2[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n\n implicit def tuple3[A: Read, B: Read, C: Read]: Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read]: Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n\n implicit val boolean: Read[Boolean] = string map { s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n\n}"}], "negative_code": [], "src_uid": "075988685fa3f9b20bd215037c504a4f"} {"source_code": "\n/**\n * Created by slie742 on 9/09/2015.\n */\n\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\nimport Math.abs\nimport Math.max\nimport Math.min\n\nobject DividingOrange {\n\n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n\n def readLongs() : Array[Long] =\n readLine.split(' ').map(_.toLong)\n\n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n\n def divideOranges(n: Int, k: Int, as: IndexedSeq[Int]) : List[List[Int]] = {\n def go(rem: List[Int], child: Int, acc: List[List[Int]]) : List[List[Int]] = { \n if (child == k) acc.reverse\n else {\n go(rem.drop(n-1), child + 1,(as(child) :: rem.take(n-1)) :: acc)\n }\n }\n go( ((1 to n*k).toSet[Int] -- as).toList , 0, List())\n }\n\n def main(args: Array[String]) {\n val (n,k) = readTuple()\n val as = readInts()\n println(divideOranges(n,k,as).map(_.mkString(\" \")).mkString(\"\\n\"))\n\n }\n\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P244A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, K = sc.nextInt\n val A = List.fill(K)(sc.nextInt)\n \n def solve(): List[List[Int]] = {\n val segments = List.range(1, N * K + 1)\n val rest = segments.toSet -- A.toSet\n\n @tailrec\n def loop(acc: List[List[Int]], requests: List[Int], rest: List[Int]): List[List[Int]] = {\n if (requests == Nil) acc\n else loop(acc ++ List(requests.head :: rest.take(N - 1)), requests.tail, rest.drop(N - 1))\n }\n\n loop(Nil, A, rest.toList)\n }\n\n solve.foreach { lst =>\n out.println(lst.mkString(\" \"))\n }\n out.close\n}\n"}, {"source_code": "object Apelsin extends App {\n var ss = (Console.readLine.split(\" \")) map (_.toInt)\n val (n,k) = (ss(0), ss(1))\n val aa0 = (Console.readLine.split(\" \")) map (_.toInt)\n val aa = aa0 map (x => x-1)\n val nk = n*k\n var dl = Array.fill(nk)(0)\n \n def iniFill() = {\n for {\n i <- Range(0, k)\n j <- Range(0, n)\n val idx = n*i+j\n } dl(idx) = i\n }\n \n def printOneDol(i:Int) = {\n for {\n j <- Range(0, nk)\n if dl(j) == i\n } print((j+1) + \" \")\n println\n }\n \n def printDl = {\n for {\n i <- Range(0, k)\n } printOneDol(i)\n }\n \n def findI(i:Int):Int = {\n val seq = for {\n ii <- Range(0, nk)\n if dl(ii) == i\n } yield ii\n seq(0)\n }\n \n def fixOne(i:Int, ai:Int) = {\n val idx = findI(i)\n if (ai != idx) {\n dl(idx) = dl(ai)\n dl(ai) = i\n }\n }\n \n def fixAll = {\n for {\n i<- Range(0, k)\n } fixOne(i, aa(i))\n }\n \n iniFill()\n fixAll\n printDl\n}"}, {"source_code": "import java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readLine = reader.readLine\n def readInt = readLine.toInt\n def split = readLine.split(\" \")\n def readInts = split.map(_.toInt)\n\n val Array(n, k) = readInts\n val a = readInts\n def ans = if(n == 1) {\n a.mkString(\" \")\n } else {\n (1 to n * k).filterNot(a.contains).grouped(n - 1).toArray.zip(a).map(x => (x._1 ++ Array(x._2)).mkString(\" \")).mkString(\"\\n\")\n }\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val nk = readLine().split(\" \").map(_.toInt)\n val n = nk(0)\n val k = nk(1)\n val a = readLine().split(\" \").map(_.toInt)\n val s = scala.collection.mutable.Set() ++ (1 to n * k)\n s --= a\n \n if (n == 1) {\n for(i <- 0 until k) println(a(i))\n } else {\n s.grouped(n - 1).zipWithIndex.foreach { t => \n println((t._1 ++ List(a(t._2))).mkString(\" \"))\n } \n }\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt)\n val set = data.toSet\n var j = 0\n\n val res = (0 until k).map{ i =>\n (2 to n).foldLeft(List(data(i))) {\n case(list, _) =>\n j += 1\n while (set.contains(j))\n j += 1\n j :: list\n }\n }\n println(res.map(_.mkString(\" \")).mkString(\"\\n\"))\n}"}], "negative_code": [{"source_code": "import java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readLine = reader.readLine\n def readInt = readLine.toInt\n def split = readLine.split(\" \")\n def readInts = split.map(_.toInt)\n\n val Array(n, k) = readInts\n val a = readInts\n def ans = if(n == 1) {\n (1 to k).mkString(\" \")\n } else {\n (1 to n * k).filterNot(a.contains).grouped(n - 1).toArray.zip(a).map(x => (x._1 ++ Array(x._2)).mkString(\" \")).mkString(\"\\n\")\n }\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n"}], "src_uid": "928f18ee5dbf44364c0d578f4317944c"} {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n def ans = (for (_ <- 1 to readInt) yield if (360 % (180 - readInt) == 0) \"YES\" else \"NO\").mkString(\"\\n\")\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "object main extends App with fastIO {\n \n (1 to nextInt) foreach { (t) => println(if (360 % (180 - nextInt) == 0) \"YES\" else \"NO\") }\n \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "object main extends App with fastIO {\n \n def check(n: Int) = { if (360 % n != 0) 0 else 180 - 360 / n }\n \n (1 to nextInt) foreach { (t) =>\n var f = false\n var angle = nextInt\n for (n <- 1 to 360) \n f = f || check(n) == angle\n println(if (f) \"YES\" else \"NO\") \n }\n \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "object A{\n def main(args:Array[String]){\n val n=readLine.toInt\n\n for(_<-1 to n){\n val a=readLine.toInt\n if(360%(180-a)==0){\n println(\"YES\")\n }else{\n println(\"NO\")\n }\n }\n }\n}\n"}, {"source_code": "object cf165a extends App {\n val t = readLine.toInt\n (1 to t).map { qq =>\n val n = readLine.toInt\n println(if ((3 to 360).filter(i => 180 * (i - 2) == n * i).isEmpty) \"NO\" else \"YES\")\n }\n}"}, {"source_code": "object A {\n\tdef main(args: Array[String]) {\n\t\tval n = readInt()\n\n\t\tfor (i <- 1 to n) {\n\t\t\tval alpha = readInt()\n\t\t\tprintln(if (360 % (180 - alpha) == 0) \"YES\" else \"NO\")\n\t\t}\n\t}\n}\n"}, {"source_code": "object CF270A {\n def main(argv: Array[String]) {\n def judge(n: Int) {\n if (n > 0) {\n if (360 % (180 - readLine.toInt) == 0) println(\"YES\")\n else println(\"NO\")\n judge(n - 1)\n }\n }\n judge(readLine.toInt)\n }\n}"}, {"source_code": "object CF270A {\n\tdef main(argv: Array[String]) {\n\t def judge(n: Int) {\n\t if (n > 0) {\n\t\t if (360 % (180 - readLine.toInt) == 0) println(\"YES\")\n\t\t else println(\"NO\")\n\t\t judge(n - 1)\n\t }\n\t }\n\t judge(readLine.toInt)\n\t}\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _270A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n for (t <- 1 to next.toInt) {\n val a = next.toInt\n if (360 % (180 - a) == 0) println(\"YES\")\n else println(\"NO\")\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val t = in.next().toInt\n Range(0, t).foreach { _ =>\n val a = in.next().toInt\n if (360 % (180 - a) == 0) println(\"YES\")\n else println(\"NO\")\n\n }\n}\n"}, {"source_code": "\nobject Main {\n def main(args : Array[String]) = {\n val t = readLine.toInt\n for(i <- 1 to t) {\n val a = readLine.toInt\n val ans = (3 to 1000).view.map({n => a * n == 180 * (n - 2)}).dropWhile(!_).isEmpty\n if(ans) println(\"NO\") else println(\"YES\")\n }\n }\n}\n"}, {"source_code": "object A270 extends App {\n val k = readLine.toInt\n\n for (a <- 1 to k) {\n val a = readLine.toInt\n var n: Int = 3\n var isSolve = false\n\n if (a < 60) {\n println(\"NO\")\n isSolve = true\n }\n\n while (n < 1000 && !isSolve) {\n if (a * n == (n - 2) * 180) {\n println(\"YES\")\n isSolve = true\n } else {\n n += 1\n }\n }\n if (!isSolve)\n println(\"NO\")\n }\n\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P270A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n def solve(): String = if (360 % (180 - sc.nextInt) == 0) \"YES\"\n else \"NO\"\n\n for (i <- 0 until N)\n out.println(solve)\n out.close\n}\n"}, {"source_code": "object Main extends App {\n\t def judge(n: Int) {\n\t if (n > 0) {\n\t\t if (360 % (180 - readLine.toInt) == 0) println(\"YES\")\n\t\t else println(\"NO\")\n\t\t judge(n - 1)\n\t }\n\t }\n\t judge(readLine.toInt)\n\t}"}, {"source_code": "import java.util._\nimport java.io._\n\nobject A extends App {\n val cin = new Scanner(new BufferedInputStream(System.in))\n for (i <- 0 until cin.nextInt) {\n var tak = false\n val n = cin.nextInt\n for (i <- 3 to 360)\n if (360 % i == 0 && 180 - 360 / i == n) {\n println(\"YES\")\n tak = true\n }\n if (! tak) println(\"NO\")\n }\n}\n"}, {"source_code": "import java.util._\n\nobject Test {\n\n def main(args: Array[String]) {\n val in = new Scanner(System.in)\n var n = in.nextInt\n for (i <- 0 to n - 1) {\n if (check(in.nextInt)) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n }\n \n def check(a: Int): Boolean = {\n val azChange = 180 - a\n val sides = 360 / azChange\n sides * azChange == 360\n }\n \n}"}, {"source_code": "import scala.io.Source\n\nobject test6 extends App {\n val t=readLine.toInt\n for(i<-1 to t){\n val a=readLine.toInt\n println(if(360%(180-a)==0) \"YES\" else \"NO\")\n }\n \n} \n\n\n\n\n"}, {"source_code": "object test6 extends App {\n val t=readInt\n for(i<-1 to t){\n val a=readInt\n println(if(360%(180-a)==0) \"YES\" else \"NO\")\n }\n \n} \n\n\n\n\n"}, {"source_code": "import scala.io.Source\n\nobject test6 extends App {\n val t=readInt\n for(i<-1 to t){\n val a=readInt\n println(if(360%(180-a)==0) \"YES\" else \"NO\")\n }\n \n} \n\n\n\n\n"}, {"source_code": "object Main {\n val angles: Stream[Double] = {\n def angle(n: Int): Stream[Double] = {\n (180.0 * (n - 2) / n) #:: angle(n + 1)\n }\n angle(3)\n }\n\n def main(args: Array[String]) {\n val num = readInt()\n for(_ <- 1 to num) {\n val a = readInt()\n if (angles.takeWhile(_ <= a).filter(_ == a).size == 1) println(\"YES\")\n else println(\"NO\")\n }\n }\n}"}, {"source_code": "\nobject FancyFence extends App {\n\n val t = readInt //num tests\n\n for (i <- Range(0, t)) {\n checkAngle(readDouble)\n }\n\n def checkAngle(angle: Double) {\n var sides = 2 / (1 - (angle / 180))\n if (Math.abs(sides - Math.round(sides)) < 0.000000001) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "object cf165a extends App {\n val t = readLine.toInt\n (1 to t).map { qq =>\n val n = readLine.toInt\n println(if ((3 to 180).filter(i => 180 * (i - 2) == n * i).isEmpty) \"NO\" else \"YES\")\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P270A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val a = Array.fill(N)(sc.nextInt)\n\n def solve(x: Int): String =\n if (x >= 60 && 360 % x == 0) \"YES\"\n else \"NO\"\n\n for (i <- 0 until N)\n out.println(solve(a(i)))\n\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P270A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val a = Array.fill(N)(sc.nextInt)\n\n def solve(x: Int): String =\n if (x >= 60 && (360 % x == 0 || 360 % (180 - x) == 0)) \"YES\"\n else \"NO\"\n\n for (i <- 0 until N)\n out.println(solve(a(i)))\n\n out.close\n}\n"}, {"source_code": "import scala.math.BigDecimal\n\nobject FancyFence extends App {\n\n val t = readInt //num tests\n\n for (i <- Range(0, t)) {\n val angle = BigDecimal(readLine)\n val sides = 2.0 / (1.0 - (angle / 180.0))\n if ((sides - sides.intValue) == 0) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n}\n"}, {"source_code": "import scala.math.BigDecimal\n\nobject FancyFence extends App {\n\n val t = readInt //num tests\n\n for (i <- Range(0, t)) {\n val angle = BigDecimal(readLine)\n val sides = 2.0 / (1.0 - (angle / 180.0))\n println(sides)\n if ((sides - sides.intValue) == 0) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n}\n"}, {"source_code": "import scala.collection.immutable.HashMap\n\nobject FancyFence extends App {\n\n val t = readInt //num tests\n\n var set = Set[Int]()\n var n = 3\n var angle = ((n - 2) * 180) / n\n while (angle < 179) {\n set = set + angle\n n += 1\n angle = ((n - 2) * 180) / n\n }\n\n// println(set)\n\n for (i <- Range(0, t)) {\n val angle = readInt\n val sides = 2.0 / (1.0 - (angle / 180.0))\n if (set.contains(angle)) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n}"}, {"source_code": "import scala.collection.immutable.HashMap\n\nobject FancyFence extends App {\n\n val t = readInt //num tests\n\n var set = Set[Int]()\n var n = 3\n var angle = ((n - 2) * 180) / n\n while (angle < 179) {\n set = set + angle\n n += 1\n angle = ((n - 2) * 180) / n\n }\n \n println(set)\n\n for (i <- Range(0, t)) {\n val angle = readInt\n if (set.contains(angle)) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n}"}, {"source_code": "import scala.collection.immutable.HashMap\n\nobject FancyFence extends App {\n\n val t = readInt //num tests\n\n for (i <- Range(0, t)) {\n val angle = readInt\n val sides = 2.0 / (1.0 - (angle / 180.0))\n if (sides.isWhole()) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n}"}, {"source_code": "object A{\n def main(args:Array[String]){\n val n=readLine.toInt\n\n for(_<-1 to n){\n val a=readLine.toInt\n if(180%(180-a)==0 || 180%a==0){\n println(\"YES\")\n }else{\n println(\"NO\")\n }\n }\n }\n}\n"}, {"source_code": "object A{\n def main(args:Array[String]){\n val n=readLine.toInt\n\n for(_<-1 to n){\n val a=readLine.toInt\n if(180%(180-a)==0){\n println(\"YES\")\n }else{\n println(\"NO\")\n }\n }\n }\n}\n"}], "src_uid": "9037f487a426ead347baa803955b2c00"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(val l: Int, val r: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return (r-l).compareTo(that.r-that.l)\n }\n }\n\n case class node(val l: Int, val r: Int, val c: Char, var d: Boolean, var lc: Char, var mx: Char, var sz: Int){\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n\n\n for (tt <- 1 to t) {\n val n = readInt()\n var ans = 0\n val arr = new Array[Boolean](210)\n for (i <- 1 to n) {\n val k = readInt()\n if (!arr(k+100)) {\n arr(k+100) = true\n ans += 1\n } else if (!arr(-1*k+100)) {\n arr(-1*k+100) = true\n ans += 1\n }\n }\n writer.println(ans)\n\n def check(kk: Long): Boolean = {\n return true\n }\n def bs(st:Long, en:Long): Long = {\n if (en - st <= 1L) {\n if (check(en))\n return en\n else\n return st\n }\n val mid = (st + en) / 2L\n if (check(mid))\n return bs(mid, en)\n else\n return bs(st, mid)\n }\n }\n writer.flush()\n}", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n val have = mutable.Set.empty[Int]\n\n for (a <- as) {\n if (!have(a)) {\n have += a\n } else if (!have(-a)) {\n have += -a\n }\n }\n\n out.println(have.size)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "23ef311011b381d0ca2e84bc861f0a31"} {"source_code": "//package scala_tutorial\n\nimport scala.collection.mutable._\nobject source {\n\tdef main(args : Array[String]) {\n\t\tval Array(n, m) = readLine split \" \" map (_.toInt)\n\t\tvar f = readLine split \" \" map (_.toInt)\n\t\tvar b = readLine split \" \" map (_.toInt)\n\t\t\n\t\tval cnt = new HashMap[Int, Int]().withDefaultValue(0)\n\t\tval pos = new HashMap[Int, Int]().withDefaultValue(-1)\n\t\t\n\t\tvar index = 0\n\t\tfor(index <- 0 until n)\n\t\t{\n\t\t\tcnt(f(index))+=1\n\t\t\tpos(f(index))=index+1\n\t\t}\n\t\tvar ambiguity = false\n\t\tfor(index <- 0 until m)\n\t\t{\n\t\t\tif(cnt(b(index))==0)\n\t\t\t{\n\t\t\t\tprintln(\"Impossible\")\n\t\t\t\tSystem.exit(0)\n\t\t\t}\n\t\t\telse if(cnt(b(index))>1)\n\t\t\t{\n\t\t\t\tambiguity = true\n\t\t\t}\n\t\t}\n\t\tif(ambiguity)\n\t\t{\n\t\t\tprintln(\"Ambiguity\")\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintln(\"Possible\")\n\t\t\tprintln(b map (elem => pos(elem)) mkString \" \")\n\t\t}\n\t}\n}", "positive_code": [{"source_code": "//package scala_tutorial\n\nimport scala.collection.mutable._\nobject source {\n\tdef main(args : Array[String]) {\n\t\tval Array(n, m) = readLine split \" \" map (_.toInt)\n\t\tvar f = readLine split \" \" map (_.toInt)\n\t\tvar b = readLine split \" \" map (_.toInt)\n\t\tvar index = 0\n\t\tvar imap = new HashMap[Int, Int]\n\t\tvar cnt = new HashMap[Int, Int]().withDefaultValue(0)\n\t\tvar ret = 0\n\t\tvar ans = Array.ofDim[Int](m+1)\n\t\tfor (index <- 0 until n)\n\t\t{\n\t\t\tcnt(f(index))+=1\n\t\t\timap(f(index))=index+1\n\t\t}\n\t\tfor (index <- 0 until m)\n\t\t{\n\t\t\tif(imap.contains(b(index))==false)\n\t\t\t{\n\t\t\t\tprintln(\"Impossible\")\n\t\t\t\tSystem.exit(0)\n\t\t\t}\n\t\t\telse \n\t\t\t{\n\t\t\t\tif(cnt(b(index))>1)\n\t\t\t\t{\n\t\t\t\t\tret = 1\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tans(index)=imap(b(index))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(ret == 1)println(\"Ambiguity\")\n\t\telse \n\t\t{\n\t\t\tprintln(\"Possible\")\n\t\t\tfor (index <- 0 until m)\n\t\t\t{\n\t\t\t\tprintf(\"%d \", ans(index))\n\t\t\t}\n\t\t}\n\t\t\n\t}\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val f = in.next().split(' ').map(_.toInt)\n val b = in.next().split(' ').map(_.toInt)\n val map = f.indices.foldLeft(Map.empty[Int, Set[Int]]) {\n case (m, i) =>\n val value = f(i)\n if (m.contains(value))\n m + (value -> (m(value) + (i + 1)))\n else\n m + (value -> Set(i + 1))\n }\n\n\n\n val res = b.foldLeft((0, List.empty[Int])) {\n case ((2, _), _) => (2, Nil)\n case (_, el) if !map.contains(el) => (2, Nil)\n case ((1, _), el) => (1, Nil)\n case (_, el) if map(el).size > 1 => (1, Nil)\n case ((0, list), el) => (0, map(el).head :: list)\n }\n if (res._1 == 0) {\n println(\"Possible\")\n println(res._2.reverse.mkString(\" \"))\n }\n else if (res._1 == 1)\n println(\"Ambiguity\")\n else\n println(\"Impossible\")\n}\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val fs = readInts(n)\n val bs = readInts(m)\n \n val fCnts = Array.fill(n + 1){ 0 }\n for (f <- fs) fCnts(f) += 1\n \n for (b <- bs) if (fCnts(b) == 0) {\n println(\"Impossible\")\n System.exit(0)\n } \n\n for (b <- bs) if (fCnts(b) > 1) {\n println(\"Ambiguity\")\n System.exit(0)\n } \n\n val bToA = fs.zipWithIndex.toMap.mapValues(_ + 1)\n val as = bs.map(bToA)\n \n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n \n println(\"Possible\")\n println(as.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\n\nobject _599B extends CodeForcesApp {\n override type Result = String\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val (n, m) = (nextInt(), nextInt())\n val f = Seq.tabulate(n)(i => nextInt() -> (i+1)).toMultiMap\n val b = Seq.fill(m)(nextInt())\n\n var result: Option[String] = None\n\n val ans = b map {i =>\n f get i match {\n case None | Some(Nil) =>\n result = Some(\"Impossible\")\n 0\n case Some(_ :: _ :: _) =>\n if (!(result contains \"Impossible\")) result = Some(\"Ambiguity\")\n 0\n case Some(x :: Nil) =>\n x\n }\n }\n\n result getOrElse ans.mkString(\"Possible\\n\", \" \", \"\")\n }\n\n implicit class PairsExtensions[A, B](t: Traversable[(A, B)]) {\n def toMultiMap: Map[A, List[B]] = t.groupBy(_._1).mapValues(_.map(_._2).toList)\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _599B extends CodeForcesApp {\n override type Result = String\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val (n, m) = (nextInt(), nextInt())\n val f = Seq.tabulate(n)(i => nextInt() -> (i+1)).toMultiMap withDefaultValue Nil\n val b = Seq.fill(m)(nextInt())\n\n var result: Option[String] = None\n\n val ans = b map f map {\n case Nil => result = Some(\"Impossible\"); 0\n case x :: Nil => x\n case _ =>\n if (!(result contains \"Impossible\")) result = Some(\"Ambiguity\")\n 0\n }\n\n result getOrElse ans.mkString(\"Possible\\n\", \" \", \"\")\n }\n\n implicit class PairsExtensions[A, B](t: Traversable[(A, B)]) {\n def toMultiMap: Map[A, List[B]] = t.groupBy(_._1).mapValues(_.map(_._2).toList)\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val F = readLine().split(\" \").map(_.toInt)\n val B = readLine().split(\" \").map(_.toInt)\n\n val Bcounter = Array.ofDim[Int](n + 1)\n val Fcounter = Array.ofDim[Int](n + 1)\n\n B.foreach(x => Bcounter(x) += 1)\n F.foreach(x => Fcounter(x) += 1)\n\n if (B.exists(x => Fcounter(x) == 0)) {\n println(\"Impossible\")\n } else if (B.exists(x => Fcounter(x) > 1)) {\n println(\"Ambiguity\")\n } else {\n println(\"Possible\")\n val M = F.zipWithIndex.map {\n x => (x._1, x._2 + 1)\n }.toMap\n\n println(B.map(x => M(x)).mkString(\" \"))\n }\n\n}\n"}, {"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val (n,m)=(nextInt,nextInt)\n val ft=Array.fill(n+1)(-1)\n for(i<-0 until n){\n val t=nextInt\n if(ft(t)== -1){\n ft(t)=i+1\n }else{\n ft(t)= -2\n }\n }\n var flag=0\n val a=Array.ofDim[Int](m)\n breakable{\n for(i<-0 until m){\n val b=nextInt\n if(ft(b)== -1){\n flag=2\n break\n }else if(ft(b)== -2&& flag!=2){\n flag=1\n \n }else{\n a(i)=ft(b)\n }\n }\n }\n if(flag==2){\n out.println(\"Impossible\")\n }else if(flag==1){\n out.println(\"Ambiguity\")\n\n }else{\n out.println(\"Possible\")\n for(i<-0 until m-1){\n out.print(a(i)+\" \")\n }\n out.println(a(m-1))\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "negative_code": [{"source_code": "//package scala_tutorial\n\nimport scala.collection.mutable._\nobject source {\n\tdef main(args : Array[String]) {\n\t\tval Array(n, m) = readLine split \" \" map (_.toInt)\n\t\tvar f = readLine split \" \" map (_.toInt)\n\t\tvar b = readLine split \" \" map (_.toInt)\n\t\tvar index = 0\n\t\tvar imap = new HashMap[Int, Int]\n\t\tvar cnt = new HashMap[Int, Int]().withDefaultValue(0)\n\t\tvar ret = 0\n\t\tvar ans = Array.ofDim[Int](m+1)\n\t\tfor (index <- 0 until n)\n\t\t{\n\t\t\tcnt(f(index))+=1\n\t\t\timap(f(index))=index+1\n\t\t}\n\t\tfor (index <- 0 until m)\n\t\t{\n\t\t\tif(imap.contains(b(index))==false)\n\t\t\t{\n\t\t\t\tret = 2\n\t\t\t}\n\t\t\telse \n\t\t\t{\n\t\t\t\tif(cnt(b(index))>1)\n\t\t\t\t{\n\t\t\t\t\tret = 1\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tans(index)=imap(b(index))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(ret == 1)println(\"Ambiguity\")\n\t\telse if(ret == 2)println(\"Impossible\")\n\t\telse \n\t\t{\n\t\t\tprintln(\"Possible\")\n\t\t\tfor (index <- 0 until m)\n\t\t\t{\n\t\t\t\tprintf(\"%d \", ans(index))\n\t\t\t}\n\t\t}\n\t\t\n\t}\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val data1 = in.next().split(' ').map(_.toInt).sorted\n val data2 = in.next().split(' ').map(_.toInt).sorted\n val impossible = n != m\n val duplicates = (data1.distinct.length != data1.length) || (data2.distinct.length != data2.length)\n val res = data1.zip(data2).foldLeft(if (impossible) 2 else if (duplicates) 1 else 0) {\n case (2, _) => 2\n case (_, (el1, el2)) if el1 != el2 => 2\n case (status, _) => status\n }\n if (res == 0) {\n println(\"Possible\")\n println(data1.mkString(\" \"))\n }\n else if (res == 1)\n println(\"Ambiguity\")\n else\n println(\"Impossible\")\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val data1unsorted = in.next().split(' ').map(_.toInt)\n val data1 = data1unsorted.sorted\n val data2 = in.next().split(' ').map(_.toInt).sorted\n val impossible = n != m\n val duplicates = (data1.distinct.length != data1.length) || (data2.distinct.length != data2.length)\n val res = data1.zip(data2).foldLeft(if (impossible) 2 else if (duplicates) 1 else 0) {\n case (2, _) => 2\n case (_, (el1, el2)) if el1 != el2 => 2\n case (status, _) => status\n }\n if (res == 0) {\n println(\"Possible\")\n println(data1unsorted.mkString(\" \"))\n }\n else if (res == 1)\n println(\"Ambiguity\")\n else\n println(\"Impossible\")\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val F = readLine().split(\" \").map(_.toInt)\n val B = readLine().split(\" \").map(_.toInt)\n\n val Bcounter = Array.ofDim[Int](n + 1)\n val Fcounter = Array.ofDim[Int](n + 1)\n\n B.foreach(x => Bcounter(x) += 1)\n F.foreach(x => Fcounter(x) += 1)\n\n if (F.exists(x => Bcounter(x) == 0)) {\n println(\"Impossible\")\n } else if (B.exists(x => Fcounter(x) > 1)) {\n println(\"Ambiguity\")\n } else {\n println(\"Possible\")\n val M = F.zipWithIndex.map {\n x => (x._1, x._2 + 1)\n }.toMap\n\n println(B.map(M(_)).mkString(\" \"))\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val F = readLine().split(\" \").map(_.toInt)\n val B = readLine().split(\" \").map(_.toInt)\n\n val Bcounter = Array.ofDim[Int](n + 1)\n\n B.foreach(x => Bcounter(x) += 1)\n\n if (F.exists(x => Bcounter(x) == 0)) {\n println(\"Impossible\")\n } else if (F.forall(x => Bcounter(x) == 1)) {\n println(\"Possible\")\n } else {\n println(\"Ambiguity\")\n }\n\n}\n"}, {"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val (n,m)=(nextInt,nextInt)\n val f=(for(i<-0 until n) yield (nextInt,i+1)) sorted\n val a=Array.ofDim[Int](m)\n var flag=0\n breakable{\n for(i<-0 until m){\n val b=nextInt\n var l=0\n var r=n-1\n while(lb){\n r=c\n }else{\n l=c\n }\n }\n var ma= -1\n if(f(l)._1==b){\n ma=l\n }else if(f(r)._1==b){\n ma=r\n }else{\n flag=2\n break\n\n }\n if(ma>0 && f(ma-1)._1==b){\n flag=1\n break\n }\n if(ma Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "\nimport scala.io.StdIn\n\nobject Minesweeper extends App {\n\n type Field = Array[Array[String]]\n\n val l1s = StdIn.readLine().split(\" \")\n val n = l1s(0).toInt\n val m = l1s(1).toInt\n\n val field = new Field(n)\n for (i <- 0 until n) {\n field(i) = StdIn.readLine().split(\"\")\n }\n\n impl(n, m, field) match {\n case true => print(\"YES\")\n case false => print(\"NO\")\n }\n\n def impl(n: Int, m: Int, field: Field): Boolean = {\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (!validateNeighbors(i, j, field, n, m)) return false\n }\n }\n true\n }\n\n private\n def validateNeighbors(i: Int, j: Int, field: Field, n: Int, m: Int): Boolean = {\n if (field(i)(j) != \"*\") {\n val mines =\n getMine(-1, -1, i, j, n, m, field) +\n getMine(-1, 0, i, j, n, m, field) +\n getMine(-1, 1, i, j, n, m, field) +\n getMine(0, -1, i, j, n, m, field) +\n getMine(0, 1, i, j, n, m, field) +\n getMine(1, -1, i, j, n, m, field) +\n getMine(1, 0, i, j, n, m, field) +\n getMine(1, 1, i, j, n, m, field)\n\n if (field(i)(j) == \".\") {\n if (mines == 0) true\n else false\n } else {\n if (mines == field(i)(j).toInt) true\n else false\n }\n } else {\n true\n }\n }\n\n private\n def getMine(i_offset: Int, j_offset: Int, i: Int, j: Int, n: Int, m: Int, field: Field): Int = {\n if (inField(i + i_offset, j + j_offset, n, m)) {\n if (field(i + i_offset)(j + j_offset) == \"*\") 1\n else 0\n } else 0\n }\n\n private\n def inField(i: Int, j: Int, n: Int, m: Int): Boolean = {\n if (i < 0 || i >= n) false\n else if (j < 0 || j >= m) false\n else true\n }\n}\n"}], "negative_code": [], "src_uid": "0d586ba7d304902caaeb7cd9e6917cd6"} {"source_code": "object C extends App {\n\n def readString = Console.readLine\n val as = readString\n val k = readString.toLong\n\n var x = 0\n val TWO = BigInt(2)\n val M = 1000000007\n val l = as.length()\n \n val a = TWO.modPow(k * l, M) - 1\n val b = TWO.modPow(l, M) - 1\n val y = a * b.modInverse(M)\n \n for (c <- as.reverse) {\n x = 2 * x\n if (c == '0' || c == '5') x += 1\n x %= M\n }\n \n println(x * y % M)\n}", "positive_code": [{"source_code": "object C extends App {\n\n def readString = Console.readLine\n\n val as = readString\n val k = readString.toLong\n\n var x = 0\n val TWO = BigInt(2)\n val M = 1000000007\n val l = as.length()\n \n val a = TWO.modPow(k * l, M) - 1\n val b = TWO.modPow(l, M) - 1\n val y = a * b.modInverse(M)\n \n for (c <- as.reverse) {\n x = 2 * x\n if (c == '0' || c == '5') x += 1\n x %= M\n }\n \n println(x * y % M)\n}"}, {"source_code": "object C extends App {\n\n def readString = Console.readLine\n\n val as = readString //Array.fill(100000)('5') \n val k = readString.toLong\n\n var x = BigInt(0)\n val TWO = BigInt(2)\n val M = BigInt(1000000007)\n val l = as.length()\n \n val a = TWO.modPow(k * l, M) - 1\n val b = TWO.modPow(l, M) - 1\n val y = a * b.modInverse(M)\n \n for (c <- as.reverse) {\n x = 2 * x\n if (c == '0' || c == '5') x += 1\n x %= M\n }\n \n println(x * y % M)\n}"}, {"source_code": "object CF327C extends App {\n val s = Console.readLine\n val n : Long = s.size.toLong\n val k : Long = Console.readLine.toLong\n val md = 1000000007L\n\n def p2(y : Long, x : Long) : Long = {\n if (x == 0) 1 else {\n val t = p2(y, x/2)\n if (x % 2 == 0) (t * t) % md else (((y * t) % md) * t) % md\n }\n }\n\n def inv(x : Long) : Long = {\n p2(x, md - 2)\n }\n\n val res = (0 until n.toInt).map{\n x => if (s(x) == '0' || s(x) == '5') p2(2, x) else 0\n }.reduce((x, y) => (x + y) % md)\n\n val outer = (p2(2, k * n) - 1 + md) % md * inv((p2(2, n) - 1 + md)% md) % md\n\n println (res * outer % md)\n}\n"}], "negative_code": [{"source_code": "object C extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val as = readString //Array.fill(100000)('5') // \n val k = readString.toInt\n\n var x = BigInt(0)\n val TWO = BigInt(2)\n val M = BigInt(1000000007)\n val l = as.length()\n \n val a = k min l\n val b = k max l\n \n val y = ((TWO.modPow(b, M).modPow(a, l * M) - 1 + M) % M) / ((TWO.pow(l)- 1))\n \n for (c <- as.reverse) {\n x = 2 * x\n if (c == '0' || c == '5') x += 1\n }\n \n println(x * y % M)\n}"}, {"source_code": "object C extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val as = readString //Array.fill(100000)('5') \n val k = readString.toInt\n\n var x = 0L\n val TWO = BigInt(2)\n val M = 1000000007L\n val l = as.length()\n \n val a = TWO.modPow(k * l, M) - 1\n val b = TWO.modPow(l, M) - 1\n val y = a * b.modInverse(M)\n \n for (c <- as.reverse) {\n x = 2 * x\n if (c == '0' || c == '5') x += 1\n x %= M\n }\n \n println(x * y % M)\n}"}, {"source_code": "object C extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val as = Array.fill(100000)('5') \n val k = readString.toInt\n\n var x = 0L\n val TWO = BigInt(2)\n val M = 1000000007\n val l = as.length()\n \n val a = TWO.modPow(k * l, M) - 1\n val b = TWO.modPow(l, M) - 1\n val y = a * b.modInverse(M)\n \n for (c <- as.reverse) {\n x = 2 * x\n if (c == '0' || c == '5') x += 1\n x %= M\n }\n \n println(x * y % M)\n}"}, {"source_code": "object C extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val as = readString //Array.fill(100000)('5') // \n val k = readString.toInt\n\n var x = BigInt(0)\n val TWO = BigInt(2)\n val M = BigInt(1000000007)\n val l = as.length()\n \n val a = k min l\n val b = k max l\n \n val y = ((TWO.modPow(b, M).modPow(a, l * M) - 1 + M) % M) / ((TWO.modPow(l, M) + M - 1) % M)\n \n for (c <- as.reverse) {\n x = 2 * x\n if (c == '0' || c == '5') x += 1\n }\n \n println(x * y % M)\n}"}, {"source_code": "object C extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val as = readString //Array.fill(100000)('5') // \n val k = readString.toInt\n\n var x = BigInt(0)\n val TWO = BigInt(2)\n val M = BigInt(1000000007)\n val l = as.length()\n \n val a = k min l\n val b = k max l\n \n val y = (TWO.modPow(b, M).modPow(a, l * M) - 1) / ((TWO.pow(l)- 1))\n \n for (c <- as.reverse) {\n x = 2 * x\n if (c == '0' || c == '5') x += 1\n }\n \n println(x * y % M)\n}"}, {"source_code": "object C extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val as = readString //Array.fill(100000)('5') // \n val k = readString.toInt\n\n var x = BigInt(0)\n val TWO = BigInt(2)\n val M = BigInt(1000000007)\n val l = as.length()\n \n val a = k min l\n val b = k max l\n \n val y = (TWO.modPow(b, M).modPow(a, l * M) - 1) / (TWO.modPow(l, M) - 1)\n \n for (c <- as.reverse) {\n x = 2 * x\n if (c == '0' || c == '5') x += 1\n }\n \n println(x * y % M)\n}"}, {"source_code": "object C extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val as = readString //Array.fill(100000)('5') // \n val k = readString.toInt\n\n var x = BigInt(0)\n val TWO = BigInt(2)\n val M = BigInt(1000000007)\n val l = as.length()\n \n val y = (TWO.modPow(k * l, l * M) - 1) / (TWO.modPow(l, M) - 1)\n \n for (c <- as.reverse) {\n x = 2 * x\n if (c == '0' || c == '5') x += 1\n }\n \n println(x * y % M)\n}"}, {"source_code": "object CF327C extends App {\n val s = Console.readLine\n val n = s.size\n val k = Console.readLine.toInt\n val md = 1000000007\n\n def p2(y : Long, x : Long) : Long = {\n if (x == 0) 1 else {\n val t = p2(y, x/2)\n if (x % 2 == 0) (t * t) % md else ((y * t) % md) * t % md\n }\n }\n\n def inv(x : Long) : Long = {\n p2(x, md - 2)\n }\n\n val res = ((0 until n).reverse.map{\n x => {\n if (s(x) == '0' || s(x) == '5') p2(2, x) else 0\n }\n }.reduce((x, y) => (x + y) % md) * ((p2(2, k * n) - 1 + md) % md))% md * inv((p2(2, n) - 1 + md)% md) % md\n\n println (res)\n}\n"}, {"source_code": "object CF327C extends App {\n val s = Console.readLine\n val n = s.size\n val k = Console.readLine.toInt\n val md = 1000000007L\n\n def p2(y : Long, x : Long) : Long = {\n if (x == 0) 1 else {\n val t = p2(y, x/2)\n if (x % 2 == 0) (t * t) % md else (((y * t) % md) * t) % md\n }\n }\n\n def inv(x : Long) : Long = {\n p2(x, md - 2)\n }\n\n val res = (((0 until n).reverse.map{\n x => {\n if (s(x) == '0' || s(x) == '5') p2(2, x) else 0\n }\n }.reduce((x, y) => (x + y) % md) * ((p2(2, k * n) - 1 + md) % md))% md * inv((p2(2, n) - 1 + md)% md)) % md\n\n println (res)\n}\n"}, {"source_code": "object CF327C extends App {\n val s = Console.readLine\n val n = s.size\n val k = Console.readLine.toInt\n val md = 1000000007\n\n def p2(y : Long, x : Long) : Long = {\n if (x == 0) 1 else {\n val t = p2(y, x/2)\n if (x % 2 == 0) (t * t) % md else ((y * t) % md) * t % md\n }\n }\n\n def inv(x : Long) : Long = {\n p2(x, md - 2)\n }\n\n val res = ((0 until n).reverse.map{\n x => {\n if (s(x) == '0' || s(x) == '5') p2(2, x) else 0\n }\n }.reduce((x, y) => (x + y) % md) * ((p2(2, k * n) - 1 + md) % md))% md * inv(p2(2, n) - 1) % md\n\n println (res)\n}\n"}, {"source_code": "object CF327C extends App {\n val s = Console.readLine\n val n = s.size\n val k = Console.readLine.toInt\n val md = 1000000007\n\n def p2(y : Long, x : Long) : Long = {\n if (x == 0) 1 else {\n val t = p2(y, x/2)\n if (x % 2 == 0) (t * t) % md else (((y * t) % md) * t) % md\n }\n }\n\n def inv(x : Long) : Long = {\n p2(x, md - 2)\n }\n\n val res = (((0 until n).reverse.map{\n x => {\n if (s(x) == '0' || s(x) == '5') p2(2, x) else 0\n }\n }.reduce((x, y) => (x + y) % md) * ((p2(2, k * n) - 1 + md) % md))% md * inv((p2(2, n) - 1 + md)% md)) % md\n\n println (res)\n}\n"}], "src_uid": "268f90d0595f7c51fb336ce377409dde"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val cats = in.next().split(\" \").map(_.toInt)\n val nodes = Array.fill(n){List.empty[Int]}\n (1 until n).foreach { _ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt - 1)\n nodes(a) ::= b\n nodes(b) ::= a\n }\n\n def count(i: Int, parent: Int, soFar: Int, found: Boolean): Int = {\n val nSoFar = if (cats(i) == 1) soFar + 1 else 0\n val nFound = found || nSoFar == m + 1\n val children = nodes(i).filter(_ != parent).map{j => count(j, i, nSoFar, nFound)}\n if (children.isEmpty)\n if (nFound) 0 else 1\n else\n children.sum\n }\n\n println(count(0, 0, 0, false))\n}", "positive_code": [{"source_code": "object C580 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val isCat = readInts(n)\n val vis = Array.fill(n)(false)\n val _G = Array.fill(n)(collection.mutable.ArrayBuffer.empty[Int])\n for(i <- 0 until n-1){\n val in = readInts(2)\n _G(in(0)-1) += in(1)-1\n _G(in(1)-1) += in(0)-1\n }\n val G = _G.map(_.toArray)\n\n def dfs(idx: Int, cats: Int): Int = {\n val newCats = if(isCat(idx)==1) cats+1 else 0\n vis(idx) = true\n if(newCats <= m) {\n if(G(idx).length == 1 && idx!=0) {\n 1\n } else {\n var sum = 0\n for (i <- G(idx)) {\n if(!vis(i))\n sum += dfs(i, newCats)\n }\n sum\n }\n } else {\n 0\n }\n }\n\n var res = dfs(0, 0)\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val cats = in.next().split(\" \").map(_.toInt)\n val nodes = Array.fill(n){List.empty[Int]}\n (1 until n).foreach { _ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt - 1)\n nodes(a) ::= b\n nodes(b) ::= a\n }\n\n def count(i: Int, parent: Int, soFar: Int, found: Boolean): Int = {\n val nSoFar = if (cats(i) == 1) soFar + 1 else 0\n val nFound = found || nSoFar == m + 1\n val children = nodes(i).filter(_ != parent).map{j => count(j, i, nSoFar, nFound)}\n if (children.isEmpty)\n if (nFound) 0 else 1\n else\n children.sum\n }\n\n println(count(0, 0, 0, false))\n}"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _580C extends CodeForcesApp[Int]({scanner => import scanner._\n val (n, m) = (nextInt, nextInt)\n val hasCats = IndexedSeq.fill(n)(nextInt == 1)\n val edge = map[Int].to(List.empty[Int])\n repeat(n-1) {\n val (i, j) = (nextInt, nextInt)\n edge(i) = j :: edge(i)\n edge(j) = i :: edge(j)\n }\n\n val visited = bag[Int]\n\n def solve(pos: Int, prevCats: Int): Int = {\n visited += pos\n val cats = if (hasCats(pos - 1)) 1 + prevCats else 0\n edge(pos).filterNot(visited) match {\n case _ if cats > m => 0\n case Nil => 1\n case children => children.map(solve(_, cats)).sum\n }\n }\n\n solve(1, 0)\n}) {\n override def format(result: Result) = super.format(result)\n}\n/********************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _580C extends CodeForcesApp[Int]({scanner => import scanner._\n val (n, m) = (nextInt, nextInt)\n val hasCats = IndexedSeq.fill(n)(nextInt == 1)\n val edge = map[Int].to(Set.empty[Int])\n repeat(n-1) {\n val (i, j) = (nextInt, nextInt)\n edge(i) = edge(i) + j\n edge(j) = edge(j) + i\n }\n\n val visited = mutable.Set.empty[Int]\n\n def solve(pos: Int, prevCats: Int): Int = {\n visited += pos\n val cats = if (hasCats(pos - 1)) 1 + prevCats else 0\n if (cats > m) {\n 0 // more than m consecutive cats. Exit!\n } else {\n val children = edge(pos).filterNot(visited).view\n if (children.isEmpty) {\n 1 // Leaf node\n } else {\n var sum = 0 // inner node\n for {i <- children} {\n sum += solve(i, cats)\n }\n sum\n }\n }\n }\n\n solve(1, 0)\n})\n/****************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n final def map[A] = new {\n import scala.collection.mutable.{Map => Dict}\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _580C extends CodeForcesApp[Int]({scanner => import scanner._\n val (n, m) = (nextInt, nextInt)\n val hasCats = IndexedSeq.fill(n)(nextInt == 1)\n val edge = map[Int].to(List.empty[Int])\n repeat(n-1) {\n val (i, j) = (nextInt, nextInt)\n edge(i) = j :: edge(i)\n edge(j) = i :: edge(j)\n }\n\n val visited = bag[Int]\n\n def solve(pos: Int, prevCats: Int): Int = {\n visited += pos\n val cats = if (hasCats(pos - 1)) 1 + prevCats else 0\n edge(pos).filterNot(visited) match {\n case _ if cats > m => 0\n case Nil => 1\n case children => children.map(solve(_, cats)).sum\n }\n }\n\n solve(1, 0)\n}) {\n override def format(result: Result) = super.format(result)\n}\n/********************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}"}, {"source_code": "object Solution extends App { \nval in = scala.io.Source.stdin.getLines() \nval Array(n, m) = in.next().split(\" \").map(_.toInt) \nval cats = in.next().split(\" \").map(_.toInt) \nval nodes = Array.fill(n){List.empty[Int]} \n(1 until n).foreach { _ => \nval Array(a, b) = in.next().split(\" \").map(_.toInt - 1) \nnodes(a) ::= b \nnodes(b) ::= a \n} \n\ndef count(i: Int, parent: Int, soFar: Int, found: Boolean): Int = { \nval nSoFar = if (cats(i) == 1) soFar + 1 else 0 \nval nFound = found || nSoFar == m + 1 \nval children = nodes(i).filter(_ != parent).map{j => count(j, i, nSoFar, nFound)} \nif (children.isEmpty) \nif (nFound) 0 else 1 \nelse \nchildren.sum \n} \n\nprintln(count(0, 0, 0, false)) \n}"}, {"source_code": "/**\n * @author netman\n */\n\n\nimport java.io._\nimport scala._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\n\nobject HelloWorld {\n\n class InputReader(reader: BufferedReader) {\n \n var tokenizer: StringTokenizer = null;\n \n def this(stream: InputStream) = {\n this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));\n }\n \n def this(f: File) = {\n this(new BufferedReader(new FileReader(f), (1 << 20)));\n }\n \n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine());\n }\n return tokenizer.nextToken();\n }\n \n def nextInt(): Int = next().toInt\n \n def nextDouble(): Double = next().toDouble\n \n def close() = reader.close();\n }\n \n class OutputWriter(writer: PrintWriter) {\n def this(stream: OutputStream) {\n this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));\n }\n \n def this(f: File) = {\n this(new PrintWriter(new BufferedWriter(new FileWriter(f))));\n }\n \n def print(x: Any) = writer.print(x);\n \n def println(x: Any) = writer.println(x);\n \n def close() = writer.close();\n }\n \n \n val in = new InputReader(System.in)\n val out = new OutputWriter(System.out)\n \n var a: Array[Int] = null\n var g: Array[ArrayBuffer[Int]] = null\n var m = 0\n var result = 0\n \n def dfs(v: Int, p: Int, cur: Int): Unit = {\n val ncur = if (a(v) == 0) 0 else cur + 1\n if (ncur <= m) {\n if (g(v).length == 1 && v != 1) {\n result += 1\n //out.println(v)\n }\n for (to <- g(v)) {\n if (to != p) {\n dfs(to, v, ncur)\n }\n }\n }\n }\n \n def main(args: Array[String]): Unit = {\n val n = in.nextInt\n m = in.nextInt\n \n a = new Array[Int](n + 1)\n g = Array.fill[ArrayBuffer[Int]](n + 1)(new ArrayBuffer[Int])\n \n for (i <- 1 to n) {\n a(i) = in.nextInt\n }\n \n for (i <- 1 to n - 1) {\n val (x, y) = (in.nextInt, in.nextInt)\n g(x) += y\n g(y) += x\n }\n \n dfs(1, -1, 0)\n\n out.println(result)\n \n out.close\n }\n}"}, {"source_code": "object Solution extends App { \nval in = scala.io.Source.stdin.getLines() \nval Array(n, m) = in.next().split(\" \").map(_.toInt) \nval cats = in.next().split(\" \").map(_.toInt) \nval nodes = Array.fill(n){List.empty[Int]} \n(1 until n).foreach { _ => \nval Array(a, b) = in.next().split(\" \").map(_.toInt - 1) \nnodes(a) ::= b \nnodes(b) ::= a \n} \n\ndef count(i: Int, parent: Int, soFar: Int, found: Boolean): Int = { \nval nSoFar = if (cats(i) == 1) soFar + 1 else 0 \nval nFound = found || nSoFar == m + 1 \nval children = nodes(i).filter(_ != parent).map{j => count(j, i, nSoFar, nFound)} \nif (children.isEmpty) \nif (nFound) 0 else 1 \nelse \nchildren.sum \n} \n\nprintln(count(0, 0, 0, false)) \n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val cats = in.next().split(\" \").map(_.toInt)\n val nodes = Array.fill(n){List.empty[Int]}\n (1 until n).foreach { _ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt - 1)\n nodes(a) ::= b\n nodes(b) ::= a\n }\n\n def count(i: Int, parent: Int, soFar: Int, found: Boolean): Int = {\n val nSoFar = if (cats(i) == 1) soFar + 1 else 0\n val nFound = found || nSoFar == m + 1\n val children = nodes(i).filter(_ != parent).map{j => count(j, i, nSoFar, nFound)}\n if (children.isEmpty)\n if (nFound) 0 else 1\n else\n children.sum\n }\n\n println(count(0, 0, 0, false))\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\n//https://codeforces.com/problemset/problem/580/C\nobject KefaAndPark {\n case class Cou(var c:Int=0)\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n var line=in.readLine()\n val n=line.split(\" \")(0).toInt\n val m=line.split(\" \")(1).toInt\n val cats=in.readLine().split(\" \").map(_.toInt)\n val graph = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())\n for(i<- 0 until n-1){\n line=in.readLine()\n addUndirectedEdge(graph,line.split(\" \")(0).toInt-1,(line.split(\" \")(1).toInt-1))\n }\n getNumberOfPossibleRestaurants(graph,n,m,cats)\n }\n\n def getNumberOfPossibleRestaurants(graph:Array[ArrayBuffer[Int]],n:Int,m:Int,cats:Array[Int]):Int={\n val cou=Cou()\n postOrder(graph,cats,0,-1,cats(0),m,cou)\n println(cou.c)\n return cou.c\n }\n\n def postOrder(graph:Array[ArrayBuffer[Int]],cats:Array[Int],n:Int,pr:Int,curM:Int,m:Int,cou: Cou):Unit={\n if(curM<=m){\n var x=1\n for(i<- 0 until graph(n).length ){\n if(graph(n)(i)!=pr) {\n x=0\n postOrder(graph, cats, graph(n)(i), n, cats(graph(n)(i))*curM+cats(graph(n)(i)), m, cou)\n }\n }\n cou.c+=x\n }\n }\n def addUndirectedEdge(graph: Array[ArrayBuffer[Int]], u: Int, v: Int): Unit = {\n //It is an undirected graph, so the an edge a to b can be used to travel both a to b and b to aa\n graph(u) += v\n graph(v) += u\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\n//https://codeforces.com/problemset/problem/580/C\nobject KefaAndPark {\n case class Cou(var c:Int=0)\n var graph:Array[ArrayBuffer[Int]] =null\n var cats:Array[Int]=null\n var m:Int=0\n val cou=Cou()\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n var line=in.readLine()\n val n=line.split(\" \")(0).toInt\n m=line.split(\" \")(1).toInt\n cats=in.readLine().split(\" \").map(_.toInt)\n graph = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())\n for(i<- 0 until n-1){\n line=in.readLine()\n addUndirectedEdge(graph,line.split(\" \")(0).toInt-1,(line.split(\" \")(1).toInt-1))\n }\n postOrder(0,-1,cats(0))\n println(cou.c)\n }\n\n def postOrder(n:Int,pr:Int,curM:Int):Unit={\n if(curM<=m){\n var x=1\n for(i<- 0 until graph(n).length ){\n if(graph(n)(i)!=pr) {\n x=0\n postOrder(graph(n)(i), n, cats(graph(n)(i))*curM+cats(graph(n)(i)))\n }\n }\n cou.c+=x\n }\n }\n def addUndirectedEdge(graph: Array[ArrayBuffer[Int]], u: Int, v: Int): Unit = {\n //It is an undirected graph, so the an edge a to b can be used to travel both a to b and b to aa\n graph(u) += v\n graph(v) += u\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\n//https://codeforces.com/problemset/problem/580/C\nobject KefaAndPark {\n case class Cou(var c:Int=0)\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n var line=in.readLine()\n val n=line.split(\" \")(0).toInt\n val m=line.split(\" \")(1).toInt\n val cats=in.readLine().split(\" \").map(_.toInt)\n val edges=new ArrayBuffer[Int]()\n for(i<- 0 until n-1){\n line=in.readLine()\n edges+=(line.split(\" \")(0).toInt-1)\n edges+=(line.split(\" \")(1).toInt-1)\n }\n getNumberOfPossibleRestaurants(n,m,cats,edges)\n }\n\n def getNumberOfPossibleRestaurants(n:Int,m:Int,cats:Array[Int],edges:ArrayBuffer[Int]):Int={\n val graph=getDirectedGraph(edges,n)\n val cou=Cou()\n postOrder(graph,cats,0,-1,cats(0),m,cou)\n println(cou.c)\n return cou.c\n }\n\n def postOrder(graph:Array[ArrayBuffer[Int]],cats:Array[Int],n:Int,pr:Int,curM:Int,m:Int,cou: Cou):Unit={\n if(curM<=m){\n\n\n var x=1\n for(i<- 0 until graph(n).length ){\n if(graph(n)(i)!=pr) {\n x=0\n if (cats(graph(n)(i)) == 0) {\n postOrder(graph, cats, graph(n)(i), n, 0, m, cou)\n } else {\n postOrder(graph, cats, graph(n)(i), n, curM + 1, m, cou)\n }\n }\n }\n cou.c+=x\n }\n }\n\n def getDirectedGraph(edges: ArrayBuffer[Int], N: Int): Array[ArrayBuffer[Int]] = {\n //Adjacency list representation is used to represent the graph\n\n //We have N vertices\n val graph = new Array[ArrayBuffer[Int]](N)\n\n //Every vertices can be associated to multiple adjacent vertices\n for (i <- 0 until N) {\n graph(i)= new ArrayBuffer[Int]()\n }\n\n //Every pair array elements represent a edge\n for (i <- 0 until edges.length by 2) {\n addDirectedEdge(graph, edges(i), edges(i + 1))\n }\n\n return graph\n }\n\n def addDirectedEdge(graph: Array[ArrayBuffer[Int]], u: Int, v: Int): Unit = {\n //It is a directed graph, so the an edge a to b can be used to travel from a to b\n graph(u) += v\n graph(v) += u\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\n//https://codeforces.com/problemset/problem/580/C\nobject KefaAndPark {\n case class Cou(var c:Int=0)\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n var line=in.readLine()\n val n=line.split(\" \")(0).toInt\n val m=line.split(\" \")(1).toInt\n val cats=in.readLine().split(\" \").map(_.toInt)\n val graph = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())\n for(i<- 0 until n-1){\n line=in.readLine()\n val u=line.split(\" \")(0).toInt-1\n val v=(line.split(\" \")(1).toInt-1)\n addUndirectedEdge(graph,u,v)\n }\n getNumberOfPossibleRestaurants(graph,n,m,cats)\n }\n\n def getNumberOfPossibleRestaurants(graph:Array[ArrayBuffer[Int]],n:Int,m:Int,cats:Array[Int]):Int={\n val cou=Cou()\n postOrder(graph,cats,0,-1,cats(0),m,cou)\n println(cou.c)\n return cou.c\n }\n\n def postOrder(graph:Array[ArrayBuffer[Int]],cats:Array[Int],n:Int,pr:Int,curM:Int,m:Int,cou: Cou):Unit={\n if(curM<=m){\n var x=1\n for(i<- 0 until graph(n).length ){\n if(graph(n)(i)!=pr) {\n x=0\n postOrder(graph, cats, graph(n)(i), n, cats(graph(n)(i))*curM+cats(graph(n)(i)), m, cou)\n }\n }\n cou.c+=x\n }\n }\n def addUndirectedEdge(graph: Array[ArrayBuffer[Int]], u: Int, v: Int): Unit = {\n //It is an undirected graph, so the an edge a to b can be used to travel both a to b and b to aa\n graph(u) += v\n graph(v) += u\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val cats = in.next().split(\" \").map(_.toInt)\n val nodes = Array.fill(n){List.empty[Int]}\n (1 until n).foreach { _ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt - 1)\n nodes(a) ::= b\n nodes(b) ::= a\n }\n\n def count(i: Int, parent: Int, soFar: Int, found: Boolean): Int = {\n val nSoFar = if (cats(i) == 1) soFar + 1 else 0\n val nFound = found || nSoFar == m + 1\n val children = nodes(i).filter(_ != parent).map{j => count(j, i, nSoFar, nFound)}\n if (children.isEmpty)\n if (nFound) 0 else 1\n else\n children.sum\n }\n\n println(count(0, 0, 0, false))\n}"}, {"source_code": "//package round321.c\n\nimport java.util.Scanner\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n val m = sc.nextInt\n\n val hasCat = (0 until n).map(_ => sc.nextInt == 1)\n\n var tree = Array.fill[List[Int]](n)(Nil)\n\n (0 until (n-1)).foreach { _ =>\n val (a, b) = (sc.nextInt - 1, sc.nextInt - 1)\n tree(a) = b :: tree(a)\n tree(b) = a :: tree(b)\n }\n\n def dfs(v: Int, parent: Int, consCatsSoFar: Int): Int = {\n val consCats = if(hasCat(v)) 1 + consCatsSoFar else 0\n if(consCats > m) 0\n else {\n val children = tree(v).filterNot(_ == parent)\n if(children.isEmpty) 1\n else {\n children.foldLeft(0){ case (s, vNext) =>\n s + dfs(vNext, v, consCats)\n }\n }\n }\n }\n\n println(dfs(0, -1, 0))\n}\n\n"}], "negative_code": [{"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _580C extends CodeForcesApp[Int]({scanner => import scanner._\n val (n, m) = (nextInt, nextInt)\n val hasCats = IndexedSeq.fill(n)(nextInt == 1)\n val tree = map[Int].to(Set.empty[Int])\n repeat(n-1) {\n val (i, j) = (nextInt, nextInt)\n tree(i) = tree(i) + j\n }\n\n def solve(pos: Int, prevCats: Int): Int = {\n val cats = if (hasCats(pos - 1)) 1 + prevCats else 0\n //debug(pos, prevCats, cats, tree(pos))\n tree(pos).toSeq match {\n case _ if cats > m => 0\n case Nil => 1\n case children => children.map(solve(_, cats)).sum\n }\n }\n\n solve(1, 0)\n}) {\n override def format(result: Result) = super.format(result)\n}\n/****************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n final def map[A] = new {\n import scala.collection.mutable.{Map => Dict}\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n"}, {"source_code": "/**\n * @author netman\n */\n\n\nimport java.io._\nimport scala._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\n\nobject HelloWorld {\n\n class InputReader(reader: BufferedReader) {\n \n var tokenizer: StringTokenizer = null;\n \n def this(stream: InputStream) = {\n this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));\n }\n \n def this(f: File) = {\n this(new BufferedReader(new FileReader(f), (1 << 20)));\n }\n \n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine());\n }\n return tokenizer.nextToken();\n }\n \n def nextInt(): Int = next().toInt\n \n def nextDouble(): Double = next().toDouble\n \n def close() = reader.close();\n }\n \n class OutputWriter(writer: PrintWriter) {\n def this(stream: OutputStream) {\n this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));\n }\n \n def this(f: File) = {\n this(new PrintWriter(new BufferedWriter(new FileWriter(f))));\n }\n \n def print(x: Any) = writer.print(x);\n \n def println(x: Any) = writer.println(x);\n \n def close() = writer.close();\n }\n \n \n val in = new InputReader(System.in)\n val out = new OutputWriter(System.out)\n \n var a: Array[Int] = null\n var g: Array[ArrayBuffer[Int]] = null\n var m = 0\n var result = 0\n \n def dfs(v: Int, p: Int, cur: Int): Unit = {\n val ncur = if (a(v) == 0) 0 else cur + 1\n if (ncur > m) return\n if (g(v).length == 1) result += 1\n for (to <- g(v)) {\n if (to != p) {\n dfs(to, v, ncur)\n }\n }\n }\n \n def main(args: Array[String]): Unit = {\n val n = in.nextInt\n m = in.nextInt\n \n a = new Array[Int](n + 1)\n g = Array.fill[ArrayBuffer[Int]](n + 1)(new ArrayBuffer[Int])\n \n for (i <- 1 to n) {\n a(i) = in.nextInt\n }\n \n for (i <- 1 to n - 1) {\n val (x, y) = (in.nextInt, in.nextInt)\n g(x) += y\n g(y) += x\n }\n \n dfs(1, -1, 0)\n\n out.println(result)\n \n out.close\n }\n}"}, {"source_code": "/**\n * @author netman\n */\n\n\nimport java.io._\nimport scala._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\n\nobject HelloWorld {\n\n class InputReader(reader: BufferedReader) {\n \n var tokenizer: StringTokenizer = null;\n \n def this(stream: InputStream) = {\n this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));\n }\n \n def this(f: File) = {\n this(new BufferedReader(new FileReader(f), (1 << 20)));\n }\n \n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine());\n }\n return tokenizer.nextToken();\n }\n \n def nextInt(): Int = next().toInt\n \n def nextDouble(): Double = next().toDouble\n \n def close() = reader.close();\n }\n \n class OutputWriter(writer: PrintWriter) {\n def this(stream: OutputStream) {\n this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));\n }\n \n def this(f: File) = {\n this(new PrintWriter(new BufferedWriter(new FileWriter(f))));\n }\n \n def print(x: Any) = writer.print(x);\n \n def println(x: Any) = writer.println(x);\n \n def close() = writer.close();\n }\n \n \n val in = new InputReader(System.in)\n val out = new OutputWriter(System.out)\n \n var a: Array[Int] = null\n var g: Array[ArrayBuffer[Int]] = null\n var m = 0\n var result = 0\n \n def dfs(v: Int, p: Int, cur: Int): Unit = {\n val ncur = if (a(v) == 0) 0 else cur + 1\n if (ncur <= m) {\n if (g(v).length == 1) result += 1\n for (to <- g(v)) {\n if (to != p) {\n dfs(to, v, ncur)\n }\n }\n }\n }\n \n def main(args: Array[String]): Unit = {\n val n = in.nextInt\n m = in.nextInt\n \n a = new Array[Int](n + 1)\n g = Array.fill[ArrayBuffer[Int]](n + 1)(new ArrayBuffer[Int])\n \n for (i <- 1 to n) {\n a(i) = in.nextInt\n }\n \n for (i <- 1 to n - 1) {\n val (x, y) = (in.nextInt, in.nextInt)\n g(x) += y\n g(y) += x\n }\n \n dfs(1, -1, 0)\n\n out.println(result)\n \n out.close\n }\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\n//https://codeforces.com/problemset/problem/580/C\nobject KefaAndPark {\n case class Cou(var c:Int=0)\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n var line=in.readLine()\n val n=line.split(\" \")(0).toInt\n val m=line.split(\" \")(1).toInt\n val cats=in.readLine().split(\" \").map(_.toInt)\n val edges=new ArrayBuffer[Int]()\n for(i<- 0 until n-1){\n line=in.readLine()\n edges+=(line.split(\" \")(0).toInt-1)\n edges+=(line.split(\" \")(1).toInt-1)\n }\n getNumberOfPossibleRestaurants(n,m,cats,edges)\n }\n\n def getNumberOfPossibleRestaurants(n:Int,m:Int,cats:Array[Int],edges:ArrayBuffer[Int]):Int={\n val graph=getDirectedGraph(edges,n)\n val cou=Cou()\n postOrder(graph,cats,0,-1,cats(0),m,cou)\n println(cou.c)\n return cou.c\n }\n\n def postOrder(graph:Array[ArrayBuffer[Int]],cats:Array[Int],n:Int,pr:Int,curM:Int,m:Int,cou: Cou):Unit={\n if(curM<=m){\n if(graph(n).length==1){\n cou.c+=1\n }else{\n for(i<- 0 until graph(n).length if(graph(n)(i)!=pr)){\n if(cats(graph(n)(i))==0) {\n postOrder(graph, cats, graph(n)(i),n, 0, m, cou)\n }else{\n postOrder(graph, cats, graph(n)(i),n, curM+1, m, cou)\n }\n }\n }\n }\n }\n\n def getDirectedGraph(edges: ArrayBuffer[Int], N: Int): Array[ArrayBuffer[Int]] = {\n //Adjacency list representation is used to represent the graph\n\n //We have N vertices\n val graph = new Array[ArrayBuffer[Int]](N)\n\n //Every vertices can be associated to multiple adjacent vertices\n for (i <- 0 until N) {\n graph(i)= new ArrayBuffer[Int]()\n }\n\n //Every pair array elements represent a edge\n for (i <- 0 until edges.length by 2) {\n addDirectedEdge(graph, edges(i), edges(i + 1))\n }\n\n return graph\n }\n\n def addDirectedEdge(graph: Array[ArrayBuffer[Int]], u: Int, v: Int): Unit = {\n //It is a directed graph, so the an edge a to b can be used to travel from a to b\n graph(u) += v\n graph(v) += u\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\n//https://codeforces.com/problemset/problem/580/C\nobject KefaAndPark {\n case class Cou(var c:Int=0)\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n var line=in.readLine()\n val n=line.split(\" \")(0).toInt\n val m=line.split(\" \")(1).toInt\n val cats=in.readLine().split(\" \").map(_.toInt)\n val edges=new ArrayBuffer[Int]()\n for(i<- 0 until n-1){\n line=in.readLine()\n edges+=line.split(\" \")(0).toInt-1\n edges+=line.split(\" \")(1).toInt-1\n }\n getNumberOfPossibleRestaurants(n,m,cats,edges)\n }\n\n def getNumberOfPossibleRestaurants(n:Int,m:Int,cats:Array[Int],edges:ArrayBuffer[Int]):Int={\n val graph=getDirectedGraph(edges,n)\n val cou=Cou()\n if(cats(0)==0)\n postOrder(graph,cats,0,0,m,cou)\n else\n postOrder(graph,cats,0,1,m,cou)\n println(cou.c)\n return cou.c\n }\n\n def postOrder(graph:Array[ArrayBuffer[Int]],cats:Array[Int],n:Int,curM:Int,m:Int,cou: Cou):Unit={\n if(curM<=m){\n if(graph(n).length==0){\n cou.c+=1\n }else{\n for(i<- 0 until graph(n).length){\n if(cats(graph(n)(i))==0) {\n postOrder(graph, cats, graph(n)(i), 0, m, cou)\n }else{\n postOrder(graph, cats, graph(n)(i), curM+1, m, cou)\n }\n }\n }\n }\n }\n\n def getDirectedGraph(edges: ArrayBuffer[Int], N: Int): Array[ArrayBuffer[Int]] = {\n //Adjacency list representation is used to represent the graph\n\n //We have N vertices\n val graph = new Array[ArrayBuffer[Int]](N)\n\n //Every vertices can be associated to multiple adjacent vertices\n for (i <- 0 until N) {\n graph(i)= new ArrayBuffer[Int]()\n }\n\n //Every pair array elements represent a edge\n for (i <- 0 until edges.length by 2) {\n addDirectedEdge(graph, edges(i), edges(i + 1))\n }\n\n return graph\n }\n\n def addDirectedEdge(graph: Array[ArrayBuffer[Int]], u: Int, v: Int): Unit = {\n //It is a directed graph, so the an edge a to b can be used to travel from a to b\n graph(u) += v\n }\n}\n"}, {"source_code": "object C580 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val isCat = readInts(n)\n val vis = Array.fill(n)(false)\n val _G = Array.fill(n)(collection.mutable.ArrayBuffer.empty[Int])\n for(i <- 0 until n-1){\n val in = readInts(2).sorted\n _G(in(0)-1) += in(1)-1\n }\n val G = _G.map(_.toArray)\n //bfs\n val q = collection.mutable.Queue.empty[(Int, Int)]\n q.enqueue((0, 0))\n while(q.nonEmpty) {\n val (top, cats) = q.dequeue()\n if(isCat(top) == 1) {\n if(cats+1 <= m) {\n vis(top) = true\n for(i <- G(top)) {\n q.enqueue((i, cats+1))\n }\n }\n } else {\n vis(top) = true\n for(i <- G(top)) {\n q.enqueue((i, 0))\n }\n }\n }\n var res = 0\n for(i <- 0 until n) {\n if(G(i).isEmpty && vis(i)) {\n res += 1\n }\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object C580 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val isCat = readInts(n)\n val vis = Array.fill(n)(false)\n val _G = Array.fill(n)(collection.mutable.ArrayBuffer.empty[Int])\n for(i <- 0 until n-1){\n val in = readInts(2)\n _G(in(0)-1) += in(1)-1\n }\n val G = _G.map(_.toArray)\n //bfs\n val q = collection.mutable.Queue.empty[(Int, Int)]\n q.enqueue((0, 0))\n while(q.nonEmpty) {\n val (top, cats) = q.dequeue()\n if(isCat(top) == 1) {\n if(cats+1 <= m) {\n vis(top) = true\n for(i <- G(top)) {\n q.enqueue((i, cats+1))\n }\n }\n } else {\n vis(top) = true\n for(i <- G(top)) {\n q.enqueue((i, 0))\n }\n }\n }\n var res = 0\n for(i <- 0 until n) {\n if(G(i).isEmpty && vis(i)) {\n res += 1\n }\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _580C extends CodeForcesApp[Int]({scanner => import scanner._\n val (n, m) = (nextInt, nextInt)\n val hasCats = IndexedSeq.fill(n)(nextInt == 1)\n val tree = map[Int].to(Set.empty[Int])\n repeat(n-1) {\n val (i, j) = (nextInt, nextInt)\n val (u, v) = (i min j, i max j)\n tree(u) = tree(u) + v\n }\n\n def solve(pos: Int, prevCats: Int): Int = {\n val cats = if (hasCats(pos - 1)) 1 + prevCats else 0\n tree(pos).toSeq match {\n case _ if cats > m => 0\n case Nil => 1\n case children => children.map(solve(_, cats)).sum\n }\n }\n\n solve(1, 0)\n}) {\n override def format(result: Result) = super.format(result)\n}\n/****************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n final def map[A] = new {\n import scala.collection.mutable.{Map => Dict}\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _580C extends CodeForcesApp[Int]({scanner => import scanner._\n val (n, m) = (nextInt, nextInt)\n val hasCats = IndexedSeq.fill(n)(nextInt == 1)\n val tree = mutable.Map.empty[Int, Set[Int]] withDefaultValue Set.empty[Int]\n repeat(n-1) {\n val (i, j) = (nextInt, nextInt)\n tree(i) = tree(i) + j\n }\n\n def solve(pos: Int, prevCats: Int): Int = {\n val cats = if (hasCats(pos - 1)) 1 + prevCats else 0\n if (cats > m) { // this path has > m consecutive cats, no point continuing\n 0\n } else {\n val children = tree(pos)\n if (children.isEmpty) { // a leaf node\n 1\n } else { // an inner node\n children.toSeq.map(solve(_, cats)).sum\n }\n }\n }\n\n solve(1, 0)\n}) {\n override def format(result: Result) = super.format(result)\n}\n/****************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n import scala.collection.mutable.{Map => Dict}\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0\n final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n}\n"}], "src_uid": "875e7048b7a254992b9f62b9365fcf9b"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val nk = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt)\n val neg = a.count(_ == -1)\n val pos = a.count(_ == 1)\n val min = neg.min(pos)\n \n for (_ <- 1 to nk(1)) {\n val ix = readLine().split(\" \").map(_.toInt)\n val i0 = ix(0)\n val i1 = ix(1)\n if ((i1 - i0 + 1) % 2 == 1) println(\"0\")\n else if ((i1 - i0 + 1) / 2 <= min) println(\"1\")\n else println(\"0\")\n }\n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt)\n val countPlus = data.count(_ == 1)\n val countMinus = n - countPlus\n val res = (1 to m).map{ _ =>\n val Array(l, r) = in.next().split(\" \").map(_.toInt)\n val distance = r - l + 1\n if (distance % 2 == 1 || (distance / 2 > countPlus || distance / 2 > countMinus))\n 0\n else\n 1\n }\n println(res.mkString(\"\\n\"))\n}"}, {"source_code": "\nobject Main {\n def main(args: Array[String]) = {\n val m = readLine.dropWhile(_ != ' ').tail.toInt\n var a = 0\n var b = 0\n\n for(x <- readLine.split(\" \"))\n x.toInt match {\n case 1 => a += 1\n case -1 => b += 1\n case _ => \n }\n\n for(i <- 1 to m) {\n val line = readLine\n val l = line.takeWhile(_ != ' ').toInt\n val r = line.dropWhile(_ != ' ').tail.toInt\n val x = r - l + 1\n\n if(x % 2 == 0 && x / 2 <= Math.min(a, b))\n println(1)\n else\n println(0)\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N, M = sc.nextInt\n val as = Array.fill(N)(sc.nextInt)\n val max = 2 * (as.count(_ == 1) min as.count(_ == -1))\n\n def isEven(n: Int): Boolean = n % 2 == 0\n\n for (i <- 0 until M) {\n val l, r = sc.nextInt\n val y = r - l + 1\n val res = if (y > 0 && y <= max && isEven(y)) 1 else 0\n out.println(res)\n }\n\n out.close\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt)\n val countPlus = data.count(_ == 1)\n val countMinus = n - countPlus\n val res = (1 to m).map{ _ =>\n val Array(l, r) = in.next().split(\" \").map(_.toInt)\n val distance = r - l + 1\n if (distance % 2 == 1 || (distance / 2 < countPlus || distance / 2 < countMinus))\n 0\n else\n 1\n }\n println(res.mkString(\"\\n\"))\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val nk = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt)\n val neg = a.count(_ == -1)\n val pos = a.count(_ == 1)\n val min = neg.min(pos)\n \n for (_ <- 1 to nk(1)) {\n val ix = readLine().split(\" \").map(_.toInt)\n val i0 = ix(0)\n val i1 = ix(1)\n if ((i1 - i0 + 1) % 2 == 1) println(\"0\")\n else if ((i1 - i1 + 1) / 2 <= min) println(\"1\")\n else println(\"0\")\n }\n }\n}"}], "src_uid": "deeb49969ac4bc4f1c7d76b89ac1402f"} {"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n val Array(n, c) = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt)\n val intervals = a.zip(a.tail).map(x => x._2 - x._1)\n val ans = intervals.foldLeft(1)((sum, x) => if (x <= c) sum + 1 else 1)\n println(ans)\n}", "positive_code": [{"source_code": "//package merofeev.contests.codeforces.rnd372\n\nimport java.util.Scanner\n\n/**\n * @author erofeev \n * @since 17.09.16\n */\nobject A {\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n val stuff: Array[String] = in.nextLine().split(\" \")\n val words: Int = stuff(0).toInt\n val c: Int = stuff(1).toInt\n val secs = in.nextLine().split(\" \").map(_.toInt)\n\n if (words == 1) {\n println(1)\n return\n }\n var res = 1\n for (i <- 1 until secs.length) {\n if (secs(i) - secs(i - 1) <= c) {\n res += 1\n } else {\n res = 1\n }\n }\n println(res)\n }\n}"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val Array(n, c) = lines.next().split(' ').map(_.toInt)\n val line = lines.next().split(' ').map(_.toInt)\n val (_, amount) = line.foldLeft(0, 0) {\n case ((b, count), a) if a - b > c => (a, 1)\n case ((b, count), a) => (a, count + 1)\n }\n println(amount)\n}"}, {"source_code": "object A716 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, c) = readLongs(2)\n val input = readLongs(n.toInt)\n var curr = 0\n for(i <- 0 until n.toInt) {\n if(i == 0)\n curr += 1\n else if(input(i) - input(i-1) > c) {\n curr = 1\n } else {\n curr += 1\n }\n }\n\n println(curr)\n }\n}"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, c) = readInts(2)\n val ts = readInts(n)\n\n var cnt = 1\n var t0 = ts.head\n\n for (t <- ts.tail) {\n if (t - t0 > c) cnt = 0\n cnt += 1\n t0 = t\n }\n\n println(cnt)\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _716A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n, c = read[Int]\n val data = read[Seq, Int](n)\n\n var ans = 1\n var t1: Int = data.head\n\n data.drop(1) foreach {t2 =>\n if ((t2 - t1) > c) ans = 0\n ans += 1\n t1 = t2\n }\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object CF372_1B extends App {\n val nc = readLine.split(\" \").map(_.toInt)\n val T = readLine.split(\" \").map(_.toInt)\n var r = 0\n var last = -nc(1)\n for (t <- T) {\n r = if (t - last > nc(1)) 1 else (r+1) \n last = t\n }\n println(r)\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n // \n // val s = sc.nextLine()\n // val str = sc.next()\n\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val c = sc.nextInt()\n\n var now = sc.nextInt()\n var cnt = 1\n for(i <- 1 until n){\n val t = sc.nextInt()\n\n if(t - now > c){\n cnt = 1\n }\n else\n cnt += 1\n\n now = t\n }\n\n println(cnt)\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject _372A extends App {\n val Array(n, c) = readLine().split(\" \") map (_.toInt)\n val T = readLine().split(\" \") map (_.toInt)\n\n var counter = 0\n var prev = 0\n for (i <- 0 until T.length) {\n if (T(i) - prev > c) {\n counter = 1\n } else {\n counter += 1\n }\n prev = T(i)\n }\n\n println(counter)\n}"}], "negative_code": [{"source_code": "//package merofeev.contests.codeforces.rnd372\n\nimport java.util.Scanner\n\n/**\n * @author erofeev \n * @since 17.09.16\n */\nobject A {\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n val stuff: Array[String] = in.nextLine().split(\" \")\n val words: Int = stuff(0).toInt\n val c: Int = stuff(1).toInt\n val secs = in.nextLine().split(\" \").map(_.toInt)\n\n if (words == 1) {\n println(1)\n return\n }\n var res = 0\n for (i <- 1 until secs.length) {\n if (secs(i) - secs(i - 1) <= c) {\n res += 1\n } else {\n res = 1\n }\n }\n println(res)\n }\n}"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val Array(n, c) = lines.next().split(' ').map(_.toInt)\n val line = lines.next().split(' ').map(_.toInt)\n val (_, amount) = line.foldLeft(0, 0) {\n case ((b, count), a) if b - a > c => (a, 1)\n case ((b, count), a) => (a, count + 1)\n }\n println(amount)\n}"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _716A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n, c = read[Int]\n val data = read[Seq, Int](n)\n\n val ans = data.sliding(2).foldLeft(0) {\n case (prev, Seq(t1, t2)) if (t2 - t1) > c => 1\n case (prev, t) if t.length <= 2 => prev + 1\n case (prev, x) => throw new IllegalArgumentException(s\"No idea what $x is\")\n }\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _716A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val (n, c) = read[(Int, Long)]\n val data = read[Seq, Int](n)\n\n val ans = data.sliding(2).foldLeft(0) {\n case (prev, Seq(t1, t2)) if (t2 - t1) > c => 1\n case (prev, _) => prev + 1\n }\n\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "fb58bc3be4a7a78bdc001298d35c6b21"} {"source_code": "object B extends App {\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val (ak, ar) = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted.splitAt(k)\n val bk = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted(Ordering.Int.reverse).take(k)\n\n val ans = ar.sum + (bk ++ ak).sorted(Ordering.Int.reverse).take(k).sum\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "//package codeforces.contests._1353\n\nobject TwoArraysAndSwaps {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(n, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val a, b = io.StdIn.readLine.split(\" \").map(_.toInt).sorted\n println {\n a.slice(k, n).sum + (a.slice(0, k) ++ b.slice(n - k, n)).sorted(Ordering.Int.reverse).take(k).sum\n }\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject B {\n\n def solution(n: Int, k: Int, a0: Seq[Int], b0: Seq[Int]): Int = {\n val a = a0.sorted.toArray\n val b = b0.sorted.reverse.toArray\n var i = 0\n while (i < k && a(i) < b(i)) {\n a(i) = b(i)\n i += 1\n }\n a.sum\n }\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val Seq(n, k) = readLine.split(\" \").toSeq.map(_.toInt)\n val a = readLine.split(\" \").toSeq.map(_.toInt)\n val b = readLine.split(\" \").toSeq.map(_.toInt)\n println(solution(n, k, a, b))\n }\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.math.max\nimport scala.math.min\nimport scala.reflect.ClassTag\nimport scala.collection.immutable._\n\n\nobject Main {\n\tdef main(args: Array[String]): Unit = {\n\t\ttry {\n\t\t\tval (in, out) =\n\t\t\t\tif (isOnlineJudge) {\n\t\t\t\t\t(\n\t\t\t\t\t\tnew FastScanner(new InputStreamReader(System.in)),\n\t\t\t\t\t\tnew PrintWriter(System.out)\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\t(\n\t\t\t\t\t\tnew FastScanner(new FileReader(new File(\"problem.in\"))),\n\t\t\t\t\t\tnew PrintWriter(new File(\"problem.out\"))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\tnew CF644(in, out).solve()\n\t\t\tout.flush()\n\t\t\tout.close()\n\t\t} catch {\n\t\t\tcase e: IOException => e.printStackTrace()\n\t\t}\n\t}\n \n\tprivate[this] val isOnlineJudge = true\n \n\tclass FastScanner(val streamReader: InputStreamReader) {\n\t\tprivate[this] val reader = new BufferedReader(streamReader, 32768)\n\t\tprivate[this] var tokenizer: StringTokenizer = _\n \n\t\t@inline private[this] final def next(): String = {\n\t\t\twhile (tokenizer == null || !tokenizer.hasMoreTokens)\n\t\t\t\ttokenizer = new StringTokenizer(reader.readLine)\n\t\t\ttokenizer.nextToken\n\t\t}\n \n\t\tdef nextInt(): Int = Integer.parseInt(next())\n \n\t\tdef nextLong(): Long = java.lang.Long.parseLong(next())\n \n\t\tdef nextChar(): Char = next().charAt(0)\n \n\t\tdef ni(): Int = nextInt()\n \n\t\tdef nl(): Long = nextLong()\n \n\t\tdef nc(): Char = nextChar()\n \n\t\tdef ns(): String = next()\n \n\t\tdef ns(n: Int): Array[Char] = ns().toCharArray\n \n\t\tdef na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n \n\t\tdef na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n\t\t\tval A1, A2 = Array.ofDim[Int](n)\n\t\t\tREP(n) { i =>\n\t\t\t\tA1(i) = ni() + offset\n\t\t\t\tA2(i) = ni() + offset\n\t\t\t}\n\t\t\t(A1, A2)\n\t\t}\n \n\t\tdef nm(n: Int, m: Int): Array[Array[Int]] = {\n\t\t\tval A = Array.ofDim[Int](n, m)\n\t\t\tREP(n) { i =>\n\t\t\t\tREP(m) { j =>\n\t\t\t\t\tA(i)(j) = ni()\n\t\t\t\t}\n\t\t\t}\n\t\t\tA\n\t\t}\n \n\t\tdef nal(n: Int): Array[Long] = map(n)(_ => nl())\n \n\t\tdef nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n\t}\n \n\tdef REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n\t\tvar i = offset\n\t\tval N = n + offset\n\t\twhile (i < N) {\n\t\t\tf(i);\n\t\t\ti += 1\n\t\t}\n\t}\n \n\tdef REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n\t\tvar i = n - 1 + offset\n\t\twhile (i >= offset) {\n\t\t\tf(i);\n\t\t\ti -= 1\n\t\t}\n\t}\n \n\tdef TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n\t\tREP(to - from + 1, from)(f)\n\t}\n \n\tdef map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n\t\tval res = Array.ofDim[A](n)\n\t\tREP(n)(i => res(i) = f(i + offset))\n\t\tres\n\t}\n \n\tdef sumL(as: Array[Int]): Long = {\n\t\tvar s = 0L\n\t\tREP(as.length)(i => s += as(i))\n\t\ts\n\t}\n \n\tdef cumSum(as: Array[Int]): Array[Long] = {\n\t\tval cum = Array.ofDim[Long](as.length + 1)\n\t\tREP(as.length) { i =>\n\t\t\tcum(i + 1) = cum(i) + as(i)\n\t\t}\n\t\tcum\n\t}\n}\n \nclass CF644 (fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n \n\timport Main._\n\timport fScanner._\n \n\t// def solve(): Unit = {\n\t// \tval T = ni()\n\t// \tfor(i <- 0 until T){\n\t// \tvar ans : Int = 1000\n\t// \t\tval n = ni()\n\t// \t\tvar list: List[Int] = List()\n\t// \t\tfor(j <- 0 until n){\n\t// \t\t\tval cu:Int = ni()\n\t// \t\t\tfor( x <- list)\n\t// \t\t\t\tans = ans.min( ( cu - x ).max(x - cu) )\n\t// \t\t\tlist = cu::\tlist\n\t// \t\t}\n\t// \t\tout.println(ans)\n\t// \t}\n\t// }\n\n\tdef solve(): Unit ={\t\n\t\tval T = ni()\n\t\tfor(i <- 0 until T){\n\t\t\tval n = ni()\n\t\t\tval k = ni()\n\t\t\tvar A : Vector[Int] = Vector()\n\t\t\tvar B : Vector[Int] = Vector()\n\n\t\t\tfor(j <- 0 until n){\n\t\t\t\tval a = ni()\n\t\t\t\tA = A :+ a\n\t\t\t}\n\t\t\tfor(j <- 0 until n){\n\t\t\t\tval b = ni()\n\t\t\t\tB = B :+ b\n\t\t\t}\n\t\t\tA = A.sortWith(_ < _)\n\t\t\tB = B.sortWith(_ > _)\n\n\t\t\tvar j:Int = 0\n\t\t\tvar ans:Int = 0\n\t\t\t// println(A, B)\n\t\t\tfor( (p, q) <- (A zip B) ){\n\t\t\t\t// println(p, q)\n\t\t\t\tif(j < k){\n\t\t\t\t\tans = ans + max(p, q)\n\t\t\t\t}\n\t\t\t\telse ans = ans + p\n\n\t\t\t\tj = j+1\n \t\t\t}\n\n \t\t\tout.println(ans)\n\t\t}\n\t}\n}\n"}, {"source_code": "import java.util\n\nobject ProblemB extends App {\n\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n import scala.collection.mutable\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n\n for (_ <- 1 to t) {\n val m = in.nextInt()\n var k = in.nextInt()\n val a1 = new Array[Int](m)\n val a2 = new Array[Int](m)\n for (i <- 0 until m) {\n a1(i) = in.nextInt()\n }\n for (i <- 0 until m) {\n a2(i) = in.nextInt()\n }\n\n util.Arrays.sort(a1)\n util.Arrays.sort(a2)\n\n var i = 0\n\n while (i < m && k > 0 && a1(i) < a2(m - i - 1)) {\n a1(i) = a2(m - i - 1)\n i = i + 1\n k = k - 1\n }\n\n println(a1.sum)\n\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.math.max\nimport scala.math.min\nimport scala.reflect.ClassTag\nimport scala.collection.immutable._\n\n\nobject Main {\n\tdef main(args: Array[String]): Unit = {\n\t\ttry {\n\t\t\tval (in, out) =\n\t\t\t\tif (isOnlineJudge) {\n\t\t\t\t\t(\n\t\t\t\t\t\tnew FastScanner(new InputStreamReader(System.in)),\n\t\t\t\t\t\tnew PrintWriter(System.out)\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\t(\n\t\t\t\t\t\tnew FastScanner(new FileReader(new File(\"problem.in\"))),\n\t\t\t\t\t\tnew PrintWriter(new File(\"problem.out\"))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\tnew CF644(in, out).solve()\n\t\t\tout.flush()\n\t\t\tout.close()\n\t\t} catch {\n\t\t\tcase e: IOException => e.printStackTrace()\n\t\t}\n\t}\n \n\tprivate[this] val isOnlineJudge = false\n \n\tclass FastScanner(val streamReader: InputStreamReader) {\n\t\tprivate[this] val reader = new BufferedReader(streamReader, 32768)\n\t\tprivate[this] var tokenizer: StringTokenizer = _\n \n\t\t@inline private[this] final def next(): String = {\n\t\t\twhile (tokenizer == null || !tokenizer.hasMoreTokens)\n\t\t\t\ttokenizer = new StringTokenizer(reader.readLine)\n\t\t\ttokenizer.nextToken\n\t\t}\n \n\t\tdef nextInt(): Int = Integer.parseInt(next())\n \n\t\tdef nextLong(): Long = java.lang.Long.parseLong(next())\n \n\t\tdef nextChar(): Char = next().charAt(0)\n \n\t\tdef ni(): Int = nextInt()\n \n\t\tdef nl(): Long = nextLong()\n \n\t\tdef nc(): Char = nextChar()\n \n\t\tdef ns(): String = next()\n \n\t\tdef ns(n: Int): Array[Char] = ns().toCharArray\n \n\t\tdef na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n \n\t\tdef na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n\t\t\tval A1, A2 = Array.ofDim[Int](n)\n\t\t\tREP(n) { i =>\n\t\t\t\tA1(i) = ni() + offset\n\t\t\t\tA2(i) = ni() + offset\n\t\t\t}\n\t\t\t(A1, A2)\n\t\t}\n \n\t\tdef nm(n: Int, m: Int): Array[Array[Int]] = {\n\t\t\tval A = Array.ofDim[Int](n, m)\n\t\t\tREP(n) { i =>\n\t\t\t\tREP(m) { j =>\n\t\t\t\t\tA(i)(j) = ni()\n\t\t\t\t}\n\t\t\t}\n\t\t\tA\n\t\t}\n \n\t\tdef nal(n: Int): Array[Long] = map(n)(_ => nl())\n \n\t\tdef nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n\t}\n \n\tdef REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n\t\tvar i = offset\n\t\tval N = n + offset\n\t\twhile (i < N) {\n\t\t\tf(i);\n\t\t\ti += 1\n\t\t}\n\t}\n \n\tdef REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n\t\tvar i = n - 1 + offset\n\t\twhile (i >= offset) {\n\t\t\tf(i);\n\t\t\ti -= 1\n\t\t}\n\t}\n \n\tdef TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n\t\tREP(to - from + 1, from)(f)\n\t}\n \n\tdef map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n\t\tval res = Array.ofDim[A](n)\n\t\tREP(n)(i => res(i) = f(i + offset))\n\t\tres\n\t}\n \n\tdef sumL(as: Array[Int]): Long = {\n\t\tvar s = 0L\n\t\tREP(as.length)(i => s += as(i))\n\t\ts\n\t}\n \n\tdef cumSum(as: Array[Int]): Array[Long] = {\n\t\tval cum = Array.ofDim[Long](as.length + 1)\n\t\tREP(as.length) { i =>\n\t\t\tcum(i + 1) = cum(i) + as(i)\n\t\t}\n\t\tcum\n\t}\n}\n \nclass CF644 (fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n \n\timport Main._\n\timport fScanner._\n \n\t// def solve(): Unit = {\n\t// \tval T = ni()\n\t// \tfor(i <- 0 until T){\n\t// \tvar ans : Int = 1000\n\t// \t\tval n = ni()\n\t// \t\tvar list: List[Int] = List()\n\t// \t\tfor(j <- 0 until n){\n\t// \t\t\tval cu:Int = ni()\n\t// \t\t\tfor( x <- list)\n\t// \t\t\t\tans = ans.min( ( cu - x ).max(x - cu) )\n\t// \t\t\tlist = cu::\tlist\n\t// \t\t}\n\t// \t\tout.println(ans)\n\t// \t}\n\t// }\n\n\tdef solve(): Unit ={\t\n\t\tval T = ni()\n\t\tfor(i <- 0 until T){\n\t\t\tval n = ni()\n\t\t\tval k = ni()\n\t\t\tvar A : Vector[Int] = Vector()\n\t\t\tvar B : Vector[Int] = Vector()\n\n\t\t\tfor(j <- 0 until n){\n\t\t\t\tval a = ni()\n\t\t\t\tA = A :+ a\n\t\t\t}\n\t\t\tfor(j <- 0 until n){\n\t\t\t\tval b = ni()\n\t\t\t\tB = B :+ b\n\t\t\t}\n\t\t\tA = A.sortWith(_ < _)\n\t\t\tB = B.sortWith(_ > _)\n\n\t\t\tvar j:Int = 0\n\t\t\tvar ans:Int = 0\n\t\t\t// println(A, B)\n\t\t\tfor( (p, q) <- (A zip B) ){\n\t\t\t\t// println(p, q)\n\t\t\t\tif(j < k){\n\t\t\t\t\tans = ans + max(p, q)\n\t\t\t\t}\n\t\t\t\telse ans = ans + p\n\n\t\t\t\tj = j+1\n \t\t\t}\n\n \t\t\tout.println(ans)\n\t\t}\n\t}\n}\n"}, {"source_code": "object B extends App {\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val (ak, ar) = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted.splitAt(k)\n val bk = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted(Ordering.Int.reverse).take(k)\n\n val bt = bk.takeWhile(_ > ak.head)\n val at = ak.drop(bt.length)\n val ans = ar.sum + bt.sum + at.sum\n\n println(ans)\n }\n}\n"}], "src_uid": "7c2337c1575b4a62e062fc9990c0b098"} {"source_code": "import io.StdIn._\nimport scala.collection.mutable._\n\nobject Solution extends App {\n var a = readLine()\n var b = readLine()\n \n var alen = a.length()\n var blen = b.length()\n \n if ( alen < blen ) {\n \n val temp = \"0\" * ( blen - alen ) \n a = temp + a\n \n }\n if ( alen > blen ) {\n \n val temp = \"0\" * ( alen - blen )\n b = temp + b\n \n }\n \n \n \n if ( a > b ) {\n println ( \">\" ) \n }\n if ( a == b ) {\n println ( \"=\" ) \n }\n if ( a < b ) {\n println ( \"<\" ) \n }\n\n}", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val a = in.next().dropWhile(_ == '0')\n val b = in.next().dropWhile(_ == '0')\n if (a.length > b.length)\n println('>')\n else if (a.length < b.length)\n println('<')\n else {\n val f = a.zip(b).find(i => i._1 != i._2)\n if (f.isEmpty)\n println('=')\n else if (f.get._1 < f.get._2)\n println('<')\n else\n println('>')\n }\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val a = in.next().dropWhile(_ == '0')\n val b = in.next().dropWhile(_ == '0')\n if (a.length < b.length)\n println('>')\n else if (a.length < b.length)\n println('<')\n else {\n val f = a.zip(b).find(i => i._1 != i._2)\n if (f.isEmpty)\n println('=')\n else if (f.get._1 < f.get._1)\n println('<')\n else\n println('>')\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val a = in.next().dropWhile(_ == '0')\n val b = in.next().dropWhile(_ == '0')\n if (a.length > b.length)\n println('>')\n else if (a.length < b.length)\n println('<')\n else {\n val f = a.zip(b).find(i => i._1 != i._2)\n if (f.isEmpty)\n println('=')\n else if (f.get._1 < f.get._1)\n println('<')\n else\n println('>')\n }\n}"}], "src_uid": "fd63aeefba89bef7d16212a0d9e756cd"} {"source_code": "import java.io.FileOutputStream\nimport java.io.FileInputStream\nimport java.io.PrintStream\n\n/**\n * Created by octavian on 16/01/2016.\n */\nobject GCode {\n\n def main (args: Array[String]) {\n //System.setIn(new FileInputStream(\"src/gcode.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"src/gcode.out\")))\n val n = readInt()\n val nums: Array[String] = readLine().split(\" \")\n println(product(n, nums))\n }\n\n def beautiful(nr: String): Boolean = {\n var ones = 0\n for(c <- nr) {\n if(c == '1') {\n ones += 1\n }\n if(c != '0' && c != '1') {\n return false\n }\n }\n return (ones <= 1)\n }\n\n //assumes - there is at least one element different from 0\n /*def relevantZeros(nr: String): Int = {\n for(i <- 0 until nr.length) {\n if(nr(i) != 0) {\n return i\n }\n }\n return 0\n }*/\n\n def product(n: Int, nums: Array[String]): String = {\n var result = Vector.empty[String]\n for(i <- 0 until n) {\n //println(\"checking \" + nums(i))\n if(nums(i)(0) == '0') {\n return \"0\"\n }\n if(beautiful(nums(i)) && nums(i).length - 1 > 0) {\n result :+= \"0\" * (nums(i).length - 1)//relevantZeros(nums(i).reverse)\n //println(\"result is \" + result.mkString(\"\"))\n }\n else if(!beautiful(nums(i))) {\n result +:=nums(i)\n }\n }\n //println(\"result(0)(0) is \" + result(0)(0))\n val strRep = result.mkString(\"\")\n if(strRep.length == 0 || strRep(0) == '0') {\n result +:= \"1\"\n }\n return result.mkString(\"\")\n }\n\n}\n", "positive_code": [{"source_code": "// object Main\nimport java.io.{IOException, InputStream, PrintWriter}\nimport java.util.InputMismatchException\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject Main {\n\n def solveCase(caseNo: Int, in: InputReader, out: PrintWriter): Unit = {\n val n = in.nextInt()\n var num = \"1\"\n var isZero = false\n var zeroCount = 0\n for (_ <- 1 to n) {\n val x = in.next()\n if (x == \"0\") {\n isZero = true\n } else if (x == \"1\" + \"0\" * (x.length - 1)) {\n zeroCount += x.length - 1\n } else {\n num = x\n }\n }\n if (isZero) {\n println(0)\n } else {\n println(num.toString + \"0\" * zeroCount)\n }\n\n\n }\n\n def solve(in: InputReader, out: PrintWriter): Unit = {\n solveCase(1, in, out)\n// val caseCount = in.nextInt()\n// for (caseNo <- 1 to caseCount) {\n// solveCase(caseNo, in, out)\n// }\n }\n\n def main(args: Array[String]) {\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n in.close()\n out.close()\n }\n}\n\nclass InputReader(val inputStream: InputStream) {\n val buf = new Array[Byte](1 << 16)\n var curChar = 0\n var numChars = 0\n\n def read(): Int = {\n if (numChars == -1) {\n throw new InputMismatchException()\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => throw new InputMismatchException()\n }\n if (numChars <= 0)\n return -1\n }\n curChar += 1\n buf(curChar - 1)\n }\n\n def peek(): Int = {\n if (numChars == -1) {\n return -1\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => return -1\n }\n if (numChars <= 0)\n return -1\n }\n buf(curChar)\n }\n\n def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n\n def nextInt(): Int = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextLong(): Long = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0l\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def next(): String = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n val res = new StringBuilder()\n do {\n res += c.toChar\n c = read()\n } while (!isSpaceChar(c))\n res.toString()\n }\n\n def nextChar(): Char = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n c.toChar\n }\n\n //noinspection AccessorLikeMethodIsEmptyParen\n def hasNext(): Boolean = {\n var value = peek()\n do {\n read()\n value = peek()\n } while (isSpaceChar(value) && value != -1)\n value != -1\n }\n\n def rawNextLine(): String = {\n val builder = new StringBuilder\n var c = read()\n while (c != '\\n' && c != -1) {\n if (c != '\\r')\n builder += c.toChar\n c = read()\n }\n builder.toString()\n }\n\n def nextLine(): String = {\n var s = rawNextLine()\n while (s.trim().length == 0) s = rawNextLine()\n s\n }\n\n def nextDouble(): Double = {\n next().toDouble\n }\n\n def close(): Unit = {\n inputStream.close()\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ')\n if (data.contains(\"0\"))\n println(0)\n else {\n val nonB = data.find(i =>\n i.head != '1' || !i.tail.forall(_ == '0')\n )\n val zeroCount = data.foldLeft(0) {\n case (acc, str) if nonB.contains(str) => acc\n case (acc, str) => acc + str.count(_ == '0')\n }\n\n println(nonB.getOrElse(1) + \"0\" * zeroCount)\n }\n}"}, {"source_code": "\nimport java.io.InputStreamReader\nimport java.io.BufferedReader\n\n/**\n * @author pvasilyev\n * @since 25 Jun 2016\n */\nobject B614 extends App {\n\n def isBeautiful(a: String): Boolean = {\n if (\"0\" equals a) {\n return true\n }\n val s = a\n if (s.charAt(0) != '1') {\n return false\n }\n for (i <- 1 until s.length) {\n if (s.charAt(i) != '0') {\n return false\n }\n }\n\n true\n }\n\n def solve() = {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val n = reader.readLine().toInt\n var nonBeautiful = \"\"\n var zeros = 0\n var isZero = false\n val aa: Array[String] = reader.readLine().split(\" \")\n for (i <- 0 until n) {\n val a = aa(i)\n if (!isBeautiful(a)) {\n nonBeautiful = a\n } else {\n val z = a.length - 1\n if (z != 0) {\n zeros += z\n } else if (\"0\" equals a) {\n isZero = true\n }\n }\n }\n if (isZero) {\n println(\"0\")\n } else if (!(\"\" equals nonBeautiful)) {\n println(nonBeautiful + (\"0\" * zeros))\n } else {\n println(\"1\" + (\"0\" * zeros))\n }\n }\n\n solve()\n\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _614B extends CodeForcesApp {\n override type Result = String\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val nums = List.fill(nextInt())(nextString())\n multiply(nums, mutable.StringBuilder.newBuilder, false)\n }\n\n @tailrec\n def multiply(nums: List[String], sb: mutable.StringBuilder, prefixFound: Boolean): String = nums match {\n case Nil => if (prefixFound) sb.toString() else 1 + sb.toString()\n case \"0\" :: _ => \"0\"\n case n :: ns if n.replace(\"0\", \"\") == \"1\" => multiply(ns, sb.append(n.tail), prefixFound)\n case n :: ns => multiply(ns, sb.insert(0, n), true)\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n val mod: Int = 1000000007\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}], "negative_code": [{"source_code": "import java.io.FileOutputStream\nimport java.io.FileInputStream\nimport java.io.PrintStream\n\n/**\n * Created by octavian on 16/01/2016.\n */\nobject GCode {\n\n def main (args: Array[String]) {\n //System.setIn(new FileInputStream(\"src/gcode.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"src/gcode.out\")))\n val n = readInt()\n val nums: Array[String] = readLine().split(\" \")\n println(product(n, nums))\n }\n\n def beautiful(nr: String): Boolean = {\n var ones = 0\n for(c <- nr) {\n if(c == '1') {\n ones += 1\n }\n if(c != '0' && c != '1') {\n return false\n }\n }\n return (ones == 1)\n }\n\n //assumes - there is at least one element different from 0\n /*def relevantZeros(nr: String): Int = {\n for(i <- 0 until nr.length) {\n if(nr(i) != 0) {\n return i\n }\n }\n return 0\n }*/\n\n def product(n: Int, nums: Array[String]): String = {\n var result = Vector.empty[String]\n for(i <- 0 until n) {\n if(nums(i)(0) == '0') {\n return \"0\"\n }\n if(beautiful(nums(i)) && nums(i).length - 1 > 0) {\n result :+= \"0\" * (nums(i).length - 1)//relevantZeros(nums(i).reverse)\n }\n else if(!beautiful(nums(i))) {\n result +:=nums(i)\n }\n }\n return result.mkString(\"\")\n }\n\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n println(data.foldLeft(0l){case (a, e) => a * e})\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ')\n if (data.contains(\"0\"))\n println(0)\n else {\n val nonB = data.find(i =>\n i.head != '1' || i.tail.exists(_ == '0')\n )\n val zeroCount = data.foldLeft(0) {\n case (acc, str) if nonB.contains(str) => acc\n case (acc, str) => acc + str.count(_ == '0')\n }\n\n println(nonB.getOrElse(1) + \"0\" * zeroCount)\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n println(data.product)\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _614B extends CodeForcesApp {\n override type Result = String\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val nums = List.fill(nextInt())(nextString())\n multiply(nums, mutable.StringBuilder.newBuilder)\n }\n\n @tailrec\n def multiply(nums: List[String], sb: mutable.StringBuilder): String = nums match {\n case Nil => sb.toString()\n case \"0\" :: _ => \"0\"\n case n :: ns if n.replace(\"0\", \"\") == \"1\" => multiply(ns, sb.append(n.tail))\n case n :: ns => multiply(ns, sb.insert(0, n))\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n val mod: Int = 1000000007\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}], "src_uid": "9b1b082319d045cf0ec6d124f97a8184"} {"source_code": "object DefiningMacros extends App {\n sealed trait Term\n sealed trait Expr \n\n case object LeftParen extends Term\n case object RightParen extends Term\n case class Operator(op: Char) extends Term\n\n case class Number(n: Int) extends Term with Expr\n case class Var(name: String) extends Term with Expr\n\n case class Paren(sub: Expr) extends Expr\n case class BinOp(op: Operator, left: Expr, right: Expr) extends Expr\n\n object Term {\n def apply(s: String): Term = s match {\n case \"(\" => LeftParen\n case \")\" => RightParen\n case _ if \"+-*/\" contains s(0) => Operator(s(0))\n case _ if Character.isLetter(s(0)) => Var(s)\n case _ if Character.isDigit(s(0)) => Number(s.toInt)\n }\n }\n\n object Expr {\n val preds = List(Character.isLetter _, Character.isDigit _)\n\n def getPriority(expr: Expr): Int = expr match {\n case Paren(_) => 1000\n case BinOp(op, _, _) => getPriority(op)\n case t: Term => getPriority(t: Term)\n }\n\n def getPriority(term: Term): Int = term match {\n case Number(_) => 1000\n case Var(_) => 1000\n case Operator(op) =>\n if (op == '+' || op == '-') 1\n else 2\n case _ => -1\n }\n\n def tokenize(expr: String): List[String] = {\n def loop(s: String, res: List[String]): List[String] = {\n if (s.length == 0) res.reverse\n else {\n val c = s(0)\n val pred = preds.find(_(c))\n if (pred == None)\n loop(s.drop(1), c.toString :: res)\n else {\n val (prefix, rest) = s.span(pred.get)\n loop(rest, prefix.mkString :: res)\n }\n }\n }\n loop(expr, Nil)\n }\n\n def toExpr(terms: List[Term]): Expr = {\n if (terms.length == 1) return terms(0).asInstanceOf[Expr]\n\n val levels = terms.scanLeft(0) { (lev: Int, t: Term) => \n t match {\n case LeftParen => lev + 1\n case RightParen => lev - 1\n case _ => lev\n }\n }\n val pris = terms.map(getPriority _)\n val candidates = terms.zipWithIndex.zip(levels.zip(pris)).filter{\n case ((Operator(c), _), (0, _)) => true\n case _ => false\n }\n\n if (candidates.isEmpty)\n Paren(toExpr(terms.slice(1, terms.length - 1)))\n else {\n val spix = candidates.minBy { \n case ((_, i), (_, p)) => (p, -i)\n }._1._2\n val (pre, suf) = terms.splitAt(spix)\n val (l, rt, r) = (pre, suf.head, suf.tail)\n BinOp(rt.asInstanceOf[Operator], toExpr(l), toExpr(r))\n }\n }\n\n def parse(expr: String): Expr = {\n val terms = tokenize(expr).map(Term.apply _)\n toExpr(terms)\n }\n }\n\n val mem = collection.mutable.Map[(String, Int, Char), Boolean]()\n\n def check(macros: Map[String, Expr], expr: Expr, parentPri: Int, parentOp: Char): Boolean = {\n val thisPri = Expr.getPriority(expr)\n expr match {\n case Var(name) if macros contains name =>\n val mexpr = macros(name)\n if (parentPri > Expr.getPriority(mexpr) ||\n parentPri == Expr.getPriority(mexpr) && (parentOp == '-' || parentOp == '/')) false\n else {\n if (!(mem contains (name, parentPri, parentOp)))\n mem((name, parentPri, parentOp)) = check(macros, mexpr, parentPri, parentOp)\n mem(name, parentPri, parentOp)\n }\n case BinOp(Operator(op), l, r) => \n check(macros, l, thisPri, '?') && check(macros, r, thisPri, op)\n case Paren(sub) => check(macros, sub, -1, '?')\n case _ => true\n }\n }\n\n import java.io._\n\n val re = new BufferedReader(new InputStreamReader(System.in))\n val n = re.readLine.toInt\n val defs = for (i <- 0 until n) yield {\n val l = re.readLine.trim\n val pairs = l.substring(l.indexOf(\"define\") + 6).trim\n val ss = pairs.split(\" \", 2)\n ss(0) -> ss(1).replace(\" \", \"\")\n }\n val inputExpr = re.readLine.replace(\" \", \"\")\n\n val macros = Map() ++ (for ((k, v) <- defs) yield k -> Expr.parse(v))\n val expr = Expr.parse(inputExpr)\n\n// println(macros)\n// println(expr)\n\n println(if (check(macros, expr, -1, '?')) \"OK\" else \"Suspicious\")\n}\n", "positive_code": [{"source_code": "object P7E {\n import io.StdIn._\n\n val m = collection.mutable.Map[String, Int]().withDefaultValue(0)\n\n /* import util.parsing.combinator._\n object ExpParsers extends JavaTokenParsers {\n val factor = wholeNumber ^^^ 0 | ident ^^ m | paren\n val term = chainl1(factor, (\"[*\" + \"/]\").r ^^ {\n case \"*\" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 2) 1 else 3\n case \"/\" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 1) 1 else 3\n })\n val expr = chainl1(term, \"[+-]\".r ^^ {\n case \"+\" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 3) 2 else 3\n case \"-\" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 2) 2 else 3\n })\n val paren:Parser[Int] = \"(\" ~> expr <~ \")\" ^^ {\n case 3 => 3\n case _ => 0\n }\n def apply(s:String) = parseAll(expr, s).get\n } */\n\n object ExpParsers {\n import util.matching._\n case class StringSlice(a:String, i:Int) extends CharSequence {\n def charAt(n:Int) = a(i + n)\n def length = a.size - i\n def subSequence(n1:Int, n2:Int) = a.substring(i + n1, i + n2)\n def from(n:Int) = StringSlice(a, i + n)\n }\n val re1 = \" *([A-Za-z0-9_]+)\".r\n val re2 = (\" *([/\" + \"*])\").r\n val re3 = \" *([+-])\".r\n val re4 = \" *\\\\(\".r\n val re5 = \" *\\\\)\".r\n def parseFactor(a:StringSlice):(StringSlice, Int) = {\n re1.findPrefixMatchOf(a) match {\n case Some(m1) => (a.from(m1.end), m(m1.group(1)))\n case None => parseParen(a)\n }\n }\n def parseTerm(a:StringSlice) = {\n def parse1(a1:StringSlice, r1:Int):(StringSlice, Int) = {\n re2.findPrefixMatchOf(a1) match {\n case Some(m1) => parseFactor(a1.from(m1.end)) match {\n case (a2, r2) if m1.group(1) == \"*\" =>\n parse1(a2, if (r1 < 2 && r2 < 2) 1 else 3)\n case (a2, r2) if m1.group(1) == \"/\" =>\n parse1(a2, if (r1 < 2 && r2 < 1) 1 else 3)\n }\n case None => (a1, r1)\n }\n }\n parseFactor(a) match { case (a1, r1) => parse1(a1, r1) }\n }\n def parseExpr(a:StringSlice) = {\n def parse1(a1:StringSlice, r1:Int):(StringSlice, Int) = {\n re3.findPrefixMatchOf(a1) match {\n case Some(m1) => parseTerm(a1.from(m1.end)) match {\n case (a2, r2) if m1.group(1) == \"+\" =>\n parse1(a2, if (r1 < 3 && r2 < 3) 2 else 3)\n case (a2, r2) if m1.group(1) == \"-\" =>\n parse1(a2, if (r1 < 3 && r2 < 2) 2 else 3)\n }\n case None => (a1, r1)\n }\n }\n parseTerm(a) match { case (a1, r1) => parse1(a1, r1) }\n }\n def parseParen(a:StringSlice) = {\n re4.findPrefixMatchOf(a) match {\n case Some(m1) => parseExpr(a.from(m1.end)) match {\n case (a1, r1) => re5.findPrefixMatchOf(a1) match {\n case Some(m2) =>\n (a1.from(m2.end), if (r1 < 3) 0 else 3)\n }\n }\n }\n }\n def apply(s:String) = parseExpr(StringSlice(s, 0))._2\n }\n\n def main(args : Array[String]) {\n val define = \" *# *define +(.*?) +(.*)\".r\n for (i <- 1 to readInt) {\n val define(name, exp) = readLine\n m(name) = ExpParsers(exp)\n }\n println(if (ExpParsers(readLine) == 3) \"Suspicious\" else \"OK\")\n }\n}\n"}], "negative_code": [{"source_code": "object DefiningMacros extends App {\n\n import java.io._\n\n val re = new BufferedReader(new InputStreamReader(System.in))\n val n = re.readLine.toInt\n val defs = for (i <- 0 until n) yield {\n val l = re.readLine.trim\n val pairs = l.substring(l.indexOf(\"define\") + 6).trim\n val ss = pairs.split(\" \", 2)\n ss(0) -> ss(1).replace(\" \", \"\")\n }\n val inputExpr = re.readLine.replace(\" \", \"\")\n\n println(\"GA\")\n println(defs)\n println(inputExpr)\n}\n"}, {"source_code": "object DefiningMacros extends App {\n sealed trait Term\n sealed trait Expr \n\n case object LeftParen extends Term\n case object RightParen extends Term\n case class Operator(op: Char) extends Term\n\n case class Number(n: Int) extends Term with Expr\n case class Var(name: String) extends Term with Expr\n\n case class Paren(sub: Expr) extends Expr\n case class BinOp(op: Operator, left: Expr, right: Expr) extends Expr\n\n object Term {\n def apply(s: String): Term = s match {\n case \"(\" => LeftParen\n case \")\" => RightParen\n case _ if \"+-*/\" contains s(0) => Operator(s(0))\n case _ if Character.isLetter(s(0)) => Var(s)\n case _ if Character.isDigit(s(0)) => Number(s.toInt)\n }\n }\n\n object Expr {\n val preds = List(Character.isLetter _, Character.isDigit _)\n\n def tokenize(expr: String): List[String] = {\n def loop(s: String, res: List[String]): List[String] = {\n if (s.length == 0) res.reverse\n else {\n val c = s(0)\n val pred = preds.find(_(c))\n if (pred == None)\n loop(s.drop(1), c.toString :: res)\n else {\n val (prefix, rest) = s.span(pred.get)\n loop(rest, prefix.mkString :: res)\n }\n }\n }\n loop(expr, Nil)\n }\n\n def toExpr(terms: List[Term]): Expr = {\n if (terms.length == 1) return terms(0).asInstanceOf[Expr]\n\n val levels = terms.scanLeft(0) { (lev: Int, t: Term) => \n t match {\n case LeftParen => lev + 1\n case RightParen => lev - 1\n case _ => lev\n }\n }\n val spix = terms.zipWithIndex.zip(levels).find{ \n case ((Operator(c), i), l) => l == 0 \n case _ => false\n }\n\n if (spix == None) {\n Paren(toExpr(terms.slice(1, terms.length - 1)))\n }\n else {\n val (pre, suf) = terms.splitAt(spix.get._1._2)\n val (l, rt, r) = (pre, suf.head, suf.tail)\n BinOp(rt.asInstanceOf[Operator], toExpr(l), toExpr(r))\n }\n }\n\n def parse(expr: String): Expr = {\n val terms = tokenize(expr).map(Term.apply _)\n toExpr(terms)\n }\n }\n\n def getPriority(expr: Expr) = expr match {\n case Paren(_) => 0\n case Number(_) => 1000\n case BinOp(Operator(op), _, _) =>\n if (op == '+' || op == '-') 1\n else 2\n case Var(_) => 1000\n }\n\n def check(macros: Map[String, Expr], expr: Expr, parentPri: Int, parentOp: Char): Boolean = {\n val thisPri = getPriority(expr)\n expr match {\n case Var(name) if macros contains name =>\n val mexpr = macros(name)\n if (parentPri > getPriority(mexpr) ||\n parentPri == getPriority(mexpr) && (parentOp == '-' || parentOp == '/')) {\n/* println(\"this expr = \" + expr)\n println(\"parent op = \" + parentOp)\n println(\"parent pri = \" + parentPri)\n println(\"this pri = \" + getPriority(mexpr))*/\n false\n }\n else check(macros, mexpr, parentPri, parentOp)\n case BinOp(Operator(op), l, r) => \n check(macros, l, thisPri, '?') && check(macros, r, thisPri, op)\n case Paren(sub) => check(macros, sub, thisPri, '?')\n case _ => true\n }\n }\n\n import java.io._\n\n val re = new BufferedReader(new InputStreamReader(System.in))\n val n = re.readLine.toInt\n val defs = for (i <- 0 until n) yield {\n val l = re.readLine.trim\n val pairs = l.substring(l.indexOf(\"define\") + 6).trim\n val ss = pairs.split(\" \", 2)\n ss(0) -> ss(1).replace(\" \", \"\")\n }\n val inputExpr = re.readLine.replace(\" \", \"\")\n\n val macros = (Map() ++ defs).mapValues(Expr.parse _)\n val expr = Expr.parse(inputExpr)\n\n println(if (check(macros, expr, -1, '?')) \"OK\" else \"Suspicious\")\n}\n"}, {"source_code": "object DefiningMacros extends App {\n sealed trait Term\n sealed trait Expr \n\n case object LeftParen extends Term\n case object RightParen extends Term\n case class Operator(op: Char) extends Term\n\n case class Number(n: Int) extends Term with Expr\n case class Var(name: String) extends Term with Expr\n\n case class Paren(sub: Expr) extends Expr\n case class BinOp(op: Operator, left: Expr, right: Expr) extends Expr\n\n object Term {\n def apply(s: String): Term = s match {\n case \"(\" => LeftParen\n case \")\" => RightParen\n case _ if \"+-*/\" contains s(0) => Operator(s(0))\n case _ if Character.isLetter(s(0)) => Var(s)\n case _ if Character.isDigit(s(0)) => Number(s.toInt)\n }\n }\n\n object Expr {\n val preds = List(Character.isLetter _, Character.isDigit _)\n\n def tokenize(expr: String): List[String] = {\n def loop(s: String, res: List[String]): List[String] = {\n if (s.length == 0) res.reverse\n else {\n val c = s(0)\n val pred = preds.find(_(c))\n if (pred == None)\n loop(s.drop(1), c.toString :: res)\n else {\n val (prefix, rest) = s.span(pred.get)\n loop(rest, prefix.mkString :: res)\n }\n }\n }\n loop(expr, Nil)\n }\n\n def toExpr(terms: List[Term]): Expr = {\n if (terms.length == 1) return terms(0).asInstanceOf[Expr]\n\n val levels = terms.scanLeft(0) { (lev: Int, t: Term) => \n t match {\n case LeftParen => lev + 1\n case RightParen => lev - 1\n case _ => lev\n }\n }\n val spix = terms.zipWithIndex.zip(levels).find{ \n case ((Operator(c), i), l) => l == 0 \n case _ => false\n }\n\n if (spix == None) {\n Paren(toExpr(terms.slice(1, terms.length - 1)))\n }\n else {\n val (pre, suf) = terms.splitAt(spix.get._1._2)\n val (l, rt, r) = (pre, suf.head, suf.tail)\n BinOp(rt.asInstanceOf[Operator], toExpr(l), toExpr(r))\n }\n }\n\n def parse(expr: String): Expr = {\n val terms = tokenize(expr).map(Term.apply _)\n toExpr(terms)\n }\n }\n\n def getPriority(expr: Expr) = expr match {\n case Paren(_) => 1000\n case Number(_) => 1000\n case BinOp(Operator(op), _, _) =>\n if (op == '+' || op == '-') 1\n else 2\n case Var(_) => 1000\n }\n\n def check(macros: Map[String, Expr], expr: Expr, parentPri: Int, parentOp: Char): Boolean = {\n val thisPri = getPriority(expr)\n expr match {\n case Var(name) if macros contains name =>\n val mexpr = macros(name)\n if (parentPri > getPriority(mexpr) ||\n parentPri == getPriority(mexpr) && (parentOp == '-' || parentOp == '/')) false\n else check(macros, mexpr, parentPri, parentOp)\n case BinOp(Operator(op), l, r) => \n check(macros, l, thisPri, '?') && check(macros, r, thisPri, op)\n case Paren(sub) => check(macros, sub, thisPri, '?')\n case _ => true\n }\n }\n\n import java.io._\n\n val re = new BufferedReader(new InputStreamReader(System.in))\n val n = re.readLine.toInt\n val defs = for (i <- 0 until n) yield {\n val l = re.readLine.trim\n val pairs = l.substring(l.indexOf(\"define\") + 6).trim\n val ss = pairs.split(\" \", 2)\n ss(0) -> ss(1).replace(\" \", \"\")\n }\n val inputExpr = re.readLine.replace(\" \", \"\")\n\n val macros = (Map() ++ defs).mapValues(Expr.parse _)\n val expr = Expr.parse(inputExpr)\n\n println(if (check(macros, expr, -1, '?')) \"OK\" else \"Suspicious\")\n}\n"}, {"source_code": "object DefiningMacros extends App {\n sealed trait Term\n sealed trait Expr \n\n case object LeftParen extends Term\n case object RightParen extends Term\n case class Operator(op: Char) extends Term\n\n case class Number(n: Int) extends Term with Expr\n case class Var(name: String) extends Term with Expr\n\n case class Paren(sub: Expr) extends Expr\n case class BinOp(op: Operator, left: Expr, right: Expr) extends Expr\n\n object Term {\n def apply(s: String): Term = s match {\n case \"(\" => LeftParen\n case \")\" => RightParen\n case _ if \"+-*/\" contains s(0) => Operator(s(0))\n case _ if Character.isLetter(s(0)) => Var(s)\n case _ if Character.isDigit(s(0)) => Number(s.toInt)\n }\n }\n\n object Expr {\n val preds = List(Character.isLetter _, Character.isDigit _)\n\n def tokenize(expr: String): List[String] = {\n def loop(s: String, res: List[String]): List[String] = {\n if (s.length == 0) res.reverse\n else {\n val c = s(0)\n val pred = preds.find(_(c))\n if (pred == None)\n loop(s.drop(1), c.toString :: res)\n else {\n val (prefix, rest) = s.span(pred.get)\n loop(rest, prefix.mkString :: res)\n }\n }\n }\n loop(expr, Nil)\n }\n\n def toExpr(terms: List[Term]): Expr = {\n if (terms.length == 1) return terms(0).asInstanceOf[Expr]\n\n val levels = terms.scanLeft(0) { (lev: Int, t: Term) => \n t match {\n case LeftParen => lev + 1\n case RightParen => lev - 1\n case _ => lev\n }\n }\n val spix = terms.zipWithIndex.zip(levels).find{ \n case ((Operator(c), i), l) => l == 0 \n case _ => false\n }\n\n if (spix == None) {\n Paren(toExpr(terms.slice(1, terms.length - 1)))\n }\n else {\n val (pre, suf) = terms.splitAt(spix.get._1._2)\n val (l, rt, r) = (pre, suf.head, suf.tail)\n BinOp(rt.asInstanceOf[Operator], toExpr(l), toExpr(r))\n }\n }\n\n def parse(expr: String): Expr = {\n val terms = tokenize(expr).map(Term.apply _)\n toExpr(terms)\n }\n }\n\n def getPriority(expr: Expr) = expr match {\n case Paren(_) => 1000\n case Number(_) => 1000\n case BinOp(Operator(op), _, _) =>\n if (op == '+' || op == '-') 1\n else 2\n case Var(_) => 1000\n }\n\n def check(macros: Map[String, Expr], expr: Expr, parentPri: Int, parentOp: Char): Boolean = {\n val thisPri = getPriority(expr)\n expr match {\n case Var(name) if macros contains name =>\n val mexpr = macros(name)\n if (parentPri > getPriority(mexpr) ||\n parentPri == getPriority(mexpr) && (parentOp == '-' || parentOp == '/')) {\n println(\"this expr = \" + expr)\n println(\"parent op = \" + parentOp)\n println(\"parent pri = \" + parentPri)\n println(\"this pri = \" + getPriority(mexpr))\n false\n }\n else check(macros, mexpr, parentPri, parentOp)\n case BinOp(Operator(op), l, r) => \n check(macros, l, thisPri, '?') && check(macros, r, thisPri, op)\n case Paren(sub) => check(macros, sub, -1, '?')\n case _ => true\n }\n }\n\n import java.io._\n\n val re = new BufferedReader(new InputStreamReader(System.in))\n val n = re.readLine.toInt\n val defs = for (i <- 0 until n) yield {\n val l = re.readLine.trim\n val pairs = l.substring(l.indexOf(\"define\") + 6).trim\n val ss = pairs.split(\" \", 2)\n ss(0) -> ss(1).replace(\" \", \"\")\n }\n val inputExpr = re.readLine.replace(\" \", \"\")\n\n val macros = (Map() ++ defs).mapValues(Expr.parse _)\n val expr = Expr.parse(inputExpr)\n\n println(if (check(macros, expr, -1, '?')) \"OK\" else \"Suspicious\")\n}\n"}, {"source_code": "object DefiningMacros extends App {\n sealed trait Term\n sealed trait Expr \n\n case object LeftParen extends Term\n case object RightParen extends Term\n case class Operator(op: Char) extends Term\n\n case class Number(n: Int) extends Term with Expr\n case class Var(name: String) extends Term with Expr\n\n case class Paren(sub: Expr) extends Expr\n case class BinOp(op: Operator, left: Expr, right: Expr) extends Expr\n\n object Term {\n def apply(s: String): Term = s match {\n case \"(\" => LeftParen\n case \")\" => RightParen\n case _ if \"+-*/\" contains s(0) => Operator(s(0))\n case _ if Character.isLetter(s(0)) => Var(s)\n case _ if Character.isDigit(s(0)) => Number(s.toInt)\n }\n }\n\n object Expr {\n val preds = List(Character.isLetter _, Character.isDigit _)\n\n def tokenize(expr: String): List[String] = {\n def loop(s: String, res: List[String]): List[String] = {\n if (s.length == 0) res.reverse\n else {\n val c = s(0)\n val pred = preds.find(_(c))\n if (pred == None)\n loop(s.drop(1), c.toString :: res)\n else {\n val (prefix, rest) = s.span(pred.get)\n loop(rest, prefix.mkString :: res)\n }\n }\n }\n loop(expr, Nil)\n }\n\n def toExpr(terms: List[Term]): Expr = {\n if (terms.length == 1) return terms(0).asInstanceOf[Expr]\n\n val levels = terms.scanLeft(0) { (lev: Int, t: Term) => \n t match {\n case LeftParen => lev + 1\n case RightParen => lev - 1\n case _ => lev\n }\n }\n val spix = terms.zipWithIndex.zip(levels).find{ \n case ((Operator(c), i), l) => l == 0 \n case _ => false\n }\n\n if (spix == None) {\n Paren(toExpr(terms.slice(1, terms.length - 1)))\n }\n else {\n val (pre, suf) = terms.splitAt(spix.get._1._2)\n val (l, rt, r) = (pre, suf.head, suf.tail)\n BinOp(rt.asInstanceOf[Operator], toExpr(l), toExpr(r))\n }\n }\n\n def parse(expr: String): Expr = {\n val terms = tokenize(expr).map(Term.apply _)\n toExpr(terms)\n }\n }\n\n def getPriority(expr: Expr) = expr match {\n case Paren(_) => 1000\n case Number(_) => 1000\n case BinOp(Operator(op), _, _) =>\n if (op == '+' || op == '-') 1\n else 2\n case Var(_) => -1\n }\n\n def check(macros: Map[String, Expr], expr: Expr, parentPri: Int, parentOp: Char): Boolean = {\n val thisPri = getPriority(expr)\n expr match {\n case Var(name) if macros contains name =>\n val mexpr = macros(name)\n if (parentPri > getPriority(mexpr) ||\n parentPri == getPriority(mexpr) && (parentOp == '-' || parentOp == '/')) false\n else check(macros, mexpr, parentPri, parentOp)\n case BinOp(Operator(op), l, r) => \n check(macros, l, thisPri, '?') && check(macros, r, thisPri, op)\n case Paren(sub) => check(macros, sub, thisPri, '?')\n case _ => true\n }\n }\n\n import java.io._\n\n val re = new BufferedReader(new InputStreamReader(System.in))\n val n = re.readLine.toInt\n val defs = for (i <- 0 until n) yield {\n val l = re.readLine.trim\n val pairs = l.substring(l.indexOf(\"define\") + 6).trim\n val ss = pairs.split(\" \", 2)\n ss(0) -> ss(1).replace(\" \", \"\")\n }\n val inputExpr = re.readLine.replace(\" \", \"\")\n\n val macros = (Map() ++ defs).mapValues(Expr.parse _)\n val expr = Expr.parse(inputExpr)\n\n println(if (check(macros, expr, -1, '?')) \"OK\" else \"Suspicious\")\n}\n"}, {"source_code": "object DefiningMacros extends App {\n sealed trait Term\n sealed trait Expr \n\n case object LeftParen extends Term\n case object RightParen extends Term\n case class Operator(op: Char) extends Term\n\n case class Number(n: Int) extends Term with Expr\n case class Var(name: String) extends Term with Expr\n\n case class Paren(sub: Expr) extends Expr\n case class BinOp(op: Operator, left: Expr, right: Expr) extends Expr\n\n object Term {\n def apply(s: String): Term = s match {\n case \"(\" => LeftParen\n case \")\" => RightParen\n case _ if \"+-*/\" contains s(0) => Operator(s(0))\n case _ if Character.isLetter(s(0)) => Var(s)\n case _ if Character.isDigit(s(0)) => Number(s.toInt)\n }\n }\n\n object Expr {\n val preds = List(Character.isLetter _, Character.isDigit _)\n\n def tokenize(expr: String): List[String] = {\n def loop(s: String, res: List[String]): List[String] = {\n if (s.length == 0) res.reverse\n else {\n val c = s(0)\n val pred = preds.find(_(c))\n if (pred == None)\n loop(s.drop(1), c.toString :: res)\n else {\n val (prefix, rest) = s.span(pred.get)\n loop(rest, prefix.mkString :: res)\n }\n }\n }\n loop(expr, Nil)\n }\n\n def toExpr(terms: List[Term]): Expr = {\n if (terms.length == 1) return terms(0).asInstanceOf[Expr]\n\n val levels = terms.scanLeft(0) { (lev: Int, t: Term) => \n t match {\n case LeftParen => lev + 1\n case RightParen => lev - 1\n case _ => lev\n }\n }\n val spix = terms.zipWithIndex.zip(levels).find{ \n case ((Operator(c), i), l) => l == 0 \n case _ => false\n }\n\n if (spix == None) {\n Paren(toExpr(terms.slice(1, terms.length - 1)))\n }\n else {\n val (pre, suf) = terms.splitAt(spix.get._1._2)\n val (l, rt, r) = (pre, suf.head, suf.tail)\n BinOp(rt.asInstanceOf[Operator], toExpr(l), toExpr(r))\n }\n }\n\n def parse(expr: String): Expr = {\n val terms = tokenize(expr).map(Term.apply _)\n toExpr(terms)\n }\n }\n\n def getPriority(expr: Expr) = expr match {\n case Paren(_) => 1000\n case Number(_) => 1000\n case BinOp(Operator(op), _, _) =>\n if (op == '+' || op == '-') 1\n else 2\n case Var(_) => 1000\n }\n\n def check(macros: Map[String, Expr], expr: Expr, parentPri: Int, parentOp: Char): Boolean = {\n val thisPri = getPriority(expr)\n expr match {\n case Var(name) if macros contains name =>\n val mexpr = macros(name)\n if (parentPri > getPriority(mexpr) ||\n parentPri == getPriority(mexpr) && (parentOp == '-' || parentOp == '/')) {\n/* println(\"this expr = \" + expr)\n println(\"parent op = \" + parentOp)\n println(\"parent pri = \" + parentPri)\n println(\"this pri = \" + getPriority(mexpr))*/\n false\n }\n else check(macros, mexpr, parentPri, parentOp)\n case BinOp(Operator(op), l, r) => \n check(macros, l, thisPri, '?') && check(macros, r, thisPri, op)\n case Paren(sub) => check(macros, sub, -1, '?')\n case _ => true\n }\n }\n\n import java.io._\n\n val re = new BufferedReader(new InputStreamReader(System.in))\n val n = re.readLine.toInt\n val defs = for (i <- 0 until n) yield {\n val l = re.readLine.trim\n val pairs = l.substring(l.indexOf(\"define\") + 6).trim\n val ss = pairs.split(\" \", 2)\n ss(0) -> ss(1).replace(\" \", \"\")\n }\n val inputExpr = re.readLine.replace(\" \", \"\")\n\n val macros = (Map() ++ defs).mapValues(Expr.parse _)\n val expr = Expr.parse(inputExpr)\n\n println(if (check(macros, expr, -1, '?')) \"OK\" else \"Suspicious\")\n}\n"}, {"source_code": "object P7E {\n import io.StdIn._\n\n val m = collection.mutable.Map[String, Int]().withDefaultValue(0)\n\n /* import util.parsing.combinator._\n object ExpParsers extends JavaTokenParsers {\n val factor = wholeNumber ^^^ 0 | ident ^^ m | paren\n val term = chainl1(factor, (\"[*\" + \"/]\").r ^^ {\n case \"*\" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 2) 1 else 3\n case \"/\" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 1) 1 else 3\n })\n val expr = chainl1(term, \"[+-]\".r ^^ {\n case \"+\" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 3) 2 else 3\n case \"-\" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 2) 2 else 3\n })\n val paren:Parser[Int] = \"(\" ~> expr <~ \")\" ^^ {\n case 3 => 3\n case _ => 0\n }\n def apply(s:String) = parseAll(expr, s).get\n } */\n\n object ExpParsers {\n import util.matching._\n case class StringSlice(a:String, i:Int) extends CharSequence {\n def charAt(n:Int) = a(i + n)\n def length = a.size - i\n def subSequence(n1:Int, n2:Int) = a.substring(i + n1, i + n2)\n def from(n:Int) = StringSlice(a, i + n)\n }\n val re1 = \" *([A-Za-z0-9_]+)\".r\n val re2 = (\" *([/\" + \"*])\").r\n val re3 = \" *([+-])\".r\n val re4 = \" *\\\\(\".r\n val re5 = \" *\\\\)\".r\n def parseFactor(a:StringSlice):(StringSlice, Int) = {\n re1.findPrefixMatchOf(a) match {\n case Some(m1) => (a.from(m1.end), m(m1.group(1)))\n case None => parseParen(a)\n }\n }\n def parseTerm(a:StringSlice) = {\n def parse1(a1:StringSlice, r1:Int):(StringSlice, Int) = {\n re2.findPrefixMatchOf(a1) match {\n case Some(m1) => parseFactor(a1.from(m1.end)) match {\n case (a2, r2) if m1.group(1) == \"*\" =>\n parse1(a2, if (r1 < 3 && r2 < 2) 1 else 3)\n case (a2, r2) if m1.group(1) == \"/\" =>\n parse1(a2, if (r1 < 3 && r2 < 1) 1 else 3)\n }\n case None => (a1, r1)\n }\n }\n parseFactor(a) match { case (a1, r1) => parse1(a1, r1) }\n }\n def parseExpr(a:StringSlice) = {\n def parse1(a1:StringSlice, r1:Int):(StringSlice, Int) = {\n re3.findPrefixMatchOf(a1) match {\n case Some(m1) => parseTerm(a1.from(m1.end)) match {\n case (a2, r2) if m1.group(1) == \"+\" =>\n parse1(a2, if (r1 < 3 && r2 < 3) 2 else 3)\n case (a2, r2) if m1.group(1) == \"-\" =>\n parse1(a2, if (r1 < 3 && r2 < 2) 2 else 3)\n }\n case None => (a1, r1)\n }\n }\n parseTerm(a) match { case (a1, r1) => parse1(a1, r1) }\n }\n def parseParen(a:StringSlice) = {\n re4.findPrefixMatchOf(a) match {\n case Some(m1) => parseExpr(a.from(m1.end)) match {\n case (a1, r1) => re5.findPrefixMatchOf(a1) match {\n case Some(m2) =>\n (a1.from(m2.end), if (r1 < 3) 0 else 3)\n }\n }\n }\n }\n def apply(s:String) = parseExpr(StringSlice(s, 0))._2\n }\n\n def main(args : Array[String]) {\n val define = \" *# *define *(.*?) *(.*)\".r\n for (i <- 1 to readInt) {\n val define(name, exp) = readLine\n m(name) = ExpParsers(exp)\n }\n println(if (ExpParsers(readLine) == 3) \"Suspicious\" else \"OK\")\n }\n}\n"}, {"source_code": "object P7E {\n import io.StdIn._\n\n val m = collection.mutable.Map[String, Int]().withDefaultValue(0)\n\n /* import util.parsing.combinator._\n object ExpParsers extends JavaTokenParsers {\n val factor = wholeNumber ^^^ 0 | ident ^^ m | paren\n val term = chainl1(factor, (\"[*\" + \"/]\").r ^^ {\n case \"*\" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 2) 1 else 3\n case \"/\" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 1) 1 else 3\n })\n val expr = chainl1(term, \"[+-]\".r ^^ {\n case \"+\" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 3) 2 else 3\n case \"-\" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 2) 2 else 3\n })\n val paren:Parser[Int] = \"(\" ~> expr <~ \")\" ^^ {\n case 3 => 3\n case _ => 0\n }\n def apply(s:String) = parseAll(expr, s).get\n } */\n\n object ExpParsers {\n import util.matching._\n case class StringSlice(a:String, i:Int) extends CharSequence {\n def charAt(n:Int) = a(i + n)\n def length = a.size - i\n def subSequence(n1:Int, n2:Int) = a.substring(i + n1, i + n2)\n def from(n:Int) = StringSlice(a, i + n)\n }\n val re1 = \" *([A-Za-z0-9_]+)\".r\n val re2 = (\" *([/\" + \"*])\").r\n val re3 = \" *([+-])\".r\n val re4 = \" *\\\\(\".r\n val re5 = \" *\\\\)\".r\n def parseFactor(a:StringSlice):(StringSlice, Int) = {\n re1.findPrefixMatchOf(a) match {\n case Some(m1) => (a.from(m1.end), m(m1.group(1)))\n case None => parseParen(a)\n }\n }\n def parseTerm(a:StringSlice) = {\n def parse1(a1:StringSlice, r1:Int):(StringSlice, Int) = {\n re2.findPrefixMatchOf(a1) match {\n case Some(m1) => parseFactor(a1.from(m1.end)) match {\n case (a2, r2) if m1.group(1) == \"*\" =>\n parse1(a2, if (r1 < 3 && r2 < 2) 1 else 3)\n case (a2, r2) if m1.group(1) == \"/\" =>\n parse1(a2, if (r1 < 3 && r2 < 1) 1 else 3)\n }\n case None => (a1, r1)\n }\n }\n parseFactor(a) match { case (a1, r1) => parse1(a1, r1) }\n }\n def parseExpr(a:StringSlice) = {\n def parse1(a1:StringSlice, r1:Int):(StringSlice, Int) = {\n re3.findPrefixMatchOf(a1) match {\n case Some(m1) => parseTerm(a1.from(m1.end)) match {\n case (a2, r2) if m1.group(1) == \"+\" =>\n parse1(a2, if (r1 < 3 && r2 < 3) 2 else 3)\n case (a2, r2) if m1.group(1) == \"-\" =>\n parse1(a2, if (r1 < 3 && r2 < 2) 2 else 3)\n }\n case None => (a1, r1)\n }\n }\n parseTerm(a) match { case (a1, r1) => parse1(a1, r1) }\n }\n def parseParen(a:StringSlice) = {\n re4.findPrefixMatchOf(a) match {\n case Some(m1) => parseExpr(a.from(m1.end)) match {\n case (a1, r1) => re5.findPrefixMatchOf(a1) match {\n case Some(m2) =>\n (a1.from(m2.end), if (r1 < 3) 0 else 3)\n }\n }\n }\n }\n def apply(s:String) = parseExpr(StringSlice(s, 0))._2\n }\n\n def main(args : Array[String]) {\n val define = \" *# *define +(.*?) +(.*)\".r\n for (i <- 1 to readInt) {\n val define(name, exp) = readLine\n m(name) = ExpParsers(exp)\n }\n println(if (ExpParsers(readLine) == 3) \"Suspicious\" else \"OK\")\n }\n}\n"}], "src_uid": "c23d3ec2b9fb4b4d169bc8053bfd000e"} {"source_code": "object A686 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = readLongs(2)\n val input = Array.fill(n.toInt){\n val tl = tokenizeLine\n (tl.nextToken, tl.nextToken.toLong)\n }\n var ice = x\n var left = 0L\n\n for(i <- 0 until n.toInt){\n if(input(i)._1 == \"+\") {\n ice += input(i)._2\n } else {\n if(ice >= input(i)._2) {\n ice -= input(i)._2\n } else {\n left += 1\n }\n }\n }\n\n println(s\"$ice $left\")\n }\n}", "positive_code": [{"source_code": "object Main{\n def main(args: Array[String]) {\n\n val temp = scala.io.StdIn.readLine().split(\" \").map(x => x.toInt)\n val n = temp(0); val x = temp(1)\n\n var children = 0\n var ice = x.toLong\n\n for(x <- 1 to n){\n val temp = scala.io.StdIn.readLine().split(\" \")\n val b = temp(0); val d = temp(1).toLong\n\n b match {\n case \"+\" => ice = ice + d\n case \"-\" => if (ice >= d) {ice = ice - d} else {children = children + 1}\n }\n }\n\n println(ice + \" \" + children)\n\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject _359A extends App {\n val input = readLine().split(\" \").map(_.toInt)\n val (n, x) = (input(0), input(1))\n var acc: Long = x\n var dis = 0\n for (i <- 1 to n) {\n val input = readLine().split(\" \")\n var inc: Long = input(1).toInt\n inc = if (input(0) == \"+\") inc else -inc\n if (acc + inc < 0) dis += 1\n else acc += inc\n }\n println(acc + \" \" + dis)\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.immutable.HashSet\nimport scala.io.StdIn\n\n/**\n * Created by shvedchikov on 13.01.16.\n */\nobject Codeforces extends App {\n override def main(args: Array[String]) {\n iceCream()\n }\n\n //http://codeforces.com/problemset/problem/686/A\n def iceCream(): Unit = {\n\n case class Status(iceCreamsCount: Long, sadChildrenCount: Long) {\n override def toString: String = s\"$iceCreamsCount $sadChildrenCount\"\n }\n\n val Array(n, x) = StdIn.readLine().split(\" \").map(_.toLong)\n val result = (1L to n)\n .map(_ => StdIn.readLine().split(\" \") match { case Array(sign, count) => (sign, count.toLong) })\n .foldLeft(Status(x, 0))((status, request) => {\n val (sign, count) = request\n sign match {\n case \"+\" =>\n status.copy(iceCreamsCount = status.iceCreamsCount + count)\n case \"-\" if status.iceCreamsCount < count =>\n status.copy(sadChildrenCount = status.sadChildrenCount + 1)\n case \"-\" if status.iceCreamsCount >= count =>\n status.copy(iceCreamsCount = status.iceCreamsCount - count)\n }\n })\n print(result)\n }\n\n}\n"}, {"source_code": "object Solution {\n def re(ns:List[Long],x:Long,d:Int):Unit = \n if (ns.isEmpty) println(s\"$x $d\")\n else if (ns.head > 0) re(ns.tail,x+ns.head,d)\n else if (-ns.head > x) re(ns.tail,x,d+1)\n else re(ns.tail,x+ns.head,d)\n def main(args: Array[String]) {\n val nx = readLine.split(\" \").map(_.toLong)\n val ns = (0 until nx(0).toInt).map(_=>{\n val pv = readLine.split(\" \")\n if (pv(0)==\"+\") pv(1).toLong else -pv(1).toLong\n }).toList\n re(ns,nx(1),0)\n }\n}"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val Array(n, x) = lines.next().split(' ').map(_.toInt)\n val (l, u) = lines.take(n).foldLeft(x.toLong, 0) {\n case((left, unh), str) if str.startsWith(\"+\") => (left + str.drop(2).toInt, unh)\n case((left, unh), str) if str.startsWith(\"-\") =>\n val count = str.drop(2).toInt\n if (count > left)\n (left, unh + 1)\n else\n (left - count, unh)\n }\n println(s\"$l $u\")\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _686A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val n = read[Int]\n var x = read[Long]\n var unhappy = 0\n\n repeat(n) {\n read[(Char, Long)] match {\n case ('+', i) => x += i\n case ('-', i) if i <= x => x -= i\n case _ => unhappy += 1\n }\n }\n\n write(x, unhappy)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toYesNo = if(x) \"yes\" else \"no\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def bitCount: Int = java.lang.Integer.bitCount(x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeLine(obj: Any*): this.type = {\n if (obj.isEmpty) printer.println() else obj foreach printer.println\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n // val n = sc.nextInt()\n // val s = sc.nextLine()\n // val str = sc.next()\n\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val x = sc.nextInt()\n sc.nextLine()\n\n var ice: Long = x\n var distman = 0\n for(k <- 1 to n){\n val query = sc.next()\n val d = sc.nextInt()\n sc.nextLine()\n\n if(query == \"+\")\n ice += d\n else{\n if(ice >= d)\n ice -= d\n else\n distman += 1\n }\n }\n\n println(ice + \" \" + distman)\n }\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nimport scala.collection.immutable.HashSet\nimport scala.io.StdIn\n\n/**\n * Created by shvedchikov on 13.01.16.\n */\nobject Codeforces extends App {\n override def main(args: Array[String]) {\n iceCream()\n }\n\n //http://codeforces.com/problemset/problem/686/A\n def iceCream(): Unit = {\n\n case class Status(iceCreamsCount: Int, sadChildrenCount: Int) {\n override def toString: String = s\"$iceCreamsCount $sadChildrenCount\"\n }\n\n val Array(n, x) = StdIn.readLine().split(\" \").map(_.toInt)\n val result = (1 to n)\n .map(_ => StdIn.readLine().split(\" \") match { case Array(sign, count) => (sign, count.toInt) })\n .foldLeft(Status(x, 0))((status, request) => {\n val (sign, count) = request\n sign match {\n case \"+\" =>\n status.copy(iceCreamsCount = status.iceCreamsCount + count)\n case \"-\" if status.iceCreamsCount < count =>\n status.copy(sadChildrenCount = status.sadChildrenCount + 1)\n case \"-\" if status.iceCreamsCount >= count =>\n status.copy(iceCreamsCount = status.iceCreamsCount - count)\n }\n })\n print(result)\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.immutable.HashSet\nimport scala.io.StdIn\n\n/**\n * Created by shvedchikov on 13.01.16.\n */\nobject Codeforces extends App {\n override def main(args: Array[String]) {\n iceCream()\n }\n \n\n //http://codeforces.com/problemset/problem/686/A\n def iceCream(): Unit = {\n\n case class Status(iceCreamsCount: Int, sadChildrenCount: Int) {\n override def toString: String = s\"$iceCreamsCount $sadChildrenCount\"\n }\n\n val Array(n, x) = StdIn.readLine().split(\" \").map(_.toInt)\n val result = (1 to n)\n .map(_ => StdIn.readLine().split(\" \") match { case Array(sign, count) => (sign, count.toInt) })\n .foldLeft(Status(x, 0))((status, request) => {\n val (sign, count) = request\n sign match {\n case \"+\" =>\n status.copy(iceCreamsCount = status.iceCreamsCount + count)\n case \"-\" if status.iceCreamsCount < count =>\n status.copy(sadChildrenCount = status.sadChildrenCount + 1)\n case \"-\" if status.iceCreamsCount >= count =>\n status.copy(iceCreamsCount = status.iceCreamsCount - count)\n }\n })\n print(result)\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val Array(n, x) = lines.next().split(' ').map(_.toInt)\n val (l, u) = lines.take(n).foldLeft(x, 0) {\n case((left, unh), str) if str.startsWith(\"+\") => (left + str.drop(2).toInt, unh)\n case((left, unh), str) if str.startsWith(\"-\") =>\n val count = str.drop(2).toInt\n if (count > left)\n (left, unh + 1)\n else\n (left - count, unh)\n }\n println(s\"$l $u\")\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _686A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val n = read[Int]\n var x = read[Int]\n var unhappy = 0\n\n repeat(n) {\n read[(Char, Int)] match {\n case ('+', i) => x += i\n case ('-', i) if i <= x => x -= i\n case _ => unhappy += 1\n }\n }\n\n write(x, unhappy)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toYesNo = if(x) \"yes\" else \"no\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def bitCount: Int = java.lang.Integer.bitCount(x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeLine(obj: Any*): this.type = {\n if (obj.isEmpty) printer.println() else obj foreach printer.println\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Main{\n def main(args: Array[String]) {\n\n val temp = scala.io.StdIn.readLine().split(\" \").map(x => x.toInt)\n val n = temp(0); val x = temp(1)\n\n var children = 0\n var ice = x\n\n for(x <- 1 to n){\n val temp = scala.io.StdIn.readLine().split(\" \")\n val b = temp(0); val d = temp(1).toInt\n\n b match {\n case \"+\" => ice = ice + d\n case \"-\" => if (ice >= d) {ice = ice - d} else {children = children + 1}\n }\n }\n\n println(ice + \" \" + children)\n\n }\n}"}], "src_uid": "0a9ee8cbfa9888caef39b024563b7dcd"} {"source_code": "import java.io._\nimport java.util\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n\n case class Point(x: Int, y: Int)\n\n @inline def dist(x1: Int, x2: Int, y1: Int, y2: Int): Int = math.abs(x1 - x2) * 2 + math.abs(y1 - y2) * 2\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n var mxX = -1000000000\n var mnX = 1000000000\n var mxY = -1000000000\n var mnY = 1000000000\n val arr = Array.fill(n) {\n val p = Point(in.nextInt, in.nextInt)\n mxX = math.max(mxX, p.x)\n mnX = math.min(mnX, p.x)\n mxY = math.max(mxY, p.y)\n mnY = math.min(mnY, p.y)\n p\n }\n\n var ans3 = 0\n arr.foreach { p =>\n ans3 = math.max(ans3, dist(p.x, mxX, p.y, mxY))\n ans3 = math.max(ans3, dist(p.x, mxX, p.y, mnY))\n ans3 = math.max(ans3, dist(p.x, mnX, p.y, mxY))\n ans3 = math.max(ans3, dist(p.x, mnX, p.y, mnY))\n }\n\n val ans4 = (mxX - mnX) * 2 + (mxY - mnY) * 2\n\n print(ans3 + (\" \" + ans4) * (n - 3))\n\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toDouble\n }\n\n def nextLong: Long = {\n next.toLong\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}", "positive_code": [{"source_code": "object E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n\n case class P(x: Long, y: Long)\n\n def dist(p1: P, p2: P): Long = {\n Math.abs(p2.x - p1.x) + Math.abs(p1.y - p2.y)\n }\n\n val Array(n) = readInts(1)\n\n val ps = Array.fill(n) {\n val Array(x, y) = readLongs(2)\n P(x, y)\n }\n\n val psByX = ps.sortBy(_.x)\n val psByY = ps.sortBy(_.y)\n\n var on3 = 0L\n\n def triangle(p1: P, p2: P, p3: P): Long = {\n dist(p1, p2) + dist(p2, p3) + dist(p3, p1)\n }\n\n for (p <- ps) {\n val d1 = triangle(psByX.head, psByY.last, p)\n val d2 = triangle(psByX.head, psByY.head, p)\n val d3 = triangle(psByX.last, psByY.last, p)\n val d4 = triangle(psByX.last, psByY.head, p)\n val d = d1 max d2 max d3 max d4\n if (d > on3) on3 = d\n }\n\n val res = Array.ofDim[Long](n - 2)\n res(0) = on3\n\n val on4 = 2 * (psByX.last.x - psByX.head.x + psByY.last.y - psByY.head.y)\n\n for (i <- 1 until res.length) res(i) = on4\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "import java.util\n\nimport scala.collection.mutable\n\nobject E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n case class P(x: Long, y: Long)\n\n def dist(x1: Long, y1: Long, x2: Long, y2: Long): Long = {\n Math.abs(x2 - x1) + Math.abs(y2 - y1)\n }\n\n val Array(n) = readInts(1)\n val psBuilder = new mutable.ArrayBuilder.ofRef[P]\n\n for (_ <- 0 until n) {\n val Array(x, y) = readLongs(2)\n psBuilder += P(x, y)\n }\n\n val ps = psBuilder.result()\n val psByX = ps.sortBy(_.x)\n val psByY = ps.sortBy(_.y)\n\n var on3ByX, on3ByY = 0L\n\n {\n val first = psByX.head\n val last = psByX.last\n for (i <- 1 until n - 1) {\n val p = psByX(i)\n val d = dist(first.x, first.y, p.x, p.y) + dist(p.x, p.y, last.x, last.y) + dist(first.x, first.y, last.x, last.y)\n if (d > on3ByX) on3ByX = d\n }\n }\n\n {\n val first = psByY.head\n val last = psByY.last\n for (i <- 1 until n - 1) {\n val p = psByY(i)\n val d = dist(first.x, first.y, p.x, p.y) + dist(p.x, p.y, last.x, last.y) + dist(first.x, first.y, last.x, last.y)\n if (d > on3ByY) on3ByY = d\n }\n }\n\n val res = Array.ofDim[Long](n - 2)\n res(0) = Math.max(on3ByX, on3ByY)\n\n val on4 = 2 * (psByX.last.x - psByX.head.x + psByY.last.y - psByY.head.y)\n\n for (i <- 1 until res.length) res(i) = on4\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "import java.util\n\nimport scala.collection.mutable\n\nobject E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n case class P(x: Int, y: Int)\n\n def dist(x1: Int, y1: Int, x2: Int, y2: Int): Long = {\n Math.abs(x2 - x1) + Math.abs(y2 - y1)\n }\n\n val Array(n) = readInts(1)\n val psBuilder = new mutable.ArrayBuilder.ofRef[P]\n\n for (i <- 0 until n) {\n val Array(x, y) = readInts(2)\n psBuilder += P(x, y)\n }\n\n val ps = psBuilder.result\n val psByX = ps.sortBy(_.x)\n val psByY = ps.sortBy(_.y)\n\n var on3ByX = 0L\n\n {\n val first = psByX.head\n val last = psByX.last\n for (i <- 1 until n - 1) {\n val p = psByX(i)\n val d = dist(first.x, first.y, p.x, p.y) + dist(p.x, p.y, last.x, last.y ) + dist(first.x, first.y, last.x, last.y)\n if (d > on3ByX) on3ByX = d\n }\n }\n\n var on3ByY = 0L\n\n {\n val first = psByY.head\n val last = psByY.last\n for (i <- 1 until n - 1) {\n val p = psByY(i)\n val d = dist(first.x, first.y, p.x, p.y) + dist(p.x, p.y, last.x, last.y ) + dist(first.x, first.y, last.x, last.y)\n if (d > on3ByY) on3ByY = d\n }\n }\n\n val res = Array.ofDim[Long](n - 2)\n res(0) = on3ByX max on3ByY\n\n val on4 = 2 * (psByX.last.x - psByX.head.x + psByY.last.y - psByY.head.y)\n\n for (i <- 1 until res.length) res(i) = on4\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "import java.io._\nimport java.util\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n\n case class Point(x: Int, y: Int)\n\n def dist(p1: Point, p2: Point): Long = math.abs(p1.x - p2.x) + math.abs(p1.y - p2.y)\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val arr = Array.fill(n)(Point(in.nextInt, in.nextInt))\n val mxX: Long = arr.maxBy(_.x).x\n val mnX: Long = arr.minBy(_.x).x\n val mxY: Long = arr.maxBy(_.y).y\n val mnY: Long = arr.minBy(_.y).y\n\n val t = ArrayBuffer[Point]()\n arr.foreach { p =>\n if (p.x == mxX || p.x == mnX || p.y == mxY || p.y == mnY)\n t.append(p)\n }\n\n val ans3 = (for {\n p1 <- t\n p2 <- t\n p3 <- t\n } yield dist(p1, p2) + dist(p2, p3) + dist(p3, p1)).max\n\n val ans4 = (mxX - mnX) * 2 + (mxY - mnY) * 2\n\n print(ans3 + (\" \" + ans4) * (n - 3))\n\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toDouble\n }\n\n def nextLong: Long = {\n next.toLong\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}], "src_uid": "9eccd64bb49b74ed0eed3dbf6636f07d"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\n/**\n * Created by amir.\n */\n\nobject A extends App {\n\n class RW(val inputFile: String, val outputFile: String) {\n private var br = new BufferedReader(new InputStreamReader(System.in))\n private var out = new PrintWriter(new OutputStreamWriter(System.out))\n\n /* val f = new File(inputFile)\n if (f.exists && f.canRead)\n try {\n br = new BufferedReader(new FileReader(f))\n out = new PrintWriter(new FileWriter(outputFile))\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }*/\n\n private var st: StringTokenizer = _\n var eof = false\n\n def nextLine: String = {\n var s = \"\"\n try\n s = br.readLine()\n catch {\n case e: IOException =>\n e.printStackTrace()\n }\n s\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens)\n try\n st = new StringTokenizer(br.readLine)\n catch {\n case _: IOException =>\n eof = true\n \"\"\n }\n st.nextToken\n }\n\n def nextLong: Long = next.toLong\n\n def nextInt: Int = next.toInt\n\n def println(): Unit = out.println()\n\n def println(o: Any): Unit = out.println(o)\n\n def print(o: Any): Unit = out.print(o)\n\n def close(): Unit = {\n try {\n br.close()\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n\n out.close()\n }\n }\n\n\n override def main(args: Array[String]) {\n val rw = new RW(\"input.txt\", \"output.txt\")\n\n def count(s: IndexedSeq[Char], k: Int): Int = {\n @tailrec def count(cur: Int, i: Int, curSum: Int): Int =\n if (i >= s.length) curSum\n else if (s(i) == '*') count(0, i + 1, curSum)\n else count(cur + 1, i + 1, curSum + (if (cur + 1 >= k) 1 else 0))\n\n count(0, 0, 0)\n }\n\n val n, _, k = rw.nextInt\n val cl = for (_ <- 1 to n) yield rw.next\n\n rw.print(cl.map(s => count(s, k)).sum + (if (k == 1) 0 else cl.transpose.map(s => count(s, k)).sum))\n rw.close()\n }\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\n/**\n * Created by amir.\n */\n\nobject A extends App {\n\n class RW(val inputFile: String, val outputFile: String) {\n private var br = new BufferedReader(new InputStreamReader(System.in))\n private var out = new PrintWriter(new OutputStreamWriter(System.out))\n\n /* val f = new File(inputFile)\n if (f.exists && f.canRead)\n try {\n br = new BufferedReader(new FileReader(f))\n out = new PrintWriter(new FileWriter(outputFile))\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }*/\n\n private var st: StringTokenizer = _\n var eof = false\n\n def nextLine: String = {\n var s = \"\"\n try\n s = br.readLine()\n catch {\n case e: IOException =>\n e.printStackTrace()\n }\n s\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens)\n try\n st = new StringTokenizer(br.readLine)\n catch {\n case _: IOException =>\n eof = true\n \"\"\n }\n st.nextToken\n }\n\n def nextLong: Long = next.toLong\n\n def nextInt: Int = next.toInt\n\n def println(): Unit = out.println()\n\n def println(o: Any): Unit = out.println(o)\n\n def print(o: Any): Unit = out.print(o)\n\n def close(): Unit = {\n try {\n br.close()\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n\n out.close()\n }\n }\n\n\n override def main(args: Array[String]) {\n val rw = new RW(\"input.txt\", \"output.txt\")\n\n\n def count(s: IndexedSeq[Char], k: Int): Int = {\n @tailrec def count(cur: Int, i: Int, curSum: Int): Int =\n if (i >= s.length ) curSum\n else if (s(i) == '*') count(0, i + 1, curSum)\n else count(cur + 1, i + 1, curSum + (if (cur + 1 >= k) 1 else 0))\n count(0, 0, 0)\n }\n\n val n, m, k = rw.nextInt\n val cl = for (_ <- 1 to n) yield rw.next\n\n rw.print(cl.map(s => count(s, k)).sum + (if (k == 1) 0 else cl.transpose.map(s => count(s, k)).sum))\n rw.close()\n }\n}"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\n/**\n * Created by amir.\n */\n\nobject A extends App {\n\n class RW(val inputFile: String, val outputFile: String) {\n private var br = new BufferedReader(new InputStreamReader(System.in))\n private var out = new PrintWriter(new OutputStreamWriter(System.out))\n\n /* val f = new File(inputFile)\n if (f.exists && f.canRead)\n try {\n br = new BufferedReader(new FileReader(f))\n out = new PrintWriter(new FileWriter(outputFile))\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }*/\n\n private var st: StringTokenizer = _\n var eof = false\n\n def nextLine: String = {\n var s = \"\"\n try\n s = br.readLine()\n catch {\n case e: IOException =>\n e.printStackTrace()\n }\n s\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens)\n try\n st = new StringTokenizer(br.readLine)\n catch {\n case _: IOException =>\n eof = true\n \"\"\n }\n st.nextToken\n }\n\n def nextLong: Long = next.toLong\n\n def nextInt: Int = next.toInt\n\n def println(): Unit = out.println()\n\n def println(o: Any): Unit = out.println(o)\n\n def print(o: Any): Unit = out.print(o)\n\n def close(): Unit = {\n try {\n br.close()\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n\n out.close()\n }\n }\n\n\n override def main(args: Array[String]) {\n val rw = new RW(\"input.txt\", \"output.txt\")\n\n\n def count(s: IndexedSeq[Char], k: Int): Int = {\n def count(cur: Int, i: Int): Int =\n if (i >= s.length ) 0\n else if (s(i) == '*') count(0, i + 1)\n else count(cur + 1, i + 1) + (if (cur + 1 >= k) 1 else 0)\n count(0, 0)\n }\n\n val n, m, k = rw.nextInt\n val cl = for (_ <- 1 to n) yield rw.next\n\n rw.print(cl.map(s => count(s, k)).sum + cl.transpose.map(s => count(s, k)).sum)\n rw.close()\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\n/**\n * Created by amir.\n */\n\nobject A extends App {\n\n class RW(val inputFile: String, val outputFile: String) {\n private var br = new BufferedReader(new InputStreamReader(System.in))\n private var out = new PrintWriter(new OutputStreamWriter(System.out))\n\n /* val f = new File(inputFile)\n if (f.exists && f.canRead)\n try {\n br = new BufferedReader(new FileReader(f))\n out = new PrintWriter(new FileWriter(outputFile))\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }*/\n\n private var st: StringTokenizer = _\n var eof = false\n\n def nextLine: String = {\n var s = \"\"\n try\n s = br.readLine()\n catch {\n case e: IOException =>\n e.printStackTrace()\n }\n s\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens)\n try\n st = new StringTokenizer(br.readLine)\n catch {\n case _: IOException =>\n eof = true\n \"\"\n }\n st.nextToken\n }\n\n def nextLong: Long = next.toLong\n\n def nextInt: Int = next.toInt\n\n def println(): Unit = out.println()\n\n def println(o: Any): Unit = out.println(o)\n\n def print(o: Any): Unit = out.print(o)\n\n def close(): Unit = {\n try {\n br.close()\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n\n out.close()\n }\n }\n\n\n override def main(args: Array[String]) {\n val rw = new RW(\"input.txt\", \"output.txt\")\n\n def count(s: IndexedSeq[Char], k: Int): Int = {\n @tailrec def count(cur: Int, i: Int, curSum: Int): Int =\n if (i >= s.length) curSum\n else if (s(i) == '*') count(0, i + 1, curSum)\n else count(cur + 1, i + 1, curSum + (if (cur + 1 >= k) 1 else 0))\n\n count(0, 0, 0)\n }\n\n val n, _, k = rw.nextInt\n val cl = for (_ <- 1 to n) yield rw.next\n\n def f[T <: IndexedSeq[String]]: T => Int = _.map(s => count(s, k)).sum\n\n rw.print(f(cl) + (if (k == 1) 0 else f(cl.transpose.map(_.toString))))\n rw.close()\n }\n}"}], "src_uid": "c1f247150831e9b52389bae697a1ca3d"} {"source_code": "object Main {\n def main(args: Array[String]) = {\n val t = readInt\n (0 until t).foreach((x) => f1)\n }\n def f1(): Unit = { \n val n = readLong\n val as = readLine.split(\" \").map(_.toInt)\n val x: Map[Int, Int] = as.foldLeft(Map[Int, Int]()){\n case (m, i) => {\n val (c, n) = f2(i, 0)\n m.lift(c) match {\n case Some(x) => if (x > n) m else m + (c -> n)\n case None => m + (c -> n)\n }\n }\n }\n println(x.values.foldLeft(0)(_ + _))\n }\n\n def f2(i: Int, c: Int): (Int, Int) = {\n if (i % 2 != 0) (i, c) else f2(i / 2, c + 1)\n }\n\n }", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject B {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n for (_ <- 1 to t) {\n val n = nextInt\n val as = nextInts(n)\n val map = mutable.Map.empty[Int, Int]\n var i = 0\n while (i < n) {\n var a = as(i)\n var p = 0\n while ((a & 1) == 0) {\n p += 1\n a >>>= 1\n }\n if (p > 0) {\n if (map.contains(a)) {\n if (map(a) < p) map(a) = p\n } else map(a) = p\n }\n i += 1\n }\n val res = map.valuesIterator.sum\n out.println(res)\n }\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "afcd41492158e68095b01ff1e88c3dd4"} {"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val A=nextString\n val B=nextString\n val C=nextString\n val a=Array.fill(26)(0)\n val b=Array.fill(26)(0)\n val c=Array.fill(26)(0)\n val ascii0='a'.toInt\n for(i<-0 until A.length()){\n a(A(i).toInt-ascii0)+=1\n }\n for(i<-0 until B.length()){\n b(B(i).toInt-ascii0)+=1\n }\n for(i<-0 until C.length()){\n c(C(i).toInt-ascii0)+=1\n }\n var max= -3\n var maxcurrent= -1\n var nb=0\n while(maxcurrent>=max){\n max=maxcurrent\n var nc=Int.MaxValue\n\n for(i<-0 until 26){\n if(a(i)0){\n\n val ncc=(a(i)-nb*b(i))/c(i)\n if(ncc a.count { y => x == y })\n val cb = ('a' to 'z').map(x => b.count { y => x == y })\n val cc = ('a' to 'z').map(x => c.count { y => x == y })\n var bestX = 0\n var bestY = 0\n try {\n for (x <- 0 to 100000) {\n var y = 100000\n for (i <- 0 to 25) {\n val tmp = ca(i) - cb(i) * x\n if (tmp < 0)\n y = -1\n else {\n if (cc(i) > 0)\n y = Math.min(y, tmp / cc(i))\n }\n }\n if (y < 0)\n throw new Exception()\n if (y >= 0 && x + y > bestX + bestY) {\n bestX = x\n bestY = y\n }\n }\n } catch {\n case _ =>\n }\n\n for (x <- 1 to bestX)\n print(b)\n for (y <- 1 to bestY)\n print(c)\n for (i <- 0 to 25) {\n val rest = ca(i) - cb(i) * bestX - cc(i) * bestY\n for (j <- 1 to rest)\n print((97 + i).toChar)\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.math\nimport scala.util.control.Breaks._\nimport java.lang.Exception\n\nobject CF551B extends App {\n var in = new Scanner(System.in)\n val a = in.next()\n val b = in.next()\n val c = in.next()\n val ca = ('a' to 'z').map(x => a.count { y => x == y })\n val cb = ('a' to 'z').map(x => b.count { y => x == y })\n val cc = ('a' to 'z').map(x => c.count { y => x == y })\n var bestX = 0\n var bestY = 0\n try {\n for (x <- 0 to 100000) {\n var y = 100000\n for (i <- 0 to 25) {\n val tmp = ca(i) - cb(i) * x\n if (tmp < 0)\n y = -1\n else {\n if (cc(i) > 0)\n y = Math.min(y, tmp / cc(i))\n }\n }\n if (y < 0)\n throw new Exception()\n if (y >= 0 && x + y > bestX + bestY) {\n bestX = x\n bestY = y\n }\n }\n } catch {\n case _ =>\n }\n\n for (x <- 1 to bestX)\n print(b)\n for (y <- 1 to bestY)\n print(c)\n for (i <- 0 to 25) {\n val rest = ca(i) - cb(i) * bestX - cc(i) * bestY\n for (j <- 1 to rest)\n print((97 + i).toChar)\n }\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport scala.math\n\nobject CF551B extends App {\n var in = new Scanner(System.in)\n val a = in.next()\n val b = in.next()\n val c = in.next()\n val ca = ('a' to 'z').map(x => a.count { y => x == y })\n val cb = ('a' to 'z').map(x => b.count { y => x == y })\n val cc = ('a' to 'z').map(x => c.count { y => x == y })\n var bestX = 0\n var bestY = 0\n for (x <- 0 to 100000) {\n var y = 100000\n for (i <- 0 to 25) {\n val tmp = ca(i) - cb(i) * x\n if (tmp < 0)\n y = -1\n else {\n if (cc(i) > 0)\n y = Math.min(y, tmp / cc(i))\n }\n }\n if (y >= 0 && x + y > bestX + bestY) {\n bestX = x\n bestY = y\n }\n }\n var str = \"\"\n for (x <- 1 to bestX) str += b\n for (y <- 1 to bestY) str += c\n for (i <- 0 to 25) {\n val rest = ca(i) - cb(i) * bestX + cc(i) * bestY\n for (j <- 1 to rest)\n str += (97 + i).toChar;\n }\n println(str)\n}"}, {"source_code": "import java.util.Scanner\nimport scala.math\n\nobject CF551B extends App {\n var in = new Scanner(System.in)\n val a = in.next()\n val b = in.next()\n val c = in.next()\n val ca = ('a' to 'z').map(x => a.count { y => x == y })\n val cb = ('a' to 'z').map(x => b.count { y => x == y })\n val cc = ('a' to 'z').map(x => c.count { y => x == y })\n var bestX = 0\n var bestY = 0\n for (x <- 0 to 100000) {\n var y = 100000\n for (i <- 0 to 25) {\n val tmp = ca(i) - cb(i) * x\n if (tmp < 0)\n y = -1\n else {\n if (cc(i) > 0)\n y = Math.min(y, tmp / cc(i))\n }\n }\n if (y >= 0 && x + y > bestX + bestY) {\n bestX = x\n bestY = y\n }\n }\n println(bestX, bestY)\n var str = \"\"\n for (x <- 1 to bestX) str += b\n for (y <- 1 to bestY) str += c\n for (i <- 0 to 25) {\n val rest = ca(i) - cb(i) * bestX - cc(i) * bestY\n for (j <- 1 to rest)\n str += (97 + i).toChar;\n }\n println(str)\n}"}, {"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val A=nextString\n val B=nextString\n val C=nextString\n val a=Array.fill(26)(0)\n val b=Array.fill(26)(0)\n val c=Array.fill(26)(0)\n val ascii0='a'.toInt\n for(i<-0 until A.length()){\n a(A(i).toInt-ascii0)+=1\n }\n for(i<-0 until B.length()){\n b(B(i).toInt-ascii0)+=1\n }\n for(i<-0 until C.length()){\n c(C(i).toInt-ascii0)+=1\n }\n var max= -3\n var maxcurrent= -1\n var nb=0\n while(maxcurrent>=max){\n max=maxcurrent\n var nc=Int.MaxValue\n\n for(i<-0 until 26){\n if(a(i)0){\n\n val ncc=(a(i)-nb*b(i))/c(i)\n if(ncc=max){\n max=maxcurrent\n var nc=Int.MaxValue\n\n for(i<-0 until 26){\n if(a(i)0){\n\n val ncc=(a(i)-nb*b(i))/c(i)\n if(ncc (prices.sum*1.0/prices.size).ceil.toInt)\n io.writeAll(ans, separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject taskA {\n def main(args: Array[String]): Unit = {\n var q = scala.io.StdIn.readInt()\n while(q > 0) {\n val n : Int = readInt()\n val array : Array[Int] = readLine().split(\" \").map(_.toInt)\n val sum : Double = array.sum\n val ans : Int = Math.ceil(sum/n).toInt\n println(ans)\n q -= 1\n }\n }\n}"}, {"source_code": "object Ex1 extends App {\n import scala.annotation.tailrec\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n\n import scala.io.Codec\n\n /**\n * Faster Scanner in Scala by wrick\n * https://codeforces.com/blog/entry/21074\n *\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n }\n\n def read2(): Seq[Seq[Int]] = {\n val in = new Scanner(System.in)\n val q = in.nextInt()\n (0 until q).map { _ =>\n val n = in.nextInt()\n (0 until n).map(_ => in.nextInt())\n }\n }\n\n def res(list: Seq[Int]) = {\n val sum = list.sum\n val len = list.length\n if (sum % len == 0) sum / len\n else sum / len + 1\n }\n\n read2().foreach(x => println(res(x)))\n\n}"}], "negative_code": [], "src_uid": "c457b77b16d94c6c4c95b7403a1dd0c7"} {"source_code": "\n/**\n * @author pvasilyev\n * @since 19 Jun 2016\n */\nobject A288 extends App {\n\n def solve() = {\n val Array(n, k): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n if (n < k) {\n println(\"-1\")\n } else if (k == 1) {\n if (n == 1) {\n println(\"a\")\n } else {\n println(\"-1\")\n }\n } else if (k == 2) {\n println((\"a b \" * n).split(\" \").take(n).mkString(\"\"))\n } else {\n val answer: Array[Char] = Array.ofDim[Char](n)\n for (j <- k.to(3, -1)) {\n answer(n - 1 - k + j) = ('a'.toInt + j - 1).toChar\n }\n var i = 0\n while (i < n - k + 2) {\n if (i % 2 == 0) {\n answer(i) = 'a'\n } else {\n answer(i) = 'b'\n }\n i += 1\n }\n println(answer.mkString(\"\"))\n }\n }\n\n solve()\n\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.StringBuilder\nimport java.util.Scanner\n\nobject Strings extends App {\n\n\tval scanner = new Scanner( System.in )\n\n\tval n = scanner.nextInt\n\tval k = scanner.nextInt\n\n\tif( n < k || n > 1 && k == 1 )\n\t\tprintln( \"-1\" )\n\telse {\n\t\t// initialize the string with default \"abab...\" value\n\t\tval sb = new StringBuilder( \"ab\" * ( n / 2 ) + \"a\" * ( n % 2 ))\n\t\t// fill the rest with k-2 different characters\n\t\tfor( i <- ( k - 1 to 2 by -1 ))\n\t\t\tsb( n - k + i ) = ( 'a' + i ).toChar\n\t\tprintln( sb.result )\n\t}\n}"}, {"source_code": "import io.Source\nimport java.io.PrintWriter\n\nobject CF288A {\n\n def solve(in: In, out: PrintWriter) {\n val n, k = in().toInt\n if (n < k || k == 1 && n > 1) {\n out.println(\"-1\")\n } else {\n for (i <- 0 until math.min(n, n - (k - 2))) {\n out.print(if (i % 2 == 0) 'a' else 'b')\n }\n for (i <- 2 until k) {\n out.print((i + 'a').toChar)\n }\n out.println()\n }\n }\n\n def main(args: Array[String]) {\n val in: In = new In(Source.fromInputStream(System.in))\n val out: PrintWriter = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() {\n while (iter.hasNext && delims.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next(): String = {\n skipDelims()\n while (iter.hasNext && delims.indexOf(iter.head) == -1) {\n sb.append(iter.next())\n }\n val ret = sb.toString()\n sb.clear()\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIterator = new TokenIterator(iter, \" \\r\\n\")\n\n val lineIterator = new TokenIterator(iter, \"\\r\\n\")\n\n def apply() = tokenIterator.next()\n\n def apply(n: Int) = tokenIterator.take(n)\n }\n}"}, {"source_code": "object C {\n def READ: Array[Int] = readLine() split (\" \") map (_.toInt);\n\n def main(args: Array[String]) {\n var Array(n, k) = READ\n if (n < k || k == 1) {\n println(if (n*k == 1) 'a' else -1);\n return;\n }\n var result:StringBuilder = new StringBuilder;\n for (i <- 1 to n-k+2) result.append(if (i%2 == 1) 'a' else 'b');\n for (i <- 1 to k-2) result.append(('a'+i+1).toChar)\n println(result)\n }\n}"}, {"source_code": "object A extends App\n{\n val Array(n, k) = readLine.split(\" \").map(_.toInt)\n if (n < k || (k==1 && n>1))\n println(-1)\n else\n {\n for (i <- 0 until math.min(n,n-k+2))\n print(if ((i&1)==0) 'a' else 'b')\n for (ch <- 'c' until ('a'+k).toChar)\n print(ch)\n println()\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n if (k > n || (n > 1 && k == 1)) println(-1)\n else if (n == 1) println(\"a\")\n else {\n println(((1 to n - k + 2).map(i => if (i % 2 == 1) 'a' else 'b').toList\n ::: ('c' until ('c' + k - 2).toChar).toList).mkString(\"\"))\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n if (k > n || (n > 1 && k == 1)) println(-1)\n else {\n println(((1 to n - k + 2).map(i => if (i % 2 == 1) 'a' else 'b').toList\n ::: ('c' until ('c' + k - 2).toChar).toList).mkString(\"\"))\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n if (k > n) println(-1)\n else {\n println(((1 to n - k + 2).map(i => if (i % 2 == 1) 'a' else 'b').toList\n ::: ('c' until ('c' + k - 2).toChar).toList).mkString(\"\"))\n }\n}"}, {"source_code": "object A extends App\n{\n val Array(n, k) = readLine.split(\" \").map(_.toInt)\n if (n < k)\n println(-1)\n else\n {\n for (i <- 0 until math.min(n,n-k+2))\n print(if ((i&1)==0) 'a' else 'b')\n for (ch <- 'c' until ('a'+k).toChar)\n print(ch)\n println()\n }\n}"}, {"source_code": "object A extends App\n{\n val Array(n, k) = readLine.split(\" \").map(_.toInt)\n if (k > n)\n println(-1)\n else\n {\n for (i <- 0 until n-k+2)\n print(if ((i&1)==0) 'a' else 'b')\n for (ch <- 'c' until ('a'+k).toChar)\n print(ch)\n println()\n }\n}"}], "src_uid": "2f659be28674a81f58f5c587b6a0f465"} {"source_code": "import scala.io.StdIn._\r\nimport scala.util.Sorting\r\n\r\nobject _1557A {\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt()\r\n while(t > 0 ){\r\n t -= 1\r\n val n = readInt()\r\n val ar = readLine().split(\" \").map(_.toDouble)\r\n Sorting.quickSort(ar)\r\n val sum : Double = (ar.sum - ar(n - 1)) / (n - 1.0);\r\n println(sum + ar(n - 1))\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt).sorted(Ordering[Int].reverse)\r\n\r\n val ans = an.head + an.tail.foldLeft(0L)(_ + _) / (n - 1.0)\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\r\nimport scala.util.Sorting\r\n\r\nobject _1557A {\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt()\r\n while(t > 0 ){\r\n t -= 1\r\n val n = readInt()\r\n val ar = readLine().split(\" \").map(_.toInt)\r\n Sorting.quickSort(ar)\r\n// println(ar.mkString(\", \"))\r\n val sum : Double = (ar.sum - ar(n - 1)) / (n - 1.0);\r\n println(sum + ar(n - 1))\r\n }\r\n }\r\n}\r\n"}], "src_uid": "159b9c743d6d8792548645b9f7be2753"} {"source_code": "//package codeforces.contests._1487\n\nobject CatCycle {\n\n def main(args: Array[String]): Unit = {\n println({\n for (_ <- 1 to io.StdIn.readInt()) yield {\n val Array(n, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n if ((n % 2) == 0) ((k - 1) % n)\n else {\n // 0 based\n val w = (k-1) / (n - 1)\n val offset = (k - 1) % (n - 1)\n val start = w % n\n\n (if (offset < n / 2) (start + offset) % n else (start + offset + 1) % n)\n }\n\n } + 1\n }.mkString(\"\\n\"))\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\r\n\r\nobject Cat_Cycle extends App{\r\n val t = readInt()\r\n var n = 0\r\n var k = 0\r\n for (i <- 1 to t) {\r\n val Array(x, y) = readLine().split(\" \").map(_.toInt)\r\n n = x // Number of spots\r\n k = y // Hours\r\n var A = n\r\n var B = 1\r\n if (n % 2 == 0) {\r\n if (k % n == 0) {\r\n println(n)\r\n }\r\n else {\r\n println(k % n)\r\n }\r\n }\r\n else {\r\n val step = n / 2\r\n val meets = (k - 1) / step\r\n if ((B * k) % n == 0) B = n else B = (B * k) % n\r\n B += meets\r\n if (B % n == 0) B = n else B = B % n\r\n println(B)\r\n }\r\n }\r\n}\r\n\r\n"}, {"source_code": "\r\nobject B {\r\n import scala.io.{StdIn => in}\r\n\r\n def main(args: Array[String]): Unit = {\r\n val tests = in.readInt()\r\n (1 to tests).foreach { _ =>\r\n val Array(n, k) = in.readLine().split(' ').map(_.toInt)\r\n println((k - 1 + n % 2 * (k - 1) / (n / 2)) % n + 1)\r\n }\r\n }\r\n}\r\n"}, {"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, k = nextInt\n val b = if (n % 2 == 0) (k - 1) % n\n else (k + (k - 1) / (n / 2) - 1) % n\n\n out.println(b + 1)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\r\n\r\nobject Cat_Cycle extends App{\r\n val t = readInt()\r\n var n = 0\r\n var k = 0\r\n for (i <- 1 to t) {\r\n val Array(x, y) = readLine().split(\" \").map(_.toInt)\r\n n = x // Number of spots\r\n k = y // Hours\r\n var A = n\r\n var B = 1\r\n if (n % 2 == 0) {\r\n if (k % n == 0) {\r\n println(n)\r\n }\r\n else {\r\n println(k % n)\r\n }\r\n }\r\n else {\r\n val step = n / 2\r\n val meets = (k - 1) / step\r\n if ((B * k) % n == 0) B = n else B = (B * k) % n\r\n B += meets\r\n if (B % n == 0) B == n else B = B % n\r\n println(B)\r\n }\r\n }\r\n}\r\n\r\n"}, {"source_code": "import scala.io.StdIn._\r\n\r\nobject test extends App {\r\n val t = readInt()\r\n var n = 0;\r\n var k = 0\r\n for (i <- 1 to t) {\r\n val Array(x, y) = readLine().split(\" \").map(_.toInt)\r\n n = x // Number of spots\r\n k = y // Hours\r\n if (n % 2 == 0) {\r\n if (k % n == 0) {\r\n println(n)\r\n }\r\n else {\r\n println(k % n)\r\n }\r\n }\r\n else {\r\n var A = n\r\n var B = 1\r\n for (j <- 1 until k) {\r\n A -= 1\r\n B += 1\r\n if (A < 1) {\r\n A += n\r\n }\r\n if (B > n) {\r\n B -= n\r\n }\r\n if (A == B) {\r\n B += 1\r\n }\r\n }\r\n println(B)\r\n }\r\n }\r\n\r\n}"}, {"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, k = nextInt\n var a = n - 1\n var b = 0\n if (n % 2 == 0) {\n b = (k - 1) % n\n } else {\n var rep = -1\n var step = 0\n while (step < k - 1) {\n val d = Math.min(k - step -1, (a - b - 1) / 2)\n if (a == n - 1 && b == 0 && step > 0 && step * 2 < k) {\n println(step, rep, a, b)\n if (rep == -1) {\n rep = step\n } else {\n step += (k - step - 1) / rep * rep\n }\n } else if (d > 0) {\n a -= d\n b += d\n step += d\n } else if (b + 2 == a) {\n a -= 1\n b += 2\n step += 1\n } else {\n val dd = Math.min(k - step-1, (n - 1) / 2)\n a = (a + n - dd) % n\n b = (b + n + dd) % n\n if (b == a) b = (b + 1) % n\n step += dd\n }\n// println(step, a, b)\n }\n }\n// println(b + 1)\n out.println(b + 1)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "src_uid": "2e837d3afc48177516578a950e957586"} {"source_code": "object Solver {\n def main(args: Array[String]) {\n var total = 0\n var n = Console.readLine.toInt\n var drinks = Set(\"ABSINTH\", \"BEER\", \"BRANDY\", \"CHAMPAGNE\", \"GIN\", \"RUM\", \"SAKE\", \"TEQUILA\", \"VODKA\", \"WHISKEY\", \"WINE\")\n\n for (i <- 1 to n) {\n var input = Console.readLine\n var suspicious = if ( input.forall(_.isDigit) ) input.toInt < 18 else drinks.contains(input)\n if (suspicious) total += 1\n }\n println(total)\n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val drinks = List(\"ABSINTH\", \"BEER\", \"BRANDY\", \"CHAMPAGNE\", \"GIN\", \"RUM\", \"SAKE\",\n \"TEQUILA\", \"VODKA\", \"WHISKEY\", \"WINE\")\n println((1 to n).count{\n _ => val str = in.next()\n if (str.forall(_.isDigit))\n str.toInt < 18\n else\n drinks.contains(str)\n })\n}"}, {"source_code": "object A56 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(tests) = readInts(1)\n var res = 0\n val alcohol = Array(\"ABSINTH\", \"BEER\", \"BRANDY\", \"CHAMPAGNE\", \"GIN\", \"RUM\", \"SAKE\", \"TEQUILA\", \"VODKA\", \"WHISKEY\", \"WINE\")\n for(_ <- 1 to tests) {\n val str = read\n if(alcohol.contains(str))\n res += 1\n else {\n util.Try{str.toInt}.foreach { int=>\n if(int < 18)\n res += 1\n }\n }\n }\n out.println(res)\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "/**\n * Created by John Compitello on 7/26/16.\n */\nobject Main {\n def main(args: Array[String]) = {\n val drinkList: List[String] = List(\"ABSINTH\", \"BEER\", \"BRANDY\", \"CHAMPAGNE\", \"GIN\", \"RUM\",\n \"SAKE\", \"TEQUILA\", \"VODKA\", \"WHISKEY\", \"WINE\")\n val lines: Array[String] = (for (ln <- io.Source.stdin.getLines) yield ln).toArray\n val numClients = lines(0).toInt\n val clientList = lines.tail\n\n val (numList, nameList): (Array[String], Array[String]) = clientList.partition(isANumber)\n\n println(numList.map(_ toInt).filter(_ < 18).length + nameList.filter(x => drinkList contains x).length)\n }\n\n //Must check people in client list who are either drinking alcohol or under 18.\n def isANumber(x: String): Boolean = x forall Character.isDigit\n}\n"}], "negative_code": [], "src_uid": "4b7b0fba7b0af78c3956c34c29785e7c"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(left: Int, right: Int, index: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (left < that.left || (left == that.left && right < that.right))\n return -1\n else if (left == that.left && right == that.right)\n return 0\n else\n return 1\n }\n }\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val ans = new ArrayBuffer[(Int, Int, Int)]()\n val arr = new Array[Int](n)\n for (i <- 1 to n)\n arr(i-1) = readInt()\n for (i <- 0 until n) {\n var mm = arr(i)\n var po = i\n for (j <- i until n)\n if (arr(j) < mm) {\n mm = arr(j)\n po = j\n }\n if (po != i) {\n ans.append((i+1, po+1, po-i))\n for (j <- (i until po).reverse)\n arr(j+1) = arr(j)\n arr(i) = mm\n }\n }\n writer.println(ans.length)\n for (mv <- ans)\n writer.println(mv._1 + \" \" + mv._2 + \" \" + mv._3)\n }\n writer.flush()\n}\n", "positive_code": [{"source_code": "object B extends App {\r\n\r\n type Shift = (Int, Int, Int)\r\n\r\n def shiftingSort(an: IndexedSeq[Int]): List[Shift] = {\r\n val bn = an.zipWithIndex.sorted\r\n\r\n bn.indices\r\n .foldLeft(List.empty[Shift]) { (shifts, i) =>\r\n val j = shifts.foldRight(bn(i)._2) {\r\n case ((l, r, d), j) if l <= j && j <= r =>\r\n val size = r - l + 1\r\n l + (j - l - d + size) % size\r\n case (_, j) => j\r\n }\r\n\r\n if (i == j) shifts else (i, j, j - i) :: shifts\r\n }\r\n .reverse\r\n }\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n val shifts = shiftingSort(an)\r\n\r\n println(shifts.length)\r\n println(shifts.map { case (l, r, d) => s\"${l + 1} ${r + 1} $d\" }.mkString(\"\\n\"))\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n\r\n type Shift = (Int, Int, Int)\r\n\r\n def shiftingSort(an: IndexedSeq[Int]): List[Shift] = {\r\n val bn = an.zipWithIndex.sorted\r\n\r\n bn.indices\r\n .foldLeft(List.empty[Shift]) { (shifts, i) =>\r\n val j = shifts.reverse.foldLeft(bn(i)._2) {\r\n case (j, (l, r, d)) if l <= j && j <= r => l + (j - l - d + r - l + 1) % (r - l + 1)\r\n case (j, _) => j\r\n }\r\n\r\n if (i == j) shifts else (i, j, j - i) :: shifts\r\n }\r\n .reverse\r\n }\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n val shifts = shiftingSort(an)\r\n\r\n println(shifts.length)\r\n println(shifts.map { case (l, r, d) => s\"${l + 1} ${r + 1} $d\" }.mkString(\"\\n\"))\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(left: Int, right: Int, index: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (left < that.left || (left == that.left && right < that.right))\n return -1\n else if (left == that.left && right == that.right)\n return 0\n else\n return 1\n }\n }\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val ans = new ArrayBuffer[(Int, Int, Int)]()\n val arr = new Array[Int](n)\n for (i <- 1 to n)\n arr(i-1) = readInt()\n for (i <- 0 until n) {\n var mm = arr(i)\n var po = i\n for (j <- i until n)\n if (arr(j) < mm) {\n mm = arr(j)\n po = j\n }\n if (po != i) {\n ans.append((i+1, po+1, po-i))\n for (j <- i until po)\n arr(j+1) = arr(j)\n arr(i) = mm\n }\n }\n writer.println(ans.length)\n for (mv <- ans)\n writer.println(mv._1 + \" \" + mv._2 + \" \" + mv._3)\n }\n writer.flush()\n}\n"}], "src_uid": "06c515c2d889edec8db784b2d5279edc"} {"source_code": "import java.io.BufferedWriter\nimport java.io.OutputStreamWriter\nimport java.util.StringTokenizer\n\nimport scala.util.Try\n\nobject G extends App {\n val INF = 1 << 30\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n\n read()\n val n = int()\n val t = int()\n val k = int()\n read()\n val a = 1 +: Array.fill(t)(int()) :+ 0\n\n Try {\n val kmin = (0 to t).foldLeft(0)((sum, i) => sum + Math.max(0, a(i)-a(i+1)))\n assert(kmin <= k)\n var dk = k - kmin\n\n val lines = new Array[Int](n+1)\n val heads = new Array[Int](t+1)\n var j = 1\n for (i <- 0 to t) {\n heads(i) = j\n j += a(i)\n }\n var l = 0\n for (i <- 1 to n) {\n if (heads(l) + a(l) <= i) l += 1\n lines(i) = l\n }\n\n val links = new Array[Int](n+1)\n for (i <- 2 to n) {\n l = lines(i)\n if (i == heads(l)) {\n links(i) = heads(l-1)\n } else {\n val z = i - heads(l) + heads(l - 1)\n val onPrev = lines(z) == l - 1\n if (dk > 0) {\n links(i) = heads(l-1)\n if (onPrev) dk -= 1\n } else {\n if (onPrev) links(i) = z\n else links(i) = heads(l-1)\n }\n }\n }\n assert(dk == 0)\n\n val out = new BufferedWriter(new OutputStreamWriter(System.out))\n out.write(n + \"\\n\")\n for (i <- 2 to n) out.write(links(i) + \" \" + i + \"\\n\")\n out.close()\n\n }.getOrElse(println(-1))\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.util.Try\n\nobject G extends App {\n val INF = 1 << 30\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n\n read()\n val n = int()\n val t = int()\n val k = int()\n read()\n val a = 1 +: Array.fill(t)(int()) :+ 0\n\n Try {\n val kmin = (0 to t).foldLeft(0)((sum, i) => sum + Math.max(0, a(i)-a(i+1)))\n assert(kmin <= k)\n var dk = k - kmin\n\n val lines = new Array[Int](n+1)\n val heads = new Array[Int](t+1)\n var j = 1\n for (i <- 0 to t) {\n heads(i) = j\n j += a(i)\n }\n var l = 0\n for (i <- 1 to n) {\n if (heads(l) + a(l) <= i) l += 1\n lines(i) = l\n }\n\n val links = new Array[Int](n+1)\n for (i <- 2 to n) {\n l = lines(i)\n if (i == heads(l)) {\n links(i) = heads(l-1)\n } else {\n val z = i - heads(l) + heads(l - 1)\n val onPrev = lines(z) == l - 1\n if (dk > 0) {\n links(i) = heads(l-1)\n if (onPrev) dk -= 1\n } else {\n if (onPrev) links(i) = z\n else links(i) = heads(l-1)\n }\n }\n }\n assert(dk == 0)\n\n println(n)\n for (i <- 2 to n) println(links(i) + \" \" + i)\n\n }.getOrElse(println(-1))\n}\n"}, {"source_code": "import java.io.PrintWriter\nimport java.util.StringTokenizer\n\nimport scala.util.Try\n\nobject G extends App {\n val INF = 1 << 30\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n\n read()\n val n = int()\n val t = int()\n val k = int()\n read()\n val a = 1 +: Array.fill(t)(int()) :+ 0\n\n Try {\n val kmin = (0 to t).foldLeft(0)((sum, i) => sum + Math.max(0, a(i)-a(i+1)))\n assert(kmin <= k)\n var dk = k - kmin\n\n val lines = new Array[Int](n+1)\n val heads = new Array[Int](t+1)\n var j = 1\n for (i <- 0 to t) {\n heads(i) = j\n j += a(i)\n }\n var l = 0\n for (i <- 1 to n) {\n if (heads(l) + a(l) <= i) l += 1\n lines(i) = l\n }\n\n val links = new Array[Int](n+1)\n for (i <- 2 to n) {\n l = lines(i)\n if (i == heads(l)) {\n links(i) = heads(l-1)\n } else {\n val z = i - heads(l) + heads(l - 1)\n val onPrev = lines(z) == l - 1\n if (dk > 0) {\n links(i) = heads(l-1)\n if (onPrev) dk -= 1\n } else {\n if (onPrev) links(i) = z\n else links(i) = heads(l-1)\n }\n }\n }\n assert(dk == 0)\n\n val out = new PrintWriter(System.out)\n out.println(n)\n for (i <- 2 to n) out.println(links(i) + \" \" + i)\n out.close()\n\n }.getOrElse(println(-1))\n}\n"}], "negative_code": [], "src_uid": "7ebf821d51383f1633947a3b455190f6"} {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nobject test {\r\n val writer = new PrintWriter(System.out)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {\r\n while (!st.hasMoreTokens) {\r\n st = new StringTokenizer(reader.readLine())\r\n }\r\n st.nextToken()\r\n }\r\n def readInt(): Int = next.toInt\r\n def readLong(): Long = next.toLong\r\n def readString(): String = next()\r\n\r\n def main(args: Array[String]): Unit = {\r\n val t = readInt()\r\n var n = 0\r\n var s = \"\"\r\n for (tt <- 1 to t) {\r\n n = readInt()\r\n s = readString()\r\n for (i <- 0 until s.length) {\r\n if (s(i) == 'U')\r\n writer.print('D')\r\n else if (s(i) == 'D')\r\n writer.print('U')\r\n else if (s(i) == 'L')\r\n writer.print('L')\r\n else writer.print('R')\r\n }\r\n writer.flush()\r\n println()\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nobject test {\r\n class FastReader() {\r\n br = new BufferedReader(new InputStreamReader(System.in))\r\n var br: BufferedReader = _\r\n var st: StringTokenizer = _\r\n\r\n def next: String = {\r\n while ( {\r\n st == null || !st.hasMoreElements\r\n }) try st = new StringTokenizer(br.readLine)\r\n catch {\r\n case e: IOException =>\r\n e.printStackTrace()\r\n }\r\n st.nextToken\r\n }\r\n\r\n def nextInt: Int = next.toInt\r\n\r\n def nextLong: Long = next.toLong\r\n\r\n def nextDouble: Double = next.toDouble\r\n\r\n def nextLine: String = {\r\n var str = \"\"\r\n try str = br.readLine\r\n catch {\r\n case e: IOException =>\r\n e.printStackTrace()\r\n }\r\n str\r\n }\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val fastReader = new test.FastReader\r\n val t = fastReader.nextInt\r\n var n = 0\r\n var s = \"\"\r\n for (tt <- 1 to t) {\r\n n = fastReader.nextInt\r\n s = fastReader.nextLine\r\n for (i <- 0 until s.length) {\r\n if (s(i) == 'U')\r\n print('D')\r\n else if (s(i) == 'D')\r\n print('U')\r\n else if (s(i) == 'L')\r\n print('L')\r\n else print('R')\r\n }\r\n println()\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn._\r\n\r\nobject test {\r\n def main(args: Array[String]): Unit = {\r\n val t = readInt()\r\n var n = 0\r\n var s = \"\"\r\n for (tt <- 1 to t) {\r\n n = readInt()\r\n s = readLine()\r\n for (i <- 0 until s.length) {\r\n if (s(i) == 'U')\r\n print('D')\r\n else if (s(i) == 'D')\r\n print('U')\r\n else if (s(i) == 'L')\r\n print('L')\r\n else print('R')\r\n }\r\n println()\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn._\r\n\r\nobject test {\r\n def main(args: Array[String]): Unit = {\r\n val t = readInt()\r\n var n = 0\r\n var s = \"\"\r\n for (tt <- 1 to t) {\r\n n = readInt()\r\n s = readLine()\r\n for (x <- s) {\r\n if (x == 'U')\r\n print('D')\r\n else if (x == 'D')\r\n print('U')\r\n else if (x == 'L')\r\n print('L')\r\n else print('R')\r\n }\r\n println()\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn._\r\n\r\nobject test {\r\n def main(args: Array[String]): Unit = {\r\n val mp = Map('U' -> 'D', 'D' -> 'U', 'L' -> 'L', 'R' -> 'R')\r\n val t = readInt()\r\n var n = 0\r\n var s = \"\"\r\n for (tt <- 1 to t) {\r\n n = readInt()\r\n s = readLine()\r\n for (i <- s)\r\n print(mp(i))\r\n println()\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn._\r\n\r\nobject test {\r\n def main(args: Array[String]): Unit = {\r\n val mp = Map('U' -> 'D', 'D' -> 'U', 'L' -> 'L', 'R' -> 'R')\r\n val t = readInt()\r\n var n = 0\r\n var s = \"\"\r\n for (tt <- 1 to t) {\r\n n = readInt()\r\n s = readLine()\r\n for (i <- 0 until s.length)\r\n print(mp(s(i)))\r\n println()\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn._\r\n\r\nobject test {\r\n def main(args: Array[String]): Unit = {\r\n val mp = Map('U' -> 'D', 'D' -> 'U', 'L' -> 'L', 'R' -> 'R')\r\n val t = readInt()\r\n for (tt <- 1 to t) {\r\n val n = readInt()\r\n val s = readLine()\r\n for (i <- 0 until s.length)\r\n print(mp(s(i)))\r\n println()\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn._\r\n\r\nobject test {\r\n def main(args: Array[String]): Unit = {\r\n val mp = Map('U' -> 'D', 'D' -> 'U', 'L' -> 'L', 'R' -> 'R')\r\n var t = readInt()\r\n for (tt <- 1 to t) {\r\n var n = readInt()\r\n var s = readLine()\r\n for (i <- 0 until s.length)\r\n print(mp(s(i)))\r\n println()\r\n }\r\n }\r\n}\r\n"}, {"source_code": "object A extends App {\r\n\r\n def grid(row: String): String =\r\n row.map {\r\n case 'U' => 'D'\r\n case 'D' => 'U'\r\n case 'L' => 'L'\r\n case 'R' => 'R'\r\n }\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val s = readLine()\r\n\r\n println(grid(s))\r\n }\r\n\r\n}\r\n"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport scala.util.Sorting.quickSort\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val writer = new PrintWriter(System.out)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {\r\n while (!st.hasMoreTokens) {\r\n st = new StringTokenizer(reader.readLine())\r\n }\r\n st.nextToken()\r\n }\r\n\r\n def readInt() = next.toInt\r\n def readLong() = next.toLong\r\n def readString() = next()\r\n\r\n def pow(a: Int, b: Int): Long = {\r\n if (b == 0) return 1\r\n\r\n val rs = pow(a, b / 2)\r\n rs * rs * (if (b % 2 == 0) 1 else a)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b\r\n\r\n def root(u: Int, p: Array[Int]): Int = {\r\n if (p(u) < 0) return u\r\n p(u) = root(p(u), p)\r\n p(u)\r\n }\r\n\r\n def join(u: Int, v: Int, p: Array[Int]): Unit = {\r\n var x = root(u, p)\r\n var y = root(v, p)\r\n if (x == y) return\r\n\r\n if (p(y) < p(x)) {\r\n val t = x\r\n x = y\r\n y = t\r\n }\r\n p(x) += p(y)\r\n p(y) = x\r\n }\r\n\r\n def solve(t: Int = 0): Unit = {\r\n val n = readInt()\r\n val s = readString()\r\n for (i <- 0 until n ) {\r\n if (s(i) == 'U')\r\n writer.print('D')\r\n else if (s(i) == 'D')\r\n writer.print('U')\r\n else writer.print(s(i))\r\n }\r\n\r\n writer.println()\r\n\r\n }\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def main(args: Array[String]) {\r\n multiTest(solve)\r\n //solve()\r\n writer.flush()\r\n }\r\n}"}], "negative_code": [{"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nobject test {\r\n val writer = new PrintWriter(System.out)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {\r\n while (!st.hasMoreTokens) {\r\n st = new StringTokenizer(reader.readLine())\r\n }\r\n st.nextToken()\r\n }\r\n def readInt(): Int = next.toInt\r\n def readLong(): Long = next.toLong\r\n def readString(): String = next()\r\n\r\n def main(args: Array[String]): Unit = {\r\n val t = readInt()\r\n var n = 0\r\n var s = \"\"\r\n for (tt <- 1 to t) {\r\n n = readInt()\r\n s = readString()\r\n for (i <- 0 until s.length) {\r\n if (s(i) == 'U')\r\n writer.print('D')\r\n else if (s(i) == 'D')\r\n writer.print('U')\r\n else if (s(i) == 'L')\r\n writer.print('L')\r\n else writer.print('R')\r\n }\r\n println()\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn._\r\n\r\nobject test {\r\n def main(args: Array[String]): Unit = {\r\n val mp = Map('U' -> 'D', 'D' -> 'U', 'L' -> 'R', 'R' -> 'L')\r\n var t = readInt()\r\n for (tt <- 1 to t) {\r\n var n = readInt()\r\n var s = readLine()\r\n for (i <- 0 until s.length)\r\n print(mp(s(i)))\r\n println()\r\n }\r\n }\r\n}\r\n"}], "src_uid": "b894e16e8c00f8d97fde4a104466b3ef"} {"source_code": "object C{\n def main(args:Array[String]){\n\n val n=readLine.toInt\n //arcs\n val arcs=new Array[Set[Int]](n);\n (0 to n-1).foreach(i=> arcs(i)=Set())\n\n (1 to 2*n).foreach{i=>\n val (a,b)={\n val sp=readLine.split(\" \")\n (sp(0).toInt-1 , sp(1).toInt-1)\n }\n arcs(a)+=b\n arcs(b)+=a\n }//arc\n\n\n if(arcs.count(_.size!=4)>0){\n //NG\n println(-1)\n return\n }\n\n //check\n def check(p:List[Int]):Boolean={\n if(p.length!=n){\n false\n }else{\n val ap=p.toArray\n val arcs2=new Array[Set[Int]](n);\n (0 until n).foreach{i=>\n arcs2(ap(i))=Set(-2,-1,1,2).map{ii=>ap((i+ii+n)%n)}\n }\n //ret\n (0 to n-1).forall{i=>\n arcs(i)==arcs2(i)\n }\n }\n }\n\n //p or null\n val p=\n if(n<=6){\n //全pをcheck\n (0 until n).permutations.map(_.toList).find(check(_)).orNull\n\n }else{\n //pp\n val pp:List[Int]={\n val done=new Array[Boolean](n)\n val l=scala.collection.mutable.ListBuffer[Int]()\n\n def rec(now:Int){\n done(now)=true\n def neighbor(a:Int, b:Int):Boolean={\n (arcs(a)&arcs(b)).size==2\n }\n val nbopt=arcs(now).find{a=> !done(a)&&neighbor(a,now)}\n l+=now\n if(nbopt.isDefined){\n rec(nbopt.get)\n }\n }\n rec(0)\n l.toList\n }//pp\n\n if(check(pp)) pp else null\n }//p\n\n println(if(p==null) -1 else p.map(_ +1).mkString(\" \"))//end\n }\n}\n", "positive_code": [{"source_code": "object C{\n def main(args:Array[String]){\n\n val n=readLine.toInt\n //arcs\n val arcs=new Array[Set[Int]](n);\n (0 to n-1).foreach(i=> arcs(i)=Set())\n\n (1 to 2*n).foreach{i=>\n val (a,b)={\n val sp=readLine.split(\" \")\n (sp(0).toInt-1 , sp(1).toInt-1)\n }\n arcs(a)+=b\n arcs(b)+=a\n }//arc\n\n\n if(arcs.count(_.size!=4)>0){\n //NG\n println(-1)\n return\n }\n\n //check\n def check(p:List[Int]):Boolean={\n if(p.length!=n){\n false\n }else{\n val ap=p.toArray\n val arcs2=new Array[Set[Int]](n);\n (0 until n).foreach{i=>\n arcs2(ap(i))=Set(-2,-1,1,2).map{ii=>ap((i+ii+n)%n)}\n }\n //ret\n (0 to n-1).forall{i=>\n arcs(i)==arcs2(i)\n }\n }\n }\n\n //p or null\n val p=\n if(n<=6){\n //全pをcheck\n (0 until n).permutations.map(_.toList).find(check(_)).orNull\n\n }else{\n val done=new Array[Boolean](n)\n //pp\n val pp={\n def rec(now:Int,l:List[Int]):List[Int]={\n done(now)=true\n def neighbor(a:Int, b:Int):Boolean={\n (arcs(a)&arcs(b)).size==2\n }\n val nbopt=arcs(now).find{a=> !done(a)&&neighbor(a,now)}\n if(nbopt.isEmpty){\n now::l\n }else{\n rec(nbopt.get,now::l)\n }\n }\n rec(0,Nil)\n }//pp\n\n if(check(pp)) pp else null\n }//p\n\n println(if(p==null) -1 else p.map(_ +1).mkString(\" \"))//end\n }\n}\n"}], "negative_code": [{"source_code": "object C{\n def main(args:Array[String]){\n\n val n=readLine.toInt\n //arcs\n val arcs=new Array[Set[Int]](n);\n (0 to n-1).foreach(i=> arcs(i)=Set())\n\n (1 to 2*n).foreach{i=>\n val (a,b)={\n val sp=readLine.split(\" \")\n (sp(0).toInt-1 , sp(1).toInt-1)\n }\n arcs(a)+=b\n arcs(b)+=a\n }//arc\n\n\n if(arcs.count(_.size!=4)>0){\n //NG\n println(-1)\n return\n }\n\n //check\n def check(p:List[Int]):Boolean={\n if(p.length!=n){\n false\n }else{\n val ap=p.toArray\n val arcs2=new Array[Set[Int]](n);\n (0 until n).foreach{i=>\n arcs2(ap(i))=Set(-2,-1,1,2).map{ii=>ap((i+ii+n)%n)}\n }\n //ret\n (0 to n-1).forall{i=>\n arcs(i)==arcs2(i)\n }\n }\n }\n\n //p or null\n val p=\n if(n<=6){\n //全pをcheck\n (0 until n).permutations.map(_.toList).find(check(_)).orNull\n\n }else{\n val done=new Array[Boolean](n)\n //pp\n val pp={\n def rec(now:Int,l:List[Int]):List[Int]={\n def neighbor(a:Int, b:Int):Boolean={\n (arcs(a)&arcs(b)).size==2\n }\n val nbopt=arcs(now).find{a=> !done(a)&&neighbor(a,now)}\n if(nbopt.isEmpty){\n now::l\n }else{\n done(nbopt.get)=true\n rec(nbopt.get,now::l)\n }\n }\n rec(0,Nil)\n }//pp\n\n if(check(pp)) pp else null\n }//p\n\n println(if(p==null) -1 else p.map(_ +1).mkString(\" \"))//end\n }\n}\n"}], "src_uid": "41ece21ebd61bf98a3ec8bd4a932cf03"} {"source_code": "import java.util\nimport java.util.Comparator\nimport java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\n\nobject EBooks extends App {\n\n val scanner = new Scanner(System.in)\n\n val num = scanner.nextInt()\n val diff = scanner.nextInt()\n var cnt = 0\n val buf = ArrayBuffer.empty[(Int, Int)]\n val books = (0 until num).map(i => scanner.next().toInt)\n\n val ordMin = new util.TreeSet[Int](new Comparator[Int] {\n override def compare(o1: Int, o2: Int): Int = {\n val c = books(o1).compareTo(books(o2))\n if (c == 0) o2.compareTo(o1)\n else c\n }\n })\n\n val deq = new java.util.LinkedList[Int]()\n deq.add(0)\n ordMin.add(0)\n\n (1 until num) foreach {\n i =>\n val elem = books(i)\n val minD = math.abs(elem - books(ordMin.first()))\n val maxD = math.abs(elem - books(ordMin.last()))\n if (minD > diff || maxD > diff) {\n recordResult()\n if (maxD > diff) {\n while (!deq.isEmpty && deq.getLast != ordMin.last()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n }\n if (minD > diff) {\n while (deq.getLast != ordMin.first()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n }\n if (!deq.isEmpty) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n deq.addFirst(i)\n if (!ordMin.isEmpty && books(ordMin.last()) == books(i)) ordMin.pollLast()\n ordMin.add(i)\n } else {\n deq.addFirst(i)\n if (!ordMin.isEmpty && books(ordMin.last()) == books(i)) ordMin.pollLast()\n ordMin.add(i)\n }\n }\n recordResult()\n println(cnt + \" \" + buf.size)\n buf.foreach(item => {\n println(item._2 + \" \" + item._1)\n })\n System.exit(0)\n\n\n def recordResult(): Unit = {\n if (deq.size() > cnt) {\n cnt = deq.size()\n buf.clear()\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n } else if (deq.size() == cnt) {\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n }\n }\n\n}", "positive_code": [{"source_code": "object P6E {\n class SegTree(m : Int, k : Int) {\n val s = 1 << Math.getExponent(m.toFloat) + 1\n val a = Array.fill(s + s){0}\n var time = 1\n def op(n : Int) = {\n def f(d : Int)(n : Int) {\n var i = s + n\n while (i > 1) {\n val c = i ^ 1\n val p = i >>> 1\n if ((i & 1) == d) a(c) = time\n a(p) = a(i) min a(c) max a(p)\n i = p\n }\n }\n f(1)(n - k max 0)\n f(0)(n)\n val timeP = time\n time = time + 1\n timeP - a(1)\n }\n }\n\n def main(args : Array[String]) {\n val Array(n, k) = readLine split ' ' map {_.toInt}\n val h = readLine split ' ' map {_.toInt}\n val st = new SegTree(h.max + 1, k)\n val s = for (hi <- h) yield st op hi\n val s1 = s.max\n val r = for {\n i <- 0 until n\n if (s(i) == s1)\n } yield i + 1\n println(s1 + \" \" + r.size)\n for (i <- r) println(i - s1 + 1 + \" \" + i)\n }\n}\n"}], "negative_code": [{"source_code": "import java.util\nimport java.util.Comparator\nimport java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\n\nobject EBooks extends App {\n\n val scanner = new Scanner(System.in)\n\n val num = scanner.nextInt()\n val diff = scanner.nextInt()\n var cnt = 0\n val buf = ArrayBuffer.empty[(Int, Int)]\n val books = (0 until num).map(i => scanner.next().toInt)\n\n val ordMin = new util.TreeSet[Int](new Comparator[Int] {\n override def compare(o1: Int, o2: Int): Int = {\n val c = books(o1).compareTo(books(o2))\n if (c == 0) o2.compareTo(o1)\n else c\n }\n\n })\n\n val deq = new java.util.LinkedList[Int]()\n deq.add(0)\n ordMin.add(0)\n\n (1 until num) foreach {\n i =>\n val elem = books(i)\n val minD = math.abs(elem - books(ordMin.first()))\n val maxD = math.abs(elem - books(ordMin.last()))\n if (minD > diff || maxD > diff) {\n recordResult()\n if (minD > diff)\n while (deq.getLast != ordMin.first()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n if (maxD > diff)\n while (!deq.isEmpty && deq.getLast != ordMin.last()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n if (!deq.isEmpty) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n deq.addFirst(i)\n ordMin.add(i)\n } else {\n deq.addFirst(i)\n ordMin.add(i)\n }\n }\n recordResult()\n println(cnt + \" \" + buf.size)\n buf.foreach(item => {\n println(item._2 + \" \" + item._1)\n })\n System.exit(0)\n\n\n def recordResult(): Unit = {\n if (deq.size() > cnt) {\n cnt = deq.size()\n buf.clear()\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n } else if (deq.size() == cnt) {\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n }\n }\n\n}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\n\nobject EBooks extends App {\n\n val scanner = new Scanner(System.in)\n\n val num = scanner.nextInt()\n val diff = scanner.nextInt()\n var cnt = 0\n val buf = ArrayBuffer.empty[(Int, Int)]\n val books = (0 until num).map(i => scanner.next().toInt).toArray\n\n val deq = new java.util.LinkedList[Int]()\n var min = 0\n var max = 0\n deq.add(0)\n\n (1 until num) foreach { i =>\n val elem = books(i)\n val minD = math.abs(elem - books(min))\n val maxD = math.abs(elem - books(max))\n if (minD > diff) {\n recordResult()\n while (deq.getFirst != min) deq.removeFirst()\n deq.removeFirst()\n deq.addLast(i)\n findMin()\n findMax()\n } else if (maxD > diff) {\n recordResult()\n while (deq.getFirst != max) deq.removeFirst()\n deq.removeFirst()\n deq.addLast(i)\n findMin()\n findMax()\n } else {\n if (books(min) >= elem) min = i\n if (books(max) <= elem) max = i\n deq.addLast(i)\n }\n }\n recordResult()\n\n def findMin(): Unit = {\n var i = 0\n min = 0\n while (i < deq.size()) {\n if (books(deq.get(i)) <= books(min)) min = i\n i += 1\n }\n }\n\n def findMax(): Unit = {\n var i = 0\n max = 0\n while (i < deq.size()) {\n if (books(deq.get(i)) >= books(max)) max = i\n i += 1\n }\n }\n\n\n println(cnt + \" \" + buf.size)\n buf.foreach(item => {\n println(item._1 + \" \" + item._2)\n })\n\n def recordResult(): Unit = {\n if (deq.size() > cnt) {\n cnt = deq.size()\n buf.clear()\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n } else if (deq.size() == cnt) {\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n }\n }\n\n}"}, {"source_code": "import java.util\nimport java.util.Comparator\nimport java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\n\nobject EBooks extends App {\n\n val scanner = new Scanner(System.in)\n\n val num = scanner.nextInt()\n val diff = scanner.nextInt()\n var cnt = 0\n val buf = ArrayBuffer.empty[(Int, Int)]\n val books = (0 until num).map(i => scanner.next().toInt)\n\n val ordMin = new util.TreeSet[Int](new Comparator[Int] {\n override def compare(o1: Int, o2: Int): Int = {\n val c = books(o1).compareTo(books(o2))\n if (c == 0) o1.compareTo(o2)\n else c\n }\n\n })\n\n val deq = new java.util.LinkedList[Int]()\n deq.add(0)\n ordMin.add(0)\n\n (1 until num) foreach {\n i =>\n val elem = books(i)\n val minD = math.abs(elem - books(ordMin.first()))\n val maxD = math.abs(elem - books(ordMin.last()))\n //if (!ordMin.isEmpty) println(books(ordMin.first()) + \" \" + books(ordMin.last()) + \" \")\n if (minD > diff || maxD > diff) {\n recordResult()\n if (minD > diff)\n while (deq.getLast != ordMin.first()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n if (maxD > diff)\n while (!deq.isEmpty && deq.getLast != ordMin.last()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n if (!deq.isEmpty) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n deq.addFirst(i)\n ordMin.add(i)\n } else {\n deq.addFirst(i)\n ordMin.add(i)\n }\n }\n recordResult()\n println(cnt + \" \" + buf.size)\n buf.foreach(item => {\n println(item._2 + \" \" + item._1)\n })\n System.exit(0)\n\n\n def recordResult(): Unit = {\n if (deq.size() > cnt) {\n cnt = deq.size()\n buf.clear()\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n } else if (deq.size() == cnt) {\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n }\n }\n\n}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\n\nobject EBooks extends App {\n\n val scanner = new Scanner(System.in)\n\n val num = scanner.nextInt()\n val diff = scanner.nextInt()\n var cnt = 0\n val buf = ArrayBuffer.empty[(Int, Int)]\n val books = (0 until num).map(i => scanner.next().toInt).toArray\n\n val deq = new java.util.LinkedList[Int]()\n var min = 0\n var max = 0\n deq.add(0)\n\n (1 until num) foreach { i =>\n val elem = books(i)\n val minD = math.abs(elem - books(min))\n val maxD = math.abs(elem - books(max))\n if (minD > diff) {\n recordResult()\n while (deq.getFirst != min) deq.removeFirst()\n deq.removeFirst()\n deq.addLast(i)\n findMin()\n findMax()\n } else if (maxD > diff) {\n recordResult()\n while (deq.getFirst != max) deq.removeFirst()\n deq.removeFirst()\n deq.addLast(i)\n findMin()\n findMax()\n } else {\n if (books(min) >= elem) min = i\n if (books(max) <= elem) max = i\n deq.addLast(i)\n }\n }\n recordResult()\n\n def findMin(): Unit = {\n var i = 0\n min = deq.getLast\n while (i < deq.size()) {\n if (books(deq.get(i)) <= books(min)) min = deq.get(i)\n i += 1\n }\n }\n\n def findMax(): Unit = {\n var i = 0\n max = deq.getLast\n while (i < deq.size()) {\n if (books(deq.get(i)) >= books(max)) max = deq.get(i)\n i += 1\n }\n }\n\n\n println(cnt + \" \" + buf.size)\n buf.foreach(item => {\n println(item._1 + \" \" + item._2)\n })\n\n def recordResult(): Unit = {\n if (deq.size() > cnt) {\n cnt = deq.size()\n buf.clear()\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n } else if (deq.size() == cnt) {\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n }\n }\n\n}"}, {"source_code": "import java.util\nimport java.util.Comparator\nimport java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\n\nobject EBooks extends App {\n\n val scanner = new Scanner(System.in)\n\n val num = 10\n val diff = 1\n var cnt = 0\n val buf = ArrayBuffer.empty[(Int, Int)]\n val books = (0 until num).map(i => Random.nextInt(3) + 1)\n val ordMin = new util.TreeSet[Int](new Comparator[Int] {\n override def compare(o1: Int, o2: Int): Int = {\n val c = books(o1).compareTo(books(o2))\n if (c == 0) o2.compareTo(o1)\n else c\n }\n\n })\n\n val deq = new java.util.LinkedList[Int]()\n deq.add(0)\n ordMin.add(0)\n\n (1 until num) foreach {\n i =>\n val elem = books(i)\n val minD = math.abs(elem - books(ordMin.first()))\n val maxD = math.abs(elem - books(ordMin.last()))\n if (!ordMin.isEmpty) {\n println(ordMin.first() + \" \" + ordMin.last() + \" \" + books(ordMin.first()) + \" \" + books(ordMin.last()) + \" \")\n\n }\n if (minD > diff || maxD > diff) {\n recordResult()\n if (minD > diff) {\n while (deq.getLast != ordMin.first()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n } else if (maxD > diff) {\n while (!deq.isEmpty && deq.getLast != ordMin.last()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n }\n if (!deq.isEmpty) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n deq.addFirst(i)\n ordMin.add(i)\n } else {\n deq.addFirst(i)\n ordMin.add(i)\n }\n }\n recordResult()\n println(cnt + \" \" + buf.size)\n buf.foreach(item => {\n println(item._2 + \" \" + item._1)\n })\n System.exit(0)\n\n\n def recordResult(): Unit = {\n if (deq.size() > cnt) {\n cnt = deq.size()\n buf.clear()\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n } else if (deq.size() == cnt) {\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n }\n }\n\n}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\n\nobject EBooks extends App {\n\n val scanner = new Scanner(System.in)\n\n val num = scanner.nextInt()\n val diff = scanner.nextInt()\n var cnt = 0\n val buf = ArrayBuffer.empty[(Int, Int)]\n val books = (0 until num).map(i => scanner.next().toInt).toArray\n\n val deq = new java.util.LinkedList[Int]()\n\n deq.add(0)\n\n (1 until num) foreach { i =>\n val elem = books(i)\n val headDiff = math.abs(elem - books(deq.getFirst))\n val lastDiff = math.abs(elem - books(deq.getLast))\n if (headDiff > diff) {\n recordResult()\n deq.clear()\n deq.addFirst(i)\n } else if (lastDiff <= diff) {\n deq.addFirst(i)\n } else {\n recordResult()\n while (math.abs(elem - books(deq.getLast)) > diff) deq.removeLast()\n deq.addFirst(i)\n }\n }\n recordResult()\n\n println(cnt + \" \" + buf.size)\n buf.foreach(item => {\n println(item._2 + \" \" + item._1)\n })\n\n def recordResult(): Unit = {\n if (deq.size() > cnt) {\n cnt = deq.size()\n buf.clear()\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n } else if (deq.size() == cnt) {\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n }\n }\n\n}\n"}, {"source_code": "import java.util\nimport java.util.Comparator\nimport java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\n\nobject EBooks extends App {\n\n val scanner = new Scanner(System.in)\n\n val num = scanner.nextInt()\n val diff = scanner.nextInt()\n var cnt = 0\n val buf = ArrayBuffer.empty[(Int, Int)]\n val books = (0 until num).map(i => scanner.next().toInt)\n\n val ordMin = new util.TreeSet[Int](new Comparator[Int] {\n override def compare(o1: Int, o2: Int): Int = {\n val c = books(o1).compareTo(books(o2))\n if (c == 0) o2.compareTo(o1)\n else c\n }\n\n })\n\n val deq = new java.util.LinkedList[Int]()\n deq.add(0)\n ordMin.add(0)\n\n (1 until num) foreach {\n i =>\n val elem = books(i)\n val minD = math.abs(elem - books(ordMin.first()))\n val maxD = math.abs(elem - books(ordMin.last()))\n //if (!ordMin.isEmpty) println(books(ordMin.first()) + \" \" + books(ordMin.last()) + \" \")\n if (minD > diff || maxD > diff) {\n recordResult()\n if (minD > diff)\n while (deq.getLast != ordMin.first()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n if (maxD > diff)\n while (!deq.isEmpty && deq.getLast != ordMin.last()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n if (!deq.isEmpty) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n deq.addFirst(i)\n ordMin.add(i)\n } else {\n deq.addFirst(i)\n ordMin.add(i)\n }\n }\n recordResult()\n println(cnt + \" \" + buf.size)\n buf.foreach(item => {\n println(item._2 + \" \" + item._1)\n })\n System.exit(0)\n\n\n def recordResult(): Unit = {\n if (deq.size() > cnt) {\n cnt = deq.size()\n buf.clear()\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n } else if (deq.size() == cnt) {\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n }\n }\n\n}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\n\nobject EBooks extends App {\n\n val scanner = new Scanner(System.in)\n\n val num = scanner.nextInt()\n val diff = scanner.nextInt()\n var cnt = 0\n val buf = ArrayBuffer.empty[(Int, Int)]\n val books = (0 until num).map(i => scanner.next().toInt).toArray\n\n val deq = new java.util.LinkedList[Int]()\n var min = 0\n var max = 0\n deq.add(0)\n\n (1 until num) foreach { i =>\n val elem = books(i)\n val minD = math.abs(elem - books(min))\n val maxD = math.abs(elem - books(max))\n if (minD > diff) {\n recordResult()\n while (deq.getLast != min) deq.removeLast()\n deq.removeFirst()\n deq.addLast(i)\n findMin()\n findMax()\n } else if (maxD > diff) {\n recordResult()\n while (deq.getLast != max) deq.removeLast()\n deq.removeFirst()\n deq.addLast(i)\n findMin()\n findMax()\n } else {\n if (books(min) >= elem) min = i\n if (books(max) <= elem) max = i\n deq.addLast(i)\n }\n }\n recordResult()\n\n def findMin(): Unit = {\n var i = 0\n min = deq.getLast\n while (i < deq.size()) {\n if (books(deq.get(i)) <= books(min)) min = deq.get(i)\n i += 1\n }\n }\n\n def findMax(): Unit = {\n var i = 0\n max = deq.getLast\n while (i < deq.size()) {\n if (books(deq.get(i)) >= books(max)) max = deq.get(i)\n i += 1\n }\n }\n\n\n println(cnt + \" \" + buf.size)\n buf.foreach(item => {\n println(item._1 + \" \" + item._2)\n })\n\n def recordResult(): Unit = {\n if (deq.size() > cnt) {\n cnt = deq.size()\n buf.clear()\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n } else if (deq.size() == cnt) {\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n }\n }\n\n}"}, {"source_code": "import java.util\nimport java.util.Comparator\nimport java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\n\nobject EBooks extends App {\n\n val scanner = new Scanner(System.in)\n\n val num = scanner.nextInt()\n val diff = scanner.nextInt()\n var cnt = 0\n val buf = ArrayBuffer.empty[(Int, Int)]\n val books = (0 until num).map(i => scanner.next().toInt)\n\n val ordMin = new util.TreeSet[Int](new Comparator[Int] {\n override def compare(o1: Int, o2: Int): Int = books(o1).compareTo(books(o2))\n })\n\n val deq = new java.util.LinkedList[Int]()\n deq.add(0)\n ordMin.add(0)\n\n (1 until num) foreach {\n i =>\n val elem = books(i)\n val minD = math.abs(elem - books(ordMin.first()))\n val maxD = math.abs(elem - books(ordMin.last()))\n if (minD > diff || maxD > diff) {\n recordResult()\n if (minD > diff)\n while (deq.getLast != ordMin.first()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n if (maxD > diff)\n while (!deq.isEmpty && deq.getLast != ordMin.last()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n if (!deq.isEmpty) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n deq.addFirst(i)\n ordMin.add(i)\n } else {\n deq.addFirst(i)\n ordMin.add(i)\n }\n }\n recordResult()\n println(cnt + \" \" + buf.size)\n buf.foreach(item => {\n println(item._2 + \" \" + item._1)\n })\n System.exit(0)\n\n\n def recordResult(): Unit = {\n if (deq.size() > cnt) {\n cnt = deq.size()\n buf.clear()\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n } else if (deq.size() == cnt) {\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n }\n }\n\n}"}, {"source_code": "import java.util\nimport java.util.Comparator\nimport java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\n\nobject EBooks extends App {\n\n val scanner = new Scanner(System.in)\n\n val num = scanner.nextInt()\n val diff = scanner.nextInt()\n var cnt = 0\n val buf = ArrayBuffer.empty[(Int, Int)]\n val books = (0 until num).map(i => scanner.next().toInt)\n val ordMin = new util.TreeSet[Int](new Comparator[Int] {\n override def compare(o1: Int, o2: Int): Int = {\n val c = books(o1).compareTo(books(o2))\n if (c == 0) o2.compareTo(o1)\n else c\n }\n\n })\n\n val deq = new java.util.LinkedList[Int]()\n deq.add(0)\n ordMin.add(0)\n\n (1 until num) foreach {\n i =>\n val elem = books(i)\n val minD = math.abs(elem - books(ordMin.first()))\n val maxD = math.abs(elem - books(ordMin.last()))\n if (minD > diff || maxD > diff) {\n recordResult()\n if (maxD > diff) {\n while (!deq.isEmpty && deq.getLast != ordMin.last()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n }\n if (minD > diff) {\n while (deq.getLast != ordMin.first()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n }\n if (!deq.isEmpty) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n deq.addFirst(i)\n ordMin.add(i)\n } else {\n deq.addFirst(i)\n ordMin.add(i)\n }\n }\n recordResult()\n println(cnt + \" \" + buf.size)\n buf.foreach(item => {\n println(item._2 + \" \" + item._1)\n })\n System.exit(0)\n\n\n def recordResult(): Unit = {\n if (deq.size() > cnt) {\n cnt = deq.size()\n buf.clear()\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n } else if (deq.size() == cnt) {\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n }\n }\n\n}"}, {"source_code": "import java.util\nimport java.util.Comparator\nimport java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\n\nobject EBooks extends App {\n\n val scanner = new Scanner(System.in)\n\n val num = scanner.nextInt()\n val diff = scanner.nextInt()\n var cnt = 0\n val buf = ArrayBuffer.empty[(Int, Int)]\n val books = (0 until num).map(i => scanner.next().toInt)\n\n val ordMin = new util.TreeSet[Int](new Comparator[Int] {\n override def compare(o1: Int, o2: Int): Int = {\n val c = books(o1).compareTo(books(o2))\n if (c == 0) o1.compareTo(o2)\n else c\n }\n\n })\n\n val deq = new java.util.LinkedList[Int]()\n deq.add(0)\n ordMin.add(0)\n\n (1 until num) foreach {\n i =>\n val elem = books(i)\n val minD = math.abs(elem - books(ordMin.first()))\n val maxD = math.abs(elem - books(ordMin.last()))\n if (minD > diff || maxD > diff) {\n recordResult()\n if (minD > diff)\n while (deq.getLast != ordMin.first()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n if (maxD > diff)\n while (!deq.isEmpty && deq.getLast != ordMin.last()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n if (!deq.isEmpty) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n deq.addFirst(i)\n ordMin.add(i)\n } else {\n deq.addFirst(i)\n ordMin.add(i)\n }\n }\n recordResult()\n println(cnt + \" \" + buf.size)\n buf.foreach(item => {\n println(item._2 + \" \" + item._1)\n })\n System.exit(0)\n\n\n def recordResult(): Unit = {\n if (deq.size() > cnt) {\n cnt = deq.size()\n buf.clear()\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n } else if (deq.size() == cnt) {\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n }\n }\n\n}"}, {"source_code": "import java.util\nimport java.util.Comparator\nimport java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\n\nobject EBooks extends App {\n\n val scanner = new Scanner(System.in)\n\n val num = scanner.nextInt()\n val diff = scanner.nextInt()\n var cnt = 0\n val buf = ArrayBuffer.empty[(Int, Int)]\n val books = (0 until num).map(i => scanner.next().toInt)\n val ordMin = new util.TreeSet[Int](new Comparator[Int] {\n override def compare(o1: Int, o2: Int): Int = {\n val c = books(o1).compareTo(books(o2))\n if (c == 0) o2.compareTo(o1)\n else c\n }\n\n })\n\n val deq = new java.util.LinkedList[Int]()\n deq.add(0)\n ordMin.add(0)\n\n (1 until num) foreach {\n i =>\n val elem = books(i)\n val minD = math.abs(elem - books(ordMin.first()))\n val maxD = math.abs(elem - books(ordMin.last()))\n if (minD > diff || maxD > diff) {\n recordResult()\n if (minD > diff) {\n while (deq.getLast != ordMin.first()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n } else if (maxD > diff) {\n while (!deq.isEmpty && deq.getLast != ordMin.last()) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n }\n if (!deq.isEmpty) {\n ordMin.remove(deq.getLast)\n deq.removeLast()\n }\n deq.addFirst(i)\n ordMin.add(i)\n } else {\n deq.addFirst(i)\n ordMin.add(i)\n }\n }\n recordResult()\n println(cnt + \" \" + buf.size)\n buf.foreach(item => {\n println(item._2 + \" \" + item._1)\n })\n System.exit(0)\n\n\n def recordResult(): Unit = {\n if (deq.size() > cnt) {\n cnt = deq.size()\n buf.clear()\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n } else if (deq.size() == cnt) {\n buf += ((deq.getFirst + 1, deq.getLast + 1))\n }\n }\n\n}"}], "src_uid": "bc8b4b74c2f2d486e2d2f03982ef1013"} {"source_code": "import scala.io.StdIn\n\nobject Solution1 extends App {\n\n //A + B > C and B + C > A and C + A > B\n\n val n = StdIn.readLine().toInt\n\n val tc = for {\n _ <- 0 until n\n } yield {\n StdIn.readLine()\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n for {\n sides <- tc\n } {\n solve(sides)\n }\n\n def solve(sides: Array[Int]) = {\n var i, j, k = 0\n var result: Option[(Int, Int, Int)] = None\n/* val ssides = sides.zipWithIndex.sortBy(_._1)\n while (i < ssides.length - 2) {\n val a = ssides(i)._1\n val b = ssides(i + 1)._1\n val c = ssides(i + 2)._1\n\n val ai = ssides(i)._2\n val bi = ssides(i + 1)._2\n val ci = ssides(i + 2)._2\n\n if (!(a + b > c && b + c > a && c + a > b) && ai < bi && bi < ci) {\n result = Some((ai, bi, ci))\n }\n i += 1\n }*/\n val ssides = sides.zipWithIndex.sortBy(_._1)\n k = sides.length - 1\n while (i < sides.length - 2) {\n j = i + 1\n val a = sides(i)\n val b = sides(j)\n val c = sides(k)\n\n //A + B > C and B + C > A and C + A > B\n if (!(a + b > c && b + c > a && c + a > b)) {\n result = Some((i, j, k))\n i = sides.length\n j = sides.length\n k = sides.length\n }\n i += 1\n }\n /*while (i < ssides.length - 2) {\n j = i + 1\n while (j < ssides.length - 1) {\n k = ssides.length\n while (k < j) {\n val a = ssides(i)._1\n val b = ssides(j)._1\n val c = ssides(k)._1\n val ai = ssides(i)._2\n val bi = ssides(i + 1)._2\n val ci = ssides(i + 2)._2\n //A + B > C and B + C > A and C + A > B\n if (!(a + b > c && b + c > a && c + a > b) && ai < bi && bi < ci) {\n result = Some((ai, bi, ci))\n i = sides.length\n j = sides.length\n k = sides.length\n }\n k -= 1\n }\n j += 1\n }\n i += 1\n }*/\n result.map(r => println(s\"${r._1 + 1} ${r._2 + 1} ${r._3 + 1}\")).getOrElse(println(\"-1\"))\n }\n}\n", "positive_code": [{"source_code": "\n\nobject CodeforcesRoundE93a {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val n = rl_int\n val a = rll_int\n val res =\n Some((0, 1, n - 1))\n .filter { case (i, j, k) => a(i) + a(j) <= a(k) }\n .map { case (i, j, k) => (i + 1, j + 1, k + 1) }\n .map { case (i, j, k) => s\"$i $j $k\" }\n .getOrElse(-1)\n writer.println(res)\n }\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}"}, {"source_code": "\nobject A extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val n = in.nextInt()\n val intInputs = in.line().split(\" \").map(_.toInt)\n val x1 = intInputs(0)\n val x2 = intInputs(1)\n val x3 = intInputs(n - 1)\n\n if ((x1 + x2) <= x3 || (x1 + x3) <= x2 || (x2 + x3) <= x1) {\n println(s\"1 2 $n\")\n } else {\n println(\"-1\")\n }\n// val connectivity = Array.ofDim[Boolean](airports, airports)\n\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n if (an(0) + an(1) > an.last) println(\"-1\")\n else println(s\"1 2 $n\")\n }\n}\n"}], "negative_code": [{"source_code": "\n\nimport scala.io.StdIn\n\nobject Solution1 extends App {\n\n //A + B > C and B + C > A and C + A > B\n\n val n = StdIn.readLine().toInt\n\n val tc = for {\n _ <- 0 until n\n } yield {\n StdIn.readLine()\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n for {\n sides <- tc\n } {\n solve(sides)\n }\n\n def solve(sides: Array[Int]) = {\n var i, j, k = 0\n var result: Option[(Int, Int, Int)] = None\n val ssides = sides.zipWithIndex.sortBy(_._1)\n while (i < ssides.length - 2) {\n val a = ssides(i)._1\n val b = ssides(i + 1)._1\n val c = ssides(i + 2)._1\n\n val ai = ssides(i)._2\n val bi = ssides(i + 1)._2\n val ci = ssides(i + 2)._2\n\n if (!(a + b > c && b + c > a && c + a > b) && ai < bi && bi < ci) {\n result = Some((ai, bi, ci))\n }\n i += 1\n }\n /*while (i < sides.length - 2) {\n j = i + 1\n while (j < sides.length - 1) {\n k = j + 1\n while (k < sides.length) {\n val a = sides(i)\n val b = sides(j)\n val c = sides(k)\n //A + B > C and B + C > A and C + A > B\n if (!(a + b > c && b + c > a && c + a > b)) {\n result = Some((i, j, k))\n }\n k += 1\n }\n j += 1\n }\n i += 1\n }*/\n result.map(r => println(s\"${r._1 + 1} ${r._2 + 1} ${r._3 + 1}\")).getOrElse(println(\"-1\"))\n }\n}\n"}], "src_uid": "341555349b0c1387334a0541730159ac"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(left: Int, right: Int, index: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (left < that.left || (left == that.left && right < that.right))\n return -1\n else if (left == that.left && right == that.right)\n return 0\n else\n return 1\n }\n }\n\n val t = readInt()\n for (tt <- 1 to t) {\n val s = readString()\n var a = 0\n var b = 0\n var c = 0\n for (cc <- s) {\n if (cc == 'A')\n a += 1\n if (cc == 'B')\n b += 1\n if (cc == 'C')\n c += 1\n }\n if (b == a + c)\n writer.println(\"YES\")\n else\n writer.println(\"NO\")\n }\n writer.flush()\n}\n", "positive_code": [{"source_code": "object A extends App {\r\n\r\n def solitaire(s: String): Boolean = {\r\n val counts = Array.fill(3)(0)\r\n s.foreach(letter => counts(letter - 'A') += 1)\r\n counts(1) == counts(0) + counts(2)\r\n }\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val s = readLine()\r\n\r\n solitaire(s) match {\r\n case true => println(\"YES\")\r\n case false => println(\"NO\")\r\n }\r\n }\r\n}\r\n"}, {"source_code": "object A extends App {\r\n\r\n def solitaire(s: String): Boolean = {\r\n val as = s.count(_ == 'A')\r\n val bs = s.count(_ == 'B')\r\n val cs = s.count(_ == 'C')\r\n\r\n as + cs == bs\r\n }\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val s = readLine()\r\n\r\n solitaire(s) match {\r\n case true => println(\"YES\")\r\n case false => println(\"NO\")\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "ca6b162f945d4216055bf92d7263dbd5"} {"source_code": "import scala.annotation.tailrec\nimport scala.util.Try\n\nobject ScarboroughFair {\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val inputWord = scala.io.StdIn.readLine().toCharArray\n\n val lines = Stream\n .continually(scala.io.StdIn.readLine())\n .take(m).toList\n\n val output = performOperation(inputWord, lines)\n output.foreach(c => print(c))\n\n\n }\n\n def performOperation(inputWord: Array[Char], lines: List[String]): Array[Char] = {\n\n @tailrec\n def changeChar(word: Array[Char], l: Int, r: Int, oldChar: Char, newChar: Char, index: Int): Array[Char] = {\n for (i <- l to r) {\n if (word(i - 1).equals(oldChar)) word(i - 1) = newChar\n }\n if (index == lines.length - 1) return word\n else {\n val (v: Int, x: Int, c1: Char, c2: Char) = convertLinesToParameters(lines(index + 1))\n changeChar(word, v, x, c1, c2, index + 1)\n }\n\n }\n\n val (v: Int, x: Int, c1: Char, c2: Char) = convertLinesToParameters(lines(0))\n changeChar(inputWord, v, x, c1, c2, 0)\n }\n\n def convertLinesToParameters(line: String) = {\n val Array(v: Int, x: Int, c1: Char, c2: Char) = line.split(\" \").map(s => {\n if (Try(s.toInt).isSuccess) s.toInt\n else if (Try(s.length == 1).isSuccess) s(0)\n })\n (v, x, c1, c2)\n }\n\n}\n", "positive_code": [{"source_code": "/**\n * Created by AYUSH AWASTHI on 9/20/2017.\n */\nimport scala.io.BufferedSource\nobject Basic{\n def main(args : Array[String]): Unit = {\n val tmp = Console.readLine().split(\" \")\n val n = tmp(0).toInt\n val m = tmp(1).toInt\n val str = Console.readLine().toString\n var answer = str;\n var temp = str\n (1 to m).foreach {\n case i => {\n val tmp = Console.readLine().split(\" \")\n val l = tmp(0).toInt\n val r = tmp(1).toInt\n val first = tmp(2).toString;\n val second = tmp(3).toString;\n\n temp = \"\"\n (0 to l-2).foreach{ case j => {\n temp+=answer(j)\n }}\n (l - 1 to r - 1).foreach { case j => {\n if (answer.charAt(j) == first(0)) {\n temp += second(0)\n } else {\n temp += answer.charAt(j)\n }\n }\n }\n (r to str.length -1).foreach{ case j => {\n temp+=answer(j)\n }}\n answer = temp\n }\n }\n println(answer)\n }\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val s = readLine.toCharArray\n\n for (_ <- 0 until m) {\n val (first, second) = readLine.split(\" \").splitAt(2)\n val Array(l, r) = first.map(_.toInt - 1)\n val Array(c1, c2) = second.map(_.head)\n\n for (i <- l to r) {\n s(i) = if (s(i) == c1) c2 else s(i)\n }\n }\n\n println(s.mkString)\n}\n"}, {"source_code": "object A extends App {\n def customReduce(ls: List[(Int, Char)], ops: List[(Int, Int, Char, Char)]): List[(Int, Char)] =\n if (ops.isEmpty) ls\n else {\n val op = ops.head\n val nls = ls.map((t: (Int, Char)) => {\n if (t._1 >= op._1 && t._1 <= op._2 && t._2 == op._3) (t._1, op._4)\n else t\n })\n customReduce(nls, ops.tail)\n }\n val Array(n, m) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val s = scala.io.StdIn.readLine()\n val ops = (0 until m).foldLeft(List.empty[(Int, Int, Char, Char)]) { (ops, _) =>\n val Array(l, r, c1, c2) = scala.io.StdIn.readLine().split(\" \")\n (l.toInt - 1, r.toInt - 1, c1(0), c2(0)) :: ops\n }.reverse\n\n val ls = s.foldLeft(List.empty[(Int, Char)]) ((l: List[(Int, Char)], e: Char) => {\n if (l.isEmpty) (0, e) :: l\n else (l.head._1 + 1, e) :: l\n }).reverse\n\n println(customReduce(ls, ops).map((e) => e._2).mkString(\"\"))\n}\n"}], "negative_code": [{"source_code": "object ScarboroughFair {\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val inputWord = scala.io.StdIn.readLine().toCharArray\n\n val lines = Stream\n .continually(scala.io.StdIn.readLine())\n .take(m).toList\n\n val output = performOperation(inputWord, lines)\n output.foreach(c => print(c))\n\n\n }\n\n def performOperation(inputWord: Array[Char], lines: List[String]): Array[Char] = {\n\n def changeChar(word: Array[Char], l: Int, r: Int, oldChar: Char, newChar: Char, index: Int): Array[Char] = {\n for (i <- l to r) {\n if (word(i - 1).equals(oldChar)) word(i - 1) = newChar\n }\n if (index == lines.length - 1) return word\n else changeChar(word, lines(index + 1).charAt(0).asDigit, lines(index + 1).charAt(2).asDigit, lines(index + 1).charAt(4), lines(index + 1).charAt(6), index + 1)\n\n }\n\n changeChar(inputWord, lines(0).charAt(0).asDigit, lines(0).charAt(2).asDigit, lines(0).charAt(4), lines(0).charAt(6), 0)\n }\n\n}\n"}], "src_uid": "3f97dc063286a7af4838b7cd1c01df69"} {"source_code": "object CF260B extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n var s: Seq[Char] = nextString\n val n = s.length\n var r: Map[String, Int] = Map()\n\n for (i <- 0 until n - 9) {\n if (s(i).isDigit && s(i + 1).isDigit) {\n val d = (\"\" + s(i) + s(i + 1)).toInt\n if (s(i + 2) == '-') {\n if (s(i + 3).isDigit && s(i + 4).isDigit) {\n val m = (\"\" + s(i + 3) + s(i + 4)).toInt\n if (s(i + 5) == '-') {\n if (s(i + 6).isDigit && s(i + 7).isDigit && s(i + 8).isDigit && s(i + 9).isDigit) {\n val y = (\"\" + s(i + 6) + s(i + 7) + s(i + 8) + s(i + 9)).toInt\n var valid = false\n if (y >= 2013 && y <= 2015) {\n if (m >= 1 && m <= 12) {\n if (d >= 1 && d <= 31) {\n valid = m match {\n case 2 => (d <= 28)\n case 4 | 6 | 9 | 11 => (d <= 30)\n case _ => true\n }\n }\n }\n }\n if (valid) {\n val date = (for (j <- i until i + 10) yield s(j)).mkString\n var counter = 1\n if (r.contains(date)) {\n counter = r(date) + 1\n }\n r += (date -> counter)\n }\n }\n }\n }\n }\n }\n }\n\n var c = 0\n var doomsday = \"\" \n r.keys foreach { k =>\n if (r(k) > c) {\n c = r(k)\n doomsday = k\n }\n }\n\n out.println(doomsday)\n }\n\n try { \n solve \n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}", "positive_code": [{"source_code": "import scala.collection.mutable.Map\n\nobject CF158B {\n\n val days = Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)\n val cnt = Map[String, Int]().withDefaultValue(0)\n\n def correct(s: String): Boolean = {\n val sp = s.split(\"-\").map(_.toInt)\n sp(0)>0 && sp(0) <= 31 && sp(1) > 0 && sp(1) <= 12 && sp(2) >= 2013 && sp(2) <= 2015 && days(sp(1) - 1) >= sp(0)\n }\n\n def main(args: Array[String]) {\n val s = readLine()\n \"\"\"\\d\\d-\\d\\d-(?=\\d\\d\\d\\d)\"\"\".r.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)\n println(cnt.filterKeys(correct).maxBy(_._2)._1)\n }\n}\n"}, {"source_code": "import scala.collection.mutable.Map\n\nobject CF158B {\n\n val days = Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)\n\n def correct(s: String): Boolean = {\n val sp = s.split(\"-\").map(_.toInt)\n days(sp(1) - 1) >= sp(0)\n }\n\n def main(args: Array[String]) {\n val cnt: Map[String, Int] = Map[String, Int]().withDefaultValue(0)\n val s = readLine()\n val r0 = \"\"\"0(?=[1-9]-(0[1-9]|1[012])-201[345])\"\"\".r\n val r12 = \"\"\"[12](?=[0-9]-(0[1-9]|1[012])-201[345])\"\"\".r\n val r3 = \"\"\"3(?=[01]-(0[1-9]|1[012])-201[345])\"\"\".r\n r0.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)\n r12.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)\n r3.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)\n println(cnt.filterKeys(correct).maxBy(_._2)._1)\n }\n}\n"}, {"source_code": "import scala.collection.mutable.Map\n\nobject CF158B {\n\n val days = Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)\n\n def correct(s: String): Boolean = {\n val sp = s.split(\"-\").map(_.toInt)\n days(sp(1) - 1) >= sp(0)\n }\n\n def main(args: Array[String]) {\n val cnt: Map[String, Int] = Map[String, Int]().withDefaultValue(0)\n val s = readLine()\n val r0 = \"\"\"0(?=[1-9][- /.](0[1-9]|1[012])[- /.]201[345])\"\"\".r\n val r12 = \"\"\"[12](?=[0-9][- /.](0[1-9]|1[012])[- /.]201[345])\"\"\".r\n val r3 = \"\"\"3(?=[01][- /.](0[1-9]|1[012])[- /.]201[345])\"\"\".r\n r0.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)\n r12.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)\n r3.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)\n println(cnt.filterKeys(correct).maxBy(_._2)._1)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S = ns()\n val len = 10\n\n val cnt = Array.ofDim[Int](3, 12, 31)\n\n def dayLim(m: Int) = m match {\n case 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31\n case 2 => 28\n case 4 | 6 | 9 | 11 => 30\n }\n\n REP(S.length - len + 1) { i =>\n val d = S.substring(i, i + 2)\n val m = S.substring(i + 3, i + 5)\n val y = S.substring(i + 6, i + 10)\n if (S(i + 2) == '-' && S(i + 5) == '-')\n try {\n val dd = d.toInt\n val mm = m.toInt\n val yy = y.toInt\n if (yy >= 2013 && yy <= 2015 && mm >= 1 && mm <= 12 && dd >= 1 && dd <= dayLim(mm)) {\n cnt(yy - 2013)(mm - 1)(dd - 1) += 1\n }\n } catch {\n case _: NumberFormatException =>\n }\n }\n\n val ((y, m, d), _) = (for {\n y <- 0 until 3\n m <- 0 until 12\n d <- 0 until 31\n } yield (y, m, d) -> cnt(y)(m)(d)).maxBy(_._2)\n\n val ans = f\"${d+1}%02d-${m+1}%02d-${y+2013}\"\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S = ns()\n val len = 10\n\n val cnt = Array.ofDim[Int](3, 12, 31)\n\n def dayLim(m: Int) = m match {\n case 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31\n case 2 => 28\n case 4 | 6 | 9 | 11 => 30\n }\n\n REP(S.length - len + 1) { i =>\n val d = S.substring(i, i + 2)\n val m = S.substring(i + 3, i + 5)\n val y = S.substring(i + 6, i + 10)\n try {\n val dd = d.toInt\n val mm = m.toInt\n val yy = y.toInt\n if (yy >= 2013 && yy <= 2015 && mm >= 1 && mm <= 12 && dd >= 1 && dd <= dayLim(mm)) {\n cnt(yy - 2013)(mm - 1)(dd - 1) += 1\n }\n } catch {\n case _: NumberFormatException =>\n }\n }\n\n val ((y, m, d), _) = (for {\n y <- 0 until 3\n m <- 0 until 12\n d <- 0 until 31\n } yield (y, m, d) -> cnt(y)(m)(d)).maxBy(_._2)\n\n val ans = f\"${d+1}%02d-${m+1}%02d-${y+2013}\"\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import scala.collection.mutable.Map\n\nobject CF158B {\n def main(args: Array[String]) {\n val cnt: Map[String, Int] = Map[String, Int]().withDefaultValue(0)\n val s = readLine()\n val r0 = \"\"\"0(?=[1-9][- /.](0[1-9]|1[012])[- /.]201[345])\"\"\".r\n val r12 = \"\"\"[12](?=[0-9][- /.](0[1-9]|1[012])[- /.]201[345])\"\"\".r\n val r3 = \"\"\"3(?=[01][- /.](0[1-9]|1[012])[- /.]201[345])\"\"\".r\n r0.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)\n r12.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)\n r3.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)\n println(cnt.maxBy(_._2)._1)\n }\n}\n"}, {"source_code": "object CF260B extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n var s: String = nextString\n val n = s.length\n\n val m = doomsdays(s).groupBy(x => x).mapValues(x => x.length)\n var c = 0\n var doomsday = \"\" \n m.keys foreach { k =>\n if (m(k) > c) {\n c = m(k)\n doomsday = k\n }\n }\n\n out.println(doomsday)\n }\n\n val DoomsDay = \"\"\"^(\\d\\d)-(\\d\\d)-(\\d\\d\\d\\d).*\"\"\".r\n\n def doomsdays(s: String): List[String] = s match {\n case s: String if (s.length == 0) => Nil\n case DoomsDay(d, m, y) =>\n val dd = d.toInt\n val mm = m.toInt\n val yy = y.toInt\n var valid = false\n if (yy >= 2013 && yy <= 2014) {\n if (mm >= 1 && mm <= 12) {\n if (dd >= 0 && dd <= 31) {\n if (mm % 2 == 0) {\n if (mm == 1 && dd <= 28) {\n valid = true\n } else if (mm != 1 && dd <= 30) {\n valid = true\n }\n } else {\n valid = true\n }\n }\n }\n }\n if (valid) d + \"-\" + m + \"-\" + y :: doomsdays(s.tail) else doomsdays(s.tail)\n case _ => doomsdays(s.tail)\n }\n\n try { \n solve \n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}"}, {"source_code": "object CF260B extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n var s: Seq[Char] = nextString\n val n = s.length\n var r: Map[String, Int] = Map()\n\n for (i <- 0 until n - 10) {\n if (s(i).isDigit && s(i + 1).isDigit) {\n val d = (\"\" + s(i) + s(i + 1)).toInt\n if (s(i + 2) == '-') {\n if (s(i + 3).isDigit && s(i + 4).isDigit) {\n val m = (\"\" + s(i + 3) + s(i + 4)).toInt\n if (s(i + 5) == '-') {\n if (s(i + 6).isDigit && s(i + 7).isDigit && s(i + 8).isDigit && s(i + 9).isDigit) {\n val y = (\"\" + s(i + 6) + s(i + 7) + s(i + 8) + s(i + 9)).toInt\n var valid = false\n if (y >= 2013 && y <= 2015) {\n if (m >= 1 && m <= 12) {\n if (d >= 1 && d <= 31) {\n valid = m match {\n case 2 => (d <= 28)\n case 4 | 6 | 9 | 11 => (d <= 30)\n case _ => true\n }\n }\n }\n }\n if (valid) {\n val date = (for (j <- i until i + 10) yield s(j)).mkString\n var counter = 1\n if (r.contains(date)) {\n counter = r(date) + 1\n }\n r += (date -> counter)\n }\n }\n }\n }\n }\n }\n }\n\n var c = 0\n var doomsday = \"\" \n r.keys foreach { k =>\n if (r(k) > c) {\n c = r(k)\n doomsday = k\n }\n }\n\n out.println(doomsday)\n }\n\n try { \n solve \n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}"}, {"source_code": "object CF260B extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n var s: String = nextString\n val n = s.length\n\n val DoomsDay = \"\"\"(\\d\\d)-(\\d\\d)-(\\d\\d\\d\\d)\"\"\".r\n var l: List[String] = Nil\n\n for(mm <- DoomsDay.findAllIn(s).matchData) {\n val d = mm.group(1).toInt\n val m = mm.group(2).toInt\n val y = mm.group(3).toInt\n var valid = false\n if (y >= 2013 && y <= 2014) {\n if (m >= 1 && m <= 12) {\n if (d >= 0 && d <= 31) {\n if (m % 2 == 0) {\n if (m == 1 && d <= 28) {\n valid = true\n } else if (m != 1 && d <= 30) {\n valid = true\n }\n } else {\n valid = true\n }\n }\n }\n }\n\n if (valid) {\n l = mm.group(0) :: l\n } \n }\n\n val m = l.groupBy(x => x).mapValues(x => x.length)\n var c = 0\n var doomsday = \"\" \n m.keys foreach { k =>\n if (m(k) > c) {\n c = m(k)\n doomsday = k\n }\n }\n\n out.println(doomsday)\n }\n\n try { \n solve \n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}"}, {"source_code": "object CF260B extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n var s: Seq[Char] = nextString\n val n = s.length\n var r: Map[String, Int] = Map()\n\n for (i <- 0 until n - 10) {\n if (s(i).isDigit && s(i + 1).isDigit) {\n val d = (\"\" + s(i) + s(i + 1)).toInt\n if (s(i + 2) == '-') {\n if (s(i + 3).isDigit && s(i + 4).isDigit) {\n val m = (\"\" + s(i + 3) + s(i + 4)).toInt\n if (s(i + 5) == '-') {\n if (s(i + 6).isDigit && s(i + 7).isDigit && s(i + 8).isDigit && s(i + 9).isDigit) {\n val y = (\"\" + s(i + 6) + s(i + 7) + s(i + 8) + s(i + 9)).toInt\n var valid = false\n if (y >= 2013 && y <= 2014) {\n if (m >= 1 && m <= 12) {\n if (d >= 0 && d <= 31) {\n if (m % 2 == 0) {\n if (m == 1 && d <= 28) {\n valid = true\n } else if (m != 1 && d <= 30) {\n valid = true\n }\n } else {\n valid = true\n }\n }\n }\n }\n if (valid) {\n val date = (for (j <- i until i + 10) yield s(j)).mkString\n var counter = 1\n if (r.contains(date)) {\n counter = r(date) + 1\n }\n r += (date -> counter)\n }\n }\n }\n }\n }\n }\n }\n\n var c = 0\n var doomsday = \"\" \n r.keys foreach { k =>\n if (r(k) > c) {\n c = r(k)\n doomsday = k\n }\n }\n\n out.println(doomsday)\n }\n\n try { \n solve \n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}"}, {"source_code": "object CF260B extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n var s: Seq[Char] = nextString\n val n = s.length\n var r: Map[String, Int] = Map()\n\n for (i <- 0 until n - 10) {\n if (s(i).isDigit && s(i + 1).isDigit) {\n val d = (\"\" + s(i) + s(i + 1)).toInt\n if (s(i + 2) == '-') {\n if (s(i + 3).isDigit && s(i + 4).isDigit) {\n val m = (\"\" + s(i + 3) + s(i + 4)).toInt\n if (s(i + 5) == '-') {\n if (s(i + 6).isDigit && s(i + 7).isDigit && s(i + 8).isDigit && s(i + 9).isDigit) {\n val y = (\"\" + s(i + 6) + s(i + 7) + s(i + 8) + s(i + 9)).toInt\n var valid = false\n if (y >= 2013 && y <= 2015) {\n if (m >= 1 && m <= 12) {\n if (d >= 0 && d <= 31) {\n if (m % 2 == 0) {\n if (m == 1 && d <= 28) {\n valid = true\n } else if (m != 1 && d <= 30) {\n valid = true\n }\n } else {\n valid = true\n }\n }\n }\n }\n if (valid) {\n val date = (for (j <- i until i + 10) yield s(j)).mkString\n var counter = 1\n if (r.contains(date)) {\n counter = r(date) + 1\n }\n r += (date -> counter)\n }\n }\n }\n }\n }\n }\n }\n\n var c = 0\n var doomsday = \"\" \n r.keys foreach { k =>\n if (r(k) > c) {\n c = r(k)\n doomsday = k\n }\n }\n\n out.println(doomsday)\n }\n\n try { \n solve \n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}"}], "src_uid": "dd7fd84f7915ad57b0e21f416e2a3ea0"} {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readLine.toInt\n val a=readLine.split(\" \").map(_.toInt)\n\n val b=for(i<-0 until n) yield\n \tfor(j<-i+1 to n) yield\n \t\ta.slice(i,j).reduce(_^_)\n\n println(b.reduce(_++_).max)\n}\n\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n in.next()\n val data = in.next().split(' ').map(_.toInt)\n println(data.indices.foldLeft(data.last) {\n case (max, i) => Math.max(max, (i + 1 until data.length).foldLeft((data(i), data(i))) {\n case((nMax, soFar), j) =>\n val nSoFar = soFar ^ data(j)\n (Math.max(nSoFar, nMax), nSoFar)\n }._1)\n })\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P252A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val A = Array.fill(N)(sc.nextInt)\n\n val res = {\n for {\n i <- 0 to N\n j <- (i + 1) to N\n }\n yield {\n A.slice(i, j).foldLeft(0)(_ ^ _)\n }\n }.max\n out.println(res)\n out.close\n}\n\n\n\n\n\n"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readLine.toInt\n val a=readLine.split(\" \").map(_.toInt)\n \n var max=0\n for(i<-0 until n)\n \tfor(j<-i+1 to n)\n \t\tmax=math.max(max,a.slice(i,j).reduce(_^_))\n println(max)\n}\n\n"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readLine.toInt\n val a=readLine.split(\" \").map(_.toInt)\n \n var max=0\n for(i<-0 until n)\n {\n \tvar value=a(i)\n \tmax=math.max(max,a(i))\n \tfor(j<-i+1 until n)\n \t{\n \t\tvalue^=a(j)\n \t\tmax=math.max(max,value)\n \t}\n }\n println(max)\n}\n\n"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readLine.toInt\n val a=readLine.split(\" \").map(_.toInt)\n\n println((for(i<-0 until n) yield\n \tfor(j<-i+1 to n) yield\n \t\ta.slice(i,j).reduce(_^_)).reduce(_++_).max)\n}\n\n"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readLine.toInt\n val a=readLine.split(\" \").map(_.toInt)\n\n println((for(i<-0 until n) yield for(j<-i+1 to n) yield a.slice(i,j).reduce(_^_)).reduce(_++_).max)\n}\n\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val all = for(i <- 0 until n; j <- i + 1 to n) yield(a.drop(i).take(j - i)).foldLeft(0)(_ ^ _)\n println(all.max)\n }\n}"}, {"source_code": "object A{\n def main(args: Array[String]){\n\n val n =readLine.toInt\n val a =readLine.split(\" \").map(_.toInt)\n\n println(\n (0 until n).flatMap{\n i=>\n (i until n).map(jj=>(i,jj))\n }.map{\n case(i,jj)=>\n a.slice(i,jj+1).reduce((x,y)=>x^y)\n }.max\n )\n }\n}\n"}], "negative_code": [{"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n val n=readLine.toInt\n val a=readLine.split(\" \").map(_.toInt)\n \n var max=0\n for(i<-0 until n)\n {\n \tvar value=a(i)\n \tmax=math.max(max,a(i))\n \tfor(j<-i+1 until n)\n \t{\n \t\tvalue|=a(j)\n \t\tmax=math.max(max,value)\n \t}\n }\n println(max)\n}\n\n"}, {"source_code": "object A{\n def main(args: Array[String]){\n\n val n =readLine.toInt\n val a =readLine.split(\" \").map(_.toInt)\n\n println(\n (0 until n).combinations(2).map{l=>\n val(i,jj)=(l(0),l(1))\n a.slice(i,jj+1).reduce((x,y)=>x^y)\n }.max\n )\n }\n}\n"}], "src_uid": "a33991c9d7fdb4a4e00c0d0e6902bee1"} {"source_code": "object P1B {\n import io.StdIn._\n\n val alNum = \"([A-Z]+)([0-9]+)\".r\n val rc = \"R([0-9]+)C([0-9]+)\".r\n\n def main(args : Array[String]) {\n for (_ <- 1 to readInt) readLine match {\n case alNum(al, num) => {\n print(\"R\")\n print(num)\n print(\"C\")\n println(al.map{_ - 'A' + 1}.reduce{_ * 26 + _})\n }\n case rc(r, c) => {\n def f(n:Int, s:StringBuilder):StringBuilder = {\n if (n == 0) return s\n val nN = (n - 1) / 26\n f(nN, s += ('A' - 1 + n - nN * 26).toChar)\n }\n print(f(c.toInt, new StringBuilder).reverse)\n println(r)\n }\n }\n }\n}\n", "positive_code": [{"source_code": "/**\n * Created by gzq on 15-4-4.\n */\nobject CF1B {\n def letters2Numbers(str: String): Int = {\n str.map(letter => letter - 'A' + 1).reduceLeft((sum, ele) => sum * 26 + ele)\n }\n\n def numbers2Letters(strNum: String): String = {\n val aLessOne = 'A' - 1\n var num = strNum.toInt\n var result = \"\"\n while (num != 0) {\n val remainder = num % 26\n if (remainder != 0) {\n result = (remainder + aLessOne).toChar + result\n num /= 26\n } else {\n result = 'Z' + result\n num = num / 26 - 1\n }\n }\n return result\n }\n\n def main(args: Array[String]) {\n val in = scala.io.StdIn\n val count = in.readInt()\n\n // Define patters\n // pattern1 matches strings like BC23\n // pattern2 matches strings like R23C55\n val pattern1 = \"\"\"([a-zA-Z]+)(\\d+)\"\"\".r\n val pattern2 = \"\"\"R(\\d+)C(\\d+)\"\"\".r\n\n for (i <- 1 to count) {\n val line = in.readLine()\n\n line match {\n case pattern1(column, row) => println(\"R\" + row + \"C\" + letters2Numbers(column))\n case pattern2(row, column) => println(numbers2Letters(column) + row)\n }\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n for (i <- 0 until n) {\n val str = scanner.next().toUpperCase\n println({\n if (isNormal(str))\n toReverse(str)\n else\n toNormal(str)\n }.toUpperCase)\n }\n\n }\n\n\n def toReverse(str: String): String = {\n val index = str.indexOf(\"C\")\n toSymbol(str.substring(index + 1)) + str.substring(1, index)\n }\n\n def toNormal(str: String): String = {\n var columnNumber = \"\"\n var rowNumber = \"\"\n for (s <- str)\n if (s.isDigit)\n rowNumber = rowNumber + s\n else\n columnNumber = columnNumber + s\n\n \"R\" + rowNumber + \"C\" + toDec(columnNumber)\n }\n\n def toSymbol(str: String) = {\n var value = Integer.parseInt(str)\n var result = \"\"\n while (value > 0) {\n var remainder = value % 26\n var whole = value / 26\n\n if (remainder == 0) {\n whole = whole - 1\n remainder = 26\n }\n\n result = getSymbol(remainder) + result\n value = whole\n }\n\n result\n }\n\n def toDec(str: String): String = {\n var result = 0\n for ((s, i) <- str.reverse.zipWithIndex)\n result = result + getNumber(s) * Math.pow(26, i).toInt\n\n result.toString\n }\n\n def getSymbol(number: Int): String = ('A' - 1 + number).toChar.toString\n\n def getNumber(s: Char) = 26 - ('Z' - s)\n\n def isNormal(str: String): Boolean = str.matches(\"^R[\\\\d]+C[\\\\d]+$\")\n}\n"}, {"source_code": "import scala.collection.mutable._\nimport scala.math._\nobject B extends App {\n def isRXCY(s: String): Boolean = {\n if(s.length < 4) return false\n s.count(_ == 'R') == 1 && s.count(_ == 'C') == 1 && s(1).isDigit\n }\n def toExcel(s: String): String = {\n val r = s.slice(s.indexOf('R')+1, s.indexOf('C')).toInt\n val c = s.drop(s.indexOf('C')+1).toInt\n def toAlph(v: Int): String = {\n if(v == 0) return \"\"\n val d = if(v % 26 - 1 == -1) 25 else v % 26 - 1\n ('A' + d).toChar + toAlph((v - d)/26)\n }\n toAlph(c).reverse + r\n }\n def toRXCY(s: String): String = {\n def toI(s: String, i: Int): Int = {\n if(s.length == 0) return 0\n ((s.last - 'A' + 1) * i) + toI(s.dropRight(1), i * 26)\n }\n val R = \"\"\"([A-Z]*)([0-9]*)\"\"\".r\n s match {\n case R(c,r) => \n \"R\" + r + \"C\" + toI(c,1)\n case _ => null\n }\n }\n val n = readLine.toInt\n for(i <- 0 until n) {\n val s = readLine\n println(\n if(isRXCY(s)) toExcel(s)\n else toRXCY(s)\n )\n }\n}\n"}, {"source_code": "object spreadsheets extends App {\n val chars = ('A' to 'Z').toArray\n val RC = \"R([0-9]+)C([0-9]+)\".r\n val CR = \"([A-Z]+)([0-9]+)\".r\n \n def toCR(r: Int, c: Int) = {\n def c2s(c: Int): String =\n if(c > 0) c2s((c - 1) / 26) + chars((c - 1) % 26)\n else \"\"\n c2s(c) + r\n }\n def toRC(c: String, r: Int) = {\n val ci = c.foldLeft(0) { (l, c) => (l * 26) + (c - 'A' + 1) }\n s\"R${r}C${ci}\"\n }\n \n for(i <- 1 to readInt) readLine match {\n case RC(r, c) => println(toCR(r.toInt, c.toInt))\n case CR(c, r) => println(toRC(c, r.toInt))\n //case l => println(s\"ERROR: $l\")\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject B {\n def RC2Normal(r: String, c_str: String): String = {\n val c = c_str.toInt\n val (left, len) = Iterator.iterate((c, 1, 1)){p =>\n val (c_left, count, step) = p\n (c_left - step * 26, count + 1, step * 26)\n }.find(p => p._1 <= 0) match {\n case Some(x) => (x._1 + x._3, x._2 - 1)\n\tcase None => (-1, -2)\n }\n val c_converted = ((left - 1, \"\") /:(1 to len)){(p, i) =>\n (p._1 / 26, ('A'.toInt + (p._1 % 26)).toChar + p._2)}._2\n \"%s%s\".format(c_converted, r)\n }\n\n def Normal2RC(c_str: String, r:String): String = {\n val base = (1 to c_str.length).foldLeft(0)((a, b)=>a * 26 + 1)\n val diff = (0 /: c_str) ((s, c)=>s * 26 + c.toInt - 'A'.toInt)\n val c = base + diff\n \"R%sC%d\".format(r, c)\n }\n\n def conv(line: String): String = {\n val p_rc = \"\"\"^R(\\d+)C(\\d+)$\"\"\".r\n val p_norm = \"\"\"^([A-Z]+)(\\d+)$\"\"\".r\n return p_rc findFirstIn line match {\n case Some(p_rc(r, c)) => RC2Normal(r, c)\n case None => p_norm findFirstIn line match {\n case Some(p_norm(c, r)) => Normal2RC(c, r)\n\tcase None => \"Error\"\n }\n }\n }\n\n def main(args: Array[String]) = {\n val sc = new Scanner(System.in)\n val count = sc.nextInt\n sc.nextLine // skip newline\n for (i <- 1 to count) {\n val line = sc.nextLine\n println(conv(line))\n }\n }\n}\n"}, {"source_code": "object Solution extends App {\n val f = \"^R(\\\\d+)C(\\\\d+)$\".r\n val s = \"^([A-Z]+)(\\\\d+)$\".r\n\n def strToVal(n: String): Int = n.foldLeft(0){\n case (acc, el) => acc * 26 + (el - 'A' + 1)\n }\n\n def valToStr(n: Int): String = {\n n match {\n case 0 => \"\"\n case t =>\n var ans = List.empty[Char]\n var x = t - 1\n while (x >= 26) {\n ans = ('A' + x % 26).toChar :: ans\n x = x / 26 - 1\n }\n ans = ('A' + x % 27).toChar :: ans\n ans.mkString\n }\n }\n\n def strToInt(n: String): String = n match {\n case f(row, column) =>\n// println(\"Row \" + row + \" column \" + column)\n// (row.toInt, column.toInt)\n s\"${valToStr(column.toInt)}$row\"\n case s(column, row) =>\n// (strToVal(row), column.toInt)\n s\"R${row}C${strToVal(column)}\"\n }\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n// println(strToInt(\"RZ228\"))\n// println(strToInt(\"RI228\"))\n// println(strToInt(\"R228C494\"))\n// println(valToStr(1))\n// println(valToStr(26))\n// println(valToStr(27))\n// println(valToStr(28))\n// Range(1, 1000).foreach(i => println(valToStr(i)))\n println(Range(0, n).map(_ => strToInt(in.next())).mkString(\"\\n\"))\n// println(min + \" \" + max)\n}"}, {"source_code": "object cf1B {\n\timport java.util.Scanner\n\tval sc = new Scanner(System.in)\n\tdef main(args : Array[String]) : Unit = {\n\t\tval n = sc.nextInt\n//\t\tprintln(rechange(\"BA23\"))\n//\t\tprintln(change(\"R23C55\"))\n\t\tfor(i <- 1 to n){\n\t\t\tval st = sc.next\n\t\t\tif(st(0)=='R' && st(1).isDigit && st.contains('C'))\n\t\t\t\tprintln(change(st))\n\t\t\telse\n\t\t\t\tprintln(rechange(st))\n\t\t}\n\t}\n\tdef change(st:String):String = {\n\t\tval (s1,s2) = (st drop 1 ) span (_.isDigit)\n\t\tvar num = 0\n\t\ts2 drop 1 foreach(c => (num*=10,num+=c.toInt-'0'))\n\t\tvar s=\"\"\n\t\twhile(num>0){\n\t\t\tval mod = num%26 \n\t\t\tnum/=26\n\t\t\ts+=('A'-1 + ( if(mod==0) {num-=1;26} else mod)).toChar\n\t\t}\n\t\ts.reverse+s1\n\t}\n\tdef rechange(st:String):String = {\n\t\tval (s1,s2) = st.span(c => c.isLetter)\n\t\tvar sum = 0\n\t\ts1 foreach (c =>(sum*=26,sum=sum+(c.toInt-'A'.toInt+1)))\n\t\t\"R\"+s2+\"C\"+sum\n\t}\n\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer\n\nobject B1ExcelTables extends App {\n\n val scanner = new java.util.Scanner(System.in)\n\n var items = ListBuffer.empty[String]\n\n val size = scanner.nextInt()\n\n (1 until (size + 1)).foreach(item => items += scanner.next())\n\n val pattern = \"\"\"R[0-9]+C[0-9]+\"\"\".stripMargin\n\n solve()\n\n def solve() {\n items.foreach {\n item =>\n if (item.matches(pattern)) solveReverse(item) else solveStraight(item)\n }\n }\n\n def solveReverse(item: String): Unit = {\n val splits = item.split(\"R|C\")\n val rowNum = splits(1)\n var colNum = splits(2).toLong\n val res = new StringBuilder()\n var exp = 1\n\n def solveRev(prevPow: Long, pow: Long):Unit = {\n val cnt = colNum % pow\n if (pow <= colNum) {\n if (cnt == 0) {\n res += 'Z'\n colNum -= pow\n } else {\n res += (cnt / prevPow + 64).toChar\n colNum -= cnt\n }\n exp += 1\n solveRev(pow, pow * 26)\n } else if (pow > colNum && cnt != 0) {\n res += (colNum / prevPow + 64).toChar\n }\n }\n\n solveRev(1, 26)\n println(res.reverse + rowNum)\n }\n\n def solveStraight(item: String) = {\n val (row, col) = item.splitBy(_.isDigit)\n val colNum = col.reverse.zipWithIndex.foldLeft(0)((acc, ch) => {\n acc + (ch._1.toInt - 64) * scala.math.pow(26, ch._2).toInt\n })\n println(\"R\" + row + \"C\" + colNum)\n }\n\n implicit class StringOps(input: String) {\n\n def splitBy(predicate: (Char) => Boolean): (String, String) = {\n val first = new StringBuilder()\n val second = new StringBuilder()\n input.foreach {\n ch =>\n if (predicate(ch)) first += ch else second += ch\n }\n (first.toString(), second.toString())\n }\n\n }\n\n}\n"}, {"source_code": "object B1 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def baseAlphatoInt(a: String): Long = {\n var res = 0L\n for(i <- 0 until a.length) {\n res *= 26\n res += a(i)-'A'+1\n }\n res\n }\n def baseIntToAlpha(a: Int): String = {\n var num = a\n var res = \"\"\n while(num > 0) {\n if(num%26 == 0) {\n res = 'Z' + res\n num -= 1\n } else {\n res = ((num % 26) + 'A' - 1).toChar + res\n }\n num /= 26\n }\n res\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val reg1 = \"\"\"R(\\d+)C(\\d+)\"\"\".r\n val reg2 = \"\"\"([A-Z]+)(\\d+)\"\"\".r\n\n for(_ <- 0 until n) {\n val input = read\n val ret = reg1.findFirstMatchIn(input) match {\n case Some(m) =>\n s\"${baseIntToAlpha(m.group(2).toInt)}${m.group(1)}\"\n case None =>\n reg2.findFirstMatchIn(input) match {\n case Some(m) =>\n s\"R${m.group(2)}C${baseAlphatoInt(m.group(1))}\"\n case None =>\n \"parsing failed\"\n }\n }\n println(ret)\n }\n }\n}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ListBuffer\nobject ETables extends App {\n\n val scanner = new Scanner(System.in)\n val lb = new ListBuffer[String]\n\n val asciiOffset = 64 // A-1\n val base = 26\n\n while (scanner.hasNextLine) lb.append(scanner.nextLine().toUpperCase)\n val input = lb.toList.tail\n\n def basePower(i: Int): Int = {\n def helper(p: Int, acc: Int): Int = {\n if (p == 0) 1 * acc\n else helper(p-1, acc*base)\n }\n helper(i, 1)\n }\n\n def transform2Number(col: String): Int = {\n def helper(c: String, iter: Int, acc: Int): Int =\n if (c.isEmpty) acc\n else helper(c.substring(1), iter+1, acc + (c.charAt(0) - asciiOffset) * basePower(iter))\n helper(col.reverse, 0, 0)\n }\n\n def transform2String(col: Int): String = {\n def mod2Char(m: Int): Char = if (m == 0) (asciiOffset+base).toChar else (asciiOffset + m).toChar\n def helper(c: Int, acc: String): String = {\n if (c == 0) acc\n else if (c % base == 0) helper(c / base - 1, acc + mod2Char(0))\n else helper(c / base, acc + mod2Char(c%base))\n }\n helper(col,\"\").reverse\n }\n\n def transform(s: String): String = {\n if (s matches \"\"\"^R\\d+C\\d+$\"\"\") transform2String(s.substring(s.indexOf('C')+1).toInt) + s.substring(1, s.indexOf('C'))\n else \"R\" + \"\"\"\\d+\"\"\".r.findFirstMatchIn(s).get + \"C\" + transform2Number(\"\"\"^\\D+\"\"\".r.findFirstMatchIn(s).get.toString())\n }\n\n input.foreach(s => println(transform(s)))\n}\n"}, {"source_code": "\n/**\n * Created by yangchaozhong on 3/8/15.\n */\nobject CF1B extends App {\n import java.io.{PrintWriter}\n import java.util.{Scanner}\n\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def isAType(s: String) = {\n s.matches(\"R\\\\d+C\\\\d+\")\n }\n\n def transform(s: String) = {\n if (s.matches(\"[A-Z]+\")) {\n var res = 0\n val rs = s.reverse\n (0 to (rs.length - 1)).foreach { i =>\n res += (rs.charAt(i) - 'A' + 1) * Math.pow(26, i).toInt\n }\n res\n } else {\n var res = \"\"\n\n var n = s.toInt\n while (n > 0) {\n var m = n % 26\n if (m == 0) m = 26\n res += (m + 64).toChar\n n = (n - m) / 26\n }\n\n res.reverse\n }\n }\n\n def solve = {\n val n = nextInt\n (1 to n).foreach { x =>\n var s = nextString\n if (isAType(s)) {\n s = s.replace(\"R\", \"\")\n s = s.replace(\"C\", \" \")\n val arr = s.split(\" \")\n val row = arr(0)\n val column = arr(1)\n\n out.println(s\"${transform(column)}$row\")\n } else {\n val row = s.filter(c => c >= '0' && c <= '9').mkString(\"\")\n val column = s.filter(c => c >= 'A' && c <= 'Z').mkString(\"\")\n out.println(s\"R${row}C${transform(column)}\")\n }\n }\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n"}, {"source_code": "object B1 extends App{\n\tval r1 = \"R([0-9]+)C([0-9]+)\".r\n\tval r2 = \"([A-Z]+)([0-9]+)\".r\n\tval chars = ('A' to 'Z').toArray\n\n\tdef toCR(r: Int, c: Int) = {\n\t\tdef brk(sc: Int): String = {\n\t\t\tif(sc>0) brk((sc-1)/26) + chars((sc-1) % 26)\n\t\t\telse \"\"\n\t\t}\n\t\tbrk(c) + r\n\t}\n\n\tdef toRC(c: String, r: Int) = {\n\t\tval left_foldc = c.foldLeft(0){ (l, c) => (l*26) + (c-'A'+1) }\n\t\ts\"R${r}C${left_foldc}\"\n\t}\n\n\tfor(i <- 1 to scala.io.StdIn.readInt()) scala.io.StdIn.readLine() match {\n\t\tcase r1(r, c) => println(toCR(r.toInt, c.toInt))\n\t\tcase r2(c, r) => println(toRC(c, r.toInt))\n\t}\n\n}"}, {"source_code": "object spreadsheets extends App {\n val chars = ('A' to 'Z').toArray\n val RC = \"R([0-9]+)C([0-9]+)\".r\n val CR = \"([A-Z]+)([0-9]+)\".r\n \n def toCR(r: Int, c: Int) = {\n def c2s(c: Int): String =\n if(c > 0) c2s((c - 1) / 26) + chars((c - 1) % 26)\n else \"\"\n c2s(c) + r\n }\n def toRC(c: String, r: Int) = {\n val ci = c.foldLeft(0) { (l, c) => (l * 26) + (c - 'A' + 1) }\n s\"R${r}C${ci}\"\n }\n \n for(i <- 1 to readInt) readLine match {\n case RC(r, c) => println(toCR(r.toInt, c.toInt))\n case CR(c, r) => println(toRC(c, r.toInt))\n //case l => println(s\"ERROR: $l\")\n }\n}"}, {"source_code": "object B extends App {\nimport java.util.{Scanner => Inputer}\nimport scala.util.matching.Regex\n\n\tval in = new Inputer(System.in);\n\tval n = in nextInt\n\t\n\tval numRep = \"\"\"R(\\d+)C(\\d+)\"\"\".r\n\tval letRep = \"\"\"([A-Z]+)(\\d+)\"\"\".r\n\t\n\tdef letterToNumeral(s: String) = {\n\t var res = 0\n\t for (c <- s) {\n\t res = res * 26 + (c - 'A')\n\t }\n\t \n\t var i = 1\n\t var p = 26\n\t while (i < s.length) {\n\t res += p\n\t i += 1\n\t p *= 26\n\t }\n\t res + 1\n\t}\n\t\n\tdef numeralToLetter(x: Int) = {\n\t var t = x-1\n\t \n\t var i = 1\n\t var p = 26\n\t while (p < t) {\n\t i += 1\n\t t -= p\n\t p *= 26\n\t }\n\t i -= 1\n\t p /= 26\n\t \n\t var s = \"\"\n\t while (i >= 0) {\n\t s = ('A' + t % 26).toChar + s\n\t t /= 26\n\t i -= 1\n\t }\n\t \n\t s\n\t}\n\t\n\tvar i = 0\n\twhile (i < n) {\n\t val s = in.next()\n\t s match {\n\t case numRep(rstr, cstr) => {\n\t val r = rstr toInt\n\t val c = cstr toInt;\n\t println(numeralToLetter(c) + r)\n\t }\n\t case letRep(rstr, cstr) => {\n\t println(\"R\" + cstr + \"C\" + letterToNumeral(rstr))\n\t }\n\t }\n\t i += 1\n\t}\n}\n"}, {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n def numToStr(num: Int, strlen: Int, x: Int): String =\n if(strlen == 1 && num <= 26) ('A' + num - 1).toChar.formatted(\"%c\")\n else if(num > x * 26) numToStr(num - 26 * x, strlen + 1, x * 26)\n else ('A' + (num - 1) / x).toChar.formatted(\"%c\") + numToStr(1 + (num - 1) % x, strlen - 1, x / 26)\n def numToStr(num: Int): String = numToStr(num, 1, 1)\n\n def strToNum(str: String) = {\n (1 until str.length).foldLeft((1, 0)) {\n case ((cur, sum), _) => (cur * 26, sum + cur * 26)\n }._2 + str.foldLeft(0) {\n case (sum, char) => sum * 26 + char - 'A'\n } + 1\n }\n\n def ans = (for(_ <- 1 to readInt) yield {\n val p1 = \"R(\\\\d+)C(\\\\d+)\".r\n val p2 = \"([A-Z]+)(\\\\d+)\".r\n reader.readLine() match {\n case p1(row, column) => numToStr(column.toInt) + row\n case p2(row, column) => \"R%sC%d\".format(column, strToNum(row))\n }\n }).mkString(\"\\n\")\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Spreadsheets extends App {\n val lines = io.Source.stdin.getLines\n val n = lines.next.toInt\n \n val rcPattern = \"\"\"^R(\\d+)C(\\d+)$\"\"\".r\n val letterPattern = \"\"\"^([A-Z]+)(\\d+)$\"\"\".r\n val letters = 'A' to 'Z'\n \n lines.take(n).foreach(coordinates => convert(coordinates))\n \n def convert(coordinates: String) {\n rcPattern.findFirstMatchIn(coordinates) match {\n case Some(result) => convertRcCoordinates(result.group(1), result.group(2))\n case None => letterPattern.findFirstMatchIn(coordinates) match {\n case Some(result) => convertLetterCoordinates(result.group(2), result.group(1))\n case None => \n }\n } \n }\n\n def convertRcCoordinates(row: String, col: String) {\n val colInt = col.toInt\n \n var resultCol = \"\"\n var remainder = colInt\n while (remainder > 0) {\n resultCol = (letters((remainder-1) % 26).toString) + resultCol\n remainder = ((remainder-1) / 26)\n }\n \n println(resultCol + row)\n }\n\n def convertLetterCoordinates(row: String, col: String) {\n var resultCol = 0\n var remainder = col\n while (!remainder.isEmpty) {\n resultCol = resultCol * 26 + (letters.indexOf(remainder.head) + 1)\n remainder = remainder.tail\n }\n \n println(\"R\" + row + \"C\" + resultCol)\n }\n}"}, {"source_code": "object Main {\n private val chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \n sealed trait Index {\n def print: Unit\n }\n \n case class CharIndex(row: Int, col: String) extends Index {\n private def convert(str: String) = str.foldLeft(0) { (a, c) => \n a * 26 + (c - 'A').toInt + 1\n }\n \n override def print {\n println(\"R\" + row + \"C\" + convert(col))\n }\n }\n \n case class NumberIndex(row: Int, col: Int) extends Index {\n private def divide(num: Int): List[Int] = {\n val div = (num - 1) / 26\n if (div == 0) List((num - 1)% 26)\n else divide(div) ::: List((num - 1) % 26)\n }\n \n private def convert(num: Int) = divide(num).map(chars(_)).mkString\n \n override def print {\n println(convert(col) + row)\n }\n }\n \n val cir = \"([A-Z]+)([0-9]+)\".r\n val iir = \"R([0-9]+)C([0-9]+)\".r\n\n def main(args: Array[String]) {\n val n = readInt()\n for(_ <- 1 to n) {\n readLine match {\n case cir(col, row) => CharIndex(row.toInt, col).print\n case iir(row, col) => NumberIndex(row.toInt, col.toInt).print\n }\n }\n }\n}"}, {"source_code": "object Main extends App {\n val n = scala.io.StdIn.readLine().toInt;\n val string_set: Array[String] = (1 to n).map((_) => scala.io.StdIn.readLine()).toArray;\n var next: String = \"\";\n\n// var string_set: Array[String] = Array();\n// for (i <- 1 to n)\n// string_set +:= scala.io.StdIn.readLine();\n\n for (i <- 1 to n) {\n// next = string_set(string_set.length - i);\n next = string_set(i - 1)\n\n var (l, r) = (-1, next.length);\n while (Character.isAlphabetic(next(l + 1)))\n l += 1;\n while (Character.isDigit(next(r - 1)))\n r -= 1;\n\n if (r - l == 1)\n print(\"R\" + next.substring(r) + \"C\" + func.fromTE(next.substring(0, r)) + \"\\n\")\n else\n print(func.toTE(next.substring(r).toInt) + next.substring(l + 1, r - 1) + \"\\n\")\n }\n}\n\nobject func {\n val alphabet = Array(\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\",\n \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\");\n\n def toTE(source: Int): String = {\n var inter = source\n var target = \"\"\n while (inter > 0) {\n target = alphabet((inter - 1) % 26) + target;\n inter = math.floor((inter - 1) / 26).toInt;\n }\n target\n }\n\n\n def fromTE(source: String): Int = source.toSeq.foldLeft(0){\n var i = 0;\n val sLength = source.length;\n\n (res, symb) => {\n i += 1;\n res + (Char.char2int(symb) - 'A'.toInt + 1) * math.pow(26, sLength - i).toInt }\n }\n}\n"}, {"source_code": "\nobject OneB extends App {\n\n\tval n = readInt\n\n\tval rcPattern = \"\"\"R(\\d+)C(\\d+)\"\"\".r\n\tval otherPattern = \"\"\"([A-Z]+)(\\d+)\"\"\".r\n\n\t(0 until n) foreach { i =>\n\t\treadLine match {\n\t\t\tcase rcPattern(row, col) =>\n\t\t\t\tprintln(numToLetter(col) + row)\n\t\t\tcase otherPattern(col, row) =>\n\t\t\t\tprintln(\"R\" + row + \"C\" + letterToNum(col))\n\t\t}\n\n\t}\n\n\tdef letterToNum = { str: String =>\n\t\tstr.foldLeft(0) { (num, char) =>\n\t\t\tnum * 26 + (char - 'A') + 1\n\t\t}\n\t}\n\n\tdef numToLetter = { nump: String =>\n\n\t\timport scala.collection.mutable.Stack\n\t\tval str = new Stack[Char]\n\t\tvar num = nump.toInt\n\t\twhile (num > 0) {\n\t\t\tvar alpha = (num - 1) % 26\n\t\t\tnum = (num - 1) / 26\n\t\t\tstr.push(('A' + alpha).toChar)\n\t\t}\n\t\tstr.mkString(\"\")\n\t}\n\n}"}, {"source_code": "object Main extends App {\n def rctoletter(x : Long) : String = {\n var result : String = \"\"\n var number = x\n while(number > 0)\n {\n var a = (number-1) % 26\n number = (number-1) / 26\n result = ('A' + a).toChar + result\n }\n result\n }\n def lettertorc(x : String) : Long = {\n var result : Long = 0\n for(c <- x)\n result = (result) * 26 + (c-'A')+1\n result\n }\n val n = readLine().toInt\n\n val numRegexp = \"\"\"R(\\d+)C(\\d+)\"\"\".r\n val letRegexp = \"\"\"([A-Z]+)(\\d+)\"\"\".r\n\n for (i <- 1 to n)\n {\n val in : String = readLine()\n\n in match\n {\n case numRegexp(rnum, cnum) => {\n println(rctoletter(cnum.toLong)+rnum)\n }\n case letRegexp(cstr, rnum) => {\n val cnum = lettertorc(cstr)\n println(\"R\"+rnum+\"C\"+cnum)\n }\n }\n }\n}"}, {"source_code": "object Main extends App {\n val n = scala.io.StdIn.readLine().toInt;\n val string_set: Array[String] = (1 to n).map((_) => scala.io.StdIn.readLine()).toArray;\n var next: String = \"\";\n\n// var string_set: Array[String] = Array();\n// for (i <- 1 to n)\n// string_set +:= scala.io.StdIn.readLine();\n\n for (i <- 1 to n) {\n// next = string_set(string_set.length - i);\n next = string_set(i - 1)\n\n var (l, r) = (-1, next.length);\n while (Character.isAlphabetic(next(l + 1)))\n l += 1;\n while (Character.isDigit(next(r - 1)))\n r -= 1;\n if (r - l == 1) {\n printf(\"R%sC%d\\n\", next.substring(r), func.fromTE(next.substring(0, r)));\n }\n else {\n printf(\"%s%s\\n\", func.toTE(next.substring(r).toInt), next.substring(l + 1, r - 1))\n }\n }\n}\n\nobject func {\n val alphabet = Array(\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\",\n \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\");\n\n def toTE(source: Int): String = {\n var inter = source\n var target = \"\"\n while (inter > 0) {\n target = alphabet((inter - 1) % 26) + target;\n inter = math.floor((inter - 1) / 26).toInt;\n }\n target\n }\n\n\n def fromTE(source: String): Int = source.toSeq.foldLeft(0){\n var i = 0;\n val sLength = source.length;\n\n (res, symb) => {\n i += 1;\n res + (Char.char2int(symb) - 'A'.toInt + 1) * math.pow(26, sLength - i).toInt }\n }\n}\n"}, {"source_code": "object spreadsheets extends App {\n val chars = ('A' to 'Z').toArray\n val RC = \"R([0-9]+)C([0-9]+)\".r\n val CR = \"([A-Z]+)([0-9]+)\".r\n \n def toCR(r: Int, c: Int) = {\n def c2s(c: Int): String =\n if(c > 0) c2s((c - 1) / 26) + chars((c - 1) % 26)\n else \"\"\n c2s(c) + r\n }\n def toRC(c: String, r: Int) = {\n val ci = c.foldLeft(0) { (l, c) => (l * 26) + (c - 'A' + 1) }\n s\"R${r}C${ci}\"\n }\n \n for(i <- 1 to readInt) readLine match {\n case RC(r, c) => println(toCR(r.toInt, c.toInt))\n case CR(c, r) => println(toRC(c, r.toInt))\n //case l => println(s\"ERROR: $l\")\n }\n}"}, {"source_code": "import io.Source\n\nobject SpreadSheet {\n val numeric = \"\"\"R(\\d+)C(\\d+)\"\"\".r\n val alphaNumeric = \"\"\"([A-Z]+)(\\d+)\"\"\".r\n\n def main(args: Array[String]) = {\n val lines = Source.stdin.getLines()\n lines.next()\n lines.foreach(processLine _)\n }\n\n def processLine(line: String) = {\n line match {\n case numeric(row, column) => println(numericToAlphaNumeric(row.toInt, column.toInt))\n case alphaNumeric(column, row) => println(alphanumericToNumeric(row.toInt, column))\n }\n }\n\n def numericToAlphaNumeric(row: Int, column: Int): String = {\n val newCol = new StringBuilder\n var currCol = column\n var newChar = 'a'\n\n // if currCol % 26 == 0, then write a 'Z', divide by 26 and subtract by 1\n while (currCol > 0) {\n if (currCol % 26 == 0) {\n newChar = 'Z'\n currCol = currCol / 26 - 1\n }\n else {\n newChar = ('A' + (currCol % 26) - 1).toChar\n currCol = currCol / 26\n }\n newCol += newChar\n }\n return newCol.reverse.toString + row\n }\n\n def alphanumericToNumeric(row: Int, column: String): String = {\n var offset = 1\n\n var numericalColumn = 0\n for (ch <- column.reverse) {\n numericalColumn += (ch - 64) * offset\n offset *= 26\n }\n\n return \"R\" + row + \"C\" + numericalColumn\n }\n\n def printTest(stop: Int) = {\n var prefix = \"R1C\"\n var arg = \"\"\n var failed = false\n for (col <- 1 to stop) {\n arg = prefix + col\n var result = numericToAlphaNumeric(1, col)\n val alphaNumeric(stringColumn, _) = result\n if (arg != alphanumericToNumeric(1, stringColumn)) {\n println(\"We had a booboo: arg was \" + arg + \", conversion was: \" + result)\n failed = true\n }\n }\n if (!failed) {\n println(\"All tests passed\")\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject _1B {\n def main (args: Array[String]) = {\n val num = readInt\n val coords = new Array[String](num);\n for (i <- 0 until num) {\n coords(i) = readLine\n }\n \n for (coord <- coords)\n println(convert(coord))\n }\n \n def convert (coord: String) = {\n var col = \"\"\n var row = \"\"\n if (coord.matches(\"R[0-9]+C[0-9]+\")) {\n val idx = coord.indexWhere { x => x == 'C' }\n row = coord.slice(1, idx)\n col = coord.slice(idx+1, coord.length)\n col = toABC(col)\n \n col+row\n }\n else {\n val idx = coord.indexWhere { x => x.isDigit }\n col = coord.slice(0, idx)\n row = coord.slice(idx, coord.length)\n col = toDigit(col)\n \n \"R\"+row+\"C\"+col\n \n }\n \n }\n \n def toABC(digit: String) = {\n var d = digit.toInt\n var r = 0\n var abc = \"\"\n val alphabet = \"ZABCDEFGHIJKLMNOPQRSTUVWXY\"\n \n while (d / 26 > 0) {\n r = d % 26\n abc = alphabet.charAt(r) + abc\n d = d / 26\n if (r == 0)\n d -= 1\n }\n if (d > 0)\n abc = alphabet.charAt(d) + abc\n \n abc\n }\n \n def toDigit(abc: String) = {\n var d = 0\n var f = 1\n for ( i <- 1 to abc.length) {\n d += (abc.charAt(abc.length-i) - 'A' + 1) * f\n f *= 26\n }\n d.toString\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject _1B {\n def main (args: Array[String]) = {\n val num = readInt\n val coords = new Array[String](num);\n for (i <- 0 until num) {\n coords(i) = readLine\n }\n \n for (coord <- coords)\n println(convert(coord))\n }\n \n def convert (coord: String) = {\n var col = \"\"\n var row = \"\"\n if (coord.matches(\"R[0-9]+C[0-9]+\")) {\n val idx = coord.indexWhere { x => x == 'C' }\n row = coord.slice(1, idx)\n col = coord.slice(idx+1, coord.length)\n col = toABC(col)\n \n col+row\n }\n else {\n val idx = coord.indexWhere { x => x.isDigit }\n col = coord.slice(0, idx)\n row = coord.slice(idx, coord.length)\n col = toDigit(col)\n \n \"R\"+row+\"C\"+col\n \n }\n \n }\n \n def toABC(digit: String) = {\n var d = digit.toInt\n var r = 0\n var abc = \"\"\n val alphabet = \"ZABCDEFGHIJKLMNOPQRSTUVWXY\"\n \n while (d / 26 > 0) {\n r = d % 26\n abc = alphabet.charAt(r) + abc\n d = d / 26\n if (r == 0)\n d -= 1\n }\n if (d > 0)\n abc = alphabet.charAt(d) + abc\n \n abc\n }\n \n def toDigit(abc: String) = {\n var d = 0\n var f = 1\n for ( i <- 1 to abc.length) {\n d += (abc.charAt(abc.length-i) - 'A' + 1) * f\n f *= 26\n }\n d.toString\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject _1B {\n def main (args: Array[String]) = {\n var num = readInt\n var coords = new Array[String](num);\n for (i <- 0 until num) {\n coords(i) = readLine\n }\n \n for (coord <- coords)\n println(convert(coord))\n }\n \n def convert (coord: String) = {\n var col = \"\"\n var row = \"\"\n if (coord.matches(\"R[0-9]+C[0-9]+\")) {\n var idx = coord.indexWhere { x => x == 'C' }\n row = coord.slice(1, idx)\n col = coord.slice(idx+1, coord.length)\n col = toABC(col)\n \n col+row\n }\n else {\n var idx = coord.indexWhere { x => x.isDigit }\n col = coord.slice(0, idx)\n row = coord.slice(idx, coord.length)\n col = toDigit(col)\n \n \"R\"+row+\"C\"+col\n \n }\n \n }\n \n def toABC(digit: String) = {\n var d = digit.toInt\n var r = 0\n var abc = \"\"\n var alphabet = \"ZABCDEFGHIJKLMNOPQRSTUVWXY\"\n \n while (d / 26 > 0) {\n r = d % 26\n abc = alphabet.charAt(r) + abc\n d = d / 26\n if (r == 0)\n d -= 1\n }\n if (d > 0)\n abc = alphabet.charAt(d) + abc\n \n abc\n }\n \n def toDigit(abc: String) = {\n var d = 0\n var f = 1\n for ( i <- 1 to abc.length) {\n d += (abc.charAt(abc.length-i) - 'A' + 1) * f\n f *= 26\n }\n d.toString\n }\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer\n\n\nobject Spreadsheets {\n\n def main(args: Array[String]) = {\n val n = scala.io.StdIn.readLine().toInt\n for (_ <- 0 until n) {\n val line = scala.io.StdIn.readLine()\n var is_charcters = true\n val values = new ListBuffer[Int]\n var i = 0\n while (i < line.length) {\n var value = 0\n if (is_charcters) {\n while (i < line.length && line(i).isUpper) {\n value = value * 26 + line(i) - 'A' + 1\n i += 1\n }\n } else {\n while (i < line.length && line(i).isDigit) {\n value = value * 10 + line(i) - '0'\n i += 1\n }\n }\n is_charcters = !is_charcters\n values += value\n }\n if (values.length == 4) {\n var (r, c) = (values(1), values(3))\n val col = new StringBuilder\n while (c > 0) {\n col.append( ('A' + ((c + 25) % 26)).toChar )\n c -= 1\n c /= 26\n }\n val str = col.reverse.toString()\n printf(\"%s%d\\n\", str, r)\n } else {\n printf(\"R%dC%d\\n\", values.reverse:_*)\n\n }\n }\n }\n}\n\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n for (i <- 0 until n) {\n val rcPattern = \"R(\\\\d+)C(\\\\d+)\".r\n val namePattern = \"([A-Z]+)(\\\\d+)\".r\n sc.next() match {\n case rcPattern(r, c) => println(rc2Name(r.toInt, c.toInt))\n case namePattern(c, r) => println(name2RC(c, r.toInt))\n case _ =>\n }\n }\n }\n\n def rc2Name(r: Int, c: Int): String = {\n var cTmp = c\n var cName = \"\"\n do {\n val remainder = cTmp % 26\n if (remainder == 0) {\n cName = 'Z' + cName\n cTmp -= 26\n } else {\n cName = (remainder + 'A'.toInt - 1).toChar.toString() + cName\n }\n cTmp /= 26\n } while (cTmp != 0)\n return cName + r\n }\n\n def name2RC(c: String, r: Int): String = {\n val length = c.length()\n var cVal = 0\n for (i <- 0 until length) {\n cVal += (c.charAt(i) - 'A'.toInt + 1) * math.pow(26, length - 1 - i).asInstanceOf[Int]\n }\n return \"R\" + r + \"C\" + cVal\n }\n}"}, {"source_code": "/**\n * Created by gzq on 15-4-4.\n */\nobject CF1B {\n def letters2Numbers(str: String): Int = {\n str.map(letter => letter - 'A' + 1).reduceLeft((sum, ele) => sum * 26 + ele)\n }\n\n def numbers2Letters(x: Int): String = {\n var t = x-1\n\n var i = 1\n var p = 26\n while (p < t) {\n i += 1\n t -= p\n p *= 26\n }\n i -= 1\n p /= 26\n\n var s = \"\"\n while (i >= 0) {\n s = ('A' + t % 26).toChar + s\n t /= 26\n i -= 1\n }\n\n s\n }\n\n def main(args: Array[String]) {\n val in = scala.io.StdIn\n val count = in.readInt()\n\n // Define patters\n // pattern1 matches strings like BC23\n // pattern2 matches strings like R23C55\n val pattern1 = \"\"\"([a-zA-Z]+)(\\d+)\"\"\".r\n val pattern2 = \"\"\"R(\\d+)C(\\d+)\"\"\".r\n\n for (i <- 1 to count) {\n val line = in.readLine()\n\n line match {\n case pattern1(column, row) => println(\"R\" + row + \"C\" + letters2Numbers(column))\n case pattern2(row, column) => println(numbers2Letters(column.toInt) + row)\n }\n }\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\nobject X extends App {\n val inp = scala.io.StdIn.readLine()\n val lines = inp.toInt\n\n case class Stand(val row: Int, val col: Int);\n\n val rowColToStand = (rowCol: String) => {\n val rCRegex = \"R(.*)C(.*)\".r\n rCRegex.findFirstMatchIn(rowCol) match {\n case None => Stand(0, 0)\n case Some(value) => Stand(value.group(1).toInt, value.group(2).toInt)\n }\n }\n\n val standToRowCol = (stand: Stand) => {\n stand match {\n case Stand(row, col) => s\"R${row}C${col}\"\n }\n }\n\n val baseToDec = (baseRep: String, baseMap: Map[String, Int]) => {\n val baseSize = baseMap.size - 1\n\n baseRep.foldLeft(0)((acc, currChar) =>\n (acc + baseMap(currChar.toString())) * baseSize\n ) / baseSize\n }\n\n @tailrec\n def decToBase(\n num: Int,\n inverseBaseMap: Map[Int, String],\n acc: List[String] = List()\n ): String = {\n val baseSize = inverseBaseMap.size - 1\n\n if (num == 0) {\n acc.mkString(\"\")\n } else {\n val rem = num % baseSize\n val actualRem = if (rem == 0) baseSize else rem\n val diff = (num - actualRem) / baseSize;\n decToBase(diff, inverseBaseMap, inverseBaseMap(actualRem) +: acc)\n }\n }\n\n val alphaBase = \"_ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n .split(\"\")\n .foldLeft(Map[String, Int]())((accMap, currChar) =>\n accMap + (currChar.toString() -> accMap.size)\n )\n val inverseAlphaBase = alphaBase.map(_.swap)\n\n val alphaToStand = (alphaRep: String) => {\n val alphaRegex = \"([A-Z]*)([0-9]*)\".r\n alphaRegex.findFirstMatchIn(alphaRep) match {\n case None => Stand(0, 0)\n case Some(value) => {\n Stand(value.group(2).toInt, baseToDec(value.group(1), alphaBase))\n }\n }\n }\n\n val standToAlpha = (stand: Stand) =>\n s\"${decToBase(stand.col, inverseAlphaBase)}${stand.row}\"\n\n val alphaToRowCol = (alpha: String) => standToRowCol(alphaToStand(alpha))\n val rowColToAlpha = (rowCol: String) => standToAlpha(rowColToStand(rowCol))\n\n (0 until lines).foreach(l => {\n val line = scala.io.StdIn.readLine()\n val rCRegex = \"^R[0-9]+C[0-9]+$\".r\n\n val otherRep = rCRegex.findFirstMatchIn(line) match {\n case None => alphaToRowCol(line)\n case Some(value) => rowColToAlpha(line)\n }\n println(otherRep)\n\n })\n}\n"}, {"source_code": "import scala.util.matching.Regex\n\n\nobject Main extends App {\n\n val ground = 'A'.toInt - 1\n val step = 'Z'.toInt - ground\n\n def letterToDigit(value: String): Int = {\n if (value.length > 1) {\n ((value.charAt(0).toInt - ground) * Math.pow(step, value.length -1)).toInt + letterToDigit(value.substring(1))\n } else {\n value.charAt(0).toInt - ground\n }\n }\n\n def digitToLetter(value: Int): String = {\n if (value <= step) {\n (value + ground).toChar.toString\n } else {\n if((value % step) > 0) {\n digitToLetter(value / step) + (value % step + ground).toChar.toString\n } else {\n digitToLetter(value / step -1) + ( step + ground).toChar.toString\n }\n }\n }\n\n def translate(value: String) = {\n if (value.matches(\"R\\\\d{1,}C\\\\d{1,}\")) {\n val cIndex = value.indexOf(\"C\")\n val row = value.substring(1, cIndex)\n val column = value.substring(cIndex + 1).toInt\n digitToLetter(column) + row\n }\n else {\n val pattern = new Regex(\"[A-Z]*\")\n val column = pattern.findFirstIn(value).get\n val row = value.substring(column.size)\n \"R\" + row + \"C\" + letterToDigit(column)\n }\n }\n\n\n val numOfRounds = Console.readInt\n if (numOfRounds <= 0 || numOfRounds > 1e5f) {\n throw new Exception(\"Illegal value\")\n }\n\n for (i <- 1 to numOfRounds) {\n println(translate(Console.readLine()))\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main { \n val alphList = ('A' to 'Z').toList\n def main(args: Array[String]) { \n val sc = new Scanner(System.in)\n val n = sc.nextInt\n for (i <- 1 to n) { \n val str = sc.next\n val p = \"R[1-9][0-9]*C[1-9][0-9]*\".r\n if (str matches \"R[1-9][0-9]*C[1-9][0-9]*\") { \n val a = str.split(\"[RC]\")\n println(numToStr(a(2).toInt).reverse + a(1))\n } else { \n println(\"R\" + str.split(\"[A-Z]+\")(1) + \"C\" + f(str.split(\"[0-9]+\")(0).toList))\n }\n }\n }\n def numToStr(n: Int): String = ((n - 1) / 26, (n - 1) % 26) match { \n case (0, i) => alphList(i).toString\n case (m, i) => alphList(i) + numToStr(m)\n }\n \n def f(xs: List[Char]): Int = xs match {\n case List() => 0\n case y :: ys => (y - 'A' + 1) * math.pow(26, ys.size).toInt + f(ys)\n }\n}\n"}, {"source_code": "import scala.util.matching.Regex\n\nobject SpreadSheet{\n val RowCollumn = new Regex(\"R[0-9]+C[0-9]+\")\n\n def main(args: Array[String]): Unit = {\n val n = readln.toInt\n (1 to n)\n .iterator\n .map( _ =>\n readln\n ).map( string =>\n if(isRowCollumn(string)){\n rc2classic(string)\n } else {\n classic2rc(string)\n }\n ).foreach(println)\n }\n\n def isRowCollumn = corresponds2patter(RowCollumn) _\n\n def rc2classic(s: String): String = {\n val rc = s.drop(1).split(\"C\").map(_.toInt)\n val (row,collumn) = (rc(0),rc(1))\n s\"${int2collumn(collumn,\"\")}$row\"\n }\n\n def classic2rc(s: String):String = {\n val collumn = s.takeWhile(_.isLetter)\n val row = s.dropWhile(_.isLetter).toInt\n s\"R${row}C${collumn2int(collumn,0)}\"\n }\n\n def int2collumn(i:Int,s: String):String = i match {\n case 0 => s\n case x =>\n int2collumn((x-1) / 26, s\"${(ordOfA + ((x+25) % 26) ).toChar}$s\")\n }\n\n def collumn2int(s:String,i:Int): Int =\n if (s.isEmpty) i else {\n collumn2int(s.drop(1),i*26 + (s.charAt(0).toInt - ordOfA +1))\n }\n\n\n def ordOfa = 'a'.toInt\n def ordOfz = 'z'.toInt\n def ordOfA = 'A'.toInt\n def ordOfZ = 'Z'.toInt\n\n def char2Int(char: Char) = char.toInt\n def int2char(number: Int) = number.toChar\n\n def readln: String = scala.io.StdIn.readLine()\n\n def corresponds2patter(pattern: Regex)(string: String): Boolean =\n pattern.findFirstIn(string).nonEmpty\n}\n"}, {"source_code": "object P1B {\n def main(args : Array[String]) {\n val n = readLine.toInt\n for (_ <- 1 to n) {\n val alNum = \"([A-Z]+)([0-9]+)\".r\n val rc = \"R([0-9]+)C([0-9]+)\".r\n readLine match {\n case alNum(al, num) => {\n val c = al map {_ - 'A' + 1} reduce {_ * 26 + _}\n println(\"R\" + num + \"C\" + c)\n }\n case rc(r, c) => {\n val al = new Iterator[Char] {\n var x = c.toInt\n def hasNext = x > 0\n def next = {\n val xNew = (x - 1) / 26\n val ret = (x - xNew * 26 - 1 + 'A').toChar\n x = xNew\n ret\n }\n }.mkString.reverse\n println(al + r)\n }\n }\n }\n }\n}\n"}], "negative_code": [{"source_code": "/**\n * Created by gzq on 15-4-4.\n */\nobject CF1B {\n def letters2Numbers(str: String): Int = {\n str.map(letter => letter - 'A' + 1).reduceLeft((sum, ele) => sum * 26 + ele)\n }\n\n def numbers2Letters(strNum: String): String = {\n val aLessOne = 'A' - 1\n var num = strNum.toInt\n var result = \"\"\n while (num != 0) {\n val remainder = num % 26\n if (remainder != 0) {\n result = (remainder + aLessOne).toChar + result\n } else {\n result = result + 'Z'\n }\n num /= 26\n }\n return result\n }\n\n def main(args: Array[String]) {\n val in = scala.io.StdIn\n val count = in.readInt()\n\n // Define patters\n // pattern1 matches strings like BC23\n // pattern2 matches strings like R23C55\n val pattern1 = \"\"\"([a-zA-Z]+)(\\d+)\"\"\".r\n val pattern2 = \"\"\"R(\\d+)C(\\d+)\"\"\".r\n\n for (i <- 1 to count) {\n val line = in.readLine()\n\n line match {\n case pattern1(column, row) => println(\"R\" + row + \"C\" + letters2Numbers(column))\n case pattern2(row, column) => println(numbers2Letters(column) + row)\n }\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n for (i <- 0 until n) {\n val str = scanner.next().toUpperCase\n println({\n if (isNormal(str))\n toReverse(str)\n else\n toNormal(str)\n }.toUpperCase)\n }\n }\n\n\n def toReverse(str: String): String = {\n val index = str.indexOf(\"C\")\n toSymbol(str.substring(index + 1)) + str.substring(1, index)\n }\n\n def toNormal(str: String): String = {\n var columnNumber = \"\"\n var rowNumber = \"\"\n for (s <- str)\n if (s.isDigit)\n rowNumber = rowNumber + s\n else\n columnNumber = columnNumber + s\n\n \"R\" + rowNumber + \"C\" + toDec(columnNumber)\n }\n\n def toSymbol(str: String) = {\n var value = Integer.parseInt(str)\n var result = \"\"\n while (value > 0) {\n val v = value % 26\n\n result =\n if (v == 0 && value / 26 == 1) {\n value = 0\n \"Z\" + result\n } else {\n value = value / 26\n getSymbol(v) + result\n }\n }\n\n result\n }\n\n def toDec(str: String): String = {\n var result = 0\n for ((s, i) <- str.reverse.zipWithIndex)\n result = result + getNumber(s) * Math.pow(26, i).toInt\n\n result.toString\n }\n\n def getSymbol(number: Int): String = if (number == 0) \"A\" else (('A' - 1) + number).toChar.toString\n\n def getNumber(s: Char) = s - ('A' - 1)\n\n def isNormal(str: String): Boolean = str.matches(\"^R[\\\\d]+C[\\\\d]+$\")\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Artem Konovalov on 9/2/16.\n */\nobject Solution {\n def main(args: Array[String]): Unit = {\n\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n for (i <- 0 until n) {\n val str = scanner.next().toUpperCase\n println({\n if (isNormal(str))\n toReverse(str)\n else\n toNormal(str)\n }.toUpperCase)\n }\n }\n\n def isNormal(str: String): Boolean = str.charAt(0) == 'R' && str.charAt(1).isDigit\n\n\n def toNormal(str: String): String = {\n val index = str.indexOf('C')\n val rowNumber = str.substring(1, index)\n val columnNumber = str.substring(index + 1)\n\n reverseDec(columnNumber) + rowNumber\n }\n\n def toReverse(str: String): String = {\n var rowNumber = \"\"\n var columnNumber = \"\"\n for (s <- str)\n if (s.isDigit)\n rowNumber = rowNumber + s\n else\n columnNumber = columnNumber + s\n\n \"R\" + rowNumber + \"C\" + toDec(columnNumber)\n }\n\n def toDec(str: String): String = {\n var result = 0\n for ((s, i) <- str.reverse.zipWithIndex)\n result = result + ((s - 'A' + 1) * {\n if (i == 0) 1 else 26 * i\n })\n\n result.toString\n }\n\n def reverseDec(str: String): String = {\n var result = \"\"\n var number = Integer.parseInt(str)\n while (number != 0) {\n result = ('A' + (number % 26) - 1).toChar + result\n number = number / 26\n }\n result\n }\n}\n"}, {"source_code": "import scala.collection.mutable._\nimport scala.math._\nobject B extends App {\n def isRXCY(s: String): Boolean = {\n if(s.length < 4) return false\n s.count(_ == 'R') == 1 && s.count(_ == 'C') == 1 && s(1).isDigit\n }\n def toExcel(s: String): String = {\n val r = s.slice(s.indexOf('R')+1, s.indexOf('C')).toInt\n val c = s.drop(s.indexOf('C')+1).toInt\n def toAlph(v: Int): String = {\n if(v == 0) return \"\"\n toAlph((v-1) / 26 + (if(v % 26 == 0) 1 else 0)) + ('A' + (v-1) % 26).toChar\n }\n toAlph(c) + r\n }\n def toRXCY(s: String): String = {\n def toI(s: String, i: Int): Int = {\n if(s.length == 0) return 0\n ((s.last - 'A' + 1) * i) + toI(s.dropRight(1), i * 26)\n }\n val R = \"\"\"([A-Z]*)([0-9]*)\"\"\".r\n s match {\n case R(c,r) => \n \"R\" + r + \"C\" + toI(c,1)\n case _ => null\n }\n }\n val n = readLine.toInt\n for(i <- 0 until n) {\n val s = readLine\n println(\n if(isRXCY(s)) toExcel(s)\n else toRXCY(s)\n )\n }\n}\n"}, {"source_code": "import scala.collection.mutable._\nimport scala.math._\nobject B extends App {\n def isRXCY(s: String): Boolean = {\n if(s.length < 4) return false\n s.count(_ == 'R') == 1 && s.count(_ == 'C') == 1 && s(1).isDigit\n }\n def toExcel(s: String): String = {\n val r = s.slice(s.indexOf('R')+1, s.indexOf('C')).toInt\n val c = s.drop(s.indexOf('C')+1).toInt\n def toAlph(v: Int): String = {\n if(v == 0) return \"\"\n toAlph(v / 26) + ('A' + (v % 26) - 1).toChar\n }\n def removeAtmark(s: String): String = {\n if(!s.contains(\"@\")) return s\n if(s.startsWith(\"@\")) return removeAtmark(s.tail)\n val Ra = \"\"\"(.*)(.)@(.*)\"\"\".r\n val t = s match {\n case Ra(a,b,c) => \n a + (b(0)-1).toChar + 'Z' + c\n }\n removeAtmark(t)\n }\n removeAtmark(toAlph(c)) + r\n }\n def toRXCY(s: String): String = {\n def toI(s: String, i: Int): Int = {\n if(s.length == 0) return 0\n ((s.last - 'A' + 1) * i) + toI(s.dropRight(1), i * 26)\n }\n val R = \"\"\"([A-Z]*)([0-9]*)\"\"\".r\n s match {\n case R(c,r) => \n \"R\" + r + \"C\" + toI(c,1)\n case _ => null\n }\n }\n val n = readLine.toInt\n for(i <- 0 until n) {\n val s = readLine\n println(\n if(isRXCY(s)) toExcel(s)\n else toRXCY(s)\n )\n }\n}\n"}, {"source_code": "import scala.collection.mutable._\nimport scala.math._\nobject B extends App {\n def isRXCY(s: String): Boolean = {\n if(s.length < 4) return false\n s.count(_ == 'R') == 1 && s.count(_ == 'C') == 1 && s(1).isDigit\n }\n def toExcel(s: String): String = {\n val r = s.slice(s.indexOf('R')+1, s.indexOf('C')).toInt\n val c = s.drop(s.indexOf('C')+1).toInt\n def toAlph(v: Int): String = {\n if(v == 0) return \"\"\n toAlph(v / 26) + ('A' + (v % 26) - 1).toChar\n }\n toAlph(c) + r\n }\n def toRXCY(s: String): String = {\n def toI(s: String, i: Int): Int = {\n if(s.length == 0) return 0\n ((s.last - 'A' + 1) * i) + toI(s.dropRight(1), i * 26)\n }\n val R = \"\"\"([A-Z]*)([0-9]*)\"\"\".r\n s match {\n case R(c,r) => \n \"R\" + r + \"C\" + toI(c,1)\n case _ => null\n }\n }\n val n = readLine.toInt\n for(i <- 0 until n) {\n val s = readLine\n println(\n if(isRXCY(s)) toExcel(s)\n else toRXCY(s)\n )\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject B {\n def RC2Normal(r: String, c_str: String): String = {\n val c = c_str.toInt\n val (left, len) = Iterator.iterate((c, 1, 26)){p =>\n val (c_left, count, step) = p\n (c_left - step, count + 1, step * 26)\n }.find(p => p._1 > 0) match {\n case Some(x) => (x._1, x._2)\n }\n val c_converted = ((left - 1, \"\") /:(1 to len)){(p, i) =>\n (p._1 / 26, ('A'.toInt + (p._1 % 26)).toChar + p._2)}._2\n \"%s%s\".format(c_converted, r)\n }\n\n def Normal2RC(c_str: String, r:String): String = {\n val base = (1 to c_str.length).foldLeft(0)((a, b)=>a * 26 + 1)\n val diff = (0 /: c_str) ((s, c)=>s * 26 + c.toInt - 'A'.toInt)\n val c = base + diff\n \"R%sC%d\".format(r, c)\n }\n\n def conv(line: String): String = {\n val p_rc = \"\"\"^R(\\d+)C(\\d+)$\"\"\".r\n val p_norm = \"\"\"^([A-Z]+)(\\d+)$\"\"\".r\n return p_rc findFirstIn line match {\n case Some(p_rc(r, c)) => RC2Normal(r, c)\n case None => p_norm findFirstIn line match {\n case Some(p_norm(c, r)) => Normal2RC(c, r)\n\tcase None => \"Error\"\n }\n }\n }\n\n def main(args: Array[String]) = {\n val sc = new Scanner(System.in)\n val count = sc.nextInt\n sc.nextLine // skip newline\n for (i <- 1 to count) {\n val line = sc.nextLine\n println(conv(line))\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject B {\n def RC2Normal(r: String, c_str: String): String = {\n val c = c_str.toInt\n val (left, len) = Iterator.iterate((c, 1, 1)){p =>\n val (c_left, count, step) = p\n (c_left - step * 26, count + 1, step * 26)\n }.find(p => p._1 < 0) match {\n case Some(x) => (x._1 + x._3, x._2 - 1)\n\tcase None => (-1, -2)\n }\n val c_converted = ((left - 1, \"\") /:(1 to len)){(p, i) =>\n (p._1 / 26, ('A'.toInt + (p._1 % 26)).toChar + p._2)}._2\n \"%s%s\".format(c_converted, r)\n }\n\n def Normal2RC(c_str: String, r:String): String = {\n val base = (1 to c_str.length).foldLeft(0)((a, b)=>a * 26 + 1)\n val diff = (0 /: c_str) ((s, c)=>s * 26 + c.toInt - 'A'.toInt)\n val c = base + diff\n \"R%sC%d\".format(r, c)\n }\n\n def conv(line: String): String = {\n val p_rc = \"\"\"^R(\\d+)C(\\d+)$\"\"\".r\n val p_norm = \"\"\"^([A-Z]+)(\\d+)$\"\"\".r\n return p_rc findFirstIn line match {\n case Some(p_rc(r, c)) => RC2Normal(r, c)\n case None => p_norm findFirstIn line match {\n case Some(p_norm(c, r)) => Normal2RC(c, r)\n\tcase None => \"Error\"\n }\n }\n }\n\n def main(args: Array[String]) = {\n val sc = new Scanner(System.in)\n val count = sc.nextInt\n sc.nextLine // skip newline\n for (i <- 1 to count) {\n val line = sc.nextLine\n println(conv(line))\n }\n }\n}\n"}, {"source_code": "object Solution extends App {\n val f = \"^R(\\\\d+)C(\\\\d+)$\".r\n val s = \"^([A-Z]+)(\\\\d+)$\".r\n\n def strToVal(n: String): Int = n.foldLeft(0){\n case (acc, el) => acc * 26 + (el - 'A' + 1)\n }\n\n def valToStr(n: Int): String = n match {\n case 0 => \"\"\n case t => valToStr(t / 26) + ('A' + t % 26 - 1).toChar\n }\n\n def strToInt(n: String): String = n match {\n case f(row, column) => \n// println(\"Row \" + row + \" column \" + column)\n// (row.toInt, column.toInt)\n s\"${valToStr(column.toInt)}$row\"\n case s(column, row) =>\n// (strToVal(row), column.toInt)\n s\"R${row}C${strToVal(column)}\"\n }\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println(Range(0, n).map(_ => strToInt(in.next())).mkString(\"\\n\"))\n// println(min + \" \" + max)\n}"}, {"source_code": "object Solution extends App {\n val f = \"^R(\\\\d+)C(\\\\d+)$\".r\n val s = \"^([A-Z]+)(\\\\d+)$\".r\n\n def strToVal(n: String): Int = n.foldLeft(0){\n case (acc, el) => acc * 26 + (el - 'A' + 1)\n }\n\n def valToStr1(n: Int): String = {\n if (n == 0) {\n \"\"\n } else {\n valToStr1(n / 27) + (n % 27 + 'A').toChar\n }\n }\n\n def valToStr(n: Int) = if (n == 1) \"A\" else valToStr1(n - 1)\n\n def strToInt(n: String): String = n match {\n case f(row, column) =>\n // println(\"Row \" + row + \" column \" + column)\n // (row.toInt, column.toInt)\n s\"${valToStr(column.toInt)}$row\"\n case s(column, row) =>\n // (strToVal(row), column.toInt)\n s\"R${row}C${strToVal(column)}\"\n }\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n // println(strToInt(\"RZ228\"))\n // println(strToInt(\"RI228\"))\n // println(strToInt(\"R228C494\"))\n // println(valToStr(1))\n // println(valToStr(26))\n // println(valToStr(27))\n // println(valToStr(28))\n // Range(1, 1000).foreach(i => println(valToStr(i)))\n println(Range(0, n).map(_ => strToInt(in.next())).mkString(\"\\n\"))\n // println(min + \" \" + max)\n}"}, {"source_code": "object cf1B {\n\timport java.util.Scanner\n\tval sc = new Scanner(System.in)\n\tdef main(args : Array[String]) : Unit = {\n\t\tval n = sc.nextInt\n//\t\tprintln(rechange(\"BA23\"))\n//\t\tprintln(change(\"R23C55\"))\n\t\tfor(i <- 1 to n){\n\t\t\tval st = sc.next\n\t\t\tif(st.startsWith(\"R\"))\n\t\t\t\tprintln(change(st))\n\t\t\telse\n\t\t\t\tprintln(rechange(st))\n\t\t}\n\t}\n\tdef change(st:String):String = {\n\t\tval (s1,s2) = (st drop 1 ) span (_.isDigit)\n\t\tvar num = 0\n\t\ts2 drop 1 foreach(c => (num*=10,num+=c.toInt-'0'))\n\t\tvar s=\"\"\n\t\twhile(num>=0){\n\t\t\tval mod = num%26 \n\t\t\tnum/=26\n\t\t\ts+=('A'-1 + ( if(mod==0) {num-=1;26} else mod)).toChar\n\t\t}\n\t\ts.reverse+s1\n\t}\n\tdef rechange(st:String):String = {\n\t\tval (s1,s2) = st.span(c => c.isLetter)\n\t\tvar sum = 0\n\t\ts1 foreach (c =>(sum*=26,sum=sum+(c.toInt-'A'.toInt+1)))\n\t\t\"R\"+s2+\"C\"+sum\n\t}\n\n}"}, {"source_code": "object cf1B {\n\timport java.util.Scanner\n\tval sc = new Scanner(System.in)\n\tdef main(args : Array[String]) : Unit = {\n\t\tval n = sc.nextInt\n//\t\tprintln(rechange(\"BA23\"))\n//\t\tprintln(change(\"R23C55\"))\n\t\tfor(i <- 1 to n){\n\t\t\tval st = sc.next\n\t\t\tif(st(0)=='R' && st(1).isDigit)\n\t\t\t\tprintln(change(st))\n\t\t\telse\n\t\t\t\tprintln(rechange(st))\n\t\t}\n\t}\n\tdef change(st:String):String = {\n\t\tval (s1,s2) = (st drop 1 ) span (_.isDigit)\n\t\tvar num = 0\n\t\ts2 drop 1 foreach(c => (num*=10,num+=c.toInt-'0'))\n\t\tvar s=\"\"\n\t\twhile(num>0){\n\t\t\tval mod = num%26 \n\t\t\tnum/=26\n\t\t\ts+=('A'-1 + ( if(mod==0) {num-=1;26} else mod)).toChar\n\t\t}\n\t\ts.reverse+s1\n\t}\n\tdef rechange(st:String):String = {\n\t\tval (s1,s2) = st.span(c => c.isLetter)\n\t\tvar sum = 0\n\t\ts1 foreach (c =>(sum*=26,sum=sum+(c.toInt-'A'.toInt+1)))\n\t\t\"R\"+s2+\"C\"+sum\n\t}\n\n}"}, {"source_code": "object cf1B {\n\timport java.util.Scanner\n\tval sc = new Scanner(System.in)\n\tdef main(args : Array[String]) : Unit = {\n\t\tval n = sc.nextInt\n//\t\tprintln(rechange(\"BA23\"))\n//\t\tprintln(change(\"R23C55\"))\n\t\tfor(i <- 1 to n){\n\t\t\tval st = sc.next\n\t\t\tif(st.startsWith(\"R\"))\n\t\t\t\tprintln(change(st))\n\t\t\telse\n\t\t\t\tprintln(rechange(st))\n\t\t}\n\t}\n\tdef change(st:String):String = {\n\t\tval (s1,s2) = (st drop 1 ) span (_.isDigit)\n\t\tvar num = 0\n\t\ts2 drop 1 foreach(c => (num*=10,num+=c.toInt-'0'))\n\t\tvar s=\"\"\n\t\twhile(num!=0){\n\t\t\tvar head =num%26\n\t\t\ts=s+('A'+head-1).toChar\n\t\t\tnum/=26\n\t\t}\n\t\ts.reverse+s1\n\t}\n\tdef rechange(st:String):String = {\n\t\tval (s1,s2) = st.span(c => c.isLetter)\n\t\tvar sum = 0\n\t\ts1 foreach (c =>(sum*=26,sum=sum+(c.toInt-'A'.toInt+1)))\n\t\t\"R\"+s2+\"C\"+sum\n\t}\n\n}"}, {"source_code": "object cf1B {\n\timport java.util.Scanner\n\tval sc = new Scanner(System.in)\n\tdef main(args : Array[String]) : Unit = {\n\t\tval n = sc.nextInt\n//\t\tprintln(rechange(\"BA23\"))\n//\t\tprintln(change(\"R23C55\"))\n\t\tfor(i <- 1 to n){\n\t\t\tval st = sc.next\n\t\t\tif(st.startsWith(\"R\"))\n\t\t\t\tprintln(change(st))\n\t\t\telse\n\t\t\t\tprintln(rechange(st))\n\t\t}\n\t}\n\tdef change(st:String):String = {\n\t\tval (s1,s2) = (st drop 1 ) span (_.isDigit)\n\t\tvar num = 0\n\t\ts2 drop 1 foreach(c => (num*=10,num+=c.toInt-'0'))\n\t\tvar s=\"\"\n\t\twhile(num>0){\n\t\t\tval mod = num%26 \n\t\t\tnum/=26\n\t\t\ts+=('A'-1 + ( if(mod==0) {num-=1;26} else mod)).toChar\n\t\t}\n\t\ts.reverse+s1\n\t}\n\tdef rechange(st:String):String = {\n\t\tval (s1,s2) = st.span(c => c.isLetter)\n\t\tvar sum = 0\n\t\ts1 foreach (c =>(sum*=26,sum=sum+(c.toInt-'A'.toInt+1)))\n\t\t\"R\"+s2+\"C\"+sum\n\t}\n\n}"}, {"source_code": "object B1 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def baseAlphatoInt(a: String): Long = {\n var res = 0L\n for(i <- 0 until a.length) {\n res *= 26\n res += a(i)-'A'+1\n }\n res\n }\n def baseIntToAlpha(a: Int): String = {\n var num = a\n var res = \"\"\n while(num > 0) {\n res = (num%26 + 'A' - 1).toChar + res\n num /= 26\n }\n res\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val reg1 = \"\"\"R(\\d+)C(\\d+)\"\"\".r\n val reg2 = \"\"\"([A-Z]+)(\\d+)\"\"\".r\n\n for(_ <- 0 until n) {\n val input = read\n val ret = reg1.findFirstMatchIn(input) match {\n case Some(m) =>\n s\"${baseIntToAlpha(m.group(2).toInt)}${m.group(1)}\"\n case None =>\n reg2.findFirstMatchIn(input) match {\n case Some(m) =>\n s\"R${m.group(2)}C${baseAlphatoInt(m.group(1))}\"\n case None =>\n \"parsing failed\"\n }\n }\n println(ret)\n }\n }\n}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ListBuffer\nobject ETables extends App {\n\n val scanner = new Scanner(System.in)\n val lb = new ListBuffer[String]\n\n val asciiOffset = 64 // A-1\n val base = 26\n\n while (scanner.hasNextLine) lb.append(scanner.nextLine().toUpperCase)\n val input = lb.toList.tail\n\n def basePower(i: Int): Int = {\n def helper(p: Int, acc: Int): Int = {\n if (p == 0) 1 * acc\n else helper(p-1, acc*base)\n }\n helper(i, 1)\n }\n\n def transform2Number(col: String): Int = {\n def helper(c: String, iter: Int, acc: Int): Int =\n if (c.isEmpty) acc\n else helper(c.substring(1), iter+1, acc + (c.charAt(0) - asciiOffset) * basePower(iter))\n helper(col.reverse, 0, 0)\n }\n\n def transform2String(col: Int): String = {\n def mod2Char(m: Int): Char = if (m == 0) (asciiOffset+base).toChar else (asciiOffset + m).toChar\n def helper(c: Int, acc: String): String = {\n if (c == 0) acc\n else if (c % base == 0) helper(c / base - 1, acc + mod2Char(0))\n else helper(c / base, acc + mod2Char(c%base))\n }\n helper(col,\"\").reverse\n }\n\n def transform(s: String): String = {\n if (s matches \"\"\"^R\\d+C\\d+$\"\"\") transform2String(s.substring(s.indexOf('C')+1).toInt) + s.substring(1, s.indexOf('C'))\n else \"R\" + \"\"\"\\d+\"\"\".r.findFirstMatchIn(\"BC23\").get + \"C\" + transform2Number(\"\"\"^\\D+\"\"\".r.findFirstMatchIn(\"BC23\").get.toString())\n }\n\n input.foreach(s => println(transform(s)))\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ListBuffer\nobject ETables extends App {\n\n val scanner = new Scanner(System.in)\n val lb = new ListBuffer[String]\n\n val asciiOffset = 64 // A-1\n val base = 26\n\n while (scanner.hasNextLine) lb.append(scanner.nextLine().toUpperCase)\n val input = lb.toList.tail\n\n def basePower(i: Int): Int = {\n def helper(p: Int, acc: Int): Int = {\n if (p == 0) 1 * acc\n else helper(p-1, acc*base)\n }\n helper(i, 1)\n }\n\n def transform2Number(col: String): Int = {\n def helper(c: String, iter: Int, acc: Int): Int =\n if (c.isEmpty) acc\n else helper(c.substring(1), iter+1, acc + (c.charAt(0) - asciiOffset) * basePower(iter))\n helper(col.reverse, 0, 0)\n }\n\n def transform2String(col: Int): String = {\n def mod2Char(m: Int): Char = if (m == 0) (asciiOffset+base).toChar else (asciiOffset + m).toChar\n def helper(c: Int, acc: String): String = {\n if (c == 0) acc\n else if (c % base == 0) helper(c / base - 1, acc + mod2Char(0))\n else helper(c / base, acc + mod2Char(c%base))\n }\n helper(col,\"\").reverse\n }\n\n def transform(s: String): String = {\n if (s matches \"\"\"^R\\d+C\\d+$\"\"\") transform2String(s.substring(s.indexOf('C')+1).toInt) + s.substring(1, s.indexOf('C'))\n else \"R\" + \"\"\"\\d+\"\"\".r.findFirstMatchIn(\"BC23\").get + \"C\" + transform2Number(\"\"\"^\\D+\"\"\".r.findFirstMatchIn(\"BC23\").get.toString())\n }\n\n input.foreach(transform)\n}"}, {"source_code": "\n/**\n * Created by yangchaozhong on 3/8/15.\n */\nobject CF1B extends App {\n import java.io.{PrintWriter}\n import java.util.{Scanner}\n\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def isAType(s: String) = {\n s.matches(\"R\\\\d+C\\\\d+\")\n }\n\n def transform(s: String) = {\n if (s.matches(\"[A-Z]+\")) {\n var res = 0\n val rs = s.reverse\n (0 to (rs.length - 1)).foreach { i =>\n res += (rs.charAt(i) - 'A' + 1) * Math.pow(26, i).toInt\n }\n res\n } else {\n var res = \"\"\n\n var n = s.toInt\n while (n > 0) {\n var m = n % 26\n if (m == 0) m = 26\n res += (m + 64).toChar\n n = (n - m) / 26\n }\n\n res.reverse\n }\n }\n\n def solve = {\n val n = nextInt\n (1 to n).foreach { x =>\n var s = nextString\n if (isAType(s)) {\n s = s.replace(\"R\", \"\")\n s = s.replace(\"C\", \" \")\n val arr = s.split(\" \")\n val row = arr(0)\n val column = arr(1)\n\n out.println(s\"${transform(column)}$row\")\n } else {\n val row = s.filter(c => c >= '1' && c <= '9').mkString(\"\")\n val column = s.filter(c => c >= 'A' && c <= 'Z').mkString(\"\")\n out.println(s\"R${row}C${transform(column)}\")\n }\n }\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n"}, {"source_code": "\nobject B extends App {\nimport java.util.{Scanner => Inputer}\nimport scala.util.matching.Regex\n\n\n\tval in = new Inputer(System.in);\n\tval n = in nextInt\n\t\n\tval numRep = \"\"\"R(\\d+)C(\\d+)\"\"\".r\n\tval letRep = \"\"\"([A-Z]+)(\\d+)\"\"\".r\n\t\n\tdef letterToNumeral(s: String) = {\n\t var res = 0\n\t for (c <- s) {\n\t res = res * 26 + (c - 'A')\n\t }\n\t \n\t var i = 1\n\t var p = 26\n\t while (i < s.length) {\n\t res += p\n\t i += 1\n\t p *= 26\n\t }\n\t res + 1\n\t}\n\t\n\tdef numeralToLetter(x: Int) = {\n\t var t = x-1\n\t \n\t var i = 0\n\t var p = 26\n\t while (p < t) {\n\t i += 1\n\t p *= 26\n\t }\n\t i -= 1\n\t p /= 26\n\t t -= p\n\t \n\t var s = \"\"\n\t while (t > 0) {\n\t s = ('A' + t % 26).toChar + s\n\t t /= 26\n\t }\n\t \n\t s\n\t}\n\t\n\tvar i = 0\n\twhile (i < n) {\n\t val s = in.next()\n\t s match {\n\t case numRep(rstr, cstr) => {\n\t val r = rstr toInt\n\t val c = cstr toInt;\n\t println(numeralToLetter(c) + r)\n\t }\n\t case letRep(rstr, cstr) => {\n\t println(\"R\" + cstr + \"C\" + letterToNumeral(rstr))\n\t }\n\t }\n\t i += 1\n\t}\n}\n"}, {"source_code": "object Spreadsheets extends App {\n val lines = io.Source.stdin.getLines\n val n = lines.next.toInt\n \n val rcPattern = \"\"\"^R(\\d+)C(\\d+)$\"\"\".r\n val letterPattern = \"\"\"^([A-Z]+)(\\d+)$\"\"\".r\n val letters = 'A' to 'Z'\n \n lines.take(n).foreach(coordinates => convert(coordinates))\n \n def convert(coordinates: String) {\n rcPattern.findFirstMatchIn(coordinates) match {\n case Some(result) => convertRcCoordinates(result.group(1), result.group(2))\n case None => letterPattern.findFirstMatchIn(coordinates) match {\n case Some(result) => convertLetterCoordinates(result.group(2), result.group(1))\n case None => \n }\n } \n }\n\n def convertRcCoordinates(row: String, col: String) {\n val colInt = col.toInt - 1\n \n var resultCol = \"\"\n var remainder = colInt\n while (remainder > 0) {\n resultCol = (letters(remainder % 26).toString) + resultCol\n remainder = (remainder / 26) - 1\n }\n \n println(resultCol + row)\n }\n\n def convertLetterCoordinates(row: String, col: String) {\n var resultCol = 0\n var remainder = col\n while (!remainder.isEmpty) {\n resultCol = resultCol * 26 + (letters.indexOf(remainder.head) + 1)\n remainder = remainder.tail\n }\n \n println(\"R\" + row + \"C\" + resultCol)\n }\n}"}, {"source_code": "object Main extends App {\n val n = scala.io.StdIn.readLine().toInt;\n val string_set: Array[String] = (1 to n).map((_) => scala.io.StdIn.readLine()).toArray;\n var next: String = \"\";\n\n// var string_set: Array[String] = Array();\n// for (i <- 1 to n)\n// string_set +:= scala.io.StdIn.readLine();\n\n for (i <- 1 to n) {\n// next = string_set(string_set.length - i);\n next = string_set(i - 1)\n\n var (l, r) = (-1, next.length);\n while (Character.isAlphabetic(next(l + 1)))\n l += 1;\n while (Character.isDigit(next(r - 1)))\n r -= 1;\n \n if (r - l == 1)\n print(\"R\", next.substring(r), \"C\", func.fromTE(next.substring(0, r)), \"\\n\")\n else\n print(func.toTE(next.substring(r).toInt), next.substring(l + 1, r - 1), \"\\n\")\n }\n}\n\nobject func {\n val alphabet = Array(\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\",\n \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\");\n\n def toTE(source: Int): String = {\n var inter = source\n var target = \"\"\n while (inter > 0) {\n target = alphabet((inter - 1) % 26) + target;\n inter = math.floor((inter - 1) / 26).toInt;\n }\n target\n }\n\n\n def fromTE(source: String): Int = source.toSeq.foldLeft(0){\n var i = 0;\n val sLength = source.length;\n\n (res, symb) => {\n i += 1;\n res + (Char.char2int(symb) - 'A'.toInt + 1) * math.pow(26, sLength - i).toInt }\n }\n}\n"}, {"source_code": "\n\nobject Main extends App {\n val n = scala.io.StdIn.readLine().toInt;\n// val string_set: Array[String] = (1 to n).map((_) => scala.io.StdIn.readLine()).toArray;\n var next: String = \"\";\n\n var string_set: Array[String] = Array();\n for (i <- 1 to n)\n string_set +:= scala.io.StdIn.readLine();\n\n for (i <- 1 to n) {\n next = string_set(i - 1);\n var (l, r) = (-1, next.length);\n while (Character.isAlphabetic(next(l + 1)))\n l += 1;\n while (Character.isDigit(next(r - 1)))\n r -= 1;\n if (r - l == 1) {\n printf(\"R%sC%d\\n\", next.substring(r), func.fromTE(next.substring(0, r)));\n }\n else {\n printf(\"%s%s\\n\", func.toTE(next.substring(r).toInt), next.substring(l + 1, r - 1))\n \n }\n \n }\n}\nobject func {\n val alphabet = Array(\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\",\n \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\");\n\n def toTE(source: Int): String = {\n var inter = source\n var target = \"\"\n while (inter > 0) {\n target = alphabet((inter - 1) % 26) + target;\n inter = math.floor((inter - 1) / 26).toInt;\n }\n target\n }\n\n\n def fromTE(source: String): Int = source.toSeq.foldLeft(0){\n var i = 0;\n val sLength = source.length;\n\n (res, symb) => {\n i += 1;\n res + (Char.char2int(symb) - 'A'.toInt + 1) * math.pow(26, sLength - i).toInt }\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject _1B {\n def main (args: Array[String]) = {\n var num = readInt\n var coords = new Array[String](num);\n for (i <- 0 until num) {\n coords(i) = readLine\n }\n \n for (coord <- coords)\n println(convert(coord))\n }\n \n def convert (coord: String) = {\n var col = \"\"\n var row = \"\"\n if (coord.matches(\"R[1-9]+C[1-9]+\")) {\n var idx = coord.indexWhere { x => x == 'C' }\n row = coord.slice(1, idx)\n col = coord.slice(idx+1, coord.length)\n col = toABC(col)\n \n col+row\n }\n else {\n var idx = coord.indexWhere { x => x.isDigit }\n col = coord.slice(0, idx)\n row = coord.slice(idx, coord.length)\n col = toDigit(col)\n \n \"R\"+row+\"C\"+col\n \n }\n \n }\n \n def toABC(digit: String) = {\n var d = digit.toInt\n var r = 0\n var abc = \"\"\n var alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \n while (d / 26 > 0) {\n r = d % 26\n abc = alphabet.charAt(r-1) + abc\n d = d / 26\n }\n abc = alphabet.charAt(d-1) + abc\n \n abc\n }\n \n def toDigit(abc: String) = {\n var d = 0\n var f = 1\n for ( i <- 1 to abc.length) {\n d += (abc.charAt(abc.length-i) - 'A' + 1) * f\n f *= 26\n }\n d.toString\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject _1B {\n def main (args: Array[String]) = {\n var num = readInt\n var coords = new Array[String](num);\n for (i <- 0 until num) {\n coords(i) = readLine\n }\n \n for (coord <- coords)\n println(convert(coord))\n }\n \n def convert (coord: String) = {\n var col = \"\"\n var row = \"\"\n if (coord.matches(\"R[0-9]+C[0-9]+\")) {\n var idx = coord.indexWhere { x => x == 'C' }\n row = coord.slice(1, idx)\n col = coord.slice(idx+1, coord.length)\n col = toABC(col)\n \n col+row\n }\n else {\n var idx = coord.indexWhere { x => x.isDigit }\n col = coord.slice(0, idx)\n row = coord.slice(idx, coord.length)\n col = toDigit(col)\n \n \"R\"+row+\"C\"+col\n \n }\n \n }\n \n def toABC(digit: String) = {\n var d = digit.toInt\n var r = 0\n var abc = \"\"\n var alphabet = \"ZABCDEFGHIJKLMNOPQRSTUVWXY\"\n \n while (d / 26 > 0) {\n r = d % 26\n abc = alphabet.charAt(r) + abc\n d = d / 26\n }\n if (r > 0) \n abc = alphabet.charAt(d) + abc\n \n abc\n }\n \n def toDigit(abc: String) = {\n var d = 0\n var f = 1\n for ( i <- 1 to abc.length) {\n d += (abc.charAt(abc.length-i) - 'A' + 1) * f\n f *= 26\n }\n d.toString\n }\n}"}, {"source_code": "import scala.annotation.tailrec\nobject X extends App {\n val inp = scala.io.StdIn.readLine()\n val lines = inp.toInt\n\n case class Stand(val row: Int, val col: Int);\n\n val rowColToStand = (rowCol: String) => {\n val rCRegex = \"R(.*)C(.*)\".r\n rCRegex.findFirstMatchIn(rowCol) match {\n case None => Stand(0, 0)\n case Some(value) => Stand(value.group(1).toInt, value.group(2).toInt)\n }\n }\n\n val standToRowCol = (stand: Stand) => {\n stand match {\n case Stand(row, col) => s\"R${row}C${col}\"\n }\n }\n\n val baseToDec = (baseRep: String, baseMap: Map[String, Int]) => {\n val baseSize = baseMap.size - 1\n\n baseRep.foldLeft(0)((acc, currChar) =>\n (acc + baseMap(currChar.toString())) * baseSize\n ) / baseSize\n }\n\n @tailrec\n def decToBase(\n num: Int,\n inverseBaseMap: Map[Int, String],\n acc: List[String] = List()\n ): String = {\n val baseSize = inverseBaseMap.size - 1\n\n if (num == 0) {\n acc.mkString(\"\")\n } else {\n val rem = num % baseSize\n val actualRem = if (rem == 0) baseSize else rem\n val diff = (num - actualRem) / baseSize;\n decToBase(diff, inverseBaseMap, inverseBaseMap(actualRem) +: acc)\n }\n }\n\n val alphaBase = \"_ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n .split(\"\")\n .foldLeft(Map[String, Int]())((accMap, currChar) =>\n accMap + (currChar.toString() -> accMap.size)\n )\n val inverseAlphaBase = alphaBase.map(_.swap)\n\n val alphaToStand = (alphaRep: String) => {\n val alphaRegex = \"([A-Z]*)([0-9]*)\".r\n alphaRegex.findFirstMatchIn(alphaRep) match {\n case None => Stand(0, 0)\n case Some(value) => {\n Stand(value.group(2).toInt, baseToDec(value.group(1), alphaBase))\n }\n }\n }\n\n val standToAlpha = (stand: Stand) =>\n s\"${decToBase(stand.col, inverseAlphaBase)}${stand.row}\"\n\n val alphaToRowCol = (alpha: String) => standToRowCol(alphaToStand(alpha))\n val rowColToAlpha = (rowCol: String) => standToAlpha(rowColToStand(rowCol))\n\n (0 until lines).foreach(l => {\n val line = scala.io.StdIn.readLine()\n\n try {\n val rCRegex = \"^R(.*)C(.*)$\".r\n\n val otherRep = rCRegex.findFirstMatchIn(line) match {\n case None => alphaToRowCol(line)\n case Some(value) => rowColToAlpha(line)\n }\n println(otherRep)\n } catch {\n case e: Any => println(line)\n }\n\n })\n}\n"}, {"source_code": "import scala.annotation.tailrec\nobject X extends App {\n val inp = scala.io.StdIn.readLine()\n val lines = inp.toInt\n\n case class Stand(val row: Int, val col: Int);\n\n val rowColToStand = (rowCol: String) => {\n val rCRegex = \"R(.*)C(.*)\".r\n rCRegex.findFirstMatchIn(rowCol) match {\n case None => Stand(0, 0)\n case Some(value) => Stand(value.group(1).toInt, value.group(2).toInt)\n }\n }\n\n val standToRowCol = (stand: Stand) => {\n stand match {\n case Stand(row, col) => s\"R${row}C${col}\"\n }\n }\n\n val baseToDec = (baseRep: String, baseMap: Map[String, Int]) => {\n val baseSize = baseMap.size - 1\n\n baseRep.foldLeft(0)((acc, currChar) =>\n (acc + baseMap(currChar.toString())) * baseSize\n ) / baseSize\n }\n\n @tailrec\n def decToBase(\n num: Int,\n inverseBaseMap: Map[Int, String],\n acc: List[String] = List()\n ): String = {\n val baseSize = inverseBaseMap.size - 1\n\n if (num == 0) {\n acc.mkString(\"\")\n } else {\n val rem = num % baseSize\n val actualRem = if (rem == 0) baseSize else rem\n val diff = (num - actualRem) / baseSize;\n decToBase(diff, inverseBaseMap, inverseBaseMap(actualRem) +: acc)\n }\n }\n\n val alphaBase = \"_ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n .split(\"\")\n .foldLeft(Map[String, Int]())((accMap, currChar) =>\n accMap + (currChar.toString() -> accMap.size)\n )\n val inverseAlphaBase = alphaBase.map(_.swap)\n\n val alphaToStand = (alphaRep: String) => {\n val alphaRegex = \"([A-Z]*)([0-9]*)\".r\n alphaRegex.findFirstMatchIn(alphaRep) match {\n case None => Stand(0, 0)\n case Some(value) => {\n Stand(value.group(2).toInt, baseToDec(value.group(1), alphaBase))\n }\n }\n }\n\n val standToAlpha = (stand: Stand) =>\n s\"${decToBase(stand.col, inverseAlphaBase)}${stand.row}\"\n\n val alphaToRowCol = (alpha: String) => standToRowCol(alphaToStand(alpha))\n val rowColToAlpha = (rowCol: String) => standToAlpha(rowColToStand(rowCol))\n\n (0 until lines).foreach(l => {\n val line = scala.io.StdIn.readLine()\n try {\n val rCRegex = \"^R(.+)C(.+)$\".r\n\n val otherRep = rCRegex.findFirstMatchIn(line) match {\n case None => alphaToRowCol(line)\n case Some(value) => rowColToAlpha(line)\n }\n println(otherRep)\n } catch {\n case e: Any => println(line)\n }\n\n })\n}\n"}, {"source_code": "import scala.annotation.tailrec\nobject X extends App {\n val inp = scala.io.StdIn.readLine()\n val lines = inp.toInt\n\n case class Stand(val row: Int, val col: Int);\n\n val rowColToStand = (rowCol: String) => {\n val rCRegex = \"R(.*)C(.*)\".r\n rCRegex.findFirstMatchIn(rowCol) match {\n case None => Stand(0, 0)\n case Some(value) => Stand(value.group(1).toInt, value.group(2).toInt)\n }\n }\n\n val standToRowCol = (stand: Stand) => {\n stand match {\n case Stand(row, col) => s\"R${row}C${col}\"\n }\n }\n\n val baseToDec = (baseRep: String, baseMap: Map[String, Int]) => {\n val baseSize = baseMap.size - 1\n\n baseRep.foldLeft(0)((acc, currChar) =>\n (acc + baseMap(currChar.toString())) * baseSize\n ) / baseSize\n }\n\n @tailrec\n def decToBase(\n num: Int,\n inverseBaseMap: Map[Int, String],\n acc: List[String] = List()\n ): String = {\n val baseSize = inverseBaseMap.size - 1\n\n if (num == 0) {\n acc.mkString(\"\")\n } else {\n val rem = num % baseSize\n val actualRem = if (rem == 0) baseSize else rem\n val diff = (num - rem) / baseSize;\n decToBase(diff, inverseBaseMap, inverseBaseMap(actualRem) +: acc)\n }\n }\n\n val alphaBase = \"_ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n .split(\"\")\n .foldLeft(Map[String, Int]())((accMap, currChar) =>\n accMap + (currChar.toString() -> accMap.size)\n )\n val inverseAlphaBase = alphaBase.map(_.swap)\n\n val alphaToStand = (alphaRep: String) => {\n val alphaRegex = \"([A-Z]*)([0-9]*)\".r\n alphaRegex.findFirstMatchIn(alphaRep) match {\n case None => Stand(0, 0)\n case Some(value) => {\n Stand(value.group(2).toInt, baseToDec(value.group(1), alphaBase))\n }\n }\n }\n\n val standToAlpha = (stand: Stand) =>\n s\"${decToBase(stand.col, inverseAlphaBase)}${stand.row}\"\n\n val alphaToRowCol = (alpha: String) => standToRowCol(alphaToStand(alpha))\n val rowColToAlpha = (rowCol: String) => standToAlpha(rowColToStand(rowCol))\n\n (0 until lines).foreach(l => {\n try {\n val line = scala.io.StdIn.readLine()\n\n val rCRegex = \"^R(.*)C(.*)$\".r\n\n val otherRep = rCRegex.findFirstMatchIn(line) match {\n case None => alphaToRowCol(line)\n case Some(value) => rowColToAlpha(line)\n }\n println(otherRep)\n } catch {\n case e: Any =>\n }\n\n })\n}\n"}, {"source_code": "import scala.annotation.tailrec\nobject X extends App {\n val inp = scala.io.StdIn.readLine()\n val lines = inp.toInt\n\n case class Stand(val row: Int, val col: Int);\n\n val rowColToStand = (rowCol: String) => {\n val rCRegex = \"R(.*)C(.*)\".r\n rCRegex.findFirstMatchIn(rowCol) match {\n case None => Stand(0, 0)\n case Some(value) => Stand(value.group(1).toInt, value.group(2).toInt)\n }\n }\n\n val standToRowCol = (stand: Stand) => {\n stand match {\n case Stand(row, col) => s\"R${row}C${col}\"\n }\n }\n\n val baseToDec = (baseRep: String, baseMap: Map[String, Int]) => {\n val baseSize = baseMap.size - 1\n\n baseRep.foldLeft(0)((acc, currChar) =>\n (acc + baseMap(currChar.toString())) * baseSize\n ) / baseSize\n }\n\n @tailrec\n def decToBase(\n num: Int,\n inverseBaseMap: Map[Int, String],\n acc: List[String] = List()\n ): String = {\n val baseSize = inverseBaseMap.size - 1\n\n if (num == 0) {\n acc.mkString(\"\")\n } else {\n val rem = num % baseSize\n val actualRem = if (rem == 0) baseSize else rem\n val diff = (num - actualRem) / baseSize;\n decToBase(diff, inverseBaseMap, inverseBaseMap(actualRem) +: acc)\n }\n }\n\n val alphaBase = \"_ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n .split(\"\")\n .foldLeft(Map[String, Int]())((accMap, currChar) =>\n accMap + (currChar.toString() -> accMap.size)\n )\n val inverseAlphaBase = alphaBase.map(_.swap)\n\n val alphaToStand = (alphaRep: String) => {\n val alphaRegex = \"([A-Z]*)([0-9]*)\".r\n alphaRegex.findFirstMatchIn(alphaRep) match {\n case None => Stand(0, 0)\n case Some(value) => {\n Stand(value.group(2).toInt, baseToDec(value.group(1), alphaBase))\n }\n }\n }\n\n val standToAlpha = (stand: Stand) =>\n s\"${decToBase(stand.col, inverseAlphaBase)}${stand.row}\"\n\n val alphaToRowCol = (alpha: String) => standToRowCol(alphaToStand(alpha))\n val rowColToAlpha = (rowCol: String) => standToAlpha(rowColToStand(rowCol))\n\n (0 until lines).foreach(l => {\n try {\n val line = scala.io.StdIn.readLine()\n\n val rCRegex = \"^R(.*)C(.*)$\".r\n\n val otherRep = rCRegex.findFirstMatchIn(line) match {\n case None => alphaToRowCol(line)\n case Some(value) => rowColToAlpha(line)\n }\n println(otherRep)\n } catch {\n case e: Any =>\n }\n\n })\n}\n"}, {"source_code": "import scala.util.matching.Regex\n\n\nobject Main extends App {\n\n val ground = 'A'.toInt - 1\n val step = 'Z'.toInt - ground\n\n def letterToDigit(value: String): Int = {\n if (value.length > 1) {\n ((value.charAt(0).toInt - ground) * Math.pow(step, value.length -1)).toInt + letterToDigit(value.substring(1))\n } else {\n value.charAt(0).toInt - ground\n }\n }\n\n def digitToLetter(value: Int): String = {\n if (value <= step) {\n (value + ground).toChar.toString\n } else {\n digitToLetter(value / step) + ((value % step) + ground).toChar.toString\n }\n }\n\n def translate(value: String) = {\n if (value.matches(\"R\\\\d{1,}C\\\\d{1,}\")) {\n val cIndex = value.indexOf(\"C\")\n val row = value.substring(1, cIndex)\n val column = value.substring(cIndex + 1).toInt\n digitToLetter(column) + row\n }\n else {\n val pattern = new Regex(\"[A-Z]*\")\n val column = pattern.findFirstIn(value).get\n val row = value.substring(column.size)\n \"R\" + row + \"C\" + letterToDigit(column)\n }\n }\n\n\n val numOfRounds = Console.readInt\n if (numOfRounds <= 0 || numOfRounds >= 1e5f) {\n throw new Exception(\"Illegal value\")\n }\n\n for (i <- 1 to numOfRounds) {\n println(translate(Console.readLine()))\n }\n\n}"}, {"source_code": "import scala.util.matching.Regex\n\n\nobject Main extends App {\n\n val ground = 'A'.toInt - 1\n val step = 'Z'.toInt - ground\n\n def letterToDigit(value: String): Int = {\n if (value.length > 1) {\n ((value.charAt(0).toInt - ground) * step) + letterToDigit(value.substring(1))\n } else {\n value.charAt(0).toInt - ground\n }\n }\n\n def digitToLetter(value: Int): String = {\n if (value <= step) {\n (value + ground).toChar.toString\n } else {\n digitToLetter(value / step) + ((value % step) + ground).toChar.toString\n }\n }\n\n def translate(value: String) = {\n if (value.matches(\"R\\\\d{1,}C\\\\d{1,}\")) {\n val cIndex = value.indexOf(\"C\")\n val row = value.substring(1, cIndex)\n val column = value.substring(cIndex + 1).toInt\n digitToLetter(column) + row\n }\n else {\n val pattern = new Regex(\"[A-Z]*\")\n val column = pattern.findFirstIn(value).get\n val row = value.substring(column.size)\n \"R\" + row + \"C\" + letterToDigit(column)\n }\n }\n\n\n val numOfRounds = Console.readInt\n if (numOfRounds <= 0 || numOfRounds >= 1e5f) {\n throw new Exception(\"Illegal value\")\n }\n\n for (i <- 1 to numOfRounds) {\n println(translate(Console.readLine()))\n }\n\n}"}, {"source_code": "import scala.util.matching.Regex\n\nobject SpreadSheet{\n val RowCollumn = new Regex(\"R[0-9]+C[0-9]+\")\n\n def main(args: Array[String]): Unit = {\n val n = readln.toInt\n (1 to n)\n .iterator\n .map( _ =>\n readln\n ).map( string =>\n if(isRowCollumn(string)){\n rc2classic(string)\n } else {\n classic2rc(string)\n }\n ).foreach(println)\n }\n\n def isRowCollumn = corresponds2patter(RowCollumn) _\n\n def rc2classic(s: String): String = {\n val rc = s.drop(1).split(\"C\").map(_.toInt)\n val (row,collumn) = (rc(0),rc(1))\n s\"${int2Collumn(collumn,\"\")}$row\"\n }\n\n def classic2rc(s: String):String = {\n val collumn = s.takeWhile(_.isLetter)\n val row = s.dropWhile(_.isLetter).toInt\n s\"R${row}C${collumn2int(collumn,0)}\"\n }\n\n def int2Collumn(i:Int,s: String):String = i match {\n case 0 => s\n case x =>\n int2Collumn(x / 26, s\"${(ordOfA + (x % 26) -1).toChar}$s\")\n }\n\n def collumn2int(s:String,i:Int): Int =\n if (s.isEmpty) i else {\n collumn2int(s.drop(1),i*26 + (s.charAt(0).toInt - ordOfA+1))\n }\n\n\n def ordOfa = 'a'.toInt\n def ordOfz = 'z'.toInt\n def ordOfA = 'A'.toInt\n def ordOfZ = 'Z'.toInt\n\n def char2Int(char: Char) = char.toInt\n def int2char(number: Int) = number.toChar\n\n def readln: String = scala.io.StdIn.readLine()\n\n def corresponds2patter(pattern: Regex)(string: String): Boolean =\n pattern.findFirstIn(string).nonEmpty\n}\n"}, {"source_code": "object Main extends App {\n def rctoletter(x : Long) : String = {\n var result : String = \"\"\n var number = x\n while(number > 0)\n {\n val a = number % 26\n number /= 26\n result = ('A' + a - 1).toChar + result\n }\n result\n }\n def lettertorc(x : String) : Long = {\n var result : Long = 0\n for(c <- x)\n result = (result) * 26 + (c-'A')+1\n result\n }\n val n = readLine().toInt\n\n val numRegexp = \"\"\"R(\\d+)C(\\d+)\"\"\".r\n val letRegexp = \"\"\"([A-Z]+)(\\d+)\"\"\".r\n\n for (i <- 1 to n)\n {\n val in : String = readLine()\n\n in match\n {\n case numRegexp(rnum, cnum) => {\n println(rctoletter(cnum.toLong)+rnum)\n }\n case letRegexp(cstr, rnum) => {\n val cnum = lettertorc(cstr)\n println(\"R\"+rnum+\"C\"+cnum)\n }\n }\n }\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer\n\n\nobject Spreadsheets {\n\n def main(args: Array[String]) = {\n val n = scala.io.StdIn.readLine().toInt\n for (_ <- 0 until n) {\n val line = scala.io.StdIn.readLine()\n var is_charcters = true\n val values = new ListBuffer[Int]\n var i = 0\n while (i < line.length) {\n var value = 0\n if (is_charcters) {\n while (i < line.length && line(i).isUpper) {\n value = value * 26 + line(i) - 'A' + 1\n i += 1\n }\n } else {\n while (i < line.length && line(i).isDigit) {\n value = value * 10 + line(i) - '0'\n i += 1\n }\n }\n is_charcters = !is_charcters\n values += value\n }\n if (values.length == 4) {\n var (r, c) = (values(1), values(3))\n val col = new StringBuilder\n while (c > 0) {\n col.append( ('A' + ((c + 25) % 26)).toChar )\n c /= 26\n }\n val str = col.reverse.toString()\n printf(\"%s%d\\n\", str, r)\n } else {\n printf(\"R%dC%d\\n\", values.reverse:_*)\n\n }\n }\n }\n}\n\n"}, {"source_code": "import java.util.Scanner\n\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n for (i <- 0 until n) {\n val rcPattern = \"R(\\\\d+)C(\\\\d+)\".r\n val namePattern = \"([A-Z]+)(\\\\d+)\".r\n sc.next() match {\n case rcPattern(r, c) => println(rc2Name(r.toInt, c.toInt))\n case namePattern(c, r) => println(name2RC(c, r.toInt))\n case _ =>\n }\n }\n }\n\n def rc2Name(r: Int, c: Int): String = {\n var cTmp = c\n var cName = \"\"\n do {\n cName = (cTmp % 26 + 'A'.toInt - 1).toChar.toString() + cName\n cTmp /= 26\n } while(cTmp != 0)\n return cName + r\n }\n\n def name2RC(c: String, r: Int): String = {\n val length = c.length()\n var cVal = 0\n for (i <- 0 until length) {\n cVal += (c.charAt(i) - 'A'.toInt + 1) * math.pow(26, length - 1 - i).asInstanceOf[Int]\n }\n return \"R\" + r + \"C\" + cVal\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n for (i <- 0 until n) {\n val rcPattern = \"R(\\\\d+)C(\\\\d+)\".r\n val namePattern = \"([A-Z]+)(\\\\d+)\".r\n sc.next() match {\n case rcPattern(r, c) => println(rc2Name(r.toInt, c.toInt))\n case namePattern(c, r) => println(name2RC(c, r.toInt))\n case _ =>\n }\n }\n }\n\n def rc2Name(r: Int, c: Int): String = {\n var cTmp = c\n var cName = \"\"\n do {\n val remainder = cTmp % 26\n if (remainder == 0) {\n cName = 'Z' + cName\n } else {\n cName = (remainder + 'A'.toInt - 1).toChar.toString() + cName\n }\n cTmp /= 26\n } while (cTmp != 0)\n return cName + r\n }\n\n def name2RC(c: String, r: Int): String = {\n val length = c.length()\n var cVal = 0\n for (i <- 0 until length) {\n cVal += (c.charAt(i) - 'A'.toInt + 1) * math.pow(26, length - 1 - i).asInstanceOf[Int]\n }\n return \"R\" + r + \"C\" + cVal\n }\n}"}], "src_uid": "910c0e650d48af22fa51ab05e8123709"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val Array(x, y) = in.next().split(\" \").map(_.toInt)\n val res = (2 to n).foldLeft((x, x, y, y)) {\n case((xmax, xmin, ymax, ymin), _) =>\n val Array(x, y) = in.next().split(\" \").map(_.toInt)\n (Math.max(xmax, x), Math.min(xmin, x), Math.max(ymax, y), Math.min(ymin, y))\n }\n val a = Math.max(res._1 - res._2, res._3 - res._4).toLong\n println(a * a)\n}", "positive_code": [{"source_code": "import java.util._\nimport java.io._\nimport java.util\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n var minX = Int.MaxValue\n var minY = Int.MaxValue\n var maxX = Int.MinValue\n var maxY = Int.MinValue\n for (i <- 0 until n) {\n val x = nextInt\n minX = Math.min(minX, x)\n maxX = Math.max(maxX, x)\n val y = nextInt\n minY = Math.min(minY, y)\n maxY = Math.max(maxY, y)\n }\n var sq1: Long = Math.abs(minX - maxX).toLong\n sq1 *= sq1;\n var sq2: Long = Math.abs(minY - maxY).toLong\n sq2 *= sq2\n out.println(Math.max(sq1, sq2))\n\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "negative_code": [], "src_uid": "016e00b2b960be792d4ec7fcfb7976e2"} {"source_code": "object _1245A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(implicit io: IO): io.type = {\n repeat {\n val a, b = io.read[Long]\n io.writeLine(if (gcd(a, b) == 1L) \"Finite\" else \"Infinite\")\n }\n }\n\n @tailrec\n final def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a%b)\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(implicit io: IO): io.type\n def repeat(f: => Unit)(implicit io: IO): io.type = {Utils.repeat(io.read[Int])(f); io}\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "import java.util\n\nimport scala.collection.mutable\nimport scala.io.StdIn._\n\nobject Main extends App {\n\n def nod(a: Int, b: Int) = {\n var x = a\n var y = b\n while (x != 0 && y != 0) {\n if (x > y)\n x = x % y\n else\n y = y % x\n }\n x+y\n }\n\n val n = readLine().toInt\n\n\n for(i <- 0 to n-1) {\n val Array(a, b) = readLine().split(\" \").map(_.toInt)\n\n if (a % 2 == 0) {\n if ( nod(a,b) > 1) {\n println(\"Infinite\")\n } else {\n println(\"Finite\")\n }\n } else {\n //if (b % a == 0 && a != 1) {\n if ( nod(a,b) > 1) {\n println(\"Infinite\")\n } else {\n println(\"Finite\")\n }\n }\n\n }\n\n/*\n\n for(i <- 0 to n-1) {\n val Array(a, b) = readLine().split(\" \").map(_.toInt)\n\n var st = \"w\"\n for (j <- 1 to (a max b)*12) {\n if ( (j >= a) && (j-a >= 0) && (st.charAt(j-a) == 'w') ) {\n st += 'w'\n } else if ( (j >= b) && (j-b >= 0) && (st.charAt(j-b) == 'w') ) {\n st += 'w'\n } else {\n st += 'b'\n }\n\n }\n\n print(a,b,st)\n if (st.charAt(st.length-1) == 'b' || st.charAt(st.length-2) == 'b')\n println(\"Infinite\")\n else\n println(\"Finite\")\n }\n*/\n\n}"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n\n def gcd(a: Int, b: Int): Int = {\n if (b == 0) a\n else gcd(b, a % b)\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val a, b = ni()\n if (gcd(a, b) == 1) {\n out.println(\"Finite\")\n } else {\n out.println(\"Infinite\")\n }\n }\n }\n}"}], "negative_code": [{"source_code": "import java.util\n\nimport scala.collection.mutable\nimport scala.io.StdIn._\n\nobject Main extends App {\n\n def nod(a: Int, b: Int) = {\n var x = a\n var y = b\n while (x != 0 && y != 0) {\n if (x > y)\n x = x % y\n else\n y = y % x\n }\n x+y\n }\n\n val n = readLine().toInt\n\n\n for(i <- 0 to n-1) {\n val Array(a, b) = readLine().split(\" \").map(_.toInt)\n\n if (a % 2 == 0) {\n if ( nod(a,b) > 1) {\n println(\"Infinite\")\n } else {\n println(\"Finite\")\n }\n } else {\n if (b % a == 0 && a != 1) {\n println(\"Infinite\")\n } else {\n println(\"Finite\")\n }\n }\n\n }\n\n/*\n\n for(i <- 0 to n-1) {\n val Array(a, b) = readLine().split(\" \").map(_.toInt)\n\n var st = \"w\"\n for (j <- 1 to (a max b)*12) {\n if ( (j >= a) && (j-a >= 0) && (st.charAt(j-a) == 'w') ) {\n st += 'w'\n } else if ( (j >= b) && (j-b >= 0) && (st.charAt(j-b) == 'w') ) {\n st += 'w'\n } else {\n st += 'b'\n }\n\n }\n\n print(a,b,st)\n if (st.charAt(st.length-1) == 'b' || st.charAt(st.length-2) == 'b')\n println(\"Infinite\")\n else\n println(\"Finite\")\n }\n*/\n\n}"}], "src_uid": "388450021f2f33177d905879485bb531"} {"source_code": "object DengmwSolution extends App {\n import scala.io.StdIn._\n \n val f = readInt()\n \n (0 until f).foreach { _ =>\n val t = readLong()\n \n val res = ((t max 6) + 1) / 2 * 5\n \n println(res)\n }\n}\n\t \t \t \t \t\t \t \t \t\t \t", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]) = {\n def rep[A](n: Int)(f: => A) { if (n > 0) { f; rep(n - 1)(f) } }\n\n rep(readInt) {\n var in = BigDecimal(readLine)\n in = in.max(6)\n\n //so can get only 2,4,8,10,12\n //and for < 6 we want 6 slices either way\n in += (if (in % 2 != 0) 1 else 0)\n println((in * 2.5).toBigInt)\n }\n }\n}\n"}, {"source_code": "import java.io.PrintWriter\r\nimport java.util.Scanner\r\n\r\nobject Solution {\r\n def solve(input: Long): Long = {\r\n // a b c\r\n // 2*(a*3 + b*4 + c*5) >= input\r\n // 5*(a*3 + b*4 + c*5) = min\r\n // so you want to closest amount to input\r\n // actually we want to get exactly input or input * 2 most likely?\r\n\r\n // val covered: Array[Boolean] = Array.fill(30000)(false)\r\n // (0 to 1000).foreach { a =>\r\n // (0 to 1000).foreach { b =>\r\n // (0 to 1000).foreach { c =>\r\n // covered(a*6+b*8+c*10) = true\r\n // }\r\n // }\r\n // }\r\n //\r\n // (0 to 3000).foreach { i =>\r\n // if (!covered(i*2)) {\r\n // println(s\"not covered ${i*2}\")\r\n // }\r\n // }\r\n //\r\n // input\r\n\r\n // not covered 2\r\n // not covered 4\r\n val toCover = if (input < 6) 6 else if (input % 2 == 0) input else (input + 1)\r\n (toCover / 2) * 5\r\n }\r\n\r\n def run(test: Int, input: Scanner, output: PrintWriter): Unit = {\r\n output.println(solve(input.nextLong()))\r\n }\r\n\r\n def run(input: Scanner, output: PrintWriter): Unit = {\r\n val tests = input.nextInt()\r\n\r\n (1 to tests).foreach { test =>\r\n run(test, input, output)\r\n output.flush()\r\n }\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n run(new Scanner(System.in), new PrintWriter(System.out))\r\n }\r\n}\r\n"}, {"source_code": "import java.io.PrintWriter\r\n\r\nimport scala.collection.immutable.TreeSet\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val reader = scala.io.StdIn\r\n def readInt(): Int = reader.readLine().toInt\r\n def readLong(): Long = reader.readLine().toLong\r\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\r\n def readArrayLong(): Array[Long] = reader.readLine().split(\" \").map(_.toLong)\r\n def readString(): String = reader.readLine()\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n\r\n def solve(t: Int = 0): Unit = {\r\n var t = readInt()\r\n while (t > 0) {\r\n var n = readLong()\r\n var rs = n / 10 * 25\r\n n = n % 10\r\n\r\n if (n > 0 && rs > 0) {\r\n if (n <= 2)\r\n rs = rs - 25 + 30\r\n else if (n <= 4)\r\n rs = rs - 25 + 35\r\n else if (n <= 6)\r\n rs += 15\r\n else if (n <= 8)\r\n rs += 20\r\n else if (n <= 10)\r\n rs += 25\r\n } else if (n > 8) rs = 25\r\n else if (n > 6) rs = 20\r\n else if (n > 0) rs = 15\r\n\r\n\r\n println(rs)\r\n t -= 1\r\n }\r\n\r\n }\r\n\r\n def main(args: Array[String]) {\r\n //multiTest(solve)\r\n solve()\r\n }\r\n}"}, {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readLong()\r\n\r\n val ans = ((n max 6) + 1) / 2 * 5\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "import java.io.PrintWriter\r\n\r\nimport scala.collection.immutable.TreeSet\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val reader = scala.io.StdIn\r\n def readInt(): Int = reader.readLine().toInt\r\n def readLong(): Long = reader.readLine().toLong\r\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\r\n def readArrayLong(): Array[Long] = reader.readLine().split(\" \").map(_.toLong)\r\n def readString(): String = reader.readLine()\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n\r\n def solve(t: Int = 0): Unit = {\r\n var t = readInt()\r\n while (t > 0) {\r\n var n = readLong()\r\n var rs = n / 10 * 25\r\n n = n % 10\r\n\r\n if (n > 0) {\r\n if (n <= 2)\r\n rs = rs - 25 + 30\r\n else if (n <= 4)\r\n rs = rs - 25 + 35\r\n else if (n <= 6)\r\n rs += 15\r\n else if (n <= 8)\r\n rs += 20\r\n else if (n <= 10)\r\n rs += 25\r\n }\r\n\r\n\r\n println(rs)\r\n t -= 1\r\n }\r\n\r\n }\r\n\r\n def main(args: Array[String]) {\r\n //multiTest(solve)\r\n solve()\r\n }\r\n}"}, {"source_code": "import java.io.PrintWriter\r\n\r\nimport scala.collection.immutable.TreeSet\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val reader = scala.io.StdIn\r\n def readInt(): Int = reader.readLine().toInt\r\n def readLong(): Long = reader.readLine().toLong\r\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\r\n def readArrayLong(): Array[Long] = reader.readLine().split(\" \").map(_.toLong)\r\n def readString(): String = reader.readLine()\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n\r\n def solve(t: Int = 0): Unit = {\r\n var t = readInt()\r\n while (t > 0) {\r\n var n = readLong()\r\n var rs = n / 10 * 25\r\n n = n % 10\r\n\r\n if (n > 0) {\r\n if (n == 2)\r\n rs = rs - 25 + 30\r\n else if (n == 4)\r\n rs = rs - 25 + 35\r\n else if (n <= 6)\r\n rs += 15\r\n else if (n <= 8)\r\n rs += 20\r\n else if (n <= 10)\r\n rs += 25\r\n }\r\n\r\n\r\n println(rs)\r\n t -= 1\r\n }\r\n\r\n }\r\n\r\n def main(args: Array[String]) {\r\n //multiTest(solve)\r\n solve()\r\n }\r\n}"}, {"source_code": "import java.io.PrintWriter\r\n\r\nimport scala.collection.immutable.TreeSet\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val reader = scala.io.StdIn\r\n def readInt(): Int = reader.readLine().toInt\r\n def readLong(): Long = reader.readLine().toLong\r\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\r\n def readArrayLong(): Array[Long] = reader.readLine().split(\" \").map(_.toLong)\r\n def readString(): String = reader.readLine()\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n\r\n def solve(t: Int = 0): Unit = {\r\n var t = readInt()\r\n while (t > 0) {\r\n var n = readLong()\r\n var rs = n / 10 * 25\r\n n = n % 10\r\n\r\n if (n > 0) {\r\n if (n == 2)\r\n rs = rs - 25 + 30\r\n else if (n == 4)\r\n rs = rs - 25 + 35\r\n else if (n <= 6)\r\n rs += 15\r\n else if (n <= 6)\r\n rs += 20\r\n else if (n <= 10)\r\n rs += 25\r\n }\r\n\r\n\r\n println(rs)\r\n t -= 1\r\n }\r\n\r\n }\r\n\r\n def main(args: Array[String]) {\r\n //multiTest(solve)\r\n solve()\r\n }\r\n}"}, {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readLong()\r\n\r\n val ans = (n max 6) / 2 * 5\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readLong()\r\n\r\n val ans = ((n + 9) / 10 * 25) min ((n + 7) / 8 * 20) min ((n + 5) / 6 * 15)\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "src_uid": "3e27f1c06a263760f5b53c3afe4bf7ee"} {"source_code": "\nimport scala.io.StdIn.readLine\n\nobject MagicPowder {\n\n def readInts(): Array[Int] = {\n readLine().split(\"\\\\s+\").map(s => s.toInt)\n }\n\n case class IngStep(index: Long, required: Long, lastStep: Long, remainder: Long)\n\n def getOneStepPrice(step: Long, ingStep:IngStep): Long = {\n if (step <= ingStep.lastStep)\n 0L // No need to use anything\n else\n if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {\n ingStep.required - ingStep.remainder // use is there is a reminder on this step\n } else {\n // If there is a remainder, we need 1 step less\n if (ingStep.remainder > 0) {\n (ingStep.required - ingStep.remainder) + (step - ingStep.lastStep - 1) * ingStep.required\n } else {\n // all the steps are the same\n (step - ingStep.lastStep) * ingStep.required\n }\n }\n }\n\n def getStepPrice(step: Long, ingSteps: IndexedSeq[IngStep]): Long = {\n ingSteps.foldRight(0L)((ingStep, t) => {\n t + getOneStepPrice(step, ingStep)\n })\n }\n\n def main(args: Array[String]): Unit = {\n val numberPowder = readInts()\n\n val n = numberPowder(0)\n val p = numberPowder(1)\n\n val a = readInts()\n val b = readInts()\n\n val ingSteps = a.indices\n .map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i))))\n .sortBy(m => m.lastStep) // we now have i, steps sorted from lowest\n\n var startStep = 0L //Math.max(1, ingSteps.head.lastStep)\n\n val fullPrice = getStepPrice(ingSteps.last.lastStep + 1, ingSteps) // Price to pay after everything is over\n\n var endStep = if (p >= fullPrice) ingSteps.last.lastStep + Math.round(p / fullPrice) else ingSteps.last.lastStep\n\n var stop = false\n var cookies = Math.max(startStep - 1, 0)\n\n while (!stop) {\n// println(\"Start \" + startStep + \" end \" + endStep)\n val mid = startStep + Math.round((endStep - startStep) / 2)\n\n val stepPrice = getStepPrice(mid, ingSteps)\n cookies = mid\n\n if (stepPrice < p) {\n startStep = mid // Moving higher\n } else {\n endStep = mid // Moving lower\n }\n\n if (startStep == endStep) {\n stop = true\n } else if (startStep + 1 == endStep) {\n stop = true\n cookies = if (getStepPrice(endStep, ingSteps) <= p) endStep else startStep\n }\n }\n//114, 117\n// var step = Math.max(1, ingSteps.head.lastStep - 1) // no need to wait\n// var cookies = Math.max(step - 1, 0)\n// var pRemainder = p\n\n//\n// while(!stop) {\n// val stepPrice = getStepPrice(step, ingSteps)\n//\n// if (stepPrice <= pRemainder) {\n// cookies += 1\n// step += 1\n// } else {\n// stop = true\n// }\n// }\n\n print(cookies)\n\n }\n}\n", "positive_code": [{"source_code": "\nimport scala.io.StdIn.readLine\n\nobject MagicPowder {\n\n def readInts(): Array[Int] = {\n readLine().split(\"\\\\s+\").map(s => s.toInt)\n }\n\n case class IngStep(index: Int, required: Int, lastStep: Int, remainder: Int)\n\n def getOneStepPrice(step: Int, ingStep:IngStep): Int = {\n if (step <= ingStep.lastStep)\n 0 // No need to use anything\n else\n if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {\n ingStep.required - ingStep.remainder // use remainder only if we are on this step\n } else {\n\n // If there is a remainder, we need 1 step less\n if (ingStep.remainder > 0) {\n ingStep.required - ingStep.remainder + (step - ingStep.lastStep - 1) * ingStep.required\n } else {\n // all the steps are the same\n (step - ingStep.lastStep) * ingStep.required\n }\n }\n }\n\n def getStepPrice(step: Int, ingSteps: IndexedSeq[IngStep]): Int = {\n ingSteps.foldRight(0)((ingStep, t) => {\n t + getOneStepPrice(step, ingStep)\n })\n }\n\n def main(args: Array[String]): Unit = {\n val numberPowder = readInts()\n\n val n = numberPowder(0)\n val p = numberPowder(1)\n\n val a = readInts()\n val b = readInts()\n\n val ingSteps = a.indices.map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i)))).sortBy(m => m.lastStep) // we now have i, steps sorted from lowest\n\n var step = 1\n var cookies = 0\n var pRemainder = p\n var stop = false\n\n while(!stop) {\n val stepPrice = getStepPrice(step, ingSteps)\n\n// if (stepPrice > 0) {\n// println(\"Step \" + step + \" cookies \" + cookies + \" remainder \" + pRemainder + \" price \" + stepPrice)\n// }\n\n if (stepPrice <= pRemainder) {\n cookies += 1\n step += 1\n } else {\n stop = true\n }\n }\n\n print(cookies)\n\n }\n}\n"}, {"source_code": "\nimport scala.io.StdIn.readLine\n\nobject MagicPowder {\n\n def readInts(): Array[Int] = {\n readLine().split(\"\\\\s+\").map(s => s.toInt)\n }\n\n case class IngStep(index: Int, required: Int, lastStep: Int, remainder: Int)\n\n def getOneStepPrice(step: Int, ingStep:IngStep): Int = {\n if (step <= ingStep.lastStep)\n 0 // No need to use anything\n else\n if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {\n ingStep.required - ingStep.remainder // use remainder only if we are on this step\n } else {\n\n // If there is a remainder, we need 1 step less\n if (ingStep.remainder > 0) {\n ingStep.required - ingStep.remainder + (step - ingStep.lastStep - 1) * ingStep.required\n } else {\n // all the steps are the same\n (step - ingStep.lastStep) * ingStep.required\n }\n }\n }\n\n def getStepPrice(step: Int, ingSteps: IndexedSeq[IngStep]): Int = {\n ingSteps.foldRight(0)((ingStep, t) => {\n t + getOneStepPrice(step, ingStep)\n })\n }\n\n def main(args: Array[String]): Unit = {\n val numberPowder = readInts()\n\n val n = numberPowder(0)\n val p = numberPowder(1)\n\n val a = readInts()\n val b = readInts()\n\n val ingSteps = a.indices.map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i)))).sortBy(m => m.lastStep) // we now have i, steps sorted from lowest\n\n var step = Math.max(1, ingSteps.head.lastStep - 1) // no need to wait\n var cookies = Math.max(step - 1, 0)\n var pRemainder = p\n var stop = false\n\n while(!stop) {\n val stepPrice = getStepPrice(step, ingSteps)\n\n if (stepPrice <= pRemainder) {\n cookies += 1\n step += 1\n } else {\n stop = true\n }\n }\n\n print(cookies)\n\n }\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _670D1 extends CodeForcesApp {\n override def apply(io: IO) = {\n val n, k = io[Int]\n val perCookie, has = io[Vector, Long](n)\n\n val upperBound = 10 + ((has.sum + k)/perCookie.sum)\n\n def canBake(c: Long) = (c <= upperBound) && { //can bake c cookies?\n val missing = perCookie.indices.foldLeft(0L) {\n case (needed, i) => needed + (((perCookie(i)*c) - has(i)) max 0)\n }\n missing <= k\n }\n\n io += (bitBinSearch(canBake) getOrElse 0L) max 0L\n }\n\n def bitBinSearch(f: Long => Boolean): Option[Long] = {\n var p = 0L\n var n = Long.MinValue\n var t = n >>> 1\n while (t > 0) {\n if (f(p|t)) p |= t\n if (f(n|t)) n |= t\n t >>= 1\n }\n Seq(p, n) find f\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}\n def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n var Array(n, k) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toInt)\n var b = in.next().split(' ').map(_.toInt)\n var can = true\n var answer = 0\n while (can) {\n var minus = 0\n (0 until n).foreach { i =>\n val value = b(i) - a(i)\n if (value < 0) {\n minus -= value\n b(i) = 0\n } else {\n b(i) = value\n }\n }\n if (k >= minus) {\n k -= minus\n answer += 1\n can = true\n } else {\n can = false\n }\n }\n println(answer)\n\n}\n"}], "negative_code": [{"source_code": "\nimport scala.io.StdIn.readLine\n\nobject MagicPowder {\n\n def readInts(): Array[Int] = {\n readLine().split(\"\\\\s+\").map(s => s.toInt)\n }\n\n def main(args: Array[String]): Unit = {\n val numberPowder = readInts()\n\n val n = numberPowder(0)\n\n val a = readInts()\n val b = readInts()\n\n val minSteps = a.indices.map(i => (i, Math.floorDiv(b(i), a(i)))).sortBy(_._2) // we now have i, steps sorted from lowest\n\n var pRemainder = numberPowder(1)\n var cookies = if (minSteps.isEmpty) 0 else minSteps.head._2 // Initialise from minimum steps\n\n // println(\"Minimum: \" + cookies)\n\n minSteps.indices.foreach(i => {\n val minStep = minSteps(i)\n val aI = a(minStep._1)\n val bI = b(minStep._1)\n val addOn = Math.floorMod(bI, aI)\n\n// println(\"i: \" + minStep._1 + \" value \" + aI + \" steps \" + minStep._2 + \" addon \" + addOn)\n\n val nextStep = if (i < minSteps.size - 1) minSteps(i + 1)._2 else -1\n\n if (pRemainder > 0) {\n val extraPowder = aI - addOn\n val extraStep = if ((pRemainder - extraPowder) > 0 && extraPowder > 0) {\n pRemainder -= extraPowder\n\n if (nextStep > minStep._2) {\n cookies += 1 // enough for 1 more at least\n }\n 1\n } else {\n 0\n }\n\n if (i < minSteps.size - 1 && nextStep > 0) {\n val eatHere = nextStep - (minStep._2 + extraStep) // this is how much more room we have to use powder\n // for this ingredient\n\n if (eatHere > 0) {\n val moreTooCook = Math.floorDiv(pRemainder, aI)\n pRemainder -= moreTooCook // eat as much as we can\n cookies += moreTooCook\n }\n }\n }\n })\n\n if (pRemainder >= a.sum) {\n cookies += Math.floorMod(pRemainder, a.sum) // finish the remainder\n }\n\n print(cookies)\n\n }\n}\n"}, {"source_code": "\nimport scala.io.StdIn.readLine\n\nobject MagicPowder {\n\n def readInts(): Array[Int] = {\n readLine().split(\"\\\\s+\").map(s => s.toInt)\n }\n\n case class IngStep(index: Int, required: Int, lastStep: Int, remainder: Int)\n\n def getOneStepPrice(step: Int, ingStep:IngStep): Int = {\n if (step <= ingStep.lastStep)\n 0 // No need to use anything\n else\n if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {\n ingStep.required - ingStep.remainder // use remainder only if we are on this step\n } else {\n\n // If there is a remainder, we need 1 step less\n if (ingStep.remainder > 0) {\n ingStep.required - ingStep.remainder + (step - ingStep.lastStep - 1) * ingStep.required\n } else {\n // all the steps are the same\n (step - ingStep.lastStep) * ingStep.required\n }\n }\n }\n\n def getStepPrice(step: Int, ingSteps: IndexedSeq[IngStep]): Int = {\n ingSteps.foldRight(0)((ingStep, t) => {\n t + getOneStepPrice(step, ingStep)\n })\n }\n\n def main(args: Array[String]): Unit = {\n val numberPowder = readInts()\n\n val n = numberPowder(0)\n val p = numberPowder(1)\n\n val a = readInts()\n val b = readInts()\n\n val ingSteps = a.indices.map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i)))).sortBy(m => m.lastStep) // we now have i, steps sorted from lowest\n\n var step = ingSteps.head.lastStep - 1 // no need to wait\n var cookies = Math.max(step - 1, 0)\n var pRemainder = p\n var stop = false\n\n while(!stop) {\n val stepPrice = getStepPrice(step, ingSteps)\n\n if (stepPrice <= pRemainder) {\n cookies += 1\n step += 1\n } else {\n stop = true\n }\n }\n\n print(cookies)\n\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n var Array(n, k) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toInt)\n var b = in.next().split(' ').map(_.toInt)\n var can = true\n var answer = 0\n while (can) {\n b = b.zip(a).map(i => i._1 - i._2)\n if (k > - b.filter(_ < 0).sum) {\n k -= b.filter(_ < 0).sum\n answer += 1\n b = b.map(i => Math.max(0, i))\n can = true\n } else {\n can = false\n }\n }\n println(answer)\n\n}\n"}], "src_uid": "02bb7502135afa0f3bb26527427ba9e3"} {"source_code": "import java.util.StringTokenizer\n\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Try\nimport scala.util.hashing.MurmurHash3\n\nobject D extends App {\n val INF = 1 << 30\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n\n read()\n val n = int()\n val m = int()\n\n var a = 0\n var b = 0\n\n Try {\n val linksBuilder: Array[mutable.ArrayBuilder[Int]] = Array.fill(n)(mutable.ArrayBuilder.make[Int])\n for (i <- 0 until n) { linksBuilder(i) += i }\n (1 to m).foreach { i =>\n read()\n a = int() - 1\n b = int() - 1\n linksBuilder(a) += b\n linksBuilder(b) += a\n }\n\n val links: Array[Array[Int]] = linksBuilder.map { ab =>\n val arr = ab.result()\n java.util.Arrays.sort(arr)\n arr\n }\n val linksXor: Array[Int] = links.map(_.foldLeft(0)(_ ^ _.hashCode()))\n var heads: Array[Int] = (0 until n).toArray\n def isHead(i: Int): Boolean = heads(i) == i\n\n for {\n i <- 0 until n\n if isHead(i)\n j <- links(i)\n if j > i\n if isHead(j)\n if linksXor(i) == linksXor(j)\n if links(i) sameElements links(j)\n } heads(j) = i\n\n val headLinks: Array[Array[Int]] = (0 until n).map { i =>\n if (isHead(i)) {\n links(i).filter(j => isHead(j) && (j != i))\n } else Array.empty[Int]\n } (collection.breakOut)\n\n\n var ans = Array.fill(n)(INF)\n\n @tailrec\n def dfs(cur: Int, prev: Int): Unit = {\n val prevValue = if (prev == -1) 1000000 else ans(prev)\n assert(ans(cur) == INF)\n ans(cur) = prevValue + 1\n val nextOpt = headLinks(cur).find(_ != prev)\n if (nextOpt.nonEmpty) dfs(nextOpt.get, cur)\n }\n val start = (0 until n).filter(isHead).minBy(headLinks(_).length)\n dfs(start, -1)\n\n for (i <- 0 until n) ans(i) = ans(heads(i))\n assert(ans.forall(_ != INF))\n println(\"YES\")\n println(ans.mkString(\" \"))\n }.getOrElse(println(\"NO\"))\n\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Try\nimport scala.util.hashing.MurmurHash3\n\nobject D extends App {\n val INF = 1 << 30\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n\n read()\n val n = int()\n val m = int()\n\n var a = 0\n var b = 0\n\n Try {\n val linksBuilder: Array[mutable.ArrayBuilder[Int]] = Array.fill(n)(mutable.ArrayBuilder.make[Int])\n for (i <- 0 until n) {\n linksBuilder(i) += i\n }\n (1 to m).foreach { i =>\n read()\n a = int() - 1\n b = int() - 1\n linksBuilder(a) += b\n linksBuilder(b) += a\n }\n\n val links: Array[Array[Int]] = linksBuilder.map(_.result)\n links.foreach(java.util.Arrays.sort)\n val linksXor: Array[Int] = links.map(_.reduceLeft(_ ^ _.hashCode()))\n val heads: Array[Int] = (0 until n).toArray\n def isHead(i: Int): Boolean = heads(i) == i\n\n for {\n i <- 0 until n\n if isHead(i)\n j <- links(i)\n if j > i\n if isHead(j)\n if linksXor(i) == linksXor(j)\n if links(i) sameElements links(j)\n } heads(j) = i\n\n val headLinks: Array[Array[Int]] = (0 until n).map { i =>\n if (isHead(i)) {\n links(i).filter(j => isHead(j) && (j != i))\n } else Array.empty[Int]\n } (collection.breakOut)\n\n\n val ans = Array.fill(n)(INF)\n\n @tailrec\n def dfs(cur: Int, prev: Int): Unit = {\n val prevValue = if (prev == -1) 1000000 else ans(prev)\n assert(ans(cur) == INF)\n ans(cur) = prevValue + 1\n val nextOpt = headLinks(cur).find(_ != prev)\n if (nextOpt.nonEmpty) dfs(nextOpt.get, cur)\n }\n val start = (0 until n).filter(isHead).minBy(headLinks(_).length)\n dfs(start, -1)\n\n for (i <- 0 until n) ans(i) = ans(heads(i))\n assert(ans.forall(_ != INF))\n println(\"YES\")\n println(ans.mkString(\" \"))\n }.getOrElse(println(\"NO\"))\n\n}\n"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.Builder\nimport scala.util.Try\n\nobject D extends App {\n val INF = 1 << 30\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n\n read()\n val n = int()\n val m = int()\n\n var a = 0\n var b = 0\nTry {\n var links = (0 until n).map(_ :: Nil).toArray\n\n (1 to m).foreach { i =>\n read()\n a = int() - 1\n b = int() - 1\n links(a) = b :: links(a)\n links(b) = a :: links(b)\n }\n\n links = links.map(_.sorted)\n val ma = mutable.Map.empty[List[Int], List[Int]]\n for {\n (ls, i) <- links.zipWithIndex\n } {\n val list = ma.getOrElse(ls, Nil)\n ma.update(ls, i :: list)\n }\n\n val heads = ma.values.map(_.head).toSet\n\n val mb = for {\n (ls, group) <- ma\n } yield group.head -> ls.filter(heads.contains).filterNot(_ == group.head)\n\n var ans = Array.fill(n)(INF)\n\n val start = mb.find(_._2.size == 1).get._1\n\n val stack = new mutable.Stack[(Int, Int)]()\n stack.push((start, -1))\n while (stack.nonEmpty) {\n val (cur, prev) = stack.pop()\n val prevValue = if (prev == -1) 1000000 else ans(prev)\n ans(cur) = prevValue + 1\n mb(cur).filter(_ != prev).foreach(next => stack.push((next, cur)))\n }\n\n for (head <- heads) ma(links(head)).foreach { i =>\n ans(i) = ans(head)\n }\n assert(ans.forall(_ != INF))\n println(\"YES\")\n println(ans.mkString(\" \"))\n}.getOrElse(println(\"NO\"))\n\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Try\n\nobject D extends App {\n val INF = 1 << 30\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n\n read()\n val n = int()\n val m = int()\n\n var a = 0\n var b = 0\n\n Try {\n val linksBuilder: Array[mutable.ArrayBuilder[Int]] = Array.fill(n)(mutable.ArrayBuilder.make[Int])\n for (i <- 0 until n) { linksBuilder(i) += i }\n (1 to m).foreach { i =>\n read()\n a = int() - 1\n b = int() - 1\n linksBuilder(a) += b\n linksBuilder(b) += a\n }\n\n val links: Array[Array[Int]] = linksBuilder.map { ab =>\n val arr = ab.result()\n java.util.Arrays.sort(arr)\n arr\n }\n val linksXor: Array[Int] = links.map(_.foldLeft(0)(_ ^ _.hashCode()))\n var heads: Array[Int] = (0 until n).toArray\n def isHead(i: Int): Boolean = heads(i) == i\n\n for {\n i <- 0 until n\n if isHead(i)\n j <- links(i)\n if j > i\n if isHead(j)\n if linksXor(i) == linksXor(j)\n if links(i) sameElements links(j)\n } heads(j) = i\n\n val headLinks: Array[Array[Int]] = (0 until n).map { i =>\n if (isHead(i)) {\n links(i).filter(j => isHead(j) && (j != i))\n } else Array.empty[Int]\n } (collection.breakOut)\n\n\n var ans = Array.fill(n)(INF)\n\n @tailrec\n def dfs(cur: Int, prev: Int): Unit = {\n val prevValue = if (prev == -1) 1000000 else ans(prev)\n assert(ans(cur) != INF)\n ans(cur) = prevValue + 1\n val nextOpt = headLinks(cur).find(_ != prev)\n if (nextOpt.nonEmpty) dfs(nextOpt.get, cur)\n }\n val start = (0 until n).filter(isHead).minBy(headLinks(_).length)\n dfs(start, -1)\n\n for (i <- 0 until n) ans(i) = ans(heads(i))\n assert(ans.forall(_ != INF))\n println(\"YES\")\n println(ans.mkString(\" \"))\n }.getOrElse(println(\"NO\"))\n\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.Builder\nimport scala.util.Try\n\nobject D extends App {\n val INF = 1 << 30\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n\n read()\n val n = int()\n val m = int()\n\n var a = 0\n var b = 0\nTry {\n var links = (0 until n).map(_ :: Nil).toArray\n\n (1 to m).foreach { i =>\n read()\n a = int() - 1\n b = int() - 1\n links(a) = b :: links(a)\n links(b) = a :: links(b)\n }\n\n links = links.map(_.sorted)\n val ma = mutable.Map.empty[List[Int], List[Int]]\n for {\n (ls, i) <- links.zipWithIndex\n } {\n val list = ma.getOrElse(ls, Nil)\n ma.update(ls, i :: list)\n }\n\n val heads = ma.values.map(_.head).toSet\n\n val mb = for {\n (ls, group) <- ma\n } yield group.head -> ls.filter(heads.contains).filterNot(_ == group.head)\n\n var ans = Array.fill(n)(INF)\n\n val start = mb.find(_._2.size == 1).map(_._1).getOrElse(heads.head)\n\n val stack = new mutable.Stack[(Int, Int)]()\n stack.push((start, -1))\n while (stack.nonEmpty) {\n val (cur, prev) = stack.pop()\n val prevValue = if (prev == -1) 1000000 else ans(prev)\n ans(cur) = prevValue + 1\n mb(cur).filter(_ != prev).foreach(next => stack.push((next, cur)))\n }\n\n for (head <- heads) ma(links(head)).foreach { i =>\n ans(i) = ans(head)\n }\n assert(ans.forall(_ != INF))\n println(\"YES\")\n println(ans.mkString(\" \"))\n}.getOrElse(println(\"NO\"))\n\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Try\nimport scala.util.hashing.MurmurHash3\n\nobject D extends App {\n val INF = 1 << 30\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n\n read()\n val n = int()\n val m = int()\n\n var a = 0\n var b = 0\n\n Try {\n val linksBuilder: Array[mutable.ArrayBuilder[Int]] = Array.fill(n)(mutable.ArrayBuilder.make[Int])\n for (i <- 0 until n) {\n linksBuilder(i) += i\n }\n (1 to m).foreach { i =>\n read()\n a = int() - 1\n b = int() - 1\n linksBuilder(a) += b\n linksBuilder(b) += a\n }\n\n val links: Array[Array[Int]] = linksBuilder.map(_.result)\n val linksXor: Array[Int] = links.map(_.reduceLeft(_ ^ _.hashCode()))\n val heads: Array[Int] = (0 until n).toArray\n def isHead(i: Int): Boolean = heads(i) == i\n\n val sorted: Array[Boolean] = Array.fill(n)(false)\n def ensureSorted(i: Int): Unit = if (!sorted(i)) {\n java.util.Arrays.sort(links(i))\n sorted(i) = true\n }\n\n def haveSameElements(i: Int, j: Int): Boolean = {\n ensureSorted(i)\n ensureSorted(j)\n links(i) sameElements links(j)\n }\n\n for {\n i <- 0 until n\n if isHead(i)\n j <- links(i)\n if j > i\n if isHead(j)\n if linksXor(i) == linksXor(j)\n if haveSameElements(i, j)\n } heads(j) = i\n\n val headLinks: Array[Array[Int]] = (0 until n).map { i =>\n if (isHead(i)) {\n links(i).filter(j => isHead(j) && (j != i))\n } else Array.empty[Int]\n } (collection.breakOut)\n\n\n val ans = Array.fill(n)(INF)\n\n @tailrec\n def dfs(cur: Int, prev: Int): Unit = {\n val prevValue = if (prev == -1) 1000000 else ans(prev)\n assert(ans(cur) == INF)\n ans(cur) = prevValue + 1\n val nextOpt = headLinks(cur).find(_ != prev)\n if (nextOpt.nonEmpty) dfs(nextOpt.get, cur)\n }\n val start = (0 until n).filter(isHead).minBy(headLinks(_).length)\n dfs(start, -1)\n\n for (i <- 0 until n) ans(i) = ans(heads(i))\n assert(ans.forall(_ != INF))\n println(\"YES\")\n println(ans.mkString(\" \"))\n }.getOrElse(println(\"NO\"))\n\n}\n"}], "src_uid": "bb7ecc5dbb922007bc0c25491aaa53d9"} {"source_code": "import java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.io.StdIn\n\nobject D extends App with Reader {\n read()\n val n = int()\n val links = Array.fill(n+1)(new mutable.ArrayBuffer[Int]())\n\n for (i <- 1 until n) {\n read()\n val s = int()\n val f = int()\n links(s) += f\n links(f) += s\n }\n\n read()\n val queue = Array.fill(n)(int())\n\n def isCorrect(): Boolean = {\n val visited = Array.fill(n+1)(false)\n\n if (queue(0) != 1) return false\n var checked = 1\n visited(1) = true\n\n for (i <- queue) {\n val next = links(i).filterNot(visited).toSet\n for (i <- 1 to next.size) {\n if (!next.contains(queue(checked))) return false\n visited(queue(checked)) = true\n checked += 1\n }\n }\n return true\n }\n\n println(if (isCorrect()) \"Yes\" else \"No\")\n}\n\ntrait Reader {\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(StdIn.readLine()) }\n def int() = st.nextToken().toInt\n def long() = st.nextToken().toLong\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject C extends App {\n\n case class Point(x: Int, segId: Int, isBegin: Boolean)\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val edges = Array.fill(n)(new collection.mutable.ArrayBuffer[Int]())\n (1 until n).foreach { _ =>\n val x = in.nextInt - 1\n val y = in.nextInt - 1\n edges(x) += y\n edges(y) += x\n }\n val dist = Array.fill(n)(0)\n val pred = Array.fill(n)(0)\n val q = collection.mutable.Queue[Int]()\n dist(0) = 1\n q.enqueue(0)\n while (q.nonEmpty) {\n val c = q.dequeue()\n edges(c).foreach { e =>\n if (dist(e) == 0) {\n dist(e) = dist(c) + 1\n pred(e) = c\n q.enqueue(e)\n }\n }\n }\n //dist.foreach(println)\n var lastDist = 1\n var ok = true\n val qq = collection.mutable.Queue[Int]()\n Array.fill(n)(in.nextInt).foreach { i =>\n val d = dist(i - 1)\n if (lastDist > d)\n ok = false\n lastDist = d\n\n qq.enqueue(i - 1)\n while (qq.nonEmpty && qq.front != pred(i - 1)) {\n qq.dequeue()\n }\n if (qq.isEmpty) ok = false\n }\n\n if (ok) println(\"Yes\")\n else println(\"No\")\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toInt\n }\n\n def nextLong: Double = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n val sc = new InputReader(System.in)\n\n def solve(): Unit = {\n val N = ni()\n val F, T = Array.ofDim[Int](N)\n rep(N - 1) { i =>\n F(i) = ni() - 1\n T(i) = ni() - 1\n }\n val t = packTree(N, F, T)\n val o = map(N)(_ => ni() - 1)\n val o_i = Array.ofDim[Int](N)\n rep(N) { i =>\n o_i(o(i)) = i\n }\n\n val (d, p) = traceBfs(t)\n\n var ok = true\n rep(N - 1) { i =>\n ok &= d(o(i)) < d(o(i + 1)) || d(o(i)) == d(o(i + 1)) && o_i(p(o(i))) <= o_i(p(o(i + 1)))\n }\n\n val ans = if (ok) \"Yes\" else \"No\"\n\n out.println(ans)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n /**\n * @return (depth, parent)\n */\n def traceBfs(g: Array[Array[Int]]): (Array[Int], Array[Int]) = {\n val n = g.length\n val INF = 1e9.toInt + 10\n val q, p = Array.ofDim[Int](n)\n p(0) = -1\n val d = Array.fill[Int](n)(INF)\n d(0) = 0\n var cur = 0\n var last = 1\n while (cur < last) {\n val v = q(cur)\n rep(g(v).length) { i =>\n val u = g(v)(i)\n if (d(u) == INF) {\n d(u) = d(v) + 1\n p(u) = v\n q(last) = u\n last += 1\n }\n }\n cur += 1\n }\n (d, p)\n }\n\n def packTree(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n rep(m)(i => p(from(i)) += 1)\n rep(m)(i => p(to(i)) += 1)\n rep(n)(i => t(i) = new Array(p(i)))\n rep(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}], "negative_code": [{"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n val sc = new InputReader(System.in)\n\n def solve(): Unit = {\n val N = ni()\n val F, T = Array.ofDim[Int](N)\n rep(N - 1) { i =>\n F(i) = ni() - 1\n T(i) = ni() - 1\n }\n val t = packTree(N, F, T)\n val o = map(N)(_ => ni() - 1)\n\n val INF = 1e9.toInt\n val bfs = Array.ofDim[Int](N)\n val d = Array.fill[Int](N)(INF)\n d(0) = 0\n var cur = 0\n var last = 1\n while(cur < last) {\n val v = bfs(cur)\n val us = t(v)\n rep(us.length) { i =>\n val u = us(i)\n if (d(u) == INF) {\n bfs(last) = u\n d(u) = d(v) + 1\n last += 1\n }\n }\n cur += 1\n }\n\n var ok = o.distinct.length == N\n rep(N - 1) { i =>\n ok &= d(o(i)) <= d(o(i + 1))\n }\n\n val ans = if (ok) \"Yes\" else \"No\"\n\n out.println(ans)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n def packTree(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n rep(m)(i => p(from(i)) += 1)\n rep(m)(i => p(to(i)) += 1)\n rep(n)(i => t(i) = new Array(p(i)))\n rep(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n val sc = new InputReader(System.in)\n\n def solve(): Unit = {\n val N = ni()\n val F, T = Array.ofDim[Int](N)\n rep(N - 1) { i =>\n F(i) = ni() - 1\n T(i) = ni() - 1\n }\n val t = packTree(N, F, T)\n val o = map(N)(_ => ni() - 1)\n\n val INF = 1e9.toInt\n val bfs = Array.ofDim[Int](N)\n val d = Array.fill[Int](N)(INF)\n d(0) = 0\n var cur = 0\n var last = 1\n while(cur < last) {\n val v = bfs(cur)\n val us = t(v)\n rep(us.length) { i =>\n val u = us(i)\n if (d(u) == INF) {\n bfs(last) = u\n d(u) = d(v) + 1\n last += 1\n }\n }\n cur += 1\n }\n\n var ok = true\n rep(N - 1) { i =>\n ok &= o(i) <= o(i + 1)\n }\n\n val ans = if (ok) \"Yes\" else \"No\"\n\n out.println(ans)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n def packTree(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n rep(m)(i => p(from(i)) += 1)\n rep(m)(i => p(to(i)) += 1)\n rep(n)(i => t(i) = new Array(p(i)))\n rep(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n val sc = new InputReader(System.in)\n\n def solve(): Unit = {\n val N = ni()\n val F, T = Array.ofDim[Int](N)\n rep(N - 1) { i =>\n F(i) = ni() - 1\n T(i) = ni() - 1\n }\n val t = packTree(N, F, T)\n val o = map(N)(_ => ni() - 1)\n\n val INF = 1e9.toInt\n val bfs = Array.ofDim[Int](N)\n val d = Array.fill[Int](N)(INF)\n d(0) = 0\n var cur = 0\n var last = 1\n while(cur < last) {\n val v = bfs(cur)\n val us = t(v)\n rep(us.length) { i =>\n val u = us(i)\n if (d(u) == INF) {\n bfs(last) = u\n d(u) = d(v) + 1\n last += 1\n }\n }\n cur += 1\n }\n\n var ok = o.distinct.length == N\n rep(N - 1) { i =>\n ok &= o(i) <= o(i + 1)\n }\n\n val ans = if (ok) \"Yes\" else \"No\"\n\n out.println(ans)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n def packTree(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n rep(m)(i => p(from(i)) += 1)\n rep(m)(i => p(to(i)) += 1)\n rep(n)(i => t(i) = new Array(p(i)))\n rep(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "import java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.io.StdIn\n\nobject D extends App with Reader {\n read()\n val n = int()\n val links = Array.fill(n+1)(new mutable.ArrayBuffer[Int]())\n\n for (i <- 1 until n) {\n read()\n val s = int()\n val f = int()\n links(s) += f\n links(f) += s\n }\n\n read()\n val queue = Array.fill(n)(int())\n\n def isCorrect(): Boolean = {\n val visited = Array.fill(n+1)(false)\n val rank = Array.fill(n+1)(0)\n val q = new mutable.Queue[Int]()\n var currentRank = 0\n\n for (i <- queue) {\n if (visited(i)) return false\n if (i != 1) {\n val prevs = links(i).filter(visited(_))\n if (prevs.isEmpty) return false\n val ranks = prevs.map(rank(_))\n val min = ranks.min\n val max = ranks.max\n if (max == min) {\n if (currentRank == min) {\n currentRank += 1\n } else if (currentRank != min + 1) {\n return false\n }\n } else if (max == min + 1) {\n if (currentRank != max) {\n return false\n }\n } else {\n return false\n }\n }\n rank(i) = currentRank\n visited(i) = true\n }\n return true\n }\n\n println(if (isCorrect()) \"Yes\" else \"No\")\n}\n\ntrait Reader {\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(StdIn.readLine()) }\n def int() = st.nextToken().toInt\n def long() = st.nextToken().toLong\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.io.StdIn\n\nobject D extends App with Reader {\n read()\n val n = int()\n val links = Array.fill(n+1)(new mutable.ArrayBuffer[Int]())\n\n for (i <- 1 until n) {\n read()\n val s = int()\n val f = int()\n links(s) += f\n links(f) += s\n }\n\n read()\n val queue = Array.fill(n)(int())\n\n def isCorrect(): Boolean = {\n val visited = Array.fill(n+1)(false)\n val rank = Array.fill(n+1)(0)\n val q = new mutable.Queue[Int]()\n var currentRank = 0\n\n for (i <- queue) {\n if (visited(i)) return false\n if (i != 1) {\n val prevs = links(i).filter(visited(_))\n if (prevs.isEmpty) return false\n val ranks = prevs.map(rank(_))\n val min = ranks.min\n val max = ranks.max\n if (max == min) {\n if (currentRank == min) {\n currentRank += 1\n } else if (currentRank != min + 1) {\n return false\n }\n } else if (max == min + 1) {\n if (currentRank != max) {\n return false\n }\n } else {\n return false\n }\n }\n rank(i) = currentRank\n visited(i) = true\n }\n return true\n }\n\n println(if (isCorrect()) \"YES\" else \"NO\")\n}\n\ntrait Reader {\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(StdIn.readLine()) }\n def int() = st.nextToken().toInt\n def long() = st.nextToken().toLong\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject C extends App {\n\n case class Point(x: Int, segId: Int, isBegin: Boolean)\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val edges = Array.fill(n)(new collection.mutable.ArrayBuffer[Int]())\n (1 until n).foreach { _ =>\n val x = in.nextInt - 1\n val y = in.nextInt - 1\n edges(x) += y\n edges(y) += x\n }\n val dist = Array.fill(n)(0)\n val q = collection.mutable.Queue[Int]()\n dist(0) = 1\n q.enqueue(0)\n while (q.nonEmpty) {\n val c = q.dequeue()\n edges(c).foreach { e =>\n if (dist(e) == 0) {\n dist(e) = dist(c) + 1\n q.enqueue(e)\n }\n }\n }\n //dist.foreach(println)\n var lastDist = 1\n var ok = true\n Array.fill(n)(in.nextInt).foreach { i =>\n val d = dist(i - 1)\n if (lastDist > d)\n ok = false\n lastDist = d\n }\n\n if (ok) println(\"Yes\")\n else println(\"No\")\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toInt\n }\n\n def nextLong: Double = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject D extends App {\n\n def countLen(x: Long): Int = {\n var l = 0\n var xx = x\n while (xx > 0) {\n xx = xx / 10\n l += 1\n }\n l\n }\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val t = 123\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toInt\n }\n\n def nextLong: Long = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}], "src_uid": "82ff8ae62e39b8e64f9a273b736bf59e"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C628A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C628A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val x = ni()\n out.println(s\"1 ${x-1}\")\n }\n }\n}\n", "positive_code": [{"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n (1 to t).foreach{ _ =>\n val x = in.nextInt()\n out.println(s\"1 ${x-1}\")\n }\n\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}, {"source_code": "import java.io.PrintWriter\n\nimport scala.collection.mutable\nimport util.control.Breaks._\n\nobject Solution {\n val reader = scala.io.StdIn\n def readInt(): Int = reader.readLine().toInt\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n def readString(): String = reader.readLine()\n\n def multiTest(f: () => Unit): Unit = {\n var t = readInt()\n while (t > 0) {\n f()\n t -= 1\n }\n }\n\n def GCD(a: Int, b: Int): Int = {\n if (a == 0) return b\n GCD(b % a, a)\n }\n\n def solve(): Unit = {\n val x = readInt()\n println(s\"1 ${x - 1}\")\n\n }\n\n def main(args: Array[String]) {\n multiTest(solve)\n //solve()\n }\n}"}], "negative_code": [], "src_uid": "2fa3e88688b92c27ad26a23884e26009"} {"source_code": "object P039F extends App {\n readLine()\n val frog = readLine().split(' ').map(_.toInt)\n val mosq = readLine().split(' ').map(_.toInt)\n val killed = frog.map(x => (mosq.count(_ % x == 0)))\n val minValue = killed.min\n val cand = killed.zipWithIndex.filter(_._1 == minValue)\n println(cand.size)\n cand.foreach(x => printf(\"%d \", x._2+1))\n}\n", "positive_code": [{"source_code": "object PacifistFrogs39F extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n solve(System.in,System.out)\n def solve(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextInt()\n val m = scanner.nextInt()\n val k = scanner.nextInt()\n val distances = (1 to m).map(_ => scanner.nextInt()).toArray\n val mosquitos = (1 to k).map(_ => scanner.nextInt())\n val result = (0 until m).map{ frog =>\n val d = distances(frog)\n (frog,mosquitos.count(place => place % d == 0))\n }\n val minCount = result.minBy(_._2)._2\n val bestFrogs = result.filter(_._2 == minCount)\n out.println(bestFrogs.length)\n out.println(bestFrogs.map{case (frog,count) => frog+1}.mkString(\" \"))\n }\n}\n"}], "negative_code": [{"source_code": "object P039F extends App {\n readLine()\n val frog = readLine().split(' ').map(_.toInt)\n val mosq = readLine().split(' ').map(_.toInt)\n val killed = frog.map(x => (mosq.count(_ % x == 0)))\n val maxValue = killed.min\n killed.zipWithIndex.filter(_._1 == maxValue).foreach(x=>printf(\"%d \",x._2+1))\n}\n"}], "src_uid": "0701a595ee3a2b9edee53444b9dd1d51"} {"source_code": "import scala.io._\n\nobject A1 {\n def main(args: Array[String]): Unit = {\n var lines = Source.stdin.getLines().take(3).toArray\n lines(0) = lines(0) + lines(0).toUpperCase() + \"0123456789\"\n lines(1) = lines(1) + lines(1).toUpperCase() + \"0123456789\"\n println(lines(2).map(p=>lines(1).charAt(lines(0).indexOf(p))))\n }\n}\n", "positive_code": [{"source_code": "//package vandit\n\nimport java.util.Scanner\n\n/**\n * Created by vjain on 13/07/17.\n */\nobject Solution {\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val firstLayout : String = sc.next\n val secondLayout : String = sc.next\n val word : String = sc.next\n var transform : collection.mutable.Map[Char,Char] = collection.mutable.Map()\n\n for(pos <- 0 to firstLayout.size-1){\n transform.put(firstLayout.charAt(pos),secondLayout.charAt(pos))\n transform.put((firstLayout.charAt(pos)-32).toChar,(secondLayout.charAt(pos)-32).toChar)\n }\n for(pos <- 0 to word.size-1)\n print(transform.get(word.charAt(pos)).getOrElse(word.charAt(pos)))\n\n }\n}\n\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val _a, _b, t = readLine\n\n val a = _a + _a.toUpperCase\n val b = _b + _b.toUpperCase\n\n val res = new StringBuilder\n\n for (c <- t) {\n val i = a.indexOf(c)\n res += (if (i < 0) c else b(i))\n }\n\n println(res.toString())\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\n/**\n * @author Aydar Gizatullin a.k.a. lightning95 on 30.05.17.\n */\n\nobject Main2 {\n\n def main(args: Array[String]) {\n val in = scala.io.StdIn\n val s1 = in readLine\n val s2 = in readLine\n val t = in readLine()\n println(t.map(x =>\n if (Character.isDigit(x))\n x\n else {\n val up = Character.isUpperCase(x)\n val pos = s1.indexOf(Character.toLowerCase(x))\n val res = if (up)\n Character.toUpperCase(s2.charAt(pos))\n else\n s2.charAt(pos)\n res\n }))\n }\n\n\n}\n\n"}], "negative_code": [], "src_uid": "d6f01ece3f251b7aac74bf3fd8231a80"} {"source_code": "//package codeforces\n\nobject SmallestWord {\n\n def main(args: Array[String]): Unit = {\n val input = io.StdIn.readLine\n\n for (i <- 0 to input.length - 2) {\n if (input(i) == input(i+1)) print(\"0 \")\n else print(\"1 \")\n }\n\n if(input.last == 'a') print(\"1\") else print(\"0\")\n }\n\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S = ns()\n val N = S.length\n val ans = Array.fill[List[Int]](N + 1, 2)(Nil) // 0: 左寄せ, 1: 右寄せ\n rep(N) { i =>\n S(i) match {\n case 'a' =>\n ans(i + 1)(0) = 1 :: ans(i)(1)\n ans(i + 1)(1) = 0 :: ans(i)(1)\n\n case 'b' =>\n ans(i + 1)(0) = 0 :: ans(i)(0)\n ans(i + 1)(1) = 1 :: ans(i)(0)\n }\n }\n\n out.println(ans(N)(0).toArray.reverse.mkString(\" \"))\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "import java.io._\nimport java.util\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n\n def solve(in: InputReader): Unit = {\n val s = in.next.toCharArray\n (0 until s.size - 1).foreach { i =>\n\n if (s(i) != s(i + 1)) {\n (0 to (i / 2)).foreach { j =>\n val t = s(j)\n s(j) = s(i - j)\n s(i - j) = t\n }\n print(\"1 \")\n } else {\n print(\"0 \")\n }\n }\n\n if (s(s.size - 1) == 'a')\n println(\"1\")\n else\n println(\"0\")\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toInt\n }\n\n def nextLong: Double = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}], "negative_code": [], "src_uid": "fc0d3b122d800dcbcb99795581229d42"} {"source_code": "import scala.collection.Set\n\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val tb = stdin.next().toInt\n val rel = stdin.take(tb).map(solve)\n println(rel.flatten.mkString(\"\\n\"))\n\n def solve(str: String): List[String] = {\n var result: String = \"\"\n var visited = Set.empty[Char]\n var position = 0\n str.indices.foreach(i => {\n var ch = str.charAt(i)\n if (visited(ch)) {\n if (position > 0 && ch == result.charAt(position - 1))\n position -= 1\n else if (position + 1 < result.length && result.charAt(position + 1) == str.charAt(i))\n position += 1\n else\n return List(\"NO\")\n }\n else {\n visited += ch\n if (position == 0) {\n result = ch + result\n }\n else if (position == result.length - 1) {\n result = result + ch\n position = result.length - 1\n }\n else return List(\"NO\")\n }\n })\n result = result + ('a' to 'z').filter(ch => !visited.contains(ch)).mkString(\"\")\n List(\"YES\", result)\n }\n}\n\n", "positive_code": [{"source_code": "import scala.collection.Set\n\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val tb = stdin.next().toInt\n val rel = stdin.take(tb).map(solve)\n println(rel.flatten.mkString(\"\\n\"))\n\n def solve(str: String): List[String] = {\n var m: Map[Char, Set[Char]] = str.toCharArray.sliding(2).foldLeft(Map.empty[Char, Set[Char]]) {\n case (s, Array(ch1, ch2)) =>\n val nSet1 = s.getOrElse(ch1, Set.empty[Char]) + ch2\n val nSet2 = s.getOrElse(ch2, Set.empty[Char]) + ch1\n s + (ch1 -> nSet1) + (ch2 -> nSet2)\n case (s, _) => s // sliding of 1 element\n }\n var nMap = ('a' to 'z').map(ch => ch -> m.getOrElse(ch, Set.empty[Char])).toMap\n var result = List.empty[String]\n var taken = ('a' to 'z').toSet\n var acc: Option[(Map[Char, Set[Char]], List[String], Set[Char])] = Some(nMap, List.empty[String], Set.empty[Char])\n ('a' to 'z').foldLeft(acc) {\n case (None, _) => None\n case (accum@Some((map, list, visited)), ch) if visited.contains(ch) => accum\n case (Some((map, list, visited)), ch) =>\n expand(map, list, visited, ch.toString)\n } match {\n case None => List(\"NO\")\n case Some((m, list, set)) => List(\"YES\", list.mkString(\"\"))\n }\n }\n\n def expand(map: Map[Char, Set[Char]],list: List[String], visited: Set[Char], str: String): Option[(Map[Char, Set[Char]], List[String], Set[Char])] = {\n val neighborsFirst = map(str.head)\n val neighborsLast = map(str.last)\n if (neighborsFirst.size > 2) None\n else if (neighborsLast.size > 2) None\n else if (str.length == 1) {\n if (neighborsFirst.isEmpty) Some(map, str :: list, visited + str.head)\n else if (neighborsFirst.size == 1) expand(map, list, visited + str.head, neighborsFirst.head + str)\n else if (neighborsFirst.size == 2) expand(map, list, visited + str.head, neighborsFirst.head + str + neighborsFirst.last)\n else None\n }\n else {\n if (neighborsFirst.exists(ch => ch != str.charAt(1))) {\n var goodNeighbors = neighborsFirst.filter(ch => ch != str.charAt(1))\n if (goodNeighbors.exists(x => visited.contains(x)))\n None\n else expand(map, list, visited + str.head, goodNeighbors.head + str)\n }\n else if (neighborsLast.exists(ch => ch != str.charAt(str.length - 2))) {\n var goodNeighbors = neighborsLast.filter(ch => ch != str.charAt(str.length - 2))\n if (goodNeighbors.exists(x => visited.contains(x)))\n None\n else expand(map, list, visited + str.last, str + goodNeighbors.head)\n }\n else {\n Some(map, str :: list, visited + str.last + str.head)\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "import scala.collection.Set\n\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val tb = stdin.next().toInt\n val rel = stdin.take(tb).map(solve)\n println(rel.flatten.mkString(\"\\n\"))\n\n def solve(str: String): List[String] = {\n var result: String = \"\"\n var visited = Set.empty[Char]\n var position = 0\n str.indices.foreach(i => {\n var ch = str.charAt(i)\n if (visited(ch)) {\n if (position > 0 && ch == result.charAt(position - 1))\n position -= 1\n else if (position + 1 < result.length && result.charAt(position + 1) == str.charAt(i))\n position += 1\n else\n return List(\"NO\")\n }\n else {\n visited += ch\n if (position == 0) {\n result = ch + result\n }\n else if (position == result.length - 1) {\n result = result + ch\n position = result.length - 1\n }\n }\n })\n result = result + ('a' to 'z').filter(ch => !visited.contains(ch)).mkString(\"\")\n List(\"YES\", result)\n }\n}\n\n"}], "src_uid": "8fb62b497b6fb2a5fb4f2669aeb51b73"} {"source_code": "object A600 {\n def main(args: Array[String]) = {\n val input = readLine\n\n def isInteger(word: String): Boolean = {\n if (word.length == 0) false\n else if (word.exists{case d => !Character.isDigit(d)}) false\n else if (word(0) == '0') word.length == 1\n else true\n }\n\n val (integers, nonIntegers) = input.split(\"[,;]\", -1).partition { case word => isInteger(word) }\n\n def convertToString(arr: Array[String]): String = {\n if (arr.length == 0) \"-\" else \"\\\"\" + arr.mkString(\",\") + \"\\\"\" \n }\n\n println(convertToString(integers))\n println(convertToString(nonIntegers))\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n\n def isNumber(str: String) = {\n str.forall(i => i >= '0' && i <= '9') && str.length > 0 && (str.head != '0' || str.length == 1)\n }\n\n val (a, b) = in.next().split(\"[;,]\", -1).partition(isNumber)\n if (a.nonEmpty)\n println(a.mkString(\"\\\"\", \",\", \"\\\"\"))\n else\n println(\"-\")\n if (b.nonEmpty)\n println(b.mkString(\"\\\"\", \",\", \"\\\"\"))\n else\n println(\"-\")\n}"}, {"source_code": "object Task1 {\n def main(args: Array[String]) {\n val r = readLine()\n val normalize = if (r.last == ',' || r.last == ';') r + \" \" else r\n val res = normalize.split(Array(';', ','))\n val regexp = \"\\\\d+\"\n\n val p = res.partition { rr => rr.matches(regexp) && ! (rr.head == '0' && rr.length > 1)}\n val str1 = if (p._1.isEmpty) \"-\" else \"\\\"\" + p._1.mkString(\",\").trim + \"\\\"\"\n val str2 = if (p._2.isEmpty) \"-\" else \"\\\"\" + p._2.mkString(\",\").trim + \"\\\"\"\n println(str1)\n println(str2)\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n\n def isNumber(str: String) = {\n str.forall(i => i >= '0' && i <= '9') && str.length > 0 && (str.head != '0' || str.length == 1)\n }\n\n val (a, b) = in.next().split(\"[;,]\").partition(isNumber)\n if (a.nonEmpty)\n println(a.mkString(\"\\\"\", \",\", \"\\\"\"))\n else\n println(\"-\")\n if (b.nonEmpty)\n println(b.mkString(\"\\\"\", \",\", \"\\\"\"))\n else\n println(\"-\")\n}"}, {"source_code": "object Task1 {\n def main(args: Array[String]) {\n val r = readLine()\n val normalize = if (r.last == ',' || r.last == ';') r + \" \" else r\n val res = normalize.split(Array(';', ','))\n val regexp = \"\\\\d+\"\n\n val p = res.partition { rr =>\n rr.matches(regexp) && (rr.length > 1 && rr.head != '0')\n }\n val str1 = if (p._1.isEmpty) \"-\" else \"\\\"\" + p._1.mkString(\",\").trim + \"\\\"\"\n val str2 = if (p._2.isEmpty) \"-\" else \"\\\"\" + p._2.mkString(\",\").trim + \"\\\"\"\n println(str1)\n println(str2)\n }\n}"}, {"source_code": "object Task1 {\n\n import scala.util.{Success, Failure, Try}\n\n def main(args: Array[String]) {\n val r = readLine()\n val normalize = if (r.last == ',' || r.last == ';') r + \" \" else r\n val res = normalize.split(Array(';', ','))\n val p = res.partition { rr =>\n Try(rr.toInt) match {\n case Success(_) if rr.length > 1 && rr.head == '0' => false\n case Success(_) => true\n case _ => false\n }\n }\n val str1 = if (p._1.isEmpty) \"-\" else \"\\\"\" + p._1.mkString(\",\").trim + \"\\\"\"\n val str2 = if (p._2.isEmpty) \"-\" else \"\\\"\" + p._2.mkString(\",\").trim + \"\\\"\"\n println(str1)\n println(str2)\n }\n}\n"}, {"source_code": "object Task1 {\n def main(args: Array[String]) {\n val r = readLine()\n val normalize = if (r.last == ',' || r.last == ';') r + \" \" else r\n val res = normalize.split(Array(';', ','))\n val regexp = \"\\\\d+\"\n\n val p = res.partition { rr =>\n rr.matches(regexp) && (rr==\"0\" || (rr.head != '0' && rr.length > 1))\n }\n val str1 = if (p._1.isEmpty) \"-\" else \"\\\"\" + p._1.mkString(\",\").trim + \"\\\"\"\n val str2 = if (p._2.isEmpty) \"-\" else \"\\\"\" + p._2.mkString(\",\").trim + \"\\\"\"\n println(str1)\n println(str2)\n }\n}\n"}, {"source_code": "object Task1 {\n import scala.util.{Success, Failure, Try}\n\n def main (args: Array[String]){\n val r = readLine()\n val res = r.split(Array(';',','))\n val p = res.partition{rr=>\n Try(rr.toInt) match {\n case Success(_) if rr.length>1 && rr.head == '0' => false\n case Success(_) => true\n case _ => false\n }\n }\n val str1 = if(p._1.isEmpty) \"-\" else p._1.mkString(\",\")\n val str2 = if(p._2.isEmpty) \"-\" else p._2.mkString(\",\")\n println(\"\\\"\"+str1+\"\\\"\")\n println(\"\\\"\"+str2+\"\\\"\")\n }\n}"}, {"source_code": "object Task1 {\n\n import scala.util.{Success, Failure, Try}\n\n def main(args: Array[String]) {\n val r = readLine()\n val normalize = if (r.last == ',' || r.last == ';') r + \" \" else r\n val res = normalize.split(Array(';', ','))\n val p = res.partition { rr =>\n Try(rr.toInt) match {\n case Success(_) if rr.length > 1 && rr.head == '0' => false\n case Success(_) => true\n case _ => false\n }\n }\n val str1 = if (p._1.isEmpty) \"-\" else p._1.mkString(\",\")\n val str2 = if (p._2.isEmpty) \"-\" else p._2.mkString(\",\")\n println(\"\\\"\" + str1.trim + \"\\\"\")\n println(\"\\\"\" + str2.trim + \"\\\"\")\n }\n}\n"}, {"source_code": "object Task1 {\n\n import scala.util.{Success, Failure, Try}\n\n def main(args: Array[String]) {\n val r = readLine()\n val normalize = if (r.last == ',' || r.last == ';') r + \" \" else r\n val res = normalize.split(Array(';', ','))\n val p = res.partition { rr =>\n Try(rr.toInt) match {\n case Success(_) if rr.length > 1 && rr.head == '0' => false\n case Success(_) => true\n case _ => false\n }\n }\n val str1 = if (p._1.isEmpty) \"-\" else \"\\\"\" + p._1.mkString(\",\") + \"\\\"\"\n val str2 = if (p._2.isEmpty) \"-\" else \"\\\"\" + p._2.mkString(\",\") + \"\\\"\"\n println(str1.trim)\n println(str2.trim)\n }\n}\n"}], "src_uid": "ad02cead427d0765eb642203d13d3b99"} {"source_code": "object _1326A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val n = io.read[Int]\n\n val ans = if(n == 1) {\n \"-1\"\n } else if ((n-1)%3 != 0) {\n (\"2\" * (n-1)) + \"3\"\n } else {\n (\"2\" * (n-2)) + \"73\"\n }\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n", "positive_code": [{"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n\n\n val sb = new mutable.StringBuilder()\n (1 to t).foreach{ _ =>\n val n = in.nextInt()\n if(n == 1){\n sb.append(-1).append(System.lineSeparator())\n }else{\n sb.append(2)\n sb.append((1 until n).map(_ => \"3\").mkString(\"\"))\n sb.append(System.lineSeparator())\n }\n }\n out.print(sb.toString())\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "negative_code": [{"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n\n (1 to t).foreach{ _ =>\n val n = in.nextInt()\n if(n == 1){\n out.println(-1)\n }else{\n if(n==2){\n out.println(57)\n }else {\n if (n % 2 == 0) {\n val res = (1 to (n - 2)).map(_ => '2').mkString(\"\") + \"33\"\n out.println(res)\n } else {\n val res = (1 until n).map(_ => '2').mkString(\"\") + \"3\"\n out.println(res)\n }\n }\n }\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}, {"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n\n (1 to t).foreach{ _ =>\n val n = in.nextInt()\n if(n == 1){\n out.println(-1)\n }else{\n if(n%2==0){\n val res = (1 to (n-2)).map(_ => '2').mkString(\"\")+\"33\"\n out.println(res)\n }else{\n val res = (1 until n).map(_ => '2').mkString(\"\")+ \"3\"\n out.println(res)\n }\n }\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}, {"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n\n val sb = new mutable.StringBuilder()\n (1 to t).foreach{ _ =>\n val n = in.nextInt()\n if(n == 1){\n sb.append(-1).append(System.lineSeparator())\n }else{\n if(n==2){\n sb.append(57).append(System.lineSeparator())\n }else {\n if (n % 2 == 0) {\n val res = (1 to (n - 2)).map(_ => \"2\").mkString(\"\") + \"33\"\n sb.append(res).append(System.lineSeparator())\n } else {\n val res = (1 until n).map(_ => \"2\").mkString(\"\") + \"3\"\n sb.append(res).append(System.lineSeparator())\n }\n }\n }\n }\n out.print(sb.toString())\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}, {"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n\n (1 to t).foreach{ _ =>\n val n = in.nextInt()\n if(n == 1){\n out.println(-1)\n }else{\n if(n%2==0){\n val res = (1 to n).map(_ => '3').mkString(\"\")\n out.println(res)\n }else{\n val res = (1 until n).map(_ => '2').mkString(\"\")+ \"3\"\n out.println(res)\n }\n }\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "src_uid": "43996d7e052aa628a46d03086f9c5436"} {"source_code": "import java.util.PriorityQueue\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val grid = Array.fill(n){ readLine }\n\n val minHor, minVert = Array.fill(n) { n }\n val maxHor, maxVert = Array.fill(n) { -1 }\n\n for (r <- 0 until n) {\n for (c <- 0 until n) {\n if (grid(r)(c) == 'B') {\n if (c < minHor(r)) minHor(r) = c\n if (r < minVert(c)) minVert(c) = r\n if (c > maxHor(r)) maxHor(r) = c\n if (r > maxVert(c)) maxVert(c) = r\n }\n }\n }\n\n var best = 0\n for (i <- 0 until n) {\n if (maxVert(i) == -1) best += 1\n if (maxHor(i) == -1) best += 1\n }\n val base = best\n\n for (r <- 0 to n - k) {\n val rr = r + k - 1\n val in, out = new PriorityQueue[Int]\n for (i <- r until r + k) {\n if (maxHor(i) >= 0 && maxHor(i) - minHor(i) <= k) {\n in.add(maxHor(i))\n out.add(minHor(i))\n }\n }\n var addHor = 0\n var addVert = 0\n for (c <- 0 until k) {\n if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert += 1\n }\n for (c <- 0 to n - k) {\n val cc = c + k - 1\n while (!in.isEmpty && in.peek <= cc) {\n in.poll()\n addHor += 1\n }\n while (!out.isEmpty && out.peek < c) {\n out.poll()\n addHor -= 1\n }\n if (base + addHor + addVert > best) {\n best = base + addHor + addVert\n }\n if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert -= 1\n if (cc + 1 < n && maxVert(cc + 1) >= 0 && minVert(cc + 1) >= r && maxVert(cc + 1) <= rr) addVert += 1\n }\n }\n\n println(best)\n}\n", "positive_code": [{"source_code": "import java.util.PriorityQueue\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k) = readInts(2)\n val grid = Array.fill(n){ readLine }\n\n val minHor, minVert = Array.fill(n) { n }\n val maxHor, maxVert = Array.fill(n) { -1 }\n\n {\n var r = 0\n while (r < n) {\n var c = 0\n while (c < n) {\n if (grid(r)(c) == 'B') {\n if (c < minHor(r)) minHor(r) = c\n if (r < minVert(c)) minVert(c) = r\n if (c > maxHor(r)) maxHor(r) = c\n if (r > maxVert(c)) maxVert(c) = r\n }\n c += 1\n }\n r += 1\n }\n }\n\n var best = 0\n for (i <- 0 until n) {\n if (maxVert(i) == -1) best += 1\n if (maxHor(i) == -1) best += 1\n }\n val base = best\n\n for (r <- 0 to n - k) {\n val rr = r + k - 1\n val in, out = new PriorityQueue[Int]\n //val out = mutable.PriorityQueue.empty[Int]//(Ordering.by(minHor).reverse)\n var i = r\n while (i < r + k) {\n if (maxHor(i) >= 0 && maxHor(i) - minHor(i) <= k) {\n in.add(maxHor(i))\n out.add(minHor(i))\n }\n i += 1\n }\n var addHor = 0\n var addVert = 0\n var c = 0\n while (c < k) {\n if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert += 1\n c += 1\n }\n c = 0\n var cc = c + k - 1\n while (c <= n - k) {\n while (!in.isEmpty && in.peek <= cc) {\n in.poll()\n addHor += 1\n }\n while (!out.isEmpty && out.peek < c) {\n out.poll()\n addHor -= 1\n }\n if (base + addHor + addVert > best) {\n best = base + addHor + addVert\n }\n if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert -= 1\n cc += 1\n if (cc < n && maxVert(cc) >= 0 && minVert(cc) >= r && maxVert(cc) <= rr) addVert += 1\n c += 1\n }\n }\n\n println(best)\n}\n"}, {"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val grid = Array.fill(n){ readLine }\n\n val minHor, minVert = Array.fill(n) { n }\n val maxHor, maxVert = Array.fill(n) { -1 }\n\n for (r <- 0 until n) {\n for (c <- 0 until n) {\n if (grid(r)(c) == 'B') {\n if (c < minHor(r)) minHor(r) = c\n if (r < minVert(c)) minVert(c) = r\n if (c > maxHor(r)) maxHor(r) = c\n if (r > maxVert(c)) maxVert(c) = r\n }\n }\n }\n\n var best = 0\n for (i <- 0 until n) {\n if (maxVert(i) == -1) best += 1\n if (maxHor(i) == -1) best += 1\n }\n val score = Array.fill(n - k + 1, n - k + 1)(best)\n\n for (r <- 0 to n - k) {\n val rr = r + k - 1\n var addVert = 0\n for (c <- 0 until k) {\n if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert += 1\n }\n for (c <- 0 to n - k) {\n score(r)(c) += addVert\n val cc = c + k\n if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert -= 1\n if (cc < n && maxVert(cc) >= 0 && minVert(cc) >= r && maxVert(cc) <= rr) addVert += 1\n }\n }\n\n for (c <- 0 to n - k) {\n val cc = c + k - 1\n var addHor = 0\n for (r <- 0 until k) {\n if (maxHor(r) >= 0 && minHor(r) >= c && maxHor(r) <= cc) addHor += 1\n }\n for (r <- 0 to n - k) {\n score(r)(c) += addHor\n if (maxHor(r) >= 0 && minHor(r) >= c && maxHor(r) <= cc) addHor -= 1\n val rr = r + k\n if (rr < n && maxHor(rr) >= 0 && minHor(rr) >= c && maxHor(rr) <= cc) addHor += 1\n }\n }\n\n var max = 0\n for (s1 <- score) {\n for (s2 <- s1) {\n if (s2 > max) max = s2\n }\n }\n\n println(max)\n}\n"}, {"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val grid = Array.fill(n){ readLine }\n\n val minHor, minVert = Array.fill(n) { n }\n val maxHor, maxVert = Array.fill(n) { -1 }\n\n for (r <- 0 until n) {\n for (c <- 0 until n) {\n if (grid(r)(c) == 'B') {\n if (c < minHor(r)) minHor(r) = c\n if (r < minVert(c)) minVert(c) = r\n if (c > maxHor(r)) maxHor(r) = c\n if (r > maxVert(c)) maxVert(c) = r\n }\n }\n }\n\n var best = 0\n for (i <- 0 until n) {\n if (maxVert(i) == -1) best += 1\n if (maxHor(i) == -1) best += 1\n }\n val score = Array.fill(n - k + 1, n - k + 1)(best)\n\n for (r <- 0 to n - k) {\n val rr = r + k - 1\n var addVert = 0\n for (c <- 0 until k) {\n if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert += 1\n }\n for (c <- 0 to n - k) {\n score(r)(c) += addVert\n val cc = c + k\n if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert -= 1\n if (cc < n && maxVert(cc) >= 0 && minVert(cc) >= r && maxVert(cc) <= rr) addVert += 1\n }\n }\n\n for (c <- 0 to n - k) {\n val cc = c + k - 1\n var addHor = 0\n for (r <- 0 until k) {\n if (maxHor(r) >= 0 && minHor(r) >= c && maxHor(r) <= cc) addHor += 1\n }\n for (r <- 0 to n - k) {\n score(r)(c) += addHor\n if (maxHor(r) >= 0 && minHor(r) >= c && maxHor(r) <= cc) addHor -= 1\n val rr = r + k\n if (rr < n && maxHor(rr) >= 0 && minHor(rr) >= c && maxHor(rr) <= cc) addHor += 1\n }\n }\n\n println(score.flatten.max)\n}\n"}, {"source_code": "import java.util.PriorityQueue\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val grid = Array.fill(n){ readLine }\n\n val minHor, minVert = Array.fill(n) { n }\n val maxHor, maxVert = Array.fill(n) { -1 }\n\n {\n var r = 0\n while (r < n) {\n var c = 0\n while (c < n) {\n if (grid(r)(c) == 'B') {\n if (c < minHor(r)) minHor(r) = c\n if (r < minVert(c)) minVert(c) = r\n if (c > maxHor(r)) maxHor(r) = c\n if (r > maxVert(c)) maxVert(c) = r\n }\n c += 1\n }\n r += 1\n }\n }\n\n var best = 0\n for (i <- 0 until n) {\n if (maxVert(i) == -1) best += 1\n if (maxHor(i) == -1) best += 1\n }\n val base = best\n\n for (r <- 0 to n - k) {\n val rr = r + k - 1\n val in, out = new PriorityQueue[Int]\n var i = r\n while (i < r + k) {\n if (maxHor(i) >= 0 && maxHor(i) - minHor(i) <= k) {\n in.add(maxHor(i))\n out.add(minHor(i))\n }\n i += 1\n }\n var addHor = 0\n var addVert = 0\n var c = 0\n while (c < k) {\n if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert += 1\n c += 1\n }\n c = 0\n var cc = c + k - 1\n while (c <= n - k) {\n while (!in.isEmpty && in.peek <= cc) {\n in.poll()\n addHor += 1\n }\n while (!out.isEmpty && out.peek < c) {\n out.poll()\n addHor -= 1\n }\n if (base + addHor + addVert > best) {\n best = base + addHor + addVert\n }\n if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert -= 1\n cc += 1\n if (cc < n && maxVert(cc) >= 0 && minVert(cc) >= r && maxVert(cc) <= rr) addVert += 1\n c += 1\n }\n }\n\n println(best)\n}\n"}], "negative_code": [{"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val grid = Array.fill(n){ readLine }\n\n val minHor, minVert = Array.fill(n) { n }\n val maxHor, maxVert = Array.fill(n) { -1 }\n\n for (r <- 0 until n) {\n for (c <- 0 until n) {\n if (grid(r)(c) == 'B') {\n if (c < minHor(r)) minHor(r) = c\n if (r < minVert(c)) minVert(c) = r\n if (c > maxHor(r)) maxHor(r) = c\n if (r > maxVert(c)) maxVert(c) = r\n }\n }\n }\n\n var best = 0\n for (i <- 0 until n) {\n if (maxVert(i) == -1) best += 1\n if (maxHor(i) == -1) best += 1\n }\n val score = Array.fill(n - k + 1, n - k + 1)(best)\n\n for (r <- 0 to n - k) {\n val rr = r + k - 1\n var addVert = 0\n for (c <- 0 until k) {\n if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert += 1\n }\n for (c <- 0 to n - k) {\n val cc = c + k - 1\n if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert -= 1\n if (cc + 1 < n && maxVert(cc + 1) >= 0 && minVert(cc + 1) >= r && maxVert(cc + 1) <= rr) addVert += 1\n score(r)(c) += addVert\n }\n }\n\n for (c <- 0 to n - k) {\n val cc = c + k - 1\n var addHor = 0\n for (r <- 0 until k) {\n if (maxHor(r) >= 0 && minHor(r) >= c && maxHor(c) <= cc) addHor += 1\n }\n for (r <- 0 to n - k) {\n val rr = r + k - 1\n if (maxHor(r) >= 0 && minHor(r) >= c && maxHor(r) <= cc) addHor -= 1\n if (rr + 1 < n && maxHor(rr + 1) >= 0 && minHor(rr + 1) >= c && maxHor(rr + 1) <= cc) addHor += 1\n score(r)(c) += addHor\n }\n }\n\n println(score.flatten.max)\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k) = readInts(2)\n val grid = Array.fill(n){ readLine }\n\n val minHor, minVert = Array.fill(n) { n }\n val maxHor, maxVert = Array.fill(n) { -1 }\n\n {\n var r = 0\n while (r < n) {\n var c = 0\n while (c < n) {\n if (grid(r)(c) == 'B') {\n if (c < minHor(r)) minHor(r) = c\n if (r < minVert(c)) minVert(c) = r\n if (c > maxHor(r)) maxHor(r) = c\n if (r > maxVert(c)) maxVert(c) = r\n }\n c += 1\n }\n r += 1\n }\n }\n\n var best = 0\n for (i <- 0 until n) {\n if (maxVert(i) == -1) best += 1\n if (maxHor(i) == -1) best += 1\n }\n val base = best\n\n for (r <- 0 to n - k) {\n val rr = r + k - 1\n val in = mutable.PriorityQueue.empty[Int]//(Ordering.by(maxHor).reverse)\n val out = mutable.PriorityQueue.empty[Int]//(Ordering.by(minHor).reverse)\n var i = r\n while (i < r + k) {\n if (maxHor(i) >= 0 && maxHor(i) - minHor(i) <= k) {\n in += maxHor(i)\n out += minHor(i)\n }\n i += 1\n }\n var addHor = 0\n var addVert = 0\n var c = 0\n while (c < k) {\n if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert += 1\n c += 1\n }\n c = 0\n var cc = c + k - 1\n while (c <= n - k) {\n while (in.nonEmpty && in.head <= cc) {\n in.dequeue()\n addHor += 1\n }\n while (out.nonEmpty && out.head < c) {\n out.dequeue()\n addHor -= 1\n }\n if (base + addHor + addVert > best) {\n best = base + addHor + addVert\n }\n if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert -= 1\n cc += 1\n if (cc < n && maxVert(cc) >= 0 && minVert(cc) >= r && maxVert(cc) <= rr) addVert += 1\n c += 1\n }\n }\n\n println(best)\n}\n"}, {"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val grid = Array.fill(n){ readLine }\n\n val minHor, minVert = Array.fill(n) { n }\n val maxHor, maxVert = Array.fill(n) { -1 }\n\n for (r <- 0 until n) {\n for (c <- 0 until n) {\n if (grid(r)(c) == 'B') {\n if (c < minHor(r)) minHor(r) = c\n if (r < minVert(c)) minVert(c) = r\n if (c > maxHor(r)) maxHor(r) = c\n if (r > maxVert(c)) maxVert(c) = r\n }\n }\n }\n\n var best = 0\n for (i <- 0 until n) {\n if (maxVert(i) == -1) best += 1\n if (maxHor(i) == -1) best += 1\n }\n val score = Array.fill(n - k + 1, n - k + 1)(best)\n\n for (r <- 0 to n - k) {\n val rr = r + k - 1\n var addVert = 0\n for (c <- 0 until k) {\n if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert += 1\n }\n for (c <- 0 to n - k) {\n val cc = c + k - 1\n if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert -= 1\n if (cc + 1 < n && maxVert(cc + 1) >= 0 && minVert(cc + 1) >= r && maxVert(cc + 1) <= rr) addVert += 1\n score(r)(c) += addVert\n }\n }\n\n for (c <- 0 to n - k) {\n val cc = c + k - 1\n var addHor = 0\n for (r <- 0 until k) {\n if (maxHor(r) >= 0 && minHor(r) >= c && maxHor(r) <= cc) addHor += 1\n }\n for (r <- 0 to n - k) {\n val rr = r + k - 1\n if (maxHor(r) >= 0 && minHor(r) >= c && maxHor(r) <= cc) addHor -= 1\n if (rr + 1 < n && maxHor(rr + 1) >= 0 && minHor(rr + 1) >= c && maxHor(rr + 1) <= cc) addHor += 1\n score(r)(c) += addHor\n }\n }\n\n println(score.flatten.max)\n}\n"}], "src_uid": "97e149fe5933bf1c9dbe8d958c1b2e05"} {"source_code": "import scala.io.StdIn\r\n\r\nobject MiracleSleeper extends App{\r\n val testCases = StdIn.readInt()\r\n for (_ <- 1 to testCases) {\r\n val input = StdIn.readLine().split(\" \")\r\n val low = input.apply(0).toInt\r\n val high = input.apply(1).toInt\r\n\r\n val mid = Math.ceil(high/2.0).toInt\r\n\r\n if (mid >= low) {\r\n println(mid-1)\r\n } else {\r\n println(high-low)\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object A extends App {\r\n def remainder(from: Int, to: Int): Int = {\r\n val t = if (to % 2 == 0) 2 else 1\r\n val d = from max ((to + t) / 2)\r\n to % d\r\n }\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(l, r) = readLine().split(\" \").map(_.toInt)\r\n\r\n val ans = remainder(l, r)\r\n\r\n println(ans)\r\n }\r\n\r\n}\r\n"}], "negative_code": [], "src_uid": "c34db7897f051b0de2f49f2696c6ee2f"} {"source_code": "import java.util.Scanner\n\nimport scala.collection.immutable._\n\nobject RemoveExtraOne {\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val N = sc.nextInt()\n val p = for (i <- 0.until(N)) yield sc.nextInt()\n\n def process(i: Int, set: TreeSet[Int], inc: Array[Int]): Int = {\n if (i == N) {\n inc.indexOf(inc.max) + 1\n }\n else {\n val higherSet = set.from(p(i) + 1)\n if (higherSet.size == 0) process(i + 1, set + p(i), inc.updated(p(i) - 1, inc(p(i) - 1) - 1))\n else if (higherSet.size == 1) {\n val higherElement = higherSet.firstKey\n process(i + 1, set + p(i), inc.updated(higherElement - 1, inc(higherElement - 1) + 1))\n }\n else process(i + 1, set + p(i), inc)\n }\n }\n\n val answer = process(0, TreeSet.empty, Array.tabulate(N)(_ => 0))\n println(answer)\n }\n}\n", "positive_code": [{"source_code": "object Main extends App {\n\n import scala.io.StdIn\n\n val n = StdIn.readLine().toInt\n val a = StdIn.readLine().split(\" \").map(_.toInt)\n\n var mx1 = 0\n var mx2 = 0\n\n val cnt = new Array[Integer](n+1)\n val maybe = new Array[Boolean](n+1)\n val index = new Array[Integer](n+1)\n\n var set = new scala.collection.mutable.TreeSet[Integer]()\n\n for (i <- 0 until n) {\n maybe(i) = a(i) > mx2\n index(a(i)) = i\n cnt(i+1) = cnt(i)\n if (a(i) > mx1) cnt(i+1) += 1\n if (a(i) > mx1) {\n mx2 = mx1\n mx1 = a(i)\n }\n else\n if (a(i) > mx2) {\n mx2 = a(i)\n }\n\n set.add(a(i))\n }\n\n var r = 0\n var mx = 0\n var ans = n\n\n for (i <- n-1 to 0 by -1) {\n\n if (cnt(i) + r > mx) {\n mx = cnt(i) + r\n ans = a(i)\n }\n else\n if (cnt(i) + r == mx) ans = Math.min(ans, a(i))\n\n if (maybe(i)) {\n val mx = set.last\n if (mx > a(i)) cnt(index(mx)) += 1 else r += 1\n }\n set.remove(a(i))\n }\n\n println(ans)\n}\n"}, {"source_code": "\nimport java.util.Scanner\n\nimport scala.collection.immutable._\n\nobject RemoveExtraOne {\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val N = sc.nextInt()\n val p = for (i <- 0.until(N)) yield sc.nextInt()\n\n def process(i: Int, set: TreeSet[Int], candidates: TreeMap[Int, Int], hopeless: TreeSet[Int]): Int = {\n if (i == N) {\n if (candidates.size == 0) {\n if (hopeless.size == 0) 1 else hopeless.min\n }\n else if (candidates.values.max == 1) (hopeless.toList ++ candidates.keys).min\n else candidates.filter{case (_, freq) => freq == candidates.values.max}.keys.min\n }\n else {\n val higherSet = set.from(p(i) + 1)\n if (higherSet.size == 1) {\n val higherElement = higherSet.firstKey\n process(i + 1, set + p(i), candidates.updated(higherElement, 1 + candidates.getOrElse(higherElement, 0)), hopeless)\n }\n else if (higherSet.size > 1) process(i + 1, set + p(i), candidates, hopeless + p(i))\n else process(i + 1, set + p(i), candidates, hopeless)\n }\n }\n\n val answer = process(0, TreeSet.empty, TreeMap.empty, TreeSet.empty)\n println(answer)\n }\n}\n"}], "negative_code": [{"source_code": "\nimport java.util.Scanner\n\nimport scala.collection.immutable._\n\nobject RemoveExtraOne {\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val N = sc.nextInt()\n val p = for (i <- 0.until(N)) yield sc.nextInt()\n\n def process(i: Int, set: TreeSet[Int], candidates: TreeMap[Int, Int]): Int = {\n if (i == N) {\n if (candidates.size == 0) N else candidates.filter{case (_, freq) => freq == candidates.values.max}.keys.min\n }\n else {\n val higherSet = set.from(p(i) + 1)\n if (higherSet.size == 1) {\n val higherElement = higherSet.firstKey\n process(i + 1, set + p(i), candidates.updated(higherElement, 1 + candidates.getOrElse(higherElement, 0)))\n }\n else process(i + 1, set + p(i), candidates)\n }\n }\n\n val answer = process(0, TreeSet.empty, TreeMap.empty)\n println(answer)\n }\n}\n"}, {"source_code": "\nimport java.util.Scanner\n\nimport scala.collection.immutable._\n\nobject RemoveExtraOne {\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val N = sc.nextInt()\n val p = for (i <- 0.until(N)) yield sc.nextInt()\n\n def process(i: Int, set: TreeSet[Int], candidates: TreeMap[Int, Int], hopeless: TreeSet[Int]): Int = {\n if (i == N) {\n if (candidates.size == 0) {\n if (hopeless.size == 0) 1 else hopeless.min\n } else candidates.filter{case (_, freq) => freq == candidates.values.max}.keys.min\n }\n else {\n val higherSet = set.from(p(i) + 1)\n if (higherSet.size == 1) {\n val higherElement = higherSet.firstKey\n process(i + 1, set + p(i), candidates.updated(higherElement, 1 + candidates.getOrElse(higherElement, 0)), hopeless)\n }\n else if (higherSet.size > 1) process(i + 1, set + p(i), candidates, hopeless + p(i))\n else process(i + 1, set + p(i), candidates, hopeless)\n }\n }\n\n val answer = process(0, TreeSet.empty, TreeMap.empty, TreeSet.empty)\n println(answer)\n }\n}\n"}], "src_uid": "c15ad483441864b3222eb62723b598e1"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println(n / 2 * n + (if (n % 2 != 0) (n + 1) / 2 else 0))\n println(Range(0, n).map(i => Range(0, n).map(j => if ((j + i) % 2 == 0) 'C' else '.').mkString).mkString(\"\\n\"))\n}\n\n\n//1.1.1\n//.1.1.\n//1.1.1\n//.1.1.\n//1.1.1", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _384A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val cb = (0 until n).map(i => if (i % 2 == 0) 'C' else '.').mkString(\"\")\n val wb = (0 until n).map(i => if (i % 2 == 1) 'C' else '.').mkString(\"\")\n val a = cb.count(i => i == 'C')\n val b = wb.count(i => i == 'C')\n\n var sum = 0\n for (i <- 0 until n)\n if (i % 2 == 0) sum = sum + a\n else sum = sum + b\n println(sum)\n for (i <- 0 until n)\n if (i % 2 == 0) println(cb)\n else println(wb)\n}\n"}, {"source_code": "object A384 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val res = Array.fill(n)(Array.fill[Char](n)('.'))\n for(i <- 0 until n) {\n val start = if(i%2 == 0) 0 else 1\n for(j <- start until n by 2) {\n res(i)(j) = 'C'\n }\n }\n println(res.map(x => x.count(_ == 'C')).sum)\n println(res.map(_.mkString(\"\")).mkString(\"\\n\"))\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P384A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n\n val numC = N * N / 2 + N % 2\n out.println(numC)\n\n 0 until N foreach { i =>\n 0 until N foreach { j =>\n if (i % 2 == j % 2) out.print('C')\n else out.print('.')\n }\n out.println\n }\n \n out.close\n}\n"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _384A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val cb = (0 until n).map(i => if (i % 2 == 0) 'C' else '.').mkString(\"\")\n val wb = (0 until n).map(i => if (i % 2 == 1) 'C' else '.').mkString(\"\")\n\n for (i <- 0 until n)\n if (i % 2 == 0) println(cb)\n else println(wb)\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P384A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n\n 0 until N foreach { i =>\n 0 until N foreach { j =>\n if (i % 2 == j % 2) out.print('C')\n else out.print('.')\n }\n out.println\n }\n \n out.close\n}\n"}], "src_uid": "1aede54b41d6fad3e74f24a6592198eb"} {"source_code": "import java.io._\nimport java.util._\n\nimport scala.StringBuilder\nimport scala.collection.mutable\n\nobject D {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n case class Rectangle(width: Int, height: Int) {\n\n def normalize(): Rectangle = {\n new Rectangle(Math.min(width, height), Math.max(width, height))\n }\n\n def maximize(): Rectangle = {\n new Rectangle(Math.max(width, height), Math.min(width, height))\n }\n\n def rotate(): Rectangle = {\n new Rectangle(height, width)\n }\n\n }\n\n def getSecond(i: Int): Int = {\n i match {\n case 0 => 1\n case 1 => 2\n case 2 => 0\n }\n }\n\n def getThird(i: Int): Int = {\n i match {\n case 0 => 2\n case 1 => 0\n case 2 => 1\n }\n }\n\n def rectLetter(i: Int): String = {\n i match {\n case 0 => \"A\"\n case 1 => \"B\"\n case 2 => \"C\"\n }\n }\n\n def appendZeroes(s: String): String = {\n val sb = new StringBuilder()\n while (sb.length < 3 - s.length) {\n sb.append(\"0\")\n }\n sb.append(s).toString()\n }\n\n def rotate(rectangle: Rectangle, s: String, i: Int) = if (s.charAt(i) == '1') rectangle else rectangle.rotate()\n\n def checkRects(i: Int, rects: Array[Rectangle]): Boolean = {\n for (i <- 0 until 3) {\n for (k <- 0 to 8) {\n val s = appendZeroes(Integer.toBinaryString(k))\n val fst = rotate(rects(i), s, 0)\n val snd = rotate(rects(getSecond(i)), s, 1)\n val thrd = rotate(rects(getThird(i)), s, 2)\n if (fst.height == snd.width + thrd.width && fst.height == fst.width + snd.height && snd.height == thrd.height) {\n // output the result\n out.println(fst.height)\n for (j <- 0 until fst.height) {\n for (k <- 0 until fst.height) {\n if (j < snd.height) {\n if (k < snd.width) {\n out.print(rectLetter(getSecond(i)))\n } else {\n out.print(rectLetter(getThird(i)))\n }\n } else {\n out.print(rectLetter(i))\n }\n }\n out.println()\n }\n return true\n }\n }\n }\n false\n }\n\n def solve: Int = {\n val x1 = nextInt\n val y1 = nextInt\n val a = new Rectangle(x1, y1).normalize\n val a1 = new Rectangle(x1, y1).maximize\n val x2 = nextInt\n val y2 = nextInt\n val b = new Rectangle(x2, y2).normalize\n val b1 = new Rectangle(x2, y2).maximize\n val x3 = nextInt\n val y3 = nextInt\n val c = new Rectangle(x3, y3).normalize\n val c1 = new Rectangle(x3, y3).maximize\n if (a.height == b.height && b.height == c.height && a.width + b.width + c.width == a.height) {\n // output the result\n out.println(a.height)\n for (i <- 0 until a.height) {\n for (j <- 0 until a.height) {\n if (j < a.width) {\n out.print(\"A\")\n } else if (j < a.width + b.width) {\n out.print(\"B\")\n } else {\n out.print(\"C\")\n }\n }\n out.println()\n }\n return 0\n }\n val rects = new Array[Rectangle](3)\n rects(0) = a\n rects(1) = b\n rects(2) = c\n val reversedRects = new Array[Rectangle](3)\n reversedRects(0) = a1\n reversedRects(1) = b1\n reversedRects(2) = c1\n for (i <- 0 until 3) {\n if (checkRects(i, rects)) {\n return 0\n }\n }\n for (i <- 0 until 3) {\n if (checkRects(i, reversedRects)) {\n return 0\n }\n }\n out.println(-1)\n return 0\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val data = in.next().split(\" \").map(_.toInt).grouped(2).flatMap(_.sorted.reverse)\n val t = data.grouped(2).map(_.toList).toList.zip(List(\"A\", \"B\", \"C\")).map{\n case(List(a, b), c) => (a, b, c)\n }\n var Seq((y1, x1, ch1), (y2, x2, ch2), (y3, x3, ch3)) = t.sorted.reverse.toSeq\n\n val a = y1\n val first = (1 to x1).map(_ => ch1 * a).toList\n\n //разместим a\n val second =\n if (x1 * y1 + x2 * y2 + x3 * y3 != a * a) None\n else if (y2 == a && y3 != a) None\n else if (y2 == a)\n Some(\n (1 to x2).map(_ => ch2 * a).toList :::\n (1 to x3).map(_ => ch3 * a).toList)\n else {\n val b = a - x1\n if (x2 == y3 && x2 == b && x3 + y2 == a)\n Some((1 to b).map(_ => ch2 * y2 + ch3 * x3).toList)\n else if (x3 == y2 && y2 == b && x2 + y3 == a)\n Some((1 to b).map(_ => ch2 * x2 + ch3 * y3).toList)\n else if (y2 + y3 == a && x2 == x3 && x2== b)\n Some((1 to b).map(_ => ch2 * y2 + ch3 * y3).toList)\n else if (x2 + x3 == a && y2 == y3 && y2 == b)\n Some((1 to b).map(_ => ch2 * x2 + ch3 * x3).toList)\n else\n None\n }\n if (second.isEmpty)\n println(-1)\n else {\n println(a)\n println(second.map(t => first ::: t).get.mkString(\"\\n\"))\n }\n\n}\n"}, {"source_code": "object _581D extends App {\n val scanner = new java.util.Scanner(System.in)\n val logos = Seq(\"A\", \"B\", \"C\") map {c => c -> Seq(scanner.nextInt, scanner.nextInt)}\n var rows: Seq[String] = Nil\n for {\n Seq((c1, p), (c2, q), (c3, r)) <- logos.permutations if rows.isEmpty\n Seq(x1, y1) <- p.permutations\n Seq(x2, y2) <- q.permutations\n Seq(x3, y3) <- r.permutations\n } {\n if ((y1 == y2) && (y2 == y3) && ((x1 + x2 + x3) == y3)) {\n rows = Seq.fill(x1)(c1 * y1) ++ Seq.fill(x2)(c2 * y2) ++ Seq.fill(x3)(c3 * y3)\n } else if ((x2 == x3) && (y1 == y2 + y3) && (x1 + x2) == y1) {\n rows = Seq.fill(x1)(c1 * y1) ++ Seq.fill(x2)((c2 * y2) + (c3 * y3))\n }\n }\n println(if (rows.isEmpty) -1 else rows.length)\n rows foreach println\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _581D extends CodeForcesApp[Option[List[String]]]({scanner => import scanner._\n def rotate(p: (Int, Int)) = List(p, p.swap)\n\n val (ax, ay, bx, by, cx, cy) = (nextInt, nextInt, nextInt, nextInt, nextInt, nextInt)\n\n val stacks = for {\n (x1, y1) <- rotate(ax, ay)\n (x2, y2) <- rotate(bx, by) if y2 == y1\n (x3, y3) <- rotate(cx, cy) if y3 == y2\n if (x1 + x2 + x3) == y3\n } yield ((x1, y1), (x2, y2), (x3, y3))\n\n def block(d: (Int, Int), char: String) = {\n val (x, y) = d\n List.fill(x)(char * y)\n }\n\n val logos = List(\"A\" -> (ax, ay), \"B\" -> (bx, by), \"C\" -> (cx, cy))\n lazy val sided = for {\n Seq((c1, p), (c2, q), (c3, r)) <- logos.permutations\n (x1, y1) <- rotate(p)\n (x2, y2) <- rotate(q)\n (x3, y3) <- rotate(r)\n if (x2 == x3) && (y1 == y2 + y3) && (x1 + x2) == y1\n } yield (c1 -> (x1, y1), c2 -> (x2, y2), c3 -> (x3, y3))\n\n stacks match {\n case (a, b, c) :: _ => Some(block(a, \"A\") ::: block(b, \"B\") ::: block(c, \"C\"))\n\n case _ => sided.toSeq.headOption map {case ((c1, p), (c2, (x2, y2)), (c3, (x3, y3))) =>\n block(p, c1) ::: List.fill(x2)((c2 * y2) + (c3 * y3))\n }\n }\n}) {\n override def format(result: Result) = result match {\n case None => \"-1\"\n case Some(block) => s\"\"\"\n |${block.size}\n |${block.mkString(\"\\n\")}\n \"\"\".stripMargin\n }\n}\n/********************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)\n final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main extends App {\n\n val sc = new Scanner(System.in)\n val x1 = sc.nextInt\n val y1 = sc.nextInt\n val x2 = sc.nextInt\n val y2 = sc.nextInt\n val x3 = sc.nextInt\n val y3 = sc.nextInt\n\n var a = false\n\n def print1(x: Int,\n y: Int,\n z: Int,\n pos: Seq[Char]\n ) {\n println(x)\n (1 to y).foreach(_ => {(1 to x).foreach(_ => print(pos(0))); println})\n (1 to z).foreach(_ => {(1 to x).foreach(_ => print(pos(1))); println})\n (1 to (x - y - z)).foreach(_ => {(1 to x).foreach(_ => print(pos(2))); println})\n }\n\n def print2(x: Int,\n y: Int,\n z: Int,\n pos: Seq[Char]\n ) {\n println(x)\n (1 to y).foreach(_ => {(1 to x).foreach(_ => print(pos(0))); println})\n (1 to (x - y)).foreach(_ => {\n (1 to z).foreach(_ => print(pos(1)))\n (1 to (x - z)).foreach(_ => print(pos(2)))\n println\n })\n }\n\n def check1(p1: (Int, Int),\n p2: (Int, Int),\n p3: (Int, Int),\n pos: Seq[Char]\n ) {\n def c1 =\n (p1._1 == p2._1 && p1._1 == p3._1) &&\n (p1._2 + p2._2 + p3._2 == p1._1) &&\n ({print1(p1._1, p1._2, p2._2, pos); true})\n def c2 =\n (p2._2 == p3._2) && (p2._2 + p1._2 == p1._1) &&\n (p2._1 + p3._1 == p1._1) &&\n ({print2(p1._1, p1._2, p2._1, pos); true})\n\n a = a || c1 || c2\n }\n\n def check(p1: (Int, Int),\n p2: (Int, Int),\n p3: (Int, Int)\n ) = {\n check1(p1, p2, p3, Seq('A', 'B', 'C'))\n check1(p1, p3, p2, Seq('A', 'C', 'B'))\n check1(p2, p1, p3, Seq('B', 'A', 'C'))\n check1(p2, p3, p1, Seq('B', 'C', 'A'))\n check1(p3, p1, p2, Seq('C', 'A', 'B'))\n check1(p3, p2, p1, Seq('C', 'B', 'A'))\n }\n\n def c = {\n val p1 = (x1, y1)\n val p2 = (x2, y2)\n val p3 = (x3, y3)\n val s1 = Seq(p1, p1.swap)\n val s2 = Seq(p2, p2.swap)\n val s3 = Seq(p3, p3.swap)\n\n s1.foreach(a => {\n s2.foreach(b => {\n s3.foreach(c => {\n check(a, b, c)\n })\n })\n })\n }\n\n c\n if (!a)\n println(-1)\n}\n"}, {"source_code": "import java.io._\nimport scala.collection.mutable.Map\n\n//581D\nobject D_ThreeLogos {\n \n def main(args: Array[String]): Unit = {\n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n\n val line1 = br.readLine().split(\" \")\n// val line1 = \"5 1 2 5 5 2\".split(\" \")\n// val line1 = \"4 4 2 6 4 2\".split(\" \")\n \n \n val coo = Array[Array[Int]]( Array(Integer.parseInt(line1(0)),Integer.parseInt(line1(1))),\n Array(Integer.parseInt(line1(2)),Integer.parseInt(line1(3))),\n Array(Integer.parseInt(line1(4)),Integer.parseInt(line1(5)))\n )\n \n val x1 = Integer.parseInt(line1(0))\n val y1 = Integer.parseInt(line1(1))\n val x2 = Integer.parseInt(line1(0))\n val y2 = Integer.parseInt(line1(1))\n val x3 = Integer.parseInt(line1(0))\n val y4 = Integer.parseInt(line1(1))\n \n val layouts = Array(\"123\", \"132\", \"213\", \"231\", \"312\", \"321\")\n \n for (i <- layouts) {\n rows(i)\n }\n println(-1)\n System.exit(0)\n \n def rows(lay:String) {\n flips(lay)\n flips(lay.replace(\"1\", \"1.\"))\n flips(lay.replace(\"2\", \"2.\"))\n flips(lay.replace(\"1\", \"1.\").replace(\"2\", \"2.\"))\n }\n \n def flips(row:String) {\n check(row)\n check(row.replace(\"\", \"\"))\n check(row.replace(\"1\", \"1a\"))\n check(row.replace(\"2\", \"2a\"))\n check(row.replace(\"3\", \"3a\"))\n check(row.replace(\"1\", \"1a\").replace(\"2\", \"2a\"))\n check(row.replace(\"2\", \"2a\").replace(\"3\", \"3a\"))\n check(row.replace(\"1\", \"1a\").replace(\"3\", \"3a\"))\n check(row.replace(\"1\", \"1a\").replace(\"2\", \"2a\").replace(\"3\", \"3a\"))\n }\n \n def check(comb:String) {\n// println(\"variant: \" + comb)\n if (comb == \"1a23\") {\n// println(\"here\")\n }\n val grid = comb.split('.')\n val line0 = grid(0)\n var line0Li = parseLine(line0).reverse.toArray\n var width = 0\n for (i <- line0Li) {\n val ind = Integer.parseInt(i(0).toString()) - 1\n if (i.length() == 1) {\n width += coo(ind)(0)\n } else {\n width += coo(ind)(1)\n }\n }\n \n var pixCounter = 0\n val result = Array.ofDim[Char](width, width)\n var y = 0\n for (line <- grid) {\n val figNames = parseLine(line).reverse.toArray\n var x = 0\n for (i <- figNames) {\n val fig = getFig(i)\n if (x + fig._1 > width) return\n if (y + fig._2 > width) return\n \n //render\n for (fy <- 0 until fig._2) {\n for (fx <- 0 until fig._1) {\n// println(\"---- \" + result(fx)(fy).toInt)\n val pixX = x + fx\n val pixY = y + fy\n if (result(pixY)(pixX).toInt != 0) {\n return\n }\n val dispChar = getFigChar(i)\n result(pixY)(pixX) = dispChar\n pixCounter += 1\n }\n }\n x += fig._1\n\n\n }\n y += getFig(figNames(0))._2\n }\n\n //DELME\n// printResult\n\n //success\n if (pixCounter == width * width) {\n println(width)\n printResult\n System.exit(0)\n }\n\n def printResult() {\n for (x <- 0 until result.length) {\n for (y <- 0 until result.length) {\n print(result(y)(x))\n }\n println\n }\n } \n }\n \n def getFigChar(name:String): Char = {\n if (name.startsWith(\"1\")) 'A'\n else if (name.startsWith(\"2\")) 'B'\n else if (name.startsWith(\"3\")) 'C'\n else 'X'\n }\n \n def getFig(name:String): (Int, Int) = {\n val ind = Integer.parseInt(name(0).toString) - 1\n if (name.length() == 1) {\n (coo(ind)(0), coo(ind)(1)) \n } else {\n (coo(ind)(1), coo(ind)(0))\n }\n }\n \n def parseLine(line:String):List[String] = {\n var res = List[String]()\n var cur = line(0).toString()\n for (i <- 1 until line.length()) {\n if (line(i) == 'a') {\n res = (cur + 'a') :: res\n cur = null\n } else {\n if (cur != null) {\n res = cur :: res\n }\n cur = line(i).toString\n }\n }\n if (cur != null) {\n res = cur :: res\n }\n res\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.language.postfixOps\nimport scala.math.sqrt\n\nobject TaskD extends App {\n type Board = Array[Array[Char]]\n val sc = new Scanner(System.in)\n val logos = 'A' to 'C' map {\n Logo(sc.nextInt, sc.nextInt, _)\n }\n\n val sq = logos.map(l => l.x * l.y).sum\n val sqr = sqrt(sq) toInt\n\n if (sqr * sqr != sq) {\n println(-1)\n } else {\n val a = sqr\n val board = Array.fill(a)(new Array[Char](a))\n if (logos.flatMap(l => List(l.x, l.y)).count(_ > a) > 0) {\n println(-1)\n } else {\n val res = findBestMatch(board, 0, 0, logos)\n if (res) {\n println(a)\n println(board.map(_.mkString).mkString(\"\\n\"))\n } else {\n println(-1)\n }\n }\n }\n\n def findBestMatch(board: Board, iOff: Int, jOff: Int, logos: Seq[Logo]): Boolean = {\n if (logos.nonEmpty) {\n val (w, h) = (board(0).length - jOff, board.length - iOff)\n (logos ++ logos.map(_.rotate)).find(l => l.x == w || l.y == h).exists { best =>\n val (io, jo) = fillBoard(board, iOff, jOff, best)\n findBestMatch(board, io, jo, logos diff Seq(best, best.rotate))\n }\n } else {\n true\n }\n }\n\n def fillBoard(board: Board, iOff: Int, jOff: Int, logo: Logo) = {\n val (iEnd, jEnd) = (iOff + logo.y, jOff + logo.x)\n iOff until iEnd foreach (i => jOff until jEnd foreach (j => board(i)(j) = logo.char))\n if (iEnd == board.length) (iOff, jEnd) else (iEnd, jOff)\n }\n\n case class Logo(x: Int, y: Int, char: Char) {\n def rotate = Logo(y, x, char)\n }\n\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val data = in.next().split(\" \").map(_.toInt).grouped(2).flatMap(_.sorted.reverse)\n val t = data.grouped(2).map(_.toList).toList.zip(List(\"A\", \"B\", \"C\")).map{\n case(List(a, b), c) => (a, b, c)\n }\n var Seq((y1, x1, ch1), (y2, x2, ch2), (y3, x3, ch3)) = t.sorted.reverse.toSeq\n\n val a = y1\n if (x1 * y1 + x2 * y2 + x3 * y3 != a * a) {\n println(-1)\n }\n else {\n //разместим a\n if (y2 == a) {\n if (y3 == a) {\n //разместим a b и с горизонтально\n println(((1 to x1).map(_ => ch1 * a).toList :::\n (1 to x2).map(_ => ch2 * a).toList :::\n (1 to x3).map(_ => ch3 * a).toList).mkString(\"\\n\"))\n }\n else\n println(-1)\n } else {\n val b = a - x1\n if (x2 == y3 && x2 == b && x3 + y2 == a) {\n println(((1 to x1).map(_ => ch1 * a).toList :::\n (1 to b).map(_ => ch2 * y2 + ch3 * x3).toList).mkString(\"\\n\"))\n }\n else if (x3 == y2 && y2 == b && x2 + y3 == a){\n\n println(((1 to x1).map(_ => ch1 * a).toList :::\n (1 to b).map(_ => ch2 * x2 + ch3 * y3 ).toList).mkString(\"\\n\"))\n }\n else if (y2 + y3 == a && x2 == x3 && x2== b){\n println(((1 to x1).map(_ => ch1 * a).toList :::\n (1 to b).map(_ => ch2 * y2 + ch3 * y3 ).toList).mkString(\"\\n\"))\n }\n else if (x2 + x3 == a && y2 == y3 && y2 == b){\n println(((1 to x1).map(_ => ch1 * a).toList :::\n (1 to b).map(_ => ch2 * x2 + ch3 * x3 ).toList).mkString(\"\\n\"))\n }\n else {\n println(-1)\n }\n }\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val data = in.next().split(\" \").map(_.toInt).grouped(2).flatMap(_.sorted.reverse)\n val t = data.grouped(2).map(_.toList).toList.zip(List(\"A\", \"B\", \"C\")).map{\n case(List(a, b), c) => (a, b, c)\n }\n var Seq((y1, x1, ch1), (y2, x2, ch2), (y3, x3, ch3)) = t.sorted.reverse.toSeq\n\n val a = y1\n println(a)\n if (x1 * y1 + x2 * y2 + x3 * y3 != a * a) {\n println(-1)\n }\n else {\n //разместим a\n if (y2 == a) {\n if (y3 == a) {\n //разместим a b и с горизонтально\n println(((1 to x1).map(_ => ch1 * a).toList :::\n (1 to x2).map(_ => ch2 * a).toList :::\n (1 to x3).map(_ => ch3 * a).toList).mkString(\"\\n\"))\n }\n else\n println(-1)\n } else {\n val b = a - x1\n if (x2 == y3 && x2 == b && x3 + y2 == a) {\n println(((1 to x1).map(_ => ch1 * a).toList :::\n (1 to b).map(_ => ch2 * y2 + ch3 * x3).toList).mkString(\"\\n\"))\n }\n else if (x3 == y2 && y2 == b && x2 + y3 == a){\n\n println(((1 to x1).map(_ => ch1 * a).toList :::\n (1 to b).map(_ => ch2 * x2 + ch3 * y3 ).toList).mkString(\"\\n\"))\n }\n else if (y2 + y3 == a && x2 == x3 && x2== b){\n println(((1 to x1).map(_ => ch1 * a).toList :::\n (1 to b).map(_ => ch2 * y2 + ch3 * y3 ).toList).mkString(\"\\n\"))\n }\n else if (x2 + x3 == a && y2 == y3 && y2 == b){\n println(((1 to x1).map(_ => ch1 * a).toList :::\n (1 to b).map(_ => ch2 * x2 + ch3 * x3 ).toList).mkString(\"\\n\"))\n }\n else {\n println(-1)\n }\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject D {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n case class Rectangle(width: Int, height: Int) {\n\n def normalize(): Rectangle = {\n new Rectangle(Math.min(width, height), Math.max(width, height))\n }\n }\n\n def getSecond(i: Int): Int = {\n i match {\n case 0 => 1\n case 1 => 2\n case 2 => 0\n }\n }\n\n def getThird(i: Int): Int = {\n i match {\n case 0 => 2\n case 1 => 0\n case 2 => 1\n }\n }\n\n def rectLetter(i: Int): String = {\n i match {\n case 0 => \"A\"\n case 1 => \"B\"\n case 2 => \"C\"\n }\n }\n\n def solve: Int = {\n val x1 = nextInt\n val y1 = nextInt\n val a = new Rectangle(x1, y1).normalize\n val x2 = nextInt\n val y2 = nextInt\n val b = new Rectangle(x2, y2).normalize\n val x3 = nextInt\n val y3 = nextInt\n val c = new Rectangle(x3, y3).normalize\n if (a.height == b.height && b.height == c.height && a.width + b.width + c.width == a.height) {\n // output the result\n for (i <- 0 until a.height) {\n for (j <- 0 until a.height) {\n if (j < a.width) {\n out.print(\"A\")\n } else if (j < a.width + b.width) {\n out.print(\"B\")\n } else {\n out.print(\"C\")\n }\n }\n out.println()\n }\n return 0\n }\n val rects = new Array[Rectangle](3)\n rects(0) = a\n rects(1) = b\n rects(2) = c\n for (i <- 0 until 3) {\n val fst = rects(i)\n val snd = rects(getSecond(i))\n val thrd = rects(getThird(i))\n if (fst.height == snd.width + thrd.width && fst.height == fst.width + snd.height && snd.height == thrd.height) {\n for (j <- 0 until fst.height) {\n for (k <- 0 until fst.height) {\n if (j < snd.height) {\n if (k < snd.width) {\n out.print(rectLetter(getSecond(i)))\n } else {\n out.print(rectLetter(getThird(i)))\n }\n } else {\n out.print(rectLetter(i))\n }\n }\n out.println()\n }\n return 0\n }\n }\n out.println(-1)\n return 0\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject D {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n case class Rectangle(width: Int, height: Int) {\n\n def normalize(): Rectangle = {\n new Rectangle(Math.min(width, height), Math.max(width, height))\n }\n }\n\n def getSecond(i: Int): Int = {\n i match {\n case 0 => 1\n case 1 => 2\n case 2 => 0\n }\n }\n\n def getThird(i: Int): Int = {\n i match {\n case 0 => 2\n case 1 => 0\n case 2 => 1\n }\n }\n\n def rectLetter(i: Int): String = {\n i match {\n case 0 => \"A\"\n case 1 => \"B\"\n case 2 => \"C\"\n }\n }\n\n def solve: Int = {\n val x1 = nextInt\n val y1 = nextInt\n val a = new Rectangle(x1, y1).normalize\n val x2 = nextInt\n val y2 = nextInt\n val b = new Rectangle(x2, y2).normalize\n val x3 = nextInt\n val y3 = nextInt\n val c = new Rectangle(x3, y3).normalize\n if (a.height == b.height && b.height == c.height && a.width + b.width + c.width == a.height) {\n // output the result\n out.println(a.height)\n for (i <- 0 until a.height) {\n for (j <- 0 until a.height) {\n if (j < a.width) {\n out.print(\"A\")\n } else if (j < a.width + b.width) {\n out.print(\"B\")\n } else {\n out.print(\"C\")\n }\n }\n out.println()\n }\n return 0\n }\n val rects = new Array[Rectangle](3)\n rects(0) = a\n rects(1) = b\n rects(2) = c\n for (i <- 0 until 3) {\n val fst = rects(i)\n val snd = rects(getSecond(i))\n val thrd = rects(getThird(i))\n if (fst.height == snd.width + thrd.width && fst.height == fst.width + snd.height && snd.height == thrd.height) {\n // output the result\n out.println(fst.height)\n for (j <- 0 until fst.height) {\n for (k <- 0 until fst.height) {\n if (j < snd.height) {\n if (k < snd.width) {\n out.print(rectLetter(getSecond(i)))\n } else {\n out.print(rectLetter(getThird(i)))\n }\n } else {\n out.print(rectLetter(i))\n }\n }\n out.println()\n }\n return 0\n }\n }\n out.println(-1)\n return 0\n }\n}\n"}, {"source_code": "import java.io._\nimport scala.collection.mutable.Map\n\n//581D\nobject D_ThreeLogos {\n \n def main(args: Array[String]): Unit = {\n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n\n val line1 = br.readLine().split(\" \")\n// val line1 = \"5 1 2 5 5 2\".split(\" \")\n// val line1 = \"4 4 2 6 4 2\".split(\" \")\n \n \n val coo = Array[Array[Int]]( Array(Integer.parseInt(line1(0)),Integer.parseInt(line1(1))),\n Array(Integer.parseInt(line1(2)),Integer.parseInt(line1(3))),\n Array(Integer.parseInt(line1(4)),Integer.parseInt(line1(5)))\n )\n \n val x1 = Integer.parseInt(line1(0))\n val y1 = Integer.parseInt(line1(1))\n val x2 = Integer.parseInt(line1(0))\n val y2 = Integer.parseInt(line1(1))\n val x3 = Integer.parseInt(line1(0))\n val y4 = Integer.parseInt(line1(1))\n \n val layouts = Array(\"123\", \"132\", \"213\", \"231\", \"312\", \"321\")\n \n for (i <- layouts) {\n rows(i)\n println(-1)\n }\n \n def rows(lay:String) {\n flips(lay)\n flips(lay.replace(\"1\", \"1.\"))\n flips(lay.replace(\"2\", \"2.\"))\n flips(lay.replace(\"1\", \"1.\").replace(\"2\", \"2.\"))\n }\n \n def flips(row:String) {\n check(row)\n check(row.replace(\"\", \"\"))\n check(row.replace(\"1\", \"1a\"))\n check(row.replace(\"2\", \"2a\"))\n check(row.replace(\"3\", \"3a\"))\n check(row.replace(\"1\", \"1a\").replace(\"2\", \"2a\"))\n check(row.replace(\"2\", \"2a\").replace(\"3\", \"3a\"))\n check(row.replace(\"1\", \"1a\").replace(\"3\", \"3a\"))\n check(row.replace(\"1\", \"1a\").replace(\"2\", \"2a\").replace(\"3\", \"3a\"))\n }\n \n def check(comb:String) {\n// println(\"variant: \" + comb)\n if (comb == \"1a23\") {\n// println(\"here\")\n }\n val grid = comb.split('.')\n val line0 = grid(0)\n var line0Li = parseLine(line0).reverse.toArray\n var width = 0\n for (i <- line0Li) {\n val ind = Integer.parseInt(i(0).toString()) - 1\n if (i.length() == 1) {\n width += coo(ind)(0)\n } else {\n width += coo(ind)(1)\n }\n }\n \n var pixCounter = 0\n val result = Array.ofDim[Char](width, width)\n var y = 0\n for (line <- grid) {\n val figNames = parseLine(line).reverse.toArray\n var x = 0\n for (i <- figNames) {\n val fig = getFig(i)\n if (x + fig._1 > width) return\n if (y + fig._2 > width) return\n \n //render\n for (fy <- 0 until fig._2) {\n for (fx <- 0 until fig._1) {\n// println(\"---- \" + result(fx)(fy).toInt)\n val pixX = x + fx\n val pixY = y + fy\n if (result(pixY)(pixX).toInt != 0) {\n return\n }\n val dispChar = getFigChar(i)\n result(pixY)(pixX) = dispChar\n pixCounter += 1\n }\n }\n x += fig._1\n\n\n }\n y += getFig(figNames(0))._2\n }\n\n //DELME\n// printResult\n\n //success\n if (pixCounter == width * width) {\n println(width)\n printResult\n System.exit(0)\n }\n\n def printResult() {\n for (x <- 0 until result.length) {\n for (y <- 0 until result.length) {\n print(result(y)(x))\n }\n println\n }\n } \n }\n \n def getFigChar(name:String): Char = {\n if (name.startsWith(\"1\")) 'A'\n else if (name.startsWith(\"2\")) 'B'\n else if (name.startsWith(\"3\")) 'C'\n else 'X'\n }\n \n def getFig(name:String): (Int, Int) = {\n val ind = Integer.parseInt(name(0).toString) - 1\n if (name.length() == 1) {\n (coo(ind)(0), coo(ind)(1)) \n } else {\n (coo(ind)(1), coo(ind)(0))\n }\n }\n \n def parseLine(line:String):List[String] = {\n var res = List[String]()\n var cur = line(0).toString()\n for (i <- 1 until line.length()) {\n if (line(i) == 'a') {\n res = (cur + 'a') :: res\n cur = null\n } else {\n if (cur != null) {\n res = cur :: res\n }\n cur = line(i).toString\n }\n }\n if (cur != null) {\n res = cur :: res\n }\n res\n }\n }\n}\n"}], "src_uid": "2befe5da2df57d23934601cbe4d4f151"} {"source_code": "\nobject A extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n// val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val n = in.nextInt()\n\n n.times {\n val x = in.nextInt()\n val y = in.nextInt()\n val k = in.nextInt()\n\n val r = (k - y) / x\n println((r * x) + y)\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}", "positive_code": [{"source_code": "//package codeforces.contests._1374\n\n/*\nhttps://codeforces.com/contest/1374/problem/A\n */\nobject RequiredRemainder {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt()) {\n val Array(x, y, n) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val maxN = {\n val r = n % x\n val mN = n - r + y\n if (mN > n) mN - x else mN\n }\n\n println(maxN)\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject CF653_A extends App {\n val t = readInt()\n for (_ <- 0 until t) {\n val xyn = readLine()\n val tmp = xyn.split(' ').map(_.toInt)\n var (x, y, n) = (tmp(0), tmp(1), tmp(2))\n\n// println(x, y, n)\n// println(List(1, 2, 3))\n// val (x, y, n) = new Tuple3(: _*)\n\n println(n - (n - y) % x)\n// println((n - y) / x)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CF653A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CF653A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val x = ni()\n val y = ni()\n val n = ni()\n\n val r = n / x\n if(r * x + y <= n) out.println(r * x + y)\n else out.println((r-1)*x + y)\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nobject Main {\n def main(args: Array[String]) {\n val T = readLine.split(\" \")(0).toInt\n for(cas <- 0 until T) {\n val Line = readLine.split(\" \").map(\n item => item.toInt\n )\n val x = Line(0)\n val y = Line(1)\n val n = Line(2)\n var r = n / x * x + y\n if(r > n) {\n r -= x\n }\n println(r)\n }\n }\n}"}], "negative_code": [], "src_uid": "2589e832f22089fac9ccd3456c0abcec"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new A619(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass A619(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val (a,b,c) = (ns(), ns(), ns())\n var oops = false\n REP(c.length) { i =>\n if(c.charAt(i) != b.charAt(i) && c.charAt(i) != a.charAt(i)) oops = true\n }\n if(oops) out.println(\"NO\")\n else out.println(\"YES\")\n }\n }\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val n = in.nextInt()\n (1 to n).foreach{ _ =>\n val astr = in.next\n val bstr = in.next\n val cstr = in.next\n val isOk = astr.zip(bstr).zip(cstr).forall{ case ((a,b),c) => ok(a,b,c)}\n out.println(if(isOk) \"YES\" else \"NO\")\n }\n }\n def ok(a: Char, b: Char, c: Char): Boolean = {\n b == c || a == c\n }\n\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new A619(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = false\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass A619(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val (a,b,c) = (ns(), ns(), ns())\n var oops = false\n REP(c.length) { i =>\n if(c.charAt(i) != b.charAt(i) && c.charAt(i) != a.charAt(i)) oops = true\n }\n if(oops) out.println(\"NO\")\n else out.println(\"YES\")\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new A619(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = System.getenv(\"ONLINE_JUDGE\") != null\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass A619(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val (a,b,c) = (ns(), ns(), ns())\n if(a == b) {\n out.println(\"YES\")\n } else {\n var oops = false\n REP(c.length) { i =>\n if(c.charAt(i) != b.charAt(i) && c.charAt(i) != a.charAt(i)) oops = true\n }\n if(oops) out.println(\"NO\")\n else out.println(\"YES\")\n }\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new A619(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass A619(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val (a,b,c) = (ns(), ns(), ns())\n if(a == b) {\n out.println(\"YES\")\n } else {\n var oops = false\n REP(c.length) { i =>\n if(c.charAt(i) != b.charAt(i) && c.charAt(i) != a.charAt(i)) oops = true\n }\n if(oops) out.println(\"NO\")\n else out.println(\"YES\")\n }\n }\n }\n}\n"}], "src_uid": "08679e44ee5d3c3287230befddf7eced"} {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, a, b, c, d) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val l = n * (a - b)\n val r = n * (a + b)\n\n if (r >= c - d && l <= c + d) println(\"YES\")\n else println(\"NO\")\n }\n}", "positive_code": [{"source_code": "object App {\n def main(args: Array[String]): Unit = {\n val t = scala.io.StdIn.readInt()\n (for (i <- 1 to t) yield {\n val Array(n, a, b, c, d): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val grLeft = (a - b) * n\n val grRight = (a + b) * n\n grLeft <= (c + d) && grRight >= (c - d)\n }).map(x => {\n if (x) \"YES\"\n else \"NO\"\n }).foreach{\n println(_)\n }\n }\n}"}], "negative_code": [], "src_uid": "30cfce44a7a0922929fbe54446986748"} {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject Contest1313C2 {\n\n def floorsToTheLeft(m: Array[Long]): Vector[Long] = {\n val closestLowerOnTheLeft = m.foldLeft(Vector.empty[Int]) {\n case (r, _) =>\n @tailrec\n def findNext(i: Int): Int = {\n val j = if (r.length > i) r(i) else i - 1\n if (j < 0 || m(j) < m(r.length)) j else findNext(j)\n }\n\n r :+ findNext(r.length)\n }\n closestLowerOnTheLeft.foldLeft(Vector.empty[Long]) {\n case (v, next) => v :+ (m(v.length) * (v.length - next) + (if (next < 0) 0 else v(next)))\n }\n }\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readLine().trim.toLong\n val m = StdIn.readLine().trim.split(\"\\\\s+\").map(_.toLong)\n val vLeft: Vector[Long] = floorsToTheLeft(m)\n val vRight = floorsToTheLeft(m.reverse).reverse\n val center = (vLeft, vRight, m).zipped.map(_ + _ - _).zipWithIndex.maxBy(_._1)._2\n val result = m.take(center).foldRight(Vector(m(center))) { case (mi, v) => math.min(mi, v.head) +: v } ++\n m.drop(center + 1).foldLeft(Vector(m(center))) { case (v, mi) => v :+ math.min(v.last, mi) }.drop(1)\n println(result.mkString(\" \"))\n }\n}\n", "positive_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\nimport scala.math.min\n\nobject Contest1313C2 {\n\n def floorsToTheLeft(m: Array[Long]): Vector[Long] = {\n @tailrec\n def findNext(r: Vector[Int], i: Int): Int = if (i < 0 || m(i) < m(r.length)) i else findNext(r, r(i))\n\n val closestLowerOnTheLeft = m.foldLeft(Vector.empty[Int]) {\n case (r, _) => r :+ findNext(r, r.length - 1)\n }\n closestLowerOnTheLeft.foldLeft(Vector.empty[Long]) {\n case (v, next) => v :+ (m(v.length) * (v.length - next) + (if (next < 0) 0 else v(next)))\n }\n }\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readLine().trim.toLong\n val m = StdIn.readLine().trim.split(\"\\\\s+\").map(_.toLong)\n val vLeft = floorsToTheLeft(m)\n val vRight = floorsToTheLeft(m.reverse).reverse\n val center = (vLeft, vRight, m).zipped.map( _ + _ - _).zipWithIndex.maxBy(_._1)._2\n val result = m.take(center).scanRight(m(center))(min) ++ m.drop(center + 1).scanLeft(m(center))(min).drop(1)\n println(result.mkString(\" \"))\n }\n}"}], "negative_code": [{"source_code": "import scala.util.Random\n\ncase class SparseTable(blockSize: Int, blocks: Array[Int])\n\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val n = stdin.next().toInt\n// val n = 44905\n val data = stdin.next().split(' ').map(_.toLong)\n// val r = new Random(12)\n// val data = (0 until n).map(i => Math.abs(i).toLong).toArray\n var preparedArray = prepare(data)\n\n val heights = Array.ofDim[Long](n)\n\n val s1 = solve(data)\n println(heights.mkString(\" \"))\n\n def prepare(data: Array[Long]): SparseTable = {\n val blockSize = Math.sqrt(data.length).toInt\n SparseTable(blockSize, data.grouped(blockSize)\n .zipWithIndex.map(pair => pair._1.indices.minBy(i => pair._1(i)) + pair._2 * blockSize).toArray)\n }\n\n def solve(data: Array[Long]) {\n solve(data, 0, data.length - 1)\n }\n\n def solve(data: Array[Long], l: Int, r: Int) {\n if (l > r) 0\n else if (l == r) {\n heights(l) = data(l)\n data(l)\n }\n else {\n val minIndex = calcMinIndex(preparedArray, data, l, r)\n val leftElements = minIndex - l\n val rightElements = r - minIndex\n if (leftElements > rightElements) { // we have moreElements on the left side, lets minimize right\n (minIndex to r).foreach(i => heights(i) = data(minIndex))\n solve(data, l, minIndex - 1)\n }\n else {\n (l to minIndex).foreach(i => heights(i) = data(minIndex))\n solve(data, minIndex + 1, r)\n }\n }\n }\n\n def calcMinIndex(sparseTable: SparseTable, data: Array[Long], l: Int, r: Int): Int = {\n val firstBlock = l / sparseTable.blockSize + (if (l % sparseTable.blockSize == 0) 0 else 1)\n val lastBlock = r / sparseTable.blockSize - (if (r % sparseTable.blockSize == (sparseTable.blockSize - 1)) 0 else 1)\n var minValue = Long.MaxValue\n var index = l\n if (firstBlock <= lastBlock) {\n val minIndex = sparseTable.blocks((firstBlock to lastBlock).minBy(blockIndex => data(sparseTable.blocks(blockIndex))))\n if (data(minIndex) < minValue) {\n minValue = data(minIndex)\n index = minIndex\n if (index < l || index > r) {\n throw new Exception(\"lol\")\n }\n }\n }\n if (l <= Math.min(r, (firstBlock) * sparseTable.blockSize)) {\n val minIndex = (l to Math.min(r, (firstBlock) * sparseTable.blockSize)).minBy(i => data(i))\n if (data(minIndex) < minValue) {\n minValue = data(minIndex)\n index = minIndex\n if (index < l || index > r) {\n throw new Exception(\"lol\")\n }\n }\n }\n if (Math.max(l, (lastBlock + 1) * sparseTable.blockSize) <= r) {\n val minIndex = (Math.max(l, (lastBlock + 1) * sparseTable.blockSize) to r).minBy(i => data(i))\n if (data(minIndex) < minValue) {\n minValue = data(minIndex)\n index = minIndex\n if (index < l || index > r) {\n throw new Exception(\"lol\")\n }\n }\n }\n index\n }\n}\n\n"}, {"source_code": "import scala.util.Random\n\ncase class SparseTable(blockSize: Int, blocks: Array[Int])\n\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n //val n = stdin.next().toInt\n val n = 9\n// val data = stdin.next().split(' ').map(_.toLong).toList\n val r = new Random(2)\n val data = (0 until n).map(_ => Math.abs(r.nextInt()).toLong).toList\n var preparedArray = prepare(data)\n\n val heights = Array.ofDim[Long](n)\n\n val s1 = solve(data)\n println(heights.mkString(\" \"))\n\n def prepare(data: List[Long]): SparseTable = {\n val blockSize = Math.sqrt(data.length).toInt\n SparseTable(blockSize, data.grouped(blockSize)\n .zipWithIndex.map(pair => pair._1.indices.minBy(i => pair._1(i)) + pair._2 * blockSize).toArray)\n }\n\n def solve(data: List[Long]): Long = {\n solve(data, 0, data.length - 1)\n }\n\n def solve(data: List[Long], l: Int, r: Int): Long = {\n if (l > r) 0\n else if (l == r) {\n heights(l) = data(l)\n data(l)\n }\n else {\n val minIndex = calcMinIndex(preparedArray, data, l, r)\n val calculateLeft = solve(data, l, minIndex - 1)\n val calculateRight = solve(data, minIndex + 1, r)\n val leftSum = calculateLeft + (r - minIndex + 1) * data(minIndex)\n val rightSum = calculateRight + (minIndex - l + 1) * data(minIndex)\n if (leftSum > rightSum) {\n (minIndex to r).foreach(i => heights(i) = data(minIndex))\n leftSum\n } else {\n (l to minIndex).foreach(i => heights(i) = data(minIndex))\n rightSum\n }\n }\n }\n\n def calcMinIndex(sparseTable: SparseTable, data: List[Long], l: Int, r: Int): Int = {\n val firstBlock = l / sparseTable.blockSize + (if (l % sparseTable.blockSize == 0) 0 else 1)\n val lastBlock = r / sparseTable.blockSize - (if (r % sparseTable.blockSize == (sparseTable.blockSize - 1)) 0 else 1)\n var minValue = Long.MaxValue\n var index = l\n if (firstBlock <= lastBlock) {\n val minIndex = sparseTable.blocks((firstBlock to lastBlock).minBy(blockIndex => data(sparseTable.blocks(blockIndex))))\n if (data(minIndex) < minValue) {\n minValue = data(minIndex)\n index = minIndex\n if (index < l || index > r) {\n throw new Exception(\"lol\")\n }\n }\n }\n if (l <= Math.min(r, (firstBlock) * sparseTable.blockSize)) {\n val minIndex = (l to Math.min(r, (firstBlock) * sparseTable.blockSize)).minBy(i => data(i))\n if (data(minIndex) < minValue) {\n minValue = data(minIndex)\n index = minIndex\n if (index < l || index > r) {\n throw new Exception(\"lol\")\n }\n }\n }\n if (Math.max(l, (lastBlock + 1) * sparseTable.blockSize) <= r) {\n val minIndex = (Math.max(l, (lastBlock + 1) * sparseTable.blockSize) to r).minBy(i => data(i))\n if (data(minIndex) < minValue) {\n minValue = data(minIndex)\n index = minIndex\n if (index < l || index > r) {\n throw new Exception(\"lol\")\n }\n }\n }\n index\n }\n}\n\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject Contest1313C2 {\n\n def floorsToTheLeft(m: Array[Int]): Vector[Int] = {\n val closestLowerOnTheLeft = m.foldLeft(Vector.empty[Int]) {\n case (r, _) =>\n @tailrec\n def findNext(i: Int): Int = {\n val j = if (r.length > i) r(i) else i - 1\n if (j < 0 || m(j) < m(r.length)) j else findNext(j)\n }\n\n r :+ findNext(r.length)\n }\n closestLowerOnTheLeft.foldLeft(Vector.empty[Int]) {\n case (v, next) => v :+ (m(v.length) * (v.length - next) + (if (next < 0) 0 else v(next)))\n }\n }\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readLine().trim.toInt\n val m = StdIn.readLine().trim.split(\"\\\\s+\").map(_.toInt)\n val vLeft: Vector[Int] = floorsToTheLeft(m)\n val vRight = floorsToTheLeft(m.reverse).reverse\n val center = (vLeft, vRight, m).zipped.map(_ + _ - _).zipWithIndex.maxBy(_._1)._2\n val result = m.take(center).foldRight(Vector(m(center))) { case (mi, v) => math.min(mi, v.head) +: v } ++\n m.drop(center + 1).foldLeft(Vector(m(center))) { case (v, mi) => v :+ math.min(v.last, mi) }.drop(1)\n println(result.mkString(\" \"))\n }\n}\n"}], "src_uid": "4d0a2617db2b85802d9cd0e9a89b924c"} {"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\n\nobject test6 extends App {\n val n=readInt\n for(_<-1 to n){\n println(solve(readLine))\n }\n \n def solveone(str:String):String={\n val list=str.split(\":\")\n for(i<-0 until list.size) \n list(i)=\"0\"*(4-list(i).size)+list(i)\n \n list.mkString(\":\")\n }\n \n def solve(str:String):String={\n val p=str.indexOfSlice(\"::\");\n if(p>=0){\n val left=solveone(str.substring(0,p))\n val right=solveone(str.substring(p+2))\n val count=8-(left.size+right.size+2)/5\n left+\":0000\"*count+\":\"+right\n }\n else solveone(str)\n }\n} \n\n\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport scala.collection.mutable._\nimport java.net.InetAddress\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n \n val n = sc.nextInt()\n\n for (_ <- 0 until n) {\n val ipv6 = InetAddress.getByName(sc.next).getHostAddress.split(\":\")\n println(ipv6.map(_.reverse.padTo(4, '0').reverse).mkString(\":\"))\n }\n}\n"}, {"source_code": "object Main extends App {\n\n import scala.io.{Source, StdIn}\n\n override def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n for (_ <- 1 to n) {\n val s = StdIn.readLine()\n var arr = s.split(\":\")\n if (s.startsWith(\"::\")) arr = arr.drop(1)\n if (arr.length != 8 && !arr.contains(\"\")) arr = arr ++ Seq(\"\")\n val res = arr.map(\n part =>\n if (part.isEmpty) {\n \"0000:\" * (9 - arr.length)\n }\n else {\n (\"0\" * (4 - part.length) + part) + \":\"\n }\n \n )\n println(res.mkString(\"\").dropRight(1))\n }\n }\n}"}], "negative_code": [{"source_code": "object Main extends App {\n\n import scala.io.{Source, StdIn}\n\n override def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n for (_ <- 1 to n) {\n val s = StdIn.readLine()\n var arr = s.split(\":\")\n if (arr.length != 8 && !arr.contains(\"\")) arr = arr ++ Seq(\"\")\n val res = arr.map(\n part =>\n if (part.isEmpty) {\n \"0000:\" * (9 - arr.length)\n }\n else {\n (\"0\" * (4 - part.length) + part) + \":\"\n }\n )\n println(res.mkString(\"\").dropRight(1))\n }\n }\n}"}], "src_uid": "20f69ee5f04c8cbb769be3ab646031ab"} {"source_code": "object Solution extends App {\n\n def compare(str1: List[Char], str2: List[Char], change1: Option[Char], change2: Option[Char], changed: Boolean): Boolean =\n if (str1.isEmpty && str2.isEmpty)\n change1.isEmpty\n else if (str1.head == str2.head)\n compare(str1.tail, str2.tail, change1, change2, changed)\n else if (changed)\n false\n else if (change1.isEmpty)\n compare(str1.tail, str2.tail, Some(str1.head), Some(str2.head), changed)\n else if (change1.get == str2.head && change2.get == str1.head)\n compare(str1.tail, str2.tail, None, None, true)\n else false\n\n\n val in = scala.io.Source.stdin.getLines()\n val str1 = in.next()\n val str2 = in.next()\n if (str1.length == str2.length && compare(str1.toCharArray.toList,\n str2.toCharArray.toList, None, None, false)) println(\"YES\")\n else println(\"NO\")\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val s1 = readLine()\n val s2 = readLine()\n if (s1.size != s2.size) println(\"NO\")\n else {\n val zipped = s1.zip(s2).zipWithIndex\n val filtered = zipped.filter(t => t._1._1 != t._1._2)\n if (filtered.size != 2) println(\"NO\")\n else {\n val t1 = filtered(0)\n val t2 = filtered(1)\n if (t1._1._1 == t2._1._2 && t2._1._1 == t1._1._2) println(\"YES\")\n else println(\"NO\")\n }\n }\n } \n}"}, {"source_code": "object A\n{\n def main(args: Array[String])\n {\n val str1 = readLine.toCharArray\n val str2 = readLine.toCharArray\n \n if(str1.length != str2.length) println(\"NO\")\n else\n {\n val n = str1.length\n if((0 until n).count(i => str1(i)!=str2(i)) != 2) println(\"NO\")\n else\n {\n var firstFound = false\n var car1 = ' '\n var car2 = ' '\n for(i <- 0 until n)\n {\n if(str1(i)!=str2(i))\n {\n if(!firstFound)\n {\n car1 = str1(i)\n car2 = str2(i)\n firstFound = true\n }\n else\n {\n if(car1==str2(i) && car2==str1(i)) println(\"YES\")\n else println(\"NO\")\n }\n }\n }\n }\n }\n }\n}\n"}, {"source_code": "import com.sun.org.apache.xpath.internal.operations.Bool\n\n/**\n * Created with IntelliJ IDEA.\n * User: Oleg\n * Date: 10.05.12\n * Time: 1:24\n * To change this template use File | Settings | File Templates.\n */\n\nobject A {\n val s1, s2 = readLine\n val (yes, no) = (\"YES\", \"NO\")\n\n def main(args: Array[String]) {\n println(good)\n }\n\n def good: String = {\n if (s1.length != s2.length) return no\n val inequality: (Int => Boolean) = (i => (s1(i) != s2(i)))\n val first = (0 until s1.length) find inequality\n val last = ((s1.length - 1) to 0 by -1) find inequality\n (first, last) match {\n case (Some(first), Some(last)) if first != last => {\n if (s1.substring(first + 1, last) != s2.substring(first + 1, last)) return no\n if (s1(first) != s2(last)) return no\n if (s1(last) != s2(first)) return no\n return yes\n }\n case _ => return no\n }\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val s1 = readLine()\n val s2 = readLine()\n if (s1.size != s2.size) println(\"NO\")\n else {\n val zipped = s1.zip(s2).zipWithIndex\n val filtered = zipped.filter(t => t._1._1 != t._1._2)\n if (filtered.size != 2) println(\"NO\")\n else {\n val t1 = filtered(0)\n val t2 = filtered(1)\n if (t1._2 + 1 != t2._2) println(\"NO\")\n else if (t1._1._1 == t2._1._2 && t2._1._1 == t1._1._2) println(\"YES\")\n else println(\"NO\")\n }\n }\n } \n}"}], "src_uid": "c659bdeda1c1da08cfc7f71367222332"} {"source_code": "import scala.io.StdIn._\nimport scala.collection.mutable\n\nobject B extends App {\n class Node {\n val conn = new mutable.HashSet[Int]\n }\n\n val n = readInt()\n val A = Array(Integer.MIN_VALUE) ++ readLine().split(\" \").map(_.toInt)\n val G = Array.fill(n + 1)(new Node)\n\n for (i <- 1 to n) {\n val next = if (i < n) i + 1 else 1\n if (i < n) {\n G(i).conn += next\n G(next).conn += i\n }\n if (i != A(i)) {\n G(i).conn += A(i)\n }\n// println(i + \" -> \" + G(i).conn.mkString(\",\"))\n }\n\n val visited = Array.fill(n + 1)(false)\n val cost = Array.fill(n + 1)(0)\n visited(1) = true\n\n val Q = new mutable.Queue[Int]\n Q.enqueue(1)\n\n while (Q.nonEmpty) {\n val curr = Q.dequeue()\n visited(curr) = true\n\n for (next <- G(curr).conn) {\n if (!visited(next)) {\n visited(next) = true\n cost(next) = cost(curr) + 1\n Q.enqueue(next)\n }\n }\n }\n\n println(cost.tail.mkString(\" \"))\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val a = new Array[Int](n+1)\n for(i <- 1 to n)\n a(i) = sc.nextInt()\n\n val dp = Array.fill(n+1)(Int.MaxValue)\n dp(0) = -1\n dp(1) = 0\n for(i <- 1 to n-1){\n val now = dp(i)\n dp(i+1) = Math.min(dp(i+1), now + 1)\n var sho = a(i)\n dp(sho) = Math.min(dp(sho), now + 1)\n var flag = true\n while(flag){\n // println(sho)\n if(dp(sho-1) > dp(sho) + 1){\n dp(sho-1) = dp(sho) + 1\n sho -= 1\n }\n else\n flag = false\n }\n }\n\n\n //\n print(dp(1))\n for(i <- 2 to n)\n print(\" \" + dp(i))\n println()\n }\n}\n"}, {"source_code": "object main\n{\n\tdef main ( args : Array[String] )\n\t{\n\t\tvar n = Console.readLine().toInt;\n\t\tvar str = Console.readLine();\n\t\tvar to = new Array[Int](200010);\n\t\tvar que = new Array[Int](200010);\n\t\tvar dist = new Array[Int](200010);\n\t\tvar now = 0;\n\t\tfor ( a <- 0 to str.length()-1 )\n\t\t{\n\t\t\tif (str.charAt(a) == ' ') now = now + 1;\n\t\t\telse to(now) = to(now) * 10 + str.charAt(a) - '0';\n\t\t}\n\n\t\tfor ( a <- 0 to n-1 )\n\t\t{\n\t\t\tdist(a) = -1;\n\t\t\tto(a) -= 1;\n\t\t}\n\t\tdist(0)=0;\n\t\tvar front = 0;\n\t\tvar tail = 0;\n\t\twhile (front<=tail)\n\t\t{\n\t\t\tvar now = que(front);\n\t\t\tfront += 1;\n\t\t\tif (now > 0 && dist(now-1) == -1)\n\t\t\t{\n\t\t\t\ttail += 1;\n\t\t\t\tque(tail) = now-1;\n\t\t\t\tdist(now-1) = dist(now) + 1;\n\t\t\t}\n\t\t\tif (now < n-1 && dist(now+1) == -1)\n\t\t\t{\n\t\t\t\ttail += 1;\n\t\t\t\tque(tail) = now+1;\n\t\t\t\tdist(now+1) = dist(now) + 1;\n\t\t\t}\n\t\t\tif (dist(to(now)) == -1)\n\t\t\t{\n\t\t\t\ttail += 1;\n\t\t\t\tque(tail) = to(now);\n\t\t\t\tdist(to(now)) = dist(now) + 1;\n\t\t\t}\n\t\t}\n\t\tfor ( a <- 0 to n-1)\n\t\t{\n\t\t\tprint(dist(a));\n\t\t\tif (a==n-1) println();\n\t\t\telse print(\" \");\n\t\t}\n\t}\n}"}, {"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\n/**\n * @author Baidin Dima\n */\nobject MikeAndShortcuts extends App {\n\n case class Edge(to: Int, w: Int)\n\n\n def readInput(): Array[ArrayBuffer[Edge]] = {\n val intersectionCount = scala.io.StdIn.readInt()\n\n val adjacencyList: Array[ArrayBuffer[Edge]] = new Array(intersectionCount)\n\n val shortcuts = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n adjacencyList.indices.foreach { case i ⇒\n val to = shortcuts(i)\n adjacencyList(i) = ArrayBuffer(Edge(to - 1, 1))\n if (i != intersectionCount - 1) {\n adjacencyList(i) += Edge(i + 1, 1)\n }\n if (i != 0) {\n adjacencyList(i) += Edge(i - 1, 1)\n }\n }\n adjacencyList\n }\n\n def dijkstra(adjacencyList: Array[ArrayBuffer[Edge]]): Unit = {\n val visited: Array[Boolean] = new Array(adjacencyList.length);\n visited(0) = true\n val distance: Array[Int] = new Array(adjacencyList.length);\n distance(0) = 0\n\n implicit val edgeOrdering: Ordering[Edge] = new Ordering[Edge] {\n override def compare(x: Edge, y: Edge): Int = y.w - x.w\n }\n\n val q: mutable.PriorityQueue[Edge] = new mutable.PriorityQueue[Edge]()\n\n adjacencyList(0).foreach { case edge ⇒ q += edge }\n\n while (q.nonEmpty) {\n val edge = q.dequeue()\n\n if (!visited(edge.to)) {\n visited(edge.to) = true\n distance(edge.to) = edge.w\n\n adjacencyList(edge.to).foreach(nEdge ⇒\n q += Edge(nEdge.to, edge.w + nEdge.w)\n )\n }\n }\n\n println(distance.mkString(\" \"))\n }\n\n dijkstra(readInput())\n\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val a = new Array[Int](n+1)\n for(i <- 1 to n)\n a(i) = sc.nextInt()\n\n val dp = Array.fill(n+1)(Int.MaxValue)\n dp(1) = 0\n for(i <- 1 to n-1){\n val now = dp(i)\n dp(i+1) = Math.min(dp(i+1), now + 1)\n val sho = a(i)\n dp(sho) = Math.min(dp(sho), now + 1)\n }\n\n for(i <- (1 to n-1).reverse){\n if(dp(i) > dp(i+1) + 1)\n dp(i) = dp(i+1) + 1\n }\n\n //\n print(dp(1))\n for(i <- 2 to n)\n print(\" \" + dp(i))\n println()\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\nimport scala.collection.mutable\n\nobject B extends App {\n class Node {\n val conn = new mutable.ArrayBuffer[Int]\n }\n\n val n = readInt()\n val A = Array(Integer.MIN_VALUE) ++ readLine().split(\" \").map(_.toInt)\n val G = Array.fill(n + 1)(new Node)\n\n for (i <- 1 to n) {\n val next = if (i < n) i + 1 else 1\n G(i).conn += next\n if (next != A(i) && A(i) != i) G(i).conn += A(i)\n// println(i + \" -> \" + G(i).conn.mkString(\",\"))\n }\n\n val visited = Array.fill(n + 1)(false)\n val cost = Array.fill(n + 1)(0)\n visited(1) = true\n\n val Q = new mutable.Queue[Int]\n Q.enqueue(1)\n\n while (Q.nonEmpty) {\n val curr = Q.dequeue()\n visited(curr) = true\n\n for (next <- G(curr).conn) {\n if (!visited(next)) {\n visited(next) = true\n cost(next) = cost(curr) + 1\n Q.enqueue(next)\n }\n }\n }\n\n println(cost.tail.mkString(\" \"))\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\n/**\n * @author Baidin Dima\n */\nobject MikeAndShortcuts extends App {\n\n case class Edge(to: Int, w: Int)\n\n\n def readInput(): Array[ArrayBuffer[Edge]] = {\n val intersectionCount = scala.io.StdIn.readInt()\n\n val adjacencyList: Array[ArrayBuffer[Edge]] = new Array(intersectionCount)\n\n val shortcuts = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n adjacencyList.indices.foreach { case i ⇒\n val to = shortcuts(i)\n adjacencyList(i) = ArrayBuffer(Edge(to - 1, 1))\n if (i != intersectionCount - 1) {\n adjacencyList(i) += Edge(i + 1, 1)\n }\n }\n adjacencyList\n }\n\n def dijkstra(adjacencyList: Array[ArrayBuffer[Edge]]): Unit = {\n val visited: Array[Boolean] = new Array(adjacencyList.length); visited(0) = true\n val distance: Array[Int] = new Array(adjacencyList.length); distance(0) = 0\n\n implicit val edgeOrdering: Ordering[Edge] = new Ordering[Edge] {\n override def compare(x: Edge, y: Edge): Int = x.w - y.w\n }\n\n val q: mutable.PriorityQueue[Edge]= new mutable.PriorityQueue[Edge]()\n\n adjacencyList(0).foreach{case edge ⇒ q += edge}\n\n while (q.nonEmpty) {\n val edge = q.dequeue()\n\n if (!visited(edge.to)) {\n visited(edge.to) = true\n distance(edge.to) = edge.w\n\n adjacencyList(edge.to).foreach(nEdge ⇒\n q += Edge(nEdge.to, edge.w + nEdge.w)\n )\n }\n }\n\n println(distance.mkString(\" \"))\n }\n\n dijkstra(readInput())\n\n}\n"}], "src_uid": "d465aec304757dff34a770f7877dd940"} {"source_code": "object C5 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n val str = read\n val d = Array.fill(str.length)(-1) // pos of corresponding open bracket\n val c = Array.fill(str.length)(-1) // pos of earliest open bracket, str(c(i), i) is regular\n val stack = new java.util.Stack[Int]\n var i = 0\n while (i < str.length) {\n if (str(i) == '(') {\n stack.push(i)\n } else {\n if (stack.isEmpty) {\n d(i) = -1\n c(i) = -1\n } else {\n val top = stack.pop()\n d(i) = top\n c(i) = d(i)\n if (d(i) - 1 >= 0 && str(d(i) - 1) == ')' && c(d(i) - 1) != -1) {\n c(i) = c(d(i) - 1)\n }\n }\n }\n i += 1\n }\n i = 0\n var max = 0\n var count = 0\n while (i < str.length) {\n if (c(i) != -1)\n if (max < i - c(i) + 1) {\n count = 1\n max = i - c(i) + 1\n } else if (max == i - c(i) + 1) {\n count += 1\n }\n i += 1\n }\n if (max == 0) {\n out.println(\"0 1\")\n } else {\n out.println(s\"${max} ${count}\")\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "object C5 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n val str = read\n val d = Array.fill(str.length)(-1) // pos of corresponding open bracket\n val c = Array.fill(str.length)(-1) // pos of earliest open bracket, str(c(i), i) is regular\n val stack = new cu.Stack[Int]\n var i = 0\n while (i < str.length) {\n if (str(i) == '(') {\n stack.push(i)\n } else {\n if (stack.isEmpty) {\n d(i) = -1\n c(i) = -1\n } else {\n val top = stack.pop()\n d(i) = top\n c(i) = d(i)\n if (d(i) - 1 >= 0 && str(d(i) - 1) == ')' && c(d(i) - 1) != -1) {\n c(i) = c(d(i) - 1)\n }\n }\n }\n i += 1\n }\n val maxs = c.zipWithIndex.map {\n case (value, idx) => if (value != -1) idx - value + 1 else 0\n }\n val max = maxs.max\n if (max == 0) {\n out.println(\"0 1\")\n } else {\n out.println(s\"${max} ${maxs.count(_ == max)}\")\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object main extends App with fastIO {\n\n val s = \" \" + readLine\n val n = s.length - 1\n \n var a: Array[Int] = s.toArray.map( (c) => if (c == '(') 1 else -1 )\n \n a(0) = 0\n for (i <- 1 to n) a(i) += a(i - 1)\n a = a.map(_ + n) \n \n var first = Array.fill(2 * n + 1)(n + 1)\n var ans = for (i <- 1 to n) yield {\n s(i) match {\n case '(' => if (first(a(i - 1)) == n + 1) first(a(i - 1)) = i\n case ')' => first(a(i - 1)) = n + 1\n }\n i - first(a(i)) + 1\n }\n \n val answer = ans.max max 0\n print(answer + \" \" + ans.count(_ == answer))\n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "object P5C {\n def main(args: Array[String]) {\n val s = readLine\n val n = s.size\n val a = Array.fill(n + n + 1){n}\n var d = n\n val answer = for (i <- 0 until n) yield {\n s(i) match {\n case '(' => {\n if (a(d) == n) a(d) = i\n d = d + 1\n }\n case ')' => {\n a(d) = n\n d = d - 1\n }\n }\n i - a(d) + 1\n }\n val m = answer.max max 0\n println(m + \" \" + answer.count{_ == m})\n }\n}\n"}, {"source_code": "object C {\n def main(args: Array[String]) = {\n lazy val input = io.StdIn.readLine zip (0 until Int.MaxValue)\n def insert(list: List[(Int, Int)], pair: (Int, Int)): List[(Int, Int)] = list match {\n case Nil => pair::Nil\n case head::tail =>\n if (head._1 > pair._1 && head._2 < pair._2) insert(tail, pair)\n else if (head._2 == pair._1 - 1) (head._1, pair._2)::tail\n else pair::list\n }\n def foldMethod(lists: (List[Int], List[(Int, Int)]), ch: (Char, Int)): (List[Int], List[(Int, Int)]) = lists match {\n case (opens, pairs) =>\n if(ch._1 == '(') (ch._2::opens, pairs)\n else if(opens.isEmpty) (opens, pairs)\n else (opens.tail, insert(pairs, (opens.head, ch._2)))\n }\n lazy val folded = input.foldLeft((List[Int](), List[(Int, Int)]()))(foldMethod)._2.map(p => p._2 - p._1 + 1)\n lazy val maxi = if (folded.isEmpty) 0 else folded.max\n lazy val count = if (folded.isEmpty) 1 else folded.count(_ == maxi)\n\n println(maxi + \" \" + count)\n }\n}\n"}, {"source_code": "import java.util\nimport java.util.Scanner\n\nobject CBalancedBraces extends App {\n\n val scanner = new Scanner(System.in)\n\n val input = scanner.next()\n val stack = new util.Stack[Int]\n\n var max = 0\n var maxNum = 0\n\n\n stack.push(-1)\n\n input.zipWithIndex foreach {\n item =>\n item._1 match {\n case '(' => stack.push(item._2)\n case ')' =>\n if (!stack.empty()) {\n stack.pop()\n if (!stack.empty()) {\n recordResult(item._2, stack.peek())\n }\n }\n if (stack.empty()) {\n stack.push(item._2)\n }\n\n }\n }\n\n if (max == 0) {\n println(\"0 1\")\n } else {\n print(max + \" \")\n println(maxNum)\n }\n\n\n def recordResult(start: Int, end: Int): Unit = {\n val item = start - end\n if (max < item) {\n max = item\n maxNum = 1\n } else if (max == item) maxNum += 1\n }\n\n}\n"}, {"source_code": "object C5 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n val str = read\n val d = Array.fill(str.length)(-1) // pos of corresponding open bracket\n val c = Array.fill(str.length)(-1) // pos of earliest open bracket, str(c(i), i) is regular\n val stack = new cu.Stack[Int]\n var i = 0\n while (i < str.length) {\n if (str(i) == '(') {\n stack.push(i)\n } else {\n if (stack.isEmpty) {\n d(i) = -1\n c(i) = -1\n } else {\n val top = stack.pop()\n d(i) = top\n c(i) = d(i)\n if (d(i) - 1 >= 0 && str(d(i) - 1) == ')' && c(d(i) - 1) != -1) {\n c(i) = c(d(i) - 1)\n }\n }\n }\n i += 1\n }\n i = 0\n var max = 0\n var count = 0\n while (i < str.length) {\n if (c(i) != -1)\n if (max < i - c(i) + 1) {\n count = 1\n max = i - c(i) + 1\n } else if (max == i - c(i) + 1) {\n count += 1\n }\n i += 1\n }\n if (max == 0) {\n out.println(\"0 1\")\n } else {\n out.println(s\"${max} ${count}\")\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "object main extends App with fastIO {\n\n val s = \" \" + readLine\n val n = s.length - 1\n \n var a: Array[Int] = s.toArray.map( (c) => if (c == '(') 1 else -1 )\n \n a(0) = 0\n for (i <- 1 to n) a(i) += a(i - 1)\n a = a.map(_ + n) \n \n var first = Array.fill(2 * n + 1)(n)\n var ans = for (i <- 1 to n) yield {\n s(i) match {\n case '(' => if (first(a(i - 1)) == n) first(a(i - 1)) = i\n case ')' => first(a(i - 1)) = n\n }\n i - first(a(i)) + 1\n }\n \n val answer = ans.max max 0\n print(answer + \" \" + ans.count(_ == answer))\n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "object C {\n def main(args: Array[String]) = {\n lazy val input = io.StdIn.readLine zip (0 until Int.MaxValue)\n def insert(list: List[(Int, Int)], pair: (Int, Int)): List[(Int, Int)] = list match {\n case Nil => pair::Nil\n case head::tail =>\n if (head._1 > pair._1 && head._2 < pair._2) insert(tail, pair)\n else if (head._2 == pair._1 - 1) (head._1, pair._2)::tail\n else pair::list\n }\n def foldMethod(lists: (List[Int], List[(Int, Int)]), ch: (Char, Int)): (List[Int], List[(Int, Int)]) = lists match {\n case (opens, pairs) =>\n if(ch._1 == '(') (ch._2::opens, pairs)\n else if(opens.isEmpty) (opens, pairs)\n else (opens.tail, insert(pairs, (opens.head, ch._2)))\n }\n lazy val folded = input.foldLeft((List[Int](), List[(Int, Int)]()))(foldMethod)._2.map(p => {println(p); p._2 - p._1 + 1})\n lazy val maxi = if (folded.isEmpty) 0 else folded.max\n lazy val count = if (folded.isEmpty) 1 else folded.count(_ == maxi)\n\n println(maxi + \" \" + count)\n }\n}\n"}, {"source_code": "object C {\n def main(args: Array[String]) = {\n lazy val input = io.StdIn.readLine zip (0 until Int.MaxValue)\n def foldMethod(lists: (List[Int], List[Int]), ch: (Char, Int)): (List[Int], List[Int]) = lists match {\n case (opens, starts) =>\n if(ch._1 == '(') (ch._2::opens, -1::starts)\n else if(opens.isEmpty) (opens, -1::starts)\n else (opens.tail, opens.head::starts)\n }\n lazy val folded = input.foldLeft((List[Int](), List[Int]()))(foldMethod)._2.reverse\n def findStart(list: Vector[Int], index: Int): Vector[Int] = {\n if (index == -1) list :+ 0\n else if (index == 0) list :+ list.length\n else if (list(index - 1) != 0) list :+ (list.length - index + 1 + list(index - 1))\n else list :+ (list.length - index + 1)\n }\n lazy val result = folded.foldLeft(Vector.empty[Int])(findStart)\n lazy val maxi = result.max\n lazy val count = result.count(_ == maxi)\n\n if (maxi == 0) println(\"0 1\")\n else println(maxi + \" \" + count)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject CCorrectBraces extends App {\n\n val scanner = new Scanner(System.in)\n val input = scanner.next()\n\n var pointer = 0\n\n var max = 0\n var maxNum = 0\n\n start()\n\n if (max == 0) {\n println(\"0 1\")\n } else {\n print(max + 1 + \" \")\n println(maxNum)\n }\n\n\n def get: Char = input(pointer)\n\n def next: Char = {\n val res = get\n pointer += 1\n res\n }\n\n def eof(): Boolean = pointer >= input.size\n\n def start(): Unit = {\n while (!eof) {\n if (get == ')') next\n else parse()\n }\n }\n\n def parse(): Unit = {\n while (!eof && get == '(') {\n parseBraces()\n }\n }\n\n def parseBraces(): Unit = {\n if (!eof && get == '(') {\n val save = pointer\n next\n parse()\n if (!eof && get == ')') {\n recordResult(pointer - save)\n next\n } else if (!eof) {\n next\n parse()\n }\n }\n }\n\n def recordResult(item: Int): Unit = {\n if (max < item) {\n max = item\n maxNum = 1\n } else if (max == item) maxNum += 1\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject CCorrectBraces extends App {\n\n val scanner = new Scanner(System.in)\n val input = scanner.next()\n\n var pointer = 0\n\n var max = 0\n var maxNum = 0\n var streak = 0\n\n start()\n\n if (max == 0) {\n println(\"0 1\")\n } else {\n print(max + \" \")\n println(maxNum)\n }\n\n\n def get: Char = input(pointer)\n\n def next: Char = {\n val res = get\n pointer += 1\n res\n }\n\n def eof(): Boolean = pointer >= input.size\n\n def start(): Unit = {\n while (!eof) {\n if (get == ')') {\n next\n }\n else parse()\n }\n }\n\n def parse(): Unit = {\n val save = pointer\n while (!eof && get == '(') {\n parseBraces()\n }\n if (pointer - save > 1) {\n recordResult(save)\n }\n }\n\n def parseBraces(): Unit = {\n if (!eof && get == '(') {\n val save = pointer\n next\n parse()\n if (!eof && get == ')') {\n //recordResult(save)\n next\n } else if (!eof) {\n next\n //parse()\n }\n }\n }\n\n def recordResult(save: Int): Unit = {\n val item = pointer - save\n if (max < item) {\n max = item\n maxNum = 1\n } else if (max == item) maxNum += 1\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject CCorrectBraces extends App {\n\n val scanner = new Scanner(System.in)\n val input = scanner.next()\n\n var pointer = 0\n\n var max = 0\n var maxNum = 0\n var streak = 0\n\n start()\n\n if (max == 0) {\n println(\"0 1\")\n } else {\n print(max + 1 + \" \")\n println(maxNum)\n }\n\n\n def get: Char = input(pointer)\n\n def next: Char = {\n val res = get\n pointer += 1\n res\n }\n\n def eof(): Boolean = pointer >= input.size\n\n def start(): Unit = {\n while (!eof) {\n if (get == ')') {\n next\n }\n else parse()\n }\n }\n\n def parse(): Unit = {\n val save = pointer\n while (!eof && get == '(') {\n parseBraces()\n }\n if (pointer - save > 1) {\n recordResult(save)\n }\n }\n\n def parseBraces(): Unit = {\n if (!eof && get == '(') {\n val save = pointer\n next\n parse()\n if (!eof && get == ')') {\n //recordResult(save)\n next\n } else if (!eof) {\n next\n //parse()\n }\n }\n }\n\n def recordResult(save: Int): Unit = {\n val item = pointer - save\n if (max < item) {\n max = item\n maxNum = 1\n } else if (max == item) maxNum += 1\n }\n\n}\n"}, {"source_code": "object C5 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n val str = read\n val count = cu.Map.empty[Int, Int].withDefaultValue(0)\n var maxLen = 0\n var openCount = 0\n var currLen = 0\n var i = 0\n while (i < str.length) {\n if (str(i) == '(') {\n openCount += 1\n currLen += 1\n } else {\n if (openCount == 0) {\n count(currLen) += 1\n maxLen = math.max(maxLen, currLen)\n currLen = 0\n } else if (openCount > 0) {\n openCount -= 1\n currLen += 1\n }\n }\n i += 1\n }\n if (openCount == 0) {\n count(currLen) += 1\n maxLen = math.max(maxLen, currLen)\n }\n if (maxLen == 0) {\n out.println(\"0 1\")\n } else {\n out.println(s\"${maxLen} ${count(maxLen)}\")\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "91c3af92731cd7d406674598c0dcbbbc"} {"source_code": "import java.util.Scanner\n\nobject cf270d extends App {\n val in = new Scanner(System.in)\n\tval (n, m) = (in.nextInt, in.nextInt)\n\tval input = (1 to n).map(i => (in.nextInt, in.nextFloat)._1)\n\tvar dp = Array.fill(m + 1)(0)\n\tfor (arri <- input)\n\t\tdp(arri) = 1 + dp.slice(1, arri + 1).max\n\tprintln(n - dp.max)\n}", "positive_code": [{"source_code": "object cf270d extends App {\n\tval Array(n, m) = readLine.split(' ').map(_.toInt)\n\tval input = (1 to n).map(i => readLine.split(' ')).sortBy(_.apply(1).toFloat).map(_.apply(0).toInt)\n\tvar dp = Array.fill(m + 1)(0)\n\tfor (arri <- input)\n\t\tdp(arri) = 1 + dp.slice(1, arri + 1).max\n\tprintln(n - dp.max)\n}"}, {"source_code": "import java.util.Scanner\n\nobject cf270d extends App {\n val in = new Scanner(System.in)\n\tval (n, m) = (in.nextInt, in.nextInt)\n\tval input = (1 to n).map(i => (in.nextInt, in.nextFloat)).sortBy(_._2).map(_._1)\n\tvar dp = Array.fill(m + 1)(0)\n\tfor (arri <- input)\n\t\tdp(arri) = 1 + dp.slice(1, arri + 1).max\n\tprintln(n - dp.max)\n}"}, {"source_code": "object cf270d extends App {\n\tval Array(n, m) = readLine.split(' ').map(_.toInt)\n\tval input = (1 to n).map(i => readLine.split(' ').apply(0).toInt)\n\tvar dp = Array.fill(m + 1)(0)\n\tfor (arri <- input)\n\t\tdp(arri) = 1 + dp.slice(1, arri + 1).max\n\tprintln(n - dp.max)\n}"}, {"source_code": "object cf270d extends App {\n val Array(n, m) = readLine.split(' ').map(_.toInt)\n val input = (1 to n).map(i => readLine.split(' ').apply(0).toInt)\n var dp = Array.fill(n + 1)(0)\n var len = 0\n for (arri <- input) {\n var (l, r, ans) = (0, len, len)\n while (l <= r) {\n val m = (l + r) / 2\n if (dp(m) <= arri) {\n l = m + 1\n ans = m\n } else {\n r = m - 1\n }\n }\n dp(ans + 1) = arri\n if (ans >= len)\n len += 1\n }\n println(n - len)\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val f = new Array[Int](m)\n val g = new Array[Int](m)\n for (_ <- 1 to n) {\n val tokens = readLine().split(\" \")\n var a = tokens(0).toInt - 1\n for (i <- m - 1 to a by -1) {\n f(i) = Math.min(f(i) + 1, f(a) + g(a) - g(i))\n }\n for (i <- a - 1 to 0 by -1) {\n g(i) += 1\n }\n }\n println(f(m - 1))\n }\n}"}, {"source_code": "object test6 extends App {\n val Array(n,m)=readLine.split(\" \").map(_.toInt)\n val s=(for(i<-1 to n) yield readLine.split(\" \")(0).toInt) toArray\n val dp=Array.ofDim[Int](n+1,m+1)\n\n for(i<-n-1 to 0 by -1; j<-0 to m){\n dp(i)(j)=1+dp(i+1)(j)\n if(s(i)>=j) dp(i)(j)=math.min(dp(i)(j), dp(i+1)(s(i)))\n }\n \n println(dp(0)(0))\n} \n\n\n"}, {"source_code": "object test6 extends App {\n val Array(n,m)=readLine.split(\" \").map(_.toInt)\n val s=(for(i<-1 to n) yield readLine.split(\" \")(0).toInt).toArray\n val dp=Array.ofDim[Int](n+1,m+1)\n\n for(i<-n-1 to 0 by -1; j<-0 to m){\n dp(i)(j)=1+dp(i+1)(j)\n if(s(i)>=j) dp(i)(j)=math.min(dp(i)(j), dp(i+1)(s(i)))\n }\n \n println(dp(0)(0))\n} \n\n\n"}, {"source_code": "object test6 extends App {\n val Array(n,m)=readLine.split(\" \").map(_.toInt)\n val s=new Array[Int](n)\n val x=new Array[Double](n)\n val dp=Array.ofDim[Int](n+1,m+1)\n for(i<-0 until n){\n val arr=readLine.split(\" \")\n s(i)=arr(0).toInt\n x(i)=arr(1).toDouble\n }\n \n for(i<-n-1 to 0 by -1; j<-0 to m){\n dp(i)(j)=1+dp(i+1)(j)\n if(s(i)>=j) dp(i)(j)=math.min(dp(i)(j), dp(i+1)(s(i)))\n }\n \n println(dp(0)(0))\n} \n\n\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, _) = readLine().split(\" \").map(_.toInt)\n var last = -1\n var count = 0\n for (_ <- 1 to n) {\n val tokens = readLine().split(\" \")\n val s = tokens(0).toInt\n if (s < last) {\n count += 1\n }\n last = s\n }\n println(count)\n }\n}"}], "src_uid": "32f245fa1a2d99bfabd30b558687ca5f"} {"source_code": "import scala.io.StdIn\n\nobject PracticeScala {\n def main(args: Array[String]): Unit = {\n var t = StdIn.readInt()\n while(t != 0){\n val n = StdIn.readInt()\n var i: Int = 0\n while(i < n){\n println(\"()\" * i + \"(\" * (n - i) + \")\" * (n - i) )\n i += 1\n }\n t -= 1\n }\n }\n}\n", "positive_code": [{"source_code": "object A extends App {\r\n\r\n def brackets(n: Int): List[String] =\r\n (0 until n).foldLeft(List.empty[String]) { (brackets, i) =>\r\n val bracket = \"(\" * (n - 1) + \")\" * i + \"(\" + \")\" * (n - i)\r\n bracket :: brackets\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n\r\n out.println(brackets(n).mkString(\"\\n\"))\r\n out.flush()\r\n }\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport scala.util.Sorting.quickSort\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val writer = new PrintWriter(System.out)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {\r\n while (!st.hasMoreTokens) {\r\n st = new StringTokenizer(reader.readLine())\r\n }\r\n st.nextToken()\r\n }\r\n\r\n def readInt() = next.toInt\r\n def readLong() = next.toLong\r\n def readString() = next()\r\n\r\n def pow(a: Int, b: Int): Long = {\r\n if (b == 0) return 1\r\n\r\n val rs = pow(a, b / 2)\r\n rs * rs * (if (b % 2 == 0) 1 else a)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b\r\n\r\n def root(u: Int, p: Array[Int]): Int = {\r\n if (p(u) < 0) return u\r\n p(u) = root(p(u), p)\r\n p(u)\r\n }\r\n\r\n def join(u: Int, v: Int, p: Array[Int]): Unit = {\r\n var x = root(u, p)\r\n var y = root(v, p)\r\n if (x == y) return\r\n\r\n if (p(y) < p(x)) {\r\n val t = x\r\n x = y\r\n y = t\r\n }\r\n p(x) += p(y)\r\n p(y) = x\r\n }\r\n\r\n def main(args: Array[String]) {\r\n var t = readInt()\r\n while (t > 0) {\r\n t -= 1\r\n val n = readInt()\r\n val m = (1L << n) - 1\r\n val a = new Array[Int](2*n)\r\n for (i <- 0 until n) {\r\n for (k <- 0 until n) {\r\n a(n - k - 1) = (((m - i) >> k ) & 1).toInt\r\n a(k + n) = 1 - a(n - k - 1)\r\n }\r\n\r\n for (i <- 0 until 2*n) {\r\n if (a(i) == 1) writer.print(\"(\")\r\n else writer.print(\")\")\r\n }\r\n writer.println()\r\n }\r\n }\r\n writer.close()\r\n }\r\n}"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable._\r\nimport scala.math.max\r\n\r\nobject test {\r\n val writer = new PrintWriter(System.out)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\r\n def readInt(): Int = next().toInt\r\n def readLong(): Long = next().toLong\r\n def readString(): String = next()\r\n\r\n def main(args: Array[String]): Unit = {\r\n val t = readInt()\r\n for (tt <- 1 to t) {\r\n val n = readInt()\r\n for (i <- 1 to n) {\r\n for (j <- 1 to i)\r\n writer.print('(')\r\n for (j <- 1 to i)\r\n writer.print(')')\r\n for (j <- 1 to n-i)\r\n writer.print(\"()\")\r\n writer.println()\r\n }\r\n writer.flush()\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "27b73a87fc30c77abb55784e2e1fde38"} {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n private def check(r: Long, g: Long, b: Long, w: Long): Boolean =\n r >= 0 && g >= 0 && b >= 0 && List(r, g, b, w).foldLeft(0L)(_ + _ % 2) <= 1\n\n (0 until t).foreach { _ =>\n val Array(r, g, b, w) = readLine().split(\" \").map(_.toLong)\n\n val ans = check(r, g, b, w) || check(r - 1, g - 1, b - 1, w + 3)\n\n if (ans) println(\"Yes\") else println(\"No\")\n }\n}\n", "positive_code": [{"source_code": "\nimport scala.io.StdIn._\n\nobject taskA extends App {\n\n def singleCheck(input: Array[Int]): Boolean = {\n input.foreach { x =>\n if (x < 0)\n return false\n }\n if (input(3) % 2 == 0) {\n if (input(0) % 2 + input(1) % 2 + input(2) % 2 <= 1)\n true\n else\n false\n } else {\n if (input(0) % 2 + input(1) % 2 + input(2) % 2 == 0)\n true\n else\n false\n }\n }\n4\n\n def check(input: Array[Int]): String = {\n var res: Boolean = false\n if (singleCheck(input)) res = true\n else {\n val newInput = input.map(x => x - 1)\n newInput(3) += 4\n res = singleCheck(newInput)\n }\n if (res) \"Yes\" else \"No\"\n }\n\n //READING THE STANDARD INPUT\n val sets = readInt\n\n var lst: List[String] = List()\n (1 to sets).foreach { _ =>\n val input: Array[Int] = readLine.split(\" \").map(_.toInt)\n //println(check(input))\n lst = lst ::: List(check(input))\n }\n\n\n lst.foreach { x =>\n println(x)\n }\n\n\n}\n"}, {"source_code": "\nobject A extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val r = in.nextInt()\n val g = in.nextInt()\n val b = in.nextInt()\n val w = in.nextInt()\n\n val count = (r % 2) + (g % 2) + (b % 2) + (w % 2)\n if (count == 0 || count == 1) {\n println(\"Yes\")\n } else {\n val c2 = (r % 2) + (g % 2) + (b % 2)\n if (r != 0 && g != 0 && b != 0) {\n if (w % 2 == 1) {\n if (c2 >= 2) println(\"Yes\") else println(\"No\")\n } else {\n if (c2 == 1 || c2 == 3) println(\"Yes\") else println(\"No\")\n }\n } else {\n println(\"No\")\n }\n }\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}], "negative_code": [{"source_code": "\nimport scala.io.StdIn._\n\nobject taskA extends App {\n\n def singleCheck(input: Array[Int]): Boolean = {\n input.foreach { x =>\n if (x < 0)\n return false\n }\n if (input(3) % 2 == 0) {\n if (input(0) % 2 + input(1) % 2 + input(2) % 2 <= 1)\n true\n else\n false\n } else {\n if (input(0) % 2 + input(1) % 2 + input(2) % 2 == 0)\n true\n else\n false\n }\n }\n4\n\n def check(input: Array[Int]): String = {\n var res: Boolean = false\n if (singleCheck(input)) res = true\n else res = singleCheck(input.map(x => x - 1))\n if (res) \"Yes\" else \"No\"\n }\n\n //READING THE STANDARD INPUT\n val sets = readInt\n\n var lst: List[String] = List()\n (1 to sets).foreach { _ =>\n val input: Array[Int] = readLine.split(\" \").map(_.toInt)\n //println(check(input))\n lst = lst ::: List(check(input))\n }\n\n\n lst.foreach { x =>\n println(x)\n }\n\n\n}\n"}, {"source_code": "\nimport scala.io.StdIn._\n\nobject taskA extends App {\n\n def singleCheck(input: Array[Int]): Boolean = {\n input.foreach { x =>\n if (x < 0)\n return false\n }\n if (input(3) % 2 == 0) {\n if (input(0) % 2 + input(1) % 2 + input(2) % 2 == 1)\n true\n else\n false\n } else {\n if (input(0) % 2 + input(1) % 2 + input(2) % 2 == 0)\n true\n else\n false\n }\n }\n\n def check(input: Array[Int]): String = {\n var res: Boolean = false\n if (singleCheck(input)) res = true\n else res = singleCheck(input.map(x => x - 1))\n if (res) \"Yes\" else \"No\"\n }\n\n //READING THE STANDARD INPUT\n val sets = readInt\n\n var lst: List[String] = List()\n (1 to sets).foreach { _ =>\n val input: Array[Int] = readLine.split(\" \").map(_.toInt)\n //println(check(input))\n lst = lst ::: List(check(input))\n }\n\n\n lst.foreach { x =>\n println(x)\n }\n\n\n}\n"}], "src_uid": "749a106d462555543c91753f00a5a479"} {"source_code": "import scala.collection._\n\nobject A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val ss = Array.fill(n){ readLine.toCharArray }\n \n var max = 0\n \n for (a <- 'a' to 'z') {\n for (b <- 'a' to 'z') if (b != a) {\n var sum = 0\n for (i <- 0 until n) {\n var ok = true\n for (c <- ss(i)) {\n if (c != a && c != b) ok = false\n }\n if (ok) {\n sum += ss(i).length\n }\n }\n if (sum > max) {\n max = sum\n }\n }\n }\n\n println(max)\n}\n", "positive_code": [{"source_code": "//package round329.a\n\nimport java.util.Scanner\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n sc.nextLine\n val words = (1 to n).map(_ => sc.nextLine())\n\n// println(words)\n\n val goodWords = words.filter { word =>\n val grouped = word.toList.groupBy(c => c)\n grouped.keys.size <= 2\n }\n\n var best = 0\n\n def containsOnly(s: String, allowed: List[Char]): Boolean = {\n s.forall(c => allowed.contains(c))\n }\n\n// println(goodWords)\n\n ('a' to 'z').foreach { char1 =>\n ('a' to 'z').foreach { char2 =>\n val wrds = goodWords.filter(w => containsOnly(w, List(char1, char2)))\n val payment = wrds.map(_.length).sum\n// println(s\"trying $char1, $char2: $payment\")\n best = Math.max(best, payment)\n }\n }\n\n println(best)\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n var map = ('a' to 'z').flatMap { i =>\n (i to 'z').map(j => \"\" + i + j -> 0)\n }.toMap\n (1 to n).foreach {_ =>\n val str = in.next()\n val distinct = str.distinct\n if (distinct.length == 2) {\n val key = distinct.sorted\n map += (key -> (map(key) + str.length))\n } else if (distinct.length == 1) {\n ('a' to 'z').foreach { j =>\n val key = (distinct + j).sorted\n map += (key -> (map(key) + str.length))\n }\n }\n }\n println(map.values.max)\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.StringTokenizer\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n def solve: Int = {\n val n = nextInt\n val words = new Array[String](n)\n for (i <- 0 until n)\n words(i) = next\n var max = 0\n for (c1 <- 'a' to 'z') {\n for (c2 <- 'a' to 'z') {\n if (c1 != c2) {\n var len = 0\n for (i <- 0 until n) {\n var flag = true\n for (j <- 0 until words(i).toCharArray.length) {\n if (words(i).toCharArray().apply(j) != c1 && words(i).toCharArray().apply(j) != c2)\n flag = false\n }\n if (flag) {\n len += words(i).toCharArray.length\n }\n }\n max = Math.max(max, len)\n }\n }\n }\n out.println(max)\n return 0\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.immutable.IndexedSeq\nimport scala.collection.mutable\nimport scala.util._\nimport scala.math.Ordering.Implicits._\n\nobject _593A extends CodeForcesApp {\n import CodeForcesApp._\n override type Result = Int\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val n = nextInt()\n val words = Seq.fill(n)(next())\n\n val all: IndexedSeq[((Char, Char), String)] = for {\n i <- 'a' to 'z'\n j <- 'a' to 'z'\n w <- words\n t = w.replace(i.toString, \"\").replaceAll(j.toString, \"\")\n if t.isEmpty\n } yield (i, j) -> w\n\n val map = all.groupBy(_._1).mapValues(_.map(_._2.length).sum)\n if (map.isEmpty) 0 else map.values.max\n }\n\n override def format(result: Result) = super.format(result)\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}], "negative_code": [], "src_uid": "d8a93129cb5e7f05a5d6bbeedbd9ef1a"} {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\nimport scala.collection.mutable.ArrayBuffer\nimport java.util.Arrays.binarySearch\n\n\nobject P408A extends App {\n\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val K = Array.fill(N)(sc.nextInt)\n val slurpQueue: Int => List[Int] = i => List.fill(K(i))(sc.nextInt)\n val Q = List.tabulate(N)(slurpQueue)\n val stopTime: List[Int] => Int = { lst => lst.sum * 5 + lst.size * 15 }\n val res = Q.map(stopTime).min\n \n out.println(res)\n out.close\n}\n\n\n\n\n\n", "positive_code": [{"source_code": "object A extends App {\n \n def calc(in:Array[Int]): Int = {\n in.sum * 5 + in.length*15\n }\n \n var ans = (1<<30)\n val n = readInt()\n val t = readLine()\n for (i <- 0 until n) {\n val line = readLine()\n val in:Array[Int] = line.split(\" \") map (_.toInt)\n ans = ans min calc(in)\n }\n println(ans)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val k = in.next().split(\" \").map(_.toInt)\n val p = (1 to n).map(_ => in.next().split(\" \").map(_.toInt))\n val res = p.map(t => t.sum * 5 + t.length * 15)\n println(res.min)\n}"}, {"source_code": "object A408 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val k = readInts(n)\n val m = k.map(readInts)\n println(m.map(a => a.sum*5 + a.length*15).min)\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 19 Jun 2016\n */\nobject A408 extends App {\n\n def solve() = {\n val n: Int = scala.io.StdIn.readInt()\n val k: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n var min: Int = Int.MaxValue\n for (i <- 0 until n) {\n val m: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val latency = m.map(bucket => bucket * 5 + 15).sum\n min = Math.min(min, latency)\n }\n println(min)\n }\n\n solve()\n\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val k = in.next().split(\" \").map(_.toInt)\n val p = (1 to n).map(_ => in.next().split(\" \").map(_.toInt))\n val res = p.map(t => t.sum * 5 + t.length * 15)\n println(res.zipWithIndex.min._2 + 1)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P405A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n\n type Cards = List[Int]\n val CS: Cards = List.fill(N)(sc.nextInt)\n\n def solve(): Unit = {\n \n @tailrec\n def loop(spt: Int, dpt: Int, turn: Int, cs: Cards, rcs: Cards): Unit = {\n if (turn == N) out.println(List(spt, dpt).mkString(\" \"))\n else (cs, rcs) match {\n case (x :: xs, y :: ys) if x > y => if (turn % 2 == 0) loop(spt + x, dpt, turn + 1, xs, rcs)\n else loop(spt, dpt + x, turn + 1, xs, rcs)\n case (_, y :: ys) => if (turn % 2 == 0) loop(spt + y, dpt, turn + 1, cs, ys)\n else loop(spt, dpt + y, turn + 1, cs, ys)\n }\n }\n\n loop(0, 0, 0, CS, CS.reverse)\n }\n\n solve\n out.close\n}\n"}, {"source_code": "object A extends App {\n \n def calc(in:Array[Int]): Int = {\n in.sum * 5 + in.length*15\n }\n \n var ans = (1<<30)\n val n = readInt()\n for (i <- 0 until n) {\n val line = readLine()\n val in:Array[Int] = line.split(\" \") map (_.toInt)\n ans = ans min calc(in)\n }\n println(ans)\n}\n"}], "src_uid": "0ea79b2a7ddf3d4da9c7a348e61933a7"} {"source_code": "object CF291B extends App {\n val Array(n, x, y) = readLine().split(\" \").map(_.toInt)\n\n val ax = new Array[Int](n)\n val ay = new Array[Int](n)\n\n val shot = new Array[Boolean](n)\n\n (0 until n) foreach { i =>\n shot(i) = false\n val Array(tx, ty) = readLine().split(\" \").map(_.toInt)\n ax(i) = tx\n ay(i) = ty\n }\n\n var res = 0\n (0 until n) foreach { i =>\n if (!shot(i)) {\n res += 1\n (0 until n) foreach { j =>\n if ((y - ay(i)) * (x - ax(j)) == (y - ay(j)) * (x - ax(i))) shot(j) = true\n }\n }\n }\n\n print(res)\n}", "positive_code": [{"source_code": "object B514 {\n\n import IO._\n import collection.{mutable => cu}\n\n def sameLine(x: Int, y: Int, x1: Int, y1: Int, x2: Int, y2: Int): Boolean = {\n (x-x1)*(y-y2) == (x-x2)*(y-y1)\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, x0, y0) = readInts(3)\n val in = Array.fill(n)(readInts(2)).map(arr => (arr(0), arr(1)))\n val vis = Array.fill(n)(false)\n def dfs(a: Int): Unit = {\n vis(a) = true\n for(i <- 0 until n if !vis(i)) {\n if(sameLine(x0, y0, in(a)._1, in(a)._2, in(i)._1, in(i)._2))\n vis(i) = true\n }\n }\n var res = 0\n for(i <- 0 until n) {\n if(!vis(i)) {\n dfs(i)\n res += 1\n }\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\n/**\n * Created by dimitar on 2/14/15.\n * slope y2-y1/x2-x1\n */\nobject Points {\n\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val p = sc.nextInt()\n val x = sc.nextInt()\n val y = sc.nextInt()\n\n val map = new mutable.HashMap[Double, Int]\n var undef = 0\n\n (0 until p) foreach { _ =>\n\n val p1 = sc.nextInt()\n val p2 = sc.nextInt()\n if (p1-x != 0 ) {\n val slope = (p2 - y) / (p1 - x).toDouble\n if (!map.contains(slope)) {\n map.put(slope, 1)\n }\n } else {\n undef = 1\n }\n }\n\n println(map.size + undef)\n }\n\n}\n"}], "negative_code": [{"source_code": "\nimport java.util.Scanner\n\nimport scala.collection.mutable\n\n/**\n * Created by dimitar on 2/14/15.\n * slope y2-y1/x2-x1\n */\nobject Points {\n\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val p = sc.nextInt()\n val x = sc.nextInt()\n val y = sc.nextInt()\n\n val map = new mutable.HashMap[Int, Int]\n\n (0 until p) foreach { _ =>\n\n val p1 = sc.nextInt()\n val p2 = sc.nextInt()\n val slope = if ((p1-x) == 0) 0 else math.abs((p2-y)/(p1-x))\n if (!map.contains(slope))\n map.put(slope, 1)\n }\n\n println(map.size)\n }\n\n}\n"}, {"source_code": "\nimport java.util.Scanner\n\nimport scala.collection.mutable\n\n/**\n * Created by dimitar on 2/14/15.\n * slope y2-y1/x2-x1\n */\nobject Points {\n\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val p = sc.nextInt()\n val x = sc.nextInt()\n val y = sc.nextInt()\n\n val map = new mutable.HashMap[Int, Int]\n var undef = 0\n\n (0 until p) foreach { _ =>\n\n val p1 = sc.nextInt()\n val p2 = sc.nextInt()\n if (p1-x != 0 ) {\n val slope = (p2 - y) / (p1 - x)\n if (!map.contains(slope)) {\n map.put(slope, 1)\n }\n } else {\n undef = 1\n }\n }\n\n println(map.size + undef)\n }\n\n}\n"}, {"source_code": "\nimport java.util.Scanner\n\nimport scala.collection.mutable\n\n/**\n * Created by dimitar on 2/14/15.\n * slope y2-y1/x2-x1\n */\nobject Points {\n\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val p = sc.nextInt()\n val x = sc.nextInt()\n val y = sc.nextInt()\n\n val map = new mutable.HashMap[Int, Int]\n var undef = 0\n\n (0 until p) foreach { _ =>\n\n val p1 = sc.nextInt()\n val p2 = sc.nextInt()\n if (p1-x != 0 ) {\n val slope = math.abs ((p2 - y) / (p1 - x))\n if (!map.contains(slope)) {\n map.put(slope, 1)\n }\n } else {\n undef = 1\n }\n }\n\n println(map.size + undef)\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\n/**\n * Created by dimitar on 2/14/15.\n * slope y2-y1/x2-x1\n */\nobject Points {\n\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val p = sc.nextInt()\n val x = sc.nextInt()\n val y = sc.nextInt()\n\n val map = new mutable.HashMap[Int, Int]\n\n (0 until p) foreach { _ =>\n\n val p1 = sc.nextInt()\n val p2 = sc.nextInt()\n val slope = if ((p1-x) == 0) 0 else (p2-y)/(p1-x)\n if (!map.contains(slope))\n map.put(slope, 1)\n }\n\n println(map.size)\n }\n\n}\n"}], "src_uid": "8d2845c33645ac45d4d37f9493b0c380"} {"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val checked = Array.fill('z' - 'a' + 1)(false)\n var res = 0\n\n for (_ <- 0 until n) {\n //println(checked.count(_ == false))\n val solved = checked.count(_ == false) == 1\n readLine.split(\" \") match {\n\n case Array(\".\", w) =>\n for (c <- w) checked(c - 'a') = true\n\n case Array(\"!\", w) =>\n if (solved) res += 1\n val bad = w.toSet\n for (c <- 'a' to 'z') if (!bad(c)) checked(c - 'a') = true\n\n case Array(\"?\", s) =>\n if (solved) res += 1\n checked(s.head - 'a') = true\n }\n }\n\n println(Math.max(0, res - 1))\n}\n", "positive_code": [{"source_code": "import java.util\n\nimport scala.collection.mutable\nimport scala.io.StdIn\n\n\nobject Solution {\n\n //Console.setIn(new FileReader(new java.io.File(\"input\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n\n var caseNo = 1\n\n def doCase() : Unit = {\n val Array(n) = readIntLine()\n var excessiveCount = 0\n var poss = new mutable.HashSet[Char]()\n (0 until 26).map('a' + _).map(_.asInstanceOf[Char]).foreach(c => poss.add(c))\n var step = 0\n while (step < n) {\n val Array(cmd, wd) = StdIn.readLine().split(\" \")\n cmd match {\n case \"!\" =>\n if (poss.size <= 1) {\n excessiveCount += 1\n }\n poss = poss.intersect(wd.toSet)\n case \".\" => poss = poss.diff(wd.toSet)\n case \"?\" =>\n if (poss.size <= 1 && step != n - 1) {\n excessiveCount += 1\n }\n poss.remove(wd(0))\n }\n step += 1\n }\n println(excessiveCount)\n }\n\n\n def main(args: Array[String]) {\n var tests = 1\n for (test <- 0 until tests) {\n doCase()\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n}\n"}], "negative_code": [], "src_uid": "3583a9762191ee8f8c3c2a287cb1ec1d"} {"source_code": "object AA extends App {\n val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val s3 = v3 max vm\n val s2 = (2 * vm + 1) max (2 * v2)\n val s1 = (2 * vm + 1) max (2 * v1)\n\n def like(v: Int, s: Int): Boolean = v <= s && 2 * v >= s\n\n if (\n vm <= s1 && vm <= s2 && vm <= s3 &&\n like(v1, s1) && like(v2, s2) && like(v3, s3) &&\n !like(vm, s1) && !like(vm, s2) && like(vm, s3)\n ) {\n println(s1)\n println(s2)\n println(s3)\n } else {\n println(\"-1\")\n }\n}\n", "positive_code": [{"source_code": "import java.util\n\nimport scala.collection.mutable\nimport scala.io.StdIn\n\n\nobject Solution {\n\n //Console.setIn(new FileReader(new java.io.File(\"input\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n\n var caseNo = 1\n\n def doCase() : Unit = {\n val Array(f, mo, son, ma) = readIntLine()\n\n var l = f\n while (l <= f * 2) {\n var m = mo\n while (m < Math.min(mo * 2 + 1, l)) {\n var s = son\n while (s < Math.min(m, son * 2 + 1)) {\n\n if (ma * 2 >= s && ma <= s && ma * 2 < m) {\n println(l)\n println(m)\n println(s)\n return\n }\n\n s += 1\n }\n m += 1\n }\n l += 1\n }\n println(-1)\n\n }\n\n\n def main(args: Array[String]) {\n var tests = 1\n for (test <- 0 until tests) {\n doCase()\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n}\n"}, {"source_code": "/**\n * @see http://codeforces.com/contest/907/problem/A\n */\n\nobject AMashaAndBears extends App {\n def like(a: Int, b: Int): Boolean = a <= b && 2 * a >= b\n\n val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val s3 = v3 max vm\n val s2 = (2 * vm + 1) max v2\n val s1 = (2 * vm + 1) max (s2 + 1) max v1\n\n if (like(v1, s1) && like(v2, s2) && like(v3, s3) && like(vm, s3)) {\n println(s1)\n println(s2)\n println(s3)\n } else println(-1)\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(v3, v2, v1, vm) = readInts(4)\n\n for {\n c1 <- vm to 200\n c2 <- c1 + 1 to 200\n c3 <- c2 + 1 to 200\n } {\n if (v1 <= c1 && 2 * v1 >= c1 && //2 * v1 < c2 && //2 * v1 < c2 */&&\n /*v2 > c1 && */v2 <= c2 && 2 * v2 >= c2 && //2 * v2 < c3 &&\n /*v3 > c1 && v3 > c2 && */v3 <= c3 && 2 * v3 >= c3 &&\n 2 * vm >= c1 && 2 * vm < c2 && 2 * vm < c3) {\n println(c3)\n println(c2)\n println(c1)\n System.exit(0)\n }\n }\n\n println(-1)\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(v3, v2, v1, vm) = readInts(4)\n\n for {\n c1 <- vm to 200\n c2 <- c1 + 1 to 200\n c3 <- c2 + 1 to 200\n } {\n if (v1 <= c1 && 2 * v1 >= c1 &&\n v2 <= c2 && 2 * v2 >= c2 &&\n v3 <= c3 && 2 * v3 >= c3 &&\n 2 * vm >= c1 && 2 * vm < c2 && 2 * vm < c3) {\n println(c3)\n println(c2)\n println(c1)\n System.exit(0)\n }\n }\n\n println(-1)\n}\n"}], "negative_code": [{"source_code": "import java.util\n\nimport scala.collection.mutable\nimport scala.io.StdIn\n\n\nobject Solution {\n\n //Console.setIn(new FileReader(new java.io.File(\"input\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n\n var caseNo = 1\n\n def doCase() : Unit = {\n val Array(f, mo, s, ma) = readIntLine()\n\n var lc = f * 2\n var mc = Math.min(lc - 1, mo * 2)\n var sc = Math.max(s, ma)\n if (s * 2 < sc || ma * 2 < sc || s < sc || ma < sc || sc >= mc) {\n println(-1)\n } else {\n println(lc)\n println(mc)\n println(sc)\n }\n\n }\n\n\n def main(args: Array[String]) {\n var tests = 1\n for (test <- 0 until tests) {\n doCase()\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n}\n"}, {"source_code": "import java.util\n\nimport scala.collection.mutable\nimport scala.io.StdIn\n\n\nobject Solution {\n\n //Console.setIn(new FileReader(new java.io.File(\"input\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n\n var caseNo = 1\n\n def doCase() : Unit = {\n val Array(f, mo, s, ma) = readIntLine()\n\n var lc = f * 2\n var mc = Math.min(lc - 1, mo * 2)\n var sc = Math.max(s, ma)\n if (s * 2 < sc\n || ma * 2 < sc\n || s < sc\n || ma < sc\n || sc >= mc\n || ma * 2 >= mc) {\n println(-1)\n } else {\n println(lc)\n println(mc)\n println(sc)\n }\n\n }\n\n\n def main(args: Array[String]) {\n var tests = 1\n for (test <- 0 until tests) {\n doCase()\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(v3, v2, v1, vm) = readInts(4)\n\n for {\n c1 <- vm to 200\n c2 <- c1 to 200\n c3 <- c2 to 200\n } {\n val cMin = Math.min(c1, Math.min(c2, c3))\n if (v1 <= c1 && 2 * v1 >= c1 && //2 * v1 < c2 && //2 * v1 < c2 */&&\n /*v2 > c1 && */v2 <= c2 && 2 * v2 >= c2 && //2 * v2 < c3 &&\n /*v3 > c1 && v3 > c2 && */v3 <= c3 && 2 * v3 >= c3 &&\n 2 * vm >= cMin && (2 * vm < c1 || c1 == cMin) &&\n (2 * vm < c2 || c2 == cMin) && (2 * vm < c3 || c3 == cMin)) {\n println(c3)\n println(c2)\n println(c1)\n System.exit(0)\n }\n }\n\n println(-1)\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(v3, v2, v1, vm) = readInts(4)\n\n for {\n c1 <- vm to 200\n c2 <- vm to 200\n c3 <- vm to 200\n } {\n val cMin = Math.min(c1, Math.min(c2, c3))\n if (v1 <= c1 && 2 * v1 >= c1 && //2 * v1 < c2 && //2 * v1 < c2 */&&\n /*v2 > c1 && */v2 <= c2 && 2 * v2 >= c2 && //2 * v2 < c3 &&\n /*v3 > c1 && v3 > c2 && */v3 <= c3 && 2 * v3 >= c3 &&\n 2 * vm >= cMin && (2 * vm < c1 || c1 == cMin) &&\n (2 * vm < c2 || c2 == cMin) && (2 * vm < c3 || c3 == cMin)) {\n println(c3)\n println(c2)\n println(c1)\n System.exit(0)\n }\n }\n\n println(-1)\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(v3, v2, v1, vm) = readInts(4)\n\n for {\n c1 <- vm to 200\n c2 <- vm to 200\n c3 <- vm to 200\n } {\n if (v1 <= c1 && 2 * v1 >= c1 && //2 * v1 < c2 && //2 * v1 < c2 */&&\n /*v2 > c1 && */v2 <= c2 && 2 * v2 >= c2 && //2 * v2 < c3 &&\n /*v3 > c1 && v3 > c2 && */v3 <= c3 && 2 * v3 >= c3 &&\n 2 * vm >= c1 && 2 * vm < c2 && 2 * vm < c3) {\n println(c3)\n println(c2)\n println(c1)\n System.exit(0)\n }\n }\n\n println(-1)\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(v3, v2, v1, vm) = readInts(4)\n\n for {\n c1 <- vm to 200\n c2 <- vm to 200\n c3 <- vm to 200\n } {\n if (v1 <= c1 && 2 * v1 >= c1 && //2 * v1 < c2 && //2 * v1 < c2 */&&\n /*v2 > c1 && */v2 <= c2 && 2 * v2 >= c2 && //2 * v2 < c3 &&\n /*v3 > c1 && v3 > c2 && */v3 <= c3 && 2 * c3 >= c3 &&\n 2 * vm >= c1 && 2 * vm < c2 && 2 * vm < c3) {\n println(c3)\n println(c2)\n println(c1)\n System.exit(0)\n }\n }\n\n println(-1)\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(v3, v2, v1, vm) = readInts(4)\n\n for {\n c1 <- vm to 200\n c2 <- c1 + 1 to 200\n c3 <- c2 + 1 to 200\n } {\n if (v1 <= c1 && 2 * v1 >= c1 && //2 * v1 < c2 && //2 * v1 < c2 */&&\n /*v2 > c1 && */v2 <= c2 && 2 * v2 >= c2 && //2 * v2 < c3 &&\n /*v3 > c1 && v3 > c2 && */v3 <= c3 && 2 * v3 >= c3 &&\n 2 * vm >= c1) {\n println(c3)\n println(c2)\n println(c1)\n System.exit(0)\n }\n }\n\n println(-1)\n}\n"}, {"source_code": "object AA extends App {\n val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val s3 = v3 max vm\n val s2 = (2 * vm) max v2\n val s1 = (2 * vm) max v1\n\n def like(v: Int, s: Int): Boolean = v <= s && 2 * v >= s\n\n if (like(v3, s3) && like(v2, s2) && like(v1, s1) && like(vm, s3) && !like(vm, s2) && !like(vm, s1)) {\n println(v1)\n println(v2)\n println(v3)\n } else {\n println(\"-1\")\n }\n\n}\n"}, {"source_code": "object AA extends App {\n val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val s3 = v3 max vm\n val s2 = (2 * vm + 1) max v2\n val s1 = (2 * vm + 1) max v1\n\n def like(v: Int, s: Int): Boolean = v <= s && 2 * v >= s\n\n if (\n vm <= s1 && vm <= s2 && vm <= s3 &&\n like(v1, s1) && like(v2, s2) && like(v3, s3) &&\n like(vm, s1) && !like(vm, s2) && !like(vm, s3)\n ) {\n println(v1)\n println(v2)\n println(v3)\n } else {\n println(\"-1\")\n }\n}\n"}, {"source_code": "object AA extends App {\n val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val s3 = v3 max vm\n val s2 = (s3 + 1) max v2\n val s1 = (s3 + 1) max v1\n\n def like(v: Int, s: Int): Boolean = v <= s && 2 * v >= s\n\n if (like(v3, s3) && like(v2, s2) && like(v1, s1) && like(vm, s3) && !like(vm, s2) && !like(vm, s1)) {\n println(v1)\n println(v2)\n println(v3)\n } else {\n println(\"-1\")\n }\n\n}\n"}, {"source_code": "object AA extends App {\n val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val s3 = v3 max vm\n val s2 = (2 * vm + 1) max v2\n val s1 = (2 * vm + 1) max v1\n\n def like(v: Int, s: Int): Boolean = v <= s && 2 * v >= s\n\n if (\n vm <= s1 && vm <= s2 && vm <= s3 &&\n like(v1, s1) && like(v2, s2) && like(v3, s3) &&\n !like(vm, s1) && !like(vm, s2) && like(vm, s3)\n ) {\n println(v1)\n println(v2)\n println(v3)\n } else {\n println(\"-1\")\n }\n}\n"}, {"source_code": "object AA extends App {\n val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n if ((v3 max vm) > ((2 * v3) min (2 * vm))) println(\"-1\")\n else {\n println(v1)\n println(v2)\n println(v3 max vm)\n }\n}\n"}, {"source_code": "object AA extends App {\n val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val s3 = v3 max vm\n val s2 = (2 * vm + 1) max v2\n val s1 = (2 * vm + 1) max v1\n\n def like(v: Int, s: Int): Boolean = v <= s && 2 * v >= s\n\n if (like(v3, s3) && like(v2, s2) && like(v1, s1) && like(vm, s3) && !like(vm, s2) && !like(vm, s1)) {\n println(v1)\n println(v2)\n println(v3)\n } else {\n println(\"-1\")\n }\n\n}\n"}, {"source_code": "object AA extends App {\n val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val s3 = v3 max vm\n val s2 = (2 * vm + 1) max (2 * v2)\n val s1 = (2 * vm + 1) max (2 * v1)\n\n def like(v: Int, s: Int): Boolean = v <= s && 2 * v >= s\n\n if (\n vm <= s1 && vm <= s2 && vm <= s3 &&\n like(v1, s1) && like(v2, s2) && like(v3, s3) &&\n !like(vm, s1) && !like(vm, s2) && like(vm, s3)\n ) {\n println(v1)\n println(v2)\n println(v3)\n } else {\n println(\"-1\")\n }\n}\n"}, {"source_code": "/**\n * @see http://codeforces.com/contest/907/problem/A\n */\n\nobject AMashaAndBears extends App {\n def like(a: Int, b: Int): Boolean = a <= b && 2 * a >= b\n\n val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val s3 = v3 max vm\n val s2 = (2 * vm + 1) max v2\n val s1 = (2 * vm + 1) max v1\n\n if (like(v1, s1) && like(v2, s2) && like(v3, s3) && like(vm, s3)) {\n println(s1)\n println(s2)\n println(s3)\n } else println(-1)\n}\n"}], "src_uid": "56535017d012fdfcc13695dfd5b33084"} {"source_code": "object _977C extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val n, k = io.read[Int]\n val nums = 1 +: io.read[Vector, Int](n).sorted\n val ans = if (k == n || nums(k) != nums(k+1)) {\n nums(k)\n } else {\n -1\n }\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val A = na(N)\n radixSort(A)\n\n val x = if (K == 0) 1 else A(K - 1)\n val x1 = if (K == N) A(K - 1) + 1 else A(K)\n if (x == x1) out.println(-1)\n else out.println(x)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n def radixSort(f: Array[Int]): Array[Int] = radixSort(f, f.length)\n def radixSort(f1: Array[Int], n: Int): Array[Int] = {\n var f = f1\n var to = Array.ofDim[Int](n)\n\n val b = Array.ofDim[Int](65537)\n rep(n){ i => b(1 + (f(i) & 0xffff)) += 1 }\n rep(65536, 1){ i => b(i) += b(i - 1) }\n rep(n){ i =>\n val j = f(i) & 0xffff\n to(b(j)) = f(i)\n b(j) += 1\n }\n val temp = f\n f = to\n to = temp\n\n java.util.Arrays.fill(b, 0)\n rep(n){ i => b(1 + (f(i) >>> 16)) += 1 }\n rep(65536, 1){ i => b(i) += b(i - 1) }\n rep(n){ i =>\n val j = f(i) >>> 16\n to(b(j)) = f(i)\n b(j) += 1\n }\n to\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val A = na(N)\n\n def cntLe(x: Int): Int = {\n var res = 0\n rep(N) { i =>\n if (A(i) <= x) res += 1\n }\n res\n }\n\n def f(x: Int): Boolean = {\n cntLe(x) >= K\n }\n\n var l = 0\n var h = 1e9.toInt + 1\n while(h - l > 1) {\n val m = (h + l) / 2\n if (f(m)) h = m\n else l = m\n }\n\n val x = h\n if (cntLe(x) == K) out.println(x)\n else out.println(-1)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "import java.util.PriorityQueue\n\nimport scala.collection.mutable\n\nobject CE976B extends App {\n val arrayLine = readLine().split(\" \")\n val n = arrayLine(0).toInt\n val k = arrayLine(1).toInt\n val string = readLine();\n val numMap = string.split(\" \").map(_.toInt).sorted\n if (k == 0)\n if (numMap(0) > 1)\n print(numMap(0) - 1)\n else\n print(-1)\n else if (k == n)\n print(numMap(k - 1))\n else if (numMap(k - 1) == numMap(k))\n print(-1)\n else\n print(numMap(k - 1))\n}\n"}, {"source_code": "\n\nimport scala.io.StdIn\n\nobject LessOrEqualTest {\n def main(args: Array[String]):Unit ={\n// val number = StdIn.readInt()\n// val lessOrEqual = new LessOrEqual\n// val isLessOrEqual = lessOrEqual.process(number )\n// print(isLessOrEqual)\n val nk = StdIn.readLine().split(\" \").map(_.toInt)\n val elements = StdIn.readLine().split(\" \").map(_.toInt)\n val elementsSorted = elements.sortWith(_ < _)\n val k = nk(1)\n val n = nk(0)\n\n val res = proc(k,n,elementsSorted)\n\n print(res)\n }\n\n def proc(k: Int, tam: Int, elements:Array[Int]): String ={\n if( k > tam ) return \"-1\"\n if (k == tam) return elements(k-1)+\" \"\n if(k < tam){\n\n if (k == 0 ){\n if (elements(0) > 1){\n return elements( 0 ) - 1+\"\"\n }\n else return \"-1\"\n }\n \n if ( elements( k - 1 ) < elements( k ))\n {return elements(k - 1)+ \"\"}\n }\n return \"-1\"\n }\n}\n"}, {"source_code": "object C732 extends App {\n def parseIn(): (Int, Int, Array[Int]) = {\n val splitted = readLine.split(\" \").map(_.toInt)\n (splitted(0), splitted(1), readLine.split(\" \").map(_.toInt))\n }\n\n def solve(k: Int, data: Array[Int]): Int = {\n if (k == n) data.reverse.head\n else if (k != 0 & n > 1) {\n if (data(k - 1) != data(k)) data(k - 1)\n else -1\n } else {\n if (data.head > 1) {\n if (k == 0 & data.head == 1) -1 \n else if (k == 0) data.head - 1\n else data.head\n } else -1\n }\n }\n\n val (n, k, data) = parseIn\n println(solve(k, data.sortWith(_ < _)))\n}"}, {"source_code": "\nobject problemA {\n import java.io.{BufferedReader, FileInputStream, InputStreamReader}\n import scala.collection.mutable.ArrayBuffer\n import scala.collection.mutable\n import scala.util.control.Breaks._\n import scala.collection.JavaConverters._\n\n val source = System.in\n implicit val reader = new BufferedReader(new InputStreamReader(source))\n\n def read()(implicit reader: BufferedReader): String = reader.readLine().split(\" \")(0)\n def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(\" \")\n def readString()(implicit reader: BufferedReader): String = reader.readLine()\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readArray().map(_.toInt)\n var a = readArray().map(_.toInt)\n a = a.sortWith(_ < _)\n if (k == n) {\n print(a(n - 1))\n return\n }\n\n if (k == 0) {\n if (a(0) - 1 > 0) print(a(0) - 1)\n else print(-1)\n return\n }\n\n if (a(k - 1) == a(k)) {\n print(-1)\n return\n }\n print(a(k - 1))\n }\n}\n"}, {"source_code": "object Problem_977C {\n // Less or Equal\n // The first line of the input contains integer numbers n and k (1≤n≤2⋅105, 0≤k≤n).\n // The second line of the input contains n integer numbers a1,a2,…,an (1≤ai≤109) — the sequence itself.\n\n def main(args: Array[String]) {\n val scan = scala.io.StdIn\n\n //Get inputs\n val inputs: Array[Int] = scan.readLine().split(\" \").map(_.toInt)\n val targetArr: Array[Int] = scan.readLine().split(\" \").map(_.toInt)\n val n= inputs(0)\n val k= inputs(1)\n\n if (k == n) {\n println(targetArr.max)\n }\n else if (k == 0) {\n if (targetArr.min == 1)\n println(\"-1\")\n else\n println(targetArr.min - 1)\n }\n else{\n val sortedArr = targetArr.sorted\n if(sortedArr(k-1) == sortedArr(k))\n println(\"-1\")\n else\n println(sortedArr(k-1))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "object Problem_977C {\n // Less or Equal\n // The first line of the input contains integer numbers n and k (1≤n≤2⋅105, 0≤k≤n).\n // The second line of the input contains n integer numbers a1,a2,…,an (1≤ai≤109) — the sequence itself.\n\n def main(args: Array[String]) {\n val scan = scala.io.StdIn\n\n //Get inputs\n val inputs: Array[Int] = scan.readLine().split(\" \").map(_.toInt)\n val targetArr: Array[Int] = scan.readLine().split(\" \").map(_.toInt)\n val n= inputs(0)\n val k= inputs(1)\n\n if (k == n) {\n if (targetArr.max == Math.pow(10, 9))\n println(\"-1\")\n else\n println(targetArr.max + 1)\n }\n else if (k == 0) {\n if (targetArr.min == 1)\n println(\"-1\")\n else\n println(targetArr.min - 1)\n }\n else{\n val sortedArr = targetArr.sorted\n if(sortedArr(k-1) == sortedArr(k))\n println(\"-1\")\n else\n println(sortedArr(k-1))\n }\n }\n\n}\n"}, {"source_code": "object Problem_977C {\n // Less or Equal\n // The first line of the input contains integer numbers n and k (1≤n≤2⋅105, 0≤k≤n).\n // The second line of the input contains n integer numbers a1,a2,…,an (1≤ai≤109) — the sequence itself.\n\n def main(args: Array[String]) {\n val scan = scala.io.StdIn\n\n //Get inputs\n val inputs: Array[Int] = scan.readLine().split(\" \").map(_.toInt)\n val targetArr: Array[Int] = scan.readLine().split(\" \").map(_.toInt)\n val n= inputs(0)\n val k= inputs(1)\n\n if (k == n) {\n if (targetArr.max == Math.pow(10, 9))\n println(\"-1\")\n else\n println(targetArr.max + 1)\n }\n else if (k == 0) {\n if (targetArr.min == 0)\n println(\"-1\")\n else\n println(targetArr.min - 1)\n }\n else{\n val sortedArr = targetArr.sorted\n if(sortedArr(k-1) == sortedArr(k))\n println(\"-1\")\n else\n println(sortedArr(k-1))\n }\n }\n\n}\n"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val A = na(N)\n\n val ms = A.min\n if (K == 0 && ms == 1) {\n out.println(-1)\n } else if (K == 0 && ms > 1) {\n out.println(1)\n } else if (K == N) {\n out.println(A(N - 1))\n } else {\n def cnt(x: Int) = {\n var s = 0\n rep(N) { i =>\n if (A(i) <= x) s += 1\n }\n s\n }\n\n var l = -1\n var h = N\n while(h - l > 1) {\n val m = (l + h) / 2\n if (cnt(m) < K) l = m\n else h = m\n }\n\n val x = h\n val ans = if (cnt(x) != K) -1 else x\n out.println(ans)\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val A = na(N)\n\n def cnt(x: Int) = {\n var s = 0\n rep(N) { i =>\n if (A(i) <= x) s += 1\n }\n s\n }\n\n if (K == 0) {\n if (cnt(1) > 0) {\n out.println(-1)\n } else {\n out.println(1)\n }\n } else {\n var l = -1\n var h = N\n while(h - l > 1) {\n val m = (l + h) / 2\n if (cnt(m) < K) l = m\n else h = m\n }\n\n val x = h\n val ans = if (cnt(x) != K) -1 else x\n out.println(ans)\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val A = na(N)\n\n def cnt(x: Int) = {\n var s = 0\n rep(N) { i =>\n if (A(i) <= x) s += 1\n }\n s\n }\n\n if (K == 0) {\n if (cnt(1) > 1) {\n out.println(-1)\n } else {\n out.println(1)\n }\n } else if (K == N) {\n out.println(A.max)\n } else {\n var l = -1\n var h = N\n while(h - l > 1) {\n val m = (l + h) / 2\n if (cnt(m) < K) l = m\n else h = m\n }\n\n val x = h\n val ans = if (cnt(x) != K) -1 else x\n out.println(ans)\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "import java.util.PriorityQueue\n\nimport scala.collection.mutable\n\nobject CE976B extends App {\n val arrayLine = readLine().split(\" \")\n val n = arrayLine(0).toInt\n val k = arrayLine(1).toInt\n val string = readLine();\n val numMap = string.split(\" \").map(_.toInt).sorted\n if (k == 0)\n print(numMap(0) - 1)\n else if (k == n)\n print(numMap(k - 1))\n else if (numMap(k - 1) == numMap(k))\n print(-1)\n else\n print(numMap(k - 1))\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject LessOrEqualTest {\n def main(args: Array[String]):Unit ={\n// val number = StdIn.readInt()\n// val lessOrEqual = new LessOrEqual\n// val isLessOrEqual = lessOrEqual.process(number )\n// print(isLessOrEqual)\n val nk = StdIn.readLine().split(\" \").map(_.toInt)\n val elements = StdIn.readLine().split(\" \").map(_.toInt)\n val elementsSorted = elements.sortWith(_ < _)\n val k = nk(1)\n if(k > 0)\n if ( elements( k - 1 ) < elements( k ))\n print( elementsSorted(k - 1) )\n\n print(\"-1\")\n\n }\n}\n"}, {"source_code": "\n\nimport scala.io.StdIn\n\nobject LessOrEqualTest {\n def main(args: Array[String]):Unit ={\n// val number = StdIn.readInt()\n// val lessOrEqual = new LessOrEqual\n// val isLessOrEqual = lessOrEqual.process(number )\n// print(isLessOrEqual)\n val nk = StdIn.readLine().split(\" \").map(_.toInt)\n val elements = StdIn.readLine().split(\" \").map(_.toInt)\n val elementsSorted = elements.sortWith(_ < _)\n val k = nk(1)\n if(k > 0)\n if ( elements( k - 1 ) < elements( k ))\n print( elementsSorted(k - 1) )\n else print(\"-1\")\n else print(\"-1\")\n\n }\n}\n"}, {"source_code": "\n\nimport scala.io.StdIn\n\nobject LessOrEqualTest {\n def main(args: Array[String]):Unit ={\n// val number = StdIn.readInt()\n// val lessOrEqual = new LessOrEqual\n// val isLessOrEqual = lessOrEqual.process(number )\n// print(isLessOrEqual)\n val nk = StdIn.readLine().split(\" \").map(_.toInt)\n val elements = StdIn.readLine().split(\" \").map(_.toInt)\n val elementsSorted = elements.sortWith(_ < _)\n val k = nk(1)\n if(k > 0)\n if ( elements( k - 1 ) < elements( k ))\n print( elementsSorted(k - 1) )\n else print(\"-1\")\n print(\"-1\")\n\n }\n}\n"}, {"source_code": "object C732 extends App {\n def parseIn(): (Int, Int, Array[Int]) = {\n val splitted = readLine.split(\" \").map(_.toInt)\n (splitted(0), splitted(1), readLine.split(\" \").map(_.toInt))\n }\n\n def solve(k: Int, data: Array[Int]): Int = {\n if (k != 0) {\n if (data(k - 1) != data(k)) data(k - 1)\n else -1\n } else -1\n }\n\n val (n, k, data) = parseIn\n println(solve(k, data.sortWith(_ < _)))\n}"}], "src_uid": "55297e2a65144323af4d6abd6a6ef050"} {"source_code": "\n/**\n * Created by ruslan on 3/4/17.\n */\nobject ProblemE extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\nimport java.util.StringTokenizer\n\n override def main(args: Array[String]): Unit = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n var st: StringTokenizer = null\n val out = new PrintWriter(System.out)\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) st =\n new StringTokenizer(br.readLine)\n st.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n val n = nextInt\n\n var result = 0\n for (i <- 1 to n) {\n result += (next match {\n case \"Tetrahedron\" => 4\n case \"Cube\" => 6\n case \"Octahedron\" => 8\n case \"Dodecahedron\" => 12\n case \"Icosahedron\" => 20\n })\n }\n println(result)\n }\n}\n", "positive_code": [{"source_code": "object tanya extends App{\nvar a = readInt\nvar sum = 0\nfor(i <- 0 to a){\n var str = readLine\n if(str == \"Tetrahedron\"){\n sum = sum + 4\n }else if(str == \"Cube\"){\n sum = sum + 6\n }else if(str == \"Octahedron\"){\n sum = sum + 8\n }else if(str == \"Dodecahedron\"){\n sum = sum + 12\n }else if(str == \"Icosahedron\"){\n sum = sum + 20\n }\n}\nprintln(sum)\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.immutable.HashMap\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n\n\nobject A extends App {\n\n\n val sc = new Scanner(System.in)\n\n val sides = HashMap[String, Int](\n \"Tetrahedron\" -> 4,\n \"Cube\" -> 6,\n \"Octahedron\" -> 8,\n \"Dodecahedron\" -> 12,\n \"Icosahedron\" -> 20\n )\n\n val n = sc.nextInt()\n var total = 0\n (1 to n) foreach { _ =>\n total += sides(sc.next())\n }\n println(total)\n}\n"}, {"source_code": "object A785 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n var res = 0L\n val map = Map(\"Tetrahedron\"->4, \"Cube\"->6, \"Octahedron\"->8, \"Dodecahedron\"->12, \"Icosahedron\"->20)\n for(_ <- 1 to n) {\n val input = read\n res += map(input)\n }\n println(res)\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import io.StdIn._\nobject AntonAndHydrones {\n\n def main(args: Array[String]): Unit = {\n val number = readInt()\n var sum = 0\n val result = for(i <- 1 to number) yield{\n var line = readLine()\n var lineValue = line match {\n case \"Tetrahedron\" => 4\n case \"Cube\" => 6\n case \"Octahedron\" => 8\n case \"Dodecahedron\" => 12\n case \"Icosahedron\" => 20\n }\n sum += lineValue\n }\n println(sum)\n }\n\n}"}, {"source_code": "object _785A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n val polygons = read[Seq[String]]\n\n val faces = polygons sumWith {\n case \"Tetrahedron\" => 4\n case \"Cube\" => 6\n case \"Octahedron\" => 8\n case \"Dodecahedron\" => 12\n case \"Icosahedron\" => 20\n }\n\n write(faces)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn\n\nobject TaskA {\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n\n def f(): Int = {\n StdIn.readLine() match {\n case \"Tetrahedron\" => 4\n case \"Cube\" => 6\n case \"Octahedron\" => 8\n case \"Dodecahedron\" => 12\n case \"Icosahedron\" => 20\n }\n }\n\n println((1 to n map (_ => f())).sum)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Codeforces785A extends App {\n var n = StdIn.readLine().toInt\n var s = 0\n while (n > 0) {\n n -= 1\n val p = StdIn.readLine()\n if (p == \"Tetrahedron\") s += 4\n if (p == \"Cube\") s += 6\n if (p == \"Octahedron\") s += 8\n if (p == \"Dodecahedron\") s += 12\n if (p == \"Icosahedron\") s += 20\n }\n print(s)\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Main2 extends App {\n val figureNumber = readInt()\n val res = 0.until(figureNumber).map(_ => readLine()).map {\n case \"Tetrahedron\" => 4\n case \"Cube\" => 6\n case \"Octahedron\" => 8\n case \"Dodecahedron\" => 12\n case \"Icosahedron\" => 20\n }.sum\n println(res)\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.language.postfixOps\n\nobject TaskA extends App {\n val ir = new InputReader(System.in)\n val n = ir.nextInt\n\n val m = Map(\"Tetrahedron\" -> 4, \"Cube\" -> 6, \"Octahedron\" -> 8, \"Dodecahedron\" -> 12, \"Icosahedron\" -> 20)\n\n println(1 to n map { _ => ir.nextString } map m sum)\n}\n\nclass InputReader(val stream: InputStream) {\n val reader = new BufferedReader(new InputStreamReader(stream))\n var stt: StringTokenizer = _\n\n def nextString: String = {\n while (stt == null || !stt.hasMoreTokens) stt = new StringTokenizer(reader.readLine)\n stt.nextToken\n }\n\n def nextInt: Int = nextString.toInt\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Solution {\n\n\tvar n = readLine.toInt\n var shapes = Array.fill[String](n)(null)\n for(i <- 0 until n) shapes(i) = readLine\n\n\tdef main(args:Array[String]):Unit = {\n\t\t\n\t\tvar ret = 0\n\n for(i <- 0 until n) {\n var sides = shapes(i) match {\n case \"Tetrahedron\" => 4\n\t\t\t\tcase \"Cube\" => 6\n\t\t\t\tcase \"Octahedron\" => 8\n\t\t\t\tcase \"Dodecahedron\" => 12\n\t\t\t\tcase \"Icosahedron\" => 20\n }\n\t\t\tret += sides\n }\n\t\t\n\t\tprintln(ret)\n\t}\n\n}\n"}], "negative_code": [{"source_code": "\n/**\n * Created by ruslan on 3/4/17.\n */\nobject ProblemE extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\nimport java.util.StringTokenizer\n\n override def main(args: Array[String]): Unit = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n var st: StringTokenizer = null\n val out = new PrintWriter(System.out)\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) st =\n new StringTokenizer(br.readLine)\n st.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n val n = nextInt\n\n var result = 0\n for (i <- 1 to n) {\n result += (next match {\n case \"Tetrahedron\" => 4\n case \"Cube\" => 4\n case \"Octahedron\" => 8\n case \"Dodecahedron\" => 12\n case \"Icosahedron\" => 20\n })\n }\n println(result)\n }\n}\n"}], "src_uid": "e6689123fefea251555e0e096f58f6d1"} {"source_code": "object Solution {\n def main(args: Array[String]) {\n val r = new Reader()\n val n, k, m = r.read[Int]\n \n import collection.mutable.{ ArrayBuffer, HashMap, HashSet }\n var ws = new HashMap[String, Int]()\n \n for (i <- 0 to n - 1) {\n ws(r.read[String]) = i\n }\n \n val cs = r.read[Array[Long]](n)\n var gs = ArrayBuffer.fill(k)(Long.MaxValue)\n var gs2 = ArrayBuffer.fill(n)(0)\n \n for (i <- 0 to k - 1) {\n val s = r.read[Int]\n \n for (_ <- 1 to s) {\n val e = r.read[Int] - 1\n \n gs(i) = math.min(gs(i), cs(e))\n gs2(e) = i\n }\n }\n \n val ws2 = r.read[Array[String]](m)\n println(ws2.map{ w => gs(gs2(ws(w))) }.sum)\n }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n \n def this() = this(new InputStreamReader(System.in))\n \n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n \n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val int: Read[Int] = new Read(_.tokenizer.next.toInt)\n implicit val long: Read[Long] = new Read(_.tokenizer.next.toLong)\n implicit val double: Read[Double] = new Read(_.tokenizer.next.toDouble)\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n\n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n\n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n}", "positive_code": [{"source_code": "\nobject problemA {\n import java.io.{BufferedReader, FileInputStream, InputStreamReader}\n import scala.collection.mutable.ArrayBuffer\n import scala.collection.mutable\n import scala.util.control.Breaks._\n\n val source = System.in\n //new FileInputStream(\"D://in.txt\")\n implicit val reader = new BufferedReader(new InputStreamReader(source))\n\n def read()(implicit reader: BufferedReader): String = reader.readLine().split(\" \")(0)\n def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(\" \")\n def readString()(implicit reader: BufferedReader): String = reader.readLine()\n\n def main(args: Array[String]): Unit = {\n val Array(n, k, m) = readArray().map(_.toInt)\n val _s = readArray()\n var s = new Array[(String, Int)](n)\n for (i <- 0 until n) s(i) = ((_s(i), i))\n val a = readArray().map(_.toInt)\n var f = new Array[Array[Int]](k)\n val g = new mutable.HashMap[Int, Int]()\n\n for (i <- 0 until k) {\n val x = readArray().map(_.toInt)\n f(i) = new Array(x(0))\n for (j <- 0 until x(0)) {\n f(i)(j) = x(j + 1) - 1\n g += x(j + 1) - 1 -> i\n }\n }\n\n val _s2 = readArray()\n var s2 = new Array[(String, Int)](m)\n for (i <- 0 until m) s2(i) = ((_s2(i), i))\n\n\n var (x, y) = (0, 0)\n val index = new Array[Int](k)\n s = s.sortWith(_._1 < _._1)\n s2 = s2.sortWith(_._1 < _._1)\n f = f.map(_.sortWith(a(_) < a(_)))\n\n var res = 0L\n while (x < s.size && y < s2.size) {\n if (s(x)._1 == s2(y)._1) {\n val id = s(x)._2\n res += a(f(g(id))(0))\n index(g(id)) += 1\n\n y += 1\n } else x += 1\n }\n\n print(res)\n }\n}\n"}], "negative_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val r = new Reader()\n val n, k, m = r.read[Int]\n \n import collection.mutable.{ ArrayBuffer, HashMap, HashSet }\n var ws = new HashMap[String, Int]()\n \n for (i <- 0 to n - 1) {\n ws(r.read[String]) = i\n }\n \n val cs = r.read[Array[Int]](n)\n var gs = ArrayBuffer.fill(k)(Int.MaxValue)\n var gs2 = ArrayBuffer.fill(n)(0)\n \n for (i <- 0 to k - 1) {\n val s = r.read[Int]\n \n for (_ <- 1 to s) {\n val e = r.read[Int] - 1\n \n gs(i) = math.min(gs(i), cs(e))\n gs2(e) = i\n }\n }\n \n val ws2 = r.read[Array[String]](m)\n println(ws2.map{ w => gs(gs2(ws(w))) }.sum)\n }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n \n def this() = this(new InputStreamReader(System.in))\n \n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n \n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val int: Read[Int] = new Read(_.tokenizer.next.toInt)\n implicit val long: Read[Long] = new Read(_.tokenizer.next.toLong)\n implicit val double: Read[Double] = new Read(_.tokenizer.next.toDouble)\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n\n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n\n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n}"}, {"source_code": "\nobject problemA {\n import java.io.{BufferedReader, FileInputStream, InputStreamReader}\n import scala.collection.mutable.ArrayBuffer\n import scala.collection.mutable\n import scala.util.control.Breaks._\n\n val source = System.in\n //new FileInputStream(\"D://in.txt\")\n implicit val reader = new BufferedReader(new InputStreamReader(source))\n\n def read()(implicit reader: BufferedReader): String = reader.readLine().split(\" \")(0)\n def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(\" \")\n def readString()(implicit reader: BufferedReader): String = reader.readLine()\n\n def main(args: Array[String]): Unit = {\n val Array(n, k, m) = readArray().map(_.toInt)\n val _s = readArray()\n var s = new Array[(String, Int)](n)\n for (i <- 0 until n) s(i) = ((_s(i), i))\n val a = readArray().map(_.toInt)\n var f = new Array[Array[Int]](k)\n val g = new mutable.HashMap[Int, Int]()\n\n for (i <- 0 until k) {\n val x = readArray().map(_.toInt)\n f(i) = new Array(x(0))\n for (j <- 0 until x(0)) {\n f(i)(j) = x(j + 1) - 1\n g += x(j + 1) - 1 -> i\n }\n }\n\n val _s2 = readArray()\n var s2 = new Array[(String, Int)](m)\n for (i <- 0 until m) s2(i) = ((_s2(i), i))\n\n\n var (x, y) = (0, 0)\n val index = new Array[Int](k)\n s = s.sortWith(_._1 < _._1)\n s2 = s2.sortWith(_._1 < _._1)\n f = f.map(_.sortWith(a(_) < a(_)))\n\n var res = 0\n while (x < s.size && y < s2.size) {\n if (s(x)._1 == s2(y)._1) {\n val id = s(x)._2\n res += a(f(g(id))(0))\n index(g(id)) += 1\n\n y += 1\n } else x += 1\n }\n\n print(res)\n }\n}\n"}, {"source_code": "\nobject problemA {\n import java.io.{BufferedReader, FileInputStream, InputStreamReader}\n import scala.collection.mutable.ArrayBuffer\n import scala.collection.mutable\n import scala.util.control.Breaks._\n\n val source = System.in\n //new FileInputStream(\"D://in.txt\")\n implicit val reader = new BufferedReader(new InputStreamReader(source))\n\n def read()(implicit reader: BufferedReader): String = reader.readLine().split(\" \")(0)\n def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(\" \")\n def readString()(implicit reader: BufferedReader): String = reader.readLine()\n\n def main(args: Array[String]): Unit = {\n val Array(n, k, m) = readArray().map(_.toInt)\n val s = readArray()\n val a = readArray().map(_.toInt)\n var f = new Array[Array[Int]](k)\n val g = new mutable.HashMap[Int, Int]()\n\n for (i <- 0 until k) {\n val x = readArray().map(_.toInt)\n f(i) = new Array(x(0))\n for (j <- 0 until x(0)) {\n f(i)(j) = x(j + 1) - 1\n g += x(j + 1) - 1 -> i\n }\n }\n\n val s2 = readArray()\n\n var (x, y) = (0, 0)\n val index = new Array[Int](k)\n f = f.map(_.sortWith(a(_) < a(_)))\n\n var res = 0\n while (x < s.size && y < s2.size) {\n if (s(x) == s2(y)) {\n res += a(f(g(x))(index(g(x))))\n index(g(x)) += 1\n\n x += 1\n y += 1\n } else x += 1\n }\n\n print(res)\n }\n}\n"}, {"source_code": "\nobject problemA {\n import java.io.{BufferedReader, FileInputStream, InputStreamReader}\n import scala.collection.mutable.ArrayBuffer\n import scala.collection.mutable\n import scala.util.control.Breaks._\n\n val source = System.in\n //new FileInputStream(\"D://in.txt\")\n implicit val reader = new BufferedReader(new InputStreamReader(source))\n\n def read()(implicit reader: BufferedReader): String = reader.readLine().split(\" \")(0)\n def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(\" \")\n def readString()(implicit reader: BufferedReader): String = reader.readLine()\n\n def main(args: Array[String]): Unit = {\n val Array(n, k, m) = readArray().map(_.toInt)\n val _s = readArray()\n var s = new Array[(String, Int)](n)\n for (i <- 0 until n) s(i) = ((_s(i), i))\n val a = readArray().map(_.toInt)\n var f = new Array[Array[Int]](k)\n val g = new mutable.HashMap[Int, Int]()\n\n for (i <- 0 until k) {\n val x = readArray().map(_.toInt)\n f(i) = new Array(x(0))\n for (j <- 0 until x(0)) {\n f(i)(j) = x(j + 1) - 1\n g += x(j + 1) - 1 -> i\n }\n }\n\n val _s2 = readArray()\n var s2 = new Array[(String, Int)](m)\n for (i <- 0 until m) s2(i) = ((_s2(i), i))\n\n\n var (x, y) = (0, 0)\n val index = new Array[Int](k)\n s = s.sortWith(_._1 < _._1)\n s2 = s2.sortWith(_._1 < _._1)\n f = f.map(_.sortWith(a(_) < a(_)))\n\n var res = 0\n while (x < s.size && y < s2.size) {\n if (s(x)._1 == s2(y)._1) {\n val id = s(x)._2\n res += a(f(g(id))(index(g(id))))\n index(g(id)) += 1\n\n x += 1\n y += 1\n } else x += 1\n }\n\n print(res)\n }\n}\n"}], "src_uid": "296552dc2df23b3920baef7d47d0a591"} {"source_code": "object A681 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = Array.fill(n){\n val tl = tokenizeLine\n tl.nextToken()\n (tl.nextToken().toInt, tl.nextToken().toInt)\n }\n if(in.exists{case (b, a) => b >= 2400 && a > b}) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val n = lines.next().toInt\n if (lines.take(n).map(_.split(' ').drop(1).map(_.toInt)).exists{\n case Array(a, b) => a >= 2400 && b > a\n }) \n println(\"YES\")\n else\n println(\"NO\")\n}\n"}, {"source_code": "\nobject A681 extends App {\n var n = readInt\n var result = \"NO\"\n while(n > 0) {\n val s = readLine.split(\" \")\n\n if(s(1).toInt >= 2400 && s(2).toInt > s(1).toInt) {\n result = \"YES\"\n n = 0\n }\n\n n = n - 1\n }\n\n print(result)\n}\n"}], "negative_code": [], "src_uid": "3bff9b69423cf6c8425e347a4beef96b"} {"source_code": "import java.util.InputMismatchException\nimport java.io.InputStream\nimport scala.collection\n\n/**\n * Created by hama_du on 2014/06/21.\n */\nobject ProblemC extends App {\n /**\n * fast IO\n */\n class InputReader(stream: InputStream) {\n val buf = new Array[Byte](1024)\n var curChar = 0\n var numChars = 0\n\n def next(): Int = {\n if (numChars == -1)\n throw new InputMismatchException();\n if (curChar >= numChars) {\n curChar = 0;\n numChars = stream.read(buf);\n if (numChars <= 0) {\n -1;\n }\n }\n val res = buf(curChar)\n curChar += 1\n res\n }\n\n def nextLong(): Long = {\n var c = next()\n while (isSpaceChar(c)) {\n c = next()\n }\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = next()\n }\n var res = 0L\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c - '0'\n c = next()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextInt(): Int = {\n nextLong.toInt\n }\n\n def isSpaceChar(c: Int) = {\n c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n }\n }\n\n /**\n * solution\n */\n def solve(a: Array[Long]): Long = {\n val n = a.length\n if (n <= 2) {\n return 0\n }\n\n val stack = new collection.mutable.Stack[Long]()\n val score = a.foldLeft(0L)((score, top) => {\n var nextScore = score\n while (stack.size >= 2 && stack(1) >= stack(0) && stack(0) <= top) {\n nextScore += Math.min(top, stack(1))\n stack.pop()\n }\n stack.push(top)\n nextScore\n })\n score + stack.toArray.sorted.dropRight(2).sum\n }\n\n val in = new InputReader(System.in)\n val n = in.nextInt()\n val a = (0 until n).map(_ => in.nextLong()).toArray\n println(solve(a))\n}\n", "positive_code": [{"source_code": "import java.util.InputMismatchException\nimport java.io.InputStream\nimport scala.collection\n\n/**\n * Created by hama_du on 2014/06/21.\n */\nobject ProblemC extends App {\n /**\n * fast IO\n */\n class InputReader(stream: InputStream) {\n val buf = new Array[Byte](1024)\n var curChar = 0\n var numChars = 0\n\n def next(): Int = {\n if (numChars == -1)\n throw new InputMismatchException();\n if (curChar >= numChars) {\n curChar = 0;\n numChars = stream.read(buf);\n if (numChars <= 0) {\n -1;\n }\n }\n val res = buf(curChar)\n curChar += 1\n res\n }\n\n def nextLong(): Long = {\n var c = next()\n while (isSpaceChar(c)) {\n c = next()\n }\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = next()\n }\n var res = 0L\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c - '0'\n c = next()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextInt(): Int = {\n nextLong.toInt\n }\n\n def isSpaceChar(c: Int) = {\n c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n }\n }\n\n def solve(a: Array[(Long,Int)]): Long = {\n val n = a.length\n if (n <= 2) {\n return 0\n }\n\n val done = new Array[Boolean](n)\n val stack = new collection.mutable.Stack[(Long,Int)]()\n val score = a.foldLeft(0L)((score, topWithIndex) => {\n val (top,_) = topWithIndex\n var nextScore = score\n while (stack.size >= 2 && stack(1)._1 >= stack(0)._1 && stack(0)._1 <= top) {\n nextScore += Math.min(top, stack(1)._1)\n val removed = stack.pop()\n done(removed._2) = true\n }\n stack.push(topWithIndex)\n nextScore\n })\n score + a.filterNot(ai => done(ai._2)).map(ai => ai._1).sorted.dropRight(2).sum\n }\n\n val in = new InputReader(System.in)\n val n = in.nextInt()\n val a = (0 until n).map(_ => in.nextLong()).toArray.zipWithIndex\n println(solve(a))\n}\n"}], "negative_code": [{"source_code": "import java.util.InputMismatchException\nimport java.io.InputStream\n\n/**\n * Created by hama_du on 2014/06/21.\n */\nobject ProblemC extends App {\n /**\n * fast IO\n */\n class InputReader(stream: InputStream) {\n val buf = new Array[Byte](1024)\n var curChar = 0\n var numChars = 0\n\n def next(): Int = {\n if (numChars == -1)\n throw new InputMismatchException();\n if (curChar >= numChars) {\n curChar = 0;\n numChars = stream.read(buf);\n if (numChars <= 0) {\n -1;\n }\n }\n val res = buf(curChar)\n curChar += 1\n res\n }\n\n def nextLong(): Long = {\n var c = next()\n while (isSpaceChar(c)) {\n c = next()\n }\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = next()\n }\n var res = 0L\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c - '0'\n c = next()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextInt(): Int = {\n nextLong.toInt\n }\n\n def isSpaceChar(c: Int) = {\n c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n }\n }\n\n def solve(a: Array[(Long,Int)]): Long = {\n val n = a.length\n if (n <= 2) {\n return 0\n }\n\n val done = new Array[Boolean](n)\n val score = a.foldLeft((-2L, -1L, 0L))((lcs, rightWithIndex) => {\n val (left, center, score) = lcs\n val (right,index) = rightWithIndex\n if (left >= center && center <= right) {\n done(index-1) = true\n (left, right, score + Math.min(left, right))\n } else {\n (center, right, score)\n }\n })._3\n score + a.filterNot(ai => done(ai._2)).map(ai => ai._1).sorted.dropRight(2).sum\n }\n\n val in = new InputReader(System.in)\n val n = in.nextInt()\n val a = (0 until n).map(_ => in.nextLong()).toArray.zipWithIndex\n println(solve(a))\n}\n\n"}], "src_uid": "e7e0f9069166fe992abe6f0e19caa6a1"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readLine().toInt\n var best = 0\n for (_ <- 1 to n) {\n val Array(k, a) = readLine().split(\" \").map(_.toInt)\n var need = k + 1;\n var c:Long = 4\n while (a > c) {\n need = need + 1\n c *= 4\n }\n if (need > best) {\n best = need\n }\n }\n println(best)\n }\n}", "positive_code": [{"source_code": "object cf165c extends App {\n val n = readLine.toInt\n val input = (1 to n).map(n => readLine.split(' ').map(_.toInt)).sortBy(x => x(0)).map(p => (p(0), p(1)))\n def cnt(k: Int, num: Int) =\n if (k >= 16) (if (num != 0) 1 else 0) else (num - 1 + (1 << (2 * k))) >> (2 * k)\n var (ans, k) = input.reduceLeft((l, r) => (r._1, List(r._2, cnt(r._1 - l._1, l._2)).max))\n while (k != 1) {\n ans += 1\n k = (k + 3) >> 2\n }\n println(List(ans, input(n-1)._1 + 1).max)\n}"}, {"source_code": "import collection.mutable.Queue\n\nobject test6 extends App {\n val getCount=(count:Double, layer:Int)=>(count/math.pow(4,layer)).ceil toInt\n \n //println(getCount(17,2))\n \n val n=readLine.toInt\n var arr=(for(i<-0 until n) yield readLine.split(\" \").map(_.toInt) toArray) sortBy {a=>a(0)}\n \n\n\n var count=arr(0)(1)\n for(i<- 1 until arr.length){\n count=math.max(arr(i)(1),getCount(count, arr(i)(0)-arr(i-1)(0)))\n }\n \n var i=arr.last.head\n while(count>1) {count=getCount(count,1);i+=1}\n \n println(math.max(i,arr.last.head+1))\n} \n\n\n"}, {"source_code": "object test6 extends App {\n val getCount=(count:Double, layer:Int)=>(count/math.pow(4,layer)).ceil toInt\n \n val n=readLine.toInt\n var arr=(for(i<-0 until n) yield readLine.split(\" \").map(_.toInt) toArray) sortBy {a=>a(0)}\n\n var count=arr(0)(1)\n for(i<- 1 until arr.length){\n count=math.max(arr(i)(1),getCount(count, arr(i)(0)-arr(i-1)(0)))\n }\n \n val ans=arr.last.head+((math.log(count)/math.log(4)).ceil toInt)\n println(math.max(ans,arr.last.head+1))\n} \n\n\n"}], "negative_code": [{"source_code": "object cf165c extends App {\n val n = readLine.toInt\n val input = (1 to n).map(n => readLine.split(' ').map(_.toInt)).sortBy(p => p(1)).map(p => (p(0), p(1)))\n def cnt(k: Int, n: Int) = (n - 1 + (1 << (2 * k))) >> (2 * k)\n var (ans, k) = input.reduceLeft((l, r) => (r._1, List(r._2, cnt(r._1 - l._1, l._2)).max))\n while (k != 1) {\n ans += 1\n k = (k + 3) >> 2\n }\n println( if (input.length == 1 && input(0)._2 == 1) input(0)._1 + 1 else ans)\n}"}, {"source_code": "object cf165c extends App {\n val n = readLine.toInt\n val input = (1 to n).map(n => readLine.split(' ').map(_.toInt)).sortBy(p => p(1)).map(p => (p(0), p(1)))\n def cnt(k: Int, n: Int) = (n - 1 + (1 << (2 * k))) >> (2 * k)\n var (ans, k) = input.reduceLeft((l, r) => (r._1, r._2 + cnt(r._1 - l._1, l._2)))\n while (k != 1) {\n ans += 1\n k = (k + 3) >> 2\n }\n println( if (input.length == 1 && input(0)._2 == 1) input(0)._1 + 1 else ans)\n}"}, {"source_code": "object cf165c extends App {\n val n = readLine.toInt\n val input = (1 to n).map(n => readLine.split(' ').map(_.toInt)).sortBy(p => p(1)).map(p => (p(0), p(1)))\n def cnt(k: Int, n: Int) = (n - 1 + (1 << (2 * k))) >> (2 * k)\n var (k, ans) = input.reduceLeft((l, r) => (r._1, r._2 + cnt(r._1 - l._1, l._2)))\n while (k != 1) {\n ans += 1\n k = (k + 3) >> 2\n }\n println(ans)\n}"}, {"source_code": "object cf165c extends App {\n val n = readLine.toInt\n val input = (1 to n).map(n => readLine.split(' ').map(_.toInt)).sortBy(p => p(1)).map(p => (p(0), p(1)))\n def cnt(k: Int, n: Int): Int = (n - 1 + (1 << (2 * k))) >> (2 * k)\n var (ans, k) = input.reduceLeft((l, r) => (r._1, r._2 + cnt(r._1 - l._1, l._2)))\n while (k != 1) {\n ans += 1\n k = (k + 3) / 4\n }\n println(ans)\n}"}, {"source_code": "object cf165c extends App {\n val n = readLine.toInt\n val input = (1 to n).map(n => readLine.split(' ').map(_.toInt)).sortBy(x => x(0)).map(p => (p(0), p(1)))\n def cnt(k: Int, num: Int) = (num - 1 + (1 << (2 * k))) >> (2 * k)\n var (ans, k) = input.reduceLeft((l, r) => (r._1, List(r._2, cnt(r._1 - l._1, l._2)).max))\n while (k != 1) {\n ans += 1\n k = (k + 3) >> 2\n }\n println(if (input.length == 1 && input(0)._2 == 1) input(0)._1 + 1 else ans)\n}"}, {"source_code": "object cf165c extends App {\n val n = readLine.toInt\n val input = (1 to n).map(n => readLine.split(' ').map(_.toInt)).sortBy(x => x(0)).map(p => (p(0), p(1)))\n def cnt(k: Int, num: Int) =\n if (k >= 16) (if (num != 0) 1 else 0) else (num - 1 + (1 << (2 * k))) >> (2 * k)\n var (ans, k) = input.reduceLeft((l, r) => (r._1, List(r._2, cnt(r._1 - l._1, l._2)).max))\n while (k != 1) {\n ans += 1\n k = (k + 3) >> 2\n }\n println(if (input.length == 1 && input(0)._2 == 1) input(0)._1 + 1 else ans)\n}"}, {"source_code": "import collection.mutable.Queue\n\nobject test6 extends App {\n val n=readLine.toInt\n var arr=(for(i<-0 until n) yield readLine.split(\" \").map(_.toInt) toArray) sortBy {a=>a(0)}\n \n //for(i<-0 until n) println(arr(i).mkString(\",\"))\n val getCount=(count:Int)=>count/4 + (if(count%4==0) 0 else 1)\n var count=0\n var j=0\n for(i<-0 to arr.last.head){\n if(arr(j)(0)==i){\n count=math.max(getCount(count), arr(j).last)\n j+=1\n }\n else count=getCount(count)\n }\n \n var i=arr.last.head\n while(count>1) {count=getCount(count);i+=1}\n println(i)\n} \n\n\n"}, {"source_code": "import collection.mutable.Queue\n\nobject test6 extends App {\n val n=readLine.toInt\n var arr=(for(i<-0 until n) yield readLine.split(\" \").map(_.toInt) toArray) sortBy {a=>a(0)}\n \n //for(i<-0 until n) println(arr(i).mkString(\",\"))\n val getCount=(count:Int)=>count/4 + (if(count%4==0) 0 else 1)\n var count=0\n var j=0\n for(i<-0 to arr.last.head){\n if(arr(j)(0)==i){\n count=math.max(getCount(count), arr(j).last)\n j+=1\n }\n else count=getCount(count)\n }\n \n var i=arr.last.head\n while(count>1) {count=getCount(count);i+=1}\n \n println(if(i==arr.last.head) i+1 else 1)\n} \n\n\n"}, {"source_code": "object test6 extends App {\n val getCount=(count:Double, layer:Int)=>(count/math.pow(4,layer)).ceil toInt\n \n val n=readLine.toInt\n var arr=(for(i<-0 until n) yield readLine.split(\" \").map(_.toInt) toArray) sortBy {a=>a(0)}\n\n var count=arr(0)(1)\n for(i<- 1 until arr.length){\n count=math.max(arr(i)(1),getCount(count, arr(i)(0)-arr(i-1)(0)))\n }\n \n val ans=arr.last.head+(math.log(count)/math.log(4) toInt)\n println(math.max(ans,arr.last.head+1))\n} \n\n\n"}], "src_uid": "15aac7420160f156d5b73059af1fae3b"} {"source_code": "object P032A extends App {\n def upper(a: Array[Int], pos: Int, h: Int):Int = {\n var i = pos\n val b = a(i) + h\n var j = a.length - 1\n if (a(j) <= b) return j;\n while (j > i + 1) {\n val mid = (i + j) / 2\n if (a(mid) <= b) i = mid\n else j = mid\n }\n return i\n }\n def lower(a: Array[Int], pos:Int, h: Int):Int = {\n var i = 0\n var j = pos\n val b = a(j) - h\n if (a(i) >= b) return i\n while (j > i + 1) {\n val mid = (i + j) / 2\n if (a(mid) < b) i = mid\n else j = mid\n }\n return j;\n }\n\n val param = readLine.split(' ').map(_.toInt)\n val a = readLine.split(' ').map(_.toInt).sorted\n var result = 0\n for (i <- 0 to param(0)-1) {\n result += upper(a, i, param(1)) - lower(a, i, param(1))\n }\n print(result)\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, d) = in.next().split(' ').map(_.toInt)\n val line = in.next().split(' ').map(_.toInt)\n\n println(line.indices.foldLeft(0) {\n case (acc, i) => acc + line.indices.count(j => i != j && Math.abs(line(i) - line(j)) <= d)\n })\n}"}, {"source_code": "object A32 {\n import IO._\n import collection.{mutable => cu}\n def main(args: Array[String]): Unit = {\n val Array(n, d) = readInts(2)\n val num = readLongs(n).sorted\n var res = 0\n for(i <- 0 until n; j <- i+1 until n) {\n if(num(j)-num(i) <= d)\n res += 1\n }\n out.println(2*res)\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n}\n"}, {"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var Array(n, d) = readLine.split(\" \").map(_.toInt);\n var arr = readLine.split(\" \").map(_.toInt);\n var result = 0;\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n if (i != j) {\n \t if (math.abs(arr(i) - arr(j)) <= d) {\n \t result += 1;\n \t }\n }\n }\n }\n println(result);\n }\n\n}"}], "negative_code": [], "src_uid": "d7381f73ee29c9b89671f21cafee12e7"} {"source_code": "import scala.collection.mutable.ArrayBuilder\nimport scala.collection.mutable.BitSet\nimport java.io.PrintWriter\n\nobject E extends App {\n\n final class UnionFind(size: Int) {\n\n private val height = Array.fill(size) { 0 }\n private val parent = Array.tabulate(size)(identity)\n\n def find(x: Int): Int = {\n if (parent(x) == x) x\n else {\n parent(x) = find(parent(x))\n parent(x)\n }\n }\n\n def union(x: Int, y: Int) {\n val px = find(x)\n val py = find(y)\n if (height(px) < height(py)) {\n parent(px) = py\n } else {\n parent(py) = px\n if (height(px) == height(py)) height(px) += 1\n }\n }\n\n def same(x: Int, y: Int) = find(x) == find(y)\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n case class Edge(u: Int, v: Int, w: Int, id: Int) {\n def reverse = copy(u = v, v = u)\n }\n\n val edges = Array.ofDim[Edge](2 * m)\n\n for (i <- 0 until m) {\n val Array(u, v, w) = readInts(3)\n val edge = Edge(u - 1, v - 1, w, i)\n edges(i) = edge\n edges(i + m) = edge.reverse\n }\n\n val depths = Array.ofDim[Int](n)\n val ancestors = Array.ofDim[Array[Int]](n)\n val maxWs = Array.ofDim[Array[Int]](n)\n\n def levelAncestor(_v: Int, depth: Int): (Int, Int) = {\n var v = _v\n var i = ancestors(v).length - 1\n var maxW = 0\n while (i >= 0) {\n if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {\n maxW = Math.max(maxW, maxWs(v)(i))\n v = ancestors(v)(i)\n }\n i -= 1\n }\n (v, maxW)\n }\n\n def lowestCommonAncestor(_v: Int, _u: Int): Int = {\n var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)\n var (v, maxW) = levelAncestor(v0, depths(u))\n // now depths(v) == depths(u)\n if (v == u) maxW\n else {\n var i = ancestors(v).length - 1\n while (i >= 0) {\n if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {\n maxW = Math.max(Math.max(maxW, maxWs(u)(i)), maxWs(v)(i))\n u = ancestors(u)(i)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n Math.max(Math.max(maxW, maxWs(u)(0)), maxWs(v)(0))\n }\n }\n\n var mstWeight = 0L\n val uf = new UnionFind(n)\n val onMst = new BitSet(m)\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (edge <- edges.take(m).sortBy(_.w)) {\n if (!uf.same(edge.u, edge.v)) {\n uf.union(edge.u, edge.v)\n mstWeight += edge.w\n onMst += edge.id\n adjBuilders(edge.u) += edge.id\n adjBuilders(edge.v) += edge.id + m\n }\n }\n\n val adjs = adjBuilders.map(_.result)\n\n def dfs(u: Int, parent: Int, depth: Int, w: Int): Unit = {\n\n depths(u) = depth\n\n val ancestorsBuilder = new ArrayBuilder.ofInt\n val maxWBuilder = new ArrayBuilder.ofInt\n\n if (parent >= 0) {\n var i = 0\n var prev = parent\n var max = w\n ancestorsBuilder += parent\n maxWBuilder += max\n while (prev > 0 && i < ancestors(prev).length) {\n max = Math.max(max, maxWs(prev)(i))\n maxWBuilder += max\n prev = ancestors(prev)(i)\n ancestorsBuilder += prev\n i += 1\n }\n }\n\n ancestors(u) = ancestorsBuilder.result\n maxWs(u) = maxWBuilder.result\n\n var i = 0\n while (i < adjs(u).length) {\n val e = edges(adjs(u)(i))\n if (e.v != parent) dfs(e.v, u, depth + 1, e.w)\n i += 1\n }\n }\n\n dfs(0, -1, 0, 0) // prepare\n\n val out = new PrintWriter(System.out)\n for (i <- 0 until m) {\n if (onMst(i)) out.println(mstWeight)\n else {\n val edge = edges(i)\n val maxW = lowestCommonAncestor(edge.u, edge.v)\n out.println(mstWeight - maxW + edge.w)\n }\n }\n\n out.close()\n}", "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuilder\nimport scala.collection.mutable.BitSet\nimport java.io.PrintWriter\n\nobject E extends App {\n\n //new Thread(null, new Main, \"\", 32 * 1024 * 1024).start()\n\n final class UnionFind(size: Int) {\n\n private val height = Array.fill(size) { 0 }\n private val parent = Array.tabulate(size)(identity)\n\n def find(x: Int): Int = {\n if (parent(x) == x) x\n else {\n parent(x) = find(parent(x))\n parent(x)\n }\n }\n\n def union(x: Int, y: Int) {\n val px = find(x)\n val py = find(y)\n if (height(px) < height(py)) {\n parent(px) = py\n } else {\n parent(py) = px\n if (height(px) == height(py)) height(px) += 1\n }\n }\n\n def same(x: Int, y: Int) = find(x) == find(y)\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n case class Edge(u: Int, v: Int, w: Int, id: Int) {\n def reverse = copy(u = v, v = u)\n }\n\n val edges = Array.ofDim[Edge](2 * m)\n\n for (i <- 0 until m) {\n val Array(u, v, w) = readInts(3)\n val edge = Edge(u - 1, v - 1, w, i)\n edges(i) = edge\n edges(i + m) = edge.reverse\n }\n\n val depths = Array.ofDim[Int](n)\n val ancestors = Array.ofDim[Array[Int]](n)\n val maxWs = Array.ofDim[Array[Int]](n)\n\n def levelAncestor(_v: Int, depth: Int): (Int, Int) = {\n var v = _v\n var i = ancestors(v).length - 1\n var maxW = 0\n while (i >= 0) {\n if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {\n maxW = Math.max(maxW, maxWs(v)(i))\n v = ancestors(v)(i)\n }\n i -= 1\n }\n (v, maxW)\n }\n\n def lowestCommonAncestor(_v: Int, _u: Int): Int = {\n var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)\n var (v, maxW) = levelAncestor(v0, depths(u))\n // now depths(v) == depths(u)\n if (v == u) maxW\n else {\n var i = ancestors(v).length - 1\n while (i >= 0) {\n if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {\n maxW = Math.max(Math.max(maxW, maxWs(u)(i)), maxWs(v)(i))\n u = ancestors(u)(i)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n Math.max(Math.max(maxW, maxWs(u)(0)), maxWs(v)(0))\n }\n }\n\n var mstWeight = 0L\n val uf = new UnionFind(n)\n val onMst = new BitSet(m)\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (edge <- edges.take(m).sortBy(_.w)) {\n if (!uf.same(edge.u, edge.v)) {\n uf.union(edge.u, edge.v)\n mstWeight += edge.w\n onMst += edge.id\n adjBuilders(edge.u) += edge.id\n adjBuilders(edge.v) += edge.id + m\n }\n }\n\n val adjs = adjBuilders.map(_.result)\n\n def dfs(u: Int, parent: Int, depth: Int, w: Int): Unit = {\n\n depths(u) = depth\n\n val ancestorsBuilder = new ArrayBuilder.ofInt\n val maxWBuilder = new ArrayBuilder.ofInt\n\n if (parent >= 0) {\n var i = 0\n var prev = parent\n var max = w\n ancestorsBuilder.sizeHint(ancestors(prev).length + 1)\n maxWBuilder.sizeHint(ancestors(prev).length + 1)\n ancestorsBuilder += parent\n maxWBuilder += max\n while (prev > 0 && i < ancestors(prev).length) {\n max = Math.max(max, maxWs(prev)(i))\n maxWBuilder += max\n prev = ancestors(prev)(i)\n ancestorsBuilder += prev\n i += 1\n }\n }\n\n ancestors(u) = ancestorsBuilder.result\n maxWs(u) = maxWBuilder.result\n\n var i = 0\n while (i < adjs(u).length) {\n val e = edges(adjs(u)(i))\n if (e.v != parent) dfs(e.v, u, depth + 1, e.w)\n i += 1\n }\n }\n\n dfs(0, -1, 0, 0) // prepare\n\n val res = Array.ofDim[Long](m)\n\n val out = new PrintWriter(System.out)\n for (i <- 0 until m) {\n if (onMst(i)) res(i) = mstWeight\n else {\n val edge = edges(i)\n val maxW = lowestCommonAncestor(edge.u, edge.v)\n res(edge.id) = mstWeight - maxW + edge.w\n }\n }\n\n out.println(res.mkString(\"\\n\"))\n out.close()\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuilder\nimport scala.collection.mutable.BitSet\nimport java.io.PrintWriter\n\nobject E extends App {\n\n final class UnionFind(size: Int) {\n\n private val height = Array.fill(size) { 0 }\n private val parent = Array.tabulate(size)(identity)\n\n def find(x: Int): Int = {\n if (parent(x) == x) x\n else {\n parent(x) = find(parent(x))\n parent(x)\n }\n }\n\n def union(x: Int, y: Int) {\n val px = find(x)\n val py = find(y)\n if (height(px) < height(py)) {\n parent(px) = py\n } else {\n parent(py) = px\n if (height(px) == height(py)) height(px) += 1\n }\n }\n\n def same(x: Int, y: Int) = find(x) == find(y)\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n case class Edge(u: Int, v: Int, w: Int, id: Int) {\n def reverse = copy(u = v, v = u)\n }\n\n val edges = Array.ofDim[Edge](2 * m)\n\n for (i <- 0 until m) {\n val Array(u, v, w) = readInts(3)\n val edge = Edge(u - 1, v - 1, w, i)\n edges(i) = edge\n edges(i + m) = edge.reverse\n }\n\n val depths = Array.ofDim[Int](n)\n val ancestors = Array.ofDim[Array[Int]](n)\n val maxWs = Array.ofDim[Array[Int]](n)\n\n def levelAncestor(_v: Int, depth: Int): (Int, Int) = {\n var v = _v\n var i = ancestors(v).length - 1\n var maxW = 0\n while (i >= 0) {\n if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {\n maxW = Math.max(maxW, maxWs(v)(i))\n v = ancestors(v)(i)\n }\n i -= 1\n }\n (v, maxW)\n }\n\n def lowestCommonAncestor(_v: Int, _u: Int): Int = {\n var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)\n var (v, maxW) = levelAncestor(v0, depths(u))\n // now depths(v) == depths(u)\n if (v == u) maxW\n else {\n var i = ancestors(v).length - 1\n while (i >= 0) {\n if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {\n maxW = Math.max(Math.max(maxW, maxWs(u)(i)), maxWs(v)(i))\n u = ancestors(u)(i)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n Math.max(Math.max(maxW, maxWs(u)(0)), maxWs(v)(0))\n }\n }\n\n var mstWeight = 0L\n val uf = new UnionFind(n)\n val onMst = new BitSet(m)\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (edge <- edges.take(m).sortBy(_.w)) {\n if (!uf.same(edge.u, edge.v)) {\n uf.union(edge.u, edge.v)\n mstWeight += edge.w\n onMst += edge.id\n adjBuilders(edge.u) += edge.id\n adjBuilders(edge.v) += edge.id + m\n }\n }\n\n val adjs = adjBuilders.map(_.result)\n\n def dfs(u: Int, parent: Int, depth: Int, w: Int): Unit = {\n\n depths(u) = depth\n\n val ancestorsBuilder = new ArrayBuilder.ofInt\n val maxWBuilder = new ArrayBuilder.ofInt\n\n if (parent >= 0) {\n var i = 0\n var prev = parent\n var max = w\n //ancestorsBuilder.sizeHint(ancestors(prev).length + 1)\n //maxWBuilder.sizeHint(ancestors(prev).length + 1)\n ancestorsBuilder += parent\n maxWBuilder += max\n while (prev > 0 && i < ancestors(prev).length) {\n max = Math.max(max, maxWs(prev)(i))\n maxWBuilder += max\n prev = ancestors(prev)(i)\n ancestorsBuilder += prev\n i += 1\n }\n }\n\n ancestors(u) = ancestorsBuilder.result\n maxWs(u) = maxWBuilder.result\n\n var i = 0\n while (i < adjs(u).length) {\n val e = edges(adjs(u)(i))\n if (e.v != parent) dfs(e.v, u, depth + 1, e.w)\n i += 1\n }\n }\n\n dfs(0, -1, 0, 0) // prepare\n\n val res = Array.ofDim[Long](m)\n\n val out = new PrintWriter(System.out)\n for (i <- 0 until m) {\n if (onMst(i)) res(i) = mstWeight\n else {\n val edge = edges(i)\n val maxW = lowestCommonAncestor(edge.u, edge.v)\n res(edge.id) = mstWeight - maxW + edge.w\n }\n }\n\n out.println(res.mkString(\"\\n\"))\n out.close()\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuilder\nimport scala.collection.mutable.BitSet\nimport java.io.PrintWriter\n\nobject E extends App {\n\n final class UnionFind(size: Int) {\n\n private val height = Array.fill(size) { 0 }\n private val parent = Array.tabulate(size)(identity)\n\n def find(x: Int): Int = {\n if (parent(x) == x) x\n else {\n parent(x) = find(parent(x))\n parent(x)\n }\n }\n\n def union(x: Int, y: Int) {\n val px = find(x)\n val py = find(y)\n if (height(px) < height(py)) {\n parent(px) = py\n } else {\n parent(py) = px\n if (height(px) == height(py)) height(px) += 1\n }\n }\n\n def same(x: Int, y: Int) = find(x) == find(y)\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n case class Edge(u: Int, v: Int, w: Int, id: Int) {\n def reverse = copy(u = v, v = u)\n }\n\n val edges = Array.ofDim[Edge](2 * m)\n\n for (i <- 0 until m) {\n val Array(u, v, w) = readInts(3)\n val edge = Edge(u - 1, v - 1, w, i)\n edges(i) = edge\n edges(i + m) = edge.reverse\n }\n\n val depths = Array.ofDim[Int](n)\n val ancestors = Array.ofDim[Array[Int]](n)\n val maxWs = Array.ofDim[Array[Int]](n)\n\n def levelAncestor(_v: Int, depth: Int): (Int, Int) = {\n var v = _v\n var i = ancestors(v).length - 1\n var maxW = 0\n while (i >= 0) {\n if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {\n maxW = Math.max(maxW, maxWs(v)(i))\n v = ancestors(v)(i)\n }\n i -= 1\n }\n (v, maxW)\n }\n\n def lowestCommonAncestor(_v: Int, _u: Int): Int = {\n var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)\n var (v, maxW) = levelAncestor(v0, depths(u))\n // now depths(v) == depths(u)\n if (v == u) maxW\n else {\n var i = ancestors(v).length - 1\n while (i >= 0) {\n if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {\n maxW = Math.max(Math.max(maxW, maxWs(u)(i)), maxWs(v)(i))\n u = ancestors(u)(i)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n Math.max(Math.max(maxW, maxWs(u)(0)), maxWs(v)(0))\n }\n }\n\n var mstWeight = 0L\n val uf = new UnionFind(n)\n val onMst = new BitSet(m)\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (edge <- edges.take(m).sortBy(_.w)) {\n if (!uf.same(edge.u, edge.v)) {\n uf.union(edge.u, edge.v)\n mstWeight += edge.w\n onMst += edge.id\n adjBuilders(edge.u) += edge.id\n adjBuilders(edge.v) += edge.id + m\n }\n }\n\n val adjs = adjBuilders.map(_.result)\n\n def dfs(u: Int, parent: Int, depth: Int, w: Int): Unit = {\n\n depths(u) = depth\n\n val ancestorsBuilder = new ArrayBuilder.ofInt\n val maxWBuilder = new ArrayBuilder.ofInt\n\n if (parent >= 0) {\n var i = 0\n var prev = parent\n var max = w\n ancestorsBuilder += parent\n maxWBuilder += max\n while (prev > 0 && i < ancestors(prev).length) {\n max = Math.max(max, maxWs(prev)(i))\n maxWBuilder += max\n prev = ancestors(prev)(i)\n ancestorsBuilder += prev\n i += 1\n }\n }\n\n ancestors(u) = ancestorsBuilder.result\n maxWs(u) = maxWBuilder.result\n\n var i = 0\n while (i < adjs(u).length) {\n val e = edges(adjs(u)(i))\n if (e.v != parent) dfs(e.v, u, depth + 1, e.w)\n i += 1\n }\n }\n\n dfs(0, -1, 0, 0) // prepare\n\n val res = Array.ofDim[Long](m)\n\n val out = new PrintWriter(System.out)\n for (i <- 0 until m) {\n if (onMst(i)) res(i) = mstWeight\n else {\n val edge = edges(i)\n val maxW = lowestCommonAncestor(edge.u, edge.v)\n res(edge.id) = mstWeight - maxW + edge.w\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.mkString(\"\\n\"))\n Console.flush\n //out.println(res.mkString(\"\\n\"))\n //out.close()\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable.ArrayBuilder\nimport scala.util.Sorting\nimport scala.collection.mutable.BitSet\n\nobject E extends App {\n\n final class UnionFind(size: Int) {\n\n private val height = Array.fill(size){ 0 }\n private val parent = Array.tabulate(size)(identity)\n\n def find(x: Int): Int = {\n if (parent(x) == x) x\n else {\n parent(x) = find(parent(x))\n parent(x)\n }\n }\n\n def union(x: Int, y: Int) {\n val px = find(x)\n val py = find(y)\n if (height(px) < height(py)) {\n parent(px) = py\n } else {\n parent(py) = px\n if (height(px) == height(py)) height(px) += 1\n }\n }\n\n def same(x: Int, y: Int) = find(x) == find(y)\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofRef[Edge] }\n\n case class Edge(u: Int, v: Int, w: Int, id: Int) {\n def reverse = copy(u = v, v = u)\n }\n\n val edges = Array.ofDim[Edge](m)\n\n for (i <- 0 until m) {\n val Array(u, v, w) = readInts(3)\n val edge = Edge(u - 1, v - 1, w, i)\n edges(i) = edge\n adjBuilders(edge.u) += edge\n adjBuilders(edge.v) += edge.reverse\n }\n\n val adjs = adjBuilders.map(_.result)\n\n val res = Array.ofDim[Long](m)\n val onMst = new BitSet(m)\n val depths = Array.ofDim[Int](n)\n val ancestors = Array.ofDim[Array[Int]](n)\n val maxWs = Array.ofDim[Array[Long]](n)\n\n def dfs(u: Int, parent: Int, depth: Int, w: Int): Unit = {\n\n depths(u) = depth\n\n val ancestorsBuilder = new ArrayBuilder.ofInt\n val maxWBuilder = new ArrayBuilder.ofLong\n\n if (parent >= 0) {\n var i = 0\n var prev = parent\n var max: Long = w\n ancestorsBuilder += parent\n maxWBuilder += max\n while (prev > 0 && i < ancestors(prev).length) {\n max = max max maxWs(prev)(i)\n maxWBuilder += max\n prev = ancestors(prev)(i)\n ancestorsBuilder += prev\n i += 1\n }\n }\n\n ancestors(u) = ancestorsBuilder.result\n maxWs(u) = maxWBuilder.result\n\n for (e <- adjs(u)) {\n if (e.v != parent && onMst(e.id)) dfs(e.v, u, depth + 1, e.w)\n }\n }\n\n def levelAncestor(_v: Int, depth: Int): (Int, Long) = {\n var v = _v\n var i = ancestors(v).length - 1\n var maxW = 0L\n while (i >= 0) {\n if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {\n maxW = maxW max maxWs(v)(i)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n (v, maxW)\n }\n\n def lowestCommonAncestor(_v: Int, _u: Int): (Int, Long) = {\n var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)\n var (v, maxW) = levelAncestor(v0, depths(u))\n // now depths(v) == depths(u)\n if (v == u) (v, maxW)\n else {\n var i = ancestors(v).length - 1\n while (i >= 0) {\n if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {\n maxW = maxW max maxWs(u)(i) max maxWs(v)(i)\n u = ancestors(u)(i)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n (ancestors(v)(0), maxW)\n }\n }\n\n var mstWeight = 0L\n val uf = new UnionFind(n)\n\n for (edge <- edges.sortBy(_.w)) {\n if (!uf.same(edge.u, edge.v)) {\n uf.union(edge.u, edge.v)\n mstWeight += edge.w\n onMst += edge.id\n }\n }\n\n dfs(0, -1, 0, 0) // prepare\n\n for (edge <- edges) {\n if (onMst(edge.id)) res(edge.id) = mstWeight\n else {\n val (_, maxW) = lowestCommonAncestor(edge.u, edge.v)\n res(edge.id) = mstWeight - maxW + edge.w\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.mkString(\"\\n\"))\n Console.flush\n}"}], "src_uid": "bab40fe0052e2322116c084008c43366"} {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\n\nobject P376A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n type Lever = Array[Char]\n val lever: Lever = sc.nextLine.toArray\n \n def solve(): String = {\n val pivot: Int = lever.indexOf('^')\n val lhs = lever.slice(0, pivot).reverse\n val rhs = lever.slice(pivot + 1, lever.length)\n \n def moment(l: Lever): Long = {\n \n def w(c: Char): Long = if (c == '=') 0l\n else (c - '0').toLong\n\n var res = 0l\n 0 until l.size foreach { i => res += (i + 1) * w(l(i)) }\n res\n }\n\n val rm = moment(rhs)\n val lm = moment(lhs)\n\n if (lm > rm) \"left\"\n else if (lm < rm) \"right\"\n else \"balance\"\n }\n\n out.println(solve)\n out.close\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val s = readLine()\n val i = s.indexOf('^')\n val sum = s.zipWithIndex.map{ case (c, j) => \n c match {\n case '=' | '^' => 0\n case '1' => 1L * (i - j).toLong\n case '2' => 2L * (i - j).toLong\n case '3' => 3L * (i - j).toLong\n case '4' => 4L * (i - j).toLong\n case '5' => 5L * (i - j).toLong\n case '6' => 6L * (i - j).toLong\n case '7' => 7L * (i - j).toLong\n case '8' => 8L * (i - j).toLong\n case '9' => 9L * (i - j).toLong\n }\n }.sum\n sum match {\n case 0L => println(\"balance\")\n case i: Long if i > 0L => println(\"left\")\n case i: Long if i < 0L => println(\"right\")\n }\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n var str = in.next().split('^')\n val left = str.head.reverse.zipWithIndex.foldLeft(0l){\n case(sum, ('=', index)) => sum\n case(sum, (el, index)) => sum + 1l * el.asDigit * (index + 1)\n }\n val right = str.last.zipWithIndex.foldLeft(0l){\n case(sum, ('=', index)) => sum\n case(sum, (el, index)) => sum + 1l * el.asDigit * (index + 1)\n }\n if (left == right)\n println(\"balance\")\n else if (left > right)\n println(\"left\")\n else\n println(\"right\")\n}"}, {"source_code": "object A376 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n var Array(left, right) = read.split('^')\n left = left.reverse\n var lw = 0L\n for(i <- 0 until left.length if left(i).isDigit) {\n lw += (i+1)*(left(i)-'0')\n }\n var rw = 0L\n for(i <- 0 until right.length if right(i).isDigit) {\n rw += (i+1)*(right(i)-'0')\n }\n if(rw == lw) {\n println(\"balance\")\n } else if (rw > lw) {\n println(\"right\")\n } else {\n println(\"left\")\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\n\nobject P376A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n type Lever = Array[Char]\n\n val lever: Lever = sc.nextLine.toArray\n val N: Int = lever.length\n\n def solve(): String = {\n \n @inline\n def w(c: Char): Long = {\n if (c == '=') 0l\n else (c - '0').toLong\n }\n\n val pivot: Int = {\n var i = 0\n while (lever(i) != '^') i += 1\n i\n }\n\n val lhs: Long = {\n var i = pivot - 1\n var res = 0l\n while (i >= 0) {\n res += (pivot - i) * w(lever(i))\n i -= 1\n }\n res\n }\n\n val rhs: Long = {\n var i = pivot + 1\n var res = 0l\n while (i < N) {\n res += (i - pivot) * w(lever(i))\n i += 1\n }\n res\n }\n \n if (lhs > rhs) \"left\"\n else if (lhs < rhs) \"right\"\n else \"balance\"\n }\n\n out.println(solve)\n out.close\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val s = readLine()\n val i = s.indexOf('^')\n val sum = s.zipWithIndex.map{ case (c, j) => \n c match {\n case '=' | '^' => 0\n case '1' => 1 * (i - j)\n case '2' => 2 * (i - j)\n case '3' => 3 * (i - j)\n case '4' => 4 * (i - j)\n case '5' => 5 * (i - j)\n case '6' => 6 * (i - j)\n case '7' => 7 * (i - j)\n case '8' => 8 * (i - j)\n case '9' => 9 * (i - j)\n }\n }.sum\n sum match {\n case 0 => println(\"balance\")\n case i: Int if i > 0 => println(\"left\")\n case i: Int if i < 0 => println(\"right\")\n }\n }\n}"}], "src_uid": "19f2c21b18e84f50e251b1dfd557d32f"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val m = in.nextInt\n val arr = Array.fill(m, n)(in.nextInt - 1)\n val pos = Array.fill(m, n)(0)\n (0 until m).foreach { i =>\n (0 until n).foreach { j =>\n pos(i)(arr(i)(j)) = j\n }\n }\n var ans: Long = 0\n var i = 0\n\n @inline def ok(x: Int, y: Int): Boolean = (1 until m).forall(i => pos(i)(x) + 1 == pos(i)(y))\n\n while (i < n) {\n val c = i\n while (i < n - 1 && ok(arr(0)(i), arr(0)(i + 1))) {\n i += 1\n }\n i += 1\n ans += (i - c).toLong * (i - c + 1) / 2\n }\n\n println(ans)\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toInt\n }\n\n def nextLong: Double = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}", "positive_code": [{"source_code": "//package codeforces\n\nobject MysteriousCrime {\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val input = new Array[Array[Int]](m)\n\n val trackNext = Array.fill(n + 1)(0)\n\n (0 until m).foreach(i => {\n\n input(i) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n (0 until n).foreach(j => {\n\n trackNext(input(i)(j)) = trackNext(input(i)(j)) match {\n\n case 0 => if (j + 1 < n) input(i)(j + 1) else -1 // uninitialized\n\n case x if j + 1 < n && x != input(i)(j + 1) || j + 1 == n && x != -1 => -1 // discarding now\n\n case y => y // all cool bro\n }\n })\n\n })\n\n\n def computeResult(ls: List[Int], counter: Int, res: Long): Long = {\n\n ls match {\n\n case Nil => res\n\n case h :: t if trackNext(h) == -1 => computeResult(t, 0, res)\n\n case h :: t if trackNext(h) != -1 => computeResult(t, counter + 1, res + counter + 1)\n\n }\n\n }\n\n\n println(n + computeResult(input(0).toList, 0, 0))\n }\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M = ni()\n val A, R = Array.ofDim[Int](N)\n rep(N) { i =>\n A(i) = ni() - 1\n R(A(i)) = i\n }\n\n val flag = Array.fill[Boolean](N - 1)(true)\n rep(M - 1) { _ =>\n val B = Array.ofDim[Int](N)\n rep(N) { i => B(i) = ni() - 1 }\n\n rep(N - 1) { i =>\n val ix = R(B(i))\n if (ix < N - 1) flag(ix) &= A(ix + 1) == B(i + 1)\n }\n val ix = R(B(N - 1))\n if (ix != N - 1) {\n flag(ix) = false\n }\n }\n\n var ans: Long = N\n var cnt = 0\n rep(flag.length) { i =>\n if (flag(i)) {\n cnt += 1\n } else {\n cnt = 0\n }\n ans += cnt\n }\n\n out.println(ans)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}], "negative_code": [{"source_code": "//package codeforces\n\nobject MysteriousCrime {\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val input = new Array[Array[Int]](m)\n\n val trackNext = Array.fill(n + 1)(-2)\n\n (0 until m).foreach(i => {\n\n input(i) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n (0 until n).foreach(j => {\n\n trackNext(input(i)(j)) = trackNext(input(i)(j)) match {\n\n case -2 => if (j + 1 < n) input(i)(j + 1) else 0 // uninitialized\n\n case -1 => -1 // already discarded\n\n case x if j + 1 < n && x != input(i)(j + 1) || j + 1 == n && x != 0 => -1 // discarding now\n\n case y => y // all cool bro\n }\n })\n\n })\n\n\n def computeResult(ls: List[Int], counter: Int, res: Int): Int = {\n\n ls match {\n\n case Nil => res\n\n case h :: t if trackNext(h) == -1 => computeResult(t, 0, res)\n\n case h :: t if trackNext(h) != -1 => computeResult(t, counter + 1, res + counter + 1)\n\n }\n\n }\n\n\n println(n + computeResult(input(0).toList, 0, 0))\n }\n\n}\n"}, {"source_code": "//package codeforces\n\nobject MysteriousCrime {\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val input = new Array[Array[Int]](m)\n\n val trackNext = Array.fill(n + 1)(0)\n\n (0 until m).foreach(i => {\n\n input(i) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n (0 until n).foreach(j => {\n\n trackNext(input(i)(j)) = trackNext(input(i)(j)) match {\n\n case 0 => if (j + 1 < n) input(i)(j + 1) else -1 // uninitialized\n\n case x if j + 1 < n && x != input(i)(j + 1) || j + 1 == n && x != -1 => -1 // discarding now\n\n case y => y // all cool bro\n }\n })\n\n })\n\n\n def computeResult(ls: List[Int], counter: Int, res: Int): Int = {\n\n ls match {\n\n case Nil => res\n\n case h :: t if trackNext(h) == -1 => computeResult(t, 0, res)\n\n case h :: t if trackNext(h) != -1 => computeResult(t, counter + 1, res + counter + 1)\n\n }\n\n }\n\n\n println(n + computeResult(input(0).toList, 0, 0))\n }\n\n}\n"}, {"source_code": "//package codeforces\n\nobject MysteriousCrime {\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val input = new Array[Array[Int]](m)\n\n val trackNext = Array.fill(n + 1)(-2)\n\n (0 until m).foreach(i => {\n\n input(i) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n (0 until n).foreach(j => {\n\n trackNext(input(i)(j)) = trackNext(input(i)(j)) match {\n\n case -2 => if (j + 1 < n) input(i)(j + 1) else 0 // uninitialized\n\n case -1 => -1 // already discarded\n\n case x if j + 1 < n && x != input(i)(j + 1) || j + 1 == n && x != 0 => -1 // discarding now\n\n case y => y // all cool bro\n }\n })\n\n })\n\n\n def computeResult(ls: List[Int], counter: Int, res: Int): Int = {\n\n ls match {\n\n case Nil => res\n\n case h :: t if trackNext(h) == -1 => computeResult(t, 0, res)\n\n case h :: t if trackNext(h) != -1 => computeResult(t, counter + 1, res + counter + 1)\n\n }\n\n }\n\n\n println(n + (if (n > 1) computeResult(input(0).toList, 0, 0) else 0))\n }\n\n}\n"}, {"source_code": "//package codeforces\n\nobject MysteriousCrime {\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val input = new Array[Array[Int]](m)\n\n val trackNext = Array.fill(n + 1)(-2)\n\n (0 until m).foreach(i => {\n\n input(i) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n (0 until n).foreach(j => {\n\n trackNext(input(i)(j)) = trackNext(input(i)(j)) match {\n\n case -2 => if (j + 1 < n) input(i)(j + 1) else 0 // uninitialized\n\n case -1 => -1 // already discarded\n\n case x if j + 1 < n && x != input(i)(j + 1) || j + 1 == n && x != 0 => -1 // discarding now\n\n case y => y // all cool bro\n }\n })\n\n })\n\n\n def computeResult(ls: List[Int], counter: Int, res: Int): Int = {\n\n ls match {\n\n case Nil => res\n\n case h :: t if trackNext(h) == -1 => computeResult(t, 0, res)\n\n case h :: t if trackNext(h) != -1 => computeResult(t, counter + 1, res + counter + 1)\n\n }\n\n }\n\n\n println(n + computeResult(input(0).toList.tail, 0, 0))\n }\n\n}\n"}], "src_uid": "7733551cffde2a78826e9cd53f3a7c9d"} {"source_code": "object GolfedVersion extends App {\n val sc = new java.util.Scanner(System.in)\n val n0, k0 = sc.nextInt\n \n def loop(i: Int, n: Int, k: Int): Option[Map[Int, Int]] =\n if (k > n || k < 1) None\n else if (n/2 >= k) loop(i*2, n/2, k - n%2).map(_ + (i -> n%2))\n else Some(Map(i*2 -> (n-k), i -> (n - (n-k)*2)))\n\n print(loop(1, n0, k0).fold(\"NO\")(m =>\n \"YES\\n\" + (for {\n (k, v) <- m.toSeq.sorted\n e <- Seq.fill(v)(k)\n } yield e).mkString(\" \")\n ))\n}\n", "positive_code": [{"source_code": "object CF_529_3_C {\n\n type In = (Int, Int)\n type Out = String\n\n def solve(in: In): Out = {\n val (n0, k0) = in\n\n def loop(i: Int, bs: Vector[Int], e: Int): Option[Vector[Int]] = (i, e, bs(i)) match {\n // Reached 0, no more to split\n case (0, 0, _) => Some(bs)\n // Reached 0, nonzero splits required\n case (0, _, _) => None\n // No splits required, move to next index\n case (_, _, _) if e < 1 => loop(i-1, bs, e)\n // No digits left to split, move to next index\n case (_, _, 0) => loop(i-1, bs, e)\n // Split a digit\n case (_, _, b) => loop(i, bs.updated(i-1, bs(i-1) + 2).updated(i, b-1), e - 1)\n }\n\n val bs = BigInt(n0).toString(2).toVector.map(_.asDigit).reverse\n\n loop(bs.length - 1, bs, k0 - bs.sum) match {\n case None => \"NO\"\n case Some (xs) =>\n val seq = for {\n (x, i) <- xs.zipWithIndex\n if x > 0\n e <- Seq.fill(x)(math.pow(2, i).toInt)\n } yield e\n \"YES\\n\" + seq.mkString (\" \")\n }\n }\n\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, i.int)\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change: \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def ceil(a: Int, b: Int) = (a - 1)/b + 1\n def ceil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}, {"source_code": "object CF_529_3_C {\n\n type In = (Int, Int)\n type Out = String\n\n def solve(in: In): Out = {\n val (n0, k0) = in\n\n def loop(i: Int, n: Int, k: Int): Option[Map[Int, Int]] =\n if (k > n || k < 1) None\n else if (n/2 >= k)\n // join as many as possible\n loop(i * 2, n/2, k - n%2).map(_ + (i -> n%2))\n else {\n // only join as many as required. c = number to join\n val c = n - k\n Some(Map(i * 2 -> c, i -> (n - c*2)))\n }\n\n loop(1, n0, k0) match {\n case None => \"NO\"\n case Some(m) =>\n val seq = for {\n (k, v) <- m.toSeq.sorted\n e <- Seq.fill(v)(k)\n } yield e\n \"YES\\n\" + seq.mkString(\" \")\n }\n }\n \n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, i.int)\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change: \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def ceil(a: Int, b: Int) = (a - 1)/b + 1\n def ceil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val A = Integer.toBinaryString(N).map(_ - '0').toArray\n val n = A.length\n val cnt = Integer.bitCount(N)\n var k = K - cnt\n var d = 0\n while(k > 0 && d < n - 1) {\n if (A(d) > 0) {\n A(d) -= 1\n A(d + 1) += 2\n k -= 1\n } else {\n d += 1\n }\n }\n\n// debug(A.mkString)\n\n if (k == 0) {\n out.println(\"YES\")\n val ans = ArrayBuffer[Int]()\n REP(n) { d =>\n val num = 1 << (n - 1 - d)\n REP(A(d)) { _ =>\n ans += num\n }\n }\n out.println(ans.reverse.mkString(\" \"))\n } else {\n out.println(\"NO\")\n }\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [], "src_uid": "10d6179b479e1238a51154a9a6fc13cb"} {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, m) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n if (n == 1 || m == 1 || n == m && n == 2) println(\"YES\")\n else println(\"NO\")\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject A {\n def solution(n: Int, m: Int): Boolean =\n n == 1 || m == 1 || (n == 2 && m == 2)\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val Seq(n, m) = readLine.split(\" \").toSeq.map(_.toInt)\n println(if (solution(n, m)) \"YES\" else \"NO\")\n }\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject PuzzlePieces {\n def main(args: Array[String]): Unit = {\n val n = readLine().toInt\n loopWithIndex(n) { i =>\n val l = readLine.split(\" \").map(_.toInt).toList\n val c = l(0)\n val r = l(1)\n if (c == 1 || r == 1) println(\"YES\")\n else\n if (c > 2 || r > 2) println(\"NO\")\n else println(\"YES\")\n }\n }\n\n def loopWithIndex[T](n: Int)(block: Int => T) =\n (1 to n).foreach(e => block(e))\n}"}, {"source_code": "object ProblemA extends App {\n import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val n = in.nextInt()\n\n for (i <- 1 to n) {\n val m = in.nextInt()\n val n = in.nextInt()\n\n if ((n == 1 || m == 1) || (n == 2 && m == 2)) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject PuzzlePieces {\n def main(args: Array[String]): Unit = {\n val n = readLine().toInt\n loopWithIndex(n) { i =>\n val l = readLine.split(\" \").map(_.toInt).toList\n val c = l(0)\n val r = l(1)\n if ((c == 1 && r == 3) || (c == 3 && r == 1)) println(\"YES\")\n else\n if (c > 2 || r > 2) println(\"NO\")\n else println(\"YES\")\n }\n }\n\n def loopWithIndex[T](n: Int)(block: Int => T) =\n (1 to n).foreach(e => block(e))\n}"}], "src_uid": "55595ff38a08b80bc86cf1ebae6f55af"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val (f, s) = in.next().split(' ').map(_.toInt).foldLeft(101, 101) {\n case ((min, second), el) if el < min =>\n (el, min)\n case ((min, second), el) if el < second && el != min =>\n (min, el)\n case (acc, el) => acc\n }\n if (s == 101)\n println(\"NO\")\n else\n println(s)\n}", "positive_code": [{"source_code": "object Flask {\n def main(args: Array[String]): Unit = {\n readLine\n var data = readLine.split(\" \").map(_.toInt)\n if (data.size < 2) { println(\"NO\"); return; }\n \n var first: Option[Int] = None\n var second: Option[Int] = None\n data.foreach(x => x match {\n case x if first == None || x < first.get => { second = first; first = Some(x) }\n case x if first.get != x && (second == None || x < second.get) => { second = Some(x) } \n case _ => {}\n })\n println( if (second == None) \"NO\" else second.get)\n }\n}\n"}, {"source_code": "object A22 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n).distinct.sorted\n if(input.length == 1) {\n out.println(\"NO\")\n } else {\n out.println(input(1))\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var n = readInt;\n var arr = readLine.split(\" \").toList.map(_.toInt);\n var min = arr.min;\n var arrf = arr.filter(p => p != min);\n var result = \"NO\"\n if (!arrf.isEmpty) \n result = arrf.min.toString;\n println(result);\n }\n\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt).toSet.toSeq\n a.sorted.drop(1).headOption match {\n case None => println(\"NO\")\n case Some(i) => println(i)\n }\n }\n}"}], "negative_code": [{"source_code": "object Flask {\n def main(args: Array[String]): Unit = {\n readLine\n var data = readLine.split(\" \").map(_.toInt)\n if (data.size < 3) { println(\"NO\"); return; }\n \n var first: Option[Int] = None\n var second: Option[Int] = None\n data.foreach(x => x match {\n case x if first == None || x < first.get => { second = first; first = Some(x) }\n case x if first.get != x && (second == None || x < second.get) => { second = Some(x) } \n case _ => {}\n })\n println(second.get)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val (f, s) = in.next().split(' ').map(_.toInt).foldLeft(-101, -101) {\n case ((max, second), el) if el > max =>\n (el, max)\n case ((max, second), el) if el > second && el != max =>\n (max, el)\n case (acc, el) => acc\n }\n if (s == -101)\n println(\"NO\")\n else\n println(s)\n\n}"}], "src_uid": "930be5ec102fbe062062aa23eac75187"} {"source_code": "import scala.io.StdIn \n \nobject Solution extends App { \n val arr = StdIn.readLine().split(\" \").map(_.toInt) \n var n = arr(0) \n var k = arr(1) \n \n val days = StdIn.readLine().split(\" \").map(_.toInt) \n if (days.length == 1) println(days.head)else if (k == 1){ \n println(days.max) \n }else { \n var i = 0 \n var max = 0.0 \n while (i + k <= days.length) { \n var start = i + k - 1 \n var aver = 0.0 \n var x = i \n while(x < start) \n { \n aver = aver + days(x) \n x = x + 1 \n } \n aver = aver / (k - 1) \n var lastK = k - 1 \n while (start < days.length) \n { \n val newK = lastK + 1 \n aver = (aver * lastK + days(start) ) / newK \n if (aver > max) max = aver \n lastK = newK \n start = start + 1 \n } \n i = i + 1 \n } \n println(max) \n } \n} ", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val (n, k, temperatures) = readInput\n\n if(k == 1) {\n println(temperatures.max)\n sys.exit(0)\n }\n\n var sum: Double = 0\n var result: Double = 0\n\n (0 to n - k).foreach { i =>\n sum = calcTotal(temperatures, i, i + k - 1)\n\n sum / ((i + k - 1) - i + 1) match {\n case average if (average > result) => result = average\n case _ =>\n }\n\n (i + k to n - 1).foreach { j =>\n sum += temperatures(j)\n\n sum / (j - i + 1) match {\n case average if (average > result) => result = average\n case _ =>\n }\n }\n }\n\n println(result)\n }\n\n private\n\n def readInput = {\n val inputs = readLine.split(' ').map(_.toInt)\n val temperatures = readLine.split(' ').map(_.toInt)\n\n (inputs(0), inputs(1), temperatures)\n }\n\n def calcTotal(temperatures: IndexedSeq[Int], i: Int, j: Int): Int = {\n (i to j).map { i => temperatures(i) }.sum\n }\n\n def isInBounds(i: Int, j: Int, n: Int, k: Int): Boolean = {\n i >= 0 &&\n i <= n - k &&\n j < n\n }\n}\n"}, {"source_code": "object CF_494_3_C {\n\n type In = (Int, Int, Seq[Int])\n type Out = Double\n \n def solve(in: In): Out = {\n val (n, k, as) = in\n\n val cumulative = as.scanLeft(0)(_+_)\n\n var MAX = 0.0\n for {\n start <- 1 to cumulative.size - k\n end <- (start + k - 1) to n\n } MAX = MAX max (cumulative(end) - cumulative(start - 1))/(end - start + 1.0)\n MAX\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, i.int, {i.nextLine; i.intSeq})\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n // `a` MUST be > 0. Incorrect otherwise.\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}, {"source_code": "object CF_494_3_C {\n\n type In = (Int, Int, Seq[Int])\n type Out = Double\n \n def solve(in: In): Out = {\n val (n, k, as) = in\n\n val cumulative = as.scanLeft(0)(_+_)\n\n val aves = for {\n start <- 1 to cumulative.size - k\n end <- (start + k - 1) to n\n } yield (cumulative(end) - cumulative(start - 1))/(end - start + 1.0)\n aves.max\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, i.int, {i.nextLine; i.intSeq})\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n // `a` MUST be > 0. Incorrect otherwise.\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}, {"source_code": "object _1003C extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val n, k = io.read[Int]\n val temps: Vector[Int] = io.read(n)\n val runningSum = temps.scanLeft(0.0)(_ + _)\n\n var ans = 1.0\n for {\n i <- 0 to (n - k)\n j <- (i + k - 1) until n\n l = j - i + 1\n s = runningSum(j+1) - runningSum(i)\n } ans = ans max s/l\n\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val (n, k, temperatures) = readInput\n\n if(k == 1) {\n println(temperatures.max)\n sys.exit(0)\n }\n\n if(n == 500 && k == 250) {\n (8 to 9).foreach { x =>\n println(temperatures.takeRight(500 - x * 50).take(50))\n }\n } else {\n println(\n // new Naive(temperatures, k).run,\n // new Shrink(temperatures, k).run,\n new Expand(temperatures, k).run\n )\n }\n }\n\n private\n\n def readInput = {\n val inputs = readLine.split(' ').map(_.toInt)\n val temperatures = readLine.split(' ').map(_.toInt).toList\n\n (inputs(0), inputs(1), temperatures)\n }\n}\n\nabstract class Solver(temperatures: List[Int], k: Int) {\n val n = temperatures.size\n var total: Double = temperatures.sum\n\n def run: Double\n\n protected\n\n def calcTotal(i: Int, j: Int): Int = {\n (i to j).map { i => temperatures(i) }.toList.sum\n }\n\n def calcAverage(i: Int, j: Int): Double = {\n calcTotal(i, j).toDouble / (j - i + 1)\n }\n}\n\nclass Naive(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n var maxAverage: Double = 0\n\n (0 to n - k).foreach { i =>\n (i + k - 1 to n - 1).foreach { j =>\n calcAverage(i, j) match {\n case average if (average > maxAverage) => {\n maxAverage = average\n }\n case _ =>\n }\n }\n }\n\n maxAverage\n }\n}\n\nclass Shrink(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n shrink(0, n - 1)\n }\n\n private\n\n def shrink(i: Int, j: Int): Double = {\n val size = j - i + 1\n val average = total / size\n\n val noHead = total - temperatures(i)\n val noHeadAverage = noHead / (size - 1)\n\n val noTail = total - temperatures(j)\n val noTailAverage = noTail / (size - 1)\n\n if(j - i + 1 <= k) {\n average\n } else if(noHeadAverage > average) {\n total = noHead\n shrink(i + 1, j)\n } else if(noTailAverage > average) {\n total = noTail\n shrink(i, j - 1)\n } else {\n average\n }\n }\n}\n\nclass Expand(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n (expand _).tupled(start)\n }\n\n private\n\n def start: (Int, Int) = {\n var maxSmallestTotal: Double = 0\n var maxSmallestIndices: (Int, Int) = (0, 0)\n\n (0 to n - k).foreach { i =>\n val j = i + k - 1\n\n calcTotal(i, j) match {\n case average if (average > maxSmallestTotal) => {\n maxSmallestTotal = average\n maxSmallestIndices = (i, j)\n }\n case _ =>\n }\n }\n\n total = maxSmallestTotal\n maxSmallestIndices\n }\n\n def expand(i: Int, j: Int): Double = {\n val size = j - i + 1\n val average = total / size\n\n val leftExpanded = if (i - 1 < 0) total else total + temperatures(i - 1)\n val leftExpandedAverage = leftExpanded / (size + 1)\n\n val rightExpanded = if (j + 1 >= n) total else total + temperatures(j + 1)\n val rightExpandedAverage = rightExpanded / (size + 1)\n\n if(leftExpandedAverage > average) {\n total = leftExpanded\n expand(i - 1, j)\n } else if(rightExpandedAverage > average) {\n total = rightExpanded\n expand(i, j + 1)\n } else {\n average\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.math.pow\n\nobject Main {\n def main(args: Array[String]) = {\n val (n, k) = readMeta\n val temperatures: List[Int] = readLine.split(' ').map(_ toInt).toList\n\n val intensities = (0 to n - k).map { x =>\n val y = x + k - 1\n\n intensity(temperatures, x, y)\n }\n\n println(intensities.max)\n }\n\n def readMeta = {\n val inputs = readLine.split(' ').map(_ toInt)\n\n (inputs(0), inputs(1))\n }\n\n def intensity(list: List[Int], x: Int, y: Int): Double = {\n var sum: Double = 0\n\n (x to y).foreach { i => sum += list(i) }\n\n sum / (y - x + 1)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\nimport util.control.Breaks._\nimport scala.collection.immutable.ListMap\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val (n, k) = getMeta\n val (temperatures, temperatureTuples) = getTemperatures(n)\n\n if(k == 1) {\n println(temperatures.max)\n sys.exit(0)\n }\n\n var maxIntensity: Double = 0\n\n var i = 0\n while(i <= n - 1) {\n var j = i + 1\n\n breakable {\n while(j <= n - 1) {\n val (x, y) = rangeTuple(temperatureTuples, i, j)\n val rangeLength = y - x + 1\n\n if(rangeLength >= k) {\n calcIntensity(temperatures, x, y) match {\n case intensity if (intensity > maxIntensity) => maxIntensity = intensity\n case intensity => break\n }\n }\n\n j += 1\n }\n }\n\n i += 1\n }\n\n println(maxIntensity)\n }\n\n def getMeta = {\n val inputs = readLine.split(' ').map(_.toInt)\n\n (inputs(0), inputs(1))\n }\n\n def getTemperatures(n: Int): (List[Int], List[(Int, Int)]) = {\n val temperatures: List[Int] = readLine.split(' ').map(_.toInt).toList\n val temperatureTuples: List[(Int, Int)] = (0 to n - 1).map { i => (i, temperatures(i)) }.sortBy(_._2 * -1).toList\n\n (temperatures, temperatureTuples)\n }\n\n def calcIntensity(list: List[Int], x: Int, y: Int): Double = {\n var sum: Double = 0\n\n (x to y) foreach { i => sum += list(i) }\n\n sum / (y - x + 1)\n }\n\n def rangeTuple(temperatureTuples: List[(Int, Int)], i: Int, j: Int): (Int, Int) = {\n val list = List(temperatureTuples(i)._1, temperatureTuples(j)._1)\n\n (list.min, list.max)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val (n, k, temperatures) = readInput\n\n if(k == 1) {\n println(temperatures.max)\n sys.exit(0)\n }\n\n var i = 0\n var j = i + k - 1\n var sum = calcTotal(temperatures, i, j).toDouble\n var result = sum / (j - i + 1)\n\n while(isInBounds(i, j, n, k)) {\n j += 1\n\n if(isInBounds(i, j, n, k)) {\n sum = sum + temperatures(j)\n\n sum / (j - i + 1) match {\n case average if (average > result) => result = average\n case _ =>\n }\n } else {\n i += 1\n j = i + k - 1\n if(isInBounds(i, j, n, k)) sum = calcTotal(temperatures, i, j)\n }\n }\n\n println(result)\n }\n\n private\n\n def readInput = {\n val inputs = readLine.split(' ').map(_.toInt)\n val temperatures = readLine.split(' ').map(_.toInt).toList\n\n (inputs(0), inputs(1), temperatures)\n }\n\n def calcTotal(temperatures: List[Int], i: Int, j: Int): Int = {\n (i to j).map { i => temperatures(i) }.toList.sum\n }\n\n def isInBounds(i: Int, j: Int, n: Int, k: Int): Boolean = {\n i >= 0 &&\n i <= n - k &&\n j >= i + k - 1 &&\n j < n\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val (n, k, temperatures) = readInput\n\n if(k == 1) {\n println(temperatures.max)\n sys.exit(0)\n }\n\n if(n == 500 && k == 250) {\n (2 to 9).foreach { x =>\n println(temperatures.takeRight(500 - x * 50).take(50))\n }\n } else {\n println(\n // new Naive(temperatures, k).run,\n // new Shrink(temperatures, k).run,\n new Expand(temperatures, k).run\n )\n }\n }\n\n private\n\n def readInput = {\n val inputs = readLine.split(' ').map(_.toInt)\n val temperatures = readLine.split(' ').map(_.toInt).toList\n\n (inputs(0), inputs(1), temperatures)\n }\n}\n\nabstract class Solver(temperatures: List[Int], k: Int) {\n val n = temperatures.size\n var total: Double = temperatures.sum\n\n def run: Double\n\n protected\n\n def calcTotal(i: Int, j: Int): Int = {\n (i to j).map { i => temperatures(i) }.toList.sum\n }\n\n def calcAverage(i: Int, j: Int): Double = {\n calcTotal(i, j).toDouble / (j - i + 1)\n }\n}\n\nclass Naive(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n var maxAverage: Double = 0\n\n (0 to n - k).foreach { i =>\n (i + k - 1 to n - 1).foreach { j =>\n calcAverage(i, j) match {\n case average if (average > maxAverage) => {\n maxAverage = average\n }\n case _ =>\n }\n }\n }\n\n maxAverage\n }\n}\n\nclass Shrink(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n shrink(0, n - 1)\n }\n\n private\n\n def shrink(i: Int, j: Int): Double = {\n val size = j - i + 1\n val average = total / size\n\n val noHead = total - temperatures(i)\n val noHeadAverage = noHead / (size - 1)\n\n val noTail = total - temperatures(j)\n val noTailAverage = noTail / (size - 1)\n\n if(j - i + 1 <= k) {\n average\n } else if(noHeadAverage > average) {\n total = noHead\n shrink(i + 1, j)\n } else if(noTailAverage > average) {\n total = noTail\n shrink(i, j - 1)\n } else {\n average\n }\n }\n}\n\nclass Expand(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n (expand _).tupled(start)\n }\n\n private\n\n def start: (Int, Int) = {\n var maxSmallestTotal: Double = 0\n var maxSmallestIndices: (Int, Int) = (0, 0)\n\n (0 to n - k).foreach { i =>\n val j = i + k - 1\n\n calcTotal(i, j) match {\n case average if (average > maxSmallestTotal) => {\n maxSmallestTotal = average\n maxSmallestIndices = (i, j)\n }\n case _ =>\n }\n }\n\n total = maxSmallestTotal\n maxSmallestIndices\n }\n\n def expand(i: Int, j: Int): Double = {\n val size = j - i + 1\n val average = total / size\n\n val leftExpanded = if (i - 1 < 0) total else total + temperatures(i - 1)\n val leftExpandedAverage = leftExpanded / (size + 1)\n\n val rightExpanded = if (j + 1 >= n) total else total + temperatures(j + 1)\n val rightExpandedAverage = rightExpanded / (size + 1)\n\n if(leftExpandedAverage > average) {\n total = leftExpanded\n expand(i - 1, j)\n } else if(rightExpandedAverage > average) {\n total = rightExpanded\n expand(i, j + 1)\n } else {\n average\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val (n, k, temperatures) = readInput\n\n if(k == 1) {\n println(temperatures.max)\n sys.exit(0)\n }\n\n if(n == 500 && k == 250) {\n (6 to 9).foreach { x =>\n println(temperatures.takeRight(500 - x * 50).take(50))\n }\n } else {\n println(\n // new Naive(temperatures, k).run,\n // new Shrink(temperatures, k).run,\n new Expand(temperatures, k).run\n )\n }\n }\n\n private\n\n def readInput = {\n val inputs = readLine.split(' ').map(_.toInt)\n val temperatures = readLine.split(' ').map(_.toInt).toList\n\n (inputs(0), inputs(1), temperatures)\n }\n}\n\nabstract class Solver(temperatures: List[Int], k: Int) {\n val n = temperatures.size\n var total: Double = temperatures.sum\n\n def run: Double\n\n protected\n\n def calcTotal(i: Int, j: Int): Int = {\n (i to j).map { i => temperatures(i) }.toList.sum\n }\n\n def calcAverage(i: Int, j: Int): Double = {\n calcTotal(i, j).toDouble / (j - i + 1)\n }\n}\n\nclass Naive(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n var maxAverage: Double = 0\n\n (0 to n - k).foreach { i =>\n (i + k - 1 to n - 1).foreach { j =>\n calcAverage(i, j) match {\n case average if (average > maxAverage) => {\n maxAverage = average\n }\n case _ =>\n }\n }\n }\n\n maxAverage\n }\n}\n\nclass Shrink(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n shrink(0, n - 1)\n }\n\n private\n\n def shrink(i: Int, j: Int): Double = {\n val size = j - i + 1\n val average = total / size\n\n val noHead = total - temperatures(i)\n val noHeadAverage = noHead / (size - 1)\n\n val noTail = total - temperatures(j)\n val noTailAverage = noTail / (size - 1)\n\n if(j - i + 1 <= k) {\n average\n } else if(noHeadAverage > average) {\n total = noHead\n shrink(i + 1, j)\n } else if(noTailAverage > average) {\n total = noTail\n shrink(i, j - 1)\n } else {\n average\n }\n }\n}\n\nclass Expand(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n (expand _).tupled(start)\n }\n\n private\n\n def start: (Int, Int) = {\n var maxSmallestTotal: Double = 0\n var maxSmallestIndices: (Int, Int) = (0, 0)\n\n (0 to n - k).foreach { i =>\n val j = i + k - 1\n\n calcTotal(i, j) match {\n case average if (average > maxSmallestTotal) => {\n maxSmallestTotal = average\n maxSmallestIndices = (i, j)\n }\n case _ =>\n }\n }\n\n total = maxSmallestTotal\n maxSmallestIndices\n }\n\n def expand(i: Int, j: Int): Double = {\n val size = j - i + 1\n val average = total / size\n\n val leftExpanded = if (i - 1 < 0) total else total + temperatures(i - 1)\n val leftExpandedAverage = leftExpanded / (size + 1)\n\n val rightExpanded = if (j + 1 >= n) total else total + temperatures(j + 1)\n val rightExpandedAverage = rightExpanded / (size + 1)\n\n if(leftExpandedAverage > average) {\n total = leftExpanded\n expand(i - 1, j)\n } else if(rightExpandedAverage > average) {\n total = rightExpanded\n expand(i, j + 1)\n } else {\n average\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val (n, k, temperatures) = readInput\n\n if(k == 1) {\n println(temperatures.max)\n sys.exit(0)\n }\n\n if(n == 500 && k == 250) {\n (4 to 9).foreach { x =>\n println(temperatures.takeRight(500 - x * 50).take(50))\n }\n } else {\n println(\n // new Naive(temperatures, k).run,\n // new Shrink(temperatures, k).run,\n new Expand(temperatures, k).run\n )\n }\n }\n\n private\n\n def readInput = {\n val inputs = readLine.split(' ').map(_.toInt)\n val temperatures = readLine.split(' ').map(_.toInt).toList\n\n (inputs(0), inputs(1), temperatures)\n }\n}\n\nabstract class Solver(temperatures: List[Int], k: Int) {\n val n = temperatures.size\n var total: Double = temperatures.sum\n\n def run: Double\n\n protected\n\n def calcTotal(i: Int, j: Int): Int = {\n (i to j).map { i => temperatures(i) }.toList.sum\n }\n\n def calcAverage(i: Int, j: Int): Double = {\n calcTotal(i, j).toDouble / (j - i + 1)\n }\n}\n\nclass Naive(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n var maxAverage: Double = 0\n\n (0 to n - k).foreach { i =>\n (i + k - 1 to n - 1).foreach { j =>\n calcAverage(i, j) match {\n case average if (average > maxAverage) => {\n maxAverage = average\n }\n case _ =>\n }\n }\n }\n\n maxAverage\n }\n}\n\nclass Shrink(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n shrink(0, n - 1)\n }\n\n private\n\n def shrink(i: Int, j: Int): Double = {\n val size = j - i + 1\n val average = total / size\n\n val noHead = total - temperatures(i)\n val noHeadAverage = noHead / (size - 1)\n\n val noTail = total - temperatures(j)\n val noTailAverage = noTail / (size - 1)\n\n if(j - i + 1 <= k) {\n average\n } else if(noHeadAverage > average) {\n total = noHead\n shrink(i + 1, j)\n } else if(noTailAverage > average) {\n total = noTail\n shrink(i, j - 1)\n } else {\n average\n }\n }\n}\n\nclass Expand(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n (expand _).tupled(start)\n }\n\n private\n\n def start: (Int, Int) = {\n var maxSmallestTotal: Double = 0\n var maxSmallestIndices: (Int, Int) = (0, 0)\n\n (0 to n - k).foreach { i =>\n val j = i + k - 1\n\n calcTotal(i, j) match {\n case average if (average > maxSmallestTotal) => {\n maxSmallestTotal = average\n maxSmallestIndices = (i, j)\n }\n case _ =>\n }\n }\n\n total = maxSmallestTotal\n maxSmallestIndices\n }\n\n def expand(i: Int, j: Int): Double = {\n val size = j - i + 1\n val average = total / size\n\n val leftExpanded = if (i - 1 < 0) total else total + temperatures(i - 1)\n val leftExpandedAverage = leftExpanded / (size + 1)\n\n val rightExpanded = if (j + 1 >= n) total else total + temperatures(j + 1)\n val rightExpandedAverage = rightExpanded / (size + 1)\n\n if(leftExpandedAverage > average) {\n total = leftExpanded\n expand(i - 1, j)\n } else if(rightExpandedAverage > average) {\n total = rightExpanded\n expand(i, j + 1)\n } else {\n average\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val (n, k, temperatures) = readInput\n\n if(k == 1) {\n println(temperatures.max)\n sys.exit(0)\n }\n\n if(n == 500 && k == 250) {\n println(temperatures)\n } else {\n println(\n // new Naive(temperatures, k).run,\n // new Shrink(temperatures, k).run,\n new Expand(temperatures, k).run\n )\n }\n }\n\n private\n\n def readInput = {\n val inputs = readLine.split(' ').map(_.toInt)\n val temperatures = readLine.split(' ').map(_.toInt).toList\n\n (inputs(0), inputs(1), temperatures)\n }\n}\n\nabstract class Solver(temperatures: List[Int], k: Int) {\n val n = temperatures.size\n var total: Double = temperatures.sum\n\n def run: Double\n\n protected\n\n def calcTotal(i: Int, j: Int): Int = {\n (i to j).map { i => temperatures(i) }.toList.sum\n }\n\n def calcAverage(i: Int, j: Int): Double = {\n calcTotal(i, j).toDouble / (j - i + 1)\n }\n}\n\nclass Naive(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n var maxAverage: Double = 0\n\n (0 to n - k).foreach { i =>\n (i + k - 1 to n - 1).foreach { j =>\n calcAverage(i, j) match {\n case average if (average > maxAverage) => {\n maxAverage = average\n }\n case _ =>\n }\n }\n }\n\n maxAverage\n }\n}\n\nclass Shrink(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n shrink(0, n - 1)\n }\n\n private\n\n def shrink(i: Int, j: Int): Double = {\n val size = j - i + 1\n val average = total / size\n\n val noHead = total - temperatures(i)\n val noHeadAverage = noHead / (size - 1)\n\n val noTail = total - temperatures(j)\n val noTailAverage = noTail / (size - 1)\n\n if(j - i + 1 <= k) {\n average\n } else if(noHeadAverage > average) {\n total = noHead\n shrink(i + 1, j)\n } else if(noTailAverage > average) {\n total = noTail\n shrink(i, j - 1)\n } else {\n average\n }\n }\n}\n\nclass Expand(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n (expand _).tupled(start)\n }\n\n private\n\n def start: (Int, Int) = {\n var maxSmallestTotal: Double = 0\n var maxSmallestIndices: (Int, Int) = (0, 0)\n\n (0 to n - k).foreach { i =>\n val j = i + k - 1\n\n calcTotal(i, j) match {\n case average if (average > maxSmallestTotal) => {\n maxSmallestTotal = average\n maxSmallestIndices = (i, j)\n }\n case _ =>\n }\n }\n\n total = maxSmallestTotal\n maxSmallestIndices\n }\n\n def expand(i: Int, j: Int): Double = {\n val size = j - i + 1\n val average = total / size\n\n val leftExpanded = if (i - 1 < 0) total else total + temperatures(i - 1)\n val leftExpandedAverage = leftExpanded / (size + 1)\n\n val rightExpanded = if (j + 1 >= n) total else total + temperatures(j + 1)\n val rightExpandedAverage = rightExpanded / (size + 1)\n\n if(leftExpandedAverage > average) {\n total = leftExpanded\n expand(i - 1, j)\n } else if(rightExpandedAverage > average) {\n total = rightExpanded\n expand(i, j + 1)\n } else {\n average\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val (n, k, temperatures) = readInput\n\n if(k == 1) {\n println(temperatures.max)\n sys.exit(0)\n }\n\n if(n == 500 && k == 250) {\n (0 to 9).foreach { x =>\n println(temperatures.takeRight(500 - x * 50).take(50))\n }\n } else {\n println(\n // new Naive(temperatures, k).run,\n // new Shrink(temperatures, k).run,\n new Expand(temperatures, k).run\n )\n }\n }\n\n private\n\n def readInput = {\n val inputs = readLine.split(' ').map(_.toInt)\n val temperatures = readLine.split(' ').map(_.toInt).toList\n\n (inputs(0), inputs(1), temperatures)\n }\n}\n\nabstract class Solver(temperatures: List[Int], k: Int) {\n val n = temperatures.size\n var total: Double = temperatures.sum\n\n def run: Double\n\n protected\n\n def calcTotal(i: Int, j: Int): Int = {\n (i to j).map { i => temperatures(i) }.toList.sum\n }\n\n def calcAverage(i: Int, j: Int): Double = {\n calcTotal(i, j).toDouble / (j - i + 1)\n }\n}\n\nclass Naive(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n var maxAverage: Double = 0\n\n (0 to n - k).foreach { i =>\n (i + k - 1 to n - 1).foreach { j =>\n calcAverage(i, j) match {\n case average if (average > maxAverage) => {\n maxAverage = average\n }\n case _ =>\n }\n }\n }\n\n maxAverage\n }\n}\n\nclass Shrink(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n shrink(0, n - 1)\n }\n\n private\n\n def shrink(i: Int, j: Int): Double = {\n val size = j - i + 1\n val average = total / size\n\n val noHead = total - temperatures(i)\n val noHeadAverage = noHead / (size - 1)\n\n val noTail = total - temperatures(j)\n val noTailAverage = noTail / (size - 1)\n\n if(j - i + 1 <= k) {\n average\n } else if(noHeadAverage > average) {\n total = noHead\n shrink(i + 1, j)\n } else if(noTailAverage > average) {\n total = noTail\n shrink(i, j - 1)\n } else {\n average\n }\n }\n}\n\nclass Expand(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n (expand _).tupled(start)\n }\n\n private\n\n def start: (Int, Int) = {\n var maxSmallestTotal: Double = 0\n var maxSmallestIndices: (Int, Int) = (0, 0)\n\n (0 to n - k).foreach { i =>\n val j = i + k - 1\n\n calcTotal(i, j) match {\n case average if (average > maxSmallestTotal) => {\n maxSmallestTotal = average\n maxSmallestIndices = (i, j)\n }\n case _ =>\n }\n }\n\n total = maxSmallestTotal\n maxSmallestIndices\n }\n\n def expand(i: Int, j: Int): Double = {\n val size = j - i + 1\n val average = total / size\n\n val leftExpanded = if (i - 1 < 0) total else total + temperatures(i - 1)\n val leftExpandedAverage = leftExpanded / (size + 1)\n\n val rightExpanded = if (j + 1 >= n) total else total + temperatures(j + 1)\n val rightExpandedAverage = rightExpanded / (size + 1)\n\n if(leftExpandedAverage > average) {\n total = leftExpanded\n expand(i - 1, j)\n } else if(rightExpandedAverage > average) {\n total = rightExpanded\n expand(i, j + 1)\n } else {\n average\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn\nimport util.control.Breaks._\nimport scala.collection.immutable.ListMap\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val (n, k) = getMeta\n val (temperatures, temperatureTuples) = getTemperatures(n)\n\n if(k == 1) sys.exit(0)\n\n var maxIntensity: Double = 0\n\n var i = 0\n while(i <= n - 1) {\n var j = i + 1\n\n breakable {\n while(j <= n - 1) {\n val (x, y) = rangeTuple(temperatureTuples, i, j)\n val rangeLength = y - x + 1\n\n if(rangeLength >= k) {\n calcIntensity(temperatures, x, y) match {\n case intensity if (intensity > maxIntensity) => maxIntensity = intensity\n case intensity => break\n }\n }\n\n j += 1\n }\n }\n\n i += 1\n }\n\n println(maxIntensity)\n }\n\n def getMeta = {\n val inputs = readLine.split(' ').map(_.toInt)\n\n (inputs(0), inputs(1))\n }\n\n def getTemperatures(n: Int): (List[Int], List[(Int, Int)]) = {\n val temperatures: List[Int] = readLine.split(' ').map(_.toInt).toList\n val temperatureTuples: List[(Int, Int)] = (0 to n - 1).map { i => (i, temperatures(i)) }.sortBy(_._2 * -1).toList\n\n (temperatures, temperatureTuples)\n }\n\n def calcIntensity(list: List[Int], x: Int, y: Int): Double = {\n var sum: Double = 0\n\n (x to y) foreach { i => sum += list(i) }\n\n sum / (y - x + 1)\n }\n\n def rangeTuple(temperatureTuples: List[(Int, Int)], i: Int, j: Int): (Int, Int) = {\n val list = List(temperatureTuples(i)._1, temperatureTuples(j)._1)\n\n (list.min, list.max)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\nimport util.control.Breaks._\nimport scala.collection.immutable.ListMap\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val (n, k) = getMeta\n val (temperatures, temperatureTuples) = getTemperatures(n)\n\n if(k == 1) sys.exit(0)\n\n var maxIntensity: Double = 0\n\n var i = 0\n while(i <= n - 1) {\n var j = i + 1\n\n breakable {\n while(j <= n - 1) {\n val (x, y) = rangeTuple(temperatureTuples, i, j)\n val rangeLength = y - x + 1\n\n if(rangeLength >= k) {\n calcIntensity(temperatures, x, y) match {\n case intensity if (intensity > maxIntensity) => maxIntensity = intensity\n case intensity => break\n }\n }\n\n j += 1\n }\n }\n\n i += 1\n }\n\n printf(\"%.12f\", maxIntensity)\n }\n\n def getMeta = {\n val inputs = readLine.split(' ').map(_.toInt)\n\n (inputs(0), inputs(1))\n }\n\n def getTemperatures(n: Int): (List[Int], List[(Int, Int)]) = {\n val temperatures: List[Int] = readLine.split(' ').map(_.toInt).toList\n val temperatureTuples: List[(Int, Int)] = (0 to n - 1).map { i => (i, temperatures(i)) }.sortBy(_._2 * -1).toList\n\n (temperatures, temperatureTuples)\n }\n\n def calcIntensity(list: List[Int], x: Int, y: Int): Double = {\n var sum: Double = 0\n\n (x to y) foreach { i => sum += list(i) }\n\n sum / (y - x + 1)\n }\n\n def rangeTuple(temperatureTuples: List[(Int, Int)], i: Int, j: Int): (Int, Int) = {\n val list = List(temperatureTuples(i)._1, temperatureTuples(j)._1)\n\n (list.min, list.max)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val (n, k, temperatures) = readInput\n\n if(k == 1) {\n println(temperatures.max)\n sys.exit(0)\n }\n\n println(\n // new Naive(temperatures, k).run,\n // new Shrink(temperatures, k).run,\n new Expand(temperatures, k).run\n )\n }\n\n private\n\n def readInput = {\n val inputs = readLine.split(' ').map(_.toInt)\n val temperatures = readLine.split(' ').map(_.toInt).toList\n\n (inputs(0), inputs(1), temperatures)\n }\n}\n\nabstract class Solver(temperatures: List[Int], k: Int) {\n val n = temperatures.size\n var total: Double = temperatures.sum\n\n def run: Double\n\n protected\n\n def calcTotal(i: Int, j: Int): Int = {\n (i to j).map { i => temperatures(i) }.toList.sum\n }\n\n def calcAverage(i: Int, j: Int): Double = {\n calcTotal(i, j).toDouble / (j - i + 1)\n }\n}\n\nclass Naive(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n var maxAverage: Double = 0\n\n (0 to n - k).foreach { i =>\n (i + k - 1 to n - 1).foreach { j =>\n calcAverage(i, j) match {\n case average if (average > maxAverage) => {\n maxAverage = average\n }\n case _ =>\n }\n }\n }\n\n maxAverage\n }\n}\n\nclass Shrink(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n shrink(0, n - 1)\n }\n\n private\n\n def shrink(i: Int, j: Int): Double = {\n val size = j - i + 1\n val average = total / size\n\n val noHead = total - temperatures(i)\n val noHeadAverage = noHead / (size - 1)\n\n val noTail = total - temperatures(j)\n val noTailAverage = noTail / (size - 1)\n\n if(j - i + 1 <= k) {\n average\n } else if(noHeadAverage > average) {\n total = noHead\n shrink(i + 1, j)\n } else if(noTailAverage > average) {\n total = noTail\n shrink(i, j - 1)\n } else {\n average\n }\n }\n}\n\nclass Expand(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {\n def run: Double = {\n (expand _).tupled(start)\n }\n\n private\n\n def start: (Int, Int) = {\n var maxSmallestTotal: Double = 0\n var maxSmallestIndices: (Int, Int) = (0, 0)\n\n (0 to n - k).foreach { i =>\n val j = i + k - 1\n\n calcTotal(i, j) match {\n case average if (average > maxSmallestTotal) => {\n maxSmallestTotal = average\n maxSmallestIndices = (i, j)\n }\n case _ =>\n }\n }\n\n total = maxSmallestTotal\n maxSmallestIndices\n }\n\n def expand(i: Int, j: Int): Double = {\n val size = j - i + 1\n val average = total / size\n\n val leftExpanded = if (i - 1 < 0) total else total + temperatures(i - 1)\n val leftExpandedAverage = leftExpanded / (size + 1)\n\n val rightExpanded = if (j + 1 >= n) total else total + temperatures(j + 1)\n val rightExpandedAverage = rightExpanded / (size + 1)\n\n if(leftExpandedAverage > average) {\n total = leftExpanded\n expand(i - 1, j)\n } else if(rightExpandedAverage > average) {\n total = rightExpanded\n expand(i, j + 1)\n } else {\n average\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn \n \nobject Solution extends App { \n val arr = StdIn.readLine().split(\" \").map(_.toInt) \n var n = arr(0) \n var k = arr(1) \n \n val days = StdIn.readLine().split(\" \").map(_.toInt) .toList \n \n var i = 0 \n var max = 0.0 \n while (i + k < days.length) \n { \n var start = i + k \n while(start < days.length) { \n val l = days.slice(i, start) \n var rez = l.sum.toDouble / l.size \n if (rez > max) max = rez \n start = start + 1 \n } \n i = i + 1 \n } \n println(max) \n \n} "}, {"source_code": "object CF_494_3_C {\n\n type In = (Int, Int, Seq[Int])\n type Out = Double\n \n def solve(in: In): Out = {\n val (n, k, as) = in\n\n val aves = for {\n ts <- as.sliding(k)\n } yield ts.sum.toDouble / ts.size\n\n aves.max\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, i.int, {i.nextLine; i.intSeq})\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n // `a` MUST be > 0. Incorrect otherwise.\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}"}, {"source_code": "object CF_494_3_C {\n\n type In = (Int, Int, Seq[Int])\n type Out = Double\n \n def solve(in: In): Out = {\n val (n, k, as) = in\n\n val aves = for {\n ts <- as.sliding(k).filter(_.length == k)\n } yield ts.sum.toDouble / ts.size\n\n aves.max\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, i.int, {i.nextLine; i.intSeq})\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n // `a` MUST be > 0. Incorrect otherwise.\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}"}], "src_uid": "7bdb68ab0752f8df94b4d5c7df759dfb"} {"source_code": "import java.util.Scanner\n\nobject Matrix extends App {\n\n\tval scanner = new Scanner( System.in )\n\n\tval n = scanner.nextInt\n\tval m = scanner.nextInt\n\tval d = scanner.nextInt\n\n\t// there is no need to represent the matrix as two dimensional array - it simple to use 1 dimension\n\tval size = n * m\n\tval matrix = Array.ofDim[Int]( size )\n\n\tfor( i <- 0 until size )\n\t\tmatrix( i ) = scanner.nextInt\n\n\tval min = matrix.min\n\tval possible = matrix.forall( v => (v - min) % d == 0 )\n\n\tval moves = if( possible ) {\n\t\tval sorted = matrix.sorted\n\t\tval target = sorted( size / 2 )\t\t// median (we don't need exact value for even sample size)\n\t\tmatrix.foldLeft( 0 )( (m,v) => m + (v - target).abs / d )\n\t}\n\telse\n\t\t-1\n\n\tprintln( moves )\n}", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m, d) = in.next().split(' ').map(_.toInt)\n val data = (1 to n).flatMap(i => in.next().split(' ').map(_.toInt))\n val min = data.min\n val normData = data.map(_ - min)\n if (normData.exists(_ % d != 0))\n println(-1)\n else {\n val goodData = data.map(_ / d)\n val max = goodData.max\n val start = goodData.sum / goodData.length\n val up = (start to max).foldLeft((false, Integer.MAX_VALUE)) {\n case (acc@(true, _), i) => acc\n case ((false, prevValue), i) =>\n val nValue = goodData.foldLeft(0){case(acc, j) => acc + Math.abs(i - j)}\n if (nValue > prevValue)\n (true, prevValue)\n else\n (false, nValue)\n }._2\n val down = (start - 1 to 0 by -1).foldLeft((false, Integer.MAX_VALUE)) {\n case (acc@(true, _), i) => acc\n case ((false, prevValue), i) =>\n val nValue = goodData.foldLeft(0){case(acc, j) => acc + Math.abs(i - j)}\n if (nValue > prevValue)\n (true, prevValue)\n else\n (false, nValue)\n }._2\n println(Math.min(down, up))\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, m, d) = readLine().split(\" \").map(_.toInt)\n val a = (1 to n) flatMap { _ => readLine().split(\" \").map(_.toInt) }\n val s = a.sorted\n val avg1 = s(s.size / 2)\n val cor = a forall (i => (i - avg1).abs % d == 0)\n if (!cor) println(\"-1\")\n else println(a.map(i => (i - avg1).abs / d).sum)\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, m, d) = readLine().split(\" \").map(_.toInt)\n val a = (1 to n) flatMap { _ => readLine().split(\" \").map(_.toInt) }\n val avg = a.map(_.toFloat).sum / (n * m)\n val avg1 = ((a(0).toFloat - avg).abs / d).round.toInt + a(0)\n val cor = a forall (i => (i - avg1).abs % d == 0)\n if (!cor) println(\"-1\")\n else println(a.map(i => (i - avg1).abs / d).sum)\n }\n}"}], "src_uid": "3488bb49de69c0c17ea0439e71b1e6ae"} {"source_code": "import java.util.Scanner\n\n/**\n * Created by lurker on 2014. 7. 20..\n */\nobject CF256_C extends App {\n\n def Process(values:Array[Int]):Int = {\n case class WaitingCall(l:Int, r:Int, h:Int,var v:Option[Int] = None)\n case class Visited(minh:Int, left:WaitingCall, right:WaitingCall, me:WaitingCall)\n\n val waitingQueue = scala.collection.mutable.Queue[WaitingCall]()\n val visited = scala.collection.mutable.Stack[Visited]()\n\n waitingQueue.enqueue(WaitingCall(0, values.length-1, 0))\n\n while(waitingQueue.nonEmpty) {\n val v = waitingQueue.dequeue()\n if(v.l > v.r) {\n v.v = Some(0)\n } else {\n var minvalue = Integer.MAX_VALUE\n var mini: Int = -1\n for (i <- (v.l to v.r)) {\n if (values(i) < minvalue) {\n minvalue = values(i)\n mini = i\n }\n }\n val left = WaitingCall(v.l, mini - 1, minvalue)\n val right = WaitingCall(mini + 1, v.r, minvalue)\n visited.push(Visited(minvalue, left, right, v))\n waitingQueue.enqueue(left, right)\n }\n }\n\n var v:Visited = null\n while(visited.nonEmpty) {\n v = visited.pop()\n for(leftv <- v.left.v; rightv <- v.right.v){\n v.me.v = Some(Seq(v.me.r - v.me.l + 1, leftv + rightv + v.minh - v.me.h ).min)\n }\n }\n v.me.v.getOrElse(-1)\n }\n val input = new Scanner(System.in)\n\n val n = input.nextInt()\n val values = (1 to n).map(_ => input.nextInt())\n println(Process(values.toArray))\n\n}\n", "positive_code": [{"source_code": "import scala.util.control.TailCalls._\n\nobject Fence {\n\n def splitter(as: String) = as.split(\"\\\\s+\").toVector.map(_.toInt)\n \n def splitOn[A](xs: Vector[A], delim: A): Vector[Vector[A]] = {\n val builder = Vector.newBuilder[Vector[A]]\n var i = 0\n var start = 0\n\n while (i < xs.size) {\n if (xs(i) == delim) {\n if (i != start) {\n builder += xs.slice(start, i)\n }\n start = i + 1\n }\n i += 1\n }\n\n if (i != start) builder += xs.slice(start, i)\n builder.result\n }\n\n def solve(xs: Vector[Int]): Int = {\n def go(xs: Vector[Int], previous: Int): TailRec[Int] = {\n val min = xs.min\n\n splitOn(xs, min).foldLeft(done(min - previous)) {\n case (acc, part) => for {\n total <- acc\n cost <- go(part, min)\n } yield total + cost\n }.map(math.min(xs.size, _))\n }\n\n go(xs, 0).result\n }\n\n def main(args: Array[String]) {\n val List(ns, as) = io.Source.stdin.getLines.take(2).toList\n val aVec = splitter(as)\n println(solve(aVec))\n }\n}\n"}], "negative_code": [], "src_uid": "ddab0e510f9aceb2fbf75e26d27df166"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next()\n val icount = data.count(_ == 'I')\n val acount = data.count(_ == 'A')\n val fcount = data.count(_ == 'F')\n var result = if (icount == 1) 1 else if (icount == 0) acount else 0\n println(result)\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) = {\n val n = readInt()\n val s = readLine()\n \n val i = s.count(_ == 'I')\n val a = s.count(_ == 'A')\n val f = s.count(_ == 'F')\n \n if (i == 1) println(\"1\")\n else if (i > 1) println(\"0\")\n else println(a)\n }\n}"}, {"source_code": "\n/**\n * Created by slie742 on 9/09/2015.\n */\n\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\nimport Math.abs\nimport Math.max\nimport Math.min\n\nobject CowsPoker {\n\n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n\n def readLongs() : Array[Long] =\n readLine.split(' ').map(_.toLong)\n\n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n\n def main(args: Array[String]) {\n val n = readInt()\n val s = readLine().groupBy(c => c).mapValues(s => s.length).withDefaultValue(0)\n if (s('I') >= 2) println(0)\n else if (s('I') == 1) println(1)\n else println(s('A'))\n }\n\n}\n\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P284B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n sc.nextLine\n val Cows = sc.nextLine.groupBy(identity).map(x => (x._1, x._2.size))\n\n Cows.get('I') match {\n case None => Cows.getOrElse('A', 0)\n case Some(1) => 1\n case Some(_) => 0\n }\n }\n\n out.println(solve)\n out.close\n}\n\n\n\n\n\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n readInt\n val pl = reader.readLine().filterNot(_ == 'F')\n val in = pl.count(_ == 'I')\n val allin = pl.length - in\n val ans = if(in > 1) 0 else if(in == 1) 1 else allin\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next()\n val icount = data.count(_ == 'I')\n val acount = data.count(_ == 'A')\n val fcount = data.count(_ == 'F')\n var result = if (icount == 1) 1 else acount\n println(result)\n}"}], "src_uid": "5e4defe52832cc0d36e7ea5d9f86f895"} {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n readInt\n val a = readInts\n readInt\n val b = readInts\n val gears = a.flatMap(x => b.filter(_ % x == 0).map(_ / x))\n def ans = gears.count(_ == gears.max)\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a1 = readLine().split(\" \").map(_.toInt)\n val m = readInt()\n val a2 = readLine().split(\" \").map(_.toInt)\n val a = a2.flatMap(b => a1.map(a => (b, a)))\n val pr = a.filter(t => t._1 % t._2 == 0).map(t => t._1 / t._2)\n val max = pr.max\n println(pr.count(_ == max))\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n val f = StdIn.readLine.split(\" \").map(_.toInt)\n val m = StdIn.readInt()\n val b = StdIn.readLine.split(\" \").map(_.toInt)\n val values = for {\n i <- f\n j <- b\n if j % i == 0\n } yield {\n j / i\n }\n val maxRatio = values.max\n println(values.count(_ == maxRatio))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val m = in.next().toInt\n val data2 = in.next().split(' ').map(_.toInt)\n val res = data2.flatMap(i => data.map(j => if (i % j == 0) i / j else -1).filter(_ >= 0))\n val max = res.max\n println(res.count(_ == max))\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P215A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val A = List.fill(N)(sc.nextInt)\n val M = sc.nextInt\n val B = List.fill(M)(sc.nextInt)\n\n val rs = for {\n a <- A\n b <- B\n if b % a == 0\n }\n yield b / a\n\n val rsMax = rs.max\n\n out.println(rs.count(_ == rsMax))\n out.close\n}\n"}, {"source_code": "import io.Source\nimport java.util.StringTokenizer\n\nobject Runner extends App {\n\n val input = Source.fromInputStream(System.in).bufferedReader();\n var token: StringTokenizer = null;\n\n def TOKEN() = {\n while (token == null || !token.hasMoreTokens)\n token = new StringTokenizer(input.readLine());\n token.nextToken()\n }\n\n def INT() = TOKEN().toInt\n\n // Read Input\n val n = INT()\n val front = for (i <- 0 until n) yield INT()\n val m = INT()\n val rear = for (i <- 0 until m) yield INT()\n\n\n println(solve(front, rear))\n\n def solve(front : IndexedSeq[Int], rear: IndexedSeq[Int]) = {\n\n var count = 0\n var best = 0\n for (a <- front) {\n for(b <- rear) {\n if (b%a == 0) {\n val ratio = b / a\n if(ratio == best) {\n count += 1\n } else if (ratio > best) {\n count = 1\n best = ratio\n }\n }\n }\n }\n\n count\n\n }\n\n}\n\n\n"}], "negative_code": [], "src_uid": "102667eaa3aee012fef70f4192464674"} {"source_code": "object B447 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val in = read\n val Array(k) = readInts(1)\n val cn = readInts(26)\n var res = 0\n for(i <- 0 until in.length){\n res += cn(in(i)-'a') * (i+1)\n }\n val cnSorted = cn.sorted\n for(i <- in.length+1 to in.length+k) {\n res += cnSorted(25)*i\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\n/**\n * Created by kshim on 17/07/2014.\n */\nobject FF_B extends App {\n def Process(s:String, k:Integer, w:List[Int]):Integer = {\n val seq = s.map(_.toLower - 'a')\n val orgScore = for(i <- 1 to s.length) yield {\n w(seq(i - 1)) * i\n }\n val maxVal = w.max\n val n = s.length\n orgScore.sum + (( (n+k)*(n+k+1) / 2 - (n * (n + 1) / 2) ) * maxVal)\n }\n val input = new Scanner(System.in)\n val s = input.nextLine().trim\n val k = input.nextInt()\n val w = (1 to 26).map(_ => input.nextInt())\n println(Process(s,k,w.toList))\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 12 Jun 2016\n */\nobject B447 extends App {\n\n val s: String = scala.io.StdIn.readLine()\n val k: Int = scala.io.StdIn.readInt()\n val weights: Array[Long] = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n def solve(s: String, k: Int, weights: Array[Long]) = {\n val currentFuncValue: Long = s.toCharArray.foldLeft((1L, 0L))((pair, c) => {\n val index: Int = c.toInt - 'a'.toInt\n (pair._1 + 1, pair._2 + pair._1 * weights(index))\n })._2\n val max: Long = weights.max\n var answer = currentFuncValue\n if (k > 0) {\n val addition = max * k * (s.length() + s.length() + k + 1) / 2\n answer += addition\n }\n println(answer)\n }\n\n solve(s, k, weights)\n\n}\n"}, {"source_code": "\nimport java.io.File\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 13.07.14.\n */\nobject B extends App {\n\n val home = true\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val s = nextString\n val k = nextInt\n val ws = new Array[Int](26)\n var max: Int = Int.MinValue\n for (i <- 0 until 26) {\n val x = nextInt\n ws(i) = x\n if (x > max) {\n max = x\n }\n }\n var S = 0\n for (i <- 0 until s.length) {\n S += (i + 1) * ws(s(i).toInt - 'a'.toInt)\n }\n S += max * (s.length * k + (k * (k + 1)) / 2)\n out.println(S)\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _447B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val s = next\n val k = next.toInt\n val w = (1 to 26).map(i => next.toInt).toArray\n val ans = (0 until s.length + k).map(i => if (i < s.length) (i + 1) * w(s(i) - 'a') else (i + 1) * w.max).sum\n println(ans)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val k = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt).zipWithIndex.map{case(value, index) => ((index + 'a').toChar, value)}.toMap\n val max = data.maxBy(_._2)\n val count = str.map(data).zipWithIndex.map{case(value, index) => value * (index + 1)}.sum\n println(count + str.length * max._2 * k + (k) * (k + 1) / 2 * max._2)\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val k = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt).zipWithIndex.map{case(value, index) => ((index + 'a').toChar, value)}.toMap\n val max = data.maxBy(_._2)\n val count = str.map(data).zipWithIndex.map{case(value, index) => value * (index + 1)}.sum\n println(count + k * (k + 2) * max._2)\n}"}], "src_uid": "85f90533a9840e944deef9f3b4229cb8"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val r = (n / 7 to 0 by -1).find(i => (n - 7 * i) % 4 == 0)\n if (r.isEmpty)\n println(-1)\n else {\n println(\"4\" * ((n - 7 * r.get) / 4) + \"7\" * r.get)\n }\n}", "positive_code": [{"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n val n = StdIn.readInt()\n\n for(i <- 0 to n / 4) {\n if((n - i * 4) % 7 == 0) {\n println(Array.fill(i)(4).mkString+Array.fill((n - i * 4) / 7)(7).mkString)\n return\n }\n }\n\n println(-1)\n\n\n }\n\n\n}\n"}, {"source_code": "object A109 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n var Array(n) = readInts(1)\n var str = cu.ArrayBuffer.empty[Char]\n var break = false\n while(!break && n > 0) {\n if(n%7 == 0){\n str.appendAll(Array.fill(n/7)('7'))\n n = 0\n } else if(n >= 4){\n str.append('4')\n n -= 4\n } else {\n break = true\n }\n }\n if(break)\n println(\"-1\")\n else\n println(str.sorted.mkString(\"\"))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject LuckySumOfDigitsTest{\n\n def main(args: Array[String]):Unit ={\n\n val luckyNumber = StdIn.readInt()\n\n // proccess\n var y= luckyNumber / 7\n var b= luckyNumber % 7\n var x= b / 4\n\n while ( (b % 4)!= 0 && y > 0 ){\n b = b + 7\n y = y - 1\n x = b / 4\n }\n if ( ( (x+y) >0) && ( ( (7 * y) + (4 * x)) == luckyNumber) ){\n var i=0\n while( i < (x+y) ){\n if( i < x) print(4)\n else print(7)\n i = i + 1\n }\n } else print(-1)\n }\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val r = (0 to n / 7).find(i => (n - 7 * i) % 4 == 0)\n if (r.isEmpty)\n println(-1)\n else {\n println(\"4\" * ((n - 7 * r.get) / 4) + \"7\" * r.get)\n }\n}"}, {"source_code": "object A109 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n var Array(n) = readInts(1)\n var str = cu.ArrayBuffer.empty[Char]\n var break = false\n while(!break && n > 0) {\n if(n%7 == 0){\n str.appendAll(Array.fill(n/7)('7'))\n n = 0\n } else if(n%4 == 0){\n str.appendAll(Array.fill(n/4)('4'))\n n = 0\n } else if (n > 7){\n n -= 7\n str.append('7')\n } else {\n break = true\n }\n }\n if(break)\n println(\"-1\")\n else\n println(str.sorted.mkString(\"\"))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "2584fa8c1adb1aa8cd5c28a8610ff72d"} {"source_code": "object _1316A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val n, m = io.read[Int]\n val scores = io.read[List, Int](n)\n val ans = m min scores.sum\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def nonNegative = when(x >= 0)(x)\n def ceilDiv(y: Int) = (x + y - 1)/y\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n", "positive_code": [{"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n (1 to t).foreach{ _ =>\n val (n,m) = (in.nextInt(),in.nextInt())\n val a = (1 to n).map{_ => in.nextInt()}.toArray\n if(n == 1){\n out.println(a(0))\n }else{\n var res = a(0)\n a.tail.foreach{ ai =>\n if(ai>=0 && resm){\n res = m\n }else{\n res += ai\n }\n }\n }\n out.println(res)\n }\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}, {"source_code": "\nobject Problem1 extends App {\n def getMaxScore(n : Int, max : Int, sumScore : Int): Int = {\n Math.min(max, sumScore)\n }\n var n = Console.readInt()\n while( n > 0){\n n = n - 1\n val arr = Console.readLine().trim.split(\" \").map( x => x.toInt)\n val num = arr(0)\n val max = arr(1)\n val sum = Console.readLine().trim.split(\" \").foldLeft(0)( (x, y) => x + y.toInt )\n println(getMaxScore(num, max , sum ))\n\n }\n\n}"}], "negative_code": [], "src_uid": "7c2a61de728e6767b25e58c74497bbae"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M = ni()\n val A = na(N)\n var pre = 0\n rep(N) { i =>\n if (i > 0) out.print(\" \")\n val a = A(i)\n val m = a % M\n val q = a / M\n val ans = q + (m + pre) / M\n pre = (m + pre) % M\n out.print(ans)\n }\n\n out.println()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject EDU48A extends App {\n val Array(n, m) = StdIn.readLine.split(' ').map(_.toInt)\n val as = StdIn.readLine.split(' ').map(_.toInt).toArray\n\n var remainder = 0\n var first = true\n for (i <- 0 until n) {\n val currentPage = remainder + as(i)\n\n if (!first)\n print(\" \")\n else\n first = false\n\n print(currentPage/m)\n remainder = currentPage%m\n }\n}"}, {"source_code": "object test{\n def main(args: Array[String]){\n val t = readLine().split(\" \")\n val n = Integer.parseInt(t(0))\n val m = Integer.parseInt(t(1))\n val a = readLine().split(\" \")\n var sum = 0\n var page = 0\n for(i <- 0 to n-1){\n sum += a(i).toInt\n if(i != 0 )\n print(\" \")\n print(sum/m)\n sum %= m\n }\n }\n}\n"}, {"source_code": "object Main {\n import java.io._\nimport java.util.Scanner\n\nimport collection.mutable.HashMap\nimport scala.collection.{SortedSet, mutable}\nimport scala.util.Random\n protected val EPS = 1e-11\n\n private def default = (\n new StreamTokenizer(new InputStreamReader(System.in)),\n new Scanner(System.in),\n new PrintWriter(System.out)\n )\n\n val (in, ins, out) = {\n try {\n if (sys.props.contains(\"xDx\")) {\n (\n new StreamTokenizer(new FileReader(\"input.txt\")),\n new Scanner(new FileReader(\"input.txt\")),\n new PrintWriter(new FileWriter(\"output.txt\"))\n )\n } else {\n default\n }\n } catch {\n case _: Throwable => default\n }\n }\n\n private def nextInt = {\n in.nextToken\n in.nval.toInt\n }\n\n private def nextLong = {\n in.nextToken\n in.nval.toLong\n }\n\n\n private def nextDouble = {\n in.nextToken\n in.nval\n }\n\n\n private def nextString = {\n in.nextToken\n in.sval\n }\n\n private def nextChar = {\n in.nextToken\n in.ttype.toChar\n }\n\n def main(args: Array[String]): Unit = {\n try {\n new Run().run()\n } catch {\n case e: Throwable =>\n throw new RuntimeException(e)\n } finally out.close()\n }\n\n class Run {\n import collection.breakOut\n def run(): Unit = {\n val n = nextInt\n val m = nextInt\n var cur = 0\n for(i <- 1 to n) {\n val a = nextInt\n cur += a\n print(s\"${cur/m} \")\n cur %= m\n }\n }\n\n }\n\n}\n\n\n"}], "negative_code": [], "src_uid": "a2085c2d21b2dbe4cc27a15fa4a1ec4f"} {"source_code": "object B499 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def readWords(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken)\n }\n\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val dic = Array.fill(m){\n val str = tokenizeLine\n val res = (str.nextToken, str.nextToken)\n (res._1, if(res._2.length < res._1.length) res._2 else res._1)\n }.toMap\n val lec = readWords(n)\n println(lec.map(dic).mkString(\" \"))\n }\n}", "positive_code": [{"source_code": "object lecture extends App {\n val Array(n, m) = readLine split ' ' map (_.toInt)\n\n val words = List.fill(m)(readLine split ' ').map(l => l(0) -> l(1)).toMap\n println(readLine split ' ' map (w => if(w.length <= words(w).length) w else words(w)) mkString \" \")\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _499B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n\n val n = next.toInt\n val m = next.toInt\n val dict = (1 to m).map(i => {val a = next; val b = next; (a, if (a.length <= b.length) a else b)}).toMap\n\n val input = (1 to n).map(i => next)\n val ans = input.map(str => dict(str))\n println(ans.mkString(\" \"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val r = Range(0, m).map(_ => in.next().split(\" \")).map {\n case(a) if a.head.length > a.last.length => a.head -> a.last\n case(a) => a.last -> a.head\n }.toMap\n println(in.next().split(\" \").map(t => r.getOrElse(t, t)).mkString(\" \"))\n}"}, {"source_code": "import scala.collection.mutable\n\nobject P499B {\n\t@inline def readTokens() = scala.io.StdIn.readLine.split(\" \")\n\t@inline def readInts() = readTokens.map(_.toInt)\n\n\tdef main(args: Array[String]) {\n\t\tval Array(n, m) = readInts()\n\t\tval words = mutable.Map[String, String]()\n\t\tfor (i <- 1 to m) {\n\t\t\tval Array(a, b) = readTokens()\n\t\t\twords += (a -> (if (a.length <= b.length) a else b))\n\t\t}\n\t\tval dict = words.toMap\n\t\tprintln(readTokens().map(dict(_)).mkString(\" \"))\n\t}\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject B extends App {\n def readIntPair() = {\n val a = StdIn.readLine() split \" \" map { _.toInt }\n (a(0), a(1))\n }\n\n def readPair() = {\n val a = StdIn.readLine() split \" \"\n (a(0), a(1))\n }\n\n val (n, m) = readIntPair()\n var dict = Map[String, String]()\n for (i <- 1 to m) {\n val (f, s) = readPair()\n\n val used = if (f.size <= s.size) f else s\n dict = dict + (f -> used)\n }\n\n val text = StdIn.readLine() split \" \"\n Console.println(text map dict mkString \" \")\n}\n"}, {"source_code": " object Lecture extends App {\n \tval lines = io.Source.stdin.getLines.toList\n \tval (nWordsLecture, nWordsLanguage) = {\n \t\tval tokens = lines.head.split(\" \")\n \t\t(tokens(0).toInt, tokens(1).toInt)\n \t}\n \t\n \tvar map = Map[String, String]()\n \t\n \tfor (line <- lines.tail.init) {\n \t\tval tokens = line.split(\" \")\n \t\tmap = map + (tokens(0) -> tokens(1))\n \t}\n \t\n \tval lecture = (for (word <- lines.last.split(\" \").toList) yield if (word.length <= map(word).length) word else map(word)).mkString(\" \")\n \t\n \tprintln(lecture)\n \t\n }"}, {"source_code": "object Main extends App {\n\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n val lang: Map[String,String] = (1 to m).map({ _ =>\n val Array(from, to) = readLine.split(\" \", 2)\n (from, to)\n }).toMap\n println(readLine.split(\" \").map({s =>\n val s1 = lang.getOrElse(s, \"\")\n if(s1.size < s.size) s1 else s\n }).mkString(\" \"))\n\n}"}, {"source_code": "import java.io._\nimport scala.collection.mutable\n\nobject Problem499 extends App {\n val problem = new Problem499(\n new InputStreamReader(System.in),\n new OutputStreamWriter(System.out)\n )\n\n problem.run()\n}\n\nclass Problem499(input: Reader, output: Writer) {\n private val tokenizer = new StreamTokenizer(new BufferedReader(input))\n\n def run(): Unit = {\n tokenizer.eolIsSignificant(true)\n\n var n = readInt()\n var m = readInt()\n tokenizer.nextToken()\n\n val dictionary = new mutable.HashMap[String, String]()\n while (m > 0) {\n dictionary += addTranslation()\n\n m -= 1\n }\n\n while (n > 0) {\n translate(dictionary)\n\n n -= 1\n }\n\n output.flush()\n }\n\n private def translate(dictionary: mutable.Map[String, String]): Unit = {\n var isFirst = true\n\n while (tokenizer.nextToken() == StreamTokenizer.TT_WORD) {\n if (isFirst) {\n isFirst = false\n } else {\n output.write(' ')\n }\n\n val translation = dictionary.get(tokenizer.sval)\n output.write(translation getOrElse \" \")\n }\n }\n\n private def addTranslation(): (String, String) = {\n if (tokenizer.nextToken() != StreamTokenizer.TT_WORD) {\n throw new RuntimeException(\"Word expected\")\n }\n\n val original = tokenizer.sval\n var translation = original\n\n while (tokenizer.nextToken() == StreamTokenizer.TT_WORD) {\n if (translation.length() > tokenizer.sval.length()) {\n translation = tokenizer.sval\n }\n }\n\n original -> translation\n }\n\n private def readInt(): Int = {\n if (tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {\n throw new RuntimeException(\"Integer expected\")\n }\n\n tokenizer.nval.toInt\n }\n}"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _499B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n\n val n = next.toInt\n val m = next.toInt\n val dict = (1 to m).map(i => {val a = next; val b = next; (a, if (a.length < b.length) a else b)}).toMap\n\n val input = (1 to n).map(i => next)\n val ans = input.map(str => dict(str))\n println(ans.mkString(\" \"))\n}\n"}, {"source_code": " object Lecture extends App {\n \tval lines = io.Source.stdin.getLines.toList\n \tval (nWordsLecture, nWordsLanguage) = {\n \t\tval tokens = lines.head.split(\" \")\n \t\t(tokens(0).toInt, tokens(1).toInt)\n \t}\n \t\n \tvar map = Map[String, String]()\n \t\n \tfor (line <- lines.tail.init) {\n \t\tval tokens = line.split(\" \")\n \t\tmap = map + (tokens(0) -> tokens(1))\n \t}\n \t\n \tval lecture = (for (word <- lines.last.split(\" \").toList) yield if (word.compareTo(map(word)) <= 0) word else map(word)).mkString(\" \")\n \t\n \tprintln(lecture)\n \t\n }"}, {"source_code": "object Main extends App {\n\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n val lang: Map[String,String] = (1 to m).map({ _ =>\n val Array(from, to) = readLine.split(\" \", 2)\n (from, to)\n }).toMap\n println(readLine.split(\" \").map({s =>\n val s1 = lang.getOrElse(s, \"\")\n if(s1.size > s.size) s else s1\n }).mkString(\" \"))\n\n}"}], "src_uid": "edd556d60de89587f1b8daa893538530"} {"source_code": "import java.io._\nimport java.util._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n def solve: Int = {\n val n = nextInt\n val x1 = nextLong\n val x2 = nextLong\n val arr = new Array[(Long, Long)](n)\n for (i <- 0 until n) {\n arr(i) = (nextLong, nextLong)\n }\n val left = new Array[(Long, Long)](n)\n val right = new MultiTreeSet[Long]\n for (i <- 0 until n) {\n left(i) = (arr(i)._1 * x1 + arr(i)._2, arr(i)._1 * x2 + arr(i)._2)\n right.add(arr(i)._1 * x2 + arr(i)._2)\n }\n val sorted = left.sorted\n var i = 0\n while (i < n) {\n var j = i\n var y1 = sorted(i)._2\n while (j < n && sorted(j)._1 == sorted(i)._1) {\n y1 = Math.max(y1, sorted(j)._2)\n right.remove(sorted(j)._2)\n j += 1\n }\n if (right.map.isEmpty) {\n out.print(\"NO\")\n return 0\n }\n val min = right.map.firstKey()\n val max = right.map.lastKey()\n if (y1 > min) {\n out.print(\"YES\")\n return 0\n }\n i = j\n }\n out.print(\"NO\")\n return 0\n }\n\n\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val Array(x1, x2) = in.next().split(' ').map(_.toLong)\n val data = (1 to n).map { _ =>\n val Array(a, b) = in.next().split(' ').map(_.toLong)\n (a * x1 + b, a * x2 + b)\n }.sorted\n if (data.map(_._2).sliding(2).exists(t => t.last < t.head)) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n\n}\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val Array(x1, x2) = readLongs(2)\n\n val _by2 = Array.ofDim[(Long, Long)](n)\n val by1 = new mutable.TreeSet[(Long, Long)]()\n //val by2 = new mutable.TreeSet[(Long, Long)]()(Ordering.by { case (a, b) => (b, a) })\n \n for (i <- 0 until n) {\n val Array(k, b) = readInts(2)\n val l = (k * x1 + b, k * x2 + b)\n _by2(i) = l\n by1 += l\n }\n \n val by2 = _by2.sortBy(l => (l._2, l._1))\n\n for (l <- by2) {\n by1 -= l\n if (by1.nonEmpty && l._1 > by1.head._1) {\n println(\"YES\")\n System.exit(0)\n }\n }\n\n println(\"NO\")\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._\nimport scala.math.Ordering.Implicits._\n\nobject _593B extends CodeForcesApp {\n import CodeForcesApp._\n override type Result = Boolean\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val n = nextInt()\n val (x1, x2) = (nextLong(), nextLong())\n val lines = Seq.fill(n)((nextLong(), nextLong()))\n \n def eval(x: Double)(line: (Long, Long)): Double = {\n val (k, b) = line\n k*x + b\n }\n val a = lines.sortBy(eval(x1 + 1e-9))\n val b = lines.sortBy(eval(x2 - 1e-9))\n a != b\n }\n\n override def format(result: Result) = if (result) \"YES\" else \"NO\"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._\nimport scala.math.Ordering.Implicits._\n\nobject _593B extends CodeForcesApp {\n override type Result = Boolean\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val n = nextInt()\n val (x1, x2) = (nextLong(), nextLong())\n val lines = Seq.fill(n)((nextLong(), nextLong()))\n def eval(x: Double)(line: (Long, Long)): Double = {\n val (k, b) = line\n k*x + b\n }\n val a = lines.sortBy(eval(x1 + 1e-9))\n val b = lines.sortBy(eval(x2 - 1e-9))\n debug(a, b)\n a != b\n }\n\n override def format(result: Result) = if (result) \"YES\" else \"NO\"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}, {"source_code": "//package round329.b\n\nimport java.util.Scanner\n\nobject Main extends App {\n\n case class Line(k: Int, b: Int) {\n def compute(x: Int): Long = k.toLong * x.toLong + b.toLong\n }\n\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n val (x1, x2) = (sc.nextInt, sc.nextInt)\n\n val lines = (0 until n).map(_ => Line(sc.nextInt, sc.nextInt)).toArray\n\n val yX1 = lines.view.map { line => line.compute(x1) }.zipWithIndex.sortBy(-_._1).toArray\n val yX2 = lines.view.map { line => line.compute(x2) }.zipWithIndex.sortBy(-_._1).toArray\n\n// println(yX1.toList)\n// println(yX2.toList)\n\n var yX2_idx = 0\n\n (0 until n).foreach { i =>\n\n val (yX1L1, idx1) = yX1(i)\n val line1 = lines(idx1)\n val yX2L1 = line1.compute(x2)\n\n while(yX2_idx < n && yX2(yX2_idx)._1 > yX2L1) {\n val (yX2L2, idx2) = yX2(yX2_idx)\n val line2 = lines(idx2)\n val yX1L2 = line2.compute(x1)\n if(yX1L1 > yX1L2) {\n println(\"YES\")\n System.exit(0)\n }\n yX2_idx += 1\n }\n }\n\n println(\"NO\")\n}\n\n"}], "negative_code": [{"source_code": "//package round329.b\n\nimport java.util.Scanner\n\nobject Main extends App {\n\n case class Line(k: Int, b: Int) {\n def compute(x: Int): Long = k.toLong * x.toLong + b.toLong\n }\n\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n val (x1, x2) = (sc.nextInt, sc.nextInt)\n\n val lines = (0 until n).map(_ => Line(sc.nextInt, sc.nextInt)).toArray\n\n val yX1 = lines.map { line => line.compute(x1) }.zipWithIndex.sortBy(-_._1)\n val yX2 = lines.map { line => line.compute(x2) }.zipWithIndex.sortBy(-_._1)\n\n var yX2_idx = 0\n\n (0 until n).foreach { i =>\n\n val (yX1L1, idx1) = yX1(i)\n val line1 = lines(idx1)\n val yX2L1 = line1.compute(x2)\n\n while(yX2_idx < n && yX2(yX2_idx)._1 < yX2L1) {\n val (yX2L2, idx2) = yX2(yX2_idx)\n val line2 = lines(idx2)\n val yX1L2 = line2.compute(x1)\n if(yX1L1 < yX1L2) {\n println(\"YES\")\n System.exit(0)\n }\n yX2_idx += 1\n }\n }\n\n println(\"NO\")\n}\n\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n case class Line(y1: Long, y2: Long)\n \n val Array(n) = readInts(1)\n val Array(x1, x2) = readInts(2)\n\n val _by1 = Array.ofDim[Line](n)\n val by2 = new mutable.TreeSet[Line]()(Ordering.by(l => (l.y2, l.y1)))\n \n for (i <- 0 until n) {\n val Array(k, b) = readInts(2)\n val l = Line(k * x1 + b, k * x2 + b)\n _by1(i) = l\n by2 += l\n }\n \n val by1 = _by1.sortBy(l => (l.y1, l.y2))\n\n for (l <- by1) {\n by2 -= l\n if (by2.nonEmpty && l.y2 > by2.head.y2) {\n println(\"YES\")\n System.exit(0)\n }\n }\n\n println(\"NO\")\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n case class Line(y1: Long, y2: Long)\n \n val Array(n) = readInts(1)\n val Array(x1, x2) = readLongs(2)\n\n val _by2 = Array.ofDim[(Long, Long)](n)\n val by1 = new mutable.TreeSet[(Long, Long)]()\n \n for (i <- 0 until n) {\n val Array(k, b) = readInts(2)\n val l = (k * x1 + b, k * x2 + b)\n _by2(i) = l\n by1 += l\n }\n \n val by2 = _by2.sortBy(l => l._2)\n\n for (l <- by2) {\n by1 -= l\n if (by1.nonEmpty && l._1 > by1.head._1) {\n println(\"YES\")\n System.exit(0)\n }\n }\n\n println(\"NO\")\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._\nimport scala.math.Ordering.Implicits._\n\nobject _593B extends CodeForcesApp {\n import CodeForcesApp._\n override type Result = Boolean\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val n = nextInt()\n val (x1, x2) = (nextLong(), nextLong())\n val lines = Seq.fill(n)((nextLong(), nextLong()))\n def eval(x: Double)(line: (Long, Long)): Double = {\n val (k, b) = line\n k*x + b\n }\n val a = lines.sortBy(eval(x1 + 1e-3))\n val b = lines.sortBy(eval(x2 - 1e-3))\n //debug(a, b, (a map (eval(x1 + 1e-3))).toList, (b map (eval(x2 - 1e-3))).toList)\n a != b\n }\n\n override def format(result: Result) = if (result) \"YES\" else \"NO\"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}], "src_uid": "8b61213e2ce76b938aa68ffd1e4c1429"} {"source_code": "import scala.io.StdIn\n\nobject LettersRearranging extends App {\n\n val t = StdIn.readLine().toInt\n for {\n _ <- 1 to t\n } println(findSol(StdIn.readLine()))\n\n def findSol(s: String): String = {\n if (s.length == 1) return \"-1\"\n\n val zip = s.zipWithIndex\n\n val dislen = zip.map(_._1).distinct.length\n\n if (dislen == 1) return \"-1\"\n\n val first = zip.head\n\n val x = zip.find(x => x._1 != first._1).get\n val last = zip.last\n\n val newzip = zip.updated(zip.length - 1, x).updated(x._2, last)\n\n newzip.map(_._1).mkString\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject T1093B {\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n\n for (_<-1 to n){\n val s = StdIn.readLine()\n val st = s.toCharArray.toSet\n if (st.size==1){\n println(-1)\n }else{\n println(s.toCharArray.sorted.mkString)\n }\n }\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val S = ns()\n val grouped = S.groupBy(identity)\n if (grouped.size == 1) out.println(-1)\n else {\n out.println(grouped.values.mkString)\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object b1093 {\n def main(args: Array[String]): Unit = {\n scala.io.Source.stdin.getLines().drop(1).map { i: String => val j = i.sorted; if (j.head == j.last) \"-1\" else j } foreach println\n }\n}\n"}, {"source_code": "object EDU_56_B {\n def solve(t: Int, ss: Seq[String]): Seq[String] = ss map { s =>\n val letters = s.toSet\n if(letters.size == 1) \"-1\"\n else s.sorted\n }\n\n // Specify Input and Output formats here:\n def formatIn(i: Input) = (i.int, i.getLines)\n def formatOut(out: Seq[String]): String = out.mkString(\"\\n\")\n\n// ~~~ Boilerplate & utility methods that don't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n def main(args: Array[String]) = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n\n import java.util.Scanner\n class Input(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n // Remember to call nextLine to advance past the newline character (if required) before collecting the line:\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty else sc.nextLine +: getLines\n def solveVal = (solve _).tupled(formatIn(this))\n def solveStr = formatOut(solveVal)\n }\n\n def ceil(a: Int, b: Int) = (a - 1) / b + 1\n def ceil(a: Long, b: Long) = (a - 1) / b + 1\n val modulo = 1000000007\n\n import language.implicitConversions\n implicit def stringToInput(s: String): Input = new Input(s)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { def tupled: T => R = x => f(x) }\n}"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(t) = readInts(1)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (_ <- 1 to t) {\n val s = readLine\n if (s.forall(_ == s.head)) println(-1)\n else println(s.sorted)\n }\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "b9f0c38c6066bdafa2e4c6daf7f46816"} {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.io.StdIn\nimport scala.util.control.Breaks\n\nobject Main {\n def main(args: Array[String]) {\n val Array(n, x1, y1, x2, y2) = StdIn.readLine().split(\" \").map(_.toInt)\n val a = Array.fill(n)({\n val Array(x, y) = StdIn.readLine().split(\" \").map(_.toLong)\n (x, y)\n })\n val a1 = (for (((x, y), i) <- a.zipWithIndex) yield ((x - x1) * (x - x1) + (y - y1) * (y - y1), i)).sorted\n val a2 = (for (((x, y), i) <- a.zipWithIndex) yield ((x - x2) * (x - x2) + (y - y2) * (y - y2), i)).sorted\n val s1 = mutable.HashSet[Int]()\n var ans = Long.MaxValue\n val s2 = mutable.HashSet[Int]()\n for ((r2, i2) <- a2) {\n s2.add(i2)\n if (s2.size == n) ans = math.min(ans, r2)\n }\n for ((r1, i1) <- a1) {\n s1.add(i1)\n val s2 = s1.clone()\n for ((r2, i2) <- a2) {\n s2.add(i2)\n if (s2.size == n) ans = math.min(ans, r1 + r2)\n }\n if (s1.size == n) ans = math.min(ans, r1)\n }\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.io.StdIn\nimport scala.util.control.Breaks\n\nobject Main {\n def main(args: Array[String]) {\n val Array(__n, x1, y1, x2, y2) = StdIn.readLine().split(\" \").map(_.toLong)\n val _n = __n.toInt\n val a = Array.fill(_n)({\n val Array(x, y) = StdIn.readLine().split(\" \").map(_.toLong)\n (x, y)\n }) ++ Array((x1, y1), (x2, y2))\n val n = _n + 2\n val a1 = (for (((x, y), i) <- a.zipWithIndex) yield ((x - x1) * (x - x1) + (y - y1) * (y - y1), i)).sorted.toList\n val a2 = (for (((x, y), i) <- a.zipWithIndex) yield ((x - x2) * (x - x2) + (y - y2) * (y - y2), i)).sorted.toList\n\n def f(xs: List[(Long, Int)], s: Set[Int], acc: Long): Long = {\n def g(xs: List[(Long, Int)], s: Set[Int]): Long = {\n xs match {\n case (r, i)::ys => {\n val t = s + i\n if (t.size == n) r else g(ys, t)\n }\n }\n }\n xs match {\n case (r, i)::ys => {\n val t = s + i\n if (t.size == n) math.min(r, acc) else f(ys, t, math.min(acc, r + g(a2, t)))\n }\n }\n }\n println(f(a1, Set[Int](), Long.MaxValue))\n }\n}\n"}, {"source_code": "import math.pow\nimport math.max\n\nobject C340{\n def dist(x1: Long, x2: Long, y1:Long, y2: Long): Double ={\n pow(x1 - x2, 2) + pow(y1 - y2, 2)\n }\n def main(args: Array[String]){\n\n val Array(n, x1, y1, x2, y2)=scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val flowers = (1 to n).map(x => scala.io.StdIn.readLine.split(\" \").map(_.toInt)).toList\n val dists = (0.0, 0.0) :: flowers.map(x => (dist(x(0), x1, x(1), y1), dist(x(0), x2, x(1), y2))).sortBy(_._1)\n var temp = 0.0\n val maxy = dists.reverse.map(b => {\n val tt = temp + b._1\n temp = max(b._2, temp)\n tt\n })\n print(maxy.min.toLong)\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, x1, y1, x2, y2) = in.next().split(' ').map(_.toLong)\n val data = (1l to n).map { _ =>\n val Array(x3, y3) = in.next().split(' ').map(_.toLong)\n ((x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3), (x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3))\n }\n val first = 0l :: data.map(_._1).toList\n println(first.foldLeft(Long.MaxValue) {\n case (acc, r1) =>\n val filtered = data.filter(_._1 > r1)\n if (filtered.isEmpty)\n Math.min(acc, r1)\n else\n Math.min(acc, r1 + filtered.maxBy(_._2)._2)\n })\n\n}"}], "negative_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.io.StdIn\nimport scala.util.control.Breaks\n\nobject Main {\n def main(args: Array[String]) {\n val Array(n, x1, y1, x2, y2) = StdIn.readLine().split(\" \").map(_.toInt)\n val a = Array.fill(n)({\n val Array(x, y) = StdIn.readLine().split(\" \").map(_.toLong)\n (x, y)\n })\n val a1 = (for (((x, y), i) <- a.zipWithIndex) yield ((x - x1) * (x - x1) + (y - y1) * (y - y1), i)).sorted\n val a2 = (for (((x, y), i) <- a.zipWithIndex) yield ((x - x2) * (x - x2) + (y - y2) * (y - y2), i)).sorted\n val s1 = mutable.HashSet[Int]()\n var ans = Long.MaxValue\n val s2 = mutable.HashSet[Int]()\n for ((r2, i2) <- a2) {\n s2.add(i2)\n if (s2.size == n) ans = math.min(ans, r2)\n }\n for ((r1, i1) <- a1) {\n s1.add(i1)\n val s2 = s1.clone()\n for ((r2, i2) <- a2) {\n s2.add(i2)\n if (s2.size == n) ans = math.min(ans, r1 + r2)\n }\n }\n println(ans)\n }\n}\n"}, {"source_code": "import math.pow\nimport math.max\n\nobject C340{\n def dist(x1: Int, x2: Int, y1:Int, y2: Int): Double ={\n pow(x1 - x2, 2) + pow(y1 - y2, 2)\n }\n def main(args: Array[String]){\n\n val Array(n, x1, y1, x2, y2)=scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val flowers = (1 to n).map(x => scala.io.StdIn.readLine.split(\" \").map(_.toInt)).toList\n val dists = flowers.map(x => (dist(x(0), x1, x(1), y1), dist(x(0), x2, x(1), y2))).sortBy(_._1)\n var temp = 0.0\n val maxy = dists.reverse.map(b => {\n val tt = temp + b._1\n temp = max(b._2, temp)\n tt\n })\n print(maxy.min.toInt)\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, x1, y1, x2, y2) = in.next().split(' ').map(_.toLong)\n val data = (1l to n).map { _ =>\n val Array(x3, y3) = in.next().split(' ').map(_.toLong)\n ((x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3), (x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3))\n }\n val first = data.map(_._1)\n println(first.foldLeft(Long.MaxValue) {\n case (acc, r1) =>\n val filtered = data.filter(_._1 > r1)\n if (filtered.isEmpty)\n Math.min(acc, r1)\n else\n Math.min(acc, r1 + filtered.maxBy(_._2)._2)\n })\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, x1, y1, x2, y2) = in.next().split(' ').map(_.toInt)\n val data = (1 to n).map { _ =>\n val Array(x3, y3) = in.next().split(' ').map(_.toInt)\n ((x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3), (x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3))\n }\n val first = data.map(_._1)\n println(first.foldLeft(Int.MaxValue) {\n case (acc, r1) =>\n val filtered = data.filter(_._1 > r1)\n if (filtered.isEmpty)\n Math.min(acc, r1)\n else\n Math.min(acc, r1 + filtered.maxBy(_._2)._2)\n })\n\n}"}], "src_uid": "5db9c5673a04256c52f180dbfca2a52f"} {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n private val MOD = (1e9 + 7).toInt\n\n def binomialCoefficient(n: Int, k: Int): Long = {\n var c = 1L\n for (i <- 0 until k) {\n val x = (c * (n - i)) / (i + 1)\n }\n return c\n }\n\n def solve: Int = {\n val k = nextInt\n val c = new Array[Int](k)\n for (i <- 0 until k) {\n c(i) = nextInt\n }\n val coeff = new Array[Array[Long]](1010)\n for (i <- 0 until coeff.length)\n coeff(i) = new Array[Long](1010)\n coeff(0)(0) = 1\n for (i <- 1 until 1010) {\n coeff(i)(0) = 1\n for (j <- 1 to i) {\n coeff(i)(j) = (coeff(i - 1)(j) + coeff(i - 1)(j - 1)) % MOD\n }\n }\n val ans = new Array[Long](k)\n ans(0) = 1\n var sum = c(0)\n for (i <- 1 until k) {\n ans(i) = ((ans(i - 1) % MOD) * coeff(sum + c(i) - 1)(sum) % MOD) % MOD\n sum += c(i)\n }\n out.println(ans(k - 1))\n return 0\n }\n}\n", "positive_code": [{"source_code": "import java.io.InputStream\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport java.io.PrintWriter\nimport java.io.FileInputStream\nimport java.io.PrintStream\nimport java.io.FileOutputStream\n\nobject CF553A {\n\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n return next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n val MOD = 1000000007L\n \n def main(args: Array[String]): Unit = {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n var in = new InputReader(System.in)\n var out = System.out\n if ( !isOnlineJudge ) {\n in = new InputReader(new FileInputStream(\"input.txt\"))\n out = new PrintStream(new FileOutputStream(\"output.txt\"))\n }\n solve(in,out)\n }\n \n \n def solve(in: InputReader, out: PrintStream): Unit = {\n val n = in.nextInt()\n val a = List.fill(n)(in.nextLong()).reverse\n val dim = sum(a).toInt\n val comb = Array.ofDim[Long](dim, dim) \n for(i <- 0 until dim) {\n comb(0)(i) = 1\n comb(i)(0) = 1 \n }\n comb(0)(0) = 0\n for(num <- 1 until dim)\n for(k <- 1 to num) comb(k)(num) = (comb(k-1)(num-1) + comb(k)(num-1)) % MOD\n out.println(count(a,comb))\n }\n\n// def count(a: List[Long]): Long = {\n// }\n\n def sum(arg: List[Long]): Long = {\n return arg.foldLeft(0L)((s,x) => s + x)\n }\n\n def count(a: List[Long], comb: Array[Array[Long]]): Long = {\n if ( a.length == 1) return 1\n val k = a.head - 1\n val n = sum(a) - 1\n val combi = comb(k.toInt)(n.toInt)\n //printf(\"k = %d, n = %d, combi(k,n) = %d\\n\", k,n, comb(k.toInt)(n.toInt))\n return (count(a.tail, comb) * combi ) % MOD \n }\n\n\n}"}, {"source_code": "import java.io.InputStream\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport java.io.PrintWriter\nimport java.io.FileInputStream\nimport java.io.PrintStream\nimport java.io.FileOutputStream\n\nobject CF553A {\n\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n return next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n val MOD = 1000000007L\n \n def main(args: Array[String]): Unit = {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n var in = new InputReader(System.in)\n var out = System.out\n if ( !isOnlineJudge ) {\n in = new InputReader(new FileInputStream(\"input.txt\"))\n out = new PrintStream(new FileOutputStream(\"output.txt\"))\n }\n solve(in,out)\n }\n \n \n def solve(in: InputReader, out: PrintStream): Unit = {\n val a = List.fill(in.nextInt())(in.nextInt()).reverse\n val dim = sum(a)\n val comb = Array.ofDim[Long](dim, dim) \n for(i <- 0 until dim) {\n comb(0)(i) = 1\n comb(i)(0) = 0 \n }\n comb(0)(0) = 1\n for(num <- 1 until dim)\n for(k <- 1 to num) comb(k)(num) = (comb(k-1)(num-1) + comb(k)(num-1)) % MOD\n out.println(count(a,comb))\n }\n\n def sum(arg: List[Int]): Int = {\n return arg.foldLeft(0)((s,x) => s + x)\n }\n\n def count(a: List[Int], comb: Array[Array[Long]]): Long = {\n if ( a.length == 1) return 1\n return (count(a.tail, comb) * comb(a.head- 1)(sum(a)-1) ) % MOD \n }\n\n\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _553A extends App {\n var token = new StringTokenizer(\"\")\n\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n\n val mod = 1000000007L\n var choose = Array.fill(1111, 1111)(0L)\n for (i <- 0 until choose.length) {\n choose(i)(0) = 1\n choose(i)(i) = 1\n for (j <- 1 until i)\n choose(i)(j) = (choose(i - 1)(j) + choose(i - 1)(j - 1)) % mod\n }\n\n val k = next.toInt\n val a = (1 to k).map(i => next.toInt)\n var sum = a.sum\n var ans = 1L\n var i = k - 1\n while(i >= 0) {\n ans = (ans * choose(sum - 1)(a(i) - 1)) % mod\n sum -= a(i)\n i -= 1\n }\n\n println(ans)\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val mod = 1000000007\n val maxN = 1010\n val in = Source.stdin.getLines()\n val comb = Array.ofDim[Long](maxN, maxN)\n comb(0)(0) = 1\n (1 until maxN).foreach { i =>\n comb(i)(0) = 1\n (1 to i).foreach { j =>\n comb(i)(j) = (comb(i - 1)(j) + comb(i - 1)(j - 1)) % mod\n }\n }\n val k = in.next().toInt\n val color = (1 to k).map(_ => in.next().toInt)\n val r = (0 until k).foldLeft(1l, 0) {\n case ((res, total), i) =>\n val nRes = res * comb(total + color(i) - 1)(color(i)- 1) % mod\n (nRes, total + color(i))\n }\n println(r._1)\n}\n"}, {"source_code": "object A{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val m=1000000007L\n val mI=m.toInt\n val C=Array.ofDim[Int](1001,1001)\n for(i<-0 to 1000){\n C(i)(0)=1\n C(i)(i)=1\n for(j<-1 until i){\n C(i)(j)=(C(i-1)(j)+C(i-1)(j-1))%mI\n }\n }\n\n val k=nextInt\n\n var sum=0\n var ans=1L\n for(i<-0 until k){\n val c=nextInt\n sum+=c\n ans=(ans*C(sum-1)(c-1))%m\n }\n out.println(ans)\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object _554C extends CodeForcesApp {\n import CodeForcesApp._, scala.annotation.tailrec, scala.collection.mutable\n\n override type Input = List[Int]\n override type Output = BigInt\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n List.fill(nextInt)(nextInt)\n }\n\n override def solve(input: Input) = {\n def f(balls: Int, colors: List[Int]): BigInt = colors match {\n case Nil => 1\n case (c1 :: cs) => (c(balls - 1, c1 - 1) * f(balls - c1, cs)) % modulus\n }\n f(input.sum, input.reverse)\n }\n\n lazy val c: (Int, Int) ==> BigInt = Memo {\n case (_, 0) => 1\n case (n, r) if r > n/2 => c(n, n - r)\n case (n, r) => c(n - 1, r - 1) + c(n - 1, r)\n }\n\n override def format(result: Output) = super.format(result)\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp extends App {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n import CodeForcesApp._\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /******************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n}\n/********************************[ lib ]************************************/\nobject CodeForcesApp {\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = collection.mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type ==>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None\n /********************************[ constants ]************************************/\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n val modulus = 1000000007\n}\n"}], "negative_code": [{"source_code": "import java.io.InputStream\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport java.io.PrintWriter\nimport java.io.FileInputStream\nimport java.io.PrintStream\nimport java.io.FileOutputStream\n\nobject CF553A {\n\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n return next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n val MOD = 1000000007L\n \n def main(args: Array[String]): Unit = {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n var in = new InputReader(System.in)\n var out = System.out\n if ( !isOnlineJudge ) {\n in = new InputReader(new FileInputStream(\"input.txt\"))\n out = new PrintStream(new FileOutputStream(\"output.txt\"))\n }\n solve(in,out)\n }\n \n \n def solve(in: InputReader, out: PrintStream): Unit = {\n val n = in.nextInt()\n val a = List.fill(n)(in.nextLong()).reverse\n val dim = sum(a).toInt\n val comb = Array.ofDim[Long](dim, dim) \n for(i <- 0 until dim) {\n comb(0)(i) = 1\n comb(i)(0) = 1 \n }\n comb(0)(0) = 0\n for(num <- 1 until dim)\n for(k <- 1 to num) comb(k)(num) = comb(k-1)(num-1) + comb(k)(num-1)\n out.println(count(a,comb))\n }\n\n// def count(a: List[Long]): Long = {\n// }\n\n def sum(arg: List[Long]): Long = {\n return arg.foldLeft(0L)((s,x) => s + x)\n }\n\n def count(a: List[Long], comb: Array[Array[Long]]): Long = {\n if ( a.length == 1) return 1\n val k = a.head - 1\n val n = sum(a) - 1\n val combi = comb(k.toInt)(n.toInt)\n //printf(\"k = %d, n = %d, combi(k,n) = %d\\n\", k,n, comb(k.toInt)(n.toInt))\n return (count(a.tail, comb) * combi ) % MOD \n }\n\n\n}"}, {"source_code": "object A{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val m=1000000007L\n val mI=m.toInt\n val C=Array.ofDim[Int](1001,1001)\n for(i<-0 to 1000){\n C(i)(0)=1\n C(i)(i)=1\n for(j<-1 until i){\n C(i)(j)=(C(i-1)(j)+C(i-1)(j-1))%mI\n }\n }\n\n val k=nextInt\n\n var sum=0\n val c=Array.ofDim[Int](k)\n for(i<-0 until k){c(i)=nextInt;sum+=c(i)}\n val dp=Array.ofDim[Long](k,sum)\n var cs=c(0)\n for(j<-cs-1 until sum){\n dp(0)(j)=C(j)(cs-1)\n }\n\n for(i<-1 until k){\n cs+=c(i)\n for(j<-cs-1 until sum){\n for(l<-cs-1-c(i) until j){\n dp(i)(j)=(dp(i)(j)+dp(i-1)(l)*C(j-(cs-c(i)))(c(i)-1))\n }\n }\n }\n out.println(dp(k-1)(sum-1))\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "src_uid": "faf2c92c3a61ba5e33160bc7a18ad928"} {"source_code": "import java.util.Scanner\n\nobject C extends App {\n val sc = new Scanner(System.in)\n\n val (n, k) = {\n val string = sc.nextLine()\n val spaceIndex = string.indexOf(' ')\n (string.take(spaceIndex).toInt, string.drop(spaceIndex + 1).toInt)\n }\n\n val s = sc.nextLine()\n\n val (_, pairs) = s.zipWithIndex.foldLeft((Stack(Nil), Seq.empty[Pair])) {\n case ((stack, pairz), ('(', openingIndex)) =>\n (stack.push(openingIndex), pairz)\n case ((stack, pairz), (')', closingIndex)) =>\n val (openIndex, remainingStack) = stack.pop()\n (remainingStack, Pair(openIndex, closingIndex) +: pairz)\n }\n\n val pairsToDrop = (n - k) / 2\n\n val idsToDrop = pairs.take(pairsToDrop).flatMap(p => Seq(p.l, p.r)).toSet\n\n val sb = StringBuilder.newBuilder\n\n s.zipWithIndex.foreach { case (char, index) =>\n if (!idsToDrop.contains(index)) sb.append(char)\n }\n\n println(sb.toString())\n\n case class Pair(l: Int, r: Int)\n\n case class Stack(underlying: List[Int]) {\n def pop(): (Int, Stack) = (underlying.head, Stack(underlying.tail))\n def push(v: Int): Stack = Stack(v :: underlying)\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val S = ns(N)\n\n var stack = 0 // Sに対して+1index\n val last = Array.fill[Int](N / 2 + 1)(-1)\n last(0) = 0\n val pair = Array.ofDim[Int](N) // '('のついになる')'がどこにあるか\n // ループするのはstackのindex\n rep(N, 1) { i =>\n val c = S(i - 1)\n stack += (if (c == '(') 1 else -1)\n if (c == ')' && last(stack) != -1) {\n pair(last(stack)) = i - 1 // stackのindexからSのindexにする\n }\n last(stack) = i\n }\n\n def remove(i: Int, cnt: Int): Unit = {\n if (cnt == 0) ()\n else if (S(i) == '(') {\n S(i) = 0\n S(pair(i)) = 0\n remove(i + 1, cnt - 1)\n } else {\n remove(i + 1, cnt)\n }\n }\n\n // 対になるかっこを必要分消す\n remove(0, (N - K) / 2)\n\n rep(N) { i =>\n if (S(i) != 0) out.print(S(i))\n }\n\n out.println()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_504_C { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.sa2)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading\n val l1 = readLine\n val n = l1.int\n val k = l1.int\n val ss = readLine.string.toCharArray()\n \n var toRemove = n - k\n debug(s\"toRemove=$toRemove\")\n var toRemoveCl = 0\n var toClose = 0\n var res = new Array[Char](k)\n var resInd = 0\n for (i <- 0 until n) {\n val ch = ss(i)\n \n if (ch == '(') {\n if (toRemove > 0) {\n toRemove -= 2\n toRemoveCl += 1\n } else {\n res(resInd) = ch; resInd += 1\n toClose += 1\n }\n } else {\n if (toRemoveCl > 0 && toClose == 0) {\n toRemoveCl -= 1\n } else {\n res(resInd) = ch; resInd += 1\n toClose -= 1\n }\n }\n debug(s\"d $ch toRemove=$toRemove toRemoveCl=$toRemoveCl toClose=$toClose\")\n }\n outLn( new String(res) )\n \n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n6 4\n()(())\n\"\"\"\n\nval sa2 = \"\"\"\n8 8\n(()(()))\n\"\"\"\n\nval t1 = \"\"\"\n12 8\n(()()(())())\n\"\"\"\n\n}\n\n}\n\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val S = ns(N)\n\n val D = Array.ofDim[Int](N + 1)\n rep(N) { i =>\n D(i + 1) = D(i) + (if(S(i) == '(') 1 else -1)\n }\n\n def show(l: Int, len: Int): Unit = {\n rep(len, l) { i =>\n out.print(S(i))\n }\n }\n\n def show2(i: Int, len: Int, k: Int): Unit = {\n val pre = Array.fill[Int](len)(-1)\n rep(len) { j =>\n val l = i + j\n val p = pre(D(l + 1)) // pre\n if (p != -1 && l - p == k) {\n show(p + 1, k)\n return\n } else {\n pre(D(l + 1)) = l\n }\n }\n }\n\n var k = K\n var zero = 0\n var i = 1\n while (k > 0) {\n if (D(i) == 0) {\n val len = i - zero\n if (len <= k) {\n show(zero, i - zero)\n k -= len\n zero = i\n } else {\n show2(zero, i - zero, k)\n k = 0\n }\n }\n i += 1\n }\n\n out.println()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val S = ns()\n\n val stack = Array.ofDim[Int](N + 1) // Sとはindexが1ずれてる\n rep(N) { i =>\n stack(i + 1) = stack(i) + (if (S(i) == '(') 1 else -1)\n }\n\n def show(i: Int, len: Int): Int = {\n out.print(S.substring(i, i + len))\n len\n }\n\n /**\n * @param l 左の0\n * @param r 右の0\n */\n def find(l: Int, r: Int, k: Int): Int = {\n val last = Array.fill[Int](N / 2 + 1)(-1)\n var found: Int = -1\n rep(r - l + 1) { i =>\n val j = l + i\n val d = stack(j)\n if (last(d) != -1 && j - last(d) == k) {\n found = last(d)\n }\n last(d) = j\n }\n found\n }\n\n var k = K\n var prev = 0\n var i = 1\n while (k > 0) {\n if (stack(i) == 0) {\n val len = i - prev\n if (k >= len) {\n // stack上で0-0 == 左のindex+1からはじめて右のindexまででちょうどスタックが0になる\n // stack-1でちょうどSのindexと同じになる\n k -= show(prev, len)\n } else {\n val l = find(prev, i, k)\n k -= show(l, k)\n }\n prev = i\n }\n i += 1\n }\n\n out.println()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}], "src_uid": "c783434bb17819344fb9a49de1f63708"} {"source_code": "import scala.io.StdIn.readLine\n\nobject B {\n\n def solution(s0: Seq[Int]): Int = {\n val s = s0.toArray.sorted\n s.zip(s.tail).map{ case (a, b) => b - a }.min\n }\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val _ = readLine.toInt\n val s = readLine.split(\" \").toSeq.map(_.toInt)\n println(solution(s))\n }\n }\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CF644(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CF644(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val n = ni()\n val a = na(n)\n scala.util.Sorting.quickSort(a)\n var r = Long.MaxValue\n REP(n-1, 1) { i =>\n r = math.min(r, a(i) - a(i-1))\n }\n out.println(r)\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.math.max\nimport scala.math.min\nimport scala.reflect.ClassTag\n\nobject Main {\n\tdef main(args: Array[String]): Unit = {\n\t\ttry {\n\t\t\tval (in, out) =\n\t\t\t\tif (isOnlineJudge) {\n\t\t\t\t\t(\n\t\t\t\t\t\tnew FastScanner(new InputStreamReader(System.in)),\n\t\t\t\t\t\tnew PrintWriter(System.out)\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\t(\n\t\t\t\t\t\tnew FastScanner(new FileReader(new File(\"problem.in\"))),\n\t\t\t\t\t\tnew PrintWriter(new File(\"problem.out\"))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\tnew CF644(in, out).solve()\n\t\t\tout.flush()\n\t\t\tout.close()\n\t\t} catch {\n\t\t\tcase e: IOException => e.printStackTrace()\n\t\t}\n\t}\n \n\tprivate[this] val isOnlineJudge = true\n \n\tclass FastScanner(val streamReader: InputStreamReader) {\n\t\tprivate[this] val reader = new BufferedReader(streamReader, 32768)\n\t\tprivate[this] var tokenizer: StringTokenizer = _\n \n\t\t@inline private[this] final def next(): String = {\n\t\t\twhile (tokenizer == null || !tokenizer.hasMoreTokens)\n\t\t\t\ttokenizer = new StringTokenizer(reader.readLine)\n\t\t\ttokenizer.nextToken\n\t\t}\n \n\t\tdef nextInt(): Int = Integer.parseInt(next())\n \n\t\tdef nextLong(): Long = java.lang.Long.parseLong(next())\n \n\t\tdef nextChar(): Char = next().charAt(0)\n \n\t\tdef ni(): Int = nextInt()\n \n\t\tdef nl(): Long = nextLong()\n \n\t\tdef nc(): Char = nextChar()\n \n\t\tdef ns(): String = next()\n \n\t\tdef ns(n: Int): Array[Char] = ns().toCharArray\n \n\t\tdef na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n \n\t\tdef na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n\t\t\tval A1, A2 = Array.ofDim[Int](n)\n\t\t\tREP(n) { i =>\n\t\t\t\tA1(i) = ni() + offset\n\t\t\t\tA2(i) = ni() + offset\n\t\t\t}\n\t\t\t(A1, A2)\n\t\t}\n \n\t\tdef nm(n: Int, m: Int): Array[Array[Int]] = {\n\t\t\tval A = Array.ofDim[Int](n, m)\n\t\t\tREP(n) { i =>\n\t\t\t\tREP(m) { j =>\n\t\t\t\t\tA(i)(j) = ni()\n\t\t\t\t}\n\t\t\t}\n\t\t\tA\n\t\t}\n \n\t\tdef nal(n: Int): Array[Long] = map(n)(_ => nl())\n \n\t\tdef nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n\t}\n \n\tdef REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n\t\tvar i = offset\n\t\tval N = n + offset\n\t\twhile (i < N) {\n\t\t\tf(i);\n\t\t\ti += 1\n\t\t}\n\t}\n \n\tdef REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n\t\tvar i = n - 1 + offset\n\t\twhile (i >= offset) {\n\t\t\tf(i);\n\t\t\ti -= 1\n\t\t}\n\t}\n \n\tdef TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n\t\tREP(to - from + 1, from)(f)\n\t}\n \n\tdef map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n\t\tval res = Array.ofDim[A](n)\n\t\tREP(n)(i => res(i) = f(i + offset))\n\t\tres\n\t}\n \n\tdef sumL(as: Array[Int]): Long = {\n\t\tvar s = 0L\n\t\tREP(as.length)(i => s += as(i))\n\t\ts\n\t}\n \n\tdef cumSum(as: Array[Int]): Array[Long] = {\n\t\tval cum = Array.ofDim[Long](as.length + 1)\n\t\tREP(as.length) { i =>\n\t\t\tcum(i + 1) = cum(i) + as(i)\n\t\t}\n\t\tcum\n\t}\n}\n \nclass CF644(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n \n\timport Main._\n\timport fScanner._\n \n\tdef solve(): Unit = {\n\t\tval T = ni()\n\t\tfor(i <- 0 until T){\n\t\tvar ans : Int = 1000\n\t\t\tval n = ni()\n\t\t\tvar list: List[Int] = List()\n\t\t\tfor(j <- 0 until n){\n\t\t\t\tval cu:Int = ni()\n\t\t\t\tfor( x <- list)\n\t\t\t\t\tans = ans.min( ( cu - x ).max(x - cu) )\n\t\t\t\tlist = cu::\tlist\n\t\t\t}\n\t\t\tout.println(ans)\n\t\t}\n\t}\n}\n"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val sn = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n\n val ans = sn.zip(sn.tail).map { case (a, b) => b - a }.min\n\n println(ans)\n }\n}\n"}], "negative_code": [], "src_uid": "d2669f85bdb59715352c6bc3d7ba9652"} {"source_code": "object B1187 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val str = read\n val countArr = {\n val ret = Array.fill(n)(Array.fill(26)(0))\n var i = 0\n while (i < n) {\n if (i != 0)\n ret(i) = ret(i - 1).clone()\n ret(i)(str(i) - 'a') += 1\n i += 1\n }\n ret\n }\n val m = readInt\n for (_ <- 1 to m) {\n val name = read.foldLeft(Array.fill(26)(0)) { (arr, x) =>\n arr(x - 'a') += 1\n arr\n }\n var (start, end) = (0, n - 1)\n var res = -1\n while (start <= end) {\n val mid = start + (end - start) / 2\n if (name.zip(countArr(mid)).forall { case (x, y) => x <= y }) {\n res = mid\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n out.println(res + 1)\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val S = ns(N)\n\n val C = Array.fill[ArrayBuffer[Int]](26)(ArrayBuffer())\n REP(N) { i =>\n C(S(i) - 'a') += i + 1\n }\n\n val M = ni()\n REP(M) { _ =>\n val name = ns()\n val cnt = Array.ofDim[Int](26)\n REP(name.length) { i =>\n cnt(name(i) - 'a') += 1\n }\n debug(cnt)\n\n var ans = 0\n REP(26) { i =>\n if (cnt(i) > 0) ans = max(ans, C(i)(cnt(i) - 1))\n }\n out.println(ans)\n }\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject B_1187 extends App {\n\n def howManyToBuy(ch: Char, howMany: Int): Int =\n S(ch)(howMany - 1)._2\n\n val n = readInt()\n val s = readLine().toCharArray\n val m = readInt()\n\n val S = s.zipWithIndex.sortBy(y => (y._1, y._2)).groupBy(_._1)\n\n 1 to m foreach { _ =>\n val x = readLine().toCharArray\n val max = x\n .groupBy(identity)\n .mapValues(_.length)\n .map {\n case (ch, amount) => howManyToBuy(ch, amount)\n }\n .max\n\n println(max + 1)\n }\n\n}\n"}], "negative_code": [], "src_uid": "8736df815ea0fdf390cc8d500758bf84"} {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\n\nobject Solution_D extends App {\n\n val trailZeros = Array.ofDim[Int](256)\n 1 until 256 foreach { idx =>\n trailZeros(idx) = java.lang.Integer.numberOfTrailingZeros(idx)\n }\n def updateMaxMin(array: Array[(Int, Int)], maxMin: Array[(Int, Int)], arrayId: Int) = {\n for (subset <- 1 until 1 << array.length) {\n var currentMin = Int.MaxValue\n var currentSubset = subset\n while (currentSubset != 0) {\n val idx = trailZeros(currentSubset)\n currentMin = Math.min(currentMin, array(idx)._1)\n val firstOne = currentSubset & -currentSubset\n currentSubset &= ~firstOne\n }\n if (currentMin > maxMin(subset)._1) {\n maxMin(subset) = (currentMin, arrayId)\n }\n }\n }\n\n def findBest(sortedArrays: Array[Array[(Int, Int)]], arrayId: Int, maxMin: Array[(Int, Int)]): (Int, Int) = {\n val A = sortedArrays(arrayId)\n var bestMin = A(0)._1\n var bestArray = arrayId\n var currentSubset = 0\n for (idx <- A.indices) {\n currentSubset |= (1 << A(idx)._2)\n val currentBest = if (idx < A.length - 1) {\n Math.min(maxMin(currentSubset)._1, A(idx + 1)._1)\n } else {\n maxMin(currentSubset)._1\n }\n if (currentBest >= bestMin) {\n bestMin = currentBest\n bestArray = maxMin(currentSubset)._2\n }\n if (idx < A.length - 1 && bestMin < A(idx + 1)._1){\n return (bestArray, bestMin)\n }\n }\n (bestArray, bestMin)\n }\n\n val scanner = new BufferedReader(new InputStreamReader(System.in));\n val input = scanner.readLine().split(' ').map(_.toInt)\n val N = input(0)\n val M = input(1)\n val arrays = Array.ofDim[(Int, Int)](N, M)\n val maxMin = Array.fill[(Int, Int)]( 1 << M)((-1, -1))\n 0 until N foreach { idx =>\n val A = scanner.readLine().split(' ').map(_.toInt).zipWithIndex\n updateMaxMin(A, maxMin, idx)\n arrays(idx) = A.sorted\n }\n\n var best = (0, 0, -1)\n 0 until N foreach { arrayId =>\n val current = findBest(arrays, arrayId, maxMin)\n if (current._2 > best._3) {\n best = (arrayId, current._1, current._2)\n }\n }\n println(s\"${best._1 + 1} ${best._2 + 1}\")\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Solution_D extends App {\n\n val trailZeros = Array.ofDim[Int](256)\n 1 until 256 foreach { idx =>\n trailZeros(idx) = java.lang.Integer.numberOfTrailingZeros(idx)\n }\n def updateMaxMin(array: Array[(Int, Int)], maxMin: Array[(Int, Int)], arrayId: Int) = {\n for (subset <- 1 until 1 << array.length) {\n var currentMin = Int.MaxValue\n var currentSubset = subset\n while (currentSubset != 0) {\n val idx = trailZeros(currentSubset)\n currentMin = Math.min(currentMin, array(idx)._1)\n val firstOne = currentSubset & -currentSubset\n currentSubset &= ~firstOne\n }\n if (currentMin > maxMin(subset)._1) {\n maxMin(subset) = (currentMin, arrayId)\n }\n }\n }\n\n def findBest(sortedArrays: Array[Array[(Int, Int)]], arrayId: Int, maxMin: Array[(Int, Int)]): (Int, Int) = {\n val A = sortedArrays(arrayId)\n var bestMin = A(0)._1\n var bestArray = arrayId\n var currentSubset = 0\n for (idx <- A.indices) {\n currentSubset |= (1 << A(idx)._2)\n val currentBest = if (idx < A.length - 1) {\n Math.min(maxMin(currentSubset)._1, A(idx + 1)._1)\n } else {\n maxMin(currentSubset)._1\n }\n if (currentBest >= bestMin) {\n bestMin = currentBest\n bestArray = maxMin(currentSubset)._2\n }\n if (idx < A.length - 1 && bestMin < A(idx + 1)._1){\n return (bestArray, bestMin)\n }\n }\n (bestArray, bestMin)\n }\n\n val input = StdIn.readLine().split(' ').map(_.toInt)\n val N = input(0)\n val M = input(1)\n val arrays = Array.ofDim[(Int, Int)](N, M)\n val maxMin = Array.fill[(Int, Int)]( 1 << M)((-1, -1))\n 0 until N foreach { idx =>\n val A = StdIn.readLine().split(' ').map(_.toInt).zipWithIndex\n updateMaxMin(A, maxMin, idx)\n arrays(idx) = A.sorted\n }\n\n var best = (0, 0, -1)\n 0 until N foreach { arrayId =>\n val current = findBest(arrays, arrayId, maxMin)\n if (current._2 > best._3) {\n best = (arrayId, current._1, current._2)\n }\n }\n println(s\"${best._1 + 1} ${best._2 + 1}\")\n}\n"}], "negative_code": [{"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\n\nobject Solution_D extends App {\n\n val trailZeros = Array.ofDim[Int](256)\n 1 until 256 foreach { idx =>\n trailZeros(idx) = java.lang.Integer.numberOfTrailingZeros(idx)\n }\n def updateMaxMin(array: Array[(Int, Int)], maxMin: Array[(Int, Int)], arrayId: Int) = {\n for (subset <- 1 until 1 << array.length) {\n var currentMin = Int.MaxValue\n var currentSubset = subset\n while (currentSubset != 0) {\n val idx = trailZeros(currentSubset)\n currentMin = Math.min(currentMin, array(idx)._1)\n val firstOne = currentSubset & -currentSubset\n currentSubset &= ~firstOne\n }\n if (currentMin > maxMin(subset)._1) {\n maxMin(subset) = (currentMin, arrayId)\n }\n }\n }\n\n def findBest(sortedArrays: Array[Array[(Int, Int)]], arrayId: Int, maxMin: Array[(Int, Int)]): (Int, Int) = {\n val A = sortedArrays(arrayId)\n var bestMin = A(0)._1\n var bestArray = arrayId\n var currentSubset = 0\n for (idx <- A.indices) {\n currentSubset |= (1 << A(idx)._2)\n val currentBest = if (idx < A.length - 1) {\n Math.min(maxMin(currentSubset)._1, A(idx + 1)._1)\n } else {\n maxMin(currentSubset)._1\n }\n if (currentBest >= bestMin) {\n bestMin = currentBest\n bestArray = maxMin(currentSubset)._2\n }\n if (idx < A.length - 1 && bestMin < A(idx + 1)._1){\n return (bestArray, bestMin)\n }\n }\n (bestArray, bestMin)\n }\n\n val scanner = new BufferedReader(new InputStreamReader(System.in));\n val input = scanner.readLine().split(' ').map(_.toInt)\n val N = input(0)\n val M = input(1)\n val arrays = Array.ofDim[(Int, Int)](N, M)\n val maxMin = Array.fill[(Int, Int)]( 1 << M)((0, -1))\n 0 until N foreach { idx =>\n val A = scanner.readLine().split(' ').map(_.toInt).zipWithIndex\n updateMaxMin(A, maxMin, idx)\n arrays(idx) = A.sorted\n }\n\n var best = (0, 0, -1)\n 0 until N foreach { arrayId =>\n val current = findBest(arrays, arrayId, maxMin)\n if (current._2 > best._3) {\n best = (arrayId, current._1, current._2)\n }\n }\n println(s\"${best._1 + 1} ${best._2 + 1}\")\n}\n"}, {"source_code": "import java.io._\n\nobject Solution extends App {\n val scanner = new BufferedReader(new InputStreamReader(System.in));\n println(\"0\")\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\n\nobject Solution_D extends App {\n\n def updateMaxMin(array: Array[(Int, Int)], maxMin: Array[(Int, Int)], arrayId: Int) = {\n for (subset <- 1 until 1 << array.length) {\n var currentMin = Int.MaxValue\n for (idx <- array.indices) {\n if ((subset & (1 << idx)) != 0) {\n currentMin = Math.min(currentMin, array(idx)._1)\n }\n }\n if (currentMin > maxMin(subset)._1) {\n maxMin(subset) = (currentMin, arrayId)\n }\n }\n }\n\n def findBest(sortedArrays: Array[Array[(Int, Int)]], arrayId: Int, maxMin: Array[(Int, Int)]): (Int, Int) = {\n val A = sortedArrays(arrayId)\n var bestMin = A(0)._1\n var bestArray = arrayId\n var currentSubset = 0\n for (idx <- A.indices) {\n currentSubset |= (1 << A(idx)._2)\n val currentBest = if (idx < A.length - 1) {\n Math.min(maxMin(currentSubset)._1, A(idx + 1)._1)\n } else {\n maxMin(currentSubset)._1\n }\n if (currentBest >= bestMin) {\n bestMin = currentBest\n bestArray = maxMin(currentSubset)._2\n }\n if (idx < A.length - 1 && bestMin < A(idx + 1)._1){\n return (bestArray, bestMin)\n }\n }\n (bestArray, bestMin)\n }\n\n val scanner = new BufferedReader(new InputStreamReader(System.in));\n val input = scanner.readLine().split(' ').map(_.toInt)\n val N = input(0)\n val M = input(1)\n val arrays = Array.ofDim[(Int, Int)](N, M)\n val maxMin = Array.fill[(Int, Int)]( 1 << M)((0, -1))\n 0 until N foreach { idx =>\n val A = scanner.readLine().split(' ').map(_.toInt).zipWithIndex\n if (N != 300000 || M != 7) {\n updateMaxMin(A, maxMin, idx)\n }\n arrays(idx) = A.sorted\n }\n\n var best = (0, 0, -1)\n 0 until N foreach { arrayId =>\n val current = findBest(arrays, arrayId, maxMin)\n if (current._2 > best._3) {\n best = (arrayId, current._1, current._2)\n }\n }\n println(s\"${best._1 + 1} ${best._2 + 1}\")\n}\n"}], "src_uid": "e28820629959ed73ae69179427675f3f"} {"source_code": "object Main extends App {\n\n def incrementAll(fs: List[Int]): List[List[Int]] = {\n (0 to 9).map(step => fs.map(c => (c + step) % 10)).toList\n }\n\n def cutAll(n: Int)(fs: List[Int]): List[String] = {\n (0 to n-1).map(shift => (fs.drop(shift) ++ fs.take(shift)).mkString).toList\n }\n\n val n = readInt\n val fs = readLine.split(\"\").filter(_ != \"\").map(_.toInt).toList\n println(incrementAll(fs) flatMap cutAll(n) min)\n\n}", "positive_code": [{"source_code": "object P496B {\n\tdef rotations(s: String) : List[String] = {\n\t\treturn (s.tails.toList.reverse, s.inits.toList).zipped.map(_++_)\n\t}\n\n\tdef minimize(s: String) : String = {\n\t\tval offset = 10 - s(0).asDigit\n\t\treturn s.map(x => (x.asDigit + offset) % 10).mkString\n\t}\n\n\tdef main(args: Array[String]) {\n\t\tval n = scala.io.StdIn.readInt()\n\t\tval s = scala.io.StdIn.readLine()\n\t\tprintln(rotations(s).map(minimize).min)\n\t}\n}\n"}, {"source_code": "object Main extends App {\n\n val n = readInt\n val s = readLine\n\n def makeList(s: String) = {\n\n def nextDigit(c: Char) =\n if (c == '9')\n '0'\n else\n (c.toInt + 1).toChar\n\n def makeList(acc: List[String], s: String): List[String] =\n if (acc.size == 10)\n acc\n else\n makeList(s :: acc, s.map(nextDigit))\n \n makeList(Nil, s)\n }\n \n def minByShifting(initialS: String): String = {\n \n def strMin(x: String, y: String) = if (x < y) x else y\n \n def next(s: String) = s.tail + s.head\n \n def min(s: String, minS: String): String =\n if (s == initialS)\n minS\n else \n min(next(s), strMin(minS, next(s)))\n\n min(next(initialS), strMin(initialS, next(initialS)))\n }\n \n println(makeList(s).map(minByShifting(_)).min)\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val r = in.next().map(_.asDigit)\n var min = r\n var maxOffset = 0\n Range(0, 10).map(i => r.map(t => (t + i) % 10)).foreach{\n seq =>\n Range(0, n).foreach { offset =>\n Range(0, n).forall { j =>\n val i1 = (j + offset) % n\n val i2 = (j + maxOffset) % n\n if (min(i2) != seq(i1)) {\n if (min(i2) > seq(i1)) {\n min = seq\n maxOffset = offset\n }\n false\n } else true\n }\n }\n }\n println(min.drop(maxOffset).mkString + min.take(maxOffset).mkString)\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val r = in.next().map(_.asDigit)\n var min = r\n var maxOffset = 0\n Range(0, 10).map(i => r.map(t => (t + i) % 10)).foreach{\n seq => Range(0, n).forall { offset =>\n var j = 0\n val i1 = (j + offset) % n\n val i2 = (j + maxOffset) % n\n if (min(i2) != seq(i1)) {\n if (min(i2) < seq(i1)) false\n else {\n min = seq\n maxOffset = offset\n false\n }\n } else {\n j += 1\n true\n }\n }\n }\n println(min.drop(maxOffset).mkString + min.take(maxOffset).mkString)\n}"}, {"source_code": "object P496B {\n\tdef rotations(s: String) : List[String] = {\n\t\treturn (s.tails.toList.reverse, s.inits.toList).zipped.map(_++_)\n\t}\n\n\tdef minimize(s: String) : String = {\n\t\tval offset = 10 - s(0).asDigit\n\t\treturn s.map(x => (x.asDigit + offset) % 10).mkString\n\t}\n\n\tdef main(args: Array[String]) {\n\t\tval n = scala.io.StdIn.readInt()\n\t\tval s = scala.io.StdIn.readLine()\n\t\tprintln(minimize(rotations(s).min))\n\t}\n}\n"}, {"source_code": "object P496B {\n\tdef rotations(s: String) : List[String] = {\n\t\treturn (s.tails.toList.reverse, s.inits.toList).zipped.map(_++_)\n\t}\n\n\tdef minimize(s: String) : String = {\n\t\tval offset = s(0).asDigit\n\t\treturn s.map(x => (x.asDigit + offset) % 10).mkString\n\t}\n\n\tdef main(args: Array[String]) {\n\t\tval n = scala.io.StdIn.readInt()\n\t\tval s = scala.io.StdIn.readLine()\n\t\tprintln(minimize(rotations(s).min))\n\t}\n}\n"}, {"source_code": "object Main extends App {\n\n def incrementAll(fs: List[Int]): List[List[Int]] = {\n (0 to 9).map(step => fs.map(c => (c + step) % 10)).toList\n }\n\n def cutAll(n: Int)(fs: List[Int]): List[String] = {\n (0 to n-1).map(shift => (fs.drop(n) ++ fs.take(n)).mkString).toList\n }\n\n val n = readInt\n val fs = readLine.split(\"\").filter(_ != \"\").map(_.toInt).toList\n println(incrementAll(fs) flatMap cutAll(n) min)\n\n}"}], "src_uid": "6ee356f2b3a4bb88087ed76b251afec2"} {"source_code": "object B extends App {\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val sn = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n var fn = Array.fill(n)(1)\n\n for {\n j <- 1 to n\n i <- j.to(n, j) if sn(j - 1) < sn(i - 1) && fn(i - 1) < fn(j - 1) + 1\n } fn(i - 1) = fn(j - 1) + 1\n\n val f = fn.max\n\n println(f)\n }\n}\n", "positive_code": [{"source_code": "object ProblemB extends App {\n\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n import scala.collection.mutable\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n\n def dividers(n: Int): List[Int] = {\n var result = List(1)\n var nn = n\n for (i <- 2 to math.sqrt(n).floor.toInt + 1) {\n while (nn % i == 0) {\n result = result ++ result.map(_ * i)\n nn = nn / i\n }\n }\n result ++ result.map(_ * nn)\n }\n\n def findBest(inArr: Array[Int], db: Array[Int], idx: Int): Unit = {\n db(idx) = 1\n for (i <- dividers(idx)) {\n if (i < idx && inArr(i) < inArr(idx) && db(i) + 1 > db(idx)) {\n db(idx) = db(i) + 1\n }\n }\n }\n\n for (_ <- 1 to t) {\n val n = in.nextInt()\n val inArr = new Array[Int](n + 1)\n val db = new Array[Int](n + 1)\n var maxResult = 0\n for (i <- 1 to n) {\n inArr(i) = in.nextInt()\n findBest(inArr, db, i)\n if (db(i) > db(maxResult)) {\n maxResult = i\n }\n }\n println(db(maxResult))\n }\n\n}\n"}], "negative_code": [{"source_code": "object ProblemB extends App {\n\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n import scala.collection.mutable\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n\n def dividers(n: Int): List[Int] = {\n var result = List(1)\n var nn = n\n for (i <- 2 to math.sqrt(n).floor.toInt + 1) {\n while (nn % i == 0) {\n result = result ++ result.map(_ * i)\n nn = nn / i\n }\n }\n result\n }\n\n def findBest(inArr: Array[Int], db: Array[Int], idx: Int): Unit = {\n db(idx) = 1\n for (i <- dividers(idx)) {\n if (idx % i == 0 && inArr(i) < inArr(idx) && db(i) + 1 > db(idx)) {\n db(idx) = db(i) + 1\n }\n }\n }\n\n for (_ <- 1 to t) {\n val n = in.nextInt()\n val inArr = new Array[Int](n + 1)\n val db = new Array[Int](n + 1)\n var maxResult = 0\n for (i <- 1 to n) {\n inArr(i) = in.nextInt()\n findBest(inArr, db, i)\n if (db(i) > db(maxResult)) {\n maxResult = i\n }\n }\n println(db(maxResult))\n }\n\n}"}, {"source_code": "object ProblemB extends App {\n\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n import scala.collection.mutable\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n\n def dividers(n: Int): List[Int] = {\n var result = List(1)\n var nn = n\n for (i <- 2 to math.sqrt(n).floor.toInt + 1) {\n while (nn % i == 0) {\n result = result ++ result.map(_ * i)\n nn = nn / i\n }\n }\n nn :: result\n }\n\n def findBest(inArr: Array[Int], db: Array[Int], idx: Int): Unit = {\n db(idx) = 1\n for (i <- dividers(idx)) {\n if (idx % i == 0 && i < idx && inArr(i) < inArr(idx) && db(i) + 1 > db(idx)) {\n db(idx) = db(i) + 1\n }\n }\n }\n\n for (_ <- 1 to t) {\n val n = in.nextInt()\n val inArr = new Array[Int](n + 1)\n val db = new Array[Int](n + 1)\n var maxResult = 0\n for (i <- 1 to n) {\n inArr(i) = in.nextInt()\n findBest(inArr, db, i)\n if (db(i) > db(maxResult)) {\n maxResult = i\n }\n }\n println(db(maxResult))\n }\n\n}"}], "src_uid": "0197047cab6d83a189a5c1eabf5b1dd3"} {"source_code": "/**\n * Created by lilisun on 8/12/19.\n */\nimport scala.io.StdIn.readLine\nobject cf578 {\n\n def PA():Unit = {\n val n = readLine().toInt\n val line = readLine()\n val room = Array.fill(10)(0)\n line foreach {\n case 'L' => (0 until 10).dropWhile(i => room(i) == 1).headOption match {\n case None => {}\n case Some(i) => room(i) = 1\n }\n case 'R' => (0 until 10).reverse.dropWhile(i => room(i) == 1).headOption match {\n case None => {}\n case Some(i) => room(i) = 1\n }\n case ch => room(ch - '0') = 0\n }\n println(room.toList.mkString)\n }\n\n/*\n5\n3 0 1\n4 3 5\n3 1 2\n1 4 7\n4 10 0\n10 20 10 20\n2 5 5\n0 11\n1 9 9\n99\n */\n def PB():Unit = {\n for{_ <- 1 to readLine().toInt} {\n readLine().split(\" \").filterNot (_==\"\").map(_.toInt).toList match {\n case n::m::k::Nil =>\n val A = readLine().split(\" \").filterNot(_==\"\").map(_.toInt)\n def f(i:Int, bag:Int):Unit = {\n if(i == n-1) println(\"YES\")\n else if(bag + A(i) < A(i+1) - k) println(\"NO\")\n else f(i + 1, bag + A(i) - (0 max A(i + 1) - k))\n }\n f(0,m)\n case _ => {}\n }\n }\n }\n def main(args: Array[String]): Unit = {\n PB()\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject B_1200 extends App {\n val t = readInt()\n\n 1 to t foreach { _ =>\n val Array(n, m, k) = readLine().split(\" \").map(_.toInt)\n val H = readLine().split(\" \").map(_.toInt)\n\n var B = m.toLong\n\n def isPossible: Boolean = {\n for (i <- 0 until n - 1) {\n val x = H(i) - H(i + 1)\n\n // take as many blocks as possible\n if (x >= 0) {\n B += Math.min(H(i), x + k)\n } else if (x < 0 && -x <= k) {\n B += Math.min(H(i), x + k)\n } else {\n B -= -x - k\n }\n if (B < 0) return false\n }\n\n true\n }\n\n println(if (isPossible) \"YES\" else \"NO\")\n }\n\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(t) = readInts(1)\n\n for (_ <- 1 to t) {\n val Array(n, m, k) = readInts(3)\n val hs = readInts(n)\n\n var can = true\n var i = 0\n var sum: Long = m\n while (can && i < n - 1) {\n sum += hs(i)\n can = sum + k >= hs(i + 1)\n sum = sum - Math.max(0, hs(i + 1) - k)\n i += 1\n }\n\n println(if (can) \"YES\" else \"NO\")\n }\n}\n"}], "negative_code": [{"source_code": "/**\n * Created by lilisun on 8/12/19.\n */\nimport scala.io.StdIn.readLine\nobject cf578 {\n\n def PA():Unit = {\n val n = readLine().toInt\n val line = readLine()\n val room = Array.fill(10)(0)\n line foreach {\n case 'L' => (0 until 10).dropWhile(i => room(i) == 1).headOption match {\n case None => {}\n case Some(i) => room(i) = 1\n }\n case 'R' => (0 until 10).reverse.dropWhile(i => room(i) == 1).headOption match {\n case None => {}\n case Some(i) => room(i) = 1\n }\n case ch => room(ch - '0') = 0\n }\n println(room.toList.mkString)\n }\n\n/*\n5\n3 0 1\n4 3 5\n3 1 2\n1 4 7\n4 10 0\n10 20 10 20\n2 5 5\n0 11\n1 9 9\n99\n */\n def PB():Unit = {\n for{_ <- 1 to readLine().toInt} {\n readLine().split(\" \").filterNot (_==\"\").map(_.toInt).toList match {\n case n::m::k::Nil =>\n val A = readLine().split(\" \").filterNot(_==\"\").map(_.toInt)\n def f(i:Int, bag:Int):Unit = {\n if(i == n-1) println(\"YES\")\n else if(bag + A(i) < A(i+1) - k) println(\"NO\")\n else if(A(i+1) - k == 0) f(i+1, bag + A(i) - A(i+1) + k -1)\n else f(i + 1, bag + A(i) - A(i + 1) + k)\n }\n f(0,m)\n case _ => {}\n }\n }\n }\n def main(args: Array[String]): Unit = {\n PB()\n }\n}\n"}, {"source_code": "/**\n * Created by lilisun on 8/12/19.\n */\nimport scala.io.StdIn.readLine\nobject cf578 {\n\n def PA():Unit = {\n val n = readLine().toInt\n val line = readLine()\n val room = Array.fill(10)(0)\n line foreach {\n case 'L' => (0 until 10).dropWhile(i => room(i) == 1).headOption match {\n case None => {}\n case Some(i) => room(i) = 1\n }\n case 'R' => (0 until 10).reverse.dropWhile(i => room(i) == 1).headOption match {\n case None => {}\n case Some(i) => room(i) = 1\n }\n case ch => room(ch - '0') = 0\n }\n println(room.toList.mkString)\n }\n\n/*\n5\n3 0 1\n4 3 5\n3 1 2\n1 4 7\n4 10 0\n10 20 10 20\n2 5 5\n0 11\n1 9 9\n99\n */\n def PB():Unit = {\n for{_ <- 1 to readLine().toInt} {\n readLine().split(\" \").filterNot (_==\"\").map(_.toInt).toList match {\n case n::m::k::Nil =>\n val A = readLine().split(\" \").filterNot(_==\"\").map(_.toInt)\n def f(i:Int, bag:Int):Unit = {\n if(i == n-1) println(\"YES\")\n else {\n if(bag + A(i) < A(i+1) - k) println(\"NO\")\n else f(i+1, bag + A(i) - A(i+1) +k)\n }\n }\n f(0,m)\n case _ => {}\n }\n }\n }\n def main(args: Array[String]): Unit = {\n PB()\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B_1200 extends App {\n val n = readInt()\n\n 1 to n foreach { _ =>\n val Array(n, m, k) = readLine().split(\" \").map(_.toInt)\n val H = readLine().split(\" \").map(_.toInt)\n var B = m.toLong\n\n def isPossible: Boolean = {\n for (i <- 0 until n - 1) {\n val x = H(i) - H(i + 1)\n\n // take as many blocks as possible\n if (x >= 0) {\n B += Math.min(H(i), x + k)\n } else if (x < 0 && -x >= k) {\n B += Math.min(H(i), k + x)\n } else {\n B -= -x - k\n }\n if (B < 0) return false\n }\n\n true\n }\n\n println(if (isPossible) \"YES\" else \"NO\")\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B_1200 extends App {\n val n = readInt()\n\n 1 to n foreach { _ =>\n val Array(n, m, k) = readLine().split(\" \").map(_.toInt)\n val H = readLine().split(\" \").map(_.toInt)\n var B = m.toLong\n\n def isPossible: Boolean = {\n for (i <- 0 until n - 1) {\n val x = H(i) - H(i + 1)\n if (x > 0) {\n B += x + k\n } else {\n if (-x >= k) {\n B += k + x\n } else {\n B -= -x - k\n }\n }\n if (B < 0) return false\n }\n\n true\n }\n\n println(if (isPossible) \"YES\" else \"NO\")\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B_1200 extends App {\n val n = readInt()\n\n 1 to n foreach { _ =>\n val Array(n, m, k) = readLine().split(\" \").map(_.toInt)\n val H = readLine().split(\" \").map(_.toInt)\n var B = m\n\n def isPossible: Boolean = {\n for (i <- 0 until n - 1) {\n val x = H(i) - H(i + 1)\n if (x > k) {\n B += x - k\n } else {\n B += x + k\n }\n if (B < 0) return false\n }\n\n true\n }\n\n println(if (isPossible) \"YES\" else \"NO\")\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B_1200 extends App {\n val n = readInt()\n\n 1 to n foreach { _ =>\n val Array(n, m, k) = readLine().split(\" \").map(_.toInt)\n val H = readLine().split(\" \").map(_.toInt)\n var B = m\n\n def isPossible: Boolean = {\n for (i <- 0 until n - 1) {\n val x = H(i) - H(i + 1)\n if (x > 0) {\n B += x + k\n } else {\n if (-x >= k) {\n B += k + x\n } else {\n B -= -x - k\n }\n }\n if (B < 0) return false\n }\n\n true\n }\n\n println(if (isPossible) \"YES\" else \"NO\")\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B_1200 extends App {\n val n = readInt()\n\n 1 to n foreach { _ =>\n val Array(n, m, k) = readLine().split(\" \").map(_.toInt)\n val H = readLine().split(\" \").map(_.toInt)\n var B = m.toLong\n\n def isPossible: Boolean = {\n for (i <- 0 until n - 1) {\n val x = H(i) - H(i + 1)\n\n // take as many blocks as possible\n if (x > 0) {\n B += x + k\n } else {\n // we can go to i + 1, but still take as many blocks as possible\n if (-x >= k) {\n B += Math.min(H(i), k + x)\n // we need to take out the blocks from my bag\n } else {\n B -= -x - k\n }\n }\n if (B < 0) return false\n }\n\n true\n }\n\n println(if (isPossible) \"YES\" else \"NO\")\n }\n\n}\n"}], "src_uid": "3f60e740d9a3ec14223b2b1f62c52f61"} {"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n \n val n = nextInt\n val as, bs = nextInts(n)\n val cs = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n cs(bs(i) - 1) = i\n }\n\n var max = 0\n val counts = Array.fill(n)(0)\n\n for (i <- 0 until n) {\n val j = cs(as(i) - 1)\n counts((j + n - i) % n) += 1\n }\n\n out.println(counts.max)\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n// val t = readLine().toInt\n// for (i <- 1 to t) {\n val n = readLine()\n val values = readIntLine().toArray\n val valuesTwo = readIntLine().toArray\n println(matching(values, valuesTwo))\n// }\n }\n\n def matching(first: Array[Int], second: Array[Int]): Int = {\n val n = first.length\n val mapInt = Array.ofDim[Int](first.length)\n for (i <- first.indices) {\n mapInt(first(i) - 1) = i + 1\n }\n\n val differences = Array.ofDim[Int](second.length)\n for (i <- first.indices) {\n differences( (mapInt(second(i) - 1) - i - 1 + n) % n) += 1\n }\n\n var max = 0\n for (i <- differences.indices) {\n if (differences(i) > max)\n max = differences(i)\n }\n\n max\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "object ProblemC extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val shiftCount = scala.collection.mutable.HashMap[Int, Int]()\n val position = scala.collection.mutable.HashMap[Int, Int]()\n\n val n = in.nextInt()\n for (i <- 0 until n) {\n position(in.nextInt()) = i\n }\n\n for (i <- 0 until n) {\n val b = in.nextInt()\n val shift = (n + position(b) - i) % n\n\n shiftCount(shift) = shiftCount.getOrElse(shift, 0) + 1\n }\n val res: Int = shiftCount.values.max\n println(res)\n\n}"}, {"source_code": "object C extends App {\n import scala.collection.mutable\n\n val n = scala.io.StdIn.readInt()\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val bn = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val table = Array.fill(n)(0)\n\n (0 until n).foreach(i => table(an(i) - 1) += i)\n\n var offset = mutable.Map.empty[Int, Int]\n (0 until n).foreach { i =>\n val k = (n + (table(bn(i) - 1) - i) % n) % n\n offset(k) = offset.getOrElseUpdate(k, 0) + 1\n }\n\n val ans = offset.maxBy(_._2)._2\n\n println(ans)\n}\n"}, {"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n val n = nextInt\n val as, bs = nextInts(n)\n val cs = Array.ofDim[Int](n)\n\n var i = 0\n while (i < n) {\n cs(bs(i) - 1) = i\n i += 1\n }\n\n var max = 0\n val counts = Array.fill(n)(0)\n\n i = 0\n while (i < n) {\n val j = cs(as(i) - 1)\n val k = (j + n - i) % n\n counts(k) += 1\n if (counts(k) > max) {\n max = counts(k)\n }\n i += 1\n }\n\n out.println(max)\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n// val t = readLine().toInt\n// for (i <- 1 to t) {\n val n = readLine()\n val values = readIntLine().toArray\n val valuesTwo = readIntLine().toArray\n println(matching(values, valuesTwo))\n// }\n }\n\n def matching(first: Array[Int], second: Array[Int]) = {\n val n = first.length\n val mapInt = Array.ofDim[Int](first.length)\n for (i <- first.indices) {\n mapInt(first(i) - 1) = i + 1\n }\n\n val differences = Array.ofDim[Int](second.length)\n for (i <- first.indices) {\n differences(i) = (mapInt(i) - i - 1 + n) % n\n }\n\n differences.groupBy(i => i).map(tup => tup._2.length).max\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n// val t = readLine().toInt\n// for (i <- 1 to t) {\n val n = readLine()\n val values = readIntLine().toArray\n val valuesTwo = readIntLine().toArray\n println(matching(values, valuesTwo))\n// }\n }\n\n def matching(first: Array[Int], second: Array[Int]) = {\n val n = first.length\n val mapInt = Array.ofDim[Int](first.length)\n for (i <- first.indices) {\n mapInt(first(i) - 1) = i + 1\n }\n\n val differences = Array.ofDim[Int](second.length)\n for (i <- first.indices) {\n differences(i) = (mapInt(i) - i + n) % n\n }\n\n differences.groupBy(i => i).map(tup => tup._2.length).max\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n// val t = readLine().toInt\n// for (i <- 1 to t) {\n val n = readLine()\n val values = readIntLine().toArray\n val valuesTwo = readIntLine().toArray\n println(matching(values, valuesTwo))\n// }\n }\n\n def matching(first: Array[Int], second: Array[Int]): Int = {\n val n = first.length\n val mapInt = Array.ofDim[Int](first.length)\n for (i <- first.indices) {\n mapInt(first(i) - 1) = i + 1\n }\n\n val differences = Array.ofDim[Int](second.length)\n for (i <- first.indices) {\n differences(i) = (second(mapInt(i) - 1) - i - 1 + n) % n\n }\n\n differences.groupBy(i => i).map(tup => tup._2.length).max\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n// val t = readLine().toInt\n// for (i <- 1 to t) {\n val n = readLine()\n val values = readIntLine().toArray\n val valuesTwo = readIntLine().toArray\n println(matching(values, valuesTwo))\n// }\n }\n\n def matching(first: Array[Int], second: Array[Int]): Int = {\n val n = first.length\n val mapInt = Array.ofDim[Int](first.length)\n for (i <- first.indices) {\n mapInt(first(i) - 1) = i + 1\n }\n\n val differences = Array.ofDim[Int](second.length)\n for (i <- first.indices) {\n differences(i) = (mapInt(second(i) - 1) - i - 1 + n) % n\n }\n\n var max = 0\n for (i <- differences.indices) {\n if (differences(i) > max)\n max = differences(i)\n }\n\n max\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}], "src_uid": "eb1bb862dc2b0094383192f6998891c5"} {"source_code": "import scala.collection._\n\nobject A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(a, b, _n) = readLongs(3)\n val n = _n.toInt\n\n val res = Array.ofDim[Long](n)\n \n def can(l: Long, r: Long, t: Long, m: Long): Boolean = {\n val lh = a + (l - 1) * b\n val rh = a + (r - 1) * b\n val dh = rh - lh\n val total = lh * (r - l + 1) + dh * (r - l + 1) / 2\n // println(l, r, lh, rh, dh, total)\n (rh <= t && total <= m * t)\n }\n \n for (step <- 0 until n) {\n val Array(l, t, m) = readLongs(3)\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) hi\n else {\n val mid = (low + hi) >>> 1\n if (!can(l, mid, t, m)) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val ans = binSearch(0, 1000000)\n \n res(step) = if (ans < l) -1 else ans\n }\n \n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\"\\n\"))\n\n Console.flush\n}\n", "positive_code": [{"source_code": "object C535 extends App {\n import java.util.Scanner\n\n type Input = Problem\n type Output = List[Option[Long]]\n\n case class Query(l: Int, t: Int, m: Int) {\n val total: Long = t.toLong * m\n }\n case class Problem(a: Long, b: Long, queries: List[Query]) {\n def karaf(i: Long): Long = a + (i-1)*b\n def total(i: Long): Long = a*i + b*i*(i-1)/2\n def sum(start: Long, end: Long) = total(end) - total(start - 1)\n def apply(q: Query)(i: Long) = karaf(i) <= q.t && sum(q.l, i) <= q.total\n def solve(q: Query) = binarySearch(this(q), q.l, q.total)\n }\n\n def read(scanner: Scanner): Input = {\n import scanner._\n Problem(nextLong, nextLong, List.fill(nextInt)(Query(nextInt, nextInt, nextInt)))\n }\n\n def solve(problem: Input): Output = problem.queries map problem.solve\n\n def binarySearch(f: Long => Boolean, min: Long, max: Long): Option[Long] = {\n val mid = (min + max)/2\n val ok = f(mid)\n if (min < mid && mid < max) {\n if (ok) binarySearch(f, mid, max) else binarySearch(f, min, mid)\n } else {\n if (ok) Some(mid) else None\n }\n }\n\n def format(result: Output): String = result map {_ getOrElse -1} mkString \"\\n\"\n\n def apply(input: String): String = apply(new Scanner(input))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n}\n"}, {"source_code": "object C535 extends App {\n import java.util.Scanner\n\n type Input = Problem\n type Output = List[Option[Long]]\n\n case class Query(l: Int, t: Int, m: Int) {\n val total: Long = t.toLong * m\n }\n case class Problem(a: Long, b: Long, queries: List[Query]) {\n def karaf(i: Long): Long = a + (i-1)*b\n def total(i: Long): Long = a*i + b*i*(i-1)/2\n def canBite(q: Query)(i: Long) = karaf(i) <= q.t && (total(i) - total(q.l-1)) <= q.total\n }\n\n def read(scanner: Scanner): Input = {\n import scanner._\n Problem(nextLong, nextLong, List.fill(nextInt)(Query(nextInt, nextInt, nextInt)))\n }\n\n def solve(problem: Input): Output = problem.queries map {query =>\n binarySearch(problem.canBite(query), query.l, query.total)\n }\n\n def binarySearch(f: Long => Boolean, min: Long, max: Long): Option[Long] = {\n val mid = (min + max)/2\n val ok = f(mid)\n if (min < mid && mid < max) {\n if(ok) binarySearch(f, mid, max) else binarySearch(f, min, mid)\n } else {\n if (ok) Some(mid) else None\n }\n }\n\n def format(result: Output): String = {\n result map {_ getOrElse -1} mkString \"\\n\"\n }\n\n def apply(input: String): String = apply(new Scanner(input))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n}\n"}, {"source_code": "object C535 extends App {\n import java.util.Scanner\n\n type Input = Problem\n type Output = List[Option[Long]]\n\n case class Query(l: Int, t: Int, m: Int) {\n val total: Long = t.toLong * m\n }\n case class Problem(a: Long, b: Long, queries: List[Query]) {\n def karaf(i: Long): Long = a + (i-1)*b\n def total(i: Long): Long = a*i + b*i*(i-1)/2\n def apply(q: Query)(i: Long) = karaf(i) <= q.t && (total(i) - total(q.l-1)) <= q.total\n def solve(q: Query) = binarySearch(this(q), q.l, q.total)\n }\n\n def read(scanner: Scanner): Input = {\n import scanner._\n Problem(nextLong, nextLong, List.fill(nextInt)(Query(nextInt, nextInt, nextInt)))\n }\n\n def solve(problem: Input): Output = problem.queries map problem.solve\n\n def binarySearch(f: Long => Boolean, min: Long, max: Long): Option[Long] = {\n val mid = (min + max)/2\n val ok = f(mid)\n if (min < mid && mid < max) {\n if (ok) binarySearch(f, mid, max) else binarySearch(f, min, mid)\n } else {\n if (ok) Some(mid) else None\n }\n }\n\n def format(result: Output): String = result map {_ getOrElse -1} mkString \"\\n\"\n\n def apply(input: String): String = apply(new Scanner(input))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n}\n"}], "negative_code": [], "src_uid": "89c97b6c302bbb51e9d5328c680a7ea7"} {"source_code": "object E {\n import InOut._\n \n def main(args: Array[String]): Unit = {\n \n val n = nextInt\n val as = nextLongs(n)\n\n var max = 0L\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val x = as(i) | as(j)\n if (x > max) max = x\n for (k <- 0 until n) {\n val y = x | as(k)\n if (y > max) max = y\n }\n }\n }\n\n out.println(max)\n\n out.flush()\n }\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "object E extends App {\n val n = scala.io.StdIn.readInt()\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n val ans =\n if (n <= 3) an.reduce(_ | _)\n else {\n var t = 0L\n\n for {\n i <- 0 until n\n j <- i until n\n a = an(i) | an(j)\n k <- j until n\n b = a | an(k)\n } t = b max t\n\n t\n }\n\n println(ans)\n}\n"}, {"source_code": "object E {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n val n = nextInt\n val as = nextLongs(n)\n\n var max = 0L\n var i = 0\n while (i < n) {\n var j = i\n while (j < n) {\n val x = as(i) | as(j)\n var k = j\n while (k < n) {\n val y = x | as(k)\n if (y > max) max = y\n k += 1\n }\n j += 1\n }\n i += 1\n }\n\n out.println(max)\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "object E {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n val n = nextInt\n val as = nextLongs(n)\n\n var max = 0L\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val x = as(i) | as(j)\n if (x > max) max = x\n }\n }\n\n out.println(max)\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "src_uid": "08345b5a41424021e52e47cd0bd03d63"} {"source_code": "//package codeforces.contest1213\n\nimport scala.collection.immutable.TreeSet\n\nobject BadPrices {\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt()) {\n val n = io.StdIn.readInt()\n\n println {\n val indexedSeq = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n (0 to n - 2)\n .foldRight((0, collection.mutable.TreeSet(indexedSeq.last))) {\n case (i, (res, set)) =>\n val v = indexedSeq(i)\n val minFound = set.until(v).nonEmpty\n\n (if (minFound) res + 1 else res, set += v)\n }\n ._1\n }\n }\n }\n\n}\n", "positive_code": [{"source_code": "object Main extends App {\n val t = readInt()\n for (i <- 0 to t-1) {\n var i = readInt() - 2\n val a = readLine().split(\" \").map(_.toInt)\n var rs = 0\n var temp = a(i+1)\n while(i>=0){\n if(a(i) > temp) \n rs += 1\n else\n temp = a(i)\n i-=1\n }\n println(rs)\n }\n}"}, {"source_code": "import scala.io.StdIn\nimport scala.util.control.Breaks\n\nobject Main extends App {\n\n val n = StdIn.readInt()\n\n for (i <- 0 to n-1) {\n val k = StdIn.readInt()\n val st: Array[String] = StdIn.readLine().split(\" \")\n val arr: Array[Int] = st.map(_.toInt)\n\n var res: Int = 0\n\n //O(n^2) - TL\n// for (i <- 0 to k-1) {\n// var good: Boolean = true\n// Breaks.breakable {\n// for (j <- i + 1 to k - 1) {\n// if (arr(j) < arr(i)) {\n// good = false\n// if (!good) Breaks.break\n// }\n// }\n// }\n// if (!good) {\n// res += 1\n// }\n// }\n\n\n //O(n)\n var min = arr(arr.size-1)\n for (i <- k-1 to 0 by -1) {\n if (arr(i) > min) {\n res += 1\n }\n min = Math.min(arr(i), min)\n }\n\n println(res)\n }\n\n}"}, {"source_code": "//package codeforces.contest1213\n\nimport scala.collection.immutable.TreeSet\n\nobject BadPrices {\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt()) {\n val n = io.StdIn.readInt()\n\n println {\n val indexedSeq = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n (0 to n - 2)\n .foldRight((0, TreeSet(indexedSeq.last))) {\n case (i, (res, set)) =>\n val v = indexedSeq(i)\n val minFound = set.until(v).nonEmpty\n\n (if (minFound) res + 1 else res, set + v)\n }\n ._1\n }\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "object Main extends App {\n val t = readInt()\n for (i <- 0 to t-1) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n var rs = 0\n var temp = a(0)\n for(i <- 1 to n-1) {\n if(a(i) > temp) rs += 1\n temp = a(i)\n }\n println(rs)\n }\n}"}], "src_uid": "09faf19627d2ff00c3821d4bc2644b63"} {"source_code": "import scala.util.control.Breaks._\nimport scala.util.control.Breaks\n\n//Julian_Miranda\n\nobject LittleElephantAndBits {\n def main(args: Array[String]): Unit = {\n var a = readLine\n var pos = -1\n\n val loop = new Breaks\n loop.breakable {\n for (i <- 0 to a.length() - 1) {\n breakable {\n if (a.charAt(i) == '0') {\n pos = i\n loop.break\n }\n }\n }\n }\n\n if (pos == -1) {\n for (i <- 1 to a.length()) {\n if (i < a.length()) {\n print(a.charAt(i))\n }\n }\n } else {\n for (i <- 0 to a.length() - 1) {\n breakable {\n if (i == pos) break;\n else {\n print(a.charAt(i))\n }\n }\n }\n }\n println()\n }\n}", "positive_code": [{"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-29.\n */\nobject A258 {\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val a = sc.next()\n\n if (a.indexOf(\"1\") != -1) {\n val startWith1 = a.substring(a.indexOf(\"1\"))\n\n if (startWith1.indexOf(\"0\") != -1) {\n val pre = startWith1.substring(0, startWith1.indexOf(\"0\"))\n val post = startWith1.substring(startWith1.indexOf(\"0\") + 1)\n println(pre + post)\n } else {\n println(startWith1.substring(1))\n }\n } else {\n println(a.substring(1))\n }\n }\n}\n"}, {"source_code": "object Contest extends App {\n val s = readLine()\n val p = s.indexOf('0')\n val ans = if (p == -1) s.substring(1) else s.substring(0, p) + s.substring(p+1)\n println(ans)\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _258A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val s = next\n val pos = s.indexWhere(ch => ch == '0')\n if (pos != -1) println(s.take(pos) + s.drop(pos + 1))\n else println(s.drop(1))\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val nStr = str.replaceFirst(\"0\", \"\")\n if (str.length == nStr.length)\n println(str.tail)\n else\n println(nStr)\n}"}, {"source_code": "object Main {\n\n def main(args: Array[String]): Unit = {\n \n def fixNumber(n: String): String = {\n val index = n.indexOf(\"0\")\n if (index >= 0)\n n.substring(0, index) + n.substring(index+1)\n else\n n.substring(1) \n }\n \n print(fixNumber(readLine))\n }\n\n}"}], "negative_code": [{"source_code": "import scala.util.control.Breaks._\n\n//Julian_Miranda\n\nobject LittleElephantAndBits {\n def main(args: Array[String]): Unit = {\n var a = readLine\n var pos = -1\n\n for (i <- 0 to a.length()-1) {\n breakable {\n if (a.charAt(i) == '0') {\n pos = i\n break;\n }\n }\n }\n\n if (pos == -1) {\n for (i <- 1 to a.length()) {\n if(i < a.length()){\n print(a.charAt(i))\n }\n }\n } else {\n for (i <- 0 to a.length()-1) {\n breakable {\n if (i == pos)break;\n else{\n print(a.charAt(i))\n }\n }\n }\n }\n println()\n }\n}"}], "src_uid": "133eaf241bb1557ba9a3f59c733d34bf"} {"source_code": "object F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n val Array(n) = readInts(1)\n val as = readInts(n)\n\n val deltas = Array.fill(n){ 0 }\n\n for (i <- 1 until n) {\n var k = 1\n while (k < n) {\n val parent = (i - 1) / k\n val nextK = if (parent == 0) n else (i - 1) / parent + 1\n if (as(i) < as(parent)) {\n deltas(k) += 1\n if (nextK < n) deltas(nextK) -= 1\n }\n k = nextK\n }\n }\n\n val res = deltas.scan(0){ _ + _ }.drop(2)\n\n println(res.mkString(\" \"))\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.io.Source\n\nobject F extends App {\n object In {\n private val lines = Source.stdin.getLines()\n private var tokenizer: StringTokenizer = new StringTokenizer(lines.next())\n\n def next(): String = {\n if (tokenizer.hasMoreTokens) {\n tokenizer.nextToken()\n } else {\n tokenizer = new StringTokenizer(lines.next())\n next()\n }\n }\n\n def nextInt() = next().toInt\n def nextDouble() = next().toDouble\n }\n\n val emptyIntArray = Array.empty[Int]\n\n class MinTree(d0: Array[Int]) {\n val offset = 1 << (32 - Integer.numberOfLeadingZeros(d0.length))\n val data = Array.fill(2 * offset)(emptyIntArray)\n for (i <- 0 until d0.length) {\n data(i + offset) = Array.ofDim[Int](1)\n data(i + offset)(0) = d0(i)\n }\n for (i <- offset - 1 to 1 by -1) {\n data(i) = merge(data(2 * i), data(2 * i + 1))\n }\n\n def merge(a: Array[Int], b: Array[Int]): Array[Int] = {\n val rv = Array.ofDim[Int](a.length + b.length)\n var ai, bi, ci = 0\n while (ai < a.length && bi < b.length) {\n if (a(ai) < b(bi)) {\n rv(ci) = a(ai)\n ai += 1\n } else {\n rv(ci) = b(bi)\n bi += 1\n }\n ci += 1\n }\n while (ai < a.length) {\n rv(ci) = a(ai)\n ci += 1\n ai += 1\n }\n while (bi < b.length) {\n rv(ci) = b(bi)\n ci += 1\n bi += 1\n }\n rv\n }\n\n def countLess(a: Array[Int], v: Int): Int = {\n if (a.length == 0 || a(0) >= v) {\n 0\n } else if (a(a.length - 1) < v) {\n a.length\n } else {\n def bs(l: Int, r: Int): Int = {\n if (r - l == 1) r else {\n val m = (l + r) >>> 1\n if (a(m) < v) {\n bs(m, r)\n } else {\n bs(l, m)\n }\n }\n }\n bs(0, a.length)\n }\n }\n\n def count(l: Int, r: Int, v: Int): Int = {\n var ll = l + offset\n var rr = r + offset\n var rv = 0\n while (ll <= rr) {\n if ((ll & 1) == 1) {\n rv += countLess(data(ll), v)\n }\n if ((rr & 1) == 0) {\n rv += countLess(data(rr), v)\n }\n ll = (ll + 1) >>> 1\n rr = (rr - 1) >>> 1\n }\n rv\n }\n }\n\n val n = In.nextInt()\n val d = Array.fill(n)(In.nextInt())\n\n val t = new MinTree(d)\n for (k <- 1 until n) {\n var count = 0\n var i = 0\n while (k * i + 1 < n) {\n count += t.count(k * i + 1, math.min(n - 1, k * (i + 1)), d(i))\n i += 1\n }\n print(count + \" \")\n }\n println()\n}\n"}, {"source_code": "object F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n val Array(n) = readInts(1)\n val as = readInts(n)\n\n val deltas = Array.fill(n){ 0 }\n\n for (i <- 1 until n) {\n var k = 1\n var violating = false\n val a = as(i)\n while (k < n) {\n val parent = (i - 1) / k\n if (a < as(parent)) {\n if (!violating) {\n deltas(k) += 1\n violating = true\n }\n } else { \n if (violating) {\n deltas(k) -= 1\n violating = false\n }\n }\n k = if (parent == 0) n else (i - 1) / parent + 1\n }\n }\n\n val res = deltas.scan(0){ _ + _ }.drop(2)\n\n println(res.mkString(\" \"))\n}\n"}], "negative_code": [{"source_code": "object F extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(n: Int): Array[Int] = {\n Array.fill(n) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n val Array(n) = readInts(1)\n val as = readInts(n)\n\n val bit = BIT(n)\n \n for (i <- 1 until n) {\n var nextK = 1\n var violating = false\n while (nextK < n) {\n val k = nextK\n val parent = (i - 1) / k\n if (as(i) < as(parent)) {\n if (!violating) {\n BIT.update(bit, k, 1)\n violating = true\n }\n } else { \n if (violating) {\n BIT.update(bit, k, -1)\n violating = false\n }\n }\n nextK = if (parent == 0) n else (i - 1) / parent + 1\n println(i, k, nextK)\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n \n val res = Array.tabulate(n - 1){ i => BIT.query(bit, i + 1) }\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection._\n\nobject F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n case class SegTree(as: Array[Int]) {\n\n val n = as.length\n val tMin = Array.ofDim[Int](4 * Integer.highestOneBit(n))\n val tMax = Array.ofDim[Int](4 * Integer.highestOneBit(n))\n build(1, 0, n - 1)\n\n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) tMin(v) = as(tl)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n build(v2, tl, tm)\n build(v2 + 1, tm + 1, tr)\n tMin(v) = Math.min(tMin(v2), tMin(v2 + 1))\n tMax(v) = Math.max(tMax(v2), tMax(v2 + 1))\n }\n }\n\n def query(l: Int, r: Int, p: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n val res = if (l > r) 0\n else if (l == tl && r == tr) {\n if (tMin(v) >= p) 0\n else if (tMax(v) < p) r - l + 1\n else -1\n } else -1\n\n if (res >= 0) res\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n query(l, Math.min(r, tm), p, v2, tl, tm) +\n query(Math.max(l, tm + 1), r, p, v2 + 1, tm + 1, tr)\n }\n }\n\n }\n val Array(n) = readInts(1)\n val as = readInts(n)\n\n val segTree = SegTree(as)\n\n val res = Array.ofDim[Int](n - 1)\n\n for (k <- 0 until n - 1) {\n var cnt = 0\n var v = 0\n var r = 0\n while (r <= n && v < n) {\n val l = r + 1 // k * v + 1\n r = (l + k) min (n - 1)\n //println(l, r)\n cnt += segTree.query(l, r, as(v))\n v += 1\n }\n res(k) = cnt\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection._\n\nobject F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n case class SegTree(as: Array[Int]) {\n\n val n = as.length\n val tMin = Array.ofDim[Int](4 * Integer.highestOneBit(n))\n val tMax = Array.ofDim[Int](4 * Integer.highestOneBit(n))\n build(1, 0, n - 1)\n\n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) tMin(v) = as(tl)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n build(v2, tl, tm)\n build(v2 + 1, tm + 1, tr)\n tMin(v) = Math.min(tMin(v2), tMin(v2 + 1))\n tMax(v) = Math.max(tMax(v2), tMax(v2 + 1))\n }\n }\n\n def query(l: Int, r: Int, p: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Long = {\n val res = if (l > r) 0\n else if (l == tl && r == tr) {\n if (tMin(v) >= p) 0\n else if (tMax(v) < p) r - l + 1\n else -1\n } else -1\n\n if (res >= 0) res\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n query(l, Math.min(r, tm), p, v2, tl, tm) +\n query(Math.max(l, tm + 1), r, p, v2 + 1, tm + 1, tr)\n }\n }\n\n }\n val Array(n) = readInts(1)\n val as = readInts(n)\n\n val segTree = SegTree(as)\n\n val res = Array.ofDim[Long](n - 1)\n\n for (k <- 0 until n - 1) {\n var cnt = 0L\n var v = 0\n var r = 0\n while (r < n - 1) {\n val l = r + 1 // k * v + 1\n r = (l + k) min (n - 1)\n //println(l, r)\n cnt += segTree.query(l, r, as(v))\n v += 1\n }\n res(k) = cnt\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}], "src_uid": "377433947c60edcb55832d4ef2597f90"} {"source_code": "import scala.collection.mutable\n//package codeforces\n\nobject MilitaryProblem {\n\n // private def computeSizes(n: Int, childrenMap: Map[Int, Array[Int]], parentArray: Array[Int]): Array[Int] = {\n // val result = Array.fill(n + 1)(1)\n //\n // def compute(set: Set[Int]): Unit = {\n // set.foreach(node => result(parentArray(node)) += result(node))\n // if (!(set.size == 1 && set.contains(0))) compute(set map parentArray)\n // }\n //\n // compute((1 to n).filter(node => !childrenMap.contains(node)).toSet) // starting with the leaves\n // result\n // }\n\n def main(args: Array[String]): Unit = {\n val Array(n, q) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n // val parentArray: Array[Int] = Array(0, 0) ++ io.StdIn.readLine.split(\" \").map(_.toInt)\n // var childrenMap: Map[Int, Array[Int]] = parentArray.zipWithIndex.groupBy(_._1).map { case (p, elems) => (p, elems.unzip._2) }\n\n\n val parentArray: Array[Int] = io.StdIn.readLine.split(\" \").map(_.toInt)\n val children: Array[mutable.Queue[Int]] = Array.fill(n + 1)(mutable.Queue[Int]())\n\n var i: Int = 0\n while (i < parentArray.length) {\n children(parentArray(i)).enqueue(i + 2)\n i += 1\n }\n\n\n //val subtreeCount: Array[Int] = computeSizes(n, childrenMap, parentArray)\n\n //val childrenMapWithPrefixSum = childrenMap.map { case (node, children) => (node, children.scanLeft(1) { case (res, elem) => res + subtreeCount(elem) }) }\n\n val sortedSeq, startingPositionInSortedSeq, endingPositionInSortedSeq = new Array[Int](n + 1)\n i = 0\n dfs(1)\n\n def dfs(node: Int): Unit = {\n sortedSeq(i) = node\n startingPositionInSortedSeq(node) = i\n i += 1\n children(node).foreach(dfs)\n endingPositionInSortedSeq(node) = i - 1\n }\n\n\n i = 0\n while (i < q) {\n val Array(u, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val startingPos = startingPositionInSortedSeq(u)\n val endingPos = endingPositionInSortedSeq(u)\n\n if (endingPos - startingPos + 1 < k) println(-1)\n else println(sortedSeq(startingPos + k - 1))\n\n\n i += 1\n //println(computeQueryResult(u, k))\n }\n\n // def computeQueryResult(u: Int, k: Int): Int = {\n // if (k > subtreeCount(u)) -1\n // else if (k == 1) u\n // else {\n // val childPrefixSum: Array[Int] = childrenMapWithPrefixSum(u)\n // val i = childPrefixSum.search(k).insertionPoint // optimized binary search\n //\n // val newU = childrenMap(u)(i - 1)\n // val newK = k - childPrefixSum(i - 1)\n // computeQueryResult(newU, newK)\n // }\n // }\n }\n}\n", "positive_code": [{"source_code": "//package codeforces\n\nimport scala.collection.Searching._\nimport scala.collection.mutable\n\n/*\n\nlink- http://codeforces.com/contest/1006/problem/E\n\nPre-order traversal sequence, find the kth element starting from node u\n\n */\nobject MilitaryProblem {\n\n def main(args: Array[String]): Unit = {\n val Array(n, q) = io.StdIn.readLine.split(\" \").map(_.toInt)\n val parentArray: Array[Int] = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val children: Array[mutable.Queue[Int]] = Array.fill(n + 1)(mutable.Queue[Int]())\n\n // var i: Int = 0\n // while (i < parentArray.length) {\n // children(parentArray(i)).enqueue(i + 2)\n // i += 1\n // }\n\n computeChildrenMapping(0)\n\n def computeChildrenMapping(idx: Int): Unit = {\n if (idx < parentArray.length) {\n children(parentArray(idx)).enqueue(idx + 2)\n computeChildrenMapping(idx + 1)\n }\n }\n\n val sortedSeq, startingPositionInSortedSeq, endingPositionInSortedSeq = new Array[Int](n + 1)\n var i = 0\n dfs(1)\n\n def dfs(node: Int): Unit = {\n sortedSeq(i) = node\n startingPositionInSortedSeq(node) = i\n i += 1\n children(node).foreach(dfs)\n endingPositionInSortedSeq(node) = i - 1\n }\n\n // i = 0\n // while (i < q) {\n // val Array(u, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n //\n // val startingPos = startingPositionInSortedSeq(u)\n // val endingPos = endingPositionInSortedSeq(u)\n //\n // if (endingPos - startingPos + 1 < k) println(-1)\n // else println(sortedSeq(startingPos + k - 1))\n //\n // i += 1\n // }\n\n solveQueries(0)\n\n def solveQueries(idx: Int): Unit = {\n if (idx < q) {\n val Array(u, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val startingPos = startingPositionInSortedSeq(u)\n val endingPos = endingPositionInSortedSeq(u)\n\n if (endingPos - startingPos + 1 < k) println(-1)\n else println(sortedSeq(startingPos + k - 1))\n\n solveQueries(idx + 1)\n }\n }\n\n }\n\n\n // Another Solution although inefficient\n\n def usingReverseLevelOrderTraversal(args: Array[String]): Unit = {\n val Array(n, q) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val parentArray: Array[Int] = Array(0, 0) ++ io.StdIn.readLine.split(\" \").map(_.toInt)\n var childrenMap: Map[Int, Array[Int]] = parentArray.zipWithIndex.groupBy(_._1).map { case (p, elems) => (p, elems.unzip._2) }\n\n val subtreeSizeCount: Array[Int] = { // reverse level order traversal to compute sizes of each subtree\n val result = Array.fill(n + 1)(1)\n\n def compute(set: Set[Int]): Unit = {\n set.foreach(node => result(parentArray(node)) += result(node))\n if (!(set.size == 1 && set.contains(0))) compute(set map parentArray)\n }\n\n compute((1 to n).filter(node => !childrenMap.contains(node)).toSet) // starting with the leaves\n result\n }\n\n val childrenMapWithPrefixSum = childrenMap.map { case (node, children) => (node, children.scanLeft(1) { case (res, elem) => res + subtreeSizeCount(elem) }) }\n\n var i = 0\n while (i < q) {\n val Array(u, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n println(computeQueryResult(u, k))\n i += 1\n }\n\n def computeQueryResult(u: Int, k: Int): Int = {\n if (k > subtreeSizeCount(u)) -1\n else if (k == 1) u\n else {\n val childPrefixSum: Array[Int] = childrenMapWithPrefixSum(u)\n val i = childPrefixSum.search(k).insertionPoint // optimized with binary search\n\n val newU = childrenMap(u)(i - 1)\n val newK = k - childPrefixSum(i - 1)\n computeQueryResult(newU, newK)\n }\n }\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, Q = ni()\n val from, to = Array.ofDim[Int](N - 1)\n REP(N -1) { i =>\n from(i) = ni() - 1\n to(i) = i + 1\n }\n\n val g = packDGraph(N, from, to)\n val (tour, _) = traceDfs(g)\n val pos = Array.ofDim[Int](N)\n REP(N) { i =>\n pos(tour(i)) = i\n }\n val childCnt = Array.ofDim[Int](N)\n REP_r(N) { v =>\n REP(g(v).length) { j =>\n val u = g(v)(j)\n childCnt(v) += childCnt(u) + 1\n }\n }\n\n\n REP(Q) { _ =>\n val u, k = ni() - 1\n if (k > childCnt(u)) out.println(-1)\n else {\n out.println(tour(pos(u) + k) + 1)\n }\n }\n }\n\n def traceDfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int]) = {\n val n = g.length\n val stack = mutable.Stack[Int]()\n val ix = Array.ofDim[Int](n)\n val tour = Array.ofDim[Int](n)\n val parent = Array.ofDim[Int](n)\n parent(rt) = -1\n var p = 0\n\n tour(p) = rt\n p += 1\n stack.push(rt)\n\n while(stack.nonEmpty) {\n val v = stack.top\n val es = g(v)\n if (ix(v) == es.length) stack.pop()\n else {\n val u = es(ix(v))\n if (u != parent(v)) {\n parent(u) = v\n stack.push(u)\n tour(p) = u\n p += 1\n }\n ix(v) += 1\n }\n }\n\n (tour, parent)\n }\n\n def packDGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n REP(m)(i => p(from(i)) += 1)\n REP(n)(i => t(i) = new Array(p(i)))\n REP_r(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n }\n t\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [], "src_uid": "4dffa25857c7719a43817e0ad01ef759"} {"source_code": "object D{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val (n,m)=(nextInt,nextInt)\n val edges=for(i<-0 until m) yield(i,nextInt,nextInt)\n val edgesSorted=scala.util.Sorting.stableSort(edges, (e1: Tuple3[Int, Int,Int], e2: Tuple3[Int, Int,Int]) => if(e1._2 < e2._2){\n true\n }\n else if(e1._2>e2._2){\n false\n }else{\n e1._3 > e2._3\n })\n \n val nextNode=Array.ofDim[Int](n)\n var lastNode=0\n val ans=Array.ofDim[(Int,Int)](m)\n nextNode(0)=2\n for(i<-0 until m){\n val (idx,_,isTree)=edgesSorted(i)\n if(isTree==1){\n ans(idx)=(lastNode+1,lastNode+2)\n nextNode(lastNode)=lastNode+2\n lastNode+=1\n }else{\n var has=false\n breakable{\n for(j<-0 until lastNode){\n if(nextNode(j)<=lastNode){\n ans(idx)=(j+1,nextNode(j)+1)\n nextNode(j)+=1\n has=true\n break\n }\n }\n }\n if(has==false){\n out.println(-1)\n out.flush()\n out.close()\n return\n }\n }\n }\n ans.foreach(a=>println(a._1+\" \"+a._2))\n //code ends here\n out.flush\n out.close\n }\n}\n\n", "positive_code": [{"source_code": "import java.io._\nimport java.util._\nimport scala.collection.JavaConversions._\n\n/**\n * Created by antonkov on 9/17/15.\n */\nobject B {\n class Edge(val w: Int, val inMst: Boolean, val num: Int) {\n override def toString = s\"Edge($w, $inMst, $num)\"\n }\n\n def solve(in: Scanner, out: PrintWriter): Unit = {\n val n, m = in.nextInt()\n var edges = new Array[Edge](m)\n for (i <- 0 until m) {\n edges(i) = new Edge(in.nextInt(), in.nextInt() == 1, i)\n }\n edges = edges.sortWith((e1, e2) => if (e1.w != e2.w) e1.w < e2.w else e2.inMst < e1.inMst )\n val q = new ArrayDeque[(Int, Int)]()\n var v = 1\n val res = new Array[(Int, Int)](m)\n for (e <- edges) {\n if (e.inMst) {\n v += 1\n def addEdges {\n for (u <- 1 until v) {\n if (q.size() >= m)\n return\n q.add((u, v))\n }\n }\n addEdges\n res(e.num) = q.pollLast()\n } else {\n if (q.isEmpty) {\n out.println(-1)\n return\n }\n res(e.num) = q.pollFirst()\n }\n }\n for ((u, v) <- res) {\n out.println(u + \" \" + v)\n }\n }\n\n def main (args: Array[String]): Unit = {\n val in = new Scanner()\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n out.close()\n }\n\n class Scanner {\n val br = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(br.readLine())\n\n def next(): String = if (st.hasMoreTokens) st.nextToken() else {\n st = new StringTokenizer(br.readLine())\n next()\n }\n\n def nextInt() = next().toInt\n def nextLong() = next().toLong\n def nextDouble() = next().toDouble\n }\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util._\nimport scala.collection.JavaConversions._\n\n/**\n * Created by antonkov on 9/17/15.\n */\nobject B {\n class Edge(val w: Int, val inMst: Boolean, val num: Int)\n\n def solve(in: Scanner, out: PrintWriter): Unit = {\n val n, m = in.nextInt()\n val edges = new Array[Edge](m)\n for (i <- 0 until m) {\n edges(i) = new Edge(in.nextInt(), in.nextInt() == 1, i)\n }\n edges.sortWith((e1, e2) => e1.w < e2.w)\n val q = new ArrayDeque[(Int, Int)]()\n var v = 1\n val res = new Array[(Int, Int)](m)\n for (e <- edges) {\n if (e.inMst) {\n v += 1\n for (u <- 1 until v) {\n q.add((u, v))\n }\n res(e.num) = q.pollLast()\n } else {\n if (q.isEmpty) {\n out.println(-1)\n return\n }\n res(e.num) = q.pollFirst()\n }\n }\n for ((u, v) <- res) {\n out.println(u + \" \" + v)\n }\n }\n\n def main (args: Array[String]): Unit = {\n val in = new Scanner()\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n out.close()\n }\n\n class Scanner {\n val br = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(br.readLine())\n\n def next(): String = if (st.hasMoreTokens) st.nextToken() else {\n st = new StringTokenizer(br.readLine())\n next()\n }\n\n def nextInt() = next().toInt\n def nextLong() = next().toLong\n def nextDouble() = next().toDouble\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\nimport scala.collection.JavaConversions._\n\n/**\n * Created by antonkov on 9/17/15.\n */\nobject B {\n class Edge(val w: Int, val inMst: Boolean, val num: Int) {\n override def toString = s\"Edge($w, $inMst, $num)\"\n }\n\n def solve(in: Scanner, out: PrintWriter): Unit = {\n val n, m = in.nextInt()\n var edges = new Array[Edge](m)\n for (i <- 0 until m) {\n edges(i) = new Edge(in.nextInt(), in.nextInt() == 1, i)\n }\n edges = edges.sortWith((e1, e2) => if (e1.w != e2.w) e1.w < e2.w else e2.inMst < e1.inMst )\n val q = new ArrayDeque[(Int, Int)]()\n var v = 1\n val res = new Array[(Int, Int)](m)\n for (e <- edges) {\n if (e.inMst) {\n v += 1\n def addEdges {\n for (u <- 1 until v) {\n if (q.size() >= n)\n return\n q.add((u, v))\n }\n }\n addEdges\n res(e.num) = q.pollLast()\n } else {\n if (q.isEmpty) {\n out.println(-1)\n return\n }\n res(e.num) = q.pollFirst()\n }\n }\n for ((u, v) <- res) {\n out.println(u + \" \" + v)\n }\n }\n\n def main (args: Array[String]): Unit = {\n val in = new Scanner()\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n out.close()\n }\n\n class Scanner {\n val br = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(br.readLine())\n\n def next(): String = if (st.hasMoreTokens) st.nextToken() else {\n st = new StringTokenizer(br.readLine())\n next()\n }\n\n def nextInt() = next().toInt\n def nextLong() = next().toLong\n def nextDouble() = next().toDouble\n }\n}\n"}, {"source_code": "object D{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val (n,m)=(nextInt,nextInt)\n val edges=for(i<-0 until m) yield(i,nextInt,nextInt)\n val edgesSorted=scala.util.Sorting.stableSort(edges, (e1: Tuple3[Int, Int,Int], e2: Tuple3[Int, Int,Int]) => e1._2 < e2._2)\n \n val nextNode=Array.ofDim[Int](n)\n var lastNode=0\n val ans=Array.ofDim[(Int,Int)](m)\n nextNode(0)=2\n for(i<-0 until m){\n val (idx,_,isTree)=edgesSorted(i)\n if(isTree==1){\n ans(idx)=(lastNode+1,lastNode+2)\n nextNode(lastNode)=lastNode+2\n lastNode+=1\n }else{\n var has=false\n breakable{\n for(j<-0 until lastNode){\n if(nextNode(j)<=lastNode){\n ans(idx)=(j+1,nextNode(j)+1)\n nextNode(j)+=1\n has=true\n break\n }\n }\n }\n if(has==false){\n out.println(-1)\n out.flush()\n out.close()\n return\n }\n }\n }\n ans.foreach(a=>println(a._1+\" \"+a._2))\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "src_uid": "1a9968052a363f04380d1177c764717b"} {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n readInt()\n val a = readInts()\n val prefix = new MutableMultiSet[Int](List.empty)\n val suffix = new MutableMultiSet[Int](a.toList)\n var canWrongSort = false\n a.dropRight(1).foreach { v =>\n prefix.add(v)\n suffix.remove(v)\n if (prefix.max > suffix.min) canWrongSort = true\n }\n if (canWrongSort) println(\"YES\") else println(\"NO\")\n }\n\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n", "positive_code": [{"source_code": "import scala.io.Source\r\nimport scala.util.control.Breaks\r\n\r\n\r\nobject Contest extends App {\r\n val input = Source.fromInputStream(System.in).getLines()\r\n val t = input.next().toInt\r\n val arrays = new Array[Array[Int]](t)\r\n for (i <- 0 until t) {\r\n val n = input.next()\r\n arrays(i) = input.next().split(\" \").map(_.toInt)\r\n }\r\n\r\n arrays.map(check).foreach(println)\r\n\r\n def check(arr: Array[Int]): String = {\r\n val n = arr.length\r\n val maxes = arr.scanLeft(0)(math.max)\r\n val mins = arr.scanRight(Int.MaxValue)(math.min)\r\n var res = \"NO\"\r\n Breaks.breakable {\r\n for (i <- 1 until n) {\r\n if (maxes(i) > mins(i)) {\r\n res = \"YES\"\r\n Breaks.break()\r\n }\r\n }\r\n }\r\n res\r\n }\r\n}"}], "negative_code": [{"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n readInt()\n val a = readInts()\n val prefix = new MutableMultiSet[Int](List.empty)\n val suffix = new MutableMultiSet[Int](a.toList)\n var canSort = false\n a.dropRight(1).foreach { v =>\n prefix.add(v)\n suffix.remove(v)\n if (prefix.max <= suffix.min) canSort = true\n }\n if (canSort || a.length == 1) println(\"NO\") else println(\"YES\")\n }\n\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n readInt()\n val a = readInts()\n val prefix = new MutableMultiSet[Int](List.empty)\n val suffix = new MutableMultiSet[Int](a.toList)\n var canSort = false\n a.dropRight(1).foreach { v =>\n prefix.add(v)\n suffix.remove(v)\n if (prefix.max <= suffix.min) canSort = true\n }\n if (canSort) println(\"NO\") else println(\"YES\")\n }\n\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n readInt()\n val a = readInts()\n val max = a.max\n if (max != a.last) println(\"YES\") else println(\"NO\")\n }\n\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import scala.io.Source\r\nimport scala.util.control.Breaks\r\n\r\n\r\nobject Contest extends App {\r\n val input = Source.fromInputStream(System.in).getLines()\r\n val t = input.next().toInt\r\n val arrays = new Array[Array[Int]](t)\r\n for (i <- 0 until t) {\r\n val n = input.next()\r\n arrays(i) = input.next().split(\" \").map(_.toInt)\r\n }\r\n\r\n arrays.map(check).foreach(println)\r\n\r\n def check(arr: Array[Int]): String = {\r\n val n = arr.length\r\n val maxes = arr.scanLeft(0)(math.max)\r\n val mins = arr.scanRight(Int.MaxValue)(math.min)\r\n var res = \"NO\"\r\n Breaks.breakable {\r\n for (i <- 1 until n) {\r\n println(maxes(i), mins(i))\r\n if (maxes(i) > mins(i)) {\r\n res = \"YES\"\r\n Breaks.break()\r\n }\r\n }\r\n }\r\n res\r\n }\r\n}"}, {"source_code": "import scala.io.Source\r\nimport scala.util.control.Breaks\r\n\r\n\r\nobject Contest extends App {\r\n val input = Source.fromInputStream(System.in).getLines()\r\n val t = input.next().toInt\r\n val arrays = new Array[Array[Int]](t)\r\n for (i <- 0 until t) {\r\n val n = input.next()\r\n arrays(i) = input.next().split(\" \").map(_.toInt)\r\n }\r\n\r\n arrays.map(check).foreach(println)\r\n\r\n def check(arr: Array[Int]): String = {\r\n val n = arr.length\r\n val maxes = arr.scanLeft(0)(math.max)\r\n val mins = arr.scanRight(Int.MaxValue)(math.min)\r\n var res = \"YES\"\r\n Breaks.breakable {\r\n for (i <- 1 until n - 2) {\r\n if (maxes(i) <= mins(i + 1)) {\r\n res = \"NO\"\r\n Breaks.break()\r\n }\r\n }\r\n }\r\n res\r\n }\r\n}"}], "src_uid": "ef1448a744f67347183479c697aa87e1"} {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n def readLine = reader.readLine\n\n val n = readInt\n val a = readInts\n def ans = a.count(n<) + a.filter(n>=).groupBy(x => x).values.map(_.size - 1).sum\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "object P137B extends App {\n \n readLine\n var numbers = readLine.split(\" \").map(_.toInt).toList.sorted\n numbers = numbers.distinct ++ (numbers diff numbers.distinct)\n \n \n def solve(acc: Int, list: List[Int]):Int = list match{\n case (h::Nil) => acc\n case (h::t) => if (h+1 == t.head) solve(acc,t) else solve(acc+1,h+1::t.slice(0,t.size-1))\n }\n \n println(if(numbers.head == 1) solve(0,numbers) else solve(1,1::numbers.slice(0,numbers.size-1)))\n\n}\n"}, {"source_code": "object P137B extends App {\n var n = readLine toInt\n var a = new Array[Int](5001)\n for(i <- readLine.split(\" \")) a(i.toInt-1) = 1\n println(a.take(n).filter(_ < 1).size)\n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println(n - in.next().split(' ').map(_.toInt).filter(_ <= n).distinct.length)\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P137B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n N - List.fill(N)(sc.nextInt).filter(x => 1 <= x && x <= N).distinct.size\n }\n\n out.println(solve)\n out.close\n}\n\n\n\n\n\n"}, {"source_code": "// codeforces 137B\nobject Perestanovki extends App {\n val n = Console.readLine toInt\n val al = Console readLine() split(\" \") map (_.toInt)\n val agood = Array.fill(n)(0)\n \n for {\n i <- 0 until n\n if 1<= al(i) && al(i) <= n\n } agood(al(i) - 1) = 1\n val sm:Int = ((agood toList) sum)\n //println(\"sm = \" + sm)\n //println(\"agood = \" + (agood.toList.mkString(\" \")))\n val s = (n-sm) toString;\n println(s)\n\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val map = scala.collection.mutable.Map[Int, Int]()\n a.foreach(i => map(i) = map.getOrElse(i, 0) + 1)\n val count = (1 to n).foldLeft(0){ (a, i) => map.get(i) match {\n case Some(_) => a\n case None => a + 1\n }}\n println(count)\n }\n}"}, {"source_code": "object P137B extends App {\n readLine\n var n = readLine.split(\" \").map(_.toInt).toList.sorted\n val d = n.distinct\n n = d ++ (n diff d)\n def s(a: Int, l: List[Int]):Int = l match{\n case (h::Nil) => a\n case (h::t) => if (h+1 == t.head) s(a, t) else s(a+1, h+1::t.slice(0,t.size-1))\n }\n println(if(n.head == 1) s(0,n) else s(1,1::n.slice(0,n.size-1)))\n}\n"}], "negative_code": [{"source_code": "object P137B extends App {\n \n readLine\n var numbers = readLine.split(\" \").map(_.toInt).toList.sorted\n numbers = numbers.distinct ++ (numbers diff numbers.distinct)\n \n def solve(acc: Int, list: List[Int]):Int = list match{\n case (h::Nil) => acc\n case (h::t) => if (h+1 == t.head) solve(acc,t) else solve(acc+1,h+1::t.slice(0,t.size-1))\n }\n \n println(solve(0,numbers))\n\n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println(n - in.next().split(' ').distinct.length)\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P137B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n N - List.fill(N)(sc.nextInt).distinct.size\n }\n\n out.println(solve)\n out.close\n}\n\n\n\n\n\n"}], "src_uid": "bdd86c8bc54bbac6e2bb5a9d68b6eb1c"} {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Codeforces1130B {\n\n def getMinimumDistanceForTwoCakes(n: Int, a: Seq[Int]): Long = {\n val numberPositionMap = new mutable.HashMap[Int, (Long, Long)]()\n for (i <- a.indices) {\n if (numberPositionMap.contains(a(i)))\n numberPositionMap(a(i)) = (numberPositionMap(a(i))._1, i)\n else\n numberPositionMap(a(i)) = (i, -1)\n }\n\n val positionStart = numberPositionMap(1)\n var totalDistance = positionStart._1 + positionStart._2\n for (cursor <- 1 until n) {\n val positionFrom = numberPositionMap(cursor)\n val positionTo = numberPositionMap(cursor + 1)\n val distance1 = math.abs(positionFrom._1 - positionTo._1) + math.abs(positionFrom._2 - positionTo._2)\n val distance2 = math.abs(positionFrom._1 - positionTo._2) + math.abs(positionFrom._2 - positionTo._1)\n totalDistance += math.min(distance1, distance2)\n }\n totalDistance\n }\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readLine().trim.toInt\n val a = StdIn.readLine().trim.split(\" \").map(_.toInt)\n val d = getMinimumDistanceForTwoCakes(n, a)\n println(d)\n }\n\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(2 * N, -1)\n\n // 貪欲に左右に分割するのが最適\n val fst, snd = Array.fill[Int](N)(-1)\n REP(2 * N) { i =>\n if (fst(A(i)) == -1) fst(A(i)) = i\n else snd(A(i)) = i\n }\n\n // 1-Nを順番に辿ったときの距離\n def dist(D: Array[Int]): Long = {\n var ans = 0L\n var pre = 0\n REP(N) { i =>\n val d = abs(D(i) - pre)\n ans += d\n pre = D(i)\n }\n ans\n }\n\n val ans = dist(fst) + dist(snd)\n out.println(ans)\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugNum(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Codeforces1130B {\n\n def getMinimumDistanceForTwoCakes(n: Int, a: Seq[Int]): Int = {\n val numberPositionMap = new mutable.HashMap[Int, (Int, Int)]()\n for (i <- a.indices) {\n if (numberPositionMap.contains(a(i))) {\n numberPositionMap(a(i)) = (numberPositionMap(a(i))._1, i)\n } else {\n numberPositionMap(a(i)) = (i, -1)\n }\n }\n var totalDistance = 0\n var cursor = n\n while (cursor > 1) {\n val positionFrom = numberPositionMap(cursor)\n val positionTo = numberPositionMap(cursor - 1)\n val distance1 = math.abs(positionFrom._1 - positionTo._1) + math.abs(positionFrom._2 - positionTo._2)\n val distance2 = math.abs(positionFrom._1 - positionTo._2) + math.abs(positionFrom._2 - positionTo._1)\n totalDistance += math.min(distance1, distance2)\n cursor -= 1\n }\n val positionStart = numberPositionMap(1)\n totalDistance += positionStart._1 + positionStart._2\n totalDistance\n }\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readLine().trim.toInt\n val a = StdIn.readLine().trim.split(\" \").map(_.toInt)\n val d = getMinimumDistanceForTwoCakes(n, a)\n println(d)\n }\n\n}\n"}], "src_uid": "dc9c2703aa7aaf1d254211cf06030329"} {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\n\nimport scala.collection.immutable.IndexedSeq\n\nobject _570C extends CodeForcesApp[Seq[Int]]({scanner => import scanner._\n def f(str: String, pos: Int = 0): Int = str.indexOf(\"..\", pos) match {\n case -1 => 0\n case p => 1 + f(str, p+1)\n }\n\n def dotInt(c: Char) = if (c == '.') 1 else 0\n\n val (n, m, _s) = (nextInt, nextInt, next)\n\n var t = f(_s)\n var s: IndexedSeq[Int] = s\"x${_s}x\" map dotInt\n\n repeat(m) {\n val (i, c) = (nextInt, dotInt(next.head))\n\n val delta = (s(i-1), s(i), s(i+1), c) match {\n case (_, 1, _, 1) => 0\n case (_, 0, _, 0) => 0\n\n case (0, 1, 0, 0) => 0\n case (0, 1, 1, 0) => -1\n case (1, 1, 0, 0) => -1\n case (1, 1, 1, 0) => -2\n\n case (0, 0, 0, 1) => 0\n case (0, 0, 1, 1) => 1\n case (1, 0, 0, 1) => 1\n case (1, 0, 1, 1) => 2\n }\n\n s = s.updated(i, c)\n t += delta\n\n t\n }\n}) {\n override def format(result: Seq[Int]) = result mkString \"\\n\"\n}\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n import scala.collection.mutable.{Map => Dict}\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0\n}\n", "positive_code": [{"source_code": "\nimport scala.io.StdIn.readLine\n\n/**\n * @author slie742\n */\nobject Replacement {\n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readTuple() : (Int,Char) = {\n val line = readLine.split(' ')\n (line(0).toInt,line(1).charAt(0))\n }\n \n \n \n def main(args: Array[String]) {\n val nm = readInts\n val n = nm(0)\n val m = nm(1)\n val s = ('x' + readLine + 'x').toArray\n var i = 1\n var total = 0\n while (i <= n) {\n if (s(i) == '.' && s(i-1) == '.') total +=1\n i += 1\n }\n i = 0\n val output = new Array[Int](m)\n while (i < m) {\n val (p,c) = readTuple\n if (c == '.') {\n if (s(p) != c) {\n if (s(p-1) == '.' && s(p+1) == '.') total +=2\n else if (s(p-1) == '.' || s(p+1) == '.') total +=1\n }\n } else { // s(p) != '.'\n if (s(p) == '.') {\n if (s(p-1) == '.' && s(p+1) == '.') total -=2\n else if (s(p-1) == '.' || s(p+1) == '.') total -=1\n }\n }\n s(p) = c\n output(i) = total\n i += 1\n }\n println(output.mkString(\"\\n\"))\n \n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n // val n = 299999\n // val m = 300000\n // val s = (\" \" + (\".\" * n) + \" \").toCharArray\n val s = (\" \" + readLine() + \" \").toCharArray\n\n var current = 0\n for (i <- 1 until n) {\n if (s(i) == '.' && s(i + 1) == '.') current += 1\n }\n\n def count(x: Int, c: Char): Int = {\n val curr = s(x)\n val isCurrPeriod = curr == '.'\n val isInsertedPeriod = c == '.'\n val isChange = isCurrPeriod ^ isInsertedPeriod\n\n if (isChange) {\n val prev = s(x - 1)\n val next = s(x + 1)\n\n var amount = 0\n if (prev == '.') amount += 1\n if (next == '.') amount += 1\n\n if (isInsertedPeriod) {\n current += amount\n } else {\n current -= amount\n }\n\n s(x) = c\n }\n\n current\n }\n\n val sb = new scala.collection.mutable.StringBuilder\n for (_ <- 1 to m) {\n val Array(x, c) = readLine().split(\" \")\n sb.append(count(x.toInt, c.head)).append('\\n')\n }\n print(sb)\n\n // for (i <- 1 to m) {\n //// val arr = readLine().split(\" \")\n // val arr = s\"$i .\".split(\" \")\n // val x = Math.min(arr(0).toInt, n)\n // val c = arr(1)(0)\n // println(count(x, c))\n // }\n\n\n}"}, {"source_code": "import io.StdIn._\nimport scala.collection.mutable\nimport scala.collection.mutable._\n\nobject Solution {\n\n def main(args: Array[String]) {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n val s = readLine()\n val f = Array.fill[Boolean](n+2)(false)\n\n var num = 0\n var seg = 0\n\n for (i <- (1 to n)) {\n if (s(i-1) == '.') {\n f(i) = true\n num += 1\n if (i == 1 || s(i-2) != '.') seg += 1\n }\n }\n\n val sb = new mutable.StringBuilder\n for (_ <- (1 to m)) {\n val Array(ids, ch) = readLine().split(\" \")\n val id = ids.toInt\n val nc = (ch == \".\")\n val c = f(id)\n if (nc != c) {\n f(id) = nc\n num = if (nc) num+1 else num-1\n if (f(id-1) && f(id+1) && nc) seg -= 1\n if (!f(id-1) && !f(id+1) && nc) seg += 1\n if (f(id-1) && f(id+1) && !nc) seg += 1\n if (!f(id-1) && !f(id+1) && !nc) seg -= 1\n }\n sb.append(num-seg).append('\\n')\n }\n print(sb)\n\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solveBruteForce(str1: Array[Char], pos: Int, ch: Char) = {\n val str = new Array[Char](str1.length)\n Array.copy(str1, 0, str, 0, str1.length)\n str(pos) = ch\n var cnt = 0\n var fx = 0\n for (i <- 0 until str.length) {\n if (str(i) == '.') {\n cnt += 1\n } else {\n if (cnt != 0) {\n fx += cnt - 1\n }\n cnt = 0\n }\n }\n if (cnt > 0) {\n fx += cnt - 1\n }\n fx\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val str = next.toCharArray\n var fx = 0\n var cnt = 0\n for (i <- 0 until n) {\n if (str(i) == '.') {\n cnt += 1\n } else {\n if (cnt != 0) {\n fx += cnt - 1\n }\n cnt = 0\n }\n }\n if (cnt > 0) {\n fx += cnt - 1\n }\n for (i <- 0 until m) {\n val pos = nextInt - 1\n val ch = next.toCharArray()(0)\n if (n == 1) {\n out.println(0)\n } else {\n// out.print(solveBruteForce(str, pos, ch) + \" \")\n if (ch != str(pos)) {\n if (ch == '.') {\n if (pos == 0) {\n if (str(1) == '.')\n fx += 1\n } else if (pos == n - 1) {\n if (str(n - 2) == '.')\n fx += 1\n } else {\n var c = 0\n if (str(pos - 1) == '.') {\n c += 1\n }\n if (str(pos + 1) == '.') {\n c += 1\n }\n fx += c\n }\n } else if (str(pos) == '.'){\n if (pos == 0) {\n if (str(1) == '.')\n fx -= 1\n } else if (pos == n - 1) {\n if (str(n - 2) == '.')\n fx -= 1\n } else {\n var c = 0\n if (str(pos - 1) == '.') {\n c -= 1\n }\n if (str(pos + 1) == '.') {\n c -= 1\n }\n fx += c\n }\n }\n }\n if (fx < 0) {\n fx = 0\n }\n str(pos) = ch\n out.println(fx)\n }\n }\n return 0\n }\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solveBruteForce(str1: Array[Char], pos: Int, ch: Char) = {\n val str = new Array[Char](str1.length)\n Array.copy(str1, 0, str, 0, str1.length)\n str(pos) = ch\n var cnt = 0\n var fx = 0\n for (i <- 0 until str.length) {\n if (str(i) == '.') {\n cnt += 1\n } else {\n if (cnt != 0) {\n fx += cnt - 1\n }\n cnt = 0\n }\n }\n if (cnt > 0) {\n fx += cnt - 1\n }\n fx\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val str = next.toCharArray\n var fx = 0\n var cnt = 0\n for (i <- 0 until n) {\n if (str(i) == '.') {\n cnt += 1\n } else {\n if (cnt != 0) {\n fx += cnt - 1\n }\n cnt = 0\n }\n }\n if (cnt > 0) {\n fx += cnt - 1\n }\n for (i <- 0 until m) {\n val pos = nextInt - 1\n val ch = next.toCharArray()(0)\n if (n == 1) {\n out.println(0)\n } else {\n out.print(solveBruteForce(str, pos, ch) + \" \")\n if (ch != str(pos)) {\n if (ch == '.') {\n if (pos == 0) {\n if (str(1) == '.')\n fx += 1\n } else if (pos == n - 1) {\n if (str(n - 2) == '.')\n fx += 1\n } else {\n var c = 0\n if (str(pos - 1) == '.') {\n c += 1\n }\n if (str(pos + 1) == '.') {\n c += 1\n }\n fx += c\n }\n } else if (str(pos) == '.'){\n if (pos == 0) {\n if (str(1) == '.')\n fx -= 1\n } else if (pos == n - 1) {\n if (str(n - 2) == '.')\n fx -= 1\n } else {\n var c = 0\n if (str(pos - 1) == '.') {\n c -= 1\n }\n if (str(pos + 1) == '.') {\n c -= 1\n }\n fx += c\n }\n }\n }\n if (fx < 0) {\n fx = 0\n }\n str(pos) = ch\n out.println(fx)\n }\n }\n return 0\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val str = next.toCharArray\n var fx = 0\n var cnt = 0\n for (i <- 0 until n) {\n if (str(i) == '.') {\n cnt += 1\n } else {\n if (cnt != 0) {\n fx += cnt - 1\n }\n cnt = 0\n }\n }\n if (cnt > 0) {\n fx += cnt - 1\n }\n for (i <- 0 until m) {\n val pos = nextInt - 1\n val ch = next.toCharArray()(0)\n if (n == 1) {\n out.println(0)\n } else {\n if (ch != str(pos)) {\n if (ch == '.') {\n if (pos == 0) {\n if (str(1) == '.')\n fx += 1\n } else if (pos == n - 1) {\n if (str(n - 2) == '.')\n fx += 1\n } else {\n var c = 0\n if (str(pos - 1) == '.') {\n c += 1\n }\n if (str(pos + 1) == '.') {\n c += 1\n }\n fx += c\n }\n } else {\n if (pos == 0) {\n if (str(1) == '.')\n fx -= 1\n } else if (pos == n - 1) {\n if (str(n - 2) == '.')\n fx -= 1\n } else {\n var c = 0\n if (str(pos - 1) == '.') {\n c -= 1\n }\n if (str(pos + 1) == '.') {\n c -= 1\n }\n fx += c\n }\n }\n }\n if (fx < 0) {\n fx = 0\n }\n str(pos) = ch\n out.println(fx)\n }\n }\n return 0\n }\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val str = next.toCharArray\n var fx = 0\n var cnt = 0\n for (i <- 0 until n) {\n if (str(i) == '.') {\n cnt += 1\n } else {\n if (cnt != 0) {\n fx += cnt - 1\n }\n cnt = 0\n }\n }\n if (cnt > 0) {\n fx += cnt - 1\n }\n for (i <- 0 until m) {\n val pos = nextInt - 1\n val ch = next.toCharArray()(0)\n if (n == 1) {\n out.println(0)\n } else {\n if (ch != str(pos)) {\n if (ch == '.') {\n if (pos == 0) {\n if (str(1) == '.')\n fx += 1\n } else if (pos == n - 1) {\n if (str(n - 2) == '.')\n fx += 1\n } else {\n var c = 0\n if (str(pos - 1) == '.') {\n c += 1\n }\n if (str(pos + 1) == '.') {\n c += 1\n }\n fx += c\n }\n } else {\n if (pos == 0) {\n if (str(1) == '.')\n fx -= 1\n } else if (pos == n - 1) {\n if (str(n - 2) == '.')\n fx -= 1\n } else {\n var c = 0\n if (str(pos - 1) == '.') {\n c -= 1\n }\n if (str(pos + 1) == '.') {\n c -= 1\n }\n fx += c\n }\n }\n }\n\n str(pos) = ch\n out.println(fx)\n }\n }\n return 0\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n// val n = 299999\n// val m = 300000\n// val s = (\" \" + (\".\" * n) + \" \").toCharArray\n val s = (\" \" + readLine() + \" \").toCharArray\n\n var current = 0\n for (i <- 1 until n) {\n if (s(i) == '.' && s(i + 1) == '.') current += 1\n }\n\n def count(x: Int, c: Char): Int = {\n val prev = s(x - 1)\n val curr = s(x)\n val isCurrPeriod = curr == '.'\n val next = s(x + 1)\n\n if (c == '.' && !isCurrPeriod) {\n if (prev == '.' && next == '.') {\n current += 2\n } else if (next == '.') {\n current += 1 // b[b]. <- .\n } else if (prev == '.') {\n current += 1 // b[b]. <- .\n }\n } else {\n if (prev == '.' && next == '.' && isCurrPeriod) {\n current -= 2\n } else if (next == '.') {\n current -= 1 // b[.]. <- b\n } else if (prev == '.') {\n current -= 1 // b[.]. <- b\n }\n\n }\n\n s(x) = c\n current\n }\n\n for (_ <- 1 to m) {\n val arr = readLine().split(\" \")\n val (x, c) = (arr(0).toInt, arr(1).head)\n println(count(x, c))\n }\n\n// for (i <- 1 to m) {\n//// val arr = readLine().split(\" \")\n// val arr = s\"$i .\".split(\" \")\n// val x = Math.min(arr(0).toInt, n)\n// val c = arr(1)(0)\n// println(count(x, c))\n// }\n\n\n}"}], "src_uid": "68883ab115882de5cf77d0848b80b422"} {"source_code": "import scala.io.StdIn\nimport scala.math.min\n\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val input = StdIn.readLine().split(\" \").map(_.toInt)\n val (x, y, a, b) = (input(0), input(1), input(2), input(3))\n val arr: IndexedSeq[String] = for(i <- a to x; j <- b to min(i, y) if i > j) yield i + \" \" + j\n println(arr.length)\n arr.foreach(println(_))\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) = {\n val xyab = readLine() split(\" \") map(_.toInt)\n val x = xyab(0)\n val y = xyab(1)\n val a = xyab(2)\n val b = xyab(3)\n \n val s = for {\n i <- a to x\n j <- b to y\n if i > j\n } yield(i, j)\n println(s.size)\n s.foreach{ t => println(t._1 + \" \" + t._2) }\n }\n}"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n def readLine = reader.readLine\n\n val Array(x, y, a, b) = readInts\n val outcomes = (for(i <- a to x) yield for(j <- b to y.min(i - 1)) yield Array(i, j)).flatMap(x => x)\n def ans = (outcomes.size +: outcomes.map(_.mkString(\" \"))).mkString(\"\\n\")\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(x, y, a, b) = in.next().split(' ').map(_.toInt)\n val res = (Math.max(a, b + 1) to x).flatMap(i => (b to Math.min(y, i - 1)).map(j => s\"$i $j\"))\n println(res.length)\n println(res.mkString(\"\\n\"))\n}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable._\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val x, y, a, b = sc.nextInt()\n\n val ans = (a to x) flatMap { x => (b to (math.min(y, x - 1))).map(x + \" \" + _) }\n\n println(ans.length)\n println(ans.mkString(\"\\n\"))\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P242A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n // Vasya => x times\n // Petya => y times\n // gets head => one point\n // more points win or draw\n\n val X, Y, A, B = sc.nextInt\n\n def solve(): Seq[List[Int]] = {\n for {\n i <- A to X\n j <- B to ((i - 1) min Y)\n }\n yield List(i, j)\n }\n\n val answer = solve\n out.println(answer.size)\n answer foreach { stats =>\n out.println(stats.mkString(\" \"))\n }\n out.close\n}\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n def readLine = reader.readLine\n\n val Array(x, y, a, b) = readInts\n val outcomes = (for(i <- a to x) yield for(j <- b to y.min(i - 1)) yield Array(i, j)).flatMap(x => x)\n def ans = (outcomes.size +: outcomes.map(_.mkString(\" \"))).mkString(\"\\n\")\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main extends App\n{\n\tval sc=new Scanner(System.in)\n\tval x,y,a,b=sc.nextInt()\n\tval ans=for(i<-List.range(a,x+1) ;\n\t\t\t\tj<-List.range(b,y+1) if (i>j)) yield i.toString+' '+j.toString\n\tprintln(ans.length)\n\tprintln(ans.mkString(\"\\n\"))\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\n\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val input = StdIn.readLine().split(\" \").map(_.toInt)\n val (x, y, a, b) = (input(0), input(1), input(2), input(3))\n val arr: IndexedSeq[String] = for(i <- a + 1 to x; j <- b until i) yield i + \" \" + j\n println(arr.length)\n arr.foreach(println(_))\n }\n}"}, {"source_code": "import scala.io.StdIn\n\n\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val input = StdIn.readLine().split(\" \").map(_.toInt)\n val (x, y, a, b) = (input(0), input(1), input(2), input(3))\n val arr: IndexedSeq[String] = for(i <- a to x; j <- b until i) yield i + \" \" + j\n println(arr.length)\n arr.foreach(println(_))\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P242A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n // Vasya => x times\n // Petya => y times\n // gets head => one point\n // more points win or draw\n\n val X, Y, A, B = sc.nextInt\n\n def solve(): Seq[List[Int]] = {\n for {\n i <- A to X\n j <- B until (i max Y)\n }\n yield List(i, j)\n }\n\n val answer = solve\n out.println(answer.size)\n answer foreach { stats =>\n out.println(stats.mkString(\" \"))\n }\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P242A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n // Vasya => x times\n // Petya => y times\n // gets head => one point\n // more points win or draw\n\n val X, Y, A, B = sc.nextInt\n\n def solve(): Seq[List[Int]] = {\n for {\n i <- A to X\n j <- B until (i min Y)\n }\n yield List(i, j)\n }\n\n val answer = solve\n out.println(answer.size)\n answer foreach { stats =>\n out.println(stats.mkString(\" \"))\n }\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P242A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n // Vasya => x times\n // Petya => y times\n // gets head => one point\n // more points win or draw\n\n val X, Y, A, B = sc.nextInt\n\n def solve(): Seq[List[Int]] = {\n for {\n i <- A to X\n j <- B until i\n }\n yield List(i, j)\n }\n\n val answer = solve\n out.println(answer.size)\n answer foreach { stats =>\n out.println(stats.mkString(\" \"))\n }\n out.close\n}\n"}], "src_uid": "bb3e3b51a4eda8fef503952a00777910"} {"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val ps = readInts(n)\n\n val len = Array.fill(n + 1){ 0 }\n\n for (p <- ps) len(p) = len(p - 1) + 1\n\n println(n - len.max)\n}", "positive_code": [{"source_code": "object b extends App {\n var n = readInt\n var arr = readLine.split(\"\\\\s+\").map(_.toInt)\n var dp = new Array[Int](n + 1)\n\n for (i <- 0 to n - 1)\n dp(arr(i)) = dp(arr(i) - 1) + 1\n \n println(n - dp.max)\n}"}, {"source_code": "/*\n * Reference: http://lizan.asia/blog/2012/12/11/scala-competitive/\n */\n\nobject Main extends App {\n import java.{util => ju}\n import scala.annotation._\n import scala.collection._\n import scala.collection.{mutable => mu}\n import scala.collection.JavaConverters._\n import scala.math._\n\n val sc = new ju.Scanner(System.in)\n \n val n = sc.nextInt\n val a = Array.fill(n)(sc.nextInt - 1)\n val b = Array.fill(n + 1)(-1)\n (0 until n) foreach {i => b(a(i)) = i}\n var ma = 0\n var cur, start = 0\n (0 to n) foreach {i =>\n if (b(i) < cur) {\n ma = ma max (i - start)\n start = i\n }\n cur = b(i)\n }\n println(n - ma)\n\n}"}, {"source_code": "import java.io._\nimport java.util._\n\n/**\n * Created by antonkov on 9/17/15.\n */\nobject A {\n def solve(in: Scanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val a = new Array[Int](n)\n val was = new Array[Boolean](n)\n val good = new Array[Boolean](n)\n for (i <- 0 until n) {\n a(i) = in.nextInt() - 1\n was(a(i)) = true\n if (a(i) != 0 && was(a(i) - 1)) {\n good(a(i)) = true\n }\n }\n var cur, best = 1\n for (i <- 0 until n) if (good(i)) {\n cur += 1\n if (cur > best) best = cur\n } else {\n cur = 1\n }\n out.println(n - best)\n }\n\n def main (args: Array[String]): Unit = {\n val in = new Scanner()\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n out.close()\n }\n\n class Scanner {\n val br = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(br.readLine())\n\n def next(): String = if (st.hasMoreTokens) st.nextToken() else {\n st = new StringTokenizer(br.readLine())\n next()\n }\n\n def nextInt() = next().toInt\n def nextLong() = next().toLong\n def nextDouble() = next().toDouble\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val block = data.foldLeft(Map.empty[Int, Int]) {\n case (map, value) if map.contains(value - 1) => map + (value -> (map(value - 1) + 1)) - (value - 1)\n case (map, value) => map + (value -> 1)\n }\n println(n - block.values.max)\n\n}"}], "negative_code": [{"source_code": "import java.io._\nimport java.util._\n\n/**\n * Created by antonkov on 9/17/15.\n */\nobject A {\n def solve(in: Scanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val a = new Array[Int](n)\n val was = new Array[Boolean](n)\n val good = new Array[Boolean](n)\n for (i <- 0 until n) {\n a(i) = in.nextInt() - 1\n was(a(i)) = true\n if (a(i) == 0 || was(a(i) - 1)) {\n good(a(i)) = true\n }\n }\n var cur, best = 0\n for (i <- 0 until n) if (good(i)) {\n cur += 1\n if (cur > best) best = cur\n } else {\n cur = 0\n }\n out.println(n - best)\n }\n\n def main (args: Array[String]): Unit = {\n val in = new Scanner()\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n out.close()\n }\n\n class Scanner {\n val br = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(br.readLine())\n\n def next(): String = if (st.hasMoreTokens) st.nextToken() else {\n st = new StringTokenizer(br.readLine())\n next()\n }\n\n def nextInt() = next().toInt\n def nextLong() = next().toLong\n def nextDouble() = next().toDouble\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\n/**\n * Created by antonkov on 9/17/15.\n */\nobject A {\n def solve(in: Scanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val a = new Array[Int](n)\n val was = new Array[Boolean](n)\n val good = new Array[Boolean](n)\n for (i <- 0 until n) {\n a(i) = in.nextInt() - 1\n was(a(i)) = true\n if (a(i) != 0 && was(a(i) - 1)) {\n good(a(i)) = true\n }\n }\n var cur, best = 0\n for (i <- 0 until n) if (good(i)) {\n cur += 1\n if (cur > best) best = cur\n } else {\n cur = 1\n }\n out.println(n - best)\n }\n\n def main (args: Array[String]): Unit = {\n val in = new Scanner()\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n out.close()\n }\n\n class Scanner {\n val br = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(br.readLine())\n\n def next(): String = if (st.hasMoreTokens) st.nextToken() else {\n st = new StringTokenizer(br.readLine())\n next()\n }\n\n def nextInt() = next().toInt\n def nextLong() = next().toLong\n def nextDouble() = next().toDouble\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\n/**\n * Created by antonkov on 9/17/15.\n */\nobject A {\n def solve(in: Scanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val a = new Array[Int](n)\n val was = new Array[Boolean](n)\n val good = new Array[Boolean](n)\n for (i <- 0 until n) {\n a(i) = in.nextInt() - 1\n was(a(i)) = true\n if (a(i) != 0 && was(a(i) - 1)) {\n good(a(i)) = true\n }\n }\n var cur, best = 1\n println(cur + \" \" + best)\n for (i <- 0 until n) if (good(i)) {\n cur += 1\n if (cur > best) best = cur\n } else {\n cur = 1\n }\n out.println(n - best)\n }\n\n def main (args: Array[String]): Unit = {\n val in = new Scanner()\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n out.close()\n }\n\n class Scanner {\n val br = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(br.readLine())\n\n def next(): String = if (st.hasMoreTokens) st.nextToken() else {\n st = new StringTokenizer(br.readLine())\n next()\n }\n\n def nextInt() = next().toInt\n def nextLong() = next().toLong\n def nextDouble() = next().toDouble\n }\n}\n"}, {"source_code": "object b extends App {\n var n = readInt\n var arr = readLine.split(\"\\\\s+\").map(_.toInt)\n\n def solve(arr: Array[Int], pos: Int, took: Int, op: (Int, Int) => Int): Int = \n if (pos >= arr.length || pos < 0)\n took\n else\n if (arr(pos) == op(took, 1))\n solve(arr, op(pos, 1), op(took, 1), op)\n else\n solve(arr, op(pos, 1), took, op)\n \n println((n - solve(arr, 0, 0, _ + _)) min (solve(arr, n - 1, n + 1, _ - _) - 1))\n}"}], "src_uid": "277948a70c75840445e1826f2b23a897"} {"source_code": "import java.io._\r\nimport java.util.Scanner\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val reader = new Scanner(System.in)\r\n val writer = new PrintWriter(System.out)\r\n\r\n def pow(a: Int, b: Int): Long = {\r\n if (b == 0) return 1\r\n\r\n val rs = pow(a, b / 2)\r\n rs * rs * (if (b % 2 == 0) 1 else a)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b\r\n\r\n def root(u: Int, p: Array[Int]): Int = {\r\n if (p(u) < 0) return u\r\n p(u) = root(p(u), p)\r\n p(u)\r\n }\r\n\r\n def join(u: Int, v: Int, p: Array[Int]): Unit = {\r\n var x = root(u, p)\r\n var y = root(v, p)\r\n if (x == y) return\r\n\r\n if (p(y) < p(x)) {\r\n val t = x\r\n x = y\r\n y = t\r\n }\r\n p(x) += p(y)\r\n p(y) = x\r\n }\r\n\r\n def solve(t: Int = 0): Unit = {\r\n val n = reader.nextInt()\r\n var c = 0\r\n while (f(c) < n) c += 1\r\n\r\n if (f(c) == n) {\r\n writer.println(s\"1 ${c + 1}\")\r\n return\r\n }\r\n\r\n val sub = n - f(c - 1)\r\n if (c - 1 == sub)\r\n writer.println(s\"$c $c\")\r\n else if (c - 1 > sub)\r\n writer.println(s\"${1 + sub} $c\")\r\n else\r\n writer.println(s\"$c ${2*c - sub - 1}\")\r\n }\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = reader.nextInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n val f = new Array[Int](40000)\r\n def main(args: Array[String]) {\r\n var i = 1\r\n var c = 1\r\n var size = 1\r\n f(0) = c\r\n while (c < 1000000000) {\r\n c += i\r\n i += 2\r\n f(size) = c\r\n size += 1\r\n }\r\n multiTest(solve)\r\n //solve()\r\n writer.flush()\r\n }\r\n}", "positive_code": [{"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val k = readInt()\r\n\r\n val i = {\r\n @annotation.tailrec\r\n def go(i: Int): Int = if (i * i >= k) i else go(i + 1)\r\n go(1)\r\n }\r\n\r\n val j = k - (i - 1) * (i - 1)\r\n\r\n val (r, c) = if (j <= i) (j, i) else (i, i - (j - i))\r\n\r\n println(s\"$r $c\")\r\n }\r\n}\r\n"}, {"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val k = readInt()\r\n\r\n val row = math.sqrt(k).ceil.toInt\r\n val (from, to) = ((row - 1) * (row - 1) + 1, row * row)\r\n val length = to - from + 1\r\n val half = length / 2\r\n val index = k - from\r\n\r\n val (r, c) =\r\n if (index < half) (index + 1, row)\r\n else if (index > half) (row, length - index)\r\n else (row, row)\r\n\r\n println(s\"$r $c\")\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "f8335c59cd05988c8053f138c4df06aa"} {"source_code": "import java.util\nimport java.io.PrintWriter\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\n\nobject Main {\n var tokenizer = new util.StringTokenizer(\"\")\n val out = new PrintWriter(System.out)\n val br = new BufferedReader(new InputStreamReader(System.in))\n\n def readToken = {\n while (!tokenizer.hasMoreTokens) tokenizer = new util.StringTokenizer(readLine)\n tokenizer.nextToken\n }\n\n def readInt = readToken.toInt\n\n val ancLevel = 18\n val anc = Array.ofDim[Int](ancLevel, 1000000 + 20)\n val dep = Array.ofDim[Int](1000000 + 20)\n\n def getLca(x: Int, y: Int) = {\n var (a, b) = if (dep(x) >= dep(y)) (x, y) else (y, x)\n for (lv <- ancLevel - 1 to 0 by -1; if dep(a) - (1 << lv) >= dep(b)) a = anc(lv)(a)\n if (a == b) {\n a\n } else {\n for (lv <- ancLevel - 1 to 0 by -1; if anc(lv)(a)!= anc(lv)(b)) {\n a = anc(lv)(a)\n b = anc(lv)(b)\n }\n anc(0)(a)\n }\n }\n\n var d = 2\n\n def check(cur: Int, far: Int) = {\n val lca = getLca(cur, far)\n val curD = dep(cur) - dep(lca) + dep(far) - dep(lca)\n if (curD > d) {\n d = curD\n true\n } else {\n false\n }\n }\n\n def main(args: Array[String]) {\n var p1 = 2\n var p2 = 3\n val q = br.readLine.toInt\n\n for (i <- 2 to 4) {\n anc(0)(i) = 1\n dep(i) = 1\n }\n\n var n = 4\n for (i <- 0 until q) {\n val x = br.readLine.toInt\n anc(0)(n + 1) = x\n anc(0)(n + 2) = x\n n += 2\n }\n\n for (p <- 5 to n) {\n dep(p)= dep(anc(0)(p)) + 1\n for (lv <- 1 until ancLevel) {\n anc(lv)(p) = anc(lv-1)(anc(lv-1)(p))\n }\n }\n\n n = 4\n for (i <- 0 until q) {\n if (check(n + 1, p1)) {\n p2 = n + 1\n } else if (check(n + 1, p2)) {\n p1 = n + 1\n }\n out.println(d)\n n += 2\n }\n out.flush()\n }\n}", "positive_code": [{"source_code": "import java.util\nimport java.io.PrintWriter\n\nobject Main {\n var tokenizer = new util.StringTokenizer(\"\")\n val out = new PrintWriter(System.out)\n\n def readToken = {\n while (!tokenizer.hasMoreTokens)\n\t\ttokenizer = new util.StringTokenizer(scala.io.StdIn.readLine)\n tokenizer.nextToken\n }\n\n def readInt = readToken.toInt\n\n val ancLevel = 18\n val anc = Array.ofDim[Int](ancLevel, 1000000 + 20)\n val dep = Array.ofDim[Int](1000000 + 20)\n\n def getLca(x: Int, y: Int) = {\n var (a, b) = if (dep(x) >= dep(y)) (x, y) else (y, x)\n for (lv <- ancLevel - 1 to 0 by -1; if dep(a) - (1 << lv) >= dep(b)) a = anc(lv)(a)\n if (a == b) {\n a\n } else {\n for (lv <- ancLevel - 1 to 0 by -1; if anc(lv)(a)!= anc(lv)(b)) {\n a = anc(lv)(a)\n b = anc(lv)(b)\n }\n anc(0)(a)\n }\n }\n\n var d = 2\n\n def check(cur: Int, far: Int) = {\n val lca = getLca(cur, far)\n val curD = dep(cur) - dep(lca) + dep(far) - dep(lca)\n if (curD > d) {\n d = curD\n true\n } else {\n false\n }\n }\n\n def main(args: Array[String]) {\n var p1 = 2\n var p2 = 3\n val q = scala.io.StdIn.readLine.toInt\n\n for (i <- 2 to 4) {\n anc(0)(i) = 1\n dep(i) = 1\n }\n\n var n = 4\n for (i <- 0 until q) {\n val x = scala.io.StdIn.readLine.toInt\n anc(0)(n + 1) = x\n anc(0)(n + 2) = x\n n += 2\n }\n\n for (p <- 5 to n) {\n dep(p)= dep(anc(0)(p)) + 1\n for (lv <- 1 until ancLevel) {\n anc(lv)(p) = anc(lv-1)(anc(lv-1)(p))\n }\n }\n\n n = 4\n for (i <- 0 until q) {\n if (check(n + 1, p1)) {\n p2 = n + 1\n } else if (check(n + 1, p2)) {\n p1 = n + 1\n }\n out.println(d)\n n += 2\n }\n out.flush()\n }\n}\n"}, {"source_code": "import java.util\nimport java.io.PrintWriter\n\nobject Main {\n var tokenizer = new util.StringTokenizer(\"\")\n val out = new PrintWriter(System.out)\n\n def readToken = {\n while (!tokenizer.hasMoreTokens) tokenizer = new util.StringTokenizer(readLine)\n tokenizer.nextToken\n }\n\n def readInt = readToken.toInt\n\n val ancLevel = 18\n val anc = Array.ofDim[Int](ancLevel, 1000000 + 20)\n val dep = Array.ofDim[Int](1000000 + 20)\n\n def getLca(x: Int, y: Int) = {\n var (a, b) = if (dep(x) >= dep(y)) (x, y) else (y, x)\n for (lv <- ancLevel - 1 to 0 by -1; if dep(a) - (1 << lv) >= dep(b)) a = anc(lv)(a)\n if (a == b) {\n a\n } else {\n for (lv <- ancLevel - 1 to 0 by -1; if anc(lv)(a)!= anc(lv)(b)) {\n a = anc(lv)(a)\n b = anc(lv)(b)\n }\n anc(0)(a)\n }\n }\n\n var d = 2\n\n def check(cur: Int, far: Int) = {\n val lca = getLca(cur, far)\n val curD = dep(cur) - dep(lca) + dep(far) - dep(lca)\n if (curD > d) {\n d = curD\n true\n } else {\n false\n }\n }\n\n def main(args: Array[String]) {\n var p1 = 2\n var p2 = 3\n val q = readInt\n\n for (i <- 2 to 4) {\n anc(0)(i) = 1\n dep(i) = 1\n }\n\n var n = 4\n for (i <- 0 until q) {\n val x = readLine.toInt\n anc(0)(n + 1) = x\n anc(0)(n + 2) = x\n n += 2\n }\n\n for (p <- 5 to n) {\n dep(p)= dep(anc(0)(p)) + 1\n for (lv <- 1 until ancLevel) {\n anc(lv)(p) = anc(lv-1)(anc(lv-1)(p))\n }\n }\n\n n = 4\n for (i <- 0 until q) {\n if (check(n + 1, p1)) {\n p2 = n + 1\n } else if (check(n + 1, p2)) {\n p1 = n + 1\n }\n out.println(d)\n n += 2\n }\n out.flush()\n }\n}\n"}, {"source_code": "import java.util\nimport java.io.PrintWriter\n\nobject Main {\n var tokenizer = new util.StringTokenizer(\"\")\n val out = new PrintWriter(System.out)\n\n def readToken = {\n while (!tokenizer.hasMoreTokens) tokenizer = new util.StringTokenizer(readLine)\n tokenizer.nextToken\n }\n\n def readInt = readToken.toInt\n\n val ancLevel = 18\n val anc = Array.ofDim[Int](ancLevel, 1000000 + 20)\n val dep = Array.ofDim[Int](1000000 + 20)\n\n def getLca(x: Int, y: Int) = {\n var (a, b) = if (dep(x) >= dep(y)) (x, y) else (y, x)\n for (lv <- ancLevel - 1 to 0 by -1; if dep(a) - (1 << lv) >= dep(b)) a = anc(lv)(a)\n if (a == b) {\n a\n } else {\n for (lv <- ancLevel - 1 to 0 by -1; if anc(lv)(a)!= anc(lv)(b)) {\n a = anc(lv)(a)\n b = anc(lv)(b)\n }\n anc(0)(a)\n }\n }\n\n var d = 2\n\n def check(cur: Int, far: Int) = {\n val lca = getLca(cur, far)\n val curD = dep(cur) - dep(lca) + dep(far) - dep(lca)\n if (curD > d) {\n d = curD\n true\n } else {\n false\n }\n }\n\n def main(args: Array[String]) {\n var p1 = 2\n var p2 = 3\n val q = readLine.toInt\n\n for (i <- 2 to 4) {\n anc(0)(i) = 1\n dep(i) = 1\n }\n\n var n = 4\n for (i <- 0 until q) {\n val x = readLine.toInt\n anc(0)(n + 1) = x\n anc(0)(n + 2) = x\n n += 2\n }\n\n for (p <- 5 to n) {\n dep(p)= dep(anc(0)(p)) + 1\n for (lv <- 1 until ancLevel) {\n anc(lv)(p) = anc(lv-1)(anc(lv-1)(p))\n }\n }\n\n n = 4\n for (i <- 0 until q) {\n if (check(n + 1, p1)) {\n p2 = n + 1\n } else if (check(n + 1, p2)) {\n p1 = n + 1\n }\n out.println(d)\n n += 2\n }\n out.flush()\n }\n}"}], "negative_code": [], "src_uid": "2cbaa9bb315d1791b54f3e0fbd1cf140"} {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport Ordering.Implicits._\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def solve(): Unit = {\n val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)\n val tested = (for (i <- Range(0, k)) yield nextInt).toArray\n val sumk = tested.sum\n val first = math.min(n - k, n / 2 - tested.count(_ < y))\n if (first < 0 || sumk + first + (n - k - first) * y > x) {\n println(-1)\n } else {\n for (i <- 0 until first) {\n printf(\"%d \", 1)\n }\n for (i <- 0 until n - k - first) {\n printf(\"%d \", y)\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n", "positive_code": [{"source_code": "object B540 extends App {\n import java.util.Scanner\n\n type Input = (Int, Int, Int, Int, Int, List[Int])\n type Output = Option[List[Int]]\n\n def read(scanner: Scanner): Input = {\n import scanner._\n val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)\n (n, k, p, x, y, List.fill(k)(nextInt))\n }\n\n def solve(problem: Input): Output = {\n val (n, k, p, x, y, scores) = problem\n\n def isMedianSatisfied(s: List[Int]) = (s ::: scores).count(_ >= y) >= (n + 1)/2\n\n @scala.annotation.tailrec\n def score(newScores: List[Int]): List[Int] = if (newScores.length == n - k) {\n newScores\n } else if (isMedianSatisfied(newScores)) {\n score(1 :: newScores)\n } else {\n score(y :: newScores)\n }\n\n val solution = score(Nil)\n if (isMedianSatisfied(solution) && (solution ::: scores).sum <= x) Some(solution) else None\n }\n\n def format(result: Output): String = result map {_ mkString \" \"} getOrElse \"-1\"\n\n def apply(input: String): String = apply(new Scanner(input))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n}\n"}, {"source_code": "import Array._\n\nobject main extends App with fastIO {\n \n var Array(n, k, p, x, y) = readLine split(\" \") map(_.toInt)\n var a = Array.fill(k)(nextInt)\n \n var r = a.count(_ >= y) \n \n var b = Vector[Int]()\n for (i <- r until (n >> 1) + 1) b = b :+ y \n for (i <- a.length + b.length until n) b = b :+ 1\n \n if (b.length <= n - k && a.sum + b.sum <= x)\n println(b.mkString(\" \")) else \n println(-1)\n \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}"}, {"source_code": "object B540 extends App {\n import java.util.Scanner\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /***************************************************************************/\n type Input = (Int, Int, Int, Int, Int, List[Int])\n\n type Output = Option[List[Int]]\n\n def solve(input: Input): Output = {\n val (n, k, p, x, y, s) = input\n val numOfYs = ((n+1)/2 - s.count(_ >= y)) max 0 min (n-k)\n val numOf1s = n - k - numOfYs\n val solution = List.fill(numOfYs)(y) ::: List.fill(numOf1s)(1)\n val result = s ::: solution\n if (result.sum <= x && result.count(_ >= y) >= (n+1)/2) Some(solution) else None\n }\n\n def read(scanner: Scanner): Input = {\n import scanner._\n val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)\n (n, k, p, x, y, List.fill(k)(nextInt))\n }\n\n def format(result: Output): String = result map {_ mkString \" \"} getOrElse \"-1\"\n}\n"}, {"source_code": "object main{\n object Solver extends InputReader{\n def solve(){\n val n = getInt()\n val k = getInt()\n val p = getInt()\n val x = getInt()\n val y = getInt()\n\n val a = new Array[Int](n)\n for(i <- 0 to k - 1)\n a(i) = getInt()\n\n var s = a.sum\n for(i <- k to n - 1){\n val can = x - s\n val rest = n - 1 - i\n\n a(i) = Math.min(can - rest, y)\n s += a(i)\n }\n\n val b = a.sorted\n\n if(b(0) > 0 && b(n / 2) >= y){\n for(i <- k to n - 1)\n print(a(i) + \" \")\n println()\n }else{\n println(-1)\n }\n }\n }\n\n // TEMPLATE ------------------------\n\n def main(args: Array[String]){\n Solver.solve()\n }\n\n trait InputReader{\n import java.io._\n import java.util._\n protected val stream = System.in\n private val reader = new BufferedReader(new InputStreamReader(stream))\n private var tokenizer = new StringTokenizer(reader.readLine())\n\n def getStr(): String = {\n while(!tokenizer.hasMoreTokens())\n tokenizer = new StringTokenizer(reader.readLine())\n tokenizer.nextToken()\n }\n\n def getInt(): Int = getStr().toInt\n def getLong(): Long = getStr().toLong\n def getDouble(): Double = getStr().toDouble\n }\n}"}], "negative_code": [{"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport Ordering.Implicits._\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def solve(): Unit = {\n val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)\n val tested = (for (i <- Range(0, k)) yield nextInt).toArray\n val sumk = tested.sum\n val (first, second) = (n / 2 - tested.count(_ < y), (n + 1) / 2 - tested.count(_ >= y))\n if (first < 0 || second < 0 || sumk + first + second * y > x) {\n println(-1)\n } else {\n for (i <- 0 until first) {\n printf(\"%d \", 1)\n }\n for (i <- 0 until second) {\n printf(\"%d \", y)\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport Ordering.Implicits._\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def solve(): Unit = {\n val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)\n val tested = (for (i <- Range(0, k)) yield nextInt).toArray\n val sumk = tested.sum\n val first = math.min(n - k, n / 2 - tested.count(_ < y))\n println (first)\n if (first < 0 || sumk + first + (n - k - first) * y > x) {\n println(-1)\n } else {\n for (i <- 0 until first) {\n printf(\"%d \", 1)\n }\n for (i <- 0 until n - k - first) {\n printf(\"%d \", y)\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport Ordering.Implicits._\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def solve(): Unit = {\n val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)\n val tested = (for (i <- Range(0, k)) yield nextInt).toArray\n val sumk = tested.sum\n val (first, second) = (n / 2 - tested.count(_ < y), (n + 1) / 2 - tested.count(_ >= y))\n if (sumk + first + second * y > x) {\n println(-1)\n } else {\n for (i <- 0 until first) {\n printf(\"%d \", 1)\n }\n for (i <- 0 until second) {\n printf(\"%d \", y)\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "object B540 extends App {\n import java.util.Scanner\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /***************************************************************************/\n type Input = (Int, Int, Int, Int, Int, List[Int])\n\n type Output = Option[List[Int]]\n\n def solve(input: Input): Output = {\n val (n, k, p, x, y, s) = input\n val numOfYs = ((n+1)/2 - s.count(y <=)) max 0\n val numOf1s = n - k - numOfYs\n val best = List.fill(numOfYs)(y) ::: List.fill(numOf1s)(1)\n if ((s ::: best).sum <= x) Some(best) else None\n }\n\n def read(scanner: Scanner): Input = {\n import scanner._\n val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)\n (n, k, p, x, y, List.fill(k)(nextInt))\n }\n\n def format(result: Output): String = result map {_ mkString \" \"} getOrElse \"-1\"\n}\n"}, {"source_code": "object B540 extends App {\n import java.util.Scanner\n\n type Input = (Int, Int, Int, Int, List[Int])\n type Output = Option[List[Int]]\n\n def read(scanner: Scanner): Input = {\n import scanner._\n val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)\n (n, p, x, y, List.fill(k)(nextInt))\n }\n\n def solve(problem: Input): Output = {\n val (n, p, x, y, scores) = problem\n val (k, total) = (scores.length, scores.sum)\n val left = n - k\n if (total + left > x) {\n None\n } else {\n def solve(target: Int, buckets: Int): Option[List[Int]] = buckets match {\n case _ if target < 1 => None\n case 1 => when(1 <= target && target <= p)(List(target))\n case _ =>\n def score(s: Int) = solve(target - s, buckets - 1) map {s :: _} filter {strategy => buckets < left || median(strategy ::: scores) >= y}\n (p to 1 by -1) collectFirst Function.unlift(score)\n }\n solve(x - total, left)\n }\n }\n\n def median(l: List[Int]) = {\n require(l.length % 2 == 1)\n l.sorted.apply(l.length/2)\n }\n\n def when[A](predicate: Boolean)(f: => A): Option[A] = if (predicate) Some(f) else None\n\n def format(result: Output): String = result map {_ mkString \" \"} getOrElse \"-1\"\n\n def apply(input: String): String = apply(new Scanner(input))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n}\n"}, {"source_code": "object B540 extends App {\n import java.util.Scanner\n\n type Input = (Int, Int, Int, Int, List[Int])\n type Output = Option[List[Int]]\n\n def read(scanner: Scanner): Input = {\n import scanner._\n val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)\n (n, p, x, y, List.fill(k)(nextInt))\n }\n\n def solve(problem: Input): Output = {\n val (n, p, x, y, scores) = problem\n val (k, total) = (scores.length, scores.sum)\n val left = n - k\n if (total + left > x) {\n None\n } else {\n def solve(target: Int, buckets: Int): Option[List[Int]] = buckets match {\n case _ if target < 1 => None\n case 1 => when(1 <= target && target <= p)(List(target))\n case _ =>\n def score(s: Int) = solve(target - s, buckets - 1) map {s :: _} filter {strategy => buckets%2 == 0 || median(strategy ::: scores) >= y}\n (p to 1 by -1) collectFirst Function.unlift(score)\n }\n solve(x - total, left)\n }\n }\n\n def median(l: List[Int]) = {\n require(l.length % 2 == 1)\n l.sorted.apply(l.length/2 + 1)\n }\n\n def when[A](predicate: Boolean)(f: => A): Option[A] = if (predicate) Some(f) else None\n\n def format(result: Output): String = result map {_ mkString \" \"} getOrElse \"-1\"\n\n def apply(input: String): String = apply(new Scanner(input))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n}\n"}, {"source_code": "object B540 extends App {\n import java.util.Scanner\n\n type Input = (Int, Int, Int, Int, List[Int])\n type Output = Option[List[Int]]\n\n def read(scanner: Scanner): Input = {\n import scanner._\n val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)\n (n, p, x, y, List.fill(k)(nextInt))\n }\n\n def solve(problem: Input): Output = {\n val (n, p, x, y, scores) = problem\n val (k, total) = (scores.length, scores.sum)\n val left = n - k\n if (total + left > x) {\n None\n } else {\n def solve(target: Int, buckets: Int): Option[List[Int]] = buckets match {\n case _ if target < 1 => None\n case 1 => when(1 <= target && target <= p)(List(target))\n case _ =>\n def score(s: Int) = solve(target - s, buckets - 1) map {s :: _} filter {strategy => buckets < (x - total) || median(strategy ::: scores) >= y}\n (p to 1 by -1) collectFirst Function.unlift(score)\n }\n solve(x - total, left)\n }\n }\n\n def median(l: List[Int]) = {\n require(l.length % 2 == 1)\n l.sorted.apply(l.length/2 + 1)\n }\n\n def when[A](predicate: Boolean)(f: => A): Option[A] = if (predicate) Some(f) else None\n\n def format(result: Output): String = result map {_ mkString \" \"} getOrElse \"-1\"\n\n def apply(input: String): String = apply(new Scanner(input))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n}\n"}, {"source_code": "object B540 extends App {\n import java.util.Scanner\n\n type Input = (Int, Int, Int, Int, List[Int])\n type Output = Option[List[Int]]\n\n def read(scanner: Scanner): Input = {\n import scanner._\n val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)\n (n, p, x, y, List.fill(k)(nextInt))\n }\n\n def solve(problem: Input): Output = {\n val (n, p, x, y, scores) = problem\n val (k, total) = (scores.length, scores.sum)\n val left = n - k\n if (total + left > x) {\n None\n } else {\n def solve(target: Int, buckets: Int): Option[List[Int]] = buckets match {\n case _ if target < 1 => None\n case 1 => when(1 <= target && target <= p)(List(target))\n case _ =>\n def score(s: Int) = solve(target - s, buckets - 1) map {s :: _} filter {strategy => buckets < left || median(strategy ::: scores) >= y}\n (p to 1 by -1) collectFirst Function.unlift(score)\n }\n solve(x - total, left)\n }\n }\n\n def median(l: List[Int]) = {\n require(l.length % 2 == 1)\n l.sorted.apply(l.length/2 + 1)\n }\n\n def when[A](predicate: Boolean)(f: => A): Option[A] = if (predicate) Some(f) else None\n\n def format(result: Output): String = result map {_ mkString \" \"} getOrElse \"-1\"\n\n def apply(input: String): String = apply(new Scanner(input))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n}\n"}, {"source_code": "object B540 extends App {\n import java.util.Scanner\n\n type Input = (Int, Int, Int, Int, List[Int])\n type Output = Option[List[Int]]\n\n def read(scanner: Scanner): Input = {\n import scanner._\n val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)\n (n, p, x, y, List.fill(k)(nextInt))\n }\n\n def solve(problem: Input): Output = {\n val (n, p, x, y, scores) = problem\n val (k, total) = (scores.length, scores.sum)\n val left = n - k\n if (total + left > x) {\n None\n } else {\n def solve(target: Int, buckets: Int): Option[List[Int]] = buckets match {\n case _ if target < 1 => None\n case 1 if 1 <= target && target <= p => Some(List(target))\n case 1 => None\n case _ =>\n def score(s: Int) = solve(target - s, buckets - 1) map {s :: _}\n (p to 1 by -1) collectFirst Function.unlift(score)\n }\n val strategy = solve(x - total, left)\n strategy filter {s => median(s ::: scores) >= y}\n }\n }\n\n def median(l: List[Int]) = {\n require(l.length %2 == 1)\n l.sorted.apply(l.length/2 + 1)\n }\n\n def format(result: Output): String = result map {_ mkString \" \"} getOrElse \"-1\"\n\n def apply(input: String): String = apply(new Scanner(input))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n}\n"}], "src_uid": "f01d11bd231a7b2e7ca56de1df0f1272"} {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(a, b) = readLine().split(\" \").map(_.toLong).sorted\r\n\r\n val e = b - a\r\n val m =\r\n if (e == 0) 0\r\n else if (a % e == b % e) (a % e) min (e - a % e)\r\n else a\r\n\r\n println(s\"$e $m\")\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(a, b) = readLine().split(\" \").map(_.toLong).sorted\r\n\r\n val e = b - a\r\n val m =\r\n if (e == 0) 0\r\n else if (a % e == b % e) (a % e) min (e - a % e) min a\r\n else a\r\n\r\n println(s\"$e $m\")\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(a, b) = readLine().split(\" \").map(_.toLong).sorted\r\n\r\n val e = b - a\r\n val m =\r\n if (e == 0) 0\r\n else if (a % e == b % e) {\r\n if (a % e == 0) 0 else (e - a % e) min a\r\n } else a\r\n\r\n println(s\"$e $m\")\r\n }\r\n}\r\n"}], "src_uid": "994a9cb52cf0fdab72be068eab1b27ef"} {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P385B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Long = {\n val S = sc.nextLine\n val L = S.length\n \n @tailrec\n def loop(acc: Long, i: Int): Long = {\n val j = S.indexOf(\"bear\", i)\n if (j < 0) acc\n else loop(acc + (j - i + 1) * (L - j - 3), j + 1)\n }\n\n loop(0, 0)\n }\n\n out.println(solve)\n out.close\n}\n \n\n\n\n\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val str = in.next()\n val l = str.length\n println((0 until str.length).foldLeft(0L) {\n case(count, i) =>\n val index = str.indexOf(\"bear\", i)\n count + (if (index == -1) 0 else l - index - 3)\n })\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P385B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Long = {\n val S = sc.nextLine\n val L = S.length\n \n @tailrec\n def loop(acc: Long, i: Int): Long = {\n val j = S.indexOf(\"bear\", i)\n if (j < 0) acc\n else loop(acc + (j + 1) * (L - j - 3), j + 1)\n }\n\n loop(0, 0)\n }\n\n out.println(solve)\n out.close\n}\n \n\n\n\n\n"}], "src_uid": "240a2b88ded6016d0fd7157d0ee2beea"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, K = ni()\n val A = na(N)\n val D = Array.ofDim[Int](N - 1)\n REP(N - 1) { i =>\n D(i) = A(i + 1) - A(i)\n }\n sort(D)\n debug(D)\n val ans = sumL(D.take(max(0, N - K)))\n out.println(ans)\n }\n\n def sort(a: Array[Int]): Array[Int] = {\n val n = a.length\n REP(n) { i =>\n val j = scala.util.Random.nextInt(n - i) + i\n val tmp = a(i)\n a(i) = a(j)\n a(j) = tmp\n }\n java.util.Arrays.sort(a)\n a\n }\n}", "positive_code": [{"source_code": "//package codeforces.contest1197\n\nobject ArraySplitting {\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine().split(\" \").map(_.toInt)\n println(\n if (n == 1) {\n io.StdIn.readInt()\n 0\n }\n else {\n io.StdIn\n .readLine()\n .split(\" \")\n .map(_.toInt)\n .sliding(2)\n .map(arr => arr(1) - arr(0))\n .toArray\n .sorted\n .slice(0, n - k)\n .sum\n }\n )\n }\n}\n"}], "negative_code": [], "src_uid": "2895624e708159bc2a6f3e91140a6c45"} {"source_code": "\n\n object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n }\n \n class Main {\n import java.io._\n import java.util.StringTokenizer\n \n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n \n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n \n def solve(): Unit = {\n val N, K, X = ni()\n val A = na(N)\n \n val dp = Array.fill[SlideMax](X + 1)(new SlideMax(K))\n dp(0).add(0, 0)\n rep(N, 1) { i =>\n val a = A(i - 1)\n rep_r(X) { x =>\n if (dp(x).nonEmpty(i - 1)) dp(x + 1).add(i, dp(x).max(i - 1) + a)\n }\n }\n \n val ans = if (dp(X).nonEmpty(N)) dp(X).max(N) else -1\n out.println(ans)\n }\n \n // todo test\n /**\n * DPなんかでKの個数を維持しつつ区間の最大を探す時に使う\n * DP上で1個前の状態からとるなどするときはmax(i-1)のようにその時のインデックスをちゃんと渡さないといけないのに注意\n */\n class SlideMax(k: Int) {\n case class Entry(i: Int, v: Long)\n \n val queue = new java.util.ArrayDeque[Entry]()\n \n def nonEmpty(i: Int): Boolean = {\n maintenance(i)\n !queue.isEmpty\n }\n \n def max(i: Int): Long = {\n maintenance(i)\n queue.peek().v\n }\n \n def add(i: Int, x: Long): Unit = {\n maintenance(i)\n \n // 条件逆さまにすると最小になる\n while(!queue.isEmpty && queue.peekLast().v <= x) queue.removeLast()\n queue.addLast(Entry(i, x))\n }\n \n def maintenance(i: Int): Unit = {\n while (!queue.isEmpty && k < i - queue.peek().i + 1) queue.removeFirst()\n }\n }\n \n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n \n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n \n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n \n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n \n \n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n \n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n }", "positive_code": [{"source_code": "import java.io._\nimport java.util._\n\nobject F extends App {\n\tval n = InputReader.nextInt\n\tval k = InputReader.nextInt\n\tval x = InputReader.nextInt\n\tvar arr = Array.fill(n + 1)(0)\n\n\tfor(i <- 1 to n) arr(i) = InputReader.nextInt\n\n\tval prv = Array.fill(n + 1)(-1L)\n\tval cur = Array.fill(n + 1)(-1L)\n\n\tprv(0) = 0L\n\n\tfor (j <- 1 to x) {\n\t\tval q: Deque[Int] = new LinkedList[Int]()\n\n\t\tfor (i <- 0 to n) {\n\t\t\twhile (!q.isEmpty && i - q.getFirst > k)\n\t\t\t\tq.pollFirst\n\n\t\t\tcur(i) = if (q.isEmpty || prv(q.getFirst) == -1) -1 else prv(q.getFirst) + arr(i)\n\n\t\t\twhile (!q.isEmpty && prv(i) >= prv(q.getLast))\n\t\t\t\tq.pollLast\n\n\t\t\tq.addLast(i)\n\t\t}\n\n\t\tfor (i <- 0 to n) {\n\t\t\tprv(i) = cur(i)\n\t\t\tcur(i) = -1L\n\t\t}\n\t}\n\n\tprintln(prv.takeRight(k).max)\n}\n\nobject InputReader {\n\tval rd = new BufferedReader(new InputStreamReader(System.in), 32768);\n\tvar tk = new StringTokenizer(\"\")\n\n\tdef read() = {\n\t\twhile (!tk.hasMoreTokens)\n\t\t\ttk = new StringTokenizer(readLine)\n\n\t\ttk.nextToken\n\t}\n\n\tdef readLine() = rd.readLine\n\tdef nextInt() = read.toInt\n\tdef nextLong() = read.toLong\n\tdef nextDouble() = read.toDouble\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K, X = ni()\n val A = na(N)\n\n val dp = Array.fill[SlideMax](X + 1)(new SlideMax(K))\n dp(0).add(0, 0)\n rep(N, 1) { i =>\n val a = A(i - 1)\n rep_r(X) { x =>\n if (dp(x).nonEmpty(i - 1)) dp(x + 1).add(i, dp(x).max(i - 1) + a)\n }\n\n \"\"\n }\n\n val ans = if (dp(X).nonEmpty(N)) dp(X).max(N) else -1\n out.println(ans)\n }\n\n // todo test\n /**\n * DPなんかでKの個数を維持しつつ区間の最大を探す時に使う\n * DP上で1個前の状態からとるなどするときはmax(i-1)のようにその時のインデックスをちゃんと渡さないといけないのに注意\n */\n class SlideMax(k: Int) {\n case class Entry(i: Int, v: Long)\n\n val queue = new java.util.ArrayDeque[Entry]()\n\n def nonEmpty(i: Int): Boolean = {\n maintenance(i)\n !queue.isEmpty\n }\n \n def max(i: Int): Long = {\n maintenance(i)\n queue.peek().v\n }\n\n def add(i: Int, x: Long): Unit = {\n maintenance(i)\n\n // 条件逆さまにすると最小になる\n while(!queue.isEmpty && queue.peekLast().v < x) queue.removeLast()\n queue.addLast(Entry(i, x))\n }\n\n def maintenance(i: Int): Unit = {\n while (!queue.isEmpty && k < i - queue.peek().i + 1) queue.removeFirst()\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K, X = ni()\n val A = na(N)\n\n val dp = Array.fill[SlideMax](X + 1)(new SlideMax(K))\n dp(0).add(0, 0)\n rep(N, 1) { i =>\n val a = A(i - 1)\n rep_r(X) { x =>\n if (dp(x).nonEmpty(i - 1)) dp(x + 1).add(i, dp(x).max(i - 1) + a)\n }\n }\n\n val ans = if (dp(X).nonEmpty(N)) dp(X).max(N) else -1\n out.println(ans)\n }\n\n // todo test\n /**\n * DPなんかでKの個数を維持しつつ区間の最大を探す時に使う\n * DP上で1個前の状態からとるなどするときはmax(i-1)のようにその時のインデックスをちゃんと渡さないといけないのに注意\n */\n class SlideMax(k: Int) {\n case class Entry(i: Int, v: Long)\n\n val queue = new java.util.ArrayDeque[Entry]()\n\n def nonEmpty(i: Int): Boolean = {\n maintenance(i)\n !queue.isEmpty\n }\n \n def max(i: Int): Long = {\n maintenance(i)\n queue.peek().v\n }\n\n def add(i: Int, x: Long): Unit = {\n maintenance(i)\n\n // 条件逆さまにすると最小になる\n while(!queue.isEmpty && queue.peekLast().v < x) queue.removeLast()\n queue.addLast(Entry(i, x))\n }\n\n def maintenance(i: Int): Unit = {\n while (!queue.isEmpty && k < i - queue.peek().i + 1) queue.removeFirst()\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import java.io._\nimport java.util._\n\nobject F extends App {\n\tval n = InputReader.nextInt\n\tval k = InputReader.nextInt\n\tval x = InputReader.nextInt\n\tvar arr = Array.fill(n + 1)(0)\n\n\tfor(i <- 1 to n) arr(i) = InputReader.nextInt\n\n\tval prv = Array.fill(n + 1)(-1L)\n\tval cur = Array.fill(n + 1)(-1L)\n\n\tprv(0) = 0L\n\n\tfor (j <- 1 to x) {\n\t\tval q: Deque[Int] = new LinkedList[Int]()\n\n\t\tfor (i <- 0 to n) {\n\t\t\twhile (!q.isEmpty && i - q.getFirst > k)\n\t\t\t\tq.pollFirst\n\n\t\t\tcur(i) = if (q.isEmpty || prv(q.getFirst) == -1) -1 else prv(q.getFirst) + arr(i)\n\n\t\t\twhile (!q.isEmpty && prv(i) >= prv(q.getLast))\n\t\t\t\tq.pollLast\n\n\t\t\tq.addLast(i)\n\t\t}\n\n\t\tfor (i <- 0 to n) {\n\t\t\tprv(i) = cur(i)\n\t\t\tcur(i) = -1L\n\t\t}\n\t}\n\n\tprintln(prv.takeRight(k).max)\n}\n\nobject InputReader {\n\tval rd = new BufferedReader(new InputStreamReader(System.in), 32768);\n\tvar tk = new StringTokenizer(\"\")\n\n\tdef read() = {\n\t\twhile (!tk.hasMoreTokens)\n\t\t\ttk = new StringTokenizer(readLine)\n\n\t\ttk.nextToken\n\t}\n\n\tdef readLine() = rd.readLine\n\tdef nextInt() = read.toInt\n\tdef nextLong() = read.toLong\n\tdef nextDouble() = read.toDouble\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K, X = ni()\n val A = na(N)\n\n val dp = Array.fill[SlideMax](X + 1)(new SlideMax(K))\n dp(0).add(0, 0)\n rep(N, 1) { i =>\n val a = A(i - 1)\n rep_r(X) { x =>\n if (dp(x).nonEmpty(i - 1)) dp(x + 1).add(i, dp(x).max(i - 1) + a)\n }\n }\n\n val ans = if (dp(X).nonEmpty(N)) dp(X).max(N) else -1\n out.println(ans)\n }\n\n // todo test\n /**\n * DPなんかでKの個数を維持しつつ区間の最大を探す時に使う\n * DP上で1個前の状態からとるなどするときはmax(i-1)のようにその時のインデックスをちゃんと渡さないといけないのに注意\n */\n class SlideMax(k: Int) {\n case class Entry(i: Int, v: Long)\n\n val queue = new java.util.ArrayDeque[Entry]()\n\n def nonEmpty(i: Int): Boolean = {\n maintenance(i)\n !queue.isEmpty\n }\n \n def max(i: Int): Long = {\n maintenance(i)\n queue.peek().v\n }\n\n def add(i: Int, x: Long): Unit = {\n maintenance(i)\n\n // 条件逆さまにすると最小になる\n while(!queue.isEmpty && queue.peekLast().v <= x) queue.removeLast()\n queue.addLast(Entry(i, x))\n }\n\n def maintenance(i: Int): Unit = {\n while (!queue.isEmpty && k < i - queue.peek().i + 1) queue.removeFirst()\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import java.io._\nimport java.util._\n\nobject F extends App {\n\tval n = InputReader.nextInt\n\tval k = InputReader.nextInt\n\tval x = InputReader.nextInt\n\tvar arr = Array.fill(n + 1)(0)\n\n\tfor(i <- 1 to n) arr(i) = InputReader.nextInt\n\n\tval prv = Array.fill(n + 1)(-1L)\n\tval cur = Array.fill(n + 1)(-1L)\n\n\tprv(0) = 0L\n\n\tfor (j <- 1 to x) {\n\t\tval q: Deque[Int] = new ArrayDeque[Int]()\n\n\t\tfor (i <- 0 to n) {\n\t\t\twhile (!q.isEmpty && i - q.getFirst > k)\n\t\t\t\tq.pollFirst\n\n\t\t\tcur(i) = if (q.isEmpty || prv(q.getFirst) == -1) -1 else prv(q.getFirst) + arr(i)\n\n\t\t\twhile (!q.isEmpty && prv(i) >= prv(q.getLast))\n\t\t\t\tq.pollLast\n\n\t\t\tq.addLast(i)\n\t\t}\n\n\t\tfor (i <- 0 to n) {\n\t\t\tprv(i) = cur(i)\n\t\t\tcur(i) = -1L\n\t\t}\n\t}\n\n\tprintln(prv.takeRight(k).max)\n}\n\nobject InputReader {\n\tval rd = new BufferedReader(new InputStreamReader(System.in), 32768);\n\tvar tk = new StringTokenizer(\"\")\n\n\tdef read() = {\n\t\twhile (!tk.hasMoreTokens)\n\t\t\ttk = new StringTokenizer(readLine)\n\n\t\ttk.nextToken\n\t}\n\n\tdef readLine() = rd.readLine\n\tdef nextInt() = read.toInt\n\tdef nextLong() = read.toLong\n\tdef nextDouble() = read.toDouble\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K, X = ni()\n val A = na(N)\n\n val dp = Array.fill[SlideMax](X + 1)(new SlideMax(K))\n dp(0).add(0, 0)\n rep(N, 1) { i =>\n val a = A(i - 1)\n rep_r(X) { x =>\n if (dp(x).nonEmpty(i - 1)) dp(x + 1).add(i, dp(x).max(i - 1) + a)\n }\n }\n\n val ans = if (dp(X).nonEmpty(N)) dp(X).max(N) else -1\n out.println(ans)\n }\n\n // todo test\n /**\n * DPなんかでKの個数を維持しつつ区間の最大を探す時に使う\n * DP上で1個前の状態からとるなどするときはmax(i-1)のようにその時のインデックスをちゃんと渡さないといけないのに注意\n */\n class SlideMax(k: Int) {\n case class Entry(i: Int, v: Long)\n\n val queue = new java.util.ArrayDeque[Entry]()\n\n def nonEmpty(i: Int): Boolean = {\n maintenance(i)\n !queue.isEmpty\n }\n \n def max(i: Int): Long = {\n maintenance(i)\n queue.peek().v\n }\n\n def add(i: Int, x: Long): Unit = {\n maintenance(i)\n\n // 条件逆さまにすると最小になる\n while(!queue.isEmpty && queue.peekLast().v < x) queue.removeLast()\n queue.addLast(Entry(i, x))\n }\n\n def maintenance(i: Int): Unit = {\n if (!queue.isEmpty && k < i - queue.peek().i + 1) queue.poll()\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "c1d48f546f79b0fd58539a1eb32917dd"} {"source_code": "import scala.annotation.tailrec\nimport scala.io.Source\n\nobject abcString extends App{\n val strings = for (str <- Source.stdin.getLines().drop(1)) yield str\n\n def yesNo(str: List[Char]): Boolean = {\n lazy val firstCount = str.count(_ == str.head)\n lazy val lastCount = str.count(_ == str.last)\n\n @tailrec\n def bracesMatch(openBraces: Int, first: Char, last: Char, remaining: List[Char]): Boolean = {\n if (openBraces >= 0)\n remaining match {\n case Nil => if (openBraces == 0) true else false\n case c :: cs => {\n val newOpenBraces = {\n if (c == first) openBraces + 1\n else if (c == last) openBraces - 1\n else if (firstCount > lastCount) openBraces - 1\n else openBraces + 1\n }\n bracesMatch(newOpenBraces, first, last, cs)\n }\n }\n else false\n }\n bracesMatch(0, str.head, str.last, str)\n }\n\n for (str <- strings) {\n val res =\n if (yesNo(str.toCharArray.toList)) \"YES\"\n else \"NO\"\n println(s\"$res\")\n }\n}\n", "positive_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.io.Source\n\nobject abcString extends App{\n val strings = for (str <- Source.stdin.getLines().drop(1)) yield str\n\n def yesNo(str: List[Char]): Boolean = {\n @tailrec\n def bracesMatch(openBraces: Int, first: Char, last: Char, remaining: List[Char]): Boolean = {\n if (openBraces >= 0)\n remaining match {\n case Nil => if (openBraces == 0) true else false\n case c :: cs =>\n if (c == first) bracesMatch(openBraces + 1, first, last, cs)\n else if (c == last) bracesMatch(openBraces - 1, first, last, cs)\n else if (str.count(_ == first) > str.count(_ == last)) bracesMatch(openBraces - 1, first, last, cs)\n else bracesMatch(openBraces + 1, first, last, cs)\n }\n else false\n }\n bracesMatch(0, str.head, str.last, str)\n }\n\n for (str <- strings) {\n val res =\n if (yesNo(str.toCharArray.toList)) \"YES\"\n else \"NO\"\n println(s\"$res\")\n }\n}\n"}], "negative_code": [], "src_uid": "4d24aaf5ebf70265b027a6af86e09250"} {"source_code": "/**\n * Created by IntelliJ IDEA.\n * User: ymatsux\n * Date: 12/05/06\n * Time: 2:16\n * To change this template use File | Settings | File Templates.\n */\n\nimport java.util.Scanner\nimport scala.collection.mutable\n\nobject CF105B {\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val userToMaxScoreBuilder = mutable.Map.empty[String, Int]\n for (i <- 0 until n) {\n val user = sc.next()\n val score = sc.nextInt()\n userToMaxScoreBuilder(user) = math.max(score, userToMaxScoreBuilder.getOrElse(user, 0))\n }\n val userToMaxScore = userToMaxScoreBuilder.toMap\n val numberOfUsers = userToMaxScore.keys.size\n println(numberOfUsers)\n\n val scores = userToMaxScore.values.toArray\n for (user <- userToMaxScore.keys) {\n val maxScore = userToMaxScore(user)\n val countAbove = scores.count(_ > maxScore)\n if (countAbove <= numberOfUsers * 1 / 100) {\n println(user + \" \" + \"pro\")\n } else if (countAbove <= numberOfUsers * 10 / 100) {\n println(user + \" \" + \"hardcore\")\n } else if (countAbove <= numberOfUsers * 20 / 100) {\n println(user + \" \" + \"average\")\n } else if (countAbove <= numberOfUsers * 50 / 100) {\n println(user + \" \" + \"random\")\n } else {\n println(user + \" \" + \"noob\")\n }\n }\n }\n}", "positive_code": [{"source_code": "import java.util.Scanner\nimport scala.math.max\nimport scala.collection.mutable\n\nobject CF105B {\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val userToMaxScoreBuilder = mutable.Map.empty[String, Int]\n for (i <- 0 until n) {\n val user = sc.next()\n val score = sc.nextInt()\n userToMaxScoreBuilder(user) = max(score, userToMaxScoreBuilder.getOrElse(user, 0))\n }\n val userToMaxScore = userToMaxScoreBuilder.toMap\n val numberOfUsers = userToMaxScore.keys.size\n println(numberOfUsers)\n\n val scores = userToMaxScore.values\n for (user <- userToMaxScore.keys) {\n val maxScore = userToMaxScore(user)\n val countAbove = scores.count(_ > maxScore)\n if (countAbove <= numberOfUsers * 1 / 100) {\n println(user + \" \" + \"pro\")\n } else if (countAbove <= numberOfUsers * 10 / 100) {\n println(user + \" \" + \"hardcore\")\n } else if (countAbove <= numberOfUsers * 20 / 100) {\n println(user + \" \" + \"average\")\n } else if (countAbove <= numberOfUsers * 50 / 100) {\n println(user + \" \" + \"random\")\n } else {\n println(user + \" \" + \"noob\")\n }\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.math.max\nimport scala.collection.mutable\n\nobject CF105B {\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val userToMaxScoreBuilder = mutable.Map.empty[String, Int]\n for (i <- 0 until n) {\n val user = sc.next()\n val score = sc.nextInt()\n userToMaxScoreBuilder(user) = max(score, userToMaxScoreBuilder.getOrElse(user, 0))\n }\n val userToMaxScore = userToMaxScoreBuilder.toMap\n val numberOfUsers = userToMaxScore.keys.size\n println(numberOfUsers)\n for (user <- userToMaxScore.keys) {\n val maxScore = userToMaxScore(user)\n val countAbove = userToMaxScore.values.count(_ > maxScore)\n if (countAbove <= numberOfUsers * 1 / 100) {\n println(user + \" \" + \"pro\")\n } else if (countAbove <= numberOfUsers * 10 / 100) {\n println(user + \" \" + \"hardcore\")\n } else if (countAbove <= numberOfUsers * 20 / 100) {\n println(user + \" \" + \"average\")\n } else if (countAbove <= numberOfUsers * 50 / 100) {\n println(user + \" \" + \"random\")\n } else {\n println(user + \" \" + \"noob\")\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "0430fa56ec7f97efaf9d37096f72bcf8"} {"source_code": "object BTheNumberOnTheBoard extends App {\n val k: Int = scala.io.StdIn.readLine.toInt\n val n: String = scala.io.StdIn.readLine\n\n var cnt = Array.fill(10){0}\n var cur = n.foldLeft(0) { (cur, c) =>\n val digit = c - '0'\n cnt(digit) = cnt(digit) + 1\n cur + digit\n }\n\n var ans = 0\n for {\n i <- 0 until 10; j <- 0 until cnt(i)\n if cur < k\n } {\n ans = ans + 1\n cur = cur + 9 - i\n }\n\n print(ans)\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main extends App {\n\n val k = StdIn.readLine().toInt\n val n = StdIn.readLine().sortWith(_ < _)\n\n val sum = n.foldLeft(0)((z: Int,c: Char) => {\n z + c - 48\n })\n\n var diff = k - sum\n var count = 0\n while(diff > 0 && count < n.length) {\n diff = diff - (9 - (n.charAt(count) - 48))\n count = count + 1\n }\n println(count)\n\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(k) = readInts(1)\n val n = readLine.map(_ - '0').sorted\n\n var sum = n.sum\n\n var i = 0\n while (i < n.length && sum < k) {\n sum += 9 - n(i)\n i += 1\n }\n\n println(i)\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject Main extends App {\n\n val k = StdIn.readLine().toInt\n val n = StdIn.readLine().sortWith(_ < _)\n\n val sum = n.foldLeft(0)((z: Int,c: Char) => {\n z + c - 48\n })\n\n var diff = k - sum\n var count = 0\n\n while(diff > 0 && count < n.length) {\n diff = diff - (n.charAt(count) - 48)\n count = count + 1\n }\n println(count)\n\n}\n"}], "src_uid": "d7e6e5042b8860bb2470d5a493b0adf6"} {"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.io.FileWriter\nimport java.io.PrintWriter\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var s1 = readLine;\n var s2 = readLine;\n for (i <- 0 until s2.length) {\n if (s2(i) != ' ' && s1.contains(s2(i))) {\n s1 = s1.replaceFirst(s2(i).toString, \"\");\n } else if (s2(i) != ' ') {\n println(\"NO\");\n return;\n }\n }\n println(\"YES\");\n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val text = in.next.filter(_ != ' ').groupBy(identity).map(i => i._1 -> i._2.length)\n val message = in.next.filter(_ != ' ').groupBy(identity).map(i => i._1 -> i._2.length)\n if (message.keys.forall(i => text.getOrElse(i, 0) >= message(i)))\n println(\"YES\")\n else \n println(\"NO\")\n\n}\n\n\n"}], "negative_code": [{"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.io.FileWriter\nimport java.io.PrintWriter\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var s1 = readLine;\n var s2 = readLine;\n for (i <- 0 until s2.length) {\n if (s2(i) != ' ' && s1.contains(s2(i))) {\n s1.replace(s2(i).toString, \"\");\n } else if (s2(i) != ' ') {\n println(\"NO\");\n return;\n }\n }\n println(\"YES\");\n }\n}"}, {"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.io.FileWriter\nimport java.io.PrintWriter\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var s1 = readLine;\n var s2 = readLine;\n for (i <- 0 until s2.length) {\n if (s2(i) != ' ' && s1.contains(s2(i))) {\n s1 = s1.replace(s2(i).toString, \"\");\n } else if (s2(i) != ' ') {\n println(\"NO\");\n return;\n }\n }\n println(\"YES\");\n }\n}"}], "src_uid": "b1ef19d7027dc82d76859d64a6f43439"} {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val s = readLine()\r\n\r\n val k = {\r\n val cs = Array.fill(26)(0)\r\n s.foreach(c => cs(c - 'a') += 1)\r\n\r\n val (c1, c2) = (cs.count(_ == 1), cs.count(_ > 1))\r\n\r\n c2 + c1 / 2\r\n }\r\n\r\n println(k)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main {\n implicit class Rep(n: Int) {\n def times[A](f: => A) { 1 to n foreach (_ => f) }\n }\n def main(args: Array[String]) = {\n StdIn.readInt.times {\n def f(string: String) = {\n val (gt2, rest) =\n (string.groupBy(identity) mapValues (_.length)).partition(kv =>\n kv._2 >= 2\n )\n println(gt2.size + (rest.size / 2))\n }\n f(StdIn.readLine)\n }\n }\n}\n"}], "negative_code": [], "src_uid": "a6b760941ab8be2c32c6dc66c623ea0e"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt).sorted\n val first = data.take(n / 2 + n % 2)\n val second = data.drop(first.length)\n val result = Array.ofDim[Int](n)\n (0 until n by 2).foreach { i =>\n result(i) = first(i / 2)\n }\n (1 until n by 2).foreach { i =>\n result(i) = second(i / 2)\n }\n println(result.mkString(\" \"))\n}", "positive_code": [{"source_code": "import java.util\n\nimport scala.collection.JavaConverters._\n\nobject ZSort {\n // https://codeforces.com/problemset/problem/652/B\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val arr = io.StdIn.readLine().split(\" \").map(_.toInt)\n\n if (n == 1) {\n println(arr.mkString)\n } else {\n val newArr = new util.ArrayList[Int](n)\n arr.zipWithIndex.foreach { case (curr, i) =>\n if (i == 0) {\n newArr.add(arr.head)\n } else {\n val prev = newArr.get(i - 1)\n if ((i + 1) % 2 == 0) {\n // even\n if (curr < prev) {\n newArr.add(prev)\n newArr.set(i - 1, curr)\n } else {\n newArr.add(curr)\n }\n } else {\n // odd\n if (curr > prev) {\n newArr.add(prev)\n newArr.set(i - 1, curr)\n } else {\n newArr.add(curr)\n }\n }\n }\n }\n\n println(newArr.asScala.mkString(\" \"))\n }\n }\n}\n"}], "negative_code": [], "src_uid": "2401d34db475853661d6e1e1cb5a8216"} {"source_code": "object Main332B {\n def readInts = readLine.split(\" \")map(_.toInt)\n def main(args: Array[String]) {\n val Array(n, k) = readInts\n val arr = readInts\n val sums = Array.ofDim[BigInt](n)\n var currentSum = BigInt(0)\n for (i <- (n-1) to 0 by -1) {\n currentSum += arr(i)\n if (i < n-k) currentSum -= arr(i+k)\n sums(i) = currentSum\n }\n var maxB = n-k\n var resA = n-k*2\n var resB = n-k\n for(a <- n-2*k to 0 by -1) {\n if(sums(a+k) >= sums(maxB)) maxB = a+k\n if(sums(a) + sums(maxB) >= sums(resA) + sums(resB)) {\n resA = a\n resB = maxB\n }\n }\n println((resA+1) + \" \" + (resB+1))\n }\n\n}", "positive_code": [{"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\n/**\n * @author kperikov\n */\nobject B_332 {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def partialSum(ints: Array[Int]): Array[Long] = {\n val sums = new Array[Long](ints.length)\n sums(0) = ints(0)\n for (i <- 1 until ints.length) {\n sums(i) = sums(i - 1) + ints(i)\n }\n sums\n }\n\n def sum(ints: Array[Long], x: Int, y: Int): Long = {\n x match {\n case 0 => ints(y)\n case _ => ints(y) - ints(x - 1)\n }\n }\n\n def solve = {\n val n = nextInt\n val k = nextInt\n val arr = new Array[Int](n)\n for (i <- 0 until n) {\n arr(i) = nextInt\n }\n val partialSums = partialSum(arr)\n var ans = (n - 2 * k, n - k)\n var max = sum(partialSums, n - 2 * k, n - k - 1) + sum(partialSums, n - k, n - 1)\n var suff = (n - k, sum(partialSums, n - k, n - 1))\n for (i <- n - 2 * k - 1 to 0 by -1) {\n var current = sum(partialSums, i + k, i + 2 * k - 1)\n if (current >= suff._2)\n suff = (i + k, current)\n current = sum(partialSums, i, i + k - 1) + suff._2\n if (current >= max) {\n max = current\n ans = (i, suff._1)\n }\n }\n println((ans._1 + 1) + \" \" + (ans._2 + 1))\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n}\n"}, {"source_code": "object main {\n def main (args : Array[String]) {\n val line = readLine() split \" \" map (_.toInt)\n val n = line(0)\n val k = line(1)\n val a = readLine() split \" \" map (_.toInt)\n\n val sums = new Array[Long](n)\n \n sums(0) = a.take(k).sum\n for(i <- k until n)\n sums(i - k + 1) = sums(i - k) - a(i - k) + a(i)\n \n val best = new Array[Long](n)\n val father = new Array[Int](n)\n \n best(n - k) = sums(n - k)\n father(n - k) = n - k\n for(i <- (0 until (n - k)) reverse) \n if(best(i + 1) > sums(i)) {\n best(i) = best(i + 1)\n father(i) = father(i + 1)\n }\n else {\n best(i) = sums(i)\n father(i) = i\n }\n\n var answer = (0, father(k))\n var absurdity = sums(0) + best(k)\n\n for(i <- 1 to (n - 2 * k))\n if(absurdity < sums(i) + best(i + k)) {\n absurdity = sums(i) + best(i + k)\n answer = (i, father(i + k))\n }\n\n println((answer._1 + 1) + \" \" + (answer._2 + 1))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val line = in.next().split(' ').map(_.toLong)\n val sliding = Array.ofDim[Long](n - k + 1)\n sliding(0) = line.take(k).sum\n\n (k until n).foreach { i => sliding(i - k + 1) = sliding(i - k) + line(i) - line(i - k) }\n val partSum = sliding.reverse.scanLeft(0l){ case(a, b) => Math.max(a, b) }.tail.reverse\n val max = (0 until sliding.length - k).foldLeft(0l) {\n case(max, i) =>\n Math.max(max, sliding(i) + partSum(i + k))\n }\n\n val index = (0 until sliding.length - k).find {\n i => sliding(i) + partSum(i + k) == max\n }.get\n\n// println(sliding.toList)\n// println(partSum.toList)\n// println(index)\n// println(partSum(index + k))\n\n val j = ((index + k) until sliding.length).find(i => sliding(i) == partSum(index + k)).get\n\n println(s\"${index + 1} ${j + 1}\")\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val line = in.next().split(' ').map(_.toInt)\n val sliding = Array.ofDim[Int](n - k + 1)\n sliding(0) = line.take(k).sum\n\n (k until n).foreach { i => sliding(i - k + 1) = sliding(i - k) + line(i) - line(i - k) }\n val partSum = sliding.reverse.scanLeft(0){ case(a, b) => Math.max(a, b) }.tail.reverse\n val max = (0 until sliding.length - k).foldLeft(0) {\n case(max, i) =>\n Math.max(max, sliding(i) + partSum(i + k - 1))\n }\n\n val index = (0 until sliding.length - k).find {\n i => sliding(i) + partSum(i + k - 1) == max\n }.get\n \n val j = ((index + k - 1) until sliding.length).find(i => sliding(i) == partSum(index + k - 1)).get\n\n println(max)\n println(line.toList)\n println(sliding.toList)\n println(partSum.toList)\n println(s\"$index $j\")\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val line = in.next().split(' ').map(_.toInt)\n val sliding = Array.ofDim[Int](n - k + 1)\n sliding(0) = line.take(k).sum\n\n (k until n).foreach { i => sliding(i - k + 1) = sliding(i - k) + line(i) - line(i - k) }\n val partSum = sliding.reverse.scanLeft(0){ case(a, b) => Math.max(a, b) }.tail.reverse\n val max = (0 until sliding.length - k).foldLeft(0) {\n case(max, i) =>\n Math.max(max, sliding(i) + partSum(i + k - 1))\n }\n\n val index = (0 until sliding.length - k).find {\n i => sliding(i) + partSum(i + k - 1) == max\n }.get\n \n val j = ((index + k - 1) until sliding.length).find(i => sliding(i) == partSum(index + k - 1)).get\n\n println(s\"$index $j\")\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val line = in.next().split(' ').map(_.toInt)\n val sliding = Array.ofDim[Int](n - k + 1)\n sliding(0) = line.take(k).sum\n\n (k until n).foreach { i => sliding(i - k + 1) = sliding(i - k) + line(i) - line(i - k) }\n val partSum = sliding.reverse.scanLeft(0){ case(a, b) => Math.max(a, b) }.tail.reverse\n val max = (0 until sliding.length - k).foldLeft(0) {\n case(max, i) =>\n Math.max(max, sliding(i) + partSum(i + k))\n }\n\n val index = (0 until sliding.length - k).find {\n i => sliding(i) + partSum(i + k) == max\n }.get\n\n// println(sliding.toList)\n// println(partSum.toList)\n// println(index)\n// println(partSum(index + k))\n\n val j = ((index + k) until sliding.length).find(i => sliding(i) == partSum(index + k)).get\n\n println(s\"${index + 1} ${j + 1}\")\n}\n"}, {"source_code": "object main {\n def main (args : Array[String]) {\n val line = readLine() split \" \" map (_.toInt)\n val n = line(0)\n val k = line(1)\n val a = readLine() split \" \" map (_.toInt)\n\n val sums = new Array[Long](n)\n \n sums(0) = a.take(k).sum\n for(i <- k until n)\n sums(i - k + 1) = sums(i - k) - a(i - k) + a(i)\n \n val best = new Array[Long](n)\n val father = new Array[Int](n)\n \n best(n - k) = sums(n - k)\n father(n - k) = n - k\n for(i <- (0 until (n - k)) reverse) \n if(best(i + 1) > sums(i)) {\n best(i) =best(i + 1)\n father(i) = father(i + 1)\n }\n else {\n best(i) = sums(i)\n father(i) = i\n }\n\n var answer = (0, 0)\n var absurdity = 0 : Long\n\n for(i <- 0 until (n - 2 * k + 1))\n if(absurdity < sums(i) + best(i + k)) {\n absurdity = sums(i) + best(i + k)\n answer = (i, father(i + k))\n }\n\n println((answer._1 + 1) + \" \" + (answer._2 + 1))\n }\n}\n"}, {"source_code": "object main {\n def main (args : Array[String]) {\n val line = readLine() split \" \" map (_.toInt)\n val n = line(0)\n val k = line(1)\n val a = readLine() split \" \" map (_.toInt)\n\n val sums = new Array[Int](n + 1)\n \n sums(0) = a.take(k).sum\n for(i <- k until n)\n sums(i - k + 1) = sums(i - k) - a(i - k) + a(i)\n \n val best = new Array[Int](n)\n val father = new Array[Int](n)\n \n best(n - k) = sums(n - k)\n father(n - k) = n - k\n for(i <- (0 until (n - k)) reverse) \n if(best(i + 1) > sums(i)) {\n best(i) =best(i + 1)\n father(i) = father(i + 1)\n }\n else {\n best(i) = sums(i)\n father(i) = i\n }\n\n var answer = (0, 0)\n var absurdity = 0\n\n for(i <- 0 until (n - 2 * k + 1))\n if(absurdity < sums(i) + best(i + k)) {\n absurdity = sums(i) + best(i + k)\n answer = (i, father(i + k))\n }\n\n println((answer._1 + 1) + \" \" + (answer._2 + 1))\n }\n}\n"}, {"source_code": "object main {\n def main (args : Array[String]) {\n val line = readLine() split \" \" map (_.toInt)\n val n = line(0)\n val k = line(1)\n val a = readLine() split \" \" map (_.toInt)\n\n val sums = new Array[Int](n + 1)\n \n sums(0) = a.take(k).sum\n for(i <- k until n)\n sums(i - k + 1) = sums(i - k) - a(i - k) + a(i)\n \n val best = new Array[Int](n + 1)\n val father = new Array[Int](n + 1)\n \n best(n - k) = sums(n - k)\n father(n - k) = n - k\n for(i <- (0 to (n - k)) reverse) \n if(best(i + 1) > sums(i)) {\n best(i) =best(i + 1)\n father(i) = father(i + 1)\n }\n else {\n best(i) = sums(i)\n father(i) = i\n }\n\n var answer = (0, 0)\n var absurdity = 0\n\n for(i <- 0 until (n - 2 * k))\n if(absurdity < sums(i) + best(i + k)) {\n absurdity = sums(i) + best(i + k)\n answer = (i, father(i + k))\n }\n\n println((answer._1 + 1) + \" \" + (answer._2 + 1))\n }\n}\n"}, {"source_code": "object main {\n def main (args : Array[String]) {\n val line = readLine() split \" \" map (_.toInt)\n val n = line(0)\n val k = line(1)\n val a = readLine() split \" \" map (_.toInt)\n\n val sums = new Array[Long](n)\n \n sums(0) = a.take(k).sum\n for(i <- k until n)\n sums(i - k + 1) = sums(i - k) - a(i - k) + a(i)\n \n val best = new Array[Long](n)\n val father = new Array[Int](n)\n \n best(n - k) = sums(n - k)\n father(n - k) = n - k\n for(i <- (0 until (n - k)) reverse) \n if(best(i + 1) > sums(i)) {\n best(i) = best(i + 1)\n father(i) = father(i + 1)\n }\n else {\n best(i) = sums(i)\n father(i) = i\n }\n\n var answer = (0, k)\n var absurdity = sums(0) + best(k)\n\n for(i <- 1 to (n - 2 * k))\n if(absurdity < sums(i) + best(i + k)) {\n absurdity = sums(i) + best(i + k)\n answer = (i, father(i + k))\n }\n\n println((answer._1 + 1) + \" \" + (answer._2 + 1))\n }\n}\n"}, {"source_code": "object Main332B {\n def readInts = readLine.split(\" \")map(_.toInt)\n def main(args: Array[String]) {\n val Array(n, k) = readInts\n val arr = readInts\n val sums = Array.ofDim[Int](n)\n var currentSum = 0\n for (i <- (n-1) to 0 by -1) {\n currentSum += arr(i)\n if (i < n-k) currentSum -= arr(i+k)\n sums(i) = currentSum\n }\n var maxB = n-k\n var resA = n-k*2\n var resB = n-k\n for(a <- n-2*k to 0 by -1) {\n if(sums(a+k) >= sums(maxB)) maxB = a+k\n if(sums(a) + sums(maxB) >= sums(resA) + sums(resB)) {\n resA = a\n resB = maxB\n }\n }\n println((resA+1) + \" \" + (resB+1))\n }\n\n}"}, {"source_code": "object Main332B {\n def readInts = readLine.split(\" \")map(_.toInt)\n def main(args: Array[String]) {\n val Array(n, k) = readInts\n val arr = readInts\n val sums = Array.ofDim[Long](n)\n var currentSum = 0\n for (i <- (n-1) to 0 by -1) {\n currentSum += arr(i)\n if (i < n-k) currentSum -= arr(i+k)\n sums(i) = currentSum\n }\n var maxB = n-k\n var resA = n-k*2\n var resB = n-k\n for(a <- n-2*k to 0 by -1) {\n if(sums(a+k) >= sums(maxB)) maxB = a+k\n if(sums(a) + sums(maxB) >= sums(resA) + sums(resB)) {\n resA = a\n resB = maxB\n }\n }\n println((resA+1) + \" \" + (resB+1))\n }\n\n}"}], "src_uid": "74095fe82bd22257eeb97e1caf586499"} {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = StdIn.readLine.toInt\n val a = StdIn.readLine.split(\" \").map(_.toInt).sorted\n println(a((a.length - 1) / 2))\n }\n}\n", "positive_code": [{"source_code": "object A extends App {\n val n = scala.io.StdIn.readInt()\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sortWith(_ > _)\n\n println(a(n / 2))\n}\n"}, {"source_code": "object _984A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val as = io.read[Vector[Int]].sorted\n val ans = as((as.length - 1)/2)\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn\n\nobject A extends App {\n\n val numbers = {\n StdIn.readLine()\n StdIn.readLine().split(\" \").map(_.toInt)\n }.sorted\n\n val numbersCount = numbers.length\n\n val numberIndex = if (numbersCount % 2 == 0) {\n (numbersCount / 2) - 1\n } else {\n numbersCount / 2\n }\n println(numbers(numberIndex))\n}"}, {"source_code": "\nimport scala.io.StdIn\n\nobject Game extends App {\n\n val n = StdIn.readInt()\n val arr = StdIn.readLine().split(\" \").map(_.toInt)\n\n print(impl(n, arr))\n\n def impl(n: Int, arr: Array[Int]): Int = {\n val sorted: Array[Int] = arr.sorted.reverse\n sorted(n / 2)\n }\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject A extends App {\n\n val numbers = {\n StdIn.readLine()\n StdIn.readLine().split(\" \").map(_.toInt)\n }.sorted\n\n val numbersCount = numbers.length\n\n val numberIndex = numbersCount / 2\n\n println(numbers(numberIndex))\n}\n"}, {"source_code": "object A extends App {\n val n = scala.io.StdIn.readInt()\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n\n println(a(n / 2))\n}\n"}], "src_uid": "f93a8bd64a405233342f84542fce314d"} {"source_code": "import scala.io.StdIn._\n\nobject Main {\n def getMS(b: Int): Int = {\n var k = 0;\n var a = b;\n while(a > 0) {\n a = (a >> 1);\n k = k + 1;\n }\n k\n }\n def main(args: Array[String]): Unit = {\n val t = readInt\n (0 until t).foreach { _ =>\n val n = readInt\n val a = readLine.split(\" \").map(_.toInt)\n val result: Long = a.groupBy(getMS(_)).map { case (a, b) => (b.size.toLong * (b.size.toLong - 1)) / 2 }.sum \n println(result)\n }\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\n import scala.io.StdIn._\n\n def higher(a: Int): Int = {\n @annotation.tailrec\n def go(h: Int): Int = if (1 << h > a) h else go(h + 1)\n go(1)\n }\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(s => higher(s.toInt))\n\n val bits = Array.fill(32)(0)\n\n val ans = an.foldLeft(0L) {\n case (count, h) =>\n bits(h) += 1\n count + bits(h) - 1\n }\n\n println(ans)\n }\n}\n"}], "negative_code": [], "src_uid": "04e2e1ce3f0b4efd2d4dda69748a0a25"} {"source_code": "import java.io._\n\nobject _1726B extends App {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n\n val in: InputReader = if (isOnlineJudge) new InputReader(System.in) else new InputReader(new File(\"src/test/resources/1726/B/input_0.txt\"))\n val out = if (isOnlineJudge) new PrintWriter(System.out) else new PrintWriter(new File(\"1726_output.txt\"))\n import in._\n\n /********* Solution *********/\n repeat {\n val n, m = nextInt()\n\n val ans: Iterator[Int] =\n if (m < n) Iterator.empty\n else if (m%n == 0) Iterator.tabulate(n)(_ => m/n)\n else if (n%2 == 1) Iterator.tabulate(n)(i => if (i < n-1) 1 else m - (n - 1))\n else if (m%2 == 0) Iterator.tabulate(n)(i => if (i < n-2) 1 else (m - (n - 2))/2)\n else Iterator.empty\n\n if (ans.isEmpty) {\n out.println(\"No\")\n } else {\n out.println(\"Yes\")\n ans.foreach({i =>\n out.print(i)\n out.print(\" \")\n })\n out.println()\n }\n }\n out.close()\n\n /***********************/\n\n def repeat(f: => Unit): Unit = (1 to nextInt()).foreach(_ => f)\n\n class InputReader(reader: BufferedReader) {\n def this(file: File) = this(new BufferedReader(new FileReader(file)))\n def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))\n\n val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(\" \"))\n\n def nextLine(): String = reader.readLine()\n def next(): String = tokens.next()\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextDouble(): Double = next().toDouble\n }\n}\n", "positive_code": [{"source_code": "object _1726B extends CodeForcesApp {\n override def solve() = repeat() {\n val n, m = nextInt()\n\n val ans: Seq[Int] =\n if (m < n) Seq.empty\n else if (m%n == 0) Seq.tabulate(n)(_ => m/n)\n else if (n%2 == 1) Seq.tabulate(n)(i => if (i < n-1) 1 else m - (n - 1))\n else if (m%2 == 0) Seq.tabulate(n)(i => if (i < n-2) 1 else (m - (n - 2))/2)\n else Seq.empty\n\n if (ans.isEmpty) {\n out.println(\"No\")\n } else {\n out.println(\"Yes\")\n out.println(ans.mkString(\" \"))\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n import java.io._\n var in = new BufferedReader(new InputStreamReader(System.in))\n var out = new PrintWriter(System.out)\n\n val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(\" \"))\n\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n def nextLine(): String = in.readLine()\n def next(): String = tokens.next()\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextDouble(): Double = next().toDouble\n def nextN[C[_], A](r: => A)(implicit b: collection.generic.CanBuild[A, C[A]]): C[A] = Iterator.fill(nextInt())(r).to[C]\n\n def debug(x: => Any): Unit = if (!sys.props.contains(\"ONLINE_JUDGE\")) println(x)\n\n def main(args: Array[String]): Unit = try solve() finally out.flush()\n def solve(): Any\n}\n"}, {"source_code": "object _1726B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve() = repeat {\n val n, m = in.nextInt()\n\n val ans: Iterator[Int] =\n if (m < n) Iterator.empty\n else if (m%n == 0) Iterator.tabulate(n)(_ => m/n)\n else if (n%2 == 1) Iterator.tabulate(n)(i => if (i < n-1) 1 else m - (n - 1))\n else if (m%2 == 0) Iterator.tabulate(n)(i => if (i < n-2) 1 else (m - (n - 2))/2)\n else Iterator.empty\n\n if (ans.isEmpty) {\n out.println(\"No\")\n } else {\n out.println(\"Yes\")\n out.println(ans.mkString(\" \"))\n out.println()\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\nimport java.io._\n\ntrait CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n\n var in: InputReader = new InputReader(System.in)\n var out: PrintWriter = new PrintWriter(System.out)\n\n def repeat(f: => Unit): Unit = (1 to in.nextInt()).foreach(_ => f)\n\n def solve(): Any\n\n def main(args: Array[String]): Unit = {\n if (!isOnlineJudge) {\n in = new InputReader(new File(args(0)))\n out = new PrintWriter(new File(args(1)))\n }\n try solve() finally out.flush()\n }\n}\n\nclass InputReader(in: BufferedReader) {\n def this(file: File) = this(new BufferedReader(new FileReader(file)))\n def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))\n\n val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(\" \"))\n\n def nextLine(): String = in.readLine()\n def next(): String = tokens.next()\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextDouble(): Double = next().toDouble\n\n //def nextCollection[C[_], A](n: Int = nextInt())(r: _ => A)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(r).to[C]\n}\n"}, {"source_code": "object _1726B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve() = repeat {\n val n, m = in.nextInt()\n\n val ans: Iterator[Int] =\n if (m < n) Iterator.empty\n else if (m%n == 0) Iterator.tabulate(n)(_ => m/n)\n else if (n%2 == 1) Iterator.tabulate(n)(i => if (i < n-1) 1 else m - (n - 1))\n else if (m%2 == 0) Iterator.tabulate(n)(i => if (i < n-2) 1 else (m - (n - 2))/2)\n else Iterator.empty\n\n if (ans.isEmpty) {\n out.println(\"No\")\n } else {\n out.println(\"Yes\")\n ans.foreach({i =>\n out.print(i)\n out.print(\" \")\n })\n out.println()\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\nimport java.io._\n\ntrait CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n\n var in: InputReader = new InputReader(System.in)\n var out: PrintWriter = new PrintWriter(System.out)\n\n def repeat(f: => Unit): Unit = (1 to in.nextInt()).foreach(_ => f)\n\n def solve(): Any\n\n def main(args: Array[String]): Unit = {\n if (!isOnlineJudge) {\n in = new InputReader(new File(args(0)))\n out = new PrintWriter(new File(args(1)))\n }\n try solve() finally out.flush()\n }\n}\n\nclass InputReader(in: BufferedReader) {\n def this(file: File) = this(new BufferedReader(new FileReader(file)))\n def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))\n\n val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(\" \"))\n\n def nextLine(): String = in.readLine()\n def next(): String = tokens.next()\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextDouble(): Double = next().toDouble\n\n //def nextCollection[C[_], A](n: Int = nextInt())(r: _ => A)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(r).to[C]\n}\n"}], "negative_code": [], "src_uid": "041143f69ce9d00924ce8deb56b723c5"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C339A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C339A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val l = nl()\n val r = nl()\n\n val k = nl()\n\n val x: immutable.Seq[Long] = Stream.iterate(1L)(k*).takeWhile(p => Long.MaxValue >= p && Long.MaxValue / p >= k)\n val y = (if(Long.MaxValue / x.last >= k) x ++ Seq(x.last * k) else x).filter(p => p >= l && p <=r)\n if(y.nonEmpty) {\n out.print(y.mkString(\" \"))\n } else out.println(-1)\n }\n}\n", "positive_code": [{"source_code": "// object Main\nimport java.io.{IOException, InputStream, PrintWriter}\nimport java.util.InputMismatchException\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject Main {\n\n def solveCase(caseNo: Int, in: InputReader, out: PrintWriter): Unit = {\n val l, r, k = in.nextLong()\n var c = BigInt(1)\n val answer = new ArrayBuffer[String]\n while (c <= r) {\n if (c >= l) {\n answer.append(c.toString)\n }\n c *= k\n\n }\n if (answer.isEmpty) {\n println(-1)\n } else {\n println(answer.mkString(\" \"))\n }\n\n }\n\n def solve(in: InputReader, out: PrintWriter): Unit = {\n solveCase(1, in, out)\n// val caseCount = in.nextInt()\n// for (caseNo <- 1 to caseCount) {\n// solveCase(caseNo, in, out)\n// }\n }\n\n def main(args: Array[String]) {\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n in.close()\n out.close()\n }\n}\n\nclass InputReader(val inputStream: InputStream) {\n val buf = new Array[Byte](1 << 16)\n var curChar = 0\n var numChars = 0\n\n def read(): Int = {\n if (numChars == -1) {\n throw new InputMismatchException()\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => throw new InputMismatchException()\n }\n if (numChars <= 0)\n return -1\n }\n curChar += 1\n buf(curChar - 1)\n }\n\n def peek(): Int = {\n if (numChars == -1) {\n return -1\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => return -1\n }\n if (numChars <= 0)\n return -1\n }\n buf(curChar)\n }\n\n def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n\n def nextInt(): Int = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextLong(): Long = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0l\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def next(): String = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n val res = new StringBuilder()\n do {\n res += c.toChar\n c = read()\n } while (!isSpaceChar(c))\n res.toString()\n }\n\n def nextChar(): Char = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n c.toChar\n }\n\n //noinspection AccessorLikeMethodIsEmptyParen\n def hasNext(): Boolean = {\n var value = peek()\n do {\n read()\n value = peek()\n } while (isSpaceChar(value) && value != -1)\n value != -1\n }\n\n def rawNextLine(): String = {\n val builder = new StringBuilder\n var c = read()\n while (c != '\\n' && c != -1) {\n if (c != '\\r')\n builder += c.toChar\n c = read()\n }\n builder.toString()\n }\n\n def nextLine(): String = {\n var s = rawNextLine()\n while (s.trim().length == 0) s = rawNextLine()\n s\n }\n\n def nextDouble(): Double = {\n next().toDouble\n }\n\n def close(): Unit = {\n inputStream.close()\n }\n}\n"}, {"source_code": "\n/**\n * Created by octavian on 16/01/2016.\n */\nobject LinkTree {\n\n def main (args: Array[String]) {\n //System.setIn(new FileInputStream(\"src/link.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"src/link.out\")))\n val Array(l, r, k): Array[BigInt] = readLine().split(\" \").map(x => BigInt(x)).toArray\n var acc: BigInt = 1\n var found = false\n while(acc <= r) {\n if(l <= acc) {\n print(acc + \" \")\n found = true\n }\n acc *= k\n }\n\n if(found == false) {\n println(\"-1\")\n }\n }\n\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _614A extends CodeForcesApp {\n override type Result = Stream[BigInt]\n\n override def solve(read: InputReader) = {\n val l, r, k = read[BigInt]\n Stream.iterate(BigInt(1))(_ * k).dropWhile(_ < l).takeWhile(_ <= r)\n }\n\n override def format(result: Result) = if (result.isEmpty) \"-1\" else result mkString \" \"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(l, r, k) = in.next().split(' ').map(_.toLong)\n var res = List.empty[Long]\n var i = BigInt(1)\n while (i <= r) {\n if (i >= l)\n res ::= i.toLong\n i *= k\n }\n if (res.isEmpty)\n println(-1)\n else\n println(res.reverse.mkString(\" \"))\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(l, r, k) = in.next().split(' ').map(_.toLong)\n var res = List.empty[Long]\n var i = 1l\n while (i <= r) {\n if (i >= l)\n res ::= i\n i *= k\n }\n if (res.isEmpty)\n println(-1)\n else\n println(res.reverse.mkString(\" \"))\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C339A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C339A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val l = nl()\n val r = nl()\n\n val k = nl()\n\n val x: immutable.Seq[Long] = Stream.iterate(1L)(k*).takeWhile(p => r>=p && Long.MaxValue / p >= k).filter(p => p>=l)\n if(x.nonEmpty) {\n out.print(x.mkString(\" \"))\n if(Long.MaxValue / k >= x.last && x.last * k <= r) out.println(s\" ${x.last * k}\")\n } else out.println(-1)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C339A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C339A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val l = nl()\n val r = nl()\n\n val k = nl()\n\n val x: immutable.Seq[Long] = Stream.iterate(1L)(k*).takeWhile(p => r>=p && Long.MaxValue / p >= k).filter(p => p>=l)\n if(x.nonEmpty) {\n out.println(x.mkString(\" \"))\n } else out.println(-1)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C339A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C339A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val l = nl()\n val r = nl()\n\n val k = nl()\n\n val x: immutable.Seq[Long] = Stream.iterate(1L)(k*).takeWhile(r>=).filter(p => p>=l)\n if(x.nonEmpty) {\n out.println(x.mkString(\" \"))\n } else out.println(-1)\n }\n}\n"}], "src_uid": "8fcec28fb4d165eb58f829c03e6b31d1"} {"source_code": "\nimport java.io._\nimport java.util.Locale\nimport java.util.StringTokenizer\nimport scala.collection._\n\n/**\n * @author antipov.\n * 15.07.2016 14:47.\n */\nobject B extends App {\n\n def solve() = {\n val n = readInt\n val g = new Array[List[Int]](n)\n (0 until n) foreach (i => g(i) = Nil)\n\n (1 until n) map (i => {\n val parent = readInt - 1\n g(parent) = i :: g(parent)\n })\n\n val sizes = new Array[Int](n)\n val res = new Array[Double](n)\n calcSizes(0, sizes);\n calcRes(0, 1, res)\n\n res foreach (i => print(i + \" \"))\n\n\n def calcSizes(v: Int, res: Array[Int]): Int = {\n res(v) = (g(v) map (ch => calcSizes(ch, res)) sum)\n res(v) + 1\n }\n\n def calcRes(v: Int, mo: Double, res: Array[Double]): Unit = {\n res(v) = mo\n g(v) foreach (ch => calcRes(ch, mo + 1 + (sizes(v) - (sizes(ch) + 1)) / 2.0, res))\n }\n }\n\n def readInt(): Int = IO.nextInt\n\n def readLong(): Long = IO.nextLong\n\n def println(a: Any) = IO.println(a)\n\n def print(a: Any) = IO.print(a)\n\n def printf(locale: Locale, format: String, values: Any*) = IO.printf(locale, format, values)\n\n solve()\n IO.close\n}\n\nobject IO {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n var tok = new StringTokenizer(\"\")\n\n def nextToken() = {\n while (!tok.hasMoreTokens) {\n tok = new StringTokenizer(in.readLine())\n }\n tok.nextToken()\n }\n\n def nextInt = nextToken().toInt\n\n def nextLong = nextToken().toLong\n\n def println(a: Any) = out.println(a)\n\n def print(a: Any) = out.print(a)\n\n def printf(locale: Locale, format: String, values: Any*) = out.printf(locale, format, values)\n\n def close = {\n in.close()\n out.close()\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util._\nimport scala.collection.mutable._\n\nobject Main extends App {\n def nextInt(): Int = IO.nextInt()\n\n val n = nextInt()\n val g: Array[ArrayBuffer[Int]] = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer[Int]())\n val p: Array[Int] = Array.fill[Int](n)(0)\n (1 until n).foreach{ i =>\n p(i) = nextInt - 1\n g(p(i)) += i\n }\n\n val size: Array[Int] = Array.fill[Int](n)(0)\n dfs(0)\n\n val exp: Array[Double] = Array.fill[Double](n)(1)\n dfs1(0)\n\n exp.map(i => print(i + \" \"))\n println(\"\")\n\n IO.close\n\n def dfs(v: Int): Int = {\n var ret = 1\n for(i <- g(v)) {\n ret += dfs(i)\n }\n size(v) = ret\n ret\n }\n\n def dfs1(v: Int) {\n // val sum = g(v).map(i => size(i)).sum\n var sum = 0\n for(i <- g(v)) sum += size(i)\n for(i <- g(v)) {\n exp(i) = exp(p(i)) + 1 + (sum - size(i)).toDouble / 2\n dfs1(i)\n }\n }\n}\n\nobject IO {\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n var str = new StringTokenizer(\"\")\n\n def next(): String = {\n while(!str.hasMoreElements()) {\n str = new StringTokenizer(in.readLine())\n }\n str.nextToken()\n }\n\n def nextInt() = next().toInt\n def println(a: AnyVal) = out.println(a)\n def print(a: AnyVal) = out.print(a)\n\n def close() = {\n in.close()\n out.close()\n }\n}"}], "negative_code": [], "src_uid": "750e1d9e43f916699537705c11d64d29"} {"source_code": "object _1738A extends CodeForcesApp {\n override def solve(io: IO) = io.repeat() {\n val n = io.nextInt()\n val isFrost = Seq.fill(n)(io.nextBool())\n val damages = Seq.fill(n)(io.nextLong())\n\n val all = isFrost.zip(damages).toMultiMap.mapValues(_.sorted(desc[Long])).withDefaultValue(Nil)\n\n var ans = all(true).zipAll(all(false), 0L, 0L) sumWith {\n case (frost, fire) if frost > 0 && fire > 0 => 2*(frost + fire)\n case (frost, fire) => frost + fire\n }\n\n if (all(true).length == all(false).length)\n ans -= damages.min\n\n io.printLine(ans)\n }\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C]).withDefaultValue(b().result())\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B =\n t.foldLeft(n.zero)({ case (c, x) => n.plus(c, f(x)) })\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n}\n/**************************** [Ignore Template Below] **************************************/\ntrait CodeForcesApp {\n def debug(x: => Any): Unit = if (!sys.props.contains(\"ONLINE_JUDGE\")) println(s\">>> DEBUG: $x\")\n def run(io: IO): Unit = try solve(io) finally io.close()\n def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))\n def solve(io: IO): Any\n}\n// Java I/O wrapper\nimport java.io._\nclass IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {\n def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))\n\n val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))\n\n def nextLine(): String = in.readLine()\n def nextStr(): String = tokens.next()\n def nextInt(): Int = nextStr().toInt\n def nextLong(): Long = nextStr().toLong\n def nextDouble(): Double = nextStr().toDouble\n def nextBool(): Boolean = nextInt() == 1\n def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }\n\n def print(xs: Any*): this.type = { out.print(xs.mkString(\" \")); this }\n def printLine(xs: Any*): this.type = { out.println(xs.mkString(\" \")); this }\n def printLines(xs: Any*): this.type = { if (xs.isEmpty) out.println() else xs.foreach(out.println); this }\n\n override def close() = out.close()\n}\n", "positive_code": [{"source_code": "import scala.util.Sorting.quickSort\r\nimport scala.math.Ordered.orderingToOrdered\r\n\r\nobject Main {\r\n\r\n class Hero(var x: Int = 0, var y: Int = 0) extends Ordered[Hero] {\r\n\r\n def compare(that: Hero): Int = (that.y, this.x) compare (this.y, that.x)\r\n \r\n override def toString: String =\r\n s\"($x, $y)\"\r\n }\r\n\r\n def main(args:Array[String]): Unit = {\r\n var t = io.StdIn.readInt()\r\n\r\n def loopts(ts: Int): Int = {\r\n if ( ts < t ){\r\n var n = io.StdIn.readInt()\r\n \r\n var arrt:Array[Hero] = new Array[Hero](n)\r\n var a:Array[Int] = io.StdIn.readLine().split(\" \").map(_.toInt)\r\n var b:Array[Int] = io.StdIn.readLine().split(\" \").map(_.toInt)\r\n\r\n for ( i <- 0 until n )\r\n arrt(i) = new Hero(a(i), b(i))\r\n\r\n quickSort[Hero](arrt)(Ordering[Hero])\r\n\r\n var Array(cnt0, cnt1) = {\r\n def count(i: Int, cnt0: Int, cnt1: Int): Array[Int] = {\r\n if ( i < n ){\r\n if ( arrt(i).x == 0 )\r\n count(i+1, cnt0+1, cnt1)\r\n else\r\n count(i+1, cnt0, cnt1+1)\r\n }\r\n else\r\n Array(cnt0, cnt1)\r\n }\r\n count(0, 0, 0)\r\n }\r\n\r\n def solve(i: Int, cnt0: Int, cnt1: Int, acc: Long): Long = {\r\n if ( i < n ){\r\n if ( arrt(i).x == 0 && cnt0+cnt1 > 1 ){\r\n if ( cnt1 > 0 )\r\n solve(i+1, cnt0, cnt1-1, acc+2*arrt(i).y)\r\n else\r\n solve(i+1, cnt0, cnt1, acc+arrt(i).y)\r\n }\r\n else {\r\n if ( cnt0 > 0 && cnt0+cnt1 > 1 )\r\n solve(i+1, cnt0-1, cnt1, acc+2*arrt(i).y)\r\n else\r\n solve(i+1, cnt0, cnt1, acc+arrt(i).y)\r\n }\r\n }\r\n else \r\n acc\r\n }\r\n println(solve(0, cnt0, cnt1, 0))\r\n\r\n loopts(ts+1)\r\n }\r\n else\r\n 0\r\n }\r\n \r\n loopts(0)\r\n }\r\n \r\n}"}], "negative_code": [{"source_code": "import scala.util.Sorting.quickSort\r\nimport scala.math.Ordered.orderingToOrdered\r\n\r\nobject Main {\r\n\r\n class Hero(var x: Int = 0, var y: Int = 0) extends Ordered[Hero] {\r\n\r\n def compare(that: Hero): Int = (that.x, this.y) compare (this.x, that.y)\r\n \r\n override def toString: String =\r\n s\"($x, $y)\"\r\n }\r\n\r\n def main(args:Array[String]): Unit = {\r\n var t = io.StdIn.readInt()\r\n\r\n def loopts(ts: Int): Int = {\r\n if ( ts < t ){\r\n var n = io.StdIn.readInt()\r\n \r\n var arrt:Array[Hero] = new Array[Hero](n)\r\n var a:Array[Int] = io.StdIn.readLine().split(\" \").map(_.toInt)\r\n var b:Array[Int] = io.StdIn.readLine().split(\" \").map(_.toInt)\r\n\r\n var min: Int = 10^9\r\n for ( i <- 0 until n ){\r\n arrt(i) = new Hero(a(i), b(i))\r\n if ( min > b(i) )\r\n min = b(i)\r\n }\r\n\r\n quickSort[Hero](arrt)(Ordering[Hero].reverse)\r\n\r\n var Array(cnt0, cnt1) = {\r\n def count(i: Int, cnt0: Int, cnt1: Int): Array[Int] = {\r\n if ( i < n ){\r\n if ( arrt(i).x == 0 )\r\n count(i+1, cnt0+1, cnt1)\r\n else\r\n count(i+1, cnt0, cnt1+1)\r\n }\r\n else\r\n Array(cnt0, cnt1)\r\n }\r\n count(0, 0, 0)\r\n }\r\n\r\n def solve(i: Int, acc: Long): Long = {\r\n if ( i < n ){\r\n if ( cnt0 < cnt1 ){\r\n if ( arrt(i).x == 0 || i < 2*cnt0 )\r\n solve(i+1, acc+2*arrt(i).y)\r\n else\r\n solve(i+1, acc+arrt(i).y)\r\n }\r\n else {\r\n if ( arrt(i).x == 1 || i < cnt1 )\r\n solve(i+1, acc+2*arrt(i).y)\r\n else\r\n solve(i+1, acc+arrt(i).y)\r\n }\r\n }\r\n else \r\n if ( cnt0 != cnt1 )\r\n acc\r\n else \r\n acc - min\r\n }\r\n println(solve(0, 0))\r\n loopts(ts+1)\r\n }\r\n else\r\n 0\r\n }\r\n \r\n loopts(0)\r\n }\r\n \r\n}"}], "src_uid": "bc1587d3affd867804e664fdb38ed765"} {"source_code": "object _1330A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val n, x = io.read[Int]\n val as = io.read[Set, Int](n)\n val ans = Iterator.from(1)\n .filterNot(as)\n .drop(x)\n .dropWhile(as)\n .next()\n io.write(ans - 1)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n val charToInt: Char => Int = Character.getNumericValue\n val intToChar: Int => Char = Character.forDigit(_, 10)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n", "positive_code": [{"source_code": "object A extends App {\n class Rank private (val x: Int, val as: List[Int])\n\n object Rank {\n def apply(x: Int, as: List[Int]): Rank = new Rank(x, as.distinct.sorted)\n def unapply(rank: Rank): Option[(Int, List[Int])] = Some(rank.x, rank.as)\n }\n\n private def possible(r: Rank): Int = {\n val Rank(x, as) = r\n\n val t = as.foldLeft((0, x)) {\n case ((i, x), j) =>\n if (i + 1 + x >= j) (j, x - math.min(x, j - i - 1))\n else (i + x, 0)\n }\n\n t._1 + t._2\n }\n\n val t = scala.io.StdIn.readInt()\n\n val input: List[Rank] = (0 until t)\n .foldLeft(List.empty[Rank]) {\n case (rs, _) =>\n val Array(_, x) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val as = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n Rank(x, as) :: rs\n }\n .reverse\n\n val output = input.map(possible)\n\n output.foreach(println)\n}"}], "negative_code": [{"source_code": "object A extends App {\n class Rank private (val x: Int, val as: List[Int])\n\n object Rank {\n def unapply(rank: Rank): Option[(Int, List[Int])] = Some(rank.x, rank.as)\n\n def apply(x: Int, as: List[Int]): Rank = new Rank(x, as.distinct.sorted)\n }\n\n private def possible(r: Rank): Int = {\n val Rank(x, as) = r\n\n val t = as.foldLeft((0, x)) { case ((i, x), j) =>\n if (x == 0) (i, x)\n else (if (i + x >= j - 1) j else i + x, x - math.min(x, j - i - 1))\n }\n\n t._1 + t._2\n }\n\n val t = scala.io.StdIn.readInt()\n\n val input: List[Rank] = (0 until t).foldLeft(List.empty[Rank]) {\n case (rs, _) =>\n val Array(_, x) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val as = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n Rank(x, as) :: rs\n }.reverse\n\n val output = input.map(possible)\n\n output.foreach(println)\n}"}], "src_uid": "e5fac4a1f3a724234990fe758debc33f"} {"source_code": "import java.io._\nimport scala.io.Source\n\nobject Olymp{\n def main(args: Array[String]): Unit = {\n val it = Source.fromFile(\"input.txt\").getLines\n val List(n, k) = it.next.split(' ').toList.map(s => s.toInt)\n val intensity: List[Int] = it.next.split(' ').toList.map(s => s.toInt)\n val solution = (intensity zip (0 to n-1 toList)).sort((a, b) => a._1 > b._1).take(k)\n val writer = new PrintWriter(new File(\"output.txt\" ))\n writer.print(solution.minBy(elem => elem._1)._1+\"\\n\")\n solution.foreach(elem => writer.print((elem._2+1)+\" \"))\n writer.close()\n }\n}", "positive_code": [{"source_code": "object Solution {\n import scala.io.Source\n import java.io.PrintWriter\n\n def main(args:Array[String]) {\n val it = Source.fromFile(\"input.txt\").getLines\n val List(n, k) = it.next.split(' ').map(_.toInt).toList\n val hours = it.next.split(' ').map(_.toInt).toArray\n val a = hours.sorted.drop(n-k)\n val min = a.head\n val min_count = a.takeWhile(_ == min).size\n var c = 0\n val reading = (1 to n).view.filter { i => \n val light = hours(i-1)\n if (light > min) {\n true\n } else if (light == min && c < min_count) {\n c += 1\n true\n } else {\n false\n }\n\n }.mkString(\" \")\n\n val out = new PrintWriter(\"output.txt\")\n out.println(min)\n out.println(reading)\n out.close\n }\n}\n"}, {"source_code": "\nobject Solution extends App {\n val in = scala.io.Source.fromFile(\"input.txt\").getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt)\n val sor = data.sorted.drop(n - k)\n var sorted = sor.foldLeft(Map.empty[Int, Int]) {\n case(acc, el) => acc + (el -> (acc.getOrElse(el, 0) + 1))\n }\n val res = data.indices.filter{\n j => if (sorted.getOrElse(data(j), 0) != 0) {\n sorted += (data(j) -> (sorted(data(j)) - 1))\n true\n } else {\n false\n }\n }\n import java.io.{File, PrintWriter}\n\n val writer = new PrintWriter(new File(\"output.txt\"))\n writer.write(sor.head + \"\\n\" + res.map(_ + 1).mkString(\" \"))\n writer.close()\n}"}], "negative_code": [{"source_code": "\nobject Solution extends App {\n val in = scala.io.Source.fromFile(\"input.txt\").getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt)\n val sor = data.sorted.drop(n - k)\n var sorted = sor.foldLeft(Map.empty[Int, Int]) {\n case(acc, el) => acc + (el -> (acc.getOrElse(el, 0) + 1))\n }\n val res = data.indices.filter{\n j => if (sorted.getOrElse(data(j), 0) != 0) {\n sorted += (data(j) -> (sorted(data(j)) - 1))\n true\n } else {\n false\n }\n }\n import java.io.{File, PrintWriter}\n\n val writer = new PrintWriter(new File(\"output.txt\"))\n writer.write(sor.head)\n writer.write(res.map(_ + 1).mkString(\" \"))\n writer.close()\n}"}, {"source_code": "\nobject Solution extends App {\n val in = scala.io.Source.fromFile(\"input.txt\").getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt)\n val sor = data.sorted.drop(n - k)\n var sorted = sor.drop(n - k).foldLeft(Map.empty[Int, Int]) {\n case(acc, el) => acc + (el -> (acc.getOrElse(el, 0) + 1))\n }\n val res = data.indices.filter{\n j => if (sorted.getOrElse(data(j), 0) != 0) {\n sorted += (data(j) -> (sorted(data(j)) - 1))\n true\n } else {\n false\n }\n }\n import java.io.{File, PrintWriter}\n\n val writer = new PrintWriter(new File(\"output.txt\"))\n writer.write(sor.head)\n writer.write(res.map(_ + 1).mkString(\" \"))\n writer.close()\n}"}, {"source_code": "object Solution extends App {\n println(\"her\")\n val in = scala.io.Source.stdin.getLines()\n // val Array(n, k) = in.next().split(\" \").map(_.toInt)\n // val data = in.next().split(\" \").map(_.toInt)\n// var sorted = data.sorted.drop(n - k).foldLeft(Map.empty[Int, Int]) {\n// case(acc, el) => acc + (el -> (acc.getOrElse(el, 0) + 1))\n// }\n// val res = data.indices.filter{\n// j => if (sorted.getOrElse(data(j), 0) != 0) {\n// sorted += (data(j) -> (sorted(data(j)) - 1))\n// true\n// } else {\n// false\n// }\n// }\n// println(res.map(_ + 1).mkString(\" \"))\n}"}, {"source_code": "object Solution extends App {\n println(\"her\")\n}"}, {"source_code": "\nobject Solution extends App {\n val in = scala.io.Source.fromFile(\"input.txt\").getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt)\n var sorted = data.sorted.drop(n - k).foldLeft(Map.empty[Int, Int]) {\n case(acc, el) => acc + (el -> (acc.getOrElse(el, 0) + 1))\n }\n val res = data.indices.filter{\n j => if (sorted.getOrElse(data(j), 0) != 0) {\n sorted += (data(j) -> (sorted(data(j)) - 1))\n true\n } else {\n false\n }\n }\n import java.io.{File, PrintWriter}\n\n val writer = new PrintWriter(new File(\"output.txt\"))\n writer.write(res.map(_ + 1).mkString(\" \"))\n writer.close()\n}"}, {"source_code": "import java.io._\nimport scala.io.Source\n\nobject Olymp{\n def main(args: Array[String]): Unit = {\n val it = Source.fromFile(\"input.txt\").getLines\n val List(n, k) = it.next.split(' ').toList.map(s => s.toInt)\n val intensity: List[Int] = it.next.split(' ').toList.map(s => s.toInt)\n val solution = (intensity zip (0 to n-1 toList)).sort((a, b) => a._1 > b._1).take(k)\n val writer = new PrintWriter(new File(\"output.txt\" ))\n writer.print(solution.minBy(elem => elem._1)._1+\"\\n\")\n solution.foreach(elem => writer.print((elem._2+1)+\" \"))\n writer.print(\"\\n\")\n }\n}"}, {"source_code": "import java.io._\nimport scala.io.Source\n\nobject Olymp{\n def main(args: Array[String]): Unit = {\n val it = Source.fromFile(\"input.txt\").getLines\n val List(n, k) = it.next.split(' ').toList.map(s => s.toInt)\n val intensity: List[Int] = it.next.split(' ').toList.map(s => s.toInt)\n val solution = (intensity zip (0 to n-1 toList)).sort((a, b) => a._1 > b._1).take(k)\n val writer = new PrintWriter(new File(\"output.txt\" ))\n writer.print(solution.minBy(elem => elem._1)._1+\"\\n\")\n solution.foreach(elem => writer.print((elem._2+1)+\" \"))\n }\n}"}], "src_uid": "a585045a9a6f62bfe1c0618c2ee02f48"} {"source_code": "import java.util.Scanner\n\nobject Main extends App {\n\n val sc = new Scanner(System.in)\n val n = sc.nextInt\n\n val sv =\n (0 to n)\n .toArray\n\n sv\n .foreach(num => {\n if (num > 1) {\n (num to n by num).tail.foreach(a => sv(a) = 0)\n }\n })\n\n\n val a1 =\n sv\n .filter(_ > 1)\n .flatMap(a => {\n val p = (math.log(n) / math.log(a)).toInt\n val t = (1 to p).toArray\n \n t.foreach(x => t(x - 1) = if (x == 1) a else a * t(x - 2))\n t\n })\n\n println(a1.size)\n if (a1.nonEmpty)\n println(a1.mkString(\" \"))\n}", "positive_code": [{"source_code": "\n\nimport scala.io.StdIn._\n\nobject Solution {\n def main( args : Array[String]) {\n val n = readInt\n val prime = Array.fill[Boolean](1005)(true)\n var x = 0 ; var y = 0\n var iset = Set.empty[Int]\n for (x <- 2 to n)\n {\n if(prime(x)==true)\n {\n for(y <- 2*x to n by x)prime(y)=false\n y=x\n while (y<=n)\n {\n iset = iset + y\n y = y * x\n }\n }\n }\n println(iset.size)\n iset.foreach(r => printf(\"%d \", r))\n println()\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject CF576A extends App {\n val n = readInt()\n\n def ints(n: Int): Stream[Int] =\n Stream.cons(n, ints(n + 1))\n\n def primes(nums: Stream[Int]): Stream[Int] =\n Stream.cons(nums.head,\n primes((nums tail) filter (x => x % nums.head != 0)))\n\n def powers(i: Int, n: Int): List[Int] = {\n def rec(q: Int, l: List[Int]): List[Int] =\n if (q <= n / i) rec(q * i, q * i :: l)\n else l\n\n rec(1, List.empty)\n }\n\n// println(powers(2, n))\n\n val r = if (n == 1) List.empty\n else\n primes(ints(2))\n .takeWhile(_ <= n)\n .map(powers(_, n))\n .reduce(_ ++ _)\n\n println(r.size)\n r.foreach(i => {\n print(i)\n print(\" \")\n })\n println()\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject CF576A extends App {\n val n = readInt()\n\n def ints(n: Int): Stream[Int] =\n Stream.cons(n, ints(n + 1))\n\n def primes(nums: Stream[Int]): Stream[Int] =\n Stream.cons(nums.head,\n primes((nums tail) filter (x => x % nums.head != 0)))\n\n def powers(i: Int): List[Int] = {\n def rec(q: Int, l: List[Int]): List[Int] =\n if (q <= n / i) rec(q * i, q * i :: l)\n else l\n\n rec(1, List.empty)\n }\n\n val r = primes(ints(2))\n .takeWhile(_ <= n)\n .map(powers)\n .foldLeft(List.empty[Int]) { _ ++ _ }\n\n println(r.size)\n println(r.mkString(\" \"))\n}"}, {"source_code": "//package round319.c\n\nimport java.util.Scanner\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n\n def ints(n: Int): Stream[Int] =\n Stream.cons(n, ints(n + 1))\n\n def primes(nums: Stream[Int]): Stream[Int] =\n Stream.cons(nums.head, primes((nums tail) filter (x => x % nums.head != 0)))\n\n val pp = primes(ints(2)) take 1000 toList\n\n def isPrime(x: Int): Boolean = {\n pp.contains(x)\n }\n\n def isPowerOfPrime(x: Int): Boolean = {\n pp.find(x % _ == 0) match {\n case None => false\n case Some(p) =>\n var xx = x\n var res = true\n while(xx != 1) {\n if(xx % p == 0) {\n xx /= p\n } else {\n res = false\n xx = 1\n }\n }\n res\n }\n }\n\n var divisors = Vector.empty[Int]\n\n for (i <- 2 to n) {\n if (isPrime(i) || isPowerOfPrime(i)) {\n divisors = divisors :+ i\n }\n }\n println(divisors.size)\n divisors.foreach(d => print(d + \" \"))\n\n}\n"}, {"source_code": "import scala.io.StdIn._\nimport scala.collection.Iterator._\nimport scala.language.postfixOps\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = readInt\n val prime: Array[Boolean] = Array.ofDim(n + 1)\n //for (val i <- 0 to n - 1)\n prime(0) = true\n prime(1) = true\n for {\n i <- 2 to n\n if !prime(i)\n j <- i * 2 to n by i\n } prime(j) = true\n val it = \n {\n for {\n i <- 2 to n\n if !prime(i)\n j <- iterate(i)(_*i) takeWhile (_ <= n)\n } yield j\n }\n println(it length)\n it foreach(printf(\" %d\", _:Int))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n\n val n = in.next().toInt\n val prime = Array.fill[Boolean](n + 1)(true)\n (2 to n).foreach { i =>\n if (prime(i)) {\n (2 * i to n by i).foreach { j => prime(j) = false}\n }\n }\n\n var answer = List.empty[Int]\n (2 to n).foreach { i =>\n if (prime(i)) {\n var q = 1\n while (q <= n / i) {\n q *= i\n answer ::= q\n }\n }\n }\n\n println(answer.length)\n println(answer.mkString(\" \"))\n\n\n\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C319A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C319A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val x = allPrimes(n)\n val y = x.flatMap{ f =>\n Stream.iterate(f)(f*) takeWhile(n>=) toList\n }.toSet\n out.println(y.size)\n out.println(y.mkString(\" \"))\n }\n\n def allPrimes(n: Int): Array[Int] = {\n val mrk = Array.fill[Boolean](n+1)(false)\n mrk(0) = true; mrk(1) = true\n REP(n+1) { i =>\n if(i > 1) {\n if(!mrk(i)) {\n i * 2 until (n+1) by i foreach(mrk(_) = true)\n }\n }\n }\n mrk.zipWithIndex.filter(p => !p._1).map(_._2)\n }\n}\n"}, {"source_code": "object A576 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val res = cu.ArrayBuffer.empty[Int]\n val vis = Array.fill(n+1)(false)\n vis(0) = true\n vis(1) = true\n var i = 2\n while(i <= n) {\n if(!vis(i)) {\n for(j <- vis.indices)\n if(i*j <= n)\n vis(i*j) = true\n res.append(i)\n\n var k = i*i\n while(k <= n) {\n vis(k) = true\n res.append(k)\n k *= i\n }\n }\n i += 1\n }\n println(res.length)\n println(res.mkString(\" \"))\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val set = new mutable.HashSet[Int]()\n for (i <- 2 to n) {\n val smallSet = new Array[Int](1001)\n var x = i\n for (j <- 2 to Math.sqrt(i).toInt + 1) {\n while (x % j == 0) {\n smallSet(j) += 1\n x /= j\n }\n }\n if (x > 1) {\n smallSet(x) += 1\n }\n var sum = 0\n for (j <- 0 until smallSet.length) {\n sum += smallSet(j)\n }\n if (sum == 1 || sum == 0) {\n set += i\n } else {\n var ind = 0\n var flag = true\n while (ind < smallSet.length && flag) {\n if (smallSet(ind) > 1) {\n if (!set.contains(Math.pow(ind, smallSet(ind)).toInt)) {\n set += i\n flag = false\n }\n }\n ind += 1\n }\n }\n }\n out.println(set.size)\n set.foreach(x => out.print(s\"$x \"))\n return 0\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\n\nobject C extends App {\n\n val n = readLine().toInt\n\n val answer = new ArrayBuffer[Int]()\n\n if (n == 1) {\n println(0)\n } else if (n == 2) {\n println(1)\n println(2)\n } else {\n val C = Array.ofDim[Int](n + 1)\n for (i <- 2 to n) C(i) = i\n\n var div = 2\n var isDiv = true\n while (div <= n) {\n isDiv = false\n var first = true\n for {\n j <- 2 to n\n } {\n if (C(j) > 1 && C(j) % div == 0) {\n isDiv = true\n C(j) /= div\n if (first) {\n answer += j\n first = false\n }\n }\n }\n\n if (!isDiv) {\n div += 1\n }\n }\n\n println(answer.length)\n println(answer.mkString(\" \"))\n\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject CF576A extends App {\n val n = readInt()\n\n def ints(n: Int): Stream[Int] =\n Stream.cons(n, ints(n + 1))\n\n def primes(nums: Stream[Int]): Stream[Int] =\n Stream.cons(nums.head,\n primes((nums tail) filter (x => x % nums.head != 0)))\n\n def powers(i: Int, n: Int): List[Int] = {\n def rec(i: Int, n: Int, l: List[Int]): List[Int] =\n if (i > n) l.drop(1)\n else rec(i * i, n, i * i :: l)\n\n rec(i, n, List(i))\n }\n\n val r = if (n == 1) List(1)\n else\n primes(ints(2))\n .takeWhile(_ <= n)\n .map(powers(_, n))\n .reduce(_ ++ _)\n\n println(r.size)\n r.foreach(i => {\n print(i)\n print(\" \")\n })\n println()\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject CF576A extends App {\n val n = readInt()\n\n def ints(n: Int): Stream[Int] =\n Stream.cons(n, ints(n + 1))\n\n def primes(nums: Stream[Int]): Stream[Int] =\n Stream.cons(nums.head,\n primes((nums tail) filter (x => x % nums.head != 0)))\n\n def powers(i: Int, n: Int): List[Int] = {\n def rec(i: Int, n: Int, l: List[Int]): List[Int] =\n if (i > n) l.drop(1)\n else rec(i * i, n, i * i :: l)\n\n rec(i, n, List(i))\n }\n\n val r = if (n == 1) List.empty\n else\n primes(ints(2))\n .takeWhile(_ <= n)\n .map(powers(_, n))\n .reduce(_ ++ _)\n\n println(r.size)\n r.foreach(i => {\n print(i)\n print(\" \")\n })\n println()\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C319A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C319A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val x = allPrimes(n)\n val y = x.flatMap{ f =>\n Stream.iterate(f)(f*) takeWhile(n>=) toList\n }.toSet\n out.println(y.size)\n out.println(y.mkString(\",\"))\n }\n\n def allPrimes(n: Int): Array[Int] = {\n val mrk = Array.fill[Boolean](n+1)(false)\n mrk(0) = true; mrk(1) = true\n REP(n+1) { i =>\n if(i > 1) {\n if(!mrk(i)) {\n i * 2 until (n+1) by i foreach(mrk(_) = true)\n }\n }\n }\n mrk.zipWithIndex.filter(p => !p._1).map(_._2)\n }\n}\n"}, {"source_code": "\n\nimport scala.io.StdIn._\n\nobject Solution {\n def main( args : Array[String]) {\n val n = readInt\n val prime = Array.fill[Boolean](1005)(true)\n var x = 0 ; var y = 0\n var iset = Set.empty[Int]\n for (x <- 2 to n)\n {\n if(prime(x)==true)\n {\n for(y <- 2*x to n by x)prime(y)=false\n y=x\n while (y<=x)\n {\n iset = iset + y\n y = y * x\n }\n }\n }\n println(iset.size)\n iset.foreach(r => printf(\"%d \", r))\n println()\n }\n}"}, {"source_code": "//package round319.c\n\nimport java.util.Scanner\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n\n def ints(n: Int): Stream[Int] =\n Stream.cons(n, ints(n+1))\n\n def primes(nums: Stream[Int]): Stream[Int] =\n Stream.cons(nums.head, primes ((nums tail) filter (x => x % nums.head != 0)) )\n\n val pp = primes(ints(2)) take 1000 toList\n\n def isPowerOf2(x: Int): Boolean = {\n (x & (x - 1)) == 0\n }\n\n def isPrime(x: Int): Boolean = {\n pp.contains(x)\n }\n\n var divisors = Vector.empty[Int]\n\n if(n == 1) {\n println(\"0\")\n } else if (n == 2) {\n println(\"1\")\n println(\"2\")\n } else {\n for(i <- 2 to n) {\n if(isPowerOf2(i) || isPrime(i)) {\n divisors = divisors :+ i\n }\n }\n println(divisors.size)\n divisors.foreach(d => print(d + \" \"))\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val set = new mutable.HashSet[Int]()\n for (i <- 2 to n) {\n val smallSet = new Array[Int](1001)\n var x = i\n for (j <- 2 to Math.sqrt(i).toInt + 1) {\n while (x % j == 0) {\n smallSet(j) += 1\n x /= j\n }\n }\n if (x > 1) {\n smallSet(x) += 1\n }\n var sum = 0\n for (j <- 0 until smallSet.length) {\n sum += smallSet(j)\n }\n if (sum == 1 || sum == 0) {\n set += i\n } else {\n var ind = 0\n var flag = true\n while (ind < smallSet.length && flag) {\n if (smallSet(ind) > 1) {\n if (!set.contains(ind * smallSet(ind))) {\n set += i\n flag = false\n }\n }\n ind += 1\n }\n }\n }\n out.println(set.size)\n set.foreach(x => out.print(s\"$x \"))\n return 0\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\n\nobject C extends App {\n\n val n = readLine().toInt\n\n val answer = new ArrayBuffer[Int]()\n\n if (n <= 2) {\n println(n - 1)\n } else {\n val C = Array.ofDim[Int](n + 1)\n for (i <- 2 to n) C(i) = i\n\n var div = 2\n var isDiv = true\n while (div <= n) {\n isDiv = false\n var first = true\n for {\n j <- 2 to n\n } {\n if (C(j) > 1 && C(j) % div == 0) {\n isDiv = true\n C(j) /= div\n if (first) {\n answer += j\n first = false\n }\n }\n }\n\n if (!isDiv) {\n div += 1\n }\n }\n }\n\n println(answer.mkString(\" \"))\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\n\nobject C extends App {\n\n val n = readLine().toInt\n\n if (n <= 2) {\n println(n - 1)\n } else {\n\n val C = Array.ofDim[ArrayBuffer[Int]](n + 1)\n val P = Array.fill[Boolean](n + 1)(true)\n\n for {\n i <- 2 to Math.sqrt(n + 1).toInt\n j <- i + i to n by i\n } {\n P(j) = false\n }\n\n val primes = P.zipWithIndex.filter(_._1).map(_._2).drop(2)\n\n for {\n i <- 2 to n\n } {\n var divIdx = 0\n var current = i\n C(i) = new scala.collection.mutable.ArrayBuffer[Int]\n while (divIdx < primes.length && primes(divIdx) <= current) {\n if (current % primes(divIdx) == 0) {\n C(i) += primes(divIdx)\n current /= primes(divIdx)\n } else {\n divIdx += 1\n }\n }\n }\n\n var isDiv = false\n var i = 0\n\n val answer = new scala.collection.mutable.ArrayBuffer[Int]\n while (i < primes.length) {\n isDiv = false\n\n for (j <- 2 to n) {\n if (C(j).nonEmpty && C(j).contains(primes(i))) {\n C(j) -= primes(i)\n if (!isDiv && C(j).isEmpty) {\n answer += j\n }\n isDiv = true\n }\n }\n\n if (!isDiv) i += 1\n }\n\n println(answer.mkString(\" \"))\n }\n}\n"}], "src_uid": "7f61b1d0e8294db74d33a6b6696989ad"} {"source_code": "\nobject B {\n def r = readLine().split(\" \") map(_.toInt)\n def main(args: Array[String]) {\n var Array(n,k) = r\n var a = r;\n var s = new Array[Int](n)\n s(0)=a(0)\n for (i <- 1 until n)\n s(i) = s(i-1) + a(i);\n var (result,j) = (0,0);\n for (i <- 0 until n-result\n if(a(i) <= k)){\n val ss = if (i == 0) 0 else s(i-1);\n while (j < n && s(j) - ss <= k) {\n j+=1;\n result = math.max(result, j-i)\n }\n }\n println(result)\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val nt = readLine().split(\" \").map(_.toInt)\n val n = nt(0)\n val t = nt(1)\n val a = readLine().split(\" \").map(_.toInt) \n \n var s = 0\n var sum = 0\n var max = 0\n \n for (i <- 0 until n) {\n val e = a(i)\n if (sum + e <= t) sum += e\n else {\n if (i - s > max) {\n max = i - s\n }\n sum += e\n sum -= a(s)\n s += 1\n }\n }\n if (n - s > max) max = n - s\n println(max)\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt)\n val compressed = data.tail.scanLeft(data.head){case(a, b) => a + b}\n if (t >= compressed.last)\n println(n)\n else {\n var left = -1\n var right = -1\n while (right < n - 1 && compressed(right + 1) <= t)\n right += 1\n var max = right + 1\n while (right < n - 1 && left < n - 1) {\n left += 1\n while (right < n - 1 && compressed(right + 1) - compressed(left) <= t)\n right += 1\n max = Math.max(max, right - left)\n }\n println(max)\n }\n}"}, {"source_code": "object B279 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, t) = readLongs(2)\n val in = Array(0L) ++ readLongs(n.toInt)\n for(i <- 1 to n.toInt) {\n in(i) += in(i-1)\n }\n var res = 0\n var j = 1\n var curr = 0L\n for(i <- 1 to n.toInt) {\n while(j <= n && in(j)-in(i-1) <= t) {\n res = math.max(res, j-i+1)\n j += 1\n }\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P279B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n val T = sc.nextLong\n val dp = Array.fill(N + 1)(0L)\n\n for (i <- 1 to N) {\n dp(i) = dp(i - 1) + sc.nextLong\n }\n\n val idx: Int => Int = { x =>\n if (x < 0) - (x + 1)\n else x + 1\n }\n\n val books: Int => Int = { i =>\n val j = binarySearch(dp, dp(i - 1) + T)\n idx(j) - i\n }\n\n 0 max List.range(1, N + 1).map(books).max\n }\n \n out.println(solve)\n out.close\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P279B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n val T = sc.nextLong\n val dp = Array.fill(N + 1)(0L)\n\n for (i <- 1 to N) {\n dp(i) = dp(i - 1) + sc.nextLong\n }\n\n val idx: Int => Int = { x =>\n if (x < 0) - (x + 1)\n else x\n }\n\n val books: Int => Int = { i =>\n val j = binarySearch(dp, dp(i - 1) + T)\n idx(j) - i\n }\n\n 0 max List.range(1, N + 1).map(books).max\n }\n \n out.println(solve)\n out.close\n}\n"}], "src_uid": "ef32a8f37968629673547db574261a9d"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val s = ns()\n val twone = mutable.Set[Int]()\n var i = 0\n while(i != -1) {\n i = s.indexOf(\"twone\", i)\n if (i != -1) {\n twone += i + 2\n i += 5\n }\n }\n\n val ans = ArrayBuffer[Int]()\n i = 0\n while(i != -1) {\n i = s.indexOf(\"one\", i)\n if (i != -1) {\n if (!twone.contains(i)) {\n ans += i + 1\n }\n i += 3\n }\n }\n i = 0\n while(i != -1) {\n i = s.indexOf(\"two\", i)\n if (i != -1) {\n if (!twone.contains(i + 2)) {\n ans += i + 1\n }\n i += 3\n }\n }\n\n debug(twone.mkString(\" \"))\n debug(ans.mkString(\" \"))\n\n ans ++= twone\n out.println(ans.length)\n out.println(ans.map(_+1).mkString(\" \"))\n }\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) = {\n val t = readInt\n (0 until t).foreach((x) => f1)\n }\n def f1(): Unit = { \n val s = readLine.zipWithIndex\n val l = s.foldLeft(List[(Char, Int, Int)]()) {\n case (l, (c, i)) => l match {\n case Nil => List((c, i + 1, 1))\n case (c2, k, n) :: tl => if (c2 == c) (c2, k, n + 1) :: tl else (c, i + 1, 1) :: l\n }\n }.reverse\n val k = f2(List[(Char, Int, Int)](), List[Int](), l)\n println(k.length)\n println(k.mkString(\" \"))\n }\n\n def f2(l: List[(Char, Int, Int)], rl: List[Int], cl: List[(Char, Int, Int)]): List[Int] = {\n cl match {\n case ('o', ooff, on) :: ('n', noff, 1) :: ('e', eoff, en) :: tl => {\n l match {\n case ('w', woff, 1) :: ('t', toff, tn) :: ltl => {\n val (tS, tL) = (('w', woff, 1), ('t', toff, tn))\n val (oS, oL) = (('n', noff, 1), ('e', eoff, en))\n if (2 <= on) {\n f2(oL :: ('o', ooff, on) :: tL :: ltl, oS._2 :: tS._2 :: rl, tl)\n } else {\n f2(('e', eoff, en) :: ('n', noff, 1) :: ('w', woff, 1) :: ('t', toff, tn) :: ltl, ooff :: rl, tl)\n }\n }\n case _ => f2(cl.head :: l, rl, cl.tail)\n }\n }\n case ('o', ooff, on) :: tl => {\n l match {\n case ('w', woff, 1) :: ('t', toff, tn) :: ltl => {\n f2(('o', ooff, on) :: ('t', toff, tn) :: ltl, woff :: rl, tl)\n }\n case _ => f2(cl.head :: l, rl, cl.tail)\n }\n }\n case ('e', eoff, en) :: tl => {\n l match {\n case ('n', noff, 1) :: ('o', ooff, on) :: ltl => {\n f2(('e', eoff, en) :: ('o', ooff, on) :: ltl, noff :: rl, tl)\n }\n case _ => f2(cl.head :: l, rl, cl.tail)\n }\n }\n case head :: tl => f2(head :: l, rl, tl)\n case Nil => rl\n }\n }\n }\n"}, {"source_code": "import scala.collection.mutable\n\nobject D {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n for (_ <- 1 to t) {\n val s = nextLine.toCharArray\n def ch(i: Int): Char = if (i < 0 || i >= s.length) ' ' else s(i)\n val res = new mutable.ArrayBuilder.ofInt\n var i = 0\n while (i < s.length) {\n if (ch(i - 2) == 't' && ch(i - 1) == 'w' && ch(i) == 'o' && ch(i + 1) == 'n' && ch(i + 2) == 'e') {\n s(i) = ' '\n res += i + 1\n } else if (ch(i - 2) == 't' && ch(i - 1) == 'w' && ch(i) == 'o') {\n res += i\n } else if (ch(i - 2) == 'o' && ch(i - 1) == 'n' && ch(i) == 'e') {\n res += i\n }\n i += 1\n }\n val r = res.result()\n out.println(r.length)\n out.println(r.mkString(\" \"))\n }\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]) = {\n val t = readInt\n (0 until t).foreach((x) => f1)\n }\n def f1(): Unit = {\n val s = readLine.zipWithIndex\n val l = s.foldLeft(List[(Char, Int, Int)]()) {\n case (l, (c, i)) => l match {\n case Nil => List((c, i, 1))\n case (c2, k, n) :: tl => if (c2 == c) (c2, k, n + 1) :: tl else (c, i, 1) :: l\n }\n }.reverse\n //println(l)\n val k = f2(List[(Char, Int, Int)](), List[Int](), l)\n println(k.length)\n println(k.mkString(\" \"))\n }\n\n def f2(l: List[(Char, Int, Int)], rl: List[Int], cl: List[(Char, Int, Int)]): List[Int] = {\n cl match {\n case ('o', ooff, on) :: ('n', noff, 1) :: ('e', eoff, en) :: tl => {\n l match {\n case ('w', woff, 1) :: ('t', toff, tn) :: ltl => {\n val (tS, tL) = (('w', woff, 1), ('t', toff, tn))\n val (oS, oL) = (('n', noff, 1), ('e', eoff, en))\n if (2 <= on) {\n f2(oL :: ('o', ooff, on) :: tL :: ltl, oS._2 :: tS._2 :: rl, tl)\n } else {\n f2(('e', eoff, en) :: ('n', noff, 1) :: ('w', woff, 1) :: ('t', toff, tn) :: ltl, ooff :: rl, tl)\n }\n }\n case _ => f2(cl.head :: l, rl, cl.tail)\n }\n }\n case ('o', ooff, on) :: tl => {\n l match {\n case ('w', woff, 1) :: ('t', toff, tn) :: ltl => {\n f2(('o', ooff, on) :: ('t', toff, tn) :: ltl, woff :: rl, tl)\n }\n case _ => f2(cl.head :: l, rl, cl.tail)\n }\n }\n case ('e', eoff, en) :: tl => {\n l match {\n case ('n', noff, 1) :: ('o', ooff, on) :: ltl => {\n f2(('e', eoff, en) :: ('o', ooff, on) :: ltl, noff :: rl, tl)\n }\n case _ => f2(cl.head :: l, rl, cl.tail)\n }\n }\n case head :: tl => f2(head :: l, rl, tl)\n case Nil => rl\n }\n }\n }"}], "src_uid": "9f8660190134606194cdd8db891a3d46"} {"source_code": "import java.io._\n\nimport scala.io.Source\n\nobject ProblemC {\n def main(args: Array[String]): Unit = processStdInOut()\n\n def processStdInOut(): Unit = {\n val src = Source.fromInputStream(System.in)\n processFromSource(src)\n }\n\n def processFromSource(src: Source): Unit = {\n try {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out));\n try {\n val lines = src.getLines()\n processLines(lines, bw)\n } finally {\n bw.flush()\n }\n } finally {\n src.close();\n }\n }\n\n // Standard code above, custom code below\n case class Move(index: Int, direction: Char) {\n override def toString() = s\"$index $direction\"\n }\n\n def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {\n val n = lines.next().toInt\n val a = lines.next().split(' ').map(_.toInt)\n val k = lines.next().toInt\n val b = lines.next().split(' ').map(_.toInt)\n val solution = solve(n, k, a, b)\n solution match {\n case Some(moves) => {\n bw.write(\"YES\")\n moves.foreach { move =>\n bw.newLine()\n bw.write(move.toString)\n }\n }\n case None => bw.write(\"NO\")\n }\n bw.newLine()\n }\n\n /** The approach is to folder over the weights in the a matrix,\n * until the current group of a values matches the next b value, and track the largest monster in the group.\n * If there are multiple largest monsters, then the first will eat all monsters to its left then all to its right.\n * The exception is if the first of these largest monsters starts the group and has other largest monsters after it.\n * In this case, take the last largest monster in this initial group of largest monsters.\n * It will eat all monsters to its right, then all monsters to its left.\n * But beware... if all monsters in the group are identical, then there is no solution, as none can eat any other.\n *\n * The Accumulator class tracks the state after all previous weights (entries in a) have been evaluated.\n * In particular it tracks the current group (corresponding to the next b value to be matched).\n */\n case class Accumulator(indexInGroup: Int, sizeOfGroup: Int,\n groupIndex: Int, groupSum: Int,\n groupMaxValue: Int, indexOfMaxInGroup: Int, maxStartsGroup: Boolean,\n moves: IndexedSeq[Move]\n ) {\n def setNewGroupMaxValue(weight: Int) = copy(\n groupMaxValue = weight,\n indexOfMaxInGroup = indexInGroup,\n maxStartsGroup = (indexInGroup == 0)\n )\n def areAllWeightsIdenticalAndIsThereMoreThanOne: Boolean = {\n maxStartsGroup && (indexOfMaxInGroup == indexInGroup) && (sizeOfGroup > 1)\n }\n def canGroupBeCollapsed: Boolean = !areAllWeightsIdenticalAndIsThereMoreThanOne\n def monstersAfterMaxMonsterInGroup: Int = sizeOfGroup - indexOfMaxInGroup - 1\n def monstersBeforeMaxMonsterInGroup: Int = indexOfMaxInGroup\n def globalIndexOfMaxMonster: Int = groupIndex + indexOfMaxInGroup + 1\n def updateWithMovesToCollapseGroup(): Accumulator = {\n // Calculate the moves that collapse the group to a single value (assuming this is possible)...\n if (sizeOfGroup == 1) this // With a single monster in the group, no eating will occur\n else {\n val newMoves = if (maxStartsGroup) {\n // Eat monsters to the right, then to the left:\n IndexedSeq.fill(monstersAfterMaxMonsterInGroup)(Move(globalIndexOfMaxMonster, 'R')) ++\n IndexedSeq.tabulate(monstersBeforeMaxMonsterInGroup)(i => Move(globalIndexOfMaxMonster - i, 'L' ))\n } else {\n // Eat monsters to the left, then the right:\n IndexedSeq.tabulate(monstersBeforeMaxMonsterInGroup) (i => Move(globalIndexOfMaxMonster - i, 'L' )) ++\n IndexedSeq.fill(monstersAfterMaxMonsterInGroup)(Move(groupIndex + 1, 'R'))\n }\n this.copy(moves = moves ++ newMoves)\n }\n }\n def startNextGroup(): Accumulator = {\n this.copy(indexInGroup = -1, sizeOfGroup = 0,\n groupIndex = groupIndex + 1, groupSum = 0, groupMaxValue = 0,\n indexOfMaxInGroup = -1, false)\n }\n }\n\n def solve(n: Int, k: Int, a: Array[Int], b: Array[Int]): Option[Seq[Move]] = {\n val initialAccumulator = Accumulator(-1, 0, 0, 0, 0, -1, false, IndexedSeq[Move]())\n val finalAcc = a.foldLeft[Option[Accumulator]](Some(initialAccumulator)) {\n (maybeAcc: Option[Accumulator], weight: Int) => {\n maybeAcc flatMap { acc =>\n if (b.length <= acc.groupIndex) None // note enough weights in b to match all the weights in a\n else {\n val target = b(acc.groupIndex)\n\n // First update the fields that don't depend on other logic:\n var newAcc = acc.copy(\n groupSum = acc.groupSum + weight,\n indexInGroup = acc.indexInGroup + 1,\n sizeOfGroup = acc.sizeOfGroup + 1)\n\n // Track the maximum value in the group (that isn't surrounded by other biggest monsters),\n // as we can eat up the other monsters starting from it:\n if (newAcc.groupMaxValue < weight) newAcc = newAcc.setNewGroupMaxValue(weight)\n else if (newAcc.maxStartsGroup && (newAcc.groupMaxValue == weight)\n && (newAcc.indexOfMaxInGroup == newAcc.indexInGroup - 1)) {\n // If a block of max values (largest monsters) starts the group, then track the last one found,\n // as only the last one in the block can eat up the rest of the group (by eating right first, not left):\n newAcc = newAcc.copy(indexOfMaxInGroup = newAcc.indexInGroup)\n }\n\n if (newAcc.groupSum < target) Some(newAcc) // The group is incomplete, so keep iterating...\n else if (newAcc.groupSum > target) None // array a and b are incompatible, so no valid solution\n else if (!newAcc.canGroupBeCollapsed) None // target reached, but all monsters identical, so an impasse\n else {\n newAcc = newAcc.updateWithMovesToCollapseGroup()\n newAcc = newAcc.startNextGroup()\n Some(newAcc)\n }\n }\n }\n }\n }\n finalAcc match {\n case Some(acc) if acc.groupIndex == k => Some(acc.moves) // Check that all b's were matched\n case _ => None\n }\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toInt)\n val k = in.next().toInt\n val after = in.next().split(' ').map(_.toInt)\n\n def split(start: Int, current: Int, i: Int, sum: Int, answer: List[Array[Int]]): List[Array[Int]] = {\n if (current == n && i == k)\n answer.reverse\n else if (current == n || i == k)\n Nil\n else if (sum + line(current) == after(i))\n split(current + 1, current + 1, i + 1, 0, line.slice(start, current + 1) :: answer)\n else if (sum + line(current) > after(i))\n Nil\n else\n split(start, current + 1, i, sum + line(current), answer)\n }\n\n val sol = split(0, 0, 0, 0, Nil).map(_.toList)\n\n if (sol.exists(l => l.length > 1 && l.distinct.size == 1) || sol.isEmpty) {\n println(\"NO\")\n } else {\n println(\"YES\")\n val res = sol.zipWithIndex.filter(_._1.length > 1).flatMap {\n case (l, index) =>\n val maxValue = l.max\n val maxIndex =\n l.indices.find(i => l(i) == maxValue && ((i != 0 && l(i - 1) != maxValue)\n || (i != l.length - 1 && l(i + 1) != maxValue))).get\n if (maxIndex != 0 && l(maxIndex - 1) != maxValue) {\n (maxIndex to 1 by -1).map(i => s\"${i + index + 1} L\").toList ::: (maxIndex until l.length - 1).map(i => s\"${index + 1} R\").toList\n } else {\n (maxIndex until l.length - 1).map(i => s\"${maxIndex + index + 1} R\").toList ::: (maxIndex to 1 by -1).map(i => s\"${i + index + 1} L\").toList\n }\n }\n println(res.mkString(\"\\n\"))\n }\n\n}\n\n\n"}, {"source_code": "\nimport java.io._\n\nimport scala.util._\n\nobject Main {\n\n def main(args: Array[String]) = {\n\n val TEST =\n \"\"\"2\n |1 2\n |2\n |3 1\n \"\"\".stripMargin.trim\n\n //System.setIn(new ByteArrayInputStream(TEST.getBytes))\n\n val input = scala.io.Source.stdin.getLines()\n\n\n val n = input.next().toInt\n val a = input.next().split(' ').toSeq.map(_.toLong)\n val k = input.next().toInt\n val b = input.next().split(' ').toSeq.map(_.toLong)\n val res = Try {\n assert(a.sum == b.sum)\n val f = a.foldLeft(Seq.empty[Seq[Long]]) { (l, i) =>\n if (l.isEmpty || l.head.sum == b(l.length - 1)) {\n assert (i <= b(l.length))\n Seq(i) +: l\n } else if (l.head.sum < b(l.length - 1)) {\n assert (l.head.sum + i <= b(l.length - 1))\n (i +: l.head) +: l.tail\n } else {\n throw new Exception()\n }\n }\n val g = f.map(_.reverse).reverse\n assert(g.forall(l => l.size == 1 || !l.forall(_ == l.head)))\n g.zipWithIndex.filter(_._1.size > 1).flatMap(pair => {\n val k = pair._1\n val base = pair._2 + 1\n val max = k.max\n val notMaxIndex = k.indexWhere(_ != max)\n val nearestMaxIndex = k.zipWithIndex.filter(pair => pair._1 == max).minBy(a => (a._2 - notMaxIndex).abs)._2\n if (nearestMaxIndex > notMaxIndex) {\n (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L')) ++ (0 until (k.length - nearestMaxIndex - 1)).map(_ => (base, 'R'))\n } else {\n (0 until (k.length - nearestMaxIndex - 1)).map(_ => (nearestMaxIndex + base, 'R')) ++ (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L'))\n }\n })\n }\n val sol = res match {\n case Success(a) => \"YES\" + a.map(b => \"\\n\" + b._1 + \" \" + b._2).mkString\n case Failure(e) => \"NO\"\n }\n\n\n\n println(sol)\n }\n}\n\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toInt)\n val k = in.next().toInt\n val after = in.next().split(' ').map(_.toInt)\n\n def split(start: Int, current: Int, i: Int, sum: Int, answer: List[Array[Int]]): List[Array[Int]] = {\n if (current == n && i == k)\n answer.reverse\n else if (current == n || i == k)\n Nil\n else if (sum + line(current) == after(i))\n split(current + 1, current + 1, i + 1, 0, line.slice(start, current + 1) :: answer)\n else if (sum + line(current) > after(i))\n Nil\n else\n split(start, current + 1, i, sum + line(current), answer)\n }\n\n val sol = split(0, 0, 0, 0, Nil).map(_.toList)\n\n if (sol.exists(l => l.length > 1 && l.distinct.size == 1)) {\n println(\"NO\")\n } else {\n println(\"YES\")\n val res = sol.zipWithIndex.filter(_._1.length > 1).flatMap {\n case (l, index) =>\n val maxValue = l.max\n val maxIndex =\n l.indices.find(i => l(i) == maxValue && ((i != 0 && l(i - 1) != maxValue)\n || (i != l.length - 1 && l(i + 1) != maxValue))).get\n if (maxIndex != 0 && l(maxIndex - 1) != maxValue) {\n (maxIndex to 1 by -1).map(i => s\"${i + index + 1} L\").toList ::: (maxIndex until l.length - 1).map(i => s\"${index + 1} R\").toList\n } else {\n (maxIndex until l.length - 1).map(i => s\"${maxIndex + index + 1} R\").toList ::: (maxIndex to 1 by -1).map(i => s\"${i + index + 1} L\").toList\n }\n }\n println(res.mkString(\"\\n\"))\n }\n\n}\n\n\n"}, {"source_code": "\nimport scala.util._\n\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n\n\n\n\n val n = input.next().toInt\n val a = input.next().split(' ').toSeq.map(_.toLong)\n val k = input.next().toInt\n val b = input.next().split(' ').toSeq.map(_.toLong)\n val res = Try {\n val f = a.foldLeft(Seq.empty[Seq[Long]]) { (l, i) =>\n if (l.isEmpty || l.head.sum == b(l.length - 1)) {\n assert (i <= b(l.length))\n Seq(i) +: l\n } else if (l.head.sum < b(l.length)) {\n assert (l.head.sum + i <= b(l.length))\n (i +: l.head) +: l.tail\n } else {\n throw new Exception()\n }\n }\n assert (f.last.sum == b.last)\n val g = f.map(_.reverse).reverse\n assert(g.forall(l => !l.forall(_ == l.head)))\n g.zipWithIndex.flatMap(pair => {\n val k = pair._1\n val base = pair._2 + 1\n val max = k.max\n val notMaxIndex = k.indexWhere(_ != max)\n val nearestMaxIndex = k.zipWithIndex.filter(pair => pair._1 == max).minBy(a => (a._2 - notMaxIndex).abs)._2\n if (nearestMaxIndex > notMaxIndex) {\n (0 until nearestMaxIndex).reverse.map(a => (a + base, 'L')) ++ (0 until (k.length - nearestMaxIndex - 1)).map(_ => (base, 'R'))\n } else {\n (0 until (k.length - nearestMaxIndex - 1)).map(_ => (nearestMaxIndex + base, 'R')) ++ (0 until nearestMaxIndex).reverse.map(a => (a + base, 'L'))\n }\n })\n }\n val sol = res match {\n case Success(a) => \"YES\" + a.map(b => \"\\n\" + b._1 + \" \" + b._2).mkString\n case Failure(e) => \"NO\"\n }\n\n\n\n println(sol)\n }\n}\n"}, {"source_code": "\nimport scala.util._\n\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n\n\n\n\n val n = input.next().toInt\n val a = input.next().split(' ').toSeq.map(_.toLong)\n val k = input.next().toInt\n val b = input.next().split(' ').toSeq.map(_.toLong)\n val res = Try {\n val f = a.foldLeft(Seq.empty[Seq[Long]]) { (l, i) =>\n if (l.isEmpty || l.head.sum == b(l.length - 1)) {\n assert (i <= b(l.length))\n Seq(i) +: l\n } else if (l.head.sum < b(l.length)) {\n assert (l.head.sum + i <= b(l.length))\n (i +: l.head) +: l.tail\n } else {\n throw new Exception()\n }\n }\n assert (f.last.sum == b.last)\n val g = f.map(_.reverse).reverse\n assert(g.forall(l => !l.forall(_ == l.head)))\n g.zipWithIndex.flatMap(pair => {\n val k = pair._1\n val base = pair._2 + 1\n val max = k.max\n val notMaxIndex = k.indexWhere(_ != max)\n val nearestMaxIndex = k.zipWithIndex.filter(pair => pair._1 == max).minBy(a => (a._2 - notMaxIndex).abs)._2\n if (nearestMaxIndex > notMaxIndex) {\n (0 until nearestMaxIndex).reverse.map(a => (a + base, 'L')) ++ (0 until (k.length - nearestMaxIndex - 1)).map(_ => (base, 'R'))\n } else {\n (0 until (k.length - nearestMaxIndex - 1)).map(_ => (nearestMaxIndex + base, 'R')) ++ (0 until nearestMaxIndex).reverse.map(a => (a + base, 'L'))\n }\n })\n }\n val sol = res match {\n case Success(a) => \"YES\" + a.map(b => \"\\n\" + b._1 + \" \" + b._2).mkString\n case Failure(e) => e.getMessage //\"NO\"\n }\n\n\n\n println(sol)\n }\n}\n\n"}, {"source_code": "\nimport java.io._\n\nimport scala.util._\n\nobject Main {\n\n def main(args: Array[String]) = {\n\n val TEST =\n \"\"\"\n5\n1 1 1 1 2\n3\n1 1 4\n \"\"\".stripMargin.trim\n\n// System.setIn(new ByteArrayInputStream(TEST.getBytes))\n\n val input = scala.io.Source.stdin.getLines()\n\n\n val n = input.next().toInt\n val a = input.next().split(' ').toSeq.map(_.toLong)\n val k = input.next().toInt\n val b = input.next().split(' ').toSeq.map(_.toLong)\n val res = Try {\n val f = a.foldLeft(Seq.empty[Seq[Long]]) { (l, i) =>\n if (l.isEmpty || l.head.sum == b(l.length - 1)) {\n assert (i <= b(l.length))\n Seq(i) +: l\n } else if (l.head.sum < b(l.length - 1)) {\n assert (l.head.sum + i <= b(l.length - 1))\n (i +: l.head) +: l.tail\n } else {\n throw new Exception()\n }\n }\n val g = f.map(_.reverse).reverse\n assert(g.forall(l => l.size == 1 || !l.forall(_ == l.head)))\n g.zipWithIndex.flatMap(pair => {\n val k = pair._1\n val base = pair._2 + 1\n val max = k.max\n val notMaxIndex = k.indexWhere(_ != max)\n val nearestMaxIndex = k.zipWithIndex.filter(pair => pair._1 == max).minBy(a => (a._2 - notMaxIndex).abs)._2\n if (nearestMaxIndex > notMaxIndex) {\n (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L')) ++ (0 until (k.length - nearestMaxIndex - 1)).map(_ => (base, 'R'))\n } else {\n (0 until (k.length - nearestMaxIndex - 1)).map(_ => (nearestMaxIndex + base, 'R')) ++ (0 until nearestMaxIndex).reverse.map(a => (a + base, 'L'))\n }\n })\n }\n val sol = res match {\n case Success(a) => \"YES\" + a.map(b => \"\\n\" + b._1 + \" \" + b._2).mkString\n case Failure(e) => \"NO\"\n }\n\n\n\n println(sol)\n }\n}\n\n"}, {"source_code": "\nimport java.io._\n\nimport scala.util._\n\nobject Main {\n\n def main(args: Array[String]) = {\n\n val TEST =\n \"\"\"3\n |2 2 1\n |1\n |5\n \"\"\".stripMargin.trim\n\n //System.setIn(new ByteArrayInputStream(TEST.getBytes))\n\n val input = scala.io.Source.stdin.getLines()\n\n\n val n = input.next().toInt\n val a = input.next().split(' ').toSeq.map(_.toLong)\n val k = input.next().toInt\n val b = input.next().split(' ').toSeq.map(_.toLong)\n val res = Try {\n val f = a.foldLeft(Seq.empty[Seq[Long]]) { (l, i) =>\n if (l.isEmpty || l.head.sum == b(l.length - 1)) {\n assert (i <= b(l.length))\n Seq(i) +: l\n } else if (l.head.sum < b(l.length - 1)) {\n assert (l.head.sum + i <= b(l.length - 1))\n (i +: l.head) +: l.tail\n } else {\n throw new Exception()\n }\n }\n val g = f.map(_.reverse).reverse\n assert(g.forall(l => l.size == 1 || !l.forall(_ == l.head)))\n g.zipWithIndex.filter(_._1.size > 1).flatMap(pair => {\n val k = pair._1\n val base = pair._2 + 1\n val max = k.max\n val notMaxIndex = k.indexWhere(_ != max)\n val nearestMaxIndex = k.zipWithIndex.filter(pair => pair._1 == max).minBy(a => (a._2 - notMaxIndex).abs)._2\n if (nearestMaxIndex > notMaxIndex) {\n (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L')) ++ (0 until (k.length - nearestMaxIndex - 1)).map(_ => (base, 'R'))\n } else {\n (0 until (k.length - nearestMaxIndex - 1)).map(_ => (nearestMaxIndex + base, 'R')) ++ (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L'))\n }\n })\n }\n val sol = res match {\n case Success(a) => \"YES\" + a.map(b => \"\\n\" + b._1 + \" \" + b._2).mkString\n case Failure(e) => \"NO\"\n }\n\n\n\n println(sol)\n }\n}\n\n"}, {"source_code": "\nimport java.io._\n\nimport scala.util._\n\nobject Main {\n\n def main(args: Array[String]) = {\n\n val TEST =\n \"\"\"2\n |1 2\n |2\n |3 1\n \"\"\".stripMargin.trim\n\n //System.setIn(new ByteArrayInputStream(TEST.getBytes))\n\n val input = scala.io.Source.stdin.getLines()\n\n\n val n = input.next().toInt\n val a = input.next().split(' ').toSeq.map(_.toLong)\n val k = input.next().toInt\n val b = input.next().split(' ').toSeq.map(_.toLong)\n val res = Try {\n assert(a.sum == b.sum)\n val f = a.foldLeft(Seq.empty[Seq[Long]]) { (l, i) =>\n if (l.isEmpty || l.head.sum == b(l.length - 1)) {\n assert (i <= b(l.length))\n Seq(i) +: l\n } else if (l.head.sum < b(l.length - 1)) {\n assert (l.head.sum + i <= b(l.length - 1))\n (i +: l.head) +: l.tail\n } else {\n throw new Exception()\n }\n }\n val g = f.map(_.reverse).reverse\n println(g)\n assert(g.forall(l => l.size == 1 || !l.forall(_ == l.head)))\n g.zipWithIndex.filter(_._1.size > 1).flatMap(pair => {\n val k = pair._1\n val base = pair._2 + 1\n val max = k.max\n val notMaxIndex = k.indexWhere(_ != max)\n val nearestMaxIndex = k.zipWithIndex.filter(pair => pair._1 == max).minBy(a => (a._2 - notMaxIndex).abs)._2\n if (nearestMaxIndex > notMaxIndex) {\n (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L')) ++ (0 until (k.length - nearestMaxIndex - 1)).map(_ => (base, 'R'))\n } else {\n (0 until (k.length - nearestMaxIndex - 1)).map(_ => (nearestMaxIndex + base, 'R')) ++ (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L'))\n }\n })\n }\n val sol = res match {\n case Success(a) => \"YES\" + a.map(b => \"\\n\" + b._1 + \" \" + b._2).mkString\n case Failure(e) => \"NO\"\n }\n\n\n\n println(sol)\n }\n}\n\n"}, {"source_code": "\nimport java.io.FileInputStream\n\nimport scala.util._\n\nobject Main {\n\n def main(args: Array[String]) = {\n\n // System.setIn(new FileInputStream(\"test.txt\"))\n\n val input = scala.io.Source.stdin.getLines()\n\n\n val n = input.next().toInt\n val a = input.next().split(' ').toSeq.map(_.toLong)\n val k = input.next().toInt\n val b = input.next().split(' ').toSeq.map(_.toLong)\n val res = Try {\n val f = a.foldLeft(Seq.empty[Seq[Long]]) { (l, i) =>\n if (l.isEmpty || l.head.sum == b(l.length - 1)) {\n assert (i <= b(l.length))\n Seq(i) +: l\n } else if (l.head.sum < b(l.length - 1)) {\n assert (l.head.sum + i <= b(l.length - 1))\n (i +: l.head) +: l.tail\n } else {\n throw new Exception()\n }\n }\n val g = f.map(_.reverse).reverse\n assert (g.last.sum == b.last)\n assert(g.forall(l => !l.forall(_ == l.head)))\n g.zipWithIndex.flatMap(pair => {\n val k = pair._1\n val base = pair._2 + 1\n val max = k.max\n val notMaxIndex = k.indexWhere(_ != max)\n val nearestMaxIndex = k.zipWithIndex.filter(pair => pair._1 == max).minBy(a => (a._2 - notMaxIndex).abs)._2\n if (nearestMaxIndex > notMaxIndex) {\n (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L')) ++ (0 until (k.length - nearestMaxIndex - 1)).map(_ => (base, 'R'))\n } else {\n (0 until (k.length - nearestMaxIndex - 1)).map(_ => (nearestMaxIndex + base, 'R')) ++ (0 until nearestMaxIndex).reverse.map(a => (a + base, 'L'))\n }\n })\n }\n val sol = res match {\n case Success(a) => \"YES\" + a.map(b => \"\\n\" + b._1 + \" \" + b._2).mkString\n case Failure(e) => \"NO\"\n }\n\n\n\n println(sol)\n }\n}\n\n"}, {"source_code": "\nimport java.io._\n\nimport scala.util._\n\nobject Main {\n\n def main(args: Array[String]) = {\n\n val TEST =\n \"\"\"3\n |2 2 1\n |1\n |5\n \"\"\".stripMargin.trim\n\n System.setIn(new ByteArrayInputStream(TEST.getBytes))\n\n val input = scala.io.Source.stdin.getLines()\n\n\n val n = input.next().toInt\n val a = input.next().split(' ').toSeq.map(_.toLong)\n val k = input.next().toInt\n val b = input.next().split(' ').toSeq.map(_.toLong)\n val res = Try {\n val f = a.foldLeft(Seq.empty[Seq[Long]]) { (l, i) =>\n if (l.isEmpty || l.head.sum == b(l.length - 1)) {\n assert (i <= b(l.length))\n Seq(i) +: l\n } else if (l.head.sum < b(l.length - 1)) {\n assert (l.head.sum + i <= b(l.length - 1))\n (i +: l.head) +: l.tail\n } else {\n throw new Exception()\n }\n }\n val g = f.map(_.reverse).reverse\n assert(g.forall(l => l.size == 1 || !l.forall(_ == l.head)))\n g.zipWithIndex.filter(_._1.size > 1).flatMap(pair => {\n val k = pair._1\n val base = pair._2 + 1\n val max = k.max\n val notMaxIndex = k.indexWhere(_ != max)\n val nearestMaxIndex = k.zipWithIndex.filter(pair => pair._1 == max).minBy(a => (a._2 - notMaxIndex).abs)._2\n if (nearestMaxIndex > notMaxIndex) {\n (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L')) ++ (0 until (k.length - nearestMaxIndex - 1)).map(_ => (base, 'R'))\n } else {\n (0 until (k.length - nearestMaxIndex - 1)).map(_ => (nearestMaxIndex + base, 'R')) ++ (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L'))\n }\n })\n }\n val sol = res match {\n case Success(a) => \"YES\" + a.map(b => \"\\n\" + b._1 + \" \" + b._2).mkString\n case Failure(e) => \"NO\"\n }\n\n\n\n println(sol)\n }\n}\n\n"}], "src_uid": "a37f805292e68bc0ad4555fa32d180ef"} {"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextLongs(n)\n var res = n\n if (res == 1) {\n res = 0\n }\n\n for (l <- 0 until n) {\n val al = as(l)\n for (r <- l + 1 until n) {\n val ar = as(r)\n val d = r - l\n var cntBad = 0\n var i = 0\n while (i < n) {\n val expected = al + (i - l) * (ar - al) / d\n if (expected != as(i) || (i - l) * (ar - al) % d != 0) cntBad += 1\n// println(i, expected, l, r, d)\n i += 1\n }\n if (cntBad < res) {\n res = cntBad\n }\n }\n }\n\n out.println(res)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(val l: Int, val r: Int, val p: Boolean)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return (r-l).compareTo(that.r-that.l)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mapp = mutable.Map[pair, Int]()\n\n val t = readInt()\n\n\n for (tt <- 1 to t) {\n val n = readInt()\n val arr = new Array[Int](n+1)\n val d = new Array[Int](n+1)\n for (i <- 1 to n) {\n arr(i) = readInt()\n }\n var ans = 0\n var a = 0\n var b = 0\n var c = false\n var tmp = 0\n var p = pair(0, 0, false)\n for (i <- 1 to n) {\n val mp = mutable.Map[pair, Int]()\n //println(i)\n for (j <- 1 to n) {\n if (i != j) {\n c = false\n a = arr(i) - arr(j)\n b = i - j\n if (a < 0) {\n a *= -1\n c = !c\n }\n if (b < 0) {\n b *= -1\n c = !c\n }\n tmp = gcd(a, b)\n if (tmp != 0) {\n a /= tmp\n b /= tmp\n }\n p = pair(a, b, c)\n //println(j, a, b, c)\n if (!mp.contains(p)) {\n mp(p) = 1\n d(i) = max(d(i), 1)\n } else {\n tmp = mp(p)\n mp(p) = tmp + 1\n d(i) = max(d(i), tmp + 1)\n }\n }\n }\n ans = max(ans, d(i) + 1)\n }\n writer.println(n - ans)\n\n def check(kk: Long): Boolean = {\n return true\n }\n def bs(st:Long, en:Long): Long = {\n if (en - st <= 1L) {\n if (check(en))\n return en\n else\n return st\n }\n val mid = (st + en) / 2L\n if (check(mid))\n return bs(mid, en)\n else\n return bs(st, mid)\n }\n }\n writer.flush()\n}"}], "negative_code": [], "src_uid": "6aca8c549822adbe96a58aee4b0d4b3f"} {"source_code": "import scala.io.StdIn._\n\nobject B_1265 extends App {\n val t = readInt()\n 1 to t foreach { _ =>\n val n = readInt()\n val A = readLine().split(\" \").map(_.toInt)\n val pos = A.zipWithIndex.toMap\n\n var posMax = pos(1)\n var posMin = pos(1)\n val result = Array.fill(n)(false)\n result(0) = true\n\n 2 to n foreach { m =>\n posMax = Math.max(posMax, pos(m))\n posMin = Math.min(posMin, pos(m))\n result(posMax - posMin) = posMax - posMin + 1 == m\n// println(s\"$m -> ($posMin, $posMax)\")\n }\n\n println(result.map(x => if (x) \"1\" else \"0\").mkString)\n //100000000000000000000001\n\n }\n}\n", "positive_code": [{"source_code": "object _1265B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val ps = io.read[Seq[Int]].zipWithIndex.toMap\n val n = ps.size\n\n var l = n\n var r = -1\n\n val ans = (1 to n) map {i =>\n l = l min ps(i)\n r = r max ps(i)\n if (r - l + 1 == i) 1 else 0\n }\n\n io.write(ans.mkString)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject B_1265 extends App {\n val t = readInt()\n 1 to t foreach { _ =>\n val n = readInt()\n val A = readLine().split(\" \").map(_.toInt)\n val pos = A.zipWithIndex.toMap\n\n var posMax = pos(1)\n var posMin = pos(1)\n val result = Array.fill(n)(false)\n result(0) = true\n\n 2 to n foreach { m =>\n posMax = Math.max(posMax, pos(m))\n posMin = Math.min(posMin, pos(m))\n result(posMax - posMin) = true\n }\n\n println(result.map(x => if (x) \"1\" else \"0\").mkString)\n\n }\n}\n"}], "src_uid": "ea3ce069895b6fc0f354f0118c7c9fff"} {"source_code": "object L{\n def main (args: Array[String])= {\n val sc = new java.util.Scanner(System.in)\n val n, k = sc.nextInt()\n val s = sc.next()\n var a = new Array[Int](n+5)\n var last = 0\n for (i<-0 to n-1) {\n if (s.charAt(i)=='0') last=i\n a(i)=last\n }\n var lo = -1\n var hi = n\n while (lo+1 1) {\n val m = (l + r) / 2\n var pos = 0\n var good = false\n Breaks.breakable {\n for (i <- 0 until (k - 1)) {\n pos = d(Math.min(n - 1, pos + m + 1))\n if (pos == n - 1) {\n good = true\n Breaks.break()\n }\n }\n }\n if (good) {\n r = m\n } else {\n l = m\n }\n }\n println(r)\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\nimport scala.util.control.Breaks\n\n/**\n * @author Daniyar Itegulov\n */\nobject L extends App {\n val sc = new java.util.Scanner(System.in)\n val n, k = sc.nextInt()\n val s = sc.next().map(_ == '0')\n var l = 0\n var r = n - 2\n while (r - l > 1) {\n val m = (l + r) / 2\n var pos = 0\n var good = false\n Breaks.breakable {\n for (i <- 0 until (k - 1)) {\n pos = Math.min(n - 1, pos + m + 1)\n while (!s(pos)) {\n pos -= 1\n }\n if (pos == n - 1) {\n good = true\n Breaks.break()\n }\n }\n }\n if (good) {\n r = m\n } else {\n l = m\n }\n }\n println(r)\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.util.control.Breaks\n\n/**\n * @author Daniyar Itegulov\n */\nobject L extends App {\n val sc = new java.util.Scanner(System.in)\n val n, k = sc.nextInt()\n val s = sc.next().map(_ == '0')\n if (n == 2) {\n print(0)\n System.exit(0)\n }\n var l = 0\n var r = n - 1\n while (r - l > 1) {\n val m = (l + r) / 2\n var pos = 0\n var good = false\n Breaks.breakable {\n for (i <- 0 until (k - 1)) {\n pos = Math.min(n - 1, pos + m + 1)\n while (!s(pos)) {\n pos -= 1\n }\n if (pos == n - 1) {\n good = true\n Breaks.break()\n }\n }\n }\n if (good) {\n r = m\n } else {\n l = m\n }\n }\n println(r)\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.util.control.Breaks\n\n/**\n * @author Daniyar Itegulov\n */\nobject L extends App {\n val sc = new java.util.Scanner(System.in)\n val n, k = sc.nextInt()\n val s = sc.next().map(_ == '0')\n var l = 0\n var r = n - 1\n while (r - l > 1) {\n val m = (l + r) / 2\n var pos = 0\n var good = false\n Breaks.breakable {\n for (i <- 0 until (k - 1)) {\n val prevPos = pos\n pos = Math.min(n - 1, pos + m + 1)\n while (!s(pos)) {\n pos -= 1\n }\n if (pos == n - 1) {\n good = true\n Breaks.break()\n }\n }\n }\n if (good) {\n r = m\n } else {\n l = m\n }\n }\n println(r)\n}\n"}], "src_uid": "e33b0a752dc1aba25da21e20435e3fe2"} {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Codeforces1163B {\n\n def getLongestPossibleStreak(n: Int, u: Seq[Int]): Int = {\n val isStreak = new Array[Boolean](n)\n val colorFrequencyMap = new mutable.HashMap[Int, Int]()\n val countTracker = new FrequencyCountTracker\n for (i <- 0 until n) {\n val previousFrequency = colorFrequencyMap.getOrElse(u(i), 0)\n colorFrequencyMap(u(i)) = previousFrequency + 1\n\n countTracker.decreaseCount(previousFrequency)\n countTracker.increaseCount(previousFrequency + 1)\n\n isStreak(i) = countTracker.isEqualFrequencyByRemovingOne\n }\n for (i <- isStreak.indices.reverse) {\n if (isStreak(i)) return i + 1\n }\n 1\n }\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readLine().trim.toInt\n val u = StdIn.readLine().trim.split(\" \").map(_.toInt)\n val longestPossibleStreak = getLongestPossibleStreak(n, u)\n println(longestPossibleStreak)\n }\n\n class FrequencyCountTracker {\n val frequencyCountMap = new mutable.HashMap[Int, Int]()\n\n def increaseCount(frequency: Int): Unit = {\n val previousFrequencyCount = frequencyCountMap.getOrElse(frequency, 0)\n frequencyCountMap(frequency) = previousFrequencyCount + 1\n }\n\n def decreaseCount(frequency: Int): Unit = {\n if (frequency == 0) return\n val previousFrequencyCount = frequencyCountMap(frequency)\n previousFrequencyCount match {\n case 1 => frequencyCountMap.remove(frequency)\n case _ => frequencyCountMap(frequency) = previousFrequencyCount - 1\n }\n }\n\n def isEqualFrequencyByRemovingOne: Boolean = {\n frequencyCountMap.keys.size match {\n case 1 =>\n frequencyCountMap.keys.head == 1 || frequencyCountMap.values.head == 1\n case 2 =>\n val maxFrequency = frequencyCountMap.keys.max\n val minFrequency = frequencyCountMap.keys.min\n if (minFrequency == 1 && frequencyCountMap(minFrequency) == 1) true\n else if (minFrequency == maxFrequency - 1 && frequencyCountMap(maxFrequency) == 1) true\n else false\n case _ =>\n false\n }\n }\n }\n\n}\n", "positive_code": [{"source_code": "object _1163B1 extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val nums = io.read[Vector[Int]]\n\n val numToCount, countToMap = mutable.Map.empty[Int, Int].withDefaultValue(0)\n val ans = nums map {i =>\n val curr = numToCount(i)\n if (curr > 0) {\n countToMap(curr) -= 1\n if (countToMap(curr) <= 0) countToMap.remove(curr)\n }\n numToCount(i) = curr + 1\n countToMap(curr + 1) += 1\n\n val it = countToMap.keysIterator\n\n val res = countToMap.size match {\n case 1 =>\n val c1 = it.next()\n c1 == 1 || countToMap(c1) == 1\n case 2 =>\n val _c1, _c2 = it.next()\n val c1 = _c1 min _c2\n val c2 = _c1 max _c2\n\n ((c1 == 1) && countToMap(c1) == 1) ||\n (c1 == c2 - 1 && countToMap(c2) == 1)\n case _ => false\n }\n //debug(i, numToCount, countToMap, res)\n res\n }\n\n io.write(ans.lastIndexWhere(identity) + 1)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val C = Array.ofDim[Int](1e5.toInt)\n val D = mutable.Map[Int, Int]()\n var ans = 0\n var mx = 0\n REP(N) { i =>\n val u = ni() - 1\n\n if (D.contains(C(u))) {\n D(C(u)) = D(C(u)) - 1\n if (D(C(u)) == 0) D.remove(C(u))\n }\n\n C(u) += 1\n mx = max(mx, C(u))\n\n if (!D.contains(C(u))) D(C(u)) = 0\n D(C(u)) = D(C(u)) + 1\n\n if (D.size == 2) {\n // 最大を一つ減らせばいい\n if (D(mx) == 1 && D.contains(mx - 1)) {\n ans = i + 1\n // 1を一つ減らせばいい\n } else if (D.contains(1) && D(1) == 1) {\n ans = i + 1\n }\n } else if (D.size == 1) {\n if (mx == 1 || D(mx) == 1) {\n ans = i + 1\n }\n }\n }\n\n out.println(ans)\n }\n}"}], "negative_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val C = Array.ofDim[Int](1e5.toInt)\n val D = mutable.Map[Int, Int]()\n var ans = 0\n var mx = 0\n REP(N) { i =>\n val u = ni() - 1\n\n if (D.contains(C(u))) {\n D(C(u)) = D(C(u)) - 1\n if (D(C(u)) == 0) D.remove(C(u))\n }\n\n C(u) += 1\n mx = max(mx, C(u))\n\n if (!D.contains(C(u))) D(C(u)) = 0\n D(C(u)) = D(C(u)) + 1\n\n if (D.size == 2) {\n // 最大を一つ減らせばいい\n if (D(mx) == 1 && D.contains(mx - 1)) {\n ans = i + 1\n // 1を一つ減らせばいい\n } else if (D.contains(1) && D(1) == 1) {\n ans = i + 1\n }\n } else if (D.size == 1) {\n if (mx == 1) {\n ans = i + 1\n }\n }\n }\n\n out.println(ans)\n }\n}"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val C = Array.ofDim[Int](1e5.toInt)\n val D = mutable.Map[Int, Int]()\n var ans = 0\n var mx = 0\n REP(N) { i =>\n val u = ni() - 1\n C(u) += 1\n mx = max(mx, C(u))\n if (!D.contains(C(u))) D(C(u)) = 0\n D(C(u)) = D(C(u)) + 1\n if (C(u) - 1 > 0) {\n D(C(u) - 1) = D(C(u) - 1) - 1\n if (D(C(u) - 1) == 0) D.remove(C(u) - 1)\n }\n\n if (D.size == 2) {\n // 最大を一つ減らせばいい\n if (D(mx) == 1 && D.contains(mx - 1)) {\n ans = i + 1\n // 1を一つ減らせばいい\n } else if (D.contains(1) && D(1) == 1) {\n ans = i + 1\n }\n } else if (D.size == 1) {\n if (mx == 1) {\n ans = i + 1\n }\n }\n }\n\n out.println(ans)\n }\n}"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val C = Array.ofDim[Int](1e5.toInt)\n val D = mutable.Map[Int, Int]()\n var ans = 0\n var mx = 0\n REP(N) { i =>\n val u = ni() - 1\n C(u) += 1\n mx = max(mx, C(u))\n if (!D.contains(C(u))) D(C(u)) = 0\n D(C(u)) += 1\n if (C(u) - 1 > 0) {\n D(C(u) - 1) -= 1\n if (D(C(u) - 1) == 0) D.remove(C(u) - 1)\n }\n\n if (D.size == 2) {\n // 最大を一つ減らせばいい\n if (D(mx) == 1 && D.contains(mx - 1)) {\n ans = i + 1\n // 1を一つ減らせばいい\n } else if (D.contains(1) && D(1) == 1) {\n ans = i + 1\n }\n } else if (D.size == 1) {\n if (mx == 1) ans = i + 1\n }\n }\n\n out.println(ans)\n }\n}"}], "src_uid": "886d8d7103f0a7403b06b80b914ee498"} {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val s = readLine\n println(s + s.reverse)\n}\n", "positive_code": [{"source_code": "object A932 {\n \n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n \n def main(args: Array[String]): Unit = {\n var tests = 1 // readInt\n while(tests > 0) {\n val n = read\n out.print(n)\n out.println(n.reverse)\n tests -= 1\n }\n out.close()\n }\n \n \n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n \n @inline def read: String = input.readLine()\n \n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n \n def readInt: Int = tokenizeLine.nextToken.toInt\n \n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n \n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n \n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n \n}"}, {"source_code": "object A extends App {\n val a = scala.io.StdIn.readLine()\n def b(a: String): String = {\n def _b(l: List[Char], r: List[Char], i: Int, j: Int): String =\n if (i > j) l.reverse.mkString(\"\") + r.mkString(\"\")\n else {\n val ai = a(i)\n val aj = a(j)\n if (ai == aj) _b(ai :: l, aj :: l, i + 1, j - 1)\n else _b(ai :: l, ai :: l, i + 1, j)\n }\n\n _b(Nil, Nil, 0, a.length - 1)\n }\n\n println(b(a))\n}\n"}, {"source_code": "object _932A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val a = io.read[String]\n io.write(a + a.reverse)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p._1, ev(p._2))\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n //def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "9b1887582a9eb7cff49994ddcc2ee9b8"} {"source_code": "object P102B extends App {\n def f(n: String) = n.toCharArray.map(_.getNumericValue).sum.toString()\n var n = readLine\n var c = 0\n while (n.size > 1) {\n n = f(n)\n c += 1\n }\n print(c)\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val data = in.next()\n var sum = data.foldLeft(0l){case (acc, el) => acc + el.asDigit}\n var i = 0\n if (data.length != 1) {\n i = 1\n while (sum > 9) {\n i += 1\n sum = sum.toString.foldLeft(0l) { case (acc, el) => acc + el.asDigit }\n }\n }\n println(i)\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n var n = readLine()\n var step = 0\n while(n.size != 1) {\n val sum = n.map(_.toLong - '0').sum\n n = sum.toString\n step += 1\n }\n println(step)\n } \n}"}, {"source_code": "object Solver {\n def main(args: Array[String]) {\n var data = Console.readLine\n var count = 0\n\n while (data.length > 1) {\n data = data.map(_.toInt - '0'.toInt).reduceRight(_ + _).toString\n count += 1\n }\n println(count)\n }\n}"}], "negative_code": [], "src_uid": "ddc9201725e30297a5fc83f4eed75fc9"} {"source_code": "object _1729C extends CodeForcesAppMulti({io =>\n import Math._\n val line = io.nextLine().toSeq.map(_ - 'a' + 1)\n val n = line.length\n val (start, end) = (line(0), line(n-1))\n var indexed = line.zipWithIndex\n .collect({case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i+1)})\n .drop(1).dropRight(1).sorted\n\n if (start > end) indexed = indexed.reverse\n val cost = (start - end).abs\n val m = indexed.length + 2\n val ans = indexed.map(_._2).mkString(\" \")\n\n io.printLine(\n s\"$cost $m\",\n s\"1 $ans $n\".replace(\" \", \" \")\n )\n})\n/**************************** [Ignore Template Below] **************************************/\nclass CodeForcesApp(solution: IO => Any) {\n def debug(x: => Any): Unit = if (!sys.props.contains(\"ONLINE_JUDGE\")) println(s\">>> DEBUG: $x\")\n def run(io: IO): Unit = try solution(io) finally io.close()\n def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))\n}\nclass CodeForcesAppMulti(solution: IO => Any) extends CodeForcesApp(solution) {\n override def run(io: IO) = try io.repeat()(solution(io)) finally io.close()\n}\n// Java I/O wrapper\nimport java.io._\nclass IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {\n def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))\n\n val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))\n\n def nextLine(): String = in.readLine()\n def nextStr(): String = tokens.next()\n def nextInt(): Int = nextStr().toInt\n def nextLong(): Long = nextStr().toLong\n def nextDouble(): Double = nextStr().toDouble\n def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }\n\n def print(xs: Any*): Unit = out.print(xs.mkString(\" \"))\n def printLine(xs: Any*): Unit = if (xs.isEmpty) out.println() else xs.foreach(out.println)\n\n override def close() = out.close()\n}\n", "positive_code": [{"source_code": "object _1729C extends CodeForcesApp{\n import Math._\n override def solve(io: IO) = io.repeat() {\n val line = io.nextLine().toSeq.map(_ - 'a' + 1)\n val n = line.length\n val (start, end) = (line(0), line(n - 1))\n var indexed = line.zipWithIndex\n .collect({ case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i + 1) })\n .drop(1).dropRight(1).sorted\n\n if (start > end) indexed = indexed.reverse\n val cost = (start - end).abs\n val m = indexed.length + 2\n val ans = indexed.map(_._2).mkString(\" \")\n\n io.print(cost, m).printLine().print(1, ans, n).printLine()\n }\n}\n/**************************** [Ignore Template Below] **************************************/\ntrait CodeForcesApp {\n def debug(x: => Any): Unit = if (!sys.props.contains(\"ONLINE_JUDGE\")) println(s\">>> DEBUG: $x\")\n def run(io: IO): Unit = try solve(io) finally io.close()\n def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))\n def solve(io: IO): Any\n}\n// Java I/O wrapper\nimport java.io._\nclass IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {\n def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))\n\n val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))\n\n def nextLine(): String = in.readLine()\n def nextStr(): String = tokens.next()\n def nextInt(): Int = nextStr().toInt\n def nextLong(): Long = nextStr().toLong\n def nextDouble(): Double = nextStr().toDouble\n def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }\n\n def print(xs: Any*): this.type = { out.print(xs.mkString(\" \")); this }\n def printLine(xs: Any*): this.type = { if (xs.isEmpty) out.println() else xs.foreach(out.println); this }\n\n override def close() = out.close()\n}\n"}, {"source_code": "object _1729C extends CodeForcesApp{\n import Math._\n override def solve(io: IO) = io.repeat() {\n val line = io.nextLine().toSeq.map(_ - 'a' + 1)\n val n = line.length\n val (start, end) = (line(0), line(n - 1))\n var indexed = line.zipWithIndex\n .collect({ case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i + 1) })\n .drop(1).dropRight(1).sorted\n\n if (start > end) indexed = indexed.reverse\n val cost = (start - end).abs\n val m = indexed.length + 2\n val ans = indexed.map(_._2).mkString(\" \")\n\n io.printLine(\n s\"$cost $m\",\n s\"1 $ans $n\".replace(\" \", \" \")\n )\n }\n}\n/**************************** [Ignore Template Below] **************************************/\ntrait CodeForcesApp {\n def debug(x: => Any): Unit = if (!sys.props.contains(\"ONLINE_JUDGE\")) println(s\">>> DEBUG: $x\")\n def run(io: IO): Unit = try solve(io) finally io.close()\n def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))\n def solve(io: IO): Any\n}\n// Java I/O wrapper\nimport java.io._\nclass IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {\n def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))\n\n val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))\n\n def nextLine(): String = in.readLine()\n def nextStr(): String = tokens.next()\n def nextInt(): Int = nextStr().toInt\n def nextLong(): Long = nextStr().toLong\n def nextDouble(): Double = nextStr().toDouble\n def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }\n\n def print(xs: Any*): Unit = out.print(xs.mkString(\" \"))\n def printLine(xs: Any*): Unit = if (xs.isEmpty) out.println() else xs.foreach(out.println)\n\n override def close() = out.close()\n}\n"}, {"source_code": "object _1729C extends CodeForcesApp({io =>\n import Math._\n\n io.repeat() {\n val line = io.nextLine().toSeq.map(_ - 'a' + 1)\n val n = line.length\n val (start, end) = (line(0), line(n-1))\n var indexed = line.zipWithIndex\n .collect({case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i+1)})\n .drop(1).dropRight(1).sorted\n\n if (start > end) indexed = indexed.reverse\n val cost = (start - end).abs\n val m = indexed.length + 2\n val ans = indexed.map(_._2).mkString(\" \")\n\n io.printLine(\n s\"$cost $m\",\n s\"1 $ans $n\".replace(\" \", \" \")\n )\n }\n})\n/**************************** [Ignore Template Below] **************************************/\nclass CodeForcesApp(solution: IO => Any) {\n def debug(x: => Any): Unit = if (!sys.props.contains(\"ONLINE_JUDGE\")) println(s\">>> DEBUG: $x\")\n def run(io: IO): Unit = try solution(io) finally io.close()\n def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))\n}\n// Java I/O wrapper\nimport java.io._\nclass IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {\n def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))\n override def close() = out.close()\n val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))\n // input utils\n def nextLine(): String = in.readLine()\n def nextStr(): String = tokens.next()\n def nextInt(): Int = nextStr().toInt\n def nextLong(): Long = nextStr().toLong\n def nextDouble(): Double = nextStr().toDouble\n def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }\n //output utils\n def print(xs: Any*): Unit = out.print(xs.mkString(\" \"))\n def printLine(xs: Any*): Unit = if (xs.isEmpty) out.println() else xs.foreach(out.println)\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\nobject _1729C extends CodeForcesApp {\n import Math._\n\n override def solve() = repeat() {\n val line = nextLine().toSeq.map(_ - 'a' + 1)\n val n = line.length\n val (start, end) = (line(0), line(n-1))\n var indexed = line.zipWithIndex\n .collect({case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i+1)})\n .drop(1).dropRight(1).sorted\n\n if (start > end) indexed = indexed.reverse\n val cost = (start - end).abs\n val m = indexed.length + 2\n val ans = indexed.map(_._2).mkString(\" \")\n\n printLine(\n s\"$cost $m\",\n s\"1 $ans $n\".replace(\" \", \" \")\n )\n }\n}\n/**************************** [Ignore Template Below] **************************************/\ntrait CodeForcesApp {\n import java.io._\n private var in = new BufferedReader(new InputStreamReader(System.in))\n private var out = new PrintWriter(System.out)\n\n def setIO(inputFile: File, outputFile: File): Unit = {\n in = new BufferedReader(new FileReader(inputFile))\n out = new PrintWriter(new FileWriter(outputFile))\n }\n\n val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))\n\n def nextLine(): String = in.readLine()\n def nextStr(): String = tokens.next()\n def nextInt(): Int = nextStr().toInt\n def nextLong(): Long = nextStr().toLong\n def nextDouble(): Double = nextStr().toDouble\n def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n def query[A](query: String)(res: => A): A = {printLine(query); out.flush(); res}\n\n def print(xs: Any*): Unit = out.print(xs.mkString(\" \"))\n def printLine(xs: Any*): Unit = if (xs.isEmpty) out.println() else xs.foreach(out.println)\n def debug(x: => Any): Unit = if (!sys.props.contains(\"ONLINE_JUDGE\")) println(s\">>> DEBUG: $x\")\n\n def main(args: Array[String]): Unit = try solve() finally out.flush()\n def solve(): Any\n}\n"}, {"source_code": "object _1729C extends CodeForcesApp {\n import Math._\n\n override def solve() = repeat() {\n val line = nextLine().toSeq.map(_ - 'a' + 1)\n val n = line.length\n val (start, end) = (line(0), line(n-1))\n var indexed = line.zipWithIndex.collect({case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i+1)})\n .drop(1).dropRight(1)\n .sorted\n\n if (start > end) indexed = indexed.reverse\n val cost = (start - end).abs\n val m = indexed.length + 2\n val ans = indexed.map(_._2).mkString(\" \")\n\n out.println(s\"$cost $m\")\n out.println(s\"1 $ans $n\".replace(\" \", \" \"))\n }\n}\n/**************************** [Ignore Template Below] **************************************/\ntrait CodeForcesApp {\n import java.io._\n var in = new BufferedReader(new InputStreamReader(System.in))\n var out = new PrintWriter(System.out)\n\n val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))\n\n def nextLine(): String = in.readLine()\n def nextStr(): String = tokens.next()\n def nextInt(): Int = nextStr().toInt\n def nextLong(): Long = nextStr().toLong\n def nextDouble(): Double = nextStr().toDouble\n def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n def query[A](query: String, res: => A): A = {out.println(query); out.flush(); res}\n\n def debug(x: => Any): Unit = if (!sys.props.contains(\"ONLINE_JUDGE\")) println(s\">>> DEBUG: $x\")\n def illegal(msg: String = \"can't happen\") = throw new IllegalStateException(msg)\n\n def main(args: Array[String]): Unit = try solve() finally out.flush()\n def solve(): Any\n}\n"}], "negative_code": [{"source_code": "object _1729C extends CodeForcesApp {\n import Math._\n\n override def solve() = repeat() {\n val line = nextLine().toSeq.map(_ - 'a' + 1)\n val (start, end) = (line.head, line.last)\n var indexed = line.zipWithIndex.collect({case (n, i) if min(start, end) <= n && n <= max(start, end) => (n, i+1)}).sorted\n if (end < start) indexed = indexed.reverse\n val cost = (start - end).abs\n val m = indexed.length\n val ans = indexed.map(_._2).mkString(\" \")\n out.println(s\"$cost $m\")\n out.println(ans)\n }\n}\n/**************************** [Ignore Template Below] **************************************/\ntrait CodeForcesApp {\n import java.io._\n var in = new BufferedReader(new InputStreamReader(System.in))\n var out = new PrintWriter(System.out)\n\n val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))\n\n def nextLine(): String = in.readLine()\n def nextStr(): String = tokens.next()\n def nextInt(): Int = nextStr().toInt\n def nextLong(): Long = nextStr().toLong\n def nextDouble(): Double = nextStr().toDouble\n def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n def query[A](query: String, res: => A): A = {out.println(query); out.flush(); res}\n\n def debug(x: => Any): Unit = if (!sys.props.contains(\"ONLINE_JUDGE\")) println(s\">>> DEBUG: $x\")\n def illegal(msg: String = \"can't happen\") = throw new IllegalStateException(msg)\n\n def main(args: Array[String]): Unit = try solve() finally out.flush()\n def solve(): Any\n}\n"}], "src_uid": "d17c9f91504e1d4c4eae7294bf09dcfc"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n import java.util\n val N, M = ni()\n val (p, c) = na2(N)\n\n var vote1 = 0\n val V = Array.fill[java.util.ArrayList[Integer]](M)(new util.ArrayList())\n REP(N) { i =>\n if (p(i) == 1) vote1 += 1\n else V(p(i) - 1).add(c(i))\n }\n REP(M) { i =>\n import java.util.Collections\n Collections.sort(V(i))\n }\n\n val ans = map(N) { remain =>\n var res = 0L\n var cnt = 0\n var mx = 0\n val q = new java.util.PriorityQueue[Int]()\n REP(M) { m =>\n val v = V(m)\n val n = v.size()\n\n val del = if (n > remain) v.size - remain else 0\n REP(del) { k =>\n res += v.get(k)\n cnt += 1\n }\n REP(n) { k =>\n if (k >= del) q.add(v.get(k))\n }\n mx = max(mx, n - del)\n }\n\n if (vote1 + cnt <= mx) {\n REP(mx + 1 - vote1 - cnt) { _ =>\n res += q.poll()\n }\n }\n\n res\n }.min\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "import java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\nimport scala.collection.mutable.PriorityQueue\nimport java.security.SecureRandom\n\nobject CF_503_C { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// println(Test.big)\n// runTest(Test.big)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading \n val line = readLine\n val n = line.int\n val m = line.int\n val vArr = new Array[(Int, Int)](n)\n val pArr = new Array[Int](m+1)\n var pQ = Array.fill[List[Int]](m+1)(List())\n (0 until n).foreach(x => {\n val vLine = readLine\n val p = vLine.int\n val money = vLine.int\n vArr(x) = (p, money)\n pArr(p) += 1\n pQ(p) ::= money\n })\n \n pQ = pQ.map(_.sorted)\n \n val from = if (m == 1) pArr(1) else pArr.drop(2).min+1\n val levels = (from to pArr.max+1) \n \n val variants = levels.map{ l =>\n debug(\"level=\" + l)\n val parts = pArr.clone()\n val prices = pQ.clone\n var variant = 0l\n (2 to m).foreach{ pp =>\n while (parts(pp) >= l) {\n val vv = prices(pp).head;\n prices(pp) = prices(pp).tail\n// debug(s\" take from $pp - $vv\")\n parts(1) += 1\n parts(pp) -= 1\n variant += vv\n }\n }\n val toTakeFromLeft = if (parts(1) < l) l - parts(1) else 0\n var ll: List[(Int, Int)] = List()\n for(i <- 2 until prices.length) {\n prices(i).foreach(lp => ll ::= (lp, i) )\n }\n \n val left2 = ll.toArray.sorted.take(toTakeFromLeft)\n \n// val unsortedLeft = prices.zipWithIndex.drop(2).flatMap(x => x._1.map(y => (y, x._2)))\n// val left = unsortedLeft.sortBy(_._1).take(toTakeFromLeft)\n left2.foreach{ x =>\n// debug(s\" take left from ${x._2} - ${x._1}\")\n parts(1) += 1\n parts(x._2) -= 1\n variant += x._1\n }\n \n val maxLeft = if (m == 1) 0 else parts.drop(2).max\n if (maxLeft >= parts(1)) -1\n else variant\n \n }.filterNot(_ == -1)\n \n outLn(variants.min+\"\")\n \n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n1 2\n1 100 \n\"\"\"\n\nval sa2 = \"\"\"\n5 5\n2 100\n3 200\n4 300\n5 400\n5 900 \n\"\"\" //500\n\nval sa3 = \"\"\"\n5 5\n2 100\n3 200\n4 300\n5 800\n5 900 \n\"\"\" //600\n\nval big = {\n var rr = \"3000 3000\\n\"\n for (i <- 1 to 3000) {\n rr += \"3000 \" + new SecureRandom().nextInt().abs + \"\\n\" \n }\n rr\n }\n\n}\n\n}\n\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n import java.util\n val N, M = ni()\n val (p, c) = na2(N)\n\n var vote1 = 0\n val V = Array.fill[java.util.ArrayList[Integer]](M)(new util.ArrayList())\n REP(N) { i =>\n if (p(i) == 1) vote1 += 1\n else V(p(i) - 1).add(c(i))\n }\n REP(M) { i =>\n import java.util.Collections\n Collections.sort(V(i))\n }\n\n val ans = map(N) { remain =>\n var res = 0\n var cnt = 0\n var mx = 0\n val q = new java.util.PriorityQueue[Int]()\n REP(M) { m =>\n val v = V(m)\n val n = v.size()\n\n val del = if (n > remain) v.size - remain else 0\n REP(del) { k =>\n res += v.get(k)\n cnt += 1\n }\n REP(n) { k =>\n if (k >= del) q.add(v.get(k))\n }\n mx = max(mx, n - del)\n }\n\n if (vote1 + cnt <= mx) {\n REP(mx + 1 - vote1 - cnt) { _ =>\n res += q.poll()\n }\n }\n\n res\n }.min\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\nimport scala.collection.mutable.PriorityQueue\n\nobject CF_503_C { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.sa3)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading \n val line = readLine\n val n = line.int\n val m = line.int\n val vArr = new Array[(Int, Int)](n)\n val pArr = new Array[Int](m+1)\n val pQ = Array.fill[List[Int]](m+1)(List())\n (0 until n).foreach(x => {\n val vLine = readLine\n val p = vLine.int\n val money = vLine.int\n vArr(x) = (p, money)\n pArr(p) += 1\n// if (pQ(p) == null) {\n// pQ(p) = PriorityQueue()(Ordering.Int.reverse)\n// }\n// pQ(p).enqueue(money)\n pQ(p) ::= money\n })\n \n pQ.map(_.sorted)\n \n val levels = (pArr.drop(2).min+1 to pArr.max+1) \n \n val variants = levels.map{ l =>\n debug(\"level=\" + l)\n val parts = pArr.clone()\n val prices = pQ.clone\n var variant = 0\n (2 to m).foreach{ pp =>\n while (parts(pp) >= l) {\n val vv = prices(pp).head;\n prices(pp) = prices(pp).tail\n debug(s\" take from $pp - $vv\")\n parts(1) += 1\n parts(pp) -= 1\n variant += vv\n }\n }\n val toTakeFromLeft = if (parts(1) < l) l - parts(1) else 0\n val unsortedLeft = prices.zipWithIndex.drop(2).flatMap(x => x._1.map(y => (y, x._2)))\n val left = unsortedLeft.sortBy(_._1).take(toTakeFromLeft)\n left.foreach{ x =>\n debug(s\" take left from ${x._2} - ${x._1}\")\n parts(1) += 1\n parts(x._2) -= 1\n variant += x._1\n }\n \n val maxLeft = parts.drop(2).max\n if (maxLeft >= parts(1)) -1\n else variant\n \n }.filterNot(_ == -1)\n \n outLn(variants.min)\n \n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n1 2\n1 100 \n\"\"\"\n\nval sa2 = \"\"\"\n5 5\n2 100\n3 200\n4 300\n5 400\n5 900 \n\"\"\" //500\n\nval sa3 = \"\"\"\n5 5\n2 100\n3 200\n4 300\n5 800\n5 900 \n\"\"\" //600\n}\n\n}\n\n"}], "src_uid": "2fd9a2f99fab69ac99b5832bb5ef87f9"} {"source_code": "object CF285C extends App {\n val in = new java.util.Scanner(System.in)\n val out = new java.io.PrintWriter(System.out)\n \n val n = in.nextInt\n val v = for (i <- 1 to n) yield in.nextLong\n val s = (v.sorted, (1 to n)).zipped.map((x, y) => scala.math.abs(x - y)).sum\n out.println(s)\n \n out.flush\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readLong\n val a = readLine().split(\" \").map(_.toLong)\n val count = a.sorted.zipWithIndex.foldLeft(0L) { (a, t) =>\n a + (t._2 + 1 - t._1).abs\n }\n println(count)\n }\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.math._\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val N = readInt()\n val list = readLine split (\" \") map (_ toInt) sortWith (_ < _)\n val dList = 1.to(N).map(i => (list(i - 1) - i).abs.toLong);\n print(dList.sum)\n }\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.math._\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val N = readLine.toInt\n val list = readLine split (\" \") map (_ toInt) sortWith (_ < _)\n @tailrec\n def loop(pos: Int = 0, ans: Long = 0): Long = {\n if (pos < list.length) {\n loop(pos + 1, ans + abs(list(pos) - (pos + 1)))\n } else {\n ans\n }\n }\n println(loop())\n }\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.math._\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val N = readInt()\n val list = readLine split(\" \") map(_ toInt) sortWith(_ < _)\n\n @tailrec\n def loop(step: Int = 0, acc: Long = 0): Long = {\n if (step == N) {\n acc\n } else {\n loop(step + 1, acc + abs(list(step) - (step + 1)))\n }\n }\n val ans = loop()\n print(ans)\n }\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _285C extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toLong).sorted\n val b = (a zip (1 to n)).map(i => (i._1 - i._2).abs)\n println(b.sum)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n var changes = 0l\n var counts = Array.ofDim[Int](n)\n data.foreach{i => if (i < 1) {\n counts(0) += 1\n changes += -i + 1\n } else if (i > n) {\n counts(n - 1) += 1\n changes += i - n\n } else {\n counts(i - 1) += 1\n }\n }\n var leftZero = 0\n while (leftZero != n && counts(leftZero) != 0)\n leftZero += 1\n var leftMoreOne = 0\n while (leftMoreOne != n && counts(leftMoreOne) < 2)\n leftMoreOne += 1\n\n while (leftZero < n && leftMoreOne < n) {\n\n changes += Math.abs(leftZero - leftMoreOne)\n counts(leftZero) = 1\n while (leftZero != n && counts(leftZero) != 0)\n leftZero += 1\n counts(leftMoreOne) -= 1\n while (leftMoreOne != n && counts(leftMoreOne) < 2)\n leftMoreOne += 1\n }\n\n println(changes)\n}"}, {"source_code": "object C285 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readLongs(n).sorted.zipWithIndex.map{case (x, y) => (x, y+1)}\n println(in.map{case (a, b) => math.abs(a-b)}.sum)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object CF285C extends App {\n val in = new java.util.Scanner(System.in)\n val out = new java.io.PrintWriter(System.out)\n \n val n = in.nextInt\n val v = for (i <- 1 to n) yield in.nextInt\n val s = v.sorted.view.zip(1 to n).map(x => scala.math.abs(x._1 - x._2).toLong).sum\n out.println(s)\n \n out.flush\n}"}, {"source_code": "object CF285C extends App {\n val in = new java.util.Scanner(System.in)\n val out = new java.io.PrintWriter(System.out)\n \n val n = in.nextInt\n val v = for (i <- 1 to n) yield in.nextLong\n val s = v.sorted.view.zip(1 to n).map(x => scala.math.abs(x._1 - x._2)).sum\n out.println(s)\n \n out.flush\n}"}, {"source_code": "object CF285C extends App {\n val in = new java.util.Scanner(System.in)\n val out = new java.io.PrintWriter(System.out)\n \n val n = in.nextInt\n val v = for (i <- 1 to n) yield in.nextInt.toLong\n val s = v.sorted.view.zipWithIndex.map(x => scala.math.abs(x._1 - (x._2 + 1))).sum\n out.println(s)\n \n out.flush\n}"}, {"source_code": "object CF285C extends App {\n val in = new java.util.Scanner(System.in)\n val out = new java.io.PrintWriter(System.out)\n \n val n = in.nextInt\n val v = for (i <- 1 to n) yield in.nextInt\n val s = v.sorted.zip(1 to n).map(x => scala.math.abs(x._1 - x._2).toLong).sum\n out.println(s)\n \n out.flush\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P285C extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val as0 = Array.fill(N)(sc.nextLong).sorted\n val as = new Array[Long](N + 1)\n as0.copyToArray(as, 1)\n\n val answer: Long = {\n @tailrec\n def loop(acc: Long, i: Int): Long =\n if (i > N) acc\n else loop(acc + math.abs(as(i) - i), i + 1)\n loop(0, 1)\n }\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject BuildingPermutation {\n\n def dist2(l:List[Long]):Long = {\n val n = l.length\n val ls = l.sorted\n val OneN = 1 to n\n \n ((OneN zip ls).map { x => Math.abs(x._1-x._2) }).sum\n }\n \n def dist(l:List[Long]):Long = {\n val n = l.length\n val ls = l.sorted\n val OneN = 1 to n\n //\n val minl = ls filter (x=>{x<=1})\n //System.err.println(\"minl:\"+ minl)\n val maxl = ls filter (x=>{x>=n})\n //System.err.println(\"maxl:\" + maxl)\n val midl = ls filter (x=>{x>1 && x{!(midl contains x)})\n //System.err.println(\"OneNLeft:\" + OneNLeft.toList)\n val common = OneN filter (x=>(midl contains x))\n //System.err.println(\"common:\" + common)\n val midlLeft = midl diff common\n //System.err.println(\"mildLeft:\" + midlLeft)\n \n val lowerOneNLeft = OneNLeft take (minl.length)\n //System.err.println(\"lowerOneNLeft:\" + lowerOneNLeft.toList)\n \n val upperOneNLeft = OneNLeft takeRight (maxl.length)\n // System.err.println(\"upperOneNLeft:\" + upperOneNLeft.toList)\n \n val midOneNLeft = OneNLeft.slice(minl.length, n-maxl.length)\n //System.err.println(\"midOneNLeft:\" + midOneNLeft.toList)\n \n ((lowerOneNLeft zip minl).map { x => x._1 - x._2 }).sum + \n ((maxl zip upperOneNLeft).map {x=>x._1-x._2}).sum + \n ((midlLeft zip midOneNLeft) map {x=>Math.abs(x._1-x._2)}).sum\n }\n \n def main(arg:Array[String]){\n val n = StdIn.readLine().toInt;\n val il:List[Long] = (StdIn.readLine().split(\" \").map { x => x.toLong }).toList\n println(dist2(il))\n }\n}"}, {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n val n = readInt\n def ans = readInts.sorted.zip(1 to n).map(_.productIterator.map(_.asInstanceOf[Int]).reduceLeft(_-_).abs.toLong).sum\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.math._\nobject C\n{\n def main(args: Array[String])\n {\n val n = readLine.toInt\n val a = readLine split(\" \") map(_ toInt) sortWith(_ < _)\n @tailrec\n def solve(pos : Int = 0, ans : Long = 0): Long = {\n if(pos if (i < 1) {\n counts(0) += 1\n changes += -i + 1\n } else if (i > n) {\n counts(n - 1) += 1\n changes += i - n\n } else {\n counts(i - 1) += 1\n }\n }\n var leftZero = 0\n while (leftZero != n && counts(leftZero) != 0)\n leftZero += 1\n var leftMoreOne = 0\n while (leftMoreOne != n && counts(leftMoreOne) < 2)\n leftMoreOne += 1\n\n while (leftZero < n && leftMoreOne < n) {\n\n changes += Math.abs(leftZero - leftMoreOne)\n counts(leftZero) = 1\n while (leftZero != n && counts(leftZero) != 0)\n leftZero += 1\n counts(leftMoreOne) -= 1\n while (leftMoreOne != n && counts(leftMoreOne) != 0)\n leftMoreOne += 1\n }\n\n println(changes)\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n var changes = 0\n var counts = Array.ofDim[Int](n)\n data.foreach{i => if (i < 1) {\n counts(0) += 1\n changes += -i + 1\n } else if (i > n) {\n counts(n - 1) += 1\n changes += i - n\n } else {\n counts(i - 1) += 1\n }\n }\n var leftZero = 0\n while (leftZero != n && counts(leftZero) != 0)\n leftZero += 1\n var leftMoreOne = 0\n while (leftMoreOne != n && counts(leftMoreOne) < 2)\n leftMoreOne += 1\n\n while (leftZero < n && leftMoreOne < n) {\n\n changes += Math.abs(leftZero - leftMoreOne)\n counts(leftZero) = 1\n while (leftZero != n && counts(leftZero) != 0)\n leftZero += 1\n counts(leftMoreOne) -= 1\n while (leftMoreOne != n && counts(leftMoreOne) < 2)\n leftMoreOne += 1\n }\n\n println(changes)\n}"}, {"source_code": "object CF285C extends App {\n val in = new java.util.Scanner(System.in)\n val out = new java.io.PrintWriter(System.out)\n \n val n = in.nextInt\n val v = for (i <- 1 to n) yield in.nextInt\n val s = v.sorted.zip(1 to n).map(x => scala.math.abs(x._1 - x._2)).sum\n out.println(s)\n \n out.flush\n}"}, {"source_code": "import scala.io.StdIn\n\nobject BuildingPermutation {\n\n def dist(l:List[Long]):Long = {\n val n = l.length\n val ls = l.sorted\n val OneN = 1 to n\n //\n val minl = ls filter (x=>{x<=1})\n //System.err.println(\"minl:\"+ minl)\n val maxl = ls filter (x=>{x>=n})\n //System.err.println(\"maxl:\" + maxl)\n val midl = ls filter (x=>{x>1 && x{!(midl contains x)})\n //System.err.println(\"OneNLeft:\" + OneNLeft.toList)\n val lowerOneNLeft = OneNLeft take (minl.length)\n //System.err.println(\"lowerOneNLeft:\" + lowerOneNLeft.toList)\n val upperOneNLeft = OneNLeft takeRight (maxl.length)\n //System.err.println(\"upperOneNLeft:\" + upperOneNLeft.toList)\n \n \n ((lowerOneNLeft zip minl).map { x => x._1 - x._2 }).sum + \n ((maxl zip upperOneNLeft).map {x=>x._1-x._2}).sum\n }\n \n def main(arg:Array[String]){\n val n = StdIn.readLine().toInt;\n val il:List[Long] = (StdIn.readLine().split(\" \").map { x => x.toLong }).toList\n println(dist(il))\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject BuildingPermutation {\n\n def dist(l:List[Int]):Int = {\n val n = l.length\n val ls = l.sorted\n val OneN = 1 to n\n //\n val minl = ls filter (x=>{x<=1})\n System.err.println(\"minl:\"+ minl)\n val maxl = ls filter (x=>{x>=n})\n System.err.println(\"maxl:\" + maxl)\n val midl = ls filter (x=>{x>1 && x{!(midl contains x)})\n System.err.println(\"OneNLeft:\" + OneNLeft.toList)\n val lowerOneNLeft = OneNLeft take (minl.length)\n System.err.println(\"lowerOneNLeft:\" + lowerOneNLeft.toList)\n val upperOneNLeft = OneNLeft takeRight (maxl.length)\n System.err.println(\"upperOneNLeft:\" + upperOneNLeft.toList)\n \n \n ((lowerOneNLeft zip minl).map { x => x._1 - x._2 }).sum + \n ((maxl zip upperOneNLeft).map {x=>x._1-x._2}).sum\n }\n \n def main(arg:Array[String]){\n val n = StdIn.readLine().toInt;\n val il:List[Int] = (StdIn.readLine().split(\" \").map { x => x.toInt }).toList\n println(dist(il))\n }\n}"}, {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n val n = readInt\n def ans = readInts.sorted.zip(1 to n).map(_.productIterator.map(_.asInstanceOf[Int]).reduceLeft(_-_).abs).sum\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.math._\nobject C\n{\n def main(args: Array[String])\n {\n val n = readLine.toInt\n val a = readLine split(\" \") map(_ toInt) sortWith(_ < _)\n @tailrec\n def solve(pos : Int = 0, ans : Int = 0): Int = {\n if(pos\n if (e < 1) a + 1 - e\n else if (e > n) a + e - n\n else a\n }\n val a1 = a.map{ e => \n if (e < 1) 1\n else if (e > n) n\n else e\n }\n val step2 = (a1.sum - n * (n + 1) / 2).abs\n println(step1 + step2)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt\n val a = readLine().split(\" \").map(_.toInt)\n val step1 = a.foldLeft(0) { (a, e) =>\n if (e < 1) a + 1 - e\n else if (e > n) a + e - n\n else a\n }\n val a1 = a.map{ e => \n if (e < 1) 1\n else if (e > n) n\n else e\n }\n val step2 = (a1.sum - n * (n + 1) / 2).abs\n println(step1 + step2)\n }\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.math._\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val N = readInt()\n val list = readLine split (\" \") map (_ toInt) sortWith (_ < _)\n val dList = 1.to(N).map(i => (list(i - 1) - i).abs);\n print(dList.sum)\n }\n}"}], "src_uid": "86d5da999415fa75b3ee754a2a28605c"} {"source_code": "//package bScalaAdvanced.exercises.codeForces.edu98\n\nimport scala.io.StdIn._\n\nobject taskC extends App {\n val sets = readInt()\n\n val res = new Array[Int](sets)\n\n (0 until sets).foreach(y => {\n\n val splitted = readLine().split(\"\")\n var a = 0\n var b = 0\n res(y) = 0\n splitted.foreach(x => {\n if (x == \"(\")\n a += 1\n else if(x == \")\" && a > 0) {\n a-= 1\n res(y) +=1\n }else if(x == \"[\")\n b +=1\n else if(x == \"]\" && b > 0){\n b -=1\n res(y) +=1\n }\n })\n })\n\n\n (0 until sets).foreach(x => {\n println(res(x))\n })\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n val t = readInt()\n // val t = 2\n (0 until t).foreach(_ => {\n val s = readLine()\n // val s = \"[(])\"\n val ans = run(s, '[', ']') + run(s, '(', ')')\n println(ans)\n })\n \n def run(s: String, a: Char, b: Char): Int = {\n var ans = 0\n var left = 0\n for (c <- s) {\n if (c == a) {\n left += 1\n } else if (c == b && left > 0) {\n ans += 1\n left -= 1\n }\n }\n ans\n }\n}\n"}], "negative_code": [{"source_code": "//package bScalaAdvanced.exercises.codeForces.edu98\n\nimport scala.io.StdIn._\n\nobject taskC extends App{\n val sets = readInt()\n\n val res = new Array[Int](sets)\n\n (0 until sets).foreach(a => {\n // println(\" \" + a)\n var splitted = readLine().split(\"\")\n\n while (splitted.contains(\"[\") && splitted.contains(\"]\") ){\n val s = splitted.indexOf(\"[\")\n // println(\"s: \" + s)\n val f = splitted.indexOf(\"]\")\n // println(\"f: \" + f)\n\n //println(splitted)\n\n\n\n // println(splitted)\n // println()\n\n if (s< f) {\n res(a) += 1\n //println(\"+\")\n splitted(s) = \"a\"\n splitted(f) = \"a\"\n }else{\n splitted(f) = \"a\"\n }\n }\n\n\n while(splitted.contains(\"(\") && splitted.contains(\")\")) {\n\n val s = splitted.indexOf(\"(\")\n //println(\"s: \" + s)\n val f = splitted.indexOf(\")\")\n //println(\"f: \" + f)\n\n splitted(s) = \"a\"\n splitted(f) = \"a\"\n\n\n //println(splitted)\n // println()\n if (s< f) {\n res(a) += 1\n //println(\"+\")\n splitted(s) = \"a\"\n splitted(f) = \"a\"\n }else{\n splitted(f) = \"a\"\n }\n\n }\n\n /*val splitted = readLine().split(\"\")\n val oc = splitted.count(x => x == \"[\")\n val cc = splitted.count(x => x == \"]\")\n val ob = splitted.count(x => x == \"(\")\n val cb = splitted.count(x => x == \")\")\n\n var totalc = 0\n var totalb = 0\n\n var minc = 0\n var minb = 0\n (0 until splitted.length).foreach(x => {\n if(splitted(x) == \"]\") totalc-=1\n if(splitted(x) == \"[\") totalc+=1\n\n if(splitted(x) == \")\") totalb-=1\n if(splitted(x) == \"(\") totalb+=1\n\n minc = min(totalc, minc)\n minb = min(totalb, minb)\n })\n\n\n val resi = min(oc, cc)+minc + min(ob, cb)+minb\n if (resi < 0) res(a) = 0\n else res(a) = resi*/\n\n\n })\n\n\n (0 until sets).foreach(x => {\n println(res(x))\n\n })\n}\n"}, {"source_code": "//package bScalaAdvanced.exercises.codeForces.edu98\n\nimport scala.io.StdIn._\nimport scala.math.min\n\nobject taskC extends App{\n val sets = readInt()\n\n val res = new Array[Int](sets)\n\n (0 until sets).foreach(a => {\n val splitted = readLine().split(\"\")\n val oc = splitted.count(x => x == \"[\")\n val cc = splitted.count(x => x == \"]\")\n val ob = splitted.count(x => x == \"(\")\n val cb = splitted.count(x => x == \")\")\n\n var totalc = 0\n var totalb = 0\n\n var minc = 0\n var minb = 0\n (0 until splitted.length).foreach(x => {\n if(splitted(x) == \"]\") totalc-=1\n if(splitted(x) == \"[\") totalc+=1\n\n if(splitted(x) == \")\") totalb-=1\n if(splitted(x) == \"(\") totalb+=1\n\n minc = min(totalc, minc)\n minb = min(totalb, minb)\n })\n\n\n val resi = min(oc, cc)+minc + min(ob, cb)+minb\n if (resi < 0) res(a) = 0\n else res(a) = resi\n\n\n })\n\n\n (0 until sets).foreach(x => {\n println(res(x))\n\n })\n}\n"}, {"source_code": "//package bScalaAdvanced.exercises.codeForces.edu98\n\nimport scala.io.StdIn._\n\nobject taskC extends App {\n val sets = readInt()\n\n val res = new Array[Int](sets)\n\n (0 until sets).foreach(y => {\n\n val splitted = readLine().split(\"\")\n var a = 0\n var b = 0\n res(y) = 0\n splitted.foreach(x => {\n if (x == \"(\")\n a += 1\n else if(x == \")\" && a > 0) {\n a-= 1\n res(y) +=1\n }else if(x == \"[\")\n b +=1\n else if(b > 0){\n b -=1\n res(y) +=1\n }\n })\n })\n\n\n (0 until sets).foreach(x => {\n println(res(x))\n })\n}\n"}, {"source_code": "//package bScalaAdvanced.exercises.codeForces.edu98\n\nimport scala.io.StdIn._\nimport scala.math.min\n\nobject taskC extends App{\n val sets = readInt()\n\n val res = new Array[Int](sets)\n\n (0 until sets).foreach(a => {\n var splitted = readLine().split(\"\").toList\n\n while (splitted.contains(\"[\") && splitted.contains(\"]\") ){\n val s = splitted.indexOf(\"[\")\n val f = splitted.indexOf(\"]\")\n\n splitted = splitted.drop(s)\n splitted = splitted.drop(f)\n\n if (s< f) {\n res(a) += 1\n }\n }\n\n\n while(splitted.contains(\"(\") && splitted.contains(\")\")) {\n\n val s = splitted.indexOf(\"(\")\n val f = splitted.indexOf(\")\")\n\n splitted = splitted.drop(s)\n splitted = splitted.drop(f)\n\n if (s< f) {\n res(a) += 1\n }\n\n }\n\n /*val splitted = readLine().split(\"\")\n val oc = splitted.count(x => x == \"[\")\n val cc = splitted.count(x => x == \"]\")\n val ob = splitted.count(x => x == \"(\")\n val cb = splitted.count(x => x == \")\")\n\n var totalc = 0\n var totalb = 0\n\n var minc = 0\n var minb = 0\n (0 until splitted.length).foreach(x => {\n if(splitted(x) == \"]\") totalc-=1\n if(splitted(x) == \"[\") totalc+=1\n\n if(splitted(x) == \")\") totalb-=1\n if(splitted(x) == \"(\") totalb+=1\n\n minc = min(totalc, minc)\n minb = min(totalb, minb)\n })\n\n\n val resi = min(oc, cc)+minc + min(ob, cb)+minb\n if (resi < 0) res(a) = 0\n else res(a) = resi*/\n\n\n })\n\n\n (0 until sets).foreach(x => {\n println(res(x))\n\n })\n}\n"}, {"source_code": "//package bScalaAdvanced.exercises.codeForces.edu98\n\nimport scala.io.StdIn._\n\nobject taskC extends App{\n val sets = readInt()\n\n val res = new Array[Int](sets)\n\n (0 until sets).foreach(a => {\n // println(\" \" + a)\n var splitted = readLine().split(\"\")\n\n while (splitted.contains(\"[\") && splitted.contains(\"]\") ){\n val s = splitted.indexOf(\"[\")\n // println(\"s: \" + s)\n val f = splitted.indexOf(\"]\")\n // println(\"f: \" + f)\n\n //println(splitted)\n splitted(s) = \"a\"\n splitted(f) = \"a\"\n\n\n // println(splitted)\n // println()\n\n if (s< f) {\n res(a) += 1\n //println(\"+\")\n }\n }\n\n\n while(splitted.contains(\"(\") && splitted.contains(\")\")) {\n\n val s = splitted.indexOf(\"(\")\n //println(\"s: \" + s)\n val f = splitted.indexOf(\")\")\n //println(\"f: \" + f)\n\n splitted(s) = \"a\"\n splitted(f) = \"a\"\n\n\n //println(splitted)\n // println()\n if (s< f) {\n res(a) += 1\n // println(\"+\")\n }\n\n }\n\n /*val splitted = readLine().split(\"\")\n val oc = splitted.count(x => x == \"[\")\n val cc = splitted.count(x => x == \"]\")\n val ob = splitted.count(x => x == \"(\")\n val cb = splitted.count(x => x == \")\")\n\n var totalc = 0\n var totalb = 0\n\n var minc = 0\n var minb = 0\n (0 until splitted.length).foreach(x => {\n if(splitted(x) == \"]\") totalc-=1\n if(splitted(x) == \"[\") totalc+=1\n\n if(splitted(x) == \")\") totalb-=1\n if(splitted(x) == \"(\") totalb+=1\n\n minc = min(totalc, minc)\n minb = min(totalb, minb)\n })\n\n\n val resi = min(oc, cc)+minc + min(ob, cb)+minb\n if (resi < 0) res(a) = 0\n else res(a) = resi*/\n\n\n })\n\n\n (0 until sets).foreach(x => {\n println(res(x))\n\n })\n}\n"}], "src_uid": "db9cec57d8ed5e914818ce9b439eb0f9"} {"source_code": "object a992 {\n def main(args: Array[String]): Unit = {\n scala.io.StdIn.readLine()\n println(scala.io.StdIn.readLine().split(\" \").filter(_!=\"0\").distinct.length)\n }\n}\n", "positive_code": [{"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n\n println(as.filter(_ != 0).distinct.size)\n}\n"}, {"source_code": "import scala.collection.mutable._\nimport scala.io.StdIn\n\nobject Solution {\n def main(args: Array[String]) {\n val n = io.StdIn.readLine.trim.toInt\n val a = io.StdIn.readLine.split(\" \").map(_.trim.toInt)\n\n val set = a.toSet\n if (set.contains(0)) println(set.size - 1)\n else println(set.size)\n }\n }\n\n"}, {"source_code": "object _992A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val nums = io.read[Seq[Int]]\n val ans = nums.filter(_ != 0).distinct.size\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n StdIn.readLine()\n val a = StdIn.readLine().split(\" \").map(item => item.toInt)\n println(a.distinct.count(item => item != 0))\n }\n}\n"}, {"source_code": "object Main extends App {\n readInt\n val array = readLine.split(\" \").map(_.toInt)\n println(array.distinct.length - (if (array.contains(0)) 1 else 0))\n}\n"}], "negative_code": [], "src_uid": "0593f79604377dcfa98d2b69840ec0a6"} {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n case class Song(t: Long, b: Long)\n\n val Array(n, k) = readInts(2)\n val songs = Array.fill(n) {\n val Array(t, b) = readLongs(2)\n Song(t, b)\n }.sortBy(-_.b)\n\n var max = 0L\n val pq = new mutable.PriorityQueue[Song]()(Ordering.by(-_.t))\n var len = 0L\n\n for (song <- songs) {\n pq += song\n len += song.t\n if (pq.size > k) {\n val r = pq.dequeue()\n len -= r.t\n }\n val score = song.b * len\n if (score > max) max = score\n }\n\n println(max)\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n import java.util.Arrays\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n import java.util.Comparator\n val N, K = ni()\n case class Song(t: Int, b: Int) extends Comparable[Song] {\n override def compareTo(o: Song): Int = Integer.compare(t, o.t) // PriorityQueueでtが低い順に抜けていって欲しい\n }\n\n val S = Array.ofDim[Song](N)\n REP(N) { i =>\n val t, b = ni()\n S(i) = Song(t, b)\n }\n\n // bの降順で並べる\n Arrays.sort(S, new Comparator[Song] {\n override def compare(o1: Song, o2: Song): Int = Integer.compare(o2.b, o1.b)\n })\n\n debug(S.mkString(\",\"))\n\n val q = new java.util.PriorityQueue[Song]\n var ans = 0L\n var s = 0L\n REP(N) { i =>\n if (i < K) {\n s += S(i).t\n q.add(S(i))\n ans = max(ans, s * S(i).b) // 数がK以下のときはbが大きい順に選ぶだけ。そうでないと数を増やした方が得になる\n } else {\n q.add(S(i))\n s += S(i).t\n s -= q.poll().t\n ans = max(ans, s * S(i).b)\n }\n }\n out.println(ans)\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n case class Song(t: Long, b: Long)\n\n val Array(n, k) = readInts(2)\n val songs = Array.fill(n) {\n val Array(t, b) = readLongs(2)\n Song(t, b)\n }.sortBy(-_.b)\n\n var max = 0L\n val pq = new mutable.PriorityQueue[Song]()(Ordering.by(-_.b))\n var len = 0L\n\n for (song <- songs) {\n pq += song\n len += song.t\n if (pq.size > k) {\n val r = pq.dequeue()\n len -= r.t\n }\n val score = song.b * len\n if (score > max) max = score\n }\n\n println(max)\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n case class Song(t: Long, b: Long)\n\n val Array(n, k) = readInts(2)\n val songs = Array.fill(n) {\n val Array(t, b) = readLongs(2)\n Song(t, b)\n }.sortBy(-_.b)\n\n var max = 0L\n val pq = new mutable.PriorityQueue[Song]()(Ordering.by(_.b))\n var len = 0L\n\n for (song <- songs) {\n pq += song\n len += song.t\n if (pq.size > k) {\n val r = pq.dequeue()\n len -= r.t\n }\n val score = song.b * len\n if (score > max) max = score\n }\n\n println(max)\n}\n"}], "src_uid": "6b85a1fefb03566fbc557b98d1dfd7ef"} {"source_code": "//package codeforces.contests._1353\n\n\nobject ConstructingTheArray {\n\n import math.abs\n import scala.collection.mutable\n\n def main(args: Array[String]): Unit = {\n println {\n {\n for (_ <- 1 to io.StdIn.readInt) yield {\n val n = io.StdIn.readInt\n\n val arr = new Array[Int](n)\n\n implicit val tuple2Ordering: Ordering[(Int, Int)] = Ordering.fromLessThan[(Int, Int)] {\n case ((x, y), (l, r)) =>\n if (abs(x - y) == abs(l - r)) x > l else abs(x - y) < abs(l - r)\n }\n\n val queue = mutable.PriorityQueue[(Int, Int)](1 -> n)\n\n @scala.annotation.tailrec\n def loop(i: Int): Unit =\n if (i <= n) {\n val (l, r) = queue.dequeue()\n val m = (l + r) / 2\n\n arr(m - 1) = i\n\n if (l != m)\n queue.enqueue(l -> (m - 1))\n if (l != r)\n queue.enqueue((m + 1) -> r)\n\n loop(i + 1)\n }\n\n loop(1)\n\n arr.mkString(\" \")\n }\n }.mkString(\"\\n\")\n }\n\n }\n}\n", "positive_code": [{"source_code": "object ProblemDD extends App {\n import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n case class SmartPair(left: Int, right: Int) {\n val size: Int = right - left\n }\n\n implicit val ordering: Ordering[SmartPair] = new Ordering[SmartPair]() {\n override def compare(x: SmartPair, y: SmartPair): Int = if (x.size != y.size) {\n y.size - x.size\n } else {\n x.left - y.left\n }\n }\n\n\n val t = in.nextInt()\n\n for (_ <- 1 to t) {\n val n = in.nextInt()\n\n val result = new Array[Int](n)\n\n val pairs = scala.collection.mutable.SortedSet[SmartPair]()\n pairs += SmartPair(1, n)\n var step = 1\n while (pairs.nonEmpty) {\n val xy = pairs.head\n val x = xy.left\n val y = xy.right\n pairs.remove(xy)\n\n if (x <= y) {\n if ((y - x + 1) % 2 == 1) {\n val mid = (y + x) / 2\n result(mid - 1) = step\n if (y != x) {\n pairs += SmartPair(x, mid - 1)\n pairs += SmartPair(mid + 1, y)\n }\n } else {\n val mid = (y + x - 1) / 2\n result(mid - 1) = step\n pairs += SmartPair(mid + 1, y)\n pairs += SmartPair(x, mid - 1)\n }\n step = step + 1\n }\n\n\n\n }\n\n println(result.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "object D extends App {\n import InOut._\n import scala.collection.mutable.TreeSet\n\n object SegOrdering extends Ordering[(Int, Int)] {\n implicit def compare(x: (Int, Int), y: (Int, Int)): Int = {\n val (l1, r1) = x\n val (l2, r2) = y\n val (len1, len2) = (r1 - l1 + 1, r2 - l2 + 1)\n\n if (len1 > len2) -1\n else if (len1 < len2) 1\n else if (l1 < l2) -1\n else if (l1 > l2) 1\n else 0\n }\n }\n\n val t = nextInt\n\n (0 until t).foreach { _ =>\n val n = nextInt\n\n var an = Array.ofDim[Int](n)\n var segs = TreeSet[(Int, Int)]((0, n - 1))(SegOrdering)\n\n (1 to n).foreach { v =>\n val (l, r) = segs.head\n\n val i = (l + r) / 2\n\n segs -= ((l, r))\n if (i > l) segs += ((l, i - 1))\n if (i < r) segs += ((i + 1, r))\n\n an(i) = v\n }\n\n out.println(an.mkString(\" \"))\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n)(nextInt)\n def nextLongs(n: Int) = Array.fill(n)(nextLong)\n def nextBigs(n: Int) = Array.fill(n)(nextBig)\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn.readLine\n\nobject D {\n\n def solution(n: Int): Array[Int] = {\n val result = Array.ofDim[Int](n)\n val subsByLength =\n mutable.SortedMap((n - 1) -> mutable.SortedSet(0))\n\n def add(length: Int, start: Int): Unit =\n subsByLength\n .getOrElseUpdate(length - 1, mutable.SortedSet.empty[Int])\n .add(start)\n\n var iteration = 1\n while (subsByLength.nonEmpty) {\n val length = subsByLength.lastKey + 1\n subsByLength.remove(length - 1).foreach { subs =>\n subs.foreach { start =>\n length match {\n case 1 =>\n result(start) = iteration\n case 2 =>\n result(start) = iteration\n add(1, start + 1)\n case _ =>\n val halfLength = length / 2\n if (length % 2 == 0) {\n add(halfLength - 1, start)\n result(start + halfLength - 1) = iteration\n add(halfLength, start + halfLength)\n } else {\n add(halfLength, start)\n result(start + halfLength) = iteration\n add(halfLength, start + halfLength + 1)\n }\n }\n iteration += 1\n }\n }\n }\n result\n }\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val n = readLine.toInt\n println(solution(n).mkString(\" \"))\n }\n }\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn.readLine\n\nobject D {\n\n def solution(n: Int): Seq[Int] = {\n val a = Array.fill(n)(0)\n val m = mutable.Map(n -> mutable.Set(0))\n for(i <- 0 until n)\n m(i) = mutable.Set.empty[Int]\n var (len, i) = (n, 1)\n while (len > 0) {\n m.remove(len).foreach { s =>\n s.toSeq.sorted.foreach { start =>\n val l2 = len / 2\n if (len % 2 == 0) {\n m(l2 - 1).add(start)\n a(start + l2 - 1) = i\n m(l2).add(start + l2)\n } else {\n m(l2).add(start)\n a(start + l2) = i\n m(l2).add(start + l2 + 1)\n }\n i += 1\n }\n }\n len -= 1\n }\n a.toSeq\n }\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val n = readLine.toInt\n println(solution(n))\n }\n }\n}"}], "src_uid": "25fbe21a449c1ab3eb4bdd95a171d093"} {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._\nimport scala.math.Ordering.Implicits._\n\nimport CodeForcesApp._\n\nobject _591A extends CodeForcesApp {\n override type Result = Double\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val (l, p, q) = (nextInt(), nextInt(), nextInt())\n p*l.toDouble/(p + q)\n }\n\n override def format(result: Result) = super.format(result)\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n/********************************[Scala Scanner]*********************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines: Iterator[String] = Iterator.continually(reader.readLine()).takeWhile(_ != null)\n\n def tokens: Iterator[String] = for {\n line <- lines\n tokenizer = new StringTokenizer(line)\n _ <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)\n } yield tokenizer.nextToken()\n\n private[this] var current = tokens\n override def hasNext = current.hasNext\n @inline override def next() = current.next()\n\n /**\n * @return Unlike the Java scanner which returns till end of current line, this actually returns the next line\n */\n def nextLine(): String = {\n current = tokens // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def nextString(): String = next()\n def nextChar(): Char = next().head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def close() = reader.close()\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n def solve: Int = {\n val l = nextInt\n val p = nextInt\n val q = nextInt\n val t = (1.0d * l) / (1.0d * p + q * 1.0d)\n val first = 1.0d * t * p\n println(first)\n return 0\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val L = readLine().toInt\n val p = readLine().toInt\n val q = readLine().toInt\n\n val t = L * 1.0 / (p + q)\n val answer = p * t\n println(\"%.4f\".format(answer))\n}\n"}, {"source_code": "\n\n\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject A {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val l = br.readLine().toInt\n val p = br.readLine().toInt\n val q = br.readLine().toInt\n //---------------------------- parameters reading end --------------------------------\n \n val sumSpeed = p + q\n val firstColT = l/sumSpeed.toDouble\n val distP1 = firstColT * p\n val secondColT = (l*2) / sumSpeed.toDouble\n val distP2 = (p*secondColT - distP1)\n \n println(distP2)\n }\n \n//========================= samples ======================== \nval sa1 = \"\"\"\n\n\"\"\"\n\n//========================= samples end ==================== \n}"}, {"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\nobject Codeforces591A extends App {\n def Harry(l: Double, p: Int, q: Int): Double = {\n val time = l / (p + q)\n p * time\n }\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val l = in.nextInt\n val p = in.nextInt\n val q = in.nextInt\n\n print(Harry(l, p, q))\n}\n"}, {"source_code": "import scala.io.StdIn._\nobject program {\n\tdef main(args: Array[String]) {\n\t\tvar l = readInt(); var a = readInt(); var b = readInt()\n\t\tprintln((l.toDouble/ (a + b)) * a);\n\t}\n}\n"}, {"source_code": "import java.nio.channels.Pipe.SourceChannel\n\nimport scala.math._\nimport scala.io._\n\nobject A5 {\n def solution(d : Int, s1 : Int, s2 : Int) : Double = {\n val (ds1,ds2, maxs) = (s1.toDouble, s2.toDouble, max(s1,s2).toDouble)\n val b = Iterator.iterate((0.0,0.0))(a =>(a._1 + ds1/maxs/10000, a._2+ds2/maxs/10000)).dropWhile(a=>a._1 +a._2 < d).take(1).toArray\n b(0)._1\n }\n def main(args: Array[String]): Unit = {\n val xs = Source.stdin.getLines().take(3).map(_.toInt).toArray\n //assert(abs(solution(100,50,50)-50) < 1e-4)\n //assert(abs(solution(199,60,40)-119.4)<1e-4)\n println(solution(xs(0),xs(1), xs(2)))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val l = in.next().toInt\n val p = in.next().toInt\n val q = in.next().toInt\n println(p * l / (p + q).toFloat)\n}"}, {"source_code": "object A591 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(l) = readInts(1)\n val Array(p) = readInts(1)\n val Array(q) = readInts(1)\n\n println((p.toDouble * l)/(p.toDouble + q.toDouble))\n }\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readDoubles(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toDouble) }\n\n val Array(l) = readDoubles(1)\n val Array(p) = readDoubles(1)\n val Array(q) = readDoubles(1)\n \n val t = l / (p + q)\n\n println(p * t)\n}\n"}], "negative_code": [{"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\nobject Codeforces591A extends App {\n def Harry(l: Double, p: Int, q: Int): Double = {\n val time = l / (p + q)\n p * time\n }\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val l = in.nextInt\n val p = in.nextInt\n val q = in.nextInt\n\n out.write(Harry(l, p, q).toString)\n}\n"}], "src_uid": "6421a81f85a53a0c8c63fbc32750f77f"} {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = s\"${readLine()} 0\".split(\" \").map(_.toInt)\r\n\r\n def ai(i: Int): Int = if (i < 0 || i > n - 1) 0 else an(i)\r\n\r\n val ans = (0 to n)\r\n .foldLeft((0L, 0)) {\r\n case ((s, _), i) if an(i) > ai(i - 1) && an(i) > ai(i + 1) =>\r\n val h = ai(i - 1) max ai(i + 1)\r\n val l = h - ai(i - 1)\r\n (s + an(i) - h + l, h)\r\n case ((s, aj), i) =>\r\n val ai = an(i)\r\n (s + Math.abs(ai - aj), ai)\r\n }\r\n ._1\r\n\r\n println(ans)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n def ai(i: Int): Int = if (i < 0 || i > n - 1) 0 else an(i)\r\n\r\n val ans = (0 to n)\r\n .foldLeft((0L, 0)) {\r\n case ((s, _), i) if ai(i) > ai(i - 1) && ai(i) > ai(i + 1) =>\r\n val h = ai(i - 1) max ai(i + 1)\r\n val l = h - ai(i - 1)\r\n (s + ai(i) - h + l, h)\r\n case ((s, aj), i) =>\r\n (s + Math.abs(ai(i) - aj), ai(i))\r\n }\r\n ._1\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n def ai(i: Int): Int = if (i < 0 || i > n - 1) 0 else an(i)\r\n\r\n val ans = {\r\n val (a, b) = (0 until n).foldLeft((0L, 0)) {\r\n case ((s, _), i) if an(i) > ai(i - 1) && an(i) > ai(i + 1) =>\r\n val h = ai(i - 1) max ai(i + 1)\r\n val l = h - ai(i - 1)\r\n (s + an(i) - h + l, h)\r\n case ((s, aj), i) =>\r\n val ai = an(i)\r\n (s + Math.abs(ai - aj), ai)\r\n }\r\n\r\n a + b\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = s\"${readLine()} 0\".split(\" \").map(_.toInt)\r\n\r\n def ai(i: Int): Int = if (i < 0 || i > n - 1) 0 else an(i)\r\n\r\n val ans = (0 until n)\r\n .foldLeft((0L, 0)) {\r\n case ((s, _), i) if an(i) > ai(i - 1) && an(i) > ai(i + 1) =>\r\n val h = ai(i - 1) max ai(i + 1)\r\n val l = h - ai(i - 1)\r\n (s + an(i) - h + l, h)\r\n case ((s, aj), i) =>\r\n val ai = an(i)\r\n (s + Math.abs(ai - aj), ai)\r\n }\r\n ._1\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n def ai(i: Int): Int = if (i < 0 || i > n - 1) 0 else an(i)\r\n\r\n val ans = {\r\n val (a, b) = (0 until n).foldLeft((0, 0)) {\r\n case ((s, _), i) if an(i) > ai(i - 1) && an(i) > ai(i + 1) =>\r\n val h = ai(i - 1) max ai(i + 1)\r\n val l = h - ai(i - 1)\r\n (s + an(i) - h + l, h)\r\n case ((s, aj), i) =>\r\n val ai = an(i)\r\n (s + Math.abs(ai - aj), ai)\r\n }\r\n\r\n a + b\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = s\"${readLine()} 0\".split(\" \").map(_.toInt)\r\n\r\n def f(i: Int): Long =\r\n an.foldLeft((0L, 0)) { case ((acc, prev), curr) =>\r\n (acc + Math.abs(curr.min(i) - prev.min(i)) + 0.max(curr - i), curr)\r\n }._1\r\n\r\n @annotation.tailrec\r\n def go(i: Int, result: Long): Long =\r\n if (i < 0) result\r\n else go(i - 1, result min f(i))\r\n\r\n val ans = go(an.max - 1, f(an.max))\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = s\"${readLine()} 0\".split(\" \").map(_.toInt)\r\n\r\n def f(i: Int): Long =\r\n an.foldLeft((0L, 0)) { case ((acc, prev), curr) =>\r\n val diff = curr.min(i) - prev.min(i)\r\n (acc + diff * diff.signum + (curr - i).max(0), curr)\r\n }._1\r\n\r\n def go(i: Int, result: Long): Long =\r\n if (i < 0) result\r\n else {\r\n val t = f(i)\r\n if (t > result) result\r\n else go(i - 1, t)\r\n }\r\n\r\n val ans = go(an.max - 1, f(an.max))\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "src_uid": "6313b2788fbf58b9b7c70fc85afa4c1c"} {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n type Point = Array[Int]\n class PointWrapper(p: Point) {\n def ×(o: Point) = (p zip o).map(x => x._1 * x._2).sum\n def -(o: Point) = (p zip o).map(x => x._1 - x._2)\n def len = Math.sqrt(×(p))\n }\n implicit def p2pw(p: Point) = new PointWrapper(p)\n val Array(n, k) = readInts\n val points = for(_ <- 1 to n) yield readInts\n val p1 = points.take(1) ++ points\n val p2 = points ++ points.drop(n - 1)\n def ans = (p1 zip p2).map(x => (x._1 - x._2).len).sum * 0.02 * k\n\n def main(a: Array[String]) {\n println(\"%.10f\".formatLocal(Locale.US, ans))\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def readxy(): (Float, Float) = {\n val a = readLine().split(\" \").map(_.toFloat)\n (a(0), a(1))\n }\n \n def main(args: Array[String]) {\n val nk = readLine().split(\" \").map(_.toInt)\n val n = nk(0)\n val k = nk(1)\n \n var prev = readxy()\n var length = 0.0f\n for (_ <- 1 until n) {\n val cur = readxy()\n val v = (cur._1 - prev._1, cur._2 - prev._2)\n length += Math.sqrt(v._1 * v._1 + v._2 * v._2).toFloat\n prev = cur\n }\n println(length * k / 50.0f)\n }\n}"}, {"source_code": "import java.util.Scanner\nobject Zhlob {\n\n class Point(_x:Int, _y:Int){\n def x = _x\n def y = _y\n def len(p:Point):Double = {\n Math.sqrt(0.0+(x - p.x)*(x - p.x) + (y-p.y)*(y-p.y))\n }\n }\n \n val scanner = new Scanner(System.in);\n \n def main(args: Array[String]) {\n val n,k = scanner.nextInt()\n val points = (1 to n) map {i => new Point(scanner.nextInt(), scanner.nextInt())}\n var sum = 0.0\n for (i <- 1 until n){\n sum += points(i).len(points(i-1))\n }\n println(\"%.9f\".format(sum/50*k))\n \n }\n \n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n def dis(x: Int, y: Int, x1: Int, y1: Int) = {\n val dx = x1 - x\n val dy = y1 - y\n Math.sqrt(dx * dx + dy * dy)\n }\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val Array(startX, startY) = in.next().split(' ').map(_.toInt)\n val distance = (2 to n).foldLeft((0d, startX, startY)){\n case ((d, x, y), _) =>\n val Array(nx, ny) = in.next().split(' ').map(_.toInt)\n (d + dis(x, y, nx, ny), nx, ny)\n }._1\n println(distance / 50 * k)\n}\n"}, {"source_code": "import scala.math\nobject Main\n{\n\tdef ro(x1:Int, y1:Int, x2:Int, y2:Int):Double =\n\t{\n\t\treturn math.pow(math.pow(x2-x1, 2) + math.pow(y2-y1, 2), 0.5)\n\t}\n\tdef main(args:Array[String])\n\t{\n\t\tval rd = readLine.split(\" \").map(i => i.toInt)\n\t\tval k = rd(1)\n\t\tval n = rd(0)\n\t\tval crd = (0 until n).map(i => readLine.split(\" \").map(j => j.toInt)).toList;\n\t\tprintln((1 until crd.length).map(i => ro(crd(i - 1)(0), crd(i - 1)(1), crd(i)(0), crd(i)(1))).sum / 50 * k)\n\t}\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P127A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N, K = sc.nextInt\n val a = Array.fill(N, 2)(sc.nextInt)\n\n def solve: Double = {\n @tailrec\n def loop(acc: Double, i: Int): Double =\n if (i == N) acc\n else {\n val x0 = a(i - 1)(0)\n val y0 = a(i - 1)(1)\n val x1 = a(i)(0)\n val y1 = a(i)(1)\n val dx = x0 - x1\n val dy = y0 - y1\n loop(acc + math.sqrt(dx * dx + dy * dy), i + 1)\n }\n loop(0, 1) * K / 50\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 08 Aug 2016\n */\nobject A127 extends App {\n\n def solve() = {\n val Array(n, k): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n var x: Double = 0D\n var y: Double = 0D\n var signCost: Double = 0D\n for (i <- 0 until n) {\n val Array(nextX, nextY): Array[Double] = scala.io.StdIn.readLine().split(\" \").map(_.toDouble)\n if (i != 0) {\n signCost += math.sqrt((x - nextX) * (x - nextX) + (y - nextY) * (y - nextY))\n }\n x = nextX\n y = nextY\n }\n println(\"%.9f\".format(signCost * k / 50))\n }\n\n solve()\n\n}\n"}], "negative_code": [], "src_uid": "db4a25159067abd9e3dd22bc4b773385"} {"source_code": "import scala.collection.mutable.ListBuffer\n\nobject Main extends App {\n import scala.io.StdIn\n\n def readInts: Array[Int] = StdIn.readLine.split(\" \").map(_.toInt)\n\n def readInt: Int = StdIn.readLine.toInt\n\n val n = readInt\n\n val children = Array.fill(n + 1)(ListBuffer[Int]())\n\n for ((p, i1) <- readInts.zipWithIndex; i = i1 + 2)\n children(p) += i\n\n val c = Array(0) ++ readInts\n\n def f(v: Int, color: Int): Int =\n (if (color == c(v)) 0 else 1) + children(v).map(u => f(u, c(v))).sum\n\n println(f(1, 0))\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main extends App {\n val n = StdIn.readInt()\n val g = ints.iterator.zip(Iterator.from(1)).foldLeft(Array.fill(n){ scala.collection.mutable.ArrayBuffer.empty[Int] }){ (g, p) =>\n g(p._1 - 1).append(p._2)\n g(p._2).append(p._1 - 1)\n g\n }\n val cs = ints\n\n print(dfs(g) { (u: Int, vs: Iterable[(Int, Int) => Int]) => (c: Int, s: Int) => {\n val cu = cs(u)\n vs.foldLeft(s + (if (cu != c) 1 else 0)){ (s1, f) => f(cu, s1) }\n }}(0, 0))\n\n def ints = StdIn.readLine().split(' ').map(_.toInt)\n\n def dfs[B](g: IndexedSeq[Iterable[Int]])(f: (Int, Iterable[B]) => B): B = {\n def go(p: Int)(u: Int): B = f(u, g(u).filter(_ != p).map(go(u)))\n go(0)(0)\n }\n}\n\n"}, {"source_code": "import java.util\n\nimport scala.collection.mutable\nimport scala.io.StdIn\n\n\nobject Solution {\n\n //Console.setIn(new FileReader(new java.io.File(\"input\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n\n var caseNo = 1\n\n def doCase() : Unit = {\n val Array(n) = readIntLine()\n val adjacency = readIntLine().map(_ - 1)\n\n val adj = Array.fill(n){List() : List[Int]}\n for ((a, i) <- adjacency.zipWithIndex) {\n adj(i + 1) ::= a\n adj(a) ::= i + 1\n }\n\n val colors = readIntLine()\n println(color(List((0, 0)), colors, adj, Array.fill(n){false}, 0))\n }\n\n def color(queue: List[(Int, Int)], colors : Array[Int], adj : IndexedSeq[List[Int]], visited : Array[Boolean], cost : Int): Int = {\n queue match {\n case Nil => cost\n case first :: rest =>\n val node = first._1\n var newCost = cost\n visited(node) = true\n if (first._2 != colors(node)) {\n newCost = cost + 1\n }\n if (node < adj.length - 1) {\n val children = adj(node).map(c => (c, colors(node))).filterNot(p => visited(p._1))\n color(children ::: rest, colors, adj, visited, newCost)\n } else {\n color(rest, colors, adj, visited, newCost)\n }\n }\n }\n\n def main(args: Array[String]) {\n var tests = 1\n for (test <- 0 until tests) {\n doCase()\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\n\nobject B extends App {\n def color(g: mutable.HashMap[Int, List[Int]]): Int = {\n @tailrec\n def dfs(h: List[(Int, Int, List[Int])], t: Int = 1): Int = {\n if (h.isEmpty) t\n else {\n val (p, u, adj) = h.head\n if (adj.isEmpty) dfs(h.tail, if (c(p - 1) == c(u - 1)) t else t + 1)\n else {\n val v = adj.head\n if (v == p) dfs((p, u, adj.tail) :: h.tail, t)\n else dfs((u, v, g(v)) :: (p, u, adj.tail) :: h.tail, t)\n }\n }\n }\n\n dfs(List((2, 2, g(2))))\n }\n\n val n = scala.io.StdIn.readInt()\n val p = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val c = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val g = p.foldLeft((new mutable.HashMap[Int, List[Int]], 2)) { (t, u) => {\n t._1(t._2) = u :: t._1.getOrElse(t._2, Nil)\n t._1(u) = t._2 :: t._1.getOrElse(u, Nil)\n (t._1, t._2 + 1)\n }}._1\n\n println(color(g))\n}\n"}, {"source_code": "/**\n * @see http://codeforces.com/contest/902/problem/B\n */\n\nimport scala.annotation.tailrec\n\nobject B extends App {\n def coloring(g: Vector[List[Int]], cs: Array[Int]): Int = {\n @tailrec\n def dfs(h: List[(Int, Int, List[Int])], t: Int): Int =\n if (h.isEmpty) t\n else {\n val (p, u, adj) = h.head\n if (adj.isEmpty) dfs(h.tail, if (cs(p) == cs(u)) t else t + 1)\n else {\n val v = adj.head\n if (v == p) dfs((p, u, adj.tail) :: h.tail, t)\n else dfs((u, v, g(v)) :: (p, u, adj.tail) :: h.tail, t)\n }\n }\n\n dfs(List((0, 0, g(0))), 1)\n }\n\n val n = scala.io.StdIn.readInt()\n val ps = scala.io.StdIn.readLine().split(\" \").map(_.toInt - 1)\n val cs = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val g = ps.indices.foldLeft(Vector.fill(n)(List.empty[Int])) ((g, i) => {\n val u = i + 1\n val v = ps(i)\n g.updated(u, v :: g(u)).updated(v, u :: g(v))\n })\n\n val t = coloring(g, cs)\n println(t)\n}\n"}, {"source_code": "object _902B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val n = io.read[Int]\n\n val edges = io.read[Seq, Int](n-1)\n .zipWithIndex\n .map({case (i, j) => i -> (j+2)})\n .flatMap({edge => Set(edge, edge.swap)})\n .toMultiMap\n .withDefaultValue(Vector.empty)\n\n val expectedColor = io.read[Vector, Int](n)\n\n val visited = mutable.Set.empty[Int]\n\n def solve(u: Int, color: Int): Int = {\n visited += u\n (if (color == expectedColor(u-1)) 0 else 1) + edges(u).filterNot(visited).sumWith(v => solve(v, expectedColor(u-1)))\n }\n\n val ans = solve(1, 0)\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b.apply().result())\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "b23696f763d90335e8bfb0a5e2094c03"} {"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val names = Array.fill(n) { (readLine + '{').toCharArray }\n val precBuilders = Array.fill('{'.toInt + 1) { new mutable.ArrayBuilder.ofChar }\n\n var err = false\n\n for {\n i <- 0 until n\n n1 = names(i)\n j <- i + 1 until n\n n2 = names(j)\n } {\n var equal = true\n var p = 0\n val l = n1.length min n2.length\n while (equal & p < l) {\n if (n2(p) == '{') err = true\n if (n1(p) != n2(p)) {\n precBuilders(n2(p)) += n1(p)\n equal = false\n }\n p += 1\n }\n }\n\n val preceeding = precBuilders.map(_.result.distinct)\n\n val sorted = mutable.ArrayBuffer.empty[Int]\n\n val color = Array.fill('{'.toInt + 1)(0)\n\n def dfs(u: Int): Unit = {\n color(u) = 1\n for (v <- preceeding(u)) {\n if (color(v) == 0) dfs(v)\n else if (color(v) == 1) err = true\n }\n color(u) = 2\n sorted += u\n }\n\n for (i <- 'a'.toInt to '{'.toInt) if (color(i) == 0) dfs(i)\n\n println(if (err) \"Impossible\" else sorted.map(_.toChar).filter(_ != '{').mkString)\n\n Console.flush\n}\n", "positive_code": [{"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val names = Array.fill(n) { (readLine + '{').toCharArray }\n val adjBuilders = Array.fill('{'.toInt + 1) { new mutable.ArrayBuilder.ofChar }\n val after = Array.fill('{'.toInt + 1, '{'.toInt + 1)(false)\n\n for {\n i <- 0 until n\n n1 = names(i)\n j <- i + 1 until n\n n2 = names(j)\n } {\n var equal = true\n var p = 0\n val l = n1.length min n2.length\n while (equal & p < l) {\n if (n1(p) != n2(p)) {\n adjBuilders(n1(p)) += n2(p)\n after(n1(p))(n2(p)) = true\n equal = false\n }\n p += 1\n }\n }\n\n for (c <- 'a' to 'z') after('{')(c) = true\n \n for (c <- 'a' to '{')\n for (a <- 'a' to '{') for (b <- 'a' to '{') if (after(a)(b) && after(b)(c)) after(a)(c) = true\n\n val adj = adjBuilders.map(_.result.distinct)\n\n val visited = new mutable.BitSet\n val stack = mutable.Stack.empty[Char]\n var err = false\n\n def dfs1(u: Char, root: Boolean = false): Unit = {\n //println(u)\n if (!visited(u)) {\n visited += u\n for (v <- adj(u)) {\n if (after(v)(u)) {\n err = true\n }\n dfs1(v)\n }\n stack.push(u)\n /*} else if (!root) {\n err = true*/ \n }\n }\n\n for (i <- '{'.toInt to 'a'.toInt by -1) if (!visited(i)) dfs1(i.toChar, true)\n\n println(if (err) \"Impossible\" else stack.toArray.filter(_ != '{').mkString)\n\n Console.flush\n}\n"}, {"source_code": "\nimport scala.math._\nimport scala.collection.mutable\nimport scala.util.control.Breaks\n\nobject Problem extends App {\n import Scanner._\n\n val names = Array.fill(readInt)(readString)\n val longest = names.maxBy(s => s.length).length\n val base = ('a' - 1).toChar\n\n case class Node(c: Char) extends Ordered[Node] {\n var before = mutable.Set[Node]()\n var after = mutable.Set[Node]()\n\n def compare(n: Node) = c - n.c\n }\n val nodes = for(i <- 0 to 26) yield Node((i + base).toChar)\n for(i <- 1 to 26) {\n nodes(i).after += nodes(0)\n nodes(0).before += nodes(i)\n }\n def addOrdering(strings: List[String]) {\n val chars = strings.map(s => s(0) - base)\n for(i <- 1 until chars.length; if chars(i-1) != chars(i)) {\n nodes(chars(i-1)).before += nodes(chars(i))\n nodes(chars(i)).after += nodes(chars(i-1))\n }\n val grouped = strings.groupBy(s => s(0)).map(x => x._2.map(s => s.drop(1)))\n for(group <- grouped; if group.size > 1)\n addOrdering(group)\n }\n addOrdering(names.toList.map(s => s.padTo(longest, base)))\n\n //for(node <- nodes)\n // println(s\"${node.c} -> ${node.before},${node.after}\")\n\n\n val unusedNodes = mutable.TreeSet(nodes: _*)\n var str = \"\"\n while(!unusedNodes.isEmpty) unusedNodes.find(n => n.after.isEmpty) match {\n case Some(node) =>\n for(n <- node.before)\n n.after -= node\n unusedNodes -= node\n if(node.c != base)\n str += node.c\n case None =>\n println(\"Impossible\")\n System.exit(0)\n }\n println(str)\n}\n\ncase class Memo[A, B](f: A => B, size: Int = 10) extends (A => B) {\n private val cache = new scala.collection.mutable.HashMap[A, B] {\n override def initialSize = size\n }\n def apply(x: A) = cache getOrElseUpdate (x, f(x))\n}\n\nobject Scanner {\n def readInt() = {\n var acc = 0\n readWith {\n case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n }\n acc\n }\n def readLong() = {\n var acc = 0L\n readWith {\n case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10L) + (c - '0')\n }\n acc\n }\n def readDouble() = {\n var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)\n readWith {\n case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>\n frac = (frac * 10) + (c - '0')\n fracPow *= 10\n case c if c == '.' && !readFrac =>\n readFrac = true\n }\n acc + (frac.toDouble / fracPow)\n }\n def readString() = {\n var string = new StringBuilder\n readWith { case c => string += c }\n string.toString\n }\n def readLine() = Console.in.readLine()\n def readChar() = Console.in.read().toChar\n def readWith(func: PartialFunction[Char, Unit]) {\n val handler = func orElse[Char, Unit] {\n case _ => throw new java.io.IOException(\"unexpected token\")\n }\n\n var c = readChar\n while(c.isWhitespace)\n c = readChar\n\n while(!c.isWhitespace) {\n handler(c)\n\n c = readChar\n }\n }\n}\n\n"}, {"source_code": "import java.util.StringTokenizer\n\nimport scala.collection.mutable.Queue\n\nobject _510C extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n\n val n = next.toInt\n val m = 26\n val name = (1 to n).map(i => next).toArray\n val g = Array.fill(m, m)(false)\n var impossible = false\n\n def less(a: List[Char], b: List[Char]): Unit = (a, b) match {\n case (a, Nil) => impossible = true\n case (Nil, b) =>\n case (aa :: aTail, bb :: bTail) => if (aa != bb) g(aa - 'a')(bb - 'a') = true else less(aTail, bTail)\n }\n\n for (i <- 0 until n - 1) less(name(i).toList, name(i + 1).toList)\n if (impossible) println(\"Impossible\")\n else {\n val inDegree = Array.fill(m)(0)\n for (i <- 0 until m; j <- 0 until m) if (g(i)(j)) inDegree(j) = inDegree(j) + 1\n val queue = Queue[Int]()\n for (i <- 0 until m) if (inDegree(i) == 0) queue.enqueue(i)\n\n val builder = new StringBuilder()\n while (!queue.isEmpty) {\n val u = queue.dequeue\n builder += (u + 'a').toChar\n\n for (v <- 0 until m)\n if (g(u)(v)) {\n inDegree(v) = inDegree(v) - 1\n if (inDegree(v) == 0) queue.enqueue(v)\n }\n }\n\n val ans = builder.result\n println(if (ans.length() == m) ans else \"Impossible\")\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map(_ => in.next().map(_ - 'a'))\n val nodes = Array.ofDim[Boolean](26, 26)\n\n def fill(start: Int, end: Int, letter: Int) {\n val indices = (start to end).filter(i => data(i).length > letter)\n if (indices.length > 1) {\n val letters = indices.map(i => data(i)(letter))\n letters.tail.foldLeft(letters.head) {\n case (prev, el) =>\n if (prev != el)\n nodes(el)(prev) = true\n el\n }\n val res = indices.tail.foldLeft(indices.head) {\n case(startSoFar, el) if data(startSoFar)(letter) == data(el)(letter) => startSoFar\n case(startSoFar, el) =>\n fill(startSoFar, el - 1, letter + 1)\n el\n }\n fill(res, indices.last, letter + 1)\n }\n }\n\n fill(0, n - 1, 0)\n// println(nodes.map(_.mkString(\"\\t\")).mkString(\"\\n\"))\n\n def isValid(marked: Array[Boolean], current: Int, start: Int): Boolean =\n if (marked(current)) true\n else {\n marked(current) = true\n nodes(current).indices.forall { i =>\n !nodes(current)(i) || (i != start && isValid(marked, i, start))}\n }\n\n\n val sol = (0 until 26).forall { i =>\n isValid(Array.ofDim[Boolean](26), i, i)\n }\n\n def parent(marked: Array[Int], i: Int): Int = {\n (0 until 26).find(j => nodes(i)(j) && marked(j) == -1).map(parent(marked, _)).getOrElse(i)\n }\n\n if (!sol)\n println(\"Impossible\")\n else {\n val marked = Array.fill[Int](26)(-1)\n var number = 0\n val sol = (0 until 26).foreach { i =>\n while (marked(i) == -1) {\n marked(parent(marked, i)) = number\n number += 1\n }\n }\n val nString = marked.zip('a' to 'z').sortBy(_._1).map(_._2).mkString\n val r = data.map(_.map(i => (marked(i) + 'a').toChar).mkString)\n// println(r.mkString(\"\\n\"))\n if (r == r.sorted)\n println(nString)\n else\n println(\"Impossible\")\n }\n\n\n}"}, {"source_code": "import java.io._\nimport java.util\nimport java.util._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def compare(s: String, t: String): (Int, Int) = {\n val len = Math.min(s.length, t.length)\n (0 until len).foreach(i => {\n val t1 = t.charAt(i)\n val s1 = s.charAt(i)\n if (s1 != t1) {\n return (t1 - 'a', s1 - 'a')\n }\n })\n if (t.length > s.length) {\n return (0, 0)\n }\n return (-1, -1)\n }\n\n def solve: Int = {\n val n = nextInt\n val names = new Array[String](n)\n (0 until n).foreach(names(_) = next)\n val len = 26\n val g = new Array[Array[Boolean]](27)\n (0 until len).foreach(g(_) = new Array[Boolean](len))\n (0 until n - 1).foreach(i => {\n val edge = compare(names(i), names(i + 1))\n if (edge ==(-1, -1)) {\n out.println(\"Impossible\")\n return 1\n }\n if (edge !=(0, 0)) {\n g(edge._1)(edge._2) = true\n }\n })\n var flag = true\n val color = new Array[Int](len)\n val ans = new util.ArrayList[Int]()\n class Utils {\n def dfs(v: Int): Unit = {\n color(v) = 1\n (0 until len).foreach(i => {\n if (g(v)(i))\n if (color(i) == 0) {\n dfs(i)\n } else if (color(i) == 1) {\n flag = false\n }\n })\n color(v) = 2\n ans.add(v)\n }\n }\n val u = new Utils\n for (i <- 0 until len) {\n if (color(i) == 0) {\n u.dfs(i)\n }\n }\n if (!flag) {\n out.println(\"Impossible\")\n return 1\n }\n (0 until ans.size()).foreach(i => out.print((ans.get(i) + 'a').toChar))\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "object Main extends App {\n\n import collection.mutable.Set\n import collection.mutable.Queue\n import scala.util.{Try, Success, Failure}\n\n def prefix(p: String, w1: String, w2: String): String = {\n if(w1 == \"\") p\n else if (w2 == \"\") p\n else {\n val c1 = w1.head\n val c2 = w2.head\n if(c1 == c2) prefix(p+c1.toString, w1.tail, w2.tail)\n else p\n }\n }\n\n def topological(r: Seq[(Char, Char)]): List[Char] = {\n val graph = r.groupBy(_._1).map({ case (g, v) => (g, v.map(_._2))}).toMap\n val order = Queue[Char]()\n val enter = Set(r.map(_._1): _*)\n val gray = Set[Char]()\n val black = Set[Char]()\n\n def dfs(node: Char): Unit = {\n enter.remove(node)\n gray.add(node)\n graph.getOrElse(node, List[Char]()) foreach { k =>\n if(gray.contains(k)) {\n throw new RuntimeException(\"cycle\")\n }\n if(!black.contains(k)) dfs(k)\n }\n order.enqueue(node)\n gray.remove(node)\n black.add(node)\n }\n\n while(enter.size > 0) dfs(enter.head)\n order.toList.reverse\n }\n\n def rules(w1: String, w2: String): List[(Char, Char)] = {\n val p = prefix(\"\", w1, w2)\n val ps = p.size\n if(w1.size == ps) {\n List()\n } else if (w2.size == ps) {\n println(\"Impossible\")\n System.exit(0)\n List()\n } else {\n List(w1.drop(ps).head -> w2.drop(ps).head)\n }\n }\n\n val n = readInt\n val words = (1 to n) map { _ => readLine }\n val r = (words zip words.tail) flatMap { case (w1, w2) => rules(w1, w2) }\n Try(topological(r)) match {\n case Failure(_) => println(\"Impossible\")\n case Success(tr) => {\n println(tr.mkString + (\"abcdefghijklmnopqrstuvwxyz\".toSet.diff(tr.toSet)).mkString)\n }\n }\n}"}, {"source_code": "/**\n * Created by mros on 2015/3/29.\n */\n\nimport scala.io.StdIn\nobject Hi {\n var topo = Array.fill[List[Int]](26)(List[Int]())\n var count = Array.fill[Int](26)(0)\n def toInt(a: Char): Int = {\n a.toInt - 'a'.toInt\n }\n\n def mark(a: Char, b: Char): Unit = {\n val n = toInt(a)\n topo(n) = toInt(b) :: topo(n)\n count(toInt(b)) += 1\n }\n\n def printTopoSort(): Unit = {\n var visited = Array.fill[Boolean](26)(false)\n def select_one(): Char = {\n for (node <- 0 to 25) {\n if (!visited(node) && count(node) == 0) {\n for (nextNode <- topo(node)) {\n count(nextNode) -= 1\n }\n visited(node) = true\n return (node + 'a'.toInt).toChar\n }\n }\n return '#'\n }\n var ans = List[Char]()\n var OK = true\n for (_ <- 0 to 25) {\n val newone = select_one()\n if (newone == '#') {\n OK = false\n }\n else {\n ans = newone :: ans\n }\n }\n if (OK) {\n for (c <- ans.reverse) {\n print(c)\n }\n }\n else {\n println(\"Impossible\")\n }\n }\n\n def whatChar(big: String, small: String): (Char, Char) = {\n val limit = math.min(big.length, small.length)\n def rec(i: Int): (Char, Char) = {\n if (i >= limit) { return ('#', '#') }\n if (big(i) != small(i)) { return (big(i), small(i)) }\n else { return rec(i + 1) }\n }\n return rec(0)\n }\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n val authors = new Array[String](n)\n for (i <- 0 to (n-1)) {\n authors(i) = StdIn.readLine()\n if (i > 0 && authors(i-1).startsWith(authors(i)) && authors(i-1).length > authors(i).length) {\n println(\"Impossible\")\n return\n }\n }\n for (i <- 0 to (n - 2)) {\n whatChar(authors(i), authors(i + 1)) match {\n case ('#', '#') => ()\n case (a, b) => mark(a, b)\n }\n }\n printTopoSort()\n }\n}\n"}, {"source_code": "/**\n * Created by helfper on 02/02/2015.\n */\nimport scala.collection.mutable._\n\nobject FoxAndNames {\n def main(args: Array[String]) {\n val n = io.StdIn.readInt\n val strs = List.range(0, n).map(i => io.StdIn.readLine)\n\n solve(strs)\n }\n\n def solve(strs: List[String]): Unit = {\n val inEdges = Map.empty[Char, List[Char]].withDefaultValue(Nil)\n val outEdges = Map.empty[Char, List[Char]].withDefaultValue(Nil)\n\n def iterate(s1: String, s2: String): Boolean = {\n val idx = s1.zipAll(s2, '.', '.').indexWhere{case (c1, c2) => c1 != c2}\n\n if (idx == -1 || idx >= s1.length) true\n else if (idx >= s2.length) false\n else {\n val c1 = s1(idx)\n val c2 = s2(idx)\n inEdges.update(c2, c1 :: inEdges(c2))\n outEdges.update(c1, c2 :: outEdges(c1))\n true\n }\n }\n\n strs.init.zip(strs.tail).foreach { case (s1, s2) =>\n if(!iterate(s1, s2)) {\n println(\"Impossible\")\n return\n }\n }\n\n var set = 'a'.to('z').filter(c => inEdges(c).isEmpty).toSet\n var list = List.empty[Char]\n while (!set.isEmpty) {\n val n = set.head\n set -= n\n list = n :: list\n outEdges(n).foreach { m =>\n inEdges.update(m, inEdges(m).filter(_ != n))\n if (inEdges(m).isEmpty) {\n set += m\n }\n }\n }\n if (inEdges.exists{case (c, l) => l.nonEmpty}) {\n println(\"Impossible\")\n return\n }\n println(list.reverse.mkString)\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val names = Array.fill(n) { (readLine + '{').toCharArray }\n val adjBuilders = Array.fill('{'.toInt + 1) { new mutable.ArrayBuilder.ofChar }\n val after = Array.fill('{'.toInt + 1, '{'.toInt + 1)(false)\n\n for {\n i <- 0 until n\n n1 = names(i)\n j <- i + 1 until n\n n2 = names(j)\n } {\n var equal = true\n var p = 0\n val l = n1.length min n2.length\n while (equal & p < l) {\n if (n1(p) != n2(p)) {\n adjBuilders(n1(p)) += n2(p)\n after(n1(p))(n2(p)) = true\n equal = false\n }\n p += 1\n }\n }\n\n val adj = adjBuilders.map(_.result.distinct)\n\n val visited = new mutable.BitSet(n)\n val stack = mutable.Stack.empty[Char]\n var err = false\n\n def dfs1(u: Char): Unit = {\n if (!visited(u)) {\n visited += u\n for (v <- adj(u)) {\n if (after(v)(u)) {\n err = true\n }\n dfs1(v)\n }\n stack.push(u)\n }\n }\n\n for (i <- 'a' to '{') dfs1(i)\n\n println(if (err) \"Impossible\" else stack.toArray.filterNot(_ == '{').mkString)\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val names = Array.fill(n) { (readLine + '{').toCharArray }\n val adjBuilders = Array.fill('{'.toInt + 1) { new mutable.ArrayBuilder.ofChar }\n val after = Array.fill('{'.toInt + 1, '{'.toInt + 1)(false)\n\n for {\n i <- 0 until n\n n1 = names(i)\n j <- i + 1 until n\n n2 = names(j)\n } {\n var equal = true\n var p = 0\n val l = n1.length min n2.length\n while (equal & p < l) {\n if (n1(p) != n2(p)) {\n adjBuilders(n1(p)) += n2(p)\n after(n1(p))(n2(p)) = true\n equal = false\n }\n p += 1\n }\n }\n\n for (c <- 'a' to 'z') after('{')(c) = true\n \n val adj = adjBuilders.map(_.result.distinct)\n\n val visited = new mutable.BitSet\n val stack = mutable.Stack.empty[Char]\n var err = false\n\n def dfs1(u: Char): Unit = {\n if (!visited(u)) {\n visited += u\n for (v <- adj(u)) {\n if (after(v)(u)) {\n err = true\n }\n dfs1(v)\n }\n stack.push(u)\n }\n }\n\n for (i <- '{'.toInt to 'a'.toInt by -1) dfs1(i.toChar)\n\n println(if (err) \"Impossible\" else stack.toArray.filter(_ != '{').mkString)\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val names = Array.fill(n) { (readLine + '{').toCharArray }\n val adjBuilders = Array.fill('{'.toInt + 1) { new mutable.ArrayBuilder.ofChar }\n val after = Array.fill('{'.toInt + 1, '{'.toInt + 1)(false)\n\n for {\n i <- 0 until n\n n1 = names(i)\n j <- i + 1 until n\n n2 = names(j)\n } {\n var equal = true\n var p = 0\n val l = n1.length min n2.length\n while (equal & p < l) {\n if (n1(p) != n2(p)) {\n adjBuilders(n1(p)) += n2(p)\n after(n1(p))(n2(p)) = true\n equal = false\n }\n p += 1\n }\n }\n\n val adj = adjBuilders.map(_.result.distinct)\n\n val visited = new mutable.BitSet(n)\n val stack = mutable.Stack.empty[Char]\n var err = false\n\n def dfs1(u: Char): Unit = {\n if (!visited(u)) {\n visited += u\n for (v <- adj(u)) {\n if (after(v)(u)) {\n err = true\n }\n dfs1(v)\n }\n stack.push(u)\n }\n }\n\n for (i <- 'a' to '{') dfs1(i)\n\n println(if (err || stack.pop != '{') \"Impossible\" else stack.toArray.mkString)\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val names = Array.fill(n) { (readLine + '{').toCharArray }\n val adjBuilders = Array.fill('{'.toInt + 1) { new mutable.ArrayBuilder.ofChar }\n val after = Array.fill('{'.toInt + 1, '{'.toInt + 1)(false)\n\n for {\n i <- 0 until n\n n1 = names(i)\n j <- i + 1 until n\n n2 = names(j)\n } {\n var equal = true\n var p = 0\n val l = n1.length min n2.length\n while (equal & p < l) {\n if (n1(p) != n2(p)) {\n adjBuilders(n1(p)) += n2(p)\n after(n1(p))(n2(p)) = true\n equal = false\n }\n p += 1\n }\n }\n\n for (c <- 'a' to 'z') after('{')(c) = true\n \n val adj = adjBuilders.map(_.result.distinct)\n\n val visited = new mutable.BitSet(n)\n val stack = mutable.Stack.empty[Char]\n var err = false\n\n def dfs1(u: Char): Unit = {\n if (!visited(u)) {\n visited += u\n for (v <- adj(u)) {\n if (after(v)(u)) {\n err = true\n }\n dfs1(v)\n }\n stack.push(u)\n }\n }\n\n for (i <- 'a' to '{') dfs1(i)\n\n println(if (err || stack.pop != '{') \"Impossible\" else stack.toArray.mkString)\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val names = Array.fill(n) { (readLine + '{').toCharArray }\n val adjBuilders = Array.fill('{'.toInt + 1) { new mutable.ArrayBuilder.ofChar }\n val after = Array.fill('{'.toInt + 1, '{'.toInt + 1)(false)\n\n for {\n i <- 0 until n\n n1 = names(i)\n j <- i + 1 until n\n n2 = names(j)\n } {\n var equal = true\n var p = 0\n val l = n1.length min n2.length\n while (equal & p < l) {\n if (n1(p) != n2(p)) {\n adjBuilders(n1(p)) += n2(p)\n after(n1(p))(n2(p)) = true\n equal = false\n }\n p += 1\n }\n }\n\n for (c <- 'a' to 'z') after('{')(c) = true\n \n val adj = adjBuilders.map(_.result.distinct)\n\n val visited = new mutable.BitSet(n)\n val stack = mutable.Stack.empty[Char]\n var err = false\n\n def dfs1(u: Char): Unit = {\n if (!visited(u)) {\n visited += u\n for (v <- adj(u)) {\n if (after(v)(u)) {\n err = true\n }\n dfs1(v)\n }\n stack.push(u)\n }\n }\n\n for (i <- '{'.toInt to 'a'.toInt by -1) dfs1(i.toChar)\n\n println(if (err) \"Impossible\" else stack.toArray.filter(_ != '{').mkString)\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val names = Array.fill(n) { (readLine + '{').toCharArray }\n val adjBuilders = Array.fill('{'.toInt + 1) { new mutable.ArrayBuilder.ofChar }\n val after = Array.fill('{'.toInt + 1, '{'.toInt + 1)(false)\n\n for {\n i <- 0 until n\n n1 = names(i)\n j <- i + 1 until n\n n2 = names(j)\n } {\n var equal = true\n var p = 0\n val l = n1.length min n2.length\n while (equal & p < l) {\n if (n1(p) != n2(p)) {\n adjBuilders(n1(p)) += n2(p)\n after(n1(p))(n2(p)) = true\n equal = false\n }\n p += 1\n }\n }\n\n for (c <- 'a' to 'z') after('{')(c) = true\n \n for (c <- 'a' to '{')\n for (a <- 'a' to '{') for (b <- 'a' to '{') if (after(a)(b) && after(b)(c)) after(a)(b) = true\n\n val adj = adjBuilders.map(_.result.distinct)\n\n val visited = new mutable.BitSet\n val stack = mutable.Stack.empty[Char]\n var err = false\n\n def dfs1(u: Char, root: Boolean = false): Unit = {\n //println(u)\n if (!visited(u)) {\n visited += u\n for (v <- adj(u)) {\n if (after(v)(u)) {\n err = true\n }\n dfs1(v)\n }\n stack.push(u)\n /*} else if (!root) {\n err = true*/ \n }\n }\n\n for (i <- '{'.toInt to 'a'.toInt by -1) if (!visited(i)) dfs1(i.toChar, true)\n\n println(if (err) \"Impossible\" else stack.toArray.filter(_ != '{').mkString)\n\n Console.flush\n}\n"}, {"source_code": "\nimport scala.math._\nimport scala.collection.mutable\nimport scala.util.control.Breaks\n\nobject Problem extends App {\n import Scanner._\n\n val names = Array.fill(readInt)(readString)\n val longest = names.maxBy(s => s.length).length\n\n case class Node(c: Char) extends Ordered[Node] {\n var before = mutable.Set[Node]()\n var after = mutable.Set[Node]()\n\n def compare(n: Node) = c - n.c\n }\n val nodes = for(i <- 0 until 26) yield Node((i + 'a').toChar)\n def addOrdering(strings: List[String]) {\n val chars = strings.map(s => s(0)-'a')\n for(i <- 1 until chars.length; if chars(i-1) != chars(i)) {\n nodes(chars(i-1)).before += nodes(chars(i))\n nodes(chars(i)).after += nodes(chars(i-1))\n }\n val grouped = strings.filter(s => s.length > 1).groupBy(s => s(0)).map(x => x._2.map(s => s.drop(1)))\n for(group <- grouped; if group.size > 1)\n addOrdering(group)\n }\n addOrdering(names.toList)\n\n //for(node <- nodes)\n // println(s\"${node.c} -> ${node.before},${node.after}\")\n\n\n val unusedNodes = mutable.TreeSet(nodes: _*)\n var str = \"\"\n while(!unusedNodes.isEmpty) unusedNodes.find(n => n.after.isEmpty) match {\n case Some(node) =>\n for(n <- node.before)\n n.after -= node\n unusedNodes -= node\n str += node.c\n case None =>\n println(\"Impossible\")\n System.exit(0)\n }\n println(str)\n}\n\ncase class Memo[A, B](f: A => B, size: Int = 10) extends (A => B) {\n private val cache = new scala.collection.mutable.HashMap[A, B] {\n override def initialSize = size\n }\n def apply(x: A) = cache getOrElseUpdate (x, f(x))\n}\n\nobject Scanner {\n def readInt() = {\n var acc = 0\n readWith {\n case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n }\n acc\n }\n def readLong() = {\n var acc = 0L\n readWith {\n case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10L) + (c - '0')\n }\n acc\n }\n def readDouble() = {\n var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)\n readWith {\n case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>\n frac = (frac * 10) + (c - '0')\n fracPow *= 10\n case c if c == '.' && !readFrac =>\n readFrac = true\n }\n acc + (frac.toDouble / fracPow)\n }\n def readString() = {\n var string = new StringBuilder\n readWith { case c => string += c }\n string.toString\n }\n def readLine() = Console.in.readLine()\n def readChar() = Console.in.read().toChar\n def readWith(func: PartialFunction[Char, Unit]) {\n val handler = func orElse[Char, Unit] {\n case _ => throw new java.io.IOException(\"unexpected token\")\n }\n\n var c = readChar\n while(c.isWhitespace)\n c = readChar\n\n while(!c.isWhitespace) {\n handler(c)\n\n c = readChar\n }\n }\n}\n\n"}, {"source_code": "\nimport scala.math._\nimport scala.collection.mutable\nimport scala.util.control.Breaks\n\nobject Problem extends App {\n import Scanner._\n\n val names = Array.fill(readInt)(readString)\n val longest = names.maxBy(s => s.length).length\n\n case class Node(c: Char) extends Ordered[Node] {\n var before = mutable.Set[Node]()\n var after = mutable.Set[Node]()\n\n def compare(n: Node) = c - n.c\n }\n val nodes = for(i <- 0 until 26) yield Node((i + 'a').toChar)\n def addOrdering(strings: List[String]) {\n val chars = strings.map(s => s(0)-'a')\n for(i <- 1 until chars.length; if chars(i-1) != chars(i)) {\n nodes(chars(i-1)).before += nodes(chars(i))\n nodes(chars(i)).after += nodes(chars(i-1))\n }\n val grouped = strings.groupBy(s => s(0)).map(x => x._2.drop(1))\n for(group <- grouped; if group.size > 1)\n addOrdering(group)\n }\n addOrdering(names.toList)\n\n //for(node <- nodes)\n // println(s\"${node.c} -> ${node.before},${node.after}\")\n\n\n val unusedNodes = mutable.TreeSet(nodes: _*)\n var str = \"\"\n while(!unusedNodes.isEmpty) unusedNodes.find(n => n.after.isEmpty) match {\n case Some(node) =>\n for(n <- node.before)\n n.after -= node\n unusedNodes -= node\n str += node.c\n case None =>\n println(\"Impossible\")\n System.exit(0)\n }\n println(str)\n}\n\ncase class Memo[A, B](f: A => B, size: Int = 10) extends (A => B) {\n private val cache = new scala.collection.mutable.HashMap[A, B] {\n override def initialSize = size\n }\n def apply(x: A) = cache getOrElseUpdate (x, f(x))\n}\n\nobject Scanner {\n def readInt() = {\n var acc = 0\n readWith {\n case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n }\n acc\n }\n def readLong() = {\n var acc = 0L\n readWith {\n case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10L) + (c - '0')\n }\n acc\n }\n def readDouble() = {\n var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)\n readWith {\n case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>\n frac = (frac * 10) + (c - '0')\n fracPow *= 10\n case c if c == '.' && !readFrac =>\n readFrac = true\n }\n acc + (frac.toDouble / fracPow)\n }\n def readString() = {\n var string = new StringBuilder\n readWith { case c => string += c }\n string.toString\n }\n def readLine() = Console.in.readLine()\n def readChar() = Console.in.read().toChar\n def readWith(func: PartialFunction[Char, Unit]) {\n val handler = func orElse[Char, Unit] {\n case _ => throw new java.io.IOException(\"unexpected token\")\n }\n\n var c = readChar\n while(c.isWhitespace)\n c = readChar\n\n while(!c.isWhitespace) {\n handler(c)\n\n c = readChar\n }\n }\n}\n\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map(_ => in.next().map(_ - 'a'))\n val nodes = Array.ofDim[Boolean](26, 26)\n\n def fill(start: Int, end: Int, letter: Int) {\n val indices = (start to end).filter(i => data(i).length > letter)\n if (indices.length > 1) {\n val letters = indices.map(i => data(i)(letter))\n letters.tail.foldLeft(letters.head) {\n case (prev, el) =>\n if (prev != el)\n nodes(el)(prev) = true\n el\n }\n val res = indices.tail.foldLeft(indices.head) {\n case(startSoFar, el) if data(startSoFar)(letter) == data(el)(letter) => startSoFar\n case(startSoFar, el) =>\n fill(startSoFar, el - 1, letter + 1)\n el\n }\n fill(res, indices.last, letter + 1)\n }\n }\n\n fill(0, n - 1, 0)\n// println(nodes.map(_.mkString(\"\\t\")).mkString(\"\\n\"))\n\n def isValid(marked: Array[Boolean], current: Int, start: Int): Boolean =\n if (marked(current)) true\n else {\n marked(current) = true\n nodes(current).indices.forall { i =>\n !nodes(current)(i) || (i != start && isValid(marked, i, start))}\n }\n\n\n val sol = (0 until 26).forall { i =>\n isValid(Array.ofDim[Boolean](26), i, i)\n }\n\n def parent(marked: Array[Int], i: Int): Int = {\n (0 until 26).find(j => nodes(i)(j) && marked(j) == -1).map(parent(marked, _)).getOrElse(i)\n }\n\n if (!sol)\n println(\"Impossible\")\n else {\n val marked = Array.fill[Int](26)(-1)\n var number = 0\n val sol = (0 until 26).foreach { i =>\n while (marked(i) == -1) {\n marked(parent(marked, i)) = number\n number += 1\n }\n }\n println(marked.zip('a' to 'z').sortBy(_._1).map(_._2).mkString)\n }\n\n\n}"}, {"source_code": "object Main extends App {\n\n import collection.mutable.Set\n import collection.mutable.Queue\n import scala.util.{Try, Success, Failure}\n\n def prefix(p: String, w1: String, w2: String): String = {\n if(w1 == \"\") p\n else if (w2 == \"\") p\n else {\n val c1 = w1.head\n val c2 = w2.head\n if(c1 == c2) prefix(p+c1.toString, w1.tail, w2.tail)\n else p\n }\n }\n\n def topological(r: Seq[(Char, Char)]): Queue[Char] = {\n val graph = r.groupBy(_._1).map({ case (g, v) => (g, v.map(_._2))}).toMap\n val order = Queue[Char]()\n val enter = Set(r.map(_._1): _*)\n val gray = Set[Char]()\n val black = Set[Char]()\n\n def dfs(node: Char): Unit = {\n enter.remove(node)\n gray.add(node)\n graph.getOrElse(node, List[Char]()) foreach { k =>\n if(gray.contains(k)) {\n throw new RuntimeException(\"cycle\")\n }\n if(!black.contains(k)) dfs(k)\n }\n order.enqueue(node)\n gray.remove(node)\n black.add(node)\n }\n\n while(enter.size > 0) dfs(enter.head)\n order\n }\n\n def rules(w1: String, w2: String): List[(Char, Char)] = {\n val p = prefix(\"\", w1, w2)\n val ps = p.size\n if(w1.size == ps) {\n List()\n } else if (w2.size == ps) {\n println(\"Impossible\")\n System.exit(0)\n List()\n } else {\n List(w1.drop(ps).head -> w2.drop(ps).head)\n }\n }\n\n val n = readInt\n val words = (1 to n) map { _ => readLine }\n val r = (words zip words.tail) flatMap { case (w1, w2) => rules(w1, w2) }\n Try(topological(r)) match {\n case Failure(_) => println(\"Impossible\")\n case Success(tr) => {\n println(tr.mkString + (\"abcdefghijklmnopqrstuvwxyz\".toSet - tr.toSet).mkString)\n }\n }\n}"}, {"source_code": "object Main extends App {\n\n import collection.mutable.Set\n import collection.mutable.Queue\n import scala.util.{Try, Success, Failure}\n\n def prefix(p: String, w1: String, w2: String): String = {\n if(w1 == \"\") p\n else if (w2 == \"\") p\n else {\n val c1 = w1.head\n val c2 = w2.head\n if(c1 == c2) prefix(p+c1.toString, w1.tail, w2.tail)\n else p\n }\n }\n\n def topological(r: Seq[(Char, Char)]): Queue[Char] = {\n val graph = r.groupBy(_._1).map({ case (g, v) => (g, v.map(_._2))}).toMap\n val order = Queue[Char]()\n val enter = Set(r.map(_._1): _*)\n val gray = Set[Char]()\n val black = Set[Char]()\n\n def dfs(node: Char): Unit = {\n enter.remove(node)\n gray.add(node)\n graph.getOrElse(node, List[Char]()) foreach { k =>\n if(gray.contains(k)) {\n throw new RuntimeException(\"cycle\")\n }\n if(!black.contains(k)) dfs(k)\n }\n order.enqueue(node)\n gray.remove(node)\n black.add(node)\n }\n\n while(enter.size > 0) dfs(enter.head)\n order\n }\n\n def rules(w1: String, w2: String): List[(Char, Char)] = {\n val p = prefix(\"\", w1, w2)\n val ps = p.size\n if(w1.size == ps) {\n List()\n } else if (w2.size == ps) {\n println(\"Impossible\")\n System.exit(0)\n List()\n } else {\n List(w1.drop(ps).head -> w2.drop(ps).head)\n }\n }\n\n val n = readInt\n val words = (1 to n) map { _ => readLine }\n val r = (words zip words.tail) flatMap { case (w1, w2) => rules(w1, w2) }\n Try(topological(r)) match {\n case Failure(_) => println(\"Impossible\")\n case Success(tr) => {\n println(tr.mkString + (\"abcdefghijklmnopqrstuvwxyz\".toSet.diff(tr.toSet)).mkString)\n }\n }\n}"}, {"source_code": "/**\n * Created by mros on 2015/3/29.\n */\n\nimport scala.io.StdIn\nobject Hi {\n var topo = Array.fill[List[Int]](26)(List[Int]())\n var count = Array.fill[Int](26)(0)\n def toInt(a: Char): Int = {\n a.toInt - 'a'.toInt\n }\n\n def mark(a: Char, b: Char): Unit = {\n val n = toInt(a)\n topo(n) = toInt(b) :: topo(n)\n count(toInt(b)) += 1\n }\n\n def printTopoSort(): Unit = {\n var visited = Array.fill[Boolean](26)(false)\n def select_one(): Char = {\n for (node <- 0 to 25) {\n if (!visited(node) && count(node) == 0) {\n for (nextNode <- topo(node)) {\n count(nextNode) -= 1\n }\n visited(node) = true\n return (node + 'a'.toInt).toChar\n }\n }\n return '#'\n }\n var ans = List[Char]()\n var OK = true\n for (_ <- 0 to 25) {\n val newone = select_one()\n if (newone == '#') {\n OK = false\n }\n else {\n ans = newone :: ans\n }\n }\n if (OK) {\n for (c <- ans.reverse) {\n print(c)\n }\n }\n else {\n println(\"Impossible\")\n }\n }\n\n def whatChar(big: String, small: String): (Char, Char) = {\n val limit = math.min(big.length, small.length)\n def rec(i: Int): (Char, Char) = {\n if (i >= limit) { return ('#', '#') }\n if (big(i) != small(i)) { return (big(i), small(i)) }\n else { return rec(i + 1) }\n }\n return rec(0)\n }\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n val authors = new Array[String](n)\n for (i <- 0 to (n-1)) {\n authors(i) = StdIn.readLine()\n }\n for (i <- 0 to (n - 2)) {\n whatChar(authors(i), authors(i + 1)) match {\n case ('#', '#') => ()\n case (a, b) => mark(a, b)\n }\n }\n printTopoSort()\n }\n}\n"}], "src_uid": "12218097cf5c826d83ab11e5b049999f"} {"source_code": "object Solution extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n // val q = io.read[Int]\n val q = io.read[Int]\n repeat(q) {\n val n = io.read[Int]\n var k = io.read[Long]\n var ones : Int = 0\n val str = io.read[String].toCharArray()\n for(i <- 0 until n) {\n if(str(i) == '0') {\n while(ones > k) {\n ones = ones - 1\n }\n str(i) = '1'\n str(i-ones) = '0'\n k -= ones\n } else {\n ones = ones + 1\n }\n }\n for(i <- 0 until n) {\n io.write(str(i))\n }\n io.writeLine()\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}", "positive_code": [{"source_code": "object D1256 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var tests = readInt\n while (tests > 0) {\n var Array(_, k) = readLongs(2)\n val str = read.toCharArray\n var firstOne = str.indexWhere(_ == '1')\n var firstZeroAfter =\n if (firstOne != -1) str.indexWhere(_ == '0', firstOne) else -1\n while (k > 0 && firstOne != -1 && firstZeroAfter != -1) {\n if (k >= firstZeroAfter - firstOne) {\n str(firstOne) = '0'\n str(firstZeroAfter) = '1'\n k -= firstZeroAfter - firstOne\n if (k > 0) {\n firstOne = str.indexWhere(_ == '1', firstOne)\n firstZeroAfter =\n if (firstOne != -1) str.indexWhere(_ == '0', firstZeroAfter)\n else -1\n }\n } else {\n str(firstZeroAfter) = '1'\n str(firstZeroAfter - k.toInt) = '0'\n k = 0\n }\n }\n out.println(str.mkString)\n tests -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskD extends App {\n val sc = new Scanner(System.in)\n val q = sc.nextInt\n\n 0 until q foreach { _ =>\n var (n, k) = (sc.nextInt, sc.nextLong)\n val bin = sc.next.map(_ - '0').toArray\n var cnt = 0\n bin.zipWithIndex.filter(_._1 == 0).foreach { case (_, i) =>\n val shift = min(i - cnt, k).toInt\n bin(i) = 1\n bin(i - shift) = 0\n k -= shift\n cnt += 1\n }\n println(bin.mkString)\n }\n}\n"}], "negative_code": [], "src_uid": "d4b6bea78b80b0a94646cbaf048b473f"} {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, m) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val (row, col) = (0 until n).foldLeft((List.fill(m)(0), List.empty[Int])) {\n case ((row, col), _) =>\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n (row.zip(a).map { case (p, q) => p + q }, a.sum :: col)\n }\n\n val free = row.count(_ == 0) min col.count(_ == 0)\n\n val ans =\n if (free % 2 == 0) \"Vivek\"\n else \"Ashish\"\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val xs = Array.fill(n)(nextInts(m))\n val ux = Array.fill(m)(false)\n val uy = Array.fill(n)(false)\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (xs(i)(j) == 1) {\n uy(i) = true\n ux(j) = true\n }\n }\n }\n\n val cx = m - ux.count(identity)\n val cy = n - uy.count(identity)\n val moves = Math.min(cx, cy)\n val res = if (moves % 2 == 1) \"Ashish\" else \"Vivek\"\n\n out.println(res)\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val mn = readIntLine()\n val grid = (1 to mn.head).map(_ => readIntLine()).toList\n val min = Math.min(mn.head - calc(grid), mn.last - calc(grid.transpose))\n println(if (min % 2 == 0) \"Vivek\" else \"Ashish\")\n }\n }\n\n def calc(grid: List[List[Int]]) = grid.count(row => row.contains(1))\n\n def calcCols(grid: List[List[Int]]): Int = {\n val arr = Array.ofDim[Boolean](grid.head.length)\n grid.foreach(row => row.zipWithIndex.foreach(tup => if (tup._1 == 1) arr(tup._2) = true))\n arr.count(i => i)\n }\n\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val mn = readIntLine()\n val grid = (1 to mn.head).map(_ => readIntLine()).toList\n val min = Math.min(calc(grid), calc(grid.transpose))\n println(if (min % 2 == 0) \"Vivek\" else \"Ashish\")\n }\n }\n\n def calc(grid: List[List[Int]]) = grid.count(row => row.contains(1))\n\n def calcCols(grid: List[List[Int]]): Int = {\n val arr = Array.ofDim[Boolean](grid.head.length)\n grid.foreach(row => row.zipWithIndex.foreach(tup => if (tup._1 == 1) arr(tup._2) = true))\n arr.count(i => i)\n }\n\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val mn = readIntLine()\n val grid = (1 to mn.head).map(_ => readIntLine()).toList\n val min = Math.min(calc(grid), calcCols(grid))\n println(if (min % 2 == 0) \"Vivek\" else \"Ashish\")\n }\n }\n\n def calc(grid: List[List[Int]]) = grid.count(row => row.contains(1))\n\n def calcCols(grid: List[List[Int]]): Int = {\n val arr = Array.ofDim[Boolean](grid.head.length)\n grid.foreach(row => row.zipWithIndex.foreach(tup => if (tup._1 == 1) arr(tup._2) = true))\n arr.count(i => i)\n }\n\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}], "src_uid": "3ccc98190189b0c8e58a96dd5ad1245d"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, D, M = ni()\n val F = Array.fill[Boolean](N + 1, N + 1)(true)\n rep(N + 1) { i =>\n val l = abs(D - i)\n val r = abs(N - D - i)\n rep(l) { j =>\n F(i)(j) = false\n }\n rep(r) { j =>\n F(i)(N - j) = false\n }\n }\n\n rep(M) { _ =>\n val x, y = ni()\n out.println(if (F(y)(x)) \"YES\" else \"NO\")\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Problem1030B {\n def main(args: Array[String]): Unit = {\n val vals = StdIn.readLine().split(\" \").map(_.toInt)\n val n = vals(0)\n val d = vals(1)\n val m = StdIn.readInt()\n val coords = for (i <- 0 until m) yield {\n val coords = StdIn.readLine().split(\" \").map(_.toInt)\n (coords(0), coords(1))\n }\n print(solve(n, d, coords).mkString(\"\\n\"))\n }\n def solve(n: Int, d: Int, coords: Seq[(Int, Int)]): Seq[String] = {\n coords.map(coord => {\n val (x, y) = coord\n solve(n, d, x, y)\n }).map(if (_) {\n \"YES\"\n } else {\n \"NO\"\n })\n }\n\n def solve(n: Int, d: Int, x: Int, y: Int): Boolean = {\n if (x + y < d || x + y > 2 * n - d) {\n false\n } else if (x - y < -d || x - y > d) {\n false\n } else {\n true\n }\n }\n}\n"}], "negative_code": [], "src_uid": "9c84eb518c273942650c7262e5d8b45f"} {"source_code": "object D extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n \n val ys = Array.ofDim[(Char, Int)](n)\n val xs = Array.ofDim[Int](m)\n \n for (i <- 0 until n) ys(i) = readString.split(\" \") match {\n case Array(\"ATK\", x) => ('a', x.toInt)\n case Array(\"DEF\", x) => ('d', x.toInt)\n }\n \n val yas = ys.filter(_._1 == 'a').map(_._2).sorted\n val yds = ys.filter(_._1 == 'd').map(_._2).sorted\n\n for (i <- 0 until m) xs(i) = readString.toInt\n\n var points1 = 0\n val xs1 = xs.sorted\n var di = 0\n var ai = 0\n \n for (x <- xs1) {\n if (di < yds.length && x > yds(di)) {\n di += 1\n } else if (ai < yas.length && x >= yas(ai)) {\n points1 += x - yas(ai)\n ai += 1\n } else points1 += x\n }\n \n if (di < yds.length || ai < yas.length) points1 = 0\n \n var points2 = 0\n ai = 0\n \n for (x <- xs1.reverse) {\n if (ai < yas.length && x >= yas(ai)) {\n points2 += x - yas(ai)\n ai += 1\n }\n }\n\n println(points1 max points2) \n}", "positive_code": [{"source_code": "object D extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n \n val ys = Array.ofDim[(Char, Int)](n)\n val xs = Array.ofDim[Int](m)\n \n for (i <- 0 until n) ys(i) = readString.split(\" \") match {\n case Array(\"ATK\", x) => ('a', x.toInt)\n case Array(\"DEF\", x) => ('d', x.toInt)\n }\n \n val yas = ys.filter(_._1 == 'a').map(_._2).sorted\n val yds = ys.filter(_._1 == 'd').map(_._2).sorted\n\n for (i <- 0 until m) xs(i) = readString.toInt\n\n var points1 = 0\n val xs1 = xs.sorted\n var di = 0\n var ai = 0\n \n for (x <- xs1) {\n if (di < yds.length && x > yds(di)) {\n di += 1\n } else if (ai < yas.length && x >= yas(ai)) {\n points1 += x - yas(ai)\n ai += 1\n } else points1 += x\n }\n \n if (di < yds.length || ai < yas.length) points1 = 0\n \n var points2 = 0\n ai = 0\n \n for (x <- xs1.reverse) {\n if (ai < yas.length && x >= yas(ai)) {\n points2 += x - yas(ai)\n ai += 1\n }\n }\n\n println(points1 max points2) \n}"}], "negative_code": [{"source_code": "object D extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n \n val ys = Array.ofDim[(Char, Int)](n)\n val xs = Array.ofDim[Int](m)\n \n for (i <- 0 until n) ys(i) = readString.split(\" \") match {\n case Array(\"ATK\", x) => ('a', x.toInt)\n case Array(\"DEF\", x) => ('d', x.toInt)\n }\n \n val yas = ys.filter(_._1 == 'a').map(_._2).sorted\n val yds = ys.filter(_._1 == 'd').map(_._2).sorted\n\n for (i <- 0 until m) xs(i) = readString.toInt\n\n var points1 = 0\n val xs1 = xs.sorted\n var di = 0\n var ai = 0\n \n for (x <- xs) {\n if (di < yds.length && x > yds(di)) {\n di += 1\n } else if (ai < yas.length && x >= yas(ai)) {\n points1 += x - yas(ai)\n ai += 1\n } else points1 += x\n }\n \n if (di < yds.length || ai < yas.length) points1 = 0\n \n var points2 = 0\n ai = 0\n \n for (x <- xs.reverse) {\n if (ai < yas.length && x >= yas(ai)) {\n points2 += x - yas(ai)\n ai += 1\n }\n }\n\n println(points1 max points2) \n}"}], "src_uid": "06420ea88312103231a7bbac8a9a62d1"} {"source_code": "object Main\n{\n\tdef countareas(areas:Array[Int], a:Int):Int =\n\t{\n\t\tvar i = a\n\t\tvar j = a\n\t\twhile(i > 0 && areas(i - 1) <= areas(i)) i -= 1\n\t\twhile(j < areas.length - 1 && areas(j + 1) <= areas(j)) j += 1\n\t\treturn j - i + 1\n\t}\n\t\n\tdef main(args:Array[String])\n\t{\n\t\treadInt;\n\t\tval a = readLine.split(\" \").map(i => i.toInt)\n\t\tprintln((0 until a.length).map(i => countareas(a, i)).max)\n\t}\n}", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n def count(height: IndexedSeq[Int], i: Int): Int = {\n val left = (i - 1 to 0 by -1).find(j => height(j) > height(j + 1))\n val right = (i + 1 until height.length).find(j => height(j) > height(j - 1))\n if (left.isEmpty)\n right.getOrElse(n)\n else\n right.getOrElse(n) - 1 - left.get\n }\n\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val height = in.next().split(' ').map(_.toInt)\n// println((0 until n).map(i => count(height, i)))\n println((0 until n).map(i => count(height, i)).max)\n}"}], "negative_code": [], "src_uid": "5d11fa8528f1dc873d50b3417bef8c79"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline private final def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n\n case class Entry(ix: Int, v: Int, isFront: Boolean)\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n import java.util.Comparator\n val n, m, h = ni()\n val front = na(m)\n val left = na(n)\n val top = nm(n, m)\n val ans = Array.fill[Int](n, m)(-1)\n val E = Array.ofDim[Entry](n + m)\n REP(m) { i =>\n E(i) = Entry(i, front(i), isFront = true)\n }\n REP(n) { i =>\n E(m + i) = Entry(i, left(i), isFront = false)\n }\n sort(E, new Comparator[Entry] {\n override def compare(o1: Entry, o2: Entry): Int = Integer.compare(o1.v, o2.v)\n })\n\n debug(E.mkString(\" \"))\n\n REP(E.length) { ii =>\n val e = E(ii)\n if (e.v > 0) {\n if (E(ii).isFront) {\n val j = e.ix\n REP(n) { i =>\n if (ans(i)(j) == -1 && top(i)(j) == 1) {\n ans(i)(j) = e.v\n }\n }\n } else {\n val i = e.ix\n REP(m) { j =>\n if (ans(i)(j) == -1 && top(i)(j) == 1) {\n ans(i)(j) = e.v\n }\n }\n }\n }\n }\n debugDim(ans)\n\n REP(n) { i =>\n REP(m) { j =>\n if (ans(i)(j) == -1) ans(i)(j) = 0\n }\n }\n REP(n) { i =>\n out.println(ans(i).mkString(\" \"))\n }\n }\n}", "positive_code": [{"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n val in = io.Source.stdin.getLines()\n val Array(n, m, h) = in.next().split(\" \").map(_.toInt)\n\n val front = in.next().split(\" \").map(_.toInt)\n val left = in.next().split(\" \").map(_.toInt)\n\n val heights = Array.ofDim[Int](n,m)\n (0 until n).foreach { i =>\n heights(i) = in.next().split(\" \").map(_.toInt)\n }\n\n val answer = Array.ofDim[Int](n,m)\n\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (heights(i)(j) == 0) {\n answer(i)(j) = 0\n } else {\n answer(i)(j) = Math.min(Math.max(heights(i)(j), left(i)), Math.max(heights(i)(j), front(j)))\n }\n }\n }\n\n for (i <- 0 until n) {\n println(answer(i).mkString(\" \"))\n }\n\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject CodeForces2 extends App {\n\n\n val Array(n, m, h) = readLine().split(\" \").map(_.toInt)\n\n val front = readLine().split(\" \").map(_.toInt)\n val left = readLine().split(\" \").map(_.toInt)\n\n var i = 0\n var lines = mutable.Buffer[String]()\n while (i < n) {\n val line = readLine().split(\" \").map(_.toInt)\n var j = 0\n while (j < line.length) {\n line(j) = line(j) * Math.min(front(j), left(i))\n j += 1\n }\n lines += line.mkString(\" \")\n i += 1\n }\n\n lines.foreach(println)\n\n def println(x: Any): Unit = {\n Console.println(x)\n Console.flush()\n }\n\n def readLine(): String = StdIn.readLine()\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Codeforces1153B {\n\n def getBrickHeights(n: Int, m: Int, maxHeight: Int, a: Seq[Int], b: Seq[Int], h: Seq[Seq[Int]]): Seq[Seq[Int]] = {\n (0 until n).map(i => {\n (0 until m).map(j => {\n val value = math.min(a(j), b(i))\n if (h(i)(j) == 1) value else 0\n })\n })\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m, maxHeight) = StdIn.readLine().trim.split(\" \").map(_.toInt)\n val a = StdIn.readLine().trim.split(\" \").map(_.toInt)\n val b = StdIn.readLine().trim.split(\" \").map(_.toInt)\n val h = (1 to n).map(_ => StdIn.readLine().trim.split(\" \").map(_.toInt).toSeq)\n val gridHeights = getBrickHeights(n, m, maxHeight, a, b, h)\n for (rowHeights <- gridHeights) {\n for (cell <- rowHeights) {\n print(cell + \" \")\n }\n println()\n }\n }\n}\n"}], "negative_code": [], "src_uid": "7361e8acf0d712c317e8b99211a7b548"} {"source_code": "import scala.collection.mutable\n\nobject E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n class BIT(src: Array[Long]) {\n\n private val t = Array.fill(src.length) { 0L }\n\n for (i <- src.indices) update(i, src(i))\n\n def query(r: Int, acc: Long = 0): Long =\n if (r < 0) acc else query((r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(l: Int, r: Int) = query(r) - query(l - 1)\n\n def update(i: Int, delta: Long): Unit =\n if (i < t.length) {\n t(i) += delta\n update(i | (i + 1), delta)\n }\n\n }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n val max = as.max\n val positionBuilders = Array.fill(max + 1){ new mutable.ArrayBuilder.ofInt }\n\n for (i <- as.indices) {\n positionBuilders(as(i)) += i\n }\n\n val positionsByA = positionBuilders.map(_.result)\n\n val bit = new BIT(Array.fill(n){ 0 })\n for (i <- 0 until n) bit.update(i, 1)\n\n var res = 0L\n var p = 0\n var a = 1\n\n while (a <= max) {\n val positions = positionsByA(a)\n if (positions.nonEmpty) {\n if (positions.head >= p) {\n val nextP = positions.last\n res += bit.rangeQuery(p, nextP)\n p = nextP\n for (pos <- positions) {\n bit.update(pos, -1)\n }\n } else {\n var nextP = p\n for (pos <- positions) {\n if (pos < p) nextP = pos\n }\n res += bit.rangeQuery(0, nextP)\n res += bit.rangeQuery(p, n - 1)\n p = nextP\n for (pos <- positions) {\n bit.update(pos, -1)\n }\n }\n }\n a += 1\n }\n\n println(res)\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n class BIT(src: Array[Long]) {\n\n private val t = Array.fill(src.length) { 0L }\n\n for (i <- src.indices) update(i, src(i))\n\n def query(r: Int, acc: Long = 0): Long =\n if (r < 0) acc else query((r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(l: Int, r: Int) = query(r) - query(l - 1)\n\n def update(i: Int, delta: Long): Unit =\n if (i < t.length) {\n t(i) += delta\n update(i | (i + 1), delta)\n }\n\n }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n val max = as.max\n val positionBuilders = Array.fill(max + 1){ new mutable.ArrayBuilder.ofInt }\n\n for (i <- as.indices) {\n positionBuilders(as(i)) += i\n }\n\n val positionsByA = positionBuilders.map(_.result)\n\n val bit = new BIT(Array.fill(n){ 0 })\n for (i <- 0 until n) bit.update(i, 1)\n\n var res = 0L\n var pos = 0\n var a = 1\n\n while (a <= max) {\n val positions = positionsByA(a)\n if (positions.nonEmpty) {\n var nextP = pos\n if (positions.head >= pos) {\n nextP = positions.last\n res += bit.rangeQuery(pos, nextP)\n } else {\n for (p <- positions) {\n if (p < pos) nextP = p\n }\n res += bit.rangeQuery(pos, n - 1) + bit.query(nextP)\n }\n for (p <- positions) {\n bit.update(p, -1)\n }\n pos = nextP\n }\n a += 1\n }\n\n println(res)\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\nobject E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n class BIT(src: Array[Long]) {\n\n private val t = Array.fill(src.length) { 0L }\n\n for (i <- src.indices) update(i, src(i))\n\n def query(r: Int, acc: Long = 0): Long =\n if (r < 0) acc else query((r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(l: Int, r: Int) = query(r) - query(l - 1)\n\n def update(i: Int, delta: Long): Unit =\n if (i < t.length) {\n t(i) += delta\n update(i | (i + 1), delta)\n }\n\n }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n val max = as.max\n val positionBuilders = Array.fill(max + 1){ new mutable.ArrayBuilder.ofInt }\n\n for (i <- as.indices) {\n positionBuilders(as(i)) += i\n }\n\n val positionsByA = positionBuilders.map(_.result)\n\n val bit = new BIT(Array.fill(n){ 0 })\n for (i <- 0 until n) bit.update(i, 1)\n\n var res = 0L\n var pos = 0\n var a = 1\n\n while (a <= max) {\n val positions = positionsByA(a)\n if (positions.nonEmpty) {\n var nextP = pos\n if (positions.head >= pos) {\n nextP = positions.last\n res += bit.rangeQuery(pos, nextP)\n } else {\n for (pos <- positions) {\n if (pos < pos) nextP = pos\n }\n res += bit.rangeQuery(pos, n - 1) + bit.query(nextP)\n }\n for (pos <- positions) {\n bit.update(pos, -1)\n }\n pos = nextP\n }\n a += 1\n }\n\n println(res)\n}\n"}], "src_uid": "68987c2618285686aa9b505e0a3d8230"} {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, s) = readInts(2)\n val as, bs = readInts(n)\n\n if (as(0) == 1 && as(s - 1) == 1) println(\"YES\")\n else if (as(0) == 1 && bs(s - 1) == 1) {\n if ((s until n).exists(i => as(i) == 1 && bs(i) == 1)) println(\"YES\")\n else println(\"NO\")\n } else println(\"NO\")\n\n Console.flush\n}\n", "positive_code": [{"source_code": "object A extends App {\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n val Y = \"YES\"\n val N = \"NO\"\n\n var isOk:Boolean = false\n\n def solve = {\n var n = nextInt\n var loc = nextInt\n\n var s1 = (for (i <- 0 until n) yield nextInt).toArray\n var s2 = (for (i <- 0 until n) yield nextInt).toArray\n\n if (loc == 1) {\n isOk = true\n } else if (s1(loc - 1) == 0 && s2(loc - 1) == 0) {\n isOk = false\n } else if (s1(0) == 0 && loc > 1) {\n isOk = false\n } else {\n // for \n for (i <- 0 until n) {\n // println(i + \",\" + n + \",\" + loc)\n if (s1(i) == 1) {\n if (i == loc - 1) {\n isOk = true\n } else if (s2(loc - 1) == 1 && i >= loc - 1 && s2(i) == 1) {\n isOk = true\n }\n }\n }\n }\n\n // println(s\"$n, $loc, $s1\")\n }\n\n solve\n println(if(isOk) Y else N)\n}"}, {"source_code": "object Main {\n import java.io.PrintStream\n\n def main(args: Array[String]): Unit = {\n val s = new Main()\n val ps = new PrintStream(Console.out)\n Console.withOut(ps) {\n s.solve()\n }\n ps.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n import scala.Console\n\n val MOD = 1000000007\n\n def solve(): Unit = {\n val N, S = ni()\n val A, B = na(N) map (_ == 1)\n\n def openABAfter = {\n S until N exists { i =>\n A(i) && B(i)\n }\n }\n\n val ok = A(0) && ((A(S - 1) || B(S - 1) && openABAfter))\n println(if (ok) \"YES\" else \"NO\")\n }\n\n\n class InputReader(reader: BufferedReader) {\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(Console.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "//package codeforce.mailru\n\nobject A {\n def main(args: Array[String]): Unit = {\n val row = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt)\n val n = row(0)\n val a = row(1)\n\n //println(s\"n a ${n} ${a}\")\n\n val first = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt)\n val second = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt)\n\n if (first(0) == 0 || (first(a - 1) == 0 && second(a - 1) == 0)) {\n println(\"NO\")\n }\n else if (first(a - 1) == 1){\n println(\"YES\")\n }\n else {\n var found = false\n (a - 1 until n).foreach{ mid =>\n if (first(mid) == 1 && second(mid) == 1) {\n found = true\n }\n }\n\n if (found) println(\"YES\") else println(\"NO\")\n }\n\n }\n}\n"}], "negative_code": [{"source_code": "object A {\n def main(args: Array[String]): Unit = {\n val row = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt)\n val n = row(0)\n val a = row(1)\n\n val first = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)\n\n val second = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)\n\n if (first(0) == 0 || (first(a - 1) == 0 && second(a - 1) == 0)) {\n println(\"NO\")\n }\n else {\n if (first.contains(a)) {\n println(\"YES\")\n }\n else {\n if (first.intersect(second).filter(_ >= a).size > 0) {\n println(\"YES\")\n }\n else {\n println(\"NO\")\n }\n }\n }\n }\n}\n"}, {"source_code": "//package codeforce.mailru\n\nobject A {\n def main(args: Array[String]): Unit = {\n val row = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt)\n val n = row(0)\n val a = row(1)\n\n val first = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)\n\n val second = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)\n\n println(first.mkString(\" \"))\n println(second.mkString(\" \"))\n\n if (!first.contains(0) || (!first.contains(a - 1) && !second.contains(a - 1))) {\n println(\"NO\")\n }\n else {\n if (first.contains(a)) {\n println(\"YES\")\n }\n else {\n if (first.intersect(second).filter(_ >= a).size > 0) {\n println(\"YES\")\n }\n else {\n println(\"NO\")\n }\n }\n }\n }\n}\n"}, {"source_code": "//package codeforce.mailru\n\nobject A {\n def main(args: Array[String]): Unit = {\n val row = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt)\n val n = row(0)\n val a = row(1)\n\n val first = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt)\n val second = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt)\n\n if (first(0) == 0 || (first(a - 1) == 0 && second(a - 1) == 0)) {\n println(\"NO\")\n }\n else if (first(a - 1) == 0){\n println(\"YES\")\n }\n else {\n var found = false\n (a - 1 until n).foreach{ mid =>\n if (first(mid) == 1 && second(mid) == 1) {\n found = true\n }\n }\n\n if (found) println(\"YES\") else println(\"NO\")\n }\n\n }\n}\n"}, {"source_code": "//package codeforce.mailru\n\nobject A {\n def main(args: Array[String]): Unit = {\n val row = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt)\n val n = row(0)\n val a = row(1)\n\n val first = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt).zipWithIndex.filter(_._1 >= 0).map(_._2)\n\n val second = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt).zipWithIndex.filter(_._1 >= 0).map(_._2)\n\n //println(first.mkString(\" \"))\n //println(second.mkString(\" \"))\n\n if (!first.contains(0) || (!first.contains(a - 1) && !second.contains(a - 1))) {\n println(\"NO\")\n }\n else {\n if (first.contains(a)) {\n println(\"YES\")\n }\n else {\n if (first.intersect(second).filter(_ >= a).size > 0) {\n println(\"YES\")\n }\n else {\n println(\"NO\")\n }\n }\n }\n }\n}\n"}, {"source_code": "//package codeforce.mailru\n\nobject A {\n def main(args: Array[String]): Unit = {\n val row = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt)\n val n = row(0)\n val a = row(1)\n\n val first = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt).zipWithIndex.filter(_._1 > 0).map(_._2)\n\n val second = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt).zipWithIndex.filter(_._1 > 0).map(_._2)\n\n //println(first.mkString(\" \"))\n //println(second.mkString(\" \"))\n\n if (!first.contains(0) || (!first.contains(a - 1) && !second.contains(a - 1))) {\n println(\"NO\")\n }\n else {\n if (first.contains(a)) {\n println(\"YES\")\n }\n else {\n if (first.intersect(second).filter(_ >= a).size > 0) {\n println(\"YES\")\n }\n else {\n println(\"NO\")\n }\n }\n }\n }\n}\n"}, {"source_code": "object A {\n def main(args: Array[String]): Unit = {\n val row = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt)\n val n = row(0)\n val a = row(1)\n\n val first = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)\n\n val second = scala.io.StdIn.readLine().split(\"\\\\s+\").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)\n\n if (!first.contains(0) == 0 || (!first.contains(a - 1) == 0 && !second.contains(a - 1) == 0)) {\n println(\"NO\")\n }\n else {\n if (first.contains(a)) {\n println(\"YES\")\n }\n else {\n if (first.intersect(second).filter(_ >= a).size > 0) {\n println(\"YES\")\n }\n else {\n println(\"NO\")\n }\n }\n }\n }\n}\n"}, {"source_code": "object A extends App {\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n val Y = \"YES\"\n val N = \"NO\"\n\n var isOk:Boolean = false\n\n def solve = {\n var n = nextInt\n var loc = nextInt\n\n var s1 = (for (i <- 0 until n) yield nextInt).toArray\n var s2 = (for (i <- 0 until n) yield nextInt).toArray\n\n if (loc == 1) {\n isOk = true\n } else if (s1(0) == 0 && loc > 1) {\n isOk = false\n } else {\n // for \n for (i <- 0 until n) {\n // println(i + \",\" + n + \",\" + loc)\n if (s1(i) == 1) {\n if (i == loc - 1) {\n isOk = true\n } else if (s2(loc - 1) == 1) {\n isOk = true\n }\n }\n }\n }\n\n // println(s\"$n, $loc, $s1\")\n }\n\n solve\n println(if(isOk) Y else N)\n}"}, {"source_code": "object A extends App {\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n val Y = \"YES\"\n val N = \"NO\"\n\n var isOk:Boolean = false\n\n def solve = {\n var n = nextInt\n var loc = nextInt\n\n var s1 = (for (i <- 0 until n) yield nextInt).toArray\n var s2 = (for (i <- 0 until n) yield nextInt).toArray\n\n if (loc == 1) {\n isOk = true\n } else if (s1(0) == 0 && loc > 1) {\n isOk = false\n } else {\n // for \n for (i <- 0 until n) {\n // println(i + \",\" + n + \",\" + loc)\n if (s1(i) == 1) {\n if (i == loc - 1) {\n isOk = true\n }\n }\n if (s2(loc - 1) == 1 && i >= loc - 1 && s2(i) == 1) {\n isOk = true\n }\n }\n }\n\n // println(s\"$n, $loc, $s1\")\n }\n\n solve\n println(if(isOk) Y else N)\n}"}], "src_uid": "64b597a47106d0f08fcfad155e0495c3"} {"source_code": "object _977D extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val nums = io.read[Vector[Long]]\n val counts = nums.groupBy(identity).mapValues(_.size).toMutable\n\n val Some(first) = nums.find(i => !counts.contains(3*i) && (i%2 == 1 || !counts.contains(i/2)))\n\n val ans = Vector.iterate(first, nums.length) {i =>\n dec(counts, i)\n if(i%3 == 0 && counts.contains(i/3)) {\n i/3\n } else if (counts.contains(2*i)) {\n 2*i\n } else {\n throw new IllegalStateException(\"Cannot be here!\")\n }\n }\n\n io.writeAll(ans)\n }\n\n def dec[A](map: mutable.Map[A, Int], key: A) = {\n if (map(key) == 1) map.remove(key) else map(key) = map(key) - 1\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "\nobject problemA {\n import java.io.{BufferedReader, FileInputStream, InputStreamReader}\n import scala.collection.mutable.ArrayBuffer\n import scala.collection.mutable\n import scala.util.control.Breaks._\n import scala.collection.JavaConverters._\n\n val source = System.in\n implicit val reader = new BufferedReader(new InputStreamReader(source))\n\n def read()(implicit reader: BufferedReader): String = reader.readLine().split(\" \")(0)\n def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(\" \")\n def readString()(implicit reader: BufferedReader): String = reader.readLine()\n\n def main(args: Array[String]): Unit = {\n val n = read().toInt\n val a = readArray().map(_.toLong)\n\n val ch = Array.fill[Boolean](n)(true)\n val f = new Array[Long](n)\n var c = 0\n\n def solve(k: Int): Unit = {\n if (c == n) {\n f.foreach(p => print(s\"$p \"))\n return\n }\n\n for (i <- 0 until n if ch(i)) {\n if (a(k) % 3 == 0 && a(k) / 3 == a(i)) {\n f(c) = a(i)\n c += 1\n ch(i) = false\n solve(i)\n ch(i) = true\n c -= 1\n\n } else if (a(k) * 2 == a(i)) {\n f(c) = a(i)\n c += 1\n ch(i) = false\n solve(i)\n ch(i) = true\n c -= 1\n }\n }\n }\n\n for (i <- 0 until n) {\n f(c) = a(i)\n c += 1\n ch(i) = false\n solve(i)\n ch(i) = true\n c -= 1\n }\n }\n}\n"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = map(N)(_ => nl())\n \n def factorize(a: Long) = {\n var x = a\n \n var i = 0\n while(x % 2 == 0) {\n i += 1\n x /= 2\n }\n \n var j = 0\n while(x % 3 == 0) {\n j += 1\n x /= 3\n }\n \n (i, j, x)\n }\n \n def toNum(p: (Int, Int, Long)) = {\n pow(2, p._1) * pow(3, p._2) * p._3\n }\n \n val p = (A map factorize).sortBy(a => a._1 + a._2 * -1)\n val n = p map toNum\n out.println(n.mkString(\" \"))\n }\n\n def pow(x: Long, n: Long): Long = {\n n match {\n case 0 => 1\n case _ =>\n val r = pow(x * x, n / 2)\n if (n % 2 == 1) r * x else r\n }\n }\n \n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "object D977 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val arr = readLongs(n).toSet\n val res = ArrayBuffer.empty[Long]\n arr.exists { _start =>\n var start = _start\n res.clear()\n res.append(start)\n while (res.length != n && ((start % 3 == 0 && arr.contains(start / 3)) || (start <= (Long.MaxValue >> 1) && arr\n .contains(start * 2)))) {\n if (start % 3 == 0 && arr.contains(start / 3)) {\n res.append(start / 3)\n start /= 3\n } else {\n res.append(start * 2)\n start *= 2\n }\n }\n res.length == n\n }\n\n out.println(res.mkString(\" \"))\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [], "src_uid": "f9375003a3b64bab17176a05764c20e8"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\n\nobject C extends App {\n\n def solve(in: InputReader): Unit = {\n val sticks = new Array[Int](1000000)\n val t = in.nextInt\n val sb = StringBuilder.newBuilder\n val met = mutable.HashMap.empty[Int, Boolean]\n var x: Int = 0\n var y: Int = 0\n var a: Int = 0\n var b: Int = 0\n var n: Int = 0\n var count: Int = 0\n var cur: Int = 0\n\n for (_ <- 1 to t) {\n n = in.nextInt\n count = 0\n met.clear()\n for (_ <- 0 until n) {\n cur = in.nextInt\n if (met.getOrElse(cur, false)) {\n sticks.update(count, cur)\n count = count + 1\n met.update(cur, false)\n } else {\n met.update(cur, true)\n }\n }\n java.util.Arrays.sort(sticks, 0, count)\n x = sticks(0)\n y = sticks(1)\n for (i <- 0 until count - 1) {\n a = sticks(i)\n b = sticks(i + 1)\n if (x.toDouble / y.toDouble < a.toDouble / b.toDouble) {\n x = a\n y = b\n }\n }\n sb.append(x)\n sb.append(' ')\n sb.append(x)\n sb.append(' ')\n sb.append(y)\n sb.append(' ')\n sb.append(y)\n sb.append('\\n')\n }\n print(sb.toString())\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}\n\n", "positive_code": [{"source_code": "import java.util\n\nimport scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(t) = readInts(1)\n val res = new StringBuilder\n val counts = Array.fill(10001)(0)\n\n def getX(a: Int, b: Int): Double = {\n val p = 2d * (a + b)\n val s = a * b\n p * p / s\n }\n\n for (_ <- 1 to t) {\n val Array(n) = readInts(1)\n val as = readInts(n)\n\n var i = 0\n while (i < n) {\n counts(as(i)) = 0\n i += 1\n }\n\n i = 0\n val bsBuilder = new mutable.ArrayBuilder.ofInt\n while (i < n) {\n counts(as(i)) += 1\n if (counts(as(i)) == 2) bsBuilder += as(i)\n i += 1\n }\n val bs = bsBuilder.result().sorted\n\n i = 0\n var bestX = Double.PositiveInfinity\n var bestA = 0\n var bestB = 0\n while (i < bs.length) {\n val a = bs(i)\n if (counts(a) >= 4) {\n val x = getX(a, a)\n if (x < bestX) {\n bestX = x\n bestA = a\n bestB = a\n }\n }\n var j = i + 1\n while (j < bs.length) {\n val b = bs(j)\n val x = getX(a, b)\n if (x < bestX) {\n bestX = x\n bestA = a\n bestB = b\n j = bs.length\n } else {\n j = bs.length\n }\n }\n i += 1\n }\n val aStr = bestA.toString\n val bStr = bestB.toString\n res ++= aStr\n res += ' '\n res ++= aStr\n res += ' '\n res ++= bStr\n res += ' '\n res ++= bStr\n res += '\\n'\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.result)\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\n\nobject C extends App {\n\n def solve(in: InputReader): Unit = {\n val sticks = new Array[Int](1000000)\n val t = in.nextInt\n val sb = StringBuilder.newBuilder\n val met = mutable.HashMap.empty[Int, Boolean]\n var x: Int = 0\n var y: Int = 0\n var a: Int = 0\n var b: Int = 0\n var n: Int = 0\n var count: Int = 0\n var cur: Int = 0\n\n for (_ <- 1 to t) {\n n = in.nextInt\n count = 0\n for (_ <- 0 until n) {\n cur = in.nextInt\n if (met.getOrElse(cur, false)) {\n sticks.update(count, cur)\n count = count + 1\n met.update(cur, false)\n } else {\n met.update(cur, true)\n }\n }\n java.util.Arrays.sort(sticks, 0, count)\n x = sticks(0)\n y = sticks(1)\n for (i <- 0 until count - 1) {\n a = sticks(i)\n b = sticks(i + 1)\n if (x.toDouble / y.toDouble < a.toDouble / b.toDouble) {\n x = a\n y = b\n }\n }\n sb.append(x)\n sb.append(' ')\n sb.append(x)\n sb.append(' ')\n sb.append(y)\n sb.append(' ')\n sb.append(y)\n sb.append('\\n')\n }\n print(sb.toString())\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}\n\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject C extends App {\n\n def solve(in: InputReader): Unit = {\n val met = mutable.HashMap.empty[Int, Int]\n val t = in.nextInt\n\n for (_ <- 1 to t) {\n met.clear()\n val n = in.nextInt\n val possibleSides = new ArrayBuffer[Int](n)\n for (_ <- 1 to n) {\n val cur = in.nextInt\n val times = met.getOrElse(cur, 0)\n if (times == 3) {\n printf(\"%d %d %d %d\\n\", cur, cur, cur, cur)\n return Unit\n }\n if (times % 2 == 1) {\n possibleSides.append(cur)\n }\n met.update(cur, times + 1)\n }\n val sorted = possibleSides.toVector.sorted\n var (x, y) = (sorted.head, sorted(1))\n sorted.sliding(2).foreach { case Seq(a, b) =>\n if (x.toDouble / y.toDouble < a.toDouble / b.toDouble) {\n x = a\n y = b\n }\n }\n printf(\"%d %d %d %d\\n\", x, x, y, y)\n }\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}\n\n"}], "src_uid": "fc54d6febbf1d91e9f0e6121f248d2aa"} {"source_code": "\nimport scala.math\nobject C {\n def main(args: Array[String]) {\n val s0 = readLine()\n val s1 = readLine();\n if (s1.length() != s0.length() || math.min(s1.length, s0.length) < 0 || (!s1.contains(\"1\") && s0.contains(\"1\")) || (!s0.contains(\"1\") && s1.contains(\"1\"))) {\n println(\"NO\")\n return;\n }\n println(\"YES\");\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val s1 = readLine()\n val s2 = readLine()\n \n val zero1 = s1.count(_ == '0') == s1.size\n val zero2 = s2.count(_ == '0') == s2.size\n \n if(s1.size != s2.size || zero1 != zero2) println(\"NO\")\n else println(\"YES\")\n }\n}"}, {"source_code": "object CF173Div2C {\n def main(args: Array[String]){\n val a = readLine\n val b = readLine\n val res = {\n if(a==b) \"YES\"\n else if(a.length != b.length) \"NO\"\n else if(!a.contains('1') || !b.contains('1')) \"NO\"\n else \"YES\"\n }\n println(res)\n }\n}"}], "negative_code": [{"source_code": "object C {\n def main(args: Array[String]) {\n val s0 = readLine()\n val s1 = readLine();\n if (s1.length() != s0.length() || (!s1.contains(\"1\") && s0.contains(\"1\"))) {\n println(\"NO\")\n return;\n }\n println(\"YES\");\n }\n}\n"}], "src_uid": "113ae625e67c8ea5ab07be44c3b58a8f"} {"source_code": "object A601 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val graph = Array.fill(n)(cu.Set.empty[Int])\n for (_ <- 1 to m) {\n val Array(x, y) = readInts(2).map(_ - 1)\n graph(x).add(y)\n graph(y).add(x)\n }\n val isTrainDone = graph(0).contains(n - 1)\n var res = -1\n\n def canVisit(top: Int) = {\n if (isTrainDone) {\n (0 until n).filter(_ != top).toSet.diff(graph(top))\n } else {\n graph(top)\n }\n }\n\n val q = cu.Queue.empty[Int]\n val vis = Array.fill(n)(false)\n val dist = Array.fill(n)(0)\n q.enqueue(0)\n var curr = 0\n while (q.nonEmpty && res == -1) {\n curr += 1\n val top = q.dequeue()\n val connections = canVisit(top)\n for (edge <- connections) {\n if (!vis(edge)) {\n vis(edge) = true\n dist(edge) = dist(top) + 1\n if (edge == n - 1 && res == -1) {\n res = dist(edge)\n } else {\n q.enqueue(edge)\n }\n }\n }\n }\n out.println(res)\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "object C{\n import scala.collection.mutable.Queue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val (n,m)=(nextInt,nextInt)\n val bd=Array.ofDim[Int](n,n)\n for(i<-0 until m){\n val i0=nextInt-1\n val j=nextInt-1\n bd(i0)(j)=1\n bd(j)(i0)=1\n }\n val con=1-bd(0)(n-1)\n //con is the long way\n val q=new Queue[(Int,Int)]\n q+=((0,0))\n \n\n var le= -1\n val visited=Array.ofDim[Int](n)\n breakable{\n while(!q.isEmpty){\n val (cn,cl)=q.dequeue\n \n \n for(i<-0 until n if i!=cn){\n if(bd(i)(cn)==con){\n if(i==n-1){\n le=cl+1\n break\n }else{\n if(visited(i)==0){\n q+=((i,cl+1))\n visited(i)=1\n }\n }\n }\n }\n }\n }\n out.println(le)\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "import scala.collection.mutable\n\nobject Solution extends App {\n\n def bfs(iron: Array[mutable.Set[Int]], isIron: Boolean): Int = {\n val n = iron.length - 1\n val marked = Array.ofDim[Boolean](n + 1)\n marked(1) = true\n var fringe = List(1)\n var count = 0\n while (fringe.nonEmpty) {\n var newFringe = List.empty[Int]\n fringe.foreach { i =>\n if (i == n)\n return count\n else {\n if (isIron) {\n iron(i).foreach{ j =>\n if (!marked(j)) {\n marked(j) = true\n newFringe ::= j\n }\n }\n } else {\n (1 to n).foreach { j =>\n if (!iron(i).contains(j) && !marked(j)) {\n marked(j) = true\n newFringe ::= j\n }\n }\n }\n }\n }\n count += 1\n fringe = newFringe\n }\n -1\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val iron: Array[mutable.Set[Int]] = Array.fill(n + 1) {scala.collection.mutable.Set.empty[Int]}\n (1 to m).foreach { _ =>\n val Array(u, v) = in.next().split(' ').map(_.toInt)\n iron(u) += v\n iron(v) += u\n }\n println(bfs(iron, !iron(n).contains(1)))\n}\n"}], "negative_code": [{"source_code": "object C{\n import scala.collection.mutable.Queue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val (n,m)=(nextInt,nextInt)\n val bd=Array.ofDim[Int](n,n)\n for(i<-0 until m){\n val i0=nextInt-1\n val j=nextInt-1\n bd(i0)(j)=1\n bd(j)(i0)=1\n }\n if(n==400 && m==42944){\n //I don't know why there is memory issue, testing\n out.println(\"reading finished\")\n return\n }\n val con=1-bd(0)(n-1)\n //con is the long way\n val q=new Queue[(Int,Int)]\n q+=((0,0))\n var le= -1\n val visited=Array.ofDim[Int](n)\n breakable{\n while(!q.isEmpty){\n val (cn,cl)=q.dequeue\n //out.println(cn+\" \"+cl)\n visited(cn)=1\n for(i<-0 until n if i!=cn){\n if(bd(i)(cn)==con){\n if(i==n-1){\n le=cl+1\n break\n }else{\n if(visited(i)==0){\n q+=((i,cl+1))\n }\n }\n }\n }\n }\n }\n out.println(le)\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object C{\n import scala.collection.mutable.Queue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val (n,m)=(nextInt,nextInt)\n val bd=Array.ofDim[Int](n,n)\n for(i<-0 until m){\n val i0=nextInt-1\n val j=nextInt-1\n bd(i0)(j)=1\n bd(j)(i0)=1\n }\n val con=1-bd(0)(n-1)\n //con is the long way\n val q=new Queue[(Int,Int)]\n q+=((0,0))\n if(n==400 && m==42944){\n //I don't know why there is memory issue, testing\n for(i<-0 until 400){\n q+=((i,i+1))\n }\n out.println(\"queue finished\")\n out.flush\n out.close\n return\n }\n\n var le= -1\n val visited=Array.ofDim[Int](n)\n breakable{\n while(!q.isEmpty){\n val (cn,cl)=q.dequeue\n //out.println(cn+\" \"+cl)\n visited(cn)=1\n for(i<-0 until n if i!=cn){\n if(bd(i)(cn)==con){\n if(i==n-1){\n le=cl+1\n break\n }else{\n if(visited(i)==0){\n q+=((i,cl+1))\n }\n }\n }\n }\n }\n }\n out.println(le)\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "src_uid": "fbfc333ad4b0a750f654a00be84aea67"} {"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val caves = readInt()\r\n val (power, _) = Array\r\n .fill(caves) {\r\n val Array(k, ak @ _*) = readLine().split(\" \").map(_.toInt)\r\n val power = ak.zipWithIndex.foldLeft(0) { case (power, (ai, i)) => power max (ai - i + 1) }\r\n (power, k)\r\n }\r\n .sorted\r\n .reduce[(Int, Int)] {\r\n case ((a, ak), (b, bk)) if (b > a + ak) => (b - ak, ak + bk)\r\n case ((a, ak), (b, bk)) => (a, ak + bk)\r\n }\r\n\r\n println(power)\r\n }\r\n\r\n}\r\n", "positive_code": [{"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport scala.util.Sorting.quickSort\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val writer = new PrintWriter(System.out)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {\r\n while (!st.hasMoreTokens) {\r\n st = new StringTokenizer(reader.readLine())\r\n }\r\n st.nextToken()\r\n }\r\n\r\n def readInt() = next.toInt\r\n def readLong() = next.toLong\r\n def readString() = next()\r\n def readArrayInt(n: Int = 0): Array[Int] = {\r\n if (n == 0)\r\n return reader.readLine().split(\" \").map(_.toInt)\r\n\r\n val a = new Array[Int](n)\r\n for (i <- 0 until n) {\r\n a(i) = readInt()\r\n }\r\n a\r\n }\r\n\r\n def pow(a: Int, b: Int): Long = {\r\n if (b == 0) return 1\r\n\r\n val rs = pow(a, b / 2)\r\n rs * rs * (if (b % 2 == 0) 1 else a)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b\r\n\r\n def root(u: Int, p: Array[Int]): Int = {\r\n if (p(u) < 0) return u\r\n p(u) = root(p(u), p)\r\n p(u)\r\n }\r\n\r\n def join(u: Int, v: Int, p: Array[Int]): Unit = {\r\n var x = root(u, p)\r\n var y = root(v, p)\r\n if (x == y) return\r\n\r\n if (p(y) < p(x)) {\r\n val t = x\r\n x = y\r\n y = t\r\n }\r\n p(x) += p(y)\r\n p(y) = x\r\n }\r\n\r\n def solve(t: Int = 0): Unit = {\r\n val n = readInt()\r\n\r\n val f = new Array[(Int, Int)](n)\r\n for (i <- 0 until n) {\r\n val k = readInt()\r\n var max = -Int.MaxValue\r\n for (j <- 0 until k) {\r\n val a = readInt()\r\n val b = a - j + 1\r\n max = Math.max(b, max)\r\n }\r\n f(i) = ((max, max + k))\r\n }\r\n\r\n quickSort[(Int, Int)](f)(Ordering.by[(Int, Int), Int](_._1))\r\n\r\n var l = f(0)._1\r\n var r = f(0)._2\r\n for (i <- 1 until n) {\r\n if (f(i)._1 <= r) {\r\n r += f(i)._2 - f(i)._1\r\n } else {\r\n l += f(i)._1 - r\r\n r = f(i)._2\r\n }\r\n }\r\n\r\n writer.println(l)\r\n }\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def main(args: Array[String]) {\r\n multiTest(solve)\r\n //solve()\r\n writer.flush()\r\n }\r\n}"}, {"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val caves = readInt()\r\n val (power, _) = Array\r\n .fill(caves) {\r\n val Array(k, ak @ _*) = readLine().split(\" \").map(_.toInt)\r\n val power = ak.zipWithIndex.foldLeft(0) { case (power, (ai, i)) => power max (ai - i + 1) }\r\n (power, k)\r\n }\r\n .sorted\r\n .reduce[(Int, Int)] { case ((a, ak), (b, bk)) => (a max (b - ak), ak + bk) }\r\n\r\n println(power)\r\n }\r\n\r\n}\r\n"}], "negative_code": [{"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val caves = readInt()\r\n val (power, _) = Array\r\n .fill(caves) {\r\n val Array(k, ak @ _*) = readLine().split(\" \").map(_.toInt)\r\n val power = ak.zipWithIndex.foldLeft(0) { case (power, (ai, i)) => power max (ai - i + 1) }\r\n (power, k)\r\n }\r\n .sorted\r\n .reduce[(Int, Int)] {\r\n case ((a, ak), (b, bk)) if (b > a + ak) => (b - ak, bk)\r\n case ((a, ak), (b, bk)) => (a, ak + bk)\r\n }\r\n\r\n println(power)\r\n }\r\n\r\n}\r\n"}, {"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val caves = readInt()\r\n val (power, _) = Array\r\n .fill(caves) {\r\n val Array(k, ak @ _*) = readLine().split(\" \").map(_.toInt)\r\n val power = ak.zipWithIndex.foldLeft(0) { case (power, (ai, i)) => power max (ai - i + 1) }\r\n (power, power + k)\r\n }\r\n .sorted\r\n .reduce[(Int, Int)] {\r\n case ((a1, a2), (b1, b2)) if (b1 > a2) => (b1 - (a2 - a1), b1 - (a2 - a1) + (b2 - b1))\r\n case ((a1, _), (_, b2)) => (a1, b2)\r\n }\r\n\r\n println(power)\r\n }\r\n\r\n}\r\n"}, {"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val caves = readInt()\r\n val (power, _) = Array\r\n .fill(caves) {\r\n val Array(k, ak @ _*) = readLine().split(\" \").map(_.toInt)\r\n val power = ak.zipWithIndex.foldLeft(0) { case (power, (ai, i)) => power max (ai - i + 1) }\r\n (power, power + k)\r\n }\r\n .sorted\r\n .reduce[(Int, Int)] {\r\n case ((_, a2), (b1, b2)) if (b1 > a2) => (b1, b2)\r\n case ((a1, _), (_, b2)) => (a1, b2)\r\n }\r\n\r\n println(power)\r\n }\r\n\r\n}\r\n"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport scala.util.Sorting.quickSort\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val writer = new PrintWriter(System.out)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {\r\n while (!st.hasMoreTokens) {\r\n st = new StringTokenizer(reader.readLine())\r\n }\r\n st.nextToken()\r\n }\r\n\r\n def readInt() = next.toInt\r\n def readLong() = next.toLong\r\n def readString() = next()\r\n def readArrayInt(n: Int = 0): Array[Int] = {\r\n if (n == 0)\r\n return reader.readLine().split(\" \").map(_.toInt)\r\n\r\n val a = new Array[Int](n)\r\n for (i <- 0 until n) {\r\n a(i) = readInt()\r\n }\r\n a\r\n }\r\n\r\n def pow(a: Int, b: Int): Long = {\r\n if (b == 0) return 1\r\n\r\n val rs = pow(a, b / 2)\r\n rs * rs * (if (b % 2 == 0) 1 else a)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b\r\n\r\n def root(u: Int, p: Array[Int]): Int = {\r\n if (p(u) < 0) return u\r\n p(u) = root(p(u), p)\r\n p(u)\r\n }\r\n\r\n def join(u: Int, v: Int, p: Array[Int]): Unit = {\r\n var x = root(u, p)\r\n var y = root(v, p)\r\n if (x == y) return\r\n\r\n if (p(y) < p(x)) {\r\n val t = x\r\n x = y\r\n y = t\r\n }\r\n p(x) += p(y)\r\n p(y) = x\r\n }\r\n\r\n def solve(t: Int = 0): Unit = {\r\n val n = readInt()\r\n\r\n val f = new Array[(Int, Int)](n)\r\n for (i <- 0 until n) {\r\n val k = readInt()\r\n var max = -Int.MaxValue\r\n for (j <- 0 until k) {\r\n val a = readInt()\r\n val b = a - j + 1\r\n max = Math.max(b, max)\r\n }\r\n f(i) = ((max, max + k))\r\n }\r\n\r\n quickSort[(Int, Int)](f)(Ordering.by[(Int, Int), Int](_._1))\r\n\r\n var l = f(0)._1\r\n var r = f(0)._2\r\n for (i <- 1 until n) {\r\n if (f(i)._1 <= r) {\r\n r += f(i)._2 - f(i)._1\r\n } else {\r\n l += f(i)._1 - r\r\n r += f(i)._2\r\n }\r\n }\r\n\r\n writer.println(l)\r\n }\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def main(args: Array[String]) {\r\n multiTest(solve)\r\n //solve()\r\n writer.flush()\r\n }\r\n}"}], "src_uid": "88488ff074bc25a6cf925c8a07a1d8c6"} {"source_code": "object _1088B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val n, k = io.read[Int]\n val as = io.read[IndexedSeq, Int](n).sorted.lift\n\n var i, s = 0\n val ans = mutable.ArrayBuffer.empty[Int]\n while(ans.length < k) {\n as(i) match {\n case None => ans.append(0)\n case Some(a) if a > s =>\n ans.append(a - s)\n s += a - s\n case _ =>\n }\n i += 1\n }\n\n io.writeAll(ans, separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": " import scala.io.StdIn\n\nobject B extends App {\n def readInts = StdIn.readLine().split(\" \").map(_.toInt)\n\n val Array(n, k) = readInts\n val A = readInts.distinct.sorted\n\n def solve() = {\n var i = 0\n var offset = 0\n\n (0 until k).map { _ =>\n while (i < A.length && (A(i) - offset) == 0) i += 1\n if (i >= A.length) 0\n else {\n val res = A(i) - offset\n offset = A(i)\n res\n }\n }\n }\n\n println(solve().mkString(\"\\n\"))\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val A = na(N)\n val nums = mutable.Set[Int]()\n REP(N) { i =>\n nums += A(i)\n }\n val sorted = nums.toSeq.sorted\n var sum = 0L\n val n = sorted.length\n REP(K) { i =>\n if (i < n) {\n val a = sorted(i) - sum\n sum += a\n out.println(a)\n } else {\n out.println(0)\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import java.io.PrintWriter\nimport scala.collection.SortedSet\n\nobject CF_525_2_B {\n\n def solve(n: Int, k: Int, as: Vector[Int]): Seq[Int] = {\n val xs = SortedSet(as: _*).toStream\n val xs0 = 0 #:: xs\n (xs0, xs).zipped.map((a, b) => b-a).take(k).padTo(k, 0)\n }\n\n def main(args: Array[String]) = {\n val io = new IO(System.in); import io._\n val solution = solve(int, int, {nextLine; intSeq()})\n val out = new PrintWriter(System.out)\n solution foreach out.println\n out.close()\n }\n\n\n\n\n\n/// boilerplate utility methods: ///\n import java.util.Scanner\n class IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def long() = sc.nextLong()\n def double() = sc.nextDouble()\n }\n\n object Utility {\n def intCeil(a: Int, b: Int) = (a - 1) / b + 1\n def longCeil(a: Long, b: Long) = (a - 1) / b + 1\n }\n}"}, {"source_code": "import java.io.PrintWriter\nimport scala.collection.SortedSet\n\nobject CF_525_2_B {\n\n def solve(n: Int, k: Int, as: Vector[Int]): Seq[Int] = {\n val xs = SortedSet(as: _*).toStream\n val xs0 = 0 #:: xs\n (xs0, xs).zipped.map((a, b) => b-a).take(k).padTo(k, 0)\n }\n\n def main(args: Array[String]) = {\n val io = new IO(System.in); import io._\n val solution = solve(int, int, {nextLine; intSeq()})\n val out = new PrintWriter(System.out)\n out.println(solution.mkString(\"\\n\"))\n out.close()\n }\n\n\n\n\n\n/// boilerplate utility methods: ///\n import java.util.Scanner\n class IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def long() = sc.nextLong()\n def double() = sc.nextDouble()\n }\n\n object Utility {\n def intCeil(a: Int, b: Int) = (a - 1) / b + 1\n def longCeil(a: Long, b: Long) = (a - 1) / b + 1\n }\n}"}, {"source_code": "import scala.collection.SortedSet\n\nobject CF_525_2_B {\n\n def solve(n: Int, k: Int, as: Vector[Int]): Unit = {\n // println in the middle of a function makes me feel sick\n // Just submitting this to test performance\n val out = new java.io.PrintWriter(System.out)\n val xs = SortedSet(as: _*).take(k).toList\n var last = 0\n for {\n x <- xs\n } {\n out.println(x - last)\n last = x\n }\n for {\n i <- xs.length until k\n } out.println(0)\n out.close()\n }\n \n def main(args: Array[String]) = {\n val io = new IO(System.in); import io._\n solve(int, int, {nextLine; intSeq()})\n }\n\n\n\n\n\n\n import java.util.Scanner\n class IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def long() = sc.nextLong()\n def double() = sc.nextDouble()\n }\n}"}], "negative_code": [{"source_code": "object CF_525_2_B {\n def solve(n: Int, k: Int, arr: Array[Int]): Vector[Int] = {\n // Going mutable for performance - blech\n if(arr.forall(_ == 0))\n Vector.fill(n)(0)\n else {\n var min = arr.filter(_ > 0).min\n var pass = 0\n var out = Vector.empty[Int]\n while (pass < k) {\n out :+= min\n var newMin = min\n var i = 0\n var allAreZero = true\n while (i < arr.length) {\n if (arr(i) > 0) {\n arr(i) -= min\n if (arr(i) > 0) {\n allAreZero = false\n if (arr(i) < newMin)\n newMin = arr(i)\n }\n }\n i += 1\n }\n if(allAreZero) min = 0 else min = newMin\n pass += 1\n }\n out\n }\n }\n \n def main(args: Array[String]) = {\n val io = new IO(System.in); import io._\n val solution = solve(int, int, {nextLine; intSeq()}.toArray)\n solution foreach println\n }\n\n\n\n\n\n/// boilerplate utility methods: ///\n import java.util.Scanner\n class IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def long() = sc.nextLong()\n def double() = sc.nextDouble()\n }\n\n object Utility {\n def intCeil(a: Int, b: Int) = (a - 1) / b + 1\n def longCeil(a: Long, b: Long) = (a - 1) / b + 1\n }\n}"}, {"source_code": "import scala.collection.SortedSet\n\nobject CF_525_2_B {\n\n def solve(n: Int, k: Int, as: Vector[Int]): Unit = {\n // println in the middle of a function makes me feel sick\n // Just submitting this to test performance\n val out = new java.io.PrintWriter(System.out)\n val xs = SortedSet(as: _*).take(k).toList\n var last = 0\n for {\n x <- xs\n } {\n out.println(x - last)\n last = x\n }\n for {\n i <- xs.length until k\n } out.println(0)\n }\n \n def main(args: Array[String]) = {\n val io = new IO(System.in); import io._\n solve(int, int, {nextLine; intSeq()})\n }\n\n\n\n\n\n\n import java.util.Scanner\n class IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def long() = sc.nextLong()\n def double() = sc.nextDouble()\n }\n}"}, {"source_code": "import scala.collection.SortedSet\n\nobject CF_525_2_B {\n\n def solve(n: Int, k: Int, as: Vector[Int]): Unit = {\n // println in the middle of a function makes me feel sick\n val xs = as.sorted.take(k)\n var last = 0\n for {\n x <- xs\n } {\n println(x - last)\n last = x\n }\n for {\n i <- xs.length until k\n } println(0)\n }\n \n def main(args: Array[String]) = {\n val io = new IO(System.in); import io._\n solve(int, int, {nextLine; intSeq()})\n }\n\n\n\n\n\n\n import java.util.Scanner\n class IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def long() = sc.nextLong()\n def double() = sc.nextDouble()\n }\n}"}, {"source_code": "import java.io.PrintWriter\nimport scala.collection.SortedSet\n\nobject CF_525_2_B {\n\n def solve(n: Int, k: Int, as: Vector[Int]): Seq[Int] = {\n val xs = SortedSet(as: _*).toStream\n val xs0 = 0 #:: xs\n (xs0, xs).zipped.map((a, b) => b-a).take(k).padTo(k, 0)\n }\n\n def main(args: Array[String]) = {\n val io = new IO(System.in); import io._\n val solution = solve(int, int, {nextLine; intSeq()})\n val out = new PrintWriter(System.out)\n solution foreach out.println\n }\n\n\n\n\n\n/// boilerplate utility methods: ///\n import java.util.Scanner\n class IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def long() = sc.nextLong()\n def double() = sc.nextDouble()\n }\n\n object Utility {\n def intCeil(a: Int, b: Int) = (a - 1) / b + 1\n def longCeil(a: Long, b: Long) = (a - 1) / b + 1\n }\n}"}, {"source_code": "import scala.collection.SortedSet\n\nobject CF_525_2_B {\n\n def solve(n: Int, k: Int, as: Vector[Int]): Unit = {\n // println in the middle of a function makes me feel sick\n val xs = SortedSet(as: _*).take(k).toList\n var last = 0\n for {\n x <- xs\n } {\n println(x - last)\n last = x\n }\n for {\n i <- xs.length to k\n } println(0)\n }\n \n def main(args: Array[String]) = {\n val io = new IO(System.in); import io._\n solve(int, int, {nextLine; intSeq()})\n }\n\n\n\n\n\n/// boilerplate utility methods: ///\n import java.util.Scanner\n class IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def long() = sc.nextLong()\n def double() = sc.nextDouble()\n }\n\n object Utility {\n def intCeil(a: Int, b: Int) = (a - 1) / b + 1\n def longCeil(a: Long, b: Long) = (a - 1) / b + 1\n }\n}"}, {"source_code": "object CF_525_2_B {\n def solve(n: Int, k: Int, xs: Vector[Int], out: Vector[Int] = Vector.empty): Vector[Int] = k match {\n case 0 => out\n case k => {\n val m = xs.min\n solve(n, k - 1, xs.map(_-m), out :+ m)\n }\n }\n \n def main(args: Array[String]) = {\n val io = new IO(System.in); import io._\n val solution = solve(int, int, {nextLine; intSeq()})\n solution foreach println\n }\n\n\n\n\n\n/// boilerplate utility methods: ///\n import java.util.Scanner\n class IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def long() = sc.nextLong()\n def double() = sc.nextDouble()\n }\n\n object Utility {\n def intCeil(a: Int, b: Int) = (a - 1) / b + 1\n def longCeil(a: Long, b: Long) = (a - 1) / b + 1\n }\n}"}], "src_uid": "0f100199a720b0fdead5f03e1882f2f3"} {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val ab = readIntLine()\n println(calc(ab.head, ab.last))\n }\n }\n\n def calc(a: Int, b: Int) = {\n val min = math.min(a, b)\n val max = math.max(a, b)\n val diff = max - min\n val diffMoney = diff\n val rest = min - diff\n if (rest < 0) min else diffMoney + rest / 3 * 2 + (if (rest % 3 == 2) 1 else 0)\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n// def printArray[T](arr: Array[T]): Unit = {\n// val str = new StringBuilder()\n// str.addAll((if (arr.head == -1) 0 else arr.head).toString)\n// // print(arr(0))\n// for (i <- 1 until arr.length) {\n// str.addAll(\" \" + (if (arr(i) == -1) 0 else arr(i)))\n// }\n// println(str)\n// }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n", "positive_code": [{"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b) = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n\n val ans = a min b min ((a + b) / 3)\n\n println(ans)\n }\n}\n"}, {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b) = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n\n val t2 = a min ((2 * b - a) / 3)\n val t1 = (a - t2) / 2\n\n val ans = t1 + t2\n\n println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val ab = readIntLine()\n println(calc(ab.head, ab.last))\n }\n }\n\n def calc(a: Int, b: Int) = {\n val min = math.min(a, b)\n val max = math.max(a, b)\n val diff = max - min\n val diffMoney = diff\n val rest = min - diff\n if (rest < 0) min else diffMoney + rest / 3 * 2\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n// def printArray[T](arr: Array[T]): Unit = {\n// val str = new StringBuilder()\n// str.addAll((if (arr.head == -1) 0 else arr.head).toString)\n// // print(arr(0))\n// for (i <- 1 until arr.length) {\n// str.addAll(\" \" + (if (arr(i) == -1) 0 else arr(i)))\n// }\n// println(str)\n// }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}, {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b) = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n val t1 = (b - a) min a\n val (a1, b1) = (a - t1, b - 2 * t1)\n val t2 = 2 * a1 / 3\n val (a2, b2) = (a1 - t2 / 2 * 3, b1 - t2 / 2 * 3)\n val t3 = a2 min (b2 / 2)\n\n val ans = t1 + t2 + t3\n\n println(ans)\n }\n}\n"}], "src_uid": "8bbec86e427e26158393bbfbf1a067fe"} {"source_code": "import scala.io.StdIn\n\nobject F {\n\n def check(s: String) = {\n val pairs = s zip s.tail\n (pairs.count { case (a, b) => a == b && a == '0'},\n pairs.count { case (a, b) => a != b},\n pairs.count { case (a, b) => a == b && a == '1'})\n }\n\n def solution(n00: Int, n01: Int, n11: Int): String = {\n if (n01 == 0)\n if (n00 == 0)\n Seq.fill(n11 + 1)(\"1\")\n else // n11 == 0\n Seq.fill(n00 + 1)(\"0\")\n else {\n val s01 = Stream.continually(Seq(\"0\", \"1\")).flatten.take(n01 - 1).toSeq\n val s00 = Seq.fill(n00 + 1)(\"0\")\n val s11 = Seq.fill(n11 + 1)(\"1\")\n s01 ++ (if (n01 % 2 == 1) s00 ++ s11 else s11 ++ s00)\n }\n }\n .mkString(\"\")\n\n def main(args: Array[String]): Unit = {\n for (_ <- (0 until StdIn.readLine.toInt)) {\n val Seq(n00, n01, n11) = StdIn.readLine.split(\" \").toSeq.map(_.toInt)\n println(F.solution(n00, n01, n11))\n }\n }\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C640B(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t =ni()\n REP(t) { _ =>\n val n0 = ni()\n val n1 = ni()\n val n2 = ni()\n\n val sb = new StringBuilder\n if(n1 > 0) {\n REP(n1+1) { i =>\n if(i%2 == 0) sb.append(\"1\")\n else sb.append(\"0\")\n }\n sb.insert(1, (0 until n0 map(_ => '0')).mkString(\"\"))\n sb.insert(0, (0 until n2 map(_ => '1')).mkString(\"\"))\n out.println(sb.toString())\n } else {\n if(n0 > 0) 0 to n0 foreach(_ => sb.append(\"0\"))\n if(n2 > 0) 0 to n2 foreach(_ => sb.append(\"1\"))\n out.println(sb.toString())\n }\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject F {\n\n def check(s: String) = {\n val pairs = s zip s.tail\n (pairs.count { case (a, b) => a == b && a == '0'},\n pairs.count { case (a, b) => a != b},\n pairs.count { case (a, b) => a == b && a == '1'})\n }\n\n def solution(n00: Int, n01: Int, n11: Int): String = {\n if (n01 == 0)\n if (n00 == 0)\n Seq.fill(n11 + 1)(\"1\")\n else // n11 == 0\n Seq.fill(n00 + 1)(\"0\")\n else {\n Seq.fill(n01 / 2)(\"01\").take(n01 - 1) ++\n Seq.fill(n00 + 1)(\"0\") ++\n Seq.fill(n11 + 1)(\"1\")\n }\n /*\n 01 1\n 01 0 2\n 01 01 3\n 01 010 4\n 01 0100 5\n */\n }\n .mkString(\"\")\n\n def main(args: Array[String]): Unit = {\n for (_ <- (0 until StdIn.readLine.toInt)) {\n val Seq(n00, n01, n11) = StdIn.readLine.split(\" \").toSeq.map(_.toInt)\n println(F.solution(n00, n01, n11))\n }\n }\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject F {\n\n def check(s: String) = {\n val pairs = s zip s.tail\n (pairs.count { case (a, b) => a == b && a == '0'},\n pairs.count { case (a, b) => a != b},\n pairs.count { case (a, b) => a == b && a == '1'})\n }\n\n def solution(n00: Int, n01: Int, n11: Int): String = {\n if (n01 == 0)\n if (n00 == 0)\n Seq.fill(n11 + 1)(\"1\")\n else // n11 == 0\n Seq.fill(n00 + 1)(\"0\")\n else {\n Seq.fill(n11 + 1)(\"1\") ++\n Seq.fill(n00 + 1)(\"0\") ++\n Seq.fill(n01 / 2)(\"01\").take(n01 - 1)\n }\n /*\n 01 1\n 01 0 2\n 01 01 3\n 01 010 4\n 01 0100 5\n */\n }\n .mkString(\"\")\n\n def main(args: Array[String]): Unit = {\n for (_ <- (0 until StdIn.readLine.toInt)) {\n val Seq(n00, n01, n11) = StdIn.readLine.split(\" \").toSeq.map(_.toInt)\n println(F.solution(n00, n01, n11))\n }\n }\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject F {\n\n def check(s: String) = {\n val pairs = s zip s.tail\n (pairs.count { case (a, b) => a == b && a == '0'},\n pairs.count { case (a, b) => a != b},\n pairs.count { case (a, b) => a == b && a == '1'})\n }\n\n def solution(n00: Int, n01: Int, n11: Int): String = {\n if (n01 == 0)\n if (n00 == 0)\n Seq.fill(n11 + 1)(\"1\")\n else // n11 == 0\n Seq.fill(n00 + 1)(\"0\")\n else {\n Seq.fill(n11)(\"1\") ++\n Seq.fill(n00)(\"0\") ++\n Seq.fill(n01 / 2)(\"01\").take(n01 - 1)\n }\n /*\n 01 1\n 01 0 2\n 01 01 3\n 01 010 4\n 01 0100 5\n */\n }\n .mkString(\"\")\n\n def main(args: Array[String]): Unit = {\n for (_ <- (0 until StdIn.readLine.toInt)) {\n val Seq(n00, n01, n11) = StdIn.readLine.split(\" \").toSeq.map(_.toInt)\n println(F.solution(n00, n01, n11))\n }\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C640B(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t =ni()\n REP(t) { _ =>\n val n0 = ni()\n val n1 = ni()\n val n2 = ni()\n\n val sb = new StringBuilder\n if(n1 > 0) {\n 0 until (n1+1)/2 foreach(_ => sb.append(\"10\"))\n 0 until n0 foreach(_ => sb.append(\"0\"))\n out.println((1 to n2 map(_ => \"1\")).mkString(\"\") + sb.toString())\n } else {\n if(n0 > 0) 0 to n0 foreach(_ => sb.append(\"0\"))\n if(n2 > 0) 0 to n2 foreach(_ => sb.append(\"1\"))\n out.println(sb.toString())\n }\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C640B(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t =ni()\n REP(t) { _ =>\n val n0 = ni()\n val n1 = ni()\n val n2 = ni()\n\n val sb = new StringBuilder\n if(n1 > 0) {\n 0 until (n1+1)/2 foreach(_ => sb.append(\"10\"))\n 0 until n0 foreach(_ => sb.append(\"0\"))\n out.println((1 until n2 map(_ => \"1\")).mkString(\"\") + sb.toString())\n } else {\n if(n0 > 0) 0 to n0 foreach(_ => sb.append(\"0\"))\n if(n2 > 0) 0 to n2 foreach(_ => sb.append(\"1\"))\n out.println(sb.toString())\n }\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C640B(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t =ni()\n REP(t) { _ =>\n val n0 = ni()\n val n1 = ni()\n val n2 = ni()\n\n val sb = new StringBuilder\n if(n1 > 0) {\n REP(n1+1) { i =>\n if(i%2 == 0) sb.append(\"1\")\n else sb.append(\"0\")\n }\n sb.insert(1, (0 until n0 map(_ => '0')).mkString(\"\"))\n sb.insert(0, (0 until n1 map(_ => '1')).mkString(\"\"))\n out.println(sb.toString())\n } else {\n if(n0 > 0) 0 to n0 foreach(_ => sb.append(\"0\"))\n if(n2 > 0) 0 to n2 foreach(_ => sb.append(\"1\"))\n out.println(sb.toString())\n }\n }\n }\n}\n"}], "src_uid": "4bbb078b66b26d6414e30b0aae845b98"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val x, y = ni()\n val ok = y <= x ||\n x == 2 && y == 3 ||\n x >= 4\n if (ok) out.println(\"YES\")\n else out.println(\"NO\")\n }\n }\n}", "positive_code": [{"source_code": "object B1257 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var t = readInt\n while (t > 0) {\n val Array(x, y) = readInts(2)\n val res = if (x == 1) {\n if (y == 1)\n \"YES\"\n else\n \"NO\"\n } else if (x == 2) {\n if (Array(1, 2, 3).contains(y))\n \"YES\"\n else\n \"NO\"\n } else if (x == 3) {\n if (Array(1, 2, 3).contains(y))\n \"YES\"\n else\n \"NO\"\n } else \"YES\"\n\n out.println(res)\n t -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [], "src_uid": "b3978805756262e17df738e049830427"} {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject B {\n def main(args: Array[String]): Unit = {\n val s = StdIn.readLine\n val seq = s.to[ArrayBuffer]\n val n = StdIn.readInt\n for (_ <- 1 to n) {\n var Array(l, r, k) = StdIn.readLine.split(\" \").map(_.toInt)\n val len = r - l + 1\n k %= len\n r -= 1\n l -= 1\n val nseq = new ArrayBuffer[Char]\n for (i <- 0 to r-l) {\n nseq += seq(l + (i - k + len) % len)\n }\n for (i <- l to r) {\n seq(i) = nseq(i - l)\n }\n }\n println(seq.mkString)\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject B {\n def main(args: Array[String]): Unit = {\n val seq = StdIn.readLine.toCharArray\n val n = StdIn.readInt\n (1 to n).foreach { _ =>\n var Array(l, r, k) = StdIn.readLine.split(\" \").map(_.toInt)\n val len = r - l + 1\n k %= len; r -= 1; l -= 1\n val tmp = Array.ofDim[Char](len)\n tmp.indices.foreach { i => tmp(i) = seq(l + (i - k + len) % len) }\n tmp.indices.foreach { i => seq(i+l) = tmp(i) }\n }\n println(seq.mkString)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next().toCharArray\n val m = in.next().toInt\n (1 to m).foreach { _ =>\n val Array(l, r, k) = in.next().split(' ').map(_.toInt)\n val distance = r - l + 1\n val leftover = k % distance\n val temp = Array.ofDim[Char](distance)\n (0 until distance).foreach { i =>\n temp((i + k) % distance) = str(i + l - 1)\n }\n temp.indices.foreach(i => str(i + l - 1) = temp(i))\n }\n println(str.mkString(\"\"))\n\n}\n"}, {"source_code": "object B598 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val in = read.toCharArray\n val Array(m) = readInts(1)\n for(_ <- 0 until m) {\n var Array(l, r, k) = readInts(3)\n k %= (r-l+1)\n l -= 1\n val temp = in.slice(l, r)\n val left = temp.takeRight(k).clone()\n val right = temp.take(r-l-k).clone()\n for(i <- 0 until k){\n in(l+i) = left(i)\n }\n for(i <- 0 until r-l-k){\n in(l+k+i) = right(i)\n }\n }\n println(in.mkString(\"\"))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by enxhell on 11/25/15.\n */\nobject StringShift {\n\n def gcd(a: Int,b: Int): Int = {\n if(b ==0) a else gcd(b, a%b)\n }\n\n def mod(v: Long, m: Int) = {\n if(v >= 0){\n v % m\n }else if((-v) % m == 0) {\n 0l\n }else{\n m - ((-v) % m)\n }\n }\n\n def processQuery(l: Int, r: Int, k: Int, str: Array[Char]) = {\n// println(l,r,k)\n// println(gcd(k,r-l+1))\n for(i <- 0 until gcd(k,r-l+1)){\n val tmp = str(i+l)\n var j : Long = i\n while(mod(j-k,r-l+1)!=i){\n// println(j,mod(j,r-l+1),mod(j-k, r-l+1))\n str((mod(j, r-l+1)+l).toInt) = str((mod(j-k, r-l+1)+l).toInt)\n j -= k\n }\n str((mod(j, (r-l+1))+l).toInt) = tmp\n }\n }\n\n def main(args: Array[String]): Unit = {\n val scanner = new Scanner(System.in)\n val str = scanner.next().toCharArray\n scanner.nextLine()\n\n val n = scanner.nextInt()\n (1 to n).foreach(x => processQuery(scanner.nextInt()-1, scanner.nextInt()-1, scanner.nextInt(), str))\n\n println(str.foldLeft(\"\")((r,c)=> r+c))\n\n }\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\n\n/**\n * Created by enxhell on 11/25/15.\n */\nobject StringShift {\n\n def gcd(a: Int,b: Int): Int = {\n if(b ==0) a else gcd(b, a%b)\n }\n\n def mod(v: Int, m: Int) = {\n if(v >= 0){\n v % m\n }else if((-v) % m == 0) {\n 0\n }else{\n m - ((-v) % m)\n }\n }\n\n def processQuery(l: Int, r: Int, k: Int, str: Array[Char]) = {\n// println(l,r,k)\n// println(gcd(k,r-l+1))\n for(i <- 0 until gcd(k,r-l+1)){\n val tmp = str(i+l)\n var j = i\n while(mod(j-k,r-l+1)!=i){\n// println(j,mod(j,r-l+1),mod(j-k, r-l+1))\n str(mod(j, r-l+1)+l) = str(mod(j-k, r-l+1)+l)\n j -= k\n }\n str(mod(j, (r-l+1))+l) = tmp\n }\n }\n\n def main(args: Array[String]): Unit = {\n val scanner = new Scanner(System.in)\n val str = scanner.next().toCharArray\n scanner.nextLine()\n\n val n = scanner.nextInt()\n (1 to n).foreach(x => processQuery(scanner.nextInt()-1, scanner.nextInt()-1, scanner.nextInt(), str))\n\n println(str.foldLeft(\"\")((r,c)=> r+c))\n\n }\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject B {\n def main(args: Array[String]): Unit = {\n val s = StdIn.readLine\n val seq = s.to[ArrayBuffer]\n val n = StdIn.readInt\n for (j <- 1 to n) {\n var Array(l, r, k) = StdIn.readLine.split(\" \").map(_.toInt)\n val len = r - l + 1\n k %= len\n r -= 1\n l -= 1\n val nseq = new ArrayBuffer[Char]\n for (i <- l to r) {\n nseq += seq((i - k + len) % len)\n }\n for (i <- l to r) {\n seq(i) = nseq(i - l)\n }\n }\n println(seq.mkString)\n }\n}\n"}], "src_uid": "501b60c4dc465b8a60fd567b208ea1e3"} {"source_code": "object C659 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n var Array(n, m) = readInts(2)\n val a = Array(0) ++ readInts(n).sorted\n val res = cu.ArrayBuffer.empty[Int]\n\n var curr = 0L\n var max = a.max + 1\n for(i <- 1 to n if m > 0) {\n if(a(i) > a(i-1)+1) {\n var x = a(i-1)+1\n while(x < a(i) && curr + x <= m) {\n res.append(x)\n m -= x\n x += 1\n }\n }\n }\n while(max + curr <= m) {\n res.append(max)\n m -= max\n max += 1\n }\n println(res.length)\n println(res.mkString(\" \"))\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _659C extends CodeForcesApp {\n override def apply(io: IO) = {\n var n, m = io[Int]\n val has = io[Set, Int](n)\n var ans = Vector.empty[Int]\n\n var t = 1\n while(m >= t) {\n if(!has(t)) {\n ans = ans :+ t\n m -= t\n }\n t += 1\n }\n\n io.+=(ans.length).appendNewLine().+=(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sum[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default\n }\n def memoize[I] = new {\n def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val newLine: String = \"\\n\"\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def appendNewLine(): this.type = {\n println()\n this\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn\nimport scala.collection.mutable.ListBuffer\n\nobject Main {\n def main(args: Array[String]) {\n val (n, m) = StdIn.readLine.split(\" \").map(_.toInt) match {\n case xy: Array[Int] => (xy(0), xy(1))\n }\n val a = StdIn.readLine.split(\" \").map(_.toInt).toSet\n var picks = new ListBuffer[Int]()\n var cost = 0\n var i = 1\n while (cost <= m) {\n // println(i, cost)\n if (!a.contains(i)) { // pick\n picks.append(i)\n cost += i\n }\n i += 1\n }\n val ans = picks.init.toList\n println(ans.length)\n println(ans.mkString(\" \"))\n }\n\n}\n\n"}, {"source_code": "import scala.collection.mutable.ListBuffer\n\nobject E {\n def main(args: Array[String]) {\n var Array(n, m) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val a = scala.io.StdIn.readLine.split(\" \").map(_.toInt).sorted\n var k = 1\n val res = ListBuffer[Int]()\n var t = a(0)\n var i = 0\n while (k <= m){\n if (k != t){\n res += k\n m -= k\n } else {\n i += 1\n if (i < a.length){\n t = a(i)\n }\n }\n k += 1\n }\n val rr = res.result()\n println(rr.length)\n println(rr.mkString(\" \"))\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n var Array(n, m) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt).toSet\n var result = List.empty[Int]\n var i = 1\n while (m >= i) {\n if (!data.contains(i)) {\n result ::= i\n m -= i\n }\n i += 1\n }\n println(result.length)\n println(result.mkString(\" \"))\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable.ListBuffer\n\nobject E {\n def main(args: Array[String]) {\n var Array(n, m) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val a = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n var suma = a.sum\n var k = 1\n val res = ListBuffer[Int]()\n var t = a(0)\n var i = 0\n while (k <= m){\n if (k != t){\n res += k\n m -= k\n } else {\n i += 1\n if (i < a.length){\n t = a(i)\n }\n }\n k += 1\n }\n val rr = res.result()\n println(rr.length)\n println(rr.mkString(\" \"))\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n var Array(n, m) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt).toSet\n var result = List.empty[Int]\n var i = 1\n while (m >= i) {\n if (!data.contains(i)) {\n result ::= i\n m -= i\n }\n i += 1\n }\n println(result.mkString(\" \"))\n}"}, {"source_code": "object C659 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n var Array(n, m) = readInts(2)\n val a = Array(0) ++ readInts(n).sorted\n val res = cu.ArrayBuffer.empty[Int]\n\n var curr = 0L\n var max = a.max + 1\n for(i <- 1 until n if m > 0) {\n if(a(i) > a(i-1)+1) {\n var x = a(i-1)+1\n while(x < a(i) && curr + x <= m) {\n res.append(x)\n m -= x\n x += 1\n }\n }\n }\n while(max + curr <= m) {\n res.append(max)\n m -= max\n max += 1\n }\n println(res.length)\n println(res.mkString(\" \"))\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "0318d4d5ea3425bf6506edeb1026f597"} {"source_code": "import scala.math.min\nimport scala.math.max\nimport scala.util.control.Breaks._\n\nimport java.io.BufferedReader\nimport java.io.IOException\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject A{\n\tdef main(args: Array[String]) = {\n\t\tvar br = new BufferedReader(new InputStreamReader(System.in));\n \tvar a = br.readLine().split(\" \")\n\t\tvar n: Int = a(0).toInt\n\t\tvar x: Int = a(1).toInt\n\t\tvar y: Int = a(2).toInt\n\t\tvar b = br.readLine().split(\" \")\n\t\tvar c: Array[Int] = new Array[Int](n)\n\t\tvar i = 0\n\t\tfor(i <- 0 to n-1)\n\t\t{\n\t\t\tc(i) = b(i).toInt\n\t\t}\n\t\tvar ans: Int = -1\n\t\tfor(i <- 0 to n-1)\n\t\t{\n\t\t\tvar f: Int = 0\n\t\t\tvar j: Int = 0\n\t\t\tfor(j <- max(0,i-x) to min(i+y,n-1) )\n\t\t\t{\n\t\t\t\tif(j!=i && c(i)>=c(j))\n\t\t\t\t\tf=1\n\t\t\t}\n\t\t\tif(f==0)\n\t\t\t{\n\t\t\t\tif(ans equals -1)\n\t\t\t\t\tans = i\n\t\t\t}\n\t\t}\n\t\tprintln(ans+1)\n\t}\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, X, Y = ni()\n val A = na(N)\n REP(N) { i =>\n var ok = true\n REP(X, 1) { j =>\n if (i - j >= 0) {\n ok &&= A(i) < A(i - j)\n }\n }\n REP(Y, 1) { j =>\n if (i + j < N) {\n ok &&= A(i) < A(i + j)\n }\n }\n if (ok) {\n out.println(i + 1)\n return\n }\n }\n }\n}"}, {"source_code": "object _1199A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val n, x, y = io.read[Int]\n val as = io.read[Vector, Int](n)\n\n val ans = as.indices find {i =>\n val a = as(i)\n (max(i - x, 0) until i).forall(j => a < as(j)) &&\n ((i+1) to min(i + y, n - 1)).forall(j => a < as(j))\n }\n\n io.write(ans.get+1)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "5e2a5ee02c1a2f35a52e76cde96463a3"} {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k) = readInts(2)\n val rooms = readLine\n\n var min = Int.MaxValue\n var left = 0\n\n while (rooms(left) == '1') left += 1\n var right = left\n var mid = left\n var cnt = 0\n\n while (cnt < k) {\n right += 1\n if (rooms(right) == '0') cnt += 1\n }\n\n def toLeft = mid - left\n def toRight = right - mid\n\n while (toLeft < toRight) {\n mid += 1\n if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))\n }\n while (mid < n && rooms(mid) == '1') mid += 1\n\n while (right < n) {\n if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))\n right += 1\n while (right < n && rooms(right) == '1') right += 1\n if (right < n) {\n left += 1\n while (rooms(left) == '1') left += 1\n if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))\n while (toLeft < toRight) {\n mid += 1\n if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))\n }\n while (mid < n && rooms(mid) == '1') mid += 1\n }\n }\n\n if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))\n\n println(min)\n}\n", "positive_code": [{"source_code": "object E {\n def main(args: Array[String]) {\n val Array(n, k) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val hotel = scala.io.StdIn.readLine.zipWithIndex\n val rooms = hotel.filter(_._1 == '0').map(_._2)\n var s = 0\n var e = k\n var x1 = 0\n var x2 = 1\n var zeros = 0\n var mmin = 100000\n while (s < rooms.length - k){\n while (!((2*rooms(x1) < rooms(s)+rooms(e)) && (2*rooms(x2) >= rooms(s)+rooms(e)))){\n x1 += 1\n x2 += 1\n }\n if ((rooms(e) - rooms(x1)) < mmin){\n mmin = rooms(e)-rooms(x1)\n }\n if ((rooms(x2) - rooms(s)) < mmin){\n mmin = rooms(x2) - rooms(s)\n }\n e += 1\n s += 1\n }\n println(mmin)\n }\n}"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k) = readInts(2)\n val rooms = readLine\n\n var min = Int.MaxValue\n var left = 0\n\n while (rooms(left) == '1') left += 1\n var right = left\n var mid = left\n var cnt = 0\n\n while (cnt < k) {\n right += 1\n if (rooms(right) == '0') cnt += 1\n }\n\n def toLeft = mid - left\n def toRight = right - mid\n\n while (toLeft < toRight || rooms(mid) == '1') mid += 1\n\n while (right < n) {\n if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))\n right += 1\n while (right < n && rooms(right) == '1') right += 1\n if (right < n) {\n left += 1\n if (rooms(mid) == '0') while (rooms(left) == '1') left += 1\n min = math.min(min, math.max(toLeft, toRight))\n while (toLeft < toRight) {\n mid += 1\n if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))\n }\n }\n }\n\n if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))\n\n println(min)\n}\n"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k) = readInts(2)\n val rooms = readLine\n\n var min = Int.MaxValue\n var left = 0\n\n while (rooms(left) == '1') left += 1\n var right = left\n var mid = left\n var cnt = 0\n\n while (cnt < k) {\n right += 1\n if (rooms(right) == '0') cnt += 1\n }\n\n def toLeft = mid - left\n def toRight = right - mid\n\n while (toLeft < toRight || rooms(mid) == '1') mid += 1\n\n while (right < n) {\n min = math.min(min, math.max(toLeft, toRight))\n right += 1\n while (right < n && rooms(right) == '1') right += 1\n if (right < n) {\n left += 1\n while (rooms(left) == '1') left += 1\n min = math.min(min, math.max(toLeft, toRight))\n while (toLeft < toRight || rooms(mid) == '1') mid += 1\n }\n }\n\n min = math.min(min, math.max(toLeft, toRight))\n\n println(min)\n}\n"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k) = readInts(2)\n val rooms = readLine\n\n var min = Int.MaxValue\n var left = 0\n\n while (rooms(left) == '1') left += 1\n var right = left\n var mid = left\n var cnt = 0\n\n while (cnt < k) {\n right += 1\n if (rooms(right) == '0') cnt += 1\n }\n\n def toLeft = mid - left\n def toRight = right - mid\n\n while (toLeft < toRight || rooms(mid) == '1') mid += 1\n\n while (right < n) {\n if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))\n right += 1\n while (right < n && rooms(right) == '1') right += 1\n if (right < n) {\n left += 1\n if (rooms(mid) == '0') while (rooms(left) == '1') left += 1\n min = math.min(min, math.max(toLeft, toRight))\n while (toLeft < toRight) {\n mid += 1\n if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))\n }\n while (mid < n && rooms(mid) == '1') mid += 1\n }\n }\n\n if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))\n\n println(min)\n}\n"}], "src_uid": "a5d1a96fd8514840062d747e6fda2c37"} {"source_code": "import java.util._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val b = new Array[Int](n)\n var max = Int.MinValue\n var min = Int.MaxValue\n for (i <- 0 until n) {\n b(i) = nextInt\n max = Math.max(max, b(i))\n min = Math.min(min, b(i))\n }\n var maxN = 0\n var minN = 0\n out.print(Math.abs(max - min) + \" \")\n for (i <- 0 until n) {\n if (b(i) == max) {\n maxN += 1\n }\n if (b(i) == min) {\n minN += 1\n }\n }\n if (max != min) {\n out.print(maxN.toLong * minN.toLong)\n } else {\n out.print((maxN.toLong * (maxN.toLong - 1)) / 2)\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n", "positive_code": [{"source_code": "import java.util.InputMismatchException\nimport java.io.InputStream\n\n/**\n * Created by hama_du on 2014/08/24.\n */\nobject ProblemB extends App {\n val in = new InputReader(System.in)\n\n val n = in.nextInt()\n val f = (0 until n).map(_ => in.nextInt())\n val min = f.min\n val max = f.max\n val minCount: Long = f.count(b => b == min)\n val maxCount: Long = f.count(b => b == max)\n if (min == max) {\n println(0 + \" \" + (1L * n * (n - 1) / 2))\n } else {\n println((max - min) + \" \" + minCount * maxCount)\n }\n}\n\nclass InputReader(stream: InputStream) {\n val buf = new Array[Byte](1024)\n var curChar = 0\n var numChars = 0\n\n def next(): Int = {\n if (numChars == -1)\n throw new InputMismatchException();\n if (curChar >= numChars) {\n curChar = 0;\n numChars = stream.read(buf);\n if (numChars <= 0) {\n -1;\n }\n }\n val res = buf(curChar)\n curChar += 1\n res\n }\n\n def nextLong(): Long = {\n var c = next()\n while (isSpaceChar(c)) {\n c = next()\n }\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = next()\n }\n var res = 0L\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c - '0'\n c = next()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextInt(): Int = {\n nextLong.toInt\n }\n\n def isSpaceChar(c: Int) = {\n c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n io.StdIn.readLine()\n sol(io.StdIn.readLine().split(' ').map(Integer.parseInt(_)))\n }\n\n def sol(bs: Array[Int]): Unit = {\n def extrema(nums: List[Int]): (Int, Int, Int, Int) = {\n ((nums.head, 1, nums.head, 1) /: nums.tail) { (e, b) =>\n val _min = math.min(e._1, b)\n val _max = math.max(e._3, b)\n val minCount = if (_min != e._1) 1 else if (b == _min) e._2 + 1 else e._2\n val maxCount = if (_max != e._3) 1 else if (b == _max) e._4 + 1 else e._4\n (_min, minCount, _max, maxCount)\n }\n }\n extrema(bs.toList) match {\n case (x, y, z, w) =>\n println(s\"${z-x} ${if (z == x) y.toLong * (y - 1) / 2 else y.toLong * w}\")\n }\n }\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 15.08.14.\n */\nobject B extends App {\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n val bs = Array.fill(n)(0L)\n (0 until n).foreach(i => bs(i) = nextLong)\n val sorted = bs.sorted\n val minBeauty = sorted(0)\n val maxBeauty = sorted(n - 1)\n var maxDiff = maxBeauty - minBeauty\n var minCount = 0L\n var maxCount = 0L\n while (minCount < n && sorted(minCount.toInt) == minBeauty) {\n minCount += 1L\n }\n while (maxCount < n && sorted(n - 1 - maxCount.toInt) == maxBeauty) {\n maxCount += 1L\n }\n val maxDiffCount = if(minBeauty == maxBeauty) n.toLong * (n.toLong - 1) / 2L else maxCount * minCount\n out.print(maxDiff + \" \" + maxDiffCount)\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}"}, {"source_code": "object main extends App with fastIO {\n \n val Array(n) = readLine split(\" \") map(_.toLong)\n var a = readLine split(\" \") map(_.toInt)\n \n val (max, min) = (a.max, a.min) \n val res = if (max == min) n * (n - 1) / 2 else \n a.count(_ == min).toLong * a.count(_ == max).toLong\n \n println((max - min) + \" \" + res) \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _459B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt)\n val max = a.max\n val min = a.min\n if (max == min) {\n println(\"%d %d\".format(0, 1L * a.length * (a.length - 1) / 2))\n } else {\n println(\"%d %d\".format(max - min, 1L * a.count(i => i == max) * a.count(i => i == min)))\n }\n}\n"}, {"source_code": "/**\n * Created by lurker on 2014. 8. 15..\n */\nobject CF261_2 extends App {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n val Array(n) = readInts(1)\n val b = readInts(n.toInt)\n\n val maxb = b.max\n val minb = b.min\n\n val nmax:Long = b.filter(_ == maxb).length\n val nmin:Long = b.filter(_ == minb).length\n\n val r:Long = maxb - minb\n val result = nmax * nmin\n\n val rcases:Long = if(maxb != minb){\n nmax * nmin\n } else {\n nmax * (nmax - 1) / 2L\n }\n println(s\"$r $rcases\")\n}\n"}, {"source_code": "object B459 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n\n val max = input.max\n val min = input.min\n\n val ways = if(min == max) {\n val count = input.count(_ == max).toLong\n (count*(count-1))/2L\n } else {\n input.count(_ == max).toLong * input.count(_ == min).toLong\n }\n\n println(s\"${max-min} $ways\")\n }\n}"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 05 May 2016\n */\nobject B459 extends App {\n\n val n: Int = scala.io.StdIn.readInt()\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n var min = Integer.MAX_VALUE\n var minCount = 1\n var max = 0\n var maxCount = 1\n a.foreach(b => {\n if (min > b) {\n min = b\n minCount = 1\n } else if (min == b) {\n minCount += 1\n }\n if (max < b) {\n max = b\n maxCount = 1\n } else if (max == b) {\n maxCount += 1\n }\n })\n\n print(max - min)\n print(\" \")\n if (max == min) {\n println(1L * maxCount * (maxCount - 1) / 2)\n } else {\n println(1L * maxCount * minCount)\n }\n\n}\n"}, {"source_code": "import java.util._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val b = new Array[Long](n)\n var max: Long = Long.MinValue\n var min: Long = Long.MaxValue\n for (i <- 0 until n) {\n b(i) = nextLong\n max = Math.max(max, b(i))\n min = Math.min(min, b(i))\n }\n var maxN: Long = 0L\n var minN: Long = 0L\n out.print(Math.abs(max - min) + \" \")\n for (i <- 0 until n) {\n if (b(i) == max) {\n maxN += 1\n }\n if (b(i) == min) {\n minN += 1\n }\n }\n if (max != min) {\n out.print(maxN * minN * 1L)\n } else {\n out.print((maxN * 1L * (maxN * 1L - 1L)) / 2L)\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.util.Sorting\n\nobject PashmakFlowers {\n \n def pashmakFlowers(inputA:Array[Int]):String = {\n Sorting.quickSort(inputA)\n val cnt:Int = inputA.length\n if (cnt>1){\n val small = inputA(0);\n val large = inputA(cnt-1)\n if (small == large){\n 0 + \" \" + cnt.toLong*(cnt-1).toLong/2\n }else{\n var sc=0\n while(inputA(sc)==small){\n sc = sc + 1\n }\n var lc=0\n while(inputA(cnt-1-lc)==large){\n lc = lc + 1\n }\n val comb:Long = sc.toLong * lc.toLong\n large-small + \" \" + comb\n }\n }else{\n \"Error Input: Input has less then 2 numbers\"\n }\n }\n \n def pashmakFlowers(num:Int, ln2:String):String = {\n val input = ln2.split(\" \");\n val inputA:Array[Int] = new Array(num);\n for (a<-1 to num){\n inputA(a-1)=input(a-1).toInt\n }\n pashmakFlowers(inputA)\n }\n def main(args: Array[String]) {\n val ln1:String = StdIn.readLine()\n val ln2:String = StdIn.readLine()\n val num = ln1.toInt\n println(pashmakFlowers(num, ln2))\n }\n\n\n}"}], "negative_code": [{"source_code": "/**\n * Created by lurker on 2014. 8. 15..\n */\nobject CF261_2 extends App {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n val Array(n) = readInts(1)\n val b = readInts(n.toInt)\n\n val maxb = b.max\n val minb = b.min\n\n val nmax = b.filter(_ == maxb).length\n val nmin = b.filter(_ == minb).length\n\n val r = maxb - minb\n val rcases = if(maxb != minb){\n nmax * nmin\n } else {\n nmax * (nmax - 1) / 2\n }\n println(s\"$r $rcases\")\n}\n"}, {"source_code": "/**\n * Created by lurker on 2014. 8. 15..\n */\nobject CF261_2 extends App {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n val Array(n) = readInts(1)\n val b = readInts(n.toInt)\n\n val maxb = b.max\n val minb = b.min\n\n val nmax = b.filter(_ == maxb).length\n val nmin = b.filter(_ == minb).length\n\n val r:Long = maxb - minb\n val result = nmax * nmin\n\n if(n==200000){\n println(s\"$maxb $minb $nmax $nmin $r $result\")\n println(result)\n }\n\n\n val rcases:Long = if(maxb != minb){\n nmax * nmin\n } else {\n nmax * (nmax - 1) / 2L\n }\n println(s\"$r $rcases\")\n}\n"}, {"source_code": "/**\n * Created by lurker on 2014. 8. 15..\n */\nobject CF261_2 extends App {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n val Array(n) = readInts(1)\n val b = readInts(n)\n\n val maxb = b.max\n val minb = b.min\n\n val nmax = b.filter(_ == maxb).length\n val nmin = b.filter(_ == minb).length\n\n val r = maxb - minb\n val rcases = nmax * nmin\n println(s\"$r $rcases\")\n}\n"}, {"source_code": "/**\n * Created by lurker on 2014. 8. 15..\n */\nobject CF261_2 extends App {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n val Array(n) = readInts(1)\n val b = readInts(n.toInt)\n\n val maxb = b.max\n val minb = b.min\n\n val nmax = b.filter(_ == maxb).length\n val nmin = b.filter(_ == minb).length\n\n val r:Long = maxb - minb\n\n val rcases:Long = if(maxb != minb){\n nmax * nmin\n } else {\n nmax * (nmax - 1) / 2L\n }\n println(s\"$r $rcases\")\n}\n"}, {"source_code": "/**\n * Created by lurker on 2014. 8. 15..\n */\nobject CF261_2 extends App {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n val Array(n) = readInts(1)\n val b = readInts(n.toInt)\n\n val maxb = b.max\n val minb = b.min\n\n val nmax = b.filter(_ == maxb).length\n val nmin = b.filter(_ == minb).length\n\n val r:Long = maxb - minb\n if(n==200000){\n println(s\"$maxb $minb $nmax $nmin $r\")\n }\n\n val rcases:Long = if(maxb != minb){\n nmax * nmin\n } else {\n nmax * (nmax - 1) / 2L\n }\n println(s\"$r $rcases\")\n}\n"}, {"source_code": "object B459 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n\n val max = input.max\n val min = input.min\n\n val ways = if(min == max) {\n val count = input.count(_ == max).toLong\n (count*count-1)/2L\n } else {\n input.count(_ == max).toLong * input.count(_ == min).toLong\n }\n\n println(s\"${max-min} $ways\")\n }\n}"}, {"source_code": "object B459 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n\n val max = input.max\n val min = input.min\n\n val ways = input.count(_ == max) * input.count(_ == min)\n\n println(s\"${max-min} $ways\")\n }\n}"}, {"source_code": "object B459 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n\n val max = input.max\n val min = input.min\n\n val ways = input.count(_ == max).toLong * input.count(_ == min).toLong\n\n println(s\"${max-min} $ways\")\n }\n}"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 05 May 2016\n */\nobject B459 extends App {\n\n val n: Int = scala.io.StdIn.readInt()\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n var min = Integer.MAX_VALUE\n var minCount = 1\n var max = 0\n var maxCount = 1\n a.foreach(b => {\n if (min > b) {\n min = b\n minCount = 1\n } else if (min == b) {\n minCount += 1\n }\n if (max < b) {\n max = b\n maxCount = 1\n } else if (max == b) {\n maxCount += 1\n }\n })\n\n print(max - min)\n print(\" \")\n println(1L * maxCount * minCount)\n\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 05 May 2016\n */\nobject B459 extends App {\n\n val n: Int = scala.io.StdIn.readInt()\n val a: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n var min = Integer.MAX_VALUE\n var minCount = 1\n var max = 0\n var maxCount = 1\n a.foreach(b => {\n if (min > b) {\n min = b\n minCount = 1\n } else if (min == b) {\n minCount += 1\n }\n if (max < b) {\n max = b\n maxCount = 1\n } else if (max == b) {\n maxCount += 1\n }\n })\n\n print(max - min)\n print(\" \")\n println(maxCount * minCount)\n\n}\n"}, {"source_code": "import java.util._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val b = new Array[Int](n)\n var max = Int.MinValue\n var min = Int.MaxValue\n for (i <- 0 until n) {\n b(i) = nextInt\n max = Math.max(max, b(i))\n min = Math.min(min, b(i))\n }\n var maxN = 0\n var minN = 0\n out.print((max - min) + \" \")\n for (i <- 0 until n) {\n if (b(i) == max) {\n maxN += 1\n }\n if (b(i) == min) {\n minN += 1\n }\n }\n if (max - min > 0) {\n out.print(maxN * minN * 1L)\n } else {\n out.print((maxN * 1L * (maxN * 1L - 1L)) / 2L)\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.util._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val b = new Array[Int](n)\n var max = Int.MinValue\n var min = Int.MaxValue\n for (i <- 0 until n) {\n b(i) = nextInt\n max = Math.max(max, b(i))\n min = Math.min(min, b(i))\n }\n var maxN = 0\n var minN = 0\n out.print(Math.abs(max - min) + \" \")\n for (i <- 0 until n) {\n if (b(i) == max) {\n maxN += 1\n }\n if (b(i) == min) {\n minN += 1\n }\n }\n if (max != min) {\n out.print(maxN * minN * 1L)\n } else {\n out.print((maxN * 1L * (maxN * 1L - 1L)) / 2L)\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.util._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val b = new Array[Int](n)\n var max = Int.MinValue\n var min = Int.MaxValue\n for (i <- 0 until n) {\n b(i) = nextInt\n max = Math.max(max, b(i))\n min = Math.min(min, b(i))\n }\n var maxN = 0\n var minN = 0\n out.print((max - min) + \" \")\n for (i <- 0 until n) {\n if (b(i) == max) {\n maxN += 1\n }\n if (b(i) == min) {\n minN += 1\n }\n }\n if (max - min > 0) {\n out.print(maxN * minN * 1L)\n } else {\n out.print(maxN * 1L * (maxN - 1) / 2L)\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.util.Sorting\n\nobject PashmakFlowers {\n \n def pashmakFlowers(inputA:Array[Int]):String = {\n Sorting.quickSort(inputA)\n val cnt:Int = inputA.length\n if (cnt>1){\n val small = inputA(0);\n val large = inputA(cnt-1)\n if (small == large){\n 0 + \" \" + cnt*(cnt-1)/2\n }else{\n var sc=0\n while(inputA(sc)==small){\n sc = sc + 1\n }\n var lc=0\n while(inputA(cnt-1-lc)==large){\n lc = lc + 1\n }\n large-small + \" \" + sc*lc\n }\n }else{\n \"Error Input: Input has less then 2 numbers\"\n }\n }\n \n def main(args: Array[String]) {\n val ln1:String = StdIn.readLine()\n val ln2:String = StdIn.readLine()\n val num = ln1.toInt\n val input = ln2.split(\" \");\n val inputA:Array[Int] = new Array(num);\n for (a<-1 to num){\n inputA(a-1)=input(a-1).toInt\n }\n println(pashmakFlowers(inputA))\n }\n\n\n}"}, {"source_code": "import scala.io.StdIn\nimport scala.util.Sorting\n\nobject PashmakFlowers {\n \n def pashmakFlowers(inputA:Array[Int]):String = {\n Sorting.quickSort(inputA)\n val cnt:Int = inputA.length\n if (cnt>1){\n val small = inputA(0);\n val large = inputA(cnt-1)\n if (small == large){\n 0 + \" \" + cnt*(cnt-1)/2\n }else{\n var sc=0\n while(inputA(sc)==small){\n sc = sc + 1\n }\n var lc=0\n while(inputA(cnt-1-lc)==large){\n lc = lc + 1\n }\n val comb:Long = sc.toLong * lc.toLong\n large-small + \" \" + comb\n }\n }else{\n \"Error Input: Input has less then 2 numbers\"\n }\n }\n \n def pashmakFlowers(num:Int, ln2:String):String = {\n val input = ln2.split(\" \");\n val inputA:Array[Int] = new Array(num);\n for (a<-1 to num){\n inputA(a-1)=input(a-1).toInt\n }\n pashmakFlowers(inputA)\n }\n def main(args: Array[String]) {\n val ln1:String = StdIn.readLine()\n val ln2:String = StdIn.readLine()\n val num = ln1.toInt\n println(pashmakFlowers(num, ln2))\n }\n\n\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n io.StdIn.readLine()\n sol(io.StdIn.readLine().split(' ').map(Integer.parseInt(_)))\n }\n\n def sol(bs: Array[Int]): Unit = {\n def extrema(nums: List[Int]): (Int, Int, Int, Int) = {\n ((nums.head, 1, nums.head, 1) /: nums.tail) { (e, b) =>\n val _min = math.min(e._1, b)\n val _max = math.max(e._3, b)\n val minCount = if (_min != e._1) 1 else if (b == _min) e._2 + 1 else e._2\n val maxCount = if (_max != e._3) 1 else if (b == _max) e._4 + 1 else e._4\n (_min, minCount, _max, maxCount)\n }\n }\n extrema(bs.toList) match {\n case (x, y, z, w) =>\n println(s\"${z-x} ${if (z == x) (if (y == 2) 1 else y.toLong*y/2) else y.toLong * w}\")\n }\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n io.StdIn.readLine()\n sol(io.StdIn.readLine().split(' ').map(Integer.parseInt(_)))\n }\n\n def sol(bs: Array[Int]): Unit = {\n def extrema(nums: List[Int]): (Int, Int, Int, Int) = {\n ((nums.head, 1, nums.head, 1) /: nums.tail) { (e, b) =>\n val _min = math.min(e._1, b)\n val _max = math.max(e._3, b)\n val minCount = if (_min != e._1) 1 else if (b == _min) e._2 + 1 else e._2\n val maxCount = if (_max != e._3) 1 else if (b == _max) e._4 + 1 else e._4\n (_min, minCount, _max, maxCount)\n }\n }\n extrema(bs.toList) match {\n case (x, y, z, w) =>\n println(s\"${z-x} ${if (z == x) (if (y == 2) 1 else y) else y.toLong * w}\")\n }\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n io.StdIn.readLine()\n sol(io.StdIn.readLine().split(' ').map(Integer.parseInt(_)))\n }\n\n def sol(bs: Array[Int]): Unit = {\n def extrema(nums: List[Int]): (Int, Int, Int, Int) = {\n ((nums.head, 1, nums.head, 1) /: nums.tail) { (e, b) =>\n val _min = math.min(e._1, b)\n val _max = math.max(e._3, b)\n val minCount = if (_min != e._1) 1 else if (b == _min) e._2 + 1 else e._2\n val maxCount = if (_max != e._3) 1 else if (b == _max) e._4 + 1 else e._4\n (_min, minCount, _max, maxCount)\n }\n }\n extrema(bs.toList) match {\n case (x,y,z,w) =>\n println(s\"${z-x} ${y*w}\")\n }\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n io.StdIn.readLine()\n sol(io.StdIn.readLine().split(' ').map(Integer.parseInt(_)))\n }\n\n def sol(bs: Array[Int]): Unit = {\n def extrema(nums: List[Int]): (Int, Int, Int, Int) = {\n ((nums.head, 1, nums.head, 1) /: nums.tail) { (e, b) =>\n val _min = math.min(e._1, b)\n val _max = math.max(e._3, b)\n val minCount = if (_min != e._1) 1 else if (b == _min) e._2 + 1 else e._2\n val maxCount = if (_max != e._3) 1 else if (b == _max) e._4 + 1 else e._4\n (_min, minCount, _max, maxCount)\n }\n }\n extrema(bs.toList) match {\n case (x,y,z,w) =>\n println(s\"${z-x} ${y.toLong*w.toLong}\")\n }\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n io.StdIn.readLine()\n sol(io.StdIn.readLine().split(' ').map(Integer.parseInt(_)))\n }\n\n def sol(bs: Array[Int]): Unit = {\n def extrema(nums: List[Int]): (Int, Int, Int, Int) = {\n ((nums.head, 1, nums.head, 1) /: nums.tail) { (e, b) =>\n val _min = math.min(e._1, b)\n val _max = math.max(e._3, b)\n val minCount = if (_min != e._1) 1 else if (b == _min) e._2 + 1 else e._2\n val maxCount = if (_max != e._3) 1 else if (b == _max) e._4 + 1 else e._4\n (_min, minCount, _max, maxCount)\n }\n }\n extrema(bs.toList) match {\n case (x, y, z, w) =>\n println(s\"${z-x} ${if (z == x) y else y.toLong * w}\")\n }\n }\n}"}, {"source_code": "object main extends App with fastIO {\n \n val Array(n) = readLine split(\" \") map(_.toInt)\n var a = readLine split(\" \") map(_.toInt)\n \n val (max, min) = (a.max, a.min) \n val res = if (max == min) n * (n - 1) / 2 else \n a.count(_ == min) * a.count(_ == max)\n \n println((max - min) + \" \" + res) \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}"}], "src_uid": "eb2d1072c5308d9ef686315a122d9d3c"} {"source_code": "object HelloWorld {\n def main (args: Array[String]) {\n val N = readInt\n val first = readInt\n var pred = 7-first\n var i = 0; \n var res = true\n while (i < N) {\n var s = readLine\n val tokens = s.split(\" \")\n val one = tokens(0).toInt\n val two = tokens(1).toInt\n if (!((one != pred) && (two != pred) && (7-one != pred) && (7-two != pred))) res = false \n i+=1;\n }\n if (res) println(\"YES\") else println(\"NO\")\n }\n }", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val top = in.next().toInt\n val Array(l, r) = in.next().split(' ').map(_.toInt)\n val res = (2 to n).foldLeft((7 - top, Set(l, r, 7 - l, 7 - r, top).size == 5)) {\n case ((s, false), _) => (s, false)\n case ((s, true), _) =>\n val Array(l, r) = in.next().split(' ').map(_.toInt)\n val set = Set(l, r, s, 7 - l, 7 - r)\n if (set.size < 5)\n (s, false)\n else {\n val nt = (1 to 6).find(i => !set.contains(i)).get\n (nt, true)\n }\n }\n if (res._2)\n println(\"YES\")\n else\n println(\"NO\")\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.immutable.Queue\nimport scala.util.Random\n\nobject P225A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt // the number of dice in the tower\n val X = sc.nextInt // the number on the top of the tower\n val AB = List.fill(N, 2)(sc.nextInt) // two side long faces-es\n\n def solve(): Unit = {\n\n @tailrec\n def loop(acc: Int, dices: List[List[Int]]): Unit = {\n dices match {\n case Nil => out.println(\"YES\")\n case List(x, y) :: ds => {\n val known = acc :: List(x, y, 7 - x, 7 - y)\n val rest = List.range(1, 7) diff known\n rest match {\n case r :: Nil => loop(r, ds)\n case _ => out.println(\"NO\")\n }\n }\n }\n }\n\n loop(X, AB)\n }\n\n solve\n out.close\n}\n \n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n def readLine = reader.readLine\n\n val n = readInt\n val x = readInt\n def ans = if((for(_ <- 1 to n) yield readInts.count(y => y == x || y == 7 - x)).sum == 0) \"YES\" else \"NO\"\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val n = readInt()\n val up = readInt()\n val a = (1 to n) map (_ => readLine() split (\" \") map (_.toInt))\n val s = Set[Int]() ++ (1 to 6)\n \n var low = 7 - up\n val r = a.foldLeft(true) { (ac, a0) =>\n val next = s - (a0(0), 7 - a0(0), a0(1), 7 - a0(1), low)\n if (next.size == 1) {\n low = next.toList(0)\n ac\n } else {\n false\n }\n }\n if (r) println(\"YES\")\n else println(\"NO\")\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val top = in.next().toInt\n val Array(l, r) = in.next().split(' ').map(_.toInt)\n val res = (2 to n).foldLeft((7 - top, Set(l, r, 7 - l, 7 - r, top).size == 5)) {\n case ((s, false), _) => (s, false)\n case ((s, true), _) =>\n val Array(l, r) = in.next().split(' ').map(_.toInt)\n val set = Set(l, r, s, 7 - l, s - r)\n if (set.size < 5)\n (s, false)\n else {\n val nt = (1 to 6).find(i => !set.contains(i)).get\n (nt, true)\n }\n }\n if (res._2)\n println(\"YES\")\n else\n println(\"NO\")\n}\n"}, {"source_code": "object HelloWorld {\n def main (args: Array[String]) {\n val N = readInt\n val first = readInt\n var pred = 7-first\n var i = 0; \n var res = true\n while (i < N) {\n var s = readLine\n val tokens = s.split(\" \")\n val one = tokens(0).toInt\n val two = tokens(1).toInt\n if (!(one != pred) && (two != pred) && (7-one != pred) && (7-two != pred)) res = false \n i+=1;\n }\n if (res) println(\"YES\") else println(\"NO\")\n }\n }"}], "src_uid": "2d6a1202139e1f77f32377224e1fe752"} {"source_code": "object main extends App with fastIO {\n \n var a = readLine split(\" \") map(_.toInt) \n println(readLine.foldLeft(0)((s, c) => s + a(c - '1'))) \n \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}", "positive_code": [{"source_code": "object BlackSquareGame {\n def main(args: Array[String]): Unit = {\n val A = readLine.split(\" \")\n val S = readLine\n var sum = 0\n S.foreach(c => {\n sum = sum + A(c.asDigit-1).toInt\n })\n println(sum)\n }\n\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _431 extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val a = (0 until 4).map(i => next.toInt).toArray\n val s = next\n val ans = s.map(i => a(i - '0' - 1)).sum\n println(ans)\n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val call = in.next().split(\" \").zipWithIndex.map {\n case(en, index) => (index + 1) -> en.toInt\n }.toMap\n println(in.next().map(t => call(t.asDigit)).sum)\n}\n"}, {"source_code": "//package codeblocks\nimport java.util.Scanner\nobject cf413A {\n\tdef main(args : Array[String]) : Unit = {\n\tval scn = new Scanner(System.in)\n\tval caroli :List[Int] = {for(i <- 1 to 4 ) yield scn.nextInt}.toList\n\tval seq:List[Int] = scn.next.toList.map(_-'0')\n\tvar sum =0\n\tseq.foreach(x=>sum+=caroli(x - 1))\n\tprintln(sum)\n\t\t\n\t}\n\t\n//\tdef getResult(seq:List[Int],caroli:List[Int]):Int = {\n//\t\tval (head,tail) = seq.splitAt(4)\n//\t\tif(head.isEmpty) 0\n//\t\telse{\n//\t\t\t\n//\t\t\tval place = getRightPlace(head,head.length)\n//\t\t\tif(place!=0)\n//\t\t\t{\n//\t\t\t\tval (shead,thead) = head splitAt place-1\n//\t\t\t\tcaroli(place-1)+getResult(shead:::thead.tail:::tail,caroli)\n//\t\t\t}\n//\t\t\telse \n//\t\t\t\t0\n//\n//\t\t}\n//\t}\n//\tdef getRightPlace(xs:List[Int],n:Int ):Int = {\n//\t\tif(n == 0) 0\n//\t\t\n//\t\tif(xs(n-1)==n) n \n//\t\telse getRightPlace(xs take n-1,n-1)\n//\t\t\n//\t}\n\n}"}, {"source_code": "object B {\n \n def main(args: Array[String]): Unit = {\n var a = readLine.split(\" \").map(_.toInt)\n var s = readLine\n var ans = 0;\n \n for (i <- 0 to s.length()-1)\n \tif (s.charAt(i)=='1')\n \t\tans = ans + a(0)\t\n \telse if (s.charAt(i)=='2')\n \t\tans = ans + a(1)\n \telse if (s.charAt(i)=='3')\n \t\tans = ans + a(2)\n \telse if (s.charAt(i)=='4')\n \t\tans = ans + a(3)\n println(ans) \n }\n\n}"}, {"source_code": "import java.util.Scanner\n\nobject ASquare extends App {\n\n val scanner = new Scanner(System.in)\n\n val cal = (0 until 4).map(i => scanner.nextInt())\n\n val in = scanner.next().map(_.toString.toInt)\n\n val res = in.foldLeft(0)((acc, i) => acc + cal(i - 1))\n\n println(res)\n\n}\n"}, {"source_code": "object A431 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val input = readInts(4)\n val strip = read\n println(strip.map(ch => input(ch - '1')).sum)\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject ASquare extends App {\n\n val scanner = new Scanner(System.in)\n\n val cal = (0 until 4).map(i => scanner.nextInt())\n\n val in = scanner.next().map(_.toString.toInt)\n\n val res = in.foldLeft(0)((acc, i) => acc + cal(i - 1))\n\n println(res)\n\n}"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by hama_du on 2014/05/22.\n */\nobject ProblemA extends App {\n val in = new Scanner(System.in)\n val table = Array(in.nextInt, in.nextInt, in.nextInt, in.nextInt)\n val s = in.next().toCharArray.foldLeft(0)((a, b) => a + table(b-'1'))\n println(s)\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-19.\n */\nobject A431 extends App{\n val sc = new Scanner(System.in)\n val a1, a2, a3, a4 = sc.nextInt()\n val input = sc.next()\n\n println(input.toCharArray.map {\n case '1' => a1\n case '2' => a2\n case '3' => a3\n case '4' => a4\n }.sum)\n}\n"}, {"source_code": "object A {\n def main(args: Array[String]): Unit = {\n val a: Array[Int] = new Array[Int](4)\n val words:Array[String] = scala.io.StdIn.readLine().split(\" \")\n for (i <- 0 to 3)\n a(i) = words(i).toInt\n val s = scala.io.StdIn.readLine()\n var res = 0\n val n = s.length()\n for (i <- 0 to n - 1) {\n val j = s.charAt(i).toInt - '1'\n res = res + a(j)\n }\n println(res)\n }\n}\n"}, {"source_code": "/**\n * Created by Amit on 5/21/2014.\n */\nobject Testing {\n def main (args: Array[String]) {\n val first = Console.readLine()\n val nums = first.split(\" \")\n val str = Console.readLine()\n var count = 0\n for(c <- str){\n count += nums(c-49).toInt\n }\n println(count)\n }\n}\n"}], "negative_code": [], "src_uid": "db9065d975878227a749083f0036a169"} {"source_code": "import scala.collection.mutable.Stack\nimport scala.collection.mutable.Queue\n\nobject Main {\n\n def main(args: Array[String]): Unit = {\n //val f = new java.io.File(\"/home/grigore/Documents/a.in\")\n var s = new java.util.Scanner(System.in)\n val (n, m) = (s.nextInt(), s.nextInt())\n if (n == 0 || m == 0)\n println(0)\n else {\n println(n+m-1)\n for (i <- 1 to n) \n println(i + \" \" + 1)\n for (i <- 2 to m)\n println(1 + \" \" + i)\n }\n \n }\n}", "positive_code": [{"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val m = nextInt\n val k = math.max(n, m) + math.min(n, m) - 1\n out.println(k)\n for (i <- 1 to math.max(n, m)) {\n if (n > m) {\n out.println(i + \" 1\")\n } else {\n out.println(\"1 \" + i)\n }\n }\n for (i <- 2 to math.min(n, m)) {\n if (n > m) {\n out.println(\"1 \" + i)\n } else {\n out.println(i + \" 1\")\n }\n }\n\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}, {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\n/**\n * @author kperikov\n */\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val m = nextInt\n val k = math.max(n, m) + math.min(n, m) - 1\n out.println(k)\n for (i <- 1 to math.max(n, m)) {\n if (n > m) {\n out.println(i + \" 1\")\n } else {\n out.println(\"1 \" + i)\n }\n }\n for (i <- 2 to math.min(n, m)) {\n if (n > m) {\n out.println(\"1 \" + i)\n } else {\n out.println(i + \" 1\")\n }\n }\n\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val Array(n, m) = readInts\n\n\n def main(a: Array[String]) {\n println(n + m - 1)\n for(i <- 1 to n) {\n println(i + \" 1\")\n }\n for(i <- 2 to m) {\n println(\"1 \" + i)\n }\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val nm = readLine().split(\" \").map(_.toInt)\n val n = nm(0)\n val m = nm(1)\n println(n + m - 1)\n for(i <- 1 to n) println(i + \" \" + 1)\n for(j <- 2 to m) println(1 + \" \" + j)\n }\n}"}, {"source_code": "//package round190.A\n\nobject A {\n\n def main(args: Array[String]): Unit = {\n val input = readLine.split(\" \")\n val n = input(0).toInt\n val m = input(1).toInt\n println (m + n - 1)\n for (i <- 1 to n) println(i + \" \" + 1)\n for (i <- 2 to m) println(1 + \" \" + i)\n }\n\n}"}, {"source_code": "object Dance {\n def main(args:Array[String]):Unit={\n val l=readLine().split(\" \").toList.map(_.toInt)\n val n=l(0)\n val m=l(1)\n println(n+m-1)\n for(i<-1 to m) println(1+\" \"+i)\n if(n>1) {for(k<-2 to n) println(k+\" \"+1)}\n }\n\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport scala.math._\n\nobject Main {\n\t\n\tdef main(args: Array[String]) { \n\t\tvar (n,m) = (in.rdInt,in.rdInt)\n\t\tprintln(n+m-1)\n\t\tfor (i <- 1 to max(n,m)) println(if (n>=m) i+\" 1\" else \"1 \"+i)\n\t\tfor (i <- 2 to min(n,m)) println(if (n>=m) \"1 \"+i else i+\" 1\")\n\t}\n\n\tobject in {\n\t\tval in = new BufferedReader(new InputStreamReader(System.in))\n\t\tvar st = new StringTokenizer(\"\")\n\n\t\tdef next : String = {\n\t\t\twhile (!st.hasMoreTokens) {\n\t\t\t\tval line = in.readLine\n\t\t\t\tif (line == null) return null\n\t\t\t\teat(line)\n\t\t\t}\n\t\t\tst.nextToken\n\t\t}\n\t\t\n\t\tdef FastReader = eat(\"\")\n\t\tdef eat(s : String) = st = new StringTokenizer(s)\n\t\tdef rdInt = next.toInt\n\t\tdef rdLong = next.toLong\n\t\tdef rdDouble = next.toDouble\n\t}\n\t\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _322A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val m = next.toInt\n println(n + m - 1)\n for (i <- 1 to n) println(i + \" \" + 1)\n for (j <- 2 to m) println(1 + \" \" + j)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val result = (1 to n).map(i => s\"$i 1\").toList ::: (2 to m).map(i => s\"1 $i\").toList\n println(result.size)\n println(result.mkString(\"\\n\"))\n}"}, {"source_code": "import java.util.Scanner\n\nobject CielAndDancing {\n\tdef main(args: Array[String]) {\n\t\tval in = new Scanner(System.in)\n\t\tval n = in.nextInt()\n\t\tval m = in.nextInt()\n\t\tprintln(m + n - 1)\n\t\tfor (j <- 1 to m) {\n\t\t\tprintln(\"1 \" + j.toString)\n\t\t}\n\t\tfor (i <- 2 to n) {\n\t\t\tprintln(i.toString + \" 1\")\n\t\t}\n\t}\n}\n"}, {"source_code": "object A extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m) = readInts\n\n println(n + m - 1)\n \n for (i <- 1 to n) println(i + \" \" + 1)\n for (j <- 2 to m) println(1 + \" \" + j)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P322A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, M = sc.nextInt\n val isSwapped = M < N\n val (n, m) = if (M < N) (M, N) else (N, M)\n\n val pairs = List.tabulate(m)(x => List(1, x + 1)) ++\n (2 to n).toList.map(List(_, 1))\n\n out.println(pairs.size)\n pairs foreach { p0 =>\n val p1 = if (isSwapped) p0.reverse else p0\n out.println(p1.mkString(\" \"))\n }\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ListBuffer\n\nobject R322_A extends App {\n\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val m = sc.nextInt()\n val as = process(n,m)\n println(as.size)\n as.foreach(a => {\n val (b,c)=a\n println(b + \" \" + c)\n })\n def process(n:Int,m:Int):List[(Int,Int)]={\n var ns = 1\n var ms = 1\n val res = new ListBuffer[(Int,Int)]\n res += ((ns,ms))\n while(ns != n || ms != m){\n if(ns==n){\n ms+=1 \n }else if (ms==m){\n ns+=1\n }else if(ns > ms){\n ms += 1\n } else {\n ns += 1\n }\n res += ((ns,ms))\n }\n res.toList\n }\n}"}], "negative_code": [{"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport scala.math._\n\nobject Main {\n\t\n\tdef main(args: Array[String]) { \n\t\tval (n,m) = (in.rdInt,in.rdInt)\n\t\tval k = min(n,m)\n\t\tprintln(k)\n\t\tfor (i <- 1 to k) println(i+\" \"+i)\n\t}\n\n\tobject in {\n\t\tval in = new BufferedReader(new InputStreamReader(System.in))\n\t\tvar st = new StringTokenizer(\"\")\n\n\t\tdef next : String = {\n\t\t\twhile (!st.hasMoreTokens) {\n\t\t\t\tval line = in.readLine\n\t\t\t\tif (line == null) return null\n\t\t\t\teat(line)\n\t\t\t}\n\t\t\tst.nextToken\n\t\t}\n\t\t\n\t\tdef FastReader = eat(\"\")\n\t\tdef eat(s : String) = st = new StringTokenizer(s)\n\t\tdef rdInt = next.toInt\n\t\tdef rdLong = next.toLong\n\t\tdef rdDouble = next.toDouble\n\t}\n\t\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport scala.math._\n\nobject Main {\n\t\n\tdef main(args: Array[String]) { \n\t\tval (n,m) = (in.rdInt,in.rdInt)\n\t\tval k = min(n,m)\n\t\tprintln(max(n,m))\n\t\tfor (i <- 1 to k) println(i+\" \"+i)\n\t\tfor (i <- k+1 to m) println(\"1 \" + i)\n\t\tfor (i <- k+1 to n) println(i + \" 1\")\n\t}\n\n\tobject in {\n\t\tval in = new BufferedReader(new InputStreamReader(System.in))\n\t\tvar st = new StringTokenizer(\"\")\n\n\t\tdef next : String = {\n\t\t\twhile (!st.hasMoreTokens) {\n\t\t\t\tval line = in.readLine\n\t\t\t\tif (line == null) return null\n\t\t\t\teat(line)\n\t\t\t}\n\t\t\tst.nextToken\n\t\t}\n\t\t\n\t\tdef FastReader = eat(\"\")\n\t\tdef eat(s : String) = st = new StringTokenizer(s)\n\t\tdef rdInt = next.toInt\n\t\tdef rdLong = next.toLong\n\t\tdef rdDouble = next.toDouble\n\t}\n\t\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val result = (1 to m).map(i => s\"$i 1\").toList ::: (2 to n).map(i => s\"1 $i\").toList\n println(result.size)\n println(result.mkString(\"\\n\"))\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P322A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, M = sc.nextInt\n val isSwapped = M < N\n val (n, m) = if (M < N) (M, N) else (N, M)\n\n val pairs = List.tabulate(M)(x => List(1, x + 1)) ++\n (2 to N).toList.map(List(_, 1))\n\n out.println(pairs.size)\n pairs foreach { p0 =>\n val p1 = if (isSwapped) p0.reverse else p0\n out.println(p1.mkString(\" \"))\n }\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P322A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, M = sc.nextInt\n\n val b0 = List.tabulate(N)(_ + 1).flatMap(i => List(i, i))\n val g0 = List.tabulate(M)(_ + 1).flatMap(i => List(i, i))\n\n val b = if (N < M) b0 else b0.tail\n val g = if (N < M) g0.tail else g0\n\n val pairs = (b, g).zipped.map(List(_, _))\n\n out.println(pairs.size)\n pairs foreach { p =>\n out.println(p.mkString(\" \"))\n }\n out.close\n}\n"}, {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\n/**\n * @author kperikov\n */\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val m = nextInt\n val k = math.max(n, m) + math.min(n, m) - 1\n out.println(k)\n for (i <- 1 to math.max(n, m)) {\n out.println(\"1 \" + i)\n }\n for (i <- 2 to math.min(n, m)) {\n out.println(i + \" 1\")\n }\n\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val nm = readLine().split(\" \").map(_.toInt)\n val n = nm(0)\n val m = nm(0)\n println(n + m - 1)\n for(i <- 1 to n) println(i + \" \" + 1)\n for(j <- 2 to m) println(1 + \" \" + j)\n }\n}"}, {"source_code": "object Dance {\n def main(args:Array[String]):Unit={\n val l=readLine().split(\" \").toList.map(_.toInt)\n val n=l(0)\n val m=l(1)\n println(n+m-1)\n for(i<-1 to m) println(1+\" \"+i)\n if(n>1) for(k<-2 to n) println(n+\" \"+1)\n }\n\n}"}], "src_uid": "14fc3a7fef44a02791aee62838c4c8c8"} {"source_code": "import java.io._\nimport java.nio.file._\nimport java.util.StringTokenizer\n \nimport scala.annotation.tailrec\nimport scala.+:\nimport scala.io.Codec\n \nobject Solution {\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)))\n val pw = new PrintWriter(System.out, false)\n \n val t = sc.nextInt()\n var i = 0\n for (i <- 0 to (t-1)) {\n Solver.solve(sc, pw, i)\n }\n pw.flush()\n }\n}\n \n/**\n * Actual solution\n */\nobject Solver {\n def solve(sc: Scanner, pw: PrintWriter, testcast: Int): Unit = {\n val n = sc.nextInt()\n val S = sc.next()\n .split('W').toSeq\n .filter(s => !s.isEmpty)\n .map(check _)\n .fold(true)((a, b) => a & b)\n S match {\n case true => pw.println(\"YES\")\n case false => pw.println(\"NO\")\n }\n }\n\n def check(s: String): Boolean = {\n s.distinct.length() > 1\n }\n}\n \n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n \n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n \n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n \n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}", "positive_code": [{"source_code": "import scala.io.StdIn\r\n\r\nobject Task4 extends App {\r\n sealed trait State\r\n case object Init extends State\r\n case object TerminateFail extends State\r\n case object WasBlue extends State\r\n case object WasRed extends State\r\n case object WasBlueAndRed extends State\r\n\r\n def getNextNum: Int = StdIn.readLine().toInt\r\n\r\n val inputSize = getNextNum\r\n\r\n for (_ <- 0 until inputSize) {\r\n getNextNum\r\n\r\n val chars = StdIn.readLine().toCharArray\r\n var pos = 0;\r\n var state: State = Init\r\n\r\n do {\r\n state match {\r\n case Init if chars(pos) == 'W' =>\r\n do {\r\n pos += 1\r\n } while (pos < chars.length && chars(pos) == 'W')\r\n pos -= 1\r\n\r\n case Init if chars(pos) == 'B' =>\r\n state = WasBlue\r\n case Init if chars(pos) == 'R' =>\r\n state = WasRed\r\n case WasBlue | WasRed if chars(pos) == 'W' =>\r\n state = TerminateFail\r\n case WasBlue if chars(pos) == 'B' => ()\r\n case WasBlue if chars(pos) == 'R' =>\r\n state = WasBlueAndRed\r\n case WasRed if chars(pos) == 'R' => ()\r\n case WasRed if chars(pos) == 'B' =>\r\n state = WasBlueAndRed\r\n case WasBlueAndRed if chars(pos) == 'B' || chars(pos) == 'R' =>\r\n state = Init\r\n do {\r\n pos += 1\r\n } while(pos < chars.length && chars(pos) != 'W')\r\n pos -= 1\r\n case WasBlueAndRed if chars(pos) == 'W' =>\r\n state = Init\r\n }\r\n\r\n pos += 1\r\n } while(state != TerminateFail && pos < chars.length)\r\n\r\n if (state == TerminateFail || state == WasRed || state == WasBlue) {\r\n println(\"NO\")\r\n } else {\r\n println(\"YES\")\r\n }\r\n\r\n\r\n }\r\n\r\n}\r\n"}], "negative_code": [], "src_uid": "3f284afb044c8a57a02cd015d06e0ef0"} {"source_code": "object A extends App {\r\n\r\n implicit final class StringOps(private val s: String) extends AnyVal {\r\n def isSquare: Boolean = {\r\n val (half, remainder) = (s.size / 2, s.size % 2)\r\n remainder == 0 && (0 until half).forall(i => s(i) == s(i + half))\r\n }\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val s = nextLine()\r\n\r\n s.isSquare match {\r\n case true => out.println(\"YES\")\r\n case false => out.println(\"NO\")\r\n }\r\n }\r\n\r\n out.flush()\r\n\r\n object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n private[this] def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object scala{\r\n def main(args: Array[String]): Unit = {\r\n val a = readLine.toInt\r\n (0 until a).foreach{\r\n _ =>\r\n val b = readLine.trim\r\n if(b.length%2 != 0) println(\"NO\")\r\n else{\r\n var i = 0\r\n while(i< b.length/2 && b(i) == b((b.length/2) + i)){ i += 1 }\r\n if(i < b.length/2) println(\"NO\")\r\n else println(\"YES\")\r\n }\r\n }\r\n }\r\n}"}], "negative_code": [{"source_code": "object scala{\r\n def main(args: Array[String]): Unit = {\r\n val a = readLine.toInt\r\n (0 until a).foreach{\r\n _ =>\r\n val b = readLine.trim\r\n if(b.length%2 != 0) print(\"NO\")\r\n else{\r\n var i = 0\r\n while(i< b.length/2 && b(i) == b((b.length/2) + i)){ i += 1 }\r\n if(i < b.length/2) print(\"NO\")\r\n else print(\"YES\")\r\n }\r\n }\r\n }\r\n}"}], "src_uid": "9640b7197bd7b8a59f29aecf104291e1"} {"source_code": "object TaskA extends App {\n val n = readInt()\n val l = (0 until n).map{\n _ => readLine()\n }.map{\n _.split(' ').map(_.toInt)\n }.map{\n a => {\n val Array(left, right) = a\n (left, right)\n }\n }\n val k = readInt()\n\n val resultSeq = l.dropWhile{\n case (first, last) => !(k >= first && k <= last)\n }\n\n println(resultSeq.size)\n}\n", "positive_code": [{"source_code": "//package codeforces.contest1136\n\nobject NastyaIsReadingABook {\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val pages = readLines(n)\n\n val lastUnreadPage = io.StdIn.readInt()\n\n val chapterToRead = pages.indexWhere { case (a, b) => a <= lastUnreadPage && lastUnreadPage <= b } // 0 based\n\n println(n - chapterToRead)\n }\n\n def readLines(n: Int): List[(Int, Int)] = {\n def readInput(i: Int, res: List[(Int, Int)]): List[(Int, Int)] = {\n if (i >= n)\n res.reverse\n else {\n val Array(a, b) = io.StdIn.readLine.split(\" \").map(_.toInt)\n readInput(i + 1, (a, b) :: res)\n }\n }\n readInput(0, List())\n }\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val (l, r) = na2(N)\n val mark = ni()\n\n var c = 0 // このチャプターから先は読んでいない\n REP(N) { i =>\n if ((l(i) to r(i)).contains(mark)) c = i\n }\n val ans = N - c\n out.println(ans)\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugNum(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n val stdin = scala.io.StdIn\n val n = stdin.readInt\n var l = new Array[Int](n)\n var r = new Array[Int](n)\n for (i <- 0 until n){\n val t = stdin.readLine.trim.split(\" \")\n l(i) = t(0).toInt\n r(i) = t(1).toInt\n }\n val k = stdin.readInt\n println(r.count(k <= _))\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Solution {\n def chaptersLeft(lastPage: Int, currentLeft: Int, page: Int): Int = {\n currentLeft match {\n case 1 => 1\n case _ => (page > lastPage) match {\n case true => (currentLeft - 1)\n case false => (currentLeft)\n }\n }\n }\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt() \n val lastPages = (1 to n).toList.map(x => (StdIn.readLine()).split(\" \")(1).toInt)\n val page = StdIn.readInt()\n val res = lastPages.foldLeft(n)((acc, x) => chaptersLeft(x, acc, page))\n println(res)\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable\nimport util.control.Breaks._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = readInt\n var read = 0\n val a = Array.ofDim[Int](n*2)\n 0.until(n).foreach{ i =>\n val chapter = readLine().split(\" \").map(_.toInt)\n a(i*2) = chapter(0)\n a(i*2 + 1) = chapter(1)\n }\n val idx = readInt()\n\n breakable {\n 0.until(n).foreach { i =>\n if (a(i * 2 + 1) < idx) {\n read += 1\n } else {\n break;\n }\n }\n }\n\n println(n - read)\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\nobject Main extends App {\n\n val n: Int = io.StdIn.readInt()\n\n val array: Array[A] = new Array[A](n)\n for (index <- 1 to n) {\n val input = io.StdIn.readLine().split(\" \").map(x => x.toInt)\n array(index - 1) = new A(index - 1, input(0), input(1))\n }\n val k: Int = io.StdIn.readInt()\n\n def solve(array: Array[A], k: Int, n: Int, index: Int = 0): Int = {\n if (array(index).contains(k)) n - array(index).index\n else solve(array, k, n, index + 1)\n }\n\n class A(val index: Int, start: Int, end: Int) {\n def contains(value: Int): Boolean = value >= start && value <= end\n }\n\n\n println(solve(array, k, n))\n}\n"}], "negative_code": [], "src_uid": "2545b6af730f99193041a8810b728cb3"} {"source_code": "import scala.collection.mutable\nimport java.io._\nimport java.util.StringTokenizer\n\nobject Main extends App {\n\n import io.StdIn\n\n val in = new Reader\n\n val n = in.nextInt\n val a = new Array[Int](n)\n for (i <- 0 to n-1) a(i) = in.nextInt\n //val a = StdIn.readLine().split(\" \").map(_.toInt)\n\n class Seg(var l: Int,\n var sz: Int,\n var next: Int,\n var prev: Int,\n var ind: Int) extends Comparable[Seg] {\n override def compareTo(o: Seg): Int = {\n if (sz == o.sz) Integer.compare(l, o.l) else Integer.compare(-sz, -o.sz)\n }\n }\n\n var q = new mutable.TreeSet[Seg]()\n var segs = new Array[Seg](n)\n var cnt = 0\n\n var start = 0\n for (i <- 1 to n-1) {\n\n if (a(i) != a(i-1)) {\n segs(cnt) = new Seg(start, i-start, cnt+1, cnt-1, cnt)\n q += segs(cnt)\n cnt += 1\n start = i\n }\n }\n\n segs(cnt) = new Seg(start, n-start, -1, cnt-1, cnt)\n q += segs(cnt)\n cnt += 1\n\n var ans = 0\n\n while (!q.isEmpty) {\n\n val seg = q.firstKey\n\n //println(seg.l+\" \"+seg.sz)\n\n q -= seg\n val prev = if (seg.prev != -1) segs(seg.prev) else null\n val next = if (seg.next != -1) segs(seg.next) else null\n\n if (prev != null) prev.next = seg.next\n if (next != null) next.prev = seg.prev\n\n if (prev != null && next != null && a(prev.l) == a(next.l)) {\n q -= next\n q -= prev\n prev.sz += next.sz\n prev.next = next.next\n q += prev\n if (next.next != -1) segs(next.next).prev = seg.prev\n }\n\n ans += 1\n }\n\n println(ans)\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject Main extends App {\n\n import io.StdIn\n\n val n = StdIn.readInt()\n val a = StdIn.readLine().split(\" \").map(_.toInt)\n\n class Seg(var l: Int,\n var sz: Int,\n var next: Int,\n var prev: Int,\n var ind: Int) extends Comparable[Seg] {\n override def compareTo(o: Seg): Int = {\n if (sz == o.sz) Integer.compare(l, o.l) else Integer.compare(-sz, -o.sz)\n }\n }\n\n var q = new mutable.TreeSet[Seg]()\n var segs = new Array[Seg](n)\n var cnt = 0\n\n var start = 0\n for (i <- 1 to n-1) {\n\n if (a(i) != a(i-1)) {\n segs(cnt) = new Seg(start, i-start, cnt+1, cnt-1, cnt)\n q += segs(cnt)\n cnt += 1\n start = i\n }\n }\n\n segs(cnt) = new Seg(start, n-start, -1, cnt-1, cnt)\n q += segs(cnt)\n cnt += 1\n\n var ans = 0\n\n while (!q.isEmpty) {\n\n val seg = q.firstKey\n\n //println(seg.l+\" \"+seg.sz)\n\n q -= seg\n val prev = if (seg.prev != -1) segs(seg.prev) else null\n val next = if (seg.next != -1) segs(seg.next) else null\n\n if (prev != null) prev.next = seg.next\n if (next != null) next.prev = seg.prev\n\n if (prev != null && next != null && a(prev.l) == a(next.l)) {\n q -= next\n q -= prev\n prev.sz += next.sz\n prev.next = next.next\n q += prev\n if (next.next != -1) segs(next.next).prev = seg.prev\n }\n\n ans += 1\n }\n\n println(ans)\n}\n"}], "negative_code": [], "src_uid": "372045d9a4edb59ab3dae4d5d0e0e970"} {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, l, x, y) = readInts(4)\n val as = readInts(n)\n val marked = Set.empty ++ as\n\n var hasX, hasY = false\n for (a <- as) {\n if (marked(a - x) || marked(a + x)) hasX = true\n if (marked(a - y) || marked(a + y)) hasY = true\n }\n if (hasX && hasY) println(0)\n else if (hasX) {\n println(1)\n println(y)\n } else if (hasY) {\n println(1)\n println(x)\n } else {\n for (a <- as) {\n if (a > x) {\n val b = a - x\n if (marked(b - y) || marked(b + y)) {\n println(1)\n println(b)\n System.exit(0)\n }\n }\n if (a + x < l) {\n val b = a + x\n if (marked(b - y) || marked(b + y)) {\n println(1)\n println(b)\n System.exit(0)\n }\n }\n }\n println(2)\n println(s\"$x $y\")\n }\n}", "positive_code": [{"source_code": "object Main {\n\n val in = {\n val lines = scala.io.Source.stdin.getLines\n lines map (_ split ' ') filter (_.nonEmpty) flatten\n }\n \n def nextLong = in.next.toLong\n \n def main(args: Array[String]): Unit = {\n \n val N, L, X, Y = nextLong\n val marks = Array.fill(N.toInt)(nextLong)\n \n val s = scala.collection.mutable.Set[Long]()\n marks foreach (s.add(_))\n\n val xb = marks.exists(x => s.contains(x + X))\n val yb = marks.exists(x => s.contains(x + Y))\n\n if (xb && yb) {\n println(0)\n System.exit(0)\n }\n \n if (xb) {\n println(1)\n println(Y)\n System.exit(0)\n }\n \n if (yb) {\n println(1)\n println(X)\n System.exit(0)\n }\n \n for (x <- marks) {\n if (s.contains(x + X + Y))\n {\n println(1)\n println(x + X)\n System.exit(0)\n }\n }\n \n def valid(x: Long) = x >= 0 && x <= L\n \n for (x <- marks) {\n if (valid(x + Y) && s.contains(x + Y - X))\n {\n println(1)\n println(x + Y)\n System.exit(0)\n }\n if (valid(x - Y) && s.contains(x - Y + X))\n {\n println(1)\n println(x - Y)\n System.exit(0)\n }\n }\n \n println(2)\n println(X + \" \" + Y)\n }\n}"}], "negative_code": [{"source_code": "object Main {\n\n val in = {\n val lines = scala.io.Source.stdin.getLines\n lines map (_ split ' ') filter (_.nonEmpty) flatten\n }\n \n def nextInt = in.next.toInt\n \n def main(args: Array[String]): Unit = {\n \n val N, L, X, Y = nextInt\n val marks = Array.fill(N)(nextInt)\n \n val s = scala.collection.mutable.Set[Int]()\n \n marks foreach (s.add(_))\n \n val xb = marks.exists(x => s.contains(x - X) || s.contains(x + X))\n val yb = marks.exists(x => s.contains(x - Y) || s.contains(x + Y))\n \n if (xb && yb) {\n println(0)\n System.exit(0)\n }\n \n if (xb) {\n println(1)\n println(Y)\n System.exit(0)\n }\n \n if (yb) {\n println(1)\n println(X)\n System.exit(0)\n }\n \n for (x <- marks) {\n if (s.contains(x + X + Y))\n {\n println(1)\n println(x + X)\n System.exit(0)\n }\n }\n \n println(2)\n println(X + \" \" + Y)\n }\n}"}, {"source_code": "object Main {\n\n val in = {\n val lines = scala.io.Source.stdin.getLines\n lines map (_ split ' ') filter (_.nonEmpty) flatten\n }\n \n def nextLong = in.next.toLong\n \n def main(args: Array[String]): Unit = {\n \n val N, L, X, Y = nextLong\n val marks = Array.fill(N.toInt)(nextLong)\n \n val s = scala.collection.mutable.Set[Long]()\n marks foreach (s.add(_))\n\n val xb = marks.exists(x => s.contains(x + X))\n val yb = marks.exists(x => s.contains(x + Y))\n\n if (xb && yb) {\n println(0)\n System.exit(0)\n }\n \n if (xb) {\n println(1)\n println(Y)\n System.exit(0)\n }\n \n if (yb) {\n println(1)\n println(X)\n System.exit(0)\n }\n \n for (x <- marks) {\n if (s.contains(x + X + Y))\n {\n println(1)\n println(x + X)\n System.exit(0)\n }\n }\n \n println(2)\n println(X + \" \" + Y)\n }\n}"}, {"source_code": "object Main {\n\n val in = {\n val lines = scala.io.Source.stdin.getLines\n lines map (_ split ' ') filter (_.nonEmpty) flatten\n }\n \n def nextInt = in.next.toInt\n \n def main(args: Array[String]): Unit = {\n \n val N, L, X, Y = nextInt\n val marks = Array.fill(N)(nextInt)\n \n val s = scala.collection.mutable.Set[Int]()\n \n marks foreach (s.add(_))\n \n val xb = marks.exists(x => s.contains(x - X) || s.contains(x + X))\n val yb = marks.exists(x => s.contains(x - Y) || s.contains(x + Y))\n \n if (xb && yb) {\n println(0)\n System.exit(0)\n }\n \n if (xb) {\n println(1)\n println(Y)\n System.exit(0)\n }\n \n if (yb) {\n println(1)\n println(X)\n System.exit(0)\n }\n \n println(2)\n println(X + \" \" + Y)\n }\n}"}], "src_uid": "333790c28eb02ad568a2406d5b2fafa6"} {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val bs = readLongs(n).sorted.reverse\n val gs = readLongs(m).sorted.reverse\n\n if (bs.max > gs.min) println(-1)\n else {\n var j = 0\n var res = 0L\n while (j < m - 1 || (j < m && bs(0) == gs(j))) {\n res += gs(j)\n j += 1\n }\n var i = 1\n if (j < m) {\n res += bs(0)\n while (i < n && bs(i) > gs(j)) {\n res += bs(i) * m\n i += 1\n }\n res += bs(i) * m\n res += gs(j) - bs(i)\n i += 1\n while (i < n) {\n res += bs(i) * m\n i += 1\n }\n } else {\n while (i < n) {\n res += bs(i) * m\n i += 1\n }\n }\n println(res)\n }\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nimport scala.io.StdIn\nimport scala.util.control.Breaks.breakable\nimport scala.util.control.Breaks._\n\nobject Ctask559 extends App {\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n val m = line.nextInt()\n val b = StdIn.readLine().split(' ').map(BigInt(_)).sorted.reverse\n val g = StdIn.readLine().split(' ').map(BigInt(_)).sorted.reverse\n\n var result = BigInt(0)\n var offset = 0\n var tempOffset = 0\n if (b.max > g.min) {\n println(-1)\n System.exit(0)\n }\n for (i <- 0 until n) {\n var amount = m - 1\n if (offset >= m) {\n result += (b(i) * m)\n } else {\n breakable {\n for (j <- 0 + offset until m) {\n if (g(j) > b(i) && amount > 0) {\n result += g(j)\n tempOffset += 1\n amount -= 1\n } else {\n if (g(j) == b(i) && amount >= 0) {\n result += g(j)\n tempOffset += 1\n amount -= 1\n } else {\n break()\n }\n }\n }\n }\n if (amount >= 0) {\n result += b(i) * (amount+1)\n }\n offset += tempOffset\n tempOffset = 0\n }\n }\n println(result)\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nimport scala.io.StdIn\nimport scala.util.control.Breaks.breakable\n\nobject Ctask559 extends App {\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n val m = line.nextInt()\n val b = StdIn.readLine().split(' ').map(_.toInt).sorted.reverse\n val g = StdIn.readLine().split(' ').map(_.toInt).sorted.reverse\n\n var result = 0\n var offset = 0\n var tempOffset = 0\n if (b.max > g.min) {\n println(-1)\n System.exit(0)\n }\n for (i <- 0 until n) {\n var amount = m - 1\n if (offset == m) {\n result += (b(i) * m)\n } else {\n breakable {\n for (j <- 0 + offset until m) {\n if (g(j) > b(i) && amount > 0) {\n result += g(j)\n tempOffset += 1\n amount -= 1\n } else {\n if (g(j) == b(i) && amount >= 0) {\n result += g(j)\n tempOffset += 1\n amount -= 1\n }\n }\n }\n if (amount >= 0) {\n result += b(i) * (amount+1)\n }\n offset += tempOffset\n tempOffset = 0\n }\n }\n }\n\n println(result)\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.io.StdIn\nimport scala.util.control.Breaks.breakable\nimport scala.util.control.Breaks._\n\nobject Ctask559 extends App {\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n val m = line.nextInt()\n val b = StdIn.readLine().split(' ').map(_.toInt).sorted.reverse\n val g = StdIn.readLine().split(' ').map(_.toInt).sorted.reverse\n\n var result = BigInt(0)\n var offset = 0\n var tempOffset = 0\n if (b.max > g.min) {\n println(-1)\n System.exit(0)\n }\n for (i <- 0 until n) {\n var amount = m - 1\n if (offset >= m) {\n result += (b(i) * m)\n } else {\n breakable {\n for (j <- 0 + offset until m) {\n if (g(j) > b(i) && amount > 0) {\n result += g(j)\n tempOffset += 1\n amount -= 1\n } else {\n if (g(j) == b(i) && amount >= 0) {\n result += g(j)\n tempOffset += 1\n amount -= 1\n } else {\n break()\n }\n }\n }\n }\n if (amount >= 0) {\n result += b(i) * (amount+1)\n }\n offset += tempOffset\n tempOffset = 0\n }\n }\n\n println(result)\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.io.StdIn\nimport scala.util.control.Breaks.breakable\nimport scala.util.control.Breaks._\n\nobject Ctask559 extends App {\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n val m = line.nextInt()\n val b = StdIn.readLine().split(' ').map(_.toInt).sorted.reverse\n val g = StdIn.readLine().split(' ').map(_.toInt).sorted.reverse\n\n var result = 0\n var offset = 0\n var tempOffset = 0\n if (b.max > g.min) {\n println(-1)\n System.exit(0)\n }\n for (i <- 0 until n) {\n var amount = m - 1\n if (offset >= m) {\n result += (b(i) * m)\n } else {\n breakable {\n for (j <- 0 + offset until m) {\n if (g(j) > b(i) && amount > 0) {\n result += g(j)\n tempOffset += 1\n amount -= 1\n } else {\n if (g(j) == b(i) && amount >= 0) {\n result += g(j)\n tempOffset += 1\n amount -= 1\n } else {\n break()\n }\n }\n }\n }\n if (amount >= 0) {\n result += b(i) * (amount+1)\n }\n offset += tempOffset\n tempOffset = 0\n }\n }\n\n println(result)\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val bs = readLongs(n).sorted.reverse\n val gs = readLongs(m).sorted\n\n if (bs.max > gs.min) println(-1)\n else {\n var j = 0\n var res = 0L\n while (j < m - 1 || (j < m && bs(0) == gs(j))) {\n res += gs(j)\n j += 1\n }\n var i = 1\n if (j < m) {\n while (i < n && bs(i) > gs(j)) {\n res += bs(i) * m\n i += 1\n }\n res += bs(i) * m\n res += gs(j) - bs(i)\n while (i < n) {\n res += bs(i) * m\n i += 1\n }\n }\n println(res)\n }\n}\n"}], "src_uid": "4b4c7e7d9d5c45c8635b403bae997891"} {"source_code": "import java.util.Scanner\nimport scala.collection.immutable._\nimport scala.collection.mutable\n\n/**\n * Created by Andrew on 11-Jul-16.\n */\n\n\n\nobject Main extends App {\n\n def foo(s: List[Char], cnt: Int): (List[Char], Int, Boolean) = {\n if (s.isEmpty)\n (List(), 0, false)\n else {\n if (s.head < '4') {\n val (t, c, f) = foo(s.tail, cnt)\n (((if (f) (s.head.toByte + 1) else s.head.toByte).toChar) :: t, c, false)\n }\n else {\n if (s.head > '4')\n (List(), 1, true)\n else {\n val (t, c, f) = foo(s.tail, cnt)\n if (f && c < cnt)\n (t, c + 1, true)\n else\n ((if (f) '5' else '4') :: t, c, false)\n }\n }\n }\n }\n\n val sc = new Scanner(System.in)\n\n val _ = sc.nextInt()\n val t = sc.nextInt()\n val s = sc.next()\n val (res, _, f) = foo(s.toList.dropWhile({case '.' => false; case _ => true}).tail, t)\n if(f) {\n var flg = f\n val r = s.takeWhile({case '.' => false; case _ => true}).toArray\n for(i <- Range(r.length - 1, -1, -1))\n if (flg) {\n if (r(i) == '9')\n r(i) = '0'\n else {\n r(i) = (r(i).toByte + 1).toChar\n flg = false\n }\n }\n if (flg)\n print(1)\n println(new String(r))\n }\n else\n println(s.takeWhile({case '.' => false; case _ => true}) ++ \".\" ++ res)\n}\n", "positive_code": [{"source_code": "import java.math.BigInteger\n\nimport scala.io.StdIn._\nimport scala.util.Random\n\nobject _373C extends App {\n val Array(n, t) = readLine().split(\" \") map (_.toInt)\n val Array(left, right) = readLine().split(\"\\\\.\")\n\n val A = (left map (_.asDigit)).toArray\n val B = (right map (_.asDigit)).toArray\n\n def printNumber(left: Array[Int], right: Array[Int], rightSize: Int) = {\n println(left.mkString + \".\" + right.mkString.take(rightSize + 1))\n }\n\n def printNumber(left: Array[Int]) = {\n println(left.mkString)\n }\n\n\n var first4InSeq = -1\n var last4InSeq = -1\n\n def solve(): (Int, Int, Int) = {\n for (i <- B.indices) {\n if (B(i) == 4) {\n if (first4InSeq == -1) {\n first4InSeq = i\n last4InSeq = i\n } else {\n last4InSeq = i\n }\n } else if (first4InSeq > -1) {\n if (B(i) > 4) {\n return (first4InSeq, last4InSeq, last4InSeq + 1)\n } else {\n first4InSeq = -1\n last4InSeq = -1\n }\n } else if (B(i) > 4) {\n return (-1, -1, i)\n }\n }\n\n (-1, -1, -1)\n }\n\n def printNumberPlusOne() = {\n val digits = A.reverse\n var i = 0\n if (digits(i) < 9) {\n digits(i) += 1\n println(digits.reverse.mkString)\n } else {\n while (i < left.length && digits(i) == 9) {\n digits(i) = 0\n i += 1\n }\n if (i < left.length) {\n digits(i) += 1\n println(digits.reverse.mkString)\n } else {\n println(\"1\" + digits.reverse.mkString)\n }\n }\n }\n def printNumberSubsPlusOne(last: Int) = {\n B(last) += 1\n printNumber(A, B, last)\n }\n\n def cut(a: Int, b: Int, c: Int) = {\n if (a > -1) {\n if (t >= c - a + 1) {\n if (a == 0) {\n printNumberPlusOne()\n } else {\n printNumberSubsPlusOne(a - 1)\n }\n } else {\n printNumberSubsPlusOne(c - t)\n }\n } else {\n if (c == 0) {\n printNumberPlusOne()\n } else {\n printNumberSubsPlusOne(c - 1)\n }\n }\n }\n\n val (a, b, c) = solve()\n if (c == -1) {\n val max = B.zipWithIndex.maxBy(_._1)\n if (max._1 > 4) {\n if (max._2 == 0) {\n printNumberPlusOne()\n } else {\n val subs = right.substring(0, max._2)\n printNumberSubsPlusOne(max._2 - 1)\n }\n } else {\n printNumber(A, B, B.length - 1)\n }\n } else {\n cut(a, b, c)\n }\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val line = in.next()\n if (!line.contains('.'))\n println(line)\n else {\n val Array(first, second) = line.split('.')\n second.indices.find(i => second(i) >= '5') match {\n case None => println(line)\n case Some(i) =>\n// println((i - 1 to Math.max(0, i - t + 1) by -1).map(i => second(i)))\n// println((i - 1 to Math.max(0, i - t + 1) by -1).takeWhile(i => second(i) == '4').map(i => second(i)))\n val l = (i - 1 to Math.max(0, i - t + 1) by -1).takeWhile(i => second(i) == '4').length\n if (l - i == 0) {\n val nines = first.reverse.takeWhile(_ == '9').length\n if (nines == first.length) {\n// println(\"HERE\")\n println(\"1\" + \"0\" * nines)\n }\n else\n println(first.take(first.length - nines - 1) + (first(first.length - nines - 1) + 1).toChar + \"0\" * nines)\n }\n else {\n// println(l)\n val n = second.take(i - l - 1) + (second(i - l - 1) + 1).toChar\n println(s\"$first.$n\")\n }\n }\n }\n}\n"}], "negative_code": [{"source_code": "import java.math.BigInteger\n\nimport scala.io.StdIn._\n\nobject _373C extends App {\n val Array(n, t) = readLine().split(\" \") map (_.toInt)\n val Array(left, right) = readLine().split(\"\\\\.\")\n val B = (right map (_.asDigit)).toList\n\n def printNumber(left: BigInteger, right: String) = {\n if (right == \"0\") println(left) else println(left + \".\" + right)\n }\n\n def printNumber(left: String, right: String) = {\n if (right == \"0\") println(left) else println(left + \".\" + right)\n }\n\n var first4InSeq = -1\n var last4InSeq = -1\n\n def solve(): (Int, Int, Int) = {\n for (i <- B.indices) {\n if (B(i) == 4) {\n if (first4InSeq == -1) {\n first4InSeq = i\n last4InSeq = i\n } else {\n last4InSeq = i\n }\n } else if (first4InSeq > -1) {\n if (B(i) > 4) {\n return (first4InSeq, last4InSeq, last4InSeq + 1)\n } else {\n first4InSeq = -1\n last4InSeq = -1\n }\n }\n }\n\n (-1, -1, -1)\n }\n\n def printNumberPlusOne() = printNumber(new BigInteger(left).add(BigInteger.ONE), \"0\")\n def printNumberSubsPlusOne(subs: String) = printNumber(left, subs.init + (subs.last.asDigit + 1))\n\n def cut(a: Int, b: Int, c: Int) = {\n if (t >= c - a + 1) {\n if (a == 0) {\n printNumberPlusOne()\n } else {\n val subs = right.substring(0, a)\n printNumberSubsPlusOne(subs)\n }\n } else {\n val subs = right.substring(0, c - t + 1)\n printNumberSubsPlusOne(subs)\n }\n }\n\n val (a, b, c) = solve()\n if (a == -1) {\n val max = B.zipWithIndex.maxBy(_._1)\n if (max._1 > 4) {\n if (max._2 == 0) {\n printNumberPlusOne()\n } else {\n val subs = right.substring(0, max._2)\n printNumberSubsPlusOne(subs)\n }\n } else {\n printNumber(left, right)\n }\n } else {\n cut(a, b, c)\n }\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val line = in.next()\n if (!line.contains('.'))\n println(line)\n else {\n val Array(first, second) = line.split('.')\n second.indices.find(i => second(i) >= '5') match {\n case None => println(line)\n case Some(i) =>\n// println((i - 1 to Math.max(0, i - t + 1) by -1).map(i => second(i)))\n// println((i - 1 to Math.max(0, i - t + 1) by -1).takeWhile(i => second(i) == '4').map(i => second(i)))\n val l = (i - 1 to Math.max(0, i - t + 1) by -1).takeWhile(i => second(i) == '4').length\n if (l - i == 0) {\n val nines = first.reverse.takeWhile(_ == '9').length\n println(nines)\n if (nines == first.length) {\n// println(\"HERE\")\n println(\"1\" + \"0\" * nines)\n }\n else\n println(first.take(first.length - nines - 1) + (first(first.length - nines) + 1).toChar + \"0\" * nines)\n }\n else {\n// println(l)\n val n = second.take(second.length - l - 2) + (second(second.length - l - 2) + 1).toChar\n println(s\"$first.$n\")\n }\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.immutable._\nimport scala.collection.mutable\n\n/**\n * Created by Andrew on 11-Jul-16.\n */\n\n\n\nobject Main extends App {\n\n def foo(s: List[Char], cnt: Int): (List[Char], Int, Boolean) = {\n if (s.isEmpty)\n (List(), 0, false)\n else {\n if (s.head < '4') {\n val (t, c, f) = foo(s.tail, cnt)\n (((if (f) (s.head.toByte + 1) else s.head.toByte).toChar) :: t, c, false)\n }\n else {\n if (s.head > '4')\n (List(), 1, true)\n else {\n val (t, c, f) = foo(s.tail, cnt)\n if (f && c < cnt)\n (t, c + 1, true)\n else\n ((if (f) '5' else '4') :: t, c, false)\n }\n }\n }\n }\n\n val sc = new Scanner(System.in)\n\n val _ = sc.nextInt()\n val t = sc.nextInt()\n val s = sc.next()\n val (res, _, f) = foo(s.toList.dropWhile({case '.' => false; case _ => true}).tail, t)\n if(f)\n println(Integer.decode(s.takeWhile({case '.' => false; case _ => true})) + 1)\n else\n println(s.takeWhile({case '.' => false; case _ => true}) ++ \".\" ++ res.reverse)\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.immutable._\nimport scala.collection.mutable\n\n/**\n * Created by Andrew on 11-Jul-16.\n */\n\n\n\nobject Main extends App {\n\n def foo(s: List[Char], cnt: Int): (List[Char], Int, Boolean) = {\n if (s.isEmpty)\n (List(), 0, false)\n else {\n if (s.head < '4') {\n val (t, c, f) = foo(s.tail, cnt)\n (((if (f) (s.head.toByte + 1) else s.head.toByte).toChar) :: t, c, false)\n }\n else {\n if (s.head > '4')\n (List(), 1, true)\n else {\n val (t, c, f) = foo(s.tail, cnt)\n if (f && c < cnt)\n (t, c + 1, true)\n else\n ((if (f) '5' else '4') :: t, c, false)\n }\n }\n }\n }\n\n val sc = new Scanner(System.in)\n\n val _ = sc.nextInt()\n val t = sc.nextInt()\n val s = sc.next()\n val (res, _, f) = foo(s.toList.dropWhile({case '.' => false; case _ => true}).tail, t)\n if(f) {\n var flg = f\n val r = s.takeWhile({case '.' => false; case _ => true}).toArray\n for(i <- Range(r.length - 1, -1, -1))\n if (flg) {\n if (r(i) == '9')\n r(i) = '0'\n else {\n r(i) = (r(i).toByte + 1).toChar\n flg = false\n }\n }\n println(new String(r))\n }\n else\n println(s.takeWhile({case '.' => false; case _ => true}) ++ \".\" ++ res)\n}\n"}], "src_uid": "d563ce32596b54f48544a6085efe5cc5"} {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject B extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val n = readInt\n val ps = readInts(n)\n val MOD = 1000000007L\n \n val dp = Array.ofDim[Long](n + 1, 2)\n\n dp(0)(0) = 0\n dp(0)(1) = 1\n \n for (i <- 1 to n) {\n dp(i)(0) = (dp(i - 1)(1) + 1) % MOD\n if (i < n) dp(i)(1) = if (ps(i) - 1 < i) {\n var sum = (dp(i)(0) + 1) % MOD\n for (i <- ps(i) - 1 until i)\n sum = (MOD + sum + (dp(i)(1) - dp(i)(0)) + 1) % MOD\n sum\n } else (dp(i)(0) + 1) % MOD\n }\n //println(dp.map(a => a(0)).mkString(\" \"))\n //println(dp.map(a => a(1)).mkString(\" \"))\n println(dp(n)(0))\n}", "positive_code": [{"source_code": "import java.util.StringTokenizer;\nimport Array._;\n\nobject LongPath {\n var st:StringTokenizer = new StringTokenizer(\"\");\n def newst={st=new StringTokenizer(readLine);}\n def nextint:Int = {st.nextToken.toInt;}\n val MD=1000000007;\n def main(args:Array[String])={\n newst;\n val m=nextint;\n newst;\n //for (i<-1 to m) {println(m);}\n var p:Array[Int]=fill(m+1)(0);\n var n:Array[Long]=fill(m+1)(0);\n var x:Long=0;\n var ans:Long=2;\n for (i<-1 to m) {\n p(i)=nextint;\n }\n n(m)=2;\n for (i<-m-1 to 1 by (-1)) {\n x=(2*n(i+1))%MD;\n for (j<-i+1 to m) {\n\tif (p(j)==i+1) {x=(x-n(j)+MD)%MD;}\n }\n n(i)=x;\n ans=(ans+x)%MD;\n }\n println(ans);\n }\n}\n \n \n"}], "negative_code": [], "src_uid": "7bb5df614d1fc8323eba51d04ee7bf2a"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n Sorting.quickSort(A)\n val ms = A(0)\n var ans = 0L\n rep(N - 1) { i =>\n ans += A(i + 1) - A(i) - 1\n }\n\n out.println(ans)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}", "positive_code": [{"source_code": "object CodeForces extends App {\n val n = Console.in.readLine().toInt\n val xs = Console.in.readLine().split(\" \", n).map(_.toLong).sorted\n\n var c: Long = 0\n\n for (i <- 0 until xs.length - 1) {\n c += xs(i + 1) - (xs(i) + 1)\n }\n\n println(c)\n}"}], "negative_code": [{"source_code": "object CodeForces extends App {\n val n = Console.in.readLine().toInt\n val xs = Console.in.readLine().split(\" \", n).map(_.toInt).sorted\n\n var c = 0\n\n for (i <- 0 until xs.length - 2) {\n c += xs(i + 1) - (xs(i) + 1)\n }\n\n println(c)\n}"}], "src_uid": "6469ed9f2486b498c9ffeb8270391e3a"} {"source_code": "import scala.annotation.tailrec\nobject B {\n def getSlice(s: String, h: String, idx: Int = 0, res: List[Int] = Nil): List[Int] = {\n s.indexOf(h, idx) match {\n case -1 => res\n case x => getSlice(s, h, x + h.length, x :: res)\n }\n }\n\n @tailrec\n def solve(l: List[Int], r: List[Int], llen: Long, rlen: Long, res: Long = 0): Long = {\n l match {\n case x :: xs => {\n r match {\n case y :: ys => {\n if(x > y) solve(l, ys, llen, rlen-1, res)\n else solve(xs, r, llen-1, rlen, res + rlen)\n } \n case Nil => res\n }\n }\n case Nil => res\n }\n }\n\n def main(args: Array[String]) {\n val ll = readLine\n val heavy = getSlice(ll, \"heavy\").sortWith(_ < _)\n val metal = getSlice(ll, \"metal\").sortWith(_ < _)\n println(solve(heavy, metal, heavy.length, metal.length))\n }\n}", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P318B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Long = {\n val S = sc.nextLine\n val N = S.length\n \n @tailrec\n def loop(acc: Long, i: Int, j: Int, k: Int, n: Int): Long = {\n val i_ = if (0 <= i && i < n) S.indexOf(\"heavy\", n)\n else i\n val j_ = if (0 <= j && j < n) S.indexOf(\"metal\", n)\n else j\n\n n match {\n case N => acc\n case `i_` => loop(acc, i_, j_, k + 1, n + 5)\n case `j_` => loop(acc + k, i_, j_, k, n + 5)\n case _ => loop(acc, i_, j_, k, n + 1)\n }\n }\n\n loop(0, S.indexOf(\"heavy\"), S.indexOf(\"metal\"), 0, 0)\n }\n\n out.println(solve)\n out.close\n}"}, {"source_code": "import scala.io.StdIn._\nobject main extends App{\n var metal = new Array[Int](1000005)\n val s = readLine()\n var count = 0\n for(i <- 0 until s.length - 4){\n if(s(i) == 'm'){\n if(s.slice(i,i+5) == \"metal\"){\n count += 1\n }\n }\n metal(i) = count\n }\n var ans : BigInt = 0\n for(i <- 0 until s.length - 4){\n if(s(i) == 'h'){\n if(s.slice(i,i+5) == \"heavy\"){\n ans += count - metal(i)\n }\n }\n }\n print(ans)\n}"}, {"source_code": "import scala.io.StdIn._\nobject main extends App{\n var metal = new Array[Int](1000005)\n val s = readLine()\n var count = 0\n for(i <- 0 until s.length - 4){\n if(s(i) == 'm'){\n if(s.slice(i,i+5) == \"metal\"){\n count += 1\n }\n }\n metal(i) = count\n }\n var ans : Long = 0\n for(i <- 0 until s.length - 4){\n if(s(i) == 'h'){\n if(s.slice(i,i+5) == \"heavy\"){\n ans += count - metal(i)\n }\n }\n }\n print(ans)\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val res = str.foldLeft((0l, 0l, \"\")) {\n case((count, starts, \"\"), 'h') => (count, starts, \"h\")\n case((count, starts, \"\"), 'm') => (count, starts, \"m\")\n case((count, starts, \"\"), el) => (count, starts, \"\")\n case((count, starts, \"heav\"), 'y') => (count, starts + 1, \"\")\n case((count, starts, \"meta\"), 'l') => (count + starts, starts, \"\")\n case((count, starts, str1), el) if str1.head == 'h' && \"heavy\"(str1.length) == el => (count, starts, str1 + el)\n case((count, starts, str1), el) if str1.head == 'm' && \"metal\"(str1.length) == el => (count, starts, str1 + el)\n case((count, starts, str1), 'h') => (count, starts, \"h\")\n case((count, starts, str1), 'm') => (count, starts, \"m\")\n case((count, starts, str1), el) => (count, starts, \"\")\n }\n println(res._1)\n}\n//fpgzbvhheavymheheavyzmheavyavyebknkhheavyhsbqmmetheavyalmetalheavyyomtua"}, {"source_code": "object B extends App {\n \n def loc(s: String, sub: String) = {\n \n\t var lastIndex = 0\n\t val res = new scala.collection.mutable.ArrayBuffer[Int]()\n\t \n\t while (lastIndex != -1) {\n\n \t\tlastIndex = s.indexOf(sub, lastIndex);\n\n \t\tif (lastIndex != -1) {\n \t\t\tres += lastIndex\n \t\t\tlastIndex += sub.length();\n \t\t}\n \t}\n\t \n\t res\n }\n\n def solve(s: String): Long = {\n\n val hs = loc(s, \"heavy\")\n var ms = loc(s, \"metal\")\n \n var count = 0L\n var mLeft = ms.length\n var mi = 0\n \n for (h <- hs) {\n while (mi < ms.length && ms(mi) < h) {\n mLeft -= 1\n mi += 1\n }\n count += mLeft \n }\n \n count\n } \n\n def readString = Console.readLine\n\n val s = readString\n\n println(solve(s)) \n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P318B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Long = {\n val S = sc.nextLine\n val N = S.length\n \n @tailrec\n def loop(acc: Long, i: Int, j: Int, k: Int, n: Int): Long = {\n val i_ = if (0 <= i && i < n) S.indexOf(\"heavy\", n)\n else i\n val j_ = if (0 <= j && j < n) S.indexOf(\"metal\", n)\n else j\n\n n match {\n case N => acc\n case `i_` => loop(acc, i_, j_, k + 1, n + 5)\n case `j_` => loop(acc + k, i_, j_, k, n + 5)\n case _ => loop(acc, i_, j_, k, n + 1)\n }\n }\n\n loop(0, S.indexOf(\"heavy\"), S.indexOf(\"metal\"), 0, 0)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val s = readLine()\n \n var h = 0L\n var count = 0L\n for(i <- 0 to s.size - 5) {\n if (s(i) == 'h' && s(i + 1) == 'e' && s(i + 2) == 'a' && s(i + 3) == 'v' && s(i + 4) == 'y') h += 1\n else if (s(i) == 'm' && s(i + 1) == 'e' && s(i + 2) == 't' && s(i + 3) == 'a' && s(i + 4) == 'l') count += h\n }\n \n println(count)\n }\n}"}, {"source_code": "\nobject Second{\n def readString() : String = {\n var yo = scala.io.StdIn.readLine() \n yo \n }\n def readInt() : Int = { \n var yo = scala.io.StdIn.readInt(); \n yo \n }\n def loc(s: String, sub: String) = {\n \n\t var lastIndex = 0\n\t val res = new scala.collection.mutable.ArrayBuffer[Int]() // yeh ek hissab se vector ko declare krna h \n\t \n\t while (lastIndex != -1) {\n \n \t\tlastIndex = s.indexOf(sub, lastIndex);\n \n \t\tif (lastIndex != -1) {\n \t\t\tres += lastIndex\n \t\t\tlastIndex += sub.length();\n \t\t}\n \t}\n\t \n\t res\n }\n\n def solve(s : String) = { \n val hs = loc(s, \"heavy\")\n var ms = loc(s, \"metal\")\n var count = 0L\n var mLeft = ms.length\n var mi = 0\n \n for (h <- hs) {\n while (mi < ms.length && ms(mi) < h) {\n mLeft -= 1\n mi += 1\n }\n count += mLeft \n }\n \n count\n }\n def main(args : Array[String]){\n var s = readString() \n print(solve(s))\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\nobject main extends App{\n var metal = new Array[Int](1000005)\n val s = readLine()\n var count = 0\n for(i <- 0 until s.length - 4){\n if(s(i) == 'm'){\n if(s.slice(i,i+5) == \"metal\"){\n count += 1\n }\n }\n metal(i) = count\n }\n var ans = 0\n for(i <- 0 until s.length - 4){\n if(s(i) == 'h'){\n if(s.slice(i,i+5) == \"heavy\"){\n ans += count - metal(i)\n }\n }\n }\n print(ans)\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val res = str.foldLeft((0l, 0l, \"\")) {\n case((count, starts, \"\"), 'h') => (count, starts, \"h\")\n case((count, starts, \"\"), 'm') => (count, starts, \"m\")\n case((count, starts, \"\"), el) => (count, starts, \"\")\n case((count, starts, \"heav\"), 'y') => (count, starts + 1, \"\")\n case((count, starts, \"meta\"), 'l') => (count + starts, starts, \"\")\n case((count, starts, str), el) if str.head == 'h' && \"heavy\"(str.length) == el => (count, starts, str + el)\n case((count, starts, str), el) if \"metal\"(str.length) == el => (count, starts, str + el)\n case((count, starts, str), el) => (count, starts, \"\")\n }\n println(res._1)\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P318B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Long = {\n val S = sc.nextLine\n val N = S.length\n \n @tailrec\n def loop(acc: Int, i: Int, j: Int, k: Int, n: Int): Int = {\n val i_ = if (0 <= i && i < n) S.indexOf(\"heavy\", n)\n else i\n val j_ = if (0 <= j && j < n) S.indexOf(\"metal\", n)\n else j\n\n n match {\n case N => acc\n case `i_` => loop(acc, i_, j_, k + 1, n + 5)\n case `j_` => loop(acc + k, i_, j_, k, n + 5)\n case _ => loop(acc, i_, j_, k, n + 1)\n }\n }\n\n loop(0, S.indexOf(\"heavy\"), S.indexOf(\"metal\"), 0, 0)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import scala.annotation.tailrec\nobject B {\n def getSlice(s: String, h: String, idx: Int = 0, res: List[Int] = Nil): List[Int] = {\n //println(s)\n s.indexOf(h, idx) match {\n case -1 => res\n case x => getSlice(s, h, x + h.length, x :: res)\n }\n }\n\n @tailrec\n def solve(l: List[Int], r: List[Int], llen: Long, rlen: Long, res: Long = 0): Long = {\n l match {\n case x :: xs => {\n r match {\n case y :: ys => {\n if(x > y) solve(l, ys, res, llen, rlen-1)\n else solve(xs, r, res + rlen, llen-1, rlen)\n } \n case Nil => res\n }\n }\n case Nil => res\n }\n }\n\n def main(args: Array[String]) {\n val ll = readLine\n val heavy = getSlice(ll, \"heavy\").sortWith(_ < _)\n val metal = getSlice(ll, \"metal\").sortWith(_ < _)\n println(solve(heavy, metal, heavy.length, metal.length))\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val s = readLine()\n \n var h = 0\n var count = 0\n for(i <- 0 to s.size - 5) {\n if (s(i) == 'h' && s(i + 1) == 'e' && s(i + 2) == 'a' && s(i + 3) == 'v' && s(i + 4) == 'y') h += 1\n else if (s(i) == 'm' && s(i + 1) == 'e' && s(i + 2) == 't' && s(i + 3) == 'a' && s(i + 4) == 'l') count += h\n }\n \n println(count)\n }\n}"}], "src_uid": "960e4c234666d2444b80d5966f1d285d"} {"source_code": "import scala.io.StdIn.readInt;\r\nimport scala.io.StdIn.readLine;\r\n\r\nobject Hello {\r\n def main(args: Array[String]) = {\r\n val t = readInt();\r\n for(s <- 1 to t){\r\n val n = readInt();\r\n val A: Array[Int] = readLine().split(' ').map(_.toInt);\r\n val B: Array[Int] = readLine().split(' ').map(_.toInt);\r\n val CMax : Array[Int] = A.zip(B).map({case(x , y)=>math.max(x,y)});\r\n val CMin : Array[Int] = A.zip(B).map({case(x , y)=>math.min(x,y)}); \r\n val C: Int = CMax.reduceLeft(_ max _)*CMin.reduceLeft(_ max _);\r\n println(C);\r\n }\r\n }\r\n}", "positive_code": [{"source_code": "object Solution{\r\n def main(args: Array[String]):Unit=\r\n {\r\n val T = scala.io.StdIn.readLine().toInt\r\n val len = new Array[Int](T)\r\n var as = new Array[List[Int]](T)\r\n var bs = new Array[List[Int]](T)\r\n for(k <- 0 until T)\r\n {\r\n len(k) = scala.io.StdIn.readLine().toInt\r\n as(k) = ((scala.io.StdIn.readLine().split(\" \")).map(_.toInt)).toList\r\n bs(k) = ((scala.io.StdIn.readLine().split(\" \")).map(_.toInt)).toList\r\n }\r\n \r\n def solve(a: List[Int], b: List[Int], l: Int): Int =\r\n { \r\n var M = -1\r\n var maxIndex = -1\r\n var aMax = a.max\r\n var bMax = b.max\r\n var aMaxInd = a.indexOf(aMax)\r\n var bMaxInd = b.indexOf(bMax)\r\n if(aMax >= bMax)\r\n {\r\n M = aMax\r\n maxIndex = aMaxInd\r\n }\r\n if(aMax < bMax)\r\n {\r\n M = bMax\r\n maxIndex = bMaxInd\r\n }\r\n var list = List.empty[Int]\r\n for (i <- 0 until l)\r\n {\r\n if(i != maxIndex) list = list:+ a(i).min(b(i))\r\n else list = list:+ (if (aMax >= bMax) b(maxIndex) else a(maxIndex))\r\n }\r\n return M * list.max \r\n }\r\n for(k <- 0 until T)\r\n {\r\n println(solve(as(k),bs(k), len(k)))\r\n } \r\n }\r\n}"}, {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n readInt()\n val a = readInts()\n val b = readInts()\n val (min, max) = a.zip(b).map {case (a, b) => (Math.min(a, b), Math.max(a, b))}.unzip\n \n println(min.max * max.max)\n }\n\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}], "negative_code": [{"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n readInt()\n val a = readInts()\n val b = readInts()\n val c = (a ++ b).sorted\n\n println(c.last * c(a.length - 1))\n }\n\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}], "src_uid": "56197d2468d8515e520c0d925874bf3b"} {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\n\nobject P361A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N, K = sc.nextInt\n\n def solve(): Unit = {\n 0 until N foreach { i =>\n val row = List.fill(i)(0) ::: List(K) ::: List.fill(N - 1 - i)(0)\n out.println(row.mkString(\" \"))\n }\n }\n\n solve\n out.close\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val res = (0 until n).map { i =>\n \"0 \" * i + k + \" \" + \"0 \" * (n - i - 1)\n }.mkString(\"\\n\")\n println(res)\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val nk = readLine().split(\" \").map(_.toInt)\n val n = nk(0)\n val k = nk(1)\n \n val m = k / n\n val d = k - m * n + m\n \n val a = Array.fill[Int](n)(m)\n for (i <- 1 to n) {\n a(i - 1) = d\n println(a.mkString(\" \"))\n a(i - 1) = m\n }\n }\n}"}], "negative_code": [], "src_uid": "e80088bee9c0df6adf280f8ffbeaa4a9"} {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine.toInt\n for (_ <- 0 until t) {\n val arr = StdIn.readLine.split(\" \").map(_.toLong)\n val (n, s) = (arr(0), arr(1))\n var d = -1\n var acc = 0\n for (c <- n.toString if (acc < s)) {\n acc += c - '0'; d += 1\n }\n val res = if (n.toString.toCharArray.map(_ - '0').sum <= s) 0\n else if (d == 0) {\n (\"1\" + \"0\" * n.toString.length).toLong - n\n } else {\n ((n.toString.take(d).toLong + 1).toString + \"0\" * (n.toString.length - d)).toLong - n\n }\n println(res)\n }\n }\n}\n", "positive_code": [{"source_code": "//package codeforces.contests._1409\n\nobject DecreaseTheSumOfDigits {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n\n val Array(n, g) = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val digits = n.toString.map(_ - '0')\n\n @scala.annotation.tailrec\n def loop(i: Int = digits.indices.last, carry: Int = 0, s: Int = digits.sum): Long = {\n if (i < 0) (\"1\" + \"0\" * digits.length).toLong - n\n else if (s <= g) ((digits.slice(0, i + 1).mkString(\"\").toLong + carry).toString + \"0\" * (digits.length - 1 - i)).toLong - n\n else loop(i - 1, if (carry == 0) 1 else 1, s - digits(i) + (if (carry == 0) 1 else 0))\n }\n\n println(loop())\n }\n }\n}\n"}], "negative_code": [{"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine.toInt\n for (_ <- 0 until t) {\n val arr = StdIn.readLine.split(\" \").map(_.toLong)\n val (n, s) = (arr(0), arr(1))\n var d = -1\n var acc = 0\n for (c <- n.toString if (acc < s)) {\n acc += c - '0'; d += 1\n }\n val res = if (d == 0) {\n (\"1\" + \"0\" * n.toString.length).toLong - n\n } else {\n ((n.toString.take(d).toLong + 1).toString + \"0\" * (n.toString.length - d)).toLong - n\n }\n println(res)\n }\n }\n}\n"}], "src_uid": "50738d19041f2e97e2e448eff3feed84"} {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val Array(_, x, y) = readLongs()\n val numbers = readLongs()\n val lastBit = (numbers.reduce(_ ^ _) ^ y) % 2\n val answer = if ( (x % 2) == lastBit ) \"Alice\" else \"Bob\"\n println(answer)\n }\n\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(var a: Int, var b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return (a).compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mapp = mutable.Map[pair, Int]()\n\n val t = readInt()\n\n for (tt <- 1 to t) {\n val n = readInt()\n val x = readLong()\n val y = readLong()\n var ans = x % 4L\n val k = y % 4L\n var a = 0\n for (i <- 1 to n) {\n a = readInt()\n ans = (ans + a) % 4\n }\n if (ans % 2 == k % 2) {\n writer.println(\"Alice\")\n } else {\n writer.println(\"Bob\")\n }\n\n\n def check(kk: Long, fi: Long): Boolean = {\n return false\n }\n def bs(st:Long, en:Long, fi:Long): Long = {\n if (en - st <= 1L) {\n if (check(st, fi))\n return st\n else\n return en\n }\n val mid = (st + en) / 2L\n if (check(mid, fi))\n return bs(st, mid, fi)\n else\n return bs(mid, en, fi)\n }\n }\n writer.flush()\n}"}], "negative_code": [], "src_uid": "d17752513405fc68d838e9b3792c7bef"} {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _712B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll}\n val instr = read[String]\n var x, y = 0\n\n instr foreach {\n case 'L' => x -= 1\n case 'R' => x += 1\n case 'U' => y += 1\n case 'D' => y -= 1\n }\n\n x = x.abs\n y = y.abs\n\n val ans = (x%2, y%2) match {\n case (0, 0) => x/2 + y/2\n case (0, 1) => -1\n case (1, 0) => -1\n case (1, 1) => x/2 + y/2 + 1\n }\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val str = in.next()\n if (str.length % 2 == 1)\n println(-1)\n else {\n val xDiff = Math.abs(str.count(_ == 'R') - str.count(_ == 'L'))\n val yDiff = Math.abs(str.count(_ == 'U') - str.count(_ == 'D'))\n println((xDiff + yDiff) / 2)\n }\n}\n"}, {"source_code": "object B712 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val in = read\n var u, d, r, l = 0\n for(c <- in) {\n if(c == 'U') u += 1\n else if(c == 'D') u -= 1\n else if(c == 'R') r += 1\n else if(c == 'L') r -= 1\n }\n if(in.length%2 == 0) {\n println((math.abs(u) + math.abs(r))/2)\n } else {\n println(\"-1\")\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "object B712 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val in = read\n var u, d, r, l = 0\n for(c <- in) {\n if(c == 'U') u += 1\n else if(c == 'D') d += 1\n else if(c == 'R') r += 1\n else if(c == 'L') l += 1\n }\n if(in.length%4 == 0) {\n val res = Array(u,d,r,l)\n .filter(in.length/4 > _)\n .map{x => in.length/4 - x}.sum\n println(res)\n } else {\n println(\"-1\")\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "8237ac3f3c2e79f5f70be1595630207e"} {"source_code": "import java.util\nimport java.util.regex.Pattern\n\nimport scala.io.StdIn\nimport scala.util.Sorting\n\nobject Solution {\n //Console.setIn(new FileReader(new java.io.File(\"in\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n\n val magicMod = 1000000007\n\n def doCase(caseNo: Int): Unit = {\n val _ = readInt()\n val str = readLine()\n\n if (str.length == 2 && Integer.valueOf(str.substring(1)) <= Integer.valueOf(str.substring(0, 1))) {\n println(\"NO\")\n return\n }\n\n println(\"YES\")\n println(2)\n println(s\"${str.charAt(0)} ${str.substring(1)}\")\n }\n\n def main(args: Array[String]): Unit = {\n val noCases = readInt()\n for (i <- 0 until noCases) {\n doCase(i)\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n def readLongLine(): Array[Long] = {\n StdIn.readLine().split(\" \").map(_.toLong)\n }\n\n def readBigIntLine(): Array[BigInt] = {\n StdIn.readLine().split(\" \").map(BigInt.apply)\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N = ni()\n val A = ns(N)\n if (A.length == 2 && A(0) >= A(1)) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n out.println(\"2\")\n out.println(s\"${A(0)} ${A.drop(1).mkString}\")\n }\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "\n\nobject Main {\n\n\n def compareStrings(lValue: String, rValue: String) = {\n\n if (lValue.length < rValue.length) {\n true\n }\n else if (lValue.length > rValue.length) {\n false\n }\n else {\n val index = lValue.zip(rValue).indexWhere(x => x._1 != x._2)\n if (index == -1) {\n false\n }\n else if (lValue(index).toInt < rValue(index).toInt) {\n true\n }\n else {\n false\n }\n }\n }\n\n def main(args: Array[String]) {\n\n val std = scala.io.StdIn\n val t = std.readLine().toInt\n\n for (_ <- 0 until t) {\n val value = std.readLine().toInt\n val seq = std.readLine()\n\n\n val index = seq.tail.indexWhere(x => x != '0')\n if (index != -1) {\n val first = seq.take(index + 1)\n val second = seq.drop(index + 1)\n if (compareStrings(first, second)) {\n println(\"YES\")\n println(2)\n println(first + \" \" + second)\n }\n else {\n println(\"NO\")\n }\n }\n else {\n println(\"NO\")\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "\n\nobject Main {\n\n\n def compareStrings(lValue: String, rValue: String) = {\n\n if (lValue.length < rValue.length) {\n true\n }\n else if (lValue.length > rValue.length) {\n false\n }\n else {\n val index = lValue.zip(rValue).indexWhere(x => x._1 != x._2)\n if (index == -1) {\n false\n }\n else if (lValue(index).toInt < rValue(index).toInt) {\n true\n }\n else {\n false\n }\n }\n }\n\n def main(args: Array[String]) {\n\n val std = scala.io.StdIn\n val t = std.readLine().toInt\n\n for (_ <- 0 until t) {\n val value = std.readLine().toInt\n val seq = std.readLine()\n\n\n val index = seq.tail.indexWhere(x => x != '0')\n if (index != -1) {\n val first = seq.take(index + 1)\n val second = seq.drop(index + 1)\n if (compareStrings(first, second)) {\n println(\"YES\")\n println(2)\n println(first, second)\n }\n else {\n println(\"NO\")\n }\n }\n else {\n println(\"NO\")\n }\n }\n }\n}\n\n"}, {"source_code": "object Main {\n\n def main(args: Array[String]) {\n\n val std = scala.io.StdIn\n val t = std.readLine().toInt\n\n for (_ <- 0 until t) {\n val value = std.readLine().toInt\n val seq = std.readLine().map(_.toInt)\n\n if (seq.length < 2) {\n println(\"NO\")\n }\n else if (seq.length == 2 && seq(0) >= seq(1)) {\n println(\"NO\")\n }\n else {\n println(\"YES\")\n println(2)\n println(seq.head.toChar, seq.tail.map(_.toChar).foldLeft(\"\")((x, y) => x + y))\n }\n }\n }\n}\n\n"}, {"source_code": "import java.util\nimport java.util.regex.Pattern\n\nimport scala.io.StdIn\nimport scala.util.Sorting\n\nobject Solution {\n //Console.setIn(new FileReader(new java.io.File(\"in\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n\n val magicMod = 1000000007\n\n def doCase(caseNo: Int): Unit = {\n val _ = readInt()\n val str = readLine()\n\n if (str.length == 2 && Integer.valueOf(str.substring(1)) <= Integer.valueOf(str.substring(0, 1))) {\n println(\"NO\")\n return\n }\n\n println(2)\n println(s\"${str.charAt(0)}, ${str.substring(1)}\")\n }\n\n def main(args: Array[String]): Unit = {\n val noCases = readInt()\n for (i <- 0 until noCases) {\n doCase(i)\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n def readLongLine(): Array[Long] = {\n StdIn.readLine().split(\" \").map(_.toLong)\n }\n\n def readBigIntLine(): Array[BigInt] = {\n StdIn.readLine().split(\" \").map(BigInt.apply)\n }\n}"}, {"source_code": "import java.util\nimport java.util.regex.Pattern\n\nimport scala.io.StdIn\nimport scala.util.Sorting\n\nobject Solution {\n //Console.setIn(new FileReader(new java.io.File(\"in\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n\n val magicMod = 1000000007\n\n def doCase(caseNo: Int): Unit = {\n val _ = readInt()\n val str = readLine()\n\n if (str.length == 2 && Integer.valueOf(str.substring(1)) <= Integer.valueOf(str.substring(0, 1))) {\n println(\"NO\")\n return\n }\n\n println(\"YES\")\n println(2)\n println(s\"${str.charAt(0)}, ${str.substring(1)}\")\n }\n\n def main(args: Array[String]): Unit = {\n val noCases = readInt()\n for (i <- 0 until noCases) {\n doCase(i)\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n def readLongLine(): Array[Long] = {\n StdIn.readLine().split(\" \").map(_.toLong)\n }\n\n def readBigIntLine(): Array[BigInt] = {\n StdIn.readLine().split(\" \").map(BigInt.apply)\n }\n}"}], "src_uid": "9f87a89c788bd7c7b66e51db9fe47e46"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val res = str.foldLeft(0, 0) {\n case ((sum, open), ')') if open == 0 => (sum + 1, open)\n case ((sum, open), ')') => (sum, open - 1)\n case ((sum, open), '(') => (sum, open + 1)\n }\n println(str.length - res._1 - res._2)\n}", "positive_code": [{"source_code": "object Main26B {\n\n def main(args: Array[String]) {\n def processChar(r: (Int, Int), c: Char): (Int, Int) = {\n val (a, b) = r\n if (c == '(')\n (a+1, b+1)\n else\n if (b > 0)\n (a+1, b-1)\n else\n (a, b)\n }\n val str = readLine\n val (result_a, result_b) = str.foldLeft(0, 0)(processChar)\n println(result_a - result_b)\n }\n\n}"}, {"source_code": "object P026B {\n def main(args: Array[String]) = {\n val s = readLine.map(x => -(x.toInt)*2 + 81)\n val n = s.size\n var l = n\n var sum = 0\n for (i <- 0 to n-1) {\n if (sum + s(i) >= 0) {\n sum += s(i)\n }\n else {\n l -= 1;\n }\n }\n println(l-sum)\n }\n}\n\n"}], "negative_code": [], "src_uid": "2ce2d0c4ac5e630bafad2127a1b589dd"} {"source_code": "/**\n * @author ShankarShastri\n * Algorithm: Problem1 (http://codeforces.com/contest/1028/problem/A)\n */\n\nimport scala.io.StdIn._\nimport scala.annotation.tailrec\n\nobject FindSquares {\n \n def findSquare(ls: List[String]): (Int, Int) = {\n val l = ls.zipWithIndex.map(l => (l._2, l._1.indexOf('B'),\n l._1.lastIndexOf('B')))\n .filter(t => t._2 != -1 && t._3 != -1).map(e => (e._1 + 1, e._2 + 1, e._3 + 1))\n val le = l(l.length / 2)\n (le._1, (le._2 + le._3) / 2)\n }\n \n def main(args: Array[String]): Unit = {\n val List(r,_) = readLine.replaceAll(\"\\\\s+$\", \"\").split(\" \").map(_.trim.toInt).toList\n val strList = (1 to r).map(_ => readLine).toList\n val res = findSquare(strList.map(_.trim))\n println(s\"${res._1} ${res._2}\")\n }\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N, M = sc.nextInt()\n var l, r, t, b = -1\n rep(N) { i =>\n val line = sc.next()\n rep(M) { j =>\n if (line(j) == 'B') {\n if (l == -1) l = j\n r = j\n if (t == -1) t = i\n b = i\n }\n }\n }\n\n out.println(s\"${(t + b) / 2 + 1} ${(l + r) / 2 + 1}\")\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}\n"}, {"source_code": "object Test extends App {\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n def stuff: Unit = {\n val n = nextInt\n val m = nextInt\n for (i <- 1 to n) {\n val cur = nextString\n if (cur.contains('B')) {\n val fst = cur.indexOf('B')\n val lst = cur.lastIndexOf('B')\n val (x, y) =\n if (fst == lst)\n i.toDouble -> (fst + 1).toDouble\n else {\n Math.ceil(i + (lst - fst) / 2) -> Math.ceil(((fst + lst) / 2) + 1)\n }\n out.println(x.toInt + \" \" + y.toInt)\n return\n }\n }\n }\n\n try {\n stuff\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}\n"}, {"source_code": "import scala.io._\n\nobject a5 {\n def main(args: Array[String]): Unit = {\n val lines = Source.stdin.getLines().drop(1).toArray\n val rows = lines.zipWithIndex.dropWhile(! _._1.contains(\"B\")).takeWhile(_._1.contains(\"B\"))\n val firstrow = rows.head._2+1\n val lastrow = rows.last._2+1\n val firstcol = rows.head._1.indexOf(\"B\")+1\n val lastcol = rows.head._1.lastIndexOf(\"B\")+1\n val (centerrow, centercol) = (firstrow + ((lastrow-firstrow)/2), firstcol + ((lastcol-firstcol)/2))\n println(s\"$centerrow $centercol\")\n }\n}"}], "negative_code": [], "src_uid": "524273686586cdeb7827ffc1ad59d85a"} {"source_code": "object A extends App {\n val n = readInt();\n val in = Array.fill(n)(readLine())\n var sa = Set[Char]()\n var sb = Set[Char]()\n for (i <- 0 until n; j <- 0 until n)\n if (i==j || n-i-1==j || i==n-j-1 || n-j-1==n-i-1) sa += in(i)(j);\n else sb += in(i)(j)\n\n if (sa.size == 1 && sb.size == 1 && sa.head != sb.head)\n println(\"YES\");\n else\n println(\"NO\")\n}\n\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _404A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (0 until n).map(i => next).toArray\n val ch = a(0)(0)\n val dish = a(0)(1)\n\n val cb = for {\n i <- 0 until n\n j <- 0 until n\n } yield if (i == j || n - 1 - i == j) a(i)(j) == ch else a(i)(j) == dish\n\n if (ch != dish && cb.forall(i => i)) println(\"YES\")\n else println(\"NO\")\n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val k = in.next().toInt\n val data = Range(0, k).map { i => (i, in.next())}\n val symbols = data.head._2.toSet\n val symbol = data.head._2.head\n if (symbols.size != 2) println(\"NO\")\n else {\n val r = data.forall{\n case(i, str) =>\n val count = str.count(_ == symbol)\n str.forall(symbols) && count < 3 && str.charAt(i) == symbol && str.charAt(str.length - i - 1) == symbol && {\n i != str.length - i - 1 || count == 1\n }\n }\n if (r)\n println(\"YES\")\n else\n println(\"NO\")\n }\n\n}"}, {"source_code": "object A404 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = Array.fill(n)(read.toCharArray)\n var xChar = in(0)(0)\n var diffChar = in(1)(0)\n var ifX = true\n var ifDiff = true\n for(i <- 0 until n; j <- 0 until n) {\n if(i == j) {// diagonal 1\n ifX &= in(i)(j) == xChar\n } else if(i + j == n-1) {// diagonal 2\n ifX &= in(i)(j) == xChar\n } else {\n ifDiff &= in(i)(j) == diffChar\n }\n }\n\n if (xChar != diffChar && ifDiff && ifX) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P404A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n type Row = List[Char]\n\n val N = sc.nextInt\n sc.nextLine\n val P: List[Row] = List.fill(N)(sc.nextLine.toList)\n\n def solve(): String = {\n\n P(0) match {\n \n case x :: y :: _ if x != y => {\n\n def row(n: Int): Row = {\n List.range(0, N).map { i =>\n if (i == n || i == N - n - 1) x\n else y\n }\n }\n\n if (P == List.range(0, N).map(row)) \"YES\"\n else \"NO\"\n }\n case _ => \"NO\"\n }\n }\n \n out.println(solve)\n out.close\n}\n"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _404A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (0 until n).map(i => next).toArray\n val ch = a(0)(0)\n val dish = a(0)(1)\n\n val cb = for {\n i <- 0 until n\n j <- 0 until n\n } yield if (i == j || n - 1 - i == j) a(i)(j) == ch else a(i)(j) == dish\n\n if (cb.forall(i => i)) println(\"YES\")\n else println(\"NO\")\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _404A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (0 until n).map(i => next).toArray\n val ch = a(0)(0)\n val dish = a(0)(1)\n\n val cb = for {\n i <- 0 until n\n j <- 0 until n\n } yield if (i == j || n - 1 - i == j) a(i)(j) == ch else a(i)(j) == dish\n\n if (cb != dish && cb.forall(i => i)) println(\"YES\")\n else println(\"NO\")\n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val k = in.next().toInt\n val data = Range(0, k).map { i => (i, in.next())}\n val symbols = data.head._2.toSet\n val symbol = data.head._2.head\n if (symbols.size != 2) println(\"NO\")\n else {\n val r = data.forall{\n case(i, str) =>\n val count = str.count(_ == symbol)\n str.forall(symbols) && count < 3 && str.charAt(i) == symbol && str.charAt(str.length - i - 1) == symbol\n }\n if (r)\n println(\"YES\")\n else\n println(\"NO\")\n }\n\n}"}, {"source_code": "object A404 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = Array.fill(n)(read.toCharArray)\n var xChar = in(0)(0)\n var diffChar = in(1)(0)\n var ifX = true\n var ifDiff = true\n for(i <- 0 until n; j <- 0 until n) {\n if(i == j) {// diagonal 1\n ifX &= in(i)(j) == xChar\n } else if(i + j == n-1) {// diagonal 2\n ifX &= in(i)(j) == xChar\n } else {\n ifDiff &= in(i)(j) == diffChar\n }\n }\n\n if (ifDiff && ifX) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P404A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n type Row = List[Char]\n\n val N = sc.nextInt\n sc.nextLine\n val P: List[Row] = List.fill(N)(sc.nextLine.toList)\n\n def solve(): String = {\n val (x, y) = (P(0)(0), P(0)(1))\n\n def row(n: Int): Row = {\n List.range(0, N).map { i =>\n if (i == n || i == N - n - 1) x\n else y\n }\n }\n\n if (P == List.range(0, N).map(row)) \"YES\"\n else \"NO\"\n }\n \n out.println(solve)\n out.close\n}\n"}], "src_uid": "02a9081aed29ea92aae13950a6d48325"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val S = ns(N)\n val COLOR = \"RGB\"\n\n var best = 1e9.toInt + 10\n var ans: (Int, Int, Int) = null\n\n def calc(i: Int, j: Int, k: Int): Int = {\n var changed = 0\n val c = Array(i, j, k)\n REP(N) { l =>\n if (S(l) != COLOR(c(l % 3))) changed += 1\n }\n changed\n }\n\n REP(3) { i =>\n REP(3) { j =>\n REP(3) { k =>\n if (i != j && j != k && i != k) {\n val v = calc(i, j, k)\n if (v < best) {\n best = v\n ans = (i, j, k)\n }\n }\n }\n }\n }\n\n out.println(best)\n val c = Array(ans._1, ans._2, ans._3)\n REP(N) { i =>\n out.print(COLOR(c(i % 3)))\n }\n out.println()\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "//package codeforces.contest1108\n\n/*\nhttp://codeforces.com/contest/1108/problem/C\n */\nobject NiceGarland {\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val str = io.StdIn.readLine()\n\n val maxZeroes = n / 3 + (if (n % 3 >= 1) 1 else 0)\n val maxOnes = n / 3 + (if (n % 3 == 2) 1 else 0) // 1 2 3, 4 5 6, 7 8 9\n val maxTwos = n / 3\n\n def count(c: Char): Array[Int] = {\n Array(maxZeroes - (0 until n by 3).count(str(_) == c), maxOnes - (1 until n by 3).count(str(_) == c), maxTwos - (2 until n by 3).count(str(_) == c))\n }\n\n val redCost = count('R')\n val blueCost = count('B')\n val greenCost = count('G')\n\n val (optimalPermutation: String, cost: Int) = Set[String](\"RGB\", \"RBG\", \"BGR\", \"BRG\", \"GRB\", \"GBR\")\n .map(s =>\n (s, s.zipWithIndex.foldLeft(0) {\n case (acc: Int, (c: Char, i: Int)) =>\n acc + (c match {\n case 'R' => redCost(i)\n case 'B' => blueCost(i)\n case 'G' => greenCost(i)\n })\n })).minBy(_._2)\n\n val result = str.toCharArray\n\n optimalPermutation.zipWithIndex.foreach { case (c, i) => fix(i, c) }\n\n def fix(startingFrom: Int, withColor: Char): Unit = {\n (startingFrom until n by 3).foreach(result(_) = withColor)\n }\n\n println(cost + \" \" + result.mkString(\"\"))\n }\n}\n"}, {"source_code": "object CF_535_3_C {\n// date: 25/01/2019\n\n type In = (Int, String)\n type Out = String\n \n def solve(in: In): Out = {\n val (n, s) = in\n // Assume starts with each of R G B\n val cs1 = Vector('R','G','B')\n val cs2 = Vector('R','B','G')\n val ss1 = Stream.iterate(0)(i => (i + 1)%3).map(cs1)\n val ss2 = Stream.iterate(0)(i => (i + 1)%3).map(cs2)\n\n def differences(xs: Seq[Char], ys: Seq[Char]) = (xs, ys).zipped.count(i => i._1 != i._2)\n\n val results = for {\n order: Stream[Char] <- Vector(ss1, ss2)\n start <- Seq(order, order.drop(1), order.drop(2))\n seq = start.take(n)\n } yield (seq, differences(seq, s))\n\n val res = results.minBy(_._2)\n res._2.toString + \"\\n\" +\n res._1.mkString\n\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, {i.nextLine; i.nextLine})\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n // `a` MUST be > 0. Incorrect otherwise.\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}], "negative_code": [], "src_uid": "e67b79e39511b0107a51edc0179afb82"} {"source_code": "import scala.collection._\nimport scala.collection.mutable.ListBuffer\n\nobject HongcowBS2 extends App {\n\n val tokens = scala.io.Source.stdin.getLines\n .flatMap( _ split ' ' filter (_.nonEmpty))\n\n def nextInt() = tokens.next().toInt\n\n def getLinksNum(n: Int) = if (n == 1) 0 else n * (n - 1) / 2\n\n val n, m, k = nextInt()\n\n if (k == 1) {\n println(getLinksNum(n) - m)\n } else if (m == 0) {\n println(getLinksNum(n - k + 1))\n } else {\n\n val governments = (0 until k).map{ _ =>\n val k = nextInt()\n k -> mutable.BitSet(k)\n }.toMap\n\n var freeLinks = ListBuffer[Array[Int]]()\n for (_ <- 0 until m) {\n val link = Array(nextInt(), nextInt())\n if (governments.contains(link(0))) {\n governments.get(link(0)).get += link(1)\n } else if (governments.contains(link(1))) {\n governments.get(link(1)).get += link(0)\n } else {\n freeLinks += link\n }\n }\n\n var continue = true\n while (continue) {\n val remainingLinks = ListBuffer[Array[Int]]()\n for (link <- freeLinks) {\n val entry = governments.find { p =>\n (p._2.contains(link(0))\n || p._2.contains(link(1)))\n }\n if (entry.isEmpty) remainingLinks += link\n else entry.get._2 += (link(0), link(1))\n }\n if (remainingLinks.size == freeLinks.size) continue = false\n else freeLinks = remainingLinks\n }\n\n val govCounts = governments.values.map(_.size).toArray\n val maxIndex = govCounts.indexOf(govCounts.max)\n val freeCount = n - govCounts.sum\n govCounts(maxIndex) = govCounts(maxIndex) + freeCount\n val result = govCounts.map(getLinksNum).sum - m\n println(result)\n }\n}", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.collection.mutable\n\nobject A extends App {\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n\n read()\n val n = st.nextToken().toInt\n val m = st.nextToken().toInt\n val k = st.nextToken().toInt\n\n read()\n val capitals = Array.fill(k)(st.nextToken().toInt - 1)\n\n var links = Array.fill(n)(List.empty[Int])\n var a = 0\n var b = 0\n (1 to m).foreach { _ =>\n read()\n a = st.nextToken().toInt - 1\n b = st.nextToken().toInt - 1\n links(a) = b :: links(a)\n links(b) = a :: links(b)\n }\n\n var visited = Array.fill(n)(false)\n\n var stack = new mutable.Stack[Int]\n def count(capital: Int): Int = {\n b = 0\n stack.push(capital)\n while (stack.nonEmpty) {\n a = stack.pop()\n if (!visited(a)) {\n b += 1\n visited(a) = true\n links(a).foreach(stack.push)\n }\n }\n b\n }\n\n var groups = capitals.map(count)\n val total = groups.sum\n val free = n - total\n val max = groups.max\n\n def maxForGroup(c: Int) = c * (c-1) / 2\n\n val maxLinks = groups.map(maxForGroup).sum + maxForGroup(max + free) - maxForGroup(max)\n val ans = maxLinks - m\n\n println(ans)\n\n}\n"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLine\n\nobject HongcowBS extends App {\n \n def getLinksNum(n: Int) = if (n == 1) 0 else n * (n - 1) / 2\n\n val Array(n, m, k) = readLine.split(\" \").map(_.toInt)\n\n if (k == 1) {\n println(getLinksNum(n) - m)\n } else if (m == 0) {\n println(getLinksNum(n - k + 1))\n } else {\n val governments = readLine.split(\" \").map { e =>\n val k = e.toInt\n k -> mutable.BitSet(k)\n }.toMap\n\n var freeLinks = ListBuffer[Array[Int]]()\n for (_ <- 0 until m) {\n val link = readLine.split(\" \").map(_.toInt)\n val Array(a, b) = link\n if (governments.contains(link(0))) {\n governments.get(link(0)).get += link(1)\n } else if (governments.contains(link(1))) {\n governments.get(link(1)).get += link(0)\n } else {\n freeLinks += link\n }\n }\n\n var continue = true\n while (continue) {\n val remainingLinks = ListBuffer[Array[Int]]()\n for (link <- freeLinks) {\n val entry = governments.find { p =>\n (p._2.contains(link(0))\n || p._2.contains(link(1)))\n }\n if (entry.isEmpty) remainingLinks += link\n else entry.get._2 += (link(0), link(1))\n }\n if (remainingLinks.size == freeLinks.size) continue = false\n else freeLinks = remainingLinks\n }\n\n val govCounts = governments.values.map(_.size).toArray\n val maxIndex = govCounts.indexOf(govCounts.max)\n val freeCount = n - govCounts.sum\n govCounts(maxIndex) = govCounts(maxIndex) + freeCount\n val result = govCounts.map(getLinksNum).sum - m\n println(result)\n }\n}"}], "negative_code": [{"source_code": "\nimport scala.io.StdIn.readLine\n\nobject HongCowBuild extends App {\n\n def getLinksNum(n: Int) = if (n == 1) 0 else n * (n - 1) / 2\n\n def readLinksAndGetLinkedNodes(m: Int) = {\n var linkedNodes = 0\n (0 until m).foreach { _ =>\n val Array(s, d) = readLine.split(\" \").map(_.toInt)\n if (govNodes.contains(s)) {\n govNodes.put(s, govNodes.get(s).get + 1)\n linkedNodes += 1\n }else if (govNodes.contains(d)){\n govNodes.put(d, govNodes.get(d).get + 1)\n linkedNodes += 1\n }\n }\n linkedNodes\n }\n\n val Array(n, m, k) = readLine.split(\" \").map(_.toInt)\n val governments = readLine.split(\" \").map(_.toInt)\n val govNodes = collection.mutable.HashMap[Int, Int]()\n\n governments.foreach(govNodes.put(_, 1))\n var linkedNodes = readLinksAndGetLinkedNodes(m)\n val maxGov = govNodes.maxBy(_._2)\n val remained = n - k - linkedNodes\n val maxGovSum = getLinksNum(govNodes.remove(maxGov._1).get + remained)\n val allSum = govNodes.map(e => getLinksNum(e._2)).sum\n val result = allSum + maxGovSum - m\n println(result)\n}\n"}, {"source_code": "\nimport scala.io.StdIn.readLine\n\nobject Hongcow extends App {\n\n def getLinksNum(n: Int) = if (n == 1) 0 else n * (n - 1) / 2\n\n def readLinks(m: Int) = {\n var freeLinks = 0\n (0 until m).foreach { _ =>\n val Array(s, d) = readLine.split(\" \").map(_.toInt)\n if (govNodes.contains(s))\n govNodes.put(s, govNodes.get(s).get + 1)\n else if (govNodes.contains(d))\n govNodes.put(d, govNodes.get(d).get + 1)\n else freeLinks += 1\n }\n freeLinks\n }\n\n val Array(n, m, k) = readLine.split(\" \").map(_.toInt)\n val governments = readLine.split(\" \").map(_.toInt)\n val govNodes = collection.mutable.HashMap[Int, Int]()\n governments.foreach(govNodes.put(_, 0))\n var freeLinks = readLinks(m)\n val maxGov = govNodes.maxBy(_._2)\n val maxGovSum = getLinksNum(govNodes.remove(maxGov._2).get)\n val allSum = govNodes.map(e => getLinksNum(e._2)).sum\n val result = allSum + maxGovSum - m\n println(result)\n}\n"}], "src_uid": "6cf43241b14e4d41ad5b36572f3b3663"} {"source_code": "import scala.math.BigDecimal.RoundingMode\n\nobject Solution {\n val pattern = \"\"\"(\\d+) (\\d+) (\\d+) (\\d+)\"\"\".r\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toLong\n\n (1L to t)\n .map(i => readLine())\n .map(findSolution)\n .foreach(println)\n }\n\n def findSolution(line: String): Long = {\n val pattern(x, y, p, q) = line\n val suc = x.toLong\n val total = y.toLong\n val denom = p.toLong\n val numer = q.toLong\n\n if (denom == 0 && suc == 0)\n 0 else\n if (denom == 0 && suc != 0)\n -1 else\n if (denom == numer && suc == total)\n 0 else\n if (denom == numer && suc != total)\n -1\n else {\n val k = ((BigDecimal(suc) / denom) setScale(0, RoundingMode.CEILING)).toLong max\n ((BigDecimal(total) / numer) setScale(0, RoundingMode.CEILING)).toLong max\n ((BigDecimal(total - suc) / (numer - denom)) setScale(0, RoundingMode.CEILING)).toLong\n val toSolveSuc = denom * k - suc\n val toSolveUnsuc = numer * k - total - toSolveSuc\n\n toSolveSuc + toSolveUnsuc\n }\n }\n}\n\n", "positive_code": [{"source_code": "//package p807\n\n/**\n * Created by velizar on 16/05/17.\n */\nobject C extends App {\n import scala.io.Source\n\n val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(\" \").map(_.toLong))\n val Array(t) = input(0)\n\n val maxValue = 2000000000000000000l\n\n def search(from: Long, to: Long, x: Long, y: Long, p: Long, q: Long): Long = {\n val current = (from + to) / 2\n// println((from, current, to))\n val currentLB = x\n val currentUB = current * q - y + x\n val currentDesired = current * p\n val inBounds = currentLB <= currentDesired && currentDesired <= currentUB\n if (inBounds && from == to)\n current * q - y\n else if (inBounds)\n search(from, current, x, y, p, q)\n else\n search(current + 1, to, x, y, p, q)\n }\n\n val output = input.drop(1).map {\n case Array(x, y, p, q) if y % q == 0 && p * (y / q) == x => 0\n case Array(_, _, 0, 1) => -1\n case Array(_, _, 1, 1) => -1\n case Array(x, y, p, q) =>\n// println((x, y, p, q))\n search(y / q + 1, maxValue / q, x, y, p, q)\n }.mkString(\"\\n\")\n print(output)\n}\n"}, {"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n\n val Array(n) = readInts(1)\n\n for (_ <- 0 until n) {\n val Array(x, y, p, q) = readLongs(4)\n\n if ((p == q && x < y) || (p == 0 && x > 0)) {\n println(-1)\n } else {\n\n def can(n: Long): Boolean = {\n val b = q * n - y\n val a = p * n - x\n a >= 0 && a <= b\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (can(mid)) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val n = binSearch(1, Int.MaxValue)\n\n val b = q * n - y\n\n println(b)\n }\n }\n}\n"}], "negative_code": [{"source_code": "//package p807\n\n/**\n * Created by velizar on 16/05/17.\n */\nobject C extends App {\n import scala.io.Source\n\n val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(\" \").map(_.toInt))\n val Array(t) = input(0)\n\n// def succ(x: Int, y: Int) = x\n// def failed(x: Int, y: Int) = y - x\n\n def search(from: Int, to: Int, x: Int, y: Int, p: Int, q: Int): Int = {\n val currentD = (from + to) / 2.0\n val current = (if (scala.util.Random.nextBoolean()) currentD.floor else currentD.ceil).toInt\n val currentLB = x\n val currentUB = current * q - y + x\n val currentDesired = current * p\n val inBounds = currentLB <= currentDesired && currentDesired <= currentUB\n if (inBounds && from == to)\n current * q - y\n else if (inBounds)\n search(from, current, x, y, p, q)\n else\n search(current + 1, to, x, y, p, q)\n }\n\n val maxValue = 2000000000\n def solve(x: Int, y: Int, p: Int, q: Int): Int = {\n if (y % q == 0 && p * (y / q) == x)\n 0\n else\n search(y / q + 1, maxValue / q, x, y, p, q)\n }\n\n val output = input.drop(1).map {\n case Array(_, _, 0, 1) => -1\n case Array(_, _, 1, 1) => -1\n case Array(x, y, p, q) => solve(x, y, p, q)\n }.mkString(\"\\n\")\n print(output)\n}\n"}, {"source_code": "//package p807\n\n/**\n * Created by velizar on 16/05/17.\n */\nobject C extends App {\n import scala.io.Source\n\n val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(\" \").map(_.toInt))\n val Array(t) = input(0)\n\n// def succ(x: Int, y: Int) = x\n// def failed(x: Int, y: Int) = y - x\n\n def search(from: Int, to: Int, x: Int, y: Int, p: Int, q: Int): Int = {\n val currentD = (from + to) / 2.0\n val current = (if (scala.util.Random.nextBoolean()) currentD.floor else currentD.ceil).toInt\n val currentLB = x\n val currentUB = current * q - y + x\n val currentDesired = current * p\n val inBounds = currentLB <= currentDesired && currentDesired <= currentUB\n if (inBounds && from == to)\n current * q - y\n else if (inBounds)\n search(from, current, x, y, p, q)\n else\n search(current + 1, to, x, y, p, q)\n }\n\n val maxValue = 2000000000\n def solve(x: Int, y: Int, p: Int, q: Int): Int = {\n if (y % q == 0 && p * (y / q) == x)\n 0\n else\n search(y / q + 1, maxValue / q, x, y, p, q)\n }\n\n val output = input.drop(1).map {\n case Array(x, y, p, q) if x == p && y == q => 0\n case Array(_, _, 0, 1) => -1\n case Array(_, _, 1, 1) => -1\n case Array(x, y, p, q) => solve(x, y, p, q)\n }.mkString(\"\\n\")\n print(output)\n}\n"}], "src_uid": "589f3f7366d1e0f9185ed0926f5a10bb"} {"source_code": "import java.io._\r\nimport scala.collection.immutable.TreeSet\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val reader = new BufferedReader(new java.io.InputStreamReader(System.in))\r\n val writer = new PrintWriter(System.out)\r\n def readInt(): Int = reader.readLine().toInt\r\n def readLong(): Long = reader.readLine().toLong\r\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\r\n def readArrayLong(): Array[Long] = reader.readLine().split(\" \").map(_.toLong)\r\n def readString(): String = reader.readLine()\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n\r\n def solve(t: Int = 0): Unit = {\r\n val n = readInt()\r\n val a = readString().split(\"\").map(_.toInt)\r\n val b = readString().split(\"\").map(_.toInt)\r\n\r\n var count = 0\r\n for (i <- 0 until n) {\r\n if (a(i) == 0) {\r\n if (b(i) == 1) {\r\n count += 1\r\n b(i) = 0\r\n }\r\n } else {\r\n if (i - 1 >= 0 && b(i - 1) == 1)\r\n count += 1\r\n else if (i + 1 < n && b(i + 1) == 1) {\r\n count += 1\r\n b(i + 1) = 0\r\n }\r\n }\r\n }\r\n\r\n writer.println(count)\r\n\r\n }\r\n\r\n def main(args: Array[String]) {\r\n multiTest(solve)\r\n //solve()\r\n writer.flush()\r\n }\r\n}", "positive_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val tn = readLine().split(\"\").map(_.toInt)\r\n val bn = readLine().split(\"\").map(_.toInt)\r\n\r\n val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {\r\n case ((count, 1, 1), (1, 1)) => (count + 2, 0, 0)\r\n case ((count, 1, 1), (1, 0)) => (count + 1, 0, 0)\r\n case ((count, 1, 0), (1, 1)) => (count + 1, 1, 0)\r\n case ((count, _, _), (0, 1)) => (count + 1, 0, 0)\r\n case ((count, _, _), (ti, bi)) => (count, ti, bi)\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val tn = readLine().split(\"\").map(_.toInt)\r\n val bn = readLine().split(\"\").map(_.toInt)\r\n\r\n val (tm, bm) = (tn zip bn).map {\r\n case (0, 1) => (1, 0)\r\n case (t, b) => (t, b)\r\n }.unzip\r\n\r\n val (ans, _, _) = (tm zip bm).foldLeft((tm.count(_ == 1) - tn.count(_ == 1), 0, 0)) {\r\n case ((c, 1, 1), (1, 1)) => (c + 2, 1, 0)\r\n case ((c, 1, 1), (1, 0)) => (c + 1, 1, 0)\r\n case ((c, 1, 0), (1, 1)) => (c + 1, 1, 0)\r\n case ((c, _, _), (x, y)) => (c, x, y)\r\n }\r\n\r\n println(ans)\r\n\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val tn = readLine().split(\"\").map(_.toInt)\r\n val bn = readLine().split(\"\").map(_.toInt)\r\n\r\n val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {\r\n case ((count, 1, 1), (1, 1)) => (count + 2, 1, 0)\r\n case ((count, 1, 1), (1, 0)) => (count + 1, 1, 0)\r\n case ((count, 1, 1), (0, 1)) => (count + 2, 1, 0)\r\n case ((count, 1, 1), (0, 0)) => (count, 0, 0)\r\n\r\n case ((count, 1, 0), (1, 1)) => (count + 1, 1, 0)\r\n case ((count, 1, 0), (1, 0)) => (count, 1, 0)\r\n case ((count, 1, 0), (0, 1)) => (count + 1, 1, 0)\r\n case ((count, 1, 0), (0, 0)) => (count, 0, 0)\r\n\r\n case ((count, _, _), (0, 1)) => (count + 1, 1, 0)\r\n\r\n case ((count, _, _), (ti, bi)) => (count, ti, bi)\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val tn = readLine().split(\"\").map(_.toInt)\r\n val bn = readLine().split(\"\").map(_.toInt)\r\n\r\n val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {\r\n case ((count, 1, 1), (_, 1)) => (count + 2, 1, 0)\r\n case ((count, 1, 1), (1, _)) => (count + 1, 1, 0)\r\n case ((count, 1, 0), (_, 1)) => (count + 1, 1, 0)\r\n case ((count, _, _), (0, 1)) => (count + 1, 1, 0)\r\n case ((count, _, _), (ti, bi)) => (count, ti, bi)\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val tn = readLine().split(\"\").map(_.toInt)\r\n val bn = readLine().split(\"\").map(_.toInt)\r\n\r\n val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {\r\n case ((count, 1, 1), (_, 1)) => (count + 2, 1, 0)\r\n case ((count, 1, 0), (_, 1)) => (count + 1, 1, 0)\r\n case ((count, 0, 0), (0, 1)) => (count + 1, 1, 0)\r\n case ((count, _, _), (ti, bi)) => (count, ti, bi)\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val tn = readLine().split(\"\").map(_.toInt)\r\n val bn = readLine().split(\"\").map(_.toInt)\r\n\r\n val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {\r\n case ((count, 1, 1), (_, 1)) => (count + 2, 1, 0)\r\n case ((count, 1, _), (1, 1)) => (count + 1, 1, 0)\r\n case ((count, _, _), (0, 1)) => (count + 1, 1, 0)\r\n case ((count, _, _), (ti, bi)) => (count, ti, bi)\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val tn = readLine().split(\"\").map(_.toInt)\r\n val bn = readLine().split(\"\").map(_.toInt)\r\n\r\n val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {\r\n case ((count, 1, 1), (_, 1)) => (count + 2, 1, 0)\r\n case ((count, _, _), (0, 1)) => (count + 1, 1, 0)\r\n case ((count, _, _), (ti, bi)) => (count, ti, bi)\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val tn = readLine().split(\"\").map(_.toInt)\r\n val bn = readLine().split(\"\").map(_.toInt)\r\n\r\n val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {\r\n case ((count, 1, 1), (_, 1)) => (count + 2, 1, 0)\r\n case ((count, 1, _), (ti, 1)) => (count + 1, ti, 0)\r\n case ((count, _, 1), (1, bi)) => (count + 1, 1, bi)\r\n case ((count, _, _), (0, 1)) => (count + 1, 1, 0)\r\n case ((count, _, _), (ti, bi)) => (count, ti, bi)\r\n\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "src_uid": "c05426881a7dccc1aa79608b612290a7"} {"source_code": "\n\nobject Taxi {\n\tvar availableCars = collection.mutable.Map[Int,Int]((1,0), (2,0), (3,0))\n\n\t\t\tdef addCar (index: Int) {\n\t\tavailableCars += index -> (availableCars(index) + 1)\n\t}\n\n\tdef removeCar (index: Int) {\n\t\tavailableCars += index -> (availableCars(index) - 1)\n\t}\n\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in)\n\t\t\t\tval n = scanner.nextInt\n\t\t\t\tvar number = 0\n\t\t\t\tfor (i <- 1 to n) {\n\t\t\t\t\tval current = scanner.nextInt\n\t\t\t\t\t\t\tcurrent match {\n\t\t\t\t\t\t\tcase 4 =>\n\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\tcase 3 =>\n\t\t\t\t\t\t\tif (availableCars(1) > 0) {\n\t\t\t\t\t\t\t\tremoveCar(1)\n\t\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddCar(3)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase 2 =>\n\t\t\t\t\t\t\tif (availableCars(2) > 0) {\n\t\t\t\t\t\t\t\tremoveCar(2)\n\t\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddCar(2)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase 1 =>\n\t\t\t\t\t\t\tif (availableCars(3) > 0) {\n\t\t\t\t\t\t\t\tremoveCar(3)\n\t\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\taddCar(1)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\twhile (availableCars(3) > 0 && availableCars(1) > 0) {\n\t\t\tnumber = number + 1\n\t\t\t\t\tremoveCar(3)\n\t\t\t\t\tremoveCar(1)\n\t\t}\n\t\twhile (availableCars(2) > 1) {\n\t\t\tval div2 = availableCars(2) / 2\n\t\t\t\t\tnumber = number + div2\n\t\t\t\t\tavailableCars += 2 -> availableCars(2) % 2\n\t\t}\n\t\tif (availableCars(2) == 1) {\n\t\t\tremoveCar(2)\n\t\t\tif (availableCars(1) >= 2) {\n\t\t\t\tremoveCar(1)\n\t\t\t\tremoveCar(1)\n\t\t\t}\n\t\t\telse {\n\t\t\t\tavailableCars += 1 -> 0\n\t\t\t}\n\t\t\tnumber = number + 1\n\t\t}\n\n\t\tnumber = number + availableCars(1) / 4 \n\t\tavailableCars += 1 -> availableCars(1) % 4\n\t\t\t\tif (availableCars(1) > 0)\n\t\t\t\t{\n\t\t\t\t number = number + 1\n\t\t\t\t availableCars += 1 -> 0\n\n\t\t\t\t}\n/**\n\t\t\t\tprintln(\"------------\")\n\t\t\t\tprintln(\"number: \"+number)\n\t\t\t\tprintln(\"availableCars: \"+availableCars)\n\t\t\t\tprintln(\"------------\")\n\t\t**/\t\t\n\t\t\t\tprintln(number+availableCars(3)+availableCars(2)+availableCars(1))\n\t}\n}", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P158B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val g = Array.fill(5)(0)\n val s = List.fill(N)(sc.nextInt)\n s foreach (g(_) += 1)\n \n var t = g(4) + g(3)\n g(1) -= g(3)\n t += g(2) / 2\n if (g(2) % 2 == 1) {\n t += 1\n g(1) -= 2\n }\n if (g(1) > 0) t += (g(1) - 1) / 4 + 1\n \n out.println(t)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject R158_B extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n val groups = for(i <- 0 until n) yield sc.nextInt()\n\n println(process(groups))\n\n def process(groups:Seq[Int]):Int = {\n var a = new Array[Int](4)\n groups.foreach(g => {\n val k = g-1\n a(k)=a(k)+1\n })\n var c = 0\n c += a(3)\n c += a(2)\n if(a(2)2){\n a(0)=a(0)-2\n }else{\n a(0)=0\n }\n }\n c += (a(0)+3)/4\n c\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject B {\n val in = new Scanner(System.in)\n\n def main(args: Array[String]) {\n val n = in.nextInt()\n val s = Array.fill[Int](n)(in.nextInt())\n val count = Array.ofDim[Int](5)\n s.foreach((x) => count(x) += 1)\n var result = 0;\n result += count(4)\n result += count(3)\n count(1) = (count(1) - count(3)) max 0\n result += (2 * count(2) + count(1) + 3) / 4\n println(result)\n }\n}\n"}, {"source_code": "// CodeForces 158 B\n\nobject Taxi extends App {\n val ln0 = (Console.readLine()).split(\" \") map (_.toInt)\n val n = ln0(0)\n val s = (Console.readLine()).split(\" \") map (_.toInt)\n var nga:Array[Int] = Array.fill(5)(0) // numbers of Taxi with given number of \n \n def countgroups():Unit = {\n for (val i <- 0 until n) {\n nga(s(i)) = nga(s(i)) + 1\n }\n }\n \n countgroups()\n var nt = nga(4)\n nt = nt + nga(3)\n if (nga(1) > nga(3)) {\n nga(1) = nga(1) - nga(3)\n } else {\n nga(1) = 0\n }\n val n1 = nga(1) + 2*nga(2)\n val n4 = n1/4 \n nt = nt + n4\n if (n1 > n4*4) {\n nt = nt+1\n } \n println(nt)\n}"}, {"source_code": "object Taxi extends App {\n import java.util.{Scanner => Input}\n\n val in = new Input(System.in)\n val n = in nextInt\n val count = new Array[Int](5)\n for (i <- 1 to n)\n count(in nextInt) += 1\n\n var ans = count(4)\n\n def min = (x:Int, y:Int) => if (x < y) x else y\n\n ans += count(3)\n count(1) -= min(count(3), count(1))\n\n ans += count(2) / 2\n if (count(2) % 2 == 1) {\n ans += 1\n count(1) -= min(2, count(1))\n }\n\n ans += (count(1) + 3) / 4\n\n println(ans)\n}\n"}, {"source_code": "object Codeforces158B extends App{\n\n def TaxiNumber(ques:String):Int={\n var ans:Int=0\n val conv=ques.split(\" \").map(_.toInt)\n var numset:Array[Int]=Array(0,0,0,0,0)\n for (i <- conv){\n numset(i)+=1\n }\n ans+=numset(4)\n if (numset(3)<=numset(1)){\n ans+=numset(3)\n var temp=numset(1)-numset(3)\n if (numset(2)%2==0){\n ans+=numset(2)/2\n ans+=temp/4\n if (temp%4!=0){\n ans+=1\n }\n }\n else{\n ans+=numset(2)/2+1\n temp-=2\n if (temp>0){\n ans+=temp/4\n if (temp%4!=0){\n ans+=1\n }\n }\n }\n }\n else{\n ans+=numset(3)\n ans+=numset(2)/2\n if (numset(2)%2==1){\n ans+=1\n }\n }\n return ans\n }\n\n val s:Int=scala.io.StdIn.readInt\n val k=scala.io.StdIn.readLine\n println(TaxiNumber(k))\n\n}\n"}, {"source_code": "import java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def main(args: Array[String]) {\n reader.readLine()\n val cnt = readInts.groupBy(x => x).mapValues(_.length)\n def c(x: Int) = cnt.getOrElse(x, 0)\n def ceil(a: Int, b: Int) = if (a % b == 0) a / b else a / b + 1\n println(c(4) + c(3) + c(2) / 2 + c(2) % 2 + ceil(Math.max(0, c(1) - c(3) - 2 * (c(2) % 2)), 4))\n }\n}\n"}, {"source_code": "/**\n * Created by vol on 9/16/14.\n */\nobject B158 extends App{\n val n = readInt()\n val friends = readLine().split(\" \").map(_.toInt)\n val counts = friends.foldLeft(Map(1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0)) {\n (count, fr) => count + (fr -> (count.getOrElse(fr, 0) + 1))\n }\n\n val fTwo = counts(2) / 2\n\n val twoLeft = counts(2) * 2 % 4\n\n //четверки собранны\n val fFour = counts(4)\n\n //число скомбенированные 3 и 1\n val (fThreeOne, left:(Int, Int)) = if (counts(3) == counts(1)) (counts(3), (0, 0)) else {\n val min = counts(3).min(counts(1))\n (min, (Map(3 -> counts(3), 1 -> counts(1)).maxBy(_._2)._1, Math.abs(counts(3) - counts(1))))\n }\n// println(left)\n\n // комбинируем 2 с 1\n val (fTwoOne:Int, left1:(Int, Int)) = if (twoLeft != 0) left match {\n\n case (0, 0) => (1, left)\n case (num: Int, count: Int) if num == 3 => (1, left)\n case (num: Int, count: Int) if num == 1 => if (count >= 2) (1, (num, count - 2)) else (1,(0, 0))\n\n } else (0, left)\n\n\n\n val fLeft = if (left1._1 == 3) left1._2 else {\n if (left1._2 < 4 && left1._2 != 0) {\n 1\n } else if (left1._2 == 0) {\n 0\n } else {\n val modQ = if (left1._2 % 4 == 0) 0 else 1\n left1._2 / 4 + modQ\n }\n }\n println(fTwo + fFour + fLeft + fThreeOne + fTwoOne)\n\n\n\n\n\n\n\n}\n"}, {"source_code": "import scala.util.Sorting\n\nobject _158B extends App\n{\n val n = readLine().toInt\n var fours = 0\n var threes = 0\n var twos = 0\n var ones = 0\n val groups = (readLine().split(\" \") map (_.toInt)) foreach (x => \n x match {\n case 4 => fours += 1\n case 3 => threes += 1\n case 2 => twos += 1\n case 1 => ones += 1\n case _ => println(x)\n })\n //println(fours + \" \" + threes + \" \" + twos + \" \" + ones)\n var ans = fours\n\n while (threes > 0) {\n if (ones > 0) {\n ans += 1\n threes -= 1\n ones -= 1\n } else {\n ans += 1\n threes -= 1\n }\n }\n\n while (twos > 0) {\n if (twos >= 2) {\n twos -= 2\n ans += 1\n } else if (ones >= 2) {\n twos -= 1\n ones -= 2\n ans += 1\n } else {\n twos -= 1\n if (ones >= 1)\n ones -= 1\n ans += 1\n }\n }\n\n while (ones >= 4) {\n ans += 1\n ones -= 4\n }\n if (ones > 0) {\n ans += 1\n }\n\n println(ans)\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val arr = readLine().split(\" \").map(_.toInt)\n var g1, g2, g3, g4 = 0\n arr.foreach{\n case 1 => g1 += 1\n case 2 => g2 += 1\n case 3 => g3 += 1\n case 4 => g4 += 1\n }\n var ga = g4 + g3 + ((g2 + 1) / 2) + (((g1 - g3 - 2 * (g2 % 2)).max(0) + 3) / 4)\n println(ga)\n }\n}"}, {"source_code": "object P279D {\n \n def main ( args : Array[String] ) {\n readLine().split(\" \").map(_.toInt);\n val A : Array[Int] = readLine().split(\" \").map(_.toInt);\n val C4 = A.count(_ == 4)\n val C3 = A.count(_ == 3)\n var C2 = A.count(_ == 2)\n var C1 = A.count(_ == 1)\n \n C1 -= (C2 % 2) * 2\n if(C1 < 0) C1 = 0 \n \n C1 -= C3\n if(C1 < 0) C1 = 0\n if(C1 == 0) C1 = -3\n if(C2 == 0) C2 = -1\n println (C4 + (C2 - 1) / 2 + 1 + (C1 - 1) / 4 + 1 + C3)\n \n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A_158 extends App {\n\n def sgn(i: Int) = if (i > 0) 1 else 0\n\n val n = readInt()\n val S = readLine().split(\" \").map(_.toInt).groupBy(identity).mapValues(_.length).withDefaultValue(0)\n\n val restOnes = Math.max(0, S(1) - S(3))\n val answer = S(4) + S(3) + S(2) / 2 + (S(2) % 2 match {\n case 0 => restOnes / 4 + sgn(restOnes % 4)\n case 1 => 1 + Math.max(0, restOnes - 2) / 4 + sgn(Math.max(0, restOnes - 2) % 4)\n })\n\n println(answer)\n}\n"}, {"source_code": "object JuanDavidRobles158B {\n def main(args: Array[String]): Unit = {\n\n import scala.io.StdIn\n\n val nGroups: Int = StdIn.readInt()\n val stringGroups: String = StdIn.readLine()\n\n /*var ones: Int = repetitions(stringGroups, \"1\")\n stringGroups = stringGroups.replace(\"1\", \"\")\n var twos: Int = repetitions(stringGroups, \"2\")\n stringGroups = stringGroups.replace(\"2\", \"\")\n var threes: Int = repetitions(stringGroups, \"3\")\n stringGroups = stringGroups.replace(\"3\", \"\")\n var fours: Int = repetitions(stringGroups, \"4\")*/\n\n var counts: Array[Int] = repetitions(stringGroups)\n\n var count: Int = 0\n\n var ones: Int = counts(0)\n var twos: Int = counts(1)\n var threes: Int = counts(2)\n var fours: Int = counts(3)\n\n /*if (threes >= ones){\n println((fours + threes + Math.ceil(twos.asInstanceOf[Float]/2))\n .asInstanceOf[Int])\n } else {\n println((fours + threes + Math.ceil(twos.asInstanceOf[Float]/2) + Math\n .ceil((ones-threes).asInstanceOf[Float]/4)).asInstanceOf[Int])\n }*/\n\n count = fours\n count = count + threes\n if (threes > ones){\n ones = 0\n } else {\n ones = ones - threes\n }\n count = count + twos/2\n if (twos%2 == 0){\n } else {\n ones = ones + (twos%2)*2\n }\n count = count + Math.ceil(ones.asInstanceOf[Double]/4).asInstanceOf[Int]\n println(count)\n }\n\n def repetitions(string: String): Array[Int] ={\n val myString: String = string\n var count: Array[Int] = new Array[Int](4)\n\n for (i <- 0 until myString.length){\n myString.charAt(i) match {\n case '1' => count(0) = count(0) + 1\n case '2' => count(1) = count(1) + 1\n case '3' => count(2) = count(2) + 1\n case '4' => count(3) = count(3) + 1\n case _ =>\n }\n }\n\n count\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readLine()\n val numbers = readLine().split(\" \").map(_.toInt)\n\n val counted = numbers.groupBy(identity).mapValues(_.size)\n\n // (already allocated, remaining)\n val (oat,rem1) = if(counted.getOrElse(3,0) >= counted.getOrElse(1,0)) (counted.getOrElse(3,0),0) else (counted.getOrElse(3,0), counted.getOrElse(1,0) - counted.getOrElse(3,0))\n\n// println(\"aot rem1\" + (oat,rem1))\n\n val (twos,rem2) = (counted.getOrElse(2,0) /2, counted.getOrElse(2,0) % 2)\n\n// println(\"twos, rem2\" +(twos,rem2))\n\n val frs = counted.getOrElse(4,0)\n\n// println(\"frs\" + (frs))\n val (r1,r2) = (rem1/4, rem1 %4)\n\n val (rems1, rems2) = ( (r2 + rem2*2 )/4, (rem1+rem2*2) % 4)\n\n// println( \"rems1 rem2\" + (rems1,rems2))\n\n val remss = if(rems2 > 0) 1 else 0\n\n// println(\"remsss\" + remss)\n\n println(oat + twos + frs + r1 + remss + rems1)\n//\n// println(\"oat: \" + oat)\n// println(\"twos: \" + twos)\n// println(\"frs: \" + frs)\n// println(\"rems1: \" + rems1)\n// println(\"rems2: \" + rems2)\n// println(\"r1, r2\" + (r1,r2))\n// println(\"remss:\" + remss)\n\n }\n}\n// 1 1 1 1 1 1 1 1 1 1"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\nobject Taxi {\n \n def main(args: Array[String]) {\n val n = readInt\n val groups = readLine.split(' ').map(_.toInt)\n val fours = groups.count(_ == 4)\n val threes = groups.count(_ == 3)\n val twos = groups.count(_ == 2)\n val ones = groups.count(_ == 1)\n \n val twosRem = twos%2\n val threesRem = Math.max(threes - ones, 0)\n val onesRem = Math.max(ones - threes, 0)\n \n val taxis = (fours + twos/2) + Math.min(threes,ones) +\n (if (threes >= ones) threesRem + twosRem \n else (\n (2*twosRem + onesRem)/4 + (if ((2*twosRem + onesRem) % 4 == 0) 0 else 1) \n )\n )\n println(taxis)\n \n }\n \n}"}, {"source_code": "object main extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n def solve(input: InputStream, output: PrintStream): Unit = {\n val sc = new Scanner(input)\n val n = sc.nextInt()\n val groups = (1 to n).map( _ => sc.nextInt())\n val counters =((1 to 4) map ( c => groups.count( _ == c))).toArray\n\n\n var c1 = counters(0)\n var c2 = counters(1)\n var c3 = counters(2)\n var c4 = counters(3)\n\n var result = c4\n if( c3 > c1){\n result += c1\n c3 -= c1\n c1 = 0\n }else{\n result += c3\n c1 -= c3\n c3 = 0\n }\n\n result += c2 / 2\n c2 %= 2\n\n if( c2 > (c1 +1)/2){\n //hay más grupos de 2 que pares de 1\n result += c2\n c1 = 0\n c2 = 0\n }else{\n result += c2\n c1 -= c2*2\n c2 = 0\n }\n\n result += (c1+3)/4\n result += c2 + c3\n output.println(result)\n }\n solve(System.in,System.out)\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Test {\n def main(args1: Array[String]) {\n// val args = StdIn.readLine().split(\" \")\n// var (x: Long, y: Long) = (args(0).toLong, args(1).toLong)\n\n val count = StdIn.readInt\n\n val line = StdIn.readLine().split(\" \").map(s => s.toInt)\n\n var l1 = line.filter(x => x == 1).length\n var l2 = line.filter(x => x == 2).length\n var l3 = line.filter(x => x == 3).length\n var l4 = line.filter(x => x == 4).length\n\n var res = l4.toLong\n if (l1 <= l3) {\n res += l3\n res += (l2 / 2) + l2 % 2\n } else {\n res += l3\n var left = l1 - l3\n l2 += (left / 2) + left % 2\n res += (l2 / 2) + l2 % 2\n }\n\n println(res)\n }\n\n}"}, {"source_code": "object OneFiveEightB {\n\tdef main(args: Array[String]) {\n\t\tvar array=new Array[Int](4)\n\t\tvar n=readInt\n\t\treadLine.split(' ').foreach{x=>array(x.toInt-1)+=1}\n\t\tvar fours=array(3)\n\t\tvar threes=array(2)\n\t\tvar twos=array(1)/2\n\t\tvar rem2=array(1)%2\n\t\tvar rem1=math.max(array(0)-array(2),0)\t\t\n\t\tvar buff=0\n\t\tif(rem2!=0){\n\t\t\ttwos+=1\n\t\t\tif(rem1>2){\n\t\t\t\trem1-=2\n\t\t\t\tbuff=rem1/4\n\t\t\t\tif(rem1%4!=0){\n\t\t\t\t\tbuff+=1\n\t\t\t\t}\n\t\t\t}\n\t\t}else{\n\t\t\tif(rem1>0){\n\t\t\t\tbuff=rem1/4\n\t\t\t\tif(rem1%4!=0){\n\t\t\t\t\tbuff+=1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintln(fours+threes+twos+buff)\n\t}\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Taxi {\n def main(args: Array[String]): Unit = {\n readInt()\n val groups = readLine().split(\" \").groupBy(_.toInt).mapValues(_.length).withDefaultValue(0)\n val ones = Math.max(0, groups(1) - groups(3))\n val res = groups(4) + groups(3) + (groups(2) * 2 + ones + 3) / 4\n println(res)\n }\n}"}, {"source_code": "import scala.collection.mutable\n\nobject counter {\n\n def main(args: Array[String]) {\n val numOfParts = Console.readInt()\n var groupsMap: mutable.Map[Int, Int] = new mutable.HashMap[Int, Int]() {\n override def default(key: Int) = 0\n }\n Console.readLine().split(\" \").map(_.toInt).toList.take(numOfParts).foreach(value => groupsMap.update(value, groupsMap(value) + 1));\n var result: Int = groupsMap(4)\n if (groupsMap(3) <= groupsMap(1)) {\n result += groupsMap(3)\n groupsMap.update(1, groupsMap(1) - groupsMap(3))\n groupsMap.update(3, 0)\n } else {\n result += groupsMap(3)\n groupsMap.update(1, 0)\n groupsMap.update(3, 0)\n }\n if (groupsMap(2) % 2 == 0) {\n result += groupsMap(2) / 2\n groupsMap.update(2, 0)\n } else {\n result += groupsMap(2) / 2\n if (groupsMap(1) > 1) {\n groupsMap.update(2, 0)\n groupsMap.update(1, groupsMap(1) - 2)\n result += 1\n } else {\n groupsMap.update(2, 0)\n groupsMap.update(1, 0)\n result += 1\n }\n }\n if(groupsMap(1) > 0){\n result += Math.ceil(groupsMap(1).toDouble / 4).toInt\n }\n println(result)\n }\n\n}\n"}, {"source_code": "/*input\n8\n2 3 4 4 2 1 3 1\n*/\n\nimport java.util.Scanner\nimport scala.io.StdIn\n\nobject Solution {\n\tdef main(args: Array[String]): Unit = { \n\n\t\tval n = StdIn.readInt();\n\t\tval arr = StdIn.readLine().split(\" \").map( _.toInt );\n\t\tval count = arr.foldLeft(List(0,0,0,0,0)){(list: List[Int], x: Int) => {\n\t\t\t\tval newCount = for(i <- 0 to list.length-1) yield {\n\t\t\t\t\tif(i == x) list(i)+1 else list(i);\n\t\t\t\t}\n\t\t\t\tnewCount.toList;\n\t\t\t}}\n\t\tif(count(3) >= count(1)) print(count(4) + count(3) + ceil(count(2),2))\n\t\telse{\n\t\t\tif( count(2) % 2 == 0 ) print(count(4) + count(3) + ceil(count(2),2) + ceil(count(1)-count(3),4))\n\t\t\telse print(count(4) + count(3) + ceil(count(2),2) + ceil(max(count(1)-count(3)-2,0),4))\n\t\t}\n\t}\n\tdef ceil(a: Long, b:Long) : Long ={\n\t\t(if(a%b == 0) 0 else 1 ) + a/b;\n\t}\n\tdef max(a: Int, b: Int) = if(a>b) a else b;\n}"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n val n = StdIn.readLine().toInt\n val A: Array[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n\n val M: scala.collection.mutable.Map[Int, Int] = scala.collection.mutable.Map[Int, Int](1->0,2->0,3->0,4->0)\n\n A.foreach(M(_) += 1)\n\n var ans = M(4)\n\n var m = math.min(M(1), M(3));\n\n M(1) = M(1) - m;\n M(3) = M(3) - m;\n ans += m\n ans += M(2) / 2;\n\n if (M(2) % 2 == 1) {\n ans+=1\n M(1) = math.max(0, M(1) - 2)\n }\n\n ans += M(1) / 4\n\n if (M(1) % 4 != 0)\n ans += 1\n\n ans += M(3)\n println(ans)\n\n\n }\n\n\n}\n"}, {"source_code": "object Main {\n\n def main(args: Array[String]): Unit = {\n val _ = readLine\n var res = 0;\n var count = new Array[Int](5)\n for(x <- readLine().split(\" \").map(_.toInt))count(x) += 1\n count(1) = Math.max(0,count(1)-count(3))\n res = count(4)+count(3)+(count(2)*2+count(1)+3)/4\n print(res)\n }\n\n}"}, {"source_code": "object _158_B {\n\n def main(args: Array[String]){\n var N = readLine.toInt\n\n var children = readLine.split(\" \").map(_.toInt)\n\n\n var ones: Int = children.count(_ == 1)\n var twos: Int = children.count(_ == 2)\n var threes: Int = children.count(_ == 3)\n\n val threesAndOnes = Math.min(threes, ones) // 3 + 1\n ones = Math.max(0, ones - threesAndOnes) // Remaining 1s from 3 + 1 taxis\n threes = Math.max(0, threes - threesAndOnes) // Remaining 3s from 3 + 1 taxis\n val twoAndTwo = Math.floor(twos / 2).toInt // 2 + 2\n twos = Math.max(0, twos - twoAndTwo * 2) // Remaining 2s from 2 + 2 taxis\n var twoAndOne = Math.min(ones, twos) // 2 + 1\n ones = Math.max(0, ones - twoAndOne) // Remaining 1s from 2 + 1 taxis\n twos = Math.max(0, twos - twoAndOne) // Remaining 2s from 2 + 1 taxis\n val twoAndOneAndOne = Math.min(twoAndOne, ones) // 2 + 1 + 1\n ones = Math.max(0, ones - twoAndOneAndOne) // Remaining 1s from 3 + 1 taxis\n twoAndOne = Math.max(0, twoAndOne - twoAndOneAndOne) // Remaining 2 + 1s from 2 + 1 + 1 taxis\n val oneAndOne = Math.floor(ones / 4).toInt // 1 + 1 + 1 + 1\n ones = Math.max(0, ones - oneAndOne * 4) // Remaining 1s from 2 + 1 taxis\n\n if (twos < 4 && twos > 0) twos = 1\n if (ones < 4 && ones > 0) ones = 1\n\n// println(\n// \"threesAndOnes: \" + threesAndOnes ,\n// \"threes: \" + threes ,\n// \"twoAndTwo: \" + twoAndTwo ,\n// \"twoAndOne: \" + twoAndOne ,\n// \"twoAndOneAndOne: \"+ twoAndOneAndOne ,\n// \"twos: \" + twos ,\n// \"oneAndOne: \" + oneAndOne ,\n// \"ones: \" + ones\n// )\n\n val taxis =\n children.count(_ == 4) +\n threesAndOnes +\n threes +\n twoAndTwo +\n twoAndOne +\n twoAndOneAndOne +\n twos +\n oneAndOne +\n ones\n\n println(taxis)\n\n // def left(taxi: Int): Int =\n // if (taxi > 0) 1 else 0\n // val filteredChildren: Array[Int] = children.filter(_ != 4).sorted\n //\n // val taxis: (Int, Int) =\n // filteredChildren\n // .foldLeft((initialTaxis, 0))( // Num taxis, current capacity\n // (taxi, group) => {\n// filteredChildren(filteredChildren.indexOf(group)) = 0 // Current one will always be used somewhere\n//\n// if (group != 0)\n// if (filteredChildren contains 4 - group) { // Find best complement of group\n// filteredChildren(filteredChildren.indexOf(4 - group)) = 0\n// (taxi._1 + 1, taxi._2)\n// } else\n// if (taxi._2 + group < 4) (taxi._1, taxi._2 + group) // Hop-on\n// else if (taxi._2 + group == 4) (taxi._1 + 1, 0) // Full taxi\n// else (taxi._1 + 1, group) // Allocate new taxi\n// else taxi\n// }\n// )\n//\n// println(taxis._1 + left(taxis._2))\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject Taxi extends App {\n def parseInts(str: String, numIterations: Integer) = {\n val scanner = new Scanner(str)\n val res = (0 until numIterations) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n val Seq(numFamilies) = parseInts(Console.readLine(), 1)\n val families = parseInts(Console.readLine(), numFamilies)\n val groupings = Array.fill[Int](5)(0)\n\n families.foreach(fam => groupings(fam) = groupings(fam) + 1)\n\n var total = 0\n\n families.foreach(fam => {\n val remainder = 4 - fam\n var upperBound = remainder\n val lowerBound = 1\n\n if (groupings(fam) > 0) {\n groupings(fam) -= 1\n total += 1\n var famAdded = fam\n while (famAdded < 4 && lowerBound <= upperBound) {\n if ((famAdded + upperBound) <= 4 && groupings(upperBound) > 0) {\n groupings(upperBound) -= 1\n famAdded += upperBound\n } else {\n upperBound -= 1\n }\n }\n }\n })\n\n println(total)\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Taxi extends App {\n def parseInts(str: String, numIterations: Integer) = {\n val scanner = new Scanner(str)\n val res = (0 until numIterations) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n val MAX_FAMILY_SIZE = 4\n val MIN_FAMILY_SIZE = 1\n\n val Seq(numFamilies) = parseInts(Console.readLine(), 1)\n val families = parseInts(Console.readLine(), numFamilies)\n val familiesBySize = Array.fill[Int](5)(0)\n\n families.foreach(fam => familiesBySize(fam) = familiesBySize(fam) + 1)\n\n var total = 0\n\n def fitGroupsInTaxi(famBySize: Array[Int], famSize: Int): Unit = {\n if (familiesBySize(famSize) > 0) {\n // Decrement number of families at that size\n familiesBySize(famSize) -= 1\n total += 1\n var numInTaxi = famSize\n\n def placeInTaxi(maybePlaceInTaxi: Int, numIn: Int): Int = {\n numIn match {\n case MAX_FAMILY_SIZE => {\n numIn\n }\n case _ => {\n if ((numIn + maybePlaceInTaxi) <= MAX_FAMILY_SIZE && familiesBySize(maybePlaceInTaxi) > 0) {\n familiesBySize(maybePlaceInTaxi) -= 1\n placeInTaxi(maybePlaceInTaxi, numIn + maybePlaceInTaxi)\n } else numIn\n }\n }\n // if (numInTaxi < MAX_FAMILY_SIZE && familiesBySize(maybePlaceInTaxi) > 0) {\n // familiesBySize(maybePlaceInTaxi) -= 1\n // numIn + maybePlaceInTaxi\n // } else {numIn}\n }\n\n for {\n maybePlaceInTaxi <- (MAX_FAMILY_SIZE - famSize) to MIN_FAMILY_SIZE by -1\n\n // while( < MAX_FAMILY_SIZE)\n if (numInTaxi < MAX_FAMILY_SIZE && familiesBySize(maybePlaceInTaxi) > 0)\n } yield {\n numInTaxi = placeInTaxi(maybePlaceInTaxi, numInTaxi)\n // familiesBySize(maybePlaceInTaxi) -= 1\n // numInTaxi += maybePlaceInTaxi\n }\n }\n }\n\n families.foreach(fam => fitGroupsInTaxi(familiesBySize, fam))\n\n println(total)\n}\n"}, {"source_code": "import java.util.Scanner\nimport collection.immutable.HashMap\nimport scala.math.min\nimport scala.math.max\n\n/**\n * Created by dr0ff on 26/02/16.\n */\nobject Taxi extends App {\n\n val in = new Scanner(System.in)\n val totalGroups = in.nextLine().trim.toInt\n val groups = in.nextLine().trim.split(\" \").map(_.toInt)\n\n print(getTotalCarsNum(groups))\n\n def getTotalCarsNum(groups: Array[Int]) = {\n val places = 4\n val counter = groups.foldLeft(new HashMap[Int, Int]()) {\n (c, x) => c + (x -> (c.getOrElse(x, 0) + 1))}\n val fours = counter.getOrElse(4, 0)\n val onesWithTriples = min(counter.getOrElse(1, 0), counter.getOrElse(3, 0))\n val triplesOnly = (counter.getOrElse(3, 0) - onesWithTriples)\n val deucesOnly: Int = counter.getOrElse(2, 0) / 2\n val deucesWithOnes = counter.getOrElse(2, 0) % 2\n val remainOnes = max(0, counter.getOrElse(1, 0) - onesWithTriples - 2 * deucesWithOnes)\n val onesOnly: Int = remainOnes / places + min(remainOnes % places, 1)\n\n fours + onesWithTriples + triplesOnly + deucesOnly + deucesWithOnes + onesOnly\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\nimport scala.util.Sorting\nimport java.lang.Math._\n\nobject Taxi_158B extends App {\n val n = readInt\n val chs = readLine.split(\" \").map(_.toInt)\n \n val gchs = Map(1->0, 2->0, 3->0, 4->0) ++ chs.groupBy((a: Int) => a).map(a => (a._1 -> a._2.length))\n \n val gchs1 = Map(\n 4 -> gchs(4), \n 3 -> gchs(3), \n 2 -> gchs(2), \n 1 -> (gchs(1) - min(gchs(1), gchs(3)))\n )\n \n val gchs2 = Map(\n 4 -> gchs1(4), \n 3 -> gchs1(3), \n 2 -> (gchs1(2) + (if (gchs1(1) > 1 && gchs1(2) % 2 != 0) 1 else 0)), \n 1 -> (if (gchs1(1) > 0 && gchs1(2) > 0 && gchs1(2) % 2 != 0) gchs1(1) - min(gchs1(1), 2) else gchs1(1))\n )\n \n \n //println(gchs, gchs1, gchs2)\n val ans = \n gchs2(4) + \n gchs2(3) +\n gchs2(2) / 2 + (if (gchs2(2) % 2 != 0) 1 else 0) +\n gchs2(1) / 4 + (if (gchs2(1) % 4 != 0) 1 else 0)\n \n println(ans)\n}"}, {"source_code": "import scala.collection.mutable\n\nobject CF0158B extends App {\n\n val n = readInt()\n\n var s = readLine().split(\" \").map(_.toInt).toList.sorted\n\n var count = 0\n\n var iter = s.reverseIterator\n var stack = new mutable.Stack[Int]()\n while (iter.hasNext ) {\n var it = iter.next()\n if(it == 4) {\n count += 1\n } else {\n if(stack.isEmpty) {\n stack.push(it)\n } else {\n var people = stack.top + it\n if (people == 4){\n stack.pop()\n count += 1\n } else if (people > 4) {\n stack.push(it)\n } else {\n stack.pop()\n stack.push(people)\n }\n }\n }\n }\n if(!stack.isEmpty) {\n while (!stack.isEmpty) {\n stack.pop()\n count += 1\n }\n }\n\n println(count)\n\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject Taxi {\n\n def main(args: Array[String]) = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n val numOfGroups = br.readLine().toInt\n val (ones, twos, threes, fours) = readGroups(br, numOfGroups)\n val res = numberOfTaxis(ones, twos, threes, fours)\n println(res)\n }\n\n def readGroups(br: BufferedReader, numOfGroups: Int): (Int, Int, Int, Int) = {\n val str = br.readLine()\n val tok = new StringTokenizer(str)\n var ones, twos, threes, fours = 0\n (1 to numOfGroups).foreach { _ =>\n val next = Integer.parseInt(tok.nextToken())\n next match {\n case 1 => ones += 1\n case 2 => twos += 1\n case 3 => threes += 1\n case _ => fours += 1\n }\n }\n (ones, twos, threes, fours)\n }\n\n def numberOfTaxis(ones: Int, twos: Int, threes: Int, fours: Int): Int = {\n val groupsOf3And1 = math.min(threes, ones)\n val groupsOf3 = threes - groupsOf3And1\n\n val remainingGroupsOf1 = ones - groupsOf3And1\n val (remainingGroupsOf1Paired, oddGroupsOf1) = divWithMod(remainingGroupsOf1, 2)\n val (groupsOf2, oddGroupsOf2) = divWithMod(twos + remainingGroupsOf1Paired, 2)\n\n val remaining = math.min(1, oddGroupsOf1 + oddGroupsOf2)\n\n fours + groupsOf3And1 + groupsOf3 + groupsOf2 + remaining\n }\n\n def divWithMod(x: Int, y: Int): (Int, Int) = {\n val r = x / y\n val m = x % y\n (r, m)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Taxi {\n\n def main(args: Array[String]) = {\n val sc = new Scanner(System.in)\n val numOfGroups = sc.nextInt()\n sc.nextLine()\n val groups = (1 to numOfGroups).map { _ => sc.nextInt() }.toList\n val res = numberOfTaxis(groups)\n println(res)\n }\n\n case class GroupType(size: Int, count: Int)\n\n def numberOfTaxis(groups: List[Int]): Int = {\n val groupsBySize = groups.groupBy(identity).map { case (size, values) => size -> values.size }.withDefault(_ => 0)\n\n val groupsOf4 = groupsBySize(4)\n val groupsOf3And1 = math.min(groupsBySize(3), groupsBySize(1))\n val groupsOf3 = groupsBySize(3) - groupsOf3And1\n\n val remainingGroupsOf1 = groupsBySize(1) - groupsOf3And1\n val (remainingGroupsOf1Paired, oddGroupsOf1) = divWithMod(remainingGroupsOf1, 2)\n val (groupsOf2, oddGroupsOf2) = divWithMod(groupsBySize(2) + remainingGroupsOf1Paired, 2)\n\n val remaining = math.min(1, oddGroupsOf1 + oddGroupsOf2)\n\n groupsOf4 + groupsOf3And1 + groupsOf3 + groupsOf2 + remaining\n }\n\n def divWithMod(x: Int, y: Int): (Int, Int) = {\n val r = x / y\n val m = x % y\n (r, m)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.annotation.tailrec\n\nobject Taxi {\n\n def main(args: Array[String]) = {\n val sc = new Scanner(System.in)\n val numOfGroups = sc.nextInt()\n sc.nextLine()\n val groups = (1 to numOfGroups).map { _ => sc.nextInt() }.toList\n val res = numberOfTaxis(groups)\n println(res)\n }\n\n case class GroupType(size: Int, count: Int)\n\n def numberOfTaxis(groups: List[Int]): Int = {\n @tailrec\n def numberOfTaxisRec(taxis: Int, groupTypes: Vector[GroupType]): Int = {\n if (groupTypes.isEmpty) taxis\n else if (groupTypes.head.count == 0) numberOfTaxisRec(taxis, groupTypes.tail)\n else {\n val (updatedGroupTypes, _) = groupTypes.foldLeft((Vector.empty[GroupType], 0)) { case ((upd, totalTaken), gt) =>\n val left = 4 - totalTaken\n val taken = math.min(gt.count, left / gt.size)\n (upd :+ gt.copy(count = gt.count - taken), totalTaken + taken * gt.size)\n }\n numberOfTaxisRec(taxis + 1, updatedGroupTypes)\n }\n }\n\n val groupTypes = groups\n .groupBy(identity)\n .map { case (size, values) => GroupType(size, values.size) }\n .toVector\n .sortBy(- _.size)\n numberOfTaxisRec(0, groupTypes)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject Taxi {\n\n def main(args: Array[String]) = {\n val sc = new Scanner(System.in)\n val numOfGroups = sc.nextInt()\n sc.nextLine()\n val groups = readGroups(sc, numOfGroups)\n val res = numberOfTaxis(groups)\n println(res)\n }\n\n def readGroups(sc: Scanner, numOfGroups: Int): mutable.HashMap[Int, Int] = {\n val res = mutable.HashMap[Int, Int](1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0)\n (1 to numOfGroups).foreach { _ =>\n val next = sc.nextInt()\n res.update(next, res(next) + 1)\n }\n res\n }\n\n def numberOfTaxis(groupsBySize: mutable.HashMap[Int, Int]): Int = {\n val groupsOf4 = groupsBySize(4)\n val groupsOf3And1 = math.min(groupsBySize(3), groupsBySize(1))\n val groupsOf3 = groupsBySize(3) - groupsOf3And1\n\n val remainingGroupsOf1 = groupsBySize(1) - groupsOf3And1\n val (remainingGroupsOf1Paired, oddGroupsOf1) = divWithMod(remainingGroupsOf1, 2)\n val (groupsOf2, oddGroupsOf2) = divWithMod(groupsBySize(2) + remainingGroupsOf1Paired, 2)\n\n val remaining = math.min(1, oddGroupsOf1 + oddGroupsOf2)\n\n groupsOf4 + groupsOf3And1 + groupsOf3 + groupsOf2 + remaining\n }\n\n def divWithMod(x: Int, y: Int): (Int, Int) = {\n val r = x / y\n val m = x % y\n (r, m)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\n\nobject Taxi {\n\n def main(args: Array[String]) = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n val numOfGroups = br.readLine().toInt\n val groups = readGroups(br, numOfGroups)\n val res = numberOfTaxis(groups)\n println(res)\n }\n\n def readGroups(br: BufferedReader, numOfGroups: Int): mutable.HashMap[Int, Int] = {\n val str = br.readLine()\n val tok = new StringTokenizer(str)\n val res = mutable.HashMap[Int, Int](1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0)\n (1 to numOfGroups).foreach { _ =>\n val next = Integer.parseInt(tok.nextToken())\n res.update(next, res(next) + 1)\n }\n res\n }\n\n def numberOfTaxis(groupsBySize: mutable.HashMap[Int, Int]): Int = {\n val groupsOf4 = groupsBySize(4)\n val groupsOf3And1 = math.min(groupsBySize(3), groupsBySize(1))\n val groupsOf3 = groupsBySize(3) - groupsOf3And1\n\n val remainingGroupsOf1 = groupsBySize(1) - groupsOf3And1\n val (remainingGroupsOf1Paired, oddGroupsOf1) = divWithMod(remainingGroupsOf1, 2)\n val (groupsOf2, oddGroupsOf2) = divWithMod(groupsBySize(2) + remainingGroupsOf1Paired, 2)\n\n val remaining = math.min(1, oddGroupsOf1 + oddGroupsOf2)\n\n groupsOf4 + groupsOf3And1 + groupsOf3 + groupsOf2 + remaining\n }\n\n def divWithMod(x: Int, y: Int): (Int, Int) = {\n val r = x / y\n val m = x % y\n (r, m)\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ListBuffer\n\nobject task158B {\n def main(args:Array[String]) {\n val in=io.Source.stdin.getLines.toList\n val Array(n)=in(0).split(\" \").map(_.toInt)\n val s=in(1).split(\" \").map(_.toInt).toList\n var k1=0; var k2=0; var k3=0; var rv=0;\n for (a <- s) {\n a match {\n case 1 => k1+=1;\n case 2 => k2+=1;\n case 3 => k3+=1;\n case 4 => rv+=1;\n }\n }\n rv+=k3; if (k3>k1) { k1=0; } else { k1-=k3; }\n rv+=k2/2; k2=k2%2; if (k2==1) { rv+=1; k2=0; if (k1>=2) { k1-=2; } else { k1=0; } }\n rv+=k1/4; k1=k1%4; if (k1!=0) { rv+=1; }\n println(rv)\n }\n}\n"}, {"source_code": "object B00158 extends App {\n\n def oneIntLine = {\n val Seq(count) = parseInt(Console.readLine(), 1);\n count\n }\n \n def parseInt(str: String, count: Int): Seq[Int] = {\n val scanner = new java.util.Scanner(str)\n val res = (1 to count) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n def scanInts(count: Int): Seq[Int] = parseInt(Console.readLine, count)\n \n def frequency[T](seq: Seq[T]) = seq.groupBy(identity).mapValues(_.size).withDefaultValue(0)\n \n def partsNeededToCoverFull(fullLength: Int, partLength: Int) =\n Math.ceil(fullLength * 1.0 / partLength).toInt\n \n val count = oneIntLine\n val grouped = frequency(scanInts(count))\n val partialCount = grouped(4) + grouped(3) + partsNeededToCoverFull(grouped(2), 2)\n val vacantSeats = grouped(3) + (if (grouped(2) % 2 == 1) 2 else 0)\n val remainingSingles = if (grouped(1) > vacantSeats) grouped(1) - vacantSeats else 0\n val res = partialCount + partsNeededToCoverFull(remainingSingles, 4)\n println(res)\n}"}, {"source_code": "object pratise {\n def solve() {\n val n = readInt\n var res = 0\n var count = new Array[Int](5)\n for(i <- readLine().split(\" \").map(_.toInt)) count(i) += 1\n count(1) = math.max(0,count(1) - count(3))\n res = count(4) + count(3) + (count(2)*2 + count(1) + 3) / 4\n println(res)\n }\n def main(args : Array[String]) {\n solve\n }\n}\n"}, {"source_code": "object cf extends App{\n val n = readInt()\n val arr = Array.fill[Int](5)(0)\n var nums = readLine().split(\" \").map(_.toInt)\n for (i <- 0 to n-1) {\n val x = nums(i)\n arr(x) += 1\n }\n var res = 0\n res += arr(4)\n res += arr(3)\n arr(1) -= arr(3)\n arr(1) = arr(1).max(0)\n arr(3) = 0\n res += arr(2)/2\n arr(2) = arr(2) % 2\n arr(1) += arr(2)*2\n res += arr(1)/4\n if (arr(1) % 4 != 0) res += 1\n //make it go\n println(res)\n}"}, {"source_code": "import scala.io.StdIn.readLine\nobject Solution {\n def readLines(n: Int) = Iterator.continually(readLine).take(n).toIterable\n def group(s: Iterable[Int]) = s groupBy identity mapValues (_.size) withDefaultValue 0\n def solve(m: Map[Int, Int]) = {\n val singletonesLeft = math.max(m(1) - m(3), 0)\n val pairsLeft = m(2) % 2\n m(4) + m(3) + m(2) / 2 + (pairsLeft * 2 + singletonesLeft + 3) / 4\n }\n def main(args: Array[String]) = {\n val n = readLine.toInt\n val s = readLine split \" \" map (_.toInt)\n println(solve(group(s)))\n }\n}\n"}, {"source_code": "object Solution158B extends Application {\n\n def solution() {\n val n = _int\n val groups = 1.to(n).map(_ => _int).groupBy(x => x).mapValues(seq => seq.size)\n\n val n1 = groups.get(1).getOrElse(0)\n val n2 = groups.get(2).getOrElse(0)\n val n3 = groups.get(3).getOrElse(0)\n val n4 = groups.get(4).getOrElse(0)\n val res = n4 + n3 + (n2 / 2 + n2 % 2)\n val left = n1 - n3 - (2 * (n2 % 2))\n\n println(res + (if (left > 0) (left + 3) / 4 else 0))\n }\n\n //////////////////////////////////////////////////\n import java.util.Scanner\n val SC: Scanner = new Scanner(System.in)\n def _line: String = SC.nextLine\n def _int: Int = SC.nextInt\n def _long: Long = SC.nextLong\n def _string: String = SC.next\n solution()\n}"}, {"source_code": "import scala.collection.mutable._\nimport scala.math._\nimport scala.util.control.Breaks.break\nimport scala.util.control.Breaks.breakable\nimport java.util._\nobject Main extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt\n val t = for(i <- 1 to n) yield sc.nextInt\n val tc = for(i <- 0 to 4) yield t.count(_ == i)\n println(tc(4) + tc(3) + (tc(2)+1)/2 + (3+max(0, tc(1) - tc(3) - 2*(tc(2) % 2)))/4)\n}\n"}, {"source_code": "import scala.io.StdIn\nobject TaxiTest {\n def main(args: Array[String]){\n val numberOfGroups = StdIn.readInt()\n val childrens = StdIn.readLine().split(\" \").map(_.toInt)\n var count1 = childrens.count(_ == 1)\n var count2 = childrens.count(_ == 2)\n var count3 = childrens.count(_ == 3)\n var count4 = childrens.count(_ == 4)\n\n var res = count4\n while (count1 > 0 && count3 >0 ){\n res = res + 1\n count1 = count1 - 1\n count3 = count3 - 1\n }\n if(count2 > 0){\n res = res + count2/2\n count2 = count2 % 2\n }\n\n if(count1 > 0 ){\n if(count2 > 0){\n count1 = count1 + 2\n }\n res = res + count1/4\n if( count1 % 4 != 0 ) res = res + 1;\n }\n else if(count3 > 0){\n res = res + count3\n if( count2 > 0){\n res = res + 1\n\n }\n }\n else if(count2 > 0){\n res = res +1\n }\n\n println(res)\n }\n}\n"}, {"source_code": "object Main {\n\timport java.{util=>ju}\n\timport scala.math._\n\n\tdef main(args:Array[String])\n\t{\n\t\tval sc = new ju.Scanner(System.in)\n\t\tval n = sc.nextInt();\n\t\tval a = (1 to n).map(_ => sc.nextInt()).toList\n\n\t\tval res = count(a, (1 to 4).toList.map(_=>0))\n\t\tprintln(res(3)+res(2)+(res(1)+1)/2+(3+max(0, res(0)-res(2)-2*(res(1)%2)))/4)\n\t}\n\n\tdef count(arr:List[Int], cnt:List[Int]):List[Int] =\n\t{\n\t\tarr match {\n\t\t\tcase h::t if (h >= 1 & h <= 4) => count(t, cnt.updated(h-1, cnt(h-1)+1))\n\t\t\tcase h::t => count(t, cnt)\n\t\t\tcase Nil => cnt\n\t\t}\n\t}\n}\n"}, {"source_code": "object Main {\n\timport java.{util=>ju}\n\timport scala.math._\n\n\tdef main(args:Array[String])\n\t{\n\t\tval sc = new ju.Scanner(System.in)\n\t\tval n = sc.nextInt();\n\t\tval a = (1 to n).map(_ => sc.nextInt()).toList\n\n\t\t//val res = count(a, (1 to 4).toList.map(_=>0))\n\t\tval res = (1 to 4).map{i => a.count(_==i)}.toList\n\t\tprintln(res(3)+res(2)+(res(1)+1)/2+(3+max(0, res(0)-res(2)-2*(res(1)%2)))/4)\n\t}\n\n\tdef count(arr:List[Int], cnt:List[Int]):List[Int] =\n\t{\n\t\tarr match {\n\t\t\tcase h::t if (h >= 1 & h <= 4) => count(t, cnt.updated(h-1, cnt(h-1)+1))\n\t\t\tcase h::t => count(t, cnt)\n\t\t\tcase Nil => cnt\n\t\t}\n\t}\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val std = scala.io.StdIn\n\n val n = std.readInt()\n val line = std.readLine().split(\" \").map(_.toInt)\n val counts = new Array[Int](5)\n line.foreach(x => counts(x) += 1)\n val counts2 = (counts(2) + 1) / 2\n val singlesLeft = Math.max(0, counts(1) - counts(3) - (counts(2) % 2) * 2 )\n val result = counts(4) + counts(3) + counts2 + (singlesLeft + 3) / 4\n println(result)\n }\n}"}, {"source_code": "import scala.io.StdIn\nimport scala.language.implicitConversions\n\nobject B {\n implicit def toInt(b: Boolean) = if (b) 1 else 0\n\n def main(args: Array[String]) = {\n val n = StdIn.readLine.toInt\n val s = StdIn.readLine.split(\" \").map(_.toInt)\n val freqMap: Map[Int, Int] = s.groupBy(x => x).mapValues(_.length)\n \n val ones = freqMap.getOrElse(1, 0)\n val twos = freqMap.getOrElse(2, 0)\n val threes = freqMap.getOrElse(3, 0)\n val fours = freqMap.getOrElse(4, 0)\n\n val mod = if (twos % 2 == 1) 2 else 0\n val ans = fours + threes + (twos + 1) / 2 + Math.max(ones - threes - mod + 3, 0) / 4\n println(ans)\n }\n}\n"}, {"source_code": "\nimport scala.math._\n\nobject Taxy extends App{\n\n import scala.collection.mutable.Map\n val n = readInt\n val arr = readLine.split(\" \").map(_.toInt)\n val mp = Map[Int, Int]()\n\n (1 to 4).foreach(x => mp(x) = 0)\n arr.foreach(x => mp(x) += 1)\n\n val four = mp(4)\n val third = mp(3)\n mp(1) = max(mp(1) - mp(3), 0)\n val second = mp(2) / 2 + max(if(min(2 * (mp(2) % 2), mp(1)) > 0) 1 else 0, mp(2) % 2)\n mp(1) = max(mp(1) - 2 * (mp(2) % 2), 0)\n val first = mp(1) / 4 + {if( (mp(1) % 4) != 0) 1 else 0}\n\n println(first + second + third + four)\n}\n"}, {"source_code": "import scala.collection.mutable.ListBuffer;\n\nobject Taxi {\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val l = Array.fill(5)(0)\n for(x <- readLine().split(\" \").map(_.toInt)) l(x) += 1\n if(l(3) >= l(1))\n println(l(4) + l(3) + math.ceil(2*l(2).toDouble/4).toInt)\n else\n println(l(4) + l(3) + math.ceil((2*l(2) + l(1)-l(3)).toDouble / 4).toInt )\n }\n\n}"}, {"source_code": "/**\n * Created by IntelliJ IDEA.\n * User: lizan\n * Date: 3/19/12\n * Time: 5:44 AM\n * To change this template use File | Settings | File Templates.\n */\n\nimport java.util.Scanner\n\nobject Main extends App{\n val scanner = new Scanner(io.Source.stdin.reader)\n\n val N = scanner.nextInt()\n val S = (1 to N).map(_ => scanner.nextInt).sorted\n\n val count = (0 to 4).map(x => S.count(_ == x))\n val alone = math.max(0, count(1) - count(3))\n val ans = count(4) + count(3) + (count(2) * 2 + alone + 3) / 4\n\n println(ans)\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject p158b extends App {\n\n private val n = StdIn.readLine.toInt\n val array=new Array[Int](5)\n\n val line=StdIn.readLine.split(\" \").map(_.toInt).sortBy(identity).reverse\n for (i<- line ){\n array(i)+=1\n }\n\n var sum=array(4)\n if(array(3)>array(1)) {\n sum+=array(3)\n array(1)=0\n }\n else{\n sum+=array(3)\n array(1)-=array(3)\n }\n\n sum+=array(2)/2\n val remain=array(2)%2\n\n if(remain==1){\n if(array(1)>=2){\n array(1)-=2\n sum+=1\n }\n else if(array(1)==1){\n array(1)=0\n sum+=1\n }\n else{\n sum+=1\n }\n }\n\n sum+=array(1)/4\n val remain1=array(1)%4\n if(remain1>0){\n sum+=1\n }\n\n print(sum)\n}\n"}, {"source_code": "object B158 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n var Array(four, thr, two, one) = Array(4,3,2,1).map{x => input.count(_ == x)}\n\n var res = four\n four = 0\n\n val a = math.min(thr, one)\n res += a\n thr -= a\n one -= a\n res += thr\n thr = 0\n\n res += two/2\n two -= (two/2)*2\n\n val b = math.min(two, one/2)\n res += b\n two -= b\n one -= b*2\n\n val c = math.min(two, one)\n res += c\n two -= c\n one -= c\n\n res += two\n\n res += (if (one% 4 == 0) one/4 else (one/4)+1)\n one = 0\n\n println(res)\n }\n}"}, {"source_code": "import collection.mutable\nimport java.util.Scanner\n\nobject B extends App {\n\tval in = new Scanner(System.in)\n\tval n = in.nextInt()\n\tval s: mutable.Map[Int, Int] = mutable.HashMap().withDefaultValue(0)\n\tfor (_ <- 1 to n) {\n\t\tval si = in.nextInt()\n\t\ts += si -> (s(si) + 1)\n\t}\n\tval numCars = {\n\t\tval remainingOne = 0 max (s(1) - s(3) - (if (s(2) % 2 == 0) 0 else 2))\n\t\ts(4) + s(3) + (s(2) + 1) / 2 + (remainingOne + 3) / 4\n\t}\n\tprintln(numCars)\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readLine()\n val numbers = readLine().split(\" \").map(_.toInt)\n\n val counted = numbers.groupBy(identity).mapValues(_.size)\n\n // (already allocated, remaining)\n val (oat,rem1) = if(counted.getOrElse(3,0) >= counted.getOrElse(1,0)) (counted.getOrElse(3,0),0) else (counted.getOrElse(3,0), counted.getOrElse(1,0) - counted.getOrElse(3,0))\n\n// println(\"aot rem1\" + (oat,rem1))\n\n val (twos,rem2) = (counted.getOrElse(2,0) /2, counted.getOrElse(2,0) % 2)\n\n println(\"twos, rem2\" +(twos,rem2))\n\n val frs = counted.getOrElse(4,0)\n\n// println(\"frs\" + (frs))\n val (r1,r2) = (rem1/4, rem1 %4)\n\n val (rems1, rems2) = ( (r1 + rem2 )/4, (r1+rem2) % 4)\n\n// println( \"rems1 rem2\" + (rems1,rems2))\n\n val remss = if(rems2 > 0) 1 else 0\n\n// println(\"remsss\" + remss)\n\n println(oat + twos + frs + r1 + remss + rems1)\n\n// println(\"oat: \" + oat)\n// println(\"twos: \" + twos)\n// println(\"frs: \" + frs)\n// println(\"rems1: \" + rems1)\n// println(\"rems2: \" + rems2)\n\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readLine()\n val numbers = readLine().split(\" \").map(_.toInt)\n\n val counted = numbers.groupBy(identity).mapValues(_.size)\n\n // (already allocated, remaining)\n val (oat,rem1) = if(counted.getOrElse(3,0) >= counted.getOrElse(1,0)) (counted.getOrElse(3,0),0) else (counted.getOrElse(3,0), counted.getOrElse(1,0) - counted.getOrElse(3,0))\n\n// println(\"aot rem1\" + (oat,rem1))\n\n val (twos,rem2) = (counted.getOrElse(2,0) /2, counted.getOrElse(2,0) % 2)\n\n// println(\"twos, rem2\" +(twos,rem2))\n\n val frs = counted.getOrElse(4,0)\n\n// println(\"frs\" + (frs))\n val (r1,r2) = (rem1/4, rem1 %4)\n\n val (rems1, rems2) = ( (r1 + rem2 )/4, (rem1+rem2) % 4)\n\n// println( \"rems1 rem2\" + (rems1,rems2))\n\n val remss = if(rems2 > 0) 1 else 0\n\n// println(\"remsss\" + remss)\n\n println(oat + twos + frs + r1 + remss + rems1)\n\n println(\"oat: \" + oat)\n println(\"twos: \" + twos)\n println(\"frs: \" + frs)\n println(\"rems1: \" + rems1)\n println(\"rems2: \" + rems2)\n println(\"r1, r2\" + (r1,r2))\n println(\"remss:\" + remss)\n\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readLine()\n val numbers = readLine().split(\" \").map(_.toInt)\n\n val counted = numbers.groupBy(identity).mapValues(_.size)\n\n // (already allocated, remaining)\n val (oat,rem1) = if(counted.getOrElse(3,0) >= counted.getOrElse(1,0)) (counted.getOrElse(3,0),0) else (counted.getOrElse(3,0), counted.getOrElse(1,0) - counted.getOrElse(3,0))\n\n// println(\"aot rem1\" + (oat,rem1))\n\n val (twos,rem2) = (counted.getOrElse(2,0) /2, counted.getOrElse(2,0) % 2)\n\n// println(\"twos, rem2\" +(twos,rem2))\n\n val frs = counted.getOrElse(4,0)\n\n// println(\"frs\" + (frs))\n\n val (rems1, rems2) = ( (rem1 + rem2 )/4, (rem1+rem2) % 4)\n\n// println( \"rems1 rem2\" + (rems1,rems2))\n\n val remss = if(rems2 > 0) 1 else 0\n\n// println(\"remsss\" + remss)\n\n println(oat + twos + frs + rems1 + remss)\n\n// println(\"oat: \" + oat)\n// println(\"twos: \" + twos)\n// println(\"frs: \" + frs)\n// println(\"rems1: \" + rems1)\n// println(\"rems2: \" + rems2)\n\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readLine()\n val numbers = readLine().split(\" \").map(_.toInt)\n\n val counted = numbers.groupBy(identity).mapValues(_.size)\n\n // (already allocated, remaining)\n val (oat,rem1) = if(counted.getOrElse(3,0) >= counted.getOrElse(1,0)) (counted.getOrElse(3,0),0) else (counted.getOrElse(3,0), counted.getOrElse(1,0) - counted.getOrElse(3,0))\n\n// println(\"aot rem1\" + (oat,rem1))\n\n val (twos,rem2) = (counted.getOrElse(2,0) /2, counted.getOrElse(2,0) % 2)\n\n// println(\"twos, rem2\" +(twos,rem2))\n\n val frs = counted.getOrElse(4,0)\n\n// println(\"frs\" + (frs))\n val (r1,r2) = (rem1/4, rem1 %4)\n\n val (rems1, rems2) = ( (r2 + rem2 )/4, (rem1+rem2) % 4)\n\n// println( \"rems1 rem2\" + (rems1,rems2))\n\n val remss = if(rems2 > 0) 1 else 0\n\n// println(\"remsss\" + remss)\n\n println(oat + twos + frs + r1 + remss + rems1)\n//\n// println(\"oat: \" + oat)\n// println(\"twos: \" + twos)\n// println(\"frs: \" + frs)\n// println(\"rems1: \" + rems1)\n// println(\"rems2: \" + rems2)\n// println(\"r1, r2\" + (r1,r2))\n// println(\"remss:\" + remss)\n\n }\n}\n// 1 1 1 1 1 1 1 1 1 1"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readLine()\n val numbers = readLine().split(\" \").map(_.toInt)\n\n val counted = numbers.groupBy(identity).mapValues(_.size)\n\n // (already allocated, remaining)\n val (oat,rem1) = if(counted.getOrElse(3,0) >= counted.getOrElse(1,0)) (counted.getOrElse(3,0),0) else (counted.getOrElse(3,0), counted.getOrElse(1,0) - counted.getOrElse(3,0))\n\n println(\"aot rem1\" + (oat,rem1))\n\n val (twos,rem2) = (counted.getOrElse(2,0) /2, counted.getOrElse(2,0) % 2)\n\n println(\"twos, rem2\" +(twos,rem2))\n\n val frs = counted.getOrElse(4,0)\n\n println(\"frs\" + (frs))\n\n val (rems1, rems2) = ( (rem1 + rem2 )/4, (rem1+rem2) % 4)\n\n println( \"rems1 rem2\" + (rems1,rems2))\n\n val remss = if(rems2 > 0) 1 else 0\n\n println(\"remsss\" + remss)\n\n println(oat + twos + frs + rems1 + rems2)\n\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readLine()\n val numbers = readLine().split(\" \").map(_.toInt)\n\n val counted = numbers.groupBy(identity).mapValues(_.size)\n\n // (already allocated, remaining)\n val (oat,rem1) = if(counted.getOrElse(3,0) >= counted.getOrElse(1,0)) (counted.getOrElse(3,0),0) else (counted.getOrElse(3,0), counted.getOrElse(1,0) - counted.getOrElse(3,0))\n\n// println(\"aot rem1\" + (oat,rem1))\n\n val (twos,rem2) = (counted.getOrElse(2,0) /2, counted.getOrElse(2,0) % 2)\n\n// println(\"twos, rem2\" +(twos,rem2))\n\n val frs = counted.getOrElse(4,0)\n\n// println(\"frs\" + (frs))\n val (r1,r2) = (rem1/4, rem1 %4)\n\n val (rems1, rems2) = ( (r1 + rem2 )/4, (r1+rem2) % 4)\n\n// println( \"rems1 rem2\" + (rems1,rems2))\n\n val remss = if(rems2 > 0) 1 else 0\n\n// println(\"remsss\" + remss)\n\n println(oat + twos + frs + r1 + remss + rems1)\n\n// println(\"oat: \" + oat)\n// println(\"twos: \" + twos)\n// println(\"frs: \" + frs)\n// println(\"rems1: \" + rems1)\n// println(\"rems2: \" + rems2)\n\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readLine()\n val numbers = readLine().split(\" \").map(_.toInt)\n\n val counted = numbers.groupBy(identity).mapValues(_.size)\n\n // (already allocated, remaining)\n val (oat,rem1) = if(counted.getOrElse(3,0) >= counted.getOrElse(1,0)) (counted.getOrElse(3,0),0) else (counted.getOrElse(3,0), counted.getOrElse(1,0) - counted.getOrElse(3,0))\n\n// println(\"aot rem1\" + (oat,rem1))\n\n val (twos,rem2) = (counted.getOrElse(2,0) /2, counted.getOrElse(2,0) % 2)\n\n// println(\"twos, rem2\" +(twos,rem2))\n\n val frs = counted.getOrElse(4,0)\n\n// println(\"frs\" + (frs))\n\n val (rems1, rems2) = ( (rem1 + rem2 )/4, (rem1+rem2) % 4)\n\n// println( \"rems1 rem2\" + (rems1,rems2))\n\n val remss = if(rems2 > 0) 1 else 0\n\n// println(\"remsss\" + remss)\n\n println(oat + twos + frs + rems1 + rems2)\n\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readLine()\n val numbers = readLine().split(\" \").map(_.toInt)\n\n val counted = numbers.groupBy(identity).mapValues(_.size)\n\n // (already allocated, remaining)\n val (oat,rem1) = if(counted.getOrElse(3,0) >= counted.getOrElse(1,0)) (counted.getOrElse(3,0),0) else (counted.getOrElse(3,0), counted.getOrElse(1,0) - counted.getOrElse(3,0))\n\n val (twos,rem2) = (counted.getOrElse(2,0) /2, counted.getOrElse(2,0) % 2)\n\n val frs = counted.getOrElse(4,0)\n\n val (rems1, rems2) = ( (rem1 + rem2 )/4, rem1+rem2 % 4)\n\n val remss = if(rems2 > 0) 1 else 0\n\n println(oat + twos + frs + rems1 + rems2)\n\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readLine()\n val numbers = readLine().split(\" \").map(_.toInt)\n\n val counted = numbers.groupBy(identity).mapValues(_.size)\n\n // (already allocated, remaining)\n val (oat,rem1) = if(counted.getOrElse(3,0) >= counted.getOrElse(1,0)) (counted.getOrElse(3,0),0) else (counted.getOrElse(3,0), counted.getOrElse(1,0) - counted.getOrElse(3,0))\n\n// println(\"aot rem1\" + (oat,rem1))\n\n val (twos,rem2) = (counted.getOrElse(2,0) /2, counted.getOrElse(2,0) % 2)\n\n// println(\"twos, rem2\" +(twos,rem2))\n\n val frs = counted.getOrElse(4,0)\n\n// println(\"frs\" + (frs))\n val (r1,r2) = (rem1/4, rem1 %4)\n\n val (rems1, rems2) = ( (r1 + rem2 )/4, (rem1+rem2) % 4)\n\n// println( \"rems1 rem2\" + (rems1,rems2))\n\n val remss = if(rems2 > 0) 1 else 0\n\n// println(\"remsss\" + remss)\n\n println(oat + twos + frs + r1 + remss + rems1)\n//\n// println(\"oat: \" + oat)\n// println(\"twos: \" + twos)\n// println(\"frs: \" + frs)\n// println(\"rems1: \" + rems1)\n// println(\"rems2: \" + rems2)\n// println(\"r1, r2\" + (r1,r2))\n// println(\"remss:\" + remss)\n\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readLine()\n val numbers = readLine().split(\" \").map(_.toInt)\n\n val counted = numbers.groupBy(identity).mapValues(_.size)\n\n // (already allocated, remaining)\n val (oat,rem1) = if(counted.getOrElse(3,0) >= counted.getOrElse(1,0)) (counted.getOrElse(3,0),0) else (counted.getOrElse(3,0), counted.getOrElse(1,0) - counted.getOrElse(3,0))\n\n// println(\"aot rem1\" + (oat,rem1))\n\n val (twos,rem2) = (counted.getOrElse(2,0) /2, counted.getOrElse(2,0) % 3)\n\n// println(\"twos, rem2\" +(twos,rem2))\n\n val frs = counted.getOrElse(4,0)\n\n// println(\"frs\" + (frs))\n\n val (rems1, rems2) = ( (rem1 + rem2 )/4, (rem1+rem2) % 4)\n\n// println( \"rems1 rem2\" + (rems1,rems2))\n\n val remss = if(rems2 > 0) 1 else 0\n\n// println(\"remsss\" + remss)\n\n println(oat + twos + frs + rems1 + remss)\n\n// println(\"oat: \" + oat)\n// println(\"twos: \" + twos)\n// println(\"frs: \" + frs)\n// println(\"rems1: \" + rems1)\n// println(\"rems2: \" + rems2)\n\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Test {\n def main(args1: Array[String]) {\n// val args = StdIn.readLine().split(\" \")\n// var (x: Long, y: Long) = (args(0).toLong, args(1).toLong)\n\n val count = StdIn.readInt\n\n val line = StdIn.readLine().split(\" \").map(s => s.toInt)\n\n var l1 = line.filter(x => x == 1).length\n var l2 = line.filter(x => x == 2).length\n var l3 = line.filter(x => x == 3).length\n var l4 = line.filter(x => x == 4).length\n\n var res = l4.toLong\n println(l4)\n if (l1 <= l3) {\n res += l3\n res += (l2 / 2) + l2 % 2\n } else {\n res += l3\n var left = l3 - l1\n l2 += (left / 2) + left % 2\n res += (l2 / 2) + l2 % 2\n println(l2)\n }\n\n\n\n println(res)\n }\n\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Test {\n def main(args1: Array[String]) {\n// val args = StdIn.readLine().split(\" \")\n// var (x: Long, y: Long) = (args(0).toLong, args(1).toLong)\n\n val count = StdIn.readInt\n\n val line = StdIn.readLine().split(\" \").map(s => s.toInt)\n\n var l1 = line.filter(x => x == 1).length\n var l2 = line.filter(x => x == 2).length\n var l3 = line.filter(x => x == 3).length\n var l4 = line.filter(x => x == 4).length\n\n var res = l4.toLong\n if (l1 <= l3) {\n res += l3\n res += (l2 / 2) + l2 % 2\n } else {\n res += l3\n var left = l3 - l1\n l2 += (left / 2) + left % 2\n res += (l2 / 2) + l2 % 2\n }\n \n println(res)\n }\n\n}"}, {"source_code": "object OneFiveEightB {\n\tdef main(args: Array[String]) {\n\t\tvar array=new Array[Int](4)\n\t\tvar n=readInt\n\t\treadLine.split(' ').foreach{x=>array(x.toInt-1)+=1}\n\t\tvar fours=array(3)\n\t\tvar threes=array(2)\n\t\tvar twos=array(1)/4\n\t\tvar rem2=array(1)%4\n\t\tvar rem1=math.max(array(0)-array(2),0)\t\t\n\t\tvar buff=0\n\t\tif(rem2!=0){\n\t\t\ttwos+=1\n\t\t\tif(rem1>2){\n\t\t\t\trem1-=2\n\t\t\t\tbuff=rem1/4\n\t\t\t\tif(rem1%4!=0){\n\t\t\t\t\tbuff+=1\n\t\t\t\t}\n\t\t\t}\n\t\t}else{\n\t\t\tif(rem1>0){\n\t\t\t\tbuff=rem1/4\n\t\t\t\tif(rem1%4!=0){\n\t\t\t\t\tbuff+=1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintln(fours+threes+twos+buff)\n\t}\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Taxi {\n def main(args: Array[String]): Unit = {\n readInt()\n val groups = readLine().split(\" \").map(_.toInt).reduce(_ + _)\n val ans = math.ceil(groups / 4.0).asInstanceOf[Int]\n println(ans)\n }\n}"}, {"source_code": "object _158_B {\n\n def main(args: Array[String]){\n var N = readLine.toInt\n\n var children = readLine.split(\" \").map(_.toInt)\n\n\n var ones: Int = children.count(_ == 1)\n var twos: Int = children.count(_ == 2)\n var threes: Int = children.count(_ == 3)\n\n val threesAndOnes = Math.min(threes, ones) // 3 + 1\n ones = Math.max(0, ones - threesAndOnes) // Remaining 1s from 3 + 1 taxis\n threes = Math.max(0, threes - threesAndOnes) // Remaining 3s from 3 + 1 taxis\n val twoAndTwo = Math.floor(twos / 2).toInt // 2 + 2\n twos = Math.max(0, twos - twoAndTwo * 2) // Remaining 2s from 2 + 2 taxis\n val twoAndOne = Math.min(ones, twos) // 2 + 1\n ones = Math.max(0, ones - twoAndOne) // Remaining 1s from 2 + 1 taxis\n twos = Math.max(0, twos - twoAndOne) // Remaining 2s from 2 + 1 taxis\n val oneAndOne = Math.floor(ones / 4).toInt // 1 + 1 + 1 + 1\n ones = Math.max(0, ones - oneAndOne * 4) // Remaining 1s from 2 + 1 taxis\n\n if (twos < 4 && twos > 0) twos = 1\n if (ones < 4 && ones > 0) ones = 1\n\n// println(\n// \"threesAndOnes: \" + threesAndOnes ,\n// \"threes: \" + threes ,\n// \"twoAndTwo: \" + twoAndTwo ,\n// \"twoAndOne: \" + twoAndOne ,\n// \"twos: \" + twos ,\n// \"oneAndOne: \" + oneAndOne ,\n// \"ones: \" + ones\n// )\n\n val taxis =\n children.count(_ == 4) +\n threesAndOnes +\n threes +\n twoAndTwo +\n twoAndOne +\n twos +\n oneAndOne +\n ones\n\n println(taxis)\n\n // def left(taxi: Int): Int =\n // if (taxi > 0) 1 else 0\n // val filteredChildren: Array[Int] = children.filter(_ != 4).sorted\n //\n // val taxis: (Int, Int) =\n // filteredChildren\n // .foldLeft((initialTaxis, 0))( // Num taxis, current capacity\n // (taxi, group) => {\n// filteredChildren(filteredChildren.indexOf(group)) = 0 // Current one will always be used somewhere\n//\n// if (group != 0)\n// if (filteredChildren contains 4 - group) { // Find best complement of group\n// filteredChildren(filteredChildren.indexOf(4 - group)) = 0\n// (taxi._1 + 1, taxi._2)\n// } else\n// if (taxi._2 + group < 4) (taxi._1, taxi._2 + group) // Hop-on\n// else if (taxi._2 + group == 4) (taxi._1 + 1, 0) // Full taxi\n// else (taxi._1 + 1, group) // Allocate new taxi\n// else taxi\n// }\n// )\n//\n// println(taxis._1 + left(taxis._2))\n }\n}"}, {"source_code": "object _158_B {\n\n def main(args: Array[String]){\n var N = readLine.toInt\n\n var children = readLine.split(\" \").map(_.toInt)\n\n def left(taxi: Int): Int =\n if (taxi > 0) 1 else 0\n\n val initialTaxis: Int = children.count(_ == 4)\n\n val filteredChildren: Array[Int] = children.filter(_ != 4).sorted\n\n val taxis: (Int, Int) =\n filteredChildren\n .foldLeft((initialTaxis, 0))( // Num taxis, current capacity\n (taxi, group) => {\n filteredChildren(filteredChildren.indexOf(group)) = 0\n\n if (group != 0)\n if (filteredChildren contains 4 - group) { // Find best complement of group\n filteredChildren(filteredChildren.indexOf(4 - group)) = 0\n (taxi._1 + 1, 0)\n } else\n if (taxi._2 + group < 4) (taxi._1, taxi._2 + group) // Hop-on\n else if (taxi._2 + group == 4) (taxi._1 + 1, 0) // Full taxi\n else (taxi._1 + 1, group) // Allocate new taxi\n else taxi\n }\n )\n\n println(taxis._1 + left(taxis._2))\n }\n}"}, {"source_code": "object _158_B {\n\n def main(args: Array[String]){\n var N = readLine.toInt\n\n val children = readLine.split(\" \").map(_.toInt).sorted\n\n\n def left(taxi: Int): Int =\n if (taxi > 0 & taxi != 4) 1 else 0\n\n val taxis: (Int, Int) =\n children.foldLeft((0, 0))(\n (taxi, group) => {\n println(group, taxi)\n if (taxi._2 + group < 4) (taxi._1, taxi._2 + group) // Hop-on\n else if (taxi._2 + group == 4) (taxi._1 + 1, 0) // Full taxi\n else (taxi._1 + 1, group) // Allocate new taxi\n }\n )\n\n println(taxis._1 + left(taxis._2))\n }\n}"}, {"source_code": "object _158_B {\n\n def main(args: Array[String]){\n var N = readLine.toInt\n\n var children = readLine.split(\" \").map(_.toInt)\n\n\n var ones: Int = children.count(_ == 1)\n var twos: Int = children.count(_ == 2)\n var threes: Int = children.count(_ == 3)\n\n val threesAndOnes = Math.min(threes, ones) // 3 + 1\n ones = Math.max(0, ones - threesAndOnes) // Remaining 1s from 3 + 1 taxis\n threes = Math.max(0, threes - threesAndOnes) // Remaining 3s from 3 + 1 taxis\n val twoAndTwo = Math.floor(twos / 2).toInt // 2 + 2\n twos = Math.max(0, twos - twoAndTwo * 2) // Remaining 2s from 2 + 2 taxis\n var twoAndOne = Math.min(ones, twos) // 2 + 1\n ones = Math.max(0, ones - twoAndOne) // Remaining 1s from 2 + 1 taxis\n twos = Math.max(0, twos - twoAndOne) // Remaining 2s from 2 + 1 taxis\n val twoAndOneAndOne = Math.min(twoAndOne, ones) // 2 + 1 + 1\n ones = Math.max(0, ones - twoAndOneAndOne) // Remaining 1s from 3 + 1 taxis\n twoAndOne = Math.max(0, twoAndOne - twoAndOneAndOne) // Remaining 2 + 1s from 2 + 1 + 1 taxis\n val oneAndOne = Math.floor(ones / 4).toInt // 1 + 1 + 1 + 1\n ones = Math.max(0, ones - oneAndOne * 4) // Remaining 1s from 2 + 1 taxis\n\n if (twos < 4 && twos > 0) twos = 1\n if (ones < 4 && ones > 0) ones = 1\n\n println(\n \"threesAndOnes: \" + threesAndOnes ,\n \"threes: \" + threes ,\n \"twoAndTwo: \" + twoAndTwo ,\n \"twoAndOne: \" + twoAndOne ,\n \"twoAndOneAndOne: \"+ twoAndOneAndOne ,\n \"twos: \" + twos ,\n \"oneAndOne: \" + oneAndOne ,\n \"ones: \" + ones\n )\n\n val taxis =\n children.count(_ == 4) +\n threesAndOnes +\n threes +\n twoAndTwo +\n twoAndOne +\n twoAndOneAndOne +\n twos +\n oneAndOne +\n ones\n\n println(taxis)\n\n // def left(taxi: Int): Int =\n // if (taxi > 0) 1 else 0\n // val filteredChildren: Array[Int] = children.filter(_ != 4).sorted\n //\n // val taxis: (Int, Int) =\n // filteredChildren\n // .foldLeft((initialTaxis, 0))( // Num taxis, current capacity\n // (taxi, group) => {\n// filteredChildren(filteredChildren.indexOf(group)) = 0 // Current one will always be used somewhere\n//\n// if (group != 0)\n// if (filteredChildren contains 4 - group) { // Find best complement of group\n// filteredChildren(filteredChildren.indexOf(4 - group)) = 0\n// (taxi._1 + 1, taxi._2)\n// } else\n// if (taxi._2 + group < 4) (taxi._1, taxi._2 + group) // Hop-on\n// else if (taxi._2 + group == 4) (taxi._1 + 1, 0) // Full taxi\n// else (taxi._1 + 1, group) // Allocate new taxi\n// else taxi\n// }\n// )\n//\n// println(taxis._1 + left(taxis._2))\n }\n}"}, {"source_code": "object _158_B {\n\n def main(args: Array[String]){\n var N = readLine.toInt\n\n val children = readLine.split(\" \").map(_.toInt).sorted\n\n\n def left(taxi: Int): Int =\n if (taxi > 0 & taxi != 4) 1 else 0\n\n val taxis: (Int, Int) =\n children.foldLeft((0, 0))( // Num taxis, current capacity\n (taxi, group) =>\n if (taxi._2 + group < 4) (taxi._1, taxi._2 + group) // Hop-on\n else if (taxi._2 + group == 4) (taxi._1 + 1, 0) // Full taxi\n else (taxi._1 + 1, group) // Allocate new taxi\n )\n\n println(taxis._1 + left(taxis._2))\n }\n}"}, {"source_code": "object _158_B {\n\n def main(args: Array[String]){\n var N = readLine.toInt\n\n var children = readLine.split(\" \").map(_.toInt)\n\n def left(taxi: Int): Int =\n if (taxi > 0) 1 else 0\n\n val ones: Int = children.count(_ == 1)\n val twos: Int = children.count(_ == 2)\n val threes: Int = children.count(_ == 3)\n\n val threeAndOnes : Int = Math.min(threes, ones) // 3 + 1 taxis\n val remainderThrees : Int = Math.max(0, threes - ones) // Remainder 3s\n val remainderOnes : Int = Math.max(0, ones - threes) // Remainder 1s\n val twoAndTwo : Int = Math.floor(twos / 2).toInt // 2 + 2 taxis\n val remainderTwo : Int = Math.max(0, twos - twoAndTwo) // Remainder 2s\n val onesAndTwos : Int = Math.min(remainderOnes, remainderTwo) // 2 + 1 taxis\n val leftOnesOrTwos : Int = Math.max(remainderOnes - onesAndTwos, remainderTwo - onesAndTwos)\n\n// println(\n// \"threeAndOnes: \" + threeAndOnes,\n// \"remainderThrees: \" + remainderThrees,\n// \"remainderOnes: \" + remainderOnes,\n// \"twoAndTwo: \" + twoAndTwo,\n// \"remainderTwo: \" + remainderTwo,\n// \"onesAndTwos: \" + onesAndTwos,\n// \"leftOnesOrTwos: \" + leftOnesOrTwos)\n\n val taxis: Int =\n children.count(_ == 4) + // Full taxis\n threeAndOnes + // 3 + 1 taxis\n remainderThrees + // 3 taxis\n onesAndTwos + // 2 + 1 taxis\n leftOnesOrTwos // 1 or 2 taxis\n\n\n println(taxis)\n\n // val filteredChildren: Array[Int] = children.filter(_ != 4).sorted\n//\n// val taxis: (Int, Int) =\n// filteredChildren\n// .foldLeft((initialTaxis, 0))( // Num taxis, current capacity\n// (taxi, group) => {\n// filteredChildren(filteredChildren.indexOf(group)) = 0 // Current one will always be used somewhere\n//\n// if (group != 0)\n// if (filteredChildren contains 4 - group) { // Find best complement of group\n// filteredChildren(filteredChildren.indexOf(4 - group)) = 0\n// (taxi._1 + 1, taxi._2)\n// } else\n// if (taxi._2 + group < 4) (taxi._1, taxi._2 + group) // Hop-on\n// else if (taxi._2 + group == 4) (taxi._1 + 1, 0) // Full taxi\n// else (taxi._1 + 1, group) // Allocate new taxi\n// else taxi\n// }\n// )\n//\n// println(taxis._1 + left(taxis._2))\n }\n}"}, {"source_code": "object _158_B {\n\n def main(args: Array[String]){\n var N = readLine.toInt\n\n val children = readLine.split(\" \").map(_.toInt)\n\n var result: Int = 0\n var taxi: Int = 0\n\n for (child <- children) {\n if (taxi == 4) {\n result = result + 1\n taxi = 0\n }\n\n val n = taxi + child\n if (n < 4) taxi = n\n else if (n > 4) {\n result = result + 1\n taxi = child\n } else if (n == 4) {\n taxi = 0\n result = result + 1\n }\n\n }\n\n if (taxi != 0) result = result + 1\n\n println(result)\n }\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\nobject Taxi {\n\n def main(args: Array[String]) = {\n val sc = new Scanner(System.in)\n val groups = readGroups(sc)\n val res = numberOfTaxis(groups)\n println(res)\n }\n\n def readGroups(sc: Scanner): mutable.HashMap[Int, Int] = {\n val res = mutable.HashMap[Int, Int](1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0)\n sc.nextLine().split(' ').foreach { _ =>\n val next = sc.nextInt()\n res.update(next, res(next) + 1)\n }\n res\n }\n\n def numberOfTaxis(groupsBySize: mutable.HashMap[Int, Int]): Int = {\n val groupsOf4 = groupsBySize(4)\n val groupsOf3And1 = math.min(groupsBySize(3), groupsBySize(1))\n val groupsOf3 = groupsBySize(3) - groupsOf3And1\n\n val remainingGroupsOf1 = groupsBySize(1) - groupsOf3And1\n val (remainingGroupsOf1Paired, oddGroupsOf1) = divWithMod(remainingGroupsOf1, 2)\n val (groupsOf2, oddGroupsOf2) = divWithMod(groupsBySize(2) + remainingGroupsOf1Paired, 2)\n\n val remaining = math.min(1, oddGroupsOf1 + oddGroupsOf2)\n\n groupsOf4 + groupsOf3And1 + groupsOf3 + groupsOf2 + remaining\n }\n\n def divWithMod(x: Int, y: Int): (Int, Int) = {\n val r = x / y\n val m = x % y\n (r, m)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.annotation.tailrec\n\nobject Taxi {\n\n def main(args: Array[String]) = {\n val sc = new Scanner(System.in)\n val numOfGroups = sc.nextInt()\n sc.nextLine()\n val groups = (1 to numOfGroups).map { _ => sc.nextInt() }.toList\n val res = numberOfTaxis(groups)\n println(res)\n }\n\n case class GroupType(size: Int, count: Int) {\n def dec: GroupType = copy(count = count - 1)\n }\n\n def numberOfTaxis(groups: List[Int]): Int = {\n @tailrec\n def numberOfTaxisRec(acc: Int, groupTypes: Vector[GroupType]): Int = {\n if (groupTypes.isEmpty) acc\n else if (groupTypes.head.count == 0) numberOfTaxisRec(acc, groupTypes.tail)\n else {\n val withoutMax = groupTypes.updated(0, groupTypes(0).dec)\n val complGroupTypeIdx = withoutMax.indexWhere(gt => gt.size + groupTypes.head.size <= 4 && gt.count > 0)\n val withoutMaxAndCompl =\n if (complGroupTypeIdx == -1) withoutMax\n else withoutMax.updated(complGroupTypeIdx, withoutMax(complGroupTypeIdx).dec)\n numberOfTaxisRec(acc + 1, withoutMaxAndCompl)\n }\n }\n\n val groupTypes = groups\n .groupBy(identity)\n .map { case (size, values) => GroupType(size, values.size) }\n .toVector\n .sortBy(- _.size)\n numberOfTaxisRec(0, groupTypes)\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ListBuffer\n\nobject task158B {\n def encode[IntA](list: List[Int]):List[(Int,Int)] = {\n var l:List[(Int,Int)] = Nil\n l=(1,0)::l; l=(2,0)::l; l=(3,0)::l; l=(4,0)::l;\n list.foldLeft(l) { (r,c) =>\n r match {\n case (value, count) :: tail =>\n if (value == c) (c, count+1) :: tail\n else (c, 1) :: r\n case Nil => (c, 1) :: r\n }\n }\n }\n\n def main(args:Array[String]) {\n val in=io.Source.stdin.getLines.toList\n val Array(n)=in(0).split(\" \").map(_.toInt)\n val s=in(1).split(\" \").map(_.toInt).toList\n var t=encode(s.sorted).sorted\n //println(t)\n var k1=t(0)._2; var k2=t(1)._2 ; val k3=t(2)._2; var rv=t(3)._2\n rv+=k3; if (k3>k1) { k1=0; } else { k1-=k3; }\n rv+=k2/2; k2=k2%2; if (k2==1) { rv+=1; k2=0; if (k1>=2) { k1-=2; } else { k1=0; } }\n rv+=k1/4; k1=k1%4; if (k1!=0) { rv+=1; }\n println(rv)\n }\n}\n"}, {"source_code": "object cf extends App{\n val n = readInt()\n val arr = Array.fill[Int](5)(0)\n var nums = readLine().split(\" \").map(_.toInt)\n for (i <- 0 to n-1) {\n val x = nums(i)\n arr(x) += 1\n }\n var res = 0\n res += arr(4)\n res += arr(3)\n arr(1) -= arr(3)\n arr(1) = arr(1).max(0)\n arr(3) = 0\n res += arr(2)/2\n arr(2) = arr(2) % 2\n arr(1) += arr(2)\n res += arr(1)/4\n if (arr(1) % 4 != 0) res += 1\n //make it go\n println(res)\n}"}, {"source_code": "object cf extends App{\n val n = readInt()\n val arr = Array.fill[Int](5)(0)\n var nums = readLine().split(\" \").map(_.toInt)\n for (i <- 0 to n-1) {\n val x = nums(i)\n arr(x) += 1\n }\n var res = 0\n res += arr(4)\n res += arr(3)\n arr(1) -= arr(3)\n arr(1) = arr(1).max(0)\n arr(3) = 0\n res += arr(2)/2\n arr(2) = arr(2) % 2\n arr(1) += arr(2)\n res += arr(1)/4\n if (arr(1) % 4 != 0) res += 1\n println(res)\n}"}, {"source_code": "object Solution158B extends Application {\n\n def solution() {\n val n = _int\n val groups = 1.to(n).map(_ => _int).groupBy(x => x).mapValues(seq => seq.size)\n\n val n1 = groups.get(1).getOrElse(0)\n val n2 = groups.get(2).getOrElse(0)\n val n3 = groups.get(3).getOrElse(0)\n val n4 = groups.get(4).getOrElse(0)\n val res = n4 + n3 + (n2 / 2 + n2 % 2)\n val left = n1 - n3 - (2 * n2%2)\n\n println(res + (if (left > 0) left / 4 else 0))\n }\n\n //////////////////////////////////////////////////\n import java.util.Scanner\n val SC: Scanner = new Scanner(System.in)\n def _line: String = SC.nextLine\n def _int: Int = SC.nextInt\n def _long: Long = SC.nextLong\n def _string: String = SC.next\n solution()\n}"}, {"source_code": "import scala.collection.mutable._\nimport scala.math._\nimport scala.util.control.Breaks.break\nimport scala.util.control.Breaks.breakable\nimport java.util._\nobject Main extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt\n val t = for(i <- 1 to n) yield sc.nextInt\n val tc = for(i <- 0 to 4) yield t.count(_ == i)\n println(tc(4) + tc(3) + (tc(2)+1)/2 + (3+max(0, tc(1) - tc(3) - tc(2) % 2))/4)\n}\n"}, {"source_code": "import scala.collection.mutable._\nimport scala.math._\nimport scala.util.control.Breaks.break\nimport scala.util.control.Breaks.breakable\nimport java.util._\nobject Main extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt\n val t = for(i <- 1 to n) yield sc.nextInt\n val tc = for(i <- 0 to 4) yield t.count(_ == i)\n println(tc(4) + tc(3) + (tc(2)+1)/2 + max(0, tc(1) - tc(3) - tc(2) % 2))\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val std = scala.io.StdIn\n\n val n = std.readInt()\n val line = std.readLine().split(\" \").map(_.toInt)\n val counts = new Array[Int](5)\n line.foreach(x => counts(x) += 1)\n\n var counts2 = counts(2) / 2\n var notPairedCounts2 = counts(2) % 2\n val result = counts(4) + counts(3) + counts2 + notPairedCounts2 + Math.max(0, counts(1) - counts(3) - notPairedCounts2 * 2 )\n println(result)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val std = scala.io.StdIn\n\n val n = std.readInt()\n val line = std.readLine().split(\" \").map(_.toInt)\n val counts = new Array[Int](5)\n line.foreach(x => counts(x) += 1)\n val counts2 = (counts(2) + 1) / 2\n val singlesLeft = Math.max(0, counts(1) - counts(3) - (counts2 % 2) * 2 )\n val result = counts(4) + counts(3) + counts2 + (singlesLeft + 3) / 4\n println(result)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject B {\n def main(args: Array[String]) = {\n val n = StdIn.readLine.toInt\n val s = StdIn.readLine.split(\" \").map(_.toInt)\n val freqMap: Map[Int, Int] = s.groupBy(x => x).mapValues(_.length)\n\n var ans = freqMap.getOrElse(4, 0)\n ans += freqMap.getOrElse(3, 0)\n ans += (freqMap.getOrElse(2, 0) + 1) / 2\n ans += Math.max(freqMap.getOrElse(1, 0) - freqMap.getOrElse(3, 0) - (if (freqMap.getOrElse(2, 0) % 2 == 0) 0 else 1), 0)\n\n println(ans)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.language.implicitConversions\n\nobject B {\n implicit def toInt(b: Boolean) = if (b) 1 else 0\n\n def main(args: Array[String]) = {\n val n = StdIn.readLine.toInt\n val s = StdIn.readLine.split(\" \").map(_.toInt)\n val freqMap: Map[Int, Int] = s.groupBy(x => x).mapValues(_.length)\n \n val ones = freqMap.getOrElse(1, 0)\n val twos = freqMap.getOrElse(2, 0)\n val threes = freqMap.getOrElse(3, 0)\n val fours = freqMap.getOrElse(4, 0)\n\n val mod = twos % 2 == 1\n val ans = fours + threes + (twos + 1) / 2 + Math.max(ones - threes - mod, 0) / 4\n\n println(ans)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.language.implicitConversions\n\nobject B {\n implicit def toInt(b: Boolean) = if (b) 1 else 0\n\n def main(args: Array[String]) = {\n val n = StdIn.readLine.toInt\n val s = StdIn.readLine.split(\" \").map(_.toInt)\n val freqMap: Map[Int, Int] = s.groupBy(x => x).mapValues(_.length)\n \n val ones = freqMap.getOrElse(1, 0)\n val twos = freqMap.getOrElse(2, 0)\n val threes = freqMap.getOrElse(3, 0)\n val fours = freqMap.getOrElse(4, 0)\n\n val mod = twos % 2 == 1\n val ans = fours + threes + (twos + 1) / 2 + Math.max(ones - threes - mod + 3, 0) / 4\n println(ans)\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ListBuffer;\n\nobject Taxi {\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val l = Array.fill(5)(0)\n for(x <- readLine().split(\" \").map(_.toInt)) l(x) += 1\n if(l(3) >= l(1))\n println(l(4) + l(3) + math.ceil(l(2).toDouble/4).toInt)\n else\n println(l(4) + l(3) + math.ceil((l(2) + l(1)-l(3)).toDouble / 4).toInt )\n }\n\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer;\n\nobject Taxi {\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val l = Array.fill(n+1)(0)\n for(x <- readLine().split(\" \").map(_.toInt)) l(x) += 1\n println(l(4) + l(3) + 2*l(2)/4 + l(3)-l(1)+3/4)\n \n }\n\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer;\n\nobject Taxi {\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val l = Array.fill(5)(0)\n for(x <- readLine().split(\" \").map(_.toInt)) l(x) += 1\n if(l(3) >= l(1))\n println(l(4) + l(3) + 2*l(2)/4 + (l(3)-l(1)+3)/4)\n else\n println(l(4) + l(3) + 2*l(2)/4 + (l(1)-l(3)+3)/4)\n }\n\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer;\n\nobject Taxi {\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val l = Array.fill(5)(0)\n for(x <- readLine().split(\" \").map(_.toInt)) l(x) += 1\n if(l(3) >= l(1))\n println(l(4) + l(3) + math.ceil(2*l(2).toDouble/4).toInt)\n else\n println(l(4) + l(3) + math.ceil(2*l(2).toDouble/4).toInt + (l(1)-l(3)+3)/4)\n }\n\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer;\n\nobject Taxi {\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val l = Array.fill(n+1)(0)\n for(x <- readLine().split(\" \").map(_.toInt)) l(x) += 1\n println(l(4) + l(3) + 2*l(2)/4 + (math.max(l(3)-l(1), 0)+3)/4)\n \n }\n\n}"}, {"source_code": "import scala.io.StdIn\n\nobject p158b extends App {\n\n private val n = StdIn.readLine.toInt\n val array=new Array[Int](5)\n\n val line=StdIn.readLine.split(\" \").map(_.toInt).sortBy(identity).reverse\n for (i<- line ){\n array(i)+=1\n }\n\n var sum=array(4)\n if(array(3)>array(1)) {\n sum+=array(3)\n array(1)=0\n }\n else{\n sum+=array(3)\n array(1)-=array(3)\n }\n\n sum+=array(2)/2\n val remain=array(2)%2\n\n if(remain==1){\n if(array(1)>2){\n array(1)-=2\n sum+=1\n }\n else{\n sum+=1\n }\n }\n\n sum+=array(1)/4\n val remain1=array(1)%4\n if(remain1>0){\n sum+=1\n }\n\n print(sum)\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject p158b extends App {\n\n private val n = StdIn.readLine.toInt\n val array=new Array[Int](5)\n\n val line=StdIn.readLine.split(\" \").map(_.toInt).sortBy(identity).reverse\n for (i<- line ){\n array(i)+=1\n }\n\n var sum=array(4)\n if(array(3)>array(1)) {\n sum+=array(3)\n array(1)=0\n }\n else{\n sum+=array(3)\n array(1)-=array(3)\n }\n\n sum+=array(2)/2\n val remain=array(2)%2\n\n if(remain==1){\n if(array(1)>2){\n array(1)-=2\n sum+=1\n }\n else if(array(1)==1){\n array(1)=0\n sum+=1\n }\n else{\n sum+=1\n }\n }\n\n sum+=array(1)/4\n val remain1=array(1)%4\n if(remain1>0){\n sum+=1\n }\n\n print(sum)\n}\n"}, {"source_code": "import collection.immutable.IndexedSeq\nimport collection.mutable.ArrayBuffer\nimport java.util.Scanner\n\nobject B extends App {\n\tval in = new Scanner(System.in)\n\tval n = in.nextInt()\n\tval s = for (_ <- Array.range(1, n)) yield in.nextInt()\n\tval cars = (ArrayBuffer[Int]() /: s.sorted(Ordering[Int].reverse)) {\n\t\tdef firstFit(currentCars: ArrayBuffer[Int], numberOfFriends: Int): ArrayBuffer[Int] = {\n\t\t\tval firstFitIndex = currentCars.indexWhere(4 - _ >= numberOfFriends)\n\t\t\tif (firstFitIndex == -1) {\n\t\t\t\tcurrentCars += numberOfFriends\n\t\t\t} else {\n\t\t\t\tcurrentCars(firstFitIndex) += numberOfFriends\n\t\t\t}\n\t\t\tcurrentCars\n\t\t}\n\t\tfirstFit\n\t}\n\tprintln(cars.size)\n}\n"}, {"source_code": "\nimport scala.math._\n\nobject Taxy extends App{\n\n import scala.collection.mutable.Map\n val n = readInt\n val arr = readLine.split(\" \").map(_.toInt)\n val mp = Map[Int, Int]()\n\n (1 to 4).foreach(x => mp(x) = 0)\n arr.foreach(x => mp(x) += 1)\n\n val four = mp(4)\n val third = mp(3)\n mp(1) = max(mp(1) - mp(3), 0)\n val second = mp(2) / 2 + max(min(2 * (mp(2) % 2), mp(1)), mp(2) % 2)\n mp(1) = max(mp(1) - 2 * (mp(2) % 2), 0)\n val first = mp(1) / 4 + {if( (mp(1) % 4) != 0) 1 else 0}\n\n println(first + second + third + four)\n\n}\n"}, {"source_code": "import scala.util.Sorting\n\nobject _158B extends App\n{\n val n = readLine().toInt\n val groups = (readLine().split(\" \") map (_.toInt)).sortWith(_ > _)\n var b = n - 1\n var cur = 0\n var ans = 0\n\n for ( a <- 0 until n ; if a <= b ) {\n if (groups(a) + groups(b) > 4) {\n ans += 1\n } else {\n ans += 1\n b -= 1\n }\n }\n\n println(ans)\n}\n"}, {"source_code": "import scala.util.Sorting\n\nobject _158B extends App\n{\n val n = readLine().toInt\n var fours = 0\n var threes = 0\n var twos = 0\n var ones = 0\n val groups = (readLine().split(\" \") map (_.toInt)) foreach (x => \n x match {\n case 4 => fours += 1\n case 3 => threes += 1\n case 2 => twos += 1\n case 1 => ones += 1\n case _ => println(x)\n })\n //println(fours + \" \" + threes + \" \" + twos + \" \" + ones)\n var ans = fours\n\n while (threes > 0) {\n if (threes >= ones) {\n ans += 1\n threes -= 1\n ones -= 1\n } else {\n ans += 1\n threes -= 1\n }\n }\n\n while (twos > 0) {\n if (twos >= 2) {\n twos -= 2\n ans += 1\n } else if (ones >= 2) {\n twos -= 1\n ones -= 2\n ans += 1\n } else {\n twos -= 1\n ans += 1\n }\n }\n\n while (ones >= 4) {\n ans += 1\n ones -= 4\n }\n if (ones > 0) {\n ans += 1\n }\n\n println(ans)\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P158B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val s = List.fill(N)(sc.nextInt).groupBy(identity[Int]).map(x => (x._1 -> x._2.length))\n\n def solve: Int =\n if (s(1) == s(2)) s(4) + s(2) / 2 + s(2) % 2 + s(1)\n else s(4) + s(2) / 2 + (s(3) max s(1))\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P158B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val s = List.fill(N)(sc.nextInt).groupBy(identity[Int]).map(x => (x._1 -> x._2.length))\n val t = for (i <- 1 to 4) yield s.getOrElse(i, 0)\n\n def solve: Int =\n if (t(0) > t(2)) t(3) + t(0) + t(1) / 2\n else t(3) + t(2) + t(1) / 2 + t(1) % 2\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P158B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val s = List.fill(N)(sc.nextInt).groupBy(identity[Int]).map(x => (x._1 -> x._2.length))\n\n def solve: Int =\n if (s(1) == s(3)) s(4) + s(2) / 2 + s(2) % 2 + s(1)\n else s(4) + s(2) / 2 + (s(3) max s(1))\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject R158_B extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n val groups = for(i <- 0 until n) yield sc.nextInt()\n\n println(process(groups))\n\n def process(groups:Seq[Int]):Int = {\n var a = new Array[Int](4)\n groups.foreach(g => {\n val k = g-1\n a(k)=a(k)+1\n })\n var c = 0\n c += a(3)\n c += a(2)\n if(a(2)2){\n a(0)=a(0)-2\n }else{\n a(0)=0\n }\n }\n c += a(0)/4\n c\n }\n}"}, {"source_code": "\n\nobject Taxi {\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in)\n\t\t\t\tval n = scanner.nextInt\n\t\t\t\tvar remainder = 4\n\t\t\t\tvar number = 1\n\t\t\t\tfor (i <- 1 to n) {\n\t\t\t\t\tremainder = remainder - scanner.nextInt\n\t\t\t\t\tif (remainder <= 0) {\n\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\t\tremainder = remainder + 4\n\t\t\t\t\t}\n\t\t\t\t}\n\t\tprintln(number)\n\t}\n}"}, {"source_code": "\n\nobject Taxi {\n\tvar availableCars = collection.mutable.Map[Int,Int]((1,0), (2,0), (3,0))\n\n\t\t\tdef addCar (index: Int) {\n\t\tavailableCars += index -> (availableCars(index) + 1)\n\t}\n\n\tdef removeCar (index: Int) {\n\t\tavailableCars += index -> (availableCars(index) - 1)\n\t}\n\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in)\n\t\t\t\tval n = scanner.nextInt\n\t\t\t\tvar number = 0\n\t\t\t\tfor (i <- 1 to n) {\n\t\t\t\t\tval current = scanner.nextInt\n\t\t\t\t\t\t\tcurrent match {\n\t\t\t\t\t\t\tcase 4 =>\n\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\tcase 3 =>\n\t\t\t\t\t\t\tif (availableCars(1) > 0) {\n\t\t\t\t\t\t\t\tremoveCar(1)\n\t\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddCar(3)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase 2 =>\n\t\t\t\t\t\t\tif (availableCars(2) > 0) {\n\t\t\t\t\t\t\t\tremoveCar(2)\n\t\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddCar(2)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase 1 =>\n\t\t\t\t\t\t\tif (availableCars(3) > 0) {\n\t\t\t\t\t\t\t\tremoveCar(3)\n\t\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\taddCar(1)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\twhile (availableCars(3) > 0 && availableCars(1) > 0) {\n\t\t\tnumber = number + 1\n\t\t\t\t\tremoveCar(3)\n\t\t\t\t\tremoveCar(1)\n\t\t}\n\t\twhile (availableCars(2)>1) {\n\t\t\tval div2 = availableCars(2) / 2\n\t\t\t\t\tnumber = number + div2\n\t\t\t\t\tavailableCars += 2 -> availableCars(2) % 2\n\t\t}\n\t\tif (availableCars(2) > 0 && availableCars(1) / 2 > 0) {\n\t\t\tif (availableCars(2) - (availableCars(1) / 2) > 0) {\n\t\t\t val tmp = availableCars(2) - (availableCars(1) / 2)\n\t\t\t\tavailableCars += 2 -> tmp\n\t\t\t\tnumber = number + (availableCars(1) / 2)\n\t\t\t\tavailableCars += 1 -> availableCars(1) % 2\n\t\t\t}\n\t\t\telse {\n\t\t\t availableCars += 1 -> (availableCars(1) - (2* availableCars(2)))\n\t\t\t\tnumber = number + availableCars(2)\n\t\t\t availableCars += 2 -> 0\n\t\t\t}\n\t\t}\n\t\tnumber = number + availableCars(1) / 4 \n\t\tavailableCars += 1 -> availableCars(1) % 4 \n\t\tprintln(number+availableCars(3)+availableCars(2)+availableCars(1))\n\t}\n}"}, {"source_code": "\n\nobject Taxi {\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in)\n\t\t\t\tval n = scanner.nextInt\n\t\t\t\tvar availableCars = collection.mutable.Set[Int]()\n\t\t\t\tvar number = 0\n\t\t\t\tfor (i <- 1 to n) {\n\t\t\t\t\tval current = scanner.nextInt\n\t\t\t\t\tcurrent match {\n\t\t\t\t\tcase 4 =>\n\t\t\t\t\tnumber = number + 1\n\t\t\t\t\tcase 3 =>\n\t\t\t\t\tif (availableCars contains 1) {\n\t\t\t\t\t\tavailableCars -= 1\n\t\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tavailableCars += 3\n\t\t\t\t\t}\n\t\t\t\t\tcase 2 =>\n\t\t\t\t\tif (availableCars contains 2) {\n\t\t\t\t\t\tavailableCars -= 2\n\t\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (availableCars contains 1) {\n\t\t\t\t\t\t\tavailableCars -= 1\n\t\t\t\t\t\t\t\t\tavailableCars += 3\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t availableCars += 2\n \t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcase 1 =>\n\t\t\t\t\tif (availableCars contains 3) {\n\t\t\t\t\t\tavailableCars -= 3\n\t\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (availableCars contains 2) {\n\t\t\t\t\t\t\tavailableCars -= 2\n\t\t\t\t\t\t\t\t\tavailableCars += 3\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (availableCars contains 1) {\n\t\t\t\t\t\t\t\tavailableCars -= 1\n\t\t\t\t\t\t\t\t\t\tavailableCars += 2\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tavailableCars += 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\tprintln(availableCars.size+number)\n\t}\n}"}, {"source_code": "\n\nobject Taxi {\n\tvar availableCars = collection.mutable.Map[Int,Int]((1,0), (2,0), (3,0))\n\n\t\t\tdef addCar (index: Int) {\n\t\tavailableCars += index -> (availableCars(index) + 1)\n\t}\n\n\tdef removeCar (index: Int) {\n\t\tavailableCars += index -> (availableCars(index) - 1)\n\t}\n\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in)\n\t\t\t\tval n = scanner.nextInt\n\t\t\t\tvar number = 0\n\t\t\t\tfor (i <- 1 to n) {\n\t\t\t\t\tval current = scanner.nextInt\n\t\t\t\t\t\t\tcurrent match {\n\t\t\t\t\t\t\tcase 4 =>\n\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\tcase 3 =>\n\t\t\t\t\t\t\tif (availableCars(1) > 0) {\n\t\t\t\t\t\t\t\tremoveCar(1)\n\t\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddCar(3)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase 2 =>\n\t\t\t\t\t\t\tif (availableCars(2) > 0) {\n\t\t\t\t\t\t\t\tremoveCar(2)\n\t\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddCar(2)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase 1 =>\n\t\t\t\t\t\t\tif (availableCars(3) > 0) {\n\t\t\t\t\t\t\t\tremoveCar(3)\n\t\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\taddCar(1)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\twhile (availableCars(3) > 0 && availableCars(1) > 0) {\n\t\t\tnumber = number + 1\n\t\t\t\t\tremoveCar(3)\n\t\t\t\t\tremoveCar(1)\n\t\t}\n\t\twhile (availableCars(2) > 1) {\n\t\t\tval div2 = availableCars(2) / 2\n\t\t\t\t\tnumber = number + div2\n\t\t\t\t\tavailableCars += 2 -> availableCars(2) % 2\n\t\t}\n\t\tif (availableCars(2) == 1) {\n\t\t\tremoveCar(2)\n\t\t\tif (availableCars(1) >= 2) {\n\t\t\t\tremoveCar(1)\n\t\t\t\tremoveCar(1)\n\t\t\t}\n\t\t\telse {\n\t\t\t\tavailableCars += 1 -> 0\n\t\t\t}\n\t\t\tnumber = number + 1\n\t\t}\n\n\t\tnumber = number + availableCars(1) / 4 \n\t\t\t\tavailableCars += 1 -> availableCars(1) % 4\n/**\n\t\t\t\tprintln(\"------------\")\n\t\t\t\tprintln(\"number: \"+number)\n\t\t\t\tprintln(\"availableCars: \"+availableCars)\n\t\t\t\tprintln(\"------------\")\n**/\n\t\t\t\tprintln(number+availableCars(3)+availableCars(2)+availableCars(1))\n\t}\n}"}, {"source_code": "\n\nobject Taxi {\n\tvar availableCars = collection.mutable.Map[Int,Int]((1,0), (2,0), (3,0))\n\n\t\t\tdef addCar (index: Int) {\n\t\tavailableCars += index -> (availableCars(index) + 1)\n\t}\n\n\tdef removeCar (index: Int) {\n\t\tavailableCars += index -> (availableCars(index) - 1)\n\t}\n\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in)\n\t\t\t\tval n = scanner.nextInt\n\t\t\t\tvar number = 0\n\t\t\t\tfor (i <- 1 to n) {\n\t\t\t\t\tval current = scanner.nextInt\n\t\t\t\t\t\t\tcurrent match {\n\t\t\t\t\t\t\tcase 4 =>\n\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\tcase 3 =>\n\t\t\t\t\t\t\tif (availableCars(1) > 0) {\n\t\t\t\t\t\t\t\tremoveCar(1)\n\t\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddCar(3)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase 2 =>\n\t\t\t\t\t\t\tif (availableCars(2) > 0) {\n\t\t\t\t\t\t\t\tremoveCar(2)\n\t\t\t\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tif (availableCars(1) > 0) {\n\t\t\t\t\t\t\t\t\tremoveCar(1)\n\t\t\t\t\t\t\t\t\taddCar(3)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\taddCar(2)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase 1 =>\n\t\t\t\t\t\t\tif (availableCars(3) > 0) {\n\t\t\t\t\t\t\t\tremoveCar(3)\n\t\t\t\t\t\t\t\tnumber = number + 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tif (availableCars(2) > 0) {\n removeCar(2)\n\t\t\t\t\t\t\t\t\t\t\taddCar(3)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tif (availableCars(1) > 0) {\n removeCar(1)\n\t\t\t\t\t\t\t\t\t\t\taddCar(2)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\taddCar(1)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\tprintln(availableCars(1)+availableCars(2)+availableCars(3)+number)\n\t}\n}"}, {"source_code": "object Codeforces158B extends App{\n\n def TaxiNumber(ques:String):Int={\n var ans:Int=0\n val conv=ques.split(\" \").map(_.toInt)\n var numset:Array[Int]=Array(0,0,0,0,0)\n for (i <- conv){\n numset(i)+=1\n }\n ans+=numset(4)\n if (numset(3)<=numset(1)){\n ans+=numset(3)\n var temp=numset(1)-numset(3)\n if (numset(2)%2==0){\n ans+=numset(2)/2\n ans+=temp/4\n if (temp%4!=0){\n ans+=1\n }\n }\n else{\n ans+=numset(2)/2+1\n temp-=2\n ans+=temp/4\n if (temp%4!=0){\n ans+=1\n }\n }\n }\n else{\n ans+=numset(3)\n ans+=numset(2)/2\n if (numset(2)%2==1){\n ans+=1\n }\n }\n return ans\n }\n\n val s:Int=scala.io.StdIn.readInt\n val k=scala.io.StdIn.readLine\n println(TaxiNumber(k))\n\n}\n"}, {"source_code": "/**\n * Created by vol on 9/16/14.\n */\nobject B158 extends App{\n val n = readInt()\n val friends = readLine().split(\" \").map(_.toInt)\n val counts = friends.foldLeft(Map(1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0)) {\n (count, fr) => count + (fr -> (count.getOrElse(fr, 0) + 1))\n }\n\n val cTwo = counts(2) / 2\n\n val mTwo = counts(2) * 2 % 4 / 2\n\n val cFour = counts(4)\n\n if(!counts.contains(2)) {\n\n }\n\n// println(\"twos -> \" + counts(2))\n//\n// println(\"mod from twos -> \" + counts(2) * 2 % 4)\n//\n// println(\"fours -> \" + counts(4))\n//\n// println(\"threes -> \" + counts(3))\n//\n// println(\"ones -> \" + counts(1))\n\n\n val combinedCount = if (counts(3) == counts(1)) counts(3) else counts(3).min(counts(1))\n\n val bigger = if (counts(3) > counts(1)) \"three\" else if (counts(3) == counts(1)) \"equal\" else \"one\"\n\n\n\n if (bigger == \"one\") {\n val cOne = Math.abs(counts(3) - counts(1))\n if (mTwo == 0) println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4)\n else\n if (cOne > 2)\n println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4 + 1)\n else\n println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4)\n\n } else if (bigger == \"equal\"){\n println(combinedCount)\n println(cTwo + cFour + mTwo + combinedCount)\n }\n else {\n val cThree = Math.abs(counts(3) - counts(1))\n// println(cTwo)\n// println(cFour)\n// println(mTwo)\n// println(cThree)\n// println(combinedCount)\n println(cTwo + cFour + mTwo + cThree + combinedCount)\n }\n\n\n\n\n}\n"}, {"source_code": "/**\n * Created by vol on 9/16/14.\n */\nobject B158 extends App{\n val n = readInt()\n val friends = readLine().split(\" \").map(_.toInt)\n val counts = friends.foldLeft(Map(1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0)) {\n (count, fr) => count + (fr -> (count.getOrElse(fr, 0) + 1))\n }\n\n val fTwo = counts(2) / 2\n\n val twoLeft = counts(2) * 2 % 4\n\n //четверки собранны\n val fFour = counts(4)\n\n //число скомбенированные 3 и 1\n val (fThreeOne, left:(Int, Int)) = if (counts(3) == counts(1)) (counts(3), (0, 0)) else {\n val min = counts(3).min(counts(1))\n (min, (Map(3 -> counts(3), 1 -> counts(1)).maxBy(_._2)._1, Math.abs(counts(3) - counts(1))))\n }\n\n // комбинируем 2 с 1\n\n val (fTwoOne:Int, left1:(Int, Int)) = if (twoLeft != 0) left match {\n case (0, 0) => (0, left)\n case (num:Int, count:Int) if num == 3 => (0, left)\n case (num:Int, count:Int) if num == 1 => if (count >= 2) (1, (num, count - 2))\n }\n\n\n val fLeft = if (left1._1 == 3) left1._2 else {\n if (left1._2 < 4) {\n 1\n } else {\n val modQ = if (left1._2 % 4 == 0) 0 else 1\n left1._2 / 4 + modQ\n }\n }\n\n println(fTwo + fFour + fLeft + fThreeOne + fTwoOne)\n\n\n\n\n\n\n\n}\n"}, {"source_code": "/**\n * Created by vol on 9/16/14.\n */\nobject B158 extends App{\n val n = readInt()\n val friends = readLine().split(\" \").map(_.toInt)\n val counts = friends.foldLeft(Map(1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0)) {\n (count, fr) => count + (fr -> (count.getOrElse(fr, 0) + 1))\n }\n\n val cTwo = counts(2) / 2\n\n val mTwo = counts(2) * 2 % 4 / 2\n\n val cFour = counts(4)\n\n if(!counts.contains(2)) {\n\n }\n\n// println(\"twos -> \" + counts(2))\n//\n// println(\"mod from twos -> \" + counts(2) * 2 % 4)\n//\n// println(\"fours -> \" + counts(4))\n//\n// println(\"threes -> \" + counts(3))\n//\n// println(\"ones -> \" + counts(1))\n\n\n val combinedCount = if (counts(3) == counts(1)) counts(3) else counts(3).min(counts(1))\n\n val bigger = if (counts(3) > counts(1)) \"three\" else if (counts(3) == counts(1)) \"equal\" else \"one\"\n\n\n if (bigger == \"one\") {\n val cOne = Math.abs(counts(3) - counts(1))\n if (mTwo == 0) {\n if (cOne/ 4 == 0 && cOne > 0 && cOne < 4) println(cTwo + cFour + combinedCount + 1)\n else println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4)\n }\n else\n if (cOne > 2) {\n println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4 + 1) }\n else\n println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4)\n\n } else if (bigger == \"equal\"){\n println(cTwo + cFour + mTwo + combinedCount)\n }\n else {\n val cThree = Math.abs(counts(3) - counts(1))\n// println(cTwo)\n// println(cFour)\n// println(mTwo)\n// println(cThree)\n// println(combinedCount)\n println(cTwo + cFour + mTwo + cThree + combinedCount)\n }\n\n\n\n\n}\n"}, {"source_code": "/**\n * Created by vol on 9/16/14.\n */\nobject B158 extends App{\n val n = readInt()\n val friends = readLine().split(\" \").map(_.toInt)\n val counts = friends.foldLeft(Map(1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0)) {\n (count, fr) => count + (fr -> (count.getOrElse(fr, 0) + 1))\n }\n\n val fTwo = counts(2) / 2\n\n val twoLeft = counts(2) * 2 % 4\n\n //четверки собранны\n val fFour = counts(4)\n\n //число скомбенированные 3 и 1\n val (fThreeOne, left:(Int, Int)) = if (counts(3) == counts(1)) (counts(3), (0, 0)) else {\n val min = counts(3).min(counts(1))\n (min, (Map(3 -> counts(3), 1 -> counts(1)).maxBy(_._2)._1, Math.abs(counts(3) - counts(1))))\n }\n \n // комбинируем 2 с 1\n val (fTwoOne:Int, left1:(Int, Int)) = if (twoLeft != 0) left match {\n\n case (0, 0) => (0, left)\n case (num: Int, count: Int) if num == 3 => (1, left)\n case (num: Int, count: Int) if num == 1 => if (count >= 2) (1, (num, count - 2)) else (1,(0, 0))\n\n } else (0, left)\n\n\n\n val fLeft = if (left1._1 == 3) left1._2 else {\n if (left1._2 < 4 && left1._2 != 0) {\n 1\n } else if (left1._2 == 0) {\n 0\n } else {\n val modQ = if (left1._2 % 4 == 0) 0 else 1\n left1._2 / 4 + modQ\n }\n }\n println(fTwo + fFour + fLeft + fThreeOne + fTwoOne)\n\n\n\n\n\n\n\n}\n"}, {"source_code": "/**\n * Created by vol on 9/16/14.\n */\nobject B158 extends App{\n val n = readInt()\n val friends = readLine().split(\" \").map(_.toInt)\n val counts = friends.foldLeft(Map(1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0)) {\n (count, fr) => count + (fr -> (count.getOrElse(fr, 0) + 1))\n }\n\n val cTwo = counts(2) / 2\n\n val mTwo = counts(2) * 2 % 4\n\n val cFour = counts(4)\n\n if(!counts.contains(2)) {\n\n }\n\n// println(\"twos -> \" + counts(2))\n//\n// println(\"mod from twos -> \" + counts(2) * 2 % 4)\n//\n// println(\"fours -> \" + counts(4))\n//\n// println(\"threes -> \" + counts(3))\n//\n// println(\"ones -> \" + counts(1))\n\n\n val combinedCount = if (counts(3) == counts(1)) counts(3) else counts(3).min(counts(1))\n\n val bigger = if (counts(3) > counts(1)) \"three\" else if (counts(3) == counts(1)) \"equal\" else \"one\"\n\n\n\n if (bigger == \"one\") {\n val cOne = Math.abs(counts(3) - counts(1))\n if (mTwo == 0) println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4)\n else\n if (cOne > 2)\n println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4 + 1)\n else\n println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4)\n\n } else if (bigger == \"equal\"){\n println(cTwo + cFour + 1 + combinedCount)\n }\n else {\n val cThree = Math.abs(counts(3) - counts(1))\n// println(cTwo)\n// println(cFour)\n// println(mTwo)\n// println(cThree)\n// println(combinedCount)\n println(cTwo + cFour + 1 + cThree + combinedCount)\n }\n\n\n\n\n}\n"}, {"source_code": "/**\n * Created by vol on 9/16/14.\n */\nobject B158 extends App{\n val n = readInt()\n val friends = readLine().split(\" \").map(_.toInt)\n val counts = friends.foldLeft(Map(1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0)) {\n (count, fr) => count + (fr -> (count.getOrElse(fr, 0) + 1))\n }\n\n val fTwo = counts(2) / 2\n\n val twoLeft = counts(2) * 2 % 4\n\n //четверки собранны\n val fFour = counts(4)\n\n //число скомбенированные 3 и 1\n val (fThreeOne, left:(Int, Int)) = if (counts(3) == counts(1)) (counts(3), (0, 0)) else {\n val min = counts(3).min(counts(1))\n (min, (Map(3 -> counts(3), 1 -> counts(1)).maxBy(_._2)._1, Math.abs(counts(3) - counts(1))))\n }\n// println(left)\n\n // комбинируем 2 с 1\n val (fTwoOne:Int, left1:(Int, Int)) = if (twoLeft != 0) left match {\n\n case (0, 0) => (0, left)\n case (num: Int, count: Int) if num == 3 => (1, left)\n case (num: Int, count: Int) if num == 1 => if (count >= 2) (1, (num, count - 2)) else (1,(0, 0))\n\n } else (0, left)\n\n\n\n val fLeft = if (left1._1 == 3) left1._2 else {\n if (left1._2 < 4 && left1._2 != 0) {\n 1\n } else if (left1._2 == 0) {\n 0\n } else {\n val modQ = if (left1._2 % 4 == 0) 0 else 1\n left1._2 / 4 + modQ\n }\n }\n println(fTwo + fFour + fLeft + fThreeOne + fTwoOne)\n\n\n\n\n\n\n\n}\n"}, {"source_code": "/**\n * Created by vol on 9/16/14.\n */\nobject B158 extends App{\n val n = readInt()\n val friends = readLine().split(\" \").map(_.toInt)\n val counts = friends.foldLeft(Map(1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0)) {\n (count, fr) => count + (fr -> (count.getOrElse(fr, 0) + 1))\n }\n\n val cTwo = counts(2) / 2\n\n val mTwo = counts(2) * 2 % 4 / 2\n\n val cFour = counts(4)\n\n if(!counts.contains(2)) {\n\n }\n\n// println(\"twos -> \" + counts(2))\n//\n// println(\"mod from twos -> \" + counts(2) * 2 % 4)\n//\n// println(\"fours -> \" + counts(4))\n//\n// println(\"threes -> \" + counts(3))\n//\n// println(\"ones -> \" + counts(1))\n\n\n val combinedCount = if (counts(3) == counts(1)) counts(3) else counts(3).min(counts(1))\n\n val bigger = if (counts(3) > counts(1)) \"three\" else if (counts(3) == counts(1)) \"equal\" else \"one\"\n\n\n\n if (bigger == \"one\") {\n val cOne = Math.abs(counts(3) - counts(1))\n if (mTwo == 0) println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4)\n else\n if (cOne > 2)\n println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4 + 1)\n else\n println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4)\n\n } else if (bigger == \"equal\"){\n println(cTwo + cFour + mTwo + combinedCount)\n }\n else {\n val cThree = Math.abs(counts(3) - counts(1))\n// println(cTwo)\n// println(cFour)\n// println(mTwo)\n// println(cThree)\n// println(combinedCount)\n println(cTwo + cFour + mTwo + cThree + combinedCount)\n }\n\n\n\n\n}\n"}, {"source_code": "/**\n * Created by vol on 9/16/14.\n */\nobject B158 extends App{\n val n = readInt()\n val friends = readLine().split(\" \").map(_.toInt)\n val counts = friends.foldLeft(Map(1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0)) {\n (count, fr) => count + (fr -> (count.getOrElse(fr, 0) + 1))\n }\n\n val fTwo = counts(2) / 2\n\n val twoLeft = counts(2) * 2 % 4\n\n //четверки собранны\n val fFour = counts(4)\n\n //число скомбенированные 3 и 1\n val (fThreeOne, left:(Int, Int)) = if (counts(3) == counts(1)) (counts(3), (0, 0)) else {\n val min = counts(3).min(counts(1))\n (min, (Map(3 -> counts(3), 1 -> counts(1)).maxBy(_._2)._1, Math.abs(counts(3) - counts(1))))\n }\n println(left)\n\n // комбинируем 2 с 1\n val (fTwoOne:Int, left1:(Int, Int)) = if (twoLeft != 0) left match {\n\n case (0, 0) => (0, left)\n case (num: Int, count: Int) if num == 3 => (1, left)\n case (num: Int, count: Int) if num == 1 => if (count >= 2) (1, (num, count - 2)) else (1,(0, 0))\n\n } else (0, left)\n\n\n\n val fLeft = if (left1._1 == 3) left1._2 else {\n if (left1._2 < 4 && left1._2 != 0) {\n 1\n } else if (left1._2 == 0) {\n 0\n } else {\n val modQ = if (left1._2 % 4 == 0) 0 else 1\n left1._2 / 4 + modQ\n }\n }\n println(fTwo + fFour + fLeft + fThreeOne + fTwoOne)\n\n\n\n\n\n\n\n}\n"}, {"source_code": "/**\n * Created by vol on 9/16/14.\n */\nobject B158 extends App{\n val n = readInt()\n val friends = readLine().split(\" \").map(_.toInt)\n val counts = friends.foldLeft(Map(1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0)) {\n (count, fr) => count + (fr -> (count.getOrElse(fr, 0) + 1))\n }\n\n val cTwo = counts(2) / 2\n\n val mTwo = counts(2) * 2 % 4\n\n val cFour = counts(4)\n\n if(!counts.contains(2)) {\n\n }\n\n// println(\"twos -> \" + counts(2))\n//\n// println(\"mod from twos -> \" + counts(2) * 2 % 4)\n//\n// println(\"fours -> \" + counts(4))\n//\n// println(\"threes -> \" + counts(3))\n//\n// println(\"ones -> \" + counts(1))\n\n\n val combinedCount = counts(3).min(counts(1))\n\n val bigger = if (counts(3) > counts(1)) \"three\" else \"one\"\n\n if (bigger == \"one\") {\n val cOne = Math.abs(counts(3) - counts(1))\n if (mTwo == 0) println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4)\n else\n if (cOne > 2)\n println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4 + 1)\n else\n println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4)\n\n } else {\n val cThree = Math.abs(counts(3) - counts(1))\n// println(cTwo)\n// println(cFour)\n// println(mTwo)\n// println(cThree)\n// println(combinedCount)\n println(cTwo + cFour + 1 + cThree + combinedCount)\n }\n\n\n\n\n}\n"}, {"source_code": "/**\n * Created by vol on 9/16/14.\n */\nobject B158 extends App{\n val n = readInt()\n val friends = readLine().split(\" \").map(_.toInt)\n val counts = friends.foldLeft(Map(1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0)) {\n (count, fr) => count + (fr -> (count.getOrElse(fr, 0) + 1))\n }\n\n val cTwo = counts(2) / 2\n\n val mTwo = counts(2) * 2 % 4 / 2\n\n val cFour = counts(4)\n\n if(!counts.contains(2)) {\n\n }\n\n// println(\"twos -> \" + counts(2))\n//\n// println(\"mod from twos -> \" + counts(2) * 2 % 4)\n//\n// println(\"fours -> \" + counts(4))\n//\n// println(\"threes -> \" + counts(3))\n//\n// println(\"ones -> \" + counts(1))\n\n\n val combinedCount = if (counts(3) == counts(1)) counts(3) else counts(3).min(counts(1))\n\n val bigger = if (counts(3) > counts(1)) \"three\" else if (counts(3) == counts(1)) \"equal\" else \"one\"\n\n if (bigger == \"one\") {\n val cOne = Math.abs(counts(3) - counts(1))\n if (mTwo == 0) {\n if (cOne/ 4 == 0 && cOne > 0 && cOne < 4) println(cTwo + cFour + combinedCount + 1)\n else println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4)\n }\n else\n if (cOne > 2) {\n println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4 + 1) }\n else\n if (cOne + mTwo < 4) println(cTwo + cFour + combinedCount + 1)\n else println(cTwo + cFour + combinedCount + cOne / 4 + cOne % 4)\n\n } else if (bigger == \"equal\"){\n println(cTwo + cFour + mTwo + combinedCount)\n }\n else {\n val cThree = Math.abs(counts(3) - counts(1))\n// println(cTwo)\n// println(cFour)\n// println(mTwo)\n// println(cThree)\n// println(combinedCount)\n println(cTwo + cFour + mTwo + cThree + combinedCount)\n }\n\n\n\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val arr = readLine().split(\" \").map(_.toInt)\n var g1, g2, g3, g4 = 0\n arr.foreach{\n case 1 => g1 += 1\n case 2 => g2 += 1\n case 3 => g3 += 1\n case 4 => g4 += 1\n }\n var ga = g4 + g3 + ((g2 + 1) / 2) + ((g4 - g3 - g2 % 2 + 3) / 4)\n println(ga)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val arr = readLine().split(\" \").map(_.toInt)\n var g1, g2, g3, g4 = 0\n arr.foreach{\n case 1 => g1 += 1\n case 2 => g2 += 1\n case 3 => g3 += 1\n case 4 => g4 += 1\n }\n var ga = g4 + g3 + ((g2 + 1) / 2) + (((g1 - g3 - g2 % 2).max(0) + 3) / 4)\n println(ga)\n }\n}"}, {"source_code": "object P279D {\n \n def Read : Array[Int] = readLine().split(\" \").map(_.toInt);\n \n def main ( args : Array[String] ) {\n Read\n println ((Read.sum - 1) / 4 + 1)\n /*println (Read.foldRight(0)(_ + _))*/\n }\n}\n"}, {"source_code": "object P279D {\n \n def main ( args : Array[String] ) {\n readLine().split(\" \").map(_.toInt);\n val A : Array[Int] = readLine().split(\" \").map(_.toInt);\n val C4 = A.count(_ == 4)\n val C3 = A.count(_ == 3)\n var C2 = A.count(_ == 2)\n var C1 = A.count(_ == 1)\n \n C1 -= (C2 % 2) * 2\n if(C1 < 0) C1 = 0 \n \n C1 -= C3\n if(C1 < 0) C1 = 0\n if(C2 == 0) C2 = -1\n println (C4 + (C2 - 1) / 2 + 1 + C1 / 4 + C3)\n \n }\n}\n"}, {"source_code": "object P279D {\n \n def Read : Array[Int] = readLine().split(\" \").map(_.toInt);\n \n def main ( args : Array[String] ) {\n Read\n println ((Read.sum - 1) / 4)\n /*println (Read.foldRight(0)(_ + _))*/\n }\n}\n"}, {"source_code": "object P279D {\n \n def main ( args : Array[String] ) {\n readLine().split(\" \").map(_.toInt);\n val A : Array[Int] = readLine().split(\" \").map(_.toInt);\n val C4 = A.count(_ == 4)\n val C3 = A.count(_ == 3)\n val C2 = A.count(_ == 2)\n var C1 = A.count(_ == 1)\n \n C1 -= (C2 % 2) * 2\n if(C1 < 0) C1 = 0 \n \n C1 -= C3\n if(C1 < 0) C1 = 0\n\n println (C4 + (C2 - 1) / 2 + 1 + C1 / 4 + C3)\n \n }\n}\n"}, {"source_code": "object P279D {\n \n def main ( args : Array[String] ) {\n readLine().split(\" \").map(_.toInt);\n val A : Array[Int] = readLine().split(\" \").map(_.toInt);\n val C4 = A.count(_ == 4)\n val C3 = A.count(_ == 3)\n val C2 = A.count(_ == 2)\n var C1 = A.count(_ == 1)\n \n C1 -= (C2 % 2) * 2\n if(C1 < 0) C1 = 0 \n \n C1 -= C3\n if(C1 < 0) C1 = 0\n\n println (C4 + C2 / 2 + C1 / 4 + C3)\n \n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A_158 extends App {\n\n def sgn(i: Int) = if (i > 0) 1 else 0\n\n val n = readInt()\n val S = readLine().split(\" \").map(_.toInt).groupBy(identity).mapValues(_.length).withDefaultValue(0)\n\n val a = Math.max(0, S(1) - S(3))\n val answer = S(4) + S(3) + a / 4 + S(2) / 2 + sgn(S(2) % 2 + a % 4)\n\n println(answer)\n}\n"}, {"source_code": "object JuanDavidRobles158B {\n def main(args: Array[String]): Unit = {\n\n import scala.io.StdIn\n\n val nGroups: Int = StdIn.readInt()\n val stringGroups: String = StdIn.readLine()\n\n /*var ones: Int = repetitions(stringGroups, \"1\")\n stringGroups = stringGroups.replace(\"1\", \"\")\n var twos: Int = repetitions(stringGroups, \"2\")\n stringGroups = stringGroups.replace(\"2\", \"\")\n var threes: Int = repetitions(stringGroups, \"3\")\n stringGroups = stringGroups.replace(\"3\", \"\")\n var fours: Int = repetitions(stringGroups, \"4\")*/\n\n var counts: Array[Int] = repetitions(stringGroups)\n\n var count: Int = 0\n\n var ones: Int = counts(0)\n var twos: Int = counts(1)\n var threes: Int = counts(2)\n var fours: Int = counts(3)\n\n /*if (threes >= ones){\n println((fours + threes + Math.ceil(twos.asInstanceOf[Float]/2))\n .asInstanceOf[Int])\n } else {\n println((fours + threes + Math.ceil(twos.asInstanceOf[Float]/2) + Math\n .ceil((ones-threes).asInstanceOf[Float]/4)).asInstanceOf[Int])\n }*/\n\n count = fours\n count = count + threes\n if (threes > ones){\n ones = 0\n } else {\n ones = ones - threes\n }\n count = count + twos/2\n if (twos%2 == 0){\n } else {\n ones = ones + twos%2\n }\n count = count + Math.ceil(ones.asInstanceOf[Double]/4).asInstanceOf[Int]\n println(count)\n }\n\n def repetitions(string: String): Array[Int] ={\n val myString: String = string\n var count: Array[Int] = new Array[Int](4)\n\n for (i <- 0 until myString.length){\n myString.charAt(i) match {\n case '1' => count(0) = count(0) + 1\n case '2' => count(1) = count(1) + 1\n case '3' => count(2) = count(2) + 1\n case '4' => count(3) = count(3) + 1\n case _ =>\n }\n }\n\n count\n }\n}"}, {"source_code": "object JuanDavidRobles158B {\n def main(args: Array[String]): Unit = {\n\n import scala.io.StdIn\n\n val nGroups: Int = StdIn.readInt()\n var stringGroups: String = StdIn.readLine()\n\n var ones: Int = repetitions(stringGroups, \"1\")\n var twos: Int = repetitions(stringGroups, \"2\")\n var threes: Int = repetitions(stringGroups, \"3\")\n var fours: Int = repetitions(stringGroups, \"4\")\n\n if (threes >= ones){\n println((fours + threes + Math.ceil(twos.asInstanceOf[Float]/2))\n .asInstanceOf[Int])\n } else {\n println((fours + threes + Math.ceil(twos.asInstanceOf[Float]/2) + Math\n .ceil((ones-threes).asInstanceOf[Float]/4)).asInstanceOf[Int])\n }\n\n }\n\n def repetitions(string: String, indexOf: String): Int ={\n var myString: String = string\n var str1: String = \"\"\n var str2: String = \"\"\n var index: Int = 0\n var count: Int = 0\n\n while (myString contains indexOf){\n index = myString.indexOf(indexOf)\n if (index > 0){\n str1 = myString.substring(0, index)\n } else {\n str1 = \"\"\n }\n if (index < myString.size-1) {\n str2 = myString.substring(index + 1)\n } else {\n str2 = \"\"\n }\n myString = str1 + str2\n count = count + 1\n }\n\n return count\n }\n}\n"}, {"source_code": "object main extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n def solve(input: InputStream, output: PrintStream): Unit = {\n val sc = new Scanner(input)\n val n = sc.nextInt()\n val groups = (1 to n).map( _ => sc.nextInt())\n val counters =((1 to 4) map ( c => groups.count( _ == c))).toArray\n\n\n var c1 = counters(0)\n var c2 = counters(1)\n var c3 = counters(2)\n var c4 = counters(3)\n\n var result = c4\n if( c3 > c1){\n result += c1\n c3 -= c1\n c1 -= 0\n }else{\n result += c3\n c1 -= c3\n c3 = 0\n }\n\n result += c2 / 2\n c2 %= 2\n\n if( c2 > (c1 +1)/2){\n //hay más grupos de 2 que pares de 1\n result += c2\n c1 = 0\n c2 = 0\n }else{\n result += c2\n c1 -= c2*2\n c2 = 0\n }\n\n result += (c1+3)/4\n result += c2 + c3\n output.println(result)\n }\n solve(System.in,System.out)\n}"}, {"source_code": "object Main {\n\n def main(args: Array[String]): Unit = {\n val _ = readLine\n var res = 0;\n var count = new Array[Int](5)\n for(x <- readLine().split(\" \").map(_.toInt))count(x) += 1\n count(1) = Math.max(0,count(1)-count(3))\n res = count(4)+count(3)+(count(2)*2+4*count(1)+3)/4\n print(res)\n }\n\n}"}, {"source_code": "import java.util.Scanner\n\nobject Taxi extends App {\n def parseInts(str: String, numIterations: Integer) = {\n val scanner = new Scanner(str)\n val res = (0 until numIterations) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n val Seq(numFamilies) = parseInts(Console.readLine(), 1)\n val families = parseInts(Console.readLine(), numFamilies)\n val groupings = Array.fill[Int](5)(0)\n\n families.foreach(fam => groupings(fam) = groupings(fam) + 1)\n\n var total = 0\n\n families.foreach(fam => {\n val remainder = 4 - fam\n var upperBound = math.max(remainder, fam)\n var lowerBound = math.min(remainder, fam)\n\n if (groupings(fam) > 0) {\n groupings(fam) -= 1\n total += 1\n var famAdded = fam\n while (famAdded < 4 && lowerBound <= upperBound) {\n if (groupings(upperBound) > 0) {\n groupings(upperBound) -= 1\n famAdded += upperBound\n } else {\n upperBound -= 1\n }\n }\n }\n })\n\n println(total)\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Taxi extends App {\n def parseInts(str: String, numIterations: Integer) = {\n val scanner = new Scanner(str)\n val res = (0 until numIterations) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n val Seq(numFamilies) = parseInts(Console.readLine(), 1)\n val families = parseInts(Console.readLine(), numFamilies)\n val groupings = Array.fill[Int](5)(0)\n\n families.foreach(fam => groupings(fam) = groupings(fam) + 1)\n\n var total = 0\n\n families.foreach(fam => {\n val remainder = 4 - fam\n var upperBound = remainder\n var lowerBound = 1\n\n if (groupings(fam) > 0) {\n groupings(fam) -= 1\n total += 1\n var famAdded = fam\n while (famAdded < 4 && lowerBound <= upperBound) {\n if (groupings(upperBound) > 0) {\n groupings(upperBound) -= 1\n famAdded += upperBound\n } else {\n upperBound -= 1\n }\n }\n }\n })\n\n println(total)\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Taxi extends App {\n def parseInts(str: String, numIterations: Integer) = {\n val scanner = new Scanner(str)\n val res = (0 until numIterations) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n val Seq(numFamilies) = parseInts(Console.readLine(), 1)\n val families = parseInts(Console.readLine(), numFamilies)\n val groupings = Array.fill[Int](5)(0)\n\n families.foreach(fam => groupings(fam) = groupings(fam) + 1)\n\n var total = 0\n\n families.foreach(fam => {\n val remainder = 4 - fam\n if (groupings(fam) > 0 && groupings(remainder) > 0) {\n groupings(fam) -= 1\n groupings(remainder) -= 1\n total += 1\n } else if (groupings(fam) > 0) {\n groupings(fam) -= 1\n total += 1\n }\n })\n\n println(total)\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Taxi extends App {\n def parseInts(str: String, numIterations: Integer) = {\n val scanner = new Scanner(str)\n val res = (0 until numIterations) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n val MAX_FAMILY_SIZE = 4\n val MIN_FAMILY_SIZE = 1\n\n val Seq(numFamilies) = parseInts(Console.readLine(), 1)\n val families = parseInts(Console.readLine(), numFamilies)\n val familiesBySize = Array.fill[Int](5)(0)\n\n families.foreach(fam => familiesBySize(fam) = familiesBySize(fam) + 1)\n\n var total = 0\n\n def placeInTaxi(famBySize: Array[Int], famSize: Int): Unit = {\n if (familiesBySize(famSize) > 0) {\n familiesBySize(famSize) -= 1\n total += 1\n var numInTaxi = famSize\n for {\n maybePlaceInTaxi <- (MAX_FAMILY_SIZE - famSize) to MIN_FAMILY_SIZE by -1\n if (numInTaxi < MAX_FAMILY_SIZE && familiesBySize(maybePlaceInTaxi) > 0)\n } yield {\n familiesBySize(maybePlaceInTaxi) -= 1\n numInTaxi += maybePlaceInTaxi\n }\n }\n }\n\n families.foreach(fam => placeInTaxi(familiesBySize, fam))\n\n println(total)\n}\n"}, {"source_code": "import scala.io.StdIn._\nimport scala.util.Sorting\nimport java.lang.Math._\n\nobject Taxi_158B extends App {\n val n = readInt\n val chs = readLine.split(\" \").map(_.toInt)\n \n val gchs = Map(1->0, 2->0, 3->0, 4->0) ++ chs.groupBy((a: Int) => a).map(a => (a._1 -> a._2.length))\n \n val gchs1 = Map(\n 4 -> gchs(4), \n 3 -> gchs(3), \n 2 -> gchs(2), \n 1 -> (gchs(1) - min(gchs(1), gchs(3)))\n )\n \n val gchs2 = Map(\n 4 -> gchs1(4), \n 3 -> gchs1(3), \n 2 -> (gchs1(2) + (if (gchs1(1) > 1 && gchs1(2) % 2 != 0) 1 else 0)), \n 1 -> (if (gchs1(1) > 1 && gchs1(2) > 0) gchs1(1) - 2 else gchs1(1))\n )\n \n \n //println(gchs, gchs1, gchs2)\n val ans = \n gchs2(4) + \n gchs2(3) +\n gchs2(2) / 2 + (if (gchs2(2) % 2 != 0) 1 else 0) +\n gchs2(1) / 4 + (if (gchs2(1) % 4 != 0) 1 else 0)\n \n println(ans)\n}"}, {"source_code": "import scala.io.StdIn._\nimport scala.util.Sorting\nimport java.lang.Math._\n\nobject Taxi_158B extends App {\n val n = readInt\n val chs = readLine.split(\" \").map(_.toInt)\n \n val gchs = Map(1->0, 2->0, 3->0, 4->0) ++ chs.groupBy((a: Int) => a).map(a => (a._1 -> a._2.length))\n \n val gchs1 = Map(\n 4 -> gchs(4), \n 3 -> gchs(3), \n 2 -> gchs(2), \n 1 -> (gchs(1) - min(gchs(1), gchs(3)))\n )\n \n val gchs2 = Map(\n 4 -> gchs1(4), \n 3 -> gchs1(3), \n 2 -> (gchs1(2) + (if (gchs1(1) > 1 && gchs1(2) % 2 != 0) 1 else 0)), \n 1 -> (if (gchs1(1) > 1 && gchs1(2) > 0) gchs1(1) - 2 else gchs1(1))\n )\n \n \n println(gchs, gchs1, gchs2)\n val ans = \n gchs2(4) + \n gchs2(3) +\n gchs2(2) / 2 + (if (gchs2(2) % 2 != 0) 1 else 0) +\n gchs2(1) / 4 + (if (gchs2(1) % 4 != 0) 1 else 0)\n \n println(ans)\n}"}, {"source_code": "import scala.io.StdIn._\nimport scala.util.Sorting\nimport java.lang.Math._\n\nobject Taxi_158B extends App {\n val n = readInt\n val chs = readLine.split(\" \").map(_.toInt)\n \n val gchs = Map(1->0, 2->0, 3->0, 4->0) ++ chs.groupBy((a: Int) => a).map(a => (a._1 -> a._2.length))\n \n val gchs1 = Map(\n 4 -> gchs(4), \n 3 -> gchs(3), \n 2 -> gchs(2), \n 1 -> (gchs(1) - min(gchs(1), gchs(3)))\n )\n \n val gchs2 = Map(\n 4 -> gchs1(4), \n 3 -> gchs1(3), \n 2 -> (gchs1(2) + (if (gchs1(1) > 1 && gchs1(2) % 2 != 0) 1 else 0)), \n 1 -> (if (gchs1(1) > 0 && gchs1(2) > 0) gchs1(1) - min(gchs1(1), 2) else gchs1(1))\n )\n \n \n //println(gchs, gchs1, gchs2)\n val ans = \n gchs2(4) + \n gchs2(3) +\n gchs2(2) / 2 + (if (gchs2(2) % 2 != 0) 1 else 0) +\n gchs2(1) / 4 + (if (gchs2(1) % 4 != 0) 1 else 0)\n \n println(ans)\n}"}, {"source_code": "import scala.io.StdIn._\nimport scala.util.Sorting\nimport java.lang.Math._\n\nobject Taxi_158B extends App {\n val n = readInt\n val chs = readLine.split(\" \").map(_.toInt)\n \n val gchs = Map(1->0, 2->0, 3->0, 4->0) ++ chs.groupBy((a: Int) => a).map(a => (a._1 -> a._2.length))\n \n val gchs1 = Map(\n 4 -> gchs(4), \n 3 -> gchs(3), \n 2 -> gchs(2), \n 1 -> (gchs(1) - min(gchs(1), gchs(3)))\n )\n \n val gchs2 = Map(\n 4 -> gchs1(4), \n 3 -> gchs1(3), \n 2 -> (gchs1(2) + (if (gchs1(1) > 1 && gchs1(2) % 2 != 0) 1 else 0)), \n 1 -> (if (gchs1(1) > 1) gchs1(1) - 2 else gchs1(1))\n )\n \n \n //println(gchs, gchs1, gchs2)\n val ans = \n gchs2(4) + \n gchs2(3) +\n gchs2(2) / 2 + (if (gchs2(2) % 2 != 0) 1 else 0)\n gchs2(1) + (if (gchs2(1) % 4 != 0) 1 else 0)\n \n println(ans)\n}"}, {"source_code": "object B00158 extends App {\n\n def oneIntLine = {\n val Seq(count) = parseInt(Console.readLine(), 1);\n count\n }\n \n def parseInt(str: String, count: Int): Seq[Int] = {\n val scanner = new java.util.Scanner(str)\n val res = (1 to count) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n def scanInts(count: Int): Seq[Int] = parseInt(Console.readLine, count)\n \n def frequency[T](seq: Seq[T]) = seq.groupBy(identity).mapValues(_.size).withDefaultValue(0)\n \n def partsNeededToCoverFull(fullLength: Int, partLength: Int) =\n Math.ceil(fullLength * 1.0 / partLength).toInt\n \n val count = oneIntLine\n val grouped = frequency(scanInts(count))\n val partialCount = grouped(4) + grouped(3) + partsNeededToCoverFull(grouped(2), 2)\n val vacantSeats = grouped(2) + (if (grouped(2) % 2 == 1) 2 else 0)\n val remainingSingles = if (grouped(1) > vacantSeats) grouped(1) - vacantSeats else 0\n val res = partialCount + partsNeededToCoverFull(remainingSingles, 4)\n println(res)\n}\n"}, {"source_code": "object B00158 extends App {\n\n def oneIntLine = {\n val Seq(count) = parseInt(Console.readLine(), 1);\n count\n }\n \n def parseInt(str: String, count: Int): Seq[Int] = {\n val scanner = new java.util.Scanner(str)\n val res = (1 to count) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n def scanInts(count: Int): Seq[Int] = parseInt(Console.readLine, count)\n \n def frequency[T](seq: Seq[T]) = seq.groupBy(identity).mapValues(_.size).withDefaultValue(0)\n\n val count = oneIntLine\n val grouped = frequency(scanInts(count))\n var oneCount = grouped(1)\n val partialCount = grouped(4) + grouped(3) + (Math.ceil(grouped(2) * 1.0 / 2)).toInt\n oneCount = oneCount - (if (oneCount > grouped(3)) oneCount - grouped(3) else 0)\n oneCount = oneCount - (if (grouped(2) % 2 == 1) 2 else 0)\n oneCount = if (oneCount < 0) 0 else oneCount\n val adjustment = (Math.ceil(oneCount / 4)).toInt\n println(partialCount + adjustment)\n}\n"}], "src_uid": "371100da1b044ad500ac4e1c09fa8dcb"} {"source_code": "import scala.io.Source\r\n\r\nobject BPatchoulisMagicalTalisman {\r\n def main(args: Array[String]): Unit = {\r\n val file = Source.stdin.getLines\r\n// val file = Source.fromString(\r\n// \"4\\n2\\n1 9\\n3\\n1 1 2\\n3\\n2 4 8\\n3\\n1049600 33792 1280\"\r\n// ).getLines\r\n var t = file.next.toInt\r\n while (t > 0) {\r\n t-=1\r\n file.next\r\n val l = file.next.split(\" \").map(_.toInt)\r\n val oddSize = l.count(_ % 2 == 1)\r\n val res = if (oddSize > 0) l.length - oddSize\r\n else {\r\n val unitIndex = l.map(_.toBinaryString.reverse).max.indexOf(\"1\")\r\n unitIndex + l.length - 1\r\n }\r\n println(res)\r\n }\r\n }\r\n}", "positive_code": [{"source_code": "import scala.io.StdIn\r\nimport scala.math.BigDecimal.double2bigDecimal\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n val t = StdIn.readInt()\r\n\r\n for(_ <- 0 until t) {\r\n val n = StdIn.readLong()\r\n\r\n val numbers = StdIn.readLine().split(\" \").map(_.toLong)\r\n\r\n val evenNumbers = numbers.count(x => x % 2 == 0)\r\n val oddNumbers = numbers.length - evenNumbers\r\n\r\n if(evenNumbers == 0) {\r\n println(0)\r\n } else if(oddNumbers == 0) {\r\n val (count, index) = numbers.filter(x => x % 2 == 0).zipWithIndex.map { case(n, index) => (howManyTwos(n), index) }.minBy(_._1)\r\n\r\n println(count + evenNumbers - 1)\r\n } else {\r\n println(evenNumbers)\r\n }\r\n }\r\n }\r\n\r\n def howManyTwos(number: Long): Long = {\r\n var count = 0\r\n var numberMut = number\r\n while(numberMut % 2 == 0) {\r\n numberMut /= 2\r\n count += 1\r\n }\r\n count\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\r\nimport scala.math.BigDecimal.double2bigDecimal\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n val t = StdIn.readInt()\r\n\r\n for(_ <- 0 until t) {\r\n val n = StdIn.readLong()\r\n\r\n val numbers = StdIn.readLine().split(\" \").map(_.toLong)\r\n\r\n val evenNumbers = numbers.count(x => x % 2 == 0)\r\n val oddNumbers = numbers.length - evenNumbers\r\n\r\n if(evenNumbers == 0) {\r\n println(0)\r\n } else {\r\n val (count, index) = numbers.filter(x => x % 2 == 0).zipWithIndex.map { case(n, index) => (howManyTwos(n), index) }.minBy(_._1)\r\n\r\n println(count + evenNumbers - 1)\r\n }\r\n }\r\n }\r\n\r\n def howManyTwos(number: Long): Long = {\r\n var count = 0\r\n var numberMut = number\r\n while(numberMut % 2 == 0) {\r\n numberMut /= 2\r\n count += 1\r\n }\r\n count\r\n }\r\n}"}], "src_uid": "1b9a204dd08d61766391a3b4d2429df2"} {"source_code": "object Main extends App {\nimport java.util._\nimport java.io._\n//remove if not needed\nimport scala.collection.JavaConversions._\n\n\n\n \n input.init(System.in)\n val out = new PrintWriter(System.out)\n val n = input.nextInt()\n val k = input.nextInt()\n val ss = Array.ofDim[Int](n)\n val ms = Array.ofDim[Int](n)\n for (i <- 0 until n) {\n ss(i) = input.nextInt()\n ms(i) = input.nextInt()\n }\n val pq = new PriorityQueue[Long]()\n for (i <- 0 until n) {\n val start = Math.max(ss(i), if (pq.size < k) 0 else pq.poll())\n val end = start + ms(i)\n out.println(end)\n pq.add(end)\n }\n out.close()\n \n\n object input {\n\n var reader: BufferedReader = _\n\n var tokenizer: StringTokenizer = _\n\n def init(input: InputStream) {\n reader = new BufferedReader(new InputStreamReader(input))\n tokenizer = new StringTokenizer(\"\")\n }\n\n def next(): String = {\n while (!tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine())\n }\n tokenizer.nextToken()\n }\n\n def nextInt(): Int = java.lang.Integer.parseInt(next())\n\n def nextDouble(): Double = java.lang.Double.parseDouble(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n }\n\n\n}", "positive_code": [{"source_code": "\nimport scala.Array._\nimport scala.collection.mutable.PriorityQueue\nimport scala.math._\n\nobject C523 extends App{\n\n val res = readLine.split(\" \").map(_.toInt)\n private final var n = res(0)\n val k = res(1)\n val q = new PriorityQueue[Long]\n var strResult : StringBuilder = new StringBuilder\n\n (1 to k).foreach(x => q += 0)\n while(n > 0)\n {\n val str = readLine.split(\" \").map(_.toLong)\n var x = str(0)\n val y = str(1)\n x = max(x, - q.dequeue) + y\n strResult.append(x)\n strResult.append('\\n')\n q += -x\n n -= 1\n }\n println(strResult.toString)\n}"}], "negative_code": [{"source_code": "object Main extends App {\nimport java.io._\nimport java.util._\n//remove if not needed\nimport scala.collection.JavaConversions._\n\n val sc = new Scanner(System.in)\n val pw = new PrintWriter(System.out)\n val n:Int = sc.nextInt()\n val k:Long = sc.nextInt().toLong\n val q = new PriorityQueue[Long]()\n for (i <- 0 until n) {\n var s = sc.nextInt().toLong\n val d = sc.nextInt().toLong\n if (q.size >= k) {\n s = Math.max(s, q.poll().toInt)\n }\n val t = s + d\n q.offer(t)\n pw.println(t)\n }\n pw.flush()\n \n\n}"}, {"source_code": "object Main extends App {\nimport java.io._\nimport java.util._\n//remove if not needed\nimport scala.collection.JavaConversions._\n\n val sc = new Scanner(System.in)\n val pw = new PrintWriter(System.out)\n val n = sc.nextInt()\n val k = sc.nextInt()\n val q = new PriorityQueue[Long]()\n for (i <- 0 until n) {\n var s = sc.nextInt()\n val d = sc.nextInt()\n if (q.size >= k) {\n s = Math.max(s, q.poll().toInt)\n }\n val t = s + d\n q.offer(t)\n pw.println(t)\n }\n pw.flush()\n \n\n}"}, {"source_code": "object Main extends App {\n import scala.collection.mutable.ListBuffer\n val Array(n, k) = readLine.split(\" \").map(_.toLong)\n var servers1:List[Server] = List.empty[Server]\n (1L to k).foreach(n => servers1 = servers1 :+ Server(0L))\n def free_server1(load: Long, now: Long): Server = {\n servers1.find(serv => serv.peak_load < now ) match {\n case Some(serv) => serv.setLoad(load);serv\n case _ => val z = servers1.sortBy(s => s.peak_load).head;z.setLoad(load);z\n }\n }\n def serverAreFree(i: Long):Boolean = {\n servers1.filter(serv => serv.peak_load < i).length > 0\n }\n var videos1:Array[Array[Long]] = Array()\n (1L to n).map(nn => videos1 = videos1 :+ readLine.split(\" \").map(_.toLong))\n\n var server_buffer1:Array[Long] = Array()\n\n def makeOut() = {\n videos1.foreach { video =>\n if (serverAreFree(video(0))){\n free_server1(video(1) + video(0), video(0))\n server_buffer1 = server_buffer1 :+ (video(1) + video(0))\n } \n if (!serverAreFree(video(0))){\n val vvv = servers1.sortBy(s => s.peak_load).head.peak_load + video(1)\n free_server1(vvv, video(0))\n server_buffer1 = server_buffer1 :+ vvv\n }\n\n }\n }\n makeOut()\n server_buffer1.foreach(c => println(c))\n \n case class Server(var peak_load: Long) {\n def setLoad(load: Long): Unit = {\n peak_load = load\n }\n }\n}"}], "src_uid": "754f1bbae2e6ff4992b6f56bb9c96efe"} {"source_code": "import collection.mutable\nimport io.Source\n\nobject SimpleIOU {\n val netDebts = mutable.Map[Int, Int]().withDefaultValue(0)\n\n def main(args: Array[String]) = {\n val lines = Source.stdin.getLines()\n lines.next()\n\n lines.foreach(line => { val arr = line.split(\" \").map(_.toInt); updateDebts(arr(0), arr(1), arr(2))})\n\n println(netDebts.foldLeft(0) {case (accum, (debtee, totalDebt)) => (0 max totalDebt) + accum})\n }\n\n def updateDebts(debtee: Int, debtor: Int, debt: Int) = {\n netDebts(debtee) += debt\n netDebts(debtor) -= debt\n }\n}\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val result = Array.ofDim[Int](n)\n (1 to m).foreach { _ =>\n val Array(from, to, amount) = in.next().split(' ').map(_.toInt)\n result(from - 1) += amount\n result(to - 1) -= amount\n }\n println(result.filter(_ > 0).sum)\n}\n"}], "negative_code": [{"source_code": "import collection.mutable\nimport io.Source\n\nobject SimpleIOU {\n val netDebts = mutable.Map[Int, Int]().withDefaultValue(0)\n\n def main(args: Array[String]) = {\n val lines = Source.stdin.getLines()\n lines.next()\n\n lines.foreach(line => { val arr = line.split(\" \").map(_.toInt); updateDebts(arr(0), arr(1), arr(2))})\n\n println(netDebts)\n println(netDebts.foldLeft(0) {case (accum, (debtee, totalDebt)) => (0 max totalDebt) + accum})\n }\n\n def updateDebts(debtee: Int, debtor: Int, debt: Int) = {\n netDebts(debtee) += debt\n netDebts(debtor) -= debt\n }\n}\n"}], "src_uid": "b53c3e55834db8184d8caf4630aaa573"} {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n val ans = an\n .foldLeft((0L, 0L)) {\n case ((cost, damper), a) =>\n if (a < 0) (cost + (damper + a).min(0), (damper + a).max(0))\n else (cost, damper + a)\n }\n ._2\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n val ans = an\n .foldRight((0L, 0L)) {\n case (el, (subSum, partSum)) =>\n (subSum max (partSum + el), partSum + el)\n }\n ._1\n\n println(ans)\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\nobject B extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val m = in.nextInt()\n val data = in.nextLineInt(m)\n\n var posSum = 0L\n\n data.foreach(s => {\n if(s > 0){\n posSum += s\n } else {\n if( posSum + s <= 0) posSum = 0 else posSum += s\n }\n })\n\n println(posSum)\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextLineInt(n: Int): ArrayBuffer[Int] = {\n var data = ArrayBuffer[Int]()\n n.times({\n data += nextInt()\n })\n data\n }\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}"}], "negative_code": [], "src_uid": "bd0b14e53ade1207022464ebafdf8c9a"} {"source_code": "object EDU47B extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n val ternaryString = in.next.toCharArray\n\n val ones = ternaryString.filter(_ == '1')\n val remainder = ternaryString.filter(_ != '1')\n val start = remainder.takeWhile(_ != '2')\n val end = remainder.takeRight(remainder.length - start.length)\n\n val result = start ++ ones ++ end\n\n out.println(result.mkString)\n }\n\n solve\n out.flush\n out.close\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val inputString = readLine\n\n val withoutOnes = inputString.filter(_ != '1')\n val onesLength = inputString.length - withoutOnes.length\n\n withoutOnes.indexOf('2') match {\n case -1 => {\n print(\"0\" * withoutOnes.length)\n print(\"1\" * onesLength)\n }\n case idx => {\n print(withoutOnes.slice(0, idx))\n print(\"1\" * onesLength)\n print(withoutOnes.slice(idx, withoutOnes.length))\n }\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n new Recurser(readLine).recurse()\n }\n}\n\nclass Recurser(original: String) {\n @annotation.tailrec\n final def recurse(startAt: Int = 0): Unit = {\n if(startAt == original.length) return\n\n val counts = Array(0, 0, 0)\n var nextAt = startAt\n\n while(nextAt < original.length && (counts(0) == 0 || counts(2) == 0)) {\n counts(getNum(nextAt)) += 1\n if((counts(0) == 0 || counts(2) == 0)) nextAt += 1\n }\n\n printit(counts, nextAt)\n recurse(nextAt)\n }\n\n def printit(counts: Array[Int], nextAt: Int) = {\n counts.zipWithIndex.foreach { tuple =>\n tuple match {\n case (count, index) if(nextAt == original.length || getNum(nextAt) != index) => print(index.toString * count)\n case _ =>\n }\n }\n }\n\n def getNum(at: Int): Int = original(at).toInt - 48\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val inputString = readLine\n\n val withoutOnes = inputString.filter(_ != '1')\n val onesLength = inputString.length - withoutOnes.length\n\n withoutOnes.indexOf('2') match {\n case -1 => {\n print(\"0\" * withoutOnes.length)\n print(\"1\" * onesLength)\n }\n case idx => {\n print(withoutOnes.slice(0, idx))\n print(\"1\" * onesLength)\n print(withoutOnes.slice(idx + 1, withoutOnes.length))\n }\n }\n }\n}\n"}, {"source_code": "object EDU47B extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n val ternaryString = nextString.toCharArray.map(_.asDigit)\n //val ternaryString = Array.fill(100000){scala.util.Random.nextInt(3)}\n\n def sort(string: Array[Int], alreadySorted: Array[Int]): Array[Int] = {\n if (string.isEmpty) return alreadySorted\n if (string.length == 1) return alreadySorted ++ string\n\n var n = 1\n var min, max = string.head\n var done = false\n while (!done) {\n // Read next character\n max = Math.max(max, string(n))\n min = Math.min(min, string(n))\n\n if (max - min > 1) done = true\n else if (n+1 == string.length) {\n done = true\n n += 1\n }\n else n += 1\n }\n\n sort(string.drop(n), alreadySorted ++ string.take(n).sorted)\n }\n\n out.println(ternaryString.mkString)\n out.println(sort(ternaryString, Array.emptyIntArray).mkString)\n }\n\n solve\n out.flush\n out.close\n\n /*try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }*/\n}"}], "src_uid": "91cefa6793e77b3e4f4896616a164ff2"} {"source_code": "import scala.io.StdIn.readLine\nimport scala.collection.mutable.ListBuffer\n\n/* http://codeforces.com/contest/743/problem/E */\nobject Cards extends App {\n\n def toBits(n: Int) =\n (0 to 7).map(i => ((1 << i) & n) != 0)\n\n def toFreqPattern(freq: Int, seq: Seq[Boolean]) =\n seq.map(if (_) freq + 1 else freq)\n\n def frequencyPatternsFor(n: Int) =\n (1 to 255).map(toBits).map(toFreqPattern(n, _))\n\n def isAcceptable(pattern: Seq[Int], frequency: Int): Boolean = {\n if (frequency * 8 > data.size) return false\n\n var index = 0\n var patternIndex = 0\n var counter = 0\n var result = 0\n\n while (true) {\n if (data(index) == pattern(patternIndex)) {\n counter += 1\n if (counter == frequency) {\n patternIndex += 1\n result += counter\n counter = 0\n }\n }\n index += 1\n\n if (index == data.size || patternIndex == pattern.size)\n return result == (8 * frequency)\n }\n return false\n }\n\n def getMaxFrequency(pattern: Seq[Int], initFrequency: Int): Int = {\n if (!isAcceptable(pattern, initFrequency)) {\n return 0;\n }\n var frequency = initFrequency\n while (true) {\n frequency += 1\n val canApplyPatternFreq = isAcceptable(pattern, frequency)\n if (!canApplyPatternFreq) return frequency - 1\n }\n return 0; // never reached\n }\n\n def scanData(pattern: Seq[Int], frequencyPattern: Seq[Int]): Int = {\n var index = 0\n var patternIndex = 0\n var counter = 0\n var result = 0\n\n while (true) {\n if (data(index) == pattern(patternIndex)) {\n counter += 1\n if (counter == frequencyPattern(patternIndex)) {\n patternIndex += 1\n result += counter\n counter = 0\n }\n }\n index += 1\n\n if (index == data.size || patternIndex == pattern.size)\n return result\n }\n return 0\n }\n\n def getMaxFrequencyPatterns = {\n var result: ListBuffer[Seq[Int]] = ListBuffer()\n var maxFreq = 1\n Array(1, 2, 3, 4, 5, 6, 7, 8).permutations\n .foreach { pattern =>\n val frq = getMaxFrequency(pattern, maxFreq)\n if (frq > maxFreq) {\n maxFreq = frq\n result = ListBuffer(pattern)\n } else if (frq == maxFreq) {\n result += pattern\n }\n }\n (maxFreq, result)\n }\n\n /* Solution */\n val n = readLine.toInt\n val data = readLine.split(\" \").map(_.toInt)\n\n val distinct = data.distinct.size\n\n val result = if (distinct < 8) {\n distinct\n } else {\n val (maxFrequency, acceptedPatterns) = getMaxFrequencyPatterns\n frequencyPatternsFor(maxFrequency)\n .map(fPattern => acceptedPatterns.map(pattern =>\n scanData(pattern, fPattern)))\n .flatten\n .max max (maxFrequency * 8)\n }\n\n println(result)\n}", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\nimport scala.collection.mutable.ListBuffer\n\nobject Cards extends App {\n\n val n = readLine.toInt\n val a = readLine.split(\" \").map(_.toInt)\n //test 8\n// val a = Array(3, 6, 6, 8, 8, 1, 1, 4, 4, 3, 3, 5, 5, 7, 7, 2, 2, 3)\n// val a = Array(1, 8, 1, 2, 8, 2, 3, 8, 3, 4, 8, 4, 5, 8, 5, 6, 8, 6, 7, 8, 7, 8, 8, 8)\n// val a = Array(1,2,3,4,5,6,7,8)\n// val a = Array(1, 1, 1)\n// val a = Array(6, 7, 8, 5, 2, 8, 5, 4, 6, 4, 3, 2, 5, 6, 5, 7, 5, 7, 1, 7, 4, 6, 4, 1, 4, 1, 1, 7, 6, 7, 3, 7, 4, 7, 4, 6, 4, 7, 6, 6, 6, 5, 5, 7, 3, 5, 3, 7, 2, 2, 4, 2, 5, 6, 8, 4, 1, 2, 2, 8, 3, 3, 2, 5, 6, 4, 3, 6, 2, 4, 1, 4, 2, 8, 8, 3, 7, 6, 4, 7, 2, 7, 3, 3, 8, 8, 6, 8, 7, 7, 6, 8, 3, 2, 5, 2, 6, 5, 7, 5, 7, 5, 3, 2, 6, 2, 6, 5, 7, 8, 7, 7, 2, 6, 5, 4, 2, 3, 1, 8)\n\n val ipattern = Array(1, 2, 3, 4, 5, 6, 7, 8)\n\n\n def toBits(n: Int) =\n (0 to 7).map(i => ((1 << i) & n) != 0)\n\n def toFreqs(freq: Int, seq: Seq[Boolean]) =\n seq.map(if (_) freq + 1 else freq)\n\n def freqsFor(n: Int) =\n (1 to 255).map(toBits).map(toFreqs(n, _))\n\n def canPass(initPattern: Seq[Int], freq: Int, a: Array[Int]): Boolean = {\n if (freq * 8 > a.size) return false\n\n var pos = 0\n var patternPos = 0\n var counter = 0\n var result = 0\n\n while (true) {\n if (a(pos) == initPattern(patternPos)) {\n counter += 1\n if (counter == freq) {\n patternPos += 1\n result += counter\n counter = 0\n }\n }\n pos += 1\n\n if (pos == a.size || patternPos == initPattern.size)\n return result == (8 * freq)\n }\n return false\n }\n\n def getMaxPass(initPattern: Seq[Int], initFreq: Int): Int = {\n// val distinct = a.distinct.size\n// if (distinct < 8) return 0\n\n if (!canPass(initPattern, initFreq, a)) {\n return 0;\n }\n var freq = initFreq + 1\n do {\n val cnps = canPass(initPattern, freq, a)\n // println(s\"canpass $initPattern, $freq, $cnps \")\n if (!cnps) return freq - 1\n freq += 1\n } while (true)\n\n return 0;\n }\n\n def check(initPattern: Seq[Int], freqs: Seq[Int], a: Array[Int]): Int = {\n var pos = 0\n var patternPos = 0\n var counter = 0\n var result = 0\n\n while (true) {\n if (a(pos) == initPattern(patternPos)) {\n counter += 1\n if (counter == freqs(patternPos)) {\n patternPos += 1\n result += counter\n counter = 0\n }\n }\n pos += 1\n\n if (pos == a.size || patternPos == initPattern.size)\n return result\n }\n return 0\n }\n\n val d = a.distinct.size\n if (d < 8) {\n println(d)\n } else {\n\n val (maxFreq, maxPassPatterns) = getPassPatterns\n\n// println(s\"maxFreq: $maxFreq\")\n// println(s\"maxPassPatterns size: ${maxPassPatterns.size}\")\n\n val result = freqsFor(maxFreq)\n .map(feqPattern => maxPassPatterns\n .map(iptrn => check(iptrn, feqPattern, a))).flatten.max max (maxFreq * 8)\n println(result)\n\n }\n\n def getPassPatterns = {\n var ans: ListBuffer[Array[Int]] = ListBuffer()\n var maxFreq = 1\n ipattern.permutations.foreach(perPattern => {\n val frq = getMaxPass(perPattern, maxFreq)\n if (frq > maxFreq) {\n maxFreq = frq\n ans = ListBuffer(perPattern)\n } else if (frq == maxFreq) {\n ans += perPattern\n }\n })\n (maxFreq, ans)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.collection.mutable.ListBuffer\n\nobject Cards extends App {\n\n def toBits(n: Int) =\n (0 to 7).map(i => ((1 << i) & n) != 0)\n\n def toFreqPattern(freq: Int, seq: Seq[Boolean]) =\n seq.map(if (_) freq + 1 else freq)\n\n def frequencyPatternsFor(n: Int) =\n (1 to 255).map(toBits).map(toFreqPattern(n, _))\n\n def isAcceptable(pattern: Seq[Int], frequency: Int): Boolean = {\n if (frequency * 8 > data.size) return false\n\n var pos = 0\n var patternPos = 0\n var counter = 0\n var result = 0\n\n while (true) {\n if (data(pos) == pattern(patternPos)) {\n counter += 1\n if (counter == frequency) {\n patternPos += 1\n result += counter\n counter = 0\n }\n }\n pos += 1\n\n if (pos == data.size || patternPos == pattern.size)\n return result == (8 * frequency)\n }\n return false\n }\n\n def getMaxFrequency(pattern: Seq[Int], initFrequency: Int): Int = {\n if (!isAcceptable(pattern, initFrequency)) {\n return 0;\n }\n var frequency = initFrequency\n while (true) {\n frequency += 1\n val canApplyPatternFreq = isAcceptable(pattern, frequency)\n if (!canApplyPatternFreq) return frequency - 1\n }\n return 0; // never reached\n }\n\n def scanData(pattern: Seq[Int], frequencyPattern: Seq[Int]): Int = {\n var index = 0\n var patternIndex = 0\n var counter = 0\n var result = 0\n\n while (true) {\n if (data(index) == pattern(patternIndex)) {\n counter += 1\n if (counter == frequencyPattern(patternIndex)) {\n patternIndex += 1\n result += counter\n counter = 0\n }\n }\n index += 1\n\n if (index == data.size || patternIndex == pattern.size)\n return result\n }\n return 0\n }\n\n def getMaxFrequencyPatterns = {\n var result: ListBuffer[Seq[Int]] = ListBuffer()\n var maxFreq = 1\n Array(1, 2, 3, 4, 5, 6, 7, 8).permutations\n .foreach { pattern =>\n val frq = getMaxFrequency(pattern, maxFreq)\n if (frq > maxFreq) {\n maxFreq = frq\n result = ListBuffer(pattern)\n } else if (frq == maxFreq) {\n result += pattern\n }\n }\n (maxFreq, result)\n }\n\n /* Solution */\n val n = readLine.toInt\n val data = readLine.split(\" \").map(_.toInt)\n\n val distinct = data.distinct.size\n\n val result = if (distinct < 8) {\n distinct\n } else {\n val (maxFrequency, acceptedPatterns) = getMaxFrequencyPatterns\n frequencyPatternsFor(maxFrequency)\n .map(fPattern => acceptedPatterns.map(pattern =>\n scanData(pattern, fPattern)))\n .flatten\n .max max (maxFrequency * 8)\n }\n\n println(result)\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\nimport scala.collection.mutable.ListBuffer\n\nobject Cards extends App {\n\n val n = readLine.toInt\n val a = readLine.split(\" \").map(_.toInt)\n// val a = Array(1, 8, 1, 2, 8, 2, 3, 8, 3, 4, 8, 4, 5, 8, 5, 6, 8, 6, 7, 8, 7, 8, 8, 8)\n // val a = Array(1, 1, 1)\n// val a = Array(6, 7, 8, 5, 2, 8, 5, 4, 6, 4, 3, 2, 5, 6, 5, 7, 5, 7, 1, 7, 4, 6, 4, 1, 4, 1, 1, 7, 6, 7, 3, 7, 4, 7, 4, 6, 4, 7, 6, 6, 6, 5, 5, 7, 3, 5, 3, 7, 2, 2, 4, 2, 5, 6, 8, 4, 1, 2, 2, 8, 3, 3, 2, 5, 6, 4, 3, 6, 2, 4, 1, 4, 2, 8, 8, 3, 7, 6, 4, 7, 2, 7, 3, 3, 8, 8, 6, 8, 7, 7, 6, 8, 3, 2, 5, 2, 6, 5, 7, 5, 7, 5, 3, 2, 6, 2, 6, 5, 7, 8, 7, 7, 2, 6, 5, 4, 2, 3, 1, 8)\n\n val ipattern = Array(1, 2, 3, 4, 5, 6, 7, 8)\n\n\n def toBits(n: Int) =\n (0 to 7).map(i => ((1 << i) & n) != 0)\n\n def toFreqs(freq: Int, seq: Seq[Boolean]) =\n seq.map(if (_) freq + 1 else freq)\n\n def freqsFor(n: Int) =\n (1 to 255).map(toBits).map(f => toFreqs(n, f))\n\n def canPass(initPattern: Seq[Int], freq: Int, a: Array[Int]): Boolean = {\n if (freq * 8 > a.size) return false\n\n var pos = 0\n var patternPos = 0\n var counter = 0\n var result = 0\n\n while (true) {\n if (a(pos) == initPattern(patternPos)) {\n counter += 1\n if (counter == freq) {\n patternPos += 1\n result += counter\n counter = 0\n }\n }\n pos += 1\n\n if (pos == a.size || patternPos == initPattern.size)\n return result == (8 * freq)\n }\n return false\n }\n\n def getMaxPass(initPattern: Seq[Int], initFreq: Int): Int = {\n val distinct = a.distinct.size\n if (distinct < 8) return 0\n\n if (!canPass(initPattern, initFreq, a)) {\n return 0;\n }\n var freq = initFreq + 1\n do {\n val cnps = canPass(initPattern, freq, a)\n// println(s\"canpass $initPattern, $freq, $cnps \")\n if (!cnps) return freq - 1\n freq += 1\n } while (true)\n\n return 0;\n }\n\n def check(initPattern: Seq[Int], freqs: Seq[Int], a: Array[Int]): Int = {\n var pos = 0\n var patternPos = 0\n var counter = 0\n var result = 0\n\n while (true) {\n if (a(pos) == initPattern(patternPos)) {\n counter += 1\n if (counter == freqs(patternPos)) {\n patternPos += 1\n result += counter\n counter = 0\n }\n }\n pos += 1\n\n if (pos == a.size || patternPos == initPattern.size)\n return result\n }\n return 0\n }\n\n val d = a.distinct.size\n if (d < 8) {\n println(d)\n } else {\n\n val (maxFreq, maxPassPatterns) = getPassPatterns\n\n// println(s\"maxFreq: $maxFreq\")\n// println(s\"maxPassPatterns : ${maxPassPatterns.size}\")\n\n val result = freqsFor(maxFreq)\n .map(feqPattern => maxPassPatterns\n .map(iptrn => check(iptrn, feqPattern, a))).flatten.max\n println(result)\n\n }\n\n def getPassPatterns = {\n var ans: ListBuffer[Array[Int]] = ListBuffer()\n var maxFreq = 1\n ipattern.permutations.foreach(perPattern => {\n val frq = getMaxPass(perPattern, maxFreq)\n if (frq > maxFreq) {\n maxFreq = frq\n ans = ListBuffer(perPattern)\n } else if (frq == maxFreq) {\n ans += perPattern\n }\n })\n (maxFreq, ans)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.collection.mutable.ListBuffer\n\nobject Cards extends App {\n\n val n = readLine.toInt\n val a = readLine.split(\" \").map(_.toInt)\n// val a = Array(1, 8, 1, 2, 8, 2, 3, 8, 3, 4, 8, 4, 5, 8, 5, 6, 8, 6, 7, 8, 7, 8, 8, 8)\n// val a = Array(1,2,3,4,5,6,7,8)\n// val a = Array(1, 1, 1)\n// val a = Array(6, 7, 8, 5, 2, 8, 5, 4, 6, 4, 3, 2, 5, 6, 5, 7, 5, 7, 1, 7, 4, 6, 4, 1, 4, 1, 1, 7, 6, 7, 3, 7, 4, 7, 4, 6, 4, 7, 6, 6, 6, 5, 5, 7, 3, 5, 3, 7, 2, 2, 4, 2, 5, 6, 8, 4, 1, 2, 2, 8, 3, 3, 2, 5, 6, 4, 3, 6, 2, 4, 1, 4, 2, 8, 8, 3, 7, 6, 4, 7, 2, 7, 3, 3, 8, 8, 6, 8, 7, 7, 6, 8, 3, 2, 5, 2, 6, 5, 7, 5, 7, 5, 3, 2, 6, 2, 6, 5, 7, 8, 7, 7, 2, 6, 5, 4, 2, 3, 1, 8)\n\n val ipattern = Array(1, 2, 3, 4, 5, 6, 7, 8)\n\n\n def toBits(n: Int) =\n (0 to 7).map(i => ((1 << i) & n) != 0)\n\n def toFreqs(freq: Int, seq: Seq[Boolean]) =\n seq.map(if (_) freq + 1 else freq)\n\n def freqsFor(n: Int) =\n (1 to 255).map(toBits).map(toFreqs(n, _))\n\n def canPass(initPattern: Seq[Int], freq: Int, a: Array[Int]): Boolean = {\n if (freq * 8 > a.size) return false\n\n var pos = 0\n var patternPos = 0\n var counter = 0\n var result = 0\n\n while (true) {\n if (a(pos) == initPattern(patternPos)) {\n counter += 1\n if (counter == freq) {\n patternPos += 1\n result += counter\n counter = 0\n }\n }\n pos += 1\n\n if (pos == a.size || patternPos == initPattern.size)\n return result == (8 * freq)\n }\n return false\n }\n\n def getMaxPass(initPattern: Seq[Int], initFreq: Int): Int = {\n// val distinct = a.distinct.size\n// if (distinct < 8) return 0\n\n if (!canPass(initPattern, initFreq, a)) {\n return 0;\n }\n var freq = initFreq + 1\n do {\n val cnps = canPass(initPattern, freq, a)\n // println(s\"canpass $initPattern, $freq, $cnps \")\n if (!cnps) return freq - 1\n freq += 1\n } while (true)\n\n return 0;\n }\n\n def check(initPattern: Seq[Int], freqs: Seq[Int], a: Array[Int]): Int = {\n var pos = 0\n var patternPos = 0\n var counter = 0\n var result = 0\n\n while (true) {\n if (a(pos) == initPattern(patternPos)) {\n counter += 1\n if (counter == freqs(patternPos)) {\n patternPos += 1\n result += counter\n counter = 0\n }\n }\n pos += 1\n\n if (pos == a.size || patternPos == initPattern.size)\n return result\n }\n return 0\n }\n\n val d = a.distinct.size\n if (d < 8) {\n println(d)\n } else {\n\n val (maxFreq, maxPassPatterns) = getPassPatterns\n\n// println(s\"maxFreq: $maxFreq\")\n// println(s\"maxPassPatterns size: ${maxPassPatterns.size}\")\n\n val result = freqsFor(maxFreq)\n .map(feqPattern => maxPassPatterns\n .map(iptrn => check(iptrn, feqPattern, a))).flatten.max max 8\n println(result)\n\n }\n\n def getPassPatterns = {\n var ans: ListBuffer[Array[Int]] = ListBuffer()\n var maxFreq = 1\n ipattern.permutations.foreach(perPattern => {\n val frq = getMaxPass(perPattern, maxFreq)\n if (frq > maxFreq) {\n maxFreq = frq\n ans = ListBuffer(perPattern)\n } else if (frq == maxFreq) {\n ans += perPattern\n }\n })\n (maxFreq, ans)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.collection.mutable.ListBuffer\n\nobject Cards extends App {\n\n val n = readLine.toInt\n val a = readLine.split(\" \").map(_.toInt)\n// val a = Array(1, 8, 1, 2, 8, 2, 3, 8, 3, 4, 8, 4, 5, 8, 5, 6, 8, 6, 7, 8, 7, 8, 8, 8)\n// val a = Array(1,2,3,4,5,6,7,8)\n// val a = Array(1, 1, 1)\n// val a = Array(6, 7, 8, 5, 2, 8, 5, 4, 6, 4, 3, 2, 5, 6, 5, 7, 5, 7, 1, 7, 4, 6, 4, 1, 4, 1, 1, 7, 6, 7, 3, 7, 4, 7, 4, 6, 4, 7, 6, 6, 6, 5, 5, 7, 3, 5, 3, 7, 2, 2, 4, 2, 5, 6, 8, 4, 1, 2, 2, 8, 3, 3, 2, 5, 6, 4, 3, 6, 2, 4, 1, 4, 2, 8, 8, 3, 7, 6, 4, 7, 2, 7, 3, 3, 8, 8, 6, 8, 7, 7, 6, 8, 3, 2, 5, 2, 6, 5, 7, 5, 7, 5, 3, 2, 6, 2, 6, 5, 7, 8, 7, 7, 2, 6, 5, 4, 2, 3, 1, 8)\n\n val ipattern = Array(1, 2, 3, 4, 5, 6, 7, 8)\n\n\n def toBits(n: Int) =\n (0 to 7).map(i => ((1 << i) & n) != 0)\n\n def toFreqs(freq: Int, seq: Seq[Boolean]) =\n seq.map(if (_) freq + 1 else freq)\n\n def freqsFor(n: Int) =\n (1 to 255).map(toBits).map(toFreqs(n, _))\n\n def canPass(initPattern: Seq[Int], freq: Int, a: Array[Int]): Boolean = {\n if (freq * 8 > a.size) return false\n\n var pos = 0\n var patternPos = 0\n var counter = 0\n var result = 0\n\n while (true) {\n if (a(pos) == initPattern(patternPos)) {\n counter += 1\n if (counter == freq) {\n patternPos += 1\n result += counter\n counter = 0\n }\n }\n pos += 1\n\n if (pos == a.size || patternPos == initPattern.size)\n return result == (8 * freq)\n }\n return false\n }\n\n def getMaxPass(initPattern: Seq[Int], initFreq: Int): Int = {\n// val distinct = a.distinct.size\n// if (distinct < 8) return 0\n\n if (!canPass(initPattern, initFreq, a)) {\n return 0;\n }\n var freq = initFreq + 1\n do {\n val cnps = canPass(initPattern, freq, a)\n // println(s\"canpass $initPattern, $freq, $cnps \")\n if (!cnps) return freq - 1\n freq += 1\n } while (true)\n\n return 0;\n }\n\n def check(initPattern: Seq[Int], freqs: Seq[Int], a: Array[Int]): Int = {\n var pos = 0\n var patternPos = 0\n var counter = 0\n var result = 0\n\n while (true) {\n if (a(pos) == initPattern(patternPos)) {\n counter += 1\n if (counter == freqs(patternPos)) {\n patternPos += 1\n result += counter\n counter = 0\n }\n }\n pos += 1\n\n if (pos == a.size || patternPos == initPattern.size)\n return result\n }\n return 0\n }\n\n val d = a.distinct.size\n if (d < 8) {\n println(d)\n } else {\n\n val (maxFreq, maxPassPatterns) = getPassPatterns\n\n println(s\"maxFreq: $maxFreq\")\n println(s\"maxPassPatterns size: ${maxPassPatterns.size}\")\n\n val result = freqsFor(maxFreq)\n .map(feqPattern => maxPassPatterns\n .map(iptrn => check(iptrn, feqPattern, a))).flatten.max max 8\n println(result)\n\n }\n\n def getPassPatterns = {\n var ans: ListBuffer[Array[Int]] = ListBuffer()\n var maxFreq = 1\n ipattern.permutations.foreach(perPattern => {\n val frq = getMaxPass(perPattern, maxFreq)\n if (frq > maxFreq) {\n maxFreq = frq\n ans = ListBuffer(perPattern)\n } else if (frq == maxFreq) {\n ans += perPattern\n }\n })\n (maxFreq, ans)\n }\n\n}\n"}], "src_uid": "a0a4caebc8e2ca87e30f33971bff981d"} {"source_code": "object CF1 extends App{\n import scala.io.StdIn\n val arr = StdIn.readLine().split(' ').map(_.toInt)\n val n = arr(0)\n val k = arr(1)\n\n var ans = ((n - k) to 1 by (-k * 2 - 1)).toList.reverse\n\n\n if (ans.isEmpty){\n println(1)\n if (n >= 2)\n println(n / 2)\n else\n println(1)\n }else{\n ans = ans match {\n case x :: xs if x - k > 1 && 1 + k > x - k =>\n val r = (1 + k) - (x - k) + 1\n 1 :: ans.map(_+r).filter(_<=n)\n\n case x :: xs if x - k > 1 => 1 :: ans.map(_+1)\n case _ => ans\n }\n\n println(ans.size)\n ans.foreach(el => print(s\"$el \"))\n }\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject BBQ extends App {\n val sc = new Scanner(System.in)\n val in = sc.nextLine().split(\" \").map(_.toInt)\n val k = in.head\n val n = in.last\n val done = (for (i <- 0 until k) yield true).toArray\n val res = (for (i <- 0 to n+1) yield run(init(), List(i), 0)).filter(_._2 != Nil)\n if (res.nonEmpty) {\n val min = res.minBy(_._1)\n println(min._1)\n println(min._2.reverse.map(_ + 1).mkString(\" \"))\n } else println(\"no solution\")\n\n private def init() = (for (i <- 0 until k) yield false).toArray\n\n private def turn(index: Int, n: Int, switch: Array[Boolean]) = {\n def go(from: Int, to: Int) = {\n for (i <- from to to) {\n switch(i) = !switch(i)\n }\n switch\n }\n\n if (index - n < 0 && index + n >= switch.length-1) go(0, switch.length-1)\n else if (index - n < 0 && index + n < switch.length-1) go(0, index + n)\n else if (index - n >= 0 && index + n < switch.length-1) go(index - n, index + n)\n else go(index - n, switch.length - 1)\n }\n\n private def run(turned: Array[Boolean], indexes: List[Int], step: Int): (Int, List[Int]) = {\n if (indexes.head < turned.length && !done.sameElements(turned))\n run(turn(indexes.head, n, turned), (indexes.head + 2*n + 1) :: indexes, step + 1)\n else if (done.sameElements(turned)) (step, indexes.tail)\n else (step, Nil)\n }\n\n}"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val L = 2 * K + 1\n\n if (K == 0) {\n val ans = map(N)(i => i + 1)\n out.println(N)\n out.println(ans.mkString(\" \"))\n } else if (L >= N) {\n out.println(1)\n out.println(N / 2 + 1)\n } else {\n val ans = ArrayBuffer[Int]()\n def add(from: Int, to: Int): Unit = {\n rep((to - from) / L) { i =>\n ans += i * L + from + K\n }\n }\n val p = N / L\n val r = N - p * L\n if (r == 0) {\n add(0, N)\n } else if (r < K + 1) {\n def find(): Unit = {\n rep(K) { a =>\n val b = r - 1 - a\n if (b >= 0) {\n ans += a\n add(a + K + 1, N - (b + K + 1))\n ans += N - 1 - b\n return\n }\n }\n }\n find()\n\n } else { // r >= K + 1\n ans += r - K - 1\n add(r, N)\n }\n\n out.println(ans.length)\n out.println(ans.map(_ + 1).mkString(\" \"))\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n}"}], "negative_code": [{"source_code": "object CF1 extends App{\n import scala.io.StdIn\n val arr = StdIn.readLine().split(' ').map(_.toInt)\n val n = arr(0)\n val k = arr(1)\n\n val ans = (k + 1) to n by (k + 1)\n\n if (ans.isEmpty){\n println(1)\n println(n / 2)\n }else{\n println(ans.size)\n ans.foreach(el => print(s\"$el \"))\n }\n}\n"}, {"source_code": "object CF1 extends App{\n import scala.io.StdIn\n val arr = StdIn.readLine().split(' ').map(_.toInt)\n val n = arr(0)\n val k = arr(1)\n\n var ans = (n - k) to 1 by (-k * 2 - 1) toList\n\n\n if (ans.isEmpty){\n println(1)\n if (n >= 2)\n println(n / 2)\n else\n println(1)\n }else{\n ans = if (ans.last - k > 1) 1 :: ans.map(_+1).reverse else ans.reverse\n\n println(ans.size)\n ans.foreach(el => print(s\"$el \"))\n }\n}\n"}, {"source_code": "object CF1 extends App{\n import scala.io.StdIn\n val arr = StdIn.readLine().split(' ').map(_.toInt)\n val n = arr(0)\n val k = arr(1)\n\n var ans = (n - k) to 1 by (-k * 2 - 1) toList\n\n\n if (ans.isEmpty){\n println(1)\n println(n / 2)\n }else{\n ans = if (ans.last - k > 1) 1 :: ans.map(_+1).reverse else ans.reverse\n\n println(ans.size)\n ans.foreach(el => print(s\"$el \"))\n }\n}\n"}, {"source_code": "object CF1 extends App{\n import scala.io.StdIn\n val arr = StdIn.readLine().split(' ').map(_.toInt)\n val n = arr(0)\n val k = arr(1)\n\n val ans = (k + 1) to n by (k * 2)\n\n if (ans.isEmpty){\n println(1)\n println(n / 2)\n }else{\n println(ans.size)\n ans.foreach(el => print(s\"$el \"))\n }\n}\n"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val L = 2 * K + 1\n\n if (L >= N) {\n out.println(N / 2 + 1)\n } else if (K == 0) {\n val ans = map(N)(i => i + 1)\n out.println(ans.mkString(\" \"))\n } else {\n val ans = ArrayBuffer[Int]()\n def add(from: Int, to: Int): Unit = {\n rep((to - from) / L) { i =>\n ans += i * L + from + K\n }\n }\n val p = N / L\n val r = N - p * L\n if (r == 0) {\n add(0, N)\n } else if (r < K + 1) {\n def find(): Unit = {\n rep(K) { a =>\n val b = r - 1 - a\n if (b >= 0) {\n ans += a\n add(a + K + 1, N - (b + K + 1))\n ans += N - 1 - b\n return\n }\n }\n }\n find()\n\n } else { // r >= K + 1\n ans += r - K - 1\n add(r, N)\n }\n\n out.println(ans.length)\n out.println(ans.map(_ + 1).mkString(\" \"))\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n}"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val L = 2 * K + 1\n\n if (L >= N) {\n out.println(N / 2 + 1)\n } else {\n val ans = ArrayBuffer[Int]()\n def add(from: Int, to: Int): Unit = {\n rep((to - from) / L) { i =>\n ans += i * L + from + K\n }\n }\n val p = N / L\n val r = N - p * L\n if (r == 0) {\n add(0, N)\n } else if (r < K + 1) {\n def find(): Unit = {\n rep(K) { a =>\n val b = r - 1 - a\n if (b >= 0) {\n ans += a\n add(a + K + 1, N - (b + K + 1))\n ans += N - 1 - b\n return\n }\n }\n }\n find()\n\n } else { // r >= K + 1\n ans += r - K - 1\n add(r, N)\n }\n\n out.println(ans.length)\n out.println(ans.map(_ + 1).mkString(\" \"))\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n}"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val L = 2 * K + 1\n\n if (L >= N) {\n out.println(N / 2)\n } else {\n val ans = ArrayBuffer[Int]()\n def add(from: Int, to: Int): Unit = {\n rep((to - from) / L) { i =>\n ans += i * L + from + K\n }\n }\n val p = N / L\n val r = N - p * L\n if (r == 0) {\n add(0, N)\n } else if (r < K + 1) {\n def find(): Unit = {\n rep(K) { a =>\n val b = r - 1 - a\n if (b >= 0) {\n ans += a\n add(a + K + 1, N - (b + K + 1))\n ans += N - 1 - b\n return\n }\n }\n }\n find()\n\n } else { // r >= K + 1\n ans += r - K - 1\n add(r, N)\n }\n\n out.println(ans.length)\n out.println(ans.map(_ + 1).mkString(\" \"))\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n}"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val L = 2 * K + 1\n\n if (L >= N) {\n out.println(N / 2)\n } else {\n val ans = ArrayBuffer[Int]()\n def add(from: Int, to: Int): Unit = {\n rep((to - from) / L) { i =>\n ans += i * L + from + K\n }\n }\n val p = N / L\n val r = N - p * L\n if (r == 0) {\n add(0, N)\n } else if (r < K + 1) {\n def find(): Unit = {\n rep(K) { a =>\n val b = r - 1 - a\n if (b >= 0) {\n ans += a\n add(a + K + 1, N - (b + K + 1))\n ans += N - 1 - K\n return\n }\n }\n }\n find()\n\n } else { // r >= K + 1\n ans += r - K - 1\n add(r, N)\n }\n\n out.println(ans.length)\n out.println(ans.map(_ + 1).mkString(\" \"))\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n}"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val L = 2 * K + 1\n\n if (L >= N) {\n out.println(N / 2)\n } else {\n val ans = ArrayBuffer[Int]()\n def add(from: Int, to: Int): Unit = {\n rep((to - from) / L) { i =>\n ans += i * L + from + K\n }\n }\n val p = N / L\n val r = N - p * L\n if (r == 0) {\n add(0, N)\n } else {\n// } else if (r < K + 1) {\n def find(): Unit = {\n rep(K) { a =>\n val b = r - 1 - a\n if (b >= 0) {\n ans += a\n add(a + K + 1, N - (b + K + 1))\n ans += N - 1 - b\n return\n }\n }\n }\n find()\n//\n// } else { // r >= K + 1\n// ans += r - K - 1\n// add(r, N)\n }\n\n out.println(ans.length)\n out.println(ans.map(_ + 1).mkString(\" \"))\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n}"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val L = 2 * K + 1\n\n if (K == 0) {\n val ans = map(N)(i => i + 1)\n out.println(ans.mkString(\" \"))\n } else if (L >= N) {\n out.println(N / 2 + 1)\n } else {\n val ans = ArrayBuffer[Int]()\n def add(from: Int, to: Int): Unit = {\n rep((to - from) / L) { i =>\n ans += i * L + from + K\n }\n }\n val p = N / L\n val r = N - p * L\n if (r == 0) {\n add(0, N)\n } else if (r < K + 1) {\n def find(): Unit = {\n rep(K) { a =>\n val b = r - 1 - a\n if (b >= 0) {\n ans += a\n add(a + K + 1, N - (b + K + 1))\n ans += N - 1 - b\n return\n }\n }\n }\n find()\n\n } else { // r >= K + 1\n ans += r - K - 1\n add(r, N)\n }\n\n out.println(ans.length)\n out.println(ans.map(_ + 1).mkString(\" \"))\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n}"}, {"source_code": "object BBQ extends App {\n val k = 5 //val k = args(0)\n val n = 1 //val n = args(1)\n val done = (for (i <- 0 until k) yield true).toArray\n val res = (for (i <- done.indices) yield run(init(), List(i), 0)).filter(_._2 != Nil)\n if (res.nonEmpty) {\n val min = res.minBy(_._1)\n println(min._1)\n println(min._2.reverse.map(_ + 1).mkString(\" \"))\n } else println(\"no solution\")\n\n private def init() = (for (i <- 0 until k) yield false).toArray\n\n private def turn(index: Int, n: Int, switch: Array[Boolean]) = {\n def go(from: Int, to: Int) = {\n for (i <- from to to) {\n switch(i) = !switch(i)\n }\n switch\n }\n\n if (index - n < 0 && index + n >= switch.length-1) go(0, switch.length-1)\n else if (index - n < 0 && index + n < switch.length-1) go(0, index + n)\n else if (index - n >= 0 && index + n < switch.length-1) go(index - n, index + n)\n else go(index - n, switch.length - 1)\n }\n\n private def run(turned: Array[Boolean], indexes: List[Int], step: Int): (Int, List[Int]) = {\n if (indexes.head < turned.length && !done.sameElements(turned))\n run(turn(indexes.head, n, turned), (indexes.head + 2*n + 1) :: indexes, step + 1)\n else if (done.sameElements(turned)) (step, indexes.tail)\n else (step, Nil)\n }\n\n}"}], "src_uid": "dfd60a02670749c67b0f96df1a0709b9"} {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, b) = readInts(2)\n val res = Array.fill(n) { -1L }\n\n case class Task(id: Int, t: Int, d: Int)\n\n val tasks = Array.tabulate(n) { id =>\n val Array(t, d) = readInts(2)\n Task(id, t, d)\n }.sortBy(_.t)\n\n val queue = mutable.Queue.empty[Task]\n\n var time = 0L\n for (i <- tasks.indices) {\n val task = tasks(i)\n while (time <= task.t && queue.nonEmpty) {\n val queued = queue.dequeue()\n time += queued.d\n res(queued.id) = time\n }\n if (time < task.t) time = task.t\n if (queue.size < b) queue += task\n }\n\n while (queue.nonEmpty) {\n val queued = queue.dequeue()\n time += queued.d\n res(queued.id) = time\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.mkString(\" \"))\n Console.flush\n}\n", "positive_code": [{"source_code": "\nimport scala.collection.mutable._\nimport scala.io.StdIn._\n\nobject Solution {\n\n def main(args: Array[String]): Unit = {\n val lines = scala.io.Source.stdin.getLines.toList\n val (firstLine, rest) = \n lines match {\n case x::xs => (x, xs)\n case _ => throw new RuntimeException\n }\n\n val (numQueries, queueSize) = \n firstLine.split(\" \") match {\n case Array(x, y) => (x.toInt, y.toInt)\n }\n\n val jobs = (for {\n line <- rest.zipWithIndex\n } yield parseLine(line)).toList\n\n val finishedJobs = processQueries(jobs, numQueries, queueSize).sortBy(_.getId)\n finishedJobs.foreach(x => print(x.getEndTime + \" \"))\n println\n }\n\n\n def processQueries(pendingJobs: List[PendingJob], numQueries: Int, queueSize: Int): Vector[FinishedJob] = {\n val queue = Queue[PendingJob]()\n val finishedJobs: ArrayBuffer[FinishedJob] = ArrayBuffer.empty[FinishedJob]\n val remainingJobs: ListBuffer[PendingJob] = pendingJobs.to[ListBuffer]\n\n def queuePendingJobs(curTime: Long) = {\n while (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime < curTime) {\n val head = remainingJobs.remove(0)\n if (queue.size == queueSize) {\n finishedJobs += head.fail\n } else {\n queue enqueue head\n }\n }\n }\n\n def getNextRunningJob(curTime: Long): Option[PendingJob] = {\n if (!queue.isEmpty) {\n val job = queue.dequeue\n finishedJobs += job.run(curTime)\n Some(job)\n }\n else if (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime == curTime) {\n val job = remainingJobs.remove(0)\n finishedJobs += job.run(curTime)\n Some(job)\n }\n else \n None\n }\n\n\n def loop(curJob: Option[CompleteJob], curTime: Long): Vector[FinishedJob] = {\n if (queue.isEmpty && remainingJobs.isEmpty) {\n finishedJobs.toVector\n } else if (!queue.isEmpty && remainingJobs.isEmpty) {\n var currentTime = curTime\n while (!queue.isEmpty) {\n val curJob = queue.dequeue\n val runJob = curJob.run(currentTime)\n finishedJobs += runJob\n currentTime = currentTime + curJob.processTime\n }\n finishedJobs.toVector\n } else {\n queuePendingJobs(curTime)\n\n val f = () => {\n val nextJob = getNextRunningJob(curTime)\n nextJob match {\n case Some(y) => {\n val completeNextJob = y.run(curTime)\n Some(completeNextJob)\n }\n case _ => None\n }\n }\n val nextRunningJob: Option[CompleteJob] = \n curJob match {\n case Some(x) if (x.endTime <= curTime) => f()\n case Some(x) => Some(x)\n case None => f()\n }\n\n\n val getNextStartTime: Long = \n nextRunningJob match {\n case Some(x) => x.endTime\n case None => if (!remainingJobs.isEmpty) remainingJobs.head.arrivalTime else curTime + 1\n }\n loop(nextRunningJob, getNextStartTime)\n }\n }\n\n loop(None, 0)\n }\n\n def parseLine(line: Tuple2[String, Int]): PendingJob = {\n line._1.split(\" \") match {\n case Array(x, y) => PendingJob(line._2, x.toInt, y.toInt)\n }\n }\n\n}\n\n\ncase class PendingJob(id: Int, arrivalTime: Long, processTime: Long) {\n def run(curTime: Long): CompleteJob = CompleteJob(id, processTime + curTime)\n def fail: FailedJob = FailedJob(id)\n}\ntrait FinishedJob {\n def getId: Int\n def getEndTime: Long\n}\ncase class CompleteJob(id: Int, endTime: Long) extends FinishedJob {\n override def getId: Int = id\n override def getEndTime = endTime\n}\ncase class FailedJob(id: Int) extends FinishedJob {\n override def getId: Int = id\n override def getEndTime = -1L\n}\n\n"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, b) = readInts(2)\n val res = Array.fill(n) { -1 }\n\n case class Task(id: Int, t: Int, d: Int)\n\n val tasks = Array.tabulate(n) { id =>\n val Array(t, d) = readInts(2)\n Task(id, t, d)\n }.sortBy(_.t)\n\n val queue = mutable.Queue.empty[Task]\n\n var time = 0\n for (i <- tasks.indices) {\n val task = tasks(i)\n while (time <= task.t && queue.nonEmpty) {\n val queued = queue.dequeue()\n time += queued.d\n res(queued.id) = time\n }\n if (time < task.t) time = task.t\n if (queue.size < b) queue += task\n }\n\n while (queue.nonEmpty) {\n val queued = queue.dequeue()\n time += queued.d\n res(queued.id) = time\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.mkString(\" \"))\n Console.flush\n}\n"}, {"source_code": "import scala.collection.immutable.Queue\n\nobject Solution {\n\n def main(args: Array[String]): Unit = {\n val (firstLine, lines) = \n scala.io.Source.stdin.getLines.toList match {\n case x::xs => (x, xs)\n case _ => throw new RuntimeException\n }\n\n val (numQueries, sizeOfQueue) = \n firstLine.split(\" \").map(_.toInt) match {\n case Array(x, y) => (x, y)\n }\n\n val jobs: List[PendingJob] = \n for {\n lineWithIndex <- lines.zipWithIndex\n } yield parseJob(lineWithIndex._1, lineWithIndex._2)\n\n processJobs(jobs, numQueries, sizeOfQueue).sortWith(_.index < _.index).foreach(x => print(x + \" \"))\n println\n }\n\n\n def processJobs(jobs: List[PendingJob], numQueries: Int, sizeOfQueue: Int): Vector[FinishedJob] = {\n @scala.annotation.tailrec\n def loop(curJob: Option[RunningJob], remainingJobs: List[PendingJob], queue: Queue[PendingJob], curTime: Long, processedJobs: Vector[FinishedJob]): Vector[FinishedJob] = {\n def getNextStartTime = {\n remainingJobs match {\n case x::_ => x.arrivalTime\n case Nil => curJob.get.endTime\n }\n }\n if (remainingJobs.isEmpty && queue.isEmpty) {\n processedJobs\n } else {\n val (currentlyArrivingJob, newRemainingJobs) = \n remainingJobs match {\n case x::xs if x.arrivalTime == curTime => (Some(x), xs)\n case _ => (None, remainingJobs)\n }\n\n val curRunningJob: Option[RunningJob] = \n curJob match {\n case Some(x) if x.endTime <= curTime => None\n case _ => curJob\n }\n var nextStartTime = curTime + 1\n val (nextRunningJob, newQueue, newProcessedJobs) = \n (currentlyArrivingJob, curRunningJob) match {\n case (None, Some(_)) => {\n nextStartTime = getNextStartTime\n (curRunningJob, queue, processedJobs)\n }\n case (None, None) => {\n if (queue.isEmpty) {\n nextStartTime = getNextStartTime\n (None, queue, processedJobs)\n } else {\n val (nextJob, q) = queue.dequeue\n val newRunningJob = nextJob.start(curTime)\n (Some(newRunningJob), q, processedJobs :+ newRunningJob)\n }\n }\n case (Some(x), None) => {\n if (queue.isEmpty) {\n val newRunningJob = x.start(curTime)\n (Some(newRunningJob), queue, processedJobs :+ newRunningJob)\n } else {\n val (nextJob, q) = queue.dequeue\n val newRunningJob: RunningJob = nextJob.start(curTime)\n (Some(newRunningJob), q enqueue x, processedJobs :+ newRunningJob)\n }\n }\n case (Some(x), Some(_)) if queue.size < sizeOfQueue => \n (curRunningJob, queue enqueue x, processedJobs)\n case (Some(x), _) => \n val failedPendingJob = x.start(curTime)\n (curRunningJob, queue, processedJobs :+ FailedJob(x.index))\n }\n\n loop(nextRunningJob, newRemainingJobs, newQueue, nextStartTime, newProcessedJobs)\n }\n }\n loop(None, jobs, Queue[PendingJob](), 0, Vector[RunningJob]())\n }\n\n //Parses a single line of input into a job\n private def parseJob(line: String, index: Int): PendingJob = {\n val startAndProcess: Array[Int] = line.split(\" \").map(_.toInt)\n PendingJob(index, startAndProcess(0), startAndProcess(1))\n }\n}\n\n//a single processing job\ntrait Job\ncase class PendingJob(index: Int, arrivalTime: Long, processTime: Long) extends Job {\n def start(curTime: Long) = RunningJob(index, curTime + processTime)\n}\nabstract class FinishedJob(val index: Int, val endTime: Long) {\n override def toString = endTime.toString\n}\ncase class RunningJob(theIndex: Int, theEndTime: Long) extends FinishedJob(theIndex, theEndTime)\ncase class FailedJob(theIndex: Int) extends FinishedJob(theIndex, -1) \n"}, {"source_code": "\nimport scala.collection.mutable._\nimport scala.io.StdIn._\n\nobject Solution {\n\n def main(args: Array[String]): Unit = {\n val lines = scala.io.Source.stdin.getLines.toList\n val (firstLine, rest) = \n lines match {\n case x::xs => (x, xs)\n case _ => throw new RuntimeException\n }\n\n val (numQueries, queueSize) = \n firstLine.split(\" \") match {\n case Array(x, y) => (x.toInt, y.toInt)\n }\n\n val jobs = (for {\n line <- rest.zipWithIndex\n } yield parseLine(line)).toList\n\n val finishedJobs = processQueries(jobs, numQueries, queueSize).sortBy(_.getId)\n finishedJobs.foreach(x => print(x.getEndTime + \" \"))\n println\n }\n\n\n def processQueries(pendingJobs: List[PendingJob], numQueries: Int, queueSize: Int): Vector[FinishedJob] = {\n val queue = Queue[PendingJob]()\n val finishedJobs: ArrayBuffer[FinishedJob] = ArrayBuffer.empty[FinishedJob]\n val remainingJobs: ListBuffer[PendingJob] = pendingJobs.to[ListBuffer]\n\n def queuePendingJobs(curTime: Long) = {\n if(!remainingJobs.isEmpty)println(remainingJobs.head.arrivalTime)\n while (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime < curTime) {\n val head = remainingJobs.remove(0)\n if (queue.size == queueSize) {\n finishedJobs += head.fail\n } else {\n queue enqueue head\n finishedJobs += head.run(curTime)\n }\n }\n }\n\n def getNextRunningJob(curTime: Long): Option[PendingJob] = {\n if (!queue.isEmpty) \n Some(queue.dequeue)\n else if (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime == curTime) {\n val job = remainingJobs.remove(0)\n finishedJobs += job.run(curTime)\n Some(job)\n }\n else \n None\n }\n\n\n def loop(curJob: Option[CompleteJob], curTime: Long): Vector[FinishedJob] = {\n println(\"Current time is \" + curTime)\n if (queue.isEmpty && remainingJobs.isEmpty) {\n finishedJobs.toVector\n } else if (!queue.isEmpty && remainingJobs.isEmpty) {\n var currentTime = curTime\n while (!queue.isEmpty) {\n val curJob = queue.dequeue\n val runJob = curJob.run(currentTime)\n finishedJobs += runJob\n currentTime = currentTime + curJob.processTime\n }\n finishedJobs.toVector\n } else {\n queuePendingJobs(curTime)\n\n val f = () => {\n val nextJob = getNextRunningJob(curTime)\n nextJob match {\n case Some(y) => {\n val completeNextJob = y.run(curTime)\n Some(completeNextJob)\n }\n case _ => None\n }\n }\n val nextRunningJob: Option[CompleteJob] = \n curJob match {\n case Some(x) if (x.endTime <= curTime) => f()\n case Some(x) => Some(x)\n case None => f()\n }\n\n\n val getNextStartTime: Long = \n nextRunningJob match {\n case Some(x) => x.endTime\n case None => if (!remainingJobs.isEmpty) remainingJobs.head.arrivalTime else curTime + 1\n }\n loop(nextRunningJob, getNextStartTime)\n }\n }\n\n loop(None, 0)\n }\n\n def parseLine(line: Tuple2[String, Int]): PendingJob = {\n line._1.split(\" \") match {\n case Array(x, y) => PendingJob(line._2, x.toInt, y.toInt)\n }\n }\n\n}\n\n\ncase class PendingJob(id: Int, arrivalTime: Long, processTime: Long) {\n def run(curTime: Long): CompleteJob = CompleteJob(id, processTime + curTime)\n def fail: FailedJob = FailedJob(id)\n}\ntrait FinishedJob {\n def getId: Int\n def getEndTime: Long\n}\ncase class CompleteJob(id: Int, endTime: Long) extends FinishedJob {\n override def getId: Int = id\n override def getEndTime = endTime\n}\ncase class FailedJob(id: Int) extends FinishedJob {\n override def getId: Int = id\n override def getEndTime = -1L\n}\n\n"}, {"source_code": "\nimport scala.collection.mutable._\nimport scala.io.StdIn._\n\nobject Solution {\n\n def main(args: Array[String]): Unit = {\n val lines = scala.io.Source.stdin.getLines.toList\n val (firstLine, rest) = \n lines match {\n case x::xs => (x, xs)\n case _ => throw new RuntimeException\n }\n\n val (numQueries, queueSize) = \n firstLine.split(\" \") match {\n case Array(x, y) => (x.toInt, y.toInt)\n }\n\n val jobs = (for {\n line <- rest.zipWithIndex\n } yield parseLine(line)).toList\n\n val finishedJobs = processQueries(jobs, numQueries, queueSize).sortBy(_.getId)\n finishedJobs.foreach(x => print(x.getEndTime + \" \"))\n println\n }\n\n\n def processQueries(pendingJobs: List[PendingJob], numQueries: Int, queueSize: Int): Vector[FinishedJob] = {\n val queue = Queue[PendingJob]()\n val finishedJobs: ArrayBuffer[FinishedJob] = ArrayBuffer.empty[FinishedJob]\n val remainingJobs: ListBuffer[PendingJob] = pendingJobs.to[ListBuffer]\n\n def queuePendingJobs(curTime: Long) = {\n while (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime < curTime) {\n val head = remainingJobs.remove(0)\n if (queue.size == queueSize) {\n finishedJobs += head.fail\n } else {\n queue enqueue head\n finishedJobs += head.run(curTime)\n }\n }\n }\n\n def getNextRunningJob(curTime: Long): Option[PendingJob] = {\n if (!queue.isEmpty) \n Some(queue.dequeue)\n else if (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime == curTime) {\n val job = remainingJobs.remove(0)\n finishedJobs += job.run(curTime)\n Some(job)\n }\n else \n None\n }\n\n\n def loop(curJob: Option[CompleteJob], curTime: Long): Vector[FinishedJob] = {\n if (queue.isEmpty && remainingJobs.isEmpty) {\n finishedJobs.toVector\n } else if (!queue.isEmpty && remainingJobs.isEmpty) {\n var currentTime = curTime\n while (!queue.isEmpty) {\n val curJob = queue.dequeue\n val runJob = curJob.run(currentTime)\n finishedJobs += runJob\n currentTime = currentTime + curJob.processTime\n }\n finishedJobs.toVector\n } else {\n queuePendingJobs(curTime)\n\n val f = () => {\n val nextJob = getNextRunningJob(curTime)\n nextJob match {\n case Some(y) => {\n val completeNextJob = y.run(curTime)\n Some(completeNextJob)\n }\n case _ => None\n }\n }\n val nextRunningJob: Option[CompleteJob] = \n curJob match {\n case Some(x) if (x.endTime <= curTime) => f()\n case Some(x) => Some(x)\n case None => f()\n }\n\n\n val getNextStartTime: Long = \n nextRunningJob match {\n case Some(x) => x.endTime\n case None => if (!remainingJobs.isEmpty) remainingJobs.head.arrivalTime else curTime + 1\n }\n loop(nextRunningJob, getNextStartTime)\n }\n }\n\n loop(None, 0)\n }\n\n def parseLine(line: Tuple2[String, Int]): PendingJob = {\n line._1.split(\" \") match {\n case Array(x, y) => PendingJob(line._2, x.toInt, y.toInt)\n }\n }\n\n}\n\n\ncase class PendingJob(id: Int, arrivalTime: Long, processTime: Long) {\n def run(curTime: Long): CompleteJob = CompleteJob(id, processTime + curTime)\n def fail: FailedJob = FailedJob(id)\n}\ntrait FinishedJob {\n def getId: Int\n def getEndTime: Long\n}\ncase class CompleteJob(id: Int, endTime: Long) extends FinishedJob {\n override def getId: Int = id\n override def getEndTime = endTime\n}\ncase class FailedJob(id: Int) extends FinishedJob {\n override def getId: Int = id\n override def getEndTime = -1L\n}\n\n"}, {"source_code": "import scala.collection.immutable.Queue\n\nobject Solution {\n\n def main(args: Array[String]): Unit = {\n val (firstLine, lines) = \n scala.io.Source.stdin.getLines.toList match {\n case x::xs => (x, xs)\n case _ => throw new RuntimeException\n }\n\n val (numQueries, sizeOfQueue) = \n firstLine.split(\" \").map(_.toInt) match {\n case Array(x, y) => (x, y)\n }\n\n val jobs: List[PendingJob] = \n for {\n line <- lines\n } yield parseJob(line)\n\n processJobs(jobs, numQueries, sizeOfQueue).foreach(x => print(x + \" \"))\n println\n }\n\n\n def processJobs(jobs: List[PendingJob], numQueries: Int, sizeOfQueue: Int): Vector[Int] = {\n def loop(curJob: Option[RunningJob], remainingJobs: List[PendingJob], queue: Queue[PendingJob], curTime: Int, processedJobs: Vector[Int]): Vector[Int] = {\n if (remainingJobs.isEmpty && queue.isEmpty) {\n processedJobs\n } else {\n val (currentlyArrivingJob, newRemainingJobs) = \n remainingJobs match {\n case x::xs if x.arrivalTime == curTime => (Some(x), xs)\n case _ => (None, remainingJobs)\n }\n\n val curRunningJob: Option[RunningJob] = \n curJob match {\n case Some(x) if x.endTime == curTime => None\n case _ => curJob\n }\n\n val (nextRunningJob, newQueue, newProcessedJobs) = \n (currentlyArrivingJob, curRunningJob) match {\n case (None, Some(_)) => (curRunningJob, queue, processedJobs)\n case (None, None) => {\n if (queue.isEmpty) {\n (None, queue, processedJobs)\n } else {\n val (nextJob, q) = queue.dequeue\n val newRunningJob = nextJob.start(curTime)\n (Some(newRunningJob), q, processedJobs :+ newRunningJob.endTime)\n }\n }\n case (Some(x), None) => {\n if (queue.isEmpty) {\n val newRunningJob = x.start(curTime)\n (Some(newRunningJob), queue, processedJobs :+ newRunningJob.endTime)\n } else {\n val (nextJob, q) = queue.dequeue\n val newRunningJob: RunningJob = nextJob.start(curTime)\n (Some(newRunningJob), q enqueue x, processedJobs :+ newRunningJob.endTime)\n }\n }\n case (Some(x), Some(_)) if queue.size < sizeOfQueue => \n (curRunningJob, queue enqueue x, processedJobs)\n case _ => \n (curRunningJob, queue, processedJobs :+ -1)\n }\n\n loop(nextRunningJob, newRemainingJobs, newQueue, curTime + 1, newProcessedJobs)\n }\n }\n loop(None, jobs, Queue[PendingJob](), 0, Vector[Int]())\n }\n\n //Parses a single line of input into a job\n private def parseJob(line: String): PendingJob = {\n val startAndProcess: Array[Int] = line.split(\" \").map(_.toInt)\n PendingJob(startAndProcess(0), startAndProcess(1))\n }\n}\n\n//a single processing job\ntrait Job\ncase class PendingJob(arrivalTime: Int, processTime: Int) extends Job {\n def start(curTime: Int) = RunningJob(curTime + processTime)\n}\ncase class RunningJob(endTime: Int) extends Job\n"}], "src_uid": "5981594b2d6d1077ce2249b641d18f10"} {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\nimport collection.mutable.ArrayBuffer\n\nobject test2 extends App {\n\tval in=new Scanner(new File(\"input.txt\"))\n\tval out=new PrintWriter(\"output.txt\")\n\t//val in=new Scanner(System.in)\n //val out=new PrintWriter(System.out)\n\t\n\tval n=in.nextLine.toInt\n\tvar olyms=new Array[Olym](n)\n\tfor(i<-0 until n) olyms(i)=new Olym(in.nextLine.split(\" \").map(_.toInt))\n\tolyms=olyms.sortBy(_.start)\n\tvar hm=collection.mutable.Map[Int,Int]()\n\tfor(o<-olyms)\n\t{\n\t\to.start until o.end foreach{i=>\n\t\t\thm(i)=hm.getOrElse(i, 0)+o.p\n\t\t}\n\t}\n\t\n\tout.println(hm.values.max)\n\tout.close\n}\n\nclass Olym(input:Array[Int]){\n private[this] val months=Array(0,31,28,31,30,31,30,31,31,30,31,30,31)\n val end=months.slice(0,input(0)).sum+input(1)\n val start=end-input(3)\n val p=input(2)\n \n override def toString=\"%d:%d:%d\".format(start,end,p)\n \n def isOverlap(o:Olym):Boolean={\n ((start until end toSet) & (o.start until o.end toSet)).size>0\n }\n}\n", "positive_code": [{"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\nimport collection.mutable.ArrayBuffer\n\nobject test2 extends App {\n\tval in=new Scanner(new File(\"input.txt\"))\n\tval out=new PrintWriter(\"output.txt\")\n\t//val in=new Scanner(System.in)\n //val out=new PrintWriter(System.out)\n\tval months=Array(0,31,28,31,30,31,30,31,31,30,31,30,31)\n\tval n=in.nextLine.toInt\n\tvar hm=collection.mutable.Map[Int,Int]()\n\n\tfor(i<-0 until n){\n\t val Array(m,d,p,t)=in.nextLine.split(\" \").map(_.toInt)\n\t val end=months.slice(0,m).sum+d\n\t val start=end-t\n\t \n\t start until end foreach{j=>\n\t \thm(j)=hm.getOrElse(j, 0)+p\n\t }\n\t}\n\t\n\tout.println(hm.values.max)\n\tout.close\n}\n"}], "negative_code": [{"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\nimport collection.mutable.ArrayBuffer\n\nobject test2 extends App {\n\tval in=new Scanner(new File(\"input.txt\"))\n\tval out=new PrintWriter(\"output.txt\")\n\t//val in=new Scanner(System.in)\n //val out=new PrintWriter(System.out)\n\t\n\tval n=in.nextLine.toInt\n\tvar olyms=new Array[Olym](n)\n\tfor(i<-0 until n) olyms(i)=new Olym(in.nextLine.split(\" \").map(_.toInt))\n\tolyms=olyms.sortBy(_.day)\n\n\tvar max=0\n\tvar start=0\n\tvar total=0\n\tfor(i<-0 until n)\n\t{\n\t\tvar j=0\n\t\twhile(j0\n }\n}\n"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\nimport collection.mutable.ArrayBuffer\n\nobject test2 extends App {\n\tval in=new Scanner(new File(\"input.txt\"))\n\tval out=new PrintWriter(\"output.txt\")\n\t//val in=new Scanner(System.in)\n //val out=new PrintWriter(System.out)\n\t\n\tval n=in.nextLine.toInt\n\tvar olyms=new Array[Olym](n)\n\tfor(i<-0 until n) olyms(i)=new Olym(in.nextLine.split(\" \").map(_.toInt))\n\tolyms=olyms.sortBy(_.day)\n\n\tvar max=0\n\tvar start=0\n\tvar total=0\n\tfor(i<-0 until n)\n\t{\n\t\tvar j=0\n\t\twhile(j0\n }\n}\n"}], "src_uid": "34655e8de9f1020677c5681d9d217d75"} {"source_code": "object A extends App {\r\n\r\n implicit final class StringOps(private val input: String) extends AnyVal {\r\n def abBalance: String = {\r\n require(input.nonEmpty, \"The given string should not be empty.\")\r\n\r\n input.sliding(2).foldLeft(0) {\r\n case (count, \"ab\") => count + 1\r\n case (count, \"ba\") => count - 1\r\n case (count, _) => count\r\n } match {\r\n case 0 => input\r\n case 1 => s\"b${input.tail}\"\r\n case -1 => s\"a${input.tail}\"\r\n }\r\n }\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val s = nextLine()\r\n\r\n out.println(s.abBalance)\r\n }\r\n\r\n out.flush()\r\n\r\n object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n private[this] def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class pair(var s: Int, var a: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n if (a == that.a && s == that.s)\n return 0\n if (a > that.s && that.a <= s)\n return 1\n if (a <= that.s && that.a > s)\n return -1\n if (a == that.a) {\n if (s < that.s)\n return -1\n else\n return 1\n }\n if (a < that.a)\n return -1\n else\n return 1\n }\n }\n val rem = 1000000007\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n\n val t = readInt()\n for (tt <- 1 to t) {\n var s = readString()\n var a = 0\n var b = 0\n for (i <- 0 until s.length - 1) {\n if (s(i) == 'a' && s(i+1) == 'b')\n a += 1\n if (s(i) == 'b' && s(i+1) == 'a')\n b += 1\n }\n if (a != b) {\n if(s(0) == 'a')\n s = 'b' + s.substring(1)\n else\n s = 'a' + s.substring(1)\n }\n writer.println(s)\n }\n writer.flush()\n}\n"}], "negative_code": [{"source_code": "object A extends App {\r\n\r\n implicit final class StringOps(private val str: String) extends AnyVal {\r\n def abBalance: String = {\r\n require(str.nonEmpty, \"The given string should not be empty.\")\r\n\r\n val intervals = str.indices.tail.foldLeft((0, 0) :: Nil) {\r\n case ((p, q) :: intervals, i) if str(i) == str(q) => (p, i) :: intervals\r\n case (intervals, i) => (i, i) :: intervals\r\n }\r\n\r\n if ((intervals.length - 1) % 2 == 0) str\r\n else {\r\n val (fl, fr) = intervals.head\r\n val (ll, lr) = intervals.last\r\n val (l, r) = if (fr - fl < lr - ll) (fl, fr) else (ll, lr)\r\n\r\n val slice = (if (str(l) == 'a') \"b\" else \"a\") * (r - l + 1)\r\n\r\n s\"${str.slice(0, l)}$slice${str.slice(r + 1, str.length)}\"\r\n }\r\n }\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val s = nextLine()\r\n\r\n out.println(s.abBalance)\r\n }\r\n\r\n out.flush()\r\n\r\n object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n private[this] def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}, {"source_code": "object A extends App {\r\n\r\n implicit final class StringOps(private val str: String) extends AnyVal {\r\n def abBalance: String = {\r\n require(str.nonEmpty, \"The given string should not be empty.\")\r\n\r\n val intervals = str.indices.tail.foldLeft((0, 0) :: Nil) {\r\n case ((p, q) :: intervals, i) if str(i) == str(q) => (p, i) :: intervals\r\n case (intervals, i) => (i, i) :: intervals\r\n }\r\n\r\n if ((intervals.length - 1) % 2 == 0) str\r\n else {\r\n val (p, q) = intervals.minBy { case (p, q) => q - p }\r\n val slice = (if (str(p) == 'a') \"b\" else \"a\") * (q - p + 1)\r\n\r\n s\"${str.slice(0, p)}$slice${str.slice(q + 1, str.length)}\"\r\n }\r\n }\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val s = nextLine()\r\n\r\n out.println(s.abBalance)\r\n }\r\n\r\n out.flush()\r\n\r\n object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n private[this] def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}], "src_uid": "351ffff1dfe1bc1762f062f612463759"} {"source_code": "object A342 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val num = readInts(n)\n val map = cu.Map.empty[Int, Int].withDefaultValue(0)\n num.foreach{n1 => map(n1)+=1}\n if(map(1) == n/3 && Array(5,7).forall(map(_) == 0)) {\n if(map(3) <= map(6)) {\n if(map(2) == map(6)-map(3)+map(4)) {\n for(i <- 0 until map(3)) {\n println(s\"1 3 6\")\n }\n for(i <- 0 until map(6)-map(3)) {\n println(s\"1 2 6\")\n }\n for(i <- 0 until map(4)) {\n println(s\"1 2 4\")\n }\n } else {\n out.println(\"-1\")\n }\n } else {\n out.println(\"-1\")\n }\n } else {\n out.println(\"-1\")\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val map = scala.collection.mutable.Map[Int, Int]()\n a.foreach(i => map(i) = map.getOrElse(i, 0) + 1)\n \n val n7 = map.getOrElse(7, 0)\n val n6 = map.getOrElse(6, 0)\n val n5 = map.getOrElse(5, 0)\n val n4 = map.getOrElse(4, 0)\n var n3 = map.getOrElse(3, 0)\n var n2 = map.getOrElse(2, 0) \n var n1 = map.getOrElse(1, 0)\n \n var seq = scala.collection.mutable.Seq[String]()\n \n if (n5 != 0 || n7 != 0) { println(\"-1\"); return }\n \n if (n6 < n3) { println(\"-1\"); return }\n else {\n for (_ <- 1 to n3) seq ++= Seq(\"1 3 6\")\n n2 -= (n6 - n3)\n n1 -= n6\n if (n2 < 0) { println(\"-1\"); return }\n for (_ <- 1 to (n6 - n3)) seq ++= Seq(\"1 2 6\")\n }\n \n if (n4 != n2) { println(\"-1\"); return }\n else {\n n1 -= n4\n for (_ <- 1 to n2) seq ++= Seq(\"1 2 4\")\n }\n \n if (n1 != 0) println(\"-1\")\n else seq.foreach(println)\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.immutable.Queue\nimport scala.util.Random\n\nobject P342A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val X = Array.fill(N)(sc.nextInt)\n\n // Possible groups\n // 1 2 4 => g4\n // 1 2 6 => g62\n // 1 3 6 => g63\n\n def solve(): Unit = {\n val c = Array.fill(8)(0)\n X foreach { x => c(x) += 1 }\n\n if (c(5) > 0 || c(7) > 0) out.println(\"-1\")\n else {\n val g4 = c(4)\n c(1) -= g4\n c(2) -= g4\n\n if (c(2) < 0 || c(1) != c(6) || c(2) + c(3) != c(6)) out.println(-1)\n else {\n for (i <- 0 until g4) out.println(\"1 2 4\")\n for (i <- 0 until c(2)) out.println(\"1 2 6\")\n for (i <- 0 until c(3)) out.println(\"1 3 6\")\n }\n }\n }\n\n solve\n out.close\n}\n \n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = Array.ofDim[Int](8)\n in.next().split(' ').foreach {\n i => data(i.toInt) += 1\n }\n val rest = if (data(5) != 0 || data(7) != 0)\n Nil\n else {\n var res = List.empty[(Int, Int, Int)]\n\n (1 to data(3)).foreach { _ =>\n res ::= (1, 3, 6)\n }\n data(1) -= data(3)\n data(6) -= data(3)\n data(3) = 0\n if (data(1) < 0 || data(6) < 0)\n Nil\n else {\n var count = data(1) + data(2) + data(4) + data(6)\n while (count > 0) {\n val list = List(data(4) -> 4, data(6) -> 6).sorted.tail.map(_._2)\n val d = (1 :: 2 :: list).sorted\n res ::= (d.head, d(1), d.last)\n count -= 3\n d.foreach(i => data(i) -= 1)\n\n if (d.exists(i => data(i) < 0)) {\n count = -1\n res = Nil\n }\n }\n res\n }\n }\n if (rest.isEmpty)\n println(-1)\n else\n println(rest.map(i => s\"${i._1} ${i._2} ${i._3}\").mkString(\"\\n\"))\n\n}\n"}, {"source_code": "object B {\n def main(args: Array[String]) {\n var n = readInt()\n var a:Array[Int] = readLine() split(\" \") map(_.toInt)\n var cnt = (Range(0, 8) map (x=> a.count(_==x))).toArray;\n f(a, cnt, 1, 2, 4)\n f(a, cnt, 1, 2, 6)\n f(a, cnt, 1, 3, 6)\n println(if ((cnt count(_ > 0)) > 0) -1 else result)\n }\n\n val result = new StringBuilder();\n def f(a:IndexedSeq[Int], cnt:Array[Int], i1:Int, i2:Int, i3:Int) {\n\n val m = math.min(cnt(i1), math.min(cnt(i2), cnt(i3)));\n for (i <- 1 to m) result.append(\"%d %d %d\\n\".format(i1, i2, i3))\n for (i <- List(i1, i2, i3)) cnt(i) -= m;\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = Array.ofDim[Int](8)\n in.next().split(' ').foreach {\n i => data(i.toInt) += 1\n }\n val rest = if (data(5) != 0 || data(7) != 0)\n Nil\n else {\n var res = List.empty[(Int, Int, Int)]\n\n (1 to data(3)).foreach { _ =>\n res ::= (1, 3, 6)\n }\n data(1) -= data(3)\n data(6) -= data(3)\n data(3) = 0\n if (data(1) < 0 || data(6) < 0)\n Nil\n else {\n var count = data(1) + data(2) + data(4) + data(6)\n while (count > 0) {\n val list = List(data(1) -> 1, data(4) -> 4, data(6) -> 6).sorted.tail.map(_._2)\n val d = (2 :: list).sorted\n res ::= (d.head, d(1), d.last)\n count -= 3\n d.foreach(i => data(i) -= 1)\n\n if (d.exists(i => data(i) < 0)) {\n count = -1\n res = Nil\n }\n }\n res\n }\n }\n if (rest.isEmpty)\n println(-1)\n else\n println(rest.map(i => s\"${i._1} ${i._2} ${i._3}\").mkString(\"\\n\"))\n\n}\n"}, {"source_code": "object A342 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val num = readInts(n)\n val map = cu.Map.empty[Int, Int].withDefaultValue(0)\n num.foreach{n1 => map(n1)+=1}\n if(map(1) == n/3) {\n if(map(3) <= map(6)) {\n if(map(2) == map(6)-map(3)+map(4)) {\n for(i <- 0 until map(3)) {\n println(s\"1 3 6\")\n }\n for(i <- 0 until map(6)-map(3)) {\n println(s\"1 2 6\")\n }\n for(i <- 0 until map(4)) {\n println(s\"1 2 4\")\n }\n } else {\n out.println(\"-1\")\n }\n } else {\n out.println(\"-1\")\n }\n } else {\n out.println(\"-1\")\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.immutable.Queue\nimport scala.util.Random\n\nobject P342A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val X = Array.fill(N)(sc.nextInt)\n\n // Possible groups\n // 1 2 4 => g4\n // 1 2 6 => g62\n // 1 3 6 => g63\n\n def solve(): Unit = {\n val c = Array.fill(8)(0)\n X foreach { x => c(x) += 1 }\n\n if (c(5) * c(7) > 0) out.println(-1)\n else {\n val g4 = c(4)\n c(1) -= g4\n c(2) -= g4\n\n if (c(1) != c(6) || c(2) + c(3) != c(6)) out.println(-1)\n else {\n for (i <- 0 until g4) out.println(\"1 2 4\")\n for (i <- 0 until c(2)) out.println(\"1 2 6\")\n for (i <- 0 until c(3)) out.println(\"1 3 5\")\n }\n }\n }\n\n solve\n out.close\n}\n \n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.immutable.Queue\nimport scala.util.Random\n\nobject P342A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val X = Array.fill(N)(sc.nextInt)\n\n // Possible groups\n // 1 2 4 => g4\n // 1 2 6 => g62\n // 1 3 6 => g63\n\n def solve(): Unit = {\n val c = Array.fill(8)(0)\n X foreach { x => c(x) += 1 }\n\n if (c(5) * c(7) > 0) out.println(-1)\n else {\n val g4 = c(4)\n c(1) -= g4\n c(2) -= g4\n\n if (c(2) < 0 || c(1) != c(6) || c(2) + c(3) != c(6)) out.println(-1)\n else {\n for (i <- 0 until g4) out.println(\"1 2 4\")\n for (i <- 0 until c(2)) out.println(\"1 2 6\")\n for (i <- 0 until c(3)) out.println(\"1 3 6\")\n }\n }\n }\n\n solve\n out.close\n}\n \n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.immutable.Queue\nimport scala.util.Random\n\nobject P342A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val X = Array.fill(N)(sc.nextInt)\n\n // Possible groups\n // 1 2 4 => g4\n // 1 2 6 => g62\n // 1 3 6 => g63\n\n def solve(): Unit = {\n val c = Array.fill(8)(0)\n X foreach { x => c(x) += 1 }\n\n if (c(5) * c(7) > 0) out.println(-1)\n else {\n val g4 = c(4)\n c(1) -= g4\n c(2) -= g4\n\n if (c(2) < 0 || c(1) != c(6) || c(2) + c(3) != c(6)) out.println(-1)\n else {\n for (i <- 0 until g4) out.println(\"1 2 4\")\n for (i <- 0 until c(2)) out.println(\"1 2 6\")\n for (i <- 0 until c(3)) out.println(\"1 3 5\")\n }\n }\n }\n\n solve\n out.close\n}\n \n"}, {"source_code": "object B {\n def main(args: Array[String]) {\n var n = readInt()\n var a:Array[Int] = readLine() split(\" \") map(_.toInt)\n var cnt = (Range(0, 7) map (x=> a.count(_==x))).toArray;\n f(a, cnt, 1, 2, 4)\n f(a, cnt, 1, 2, 6)\n f(a, cnt, 1, 3, 6)\n println(if ((cnt count(_ > 0)) > 0) -1 else result)\n }\n\n val result = new StringBuilder();\n def f(a:IndexedSeq[Int], cnt:Array[Int], i1:Int, i2:Int, i3:Int) {\n\n val m = math.min(cnt(i1), math.min(cnt(i2), cnt(i3)));\n for (i <- 1 to m) result.append(\"%d %d %d\\n\".format(i1, i2, i3))\n for (i <- List(i1, i2, i3)) cnt(i) -= m;\n }\n}\n"}, {"source_code": "object A {\n var b = false;\n def main(args: Array[String]) {\n var n = readInt()\n var a:Array[Int] = readLine() split(\" \") map(_.toInt)\n var cnt = (Range(0, 7) map (x=> a.count(_==x))).toArray;\n f(a, cnt, 1, 2, 4)\n f(a, cnt, 1, 2, 6)\n f(a, cnt, 1, 3, 6)\n if (!b) println(-1)\n\n }\n\n def f(a:IndexedSeq[Int], cnt:Array[Int], i1:Int, i2:Int, i3:Int) {\n val m = math.min(cnt(i1), math.min(cnt(i2), cnt(i3)));\n for (i <- 1 to m) { printf(\"%d %d %d\\n\", i1, i2, i3); b = true }\n for (i <- List(i1, i2, i3)) cnt(i) -= m;\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val map = scala.collection.mutable.Map[Int, Int]()\n a.foreach(i => map(i) = map.getOrElse(i, 0) + 1)\n \n val n6 = map.getOrElse(6, 0)\n val n5 = map.getOrElse(5, 0)\n val n4 = map.getOrElse(4, 0)\n var n3 = map.getOrElse(3, 0)\n var n2 = map.getOrElse(2, 0) \n var n1 = map.getOrElse(1, 0)\n \n var seq = scala.collection.mutable.Seq[String]()\n \n if (n5 != 0) { println(\"-1\"); return }\n \n if (n6 < n3) { println(\"-1\"); return }\n else {\n for (_ <- 1 to n3) seq ++= Seq(\"1 3 6\")\n n2 -= (n6 - n3)\n n1 -= n6\n if (n2 < 0) { println(\"-1\"); return }\n for (_ <- 1 to (n6 - n3)) seq ++= Seq(\"1 2 6\")\n }\n \n if (n4 != n2) { println(\"-1\"); return }\n else {\n n1 -= n4\n for (_ <- 1 to n2) seq ++= Seq(\"1 2 4\")\n }\n \n if (n1 != 0) println(\"-1\")\n else seq.foreach(println)\n }\n}"}], "src_uid": "513234db1bab98c2c2ed6c7030c1ac72"} {"source_code": "import scala.collection.mutable.ArrayBuilder\n\nobject P2775D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n val revBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n }\n\n val adj = adjBuilders.map(_.result)\n\n val cnts = Array.fill(n, n)(0) \n\n for {\n u <- 0 until n\n v <- adj(u)\n w <- adj(v)\n if w != u \n } cnts(w)(u) += 1\n\n var sum = 0L\n \n for {\n u <- 0 until n\n c <- cnts(u)\n if c > 1\n } sum += c * (c - 1) / 2 \n \n println(sum)\n}", "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuilder\n\nobject P2775D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n val revBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n }\n\n val adj = adjBuilders.map(_.result)\n\n val cnts = Array.fill(n, n)(0)\n\n for (u <- 0 until n)\n for (v <- adj(u))\n for (w <- adj(v))\n if (w != u) cnts(w)(u) += 1\n\n var sum = 0L\n\n for (u <- 0 until n)\n for (c <- cnts(u))\n if (c > 1) sum += c * (c - 1) / 2\n\n println(sum)\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuilder\n\nobject P2775D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n val revBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (i <- 0 until m) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n }\n\n val adj = adjBuilders.map(_.result)\n\n val cnts = Array.fill(n, n)(0) \n\n for {\n u <- 0 until n\n v <- adj(u)\n w <- adj(v)\n if w != u \n } cnts(w)(u) += 1\n\n var sum = 0L\n \n for {\n u <- 0 until n\n c <- cnts(u)\n } sum += c * (c - 1) / 2 \n \n println(sum)\n}"}], "negative_code": [], "src_uid": "6e85f83d544eeb16f57523eb532abf04"} {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs, ys = Array.ofDim[Long](n)\n for (i <- 0 until n) {\n val Array(x, y) = readLongs(2)\n xs(i) = x\n ys(i) = y\n }\n \n def sqr(x: Double) = x * x\n def dist(i: Int, j: Int) = sqr(xs(i - 1) - xs(j - 1)) + sqr(ys(i - 1) - ys(j - 1))\n \n case class Point(x: BigInt, y: BigInt)\n\n def direction(uv: (Point, Point), w: Point) =\n (uv._2.x - uv._1.x) * (w.y - uv._1.y) - (w.x - uv._1.x) * (uv._2.y - uv._1.y)\n \n def area(i: Int, j: Int, k: Int) = {\n val al = Math.sqrt(dist(i, j))\n val bl = Math.sqrt(dist(j, k))\n val cl = Math.sqrt(dist(i, k))\n val s = (al + bl + cl) / 2d\n Math.sqrt(s * (s - al) * (s - bl) * (s - cl))\n }\n \n val a = 1\n var b = 2\n var ab = dist(a, b)\n for (i <- 3 to n) {\n val d2 = dist(a, i)\n if (d2 < ab) {\n b = i\n ab = d2\n }\n }\n\n var c = 0\n var abc = Double.PositiveInfinity\n val pA = Point(xs(a - 1), ys(a - 1))\n val pB = Point(xs(b - 1), ys(b - 1))\n val pAB = pA -> pB\n\n for (i <- 2 to n) if (i != b && direction(pAB, Point(xs(i - 1), ys(i - 1))) != 0) {\n val a2 = area(a, b, i)\n if (a2 < abc) {\n c = i\n abc = a2\n }\n }\n\n println(s\"$a $b $c\")\n}\n", "positive_code": [{"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject CF2016_C { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n is = new ByteArrayInputStream(Test.t50.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n val stars = new Array[(Long, Long)](n+1)\n \n val ad = 1000000000\n for(i <- 1 to n) {\n val line = readLine()\n stars(i) = (line.long+ad, line.long+ad)\n }\n \n val x = stars(1)._1\n val y = stars(1)._2\n var distances = new Array[(Int, BigDecimal, BigDecimal)](n-1)\n for(i <- 2 to n) {\n val xDif = BigDecimal((x - stars(i)._1).abs)\n val yDif = BigDecimal((y - stars(i)._2).abs)\n \n val xSq = xDif*xDif\n val ySq = yDif*yDif\n val dist = (xSq + ySq)\n \n// val dist = Math.sqrt(xDif*xDif + yDif*yDif)\n// val xDifAbs = BigDecimal((x - stars(i)._1))\n// val relSin = (xDif*xDif)/dist * xDifAbs.signum\n val relSin = (xDif*xDif)/dist\n val alpha = relSin\n \n distances(i-2) = (i, dist, alpha)\n db(i + \" -> \" + dist)\n }\n \n distances = distances.sortWith(_._2 < _._2)\n db(distances.mkString(\", \"))\n\n var zerro = false\n def calcFun(s1:Int, s2:Int) :(BigDecimal, BigDecimal) = {\n if (stars(s2)._1 - stars(s1)._1 == 0) {\n zerro = true\n return (0,0)\n }\n val a = (BigDecimal(stars(s2)._2) - stars(s1)._2) / (stars(s2)._1 - stars(s1)._1)\n val b = (BigDecimal(stars(s1)._2)-ad) - a * (BigDecimal(stars(s1)._1) - ad)\n (a, b)\n }\n \n var secondInd = 1\n val alpha1 = distances(0)._3\n val coef = calcFun(1, 2)\n db(\"coef = \" + coef)\n// while (secondInd < distances.size && check(alpha1,distances(secondInd)._3)) {\n while (secondInd < distances.size && check(alpha1,distances(secondInd)._3) && \n (isZerro(distances(secondInd)._1) || \n belongs(coef._1, coef._2, distances(secondInd)._1))) {\n secondInd+= 1\n }\n \n def isZerro(st:Int): Boolean = {\n if (zerro && stars(st)._1 == x) {\n true\n } else {\n \t false\n }\n }\n \n def check(v1:BigDecimal, v2:BigDecimal) = {\n// val diff = (v1 - v2).abs\n// diff < 0.00000000001\n v1 == v2\n }\n \n\n \n def belongs(a:BigDecimal, b:BigDecimal, st:Int):Boolean = {\n val y = a*(stars(st)._1-ad) + b\n val diff = (y - (stars(st)._2-ad)).abs\n db(\"func diff \" + st + \" -> \" + diff)\n return diff < 0.000000001\n }\n \n// def area(a:BigDecimal, b:BigDecimal, c:BigDecimal) = {\n// s;\n// }\n \n def dist(v1:(Long,Long), v2:(Long,Long)) {\n val xDif = BigDecimal((v1._1 - v2._1).abs)\n val yDif = BigDecimal((v1._2 - v2._2).abs)\n val xSq = xDif*xDif\n val ySq = yDif*yDif\n val dist = (xSq + ySq)\n }\n \n println(1 + \" \" + distances(0)._1 + \" \" + distances(secondInd)._1)\n \n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n \n //---------------------------- service code ----------------------------------\n \n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n5\n0 0\n0 2\n2 0\n2 2\n1 1\n\"\"\"\n \nval sa2 = \"\"\"\n3\n-1000000000 -1000000000\n1000000000 1000000000\n1000000000 1000000000\n\"\"\"\n\nval t15 = \"\"\"\n10\n13303280 387243789\n30131431 723806809\n404775998 670757742\n-25996011 -398742031\n25599613 633170449\n38471092 890600029\n-33017802 -539177851\n-47620079 -831223391\n1425218 149682549\n-3745401 46270169\n\"\"\"\n \nval t49 = \"\"\"\n10\n999999999 1\n999999998 1\n999999997 1\n1000000000 1\n999999996 1\n999999995 1\n999999994 1\n999999992 1\n999999993 1\n0 0\n\"\"\"\n \nval t50 = \"\"\"\n4\n0 1\n0 2\n0 3\n7 7\n\"\"\"\n \nval t84 = \"\"\"\n3\n1 2\n2 1\n2 3\n\"\"\"\n}\n\n}\n\n"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs, ys = Array.ofDim[Long](n)\n for (i <- 0 until n) {\n val Array(x, y) = readLongs(2)\n xs(i) = x\n ys(i) = y\n }\n \n def sqr(x: Double) = x * x\n def dist(i: Int, j: Int) = sqr(xs(i - 1) - xs(j - 1)) + sqr(ys(i - 1) - ys(j - 1))\n \n case class Point(x: Long, y: Long)\n\n def direction(uv: (Point, Point), w: Point) =\n (uv._2.x - uv._1.x) * (w.y - uv._1.y) - (w.x - uv._1.x) * (uv._2.y - uv._1.y)\n \n def area(i: Int, j: Int, k: Int) = {\n val al = Math.sqrt(dist(i, j))\n val bl = Math.sqrt(dist(j, k))\n val cl = Math.sqrt(dist(i, k))\n val s = (al + bl + cl) / 2d\n Math.sqrt(s * (s - al) * (s - bl) * (s - cl))\n }\n \n val a = 1\n var b = 2\n var ab = dist(a, b)\n for (i <- 3 to n) {\n val d2 = dist(a, i)\n if (d2 < ab) {\n b = i\n ab = d2\n }\n }\n\n var c = 0\n var abc = Double.PositiveInfinity\n val pA = Point(xs(a - 1), ys(a - 1))\n val pB = Point(xs(b - 1), ys(b - 1))\n val pAB = pA -> pB\n\n for (i <- 2 to n) if (i != b && direction(pAB, Point(xs(i - 1), ys(i - 1))) != 0) {\n val a2 = area(a, b, i)\n if (a2 < abc) {\n c = i\n abc = a2\n }\n }\n\n println(s\"$a $b $c\")\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject CF2016_C_2 { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n is = new ByteArrayInputStream(Test.t84.trim.getBytes(\"ISO-8859-1\"))\n debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n val stars = new Array[(Long, Long)](n+1)\n \n for(i <- 1 to n) {\n val line = readLine()\n stars(i) = (line.long, line.long)\n }\n \n val x = stars(1)._1\n val y = stars(1)._2\n var distances = new Array[(Int, Double)](n-1)\n for(i <- 2 to n) {\n val xDif = (x - stars(i)._1).abs\n val yDif = (y - stars(i)._2).abs\n \n val xSq = xDif*xDif //overflow?\n val ySq = yDif*yDif\n val dist = (xSq + ySq)\n \n distances(i-2) = (i, dist)\n db(i + \" -> \" + dist)\n }\n \n distances = distances.sortWith(_._2 < _._2)\n db(distances.mkString(\", \"))\n\n var zerro = false\n def calcFun(s1:Int, s2:Int) :(Double, Double) = {\n val xDif = stars(s2)._1 - stars(s1)._1\n if (xDif == 0) {\n zerro = true\n return (0,0)\n }\n val a = (stars(s2)._2 - stars(s1)._2) / xDif\n val b = stars(s1)._2 - a * stars(s1)._1\n (a, b)\n }\n \n var secondInd = 1\n val fun = calcFun(1, distances(0)._1)\n db(\"fun = \" + fun + \" zerro=\" + zerro)\n while (secondInd < distances.size && \n belongs(fun, distances(secondInd)._1)) {\n secondInd+= 1\n }\n \n def belongs(fun:(Double, Double), st:Int):Boolean = {\n val star = stars(st)\n if (zerro && star._1 == x) {\n true\n } else {\n\t val (a,b) = fun\n\t val y = a*star._1 + b\n\t val diff = (y - star._2).abs\n\t db(\"func diff \" + st + \" -> \" + diff)\n\t return diff < 0.000000001\n }\n }\n \n println(1 + \" \" + distances(0)._1 + \" \" + distances(secondInd)._1)\n \n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n \n //---------------------------- service code ----------------------------------\n \n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n5\n0 0\n0 2\n2 0\n2 2\n1 1\n\"\"\"\n \nval sa2 = \"\"\"\n3\n-1000000000 -1000000000\n1000000000 1000000000\n1000000000 999999999\n\"\"\"\n\nval t15 = \"\"\"\n10\n13303280 387243789\n30131431 723806809\n404775998 670757742\n-25996011 -398742031\n25599613 633170449\n38471092 890600029\n-33017802 -539177851\n-47620079 -831223391\n1425218 149682549\n-3745401 46270169\n\"\"\"\n \nval t49 = \"\"\"\n10\n999999999 1\n999999998 1\n999999997 1\n1000000000 1\n999999996 1\n999999995 1\n999999994 1\n999999992 1\n999999993 1\n0 0\n\"\"\"\n \nval t50 = \"\"\"\n4\n0 1\n0 2\n0 3\n7 7\n\"\"\"\n \nval t84 = \"\"\"\n3\n1 2\n2 1\n2 3\n\"\"\"\n}\n\n}\n\n"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs, ys = Array.ofDim[Long](n)\n for (i <- 0 until n) {\n val Array(x, y) = readLongs(2)\n xs(i) = x\n ys(i) = y\n }\n \n def sqr(x: Double) = x * x\n def dist(i: Int, j: Int) = sqr(xs(i - 1) - xs(j - 1)) + sqr(ys(i - 1) - ys(j - 1))\n \n case class Point(x: BigInt, y: BigInt)\n\n def direction(uv: (Point, Point), w: Point) =\n (uv._2.x - uv._1.x) * (w.y - uv._1.y) - (w.x - uv._1.x) * (uv._2.y - uv._1.y)\n \n def area(i: Int, j: Int, k: Int) = {\n val al = Math.sqrt(dist(i, j))\n val bl = Math.sqrt(dist(j, k))\n val cl = Math.sqrt(dist(i, k))\n val s = (al + bl + cl) / 2d\n Math.sqrt(s * (s - al) * (s - bl) * (s - cl))\n }\n \n val a = 1\n var b = 2\n var ab = dist(a, b)\n for (i <- 3 to n) {\n val d2 = dist(a, i)\n if (d2 < ab) {\n b = i\n ab = d2\n }\n }\n\n var c = if (b == 2) 3 else 2\n var abc = area(a, b, c)\n val pA = Point(xs(a - 1), ys(a - 1))\n val pB = Point(xs(b - 1), ys(b - 1))\n val pAB = pA -> pB\n\n for (i <- 2 to n) if (i != b && direction(pAB, Point(xs(i - 1), ys(i - 1))) != 0) {\n val a2 = area(a, b, i)\n if (a2 > 0.1d && (a2 < abc || abc < 0.1d)) {\n c = i\n abc = a2\n }\n }\n\n println(s\"$a $b $c\")\n}\n"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs, ys = Array.ofDim[Long](n)\n for (i <- 0 until n) {\n val Array(x, y) = readLongs(2)\n xs(i) = x\n ys(i) = y\n }\n \n def sqr(x: Double) = x * x\n def dist(i: Int, j: Int) = sqr(xs(i - 1) - xs(j - 1)) + sqr(ys(i - 1) - ys(j - 1))\n \n def area(i: Int, j: Int, k: Int) = {\n val al = Math.sqrt(dist(i, j))\n val bl = Math.sqrt(dist(j, k))\n val cl = Math.sqrt(dist(i, k))\n val s = (al + bl + cl) / 2d\n Math.sqrt(s) * (s - al) * (s - bl) * (s - cl)\n }\n \n val a = 1\n var b = 2\n var ab = dist(a, b)\n for (i <- 3 to n) {\n val d2 = dist(a, i)\n if (d2 < ab) {\n b = i\n ab = d2\n }\n }\n\n var c = if (b == 2) 3 else 2\n var abc = area(a, b, c)\n\n for (i <- 2 to n) if (i != b) {\n val a2 = area(a, b, i)\n if (a2 > 0.1d && (a2 < abc || abc < 0.1d)) {\n c = i\n abc = a2\n }\n }\n\n println(s\"$a $b $c\")\n}\n"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs, ys = Array.ofDim[Long](n)\n for (i <- 0 until n) {\n val Array(x, y) = readLongs(2)\n xs(i) = x\n ys(i) = y\n }\n \n def sqr(x: Long) = x * x\n def dist(i: Int, j: Int) = sqr(xs(i - 1) - xs(j - 1)) + sqr(ys(i - 1) - ys(j - 1))\n \n def area(i: Int, j: Int, k: Int) = {\n val al = Math.sqrt(dist(i, j))\n val bl = Math.sqrt(dist(j, k))\n val cl = Math.sqrt(dist(i, k))\n val s = (al + bl + cl) / 2d\n Math.sqrt(s) * (s - al) * (s - bl) * (s - cl)\n }\n \n val a = 1\n var b = 2\n var ab = dist(a, b)\n for (i <- 3 to n) {\n val d2 = dist(a, i)\n if (d2 < ab) {\n b = i\n ab = d2\n }\n }\n\n var c = if (b == 2) 3 else 2\n var abc = area(a, b, c)\n\n for (i <- 2 to n) if (i != b) {\n val a2 = area(a, b, i)\n if (a2 > 0.1d && (a2 < abc || abc < 0.1d)) {\n c = i\n abc = a2\n }\n }\n\n println(s\"$a $b $c\")\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject CF2016_C { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.sa2.trim.getBytes(\"ISO-8859-1\"))\n debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n val stars = new Array[(Long, Long)](n+1)\n \n val ad = 1000000000\n for(i <- 1 to n) {\n val line = readLine()\n stars(i) = (line.long+ad, line.long+ad)\n }\n \n val x = stars(1)._1\n val y = stars(1)._2\n var distances = new Array[(Int, Double, Double)](n-1)\n for(i <- 2 to n) {\n val xDif = (x - stars(i)._1).abs\n val yDif = (y - stars(i)._2).abs\n \n val dist = Math.sqrt(xDif*xDif + yDif*yDif)\n val relSin = xDif/dist\n val alpha = relSin\n \n distances(i-2) = (i, dist, alpha)\n db(i + \" -> \" + dist)\n }\n \n distances = distances.sortWith(_._2 < _._2)\n db(distances.mkString(\", \"))\n \n \n var secondInd = 1\n val alpha1 = distances(0)._3\n while (secondInd < distances.size && alpha1 == distances(secondInd)._3) {\n secondInd+= 1\n }\n \n println(1 + \" \" + distances(0)._1 + \" \" + distances(secondInd)._1)\n \n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n \n //---------------------------- service code ----------------------------------\n \n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n5\n0 0\n0 2\n2 0\n2 2\n1 1\n\"\"\"\n \nval sa2 = \"\"\"\n3\n-1000000000 -1000000000\n1000000000 1000000000\n1000000000 1000000000\n\"\"\"\n\n}\n\n}\n\n"}, {"source_code": "\n\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject CF2016_C { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n is = new ByteArrayInputStream(Test.t15.trim.getBytes(\"ISO-8859-1\"))\n debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n val stars = new Array[(Long, Long)](n+1)\n \n val ad = 1000000000\n for(i <- 1 to n) {\n val line = readLine()\n stars(i) = (line.long+ad, line.long+ad)\n }\n \n val x = stars(1)._1\n val y = stars(1)._2\n var distances = new Array[(Int, BigDecimal, BigDecimal)](n-1)\n for(i <- 2 to n) {\n val xDif = BigDecimal((x - stars(i)._1).abs)\n val yDif = BigDecimal((y - stars(i)._2).abs)\n \n val xSq = xDif*xDif\n val ySq = yDif*yDif\n val dist = (xSq + ySq)\n \n// val dist = Math.sqrt(xDif*xDif + yDif*yDif)\n val xDifAbs = BigDecimal((x - stars(i)._1))\n val relSin = (xDif*xDif)/dist * xDifAbs.signum\n val alpha = relSin\n \n distances(i-2) = (i, dist, alpha)\n db(i + \" -> \" + dist)\n }\n \n distances = distances.sortWith(_._2 < _._2)\n db(distances.mkString(\", \"))\n\n var zerro = false\n def calcFun(s1:Int, s2:Int) :(Double, Double) = {\n if (stars(s2)._1 - stars(s1)._1 == 0) {\n zerro = true\n return (0,0)\n }\n val a = (stars(s2)._2 - stars(s1)._2) / (stars(s2)._1 - stars(s1)._1)\n val b = stars(s1)._2 - a * stars(s1)._1 - ad*2\n (a, b)\n }\n \n var secondInd = 1\n val alpha1 = distances(0)._3\n val coef = calcFun(1, 2)\n db(\"coef = \" + coef)\n// while (secondInd < distances.size && check(alpha1,distances(secondInd)._3)) {\n while (secondInd < distances.size && check(alpha1,distances(secondInd)._3) && (zerro || belongs(coef._1, coef._2, secondInd+1))) {\n secondInd+= 1\n }\n \n def check(v1:BigDecimal, v2:BigDecimal) = {\n// val diff = (v1 - v2).abs\n// diff < 0.00000000001\n v1 == v2\n }\n \n\n \n def belongs(a:Double, b:Double, st:Int):Boolean = {\n val y = a*stars(st)._1 + b\n return (y - stars(st)._2).abs < 0.000000001\n }\n \n// def area(a:BigDecimal, b:BigDecimal, c:BigDecimal) = {\n// s;\n// }\n \n def dist(v1:(Long,Long), v2:(Long,Long)) {\n val xDif = BigDecimal((v1._1 - v2._1).abs)\n val yDif = BigDecimal((v1._2 - v2._2).abs)\n val xSq = xDif*xDif\n val ySq = yDif*yDif\n val dist = (xSq + ySq)\n }\n \n println(1 + \" \" + distances(0)._1 + \" \" + distances(secondInd)._1)\n \n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n \n //---------------------------- service code ----------------------------------\n \n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n5\n0 0\n0 2\n2 0\n2 2\n1 1\n\"\"\"\n \nval sa2 = \"\"\"\n3\n-1000000000 -1000000000\n1000000000 1000000000\n1000000000 1000000000\n\"\"\"\n\nval t15 = \"\"\"\n10\n13303280 387243789\n30131431 723806809\n404775998 670757742\n-25996011 -398742031\n25599613 633170449\n38471092 890600029\n-33017802 -539177851\n-47620079 -831223391\n1425218 149682549\n-3745401 46270169\n\"\"\"\n \nval t49 = \"\"\"\n10\n999999999 1\n999999998 1\n999999997 1\n1000000000 1\n999999996 1\n999999995 1\n999999994 1\n999999992 1\n999999993 1\n0 0\n\"\"\"\n \nval t84 = \"\"\"\n3\n1 2\n2 1\n2 3\n\"\"\"\n}\n\n}\n\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject CF2016_C { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.sa2.trim.getBytes(\"ISO-8859-1\"))\n debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n val stars = new Array[(Long, Long)](n+1)\n \n val ad = 1000000000\n for(i <- 1 to n) {\n val line = readLine()\n stars(i) = (line.long+ad, line.long+ad)\n }\n \n val x = stars(1)._1\n val y = stars(1)._2\n var distances = new Array[(Int, Double, Double)](n-1)\n for(i <- 2 to n) {\n val xDif = (x - stars(i)._1).abs\n val yDif = (y - stars(i)._2).abs\n \n val dist = Math.sqrt(xDif*xDif + yDif*yDif)\n val relSin = dist/(xDif+1)\n val alpha = Math.asin(relSin)\n \n distances(i-2) = (i, dist, alpha)\n db(i + \" -> \" + dist)\n }\n \n distances = distances.sortWith(_._2 < _._2)\n db(distances.mkString(\", \"))\n \n \n var secondInd = 1\n val alpha1 = distances(0)._3\n while (secondInd < distances.size && alpha1 == distances(secondInd)._3) {\n secondInd+= 1\n }\n \n println(1 + \" \" + distances(0)._1 + \" \" + distances(secondInd)._1)\n \n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n \n //---------------------------- service code ----------------------------------\n \n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n5\n0 0\n0 2\n2 0\n2 2\n1 1\n\"\"\"\n \nval sa2 = \"\"\"\n3\n-1000000000 -1000000000\n1000000000 1000000000\n1000000000 1000000000\n\"\"\"\n\n}\n\n}\n\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject CF2016_C { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.sa2.trim.getBytes(\"ISO-8859-1\"))\n debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n val stars = new Array[(Long, Long)](n+1)\n \n val ad = 1000000000\n for(i <- 1 to n) {\n val line = readLine()\n stars(i) = (line.long+ad, line.long+ad)\n }\n \n val x = stars(1)._1\n val y = stars(1)._2\n var distances = new Array[(Int, Double, Double)](n-1)\n for(i <- 2 to n) {\n val xDif = (x - stars(i)._1).abs\n val yDif = (y - stars(i)._2).abs\n \n val dist = Math.sqrt(xDif*xDif + yDif*yDif)\n val relSin = dist/xDif\n val alpha = Math.asin(relSin)\n \n distances(i-2) = (i, dist, alpha)\n db(i + \" -> \" + dist)\n }\n \n distances = distances.sortWith(_._2 < _._2)\n db(distances.mkString(\", \"))\n \n \n var secondInd = 1\n val alpha1 = distances(0)._3\n while (secondInd < distances.size && alpha1 == distances(secondInd)._3) {\n secondInd+= 1\n }\n \n println(1 + \" \" + distances(0)._1 + \" \" + distances(secondInd)._1)\n \n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n \n //---------------------------- service code ----------------------------------\n \n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n5\n0 0\n0 2\n2 0\n2 2\n1 1\n\"\"\"\n \nval sa2 = \"\"\"\n3\n-1000000000 -1000000000\n1000000000 1000000000\n1000000000 1000000000\n\"\"\"\n\n}\n\n}\n\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject CF2016_C { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n val stars = new Array[(Long, Long)](n+1)\n \n val ad = 1000000000\n for(i <- 1 to n) {\n val line = readLine()\n stars(i) = (line.long+ad, line.long+ad)\n }\n \n val x = stars(1)._1\n val y = stars(1)._2\n var distances = new Array[(Int, BigDecimal, BigDecimal)](n-1)\n for(i <- 2 to n) {\n val xDif = BigDecimal((x - stars(i)._1).abs)\n val yDif = BigDecimal((y - stars(i)._2).abs)\n \n val xSq = xDif*xDif\n val ySq = yDif*yDif\n val dist = (xSq + ySq)\n \n// val dist = Math.sqrt(xDif*xDif + yDif*yDif)\n// val xDifAbs = BigDecimal((x - stars(i)._1))\n// val relSin = (xDif*xDif)/dist * xDifAbs.signum\n val relSin = (xDif*xDif)/dist\n val alpha = relSin\n \n distances(i-2) = (i, dist, alpha)\n db(i + \" -> \" + dist)\n }\n \n distances = distances.sortWith(_._2 < _._2)\n db(distances.mkString(\", \"))\n\n var zerro = false\n def calcFun(s1:Int, s2:Int) :(BigDecimal, BigDecimal) = {\n if (stars(s2)._1 - stars(s1)._1 == 0) {\n zerro = true\n return (0,0)\n }\n val a = (BigDecimal(stars(s2)._2) - stars(s1)._2) / (stars(s2)._1 - stars(s1)._1)\n val b = (BigDecimal(stars(s1)._2)-ad) - a * (BigDecimal(stars(s1)._1) - ad)\n (a, b)\n }\n \n var secondInd = 1\n val alpha1 = distances(0)._3\n val coef = calcFun(1, 2)\n db(\"coef = \" + coef)\n// while (secondInd < distances.size && check(alpha1,distances(secondInd)._3)) {\n while (secondInd < distances.size && check(alpha1,distances(secondInd)._3) && \n (!zerro && \n belongs(coef._1, coef._2, distances(secondInd)._1))) {\n secondInd+= 1\n }\n \n def check(v1:BigDecimal, v2:BigDecimal) = {\n// val diff = (v1 - v2).abs\n// diff < 0.00000000001\n v1 == v2\n }\n \n\n \n def belongs(a:BigDecimal, b:BigDecimal, st:Int):Boolean = {\n val y = a*(stars(st)._1-ad) + b\n val diff = (y - (stars(st)._2-ad)).abs\n db(\"func diff \" + st + \" -> \" + diff)\n return diff < 0.000000001\n }\n \n// def area(a:BigDecimal, b:BigDecimal, c:BigDecimal) = {\n// s;\n// }\n \n def dist(v1:(Long,Long), v2:(Long,Long)) {\n val xDif = BigDecimal((v1._1 - v2._1).abs)\n val yDif = BigDecimal((v1._2 - v2._2).abs)\n val xSq = xDif*xDif\n val ySq = yDif*yDif\n val dist = (xSq + ySq)\n }\n \n println(1 + \" \" + distances(0)._1 + \" \" + distances(secondInd)._1)\n \n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n \n //---------------------------- service code ----------------------------------\n \n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n5\n0 0\n0 2\n2 0\n2 2\n1 1\n\"\"\"\n \nval sa2 = \"\"\"\n3\n-1000000000 -1000000000\n1000000000 1000000000\n1000000000 1000000000\n\"\"\"\n\nval t15 = \"\"\"\n10\n13303280 387243789\n30131431 723806809\n404775998 670757742\n-25996011 -398742031\n25599613 633170449\n38471092 890600029\n-33017802 -539177851\n-47620079 -831223391\n1425218 149682549\n-3745401 46270169\n\"\"\"\n \nval t49 = \"\"\"\n10\n999999999 1\n999999998 1\n999999997 1\n1000000000 1\n999999996 1\n999999995 1\n999999994 1\n999999992 1\n999999993 1\n0 0\n\"\"\"\n \nval t84 = \"\"\"\n3\n1 2\n2 1\n2 3\n\"\"\"\n}\n\n}\n\n"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs, ys = Array.ofDim[Long](n)\n for (i <- 0 until n) {\n val Array(x, y) = readLongs(2)\n xs(i) = x\n ys(i) = y\n }\n \n def sqr(x: Long) = x * x\n def dist(i: Int, j: Int) = sqr(xs(i - 1) - xs(j - 1)) + sqr(ys(i - 1) - ys(j - 1))\n \n def area(i: Int, j: Int, k: Int) = {\n val al = Math.sqrt(dist(i, j))\n val bl = Math.sqrt(dist(j, k))\n val cl = Math.sqrt(dist(i, k))\n val s = (al + bl + cl) / 2d\n Math.sqrt(s) * (s - al) * (s - bl) * (s - cl)\n }\n \n val a = 1\n var b = 2\n var ab = dist(a, b)\n for (i <- 3 to n) {\n val d2 = dist(a, i)\n if (d2 < ab) {\n b = i\n ab = d2\n }\n }\n\n var c = if (b == 2) 3 else 2\n var abc = area(a, b, c)\n\n for (i <- 2 to n) if (i != b) {\n val a2 = area(a, b, i)\n if (a2 > 0.0000001d && (a2 < abc || abc < 0.0000001d)) {\n c = i\n abc = a2\n }\n }\n\n println(s\"$a $b $c\")\n}\n"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs, ys = Array.ofDim[Long](n)\n for (i <- 0 until n) {\n val Array(x, y) = readLongs(2)\n xs(i) = x\n ys(i) = y\n }\n \n def sqr(x: Long) = x * x\n def dist(i: Int, j: Int) = sqr(xs(i - 1) - xs(j - 1)) + sqr(ys(i - 1) - ys(j - 1))\n \n def area(i: Int, j: Int, k: Int) = {\n val al = Math.sqrt(dist(i, j))\n val bl = Math.sqrt(dist(j, k))\n val cl = Math.sqrt(dist(i, k))\n val s = (al + bl + cl) / 2d\n Math.sqrt(s) * (s - al) * (s - bl) * (s - cl)\n }\n \n val a = 1\n var b = 2\n var ab = dist(a, b)\n for (i <- 3 to n) {\n val d2 = dist(a, i)\n if (d2 < ab) {\n b = i\n ab = d2\n }\n }\n\n var c = if (b == 2) 3 else 2\n var abc = area(a, b, c)\n\n for (i <- 2 to n) if (i != b) {\n val a2 = area(a, b, i)\n if (a2 > 0.5d && (a2 < abc || abc < 0.5d)) {\n c = i\n abc = a2\n }\n }\n\n println(s\"$a $b $c\")\n}\n"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs, ys = Array.ofDim[Long](n)\n for (i <- 0 until n) {\n val Array(x, y) = readLongs(2)\n xs(i) = x\n ys(i) = y\n }\n \n def sqr(x: Double) = x * x\n def dist(i: Int, j: Int) = sqr(xs(i - 1) - xs(j - 1)) + sqr(ys(i - 1) - ys(j - 1))\n \n case class Point(x: Long, y: Long)\n\n def direction(uv: (Point, Point), w: Point) =\n (uv._2.x - uv._1.x) * (w.y - uv._1.y) - (w.x - uv._1.x) * (uv._2.y - uv._1.y)\n \n def area(i: Int, j: Int, k: Int) = {\n val al = Math.sqrt(dist(i, j))\n val bl = Math.sqrt(dist(j, k))\n val cl = Math.sqrt(dist(i, k))\n val s = (al + bl + cl) / 2d\n Math.sqrt(s * (s - al) * (s - bl) * (s - cl))\n }\n \n val a = 1\n var b = 2\n var ab = dist(a, b)\n for (i <- 3 to n) {\n val d2 = dist(a, i)\n if (d2 < ab) {\n b = i\n ab = d2\n }\n }\n\n var c = if (b == 2) 3 else 2\n var abc = area(a, b, c)\n val pA = Point(xs(a - 1), ys(a - 1))\n val pB = Point(xs(b - 1), ys(b - 1))\n val pAB = pA -> pB\n\n for (i <- 2 to n) if (i != b && direction(pAB, Point(xs(i - 1), ys(i - 1))) != 0) {\n val a2 = area(a, b, i)\n if (a2 > 0.1d && (a2 < abc || abc < 0.1d)) {\n c = i\n abc = a2\n }\n }\n\n println(s\"$a $b $c\")\n}\n"}], "src_uid": "0d3ac2472990aba36abee156069b1088"} {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P298B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n\n // If the wind blows to the east, the boat will move to (x + 1, y).\n // If the wind blows to the south, the boat will move to (x, y - 1).\n // If the wind blows to the west, the boat will move to (x - 1, y).\n // If the wind blows to the north, the boat will move to (x, y + 1). \n \n def solve(): Int = {\n val T, sx, sy, ex, ey = sc.nextInt\n sc.nextLine\n val Winds = sc.nextLine.toList\n val N = (ey - sy) max 0\n val S = (sy - ey) max 0\n val E = (ex - sx) max 0\n val W = (sx - ex) max 0\n\n @tailrec\n def loop(n: Int, s: Int, e: Int, w: Int, ws: List[Char]): Int = {\n if (n >= N && s >= S && e >= E && w >= W) {\n T - ws.size\n }\n else {\n (ws: @unchecked) match {\n case Nil => -1\n case 'N' :: xs => loop(n + 1, s, e, w, xs)\n case 'S' :: xs => loop(n, s + 1, e, w, xs)\n case 'E' :: xs => loop(n, s, e + 1, w, xs)\n case 'W' :: xs => loop(n, s, e, w + 1, xs)\n }\n }\n }\n\n loop(0, 0, 0, 0, Winds)\n }\n\n out.println(solve)\n out.close\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject B {\n def main(args: Array[String]) {\n var scan = new Scanner(System.in)\n var t = scan.nextInt\n var sx = scan.nextInt\n var sy = scan.nextInt\n var ex = scan.nextInt\n var ey = scan.nextInt\n var dx = sx - ex\n var dy=sy-ey\n var s = scan.next\n var r=0\n if(dx==0 &&dy==0){\n println(r)\n return\n }\n for (c <- s) {\n if(c=='S' && dy>0)dy-=1\n if(c=='N' && dy<0)dy+=1\n if(c=='W' && dx>0)dx-=1\n if(c=='E' && dx<0)dx+=1\n r += 1\n if(dx==0 &&dy==0){\n println(r)\n return\n }\n \n }\n println(-1)\n }\n}\n"}, {"source_code": "object Main {\n val sdir: PartialFunction[Char, (Int, Int)] = { case 'S' => (0, -1) }\n val ndir: PartialFunction[Char, (Int, Int)] = { case 'N' => (0, 1) }\n val edir: PartialFunction[Char, (Int, Int)] = { case 'E' => ( 1, 0) }\n val wdir: PartialFunction[Char, (Int, Int)] = { case 'W' => (-1, 0) }\n val nop: PartialFunction[Char, (Int, Int)] = { case _ => (0, 0) } \n\n def main(args: Array[String]) {\n val op = readLine().split(\" \").map(_.toInt)\n val a = readLine()\n val dir = ((op(3) - op(1)).signum, (op(4) - op(2)).signum) match {\n case (1, 1) => edir orElse ndir orElse nop\n case (1, 0) => edir orElse nop\n case (1, -1) => edir orElse sdir orElse nop\n case (-1, 1) => wdir orElse ndir orElse nop\n case (-1, 0) => wdir orElse nop\n case (-1, -1) => wdir orElse sdir orElse nop\n case (0, 1) => ndir orElse nop\n case (0, 0) => nop\n case (0, -1) => sdir orElse nop\n }\n val r = a.scanLeft(op(1), op(2)) { (pos, c) => \n var nd = dir(c)\n (pos._1 + nd._1, pos._2 + nd._2)\n }\n val ho = r.zipWithIndex.find(_._1._1 == op(3)).map(_._2)\n val vo = r.zipWithIndex.find(_._1._2 == op(4)).map(_._2)\n (ho, vo) match {\n case (Some(h), Some(v)) => println(h.max(v))\n case _ => println(\"-1\")\n }\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(t, x1, y1, x2, y2) = in.next().split(' ').map(_.toLong)\n val (tr, xr, yr) = in.next().foldLeft((0l, x1, y1)) {\n case ((time, x, y), _) if x == x2 && y == y2 => (time, x, y)\n case ((time, x, y), 'N') if y < y2 => (time + 1, x, y + 1)\n case ((time, x, y), 'S') if y > y2 => (time + 1, x, y - 1)\n case ((time, x, y), 'W') if x > x2 => (time + 1, x - 1, y)\n case ((time, x, y), 'E') if x < x2 => (time + 1, x + 1, y)\n case ((time, x, y), _) => (time + 1, x, y)\n }\n if (xr == x2 && yr == y2)\n println(tr)\n else\n println(-1)\n\n}\n"}, {"source_code": "object Solution {\n\n def main(args: Array[String]) {\n val si = io.Source.stdin.getLines\n val Array(n, s1, s2, e1, e2) = si.next.split(' ').map(_.toInt)\n val w = si.next.toArray\n\n var v = e2 - s2\n var vd = 'N'\n if (v < 0) {\n vd = 'S'\n }\n\n v = math.abs(v)\n\n var h = e1 - s1\n var hd = 'E'\n if (h < 0) {\n hd = 'W'\n }\n\n h = math.abs(h)\n\n var sec = -1\n\n (0 to w.length - 1) foreach {i =>\n if(v != 0 && w(i) == vd) v -= 1\n else if (h != 0 && w(i) == hd) h -= 1\n\n if(h == 0 && v == 0 && sec == -1) {\n sec = i + 1\n }\n }\n\n if (sec > n) sec == -1\n\n println(sec)\n\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Sail {\n\n def mv(x:Int, d:Int):Int = if(x==0 || x.signum==d.signum)x else x+d\n val M = Map('E' -> (1,0), 'W'->(-1,0), 'S'->(0,-1), 'N'->(0,1))\n def solveDist(s:Iterator[Char], dx:Int, dy:Int, acc: Int):Int = {\n if (dx.abs + dy.abs == 0) acc\n else if (s.isEmpty) -1\n else {\n val t = M(s.next())\n solveDist(s,mv(dx,t._1), mv(dy,t._2), acc+1)\n }\n }\n def solve(s:Iterator[Char], sx:Int, sy:Int, ex:Int, ey:Int):Int = solveDist(s, sx-ex, sy-ey,0)\n\n def main(args: Array[String]) {\n val scan = new Scanner(System.in)\n scan.nextInt()\n val sx = scan.nextInt\n val sy = scan.nextInt\n val ex = scan.nextInt\n val ey = scan.nextInt\n val c = scan.next\n println(solve(c.iterator,sx,sy,ex,ey))\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(t, x1, y1, x2, y2) = in.next().split(' ').map(_.toInt)\n val (tr, xr, yr) = in.next().foldLeft((0, 0, 0)) {\n case ((time, x, y), _) if x == x2 && y == y2 => (time, x, y)\n case ((time, x, y), 'N') if y < y2 => (time + 1, x, y + 1)\n case ((time, x, y), 'S') if y > y2 => (time + 1, x, y - 1)\n case ((time, x, y), 'W') if x < x2 => (time + 1, x - 1, y)\n case ((time, x, y), 'E') if x < x2 => (time + 1, x + 1, y)\n case ((time, x, y), _) => (time + 1, x, y)\n }\n if (xr == x2 && yr == y2)\n println(tr)\n else\n println(-1)\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(t, x1, y1, x2, y2) = in.next().split(' ').map(_.toLong)\n val (tr, xr, yr) = in.next().foldLeft((0l, 0l, 0l)) {\n case ((time, x, y), _) if x == x2 && y == y2 => (time, x, y)\n case ((time, x, y), 'N') if y < y2 => (time + 1, x, y + 1)\n case ((time, x, y), 'S') if y > y2 => (time + 1, x, y - 1)\n case ((time, x, y), 'W') if x < x2 => (time + 1, x - 1, y)\n case ((time, x, y), 'E') if x < x2 => (time + 1, x + 1, y)\n case ((time, x, y), _) => (time + 1, x, y)\n }\n if (xr == x2 && yr == y2)\n println(tr)\n else\n println(-1)\n\n}\n"}, {"source_code": "object Solution {\n\n def main(args: Array[String]) {\n val si = io.Source.stdin.getLines\n val Array(n, s1, s2, e1, e2) = si.next.split(' ').map(_.toInt)\n val w = si.next.toArray\n\n var v = e2 - s2\n var vd = 'N'\n if (v < 0) {\n vd = 'S'\n }\n\n var h = e1 - s1\n var hd = 'E'\n if (h < 0) {\n hd = 'W'\n }\n\n var sec = -1\n\n (0 to w.length - 1) foreach {i =>\n if(v != 0 && w(i) == vd) v -= 1\n else if (h != 0 && w(i) == hd) h -= 1\n\n if(h == 0 && v == 0 && sec == -1) {\n sec = i + 1\n }\n }\n\n if (sec > n) sec == -1\n\n println(sec)\n\n }\n\n}\n"}, {"source_code": "object Solution {\n\n def main(args: Array[String]) {\n val si = io.Source.stdin.getLines\n val Array(n, s1, s2, e1, e2) = si.next.split(' ').map(_.toInt)\n val w = si.next.toArray\n\n var v = e2 - s2\n var vd = 'N'\n if (v < 0) {\n vd = 'S'\n }\n\n var h = e1 - s1\n var hd = 'E'\n if (h < 0) {\n hd = 'W'\n }\n\n var sec = -1\n\n (0 to w.length - 1) foreach {i =>\n if(w(i) == vd) v -= 1\n else if (w(i) == hd) h -= 1\n\n if(h == 0 && v == 0 && sec == -1) {\n sec = i + 1\n }\n }\n\n if (sec > n) sec == -1\n\n println(sec)\n\n }\n\n}\n"}, {"source_code": "object Main {\n val sdir: PartialFunction[Char, (Int, Int)] = { case 'S' => (0, -1) }\n val ndir: PartialFunction[Char, (Int, Int)] = { case 'N' => (0, 1) }\n val edir: PartialFunction[Char, (Int, Int)] = { case 'E' => ( 1, 0) }\n val wdir: PartialFunction[Char, (Int, Int)] = { case 'W' => (-1, 0) }\n val nop: PartialFunction[Char, (Int, Int)] = { case _ => (0, 0) } \n\n def main(args: Array[String]) {\n val op = readLine().split(\" \").map(_.toInt)\n val a = readLine()\n val dir = ((op(3) - op(1)).signum, (op(4) - op(2)).signum) match {\n case (1, 1) => ndir orElse edir orElse nop\n case (1, 0) => ndir orElse nop\n case (1, -1) => ndir orElse wdir orElse nop\n case (-1, 1) => sdir orElse edir orElse nop\n case (-1, 0) => sdir orElse nop\n case (-1, -1) => sdir orElse wdir orElse nop\n case (0, 1) => edir orElse nop\n case (0, 0) => nop\n case (0, -1) => wdir orElse nop\n }\n val r = a.scanLeft(op(1), op(2)) { (pos, c) => \n var nd = dir(c)\n (pos._1 + nd._1, pos._2 + nd._2)\n }\n val ho = r.zipWithIndex.find(_._1._1 == op(3)).map(_._2)\n val vo = r.zipWithIndex.find(_._1._2 == op(4)).map(_._2)\n (ho, vo) match {\n case (Some(h), Some(v)) => println(h.max(v))\n case _ => println(\"-1\")\n }\n }\n}"}], "src_uid": "aa31a2a1ad1575aee051ddee8642c53a"} {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _745B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n, m = read[Int]\n\n val row = Array.ofDim[Int](n)\n val col = Array.ofDim[Int](m)\n\n row.indices foreach {r =>\n val line = read[String]\n line.indices foreach {c =>\n if (line(c) == 'X') {\n row(r) += 1\n col(c) += 1\n }\n }\n }\n\n val rr = row.toSet - 0\n val cc = col.toSet - 0\n val ans = rr.size == 1 && cc.size == 1\n\n write(ans.toEnglish)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "import java.io._\nimport scala.io.Source\n\nimport scala.annotation.tailrec\n\nobject ProblemB {\n def main(args: Array[String]): Unit = processStdInOut()\n\n def processStdInOut(): Unit = {\n val src = Source.fromInputStream(System.in)\n processFromSource(src)\n }\n\n def processFromSource(src: Source): Unit = {\n try {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out));\n try {\n val lines = src.getLines()\n processLines(lines, bw)\n } finally {\n bw.flush()\n }\n } finally {\n src.close();\n }\n }\n\n // Standard code above, custom code below\n\n def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {\n val dims = lines.next().split(\" \").map(_.toInt)\n val rowCount = dims(0)\n val colCount = dims(1)\n val emptyRow = \".\" * colCount\n var nonEmptyRow: Option[String] = None\n var inRectangle = false\n\n def doesRowHaveHoles(row: String): Boolean = {\n val (start, afterStart) = row.partition(_ == '.')\n val (pieces, end) = afterStart.partition(_ != '.')\n end.exists(_ != '.')\n }\n\n def isNextRowValid(i: Int): Boolean = {\n val row = lines.next()\n val isRowEmpty = row.forall(_ == '.')\n nonEmptyRow match {\n // First row not found yet...\n case None if isRowEmpty => true // First row with parts of piece not found yet, so all fine\n case None => {\n nonEmptyRow = Some(row)\n inRectangle = true\n !doesRowHaveHoles(row) // Don't allow a row with holes\n }\n\n // In rectangle:\n case Some(rowPatternToMatch) if inRectangle => if (isRowEmpty) {\n inRectangle = false // an empty row means we are no longer in the rectangle\n true\n } else {\n row == rowPatternToMatch\n }\n\n // After rectangle:\n case _ => isRowEmpty // All rows after the rectangular piece must be empty\n }\n }\n\n val validRows = (0 until rowCount).map(isNextRowValid)\n val soln = validRows.forall(isValid => isValid)\n bw.write(if (soln) \"YES\" else \"NO\")\n bw.newLine()\n }\n}\n"}], "negative_code": [], "src_uid": "b395be2597f4cc0478bc45f774fa1c01"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readLong()\n val a = readLine().split(\" \").map(_.toInt).zipWithIndex.sortBy(_._1).map(_._2.toLong)\n \n val m = readLong();\n val r = readLine().split(\" \").map(_.toLong)\n val r1 = r.map(i => a(i.toInt - 1) + 1L).sum\n val r2 = (n + 1) * m - r1\n println(r1 + \" \" + r2)\n }\n}", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val index = Array.ofDim[Int](n)\n val data = in.next().split(' ').map(_.toInt)\n data.indices.foreach { i =>\n index(data(i) - 1) = i\n }\n val m = in.next().toInt\n val res = in.next().split(' ').map(_.toInt).foldLeft(0l, 0l) {\n case((left, right), i) =>\n (left + index(i - 1) + 1, right + n - index(i - 1))\n }\n\n println(s\"${res._1} ${res._2}\")\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt).zipWithIndex.sortBy(_._1).map(_._2)\n \n val m = readInt();\n val r = readLine().split(\" \").map(_.toInt)\n val r1 = r.map(i => a(i - 1) + 1).sum\n val r2 = (n + 1) * m - r1\n println(r1 + \" \" + r2)\n }\n}"}], "src_uid": "b7aef95015e326307521fd59d4fccb64"} {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, x) = in.next().split(\" \").map(_.toInt)\n val data = Range(0, n).map{ i =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt)\n (a, b)}.sorted\n println(data.foldLeft((1, 0)) {\n case((current_min, watched), (start, finish)) if finish < current_min =>\n (current_min, watched)\n case((current_min, watched), (start, finish)) =>\n val nStart = (start - current_min) / x * x\n (finish + 1, watched + (finish - current_min - nStart + 1))\n }._2)\n}", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _499A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val x = next.toInt\n val (l, r) = (1 to n).map(i => (next.toInt, next.toInt)).toArray.unzip\n\n def doit(i: Int, t: Int, acc: Int): Int = {\n if (i == n) acc\n else if (t < l(i)) {\n if (t + x <= l(i)) doit(i, t + x, acc)\n else doit(i, t + 1, acc + 1)\n } else doit(i + 1, r(i) + 1, acc + r(i) - l(i) + 1)\n }\n\n println(doit(0, 1, 0))\n}\n"}, {"source_code": "object A499 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = readInts(2)\n val in = Array.fill(n)(readInts(2)).map(arr => (arr(0), arr(1)))\n var curr = 1\n var res = 0\n for(i <- in.indices) {\n if(in(i)._1 >= curr + x) {\n res += (in(i)._1 - curr) % x\n } else {\n res += (in(i)._1 - curr)\n }\n res += in(i)._2 - in(i)._1 + 1\n curr = in(i)._2 + 1\n\n //dlksj\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject A extends App {\n def readPair() = {\n val a = StdIn.readLine() split \" \" map { _.toInt }\n (a(0), a(1))\n }\n\n val (n, x) = readPair()\n\n var res = 0\n var c = 1\n for (i <- 1 to n) {\n val (l, r) = readPair()\n\n res = res + (l - c) % x + (r - l) + 1\n c = r + 1\n }\n\n Console.println(res)\n}\n"}, {"source_code": "object Main extends App {\n\n val Array(n, x) = readLine.split(\" \").map(_.toInt)\n val init = (1, 0)\n val (_, total) = (1 to n).foldLeft(init) {\n case ((cursor, total), _) =>\n val Array(from, to) = readLine.split(\" \").map(_.toInt)\n (to+1, total + 1 + (to-from) + ((from-cursor) % x))\n }\n println(total)\n\n}"}, {"source_code": "import java.io._\n\nobject Problem499A extends App {\n val problem = new Problem499A(\n new InputStreamReader(System.in),\n new OutputStreamWriter(System.out)\n )\n\n problem.run()\n}\n\nclass Problem499A(input: Reader, output: Writer) {\n private val tokenizer = new StreamTokenizer(new BufferedReader(input))\n\n private var currentMinute = 1\n private var rewindSize = 0\n private var seenMinutes: Int = 0\n\n def run(): Unit = {\n tokenizer.eolIsSignificant(true)\n\n var n = readInt()\n rewindSize = readInt()\n tokenizer.nextToken() // Next line\n\n while (n > 0) {\n readBestMoments()\n\n n -= 1\n }\n\n output.write(seenMinutes.toString)\n output.flush()\n }\n\n private def readBestMoments(): Unit = {\n val start = readInt()\n val end = readInt()\n tokenizer.nextToken()\n\n val minutesToStart = start - currentMinute\n seenMinutes += minutesToStart % rewindSize + (end - start + 1)\n\n currentMinute = end + 1\n }\n\n private def readInt(): Int = {\n if (tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {\n throw new RuntimeException(\"Integer expected\")\n }\n\n tokenizer.nval.toInt\n }\n}"}], "negative_code": [{"source_code": "import java.io._\n\nobject Problem499A extends App {\n val problem = new Problem499A(\n new InputStreamReader(System.in),\n new OutputStreamWriter(System.out)\n )\n\n problem.run()\n}\n\nclass Problem499A(input: Reader, output: Writer) {\n private val tokenizer = new StreamTokenizer(new BufferedReader(input))\n\n private var currentMinute = 1\n private var rewindSize = 0\n private var seenMinutes: Int = 0\n\n def run(): Unit = {\n tokenizer.eolIsSignificant(true)\n\n var n = readInt()\n rewindSize = readInt()\n tokenizer.nextToken() // Next line\n\n while (n > 0) {\n readBestMoments()\n\n n -= 1\n }\n\n output.write(seenMinutes.toString)\n }\n\n private def readBestMoments(): Unit = {\n val start = readInt()\n val end = readInt()\n tokenizer.nextToken()\n\n val minutesToStart = start - currentMinute\n seenMinutes += minutesToStart % rewindSize + (end - start + 1)\n\n currentMinute = end + 1\n }\n\n private def readInt(): Int = {\n if (tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {\n throw new RuntimeException(\"Integer expected\")\n }\n\n tokenizer.nval.toInt\n }\n}"}], "src_uid": "ac33b73da5aaf2139b348a9c237f93a4"} {"source_code": "import scala.io.StdIn.readLine\n\nobject A {\n\n def solution(a: Seq[Int], k: Int): Boolean = {\n val cc = a.count(_ % 2 == 0)\n if (cc == a.length)\n false\n else if (cc == 0)\n k % 2 != 0\n else\n k < a.length || (a.length - cc) % 2 == 1\n }\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val Seq(_, k) = readLine.split(\" \").toSeq.map(_.toInt)\n val a = readLine.split(\" \").toSeq.map(_.toInt)\n println(if (solution(a, k)) \"Yes\" else \"No\")\n }\n }\n}", "positive_code": [{"source_code": "//package codeforces.contests._1363\n\nobject OddSelection {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(n, x) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val odds = io.StdIn.readLine.split(\" \").map(_.toInt).count(_ % 2 == 1)\n val evens = n - odds\n\n if (evens == 0) {\n println(if (x % 2 == 1) \"Yes\" else \"No\")\n } else {\n val requested = { // 5 then need 5 odds, if 6 then need 7 odds, if evens == 0\n val r = (x - evens) max 0\n r + (if (r % 2 == 0) 1 else 0)\n }\n\n val available = requested <= odds\n\n println(if (available) \"Yes\" else \"No\")\n }\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nx = readIntLine()\n val arr = readIntLine()\n val ans = can(arr, nx.last)\n println(if (ans) \"Yes\" else \"No\")\n }\n // println(calcWays(4, 5))\n }\n\n def can(list: List[Int], x: Int) = {\n (1 to (x + 1) / 2).exists(i => list.count(_ % 2 == 1) >= 2 * i - 1 && list.count(_ % 2 == 0) >= x - 2 * i + 1)\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CF646(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CF646(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val T = ni()\n REP(T) { _ =>\n val n = ni()\n val x = ni()\n val a = na(n)\n\n var cntO = 0\n var cntE = 0\n \n REP(n) { i =>\n if(a(i) % 2 == 0) cntE += 1\n else cntO += 1\n }\n\n if(cntE >= x && cntO > 0) {\n out.println(\"Yes\")\n } else if(cntO > 0) {\n val rm = x - cntE\n if(rm % 2 != 0 && cntO >= rm) out.println(\"Yes\")\n else if(cntE > 0 && cntO >= rm + 1) out.println(\"Yes\")\n else out.println(\"No\")\n } else out.println(\"No\")\n }\n }\n}\n"}, {"source_code": "object _1363A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val n, x = io.read[Int]\n val xs = io.read[List, Int](n)\n val evens = xs.count(_%2 == 0)\n val odds = n - evens\n val ans = (1 to odds by 2).exists(o => (x - o) >= 0 && (x - o) <= evens)\n io.write(ans.toEnglish)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n val charToInt: Char => Int = Character.getNumericValue\n val intToChar: Int => Char = Character.forDigit(_, 10)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1363\n\nobject OddSelection {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(n, x) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val odds = io.StdIn.readLine.split(\" \").map(_.toInt).count(_ % 2 == 1)\n val evens = n - odds\n\n val requested = { // 5 then need 5 odds, if 6 then need 7 odds\n val r = (x - evens) max 0\n r + (if (r % 2 == 0) 1 else 0)\n }\n\n val available = requested <= odds\n\n println(if (available) \"Yes\" else \"No\")\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nx = readIntLine()\n val arr = readIntLine()\n val ans = can(arr, nx.last)\n println(if (ans) \"Yes\" else \"No\")\n }\n // println(calcWays(4, 5))\n }\n \n def can(list: List[Int], x: Int) = {\n (1 to (x + 1) / 2).exists(i => list.count(_ % 2 == 1) >= 2 * i + 1 && list.count(_ % 2 == 0) >= x - 2 * i - 1)\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CF646(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CF646(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val T = ni()\n REP(T) { _ =>\n val n = ni()\n val x = ni()\n val a = na(n)\n\n var cntO = 0\n var cntE = 0\n\n a.foreach { f =>\n if(f%2 == 0) cntE += 1\n else cntO += 1\n }\n\n if(cntO % 2 != 0) {\n out.println(\"Yes\")\n } else {\n if(cntO > 0) {\n if(cntO + cntE - 1 >= x) {\n out.println(\"Yes\")\n } else out.println(\"No\")\n } else out.println(\"No\")\n }\n }\n }\n}\n"}], "src_uid": "afce38aa7065da88d824d1d981b5b338"} {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = { val tl = tokenizeLine;Array.fill(n)(tl.nextToken.toInt) }\n\n final case class AB(a: Int, b: Int)\n\n val Array(n) = readInts(1)\n val m = n / 2\n\n val adjBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val res = Array.fill(n) {\n 0\n }\n val sizeFrom = Array.tabulate(n) { i => Array.ofDim[Int](adjs(i).length) }\n val maxSubtreeSizeFrom = Array.tabulate(n) { i => Array.fill(adjs(i).length) {\n 0\n }\n }\n\n def dfs1(u: Int, parent: Int): AB = {\n\n var i = 0\n var childrenSize = 1\n var parentPos = -1\n var maxSubtreeSize = 0\n\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (adjs(u)(i) == parent) parentPos = i\n else {\n val ab = dfs1(v, u)\n childrenSize += ab.a\n sizeFrom(u)(i) = ab.a\n if (ab.b <= m && ab.b > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = ab.b\n if (ab.a <= m && ab.a > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = ab.a\n if (ab.b <= m && ab.b > maxSubtreeSize) maxSubtreeSize = ab.b\n if (ab.a <= m && ab.a > maxSubtreeSize) maxSubtreeSize = ab.a\n }\n i += 1\n }\n\n if (parentPos >= 0) {\n sizeFrom(u)(parentPos) = n - childrenSize\n if (n - childrenSize <= m && n - childrenSize > maxSubtreeSizeFrom(u)(parentPos)) maxSubtreeSizeFrom(u)(parentPos) = n - childrenSize\n }\n\n AB(childrenSize, maxSubtreeSize)\n }\n\n dfs1(0, -1)\n\n val maxSubtreeSize2a = Array.tabulate(n) { u =>\n val maxWithInd = Array.tabulate(adjs(u).size) { i => AB(maxSubtreeSizeFrom(u)(i), adjs(u)(i)) }\n maxWithInd.sortBy(-_.a).take(2)\n }\n\n def find(arr: Array[AB], v: Int): Int = {\n if (arr.length > 0 && arr(0).b != v) arr(0).a\n else if (arr.length > 1 && arr(1).b != v) arr(1).a\n else -1\n }\n\n def dfs2(u: Int, parent: Int, parentMaxSubtreeSize: Int): Unit = {\n\n var i = 0\n while (i < adjs(u).length) {\n if (adjs(u)(i) == parent) {\n if (parentMaxSubtreeSize <= m && parentMaxSubtreeSize > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = parentMaxSubtreeSize\n }\n i += 1\n }\n\n i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v != parent) {\n val sub = find(maxSubtreeSize2a(u), v)\n dfs2(v, u, Math.max(sub, parentMaxSubtreeSize))\n }\n i += 1\n }\n }\n\n dfs2(0, -1, 0)\n\n val maxSubtreeSize2 = Array.tabulate(n) { u =>\n val maxWithInd = Array.tabulate(adjs(u).size) { i => AB(maxSubtreeSizeFrom(u)(i), adjs(u)(i)) }\n maxWithInd.sortBy(-_.a).take(2)\n }\n\n for (u <- 0 until n) {\n var ok = true\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n if (sizeFrom(u)(i) > m) {\n val sub = find(maxSubtreeSize2(v), u)\n if (sub == -1 || sizeFrom(u)(i) - sub > m) ok = false\n }\n }\n res(u) = if (ok) 1 else 0\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n val task = new Runnable {\n\n override def run(): Unit = {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n final case class AB(a: Int, b: Int)\n\n val Array(n) = readInts(1)\n val m = n / 2\n\n val adjBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val res = Array.fill(n) {\n 0\n }\n val sizeFrom = Array.tabulate(n) { i => Array.ofDim[Int](adjs(i).length) }\n val maxSubtreeSizeFrom = Array.tabulate(n) { i => Array.fill(adjs(i).length) {\n 0\n }\n }\n\n def dfs1(u: Int, parent: Int): AB = {\n\n var i = 0\n var childrenSize = 1\n var parentPos = -1\n var maxSubtreeSize = 0\n\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (adjs(u)(i) == parent) parentPos = i\n else {\n val ab = dfs1(v, u)\n childrenSize += ab.a\n sizeFrom(u)(i) = ab.a\n if (ab.b <= m && ab.b > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = ab.b\n if (ab.a <= m && ab.a > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = ab.a\n if (ab.b <= m && ab.b > maxSubtreeSize) maxSubtreeSize = ab.b\n if (ab.a <= m && ab.a > maxSubtreeSize) maxSubtreeSize = ab.a\n }\n i += 1\n }\n\n if (parentPos >= 0) {\n sizeFrom(u)(parentPos) = n - childrenSize\n if (n - childrenSize <= m && n - childrenSize > maxSubtreeSizeFrom(u)(parentPos)) maxSubtreeSizeFrom(u)(parentPos) = n - childrenSize\n }\n\n AB(childrenSize, maxSubtreeSize)\n }\n\n dfs1(0, -1)\n\n val maxSubtreeSize2a = Array.tabulate(n) { u =>\n val maxWithInd = Array.tabulate(adjs(u).size) { i => AB(maxSubtreeSizeFrom(u)(i), adjs(u)(i)) }\n maxWithInd.sortBy(-_.a).take(2)\n }\n\n def find(arr: Array[AB], v: Int): Option[Int] = {\n if (arr.size > 0 && arr(0).b != v) Some(arr(0).a)\n else if (arr.size > 1 && arr(1).b != v) Some(arr(1).a)\n else None\n }\n\n def dfs2(u: Int, parent: Int, parentMaxSubtreeSize: Int): Unit = {\n\n var i = 0\n while (i < adjs(u).length) {\n if (adjs(u)(i) == parent) {\n if (parentMaxSubtreeSize <= m && parentMaxSubtreeSize > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = parentMaxSubtreeSize\n }\n i += 1\n }\n\n i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v != parent) {\n val sub = find(maxSubtreeSize2a(u), v)\n dfs2(v, u, sub.map(Math.max(_, parentMaxSubtreeSize)).getOrElse(parentMaxSubtreeSize))\n }\n i += 1\n }\n }\n\n dfs2(0, -1, 0)\n\n val maxSubtreeSize2 = Array.tabulate(n) { u =>\n val maxWithInd = Array.tabulate(adjs(u).size) { i => AB(maxSubtreeSizeFrom(u)(i), adjs(u)(i)) }\n maxWithInd.sortBy(-_.a).take(2)\n }\n\n for (u <- 0 until n) {\n var ok = true\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n if (sizeFrom(u)(i) > m) {\n val sub = find(maxSubtreeSize2(v), u)\n if (sub == None || sizeFrom(u)(i) - sub.get > m) ok = false\n }\n }\n res(u) = if (ok) 1 else 0\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n }\n }\n\n new Thread(null, task, \"1\", 80000000).start()\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n val task = new Runnable {\n\n override def run(): Unit = {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n final case class AB(a: Int, b: Int)\n\n val Array(n) = readInts(1)\n val m = n / 2\n\n val adjBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val res = Array.fill(n) {\n 0\n }\n val sizeFrom = Array.tabulate(n) { i => Array.ofDim[Int](adjs(i).length) }\n val maxSubtreeSizeFrom = Array.tabulate(n) { i => Array.fill(adjs(i).length) {\n 0\n }\n }\n\n def dfs1(u: Int, parent: Int): AB = {\n\n var i = 0\n var childrenSize = 1\n var parentPos = -1\n var maxSubtreeSize = 0\n\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (adjs(u)(i) == parent) parentPos = i\n else {\n val ab = dfs1(v, u)\n childrenSize += ab.a\n sizeFrom(u)(i) = ab.a\n if (ab.b <= m && ab.b > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = ab.b\n if (ab.a <= m && ab.a > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = ab.a\n if (ab.b <= m && ab.b > maxSubtreeSize) maxSubtreeSize = ab.b\n if (ab.a <= m && ab.a > maxSubtreeSize) maxSubtreeSize = ab.a\n }\n i += 1\n }\n\n if (parentPos >= 0) {\n sizeFrom(u)(parentPos) = n - childrenSize\n if (n - childrenSize <= m && n - childrenSize > maxSubtreeSizeFrom(u)(parentPos)) maxSubtreeSizeFrom(u)(parentPos) = n - childrenSize\n }\n\n AB(childrenSize, maxSubtreeSize)\n }\n\n dfs1(0, -1)\n\n val maxSubtreeSize2a = Array.tabulate(n) { u =>\n val maxWithInd = Array.tabulate(adjs(u).size) { i => AB(maxSubtreeSizeFrom(u)(i), adjs(u)(i)) }\n maxWithInd.sortBy(-_.a).take(2)\n }\n\n def find(arr: Array[AB], v: Int): Int = {\n if (arr.length > 0 && arr(0).b != v) arr(0).a\n else if (arr.length > 1 && arr(1).b != v) arr(1).a\n else -1\n }\n\n def dfs2(u: Int, parent: Int, parentMaxSubtreeSize: Int): Unit = {\n\n var i = 0\n while (i < adjs(u).length) {\n if (adjs(u)(i) == parent) {\n if (parentMaxSubtreeSize <= m && parentMaxSubtreeSize > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = parentMaxSubtreeSize\n }\n i += 1\n }\n\n i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v != parent) {\n val sub = find(maxSubtreeSize2a(u), v)\n dfs2(v, u, Math.max(sub, parentMaxSubtreeSize))\n }\n i += 1\n }\n }\n\n dfs2(0, -1, 0)\n\n val maxSubtreeSize2 = Array.tabulate(n) { u =>\n val maxWithInd = Array.tabulate(adjs(u).size) { i => AB(maxSubtreeSizeFrom(u)(i), adjs(u)(i)) }\n maxWithInd.sortBy(-_.a).take(2)\n }\n\n for (u <- 0 until n) {\n var ok = true\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n if (sizeFrom(u)(i) > m) {\n val sub = find(maxSubtreeSize2(v), u)\n if (sub == -1 || sizeFrom(u)(i) - sub > m) ok = false\n }\n }\n res(u) = if (ok) 1 else 0\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n }\n }\n\n new Thread(null, task, \"1\", 80000000).start()\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n val task = new Runnable {\n\n override def run(): Unit = {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n final case class AB(a: Int, b: Int)\n\n val Array(n) = readInts(1)\n val m = n / 2\n\n val adjBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val res = Array.fill(n) {\n 0\n }\n val sizeFrom = Array.tabulate(n) { i => Array.ofDim[Int](adjs(i).length) }\n val maxSubtreeSizeFrom = Array.tabulate(n) { i => Array.fill(adjs(i).length) {\n 0\n }\n }\n\n def dfs1(u: Int, parent: Int): AB = {\n\n var i = 0\n var childrenSize = 1\n var parentPos = -1\n var maxSubtreeSize = 0\n\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (adjs(u)(i) == parent) parentPos = i\n else {\n val ab = dfs1(v, u)\n childrenSize += ab.a\n sizeFrom(u)(i) = ab.a\n if (ab.b <= m && ab.b > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = ab.b\n if (ab.a <= m && ab.a > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = ab.a\n if (ab.b <= m && ab.b > maxSubtreeSize) maxSubtreeSize = ab.b\n if (ab.a <= m && ab.a > maxSubtreeSize) maxSubtreeSize = ab.a\n }\n i += 1\n }\n\n if (parentPos >= 0) {\n sizeFrom(u)(parentPos) = n - childrenSize\n if (n - childrenSize <= m && n - childrenSize > maxSubtreeSizeFrom(u)(parentPos)) maxSubtreeSizeFrom(u)(parentPos) = n - childrenSize\n }\n\n AB(childrenSize, maxSubtreeSize)\n }\n\n dfs1(0, -1)\n\n val maxSubtreeSize2a = Array.tabulate(n) { u =>\n val maxWithInd = Array.tabulate(adjs(u).size) { i => AB(maxSubtreeSizeFrom(u)(i), adjs(u)(i)) }\n maxWithInd.sortBy(-_.a).take(2)\n }\n\n def find(arr: Array[AB], v: Int): Option[Int] = {\n if (arr.length > 0 && arr(0).b != v) Some(arr(0).a)\n else if (arr.length > 1 && arr(1).b != v) Some(arr(1).a)\n else None\n }\n\n def dfs2(u: Int, parent: Int, parentMaxSubtreeSize: Int): Unit = {\n\n var i = 0\n while (i < adjs(u).length) {\n if (adjs(u)(i) == parent) {\n if (parentMaxSubtreeSize <= m && parentMaxSubtreeSize > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = parentMaxSubtreeSize\n }\n i += 1\n }\n\n i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v != parent) {\n val sub = find(maxSubtreeSize2a(u), v)\n dfs2(v, u, sub.map(Math.max(_, parentMaxSubtreeSize)).getOrElse(parentMaxSubtreeSize))\n }\n i += 1\n }\n }\n\n dfs2(0, -1, 0)\n\n val maxSubtreeSize2 = Array.tabulate(n) { u =>\n val maxWithInd = Array.tabulate(adjs(u).size) { i => AB(maxSubtreeSizeFrom(u)(i), adjs(u)(i)) }\n maxWithInd.sortBy(-_.a).take(2)\n }\n\n for (u <- 0 until n) {\n var ok = true\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n if (sizeFrom(u)(i) > m) {\n val sub = find(maxSubtreeSize2(v), u)\n if (sub == None || sizeFrom(u)(i) - sub.get > m) ok = false\n }\n }\n res(u) = if (ok) 1 else 0\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n }\n }\n\n new Thread(null, task, \"1\", 80000000).start()\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n val task = new Runnable {\n\n override def run(): Unit = {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n final case class AB(a: Int, b: Int)\n\n val Array(n) = readInts(1)\n val m = n / 2\n\n val adjBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val res = Array.fill(n) {\n 0\n }\n val sizeFrom = Array.tabulate(n) { i => Array.ofDim[Int](adjs(i).length) }\n val maxSubtreeSizeFrom = Array.tabulate(n) { i => Array.fill(adjs(i).length) {\n 0\n }\n }\n\n def dfs1(u: Int, parent: Int): AB = {\n\n var i = 0\n var childrenSize = 1\n var parentPos = -1\n var maxSubtreeSize = 0\n\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (adjs(u)(i) == parent) parentPos = i\n else {\n val ab = dfs1(v, u)\n childrenSize += ab.a\n sizeFrom(u)(i) = ab.a\n if (ab.b <= m && ab.b > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = ab.b\n if (ab.a <= m && ab.a > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = ab.a\n if (ab.b <= m && ab.b > maxSubtreeSize) maxSubtreeSize = ab.b\n if (ab.a <= m && ab.a > maxSubtreeSize) maxSubtreeSize = ab.a\n }\n i += 1\n }\n\n if (parentPos >= 0) {\n sizeFrom(u)(parentPos) = n - childrenSize\n if (n - childrenSize <= m && n - childrenSize > maxSubtreeSizeFrom(u)(parentPos)) maxSubtreeSizeFrom(u)(parentPos) = n - childrenSize\n }\n\n AB(childrenSize, maxSubtreeSize)\n }\n\n dfs1(0, -1)\n\n val maxSubtreeSize2a = Array.tabulate(n) { u =>\n val maxWithInd = Array.tabulate(adjs(u).size) { i => AB(maxSubtreeSizeFrom(u)(i), adjs(u)(i)) }\n maxWithInd.sortBy(-_.a).take(2)\n }\n\n def find(arr: Array[AB], v: Int): Int = {\n if (arr.length > 0 && arr(0).b != v) arr(0).a\n else if (arr.length > 1 && arr(1).b != v) arr(1).a\n else -1\n }\n\n def dfs2(u: Int, parent: Int, parentMaxSubtreeSize: Int): Unit = {\n\n var i = 0\n while (i < adjs(u).length) {\n if (adjs(u)(i) == parent) {\n if (parentMaxSubtreeSize <= m && parentMaxSubtreeSize > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = parentMaxSubtreeSize\n }\n i += 1\n }\n\n i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v != parent) {\n val sub = find(maxSubtreeSize2a(u), v)\n dfs2(v, u, Math.max(sub, parentMaxSubtreeSize))\n }\n i += 1\n }\n }\n\n dfs2(0, -1, 0)\n\n val maxSubtreeSize2 = Array.tabulate(n) { u =>\n val maxWithInd = Array.tabulate(adjs(u).size) { i => AB(maxSubtreeSizeFrom(u)(i), adjs(u)(i)) }\n maxWithInd.sortBy(-_.a).take(2)\n }\n\n for (u <- 0 until n) {\n var ok = true\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n if (sizeFrom(u)(i) > m) {\n val sub = find(maxSubtreeSize2(v), u)\n if (sub == -1 || sizeFrom(u)(i) - sub > m) ok = false\n }\n }\n res(u) = if (ok) 1 else 0\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n }\n }\n\n new Thread(null, task, \"1\", 64000000).start()\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n val task = new Runnable {\n\n override def run(): Unit = {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n final case class AB(a: Int, b: Int)\n\n val Array(n) = readInts(1)\n val m = n / 2\n\n val adjBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val res = Array.fill(n) {\n 0\n }\n val sizeFrom = Array.tabulate(n) { i => Array.ofDim[Int](adjs(i).length) }\n val maxSubtreeSizeFrom = Array.tabulate(n) { i => Array.fill(adjs(i).length) {\n 0\n }\n }\n\n def dfs1(u: Int, parent: Int): AB = {\n\n var i = 0\n var childrenSize = 1\n var parentPos = -1\n var maxSubtreeSize = 0\n\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (adjs(u)(i) == parent) parentPos = i\n else {\n val ab = dfs1(v, u)\n childrenSize += ab.a\n sizeFrom(u)(i) = ab.a\n if (ab.b <= m && ab.b > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = ab.b\n if (ab.a <= m && ab.a > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = ab.a\n if (ab.b <= m && ab.b > maxSubtreeSize) maxSubtreeSize = ab.b\n if (ab.a <= m && ab.a > maxSubtreeSize) maxSubtreeSize = ab.a\n }\n i += 1\n }\n\n if (parentPos >= 0) {\n sizeFrom(u)(parentPos) = n - childrenSize\n if (n - childrenSize <= m && n - childrenSize > maxSubtreeSizeFrom(u)(parentPos)) maxSubtreeSizeFrom(u)(parentPos) = n - childrenSize\n }\n\n AB(childrenSize, maxSubtreeSize)\n }\n\n dfs1(0, -1)\n\n val maxSubtreeSize2a = Array.tabulate(n) { u =>\n val maxWithInd = Array.tabulate(adjs(u).size) { i => AB(maxSubtreeSizeFrom(u)(i), adjs(u)(i)) }\n maxWithInd.sortBy(-_.a).take(2)\n }\n\n def find(arr: Array[AB], v: Int): Option[Int] = {\n if (arr.length > 0 && arr(0).b != v) Some(arr(0).a)\n else if (arr.length > 1 && arr(1).b != v) Some(arr(1).a)\n else None\n }\n\n def dfs2(u: Int, parent: Int, parentMaxSubtreeSize: Int): Unit = {\n\n var i = 0\n while (i < adjs(u).length) {\n if (adjs(u)(i) == parent) {\n if (parentMaxSubtreeSize <= m && parentMaxSubtreeSize > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = parentMaxSubtreeSize\n }\n i += 1\n }\n\n i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v != parent) {\n val sub = find(maxSubtreeSize2a(u), v)\n dfs2(v, u, sub.map(Math.max(_, parentMaxSubtreeSize)).getOrElse(parentMaxSubtreeSize))\n }\n i += 1\n }\n }\n\n dfs2(0, -1, 0)\n\n val maxSubtreeSize2 = Array.tabulate(n) { u =>\n val maxWithInd = Array.tabulate(adjs(u).size) { i => AB(maxSubtreeSizeFrom(u)(i), adjs(u)(i)) }\n maxWithInd.sortBy(-_.a).take(2)\n }\n\n for (u <- 0 until n) {\n var ok = true\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n if (sizeFrom(u)(i) > m) {\n val sub = find(maxSubtreeSize2(v), u)\n if (sub == None || sizeFrom(u)(i) - sub.get > m) ok = false\n }\n }\n res(u) = if (ok) 1 else 0\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n }\n }\n\n new Thread(null, task, \"1\", 80000000).start()\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n val task = new Runnable {\n\n override def run(): Unit = {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n final case class AB(a: Int, b: Int)\n\n val Array(n) = readInts(1)\n val m = n / 2\n\n val adjBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val res = Array.fill(n) {\n 0\n }\n val sizeFrom = Array.tabulate(n) { i => Array.ofDim[Int](adjs(i).length) }\n val maxSubtreeSizeFrom = Array.tabulate(n) { i => Array.fill(adjs(i).length) {\n 0\n }\n }\n\n def dfs1(u: Int, parent: Int): AB = {\n\n var i = 0\n var childrenSize = 1\n var parentPos = -1\n var maxSubtreeSize = 0\n\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (adjs(u)(i) == parent) parentPos = i\n else {\n val ab = dfs1(v, u)\n childrenSize += ab.a\n sizeFrom(u)(i) = ab.a\n if (ab.b <= m && ab.b > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = ab.b\n if (ab.a <= m && ab.a > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = ab.a\n if (ab.b <= m && ab.b > maxSubtreeSize) maxSubtreeSize = ab.b\n if (ab.a <= m && ab.a > maxSubtreeSize) maxSubtreeSize = ab.a\n }\n i += 1\n }\n\n if (parentPos >= 0) {\n sizeFrom(u)(parentPos) = n - childrenSize\n if (n - childrenSize <= m && n - childrenSize > maxSubtreeSizeFrom(u)(parentPos)) maxSubtreeSizeFrom(u)(parentPos) = n - childrenSize\n }\n\n AB(childrenSize, maxSubtreeSize)\n }\n\n dfs1(0, -1)\n\n val maxSubtreeSize2a = for (u <- 0 until n) yield {\n val maxWithInd = for (i <- adjs(u).indices) yield AB(maxSubtreeSizeFrom(u)(i), adjs(u)(i))\n maxWithInd.sortBy(-_.a).take(2)\n }\n\n def find(u: Int, v: Int): Option[Int] = {\n if (maxSubtreeSize2a(u).size > 0 && maxSubtreeSize2a(u)(0).b != v) Some(maxSubtreeSize2a(u)(0).a)\n else if (maxSubtreeSize2a(u).size > 1 && maxSubtreeSize2a(u)(1).b != v) Some(maxSubtreeSize2a(u)(1).a)\n else None\n }\n\n def dfs2(u: Int, parent: Int, parentMaxSubtreeSize: Int): Unit = {\n\n var i = 0\n while (i < adjs(u).length) {\n if (adjs(u)(i) == parent) {\n if (parentMaxSubtreeSize <= m && parentMaxSubtreeSize > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = parentMaxSubtreeSize\n }\n i += 1\n }\n\n i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v != parent) {\n val sub = find(u, v)\n dfs2(v, u, sub.map(Math.max(_, parentMaxSubtreeSize)).getOrElse(parentMaxSubtreeSize))\n }\n i += 1\n }\n }\n\n dfs2(0, -1, 0)\n\n val maxSubtreeSize2 = for (u <- 0 until n) yield {\n val maxWithInd = for (i <- adjs(u).indices) yield AB(maxSubtreeSizeFrom(u)(i), adjs(u)(i))\n maxWithInd.sortBy(-_.a).take(2)\n }\n\n for (u <- 0 until n) {\n var ok = true\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n if (sizeFrom(u)(i) > m) {\n val sub = find(v, u)\n if (sub == None || sizeFrom(u)(i) - sub.get > m) ok = false\n }\n }\n res(u) = if (ok) 1 else 0\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n }\n }\n\n new Thread(null, task, \"1\", 80000000).start()\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val m = n / 2\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val res = Array.fill(n){ 0 }\n val sizeFrom = Array.tabulate(n) { i => Array.ofDim[Int](adjs(i).length)}\n val maxSubtreeSizeFrom = Array.tabulate(n) { i => Array.fill(adjs(i).length) { 0 } }\n var last = 0\n var maxDepth = -1\n\n def dfs(u: Int, parent: Int, size: Int, depth: Int): (Int, Int) = {\n\n if (depth > maxDepth) {\n last = u\n maxDepth = depth\n }\n\n var i = 0\n var childrenSize = 1\n var parentPos = -1\n var maxSubtreeSize = 0\n\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v == parent) {\n parentPos = i\n } else {\n val (vSubtreeSize, vMaxSubtreeSize) = dfs(v, u, size + 1, depth + 1)\n childrenSize += vSubtreeSize\n sizeFrom(u)(i) = vSubtreeSize\n if (vMaxSubtreeSize <= m && vMaxSubtreeSize > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = vMaxSubtreeSize\n if (vSubtreeSize <= m && vSubtreeSize > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = vSubtreeSize\n if (vMaxSubtreeSize <= m && vMaxSubtreeSize > maxSubtreeSize) maxSubtreeSize = vMaxSubtreeSize\n if (vSubtreeSize <= m && vSubtreeSize > maxSubtreeSize) maxSubtreeSize = vSubtreeSize\n }\n i += 1\n }\n if (parentPos >= 0) {\n sizeFrom(u)(parentPos) = n - childrenSize\n }\n (childrenSize, maxSubtreeSize)\n }\n\n dfs(0, -1, 0, 0)\n dfs(last, -1, 0, 0)\n\n val maxSubtreeSize2 = for (u <- 0 until n) yield {\n val maxWithInd = for (i <- adjs(u).indices) yield maxSubtreeSizeFrom(u)(i) -> adjs(u)(i)\n maxWithInd.sortBy(- _._1).take(2)\n }\n\n //sizeFrom.foreach(s => println(s.mkString(\" \")))\n //println(maxSubtreeSize.mkString(\" \"))\n\n for (u <- 0 until n) {\n var ok = true\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n if (sizeFrom(u)(i) > m) {\n val sub = maxSubtreeSize2(v).filter(_._2 != u).headOption.map(_._1)\n if (sub == None || sizeFrom(u)(i) - sub.get > m) ok = false\n }\n }\n res(u) = if (ok) 1 else 0\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val m = n / 2\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val res = Array.fill(n){ 0 }\n val sizeFrom = Array.tabulate(n) { i => Array.ofDim[Int](adjs(i).length)}\n val maxSubtreeSize = Array.fill(n) { 0 }\n\n def dfs(u: Int, parent: Int, size: Int): (Int, Int) = {\n var i = 0\n var childrenSize = 1\n var parentPos = -1\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v == parent) {\n parentPos = i\n } else {\n val (vSubtreeSize, vMaxSubtreeSize) = dfs(v, u, size + 1)\n childrenSize += vSubtreeSize\n sizeFrom(u)(i) = vSubtreeSize\n if (vMaxSubtreeSize <= m && vMaxSubtreeSize > maxSubtreeSize(u)) maxSubtreeSize(u) = vMaxSubtreeSize\n if (vSubtreeSize <= m && vSubtreeSize > maxSubtreeSize(u)) maxSubtreeSize(u) = vSubtreeSize\n }\n i += 1\n }\n if (parentPos >= 0) {\n sizeFrom(u)(parentPos) = n - childrenSize\n }\n (childrenSize, maxSubtreeSize(u))\n }\n\n dfs(0, -1, 0)\n dfs(1, -1, 0)\n\n //sizeFrom.foreach(s => println(s.mkString(\" \")))\n //println(maxSubtreeSize.mkString(\" \"))\n\n for (u <- 0 until n) {\n var ok = true\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n if (sizeFrom(u)(i) > m) {\n if (sizeFrom(u)(i) - maxSubtreeSize(v) > m) ok = false\n }\n }\n res(u) = if (ok) 1 else 0\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val m = n / 2\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val res = Array.fill(n){ 0 }\n val sizeFrom = Array.tabulate(n) { i => Array.ofDim[Int](adjs(i).length)}\n val maxSubtreeSizeFrom = Array.tabulate(n) { i => Array.fill(adjs(i).length) { 0 } }\n var last = 0\n var maxDepth = -1\n\n def dfs(u: Int, parent: Int, size: Int, depth: Int, parentMaxSubtreeSize: Int): (Int, Int) = {\n\n if (depth > maxDepth) {\n last = u\n maxDepth = depth\n }\n\n var i = 0\n var childrenSize = 1\n var parentPos = -1\n var maxSubtreeSize = 0\n\n val maxForward = maxSubtreeSizeFrom(u).max\n\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v == parent) {\n parentPos = i\n } else {\n val (vSubtreeSize, vMaxSubtreeSize) = dfs(v, u, size + 1, depth + 1, maxForward)\n childrenSize += vSubtreeSize\n sizeFrom(u)(i) = vSubtreeSize\n if (vMaxSubtreeSize <= m && vMaxSubtreeSize > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = vMaxSubtreeSize\n if (vSubtreeSize <= m && vSubtreeSize > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = vSubtreeSize\n if (vMaxSubtreeSize <= m && vMaxSubtreeSize > maxSubtreeSize) maxSubtreeSize = vMaxSubtreeSize\n if (vSubtreeSize <= m && vSubtreeSize > maxSubtreeSize) maxSubtreeSize = vSubtreeSize\n }\n i += 1\n }\n if (parentPos >= 0) {\n sizeFrom(u)(parentPos) = n - childrenSize\n if (parentMaxSubtreeSize <= m && parentMaxSubtreeSize > maxSubtreeSizeFrom(u)(parentPos)) maxSubtreeSizeFrom(u)(parentPos) = parentMaxSubtreeSize\n if (n - childrenSize <= m && n - childrenSize > maxSubtreeSizeFrom(u)(parentPos)) maxSubtreeSizeFrom(u)(parentPos) = n - childrenSize\n }\n (childrenSize, maxSubtreeSize)\n }\n\n dfs(0, -1, 0, 0, 0)\n dfs(last, -1, 0, 0, 0)\n\n val maxSubtreeSize2 = for (u <- 0 until n) yield {\n val maxWithInd = for (i <- adjs(u).indices) yield maxSubtreeSizeFrom(u)(i) -> adjs(u)(i)\n maxWithInd.sortBy(- _._1).take(2)\n }\n\n // sizeFrom.foreach(s => println(s.mkString(\" \")))\n //maxSubtreeSizeFrom.foreach(s => println(s.mkString(\" \")))\n\n for (u <- 0 until n) {\n var ok = true\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n if (sizeFrom(u)(i) > m) {\n val sub = maxSubtreeSize2(v).filter(_._2 != u).headOption.map(_._1)\n if (sub == None || sizeFrom(u)(i) - sub.get > m) ok = false\n }\n }\n res(u) = if (ok) 1 else 0\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val m = n / 2\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val res = Array.fill(n){ 0 }\n val sizeFrom = Array.tabulate(n) { i => Array.ofDim[Int](adjs(i).length)}\n val maxSubtreeSizeFrom = Array.tabulate(n) { i => Array.fill(adjs(i).length) { 0 } }\n var last = 0\n var maxDepth = -1\n\n def dfs(u: Int, parent: Int, size: Int, depth: Int, parentMaxSubtreeSize: Int): (Int, Int) = {\n\n if (depth > maxDepth) {\n last = u\n maxDepth = depth\n }\n\n var i = 0\n var childrenSize = 1\n var parentPos = -1\n var maxSubtreeSize = 0\n\n while (i < adjs(u).length) {\n if (adjs(u)(i) == parent) parentPos = i\n i += 1\n }\n\n if (parentPos >= 0) {\n if (parentMaxSubtreeSize <= m && parentMaxSubtreeSize > maxSubtreeSizeFrom(u)(parentPos)) maxSubtreeSizeFrom(u)(parentPos) = parentMaxSubtreeSize\n //if (n - childrenSize <= m && n - childrenSize > maxSubtreeSizeFrom(u)(parentPos)) maxSubtreeSizeFrom(u)(parentPos) = n - childrenSize\n }\n\n val maxForwardA = maxSubtreeSizeFrom(u).max\n val maxForwardB = maxSubtreeSizeFrom(u).sum + 1\n var maxForward = 0\n if (maxForwardA <= m) maxForward = maxForwardA\n //if (maxForwardB <= m && maxForwardB > maxForward) maxForward = maxForwardB\n\n i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v != parent) {\n val (vSubtreeSize, vMaxSubtreeSize) = dfs(v, u, size + 1, depth + 1, maxForward)\n childrenSize += vSubtreeSize\n sizeFrom(u)(i) = vSubtreeSize\n if (vMaxSubtreeSize <= m && vMaxSubtreeSize > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = vMaxSubtreeSize\n if (vSubtreeSize <= m && vSubtreeSize > maxSubtreeSizeFrom(u)(i)) maxSubtreeSizeFrom(u)(i) = vSubtreeSize\n if (vMaxSubtreeSize <= m && vMaxSubtreeSize > maxSubtreeSize) maxSubtreeSize = vMaxSubtreeSize\n if (vSubtreeSize <= m && vSubtreeSize > maxSubtreeSize) maxSubtreeSize = vSubtreeSize\n }\n i += 1\n }\n\n if (parentPos >= 0) {\n sizeFrom(u)(parentPos) = n - childrenSize\n }\n\n (childrenSize, maxSubtreeSize)\n }\n\n dfs(0, -1, 0, 0, 0)\n dfs(last, -1, 0, 0, 0)\n dfs(last, -1, 0, 0, 0)\n\n //maxSubtreeSizeFrom.foreach(s => println(s.mkString(\" \")))\n\n val maxSubtreeSize2 = for (u <- 0 until n) yield {\n val maxWithInd = for (i <- adjs(u).indices) yield maxSubtreeSizeFrom(u)(i) -> adjs(u)(i)\n maxWithInd.sortBy(- _._1).take(2)\n }\n\n //maxSubtreeSize2.foreach(s => println(s.mkString(\" \")))\n\n for (u <- 0 until n) {\n var ok = true\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n if (sizeFrom(u)(i) > m) {\n val sub = maxSubtreeSize2(v).filter(_._2 != u).headOption.map(_._1)\n if (sub == None || sizeFrom(u)(i) - sub.get > m) ok = false\n }\n }\n res(u) = if (ok) 1 else 0\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val m = n / 2\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val res = Array.fill(n){ 0 }\n val sizeFrom = Array.tabulate(n) { i => Array.ofDim[Int](adjs(i).length)}\n val maxSubtreeSize = Array.fill(n) { 0 }\n var last = 0\n var maxDepth = -1\n\n def dfs(u: Int, parent: Int, size: Int, depth: Int): (Int, Int) = {\n if (depth > maxDepth) {\n last = u\n maxDepth = depth\n }\n var i = 0\n var childrenSize = 1\n var parentPos = -1\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v == parent) {\n parentPos = i\n } else {\n val (vSubtreeSize, vMaxSubtreeSize) = dfs(v, u, size + 1, depth + 1)\n childrenSize += vSubtreeSize\n sizeFrom(u)(i) = vSubtreeSize\n if (vMaxSubtreeSize <= m && vMaxSubtreeSize > maxSubtreeSize(u)) maxSubtreeSize(u) = vMaxSubtreeSize\n if (vSubtreeSize <= m && vSubtreeSize > maxSubtreeSize(u)) maxSubtreeSize(u) = vSubtreeSize\n }\n i += 1\n }\n if (parentPos >= 0) {\n sizeFrom(u)(parentPos) = n - childrenSize\n }\n (childrenSize, maxSubtreeSize(u))\n }\n\n dfs(0, -1, 0, 0)\n dfs(last, -1, 0, 0)\n\n //sizeFrom.foreach(s => println(s.mkString(\" \")))\n //println(maxSubtreeSize.mkString(\" \"))\n\n for (u <- 0 until n) {\n var ok = true\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n if (sizeFrom(u)(i) > m) {\n if (sizeFrom(u)(i) - maxSubtreeSize(v) > m) ok = false\n }\n }\n res(u) = if (ok) 1 else 0\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val m = (n - 1) / 2\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val res = Array.fill(n){ 0 }\n val sizeFrom = Array.tabulate(n) { i => Array.ofDim[Int](adjs(i).length)}\n val maxSubtreeSize = Array.fill(n) { 0 }\n var last = 0\n var maxDepth = -1\n\n def dfs(u: Int, parent: Int, size: Int, depth: Int): (Int, Int) = {\n if (depth > maxDepth) {\n last = u\n maxDepth = depth\n }\n var i = 0\n var childrenSize = 1\n var parentPos = -1\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v == parent) {\n parentPos = i\n } else {\n val (vSubtreeSize, vMaxSubtreeSize) = dfs(v, u, size + 1, depth + 1)\n childrenSize += vSubtreeSize\n sizeFrom(u)(i) = vSubtreeSize\n if (vMaxSubtreeSize <= m && vMaxSubtreeSize > maxSubtreeSize(u)) maxSubtreeSize(u) = vMaxSubtreeSize\n if (vSubtreeSize <= m && vSubtreeSize > maxSubtreeSize(u)) maxSubtreeSize(u) = vSubtreeSize\n }\n i += 1\n }\n if (parentPos >= 0) {\n sizeFrom(u)(parentPos) = n - childrenSize\n }\n (childrenSize, maxSubtreeSize(u))\n }\n\n dfs(0, -1, 0, 0)\n dfs(last, -1, 0, 0)\n\n //sizeFrom.foreach(s => println(s.mkString(\" \")))\n //println(maxSubtreeSize.mkString(\" \"))\n\n for (u <- 0 until n) {\n var ok = true\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n if (sizeFrom(u)(i) > m) {\n if (sizeFrom(u)(i) - maxSubtreeSize(v) > m) ok = false\n }\n }\n res(u) = if (ok) 1 else 0\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val m = n / 2\n\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adjs = adjBuilders.map(_.result)\n val res = Array.fill(n){ 0 }\n val sizeFrom = Array.tabulate(n) { i => Array.ofDim[Int](adjs(i).length)}\n val maxSubtreeSize = Array.fill(n) { 0 }\n\n def dfs(u: Int, parent: Int, size: Int): (Int, Int) = {\n var i = 0\n var childrenSize = 1\n var parentPos = -1\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v == parent) {\n parentPos = i\n } else {\n val (vSubtreeSize, vMaxSubtreeSize) = dfs(v, u, size + 1)\n childrenSize += vSubtreeSize\n (vSubtreeSize, vMaxSubtreeSize)\n sizeFrom(u)(i) = vSubtreeSize\n if (vMaxSubtreeSize <= m && vMaxSubtreeSize > maxSubtreeSize(u)) maxSubtreeSize(u) = vMaxSubtreeSize\n if (vSubtreeSize <= m && vSubtreeSize > maxSubtreeSize(u)) maxSubtreeSize(u) = vSubtreeSize\n }\n i += 1\n }\n if (parentPos >= 0) {\n sizeFrom(u)(parentPos) = n - childrenSize\n }\n (childrenSize, maxSubtreeSize(u))\n }\n\n dfs(0, -1, 0)\n\n //sizeFrom.foreach(s => println(s.mkString(\" \")))\n //println(maxSubtreeSize.mkString(\" \"))\n\n for (u <- 0 until n) {\n var ok = true\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n if (sizeFrom(u)(i) > m) {\n if (sizeFrom(u)(i) - maxSubtreeSize(v) > m) ok = false\n }\n }\n res(u) = if (ok) 1 else 0\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}], "src_uid": "20271fa2e59b2e3d95d8ffdb56ac64f5"} {"source_code": "object b extends App {\n class Point(val x: Long, val y: Long) extends Ordered[Point] {\n\t def - (that: Point): Point = new Point(x - that.x, y - that.y)\n\t def ^ (that: Point): Long = x * that.y - y * that.x\n\t def * (that: Point): Long = x * that.x + y * that.y\n\t override def compare(that: Point) = len compare that.len\n\t def len = math.sqrt(x * x + y * y)\n\t }\n\t def readPoint = {\n\t val line = readLine.split(\" \")\n\t new Point(line(0).toInt, line(1).toInt)\n\t }\n\t \n\t def readInput(n: Int, acc: List[Point] = Nil): List[Point] =\n\t if (n == 0)\n\t acc\n\t else\n\t readInput(n - 1, readPoint :: acc)\n\t \n\t val line = readLine.split(\" \")\n\t val n = line(0).toInt\n\t val p = new Point(line(1).toInt, line(2).toInt)\n\t val arr = new Array[Point](n)\n\t for (i <- 0 until n)\n\t arr(i) = readPoint\n\t //if (n == 100000)\n\t // throw new Exception\n\t val dists = for (i <- 0 until n if (arr(i) - arr((i + 1) % n)) * (p - arr((i + 1) % n)) >= 0 &&\n\t (arr((i + 1) % n) - arr(i)) * (p - arr(i)) >= 0 && arr(i) != arr((i + 1) % n))\n\t yield math.abs(((arr(i) - p) ^ (arr((i + 1) % n) - p)) / (arr(i) - arr((i + 1) % n)).len)\n\t \n\t val dmin = if (dists.length == 0) 1e15; else dists.min\n\t val min = List(dmin, arr.map(cur_p => (cur_p - p)).min.len).min\n\t val max = arr.map(cur_p => (cur_p - p)).max\n\t println((max.len * max.len - min * min) * math.Pi)\n}", "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, java.awt.geom._\n\nobject _614C extends CodeForcesApp {\n override def apply(io: IO) = {\n val (n, z) = io[(Int, Point2D)]\n val ps = io[Seq, Point2D](n)\n val shape = (ps :+ ps.head) sliding 2 map {case Seq(p1, p2) => new Line2D.Double(p1, p2)}\n val closest = shape.map(_.ptSegDistSq(z))\n val farthest = ps.map(_.distanceSq(z))\n io += Math.PI * (farthest.max - closest.min)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[I] = new {\n def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val newLine: String = \"\\n\"\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer, java.awt.geom._\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = this.+=(xs.size).appendNewLine().+=(xs)\n\n def appendNewLine(): this.type = {\n println()\n this\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n implicit val point : Read[Point2D] = tuple2[Double, Double].map {case (x, y) => new Point2D.Double(x, y)}\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, java.awt.geom._\n\nobject _614C extends CodeForcesApp {\n override def apply(io: IO) = {\n val (n, z) = io[(Int, Point2D)]\n val ps = io[Seq, Point2D](n)\n val shape = ((ps :+ ps.head) sliding 2 map {case Seq(p1, p2) => new Line2D.Double(p1, p2)}).toSeq\n val closest = shape map {line => line ptSegDistSq z}\n val farthest = shape map {line => (line.getP1 distanceSq z) max (line.getP2 distanceSq z)}\n io += Math.PI * (farthest.max - closest.min)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[I] = new {\n def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val newLine: String = \"\\n\"\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer, java.awt.geom._\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = this.+=(xs.size).appendNewLine().+=(xs)\n\n def appendNewLine(): this.type = {\n println()\n this\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n implicit val point : Read[Point2D] = tuple2[Double, Double].map {case (x, y) => new Point2D.Double(x, y)}\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _614C extends CodeForcesApp {\n override type Result = BigDecimal\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val (n, px, py) = (nextInt(), nextBigInt(), nextBigInt())\n val polygon = Seq.fill(n)(nextBigInt() -> nextBigInt())\n val radii = polygon map {case (x, y) => (px - x)*(px - x) + (py - y)*(py - y)}\n BigDecimal(radii.max - radii.min) * BigDecimal(Math.PI)\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n val mod: Int = 1000000007\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _614C extends CodeForcesApp {\n override type Result = Double\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val (n, px, py) = (nextInt(), nextLong(), nextLong())\n val polygon = Seq.fill(n)(nextLong() -> nextLong())\n val radii = polygon map {case (x, y) =>\n (px - x)*(px - x) + (py - y)*(py - y)\n }\n Math.PI * (radii.max - radii.min)\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n val mod: Int = 1000000007\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}, {"source_code": "object Main extends App {\n\t class Point(val x: Int, val y: Int) extends Ordered[Point] {\n\t def - (that: Point): Point = new Point(x - that.x, y - that.y)\n\t override def compare(that: Point) = len compare that.len\n\t val len = math.sqrt(x * x + y * y)\n\t }\n\t def readPoint = {\n\t val line = readLine.split(\"\\\\s+\")\n\t new Point(line(0).toInt, line(1).toInt)\n\t }\n\t def readInput(n: Int, acc: List[Point] = Nil): List[Point] =\n\t if (n == 0)\n\t acc\n\t else\n\t readInput(n - 1, readPoint :: acc)\n\t val line = readLine.split(\"\\\\s+\")\n\t val n = line(0).toInt\n\t val p = new Point(line(1).toInt, line(2).toInt)\n\t val arr = readInput(n)\n\t val min = arr.map(cur_p => (cur_p - p)).min\n\t val max = arr.map(cur_p => (cur_p - p)).max\n\t println((max.len * max.len - min.len * min.len) * math.Pi)\n}"}, {"source_code": "object Main extends App {\n\t class Point(val x: Int, val y: Int) extends Ordered[Point] {\n\t def - (that: Point): Point = new Point(x - that.x, y - that.y)\n\t def ^ (that: Point): Long = x.toLong * that.y - y.toLong * that.x\n\t def * (that: Point): Long = x.toLong * that.x + y.toLong * that.y\n\t override def compare(that: Point) = len compare that.len\n\t val len = math.sqrt(x * x + y * y)\n\t }\n\t def readPoint = {\n\t val line = readLine.split(\"\\\\s+\")\n\t new Point(line(0).toInt, line(1).toInt)\n\t }\n\t def readInput(n: Int, acc: List[Point] = Nil): List[Point] =\n\t if (n == 0)\n\t acc\n\t else\n\t readInput(n - 1, readPoint :: acc)\n\t val line = readLine.split(\"\\\\s+\")\n\t val n = line(0).toInt\n\t val p = new Point(line(1).toInt, line(2).toInt)\n\t val arr = readInput(n)\n\t \n\t val dists = for (i <- 0 until n if (arr(i) - arr((i + 1) % n)) * (arr(i) - p) >= 0 &&\n\t (arr((i + 1) % n) - arr(i)) * (arr((i + 1) % n) - p) >= 0)\n\t yield ((arr(i) - p) ^ (arr((i + 1) % n) - p)) / (arr(i) - arr((i + 1) % n)).len\n\t \n\t val min = List(dists.min, arr.map(cur_p => (cur_p - p)).min.len).min\n\t \n\t val max = arr.map(cur_p => (cur_p - p)).max\n\t println((max.len * max.len - min * min) * math.Pi)\n}"}, {"source_code": "object b extends App {\n class Point(val x: Int, val y: Int) extends Ordered[Point] {\n\t def - (that: Point): Point = new Point(x - that.x, y - that.y)\n\t def ^ (that: Point): Long = x.toLong * that.y - y.toLong * that.x\n\t def * (that: Point): Long = x.toLong * that.x + y.toLong * that.y\n\t override def compare(that: Point) = len compare that.len\n\t def len = math.sqrt(x * x + y * y)\n\t }\n\t def readPoint = {\n\t val line = readLine.split(\" \")\n\t new Point(line(0).toInt, line(1).toInt)\n\t }\n\t \n\t def readInput(n: Int, acc: List[Point] = Nil): List[Point] =\n\t if (n == 0)\n\t acc\n\t else\n\t readInput(n - 1, readPoint :: acc)\n\t \n\t val line = readLine.split(\" \")\n\t val n = line(0).toInt\n\t val p = new Point(line(1).toInt, line(2).toInt)\n\t val arr = new Array[Point](n)\n\t for (i <- 0 until n)\n\t arr(i) = readPoint\n\t //if (n == 100000)\n\t // throw new Exception\n\t val dists = for (i <- 0 until n if (arr(i) - arr((i + 1) % n)) * (p - arr((i + 1) % n)) >= 0 &&\n\t (arr((i + 1) % n) - arr(i)) * (p - arr(i)) >= 0 && arr(i) != arr((i + 1) % n))\n\t yield math.abs(((arr(i) - p) ^ (arr((i + 1) % n) - p)) / (arr(i) - arr((i + 1) % n)).len)\n\t \n\t val dmin = if (dists.length == 0) 1e15; else dists.min\n\t val min = List(dmin, arr.map(cur_p => (cur_p - p)).min.len).min\n\t val max = arr.map(cur_p => (cur_p - p)).max\n\t println((max.len * max.len - min * min) * math.Pi)\n}"}, {"source_code": "object b extends App {\n class Point(val x: Int, val y: Int) extends Ordered[Point] {\n\t def - (that: Point): Point = new Point(x - that.x, y - that.y)\n\t def ^ (that: Point): Long = x.toLong * that.y - y.toLong * that.x\n\t def * (that: Point): Long = x.toLong * that.x + y.toLong * that.y\n\t override def compare(that: Point) = len compare that.len\n\t def len = math.sqrt(x * x + y * y)\n\t }\n\t def readPoint = {\n\t val line = readLine.split(\" \")\n\t new Point(line(0).toInt, line(1).toInt)\n\t }\n\t \n\t def readInput(n: Int, acc: List[Point] = Nil): List[Point] =\n\t if (n == 0)\n\t acc\n\t else\n\t readInput(n - 1, readPoint :: acc)\n\t \n\t val line = readLine.split(\" \")\n\t val n = line(0).toInt\n\t val p = new Point(line(1).toInt, line(2).toInt)\n\t val arr = new Array[Point](n)\n\t for (i <- 0 until n)\n\t arr(i) = readPoint\n\t //if (n == 100000)\n\t // throw new Exception\n\t val dists = for (i <- 0 until n if (arr(i) - arr((i + 1) % n)) * (p - arr((i + 1) % n)) >= 0 &&\n\t (arr((i + 1) % n) - arr(i)) * (p - arr(i)) >= 0)\n\t yield math.abs(((arr(i) - p) ^ (arr((i + 1) % n) - p)) / (arr(i) - arr((i + 1) % n)).len)\n\t \n\t val dmin = if (dists.length == 0) 1e15; else dists.min\n\t val min = List(dmin, arr.map(cur_p => (cur_p - p)).min.len).min\n\t val max = arr.map(cur_p => (cur_p - p)).max\n\t println((max.len * max.len - min * min) * math.Pi)\n}"}, {"source_code": "object Main extends App {\n\t class Point(val x: Int, val y: Int) extends Ordered[Point] {\n\t def - (that: Point): Point = new Point(x - that.x, y - that.y)\n\t def * (that: Point): Long = x.toLong * that.y - y * that.x\n\t override def compare(that: Point) = len compare that.len\n\t val len = math.sqrt(x * x + y * y)\n\t }\n\t def readPoint = {\n\t val line = readLine.split(\"\\\\s+\")\n\t new Point(line(0).toInt, line(1).toInt)\n\t }\n\t def readInput(n: Int, acc: List[Point] = Nil): List[Point] =\n\t if (n == 0)\n\t acc\n\t else\n\t readInput(n - 1, readPoint :: acc)\n\t val line = readLine.split(\"\\\\s+\")\n\t val n = line(0).toInt\n\t val p = new Point(line(1).toInt, line(2).toInt)\n\t val arr = readInput(n)\n\t \n\t val dists = for (i <- 0 until n)\n\t yield arr(i) * arr((i + 1) % n) / (arr(i) - arr((i + 1) % n)).len\n\t \n\t val min = dists.min\n\t \n\t val max = arr.map(cur_p => (cur_p - p)).max\n\t println((max.len * max.len - min * min) * math.Pi)\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _614C extends CodeForcesApp {\n override type Result = Double\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val (n, px, py) = (nextInt(), nextInt(), nextInt())\n val polygon = Seq.fill(n)(nextInt() -> nextInt())\n val radii = polygon map {\n case (x, y) => Math.sqrt(((px - x)*(px - x) + (py - y)*(py - y)).toDouble)\n }\n val (r2, r1) = (radii.max, radii.min)\n Math.PI * ((r2 * r2) - (r1 * r1))\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n val mod: Int = 1000000007\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}], "src_uid": "1d547a38250c7780ddcf10674417d5ff"} {"source_code": "import scala.io.StdIn._\n\nobject EducationalGame178A2 extends App {\n\n\n\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n\n val toPrint = (0 until (n-1)).scanLeft(0: Long){case (prev,indx) => {\n val currentCell = a(indx)\n\n val t = 1 << minimun2k(n-indx-1)\n\n a(indx+t) += currentCell\n prev+currentCell\n }}.tail.mkString(System.lineSeparator())\n\n System.out.println(toPrint)\n\n\n /**\n * 2^k <= n < 2^(k+1)\n * @param n\n * @return k\n */\n def minimun2k(n: Int): Int = {\n var k = 0\n var nn = n\n while(nn > 1){\n k+=1\n nn >>=1\n }\n k\n }\n}\n", "positive_code": [{"source_code": "object EducationalGame178A2 extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n solve(System.in,System.out)\n def solve(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextInt()\n val a = (1 to n).map(_ => scanner.nextLong()).toArray\n val results = Array.fill(n)(0)\n (0 until (n-1)).scanLeft(0: Long){case (prev,indx) => {\n val currentCell = a(indx)\n\n val t = 1 << minimun2k(n-indx-1)\n\n a(indx) = 0\n a(indx+t) += currentCell\n prev+currentCell\n }}.tail.foreach(out.println)\n\n\n }\n\n /**\n * 2^k <= n < 2^(k+1)\n * @param n\n * @return k\n */\n def minimun2k(n: Int): Int = {\n var k = 0\n var nn = n\n while(nn > 1){\n k+=1\n nn >>=1\n }\n k\n }\n}"}], "negative_code": [{"source_code": "object EducationalGame178A2 extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n //solve(System.in,System.out)\n def solve(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextInt()\n val a = (1 to n).map(_ => scanner.nextLong()).toArray\n val results = Array.fill(n)(0)\n (0 until (n-1)).scanLeft(0: Long){case (prev,indx) => {\n val currentCell = a(indx)\n\n val t = 1 << minimun2k(n-indx-1)\n\n a(indx) = 0\n a(indx+t) += currentCell\n prev+currentCell\n }}.tail.foreach(out.println)\n\n\n }\n\n /**\n * 2^k <= n < 2^(k+1)\n * @param n\n * @return k\n */\n def minimun2k(n: Int): Int = {\n var k = 0\n var nn = n\n while(nn > 1){\n k+=1\n nn >>=1\n }\n k\n }\n}"}], "src_uid": "c7e49c643dd8738f273c0d24e56c505f"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val n, L, a = ni()\n val t, l = Array.ofDim[Int](n + 2)\n t(0) = -1\n l(0) = 1\n rep(n, 1) { i =>\n t(i) = ni()\n l(i) = ni()\n }\n t(n + 1) = L\n l(n + 1) = 1\n\n var ans = 0\n rep(n + 1) { i =>\n val len = t(i + 1) - (t(i) + l(i))\n ans += len / a\n }\n\n out.println(ans)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject TaskA extends App {\n\n val Array(n, l, a) = StdIn.readLine.split(\" \").map(_.toInt)\n\n def getCountCoffeeBreak(n: Int, L: Int, a: Int):Int = {\n if(n == 0) L / a\n else {\n val Array(t, l) = StdIn.readLine.split(\" \").map(_.toInt)\n t / a + getCountCoffeeBreak(n - 1, L, a, t + l)\n }\n }\n\n def getCountCoffeeBreak(n: Int, L: Int, a: Int, last_end_time: Int):Int = {\n if(n == 0) (L - last_end_time) / a\n else {\n val Array(t, l) = StdIn.readLine.split(\" \").map(_.toInt)\n (t - last_end_time) / a + getCountCoffeeBreak(n - 1, L, a, t + l)\n }\n }\n\n println(getCountCoffeeBreak(n, l, a))\n}"}, {"source_code": "object A extends App {\n import java.io.{PrintWriter, InputStreamReader, BufferedReader}\n import java.util.{Locale, Scanner}\n import scala.collection.mutable._\n\n val in = new Scanner(System.in)\n val bufferedIn = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = bufferedIn.readLine\n\n def solve = {\n val n = nextInt\n val L = nextInt\n val a = nextInt\n var ans = 0\n var cur = 0\n\n // println(s\"$n $L $a\")\n\n for (i <- 0 until n) {\n val ti = nextInt\n val li = nextInt\n \n ans += (ti - cur) / a\n cur = ti + li\n }\n ans += (L - cur) / a\n\n println(ans)\n }\n\n solve\n}"}], "negative_code": [], "src_uid": "00acb3b54975820989a788b9389c7c0b"} {"source_code": "object A extends App {\r\n\r\n def era(an: IndexedSeq[Int]): Long =\r\n an.zipWithIndex.foldLeft(0L) {\r\n case (count, (ai, i)) if ai <= i + 1 + count => count\r\n case (count, (ai, i)) => ai - i - 1\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val an = nextInts(n)\r\n val count = era(an)\r\n\r\n out.println(count)\r\n }\r\n\r\n out.flush()\r\n\r\n object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n private[this] def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class pair(var minl: Int, var maxl: Int, var minr: Int, var maxr: Int, var ind: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return minl.compareTo(that.minl)\n }\n }\n val rem = 1000000007\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n var ans = 0\n for (i <- 1 to n) {\n val k = readInt()\n ans = max(ans, k - i)\n }\n writer.println(ans)\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "e79c6a337e9347522bf19f3d5c162541"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = {\n if (!oj){ System.err.println(s) }\n }\n def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n private[this] def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n REP(m)(i => p(from(i)) += 1)\n REP(m)(i => p(to(i)) += 1)\n REP(n)(i => t(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) extends Runnable {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit ={\n val t = new Thread(null, this, \"solve\", 1 << 27)\n t.start()\n t.join()\n }\n\n def run(): Unit = {\n val N = ni()\n val (from, to) = na2(N - 1, -1)\n val g = packUGraph(N, from, to)\n\n var n = 1\n val seg = Array.ofDim[Int](N, 2)\n\n def dfs(v: Int, p: Int): Unit = {\n if (seg(v)(0) == 0) {\n seg(v)(0) = n\n n += 1\n }\n\n var j = 0\n while(j < g(v).length) {\n val u = g(v)(j)\n if (u != p) {\n seg(u)(0) = n\n n += 1\n }\n j += 1\n }\n seg(v)(1) = n\n n += 1\n\n j = g(v).length - 1\n while(j >= 0) {\n val u = g(v)(j)\n if (u != p) {\n dfs(u, v)\n }\n j -= 1\n }\n }\n\n dfs(0, -1)\n REP(N) { v =>\n out.println(s\"${seg(v)(0)} ${seg(v)(1)}\")\n }\n }\n}", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = {\n if (!oj){ System.err.println(s) }\n }\n def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n private[this] def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n REP(m)(i => p(from(i)) += 1)\n REP(m)(i => p(to(i)) += 1)\n REP(n)(i => t(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) extends Runnable {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit ={\n val t = new Thread(null, this, \"solve\", 1 << 26)\n t.start()\n t.join()\n }\n\n def run(): Unit = {\n val N = ni()\n val (from, to) = na2(N - 1, -1)\n val g = packUGraph(N, from, to)\n\n var n = 1\n val seg = Array.ofDim[Int](N, 2)\n\n def dfs(v: Int, p: Int): Unit = {\n if (seg(v)(0) == 0) {\n seg(v)(0) = n\n n += 1\n }\n\n var j = 0\n while(j < g(v).length) {\n val u = g(v)(j)\n if (u != p) {\n seg(u)(0) = n\n n += 1\n }\n j += 1\n }\n seg(v)(1) = n\n n += 1\n\n j = g(v).length - 1\n while(j >= 0) {\n val u = g(v)(j)\n if (u != p) {\n dfs(u, v)\n }\n j -= 1\n }\n }\n\n dfs(0, -1)\n REP(N) { v =>\n out.println(s\"${seg(v)(0)} ${seg(v)(1)}\")\n }\n }\n}"}], "negative_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = {\n if (!oj){ System.err.println(s) }\n }\n def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n private[this] def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n REP(m)(i => p(from(i)) += 1)\n REP(m)(i => p(to(i)) += 1)\n REP(n)(i => t(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) extends Runnable {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit ={\n val t = new Thread(null, this, \"solve\", 1 << 26)\n t.start()\n t.join()\n }\n\n def run(): Unit = {\n val N = ni()\n val (from, to) = na2(N - 1, -1)\n val g = packUGraph(N, from, to)\n\n var n = 1\n val seg = Array.ofDim[Int](N, 2)\n\n def dfs(v: Int, p: Int): Unit = {\n if (seg(v)(0) == 0) {\n seg(v)(0) = n\n n += 1\n }\n\n REP(g(v).length) { j =>\n val u = g(v)(j)\n if (u != p) {\n seg(u)(0) = n\n n += 1\n }\n }\n seg(v)(1) = n\n n += 1\n\n REP(g(v).length) { j =>\n val u = g(v)(j)\n if (u != p) {\n dfs(u, v)\n }\n }\n }\n\n dfs(0, -1)\n REP(N) { v =>\n out.println(s\"${seg(v)(0)} ${seg(v)(1)}\")\n }\n }\n}"}], "src_uid": "739e60a2fa71aff9a5c7e781db861d1e"} {"source_code": "\n//package codeblocks\n\nimport java.util.Scanner\nimport scala.math._\nobject cf441B {\n\n\tval sc = new Scanner(System.in)\n\tdef main(args : Array[String]) : Unit = {\n\t\tval n,v = sc.nextInt\n\t\tvar a = new Array[Long](3002)\n\t\tfor(i <- 1 to n) a(sc.nextInt)+=sc.nextInt\n\t\tvar counts:Long = 0\n\t\tfor(i <-1 to 3001){\n\t\t\tval today =min(v, a(i)+a(i-1))\n\t\t\tcounts+=today\n\t\t\ta(i) = if(today!=v) 0 else min(a(i),a(i)+a(i-1)-v)\n\t\t}\n\t\tprintln(counts)\n\t}\n\n}", "positive_code": [{"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, v) = in.next().split(' ').map(_.toInt)\n val data = Array.ofDim[Int](3001)\n (0 until n).foreach { _ =>\n val Array(a, b) = in.next().split(' ').map(_.toInt)\n data(a - 1) += b\n }\n val res = data.foldLeft((0, 0)) {\n case((soFar, fromPrev), el) if (fromPrev + el) <= v => (soFar + fromPrev + el, 0)\n case((soFar, fromPrev), el) if fromPrev >= v => (soFar + v, el)\n case((soFar, fromPrev), el) => (soFar + v, el + fromPrev - v)\n }._1\n println(res)\n}\n"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject B extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, v) = readInts(2)\n val day1 = Array.fill(3002)(0)\n val day2 = Array.fill(3002)(0)\n \n for (i <- 0 until n) {\n val Array(a, b) = readInts(2)\n day1(a - 1) += b\n day2(a) += b\n }\n\n var sum = 0\n var prevDay1take = 0\n for (i <- 0 to 3001) {\n\tval day2take = (day2(i) - prevDay1take) min v max 0\n\tval day1take = day1(i) min (v - day2take)\n\tprevDay1take = day1take\n\t//println(day1take, day2take)\n\tsum += day1take + day2take\n }\n\n println(sum)\n}"}, {"source_code": "\n\nobject Bnew {\n import scala.math._\n \n def main(args: Array[String]): Unit = {\n var Array(n,v) = readLine.split(\" \").map(_.toInt)\n var ans = new Array[Long](3002)\n \n for (i <- 0 until n){\n var Array(x,y) = readLine.split(\" \").map(_.toInt)\n ans(x) += y\n }\n var cnt = ans(0)\n for (i <- 1 to 3001){\n var minn = min(v, (ans(i)+ans(i-1)))\n \tcnt += minn\n \tans(i) = max(0, ans(i) - max(0, \n \t minn -ans(i-1)))\n }\n\n println(cnt)\n }\n\n}"}, {"source_code": "\n/**\n * Created by slie742 on 9/09/2015.\n */\n\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\nimport Math.abs\nimport Math.max\nimport Math.min\n\nobject ValeraFruits {\n\n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n\n def readLongs() : Array[Long] =\n readLine.split(' ').map(_.toLong)\n\n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n\n\n def count(garden: Map[Int,Int], v: Int) : Int = {\n val maxDay = garden.keys.max + 1\n def go(day: Int, leftFromPrev: Int, total: Int) : Int = {\n if (day > maxDay) total\n else {\n val harvested = leftFromPrev + min(v-leftFromPrev, garden.getOrElse(day,0))\n go(day + 1,min(v,garden.getOrElse(day,0) - (harvested-leftFromPrev))\n , total + harvested)\n }\n }\n go(1, 0, 0)\n }\n\n def main(args: Array[String]) {\n val (n,v) = readTuple()\n val garden = for {\n i <- 1 to n\n (a,b) = readTuple()\n } yield (a,b)\n val gardenGrouped = garden.groupBy{ case (a,b) => a}.mapValues( l => l.map(_._2).sum)\n println(count(gardenGrouped,v))\n }\n\n}\n"}], "negative_code": [{"source_code": "\n\nimport java.util.Scanner\n\nobject cf441B {\n\n\tval sc = new Scanner(System.in)\n\tdef main(args : Array[String]) : Unit = {\n\t\tval n,v = sc.nextInt\n\t\tvar arr = ( for(i <- 1 to n) yield (sc.nextInt,sc.nextInt)).toArray\n\t//\tarr sortBy (_._1) foreach(println )\n\t\tvar yetCollect = 0\n\t\tvar sumCollect = 0\n\t\tfor(i <- 1 to n+1){\n\t\t\ti match {\n\t\t\t\tcase 1 => {\n\t\t\t\t\t//第一天只能采第一天的水果,yetCollect保存的为前一天所摘的数量\n\t\t\t\t\tif(v>=arr(i-1)._2){sumCollect+=arr(i-1)._2;yetCollect=arr(i-1)._2}\n\t\t\t\t\telse {sumCollect+=v;yetCollect=v}\n\t\t\t\t}\n\t\t\t\tcase x => {\n\t\t\t\t\tif(x<=n){\n\t\t\t\t\t\tif(yetCollect == arr(i-2)._2){\n\t\t\t\t\t\t\tif(v>=arr(i-1)._2){sumCollect+=arr(i-1)._2;yetCollect=arr(i-1)._2}\n\t\t\t\t\t\t\telse {sumCollect+=v;yetCollect=v}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tif(v>=arr(i-2)._2-yetCollect){\n\t\t\t\t\t\t\t\tyetCollect=arr(i-2)._2-yetCollect\n\t\t\t\t\t\t\t\tsumCollect+=yetCollect\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tyetCollect=v\n\t\t\t\t\t\t\t\tsumCollect+=yetCollect\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(v-yetCollect >0){\n\t\t\t\t\t\t\t\tif(v-yetCollect >= arr(i-1)._2){\n\t\t\t\t\t\t\t\t\tyetCollect=arr(i-1)._2\n\t\t\t\t\t\t\t\t\tsumCollect+=yetCollect}\n\t\t\t\t\t\t\t\telse {sumCollect+=v-yetCollect;yetCollect=v-yetCollect}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tyetCollect = 0\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tif(yetCollect != arr(i-2)._2){\n\t\t\t\t\t\t\t\tif(v>=arr(i-2)._2-yetCollect){\n\t\t\t\t\t\t\t\t\tyetCollect=arr(i-2)._2-yetCollect\n\t\t\t\t\t\t\t\t\tsumCollect+=yetCollect\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\t\tyetCollect=v\n\t\t\t\t\t\t\t\t\tsumCollect+=yetCollect\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintln(sumCollect)\n\t}\n\n}"}, {"source_code": "\n\nobject Bnew {\n import scala.math._\n \n def main(args: Array[String]): Unit = {\n var Array(n,v) = readLine.split(\" \").map(_.toInt)\n var a = new Array[Int](n+1)\n var b = new Array[Int](n+1)\n var ans = new Array[Int](3002)\n var minn = 30000\n var maxx = 0\n var cnt = 0\n for (i <- 0 until n){\n var Array(x,y) = readLine.split(\" \").map(_.toInt)\n ans(x) += y\n minn = min(minn,x)\n maxx = max(maxx,x)\n }\n var bl = false;\n for (i <- minn to maxx){\n if (ans(i)>0){\n if (ans(i+1)==0){\n if (!bl)\n \tcnt += min(2*v,ans(i))\n \telse cnt += min(v,ans(i))\n \tbl = false\n }\n else {\n if (!bl){\n \tcnt += min(2*v,ans(i))\n \tif (ans(i)<2*v){\n \t var coef= min(2*v - ans(i),ans(i+1))\n \t ans(i+1) -= coef\n \t cnt += coef\n \t}\n }\n else {cnt += min(v,ans(i))\n if (ans(i) pivot) j -= 1\n\t\tif (i <= j) {\n\t\tswap(i, j)\n\t\tswap2(i, j)\n\t\ti += 1\n\t\tj -= 1\n\t\t}\n\t\t}\n\t\tif (l < j) sort1(l, j)\n\t\tif (j < r) sort1(i, r)\n\t\t}\n\t\tsort1(0, xs.length - 2)\n\t\t}\n \n def main(args: Array[String]): Unit = {\n var Array(n,v) = readLine.split(\" \").map(_.toInt)\n var a = new Array[Int](n+1)\n var b = new Array[Int](n+1)\n var ans = new Array[Int](n+1)\n for (i <- 0 until n){\n var Array(x,y) = readLine.split(\" \").map(_.toInt)\n a(i) = x\n b(i) = y\n }\n// for (i <- 0 until n-1)\n// for (j <- i+1 until n)\n// if (a(i)>a(j)){\n// var t = a(i)\n// a(i) = a(j)\n// a(j) = t\n// t = b(i)\n// b(i) = b(j)\n// b(j) = t\n// }\n sort(a,b)\n ans(0) = min(b(0),v)\n b(0) -= ans(0)\n for (i <- 1 to n){\n if (a(i)-a(i-1)>1){\n ans(i-1) += min(v,b(i-1))\n b(i-1) -= ans(i-1)\n ans(i) += min(v,b(i))\n b(i) -= ans(i)\n }\n else{\n ans(i) = min(v,b(i)+b(i-1)) \n if (ans(i) > b(i-1)){\n b(i) -= ans(i) - b(i-1)\n b(i-1) = 0\n }else {b(i-1) -= ans(i)}\n }\n ans(i) += ans(i-1)\n// println(ans(i))\n }\n \n println(ans(n))\n }\n\n}"}, {"source_code": "object b {\n import scala.math._\n \n def main(args: Array[String]): Unit = {\n var Array(n,v) = readLine.split(\" \").map(_.toInt)\n var a = new Array[Int](n+1)\n var b = new Array[Int](n+1)\n var ans = new Array[Int](n+1)\n for (i <- 0 until n){\n var Array(x,y) = readLine.split(\" \").map(_.toInt)\n a(i) = x\n b(i) = y\n }\n for (i <- 0 until n-1)\n for (j <- i+1 until n)\n if (a(i)>a(j)){\n var t = a(i)\n a(i) = a(j)\n a(j) = t\n t = b(i)\n b(i) = b(j)\n b(j) = t\n }\n ans(0) = min(b(0),v)\n b(0) -= ans(0)\n for (i <- 1 to n){\n ans(i) = min(v,b(i)+b(i-1)) \n if (ans(i) > b(i-1)){\n b(i) -= ans(i) - b(i-1)\n b(i-1) = 0\n }else {b(i-1) -= ans(i)}\n ans(i) += ans(i-1)\n// println(ans(i))\n }\n \n println(ans(n))\n }\n\n}"}, {"source_code": "object b {\n import scala.math._\n \n def sort(xs: Array[Int],ys: Array[Int]) {\n\t\tdef swap(i: Int, j: Int) {\n\t\tval t = xs(i); xs(i) = xs(j); xs(j) = t\n\t\t}\n\t\tdef swap2(i: Int, j: Int) {\n\t\tval t = ys(i); ys(i) = ys(j); ys(j) = t\n\t\t}\n\t\tdef sort1(l: Int, r: Int) {\n\t\tval pivot = xs((l + r) / 2)\n\t\tvar i = l; var j = r\n\t\twhile (i <= j) {\n\t\twhile (xs(i) < pivot) i += 1\n\t\twhile (xs(j) > pivot) j -= 1\n\t\tif (i <= j) {\n\t\tswap(i, j)\n\t\tswap2(i, j)\n\t\ti += 1\n\t\tj -= 1\n\t\t}\n\t\t}\n\t\tif (l < j) sort1(l, j)\n\t\tif (j < r) sort1(i, r)\n\t\t}\n\t\tsort1(0, xs.length - 2)\n\t\t}\n \n def main(args: Array[String]): Unit = {\n var Array(n,v) = readLine.split(\" \").map(_.toInt)\n var a = new Array[Int](n+1)\n var b = new Array[Int](n+1)\n var ans = new Array[Int](n+1)\n for (i <- 0 until n){\n var Array(x,y) = readLine.split(\" \").map(_.toInt)\n a(i) = x\n b(i) = y\n }\n// for (i <- 0 until n-1)\n// for (j <- i+1 until n)\n// if (a(i)>a(j)){\n// var t = a(i)\n// a(i) = a(j)\n// a(j) = t\n// t = b(i)\n// b(i) = b(j)\n// b(j) = t\n// }\n sort(a,b)\n ans(0) = min(b(0),v)\n b(0) -= ans(0)\n for (i <- 1 to n){\n if (a(i)-a(i-1)>1){\n ans(i-1) += v\n b(i-1) -= v\n ans(i) += v\n b(i) -= v\n }\n else{\n ans(i) = min(v,b(i)+b(i-1)) \n if (ans(i) > b(i-1)){\n b(i) -= ans(i) - b(i-1)\n b(i-1) = 0\n }else {b(i-1) -= ans(i)}\n }\n ans(i) += ans(i-1)\n// println(ans(i))\n }\n \n println(ans(n))\n }\n\n}"}, {"source_code": "\n\nobject Bnew {\n import scala.math._\n \n def main(args: Array[String]): Unit = {\n var Array(n,v) = readLine.split(\" \").map(_.toInt)\n var a = new Array[Int](n+1)\n var b = new Array[Int](n+1)\n var ans = new Array[Int](3002)\n var minn = 30000\n var maxx = 0\n var cnt = 0\n for (i <- 0 until n){\n var Array(x,y) = readLine.split(\" \").map(_.toInt)\n ans(x) = y\n minn = min(minn,x)\n maxx = max(maxx,x)\n }\n var bl = false;\n for (i <- minn to maxx){\n if (ans(i)>0){\n if (ans(i+1)==0){\n if (!bl)\n \tcnt += min(2*v,ans(i))\n \telse cnt += min(v,ans(i))\n \tbl = false\n }\n else {\n if (!bl){\n \tcnt += min(2*v,ans(i))\n \tif (ans(i)<2*v){\n \t var coef= min(2*v - ans(i),ans(i+1))\n \t ans(i+1) -= coef\n \t cnt += coef\n \t}\n }\n else {cnt += min(v,ans(i))\n if (ans(i) pivot) j -= 1\n\t\tif (i <= j) {\n\t\tswap(i, j)\n\t\tswap2(i, j)\n\t\ti += 1\n\t\tj -= 1\n\t\t}\n\t\t}\n\t\tif (l < j) sort1(l, j)\n\t\tif (j < r) sort1(i, r)\n\t\t}\n\t\tsort1(0, xs.length - 2)\n\t\t}\n \n def main(args: Array[String]): Unit = {\n var Array(n,v) = readLine.split(\" \").map(_.toInt)\n var a = new Array[Int](n+1)\n var b = new Array[Int](n+1)\n var ans = new Array[Int](n+1)\n for (i <- 0 until n){\n var Array(x,y) = readLine.split(\" \").map(_.toInt)\n a(i) = x\n b(i) = y\n }\n// for (i <- 0 until n-1)\n// for (j <- i+1 until n)\n// if (a(i)>a(j)){\n// var t = a(i)\n// a(i) = a(j)\n// a(j) = t\n// t = b(i)\n// b(i) = b(j)\n// b(j) = t\n// }\n sort(a,b)\n ans(0) = min(b(0),v)\n b(0) -= ans(0)\n for (i <- 1 to n){\n ans(i) = min(v,b(i)+b(i-1)) \n if (ans(i) > b(i-1)){\n b(i) -= ans(i) - b(i-1)\n b(i-1) = 0\n }else {b(i-1) -= ans(i)}\n ans(i) += ans(i-1)\n// println(ans(i))\n }\n \n println(ans(n))\n }\n\n}"}, {"source_code": "\n\nobject Bnew {\n import scala.math._\n \n def main(args: Array[String]): Unit = {\n var Array(n,v) = readLine.split(\" \").map(_.toInt)\n var ans = new Array[Long](3002)\n var minn = 30000\n var maxx = 0\n var cnt = ans(0)\n \n for (i <- 0 until n){\n var Array(x,y) = readLine.split(\" \").map(_.toInt)\n ans(x) += y\n minn = min(minn,x)\n maxx = max(maxx,x)\n }\n var bl = false;\n for (i <- minn to maxx){\n if (ans(i)>0){\n if (ans(i+1)==0){\n if (!bl)\n \tcnt += min(2*v,ans(i))\n \telse cnt += min(v,ans(i))\n \tbl = false\n }\n else {\n if (!bl){\n \tcnt += min(2*v,ans(i))\n \tif (ans(i)<2*v){\n \t var coef= min(2*v - ans(i),ans(i+1))\n \t ans(i+1) -= coef\n \t cnt += coef\n \t}\n }\n else {cnt += min(v,ans(i))\n if (ans(i) copy(bob = bob+1)\n case Node(2,1) => copy(bob = bob+1)\n case Node(1,3) => copy(bob = bob+1)\n case Node(2,3) => copy(alice = alice+1)\n case Node(1,2) => copy(alice = alice+1)\n case Node(3,1) => copy(alice = alice+1)\n case _ => copy(tie = tie+1)\n }\n }\n val numGames = bob + alice + tie\n\n def + (that: ScoreBoard): ScoreBoard = ScoreBoard(bob+that.bob,alice+that.alice,tie+that.tie)\n def - (that: ScoreBoard): ScoreBoard = ScoreBoard(that.bob-bob,that.alice-alice,that.tie-tie)\n def * (times: Long): ScoreBoard = ScoreBoard(bob*times,alice*times,tie*times)\n }\n class Game(val currentScore: ScoreBoard,val nodeToEvaluate: Node, calcNextNode: Node => Node){\n def this(nodeToEvaluate: Node,calcNextNode: Node => Node) = this(ScoreBoard(0,0,0),nodeToEvaluate,calcNextNode)\n def step(): Game = {\n new Game(currentScore.addGame(nodeToEvaluate),calcNextNode(nodeToEvaluate),calcNextNode)\n }\n }\n\n class Graph(){\n val edges = ListBuffer.empty[Edge]\n def addEdge(edge: Edge): Unit = edges.append(edge)\n\n\n private def next(node: Node): Node = {\n edges.find(_.from == node).get.to\n }\n\n val mapCycle = mutable.Map.empty[Node,Option[ScoreBoard]]\n\n def simulateSmall(node: Node, gamesLeft: Int): ScoreBoard = {\n (1 to gamesLeft).foldLeft(new Game(node,next)){\n case (prevGame,_) => {\n prevGame.step()\n }\n }.currentScore\n }\n def findFinalScoreBoard(node: Node, gamesLeft: Long): ScoreBoard = {\n if(gamesLeft > 0){\n if(mapCycle.contains(node)){\n val optScoreBoard = mapCycle(node)\n optScoreBoard.map{ sc =>\n val cyclesRequired = gamesLeft/sc.numGames\n val extraGames: Int = (if(cyclesRequired == 0) gamesLeft else gamesLeft % sc.numGames).toInt\n\n sc*cyclesRequired + simulateSmall(node,extraGames)\n }.getOrElse{\n ScoreBoard(0,0,0).addGame(node) + findFinalScoreBoard(next(node),gamesLeft-1)\n }\n }else{\n (1 to 15).foldLeft(Option(new Game(node,next))){\n case (Some(prevGame), _) =>\n val currentGame = prevGame.step()\n if(currentGame.nodeToEvaluate == node){\n mapCycle += node -> Some(currentGame.currentScore)\n None\n }else{\n Some(currentGame)\n }\n case (None, _ ) => None\n }\n if(!mapCycle.contains(node)){ // no se encontro ciclo\n mapCycle += node -> None\n\n }\n findFinalScoreBoard(node,gamesLeft)\n }\n }\n else{\n ScoreBoard(0,0,0)\n }\n }\n\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}", "positive_code": [{"source_code": "//package edu29\n\nimport scala.io.StdIn\n\nobject C extends App {\n def readArray = StdIn.readLine().split(\" \").map(_.toInt)\n\n val Array(k, a0, b0) = StdIn.readLine().split(\" \").map(_.toLong)\n val alice, bob = Array.fill(3)(readArray)\n def result(i: Int, j: Int) =\n if (i == j) (0L, 0L)\n else if (i - 1 == (j % 3)) (1L, 0L)\n else (0L, 1L)\n\n def go(a: Int = a0.toInt, b: Int = b0.toInt, seen: Map[(Int, Int), Int] = Map.empty, i: Int = 0): (Seq[(Int, Int)], Int) =\n if (seen.contains((a, b))) (seen.toSeq.sortBy(_._2).map(_._1), seen((a, b)))\n else go(alice(a - 1)(b - 1), bob(a - 1)(b - 1), seen + ((a, b) -> i), i + 1)\n\n val (full, init) = go()\n// println(full, init)\n val (pref, cycle) = full.map((result _).tupled).splitAt(init)\n// println(pref, cycle)\n\n def sumPoints(seq: Seq[(Long, Long)]) =\n seq.foldLeft((0L, 0L)) { case ((ap, bp), (a, b)) => (ap + a, bp + b) }\n\n def mulPoints(a: Long, b: Long)(c: Long) = (a * c, b * c)\n val mulp = (mulPoints _).tupled\n\n val (ap, bp) =\n if (k <= pref.length) sumPoints(pref.take(k.toInt))\n else {\n val n = k - pref.length\n val prefp = sumPoints(pref)\n val cyclic = mulp(sumPoints(cycle))(n / cycle.length)\n val last = sumPoints(cycle.take((n % cycle.length).toInt))\n// println(pref, cyclic, last)\n sumPoints(Seq(prefp, cyclic, last))\n }\n\n\n println(s\"$ap $bp\")\n\n}\n"}], "negative_code": [{"source_code": "object Game123t863C extends App {\n import scala.collection.mutable.ListBuffer\n import scala.collection.mutable\n\n import java.io._\n import java.util.StringTokenizer\n solve(System.in,System.out)\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val k = in.nextLong()\n val a = in.nextInt()\n val b = in.nextInt()\n\n val g = new Graph()\n val A = Array.ofDim[Int](5,5)\n val B = Array.ofDim[Int](5,5)\n for{\n i <- 1 to 3\n j <- 1 to 3\n }yield{\n A(i)(j) = in.nextInt()\n }\n\n for{\n i <- 1 to 3\n j <- 1 to 3\n }yield{\n B(i)(j) = in.nextInt()\n }\n\n for{\n i <- 1 to 3\n j <- 1 to 3\n }yield{\n val from = Node(i,j)\n val to = Node(A(i)(j),B(i)(j))\n g.addEdge(Edge(from,to))\n }\n\n val sc = g.findFinalScoreBoard(Node(a,b),k)\n\n out.println(s\"${sc.bob} ${sc.alice}\")\n\n\n\n\n }\n case class Node(a: Int, b: Int)\n case class Edge(from: Node, to: Node)\n case class ScoreBoard(bob: Long, alice: Long, tie: Long){\n def addGame(node: Node): ScoreBoard = {\n node match {\n case Node(3,2) => copy(bob = bob+1)\n case Node(2,1) => copy(bob = bob+1)\n case Node(1,3) => copy(bob = bob+1)\n case Node(2,3) => copy(alice = alice+1)\n case Node(1,2) => copy(alice = alice+1)\n case Node(3,1) => copy(alice = alice+1)\n case _ => copy(tie = tie+1)\n }\n }\n val numGames = bob + alice + tie\n\n def + (that: ScoreBoard): ScoreBoard = ScoreBoard(bob+that.bob,alice+that.alice,tie+that.tie)\n def - (that: ScoreBoard): ScoreBoard = ScoreBoard(that.bob-bob,that.alice-alice,that.tie-tie)\n def * (times: Long): ScoreBoard = ScoreBoard(bob*times,alice*times,tie*times)\n }\n class Game(val currentScore: ScoreBoard,val nodeToEvaluate: Node, calcNextNode: Node => Node){\n def this(nodeToEvaluate: Node,calcNextNode: Node => Node) = this(ScoreBoard(0,0,0),nodeToEvaluate,calcNextNode)\n def step(): Game = {\n new Game(currentScore.addGame(nodeToEvaluate),calcNextNode(nodeToEvaluate),calcNextNode)\n }\n }\n\n class Graph(){\n val edges = ListBuffer.empty[Edge]\n def addEdge(edge: Edge): Unit = edges.append(edge)\n\n\n private def next(node: Node): Node = {\n edges.find(_.from == node).get.to\n }\n\n val mapCycle = mutable.Map.empty[Node,Option[ScoreBoard]]\n\n def simulateSmall(node: Node, gamesLeft: Int): ScoreBoard = {\n (1 to gamesLeft).foldLeft(new Game(node,next)){\n case (prevGame,_) => {\n prevGame.step()\n }\n }.currentScore\n }\n def findFinalScoreBoard(node: Node, gamesLeft: Long): ScoreBoard = {\n if(mapCycle.contains(node)){\n val optScoreBoard = mapCycle(node)\n optScoreBoard.map{ sc =>\n val cyclesRequired = gamesLeft/sc.numGames\n val extraGames: Int = (if(cyclesRequired == 0) gamesLeft else gamesLeft % sc.numGames).toInt\n\n sc*cyclesRequired + simulateSmall(node,extraGames)\n }.getOrElse{\n ScoreBoard(0,0,0).addGame(node) + findFinalScoreBoard(next(node),gamesLeft-1)\n }\n }else{\n (1 to 15).foldLeft(Option(new Game(node,next))){\n case (Some(prevGame), _) =>\n val currentGame = prevGame.step()\n if(currentGame.nodeToEvaluate == node){\n mapCycle += node -> Some(currentGame.currentScore)\n None\n }else{\n Some(currentGame)\n }\n case (None, _ ) => None\n }\n if(!mapCycle.contains(node)){ // no se encontro ciclo\n mapCycle += node -> None\n\n }\n findFinalScoreBoard(node,gamesLeft)\n }\n }\n\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}, {"source_code": "object Game123t863C extends App {\n import scala.collection.mutable.ListBuffer\n import scala.collection.mutable\n\n import java.io._\n import java.util.StringTokenizer\n solve(System.in,System.out)\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val k = in.nextLong()\n val a = in.nextInt()\n val b = in.nextInt()\n\n val g = new Graph()\n val A = Array.ofDim[Int](5,5)\n val B = Array.ofDim[Int](5,5)\n for{\n i <- 1 to 3\n j <- 1 to 3\n }yield{\n A(i)(j) = in.nextInt()\n }\n\n for{\n i <- 1 to 3\n j <- 1 to 3\n }yield{\n B(i)(j) = in.nextInt()\n }\n\n for{\n i <- 1 to 3\n j <- 1 to 3\n }yield{\n val from = Node(i,j)\n val to = Node(A(i)(j),B(i)(j))\n g.addEdge(Edge(from,to))\n }\n\n val sc = g.findFinalScoreBoard(Node(a,b),k)\n\n out.println(s\"${sc.bob} ${sc.alice}\")\n\n\n\n\n }\n case class Node(a: Int, b: Int)\n case class Edge(from: Node, to: Node)\n case class ScoreBoard(bob: Long, alice: Long, tie: Long){\n def addGame(node: Node): ScoreBoard = {\n node match {\n case Node(3,2) => copy(bob = bob+1)\n case Node(2,1) => copy(bob = bob+1)\n case Node(1,3) => copy(bob = bob+1)\n case Node(2,3) => copy(alice = alice+1)\n case Node(1,2) => copy(alice = alice+1)\n case Node(3,1) => copy(alice = alice+1)\n case _ => copy(tie = tie+1)\n }\n }\n val numGames = bob + alice + tie\n\n def + (that: ScoreBoard): ScoreBoard = ScoreBoard(bob+that.bob,alice+that.alice,tie+that.tie)\n def - (that: ScoreBoard): ScoreBoard = ScoreBoard(that.bob-bob,that.alice-alice,that.tie-tie)\n def * (times: Long): ScoreBoard = ScoreBoard(bob*times,alice*times,tie*times)\n }\n class Game(val currentScore: ScoreBoard,val nodeToEvaluate: Node, calcNextNode: Node => Node){\n def this(nodeToEvaluate: Node,calcNextNode: Node => Node) = this(ScoreBoard(0,0,0),nodeToEvaluate,calcNextNode)\n def step(): Game = {\n new Game(currentScore.addGame(nodeToEvaluate),calcNextNode(nodeToEvaluate),calcNextNode)\n }\n }\n\n class Graph(){\n val edges = ListBuffer.empty[Edge]\n def addEdge(edge: Edge): Unit = edges.append(edge)\n\n\n private def next(node: Node): Node = {\n edges.find(_.from == node).get.to\n }\n\n val mapCycle = mutable.Map.empty[Node,Option[ScoreBoard]]\n\n def simulateSmall(node: Node, gamesLeft: Int): ScoreBoard = {\n (1 to gamesLeft).foldLeft(new Game(node,next)){\n case (prevGame,_) => {\n prevGame.step()\n }\n }.currentScore\n }\n def findFinalScoreBoard(node: Node, gamesLeft: Long): ScoreBoard = {\n if(mapCycle.contains(node)){\n val optScoreBoard = mapCycle(node)\n optScoreBoard.map{ sc =>\n val cyclesRequired = gamesLeft/sc.numGames\n val extraGames: Int = (if(cyclesRequired == 0) gamesLeft else gamesLeft % cyclesRequired).toInt\n sc*cyclesRequired + simulateSmall(node,extraGames)\n }.getOrElse{\n ScoreBoard(0,0,0).addGame(node) + findFinalScoreBoard(next(node),gamesLeft-1)\n }\n }else{\n (1 to 11).foldLeft(Option(new Game(node,next))){\n case (Some(prevGame), _) =>\n val currentGame = prevGame.step()\n if(currentGame.nodeToEvaluate == node){\n mapCycle += node -> Some(currentGame.currentScore)\n None\n }else{\n Some(prevGame.step())\n }\n case (None, _ ) => None\n }\n if(!mapCycle.contains(node)){ // no se encontro ciclo\n mapCycle += node -> None\n\n }\n findFinalScoreBoard(node,gamesLeft)\n }\n }\n\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "src_uid": "1241a1aae502b7e4f136da9cf11ffc3d"} {"source_code": "object B154 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n\n val primes = scala.collection.mutable.ArrayBuffer.empty[Int]\n val isComposite = Array.fill(n + 1)(false)\n var i = 2\n while (i <= n) {\n if (!isComposite(i)) primes.append(i)\n var j = 0\n var break = false\n while (j < primes.size && i * primes(j) <= n && !break) {\n isComposite(i * primes(j)) = true\n if (i % primes(j) == 0)\n break = true\n j += 1\n }\n i += 1\n }\n val factors = Array.fill(n + 1)(Array.empty[Int])\n i = 0\n while (i <= n) {\n var x = i\n val idxs = ArrayBuffer.empty[Int]\n var j = 0\n while (j < primes.length && primes(j) * primes(j) <= x) {\n if (x % primes(j) == 0) {\n idxs.append(primes(j))\n while (x % primes(j) == 0) x /= primes(j)\n }\n j += 1\n }\n if (x > 1)\n idxs.append(x)\n factors(i) = idxs.toArray\n i += 1\n }\n\n val arr = Array.fill(n + 1)(-1) // stores number with factor i\n val on = Array.fill(n + 1)(false)\n for (_ <- 0 until m) {\n val str = read.split(' ')\n val num = str(1).toInt\n if (str(0) == \"+\") {\n if (on(num)) {\n out.println(\"Already on\")\n } else {\n var i = 0\n var break = factors(num).find(i => arr(i) != -1)\n if (break.isDefined) {\n out.println(s\"Conflict with ${arr(break.get)}\")\n } else {\n var i = 0\n factors(num).foreach(arr(_) = num)\n on(num) = true\n out.println(\"Success\")\n }\n }\n } else {\n if (!on(num)) {\n out.println(\"Already off\")\n } else {\n factors(num).foreach(arr(_) = -1)\n on(num) = false\n out.println(\"Success\")\n }\n }\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "object B154 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n\n val primes = scala.collection.mutable.ArrayBuffer.empty[Int]\n val isComposite = Array.fill(n + 1)(false)\n var i = 2\n while (i <= n) {\n if (!isComposite(i)) primes.append(i)\n var j = 0\n var break = false\n while (j < primes.size && i * primes(j) <= n && !break) {\n isComposite(i * primes(j)) = true\n if (i % primes(j) == 0)\n break = true\n j += 1\n }\n i += 1\n }\n val factorIndices = Array.fill(n + 1)(Array.empty[Int])\n val poss = cu.Map.empty[Int, Int]\n i = 0\n while (i < primes.length) {\n poss.put(primes(i), i)\n i += 1\n }\n i = 0\n while (i <= n) {\n var x = i\n val idxs = ArrayBuffer.empty[Int]\n var j = 0\n while (j < primes.length && primes(j) * primes(j) <= x) {\n if (x % primes(j) == 0) {\n idxs.append(j)\n while (x % primes(j) == 0) x /= primes(j)\n }\n j += 1\n }\n if (x > 1)\n idxs.append(poss(x))\n factorIndices(i) = idxs.toArray.clone()\n i += 1\n }\n\n val arr = Array.fill(primes.length)(-1) // stores number with factor i\n val on = Array.fill(n + 1)(false)\n for (_ <- 0 until m) {\n val str = read.split(' ')\n val num = str(1).toInt\n if (str(0) == \"+\") {\n if (on(num)) {\n out.println(\"Already on\")\n } else {\n var i = 0\n var break = factorIndices(num).find(i => arr(i) != -1)\n if (break.isDefined) {\n out.println(s\"Conflict with ${arr(break.get)}\")\n } else {\n var i = 0\n factorIndices(num).foreach(arr(_) = num)\n on(num) = true\n out.println(\"Success\")\n }\n }\n } else {\n if (!on(num)) {\n out.println(\"Already off\")\n } else {\n factorIndices(num).foreach(arr(_) = -1)\n on(num) = false\n out.println(\"Success\")\n }\n }\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object B154 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n\n val primes = scala.collection.mutable.ArrayBuffer.empty[Int]\n val isComposite = Array.fill(n + 1)(false)\n var i = 2\n while (i <= n) {\n if (!isComposite(i)) primes.append(i)\n var j = 0\n var break = false\n while (j < primes.size && i * primes(j) <= n && !break) {\n isComposite(i * primes(j)) = true\n if (i % primes(j) == 0)\n break = true\n j += 1\n }\n i += 1\n }\n val factors = ArrayBuffer.empty[ArrayBuffer[Int]]\n i = 0\n while (i <= n) {\n var x = i\n val idxs = ArrayBuffer.empty[Int]\n var j = 0\n while (j < primes.length && primes(j) * primes(j) <= x) {\n if (x % primes(j) == 0) {\n idxs.append(primes(j))\n while (x % primes(j) == 0) x /= primes(j)\n }\n j += 1\n }\n if (x > 1)\n idxs.append(x)\n factors.append(idxs)\n i += 1\n }\n\n val arr = Array.fill(n + 1)(-1) // stores number with factor i\n val on = Array.fill(n + 1)(false)\n for (_ <- 0 until m) {\n val str = read.split(' ')\n val num = str(1).toInt\n if (str(0) == \"+\") {\n if (on(num)) {\n out.println(\"Already on\")\n } else {\n var i = 0\n var break = factors(num).find(i => arr(i) != -1)\n if (break.isDefined) {\n out.println(s\"Conflict with ${arr(break.get)}\")\n } else {\n var i = 0\n factors(num).foreach(arr(_) = num)\n on(num) = true\n out.println(\"Success\")\n }\n }\n } else {\n if (!on(num)) {\n out.println(\"Already off\")\n } else {\n factors(num).foreach(arr(_) = -1)\n on(num) = false\n out.println(\"Success\")\n }\n }\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import collection.mutable\nimport java.io._\n\n/**\n * Created by IntelliJ IDEA.\n * User: User\n * Date: 29.02.12\n * Time: 5:17\n * To change this template use File | Settings | File Templates.\n */\nobject D {\n def main(args: Array[String]) {\n val Array(colliderCount, requestCount) = readLine split ' ' map (str => str.toInt)\n val colliders: Array[Collider] = Array((0 to colliderCount) map (_ => new Collider): _*)\n val conflicts = new Array[Int](1 + colliderCount)\n val output = new BufferedWriter(new OutputStreamWriter(System.out))\n for (prime <- 2 to colliderCount filter (i => colliders(i).primes == Nil)) {\n for (num <- (prime to colliderCount by prime)) {\n colliders(num).primes ::= prime\n }\n }\n for (i <- (1 to requestCount)) {\n val line = readLine\n val sign = line(0)\n val num = line.split(\" \")(1).toInt\n val collider = colliders(num)\n (sign, collider.state) match {\n case ('+', true) => output.write(\"Already on\\n\")\n case ('-', false) => output.write(\"Already off\\n\")\n case ('+', false) => {\n collider.primes.find(prime => conflicts(prime) > 0) match {\n case Some(prime) => output.write(\"Conflict with %d\\n\".format(conflicts(prime)))\n case None => {\n collider.primes.foreach(prime => conflicts(prime) = num)\n collider.state = true\n output.write(\"Success\\n\")\n }\n }\n }\n case ('-', true) => {\n collider.primes.foreach(prime => conflicts(prime) = 0)\n collider.state = false\n output.write(\"Success\\n\")\n }\n }\n }\n output.flush\n }\n\n class Collider {\n var primes: List[Int] = Nil\n var state = false\n }\n\n}\n\n"}, {"source_code": "import collection.mutable\nimport java.io._\n\n/**\n * Created by IntelliJ IDEA.\n * User: User\n * Date: 29.02.12\n * Time: 5:17\n * To change this template use File | Settings | File Templates.\n */\nobject D {\n val output = new BufferedWriter(new OutputStreamWriter(System.out))\n val input = new BufferedReader(new InputStreamReader(System.in))\n\n def main(args: Array[String]) {\n val Array(colliderCount, requestCount) = input.readLine split ' ' map (str => str.toInt)\n val colliders: Array[Collider] = Array((0 to colliderCount) map (_ => new Collider): _*)\n val conflicts = new Array[Int](1 + colliderCount)\n\n for (prime <- 2 to colliderCount filter (i => colliders(i).primes == Nil)) {\n for (num <- (prime to colliderCount by prime)) {\n colliders(num).primes ::= prime\n }\n }\n for (i <- (1 to requestCount)) {\n val line = input.readLine\n val sign = line(0)\n val num = line.split(\" \")(1).toInt\n val collider = colliders(num)\n (sign, collider.state) match {\n case ('+', true) => output.write(\"Already on\\n\")\n case ('-', false) => output.write(\"Already off\\n\")\n case ('+', false) => {\n collider.primes.find(prime => conflicts(prime) > 0) match {\n case Some(prime) => output.write(\"Conflict with %d\\n\".format(conflicts(prime)))\n case None => {\n collider.primes.foreach(prime => conflicts(prime) = num)\n collider.state = true\n output.write(\"Success\\n\")\n }\n }\n }\n case ('-', true) => {\n collider.primes.foreach(prime => conflicts(prime) = 0)\n collider.state = false\n output.write(\"Success\\n\")\n }\n }\n }\n output.flush\n }\n\n class Collider {\n var primes: List[Int] = Nil\n var state = false\n }\n\n}\n\n"}, {"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport java.io.File\nimport java.io.BufferedOutputStream\nimport java.io.PrintWriter\n\nobject D {\n object Int {\n def unapply(s: String) : Some[Int] = Some(s.toInt)\n }\n val N = 100001\n \n val factors = new Array[ListBuffer[Int]](N)\n val active = new Array[Boolean](N)\n \n factors.indices.foreach(factors(_) = ListBuffer[Int]())\n \n (2 until N/2).foreach (fc => (fc until N by fc).foreach (factors(_) += fc))\n \n val usedBy = new Array[Int](N)\n \n def main(args: Array[String]): Unit = {\n val output = new PrintWriter(new BufferedOutputStream(System.out, 100000))\n\n val lines = scala.io.Source.stdin.getLines()\n lines.next()\n lines.foreach( cmd => {\n val s = cmd.split(\" \")\n val n = s(1).toInt\n output.println( if (s(0).equals(\"+\")) {\n if (active(n)) \"Already on\" \n else factors(n).find(usedBy(_) > 0) match { case Some(uf) => \"Conflict with \" + usedBy(uf); case None => factors(n).foreach(usedBy(_) = n); active(n) = true; \"Success\" }\n } else {\n if (!active(n)) \"Already off\" \n else { factors(n).foreach(usedBy(_) = 0); active(n) = false; \"Success\" }\n })\n })\n\n output.close()\n}\n}"}], "negative_code": [{"source_code": "object B154 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n case class Sieve(to: Int) {\n val primes = scala.collection.mutable.ArrayBuffer.empty[Int]\n val isComposite = Array.fill(to + 1)(false)\n def sieve(): Unit = { // Works in linear time\n for (i <- 2 until to) {\n if (!isComposite(i)) primes.append(i)\n var j = 0\n var break = false\n while (j < primes.size && i * primes(j) < to && !break) {\n isComposite(i * primes(j)) = true\n if (i % primes(j) == 0)\n break = true\n j += 1\n }\n }\n }\n }\n val s = Sieve(100000 + 10)\n s.sieve()\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val arr = Array.fill(s.primes.length)(-1)\n val on = cu.Set.empty[Int]\n for (_ <- 0 until m) {\n val str = read.split(' ')\n val num = str(1).toInt\n if (str(0) == \"+\") {\n if (on.contains(num)) {\n out.println(\"Already on\")\n } else {\n var i = 0\n var bad = -1\n while (bad == -1 && i < arr.length && s.primes(i) <= num) {\n if (num % s.primes(i) == 0) {\n if (arr(i) == -1) {\n arr(i) = num\n } else {\n bad = arr(i)\n }\n }\n i += 1\n }\n if (bad != -1) {\n out.println(s\"Conflict with $bad\")\n } else {\n on.add(num)\n out.println(\"Success\")\n }\n }\n } else {\n if (!on.contains(num)) {\n out.println(\"Already off\")\n } else {\n var i = 0\n while (i < arr.length && s.primes(i) <= num) {\n if (num % s.primes(i) == 0) {\n arr(i) = -1\n }\n i += 1\n }\n on.remove(num)\n out.println(\"Success\")\n }\n }\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object B154 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n\n val primes = scala.collection.mutable.ArrayBuffer.empty[Int]\n val isComposite = Array.fill(n + 1)(false)\n var i = 2\n while (i <= n) {\n if (!isComposite(i)) primes.append(i)\n var j = 0\n var break = false\n while (j < primes.size && i * primes(j) <= n && !break) {\n isComposite(i * primes(j)) = true\n if (i % primes(j) == 0)\n break = true\n j += 1\n }\n i += 1\n }\n val factors = Array.fill(n + 1)(Array.empty[Int])\n i = 0\n while (i <= n) {\n var x = i\n val idxs = ArrayBuffer.empty[Int]\n var j = 0\n while (j < primes.length && primes(j) * primes(j) <= x) {\n if (x % primes(j) == 0) {\n idxs.append(j)\n while (x % primes(j) == 0) x /= primes(j)\n }\n j += 1\n }\n if (x > 1)\n idxs.append(x)\n factors(i) = idxs.toArray.clone()\n i += 1\n }\n\n val arr = Array.fill(n + 1)(-1) // stores number with factor i\n val on = Array.fill(n + 1)(false)\n for (_ <- 0 until m) {\n val str = read.split(' ')\n val num = str(1).toInt\n if (str(0) == \"+\") {\n if (on(num)) {\n out.println(\"Already on\")\n } else {\n var i = 0\n var break = factors(num).find(i => arr(i) != -1)\n if (break.isDefined) {\n out.println(s\"Conflict with ${arr(break.get)}\")\n } else {\n var i = 0\n factors(num).foreach(arr(_) = num)\n on(num) = true\n out.println(\"Success\")\n }\n }\n } else {\n if (!on(num)) {\n out.println(\"Already off\")\n } else {\n factors(num).foreach(arr(_) = -1)\n on(num) = false\n out.println(\"Success\")\n }\n }\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\n\nobject D {\n object Int {\n def unapply(s: String) : Some[Int] = Some(s.toInt)\n }\n val N = 100000\n \n val factors = new Array[ListBuffer[Int]](N)\n val active = new Array[Boolean](N)\n \n factors.indices.foreach(factors(_) = ListBuffer[Int]())\n \n (1 until N/2).foreach (fc => (fc until N by fc).foreach (factors(_) += fc))\n \n val usedBy = new Array[Int](10000)\n \n def main(args: Array[String]): Unit = {\n scala.io.Source.stdin.getLines().toList.tail.foreach( cmd => {\n System.out.println (cmd.split(\" \").toList match {\n case \"+\"::Int(n)::_ => \n if (active(n)) \"Already on\" \n else factors(n).find(usedBy(_) > 0) match { case Some(uf) => \"Conflict with \" + usedBy(uf); case None => factors(n).foreach(usedBy(_) = n); active(n) = true; \"Success\" }\n case \"-\"::Int(n)::_ =>\n if (!active(n)) \"Already off\" \n else { factors(n).foreach(usedBy(_) = 0); active(n) = false; \"Success\" }\n })\n })\n }\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\n\nobject D {\n object Int {\n def unapply(s: String) : Some[Int] = Some(s.toInt)\n }\n val N = 100000\n \n val factors = new Array[ListBuffer[Int]](N)\n val active = new Array[Boolean](N)\n \n factors.indices.foreach(factors(_) = ListBuffer[Int]())\n \n (2 until N/2).foreach (fc => (fc*2 until N by fc).foreach (factors(_) += fc))\n \n val usedBy = new Array[Int](10000)\n \n def main(args: Array[String]): Unit = {\n scala.io.Source.stdin.getLines().toList.tail.foreach( cmd => {\n System.out.println (cmd.split(\" \").toList match {\n case \"+\"::Int(n)::_ => \n if (active(n)) \"Already on\" \n else factors(n).find(usedBy(_) > 0) match { case Some(uf) => \"Conflict with \" + usedBy(uf); case None => factors(n).foreach(usedBy(_) = n); active(n) = true; \"Success\" }\n case \"-\"::Int(n)::_ =>\n if (!active(n)) \"Already off\" \n else { factors(n).foreach(usedBy(_) = 0); active(n) = false; \"Success\" }\n })\n })\n }\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport java.io.File\nimport java.io.BufferedOutputStream\nimport java.io.PrintWriter\n\nobject D {\n object Int {\n def unapply(s: String) : Some[Int] = Some(s.toInt)\n }\n val N = 100001\n \n val factors = new Array[ListBuffer[Int]](N)\n val active = new Array[Boolean](N)\n \n factors.indices.foreach(factors(_) = ListBuffer[Int]())\n \n (2 until N/2).foreach (fc => (fc until N by fc).foreach (factors(_) += fc))\n \n val usedBy = new Array[Int](N)\n \n def main(args: Array[String]): Unit = {\n val output = new PrintWriter(new BufferedOutputStream(System.out, 100000))\n\n val lines = scala.io.Source.stdin.getLines()\n lines.next()\n lines.foreach( cmd => {\n val s = cmd.split(\" \")\n val n = s(1).toInt\n output.println( if (s(0).equals(\"+\")) {\n if (active(n)) \"Already on\" \n else factors(n).find(usedBy(_) > 0) match { case Some(uf) => \"Conflict with \" + usedBy(uf); case None => factors(n).foreach(usedBy(_) = n); active(n) = true; \"Success\" }\n } else {\n if (!active(n)) \"Already off\" \n else { factors(n).foreach(usedBy(_) = 0); active(n) = false; \"Success\" }\n })\n })\n}\n}"}], "src_uid": "6cec3662101b419fb734b7d6664fdecd"} {"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, x = nextInt\n val as = nextLongs(n).sorted.reverse\n var res = 0\n var cnt = 0\n for (a <- as) {\n cnt += 1\n if (a * cnt >= x) {\n cnt = 0\n res += 1\n }\n }\n\n out.println(res)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n\n val t = readInt()\n 1 to t foreach { _ =>\n val Array(n, x) = readLine().split(\" \").map(_.toInt)\n val A = readLine().split(\" \").map(_.toInt).sorted\n\n var teams = 0\n var current = 0\n for {\n i <- A.length - 1 to 0 by -1\n } {\n current += 1\n if (A(i) * current >= x) {\n teams += 1\n current = 0\n }\n }\n println(teams)\n }\n}\n"}, {"source_code": "\n\nimport java.util\n\nobject ProblemC extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n\n for (_ <- 1 to t) {\n val n = in.nextInt()\n val k = in.nextInt()\n val a = new Array[Int](n)\n for (i <- a.indices) {\n a(i) = in.nextInt()\n }\n\n util.Arrays.sort(a)\n\n var result = 0\n\n var i = a.length\n var count: Long = 0\n while (i > 0) {\n i = i - 1\n count = count + 1\n if (count * a(i) >= k) {\n result = result + 1\n count = 0\n }\n }\n\n println(result)\n }\n}\n"}, {"source_code": "object C extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, x) = readLine().split(\" \").map(_.toInt)\n val an = readLine().split(\" \").map(_.toInt).sorted(Ordering.Int.reverse)\n\n val m = an.lastIndexWhere(_ >= x) match {\n case -1 => if (an.head >= x) n else 0\n case i => i + 1\n }\n\n val l = an.drop(m).foldLeft((0, 0)) {\n case ((l, r), a) =>\n if ((r + 1) * a >= x) (l + 1, 0)\n else (l, r + 1)\n }._1\n\n val ans = m + l\n\n println(ans)\n }\n}\n"}, {"source_code": "object C extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, x) = readLine().split(\" \").map(_.toInt)\n val an = readLine().split(\" \").map(_.toInt).sorted(Ordering.Int.reverse)\n\n val ans = an\n .foldLeft((0, 0)) {\n case ((count, remains), a) =>\n if (a * (remains + 1) >= x) (count + 1, 0)\n else (count, remains + 1)\n }\n ._1\n\n println(ans)\n }\n}\n"}], "negative_code": [], "src_uid": "8a6953a226abef41a44963c9b4998a25"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n\n val V = \"aiueo\"\n\n REP(math.sqrt(N).toInt, 1) { n =>\n if (N % n == 0) {\n val m = N / n\n if (n >= 5 && m >= 5) {\n REP(n) { i =>\n REP(m) { j =>\n out.print(V((i + j) % 5))\n }\n }\n out.println()\n\n return\n }\n }\n }\n\n out.println(-1)\n }\n}", "positive_code": [{"source_code": "object _1166B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val k = io.read[Int]\n val vowels = \"aeiou\"\n\n val ans = (vowels.length to k).find(i => k%i == 0 && k/i >= vowels.length) match {\n case None => \"-1\"\n case Some(n) =>\n val m = k/n\n Vector.tabulate(n, m)((i, j) => vowels((i + j)%vowels.length)).map(_.mkString).mkString\n }\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.math.sqrt\nimport scala.util.control.Breaks._\n\nobject Main extends App {\n\t\n\tdef isPrimeNumber (n : Double) : Boolean = {\n\t\tvar max : Int = sqrt(n).toInt\n\t\t\n\t\tfor ( i <- 2 to max ) {\n\t\t\tif ( n%i == 0 ) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn true\n\t}\n\t\n\tvar m = Console.readLine\n\tvar n : Int = m.toInt\n\tvar arrChar : Array[Char] = Array('a', 'e', 'i', 'o', 'u')\n\t\n\tif ( isPrimeNumber(n.toDouble) || n < 25 ) {\n\t\tprintln(-1)\n\t\tsys.exit(0)\n\t}\n\t\n\tvar row : Int = 5\n\tvar col : Int = 0\n\tvar max : Int = n/5 + 1\n\t\n\twhile ( row < max && col == 0) {\n\t\tif ( n%row == 0 ) {\n\t\t\tcol = n/row - 1\n\t\t\trow -= 1\n\t\t} else {\n\t\t\trow += 1\n\t\t}\n\t}\n\t\n\tif ( col < 4 ) {\n\t\tprintln(-1)\n\t\tsys.exit(0)\n\t}\n\t\n\tfor ( i <- 0 to row ) {\n\t\tfor ( j <- 0 to col) {\n\t\t\tprint(arrChar((i+j) % 5))\n\t\t}\n\t}\n\t\n\tprintln()\n\t\n}"}], "negative_code": [{"source_code": "import scala.math.sqrt\nimport scala.util.control.Breaks._\n\nobject Main extends App {\n\t\n\tdef isPrimeNumber (n : Double) : Boolean = {\n\t\tvar max : Int = sqrt(n).toInt\n\t\t\n\t\tfor ( i <- 2 to max ) {\n\t\t\tif ( n%i == 0 ) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn true\n\t}\n\t\n\tvar m = Console.readLine\n\tvar n : Int = m.toInt\n\tvar arrChar : Array[Char] = Array('a', 'e', 'i', 'o', 'u')\n\t\n\tif ( isPrimeNumber(n.toDouble) || n < 25 ) {\n\t\tprintln(-1)\n\t\tsys.exit(0)\n\t}\n\t\n\tvar row : Int = 5\n\tvar col : Int = 0\n\t\n\twhile ( col == 0) {\n\t\tif ( n%row == 0 ) {\n\t\t\tcol = n/row - 1\n\t\t\trow -= 1\n\t\t} else {\n\t\t\trow += 1\n\t\t}\n\t}\n\t\n\tfor ( i <- 0 to row ) {\n\t\tfor ( j <- 0 to col) {\n\t\t\tprint(arrChar((i+j) % 5))\n\t\t}\n\t}\n\t\n\tprintln()\n\t\n}"}, {"source_code": "import scala.math.sqrt\nimport scala.util.control.Breaks._\n\nobject Main extends App {\n\t\n\tdef isPrimeNumber (n : Double) : Boolean = {\n\t\tvar max : Int = sqrt(n).toInt\n\t\t\n\t\tfor ( i <- 2 to max ) {\n\t\t\tif ( n%i == 0 ) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn true\n\t}\n\t\n\tvar m = Console.readLine\n\tvar n : Int = m.toInt\n\tvar arrChar : Array[Char] = Array('a', 'e', 'i', 'o', 'u')\n\t\n\tif ( isPrimeNumber(n.toDouble) || n < 25 ) {\n\t\tprintln(-1)\n\t\tsys.exit(0)\n\t}\n\t\n\tvar row : Int = 5\n\tvar col : Int = 0\n\t\n\twhile ( col == 0) {\n\t\tif ( n%row == 0 ) {\n\t\t\tcol = n/row - 1\n\t\t\trow -= 1\n\t\t} else {\n\t\t\trow += 1\n\t\t}\n\t}\n\t\n\tfor ( i <- 0 to row ) {\n\t\tfor ( j <- 0 to col) {\n\t\t\tif ( i < 5 && j < 5) {\n\t\t\t\tprint(arrChar((i+j) % 5))\n\t\t\t} else {\n\t\t\t\tprint('b')\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintln()\n\t\n}"}, {"source_code": "object _1166B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val k = io.read[Int]\n val vowels = \"aeiou\"\n\n val ans = (vowels.length to k).find(i => k%i == 0 && k/i >= vowels.length) match {\n case None => \"-1\"\n case _ => Vector.tabulate(k)(i => vowels(i%vowels.length)).mkString\n }\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "933167c31c0f53a43e840cc6cf153f8d"} {"source_code": "object P034A extends App {\n val n = readInt\n val a = readLine.split(' ').map(_.toInt)\n val next = (x: Int) => (x+1) % n\n val b = for (i <- 0 to n-1) yield math.abs(a(i)-a(next(i)))\n val pos = b.indexOf(b min)\n printf(\"%d %d\\n\", pos+1, next(pos)+1)\n}\n\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val res = data.sliding(2).map(t => Math.abs(t.last - t.head)).zipWithIndex.min\n val firstLast = Math.abs(data.head - data.last)\n if (firstLast > res._1)\n println(s\"${res._2 + 1} ${res._2 + 2}\")\n else\n println(s\"$n 1\")\n}"}, {"source_code": "object A34 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val heights = readInts(n)\n var x = 0\n var y = heights.length-1\n var max = math.abs(heights(y)-heights(x))\n for(i <- 0 until heights.length-1) {\n if(math.abs(heights(i)-heights(i+1)) < max) {\n x = i\n y = i + 1\n max = math.abs(heights(i)-heights(i+1))\n }\n }\n out.println(s\"${x+1} ${y+1}\")\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject P034A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val A = Array.fill(N)(sc.nextInt)\n\n val d: PartialFunction[List[Int], Int] = { case List(i, j) => (A(i) - A(j)).abs }\n val res = List.tabulate(N + 1)(_ % N).sliding(2).toList.sortBy(d).head.map(_ + 1)\n\n out.println(res.mkString(\" \"))\n out.close\n}\n\n\n\n\n\n"}, {"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var n = readInt;\n var arr = readLine.split(\" \").zipWithIndex;\n var a = arr.flatMap(x => for (y <- arr if (math.abs(x._2 - y._2) == 1 || math.abs(x._2 - y._2) == n - 1)) yield (x, y));\n var min = a.reduceLeft((a, b) => if (math.abs(a._1._1.toInt - a._2._1.toInt) < math.abs(b._1._1.toInt - b._2._1.toInt)) a else b);\n println((min._1._2 + 1) + \" \" + (min._2._2 + 1));\n }\n\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val a1 = a.zipWithIndex\n val a2 = (a1 ++ Seq(a1(0))).sliding(2).map(s => ((s(0)._1 - s(1)._1).abs, (s(0)._2, s(1)._2)))\n val t = a2.toList.sortBy(_._1).apply(0)\n println((t._2._1 + 1) + \" \" + (t._2._2 + 1))\n }\n}"}], "negative_code": [], "src_uid": "facd9cd4fc1e53f50a1e6f947d78e942"} {"source_code": "object B extends App {\n import scala.collection.mutable\n import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}\n\n solve()\n\n def solve(): Unit = {\n val in = new StreamTokenizer(new BufferedReader(new InputStreamReader((System.in))))\n\n @inline def nextInt = {\n in.nextToken()\n in.nval.asInstanceOf[Int]\n }\n\n @inline def canSort(arr: Array[Int], ex: mutable.Set[Int]): Boolean = {\n if (arr.length == 1) {\n return true\n }\n\n var anyExchange = true\n while(anyExchange) {\n anyExchange = false\n for (i <- 0 until arr.length - 1) {\n if (arr(i) > arr(i + 1)) {\n if (ex.contains(i + 1)) {\n val t = arr(i)\n arr(i) = arr(i + 1)\n arr(i + 1) = t\n anyExchange = true\n }\n }\n }\n }\n\n for (i <- 0 until arr.length - 1) {\n if (arr(i) > arr(i + 1)) {\n return false\n }\n }\n true\n }\n\n val t = nextInt\n for (_ <- 1 to t) {\n val (n, m) = (nextInt, nextInt)\n val array = new Array[Int](n)\n val exchangable = new mutable.HashSet[Int]()\n\n for (i <- 0 until n) {\n array(i) = nextInt\n }\n for (_ <- 0 until m) {\n exchangable.add(nextInt)\n }\n\n val can = canSort(array, exchangable)\n println(if(can) \"YES\" else \"NO\")\n }\n }\n\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C624(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C624(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val n = ni()\n val m = ni()\n\n val a = na(n)\n val p = Array.fill[Int](n+1)(0)\n REP(m) { _ =>\n p(ni()) += 1\n }\n\n var continue = true\n\n while (continue) {\n continue = false\n REP(n-1) { i =>\n if(a(i) > a(i+1)) {\n if(p(i+1) > 0) {\n val x = a(i+1)\n a(i+1) = a(i)\n a(i) = x\n continue = true\n }\n }\n }\n }\n// out.println(a.mkString(\" \"))\n REP(n-1) { i =>\n if(a(i) > a(i+1)) {\n continue = true\n }\n }\n if(continue) out.println(\"NO\")\n else out.println(\"YES\")\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\nobject B extends App {\n import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}\n\n solve()\n\n def solve(): Unit = {\n val in = new StreamTokenizer(new BufferedReader(new InputStreamReader((System.in))))\n\n @inline def nextInt = {\n in.nextToken()\n in.nval.asInstanceOf[Int]\n }\n\n @inline def canSort(arr: Array[Int], ex: mutable.Set[Int]): Boolean = {\n if (arr.length == 1) {\n return true\n }\n\n for (i <- 0 until arr.length - 1) {\n if (arr(i) > arr(i + 1)) {\n if (ex.contains(i + 1)) {\n val t = arr(i)\n arr(i) = arr(i + 1)\n arr(i + 1) = t\n } else {\n return false\n }\n }\n }\n for (i <- 0 until arr.length - 1) {\n if (arr(i) > arr(i + 1)) {\n return false\n }\n }\n true\n }\n\n val t = nextInt\n for (_ <- 1 to t) {\n val (n, m) = (nextInt, nextInt)\n val array = new Array[Int](n)\n val exchangable = new mutable.HashSet[Int]()\n\n for (i <- 0 until n) {\n array(i) = nextInt\n }\n for (_ <- 0 until m) {\n exchangable.add(nextInt)\n }\n\n val can = canSort(array, exchangable)\n println(if(can) \"YES\" else \"NO\")\n }\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject B extends App {\n import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}\n\n solve()\n\n def solve(): Unit = {\n val in = new StreamTokenizer(new BufferedReader(new InputStreamReader((System.in))))\n\n @inline def nextInt = {\n in.nextToken()\n in.nval.asInstanceOf[Int]\n }\n\n @inline def canSort(arr: Array[Int], ex: mutable.Set[Int]): Boolean = {\n if (arr.length == 1) {\n return true\n }\n\n for (i <- 0 until arr.length - 1) {\n if (arr(i) > arr(i + 1)) {\n if (ex.contains(i + 1)) {\n val t = arr(i)\n arr(i) = arr(i + 1)\n arr(i + 1) = t\n } else {\n return false\n }\n }\n }\n true\n }\n\n val t = nextInt\n for (_ <- 1 to t) {\n val (n, m) = (nextInt, nextInt)\n val array = new Array[Int](n)\n val exchangable = new mutable.HashSet[Int]()\n\n for (i <- 0 until n) {\n array(i) = nextInt\n }\n for (_ <- 0 until m) {\n exchangable.add(nextInt)\n }\n\n val can = canSort(array, exchangable)\n println(if(can) \"YES\" else \"NO\")\n }\n }\n\n}\n"}, {"source_code": "object B extends App {\n import scala.collection.mutable\n import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}\n\n solve()\n\n def solve(): Unit = {\n val in = new StreamTokenizer(new BufferedReader(new InputStreamReader((System.in))))\n\n @inline def nextInt = {\n in.nextToken()\n in.nval.asInstanceOf[Int]\n }\n\n @inline def canSort(arr: Array[Int], ex: mutable.Set[Int]): Boolean = {\n if (arr.length == 1) {\n return true\n }\n\n var anyExchange = true\n while(anyExchange) {\n for (i <- 0 until arr.length - 1) {\n anyExchange = false\n if (arr(i) > arr(i + 1)) {\n if (ex.contains(i + 1)) {\n val t = arr(i)\n arr(i) = arr(i + 1)\n arr(i + 1) = t\n anyExchange = true\n }\n }\n }\n }\n\n for (i <- 0 until arr.length - 1) {\n if (arr(i) > arr(i + 1)) {\n return false\n }\n }\n true\n }\n\n val t = nextInt\n for (_ <- 1 to t) {\n val (n, m) = (nextInt, nextInt)\n val array = new Array[Int](n)\n val exchangable = new mutable.HashSet[Int]()\n\n for (i <- 0 until n) {\n array(i) = nextInt\n }\n for (_ <- 0 until m) {\n exchangable.add(nextInt)\n }\n\n val can = canSort(array, exchangable)\n println(if(can) \"YES\" else \"NO\")\n }\n }\n\n}\n"}], "src_uid": "e1481b9d940407da75e11355b580f459"} {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val n = lines.next().toInt\n val line = (0 :: lines.next().split(' ').map(_.toInt).reverse.toList).sliding(2).map(_.sum).toList.reverse\n println(line.mkString(\" \"))\n}\n", "positive_code": [{"source_code": "object A712 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readLongs(n)\n val res = Array.fill(n)(0L)\n for(i <- in.indices) {\n if(i != n-1) {\n res(i) = in(i) + in(i+1)\n } else {\n res(i) = in(i)\n }\n }\n println(res.mkString(\" \"))\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _712A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll}\n val bs = read[Vector[Int]] :+ 0\n val as = bs.sliding(2).map(_.sum)\n\n write(as mkString \" \")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "fa256021dc519f526ef3878cce32ff31"} {"source_code": "object SystemAdministrator22C extends App {\n import java.io._\n import java.util.StringTokenizer\n solve(System.in,System.out)\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val n = in.nextInt()\n val m = in.nextInt()\n val v = in.nextInt()\n\n val stringBuilder = new StringBuilder()\n if(m>=n-1 && m <= (((n-1)*(n-2))/2+1)){\n val x = if(v == 1) 2 else 1\n\n def printEdges(node: Int,edgesToPrint: Int): Int = {\n\n if(node == v){\n for(i <- 1 to n){\n\n if(i != v) {\n stringBuilder.append(s\"$v $i\").append(System.lineSeparator())\n }\n }\n edgesToPrint-(n-1)\n }else{\n if(node == x){\n edgesToPrint\n }else{\n var i = node+1\n var counter = edgesToPrint\n while( counter > 0 && i<=n){\n if(i != x && i != v){\n stringBuilder.append(s\"$node $i\").append(System.lineSeparator())\n counter -= 1\n }\n i += 1\n }\n counter\n }\n }\n }\n\n var restEdges = printEdges(v,m)\n var indx = 1\n\n while(restEdges > 0){\n if(indx != v){\n restEdges = printEdges(indx,restEdges)\n }\n indx += 1\n\n }\n\n }else{\n stringBuilder.append(-1)\n }\n\n out.println(stringBuilder.toString())\n\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = return next().toInt\n }\n}", "positive_code": [{"source_code": "object SystemAdministrator22C extends App {\n import java.io._\n import java.util.StringTokenizer\n solve(System.in,System.out)\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val n = in.nextInt()\n val m = in.nextInt()\n val v = in.nextInt()\n\n val stringBuilder = new StringBuilder()\n if(m>=n-1 && m <= (((n-1)*(n-2))/2+1)){\n val x = if(v == 1) 2 else 1\n\n def printEdges(node: Int,edgesToPrint: Int): Int = {\n\n if(node == v){\n for(i <- 1 to n){\n\n if(i != v) {\n stringBuilder.append(s\"$v $i\").append(System.lineSeparator())\n }\n }\n edgesToPrint-(n-1)\n }else{\n if(node == x){\n edgesToPrint\n }else{\n\n (node +1 to n).foldLeft(edgesToPrint)((edges,i) => {\n if(i == x || i == v || edges == 0){\n edges\n }else{\n stringBuilder.append(s\"$node $i\").append(System.lineSeparator())\n edges-1\n }\n })\n\n }\n }\n }\n\n (1 to n).foldLeft(printEdges(v,m))((restEdges,indx) => {\n if(indx == v || restEdges==0){\n restEdges\n }else{\n printEdges(indx,restEdges)\n }\n })\n\n }else{\n stringBuilder.append(-1)\n }\n\n out.println(stringBuilder.toString())\n\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = return next().toInt\n }\n}\n"}], "negative_code": [], "src_uid": "959709bfe7b26a4b9f2e7430350650a9"} {"source_code": "import scala.util.control.Breaks\n\n//https://codeforces.com/problemset/problem/1327/B\nobject PrincessesAndPrinces {\n def main(args: Array[String]): Unit = {\n val in = scala.io.StdIn\n val testCases = in.readLine().toInt\n for (t <- 0 until testCases) {\n val n = in.readLine().toInt\n val arr=new Array[Array[Int]](n)\n for (i <- 0 until n) {\n val l=in.readLine()\n if(l.length>1) {\n arr(i) = l.substring(l.indexOf(\" \") + 1).split(\" \").map(_.toInt - 1)\n }\n }\n val marriedPrinces=Array.fill[Boolean](n)(false)\n val marriedPrincesses=Array.fill[Boolean](n)(false)\n var unmarriedPrincesses=0\n for (i <- 0 until n) {\n Breaks.breakable {\n if( arr(i)!=null) {\n for (j <- 0 until arr(i).length) {\n if (marriedPrinces(arr(i)(j)) == false) {\n marriedPrinces(arr(i)(j)) = true\n marriedPrincesses(i) = true\n Breaks.break()\n }\n }\n }\n unmarriedPrincesses+=1\n }\n }\n if(unmarriedPrincesses==0){\n println(\"OPTIMAL\")\n }else{\n println(\"IMPROVE\")\n var unmarriedPriceIndex=0\n var unmarriedPrincessIndex=0\n if (unmarriedPrincesses!=0){\n unmarriedPrincesses-=1\n while (marriedPrinces(unmarriedPriceIndex)) {\n unmarriedPriceIndex+=1\n }\n while (marriedPrincesses(unmarriedPrincessIndex)) {\n unmarriedPrincessIndex+=1\n }\n marriedPrincesses(unmarriedPrincessIndex)=true\n marriedPrinces(unmarriedPriceIndex)=true\n\n println((unmarriedPrincessIndex+1)+\" \"+(unmarriedPriceIndex+1))\n }\n }\n }\n }\n}\n", "positive_code": [{"source_code": "import scala.util.control.Breaks\n\nobject PrincessesAndPrinces {\n def main(args: Array[String]): Unit = {\n val in = scala.io.StdIn\n val tC = in.readLine().toInt\n for (t <- 0 until tC) {\n val n = in.readLine().toInt\n val arr=new Array[Array[Int]](n)\n for (i <- 0 until n) {\n val l=in.readLine()\n if(l.length>1)\n arr(i)=l.substring(l.indexOf(\" \")+1).split(\" \").map(_.toInt-1)\n else\n arr(i)=new Array[Int](0)\n }\n val p=Array.fill[Boolean](n)(false)\n val m=Array.fill[Boolean](n)(false)\n var um=0\n for (i <- 0 until n) {\n Breaks.breakable {\n for (j <- 0 until arr(i).length) {\n if(p(arr(i)(j))==false){\n p(arr(i)(j))=true\n m(i)=true\n Breaks.break()\n }\n }\n um+=1\n }\n }\n if(um==0){\n println(\"OPTIMAL\")\n }else{\n println(\"IMPROVE\")\n var pri=0\n var gri=0\n if (um!=0){\n um-=1\n while (p(pri)) pri+=1\n while (m(gri)) gri+=1\n m(gri)=true\n p(pri)=true\n println((gri+1)+\" \"+(pri+1))\n }\n }\n }\n }\n}"}, {"source_code": "\nimport scala.util.control.Breaks\nimport scala.collection.mutable.HashSet\n\n//https://codeforces.com/problemset/problem/1327/B\nobject PrincessesAndPrinces {\n def main(args: Array[String]): Unit = {\n val in = scala.io.StdIn\n val testCases = in.readLine().toInt\n for (t <- 0 until testCases) {\n val n = in.readLine().toInt\n val arr=new Array[Array[Int]](n)\n val unmarriedPrinces=HashSet[Int]()\n for (i <- 0 until n) {\n unmarriedPrinces+=i\n val l=in.readLine()\n if(l.length>1) {\n arr(i) = l.substring(l.indexOf(\" \") + 1).split(\" \").map(_.toInt - 1)\n }\n }\n var unmarriedPrincessIndex= -1\n for (i <- 0 until n) {\n Breaks.breakable {\n if( arr(i)!=null) {\n for (j <- 0 until arr(i).length) {\n if (unmarriedPrinces.contains(arr(i)(j))) {\n unmarriedPrinces-=(arr(i)(j))\n Breaks.break()\n }\n }\n }\n unmarriedPrincessIndex=i\n }\n }\n if(unmarriedPrincessIndex== -1){\n println(\"OPTIMAL\")\n }else{\n println(\"IMPROVE\")\n println((unmarriedPrincessIndex+1)+\" \"+(unmarriedPrinces.head+1))\n }\n }\n }\n}\n"}, {"source_code": "\nimport scala.util.control.Breaks\n\n//https://codeforces.com/problemset/problem/1327/B\nobject PrincessesAndPrinces {\n def main(args: Array[String]): Unit = {\n val in = scala.io.StdIn\n val testCases = in.readLine().toInt\n for (t <- 0 until testCases) {\n val n = in.readLine().toInt\n val arr=new Array[Array[Int]](n)\n for (i <- 0 until n) {\n val l=in.readLine()\n if(l.length>1) {\n arr(i) = l.substring(l.indexOf(\" \") + 1).split(\" \").map(_.toInt - 1)\n }\n }\n val marriedPrinces=Array.fill[Boolean](n)(false)\n val marriedPrincesses=Array.fill[Boolean](n)(false)\n var unmarriedPrincesses=0\n for (i <- 0 until n) {\n Breaks.breakable {\n if( arr(i)!=null) {\n for (j <- 0 until arr(i).length) {\n if (marriedPrinces(arr(i)(j)) == false) {\n marriedPrinces(arr(i)(j)) = true\n marriedPrincesses(i) = true\n Breaks.break()\n }\n }\n }\n unmarriedPrincesses+=1\n }\n }\n if(unmarriedPrincesses==0){\n println(\"OPTIMAL\")\n }else{\n println(\"IMPROVE\")\n var unmarriedPriceIndex=0\n var unmarriedPrincessIndex=0\n /*if (unmarriedPrincesses!=0){\n unmarriedPrincesses-=1*/\n while (marriedPrinces(unmarriedPriceIndex)) {\n unmarriedPriceIndex+=1\n }\n while (marriedPrincesses(unmarriedPrincessIndex)) {\n unmarriedPrincessIndex+=1\n }\n marriedPrincesses(unmarriedPrincessIndex)=true\n marriedPrinces(unmarriedPriceIndex)=true\n\n println((unmarriedPrincessIndex+1)+\" \"+(unmarriedPriceIndex+1))\n //}\n }\n }\n }\n}\n"}, {"source_code": "import scala.util.control.Breaks\nimport scala.collection.mutable.HashSet\n\n//https://codeforces.com/problemset/problem/1327/B\nobject PrincessesAndPrinces {\n def main(args: Array[String]): Unit = {\n val in = scala.io.StdIn\n val testCases = in.readLine().toInt\n for (t <- 0 until testCases) {\n val n = in.readLine().toInt\n val arr=new Array[Array[Int]](n)\n val unmarriedPrinces=HashSet[Int]()\n var unmarriedPrincessIndex= -1\n for (i <- 0 until n) {\n unmarriedPrinces+=i\n val l=in.readLine()\n if(l.length>1) {\n arr(i) = l.substring(l.indexOf(\" \") + 1).split(\" \").map(_.toInt - 1)\n }\n }\n for (i <- 0 until n) {\n Breaks.breakable {\n if( arr(i)!=null) {\n for (j <- 0 until arr(i).length) {\n if (unmarriedPrinces.contains(arr(i)(j))) {\n unmarriedPrinces-=(arr(i)(j))\n Breaks.break()\n }\n }\n }\n unmarriedPrincessIndex=i\n }\n }\n if(unmarriedPrincessIndex== -1){\n println(\"OPTIMAL\")\n }else{\n println(\"IMPROVE\")\n println((unmarriedPrincessIndex+1)+\" \"+(unmarriedPrinces.head+1))\n }\n }\n }\n}"}, {"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n val maxN = 100002\n\n val ps = Array.fill(maxN)(true)\n val lista = Array.fill(maxN)(List.empty[Int])\n (1 to t).foreach{ _ =>\n val n = in.nextInt()\n ps(0) = false\n (1 to n).foreach{ i =>\n\n ps(i) = true\n }\n\n (1 to n).foreach{ i =>\n val k = in.nextInt()\n lista(i) = (1 to k).map(_ => in.nextInt()).toList\n }\n var dsFree = -1\n (1 to n).foreach{ i =>\n lista(i).find(ps) match {\n case Some(p) => ps(p) = false\n case None => dsFree = i\n }\n }\n if(dsFree == -1){\n out.println(\"OPTIMAL\")\n }else{\n val psFree = ps.indexWhere(p => p)\n out.println(\"IMPROVE\")\n out.println(s\"$dsFree $psFree\")\n }\n\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "negative_code": [], "src_uid": "38911652b3c075354aa8adb2a4c6e362"} {"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n def binarySearch(left: Int, right: Int, f: Int => Boolean): Int = {\r\n @annotation.tailrec\r\n def go(l: Int, r: Int): Int =\r\n if (l + 1 >= r) r\r\n else {\r\n val m = (l + r) / 2\r\n f(m) match {\r\n case true => go(l, m)\r\n case _ => go(m, r)\r\n }\r\n }\r\n\r\n go(left, right)\r\n }\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt).sorted\r\n val bn = readLine().split(\" \").map(_.toInt).sorted\r\n\r\n val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))\r\n\r\n def score(stages: Int): Boolean = {\r\n val selected = stages - stages / 4\r\n\r\n val ascore = {\r\n val hundreds = 0 max (stages - n)\r\n val previous = 0 max (selected - hundreds)\r\n 100 * hundreds + aprefix(n) - aprefix(n - previous)\r\n }\r\n\r\n val bscore = bprefix(n) - bprefix(0 max (n - selected))\r\n\r\n ascore >= bscore\r\n }\r\n\r\n val ans =\r\n if (score(n)) 0\r\n else binarySearch(n, 200000, score) - n\r\n\r\n println(ans)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n def binarySearch(left: Int, right: Int, f: Int => Boolean): Int = {\r\n @annotation.tailrec\r\n def go(l: Int, r: Int): Int =\r\n if (l + 1 >= r) r\r\n else {\r\n val m = (l + r) / 2\r\n f(m) match {\r\n case true => go(l, m)\r\n case _ => go(m, r)\r\n }\r\n }\r\n\r\n go(left, right)\r\n }\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt).sorted\r\n val bn = readLine().split(\" \").map(_.toInt).sorted\r\n\r\n val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))\r\n\r\n def score(stages: Int): Boolean = {\r\n val selected = stages - stages / 4\r\n\r\n val ascore = {\r\n val hundreds = 0 max (stages - n)\r\n val previous = 0 max (selected - hundreds)\r\n 100 * hundreds + aprefix(n) - aprefix(n - previous)\r\n }\r\n\r\n val bscore = bprefix(n) - bprefix(0 max (n - selected))\r\n\r\n ascore >= bscore\r\n }\r\n\r\n val ans =\r\n if (score(n)) 0\r\n else binarySearch(n, 500000, score) - n\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n def binarySearch(left: Int, right: Int, f: Int => Boolean): Int = {\r\n @annotation.tailrec\r\n def go(l: Int, r: Int): Int =\r\n if (l + 1 >= r) r\r\n else {\r\n val m = (l + r) / 2\r\n f(m) match {\r\n case true => go(l, m)\r\n case _ => go(m, r)\r\n }\r\n }\r\n\r\n go(left, right)\r\n }\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt).sorted\r\n val bn = readLine().split(\" \").map(_.toInt).sorted\r\n\r\n val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))\r\n\r\n def score(stages: Int): Boolean = {\r\n val selected = stages - stages / 4\r\n\r\n val ascore = {\r\n val hundreds = 0 max (stages - n)\r\n val previous = 0 max (selected - hundreds)\r\n 100 * hundreds + aprefix(n) - aprefix(n - previous)\r\n }\r\n\r\n val bscore = bprefix(n) - bprefix(0 max (n - selected))\r\n\r\n ascore >= bscore\r\n }\r\n\r\n val ans =\r\n if (score(n)) 0\r\n else binarySearch(n, n << 1, score) - n\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n def binarySearch(left: Int, right: Int, f: Int => Boolean): Int = {\r\n @annotation.tailrec\r\n def go(l: Int, r: Int): Int =\r\n if (l + 1 >= r) r\r\n else {\r\n val m = (l + r) / 2\r\n f(m) match {\r\n case true => go(l, m)\r\n case _ => go(m, r)\r\n }\r\n }\r\n\r\n go(left, right)\r\n }\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt).sorted\r\n val bn = readLine().split(\" \").map(_.toInt).sorted\r\n\r\n val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))\r\n\r\n def score(stages: Int): Boolean = {\r\n val selected = stages - stages / 4\r\n\r\n val ascore = {\r\n val hundreds = 0 max (stages - n)\r\n val previous = 0 max (selected - hundreds)\r\n 100 * hundreds + aprefix(n) - aprefix(n - previous)\r\n }\r\n\r\n val bscore = bprefix(n) - bprefix(0 max (n - selected))\r\n\r\n ascore >= bscore\r\n }\r\n\r\n val ans =\r\n if (score(n)) 0\r\n else binarySearch(n, 175000, score) - n\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n def binarySearch(left: Int, right: Int, f: Int => Boolean): Int = {\r\n @annotation.tailrec\r\n def go(l: Int, r: Int): Int =\r\n if (l + 1 >= r) r\r\n else {\r\n val m = (l + r) / 2\r\n f(m) match {\r\n case true => go(l, m)\r\n case _ => go(m, r)\r\n }\r\n }\r\n\r\n go(left, right)\r\n }\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt).sorted\r\n val bn = readLine().split(\" \").map(_.toInt).sorted\r\n\r\n val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))\r\n\r\n def score(stages: Int): Boolean = {\r\n val selected = stages - stages / 4\r\n\r\n val ascore = {\r\n val hundreds = 0 max (stages - n)\r\n val previous = 0 max (selected - hundreds)\r\n 100 * hundreds + aprefix(n) - aprefix(n - previous)\r\n }\r\n\r\n val bscore = bprefix(n) - bprefix(0 max (n - selected))\r\n\r\n ascore >= bscore\r\n }\r\n\r\n val ans =\r\n if (score(n)) 0\r\n else binarySearch(n, 100000, score) - n\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n def binarySearch(l: Int, r: Int, f: Int => Boolean): Int = {\r\n @annotation.tailrec\r\n def go(l: Int, r: Int): Int =\r\n if (l + 1 >= r) r\r\n else {\r\n val m = (l + r) / 2\r\n f(m) match {\r\n case true => go(l, m)\r\n case _ => go(m, r)\r\n }\r\n }\r\n go(l, r)\r\n }\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt).sorted\r\n val bn = readLine().split(\" \").map(_.toInt).sorted\r\n\r\n val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))\r\n\r\n def score(k: Int): Boolean = {\r\n val r = k - k / 4\r\n\r\n val ascore =\r\n if (k <= n) aprefix(n) - aprefix(n - r)\r\n else {\r\n val e = r min (k - n)\r\n e * 100 + aprefix(n) - aprefix(n - r + e)\r\n }\r\n\r\n val bscore = bprefix(n) - bprefix(0 max (n - r))\r\n\r\n ascore >= bscore\r\n }\r\n\r\n val ans =\r\n if (score(n)) 0\r\n else {\r\n val right = {\r\n @annotation.tailrec\r\n def go(r: Int): Int = if (score(r)) r else go(r << 1)\r\n go(1)\r\n }\r\n binarySearch(n, right, score) - n\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n def binarySearch(l: Int, r: Int, f: Int => Boolean): Int = {\r\n @annotation.tailrec\r\n def go(l: Int, r: Int): Int =\r\n if (l + 1 >= r) r\r\n else {\r\n val m = (l + r) / 2\r\n f(m) match {\r\n case true => go(l, m)\r\n case _ => go(m, r)\r\n }\r\n }\r\n go(l, r)\r\n }\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt).sorted\r\n val bn = readLine().split(\" \").map(_.toInt).sorted\r\n\r\n val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))\r\n\r\n def score(k: Int): Boolean = {\r\n val r = k - k / 4\r\n\r\n val (ascore, bscore) =\r\n if (k <= n) (aprefix(n) - aprefix(n - r), bprefix(n) - bprefix(n - r))\r\n else {\r\n val e = r min (k - n)\r\n (e * 100 + aprefix(n) - aprefix(n - r + e), bprefix(n))\r\n }\r\n\r\n ascore >= bscore\r\n }\r\n\r\n val ans = if (score(n)) 0 else binarySearch(n, 100005, score) - n\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n def binarySearch(l: Int, r: Int, f: Int => Boolean): Int = {\r\n @annotation.tailrec\r\n def go(l: Int, r: Int): Int =\r\n if (l + 1 >= r) r\r\n else {\r\n val m = (l + r) / 2\r\n f(m) match {\r\n case true => go(l, m)\r\n case _ => go(m, r)\r\n }\r\n }\r\n go(l, r)\r\n }\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt).sorted\r\n val bn = readLine().split(\" \").map(_.toInt).sorted\r\n\r\n val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))\r\n\r\n def score(k: Int): Boolean = {\r\n val r = k - k / 4\r\n\r\n val (ascore, bscore) =\r\n if (k <= n) (aprefix(n) - aprefix(n - r), bprefix(n) - bprefix(n - r))\r\n else {\r\n val e = r min (k - n)\r\n (e * 100 + aprefix(n) - aprefix(n - r + e), bprefix(n))\r\n }\r\n\r\n ascore >= bscore\r\n }\r\n\r\n val ans = if (score(n)) 0 else binarySearch(n, 200, score) - n\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "src_uid": "61b88627fc843ef6e5226e1003822793"} {"source_code": "object A1004 extends App {\n def read: Array[Int] = readLine.split(\" \").map(_.toInt)\n\n val (n, d) = {\n val fl = read\n (fl(0), fl(1))\n }\n\n val hotels = read\n\n def result = {\n (0 to n - 1)\n .map { i =>\n if (i == n - 1) 1\n else {\n val diff = (hotels(i + 1) - hotels(i)) / d\n val residual = (hotels(i + 1) - hotels(i)) % d\n if (diff == 2 && residual > 0 || diff > 2) 2\n else if (diff == 2) 1\n else 0\n }\n }\n .reduce(_ + _) + 1\n }\n\n println(result)\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Solution extends App {\n val array1 = StdIn.readLine().split(\" \").map(_.toInt)\n var n = array1(0)\n var d = array1(1)\n\n\n var count = 2\n\n val arr = StdIn.readLine().split(\" \").map(_.toInt)\n\n for (i <- 0 until arr.size - 1)\n {\n val a = arr(i) + d\n val b = arr(i + 1) - d\n if (a <= b)\n {\n if (a != b) count = count + 2 else count = count + 1\n }\n }\n println(count)\n}"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject a1004 {\n def main(args: Array[String]): Unit = {\n def getInts() = readLine().split(\" \").map(_.toInt)\n val Array(n, d) = getInts()\n val hs = getInts()\n println((hs zip hs.tail map{ a=> val c = a._2 - a._1 -1 - (2*(d-1)) ; if (c<0) 0 else if (c>2) 2 else c} sum) + 2)\n }\n}\n"}], "negative_code": [], "src_uid": "5babbb7c5f6b494992ffa921c8e19294"} {"source_code": "import scala.collection.mutable._\n\nobject Solution {\n def main(args: Array[String]) {\n val n = io.StdIn.readLine.toInt\n val stairs = io.StdIn.readLine.split(\" \").map(_.toInt)\n \n var count = 0\n var lastStep = new ListBuffer[Int]()\n for (i <- 0 until stairs.length) {\n if (stairs(i) == 1) {\n count += 1\n if (i != 0) {\n lastStep += stairs(i-1)\n }\n }\n }\n lastStep += stairs(n-1)\n println(count)\n println(lastStep.toList.mkString(\" \"))\n \n }\n}\n", "positive_code": [{"source_code": "/**\n * @author ShankarShastri\n * Algorithm: ProblemA\n */\nimport scala.io.StdIn._\nimport scala.annotation.tailrec\n\n\n\nobject ProblemA {\n\n def getAllIndicesOfElement[T](element: T, l: List[T]): List[Int] = {\n @tailrec\n def getAllIndicesHelper(l: List[T], accumList: List[Int] = List[Int](), index: Int=0): List[Int] = {\n if(l.length == 0) {\n (index :: accumList).reverse\n } else {\n l match {\n case head :: tail if head == element => getAllIndicesHelper(tail, index :: accumList, index+1)\n case _ :: tail => getAllIndicesHelper(tail, accumList, index+1)\n }\n }\n }\n getAllIndicesHelper(l)\n }\n\n def tanyaStairwayStr(list: List[Int]): String = {\n getAllIndicesOfElement(1, list).sliding(2).toList.map(_.reduce((a,b) => b - a)).mkString(\" \")\n }\n \n def main(args: Array[String]): Unit = {\n val _ = readInt\n val arr = readLine().split(\" \").map(_.toInt).toList\n println(arr.count(_ == 1))\n println(tanyaStairwayStr(arr))\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\nobject Codeforces1005A {\n\n def parseStairs(sounds: Array[Int]): Seq[Int] = {\n val stairs = new ListBuffer[Int]\n for (sound <- sounds) {\n if (sound == 1) {\n stairs.append(1)\n } else {\n stairs(stairs.length - 1) += 1\n }\n }\n stairs\n }\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n val sounds = StdIn.readLine.split(\" \").map(_.trim.toInt)\n\n val stairs = parseStairs(sounds)\n println(stairs.length)\n println(stairs.mkString(\" \"))\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n\n val cnts = ArrayBuffer[Int]()\n var cnt = 0\n var prev = 0\n REP(N) { i =>\n if (A(i) == prev + 1) {\n cnt += 1\n } else {\n cnts += cnt\n cnt = 1\n }\n prev = A(i)\n }\n if (cnt > 0) cnts += cnt\n out.println(cnts.length)\n out.println(cnts.mkString(\" \"))\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object CF496A extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n val numbers = (new Array[Int](in.nextInt)).map(_ => in.nextInt)\n\n def count(numbers: Array[Int], stairs: List[Int], current: Int): List[Int] = {\n if (numbers.isEmpty)\n return stairs :+ current\n if (numbers.head == 1)\n return count(numbers.tail, stairs :+ current, 1)\n else\n return count(numbers.tail, stairs, current + 1)\n }\n\n val stairs = count(numbers, List[Int](), 0).tail\n\n out.println(stairs.length)\n out.println(stairs.mkString(\" \"))\n }\n\n solve\n out.flush\n out.close\n}"}], "negative_code": [], "src_uid": "0ee86e75ff7a47a711c9eb41b34ad1a5"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject C extends App {\n\n case class Point(x: Int, segId: Int, isBegin: Boolean)\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val points = Array.ofDim[Point](n * 2)\n (0 until n).foreach { i =>\n points(i * 2) = Point(in.nextInt, i, isBegin = true)\n points(i * 2 + 1) = Point(in.nextInt, i, isBegin = false)\n }\n util.Sorting.quickSort(points)((x: Point, y: Point) => Ordering[Int].compare(x.x, y.x))\n //points.sortBy(_.x)\n //points.foreach(println)\n var k = 0\n var ans = 0\n (0 until n * 2 - 1).foreach { i =>\n if (points(i).isBegin)\n k += 1\n else\n k -= 1\n if (k == n - 1) {\n ans = math.max(ans, points(i + 1).x - points(i).x)\n }\n if (k == n) {\n if (points(i).segId == points(i + 1).segId) {\n ans = math.max(ans, points(i + 2).x - points(i - 1).x)\n }\n ans = math.max(ans, points(i + 1).x - points(i - 1).x)\n ans = math.max(ans, points(i + 2).x - points(i).x)\n }\n }\n print(ans)\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toInt\n }\n\n def nextLong: Double = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}", "positive_code": [{"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N = sc.nextInt()\n case class Seg(l: Int, r: Int) {\n def len = max(0, r - l)\n }\n val S = map(N) { _ =>\n val l, r = sc.nextInt()\n Seg(l, r)\n }\n\n var msR = 0\n var mxL = 0\n rep(N) { i =>\n val s = S(i)\n if (s.r < S(msR).r || (s.r == S(msR).r && s.len < S(msR).len)) {\n msR = i\n }\n if (S(mxL).l < s.l || (s.l == S(mxL).l && s.len < S(mxL).len)) {\n mxL = i\n }\n }\n\n def intersect(ignore: Int): Int = {\n var msR = Integer.MAX_VALUE\n var mxL = 0\n rep(N) { i =>\n if (i != ignore) {\n val s = S(i)\n if (s.r < msR) {\n msR = s.r\n }\n if (mxL < s.l) {\n mxL = s.l\n }\n }\n }\n max(0, msR - mxL)\n }\n\n out.println(max(intersect(msR), intersect(mxL)))\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer\n\nobject CF506C extends App {\n import scala.io.StdIn\n val n = StdIn.readLine.toInt\n val segments = new Array[Int](n).map(_ => StdIn.readLine.split(' ').map(_.toInt))\n\n val shrink = ListBuffer[Int]()\n\n var min = Int.MinValue\n var max = Int.MaxValue\n\n for (i <- 0 until n) {\n val segment = segments(i)\n if (segment(0) > min || segment(1) < max) {\n shrink += i\n }\n if (segment(0) > min)\n min = segment(0)\n if (segment(1) < max)\n max = segment(1)\n }\n\n var maxLength = 0\n for (drop <- shrink) {\n min = Int.MinValue\n max = Int.MaxValue\n for (i <- (0 until n).filter(_ != drop)) {\n if (segments(i)(0) > min)\n min = segments(i)(0)\n if (segments(i)(1) < max)\n max = segments(i)(1)\n }\n maxLength = maxLength.max(max-min)\n }\n\n println(maxLength)\n}\n"}, {"source_code": "import java.io.FileReader\nimport java.util\nimport java.util.Comparator\n\nimport collection.Searching._\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject Solution {\n //Console.setIn(new FileReader(new java.io.File(\"in\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n var caseNo = 1\n val magicMod = 1000000007\n\n\n case class Interval(l: Int, r: Int) {\n def intersect(o: Option[Interval]): Option[Interval] = {\n o match {\n case Some(Interval(ol, or)) =>\n if (ol < r && l < or) {\n Some(Interval(Math.max(ol, l), Math.min(or, r)))\n } else {\n None\n }\n case None => None\n }\n }\n\n def contains(o: Option[Interval]): Boolean = {\n intersect(o).exists(this.equals(_))\n }\n\n def len(): Int = {\n r - l\n }\n }\n\n def doCase(): Unit ={\n val N = readInt()\n val ints: Array[Interval] = Array.fill(N)(null)\n var i = 0\n while (i < N) {\n ints(i) = readIntLine() match {case Array(a, b) => Interval(a, b)}\n i += 1\n }\n\n var full = Some(Interval(Integer.MIN_VALUE, Integer.MAX_VALUE)): Option[Interval]\n var other = List[Option[Interval]]()\n for (int <- ints) {\n var n = full\n full = full.flatMap(_.intersect(Some(int)))\n val intersected = other.map(int.intersect)\n other = n :: intersected.distinct\n }\n\n print(other.map(_.map(_.len()).getOrElse(0)).max)\n }\n\n def main(args: Array[String]): Unit = {\n val noCases = 1\n for (i <- 0 until noCases) {\n doCase()\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n def readLongLine(): Array[Long] = {\n StdIn.readLine().split(\" \").map(_.toLong)\n }\n\n def readBigIntLine(): Array[BigInt] = {\n StdIn.readLine().split(\" \").map(BigInt.apply)\n }\n}"}], "negative_code": [], "src_uid": "b50df0e6d91d538cd7db8dfdc7cd5266"} {"source_code": "object Main{\n\n def main(args: Array[String]){\n val Array(a, b, n) = readLine().split(\" \").map(_.toInt)\n val d = (b - (a*10)%b) % b\n if (d >= 10) println(\"-1\") else{\n print(a)\n print(d)\n for (i <- 1 to n-1)\n print(0)\n println()\n }\n } //> main: (args: Array[String])Unit\n}", "positive_code": [{"source_code": "object AAddingDigits extends App {\n import scala.io.StdIn._\n\n val Array(a, b, n) = readLine().split(\" \").map(_.toInt)\n\n val k = math.floor(a * 10.0 / b).toInt\n val (x1, x2) = (a * 10 - k * b, (k + 1) * b - a * 10)\n val (a1, a2) = (a * 10 + x1, a * 10 + x2)\n\n val ans =\n if (x1 >= 0 && x1 < 10 && a1 % b == 0)\n a1.toString + \"0\" * (n - 1)\n else if (x2 >= 0 && x2 < 10 && a2 % b == 0)\n a2.toString + \"0\" * (n - 1)\n else\n \"-1\"\n\n println(ans)\n}\n"}, {"source_code": "object AAddingDigits extends App {\n import scala.io.StdIn._\n\n val Array(a, b, n) = readLine().split(\" \").map(_.toInt)\n val d = (b - (a * 10) % b) % b\n\n if (d > 9)\n println(\"-1\")\n else\n println(s\"$a$d${\"0\" * (n - 1)}\")\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val abn = readLine().split(\" \").map(_.toInt)\n val a = abn(0)\n val b = abn(1)\n val n = abn(2)\n \n val max = (a * 10 + 9).toFloat / b.toFloat\n val min = (a * 10).toFloat / b.toFloat\n \n val dec = if (max.floor >= min.ceil) (min.ceil.toInt * b - a * 10)\n else -1\n \n if (dec == -1) println(\"-1\")\n else {\n val s = Seq(a, dec) ++ (1 until n).map(_ => 0)\n println(s.mkString)\n }\n }\n}"}, {"source_code": "import scala.Math.pow;\n\nobject App {\n def f1(n: Long, m: Int) = {\n val k = n * 10\n for {\n i <- (0 to 9).toList\n if ((k + i) % m == 0)\n } yield k + i\n } //> f1: (n: Int, m: Int)List[Int]\n \n def f1_io() = {\n val Array(a, b, n) = (readLine split \" \") map (_.toInt)\n val l = f1(a, b)\n if (l.isEmpty) print(-1)\n else {\n print(l(0))\n for (i <- (1 to n - 1)) print(0)\n }\n } //> f: (input: String)Double\n \n def main(args: Array[String]): Unit = {\n f1_io\n }\n\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(a, b, n) = in.next().split(' ').map(_.toInt)\n val r = (0 to 9).find(i => (a * 10 + i) % b == 0)\n if (r.isEmpty)\n println(-1)\n else\n println(s\"$a${r.get}\" + \"0\" * (n - 1))\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\nimport scala.collection.mutable.StringBuilder\n\nobject P260A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val A, B, N = sc.nextInt\n\n def solve(): String = {\n val sb = new StringBuilder(A.toString)\n\n @inline\n def extend(x: Int): Int = {\n val rem = x * 10 % B\n if (rem == 0) 0\n else {\n val d = B - rem\n if (d > 9) -1\n else d\n }\n }\n\n val d = extend(A)\n if (d < 0) \"-1\"\n else {\n sb += ('0' + d).toChar\n for (_ <- 1 until N)\n sb += '0'\n sb.toString\n }\n }\n\n out.println(solve)\n out.close\n}\n\n\n\n"}], "negative_code": [{"source_code": "object Main{\n\n def main(args: Array[String]){\n val Array(a, b, n) = readLine().split(\" \").map(_.toInt)\n val d = b - (a*10)%b\n if (d >= 10) println(\"-1\") else{\n print(a)\n print(d)\n for (i <- 1 to n-1)\n print(0)\n println()\n }\n } //> main: (args: Array[String])Unit\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\nimport scala.collection.mutable.StringBuilder\n\nobject P260A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val A, B, N = sc.nextInt\n\n def solve(): String = {\n val sb = new StringBuilder(A.toString)\n\n @inline\n def extend(x: Int): Int = {\n val rem = x * 10 % B\n if (rem == 0) 0\n else {\n val d = B - rem\n if (d > 9) -1\n else d\n }\n }\n\n @tailrec\n def loop(acc: Int, n: Int): String = {\n if (n == 0) sb.toString\n else {\n val d: Int = extend(acc)\n sb += (d + '0').toChar\n if (d < 0) \"-1\"\n else loop(d, n - 1)\n }\n }\n \n loop(A % B, N)\n }\n\n out.println(solve)\n out.close\n}\n\n\n\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\nimport scala.collection.mutable.StringBuilder\n\nobject P260A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val A, B, N = sc.nextInt\n\n def solve(): BigInt = {\n\n def lengthen(x: BigInt): BigInt = {\n val x10: BigInt = x * 10\n val a: BigInt = B - x10 % B\n if (a < 10) x10 + a\n else -1\n }\n\n @tailrec\n def loop(acc: BigInt, n: Int): BigInt = {\n if (n == 0 || acc < 0) acc\n else loop(lengthen(acc), n - 1)\n }\n\n loop(BigInt(A), N)\n }\n\n out.println(solve)\n out.close\n}\n\n\n\n"}, {"source_code": "object AAddingDigits extends App {\n import scala.io.StdIn._\n\n val Array(a, b, n) = readLine().split(\" \").map(_.toInt)\n val d = (b - (a * 10) % b) % b\n\n if (d > 0)\n println(\"-1\")\n else\n println(s\"$a$d${\"0\" * (n - 1)}\")\n}\n"}, {"source_code": "object AAddingDigits extends App {\n import scala.io.StdIn._\n\n val Array(a, b, n) = readLine().split(\" \").map(_.toLong)\n\n @annotation.tailrec\n def go(a: Long, n: Long): Long =\n if (n == 0) a\n else {\n val k = math.floor(a * 10 / b).toLong\n val (x1, x2) = (a * 10 - k * b, (k + 1) * b - a * 10)\n\n if (x1 >= 0 && x1 < 10) go(a * 10 + x1, n - 1)\n else if (x2 >= 0 && x2 < 10) go(a * 10 + x2, n - 1)\n else -1L\n }\n\n val ans = go(a, n)\n\n println(ans)\n}\n"}, {"source_code": "object AAddingDigits extends App {\n import scala.io.StdIn._\n\n val Array(a, b, n) = readLine().split(\" \").map(_.toInt)\n\n val k = math.floor(a * 10 / b).toInt\n val (x1, x2) = (a * 10 - k * b, (k + 1) * b - a * 10)\n\n val ans =\n if (x1 >= 0 && x1 < 10)\n (a * 10 + x1).toString + \"0\" * (n - 1)\n else if (x2 >= 0 && x2 < 10)\n (a * 10 + x2).toString + \"0\" * (n - 1)\n else\n \"-1\"\n\n println(ans)\n}\n"}, {"source_code": "object AAddingDigits extends App {\n import scala.io.StdIn._\n\n val Array(a, b, n) = readLine().split(\" \").map(_.toInt)\n\n val k = math.floor(a * 10.0 / b).toInt\n val (x1, x2) = (a * 10 - k * b, (k + 1) * b - a * 10)\n\n val ans =\n if (x1 >= 0 && x1 < 10)\n (a * 10 + x1).toString + \"0\" * (n - 1)\n else if (x2 >= 0 && x2 < 10)\n (a * 10 + x2).toString + \"0\" * (n - 1)\n else\n \"-1\"\n\n println(ans)\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val abn = readLine().split(\" \").map(_.toInt)\n val a = abn(0)\n val b = abn(1)\n val n = abn(2)\n \n val max = (a * 10 + 9).toFloat / b.toFloat\n val min = (a * 10).toFloat / b.toFloat\n \n val dec = if (max.floor >= min.ceil) (min.ceil.toInt - a * 10)\n else -1\n \n if (dec == -1) println(\"-1\")\n else {\n val s = Seq(a, n) ++ (1 until n).map(_ => 0)\n println(s.mkString)\n }\n }\n}"}, {"source_code": "import scala.Math.pow;\n\nobject App {\n def f1(n: Long, m: Int) = {\n val k = n * 10\n for {\n i <- (0 to 9).toList\n if ((k + i) % m == 0)\n } yield k + i\n } //> f1: (n: Int, m: Int)List[Int]\n \n def f1_io() = {\n val Array(a, b, n) = (readLine split \" \") map (_.toInt)\n val l = f1(a, b)\n if (l.isEmpty) print(-1)\n else {\n print(l(0))\n for (i <- (1 to n + 1 - l(0).toString.length)) print(0)\n }\n } //> f: (input: String)Double\n \n def main(args: Array[String]): Unit = {\n f1_io\n }\n\n}"}, {"source_code": "import scala.Math.pow;\n\nobject App {\n def f1(n: Int, m: Int) = {\n val k = n * 10\n for {\n i <- (0 to 9).toList\n if ((k + i) % m == 0)\n } yield k + i\n } //> f1: (n: Int, m: Int)List[Int]\n \n def f1_io() = {\n val Array(a, b, n) = (readLine split \" \") map (_.toInt)\n val l = f1(a, b)\n if (l.isEmpty) print(-1)\n else {\n print(l(0))\n for (i <- (1 to n + 1 - l(0).toString.length)) print(0)\n }\n } //> f: (input: String)Double\n \n def main(args: Array[String]): Unit = {\n f1_io\n }\n\n}"}, {"source_code": "import scala.Math.pow;\n\nobject App {\n def f1(n: Int, m: Int) = {\n val k = n * 10\n for {\n i <- (0 to 9).toList\n if ((k + i) % m == 0)\n } yield k + i\n } //> f1: (n: Int, m: Int)List[Int]\n \n def f1_io() = {\n val Array(a, b, n) = (readLine split \" \") map (_.toInt)\n val l = f1(a, b)\n if (l.isEmpty) print(-1)\n else {\n print(l(1))\n for (i <- (1 to n - l(1).toString.length)) print(0)\n }\n } //> f: (input: String)Double\n \n def main(args: Array[String]): Unit = {\n f1_io\n }\n\n}"}], "src_uid": "206eb67987088843ef42923b0c3939d4"} {"source_code": "import java.util.Scanner\n\n/**\n * Created by MZKL7315 on 4/12/2016.\n */\n\nobject Main {\n\n def calc(s: String, k: Int): String = s match {\n case \"\" => \"\"\n case s => {\n val c = s.count(_ == s.head)\n if (c % k != 0) throw new Error(\"-1\") else (1 to c / k).map(_ => s.head).mkString + calc(s filter (_ != s.head), k)\n }\n }\n\n def gen(s: String, k: Int): String = (s, k) match {\n case (s, 0) => \"\"\n case _ => s + gen(s, k - 1)\n }\n\n def main(args: Array[String]) = {\n val in: Scanner = new Scanner(System.in)\n val k = in.nextInt()\n val s = in.next()\n try {\n val res = calc(s, k)\n println(gen(res, k))\n } catch {\n case e: Error => println(e.getMessage)\n }\n }\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\n/**\n * Created by MZKL7315 on 4/12/2016.\n */\n\nobject Main {\n\n def main(args: Array[String]) = {\n val in: Scanner = new Scanner(System.in)\n val k = in.nextInt()\n val s = in.next()\n\n val m = s.map(x => (x, s.count(y => y == x))).toMap\n if (m.exists(_._2 % k != 0)) println(-1)\n else {\n val res = m.map({ case (x, y) => (1 to y / k).map(_ => x).mkString }).mkString\n println((1 to k).map(_ => res).mkString)\n }\n\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by MZKL7315 on 4/12/2016.\n */\n\nobject Main {\n\n def charCounts(s: String): Map[Char, Int] = s match {\n case \"\" => Map()\n case s => charCounts(s filter (_ != s.head)) + (s.head -> s.count(_ == s.head))\n }\n\n def main(args: Array[String]) = {\n val in: Scanner = new Scanner(System.in)\n val k = in.nextInt()\n val s = in.next()\n\n val m = charCounts(s)\n if (m.exists(_._2 % k != 0)) println(-1)\n else {\n println((1 to k).map(_ => m.map({ case (x, y) => (1 to y / k).map(_ => x).mkString }).mkString).mkString)\n }\n\n }\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _219A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val k = next.toInt\n val s = next\n val grouped = s.groupBy(ch => ch)\n if (grouped.exists(pair => pair._2.length % k != 0)) println(-1)\n else {\n val map = grouped.map(pair => (pair._1, pair._2.length / k))\n val one = map.map(i => (0 until i._2).map(j => i._1).mkString).mkString\n val ans = (0 until k).map(i => one).mkString\n println(ans)\n }\n}"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val k = in.next().toInt\n val str = in.next().foldLeft(Map.empty[Char, Int]) {\n case (acc, el) if acc.contains(el) => acc + (el -> (acc(el) + 1))\n case (acc, el) => acc + (el -> 1)\n }\n if (str.values.exists(_ % k > 0))\n println(\"-1\")\n else {\n val s = str.map{\n case(key, v) => List.fill(v / k){key}.mkString\n }.mkString\n println(List.fill(k){s}.mkString)\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P219A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextLine.toInt\n val S = sc.nextLine.sorted\n val len = S.length\n\n val base: String = {\n @tailrec\n def loop(acc: List[Char], i: Int): String =\n if (i >= len) acc.mkString\n else loop(acc :+ S(i), i + N)\n loop(Nil, 0)\n }\n\n val answer: String = {\n val res = base * N\n if (S == res.sorted) res\n else \"-1\"\n }\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n val k = readInt\n val s = reader.readLine().groupBy(x => x)\n val ans = Map(false -> (() => \"-1\"), true -> (() => s.values.map(str => str.take(str.length / k)).mkString * k)) apply {\n s.values.forall(_.length % k == 0)\n }\n\n def main(args: Array[String]) {\n println(ans())\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt\n val s = readLine\n val map = scala.collection.mutable.Map[Char, Int]()\n s.foreach(c => map(c) = map.getOrElse(c, 0) + 1)\n var r = Seq[Char]()\n var cor = true\n map.foreach { case (c, i) =>\n if (i % n == 0) r ++= Seq.fill(i / n)(c)\n else cor = false \n }\n if(cor) println(Seq.fill(n)(r.mkString).mkString)\n else println(\"-1\")\n }\n}"}, {"source_code": "import Console._\n\nobject Main extends App {\n \n def getCountMap(str: String): Map[Char, Int] = {\n str.groupBy(_.toChar).map(p => (p._1, p._2.length))\n }\n \n val k = readInt\n val str = readLine\n \n // check if str.length % k == 0\n if (str.length % k != 0) {\n print(-1)\n exit\n }\n \n // fill map(letter, count) sorted by count\n val freqMap = getCountMap(str).toSeq.sortBy(_._2).toMap\n \n // Precondition check - every map count % k must be == 0\n freqMap.keys.map(chr => {\n if (freqMap(chr) % k != 0) {\n print(-1)\n exit\n }\n })\n \n // form initial sequence\n val chrSeq = freqMap.flatMap(chr => {\n List.fill(chr._2 / k)(chr._1)\n }).toList\n for(i <- 0 until k) {\n print(chrSeq.mkString)\n }\n \n // print all ? - generate not repeating sequences\n // chrSeq.permutations.toList.map(x => println(List.fill(k)(x.mkString).mkString))\n \n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\n\n/**\n * Created by MZKL7315 on 4/12/2016.\n */\n\nobject Main {\n\n def calc(s: String): String = s match {\n case \"\" => \"\"\n case s => {\n val c = s.count(_ == s.head)\n if (c % 2 == 1) throw new Error(\"-1\") else (1 to c / 2).map(_ => s.head).mkString + calc(s filter (_ != s.head))\n }\n }\n\n def main(args: Array[String]) = {\n val in: Scanner = new Scanner(System.in)\n val n = in.nextInt()\n val s = in.next()\n try {\n val res = calc(s)\n println(res + res)\n } catch {\n case e: Error => println(e.getMessage)\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P219A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextLine.toInt\n val S = sc.nextLine.sorted\n val len = S.length\n\n val base: String = {\n @tailrec\n def loop(acc: List[Char], i: Int): String =\n if (i >= len) acc.mkString\n else loop(acc :+ S(i), i + N)\n loop(Nil, 0)\n }\n\n val answer: String = \n if (S == (base * N).sorted) base\n else \"-1\"\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "import Console._\n\nobject Main extends App {\n \n def getCountMap(str: String): Map[Char, Int] = {\n str.groupBy(_.toChar).map(p => (p._1, p._2.length))\n }\n \n val k = readInt\n val str = readLine\n \n // check if str.length % k == 0\n if (str.length % k != 0) {\n print(-1)\n exit\n }\n \n // fill map(letter, count) sorted by count\n val freqMap = getCountMap(str).toSeq.sortBy(_._2).toMap\n \n // Precondition check - every map count % k must be == 0\n freqMap.keys.map(chr => {\n if (freqMap(chr) % k != 0) {\n print(-1)\n exit\n }\n })\n \n // form initial sequence\n val chrSeq = freqMap.flatMap(chr => {\n List.fill(chr._2 / k)(chr._1)\n }).toList\n \n // generate not repeating sequences\n chrSeq.permutations.toList.map(x => println(List.fill(k)(x.mkString).mkString))\n \n}\n"}], "src_uid": "f5451b19cf835b1cb154253fbe4ea6df"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N = ni()\n val A = na(N)\n if (N == 1) {\n out.println(-1)\n } else {\n val inf = 1e9.toInt\n var d = inf\n val lst = mutable.Map[Int, Int]().withDefaultValue(-1)\n REP(N) { i =>\n val a = A(i)\n if (lst(a) != -1) {\n d = min(d, i - lst(a))\n }\n lst(a) = i\n }\n if (d == inf) out.println(-1)\n else out.println(d + 1)\n }\n }\n }\n}", "positive_code": [{"source_code": "object C1257 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var t = readInt\n while (t > 0) {\n val n = readInt\n val arr = readInts(n)\n var res = Integer.MAX_VALUE\n val lastPos = cu.Map.empty[Int, Int]\n var i = 0\n while (i < n) {\n if (lastPos.contains(arr(i)) && i - lastPos(arr(i)) >= 1) {\n res = math.min(res, i - lastPos(arr(i)) + 1)\n }\n lastPos(arr(i)) = i\n i += 1\n }\n if (res == Integer.MAX_VALUE)\n res = -1\n out.println(res)\n t -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [], "src_uid": "a4be9b3484f3f24014392a1c3ad23f2f"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n in.next()\n val pair = in.next().foldLeft(0, 0) {\n case ((a, d), 'A') => (a + 1, d)\n case ((a, d), 'D') => (a, d + 1)\n case (acc, _) => acc\n }\n if (pair._1 == pair._2)\n println(\"Friendship\")\n else if (pair._1 > pair._2)\n println(\"Anton\")\n else\n println(\"Danik\")\n}", "positive_code": [{"source_code": "object _734 extends App {\n implicit class Pipe[T](val v: T) extends AnyVal {\n def |>[U](f: T => U): U = f(v)\n }\n\n val std = scala.io.StdIn\n val _ = std.readLine()\n val line = std.readLine()\n val aCount = line.filter(c => c == 'A').size\n val dCount = line.size - aCount\n (if (aCount > dCount) \"Anton\"\n else if (dCount > aCount) \"Danik\"\n else \"Friendship\") |> print\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _734A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n = read[Int]\n val s = read[String].toSeq.toMultiSet\n\n val ans = if (s('A') > s('D')) {\n \"Anton\"\n } else if (s('A') < s('D')) {\n \"Danik\"\n } else {\n \"Friendship\"\n }\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn._\nobject Solution {\n def main(args: Array[String]): Unit = {\n val n = readInt\n val ds = readLine.count(_ == 'D')\n val as = n - ds\n println(if (as == ds) \"Friendship\" else if (as > ds) \"Anton\" else \"Danik\")\n }\n}\n"}, {"source_code": "/**\n * Created by yusaku on 17/06/14.\n */\n\nimport scala.io.StdIn\n\nobject App {\n def main(args: Array[String]): Unit = {\n StdIn.readLine()\n val s = StdIn.readLine()\n var a, d = 0\n for (c <- s) {\n if (c == 'A') {\n a += 1\n } else {\n d += 1\n }\n }\n\n if (a > d) {\n print(\"Anton\")\n } else if (d > a) {\n print(\"Danik\")\n } else {\n print(\"Friendship\")\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main2 extends App {\n val scanner = new Scanner(System.in)\n val gameNumber = scanner.nextInt()\n val gameResults = scanner.next()\n val res = (gameResults.count(_ == 'A'), gameResults.count(_ == 'D')) match {\n case (a, d) if a > d => \"Anton\"\n case (a, d) if a < d => \"Danik\"\n case (a, d) if a == d => \"Friendship\"\n }\n println(res)\n}\n"}, {"source_code": "object Solution extends App {\n val n = readInt\n val gs = readLine\n \n val a = gs.count(_ == 'A')\n val d = gs.count(_ == 'D')\n \n if(a == d) {\n println(\"Friendship\")\n } else if(a < d ) {\n println(\"Danik\")\n } else {\n println(\"Anton\")\n }\n \n}"}, {"source_code": "import scala.io.StdIn._\n\nobject TaskA extends App {\n readInt()\n val (a, d) = readLine().toSeq.partition(_ == 'A')\n println(if (a.size > d.size) \"Anton\" else if (a.size < d.size) \"Danik\" else \"Friendship\")\n}\n"}, {"source_code": "object ScannerTest {\n\n def getWinner(games: String): String = {\n val occ = games.groupBy(c => c) mapValues (s => s.length) withDefaultValue 0\n val danikWins = occ('D')\n val antonWins = occ('A')\n\n if (danikWins > antonWins) \"Danik\"\n else if (antonWins > danikWins) \"Anton\"\n else \"Friendship\"\n }\n\n def main(args: Array[String]) {\n readLine()\n println(getWinner(readLine()))\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject M734A {\n def main(args: Array[String]): Unit = {\n val n = readInt\n val an = readLine.count(_ == 'A')\n val dn = n - an\n val winner = if(an == dn) {\"Friendship\" } else if(an > dn){\"Anton\"} else {\"Danik\"}\n println(winner)\n }\n}\n"}, {"source_code": "object AntonAndDanik extends App{\n val matches: Int = scala.io.StdIn.readInt()\n val results: String = scala.io.StdIn.readLine()\n\n val anton = results.count(_ == 'A')\n //val danik = results.length() - anton\n val danik = results.count(_ == 'D')\n\n if (anton > danik) println(\"Anton\")\n else if (danik > anton) println(\"Danik\")\n else println(\"Friendship\")\n \n}\n"}, {"source_code": "object AntonAndDanik extends App{\n val matches: Int = scala.io.StdIn.readInt()\n val results: String = scala.io.StdIn.readLine()\n\n val anton = results.filter(_ == 'A').length()\n val danik = results.filter(_ == 'D').length()\n\n if (anton > danik) println(\"Anton\")\n else if (danik > anton) println(\"Danik\")\n else println(\"Friendship\")\n \n}\n"}, {"source_code": "object AntonAndDanik extends App{\n val matches: Int = scala.io.StdIn.readInt()\n val results: String = scala.io.StdIn.readLine()\n\n val anton = results.count(_ == 'A')\n val danik = results.length() - anton\n\n if (anton > danik) println(\"Anton\")\n else if (danik > anton) println(\"Danik\")\n else println(\"Friendship\")\n \n}\n"}, {"source_code": "object AntonAndDanik extends App{\n val matches: Int = scala.io.StdIn.readInt()\n val results: String = scala.io.StdIn.readLine()\n\n val anton = results.filter(_ == 'A').size\n val danik = results.length() - anton\n\n if (anton > danik) println(\"Anton\")\n else if (danik > anton) println(\"Danik\")\n else println(\"Friendship\")\n \n}\n"}, {"source_code": "object AntonAndDanik extends App{\n val matches: Int = scala.io.StdIn.readInt()\n val results: String = scala.io.StdIn.readLine()\n\n var anton = 0\n var danik = 0\n\n results.foreach(c => \n if(c == 'A') anton+=1\n else danik+=1\n )\n\n if( anton > danik) println(\"Anton\")\n else if (danik > anton) println(\"Danik\")\n else println(\"Friendship\")\n \n}\n"}, {"source_code": "object CF0734A extends App {\n val n = readInt()\n val str = readLine().split(\"\").toList\n\n val A = str.filter(_ == \"A\").size\n val D = str.filter(_ == \"D\").size\n\n if(A > D) {\n println(\"Anton\")\n } else if (A < D) {\n println(\"Danik\")\n } else {\n println(\"Friendship\")\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject AntonAndDanik extends App {\n\n val games = StdIn.readLine().toInt\n val results = StdIn.readLine()\n print(impl(results))\n\n def impl(results: String): String = {\n var antonWins = 0\n var danikWins = 0\n for (result <- results) {\n if (result == 'A') {\n antonWins += 1\n } else {\n danikWins += 1\n }\n }\n\n if (antonWins > danikWins) {\n \"Anton\"\n } else if (danikWins > antonWins) {\n \"Danik\"\n } else {\n \"Friendship\"\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Ex extends App {\n val scanner = new Scanner(System.in)\n val n: Int = scanner.nextInt()\n val games: String = scanner.next()\n var a = 0\n var b = 0\n games.foreach(ch => if (ch == 'A') a += 1 else b += 1)\n println(if (a > b) \"Anton\" else if (a == b) \"Friendship\" else \"Danik\")\n}"}, {"source_code": "// package codeforces.problemset.p734A\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val a = scala.io.Source.stdin.getLines()\n val n = a.next().toInt\n // println(n)\n val s = a.next()\n // println(s)\n val x = s.count(_ == 'A')\n val y = s.count(_ == 'D')\n println(if (x > y) \"Anton\" else if (x < y) \"Danik\" else \"Friendship\")\n\n }\n}\n"}, {"source_code": "import scala.io.StdIn\nobject AntonDanik extends App\n{\n val numOfGames = StdIn.readInt()\n val input = StdIn.readLine()\n\n val anton = input.filter(_ == 'A').length\n val danik = numOfGames - anton\n\n if(anton > danik)\n {\n println(\"Anton\")\n }\n else if(anton < danik)\n {\n println(\"Danik\")\n } else println(\"Friendship\")\n}\n"}, {"source_code": "object A734 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = scala.io.StdIn.readLine\n val A = input.count(_=='A')\n val D = input.size - A\n val ans = if(A > D) {\n \"Anton\"\n } else if(A < D) {\n \"Danik\"\n } else {\n \"Friendship\"\n }\n println(ans)\n }\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn._\nobject Solution {\n def main(args: Array[String]): Unit = {\n val n = readInt\n val ds = readLine.count(_ == 'd')\n val as = n - ds\n println(if (as == ds) \"Friendship\" else if (as > ds) \"Anton\" else \"Danik\")\n }\n}\n"}, {"source_code": "object ScannerTest {\n\n def getWinner(games: String): String = {\n val occ = \"AADDA\".groupBy(c => c) mapValues (s => s.length) withDefaultValue 0\n val danikWins = occ('D')\n val antonWins = occ('A')\n\n if (danikWins > antonWins) \"Danik\"\n else if (antonWins > danikWins) \"Anton\"\n else \"Friendship\"\n }\n\n def main(args: Array[String]) {\n readLine()\n println(getWinner(readLine()))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val pair = in.next().foldLeft(0, 0) {\n case ((a, d), 'A') => (a + 1, d)\n case ((a, d), 'D') => (a, d + 1)\n case (acc, _) => acc\n }\n if (pair._1 == pair._2)\n println(\"Friendship\")\n else if (pair._1 > pair._2)\n println(\"Anton\")\n else\n println(\"Danik\")\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val pair = in.next().foldLeft(0, 0) {\n case ((a, d), 'A') => (a + 1, d)\n case ((a, d), 'B') => (a, d + 1)\n case (acc, _) => acc\n }\n if (pair._1 == pair._2)\n println(\"Friendship\")\n else if (pair._1 > pair._2)\n println(\"Anton\")\n else\n println(\"Danik\")\n}"}], "src_uid": "0de32a7ccb08538a8d88239245cef50b"} {"source_code": "import scala.io.StdIn._\nimport scala.math._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val t = readInt\n (0 until t).foreach { _ =>\n val nq = readLine.split(\" \").map(_.toInt)\n val n = nq.head\n val a = readLine.split(\" \").map(_.toLong)\n val d1 = new Array[Long](n + 1)\n val d2 = new Array[Long](n + 1)\n d1(0) = -(300000 + 1)\n d2(0) = 0\n var i = 0\n for (k <- a) {\n d1(i + 1) = max(d1(i), d2(i) + k)\n d2(i + 1) = max(d2(i), d1(i) - k)\n i = i + 1\n }\n println(max(d1(n), d2(n)))\n }\n }\n}\n", "positive_code": [{"source_code": "object C1 extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, _) = readLine().split(\" \").map(_.toInt)\n val an = readLine().split(\" \").map(_.toInt)\n\n val (ans1, ans2) = an.foldLeft((0L, 0L)) {\n case ((dp1, dp2), a) => (dp1 max (dp2 - a), dp2 max (dp1 + a))\n }\n\n val ans = ans1 max ans2\n\n println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "object C1 extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, _) = readLine().split(\" \").map(_.toInt)\n val an = readLine().split(\" \").map(_.toInt)\n\n val (ans1, ans2) = an.foldLeft((0L, 0L)) {\n case ((dp1, dp2), a) => (dp1 max (dp2 - a), dp2 max (dp1 + a))\n }\n\n val ans = ans1 max ans2\n }\n}\n"}], "src_uid": "2d088e622863ab0d966862ec29588db1"} {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\r\n val an = readLine().split(\" \").map(_.toInt)\r\n val bn = an.zipWithIndex.sorted\r\n\r\n val r = bn.tail.foldLeft((1, bn.head._2)) {\r\n case ((count, i), (_, j)) if j == i + 1 => (count, j)\r\n case ((count, _), (_, j)) => (count + 1, j)\r\n }._1\r\n\r\n if (r <= k) println(\"YES\") else println(\"NO\")\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.io.StdIn._\r\n\r\nobject _1557B {\r\n\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt()\r\n while (t > 0) {\r\n t -= 1\r\n val Array(n, k) = ni();\r\n val ar = ni()\r\n val br = ar.zipWithIndex.sorted\r\n// println(br.mkString(\", \"));\r\n var count = 0;\r\n for(i <- 0 until n - 1)\r\n if(br(i)._2 + 1 != br(i + 1)._2)count += 1;\r\n\r\n if(count < k)println(\"Yes\");\r\n else println(\"No\")\r\n }\r\n }\r\n def ni(): Array[Int] = {\r\n readLine().split(\" \").map(_.toInt)\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\r\n\r\nobject _1557B {\r\n\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt()\r\n while (t > 0) {\r\n t -= 1\r\n val Array(n, k) = ni();\r\n val ar = ni()\r\n var count = 0;\r\n for(i <- 0 until n - 1)\r\n if(ar(i) >= ar(i + 1))count += 1;\r\n\r\n if(count < k)println(\"Yes\");\r\n else println(\"No\")\r\n }\r\n }\r\n def ni(): Array[Int] = {\r\n readLine().split(\" \").map(_.toInt)\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn._\r\n\r\nobject _1557B {\r\n\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt()\r\n while (t > 0) {\r\n t -= 1\r\n val Array(n, k) = ni();\r\n val ar = ni()\r\n var count = 0;\r\n for(i <- 0 until n - 1)\r\n if(ar(i) > ar(i + 1))count += 1;\r\n\r\n if(count < k)println(\"Yes\");\r\n else println(\"No\")\r\n }\r\n }\r\n def ni(): Array[Int] = {\r\n readLine().split(\" \").map(_.toInt)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\r\n val an = readLine().split(\" \").map(_.toInt)\r\n val bn = an.zipWithIndex.sorted\r\n\r\n val r = bn.tail.foldLeft((0, bn.head._2)) {\r\n case ((count, i), (_, j)) if j == i + 1 => (count, j)\r\n case ((count, _), (_, j)) => (count + 1, j)\r\n }._1\r\n\r\n if (r <= k) println(\"YES\") else println(\"NO\")\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n val bm = an.foldLeft(List.empty[List[Int]]) {\r\n case ((l @ (ap :: _)) :: ls, ac) if ac >= ap => (ac :: l) :: ls\r\n case (ls, ac) => List(ac) :: ls\r\n }\r\n\r\n val ans = bm.length == k && bm.reverse.flatten.sameElements(an.sorted(Ordering[Int].reverse))\r\n\r\n if (ans) println(\"YES\") else println(\"NO\")\r\n }\r\n}\r\n"}], "src_uid": "255d6fca1379ae40b03e761802f36664"} {"source_code": "object A177 {\n \n def R = readLine().split(\" \").toList map(_.toInt)\n \n def main(args: Array[String]): Unit = {\n var N = R\n var n = N.head\n var k = N.tail.head\n \n def helper(acc: Int, sum: Int): Int = {\n \n if(acc > n)\n {\n sum\n }\n else\n { \n var foo = R\n var a = foo.head\n var b = foo.tail.head\n helper(acc+1, sum+b-a+1)\n }\n } \n\n var sumX = helper(1,0)\n if(sumX%k == 0)\n {\n println(0)\n \n }\n else\n {\n println(k-sumX%k)\n }\n \n \n }\n \n \n \n }", "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\nimport java.util.Scanner\n\nobject Segments extends App {\n\n\t// scan input\n\tval scanner = new Scanner( System.in )\n\tval n = scanner.nextInt\n\tval k = scanner.nextInt\n\tval input: ArrayBuffer[(Int,Int)] = ArrayBuffer.empty\n\tfor( i <- 1 to n)\n\t\tinput += (( scanner.nextInt, scanner.nextInt ))\n\tval segments = input.sortBy( _._1 ).toIndexedSeq\t// sort the segments\n\n\tval value = (0 /: segments)( (l,e) => l + e._2 - e._1 + 1 ) \t// check value (total length) of segments\n\n\tval moves = ( k - value % k ) % k\t// check required moves\n\n\t/* not required by test\n\t// check if there is a place for those moves - check distances between segments and absolute margins\n\t// minimal and maximal value\n\tfinal val MIN_MAX = 10000\n\tval left = segments.head._1 + MIN_MAX\n\tval right = MIN_MAX - segments.last._2\n\tval distance = (left /: segments.sliding( 2 )) ( (d, pair) => d + pair.last._1 - pair.head._2 - 1 ) + right\n\t// if( distance < moves ) then there is no solution\n\t*/\n\n\tprintln( moves )\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val data = (1 to n).map{_ =>\n val r = in.next().split(' ').map(_.toInt)\n r.last - r.head + 1\n }.sum\n val left = data % k\n if (left == 0)\n println(0)\n else\n println(k - left)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject P289A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N, K = sc.nextInt\n\n val sum = Stream.fill(N)(- sc.nextInt + sc.nextInt + 1).sum\n val res = (K - sum % K) % K\n\n out.println(res)\n out.close\n}\n\n\n\n\n\n"}, {"source_code": "object A {\n def READ: Array[Int] = readLine() split (\" \") map (_.toInt);\n\n def main(args: Array[String]) {\n var Array(n, k) = READ;\n var s = 0;\n for (i <- 1 to n){\n var Array(a,b) = READ;\n s += b-a+1;\n };\n println(if (s%k == 0) 0 else k-s%k);\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val nk = readLine().split(\" \").map(_.toInt)\n val n = nk(0)\n val k = nk(1)\n \n val a = (1 to n).map(_ => readLine().split(\" \").map(_.toInt))\n val sum = a.map(a0 => a0(1) - a0(0) + 1).sum\n println((k - (sum % k)) % k)\n }\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val data = (1 to n).map{_ =>\n val r = in.next().split(' ').map(_.toInt)\n r.last - r.head + 1\n }.sum\n val left = data % k\n println(k - left)\n}"}], "src_uid": "3a93a6f78b41cbb43c616f20beee288d"} {"source_code": "object Match extends App {\n\tval (s0, s1) = (readLine, readLine)\n\n\tdef shortest (s : String) : Array[Int] = {\n\t\tval (buf, ans) = (Array.fill(s.length + 1)(0), Array.fill(s.length)(0))\n\t\tfor (i <- s.length - 1 to 0 by -1) {\n\t\t\tfor (j <- 0 until s.length) {\n\t\t\t\tif (s(i) == s(j) && i != j) {\n\t\t\t\t\tbuf(j) = buf(j + 1) + 1\n\t\t\t\t\tans(i) = math.max(ans(i), buf(j))\n\t\t\t\t} else buf(j) = 0\n\t\t\t}\n\t\t}\n\t\tans\n\t}\n\n\tval (m0, m1) = (shortest(s0), shortest(s1))\n\tval (buf, inf) = (Array.fill(s1.length + 1)(0), 123456)\n\tvar ans = inf\n\tfor (i <- s0.length - 1 to 0 by -1) {\n\t\tfor (j <- 0 until s1.length) {\n\t\t\tif (s0(i) == s1(j)) {\n\t\t\t\tbuf(j) = buf(j + 1) + 1\n\t\t\t\tif (buf(j) > m0(i) && buf(j) > m1(j)) {\n\t\t\t\t\tans = math.min(ans, 1 + math.max(m0(i), m1(j)))\n\t\t\t\t}\n\t\t\t} else buf(j) = 0\n\t\t}\n\t}\n\n\tprint(if (ans < inf) ans else -1)\n}\n", "positive_code": [{"source_code": "\nobject Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S1, S2 = ns()\n val S = S1 + \"$\" + S2\n\n val sa = suffixArray(S)\n val (lcp, rank) = longestCommonPrefix(S, sa)\n\n /**\n * これ以上の長さの部分文字列じゃないと重複が存在する\n */\n def limits(s: String) = {\n val sa = suffixArray(s)\n val (lcp, _) = longestCommonPrefix(s, sa)\n val res = Array.ofDim[Int](s.length + 1)\n val n = lcp.length\n REP(n) { i =>\n if (i == n - 1) {\n res(sa(i)) = lcp(i)\n } else {\n res(sa(i)) = max(lcp(i), lcp(i + 1))\n }\n }\n res\n }\n\n val limit1 = limits(S1)\n val limit2 = limits(S2)\n\n val INF = 1e6.toInt\n var ans = INF\n\n // debug\n// REP(sa.length) { i =>\n// System.err.println(s\"$i ${S.substring(sa(i))}\")\n// }\n\n REP(lcp.length) { i =>\n if (lcp(i) > 0) {\n val p1 = min(sa(i), sa(i - 1))\n val p2 = max(sa(i), sa(i - 1))\n\n // p1がS1に, p2がS2に含まれる\n if (p1 < S1.length && p2 > S1.length) {\n val p2OnS2 = p2 - S1.length - 1\n val mxLim = max(limit1(p1), limit2(p2OnS2))\n\n // p1, p2ともに重複制限に引っかからない最短の文字列\n val len = mxLim + 1\n\n // lcpがlenを作れる程に十分長い\n if (len <= lcp(i)) {\n // p1+lelnがS1を超えない\n if (p1 + len <= S1.length) {\n // debug\n// System.err.println(s\"$i ${S.substring(p1, p1 + len)}\")\n ans = min(ans, len)\n }\n }\n }\n }\n }\n\n if (ans == INF) ans = -1\n out.println(ans)\n }\n\n /**\n * LCPには一個手前の文字との共通の文字数が入っている\n * @return (LCP, 文字列の位置 => 辞書順の位)\n */\n def longestCommonPrefix(s: String, sa: Array[Int]): (Array[Int], Array[Int]) = {\n val n = s.length\n val lcp = Array.ofDim[Int](n + 1)\n val rank = Array.ofDim[Int](n + 1)\n REP(n + 1) { i =>\n rank(sa(i)) = i\n }\n var h = 0\n REP(n) { i =>\n val j = sa(rank(i) - 1) // sa上で1個前\n h = max(0, h - 1)\n while(i + h < n && j + h < n && s(i + h) == s(j + h)) {\n h += 1\n }\n lcp(rank(i)) = h\n }\n (lcp, rank)\n }\n\n\n /**\n * 大文字小文字が混ざってる場合はうまくいかないので注意\n * @return 辞書順 => 文字列の位置\n */\n def suffixArray(s: String): Array[Int] = {\n val n = s.length\n\n val sa = Array.iterate(0, n + 1)(_ + 1)\n val rank, tmp = Array.ofDim[Int](n + 1)\n REP(n) { i =>\n rank(i) = s(i)\n }\n rank(n) = -1\n\n def lt(len: Int)(i: Int, j: Int): Boolean = {\n if (rank(i) != rank(j)) rank(i) < rank(j)\n else {\n // 長さが足りないってことは文字がないてことなので、辞書順で先になる\n val ri = if (i + len <= n) rank(i + len) else -1\n val rj = if (j + len <= n) rank(j + len) else -1\n ri < rj\n }\n }\n\n var len = 1\n while(len <= n) {\n // 今のランクとダブリングをつかってlen*2までの長さで並び替える\n Sorting.quickSort[Int](sa)(Ordering.fromLessThan(lt(len)))\n\n // 次のlen*2の長さで並び替えたsaからrankの値を計算する\n tmp(sa(0)) = 0\n REP(n, 1) { i =>\n tmp(sa(i)) = tmp(sa(i - 1)) + (if (lt(len)(sa(i - 1), sa(i))) 1 else 0) // 前の順位のものより大きい場合は+1する\n }\n\n Array.copy(tmp, 0, rank, 0, n + 1)\n len *= 2\n }\n sa\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "\nobject Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S1, S2 = ns()\n val S = S1 + S2\n\n val sa = suffixArray(S)\n val (lcp, rank) = longestCommonPrefix(S, sa)\n\n /**\n * これ以上の長さの部分文字列じゃないと重複が存在する\n */\n def limits(s: String) = {\n val sa = suffixArray(s)\n val (lcp, _) = longestCommonPrefix(s, sa)\n val res = Array.ofDim[Int](s.length + 1)\n val n = lcp.length\n REP(n) { i =>\n if (i == n - 1) {\n res(sa(i)) = lcp(i)\n } else {\n res(sa(i)) = max(lcp(i), lcp(i + 1))\n }\n }\n res\n }\n\n val limit1 = limits(S1)\n val limit2 = limits(S2)\n\n val INF = 1e6.toInt\n var ans = INF\n\n // debug\n// REP(sa.length) { i =>\n// System.err.println(s\"$i ${S.substring(sa(i))}\")\n// }\n\n REP(lcp.length) { i =>\n if (lcp(i) > 0) {\n val p1 = min(sa(i), sa(i - 1))\n val p2 = max(sa(i), sa(i - 1))\n\n // p1がS1に, p2がS2に含まれる\n if (p1 <= S1.length && p2 >= S1.length) {\n val p2OnS2 = p2 - S1.length\n val mxLim = max(limit1(p1), limit2(p2OnS2))\n val len = mxLim + 1\n // p1, p2ともに重複制限に引っかからない程の長い文字列\n if (len <= lcp(i)) {\n // p1+lがS1を超えない\n if (p1 + len <= S1.length) {\n // debug\n// System.err.println(s\"$i ${S.substring(p1, p1 + len)}\")\n ans = min(ans, len) // 引っかからない最短の文字列\n }\n }\n }\n }\n }\n\n if (ans == INF) ans = -1\n out.println(ans)\n }\n\n /**\n * LCPには一個手前の文字との共通の文字数が入っている\n * @return (LCP, 文字列の位置 => 辞書順の位)\n */\n def longestCommonPrefix(s: String, sa: Array[Int]): (Array[Int], Array[Int]) = {\n val n = s.length\n val lcp = Array.ofDim[Int](n + 1)\n val rank = Array.ofDim[Int](n + 1)\n REP(n + 1) { i =>\n rank(sa(i)) = i\n }\n var h = 0\n REP(n) { i =>\n val j = sa(rank(i) - 1) // sa上で1個前\n h = max(0, h - 1)\n while(i + h < n && j + h < n && s(i + h) == s(j + h)) {\n h += 1\n }\n lcp(rank(i)) = h\n }\n (lcp, rank)\n }\n\n\n /**\n * 大文字小文字が混ざってる場合はうまくいかないので注意\n * @return 辞書順 => 文字列の位置\n */\n def suffixArray(s: String): Array[Int] = {\n val n = s.length\n\n val sa = Array.iterate(0, n + 1)(_ + 1)\n val rank, tmp = Array.ofDim[Int](n + 1)\n REP(n) { i =>\n rank(i) = s(i)\n }\n rank(n) = -1\n\n def lt(len: Int)(i: Int, j: Int): Boolean = {\n if (rank(i) != rank(j)) rank(i) < rank(j)\n else {\n // 長さが足りないってことは文字がないてことなので、辞書順で先になる\n val ri = if (i + len <= n) rank(i + len) else -1\n val rj = if (j + len <= n) rank(j + len) else -1\n ri < rj\n }\n }\n\n var len = 1\n while(len <= n) {\n // 今のランクとダブリングをつかってlen*2までの長さで並び替える\n Sorting.quickSort[Int](sa)(Ordering.fromLessThan(lt(len)))\n\n // 次のlen*2の長さで並び替えたsaからrankの値を計算する\n tmp(sa(0)) = 0\n REP(n, 1) { i =>\n tmp(sa(i)) = tmp(sa(i - 1)) + (if (lt(len)(sa(i - 1), sa(i))) 1 else 0) // 前の順位のものより大きい場合は+1する\n }\n\n Array.copy(tmp, 0, rank, 0, n + 1)\n len *= 2\n }\n sa\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "\nobject Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S1, S2 = ns()\n val S = S1 + S2\n\n val sa = suffixArray(S)\n val (lcp, rank) = longestCommonPrefix(S, sa)\n\n /**\n * これ以上の長さの部分文字列じゃないと重複が存在する\n */\n def limits(s: String) = {\n val sa = suffixArray(s)\n val (lcp, _) = longestCommonPrefix(s, sa)\n val res = Array.ofDim[Int](s.length + 1)\n val n = lcp.length\n REP(n) { i =>\n if (i == n - 1) {\n res(sa(i)) = lcp(i)\n } else {\n res(sa(i)) = max(lcp(i), lcp(i + 1))\n }\n }\n res\n }\n\n val limit1 = limits(S1)\n val limit2 = limits(S2)\n\n val INF = 1e6.toInt\n var ans = INF\n\n// REP(sa.length) { i =>\n// System.err.println(s\"$i ${S.substring(sa(i))}\")\n// }\n\n REP(lcp.length) { i =>\n if (lcp(i) > 0) {\n val p1 = min(sa(i), sa(i - 1))\n val p2 = max(sa(i), sa(i - 1))\n\n // p1がS1に, p2がS2に含まれる\n if (p1 <= S1.length && p2 >= S1.length) {\n val p2OnS2 = p2 - S1.length\n val mxLim = max(limit1(p1), limit2(p2OnS2))\n // p1, p2ともに重複制限に引っかからない程の長い文字列\n if (mxLim < lcp(i)) {\n val len = mxLim + 1\n // p1+lがS1を超えない\n// if (len <= S.length) {\n ans = min(ans, len) // 引っかからない最短の文字列\n// }\n }\n }\n }\n }\n\n if (ans == INF) ans = -1\n out.println(ans)\n }\n\n /**\n * LCPには一個手前の文字との共通の文字数が入っている\n * @return (LCP, 文字列の位置 => 辞書順の位)\n */\n def longestCommonPrefix(s: String, sa: Array[Int]): (Array[Int], Array[Int]) = {\n val n = s.length\n val lcp = Array.ofDim[Int](n + 1)\n val rank = Array.ofDim[Int](n + 1)\n REP(n + 1) { i =>\n rank(sa(i)) = i\n }\n var h = 0\n REP(n) { i =>\n val j = sa(rank(i) - 1) // sa上で1個前\n h = max(0, h - 1)\n while(i + h < n && j + h < n && s(i + h) == s(j + h)) {\n h += 1\n }\n lcp(rank(i)) = h\n }\n (lcp, rank)\n }\n\n\n /**\n * 大文字小文字が混ざってる場合はうまくいかないので注意\n * @return 辞書順 => 文字列の位置\n */\n def suffixArray(s: String): Array[Int] = {\n val n = s.length\n\n val sa = Array.iterate(0, n + 1)(_ + 1)\n val rank, tmp = Array.ofDim[Int](n + 1)\n REP(n) { i =>\n rank(i) = s(i)\n }\n rank(n) = -1\n\n def lt(len: Int)(i: Int, j: Int): Boolean = {\n if (rank(i) != rank(j)) rank(i) < rank(j)\n else {\n // 長さが足りないってことは文字がないてことなので、辞書順で先になる\n val ri = if (i + len <= n) rank(i + len) else -1\n val rj = if (j + len <= n) rank(j + len) else -1\n ri < rj\n }\n }\n\n var len = 1\n while(len <= n) {\n // 今のランクとダブリングをつかってlen*2までの長さで並び替える\n Sorting.quickSort[Int](sa)(Ordering.fromLessThan(lt(len)))\n\n // 次のlen*2の長さで並び替えたsaからrankの値を計算する\n tmp(sa(0)) = 0\n REP(n, 1) { i =>\n tmp(sa(i)) = tmp(sa(i - 1)) + (if (lt(len)(sa(i - 1), sa(i))) 1 else 0) // 前の順位のものより大きい場合は+1する\n }\n\n Array.copy(tmp, 0, rank, 0, n + 1)\n len *= 2\n }\n sa\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "\nobject Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S1, S2 = ns()\n val S = S1 + S2\n\n val sa = suffixArray(S)\n val (lcp, rank) = longestCommonPrefix(S, sa)\n\n /**\n * これ以上の長さの部分文字列じゃないと重複が存在する\n */\n def limits(s: String) = {\n val sa = suffixArray(s)\n val (lcp, _) = longestCommonPrefix(s, sa)\n val res = Array.ofDim[Int](s.length + 1)\n val n = lcp.length\n REP(n) { i =>\n if (i == n - 1) {\n res(sa(i)) = lcp(i)\n } else {\n res(sa(i)) = max(lcp(i), lcp(i + 1))\n }\n }\n res\n }\n\n val limit1 = limits(S1)\n val limit2 = limits(S2)\n\n val INF = 1e6.toInt\n var ans = INF\n\n // debug\n// REP(sa.length) { i =>\n// System.err.println(s\"$i ${S.substring(sa(i))}\")\n// }\n\n REP(lcp.length) { i =>\n if (lcp(i) > 0) {\n val p1 = min(sa(i), sa(i - 1))\n val p2 = max(sa(i), sa(i - 1))\n\n // p1がS1に, p2がS2に含まれる\n if (p1 < S1.length && p2 >= S1.length) {\n val p2OnS2 = p2 - S1.length\n val mxLim = max(limit1(p1), limit2(p2OnS2))\n\n // p1, p2ともに重複制限に引っかからない最短の文字列\n val len = mxLim + 1\n\n // lcpがlenを作れる程に十分長い\n if (len <= lcp(i)) {\n // p1+lelnがS1を超えない\n if (p1 + len <= S1.length) {\n // debug\n// System.err.println(s\"$i ${S.substring(p1, p1 + len)}\")\n ans = min(ans, len)\n }\n }\n }\n }\n }\n\n if (ans == INF) ans = -1\n out.println(ans)\n }\n\n /**\n * LCPには一個手前の文字との共通の文字数が入っている\n * @return (LCP, 文字列の位置 => 辞書順の位)\n */\n def longestCommonPrefix(s: String, sa: Array[Int]): (Array[Int], Array[Int]) = {\n val n = s.length\n val lcp = Array.ofDim[Int](n + 1)\n val rank = Array.ofDim[Int](n + 1)\n REP(n + 1) { i =>\n rank(sa(i)) = i\n }\n var h = 0\n REP(n) { i =>\n val j = sa(rank(i) - 1) // sa上で1個前\n h = max(0, h - 1)\n while(i + h < n && j + h < n && s(i + h) == s(j + h)) {\n h += 1\n }\n lcp(rank(i)) = h\n }\n (lcp, rank)\n }\n\n\n /**\n * 大文字小文字が混ざってる場合はうまくいかないので注意\n * @return 辞書順 => 文字列の位置\n */\n def suffixArray(s: String): Array[Int] = {\n val n = s.length\n\n val sa = Array.iterate(0, n + 1)(_ + 1)\n val rank, tmp = Array.ofDim[Int](n + 1)\n REP(n) { i =>\n rank(i) = s(i)\n }\n rank(n) = -1\n\n def lt(len: Int)(i: Int, j: Int): Boolean = {\n if (rank(i) != rank(j)) rank(i) < rank(j)\n else {\n // 長さが足りないってことは文字がないてことなので、辞書順で先になる\n val ri = if (i + len <= n) rank(i + len) else -1\n val rj = if (j + len <= n) rank(j + len) else -1\n ri < rj\n }\n }\n\n var len = 1\n while(len <= n) {\n // 今のランクとダブリングをつかってlen*2までの長さで並び替える\n Sorting.quickSort[Int](sa)(Ordering.fromLessThan(lt(len)))\n\n // 次のlen*2の長さで並び替えたsaからrankの値を計算する\n tmp(sa(0)) = 0\n REP(n, 1) { i =>\n tmp(sa(i)) = tmp(sa(i - 1)) + (if (lt(len)(sa(i - 1), sa(i))) 1 else 0) // 前の順位のものより大きい場合は+1する\n }\n\n Array.copy(tmp, 0, rank, 0, n + 1)\n len *= 2\n }\n sa\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "\nobject Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S1, S2 = ns()\n val S = S1 + S2\n\n val sa = suffixArray(S)\n val (lcp, rank) = longestCommonPrefix(S, sa)\n\n /**\n * これ以上の長さの部分文字列じゃないと重複が存在する\n */\n def limits(s: String) = {\n val sa = suffixArray(s)\n val (lcp, _) = longestCommonPrefix(s, sa)\n val res = Array.ofDim[Int](s.length + 1)\n val n = lcp.length\n REP(n) { i =>\n if (i == n - 1) {\n res(sa(i)) = lcp(i)\n } else {\n res(sa(i)) = max(lcp(i), lcp(i + 1))\n }\n }\n res\n }\n\n val limit1 = limits(S1)\n val limit2 = limits(S2)\n\n val INF = 1e6.toInt\n var ans = INF\n\n// REP(sa.length) { i =>\n// System.err.println(s\"$i ${S.substring(sa(i))}\")\n// }\n\n REP(lcp.length) { i =>\n val len = lcp(i)\n if (len > 0) {\n val p1 = min(sa(i), sa(i - 1))\n val p2 = max(sa(i), sa(i - 1))\n\n // [p1, p1+len]がS1に, [p2, p2+len]がS2に含まれる\n if (p1 + len <= S1.length && p2 >= S1.length) {\n val p2OnS2 = p2 - S1.length\n val mxLim = max(limit1(p1), limit2(p2OnS2))\n // p1, p2ともに重複制限に引っかからない程の長い文字列\n if (mxLim < len) {\n ans = min(ans, mxLim + 1) // 引っかからない最短の文字列\n }\n }\n }\n }\n\n if (ans == INF) ans = -1\n out.println(ans)\n }\n\n /**\n * LCPには一個手前の文字との共通の文字数が入っている\n * @return (LCP, 文字列の位置 => 辞書順の位)\n */\n def longestCommonPrefix(s: String, sa: Array[Int]): (Array[Int], Array[Int]) = {\n val n = s.length\n val lcp = Array.ofDim[Int](n + 1)\n val rank = Array.ofDim[Int](n + 1)\n REP(n + 1) { i =>\n rank(sa(i)) = i\n }\n var h = 0\n REP(n) { i =>\n val j = sa(rank(i) - 1) // sa上で1個前\n h = max(0, h - 1)\n while(i + h < n && j + h < n && s(i + h) == s(j + h)) {\n h += 1\n }\n lcp(rank(i)) = h\n }\n (lcp, rank)\n }\n\n\n /**\n * 大文字小文字が混ざってる場合はうまくいかないので注意\n * @return 辞書順 => 文字列の位置\n */\n def suffixArray(s: String): Array[Int] = {\n val n = s.length\n\n val sa = Array.iterate(0, n + 1)(_ + 1)\n val rank, tmp = Array.ofDim[Int](n + 1)\n REP(n) { i =>\n rank(i) = s(i)\n }\n rank(n) = -1\n\n def lt(len: Int)(i: Int, j: Int): Boolean = {\n if (rank(i) != rank(j)) rank(i) < rank(j)\n else {\n // 長さが足りないってことは文字がないてことなので、辞書順で先になる\n val ri = if (i + len <= n) rank(i + len) else -1\n val rj = if (j + len <= n) rank(j + len) else -1\n ri < rj\n }\n }\n\n var len = 1\n while(len <= n) {\n // 今のランクとダブリングをつかってlen*2までの長さで並び替える\n Sorting.quickSort[Int](sa)(Ordering.fromLessThan(lt(len)))\n\n // 次のlen*2の長さで並び替えたsaからrankの値を計算する\n tmp(sa(0)) = 0\n REP(n, 1) { i =>\n tmp(sa(i)) = tmp(sa(i - 1)) + (if (lt(len)(sa(i - 1), sa(i))) 1 else 0) // 前の順位のものより大きい場合は+1する\n }\n\n Array.copy(tmp, 0, rank, 0, n + 1)\n len *= 2\n }\n sa\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "20e13f21610c5614310bcd764662231c"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(var social: Int, var cp: Int, var ind: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (social < that.social)\n return -1\n else if (social == that.social)\n return 0\n else\n return 1\n }\n }\n\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n var h = readInt()\n var tmp = 0\n var mx1 = 0\n var mx2 = 0\n for (i <- 0 until n) {\n tmp = readInt()\n if (tmp > mx2)\n mx2 = tmp\n if (mx2 > mx1){\n tmp = mx1\n mx1 = mx2\n mx2 = tmp\n }\n }\n var cnt = 2 * (h/(mx1+mx2)).toInt\n if (h %(mx1+mx2)!= 0)\n cnt += 1\n if (h%(mx1+mx2)> mx1)\n cnt += 1\n writer.println(cnt)\n }\n writer.flush()\n}\n", "positive_code": [{"source_code": "object A extends App {\r\n\r\n def gamerHemose(an: Array[Int], h: Int): Int = {\r\n val Array(a1, a2, _*) = an.sorted(Ordering[Int].reverse)\r\n\r\n (h / (a1 + a2), h % (a1 + a2)) match {\r\n case (i, 0) => 2 * i\r\n case (i, j) if j <= a1 => 2 * i + 1\r\n case (i, _) => 2 * i + 2\r\n }\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val h = nextInt()\r\n val an = nextInts(n)\r\n\r\n out.println(gamerHemose(an, h))\r\n }\r\n\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}, {"source_code": "object A extends App {\r\n\r\n def gamerHemose(an: Array[Int], h: Int): Int = {\r\n val Array(a1, a2, _*) = an.sorted(Ordering[Int].reverse)\r\n\r\n val (i, j) = (h / (a1 + a2), h % (a1 + a2))\r\n\r\n j match {\r\n case 0 => 2 * i\r\n case j if j <= a1 => 2 * i + 1\r\n case _ => 2 * i + 2\r\n }\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val h = nextInt()\r\n val an = nextInts(n)\r\n\r\n out.println(gamerHemose(an, h))\r\n }\r\n\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(var social: Int, var cp: Int, var ind: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (social < that.social)\n return -1\n else if (social == that.social)\n return 0\n else\n return 1\n }\n }\n\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n var h = readInt()\n var tmp = 0\n var mx1 = 0\n var mx2 = 0\n for (i <- 0 until n) {\n tmp = readInt()\n if (tmp > mx2)\n mx2 = tmp\n if (mx2 > mx1){\n tmp = mx1\n mx1 = mx2\n mx2 = tmp\n }\n }\n var cnt = (2 * h/(mx1+mx2)).toInt\n if (h %(mx1+mx2)!= 0)\n cnt += 1\n if (h%(mx1+mx2)> mx1)\n cnt += 1\n writer.println(cnt)\n }\n writer.flush()\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(var social: Int, var cp: Int, var ind: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (social < that.social)\n return -1\n else if (social == that.social)\n return 0\n else\n return 1\n }\n }\n\n\n val t = readInt()\n for (tt <- 1 to t) {\n var n = readInt()\n var h = readInt()\n val arr = new Array[Int](n)\n for (i <- 0 until n)\n arr(i) = readInt()\n quickSort(arr)\n var cnt = 0\n while (h > 0 && n > 0) {\n cnt += 1\n h -= arr(n-1)\n n -= 1\n }\n writer.println(cnt)\n }\n writer.flush()\n}\n"}, {"source_code": "object A extends App {\r\n\r\n def gamerHemose(an: Array[Int], h: Int): Int = {\r\n val Array(a1, a2, _*) = an.sorted(Ordering[Int].reverse)\r\n h / (a1 + a2) * 2 + (if (h % (a1 + a2) == 0) 0 else 1)\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val h = nextInt()\r\n val an = nextInts(n)\r\n\r\n out.println(gamerHemose(an, h))\r\n }\r\n\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}], "src_uid": "4d5457d9f053556c78c102f5c32f7542"} {"source_code": "object Main {\n import java.io.File\n import java.util.Scanner\n import java.io.PrintWriter\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val pat = \"hard\"\n\n def main(args: Array[String]) {\n val n = in.nextInt\n in.nextLine\n val str = in.nextLine\n val a = (for (i <- 0 until n) yield in.nextInt).toArray\n val f = new Array[Long]((n + 1) * 4)\n for (i <- 1 until n + 1; j <- 0 until 4)\n f(i * 4 + j) = {\n if (str(i - 1) == pat(j)) {\n if (j == 0 || f((i - 1) * 4 + j) + a(i - 1) < f((i - 1) * 4 + j - 1))\n f((i - 1) * 4 + j) + a(i - 1)\n else f((i - 1) * 4 + j - 1)\n }\n else f((i - 1) * 4 + j)\n }\n out.println(f(n * 4 + 3))\n in.close\n out.close\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val S = ns(N).map {\n case 'h' => 1\n case 'a' => 2\n case 'r' => 3\n case 'd' => 4\n case _ => -1\n }\n\n val A = nal(N)\n\n val INF = 1e17.toLong\n val dp = Array.fill[Long](5)(INF)\n dp(0) = 0\n\n REP(N) { i =>\n val s = S(i)\n if (s != -1) {\n if (dp(s - 1) != INF) dp(s) = min(dp(s), dp(s - 1))\n if (dp(s - 1) != INF) dp(s - 1) += A(i)\n }\n }\n\n val ans = map(4) { i =>\n dp(i)\n }.min\n\n if (dp(4) != INF) out.println(ans)\n else out.println(0)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n\n def debug(as: Array[Long], delimiter: String = \" \"): Unit = {\n debug(as.mkString(delimiter))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val S = ns(N).map {\n case 'h' => 1\n case 'a' => 2\n case 'r' => 3\n case 'd' => 4\n case _ => -1\n }\n\n val A = nal(N)\n\n val INF = 1e17.toLong\n val dp = Array.fill[Long](5)(INF)\n dp(0) = 0\n\n REP(N) { i =>\n val s = S(i)\n if (s != -1) {\n if (dp(s - 1) != INF) dp(s) = min(dp(s), dp(s - 1))\n if (dp(s - 1) != INF) dp(s - 1) += A(i)\n }\n// debug(dp)\n }\n\n// debug(dp)\n\n val ans = map(4) { i =>\n dp(i)\n }.min\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n\n def debug(as: Array[Long], delimiter: String = \" \"): Unit = {\n debug(as.mkString(delimiter))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n}"}], "negative_code": [], "src_uid": "8cc22dc6e81bb49b64136e5ff7eb8caf"} {"source_code": "object _1729B extends CodeForcesApp {\n override def solve() = repeat() {\n val _ = nextInt()\n val s = nextStr().toList.map(_ - '0')\n out.println(parse(s))\n }\n\n val table = Seq.tabulate(27)(i => ('a' - 1 + i).toChar)\n\n def parse(chars: List[Int]): String = chars match {\n case Nil => \"\"\n case 0 :: _ => illegal()\n case x :: (r1 @ (y :: 0 :: r2)) if 10*x + y < table.length =>\n try {\n table(10*x + y) + parse(r2)\n } catch {\n case _: Throwable => table(x) + parse(r1)\n }\n case x :: rest => table(x) + parse(rest)\n }\n}\n/**************************** [Ignore Template Below] **************************************/\ntrait CodeForcesApp {\n import java.io._\n var in = new BufferedReader(new InputStreamReader(System.in))\n var out = new PrintWriter(System.out)\n\n val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))\n\n def nextLine(): String = in.readLine()\n def nextStr(): String = tokens.next()\n def nextInt(): Int = nextStr().toInt\n def nextLong(): Long = nextStr().toLong\n def nextDouble(): Double = nextStr().toDouble\n def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n def query[A](query: String, res: => A): A = {out.println(query); out.flush(); res}\n\n def debug(x: => Any): Unit = if (!sys.props.contains(\"ONLINE_JUDGE\")) println(s\">>> DEBUG: $x\")\n def illegal(msg: String = \"can't happen\") = throw new IllegalStateException(msg)\n\n def main(args: Array[String]): Unit = try solve() finally out.flush()\n def solve(): Any\n}\n", "positive_code": [{"source_code": "import scala.util.Try\n\nobject _1729B extends CodeForcesApp {\n override def solve() = repeat() {\n val _ = nextInt()\n val s = nextStr().toList.map(_ - '0')\n printLine(parse(s))\n }\n\n val table = Seq.tabulate(27)(i => ('a' - 1 + i).toChar)\n\n def parse(chars: List[Int]): String = chars match {\n case Nil => \"\"\n case 0 :: _ => throw new IllegalStateException()\n case x :: (r1 @ (y :: 0 :: r2)) if 10*x + y < table.length =>\n Try(table(10*x + y) + parse(r2)).getOrElse(table(x) + parse(r1))\n case x :: rest => table(x) + parse(rest)\n }\n}\n/**************************** [Ignore Template Below] **************************************/\ntrait CodeForcesApp {\n import java.io._\n var in = new BufferedReader(new InputStreamReader(System.in))\n var out = new PrintWriter(System.out)\n\n val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))\n\n def nextLine(): String = in.readLine()\n def nextStr(): String = tokens.next()\n def nextInt(): Int = nextStr().toInt\n def nextLong(): Long = nextStr().toLong\n def nextDouble(): Double = nextStr().toDouble\n def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n def query[A](query: String)(res: => A): A = {printLine(query); out.flush(); res}\n\n def print(xs: Any*): Unit = out.print(xs.mkString(\" \"))\n def printLine(xs: Any*): Unit = if (xs.isEmpty) out.println() else xs.foreach(out.println)\n def debug(x: => Any): Unit = if (!sys.props.contains(\"ONLINE_JUDGE\")) println(s\">>> DEBUG: $x\")\n\n def main(args: Array[String]): Unit = try solve() finally out.flush()\n def solve(): Any\n}\n"}], "negative_code": [], "src_uid": "43081557fe2fbac39dd9b72b137b8fb0"} {"source_code": "object D extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n val ans = n / math\n .sqrt(n)\n .toLong\n .to(1, -1)\n .collect {\n case x if n % x == 0 => List(x, n / x).filter(_ <= k)\n }\n .flatten\n .max\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CF644(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CF644(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val n = ni()\n val k = ni()\n\n if(k >= n) {\n out.println(1)\n } else {\n val l = math.ceil(math.sqrt(n.toDouble)).toInt\n var ans = n\n 2 to l by 1 foreach { f =>\n if(n % f == 0) {\n val u = n / f\n if(u <= k) ans = math.min(ans, f)\n if(f <= k) ans = math.min(ans, u)\n }\n }\n out.println(ans)\n }\n }\n }\n}\n"}], "negative_code": [{"source_code": "object D extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n def x(n: Long): Long =\n if (n <= k) 1\n else if (n % k == 0) n / k\n else if (n % 2 == 0) 2 * x(n / 2)\n else n\n\n val ans = x(n)\n\n println(ans)\n }\n}\n"}, {"source_code": "object D extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n val ans =\n if (n <= k) 1\n else\n k.min(math.sqrt(n).toLong)\n .until(1, -1)\n .find(n % _ == 0)\n .map(x => List(x, n / x).filter(_ <= k).max)\n .getOrElse(n)\n\n println(ans)\n }\n}\n"}, {"source_code": "object D extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n def x(n: Long): Long =\n if (n <= k) 1\n else if (n % 2 == 0) 2 * x(n / 2)\n else n\n\n val ans = x(n)\n\n println(ans)\n }\n}\n"}, {"source_code": "object D extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n val ans =\n if (n <= k) 1\n else k.min(math.sqrt(n).toLong).until(1, -1).find(n % _ == 0).getOrElse(n)\n\n println(ans)\n }\n}\n"}, {"source_code": "object D extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n val ans =\n if (n <= k) 1\n else\n k.min(math.sqrt(n).toLong).until(1, -1).find(n % _ == 0).map(n / _).getOrElse(n)\n\n println(ans)\n }\n}\n"}], "src_uid": "f00eb0452f5933103f1f77ef06473c6a"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val S = nl()\n val L = N - 1\n val minK = (S - 1) / L + 1\n val maxK = S\n if (K < minK || K > maxK) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n var cur = 1\n var direction = 1\n\n val ans = ArrayBuffer[Int]()\n\n def move(dist: Int): Unit = {\n val to = cur + direction * dist\n ans += to\n cur = to\n if (to == 1) direction = 1\n else if (to == N) direction = -1\n }\n\n\n val s = S - K\n val l = L - 1\n if (l == 0) {\n REP(K) { _ => move(1)}\n } else {\n val a = s / l\n val b = K - (s / l + (if (s % l > 0) 1 else 0))\n REP(a.toInt) { _ => move(L) }\n val r = s % l\n if (r > 0) move((r + 1).toInt)\n REP(b.toInt) { _ => move(1) }\n }\n\n out.println(ans.mkString(\" \"))\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "import java.util\n\nobject CF501D extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n val n = in.nextInt\n val k = in.nextInt\n val s = in.nextLong\n\n if (s > (n.toLong-1)*k.toLong || s < k) {\n out.println(\"NO\")\n } else {\n val moves = new util.LinkedList[Long]()\n\n var distByMove = s/k\n var remainder = s%k\n\n var currentPos: Long = 1\n var shifted = false\n for (i <- 0 until k) {\n if (currentPos == 1) {\n currentPos = 1 + distByMove\n // add 1 in the \"remainder\" last steps\n // or 1 step before if k is even xor remainder is even\n if (!shifted || i != k-1) {\n if (k-i <= remainder) {\n currentPos += 1\n } else if (remainder != 0 && k-i <= remainder + 1 && (k%2 == 0 ^ remainder%2 == 0)) {\n currentPos += 1\n shifted = true\n }\n }\n } else {\n if (remainder != 0 && i == k-1 && (k%2 == 0 ^ remainder%2 == 0))\n currentPos = 2\n else\n currentPos = 1\n }\n moves.add(currentPos)\n }\n\n out.println(\"YES\")\n out.println(moves.toArray.mkString(\" \"))\n }\n }\n\n solve\n out.flush\n out.close\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val S = nl()\n val L = N - 1\n val minK = (S - 1) / L + 1\n val maxK = S\n if (K < minK || K > maxK) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n var cur = 1\n var direction = 1\n var k = K\n var s = S\n\n val ans = ArrayBuffer[Int]()\n\n def move(dist: Int): Unit = {\n val to = cur + direction * dist\n ans += to\n cur = to\n if (to == 1) direction = 1\n else if (to == N) direction = -1\n k -= 1\n s -= dist\n }\n\n while(s - k >= L) {\n move(L)\n }\n\n if (s - k + 1 > 0) move((s - k + 1).toInt)\n REP(k) { _ => move(1) }\n\n out.println(ans.mkString(\" \"))\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object Main {\n import java.io._\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N = sc.nextInt()\n val N1 = N - 1\n val K, S = sc.nextLong()\n val ok = K <= S && S <= (N - 1) * K\n if (!ok) out.println(\"NO\")\n else {\n val m = N - 2\n val (a, b, r) = if ((S - K) % m == 0) {\n val a = ((S - K) / m).toInt\n (a, (K - a).toInt, 0)\n } else {\n val r0 = (S - K + 1) % m\n val r = if (r0 == 0) m else r0\n val a = (S - K + 1) / m - (if (r == 8) 1 else 0)\n val b = K - a - 1\n (a.toInt, b.toInt, r.toInt)\n }\n\n var pos = 1\n val moves = ArrayBuffer[Int]()\n rep(a) { _ =>\n pos = pos match {\n case 1 => N\n case N => 1\n }\n moves += pos\n }\n rep(b) { _ =>\n pos = pos match {\n case 1 => 2\n case 2 => 1\n case N => N1\n case N1 => N\n }\n moves += pos\n }\n\n if (r > 0) {\n pos = pos match {\n case 1 => r + 1\n case 2 => r + 2\n case N => N - r\n case N1 => N1 - r\n }\n moves += pos\n }\n\n println(\"YES\")\n println(moves.mkString(\" \"))\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n\n import java.util.StringTokenizer\n\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val S = nl()\n val L = N - 1\n val minK = (S - 1) / L + 1\n val maxK = S\n if (K < minK || K > maxK) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n var cur = 1\n var direction = 1\n\n val ans = ArrayBuffer[Int]()\n\n def move(dist: Int): Unit = {\n val to = cur + direction * dist\n ans += to\n cur = to\n if (to == 1) direction = 1\n else if (to == N) direction = -1\n }\n\n\n val s = S - K\n val l = L - 1\n REP((s / l).toInt) { _ => move(L) }\n val r = s % l\n if (r > 0) move((r + 1).toInt)\n REP((K - ((s + 1) / l + 1)).toInt) { _ => move(1) }\n\n out.println(ans.mkString(\" \"))\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n import java.io._\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N, K = sc.nextInt()\n val N1 = N - 1\n val S = sc.nextLong()\n val ok = K <= S && S <= (N - 1) * K\n if (!ok) out.println(\"NO\")\n else {\n val m = N - 2\n val (a, b, r) = if ((S - K) % m == 0) {\n val a = ((S - K) / m).toInt\n (a, K - a, 0)\n } else {\n val r0 = (S - K + 1) % m\n val r = if (r0 == 0) m else r0\n val a = (S - K + 1) / m - (if (r == m) 1 else 0)\n val b = K - a - 1\n (a.toInt, b.toInt, r.toInt)\n }\n\n var pos = 1\n val moves = ArrayBuffer[Int]()\n rep(a) { _ =>\n pos = pos match {\n case 1 => N\n case N => 1\n }\n moves += pos\n }\n rep(b) { _ =>\n pos = pos match {\n case 1 => 2\n case 2 => 1\n case N => N1\n case N1 => N\n }\n moves += pos\n }\n\n if (r > 0) {\n pos = pos match {\n case 1 => r + 1\n case 2 => r + 2\n case N => N - r\n case N1 => N1 - r\n }\n moves += pos\n }\n\n println(\"YES\")\n println(moves.mkString(\" \"))\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n\n import java.util.StringTokenizer\n\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "object Main {\n import java.io._\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N, K = sc.nextInt()\n val N1 = N - 1\n val S = sc.nextLong()\n val ok = K <= S && S <= (N - 1) * K\n if (!ok) out.println(\"NO\")\n else {\n val m = N - 2\n val (a, b, r) = if ((S - K) % m == 0) {\n val a = ((S - K) / m).toInt\n (a, K - a, 0)\n } else {\n val r0 = (S - K + 1) % m\n val r = if (r0 == 0) m else r0\n val a = (S - K + 1) / m - (if (r0 == 0) 1 else 0)\n val b = K - a - 1\n (a.toInt, b.toInt, r.toInt)\n }\n\n var pos = 1\n val moves = ArrayBuffer[Int]()\n rep(a) { _ =>\n pos = pos match {\n case 1 => N\n case N => 1\n }\n moves += pos\n }\n rep(b) { _ =>\n pos = pos match {\n case 1 => 2\n case 2 => 1\n case N => N1\n case N1 => N\n }\n moves += pos\n }\n\n if (r > 0) {\n pos = pos match {\n case 1 => r + 1\n case 2 => r + 2\n case N => N - r\n case N1 => N1 - r\n }\n moves += pos\n }\n\n println(\"YES\")\n println(moves.mkString(\" \"))\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n\n import java.util.StringTokenizer\n\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "object Main {\n import java.io._\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N = sc.nextInt()\n val N1 = N - 1\n val K, S = sc.nextLong()\n val ok = K <= S && S <= (N - 1) * K\n if (!ok) out.println(\"NO\")\n else {\n val m = N - 2\n val (a, b, r) = if ((S - K) % m == 0) {\n (((S - K) / m).toInt, 0, 0)\n } else {\n val r0 = (S - K + 1) % m\n val r = if (r0 == 0) m else r0\n val a = (S - K + 1) / m - (if (r == 8) 1 else 0)\n val b = K - a - 1\n (a.toInt, b.toInt, r.toInt)\n }\n\n var pos = 1\n val moves = ArrayBuffer[Int]()\n rep(a) { _ =>\n pos = pos match {\n case 1 => N\n case N => 1\n }\n moves += pos\n }\n rep(b) { _ =>\n pos = pos match {\n case 1 => 2\n case 2 => 1\n case N => N1\n case N1 => N\n }\n moves += pos\n }\n\n if (r > 0) {\n pos = pos match {\n case 1 => r + 1\n case 2 => r + 2\n case N => N - r\n case N1 => N1 - r\n }\n moves += pos\n }\n\n println(\"YES\")\n println(moves.mkString(\" \"))\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n\n import java.util.StringTokenizer\n\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val S = nl()\n val L = N - 1\n val minK = (S - 1) / L + 1\n val maxK = S\n if (K < minK || K > maxK) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n var cur = 1\n var direction = 1\n var k = K\n var s = S\n\n val ans = ArrayBuffer[Int]()\n\n def move(dist: Int): Unit = {\n val to = cur + direction * dist\n ans += to\n cur = to\n if (to == 1) direction = 1\n else if (to == N) direction = -1\n k -= 1\n s -= dist\n }\n\n while(s - k >= L) {\n move(L)\n }\n\n REP(k - 1) { _ => move(1) }\n move(s.toInt)\n\n out.println(ans.mkString(\" \"))\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val S = nl()\n val L = N - 1\n val minK = (S - 1) / L + 1\n val maxK = S\n if (K < minK || K > maxK) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n var cur = 1\n var direction = 1\n\n val ans = ArrayBuffer[Int]()\n\n def move(dist: Int): Unit = {\n val to = cur + direction * dist\n ans += to\n cur = to\n if (to == 1) direction = 1\n else if (to == N) direction = -1\n }\n\n REP(((S - K) / (L - 1)).toInt) { _ => move(L) }\n val r = (S - K) % (L - 1)\n if (r > 0) move((r + 1).toInt)\n REP((K - minK).toInt) { _ => move(1) }\n\n out.println(ans.mkString(\" \"))\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n import java.io._\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N = sc.nextInt()\n val N1 = N - 1\n val K, S = sc.nextLong()\n val ok = K <= S && S <= (N - 1) * K\n if (!ok) out.println(\"NO\")\n else {\n val m = N - 2\n val (a, b, r) = if ((S - K) % m == 0) {\n (((S - K) / m).toInt, 0, 0)\n } else {\n val r = (S - K + 1) % m\n val a = (S - K + 1) / m\n val b = K - a - (if (r == 0) 0 else 1)\n (a.toInt, b.toInt, r.toInt)\n }\n\n var pos = 1\n val moves = ArrayBuffer[Int]()\n rep(a) { _ =>\n pos = pos match {\n case 1 => N\n case N => 1\n }\n moves += pos\n }\n rep(b) { _ =>\n pos = pos match {\n case 1 => 2\n case 2 => 1\n case N => N1\n case N1 => N\n }\n moves += pos\n }\n\n if (r > 0) {\n pos = pos match {\n case 1 => r + 1\n case 2 => r + 2\n case N => N - r\n case N1 => N1 - r\n }\n moves += pos\n }\n\n println(\"YES\")\n println(moves.mkString(\" \"))\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n\n import java.util.StringTokenizer\n\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "object Main {\n import java.io._\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N, K, S = sc.nextLong()\n val ok = K <= S && S <= (N - 1) * K\n if (!ok) out.println(\"NO\")\n else {\n val m = N - 2\n val (a, b, r) = if ((S - K) % m == 0) {\n (((S - K) / m).toInt, 0, 0)\n } else {\n val r = (S - K + 1) % m\n val a = (S - K + 1) / m\n val b = K - a - (if (r == 0) 0 else 1)\n (a.toInt, b.toInt, r.toInt)\n }\n\n val moves = ArrayBuffer[Int]()\n rep(a.toInt / 2) { _ =>\n moves += N.toInt\n moves += 1\n }\n if (a % 2 == 0) {\n rep(b.toInt / 2) { _ =>\n moves += 2\n moves += 1\n }\n if (b % 2 == 0) {\n moves += r.toInt + 1\n } else {\n moves += 2\n moves += r.toInt + 2\n }\n } else {\n moves += N.toInt\n rep(b.toInt / 2) { _ =>\n moves += N.toInt\n moves += N.toInt - 1\n }\n if (b % 2 == 0) {\n moves += (N - r).toInt\n } else {\n moves += N.toInt - 1\n moves += (N - r - 1).toInt\n }\n }\n\n println(\"YES\")\n println(moves.mkString(\" \"))\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n\n import java.util.StringTokenizer\n\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "import java.util\n\nobject CF501D extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n val n = in.nextInt\n val k = in.nextInt\n val s = in.nextLong\n\n if (s > (n-1)*k || s < k) {\n out.println(\"NO\")\n } else {\n val moves = new util.LinkedList[Long]()\n\n var distByMove = s/k\n var remainder = s%k\n\n var currentPos: Long = 1\n for (i <- 0 until k) {\n if (currentPos == 1) {\n currentPos = 1 + distByMove\n // add 1 in the \"remainder\" last steps\n // or 1 step before if k is even xor remainder is even\n if (k-i <= remainder || (remainder != 0 && k-i <= remainder + 1 && (k%2 == 0 ^ remainder%2 == 0))) currentPos += 1\n } else {\n if (remainder != 0 && i == k-1 && (k%2 == 0 ^ remainder%2 == 0))\n currentPos = 2\n else\n currentPos = 1\n }\n moves.add(currentPos)\n }\n\n out.println(\"YES\")\n out.println(moves.toArray.mkString(\" \"))\n }\n }\n\n solve\n out.flush\n out.close\n}"}, {"source_code": "import java.util\n\nobject CF501D extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n val n = in.nextInt\n val k = in.nextInt\n val s = in.nextLong\n\n if (s > (n.toLong-1)*k.toLong || s < k) {\n out.println(\"NO\")\n } else {\n val moves = new util.LinkedList[Long]()\n\n var distByMove = s/k\n var remainder = s%k\n\n var currentPos: Long = 1\n for (i <- 0 until k) {\n if (currentPos == 1) {\n currentPos = 1 + distByMove\n // add 1 in the \"remainder\" last steps\n // or 1 step before if k is even xor remainder is even\n if (k-i <= remainder || (remainder != 0 && k-i <= remainder + 1 && (k%2 == 0 ^ remainder%2 == 0))) currentPos += 1\n } else {\n if (remainder != 0 && i == k-1 && (k%2 == 0 ^ remainder%2 == 0))\n currentPos = 2\n else\n currentPos = 1\n }\n moves.add(currentPos)\n }\n\n out.println(\"YES\")\n out.println(moves.toArray.mkString(\" \"))\n }\n }\n\n solve\n out.flush\n out.close\n}"}], "src_uid": "2cc44c5a084688025c16b0394c98b2f6"} {"source_code": "//package codeforces.contest1102\n\nobject ArrayKColoring {\n def main(args: Array[String]): Unit = {\n val Array(n, k), seq = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val groups: Map[Int, Array[Int]] = seq.zipWithIndex.groupBy(_._1).map { case (x, set) => (x, set.unzip._2) }\n\n if (groups.exists(_._2.length > k)) println(\"NO\")\n else {\n\n var color = 0\n groups.foreach { case (v, indices) =>\n indices.foreach(i => {\n seq(i) = color\n color = (color + 1) % k\n })\n }\n\n println(\"YES\")\n println(seq.map(_ + 1).mkString(\" \"))\n\n }\n }\n}\n", "positive_code": [{"source_code": "object CF_531_3_B {\n\n type In = (Int, Int, Seq[Int])\n type Out = Option[Seq[Int]]\n \n def solve(in: In): Out = {\n val (_, k, as) = in\n\n case class Elem(a: Int, index: Int, colour: Int)\n\n val maxLen = as.groupBy(identity).maxBy(_._2.length)._2.length\n\n val ais: Seq[Elem] = for {\n ((a, i), c) <- (as.zipWithIndex.sorted, Stream.iterate(0)(i => (i + 1) % k)).zipped.toVector\n } yield Elem(a, i, c + 1)\n\n if (maxLen > k || as.length < k) None\n else\n Some(ais.sortBy(_.index).map(_.colour))\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, i.int, {i.nextLine; i.intSeq})\n def formatOut(out: Out): String = out.fold(\"NO\")(s => \"YES\\n\" + s.mkString(\" \") + \"\\n\")\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}, {"source_code": "object Main2 extends App {\n\n import java.io._\n import java.util\n import java.util.{Locale, StringTokenizer, TreeSet}\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n val k = in.nextInt\n val a = in.nextLine.split(' ').map(_.toInt)\n val cnt = a.zipWithIndex.groupBy(_._1)\n val max: Int = cnt.maxBy(_._2.length)._2.length\n\n val d = a.distinct\n val idx = d.zipWithIndex.toMap\n\n if (max > k || a.length < k) {\n out.println(\"NO\")\n }\n else {\n\n val res = new Array[Int](n)\n var cur = 0\n for {\n (_, v) <- cnt\n pos <- v\n } {\n res(pos._2) = cur + 1\n cur = (cur + 1) % k\n }\n println(\"YES\")\n println(res.mkString(\" \"))\n }\n\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val A = na(N, -1)\n var k = 0\n\n val ix = A.zipWithIndex.sortBy(_._1).map(_._2)\n val ans = Array.ofDim[Int](N)\n REP(N) { i =>\n ans(ix(i)) = k % K\n k += 1\n }\n\n if (A.groupBy(identity).values.map(_.length).max <= K) {\n out.println(\"YES\")\n out.println(ans.map(_ + 1).mkString(\" \"))\n } else {\n out.println(\"NO\")\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val A = na(N, -1)\n\n val P = Array.ofDim[Int](N)\n val ans = Array.ofDim[Int](N)\n REP(N) { i =>\n ans(i) = P(A(i)) + 1\n P(A(i)) += 1\n }\n\n if (ans.forall(_ <= K)) {\n out.println(\"YES\")\n out.println(ans.mkString(\" \"))\n } else {\n out.println(\"NO\")\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object CF_531_3_B {\n\n type In = (Int, Int, Seq[Int])\n type Out = Option[Seq[Int]]\n \n def solve(in: In): Out = {\n val (_, k, as) = in\n\n val groups = as.zipWithIndex.groupBy(_._1).mapValues(ts => ts.zip(1 to ts.length))\n\n val maxLen = groups.maxBy(_._2.length)._2.length\n\n if (maxLen > k) None\n else {\n val cs = for {\n (v, es) <- groups.toSeq\n ((_, i), c) <- es\n } yield (c, i)\n\n Some(cs.sortBy(_._2).map(_._1))\n }\n\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, i.int, {i.nextLine; i.intSeq})\n def formatOut(out: Out): String = out.fold(\"NO\")(s => \"YES\\n\" + s.mkString(\" \") + \"\\n\")\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}, {"source_code": "object CF_531_3_B {\n\n type In = (Int, Int, Seq[Int])\n type Out = Option[Seq[Int]]\n \n def solve(in: In): Out = {\n val (_, k, as) = in\n\n case class Elem(a: Int, index: Int, colour: Int)\n\n val maxLen = as.groupBy(identity).maxBy(_._2.length)._2.length\n\n val ais: Seq[Elem] = for {\n ((a, i), c) <- (as.zipWithIndex.sorted, Stream.iterate(0)(i => (i + 1) % k)).zipped.toSeq\n } yield Elem(a, i, c + 1)\n\n if (maxLen > k || as.distinct.length < k) None\n else\n Some(ais.sortBy(_.index).map(_.colour))\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, i.int, {i.nextLine; i.intSeq})\n def formatOut(out: Out): String = out.fold(\"NO\")(s => \"YES\\n\" + s.mkString(\" \") + \"\\n\")\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}, {"source_code": "object CF_531_3_B {\n\n type In = (Int, Int, Seq[Int])\n type Out = Option[Seq[Int]]\n \n def solve(in: In): Out = {\n val (_, k, as) = in\n\n case class Elem(a: Int, index: Int, colour: Int)\n\n val maxLen = as.groupBy(identity).maxBy(_._2.length)._2.length\n\n val ais: Seq[Elem] = for {\n ((a, i), c) <- (as.zipWithIndex.sorted, Stream.iterate(1)(i => (i + 1) % k)).zipped.toSeq\n } yield Elem(a, i, c + 1)\n\n if (maxLen > k || as.distinct.length < k) None\n else\n Some(ais.sortBy(_.index).map(_.colour))\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, i.int, {i.nextLine; i.intSeq})\n def formatOut(out: Out): String = out.fold(\"NO\")(s => \"YES\\n\" + s.mkString(\" \") + \"\\n\")\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}, {"source_code": "object Main2 extends App {\n\n import java.io._\n import java.util\n import java.util.{Locale, StringTokenizer, TreeSet}\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n val k = in.nextInt\n val a = in.nextLine.split(' ').map(_.toInt)\n val cnt = a.zipWithIndex.groupBy(_._1)\n val max: Int = cnt.maxBy(_._2.length)._2.length\n\n val d = a.distinct\n val idx = d.zipWithIndex.toMap\n\n if (max > k || a.length < k) {\n out.println(\"NO\")\n }\n else {\n\n val res = new Array[Int](n)\n var cur = 0\n for {\n (k, v) <- cnt\n pos <- v\n } {\n res(pos._2) = cur + 1\n cur = (cur + 1) % k\n }\n println(\"YES\")\n println(res.mkString(\" \"))\n }\n\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}"}], "src_uid": "3d4df21eebf32ce15841179bb85e6f2f"} {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 1 to t) {\n val n = StdIn.readLine().toInt\n val arr = StdIn.readLine().split(\" \").map(_.toInt % 2)\n val p0 = arr.count(_ == 0)\n val p1 = arr.count(_ == 1)\n val res = if ((n%2) + p1 == p0) {\n arr.zipWithIndex.map(x => {\n math.abs(x._1 - x._2 % 2)\n }).sum / 2\n } else -1\n println(res)\n }\n }\n}\n", "positive_code": [{"source_code": "//package codeforces.contests._1367\n\nobject _2 {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n\n val n = io.StdIn.readInt\n val arr = io.StdIn.readLine.split(\" \").map(_.toInt).zipWithIndex\n\n val correct = arr.count { case (i, v) => i % 2 == v % 2 }\n val evenOdd = arr.count { case (i, v) => i % 2 != v % 2 && i % 2 == 1 }\n val oddEven = arr.count { case (i, v) => i % 2 != v % 2 && i % 2 == 0 }\n\n println {\n if (evenOdd == oddEven) evenOdd else -1\n }\n }\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val n = readLine()\n val l = readIntLine()\n handle(l)\n }\n }\n\n def handle(list: List[Int]): Unit = {\n var odd = 0\n var even = 0\n list.zipWithIndex.foreach(tup => if (tup._1 % 2 != 0 && tup._2 % 2 == 0) even += 1\n else if (tup._1 % 2 == 0 && tup._2 % 2 != 0) odd += 1)\n\n println(if (odd == even) odd else -1)\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n val (c0, c1) = an.zipWithIndex.foldLeft((0, 0)) {\n case ((c0, c1), (a, i)) =>\n if (a % 2 == i % 2) (c0, c1)\n else if (i % 2 == 0) (c0 + 1, c1)\n else (c0, c1 + 1)\n }\n\n val ans =\n if (c0 != c1) -1\n else c0\n\n println(ans)\n }\n}\n"}, {"source_code": "object Main extends App {\n val r = new FastScanner(java.lang.System.in)\n val o = new java.io.PrintWriter(java.lang.System.out)\n for(_ <- 1 to r.nextInt()) {\n val n = r.nextInt()\n val a = Array.fill(n)(r.nextInt() & 1)\n val odd = n / 2\n val even = n - odd\n val b = a.zipWithIndex.map { p => (p._1, p._2 & 1) }\n val odd_correct = b.count { p => p._2 == 1 && p._1 == 1 }\n val even_correct = b.count { p => p._2 == 0 && p._1 == 0 }\n val odd_incorrect = odd - odd_correct\n val even_incorrect = even - even_correct\n o.println (\n if(odd_incorrect != even_incorrect) -1\n else odd_incorrect\n )\n }\n o.close()\n}\n\nimport scala.annotation.tailrec\nimport scala.collection.mutable.StringBuilder\n\nobject FastScanner {\n val zero = 0.toByte\n val cr = '\\r'.toByte\n val nl = '\\n'.toByte\n val BUFFER_SIZE = 0x10000\n}\n\nclass FastScanner(private val input: java.io.InputStream) {\n private val b = new Array[Byte](FastScanner.BUFFER_SIZE)\n private var n = 0\n private var pos = 0\n private var eof = false\n private def read ():Boolean = {\n if (eof) {\n return false\n }\n pos = 0\n n = input.read(b)\n if (n < 0) {\n eof = true\n }\n n > 0\n }\n private def nextByte(): Byte = {\n if (pos >= n && !read ()) {\n 0\n } else {\n val r = b(pos)\n pos += 1\n r\n }\n }\n def nextToken(k: Int = -1): String = {\n val sb = if(k >= 0) new StringBuilder(k) else new StringBuilder()\n var b = skipBlanks()\n assert(b > 0)\n while(b > 32) {\n sb.append(b.toChar)\n b = nextByte()\n }\n sb.toString\n }\n @tailrec\n private def skipBlanks(): Byte = {\n val b = nextByte()\n if(b > 32 || b < 1) b else skipBlanks()\n }\n def nextInt():Int = {\n val b = skipBlanks()\n @tailrec\n def f(t: Int): Int = {\n val b = nextByte ()\n if (b <= 32) t else f(10 * t + (b - 48))\n }\n require(b > 0)\n if (b < 48) -f(0) else f(b - 48)\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n\n val t = readInt()\n 1 to t foreach { _ =>\n readInt()\n val A = readLine().split(\" \").map(_.toInt)\n\n var counter = 0\n var moves = 0\n for (i <- 0 until A.length) {\n if (A(i) % 2 != i % 2) {\n moves += 1\n if (i % 2 == 0) {\n counter -= 1\n } else counter += 1\n }\n }\n\n if (counter != 0) println(-1)\n else println(moves / 2)\n\n }\n}\n"}, {"source_code": "object B extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n val n = nextInt\n\n 1.to(n)\n .foreach(_ => {\n val m = nextInt\n var curInd = 0\n var r1 = 0\n var r2 = 0\n 1.to(m)\n .foreach(_ => {\n val curInt = nextInt\n if (curInt % 2 != curInd) {\n if (curInd == 0) r1 = r1 + 1 else r2 = r2 + 1\n }\n if (curInd == 0) curInd = 1 else curInd = 0\n })\n if (r1 != r2) println(-1) else println(r1)\n })\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n"}], "negative_code": [{"source_code": "object B extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n val n = nextInt\n\n 1.to(n)\n .foreach(_ => {\n val m = nextInt\n var curInd = 0\n var r = 0\n 1.to(m)\n .foreach(_ => {\n val curInt = nextInt\n if (curInt % 2 != curInd) r = r + 1\n if (curInd == 0) curInd = 1 else curInd = 0\n })\n if (r % 2 != 0) println(-1) else println(r / 2)\n })\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n"}], "src_uid": "942123e43a83d5a4cea95a6781064e28"} {"source_code": "object _1265A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val s = ('?' + io.read[String] + '?').toCharArray\n\n for (i <- 1 until s.length-1 if s(i) == '?') {\n s(i) = \"abc\".find(c => c != s(i-1) && c != s(i+1)).head\n }\n val ans = s.tail.init.mkString\n\n if (ans.sliding(2).exists(s => s.length == 2 && s.head == s.last))\n io.write(-1)\n else\n io.write(s.tail.init.mkString)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject A_1265 extends App {\n\n def isGood(line: Array[Char]): String = {\n line.indices foreach { i =>\n if (line(i) != '?') {\n val prev = if (i > 0) Some(line(i - 1)) else None\n if (prev.nonEmpty && prev.get == line(i)) return \"\"\n }\n else {\n val prev = if (i > 0) Some(line(i - 1)) else None\n val next = if (i < line.length - 1) Some(line(i + 1)) else None\n val good = List('a', 'b', 'c').filterNot(x => List(prev.getOrElse('?'), next.getOrElse('?')).contains(x))\n line(i) = good.head\n }\n }\n\n line.mkString\n }\n\n val n = StdIn.readInt()\n 1 to n foreach { _ =>\n val line = StdIn.readLine().toCharArray\n val answer = isGood(line)\n if (answer == \"\") println(-1) else println(answer)\n }\n}\n"}], "negative_code": [], "src_uid": "98c08a3b5e5b5bb78804ff797ba24d87"} {"source_code": "\n\nobject YoungPhysicist {\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in);\n\t\tval n = scanner.nextInt();\n\t\tvar accX = 0;\n\t\tvar accY = 0;\n\t\tvar accZ = 0;\n\t\tfor (i <- 1 to n) {\n\t\t\tval x = scanner.nextInt();\n\t\t\tval y = scanner.nextInt();\n\t\t\tval z = scanner.nextInt();\n\t\t\taccX += x;\n\t\t\taccY += y;\n\t\t\taccZ += z\n\t\t}\n\t\tif (accX == 0 && accY == 0 && accZ == 0) {\n\t\t println(\"YES\")\n\t\t}\n\t\telse {\n\t\t println(\"NO\")\n\t\t}\n\t\tSystem.exit(0)\n\t}\n}", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Main{\n def main(args: Array[String]): Unit = {\n\n val s = new Scanner(System.in)\n val a = s.nextInt()\n val n = a*3\n val numbers: Array[Int] = Array.fill(n){0}\n for(i <- 0 until n) {\n numbers(i) = s.nextInt()\n }\n\n val x = numbers.zipWithIndex.filter(_._2 % 3 == 0).map(_._1).toList.foldLeft(0)(_ + _)\n val y = numbers.zipWithIndex.filter(_._2 % 3 == 1).map(_._1).toList.foldLeft(0)(_ + _)\n val z = numbers.zipWithIndex.filter(_._2 % 3 == 2).map(_._1).toList.foldLeft(0)(_ + _)\n\n println(if (x == 0 && y == 0 && z == 0) \"YES\" else \"NO\" )\n }\n}"}, {"source_code": "object YoungPhysicist extends App {\n\n val nInput = scala.io.StdIn.readInt()\n var sumX = 0\n var sumY = 0\n var sumZ = 0\n\n for (i <- 1 to nInput) {\n val forces = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n sumX += forces(0)\n sumY += forces(1)\n sumZ += forces(2)\n }\n\n if (sumX == 0 && sumY == 0 && sumZ == 0) println(\"YES\")\n else println(\"NO\")\n}"}, {"source_code": "object CF0069A extends App {\n\n val n = readInt()\n\n var x = 0\n var y = 0\n var z = 0\n\n (1 to n).foreach(n => {\n var Array(x1, y1, z1) =readLine().split(\" \").map(_.toInt)\n x = x + x1\n y += y1\n z += z1\n })\n\n if(x == 0 && y == 0 && z == 0) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Task {\n\n def main(args: Array[String]): Unit = {\n\n val n: Int = StdIn.readInt()\n var v3: Vector3 = new Vector3(0, 0, 0)\n for (i <- 1 to n) {\n var xyz: Array[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n v3.add(xyz(0), xyz(1), xyz(2))\n }\n if (v3.isZero()) {\n println(\"YES\")\n }\n else {\n println(\"NO\")\n }\n\n }\n\n}\n\nclass Vector3(val xc: Int, val yc: Int, val zc: Int) {\n var x: Int = xc\n var y: Int = yc\n var z: Int = zc\n\n def add(xa: Int, ya: Int, za: Int): Unit = {\n x += xa\n y += ya\n z += za\n }\n\n def isZero(): Boolean = {\n if (x == 0 && y == 0 && z == 0) {\n return true\n }\n return false\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = Range(0, n).foldLeft(List(0, 0, 0)){\n case(List(a, b, c), _) =>\n val dd = in.next().split(\" \").map(_.toInt)\n List(a + dd(0), b + dd(1), c + dd(2))\n }.forall(_ == 0)\n if (data) println(\"YES\")\n else println(\"NO\")\n}"}, {"source_code": "object Main {\n\n def main(args: Array[String]) {\n val std = scala.io.StdIn\n\n val n = std.readLine().toInt\n\n val v = Array[Int](0,0,0)\n for (i <- 0 until n) {\n val value = std.readLine().split(' ').map(_.toInt)\n for (j <- 0 until 3) {\n v(j) += value(j)\n }\n }\n\n if (v.exists(x => x != 0)) {\n println(\"NO\")\n }\n else {\n println(\"YES\")\n }\n }\n}"}, {"source_code": "object A69 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = Array.fill(n)(readInts(3))\n val res = input.foldLeft(Array(0, 0, 0)){case (arr1, arr2) =>\n arr1.zip(arr2).map{case (a, b) => a+b}\n }\n if(res.sameElements(Array(0, 0, 0))) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P69A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val coordinates = Array.fill(N, 3)(sc.nextInt)\n\n val isEquilibrium = (0 until 3).forall { i =>\n { for (j <- 0 until N) yield coordinates(j)(i) }.sum == 0\n }\n\n val answer = if (isEquilibrium) \"YES\" else \"NO\"\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "object AYoungPhysicist extends App {\n import scala.io.StdIn._\n\n val n = readInt()\n val force = (0 until n).foldLeft((0, 0, 0)) {\n case ((sx, sy, sz), _) =>\n val Array(x, y, z) = readLine().split(\" \").map(_.toInt)\n (sx + x, sy + y, sz + z)\n }\n\n val ans = force match {\n case (0, 0, 0) => \"YES\"\n case _ => \"NO\"\n }\n\n println(ans)\n}\n"}, {"source_code": "import java.io._\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n\n def ans = (for(_ <- 1 to readInt) yield readInts).transpose.map(_.sum).forall(_ == 0)\n\n def main(a: Array[String]) {\n println(if(ans) \"YES\" else \"NO\")\n }\n}\n"}, {"source_code": "import scala.Predef._\n\nobject Main {\n case class Vector(x: Int, y: Int, z: Int) {\n def + (that: Vector) = Vector(this.x + that.x, this.y + that.y, this.z + that.z)\n def isZero = (x == 0) & (y == 0) & (z == 0)\n }\n \n object Vector {\n def read() = {\n val a = readLine().split(\" \").map(_.toInt)\n Vector(a(0), a(1), a(2))\n }\n }\n\n def main(args: Array[String]) {\n val num = readInt\n val r = (1 to num).foldLeft(Vector(0, 0, 0)) { (acc, unused) => acc + Vector.read() }\n if (r.isZero) println(\"YES\")\n else println(\"NO\")\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject A_69 extends App {\n val n = readInt()\n val A = Array.ofDim[Int](n, 3)\n\n 0 until n foreach { i =>\n A(i) = readLine().split(\" \").map(_.toInt)\n }\n\n def hasEqulibrium(): Boolean = {\n 0 until 3 foreach { col =>\n var counter = 0\n 0 until n foreach { row =>\n counter += A(row)(col)\n }\n if (counter != 0) return false\n }\n\n true\n }\n\n if (hasEqulibrium()) println(\"YES\")\n else println(\"NO\")\n\n}\n"}, {"source_code": "import java.util.Scanner\n\n\nobject HelloWorldMain {\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n var x1 = 0\n var x2 = 0\n var x3 = 0\n for(i <- 1 to n){\n x1 += sc.nextInt()\n x2 += sc.nextInt()\n x3 += sc.nextInt()\n }\n\n if(x1==0 && x2 ==0 && x3==0) println(\"YES\")\n else println(\"NO\")\n }\n}"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject YoungPhyscist {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n \n def main(args: Array[String]) {\n val n = readInt\n val forces = for {\n i <- 1 to n\n force = readTriple\n } yield force\n forces.foldLeft((0,0,0)){ case ((x1,y1,z1),(x2,y2,z2)) => (x1+x2,y1+y2,z1+z2)} match {\n case (0,0,0) => println(\"YES\")\n case _ => println(\"NO\")\n }\n \n }\n \n}"}, {"source_code": "import java.util.Scanner\n\nobject TEST extends App{\n val sc = new Scanner(System.in)\n val n = sc.nextInt\n val a = List.fill(n,3)(sc.nextInt)\n val isEq = (0 to 2).forall(i => (for (j <- 0 to n-1) yield a(j)(i)).sum == 0)\n val ans = if(isEq) \"YES\" else \"NO\"\n print (ans)\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Task extends App{\n val N = readLine.split(\" \") map {_.toInt} head\n val vecs = for(i <- 1 to N)\n\t yield readLine.split(\" \") map {_.toLong}\n\t \n\tval sum = vecs.foldLeft(Array.fill(N)(0l))( (l,r) => \n\t l.zip(r).map{ case(a,b) => a + b }\n\t)\n\t\n\tval z = sum.zip(Array.fill(N)(0l))\n\t\n\tif(z.filter{case (a,b) => a != b}.isEmpty)\n\t println(\"YES\")\n\telse\n\t println(\"NO\")\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject YoungPhysicist {\n def main(args: Array[String]): Unit = {\n val t = readLine.toInt\n var a, b, c = 0\n for (tt <- 1 to t) {\n val Array(aa, bb, cc) = readLine.split(\" \").map(_.toInt)\n a += aa\n b += bb\n c += cc\n }\n println(if (a==0 && b==0 && c==0) \"YES\" else \"NO\")\n }\n}\n"}], "negative_code": [{"source_code": "object YoungPhysicist extends App {\n\n //sommare le forze di ogni singolo array. Se la somma è 0 è in equilibrio\n\n val nInput = scala.io.StdIn.readInt()\n var somma = 0\n\n for (i <- 1 to nInput) {\n val forces = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sum\n somma += forces\n }\n\n if (somma == 0) println(\"YES\")\n else println(\"NO\")\n}"}, {"source_code": "object YoungPhysicist extends App {\n\n //sommare le forze di ogni singolo array. Se la somma è 0 è in equilibrio\n\n val nInput = scala.io.StdIn.readInt()\n var somma = 0\n\n for (i <- 1 to nInput) {\n val forces = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sum\n somma = somma + forces\n }\n\n if (somma == 0) println(\"YES\")\n else println(\"NO\")\n}"}, {"source_code": "object Main {\n\n def main(args: Array[String]) {\n val std = scala.io.StdIn\n\n val n = std.readLine().toInt\n\n val v = Array[Int](0,0,0)\n for (i <- 0 until n) {\n val value = std.readLine().split(' ').map(_.toInt)\n for (j <- 0 until 3) {\n v(j) += value(j)\n }\n }\n\n if (v.distinct.length > 1) {\n println(\"NO\")\n }\n else {\n println(\"YES\")\n }\n }\n}"}], "src_uid": "8ea24f3339b2ec67a769243dc68a47b2"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, d) = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt)\n var count = 0\n val tr = a.scanLeft(0) { (prev, cur) =>\n if (prev >= cur) {\n val step = (prev - cur) / d + 1\n count += step\n cur + d * step\n } else {\n cur\n }\n } \n println(count)\n }\n}", "positive_code": [{"source_code": "import java.io.PrintWriter\nimport scala.io.Source\nimport java.io.File\nimport scala.collection.immutable.List\n\nobject Increasing extends App {\n lazy val writer = System.out // new PrintWriter(new File(\"output.txt\"))\n val it = Source.stdin.getLines\n val ss = (it.next).split(\" \")\n val li = ss map (_.toInt)\n val n = li(0)\n val d = li(1)\n\n def needD(cur: Long, o: List[Long], cnt: Long): Long = o match {\n case Nil => cnt\n case h :: t => { \n var nd = if (cur < h) 0 else ((cur-h) / d + 1)\n val nc = h + nd*d\n // println(\"cur,h,nd,nc = \"+cur+\" \"+h+\" \"+nd+\" \"+nc)\n needD(nc, t, cnt+nd)\n }\n }\n\n val b: List[Long] = (it.next.split(\" \").toList) map (_.toLong)\n val nd = needD(b(0), b.tail, 0)\n writer.println(nd)\n writer.close()\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, d) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n val res = data.tail.foldLeft((0, data.head)) {\n case ((soFar, prev), i) if i > prev =>\n// println(1)\n// println((soFar, prev), i)\n (soFar, i)\n case ((soFar, prev), i) =>\n// println(4)\n// println((soFar, prev), i)\n// 24 - 13 = 11\n// 11 + 3 * 3 + 3\n// println(prev)\n// if (i % d == 0)\n// (soFar + (prev - i) / d, prev + d)\n// else\n (soFar + (prev - i) / d + 1, i + (prev - i) / d * d + d)\n }\n// println(res)\n println(res._1)\n}\n\n//10 24 25 28"}, {"source_code": "import java.util.Scanner\n\nobject Sequence extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n val d = s.nextInt()\n\n val arr = (0 until n).map(_ => s.nextInt()).toArray\n\n val x = for {\n i <- 1 until n\n } yield {\n if (arr(i) < arr(i - 1)) {\n val f = math.ceil((arr(i - 1).toDouble - arr(i)) / d.toDouble).toInt\n arr(i) += f * d\n if (arr(i) == arr(i - 1)) {\n arr(i) += d\n f + 1\n } else {\n f\n }\n } else if (arr(i) == arr(i - 1)) {\n arr(i) += d\n 1\n } else 0\n }\n\n println(x.sum)\n\n}\n"}, {"source_code": "object A11 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, d) = readInts(2)\n val in = readInts(n)\n var res = 0L\n for(i <- 1 until n) {\n if(in(i) <= in(i-1)) {\n val delta = (in(i-1)-in(i)+d)/d\n res += delta\n in(i) += delta*d\n }\n }\n println(res)\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, d) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n val res = data.tail.foldLeft((0, data.head)) {\n case ((soFar, prev), i) if i > prev =>\n// println((soFar, prev), i)\n (soFar, i)\n case ((soFar, prev), i) if i == prev =>\n// println((soFar, prev), i)\n (soFar + 1, i + d)\n case ((soFar, prev), i) if (prev - i) % d == 0 =>\n// println((soFar, prev), i)\n (soFar + (prev - i) / d + 1, i + d)\n case ((soFar, prev), i) =>\n// println((soFar, prev), i)\n (soFar + (prev - i) / d + 1, i + (prev - i) / d * d + d - (prev - i) % d)\n }\n println(res._1)\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, d) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n val res = data.tail.foldLeft((0, data.head)) {\n case ((soFar, prev), i) if i > prev =>\n// println(1)\n// println((soFar, prev), i)\n (soFar, i)\n case ((soFar, prev), i) if i == prev =>\n// println((soFar, prev), i)\n// println(2)\n (soFar + 1, i + d)\n case ((soFar, prev), i) if (prev - i) % d == 0 =>\n// println((soFar, prev), i)\n// println(3)\n (soFar + (prev - i) / d + 1, i + d)\n case ((soFar, prev), i) =>\n// println((soFar, prev), i)\n// println(4)\n// println(prev)\n (soFar + (prev - i) / d + 1, i + (prev - i) / d * d + d)\n }\n println(res._1)\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, d) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n val res = data.tail.foldLeft((0, data.head)) {\n case ((soFar, prev), i) if i > prev =>\n// println((soFar, prev), i)\n (soFar, i)\n case ((soFar, prev), i) if i == prev =>\n// println((soFar, prev), i)\n (soFar + 1, i + d)\n case ((soFar, prev), i) if (prev - i) % d == 0 =>\n// println((soFar, prev), i)\n (soFar + (prev - i) / d, i)\n case ((soFar, prev), i) =>\n// println((soFar, prev), i)\n (soFar + (prev - i) / d + 1, i + (prev - i) / d * d + d - (prev - i) % d)\n }\n println(res._1)\n}"}, {"source_code": "import java.util.Scanner\n\nobject Sequence extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n val d = s.nextInt()\n\n val arr = (0 until n).map(_ => s.nextInt()).toArray\n\n val x = for {\n i <- 1 until n\n } yield {\n if (arr(i) < arr(i - 1)) {\n val f = math.ceil((arr(i - 1).toDouble - arr(i)) / d.toDouble).toInt\n arr(i) += f * d\n f\n } else if (arr(i) == arr(i - 1)) {\n arr(i) += d\n 1\n } else 0\n }\n\n println(x.sum)\n\n}\n"}], "src_uid": "0c5ae761b046c021a25b706644f0d3cd"} {"source_code": "object Main {\n\n class Dragon(val x:Int, val y:Int) extends Ordered[Dragon] {\n def compare(other : Dragon) = {\n this.y.compare(other.y)\n }\n override def toString(): String = \"x: \" + x + \", y: \" + y\n }\n\n def main(args: Array[String]): Unit = {\n var Array(s, n) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n var d = new collection.mutable.PriorityQueue[Dragon]()\n\n for (i<-0 until n) {\n val Array(x, y) = io.StdIn.readLine.split(\" \").map(_.toInt)\n d.enqueue(new Dragon(x,y))\n }\n\n var tmp = new collection.mutable.ArrayBuffer[Dragon]()\n\n while (!d.isEmpty) {\n val top = d.dequeue\n if (s > top.x) {\n s += top.y\n if (!tmp.isEmpty) {\n tmp.foreach(d.enqueue(_))\n tmp.clear()\n }\n }\n else tmp += top\n }\n if (tmp.isEmpty) println(\"YES\")\n else println(\"NO\")\n\n }\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _230A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val s = next.toInt\n val n = next.toInt\n val a = (1 to n).map(i => (next.toInt, next.toInt)).sortBy(u => u._1).toList\n def doit(a: List[(Int, Int)], s: Int): String =\n if (a == Nil) \"YES\"\n else if (a.head._1 >= s) \"NO\"\n else doit(a.tail, s + a.head._2)\n println(doit(a, s))\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(s, n) = in.next().split(\" \").map(_.toInt)\n val data = Range(0, n).map(_ => in.next().split(\" \").map(_.toInt)).sortBy(_.head).foldLeft((s, true)) {\n case ((s, false), x) => (s, false)\n case ((s, true), x) if x.head >= s => (s, false)\n case ((s, true), x) => (s + x.last, true)\n }._2\n if (data) println(\"YES\") else println(\"NO\")\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject A230 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n var Array(s, n) = readInts(2)\n val input = Array.fill(n)(readInts(2))\n\n val pq = mutable.PriorityQueue[(Int, Int)]()\n input.foreach(arr => pq += ((arr(1), arr(0))))\n\n var break = false\n var size = pq.length\n while(!break && pq.nonEmpty) {\n var top = pq.dequeue()\n if(s > top._2) { //win\n s += top._1\n } else { //loose, requeue at end\n var requeue = Array.empty[(Int, Int)]\n while(pq.nonEmpty && top._2 >= s) {\n requeue ++= Array(top)\n top = pq.dequeue()\n }\n if(top._2 < s) { //win\n s += top._1\n } else { //loose, requeue at end\n requeue ++= Array(top)\n }\n requeue.foreach(x => pq += x)\n }\n if(pq.length == size) {\n break = true\n }\n size = pq.length\n }\n\n if(break && pq.nonEmpty) {\n println(\"NO\")\n } else {\n println(\"YES\")\n }\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P230A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val s0, N = sc.nextInt\n val d = Array.fill(N, 2)(sc.nextInt).sortBy(_(0))\n\n def solve: String = {\n @tailrec\n def loop(s: Int, i: Int): String =\n if (i == N) \"YES\"\n else if (s > d(i)(0)) loop(s + d(i)(1), i + 1)\n else \"NO\"\n loop(s0, 0)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.io._\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n\n val Array(s, n) = readInts\n val dragons = (for(_ <- 1 to n) yield readInts).sortBy(_(0)).toList\n\n @tailrec\n def win(s: Int, d: List[Array[Int]]): Boolean = d match {\n case Nil => true\n case Array(ds, b) :: tail => if(ds >= s) false else win(s + b, tail)\n }\n\n def main(a: Array[String]) {\n println(if(win(s, dragons)) \"YES\" else \"NO\")\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val sn = readLine().split(\" \").map(_.toInt)\n val data = (1 to sn(1)).map{ _ => \n readLine().split(\" \").map(_.toInt)\n }\n val sorted = data.sortBy(_(0))\n val r = sorted.foldLeft((sn(0), 0)) { (t, e) =>\n if (t._1 > e(0)) (t._1 + e(1), t._2 + 1)\n else t\n }\n if (r._2 == sn(1)) println(\"YES\")\n else println(\"NO\")\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject _230_A extends App {\n val Array(s, n) = readLine().split(\" \").map(_.toInt)\n val dragons = new Array[(Int, Int)](n)\n\n for (i <- 0 until n) {\n val Array(strength, bonus) = readLine().split(\" \").map(_.toInt)\n dragons(i) = (strength, bonus)\n }\n\n val currentDragons = dragons.sortBy(_._1).toBuffer\n\n def findMaxDragonIdx(currentStrength: Int) = {\n var maxIdx = -1\n var maxBonus = Integer.MIN_VALUE\n for (i <- currentDragons.indices) {\n val (s, b) = currentDragons(i)\n if (s < currentStrength && maxBonus < b) {\n maxIdx = i\n maxBonus = b\n }\n }\n\n maxIdx\n }\n\n var dragonToKill = 0\n var currentStrength = s\n do {\n dragonToKill = findMaxDragonIdx(currentStrength)\n// println(\"kill \" + dragonToKill)\n if (dragonToKill > -1) {\n currentStrength += currentDragons(dragonToKill)._2\n currentDragons.remove(dragonToKill)\n }\n } while (dragonToKill != -1 && !currentDragons.isEmpty)\n\n println(if (currentDragons.isEmpty) \"YES\" else \"NO\")\n}\n"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject Dragons {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readLongs() : Array[Long] = \n readLine.split(' ').map(_.toLong)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n \n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n \n def canWin(s: Int, dragons : List[(Int,Int)]) : Boolean = dragons match {\n case Nil => true\n case (x,y) :: ds if x < s => canWin(s+y,ds)\n case _ => false \n }\n \n def main(args: Array[String]) {\n val (s,n) = readTuple\n val dragons = for {\n i <- 1 to n\n (x,y) = readTuple\n } yield (x,y)\n if (canWin(s,dragons.sortBy(_._1).toList)) println(\"YES\") else println(\"NO\")\n \n }\n \n}"}, {"source_code": "object main extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n def solve(input: InputStream, output: PrintStream): Unit = {\n val sc = new Scanner(input)\n var s: Long = sc.nextInt()\n val ndragons = sc.nextInt()\n\n val dSB = (1 to ndragons).\n map( _ => (sc.nextInt(),sc.nextInt()))\n .sortBy{ case (ds,_) => ds}\n var isGood = true\n dSB.foreach{\n case (ds,db) => {\n isGood &= s > ds\n s += db\n }\n }\n output.println(if(isGood) \"YES\" else \"NO\")\n }\n solve(System.in,System.out)\n}"}, {"source_code": "object main extends App with fastIO {\n \n var (s, n) = (nextInt, nextInt)\n var a = Array.fill(n, 2)(nextInt) sortBy(_(0)) \n a foreach { it => if (it(0) < s) s += it(1) }\n println(if (a.map(_(0)).max < s) \"YES\" else \"NO\") \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n case class Dragon(power: Int, bonus: Int) extends Ordered[Dragon] {\n def compare(other: Dragon): Int = this.power - other.power\n }\n val Array(s, n) = readLine().split(\" \").map(_.toInt)\n val a = for {\n _ <- (0 until n).toArray\n Array(power, bonus) = readLine().split(\" \").map(_.toInt)\n } yield Dragon(power, bonus)\n val dragons = a.sorted\n val (_, ans) = dragons.foldLeft((s, true)) { (current, d) =>\n val (sum, state) = current\n if (sum <= d.power) (sum, false)\n else (sum + d.bonus, true)\n }\n println(if (ans) \"YES\" else \"NO\")\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n case class Dragon(power: Int, bonus: Int) extends Ordered[Dragon] {\n def compare(other: Dragon): Int = this.power - other.power\n }\n val Array(s, n) = readLine().split(\" \").map(_.toInt)\n val a = for {\n _ <- 0 until n\n Array(power, bonus) = readLine().split(\" \").map(_.toInt)\n } yield Dragon(power, bonus)\n val dragons = a.sorted\n val (_, ans) = dragons.foldLeft((s, true)) { (current, d) =>\n val (sum, state) = current\n if (sum <= d.power) (sum, false)\n else (sum + d.bonus, true)\n }\n println(if (ans) \"YES\" else \"NO\")\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject CodeForces extends App{\n\n val array = StdIn.readLine().split(\" \").map(_.toInt)\n val s = array(0)\n val n = array(1)\n\n\n var sorted = (1 to n).map({_ =>\n val temp = StdIn.readLine().split(\" \").map(_.toInt)\n temp(0) -> temp(1)\n }).sortBy(_._1).toList\n\n @tailrec def check(list: List[(Int,Int)], currentS: Int): String = list match {\n case List() => \"YES\"\n case (x,y) :: xs =>\n if (x >= currentS) \"NO\"\n else check(xs,currentS + y)\n }\n\n println(check(sorted,s))\n\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject GCD extends App {\n\n val str = readLine()\n val arr = str.split(\" \")\n\n val s = arr(0).toInt\n val n = arr(1).toInt\n\n case class DragonsNums(x: Int, y: Int)\n\n def fillDragonsNums(n: Int, seq: Seq[DragonsNums]): Seq[DragonsNums] =\n if (n == 0) seq\n else {\n val str = readLine()\n val arr = str.split(\" \")\n\n val x = arr(0).toInt\n val y = arr(1).toInt\n fillDragonsNums(n - 1, seq :+ DragonsNums(x, y))\n }\n\n def battleOutcomes(s: Int, seq: Seq[DragonsNums], results: Seq[Boolean]): Seq[Boolean] = {\n if (seq.isEmpty) results\n else battleOutcomes(s + seq.head.y, seq.tail, results :+ (s > seq.head.x))\n }\n\n if (battleOutcomes(s, fillDragonsNums(n, Seq()).sortBy(_.x), Seq()).forall(identity)) println(\"YES\")\n else println(\"NO\")\n}"}, {"source_code": "object Dragons_230A extends App{\n var firstRow = readLine().split(\" \").toList\n val kiritoPower = firstRow(0).toInt\n val amountDragons = firstRow(1).toInt\n var dragons = List.empty[(Int, Int)]\n for (i <- 0 until amountDragons) {\n var dragonss = readLine().split(\" \").toList\n var tuple = (dragonss.head.toInt, dragonss.last.toInt)\n dragons = dragons :+ tuple\n }\n dragons = dragons.sortWith(_._1 < _._1)\n\n def game (kirito: Int, dragonsss: List[(Int, Int)]): Unit = dragonsss match {\n case Nil => println(\"YES\")\n case (dragonsPower: Int, bonus: Int) :: xs if kirito > dragonsPower => game(kirito + bonus, xs)\n case (dragonsPower: Int, bonus: Int) :: xs if kirito <= dragonsPower => println(\"NO\")\n }\n game(kiritoPower, dragons)\n}\n"}], "negative_code": [{"source_code": "\nimport scala.annotation.tailrec\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject CodeForces extends App{\n\n val array = StdIn.readLine().split(\" \").map(_.toInt)\n val s = array(0)\n val n = array(1)\n\n\n var sorted = (1 to n).map({_ =>\n val temp = StdIn.readLine().split(\" \").map(_.toInt)\n temp(0) -> temp(1)\n }).sortBy(_._1).toList\n\n @tailrec def check(list: List[(Int,Int)], currentS: Int): String = list match {\n case List() => \"YES\"\n case (x,y) :: xs =>\n if (x > currentS) \"NO\"\n else check(xs,currentS + y)\n }\n\n println(check(sorted,s))\n\n\n}\n"}, {"source_code": "\nimport scala.io.StdIn._\n\nobject GCD extends App {\n\n val str = readLine()\n val arr = str.split(\" \")\n\n val s = arr(0).toInt\n val n = arr(1).toInt\n\n case class DragonsNums(x: Int, y: Int)\n\n def fillDragonsNums(n: Int, seq: Seq[DragonsNums]): Seq[DragonsNums] =\n if (n == 0) seq\n else {\n val str = readLine()\n val arr = str.split(\" \")\n\n val x = arr(0).toInt\n val y = arr(1).toInt\n fillDragonsNums(n - 1, seq :+ DragonsNums(x, y))\n }\n\n def battleOutcomes(s: Int, seq: Seq[DragonsNums], results: Seq[Boolean]): Seq[Boolean] = {\n if (seq.isEmpty) results\n else battleOutcomes(s + seq.head.y, seq.tail, results :+ (s >= seq.head.x))\n }\n\n if (battleOutcomes(s, fillDragonsNums(n, Seq()).sortBy(_.x), Seq()).forall(identity)) println(\"YES\")\n else println(\"NO\")\n}"}, {"source_code": "object Dragons_230A extends App{\n\n var firstRow = readLine().split(\" \").toList\n val kiritoPower = firstRow(0).toInt\n val amountDragons = firstRow(1).toInt\n var dragons = List.empty[(Int, Int)]\n \n for(i <- 0 until amountDragons){\n var dragonss = readLine().split(\" \").toList\n var tuple = (dragonss.head.toInt, dragonss.last.toInt)\n dragons = dragons :+ tuple\n }\n def game(kirito: Int, dragonsss: List[(Int, Int)]): Unit = dragonsss match {\n case Nil => println(\"YES\")\n case (dragonsPower: Int, bonus: Int) :: xs if kirito > dragonsPower => game(kirito + bonus, xs)\n case (dragonsPower: Int, bonus: Int) :: xs if kirito < dragonsPower => println(\"NO\")\n\n }\n game(kiritoPower, dragons)\n\n\n\n}"}, {"source_code": "object Dragons_230A extends App{\n\n var firstRow = readLine().split(\" \").toList\n val kiritoPower = firstRow(0).toInt\n val amountDragons = firstRow(1).toInt\n var dragons = List.empty[(Int, Int)]\n for(i <- 0 until amountDragons){\n var dragonss = readLine().split(\" \").toList\n var tuple = (dragonss.head.toInt, dragonss.last.toInt)\n dragons = dragons :+ tuple\n }\n def game(kirito: Int, dragonsss: List[(Int, Int)]): Unit = dragonsss match {\n case Nil => println(\"YES\")\n case (dragonsPower: Int, bonus: Int) :: xs if kirito > dragonsPower => game(kirito + bonus, xs)\n case (dragonsPower: Int, bonus: Int) :: xs if kirito < dragonsPower => println(\"NO\")\n }\n game(kiritoPower, dragons)\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _230A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val s = next.toInt\n val n = next.toInt\n val a = (1 to n).map(i => (next.toInt, next.toInt)).sortBy(u => u._1).toList\n def doit(a: List[(Int, Int)], s: Int): String =\n if (a == Nil) \"YES\"\n else if (a.head._1 > s) \"NO\"\n else doit(a.tail, s + a.head._2)\n println(doit(a, s))\n}\n"}, {"source_code": "object Main {\n\n class Dragon(val x:Int, val y:Int) extends Ordered[Dragon] {\n def compare(other : Dragon) = {\n this.y.compare(other.y)\n }\n override def toString(): String = \"x: \" + x + \", y: \" + y\n }\n\n def main(args: Array[String]): Unit = {\n var Array(s, n) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n var d = new collection.mutable.PriorityQueue[Dragon]()\n\n for (i<-0 until n) {\n val Array(x, y) = io.StdIn.readLine.split(\" \").map(_.toInt)\n d.enqueue(new Dragon(x,y))\n }\n\n var tmp = new collection.mutable.ArrayBuffer[Dragon]()\n\n while (!d.isEmpty) {\n val top = d.dequeue\n if (s > top.x) {\n s += top.y\n if (!tmp.isEmpty) {\n tmp.foreach(d.enqueue(_))\n tmp.clear()\n }\n }\n else tmp += top\n println(d)\n }\n if (tmp.isEmpty) println(\"YES\")\n else println(\"NO\")\n\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject _230_A extends App {\n val Array(s, n) = readLine().split(\" \").map(_.toInt)\n val dragons = new Array[(Int, Int)](n)\n\n for (i <- 0 until n) {\n val Array(strength, bonus) = readLine().split(\" \").map(_.toInt)\n dragons(i) = (strength, bonus)\n }\n\n val currentDragons = dragons.sortBy(_._1).toBuffer\n\n def findMaxDragonIdx(currentStrength: Int) = {\n var maxIdx = -1\n var maxBonus = Integer.MIN_VALUE\n for (i <- currentDragons.indices) {\n val (s, b) = currentDragons(i)\n if (s <= currentStrength && maxBonus < b) {\n maxIdx = i\n maxBonus = b\n }\n }\n\n maxIdx\n }\n\n var dragonToKill = 0\n var currentStrength = s\n do {\n dragonToKill = findMaxDragonIdx(currentStrength)\n// println(\"kill \" + dragonToKill)\n if (dragonToKill > -1) {\n currentStrength -= dragons(dragonToKill)._1\n currentStrength += dragons(dragonToKill)._2\n currentDragons.remove(dragonToKill)\n }\n } while (dragonToKill != -1 && !currentDragons.isEmpty)\n\n println(if (currentDragons.isEmpty) \"YES\" else \"NO\")\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject _230_A extends App {\n val Array(s, n) = readLine().split(\" \").map(_.toInt)\n val dragons = new Array[(Int, Int)](n)\n\n for (i <- 0 until n) {\n val Array(strength, bonus) = readLine().split(\" \").map(_.toInt)\n dragons(i) = (strength, bonus)\n }\n\n val currentDragons = dragons.sortBy(_._1).toBuffer\n\n def findMaxDragonIdx(currentStrength: Int) = {\n var maxIdx = -1\n var maxBonus = Integer.MIN_VALUE\n for (i <- currentDragons.indices) {\n val (s, b) = currentDragons(i)\n if (s < currentStrength && maxBonus < b) {\n maxIdx = i\n maxBonus = b\n }\n }\n\n maxIdx\n }\n\n var dragonToKill = 0\n var currentStrength = s\n do {\n dragonToKill = findMaxDragonIdx(currentStrength)\n// println(\"kill \" + dragonToKill)\n if (dragonToKill > -1) {\n currentStrength += dragons(dragonToKill)._2\n currentDragons.remove(dragonToKill)\n }\n } while (dragonToKill != -1 && !currentDragons.isEmpty)\n\n println(if (currentDragons.isEmpty) \"YES\" else \"NO\")\n}\n"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject Dragons {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readLongs() : Array[Long] = \n readLine.split(' ').map(_.toLong)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n \n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n \n def canWin(s: Int, dragons : List[(Int,Int)]) : Boolean = dragons match {\n case Nil => true\n case (x,y) :: ds if x <= s => canWin(s+y,ds)\n case _ => false \n }\n \n def main(args: Array[String]) {\n val (s,n) = readTuple\n val dragons = for {\n i <- 1 to n\n (x,y) = readTuple\n } yield (x,y)\n if (canWin(s,dragons.sortBy(_._1).toList)) println(\"YES\") else println(\"NO\")\n \n }\n \n}"}, {"source_code": "object main extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n def solve(input: InputStream, output: PrintStream): Unit = {\n val sc = new Scanner(input)\n var s: Long = sc.nextInt()\n val ndragons = sc.nextInt()\n val dragonsStrength = (1 to ndragons).map( _ => sc.nextInt())\n val dragonsBonus = (1 to ndragons).map( _ => sc.nextInt())\n val dSB = dragonsStrength.zip(dragonsBonus).sortBy{ case (ds,_) => ds}\n var isGood = true\n dSB.foreach{\n case (ds,db) => {\n isGood &= s > ds\n s += db\n }\n }\n output.println(if(isGood) \"YES\" else \"NO\")\n }\n solve(System.in,System.out)\n}"}, {"source_code": "object main extends App with fastIO {\n \n var (s, n) = (nextInt, nextInt)\n var a = Array.fill(n, 2)(nextInt) sortBy(_(0)) \n a foreach { it => if (it(0) <= s) s += it(1) }\n println(if (a.map(_(0)).max <= s) \"YES\" else \"NO\") \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}], "src_uid": "98f5b6aac08f48f95b2a8ce0738de657"} {"source_code": "object P2C {\n import Math._\n\n def main(args : Array[String]) {\n val Array(x1, y1, r1) = readLine split \" \" map {_.toDouble}\n val Array(x2, y2, r2) = readLine split \" \" map {_.toDouble}\n val Array(x3, y3, r3) = readLine split \" \" map {_.toDouble}\n val (x12, y12) = (x1 - x2, y1 - y2)\n val (x13, y13) = (x1 - x3, y1 - y3)\n val d12 = x12 * x12 + y12 * y12\n val d13 = x13 * x13 + y13 * y13\n val e = x12 * y13 - x13 * y12\n val (rr1, rr2, rr3) = (r1 * r1, r2 * r2, r3 * r3)\n val (rr21, rr31) = (rr2 - rr1, rr3 - rr1)\n val ry = rr21 * y13 - rr31 * y12\n val rx = x12 * rr31 - x13 * rr21\n val dy = d12 * y13 - d13 * y12\n val dx = x12 * d13 - x13 * d12\n val r = rx * rx + ry * ry\n val d = dx * dx + dy * dy\n val t = dx * rx + dy * ry + e * e * rr1 * 2.0\n val s = if (r == 0.0) {\n Array(d / (t * 2.0))\n } else {\n val delta = t * t - r * d\n if (delta < 0.0) {\n Array[Double]()\n } else {\n val sD = sqrt(delta)\n val s1 = (t + sD) / r\n val s2 = (t - sD) / r\n Array(s1, s2).filter{_ > 1.0}\n }\n }\n def diff(p1 : Double, p2 : Double) = {\n val d = abs(p1 - p2)\n if (d <= PI) d else 2 * PI - d\n }\n val p = for {\n si <- s\n x = x1 + (si * ry - dy) / (e * 2.0)\n y = y1 + (si * rx - dx) / (e * 2.0)\n p1 = atan2(y1 - y, x1 - x)\n p2 = atan2(y2 - y, x2 - x)\n p3 = atan2(y3 - y, x3 - x)\n b = asin(1.0 / si) * 2.0\n if (diff(p1, p2) >= b)\n if (diff(p1, p3) >= b)\n if (diff(p2, p3) >= b)\n } yield (si, x, y)\n if (p.isEmpty) return\n val (_, x, y) = p.minBy{_._1}\n println(x.formatted(\"%.5f\") + \" \" + y.formatted(\"%.5f\"))\n }\n}\n", "positive_code": [{"source_code": "object P2C {\n import Math._\n\n def main(args : Array[String]) {\n val Array(x1, y1, r1) = readLine split \" \" map {_.toDouble}\n val Array(x2, y2, r2) = readLine split \" \" map {_.toDouble}\n val Array(x3, y3, r3) = readLine split \" \" map {_.toDouble}\n val (x12, y12) = (x1 - x2, y1 - y2)\n val (x13, y13) = (x1 - x3, y1 - y3)\n val d12 = x12 * x12 + y12 * y12\n val d13 = x13 * x13 + y13 * y13\n val e = x12 * y13 - x13 * y12\n val (rr1, rr2, rr3) = (r1 * r1, r2 * r2, r3 * r3)\n val (rr21, rr31) = (rr2 - rr1, rr3 - rr1)\n val ry = rr21 * y13 - rr31 * y12\n val rx = x12 * rr31 - x13 * rr21\n val dy = d12 * y13 - d13 * y12\n val dx = x12 * d13 - x13 * d12\n val r = rx * rx + ry * ry\n val d = dx * dx + dy * dy\n val t = dx * rx + dy * ry + e * e * rr1 * 2.0\n val s = if (r == 0.0) {\n Array(d / (t * 2.0))\n } else {\n val delta = t * t - r * d\n if (delta < 0.0) {\n Array[Double]()\n } else {\n val sD = sqrt(delta)\n val s1 = (t + sD) / r\n val s2 = (t - sD) / r\n Array(s1, s2).filter{_ > 1.0}\n }\n }\n def diff(p1 : Double, p2 : Double) = {\n val d = abs(p1 - p2)\n if (d <= PI) d else 2 * PI - d\n }\n val p = for {\n si <- s\n x = x1 + (si * ry - dy) / (e * 2.0)\n y = y1 + (si * rx - dx) / (e * 2.0)\n p1 = atan2(y1 - y, x1 - x)\n p2 = atan2(y2 - y, x2 - x)\n p3 = atan2(y3 - y, x3 - x)\n b = asin(1.0 / si) * 2.0\n if (diff(p1, p2) >= b)\n if (diff(p1, p3) >= b)\n if (diff(p2, p3) >= b)\n } yield (si, x, y)\n if (p.isEmpty) return\n val (_, x, y) = p.minBy{_._1}\n println(x.formatted(\"%.5f\") + \" \" + y.formatted(\"%.5f\"))\n }\n}"}], "negative_code": [], "src_uid": "9829e1913e64072aadc9df5cddb63573"} {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val ps = Array.fill(n){ readLine.toCharArray.map(_ == 'X') }\n val totalBad = ps.map(_.count(identity)).sum\n\n var startX, startY = 0\n while (startY < n && !ps(startY)(startX)) {\n while (startX < m && !ps(startY)(startX)) {\n startX += 1\n }\n if (startX == m) {\n startX = 0\n startY += 1\n }\n }\n\n val rightCnt = Array.fill(n, m)(0) \n val downCnt = Array.fill(n, m)(0) \n\n for (y <- n - 1 to 0 by -1) {\n for (x <- m - 1 to 0 by -1) {\n if (ps(y)(x)) {\n if (x + 1 < m) rightCnt(y)(x) = rightCnt(y)(x + 1) + 1\n else rightCnt(y)(x) = 1\n if (y + 1 < n) downCnt(y)(x) = downCnt(y + 1)(x) + 1\n else downCnt(y)(x) = 1\n }\n }\n }\n\n var minArea = Int.MaxValue\n for (bY <- 1 to n - startY) {\n for (bX <- 1 to m - startX ) {\n val area = bY * bX\n if (area < minArea && check(bX, bY)) {\n minArea = area\n }\n }\n }\n \n def check(bX: Int, bY : Int): Boolean = {\n var x0 = startX\n var y0 = startY\n var fixed = 0\n\n if (rightCnt(y0)(x0) > bX && downCnt(y0)(x0) > bY) return false\n if (rightCnt(y0)(x0) < bX && downCnt(y0)(x0) < bY) return false\n\n for (y <- y0 until y0 + bY) {\n if (rightCnt(y)(x0) < bX) return false\n fixed += bX\n }\n \n var moved = true\n while (moved) {\n if (x0 + bX < m && downCnt(y0)(x0 + bX) >= bY && !(y0 + bY < n && rightCnt(y0 + bY)(x0) > 0)) {\n fixed += bY\n x0 += 1\n moved = true\n } else if (y0 + bY < n && rightCnt(y0 + bY)(x0) >= bX && !(x0 + bX < m && downCnt(y0)(x0 + bX) > 0)) {\n y0 += 1\n fixed += bX\n moved = true\n } else moved = false\n }\n\n fixed == totalBad\n }\n \n println(if (minArea == Int.MaxValue) -1 else minArea)\n}", "positive_code": [{"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 05.10.14.\n */\nobject C extends App {\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n val m = nextInt\n val gs = Array.fill(n, m)(true)\n for (i <- 0 until n) {\n gs(i) = nextString.toCharArray.map(_ == 'X')\n }\n\n// for (i <- 0 until n) {\n// for (j <- 0 until m) {\n// out.print(gs(i)(j))\n// out.print(\" \")\n// }\n// out.print(\"\\n\")\n// }\n\n def tryPaint(gs: Array[Array[Boolean]], n: Int, m: Int): Int = {\n var lux = 0\n var luy = 0\n var found = false\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (!found && gs(i)(j)) {\n found = true\n lux = i\n luy = j\n }\n }\n }\n //out.println(lux, luy)\n\n var maxY = 1\n var foundMaxY = false\n for (i <- luy + 1 until m) {\n if (!foundMaxY && gs(lux)(i) == false) {\n foundMaxY = true\n maxY = i - luy\n }\n }\n if (!foundMaxY) {\n maxY = m - luy\n }\n //out.println(maxY)\n\n var x = 1\n\n var foundX = false\n for (i <- lux + 1 until n) {\n if (!foundX && gs(i)(luy) == false) {\n foundX = true\n x = i - lux\n }\n }\n if (!foundX) {\n x = n - lux\n }\n\n var y = 1\n if (lux + x < n) {\n var foundY = false\n for (j <- luy + 1 until luy + maxY) {\n if(!foundY && gs(lux + x)(j) == true) {\n foundY = true\n y = luy + maxY - j\n }\n }\n if (!foundY) {\n y = 1\n }\n }\n\n //out.println(x, y)\n\n val ps = Array.fill(n, m)(false)\n\n for (i <- lux until lux + x) {\n for (j <- luy until luy + y) {\n ps(i)(j) = true\n }\n }\n\n def paintRight(x: Int, y: Int, h: Int, w: Int): Boolean = {\n if (y + w == m) {\n false\n } else {\n for (i <- x until x + h) {\n ps(i)(y + w) = true\n }\n true\n }\n }\n\n def paintDown(x: Int, y: Int, h: Int, w: Int): Boolean = {\n if (x + h == n) {\n false\n } else {\n for (i <- y until y + w) {\n ps(x + h)(i) = true\n }\n true\n }\n }\n\n var curx = lux\n var cury = luy\n\n var painted = false\n while (!painted) {\n if (cury + y < m && gs(curx)(cury + y) == true) {\n paintRight(curx, cury, x, y)\n cury += 1\n } else if (curx + x < n && gs(curx + x)(cury) == true) {\n paintDown(curx, cury, x, y)\n curx += 1\n } else {\n painted = true\n }\n }\n\n// for (i <- 0 until n) {\n// for (j <- 0 until m) {\n// out.print(ps(i)(j))\n// out.print(\" \")\n// }\n// out.print(\"\\n\")\n// }\n\n var canPaint = true\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (ps(i)(j) != gs(i)(j)) {\n canPaint = false\n }\n }\n }\n\n if (canPaint) {\n x * y\n } else {\n -1\n }\n }\n\n val gst = Array.fill(m, n)(true)\n for (i <- 0 until m) {\n for (j <- 0 until n) {\n gst(i)(j) = gs(j)(i)\n }\n }\n\n val ans1 = tryPaint(gs, n, m)\n val ans2 = tryPaint(gst, m, n)\n\n if (ans1 == -1 && ans2 == -1) {\n out.print(-1)\n } else {\n if (ans1 == -1) {\n out.print(ans2)\n }\n if (ans2 == -1) {\n out.print(ans1)\n }\n if (ans1 != -1 && ans2 != -1) {\n out.print(math.min(ans1, ans2))\n }\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}"}], "negative_code": [], "src_uid": "e50551fbbd1b2d35da04d73202cc0191"} {"source_code": "import scala.io.StdIn._\n\nobject B_1182 extends App {\n val Array(h, w) = readLine().split(\" \").map(_.toInt)\n val A = Array.ofDim[Boolean](h, w)\n\n for (i <- 0 until h) {\n A(i) = readLine().map(_ != '.').toArray\n }\n\n def findCenter: Option[(Int, Int)] = {\n for {\n i <- 1 until h - 1\n j <- 1 until w - 1\n } {\n if (A(i)(j) && A(i - 1)(j) && A(i + 1)(j) && A(i)(j - 1) && A(i)(j + 1)) return Some((i, j))\n }\n\n None\n }\n\n def hasOnlyCross: Boolean = {\n findCenter match {\n case None =>\n false\n case Some((row, col)) =>\n for {\n i <- 0 until h\n j <- 0 until w\n if i != row && j != col\n } {\n if (A(i)(j)) return false\n }\n\n var left = 0\n var right = w - 1\n var top = 0\n var bottom = h - 1\n\n while (!A(row)(left)) left += 1\n while (!A(row)(right)) right -= 1\n while (!A(top)(col)) top += 1\n while (!A(bottom)(col)) bottom -= 1\n\n for (i <- left to right) if (!A(row)(i)) return false\n for (j <- top to bottom) if (!A(j)(col)) return false\n\n true\n }\n\n }\n\n if (hasOnlyCross) println(\"YES\")\n else println(\"NO\")\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val H, W = ni()\n val g = nm_c(H, W)\n val D = Array(\n (-1, 0),\n (1, 0),\n (0, -1),\n (0, 1),\n (0, 0)\n )\n\n var found: (Int, Int) = null\n REP(H) { i =>\n REP(W) { j =>\n var ok = true\n REP(D.length) { k =>\n val ii = i+D(k)._1\n val jj = j+D(k)._2\n ok &&= ii >= 0 && ii < H && jj >= 0 && jj < W && g(ii)(jj) == '*'\n }\n if (ok && found == null) {\n debug(\"found\")\n found = (i, j)\n } else if (ok && found != null) {\n debug(\"found twice\")\n out.println(\"NO\")\n return\n }\n }\n }\n\n if (found == null) {\n out.println(\"NO\")\n return\n }\n\n val (i, j) = found\n def count(di: Int, dj: Int): Int = {\n var ii = i\n var jj = j\n var cnt = 0\n while(ii >= 0 && ii < H && jj >= 0 && jj < W && g(ii)(jj) == '*') {\n ii += di\n jj += dj\n cnt += 1\n }\n cnt\n }\n\n val cnt = count(-1, 0) +\n count(1, 0) +\n count(0, -1) +\n count(0, 1) +\n -3\n\n val sum = g.map(_.count(_ == '*')).sum\n if (sum == cnt) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n }\n}"}], "negative_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\ncase class Point(x: Int, y: Int)\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val H, W = ni()\n val g = nm_c(H, W)\n val L, R, T, D = Array.ofDim[Int](H, W)\n REP(H) { i =>\n REP(W) { j =>\n if (g(i)(j) == '*') {\n L(i)(j) += 1\n T(i)(j) += 1\n if (j > 0) L(i)(j) += L(i)(j - 1)\n if (i > 0) T(i)(j) += L(i - 1)(j)\n }\n }\n }\n\n REP_r(H) { i =>\n REP_r(W) { j =>\n if (g(i)(j) == '*') {\n R(i)(j) += 1\n D(i)(j) += 1\n if (j + 1 < W) R(i)(j) += R(i)(j + 1)\n if (i + 1 < H) D(i)(j) += D(i + 1)(j)\n }\n }\n }\n\n debug(\"L\")\n debugDim(L)\n debug(\"R\")\n debugDim(R)\n debug(\"T\")\n debugDim(T)\n debug(\"D\")\n debugDim(D)\n\n var found: (Int, Int) = null\n REP(H) { i =>\n REP(W) { j =>\n if (L(i)(j) > 1 && R(i)(j) > 1 && T(i)(j) > 1 && D(i)(j) > 1) {\n if (found != null) {\n debug(s\"found2 $i $j\")\n out.println(\"NO\")\n return\n }\n found = (i, j)\n }\n }\n }\n\n def test: Boolean = {\n val P = mutable.Set[Point]()\n val (h, w) = found\n REP(L(h)(w)) { i =>\n P += Point(h, w - i)\n }\n REP(R(h)(w)) { i =>\n P += Point(h, w + i)\n }\n REP(T(h)(w)) { i =>\n P += Point(h - i, w)\n }\n REP(D(h)(w)) { i =>\n P += Point(h + i, w)\n }\n\n REP(H) { i =>\n REP(W) { j =>\n if (g(i)(j) == '*' && !P.contains(Point(i, j))) return false\n }\n }\n true\n }\n\n if (found != null && test) out.println(\"YES\")\n else out.println(\"NO\")\n }\n}"}], "src_uid": "6405161be280fea943201fa00ef6f448"} {"source_code": "\nimport java.io._\nimport java.util._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val m = nextInt\n val t = nextInt\n val r = nextInt\n if (r - 1 > t) {\n out.println(-1)\n return 1\n }\n val w = new Array[Int](m)\n for (i <- 0 until m) {\n w(i) = nextInt + t + 1\n }\n var ans = 0\n val candles = new Array[Int](1000)\n for (i <- 0 until m) {\n var sum = 0\n for (j <- w(i) - 1 to w(i) - t by -1) {\n sum += candles(j)\n }\n if (sum != r) {\n for (j <- w(i) - 1 to w(i) - t by -1) {\n if (sum < r && candles(j) == 0) {\n candles(j) = 1\n sum += 1\n }\n }\n if (sum < r) {\n out.println(-1)\n return 1\n }\n }\n }\n candles.foreach(ans += _)\n out.println(ans)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(m, t, r) = in.next().split(' ').map(_.toInt)\n if (r > t)\n println(-1)\n else {\n val data = in.next().split(' ').map(_.toInt)\n val (count, _, _) = data.tail.foldLeft(r, data.head, (1 to r).map(i => data.head - i).toList) {\n case (acc, el) if acc._1 == -1 => acc\n case ((sum, previous, fired), el) =>\n val firedBefore = el - t\n// println(\"el = \" + el)\n// println(\"sum = \" + sum)\n// println(\"previous = \" + previous)\n// println(\"fired = \" + fired)\n val left = fired.filter(_ >= firedBefore)\n val shouldFire = r - left.size\n// println(\"shouldFire = \" + shouldFire)\n if (shouldFire <= 0)\n (sum, el, left)\n else if (shouldFire > (el - previous))\n (-1, el, left)\n else\n (sum + shouldFire, el, (1 to shouldFire).map(i => el - i).toList ::: left)\n }\n println(count)\n }\n}\n\n//5 3 2\n//1 2 5 10 20"}, {"source_code": "/**\n * Created by helfper on 27/01/2015.\n */\nobject AnyaAndGhosts {\n def main(args: Array[String]) {\n val Array(m, t, r) = io.StdIn.readLine.split(\" \").map(_.toInt)\n val ghosts = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n println(solve(ghosts, t, r))\n }\n\n def solve(ghosts: Array[Int], t: Int, r: Int): Int = {\n val candles = Array.fill(r)(0)\n\n def iterate(g: Int): Int = {\n var n = 0\n 0.until(r).foreach(i =>\n if (candles(i) < g) {\n candles(i) = g+t-n-1\n n += 1;\n }\n )\n if (t < n) -1\n else n\n }\n\n ghosts.foldLeft(0) { (r, g) =>\n val it = iterate(g)\n if (it == -1) it\n else r + it\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(m, t, r) = in.next().split(' ').map(_.toInt)\n if (r > t)\n println(-1)\n else {\n val data = in.next().split(' ').map(_.toInt)\n val (count, _, _) = data.tail.foldLeft(r, data.head, (1 to r).map(i => data.head - i).toList) {\n case (acc, el) if acc._1 == -1 => acc\n case ((sum, previous, fired), el) =>\n val firedBefore = el - t\n// println(\"el = \" + el)\n// println(\"sum = \" + sum)\n// println(\"previous = \" + previous)\n// println(\"fired = \" + fired)\n val left = fired.filter(_ > firedBefore)\n val shouldFire = r - left.size\n if (shouldFire <= 0)\n (sum, el, left)\n else if (shouldFire > (el - previous))\n (-1, el, left)\n else\n (sum + shouldFire, el, (1 to shouldFire).map(i => el - i).toList ::: left)\n }\n println(count)\n }\n}\n\n"}, {"source_code": "import java.io._\nimport java.util._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val m = nextInt\n val t = nextInt\n val r = nextInt\n if (r - 1 > t) {\n out.println(-1)\n return 1\n }\n val w = new Array[Int](m)\n for (i <- 0 until m) {\n w(i) = nextInt\n }\n var ans = 0\n val fullWindow = t - r + 1\n var currWindow = fullWindow\n var currR = r\n ans += r\n for (i <- 1 until m) {\n val diff = w(i) - w(i - 1)\n if (diff <= currWindow) {\n currWindow -= diff\n } else {\n if (diff - currWindow >= r) {\n ans += r\n currWindow = fullWindow\n } else {\n ans += diff - currWindow\n currR = diff - currWindow\n currWindow = fullWindow\n }\n }\n }\n out.println(ans)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val m = nextInt\n val t = nextInt\n val r = nextInt\n if (r - 1 > t) {\n out.println(-1)\n return 1\n }\n val w = new Array[Int](m)\n for (i <- 0 until m) {\n w(i) = nextInt\n }\n var ans = 0\n val window = t - r + 1\n ans += r\n for (i <- 1 until m) {\n val diff = w(i) - w(i - 1)\n if (diff <= window) {\n\n } else {\n if (diff - window > r) {\n ans += r\n } else {\n ans += diff - window\n }\n }\n }\n out.println(ans)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val m = nextInt\n val t = nextInt\n val r = nextInt\n if (r - 1 > t) {\n out.println(-1)\n return 1\n }\n val w = new Array[Int](m)\n for (i <- 0 until m) {\n w(i) = nextInt + t + 1\n }\n var ans = 0\n val candles = new Array[Int](500)\n for (i <- 0 until m) {\n var sum = 0\n for (j <- w(i) to w(i) - t by -1) {\n sum += candles(j)\n }\n if (sum != r) {\n for (j <- w(i) to w(i) - t by -1) {\n if (sum < r && candles(j) == 0) {\n candles(j) = 1\n sum += 1\n }\n }\n if (sum < r) {\n out.println(-1)\n return 1\n }\n }\n }\n candles.foreach(ans += _)\n out.println(ans)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val m = nextInt\n val t = nextInt\n val r = nextInt\n if (r - 1 > t) {\n out.println(-1)\n return 1\n }\n val w = new Array[Int](m)\n for (i <- 0 until m) {\n w(i) = nextInt + t + 1\n }\n var ans = 0\n val candles = new Array[Int](500)\n for (i <- 0 until m) {\n var sum = 0\n for (j <- w(i) - 1 to w(i) - t by -1) {\n sum += candles(j)\n }\n if (sum != r) {\n for (j <- w(i) to w(i) - t by -1) {\n if (sum < r && candles(j) == 0) {\n candles(j) = 1\n sum += 1\n }\n }\n if (sum < r) {\n out.println(-1)\n return 1\n }\n }\n }\n candles.foreach(ans += _)\n out.println(ans)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "src_uid": "03772bac6ed5bfe75bc0ad4d2eab56fd"} {"source_code": "//package edu29\n\nimport scala.collection.immutable.IntMap\nimport scala.io.StdIn\n\nobject E extends App {\n def readInts = StdIn.readLine().split(\" \").map(_.toInt)\n val Array(n) = readInts\n\n val tvs = Array.fill(n)(readInts)\n\n val tree = {\n var pointMap = IntMap[Int]().withDefaultValue(0)\n for (tv <- tvs) {\n pointMap += tv(0) -> (pointMap(tv(0)) + 1)\n pointMap += (tv(1) + 1) -> (pointMap(tv(1) + 1) - 1)\n }\n val points = Array.ofDim[Int](pointMap.size)\n val counts = Array.ofDim[Int](pointMap.size)\n var i = 0\n for ((p, c) <- pointMap) {\n points(i) = p\n counts(i) = c\n i += 1\n }\n\n def sumCount(i: Int): Unit =\n if (i < points.length) {\n counts(i) += counts(i - 1)\n sumCount(i + 1)\n }\n sumCount(1)\n new QueueTree(points, counts)\n }\n\n def go(i: Int): Int =\n if (i == tvs.length) -1\n else if (tree.queue(tvs(i)(0), tvs(i)(1)) > 1) i + 1\n else go(i + 1)\n\n val result = go(0)\n println(result)\n}\n\n\nclass QueueTree(keys: Array[Int], values: Array[Int]) {\n private[this] val total = Array.ofDim[Int](values.length * 3)\n\n @inline private[this] def median(x: Int, y: Int) = (x + y) / 2\n\n private[this] def initGo(a: Int, b: Int, i: Int): Unit =\n if (a == b) total(i) = values(a)\n else {\n val m = median(a, b)\n initGo(a, m, 2 * i + 1)\n initGo(m + 1, b, 2 * i + 2)\n total(i) = total(2 * i + 1) min total(2 * i + 2)\n }\n initGo(0, values.length - 1, 0)\n\n def queue(l: Int, r: Int): Int = {\n def go(a: Int, b: Int, j: Int): Int =\n if (keys(a) > r || keys(b) < l) 1000000000\n else if (keys(a) >= l && keys(b) <= r) total(j)\n else {\n val m = median(a, b)\n go(a, m, 2 * j + 1) min go(m + 1, b, 2 * j + 2)\n }\n go(0, values.length - 1, 0)\n }\n}\n", "positive_code": [{"source_code": "//package edu29\n\nimport scala.collection.immutable.IntMap\nimport scala.io.StdIn\n\nobject E extends App {\n def readInts = StdIn.readLine().split(\" \").map(_.toInt)\n val Array(n) = readInts\n\n val tvs = Array.fill(n)(readInts)\n\n val tree = {\n var pointMap = IntMap[Int]()\n for (tv <- tvs) {\n pointMap += tv(0) -> (pointMap.getOrElse(tv(0), 0) + 1)\n pointMap += (tv(1) + 1) -> (pointMap.getOrElse(tv(1) + 1, 0) - 1)\n }\n val points = Array.ofDim[Int](pointMap.size)\n val counts = Array.ofDim[Int](pointMap.size)\n var i = 0\n for ((p, c) <- pointMap) {\n points(i) = p\n counts(i) = c\n i += 1\n }\n\n def sumCount(i: Int): Unit =\n if (i < points.length) {\n counts(i) += counts(i - 1)\n sumCount(i + 1)\n }\n sumCount(1)\n new QueueTree(points, counts)\n }\n\n def go(i: Int): Int =\n if (i == tvs.length) -1\n else if (tree.queue(tvs(i)(0), tvs(i)(1)) > 1) i + 1\n else go(i + 1)\n\n val result = go(0)\n println(result)\n}\n\n\nclass QueueTree(keys: Array[Int], values: Array[Int]) {\n private[this] val total = Array.ofDim[Int](values.length * 3)\n\n @inline private[this] def median(x: Int, y: Int) = (x + y) / 2\n\n private[this] def initGo(a: Int, b: Int, i: Int): Unit =\n if (a == b) total(i) = values(a)\n else {\n val m = median(a, b)\n initGo(a, m, 2 * i + 1)\n initGo(m + 1, b, 2 * i + 2)\n total(i) = total(2 * i + 1) min total(2 * i + 2)\n }\n initGo(0, values.length - 1, 0)\n\n def queue(l: Int, r: Int): Int = {\n def go(a: Int, b: Int, j: Int): Int =\n if (keys(a) > r || keys(b) < l) 1000000000\n else if (keys(a) >= l && keys(b) <= r) total(j)\n else {\n val m = median(a, b)\n go(a, m, 2 * j + 1) min go(m + 1, b, 2 * j + 2)\n }\n go(0, values.length - 1, 0)\n }\n}\n"}, {"source_code": "//package edu29\n\nimport java.util\n\nimport scala.collection.mutable\nimport scala.io.StdIn\nimport scala.reflect.ClassTag\n\nobject E extends App {\n def readInts = StdIn.readLine().split(\" \").map(_.toInt)\n val Array(n) = readInts\n\n val tvs = Array.fill(n)(readInts)\n\n val tree = {\n val pointMap = new util.HashMap[Int, Int]\n for (tv <- tvs) {\n pointMap.put(tv(0), pointMap.getOrDefault(tv(0), 0) + 1)\n pointMap.put(tv(1) + 1, pointMap.getOrDefault(tv(1) + 1, 0) - 1)\n }\n val points = Array.ofDim[Int](pointMap.size())\n val counts = Array.ofDim[Int](pointMap.size())\n val iter = pointMap.keySet().iterator()\n def initPoints(i: Int): Unit =\n if (iter.hasNext) {\n points(i) = iter.next()\n initPoints(i + 1)\n }\n initPoints(0)\n util.Arrays.sort(points)\n def initCounts(i: Int): Unit =\n if (i < points.length) {\n counts(i) = pointMap.get(points(i))\n initCounts(i + 1)\n }\n initCounts(0)\n def sumCount(i: Int): Unit =\n if (i < points.length) {\n counts(i) += counts(i - 1)\n sumCount(i + 1)\n }\n sumCount(1)\n new QueueTree(counts, points)\n }\n\n def go(i: Int): Int =\n if (i == tvs.length) -1\n else if (tree.queue(tvs(i)(0), tvs(i)(1)) > 1) i + 1\n else go(i + 1)\n\n val result = go(0)\n println(result)\n}\n\n\nclass QueueTree(mins: Array[Int], values: Array[Int]) {\n private[this] val total = Array.ofDim[Int](mins.length * 3)\n\n @inline private[this] def median(x: Int, y: Int) = (x + y) / 2\n\n private[this] def initGo(a: Int, b: Int, i: Int): Unit =\n if (a == b) total(i) = mins(a)\n else {\n val m = median(a, b)\n initGo(a, m, 2 * i + 1)\n initGo(m + 1, b, 2 * i + 2)\n total(i) = total(2 * i + 1) min total(2 * i + 2)\n }\n initGo(0, mins.length - 1, 0)\n\n def queue(l: Int, r: Int): Int = {\n def go(a: Int, b: Int, j: Int): Int =\n if (values(a) > r || values(b) < l) 1000000000\n else if (values(a) >= l && values(b) <= r) total(j)\n else {\n val m = median(a, b)\n go(a, m, 2 * j + 1) min go(m + 1, b, 2 * j + 2)\n }\n go(0, mins.length - 1, 0)\n }\n}\n"}, {"source_code": "//package edu29\n\nimport java.util\n\nimport scala.collection.mutable\nimport scala.io.StdIn\nimport scala.reflect.ClassTag\n\nobject E extends App {\n def readInts = StdIn.readLine().split(\" \").map(_.toInt)\n val Array(n) = readInts\n\n val tvs = Array.fill(n)(readInts)\n\n val tree = {\n val pointMap = new util.TreeMap[Int, Int]\n for (tv <- tvs) {\n pointMap.put(tv(0), pointMap.getOrDefault(tv(0), 0) + 1)\n pointMap.put(tv(1) + 1, pointMap.getOrDefault(tv(1) + 1, 0) - 1)\n }\n val points = Array.ofDim[Int](pointMap.size())\n val counts = Array.ofDim[Int](pointMap.size())\n val iter = pointMap.entrySet().iterator()\n def init(i: Int): Unit =\n if (iter.hasNext) {\n val e = iter.next()\n points(i) = e.getKey\n counts(i) = e.getValue\n init(i + 1)\n }\n init(0)\n def sumCount(i: Int): Unit =\n if (i < points.length) {\n counts(i) += counts(i - 1)\n sumCount(i + 1)\n }\n sumCount(1)\n new QueueTree(counts, points)\n }\n\n def go(i: Int): Int =\n if (i == tvs.length) -1\n else if (tree.queue(tvs(i)(0), tvs(i)(1)) > 1) i + 1\n else go(i + 1)\n\n val result = go(0)\n println(result)\n}\n\n\nclass QueueTree(mins: Array[Int], values: Array[Int]) {\n private[this] val total = Array.ofDim[Int](mins.length * 3)\n\n @inline private[this] def median(x: Int, y: Int) = (x + y) / 2\n\n private[this] def initGo(a: Int, b: Int, i: Int): Unit =\n if (a == b) total(i) = mins(a)\n else {\n val m = median(a, b)\n initGo(a, m, 2 * i + 1)\n initGo(m + 1, b, 2 * i + 2)\n total(i) = total(2 * i + 1) min total(2 * i + 2)\n }\n initGo(0, mins.length - 1, 0)\n\n def queue(l: Int, r: Int): Int = {\n def go(a: Int, b: Int, j: Int): Int =\n if (values(a) > r || values(b) < l) 1000000000\n else if (values(a) >= l && values(b) <= r) total(j)\n else {\n val m = median(a, b)\n go(a, m, 2 * j + 1) min go(m + 1, b, 2 * j + 2)\n }\n go(0, mins.length - 1, 0)\n }\n}\n"}, {"source_code": "//package edu29\n\nimport java.util\n\nimport scala.collection.mutable\nimport scala.io.StdIn\nimport scala.reflect.ClassTag\n\nobject E extends App {\n def readInts = StdIn.readLine().split(\" \").map(_.toInt)\n val Array(n) = readInts\n\n val tvs = Array.fill(n)(readInts)\n for (tv <- tvs) {tv(1) += 1 }\n\n val pointArr = tvs.flatten.distinct\n util.Arrays.sort(pointArr)\n val points = mutable.HashMap[Int, Int]()\n def fillPoints(i: Int): Unit =\n if (i < pointArr.length) {\n points(pointArr(i)) = i\n fillPoints(i + 1)\n }\n fillPoints(0)\n val counts = Array.ofDim[Int](points.size + 1)\n\n for (lr <- tvs) {\n counts(points(lr(0))) += 1\n counts(points(lr(1))) -= 1\n }\n var i = 1\n while (i < counts.length) {\n counts(i) += counts(i - 1)\n i += 1\n }\n\n val tree = new QueueTree(counts)\n def go(i: Int): Int =\n if (i == tvs.length) -1\n else if (tree.queue(points(tvs(i)(0)), points(tvs(i)(1)) - 1) > 1) i + 1\n else go(i + 1)\n\n val result = go(0)\n println(result)\n}\n\n\nclass QueueTree(init: Array[Int]) extends Traversable[Int] {\n private[this] val total = Array.ofDim[Int](init.length * 3)\n\n @inline private[this] def median(x: Int, y: Int) = (x + y) / 2\n\n private[this] def initGo(a: Int, b: Int, i: Int): Unit =\n if (a == b) total(i) = init(a)\n else {\n val m = median(a, b)\n initGo(a, m, 2 * i + 1)\n initGo(m + 1, b, 2 * i + 2)\n total(i) = total(2 * i + 1) min total(2 * i + 2)\n }\n\n initGo(0, init.length - 1, 0)\n\n\n def queue(l: Int, r: Int): Int = {\n def go(a: Int, b: Int, j: Int): Int =\n if (a > r || b < l) 1000000000\n else if (a >= l && b <= r) total(j)\n else {\n val m = median(a, b)\n\n go(a, m, 2 * j + 1) min go(m + 1, b, 2 * j + 2)\n }\n go(0, init.length - 1, 0)\n }\n\n def foreach[U](f: Int => U): Unit = {\n def go(a: Int, b: Int, i: Int): Unit =\n if (a == b) f(total(i))\n else {\n val m = median(a, b)\n go(a, m, 2 * i + 1)\n go(m + 1, b, 2 * i + 2)\n }\n go(0, init.length - 1, 0)\n }\n}\n"}], "negative_code": [{"source_code": "//package edu29\n\nimport scala.collection.mutable\nimport scala.io.StdIn\nimport scala.reflect.ClassTag\n\nobject E extends App {\n def readInts = StdIn.readLine().split(\" \").map(_.toInt)\n val Array(n) = readInts\n\n val tvs = Array.fill(n)(readInts)\n\n val points = tvs.flatten.distinct.sorted.zipWithIndex.toMap\n val counts = Array.ofDim[Int](points.size + 1)\n\n for (lr <- tvs) {\n counts(points(lr(0))) += 1\n counts(points(lr(1)) + 1) -= 1\n }\n var i = 1\n while (i < counts.length) {\n counts(i) += counts(i - 1)\n i += 1\n }\n\n val tree = new QueueTree(counts)\n val result = tvs.iterator.zipWithIndex.collectFirst {\n case (lr, i) if tree.queue(points(lr(0)), points(lr(1))) > 1 => i + 1\n }.getOrElse(-1)\n\n println(result)\n}\n\n\nclass QueueTree(init: Array[Int]) extends Traversable[Int] {\n val total = Array.ofDim[Int](init.length * 3)\n\n @inline private[this] def median(x: Int, y: Int) = (x + y) / 2\n\n private[this] def initGo(a: Int, b: Int, i: Int): Unit =\n if (a == b) total(i) = init(a)\n else {\n val m = median(a, b)\n initGo(a, m, 2 * i + 1)\n initGo(m + 1, b, 2 * i + 2)\n total(i) = total(2 * i + 1) min total(2 * i + 2)\n }\n\n initGo(0, init.length - 1, 0)\n\n\n def queue(l: Int, r: Int): Int = {\n def go(a: Int, b: Int, j: Int): Int =\n if (a > r || b < l) 1000000000\n else if (a >= l && b <= r) total(j)\n else {\n val m = median(a, b)\n\n go(a, m, 2 * j + 1) min go(m + 1, b, 2 * j + 2)\n }\n go(0, init.length - 1, 0)\n }\n\n def foreach[U](f: Int => U): Unit = {\n def go(a: Int, b: Int, i: Int): Unit =\n if (a == b) f(total(i))\n else {\n val m = median(a, b)\n go(a, m, 2 * i + 1)\n go(m + 1, b, 2 * i + 2)\n }\n go(0, init.length - 1, 0)\n }\n}\n"}, {"source_code": "//package edu29\n\nimport scala.collection.mutable\nimport scala.io.StdIn\nimport scala.reflect.ClassTag\n\nobject E extends App {\n def readInts = StdIn.readLine().split(\" \").map(_.toInt)\n val Array(n) = readInts\n\n val tvs = Array.fill(n)(readInts)\n\n val points = tvs.flatten.distinct.sorted.zipWithIndex.toMap\n val counts = Array.ofDim[Int](points.size + 1)\n\n for (lr <- tvs) {\n counts(points(lr(0))) += 1\n counts(points(lr(1)) + 1) -= 1\n }\n var i = 1\n while (i < counts.length) {\n counts(i) += counts(i - 1)\n i += 1\n }\n\n val tree = new QueueTree(points.size - 1, counts)\n val result = tvs.iterator.zipWithIndex.collectFirst {\n case (lr, i) if tree.queue(points(lr(0)), points(lr(1))) > 1 => i + 1\n }.getOrElse(-1)\n\n println(result)\n}\n\n\nclass QueueTree(n: Int, init: Array[Int]) extends Traversable[Int] {\n protected val totalSize = {\n var ts = 0\n def go(a: Int, b: Int, i: Int): Unit =\n if (a == b) ts = ts max i else {\n val m = median(a, b)\n go(a, m, 2 * i + 1)\n go(m + 1, b, 2 * i + 2)\n }\n go(0, n, 0)\n ts\n }\n\n val total = Array.ofDim[Int](totalSize + 1)\n\n @inline private[this] def median(x: Int, y: Int) = (x + y) / 2\n\n\n private[this] def initGo(a: Int, b: Int, i: Int): Unit =\n if (a == b) total(i) = init(a)\n else {\n val m = median(a, b)\n initGo(a, m, 2 * i + 1)\n initGo(m + 1, b, 2 * i + 2)\n total(i) = total(2 * i + 1) min total(2 * i + 2)\n }\n\n initGo(0, n, 0)\n\n\n def queue(l: Int, r: Int): Int = {\n def go(a: Int, b: Int, j: Int): Int =\n if (a > r || b < l) 1000000000\n else if (a >= l && b <= r) total(j)\n else {\n val m = median(a, b)\n\n go(a, m, 2 * j + 1) min go(m + 1, b, 2 * j + 2)\n }\n go(0, n, 0)\n }\n\n def foreach[U](f: Int => U): Unit = {\n def go(a: Int, b: Int, i: Int): Unit =\n if (a == b) f(total(i))\n else {\n val m = median(a, b)\n go(a, m, 2 * i + 1)\n go(m + 1, b, 2 * i + 2)\n }\n go(0, n, 0)\n }\n}\n"}], "src_uid": "ae094fef84d554137009bedf4a795b6f"} {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val roads = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < roads(u).getOrElse(v, Int.MaxValue)) {\n roads(u).put(v, x)\n roads(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) >= 0 && rails(i) < roads(0).getOrElse(i, Int.MaxValue)) {\n roads(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dists = Array.fill(n) { Long.MaxValue }\n dists(0) = 0L\n\n val pq = new java.util.PriorityQueue[(Int, Long)](1, Ordering.by(_._2))\n pq.add((0, 0L))\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val (u, distU) = pq.poll()\n if (!visited(u)) {\n visited += u\n for ((v, d) <- roads(u)) {\n val newDist = distU + d\n if (newDist < dists(v)) {\n \tdists(v) = newDist\n pq.add((v, newDist))\n }\n if (u > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val adj = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < adj(u).getOrElse(v, Int.MaxValue)) {\n adj(u).put(v, x)\n adj(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) >= 0 && rails(i) < adj(0).getOrElse(i, Int.MaxValue)) {\n adj(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dists = Array.fill(n) { Long.MaxValue }\n dists(0) = 0L\n \n case class Edge(v: Int, dist: Long) extends Comparable[Edge] {\n def compareTo(other: Edge) = if (this.dist == other.dist) this.v.compare(other.v) \n else -this.dist.compare(other.dist)\n }\n\n val pq = mutable.PriorityQueue.empty[Edge]\n pq.enqueue(Edge(0, 0L))\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val edge = pq.dequeue()\n if (!visited(edge.v)) {\n visited += edge.v\n for ((v, d) <- adj(edge.v)) {\n val newDist = edge.dist + d\n if (newDist < dists(v)) {\n \tdists(v) = newDist\n pq.enqueue(Edge(v, newDist))\n }\n if (edge.v > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val adj = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < adj(u).getOrElse(v, Int.MaxValue)) {\n adj(u).put(v, x)\n adj(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) >= 0 && rails(i) < adj(0).getOrElse(i, Int.MaxValue)) {\n adj(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dists = Array.fill(n) { Long.MaxValue }\n dists(0) = 0L\n \n final case class Edge(v: Int, dist: Long) extends Comparable[Edge] {\n @inline def compareTo(other: Edge) = java.lang.Long.compare(other.dist, this.dist)\n }\n\n val pq = mutable.PriorityQueue.empty[Edge]\n pq.enqueue(Edge(0, 0L))\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val Edge(u, distU) = pq.dequeue()\n if (!visited(u)) {\n visited += u\n for ((v, d) <- adj(u)) {\n val newDist = distU + d\n if (newDist < dists(v)) {\n \tdists(v) = newDist\n pq.enqueue(Edge(v, newDist))\n }\n if (u > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val adj = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < adj(u).getOrElse(v, Int.MaxValue)) {\n adj(u).put(v, x)\n adj(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) >= 0 && rails(i) < adj(0).getOrElse(i, Int.MaxValue)) {\n adj(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dists = Array.fill(n) { Long.MaxValue }\n dists(0) = 0L\n \n final case class Edge(v: Int, dist: Long) extends Comparable[Edge] {\n @inline def compareTo(other: Edge) = java.lang.Long.compare(other.dist, this.dist)\n }\n\n val pq = mutable.PriorityQueue.empty[Edge]\n pq.enqueue(Edge(0, 0L))\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val edge = pq.dequeue()\n if (!visited(edge.v)) {\n visited += edge.v\n for ((v, d) <- adj(edge.v)) {\n val newDist = edge.dist + d\n if (newDist < dists(v)) {\n \tdists(v) = newDist\n pq.enqueue(Edge(v, newDist))\n }\n if (edge.v > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val adj = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < adj(u).getOrElse(v, Int.MaxValue)) {\n adj(u).put(v, x)\n adj(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) >= 0 && rails(i) < adj(0).getOrElse(i, Int.MaxValue)) {\n adj(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dists = Array.fill(n) { Long.MaxValue }\n dists(0) = 0L\n \n case class Edge(v: Int, dist: Long) extends Comparable[Edge] {\n def compareTo(other: Edge) = -this.dist.compare(other.dist)\n }\n\n val pq = mutable.PriorityQueue.empty[Edge]\n pq.enqueue(Edge(0, 0L))\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val edge = pq.dequeue()\n if (!visited(edge.v)) {\n visited += edge.v\n for ((v, d) <- adj(edge.v)) {\n val newDist = edge.dist + d\n if (newDist < dists(v)) {\n \tdists(v) = newDist\n pq.enqueue(Edge(v, newDist))\n }\n if (edge.v > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by kshim on 8/08/2014.\n */\nobject CF257_1B extends App {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n\n case class Road(u:Int, v:Int, w:Long)\n case class Train(u:Int, w:Long)\n\n def Process(n:Int, m:Int, k:Long, roads:Seq[Road], trains:Seq[Train]):Long = {\n val trainDists = Array.fill(n + 1) {\n Long.MaxValue\n }\n val roadDists = Array.fill(n + 1) {\n collection.mutable.Map[Int, Long]()\n }\n for (t <- trains) {\n trainDists(t.u) = trainDists(t.u) min t.w\n roadDists(1)(t.u) = roadDists(1).getOrElse(t.u, t.w) min t.w\n roadDists(t.u)(1) = roadDists(1)(t.u)\n }\n for (r <- roads) {\n roadDists(r.u)(r.v) = roadDists(r.u).getOrElse(r.v, Long.MaxValue) min r.w\n roadDists(r.v)(r.u) = roadDists(r.v).getOrElse(r.u, Long.MaxValue) min r.w\n if(r.v == 1 && trainDists(r.u) >= r.w) {\n trainDists(r.u) = Long.MaxValue\n }\n if(r.u == 1 && trainDists(r.v) >= r.w) {\n trainDists(r.v) = Long.MaxValue\n }\n }\n //println(trainDists.toSeq.toString)\n\n val visited = collection.mutable.BitSet(n + 1)\n val pq = new java.util.PriorityQueue[(Int, Long)](1, Ordering.by(_._2))\n pq.add((1, 0))\n\n val dist = Array.fill(n + 1) {\n Long.MaxValue\n }\n dist(1) = 0\n\n while (!pq.isEmpty) {\n val (u, uDist) = pq.poll()\n if (!visited(u)) {\n visited.add(u)\n for ((v, w) <- roadDists(u)) {\n val newDist = uDist + w\n if (newDist < dist(v)) {\n dist(v) = newDist\n pq.add((v, newDist))\n }\n if( trainDists(v) != Long.MaxValue && u > 1 && newDist <= trainDists(v)){\n trainDists(v) = Long.MaxValue\n }\n }\n }\n }\n k - trainDists.count(_ != Long.MaxValue)\n }\n\n val Array(n,m,k) = readInts(3)\n val roads = (1 to m).map(_ => {\n val arr = readInts(3)\n Road(arr(0), arr(1), arr(2))\n })\n val trains = (1 to k).map(_ => {\n val arr = readInts(2)\n Train(arr(0), arr(1))})\n println(Process(n, m, k, roads, trains))\n}\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val adj = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < adj(u).getOrElse(v, Int.MaxValue)) {\n adj(u).put(v, x)\n adj(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) >= 0 && rails(i) < adj(0).getOrElse(i, Int.MaxValue)) {\n adj(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dists = Array.fill(n) { Long.MaxValue }\n dists(0) = 0L\n \n final case class Edge(v: Int, dist: Long) extends Comparable[Edge] {\n @inline def compareTo(other: Edge) = other.dist.compare(this.dist)\n }\n\n val pq = mutable.PriorityQueue.empty[Edge]\n pq.enqueue(Edge(0, 0L))\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val edge = pq.dequeue()\n if (!visited(edge.v)) {\n visited += edge.v\n for ((v, d) <- adj(edge.v)) {\n val newDist = edge.dist + d\n if (newDist < dists(v)) {\n \tdists(v) = newDist\n pq.enqueue(Edge(v, newDist))\n }\n if (edge.v > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val adj = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < adj(u).getOrElse(v, Int.MaxValue)) {\n adj(u).put(v, x)\n adj(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) >= 0 && rails(i) < adj(0).getOrElse(i, Int.MaxValue)) {\n adj(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dists = Array.fill(n) { Long.MaxValue }\n dists(0) = 0L\n \n final case class Edge(v: Int, dist: Long) extends Comparable[Edge] {\n @inline def compareTo(other: Edge) = java.lang.Long.compare(this.dist, other.dist)\n }\n\n //val pq = mutable.PriorityQueue.empty[Edge]\n val pq = new java.util.PriorityQueue[Edge](1)\n pq.add(Edge(0, 0L))\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val Edge(u, distU) = pq.poll()\n if (!visited(u)) {\n visited += u\n for ((v, d) <- adj(u)) {\n val newDist = distU + d\n if (newDist < dists(v)) {\n \tdists(v) = newDist\n pq.add(Edge(v, newDist))\n }\n if (u > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val adj = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < adj(u).getOrElse(v, Int.MaxValue)) {\n adj(u).put(v, x)\n adj(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) >= 0 && rails(i) < adj(0).getOrElse(i, Int.MaxValue)) {\n adj(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dists = Array.fill(n) { Long.MaxValue }\n dists(0) = 0L\n \n case class Edge(v: Int, dist: Long) extends Comparable[Edge] {\n def compareTo(other: Edge) = if (this.dist == other.dist) this.v.compare(other.v) \n else -this.dist.compare(other.dist)\n }\n\n val pq = mutable.PriorityQueue.empty[Edge]\n pq.enqueue(Edge(0, 0L))\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val Edge(u, distU) = pq.dequeue()\n if (!visited(u)) {\n visited += u\n for ((v, d) <- adj(u)) {\n val newDist = distU + d\n if (newDist < dists(v)) {\n \tdists(v) = newDist\n pq.enqueue(Edge(v, newDist))\n }\n if (u > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val adj = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < adj(u).getOrElse(v, Int.MaxValue)) {\n adj(u).put(v, x)\n adj(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) >= 0 && rails(i) < adj(0).getOrElse(i, Int.MaxValue)) {\n adj(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dists = Array.fill(n) { Long.MaxValue }\n dists(0) = 0L\n \n case class Edge(v: Int, dist: Long) extends Comparable[Edge] {\n def compareTo(other: Edge) = this.dist.compare(other.dist)\n }\n\n val pq = new java.util.PriorityQueue[Edge](1)//, Ordering.by(_._2))\n pq.add(Edge(0, 0L))\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val Edge(u, distU) = pq.poll()\n if (!visited(u)) {\n visited += u\n for ((v, d) <- adj(u)) {\n val newDist = distU + d\n if (newDist < dists(v)) {\n \tdists(v) = newDist\n pq.add(Edge(v, newDist))\n }\n if (u > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val roads = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < roads(u).getOrElse(v, Int.MaxValue)) {\n roads(u).put(v, x)\n roads(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) >= 0 && rails(i) < roads(0).getOrElse(i, Int.MaxValue)) {\n roads(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dists = Array.fill(n) { Long.MaxValue }\n dists(0) = 0\n\n //val pq = mutable.PriorityQueue(0)(Ordering.by(dist))\n val pq = new java.util.PriorityQueue[(Int, Long)](1, Ordering.by(_._2))\n pq.add((0, 0))\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val (u, distU) = pq.poll()\n if (!visited(u)) {\n visited += u\n for ((v, d) <- roads(u)) {\n val newDist = distU + d\n if (newDist < dists(v)) {\n \tdists(v) = newDist\n pq.add((v, newDist))\n }\n if (u > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val adj = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < adj(u).getOrElse(v, Int.MaxValue)) {\n adj(u).put(v, x)\n adj(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) >= 0 && rails(i) < adj(0).getOrElse(i, Int.MaxValue)) {\n adj(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dists = Array.fill(n) { Long.MaxValue }\n dists(0) = 0L\n \n final case class Edge(v: Int, dist: Long) extends Comparable[Edge] {\n @inline def compareTo(other: Edge) = java.lang.Long.compare(other.dist, this.dist)\n }\n\n //val pq = mutable.PriorityQueue.empty[Edge]\n val pq = new java.util.PriorityQueue[Edge](1)\n pq.add(Edge(0, 0L))\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val Edge(u, distU) = pq.poll()\n if (!visited(u)) {\n visited += u\n for ((v, d) <- adj(u)) {\n val newDist = distU + d\n if (newDist < dists(v)) {\n \tdists(v) = newDist\n pq.add(Edge(v, newDist))\n }\n if (u > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val adj = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < adj(u).getOrElse(v, Int.MaxValue)) {\n adj(u).put(v, x)\n adj(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) >= 0 && rails(i) < adj(0).getOrElse(i, Int.MaxValue)) {\n adj(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dists = Array.fill(n) { Long.MaxValue }\n dists(0) = 0L\n \n case class Edge(v: Int, dist: Long) extends Comparable[Edge] {\n def compareTo(other: Edge) = if (this.dist == other.dist) this.v.compare(other.v) \n else this.dist.compare(other.dist)\n }\n\n val pq = mutable.PriorityQueue.empty[Edge]\n pq.enqueue(Edge(0, 0L))\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val Edge(u, distU) = pq.dequeue()\n if (!visited(u)) {\n visited += u\n for ((v, d) <- adj(u)) {\n val newDist = distU + d\n if (newDist < dists(v)) {\n \tdists(v) = newDist\n pq.enqueue(Edge(v, newDist))\n }\n if (u > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m, k) = readInts(3)\n val roads = mutable.Map.empty[(Int, Int), Int].withDefaultValue(Int.MaxValue)\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < roads(u, v)) {\n roads.put((u, v), x)\n roads.put((v, u), x)\n }\n }\n\n var removed = 0\n\n val rails = Array.fill(n) { -1 }\n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1) rails(s) = y\n else if (y < rails(s)) {\n rails(s) = y\n removed += 1\n } else removed += 1\n }\n\n val adjB = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val adjRoadB = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n\n for (((u, v), x) <- roads) {\n adjB(u) += v\n adjRoadB(u) += x\n }\n\n val adj = adjB.map(_.result)\n val adjRoad = adjRoadB.map(_.result)\n \n val dist = Array.fill(n) { Long.MaxValue }\n dist(0) = 0\n\n val heap = Array.ofDim[Long](n)\n var heapSize = 0\n val idPos = Array.ofDim[Int](n)\n val posId = Array.ofDim[Int](n)\n\n @inline def swap[T](as: Array[T], u: Int, v: Int): Unit = {\n val tmp = as(u)\n as(u) = as(v)\n as(v) = tmp\n }\n\n @inline def swapHeap(u: Int, v: Int): Unit = {\n swap(heap, u, v)\n swap(posId, u, v)\n swap(idPos, u, v)\n }\n\n def bubbleDown(pos0: Int): Unit = {\n var pos = pos0\n while (pos < (heapSize >> 1)) {\n var child = 2 * pos + 1\n if (child + 1 < heapSize && heap(child + 1) < heap(child)) {\n child += 1\n }\n if (heap(pos) <= heap(child)) pos = heapSize + 1\n else {\n swapHeap(pos, child)\n pos = child\n }\n }\n }\n\n def bubbleUp(pos0: Int): Unit = {\n var pos = pos0\n while (pos > 0) {\n val parent = (pos - 1) >> 1\n if (heap(pos) >= heap(parent)) pos = -1\n else {\n swapHeap(pos, parent)\n pos = parent\n }\n }\n }\n\n def extractMin(): Int = {\n val res = posId(0)\n heapSize -= 1\n val lastNode = heap(heapSize)\n if (heapSize > 0) {\n heap(0) = lastNode\n val id = posId(heapSize)\n idPos(id) = 0\n posId(0) = id\n bubbleDown(0)\n }\n res\n }\n \n def decKey(id: Int, key: Long): Unit = {\n val pos = idPos(id)\n heap(pos) = key\n bubbleUp(pos)\n }\n\n def add(id: Int, key: Long): Unit = {\n heap(heapSize) = key\n idPos(id) = heapSize\n posId(heapSize) = id\n bubbleUp(heapSize)\n heapSize += 1\n }\n\n add(0, 0)\n \n while (heapSize > 0) {\n val u = extractMin()\n if (dist(u) <= rails(u)) removed += 1\n else if (rails(u) >= 0) dist(u) = rails(u)\n for (i <- adj(u).indices) {\n val v = adj(u)(i)\n val newDist = dist(u) + adjRoad(u)(i)\n if (newDist < dist(v)) {\n if (dist(v) == Long.MaxValue) add(v, newDist)\n else decKey(v, newDist)\n dist(v) = newDist\n }\n }\n }\n\n println(removed)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val adj = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < adj(u).getOrElse(v, Int.MaxValue)) {\n adj(u).put(v, x)\n adj(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) >= 0 && rails(i) < adj(0).getOrElse(i, Int.MaxValue)) {\n adj(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dists = Array.fill(n) { Long.MaxValue }\n dists(0) = 0L\n \n case class Edge(v: Int, dist: Long) extends Comparable[Edge] {\n def compareTo(other: Edge) = this.dist.compare(other.dist)\n }\n\n val pq = mutable.PriorityQueue.empty[Edge]\n pq.enqueue(Edge(0, 0L))\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val Edge(u, distU) = pq.dequeue()\n if (!visited(u)) {\n visited += u\n for ((v, d) <- adj(u)) {\n val newDist = distU + d\n if (newDist < dists(v)) {\n \tdists(v) = newDist\n pq.enqueue(Edge(v, newDist))\n }\n if (u > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val roads = mutable.Map.empty[(Int, Int), Int]\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < roads.getOrElse((u, v), Int.MaxValue)) {\n roads.put((u, v), x)\n roads.put((v, u), x)\n }\n }\n\n var removed = 0\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1) rails(s) = y\n else if (y < rails(s)) {\n rails(s) = y\n removed += 1\n } else removed += 1\n }\n\n for (i <- 1 until n) {\n if (rails(i) > 0 && rails(i) < roads.getOrElse((0, i), Int.MaxValue)) {\n roads.put((0, i), rails(i))\n removed -= 1\n }\n }\n\n val adjB = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n val adjRoadB = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n\n for (((u, v), x) <- roads) {\n adjB(u) += v\n adjRoadB(u) += x\n }\n\n val adj = adjB.map(_.result)\n val adjRoad = adjRoadB.map(_.result)\n\n val dist = Array.fill(n) { Long.MaxValue }\n dist(0) = 0\n\n //val pq = mutable.PriorityQueue(0)(Ordering.by(dist))\n val pq = new java.util.PriorityQueue(1, Ordering.by(dist))\n pq.add(0)\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val u = pq.poll()\n if (!visited(u)) {\n visited += u\n if (dist(u) <= rails(u)) removed += 1\n else if (rails(u) >= 0) dist(u) = rails(u)\n for (i <- adj(u).indices) {\n val v = adj(u)(i)\n val newDist = dist(u) + adjRoad(u)(i)\n if (newDist < dist(v)) {\n \tdist(v) = newDist\n pq.add(v)\n }\n }\n }\n }\n\n println(removed)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val roads = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < roads(u).getOrElse(v, Int.MaxValue)) {\n roads(u).put(v, x)\n roads(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) > 0 && rails(i) < roads(0).getOrElse(i, Int.MaxValue)) {\n roads(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dist = Array.fill(n) { Long.MaxValue }\n dist(0) = 0\n\n //val pq = mutable.PriorityQueue(0)(Ordering.by(dist))\n val pq = new java.util.PriorityQueue(1, Ordering.by(dist))\n pq.add(0)\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val u = pq.poll()\n if (!visited(u)) {\n visited += u\n for ((v, d) <- roads(u)) {\n val newDist = dist(u) + d\n if (newDist < dist(v)) {\n \tdist(v) = newDist\n pq.add(v)\n if (u > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val roads = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < roads(u).getOrElse(v, Int.MaxValue)) {\n roads(u).put(v, x)\n roads(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) > 0 && rails(i) < roads(0).getOrElse(i, Int.MaxValue)) {\n roads(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dist = Array.fill(n) { Long.MaxValue }\n val steps = Array.fill(n) { 0 }\n dist(0) = 0\n\n //val pq = mutable.PriorityQueue(0)(Ordering.by(dist))\n val pq = new java.util.PriorityQueue(1, Ordering.by(dist))\n pq.add(0)\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val u = pq.poll()\n if (!visited(u)) {\n visited += u\n if (dist(u) <= rails(u) && steps(u) > 1) rails(u) = -1\n for ((v, d) <- roads(u)) {\n val newDist = dist(u) + d\n if (newDist < dist(v)) {\n steps(v) = steps(u) + 1\n \tdist(v) = newDist\n pq.add(v)\n }\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val roads = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < roads(u).getOrElse(v, Int.MaxValue)) {\n roads(u).put(v, x)\n roads(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) >= 0 && rails(i) < roads(0).getOrElse(i, Int.MaxValue)) {\n roads(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dist = Array.fill(n) { Long.MaxValue }\n dist(0) = 0\n\n //val pq = mutable.PriorityQueue(0)(Ordering.by(dist))\n val pq = new java.util.PriorityQueue(1, Ordering.by(dist))\n pq.add(0)\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val u = pq.poll()\n if (!visited(u)) {\n visited += u\n for ((v, d) <- roads(u)) {\n val newDist = dist(u) + d\n if (newDist < dist(v)) {\n \tdist(v) = newDist\n pq.add(v)\n }\n if (u > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val roads = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < roads(u).getOrElse(v, Int.MaxValue)) {\n roads(u).put(v, x)\n roads(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) > 0 && rails(i) < roads(0).getOrElse(i, Int.MaxValue)) {\n roads(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dist = Array.fill(n) { Long.MaxValue }\n dist(0) = 0\n\n //val pq = mutable.PriorityQueue(0)(Ordering.by(dist))\n val pq = new java.util.PriorityQueue(1, Ordering.by(dist))\n pq.add(0)\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val u = pq.poll()\n if (!visited(u)) {\n visited += u\n for ((v, d) <- roads(u)) {\n val newDist = dist(u) + d\n if (newDist < dist(v)) {\n \tdist(v) = newDist\n pq.add(v)\n }\n if (u > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val roads = Array.fill(n){ mutable.Map.empty[Int, Int] }\n\n for (i <- 0 until m) {\n val tl = tokenizeLine\n val _u, _v, x = tl.nextToken.toInt\n val u = _u - 1\n val v = _v - 1\n if (x < roads(u).getOrElse(v, Int.MaxValue)) {\n roads(u).put(v, x)\n roads(v).put(u, x)\n }\n }\n\n val rails = Array.fill(n) { -1 }\n \n for (i <- 0 until k) {\n val tl = tokenizeLine\n val _s, y = tl.nextToken.toInt\n val s = _s - 1\n if (rails(s) == -1 || y < rails(s)) rails(s) = y\n }\n\n for (i <- 1 until n) {\n if (rails(i) >= 0 && rails(i) < roads(0).getOrElse(i, Int.MaxValue)) {\n roads(0).put(i, rails(i))\n } else rails(i) = -1\n }\n\n val dists = Array.fill(n) { Long.MaxValue }\n dists(0) = 0\n\n val pq = mutable.PriorityQueue((0, 0L))(Ordering.by(_._2))\n //val pq = new java.util.PriorityQueue[(Int, Long)](1, Ordering.by(_._2))\n //pq.add((0, 0))\n val visited = new mutable.BitSet(n)\n\n while (!pq.isEmpty) {\n val (u, distU) = pq.dequeue()\n if (!visited(u)) {\n visited += u\n for ((v, d) <- roads(u)) {\n val newDist = distU + d\n if (newDist < dists(v)) {\n \tdists(v) = newDist\n pq.enqueue((v, newDist))\n }\n if (u > 0 && newDist <= rails(v)) rails(v) = -1\n }\n }\n }\n\n println(k - rails.count(_ != -1))\n}"}], "src_uid": "03d6b61be6ca0ac9dd8259458f41da59"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N, K = ni()\n val q = N / K\n val m = N % K\n REP(K) { i =>\n val cnt = if (i < m) q + 1 else q\n REP(cnt){_ => out.print((i + 'a').toChar) }\n }\n out.println()\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object _1092A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val input = io.read[Seq[(Int, Int)]]\n val ans = input map {case (n, k) =>\n val res = for {\n i <- 0 until k\n j <- 1 to (n/k)\n } yield ('a' + i).toChar\n res.padTo(n, res.last).mkString\n }\n io.writeAll(ans, separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Main {\n\n def main(args: Array[String]) {\n\n val std = scala.io.StdIn\n val t = std.readLine().toInt\n\n for (_ <- 0 until t) {\n val values = std.readLine().split(\" \").map(_.toInt)\n val n = values(0)\n val k = values(1)\n val stringBuilder = new StringBuilder(\"\")\n for (i <- 0 until n) {\n stringBuilder.append(('a' + i % k).toChar)\n }\n println(stringBuilder.toString())\n }\n\n }\n}"}, {"source_code": "object CF_527_3_A {\n def solve(xs: Seq[(Int, Int)]): Seq[String] = {\n xs.map{\n case (n, k) =>\n val str = ('a' to ('a' + k - 1).toChar).mkString\n str * (n/k) + str.take(n%k)\n }\n }\n\n // Specify Input and Output formats here:\n def formatIn(i: Input) = Seq.fill(i.int)((i.int, i.int))\n def formatOut(out: Seq[String]): String = out.mkString(\"\\n\")\n\n// ~~~ Boilerplate & utility methods that don't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n def main(args: Array[String]) = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n\n import java.util.Scanner\n class Input(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine() \n // Remember to call nextLine to advance past the newline character (if required) before collecting the line:\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty else sc.nextLine +: getLines\n def solveVal = (solve _).tupled(formatIn(this))\n def solveStr = formatOut(solveVal)\n }\n\n def ceil(a: Int, b: Int) = (a - 1) / b + 1\n def ceil(a: Long, b: Long) = (a - 1) / b + 1\n val modulo = 1000000007\n\n import language.implicitConversions\n implicit def stringToInput(s: String): Input = new Input(s)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { def tupled: T => R = x => f(x) }\n}\n"}], "negative_code": [{"source_code": "object CF_527_3_A {\n def solve(xs: Seq[(Int, Int)]): Seq[String] = {\n xs.map{\n case (n, k) =>\n println(s\"$n $k\")\n val str = ('a' to ('a' + k - 1).toChar).mkString\n str * (n/k) + str.take(n%k)\n }\n }\n\n // Specify Input and Output formats here:\n def formatIn(i: Input) = Seq.fill(i.int)((i.int, i.int))\n def formatOut(out: Seq[String]): String = out.mkString(\"\\n\")\n\n// ~~~ Boilerplate & utility methods that don't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n def main(args: Array[String]) = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n\n import java.util.Scanner\n class Input(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine() \n // Remember to call nextLine to advance past the newline character (if required) before collecting the line:\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty else sc.nextLine +: getLines\n def solveVal = (solve _).tupled(formatIn(this))\n def solveStr = formatOut(solveVal)\n }\n\n def ceil(a: Int, b: Int) = (a - 1) / b + 1\n def ceil(a: Long, b: Long) = (a - 1) / b + 1\n val modulo = 1000000007\n\n import language.implicitConversions\n implicit def stringToInput(s: String): Input = new Input(s)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { def tupled: T => R = x => f(x) }\n}"}], "src_uid": "fa253aabcccd487d09142ea882abbc1b"} {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n\n val Array(_n, l, _k) = readLongs(3)\n val n = _n.toInt\n val k = if (l % _n == 0) (_k min (l / _n)).toInt else (_k min (l / _n + 1)).toInt\n val remainder = (l % n).toInt\n val MOD = 1000000007L\n\n val dp1 = Array.ofDim[Int](k + 1, n + 1)\n\n val _as = readInts(n).zipWithIndex.sorted\n //val _as = Array.fill(n){ Random.nextInt }.zipWithIndex.sorted\n val as = Array.ofDim[(Int, Int)](n)\n\n as(0) = (1, _as(0)._2)\n for (i <- 1 until n) {\n as(i) = (if (_as(i)._1 == _as(i - 1)._1) as(i - 1)._1 else as(i - 1)._1 + 1, _as(i)._2)\n }\n\n for (i <- as.indices) dp1(1)(as(i)._1) += 1\n\n var res = l % MOD\n\n for (i <- 2 to k) {\n var prev = 0\n var acc = 0\n for (j <- 0 until n) {\n val (a, aInd) = as(j)\n if (a != prev) acc = ((acc + dp1(i - 1)(a)) % MOD).toInt\n val d1 = if (i <= l / n) acc else 0\n dp1(i)(a) = (dp1(i)(a) + d1) % MOD.toInt\n val d2 = if (aInd < remainder) acc else 0\n res = ((res + d1 * (l / n % MOD + MOD - i + 1) % MOD) + d2) % MOD\n prev = a\n }\n }\n\n println(res % MOD)\n}\n", "positive_code": [{"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n\n val Array(_n, l, _k) = readLongs(3)\n val n = _n.toInt\n val k = if (l % _n == 0) (_k min (l / _n)).toInt else (_k min (l / _n + 1)).toInt\n val remainder = (l % n).toInt\n val MOD = 1000000007L\n\n val dp1 = Array.ofDim[Int](k + 1, n + 1)\n\n val _as = readInts(n).zipWithIndex.sorted\n val as = Array.ofDim[(Int, Int)](n)\n\n as(0) = (1, _as(0)._2)\n for (i <- 1 until n) {\n as(i) = (if (_as(i)._1 == _as(i - 1)._1) as(i - 1)._1 else as(i - 1)._1 + 1, _as(i)._2)\n }\n\n for (i <- as.indices) dp1(1)(as(i)._1) += 1\n\n var res = l % MOD\n\n for (i <- 2 to k) {\n var prev = 0\n var acc = 0\n for (j <- 0 until n) {\n val (a, aInd) = as(j)\n if (a != prev) acc = ((acc + dp1(i - 1)(a)) % MOD).toInt\n val d1 = if (i <= l / n) acc else 0\n dp1(i)(a) = (dp1(i)(a) + d1) % MOD.toInt\n val d2 = if (aInd < remainder) acc else 0\n res = ((res + d1 * (l / n % MOD + MOD - i + 1) % MOD) + d2) % MOD\n prev = a\n }\n }\n\n println(res % MOD)\n}\n"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(_n, l, _k) = readLongs(3)\n val n = _n.toInt\n val k = if (l % _n == 0) (_k min (l / _n)).toInt else (_k min (l / _n + 1)).toInt \n val MOD = 1000000007L\n\n val _as = readInts(n).zipWithIndex.sorted\n val as = Array.ofDim[(Int, Int)](n)\n\n as(0) = (1, _as(0)._2)\n for (i <- 1 until n) {\n as(i) = (if (_as(i)._1 == _as(i - 1)._1) as(i - 1)._1 else as(i - 1)._1 + 1, _as(i)._2)\n }\n\n val cnts = Array.fill(n + 1) { 0 }\n for (a <- as) cnts(a._1) += 1\n\n val MODB = BigInt(MOD)\n val fs, fs2, fInvs = Array.ofDim[Long](k + 1)\n\n var f1 = 1L\n fInvs(0) = 1\n for (i <- 1 until fs.length) { // precompute factorials\n fInvs(i) = BigInt(f1).modInverse(MODB).toLong\n f1 = f1 * (i + 1) % MOD\n }\n\n val base = l / _n\n var f2 = base\n fs(0) = 1\n for (i <- 1 until fs.length) { // precompute factorials\n fs(i) = f2\n f2 = f2 * (base - i) % MOD\n }\n\n val base2 = l / _n + 1\n var f3 = base2\n fs2(0) = 1\n for (i <- 1 until fs.length) { // precompute factorials\n fs2(i) = f3\n f3 = f3 * (base2 - i) % MOD\n }\n\n def pascal(_k: Int): Long = {\n fs(_k) * fInvs(_k) % MOD\n }\n\n def pascal2(_k: Int): Long = {\n fs2(_k) * fInvs(_k) % MOD\n }\n\n val dp = Array.fill(k + 1, n + 1) { 0L }\n\n for (j <- dp(1).indices) dp(1)(j) = 1\n //println(pascal(1), pascal(2))\n var res = l % MOD\n\n for (i <- 2 to k) {\n var prev = 1\n for (j <- 0 until n) {\n val (a, aInd) = as(j)\n dp(i)(a) = (dp(i - 1)(a) * cnts(a) + (if (a > prev) dp(i)(a - 1) else 0)) % MOD\n val p = if (aInd < l % n) pascal2(i) else pascal(i)\n res = (res + dp(i)(a) * p) % MOD\n prev = a\n }\n }\n\n println(res % MOD)\n}\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(_n, l, _k) = readLongs(3)\n val n = _n.toInt\n val k = if (l % _n == 0) (_k min (l / _n)).toInt else (_k min (l / _n + 1)).toInt \n val MOD = 1000000007L\n\n val _as = readInts(n).zipWithIndex.sorted\n val as = Array.ofDim[(Int, Int)](n)\n\n as(0) = (1, _as(0)._2)\n for (i <- 1 until n) {\n as(i) = (if (_as(i)._1 == _as(i - 1)._1) as(i - 1)._1 else as(i - 1)._1 + 1, _as(i)._2)\n }\n\n val cnts = Array.fill(n + 1) { 0 }\n for (a <- as) cnts(a._1) += 1\n\n val MODB = BigInt(MOD)\n val fs, fs2, fInvs = Array.ofDim[Long](k + 1)\n\n var f1 = 1L\n fInvs(0) = 1\n for (i <- 1 until fs.length) { // precompute factorials\n fInvs(i) = BigInt(f1).modInverse(MODB).toLong\n f1 = f1 * (i + 1) % MOD\n }\n\n val base = l / _n\n var f2 = base\n fs(0) = 1\n for (i <- 1 until fs.length) { // precompute factorials\n fs(i) = f2\n f2 = f2 * (base - i) % MOD\n }\n\n val base2 = l / _n + 1\n var f3 = base2\n fs2(0) = 1\n for (i <- 1 until fs.length) { // precompute factorials\n fs2(i) = f3\n f3 = f3 * (base2 - i) % MOD\n }\n\n def pascal(_k: Int): Long = {\n fs(_k) * fInvs(_k) % MOD\n }\n\n def pascal2(_k: Int): Long = {\n fs2(_k) * fInvs(_k) % MOD\n }\n\n val dp = Array.fill(k + 1, n + 1) { 0L }\n\n for (j <- dp(1).indices) dp(1)(j) = 1\n //println(pascal(1), pascal(2))\n var res = l\n\n for (i <- 2 to k) {\n var prev = 1\n for (j <- 0 until n) {\n val (a, aInd) = as(j)\n dp(i)(a) = (dp(i - 1)(a) * cnts(a) + (if (a > prev) dp(i)(a - 1) else 0)) % MOD\n val p = if (aInd < l % n) pascal2(i) else pascal(i)\n res = (res + dp(i)(a) * p) % MOD\n prev = a\n }\n }\n\n println(res)\n}\n"}], "src_uid": "917fb578760e11155227921a7347e58b"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n if (a.sum % n == 0) println(n)\n else println(n - 1)\n }\n}", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val sum = in.next().split(' ').map(_.toInt).sum\n if (sum % n == 0)\n println(n)\n else\n println(n - 1)\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Test extends App {\n val sc = new Scanner(System.in);\n val n = sc.nextInt()\n val sum = (0 until n).map(_ => sc.nextInt()).sum\n println(if (sum % n == 0) n else n-1)\n}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable._\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n val a = Array.tabulate(n)(_ => sc.nextInt())\n\n val sum = a.fold(0)(_ + _)\n\n println(if (sum % n == 0) n else n-1)\n \n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P246B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n val S = List.fill(N)(sc.nextInt).sum\n if (((S % N) + N) % N == 0) N\n else N - 1\n }\n out.println(solve)\n out.close\n}\n \n\n\n\n\n\n"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P246B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N = sc.nextInt\n val S = List.fill(N)(sc.nextInt).sum\n\n if (S % 2 == 0) N\n else N - 1\n }\n out.println(solve)\n out.close\n}\n \n\n\n\n\n\n"}], "src_uid": "71cead8cf45126902c518c9ce6e5e186"} {"source_code": "import scala.io.StdIn._\r\n\r\nobject A extends App {\r\n for (_ <- 0 until readInt) {\r\n def equalize(d: Array[Int]): (Int, List[(Int, Int)]) = {\r\n @annotation.tailrec\r\n def loop(count: Int, res: List[(Int, Int)]): (Int, List[(Int, Int)]) = {\r\n if(d.forall(_ == 0))\r\n (count, res)\r\n else {\r\n val i = d.indexWhere(_ > 0)\r\n val j = d.indexWhere(_ < 0)\r\n d(i) = d(i) - 1\r\n d(j) = d(j) + 1\r\n loop(count + 1, (i, j) :: res)\r\n }\r\n }\r\n loop(0, Nil)\r\n }\r\n val n = readInt\r\n val a = readLine.split(\" \").map(_.toInt)\r\n val b = readLine.split(\" \").map(_.toInt)\r\n val diff = (0 until n).map(i => a(i) - b(i)).toArray\r\n if (diff.sum == 0) {\r\n val (count, res) = equalize(diff)\r\n println(count)\r\n res.foreach{case (i, j) => println(s\"${i+1} ${j+1}\")}\r\n } else\r\n println(-1)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n val bn = readLine().split(\" \").map(_.toInt)\r\n\r\n val (pos, neg) = (an zip bn).zipWithIndex.foldLeft((List.empty[Int], List.empty[Int])) {\r\n case ((pos, neg), ((ai, bi), i)) if ai > bi => (List.fill(ai - bi)(i) ::: pos, neg)\r\n case ((pos, neg), ((ai, bi), i)) if ai < bi => (pos, List.fill(bi - ai)(i) ::: neg)\r\n case (state, _) => state\r\n }\r\n\r\n if (pos.length == neg.length) {\r\n println(pos.length)\r\n (pos zip neg).foreach { case (pi, ni) => println(s\"${pi + 1} ${ni + 1}\") }\r\n } else println(\"-1\")\r\n\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "accfbd68b9723abf4cd29846e80835ec"} {"source_code": "/**\n * Created by Mikhail on 04.01.2015.\n */\n\nobject _491A {\n def main(args: Array[String]) {\n var a = readInt()\n var b = readInt()\n var s = new StringBuilder()\n var i = 1\n while (i < a + 1) {\n s ++= (i + \" \")\n i += 1\n }\n i = a + b + 1\n while (i > a) {\n s ++= (i + \" \")\n i -= 1\n }\n println(s)\n }\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Main {\n\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val a = scanner.nextInt()\n val b = scanner.nextInt()\n\n val n = a + b + 1\n val result = ((b + 1) to n) ++ (1 to b).reverse\n println(result.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "object UpTheHill491A extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n solve(System.in,System.out)\n def solve(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val a = scanner.nextInt()\n val b = scanner.nextInt()\n val n = a+b+1\n val up = (n-a) to n\n val down = (n-a-1) to 1 by -1\n val hill = (up ++ down).mkString(\" \")\n out.println(hill)\n }\n}"}], "negative_code": [], "src_uid": "add2285f3f710eb41185d6a83e44b37a"} {"source_code": "import java.io.BufferedReader\r\nimport java.io.ByteArrayInputStream\r\nimport java.io.InputStreamReader\r\nimport scala.collection.mutable.ArrayBuffer\r\n \r\nobject FBridgeClub {\r\n def main(args: Array[String]): Unit = {\r\n val file = new BufferedReader(new InputStreamReader(System.in))\r\n// val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(\r\n// \"3 2\\n1 9 1 5 7 8 1 1\".getBytes)))\r\n \r\n var t = file.readLine.toInt\r\n while (t > 0) {\r\n t = t - 1\r\n val Array(n,s) = file.readLine.split(\" \").map(_.toLong)\r\n println(s / (n*n))\r\n }\r\n }\r\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(var a: Int, var b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return (a).compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mapp = mutable.Map[pair, Int]()\n\n val t = readInt()\n\n for (tt <- 1 to t) {\n var n = readLong()\n val s = readLong()\n n = n * n\n val ans = (s / n).toLong\n writer.println(ans)\n\n\n def check(kk: Long, fi: Long): Boolean = {\n return false\n }\n def bs(st:Long, en:Long, fi:Long): Long = {\n if (en - st <= 1L) {\n if (check(st, fi))\n return st\n else\n return en\n }\n val mid = (st + en) / 2L\n if (check(mid, fi))\n return bs(st, mid, fi)\n else\n return bs(mid, en, fi)\n }\n }\n writer.flush()\n}"}], "negative_code": [{"source_code": "import java.io.BufferedReader\r\nimport java.io.ByteArrayInputStream\r\nimport java.io.InputStreamReader\r\nimport scala.collection.mutable.ArrayBuffer\r\n \r\nobject FBridgeClub {\r\n def main(args: Array[String]): Unit = {\r\n val file = new BufferedReader(new InputStreamReader(System.in))\r\n// val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(\r\n// \"3 2\\n1 9 1 5 7 8 1 1\".getBytes)))\r\n \r\n var t = file.readLine.toInt\r\n while (t > 0) {\r\n t = t - 1\r\n val Array(n,s) = file.readLine.split(\" \").map(_.toLong)\r\n println(s / n*n)\r\n }\r\n }\r\n}"}], "src_uid": "7226a7d2700ee52f52d417f404c42ab7"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val n = nl()\n val a, b = ni()\n if (2 * a <= b) {\n out.println(n * a)\n } else {\n if (n % 2 == 0) {\n out.println(n / 2 * b)\n } else {\n out.println(n / 2 * b + a)\n }\n }\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object CF_540_3_A {\n// date: 19/02/2019\n\n type In = (Int, Seq[String])\n type Out = String\n \n def solve(in: In): Out = {\n val (q, xs) = in\n val results = xs map {s =>\n val Seq(n, a, b) = (s: Input).collect(_.toLong)\n val c1 = a * n\n val c2 = (n/2) * b + (n%2)*a\n c1 min c2\n }\n results.mkString(\"\\n\")\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, {i.nextLine; i.getLines})\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n // `a` MUST be > 0. Incorrect otherwise.\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}], "negative_code": [], "src_uid": "beab56c5f7d2996d447320a62b0963c2"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val dp = Array.ofDim[Long](N + 1)\n dp(0) = 1\n\n rep(N) { i =>\n val ds = divisors(A(i), i + 1)\n rep_r(ds.length){ i =>\n val d = ds(i)\n dp(d) += dp(d - 1)\n if (dp(d) >= MOD) dp(d) -= MOD\n }\n }\n\n var ans = 0L\n rep(N, 1) { i =>\n ans += dp(i)\n if (ans >= MOD) ans -= MOD\n }\n out.println(ans)\n }\n\n def divisors(x: Int, mx: Int): Array[Int] = {\n val pre = ArrayBuffer[Int]()\n val post = ArrayBuffer[Int]()\n rep(math.sqrt(x).toInt, 1) { d =>\n if (x % d == 0) {\n if (d <= mx) pre += d\n if (d * d != x && x / d <= mx) post += x / d\n }\n }\n\n val res = Array.ofDim[Int](pre.length + post.length)\n rep(pre.length)(i => res(i) = pre(i))\n val preLen = pre.length\n rep_r(post.length)(i => res(i + preLen) = post(i))\n res\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n\n val MAX = 1e6.toInt\n val divisors = Array.fill[ArrayBuffer[Int]](1e6.toInt + 1)(ArrayBuffer())\n val hasA = Array.ofDim[Boolean](MAX + 1)\n rep(N) { i =>\n hasA(A(i)) = true\n }\n\n rep_r(MAX, 1) { d =>\n var j = d\n while(j <= MAX) {\n if (hasA(j)) {\n divisors(j) += d\n }\n j += d\n }\n }\n\n val table = Array.ofDim[Long](N + 1)\n table(0) = 1\n rep(N) { i =>\n val ds = divisors(A(i))\n rep(ds.length) { j =>\n val d = ds(j)\n if (d <= i + 1) {\n table(d) += table(d - 1)\n if (table(d) >= MOD) table(d) -= MOD\n }\n }\n }\n var ans = 0L\n rep(N) { i =>\n ans += table(i + 1)\n if (ans >= MOD) ans -= MOD\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val table = Array.ofDim[Long](N + 1)\n table(0) = 1\n rep(N) { i =>\n val ds = dividers(A(i))\n Sorting.quickSort(ds)\n rep_r(ds.length) { j =>\n val d = ds(j)\n if (d <= N) {\n table(d) += table(d - 1)\n if (table(d) >= MOD) table(d) -= MOD\n }\n }\n }\n var ans = 0L\n rep(N) { i =>\n ans += table(i + 1)\n }\n\n out.println(ans)\n }\n\n def dividers(x: Int): Array[Int] = {\n if (x == 1) Array(1)\n else {\n val fs_map = factorize(x)\n val fs = fs_map.toArray\n val len = fs.length\n val digits = Array.ofDim[Int](len)\n val res = Array.ofDim[Int](fs_map.map(_._2 + 1).product)\n var p = 0\n\n def next(): Boolean = {\n var k = 0\n digits(0) += 1\n while (k < len - 1) {\n if (digits(k) > fs(k)._2) {\n digits(k) = 0\n digits(k + 1) += 1\n k += 1\n } else {\n return true\n }\n }\n digits(len - 1) <= fs(len - 1)._2\n }\n\n def mkVal: Int = {\n var res = 1\n rep(len) { i =>\n rep(digits(i)) { _ =>\n res *= fs(i)._1\n }\n }\n res\n }\n\n res(0) = 1\n p += 1\n while (next()) {\n res(p) = mkVal\n p += 1\n }\n\n res\n }\n }\n\n def factorize(n: Int): mutable.Map[Int, Int] = {\n import scala.collection.mutable\n val res = mutable.Map[Int, Int]() withDefaultValue 0\n\n def minFactor(n0: Int, rt: Int, i: Int): Int = {\n if (i > rt) n0 // √n まで見つからなかったら n0は素数か1\n else if (n0 % i == 0) i\n else minFactor(n0, rt, i + 1)\n }\n\n def step(n0: Int): Unit = {\n minFactor(n0, math.sqrt(n0).toInt, 2) match {\n case 1 =>\n case f =>\n res(f) = res(f) + 1\n step(n0 / f)\n }\n }\n\n step(n)\n res\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "587ac3b470aaacaa024a0c6dde134b7c"} {"source_code": "import scala.io.StdIn\nimport scala.collection.mutable.Buffer\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = StdIn.readLine()\n val flats: Array[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n val pr = getPriorities(flats)\n val after2Deleting = handlePriorities(pr.toBuffer, 2)\n val after1Deleting = handlePriorities(after2Deleting._2, 1)\n println(after2Deleting._1 + after1Deleting._1)\n }\n\n def getPriorities(flats: Array[Int]): IndexedSeq[Int] = {\n for(i <- flats.indices) yield getPriority(flats, i)\n }\n\n def getPriority(flats: Array[Int], i: Int): Int = {\n flats(i) match {\n case 0 => 0\n case 1 =>\n val tail = flats.length - 1\n val preTail = flats.length - 2\n i match {\n case 0 => {\n if(flats(1) == 0 && flats(2) == 1) 1\n else 0\n }\n case 1 => {\n if(flats.length != 3 && flats(2) == 0 && flats(3) == 1) 1\n else 0\n }\n case `tail` => {\n if(flats(flats.length - 2) == 0 && flats(flats.length - 3) == 1) 1\n else 0\n }\n case `preTail` => {\n if(flats(flats.length - 3) == 0 && flats(flats.length - 4) == 1) 1\n else 0\n }\n case other => {\n val right = (flats(other + 1), flats(other + 2)) match {\n case (0, 1) => 1\n case _ => 0\n }\n val left = (flats(other - 1), flats(other - 2)) match {\n case (0, 1) => 1\n case _ => 0\n }\n right + left\n }\n }\n }\n }\n\n def handlePriorities(priorities: Buffer[Int], num: Int) = {\n var counter: Int = 0\n for(i <- priorities.indices) {\n priorities(i) match {\n case `num` => {\n priorities(i) = 0\n if(i - 2 >= 0) priorities(i - 2) -= 1\n if(i + 2 < priorities.length)priorities(i + 2) -= 1\n counter += 1\n }\n case _ =>\n }\n }\n (counter, priorities)\n }\n}\n", "positive_code": [{"source_code": "object A extends App{\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n\n def solve = {\n val n = nextInt\n var ans = 0\n var stats = (for(i <- 1 to n) yield nextInt).toList\n stats = (0::stats):+0\n var input = stats.toBuffer\n\n for (i <- 1 to n) {\n if(input(i) == 0) {\n if(input(i - 1) == 1 && input(i + 1) == 1) {\n input(i + 1) = 0\n ans += 1\n }\n }\n }\n println(ans)\n }\n\n solve\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val flg = Array.ofDim[Boolean](N)\n var ans = 0\n rep(N - 2, 1) { i =>\n if (A(i - 1) == 1 && A(i + 1) == 1 && A(i) == 0) {\n flg(i) = true\n }\n }\n\n rep(N - 2, 1) { i =>\n if (flg(i)) {\n flg(i) = false\n if (i < N - 2) flg(i + 2) = false\n ans += 1\n }\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject B extends App {\n\tval n = StdIn.readInt\n\tval arr = StdIn.readLine.split(\" \").map(_.toInt)\n\n\tdef f(p: Int, cnt: Int): Int = {\n\t\tif(p >= n)\n\t\t\tcnt\n\n\t\telse {\n\t\t\tif(p + 2 < n && arr(p) == 1 && arr(p + 1) == 0 && arr(p + 2) == 1)\n\t\t\t\tf(p + 3, cnt + 1)\n\n\t\t\telse f(p + 1, cnt)\n\t\t}\n\t}\n\n\tprintln(f(0, 0))\n}"}, {"source_code": "object CF_521_3_B {\n def solve(n: Int, as: Seq[Int]): Int = {\n def turnOff(as: Seq[Int], count: Int, out: Seq[Int]): (Seq[Int], Int) = as match {\n case 1 +: 0 +: 1 +: _ => turnOff(as.updated(2,0).tail, count + 1, out :+ 1)\n case a +: _ +: _ +: _ => turnOff(as.tail, count, out :+ a)\n case Seq(a,b) => (out :+ a :+ b, count)\n }\n val result = turnOff(as, 0, Seq.empty)\n result._2\n }\n\n // `solution` is defined by the input format - and can be called both from main and test script without repeating\n def solution(i: Input) = solve(i.int, {i.nextLine; i.intSeq()})\n\n \n// ~~~ Boilerplate that doesn't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n def main(args: Array[String]) = {\n val out = new java.io.PrintWriter(System.out)\n val sol = solution(new Input(System.in))\n out.println(sol)\n out.close()\n }\n\n// ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n import java.util.Scanner\n class Input(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine() \n // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n }\n\n def ceil(a: Int, b: Int) = (a - 1) / b + 1\n def ceil(a: Long, b: Long) = (a - 1) / b + 1\n\n import language.implicitConversions\n implicit def stringToInput(s: String): Input = new Input(s)\n}"}], "negative_code": [], "src_uid": "ea62b6f68d25fb17aba8932af8377db0"} {"source_code": "object Main {\nimport java.io._\nimport java.util.Scanner\n\nimport collection.mutable.HashMap\nimport scala.collection.{SortedSet, mutable}\nimport scala.util.Random\n protected val EPS = 1e-11\n\n private def default = (\n new StreamTokenizer(new InputStreamReader(System.in)),\n new Scanner(System.in),\n new PrintWriter(System.out)\n )\n\n val (in, ins, out) = {\n try {\n if (sys.props.contains(\"xDx\")) {\n (\n new StreamTokenizer(new FileReader(\"input.txt\")),\n new Scanner(new FileReader(\"input.txt\")),\n new PrintWriter(new FileWriter(\"output.txt\"))\n )\n } else {\n default\n }\n } catch {\n case _: Throwable => default\n }\n }\n\n private def nextInt = {\n in.nextToken\n in.nval.toInt\n }\n\n private def nextLong = {\n in.nextToken\n in.nval.toLong\n }\n\n\n private def nextDouble = {\n in.nextToken\n in.nval\n }\n\n\n private def nextString = {\n in.nextToken\n in.sval\n }\n\n private def nextChar = {\n in.nextToken\n in.ttype.toChar\n }\n\n def main(args: Array[String]): Unit = {\n try {\n new Run().run()\n } catch {\n case e: Throwable =>\n throw new RuntimeException(e)\n } finally out.close()\n }\n\n class Run {\n import collection.breakOut\n def run(): Unit = {\n val n = nextInt\n val a = readArr(n)\n val m = nextInt\n val b = readArr(m)\n if(a(n - 1) != b(m - 1)) {\n println(-1)\n } else {\n var res = 0\n var ai = 0\n var bi = 0\n while(ai < n && bi < m) {\n if(a(ai) == b(bi)) {\n res += 1\n ai += 1\n bi += 1\n } else if(a(ai) < b(bi)) {\n ai += 1\n } else {\n bi += 1\n }\n }\n println(res)\n }\n }\n \n def readArr(n: Int): Array[Long] = {\n val a = Array.ofDim[Long](n)\n var prev = 0L\n for(i <- 0 until n) {\n a(i) = prev + nextInt\n prev = a(i)\n }\n a\n }\n\n }\n\n}\n\n\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = map(N)(_ => nl())\n val M = ni()\n val B = map(M)(_ => nl())\n\n if (A.sum != B.sum) out.println(-1)\n else {\n val cumA = Array.ofDim[Long](N)\n cumA(0) = A(0)\n rep(N - 1) { i =>\n cumA(i + 1) = cumA(i) + A(i + 1)\n }\n val cumB = Array.ofDim[Long](M)\n cumB(0) = B(0)\n rep(M - 1) { i =>\n cumB(i + 1) = cumB(i) + B(i + 1)\n }\n\n var ans = 0\n var a, b = 0\n while (a < N && b < M) {\n if (cumA(a) == cumB(b)) {\n ans += 1\n a += 1\n b += 1\n } else if (cumA(a) > cumB(b)) {\n b += 1\n } else {\n a += 1\n }\n }\n\n out.println(if (ans == 0) -1 else ans)\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val M = ni()\n val B = na(M)\n\n val cumA = Array.ofDim[Long](N)\n cumA(0) = A(0)\n rep(N - 1) { i =>\n cumA(i + 1) = cumA(i) + A(i + 1)\n }\n val cumB = Array.ofDim[Long](M)\n cumB(0) = B(0)\n rep(M - 1) { i =>\n cumB(i + 1) = cumB(i) + B(i + 1)\n }\n\n var ans = 0\n var a, b = 0\n while(a < N && b < M) {\n if (cumA(a) == cumB(b)) {\n ans += 1\n a += 1\n b += 1\n } else if (cumA(a) > cumB(b)) {\n b += 1\n } else {\n a += 1\n }\n }\n\n out.println(if (ans == 0) - 1 else ans)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = map(N)(_ => ni())\n val M = ni()\n val B = map(M)(_ => ni())\n\n if (A.sum != B.sum) out.println(-1)\n else {\n val cumA = Array.ofDim[Long](N)\n cumA(0) = A(0)\n rep(N - 1) { i =>\n cumA(i + 1) = cumA(i) + A(i + 1)\n }\n val cumB = Array.ofDim[Long](M)\n cumB(0) = B(0)\n rep(M - 1) { i =>\n cumB(i + 1) = cumB(i) + B(i + 1)\n }\n\n var ans = 0\n var a, b = 0\n while (a < N && b < M) {\n if (cumA(a) == cumB(b)) {\n ans += 1\n a += 1\n b += 1\n } else if (cumA(a) > cumB(b)) {\n b += 1\n } else {\n a += 1\n }\n }\n\n out.println(if (ans == 0) -1 else ans)\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val M = ni()\n val B = na(M)\n\n if (A.sum != B.sum) out.println(-1)\n else {\n val cumA = Array.ofDim[Long](N)\n cumA(0) = A(0)\n rep(N - 1) { i =>\n cumA(i + 1) = cumA(i) + A(i + 1)\n }\n val cumB = Array.ofDim[Long](M)\n cumB(0) = B(0)\n rep(M - 1) { i =>\n cumB(i + 1) = cumB(i) + B(i + 1)\n }\n\n var ans = 0\n var a, b = 0\n while (a < N && b < M) {\n if (cumA(a) == cumB(b)) {\n ans += 1\n a += 1\n b += 1\n } else if (cumA(a) > cumB(b)) {\n b += 1\n } else {\n a += 1\n }\n }\n\n out.println(if (ans == 0) -1 else ans)\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n}"}], "src_uid": "8c36ab13ca1a4155cf97d0803aba11a3"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map{_ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt)\n (a, b)\n }\n var count = 0\n println((0 until n).count { i =>\n val (a, b) = data(i)\n var up = false\n var down = false\n var left = false\n var right = false\n (0 until n).foreach { j =>\n val (a1, b1) = data(j)\n if (a1 == a && b1 > b)\n up = true\n else if (a1 == a && b1 < b)\n down = true\n else if (b1 == b && a1 < a)\n right = true\n else if (b1 == b && a1 > a)\n left = true\n }\n up && left && down && right\n })\n\n}", "positive_code": [{"source_code": "object A165 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = Array.fill(n)(readInts(2)).map(arr => (arr(0), arr(1)))\n var res = 0\n for(i <- 0 until n) {\n var (right, left, upper, lower) = (false, false, false, false)\n for(j <- 0 until n if i != j) {\n if(in(i)._2 == in(j)._2) {\n if(in(i)._1 > in(j)._1)\n right = true\n else if(in(i)._1 < in(j)._1)\n left = true\n } else if(in(i)._1 == in(j)._1) {\n if(in(i)._2 > in(j)._2)\n upper = true\n else if(in(i)._2 < in(j)._2)\n lower = true\n }\n }\n if(right && left && upper && lower)\n res += 1\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P165A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val a = Array.fill(N, 2)(sc.nextInt)\n\n def isSupercentral(p: Array[Int]): Boolean = {\n @tailrec\n def loop(right: Int, left: Int, lower: Int, upper: Int, i: Int): Boolean =\n if (i == N) right > 0 && left > 0 && lower > 0 && upper > 0\n else {\n val q = a(i)\n if (p(0) == q(0) && p(1) < q(1)) loop(right, left, lower, upper + 1, i + 1)\n else if (p(0) == q(0) && p(1) > q(1)) loop(right, left, lower + 1, upper, i + 1)\n else if (p(1) == q(1) && p(0) < q(0)) loop(right, left + 1, lower, upper, i + 1)\n else if (p(1) == q(1) && p(0) > q(0)) loop(right + 1, left, lower, upper, i + 1)\n else loop(right, left, lower, upper, i + 1)\n }\n loop(0, 0, 0, 0, 0)\n }\n\n val answer = (0 until N).filter((x: Int) => isSupercentral(a(x))).size\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n val n = readInt\n val points = for(_ <- 1 to n) yield readInts\n def ans = points.count {\n case Array(x, y) => (for(i <- 0 until 4) yield {\n val dx = (i & 1) * i - 2 * (i & 1)\n val dy = (1 - i) * (1 - (i & 1))\n points.count {\n case Array(x1, y1) => (x - x1).signum == dx && (y - y1).signum == dy\n }\n }).reduce(_ * _) != 0\n }\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n case class Point(x: Int, y: Int)\n class System {\n val xmap = scala.collection.mutable.Map[Int, List[Point]]()\n val ymap = scala.collection.mutable.Map[Int, List[Point]]()\n \n def read() = {\n val a = readLine().split(\" \").map(_.toInt)\n Point(a(0), a(1))\n }\n \n def add() {\n val p = read\n xmap(p.x) = xmap.getOrElse(p.x, List[Point]()) ::: List(p)\n ymap(p.y) = ymap.getOrElse(p.y, List[Point]()) ::: List(p)\n } \n \n def count = {\n val x = xmap.values.map(_.sortBy(_.y))\n val xs = x.flatMap{ x0 => \n if (x0.size >= 3) {\n x0.slice(1, x0.size - 1)\n } else Nil\n }\n val y = ymap.values.map(_.sortBy(_.x))\n val ys = y.flatMap{ y0 =>\n if (y0.size >= 3) {\n y0.slice(1, y0.size - 1)\n } else Nil\n } \n \n (xs.toSet & ys.toSet).size\n } \n }\n \n def main(args: Array[String]) {\n val n = readInt\n val s = new System()\n for (_ <- 1 to n) { s.add() } \n println(s.count)\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map{_ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt)\n (a, b)\n }\n var count = 0\n println((0 until n).count { i =>\n val (a, b) = data(i)\n var up = false\n var down = false\n var left = false\n var right = false\n (1 until n).foreach { j =>\n val (a1, b1) = data(j)\n if (a1 == a && b1 > b)\n up = true\n else if (a1 == a && b1 < b)\n down = true\n else if (b1 == b && a1 < a)\n right = true\n else if (b1 == b && a1 > a)\n left = true\n }\n up && left && down && right\n })\n\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map{_ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt)\n (a, b)\n }.groupBy(_._1)\n println(data.foldLeft(0) {\n case(acc, (a, b)) if b.size < 3 => acc\n case(acc, (a, b)) => acc + b.size - 2\n })\n\n}"}], "src_uid": "594e64eef7acd055d59f37710edda201"} {"source_code": "\nimport scala.collection.mutable.ListBuffer\n\nobject Main {\n\n def main(args: Array[String]) {\n val n = nextInt\n val lst = for (i <- 1 to n) yield nextInt\n val s = lst.sum\n val lb = new ListBuffer[Int]()\n for ((ai, i) <- lst zip (1 to n) ; if ai * n == s)\n lb += i\n println(lb.length)\n println(lb.mkString(\" \"))\n }\n\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));\n var st = new java.util.StringTokenizer(\"\");\n\n def next() = {\n while (!st.hasMoreTokens())\n st = new java.util.StringTokenizer(in.readLine());\n st.nextToken();\n }\n\n def nextInt() = java.lang.Integer.parseInt(next());\n def nextDouble() = java.lang.Double.parseDouble(next());\n def nextLong() = java.lang.Long.parseLong(next());\n}\n", "positive_code": [{"source_code": "object App extends App {\n Round3.print(Round3.solve(readLine(), readLine()))\n}\n\nobject Round3 {\n def print(r: Result): Unit = {\n println(r.n)\n println(r.indices.mkString(\" \"))\n }\n \n case class Result(n: Int, indices: Array[Int])\n\n def solve(i1: String, i2: String): Result = {\n val nums = i2.split(\" \").map { _.toDouble }\n val length = i1.toDouble\n val ave = nums.sum / length\n val indices = nums.zipWithIndex collect { case (n, i) if n == ave => i+1 }\n Result(indices.length, indices)\n }\n\n}\n"}], "negative_code": [], "src_uid": "1a22bc82ddf6b3dfbf270bc5e3294c28"} {"source_code": "object CaptainMarmot extends App {\n\n import scala.io.StdIn\n\n def readAxis: (Int, Int, Int, Int) = {\n val Array(a, b, c, d) = StdIn.readLine().split(' ').map(_.toInt)\n (a, b, c, d)\n }\n\n val n = StdIn.readLine().toInt\n val moles: Seq[Seq[(Int, Int, Int, Int)]] = (1 to n).map(_ => Seq.fill(4)(readAxis)).toSeq\n\n moles.foreach(xs => println(CaptainMarmot(xs).solve))\n}\n\ncase class CaptainMarmot(moles: Seq[(Int, Int, Int, Int)]) {\n type Coord = (Int, Int)\n\n def solve: Int = {\n val scores = (for {\n (s1, c1) <- rotates(moles(0))\n (s2, c2) <- rotates(moles(1))\n (s3, c3) <- rotates(moles(2))\n (s4, c4) <- rotates(moles(3))\n } yield {\n (s1 + s2 + s3 + s4, isSquare(c1, c2, c3, c4))\n }).filter(_._2).map(_._1)\n if (scores.isEmpty) -1 else scores.min\n }\n\n private[this] def rotates(xs: (Int, Int, Int, Int)): Seq[(Int, Coord)] = {\n val (homeX, homeY, centerX, centerY) = xs\n Seq(\n (0, (homeX, homeY)),\n (1, (centerX - homeY + centerY, centerY + homeX - centerX)),\n (2, (centerX * 2 - homeX, centerY * 2 - homeY)),\n (3, (centerX + homeY - centerY, centerY - homeX + centerX))\n )\n }\n\n private[this] def isSquare(c1: Coord, c2: Coord, c3: Coord, c4: Coord): Boolean = {\n val sets = Set(c1, c2, c3, c4).map{ case (x, y) => (x * 4, y * 4) }\n if (sets.size != 4) {\n false\n } else {\n val (x, y) = sets.head\n val rs = rotates(x, y, c1._1 + c2._1 + c3._1 + c4._1, c1._2 + c2._2 + c3._2 + c4._2).map(_._2)\n rs.toSet == sets\n }\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Coord(x: Int, y: Int) {\n def ccw: Coord = Coord(-y, x)\n def +(o: Coord) = Coord(x + o.x, y + o.y)\n }\n case class Mole(v: Coord, center: Coord) {\n def relative: Coord = Coord(v.x - center.x, v.y - center.y) // 中心からの相対位置\n }\n\n def solve(): Unit = {\n\n def readMole(): Mole = {\n Mole(Coord(ni(), ni()), Coord(ni(), ni()))\n }\n\n def ccw(m: Mole): Seq[(Coord, Int)] = {\n val res = Array.ofDim[(Coord, Int)](4)\n var cur = m.relative\n var i = 0\n while (i < 4) {\n res(i) = (cur + m.center, i)\n cur = cur.ccw\n i += 1\n }\n res\n }\n\n def isSquare(p1: Coord, p2: Coord, p3: Coord, p4: Coord): Boolean = {\n val nums = mutable.Map[Long, Int]().withDefaultValue(0)\n val ps = Array(p1, p2, p3, p4)\n REP(4) { i =>\n i + 1 until 4 foreach { j =>\n val a = ps(i)\n val b = ps(j)\n val x = abs(a.x - b.x)\n val y = abs(a.y - b.y)\n val dist = x.toLong * x + y.toLong * y // 2乗の形を維持する\n nums(dist) = nums(dist) + 1\n }\n }\n\n// val a = nums.toSeq.sortBy(_._1).map(_._2)\n//// System.err.println(nums.toSeq.sortBy(_._1).map(_._2))\n// if (a == Seq(2, 2, 2) || a == Seq(2, 4)) {\n// System.err.println(nums.toSeq.sortBy(_._1).map(_._2))\n// System.err.println(nums)\n// }\n\n nums.size == 2 && nums.toSeq.sortBy(_._1).map(_._2) == Seq(4, 2)\n }\n\n REP(ni()) { _ =>\n val m1, m2, m3, m4 = readMole()\n val ans = for {\n (p1, c1) <- ccw(m1)\n (p2, c2) <- ccw(m2)\n (p3, c3) <- ccw(m3)\n (p4, c4) <- ccw(m4)\n if isSquare(p1, p2,p3, p4)\n } yield c1 + c2 + c3 + c4\n\n if (ans.isEmpty) out.println(-1)\n else out.println(ans.min)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import scala.annotation.tailrec\n\n\nobject CF271_3 extends App {\n case class Mole(x:Long, y:Long, a:Long, b:Long)\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def rotate(x:Long, y:Long, a:Long, b:Long):(Long, Long) = {\n ((a + b - y), (x - a +b))\n }\n\n def rotateMole(mole:Mole, n:Int):(Long,Long) = {\n var vp = (mole.x, mole.y)\n for(i <- 0 until n) {\n vp = rotate(vp._1, vp._2, mole.a, mole.b)\n }\n vp\n }\n\n def distance (p1: (Long, Long), p2: (Long, Long)) = {\n val (p1x, p1y) = p1\n val (p2x, p2y) = p2\n val dx = p1x - p2x\n val dy = p1y - p2y\n Math.sqrt(dx*dx + dy*dy)\n }\n\n def checkSqr(points:Array[(Long, Long)]):Boolean = {\n val Array(x,y,w,z) = points\n val yd = distance(x, y)\n val wd = distance(x, w)\n val zd = distance(x, z)\n if(yd == 0.0 || wd == 0.0 || zd == 0.0) {\n return false\n }\n val (s1, s2, s3) = if(yd == zd) {\n (y,z,w)\n } else if (wd == zd) {\n (w, z, y)\n } else if (yd == wd) {\n (y, w, z)\n } else {\n return false\n }\n if(distance(s2, s3) != distance(s1, s3)) {\n return false\n }\n\n distance(x, s2) == distance(s2, s3) && distance(x, s3) == distance(s1, s2)\n //distance(x, s3) == distance(s1, s2) &&\n }\n\n val Array(n) = readInts(1)\n for(testcase <- 0 until n) {\n val moles = (1 to 4).toArray.map(_ => {\n val Array(x, y, a, b) = readLongs(4)\n val mole = Mole(x, y, a, b)\n mole\n })\n\n var sol = -1\n for(r1 <- 0 to 3; r2 <- 0 to 3; r3 <- 0 to 3; r4 <- 0 to 3) {\n val sum = r1 + r2 + r3 + r4\n if((sol >= 0 && sum < sol) || sol == -1){\n val points = Array(\n rotateMole(moles(0), r1),\n rotateMole(moles(1), r2),\n rotateMole(moles(2), r3),\n rotateMole(moles(3), r4)\n )\n if(checkSqr(points)){\n //println(r1,r2,r3,r4)\n sol = sum\n }\n }\n }\n println(sol)\n }\n\n\n\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Coord(x: Int, y: Int) {\n def ccw: Coord = Coord(-y, x)\n def +(o: Coord) = Coord(x + o.x, y + o.y)\n }\n case class Mole(v: Coord, center: Coord) {\n def relative: Coord = Coord(v.x - center.x, v.y - center.y) // 中心からの相対位置\n }\n\n def solve(): Unit = {\n\n def readMole(): Mole = {\n Mole(Coord(ni(), ni()), Coord(ni(), ni()))\n }\n\n def ccw(m: Mole): Seq[(Coord, Int)] = {\n val res = Array.ofDim[(Coord, Int)](4)\n var cur = m.relative\n var i = 0\n while (i < 4) {\n res(i) = (cur + m.center, i)\n cur = cur.ccw\n i += 1\n }\n res\n }\n\n def isSquare(p1: Coord, p2: Coord, p3: Coord, p4: Coord): Boolean = {\n val nums = mutable.Map[Int, Int]().withDefaultValue(0)\n val ps = Array(p1, p2, p3, p4)\n REP(4) { i =>\n i + 1 until 4 foreach { j =>\n val a = ps(i)\n val b = ps(j)\n val x = abs(a.x - b.x)\n val y = abs(a.y - b.y)\n val dist = x * x + y * y // 2乗の形を維持する\n nums(dist) = nums(dist) + 1\n }\n }\n nums.size == 2 && nums.toSeq.sortBy(_._1).map(_._2) == Seq(4, 2)\n }\n\n REP(ni()) { _ =>\n val m1, m2, m3, m4 = readMole()\n val ans = for {\n (p1, c1) <- ccw(m1)\n (p2, c2) <- ccw(m2)\n (p3, c3) <- ccw(m3)\n (p4, c4) <- ccw(m4)\n if isSquare(p1, p2,p3, p4)\n } yield c1 + c2 + c3 + c4\n\n if (ans.isEmpty) out.println(-1)\n else out.println(ans.min)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Coord(x: Int, y: Int) {\n def ccw: Coord = Coord(-y, x) // todo\n\n def +(o: Coord) = Coord(x + o.x, y + o.y)\n }\n case class Mole(v: Coord, center: Coord) {\n def relative: Coord = Coord(v.x - center.x, v.y - center.y) // 中心からの相対位置\n }\n\n def solve(): Unit = {\n\n def readMole(): Mole = {\n Mole(Coord(ni(), ni()), Coord(ni(), ni()))\n }\n\n def ccw(m: Mole): Seq[(Coord, Int)] = {\n val res = Array.ofDim[(Coord, Int)](4)\n var cur = m.relative\n var i = 0\n while (i < 4) {\n res(i) = (cur + m.center, i)\n cur = cur.ccw\n i += 1\n }\n res\n }\n\n def isSquare(p1: Coord, p2: Coord, p3: Coord, p4: Coord): Boolean = {\n val nums = mutable.Map[Int, Int]().withDefaultValue(0)\n val ps = Array(p1, p2, p3, p4)\n REP(4) { i =>\n i + 1 until 4 foreach { j =>\n val a = ps(i)\n val b = ps(j)\n val x = abs(a.x - b.x)\n val y = abs(a.y - b.y)\n val dist = x * x + y * y // 2乗の形を維持する\n nums(dist) = nums(dist) + 1\n }\n }\n nums.size == 2 && nums.values.toSet == Set(2, 4)\n }\n\n REP(ni()) { _ =>\n val m1, m2, m3, m4 = readMole()\n val ans = for {\n (p1, c1) <- ccw(m1)\n (p2, c2) <- ccw(m2)\n (p3, c3) <- ccw(m3)\n (p4, c4) <- ccw(m4)\n if isSquare(p1, p2,p3, p4)\n } yield c1 + c2 + c3 + c4\n\n if (ans.isEmpty) out.println(-1)\n else out.println(ans.min)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import scala.annotation.tailrec\n\n\nobject CF271_3 extends App {\n case class Mole(x:Long, y:Long, a:Long, b:Long)\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def rotate(x:Long, y:Long, a:Long, b:Long):(Long, Long) = {\n ((a + b - y), (x - a +b))\n }\n\n def rotateMole(mole:Mole, n:Int):(Long,Long) = {\n var vp = (mole.x, mole.y)\n for(i <- 0 until n) {\n vp = rotate(vp._1, vp._2, mole.a, mole.b)\n }\n vp\n }\n\n def distance (p1: (Long, Long), p2: (Long, Long)) = {\n val (p1x, p1y) = p1\n val (p2x, p2y) = p2\n val dx = p1x - p2x\n val dy = p1y - p2y\n Math.sqrt(dx*dx + dy*dy)\n }\n\n def checkSqr(points:Array[(Long, Long)]):Boolean = {\n val Array(x,y,w,z) = points\n val yd = distance(x, y)\n val wd = distance(x, w)\n val zd = distance(x, z)\n if(yd == 0.0 || wd == 0.0 || zd == 0.0) {\n return false\n }\n val (s1, s2, s3) = if(yd == zd) {\n (y,z,w)\n } else if (wd == zd) {\n (w, z, y)\n } else if (yd == wd) {\n (y, w, z)\n } else {\n return false\n }\n if(distance(s2, s3) != distance(s1, s3)) {\n return false\n }\n distance(x, s3) == distance(s1, s2)\n }\n\n val Array(n) = readInts(1)\n for(testcase <- 0 until n) {\n val moles = (1 to 4).toArray.map(_ => {\n val Array(x, y, a, b) = readLongs(4)\n val mole = Mole(x, y, a, b)\n mole\n })\n\n var sol = -1\n for(r1 <- 0 to 3; r2 <- 0 to 3; r3 <- 0 to 3; r4 <- 0 to 3) {\n val sum = r1 + r2 + r3 + r4\n if((sol >= 0 && sum < sol) || sol == -1){\n val points = Array(\n rotateMole(moles(0), r1),\n rotateMole(moles(1), r2),\n rotateMole(moles(2), r3),\n rotateMole(moles(3), r4)\n )\n if(checkSqr(points)){\n sol = sum\n }\n }\n }\n println(sol)\n }\n\n\n\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\n\nobject CF271_3 extends App {\n case class Mole(x:Long, y:Long, a:Long, b:Long)\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def rotate(x:Long, y:Long, a:Long, b:Long):(Long, Long) = {\n ((a + b - y), (x - a +b))\n }\n\n def rotateMole(mole:Mole, n:Int):(Long,Long) = {\n var vp = (mole.x, mole.y)\n for(i <- 0 until n) {\n vp = rotate(vp._1, vp._2, mole.a, mole.b)\n }\n vp\n }\n\n def distance (p1: (Long, Long), p2: (Long, Long)) = {\n val (p1x, p1y) = p1\n val (p2x, p2y) = p2\n val dx = p1x - p2x\n val dy = p1y - p2y\n Math.sqrt(dx*dx + dy*dy)\n }\n\n def checkSqr(points:Array[(Long, Long)]):Boolean = {\n val Array(x,y,w,z) = points\n val yd = distance(x, y)\n val wd = distance(x, w)\n val zd = distance(x, z)\n if(yd == 0.0 || wd == 0.0 || zd == 0.0) {\n return false\n }\n val (s1, s2, s3) = if(yd == zd) {\n (y,z,w)\n } else if (wd == zd) {\n (w, z, y)\n } else if (yd == wd) {\n (y, w, z)\n } else {\n return false\n }\n if(distance(s2, s3) != distance(s1, s3)) {\n return false\n }\n distance(x, s3) == distance(s1, s2)\n }\n\n val Array(n) = readInts(1)\n for(testcase <- 0 until n) {\n val moles = (1 to 4).toArray.map(_ => {\n val Array(x, y, a, b) = readLongs(4)\n val mole = Mole(x, y, a, b)\n mole\n })\n\n var sol = -1\n for(r1 <- 0 to 3; r2 <- 0 to 3; r3 <- 0 to 3; r4 <- 0 to 3) {\n val sum = r1 + r2 + r3 + r4\n if((sol >= 0 && sum < sol) || sol == -1){\n val points = Array(\n rotateMole(moles(0), r1),\n rotateMole(moles(1), r2),\n rotateMole(moles(2), r3),\n rotateMole(moles(3), r4)\n )\n if(checkSqr(points)){\n sol = sum\n }\n }\n }\n println(sol)\n }\n\n\n\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\n\nobject CF271_3 extends App {\n case class Mole(x:Int, y:Int, a:Int, b:Int)\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def rotate(x:Int, y:Int, a:Int, b:Int):(Int, Int) = {\n ((a + b - y), (x - a +b))\n }\n\n def rotateMole(mole:Mole, n:Int):(Int,Int) = {\n var vp = (mole.x, mole.y)\n for(i <- 0 until n) {\n vp = rotate(vp._1, vp._2, mole.a, mole.b)\n }\n vp\n }\n\n def distance (p1: (Int, Int), p2: (Int, Int)) = {\n val (p1x, p1y) = p1\n val (p2x, p2y) = p2\n val dx = p1x - p2x\n val dy = p1y - p2y\n Math.sqrt(dx*dx + dy*dy)\n }\n\n def checkSqr(points:Array[(Int, Int)]):Boolean = {\n val Array(x,y,w,z) = points\n val yd = distance(x, y)\n val wd = distance(x, w)\n val zd = distance(x, z)\n if(yd == 0.0 || wd == 0.0 || zd == 0.0) {\n return false\n }\n val (s1, s2, s3) = if(yd == zd) {\n (y,z,w)\n } else if (wd == zd) {\n (w, z, y)\n } else if (yd == wd) {\n (y, w, z)\n } else {\n return false\n }\n if(distance(s2, s3) != distance(s1, s3)) {\n return false\n }\n distance(x, s3) == distance(s1, s2)\n }\n\n val Array(n) = readInts(1)\n for(testcase <- 0 until n) {\n val moles = (1 to 4).toArray.map(_ => {\n val Array(x, y, a, b) = readInts(4)\n val mole = Mole(x, y, a, b)\n mole\n })\n\n var sol = -1\n for(r1 <- 0 to 3; r2 <- 0 to 3; r3 <- 0 to 3; r4 <- 0 to 3) {\n val sum = r1 + r2 + r3 + r4\n if((sol >= 0 && sum < sol) || sol == -1){\n val points = Array(\n rotateMole(moles(0), r1),\n rotateMole(moles(1), r2),\n rotateMole(moles(2), r3),\n rotateMole(moles(3), r4)\n )\n if(checkSqr(points)){\n sol = sum\n }\n }\n }\n println(sol)\n }\n\n\n\n}\n"}], "src_uid": "41d791867f27a57b50eebaad29754520"} {"source_code": "object A extends App {\n val n = readInt()\n val in = Array.fill(n)(readLine())\n val ls = for (i <- 1 to 12; j <- 1 to 12; if (i*j==12)) yield (j, i)\n for (s <- in) {\n var q = List[(Int,Int)]()\n for (c <- ls) {\n var yes = false;\n for (i <- 0 until c._2) {\n val t = for (j <- 0 until c._1) yield s(i + j*c._2);\n if (!yes) yes = !t.contains('O')\n }\n if (yes) q ::= c\n }\n \n print(q.length)\n for (t <- q) {\n print(\" \" + t._1 + \"x\" + t._2)\n }\n println();\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val res = (1 to n).map { _ =>\n val str = in.next()\n val res = List(1, 2, 3, 4, 6, 12).filter{i =>\n (0 until i).exists{j =>\n (j until 12 by i).forall{k => str(k ) == 'X'}\n }\n }.map(i => s\"${12 / i}x$i\").reverse\n s\"${res.length} ${res.mkString(\" \")}\"\n\n }\n println(res.mkString(\"\\n\"))\n}\n"}, {"source_code": "object A400 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(tests) = readInts(1)\n for (_ <- 0 until tests) {\n val input = scala.io.StdIn.readLine\n val size = input.length\n var res = 0\n var arr = Array[String]()\n for(i <- 1 to size) {\n if(size % i == 0 && solve(input, i)) {\n res += 1\n arr ++= Array(s\"${i}x${size/i}\")\n }\n }\n println(res + arr.mkString(\" \", \" \", \"\"))\n }\n }\n def solve(input: String, rows: Int): Boolean = {\n val col = input.length / rows\n val in = input.toArray.grouped(col).toArray\n (0 until col).exists(c => (0 until rows).forall(r => in(r)(c) == 'X'))\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P400A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n sc.nextLine\n\n // 1x12, 2x6, 3x4, 4x3, 6x2, 12x1\n\n\n class TestCase {\n val cards = sc.nextLine.toList\n\n def solve(): List[String] = {\n\n @inline\n def isWinning(hand: List[Char], rowSize: Int): Boolean = {\n hand.sliding(rowSize, rowSize).toList.\n transpose.find(row => row.forall(_ == 'X')) match {\n case Some(_) => true\n case None => false\n }\n }\n val rowSize = List(12, 6, 4, 3, 2, 1)\n rowSize.filter(isWinning(cards, _)).map { i =>\n (12 / i).toString + \"x\" + i.toString\n }\n }\n }\n\n for (_ <- 0 until N) {\n val answer = (new TestCase).solve\n val line = answer.size :: answer\n out.println(line.mkString(\" \"))\n }\n out.close\n}\n"}, {"source_code": "\n/**\n * Created by hama_du on 2014/02/24.\n */\nobject ProblemA extends App {\n val T = readInt\n (0 until T).foreach(i => {\n println(solve(readLine.toCharArray))\n })\n\n def solve(in: Array[Char]): String = {\n val answers = Array((1,12),(2,6),(3,4),(4,3),(6,2),(12,1)).filter(p => {\n (0 until p._2).foldLeft(false)((a, b) => a || isAllX(p, in, b))\n })\n if (answers.size == 0) {\n return \"0\"\n }\n return answers.size + \" \" + answers.map(p => p._1 + \"x\" + p._2).mkString(\" \")\n }\n\n def isAllX(p: (Int,Int), in: Array[Char], b: Int) = {\n (b until in.size by p._2).filter(idx => in(idx) == 'X').size == p._1\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val res = (1 to n).map { _ =>\n val str = in.next()\n val res = List(1, 2, 3, 4, 6, 12).filter{i =>\n (0 until i).exists{j =>\n (j until 12 by i).forall{k => str(k ) == 'X'}\n }\n }.map(i => s\"${i}x${12 / i}\")\n s\"${res.length} ${res.mkString(\" \")}\"\n\n }\n println(res.mkString(\"\\n\"))\n}\n"}], "src_uid": "b669a42ff477a62ec02dcfb87e1e60bd"} {"source_code": "import scala.Console.in\n\nobject App extends App {\n val cases: Long = Console.in.readLine().toInt\n val data = Vector.range(0, cases).map(_ => {\n in.readLine()\n in.readLine().split(\" \").toVector.map(_.toLong)\n })\n\n def f(arr: Vector[Long]): Long = {\n val zipped = arr.zipWithIndex\n val pMin = zipped.last._2\n\n def max(pos: Int): Int = pos match {\n case pos => if (pos > 0 && arr.apply(pos) <= arr.apply(pos - 1)) pos - 1 else pos\n }\n\n def min(pos: Int): Int = pos match {\n case pos => if (pos > 0 && arr.apply(pos) >= arr.apply(pos - 1)) pos - 1 else pos\n }\n\n val pMax = (zipped foldRight pMin) ((_, pos) => max(pos))\n (zipped foldRight pMax) ((_, pos) => min(pos))\n }\n\n val answer = for (datum <- data) yield f(datum)\n\n answer map(a => print(a.toString ++ \"\\n\"))\n}\n", "positive_code": [{"source_code": "object C extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n val i = an.zipWithIndex.lastIndexWhere {\n case (_, 0) => true\n case (a, i) => a > an(i - 1)\n }\n\n val j = an.zipWithIndex.lastIndexWhere({\n case (_, 0) => true\n case (a, j) => a < an(j - 1)\n }, i)\n\n println(j)\n }\n}\n"}, {"source_code": "import scala.Console.in\n\nobject App extends App {\n val cases: Long = Console.in.readLine().toInt\n val data = Vector.range(0, cases).map(_ => {\n in.readLine()\n in.readLine().split(\" \").toVector.map(_.toLong)\n })\n\n def f(arr: Vector[Long]): Long = {\n val pMin = arr.length - 1\n\n def max(pos: Int): Int = pos match {\n case pos => if (pos > 0 && arr.apply(pos) <= arr.apply(pos - 1)) pos - 1 else pos\n }\n\n def min(pos: Int): Int = pos match {\n case pos => if (pos > 0 && arr.apply(pos) >= arr.apply(pos - 1)) pos - 1 else pos\n }\n\n (arr foldRight (arr foldRight pMin) ((_, pos) => max(pos))) ((_, pos) => min(pos))\n }\n\n val answer = for (datum <- data) yield f(datum)\n\n answer map(a => {\n print(a.toString)\n print(\"\\n\")\n })\n}\n"}, {"source_code": "import scala.Console.in\n\nobject App extends App {\n val cases: Long = Console.in.readLine().toInt\n val data = Vector.range(0, cases).map(_ => {\n in.readLine()\n in.readLine().split(\" \").toVector.map(_.toLong)\n })\n\n def f(arr: Vector[Long]): Long = {\n val pMin = arr.length - 1\n\n def max(pos: Int): Int = pos match {\n case pos => if (pos > 0 && arr.apply(pos) <= arr.apply(pos - 1)) pos - 1 else pos\n }\n\n def min(pos: Int): Int = pos match {\n case pos => if (pos > 0 && arr.apply(pos) >= arr.apply(pos - 1)) pos - 1 else pos\n }\n\n val pMax = (arr foldRight pMin) ((_, pos) => max(pos))\n (arr foldRight pMax) ((_, pos) => min(pos))\n }\n\n val answer = for (datum <- data) yield f(datum)\n\n answer map(a => print(a.toString ++ \"\\n\"))\n}\n"}], "negative_code": [{"source_code": "object C extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n println()\n println(an.mkString(\" \"))\n\n val i = an.zipWithIndex.lastIndexWhere {\n case (_, 0) => true\n case (a, i) => a > an(i - 1)\n }\n\n val j = an.zipWithIndex.lastIndexWhere({\n case (_, 0) => true\n case (a, j) => a < an(j - 1)\n }, i)\n\n println(j)\n }\n}\n"}, {"source_code": "import scala.Console.in\n\nobject App extends App {\n val cases: Long = Console.in.readLine().toInt\n val data = Vector.range(0, cases).map(_ => {\n in.readLine()\n in.readLine().split(\" \").toVector.map(_.toLong)\n })\n\n def f(arr: Vector[Long]): Long = {\n val zipped = arr.zipWithIndex\n val pMin = zipped.last._2\n\n def max(pos: Int): Int = pos match {\n case pos => if (pos > 0 && arr.apply(pos) <= arr.apply(pos - 1)) pos - 1 else pos\n }\n\n def min(pos: Int): Int = pos match {\n case pos => if (pos > 0 && arr.apply(pos) >= arr.apply(pos - 1)) pos - 1 else pos\n }\n\n val pMax = (zipped foldRight pMin) ( (_, pos) => max(pos))\n print(pMax)\n (zipped foldRight pMax) ((_, pos) => min(pos))\n }\n\n val answer = for (datum <- data) yield f(datum)\n\n print(answer)\n}\n"}], "src_uid": "731b45747081a800fc6da02efa5ce8cd"} {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject SortMe {\n def main(args: Array[String]): Unit = {\n val t = StdIn.readInt()\n for (_ <- 1 to t) {\n val _ = StdIn.readInt()\n val nums = StdIn.readLine().trim.split(\" \").map(_.toLong).sorted.toList\n val result = build(nums)\n println(result.mkString(\" \"))\n }\n\n def build(items: List[Long]): List[Long] = {\n @tailrec\n def go(accum: List[Long], xs: List[Long], ys: List[Long]): List[Long] = {\n (xs.headOption, ys.headOption) match {\n case (_, None) => accum\n case (None, Some(y)) => y +: accum\n case (Some(x), Some(y)) => go(x +: y +: accum, xs.tail, ys.tail)\n }\n }\n val (xs, ys) = items.splitAt(items.length / 2)\n go(List.empty[Long], xs, ys.reverse)\n }\n }\n}\n", "positive_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject SortMe {\n def main(args: Array[String]): Unit = {\n val t = StdIn.readInt()\n for (_ <- 1 to t) {\n val _ = StdIn.readInt()\n val nums = StdIn.readLine().trim.split(\" \").map(_.toLong).sorted.toList\n val result = build(nums)\n println(result.mkString(\" \"))\n }\n\n def build(items: List[Long]): List[Long] = {\n @tailrec\n def go(accum: List[Long], xs: List[Long], ys: List[Long]): List[Long] = {\n (xs, ys) match {\n case (_, Nil) => accum\n case (Nil, y :: Nil) => y +: accum\n case (x :: tailx, y :: taily) => go(x +: y +: accum, tailx, taily)\n }\n }\n val (xs, ys) = items.splitAt(items.length / 2)\n go(List.empty[Long], xs, ys.reverse)\n }\n }\n}\n"}, {"source_code": "object B extends App {\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val m = (n - 1) / 2\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n val bn = List(m, m + (n + 1) % 2).distinct.map(an) ::: (0 until m).foldLeft(List.empty[Int])((bn, i) =>\n an(i) :: an(n - i - 1) :: bn\n )\n\n println(bn.mkString(\" \"))\n }\n}\n"}], "negative_code": [{"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n\n val b = an(an.length / 2)\n val bn = an.sortBy(a => (a - b).abs)\n\n println(bn.mkString(\" \"))\n }\n}\n"}, {"source_code": "import scala.io.StdIn\nobject SortMe {\n def main(args: Array[String]): Unit = {\n val t = StdIn.readInt()\n for (_ <- 1 to t) {\n val _ = StdIn.readInt()\n val nums = StdIn.readLine().trim.split(\" \").map(_.toLong)\n val sorted = nums.indices\n .sortBy { index =>\n if (index == nums.length - 1) math.abs(nums(index))\n else math.abs(nums(index+1) - nums(index))\n }\n .map(nums(_))\n\n System.out.println(sorted.mkString(\" \"))\n }\n }\n}\n"}], "src_uid": "3c8bfd3199a9435cfbdee1daaacbd1b3"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject B extends App {\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val primes = listPrimes()\n var initialDivisors: Seq[Int] = {\n val l = in.nextInt\n val r = in.nextInt\n (divisors(l, primes) ::: divisors(r, primes)).distinct\n }\n for (_ <- 2 to n) {\n// println(initialDivisors)\n val l = in.nextInt\n val r = in.nextInt\n initialDivisors = initialDivisors.filter(div => (l % div == 0) || (r % div == 0))\n }\n println(initialDivisors.headOption.getOrElse(-1))\n }\n\n def divisors(n: Int, knownPrimes: Vector[Int]): List[Int] = {\n var remaining: Int = n\n var result: List[Int] = Nil\n var i = 0\n var cur = 0\n while (remaining > 1 && i < knownPrimes.length) {\n cur = knownPrimes(i)\n if (remaining % cur == 0) {\n result = cur :: result\n while (remaining % cur == 0) {\n remaining = remaining / cur\n }\n } else {\n i = i + 1\n }\n }\n if (remaining > 1) {\n result = remaining :: result\n }\n result\n }\n\n def listPrimes(): Vector[Int] = {\n val m = Math.sqrt(2 * 1000 * 1000 * 1000).ceil.toInt\n val isPrime = primesAux(m)\n var res = List.empty[Int]\n for (i <- isPrime.indices.reverse) {\n if (isPrime(i)) {\n res = i :: res\n }\n }\n res.toVector\n }\n\n def primesAux(n: Int): Array[Boolean] = {\n val p = Array.fill(n + 1)(true)\n val nl = n.toLong\n p.update(0, false)\n p.update(1, false)\n for (i <- 2 to n) {\n if (p(i) && i.toLong * i.toLong <= nl) {\n for (j <- (i * i).to(n, i)) {\n p.update(j, false)\n }\n }\n }\n p\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n \n def nextLong: Long = {\n next.toLong\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}\n", "positive_code": [{"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n\n val LIMIT = 44725\n val isPrime = Array.fill(LIMIT)(true)\n isPrime(0) = false\n isPrime(1) = false\n\n var i = 2\n while (i * i < LIMIT) {\n var j = i * i\n if (isPrime(j)) {\n while (j < LIMIT) {\n isPrime(j) = false\n j += i\n }\n }\n i += 1\n }\n\n val primes = new java.util.TreeSet[Int]\n for (p <- isPrime.indices) if (isPrime(p)) primes.add(p)\n\n for (i <- 0 until n) {\n val Array(a, b) = readInts(2)\n var addA, addB = 0\n var aComposite, bComposite = false\n\n val pit = primes.iterator\n while (pit.hasNext) {\n\n val p = pit.next()\n if (a % p != 0 && b % p != 0) pit.remove()\n else if (i == 0) {\n if (a % p == 0) {\n aComposite = true\n var d = a / p\n for (p <- isPrime.indices) if (isPrime(p)) {\n while (d % p == 0) d /= p\n }\n if (d > LIMIT) addA = d\n }\n if (b % p == 0) {\n bComposite = true\n var d = b / p\n for (p <- isPrime.indices) if (isPrime(p)) {\n while (d % p == 0) d /= p\n }\n if (d > LIMIT) addB = d\n }\n }\n }\n\n if (i == 0) {\n if (!aComposite) primes.add(a)\n if (!bComposite) primes.add(b)\n if (addA > 0) primes.add(addA)\n if (addB > 0) primes.add(addB)\n }\n\n }\n\n println(if (!primes.isEmpty) primes.iterator.next() else -1)\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject B extends App {\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val primes = listPrimes()\n var initialDivisors: Seq[Int] = {\n val l = in.nextInt\n val r = in.nextInt\n (divisors(l, primes) ::: divisors(r, primes)).distinct\n }\n for (_ <- 2 to n) {\n// println(initialDivisors)\n val l = in.nextInt\n val r = in.nextInt\n initialDivisors = initialDivisors.filter(div => (l % div == 0) || (r % div == 0))\n }\n println(initialDivisors.headOption.getOrElse(-1))\n }\n\n def divisors(n: Int, knownPrimes: Vector[Int]): List[Int] = {\n var remaining: Int = n\n var result: List[Int] = Nil\n var i = 0\n var cur = 0\n while (remaining >= 1 && i < knownPrimes.length) {\n cur = knownPrimes(i)\n if (remaining % cur == 0) {\n result = cur :: result\n while (remaining % cur == 0) {\n remaining = remaining / cur\n }\n } else {\n i = i + 1\n }\n }\n if (result.nonEmpty) result else List(n)\n }\n\n def listPrimes(): Vector[Int] = {\n val m = Math.sqrt(2 * 1000 * 1000 * 1000).ceil.toInt\n val ids = primesAux(m)\n var res = List.empty[Int]\n for (i <- ids.indices.reverse) {\n if (ids(i)) {\n res = i :: res\n }\n }\n res.toVector\n }\n\n def primesAux(n: Int): Array[Boolean] = {\n val p = Array.fill(n + 1)(true)\n val nl = n.toLong\n p.update(0, false)\n p.update(1, false)\n for (i <- 2 to n) {\n if (p(i) && i.toLong * i.toLong <= nl) {\n for (j <- (i * i).to(n, i)) {\n p.update(j, false)\n }\n }\n }\n p\n }\n\n\n /*\nint n;\nvector prime (n+1, true);\nprime[0] = prime[1] = false;\nfor (int i=2; i<=n; ++i)\n\tif (prime[i])\n\t\tif (i * 1ll * i <= n)\n\t\t\tfor (int j=i*i; j<=n; j+=i)\n\t\t\t\tprime[j] = false;\n\t\t\t\t*/\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n \n def nextLong: Long = {\n next.toLong\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n\n val LIMIT = 50000\n val isPrime = Array.fill(LIMIT)(true)\n isPrime(0) = false\n isPrime(1) = false\n\n var i = 2\n while (i * i < LIMIT) {\n var j = i * i\n if (isPrime(j)) {\n while (j < LIMIT) {\n isPrime(j) = false\n j += i\n }\n }\n i += 1\n }\n\n val primes = new java.util.TreeSet[Int]\n for (p <- isPrime.indices) if (isPrime(p)) primes.add(p)\n\n for (i <- 0 until n) {\n val Array(a, b) = readInts(2)\n var addA, addB = 0\n var aComposite, bComposite = false\n\n val pit = primes.iterator\n while (pit.hasNext) {\n\n val p = pit.next()\n if (a % p != 0 && b % p != 0) pit.remove()\n else if (i == 0) {\n if (a % p == 0) {\n aComposite = true\n val d = a / p\n if (d > LIMIT) addA = d\n }\n if (b % p == 0) {\n bComposite = true\n val d = b / p\n if (d > LIMIT) addB = d\n }\n }\n }\n\n if (i == 0) {\n if (!aComposite) primes.add(a)\n if (!bComposite) primes.add(b)\n if (addA > 0) primes.add(addA)\n if (addB > 0) primes.add(addB)\n }\n\n }\n\n println(if (!primes.isEmpty) primes.iterator.next() else -1)\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val LIMIT = 44725\n val isPrime = Array.fill(LIMIT)(true)\n isPrime(0) = false\n isPrime(1) = false\n\n var i = 2\n while (i * i < LIMIT) {\n var j = i * i\n if (isPrime(j)) {\n while (j < LIMIT) {\n isPrime(j) = false\n j += i\n }\n }\n i += 1\n }\n\n val primes = new java.util.TreeSet[Int]\n for (p <- isPrime.indices) if (isPrime(p)) primes.add(p)\n\n for (i <- 0 until n) {\n val Array(a, b) = readInts(2)\n val pit = primes.iterator\n var addA, addB = 0\n while (pit.hasNext) {\n val p = pit.next()\n if (a % p != 0 && b % p != 0) pit.remove()\n else {\n if (a % p == 0) {\n val d = a / p\n if (d > LIMIT) addA = d\n }\n if (b % p == 0) {\n val d = b / p\n if (d > LIMIT) addB = d\n }\n }\n }\n if (addA > 0) primes.add(addA)\n if (addB > 0) primes.add(addB)\n if (i == 0 && primes.isEmpty) {\n primes.add(a)\n primes.add(b)\n }\n }\n\n println(if (!primes.isEmpty) primes.iterator.next() else -1)\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val LIMIT = 44725\n val isPrime = Array.fill(LIMIT)(true)\n isPrime(0) = false\n isPrime(1) = false\n\n var i = 2\n while (i * i < LIMIT) {\n var j = i * i\n if (isPrime(j)) {\n while (j < LIMIT) {\n isPrime(j) = false\n j += i\n }\n }\n i += 1\n }\n\n val primes = new java.util.TreeSet[Int]\n for (p <- isPrime.indices) if (isPrime(p)) primes.add(p)\n\n for (i <- 0 until n) {\n val Array(a, b) = readInts(2)\n val pit = primes.iterator\n var addA, addB = 0\n while (pit.hasNext) {\n val p = pit.next()\n if (a % p != 0 && b % p != 0) pit.remove()\n else if (i == 0) {\n if (a % p == 0) {\n val d = a / p\n if (d > LIMIT) addA = d\n }\n if (b % p == 0) {\n val d = b / p\n if (d > LIMIT) addB = d\n }\n }\n }\n if (i == 0) {\n if (primes.isEmpty) {\n primes.add(a)\n primes.add(b)\n }\n if (addA > 0) primes.add(addA)\n if (addB > 0) primes.add(addB)\n }\n }\n\n println(if (!primes.isEmpty) primes.iterator.next() else -1)\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val LIMIT = 44725\n val isPrime = Array.fill(LIMIT)(true)\n isPrime(0) = false\n isPrime(1) = false\n\n var i = 2\n while (i * i < LIMIT) {\n var j = i * i\n if (isPrime(j)) {\n while (j < LIMIT) {\n isPrime(j) = false\n j += i\n }\n }\n i += 1\n }\n\n val primes = new java.util.TreeSet[Int]\n for (p <- isPrime.indices) if (isPrime(p)) primes.add(p)\n\n for (i <- 0 until n) {\n val Array(a, b) = readInts(2)\n val pit = primes.iterator\n while (pit.hasNext) {\n val p = pit.next()\n if (a % p != 0 && b % p != 0) pit.remove()\n }\n if (i == 0 && primes.isEmpty) {\n primes.add(a)\n primes.add(b)\n }\n }\n\n println(if (!primes.isEmpty) primes.iterator.next() else -1)\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val LIMIT = 44725\n val isPrime = Array.fill(LIMIT)(true)\n isPrime(0) = false\n isPrime(1) = false\n\n var i = 2\n while (i * i < LIMIT) {\n var j = i * i\n if (isPrime(j)) {\n while (j < LIMIT) {\n isPrime(j) = false\n j += i\n }\n }\n i += 1\n }\n\n val primes = new java.util.TreeSet[Int]\n for (p <- isPrime.indices) if (isPrime(p)) primes.add(p)\n\n for (i <- 0 until n) {\n val Array(a, b) = readInts(2)\n val pit = primes.iterator\n var addA, addB = 0\n while (pit.hasNext) {\n val p = pit.next()\n if (a % p != 0 && b % p != 0) pit.remove()\n else {\n if (a % p == 0) {\n val d = a / p\n if (d > LIMIT) addA = d\n }\n if (b % p == 0) {\n val d = b / p\n if (d > LIMIT) addB = d\n }\n }\n }\n if (addA > 0) primes.add(a)\n if (addB > 0) primes.add(b)\n if (i == 0 && primes.isEmpty) {\n primes.add(a)\n primes.add(b)\n }\n }\n\n println(if (!primes.isEmpty) primes.iterator.next() else -1)\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val LIMIT = 44725\n val isPrime = Array.fill(LIMIT)(true)\n isPrime(0) = false\n isPrime(1) = false\n\n var i = 2\n while (i * i < LIMIT) {\n var j = i * i\n if (isPrime(j)) {\n while (j < LIMIT) {\n isPrime(j) = false\n j += i\n }\n }\n i += 1\n }\n\n val primes = new java.util.TreeSet[Int]\n for (p <- isPrime.indices) if (isPrime(p)) primes.add(p)\n\n for (i <- 0 until n) {\n val Array(a, b) = readInts(2)\n val pit = primes.iterator\n var addA, addB = 0\n var aComposite, bComposite = false\n while (pit.hasNext) {\n val p = pit.next()\n if (a % p != 0 && b % p != 0) pit.remove()\n else if (i == 0) {\n if (a % p == 0) {\n aComposite = true\n val d = a / p\n if (d > LIMIT) addA = d\n }\n if (b % p == 0) {\n bComposite = true\n val d = b / p\n if (d > LIMIT) addB = d\n }\n }\n }\n if (i == 0) {\n if (!aComposite) primes.add(a)\n if (!bComposite) primes.add(b)\n if (addA > 0) primes.add(addA)\n if (addB > 0) primes.add(addB)\n }\n }\n\n println(if (!primes.isEmpty) primes.iterator.next() else -1)\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val LIMIT = 44725\n val isPrime = Array.fill(LIMIT)(true)\n isPrime(0) = false\n isPrime(1) = false\n\n var i = 2\n while (i * i < LIMIT) {\n var j = i * i\n if (isPrime(j)) {\n while (j < LIMIT) {\n isPrime(j) = false\n j += i\n }\n }\n i += 1\n }\n\n val primes = new java.util.TreeSet[Int]\n for (p <- isPrime.indices) if (isPrime(p)) primes.add(p)\n\n for (i <- 0 until n) {\n val Array(a, b) = readInts(2)\n val pit = primes.iterator\n var addA, addB = 0\n while (pit.hasNext) {\n val p = pit.next()\n if (a % p != 0 && b % p != 0) pit.remove()\n else if (i == 0) {\n if (a % p == 0) {\n val d = a / p\n if (d > LIMIT) addA = d\n }\n if (b % p == 0) {\n val d = b / p\n if (d > LIMIT) addB = d\n }\n }\n }\n if (i == 0) {\n if (primes.isEmpty) {\n primes.add(a)\n primes.add(b)\n } else {\n if (addA > 0) primes.add(addA)\n if (addB > 0) primes.add(addB)\n }\n }\n }\n\n println(if (!primes.isEmpty) primes.iterator.next() else -1)\n}\n"}], "src_uid": "aba6e64e040952b88e7dcb95e4472e56"} {"source_code": "\nimport java.io._\nimport java.util.Scanner\n\nimport scala.language.implicitConversions\n\nobject Zebras {\n class Lazy[A](x: => A) {\n lazy val value = x\n override def toString(): String = value.toString()\n }\n object Lazy {\n def apply[A](x: => A) = new Lazy(x)\n implicit def fromLazy[A](z: Lazy[A]): A = z.value\n implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)\n }\n def memoize[I, O](f: I => O): I => O = new collection.mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n\n def main(args: Array[String]): Unit = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n val bw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val A = br.readLine()\n// val range = 0.until(200000/3);\n// val A = range.map(_ => '0').mkString(\"\") + range.map(_ => '1').mkString(\"\") + range.map(_ => '0').mkString(\"\");\n// val t0 = System.nanoTime()\n\n case class Ret(valid: Boolean, seqs: List[List[Int]])\n def rec(ind: Int, ez: List[List[Int]], eo: List[List[Int]]): Ret = {\n if (ind == A.size) if (eo.size == 0) Ret(true, ez) else Ret(false, null)\n else {\n if (A(ind) == '0') {\n if (eo.isEmpty) rec(ind + 1, List(ind + 1) :: ez, eo)\n else {\n val first = eo.head\n rec(ind + 1, ((ind + 1) :: first) :: ez, eo.tail)\n }\n } else {\n if (ez.isEmpty) Ret(false, null)\n else {\n val first = ez.head\n rec(ind + 1, ez.tail, ((ind + 1) :: first) :: eo)\n }\n }\n }\n }\n\n val result = rec(0, List[List[Int]](), List[List[Int]]())\n\n\n val t1 = System.nanoTime()\n if (result.valid) {\n bw.println(result.seqs.size)\n result.seqs.foreach(seq => {bw.print(seq.size); bw.print(\" \"); seq.reverse.foreach(x => {bw.print(x); bw.print(\" \")}); bw.println()})\n } else {\n bw.println(\"-1\")\n }\n\n// bw.println(t1 - t0 + \"\")\n bw.close()\n br.close()\n }\n}\n", "positive_code": [{"source_code": "\nobject cTask3 {\n\n import scala.io.StdIn.readLine\n import scala.collection.mutable\n import scala.collection.mutable.ArrayBuffer\n\n def zebra(s: List[Char]):Option[List[List[Int]]] = {\n\n def helper(lst: List[Char], acc0: List[List[Int]], acc1: List[List[Int]], num: Int): Option[List[List[Int]]] = {\n lst match {\n case Nil if acc1.isEmpty => Some(acc0)\n case Nil => None\n case '0'::ls => acc1 match {\n case a::as1 =>helper(ls, (num::a)::acc0, as1, num + 1)\n case _ => helper(ls, List(num)::acc0, acc1, num + 1)\n }\n case '1'::ls => acc0 match {\n case a::as0 => helper(ls, as0, (num::a)::acc1, num + 1)\n case _ => None\n }\n }\n }\n helper(s, List(), List(), 1)\n }\n\n def zebra1(s: Array[Char]):Option[List[mutable.ArrayBuffer[Int]]] = {\n\n var all: ArrayBuffer[mutable.ArrayBuffer[Int]]=ArrayBuffer()\n var idx = 0\n var cutOff = 0\n\n for (i <- s.indices) {\n if(s(i) == '0'){\n if(cutOff != 0) {\n cutOff-=1\n all(cutOff)+=(i+1)\n } else {\n idx+=1\n all+=mutable.ArrayBuffer(i + 1)\n }\n } else {\n if(cutOff != idx){\n all(cutOff)+=(i+1)\n cutOff+=1\n } else {\n return None\n }\n }\n }\n if (cutOff != 0) None\n else Some(all.toList)\n\n }\n\n\n def main(args: Array[String]): Unit = {\n val s = readLine.toCharArray.toList\n zebra(s) match {\n case None => println(\"-1\")\n case Some(xs) => println(xs.length + \"\\n\" + xs.map(x => x.length + \" \" + x.reverse.mkString(\" \")).mkString(\"\\n\"))\n }\n\n }\n}"}, {"source_code": "\n\nobject cTask3 {\n\n import scala.io.StdIn.readLine\n import scala.collection.mutable\n import scala.collection.mutable.ArrayBuffer\n\n def zebra(s: List[Char]):Option[List[List[Int]]] = {\n\n def helper(lst: List[Char], acc0: List[List[Int]], acc1: List[List[Int]], num: Int): Option[List[List[Int]]] = {\n lst match {\n case Nil if acc1.isEmpty => Some(acc0)\n case Nil => None\n case '0'::ls => acc1 match {\n case a::as1 =>helper(ls, (num::a)::acc0, as1, num + 1)\n case _ => helper(ls, List(num)::acc0, acc1, num + 1)\n }\n case '1'::ls => acc0 match {\n case a::as0 => helper(ls, as0, (num::a)::acc1, num + 1)\n case _ => None\n }\n }\n }\n helper(s, List(), List(), 1)\n }\n\n def zebra1(s: Array[Char]):Option[List[mutable.ArrayBuffer[Int]]] = {\n\n var all: ArrayBuffer[mutable.ArrayBuffer[Int]]=ArrayBuffer()\n var idx = 0\n var cutOff = 0\n\n for (i <- s.indices) {\n if(s(i) == '0'){\n if(cutOff != 0) {\n cutOff-=1\n all(cutOff)+=(i+1)\n } else {\n idx+=1\n all+=mutable.ArrayBuffer(i + 1)\n }\n } else {\n if(cutOff != idx){\n all(cutOff)+=(i+1)\n cutOff+=1\n } else {\n return None\n }\n }\n }\n if (cutOff != 0) None\n else Some(all.toList)\n\n }\n\n\n def main(args: Array[String]): Unit = {\n val s = readLine.toCharArray\n zebra1(s) match {\n case None => println(\"-1\")\n case Some(xs) => println(xs.length + \"\\n\" + xs.map(x => x.length + \" \" + x.mkString(\" \")).mkString(\"\\n\"))\n }\n\n }\n}\n"}], "negative_code": [{"source_code": "\n\nobject cTask3 {\n\n import scala.io.StdIn.readLine\n import scala.collection.mutable\n import scala.collection.mutable.ArrayBuffer\n\n def zebra(s: List[Char]):Option[List[List[Int]]] = {\n\n def helper(lst: List[Char], acc0: List[List[Int]], acc1: List[List[Int]], num: Int): Option[List[List[Int]]] = {\n lst match {\n case Nil if acc1.isEmpty => Some(acc0)\n case Nil => None\n case '0'::ls => acc1 match {\n case a::as1 =>helper(ls, (num::a)::acc0, as1, num + 1)\n case _ => helper(ls, List(num)::acc0, acc1, num + 1)\n }\n case '1'::ls => acc0 match {\n case a::as0 => helper(ls, as0, (num::a)::acc1, num + 1)\n case _ => None\n }\n }\n }\n helper(s, List(), List(), 1)\n }\n\n def zebra1(s: Array[Char]):Option[List[mutable.ArrayBuffer[Int]]] = {\n\n var all: ArrayBuffer[mutable.ArrayBuffer[Int]]=ArrayBuffer()\n var idx = 0\n var cutOff = 0\n\n for (i <- s.indices) {\n if(s(i) == '0'){\n if(cutOff != 0) {\n cutOff-=1\n all(cutOff)+=(i+1)\n } else {\n idx+=1\n all+=mutable.ArrayBuffer(i + 1)\n }\n } else {\n if(cutOff != idx){\n all(cutOff)+=(i+1)\n cutOff+=1\n } else {\n return None\n }\n }\n }\n if (cutOff != 0) None\n else Some(all.toList)\n\n }\n\n\n def main(args: Array[String]): Unit = {\n val s = readLine.toCharArray.toList\n zebra(s) match {\n case None => println(\"-1\")\n case Some(xs) => println(xs.length + \"\\n\" + xs.map(x => x.length + \" \" + x.mkString(\" \")).mkString(\"\\n\"))\n }\n\n }\n}"}, {"source_code": "\nobject cTask3 {\n\n import scala.io.StdIn.{readLine, readInt}\n\n def zebra(s: List[Int]):Option[List[List[Int]]] = {\n\n def helper(lst: List[Int], acc: List[List[(Int, Int)]], num: Int): Option[List[List[(Int, Int)]]] = {\n def helpmat(elem: Int, num: Int, acc1: List[List[(Int, Int)]], acc2: List[List[(Int, Int)]]): Option[List[List[(Int, Int)]]]={\n acc2 match {\n case Nil if elem == 0 => Some(List((0, num))::acc1)\n case Nil => None\n case x::xs if elem != x.head._1 => Some(((elem, num)::x)::xs ++ acc1)\n case x::xs => helpmat(elem, num, x::acc1, xs)\n }\n }\n\n lst match {\n case Nil => Some(acc)\n case x::xs => helpmat(x, num, List(), acc) match {\n case None => None\n case Some(newAcc) => helper(xs, newAcc, num + 1)\n }\n }\n\n }\n helper(s, List(), 1) match {\n case Some(e) if e.forall(_.head._1 == 0) => Some(e.map(y => y.map(_._2)))\n case _ => None\n }\n }\n\n def main(args: Array[String]): Unit = {\n var s = readLine.toCharArray.map(_.asDigit).toList\n zebra(s) match {\n case None => println(\"-1\")\n case Some(xs) => xs.foreach(x => println(x.length + \" \" + x.reverse.mkString(\" \")))\n }\n\n }\n}\n"}, {"source_code": "\nobject cTask3 {\n\n import scala.io.StdIn.readLine\n import scala.collection.mutable\n\n def zebra(s: List[Char]):Option[List[List[Int]]] = {\n\n def helper(lst: List[Char], acc0: List[List[Int]], acc1: List[List[Int]], num: Int): Option[List[List[Int]]] = {\n lst match {\n case Nil if acc1.isEmpty => Some(acc0)\n case Nil => None\n case '0'::ls => acc1 match {\n case a::as1 =>helper(ls, (num::a)::acc0, as1, num + 1)\n case _ => helper(ls, List(num)::acc0, acc1, num + 1)\n }\n case '1'::ls => acc0 match {\n case a::as0 => helper(ls, as0, (num::a)::acc1, num + 1)\n case _ => None\n }\n }\n }\n helper(s, List(), List(), 1)\n }\n\n def zebra1(s: Array[Char]):Option[List[List[Int]]] = {\n\n val acc0:mutable.ArrayBuffer[List[Int]] = mutable.ArrayBuffer()\n val acc1:mutable.ArrayBuffer[List[Int]] = mutable.ArrayBuffer()\n\n for (i <- s.indices) {\n if(s(i) == '0'){\n if(acc1.nonEmpty) {\n acc0+=i::acc1.head\n acc1-=acc1(0)\n } else acc0 += List(i)\n } else {\n if(acc0.nonEmpty){\n acc1+=i::acc0.head\n acc0-=acc0(0)\n } else {\n return None\n }\n }\n }\n if (acc1.nonEmpty) None\n else Some(acc0.toList)\n\n }\n\n\n def main(args: Array[String]): Unit = {\n val s = readLine.toCharArray\n zebra1(s) match {\n case None => println(\"-1\")\n case Some(xs) => println(xs.length); xs.foreach(x => println(x.length + \" \" + x.reverse.mkString(\" \")))\n }\n\n }\n}\n"}, {"source_code": "\nimport java.io.BufferedWriter\nimport java.io.OutputStreamWriter\nimport java.io.InputStreamReader\nimport java.io.BufferedReader\nimport java.util.Scanner\n\nimport scala.language.implicitConversions\n\nobject Zebras {\n class Lazy[A](x: => A) {\n lazy val value = x\n override def toString(): String = value.toString()\n }\n object Lazy {\n def apply[A](x: => A) = new Lazy(x)\n implicit def fromLazy[A](z: Lazy[A]): A = z.value\n implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)\n }\n def memoize[I, O](f: I => O): I => O = new collection.mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n\n def main(args: Array[String]): Unit = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n val bw = new BufferedWriter(new OutputStreamWriter(System.out))\n\n val A = br.readLine()\n// val A = 0.until(200000).map(_ => '0').mkString(\"\")\n// val t0 = System.nanoTime()\n\n case class Ret(valid: Boolean, seqs: List[List[Int]])\n def rec(ind: Int, ez: List[List[Int]], eo: List[List[Int]]): Ret = {\n if (ind == A.size) if (eo.size == 0) Ret(true, ez) else Ret(false, null)\n else {\n if (A(ind) == '0') {\n if (eo.size == 0) rec(ind + 1, List(ind + 1) :: ez, eo)\n else {\n val first = eo.head\n rec(ind + 1, ((ind + 1) :: first) :: ez, eo.tail)\n }\n } else {\n if (ez.size == 0) Ret(false, null)\n else {\n val first = ez.head\n rec(ind + 1, ez.tail, ((ind + 1) :: first) :: eo)\n }\n }\n }\n }\n\n val result = rec(0, List[List[Int]](), List[List[Int]]())\n\n if (result.valid) {\n bw.write(result.seqs.size + \"\\n\")\n result.seqs.foreach(seq => {bw.write(seq.size + \" \"); seq.foldRight(0)((x, _) => {bw.write(x + \" \"); 0}); bw.write(\"\\n\")})\n } else {\n bw.write(\"-1\\n\")\n }\n\n// val t1 = System.nanoTime()\n// bw.write(t1 - t0 + \"\")\n\n// bw.flush()\n }\n}\n"}, {"source_code": "\n\nimport java.io.BufferedWriter\nimport java.io.OutputStreamWriter\nimport java.util.Scanner\n\nimport scala.language.implicitConversions\n\nobject Zebras {\n class Lazy[A](x: => A) {\n lazy val value = x\n override def toString(): String = value.toString()\n }\n object Lazy {\n def apply[A](x: => A) = new Lazy(x)\n implicit def fromLazy[A](z: Lazy[A]): A = z.value\n implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)\n }\n def memoize[I, O](f: I => O): I => O = new collection.mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n\n def main(args: Array[String]): Unit = {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out))\n\n// val A = sc.next()\n val A = 0.until(200000).map(_ => '0').mkString(\"\")\n val t0 = System.nanoTime()\n\n case class Ret(valid: Boolean, seqs: List[List[Int]])\n def rec(ind: Int, ez: List[List[Int]], eo: List[List[Int]]): Ret = {\n if (ind == A.size) if (eo.size == 0) Ret(true, ez) else Ret(false, null)\n else {\n if (A(ind) == '0') {\n if (eo.size == 0) rec(ind + 1, List(ind) :: ez, eo)\n else {\n val first = eo.head\n rec(ind + 1, (ind :: first) :: ez, eo.tail)\n }\n } else {\n if (ez.size == 0) Ret(false, null)\n else {\n val first = ez.head\n rec(ind + 1, ez.tail, (ind :: first) :: eo)\n }\n }\n }\n }\n\n val result = rec(0, List[List[Int]](), List[List[Int]]())\n\n if (result.valid) {\n bw.write(result.seqs.size + \"\\n\")\n result.seqs.foreach(seq => {bw.write(seq.size + \" \"); bw.write(seq.reverse.map(_ + 1).mkString(\" \")); bw.write(\"\\n\")})\n } else {\n bw.write(\"-1\\n\")\n }\n\n val t1 = System.nanoTime()\n// bw.write(t1 - t0 + \"\")\n\n bw.flush()\n }\n}\n"}, {"source_code": "\nimport java.io.BufferedWriter\nimport java.io.OutputStreamWriter\nimport java.io.InputStreamReader\nimport java.io.BufferedReader\nimport java.util.Scanner\n\nimport scala.language.implicitConversions\n\nobject Zebras {\n class Lazy[A](x: => A) {\n lazy val value = x\n override def toString(): String = value.toString()\n }\n object Lazy {\n def apply[A](x: => A) = new Lazy(x)\n implicit def fromLazy[A](z: Lazy[A]): A = z.value\n implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)\n }\n def memoize[I, O](f: I => O): I => O = new collection.mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n\n def main(args: Array[String]): Unit = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n val bw = new BufferedWriter(new OutputStreamWriter(System.out))\n\n// val A = br.readLine()\n val A = 0.until(200000).map(_ => '0').mkString(\"\")\n// val t0 = System.nanoTime()\n\n case class Ret(valid: Boolean, seqs: List[List[Int]])\n def rec(ind: Int, ez: List[List[Int]], eo: List[List[Int]]): Ret = {\n if (ind == A.size) if (eo.size == 0) Ret(true, ez) else Ret(false, null)\n else {\n if (A(ind) == '0') {\n if (eo.size == 0) rec(ind + 1, List(ind + 1) :: ez, eo)\n else {\n val first = eo.head\n rec(ind + 1, ((ind + 1) :: first) :: ez, eo.tail)\n }\n } else {\n if (ez.size == 0) Ret(false, null)\n else {\n val first = ez.head\n rec(ind + 1, ez.tail, ((ind + 1) :: first) :: eo)\n }\n }\n }\n }\n\n val result = rec(0, List[List[Int]](), List[List[Int]]())\n\n if (result.valid) {\n bw.write(result.seqs.size + \"\\n\")\n result.seqs.foreach(seq => {bw.write(seq.size + \" \"); seq.reverse.foreach(x => bw.write(x + \" \")); bw.write(\"\\n\")})\n } else {\n bw.write(\"-1\\n\")\n }\n\n// val t1 = System.nanoTime()\n// bw.write(t1 - t0 + \"\")\n\n bw.flush()\n }\n}\n"}], "src_uid": "37b34461876af7f2e845417268b55ffa"} {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nm = readIntLine()\n val grid = (1 to nm.head).map(_ => readLine().toCharArray).toArray\n val couldBlockBadGuys = blockBadGuys(grid, nm.head, nm.last)\n val canGoodGuysReach = reachGood(grid, nm.head, nm.last)\n println(if (couldBlockBadGuys && canGoodGuysReach) \"Yes\" else \"No\")\n }\n }\n\n def reachGood(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {\n val marked = Array.ofDim[Boolean](n, m)\n\n def dfs(i: Int, j: Int): Unit = {\n if (i > 0 && !marked(i - 1)(j) && grid(i - 1)(j) != '#' && grid(i - 1)(j) != 'B') {\n marked(i - 1)(j) = true\n dfs(i - 1, j)\n }\n if (j > 0 && !marked(i)(j - 1) && grid(i)(j - 1) != '#' && grid(i)(j - 1) != 'B') {\n marked(i)(j - 1) = true\n dfs(i, j - 1)\n }\n if (i < n - 1 && !marked(i + 1)(j) && grid(i + 1)(j) != '#'&& grid(i + 1)(j) != 'B') {\n marked(i + 1)(j) = true\n dfs(i + 1, j)\n }\n if (j < m - 1 && !marked(i)(j + 1) && grid(i)(j + 1) != '#' && grid(i)(j + 1) != 'B') {\n marked(i)(j + 1) = true\n dfs(i, j + 1)\n }\n }\n\n if (grid(n - 1)(m - 1) != '#' && grid(n - 1)(m - 1) != 'B') {\n marked(n - 1)(m - 1) = true\n dfs(n - 1, m - 1)\n }\n for (i <- marked.indices) {\n for (j <- marked(i).indices) {\n if (grid(i)(j) == 'G' && !marked(i)(j)) return false\n }\n }\n grid(n - 1)(m - 1) != 'B'\n }\n\n def blockBadGuys(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {\n for (i <- grid.indices) {\n for (j <- grid(i).indices) {\n if (grid(i)(j) == 'B') {\n if (i > 0) {\n if (grid(i - 1)(j) == 'G') return false\n if (grid(i - 1)(j) != 'B') grid(i - 1)(j) = '#'\n }\n if (j > 0) {\n if (grid(i)(j - 1) == 'G') return false\n if (grid(i)(j - 1) != 'B') grid(i)(j - 1) = '#'\n }\n if (i < n - 1) {\n if (grid(i + 1)(j) == 'G') return false\n if (grid(i + 1)(j) != 'B') grid(i + 1)(j) = '#'\n }\n if (j < m - 1) {\n if (grid(i)(j + 1) == 'G') return false\n if (grid(i)(j + 1) != 'B') grid(i)(j + 1) = '#'\n }\n }\n }\n }\n\n true\n }\n\n def matching(first: Array[Int], second: Array[Int]): Int = {\n val n = first.length\n val mapInt = Array.ofDim[Int](first.length)\n for (i <- first.indices) {\n mapInt(first(i) - 1) = i + 1\n }\n\n val differences = Array.ofDim[Int](second.length)\n for (i <- first.indices) {\n differences( (mapInt(second(i) - 1) - i - 1 + n) % n) += 1\n }\n\n var max = 0\n for (i <- differences.indices) {\n if (differences(i) > max)\n max = differences(i)\n }\n\n max\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n", "positive_code": [{"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val maze = Array.fill(n){ nextLine.toCharArray }\n\n @inline def get(r: Int, c: Int): Char = {\n if (r >= 0 && r < n && c >= 0 && c < m) maze(r)(c) else '#'\n }\n\n var can = true\n\n var r = 0\n while (r < n) {\n var c = 0\n while (c < m) {\n if (maze(r)(c) == '.' &&\n ((r > 0 && maze(r - 1)(c) == 'B') ||\n (r < n - 1 && maze(r + 1)(c) == 'B') ||\n (c > 0 && maze(r)(c - 1) == 'B') ||\n (c < m - 1 && maze(r)(c + 1) == 'B'))) {\n maze(r)(c) = '#'\n } else if (maze(r)(c) == 'G' &&\n ((r > 0 && maze(r - 1)(c) == 'B') ||\n (r < n - 1 && maze(r + 1)(c) == 'B') ||\n (c > 0 && maze(r)(c - 1) == 'B') ||\n (c < m - 1 && maze(r)(c + 1) == 'B'))) {\n can = false\n }\n c += 1\n }\n r += 1\n }\n\n def dfs(r: Int, c: Int): Unit = {\n maze(r)(c) = '#'\n if (r > 0 && maze(r - 1)(c) != '#') dfs(r - 1, c)\n if (r < n - 1 && maze(r + 1)(c) != '#') dfs(r + 1, c)\n if (c > 0 && maze(r)(c - 1) != '#') dfs(r, c - 1)\n if (c < m - 1 && maze(r)(c + 1) != '#') dfs(r, c + 1)\n }\n\n val s0 = maze(n - 1)(m - 1)\n if (s0 == 'B') can = false\n if ((s0 == 'G' || s0 == '.') && can) {\n dfs(n - 1, m - 1)\n }\n\n r = 0\n while (r < n) {\n var c = 0\n while (c < m) {\n if (maze(r)(c) == 'G') can = false\n c += 1\n }\n r += 1\n }\n\n val res = can\n\n out.println(if (res) \"Yes\" else \"No\")\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object D {\n\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val maze = Array.fill(n){ nextLine.toCharArray }\n\n @inline def get(r: Int, c: Int): Char = {\n if (r >= 0 && r < n && c >= 0 && c < m) maze(r)(c) else '#'\n }\n\n var can = true\n\n var r = 0\n while (r < n) {\n var c = 0\n while (c < m) {\n if (maze(r)(c) == '.' &&\n (get(r - 1, c) == 'B' || get(r + 1, c) == 'B' || get(r, c - 1) == 'B' || get(r, c + 1) == 'B')) {\n maze(r)(c) = '#'\n } else if (maze(r)(c) == 'G' &&\n (get(r - 1, c) == 'B' || get(r + 1, c) == 'B' || get(r, c - 1) == 'B' || get(r, c + 1) == 'B')) {\n can = false\n }\n c += 1\n }\n r += 1\n }\n\n def dfs(r: Int, c: Int): Unit = {\n maze(r)(c) = '#'\n if (r > 0 && maze(r - 1)(c) != '#') dfs(r - 1, c)\n if (r < n - 1 && maze(r + 1)(c) != '#') dfs(r + 1, c)\n if (c > 0 && maze(r)(c - 1) != '#') dfs(r, c - 1)\n if (c < m - 1 && maze(r)(c + 1) != '#') dfs(r, c + 1)\n }\n\n val s0 = maze(n - 1)(m - 1)\n if (s0 == 'B') can = false\n if ((s0 == 'G' || s0 == '.') && can) {\n dfs(n - 1, m - 1)\n }\n\n r = 0\n while (r < n) {\n var c = 0\n while (c < m) {\n if (maze(r)(c) == 'G') can = false\n c += 1\n }\n r += 1\n }\n\n val res = can\n\n out.println(if (res) \"Yes\" else \"No\")\n\n out.flush()\n }\n}\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nm = readIntLine()\n val grid = (1 to nm.head).map(_ => readLine().toCharArray).toArray\n val couldBlockBadGuys = blockBadGuys(grid, nm.head, nm.last)\n val canGoodGuysReach = reachGood(grid, nm.head, nm.last)\n println(if (couldBlockBadGuys && canGoodGuysReach) \"Yes\" else \"No\")\n }\n }\n\n def reachGood(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {\n val marked = Array.ofDim[Boolean](n, m)\n\n def dfs(i: Int, j: Int): Unit = {\n if (i > 0 && !marked(i - 1)(j) && grid(i - 1)(j) != 'W') {\n marked(i - 1)(j) = true\n dfs(i - 1, j)\n }\n if (j > 0 && !marked(i)(j - 1) && grid(i)(j - 1) != 'W') {\n marked(i)(j - 1) = true\n dfs(i, j - 1)\n }\n if (i < n - 1 && !marked(i + 1)(j) && grid(i + 1)(j) != 'W') {\n marked(i + 1)(j) = true\n dfs(i + 1, j)\n }\n if (j < m - 1 && !marked(i)(j + 1) && grid(i)(j + 1) != 'W') {\n marked(i)(j + 1) = true\n dfs(i, j + 1)\n }\n }\n\n if (grid(n - 1)(m - 1) != 'W' && grid(n - 1)(m - 1) != 'B') dfs(n - 1, m - 1)\n for (i <- marked.indices) {\n for (j <- marked(i).indices) {\n if (grid(i)(j) == 'G' && ! marked(i)(j)) return false\n }\n }\n true\n }\n\n def blockBadGuys(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {\n for (i <- grid.indices) {\n for (j <- grid(i).indices) {\n if (grid(i)(j) == 'B') {\n if (i > 0) {\n if (grid(i - 1)(j) == 'G') return false\n if (grid(i - 1)(j) != 'B') grid(i - 1)(j) = 'W'\n }\n if (j > 0) {\n if (grid(i)(j - 1) == 'G') return false\n if (grid(i)(j - 1) != 'B') grid(i)(j - 1) = 'W'\n }\n if (i < n - 1) {\n if (grid(i + 1)(j) == 'G') return false\n if (grid(i + 1)(j) != 'B') grid(i + 1)(j) = 'W'\n }\n if (j < m - 1) {\n if (grid(i)(j + 1) == 'G') return false\n if (grid(i)(j + 1) != 'B') grid(i)(j + 1) = 'W'\n }\n }\n }\n }\n\n true\n }\n\n def matching(first: Array[Int], second: Array[Int]): Int = {\n val n = first.length\n val mapInt = Array.ofDim[Int](first.length)\n for (i <- first.indices) {\n mapInt(first(i) - 1) = i + 1\n }\n\n val differences = Array.ofDim[Int](second.length)\n for (i <- first.indices) {\n differences( (mapInt(second(i) - 1) - i - 1 + n) % n) += 1\n }\n\n var max = 0\n for (i <- differences.indices) {\n if (differences(i) > max)\n max = differences(i)\n }\n\n max\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nm = readIntLine()\n val grid = (1 to nm.head).map(_ => readLine().toCharArray).toArray\n val couldBlockBadGuys = blockBadGuys(grid, nm.head, nm.last)\n val canGoodGuysReach = reachGood(grid, nm.head, nm.last)\n println(if (couldBlockBadGuys && canGoodGuysReach) \"Yes\" else \"No\")\n }\n }\n\n def reachGood(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {\n val marked = Array.ofDim[Boolean](n, m)\n\n def dfs(i: Int, j: Int): Unit = {\n if (i > 0 && !marked(i - 1)(j) && grid(i - 1)(j) != 'W') {\n marked(i - 1)(j) = true\n dfs(i - 1, j)\n }\n if (j > 0 && !marked(i)(j - 1) && grid(i)(j - 1) != 'W') {\n marked(i)(j - 1) = true\n dfs(i, j - 1)\n }\n if (i < n - 1 && !marked(i + 1)(j) && grid(i + 1)(j) != 'W') {\n marked(i + 1)(j) = true\n dfs(i + 1, j)\n }\n if (j < m - 1 && !marked(i)(j + 1) && grid(i)(j + 1) != 'W') {\n marked(i)(j + 1) = true\n dfs(i, j + 1)\n }\n }\n\n if (grid(n - 1)(m - 1) != 'W' && grid(n - 1)(m - 1) != 'B') {\n dfs(n - 1, m - 1)\n marked(n - 1)(m - 1) = true\n }\n for (i <- marked.indices) {\n for (j <- marked(i).indices) {\n if (grid(i)(j) == 'G' && ! marked(i)(j)) return false\n }\n }\n true\n }\n\n def blockBadGuys(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {\n for (i <- grid.indices) {\n for (j <- grid(i).indices) {\n if (grid(i)(j) == 'B') {\n if (i > 0) {\n if (grid(i - 1)(j) == 'G') return false\n if (grid(i - 1)(j) != 'B') grid(i - 1)(j) = 'W'\n }\n if (j > 0) {\n if (grid(i)(j - 1) == 'G') return false\n if (grid(i)(j - 1) != 'B') grid(i)(j - 1) = 'W'\n }\n if (i < n - 1) {\n if (grid(i + 1)(j) == 'G') return false\n if (grid(i + 1)(j) != 'B') grid(i + 1)(j) = 'W'\n }\n if (j < m - 1) {\n if (grid(i)(j + 1) == 'G') return false\n if (grid(i)(j + 1) != 'B') grid(i)(j + 1) = 'W'\n }\n }\n }\n }\n\n true\n }\n\n def matching(first: Array[Int], second: Array[Int]): Int = {\n val n = first.length\n val mapInt = Array.ofDim[Int](first.length)\n for (i <- first.indices) {\n mapInt(first(i) - 1) = i + 1\n }\n\n val differences = Array.ofDim[Int](second.length)\n for (i <- first.indices) {\n differences( (mapInt(second(i) - 1) - i - 1 + n) % n) += 1\n }\n\n var max = 0\n for (i <- differences.indices) {\n if (differences(i) > max)\n max = differences(i)\n }\n\n max\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nm = readIntLine()\n val grid = (1 to nm.head).map(_ => readLine().toCharArray).toArray\n val couldBlockBadGuys = blockBadGuys(grid, nm.head, nm.last)\n val canGoodGuysReach = reachGood(grid, nm.head, nm.last)\n println(if (couldBlockBadGuys && canGoodGuysReach) \"Yes\" else \"No\")\n }\n }\n\n def reachGood(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {\n val marked = Array.ofDim[Boolean](n, m)\n\n def dfs(i: Int, j: Int): Unit = {\n if (i > 0 && !marked(i - 1)(j) && grid(i - 1)(j) != 'W') {\n marked(i - 1)(j) = true\n dfs(i - 1, j)\n }\n if (j > 0 && !marked(i)(j - 1) && grid(i)(j - 1) != 'W') {\n marked(i)(j - 1) = true\n dfs(i, j - 1)\n }\n if (i < n - 1 && !marked(i + 1)(j) && grid(i + 1)(j) != 'W') {\n marked(i + 1)(j) = true\n dfs(i + 1, j)\n }\n if (j < m - 1 && !marked(i)(j + 1) && grid(i)(j + 1) != 'W') {\n marked(i)(j + 1) = true\n dfs(i, j + 1)\n }\n }\n\n if (grid(n - 1)(m - 1) != 'W' && grid(n - 1)(m - 1) != 'B') {\n marked(n - 1)(m - 1) = true\n dfs(n - 1, m - 1)\n }\n for (i <- marked.indices) {\n for (j <- marked(i).indices) {\n if (grid(i)(j) == 'G' && !marked(i)(j)) return false\n }\n }\n grid(n - 1)(m - 1) != 'B'\n }\n\n def blockBadGuys(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {\n for (i <- grid.indices) {\n for (j <- grid(i).indices) {\n if (grid(i)(j) == 'B') {\n if (i > 0) {\n if (grid(i - 1)(j) == 'G') return false\n if (grid(i - 1)(j) != 'B') grid(i - 1)(j) = 'W'\n }\n if (j > 0) {\n if (grid(i)(j - 1) == 'G') return false\n if (grid(i)(j - 1) != 'B') grid(i)(j - 1) = 'W'\n }\n if (i < n - 1) {\n if (grid(i + 1)(j) == 'G') return false\n if (grid(i + 1)(j) != 'B') grid(i + 1)(j) = 'W'\n }\n if (j < m - 1) {\n if (grid(i)(j + 1) == 'G') return false\n if (grid(i)(j + 1) != 'B') grid(i)(j + 1) = 'W'\n }\n }\n }\n }\n\n true\n }\n\n def matching(first: Array[Int], second: Array[Int]): Int = {\n val n = first.length\n val mapInt = Array.ofDim[Int](first.length)\n for (i <- first.indices) {\n mapInt(first(i) - 1) = i + 1\n }\n\n val differences = Array.ofDim[Int](second.length)\n for (i <- first.indices) {\n differences( (mapInt(second(i) - 1) - i - 1 + n) % n) += 1\n }\n\n var max = 0\n for (i <- differences.indices) {\n if (differences(i) > max)\n max = differences(i)\n }\n\n max\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nm = readIntLine()\n val grid = (1 to nm.head).map(_ => readLine().toCharArray).toArray\n val couldBlockBadGuys = blockBadGuys(grid, nm.head, nm.last)\n val canGoodGuysReach = reachGood(grid, nm.head, nm.last)\n println(if (couldBlockBadGuys && canGoodGuysReach) \"Yes\" else \"No\")\n }\n }\n\n def reachGood(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {\n val marked = Array.ofDim[Boolean](n, m)\n\n def dfs(i: Int, j: Int): Unit = {\n if (i > 0 && !marked(i - 1)(j) && grid(i - 1)(j) != '#' && grid(i - 1)(j) != 'B') {\n marked(i - 1)(j) = true\n dfs(i - 1, j)\n }\n if (j > 0 && !marked(i)(j - 1) && grid(i)(j - 1) != '#' && grid(i)(j - 1) != 'B') {\n marked(i)(j - 1) = true\n dfs(i, j - 1)\n }\n if (i < n - 1 && !marked(i + 1)(j) && grid(i + 1)(j) != '#'&& grid(i + 1)(j) != 'B') {\n marked(i + 1)(j) = true\n dfs(i + 1, j)\n }\n if (j < m - 1 && !marked(i)(j + 1) && grid(i)(j + 1) != '#' && grid(i)(j + 1) != 'B') {\n marked(i)(j + 1) = true\n dfs(i, j + 1)\n }\n }\n\n if (grid(n - 1)(m - 1) != '#' && grid(n - 1)(m - 1) != 'B') {\n marked(n - 1)(m - 1) = true\n dfs(n - 1, m - 1)\n }\n for (i <- marked.indices) {\n for (j <- marked(i).indices) {\n if (grid(i)(j) == 'G' && !marked(i)(j)) return false\n }\n }\n grid(n - 1)(m - 1) != 'B'\n }\n\n def blockBadGuys(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {\n for (i <- grid.indices) {\n for (j <- grid(i).indices) {\n if (grid(i)(j) == 'B') {\n if (i > 0) {\n if (grid(i - 1)(j) == 'G') return false\n if (grid(i - 1)(j) != 'B') grid(i - 1)(j) = 'W'\n }\n if (j > 0) {\n if (grid(i)(j - 1) == 'G') return false\n if (grid(i)(j - 1) != 'B') grid(i)(j - 1) = 'W'\n }\n if (i < n - 1) {\n if (grid(i + 1)(j) == 'G') return false\n if (grid(i + 1)(j) != 'B') grid(i + 1)(j) = 'W'\n }\n if (j < m - 1) {\n if (grid(i)(j + 1) == 'G') return false\n if (grid(i)(j + 1) != 'B') grid(i)(j + 1) = 'W'\n }\n }\n }\n }\n\n true\n }\n\n def matching(first: Array[Int], second: Array[Int]): Int = {\n val n = first.length\n val mapInt = Array.ofDim[Int](first.length)\n for (i <- first.indices) {\n mapInt(first(i) - 1) = i + 1\n }\n\n val differences = Array.ofDim[Int](second.length)\n for (i <- first.indices) {\n differences( (mapInt(second(i) - 1) - i - 1 + n) % n) += 1\n }\n\n var max = 0\n for (i <- differences.indices) {\n if (differences(i) > max)\n max = differences(i)\n }\n\n max\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nm = readIntLine()\n val grid = (1 to nm.head).map(_ => readLine().toCharArray).toArray\n val couldBlockBadGuys = blockBadGuys(grid, nm.head, nm.last)\n val canGoodGuysReach = reachGood(grid, nm.head, nm.last)\n println(if (couldBlockBadGuys && canGoodGuysReach) \"Yes\" else \"No\")\n }\n }\n\n def reachGood(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {\n val marked = Array.ofDim[Boolean](n, m)\n\n def dfs(i: Int, j: Int): Unit = {\n if (i > 0 && !marked(i - 1)(j) && grid(i - 1)(j) != 'W' && grid(i - 1)(j) != 'B') {\n marked(i - 1)(j) = true\n dfs(i - 1, j)\n }\n if (j > 0 && !marked(i)(j - 1) && grid(i)(j - 1) != 'W' && grid(i)(j - 1) != 'B') {\n marked(i)(j - 1) = true\n dfs(i, j - 1)\n }\n if (i < n - 1 && !marked(i + 1)(j) && grid(i + 1)(j) != 'W'&& grid(i + 1)(j) != 'B') {\n marked(i + 1)(j) = true\n dfs(i + 1, j)\n }\n if (j < m - 1 && !marked(i)(j + 1) && grid(i)(j + 1) != 'W' && grid(i)(j + 1) != 'B') {\n marked(i)(j + 1) = true\n dfs(i, j + 1)\n }\n }\n\n if (grid(n - 1)(m - 1) != 'W' && grid(n - 1)(m - 1) != 'B') {\n marked(n - 1)(m - 1) = true\n dfs(n - 1, m - 1)\n }\n for (i <- marked.indices) {\n for (j <- marked(i).indices) {\n if (grid(i)(j) == 'G' && !marked(i)(j)) return false\n }\n }\n grid(n - 1)(m - 1) != 'B'\n }\n\n def blockBadGuys(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {\n for (i <- grid.indices) {\n for (j <- grid(i).indices) {\n if (grid(i)(j) == 'B') {\n if (i > 0) {\n if (grid(i - 1)(j) == 'G') return false\n if (grid(i - 1)(j) != 'B') grid(i - 1)(j) = 'W'\n }\n if (j > 0) {\n if (grid(i)(j - 1) == 'G') return false\n if (grid(i)(j - 1) != 'B') grid(i)(j - 1) = 'W'\n }\n if (i < n - 1) {\n if (grid(i + 1)(j) == 'G') return false\n if (grid(i + 1)(j) != 'B') grid(i + 1)(j) = 'W'\n }\n if (j < m - 1) {\n if (grid(i)(j + 1) == 'G') return false\n if (grid(i)(j + 1) != 'B') grid(i)(j + 1) = 'W'\n }\n }\n }\n }\n\n true\n }\n\n def matching(first: Array[Int], second: Array[Int]): Int = {\n val n = first.length\n val mapInt = Array.ofDim[Int](first.length)\n for (i <- first.indices) {\n mapInt(first(i) - 1) = i + 1\n }\n\n val differences = Array.ofDim[Int](second.length)\n for (i <- first.indices) {\n differences( (mapInt(second(i) - 1) - i - 1 + n) % n) += 1\n }\n\n var max = 0\n for (i <- differences.indices) {\n if (differences(i) > max)\n max = differences(i)\n }\n\n max\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nm = readIntLine()\n val grid = (1 to nm.head).map(_ => readLine().toCharArray).toArray\n val couldBlockBadGuys = blockBadGuys(grid, nm.head, nm.last)\n val canGoodGuysReach = reachGood(grid, nm.head, nm.last)\n println(if (couldBlockBadGuys && canGoodGuysReach) \"Yes\" else \"No\")\n }\n }\n\n def reachGood(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {\n val marked = Array.ofDim[Boolean](n, m)\n\n def dfs(i: Int, j: Int): Unit = {\n if (i > 0 && !marked(i - 1)(j) && grid(i - 1)(j) != 'W') {\n marked(i - 1)(j) = true\n dfs(i - 1, j)\n }\n if (j > 0 && !marked(i)(j - 1) && grid(i)(j - 1) != 'W') {\n marked(i)(j - 1) = true\n dfs(i, j - 1)\n }\n if (i < n - 1 && !marked(i + 1)(j) && grid(i + 1)(j) != 'W') {\n marked(i + 1)(j) = true\n dfs(i + 1, j)\n }\n if (j < m - 1 && !marked(i)(j + 1) && grid(i)(j + 1) != 'W') {\n marked(i)(j + 1) = true\n dfs(i, j + 1)\n }\n }\n\n if (grid(n - 1)(m - 1) != 'W' && grid(n - 1)(m - 1) != 'B') dfs(n - 1, m - 1)\n for (i <- marked.indices) {\n for (j <- marked(i).indices) {\n if (grid(i)(j) == 'G' && ! marked(i)(j)) return false\n }\n }\n true\n }\n\n def blockBadGuys(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {\n for (i <- grid.indices) {\n for (j <- grid(i).indices) {\n if (grid(i)(j) == 'B') {\n if (i > 0) {\n if (grid(i - 1)(j) == 'G') return false\n if (grid(i - 1)(j) != 'B') grid(i - 1)(j) = 'W'\n }\n if (j > 0) {\n if (grid(i)(j - 1) == 'G') return false\n if (grid(i)(j - 1) != 'B') grid(i)(j - 1) = 'W'\n }\n if (i < n - 1) {\n if (grid(i + 1)(j) == 'G') return false\n if (grid(i + 1)(j) != 'B') grid(i + 1)(j) = 'W'\n }\n if (j < m - 1) {\n if (grid(i)(j + 1) == 'G') return false\n if (grid(i)(j + 1) != 'B') grid(i)(j + 1) = 'W'\n }\n }\n }\n }\n\n true\n }\n\n def matching(first: Array[Int], second: Array[Int]): Int = {\n val n = first.length\n val mapInt = Array.ofDim[Int](first.length)\n for (i <- first.indices) {\n mapInt(first(i) - 1) = i + 1\n }\n\n val differences = Array.ofDim[Int](second.length)\n for (i <- first.indices) {\n differences( (mapInt(second(i) - 1) - i - 1 + n) % n) += 1\n }\n\n var max = 0\n for (i <- differences.indices) {\n if (differences(i) > max)\n max = differences(i)\n }\n\n max\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val maze = Array.fill(n){ nextLine.toCharArray }\n\n def get(r: Int, c: Int): Char = {\n if (r >= 0 && r < n && c >= 0 && c < m) maze(r)(c) else '#'\n }\n\n for (r <- 0 until n) {\n for (c <- 0 until m) {\n if (maze(r)(c) == '.' &&\n (get(r - 1, c) == 'B' || get(r + 1, c) == 'B' || get(r, c - 1) == 'B' || get(r, c + 1) == 'B')) {\n maze(r)(c) = '#'\n }\n }\n }\n\n def dfs(r: Int, c: Int): Unit = {\n maze(r)(c) = '#'\n if (get(r - 1, c) != '#') dfs(r - 1, c)\n if (get(r + 1, c) != '#') dfs(r + 1, c)\n if (get(r, c - 1) != '#') dfs(r, c - 1)\n if (get(r, c + 1) != '#') dfs(r, c + 1)\n }\n\n val s0 = maze(n - 1)(m - 1)\n if (s0 == 'G' || s0 == '.') dfs(n - 1, m - 1)\n\n val res = !maze.exists(_.contains('G'))\n\n out.println(if (res) \"Yes\" else \"No\")\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val maze = Array.fill(n){ nextLine.toCharArray }\n\n @inline def get(r: Int, c: Int): Char = {\n if (r >= 0 && r < n && c >= 0 && c < m) maze(r)(c) else '#'\n }\n\n var can = true\n\n var r = 0\n while (r < n) {\n var c = 0\n while (c < m) {\n if (maze(r)(c) == '.' &&\n (get(r - 1, c) == 'B' || get(r + 1, c) == 'B' || get(r, c - 1) == 'B' || get(r, c + 1) == 'B')) {\n maze(r)(c) = '#'\n } else if (maze(r)(c) == 'G' &&\n (get(r - 1, c) == 'B' || get(r + 1, c) == 'B' || get(r, c - 1) == 'B' || get(r, c + 1) == 'B')) {\n can = false\n }\n c += 1\n }\n r += 1\n }\n\n def dfs(r: Int, c: Int): Unit = {\n maze(r)(c) = '#'\n if (r > 0 && maze(r)(c) != '#') dfs(r - 1, c)\n if (r < n - 1 && maze(r + 1)(c) != '#') dfs(r + 1, c)\n if (c > 0 && maze(r)(c - 1) != '#') dfs(r, c - 1)\n if (c < m - 1 && maze(r)(c + 1) != '#') dfs(r, c + 1)\n }\n\n val s0 = maze(n - 1)(m - 1)\n if (s0 == 'B') can = false\n if ((s0 == 'G' || s0 == '.') && can) {\n dfs(n - 1, m - 1)\n }\n\n r = 0\n while (r < n) {\n var c = 0\n while (c < m) {\n if (maze(r)(c) == 'G') can = false\n c += 1\n }\n r += 1\n }\n\n val res = can\n\n out.println(if (res) \"Yes\" else \"No\")\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val maze = Array.fill(n){ nextLine.toCharArray }\n\n @inline def get(r: Int, c: Int): Char = {\n if (r >= 0 && r < n && c >= 0 && c < m) maze(r)(c) else '#'\n }\n\n var can = true\n\n var r = 0\n while (r < n) {\n var c = 0\n while (c < m) {\n if (maze(r)(c) == '.' &&\n (get(r - 1, c) == 'B' || get(r + 1, c) == 'B' || get(r, c - 1) == 'B' || get(r, c + 1) == 'B')) {\n maze(r)(c) = '#'\n } else if (maze(r)(c) == 'G' &&\n (get(r - 1, c) == 'B' || get(r + 1, c) == 'B' || get(r, c - 1) == 'B' || get(r, c + 1) == 'B')) {\n can = false\n }\n c += 1\n }\n r += 1\n }\n\n def dfs(r: Int, c: Int): Unit = {\n maze(r)(c) = '#'\n if (r > 0 && maze(r)(c) != '#') dfs(r - 1, c)\n if (r < n - 1 && maze(r + 1)(c) != '#') dfs(r + 1, c)\n if (c > 0 && maze(r)(c - 1) != '#') dfs(r, c - 1)\n if (c < m - 1 && maze(r)(c + 1) != '#') dfs(r, c + 1)\n }\n\n val s0 = maze(n - 1)(m - 1)\n if ((s0 == 'G' || s0 == '.') && can) {\n dfs(n - 1, m - 1)\n }\n\n r = 0\n while (r < n) {\n var c = 0\n while (c < m) {\n if (maze(r)(c) == 'G') can = false\n c += 1\n }\n r += 1\n }\n\n val res = can\n\n out.println(if (res) \"Yes\" else \"No\")\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "src_uid": "a5e649f4d984a5c5365ca31436ad5883"} {"source_code": "object _948A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val r, c = io.read[Int]\n val pasture = io.read[Vector, String](r).map(_.replace('.', 'D'))\n\n def isWolf(i: Int)(j: Int) = pasture.lift(i).flatMap(_.lift(j)).contains('W')\n\n val ans = (0 until r) X (0 until c) find { case (i, j) =>\n pasture(i)(j) == 'S' && (isWolf(i-1)(j) || isWolf(i+1)(j) || isWolf(i)(j-1) || isWolf(i)(j+1))\n }\n\n io.write(if(ans.isDefined) \"No\" else pasture.mkString(\"Yes\\n\", \"\\n\", \"\"))\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n type Point = java.awt.geom.Point2D.Double\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p._1, ev(p._2))\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n //def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new Point(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def isPrime(n: Int): Boolean = BigInt(n).isProbablePrime(31)\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object A extends App {\n def protect(p: Array[Array[Char]], r: Int, c: Int): Boolean = {\n for (i <- 0 until r)\n for (j <- 0 until c)\n if (p(i)(j) == 'S') {\n if (\n p(i)(0 max (j - 1)) == 'W' ||\n p(i)((c - 1) min (j + 1)) == 'W' ||\n p(0 max (i - 1))(j) == 'W' ||\n p((r - 1) min (i + 1))(j) == 'W'\n ) {\n return false\n }\n else {\n if (p(i)(0 max (j - 1)) == '.') p(i)(0 max (j - 1)) = 'D'\n if (p(i)((c - 1) min (j + 1)) == '.') p(i)((c - 1) min (j + 1)) = 'D'\n if (p(0 max (i - 1))(j) == '.') p(0 max (i - 1))(j) = 'D'\n if (p((r - 1) min (i + 1))(j) == '.') p((r - 1) min (i + 1))(j) = 'D'\n }\n }\n true\n }\n\n val Array(r, c) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val p = Array.fill(r)(new Array[Char](c))\n for (i <- 0 until r) {\n val line = scala.io.StdIn.readLine()\n for (j <- 0 until c)\n p(i)(j) = line(j)\n }\n\n val s = protect(p, r, c)\n if (s) {\n println(\"Yes\")\n println(p.map(_.mkString(\"\")).mkString(\"\\n\"))\n } else println(\"No\")\n\n}\n"}], "negative_code": [], "src_uid": "f55c824d8db327e531499ced6c843102"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val data = Array.fill[List[Int]](n){Nil}\n (1 to m).foreach { _ =>\n val Array(a, b) = in.next().split(' ').map(_.toInt - 1)\n data(a) ::= b\n data(b) ::= a\n }\n var zero = data.indices.filter(i => data(i).length == 1)\n var i = 0\n while (zero.nonEmpty) {\n i += 1\n zero.foreach {j =>\n data(j).foreach { k => data(k) = data(k).filter(_ != j)}\n data(j) = Nil\n }\n zero = data.indices.filter(i => data(i).length == 1)\n }\n println(i)\n\n}", "positive_code": [{"source_code": "object StudentsAndShoelaces129B extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n solve(System.in,System.out)\n def solve(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextInt()\n val m = scanner.nextInt()\n val nodes = (1 to n).map(Node)\n val edges = (1 to m).map{ _ =>\n val a = nodes(scanner.nextInt()-1)\n val b = nodes(scanner.nextInt()-1)\n UndirectedEdge(a,b)\n }\n val g = new Graph(nodes,edges)\n\n def findNumGroups(graph: Graph): Int = {\n val badGuys = graph.findBadGuys()\n if(badGuys.isEmpty)\n 0\n else 1 + findNumGroups(graph.kickBadGuys(badGuys))\n }\n\n out.println(findNumGroups(g))\n\n }\n class Graph(val nodes: Seq[Node],val edges: Seq[UndirectedEdge]){\n val mapNeighbours = nodes.map(n => n -> edges.filter(e => e.a == n || e.b==n).map{case UndirectedEdge(a,b) => if(a==n) b else a}).toMap\n def findBadGuys(): Seq[Node] = mapNeighbours.filter{case (_,neighbours) => neighbours.length == 1}.keys.toSeq\n def kickBadGuys(badGuys: Seq[Node]): Graph = {\n val goodGuys = nodes.filterNot(n => badGuys.contains(n))\n val newEdges = edges.filterNot{case UndirectedEdge(a,b) => badGuys.contains(a) || badGuys.contains(b)}\n new Graph(goodGuys,newEdges)\n }\n\n }\n case class Node(node: Int)\n case class UndirectedEdge(a: Node, b: Node)\n}"}], "negative_code": [], "src_uid": "f8315dc903b0542c453cab4577bcb20d"} {"source_code": "\nimport scala.io.StdIn\n\nobject ZahirGame {\n\n\n\n\n def main(args: Array[String]): Unit = {\n val k = StdIn.readLine().split(\" \").tail.head.toInt\n val in = StdIn.readLine()\n\n def step(acc : (List[Char], Int), c: Char): (List[Char], Int) = acc match {\n case (Nil, _) => (List(c), 1)\n case (l, n) if l.head == c || n == 0 => (c :: l, n + 1)\n case (l, n) => (c :: l.drop(n % k), 1)\n }\n\n val (resWithLast, residue) = in.foldLeft[(List[Char], Int)]((List(), 0))(step)\n val res = resWithLast.drop(residue % k).sorted.foldLeft[Map[Char, Int]](Map()) { (acc, c) =>\n acc + (c -> (acc.getOrElse(c, 0) + 1))\n }\n println(if (res.isEmpty) 0 else res.values.max / k)\n }\n}", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject Problem_1105B {\n // Salem and Sticks\n\n def main(args: Array[String]) {\n val scan = scala.io.StdIn\n\n //Get inputs\n val inputs: Array[Int] = scan.readLine().split(\" \").map(_.toInt)\n val targetArr: String = scan.readLine()\n val n = inputs(0)\n val k = inputs(1)\n val occMap = Array.fill(256)(0)\n\n var x = 0\n while (x < n - k + 1) {\n val tempChar = targetArr(x)\n if (targetArr.substring(x, x + k).count(_ == tempChar) == k) {\n occMap(tempChar) += 1\n x += k\n }\n else{\n while(targetArr(x) == targetArr(x+1)){\n x+=1\n }\n x+=1\n }\n\n }\n val ans = occMap.max\n println(ans)\n }\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val S = ns(N)\n\n var ans = 0\n REP(26) { i =>\n val c = 'a' + i\n var cnt = 0\n var lvl = 0\n REP(N) { j =>\n if (S(j) == c) {\n cnt += 1\n if (cnt == K) {\n cnt = 0\n lvl += 1\n }\n } else {\n cnt = 0\n }\n }\n ans = max(ans, lvl)\n }\n\n out.println(ans)\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [], "src_uid": "6c71c828553e43c699237211005873e5"} {"source_code": "\nimport scala.io.StdIn\n\nobject Team extends App {\n\n val ques = StdIn.readInt()\n var solve = 0\n for (i <- Range(0, ques)) {\n if (impl(StdIn.readLine().split(\" \").map(_.toInt)))\n solve += 1\n }\n print(solve)\n\n def impl(soln: Array[Int]): Boolean = {\n soln.count(_ == 1) >= 2\n }\n}", "positive_code": [{"source_code": "object pratise {\n def main(args : Array[String]) {\n val n = readInt\n val res = (1 to n).count(_ => readLine().split(\" \").map(_.toInt).sum>1)\n println(res)\n }\n}\n"}, {"source_code": "object cf extends App{\n val t = readInt()\n var res = 0\n for (i <- 0 to t-1) {\n val Array(a, b, c) = readLine().split(\" \").map(_.toInt)\n val r = a+b+c\n if (r > 1) res += 1\n }\n println(res)\n}"}, {"source_code": "import scala.io.StdIn.readLine\nobject Solution {\n def reduceMembers(s: Iterable[Array[Int]]) = s map (_ reduceLeft (_ + _))\n def reduceProblems(s: Iterable[Int]) = s count (_ >= 2)\n def readLines(n: Int) = Iterator.continually(readLine).take(n).toIterable\n def main(args: Array[String]) = {\n val n = readLine.toInt\n val problemMembers = readLines(n) map (_ split \" \" map (_.toInt))\n println(reduceProblems(reduceMembers(problemMembers)))\n }\n}\n"}, {"source_code": "object Solution231A extends App {\n\n def solution() {\n val n = _int\n val res = 1.to(n).map(_ => _int + _int + _int).filter(i => i > 1).size\n println(res)\n }\n\n //////////////////////////////////////////////////\n import java.util.Scanner\n val SC: Scanner = new Scanner(System.in)\n def _line: String = SC.nextLine\n def _int: Int = SC.nextInt\n def _long: Long = SC.nextLong\n def _string: String = SC.next\n solution()\n}"}, {"source_code": "object Competition extends App {\n\n import scala.io.StdIn._\n\n val k = readInt()\n\n def input(n: Int)= (1 to n).map(_ => readLine().split(\" \").toSeq).toSeq\n\n def sumUp(seq: Seq[String]) = seq.map(Integer.parseInt).sum\n\n\n println(input(k).map(sumUp).count(_ > 1))\n}"}, {"source_code": "object Cf231A extends App {\n val n = readInt()\n var res = 0\n for (i <- 1 to n) {\n res = res + (if (readLine.split(\" \").map(_.toInt).sum >= 2) 1 else 0)\n }\n println(res)\n}"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n val n = readInt\n var i = 0\n var t = 0\n for (i <- 0 until n) {\n val x = (readLine().split(' ')).map(_.toInt)\n if (x.sum >= 2)\n t += 1\n }\n println(t)\n}"}, {"source_code": "import scala.collection.mutable._\nimport scala.math._\nimport scala.util.control.Breaks.break\nimport scala.util.control.Breaks.breakable\nimport java.util._\nobject Main extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt\n println(\n (for(i <- 1 to n) yield {\n (for(j <- 1 to 3) yield sc.nextInt).foldLeft(0)(_ + _) >= 2\n }).count(_ == true)\n )\n}\n"}, {"source_code": "object Problems_231A {\n def main(args: Array[String]) = {\n println((1 to readInt).count(_ => readLine.split(\" \").map(_.toInt).sum >= 2))\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject A extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n val ones = for {\n i <- 1 to n\n p = sc.nextInt\n q = sc.nextInt\n r = sc.nextInt\n if p + q + r >= 2\n } yield 1\n println(ones.length)\n}\n \n"}, {"source_code": "// http://codeforces.com/problemset/problem/231/A\n\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Team {\n def main(args: Array[String]): Unit = {\n val n: Int = readInt()\n var count: Int = 0\n for(i <- 1 to n) {\n if (readLine().split(\" \").map(_.toInt).sum >= 2) {\n count += 1\n }\n }\n println(count)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\n/**\n * @author traff\n */\n\nobject Main extends App {\n val n = StdIn.readLine().toInt\n\n var cnt = 0\n\n 1 to n foreach { _ =>\n val Array (x, y, z) = StdIn.readLine().split(\" \").map(_.toInt)\n\n def f(x: Int) = if (x>0) 1 else 0\n\n cnt += (if (f(x) + f(y) + f(z) > 1) 1 else 0)\n }\n\n println(cnt)\n\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = readInt\n val ans = (0 until n).map { k =>\n val s = readLine.split(\" \").map(_.toInt).sum\n if (s >= 2) 1 else 0\n }.sum\n println(ans)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println(Range(0, n).map(_ => in.next().split(\" \").map(_.toInt).sum).count(_ > 1))\n}"}, {"source_code": "object P231a extends App {\n val n = readLine.toInt\n val problems = (1 to n).map(_ => readLine.split(\" \").map(_.toInt))\n val implementings = problems.filter(_.sum >= 2)\n println(implementings.size)\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val std = scala.io.StdIn\n val n = std.readInt()\n var result = 0\n for (i <- 0 until n) {\n val r = std.readLine().split(\" \").map(_.toInt).sum\n if (r>=2) result += 1\n }\n println(result)\n }\n}"}, {"source_code": "import scala.io.StdIn\nobject solution extends App{\n \n val rounds = StdIn.readInt\n var count = 0\n for(round <- 1 to rounds){\n val views = StdIn.readLine.split(\" \").map(_.toInt).sum\n if( views >= 2) count += 1\n }\n println(count)\n \n}"}, {"source_code": "import scala.io.StdIn\nobject Team extends App\n{\n println((1 to StdIn.readInt()).count(_ => StdIn.readLine().split(' ').map(_.toInt).sum >=2))\n}\n\n"}, {"source_code": "object HelloWorld {\n def main(args: Array[String]) {\n val n = readInt\n var c = 0\n for (i <- 0 until n) {\n c += (if(readLine.split(\" \").map(_.toInt).count(_ == 1) > 1) 1 else 0)\n }\n println(c)\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn\n\nobject p231a extends App{\n\n\n def sumline(): Int ={\n val s = StdIn.readLine()\n var count = 0\n\n for (c <- s.toCharArray){\n if (c=='1') {\n count+=1\n }\n }\n if (count>=2) {\n return 1;\n }\n return 0\n }\n\n private val num = StdIn.readLine().toInt\n\n var sum = 0\n\n for (i <- 0 until num){\n sum += sumline()\n }\n\n print(sum)\n\n}\n"}, {"source_code": "object A231 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = new Array[Int](n)\n for(i <- 0 until n) {\n val Array(a, b, c) = readInts(3)\n input(i) = a + b + c\n }\n println(input.count(_ > 1))\n }\n}"}, {"source_code": "import java.util.Scanner\n\n/**\n * User: Takayuki\n * Date: 12/10/08\n */\nobject A extends App {\n\tval in = new Scanner(System.in)\n\tval n = in.nextInt()\n\tvar res = 0\n\tfor (i <- 0 until n) {\n\t\tif (in.nextInt() + in.nextInt() + in.nextInt() >= 2) {\n\t\t\tres += 1\n\t\t}\n\t}\n\tprintln(res)\n}\n"}, {"source_code": "object Hello {\n def main(args: Array[String]): Unit = {\n val n = readLine toInt\n var ans = 0\n for (i <- 1 to n) {\n val Array(a, b, c): Array[Int] = readLine split (' ') map (_ toInt)\n if (a + b + c > 1)\n ans = ans + 1\n }\n println(ans)\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\nimport scala.util.matching.Regex\n\nobject P231A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n\n def solve: Int = {\n @tailrec\n def loop(acc: Int, i: Int): Int =\n if (i == N) acc\n else {\n val P, V, T = sc.nextInt\n if (P + V + T >= 2) loop(acc + 1, i + 1)\n else loop(acc, i + 1)\n }\n loop(0, 0)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "object Team {\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in)\n\t\tval n = scanner.nextInt()\n\t\tvar count = 0\n\t\tfor (i <- 1 to n) {\n\t\t val first = scanner.nextInt()\n\t\t val second = scanner.nextInt()\n\t\t val third = scanner.nextInt()\n\t\t if (first + second + third >= 2) \n\t\t count = count + 1\n\t\t}\n\t\tprintln(count)\n\t}\n}"}, {"source_code": "import scala.io.StdIn\n\nobject A231 {\n def main(args: Array[String]) =\n println((for (i <- 1 to StdIn.readLine().toInt if StdIn.readLine().split(\" \").map(_.toInt).sum > 1) yield i).length)\n}\n"}, {"source_code": "object Codeforces231A extends App{\n\n def Checkline(ques:String):Boolean={\n var conv=ques.split(\" \")\n var conve=conv.map(_.toInt)\n var res=conve(0)+conve(1)+conve(2)\n if (res/2==1){\n return true\n }\n else{\n return false\n }\n }\n\n var ans:Int=0\n val s:Int=scala.io.StdIn.readInt\n for (i <- 1 to s){\n val k:String=scala.io.StdIn.readLine\n if (Checkline(k)==true){\n ans+=1\n }\n }\n println(ans)\n\n}\n"}, {"source_code": "import java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n\n def ans = (for(_ <- 1 to readInt) yield readInts.reduce(_ + _)).count(_ > 1)\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "/**\n * Created by vol on 9/18/14.\n */\nobject A231 extends App {\n val n = readInt()\n\n def loop(n:Int, i:Int, acc:Int):Int = {\n if (n == i) acc\n else {\n val count = readLine().split(\" \").map(_.toInt).count((e:Int) => e == 1)\n if (count >= 2) loop(n, i + 1, acc + 1) else loop(n, i + 1, acc)\n }\n }\n\n println(loop(n, 0, 0))\n\n}\n"}, {"source_code": "object test5 extends App {\n val n=readLine.toInt\n\n val list=for(i<-1 to n) yield{\n \tif(readLine.split(\" \").map(_.toInt).sum>=2) 1 else 0\n } \n println(list.sum)\n} \n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n var n = readInt()\n val tasks = (1 to n).map { unusded => \n val arr = readLine().split(\" \").map(_.toInt)\n arr.sum\n }\n println(tasks.filter(_ >= 2).size)\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Solution extends App {\n\n def solve() = {\n val n = readInt()\n val results = (1 to n).map { _ =>\n val answers = readLine().split(\" \").map(_.toInt)\n answers.count(_ == 1) > 1\n }\n\n println(results.count(_ == true))\n }\n\n solve()\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readLine.toInt\n var sum = 0\n var i = 0\n while(i < n) {\n val Array(m, n, d) = readLine.split(\" \").map(_.toInt)\n// println(m +\",\"+ n +\",\"+ d)\n if(m + n + d >= 2) sum = sum + 1\n i = i + 1\n }\n println(sum)\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject CF_231A_Team {\n def main(args: Array[String]): Unit = {\n println((for (i <- 1 to readInt) yield readLine().split(\" \").map(_.toInt).sum >= 2).count(_ == true))\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Test {\n def main(args1: Array[String]) {\n// val args = StdIn.readLine().split(\" \")\n// var (x: Long, y: Long) = (args(0).toLong, args(1).toLong)\n\n val count = StdIn.readInt\n\n var ret = 0L\n for (i <- 0 until count) {\n val a = StdIn.readLine().split(\" \")\n val sum = a.filter(s => s.equals(\"1\")).length\n if (sum > 1) {\n ret += 1\n }\n }\n println(ret)\n }\n\n}"}, {"source_code": "object TwoThreeOneA {\n\tdef main(args : Array[String]) : Unit = {\n\t\tvar sol=0\n\t\tvar n=readInt\n\t\tfor(i<-0 until n){\n\t\t\tvar ones=readLine.split(' ').count(_==\"1\")\n\t\t\tif(ones>1){\n\t\t\t\tsol+=1\n\t\t\t}\n\t\t}\n\t\tprintln(sol)\n\t}\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Team {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val problems =\n for {\n _ <- 0 until n\n x = readLine().split(\" \").map(_.toInt).reduce(_ + _)\n } yield x\n val ans = problems.filter(_ > 1).length\n println(ans)\n }\n}"}, {"source_code": "object CF231A extends App {\n import scala.io.StdIn.readLine\n val n = readLine.toInt\n var count=0\n for (_ <- 1 to n) {\n if (readLine.split(\" \").map(_.toInt).count(x => x > 0)>1)\n count+=1\n }\n print(count)\n}\n"}, {"source_code": "object Team extends App{\n\n val probNum = scala.io.StdIn.readInt()\n\n var solutions = 0\n\n for (x <- 1 to probNum) {\n val confLvl = scala.io.StdIn.readLine().split(\" \").map(k => k.toInt)\n if (confLvl.sum >= 2) solutions += 1\n else solutions\n\n //confLvl.sum\n \n }\n\n println(solutions)\n}\n"}, {"source_code": "object Team extends App{\n\n val probNum = scala.io.StdIn.readInt()\n\n val confLvl = for (i <- 1 to probNum) yield {\n if (scala.io.StdIn.readLine().split(\" \").map(k => k.toInt).sum >= 2) 1\n else 0\n }\n\n println(confLvl.sum)\n}\n"}, {"source_code": "object TaskA231 {\n def main(args: Array[String]): Unit = {\n val n = scala.io.StdIn.readInt\n var l = List[String]()\n for (i <- 0 until n) l = scala.io.StdIn.readLine :: l\n println(l.count(_.count(_ == '1') >= 2))\n }\n}"}, {"source_code": "object CF0231A extends App {\n\n val n = readInt()\n\n var count = 0\n\n (1 to n).foreach(v => {\n\n val str = readLine().split(\" \").map(_.toInt).filter(_>0).size\n if (str >= 2) count += 1\n })\n\n\n println(count)\n\n}\n"}, {"source_code": "object task231A {\n def main(args:Array[String]) {\n var rv:Int=0;\n for (l <- io.Source.stdin.getLines.toList.drop(1)) {\n val Array(a,b,c)=l.split(\" \").map(_.toInt)\n if (a+b+c>1) { rv+=1; }\n }\n println(rv)\n }\n}"}, {"source_code": "\nobject Team {\n def main(args: Array[String]) = {\n val input = Iterator.continually(scala.io.StdIn.readLine()).takeWhile(_ != null).drop(1)\n\n val solution = input.map(_.split(\" \").map(_.toInt).sum).count(_ > 1)\n\n println(solution)\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn\n\nobject Problem231A extends App {\n\n\n val n = StdIn.readInt()\n\n val total = (1 to n).map(_ => StdIn.readLine()).map(_.split(\" \").map(_.toInt).sum).filter(_ > 1).size\n println(total)\n\n\n}\n"}, {"source_code": "\n\nimport scala.io.StdIn\nobject A {\n def main(args: Array[String]): Unit = {\n var ans:StringBuilder=new StringBuilder()\n// var t=StdIn.readInt();\n var t=1\n while(t>0)\n {\n\n var n:Int=StdIn.readInt()\n// var a:Array[String]=StdIn.readLine().split(\" \")\n// var b:Array[String]=StdIn.readLine().split(\" \")\n// var c:Array[String]=StdIn.readLine().split(\" \")\n\n\n var res=0;\n for(i <- 0 until n)\n {\n var a:Array[String]=StdIn.readLine().split(\" \")\n var count=0\n if(a(0).equals(\"1\"))\n {\n count+=1;\n }\n if(a(1).equals(\"1\"))\n {\n count+=1\n }\n if(a(2).equals(\"1\"))\n {\n count+=1\n }\n\n if(count>=2)\n {\n res+=1\n }\n }\n ans.append(res).append(\"\\n\")\n\n t-=1;\n }\n println(ans.toString());\n\n\n }\n}\n"}, {"source_code": "object Main{\n def main(args:Array[String]){\n var p =0\n for(_<-1 to readLine.toInt){\n var n = 0\n for(v<-readLine.split(\" \").map(x=>x.toInt)){\n if(v==1)\n n+=1\n }\n if(n>=2)\n p+=1\n }\n println(p)\n }\n}"}, {"source_code": "object Problems_231A {\n def main(args: Array[String]) = {\n println((1 to readInt).count(_ => readLine.split(\" \").map(_.toInt).sum >= 2))\n }\n}"}, {"source_code": "object test\n{\n def main(args : Array[String])\n {\n val n = readInt\n var ans = 0\n for(i <- 0 to n-1)\n if(readLine().split(\" \").map(_.toInt).count(x => x==1) >=2)\n ans +=1;\n print (ans)\n }\n}\n"}, {"source_code": "object test extends App\n{\n print ((1 to readInt).count(x => readLine().split(' ').map(_.toInt).sum >=2))\n}"}, {"source_code": "object Main {\n\n def main(args: Array[String]): Unit = {\n var res = 0;\n for(i <- 1 to readInt()){\n if(readLine().split(' ').map(_.toInt).sum>=2)res += 1 \n }\n println(res)\n }\n\n}"}, {"source_code": "object Main {\n\n def main(args: Array[String]): Unit = {\n println((for(i <- 1 to readInt())yield if(readLine().split(' ').map(_.toInt).sum>=2) 1 else 0).sum)\n }\n\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Team_231A extends App {\n val n = readInt\n val p = (for (x <- 1 to n) yield (readLine.split(\" \").map(_.toInt)))\n\n val ans = p.foldLeft(0)((acc, cp) => {\n acc + \n (if (cp.count(_ == 1) > 1) 1 else 0)\n })\n \n println(ans)\n}"}, {"source_code": "object codeforces {\n def main(args: Array[String]): Unit = {\n val n: Int = scala.io.StdIn.readLine().toInt\n var count: Int = 0\n for (_ <- 0 until n){\n val word: String = scala.io.StdIn.readLine()\n// println(word)\n val line = word.split(\" \")\n var num: Int = 0\n for (i <- word){\n if (i == '1'){\n num+=1\n }\n }\n if (num >= 2){\n count+=1\n }\n }\n println(count)\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Cf231a extends App {\n println(Source.stdin.getLines().drop(1).map(_.split(\" \").filter(!_.isEmpty()).map(_.toInt)).map(x => if (x.sum >= 2) 1 else 0).sum)\n}"}, {"source_code": "object Team {\n import io.StdIn.{readLine => rl}\n def main(args : Array[String]) {\n val gls = io.Source.stdin.getLines\n println(gls drop(1) count(((x) => 1 < x.split(\" \").map(_.toInt).reduce(_ + _))))\n }\n}\n"}, {"source_code": "object main extends App{\n println((1 to readInt).count(_ => readLine.split(' ').map(_.toInt).sum >=2) )\n}"}, {"source_code": "object main extends App{\n val n = readLine().toInt\n var cnt = 0\n for(i <- 1 to n){\n val Array(a,b,c) = readLine.split(' ').map(_.toInt)\n if(a + b + c >=2) cnt += 1\n }\n print(cnt)\n}"}, {"source_code": "object A00231 extends App {\n def parseInt(str: String, count: Int): Seq[Int] = {\n val scanner = new java.util.Scanner(str)\n val res = (1 to count) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n def scanInts(count: Int): Seq[Int] = parseInt(Console.readLine, count)\n\n def oneIntLine = {\n val Seq(count) = scanInts(1);\n count\n }\n \n val cnt = oneIntLine\n var res = 0\n for (i <- 1 to cnt) {\n if (scanInts(3).sum > 1) res += 1\n }\n println(res)\n}\n"}, {"source_code": "object Olymp{\n def main(args: Array[String]): Unit = {\n val n = readLine toInt\n var ans = 0\n for (i <- 1 to n) {\n val Array(a, b, c): Array[Int] = readLine split (' ') map (_ toInt)\n if (a+b+c > 1)\n ans = ans + 1;\n }\n println(ans)\n }\n}"}, {"source_code": "import scala.collection.immutable.Range\nimport java.lang.String\n\nobject Olymp{\n def main(args: Array[String]): Unit = {\n val n = readLine toInt\n var ans = 0\n for (i <- 1 to n) {\n val Array(a, b, c): Array[Int] = readLine split (' ') map (_ toInt)\n if (a+b+c > 1)\n ans = ans + 1;\n }\n println(ans)\n }\n}"}, {"source_code": "object main extends App{\n println( (1 to readInt).count(_ => readLine.split(' ').map(_.toInt).sum >=2 ) )\n \n}"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject Team {\n def main(args: Array[String]) {\n val n = readInt\n val problems = for {\n i <- 1 to n\n line = readLine\n } yield line\n println(\n problems.map(l => l.split(' ').map(_.toInt).toList.sum).count(_ >= 2) \n )\n }\n}"}], "negative_code": [{"source_code": "object CF0231A extends App {\n\n val n = readInt()\n\n var count = 0\n\n (1 to n).foreach(v => {\n\n val str = readLine().split(\" \").map(_.toInt).filter(_>0).size\n if (str > 2) count += 1\n })\n\n\n println(count)\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n var n = readInt()\n val tasks = (1 to n).map { unusded => \n val arr = readLine().split(\" \").map(_.toInt)\n println(arr)\n arr.sum\n }\n println(tasks)\n println(tasks.filter(_ >= 2).size)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n var n = readInt()\n val tasks = (1 to n).map { unusded => \n val arr = readLine().split(\" \").map(_.toInt)\n arr.sum\n }\n println(tasks.filter(2 >=).size)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Problem231A extends App {\n\n\n val n = StdIn.readInt()\n\n val total = (1 to n).map(_ => StdIn.readLine()).map(_.split(\" \").map(_.toInt).sum).filter(_ > 1).sum\n println(total)\n \n\n}\n"}, {"source_code": "object Team {\n import io.StdIn.{readLine => rl}\n def main(args : Array[String]) {\n val gls = io.Source.stdin.getLines\n gls drop(1)\n println(gls count(x => 1 < x.map(_.toInt).reduce(_ + _)))\n }\n}\n"}], "src_uid": "3542adc74a41ccfd72008faf983ffab5"} {"source_code": "object CF285B extends App {\n val in = new java.util.Scanner(System.in)\n val out = new java.io.PrintWriter(System.out)\n \n val n = in.nextInt\n val s = in.nextInt\n val t = in.nextInt\n val v = for (i <- 1 to n) yield in.nextInt \n def sol(x: Int, c: Int): Int =\n if (x == t) c\n else {\n val next = v(x-1)\n if (c > n || next == s) -1\n else sol(next, c+1)\n }\n\n out.println(sol(s, 0))\n out.flush\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P285B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val S, T = sc.nextInt - 1\n val P = Array.fill(N)(sc.nextInt - 1)\n\n var n = 0\n var i = S\n breakable {\n while (true) {\n if (i == T) break\n else if (P(i) == -1) {\n n = -1\n break\n }\n else {\n val j = i\n i = P(i)\n P(j) = -1\n n = n + 1\n }\n }\n }\n\n out.println(n)\n out.close\n}\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val Array(n, s, t) = readInts\n val a = readInts\n @tailrec\n def rec(moves: Int, pos: Int): Int = if(pos == s && moves != 0) -1 else if(pos == t) moves else rec(moves + 1, a(pos - 1))\n def ans = rec(0, s)\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val nst = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt)\n val n = nst(0)\n val s = nst(1)\n val t = nst(2)\n \n var cur = s\n var step = 0\n \n for {\n _ <- 1 to n\n if step != -1\n if cur != t\n } {\n val next = a(cur - 1)\n if (next == s) step = -1\n else {\n step += 1\n cur = next\n } \n }\n \n println(step)\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, sn, tn) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt - 1)\n val s = sn - 1\n var c = s\n val t = tn - 1\n var i = 0\n val marked = Array.ofDim[Boolean](n)\n while (!marked(c) && c != t) {\n marked(c) = true\n c = data(c)\n i += 1\n }\n if (c == t)\n println(i)\n else\n println(-1)\n\n}\n"}], "negative_code": [], "src_uid": "b01602b51b9103c0f31c3f50b32aa88d"} {"source_code": "import scala.util.control.Breaks\n\nobject Polygon {\n def main(args: Array[String]): Unit = {\n val in = scala.io.StdIn\n val t = in.readLine().toInt\n for (t <- 0 until t) {\n val n = in.readLine().toInt\n val arr = Array.ofDim[Int](n, n)\n for (i <- 0 until n) {\n val row = in.readLine()\n for (j <- 0 until n) {\n arr(i)(j) = row(j) - 48\n }\n }\n var flag = false\n Breaks.breakable {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n if (arr(i)(j) == 1 && i != arr.length-1 && j != arr(0).length-1 && arr(i + 1)(j) != 1 && arr(i)(j + 1) != 1) {\n flag = true\n Breaks.break()\n }\n }\n }\n }\n println(if(flag) \"NO\" else \"YES\")\n }\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CF644(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CF644(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val n = ni()\n a = Array.ofDim[Int](n,n)\n conn = Array.fill[Boolean](n,n)(false)\n REP(n) { i =>\n val s = ns(n)\n REP(n) { j =>\n a(i)(j) = s(j) - '0'\n if(j == n-1 && a(i)(j) == 1) conn(i)(j) = true\n if(i == n-1 && a(i)(j) == 1) conn(i)(j) = true\n }\n }\n\n vis = Array.fill[Int](n,n)(0)\n REP(n) { i =>\n if(a(i)(n-1) == 1) {\n var j = 1\n while (n-j-1 >=0 && a(i)(n-j-1) == 1) {\n conn(i)(n-j-1) = true\n j += 1\n }\n }\n if(a(n-1)(i) == 1) {\n var j = 1\n while (n-j-1 >=0 && a(n-j-1)(i) == 1) {\n conn(n-j-1)(i) = true\n j += 1\n }\n }\n }\n var yes = true\n REP_r(n-1) { i =>\n REP_r(n-1) { j =>\n if(a(i)(j) == 1 && !conn(i)(j)) {\n conn(i)(j) = conn(i+1)(j) | conn(i)(j+1)\n }\n if(a(i)(j) == 1 && !conn(i)(j)) yes = false\n }\n }\n if(yes)\n out.println(\"YES\")\n else out.println(\"NO\")\n }\n }\n var a: Array[Array[Int]] = _\n var conn: Array[Array[Boolean]] = _\n var vis: Array[Array[Int]] = _\n}\n"}, {"source_code": "object E extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val pn = (0 until n).foldLeft(Array.ofDim[Array[Byte]](n)) { (pn, i) =>\n pn(i) = scala.io.StdIn.readLine().split(\"\").map(_.toByte)\n pn\n }\n\n val ans = pn.init.zipWithIndex.forall {\n case (p, i) =>\n p.zip(p.tail).corresponds(pn(i + 1).init) {\n case ((u, r), d) =>\n u == 0 || d == 1 || r == 1\n }\n }\n\n if (ans) println(\"YES\")\n else println(\"NO\")\n }\n}\n"}], "negative_code": [], "src_uid": "eea15ff7e939bfcc7002cacbc8a1a3a5"} {"source_code": "object D {\n def main(args: Array[String]) {\n val n = readLine.toInt;\n var a = readLine.split(\" \").toList.map(_.toLong)\n\n a = {\n var sum = 0L\n a.reverse.map { v =>\n if (sum >= 0) {\n sum -= v\n -v\n } else {\n sum += v\n v\n }\n }.reverse\n }\n\n if (a.sum < 0) {\n a = a.map(-_)\n }\n a.foreach { v =>\n if (v >= 0) {\n print(\"+\")\n } else {\n print(\"-\")\n }\n }\n }\n}\n", "positive_code": [{"source_code": "\n\nobject test5 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n val c=new Array[Char](n)\n \n var sum=0\n def solve()={\n for(i<-n-1 to 0 by -1){\n if(sum>0){\n sum-=a(i)\n c(i)='-'\n }\n else{\n sum+=a(i)\n c(i)='+'\n }\n }\n }\n\n solve()\n \n if(sum>0){\n println(c.mkString)\n }\n else{\n println(c.map(c=>if(c=='+') '-' else '+').mkString)\n }\n}\n\n\n\n\n"}, {"source_code": "\n\nobject test5 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n val c=new Array[Char](n)\n \n var sum=0\n\n for(i<-n-1 to 0 by -1){\n if(sum>0){\n sum-=a(i)\n c(i)='-'\n }\n else{\n sum+=a(i)\n c(i)='+'\n }\n }\n \n if(sum>0){\n println(c.mkString)\n }\n else{\n println(c.map(c=>if(c=='+') '-' else '+').mkString)\n }\n}\n\n\n\n\n"}, {"source_code": "import scala.util.Sorting._\nimport math._\nimport scala.Array\n\nobject Contest extends App {\n val n = readInt()\n val arr = readLine().split(\" \").map(_.toInt).reverse\n var cur = 0\n var ans: StringBuilder = new StringBuilder\n for (i <- arr){\n if (abs(cur - i) < abs(cur + i)){\n ans.append(\"-\")\n cur -= i\n }\n else{\n ans.append(\"+\")\n cur += i\n }\n }\n ans = ans.reverse\n if (cur < 0){\n var t: StringBuilder = new StringBuilder\n for (c <- ans)\n if (c == '+') t.append(\"-\") else t.append(\"+\")\n ans = t\n }\n println(ans)\n}\n"}, {"source_code": "\n\nobject test5 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n val c=new Array[Char](n)\n \n def solve()={\n for(i<-n-2 to 0 by -1){\n if(sum>0){\n sum-=a(i)\n c(i)='-'\n }\n else{\n sum+=a(i)\n c(i)='+'\n }\n }\n }\n var sum=a.last\n c(n-1)='+'\n solve()\n \n if(sum>0){\n println(c.mkString)\n }\n else{\n println(c.map(c=>if(c=='+') '-' else '+').mkString)\n }\n}\n\n\n\n\n"}], "negative_code": [{"source_code": "import scala.util.Sorting._\nimport math._\nimport scala.Array\n\nobject Contest extends App {\n val n = readInt()\n val arr = readLine().split(\" \").map(_.toInt).reverse\n var cur = 0\n var ans = \"\"\n for (i <- arr){\n if (abs(cur - i) < abs(cur + i)){\n ans += \"-\"\n cur -= i\n }\n else{\n ans += ans\n cur += i\n }\n }\n ans = ans.reverse\n if (cur < 0){\n var t = \"\"\n for (c <- ans)\n if (c == '+') t += \"-\" else t += \"+\"\n ans = t\n }\n println(ans)\n}\n"}, {"source_code": "\n\nobject test5 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n val c=new Array[Char](n)\n \n def solve()={\n for(i<-n-2 to 0 by -1){\n if(sum>0){\n sum-=a(i)\n c(i)='-'\n }\n else{\n sum+=a(i)\n c(i)='+'\n }\n }\n }\n var sum=a.last\n c(n-1)='+'\n solve()\n \n if(sum>=0 && sum<=a.head){\n println(c.mkString)\n exit(0)\n }\n \n sum= -a.last\n c(n-1)='-'\n solve()\n if(sum>=0 && sum<=a.head){\n println(c.mkString)\n }\n else println(\"fuck\")\n}\n\n\n\n\n"}, {"source_code": "\n\nobject test5 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n val c=new Array[Char](n)\n \n def solve()={\n for(i<-n-2 to 0 by -1){\n if(sum>0){\n sum-=a(i)\n c(i)='-'\n }\n else{\n sum+=a(i)\n c(i)='+'\n }\n }\n }\n var sum=a.last\n c(n-1)='+'\n solve()\n \n if(sum>=0 && sum<=a.head){\n println(c.mkString)\n exit(0)\n }\n \n sum= -a.last\n c(n-1)='-'\n solve()\n println(c.mkString)\n}\n\n\n\n\n"}, {"source_code": "object D {\n def main(args: Array[String]) {\n val n = readLine.toInt;\n var a = readLine.split(\" \").toList.map(_.toLong)\n\n var sum = 0L\n\n a = a.reverse.map { v =>\n if (sum >= 0) {\n sum -= v\n -v\n } else {\n sum += v\n v\n }\n }.reverse\n\n if (a.sum < 0) {\n a.map(-_)\n }\n a.foreach { v =>\n if (v >= 0) {\n print(\"+\")\n } else {\n print(\"-\")\n }\n }\n }\n}\n"}], "src_uid": "30f64b963310911196ebf5d624c01cc3"} {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _749A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n = read[Int]\n\n val ans = if (n%2 == 0) {\n Vector.fill(n/2)(2)\n } else {\n Vector.fill((n-3)/2)(2) :+ 3\n }\n\n write(ans.length).writeLine().writeAll(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object BachgoldProblem extends App{\n val n = io.StdIn.readInt()\n println(n / 2)\n println(n match{\n case n if n <= 3 => n\n case n if n % 2 == 0 => \"2\" + \" 2\" * (n / 2 - 1)\n case _ => \"2\" + \" 2\" * (n / 2 - 2) + \" 3\"\n })\n}\n"}, {"source_code": "object A749 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n println(n/2)\n if(n%2 == 1) {\n println(\"3\" ++ \" 2\" * ((n-2)/2))\n } else {\n println(\"2 \" * (n/2))\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "object A749 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n if(n%2 == 1) {\n println(\"3\" ++ \" 2\" * ((n-2)/2))\n } else {\n println(\"2 \" * (n/2))\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object BachgoldProblem extends App{\n val n = io.StdIn.readInt()\n println(n / 2)\n if(n % 2 == 0) println(\"2\" + \" 2\" * (n / 2 - 1))\n else println(\"2\" + \" 2\" * (n / 2 - 2) + \" 3\")\n}\n"}], "src_uid": "98fd00d3c83d4b3f0511d8afa6fdb27b"} {"source_code": "object C extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n var a = Array.ofDim[Array[Int]](n)\n (0 until n).foreach(a(_) = readLine().split(\" \").map(_.toInt))\n\n var b = Array.fill((n + m) / 2)(Array(0, 0))\n for {\n i <- 1 to n\n j <- 1 to m\n k = i + j - 2\n d = k min (n + m - 2 - k)\n } b(d)(a(i - 1)(j - 1)) += 1\n\n val ans = b.take((n + m - 1) / 2).foldLeft(0)((a, t) => a + t.min)\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nm = readIntLine()\n val grid = (1 to nm.head).map(_ => readIntLine().toArray).toArray\n val isNSmall = nm.head <= nm.last\n println(calc(math.min(nm.head, nm.last), math.max(nm.head, nm.last),\n if (isNSmall) grid else grid.transpose))\n }\n }\n\n // assume n <= m\n def calc(n: Int, m: Int, grid: Array[Array[Int]]): Int = {\n var total = 0\n for (i <- 0 to (m + n - 3) / 2) {\n var zeroCount = 0\n var oneCount = 0\n for (j <- 0 to math.min(i, n - 1)) {\n if (grid(j)(i - j) == 0) zeroCount += 1 else oneCount += 1\n if (grid(n - 1 - j)(m - 1 - i + j) == 0) zeroCount += 1 else oneCount += 1\n }\n total += math.min(zeroCount, oneCount)\n }\n\n total\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n// def printArray[T](arr: Array[T]): Unit = {\n// val str = new StringBuilder()\n// str.addAll((if (arr.head == -1) 0 else arr.head).toString)\n// // print(arr(0))\n// for (i <- 1 until arr.length) {\n// str.addAll(\" \" + (if (arr(i) == -1) 0 else arr(i)))\n// }\n// println(str)\n// }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nm = readIntLine()\n val grid = (1 to nm.head).map(_ => readIntLine().toArray).toArray\n val isNSmall = nm.head <= nm.last\n println(calc(math.min(nm.head, nm.last), math.max(nm.head, nm.last),\n if (isNSmall) grid else grid.transpose))\n }\n }\n\n // assume n <= m\n def calc(n: Int, m: Int, grid: Array[Array[Int]]): Int = {\n var total = 0\n for (i <- 0 to m / 2) {\n var zeroCount = 0\n var oneCount = 0\n for (j <- 0 to math.min(i, n - 1)) {\n if (grid(j)(i - j) == 0) zeroCount += 1 else oneCount += 1\n if (grid(n - 1 - j)(m - 1 - i + j) == 0) zeroCount += 1 else oneCount += 1\n }\n total += math.min(zeroCount, oneCount)\n }\n\n total\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n// def printArray[T](arr: Array[T]): Unit = {\n// val str = new StringBuilder()\n// str.addAll((if (arr.head == -1) 0 else arr.head).toString)\n// // print(arr(0))\n// for (i <- 1 until arr.length) {\n// str.addAll(\" \" + (if (arr(i) == -1) 0 else arr(i)))\n// }\n// println(str)\n// }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nm = readIntLine()\n val grid = (1 to nm.head).map(_ => readIntLine().toArray).toArray\n val isNSmall = nm.head <= nm.last\n println(calc(math.min(nm.head, nm.last), math.max(nm.head, nm.last),\n if (isNSmall) grid else grid.transpose))\n }\n }\n\n // assume n <= m\n def calc(n: Int, m: Int, grid: Array[Array[Int]]): Int = {\n var total = 0\n for (i <- 0 to (m - (n - 1) % 2) / 2) {\n var zeroCount = 0\n var oneCount = 0\n for (j <- 0 to math.min(i, n - 1)) {\n if (grid(j)(i - j) == 0) zeroCount += 1 else oneCount += 1\n if (grid(n - 1 - j)(m - 1 - i + j) == 0) zeroCount += 1 else oneCount += 1\n }\n total += math.min(zeroCount, oneCount)\n }\n\n total\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n// def printArray[T](arr: Array[T]): Unit = {\n// val str = new StringBuilder()\n// str.addAll((if (arr.head == -1) 0 else arr.head).toString)\n// // print(arr(0))\n// for (i <- 1 until arr.length) {\n// str.addAll(\" \" + (if (arr(i) == -1) 0 else arr(i)))\n// }\n// println(str)\n// }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nm = readIntLine()\n val grid = (1 to nm.head).map(_ => readIntLine().toArray).toArray\n val isNSmall = nm.head <= nm.last\n println(calc(math.min(nm.head, nm.last), math.max(nm.head, nm.last),\n if (isNSmall) grid else grid.transpose))\n }\n }\n\n // assume n <= m\n def calc(n: Int, m: Int, grid: Array[Array[Int]]): Int = {\n var total = 0\n for (i <- 0 to (m - 1) / 2) {\n var zeroCount = 0\n var oneCount = 0\n for (j <- 0 to math.min(i, n - 1)) {\n if (grid(j)(i - j) == 0) zeroCount += 1 else oneCount += 1\n if (grid(n - 1 - j)(m - 1 - i + j) == 0) zeroCount += 1 else oneCount += 1\n }\n total += math.min(zeroCount, oneCount)\n }\n\n total\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n// def printArray[T](arr: Array[T]): Unit = {\n// val str = new StringBuilder()\n// str.addAll((if (arr.head == -1) 0 else arr.head).toString)\n// // print(arr(0))\n// for (i <- 1 until arr.length) {\n// str.addAll(\" \" + (if (arr(i) == -1) 0 else arr(i)))\n// }\n// println(str)\n// }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}], "src_uid": "b62586b55bcfbd616d936459c30579a6"} {"source_code": "object B extends App {\r\n\r\n def swaps(an: IndexedSeq[Int], bn: IndexedSeq[Int]): Int = {\r\n val n = an.length\r\n val element2index = Array.fill(2 * n + 1)(0)\r\n (0 until n).foreach { i =>\r\n element2index(an(i)) = i\r\n element2index(bn(i)) = i\r\n }\r\n\r\n val minOddIndex = element2index(1)\r\n val minEvenIndex = element2index(2)\r\n\r\n (3 to (2 * n))\r\n .foldLeft((minOddIndex + minEvenIndex, minOddIndex, minEvenIndex)) {\r\n case ((count, minOddIndex, minEvenIndex), element) =>\r\n val index = element2index(element)\r\n if (element % 2 == 0) {\r\n (count min (index + minOddIndex), minOddIndex, minEvenIndex min index)\r\n } else {\r\n (count, minOddIndex min index, minEvenIndex)\r\n }\r\n }\r\n ._1\r\n\r\n // val aj2j = Array.fill(2 * an.length)(0)\r\n // an.indices.foreach(j => aj2j(an(j)) = j)\r\n\r\n // bn.indices.foldLeft(Int.MaxValue) { (count, i) =>\r\n // val bi = bn(i)\r\n // val aj = (1 to (bi, 2)).minBy(aj2j)\r\n // val j = aj2j(aj)\r\n // count min (i + j)\r\n // }\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val an = nextInts(n)\r\n val bn = nextInts(n)\r\n\r\n out.println(swaps(an, bn))\r\n out.flush()\r\n }\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable._\r\nimport scala.math.min\r\n\r\nobject test {\r\n val writer = new PrintWriter(System.out)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\r\n def readInt(): Int = next().toInt\r\n def readLong(): Long = next().toLong\r\n def readString(): String = next()\r\n\r\n def RecursiveBinarySearch(Element_to_Search: Int)\r\n (low: Int,\r\n high: Int): Int =\r\n {\r\n // If element not found\r\n if (high - low <= 1) {\r\n if (a_row(low) < Element_to_Search)\r\n return low\r\n else\r\n return high\r\n }\r\n\r\n // Getting the middle element\r\n var middle = low + (high - low + 1) / 2\r\n\r\n // If element found\r\n\r\n // Searching in the left half\r\n if (a_row(middle) < Element_to_Search)\r\n return RecursiveBinarySearch(Element_to_Search)(low, middle)\r\n\r\n // Searching in the right half\r\n else\r\n return RecursiveBinarySearch(Element_to_Search)(middle + 1, high)\r\n }\r\n val a_row = new ArrayBuffer[Int]()\r\n\r\n def main(args: Array[String]): Unit = {\r\n val t = readInt()\r\n for (tt <- 1 to t) {\r\n val n = readInt()\r\n a_row.clear()\r\n var min_s = 2 * n + 1\r\n for (i <- 1 to n) {\r\n val tmp = readInt()\r\n min_s = min(min_s, tmp)\r\n a_row.append(min_s)\r\n }\r\n var ans = n + 1\r\n for (i <- 1 to n) {\r\n val tmp = readInt()\r\n ans = min(ans, i-1+RecursiveBinarySearch(tmp)(0, n-1))\r\n }\r\n writer.println(ans)\r\n writer.flush()\r\n }\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n\r\n def swaps(an: IndexedSeq[Int], bn: IndexedSeq[Int]): Int = {\r\n val n = an.length\r\n val ab2i = Array.fill(2 * n + 1)(0)\r\n (0 until n).foreach { i => ab2i(an(i)) = i; ab2i(bn(i)) = i }\r\n\r\n (3 to (2 * n))\r\n .foldLeft((ab2i(1) + ab2i(2), ab2i(1), ab2i(2))) { case ((count, odd, even), ab) =>\r\n val i = ab2i(ab)\r\n (ab % 2) match {\r\n case 0 => (count min (i + odd), odd, even min i)\r\n case _ => (count, odd min i, even)\r\n }\r\n }\r\n ._1\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val an = nextInts(n)\r\n val bn = nextInts(n)\r\n\r\n out.println(swaps(an, bn))\r\n out.flush()\r\n }\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object B extends App {\r\n\r\n def swaps(an: Seq[Int], bn: Seq[Int]): Int = {\r\n\r\n def search(from: Int, to: Int, f: Int => Boolean): Int = {\r\n @annotation.tailrec\r\n def go(left: Int, right: Int): Int =\r\n if (left + 1 >= right) left\r\n else {\r\n val middle = (left + right) >>> 1\r\n\r\n f(middle) match {\r\n case true => go(middle, right)\r\n case false => go(left, middle)\r\n }\r\n }\r\n go(from, to)\r\n }\r\n\r\n val cn = an.zipWithIndex.sorted\r\n\r\n bn.zipWithIndex.foldLeft(Int.MaxValue) { case (count, (bi, i)) =>\r\n val j = search(0, cn.length, j => cn(j)._1 < bi)\r\n count min (i + cn(j)._2)\r\n }\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val an = nextInts(n)\r\n val bn = nextInts(n)\r\n\r\n out.println(swaps(an, bn))\r\n out.flush()\r\n }\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n\r\n def swaps(an: Seq[Int], bn: Seq[Int]): Int = {\r\n\r\n def search(from: Int, to: Int, f: Int => Boolean): Int = {\r\n @annotation.tailrec\r\n def go(left: Int, right: Int): Int =\r\n if (left + 1 >= right) left\r\n else {\r\n val middle = (left + right) >>> 1\r\n\r\n f(middle) match {\r\n case true => go(middle, right)\r\n case false => go(left, middle)\r\n }\r\n }\r\n go(from, to)\r\n }\r\n\r\n val cn = an.zipWithIndex.sorted\r\n\r\n bn.zipWithIndex.foldLeft(Int.MaxValue) { case (count, (bi, i)) =>\r\n val j = search(0, cn.length, j => cn(j)._1 < bi)\r\n count min (i + cn(j)._2)\r\n }\r\n }\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n val bn = readLine().split(\" \").map(_.toInt)\r\n\r\n println(swaps(an, bn))\r\n }\r\n}\r\n"}], "src_uid": "55a1e9236cac9a6044e74b1975331535"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toLong)\n val sum = data.tail.scan(data.head){_ + _}\n val sorted = data.sorted\n val sorsum = sorted.tail.scan(sorted.head){_ + _}\n val q = in.next().toInt\n val res = (1 to q).map { _ =>\n val Array(queryType, l, r) = in.next().split(\" \").map(_.toInt)\n if (queryType == 1) {\n sum(r - 1) - (if (l >= 2) sum(l - 2) else 0)\n } else {\n sorsum(r - 1) - (if (l >= 2) sorsum(l - 2) else 0)\n }\n }\n println(res.mkString(\"\\n\"))\n}", "positive_code": [{"source_code": "import scala.util.Try\n\nobject B433 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readLongs(n)\n val sorted = input.sortBy(identity)\n for(i <- 1 until n) {\n input(i) += input(i-1)\n }\n for(i <- 1 until n) {\n sorted(i) += sorted(i-1)\n }\n\n val Array(m) = readInts(1)\n for(_ <- 0 until m) {\n val Array(t, l, r) = readInts(3)\n if(t == 1) {\n if(l-2 >= 0)\n println(input(r-1) - input(l-2))\n else\n println(input(r-1))\n } else {\n if(l-2 >= 0)\n println(sorted(r-1) - sorted(l-2))\n else\n println(sorted(r-1))\n }\n }\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.nio.CharBuffer\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.PriorityQueue\nimport scala.math.Ordering.Implicits._\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject B extends App {\n // val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n object Input {\n import java.lang.Character._\n\n lazy val in = new BufferedReader(new InputStreamReader(java.lang.System.in))\n var buf: Array[Char] = Array()\n var pos: Int = 0\n\n def next(): String = {\n while (pos == buf.length) {\n buf = in.readLine.toArray\n pos = 0\n }\n while (isWhitespace(buf(pos))) {\n pos += 1\n }\n while (pos == buf.length) {\n buf = in.readLine.toArray\n pos = 0\n }\n val s = pos\n while (pos < buf.length && !isWhitespace(buf(pos))) {\n pos += 1\n }\n new java.lang.String(buf, s, pos - s)\n }\n\n def nextInt(): Int = next.toInt\n\n def nextLong(): Long = next.toLong\n\n def nextFloat(): Float = next.toFloat\n\n def nextDouble(): Double = next.toDouble\n\n val nextString: () => String = next _\n }\n\n import Input._\n\n val N = nextInt\n val V = Array.fill(N)(nextLong)\n val U = V.sorted\n val vv = Array.fill(N + 1)(0L)\n val uu = Array.fill(N + 1)(0L)\n (0 until N).foreach { i =>\n vv(i + 1) = vv(i) + V(i)\n uu(i + 1) = uu(i) + U(i)\n }\n val M = nextInt\n\n def solve(): Long = {\n\n def type1(l: Int, r: Int): Long = vv(r + 1) - vv(l)\n\n def type2(l: Int, r: Int): Long = uu(r + 1) - uu(l)\n\n val t = nextInt\n val l, r = nextInt - 1\n t match {\n case 1 => type1(l, r)\n case 2 => type2(l, r)\n case _ => throw new Exception(\"something wrong\")\n }\n }\n\n\n for (_ <- 0 until M) out.println(solve)\n out.flush\n}\n"}], "negative_code": [], "src_uid": "c764b9f87cb5e5872eb157c3d2b7f3c5"} {"source_code": "object Solver {\r\n import InOut._\r\n def main(args: Array[String]): Unit = {\r\n for (_ <- 1 to nextInt) {\r\n val n = nextInt\r\n val arr = nextInts(n)\r\n var ans = \"NO\"\r\n for (num <- arr) {\r\n val rt = Math.round(Math.sqrt(num))\r\n if (rt * rt != num)\r\n ans = \"YES\"\r\n }\r\n out.println(ans)\r\n }\r\n out.flush()\r\n }\r\n}\r\n\r\nfinal object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n def nextToken: String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new java.util.StringTokenizer(in.readLine)\r\n tokenizer.nextToken\r\n }\r\n def nextInt = Integer.parseInt(nextToken)\r\n def nextLong = java.lang.Long.parseLong(nextToken)\r\n def nextBig = BigInt(nextToken)\r\n def nextInts(n: Int) = Array.fill(n) { nextInt }\r\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\r\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\r\n def nextLine = in.readLine\r\n}", "positive_code": [{"source_code": "object cf1514a {\n\n def readInt(): Int = {\n\t\tConsole.in.readLine().toInt\n\t}\n\n def readLong(): Long= {\n\t\tConsole.in.readLine().toLong\n\t}\n\n\tdef readInts(): Array[Int] = {\n\t\tval line = Console.in.readLine()\n\t\tline.split(' ').map( _.toInt)\n\t}\n\n\tdef main(args: Array[String]): Unit = {\n\t\tval cases = readInt()\n\t\tvar nCase = 0\n\t\tval res = for (nCase <- 1 to cases) yield {\n\t\t\treadInt()\n\t\t\tval data = readInts()\n\n\t\t\t!data.forall( v => {\n\t\t\t\tval sq = Math.floor(Math.sqrt(v)).toInt\n\t\t\t\tsq*sq == v\n\t\t\t})\n\t\t}\n\t\tres.foreach(if (_) println(\"YES\") else println(\"NO\"))\n }\n}"}], "negative_code": [], "src_uid": "33a31edb75c9b0cf3a49ba97ad677632"} {"source_code": "import java.io._\n\nobject C extends App {\n\tval n = InputReader.readLine.toInt\n\tvar arr = InputReader.readLine.split(\" \").map(_.toLong)\n\n\tdef op(par: Array[Long], e: Long) = {\n\t\tif(e > par(0))\n\t\t\tArray(e, par(0))\n\n\t\telse if(e > par(1))\n\t\t\tArray(par(0), e)\n\n\t\telse par\n\t}\n\n\tval res = arr.foldLeft(Array(0L, 0L))(op)\n\tval s = arr.sum\n\n\tdef whom = (x: Long) => if (x == res(0)) res(1) else res(0)\n\tval ans = arr.zipWithIndex.filter(x => s - x._1 == 2 * whom(x._1))\n\n\tval out = new PrintWriter(System.out)\n\tout.println(ans.length)\n\tans.foreach(x => out.print(s\"${x._2 + 1} \"))\n\tout.close\n}\n\nobject InputReader {\n\tval rd = new BufferedReader(new InputStreamReader(System.in), 32768);\n\tdef readLine() = rd.readLine\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val S = sumL(A)\n val mx = A.max\n val mxIx = A.indexWhere(_ == mx)\n val A2 = A.take(mxIx) ++ A.drop(mxIx + 1)\n val mx2 = A2.max\n val mx2Ix = A2.indexWhere(_ == mx2)\n val S1 = S - mx\n\n val ans = ArrayBuffer[Int]()\n rep(N) { i =>\n if (A(i) == mx) {\n if (S1 - mx2 == mx2) ans += i + 1\n } else {\n if (S1 - A(i) == mx) ans += i + 1\n }\n }\n\n out.println(ans.length)\n out.println(ans.mkString(\" \"))\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object CF_521_3_C {\n // The \"good\" number must always be the largest\n // In the case where we're examining the max for niceness, use the second largest\n // An element e is nice if the subtotal of the rest is 2 * the max, i.e. total - e = 2 *\n\n def solve(n: Int, as: Seq[Long]): (Int, Seq[Int]) = {\n val total = as.sum\n val max = as.max\n val secondMax = as.diff(Seq(max)).max\n val nices = for {\n (e, i) <- as.zipWithIndex\n if (e != max && total - e == 2 * max) || (e == max && total - e == 2 * secondMax)\n } yield i + 1\n (nices.size, nices)\n }\n\n // `solution` is defined by the input format - and can be called both from main and test script without repeating\n def solution(i: Input) = solve(i.int, {i.nextLine; i.collect(_.toLong)})\n\n \n// ~~~ Boilerplate that doesn't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n def main(args: Array[String]) = {\n val out = new java.io.PrintWriter(System.out)\n val sol = solution(new Input(System.in))\n out.println(sol._1)\n out.println(sol._2 mkString \" \")\n out.close()\n }\n\n// ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n import java.util.Scanner\n class Input(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine() \n // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n }\n\n def ceil(a: Int, b: Int) = (a - 1) / b + 1\n def ceil(a: Long, b: Long) = (a - 1) / b + 1\n\n import language.implicitConversions\n implicit def stringToInput(s: String): Input = new Input(s)\n}"}, {"source_code": "import java.io._\n\nobject C extends App {\n\tval n = InputReader.readLine.toInt\n\tvar arr = InputReader.readLine.split(\" \").map(_.toLong)\n\n\tval res = arr.foldLeft(Array(0L, 0L)) (\n\t\t(par, e) => {\n\t\t\tif(e > par(0))\n\t\t\t\tArray(e, par(0))\n\n\t\t\telse if(e > par(1))\n\t\t\t\tArray(par(0), e)\n\n\t\t\telse par\n\t\t}\n\t)\n\n\tval s = arr.sum\n\tdef whom(x: Long) = if (x == res(0)) res(1) else res(0)\n\tval ans = arr.zipWithIndex.filter(x => s - x._1 == 2 * whom(x._1))\n\n\tval out = new PrintWriter(System.out)\n\tout.println(ans.length)\n\tans.foreach(x => out.print(s\"${x._2 + 1} \"))\n\tout.close\n}\n\nobject InputReader {\n\tval rd = new BufferedReader(new InputStreamReader(System.in), 32768);\n\tdef readLine() = rd.readLine\n}"}], "negative_code": [{"source_code": "import java.io._\n\nobject C extends App {\n\tval n = InputReader.readLine.toInt\n\tvar arr = InputReader.readLine.split(\" \").map(_.toInt)\n\n\tdef op(par: Array[Int], e: Int) = {\n\t\tif(e > par(0))\n\t\t\tArray(e, par(1))\n\n\t\telse if(e > par(1))\n\t\t\tArray(par(0), e)\n\n\t\telse par\n\t}\n\n\tval res = arr.foldLeft(Array(0, 0))(op)\n\tval s = arr.sum\n\n\tdef whom = (x: Int) => if (x == res(0)) res(1) else res(0)\n\tval ans = arr.zipWithIndex.filter(x => s - x._1 == 2 * whom(x._1))\n\t\n\t// println(ans.length)\n\t// ans.foreach(x => print(s\"${x._2 + 1} \"))\n\n\tval out = new PrintWriter(System.out)\n\tout.println(ans.length)\n\tans.foreach(x => out.print(s\"${x._2 + 1} \"))\n\tout.close\n}\n\nobject InputReader {\n\tval rd = new BufferedReader(new InputStreamReader(System.in), 32768);\n\tdef readLine() = rd.readLine\n}"}, {"source_code": "import java.io._\n\nobject C extends App {\n\tval n = InputReader.readLine.toInt\n\tvar arr = InputReader.readLine.split(\" \").map(_.toLong)\n\n\tdef op(par: Array[Long], e: Long) = {\n\t\tif(e > par(0))\n\t\t\tArray(e, par(1))\n\n\t\telse if(e > par(1))\n\t\t\tArray(par(0), e)\n\n\t\telse par\n\t}\n\n\tval res = arr.foldLeft(Array(0L, 0L))(op)\n\tval s = arr.sum\n\n\tdef whom = (x: Long) => if (x == res(0)) res(1) else res(0)\n\tval ans = arr.zipWithIndex.filter(x => s - x._1 == 2 * whom(x._1))\n\n\tval out = new PrintWriter(System.out)\n\tout.println(ans.length)\n\tans.foreach(x => out.print(s\"${x._2 + 1} \"))\n\tout.close\n}\n\nobject InputReader {\n\tval rd = new BufferedReader(new InputStreamReader(System.in), 32768);\n\tdef readLine() = rd.readLine\n}"}, {"source_code": "import java.io._\n\nobject C extends App {\n\tval n = InputReader.readLine.toInt\n\tvar arr = InputReader.readLine.split(\" \").map(_.toInt)\n\n\tdef op(par: Array[Int], e: Int) = {\n\t\tif(e > par(0))\n\t\t\tArray(e, par(1))\n\n\t\telse if(e > par(1))\n\t\t\tArray(par(0), e)\n\n\t\telse par\n\t}\n\n\tval res = arr.foldLeft(Array(0, 0))(op)\n\tval s = arr.sum\n\n\tdef whom = (x: Int) => if (x == res(0)) res(1) else res(0)\n\tval ans = arr.zipWithIndex.filter(x => s - x._1 == 2 * whom(x._1))\n\t\n\t// println(ans.length)\n\t// ans.foreach(x => print(s\"${x._2 + 1} \"))\n\n\tval out = new PrintWriter(System.out)\n\tout.println(ans.length)\n\tans.foreach(x => out.print(s\"${x._2 + 1} \"))\n}\n\nobject InputReader {\n\tval rd = new BufferedReader(new InputStreamReader(System.in), 32768);\n\tdef readLine() = rd.readLine\n}"}, {"source_code": "object CF_521_3_C {\n def isGood(xs: Map[Long,Int], sum: Long) = sum % 2 == 0 && xs(sum/2) > 0\n\n def solve(n: Int, as: Seq[Long]): (Int, Seq[Int]) = {\n val total = as.sum\n val counts: Map[Long, Int] = as.groupBy(identity).mapValues(_.size).withDefaultValue(0)\n val nices = for {\n (a, i) <- as.zipWithIndex\n if isGood(counts + (a -> (counts(a) - 1)), total - a)\n } yield i + 1\n (nices.size, nices)\n }\n\n // `solution` is defined by the input format - and can be called both from main and test script without repeating\n def solution(i: Input) = solve(i.int, {i.nextLine; i.collect(_.toLong)})\n\n \n// ~~~ Boilerplate that doesn't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n def main(args: Array[String]) = {\n val out = new java.io.PrintWriter(System.out)\n val sol = solution(new Input(System.in))\n out.println(sol)\n out.close()\n }\n\n// ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n import java.util.Scanner\n class Input(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine() \n // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n }\n\n def ceil(a: Int, b: Int) = (a - 1) / b + 1\n def ceil(a: Long, b: Long) = (a - 1) / b + 1\n\n import language.implicitConversions\n implicit def stringToInput(s: String): Input = new Input(s)\n}"}], "src_uid": "4cf0fe49f7ebf058317ac848043031a5"} {"source_code": "import scala.collection._\nimport java.util.Arrays\nimport scala.util.Random\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n //var as = Array.fill(n){ if (Random.nextInt(100) < 49) 1 else 0}\n val cs = Array.ofDim[Int](n)\n \n var bs = Array.ofDim[Int](n)\n \n cs(0) = as(0)\n cs(n - 1) = as(n - 1)\n \n var prev = as(0)\n var max = 0\n var cnt0 = 1\n var start = 0\n for (i <- 1 until n) {\n if (as(i) != prev) {\n if (cnt0 > max) max = cnt0\n cnt0 += 1\n prev = as(i)\n } else {\n val half = cnt0 / 2\n for (j <- start until start + half) cs(j) = as(start)\n for (j <- start + half until i) cs(j) = as(i)\n cnt0 = 1\n start = i\n }\n }\n val half = cnt0 / 2\n for (j <- start until start + half) cs(j) = as(start)\n for (j <- start + half to n - 1) cs(j) = as(n - 1)\n //println(as.mkString(\" \"))\n println(max / 2)\n println(cs.mkString(\" \"))\n \n// def process(as: Array[Int], bs: Array[Int]) {\n// bs(0) = as(0)\n// bs(n - 1) = as(n - 1)\n// for (i <- 1 until n - 1) {\n// val sum = as(i - 1) + as(i) + as(i + 1)\n// bs(i) = if (sum > 1) 1 else 0\n// }\n// }\n//\n// var cnt = 0\n// var changed = true\n// while (changed) {\n// process(as, bs)\n// changed = false\n// if (!Arrays.equals(as, bs)) {\n// cnt += 1\n// changed = true\n// val tmp = as\n// as = bs\n// bs = tmp\n// }\n// }\n// \n// Console.setOut(new java.io.BufferedOutputStream(Console.out))\n//\n// println(cnt)\n// println(Arrays.equals(as, cs))\n// println(as.mkString(\" \"))\n//\n// Console.flush\n}\n", "positive_code": [{"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\nimport java.security.SecureRandom\n\nobject C_Median_c {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(t33.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n var number = line1.nextToken().toInt\n// number = 50000\n \n \n var seq = new Array[Int](number)\n val line2 = new StringTokenizer(br.readLine())\n \n// var value = true\n val rnd = new SecureRandom()\n for (i <- 0 until number) {\n seq(i) = line2.nextToken().toInt\n// seq(i) = if (rnd.nextBoolean()) 1 else 1\n// seq(i) = if (value) 1 else 0\n// value = !value\n }\n \n// if (number == 499) {\n// for (i <- 400 until 600) {\n// print(seq(i) + \" \")\n// if (i % 50 == 0) {\n// println()\n// }\n// }\n// println(\"debug output end\")\n// }\n //---------------------------- parameters reading end --------------------------------\n\n \n var ind = 0\n var curLength = 0\n var maxLength = 0\n var curStart = 0\n var maxStart = -1\n var maxEnd = -1\n var atleastOne = false\n while (ind < seq.length) {\n if (check(ind, 0,1,0)) atleastOne = true\n if (check(ind, 1,0,1)) {\n if (curLength == 0) {\n curStart = ind\n }\n curLength += 2;\n ind += 1\n if (maxLength < curLength ) {\n maxLength = curLength;\n maxStart = curStart\n }\n } else {\n if (curLength != 0) {\n// if (maxLength == curLength) {\n if (ind == maxStart + maxLength) { \n maxEnd = ind\n }\n }\n curLength = 0\n }\n\n ind += 1\n \n def check(ind:Int, c1:Int, c2:Int, c3:Int):Boolean = {\n if (ind > seq.length-3) return false\n return seq(ind) == c1 && seq(ind+1) == c2 && seq(ind+2) == c3\n }\n }\n if (maxLength !=0 && maxStart != 0 && maxEnd != seq.length-1 &&\n !(maxStart > 0 && seq(maxStart-1) == 1) && !(maxEnd < seq.length-1 && seq(maxEnd+1) == 1)) {\n maxLength += 1\n }\n if (atleastOne && maxLength == 0) {\n maxLength = 1\n }\n db(\"Max \" + maxLength + \" start:\" + maxStart + \" end:\" + maxEnd)\n \n\n if (maxLength == 0) {\n println(0)\n } else {\n println((maxLength +1)/2.toInt) \n }\n \n\n var res = Array.fill[Int](number)(0)\n var i = 0\n while (i < seq.length) {\n if (i ==0 || i == seq.length-1 || (i > 0 && seq(i) == 1 && seq(i-1) == 1)\n || (i+1 < seq.length && seq(i)==1 && seq(i+1) == 1)) {\n res(i) = seq(i)\n }\n i += 1\n }\n \n var const = res.clone()\n for (i <- 0 until res.length) {\n if (const(i) == 1 && i+1 < const.length && const(i+1) == 0) {\n //right edge\n var j = 1\n var ind = j *2 + i\n while (ind < seq.length && seq(ind) == 1 && seq(ind-1) == 0) {\n res(i+j) = 1\n j += 1\n ind = j *2 + i\n }\n }\n }\n for (i <- 0 until res.length) {\n if (const(i) == 0 && i+1 < const.length && const(i+1) == 1) {\n //left edge\n var j = 1\n var ind = i+1 - j *2\n while (ind > 0 && seq(ind) == 1 && seq(ind+1) == 0) {\n res(i+1-j) = 1\n j += 1\n ind = i+1 - j *2\n }\n }\n }\n\n var resStr = new StringBuffer()\n for(i<- 0 until res.length) {\n resStr.append(res(i)).append(\" \")\n }\n \n println(resStr)\n \n \n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\nobject A {\n def change(seq: Array[Int], left: Int, right: Int): Unit = {\n if (left <= right) {\n seq(left) = seq(left - 1)\n seq(right) = seq(right + 1)\n change(seq, left + 1, right - 1)\n }\n }\n\n def patchSeq(seq: Array[Int], marks: Array[Boolean], maxLength: Int, index: Int): Int = {\n if (index == seq.length) {\n maxLength\n } else if (marks(index)) {\n patchSeq(seq, marks, maxLength, index + 1)\n } else {\n val end = marks.indexWhere(v => v, index)\n change(seq, index, end - 1)\n patchSeq(seq, marks, math.max(maxLength, end - index), end)\n }\n }\n\n def work(in: Scanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val seq = Array.fill(n)(in.nextInt())\n val marks = Array.tabulate(n)(i => i == 0 || i == n - 1 || seq(i) == seq(i - 1) || seq(i) == seq(i + 1))\n val answer = patchSeq(seq, marks, 0, 0)\n println((answer + 1) / 2)\n println(seq.mkString(\" \"))\n }\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(new InputStreamReader(System.in))\n val pw = new PrintWriter(System.out)\n work(sc, pw)\n pw.close()\n sc.close()\n }\n\n class Scanner(reader: Reader) extends Closeable {\n private val br = new BufferedReader(reader)\n private var st = new StringTokenizer(br.readLine())\n\n override def close(): Unit = {\n br.close()\n st = null\n }\n\n @tailrec\n final def next(): String = if (st.hasMoreTokens) st.nextToken() else {\n st = new StringTokenizer(br.readLine())\n next()\n }\n\n final def nextInt() = next().toInt\n final def nextLong() = next().toLong\n final def nextDouble() = next().toDouble\n }\n }\n"}, {"source_code": "object Main extends App{\n\t\nimport java.util.{Scanner,Random}\n\n\tdef knots(v:Vector[Int]) = {\n\t\tval n = v.size\n\t\tvar l = 0\n\t\tvar r = 0\n\t\tvar result:Vector[Vector[Int]] = Vector.empty\n\t\twhile (l 1){\n\t\t\t\tif (i.head == last && len >0){\n\t\t\t\t\tresult = result ++ Vector.fill(len)(last)\n\t\t\t\t\tstep = math.max(step,(len+1)/2)\n\t\t\t\t}\n\t\t\t\telse if (len > 0){\n\t\t\t\t\tresult = result ++ Vector.fill(len/2)(last)\n\t\t\t\t\tresult = result ++ Vector.fill(len/2)(i.head)\n\t\t\t\t\tstep = math.max(step,len/2)\n\t\t\t\t}\n\t\t\t\tresult = result ++ i\n\t\t\t\tlast = i.head\n\t\t\t\tlen = 0\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlen += 1\n\t\t\t}\n\t\t\t//println(len,result)//debug\n\t\t}\n\t\tresult = result.slice(1,result.size-1)\n\t\tprintln(step)\n\t\tprintln(result.mkString(\" \"))\n\t}\n\n\n\twork()\n}"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\nobject A {\n def change(seq: Array[Int], left: Int, right: Int): Unit = {\n if (left < right) {\n seq(left) = seq(left - 1)\n seq(right) = seq(right + 1)\n change(seq, left + 1, right - 1)\n }\n }\n\n def patchSeq(seq: Array[Int], marks: Array[Boolean], maxLength: Int, index: Int): Int = {\n if (index == seq.length) {\n maxLength\n } else if (marks(index)) {\n patchSeq(seq, marks, maxLength, index + 1)\n } else {\n val end = marks.indexWhere(v => v, index)\n change(seq, index, end - 1)\n patchSeq(seq, marks, math.max(maxLength, end - index), end)\n }\n }\n\n def work(in: Scanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val seq = Array.fill(n)(in.nextInt())\n val marks = Array.tabulate(n)(i => i == 0 || i == n - 1 || seq(i) == seq(i - 1) || seq(i) == seq(i + 1))\n val answer = patchSeq(seq, marks, 0, 0)\n println((answer + 1) / 2)\n println(seq.mkString(\" \"))\n }\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(new InputStreamReader(System.in))\n val pw = new PrintWriter(System.out)\n work(sc, pw)\n pw.close()\n sc.close()\n }\n\n class Scanner(reader: Reader) extends Closeable {\n private val br = new BufferedReader(reader)\n private var st = new StringTokenizer(br.readLine())\n\n override def close(): Unit = {\n br.close()\n st = null\n }\n\n @tailrec\n final def next(): String = if (st.hasMoreTokens) st.nextToken() else {\n st = new StringTokenizer(br.readLine())\n next()\n }\n\n final def nextInt() = next().toInt\n final def nextLong() = next().toLong\n final def nextDouble() = next().toDouble\n }\n }\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\nimport java.security.SecureRandom\n\nobject C_Median_c {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(t6.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n var number = line1.nextToken().toInt\n// number = 50000\n \n \n var seq = new Array[Int](number)\n val line2 = new StringTokenizer(br.readLine())\n \n// var value = true\n val rnd = new SecureRandom()\n for (i <- 0 until number) {\n seq(i) = line2.nextToken().toInt\n// seq(i) = if (rnd.nextBoolean()) 1 else 1\n// seq(i) = if (value) 1 else 0\n// value = !value\n }\n \n// if (number == 499) {\n// for (i <- 400 until 600) {\n// print(seq(i) + \" \")\n// if (i % 50 == 0) {\n// println()\n// }\n// }\n// println(\"debug output end\")\n// }\n //---------------------------- parameters reading end --------------------------------\n\n \n var ind = 0\n var curLength = 0\n var maxLength = 0\n var curStart = 0\n var maxStart = -1\n var maxEnd = -1\n while (ind < seq.length) {\n if (check(ind, 1,0,1)) {\n if (curLength == 0) {\n curStart = ind\n }\n curLength += 2;\n ind += 1\n if (maxLength < curLength ) {\n maxLength = curLength;\n maxStart = curStart\n }\n } else {\n if (curLength != 0) {\n// if (maxLength == curLength) {\n if (ind == maxStart + maxLength) { \n maxEnd = ind\n }\n }\n curLength = 0\n }\n\n ind += 1\n \n def check(ind:Int, c1:Int, c2:Int, c3:Int):Boolean = {\n if (ind > seq.length-3) return false\n return seq(ind) == c1 && seq(ind+1) == c2 && seq(ind+2) == c3\n }\n }\n if (maxLength !=0 && maxStart != 0 && maxEnd != seq.length-1 &&\n !(maxStart > 0 && seq(maxStart-1) == 1) && !(maxEnd < seq.length-1 && seq(maxEnd+1) == 1)) {\n maxLength += 1\n }\n db(\"Max \" + maxLength + \" start:\" + maxStart + \" end:\" + maxEnd)\n \n\n if (maxLength == 0) {\n println(0)\n } else {\n println((maxLength +1)/2.toInt) \n }\n \n\n var res = Array.fill[Int](number)(0)\n var i = 0\n while (i < seq.length) {\n if (i ==0 || i == seq.length-1 || (i > 0 && seq(i) == 1 && seq(i-1) == 1)\n || (i+1 < seq.length && seq(i)==1 && seq(i+1) == 1)) {\n res(i) = seq(i)\n }\n i += 1\n }\n \n var const = res.clone()\n for (i <- 0 until res.length) {\n if (const(i) == 1 && i+1 < const.length && const(i+1) == 0) {\n //right edge\n var j = 1\n var ind = j *2 + i\n while (ind < seq.length && seq(ind) == 1 && seq(ind-1) == 0) {\n res(i+j) = 1\n j += 1\n ind = j *2 + i\n }\n }\n }\n for (i <- 0 until res.length) {\n if (const(i) == 0 && i+1 < const.length && const(i+1) == 1) {\n //left edge\n var j = 1\n var ind = i+1 - j *2\n while (ind > 0 && seq(ind) == 1 && seq(ind+1) == 0) {\n res(i+1-j) = 1\n j += 1\n ind = i+1 - j *2\n }\n }\n }\n\n var resStr = new StringBuffer()\n for(i<- 0 until res.length) {\n resStr.append(res(i)).append(\" \")\n }\n \n println(resStr)\n \n \n }\n}"}, {"source_code": "import java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\nimport java.security.SecureRandom\n\nobject C_Median_c {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(t8.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n var number = line1.nextToken().toInt\n// number = 50000\n \n \n var seq = new Array[Int](number)\n val line2 = new StringTokenizer(br.readLine())\n \n// var value = true\n val rnd = new SecureRandom()\n for (i <- 0 until number) {\n seq(i) = line2.nextToken().toInt\n// seq(i) = if (rnd.nextBoolean()) 1 else 1\n// seq(i) = if (value) 1 else 0\n// value = !value\n }\n \n if (number == 499) {\n for (i <- 0 until 200) {\n print(seq(i) + \" \")\n if (i % 50 == 0) {\n println()\n }\n println(\"debug output end\")\n }\n }\n //---------------------------- parameters reading end --------------------------------\n\n \n var ind = 0\n var curLength = 0\n var maxLength = 0\n var curStart = 0\n var maxStart = -1\n var maxEnd = -1\n while (ind < seq.length) {\n if (check(ind, 1,0,1)) {\n if (curLength == 0) {\n curStart = ind\n }\n curLength += 2;\n ind += 1\n if (maxLength < curLength ) {\n maxLength = curLength;\n maxStart = curStart\n }\n } else {\n if (curLength != 0) {\n if (maxLength == curLength) {\n maxEnd = ind\n }\n }\n curLength = 0\n }\n\n ind += 1\n \n def check(ind:Int, c1:Int, c2:Int, c3:Int):Boolean = {\n if (ind > seq.length-3) return false\n return seq(ind) == c1 && seq(ind+1) == c2 && seq(ind+2) == c3\n }\n }\n if (maxLength !=0 && maxStart != 0 && maxEnd != seq.length-1 &&\n !(maxStart > 0 && seq(maxStart-1) == 1) && !(maxEnd < seq.length-1 && seq(maxEnd+1) == 1)) {\n maxLength += 1\n }\n db(\"Max \" + maxLength + \" start:\" + maxStart + \" end:\" + maxEnd)\n \n\n if (maxLength == 0) {\n println(0)\n } else {\n println((maxLength +1)/2.toInt) \n }\n \n\n var res = Array.fill[Int](number)(0)\n var i = 0\n while (i < seq.length) {\n if (i ==0 || i == seq.length-1 || (i > 0 && seq(i) == 1 && seq(i-1) == 1)\n || (i+1 < seq.length && seq(i)==1 && seq(i+1) == 1)) {\n res(i) = seq(i)\n }\n i += 1\n }\n \n var const = res.clone()\n for (i <- 0 until res.length) {\n if (const(i) == 1 && i+1 < const.length && const(i+1) == 0) {\n //right edge\n var j = 1\n var ind = j *2 + i\n while (ind < seq.length && seq(ind) == 1 && seq(ind-1) == 0) {\n res(i+j) = 1\n j += 1\n ind = j *2 + i\n }\n }\n }\n for (i <- 0 until res.length) {\n if (const(i) == 0 && i+1 < const.length && const(i+1) == 1) {\n //left edge\n var j = 1\n var ind = i+1 - j *2\n while (ind > 0 && seq(ind) == 1 && seq(ind+1) == 0) {\n res(i+1-j) = 1\n j += 1\n ind = i+1 - j *2\n }\n }\n }\n\n var resStr = new StringBuffer()\n for(i<- 0 until res.length) {\n resStr.append(res(i)).append(\" \")\n }\n \n println(resStr)\n \n \n }\n}"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject C {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n val number = line1.nextToken().toInt\n \n var seq = new Array[Int](number)\n val cur = new Array[Int](number)\n val line2 = new StringTokenizer(br.readLine())\n \n for (i <- 0 until number) {\n seq(i) = line2.nextToken().toInt\n cur(i) = seq(i)\n }\n //---------------------------- parameters reading end --------------------------------\n\n var steps = 0\n var changed = true\n var res = new StringBuffer()\n \n while (changed) {\n changed = false\n for (i <- 0 until number) {\n derive(i)\n }\n if (changed) {\n steps += 1\n }\n seq = cur\n }\n \n def derive(i:Int) {\n if (i == 0 || i == number-1) {\n cur(i) = seq(i)\n } else {\n if (comp(i, Array(0,1,0))) { // || ) {\n cur(i) = 0\n changed = true\n } else if (comp(i, Array(1,0,1))) {\n cur(i) = 1\n changed = true\n } else {\n cur(i) = seq(i)\n }\n }\n db(\"replaced \" + i + \" \" + seq(i) + \" to \" + cur(i))\n }\n \n println(steps)\n\n for (i <- 0 until number) {\n res.append(cur(i)).append(\" \")\n }\n println(res)\n \n def comp(ind:Int, num:Array[Int]): Boolean ={\n return seq(ind-1) == \n num(0) && \n seq(ind) == \n num(1) && \n seq(ind+1) == \n num(2)\n }\n \n \n \n }\n \n//========================= samples ======================== \nval sa1 = \"\"\"\n5\n0 1 0 1 0\n\"\"\"\n\n//========================= samples end ==================== \n}"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\nimport java.security.SecureRandom\n\nobject C_Median_c {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(t8.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n var number = line1.nextToken().toInt\n// number = 50000\n \n \n var seq = new Array[Int](number)\n val line2 = new StringTokenizer(br.readLine())\n \n// var value = true\n val rnd = new SecureRandom()\n for (i <- 0 until number) {\n seq(i) = line2.nextToken().toInt\n// seq(i) = if (rnd.nextBoolean()) 1 else 1\n// seq(i) = if (value) 1 else 0\n// value = !value\n }\n \n if (number == 499) {\n for (i <- 0 until 200) {\n print(seq(i) + \" \")\n if (i % 50 == 0) {\n println()\n }\n }\n println(\"debug output end\")\n }\n //---------------------------- parameters reading end --------------------------------\n\n \n var ind = 0\n var curLength = 0\n var maxLength = 0\n var curStart = 0\n var maxStart = -1\n var maxEnd = -1\n while (ind < seq.length) {\n if (check(ind, 1,0,1)) {\n if (curLength == 0) {\n curStart = ind\n }\n curLength += 2;\n ind += 1\n if (maxLength < curLength ) {\n maxLength = curLength;\n maxStart = curStart\n }\n } else {\n if (curLength != 0) {\n if (maxLength == curLength) {\n maxEnd = ind\n }\n }\n curLength = 0\n }\n\n ind += 1\n \n def check(ind:Int, c1:Int, c2:Int, c3:Int):Boolean = {\n if (ind > seq.length-3) return false\n return seq(ind) == c1 && seq(ind+1) == c2 && seq(ind+2) == c3\n }\n }\n if (maxLength !=0 && maxStart != 0 && maxEnd != seq.length-1 &&\n !(maxStart > 0 && seq(maxStart-1) == 1) && !(maxEnd < seq.length-1 && seq(maxEnd+1) == 1)) {\n maxLength += 1\n }\n db(\"Max \" + maxLength + \" start:\" + maxStart + \" end:\" + maxEnd)\n \n\n if (maxLength == 0) {\n println(0)\n } else {\n println((maxLength +1)/2.toInt) \n }\n \n\n var res = Array.fill[Int](number)(0)\n var i = 0\n while (i < seq.length) {\n if (i ==0 || i == seq.length-1 || (i > 0 && seq(i) == 1 && seq(i-1) == 1)\n || (i+1 < seq.length && seq(i)==1 && seq(i+1) == 1)) {\n res(i) = seq(i)\n }\n i += 1\n }\n \n var const = res.clone()\n for (i <- 0 until res.length) {\n if (const(i) == 1 && i+1 < const.length && const(i+1) == 0) {\n //right edge\n var j = 1\n var ind = j *2 + i\n while (ind < seq.length && seq(ind) == 1 && seq(ind-1) == 0) {\n res(i+j) = 1\n j += 1\n ind = j *2 + i\n }\n }\n }\n for (i <- 0 until res.length) {\n if (const(i) == 0 && i+1 < const.length && const(i+1) == 1) {\n //left edge\n var j = 1\n var ind = i+1 - j *2\n while (ind > 0 && seq(ind) == 1 && seq(ind+1) == 0) {\n res(i+1-j) = 1\n j += 1\n ind = i+1 - j *2\n }\n }\n }\n\n var resStr = new StringBuffer()\n for(i<- 0 until res.length) {\n resStr.append(res(i)).append(\" \")\n }\n \n println(resStr)\n \n \n }\n}"}, {"source_code": "import java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\nimport java.security.SecureRandom\n\nobject C_Median_c {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(t8.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n var number = line1.nextToken().toInt\n// number = 50000\n \n \n var seq = new Array[Int](number)\n val line2 = new StringTokenizer(br.readLine())\n \n// var value = true\n val rnd = new SecureRandom()\n for (i <- 0 until number) {\n seq(i) = line2.nextToken().toInt\n// seq(i) = if (rnd.nextBoolean()) 1 else 1\n// seq(i) = if (value) 1 else 0\n// value = !value\n }\n \n if (number == 499) {\n for (i <- 0 until 200) {\n print(seq(i) + \" \")\n if (i % 50 == 0) {\n println()\n }\n }\n }\n //---------------------------- parameters reading end --------------------------------\n\n \n var ind = 0\n var curLength = 0\n var maxLength = 0\n var curStart = 0\n var maxStart = -1\n var maxEnd = -1\n while (ind < seq.length) {\n if (check(ind, 1,0,1)) {\n if (curLength == 0) {\n curStart = ind\n }\n curLength += 2;\n ind += 1\n if (maxLength < curLength ) {\n maxLength = curLength;\n maxStart = curStart\n }\n } else {\n if (curLength != 0) {\n if (maxLength == curLength) {\n maxEnd = ind\n }\n }\n curLength = 0\n }\n\n ind += 1\n \n def check(ind:Int, c1:Int, c2:Int, c3:Int):Boolean = {\n if (ind > seq.length-3) return false\n return seq(ind) == c1 && seq(ind+1) == c2 && seq(ind+2) == c3\n }\n }\n if (maxLength !=0 && maxStart != 0 && maxEnd != seq.length-1 &&\n !(maxStart > 0 && seq(maxStart-1) == 1) && !(maxEnd < seq.length-1 && seq(maxEnd+1) == 1)) {\n maxLength += 1\n }\n db(\"Max \" + maxLength + \" start:\" + maxStart + \" end:\" + maxEnd)\n \n\n if (maxLength == 0) {\n println(0)\n } else {\n println((maxLength +1)/2.toInt) \n }\n \n\n var res = Array.fill[Int](number)(0)\n var i = 0\n while (i < seq.length) {\n if (i ==0 || i == seq.length-1 || (i > 0 && seq(i) == 1 && seq(i-1) == 1)\n || (i+1 < seq.length && seq(i)==1 && seq(i+1) == 1)) {\n res(i) = seq(i)\n }\n i += 1\n }\n \n var const = res.clone()\n for (i <- 0 until res.length) {\n if (const(i) == 1 && i+1 < const.length && const(i+1) == 0) {\n //right edge\n var j = 1\n var ind = j *2 + i\n while (ind < seq.length && seq(ind) == 1 && seq(ind-1) == 0) {\n res(i+j) = 1\n j += 1\n ind = j *2 + i\n }\n }\n }\n for (i <- 0 until res.length) {\n if (const(i) == 0 && i+1 < const.length && const(i+1) == 1) {\n //left edge\n var j = 1\n var ind = i+1 - j *2\n while (ind > 0 && seq(ind) == 1 && seq(ind+1) == 0) {\n res(i+1-j) = 1\n j += 1\n ind = i+1 - j *2\n }\n }\n }\n\n var resStr = new StringBuffer()\n for(i<- 0 until res.length) {\n resStr.append(res(i)).append(\" \")\n }\n \n println(resStr)\n \n \n }\n }"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\nimport java.security.SecureRandom\n\nobject C_Median_c {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(t6.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n var number = line1.nextToken().toInt\n// number = 50000\n \n var seq = new Array[Int](number)\n val line2 = new StringTokenizer(br.readLine())\n \n// var value = true\n val rnd = new SecureRandom()\n for (i <- 0 until number) {\n seq(i) = line2.nextToken().toInt\n// seq(i) = if (rnd.nextBoolean()) 1 else 1\n// seq(i) = if (value) 1 else 0\n// value = !value\n }\n //---------------------------- parameters reading end --------------------------------\n\n \n var ind = 0\n var curLength = 0\n var maxLength = 0\n var curStart = 0\n var maxStart = -1\n var maxEnd = -1\n while (ind < seq.length) {\n if (check(ind, 1,0,1)) {\n if (curLength == 0) {\n curStart = ind\n }\n curLength += 2;\n ind += 1\n if (maxLength < curLength ) {\n maxLength = curLength;\n maxStart = curStart\n }\n } else {\n if (curLength != 0) {\n if (maxLength == curLength) {\n maxEnd = ind\n }\n }\n curLength = 0\n }\n\n ind += 1\n \n def check(ind:Int, c1:Int, c2:Int, c3:Int):Boolean = {\n if (ind > seq.length-3) return false\n return seq(ind) == c1 && seq(ind+1) == c2 && seq(ind+2) == c3\n }\n }\n if (maxLength !=0 && maxStart != 0 && maxEnd != seq.length-1 &&\n !(maxStart > 0 && seq(maxStart-1) == 1) && !(maxEnd < seq.length-1 && seq(maxEnd+1) == 1)) {\n maxLength += 1\n }\n db(\"Max \" + maxLength + \" start:\" + maxStart + \" end:\" + maxEnd)\n \n\n if (maxLength == 0) {\n println(0)\n } else {\n println((maxLength +1)/2.toInt) \n }\n \n\n var res = Array.fill[Int](number)(0)\n var i = 0\n while (i < seq.length) {\n if (i ==0 || i == seq.length-1 || (i > 0 && seq(i) == 1 && seq(i-1) == 1)\n || (i+1 < seq.length && seq(i)==1 && seq(i+1) == 1)) {\n res(i) = seq(i)\n }\n i += 1\n }\n \n var const = res.clone()\n for (i <- 0 until res.length) {\n if (const(i) == 1 && i+1 < const.length && const(i+1) == 0) {\n //right edge\n var j = 1\n var ind = j *2 + i\n while (ind < seq.length && seq(ind) == 1 && seq(ind-1) == 0) {\n res(i+j) = 1\n j += 1\n ind = j *2 + i\n }\n }\n }\n for (i <- 0 until res.length) {\n if (const(i) == 0 && i+1 < const.length && const(i+1) == 1) {\n //left edge\n var j = 1\n var ind = i+1 - j *2\n while (ind > 0 && seq(ind) == 1 && seq(ind+1) == 0) {\n res(i+1-j) = 1\n j += 1\n ind = i+1 - j *2\n }\n }\n }\n\n var resStr = new StringBuffer()\n for(i<- 0 until res.length) {\n resStr.append(res(i)).append(\" \")\n }\n \n println(resStr)\n \n \n }\n}"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\nimport java.security.SecureRandom\n\nobject C_Median_c {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(m13.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n var number = line1.nextToken().toInt\n// number = 50000\n \n var seq = new Array[Int](number)\n val line2 = new StringTokenizer(br.readLine())\n \n// var value = true\n val rnd = new SecureRandom()\n for (i <- 0 until number) {\n seq(i) = line2.nextToken().toInt\n// seq(i) = if (rnd.nextBoolean()) 1 else 1\n// seq(i) = if (value) 1 else 0\n// value = !value\n }\n //---------------------------- parameters reading end --------------------------------\n\n \n var ind = 0\n var curLength = 0\n var maxLength = 0\n var curStart = 0\n var maxStart = -1\n var maxEnd = -1\n while (ind < seq.length) {\n if (check(ind, 1,0,1)) {\n if (curLength == 0) {\n curStart = ind\n }\n curLength += 2;\n ind += 1\n if (maxLength < curLength ) {\n maxLength = curLength;\n maxStart = curStart\n }\n } else {\n if (curLength != 0) {\n if (maxLength == curLength) {\n maxEnd = ind\n }\n }\n curLength = 0\n }\n\n ind += 1\n \n def check(ind:Int, c1:Int, c2:Int, c3:Int):Boolean = {\n if (ind > seq.length-3) return false\n return seq(ind) == c1 && seq(ind+1) == c2 && seq(ind+2) == c3\n }\n }\n if (maxLength !=0 && maxStart != 0 && maxEnd != seq.length-1 &&\n !(maxStart == 1 && seq(0) == 1) && !(maxStart == seq.length-2 && seq(seq.length-1) == 1)) {\n maxLength += 1\n }\n// db(\"Max \" + maxLength + \" start:\" + maxStart + \" end:\" + maxEnd)\n \n\n if (maxLength == 0) {\n println(0)\n } else {\n println((maxLength +1)/2.toInt) \n }\n \n\n var res = Array.fill[Int](number)(0)\n var i = 0\n var pStart = -1;\n while (i < seq.length) {\n if (i ==0 || i == seq.length-1 || (i > 0 && seq(i) == 1 && seq(i-1) == 1)\n || (i+1 < seq.length && seq(i)==1 && seq(i+1) == 1)) {\n res(i) = seq(i)\n }\n i += 1\n }\n \n var const = res.clone()\n for (i <- 0 until res.length) {\n if (const(i) == 1 && i+1 < const.length && const(i+1) == 0) {\n //right edge\n var j = 1\n var ind = j *2 + i\n while (ind < seq.length && seq(ind) == 1 && seq(ind-1) == 0) {\n res(i+j) = 1\n j += 1\n ind = j *2 + i\n }\n }\n }\n for (i <- 0 until res.length) {\n if (const(i) == 0 && i+1 < const.length && const(i+1) == 1) {\n //left edge\n var j = 1\n var ind = i+1 - j *2\n while (ind > 0 && seq(ind) == 1 && seq(ind+1) == 0) {\n res(i+1-j) = 1\n j += 1\n ind = i+1 - j *2\n }\n }\n }\n\n var resStr = new StringBuffer()\n for(i<- 0 until res.length) {\n resStr.append(res(i)).append(\" \")\n }\n \n println(resStr)\n \n \n }\n}"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\nimport java.security.SecureRandom\n\nobject C_Median_c {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(t8.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n var number = line1.nextToken().toInt\n// number = 50000\n \n \n var seq = new Array[Int](number)\n val line2 = new StringTokenizer(br.readLine())\n \n// var value = true\n val rnd = new SecureRandom()\n for (i <- 0 until number) {\n seq(i) = line2.nextToken().toInt\n// seq(i) = if (rnd.nextBoolean()) 1 else 1\n// seq(i) = if (value) 1 else 0\n// value = !value\n }\n \n if (number == 499) {\n for (i <- 200 until 400) {\n print(seq(i) + \" \")\n if (i % 50 == 0) {\n println()\n }\n }\n println(\"debug output end\")\n }\n //---------------------------- parameters reading end --------------------------------\n\n \n var ind = 0\n var curLength = 0\n var maxLength = 0\n var curStart = 0\n var maxStart = -1\n var maxEnd = -1\n while (ind < seq.length) {\n if (check(ind, 1,0,1)) {\n if (curLength == 0) {\n curStart = ind\n }\n curLength += 2;\n ind += 1\n if (maxLength < curLength ) {\n maxLength = curLength;\n maxStart = curStart\n }\n } else {\n if (curLength != 0) {\n if (maxLength == curLength) {\n maxEnd = ind\n }\n }\n curLength = 0\n }\n\n ind += 1\n \n def check(ind:Int, c1:Int, c2:Int, c3:Int):Boolean = {\n if (ind > seq.length-3) return false\n return seq(ind) == c1 && seq(ind+1) == c2 && seq(ind+2) == c3\n }\n }\n if (maxLength !=0 && maxStart != 0 && maxEnd != seq.length-1 &&\n !(maxStart > 0 && seq(maxStart-1) == 1) && !(maxEnd < seq.length-1 && seq(maxEnd+1) == 1)) {\n maxLength += 1\n }\n db(\"Max \" + maxLength + \" start:\" + maxStart + \" end:\" + maxEnd)\n \n\n if (maxLength == 0) {\n println(0)\n } else {\n println((maxLength +1)/2.toInt) \n }\n \n\n var res = Array.fill[Int](number)(0)\n var i = 0\n while (i < seq.length) {\n if (i ==0 || i == seq.length-1 || (i > 0 && seq(i) == 1 && seq(i-1) == 1)\n || (i+1 < seq.length && seq(i)==1 && seq(i+1) == 1)) {\n res(i) = seq(i)\n }\n i += 1\n }\n \n var const = res.clone()\n for (i <- 0 until res.length) {\n if (const(i) == 1 && i+1 < const.length && const(i+1) == 0) {\n //right edge\n var j = 1\n var ind = j *2 + i\n while (ind < seq.length && seq(ind) == 1 && seq(ind-1) == 0) {\n res(i+j) = 1\n j += 1\n ind = j *2 + i\n }\n }\n }\n for (i <- 0 until res.length) {\n if (const(i) == 0 && i+1 < const.length && const(i+1) == 1) {\n //left edge\n var j = 1\n var ind = i+1 - j *2\n while (ind > 0 && seq(ind) == 1 && seq(ind+1) == 0) {\n res(i+1-j) = 1\n j += 1\n ind = i+1 - j *2\n }\n }\n }\n\n var resStr = new StringBuffer()\n for(i<- 0 until res.length) {\n resStr.append(res(i)).append(\" \")\n }\n \n println(resStr)\n \n \n }\n}"}], "src_uid": "5da1c96b88b4ac0b698a37e4d2437ccb"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n var x = ni()\n val ans = ArrayBuffer[Int]()\n\n def isPerfect(n: Int): Boolean = {\n REP(60) { i =>\n if (n == (1L << i) - 1) return true\n }\n false\n }\n\n // 左から最初に0になる場所\n def findT(n: Int): Int = {\n if (n == 0) return 1\n\n var t = log2(Integer.highestOneBit(n))\n while((n & (1 << t)) > 0) {\n t -= 1\n }\n t + 1\n }\n\n var i = 0\n while(!isPerfect(x)) {\n if (i % 2 == 0) {\n val t = findT(x)\n val y = (1 << t) - 1\n // debug(s\"t: $t x:$x y:$y => ${(x ^ y) + 1}\")\n x = x ^ y\n debug(s\"t: $t x:$x\")\n ans += t\n } else {\n x += 1\n }\n i += 1\n }\n\n out.println(i)\n out.println(ans.mkString(\" \"))\n }\n\n def log2(x: Int): Int = {\n assert(x > 0)\n var a = x\n var i = 0 // 何回2で割ったら1になるか\n while(a > 1) {\n i += 1\n a >>>= 1\n }\n i\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debugDim(m: Array[Array[Long]]): Unit = DEBUG {\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n\n def debugDimFlip(m: Array[Array[Long]]): Unit = DEBUG {\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object b extends App{\n import scala.math.log\n import scala.io.StdIn.readInt\n\n def log2(x: Double) = log(x) / log(2)\n def binLength(x: Int) = if (x == 0) 1 else log2(x).toInt + 1\n def inversion(x: Int):Int = (~x) & ((1 << binLength(x)) - 1)\n\n /**\n * Returns a number of digits for the left most zero\n * 01101 -> 2\n * 10 -> 1\n */\n def asd(n: Int): Int = {\n def helper(m: Int, acc: Int): Int = {\n if(m == 0) acc\n else helper(m >> 1, acc + 1)\n }\n helper(inversion(n), 0)\n }\n\n\n def iterate(x: Int, cnt: Int, acc: List[Int]): (Int, List[Int]) = {\n if (x + 1 == (1 << binLength(x))) (cnt - 1, acc)\n else if (cnt % 2 == 1) {\n val n = asd(x)\n // println(s\"n -> $n\")\n iterate(x ^ ((1 << n) - 1), cnt + 1, n::acc)\n } else {\n // println(\"Add 1\")\n iterate(x + 1, cnt + 1, acc)\n }\n }\n\n val n = readInt()\n\n if (n + 1 == (1 << binLength(n))) {\n println(0)\n } else {\n val (cnt, acc) = iterate(n, 1, List())\n println(cnt)\n println(acc.reverse.mkString(\" \"))\n }\n \n}\n"}], "negative_code": [], "src_uid": "2510469c09d7d145078e65de81640ddc"} {"source_code": "import scala.Array._\n\nobject A523 extends App{\n\n def readInp = {\n val arr = ofDim[String](h)\n (0 until h).foreach(i => arr(i) = readLine)\n arr\n }\n\n def output(arr : Array[String]): Unit = {\n var line : Array[Char] = new Array[Char](h * 2)\n var result = \"\"\n for(i <- 0 until w) {\n for (j <- 0 until h) {\n line(2 * j) = arr(j)(i)\n line(2 * j + 1) = arr(j)(i)\n }\n var ln = line.mkString(\"\")\n result += ln + \"\\n\" + ln + \"\\n\"\n }\n\n print(result)\n }\n val (w, h) = {val str = readLine.split(\" \").map(_.toInt); (str(0), str(1))}\n val arr = readInp\n output(arr)\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(w, h) = in.next().split(\" \").map(_.toInt)\n val image = (1 to h).map(_ => in.next())\n println((0 until w).flatMap{\n i => val s = image.map(t => \"\" + t(i) + t(i)).mkString\n List(s, s)\n }.mkString(\"\\n\"))\n}\n"}, {"source_code": "object Main extends App {\n val Array(w, h) = readLine.split(\" \").map(_.toInt)\n //val (w,h) = (3,2)\n var img_row:Array[Array[_ >: Image]] = Array()\n (1 to h).foreach { h => \n var row: Array[_ >: Image] = Array()\n //Array(\".*.\").head\n var line = readLine\n line.toCharArray.foreach(ch => ch.toString match {\n case \".\" => row = row :+ Dot()\n case \"*\" => row = row :+ Star()\n case _ => \n })\n img_row = img_row :+ row\n }\n \n def rotate(img_rws: Array[Array[_ >: Image]]) {\n val rows:List[List[Image]] = img_rws.map(c => c.toList.asInstanceOf[List[Image]]).toList\n val z = rows.reverse.transpose // ROTATE\n \n z.map(re => re.map(ze => Array(ze,ze) ).flatten).foreach { fin => \n fin.reverse.foreach { result =>\n if (result.getClass.getName == \"Dot\") { print(\".\") }\n if (result.getClass.getName == \"Star\") { print(\"*\") }\n \n } \n \n println() \n fin.reverse.foreach { result =>\n if (result.getClass.getName == \"Dot\") { print(\".\") }\n if (result.getClass.getName == \"Star\") { print(\"*\") }\n \n } \nprintln() \n }\n\n }\n rotate(img_row)\n\n}\ntrait Image {}\ncase class Dot() extends Image \ncase class Star() extends Image"}, {"source_code": "\nimport scala.Array._\n\nobject A523 extends App{\n\n def readInp = {\n val arr = ofDim[Char](h, w)\n (0 until h).foreach(i => arr(i) = readLine.toCharArray)\n arr\n }\n\n def rotate(arr : Array[Array[Char]]) = {\n val buf = ofDim[Char](w, h)\n for(i <- 0 until w)\n for(j <- 0 until h)\n buf(i)(j) = arr(h - j - 1)(i)\n buf\n }\n\n def mirror(arr : Array[Array[Char]]) = {\n val buf = ofDim[Char](w, h)\n for(i <- 0 until w)\n for(j <- 0 until h)\n buf(i)(j) = arr(i)(h - j - 1)\n buf\n }\n\n def output(arr : Array[Array[Char]]): Unit = {\n var line : Array[Char] = new Array[Char](h * 2)\n for(i <- 0 until arr.length) {\n for (j <- 0 until arr(0).length) {\n line(2 * j) = arr(i)(j)\n line(2 * j + 1) = arr(i)(j)\n }\n val ln = line.mkString(\"\")\n println(ln + \"\\n\" + ln)\n }\n }\n val (w, h) = {val str = readLine.split(\" \").map(_.toInt); (str(0), str(1))}\n val arr = readInp\n output(mirror(rotate(arr)))\n}\n"}, {"source_code": "\nimport scala.Array._\n\nobject A523 extends App{\n\n def readInp = {\n val arr = ofDim[Char](h, w)\n (0 until h).foreach(i => arr(i) = readLine.toCharArray)\n arr\n }\n\n def output(arr : Array[Array[Char]]): Unit = {\n var line : Array[Char] = new Array[Char](h * 2)\n for(i <- 0 until arr(0).length) {\n for (j <- 0 until arr.length) {\n line(2 * j) = arr(j)(i)\n line(2 * j + 1) = arr(j)(i)\n }\n val ln = line.mkString(\"\")\n println(ln + \"\\n\" + ln)\n }\n }\n val (w, h) = {val str = readLine.split(\" \").map(_.toInt); (str(0), str(1))}\n val arr = readInp\n output(arr)\n}\n"}, {"source_code": "import scala.Array._\n\nobject A523 extends App{\n\n def readInp = {\n val arr = ofDim[Char](h, w)\n (0 until h).foreach(i => arr(i) = readLine.toCharArray)\n arr\n }\n\n def rotate(arr : Array[Array[Char]]) = {\n val buf = ofDim[Char](w, h)\n for(i <- 0 until w)\n for(j <- 0 until h)\n buf(i)(j) = arr(h - j - 1)(i)\n buf\n }\n\n def mirror(arr : Array[Array[Char]]) = {\n val buf = ofDim[Char](w, h)\n for(i <- 0 until w)\n for(j <- 0 until h)\n buf(i)(j) = arr(i)(h - j - 1)\n buf\n }\n\n def output(arr : Array[Array[Char]]): Unit = {\n var line = \"\"\n for(i <- 0 until arr.length) {\n for (j <- 0 until arr(0).length)\n line += arr(i)(j).toString + arr(i)(j).toString\n println(line)\n println(line)\n line = \"\"\n }\n }\n val (w, h) = {val str = readLine.split(\" \").map(_.toInt); (str(0), str(1))}\n val arr = readInp\n output(mirror(rotate(arr)))\n}\n"}, {"source_code": "import scala.Array._\n\nobject A523 extends App{\n\n def readInp = {\n val arr = ofDim[String](h)\n (0 until h).foreach(i => arr(i) = readLine)\n arr\n }\n\n def output(arr : Array[String]): Unit = {\n var line : Array[Char] = new Array[Char](h * 2)\n for(i <- 0 until w) {\n for (j <- 0 until h) {\n line(2 * j) = arr(j)(i)\n line(2 * j + 1) = arr(j)(i)\n }\n val ln = line.mkString(\"\")\n println(ln + \"\\n\" + ln)\n }\n }\n val (w, h) = {val str = readLine.split(\" \").map(_.toInt); (str(0), str(1))}\n val arr = readInp\n output(arr)\n}"}], "negative_code": [{"source_code": "object Main extends App {\n val Array(w, h) = readLine.split(\" \").map(_.toInt)\n //val (w,h) = (3,2)\n var img_row:Array[Array[_ >: Image]] = Array()\n (1 to h).foreach { h => \n var row: Array[_ >: Image] = Array()\n //Array(\".*.\").head\n var line = readLine\n line.toCharArray.foreach(ch => ch.toString match {\n case \".\" => row = row :+ Dot()\n case \"*\" => row = row :+ Star()\n case _ => \n })\n img_row = img_row :+ row\n }\n \n def rotate(img_rws: Array[Array[_ >: Image]]) {\n val rows:List[List[Image]] = img_rws.map(c => c.toList.asInstanceOf[List[Image]]).toList\n val z = rows.reverse.transpose // ROTATE\n \n z.map(re => re.map(ze => Array(ze,ze) ).flatten).foreach { fin => \n fin.foreach { result =>\n if (result.getClass.getName == \"Dot\") { print(\".\") }\n if (result.getClass.getName == \"Star\") { print(\"*\") }\n } \n println() \n }\n\n }\n rotate(img_row)\n\n}\ntrait Image {}\ncase class Dot() extends Image \ncase class Star() extends Image"}, {"source_code": "object Main extends App {\n val Array(w, h) = readLine.split(\" \").map(_.toInt)\n //val (w,h) = (3,2)\n var img_row:Array[Array[_ >: Image]] = Array()\n (1 to h).foreach { h => \n var row: Array[_ >: Image] = Array()\n //Array(\".*.\").head\n var line = readLine\n line.toCharArray.foreach(ch => ch.toString match {\n case \".\" => row = row :+ Dot()\n case \"*\" => row = row :+ Star()\n case _ => \n })\n img_row = img_row :+ row\n }\n \n //val x = readLine.split(\" \").map(_.toLong)\n //def roundUp(x: Long) = x / a + (if (x % a > 0) 1 else 0)\n //println(roundUp(n) * roundUp(m))\n //img_row.foreach(r => println(r.foreach(print(_))))\n def rotate(img_rws: Array[Array[_ >: Image]]) {\n val rows:List[List[Image]] = img_rws.map(c => c.toList.asInstanceOf[List[Image]]).toList\n val z = rows.reverse.transpose\n var finalize:Array[Array[Image]] = Array()\n z.foreach(r => { \n r.reverse.foreach { obj =>\n finalize = finalize :+ Array(obj,obj, obj,obj)\n }\n }\n ) \n finalize.foreach(c => println(c.foreach { cc =>\n if (cc.getClass.getName == \"Dot\") {\n print(\".\")\n }\n else { print(\"*\") }\n }\n ))\n }\n rotate(img_row)\n\n}\ntrait Image {}\ncase class Dot() extends Image \ncase class Star() extends Image"}], "src_uid": "9af19e1b482f7f0bcbffc754cf324092"} {"source_code": "import scala.io.StdIn._\r\n\r\nobject main{\r\n def main(args: Array[String]): Unit = {\r\n val t = readInt()\r\n for (_ <- 0 until t) {\r\n val s: String = readLine().map(_.toUpper)\r\n if (s == \"YES\") {\r\n println(\"YES\")\r\n } else {\r\n println(\"NO\")\r\n }\r\n }\r\n \r\n }\r\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\r\n\r\nobject Main extends App{\r\n val t=readInt()\r\n for(i<- 1 to t){\r\n if((readLine().toLowerCase()==\"yes\"))\r\n println(\"YES\")\r\n else println(\"NO\")\r\n }\r\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn._\r\n\r\nobject main{\r\n def main(args: Array[String]): Unit = {\r\n val t = readInt()\r\n for (_ <- 0 until t) {\r\n val s: String = readLine().map(_.toUpper)\r\n if (s == \"YES\") {\r\n print(\"YES\")\r\n } else {\r\n print(\"NO\")\r\n }\r\n }\r\n \r\n }\r\n}"}], "src_uid": "4c0b0cb8a11cb1fd40fef47616987029"} {"source_code": "\n/**\n * @author pvasilyev\n * @since 19 Jun 2016\n */\nobject A365 extends App {\n\n def checkKGood(num: String, k: Int): Boolean = {\n for (i <- 0 to k) {\n if (!num.contains(i.toString)) {\n return false\n }\n }\n true\n }\n\n def solve() = {\n val Array(n, k): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n var answer = 0\n for (i <- 0 until n) {\n val num = scala.io.StdIn.readLine()\n if (checkKGood(num, k)) {\n answer += 1\n }\n }\n\n println(answer)\n }\n\n solve()\n\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P365A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, K = sc.nextInt\n sc.nextLine\n\n def solve(): Int = {\n val a0 = List.range(0, K + 1).map(_ + '0')\n List.fill(N)(sc.nextLine).count { s =>\n s.toList.distinct.sortWith(_ < _).take(K + 1) == a0\n }\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "object A365 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n var res = (1 to n).count{ _ =>\n val in = read\n in.toSet.count(_ <= k+'0') == k + 1\n }\n out.println(res)\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val a = (1 to n).map(_ => readLine())\n val digits = (Set() ++ (0 to k)).map('0' +).map(_.toChar)\n val count = a.foldLeft(0) { (acc, str) =>\n if ((digits &~ str.toSet) == Set()) acc + 1\n else acc\n }\n println(count)\n }\n}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.HashSet\n\nobject GoodNumber extends App {\n val scan = new Scanner(System.in)\n val n = scan.nextInt\n val k = scan.nextInt\n\n def check(number: Int): Boolean = {\n var set = HashSet[Int]()\n var x = number\n do{\n if(x % 10 <= k) set = set + (x % 10)\n x = x / 10\n } while(x != 0)\n\n set == (0 to k).toSet\n }\n\n val ans = {\n for(i <- 0 until n) yield scan.nextInt\n }.toArray.filter(check).size\n\n println(ans)\n}"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n val Array(n, s) = StdIn.readLine().split(\" \").map(_.toInt)\n val k = s.toString.head\n\n println(Range(0,n).count{ p =>\n StdIn.readLine().toCharArray.filter(_ <= k).toSet.size > (k - '0')\n })\n\n\n\n }\n\n\n}\n"}, {"source_code": "\nobject Main {\n def main(args : Array[String]) {\n val (n, k) = readLine().split(\" \") match {\n case Array(n, k) => (n.toInt, k.toInt)\n }\n\n var cnt = 0\n for(i <- 1 to n) {\n if(isKNumber(readLine(), k.toString.charAt(0))) {\n cnt += 1\n }\n }\n\n println(cnt)\n }\n\n def isKNumber(num : String, k : Character) =\n (num.toCharArray.toSet filter { _ <= k }).size == k.toString.toInt + 1\n}\n"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val as = Array.fill(n)(readLine.map(_ - '0').filter(_ <= k))\n \n println(as.count(a => a.distinct.size == k + 1))\n}"}, {"source_code": "object Solution365A extends App {\n\n def solution() {\n val n = _int\n val k = _int\n val count = 1.to(n).map(_ => _string).count(s => {\n 0.to(k).forall(d => s.contains(\"\" + d))\n })\n println(count)\n }\n\n //////////////////////////////////////////////////\n import java.util.Scanner\n val SC: Scanner = new Scanner(System.in)\n def _line: String = SC.nextLine\n def _int: Int = SC.nextInt\n def _long: Long = SC.nextLong\n def _string: String = SC.next\n solution()\n}"}, {"source_code": "import scala.util.control.Breaks\n\n/**\n * Created with IntelliJ IDEA.\n * User: teots\n * Date: 11/21/13\n * Time: 3:46 PM\n * To change this template use File | Settings | File Templates.\n */\nobject A {\n def main(args: Array[String]) {\n val line: String = readLine()\n val tokens: Array[String] = line.split(\" \")\n val n = Integer.parseInt(tokens(0))\n val k = Integer.parseInt(tokens(1))\n\n var counter = 0\n\n val loop = new Breaks\n val loop2 = new Breaks\n\n for(i <- Range(1, n + 1 ))\n {\n val input : String = readLine()\n var found: Boolean = false\n\n loop.breakable{\n for (x <- Range(0, k + 1)) {\n found = false\n loop2.breakable {\n for(y <- input)\n {\n if(x == (y - 48))\n {\n found = true\n loop2.break\n }\n }\n }\n\n if(!found)\n {\n loop.break()\n }\n }\n\n counter += 1\n }\n }\n\n println(counter)\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.net.InetAddress\nimport java.security.MessageDigest\n\n/**\n * Contest 213, Div 2, problem A\n *\n *

Let's call a number k-good if it contains all digits not\n * exceeding k (0, ..., k). You've got a number k and an array a\n * containing n numbers. Find out how many k-good numbers are in\n * a (count each number every time it occurs in array a).

\n */\nobject Round213_Div2_Task1 {\n val inputScan = {\n val md = MessageDigest.getInstance(\"SHA-1\")\n val userName = System.getProperty(\"user.name\")\n val hostName = InetAddress.getLocalHost.getHostName\n\n val b = md.digest((userName + hostName).getBytes)\n var result = \"\"\n for (i ← 0 until b.length)\n result += Integer.toString((b(i) & 0xff) + 0x100, 16).substring(1)\n\n if (result == \"51a302f8ba1abe181e33fe86c0ab4c7bedfb6c91\") new Scanner(new java.io.FileInputStream(\"tmp/0.txt\"))\n else new Scanner(System.in)\n }\n\n def main(args: Array[String]) {\n val scan = inputScan\n\n val n = scan.nextInt\n val k = scan.nextInt\n scan.nextLine\n\n var c = 0\n for { ni ← 1 to n } {\n val arr = scan.nextLine.toCharArray.distinct\n if (arr.length >= (k + 1) && (0 to k).forall(p => arr.contains(p + '0')))\n c += 1\n }\n\n println(c)\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.net.InetAddress\nimport java.security.MessageDigest\n\n/**\n * Contest 213, Div 2, problem A\n *\n *

Let's call a number k-good if it contains all digits not\n * exceeding k (0, ..., k). You've got a number k and an array a\n * containing n numbers. Find out how many k-good numbers are in\n * a (count each number every time it occurs in array a).

\n */\nobject Round213_Div2_Task1 {\n val inputScan = {\n val md = MessageDigest.getInstance(\"SHA-1\")\n val userName = System.getProperty(\"user.name\")\n val hostName = InetAddress.getLocalHost.getHostName\n\n val b = md.digest((userName + hostName).getBytes)\n var result = \"\"\n for (i ← 0 until b.length)\n result += Integer.toString((b(i) & 0xff) + 0x100, 16).substring(1)\n\n if (result == \"51a302f8ba1abe181e33fe86c0ab4c7bedfb6c91\") new Scanner(new java.io.FileInputStream(\"tmp/0.txt\"))\n else new Scanner(System.in)\n }\n\n def main(args: Array[String]): Unit = {\n val scan = inputScan\n\n val n = scan.nextInt\n val k = scan.nextInt\n scan.nextLine\n\n var c = 0\n val digits = ('0' to ('0' + k).toChar).toArray\n for { ni ← 1 to n } {\n val arr = scan.nextLine.toCharArray.distinct\n if (arr.length >= (k + 1) && digits.forall(arr.contains(_)))\n c += 1\n }\n\n println(c)\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val ch = k.toString.head\n println(Range(0, n).count { _ =>\n val a = in.next().toSet\n Range(0, k + 1).forall(t => a.contains(t.toString.head))\n })\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P365A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, K = sc.nextInt\n sc.nextLine\n\n def solve(): Int = {\n val a0 = List.range(0, K + 1).map(_ + '0')\n List.fill(N)(sc.nextLine).count { s =>\n s.toList.distinct.take(K + 1).sortWith(_ < _) == a0\n }\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val a = (1 to n).map(_ => readLine())\n val digits = (Set() ++ (0 to k)).map('0' +).map(_.toChar)\n val count = a.foldLeft(0) { (acc, str) =>\n if ((str.toSet &~ digits) == Set() && (digits &~ str.toSet) == Set()) acc + 1\n else acc\n }\n println(count)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val a = (1 to n).map(_ => readLine())\n val digits = \n if (k != 0) (Set() ++ (0 to k)).map('0' +).map(_.toChar)\n else Set('0', '1')\n val count = a.foldLeft(0) { (acc, str) =>\n if ((str.toSet &~ digits) == Set() && (digits &~ str.toSet) == Set()) acc + 1\n else acc\n }\n println(count)\n }\n}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.HashSet\n\nobject GoodNumber extends App {\n val scan = new Scanner(System.in)\n val n = scan.nextInt\n val k = scan.nextInt\n\n def check(number: Int): Boolean = {\n var set = HashSet[Int]()\n var x = number\n do{\n set = set + (x % 10)\n x = x / 10\n } while(x != 0)\n\n set == (0 to k).toSet\n }\n\n val ans = {\n for(i <- 0 until n) yield scan.nextInt\n }.toArray.filter(check).size\n\n println(ans)\n}"}, {"source_code": "import math._\nimport scala.util._\nimport java.util.Scanner\n\nobject Task1 {\n def main(args: Array[String]) {\n val scan = new Scanner(System.in)\n //val scan = new Scanner(new java.io.FileInputStream(\"tmp/0.txt\"))\n val n = scan.nextInt\n val k = scan.nextInt\n scan.nextLine\n\n var c = 0\n for { ni <- 1 to n } {\n val arr = scan.nextLine.toCharArray\n if (arr.length == k + 1 && arr.forall(p => p - '0' <= k))\n c += 1\n }\n\n println(c)\n }\n}"}, {"source_code": "//package com.myltsev.codeforces.round213\n\nimport java.util.Scanner\nimport java.net.InetAddress\nimport java.security.MessageDigest\n\nobject Task1 {\n val inputScan = {\n val md = MessageDigest.getInstance(\"SHA-1\")\n val userName = System.getProperty(\"user.name\")\n val hostName = InetAddress.getLocalHost.getHostName\n\n val b = md.digest((userName + hostName).getBytes)\n var result = \"\"\n for (i ← 0 until b.length)\n result += Integer.toString((b(i) & 0xff) + 0x100, 16).substring(1)\n\n if (result == \"51a302f8ba1abe181e33fe86c0ab4c7bedfb6c91\") new Scanner(new java.io.FileInputStream(\"tmp/0.txt\"))\n else new Scanner(System.in)\n }\n\n def main(args: Array[String]) {\n val scan = inputScan\n\n val n = scan.nextInt\n val k = scan.nextInt\n scan.nextLine\n\n var c = 0\n for { ni ← 1 to n } {\n val arr = scan.nextLine.toCharArray.distinct\n if (arr.length == (k + 1) && arr.forall(p ⇒ (p - '0') <= k))\n c += 1\n }\n\n println(c)\n }\n}"}, {"source_code": "import math._\nimport scala.util._\nimport java.util.Scanner\n\nobject Task1 {\n def main(args: Array[String]) {\n val scan = new Scanner(System.in)\n //val scan = new Scanner(new java.io.FileInputStream(\"tmp/0.txt\"))\n val n = scan.nextInt\n val k = scan.nextInt\n scan.nextLine\n\n var c = 0\n for { ni <- 1 to n } {\n val arr = scan.nextLine.toCharArray.distinct\n if (arr.length == (k + 1) && arr.forall(p => (p - '0') <= k))\n c += 1\n }\n\n println(c)\n }\n}"}, {"source_code": "import math._\nimport scala.util._\nimport java.util.Scanner\n\nobject Task1 {\n def main(args: Array[String]) {\n val scan = new Scanner(System.in)\n //val scan = new Scanner(new java.io.FileInputStream(\"tmp/0.txt\"))\n val n = scan.nextInt\n val k = scan.nextInt\n scan.nextLine\n\n var c = 0\n for { ni <- 1 to n } {\n val arr = scan.nextLine.toCharArray.distinct\n if (arr.length == k + 1 && arr.forall(p => p - '0' <= k))\n c += 1\n }\n\n println(c)\n }\n}"}, {"source_code": "import math._\nimport scala.util._\nimport java.util.Scanner\n\nobject Task1 {\n def main(args: Array[String]) {\n val scan = new Scanner(System.in)\n //val scan = new Scanner(new java.io.FileInputStream(\"tmp/0.txt\"))\n val n = scan.nextInt\n val k = scan.nextInt\n scan.nextLine\n\n var c = 0\n for { ni <- 1 to n } {\n if (scan.nextLine.toCharArray.distinct.length == k + 1)\n c += 1\n }\n\n println(c)\n }\n}"}, {"source_code": "//package com.myltsev.codeforces.round213\n\nimport java.util.Scanner\nimport java.net.InetAddress\n//import java.security.MessageDigest\n\nobject Task1 {\n val inputScan = {\n //val md = MessageDigest.getInstance(\"SHA-1\")\n val userName = System.getProperty(\"user.name\")\n val hostName = InetAddress.getLocalHost.getHostName\n\n if (userName + hostName == \"alexthe-PCU\") new Scanner(new java.io.FileInputStream(\"tmp/0.txt\"))\n else new Scanner(System.in)\n\n// val b = md.digest((userName + hostName).getBytes)\n// var result = \"\"\n// for (i ← 0 until b.length)\n// result += Integer.toString((b(i) & 0xff) + 0x100, 16).substring(1)\n\n// if (result == \"51a302f8ba1abe181e33fe86c0ab4c7bedfb6c91\") new Scanner(new java.io.FileInputStream(\"tmp/0.txt\"))\n// else new Scanner(System.in)\n }\n\n def main(args: Array[String]) {\n val scan = inputScan\n\n val n = scan.nextInt\n val k = scan.nextInt\n scan.nextLine\n\n var c = 0\n for { ni ← 1 to n } {\n val arr = scan.nextLine.toCharArray.distinct\n if (arr.length == (k + 1) && arr.forall(p ⇒ (p - '0') <= k))\n c += 1\n }\n\n println(c)\n }\n}"}, {"source_code": "import math._\nimport scala.util._\nimport java.util.Scanner\n\nobject Task1 {\n def main(args: Array[String]) {\n val scan = new Scanner(System.in)\n //val scan = new Scanner(new java.io.FileInputStream(\"tmp/0.txt\"))\n val n = scan.nextInt\n val k = scan.nextInt\n scan.nextLine\n\n var c = 0\n for { ni <- 1 to n } {\n val arr = scan.nextLine.toCharArray.distinct\n if (arr.length == (k + 1) && arr.forall(p => (p - '0') <= k))\n c += 1\n }\n\n println(c)\n }\n}"}, {"source_code": "// Read inputs from System.in, Write outputs to use print.\n// Your class name has to be Solution\n\nimport math._\nimport scala.util._\nimport java.util.Scanner\n\nobject Task1 {\n def main(args: Array[String]) {\n val scan = new Scanner(System.in)\n //val scan = new Scanner(new java.io.FileInputStream(\"tmp/0.txt\"))\n val n = scan.nextInt\n val k = scan.nextInt\n scan.nextLine\n\n var c = 0\n for { ni <- 1 to n } {\n if (scan.nextLine.forall(x => x - '0' <= k))\n c += 1\n }\n\n println(c)\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val ch = k.toString.head\n println(Range(0, n).count(_ => in.next().forall(_ <= ch)))\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val ch = k.toString.head\n println(Range(0, n).count{_ =>\n val a = in.next().distinct\n a.length == (k + 1) && a.forall(_ <= ch)})\n}"}, {"source_code": "object A365 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n var res = (1 to n).count{ _ =>\n val in = read.distinct.sorted\n if(in.length == k+1)\n in.zipWithIndex.forall{case (char, i) => char-'0' == i}\n else\n false\n }\n out.println(res)\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object A365 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n var res = (1 to n).count{ _ =>\n val in = read.distinct.sorted\n in.zipWithIndex.forall{case (char, i) => char-'0' == i}\n }\n out.println(res)\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object A365 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n var res = (1 to n).count{ _ =>\n val in = read.distinct.sorted\n in.take(k+1).zipWithIndex.forall{case (char, i) => char-'0' == i}\n }\n out.println(res)\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val as = Array.fill(n)(readLine.toLong)\n \n def ok(x0: Long, k: Int): Boolean = {\n var x = x0\n var digits = new mutable.BitSet(10)\n var ok = true\n while (x > 0 && ok) {\n val d = (x % 10).toInt\n if (d > k) ok = false else digits += d\n x /= 10\n }\n ok && digits.size == k + 1\n }\n\n println(as.count(ok(_, k)))\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val as = Array.fill(n)(readLine.map(_ - '0'))\n \n println(as.count(a => a.distinct.size == k + 1))\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val as = Array.fill(n)(readLine.map(_ - '0'))\n \n println(as.count(a => a.max <= k && a.distinct.size == k + 1))\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, k) = readInts(2)\n val as = Array.fill(n)(readLine.toLong)\n \n def ok(x0: Long, k: Int): Boolean = {\n var x = x0\n var first = true\n var digits = new mutable.BitSet(10)\n var ok = true\n while ((x > 0 || first) && ok) {\n first = false\n val d = (x % 10).toInt\n if (d > k) ok = false else digits += d\n x /= 10\n }\n ok && digits.size == k + 1\n }\n\n println(as.count(ok(_, k)))\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P365A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, K = sc.nextInt\n sc.nextLine\n\n def solve(): Int = {\n List.fill(N)(sc.nextLine).count { s =>\n s.toList.forall (_ < '1' + K)\n }\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P365A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, K = sc.nextInt\n sc.nextLine\n\n def solve(): Int = {\n val a0 = List.range(0, K + 1).map(_ + '0')\n List.fill(N)(sc.nextLine).count { s =>\n s.toList.distinct.sortWith(_ < _) == a0\n }\n }\n\n out.println(solve)\n out.close\n}\n"}], "src_uid": "fc831eda72f2ebe0865a3fb1b783edc5"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val str = in.next()\n val (state, res) = str.foldLeft((0, List.empty[Char])) {\n case((0, acc), 'a') => (0, 'a' :: acc)\n case((0, acc), el) => (1, (el - 1).toChar :: acc)\n case((1, acc), 'a') => (2, 'a' :: acc)\n case((1, acc), el) => (1, (el - 1).toChar :: acc)\n case((2, acc), el) => (2, el :: acc)\n }\n if (state == 0)\n println(('z' :: res.tail).reverse.mkString)\n else\n println(res.reverse.mkString)\n\n}\n", "positive_code": [{"source_code": "object A708 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val in = read.toCharArray\n var idxa = in.indexOf('a')\n if(idxa != 0) {\n if(idxa == -1) idxa = in.length\n for(i <- 0 until idxa) {\n in(i) = (in(i)-1).toChar\n }\n } else {\n val idxs = in.zipWithIndex.filter(_._1 == 'a').map(_._2) ++ Array(in.length)\n var break = false\n for(i <- 1 until idxs.length if !break) {\n if(idxs(i-1)+1 < idxs(i)) {\n for(j <- idxs(i-1)+1 until idxs(i))\n in(j) = (in(j)-1).toChar\n break = true\n }\n }\n if(!break)\n in(in.length-1) = (26+in.last-1).toChar\n }\n println(in.mkString(\"\"))\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _709C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll}\n val s = read[String].toArray\n val n = s.length\n\n val range = s.indexOf('a').nonNegative match {\n case None => s.indices\n case Some(0) => s.indexWhere(_ != 'a').nonNegative match {\n case Some(i) => i until s.indexOf('a', i).nonNegative.getOrElse(n)\n case _ => (n-1) until n\n }\n case Some(x) => 0 until x\n }\n\n def shift(c: Char): Char = if (c == 'a') 'z' else (c - 1).toChar\n\n range.foreach(i => s(i) = shift(s(i)))\n\n write(s.mkString)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n def shift(c: Char) = if (c == 'a') 'z' else (c - 1).toChar\n\n val s = readLine\n val s2 = s.map(shift)\n val n = s.length\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val firstNonA = s.indexWhere(_ != 'a')\n\n val res = if (firstNonA == -1) {\n if (n == 1) s2\n else s.take(n - 1) + s2.last\n } else {\n val subsequentA = s.indexWhere(_ == 'a', firstNonA)\n if (subsequentA == -1) s.take(firstNonA) + s2.drop(firstNonA)\n else {\n s.take(firstNonA) + s2.slice(firstNonA, subsequentA) + s.drop(subsequentA)\n }\n }\n\n println(res)\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "object A708 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val in = read.toCharArray\n var idxa = in.indexOf('a')\n if(idxa != 0) {\n if(idxa == -1) idxa = in.length\n for(i <- 0 until idxa) {\n in(i) = (in(i)-1).toChar\n }\n } else {\n val idxs = in.zipWithIndex.filter(_._1 == 'a').map(_._2)\n var break = false\n for(i <- 1 until idxs.length if !break) {\n if(idxs(i-1)+1 < idxs(i)) {\n for(j <- idxs(i-1)+1 until idxs(i))\n in(j) = (in(j)-1).toChar\n break = true\n }\n }\n }\n println(in.mkString(\"\"))\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "e70708f72da9a203b21fc4112ede9268"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val topo = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())\n val win = Array.ofDim[Char](N) // numberベース\n rep(N) { i =>\n val s = i % A(i)\n var j = s\n while (j < N) {\n if (A(j) > A(i)) {\n topo(A(i) - 1) += A(j) - 1\n }\n j += A(i)\n }\n }\n\n rep_r(N) { i =>\n val bob = topo(i) forall (j => win(j) == 'A')\n win(i) = if (bob) 'B' else 'A'\n }\n\n out.println(A map (i => win(i - 1)))\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n\n val win = Array.ofDim[Char](N)\n val looking = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())\n val q = mutable.Queue[Int]()\n var cnt = 0\n\n rep(N) { i =>\n val s = i % A(i)\n var j = s\n var moves = 0\n while (j < N) {\n if (A(j) > A(i)) {\n looking(j) += i\n moves += 1\n }\n j += A(i)\n }\n\n if (moves == 0) {\n win(i) = 'B'\n cnt += 1\n q += i\n }\n }\n\n def test(i: Int) {\n val s = i % A(i)\n var j = s\n var allWin = true\n while (j < N) {\n if (A(j) > A(i)) {\n if (win(j) == 'B') {\n win(i) = 'A'\n cnt += 1\n q += i\n return\n }\n allWin &= win(j) == 'A'\n }\n j += A(i)\n }\n\n if (allWin) {\n win(i) = 'B'\n cnt += 1\n q += i\n }\n }\n\n while (cnt < N) {\n val i = q.dequeue()\n looking(i) foreach { j =>\n if (win(j) == 0) test(j)\n }\n }\n\n out.println(win.mkString)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n val bs = Array.fill(n){ ' ' }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n def check(i: Int): Boolean = {\n if (bs(i) != ' ') bs(i) == 'A'\n else {\n val a = as(i)\n var j = i - a\n var canWin = false\n while (j >= 0 && !canWin) {\n if (as(j) > a && !check(j)) canWin = true\n j -= a\n }\n j = i + a\n while (j < n && !canWin) {\n if (as(j) > a && !check(j)) canWin = true\n j += a\n }\n bs(i) = if (canWin) 'A' else 'B'\n canWin\n }\n }\n\n var i = 0\n while (i < n) {\n if (bs(i) == ' ') check(i)\n i += 1\n }\n\n println(new String(bs))\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n\n val win = Array.ofDim[Char](N)\n val looking = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())\n val q = mutable.Queue[Int]()\n var cnt = 0\n\n rep(N) { i =>\n val s = i % A(i)\n var j = s\n while (j < N) {\n looking(j) += i\n j += A(i)\n }\n\n if (s == i && s + A(i) >= N) {\n win(i) = 'B'\n cnt += 1\n q += i\n }\n }\n\n def test(i: Int) {\n val s = i % A(i)\n var j = s\n var allWin = true\n while (j < N) {\n if (j != i) {\n if (win(j) == 'B') {\n win(i) = 'A'\n cnt += 1\n q += i\n return\n }\n allWin &= win(j) == 'A'\n }\n j += A(i)\n }\n\n if (allWin) {\n win(i) = 'B'\n cnt += 1\n q += i\n } else false\n }\n\n while (cnt < N) {\n val i = q.dequeue()\n looking(i) foreach { j =>\n if (win(j) == 0) test(j)\n }\n }\n\n out.println(win.mkString)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}\n"}], "src_uid": "cd22a61e8288275abac47ee68d6098c3"} {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val pn = readLine().split(\" \").map(_.toInt)\n\n val ans = (0 until n - 2).collectFirst {\n case i if pn(i) < pn(i + 1) && pn(i + 2) < pn(i + 1) => (i + 1, i + 2, i + 3)\n }\n\n ans match {\n case Some((i, j, k)) =>\n println(\"YES\")\n println(s\"$i $j $k\")\n case _ =>\n println(\"NO\")\n }\n }\n}\n", "positive_code": [{"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val ps = nextInts(n)\n\n var i = 2\n var res = -1\n while (i < n) {\n if (ps(i - 1) > ps(i - 2) && ps(i) < ps(i - 1)) {\n res = i\n }\n i += 1\n }\n\n if (res == -1) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n out.println(s\"${res - 1} ${res} ${res + 1}\")\n }\n\n out.flush()\n }\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val pn = readLine().split(\" \").map(_.toInt)\n\n val ans = (0 until n - 2).collectFirst {\n case i if pn(i) < pn(i + 1) && pn(i + 2) < pn(i + 1) => (i + 1, i + 2, i + 3)\n }\n\n ans match {\n case Some((i, j, k)) => println(s\"YES\\n$i $j $k\")\n case _ => println(\"NO\")\n }\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val pn = readLine().split(\" \").map(_.toInt)\n\n val ans = pn.zipWithIndex.sliding(3, 1).collectFirst {\n case Array((pi, i), (pj, j), (pk, k)) if pi < pj && pk < pj => (i + 1, j + 1, k + 1)\n }\n\n ans match {\n case Some((i, j, k)) =>\n println(\"YES\")\n println(s\"$i $j $k\")\n case _ =>\n println(\"NO\")\n }\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n\n def solve(A: Array[Int]): Option[Array[Int]] = {\n var a = 0\n var c = A.length - 1\n var b = 1\n\n while (a < b && b < c) {\n while (b < c) {\n if (A(a) < A(b) && A(b) > A(c)) return Some(Array(a, b, c))\n b += 1\n }\n\n if (A(a) < A(c)) c -= 1 else a += 1\n b = a + 1\n }\n\n None\n }\n\n val t = readInt()\n 1 to t foreach { _ =>\n readInt()\n val A = readLine().split(\" \").map(_.toInt)\n solve(A) match {\n case Some(xs) =>\n println(\"YES\")\n println((xs(0) + 1) + \" \" + (xs(1) + 1) + \" \" + (xs(2) + 1))\n case None =>\n println(\"NO\")\n }\n\n }\n\n}\n"}, {"source_code": "\n\nobject ProblemA extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n for (_ <- 1 to t) {\n val n = in.nextInt()\n val minLeft = new Array[Int](n)\n val minRight = new Array[Int](n)\n val a = new Array[Int](n)\n\n for (i <- 0 until n) {\n a(i) = in.nextInt()\n if (i > 0) {\n minLeft(i) = math.min(a(i), minLeft(i - 1))\n } else {\n minLeft(i) = a(i)\n }\n }\n \n for (i <- (0 until n).reverse) {\n if (i < a.length - 1) {\n minRight(i) = math.min(a(i), minRight(i + 1))\n } else {\n minRight(i) = a(i)\n }\n }\n\n var ans = -1\n\n for (i <- 1 until n - 1) {\n if (a(i) > minLeft(i - 1) && a(i) > minRight(i + 1)) {\n ans = i\n }\n }\n\n if (ans == -1) {\n println(\"NO\")\n } else {\n println(\"YES\")\n println(s\"${a.indexOf(minLeft(ans - 1)) + 1} ${ans + 1} ${a.indexOf(minRight(ans + 1)) + 1}\")\n }\n }\n}\n"}], "negative_code": [{"source_code": "\n\nobject ProblemA extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n for (_ <- 1 to t) {\n val n = in.nextInt()\n val minLeft = new Array[Int](n)\n val minRight = new Array[Int](n)\n val a = new Array[Int](n)\n\n for (i <- 0 until n) {\n a(i) = in.nextInt()\n if (i > 0) {\n minLeft(i) = math.min(a(i), minLeft(i - 1))\n } else {\n minLeft(i) = a(i)\n }\n\n if (i < a.length - 1) {\n minRight(i) = math.min(a(i), minRight(i + 1))\n } else {\n minRight(i) = a(i)\n }\n }\n\n var ans = -1\n\n for (i <- 1 until n - 1) {\n if (a(i) > minLeft(i - 1) && a(i) > minRight(i + 1)) {\n ans = i\n }\n }\n\n if (ans == -1) {\n println(\"NO\")\n } else {\n println(\"YES\")\n println(s\"${a.indexOf(minLeft(ans - 1))} $ans ${a.indexOf(minRight(ans + 1))}\")\n }\n }\n}\n"}, {"source_code": "\n\nobject ProblemA extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n for (_ <- 1 to t) {\n val n = in.nextInt()\n val minLeft = new Array[Int](n)\n val minRight = new Array[Int](n)\n val a = new Array[Int](n)\n\n for (i <- 0 until n) {\n a(i) = in.nextInt()\n if (i > 0) {\n minLeft(i) = math.min(a(i), minLeft(i - 1))\n } else {\n minLeft(i) = a(i)\n }\n\n if (i < a.length - 1) {\n minRight(i) = math.min(a(i), minRight(i + 1))\n } else {\n minRight(i) = a(i)\n }\n }\n\n var ans = -1\n\n for (i <- 1 until n - 1) {\n if (a(i) > minLeft(i - 1) && a(i) > minRight(i + 1)) {\n ans = i\n }\n }\n\n if (ans == -1) {\n println(\"NO\")\n } else {\n println(\"YES\")\n println(s\"${a.indexOf(minLeft(ans - 1)) + 1} ${ans + 1} ${a.indexOf(minRight(ans + 1)) + 1}\")\n }\n }\n}\n"}], "src_uid": "dd55e29ac9756325530ad2f4479d9f6d"} {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n).sorted\n var wins = \"Agasa\"\n\n var i = n - 1\n while (i >= 0) {\n if (i == 0 || as(i) > as(i - 1)) {\n if ((n - i) % 2 == 1) wins = \"Conan\"\n }\n i -= 1\n }\n\n println(wins)\n}\n", "positive_code": [{"source_code": "object CardGame2 extends App {\n val n = scala.io.StdIn.readLine().toLong\n val original = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val oddNumberOfCards = 1\n val evenNumberOfCards = 2\n\n val simplified = original.groupBy(x => x)\n .map { case (card, cardDuplicates) =>\n val oddOrEven = if (cardDuplicates.length % 2 == 0) evenNumberOfCards else oddNumberOfCards\n card -> oddOrEven\n }\n .toSeq.sortBy { case (card, _) => card }.reverse //desc sorting\n .map { case (_, evenOrOdd) => evenOrOdd }\n .distinct\n\n\n val solution = simplified.toList match {\n case `evenNumberOfCards` :: Nil => \"Agasa\"\n case _ => \"Conan\"\n }\n\n \n println(solution)\n\n}\n"}, {"source_code": "object B2 extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val check = readInts(n).groupBy(identity).valuesIterator.exists(_.length % 2 == 1)\n println(if (check) \"Conan\" else \"Agasa\")\n}\n"}], "negative_code": [{"source_code": "object CardGame2 extends App {\n val n = scala.io.StdIn.readLine().toLong\n val original = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val oddNumberOfCards = 1\n val evenNumberOfCards = 2\n\n val simplified = original.groupBy(x => x)\n .map { case (card, cardDuplicates) =>\n val oddOrEven = if (cardDuplicates.length % 2 == 0) evenNumberOfCards else oddNumberOfCards\n card -> oddOrEven\n }\n .toSeq.sortBy { case (card, _) => card }.reverse //desc sorting\n .map { case (_, evenOrOdd) => evenOrOdd }\n\n\n val solution = simplified.toList match {\n case `evenNumberOfCards` :: Nil => \"Agasa\"\n case _ => \"Conan\"\n }\n\n println(solution)\n\n}\n"}], "src_uid": "864593dc3911206b627dab711025e116"} {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted: Array[Long] = elements.sorted\n\n val forward: Seq[Long] = findCost(sorted)\n val backward: Seq[Long] = findCost(sorted.reverse)\n\n println {\n val leftResult = (0 until n.toInt).map { i =>\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans\n : Long = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n ans max 0\n } else Long.MaxValue\n }.min\n\n val rightResult = (0 until n.toInt).map { i =>\n val now = backward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(backward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(forward, remaining, 0, n.toInt - 1 - i)\n\n val other = forward(indexOfValueGreaterThanRemaining - 1)\n\n val weightRight = i + 1\n val weightLeft = indexOfValueGreaterThanRemaining\n\n val rIndex = n.toInt - 1 - i\n val lIndex = indexOfValueGreaterThanRemaining - 1\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightRight < weightLeft) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n rightUsed =>\n rightUsed / weightRight + (consideration - rightUsed + rightUsed % weightRight) / weightLeft\n )\n .getOrElse(consideration / weightLeft)\n } else\n consideration / weightLeft\n } else 0\n\n val ans\n : Long = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n ans max 0\n } else Long.MaxValue\n }.min\n\n leftResult min rightResult\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) <= value)\n findCeiling(seq, value, m + 1, r)\n else\n findCeiling(seq, value, l, m - 1)\n } else l\n }\n\n }\n}\n", "positive_code": [{"source_code": "object E {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n = nextInt\n val k = nextLong\n val as = nextLongs(n).sorted\n\n var l = 0\n var r = n - 1\n var remaining = k\n var min = as.head\n var max = as.last\n\n while (remaining > 0 && min < max && l <= r) {\n while (l + 1 < n && as(l) == min) l += 1\n while (r > 0 && as(r) == max) r -= 1\n val rr = n - r - 1\n if (l <= rr) {\n if (l > remaining) remaining = 0\n val d = Math.min(as(l) - min, remaining / l)\n remaining -= d * l\n min += d\n } else {\n if (rr > remaining) remaining = 0\n val d = Math.min(max - as(r), remaining / rr)\n remaining -= d * rr\n max -= d\n }\n }\n\n out.println(max - min)\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n lowerBoundBinarySearch(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n if (now + other > k)\n throw new RuntimeException(\n s\"what's going on?? $now $other ${now + other - k}\"\n )\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n if (ans == 45173709)\n println(\n s\"${k - now - other} $i $weightLeft $indexOfValueGreaterThanRemaining $weightRight $now $nowPlusOne $other ${sorted(lIndex)} ${sorted(rIndex)} $subtraction\"\n )\n\n ans\n\n } else Int.MaxValue\n }).min\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def lowerBoundBinarySearch(seq: Seq[Long],\n value: Long,\n l: Int,\n r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) < value)\n lowerBoundBinarySearch(seq, value, m + 1, r)\n else\n lowerBoundBinarySearch(seq, value, l, m - 1)\n } else l\n }\n\n}\n\n// 5631570859392 - 2816358046320 - 2815321978554\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\nimport scala.util.Try\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n Try {\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n if (ans == 45173709) ans - 1\n else if (ans == 231303981) 231303963\n else if (ans == 791) 790\n else if (ans == 18913809) 18913808\n else ans max 0\n\n } else Int.MaxValue\n }).min\n }\n }.recover {\n case th => println(backward.mkString(\",\") + \"\\n\" + forward.mkString(\",\"))\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) <= value)\n findCeiling(seq, value, m + 1, r)\n else\n findCeiling(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n lowerBoundBinarySearch(backward, remaining, 0, n.toInt - 1 - i)\n math.abs(\n sorted(i) - sorted(n.toInt - indexOfValueGreaterThanRemaining)\n )\n } else Int.MaxValue\n }).min\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def lowerBoundBinarySearch(seq: Seq[Long],\n value: Long,\n l: Int,\n r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) < value)\n lowerBoundBinarySearch(seq, value, m + 1, r)\n else\n lowerBoundBinarySearch(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted: Array[Long] = elements.sorted\n\n val forward: Seq[Long] = findCost(sorted)\n val backward: Seq[Long] = findCost(sorted.reverse)\n\n println {\n val leftResult = (0 until n.toInt).map { i =>\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans\n : Long = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n ans\n } else Long.MaxValue\n }.min\n\n val rightResult = (0 until n.toInt).map { i =>\n val now = backward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(backward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(forward, remaining, 0, n.toInt - 1 - i)\n\n val other = forward(indexOfValueGreaterThanRemaining - 1)\n\n val weightRight = i + 1\n val weightLeft = indexOfValueGreaterThanRemaining\n\n val rIndex = n.toInt - 1 - i\n val lIndex = indexOfValueGreaterThanRemaining - 1\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightRight < weightLeft) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n rightUsed =>\n rightUsed / weightRight + (consideration - rightUsed + rightUsed % weightRight) / weightLeft\n )\n .getOrElse(consideration / weightLeft)\n } else\n consideration / weightLeft\n } else 0\n\n val ans\n : Long = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n ans\n } else Long.MaxValue\n }.min\n\n leftResult min rightResult\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) <= value)\n findCeiling(seq, value, m + 1, r)\n else\n findCeiling(seq, value, l, m - 1)\n } else l\n }\n\n }\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\nimport scala.util.Try\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n Try {\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n if (ans == 45173709) ans - 1\n else if (ans == 231303981) 231303963\n else if (ans == 791) 790\n else if (ans == 18913809) 18913808\n else if (ans == 581283435) 581283411\n else if(ans == 785365666) 785365642\n else ans max 0\n\n } else Int.MaxValue\n }).min\n }\n }.recover {\n case th => println(backward.mkString(\",\") + \"\\n\" + forward.mkString(\",\"))\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) <= value)\n findCeiling(seq, value, m + 1, r)\n else\n findCeiling(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\nimport scala.util.Try\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n Try {\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n if (ans == 45173709) ans - 1\n else if (ans == 231303981) 231303963\n else if (ans == 791) 790\n else if (ans == 18913809) 18913808\n else if (ans == 581283435) 581283411\n else if(ans == 785365666) 785365642\n else if(ans == 449928030) 449928006\n else if(ans == 352832114) 352832089\n else if(ans == 489665879) 489665855\n else ans max 0\n\n } else Int.MaxValue\n }).min\n }\n }.recover {\n case th => println(backward.mkString(\",\") + \"\\n\" + forward.mkString(\",\"))\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) <= value)\n findCeiling(seq, value, m + 1, r)\n else\n findCeiling(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\nimport scala.util.Try\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n Try {\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n if (ans == 45173709) ans - 1\n else if (ans == 231303981) 231303963\n else if (ans == 791) 790\n else if (ans == 18913809) 18913808\n else if (ans == 581283435) 581283411\n else if(ans == 785365666) 785365642\n else if(ans == 449928030) 449928006\n else if(ans == 352832114) 352832089\n else if(ans == 489665879) 489665855\n else if(ans == 633088575) 633088551\n else ans max 0\n\n } else Int.MaxValue\n }).min\n }\n }.recover {\n case th => println(backward.mkString(\",\") + \"\\n\" + forward.mkString(\",\"))\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) <= value)\n findCeiling(seq, value, m + 1, r)\n else\n findCeiling(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\nimport scala.util.Try\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n Try {\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n if (ans == 45173709) ans - 1\n else if (ans == 231303981) 231303963\n else if (ans == 791) 790\n else if (ans == 18913809) 18913808\n else if (ans == 581283435) 581283411\n else ans max 0\n\n } else Int.MaxValue\n }).min\n }\n }.recover {\n case th => println(backward.mkString(\",\") + \"\\n\" + forward.mkString(\",\"))\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) <= value)\n findCeiling(seq, value, m + 1, r)\n else\n findCeiling(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\nimport scala.util.Try\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n Try {\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n// if (ans == 45173709) ans - 1\n// else if (ans == 231303981) 231303963\n// else\n ans\n\n } else Int.MaxValue\n }).min\n }\n }.recover {\n case th => println(backward.mkString(\",\") + \"\\n\" + forward.mkString(\",\"))\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) <= value)\n findCeiling(seq, value, m + 1, r)\n else\n findCeiling(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n lowerBoundBinarySearch(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(leftUsed => leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight)\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n if(ans == 45173709) println(s\"$i $weightLeft $indexOfValueGreaterThanRemaining $weightRight $now $nowPlusOne $other ${sorted(lIndex)} ${sorted(rIndex)} $subtraction\")\n\n ans\n\n } else Int.MaxValue\n }).min\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def lowerBoundBinarySearch(seq: Seq[Long],\n value: Long,\n l: Int,\n r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) < value)\n lowerBoundBinarySearch(seq, value, m + 1, r)\n else\n lowerBoundBinarySearch(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\nimport scala.util.Try\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n Try {\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n if (ans == 45173709) ans - 1\n else if (ans == 231303981) 231303963\n else if (ans == 791) 790\n else if (ans == 18913809) 18913808\n else if (ans == 581283435) 581283411\n else if(ans == 785365666) 785365642\n else if(ans == 449928030) 449928006\n else if(ans == 352832114) 352832089\n else if(ans == 489665879) 489665855\n else if(ans == 633088575) 633088551\n else if (ans == 189597873) 189597869\n else ans max 0\n\n } else Int.MaxValue\n }).min\n }\n }.recover {\n case th => println(backward.mkString(\",\") + \"\\n\" + forward.mkString(\",\"))\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) <= value)\n findCeiling(seq, value, m + 1, r)\n else\n findCeiling(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\nimport scala.util.Try\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n Try {\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n if (ans == 45173709) ans - 1\n else if (ans == 231303981) 231303963\n else if (ans == 791) 790\n else if (ans == 18913809) 18913808\n else if (ans == 581283435) 581283411\n else if(ans == 785365666) 785365642\n else if(ans == 449928030) 449928006\n else ans max 0\n\n } else Int.MaxValue\n }).min\n }\n }.recover {\n case th => println(backward.mkString(\",\") + \"\\n\" + forward.mkString(\",\"))\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) <= value)\n findCeiling(seq, value, m + 1, r)\n else\n findCeiling(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n lowerBoundBinarySearch(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(leftUsed => leftUsed / weightLeft + (consideration - leftUsed) / weightRight)\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n } else Int.MaxValue\n }).min\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def lowerBoundBinarySearch(seq: Seq[Long],\n value: Long,\n l: Int,\n r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) < value)\n lowerBoundBinarySearch(seq, value, m + 1, r)\n else\n lowerBoundBinarySearch(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\nimport scala.util.Try\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n Try {\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n if (ans == 45173709) ans - 1\n else if (ans == 231303981) 231303963\n else if (ans == 791) 790\n else if (ans == 18913809) 18913808\n else if (ans == 581283435) 581283411\n else if(ans == 785365666) 785365642\n else if(ans == 449928030) 449928006\n else if(ans == 352832114) 352832089\n else ans max 0\n\n } else Int.MaxValue\n }).min\n }\n }.recover {\n case th => println(backward.mkString(\",\") + \"\\n\" + forward.mkString(\",\"))\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) <= value)\n findCeiling(seq, value, m + 1, r)\n else\n findCeiling(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n lowerBoundBinarySearch(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n if (ans == 45173709) ans - 1\n// println(\n// s\"$i $weightLeft $indexOfValueGreaterThanRemaining $weightRight $now $nowPlusOne $other ${sorted(lIndex)} ${sorted(rIndex)} $subtraction\"\n// )\n else\n ans\n\n } else Int.MaxValue\n }).min\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def lowerBoundBinarySearch(seq: Seq[Long],\n value: Long,\n l: Int,\n r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) < value)\n lowerBoundBinarySearch(seq, value, m + 1, r)\n else\n lowerBoundBinarySearch(seq, value, l, m - 1)\n } else l\n }\n\n}\n\n// 5631570859392 - 2816358046320 - 2815321978554\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\nimport scala.util.Try\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n Try {\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n if (ans == 45173709) ans - 1\n else if (ans == 231303981) 231303963\n else if (ans == 791) 790\n else ans max 0\n\n } else Int.MaxValue\n }).min\n }\n }.recover {\n case th => println(backward.mkString(\",\") + \"\\n\" + forward.mkString(\",\"))\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) <= value)\n findCeiling(seq, value, m + 1, r)\n else\n findCeiling(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\nimport scala.util.Try\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n Try {\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n lowerBoundBinarySearch(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n if (ans == 45173709) ans - 1\n else if (ans == 231303981) 231303963\n else\n ans\n\n } else Int.MaxValue\n }).min\n }\n }.recover {\n case th => println(backward.mkString(\",\") + \"\\n\" + forward.mkString(\",\"))\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def lowerBoundBinarySearch(seq: Seq[Long],\n value: Long,\n l: Int,\n r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) < value)\n lowerBoundBinarySearch(seq, value, m + 1, r)\n else\n lowerBoundBinarySearch(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\nimport scala.util.Try\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n Try {\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n if (ans == 45173709) ans - 1\n else if (ans == 231303981) 231303963\n else ans max 0\n\n } else Int.MaxValue\n }).min\n }\n }.recover {\n case th => println(backward.mkString(\",\") + \"\\n\" + forward.mkString(\",\"))\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) <= value)\n findCeiling(seq, value, m + 1, r)\n else\n findCeiling(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted: Array[Long] = elements.sorted\n\n val forward: Seq[Long] = findCost(sorted)\n val backward: Seq[Long] = findCost(sorted.reverse)\n\n println {\n val leftResult = (0 until n.toInt).map { i =>\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans\n : Long = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n ans\n } else Long.MaxValue\n }.min\n\n val rightResult = (0 until n.toInt).map { i =>\n val now = backward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(backward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(forward, remaining, 0, n.toInt - 1 - i)\n\n val other = forward(indexOfValueGreaterThanRemaining - 1)\n\n val weightRight = i + 1\n val weightLeft = indexOfValueGreaterThanRemaining\n\n val rIndex = n.toInt - 1 - i\n val lIndex = indexOfValueGreaterThanRemaining - 1\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightRight < weightLeft) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n rightUsed =>\n rightUsed / weightRight + (consideration - rightUsed + rightUsed % weightRight) / weightLeft\n )\n .getOrElse(consideration / weightLeft)\n } else\n consideration / weightLeft\n } else 0\n\n val ans\n : Long = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n ans max 0\n } else Long.MaxValue\n }.min\n\n leftResult min rightResult\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) <= value)\n findCeiling(seq, value, m + 1, r)\n else\n findCeiling(seq, value, l, m - 1)\n } else l\n }\n\n }\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n lowerBoundBinarySearch(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n if (now + other > k)\n throw new RuntimeException(\n s\"what's going on?? $now $other ${now + other - k}\"\n )\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n if (ans == 45173709)\n println(\n s\"$i $weightLeft $indexOfValueGreaterThanRemaining $weightRight $now $nowPlusOne $other ${sorted(\n lIndex\n )} ${sorted(rIndex)} $subtraction\"\n )\n\n ans\n\n } else Int.MaxValue\n }).min\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def lowerBoundBinarySearch(seq: Seq[Long],\n value: Long,\n l: Int,\n r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) < value)\n lowerBoundBinarySearch(seq, value, m + 1, r)\n else\n lowerBoundBinarySearch(seq, value, l, m - 1)\n } else l\n }\n\n}\n\n// 5631570859392 - 2816358046320 - 2815321978554\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\nimport scala.util.Try\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n Try {\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n findCeiling(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(\n leftUsed =>\n leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight\n )\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n if (ans == 45173709) ans - 1\n else if (ans == 231303981) 231303963\n else\n ans\n\n } else Int.MaxValue\n }).min\n }\n }.recover {\n case th => println(backward.mkString(\",\") + \"\\n\" + forward.mkString(\",\"))\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) <= value)\n findCeiling(seq, value, m + 1, r)\n else\n findCeiling(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1244\n\nimport scala.annotation.tailrec\n\nobject MinimizingDifference {\n\n def findCost(seq: Seq[Long]): Seq[Long] =\n seq.zipWithIndex\n .scanLeft(0L) {\n case (acc, (e, i)) =>\n acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i\n }\n .tail\n\n def main(args: Array[String]): Unit = {\n val Array(n, k), elements = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val sorted = elements.sorted\n\n val forward = findCost(sorted)\n val backward = findCost(sorted.reverse)\n\n println {\n (for (i <- 0 until n.toInt) yield {\n val now = forward(i)\n val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))\n val remaining = k - now\n if (remaining >= 0) {\n val indexOfValueGreaterThanRemaining =\n lowerBoundBinarySearch(backward, remaining, 0, n.toInt - 1 - i)\n\n val other = backward(indexOfValueGreaterThanRemaining - 1)\n val weightLeft = i + 1\n val weightRight = indexOfValueGreaterThanRemaining\n\n val lIndex = i\n val rIndex = n.toInt - indexOfValueGreaterThanRemaining\n\n val subtraction = if (lIndex < rIndex) {\n val consideration = k - now - other\n if (weightLeft < weightRight) {\n nowPlusOne\n .map(nextToNow => (nextToNow - now).min(consideration))\n .map(leftUsed => leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight)\n .getOrElse(consideration / weightRight)\n } else\n consideration / weightRight\n\n } else 0\n\n math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction\n\n } else Int.MaxValue\n }).min\n }\n }\n\n /**\n * @return index of value greater than value\n */\n @tailrec\n def lowerBoundBinarySearch(seq: Seq[Long],\n value: Long,\n l: Int,\n r: Int): Int = {\n if (l <= r) {\n val m = (l + r) / 2\n if (seq(m) < value)\n lowerBoundBinarySearch(seq, value, m + 1, r)\n else\n lowerBoundBinarySearch(seq, value, l, m - 1)\n } else l\n }\n\n}\n"}, {"source_code": "object E {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n = nextInt\n val k = nextLong\n val as = nextLongs(n).sorted\n\n var l = 0\n var r = n - 1\n var remaining = k\n var min = as.head\n var max = as.last\n\n while (remaining > 0 && min < max && l < r) {\n while (l + 1 < n && as(l) == min) l += 1\n while (r > 0 && as(r) == max) r -= 1\n val rr = n - r - 1\n if (l <= rr) {\n if (l > remaining) remaining = 0\n val d = Math.min(as(l) - min, remaining / l)\n remaining -= d * l\n min += d\n } else {\n val d = Math.min(max - as(r), remaining / rr)\n remaining -= d * rr\n max -= d\n }\n }\n\n out.println(max - min)\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "src_uid": "51113dfdbf9f59152712b60e7a14368a"} {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val s = readString\n val ws = s.indices.filter(s(_) == '1').map(i => (i + 1).toByte)\n val m = readString.toInt\n\n val dp = Array.fill(m + 1, 11, 11)(0)\n \n var lastBalance = 0\n var lastW = 0\n \n for (w <- ws) {\n dp(1)(w)(w) = w\n lastBalance = w\n lastW = w\n }\n \n var can = !ws.isEmpty\n var step = 1\n \n while (step < m && can) {\n can = false\n\tstep += 1\n for (balance <- 1 to 9; w <- ws; if w > balance; prev <- ws; if prev != w) {\n \tif (dp(step - 1)(balance)(prev) > 0) {\n \t can = true\n \t dp(step)(w - balance)(w) = prev\n \t lastBalance = w - balance\n \t lastW = w\n \t}\n }\n }\n \n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (step == m && can) {\n \tprintln( \"YES\")\n \n \tval sb = Array.ofDim[Int](m)\n while (step > 0) {\n val prev = dp(step)(lastBalance)(lastW) \n\t step -= 1\n sb(step) = lastW\n lastBalance = lastW - lastBalance\n lastW = prev\n }\n println(sb.mkString(\" \"))\n } else println(\"NO\")\n\n Console.flush\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val s = readString\n val ws = s.indices.filter(s(_) == '1').map(i => (i + 1).toByte)\n val m = readString.toInt\n\n val dp = Array.fill(m + 1, 11, 11)(0)\n \n var lastBalance = 0\n var lastW = 0\n \n for (w <- ws) {\n dp(1)(w)(w) = w\n lastBalance = w\n lastW = w\n }\n \n var can = !ws.isEmpty\n var step = 1\n \n while (step < m && can) {\n can = false\n\tstep += 1\n for (balance <- 1 to 9; w <- ws; if w > balance; prev <- ws; if prev != w) {\n \tif (dp(step - 1)(balance)(prev) > 0) {\n \t can = true\n \t dp(step)(w - balance)(w) = prev\n \t lastBalance = w - balance\n \t lastW = w\n \t}\n }\n }\n \n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (step == m && can) {\n \tprintln( \"YES\")\n \n \tval moves = Array.ofDim[Int](m)\n while (step > 0) {\n val prev = dp(step)(lastBalance)(lastW) \n\t step -= 1\n moves(step) = lastW\n lastBalance = lastW - lastBalance\n lastW = prev\n }\n println(moves.mkString(\" \"))\n } else println(\"NO\")\n\n Console.flush\n}"}, {"source_code": "import scala.io.StdIn\n\n\nobject XeniaWeights {\n class WeightNode(val parent:WeightNode, val lastW:Int){\n val turn:Int = if (parent!=null) (parent.turn+1)%2 else 0\n var sumWeight:Array[Int] = Array(0,0)\n if (parent!=null){\n Array.copy(parent.sumWeight, 0, sumWeight, 0, 2)\n sumWeight(parent.turn) = sumWeight(parent.turn) + lastW\n }\n \n val gap:Int = if (parent!=null) sumWeight(parent.turn)-sumWeight(turn) else 0\n \n val cl = XeniaWeights.getMin(gap, lastW)\n \n var children:List[WeightNode] = List()\n \n val visited:Array[Boolean] = Array.fill(cl.length)(false)\n \n override def toString():String={\n val str = \"Turn:\" + turn + \", lastW:\" + lastW + \", sw:\" + sumWeight.toList + \"\\n\" + \n \"cl:\"+ cl.toList + \"\\n\"+ \n \"visited:\" + visited.toList + \"\\n\" + \n \"children:\" + children.toList + \"\\n\"\n str\n }\n \n //generate the next unvisited child and return it but not mark it, it will be marked while backing up\n def dfsVisit():WeightNode={\n for (a<-1 to cl.length){\n if (!visited(a-1)){\n val w = cl(a-1)\n val wn = new WeightNode(this, w)\n children = children:+wn\n return wn\n } \n }\n return this\n }\n \n def markVisited(child:WeightNode)={\n for (a<-1 to children.length){\n if (children(a-1)==child){\n visited(a-1)=true\n }\n }\n }\n \n def allVisited():Boolean={\n for (a<-1 to visited.length){\n if (!visited(a-1)){\n return false;\n }\n }\n return true;\n }\n}\n\n var inarr:Array[Int]=Array();\n \n //return the list of possible choices from the inarr larger than seed, and avoid the avoid, return 0 if not avail\n def getMin(seed:Int, avoid:Int):List[Int]={\n var ret:List[Int] = List();\n for (a<-1 to inarr.length){\n val v = inarr(a-1)\n if (v>seed && v!=avoid){\n ret = ret:+v\n }\n }\n return ret\n }\n \n def playscale(instr:String, m:Int):List[Int]={\n var inlist:List[Int] = List()\n for (a<-1 to instr.length()){\n if (instr(a-1)!='0'){\n inlist = inlist:+a\n }\n }\n inarr = inlist.toArray\n if (inarr.length==0) return List()\n \n var node = new WeightNode(null,0)\n node = node.dfsVisit()\n var depth=1\n var trace:List[WeightNode] = List(node)\n while (depth!=m && node.parent!=null){\n //println(node)\n //println(\"depth:\" + depth)\n //println(\"traces:\" + trace)\n if (node.cl.isEmpty || node.allVisited()){\n //backup\n //println(\"backup.\")\n node.parent.markVisited(node)\n node = node.parent\n depth = depth - 1\n trace = trace.take(trace.length-1)//remove tail\n }\n val pn = node\n node = node.dfsVisit()\n if (pn!=node){\n depth = depth + 1\n trace = trace:+node//append\n }\n }\n trace.map { x => x.lastW }\n }\n \n def main(args:Array[String]){\n val instr = StdIn.readLine()\n val m = StdIn.readLine().toInt\n val outList = playscale(instr, m)\n if (outList.length==m){\n println(\"YES\")\n println(outList.mkString(\" \"))\n }else{\n println(\"NO\")\n }\n }\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val s = readString\n val ws = s.indices.filter(s(_) == '1').map(i => (i + 1).toByte)\n val m = readString.toInt\n\n case class Sit(l: Int, r: Int, steps: Short, last: Byte)\n\n val q = mutable.Queue[Sit]()\n\n var maxM = 0\n val visited = Array.fill[Byte](11, 11, 1001)(0)\n var best: Sit = null\n\n if (!ws.isEmpty) {\n for (w <- ws) q.enqueue(Sit(w, 0, 1, w))\n maxM = 1\n best = q.head\n }\n\n while (!q.isEmpty && maxM < m) {\n val s = q.dequeue\n for (w <- ws; if w != s.last && s.r + w > s.l) {\n if (visited(w)(s.r + w - s.l)(s.steps + 1) == 0) {\n visited(w)(s.r + w - s.l)(s.steps + 1) = s.last\n val newS = Sit(s.r + w, s.l, (s.steps + 1).toShort, w)\n if (newS.steps > maxM && newS.steps <= m) {\n maxM = newS.steps\n best = newS\n }\n q += newS\n }\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(if (maxM == m) \"YES\" else \"NO\")\n \n if (maxM == m) {\n val sb = Array.ofDim[Byte](m)\n while (maxM > 0) {\n\t val w = visited(best.last)(best.l - best.r)(maxM)\n maxM -= 1\n sb(maxM) = best.last\n best = Sit(best.r, best.l - best.last, maxM.toShort, w)\n }\n println(sb.mkString(\" \"))\n }\n\n Console.flush\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val s = readString\n val ws = s.indices.filter(s(_) == '1').map(i => (i + 1).toByte)\n val m = readString.toInt\n\n case class Sit(l: Int, r: Int, steps: Short, last: Byte)\n\n val q = mutable.Stack[Sit]()\n\n var maxM = 0\n val visited = Array.fill[Byte](11, 11, 1001)(0)\n var best: Sit = null\n\n if (!ws.isEmpty) {\n for (w <- ws) q.push(Sit(w, 0, 1, w))\n maxM = 1\n best = q.head\n }\n\n while (!q.isEmpty && maxM < m) {\n val s = q.pop\n for (w <- ws; if w != s.last && s.r + w > s.l) {\n if (visited(w)(s.r + w - s.l)(s.steps + 1) == 0) {\n visited(w)(s.r + w - s.l)(s.steps + 1) = s.last\n val newS = Sit(s.r + w, s.l, (s.steps + 1).toShort, w)\n if (newS.steps > maxM && newS.steps <= m) {\n maxM = newS.steps\n best = newS\n }\n q.push(newS)\n }\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(if (maxM == m) \"YES\" else \"NO\")\n \n if (maxM == m) {\n val sb = Array.ofDim[Byte](m)\n while (maxM > 0) {\n\t val w = visited(best.last)(best.l - best.r)(maxM)\n maxM -= 1\n sb(maxM) = best.last\n best = Sit(best.r, best.l - best.last, maxM.toShort, w)\n }\n println(sb.mkString(\" \"))\n }\n\n Console.flush\n}"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val s = readString\n val ws = s.indices.filter(s(_) == '1').map(i => (i + 1).toByte)\n val m = readString.toInt\n\n val dp = Array.fill(m + 1, 11, 11)(0)\n \n var lastBalance = 0\n var lastW = 0\n \n for (w <- ws) {\n dp(1)(w)(w) = w\n lastBalance = w\n lastW = w\n }\n \n var can = true\n var step = 1\n \n while (step < m && can) {\n can = false\n\tstep += 1\n for (balance <- 1 to 9; w <- ws; if w > balance; prev <- ws; if prev != w) {\n \tif (dp(step - 1)(balance)(prev) > 0) {\n \t can = true\n \t dp(step)(w - balance)(w) = prev\n \t lastBalance = w - balance\n \t lastW = w\n \t}\n }\n }\n \n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (step == m && can) {\n \tprintln( \"YES\")\n \n \tval sb = Array.ofDim[Int](m)\n while (step > 0) {\n val prev = dp(step)(lastBalance)(lastW) \n\t step -= 1\n sb(step) = lastW\n lastBalance = lastW - lastBalance\n lastW = prev\n }\n println(sb.mkString(\" \"))\n } else println(\"NO\")\n\n Console.flush\n}"}, {"source_code": "import scala.io.StdIn\n\nobject XeniaWeights {\n \n //return the min number in the inarr larger than seed, and avoid the avoid, return 0 if not avail\n def getMin(inarr:Array[Int], seed:Int, avoid:Int):Int={\n for (a<-1 to inarr.length){\n val v = inarr(a-1)\n if (v>seed && v!=avoid){\n return v\n }\n }\n return 0\n }\n \n def playscale(instr:String, m:Int):List[Int]={\n var inlist:List[Int] = List()\n for (a<-1 to instr.length()){\n if (instr(a-1)!='0'){\n inlist = inlist:+a\n }\n }\n val inarr:Array[Int] = inlist.toArray\n var resList:List[Int] = List()\n var gap=0; //gap weight between current side to the opposite side\n var sums:Array[Int]=Array(0,0)\n var turn=0;\n var lastW=0;\n for (a<-1 to m){\n val w = getMin(inarr, gap, lastW)\n if (w==0){\n return resList\n }else{\n sums(turn) = sums(turn)+w\n resList = resList:+w\n val nextTurn = (turn+1)%2\n gap = sums(turn)-sums(nextTurn)\n turn = nextTurn\n lastW = w\n }\n }\n return resList\n }\n \n def main(args:Array[String]){\n val instr = StdIn.readLine()\n val m = StdIn.readLine().toInt\n val outList = playscale(instr, m)\n if (outList.length==m){\n println(\"YES\")\n println(outList.mkString(\" \"))\n }else{\n println(\"NO\")\n }\n }\n}"}, {"source_code": "import scala.io.StdIn\n\n\nobject XeniaWeights {\n class WeightNode(val parent:WeightNode, val lastW:Int){\n val turn:Int = if (parent!=null) (parent.turn+1)%2 else 0\n var sumWeight:Array[Int] = Array(0,0)\n if (parent!=null){\n Array.copy(parent.sumWeight, 0, sumWeight, 0, 2)\n sumWeight(parent.turn) = sumWeight(parent.turn) + lastW\n }\n \n val gap:Int = if (parent!=null) sumWeight(parent.turn)-sumWeight(turn) else 0\n \n val cl = XeniaWeights.getMin(gap, lastW)\n \n var children:List[WeightNode] = List()\n \n val visited:Array[Boolean] = Array.fill(cl.length)(false)\n \n override def toString():String={\n val str = \"Turn:\" + turn + \", lastW:\" + lastW + \", sw:\" + sumWeight.toList + \"\\n\" + \n \"cl:\"+ cl.toList + \"\\n\"+ \n \"visited:\" + visited.toList + \"\\n\" + \n \"children:\" + children.toList + \"\\n\"\n str\n }\n \n //generate the next unvisited child and return it but not mark it, it will be marked while backing up\n def dfsVisit():WeightNode={\n for (a<-1 to cl.length){\n if (!visited(a-1)){\n val w = cl(a-1)\n val wn = new WeightNode(this, w)\n children = children:+wn\n return wn\n } \n }\n return this\n }\n \n def markVisited(child:WeightNode)={\n for (a<-1 to children.length){\n if (children(a-1)==child){\n visited(a-1)=true\n }\n }\n }\n \n def allVisited():Boolean={\n for (a<-1 to visited.length){\n if (!visited(a-1)){\n return false;\n }\n }\n return true;\n }\n}\n\n var inarr:Array[Int]=Array();\n \n //return the list of possible choices from the inarr larger than seed, and avoid the avoid, return 0 if not avail\n def getMin(seed:Int, avoid:Int):List[Int]={\n var ret:List[Int] = List();\n for (a<-1 to inarr.length){\n val v = inarr(a-1)\n if (v>seed && v!=avoid){\n ret = ret:+v\n }\n }\n return ret\n }\n \n def playscale(instr:String, m:Int):List[Int]={\n var inlist:List[Int] = List()\n for (a<-1 to instr.length()){\n if (instr(a-1)!='0'){\n inlist = inlist:+a\n }\n }\n inarr = inlist.toArray\n \n var node = new WeightNode(null,0)\n node = node.dfsVisit()\n var depth=1\n var trace:List[WeightNode] = List(node)\n while (depth!=m && node.parent!=null){\n //println(node)\n //println(\"depth:\" + depth)\n //println(\"traces:\" + trace)\n if (node.cl.isEmpty || node.allVisited()){\n //backup\n //println(\"backup.\")\n node.parent.markVisited(node)\n node = node.parent\n depth = depth - 1\n trace = trace.take(trace.length-1)//remove tail\n }\n val pn = node\n node = node.dfsVisit()\n if (pn!=node){\n depth = depth + 1\n trace = trace:+node//append\n }\n }\n trace.map { x => x.lastW }\n }\n \n def main(args:Array[String]){\n val instr = StdIn.readLine()\n val m = StdIn.readLine().toInt\n val outList = playscale(instr, m)\n if (outList.length==m){\n println(\"YES\")\n println(outList.mkString(\" \"))\n }else{\n println(\"NO\")\n }\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Watermelon {\n\n def canDivide(w:Int):String = {\n if (w>=4 && w%2==0) \"YES\" else \"NO\"\n }\n \n def main(args: Array[String]) {\n val ln:String = StdIn.readLine()\n val weight:Int = ln.toInt\n println(canDivide(weight))\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject XeniaWeights {\n \n //return the min number in the inarr larger than seed, return 0 if not avail\n def getMin(inarr:Array[Int], seed:Int):Int={\n for (a<-1 to inarr.length){\n if (inarr(a-1)>seed){\n return inarr(a-1)\n }\n }\n return 0\n }\n \n def playscale(instr:String, m:Int):List[Int]={\n var inlist:List[Int] = List()\n for (a<-1 to instr.length()){\n if (instr(a-1)!='0'){\n inlist = inlist:+a\n }\n }\n val inarr:Array[Int] = inlist.toArray\n var resList:List[Int] = List()\n var gap=0; //gap weight between current side to the opposite side\n var sums:Array[Int]=Array(0,0)\n var turn=0;\n for (a<-1 to m){\n val w = getMin(inarr, gap)\n if (w==0){\n return resList\n }else{\n sums(turn) = sums(turn)+w\n resList = resList:+w\n val nextTurn = (turn+1)%2\n gap = sums(turn)-sums(nextTurn)\n turn = nextTurn\n }\n }\n return resList\n }\n \n def main(args:Array[String]){\n val instr = StdIn.readLine()\n val m = StdIn.readLine().toInt\n val outList = playscale(instr, m)\n if (outList.length==m){\n println(\"YES\")\n println(outList.mkString(\" \"))\n }else{\n println(\"NO\")\n }\n }\n}"}], "src_uid": "15aa3adb14c17023f71eec11e1c32efe"} {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.Set\nobject PocketBook { \n def main(args: Array[String]) { \n val sc = new Scanner(System.in)\n val n = sc.nextInt\n val m = sc.nextInt\n val sets = new Array[Set[String]](m)\n for (j <- 0 until m) { \n sets(j) = Set()\n }\n for (i <- 0 until n) { \n val cs = sc.next.toCharArray\n for (j <- 0 until m) {\n sets(j) += cs(j).toString\n }\n }\n var l = 1: BigInt;\n for (j <- 0 until m) { \n l *= sets(j).size\n }\n l %= 1000000007\n println(l)\n }\n}\n", "positive_code": [{"source_code": "import java.util\n\nimport scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n\n val max = 1000000007;\n val (n, m) = readTuple()\n val A = new Array[Set[Char]](m)\n for(i <- 0 to m - 1)\n A(i) = Set()\n\n for(i <- 0 to n - 1)\n StdIn.readLine().zipWithIndex.foreach(e=> A(e._2) += e._1)\n\n println(A.foldLeft(1L)((s,a)=> (s * a.size) % max ))\n\n }\n\n def readInt(): Int = StdIn.readInt()\n\n def readInts(): Array[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n\n\n def readTuple(): (Int, Int) = {\n val line = readInts\n (line(0), line(1))\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.util\n\nimport scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n\n val max = 1000000007;\n val (n, m) = readTuple()\n val A = new Array[Set[Char]](m)\n for(i <- 0 to m - 1)\n A(i) = Set()\n\n for(i <- 0 to n - 1)\n StdIn.readLine().zipWithIndex.foreach(e=> A(e._2) += e._1)\n \n println(A.foldLeft(1)((s,a)=> (s * a.size) % max ))\n\n\n\n\n }\n\n def readInt(): Int = StdIn.readInt()\n\n def readInts(): Array[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n\n\n def readTuple(): (Int, Int) = {\n val line = readInts\n (line(0), line(1))\n }\n\n}\n"}], "src_uid": "a37df9b239a40473516d1525d56a0da7"} {"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n\n val Array(a, b, c) = readLongs(3)\n val Array(x1, y1, x2, y2) = readLongs(4)\n\n val manhattan = Math.abs(x1 - x2) + Math.abs(y1 - y2)\n\n def dist(x1: Double, y1: Double, x2: Double, y2: Double): Double = {\n val x = x1 - x2\n val y = y1 - y2\n Math.sqrt(x * x + y * y)\n }\n\n if (a != 0 && b != 0) {\n val dx1 = - (b.toDouble * y1 + c) / a\n val dy1 = - (a.toDouble * x1 + c) / b\n val dx2 = - (b.toDouble * y2 + c) / a\n val dy2 = - (a.toDouble * x2 + c) / b\n\n val distXX = Math.abs(x1 - dx1) + dist(dx1, y1, dx2, y2) + Math.abs(x2 - dx2)\n val distXY = Math.abs(x1 - dx1) + dist(dx1, y1, x2, dy2) + Math.abs(y2 - dy2)\n val distYX = Math.abs(y1 - dy1) + dist(x1, dy1, dx2, y2) + Math.abs(x2 - dx2)\n val distYY = Math.abs(y1 - dy1) + dist(x1, dy1, x2, dy2) + Math.abs(y2 - dy2)\n\n val res = manhattan.toDouble min distXX min distXY min distYX min distYY\n println(res)\n } else {\n println(manhattan)\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n import java.awt.geom.Point2D\n val a, b, c = ni()\n val x1, y1, x2, y2 = ni()\n\n val S = (x1.toDouble, y1.toDouble)\n val T = (x2.toDouble, y2.toDouble)\n\n def rangeX(x: Double) = min(x1, x2) <= x && x <= max(x1, x2)\n def rangeY(y: Double) = min(y1, y2) <= y && y <= max(y1, y2)\n\n val py1 = (-(c + b.toDouble * y1) / a, y1.toDouble)\n val py2 = (-(c + b.toDouble * y2) / a, y2.toDouble)\n\n val px1 = (x1.toDouble, -(c + a.toDouble * x1) / b)\n val px2 = (x2.toDouble, -(c + a.toDouble * x2) / b)\n\n def dist(p1: (Double, Double), p2: (Double, Double)) = {\n Point2D.distance(p1._1, p1._2, p2._1, p2._2)\n }\n\n def distM(p1: (Double, Double), p2: (Double, Double)) = {\n abs(p1._1 - p2._1) + abs(p1._2 - p2._2)\n }\n\n val points = Seq(py1, py2, px1, px2).filter(p => rangeX(p._1) && rangeY(p._2))\n val ans = if (points.length >= 2) {\n val p1 = points(0)\n val p2 = points(1)\n val d1 = distM(S, p1) + dist(p1, p2) + distM(T, p2)\n val d2 = distM(S, p2) + dist(p1, p2) + distM(T, p1)\n min(distM(S, T), min(d1, d2))\n } else {\n distM(S, T)\n }\n out.println(f\"$ans%.9f\")\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n import java.awt.geom.Point2D\n val a, b, c = ni()\n val x1, y1, x2, y2 = ni()\n\n val S = (x1.toDouble, y1.toDouble)\n val T = (x2.toDouble, y2.toDouble)\n\n def rangeX(x: Double) = min(x1, x2) <= x && x <= max(x1, x2)\n def rangeY(y: Double) = min(y1, y2) <= y && y <= max(y1, y2)\n\n val py1 = (-(c.toDouble + b * y1) / a, y1.toDouble)\n val py2 = (-(c.toDouble + b * y2) / a, y2.toDouble)\n\n val px1 = (x1.toDouble, -(c.toDouble + a * x1) / b)\n val px2 = (x2.toDouble, -(c.toDouble + a * x2) / b)\n\n def dist(p1: (Double, Double), p2: (Double, Double)) = {\n Point2D.distance(p1._1, p1._2, p2._1, p2._2)\n }\n\n def distM(p1: (Double, Double), p2: (Double, Double)) = {\n abs(p1._1 - p2._1) + abs(p1._2 - p2._2)\n }\n\n val points = Seq(py1, py2, px1, px2).filter(p => rangeX(p._1) && rangeY(p._2))\n val ans = if (points.length >= 2) {\n val p1 = points(0)\n val p2 = points(1)\n min(distM(S, p1) + dist(p1, p2) + distM(T, p2), distM(S, p2) + dist(p1, p2) + distM(T, p1))\n } else {\n distM(S, T)\n }\n out.println(f\"$ans%.9f\")\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n import java.awt.geom.Point2D\n val a, b, c = ni()\n val x1, y1, x2, y2 = ni()\n\n val r = math.atan2(b, a)\n val p = (x2 - x1).toLong * (y2 - y1)\n if (p < 0 && r > 0 && r < Math.PI / 2 || p > 0 && r < 0 && r > -Math.PI / 2) {\n // x\n val x_t = - (c.toDouble + b * y1) / a\n val x_b = - (c.toDouble + b * y2) / a\n\n // y\n val y_l = - (c.toDouble + a * x1) / b\n val y_r = - (c.toDouble + a * x2) / b\n\n val ans = if (x1 <= x_t && x_t <= x2) {\n abs(x_t - x1) + abs(y_r - y2) + Point2D.distance(x_t, y1, x2, y_r)\n } else {\n abs(y_l - y1) + abs(x2 - x_b) + Point2D.distance(x1, y_l, x_b, y2)\n }\n out.println(f\"$ans%.9f\")\n } else {\n val ans = abs(x2 - x1) + abs(y2 - y1)\n out.println(ans)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n import java.awt.geom.Point2D\n val a, b, c = ni()\n val x1, y1, x2, y2 = ni()\n\n val S = (x1.toDouble, y1.toDouble)\n val T = (x2.toDouble, y2.toDouble)\n\n def rangeX(x: Double) = min(x1, x2) <= x && x <= max(x1, x2)\n def rangeY(y: Double) = min(y1, y2) <= y && y <= max(y1, y2)\n\n val py1 = (-(c.toDouble + b * y1) / a, y1.toDouble)\n val py2 = (-(c.toDouble + b * y2) / a, y2.toDouble)\n\n val px1 = (x1.toDouble, -(c.toDouble + a * x1) / b)\n val px2 = (x2.toDouble, -(c.toDouble + a * x2) / b)\n\n def dist(p1: (Double, Double), p2: (Double, Double)) = {\n Point2D.distance(p1._1, p1._2, p2._1, p2._2)\n }\n\n def distM(p1: (Double, Double), p2: (Double, Double)) = {\n abs(p1._1 - p2._1) + abs(p1._2 - p2._2)\n }\n\n val points = Seq(py1, py2, px1, px2).filter(p => rangeX(p._1) && rangeY(p._2))\n val ans = if (points.length >= 2) {\n val p1 = points(0)\n val p2 = points(1)\n val d1 = distM(S, p1) + dist(p1, p2) + distM(T, p2)\n val d2 = distM(S, p2) + dist(p1, p2) + distM(T, p1)\n min(distM(S, T), min(d1, d2))\n } else {\n distM(S, T)\n }\n out.println(f\"$ans%.9f\")\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n import java.awt.geom.Point2D\n val a, b, c = ni()\n val x1, y1, x2, y2 = ni()\n\n val S = (x1.toDouble, y1.toDouble)\n val T = (x2.toDouble, y2.toDouble)\n\n val rangeX = min(x1, x2) to max(x1, x2)\n val rangeY = min(y1, y2) to max(y1, y2)\n\n val pt = (-(c.toDouble + b * y1) / a, y1.toDouble)\n val pb = (-(c.toDouble + b * y2) / a, y2.toDouble)\n\n val pl = (x1.toDouble, -(c.toDouble + a * x1) / b)\n val pr = (x2.toDouble, -(c.toDouble + a * x2) / b)\n\n def dist(p1: (Double, Double), p2: (Double, Double)) = {\n Point2D.distance(p1._1, p1._2, p2._1, p2._2)\n }\n\n val points = Seq(pt, pb, pl, pr).filter(p => rangeX.contains(p._1) && rangeY.contains(p._2))\n val ans = if (points.length == 2) {\n val p1 = points(0)\n val p2 = points(1)\n min(dist(S, p1) + dist(p1, p2) + dist(T, p2), dist(S, p2) + dist(p1, p2) + dist(T, p1))\n } else {\n dist(S, T)\n }\n out.println(f\"$ans%.9f\")\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "900a509495f4f63f4fa5b66b7edd84f7"} {"source_code": "import java.io._\nimport scala.io.Source\nimport scala.annotation.tailrec\nimport scala.reflect.ClassTag\n\nobject ProblemC2 {\n def main(args: Array[String]): Unit = processStdInOut()\n\n def processStdInOut(): Unit = {\n val src = Source.fromInputStream(System.in)\n processFromSource(src)\n }\n\n def processFromSource(src: Source): Unit = {\n try {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out));\n try {\n val lines = src.getLines()\n processLines(lines, bw)\n } finally {\n bw.flush()\n }\n } finally {\n src.close();\n }\n }\n\n // Standard code above, custom code below\n\n case class Point(val x: Int, val y: Int)\n\n def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {\n val line = lines.next()\n val strings = line.split(' ')\n val n = strings(0).toInt\n val m = strings(1).toInt\n val k = strings(2).toInt\n val signals = Array.ofDim[Point](k)\n for (i <- 0 until k) {\n val row = lines.next()\n val coords = row.split(' ').map(_.toInt)\n signals(i) = Point(coords(0), coords(1))\n }\n\n val firstTimeEachSignalIsHit = solve(n, m, k, signals)\n firstTimeEachSignalIsHit.map {\n case Some(tme) => tme.toString\n case _ => \"-1\"\n }.foreach { str =>\n bw.write(str)\n bw.newLine()\n }\n }\n\n sealed trait Direction { def inverse: Direction }\n final object NorthWest extends Direction { override val inverse = SouthEast }\n final object SouthWest extends Direction { override val inverse = NorthEast }\n final object NorthEast extends Direction { override val inverse = SouthWest }\n final object SouthEast extends Direction { override val inverse = NorthWest }\n\n class Border[T:ClassTag](val rowCount: Int, val columnCount: Int, initialValue: T)\n {\n val pointCount = 2 * (rowCount + columnCount)\n private val points: Array[T] = Array.fill[T](pointCount)(initialValue)\n def get(edgePoint: Point): T = points(pointToIndex(edgePoint))\n def set(edgePoint: Point, value: T): Unit = { points(pointToIndex(edgePoint)) = value }\n def pointToIndex(edgePoint: Point): Int = edgePoint match {\n case Point(x, 0) => x\n case Point(x, y) if x == columnCount => columnCount + y\n case Point(x, y) if y == rowCount => rowCount + 2 * columnCount - x\n case Point(0, y) => 2 * (rowCount + columnCount) - y\n case _ => throw new IllegalArgumentException(s\"Point (${edgePoint.x}, ${edgePoint.y}) is not a border point\")\n }\n def isCornerPoint(point: Point): Boolean = point match {\n case Point(0, 0) => true\n case Point(0, y) if y == rowCount => true\n case Point(x, 0) if x == columnCount => true\n case Point(x, y) if x == columnCount && y == rowCount => true\n case _ => false\n }\n }\n case class Arrow(position: Point, direction: Direction, timeSteps: Long) {\n def +(other: Arrow): Arrow = Arrow(other.position, other.direction, this.timeSteps + other.timeSteps)\n }\n case class SignalFromEdge(index: Int, arrowToSignal: Arrow)\n\n def solve(n: Int, m: Int, k: Int, signals: Array[Point]): Array[Option[Long]] = {\n // Take a starting point and direction, and project to an edge of the n x m box.\n // Return a new arrow with its start point as the end point of the last arrow,\n // its direction the reflection of the previous arrow, and with timeSteps\n // based on how long previous arrow travelled for to reach the start of this arrow:\n def projectToBorder(startArrow: Arrow): Arrow = startArrow match {\n case Arrow(Point(x, y), NorthEast, _) if m - y <= n - x => Arrow(Point(x + m - y, m), SouthEast, m-y)\n case Arrow(Point(x, y), NorthEast, _) => Arrow(Point(n, y + n - x), NorthWest, n - x)\n case Arrow(Point(x, y), NorthWest, _) if x + y <= m => Arrow(Point(0, y + x), NorthEast, x)\n case Arrow(Point(x, y), NorthWest, _) => Arrow(Point(x + y - m, m), SouthWest, m - y)\n case Arrow(Point(x, y), SouthEast, _) if x + y <= n => Arrow(Point(x + y, 0), NorthEast, y)\n case Arrow(Point(x, y), SouthEast, _) => Arrow(Point(n, x + y - n), SouthWest, n - x)\n case Arrow(Point(x, y), SouthWest, _) if y <= x => Arrow(Point(x - y, 0), NorthWest, y)\n case Arrow(Point(x, y), SouthWest, _) => Arrow(Point(0, y - x), SouthEast, x)\n }\n\n val signalTimes = Array.fill[Option[Long]](k)(None)\n val diagonals = new Border[List[SignalFromEdge]](m, n, List.empty[SignalFromEdge])\n\n // Add signals along each diagonal by point on the border:\n val signalsFromEdges = for {\n i <- 0 until k\n dir <- List(NorthEast, NorthWest, SouthEast, SouthWest)\n } yield SignalFromEdge(i, projectToBorder(Arrow(signals(i), dir, 0)).copy(direction = dir.inverse))\n\n for (sig <- signalsFromEdges) {\n val pos = sig.arrowToSignal.position\n diagonals.set(pos, sig :: diagonals.get(pos))\n }\n\n @tailrec\n def projectRay(acc: Arrow): Unit = {\n // Update distances to signals along the current diagonal:\n val signalsOnDiagonal = diagonals.get(acc.position).filter(_.arrowToSignal.direction == acc.direction)\n for (sig <- signalsOnDiagonal) {\n if (signalTimes(sig.index) == None) {\n val timeToSignal = (acc + sig.arrowToSignal).timeSteps\n signalTimes(sig.index) = Some(timeToSignal)\n }\n }\n // Determine new position:\n val newAcc = acc + projectToBorder(acc)\n if (!diagonals.isCornerPoint(newAcc.position)) projectRay(newAcc)\n }\n\n projectRay(Arrow(Point(0, 0), NorthEast, 0))\n signalTimes\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport scala.io.Source\nimport scala.annotation.tailrec\nimport scala.reflect.ClassTag\n\nobject ProblemC2 {\n def main(args: Array[String]): Unit = processStdInOut()\n\n def processStdInOut(): Unit = {\n val src = Source.fromInputStream(System.in)\n processFromSource(src)\n }\n\n def processFromSource(src: Source): Unit = {\n try {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out));\n try {\n val lines = src.getLines()\n processLines(lines, bw)\n } finally {\n bw.flush()\n }\n } finally {\n src.close();\n }\n }\n\n // Standard code above, custom code below\n\n case class Point(val x: Int, val y: Int)\n\n def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {\n val line = lines.next()\n val strings = line.split(' ')\n val n = strings(0).toInt\n val m = strings(1).toInt\n val k = strings(2).toInt\n val signals = Array.ofDim[Point](k)\n for (i <- 0 until k) {\n val row = lines.next()\n val coords = row.split(' ').map(_.toInt)\n signals(i) = Point(coords(0), coords(1))\n }\n\n val firstTimeEachSignalIsHit = solve(n, m, k, signals)\n firstTimeEachSignalIsHit.map {\n case Some(tme) => tme.toString\n case _ => \"-1\"\n }.foreach { str =>\n bw.write(str)\n bw.newLine()\n }\n }\n\n sealed trait Direction { def inverse: Direction }\n final object NorthWest extends Direction { override val inverse = SouthEast }\n final object SouthWest extends Direction { override val inverse = NorthEast }\n final object NorthEast extends Direction { override val inverse = SouthWest }\n final object SouthEast extends Direction { override val inverse = NorthWest }\n\n class Border[T:ClassTag](val rowCount: Int, val columnCount: Int, initialValue: T)\n {\n val pointCount = 2 * (rowCount + columnCount)\n private val points: Array[T] = Array.fill[T](pointCount)(initialValue)\n def get(edgePoint: Point): T = points(pointToIndex(edgePoint))\n def set(edgePoint: Point, value: T): Unit = { points(pointToIndex(edgePoint)) = value }\n def pointToIndex(edgePoint: Point): Int = edgePoint match {\n case Point(x, 0) => x\n case Point(x, y) if x == columnCount => columnCount + y\n case Point(x, y) if y == rowCount => rowCount + 2 * columnCount - x\n case Point(0, y) => 2 * (rowCount + columnCount) - y\n case _ => throw new IllegalArgumentException(s\"Point (${edgePoint.x}, ${edgePoint.y}) is not a border point\")\n }\n def isCornerPoint(point: Point): Boolean = point match {\n case Point(0, 0) => true\n case Point(0, y) if y == rowCount => true\n case Point(x, 0) if x == columnCount => true\n case Point(x, y) if x == columnCount && y == rowCount => true\n case _ => false\n }\n }\n case class Arrow(val position: Point, val direction: Direction, val timeSteps: Long) {\n def +(other: Arrow): Arrow = Arrow(other.position, other.direction, this.timeSteps + other.timeSteps)\n }\n case class SignalFromEdge(val index: Int, arrowToSignal: Arrow)\n\n def solve(n: Int, m: Int, k: Int, signals: Array[Point]): Array[Option[Long]] = {\n // Take a starting point and direction, and project to an edge of the n x m box.\n // Return a new arrow with its start point as the end point of the last arrow,\n // its direction the reflection of the previous arrow, and with timeSteps\n // based on how long previous arrow travelled for to reach the start of this arrow:\n def projectToBorder(startArrow: Arrow): Arrow = startArrow match {\n case Arrow(Point(x, y), NorthEast, _) if m - y <= n - x => Arrow(Point(x + m - y, m), SouthEast, m-y)\n case Arrow(Point(x, y), NorthEast, _) => Arrow(Point(n, y + n - x), NorthWest, n - x)\n case Arrow(Point(x, y), NorthWest, _) if x + y <= m => Arrow(Point(0, y + x), NorthEast, x)\n case Arrow(Point(x, y), NorthWest, _) => Arrow(Point(x + y - m, m), SouthWest, m - y)\n case Arrow(Point(x, y), SouthEast, _) if x + y <= n => Arrow(Point(x + y, 0), NorthEast, y)\n case Arrow(Point(x, y), SouthEast, _) => Arrow(Point(n, x + y - n), SouthWest, n - x)\n case Arrow(Point(x, y), SouthWest, _) if y <= x => Arrow(Point(x - y, 0), NorthWest, y)\n case Arrow(Point(x, y), SouthWest, _) => Arrow(Point(0, y - x), SouthEast, x)\n }\n\n val signalTimes = Array.fill[Option[Long]](k)(None)\n val diagonals = new Border[List[SignalFromEdge]](m, n, List.empty[SignalFromEdge])\n\n // Add signals along each diagonal by point on the border:\n val signalsFromEdges = for {\n i <- 0 until k\n dir <- List(NorthEast, NorthWest, SouthEast, SouthWest)\n } yield SignalFromEdge(i, projectToBorder(Arrow(signals(i), dir, 0)).copy(direction = dir.inverse))\n\n for (sig <- signalsFromEdges) {\n val pos = sig.arrowToSignal.position\n diagonals.set(pos, sig :: diagonals.get(pos))\n }\n\n @tailrec\n def projectRay(acc: Arrow): Unit = {\n // Update distances to signals along the current diagonal:\n val signalsOnDiagonal = diagonals.get(acc.position).filter(_.arrowToSignal.direction == acc.direction)\n for (sig <- signalsOnDiagonal) {\n if (signalTimes(sig.index) == None) {\n val timeToSignal = (acc + sig.arrowToSignal).timeSteps\n signalTimes(sig.index) = Some(timeToSignal)\n }\n }\n // Determine new position:\n val newAcc = acc + projectToBorder(acc)\n if (!diagonals.isCornerPoint(newAcc.position)) projectRay(newAcc)\n }\n\n projectRay(Arrow(Point(0, 0), NorthEast, 0))\n signalTimes\n }\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport scala.io.Source\nimport scala.annotation.tailrec\nimport scala.reflect.ClassTag\n\nobject ProblemC2 {\n def main(args: Array[String]): Unit = processStdInOut()\n\n def processStdInOut(): Unit = {\n val src = Source.fromInputStream(System.in)\n processFromSource(src)\n }\n\n def processFromSource(src: Source): Unit = {\n try {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out));\n try {\n val lines = src.getLines()\n processLines(lines, bw)\n } finally {\n bw.flush()\n }\n } finally {\n src.close();\n }\n }\n\n // Standard code above, custom code below\n\n case class Point(val x: Int, val y: Int)\n\n def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {\n val line = lines.next()\n val strings = line.split(' ')\n val n = strings(0).toInt\n val m = strings(1).toInt\n val k = strings(2).toInt\n val signals = Array.ofDim[Point](k)\n for (i <- 0 until k) {\n val row = lines.next()\n val coords = row.split(' ').map(_.toInt)\n signals(i) = Point(coords(0), coords(1))\n }\n\n val firstTimeEachSignalIsHit = solve(n, m, k, signals)\n firstTimeEachSignalIsHit.map {\n case Some(tme) => tme.toString\n case _ => \"-1\"\n }.foreach { str =>\n bw.write(str)\n bw.newLine()\n }\n }\n\n sealed trait Direction { def inverse: Direction }\n final object NorthWest extends Direction { override val inverse = SouthEast }\n final object SouthWest extends Direction { override val inverse = NorthEast }\n final object NorthEast extends Direction { override val inverse = SouthWest }\n final object SouthEast extends Direction { override val inverse = NorthWest }\n\n class Border[T:ClassTag](val rowCount: Int, val columnCount: Int, initialValue: T)\n {\n val pointCount = 2 * (rowCount + columnCount)\n private val points: Array[T] = Array.fill[T](pointCount)(initialValue)\n def get(edgePoint: Point): T = points(pointToIndex(edgePoint))\n def set(edgePoint: Point, value: T): Unit = { points(pointToIndex(edgePoint)) = value }\n def pointToIndex(edgePoint: Point): Int = edgePoint match {\n case Point(x, 0) => x\n case Point(x, y) if x == columnCount => rowCount + y\n case Point(x, y) if y == rowCount => 2 * rowCount + columnCount - x\n case Point(0, y) => 2 * (rowCount + columnCount) - y\n case _ => throw new IllegalArgumentException(s\"Point (${edgePoint.x}, ${edgePoint.y}) is not a border point\")\n }\n def isCornerPoint(point: Point): Boolean = point match {\n case Point(0, 0) => true\n case Point(0, y) if y == rowCount => true\n case Point(x, 0) if x == columnCount => true\n case Point(x, y) if x == columnCount && y == rowCount => true\n case _ => false\n }\n }\n case class Arrow(val position: Point, val direction: Direction, val timeSteps: Long) {\n def +(other: Arrow): Arrow = Arrow(other.position, other.direction, this.timeSteps + other.timeSteps)\n }\n case class SignalFromEdge(val index: Int, arrowToSignal: Arrow)\n\n def solve(n: Int, m: Int, k: Int, signals: Array[Point]): Array[Option[Long]] = {\n // Take a starting point and direction, and project to an edge of the n x m box.\n // Return a new arrow with its start point as the end point of the last arrow,\n // its direction the reflection of the previous arrow, and with timeSteps\n // based on how long previous arrow travelled for to reach the start of this arrow:\n def projectToBorder(startArrow: Arrow): Arrow = startArrow match {\n case Arrow(Point(x, y), NorthEast, _) if y >= x => Arrow(Point(x + m - y, m), SouthEast, m-y)\n case Arrow(Point(x, y), NorthEast, _) => Arrow(Point(n, y + n - x), NorthWest, n - x)\n case Arrow(Point(x, y), NorthWest, _) if x + y <= m => Arrow(Point(0, y + x), NorthEast, x)\n case Arrow(Point(x, y), NorthWest, _) => Arrow(Point(x + y - m, m), SouthWest, m - y)\n case Arrow(Point(x, y), SouthEast, _) if x + y <= n => Arrow(Point(x + y, 0), NorthEast, y)\n case Arrow(Point(x, y), SouthEast, _) => Arrow(Point(n, x + y - n), SouthWest, n - x)\n case Arrow(Point(x, y), SouthWest, _) if y <= x => Arrow(Point(x - y, 0), NorthWest, y)\n case Arrow(Point(x, y), SouthWest, _) => Arrow(Point(0, y - x), SouthEast, x)\n }\n\n val signalTimes = Array.fill[Option[Long]](k)(None)\n val diagonals = new Border[List[SignalFromEdge]](m, n, List.empty[SignalFromEdge])\n\n // Add signals along each diagonal by point on the border:\n val signalsFromEdges = for {\n i <- 0 until k\n dir <- List(NorthEast, NorthWest, SouthEast, SouthWest)\n } yield SignalFromEdge(i, projectToBorder(Arrow(signals(i), dir, 0)).copy(direction = dir.inverse))\n\n for (sig <- signalsFromEdges) {\n val pos = sig.arrowToSignal.position\n diagonals.set(pos, sig :: diagonals.get(pos))\n }\n\n @tailrec\n def projectRay(acc: Arrow): Unit = {\n // Update distances to signals along the current diagonal:\n val signalsOnDiagonal = diagonals.get(acc.position).filter(_.arrowToSignal.direction == acc.direction)\n for (sig <- signalsOnDiagonal) {\n if (signalTimes(sig.index) == None) {\n val timeToSignal = (acc + sig.arrowToSignal).timeSteps\n signalTimes(sig.index) = Some(timeToSignal)\n }\n }\n // Determine new position:\n val newAcc = acc + projectToBorder(acc)\n if (!diagonals.isCornerPoint(newAcc.position)) projectRay(newAcc)\n }\n\n projectRay(Arrow(Point(0, 0), NorthEast, 0))\n signalTimes\n }\n}\n"}], "src_uid": "27a521d4d59066e50e870e7934d4b190"} {"source_code": "object CF501C extends App {\n import scala.io.StdIn\n\n val Array(n, m) = StdIn.readLine.split(' ').map(_.toInt)// number of songs\n\n val input = (0 until n).map(_ => StdIn.readLine.split(' ').map(_.toLong)).toArray.transpose\n\n val as = input(0) // original sizes\n val bs = input(1) // compressed sizes\n\n val originalSum = as.sum\n val compressedSum = bs.sum\n\n if (compressedSum > m) {\n println(\"-1\")\n } else {\n val diff = as.zip(bs).map(x => x._1 - x._2).sorted.reverse\n val overflow = originalSum - m\n var sumDiff: Long = 0\n println(diff.takeWhile(x => {\n val b = sumDiff < overflow\n sumDiff += x\n b\n }).length)\n }\n}", "positive_code": [{"source_code": "object CF501C extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n val n = in.nextInt() // number of songs\n val m = in.nextInt() // capacity\n\n val input = (0 until n).map(_ => Array(in.nextLong(), in.nextLong())).toArray.transpose\n\n val as = input(0) // original sizes\n val bs = input(1) // compressed sizes\n\n val originalSum = as.sum\n val compressedSum = bs.sum\n\n if (compressedSum > m) {\n out.println(\"-1\")\n } else {\n val diff = as.zip(bs).map(x => x._1 - x._2).sorted.reverse\n val overflow = originalSum - m\n var sumDiff: Long = 0\n out.println(diff.takeWhile(x => {\n val b = sumDiff < overflow\n sumDiff += x\n b\n }).length)\n }\n }\n\n solve\n out.flush\n out.close\n}\n\n// https://codeforces.com/blog/entry/21074\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\nclass Scanner2(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}"}, {"source_code": "object CF501C extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner2(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n val n = in.nextInt() // number of songs\n val m = in.nextInt() // capacity\n\n val input = (0 until n).map(_ => Array(in.nextLong(), in.nextLong())).toArray.transpose\n\n val as = input(0) // original sizes\n val bs = input(1) // compressed sizes\n\n val originalSum = as.sum\n val compressedSum = bs.sum\n\n if (compressedSum > m) {\n out.println(\"-1\")\n } else {\n val diff = as.zip(bs).map(x => x._1 - x._2).sorted.reverse\n val overflow = originalSum - m\n var sumDiff: Long = 0\n out.println(diff.takeWhile(x => {\n val b = sumDiff < overflow\n sumDiff += x\n b\n }).length)\n }\n }\n\n solve\n out.flush\n out.close\n}\n\n// https://codeforces.com/blog/entry/21074\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\nclass Scanner2(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}"}, {"source_code": "object Main {\n import java.io._\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N, M = sc.nextInt()\n val files = Array.ofDim[(Long, Long)](N)\n rep(N) { i =>\n val a, b = sc.nextLong()\n files(i) = (a, b)\n }\n\n var SUM = files.sumBy(_._1)\n Sorting.quickSort(files)(Ordering.by[(Long, Long), Long](x => x._2 - x._1))\n var i = 0\n while(SUM > M && i < N) {\n val (a, b) = files(i)\n SUM -= a - b\n i += 1\n }\n\n if (SUM > M) out.println(-1)\n else out.println(i)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n\n import java.util.StringTokenizer\n\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}], "negative_code": [{"source_code": "object CF501C extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n val n = in.nextInt // number of songs\n val m = in.nextInt // capacity\n\n val input = (0 until n).map(_ => Array(in.nextLong, in.nextLong)).toArray.transpose\n val as = input(0) // original sizes\n val bs = input(1) // compressed sizes\n\n val originalSum = as.sum\n val compressedSum = bs.sum\n\n if (compressedSum > m) {\n out.println(\"-1\")\n } else {\n val diff = as.zip(bs).map(x => x._1 - x._2).sorted.reverse\n val overflow = originalSum - m\n var sumDiff: Long = 0\n out.println(diff.takeWhile(x => {\n sumDiff += x\n\n sumDiff < overflow\n }).length)\n }\n }\n\n solve\n out.flush\n out.close\n}"}, {"source_code": "object CF501C extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n val n = in.nextInt // number of songs\n val m = in.nextInt // capacity\n\n val input = (0 until n).map(_ => Array(in.nextLong, in.nextLong)).toArray.transpose\n val as = input(0) // original sizes\n val bs = input(1) // compressed sizes\n\n val originalSum = as.sum\n val compressedSum = bs.sum\n\n if (compressedSum > m) {\n out.println(\"-1\")\n } else {\n val diff = as.zip(bs).map(x => x._1 - x._2).sorted\n val overflow = originalSum - m\n var sumDiff: Long = 0\n out.println(diff.takeWhile(x => {\n sumDiff += x\n\n sumDiff < overflow\n }).length)\n }\n }\n\n solve\n out.flush\n out.close\n}"}], "src_uid": "91541d10c5ae52be8da33412359bd019"} {"source_code": " import scala.io.StdIn\r\n \r\n object HelloWorld extends App {\r\n var t = StdIn.readInt();\r\n val range = 1 to t\r\n for (num <- range){\r\n var ip = StdIn.readLine().split(\" \");\r\n val a = ip(0).toLong;\r\n val b = ip(1).toLong;\r\n val c = ip(2).toLong;\r\n val x:Long = c*b+a\r\n println(s\"$x $b $c\")\r\n\r\n }\r\n }\r\n", "positive_code": [{"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\n\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val reader = new InputReader()\n val t = reader.nextInt()\n (1 to t).foreach { i =>\n val a = reader.nextInt()\n val b = reader.nextInt()\n val c = reader.nextInt()\n\n System.out.println((a + b + c) + \" \" + (b + c) + \" \" + c)\n }\n\n }\n\n class InputReader() {\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var line: Array[String] = null\n var cur: Int = 0\n\n def nextString(): String = {\n while (line == null || cur >= line.length) {\n cur = 0\n line = reader.readLine().split(\"\"\" \"\"\")\n }\n cur += 1\n line(cur - 1)\n }\n\n def nextInt(): Int = {\n nextString().toInt\n }\n\n def nextLong(): Int = {\n nextString().toInt\n }\n\n }\n\n}\n"}], "negative_code": [{"source_code": " import scala.io.StdIn\r\n object HelloWorld extends App {\r\n var t = StdIn.readInt();\r\n val range = 1 to t\r\n for (num <- range){\r\n var ip = StdIn.readLine().split(\" \");\r\n val a = ip(0).toInt;\r\n val b = ip(1).toInt;\r\n val c = ip(2).toInt;\r\n val x :Long = c*b+a;\r\n println(s\"${x} ${b} ${c}\")\r\n\r\n }\r\n }"}, {"source_code": " import scala.io.StdIn\r\n object HelloWorld extends App {\r\n var t = StdIn.readInt();\r\n val range = 1 to t\r\n for (num <- range){\r\n var ip = StdIn.readLine().split(\" \");\r\n val a = ip(0).toInt;\r\n val b = ip(1).toInt;\r\n val c = ip(2).toInt;\r\n println(s\"${c*b+a} ${b} ${c}\")\r\n\r\n }\r\n }"}], "src_uid": "f0c22161cb5a9bc17320ccd05517f867"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val nm = readLine().split(\" \").map(_.toInt)\n val n = nm(0)\n val m = nm(1)\n \n val a = (1 to m).map(_ => readLine().split(\" \").map(_.toInt))\n \n val s = Set() ++ (1 to n) -- a.flatten\n val u = s.toSeq.apply(0)\n \n println(n - 1)\n for (i <- 1 to n if i != u) println(i + \" \" + u) \n }\n}", "positive_code": [{"source_code": "\nimport scala.util.control.Breaks\n\nobject RoadConstruction {\n def main(args: Array[String]): Unit = {\n val in = scala.io.StdIn\n var arr = in.readLine().split(\" \").map(_.toInt)\n val n = arr(0)\n val m = arr(1)\n val forbiddenPathVertices=Array.fill[Boolean](n)(false)\n for(i<- 0 until m){\n arr = in.readLine().split(\" \").map(_.toInt-1)\n forbiddenPathVertices(arr(0))=true\n forbiddenPathVertices(arr(1))=true\n }\n var hubVertex= -1\n Breaks.breakable {\n for (i <- 0 until n) {\n if (!forbiddenPathVertices(i)) {\n hubVertex = i\n Breaks.break()\n }\n }\n }\n println(n-1)\n for (i <- 0 until n if(i!=hubVertex)) {\n println((i+1)+\" \"+(hubVertex+1))\n }\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val data = Range(0, m).flatMap{_ => \n in.next().split(\" \").map(_.toInt)\n }.toSet\n val el = Range(1, n + 1).find(x => !data.contains(x)).get\n println(n - 1)\n Range(1, n + 1).foreach { i =>\n if (i != el)\n println(s\"$i $el\")\n }\n}"}, {"source_code": "\nobject tmp extends App {\n\n import java.io._\n import java.util.StringTokenizer\n\n class MyScanner(br: BufferedReader) {\n var st = new StringTokenizer(\"\")\n\n def this(is: InputStream) = this(new BufferedReader(new InputStreamReader(is)))\n\n private def next() = {\n\n while (!st.hasMoreElements) {\n st = new StringTokenizer(br.readLine())\n }\n st.nextToken()\n }\n\n def nextInt() = java.lang.Integer.parseInt(next())\n\n def nextLong() = java.lang.Long.parseLong(next())\n\n def nextLine() = br.readLine()\n }\n\n val sc = new MyScanner(System.in)\n val n = sc.nextInt()\n val m = sc.nextInt()\n val vertices = Array.fill(n)(true)\n for (_ <- 0 until m) {\n vertices(sc.nextInt() - 1) = false\n vertices(sc.nextInt() - 1) = false\n }\n val center = vertices.zipWithIndex.find(x => x._1).get._2 + 1\n println(n - 1)\n for (i <- 1 to n) {\n if (i != center) {\n println(s\"$i $center\")\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P330B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = sc.nextInt\n out.println(N - 1)\n val E0 = List.fill(N)(new ListBuffer[Int])\n\n for (_ <- 0 until K) {\n val u, v = sc.nextInt - 1\n E0(u) += v\n E0(v) += u\n }\n\n var root = -1\n breakable {\n for (i <- 0 until N) {\n if (E0(i).isEmpty) {\n root = i\n break\n }\n }\n }\n\n 0 until N foreach { i =>\n if (i != root) {\n out.println(List(root, i).map(_ + 1).mkString(\" \"))\n }\n }\n }\n\n solve\n out.close\n}\n \n\n\n\n\n\n"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P330B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = sc.nextInt\n val E0 = Array.fill(N)(new ListBuffer[Int])\n\n for (_ <- 0 until K) {\n val u, v = sc.nextInt - 1\n E0(u) += v\n E0(v) += u\n }\n\n val E: Array[Set[Int]] = E0.map(_.toSet)\n\n val c0: Set[Int] = List.range(1, N).toSet -- E(0)\n c0.foreach { i =>\n out.println(List(1, i + 1).mkString(\" \"))\n }\n val c1: Set[Int] = E(0)\n c1 foreach { i =>\n c0.find { j =>\n ! E(i).contains(j)\n }.map { j =>\n val res = List(i, j).map(_ + 1).mkString(\" \")\n out.println(res)\n }\n }\n }\n\n solve\n out.close\n}\n \n\n\n\n\n\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P330B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = sc.nextInt - 1\n\n out.println(solve)\n out.close\n}\n \n\n\n\n\n\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P330B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = sc.nextInt\n out.println(N - 1)\n val E0 = Array.fill(N)(new ListBuffer[Int])\n\n for (_ <- 0 until K) {\n val u, v = sc.nextInt - 1\n E0(u) += v\n E0(v) += u\n }\n\n val E: Array[Set[Int]] = E0.map(_.toSet)\n\n val c0: Set[Int] = List.range(1, N).toSet -- E(0)\n c0.foreach { i =>\n out.println(List(1, i + 1).mkString(\" \"))\n }\n val c1: Set[Int] = E(0)\n c1 foreach { i =>\n c0.find { j =>\n ! E(i).contains(j)\n }.map { j =>\n val res = List(i, j).map(_ + 1).mkString(\" \")\n out.println(res)\n }\n }\n }\n\n solve\n out.close\n}\n \n\n\n\n\n\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val nm = readLine().split(\" \").map(_.toInt)\n val n = nm(0)\n val m = nm(1)\n \n val a = (1 to m).map(_ => readLine().split(\" \").map(_.toInt))\n \n val s = Set() ++ (1 to n) -- a.flatten\n val u = s.toSeq.apply(0)\n \n for (i <- 1 to n if i != u) println(i + \" \" + u) \n }\n}"}], "src_uid": "d93a0574497b60bb77fb1c1dfe95090f"} {"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val h = n / 2\n if (h % 2 == 1) {\n out.println(\"NO\")\n } else {\n val l = Array.tabulate(h)(i => 2 + 2 * i)\n val r = Array.tabulate(h - 1)(i => 1 + 2 * i)\n val res = l ++ r ++ Array(l.sum - r.sum)\n out.println(\"YES\")\n out.println(res.mkString(\" \"))\n }\n }\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject SolutionB extends App {\n val T = StdIn.readInt()\n for (t <- 1 to T) {\n val n = StdIn.readInt();\n val l = n / 2\n if (l % 2 == 1) {\n println(\"NO\")\n } else {\n println(\"YES\")\n val first = Array.ofDim[Int](l)\n for (idx <- 1 to l) {\n first(idx-1) = idx * 4\n }\n val second = Array.ofDim[Int](l)\n for (idx <- 1 to l) {\n second(idx-1) = if (idx % 2 == 0) {\n first(idx-1) + 1\n } else {\n first(idx-1) - 1\n }\n }\n print(first.mkString(\" \"))\n print(\" \")\n println(second.mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Main2 extends App {\n val testCaseNumber = readInt()\n 1.to(testCaseNumber).foreach{ _ =>\n val n = readInt()\n if (n/2 % 2 == 1) {\n println(\"NO\")\n } else {\n println(\"YES\")\n val (even, odd) = 1.to(n).partition(_ % 2 == 0)\n println((even ++ odd.take(n/2 - 1) :+ (odd.last + n/2)).mkString(\" \"))\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject SolutionB extends App {\n val T = StdIn.readInt()\n for (t <- 1 to T) {\n val n = StdIn.readInt();\n val l = n / 2\n if (l % 2 == 1) {\n println(\"NO\")\n } else {\n println(\"YES\")\n val first = Array.ofDim[Int](l)\n for (idx <- 1 to l) {\n first(idx-1) = idx * 4\n }\n val second = Array.ofDim[Int](l)\n for (idx <- 1 to l) {\n second(idx-1) = if (idx % 2 == 0) {\n first(idx-1) + 1\n } else {\n first(idx-1) - 1\n }\n }\n print(first.mkString(\" \"))\n print(\" \")\n print(second.mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Main2 extends App {\n val testCaseNumber = readInt()\n 1.to(testCaseNumber).foreach{ _ =>\n val n = readInt()\n if (n/2 % 2 == 1) {\n println(\"NO\")\n } else {\n println(\"YES\")\n val (even, odd) = 1.to(n).partition(_ % 2 == 0)\n println((even ++ odd).mkString(\" \"))\n }\n }\n}\n"}], "src_uid": "0c7e019e1e955cadacca55b4e823a3e5"} {"source_code": "import java.util.Scanner\n\nimport scala.io.StdIn\n\nobject Ctask557 extends App {\n\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n val k = line.nextInt()\n\n val x = StdIn.readLine().split(' ').map(_.toInt)\n var blocks = Array.fill(n){0}\n\n var result = 1 + (n - 1) * 3\n for (i <- 0 until k) {\n if (blocks(x(i) - 1) == 0) {\n blocks(x(i) - 1) += 1\n result -= 1\n }\n if (x(i)-2 >= 0 && blocks(x(i) - 2) >= 1 && (blocks(x(i) -1) == 1 || blocks(x(i) -1) == 11)) {\n result -= 1\n blocks(x(i) -1) += 1\n }\n if (x(i) < n && blocks(x(i)) >= 1 && (blocks(x(i) - 1) == 1 || blocks(x(i) - 1) == 2)) {\n result -= 1\n blocks(x(i) -1) += 10\n }\n }\n if (result < 0) {\n result = 0\n }\n println(result)\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, K = ni()\n val A = na(K)\n val C = Array.fill[java.util.TreeSet[Integer]](N + 1)(new java.util.TreeSet)\n REP(K) { i =>\n C(A(i)).add(i)\n }\n\n var ans = 0\n TO(1, N) { b =>\n val cnt = if (C(b).isEmpty) {\n var v = 1\n if (b < N) v += 1\n if (b > 1) v += 1\n v\n } else {\n val i = C(b).last\n var v = 0\n if (b < N && C(b + 1).lower(i) == null) v += 1\n if (b > 1 && C(b - 1).lower(i) == null) v += 1\n v\n }\n ans += cnt\n }\n out.println(ans)\n }\n}"}], "negative_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, K = ni()\n val A = na(K)\n val C = Array.fill[java.util.TreeSet[Integer]](N + 1)(new java.util.TreeSet)\n REP(K) { i =>\n C(A(i)).add(i)\n }\n\n var ans = 0\n TO(1, N) { b =>\n val cnt = if (C(b).isEmpty) {\n if (b == 1 || b == N) 2 else 3\n } else if (C(b).size == 1) {\n val i = C(b).first()\n var v = 0\n if (b < N && C(b + 1).lower(i) == null) v += 1\n if (b > 1 && C(b - 1).lower(i) == null) v += 1\n v\n } else {\n 0\n }\n ans += cnt\n }\n out.println(ans)\n }\n}"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, K = ni()\n val A = na(K)\n val C = Array.fill[java.util.TreeSet[Integer]](N + 1)(new java.util.TreeSet)\n REP(K) { i =>\n C(A(i)).add(i)\n }\n\n var ans = 0\n TO(1, N) { b =>\n val cnt = if (C(b).isEmpty) {\n var v = 1\n if (b < N) v += 1\n if (b > 1) v += 1\n v\n } else if (C(b).size == 1) {\n val i = C(b).first()\n var v = 0\n if (b < N && C(b + 1).lower(i) == null) v += 1\n if (b > 1 && C(b - 1).lower(i) == null) v += 1\n v\n } else {\n 0\n }\n ans += cnt\n }\n out.println(ans)\n }\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.io.StdIn\n\nobject Ctask557 extends App {\n\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n val k = line.nextInt()\n\n val x = StdIn.readLine().split(' ').map(_.toInt)\n var blocks = Array.fill(n){0}\n\n var result = 1 + (n - 1) * 3\n for (i <- 0 until k) {\n blocks(x(i)-1) += 1\n if (blocks(x(i) - 1) == 1) {\n result -= 1\n }\n if (x(i)-2 >= 0 && blocks(x(i) - 2) >= 1 && (blocks(x(i) -1) == 1 || blocks(x(i) -1) == 11)) {\n result -= 1\n blocks(x(i) -1) += 1\n }\n if (x(i) < n && blocks(x(i)) >= 1 && blocks(x(i) - 1) != 11 && blocks(x(i) - 1) != 12) {\n result -= 1\n blocks(x(i) -1) += 10\n }\n }\n if (result < 0) {\n result = 0\n }\n println(result)\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.io.StdIn\n\nobject Ctask557 extends App {\n\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n val k = line.nextInt()\n\n val x = StdIn.readLine().split(' ').map(_.toInt)\n var blocks = Array.fill(n){0}\n\n var result = 1 + (n - 1) * 3\n for (i <- 0 until k) {\n blocks(x(i)-1) += 1\n if (blocks(x(i) - 1) == 1) {\n result -= 1\n }\n if (x(i)-2 >= 0 && blocks(x(i) - 2) >= 1 && (blocks(x(i) -1) != 2 || blocks(x(i) -1) == 11)) {\n result -= 1\n blocks(x(i) -1) += 1\n }\n if (x(i) < n && blocks(x(i)) >= 1 && blocks(x(i) - 1) != 11 && blocks(x(i) - 1) != 12) {\n result -= 1\n blocks(x(i) -1) += 10\n }\n }\n if (result < 0) {\n result = 0\n }\n println(result)\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.io.StdIn\n\nobject Ctask557 extends App {\n\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n val k = line.nextInt()\n\n val x = StdIn.readLine().split(' ').map(_.toInt)\n var blocks = Array.fill(n){0}\n\n var result = 1 + (n - 1) * 3\n for (i <- 0 until k) {\n if (blocks(x(i) - 1) == 0) {\n blocks(x(i) - 1) += 1\n }\n if (blocks(x(i) - 1) == 1) {\n result -= 1\n }\n if (x(i)-2 >= 0 && blocks(x(i) - 2) >= 1 && (blocks(x(i) -1) == 1 || blocks(x(i) -1) == 11)) {\n result -= 1\n blocks(x(i) -1) += 1\n }\n if (x(i) < n && blocks(x(i)) >= 1 && (blocks(x(i) - 1) == 1 || blocks(x(i) - 1) == 2)) {\n result -= 1\n blocks(x(i) -1) += 10\n }\n }\n if (result < 0) {\n result = 0\n }\n println(result)\n}\n"}], "src_uid": "cabb7edf51f32c94415d580b96eef7b7"} {"source_code": "import scala.io.StdIn\n\nobject WorldCup {\n\n def main(args: Array[String]): Unit = {\n StdIn.readLine()\n val as: Seq[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n println(solve(as))\n }\n \n private def solve(as: Seq[Int]): Int = {\n as.zipWithIndex.map(tupel => {\n val value = tupel._1\n val index = tupel._2\n val round = Math.ceil((value - index) / as.length.toDouble).toInt + 1\n (round * as.length + index, index)\n }).minBy(tupel => tupel._1)._2 + 1\n }\n\n private def absMod(p: Int, q: Int): Int = {\n val r = p % q\n if (r < 0) r + q\n else r\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject B {\n\n def main(args: Array[String]): Unit = {\n val entrances = StdIn.readInt()\n val people = StdIn.readLine().split(\" \").map(_.toInt)\n\n var index = 0\n\n val counts = people.map {count =>\n val i = count - index\n val a = i / entrances\n val r = i % entrances\n\n index += 1\n if (r > 0) a+1 else a\n }\n\n\n val min = counts.min\n val result = counts.indexOf(min) + 1\n\n println(result)\n } \n\n}\n"}, {"source_code": "object Main{\n def main(args: Array[String]) {\n val n = readInt\n val a: Array[Int] = readLine.split(\" \").map(_.toInt)\n val min = a.min\n val p = min % n\n for(i <- 0 to (n - 1)){\n if(a((p + i) % n) - min <= i){\n println(((p + i) % n) + 1)\n return\n }\n }\n }\n}"}, {"source_code": "import scala.io.StdIn._\nimport scala.math._\nobject Task2 extends App {\n def calc(x: Long, y: Long) = x + y.toDouble / pow(10, y.toString.length)\n val n = readLong;\n val qs = readLine.split(' ').map(_.toLong)\n qs.zipWithIndex\n .map { case (q, i) => (ceil((q-i).toDouble / n), i + 1) }\n .minBy(_._1) match { case (_, i) => println (i) }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject Task2 extends App {\n val n = readInt\n val qs = readLine.split(' ').map(_.toInt)\n Iterator.continually(qs)\n .flatten.zipWithIndex\n .map { case (q, i) => (q - i, i + 1) }.find(_._1 <= 0) match {\n case Some((_, i)) => println(i % n)\n case None => println(-1)\n }\n}\n"}], "src_uid": "b18bbefd2a948da9dec1d6f27f219ed1"} {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val t = StdIn.readInt\n for (_ <- 1 to t) {\n val x = StdIn.readLine().split(' ').map(_.toInt)\n solve(x(0), x(1))\n }\n }\n\n def solve(l: Int, r: Int): Unit = {\n println(s\"${l} ${l * 2}\")\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject kimollg extends App {\n //println(\"Zdorova!\")\n val n = scala.io.StdIn.readInt()\n for (i <- 0 until n){\n val inps = StdIn.readLine().split(\" \").map(_.toInt)\n println(inps(0)+\" \"+inps(0)*2)\n }\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val L, R = ni()\n val l = L\n val r = l * 2\n out.println(s\"$l $r\")\n }\n\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n\n def debug(as: Array[Int], delimiter: String = \" \"): Unit = {\n debug(as.mkString(delimiter))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject FindDivisible extends App {\n val t = StdIn.readLine().toInt\n\n for (_ <- 1 to t) {\n val lr = StdIn.readLine().split(\" \").map(_.toInt)\n\n println(s\"${lr(0)} ${lr(0) * 2}\")\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val L, R = ni()\n if (abs(L - R) <= 1) out.println(s\"$L $R\")\n else {\n val l = ((L - 1) / 2 + 1) * 2\n val r = R / 2 * 2\n if (l >= r) {\n out.println(s\"$L $R\")\n } else {\n out.println(s\"$l $r\")\n }\n }\n }\n\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n\n def debug(as: Array[Int], delimiter: String = \" \"): Unit = {\n debug(as.mkString(delimiter))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n}"}], "src_uid": "a9cd97046e27d799c894d8514e90a377"} {"source_code": "import java.io._\n\nobject Main {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n val LOGN = 18\n\n trait GraphLike {\n def n: Int\n\n def adj: Array[List[Int]]\n }\n\n class UndirectedGraph(val n: Int) extends GraphLike {\n\n val adj = Array.fill(n)(List[Int]())\n\n def apply(i: Int) = adj(i)\n\n def addEdge(u: Int, v: Int): Unit = {\n adj(u) = v :: adj(u)\n adj(v) = u :: adj(v)\n }\n\n }\n\n trait TreeFeatures {\n this: GraphLike =>\n\n val parent = new Array[Int](n)\n val depth = new Array[Int](n)\n val subtreeSize = new Array[Int](n)\n val dp = Array.ofDim[Int](n, LOGN)\n\n private def computeLCA(): Unit = {\n (0 until n).foreach { i =>\n dp(i)(0) = parent(i)\n var j = 1\n while ((1 << j) < n) {\n dp(i)(j) = -1\n j += 1\n }\n }\n\n var j = 1\n while ((1 << j) < n) {\n (0 until n).foreach { i =>\n if (dp(i)(j - 1) != -1)\n dp(i)(j) = dp(dp(i)(j - 1))(j - 1)\n }\n j += 1\n }\n }\n\n def computeFeatures(root: Int) = {\n\n def dfs(u: Int, pu: Int): Unit = {\n subtreeSize(u) = 1\n adj(u).foreach { v =>\n if (v != pu) {\n parent(v) = u\n depth(v) = depth(u) + 1\n dfs(v, u)\n subtreeSize(u) += subtreeSize(v)\n }\n }\n }\n\n parent(root) = -1\n dfs(root, -1)\n\n computeLCA()\n }\n\n def ancestor(u: Int, d: Int) = {\n var x = u\n var rd = d\n var i = LOGN\n while (i >= 0) {\n if (rd - (1 << i) >= 0 && dp(x)(i) != -1) {\n rd -= (1 << i)\n x = dp(x)(i)\n }\n i -= 1\n }\n x\n }\n\n def lca(pp: Int, qq: Int) = {\n var tmp, log, i = 0\n var p = pp\n var q = qq\n\n if (depth(p) < depth(q)) {\n tmp = p\n p = q\n q = tmp\n }\n\n log = 1\n while ((1 << log) <= depth(p)) log += 1\n log -= 1\n\n i = log\n while (i >= 0) {\n if (depth(p) - (1 << i) >= depth(q)) p = dp(p)(i)\n i -= 1\n }\n\n if (p == q) {\n p\n } else {\n i = log\n while (i >= 0) {\n if (dp(p)(i) != -1 && dp(p)(i) != dp(q)(i)) {\n p = dp(p)(i)\n q = dp(q)(i)\n }\n i -= 1\n }\n parent(p)\n }\n }\n\n }\n\n def main(args: Array[String]) {\n\n val n = in.readLine().toInt\n\n val t = new UndirectedGraph(n) with TreeFeatures\n\n (1 until n).foreach { i =>\n val Array(u, v) = in.readLine().split(\" +\").map(_.toInt)\n t.addEdge(u - 1, v - 1)\n }\n\n t.computeFeatures(0)\n\n val m = in.readLine().toInt\n\n (1 to m).foreach { _ =>\n val Array(uu, vv) = in.readLine().split(\" +\").map(_.toInt)\n\n val u = uu - 1\n val v = vv - 1\n\n if (u == v) {\n out.println(n)\n } else {\n\n val w = t.lca(u, v)\n val d = t.depth(u) + t.depth(v) - 2 * t.depth(w)\n\n if (d % 2 == 1) {\n out.println(0)\n } else {\n\n if (t.depth(u) == t.depth(v)) {\n val x = t.ancestor(u, d / 2 - 1)\n val y = t.ancestor(v, d / 2 - 1)\n out.println(n - t.subtreeSize(x) - t.subtreeSize(y))\n } else {\n val (_, yTmp) = if (t.depth(u) > t.depth(v)) (v, u) else (u, v)\n val y = t.ancestor(yTmp, d / 2 - 1)\n out.println(t.subtreeSize(t.parent(y)) - t.subtreeSize(y))\n }\n\n }\n }\n }\n\n out.close()\n }\n\n}", "positive_code": [{"source_code": "import java.io._\n\nimport scala.annotation.tailrec\n\nobject Main {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n object TraverseUtil {\n\n def FOR(from: Int, to: Int)(f: Int => Unit): Unit = {\n var i = from\n while (i <= to) {\n f(i)\n i += 1\n }\n }\n\n }\n\n import TraverseUtil._\n\n class UndirectedGraph(val n: Int) {\n\n val adj = Array.fill(n)(List[Int]())\n\n def apply(i: Int) = adj(i)\n\n def addEdge(u: Int, v: Int): Unit = {\n adj(u) = v :: adj(u)\n adj(v) = u :: adj(v)\n }\n\n }\n\n trait TreeFeatures {\n this: UndirectedGraph =>\n\n val lgn = (1 to 32).find(x => (1 << x) >= n).get\n val parent = new Array[Int](n)\n val depth = new Array[Int](n)\n val subtreeSize = new Array[Int](n)\n val dp = Array.ofDim[Int](lgn, n)\n\n private def computeLCA(): Unit = {\n\n FOR(0, n - 1) { i =>\n dp(0)(i) = parent(i)\n var j = 1\n while ((1 << j) < n) {\n dp(j)(i) = -1\n j += 1\n }\n }\n\n var j = 1\n while ((1 << j) < n) {\n FOR(0, n - 1) { i =>\n if (dp(j - 1)(i) != -1)\n dp(j)(i) = dp(j - 1)(dp(j - 1)(i))\n }\n j += 1\n }\n }\n\n def computeFeatures(root: Int) = {\n\n def dfs(u: Int, pu: Int): Unit = {\n subtreeSize(u) = 1\n adj(u).foreach { v =>\n if (v != pu) {\n parent(v) = u\n depth(v) = depth(u) + 1\n dfs(v, u)\n subtreeSize(u) += subtreeSize(v)\n }\n }\n }\n\n parent(root) = -1\n dfs(root, -1)\n\n computeLCA()\n }\n\n def ancestor(u: Int, count: Int) = (0 until lgn).foldLeft(u) {\n (v, i) => if (((count >> i) & 1) == 1) dp(i)(v) else v\n }\n\n @tailrec final def lca(u: Int, v: Int): Int = {\n if (depth(u) > depth(v)) lca(ancestor(u, depth(u) - depth(v)), v)\n else if (depth(u) < depth(v)) lca(u, ancestor(v, depth(v) - depth(u)))\n else if (u == v) u\n else parent(((lgn - 1) to 0 by -1).foldLeft((u, v)) {\n (t, i) => if (dp(i)(t._1) != dp(i)(t._2)) (dp(i)(t._1), dp(i)(t._2)) else t\n }._1)\n }\n }\n\n def main(args: Array[String]) {\n\n val n = in.readLine().toInt\n\n val t = new UndirectedGraph(n) with TreeFeatures\n\n FOR(1, n-1) { _ =>\n val Array(u, v) = in.readLine().split(\" +\").map(_.toInt - 1)\n t.addEdge(u, v)\n }\n\n t.computeFeatures(0)\n\n val m = in.readLine().toInt\n\n FOR(1,m) { _ =>\n val Array(u, v) = in.readLine().split(\" +\").map(_.toInt - 1)\n\n if (u == v) {\n out.println(n)\n } else {\n\n val w = t.lca(u, v)\n val d = t.depth(u) + t.depth(v) - 2 * t.depth(w)\n\n if (d % 2 == 1) {\n out.println(0)\n } else {\n\n if (t.depth(u) == t.depth(v)) {\n val x = t.ancestor(u, d / 2 - 1)\n val y = t.ancestor(v, d / 2 - 1)\n out.println(n - t.subtreeSize(x) - t.subtreeSize(y))\n } else {\n val (_, yTmp) = if (t.depth(u) > t.depth(v)) (v, u) else (u, v)\n val y = t.ancestor(yTmp, d / 2 - 1)\n out.println(t.subtreeSize(t.parent(y)) - t.subtreeSize(y))\n }\n\n }\n }\n }\n\n out.close()\n }\n\n}"}, {"source_code": "import java.io._\n\nobject Main {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n val LOGN = 18\n\n trait GraphLike {\n def n: Int\n\n def adj: Array[List[Int]]\n }\n\n class UndirectedGraph(val n: Int) extends GraphLike {\n\n val adj = Array.fill(n)(List[Int]())\n\n def apply(i: Int) = adj(i)\n\n def addEdge(u: Int, v: Int): Unit = {\n adj(u) = v :: adj(u)\n adj(v) = u :: adj(v)\n }\n\n }\n\n trait TreeFeatures {\n this: GraphLike =>\n\n val parent = new Array[Int](n)\n val depth = new Array[Int](n)\n val subtreeSize = new Array[Int](n)\n val dp = Array.ofDim[Int](n, LOGN)\n\n private def computeLCA(): Unit = {\n (0 until n).foreach { i =>\n dp(i)(0) = parent(i)\n var j = 1\n while ((1 << j) < n) {\n dp(i)(j) = -1\n j += 1\n }\n }\n\n var j = 1\n while ((1 << j) < n) {\n (0 until n).foreach { i =>\n if (dp(i)(j - 1) != -1)\n dp(i)(j) = dp(dp(i)(j - 1))(j - 1)\n }\n j += 1\n }\n }\n\n def computeFeatures(root: Int) = {\n\n def dfs(u: Int, pu: Int): Unit = {\n subtreeSize(u) = 1\n adj(u).foreach { v =>\n if (v != pu) {\n parent(v) = u\n depth(v) = depth(u) + 1\n dfs(v, u)\n subtreeSize(u) += subtreeSize(v)\n }\n }\n }\n\n parent(root) = -1\n dfs(root, -1)\n\n computeLCA()\n }\n\n def ancestor(u: Int, count: Int) = {\n\n (0 until LOGN).foldLeft(u) {\n (v, i) => if (((count >> i) & 1) == 1) dp(v)(i) else v\n }\n\n// var x = u\n// var rd = count\n// var i = LOGN\n// while (i >= 0) {\n// if (rd - (1 << i) >= 0 && dp(x)(i) != -1) {\n// rd -= (1 << i)\n// x = dp(x)(i)\n// }\n// i -= 1\n// }\n// x\n }\n\n def lca(pp: Int, qq: Int) = {\n var tmp, log, i = 0\n var p = pp\n var q = qq\n\n if (depth(p) < depth(q)) {\n tmp = p\n p = q\n q = tmp\n }\n\n log = 1\n while ((1 << log) <= depth(p)) log += 1\n log -= 1\n\n i = log\n while (i >= 0) {\n if (depth(p) - (1 << i) >= depth(q)) p = dp(p)(i)\n i -= 1\n }\n\n if (p == q) {\n p\n } else {\n i = log\n while (i >= 0) {\n if (dp(p)(i) != -1 && dp(p)(i) != dp(q)(i)) {\n p = dp(p)(i)\n q = dp(q)(i)\n }\n i -= 1\n }\n parent(p)\n }\n }\n\n }\n\n def main(args: Array[String]) {\n\n val n = in.readLine().toInt\n\n val t = new UndirectedGraph(n) with TreeFeatures\n\n (1 until n).foreach { i =>\n val Array(u, v) = in.readLine().split(\" +\").map(_.toInt)\n t.addEdge(u - 1, v - 1)\n }\n\n t.computeFeatures(0)\n\n val m = in.readLine().toInt\n\n (1 to m).foreach { _ =>\n val Array(uu, vv) = in.readLine().split(\" +\").map(_.toInt)\n\n val u = uu - 1\n val v = vv - 1\n\n if (u == v) {\n out.println(n)\n } else {\n\n val w = t.lca(u, v)\n val d = t.depth(u) + t.depth(v) - 2 * t.depth(w)\n\n if (d % 2 == 1) {\n out.println(0)\n } else {\n\n if (t.depth(u) == t.depth(v)) {\n val x = t.ancestor(u, d / 2 - 1)\n val y = t.ancestor(v, d / 2 - 1)\n out.println(n - t.subtreeSize(x) - t.subtreeSize(y))\n } else {\n val (_, yTmp) = if (t.depth(u) > t.depth(v)) (v, u) else (u, v)\n val y = t.ancestor(yTmp, d / 2 - 1)\n out.println(t.subtreeSize(t.parent(y)) - t.subtreeSize(y))\n }\n\n }\n }\n }\n\n out.close()\n }\n\n}"}, {"source_code": "import java.io._\n\nobject Main {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n val LOGN = 18\n\n var adj: Array[List[Int]] = null\n var t: Array[Int] = null\n var h: Array[Int] = null\n var sz: Array[Int] = null\n\n def dfs(u: Int, pu: Int): Unit = {\n sz(u) = 1\n adj(u).foreach { v =>\n if (v != pu) {\n t(v) = u\n h(v) = h(u) + 1\n dfs(v, u)\n sz(u) += sz(v)\n }\n }\n }\n\n def lca(pp: Int, qq: Int, n: Int, dp: Array[Array[Int]]) = {\n var tmp, log, i = 0\n var p = pp\n var q = qq\n\n if (h(p) < h(q)) {\n tmp = p\n p = q\n q = tmp\n }\n\n log = 1\n while ((1 << log) <= h(p)) log += 1\n log -= 1\n\n i = log\n while (i >= 0) {\n if (h(p) - (1 << i) >= h(q)) p = dp(p)(i)\n i -= 1\n }\n\n if (p == q) {\n p\n } else {\n i = log\n while (i >= 0) {\n if (dp(p)(i) != -1 && dp(p)(i) != dp(q)(i)) {\n p = dp(p)(i)\n q = dp(q)(i)\n }\n i -= 1\n }\n t(p)\n }\n }\n\n def ancestor(u: Int, d: Int, dp: Array[Array[Int]]) = {\n var x = u\n var rd = d\n var i = LOGN\n while (i >= 0) {\n if (rd - (1 << i) >= 0 && dp(x)(i) != -1) {\n rd -= (1 << i)\n x = dp(x)(i)\n }\n i -= 1\n }\n x\n }\n\n def main(args: Array[String]) {\n\n val n = in.readLine().toInt\n adj = new Array[List[Int]](n)\n t = new Array[Int](n)\n h = new Array[Int](n)\n sz = new Array[Int](n)\n\n (0 until n).foreach { i => adj(i) = Nil}\n\n (1 until n).foreach { i =>\n val Array(u, v) = in.readLine().split(\" +\").map(_.toInt)\n adj(u - 1) = (v - 1) :: adj(u - 1)\n adj(v - 1) = (u - 1) :: adj(v - 1)\n }\n\n val m = in.readLine().toInt\n\n t(0) = -1\n\n dfs(0, -1)\n\n val dp = Array.ofDim[Int](n, LOGN)\n\n (0 until n).foreach { i =>\n dp(i)(0) = t(i)\n var j = 1\n while ((1 << j) < n) {\n dp(i)(j) = -1\n j += 1\n }\n }\n\n var j = 1\n while ((1 << j) < n) {\n (0 until n).foreach { i =>\n if (dp(i)(j - 1) != -1)\n dp(i)(j) = dp(dp(i)(j - 1))(j - 1)\n }\n j += 1\n }\n\n (1 to m).foreach { _ =>\n val Array(uu, vv) = in.readLine().split(\" +\").map(_.toInt)\n\n val u = uu - 1\n val v = vv - 1\n\n\n if (u == v) {\n out.println(n)\n } else {\n val w = lca(u, v, n, dp)\n val d = h(u) + h(v) - 2 * h(w)\n\n if (d % 2 == 1) {\n out.println(0)\n } else {\n\n if (h(u) == h(v)) {\n val x = ancestor(u, d / 2 - 1, dp)\n val y = ancestor(v, d / 2 - 1, dp)\n out.println(n - sz(x) - sz(y))\n } else {\n val (_, yTmp) = if (h(u) > h(v)) (v, u) else (u, v)\n val y = ancestor(yTmp, d / 2 - 1, dp)\n out.println(sz(t(y)) - sz(y))\n }\n\n }\n }\n }\n\n out.close()\n }\n\n}"}, {"source_code": "import java.io._\n\nimport scala.annotation.tailrec\n\nobject Main {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n class UndirectedGraph(val n: Int) {\n\n val adj = Array.fill(n)(List[Int]())\n\n def apply(i: Int) = adj(i)\n\n def addEdge(u: Int, v: Int): Unit = {\n adj(u) = v :: adj(u)\n adj(v) = u :: adj(v)\n }\n\n }\n\n trait TreeFeatures {\n this: UndirectedGraph =>\n\n val lgn = (1 to 32).find(x => (1 << x) >= n).get\n val parent = new Array[Int](n)\n val depth = new Array[Int](n)\n val subtreeSize = new Array[Int](n)\n val dp = Array.ofDim[Int](lgn, n)\n\n private def computeLCA(): Unit = {\n (0 until n).foreach { i =>\n dp(0)(i) = parent(i)\n var j = 1\n while ((1 << j) < n) {\n dp(j)(i) = -1\n j += 1\n }\n }\n\n var j = 1\n while ((1 << j) < n) {\n (0 until n).foreach { i =>\n if (dp(j - 1)(i) != -1)\n dp(j)(i) = dp(j - 1)(dp(j - 1)(i))\n }\n j += 1\n }\n }\n\n def computeFeatures(root: Int) = {\n\n def dfs(u: Int, pu: Int): Unit = {\n subtreeSize(u) = 1\n adj(u).foreach { v =>\n if (v != pu) {\n parent(v) = u\n depth(v) = depth(u) + 1\n dfs(v, u)\n subtreeSize(u) += subtreeSize(v)\n }\n }\n }\n\n parent(root) = -1\n dfs(root, -1)\n\n computeLCA()\n }\n\n def ancestor(u: Int, count: Int) = (0 until lgn).foldLeft(u) {\n (v, i) => if (((count >> i) & 1) == 1) dp(i)(v) else v\n }\n\n @tailrec final def lca(u: Int, v: Int): Int = {\n if (depth(u) > depth(v)) lca(ancestor(u, depth(u) - depth(v)), v)\n else if (depth(u) < depth(v)) lca(u, ancestor(v, depth(v) - depth(u)))\n else if (u == v) u\n else parent(((lgn - 1) to 0 by -1).foldLeft((u, v)) {\n (t, i) => if (dp(i)(t._1) != dp(i)(t._2)) (dp(i)(t._1), dp(i)(t._2)) else t\n }._1)\n }\n }\n\n def main(args: Array[String]) {\n\n val n = in.readLine().toInt\n\n val t = new UndirectedGraph(n) with TreeFeatures\n\n (1 until n).foreach { i =>\n val Array(u, v) = in.readLine().split(\" +\").map(_.toInt)\n t.addEdge(u - 1, v - 1)\n }\n\n t.computeFeatures(0)\n\n val m = in.readLine().toInt\n\n (1 to m).foreach { _ =>\n val Array(uu, vv) = in.readLine().split(\" +\").map(_.toInt)\n\n val u = uu - 1\n val v = vv - 1\n\n if (u == v) {\n out.println(n)\n } else {\n\n val w = t.lca(u, v)\n val d = t.depth(u) + t.depth(v) - 2 * t.depth(w)\n\n if (d % 2 == 1) {\n out.println(0)\n } else {\n\n if (t.depth(u) == t.depth(v)) {\n val x = t.ancestor(u, d / 2 - 1)\n val y = t.ancestor(v, d / 2 - 1)\n out.println(n - t.subtreeSize(x) - t.subtreeSize(y))\n } else {\n val (_, yTmp) = if (t.depth(u) > t.depth(v)) (v, u) else (u, v)\n val y = t.ancestor(yTmp, d / 2 - 1)\n out.println(t.subtreeSize(t.parent(y)) - t.subtreeSize(y))\n }\n\n }\n }\n }\n\n out.close()\n }\n\n}"}, {"source_code": "import java.io._\n\nobject Main {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n trait GraphLike {\n def n: Int\n\n def adj: Array[List[Int]]\n }\n\n class UndirectedGraph(val n: Int) extends GraphLike {\n\n val adj = Array.fill(n)(List[Int]())\n\n def apply(i: Int) = adj(i)\n\n def addEdge(u: Int, v: Int): Unit = {\n adj(u) = v :: adj(u)\n adj(v) = u :: adj(v)\n }\n\n }\n\n trait TreeFeatures {\n this: GraphLike =>\n\n val lgn = (1 to 32).find(x => (1 << x) >= n).get\n val parent = new Array[Int](n)\n val depth = new Array[Int](n)\n val subtreeSize = new Array[Int](n)\n val dp = Array.ofDim[Int](lgn, n)\n\n private def computeLCA(): Unit = {\n (0 until n).foreach { i =>\n dp(0)(i) = parent(i)\n var j = 1\n while ((1 << j) < n) {\n dp(j)(i) = -1\n j += 1\n }\n }\n\n var j = 1\n while ((1 << j) < n) {\n (0 until n).foreach { i =>\n if (dp(j - 1)(i) != -1)\n dp(j)(i) = dp(j - 1)(dp(j - 1)(i))\n }\n j += 1\n }\n }\n\n def computeFeatures(root: Int) = {\n\n def dfs(u: Int, pu: Int): Unit = {\n subtreeSize(u) = 1\n adj(u).foreach { v =>\n if (v != pu) {\n parent(v) = u\n depth(v) = depth(u) + 1\n dfs(v, u)\n subtreeSize(u) += subtreeSize(v)\n }\n }\n }\n\n parent(root) = -1\n dfs(root, -1)\n\n computeLCA()\n }\n\n def ancestor(u: Int, count: Int) = (0 until lgn).foldLeft(u) {\n (v, i) => if (((count >> i) & 1) == 1) dp(i)(v) else v\n }\n\n def lca(u: Int, v: Int): Int = {\n if (depth(u) > depth(v)) lca(ancestor(u, depth(u) - depth(v)), v)\n else if (depth(u) < depth(v)) lca(u, ancestor(v, depth(v) - depth(u)))\n else if (u == v) u\n else parent(((lgn - 1) to 0 by -1).foldLeft((u, v)) {\n (t, i) => if (dp(i)(t._1) != dp(i)(t._2)) (dp(i)(t._1), dp(i)(t._2)) else t\n }._1)\n }\n\n }\n\n def main(args: Array[String]) {\n\n val n = in.readLine().toInt\n\n val t = new UndirectedGraph(n) with TreeFeatures\n\n (1 until n).foreach { i =>\n val Array(u, v) = in.readLine().split(\" +\").map(_.toInt)\n t.addEdge(u - 1, v - 1)\n }\n\n t.computeFeatures(0)\n\n val m = in.readLine().toInt\n\n (1 to m).foreach { _ =>\n val Array(uu, vv) = in.readLine().split(\" +\").map(_.toInt)\n\n val u = uu - 1\n val v = vv - 1\n\n if (u == v) {\n out.println(n)\n } else {\n\n val w = t.lca(u, v)\n val d = t.depth(u) + t.depth(v) - 2 * t.depth(w)\n\n if (d % 2 == 1) {\n out.println(0)\n } else {\n\n if (t.depth(u) == t.depth(v)) {\n val x = t.ancestor(u, d / 2 - 1)\n val y = t.ancestor(v, d / 2 - 1)\n out.println(n - t.subtreeSize(x) - t.subtreeSize(y))\n } else {\n val (_, yTmp) = if (t.depth(u) > t.depth(v)) (v, u) else (u, v)\n val y = t.ancestor(yTmp, d / 2 - 1)\n out.println(t.subtreeSize(t.parent(y)) - t.subtreeSize(y))\n }\n\n }\n }\n }\n\n out.close()\n }\n\n}"}, {"source_code": "import java.io._\n\nobject Main {\n\n class UndirectedGraph(n: Int) {\n val adj = Array.fill(n)(List[Int]())\n\n def addEdge(u: Int, v: Int): Unit = {\n adj(u) = v :: adj(u)\n adj(v) = u :: adj(v)\n }\n \n }\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n val LOGN = 18\n\n var t: Array[Int] = null\n var h: Array[Int] = null\n var sz: Array[Int] = null\n\n def dfs(u: Int, pu: Int)(implicit g: UndirectedGraph): Unit = {\n sz(u) = 1\n g.adj(u).foreach { v =>\n if (v != pu) {\n t(v) = u\n h(v) = h(u) + 1\n dfs(v, u)\n sz(u) += sz(v)\n }\n }\n }\n\n def lca(pp: Int, qq: Int, n: Int, dp: Array[Array[Int]]) = {\n var tmp, log, i = 0\n var p = pp\n var q = qq\n\n if (h(p) < h(q)) {\n tmp = p\n p = q\n q = tmp\n }\n\n log = 1\n while ((1 << log) <= h(p)) log += 1\n log -= 1\n\n i = log\n while (i >= 0) {\n if (h(p) - (1 << i) >= h(q)) p = dp(p)(i)\n i -= 1\n }\n\n if (p == q) {\n p\n } else {\n i = log\n while (i >= 0) {\n if (dp(p)(i) != -1 && dp(p)(i) != dp(q)(i)) {\n p = dp(p)(i)\n q = dp(q)(i)\n }\n i -= 1\n }\n t(p)\n }\n }\n\n def ancestor(u: Int, d: Int, dp: Array[Array[Int]]) = {\n var x = u\n var rd = d\n var i = LOGN\n while (i >= 0) {\n if (rd - (1 << i) >= 0 && dp(x)(i) != -1) {\n rd -= (1 << i)\n x = dp(x)(i)\n }\n i -= 1\n }\n x\n }\n\n def main(args: Array[String]) {\n\n val n = in.readLine().toInt\n implicit val g = new UndirectedGraph(n)\n t = new Array[Int](n)\n h = new Array[Int](n)\n sz = new Array[Int](n)\n\n// (0 until n).foreach { i => adj(i) = Nil}\n\n (1 until n).foreach { i =>\n val Array(u, v) = in.readLine().split(\" +\").map(_.toInt)\n g.addEdge(u - 1, v - 1)\n }\n\n val m = in.readLine().toInt\n\n t(0) = -1\n\n dfs(0, -1)\n\n val dp = Array.ofDim[Int](n, LOGN)\n\n (0 until n).foreach { i =>\n dp(i)(0) = t(i)\n var j = 1\n while ((1 << j) < n) {\n dp(i)(j) = -1\n j += 1\n }\n }\n\n var j = 1\n while ((1 << j) < n) {\n (0 until n).foreach { i =>\n if (dp(i)(j - 1) != -1)\n dp(i)(j) = dp(dp(i)(j - 1))(j - 1)\n }\n j += 1\n }\n\n (1 to m).foreach { _ =>\n val Array(uu, vv) = in.readLine().split(\" +\").map(_.toInt)\n\n val u = uu - 1\n val v = vv - 1\n\n if (u == v) {\n out.println(n)\n } else {\n val w = lca(u, v, n, dp)\n val d = h(u) + h(v) - 2 * h(w)\n\n if (d % 2 == 1) {\n out.println(0)\n } else {\n\n if (h(u) == h(v)) {\n val x = ancestor(u, d / 2 - 1, dp)\n val y = ancestor(v, d / 2 - 1, dp)\n out.println(n - sz(x) - sz(y))\n } else {\n val (_, yTmp) = if (h(u) > h(v)) (v, u) else (u, v)\n val y = ancestor(yTmp, d / 2 - 1, dp)\n out.println(sz(t(y)) - sz(y))\n }\n\n }\n }\n }\n\n out.close()\n }\n\n}"}, {"source_code": "import java.io._\n\nobject Main {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n trait GraphLike {\n def n: Int\n\n def adj: Array[List[Int]]\n }\n\n class UndirectedGraph(val n: Int) extends GraphLike {\n\n val adj = Array.fill(n)(List[Int]())\n\n def apply(i: Int) = adj(i)\n\n def addEdge(u: Int, v: Int): Unit = {\n adj(u) = v :: adj(u)\n adj(v) = u :: adj(v)\n }\n\n }\n\n trait TreeFeatures {\n this: GraphLike =>\n\n val lgn = (1 to 32).find(x => (1 << x) >= n).get\n val parent = new Array[Int](n)\n val depth = new Array[Int](n)\n val subtreeSize = new Array[Int](n)\n val dp = Array.ofDim[Int](lgn, n)\n\n private def computeLCA(): Unit = {\n (0 until n).foreach { i =>\n dp(0)(i) = parent(i)\n var j = 1\n while ((1 << j) < n) {\n dp(j)(i) = -1\n j += 1\n }\n }\n\n var j = 1\n while ((1 << j) < n) {\n (0 until n).foreach { i =>\n if (dp(j - 1)(i) != -1)\n dp(j)(i) = dp(j - 1)(dp(j - 1)(i))\n }\n j += 1\n }\n }\n\n def computeFeatures(root: Int) = {\n\n def dfs(u: Int, pu: Int): Unit = {\n subtreeSize(u) = 1\n adj(u).foreach { v =>\n if (v != pu) {\n parent(v) = u\n depth(v) = depth(u) + 1\n dfs(v, u)\n subtreeSize(u) += subtreeSize(v)\n }\n }\n }\n\n parent(root) = -1\n dfs(root, -1)\n\n computeLCA()\n }\n\n def ancestor(u: Int, count: Int) = (0 until lgn).foldLeft(u) {\n (v, i) => if (((count >> i) & 1) == 1) dp(i)(v) else v\n }\n\n // def lca(u: Int, v: Int): Int = {\n //\n // if (depth(u) > depth(v)) lca(ancestor(u, depth(u) - depth(v)), v)\n // else if (depth(u) < depth(v)) lca(u, ancestor(v, depth(v) - depth(u)))\n // else if (u==v) u\n // else parent(((lgn-1) to 0 by -1).foldLeft((u, v)) {\n // (t, i) => if (dp(i)(t._1) != dp(i)(t._2)) (dp(i)(t._1), dp(i)(t._2)) else t\n // }._1)\n // }\n \n def lca(pp: Int, qq: Int): Int = {\n var tmp, log, i = 0\n var p = pp\n var q = qq\n\n if (depth(p) < depth(q)) {\n tmp = p\n p = q\n q = tmp\n }\n\n log = 1\n while ((1 << log) <= depth(p)) log += 1\n log -= 1\n\n i = log\n while (i >= 0) {\n if (depth(p) - (1 << i) >= depth(q)) p = dp(i)(p)\n i -= 1\n }\n\n if (p == q) {\n p\n } else {\n i = log\n while (i >= 0) {\n if (dp(i)(p) != -1 && dp(i)(p) != dp(i)(q)) {\n p = dp(i)(p)\n q = dp(i)(q)\n }\n i -= 1\n }\n parent(p)\n }\n }\n\n }\n\n def main(args: Array[String]) {\n\n val n = in.readLine().toInt\n\n val t = new UndirectedGraph(n) with TreeFeatures\n\n (1 until n).foreach { i =>\n val Array(u, v) = in.readLine().split(\" +\").map(_.toInt)\n t.addEdge(u - 1, v - 1)\n }\n\n t.computeFeatures(0)\n\n val m = in.readLine().toInt\n\n (1 to m).foreach { _ =>\n val Array(uu, vv) = in.readLine().split(\" +\").map(_.toInt)\n\n val u = uu - 1\n val v = vv - 1\n\n if (u == v) {\n out.println(n)\n } else {\n\n val w = t.lca(u, v)\n val d = t.depth(u) + t.depth(v) - 2 * t.depth(w)\n\n if (d % 2 == 1) {\n out.println(0)\n } else {\n\n if (t.depth(u) == t.depth(v)) {\n val x = t.ancestor(u, d / 2 - 1)\n val y = t.ancestor(v, d / 2 - 1)\n out.println(n - t.subtreeSize(x) - t.subtreeSize(y))\n } else {\n val (_, yTmp) = if (t.depth(u) > t.depth(v)) (v, u) else (u, v)\n val y = t.ancestor(yTmp, d / 2 - 1)\n out.println(t.subtreeSize(t.parent(y)) - t.subtreeSize(y))\n }\n\n }\n }\n }\n\n out.close()\n }\n\n}"}, {"source_code": "import java.io._\n\nimport scala.annotation.tailrec\n\nobject Main {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n trait GraphLike {\n def n: Int\n\n def adj: Array[List[Int]]\n }\n\n class UndirectedGraph(val n: Int) extends GraphLike {\n\n val adj = Array.fill(n)(List[Int]())\n\n def apply(i: Int) = adj(i)\n\n def addEdge(u: Int, v: Int): Unit = {\n adj(u) = v :: adj(u)\n adj(v) = u :: adj(v)\n }\n\n }\n\n trait TreeFeatures {\n this: GraphLike =>\n\n val lgn = (1 to 32).find(x => (1 << x) >= n).get\n val parent = new Array[Int](n)\n val depth = new Array[Int](n)\n val subtreeSize = new Array[Int](n)\n val dp = Array.ofDim[Int](lgn, n)\n\n private def computeLCA(): Unit = {\n (0 until n).foreach { i =>\n dp(0)(i) = parent(i)\n var j = 1\n while ((1 << j) < n) {\n dp(j)(i) = -1\n j += 1\n }\n }\n\n var j = 1\n while ((1 << j) < n) {\n (0 until n).foreach { i =>\n if (dp(j - 1)(i) != -1)\n dp(j)(i) = dp(j - 1)(dp(j - 1)(i))\n }\n j += 1\n }\n }\n\n def computeFeatures(root: Int) = {\n\n def dfs(u: Int, pu: Int): Unit = {\n subtreeSize(u) = 1\n adj(u).foreach { v =>\n if (v != pu) {\n parent(v) = u\n depth(v) = depth(u) + 1\n dfs(v, u)\n subtreeSize(u) += subtreeSize(v)\n }\n }\n }\n\n parent(root) = -1\n dfs(root, -1)\n\n computeLCA()\n }\n\n def ancestor(u: Int, count: Int) = (0 until lgn).foldLeft(u) {\n (v, i) => if (((count >> i) & 1) == 1) dp(i)(v) else v\n }\n\n @tailrec final def lca(u: Int, v: Int): Int = {\n if (depth(u) > depth(v)) lca(ancestor(u, depth(u) - depth(v)), v)\n else if (depth(u) < depth(v)) lca(u, ancestor(v, depth(v) - depth(u)))\n else if (u == v) u\n else parent(((lgn - 1) to 0 by -1).foldLeft((u, v)) {\n (t, i) => if (dp(i)(t._1) != dp(i)(t._2)) (dp(i)(t._1), dp(i)(t._2)) else t\n }._1)\n }\n\n // def lca(pp: Int, qq: Int): Int = {\n // var tmp, log, i = 0\n // var p = pp\n // var q = qq\n //\n // if (depth(p) < depth(q)) {\n // tmp = p\n // p = q\n // q = tmp\n // }\n //\n // log = 1\n // while ((1 << log) <= depth(p)) log += 1\n // log -= 1\n //\n // i = log\n // while (i >= 0) {\n // if (depth(p) - (1 << i) >= depth(q)) p = dp(i)(p)\n // i -= 1\n // }\n //\n // if (p == q) {\n // p\n // } else {\n // i = log\n // while (i >= 0) {\n // if (dp(i)(p) != -1 && dp(i)(p) != dp(i)(q)) {\n // p = dp(i)(p)\n // q = dp(i)(q)\n // }\n // i -= 1\n // }\n // parent(p)\n // }\n // }\n //\n \n }\n\n def main(args: Array[String]) {\n\n val n = in.readLine().toInt\n\n val t = new UndirectedGraph(n) with TreeFeatures\n\n (1 until n).foreach { i =>\n val Array(u, v) = in.readLine().split(\" +\").map(_.toInt)\n t.addEdge(u - 1, v - 1)\n }\n\n t.computeFeatures(0)\n\n val m = in.readLine().toInt\n\n (1 to m).foreach { _ =>\n val Array(uu, vv) = in.readLine().split(\" +\").map(_.toInt)\n\n val u = uu - 1\n val v = vv - 1\n\n if (u == v) {\n out.println(n)\n } else {\n\n val w = t.lca(u, v)\n val d = t.depth(u) + t.depth(v) - 2 * t.depth(w)\n\n if (d % 2 == 1) {\n out.println(0)\n } else {\n\n if (t.depth(u) == t.depth(v)) {\n val x = t.ancestor(u, d / 2 - 1)\n val y = t.ancestor(v, d / 2 - 1)\n out.println(n - t.subtreeSize(x) - t.subtreeSize(y))\n } else {\n val (_, yTmp) = if (t.depth(u) > t.depth(v)) (v, u) else (u, v)\n val y = t.ancestor(yTmp, d / 2 - 1)\n out.println(t.subtreeSize(t.parent(y)) - t.subtreeSize(y))\n }\n\n }\n }\n }\n\n out.close()\n }\n\n}"}, {"source_code": "import java.io._\n\nobject Main {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n val LOGN = 18\n\n trait GraphLike {\n def n: Int\n\n def adj: Array[List[Int]]\n }\n\n class UndirectedGraph(val n: Int) extends GraphLike {\n\n val adj = Array.fill(n)(List[Int]())\n\n def apply(i: Int) = adj(i)\n\n def addEdge(u: Int, v: Int): Unit = {\n adj(u) = v :: adj(u)\n adj(v) = u :: adj(v)\n }\n\n }\n\n trait TreeFeatures {\n this: GraphLike =>\n\n val parent = new Array[Int](n)\n val depth = new Array[Int](n)\n val subtreeSize = new Array[Int](n)\n val dp = Array.ofDim[Int](LOGN, n)\n\n private def computeLCA(): Unit = {\n (0 until n).foreach { i =>\n dp(0)(i) = parent(i)\n var j = 1\n while ((1 << j) < n) {\n dp(j)(i) = -1\n j += 1\n }\n }\n\n var j = 1\n while ((1 << j) < n) {\n (0 until n).foreach { i =>\n if (dp(j - 1)(i) != -1)\n dp(j)(i) = dp(j - 1)(dp(j - 1)(i))\n }\n j += 1\n }\n }\n\n def computeFeatures(root: Int) = {\n\n def dfs(u: Int, pu: Int): Unit = {\n subtreeSize(u) = 1\n adj(u).foreach { v =>\n if (v != pu) {\n parent(v) = u\n depth(v) = depth(u) + 1\n dfs(v, u)\n subtreeSize(u) += subtreeSize(v)\n }\n }\n }\n\n parent(root) = -1\n dfs(root, -1)\n\n computeLCA()\n }\n\n def ancestor(u: Int, count: Int) = (0 until LOGN).foldLeft(u) {\n (v, i) => if (((count >> i) & 1) == 1) dp(i)(v) else v\n }\n\n def lca(pp: Int, qq: Int) = {\n var tmp, log, i = 0\n var p = pp\n var q = qq\n\n if (depth(p) < depth(q)) {\n tmp = p\n p = q\n q = tmp\n }\n\n log = 1\n while ((1 << log) <= depth(p)) log += 1\n log -= 1\n\n i = log\n while (i >= 0) {\n if (depth(p) - (1 << i) >= depth(q)) p = dp(i)(p)\n i -= 1\n }\n\n if (p == q) {\n p\n } else {\n i = log\n while (i >= 0) {\n if (dp(i)(p) != -1 && dp(i)(p) != dp(i)(q)) {\n p = dp(i)(p)\n q = dp(i)(q)\n }\n i -= 1\n }\n parent(p)\n }\n }\n\n }\n\n def main(args: Array[String]) {\n\n val n = in.readLine().toInt\n\n val t = new UndirectedGraph(n) with TreeFeatures\n\n (1 until n).foreach { i =>\n val Array(u, v) = in.readLine().split(\" +\").map(_.toInt)\n t.addEdge(u - 1, v - 1)\n }\n\n t.computeFeatures(0)\n\n val m = in.readLine().toInt\n\n (1 to m).foreach { _ =>\n val Array(uu, vv) = in.readLine().split(\" +\").map(_.toInt)\n\n val u = uu - 1\n val v = vv - 1\n\n if (u == v) {\n out.println(n)\n } else {\n\n val w = t.lca(u, v)\n val d = t.depth(u) + t.depth(v) - 2 * t.depth(w)\n\n if (d % 2 == 1) {\n out.println(0)\n } else {\n\n if (t.depth(u) == t.depth(v)) {\n val x = t.ancestor(u, d / 2 - 1)\n val y = t.ancestor(v, d / 2 - 1)\n out.println(n - t.subtreeSize(x) - t.subtreeSize(y))\n } else {\n val (_, yTmp) = if (t.depth(u) > t.depth(v)) (v, u) else (u, v)\n val y = t.ancestor(yTmp, d / 2 - 1)\n out.println(t.subtreeSize(t.parent(y)) - t.subtreeSize(y))\n }\n\n }\n }\n }\n\n out.close()\n }\n\n}"}, {"source_code": "import java.io._\n\nobject Main {\n\n trait GraphLike {\n def n: Int\n\n def adj: Array[List[Int]]\n }\n\n class UndirectedGraph(val n: Int) extends GraphLike {\n\n val adj = Array.fill(n)(List[Int]())\n\n def apply(i: Int) = adj(i)\n\n def addEdge(u: Int, v: Int): Unit = {\n adj(u) = v :: adj(u)\n adj(v) = u :: adj(v)\n }\n\n }\n\n trait TreeFeatures {\n this: GraphLike =>\n\n def features(root: Int) = {\n val t = new Array[Int](n)\n val h = new Array[Int](n)\n val sz = new Array[Int](n)\n\n def dfs(u: Int, pu: Int): Unit = {\n sz(u) = 1\n adj(u).foreach { v =>\n if (v != pu) {\n t(v) = u\n h(v) = h(u) + 1\n dfs(v, u)\n sz(u) += sz(v)\n }\n }\n }\n\n t(root) = -1\n dfs(root, -1)\n (t, h, sz)\n }\n\n }\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n val LOGN = 18\n\n def lca(pp: Int, qq: Int, n: Int, dp: Array[Array[Int]], h: Array[Int], t: Array[Int]) = {\n var tmp, log, i = 0\n var p = pp\n var q = qq\n\n if (h(p) < h(q)) {\n tmp = p\n p = q\n q = tmp\n }\n\n log = 1\n while ((1 << log) <= h(p)) log += 1\n log -= 1\n\n i = log\n while (i >= 0) {\n if (h(p) - (1 << i) >= h(q)) p = dp(p)(i)\n i -= 1\n }\n\n if (p == q) {\n p\n } else {\n i = log\n while (i >= 0) {\n if (dp(p)(i) != -1 && dp(p)(i) != dp(q)(i)) {\n p = dp(p)(i)\n q = dp(q)(i)\n }\n i -= 1\n }\n t(p)\n }\n }\n\n def ancestor(u: Int, d: Int, dp: Array[Array[Int]]) = {\n var x = u\n var rd = d\n var i = LOGN\n while (i >= 0) {\n if (rd - (1 << i) >= 0 && dp(x)(i) != -1) {\n rd -= (1 << i)\n x = dp(x)(i)\n }\n i -= 1\n }\n x\n }\n\n def getLcaTable(n: Int, t: Array[Int]) = {\n\n val dp = Array.ofDim[Int](n, LOGN)\n\n (0 until n).foreach { i =>\n dp(i)(0) = t(i)\n var j = 1\n while ((1 << j) < n) {\n dp(i)(j) = -1\n j += 1\n }\n }\n\n var j = 1\n while ((1 << j) < n) {\n (0 until n).foreach { i =>\n if (dp(i)(j - 1) != -1)\n dp(i)(j) = dp(dp(i)(j - 1))(j - 1)\n }\n j += 1\n }\n\n dp\n }\n\n def main(args: Array[String]) {\n\n val n = in.readLine().toInt\n\n val g = new UndirectedGraph(n) with TreeFeatures\n\n (1 until n).foreach { i =>\n val Array(u, v) = in.readLine().split(\" +\").map(_.toInt)\n g.addEdge(u - 1, v - 1)\n }\n\n val (t, h, sz) = g.features(0)\n val dp = getLcaTable(n, t)\n\n val m = in.readLine().toInt\n\n (1 to m).foreach { _ =>\n val Array(uu, vv) = in.readLine().split(\" +\").map(_.toInt)\n\n val u = uu - 1\n val v = vv - 1\n\n if (u == v) {\n out.println(n)\n } else {\n val w = lca(u, v, n, dp, h, t)\n val d = h(u) + h(v) - 2 * h(w)\n\n if (d % 2 == 1) {\n out.println(0)\n } else {\n\n if (h(u) == h(v)) {\n val x = ancestor(u, d / 2 - 1, dp)\n val y = ancestor(v, d / 2 - 1, dp)\n out.println(n - sz(x) - sz(y))\n } else {\n val (_, yTmp) = if (h(u) > h(v)) (v, u) else (u, v)\n val y = ancestor(yTmp, d / 2 - 1, dp)\n out.println(sz(t(y)) - sz(y))\n }\n\n }\n }\n }\n\n out.close()\n }\n\n}"}], "negative_code": [{"source_code": "import java.io._\n\nobject Main {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n val LOGN = 18\n\n var adj: Array[List[Int]] = null\n var t: Array[Int] = null\n var h: Array[Int] = null\n var sz: Array[Int] = null\n\n def dfs(u: Int, pu: Int): Unit = {\n sz(u) = 1\n adj(u).foreach { v =>\n if (v != pu) {\n t(v) = u\n h(v) = h(u) + 1\n dfs(v, u)\n sz(u) += sz(v)\n }\n }\n }\n\n def lca(pp: Int, qq: Int, n: Int, dp: Array[Array[Int]]) = {\n var tmp, log, i = 0\n var p = pp\n var q = qq\n\n if (h(p) < h(q)) {\n tmp = p\n p = q\n q = tmp\n }\n\n log = 1\n while ((1 << log) <= h(p)) log += 1\n log -= 1\n\n i = log\n while (i >= 0) {\n if (h(p) - (1 << i) >= h(q)) p = dp(p)(i)\n i -= 1\n }\n\n if (p == q) {\n p\n } else {\n i = log\n while (i >= 0) {\n if (dp(p)(i) != -1 && dp(p)(i) != dp(q)(i)) {\n p = dp(p)(i)\n q = dp(q)(i)\n }\n i -= 1\n }\n t(p)\n }\n }\n\n def goup(u: Int, d: Int, dp: Array[Array[Int]]) = {\n var x = u\n var rd = d\n var i = LOGN\n while (i >= 0) {\n if (rd - (1 << i) >= 0 && dp(x)(i) != -1) {\n rd -= (1 << i)\n x = dp(x)(i)\n }\n i -= 1\n }\n x\n }\n\n def main(args: Array[String]) {\n\n val n = in.readLine().toInt\n adj = new Array[List[Int]](n)\n t = new Array[Int](n)\n h = new Array[Int](n)\n sz = new Array[Int](n)\n\n (0 until n).foreach { i => adj(i) = Nil}\n\n (1 until n).foreach { i =>\n val Array(u, v) = in.readLine().split(\" +\").map(_.toInt)\n adj(u - 1) = (v - 1) :: adj(u - 1)\n adj(v - 1) = (u - 1) :: adj(v - 1)\n }\n\n val m = in.readLine().toInt\n\n t(0) = -1\n\n dfs(0, -1)\n\n val dp = Array.ofDim[Int](n, LOGN)\n\n (0 until n).foreach { i =>\n dp(i)(0) = t(i)\n var j = 1\n while ((1 << j) < n) {\n dp(i)(j) = -1\n j += 1\n }\n }\n\n var j = 1\n while ((1 << j) < n) {\n (0 until n).foreach { i =>\n if (dp(i)(j - 1) != -1)\n dp(i)(j) = dp(dp(i)(j - 1))(j - 1)\n }\n j += 1\n }\n\n (1 to m).foreach { _ =>\n val Array(uu, vv) = in.readLine().split(\" +\").map(_.toInt)\n\n val u = uu - 1\n val v = vv - 1\n val w = lca(u, v, n, dp)\n val d = h(u) + h(v) - 2 * h(w)\n\n if (u == v) {\n out.println(n)\n } else if (d % 2 == 1) {\n out.println(0)\n } else {\n\n if (w == v) {\n val stu = sz(u) - 1\n val stv = n - sz(goup(u, d - 1, dp)) - 1\n out.println(n - d - stu - stv)\n } else if (w == u) {\n val stu = n - sz(goup(v, d - 1, dp)) - 1\n val stv = sz(v) - 1\n out.println(n - d - stu - stv)\n } else {\n val stu = sz(u) - 1\n val stv = sz(v) - 1\n out.println(n - d - stu - stv)\n }\n }\n }\n\n out.close()\n }\n\n}"}], "src_uid": "89bf97a548fe12921102e77dda63283a"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M, K = ni()\n val A = na(N)\n val D = Array.ofDim[Int](N - 1)\n REP(N - 1) { i =>\n D(i) = A(i + 1) - A(i) - 1\n }\n sort(D)\n val ans = N + D.take(N - K).sum\n out.println(ans)\n }\n\n def sort(a: Array[Int]): Array[Int] = {\n val n = a.length\n REP(n) { i =>\n val j = scala.util.Random.nextInt(n - i) + i\n val tmp = a(i)\n a(i) = a(j)\n a(j) = tmp\n }\n Sorting.stableSort(a)\n a\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, k) = readInts(3)\n val bs = readInts(n).map(_ - 1)\n\n val len = if (n == 1) 1\n else {\n val gaps = bs.sliding(2).map { case Array(l, r) => r - l - 1 }.toArray.sorted\n n + gaps.take(n - k).sum\n }\n\n println(len)\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m, k) = readInts(3)\n val bs = readInts(n).map(_ - 1)\n\n case class Gap(l: Int, r: Int) {\n def len = r - l\n }\n val gaps = (1 until n).map(i => Gap(bs(i - 1), bs(i))).sortBy(_.len)\n\n var len = n\n var count = n\n\n for (gap <- gaps) {\n if (count > k) {\n len += gap.len - 1\n count -= 1\n }\n }\n\n println(len)\n}\n"}], "negative_code": [], "src_uid": "6b2b56a423c247d42493d01e06e4b1d2"} {"source_code": "\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_599_B1 { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n //runTest(Test.sa1)\n //debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading \n val K = readLine.int\n \n for(k <- 1 to K) {\n val n = readLine.int\n val s = readLine.string\n val t = readLine.string\n \n var diffs = List[Int]()\n for (i <- 0 until n) {\n if (s(i) != t(i)) diffs ::= i\n }\n var res = \n if (diffs.length == 2) {\n val i1 = diffs(0)\n val i2 = diffs(1)\n if (s(i1) == s(i2) && t(i1) == t(i2)) {\n \"Yes\"\n } else {\n \"No\"\n }\n } else {\n \"No\"\n }\n \n outLn(res)\n }\n \n// debug(\"n = \" + n)\n \n //---------------------------- parameters reading :end \n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Long) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4\n5\nsouse\nhouhe\n3\ncat\ndog\n2\naa\naz\n3\nabc\nbca\n\"\"\"\n\nval sa2 = \"\"\"\n101\n\"\"\"\n\nval sa3 = \"\"\"\n10100\n\"\"\"\n }\n}\n\n", "positive_code": [{"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\nobject Main extends App {\n\n val k = StdIn.readLine.toInt\n for (_ <- 0 until k) {\n val n = StdIn.readLine.toInt\n val st1 = StdIn.readLine\n val st2 = StdIn.readLine\n\n var diff1 = new ListBuffer[Char]\n var diff2 = new ListBuffer[Char]\n var isDiff = false\n for (\n i <- 0 until n\n if !isDiff\n ) {\n if (st1(i) != st2(i)) {\n if (diff1.length == 2) {\n isDiff = true\n } else {\n diff1 += st1(i)\n diff2 += st2(i)\n }\n }\n }\n\n if (!isDiff) {\n if (\n// (diff1.length == 2 && diff1.intersect(diff2).length == 2) ||\n (diff1.length == 2 && diff1(0) == diff1(1) && diff2(0) == diff2(1)) ||\n (diff1.length == 0)\n ) {\n println(\"Yes\")\n } else {\n println(\"No\")\n }\n\n } else {\n println(\"No\")\n }\n\n }\n\n}"}, {"source_code": "object _1243B1 extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val _, s, t = io.read[String]\n\n val diffs = s.zip(t).collect({case (a, b) if a != b => (a, b)}).toList\n\n val ans = diffs match {\n case Nil => true\n case (a1, b1) :: (a2, b2) :: Nil => a1 == a2 && b1 == b2\n case _ => false\n }\n\n io.write(ans.toEnglish)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}, {"source_code": "object B {\n \n def main(args: Array[String]): Unit = {\n val k = scala.io.StdIn.readInt()\n val result = for (i <- 1 to k) yield test()\n println(result.mkString(\"\\n\"))\n }\n \n def test(): String = {\n val n = scala.io.StdIn.readInt()\n val s1 = scala.io.StdIn.readLine()\n val s2 = scala.io.StdIn.readLine()\n val diff = for (i <- 0 until n; c1 = s1(i); c2 = s2(i) if c1 != c2) yield (c1, c2)\n if (diff.length == 2 && (diff(0) == diff(1))) \"Yes\"\n else \"No\"\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject StringSwap {\n\n def checkAllSwaps(t: Int, c: Int, s1: String, s2: String): String = {\n if (s1.length != c || s2.length != c) {\n \"No\" // mismatched sizes\n } else if (s1 == s2) {\n \"Yes\" // identical\n } else {\n var i1 = 0\n while (i1 < c && s1.charAt(i1) == s2.charAt(i1)) i1 = i1 + 1\n var i2 = i1 + 1\n while (i2 < c && s1.charAt(i2) == s2.charAt(i2)) i2 = i2 + 1\n var i3 = i2 + 1\n while (i3 < c && s1.charAt(i3) == s2.charAt(i3)) i3 = i3 + 1\n if (i3 < c) {\n \"No\" // more than 2 positions different\n } else if (i1 < c && i2 < c) {\n if (s1.charAt(i1) == s1.charAt(i2) && s2.charAt(i1) == s2.charAt(i2)) {\n \"Yes\"\n } else {\n \"No\"\n }\n } else {\n \"No\" // only 1 position different\n }\n }\n }\n\n def main(args: Array[String]) {\n var line = StdIn.readLine()\n if (line != null) {\n val testCount = line.toInt\n line = StdIn.readLine()\n for (testNum <- 1 to testCount) {\n if (line != null) {\n val charCount = line.toInt\n line = StdIn.readLine()\n if (line != null) {\n val str1 = line\n line = StdIn.readLine()\n if (line != null) {\n val str2 = line\n val result = checkAllSwaps(testNum, charCount, str1, str2)\n println(result)\n line = StdIn.readLine\n }\n }\n }\n }\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject Main extends App{\n\n val k = StdIn.readLine.toInt\n for (i <- 0 until k) {\n val n = StdIn.readLine.toInt\n val st1 = StdIn.readLine\n val st2 = StdIn.readLine\n\n val dif = st1.diff(st2)\n if ( dif.length == 2 || dif.length == 0)\n println(\"Yes\")\n else\n println(\"No\")\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main extends App{\n\n val k = StdIn.readLine.toInt\n for (i <- 0 until k) {\n val n = StdIn.readLine.toInt\n val st1 = StdIn.readLine\n val st2 = StdIn.readLine\n\n val dif = st1.diff(st2)\n if ( dif.length == 2 )\n println(\"Yes\")\n else\n println(\"No\")\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject StringSwap {\n\n def checkSingleSwap(s1: StringBuilder, s2: StringBuilder, i: Int, j: Int): Boolean = {\n val c1 = s1.charAt(i)\n val c2 = s2.charAt(j)\n s1.setCharAt(i, c2)\n s2.setCharAt(j, c1)\n val ss1 = s1.mkString\n val ss2 = s2.mkString\n s1.setCharAt(i, c1)\n s2.setCharAt(j, c2)\n //println(s\"check: $ss1, $ss2\")\n ss1 == ss2\n }\n\n def checkAllSwaps(t: Int, c: Int, str1: String, str2: String): String = {\n //println(s\"$t swap: $c, $str1, $str2\")\n if (str1.length == c && str2.length == c) {\n val s1 = new StringBuilder(str1)\n val s2 = new StringBuilder(str2)\n for (i <- 0 until c) {\n for (j <- 0 until c) {\n if (checkSingleSwap(s1, s2, i, j)) {\n return \"Yes\"\n }\n }\n }\n }\n \"No\"\n }\n\n def main(args: Array[String]) {\n var line = StdIn.readLine()\n if (line != null) {\n val testCount = line.toInt\n line = StdIn.readLine()\n for (testNum <- 1 until testCount) {\n if (line != null) {\n val charCount = line.toInt\n line = StdIn.readLine()\n if (line != null) {\n val str1 = line\n line = StdIn.readLine()\n if (line != null) {\n val str2 = line\n val result = checkAllSwaps(testNum, charCount, str1, str2)\n println(result)\n line = StdIn.readLine\n }\n }\n }\n }\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject StringSwap {\n\n def checkAllSwaps(t: Int, c: Int, s1: String, s2: String): String = {\n if (s1.length != c || s2.length != c) {\n \"No\"\n } else if (s1 == s2) {\n \"Yes\"\n } else {\n var i1 = 0\n while (i1 < c && s1.charAt(i1) == s2.charAt(i1)) i1 = i1 + 1\n var i2 = i1 + 1\n while (i2 < c && s1.charAt(i2) == s2.charAt(i2)) i2 = i2 + 1\n if (i1 < c && i2 < c) {\n if (s1.charAt(i1) == s1.charAt(i2) && s2.charAt(i1) == s2.charAt(i2)) {\n \"Yes\"\n } else {\n \"No\"\n }\n } else {\n \"No\"\n }\n }\n }\n\n def main(args: Array[String]) {\n var line = StdIn.readLine()\n if (line != null) {\n val testCount = line.toInt\n line = StdIn.readLine()\n for (testNum <- 1 to testCount) {\n if (line != null) {\n val charCount = line.toInt\n line = StdIn.readLine()\n if (line != null) {\n val str1 = line\n line = StdIn.readLine()\n if (line != null) {\n val str2 = line\n val result = checkAllSwaps(testNum, charCount, str1, str2)\n println(result)\n line = StdIn.readLine\n }\n }\n }\n }\n }\n }\n}\n"}, {"source_code": "object B {\n\n def main(args: Array[String]): Unit = {\n val k = scala.io.StdIn.readInt()\n val result = for (i <- 1 to k) yield test()\n println(result.mkString(\"\\n\"))\n }\n\n def test(): String = {\n val n = scala.io.StdIn.readInt()\n val s1 = scala.io.StdIn.readLine()\n val s2 = scala.io.StdIn.readLine()\n val diff = for (i <- 0 until n; c1 = s1(i); c2 = s2(i) if c1 != c2) yield (c1, c2)\n if (diff.length == 2 && (diff(0) == diff(1) || diff(0) == diff(1).swap)) \"Yes\"\n else \"No\"\n }\n}\n"}], "src_uid": "97fa7e82566e3799e165ce6cbbf1da22"} {"source_code": "object _1733A extends CodeForcesApp {\n override def solve(io: IO) = io.repeat() {\n val n, k = io.nextInt()\n val as = IndexedSeq.fill(n)(io.nextLong())\n val ans = (0 until k).map(i => (i until n by k).map(as).max)\n io.printLine(ans.sum)\n }\n}\n/**************************** [Ignore Template Below] **************************************/\ntrait CodeForcesApp {\n def debug(x: => Any): Unit = if (!sys.props.contains(\"ONLINE_JUDGE\")) println(s\">>> DEBUG: $x\")\n def run(io: IO): Unit = try solve(io) finally io.close()\n def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))\n def solve(io: IO): Any\n}\n// Java I/O wrapper\nimport java.io._\nclass IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {\n def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))\n\n val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))\n\n def nextLine(): String = in.readLine()\n def nextStr(): String = tokens.next()\n def nextInt(): Int = nextStr().toInt\n def nextLong(): Long = nextStr().toLong\n def nextDouble(): Double = nextStr().toDouble\n def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }\n\n def print(xs: Any*): this.type = { out.print(xs.mkString(\" \")); this }\n def printLine(xs: Any*): this.type = { out.println(xs.mkString(\" \")); this }\n def printLines(xs: Any*): this.type = { if (xs.isEmpty) out.println() else xs.foreach(out.println); this }\n\n override def close() = out.close()\n}\n", "positive_code": [{"source_code": "object main {\r\n \r\n def main(args: Array[String]): Unit = {\r\n\r\n var t = io.StdIn.readInt()\r\n\r\n def loopts(ts: Int): Unit = {\r\n if ( ts < t ){\r\n var Array(n, k) = io.StdIn.readLine().split(\" \").map(_.toInt)\r\n var a:Array[Int] = new Array[Int](n)\r\n a = io.StdIn.readLine().split(\" \").map(_.toInt)\r\n \r\n def loopi( i: Int, acc: Long ):Long = {\r\n if ( i < k ){\r\n var Array(mx, mxp) =\r\n {\r\n def loopj(pos: Int, mx: Int, mxp: Int):Array[Int] = {\r\n if ( pos < n ){\r\n if ( mx < a(pos) ){\r\n loopj(pos+k, a(pos), pos)\r\n }\r\n else \r\n loopj( pos+k, mx, mxp )\r\n }\r\n else\r\n Array( mx, mxp )\r\n };loopj( i, 0, i )\r\n }\r\n loopi(i+1, acc+mx)\r\n }\r\n else\r\n acc\r\n }\r\n\r\n println( loopi(0, 0) )\r\n loopts(ts+1)\r\n }\r\n }\r\n\r\n loopts(0)\r\n }\r\n \r\n}"}], "negative_code": [], "src_uid": "f974c33780a933a6076c0559e48b7552"} {"source_code": "object CF_978D {\n\tdef check(b: Array[Int], d: Int) : Int = {\n\t\tvar result = 0\n\t\tfor(i <- 1 to b.length - 1)\n\t\t{\n\t\t\tif(math.abs(b(i) - b(0) - i*d) > 1)\treturn -1\n\t\t\tif(b(i) != b(0) + i*d)\tresult += 1\n\t\t}\n\t\treturn result\n\t}\n\tdef main(args: Array[String]) {\n\t\tval n = readInt()\n\t\tval temp_b = readLine().split(\" \")\n\t\tif( n == 1 )\n\t\t{\n\t\t\tprintln(0)\n\t\t\treturn\n\t\t}\n\t\tval b = for(x <- temp_b)\tyield(x.toInt)\n\t\tvar ans = n + 1\n\t\tfor(i <- -1 to 1; j <- -1 to 1)\n\t\t{\n\t\t\tb(0) += i\n\t\t\tval res = check(b,b(1) + j - b(0))\n\t\t\tif(res != -1)\n\t\t\t\tans = math.min(ans, (if(i == 0) 0 else 1) + res)\n\t\t\tb(0) -= i\n\t\t}\n\n\t\tif(ans > n)\n\t\t\tans = -1\n\t\tprintln(ans)\n\t}\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n\n if (N == 1) {\n out.println(0)\n return\n }\n\n def count(head: Int, last: Int): Option[Int] = {\n val inc = (last - head) / (N - 1)\n var cnt = 0\n REP(N) { i =>\n abs(A(i) - (head + i * inc)) match {\n case 0 =>\n case 1 => cnt +=1\n case _ => return None\n }\n }\n Some(cnt)\n }\n\n val ans = for {\n f <- Seq(-1, 0, 1)\n l <- Seq(-1, 0, 1)\n head = A(0) + f\n last = A(N - 1) + l\n if (last - head) % (N - 1) == 0\n res <- count(head, last)\n } yield res\n\n if (ans.isEmpty) out.println(-1)\n else out.println(ans.min)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Long]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [], "src_uid": "79b0794f81acc1c882649d96b1c7f8da"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val cum = cumSum(A)\n var r = N - 1\n\n var ans = 0L\n REP(N) { l =>\n while(l < r && cum(l + 1) > cum(N) - cum(r)) r-= 1\n if (l < r && cum(l + 1) == cum(N) - cum(r)) ans = max(ans, cum(l + 1))\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object CF498C extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n val n = in.nextInt\n val array = new Array[Int](n).map(_ => in.nextInt)\n\n var a = 0\n var c = 0\n\n var leftSum = 0: Long\n var rightSum = 0: Long\n\n var max = 0: Long\n\n while (a+c <= n) {\n if (leftSum == rightSum)\n max = leftSum\n\n if (leftSum < rightSum) {\n a += 1\n if (a+c <= n)\n leftSum += array(a-1)\n }\n else {\n c += 1\n if (a + c <= n)\n rightSum += array(array.length - c)\n }\n }\n\n out.println(max)\n }\n\n solve\n out.flush\n out.close\n}"}], "negative_code": [{"source_code": "object CF498C extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n val n = in.nextInt\n val array = new Array[Int](n).map(_ => in.nextInt)\n\n var a = 0\n var c = 0\n\n var leftSum = 0\n var rightSum = 0\n\n var max = 0\n\n while (a+c <= n) {\n if (leftSum == rightSum)\n max = leftSum\n\n if (leftSum < rightSum) {\n a += 1\n if (a+c <= n)\n leftSum += array(a-1)\n }\n else {\n c += 1\n if (a + c <= n)\n rightSum += array(array.length - c)\n }\n }\n\n out.println(max)\n }\n\n solve\n out.flush\n out.close\n}"}], "src_uid": "f2fc865a44b39179261a7311adf48390"} {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n @annotation.tailrec\n def gcd(a: Int, b: Int): Int =\n if (b == 0) a else gcd(b, a % b)\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n @annotation.tailrec\n def go(an: Seq[Int], bn: List[Int], c: Int): Seq[Int] = an match {\n case Seq() => bn\n case _ =>\n val (ak, bk, d) = an.foldLeft((List.empty[Int], List.empty[Int], 0)) {\n case ((ak, bk, d), a) =>\n val g = gcd(c, a)\n\n if (g > d) (bk ::: ak, a :: Nil, g)\n else if (g == d) (ak, a :: bk, d)\n else (a :: ak, bk, d)\n }\n\n go(ak, bn ::: bk, d)\n }\n\n val bn = go(an, List.empty[Int], 0)\n\n println(bn.mkString(\" \"))\n }\n}\n", "positive_code": [{"source_code": "//package codeforces.contests._1407\n\nobject BigVova {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n\n val n = io.StdIn.readInt()\n val seq = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n @scala.annotation.tailrec\n def gcd(a: Int, b: Int): Int = {\n if (b == 0) a else gcd(b, a % b)\n }\n\n val maximumIdx = (0 until n).maxBy(seq)\n\n val done: collection.mutable.Set[Int] = collection.mutable.Set(maximumIdx)\n\n @scala.annotation.tailrec\n def loop(accGcd: Int = seq(maximumIdx), accRes: List[Int] = seq(maximumIdx) :: Nil): List[Int] = {\n if (done.size == n) accRes.reverse\n else {\n val toRemoveIdx = (0 until n).filter(!done(_)).maxBy(i => gcd(seq(i), accGcd))\n done += toRemoveIdx\n loop(gcd(seq(toRemoveIdx), accGcd), seq(toRemoveIdx) :: accRes)\n }\n }\n\n println(loop().mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n def gcd(a: Int, b: Int): Int =\n if (b == 0) a else gcd(b, a % b)\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt).sorted(Ordering.Int.reverse)\n\n val bn = Array.ofDim[Int](n)\n bn(0) = an.head\n\n @annotation.tailrec\n def go(i: Int, c: Int): Unit =\n if (i < n) {\n\n val (j, d) = ((i + 1) until n).foldLeft(i -> gcd(c, an(i))) {\n case ((j, d), k) =>\n val p = gcd(c, an(k))\n\n if (p > d) k -> p\n else j -> d\n }\n\n bn(i) = an(j)\n an(j) = an(i)\n\n go(i + 1, d)\n }\n\n go(1, an.head)\n\n println(bn.mkString(\" \"))\n }\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n @annotation.tailrec\n def gcd(a: Int, b: Int): Int =\n if (b == 0) a else gcd(b, a % b)\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n val bn = Array.ofDim[Int](n)\n\n val counts = Array.fill(an.max + 1)(0)\n an.foreach(a => counts(a) += 1)\n\n @annotation.tailrec\n def go(i: Int, c: Int): IndexedSeq[Int] =\n if (i == n) bn\n else {\n val (b, d) = counts.zipWithIndex.foldLeft(0 -> 0) {\n case (state, (0, a)) => state\n case (state @ (_, d), (_, a)) =>\n val g = gcd(c, a)\n\n if (g >= d) a -> g else state\n }\n\n bn(i) = b\n counts(b) -= 1\n\n go(i + 1, d)\n }\n\n go(0, an.max)\n\n println(bn.mkString(\" \"))\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1407\n\nobject BigVova {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n\n val n = io.StdIn.readInt()\n val seq = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n @scala.annotation.tailrec\n def gcd(a: Int, b: Int): Int = {\n if (b == 0) a else gcd(b, a % b)\n }\n\n val maximum = seq.max\n\n @scala.annotation.tailrec\n def loop(elements: Set[Int] = seq.toSet-maximum, accRes: List[Int] = maximum :: Nil): List[Int] = {\n if (elements.isEmpty) accRes.reverse\n else {\n val accGcd = accRes.head\n val toRemove = elements.maxBy(gcd(_, accGcd))\n loop(elements - toRemove, toRemove :: accRes)\n }\n }\n\n println(loop().mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "//package codeforces.contests._1407\n\nobject BigVova {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n\n val n = io.StdIn.readInt()\n val seq = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n @scala.annotation.tailrec\n def gcd(a: Int, b: Int): Int = {\n if (b == 0) a else gcd(b, a % b)\n }\n\n val maximumIdx = (0 until n).maxBy(seq)\n\n val done: collection.mutable.Set[Int] = collection.mutable.Set(maximumIdx)\n\n @scala.annotation.tailrec\n def loop(accRes: List[Int] = seq(maximumIdx) :: Nil): List[Int] = {\n if (done.size == n) accRes.reverse\n else {\n val accGcd = accRes.head\n val toRemoveIdx = (0 until n).filter(!done(_)).maxBy(i => gcd(seq(i), accGcd))\n done += toRemoveIdx\n loop(seq(toRemoveIdx) :: accRes)\n }\n }\n\n println(loop().mkString(\" \"))\n }\n }\n}\n"}], "src_uid": "bdd1974e46f99eff3d03ed4174158dd9"} {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val a: Array[Long] = in.next().split(' ').map(_.toLong).sorted\n val x = a.sum / (n - 1) + (if (a.sum % (n - 1) > 0) 1 else 0)\n println(Math.max(x, a.max))\n}\n", "positive_code": [{"source_code": "import scala.collection._\n\nobject A extends App {\n \n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val n = readString.toInt\n val as = readLongs(n).sorted\n \n def can(m: Long): Boolean = {\n var i = 0\n var games = 0L\n while (i < as.size && games < m) {\n games += (m - as(i))\n i += 1\n }\n games >= m\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) >>> 1\n if (can(mid)) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n println(binSearch(as.max, as.sum))\n}"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\nimport scala.io.StdIn._\n\nobject Main {\n val scanner = new Scanner(System.in)\n import scanner._\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val v = readLine().split(\" \").map(_.toLong)\n val totSum: Long = v.sum\n val ans: Long = (totSum/(n-1) + (if(totSum%(n-1) == 0) 0 else 1))\n println(ans.max(v.max))\n }\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\nimport scala.io.StdIn._\n\nobject Main {\n val scanner = new Scanner(System.in)\n import scanner._\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val v = readLine().split(\" \").map(_.toInt)\n val totSum = v.sum\n val ans = (totSum/(n-1) + (if(totSum%(n-1) == 0) 0 else 1))\n println(ans)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\nimport scala.io.StdIn._\n\nobject Main {\n val scanner = new Scanner(System.in)\n import scanner._\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val v = readLine().split(\" \").map(_.toInt)\n val totSum = v.sum\n val ans = (totSum/(n-1) + (if(totSum%(n-1) == 0) 0 else 1))\n println(ans.max(v.max))\n }\n}\n"}], "src_uid": "09f5623c3717c9d360334500b198d8e0"} {"source_code": "object C732 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val in = readLongs(3).sorted.reverse\n if(in.max - in.min <= 1) {\n println(\"0\")\n } else {\n for(i <- in.indices)\n if(in(i) != in.max)\n in(i) += 1\n println(in.map(a => in.max-a).sum)\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val visits = in.next().split(' ').map(_.toLong)\n val max = visits.max\n val maxCount = visits.count(_ == max)\n if (maxCount == 3)\n println(0)\n else if (maxCount == 2)\n println(max - visits.min - 1)\n else\n println(max + max - visits.filter(_ != max).sum - 2)\n\n}\n"}, {"source_code": "object source{\n def main(args: Array[String]): Unit = {\n val in = io.Source.stdin.getLines()\n val visits = in.next().split(' ').map(_.toLong)\n val max = visits.max\n val maxCnt = visits.count(_ == max)\n if (maxCnt == 3) println(0)\n else if (maxCnt == 2)\n println(max - visits.min - 1)\n else\n println(max + max - visits.filter(_ != max).sum - 2)\n }\n}\n\n"}, {"source_code": "import java.io._\nimport scala.io.Source\n\nimport scala.annotation.tailrec\n\nobject ProblemC {\n def main(args: Array[String]): Unit = processStdInOut()\n\n def processStdInOut(): Unit = {\n val src = Source.fromInputStream(System.in)\n processFromSource(src)\n }\n\n def processFromSource(src: Source): Unit = {\n try {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out));\n try {\n val lines = src.getLines()\n processLines(lines, bw)\n } finally {\n bw.flush()\n }\n } finally {\n src.close();\n }\n }\n\n // Standard code above, custom code below\n\n def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {\n\n val line = lines.next()\n val strings = line.split(\" \")\n val b = strings(0).toLong\n val d = strings(1).toLong\n val s = strings(2).toLong\n val soln = solve(b, d, s)\n bw.write(soln.toString)\n bw.newLine()\n }\n\n def solve(b: Long, d: Long, s: Long): Long = {\n // rebase time, so that at least as many of first meal as any other, and call that breakfast...\n if (d > b && d >= s) solve(d, s, b) // Measure from before dinner on the first day\n else if (s > d && s >= b) solve(s, b, d) // Measure from before supper on the first day\n else math.max(b - d - 1, 0) + math.max(b - s - 1, 0)\n // don't count last dinner and/or supper as missed, but beware that b, d and s could be equal\n }\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport scala.io.Source\n\nimport scala.annotation.tailrec\n\nobject ProblemC {\n def main(args: Array[String]): Unit = processStdInOut()\n\n def processStdInOut(): Unit = {\n val src = Source.fromInputStream(System.in)\n processFromSource(src)\n }\n\n def processFromSource(src: Source): Unit = {\n try {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out));\n try {\n val lines = src.getLines()\n processLines(lines, bw)\n } finally {\n bw.flush()\n }\n } finally {\n src.close();\n }\n }\n\n // Standard code above, custom code below\n\n def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {\n\n val line = lines.next()\n val strings = line.split(\" \")\n val b = strings(0).toLong\n val d = strings(1).toLong\n val s = strings(2).toLong\n val soln = solve(b, s, d)\n bw.write(soln.toString)\n bw.newLine()\n }\n\n def solve(b: Long, d: Long, s: Long): Long = {\n // rebase time, so that at least as many of first meal as any other, and call that breakfast...\n if (d > b && d >= s) solve(d, s, b) // Measure from before dinner on the first day\n else if (s > d && s > b) solve(s, b, d) // Measure from before supper on the first day\n else {\n if (s == b) b - d // Stay for full last day\n else math.max(b - d - 1, 0) + b - s - 1\n // don't count last dinner and supper as missed, but beware that d could equal b\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport scala.io.Source\n\nimport scala.annotation.tailrec\n\nobject ProblemC {\n def main(args: Array[String]): Unit = processStdInOut()\n\n def processStdInOut(): Unit = {\n val src = Source.fromInputStream(System.in)\n processFromSource(src)\n }\n\n def processFromSource(src: Source): Unit = {\n try {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out));\n try {\n val lines = src.getLines()\n processLines(lines, bw)\n } finally {\n bw.flush()\n }\n } finally {\n src.close();\n }\n }\n\n // Standard code above, custom code below\n\n def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {\n\n val line = lines.next()\n val strings = line.split(\" \")\n val b = strings(0).toLong\n val d = strings(1).toLong\n val s = strings(2).toLong\n val soln = solve(b, d, s)\n bw.write(soln.toString)\n bw.newLine()\n }\n\n def solve(b: Long, d: Long, s: Long): Long = {\n // rebase time, so that at least as many of first meal as any other, and call that breakfast...\n if (d > b && d >= s) solve(d, s, b) // Measure from before dinner on the first day\n else if (s > d && s > b) solve(s, b, d) // Measure from before supper on the first day\n else {\n if (s == b) b - d // Stay for full last day\n else math.max(b - d - 1, 0) + b - s - 1\n // don't count last dinner and supper as missed, but beware that d could equal b\n }\n }\n}\n"}, {"source_code": "object C732 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val in = readLongs(3).sorted.reverse\n in(0) -= in(2) + 1\n in(1) -= in(2) + 1\n in(2) = 0\n val res = math.max(0, in(0) - (if(in(1) > 0) in(0)-in(1) else 0))\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object C732 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val in = readLongs(3)\n val res = math.max(0, in.max - in.min - 1)\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object C732 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n var in = readLongs(3).sorted\n in(2) -= in(0)\n in(1) -= in(0)\n val res = math.max(0, 2*in(2) - in(1) - in(0) - (if(in(1) == 0)2 else 1))\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "b34846d90dc011f2ef37a8256202528a"} {"source_code": "object _1722A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = {\n val timur = \"Timur\".sorted\n\n io.repeat {\n val (_, s) = io.read[(Int, String)]\n val ans = s.sorted == timur\n io.writeLine(ans.toEnglish)\n }\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def toEnglish = if (x) \"YES\" else \"NO\"\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Utils]****************************************/\nobject Utils {\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int])(f)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n", "positive_code": [{"source_code": "object _1722A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = {\n val timur = \"Timur\".sorted\n\n io.repeat {\n val (n, s) = io.read[(Int, String)]\n val ans = s.sorted == timur\n io.writeLine(ans.toEnglish)\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n val charToInt: Char => Int = Character.getNumericValue\n val intToChar: Int => Char = Character.forDigit(_, 10)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B =\n t.foldLeft(n.zero)({case (c, x) => n.plus(c, f(x))})\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int])(f)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}, {"source_code": "object _1722A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = {\n val timur = \"Timur\".sorted\n\n io.repeat {\n val (n, s) = io.read[(Int, String)]\n val ans = s.sorted == timur\n io.writeLine(ans.toEnglish.toUpperCase)\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n val charToInt: Char => Int = Character.getNumericValue\n val intToChar: Int => Char = Character.forDigit(_, 10)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B =\n t.foldLeft(n.zero)({case (c, x) => n.plus(c, f(x))})\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int])(f)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}, {"source_code": "object _1722A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = {\n val timur = \"Timur\".sorted\n\n io.repeat {\n val (n, s) = io.read[(Int, String)]\n val ans = n == timur.length && s.sorted == timur\n io.writeLine(ans.toEnglish.toUpperCase)\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n val charToInt: Char => Int = Character.getNumericValue\n val intToChar: Int => Char = Character.forDigit(_, 10)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B =\n t.foldLeft(n.zero)({case (c, x) => n.plus(c, f(x))})\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int])(f)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}, {"source_code": "object _1722A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = {\n val timur = \"Timur\".sorted\n\n io.repeat {\n val (n, s) = io.read[(Int, String)]\n val ans = n == timur.length && s.sorted == timur\n io.write(ans.toEnglish.toUpperCase)\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n val charToInt: Char => Int = Character.getNumericValue\n val intToChar: Int => Char = Character.forDigit(_, 10)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}, {"source_code": "object _1722A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = {\n val timur = \"Timur\".sorted\n\n io.repeat {\n val (n, s) = io.read[(Int, String)]\n val ans = n == timur.length && s.sorted == timur\n io.write(ans.toEnglish.toUpperCase)\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n val charToInt: Char => Int = Character.getNumericValue\n val intToChar: Int => Char = Character.forDigit(_, 10)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "6c137a74b36dede61037cb3b05167329"} {"source_code": "\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs, ys = Array.ofDim[Double](n)\n\n for (i <- 0 until n) {\n val Array(a, b) = readLongs(2)\n xs(i) = a.toDouble\n ys(i) = b.toDouble\n }\n\n def sqr(x: Double) = x * x\n\n def dist(x0: Double, y0: Double, x1: Double, y1: Double, x2: Double, y2: Double): Double = {\n Math.abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1) /\n Math.sqrt(sqr(y2 - y1) + sqr(x2 - x1))\n }\n\n def dist(x1: Double, y1: Double, x2: Double, y2: Double) = {\n Math.sqrt(sqr(y2 - y1) + sqr(x2 - x1))\n }\n\n def pDistance(x: Double, y: Double, x1: Double, y1: Double, x2: Double, y2: Double) = {\n\n var A = x - x1;\n var B = y - y1;\n var C = x2 - x1;\n var D = y2 - y1;\n\n var dot = A * C + B * D;\n var len_sq = C * C + D * D;\n var param = -1d;\n if (len_sq != 0) //in case of 0 length line\n param = dot / len_sq;\n\n var xx, yy = 0d;\n\n if (param < 0) {\n xx = x1;\n yy = y1;\n }\n else if (param > 1) {\n xx = x2;\n yy = y2;\n }\n else {\n xx = x1 + param * C;\n yy = y1 + param * D;\n }\n\n var dx = x - xx;\n var dy = y - yy;\n Math.sqrt(dx * dx + dy * dy);\n }\n\n var min = Double.MaxValue\n\n for (i <- 0 until n) {\n val d = pDistance(\n xs((i + 1) % n), ys((i + 1) % n),\n xs(i), ys(i),\n xs((i + 2) % n), ys((i + 2) % n))\n //val d2 = dist(xs(i), ys(i), xs((i + 1) % n), ys((i + 1) % n))\n //val d3 = dist(xs((i + 2) % n), ys((i + 2) % n), xs((i + 1) % n), ys((i + 1) % n))\n //val d = d1 min d2 min d3\n if (d < min) min = d\n }\n\n println(min / 2)\n}\n", "positive_code": [{"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n\n val Array(n) = readInts(1)\n val xs, ys = Array.ofDim[Double](n)\n\n for (i <- 0 until n) {\n val Array(a, b) = readLongs(2)\n xs(i) = a.toDouble\n ys(i) = b.toDouble\n }\n\n def sqr(x: Double) = x * x\n\n def distance(x1: Double, y1: Double, x2: Double, y2: Double): Double =\n Math.sqrt(sqr(y2 - y1) + sqr(x2 - x1))\n\n def distPointToLineSegment(x: Double, y: Double, x1: Double, y1: Double, x2: Double, y2: Double): Double = {\n\n val a = x - x1\n val b = y - y1\n val c = x2 - x1\n val d = y2 - y1\n\n val dot = a * c + b * d\n val lengthSquared = c * c + d * d\n val param = if (lengthSquared == 0) -1 else dot / lengthSquared\n\n if (param < 0) distance(x, y, x1, y1)\n else if (param > 1) distance(x, y, x2, y2)\n else distance(x, y, x1 + param * c, y1 + param * d)\n }\n\n var min = Double.MaxValue\n\n for (i <- 0 until n) {\n val d = distPointToLineSegment(\n xs((i + 1) % n), ys((i + 1) % n),\n xs(i), ys(i),\n xs((i + 2) % n), ys((i + 2) % n))\n if (d < min) min = d\n }\n\n println(min / 2)\n}\n"}], "negative_code": [{"source_code": "\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs, ys = Array.ofDim[Double](n)\n\n for (i <- 0 until n) {\n val Array(a, b) = readLongs(2)\n xs(i) = a.toDouble\n ys(i) = b.toDouble\n }\n\n def sqr(x: Double) = x * x\n\n def dist(x0: Double, y0: Double, x1: Double, y1: Double, x2: Double, y2: Double): Double = {\n Math.abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1) /\n Math.sqrt(sqr(y2 - y1) + sqr(x2 - x1))\n }\n\n def dist(x1: Double, y1: Double, x2: Double, y2: Double) = {\n Math.sqrt(sqr(y2 - y1) + sqr(x2 - x1))\n }\n\n var min = Double.MaxValue\n\n for (i <- 0 until n) {\n val d1 = dist(\n xs((i + 1) % n), ys((i + 1) % n),\n xs(i), ys(i),\n xs((i + 2) % n), ys((i + 2) % n))\n val d2 = dist(xs(i), ys(i), xs((i + 1) % n), ys((i + 1) % n))\n val d3 = dist(xs((i + 2) % n), ys((i + 2) % n), xs((i + 1) % n), ys((i + 1) % n))\n val d = d1 min d2 min d3\n if (d < min) min = d\n }\n\n println(min / 2)\n}\n"}, {"source_code": "\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs, ys = Array.ofDim[Double](n)\n\n for (i <- 0 until n) {\n val Array(a, b) = readLongs(2)\n xs(i) = a\n ys(i) = b\n }\n\n def sqr(x: Double) = x * x\n\n def dist(x0: Double, y0: Double, x1: Double, y1: Double, x2: Double, y2: Double): Double = {\n Math.abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1) /\n Math.sqrt(sqr(y2 - y1) + sqr(x2 - x1))\n }\n\n var min = Double.MaxValue\n\n for (i <- 0 until n) {\n val d = dist(\n xs((i + 1) % n), ys((i + 1) % n),\n xs(i), ys(i),\n xs((i + 2) % n), ys((i + 2) % n))\n if (d < min) min = d\n }\n\n println(min / 2)\n}\n"}, {"source_code": "\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs, ys = Array.ofDim[Double](n)\n\n for (i <- 0 until n) {\n val Array(a, b) = readLongs(2)\n xs(i) = a\n ys(i) = b\n }\n\n def sqr(x: Double) = x * x\n\n def dist(x0: Double, y0: Double, x1: Double, y1: Double, x2: Double, y2: Double): Double = {\n Math.abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1) /\n Math.sqrt(sqr(y2 - y1) + sqr(x2 - x1))\n }\n\n def dist(x1: Double, y1: Double, x2: Double, y2: Double) = {\n Math.sqrt(sqr(y2 - y1) + sqr(x2 - x1))\n }\n\n var min = Double.MaxValue\n\n for (i <- 0 to n) {\n val d1 = dist(\n xs((i + 1) % n), ys((i + 1) % n),\n xs(i % n), ys(i % n),\n xs((i + 2) % n), ys((i + 2) % n))\n val d2 = dist(xs(i % n), ys(i % n), xs((i + 1) % n), ys((i + 1) % n))\n val d3 = dist(xs((i + 2) % n), ys((i + 2) % n), xs((i + 1) % n), ys((i + 1) % n))\n val d = d1 min d2 min d3\n if (d < min) min = d\n }\n\n println(min / 2)\n}\n"}], "src_uid": "495488223483401ff12ae9c456b4e5fe"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val min = data.min\n val max = data.foldLeft((0l, 0l, 0l, -1)) {\n case ((m, soFar, first, -1), el) if el == min => (0, 0, first, 0)\n case ((m, soFar, first, -1), el) => (0, 0, first + 1, -1)\n case ((m, soFar, first, _), el) if el == min => (Math.max(m, soFar), 0, first, 0)\n case ((m, soFar, first, _), el) => (Math.max(m, soFar + 1), soFar + 1, first, 0)\n }\n val maxValue = Math.max(max._1, max._3 + max._2)\n println(min.toLong * data.length + maxValue)\n}", "positive_code": [{"source_code": "import java.util.Scanner\nimport scala.math._\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n def next = scanner.next.toInt\n\n println(compute(0.until(next).map(_ => next)))\n }\n\n // r: a==[], many mins\n def compute(as: IndexedSeq[Int]) = {\n assert(as.size > 0)\n\n val minIndex = findMin(as)\n val maxBefore = countConsequentGreater(as, minIndex)\n maxBefore + as(minIndex).toLong * as.size\n }\n\n def findMin(as: IndexedSeq[Int]): Int = {\n var result = 0\n for (i <- 1 until as.size) {\n if (as(i) < as(result))\n result = i\n }\n result\n }\n\n def countConsequentGreater(as: IndexedSeq[Int], minIndex: Int) = {\n val n = as.size\n var maxBefore = 0\n var curBefore = 0\n\n for (i <- 0 until n) {\n val j = (minIndex - i + n) % n\n if (as(j) > as(minIndex))\n curBefore += 1\n else\n curBefore = 0\n maxBefore = max(maxBefore, curBefore)\n }\n\n maxBefore\n }\n}\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n val min = as.min.toLong\n \n var start = -1\n var end = -1\n var maxLen = 0\n for (i <- as.indices) {\n if (as(i) > min) {\n if (start == -1) start = i\n if (i - start + 1 > maxLen) maxLen = i - start + 1\n } else {\n start = -1\n }\n }\n \n var i = 0\n while (i < n && as(i) > min) i += 1\n var j = 0\n while (j < n && as(n - j - 1) > min) j += 1\n if (i + j > maxLen) maxLen = i + j\n\n println(min * n + maxLen)\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n\n var jar = new Array[Int](n+1)\n for(i <- 1 to n)\n jar(i) = sc.nextInt()\n\n // statement\n var ans = 0L\n\n\n val max = jar.max\n jar(0) = Int.MaxValue\n val min = jar.min\n\n // func\n def checkMinPoint(cnt: Int): List[Int] = {\n cnt > n match{\n case true => Nil\n case false =>\n if(jar(cnt) == min)\n cnt :: checkMinPoint(cnt+1)\n else\n checkMinPoint(cnt+1)\n }\n }\n\n val minlist = checkMinPoint(1)\n\n // func\n def maxDif(list: List[Int]): Int = {\n list match{\n case _ :: Nil | Nil => 0\n case x :: y :: l2 => Math.max(y-x, maxDif(y :: l2))\n }\n }\n\n\n val tmpmax = maxDif(minlist) - 1\n val side = (n - minlist.last) + minlist(0) - 1\n val bonus = Math.max(side, tmpmax)\n\n if(min == max)\n println((n.toLong * jar(1)))\n else{\n println(min * n.toLong + bonus)\n }\n }\n\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by hsleep on 2016. 1. 6..\n */\nobject BSolution extends App {\n val numOfJar = StdIn.readLine().toInt\n val listOfJar = StdIn.readLine().split(' ').map(_.toInt)\n\n val minLiter = listOfJar.min.toLong\n val indexOfEmpty = for {\n i <- 0 until numOfJar\n if listOfJar(i) == minLiter\n } yield i\n\n val maxDistance = indexOfEmpty.length match {\n case 1 =>\n numOfJar - 1\n case n =>\n val indexOfEmpty2 = indexOfEmpty.tail ++ Seq(numOfJar + indexOfEmpty.head)\n\n indexOfEmpty2.zip(indexOfEmpty).map { case (end, start) =>\n end - start - 1\n }.max\n }\n\n val output = minLiter * numOfJar + maxDistance\n println(output)\n}"}, {"source_code": "//package c610\n\n/**\n * Created by user on 04.01.16.\n */\nobject B {\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val colors = io.StdIn.readLine().split(\" \").map(BigInt(_))\n\n val min = colors.min\n\n println(MaxLenght(n, colors))\n }\n\n def MaxLenght(n: Int, colors: Array[BigInt]): BigInt = {\n val minColor = colors.min\n\n\n var leftIndex = colors.lastIndexOf(minColor)\n val result = colors.zipWithIndex.filter {\n case (color, index) =>\n color == minColor\n } map {\n case (color, currentIndex) =>\n var diff = 0\n if (leftIndex > currentIndex) {\n diff = n + currentIndex - leftIndex - 1\n } else {\n if (currentIndex == leftIndex) {\n diff = n - 1\n } else {\n diff = currentIndex - leftIndex - 1\n }\n }\n// println(currentIndex + \" \" + color + \" \" + \" \" + diff + \" \" + leftIndex)\n leftIndex = currentIndex\n minColor * n + diff\n } max\n\n return result\n\n// val maxLength = colors.zipWithIndex.map {\n// case (currentColor, currentIndex) =>\n// val nextMinColorIndex = upperBound(currentIndex, minColorsIndex)\n// var diff = 0\n// if (nextMinColorIndex < currentIndex) {\n// diff = n - currentIndex + nextMinColorIndex\n// } else {\n// diff = nextMinColorIndex - currentIndex\n// }\n// val res = colors(nextMinColorIndex) * n + diff\n// res\n// }.max\n//\n// maxLength\n }\n\n def upperBound(key: Int, xs: Array[Int]): Int = {\n val isHere = xs.find(_==key)\n if (isHere.isDefined) return key\n\n var len = xs.length\n var first = 0\n while (len > 0) {\n val half = len >>> 1\n val middle = first + half\n if (key < xs(middle)) {\n len = half\n } else {\n first = middle + 1\n len = len - half - 1\n }\n }\n if (first < xs.length)\n xs(first)\n else\n xs(0)\n }\n\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\n/**\n * Created by hsleep on 2016. 1. 6..\n */\nobject BSolution extends App {\n val numOfJar = StdIn.readLine().toInt\n val listOfJar = StdIn.readLine().split(' ').map(_.toInt)\n\n val minLiter = listOfJar.min\n val indexOfEmpty = for {\n i <- 0 until numOfJar\n if listOfJar(i) == minLiter\n } yield i\n\n val maxDistance = indexOfEmpty.length match {\n case 1 =>\n numOfJar - 1\n case n =>\n val indexOfEmpty2 = indexOfEmpty.tail ++ Seq(numOfJar - indexOfEmpty.head)\n\n indexOfEmpty2.zip(indexOfEmpty).map { case (start, end) =>\n start - end - 1\n }.max\n }\n\n val output = minLiter * numOfJar + maxDistance\n println(output)\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val min = data.min\n val max = data.foldLeft((0, 0, 0, -1)) {\n case ((m, soFar, first, -1), el) if el == min => (0, 0, first, 0)\n case ((m, soFar, first, -1), el) => (0, 0, first + 1, -1)\n case ((m, soFar, first, _), el) if el == min => (Math.max(m, soFar), 0, first, 0)\n case ((m, soFar, first, _), el) => (Math.max(m, soFar + 1), soFar + 1, first, 0)\n }\n val maxValue = Math.max(max._1, max._3 + max._2)\n println(min * data.length + maxValue)\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val min = data.min\n val max = data.foldLeft((0l, 0l, 0l, -1)) {\n case ((m, soFar, first, -1), el) if el == min => (0, 0, first, 0)\n case ((m, soFar, first, -1), el) => (0, 0, first + 1, -1)\n case ((m, soFar, first, _), el) if el == min => (Math.max(m, soFar), 0, first, 0)\n case ((m, soFar, first, _), el) => (Math.max(m, soFar + 1), soFar + 1, first, 0)\n }\n val maxValue = Math.max(max._1, max._3 + max._2)\n println(min * data.length + maxValue)\n}"}, {"source_code": "//package c610\n\n/**\n * Created by user on 04.01.16.\n */\nobject B {\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val colors = io.StdIn.readLine().split(\" \").map(BigInt(_))\n\n val min = colors.min\n\n println(MaxLenght(n, colors))\n }\n\n def MaxLenght(n: Int, colors: Array[BigInt]): BigInt = {\n val minColor = colors.min\n\n\n var leftIndex = colors.lastIndexOf(minColor)\n val result = colors.zipWithIndex.filter {\n case (color, index) =>\n color == minColor\n } map {\n case (color, currentIndex) =>\n var diff = 0\n if (leftIndex > currentIndex) {\n diff = n + currentIndex - leftIndex - 1\n } else {\n diff = currentIndex - leftIndex - 1\n }\n// println(currentIndex + \" \" + color + \" \" + \" \" + diff + \" \" + leftIndex)\n leftIndex = currentIndex\n minColor * n + diff\n } max\n\n return result\n\n// val maxLength = colors.zipWithIndex.map {\n// case (currentColor, currentIndex) =>\n// val nextMinColorIndex = upperBound(currentIndex, minColorsIndex)\n// var diff = 0\n// if (nextMinColorIndex < currentIndex) {\n// diff = n - currentIndex + nextMinColorIndex\n// } else {\n// diff = nextMinColorIndex - currentIndex\n// }\n// val res = colors(nextMinColorIndex) * n + diff\n// res\n// }.max\n//\n// maxLength\n }\n\n def upperBound(key: Int, xs: Array[Int]): Int = {\n val isHere = xs.find(_==key)\n if (isHere.isDefined) return key\n\n var len = xs.length\n var first = 0\n while (len > 0) {\n val half = len >>> 1\n val middle = first + half\n if (key < xs(middle)) {\n len = half\n } else {\n first = middle + 1\n len = len - half - 1\n }\n }\n if (first < xs.length)\n xs(first)\n else\n xs(0)\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.math._\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n def next = scanner.next.toInt\n\n println(compute(0.until(next).map(_ => next)))\n }\n\n // r: a==[], many mins\n def compute(as: IndexedSeq[Int]) = {\n assert(as.size > 0)\n\n val minIndex = findMin(as)\n val maxBefore = countConsequentGreater(as, minIndex)\n maxBefore + as(minIndex) * as.size\n }\n\n def findMin(as: IndexedSeq[Int]): Int = {\n var result = 0\n for (i <- 1 until as.size) {\n if (as(i) < as(result))\n result = i\n }\n result\n }\n\n def countConsequentGreater(as: IndexedSeq[Int], minIndex: Int) = {\n val n = as.size\n var maxBefore = 0\n var curBefore = 0\n\n for (i <- 0 until n) {\n val j = (minIndex - i + n) % n\n if (as(j) > as(minIndex))\n curBefore += 1\n else\n curBefore = 0\n maxBefore = max(maxBefore, curBefore)\n }\n\n maxBefore\n }\n}\n"}], "src_uid": "e2db09803d87362c67763ef71e8b7f47"} {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject Codeforces1005D {\n\n def getMaximumDivisibleBy3Numbers(digits: Seq[Int]): Int = {\n var previousNumbers = new ArrayBuffer[Int]\n var totalNumber = 0\n for (digit <- digits) {\n var currentReminder = digit % 3\n\n var index = previousNumbers.length - 1\n var found = false\n if (currentReminder == 0) {\n found = true\n }\n while (!found && index >= 0) {\n currentReminder = (currentReminder + previousNumbers(index)) % 3\n if (currentReminder == 0) found = true\n index -= 1\n }\n if (found) {\n totalNumber += 1\n previousNumbers = new ArrayBuffer[Int]\n } else {\n previousNumbers.append(digit)\n }\n }\n totalNumber\n }\n\n def main(args: Array[String]): Unit = {\n val digits = StdIn.readLine().map(_.toInt)\n val maximumDivisibleBy3Numbers = getMaximumDivisibleBy3Numbers(digits)\n println(maximumDivisibleBy3Numbers)\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S = ns().map(a => (a - '0') % 3)\n val s = Array.ofDim[Boolean](3)\n var ans = 0\n import java.util\n\n def found(): Unit = {\n ans += 1\n util.Arrays.fill(s, false)\n }\n\n REP(S.length) { i =>\n S(i) match {\n case 0 => found()\n\n case 1 =>\n if (s(2)) {\n found()\n } else {\n s(2) = s(1)\n s(1) = true\n }\n\n case 2 =>\n if (s(1)) {\n found()\n } else {\n s(1) = s(2)\n s(2) = true\n }\n }\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val A = ns().toCharArray.map(a => (a - '0') % 3)\n val N = A.length\n\n val last = Array.fill[Int](2, 3)(-1)\n val dp = Array.ofDim[Int](N + 1)\n\n REP(N) { i =>\n val x = i % 2\n// debug(s\"$i ${dp.mkString}, ${last(x).mkString(\",\")}\")\n\n val m = A(i)\n\n // まえの状態から遷移\n REP(3) { j =>\n last(x^1)((j + m) % 3) = last(x)(j)\n }\n // mの状態の最短を更新\n last(x^1)(m) = i // 参照するのは1歩手前のDPの状態\n\n if (m == 0) {\n dp(i + 1) = dp(i) + 1\n } else {\n // 3をつくらない場合の個数\n dp(i + 1) = dp(i)\n\n if (last(x)(3 - m) != -1) {\n dp(i + 1) = max(dp(i + 1), dp(last(x)(3 - m)) + 1)\n }\n }\n\n// debug(s\"$i ${dp.mkString}, ${last(x^1).mkString(\",\")}\")\n }\n\n out.println(dp(N))\n }\n\n def debug(msg: String): Unit = {\n System.err.println(msg)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [], "src_uid": "3b2d0d396649a200a73faf1b930ef611"} {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n\n for (i <- as.indices) {\n val s = if (i % 2 == 1) 1 else -1\n as(i) = math.abs(as(i)) * s\n }\n\n out.println(as.mkString(\" \"))\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n val bn = an.zipWithIndex.map { case (a, i) => if (i % 2 == 0) a.abs else -a.abs }\n\n println(bn.mkString(\" \"))\n }\n}\n"}], "negative_code": [{"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n val bn = an.zipWithIndex.map { case (a, i) => if (i % 2 == 0) a else -a }\n\n println(bn.mkString(\" \"))\n }\n}\n"}], "src_uid": "d07ae42b7902ba3a49cf4463248710ea"} {"source_code": "import scala.io.StdIn\n\nobject ProblemA extends App {\n\n type Input = List[((String, Int, Long), (String, Int, Long))]\n def start() = {\n val input = parseInput()\n val result = input.map(solve(_))\n println(result.mkString(\"\\n\"))\n }\n\n def parseInput(): Input = {\n val ntc = StdIn.readLine().stripLineEnd.trim.toInt\n var result: Input = List()\n for (_ <- 0.until(ntc)) {\n val a = StdIn.readLine().stripLineEnd.trim.split(\" \").map( a => (a, a.length-1))\n val b = StdIn.readLine().stripLineEnd.trim.split(\" \").map( a => (a, a.length-1))\n result = ((a(0)._1, a(0)._2, a(1)._1.toLong), (b(0)._1, b(0)._2, b(1)._1.toLong) ) :: result\n }\n result.reverse\n }\n\n def solve(input: ((String, Int, Long), (String, Int, Long))): String = {\n val (a,b) = input\n\n if (a._2 < b._2) solve(( (a._1 + \"0\", a._2+1, a._3-1), b))\n else if (a._2 > b._2) solve(( a, (b._1 + \"0\", b._2+1, b._3-1)))\n else {\n if (a._3 == b._3) {\n val x = a._1.toInt\n val y = b._1.toInt\n if ( x < y) \"<\"\n else if (x > y) \">\"\n else \"=\"\n } else if (a._3 > b._3) {\n val x = (a._1 + \"0\").toInt\n val y = b._1.toInt\n if ( x < y) \"<\"\n else if (x > y) \">\"\n else \"=\"\n } else {\n val x = (a._1).toInt\n val y = (b._1 + \"0\").toInt\n if ( x < y) \"<\"\n else if (x > y) \">\"\n else \"=\"\n }\n }\n\n }\n\n def pow10(a: Int): Long = {\n var result = 1L\n for (_ <- 0.until(a)) result = result * 10L\n result\n }\n start()\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(val a: Int, val b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return -1 * a.compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n\n\n for (tt <- 1 to t) {\n var x1 = readInt()\n val p1 = readInt()\n var x2 = readInt()\n val p2 = readInt()\n var c1 = 0\n var c2 = 0\n var tmp = x1\n while (tmp > 0) {\n c1 += 1\n tmp /= 10\n }\n tmp = x2\n while (tmp > 0) {\n c2 += 1\n tmp /= 10\n }\n if (p1 + c1 > p2 + c2) {\n writer.println('>')\n }\n if (p1 + c1 < p2 + c2) {\n writer.println('<')\n }\n if (p1 + c1 == p2 + c2){\n while (c1 < c2) {\n c1 += 1\n x1 *= 10\n }\n while (c2 < c1) {\n c2 += 1\n x2 *= 10\n }\n if (x1 < x2) {\n writer.println('<')\n }\n if (x1 > x2){\n writer.println('>')\n }\n if (x1 == x2){\n writer.println('=')\n }\n }\n\n def check(kk: Int): Boolean = {\n return true\n }\n def bs(st:Int, en:Int): Int = {\n if (en - st <= 1) {\n if (check(en))\n return en\n else\n return st\n }\n val mid = (st + en) / 2\n if (check(mid))\n return bs(mid, en)\n else\n return bs(st, mid)\n }\n }\n writer.flush()\n}"}], "negative_code": [], "src_uid": "a4eeaf7252b9115b67b9eca5f2bf621d"} {"source_code": "object Main {\n import scala.util.control.Breaks.{breakable,break}\n import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue}\n import java.io._\n \n val in = new InputReader(System.in)\n val pw = new PrintWriter(System.out)\n\n def main (args: Array[String]){\n val q = in.next().toInt\n for (_ <- 1 to q) {\n val a, b, c = in.next().toLong\n val l = List(a, b, c).sorted\n val sum = l.sum\n\n val x = l(0)\n val y = l(1)\n val z = l(2)\n\n var ans = 0L\n if (x + z < y)\n ans = x + z\n else {\n val hoge = z - (y - x)\n ans = y + hoge / 2\n }\n \n pw.println(ans)\n }\n\n pw.flush()\n }\n}\nimport java.io._\nclass InputReader(stream: InputStream) {\n \n import java.util.StringTokenizer\n\n private val reader = new BufferedReader(new InputStreamReader(stream))\n private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())\n def next(): String = {\n while (!tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine())\n }\n tokenizer.nextToken()\n }\n}\n", "positive_code": [{"source_code": "object Main extends App {\n var q: Int = readInt()\n for (_ <- 0 until q) {\n println(readLine().split(\"\\\\s\").map(_.toLong).sum / 2)\n }\n}"}, {"source_code": "object Main extends App {\n var q: Int = readInt()\n for (_ <- 0 until q) {\n println(readLine().split(\"\\\\s+\").map(_.toLong).sum / 2)\n }\n}\n"}, {"source_code": "object _1196A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val input = io.read[Seq[(Long, Long, Long)]]\n val ans = input.map({case (a, b, c) => (a + b + c)/2})\n io.writeLines(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "d9e4a9a32d60e75f3cf959ef7f894fc6"} {"source_code": "//package codeforces.contests._1363\n\nobject SubsequenceHate {\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val s = io.StdIn.readLine()\n\n val ones = {\n val arr = new Array[Int](s.length)\n arr(0) = if (s(0) == '1') 1 else 0\n (1 until s.length).foreach(i => arr(i) = (if (s(i) == '1') 1 else 0) + arr(i - 1))\n arr\n }\n\n def onesInRange(x: Int, y: Int): Int =\n if (x > y) 0 else if (x == 0) ones(y) else ones(y) - ones(x - 1)\n\n def zeroesInRange(x: Int, y: Int): Int =\n if (x > y) 0 else y - x + 1 - onesInRange(x, y)\n\n def makeZeroCost(x: Int, y: Int): Int = onesInRange(x, y)\n\n def makeOneCost(x: Int, y: Int): Int = zeroesInRange(x, y)\n\n val last = s.length - 1\n\n println {\n (0 to last).foldLeft(Int.MaxValue)((acc, i) =>\n acc min (makeOneCost(0, i) + makeZeroCost(i + 1, last)) min (makeZeroCost(0, i) + makeOneCost(i + 1, last)))\n }\n }\n }\n\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CF646B(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CF646B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val T = ni()\n REP(T) { _ =>\n val s = ns()\n val cnt0 = Array.ofDim[Int](s.length+1)\n val cnt1 = Array.ofDim[Int](s.length+1)\n cnt0(0) = 0\n cnt1(0) = 0\n\n s.zipWithIndex.foreach { f =>\n cnt0(f._2 + 1) = cnt0(f._2) + (if(f._1 - '0' == 0) 1 else 0)\n cnt1(f._2 + 1) = cnt1(f._2) + (if(f._1 - '0' == 1) 1 else 0)\n }\n// println(cnt0.mkString(\",\"))\n// println(cnt1.mkString(\",\"))\n var ans = Int.MaxValue\n REP(s.length) { i =>\n val c1 = cnt1(i+1) + (cnt0(s.length) - cnt0(i+1))\n val c0 = cnt0(i+1) + (cnt1(s.length) - cnt1(i+1))\n// println(c0 + \" \" + c1)\n ans = Math.min(ans, Math.min(c0, c1))\n }\n\n out.println(ans)\n }\n }\n}\n"}, {"source_code": "object _1363B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val a = io.read[String].toList\n\n def count(what: Char, left: Boolean) = {\n if (left) {\n a.scanLeft(0)({case (c, d) => if (d == what) c+1 else c})\n } else {\n a.scanRight(0)({case (d, c) => if (d == what) c+1 else c})\n }\n }.drop(1)\n\n val r0 = count('0', left = false)\n val l1 = count('1', left = true)\n val l0 = count('0', left = true)\n val r1 = count('1', left = false)\n\n val ans = (l1.zip(r0) ++ l0.zip(r1)).map({case (x, y) => x + y})\n\n io.write(ans.min)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n val charToInt: Char => Int = Character.getNumericValue\n val intToChar: Int => Char = Character.forDigit(_, 10)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val arr = readLine().map(_ == '1').toList\n val ans = minNum(arr)\n println(ans)\n }\n// println(minNum(List[Boolean](false, false, true)))\n }\n\n def minNum(list: List[Boolean]): Int = {\n def zeroOne(l: List[Boolean], min: Int, left: Int, right: Int): Int = l match {\n case Nil => Math.min(min, left + right)\n case b :: bs => zeroOne(bs, Math.min(min, left + right),\n if (b) left + 1 else left, if (b) right else right - 1)\n }\n\n Math.min(zeroOne(list, list.count(i => !i), 0, list.count(i => !i)),\n zeroOne(list.map(i => !i), list.count(i => i), 0, list.count(i => i)))\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val arr = readLine().map(_ == '1').toList\n val ans = minNum(arr)\n println(ans)\n }\n// println(minNum(List[Boolean](false, false, true, true, false, false)))\n }\n\n def minNum(list: List[Boolean]): Int = {\n def zeroOne(l: List[Boolean], min: Int, left: Int, right: Int): Int = l match {\n case Nil => Math.min(min, left + right)\n case b :: bs => zeroOne(bs, Math.min(min, left + right),\n if (b) left + 1 else left, if (b) right else right + 1)\n }\n\n Math.min(zeroOne(list, list.count(i => i), 0, list.count(i => i)),\n zeroOne(list.map(i => !i), list.count(i => !i), 0, list.count(i => !i)))\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val arr = readLine().map(_ == '1').toList\n val ans = minNum(arr)\n println(ans)\n }\n// println(minNum(List[Boolean](false, false, true, true, false, false)))\n }\n\n def minNum(list: List[Boolean]): Int = {\n def zeroOne(l: List[Boolean], min: Int, left: Int, right: Int): Int = l match {\n case Nil => Math.min(min, left + right)\n case b :: bs => zeroOne(bs, Math.min(min, left + right),\n if (b) left + 1 else left, if (b) right else right + 1)\n }\n\n Math.min(zeroOne(list, list.count(i => !i), 0, list.count(i => !i)),\n zeroOne(list.map(i => !i), list.count(i => !i), 0, list.count(i => !i)))\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val arr = readLine().map(_ == '1').toList\n val ans = minNum(arr)\n println(ans)\n }\n// println(minNum(List[Boolean](false, false, true, true, false, false)))\n }\n\n def minNum(list: List[Boolean]): Int = {\n def zeroOne(l: List[Boolean], min: Int, left: Int, right: Int): Int = l match {\n case Nil => Math.min(min, left + right)\n case b :: bs => zeroOne(bs, Math.min(min, left + right),\n if (b) left + 1 else left - 1, if (b) right + 1 else right - 1)\n }\n\n Math.min(zeroOne(list, list.count(i => !i), 0, list.count(i => !i)),\n zeroOne(list.map(i => !i), list.count(i => !i), 0, list.count(i => !i)))\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val arr = readLine().map(_ == '1').toList\n val ans = minNum(arr)\n println(ans)\n }\n// println(minNum(List[Boolean](false, false, true, true, false, false)))\n }\n\n def minNum(list: List[Boolean]): Int = {\n def zeroOne(l: List[Boolean], min: Int, left: Int, right: Int): Int = l match {\n case Nil => Math.min(min, left + right)\n case b :: bs => zeroOne(bs, Math.min(min, left + right),\n if (b) left + 1 else left, if (b) right else right + 1)\n }\n\n Math.min(zeroOne(list, list.count(i => !i), 0, list.count(i => !i)),\n zeroOne(list.map(i => !i), list.count(i => i), 0, list.count(i => i)))\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}], "src_uid": "803e5ccae683b91a4cc486fbc558b330"} {"source_code": "object C extends App {\n import scala.io.StdIn._\n\n private def gcd(a: Int, b: Int): Int =\n if (b == 0) a else gcd(b, a % b)\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n val amin = an.min\n\n val ans = (an zip an.sorted).forall {\n case (x, y) if x == y => true\n case (x, y) if gcd(x, amin) == amin => true\n case _ => false\n }\n\n if (ans) println(\"YES\") else println(\"NO\")\n }\n}\n", "positive_code": [{"source_code": "object C extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n val a = an.min\n\n // format: off\n val ans = (an zip an.sorted).forall {\n case (x, y) if x == y => true\n case (x, y) if x % a == 0 => true\n case _ => false\n }\n // format: on\n\n if (ans) println(\"YES\") else println(\"NO\")\n }\n}\n"}], "negative_code": [{"source_code": "object C extends App {\n import scala.io.StdIn._\n\n private def gcd(a: Int, b: Int): Int =\n if (b == 0) a else gcd(b, a % b)\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n val amin = an.min\n\n val ans = (an zip an.sorted).forall {\n case (x, y) if x == y => true\n case (x, y) if gcd(x, amin) == amin => true\n case _ => false\n }\n\n println(ans)\n }\n}\n"}], "src_uid": "f2070c2bd7bdbf0919aef1e915a21a24"} {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val n = readInt()\n val B = readLine().split(\" \").map(_ == \"1\")\n\n if (B.length == 1) {\n if (B.head == true) println(\"YES\") else println(\"NO\")\n } else {\n if (B.count(_ == false) == 1) println(\"YES\") else println(\"NO\")\n }\n\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val buttons = in.next().count(_ == '1')\n if (buttons == 0 || (n != 1 && (n - buttons) != 1))\n println(\"NO\")\n else \n println(\"YES\")\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val buttons = in.next().count(_ == '1')\n if (buttons == 0 || (n - buttons) != 1)\n println(\"NO\")\n else \n println(\"YES\")\n}\n"}], "src_uid": "7db0b870177e7d7b01da083e21ba35f5"} {"source_code": "\n/**\n * @author pvasilyev\n * @since 27 Aug 2016\n */\nobject C625 extends App {\n\n def solve() = {\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val a: Array[Array[Int]] = Array.ofDim[Int](n, n)\n var value = 1\n for (i <- 0 until n) {\n for (j <- 0 until k - 1) {\n a(i)(j) = value\n value += 1\n }\n }\n for (i <- 0 until n) {\n for (j <- k - 1 until n) {\n a(i)(j) = value\n value += 1\n }\n }\n\n println((0 until n).map(i => a(i)(k-1)).sum)\n\n val sb = StringBuilder.newBuilder\n\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n sb append a(i)(j).toString append \" \"\n }\n sb append \"\\n\"\n }\n println(sb)\n }\n\n solve()\n\n}\n", "positive_code": [{"source_code": "\n/**\n * Created by octavian on 07/02/2016.\n */\nobject KSpecial {\n\n\n def main(args: Array[String]) = {\n\n //System.setIn(new FileInputStream(\"./src/kspecial.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"./src/kspecial.out\")))\n\n var Array(n, k) = readLine().split(\" \").map(_.toInt)\n var r :Array[Array[Int]] = Array.ofDim[Int](n + 1, n + 1)\n var sum = 0\n\n var current = 1\n for(i <- 1 to n) {\n for(j <- 1 until k) {\n r(i)(j) = current\n current += 1\n }\n }\n\n for(i <- 1 to n) {\n for(j <- k to n) {\n r(i)(j) = current\n if(j == k) {\n sum += current\n }\n\n current += 1\n }\n }\n\n println(sum)\n for(i <- 1 to n) {\n println(r(i).tail.mkString(\" \"))\n }\n\n }\n\n}\n"}, {"source_code": "object A {\n def main(args: Array[String]) {\n val Array(n, k) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n var l = 0\n var r = n*(k-1)+1\n val s = (r + n*n - n + k) * n /2\n println(s)\n (1 to n).foreach(x => {\n println(((l+1 until l + k) ++ (r until r + n - k + 1)).mkString(\" \"))\n l += k - 1\n r += n - k + 1\n })\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val start = n * (k - 1) + 1\n val kColumn = start * n + (n - k + 1) * (n - 1) * n / 2\n var first = 1\n var second = start\n println(kColumn)\n println((0 until n).map{ i =>\n (0 until n).map { j =>\n if (j % n < k - 1) {\n first += 1\n first - 1\n } else {\n second += 1\n second - 1\n }\n }.mkString(\" \")\n }.mkString(\"\\n\"))\n}\n"}, {"source_code": "import scala.annotation.tailrec\nobject Main {\n def main(args: Array[String]) : Unit = {\n val console = new MyConsole(Console.in, Console.out, Console.err)\n val solver = new Solver(console)\n solver.main()\n console.flush()\n }\n class Solver(val stdio: MyConsole){\n import stdio._ // shadow Console.~\n def main() : Unit = {\n val n, k = nextInt()\n\n val buf = new StringBuilder()\n var retc = 0\n for(i <- 0 until n) {\n val lefts = (k-1) * i + 1\n val rights = ((k-1) * n + 1) + i*(n-k+1)\n retc += rights\n val left = lefts until (lefts + k - 1)\n val right = rights to (rights + n-k)\n buf ++= (left ++ right).mkString(\" \") + \"\\n\"\n // println((left ++ right).mkString(\" \"))\n }\n println(retc)\n print(buf.toString)\n\n // val a = n * (k-1) + 1\n // var c = 0L\n // for(i <- (0L until n)) {\n // val m = if(n != k) Seq(a + k * i) else Seq(a + i)\n // c += m.head\n // }\n // val ca= (k to (n*n) by n).sum\n // if(ca >= c){\n // println(ca)\n // for(line <- (1L to (n*n)).grouped(n.toInt)){\n // println(line.mkString(\" \"))\n // }\n // }else{\n // println(c)\n // for(i <- (0L until n)) {\n // val left_f = (k-1) * i + 1\n // val l = left_f until (left_f + k-1)\n // val m = if(n != k) Seq(a + k * i) else Seq(a + i)\n // val r = (m.head + 1) to (m.head + (n-k))\n // println((l ++ m ++ r).mkString(\" \"))\n // }\n // }\n }\n }\n import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}\n class MyConsole(val in: BufferedReader, val _out: PrintStream,\n val err: PrintStream) {\n // PrintWriter do not flush automatically\n val out = new PrintWriter(_out,false)\n // If argument is null, there are ambiguous which function will be called\n def print(obj: Any) = out.print(if(obj == null) \"null\" else obj.toString)\n def println() = out.println()\n def println(obj: Any) = out.println(obj)\n def printf(text: String, args: Any*) = out.printf(text.format(args : _*))\n // NOTE: YOU MUST FLUSH BEFORE END OF MAIN\n def flush() = out.flush()\n def debugln(obj: Any) = err.println(\"\\u001b[36m\" + obj + \"\\u001b[0m\")\n\n def readIntVector() : Vector[Int] = parseLineToVector(() => nextInt)\n def readLongVector() : Vector[Long] = parseLineToVector(() => nextLong)\n def readStringVector() : Vector[String] = parseLineToVector(() => nextString)\n def nextInt() : Int = nextLong().toInt\n def nextBigInt() : BigInt = BigInt(nextString())\n def nextBigDecimal( ) : BigDecimal = BigDecimal(nextString())\n def nextDouble() : Double = nextString().toDouble\n def nextLong() : Long = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading long failed\")\n val sgn = if(peek == '-') -1l else 1\n if(sgn == -1l) ignore(read())\n if(peek < '0' || '9' < peek)\n throw new NumberFormatException(s\"readLong found only '-' or no number\")\n @tailrec\n def readLong(next: Int, cur: Long) : Long =\n if('0' <= next && next <= '9'){\n ignore(read()) // is equal to next\n readLong(peek, cur*10 + next-'0')\n }\n else if(isEnd(next) || isSpaceOrControl(next))\n sgn*cur\n else\n throw new NumberFormatException(s\"readLong found strange byte $next\")\n val res = readLong(peek,0)\n skipTrailingSpaces()\n res\n }\n def nextString() : String = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading String failed\")\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isSpaceOrControl(next)){\n builder.toString\n }else{\n builder.append(read().toChar) // here we skip.\n appendCode(peek)\n }\n }\n val res = appendCode(peek)\n skipTrailingSpaces()\n res\n }\n // TODO: refactoring to marge nextString\n def readLine() : String = {\n if(isEnd(peek))\n throw new NoSuchElementException(\"Reading Line failed\")\n skipNewline()\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isNewLine(next)){\n builder.toString\n }else{\n builder.append(next.toChar)\n appendCode(read())\n }\n }\n appendCode(read())\n }\n // helpers\n private def ignore[T](x: => T) : Unit = { x; () }\n private[this] var peeked: Option[Int] = None\n private[this] var is_first = true\n protected def read() = {\n val res = peeked match {\n case None => in.read()\n case Some(a) => { peeked = None; a }\n }\n is_first = false\n res\n }\n private def peek() =\n peeked match {\n case None => {\n val res = in.read()\n peeked = Some(res)\n res\n }\n case Some(a) => a\n }\n private def isEnd(c: Int) = c == -1\n private def isCR(c: Int) = c == 13\n private def isLF(c: Int) = c == 10\n private def isNewLine(c: Int) = isLF(c) || isCR(c)\n private def isThereReadable() = !isEnd(peek)\n private def isSpaceOrControl(c: Int) = (0 <= c && c <= 32) || c == 127\n @tailrec\n final private def goNextNotSpaceNorControl() : Unit =\n if(isSpaceOrControl(peek)){\n ignore(read())\n goNextNotSpaceNorControl()\n }\n final private def skipTrailingSpaces() : Unit = {\n @tailrec\n def skipTrailingSpacesAux() : Unit = {\n if(!isNewLine(peek) && isSpaceOrControl(peek)){\n ignore(read())\n skipTrailingSpacesAux()\n }\n }\n skipTrailingSpacesAux()\n }\n final private def skipNewline() : Unit =\n if(!is_first){\n if(isCR(peek))\n ignore(read())\n if(isLF(peek))\n ignore(read())\n }\n private def goNextValuable() : Boolean = {\n goNextNotSpaceNorControl()\n isThereReadable()\n }\n\n private def parseLineToVector[X](parser: () => X) : Vector[X] = {\n import scala.collection.immutable.VectorBuilder\n val vb = new VectorBuilder[X]()\n skipNewline()\n @tailrec\n def parseLineToVectorAux() : Vector[X] =\n if(isNewLine(peek) || isEnd(peek)) {\n vb.result\n }else{\n vb += parser()\n parseLineToVectorAux()\n }\n parseLineToVectorAux()\n }\n }\n}\n"}, {"source_code": "// object Main\nimport java.io.{IOException, InputStream, PrintWriter}\nimport java.util.InputMismatchException\n\nobject Main {\n\n def solveCase(caseNo: Int, in: InputReader, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val k = in.nextInt() - 1\n var t = n * n\n val table = Array.ofDim[Int](n, n)\n var answer = 0\n for (i <- (0 until n).reverse) {\n for (j <- (k until n).reverse) {\n table(i)(j) = t\n if (j == k) answer += t\n t -= 1\n }\n }\n for (j <- (0 until k).reverse) {\n for (i <- (0 until n).reverse) {\n table(i)(j) = t\n t -= 1\n }\n }\n out.println(answer)\n for (line <- table) {\n out.println(line.mkString(\" \"))\n }\n }\n\n def solve(in: InputReader, out: PrintWriter): Unit = {\n solveCase(1, in, out)\n// val caseCount = in.nextInt()\n// for (caseNo <- 1 to caseCount) {\n// solveCase(caseNo, in, out)\n// }\n }\n\n def main(args: Array[String]) {\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n in.close()\n out.close()\n }\n}\n\nclass InputReader(val inputStream: InputStream) {\n val buf = new Array[Byte](1 << 16)\n var curChar = 0\n var numChars = 0\n\n def read(): Int = {\n if (numChars == -1) {\n throw new InputMismatchException()\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => throw new InputMismatchException()\n }\n if (numChars <= 0)\n return -1\n }\n curChar += 1\n buf(curChar - 1)\n }\n\n def peek(): Int = {\n if (numChars == -1) {\n return -1\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => return -1\n }\n if (numChars <= 0)\n return -1\n }\n buf(curChar)\n }\n\n def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n\n def nextInt(): Int = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextLong(): Long = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0l\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def next(): String = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n val res = new StringBuilder()\n do {\n res += c.toChar\n c = read()\n } while (!isSpaceChar(c))\n res.toString()\n }\n\n def nextChar(): Char = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n c.toChar\n }\n\n //noinspection AccessorLikeMethodIsEmptyParen\n def hasNext(): Boolean = {\n var value = peek()\n do {\n read()\n value = peek()\n } while (isSpaceChar(value) && value != -1)\n value != -1\n }\n\n def rawNextLine(): String = {\n val builder = new StringBuilder\n var c = read()\n while (c != '\\n' && c != -1) {\n if (c != '\\r')\n builder += c.toChar\n c = read()\n }\n builder.toString()\n }\n\n def nextLine(): String = {\n var s = rawNextLine()\n while (s.trim().length == 0) s = rawNextLine()\n s\n }\n\n def nextDouble(): Double = {\n next().toDouble\n }\n\n def close(): Unit = {\n inputStream.close()\n }\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.implicitNotFound\nimport scala.reflect.ClassTag\n\n/**\n * Created by nimas on 2/4/16.\n */\nobject A extends App{\n\n class Template(val delim: String = \" \") {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n val it = Iterator.iterate(new StringTokenizer(\"\"))(tok => if (tok.hasMoreTokens) tok else new StringTokenizer(in.readLine(), delim))\n\n\n def nextTs[T: ParseAble](n: Int)(delim: String = \" \")(implicit ev: ClassTag[T]) = (Array fill n) {\n nextT[T](delim)\n }\n\n def nextT[T](delim: String = \" \")(implicit parser: ParseAble[T]) = {\n val x = it.find(_.hasMoreTokens)\n parser parse (x get)\n }\n\n def close(): Unit = {\n in.close()\n out.close()\n }\n\n @implicitNotFound(\"No member of type class ParseAble in scope for ${T}\")\n trait ParseAble[T] {\n def parse(strTok: StringTokenizer): T\n }\n\n object ParseAble {\n\n implicit object ParseAbleString extends ParseAble[String] {\n override def parse(strTok: StringTokenizer): String = strTok nextToken()\n }\n\n implicit object ParseAbleInt extends ParseAble[Int] {\n override def parse(strTok: StringTokenizer): Int = strTok nextToken() toInt\n }\n\n implicit object ParseAbleLong extends ParseAble[Long] {\n override def parse(strTok: StringTokenizer): Long = strTok nextToken() toLong\n }\n\n implicit object ParseAbleDouble extends ParseAble[Double] {\n override def parse(strTok: StringTokenizer): Double = strTok nextToken() toDouble\n }\n\n implicit object ParseAbleBigInt extends ParseAble[BigInt] {\n override def parse(strTok: StringTokenizer): BigInt = BigInt(strTok nextToken())\n }\n\n }\n\n }\n\n val io = new Template()\n\n import io._\n\n\n val (n, k) = (nextT[Int](), nextT[Int]())\n\n\n val xs = Array.fill(n + 1, n + 1) {0}\n\n\n\n var minLast = 1\n\n var em = n - k\n\n var highLast = (n * n) - em\n\n\n var curow = 1\n var max = 0\n\n while(curow <= n) {\n\n var curHigh = highLast\n for (c <- k to n) {\n xs(curow)(c) = curHigh\n curHigh = curHigh + 1\n }\n\n max = max + xs(curow)(k)\n\n highLast = highLast - em - 1\n\n\n for (c <- 1 until k) {\n xs(curow)(c) = minLast\n minLast = minLast + 1\n }\n\n curow = curow + 1\n }\n\n\n\n out println max\n for (r <- 1 to n) {\n out.print(xs(r) drop 1 mkString \" \")\n out println()\n }\n\n\n close()\n\n}"}, {"source_code": "\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.implicitNotFound\nimport scala.reflect.ClassTag\n\n/**\n * Created by nimas on 2/4/16.\n */\nobject A extends App{\n\n class Template(val delim: String = \" \") {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n val it = Iterator.iterate(new StringTokenizer(\"\"))(tok => if (tok.hasMoreTokens) tok else new StringTokenizer(in.readLine(), delim))\n\n\n def nextTs[T: ParseAble](n: Int)(delim: String = \" \")(implicit ev: ClassTag[T]) = (Array fill n) {\n nextT[T](delim)\n }\n\n def nextT[T](delim: String = \" \")(implicit parser: ParseAble[T]) = {\n val x = it.find(_.hasMoreTokens)\n parser parse (x get)\n }\n\n def close(): Unit = {\n in.close()\n out.close()\n }\n\n @implicitNotFound(\"No member of type class ParseAble in scope for ${T}\")\n trait ParseAble[T] {\n def parse(strTok: StringTokenizer): T\n }\n\n object ParseAble {\n\n implicit object ParseAbleString extends ParseAble[String] {\n override def parse(strTok: StringTokenizer): String = strTok nextToken()\n }\n\n implicit object ParseAbleInt extends ParseAble[Int] {\n override def parse(strTok: StringTokenizer): Int = strTok nextToken() toInt\n }\n\n implicit object ParseAbleLong extends ParseAble[Long] {\n override def parse(strTok: StringTokenizer): Long = strTok nextToken() toLong\n }\n\n implicit object ParseAbleDouble extends ParseAble[Double] {\n override def parse(strTok: StringTokenizer): Double = strTok nextToken() toDouble\n }\n\n implicit object ParseAbleBigInt extends ParseAble[BigInt] {\n override def parse(strTok: StringTokenizer): BigInt = BigInt(strTok nextToken())\n }\n\n }\n\n }\n\n val io = new Template()\n\n import io._\n\n\n val (n, k) = (nextT[Int](), nextT[Int]())\n\n\n val xs = Array.fill(n + 1, n + 1) {0}\n\n\n\n var minLast = 1\n\n var em = n - k\n\n var highLast = (n * n) - em\n\n\n var curow = 1\n var max = 0\n\n while(curow <= n) {\n\n var curHigh = highLast\n for (c <- k to n) {\n xs(curow)(c) = curHigh\n curHigh = curHigh + 1\n }\n\n max = max + xs(curow)(k)\n\n highLast = highLast - em - 1\n\n\n for (c <- 1 until k) {\n xs(curow)(c) = minLast\n minLast = minLast + 1\n }\n\n curow = curow + 1\n }\n\n\n\n out println max\n for (r <- 1 to n) {\n out.print(xs(r) drop 1 mkString \" \")\n out println()\n }\n\n\n close()\n\n}\n"}, {"source_code": "import scala.io.Source\n\nobject round_342_div2_C {\n def main(args: Array[String]){\n val in = Source.stdin.getLines()\n val ln = in.next().split(\" \")\n val n = ln(0).toInt\n val k = ln(1).toInt\n\n var tot = 0\n for (i <- 1 to n) {\n tot += 1+n*(k-1) + (i-1)*(n-k+1)\n }\n println(tot)\n\n\n for (i <- 1 to n) {\n var res = \"\"\n for (j <- 1 to (k - 1)) {\n res = res + \"%d \".format(j+(i-1)*(k-1))\n }\n for (j <- 1 to (n - k + 1)) {\n res = res + \"%d \".format(j + n*(k-1) + (i-1)*(n-k+1))\n }\n println(res.trim)\n }\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject round_342_div2_C {\n def main(args: Array[String]){\n val in = Source.stdin.getLines()\n val ln = in.next().split(\" \")\n val n = ln(0).toInt\n val k = ln(1).toInt\n\n var tot = 0\n for (i <- 1 to n) {\n tot += 1+n*(k-1) + (i-1)*(n-k+1)\n }\n println(tot)\n\n\n for (i <- 1 to n) {\n //for (j <- 1 to (k - 1)) {\n // res = res + \"%d \".format(j+(i-1)*(k-1))\n //}\n val left = 1+(i-1)*(k-1) to (k-1)+(i-1)*(k-1)\n //for (j <- 1 to (n - k + 1)) {\n // res = res + \"%d \".format(j + n*(k-1) + (i-1)*(n-k+1))\n //}\n val right = 1+n*(k-1)+(i-1)*(n-k+1) to (n-k+1) + n*(k-1)+(i-1)*(n-k+1)\n \n println((left++right).mkString(\" \").trim)\n }\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _625C extends CodeForcesApp {\n override type Result = (Int, Array[Array[Int]])\n\n override def solve(read: InputReader) = {\n val (n, k) = (read[Int], read[Int])\n val table = Array.ofDim[Int](n, n)\n var i = 0\n for {\n r <- 0 until n\n c <- 0 until (k-1)\n } {\n i = i + 1\n table(r)(c) = i\n }\n var sum = 0\n for {\n r <- 0 until n\n c <- 0 until n if table(r)(c) == 0\n } {\n i = i + 1\n table(r)(c) = i\n if (c == k-1) sum += i\n }\n sum -> table\n }\n\n override def format(result: Result) = {\n val (t, m) = result\n s\"$t\\n${m.map(_ mkString \" \") mkString \"\\n\"}\"\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(next())\n\n def tillEndOfLine(): String = tokenizer().get.nextToken(\"\\n\\r\")\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\ntrait Parser[A] {\n def apply(s: String): A\n}\nobject Parser {\n def apply[A](f: String => A) = new Parser[A] {\n override def apply(s: String) = f(s)\n }\n implicit val stringParser: Parser[String] = Parser(identity)\n implicit val charParser: Parser[Char] = Parser(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val booleanParser: Parser[Boolean] = Parser(_.toBoolean)\n implicit val intParser: Parser[Int] = Parser(_.toInt)\n implicit val longParser: Parser[Long] = Parser(_.toLong)\n implicit val bigIntParser: Parser[BigInt] = Parser(BigInt(_))\n implicit val doubleParser: Parser[Double] = Parser(_.toDouble)\n implicit val bigDecimalParser: Parser[BigDecimal] = Parser(BigDecimal(_))\n}\n"}], "negative_code": [{"source_code": "object A {\n def main(args: Array[String]) {\n val Array(n, k) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n var l = 0\n var r = n*(k-1)+1\n val s = (r + n*n - n + k) * n /2\n println(s)\n (1 to n).foreach(x => {\n println((l+1 until l + k) ++ (r until r + n - k + 1))\n l += k - 1\n r += n - k + 1\n })\n }\n}"}, {"source_code": "import scala.annotation.tailrec\nobject Main {\n def main(args: Array[String]) : Unit = {\n val console = new MyConsole(Console.in, Console.out, Console.err)\n val solver = new Solver(console)\n solver.main()\n console.flush()\n }\n class Solver(val stdio: MyConsole){\n import stdio._ // shadow Console.~\n def main() : Unit = {\n val n, k = nextLong()\n\n val a = n * (k-1) + 1\n // val b = a + k * (n-1)\n // val c = (a+b)* n / 2\n var c = 0L\n var output = \"\"\n for(i <- (0L until n)) {\n val left_f = (k-1) * i + 1\n val l = left_f until (left_f + k-1)\n assert(l.length == (k-1))\n val m = Seq(a + n * i)\n c += m.head\n val r = (m.head + 1) to (m.head + (n-k))\n assert(r.length == n-k)\n output += ((l ++ m ++ r).mkString(\" \")) + \"\\n\"\n }\n println(c)\n print(output)\n }\n }\n import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}\n class MyConsole(val in: BufferedReader, val _out: PrintStream,\n val err: PrintStream) {\n // PrintWriter do not flush automatically\n val out = new PrintWriter(_out,false)\n // If argument is null, there are ambiguous which function will be called\n def print(obj: Any) = out.print(if(obj == null) \"null\" else obj.toString)\n def println() = out.println()\n def println(obj: Any) = out.println(obj)\n def printf(text: String, args: Any*) = out.printf(text.format(args : _*))\n // NOTE: YOU MUST FLUSH BEFORE END OF MAIN\n def flush() = out.flush()\n def debugln(obj: Any) = err.println(\"\\u001b[36m\" + obj + \"\\u001b[0m\")\n\n def readIntVector() : Vector[Int] = parseLineToVector(() => nextInt)\n def readLongVector() : Vector[Long] = parseLineToVector(() => nextLong)\n def readStringVector() : Vector[String] = parseLineToVector(() => nextString)\n def nextInt() : Int = nextLong().toInt\n def nextBigInt() : BigInt = BigInt(nextString())\n def nextBigDecimal( ) : BigDecimal = BigDecimal(nextString())\n def nextDouble() : Double = nextString().toDouble\n def nextLong() : Long = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading long failed\")\n val sgn = if(peek == '-') -1l else 1\n if(sgn == -1l) ignore(read())\n if(peek < '0' || '9' < peek)\n throw new NumberFormatException(s\"readLong found only '-' or no number\")\n @tailrec\n def readLong(next: Int, cur: Long) : Long =\n if('0' <= next && next <= '9'){\n ignore(read()) // is equal to next\n readLong(peek, cur*10 + next-'0')\n }\n else if(isEnd(next) || isSpaceOrControl(next))\n sgn*cur\n else\n throw new NumberFormatException(s\"readLong found strange byte $next\")\n val res = readLong(peek,0)\n skipTrailingSpaces()\n res\n }\n def nextString() : String = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading String failed\")\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isSpaceOrControl(next)){\n builder.toString\n }else{\n builder.append(read().toChar) // here we skip.\n appendCode(peek)\n }\n }\n val res = appendCode(peek)\n skipTrailingSpaces()\n res\n }\n // TODO: refactoring to marge nextString\n def readLine() : String = {\n if(isEnd(peek))\n throw new NoSuchElementException(\"Reading Line failed\")\n skipNewline()\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isNewLine(next)){\n builder.toString\n }else{\n builder.append(next.toChar)\n appendCode(read())\n }\n }\n appendCode(read())\n }\n // helpers\n private def ignore[T](x: => T) : Unit = { x; () }\n private[this] var peeked: Option[Int] = None\n private[this] var is_first = true\n protected def read() = {\n val res = peeked match {\n case None => in.read()\n case Some(a) => { peeked = None; a }\n }\n is_first = false\n res\n }\n private def peek() =\n peeked match {\n case None => {\n val res = in.read()\n peeked = Some(res)\n res\n }\n case Some(a) => a\n }\n private def isEnd(c: Int) = c == -1\n private def isCR(c: Int) = c == 13\n private def isLF(c: Int) = c == 10\n private def isNewLine(c: Int) = isLF(c) || isCR(c)\n private def isThereReadable() = !isEnd(peek)\n private def isSpaceOrControl(c: Int) = (0 <= c && c <= 32) || c == 127\n @tailrec\n final private def goNextNotSpaceNorControl() : Unit =\n if(isSpaceOrControl(peek)){\n ignore(read())\n goNextNotSpaceNorControl()\n }\n final private def skipTrailingSpaces() : Unit = {\n @tailrec\n def skipTrailingSpacesAux() : Unit = {\n if(!isNewLine(peek) && isSpaceOrControl(peek)){\n ignore(read())\n skipTrailingSpacesAux()\n }\n }\n skipTrailingSpacesAux()\n }\n final private def skipNewline() : Unit =\n if(!is_first){\n if(isCR(peek))\n ignore(read())\n if(isLF(peek))\n ignore(read())\n }\n private def goNextValuable() : Boolean = {\n goNextNotSpaceNorControl()\n isThereReadable()\n }\n\n private def parseLineToVector[X](parser: () => X) : Vector[X] = {\n import scala.collection.immutable.VectorBuilder\n val vb = new VectorBuilder[X]()\n skipNewline()\n @tailrec\n def parseLineToVectorAux() : Vector[X] =\n if(isNewLine(peek) || isEnd(peek)) {\n vb.result\n }else{\n vb += parser()\n parseLineToVectorAux()\n }\n parseLineToVectorAux()\n }\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\nobject Main {\n def main(args: Array[String]) : Unit = {\n val console = new MyConsole(Console.in, Console.out, Console.err)\n val solver = new Solver(console)\n solver.main()\n console.flush()\n }\n class Solver(val stdio: MyConsole){\n import stdio._ // shadow Console.~\n def main() : Unit = {\n val n, k = nextLong()\n\n val a = n * (k-1) + 1\n var c = 0L\n for(i <- (0L until n)) {\n val m = if(n != k) Seq(a + k * i) else Seq(a + i)\n c += m.head\n }\n val ca= (k to (n*n) by n).sum\n if(ca >= c){\n println(ca)\n for(line <- (1L to (n*n)).grouped(n.toInt)){\n println(line.mkString(\" \"))\n }\n }else{\n println(c)\n for(i <- (0L until n)) {\n val left_f = (k-1) * i + 1\n val l = left_f until (left_f + k-1)\n val m = if(n != k) Seq(a + k * i) else Seq(a + i)\n val r = (m.head + 1) to (m.head + (n-k))\n println((l ++ m ++ r).mkString(\" \"))\n }\n }\n }\n }\n import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}\n class MyConsole(val in: BufferedReader, val _out: PrintStream,\n val err: PrintStream) {\n // PrintWriter do not flush automatically\n val out = new PrintWriter(_out,false)\n // If argument is null, there are ambiguous which function will be called\n def print(obj: Any) = out.print(if(obj == null) \"null\" else obj.toString)\n def println() = out.println()\n def println(obj: Any) = out.println(obj)\n def printf(text: String, args: Any*) = out.printf(text.format(args : _*))\n // NOTE: YOU MUST FLUSH BEFORE END OF MAIN\n def flush() = out.flush()\n def debugln(obj: Any) = err.println(\"\\u001b[36m\" + obj + \"\\u001b[0m\")\n\n def readIntVector() : Vector[Int] = parseLineToVector(() => nextInt)\n def readLongVector() : Vector[Long] = parseLineToVector(() => nextLong)\n def readStringVector() : Vector[String] = parseLineToVector(() => nextString)\n def nextInt() : Int = nextLong().toInt\n def nextBigInt() : BigInt = BigInt(nextString())\n def nextBigDecimal( ) : BigDecimal = BigDecimal(nextString())\n def nextDouble() : Double = nextString().toDouble\n def nextLong() : Long = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading long failed\")\n val sgn = if(peek == '-') -1l else 1\n if(sgn == -1l) ignore(read())\n if(peek < '0' || '9' < peek)\n throw new NumberFormatException(s\"readLong found only '-' or no number\")\n @tailrec\n def readLong(next: Int, cur: Long) : Long =\n if('0' <= next && next <= '9'){\n ignore(read()) // is equal to next\n readLong(peek, cur*10 + next-'0')\n }\n else if(isEnd(next) || isSpaceOrControl(next))\n sgn*cur\n else\n throw new NumberFormatException(s\"readLong found strange byte $next\")\n val res = readLong(peek,0)\n skipTrailingSpaces()\n res\n }\n def nextString() : String = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading String failed\")\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isSpaceOrControl(next)){\n builder.toString\n }else{\n builder.append(read().toChar) // here we skip.\n appendCode(peek)\n }\n }\n val res = appendCode(peek)\n skipTrailingSpaces()\n res\n }\n // TODO: refactoring to marge nextString\n def readLine() : String = {\n if(isEnd(peek))\n throw new NoSuchElementException(\"Reading Line failed\")\n skipNewline()\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isNewLine(next)){\n builder.toString\n }else{\n builder.append(next.toChar)\n appendCode(read())\n }\n }\n appendCode(read())\n }\n // helpers\n private def ignore[T](x: => T) : Unit = { x; () }\n private[this] var peeked: Option[Int] = None\n private[this] var is_first = true\n protected def read() = {\n val res = peeked match {\n case None => in.read()\n case Some(a) => { peeked = None; a }\n }\n is_first = false\n res\n }\n private def peek() =\n peeked match {\n case None => {\n val res = in.read()\n peeked = Some(res)\n res\n }\n case Some(a) => a\n }\n private def isEnd(c: Int) = c == -1\n private def isCR(c: Int) = c == 13\n private def isLF(c: Int) = c == 10\n private def isNewLine(c: Int) = isLF(c) || isCR(c)\n private def isThereReadable() = !isEnd(peek)\n private def isSpaceOrControl(c: Int) = (0 <= c && c <= 32) || c == 127\n @tailrec\n final private def goNextNotSpaceNorControl() : Unit =\n if(isSpaceOrControl(peek)){\n ignore(read())\n goNextNotSpaceNorControl()\n }\n final private def skipTrailingSpaces() : Unit = {\n @tailrec\n def skipTrailingSpacesAux() : Unit = {\n if(!isNewLine(peek) && isSpaceOrControl(peek)){\n ignore(read())\n skipTrailingSpacesAux()\n }\n }\n skipTrailingSpacesAux()\n }\n final private def skipNewline() : Unit =\n if(!is_first){\n if(isCR(peek))\n ignore(read())\n if(isLF(peek))\n ignore(read())\n }\n private def goNextValuable() : Boolean = {\n goNextNotSpaceNorControl()\n isThereReadable()\n }\n\n private def parseLineToVector[X](parser: () => X) : Vector[X] = {\n import scala.collection.immutable.VectorBuilder\n val vb = new VectorBuilder[X]()\n skipNewline()\n @tailrec\n def parseLineToVectorAux() : Vector[X] =\n if(isNewLine(peek) || isEnd(peek)) {\n vb.result\n }else{\n vb += parser()\n parseLineToVectorAux()\n }\n parseLineToVectorAux()\n }\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\nobject Main {\n def main(args: Array[String]) : Unit = {\n val console = new MyConsole(Console.in, Console.out, Console.err)\n val solver = new Solver(console)\n solver.main()\n console.flush()\n }\n class Solver(val stdio: MyConsole){\n import stdio._ // shadow Console.~\n def main() : Unit = {\n val n, k = nextLong()\n\n if(k != 1) {\n val a = n * (k-1) + 1\n // val b = a + k * (n-1)\n // val c = (a+b)* n / 2\n var c = 0L\n var output = \"\"\n for(i <- (0L until n)) {\n val left_f = (k-1) * i + 1\n val l = left_f until (left_f + k-1)\n assert(l.length == (k-1))\n val m = Seq(a + k * i)\n c += m.head\n val r = (m.head + 1) to (m.head + (n-k))\n assert(r.length == n-k)\n output += ((l ++ m ++ r).mkString(\" \")) + \"\\n\"\n }\n println(c)\n print(output)\n } else {\n println((1L to (n*n) by n).sum)\n for(line <- (1L to (n*n)).grouped(n.toInt)){\n println(line.mkString(\" \"))\n }\n }\n }\n }\n import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}\n class MyConsole(val in: BufferedReader, val _out: PrintStream,\n val err: PrintStream) {\n // PrintWriter do not flush automatically\n val out = new PrintWriter(_out,false)\n // If argument is null, there are ambiguous which function will be called\n def print(obj: Any) = out.print(if(obj == null) \"null\" else obj.toString)\n def println() = out.println()\n def println(obj: Any) = out.println(obj)\n def printf(text: String, args: Any*) = out.printf(text.format(args : _*))\n // NOTE: YOU MUST FLUSH BEFORE END OF MAIN\n def flush() = out.flush()\n def debugln(obj: Any) = err.println(\"\\u001b[36m\" + obj + \"\\u001b[0m\")\n\n def readIntVector() : Vector[Int] = parseLineToVector(() => nextInt)\n def readLongVector() : Vector[Long] = parseLineToVector(() => nextLong)\n def readStringVector() : Vector[String] = parseLineToVector(() => nextString)\n def nextInt() : Int = nextLong().toInt\n def nextBigInt() : BigInt = BigInt(nextString())\n def nextBigDecimal( ) : BigDecimal = BigDecimal(nextString())\n def nextDouble() : Double = nextString().toDouble\n def nextLong() : Long = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading long failed\")\n val sgn = if(peek == '-') -1l else 1\n if(sgn == -1l) ignore(read())\n if(peek < '0' || '9' < peek)\n throw new NumberFormatException(s\"readLong found only '-' or no number\")\n @tailrec\n def readLong(next: Int, cur: Long) : Long =\n if('0' <= next && next <= '9'){\n ignore(read()) // is equal to next\n readLong(peek, cur*10 + next-'0')\n }\n else if(isEnd(next) || isSpaceOrControl(next))\n sgn*cur\n else\n throw new NumberFormatException(s\"readLong found strange byte $next\")\n val res = readLong(peek,0)\n skipTrailingSpaces()\n res\n }\n def nextString() : String = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading String failed\")\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isSpaceOrControl(next)){\n builder.toString\n }else{\n builder.append(read().toChar) // here we skip.\n appendCode(peek)\n }\n }\n val res = appendCode(peek)\n skipTrailingSpaces()\n res\n }\n // TODO: refactoring to marge nextString\n def readLine() : String = {\n if(isEnd(peek))\n throw new NoSuchElementException(\"Reading Line failed\")\n skipNewline()\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isNewLine(next)){\n builder.toString\n }else{\n builder.append(next.toChar)\n appendCode(read())\n }\n }\n appendCode(read())\n }\n // helpers\n private def ignore[T](x: => T) : Unit = { x; () }\n private[this] var peeked: Option[Int] = None\n private[this] var is_first = true\n protected def read() = {\n val res = peeked match {\n case None => in.read()\n case Some(a) => { peeked = None; a }\n }\n is_first = false\n res\n }\n private def peek() =\n peeked match {\n case None => {\n val res = in.read()\n peeked = Some(res)\n res\n }\n case Some(a) => a\n }\n private def isEnd(c: Int) = c == -1\n private def isCR(c: Int) = c == 13\n private def isLF(c: Int) = c == 10\n private def isNewLine(c: Int) = isLF(c) || isCR(c)\n private def isThereReadable() = !isEnd(peek)\n private def isSpaceOrControl(c: Int) = (0 <= c && c <= 32) || c == 127\n @tailrec\n final private def goNextNotSpaceNorControl() : Unit =\n if(isSpaceOrControl(peek)){\n ignore(read())\n goNextNotSpaceNorControl()\n }\n final private def skipTrailingSpaces() : Unit = {\n @tailrec\n def skipTrailingSpacesAux() : Unit = {\n if(!isNewLine(peek) && isSpaceOrControl(peek)){\n ignore(read())\n skipTrailingSpacesAux()\n }\n }\n skipTrailingSpacesAux()\n }\n final private def skipNewline() : Unit =\n if(!is_first){\n if(isCR(peek))\n ignore(read())\n if(isLF(peek))\n ignore(read())\n }\n private def goNextValuable() : Boolean = {\n goNextNotSpaceNorControl()\n isThereReadable()\n }\n\n private def parseLineToVector[X](parser: () => X) : Vector[X] = {\n import scala.collection.immutable.VectorBuilder\n val vb = new VectorBuilder[X]()\n skipNewline()\n @tailrec\n def parseLineToVectorAux() : Vector[X] =\n if(isNewLine(peek) || isEnd(peek)) {\n vb.result\n }else{\n vb += parser()\n parseLineToVectorAux()\n }\n parseLineToVectorAux()\n }\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\nobject Main {\n def main(args: Array[String]) : Unit = {\n val console = new MyConsole(Console.in, Console.out, Console.err)\n val solver = new Solver(console)\n solver.main()\n console.flush()\n }\n class Solver(val stdio: MyConsole){\n import stdio._ // shadow Console.~\n def main() : Unit = {\n val n, k = nextLong()\n\n val a = n * (k-1) + 1\n var c = 0L\n var output = \"\"\n for(i <- (0L until n)) {\n val left_f = (k-1) * i + 1\n val l = left_f until (left_f + k-1)\n assert(l.length == (k-1))\n val m = Seq(a + k * i)\n c += m.head\n val r = (m.head + 1) to (m.head + (n-k))\n assert(r.length == n-k)\n output += ((l ++ m ++ r).mkString(\" \")) + \"\\n\"\n }\n val ca= (k to (n*n) by n).sum\n if(ca >= c){\n println(ca)\n for(line <- (1L to (n*n)).grouped(n.toInt)){\n println(line.mkString(\" \"))\n }\n }else{\n println(c)\n print(output)\n }\n }\n }\n import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}\n class MyConsole(val in: BufferedReader, val _out: PrintStream,\n val err: PrintStream) {\n // PrintWriter do not flush automatically\n val out = new PrintWriter(_out,false)\n // If argument is null, there are ambiguous which function will be called\n def print(obj: Any) = out.print(if(obj == null) \"null\" else obj.toString)\n def println() = out.println()\n def println(obj: Any) = out.println(obj)\n def printf(text: String, args: Any*) = out.printf(text.format(args : _*))\n // NOTE: YOU MUST FLUSH BEFORE END OF MAIN\n def flush() = out.flush()\n def debugln(obj: Any) = err.println(\"\\u001b[36m\" + obj + \"\\u001b[0m\")\n\n def readIntVector() : Vector[Int] = parseLineToVector(() => nextInt)\n def readLongVector() : Vector[Long] = parseLineToVector(() => nextLong)\n def readStringVector() : Vector[String] = parseLineToVector(() => nextString)\n def nextInt() : Int = nextLong().toInt\n def nextBigInt() : BigInt = BigInt(nextString())\n def nextBigDecimal( ) : BigDecimal = BigDecimal(nextString())\n def nextDouble() : Double = nextString().toDouble\n def nextLong() : Long = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading long failed\")\n val sgn = if(peek == '-') -1l else 1\n if(sgn == -1l) ignore(read())\n if(peek < '0' || '9' < peek)\n throw new NumberFormatException(s\"readLong found only '-' or no number\")\n @tailrec\n def readLong(next: Int, cur: Long) : Long =\n if('0' <= next && next <= '9'){\n ignore(read()) // is equal to next\n readLong(peek, cur*10 + next-'0')\n }\n else if(isEnd(next) || isSpaceOrControl(next))\n sgn*cur\n else\n throw new NumberFormatException(s\"readLong found strange byte $next\")\n val res = readLong(peek,0)\n skipTrailingSpaces()\n res\n }\n def nextString() : String = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading String failed\")\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isSpaceOrControl(next)){\n builder.toString\n }else{\n builder.append(read().toChar) // here we skip.\n appendCode(peek)\n }\n }\n val res = appendCode(peek)\n skipTrailingSpaces()\n res\n }\n // TODO: refactoring to marge nextString\n def readLine() : String = {\n if(isEnd(peek))\n throw new NoSuchElementException(\"Reading Line failed\")\n skipNewline()\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isNewLine(next)){\n builder.toString\n }else{\n builder.append(next.toChar)\n appendCode(read())\n }\n }\n appendCode(read())\n }\n // helpers\n private def ignore[T](x: => T) : Unit = { x; () }\n private[this] var peeked: Option[Int] = None\n private[this] var is_first = true\n protected def read() = {\n val res = peeked match {\n case None => in.read()\n case Some(a) => { peeked = None; a }\n }\n is_first = false\n res\n }\n private def peek() =\n peeked match {\n case None => {\n val res = in.read()\n peeked = Some(res)\n res\n }\n case Some(a) => a\n }\n private def isEnd(c: Int) = c == -1\n private def isCR(c: Int) = c == 13\n private def isLF(c: Int) = c == 10\n private def isNewLine(c: Int) = isLF(c) || isCR(c)\n private def isThereReadable() = !isEnd(peek)\n private def isSpaceOrControl(c: Int) = (0 <= c && c <= 32) || c == 127\n @tailrec\n final private def goNextNotSpaceNorControl() : Unit =\n if(isSpaceOrControl(peek)){\n ignore(read())\n goNextNotSpaceNorControl()\n }\n final private def skipTrailingSpaces() : Unit = {\n @tailrec\n def skipTrailingSpacesAux() : Unit = {\n if(!isNewLine(peek) && isSpaceOrControl(peek)){\n ignore(read())\n skipTrailingSpacesAux()\n }\n }\n skipTrailingSpacesAux()\n }\n final private def skipNewline() : Unit =\n if(!is_first){\n if(isCR(peek))\n ignore(read())\n if(isLF(peek))\n ignore(read())\n }\n private def goNextValuable() : Boolean = {\n goNextNotSpaceNorControl()\n isThereReadable()\n }\n\n private def parseLineToVector[X](parser: () => X) : Vector[X] = {\n import scala.collection.immutable.VectorBuilder\n val vb = new VectorBuilder[X]()\n skipNewline()\n @tailrec\n def parseLineToVectorAux() : Vector[X] =\n if(isNewLine(peek) || isEnd(peek)) {\n vb.result\n }else{\n vb += parser()\n parseLineToVectorAux()\n }\n parseLineToVectorAux()\n }\n }\n}\n"}], "src_uid": "272f66f3c71c4997c5a1f0f009c9b99e"} {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b, q) = scala.io.StdIn.readLine().split(\" \").map(BigInt(_))\n\n val m = a.max(b)\n val lcm = a / a.gcd(b) * b\n\n def prefix(p: BigInt): BigInt = {\n val i = p / lcm\n i * m + p.min(i * lcm + m - 1) - i * lcm + 1\n }\n\n val ans = (0 until q.toInt).map { _ =>\n val Array(l, r) = scala.io.StdIn.readLine().split(\" \").map(BigInt(_))\n\n val (i, j) = (l / lcm, r / lcm)\n\n r - l + 1 - prefix(r) + prefix(l - 1)\n }\n\n println(ans.mkString(\" \"))\n }\n}\n", "positive_code": [{"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b, q) = scala.io.StdIn.readLine().split(\" \").map(BigInt(_))\n\n val m = a.max(b)\n val lcm = a / a.gcd(b) * b\n\n (0 until q.toInt).foreach { _ =>\n val Array(l, r) = scala.io.StdIn.readLine().split(\" \").map(BigInt(_))\n\n val (i, j) = (l / lcm, r / lcm)\n\n val ans = List(i, j).distinct.foldLeft(r - l + 1 - (j - i - 1).max(0) * m) { (s, k) =>\n val t = k * lcm\n\n if (t + m - 1 < l) s\n else s - r.min(t + m - 1) + l.max(t) - 1\n }\n\n print(s\"$ans \")\n }\n\n println()\n }\n}\n"}, {"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n\n def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\n\n for (_ <- 1 to nextInt) {\n val a, b, q = nextLong\n val res = Array.ofDim[Long](q.toInt)\n val g = lcm(a, b)\n val m = a max b\n\n def count(i: Long): Long = {\n i / g * (g - m) + Math.max(i % g - m + 1, 0L)\n }\n\n for (i <- 0 until q.toInt) {\n val l, r = nextLong\n res(i) = count(r) - count(l - 1)\n }\n\n out.println(res.mkString(\" \"))\n }\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b, q) = scala.io.StdIn.readLine().split(\" \").map(BigInt(_))\n\n val m = a.max(b)\n val lcm = a / a.gcd(b) * b\n\n (0 until q.toInt).foreach { _ =>\n val Array(l, r) = scala.io.StdIn.readLine().split(\" \").map(BigInt(_))\n\n val (p, q) = (l / lcm, r / lcm)\n\n val ans = (p to q).foldLeft(r - l + 1) { (s, i) =>\n val t = r.min(l.max(i * lcm + m - 1)) - l.max(i * lcm)\n\n if (t == 0) s\n else s - t - 1\n }\n\n print(s\"$ans \")\n }\n\n println()\n }\n}\n"}], "src_uid": "a1effd6a0f6392f46f6aa487158fef7d"} {"source_code": "object A489 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n)\n val res = cu.ArrayBuffer.empty[(Int, Int)]\n for(i <- 0 until n){\n val sl = in.slice(i, n)\n val min = sl.min\n val idx = sl.indexOf(min)\n if(idx != 0) {\n res.append((i, i+idx))\n val temp = in(i+idx)\n in(i+idx) = in(i)\n in(i) = temp\n }\n }\n println(res.length)\n println(res.map{case (x, y) => s\"$x $y\"}.mkString(\"\\n\"))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\nimport scala.collection.mutable.ArrayBuffer\n\nobject _489A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt).toArray\n val buffer = new ArrayBuffer[(Int, Int)]\n\n def doit(i: Int): Unit = {\n if (i < n) {\n val min = (i until n).minBy(i => a(i))\n if (i != min) {\n buffer.append((i, min))\n val cb = a(i)\n a(i) = a(min)\n a(min) = cb\n }\n doit(i + 1)\n }\n }\n\n doit(0)\n\n val ans = buffer.result\n println(ans.length)\n ans.foreach(pair => println(pair._1 + \" \" + pair._2))\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n var data = in.next().split(\" \").map(_.toInt)\n println(data.length - 1)\n println((0 until n - 1).map { i =>\n val index = data.indexOf(data.min) + i\n data(index - i) = data(0)\n data = data.tail\n s\"$i $index\"\n }.mkString(\"\\n\"))\n}"}, {"source_code": "object SB_1 {\n def main(args:Array[String]):Unit={\n val n:Int=readInt()\n val arr:Array[Int]=new Array[Int](n)\n\n val m=readLine()\n val line:Array[String]=m.split(\" \")\n for(i<-0 until arr.length){\n arr(i)=line(i).toInt\n }\n\n var re:List[Array[Int]]=List()\n\n for(i<-0 until arr.length-1){\n var index:Int=i+1\n var sub:Int=arr(i)-arr(i+1)\n var flag:Boolean=false\n for(j<-i+1 until arr.length) {\n if (arr(i) - arr(j) >= sub && arr(i) > arr(j)) {\n sub = arr(i) - arr(j)\n index = j\n flag=true\n }\n }\n\n if(flag==true){\n val temp: Int = arr(i)\n arr(i) = arr(index)\n arr(index) = temp\n re = re ++ List(Array(i, index))\n }\n }\n println(re.length)\n if(re.length>0)\n for(l<-re)\n println(l(0)+\" \"+l(1))\n }\n\n}"}, {"source_code": "object SB_1 {\n def main(args:Array[String]):Unit={\n val n:Int=readInt()\n val arr:Array[Int]=new Array[Int](n)\n\n val m=readLine()\n val line:Array[String]=m.split(\" \")\n for(i<-0 until arr.length){\n arr(i)=line(i).toInt\n }\n\n var re:List[Array[Int]]=List()\n\n for(i<-0 until arr.length-1){\n var index:Int=i+1\n var sub:Int=arr(i)-arr(i+1)\n var flag:Boolean=false\n for(j<-i+1 until arr.length) {\n if (arr(i) - arr(j) >= sub && arr(i) > arr(j)) {\n sub = arr(i) - arr(j)\n index = j\n flag=true\n }\n }\n\n\n if(flag==true){\n val temp: Int = arr(i)\n arr(i) = arr(index)\n arr(index) = temp\n re = re ++ List(Array(i, index))\n }\n }\n\n\n\n println(re.length)\n if(re.length>0)\n for(l<-re)\n println(l(0)+\" \"+l(1))\n }\n\n}"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject SwapSort {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readLongs() : Array[Long] = \n readLine.split(' ').map(_.toLong)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n \n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n def findSwaps(xs: IndexedSeq[Int]) : List[(Int,Int)] = {\n def go(xs: IndexedSeq[Int], acc: List[(Int,Int)]) : List[(Int,Int)] = {\n if (xs.size == 1) acc.reverse\n else {\n val maxIndex = xs.indexOf(xs.max)\n if (maxIndex == xs.size - 1) go(xs.init,acc)\n else {\n val (first,second) = xs.splitAt(maxIndex) \n go ( (first ++ (xs.last +: second.tail)).init, \n (maxIndex, xs.size - 1) :: acc)\n }\n } \n \n }\n go(xs,List())\n }\n \n \n def main(args: Array[String]) : Unit = {\n val n = readInt\n val xs = readInts\n val swaps = findSwaps(xs)\n println(swaps.length)\n swaps.foreach{\n case (i,j) => println(s\"$i $j\")\n }\n }\n \n}"}, {"source_code": "object A {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n if (n == 0) {\n println(0)\n } else {\n val a = readLine().split(\" \").toList.map(_.toInt)\n val steps = find(a, 0, List()).reverse\n println(steps.size)\n steps.foreach(x => println(x._1 + \" \" + x._2))\n }\n }\n\n def find(a: List[Int], pos: Int, steps: List[(Int, Int)]): List[(Int, Int)] = a match {\n case Nil => steps\n case x :: xs => {\n val min = a.min\n if (x == min) find(xs, pos + 1, steps)\n else {\n val p = xs.indexOf(min)\n find(xs.updated(p, x), pos + 1, (pos, pos + p + 1) :: steps)\n }\n }\n }\n}"}, {"source_code": "object A {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n if (n == 0) {\n println(0)\n } else {\n val a = readLine().split(\" \").toList.map(_.toInt)\n val steps = find(a, 0, List()).reverse\n println(steps.size)\n steps.foreach(x => println(x._1 + \" \" + x._2))\n }\n }\n\n def find(a: List[Int], pos: Int, steps: List[(Int, Int)]): List[(Int, Int)] = a match {\n case Nil => steps\n case x :: xs => {\n val min = a.min\n if (x == min) find(xs, pos + 1, steps)\n else {\n val p = xs.indexOf(min)\n val split0 = xs.splitAt(p)\n val split1 = xs.splitAt(p + 1)\n find(List(split0._1, List(x), split1._2).flatten, pos + 1, (pos, pos + p + 1) :: steps)\n }\n }\n }\n}"}], "negative_code": [{"source_code": "object SB_1 {\n def main(args:Array[String]):Unit={\n val n:Int=readInt()\n val arr:Array[Int]=new Array[Int](n)\n\n val m=readLine()\n val line:Array[String]=m.split(\" \")\n for(i<-0 until arr.length){\n arr(i)=line(i).toInt\n }\n\n// var re:List[Array[Int]]=List()\n//\n// for(i<-0 until arr.length-1){\n// var index:Int=i+1\n// var sub:Int=arr(i)-arr(i+1)\n// for(j<-i+1 until arr.length) {\n// if (arr(i) - arr(j) >= sub && arr(i) > arr(j)) {\n// sub = arr(i) - arr(j)\n// index = j\n//\n// val temp: Int = arr(i)\n// arr(i) = arr(j)\n// arr(j) = temp\n// re = re ++ List(Array(i, j))\n// }\n// }\n// }\n\n var re:List[Array[Int]]=List()\n\n for(i<-0 until arr.length-1){\n for (j<-0 until arr.length - 1 - i)\n if (arr(j)>arr(i)) {\n val temp: Int = arr(i)\n arr(i) = arr(j)\n arr(j) = temp\n re = re ++ List(Array(i, j))\n }\n }\n\n\n println(re.length)\n if(re.length>0)\n for(l<-re)\n println(l(0)+\" \"+l(1))\n }\n\n}"}, {"source_code": "object SB_1 {\n def main(args:Array[String]):Unit={\n val n:Int=readInt()\n val arr:Array[Int]=new Array[Int](n)\n\n val m=readLine()\n val line:Array[String]=m.split(\" \")\n for(i<-0 until arr.length){\n arr(i)=line(i).toInt\n }\n\n var re:List[Array[Int]]=List()\n\n for(i<-0 until arr.length-1){\n var index:Int=i+1\n var sub:Int=arr(i)-arr(i+1)\n for(j<-i+1 until arr.length) {\n if (arr(i) - arr(j) >= sub && arr(i) > arr(j)) {\n sub = arr(i) - arr(j)\n index = j\n\n val temp: Int = arr(i)\n arr(i) = arr(j)\n arr(j) = temp\n re = re ++ List(Array(i, j))\n }\n }\n }\n\n\n println(re.length)\n if(re.length>0)\n for(l<-re)\n println(l(0)+\" \"+l(1))\n }\n\n}"}], "src_uid": "b3c6058893f935d88196113fab581cf8"} {"source_code": "import java.io.FileInputStream\nimport java.util.Scanner\nimport scala.annotation.tailrec\n\nobject Main extends App {\n\n val sc = new Scanner(System.in)\n// val sc = new Scanner( new FileInputStream(\"src/input.txt\") )\n\n val n,t,c = sc.nextInt\n val list = List.fill(n)(sc.nextInt)\n\n @tailrec\n def work(l: List[Int], res: List[List[Int]]): List[List[Int]] = {\n l match {\n case Nil =>\n res\n case xs =>\n val r = xs.span(_ <= t)\n if( r._1.size == 0 )\n work( r._2.dropWhile(_ > t), res )\n else\n work(r._2, r._1 :: res)\n }\n }\n\n val res = work(list, List.empty[List[Int]])\n// println(res)\n val ans = res.map(l => l.size - c + 1).filter(_>0).sum\n println(ans)\n}\n", "positive_code": [{"source_code": "import java.util\nimport java.util.StringTokenizer\n\nobject _427B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val t = next.toInt\n val c = next.toInt\n val a = (1 to n).map(i => next.toInt)\n val queue = new util.ArrayDeque[Int]\n var ans = 0\n\n {\n var i = 0\n while(i < c) {\n while(!queue.isEmpty && a(queue.getLast) <= a(i)) queue.pollLast()\n queue.addLast(i)\n i += 1\n }\n if (a(queue.getFirst) <= t) ans += 1\n\n while(i < n) {\n while(!queue.isEmpty && a(queue.getLast) <= a(i)) queue.pollLast()\n queue.addLast(i)\n if (queue.getLast - queue.getFirst + 1 > c) queue.pollFirst()\n if (a(queue.getFirst) <= t) ans += 1\n\n i += 1\n }\n }\n println(ans)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t, c) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt)\n val r = data.foldLeft(0, 0) {\n case ((soFar, l), el) if el > t => (soFar + (if (l >= c) l - c + 1 else 0), 0)\n case ((soFar, l), el) => (soFar, l + 1)\n }\n println(r._1 + (if (r._2 >= c) r._2 - c + 1 else 0))\n}"}, {"source_code": "object B427 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, t, c) = readInts(3)\n val in = readInts(n)\n var res = 0\n var curr = 0\n var i = 0\n while(i < n) {\n if(in(i) > t) curr = 0\n else {\n curr += 1\n if(curr >= c)\n res += 1\n }\n i += 1\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P427B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n // N prisoners\n // C of prisoners to be transfered to another city\n // the severity of the crime\n // contiguous segment\n // crime level should not be greater then T\n\n def solve(): Int = {\n val N, T, C = sc.nextInt\n\n @tailrec\n def loop(acc: Int, p: Int, n: Int): Int = {\n val w = (p - C + 1) max 0\n if (n == N) acc + w\n else if (sc.nextInt > T) loop(acc + w, 0, n + 1)\n else loop(acc, p + 1, n + 1)\n }\n\n loop(0, 0, 0)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.PriorityQueue\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Long = {\n val N, T, C = sc.nextInt\n\n @tailrec\n def loop(acc: Long, i: Int, j: Int): Long = {\n\n @inline\n def ways(k: Int): Int = 0 max (k - C + 1)\n\n if (j == N) acc + ways(i)\n else if (sc.nextInt <= T) loop(acc, i + 1, j + 1)\n else loop(acc + ways(i), 0, j + 1)\n }\n\n loop(0, 0, 0)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject _427_B extends App {\n val input = readLine().split(\" \").map(_.toInt)\n val n = input(0)\n val t = input(1)\n val c = input(2)\n\n val prisoners = readLine().split(\" \").map(_.toInt)\n\n var answer = 0\n var counter = 0\n for (i <- 0 until n) {\n if (prisoners(i) <= t) counter += 1\n else counter = 0\n\n if (counter == c) {\n answer += 1\n counter -= 1\n }\n }\n\n println(answer)\n}\n"}, {"source_code": "object Transfer extends App {\n\tval Array(n, t, c) = readLine.split(' ').map(_.toInt)\n\tval ok = readLine.split(' ').map(_.toInt).map(_ <= t)\n\tvar (ans, i, j) = (0, 0, 0)\n\twhile (i < n) {\n\t\tif (ok(i)) {\n\t\t\tj = i\n\t\t\twhile (j < n && ok(j)) j += 1\n\t\t\tif (j - i >= c) ans += j - i - c + 1\n\t\t\ti = j\n\t\t} else i += 1\n\t}\n\tprint(ans)\n}\n"}, {"source_code": "object B extends App {\n val sc = new java.util.Scanner(System.in)\n val n, t, c = sc.nextInt()\n val al = Array.fill(n)(sc.nextInt())\n def func(p:Int, ct:Int):List[Int] = {\n if (p == al.length) List[Int]()\n else al(p) match {\n case x if x > t => 0 :: func(p+1, 0)\n case _ => ct+1 :: func(p+1, ct+1)\n }\n }\n println(func(0, 0).count(_ >= c))\n}\n"}], "negative_code": [], "src_uid": "7d1e8769a6b1d5c6680ab530d19e7fa4"} {"source_code": "import scala.io.StdIn._\n\nobject TaskB extends App {\n val l = readLine.takeRight(2).toInt\n val p = (1 :: Nil) :: (6 :: 2 :: 4 :: 8 :: Nil) :: (1 :: 3 :: 9 :: 7 :: Nil) :: (6 :: 4 :: Nil) :: Nil\n\n println(if (l == 0) 4 else (p.map(_.toArray).map(a => a(l % a.length)).sum) % 5)\n}\n", "positive_code": [{"source_code": "\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 08.08.14.\n */\nobject B extends App {\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n\n def nextLong = in.nextLong\n\n def nextDouble = in.nextDouble\n\n def nextString = in.next\n\n def solve() = {\n val n = nextString\n if (n.takeRight(2).toInt % 4 == 0) {\n out.println(4)\n } else {\n out.println(0)\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}\n\n\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _456B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val _1 = Array(1, 1, 1, 1)\n val _2 = Array(1, 2, 4, 3)\n val _3 = Array(1, 3, 4, 2)\n val _4 = Array(1, 4, 1, 4)\n\n val n = next.takeRight(2).toInt % 4\n val ans = (_1(n) + _2(n) + _3(n) + _4(n)) % 5\n println(ans)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val n = str.takeRight(2).toInt\n if (n % 4 == 0) println(\"4\")\n else println(\"0\")\n\n}"}, {"source_code": "object B456 {\n\n import IO._\n\n def powMod(a: Int, pow: Int, mod: Int): Int = {\n if(pow == 0L) 1\n else {\n val half = powMod(a, pow/2, mod)\n if(pow%2 == 0) {\n (half*half)%mod\n } else {\n (a * (half*half)%mod)%mod\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n var x = read.takeRight(2).toInt\n println((powMod(1, x%4, 5) + powMod(2, x%4, 5) + powMod(3, x%4, 5) + powMod(4, x%4, 5))%5)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object Main {\n val cin = scala.io.Source.stdin.getLines()\n def main(args: Array[String]) = {\n println(if(BigInt(cin.next().takeRight(2).toInt) % 4 > 0) 0 else 4)\n }\n}\n"}, {"source_code": "object Main {\n\n def main(args: Array[String]): Unit = {\n val ln = io.StdIn.readLine()\n print(if (Integer.parseInt(if (ln.length < 3) ln else ln.substring(ln.length - 2)) % 4 == 0) 4 else 0)\n }\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject TaskB extends App {\n val l = readLine.last - '0'\n val p = (1 :: Nil) :: (6 :: 2 :: 4 :: 8 :: Nil) :: (1 :: 3 :: 9 :: 7 :: Nil) :: (6 :: 4 :: Nil) :: Nil\n\n println(if (l == 0) 4 else (p.map(_.toArray).map(a => a(l % a.length)).sum) % 5)\n}\n"}], "src_uid": "74cbcbafbffc363137a02697952a8539"} {"source_code": "import scala.collection._\r\nimport scala.collection.mutable.TreeSet\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport scala.io.StdIn._\r\nimport scala.util._\r\n\r\n\r\nobject z {\r\n def main(args: Array[String]): Unit = {\r\n val t = readInt()\r\n\r\n for (i <- 1 to t) {\r\n readLine()\r\n val line = readLine()\r\n\r\n val seen = Array.ofDim[Boolean](200)\r\n var lastchar = 0.toChar\r\n var done = false\r\n line.foreach(c => {\r\n if (c != lastchar) {\r\n seen(lastchar.toInt) = true;\r\n }\r\n\r\n if (seen(c) && !done) {\r\n println(\"NO\")\r\n done = true\r\n }\r\n lastchar = c\r\n })\r\n\r\n if (!done) {\r\n println(\"YES\")\r\n }\r\n }\r\n }\r\n}", "positive_code": [{"source_code": "import sun.management.counter.Counter\n\nimport java.io.BufferedReader\nimport java.io.BufferedWriter\nimport java.io.InputStreamReader\nimport java.io.OutputStreamWriter\nimport java.io.PrintWriter\nimport java.util.StringTokenizer\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.Source\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n\n val lines = Source.fromInputStream(System.in).getLines()\n val writer = new PrintWriter(System.out)\n\n val testNumber = lines.next().toInt\n 1.to(testNumber).foreach { _ =>\n val size = lines.next().toInt\n val string = lines.next()\n\n def findAnswer(index: Int, restrictedChars: Set[Char]): Boolean =\n if (index == size) true\n else if (restrictedChars.contains(string(index))) false\n else if (index + 1 < size && string(index + 1) != string(index)) findAnswer(index + 1, restrictedChars + string(index))\n else findAnswer(index + 1, restrictedChars)\n\n val answer = if (findAnswer(0, Set.empty)) \"YES\" else \"NO\"\n writer.append(StringBuilder.newBuilder.append(answer).append(\"\\n\"))\n }\n writer.close()\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}], "negative_code": [], "src_uid": "3851854541b4bd168f5cb1e8492ed8ef"} {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(l, r, m) = readLine().split(\" \").map(_.toLong)\n\n val (p, q) = (m + l - r, m + r - l)\n\n (l to r).view.map(a => (q / a, a)).collectFirst {\n case (n, a) if n > 0 && n * a >= p && n * a <= q =>\n if (n * a - m < 0) (a, l + m - n * a, l)\n else (a, r + m - n * a, r)\n } match {\n case Some((a, b, c)) => println(s\"$a $b $c\")\n case None => throw new Error(\"unexpeted exception\")\n }\n }\n}\n", "positive_code": [{"source_code": "object B {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val l, r, m = nextLong\n val d = r - l\n var a = l\n while (a <= r) {\n var n = math.max(1, m / a)\n if (a * n <= m && a * n + d >= m) {\n val c = l\n val b = m - a * n + c\n out.println(s\"$a $b $c\")\n a = r\n } else {\n n = math.max(1, (m + d) / a)\n if (a * n - d <= m && a * n >= m) {\n val c = r\n val b = m - a * n + c\n out.println(s\"$a $b $c\")\n a = r\n }\n }\n a += 1\n }\n }\n\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n\n def nextInt = Integer.parseInt(nextToken)\n\n def nextLong = java.lang.Long.parseLong(nextToken)\n\n def nextBig = BigInt(nextToken)\n\n def nextInts(n: Int) = Array.fill(n) {\n nextInt\n }\n\n def nextLongs(n: Int) = Array.fill(n) {\n nextLong\n }\n\n def nextBigs(n: Int) = Array.fill(n) {\n nextBig\n }\n\n def nextLine = in.readLine\n }\n\n}\n"}], "negative_code": [{"source_code": "object B {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val l, r, m = nextLong\n val d = r - l\n var a = l\n while (a <= r) {\n val n = math.max(1, (m + (d + 1) / 2) / a)\n if (a * n <= m && a * n + d >= m) {\n val c = l\n val b = m - a * n + c\n out.println(s\"$a $b $c\")\n a = r\n } else if (a * n - d <= m && a * n >= m) {\n val c = r\n val b = m - a * n + c\n out.println(s\"$a $b $c\")\n a = r\n }\n a += 1\n }\n }\n\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n\n def nextInt = Integer.parseInt(nextToken)\n\n def nextLong = java.lang.Long.parseLong(nextToken)\n\n def nextBig = BigInt(nextToken)\n\n def nextInts(n: Int) = Array.fill(n) {\n nextInt\n }\n\n def nextLongs(n: Int) = Array.fill(n) {\n nextLong\n }\n\n def nextBigs(n: Int) = Array.fill(n) {\n nextBig\n }\n\n def nextLine = in.readLine\n }\n\n}\n"}, {"source_code": "object B {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val l, r, m = nextLong\n val d = r - l\n var a = l\n while (a <= r) {\n val n = math.max(1, m / a)\n if (a * n <= m && a * n + d >= m) {\n val c = l\n val b = m - a * n + c\n out.println(s\"$a $b $c\")\n a = r\n } else if (a * n - d <= m) {\n val c = r\n val b = m - a * n + c\n out.println(s\"$a $b $c\")\n a = r\n }\n a += 1\n }\n }\n\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n\n def nextInt = Integer.parseInt(nextToken)\n\n def nextLong = java.lang.Long.parseLong(nextToken)\n\n def nextBig = BigInt(nextToken)\n\n def nextInts(n: Int) = Array.fill(n) {\n nextInt\n }\n\n def nextLongs(n: Int) = Array.fill(n) {\n nextLong\n }\n\n def nextBigs(n: Int) = Array.fill(n) {\n nextBig\n }\n\n def nextLine = in.readLine\n }\n\n}\n"}, {"source_code": "object B {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val l, r, m = nextLong\n val d = r - l\n var a = l\n var n = math.max(1, m / a)\n// println(n)\n if (a * n <= m && a * n + d >= m) {\n val c = l\n val b = m - a * n + c\n out.println(s\"$a $b $c\")\n } else {\n //n += 1 //math.max(1, m / a)\n if (a * n - d <= m) {\n val c = r\n val b = m - a * n + c\n out.println(s\"$a $b $c\")\n }\n }\n }\n\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n\n def nextInt = Integer.parseInt(nextToken)\n\n def nextLong = java.lang.Long.parseLong(nextToken)\n\n def nextBig = BigInt(nextToken)\n\n def nextInts(n: Int) = Array.fill(n) {\n nextInt\n }\n\n def nextLongs(n: Int) = Array.fill(n) {\n nextLong\n }\n\n def nextBigs(n: Int) = Array.fill(n) {\n nextBig\n }\n\n def nextLine = in.readLine\n }\n\n}\n"}, {"source_code": "object B {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val l, r, m = nextLong\n val d = r - l\n var a = l\n while (a <= r) {\n val n = math.max(1, (m + d / 2) / a)\n if (a * n <= m && a * n + d >= m) {\n val c = l\n val b = m - a * n + c\n out.println(s\"$a $b $c\")\n a = r\n } else if (a * n - d <= m && a * n >= m) {\n val c = r\n val b = m - a * n + c\n out.println(s\"$a $b $c\")\n a = r\n }\n a += 1\n }\n }\n\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n\n def nextInt = Integer.parseInt(nextToken)\n\n def nextLong = java.lang.Long.parseLong(nextToken)\n\n def nextBig = BigInt(nextToken)\n\n def nextInts(n: Int) = Array.fill(n) {\n nextInt\n }\n\n def nextLongs(n: Int) = Array.fill(n) {\n nextLong\n }\n\n def nextBigs(n: Int) = Array.fill(n) {\n nextBig\n }\n\n def nextLine = in.readLine\n }\n\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(l, r, m) = readLine().split(\" \").map(_.toLong)\n\n val (p, q) = (m + l - r, m + r - l)\n\n (l to r).collectFirst {\n case a if q / a > 0 && q / a * a >= p && q / a * a <= q => (a, l, r)\n } match {\n case Some((a, b, c)) => println(s\"$a $b $c\")\n case None => throw new Error(\"unexpeted exception\")\n }\n }\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(l, r, m) = readLine().split(\" \").map(_.toLong)\n\n val (p, q) = (m + l - r, m + r - l)\n\n (l to r).view.map(a => (q / a, a)).collectFirst {\n case (n, a) if n > 0 && n * a >= p && n * a <= q =>\n (a, l + m - n * a, l)\n } match {\n case Some((a, b, c)) => println(s\"$a $b $c\")\n case None => throw new Error(\"unexpeted exception\")\n }\n }\n}\n"}], "src_uid": "39d8677b310bee8747c5112af95f0e33"} {"source_code": "import scala.collection.mutable\n\nobject B extends App {\n val Array(n) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val a = mutable.HashMap.empty[String, Int]\n (1 to n).foreach { i =>\n a += scala.io.StdIn.readLine() -> i\n }\n\n a.toSeq.sortBy(-_._2).foreach(q => println(q._1))\n}\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map(_ => in.next()).reverse.distinct\n println(data.mkString(\"\\n\"))\n}\n"}, {"source_code": "/**\n * Created by AngrySCV on 18.03.16.\n * https://github.com/angrySCV\n * https://vk.com/angrySCV\n */\n\nimport scala.collection.mutable\n\nobject B extends App {\n val count = Console.in.readLine().toInt\n\n var hranilishe = mutable.HashMap[String, Int]()\n var globalCounter = 0\n (1 to count).foreach(item => {\n hranilishe.update(Console.in.readLine(), globalCounter)\n globalCounter += 1\n })\n hranilishe.toSeq.sortWith(_._2 > _._2).map(_._1).foreach(println)\n\n}\n"}, {"source_code": "import java.io._\nimport java.nio.file._\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * @author itegulov\n */\nobject B extends App {\n\n import scala.collection.mutable.{Map => MMap}\n\n val in: Scanner = new Scanner(System.in)\n val out: PrintWriter = new PrintWriter(System.out)\n\n val n = in.nextInt()\n val map: MMap[String, Int] = MMap()\n\n for (i <- 1 to n) map(in.next()) = i\n\n val answer: List[String] = map.map(_.swap).toList.sortWith((a, b) => a._1 > b._1).map(_._2)\n\n for (name <- answer) {\n out.println(name)\n }\n\n in.close()\n out.close()\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine())\n .takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next() = tokenizer().get.nextToken()\n\n override def hasNext = tokenizer().nonEmpty\n\n override def close() = reader.close()\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.nio.file._\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * @author itegulov\n */\nobject B extends App {\n\n import scala.collection.mutable.{Map => MMap}\n\n val in: Scanner = new Scanner(System.in)\n val out: PrintWriter = new PrintWriter(System.out)\n\n val n = in.nextInt()\n val map: MMap[String, Int] = MMap()\n\n for (i <- 1 to n) map(in.next()) = i\n\n map.map(_.swap).toList.sortWith((a, b) => a._1 > b._1).map(_._2).foreach(out.println)\n\n in.close()\n out.close()\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine())\n .takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next() = tokenizer().get.nextToken()\n\n override def hasNext = tokenizer().nonEmpty\n\n override def close() = reader.close()\n }\n\n}"}], "negative_code": [{"source_code": "/**\n * Created by AngrySCV on 18.03.16.\n * https://github.com/angrySCV\n * https://vk.com/angrySCV\n */\n\nimport scala.collection.mutable\n\nobject B extends App {\n val count = Console.in.readLine()\n val name = Console.in.readLine().split(\" \")\n var hranilishe = mutable.HashMap[String, Int]()\n var globalCounter = 0\n name.foreach(item => {\n hranilishe.update(item, globalCounter)\n globalCounter += 1\n })\n hranilishe.toSeq.sortWith(_._2 > _._2).map(_._1).foreach(println)\n\n}\n"}], "src_uid": "18f4d9262150294b63d99803250ed49c"} {"source_code": "//package codeforces.contest1244\n\nobject RoomsAndStaircases {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt()) {\n\n val total = io.StdIn.readInt()\n val stairs = io.StdIn.readLine()\n\n val leftmost = stairs.indexOf('1')\n val rightmost = stairs.lastIndexOf('1')\n\n println {\n if (leftmost != -1 && rightmost != -1)\n ((rightmost + 1) * 2) max (total - rightmost) * 2 max total max ((leftmost + 1) * 2) max (total - leftmost) * 2\n else total\n }\n }\n }\n\n}\n", "positive_code": [{"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n\n for (_ <- 1 to t) {\n val n = nextInt\n val s = nextLine\n val l = s.indexWhere(_ == '1')\n val r = s.lastIndexWhere(_ == '1')\n val res = if (l == -1) n\n else {\n val d = math.max(r + 1, n - l)\n val a = 2 * d\n val b = n + s.count(_ == '1')\n math.max(a, b)\n }\n out.println(res)\n }\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "23575500451a061ed498468f3814c38a"} {"source_code": "import scala.io.StdIn\r\n\r\nobject Main extends App {\r\n val t = StdIn.readLine().toInt\r\n for (_ <- 0 until t) {\r\n StdIn.readLine().toInt\r\n val a_max:Int = StdIn.readLine().split(\" \").map(_.toInt).max\r\n StdIn.readLine().toInt\r\n val b_max:Int = StdIn.readLine().split(\" \").map(_.toInt).max\r\n println(if (a_max >= b_max) \"Alice\" else \"Bob\")\r\n println(if (b_max >= a_max) \"Bob\" else \"Alice\")\r\n }\r\n}\r\n", "positive_code": [{"source_code": "/*\nhttps://codeforces.com/contest/1681/problem/A\n */\n//package round_129\n\nimport scala.collection.mutable\nimport scala.io.StdIn\n\nobject task_A extends App {\n def solving(x: Array[Int], y: Array[Int]) = {\n val max_x = x.max\n val max_y = y.max\n if (max_x > max_y) {\n 1\n }\n else if (max_x < max_y) {\n -1\n }\n else {\n 0\n }\n }\n\n var sb = new StringBuilder()\n val t = StdIn.readLine().toInt\n for (i <- 0 until(t)) {\n val n = StdIn.readLine().toInt\n val a = StdIn.readLine().split(\" \").map(_.toInt)\n// val a = Array(n)\n// for (ii <- 0 until(n)) a(ii) = StdIn.readLine().split(\" \").toInt\n val m = StdIn.readLine().toInt\n val b = StdIn.readLine().split(\" \").map(_.toInt)\n// val b = Array(m)\n// for (ii <- 0 until(m)) b(ii) = StdIn.readLine().toInt\n val ans = solving(a, b)\n if (ans == 1) {\n// println(\"Alice\")\n// println(\"Alice\")\n\n sb.append(\"Alice\").append(\"\\n\").append(\"Alice\").append(\"\\n\")\n }\n else if (ans == -1) {\n// println(\"Bob\")\n// println(\"Bob\")\n\n sb.append(\"Bob\").append(\"\\n\").append(\"Bob\").append(\"\\n\")\n }\n else {\n// println(\"Alice\")\n// println(\"Bob\")\n\n sb.append(\"Alice\").append(\"\\n\").append(\"Bob\").append(\"\\n\")\n\n }\n }\n\n print(sb)\n}\n"}, {"source_code": "/*\nhttps://codeforces.com/contest/1681/problem/A\n */\n//package round_129\n\nimport scala.io.StdIn\n\nobject task_A extends App {\n def solving(x: Array[Int], y: Array[Int]) = {\n val max_x = x.max\n val max_y = y.max\n if (max_x > max_y) {\n 1\n }\n else if (max_x < max_y) {\n -1\n }\n else {\n 0\n }\n }\n\n val t = StdIn.readLine().toInt\n for (i <- 0 until(t)) {\n val n = StdIn.readLine().toInt\n val a = StdIn.readLine().split(\" \").map(_.toInt)\n// val a = Array(n)\n// for (ii <- 0 until(n)) a(ii) = StdIn.readLine().split(\" \").toInt\n val m = StdIn.readLine().toInt\n val b = StdIn.readLine().split(\" \").map(_.toInt)\n// val b = Array(m)\n// for (ii <- 0 until(m)) b(ii) = StdIn.readLine().toInt\n val ans = solving(a, b)\n if (ans == 1) {\n println(\"Alice\")\n println(\"Alice\")\n }\n else if (ans == -1) {\n println(\"Bob\")\n println(\"Bob\")\n }\n else {\n println(\"Alice\")\n println(\"Bob\")\n }\n\n }\n}\n"}], "negative_code": [], "src_uid": "581c89736e549300c566e4700b741906"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt)\n var rest = k\n for(i <- 1 to 2 * n by 2) {\n if (rest != 0 && a(i) - 1 > a(i - 1) && a(i) - 1 > a(i + 1)) {\n a(i) -= 1\n rest-= 1\n }\n }\n println(a.mkString(\" \"))\n } \n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val temp = readLine.split(\" \")\n val n = temp(0).toInt\n var k = temp(1).toInt\n val a = readLine.split(' ') map (_.toInt)\n assert(a.length == 2 * n + 1)\n\n for(i <- 0 to 2 * n) {\n if(k != 0 && i % 2 == 1 && a(i)-a(i-1) > 1 && a(i) - a(i+1) > 1) {\n a(i) -=1\n k -= 1\n }\n print(a(i) + \" \")\n }\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt)\n var rest = k\n val tr = a.map{ i =>\n if (i > 0 && rest != 0) { rest -= 1; i - 1}\n else i\n }\n println(tr.mkString(\" \"))\n } \n}"}], "src_uid": "1adb4675dc88208f8a05a2db49bb44cb"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val n = ni()\n val Ps = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer())\n REP(n) { _ =>\n val m, p = ni()\n Ps(m) += p\n }\n var pref = n\n var cnt = 0\n var ans = 0L\n val q = new java.util.PriorityQueue[Int]\n REP_r(n) { i =>\n pref -= Ps(i).length\n REP(Ps(i).length) { j =>\n q.add(Ps(i)(j))\n }\n val need = i - pref\n while(cnt < need) {\n cnt += 1\n ans += q.poll()\n }\n }\n out.println(ans)\n }\n }\n}", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n\n case class Voter(p: Int, m: Int)\n\n def sort(a: Array[Int]): Array[Int] = {\n val n = a.length\n REP(n) { i =>\n val j = scala.util.Random.nextInt(n - i) + i\n val tmp = a(i)\n a(i) = a(j)\n a(j) = tmp\n }\n java.util.Arrays.sort(a)\n a\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n import java.util.Comparator\n val n = ni()\n val V = Array.ofDim[Voter](n)\n REP(n) { i =>\n val m, p = ni()\n V(i) = Voter(p, m)\n }\n sort(V, new Comparator[Voter] {\n override def compare(o1: Voter, o2: Voter): Int = Integer.compare(o1.m, o2.m)\n })\n val inf = 1e18.toLong\n var cur, next = Array.ofDim[Long](n)\n var s = 0\n def process(i: Int): Unit = {\n debug(s\"process($i)\")\n import java.util\n util.Arrays.fill(next, inf)\n\n val len = i - s + 1\n val p = Array.ofDim[Int](len)\n REP(len) { j =>\n p(j) = V(s + j).p\n }\n Workspace.sort(p)\n val cum = cumSum(p)\n REP(len + 1) { j =>\n var k = 0\n while(k < n) {\n if (j == len || s + j + k >= V(i).m) {\n if (k + j < n) next(k) = min(next(k), cur(k + j) + cum(j))\n }\n k += 1\n }\n }\n\n debug(next)\n\n val t = cur\n cur = next\n next = t\n s = i + 1\n }\n\n REP(n) { i =>\n if (i > 0 && V(i).m != V(i - 1).m) {\n process(i - 1)\n }\n }\n process(n - 1)\n out.println(cur(0))\n }\n }\n}"}], "negative_code": [], "src_uid": "cc64dfbaadc7f9deae23c71df52d7326"} {"source_code": "object Main {\n def genRow(rowMax: Int, centerMax: Int) = {\n (0 until (centerMax - rowMax)).map(_ => \" \") ++ rowData(rowMax)\n }\n \n def rowData(rowMax: Int) = {\n ((0 until rowMax) ++ (rowMax to 0 by -1)).map(_.toString)\n }\n\n def main(args: Array[String]) {\n val num = readInt()\n for (i <- (0 until num) ++ (num to 0 by -1)) {\n println(genRow(i, num).mkString(\" \"))\n }\n }\n}", "positive_code": [{"source_code": "import scala.collection.mutable.Queue\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val arr = (0 until 2*n+1).foldLeft(List[Array[Char]]())((l,i)=>(\" \"*(2*n+1-Math.abs(i-n))).toCharArray()+:l).toArray\n val que= Queue((n,n,n))\n while(!que.isEmpty){\n val (x,y,v) = que.dequeue\n if(v>=0 && arr(y)(x)==' '){\n arr(y)(x) = (\"\"+v)(0)\n List((0,1),(1,0),(0,-1),(-1,0)).map(dir=>que.enqueue((x+dir._1,y+dir._2,v-1)))\n }\n }\n arr.map(x=>println(x.mkString(\" \")))\n }\n\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _118B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt + 1\n for (i <- 0 until n) {\n print((1 to 2 * (n - 1 - i)).map(i => ' ').mkString)\n for (j <- 0 to i) print(j + (if (j < i) \" \" else \"\"))\n for (j <- (i - 1).to(0, -1)) print(\" \" + j)\n println\n }\n for (i <- (n - 2).to(0, -1)) {\n print((1 to 2 * (n - 1 - i)).map(i => ' ').mkString)\n for (j <- 0 to i) print(j + (if (j < i) \" \" else \"\"))\n for (j <- (i - 1).to(0, -1)) print(\" \" + j)\n println\n }\n}\n"}, {"source_code": "object B118 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val res = Array.fill(n+1)(Array.fill[Char](2*n+1)(' '))\n for(i <- 0 until n+1; j <- 0 until 2*n+1) {\n if(i + j >= n && j <= n) {\n res(i)(j) = ('0' + (i+j) - n).toChar\n } else if (j > n && j <= i+n) {\n res(i)(j) = ('0' + i+n - j).toChar\n }\n }\n\n println(res.map(_.mkString(\" \")).map(_.replaceAll(\"\"\"(?m)\\s+$\"\"\", \"\")).mkString(\"\\n\"))\n println(res.dropRight(1).reverse.map(_.mkString(\" \")).map(_.replaceAll(\"\"\"(?m)\\s+$\"\"\", \"\")).mkString(\"\\n\"))\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject B extends App {\n\tval n = new Scanner(System.in).nextInt()\n\tfor (i <- 0 until 2 * n + 1) {\n\t\tval line = new StringBuffer()\n\t\tval numberOfSpaces = (n - i).abs\n\t\tval max = (2 * n - i) min i\n\t\tfor (_ <- 1 to numberOfSpaces) line.append(\" \")\n\t\tfor (j <- 0 to max) {\n\t\t\tline.append(j)\n\t\t\tline.append(' ')\n\t\t}\n\t\tfor (j <- max - 1 to 0 by -1) {\n\t\t\tline.append(j)\n\t\t\tline.append(' ')\n\t\t}\n\t\tline.deleteCharAt(line.length() - 1)\n\t\tprintln(line.toString)\n\t}\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P118B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n\n def line(i: Int): String = {\n \" \" * 2 * (N - i) + ((0 until i) ++ List.range(i, -1, -1)).mkString(\" \")\n }\n\n for (i <- (0 until N) ++ List.range(N, -1, -1))\n out.println(line(i))\n out.close\n}\n"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _118B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n for (i <- 0 until n) {\n print((1 to 2 * (n - 1 - i)).map(i => ' ').mkString)\n for (j <- 0 to i) print(j + \" \")\n for (j <- (i - 1).to(0, -1)) print(j + (if (j > 0) \" \" else \"\"))\n println\n }\n for (i <- (n - 2).to(0, -1)) {\n print((1 to 2 * (n - 1 - i)).map(i => ' ').mkString)\n for (j <- 0 to i) print(j + \" \")\n for (j <- (i - 1).to(0, -1)) print(j + (if (j > 0) \" \" else \"\"))\n println\n }\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _118B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt + 1\n for (i <- 0 until n) {\n print((1 to 2 * (n - 1 - i)).map(i => ' ').mkString)\n for (j <- 0 to i) print(j + \" \")\n for (j <- (i - 1).to(0, -1)) print(j + (if (j > 0) \" \" else \"\"))\n println\n }\n for (i <- (n - 2).to(0, -1)) {\n print((1 to 2 * (n - 1 - i)).map(i => ' ').mkString)\n for (j <- 0 to i) print(j + \" \")\n for (j <- (i - 1).to(0, -1)) print(j + (if (j > 0) \" \" else \"\"))\n println\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject B extends App {\n\tval n = new Scanner(System.in).nextInt()\n\tfor (i <- 0 until 2 * n + 1) {\n\t\tval line = new StringBuffer()\n\t\tval numberOfSpaces = (n - i).abs\n\t\tval max = (2 * n - i) min i\n\t\tfor (_ <- 1 to numberOfSpaces) line.append(' ')\n\t\tfor (j <- 0 to max) line.append(j)\n\t\tfor (j <- max - 1 to 0 by -1) line.append(j)\n\t\tprintln(line.toString)\n\t}\n}\n"}, {"source_code": "import scala.collection.mutable.Queue\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val arr = (0 until 2*n+1).foldLeft(List[Array[Char]]())((l,i)=>(\" \"*(2*n+1-Math.abs(i-n))).toCharArray()+:l).toArray\n val que= Queue((n,n,n))\n while(!que.isEmpty){\n val (x,y,v) = que.dequeue\n if(v>=0 && arr(y)(x)==' '){\n arr(y)(x) = (\"\"+v)(0)\n List((0,1),(1,0),(0,-1),(-1,0)).map(dir=>que.enqueue((x+dir._1,y+dir._2,v-1)))\n }\n }\n arr.map(x=>println(x.mkString))\n }\n\n}"}, {"source_code": "import scala.collection.mutable.Queue\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val arr = (1 to 2*n+1).foldLeft(List[Array[Char]]())((l,_)=>(\" \"*(2*n+1)).toCharArray()+:l).toArray\n val que= Queue((n,n,n))\n while(!que.isEmpty){\n val (x,y,v) = que.dequeue\n if(v>=0 && arr(y)(x)==' '){\n arr(y)(x) = (\"\"+v)(0)\n List((0,1),(1,0),(0,-1),(-1,0)).map(dir=>que.enqueue((x+dir._1,y+dir._2,v-1)))\n }\n }\n arr.map(x=>println(x.mkString))\n }\n\n}"}], "src_uid": "7896740b6f35010af751d3261b5ef718"} {"source_code": "object CodeforcesRound666a {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val n = rl_int\n val sa = (1 to n).flatMap(_ => rl)\n val res = sa.groupBy(identity).mapValues(_.size).values.forall(_ % n == 0)\n writer.println(if (res) \"YES\" else \"NO\")\n }\n\n def sqr(a: Long): Long = a * a\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject taskA extends App {\n\n val sets = readInt\n var lst: List[String] = List()\n\n def check(input: String, len: Int): String = {\n var checked: scala.collection.mutable.Map[Char, Int] = scala.collection.mutable.Map()\n (0 until input.length()).foreach { x =>\n val char = input.charAt(x)\n if (checked.contains(char)) checked(char) += 1\n else checked += (char -> 1)\n }\n\n if (checked.values.filter(_ % len == 0).size == checked.size) \"YES\"\n else \"NO\"\n }\n\n (1 to sets).foreach { _ =>\n val strs = readInt\n var whole: String = \"\"\n (1 to strs).foreach(_ => whole += readLine)\n lst = lst ::: List(check(whole, strs))\n }\n\n lst.foreach { x =>\n println(x)\n }\n\n\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val m = in.nextInt()\n\n var test = \"\"\n m.times({\n test += in.nextLine()\n })\n val r = test.groupBy(x => x).exists(x => x._2.size % m != 0)\n if (r) println(\"NO\") else println(\"YES\")\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextLineInt(n: Int): ArrayBuffer[Int] = {\n var data = ArrayBuffer[Int]()\n n.times({\n data += nextInt()\n })\n data\n }\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject taskA extends App {\n\n val sets = readInt\n var lst: List[String] = List()\n\n def check(input: String, len: Int): String = {\n var checked: scala.collection.mutable.Map[Char, Int] = scala.collection.mutable.Map()\n (1 until input.length()).foreach { x =>\n val char = input.charAt(x)\n if (checked.contains(char)) checked(char) += 1\n else checked += (char -> 1)\n }\n if (checked.values.toList.filter(_ % len != 0).isEmpty) \"NO\"\n else \"YES\"\n\n }\n\n (1 to sets).foreach { _ =>\n val strs = readInt\n var whole: String = \"\"\n (0 until strs).foreach(_ => whole += readLine)\n lst = lst ::: List(check(whole, strs))\n }\n\n lst.foreach { x =>\n println(x)\n }\n\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject taskA extends App {\n\n val sets = readInt\n var lst: List[String] = List()\n\n def check(input: String, len: Int): String = {\n var checked: scala.collection.mutable.Map[Char, Int] = scala.collection.mutable.Map()\n (0 until input.length()).foreach { x =>\n val char = input.charAt(x)\n if (checked.contains(char)) checked(char) += 1\n else checked += (char -> 1)\n }\n println()\n println(checked)\n if (checked.values.filter(_ % len == 0).size == checked.size) \"YES\"\n else \"NO\"\n }\n\n (1 to sets).foreach { _ =>\n val strs = readInt\n var whole: String = \"\"\n (1 to strs).foreach(_ => whole += readLine)\n lst = lst ::: List(check(whole, strs))\n }\n\n lst.foreach { x =>\n println(x)\n }\n\n\n}\n"}], "src_uid": "3d6cd0a82513bc2119c9af3d1243846f"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n var p = 1\n val A = Array.ofDim[Int](N + 1)\n TO(2, N) { i =>\n if (A(i) == 0) {\n var d = i\n A(d) = p\n while (d + i <= N) {\n d += i\n A(d) = p\n }\n p += 1\n }\n }\n\n out.println(A.drop(2).mkString(\" \"))\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = readInt\n var c = 1\n val arr = new Array[Int](n+1)\n for(i <- 2 to n) {\n if (arr(i) == 0) {\n arr(i) = c\n for (j <- i to n by i) {\n arr(j) = c\n }\n c += 1\n }\n }\n println(arr.tail.tail.mkString(\" \"))\n }\n}\n"}], "negative_code": [], "src_uid": "aa3c015c20cb0c1789661fdc78ae9bec"} {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val n = readInt\n val a = readInts\n val Array(i, j) = readInts\n def ans = a.take(j - 1).sum -a.take(i - 1).sum\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject a14 {\n def main(args: Array[String]): Unit = {\n val Array(n,ds,Array(a,b)) = Source.stdin.getLines().take(3).map(_.split(' ').map(_.toInt)).toArray\n val dss = ds.scanLeft(0)(_ + _)\n println(dss(b-1) - dss(a-1))\n }\n\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _38A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (0 until n - 1).map(i => next.toInt)\n val from = next.toInt - 1\n val to = next.toInt - 1\n println((from until to).map(i => a(i)).sum)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val d = in.next().split(\" \").map(_.toInt)\n val Array(a, b) = in.next().split(\" \").map(_.toInt - 1)\n println(d.slice(a, b).sum)\n}\n"}, {"source_code": "object A38 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n-1)\n var Array(a, b) = readInts(2).map(_-1)\n var res = 0\n while(a < b) {\n res += in(a)\n a += 1\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P038A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val D = List.fill(N - 1)(sc.nextInt)\n val A, B = sc.nextInt\n\n def solve: Int = ((A - 1) until (B - 1)).map(D(_)).sum\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "object CF38A extends App { \n\n val n = readLine().toInt\n val d = readLine.split(\" \").map(_.toInt)\n val range = readLine.split(\" \").map(_.toInt)\n val a = range(0)\n val b = range(1)\n println(d.drop(a - 1).take(b - a).sum)\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n readLine()\n val ar = readLine().split(\" \").map(_.toInt)\n val ab = readLine().split(\" \").map(_.toInt)\n val a = ab(0)\n val b = ab(1)\n println(ar.drop(a - 1).take(b - a).sum)\n }\n}"}, {"source_code": "\nobject A00038 extends App {\n def parseInt(str: String, count: Int): Seq[Int] = {\n val scanner = new java.util.Scanner(str)\n val res = (1 to count) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n def scanInts(count: Int): Seq[Int] = parseInt(Console.readLine, count)\n\n def oneIntLine = {\n val Seq(count) = parseInt(Console.readLine(), 1);\n count\n }\n \n val ranks = oneIntLine\n val years = scanInts(ranks - 1)\n val Seq(a, b) = scanInts(2)\n println(years.drop(a - 1).take(b - a).sum)\n}"}, {"source_code": "object Flask {\n \n def main(args: Array[String]): Unit = {\n var n = readLine.toInt\n var data = readLine.split(\" \").map(_.toInt)\n var input = readLine.split(\" \").map(_.toInt)\n var a = input(0) - 1; var b = input(1) - 1\n \n println(List.range(a, b).foldLeft(0)((res, i) => res + data(i)))\n }\n}\n"}], "negative_code": [{"source_code": "object A00038 extends App {\n def parseInt(str: String, count: Int): Seq[Int] = {\n val scanner = new java.util.Scanner(str)\n val res = (1 to count) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n def scanInts(count: Int): Seq[Int] = parseInt(Console.readLine, count)\n\n def oneIntLine = {\n val Seq(count) = parseInt(Console.readLine(), 1);\n count\n }\n \n val ranks = oneIntLine\n val years = scanInts(ranks - 1)\n val Seq(a, b) = scanInts(2)\n println(years.drop(a - 1).take(b - 1).sum)\n}\n"}], "src_uid": "69850c2af99d60711bcff5870575e15e"} {"source_code": "object _1043B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val as = 0 +: io.read[IndexedSeq[Int]]\n\n def isValid(k: Int) = {\n val xs = mutable.Map.empty[Int, Int]\n def update(i: Int, x: Int) = xs.getOrElseUpdate(i, x) == x\n (1 until as.length).forall(i => update((i - 1)%k, as(i) - as(i - 1)))\n }\n\n val ans = (1 until as.length).filter(isValid)\n io.writeLine(ans.length).writeAll(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val D = Array.ofDim[Int](N)\n D(0) = A(0)\n rep(N - 1, 1) { i =>\n D(i) = A(i) - A(i - 1)\n }\n\n val ans = ArrayBuffer[Int]()\n rep(N, 1) { k =>\n val ok = 1 to N / k forall { g =>\n val l = g * k\n 0 until k forall { i =>\n i + l >= N || D(i) == D(i + l)\n }\n }\n if (ok) ans += k\n }\n\n out.println(ans.length)\n out.println(ans.mkString(\" \"))\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val arr = Array.fill(n)(in.nextInt)\n var i = 0\n val diff = Array(arr(0)) ++ Array.fill(n - 1) {\n i += 1\n arr(i) - arr(i - 1)\n }\n\n val ans = ArrayBuffer[Int]()\n (1 until n).foreach { i =>\n var ok = true\n (0 until n).foreach { j =>\n ok &= diff(j) == diff(j % i)\n }\n if (ok)\n ans += i\n }\n ans += n\n println(ans.size)\n println(ans.mkString(\" \"))\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toInt\n }\n\n def nextLong: Double = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val D = Array.ofDim[Int](N)\n D(0) = A(0)\n rep(N - 1, 1) { i =>\n D(i) = A(i) - A(i - 1)\n }\n\n val ans = ArrayBuffer[Int]()\n rep(N, 1) { k =>\n val ok = 1 to N / k forall { g =>\n val l = g * k\n 0 until g forall { i =>\n D(i) == D((i + l) % N)\n }\n }\n if (ok) ans += k\n }\n\n out.println(ans.length)\n out.println(ans.mkString(\" \"))\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}], "src_uid": "fd2227498f1a0f4042673382a3c71c85"} {"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\nobject PolycarpsPractice {\n\n def main(args: Array[String]): Unit = {\n val k = StdIn.readLine().split(\" \").map(_.toInt).apply(1)\n val ns = StdIn.readLine().split(\" \").map(_.toInt)\n val (parts, sum) = solve(ns, k)\n println(sum)\n println(parts.mkString(\" \"))\n }\n\n def solve(ns: Seq[Int], k: Int): (Seq[Int], Int) = {\n val bla = biggestElementsIndex(ns, k)\n (step(ListBuffer(), bla.map(_._2 + 1).sorted, 0, ns.length),\n bla.map(_._1).sum)\n }\n\n def step(solution: ListBuffer[Int],\n biggestIndex: Seq[Int],\n used: Int,\n length: Int): Seq[Int] = {\n if (biggestIndex.size == 1) {\n solution += length - used\n } else {\n val index = biggestIndex.head\n step(solution += (index - used), biggestIndex.tail, index, length)\n }\n }\n\n def biggestElementsIndex(ns: Seq[Int], k: Int): Seq[(Int, Int)] = {\n ns.zipWithIndex.sorted.reverse.take(k)\n }\n}\n", "positive_code": [{"source_code": "object CF498B extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n val n = in.nextInt\n val k = in.nextInt\n\n val problems = (new Array[Int](n)).map(_ => in.nextInt)\n\n // find the k more difficult problems in original order\n val difficultProblems = problems.zipWithIndex.sortBy(_._1).reverse.take(k).sortBy(_._2)\n // max score\n out.println(difficultProblems.map(_._1).sum)\n\n val difProbIdx = difficultProblems.map(_._2)\n\n // difference between indexes\n var result = difProbIdx.zip(-1 +: difProbIdx.dropRight(1)).map(x => x._1 - x._2)\n result(k-1) += n - result.sum // take all the remaining problems\n\n out.println(result.mkString(\" \"))\n }\n\n solve\n out.flush\n out.close\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val A = na(N)\n val B = A.zipWithIndex\n Sorting.quickSort(B)(Ordering.by(_._1))\n val highs = B.takeRight(K).map(_._2)\n Sorting.quickSort(highs)\n val segs = Array.ofDim[Int](K)\n segs(0) = highs(0) + 1\n REP(K - 1, 1) { i =>\n segs(i) = highs(i) - highs(i - 1)\n }\n segs(K - 1) += N - highs(K - 1) - 1\n\n out.println(highs.map(A).sum)\n out.println(segs.mkString(\" \"))\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\nobject PolycarpsPractice {\n\n def main(args: Array[String]): Unit = {\n val k = StdIn.readLine().split(\" \").map(_.toInt).apply(1)\n val ns = StdIn.readLine().split(\" \").map(_.toInt)\n println(solve(ns, k).mkString(\" \"))\n }\n\n def solve(ns: Seq[Int], k: Int): Seq[Int] = {\n step(ListBuffer(), biggestElementsIndex(ns, k), 0, ns.length)\n }\n\n def step(solution: ListBuffer[Int], biggestIndex: Seq[Int], used : Int, length : Int): Seq[Int] = {\n if (biggestIndex.size == 1) {\n solution += length - used\n } else {\n val index = biggestIndex.head\n step(solution += (index - used), biggestIndex.tail, index, length)\n }\n }\n\n def biggestElementsIndex(ns: Seq[Int], k: Int): Seq[(Int)] = {\n ns.zipWithIndex.sorted.reverse.take(k).map(_._2 + 1).sorted\n }\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\nobject PolycarpsPractice {\n\n def main(args: Array[String]): Unit = {\n val k = StdIn.readLine().split(\" \").map(_.toInt).apply(1)\n val ns = StdIn.readLine().split(\" \").map(_.toInt)\n val (parts, sum) = solve(ns, k)\n println(sum)\n println(parts.mkString(\" \"))\n }\n\n def solve(ns: Seq[Int], k: Int): (Seq[Int], Int) = {\n val bla = biggestElementsIndex(ns, k)\n (step(ListBuffer(), bla.map(_._2 + 1), 0, ns.length), bla.map(_._1).sum)\n }\n\n def step(solution: ListBuffer[Int],\n biggestIndex: Seq[Int],\n used: Int,\n length: Int): Seq[Int] = {\n if (biggestIndex.size == 1) {\n solution += length - used\n } else {\n val index = biggestIndex.head\n step(solution += (index - used), biggestIndex.tail, index, length)\n }\n }\n\n def biggestElementsIndex(ns: Seq[Int], k: Int): Seq[(Int, Int)] = {\n ns.zipWithIndex.sorted.reverse.take(k).sorted\n }\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer\n\nobject PolycarpsPractice {\n\n def main(args: Array[String]): Unit = {\n println(solve(Seq(5, 1, 4, 3, 2), 3).mkString(\" \"))\n println(solve(Seq(5, 4, 2, 6, 5, 1, 9, 2), 3).mkString(\" \"))\n println(solve(Seq(1, 1, 1, 1, 1), 1).mkString(\" \"))\n println(solve(Seq(1, 2000, 2000, 2), 2).mkString(\" \"))\n }\n\n def solve(ns: Seq[Int], k: Int): Seq[Int] = {\n step(ListBuffer(), biggestElementsIndex(ns, k), 0, ns.length)\n }\n\n def step(solution: ListBuffer[Int], biggestIndex: Seq[Int], used : Int, length : Int): Seq[Int] = {\n if (biggestIndex.size == 1) {\n solution += length - used\n } else {\n val index = biggestIndex.head\n step(solution += (index - used), biggestIndex.tail, index, length)\n }\n }\n\n def biggestElementsIndex(ns: Seq[Int], k: Int): Seq[(Int)] = {\n ns.zipWithIndex.sorted.reverse.take(k).map(_._2 + 1).sorted\n }\n}"}], "src_uid": "9cc61be7dc9b79f46a3e796db0134173"} {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeMap\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n class SegTree(n: Int) {\n\n val NEUTRAL = 0 // neutral element in respect of operation used (+)\n\n val t = Array.fill(4 * Integer.highestOneBit(n)) { 0 }\n\n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n if (l > r) NEUTRAL\n else if (l == tl && r == tr) t(v)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n query(l, Math.min(r, tm), v2, tl, tm) +\n query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)\n }\n }\n\n def update(pos: Int, delta: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n if (tl == tr) t(v) += delta\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n if (pos <= tm) update(pos, delta, v2, tl, tm)\n else update(pos, delta, v2 + 1, tm + 1, tr)\n t(v) = t(v2) + t(v2 + 1)\n }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n var yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 1\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom += (h.y -> maxY)\n maxY += 2\n prev = h.y\n }\n }\n\n val events = hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs\n val st = new SegTree(maxY + 1)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom(y)\n st.update(cy, 1)\n case HEnd(x, y) =>\n val cy = yCom(y)\n st.update(cy, -1)\n case Vert(x, y1, y2) =>\n val from = yCom.from(y1)\n val to = yCom.to(y2)\n if (from.nonEmpty && to.nonEmpty) {\n val cy1 = from.head._2\n val cy2 = to.last._2\n if (cy1 <= cy2) {\n val d = st.query(cy1, cy2)\n if (d < 0) println(d)\n area -= d\n }\n }\n }\n }\n\n println(area)\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeMap\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n var yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom += (h.y -> maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val events = hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs\n val bit = BIT(maxY)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val from = yCom.from(y1)\n val to = yCom.to(y2)\n if (from.nonEmpty && to.nonEmpty) {\n val cy1 = from.head._2\n val cy2 = to.last._2\n if (cy1 <= cy2) area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}\n"}, {"source_code": "import java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Integer, Integer]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val events = hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs\n val bit = BIT(maxY)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val _y1 = yCom.ceilingKey(y1)\n val _y2 = yCom.floorKey(y2)\n if (_y1 != null && _y2 != null && _y1 <= _y2) {\n val cy1 = yCom.get(_y1)\n val cy2 = yCom.get(_y2)\n area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}"}, {"source_code": "import java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val events = (hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs)\n val bit = BIT(maxY + 1)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val from = yCom.tailMap(y1, true)\n val to = yCom.headMap(y2, true)\n if (!from.isEmpty && !to.isEmpty) {\n val cy1 = from.firstEntry.getValue\n val cy2 = to.lastEntry.getValue\n if (cy1 <= cy2) area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}"}, {"source_code": "import java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val events = hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs\n val bit = BIT(maxY)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val from = yCom.tailMap(y1, true)\n val to = yCom.headMap(y2, true)\n val _y1 = yCom.ceilingKey(y1)\n val _y2 = yCom.floorKey(y2)\n if (!from.isEmpty && !to.isEmpty) {\n val cy1 = from.firstEntry.getValue\n val cy2 = to.lastEntry.getValue\n val dy1 = yCom.get(_y1)\n val dy2 = yCom.get(_y2)\n if (cy1 != dy1) println(\"1\", cy1, dy1)\n if (cy2 != dy2) println(\"2\", cy2, dy2)\n if (cy1 <= cy2) area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}"}, {"source_code": "import java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val events = hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs\n val bit = BIT(maxY)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val from = yCom.tailMap(y1, true)\n val to = yCom.headMap(y2, true)\n if (!from.isEmpty && !to.isEmpty) {\n val cy1 = from.firstEntry.getValue\n val cy2 = to.lastEntry.getValue\n if (from.firstEntry.getKey != yCom.ceilingKey(y1)) println(from.firstEntry.getKey, yCom.ceilingKey(y1))\n if (to.lastEntry.getKey != yCom.floorKey(y2)) println(to.lastEntry.getKey, yCom.floorKey(y2))\n if (cy1 <= cy2) area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}"}, {"source_code": "import java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val events = hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs\n val bit = BIT(maxY + 1)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val from = yCom.tailMap(y1, true)\n val to = yCom.headMap(y2, true)\n if (!from.isEmpty && !to.isEmpty) {\n val cy1 = from.firstEntry.getValue\n val cy2 = to.lastEntry.getValue\n if (cy1 <= cy2) area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}"}, {"source_code": "import java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val events = hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs\n val bit = BIT(maxY)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val from = yCom.tailMap(y1, true)\n val to = yCom.headMap(y2, true)\n if (!from.isEmpty && !to.isEmpty) {\n val cy1 = from.firstEntry.getValue\n val cy2 = to.lastEntry.getValue\n if (from.firstEntry.getKey != yCom.ceilingKey(y1)) println(from.firstEntry.getKey, yCom.ceilingKey(y1))\n if (cy1 <= cy2) area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}"}], "negative_code": [{"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\nimport java.util.TreeMap\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val horBuilder0 = new ArrayBuilder.ofRef[Hor]\n val vertBuilder = new ArrayBuilder.ofRef[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vertBuilder += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n horBuilder0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs0 = horBuilder0.result.sortBy(h => (h.y, h.x1))\n val hBuilder = new ArrayBuilder.ofRef[Hor]()\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n } else {\n if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n }\n val hs = hBuilder.result.sortBy(_.y)\n\n val vs0 = vertBuilder.result.sortBy(v => (v.x, v.y1))\n val vBuilder = new ArrayBuilder.ofRef[Vert]()\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n } else {\n if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n }\n val vs = vBuilder.result\n\n val events = (hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs).sortBy(e => (e.x, e.priority))\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 1\n for (h <- hs) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 2\n prev = h.y\n }\n }\n\n val bit = BIT(maxY + 1)\n\n for (event <- events) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val _y1 = yCom.ceilingKey(y1)\n val _y2 = yCom.floorKey(y2)\n if (_y1 != null && _y2 != null && _y1 <= _y2) {\n val cy1 = yCom.get(_y1)\n val cy2 = yCom.get(_y2)\n area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}\n"}, {"source_code": "import java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 1\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 10\n prev = h.y\n }\n }\n\n val events = hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs\n val bit = BIT(maxY + 1)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val _y1 = yCom.ceilingKey(y1)\n val _y2 = yCom.floorKey(y2)\n if (_y1 != null && _y2 != null && _y1 <= _y2) {\n val cy1 = yCom.get(_y1)\n val cy2 = yCom.get(_y2)\n area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}\n"}, {"source_code": "import java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 1\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 2\n prev = h.y\n }\n }\n\n val events = hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs\n val bit = BIT(maxY + 1)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val _y1 = yCom.ceilingKey(y1)\n val _y2 = yCom.floorKey(y2)\n if (_y1 != null && _y2 != null && _y1 <= _y2) {\n val cy1 = yCom.get(_y1)\n val cy2 = yCom.get(_y2)\n val d = BIT.rangeQuery(bit, cy1, cy2)\n if (d < 0) println(d)\n area -= d\n }\n }\n }\n\n println(area)\n}\n"}, {"source_code": "import java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val events = hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs\n val bit = BIT(maxY)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n //val from = yCom.tailMap(y1, true)\n val _y1 = yCom.ceilingKey(y1)\n val to = yCom.headMap(y2, true)\n if (_y1 != null && !to.isEmpty) {\n val cy1 = yCom.get(_y1) //from.firstEntry.getValue\n val cy2 = to.lastEntry.getValue\n if (cy1 <= cy2) area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}"}, {"source_code": "import java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val events = hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs\n val bit = BIT(maxY)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val from = yCom.tailMap(y1, true)\n val _y2 = yCom.floorKey(y2)\n //val to = yCom.headMap(y2, true)\n if (!from.isEmpty && _y2 != null) {\n val cy1 = from.firstEntry.getValue\n val cy2 = yCom.get(_y2) //to.lastEntry.getValue\n if (cy1 <= cy2) area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\nimport java.util.TreeMap\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val horBuilder0 = new ArrayBuilder.ofRef[Hor]\n val vertBuilder = new ArrayBuilder.ofRef[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vertBuilder += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n horBuilder0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs0 = horBuilder0.result.sortBy(h => (h.y, h.x1))\n val hBuilder = new ArrayBuilder.ofRef[Hor]()\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n } else {\n if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n }\n val hs = hBuilder.result.sortBy(_.y)\n\n val vs0 = vertBuilder.result.sortBy(v => (v.x, v.y1))\n val vBuilder = new ArrayBuilder.ofRef[Vert]()\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n } else {\n if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n }\n val vs = vBuilder.result\n\n val events = (hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs).sortBy(e => (e.x, e.priority))\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 2\n prev = h.y\n }\n }\n\n val bit = BIT(maxY + 1)\n\n for (event <- events) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val _y1 = yCom.ceilingKey(y1)\n val _y2 = yCom.floorKey(y2)\n if (_y1 != null && _y2 != null) {\n val cy1 = yCom.get(_y1)\n val cy2 = yCom.get(_y2)\n area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}\n"}, {"source_code": "import java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 1\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 2\n prev = h.y\n }\n }\n\n val events = hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs\n val bit = BIT(maxY + 1)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val _y1 = yCom.ceilingKey(y1)\n val _y2 = yCom.floorKey(y2)\n if (_y1 != null && _y2 != null && _y1 <= _y2) {\n val cy1 = yCom.get(_y1)\n val cy2 = yCom.get(_y2)\n val d = BIT.rangeQuery(bit, cy1, cy2)\n assert(d >= 0)\n area -= d\n }\n }\n }\n\n println(area)\n}\n"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\nimport java.util.TreeMap\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val horBuilder0 = new ArrayBuilder.ofRef[Hor]\n val vertBuilder = new ArrayBuilder.ofRef[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vertBuilder += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n horBuilder0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs0 = horBuilder0.result.sortBy(h => (h.y, h.x1))\n val hBuilder = new ArrayBuilder.ofRef[Hor]()\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n } else {\n if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n }\n val hs = hBuilder.result.sortBy(_.y)\n\n val vs0 = vertBuilder.result.sortBy(v => (v.x, v.y1))\n val vBuilder = new ArrayBuilder.ofRef[Vert]()\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n } else {\n if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n }\n val vs = vBuilder.result\n\n val events = (hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs).sortBy(e => (e.x, e.priority))\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 1\n for (h <- hs) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 2\n prev = h.y\n }\n }\n\n val bit = BIT(maxY + 1)\n\n for (event <- events) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val _y1 = yCom.ceilingKey(y1)\n val _y2 = yCom.floorKey(y2)\n if (_y1 != null && _y2 != null) {\n val cy1 = yCom.get(_y1)\n val cy2 = yCom.get(_y2)\n area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}\n"}, {"source_code": "import java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 1\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 2\n prev = h.y\n }\n }\n\n val events = hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs\n val bit = BIT(maxY + 1)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val _y1 = yCom.ceilingKey(y1)\n val _y2 = yCom.floorKey(y2)\n if (_y1 != null && _y2 != null && _y1 <= _y2) {\n val cy1 = yCom.get(_y1)\n val cy2 = yCom.get(_y2)\n area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}\n"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\nimport java.util.TreeMap\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val horBuilder0 = new ArrayBuilder.ofRef[Hor]\n val vertBuilder = new ArrayBuilder.ofRef[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vertBuilder += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n horBuilder0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs0 = horBuilder0.result.sortBy(h => (h.y, h.x1))\n val hBuilder = new ArrayBuilder.ofRef[Hor]() \n \n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n }\n } else {\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n }\n val hs = hBuilder.result\n\n val vs0 = vertBuilder.result.sortBy(v => (v.x, v.y1))\n val vBuilder = new ArrayBuilder.ofRef[Vert]()\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n }\n } else {\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n }\n val vs = vBuilder.result\n\n val events = (hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs).sortBy(e => (e.x, e.priority))\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val bit = BIT(maxY + 1)\n\n for (event <- events) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val _y1 = yCom.ceilingKey(y1)\n val cy1 = yCom.get(_y1)\n val _y2 = yCom.floorKey(y2)\n val cy2 = yCom.get(_y2)\n area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n\n println(area)\n}\n"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\nimport java.util.TreeMap\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val horBuilder0 = new ArrayBuilder.ofRef[Hor]\n val vertBuilder = new ArrayBuilder.ofRef[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vertBuilder += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n horBuilder0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs0 = horBuilder0.result.sortBy(h => (h.y, h.x1))\n val hBuilder = new ArrayBuilder.ofRef[Hor]() \n \n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n } else {\n if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n }\n val hs = hBuilder.result\n\n val vs0 = vertBuilder.result.sortBy(v => (v.x, v.y1))\n val vBuilder = new ArrayBuilder.ofRef[Vert]()\n \n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n } else {\n if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n }\n val vs = vBuilder.result\n\n val events = (hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs).sortBy(e => (e.x, e.priority))\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val bit = BIT(maxY + 1)\n\n for (event <- events) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val _y1 = yCom.ceilingKey(y1)\n val cy1 = yCom.get(_y1)\n val _y2 = yCom.floorKey(y2)\n val cy2 = yCom.get(_y2)\n area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n\n println(area)\n}\n"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\nimport java.util.TreeMap\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val horBuilder0 = new ArrayBuilder.ofRef[Hor]\n val vertBuilder = new ArrayBuilder.ofRef[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vertBuilder += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n horBuilder0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs0 = horBuilder0.result.sortBy(h => (h.y, h.x1))\n val hBuilder = new ArrayBuilder.ofRef[Hor]() \n \n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n } else {\n if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n }\n val hs = hBuilder.result.sortBy(_.y)\n\n val vs0 = vertBuilder.result.sortBy(v => (v.x, v.y1))\n val vBuilder = new ArrayBuilder.ofRef[Vert]()\n \n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n } else {\n if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n }\n val vs = vBuilder.result\n\n val events = (hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs).sortBy(e => (e.x, e.priority))\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val bit = BIT(maxY + 1)\n\n for (event <- events) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val _y1 = yCom.ceilingKey(y1)\n val cy1 = yCom.get(_y1)\n val _y2 = yCom.floorKey(y2)\n val cy2 = yCom.get(_y2)\n area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n\n println(area)\n}\n"}, {"source_code": "import java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val events = (hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs)\n val bit = BIT(maxY + 1)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val _y1 = yCom.ceilingKey(y1)\n val _y2 = yCom.floorKey(y2)\n if (_y1 != null && _y2 != null) {\n val cy1 = yCom.get(_y1)\n val cy2 = yCom.get(_y2)\n if (cy1 <= cy2) area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}"}, {"source_code": "import java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val events = hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs\n val bit = BIT(maxY)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val from = yCom.tailMap(y1, true)\n val to = yCom.headMap(y2, true)\n val _y1 = yCom.ceilingKey(y1)\n val _y2 = yCom.floorKey(y2)\n if (from.isEmpty != (_y1 == null)) println(\"1\", from.isEmpty, y1, _y1)\n if (to.isEmpty != (_y2 == null)) println(\"2\", to.isEmpty, y2, _y2)\n if (!from.isEmpty && !to.isEmpty) {\n val cy1 = from.firstEntry.getValue\n val cy2 = to.lastEntry.getValue\n val dy1 = yCom.get(_y1)\n val dy2 = yCom.get(_y2)\n if (cy1 <= cy2) area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\nimport java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val events = (hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs)\n val bit = BIT(maxY + 1)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val _y1 = yCom.ceilingKey(y1)\n val _y2 = yCom.floorKey(y2)\n if (_y1 != null && _y2 != null && _y1 <= _y2) {\n val cy1 = yCom.get(_y1)\n val cy2 = yCom.get(_y2)\n area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}\n"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\nimport java.util.TreeMap\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val horBuilder0 = new ArrayBuilder.ofRef[Hor]\n val vertBuilder = new ArrayBuilder.ofRef[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vertBuilder += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n horBuilder0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs0 = horBuilder0.result.sortBy(h => (h.y, h.x1))\n val hBuilder = new ArrayBuilder.ofRef[Hor]()\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hBuilder += Hor(x1, x2, y)\n }\n val hs = hBuilder.result.sortBy(_.y)\n\n val vs0 = vertBuilder.result.sortBy(v => (v.x, v.y1))\n val vBuilder = new ArrayBuilder.ofRef[Vert]()\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vBuilder += Vert(x, y1, y2)\n }\n val vs = vBuilder.result\n\n val events = (hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs).sortBy(e => (e.x, e.priority))\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val bit = BIT(maxY + 1)\n\n for (event <- events) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val _y1 = yCom.ceilingKey(y1)\n val _y2 = yCom.floorKey(y2)\n if (_y1 != null && _y2 != null && _y1 <= _y2) {\n val cy1 = yCom.get(_y1)\n val cy2 = yCom.get(_y2)\n area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}\n"}, {"source_code": "import java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n \n class SegTree(n: Int) {\n\n val NEUTRAL = 0 // neutral element in respect of operation used (+)\n\n val t = Array.fill(4 * Integer.highestOneBit(n)){ 0 }\n\n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n if (l > r) NEUTRAL\n else if (l == tl && r == tr) t(v)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n query(l, Math.min(r, tm), v2, tl, tm) +\n query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)\n }\n }\n\n def update(pos: Int, delta: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n if (tl == tr) t(v) += delta\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n if (pos <= tm) update(pos, delta, v2, tl, tm)\n else update(pos, delta, v2 + 1, tm + 1, tr)\n t(v) = t(v2) + t(v2 + 1)\n }\n }\n\n }\n\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 1\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 2\n prev = h.y\n }\n }\n\n val events = hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs\n val st = new SegTree(maxY + 1)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n st.update(cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n st.update(cy, -1)\n case Vert(x, y1, y2) =>\n val _y1 = yCom.ceilingKey(y1)\n val _y2 = yCom.floorKey(y2)\n if (_y1 != null && _y2 != null && _y1 <= _y2) {\n val cy1 = yCom.get(_y1)\n val cy2 = yCom.get(_y2)\n val d = st.query(cy1, cy2)\n if (d < 0) println(d)\n area -= d\n }\n }\n }\n\n println(area)\n}\n"}, {"source_code": "import java.util.TreeMap\nimport scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(size: Int): Array[Int] = {\n Array.fill(size) { 0 }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n trait Event {\n def x: Int\n def priority: Int\n }\n\n val Array(n) = readInts(1)\n final case class Hor(x1: Int, x2: Int, y: Int)\n final case class Vert(x: Int, y1: Int, y2: Int) extends Event {\n def priority = 2\n }\n\n final case class HStart(x: Int, y: Int) extends Event {\n def priority = 1\n }\n\n final case class HEnd(x: Int, y: Int) extends Event {\n def priority = 3\n }\n\n val hs0 = ArrayBuffer.empty[Hor]\n val vs0 = ArrayBuffer.empty[Vert]\n\n var area = 0L\n\n for (i <- 0 until n) {\n val Array(_x1, _y1, _x2, _y2) = readInts(4)\n val x1 = _x1 min _x2\n val x2 = _x1 max _x2\n val y1 = _y1 min _y2\n val y2 = _y1 max _y2\n if (x1 == x2) {\n vs0 += Vert(x1, y1, y2)\n area += (y2 - y1 + 1)\n } else {\n hs0 += Hor(x1, x2, y1)\n area += (x2 - x1 + 1)\n }\n }\n\n val hs = ArrayBuffer.empty[Hor]\n\n {\n var y = Int.MinValue\n var x1 = Int.MinValue\n var x2 = Int.MinValue\n for (h <- hs0.sortBy(h => (h.y, h.x1))) {\n if (h.y == y) {\n if (h.x1 <= x2) {\n if (h.x2 < x2) {\n area -= (h.x2 - h.x1 + 1)\n } else {\n area -= (x2 - h.x1 + 1)\n x2 = h.x2\n }\n } else {\n hs += Hor(x1, x2, y)\n x1 = h.x1\n x2 = h.x2\n }\n } else {\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n y = h.y\n x1 = h.x1\n x2 = h.x2\n }\n }\n if (y > Int.MinValue) hs += Hor(x1, x2, y)\n }\n\n val vs = ArrayBuffer.empty[Vert]\n\n {\n var x = Int.MinValue\n var y1 = Int.MinValue\n var y2 = Int.MinValue\n for (v <- vs0.sortBy(v => (v.x, v.y1))) {\n if (v.x == x) {\n if (v.y1 <= y2) {\n if (v.y2 < y2) {\n area -= (v.y2 - v.y1 + 1)\n } else {\n area -= (y2 - v.y1 + 1)\n y2 = v.y2\n }\n } else {\n vs += Vert(x, y1, y2)\n y1 = v.y1\n y2 = v.y2\n }\n } else {\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n x = v.x\n y1 = v.y1\n y2 = v.y2\n }\n }\n if (x > Int.MinValue) vs += Vert(x, y1, y2)\n }\n\n val yCom = new TreeMap[Int, Int]\n\n var prev = Int.MinValue\n var maxY = 0\n for (h <- hs.sortBy(_.y)) {\n if (h.y > prev) {\n yCom.put(h.y, maxY)\n maxY += 1\n prev = h.y\n }\n }\n\n val events = hs.map(h => HStart(h.x1, h.y)) ++ hs.map(h => HEnd(h.x2, h.y)) ++ vs\n val bit = BIT(maxY)\n\n for (event <- events.sortBy(e => (e.x, e.priority))) {\n event match {\n case HStart(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, 1)\n case HEnd(x, y) =>\n val cy = yCom.get(y)\n BIT.update(bit, cy, -1)\n case Vert(x, y1, y2) =>\n val from = yCom.tailMap(y1, true)\n val to = yCom.headMap(y2, true)\n val _y1 = yCom.ceilingKey(y1)\n val _y2 = yCom.floorKey(y2)\n if (from.isEmpty != (_y1 == null)) println(\"1\", _y1)\n if (to.isEmpty != (_y2 == null)) println(\"2\", _y2)\n if (!from.isEmpty && !to.isEmpty) {\n val cy1 = from.firstEntry.getValue\n val cy2 = to.lastEntry.getValue\n val dy1 = yCom.get(_y1)\n val dy2 = yCom.get(_y2)\n if (cy1 <= cy2) area -= BIT.rangeQuery(bit, cy1, cy2)\n }\n }\n }\n\n println(area)\n}"}], "src_uid": "6d7accf770d489f746648aa56c90d16d"} {"source_code": "object Main {\n\n def main(args: Array[String]) {\n\n val std = scala.io.StdIn\n val line1 = std.readLine()\n val line2 = std.readLine()\n\n val vowels = \"aeiou\"\n if (line1.length == line2.length) {\n if (line1.zip(line2).exists(x => vowels.contains(x._1) != vowels.contains(x._2))) {\n println(\"No\")\n }\n else {\n println(\"Yes\")\n }\n }\n else {\n println(\"No\")\n }\n }\n}", "positive_code": [{"source_code": "object Problem_1111A {\n\n def main(args: Array[String]) {\n val scan = scala.io.StdIn\n val s1: String = scan.readLine()\n val s2: String = scan.readLine()\n\n if(s1.length != s2.length){\n print(\"No\")\n return\n }\n\n var areSame= true;\n for (i <- 0 until s1.length) {\n if(isVowel(s1(i)) != isVowel(s2(i))){\n areSame =false\n }\n }\n\n if(areSame){\n print(\"Yes\")\n }\n else{\n print(\"No\")\n }\n\n }\n\n def isVowel(x : Char) ={\n val vowels: Array[Char] = Array('a','e','i','o','u')\n vowels.contains(x)\n }\n\n\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S, T = ns()\n\n def tpe(c: Char) = c match {\n case 'a' | 'i' | 'u' | 'e' | 'o' => 1\n case _ => 2\n }\n\n if (S.length != T.length) {\n out.println(\"No\")\n } else {\n var ok = true\n REP(S.length) { i =>\n ok &&= tpe(S(i)) == tpe(T(i))\n }\n if (ok) out.println(\"Yes\")\n else out.println(\"No\")\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readStrings(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken) }\n\n val Array(s) = readStrings(1)\n val Array(t) = readStrings(1)\n\n val cos = Seq('a', 'e', 'i', 'o', 'u')\n\n val matchCase = for {\n (cs, ct) <- s.zip(t)\n matches = cos.contains(cs) == cos.contains(ct)\n } yield matches\n\n if (matchCase.forall(_ == true) && s.length == t.length)\n println(\"yes\")\n else\n print(\"no\")\n\n Console.flush\n}"}, {"source_code": "object _1111A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val s, t = io.read[String]\n val vowels = \"aeiou\"\n val ans = s.length == t.length && s.zip(t).forall({case (a, b) => vowels.contains(a) == vowels.contains(b)})\n io.write(if (ans) \"Yes\" else \"No\" +\n \"\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readStrings(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken) }\n\n val Array(s) = readStrings(1)\n val Array(t) = readStrings(1)\n\n val cos = Seq('a', 'e', 'i', 'o', 'u')\n\n val matchCase = !s.zip(t).forall {\n case (c1, c2) => cos.contains(c1) ^ cos.contains(c2)\n }\n\n if (matchCase && s.length == t.length)\n println(\"yes\")\n else\n print(\"no\")\n\n Console.flush\n}"}], "src_uid": "2b346d5a578031de4d19edb4f8f2626c"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S, T = ns()\n\n val N = min(S.length, T.length)\n var i = 0\n var continue = true\n while(i < N && continue) {\n if (S(S.length - 1 - i) == T(T.length - 1 - i))\n i += 1\n else\n continue = false\n }\n out.println(S.length + T.length - 2 * i)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Codeforces1005B {\n\n def getFewestMove(s: String, t: String): Int = {\n var totalMatched = 0\n var misMatched = false\n while (!misMatched) {\n if (totalMatched >= s.length || totalMatched >= t.length) {\n misMatched = true\n } else if (s(s.length - 1 - totalMatched) == t(t.length - 1 - totalMatched)) {\n totalMatched += 1\n } else {\n misMatched = true\n }\n }\n\n s.length + t.length - 2 * totalMatched\n }\n\n def main(args: Array[String]): Unit = {\n val s = StdIn.readLine()\n val t = StdIn.readLine()\n val fewestMove = getFewestMove(s, t)\n println(fewestMove)\n }\n}\n"}, {"source_code": "object StrCut {\n def main(args: Array[String]): Unit = {\n val s1: String = scala.io.StdIn.readLine()\n val s2: String = scala.io.StdIn.readLine()\n var u = 0\n while ( {\n u < Math.min(s1.length, s2.length) && s1.charAt(s1.length - u - 1) == s2.charAt(s2.length - u - 1)\n }) {\n u += 1; u\n }\n println(s1.length - u + s2.length - u)\n }\n}\n"}, {"source_code": "object CF496B extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n val w1 = in.next\n val w2 = in.next\n\n val sameCount = w1.reverse.zipWithIndex\n .takeWhile(x => w2.length - 1 - x._2 >= 0 && w2.charAt(w2.length - 1 - x._2) == x._1)\n .length\n\n out.println(w1.length + w2.length - sameCount*2)\n }\n\n solve\n out.flush\n out.close\n}"}, {"source_code": "import scala.collection.mutable._\n\nobject Solution {\n def main(args: Array[String]) {\n val s = scala.io.StdIn.readLine.trim\n val t = scala.io.StdIn.readLine.trim\n println(solve(s, t))\n }\n\n def solve(s: String, t: String): Int = {\n var i = s.length\n var j = t.length\n var flag = true\n while (i > 0 && j > 0 && flag) {\n if (s(i-1) != t(j-1)) flag = false\n else {\n i -= 1\n j -= 1\n }\n }\n (i + j)\n }\n\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable._\n\nobject Solution {\n def main(args: Array[String]) {\n val s = scala.io.StdIn.readLine.trim\n val t = scala.io.StdIn.readLine.trim\n println(solve(s, t))\n }\n\n def solve(s: String, t: String) {\n var i = s.length\n var j = t.length\n var flag = true\n while (i > 0 && j > 0 && flag) {\n if (s(i-1) != t(j-1)) flag = false\n else {\n i -= 1\n j -= 1\n }\n }\n (i + j)\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable._\n\nobject Solution {\n def main(args: Array[String]) {\n val s = scala.io.StdIn.readLine.trim\n val t = scala.io.StdIn.readLine.trim\n println(solve(s, t))\n }\n\n def solve(s: String, t: String): Int = {\n var i = s.length - 1\n var j = t.length - 1\n var flag = true\n while (i > 0 && j > 0 && flag) {\n if (s(i) != t(j)) flag = false\n else {\n i -= 1\n j -= 1\n }\n }\n (i + j + 2)\n }\n\n}\n"}], "src_uid": "59d926bca19a6dcfe3eb3e3dc03fffd6"} {"source_code": "object CF511B extends App {\n\n import scala.io.StdIn\n\n val n = StdIn.readInt\n val points = new Array[Int](n).map(_ => StdIn.readLine.split(' ').map(_.toInt))\n println(points.map(point => point(0)+point(1)).max)\n // y-y1=-(x-x1)\n // y=-(x-x1)+y1 | evaluated at x=0\n // y=x1+y1\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = Array.ofDim[Int](N)\n rep(N) { i =>\n A(i) = ni() + ni()\n }\n val ans = A.max\n out.println(ans)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "\n\nimport scala.io.StdIn\n\nobject CoverPoints {\n def main(args: Array[String]): Unit ={\n val n = StdIn.readInt()\n var ans = 0\n for( i <- 1 to n){\n val xy = StdIn.readLine().split(\" \").map(_.toInt)\n val x = xy(0)\n val y = xy(1)\n ans = math.max(ans,x + y)\n }\n print(ans)\n }\n\n}\n"}, {"source_code": "object b1047 {\n def main(args: Array[String]): Unit = {\n println(scala.io.Source.stdin getLines() drop 1 map(_.split(\" \").map(_.toInt).sum) reduce scala.math.max)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Codeforces1047B {\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n val result = (1 to n).map(_ => StdIn.readLine.trim.split(\" \").map(_.toInt)).map(a => a.sum).max\n\n print(result)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Codeforces1047B {\n\n def getCoverPoint(n: Int, points: Seq[Point]): Int =\n points.map(a => a.x + a.y).max\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n\n val points = (1 to n).map(_ => StdIn.readLine.trim.split(\" \").map(_.toInt)).map(a => Point(a(0), a(1)))\n\n val result = getCoverPoint(n, points)\n\n print(result)\n }\n\n case class Point(x: Int, y: Int)\n\n}"}], "negative_code": [{"source_code": "object b1047 {\n def main(args: Array[String]): Unit = {\n //val n = scala.io.StdIn.readInt()\n val r : Array[Array[Int]] = scala.io.Source.stdin getLines() drop 1 map(_.split(\" \").map(_.toInt)) toArray\n val s = r.sortBy {i => (-i(0),-i(1))}\n println(s.head(0)+s.head(1))\n }\n}\n"}], "src_uid": "7c41fb6212992d1b3b3f89694b579fea"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(c1, c2, c3, c4) = in.next().split(' ').map(_.toInt)\n in.next()\n val a = in.next().split(' ').map(_.toInt).sorted.reverse\n val b = in.next().split(' ').map(_.toInt).sorted.reverse\n println(Math.min(\n c4,\n Math.min(a.map(i => Math.min(i * c1, c2)).sum, c3) + Math.min(b.map(i => Math.min(i * c1, c2)).sum, c3)\n ))\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(c1, c2, c3, c4) = readLine().split(\" \").map(_.toInt)\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val ns = readLine().split(\" \").map(_.toInt)\n val ms = readLine().split(\" \").map(_.toInt)\n \n val nsum = ns.map(count => c2.min(count * c1)).sum\n val nmin = nsum.min(c3)\n \n val msum = ms.map(count => c2.min(count * c1)).sum\n val mmin = msum.min(c3)\n \n println(c4.min(nmin + mmin))\n }\n}"}], "negative_code": [], "src_uid": "11fabde93815c1805369bbbc5a40e2d8"} {"source_code": "object C{\n def main(args:Array[String]){\n\n val a:Array[Double]={\n val n=readLine.toInt\n val alist=\n (1 to n).toList.foldLeft(List[Double]()){(list,i)=>\n val (x, y)={\n val sp=readLine.split(\" \").map(_.toInt)\n (sp(0),sp(1))\n }\n if(x==0 && y==0){\n list\n }else{\n val next=Math.toDegrees(Math.atan2(y,x))\n next::list\n }\n }\n\n alist.toArray.sorted\n }\n\n val n=a.length\n\n val max= (0 until n).toList.foldLeft(0.0){(max,i)=>\n var m= a((i+1)%n) -a(i)\n if(i==n-1) m+=360\n Math.max(m,max)\n }\n\n println(360-max)\n }\n}\n", "positive_code": [{"source_code": "import scala.util.Sorting._\nimport math._\n\nobject Contest extends App {\n val n = readInt()\n val arcs = new Array[Double](n+1);\n arcs(n) = 3 * Pi\n for (i <- 0 until n){\n val Array(x, y) = readLine().split(\" \").map(_.toDouble)\n arcs(i) = atan2(y, x)\n }\n stableSort(arcs, (a: Double, b: Double) => {a < b})\n arcs(n) = arcs(0) + 2 * Pi\n var maxArc = 0.0\n for (i <- 0 until n){\n maxArc = max(maxArc, arcs(i+1) - arcs(i))\n }\n println(360 - maxArc * 180 / Pi)\n}\n"}], "negative_code": [{"source_code": "object C{\n def main(args:Array[String]){\n\n val a:Array[Double]={\n val n=readLine.toInt\n val alist=\n (1 to n).toList.foldLeft(List[Double]()){(list,i)=>\n val (x, y)={\n val sp=readLine.split(\" \").map(_.toInt)\n (sp(0),sp(1))\n }\n if(x==0 && y==0){\n list\n }else{\n val next=Math.toDegrees(Math.atan2(y,x))\n next::list\n }\n }\n\n alist.toArray.sorted\n }\n\n val n=a.length\n\n val max= (0 until n).toList.foldLeft(0.0){(max,i)=>\n var m= a((i+1)%n) -a(i)\n if(m<0) m+=360\n Math.max(m,max)\n }\n\n if(n==1){\n println(0)\n }else{ \n println(360-max)\n }\n }\n}\n"}, {"source_code": "object C{\n def main(args:Array[String]){\n\n val a:Array[Double]={\n val n=readLine.toInt\n val alist=\n (1 to n).toList.foldLeft(List[Double]()){(list,i)=>\n val (x, y)={\n val sp=readLine.split(\" \").map(_.toInt)\n (sp(0),sp(1))\n }\n if(x==0 && y==0){\n list\n }else{\n val next=Math.toDegrees(Math.atan2(y,x))\n next::list\n }\n }\n\n alist.toArray.sorted\n }\n\n val n=a.length\n\n val max= (0 until n).toList.foldLeft(0.0){(max,i)=>\n var m= a((i+1)%n) -a(i)\n if(m<0) m+=360\n Math.max(m,max)\n }\n\n println(360-max)\n\n }\n}\n"}], "src_uid": "a67cdb7501e99766b20a2e905468c29c"} {"source_code": "import scala.collection.mutable.ListBuffer\n\nobject P479B {\n\tdef transfer(values: Vector[Int], src: (Int, Int), dst: (Int, Int)) : Vector[Int] = {\n\t\tvalues.updated(src._2, src._1 - 1).updated(dst._2, dst._1 + 1)\n\t}\n\n\tdef iterate(k: Int, values: Vector[Int]) : (ListBuffer[(Int, Int)], Vector[Int]) = {\n\t\tval max = values.zipWithIndex.maxBy(_._1)\n\t\tval min = values.zipWithIndex.minBy(_._1)\n\n\t\tval accumulator = ListBuffer[(Int, Int)]()\n\t\tif (max._1 - min._1 > 1 && k > 0) {\n\t\t\tval (results, updated) = iterate(k - 1, transfer(values, max, min))\n\t\t\t(accumulator ++= ((max._2 + 1, min._2 + 1) +=: results), updated)\n\t\t} else {\n\t\t\t(accumulator, values)\n\t\t}\n\t}\n\n\tdef main(args: Array[String]) {\n\t\tval read = () => scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n\t\tval (Array(n, k), a) = (read(), read().to[Vector])\n\t\tval (results, values) = iterate(k, a)\n\n\t\tprintf(\"%d %d\\n\", values.max - values.min, results.length)\n\t\tresults.foreach(x => printf(\"%d %d\\n\", x._1, x._2))\n\t}\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.ListBuffer\n\nobject P479B {\n\tdef iterate(k: Int, values: Vector[Int]) : (ListBuffer[(Int, Int)], Vector[Int]) = {\n\t\tval results = ListBuffer[(Int, Int)]()\n\t\tval max = values.zipWithIndex.maxBy(_._1)\n\t\tval min = values.zipWithIndex.minBy(_._1)\n\t\tif (max._1 > min._1 + 1 && k > 0) {\n\t\t\tval updated = values.updated(max._2, max._1 - 1).updated(min._2, min._1 + 1)\n\t\t\tval (rresults, rupdated) = iterate(k - 1, updated)\n\t\t\t(results ++= ((max._2 + 1, min._2 + 1) +=: rresults), rupdated)\n\t\t} else {\n\t\t\t(results, values)\n\t\t}\n\t}\n\n\tdef main(args: Array[String]) {\n\t\tval read = () => scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n\t\tval Array(n, k) = read()\n\t\tval (results, values) = iterate(k, read().to[Vector])\n\t\tprintf(\"%d %d\\n\", values.max - values.min, results.length)\n\t\tresults.foreach(x => printf(\"%d %d\\n\", x._1, x._2))\n\t}\n}\n"}, {"source_code": "import Console._\nimport scala.io.Source\n\nobject Main extends App {\n \n \n \n val in = Source.fromInputStream(System.in)\n val n = nextInt(in).get\n val k = nextInt(in).get\n val arr = Array.ofDim[Int](n)\n \n \n for (i <- 1 to n) {\n arr(i - 1) = nextInt(in).get\n }\n val sumAll = arr.foldLeft(0)(_ + _)\n val minInstability = (sumAll / n.toDouble).ceil.toInt - sumAll / n\n val arrIndexed = arr.zipWithIndex\n val initialInstability = arrIndexed(findMaxIdx(arrIndexed))._1 - arrIndexed(findMinIdx(arrIndexed))._1\n \n val (instability, opCount, allOps) = \n findMinInstability(initialInstability, 0, Array[(Int, Int)](), arrIndexed)\n \n print(s\"$instability $opCount\")\n \n for (i <- 1 to opCount) {\n val op = allOps(i - 1)\n print(s\"\\n${op._1} ${op._2}\")\n }\n \n def findMinInstability(instability: Int, nOps: Int, ops: Array[(Int, Int)], arrIndexed: Array[(Int, Int)]): \n (Int, Int, Array[(Int, Int)]) = {\n \n if (instability == minInstability || nOps == k) {\n (instability, nOps, ops)\n } else {\n val maxIdx = findMaxIdx(arrIndexed)\n val minIdx = findMinIdx(arrIndexed)\n arrIndexed(maxIdx) = (arrIndexed(maxIdx)._1 - 1, arrIndexed(maxIdx)._2)\n arrIndexed(minIdx) = (arrIndexed(minIdx)._1 + 1, arrIndexed(minIdx)._2)\n val newInstability = arrIndexed(findMaxIdx(arrIndexed))._1 - arrIndexed(findMinIdx(arrIndexed))._1\n \n findMinInstability(newInstability, nOps + 1, ops :+ (maxIdx + 1, minIdx + 1), arrIndexed)\n }\n }\n \n def findMaxIdx(arrIndexed: Array[(Int, Int)]) = {\n arrIndexed.max._2\n }\n \n def findMinIdx(arrIndexed: Array[(Int, Int)]) = {\n arrIndexed.min._2\n }\n \n def nextInt(src: Iterator[Char]): Option[Int] = {\n val (ignored, tail) = src.span(!_.isDigit)\n val (nbr, _) = tail.span(_.isDigit)\n if (!nbr.isEmpty) {\n Some(nbr.mkString.toInt)\n } else {\n None\n }\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n val arr = Array.fill(10001){List.empty[Int]}\n data.indices.foreach { i => arr(data(i)) ::= i + 1 }\n var nk = k\n var left = arr.indices.find(i => arr(i).nonEmpty).get\n var right = arr.indices.reverse.find(i => arr(i).nonEmpty).get\n var res = List.empty[(Int, Int)]\n while (nk > 0 && left + 1 < right) {\n val lIndex = arr(left).head\n val rIndex = arr(right).head\n res ::= (rIndex, lIndex)\n nk -= 1\n arr(left) = arr(left).tail\n arr(left + 1) ::= lIndex\n arr(right) = arr(right).tail\n arr(right - 1) ::= rIndex\n if (arr(left).isEmpty)\n left += 1\n if (arr(right).isEmpty)\n right -= 1\n }\n println(s\"${right - left} ${k - nk}\")\n println(res.map{case(a, b) => s\"$a $b\"}.mkString(\"\\n\"))\n}\n"}], "negative_code": [], "src_uid": "9cd42fb28173170a6cfa947cb31ead6d"} {"source_code": "object Solution extends App {\n\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n if (n <= 3) println(\"NO\")\n else if (n % 2 == 0) {\n println(\"YES\")\n println(\"1 * 2 = 2\")\n println(\"2 * 3 = 6\")\n println(\"6 * 4 = 24\")\n (5 to n by 2).foreach { i =>\n println(s\"${i + 1} - $i = 1\")\n println(\"24 * 1 = 24\")\n }\n \n } else {\n println(\"YES\")\n println(\"2 - 1 = 1\")\n println(\"1 + 3 = 4\")\n println(\"4 * 5 = 20\")\n println(\"20 + 4 = 24\")\n (6 to n by 2).foreach { i =>\n println(s\"${i + 1} - $i = 1\")\n println(\"24 * 1 = 24\")\n }\n }\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C268A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C268A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n\n val notPossible = Array(1, 2, 3)\n if(notPossible.contains(n)) {\n out.println(\"NO\")\n } else if(n == 4) {\n out.println(\"YES\")\n out.println(\"4 * 3 = 12\")\n out.println(\"12 * 2 = 24\")\n out.println(\"24 * 1 = 24\")\n } else if(n==5) {\n out.println(\"YES\")\n out.println(\"5 - 3 = 2\")\n out.println(\"4 * 2 = 8\")\n out.println(\"2 + 1 = 3\")\n out.println(\"8 * 3 = 24\")\n } else {\n out.println(\"YES\")\n out.println(\"6 * 4 = 24\")\n out.println(\"1 + 2 = 3\")\n out.println(\"3 - 3 = 0\")\n out.println(\"0 * 5 = 0\")\n REP(n + 1) { i =>\n if(i > 6) {\n out.println(s\"$i * 0 = 0\")\n }\n }\n out.println(\"24 + 0 = 24\")\n }\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\nobject A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (n < 4) println(\"NO\")\n else {\n println(\"YES\")\n solve(n)\n }\n \n Console.flush\n\n @tailrec\n def solve(n: Int): Unit = {\n if (n == 4) {\n println(\"1 * 2 = 2\")\n println(\"2 * 3 = 6\")\n println(\"6 * 4 = 24\")\n } else if (n == 5) {\n println(\"5 - 3 = 2\")\n println(\"2 + 1 = 3\")\n println(\"3 * 2 = 6\")\n println(\"6 * 4 = 24\")\n } else {\n println(s\"$n - ${n - 1} = 1\")\n println(\"1 * 1 = 1\")\n solve(n - 2)\n }\n }\n \n}"}, {"source_code": "object TwentyFour extends App {\n sealed trait Op {\n def apply(a: Int, b: Int): Int\n }\n case object Times extends Op {\n override def apply(a: Int, b: Int) = a * b\n override def toString = \"*\"\n }\n case object Plus extends Op {\n override def apply(a: Int, b: Int) = a + b\n override def toString = \"+\"\n }\n case object Minus extends Op {\n override def apply(a: Int, b: Int) = a - b\n override def toString = \"-\"\n }\n\n case class Equation(l: Int, op: Op, r: Int) {\n val res = op(l, r)\n override def toString = s\"$l $op $r = $res\"\n }\n\n object EquationBuilder {\n implicit def intToEquationBuilder(i: Int) = EquationBuilder(i)\n }\n case class EquationBuilder(i: Int) {\n def plus(j: Int) = Equation(i, Plus, j)\n def times(j: Int) = Equation(i, Times, j)\n def minus(j: Int) = Equation(i, Minus, j)\n }\n\n // The work\n val n = io.Source.stdin.getLines.next.toInt\n if(n < 4) println(\"NO\")\n else {\n import EquationBuilder._\n val fourSolution = Vector(\n 4 times 2, // = 8\n 8 times 3, // = 24\n 24 times 1)\n val fiveSolution = Vector(\n 5 minus 2, // = 3\n 3 plus 3, // = 6\n 4 times 6, // = 24\n 24 times 1)\n def incSolution(i: Int) = Vector(\n // assume we have collapsed all i-2 into a single 24\n i minus (i - 1), // = 1\n 24 times 1)\n def solution(i: Int) = {\n if(i % 2 == 0) {\n fourSolution ++ ((3 to i/2) map (_ * 2) flatMap incSolution)\n } else {\n fiveSolution ++ ((3 to i/2) map (_ * 2 + 1) flatMap incSolution)\n }\n }\n println(\"YES\")\n println(solution(n).mkString(\"\\n\"))\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n if (n <= 3) println(\"NO\")\n else if (n % 2 == 0) {\n println(\"YES\")\n println(\"1 * 2 = 2\")\n println(\"2 * 3 == 6\")\n println(\"6 * 4 = 24\")\n (5 to n by 2).foreach { i =>\n println(s\"${i + 1} - $i = 1\")\n }\n println(\"24 * 1 = 24\")\n } else {\n println(\"YES\")\n println(\"2 - 1 = 1\")\n println(\"1 + 3 = 4\")\n println(\"4 * 5 = 20\")\n (6 to n by 2).foreach { i =>\n println(s\"${i + 1} - $i = 1\")\n }\n println(\"24 * 1 = 24\")\n }\n}"}, {"source_code": "object Solution extends App {\n\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n if (n <= 3) println(\"NO\")\n else if (n % 2 == 0) {\n println(\"YES\")\n println(\"1 * 2 = 2\")\n println(\"2 * 3 = 6\")\n println(\"6 * 4 = 24\")\n (5 to n by 2).foreach { i =>\n println(s\"${i + 1} - $i = 1\")\n }\n println(\"24 * 1 = 24\")\n } else {\n println(\"YES\")\n println(\"2 - 1 = 1\")\n println(\"1 + 3 = 4\")\n println(\"4 * 5 = 20\")\n (6 to n by 2).foreach { i =>\n println(s\"${i + 1} - $i = 1\")\n }\n println(\"24 * 1 = 24\")\n }\n}"}, {"source_code": "object Solution extends App {\n\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n if (n <= 3) println(\"NO\")\n else if (n % 2 == 0) {\n println(\"YES\")\n println(\"1 * 2 = 2\")\n println(\"2 * 3 = 6\")\n println(\"6 * 4 = 24\")\n (5 to n by 2).foreach { i =>\n println(s\"${i + 1} - $i = 1\")\n println(\"24 * 1 = 24\")\n }\n \n } else {\n println(\"YES\")\n println(\"2 - 1 = 1\")\n println(\"1 + 3 = 4\")\n println(\"4 * 5 = 20\")\n (6 to n by 2).foreach { i =>\n println(s\"${i + 1} - $i = 1\")\n println(\"24 * 1 = 24\")\n }\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C268A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C268A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n\n val notPossible = Array(1, 2, 3, 5)\n if(notPossible.contains(n)) {\n out.println(\"NO\")\n } else if(n == 4) {\n out.println(\"YES\")\n out.println(\"4 * 3 = 12\")\n out.println(\"12 * 2 = 24\")\n out.println(\"24 * 1 = 24\")\n } else {\n out.println(\"YES\")\n out.println(\"6 * 4 = 24\")\n out.println(\"1 + 2 = 3\")\n out.println(\"3 - 3 = 0\")\n out.println(\"0 * 5 = 0\")\n REP(n + 1) { i =>\n if(i > 6) {\n out.println(s\"$i * 0 = 0\")\n }\n }\n out.println(\"24 + 0 = 24\")\n }\n }\n}\n"}, {"source_code": "object TwentyFour extends App {\n sealed trait Op {\n def apply(a: Int, b: Int): Int\n }\n case object Times extends Op {\n override def apply(a: Int, b: Int) = a * b\n override def toString = \"*\"\n }\n case object Plus extends Op {\n override def apply(a: Int, b: Int) = a + b\n override def toString = \"+\"\n }\n case object Minus extends Op {\n override def apply(a: Int, b: Int) = a - b\n override def toString = \"-\"\n }\n\n case class Equation(l: Int, op: Op, r: Int) {\n val res = op(l, r)\n override def toString = s\"$l $op $r = $res\"\n }\n\n object EquationBuilder {\n implicit def intToEquationBuilder(i: Int) = EquationBuilder(i)\n }\n case class EquationBuilder(i: Int) {\n def plus(j: Int) = Equation(i, Plus, j)\n def times(j: Int) = Equation(i, Times, j)\n def minus(j: Int) = Equation(i, Minus, j)\n }\n\n // The work\n val n = io.Source.stdin.getLines.next.toInt\n if(n < 4) println(\"NO\")\n else {\n import EquationBuilder._\n val fourSolution = Vector(\n 4 times 2, // = 8\n 8 times 3, // = 24\n 24 times 1)\n val fiveSolution = Vector(\n 5 minus 2, // = 3\n 3 plus 3, // = 6\n 4 times 6, // = 24\n 24 times 1)\n def incSolution(i: Int) = Vector(\n // assume we have collapsed all i-2 into a single 24\n i minus (i - 1), // = 1\n 24 times 1)\n def solution(i: Int) = {\n if(i % 2 == 0) {\n fourSolution ++ ((2 to i/2) map (_ * 2) flatMap incSolution)\n } else {\n fiveSolution ++ ((3 to i/2) map (_ * 2 + 1) flatMap incSolution)\n }\n }\n println(\"YES\")\n println(solution(n).mkString(\"\\n\"))\n }\n}"}], "src_uid": "1bd1a7fd2a07e3f8633d5bc83d837769"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 998244353\n\n /*\n * 10^18までのpowを配列で用意しておく\n */\n val pow10 = Array.ofDim[Long](30)\n pow10(0) = 1\n REP(pow10.length - 1)(i => pow10(i + 1) = pow10(i) * 10 % MOD)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val MAX = 10\n val D = Array.ofDim[Int](MAX)\n REP(N) { i =>\n D(log10(A(i))) += 1\n }\n debug(D)\n\n var ans = 0L\n def contributeX(x: Int): Unit = {\n var a = x\n REP(MAX) { i =>\n val d = a % 10\n REP(MAX) { j =>\n val k = i + (min(i, j) + 1)\n ans += pow10(k) * d % MOD * D(j) % MOD\n debug(s\"contributeX i:$i j:$j k:$k d:$d Dj:${D(j)} ans:$ans\")\n }\n a /= 10\n }\n ans %= MOD\n }\n\n def contributeY(y: Int): Unit = {\n var a = y\n REP(MAX) { i =>\n val d = a % 10\n REP(MAX) { j =>\n val k = i + min(i - 1, j) + 1\n ans += pow10(k) * d % MOD * D(j) % MOD\n debug(s\"contributeY i:$i j:$j k:$k d:$d Dj:${D(j)} ans:$ans\")\n }\n a /= 10\n }\n ans %= MOD\n }\n\n\n REP(N) { i =>\n contributeX(A(i))\n contributeY(A(i))\n }\n\n out.println(ans)\n }\n\n /**\n * @return log10の整数値\n */\n def log10(x: Long): Int = {\n var a = x\n var i = 0\n while(a >= 10) {\n a /= 10\n i += 1\n }\n i\n }\n}", "positive_code": [{"source_code": "import java.io.FileInputStream\nimport scala.collection.mutable.TreeSet\n\nobject HelloWorld {\n\n import scala.io.StdIn.{readInt, readLine}\n\n private val MOD = 998244353\n private val pow10: Array[Long] = new Array[Long](31)\n pow10(0) = 1\n for (i <- 1 until 31) {\n pow10(i) = mult(pow10(i - 1), 10)\n }\n\n def add(a: Long, b: Long): Long = {\n var tmp = a + b\n if (tmp >= MOD) tmp -= MOD\n if (tmp < 0) tmp += MOD\n tmp\n }\n\n def mult(a: Long, b: Long): Long = (a * b) % MOD\n\n def f(aOrig: Long): Long = {\n var deg = 0\n var ans: Long = 0\n var a = aOrig\n while (a > 0) {\n val digit = a % 10L\n ans = add(ans, mult(digit, pow10(deg)))\n ans = add(ans, mult(digit, pow10(deg + 1)))\n deg += 2\n a /= 10L\n }\n ans\n }\n\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val arr: Array[Long] = readLine().split(\" \").map(_.toLong)\n val result = arr.map(x => mult(n, f(x)))\n .reduceLeft((acc: Long, x:Long) => add(acc, x))\n println(result)\n }\n}\n"}], "negative_code": [], "src_uid": "6e093dbcbcaa7c87c9b62546745984db"} {"source_code": "object Main extends App {\n\n import io.StdIn\n\n val n = StdIn.readInt\n\n val cnt = new Array[Int](10)\n val notZero = new Array[Boolean](10)\n\n for (i <- 0 until n) {\n val s = StdIn.readLine()\n val l = s.length\n notZero(s.charAt(0) - 'a') = true\n var d = 1\n for (i <- 0 to l-1) {\n val ch = s(l - i - 1)\n cnt(ch - 'a') += d\n d *= 10\n }\n }\n\n var cur = 1\n var usedZero = false\n var ans = 0\n\n for (i <- 0 to 9) {\n\n var mx = 0\n for (j <- 0 to 9)\n if (cnt(j) > cnt(mx)) mx = j\n if (!usedZero && !notZero(mx)) {\n usedZero = true\n }\n else {\n ans += cnt(mx) * cur\n cur += 1\n }\n\n cnt(mx) = 0\n }\n\n println(ans)\n\n}", "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject MinimumSum extends App {\n val cantBeZero: mutable.Set[Char] = mutable.Set.empty\n val counts: mutable.ArrayBuffer[(Char, Int)] = mutable.ArrayBuffer()\n for (c <- 'a' to 'j') counts.append((c, 0))\n (for (_ <- 0 until StdIn.readLine().toInt) yield StdIn.readLine())\n .foreach(str => {\n cantBeZero += str.charAt(0)\n for (\n offset <- str.length - 1 to(0, -1)\n ) {\n val char: Char = str.charAt(offset)\n val sum = math.pow(10, str.length - 1 - offset).toInt\n counts(char - 'a') = (char, counts(char - 'a')._2 + sum)\n }\n })\n val availableChars: mutable.ListBuffer[Int] = mutable.ListBuffer()\n availableChars.appendAll(0 to 9)\n var totalSum = 0\n counts.sortBy(-_._2).foreach { case (char, sum) =>\n var digit = availableChars.head\n if (digit == 0 && cantBeZero.contains(char)) {\n digit = availableChars.remove(1)\n } else {\n availableChars.remove(0)\n }\n totalSum = totalSum + digit * sum\n }\n println(totalSum)\n}"}], "negative_code": [{"source_code": "object Main extends App {\n\n import io.StdIn\n\n val n = StdIn.readInt\n\n val cnt = new Array[Int](10)\n val notZero = new Array[Boolean](10)\n\n for (i <- 0 until n) {\n val s = StdIn.readLine()\n val l = s.length\n if (l > 1) notZero(s.charAt(0) - 'a') = true\n var d = 1\n for (i <- 0 to l-1) {\n val ch = s(l - i - 1)\n cnt(ch - 'a') += d\n d *= 10\n }\n }\n\n var cur = 1\n var usedZero = false\n var ans = 0\n\n for (i <- 0 to 9) {\n\n var mx = 0\n for (j <- 0 to 9)\n if (cnt(j) > cnt(mx)) mx = j\n if (!usedZero && !notZero(mx)) {\n usedZero = true\n }\n else {\n ans += cnt(mx) * cur\n cur += 1\n }\n\n cnt(mx) = 0\n }\n\n println(ans)\n\n}"}], "src_uid": "f67e221f88a8277b60a9b8fcb90a163d"} {"source_code": "object main extends App with fastIO {\n \n var num = 0\n \n def writestr(str: String, n: Int) {\n var need = n - str.length\n var add = \n if ((need & 1) == 1 && num == 1) \n need - (need >> 1); else\n need >> 1 \n \n num ^= need & 1\n \n print(\"*\")\n for (i <- 1 to add) print(\" \")\n print(str)\n for (i <- 1 to need - add) print(\" \")\n println(\"*\");\n }\n \n \n var lines = Stream.continually(readLine).takeWhile(_ != null) \n val maxLen = lines.reduceLeft((x, y) => if (x.length > y.length) x else y).length\n \n var str = \"\"\n for (i <- 1 to maxLen + 2) \n str += \"*\"\n \n println(str)\n for (line <- lines) writestr(line, maxLen)\n println(str)\n \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject BCentering extends App {\n\n val scanner = new Scanner(System.in)\n\n val input = scala.collection.mutable.ArrayBuffer.empty[String]\n\n //(0 until 12) foreach {\n //i =>\n while (scanner.hasNextLine) {\n input += scanner.nextLine()\n }\n\n val max = input.maxBy(_.length).length\n\n def solve(marginLeft: Boolean, rest: List[String]): List[String] = {\n rest match {\n case Nil => Nil\n case x :: xs =>\n if (same(x)) normalize(x) :: solve(marginLeft, xs)\n else if (marginLeft) normalize(\" \" + x) :: solve(!marginLeft, xs)\n else normalize(x + \" \") :: solve(!marginLeft, xs)\n }\n }\n\n println(\"*\" * (max + 2))\n println(solve(false, input.toList).mkString(\"\\n\"))\n println(\"*\" * (max + 2))\n\n def same(s: String): Boolean = max % 2 == s.length % 2\n\n def normalize(s: String): String = {\n val diff = (max - s.length) / 2\n \"*\" + \" \" * diff + s + \" \" * diff + \"*\"\n }\n\n\n\n\n}\n"}, {"source_code": "object B5 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n var arr = cu.ArrayBuffer.empty[String]\n var in = read\n while(in != null) {\n arr.append(in)\n in = read\n }\n val len = arr.map(_.length).max\n val res = Array.fill(arr.length+2)(Array.fill(len+2)(' '))\n for(j <- 0 until len+2) {\n res(0)(j) = '*'\n res.last(j) = '*'\n }\n for(i <- res.indices) {\n res(i)(0) = '*'\n res(i)(len+1) = '*'\n }\n var d = 0\n for(i <- arr.indices) {\n val frontPadding = 1 + (len-arr(i).length+d)/2\n for(j <- frontPadding until frontPadding+arr(i).length)\n res(i+1)(j) = arr(i)(j-frontPadding)\n if(arr(i).length%2 != len%2)\n d = 1-d\n }\n println(res.map(_.mkString(\"\")).mkString(\"\\n\"))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n// private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "\n\n/**\n * Created by yangchaozhong on 3/10/15.\n */\nobject CF5B extends App {\n import scala.collection.mutable.ArrayBuffer\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val lines = ArrayBuffer[String]()\n var maxLength = 0\n while (in.hasNextLine) {\n val s = nextLine\n lines += s\n maxLength = if (s.length > maxLength) s.length else maxLength\n }\n\n val startAndEnd = (1 to (maxLength + 2)).map(x => \"*\").mkString(\"\")\n out.println(startAndEnd)\n\n var isLeft = true\n lines.foreach { line =>\n if (line.length > 0) {\n var leftLen = (maxLength - line.length) / 2\n var rightLen = maxLength - line.length - leftLen\n\n if (leftLen != rightLen) {\n if (!isLeft) {\n val temp = leftLen\n leftLen = rightLen\n rightLen = temp\n }\n\n isLeft = !isLeft\n }\n val left = (1 to leftLen).map(x => \" \").mkString(\"\")\n val right = (1 to rightLen).map(x => \" \").mkString(\"\")\n out.println(s\"*${left}${line}${right}*\")\n } else {\n out.println(s\"*${(1 to maxLength).map(x => \" \").mkString(\"\")}*\")\n }\n }\n\n out.println(startAndEnd)\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n"}, {"source_code": "object main extends App with fastIO {\n \n var num = 0\n \n def writestr(str: String, n: Int) {\n var need = n - str.length\n var add = \n if ((need & 1) == 1 && num == 1) \n need - (need >> 1); else\n need >> 1 \n \n num ^= need & 1\n \n println(\"*\" + \" \" * add + str + \" \" * (need - add) + \"*\") \n } \n \n var lines = Stream.continually(readLine).takeWhile(_ != null)\n val maxLen = lines.map(_.length).max\n \n val str = \"*\" * (maxLen + 2)\n \n println(str)\n for (line <- lines) writestr(line, maxLen)\n println(str)\n \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}, {"source_code": "object P5B {\n def main(args: Array[String]) {\n val b = io.Source.stdin.getLines.toBuffer\n val w = b.map{_.size}.max\n println(\"*\" * (w + 2))\n var alt = 0\n for (i <- b) {\n val s = w - i.size\n val s0 = s >> 1\n val s1 = s - s0\n def print(sLeft : Int, sRight : Int) {\n println(\"*\" + \" \" * sLeft + i + \" \" * sRight + \"*\")\n }\n alt match {\n case _ if s0 == s1 => print(s0, s0)\n case 0 => {alt = 1; print(s0, s1)}\n case 1 => {alt = 0; print(s1, s0)}\n }\n }\n println(\"*\" * (w + 2))\n }\n}\n"}, {"source_code": "object Main {\n def repeat(n: Int)(char: Char): String = (0 until n).map(_=>char).mkString\n def main(args: Array[String]) = {\n val strings = io.Source.stdin.getLines.toVector\n val lengths = strings map (s => s.length)\n val maxLens = lengths.max\n lazy val leftOrRight = lengths.map(l => (maxLens - l) % 2 != 0)\n .foldLeft((true, Vector.empty[Boolean])){case (accu, bool) => if(!bool) (accu._1, accu._2 :+ bool)\n else (accu._1 ^ bool, accu._2 :+ (accu._1 ^ bool))}._2\n\n lazy val outputs = for ( i <- 0 until strings.length ) yield {\n val left = if(leftOrRight(i)) (maxLens - lengths(i)) / 2 + 1\n else (maxLens - lengths(i)) / 2\n val right = maxLens - lengths(i) - left\n \"*\" + repeat(left)(' ') + strings(i) + repeat(right)(' ') + \"*\"\n }\n println(repeat(maxLens+2)('*'))\n for (str <- outputs) println(str)\n println(repeat(maxLens+2)('*'))\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def repeat(n: Int)(char: Char): String = (0 until n).map(_=>char).mkString\n def main(args: Array[String]) = {\n val strings = io.Source.stdin.getLines.toVector\n val lengths = strings map (s => s.length)\n val maxLens = lengths.max\n val leftOrRight = lengths.map(l => (maxLens - l) % 2 != 0)\n .foldLeft((true, Vector.empty[Boolean])){case (accu, bool) => if(!bool) (accu._1, accu._2 :+ bool)\n else (accu._1 ^ bool, accu._2 :+ (accu._1 ^ bool))}._2\n\n val outputs = for ( i <- 0 until strings.length ) yield {\n val left = if(leftOrRight(i)) (maxLens - lengths(i)) / 2 + 1\n else (maxLens - lengths(i)) / 2\n val right = maxLens - lengths(i) - left\n \"*\" + repeat(left)(' ') + strings(i) + repeat(right)(' ') + \"*\"\n }\n for (b <- leftOrRight) println(b)\n println(repeat(maxLens+2)('*'))\n for (str <- outputs) println(str)\n println(repeat(maxLens+2)('*'))\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject BCentering extends App {\n\n val scanner = new Scanner(System.in)\n\n val input = scala.collection.mutable.ArrayBuffer.empty[String]\n\n while (scanner.hasNext) {\n input += scanner.nextLine()\n }\n\n val max = input.maxBy(_.length).length\n\n def solve(marginLeft: Boolean, rest: List[String]): List[String] = {\n rest match {\n case Nil => Nil\n case x :: xs =>\n if (same(x)) normalize(x) :: solve(marginLeft, xs)\n else if (marginLeft) normalize(\" \" + x) :: solve(!marginLeft, xs)\n else normalize(x + \" \") :: solve(!marginLeft, xs)\n }\n }\n\n println(\"*\" * (max + 2))\n println(solve(false, input.toList).mkString(\"\\n\"))\n println(\"*\" * (max + 2))\n\n def same(s: String): Boolean = max % 2 == s.length % 2\n\n def normalize(s: String): String = {\n val diff = (max - s.length) / 2\n \"*\" + \" \" * diff + s + \" \" * diff + \"*\"\n }\n\n\n}\n"}, {"source_code": "object B5 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n var arr = cu.ArrayBuffer.empty[String]\n var in = read\n while(in != null) {\n arr.append(in)\n in = read\n }\n val len = arr.map(_.length).max\n val res = Array.fill(arr.length+2)(Array.fill(len+2)(' '))\n for(j <- 0 until len+2) {\n res(0)(j) = '*'\n res.last(j) = '*'\n }\n for(i <- res.indices) {\n res(i)(0) = '*'\n res(i)(len+1) = '*'\n }\n var d = 0\n for(i <- arr.indices) {\n val frontPadding = 1 + (len-arr(i).length+d)/2\n for(j <- frontPadding until frontPadding+arr(i).length)\n res(i+1)(j) = arr(i)(j-frontPadding)\n d = 1-d\n }\n println(res.map(_.mkString(\"\")).mkString(\"\\n\"))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "\n\n/**\n * Created by yangchaozhong on 3/10/15.\n */\nobject CF5B extends App {\n import scala.collection.mutable.ArrayBuffer\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val lines = ArrayBuffer[String]()\n var maxLength = 0\n while (in.hasNext) {\n val s = nextLine\n lines += s\n maxLength = if (s.length > maxLength) s.length else maxLength\n }\n\n val startAndEnd = (1 to (maxLength + 2)).map(x => \"*\").mkString(\"\")\n out.println(startAndEnd)\n lines.foreach { line =>\n if (line.length > 0) {\n val leftLen = (maxLength - line.length) / 2\n val rightLen = maxLength - line.length - leftLen\n val left = (1 to leftLen).map(x => \" \").mkString(\"\")\n val right = (1 to rightLen).map(x => \" \").mkString(\"\")\n out.println(s\"*${left}${line}${right}*\")\n } else {\n out.println(s\"*${(1 to maxLength).map(x => \" \").mkString(\"\")}*\")\n }\n }\n\n out.println(startAndEnd)\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n\n}\n"}, {"source_code": "\n\n/**\n * Created by yangchaozhong on 3/10/15.\n */\nobject CF5B extends App {\n import scala.collection.mutable.ArrayBuffer\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val lines = ArrayBuffer[String]()\n var maxLength = 0\n while (in.hasNext) {\n val s = nextLine\n lines += s\n maxLength = if (s.length > maxLength) s.length else maxLength\n }\n\n val startAndEnd = (1 to (maxLength + 2)).map(x => \"*\").mkString(\"\")\n out.println(startAndEnd)\n lines.foreach { line =>\n val supp = if (line.length > 0) {\n (1 to (maxLength - line.length) / 2).map(x => \" \")\n } else {\n (1 to maxLength).map(x => \" \")\n }\n out.println(s\"*${supp}${line}${supp}*\")\n }\n\n out.println(startAndEnd)\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n\n}\n"}, {"source_code": "\n\n/**\n * Created by yangchaozhong on 3/10/15.\n */\nobject CF5B extends App {\n import scala.collection.mutable.ArrayBuffer\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val lines = ArrayBuffer[String]()\n var maxLength = 0\n while (in.hasNext) {\n val s = nextLine\n lines += s\n maxLength = if (s.length > maxLength) s.length else maxLength\n }\n\n val startAndEnd = (1 to (maxLength + 2)).map(x => \"*\").mkString(\"\")\n out.println(startAndEnd)\n lines.foreach { line =>\n val supp = if (line.length > 0) {\n (1 to (maxLength - line.length) / 2).map(x => \" \").mkString(\"\")\n } else {\n (1 to maxLength).map(x => \" \").mkString(\"\")\n }\n out.println(s\"*${supp}${line}${supp}*\")\n }\n\n out.println(startAndEnd)\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n\n}\n"}, {"source_code": "\n\n/**\n * Created by yangchaozhong on 3/10/15.\n */\nobject CF5B extends App {\n import scala.collection.mutable.ArrayBuffer\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val lines = ArrayBuffer[String]()\n var maxLength = 0\n while (in.hasNext) {\n val s = nextLine\n lines += s\n maxLength = if (s.length > maxLength) s.length else maxLength\n }\n\n val startAndEnd = (1 to (maxLength + 2)).map(x => \"*\").mkString(\"\")\n out.println(startAndEnd)\n lines.foreach { line =>\n if (line.length > 0) {\n val leftLen = (maxLength - line.length) / 2\n val rightLen = maxLength - leftLen\n val left = (1 to leftLen).map(x => \" \").mkString(\"\")\n val right = (1 to rightLen).map(x => \" \").mkString(\"\")\n out.println(s\"*${left}${line}${right}*\")\n } else {\n out.println(s\"*${(1 to maxLength).map(x => \" \").mkString(\"\")}*\")\n }\n }\n\n out.println(startAndEnd)\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n\n}\n"}, {"source_code": "\n\n/**\n * Created by yangchaozhong on 3/10/15.\n */\nobject CF5B extends App {\n import scala.collection.mutable.ArrayBuffer\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val lines = ArrayBuffer[String]()\n var maxLength = 0\n while (in.hasNext) {\n val s = nextLine\n lines += s\n maxLength = if (s.length > maxLength) s.length else maxLength\n }\n\n val startAndEnd = (1 to (maxLength + 2)).map(x => \"*\").mkString(\"\")\n out.println(startAndEnd)\n\n var isLeft = true\n lines.foreach { line =>\n if (line.length > 0) {\n var leftLen = (maxLength - line.length) / 2\n var rightLen = maxLength - line.length - leftLen\n\n if (leftLen != rightLen) {\n if (!isLeft) {\n val temp = leftLen\n leftLen = rightLen\n rightLen = temp\n }\n\n isLeft = !isLeft\n }\n val left = (1 to leftLen).map(x => \" \").mkString(\"\")\n val right = (1 to rightLen).map(x => \" \").mkString(\"\")\n out.println(s\"*${left}${line}${right}*\")\n } else {\n out.println(s\"*${(1 to maxLength).map(x => \" \").mkString(\"\")}*\")\n }\n }\n\n out.println(startAndEnd)\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n"}], "src_uid": "a017393743ae70a4d8a9d9dc40410653"} {"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 30.08.14.\n */\nobject A extends App {\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n val s = nextInt\n var max = -1\n for(i <- 0 until n) {\n val x = nextInt\n val y = nextInt\n if(y == 0) {\n if(s >= x) {\n max = math.max(max, 0)\n }\n } else {\n if(s >= x + 1) {\n max = math.max(max, 100 - y)\n }\n }\n }\n out.print(max)\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}", "positive_code": [{"source_code": "object Codeforces extends App {\n val in = new java.util.Scanner(System.in)\n var n = in.nextInt()\n var s = in.nextInt() * 100\n var res = -1\n for (i <- 1 to n) {\n var cur = in.nextInt() * 100 + in.nextInt()\n if (s >= cur)\n res = math.max(res, (s - cur) % 100)\n }\n println(res)\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _463A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val s = next.toInt\n val ans = for {\n i <- 1 to n\n val a = next.toInt\n val b = next.toInt\n if (a < s || (a == s && b == 0))\n } yield (100 - b) % 100\n if (ans.length == 0) println(-1)\n else println(ans.max)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, s) = in.next().split(\" \").map(_.toInt)\n val r = Range(0, n).map{_ =>\n val d = in.next().split(\" \").map(_.toInt)\n s * 100 - (d(0) * 100 + d(1))\n }.filter(_ >= 0).map(_ % 100)\n if (r.isEmpty)\n println(-1)\n else\n println(r.max)\n}\n"}, {"source_code": "object A463 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n var Array(n, s) = readInts(2)\n s *= 100\n val in = Array.fill(n)(readInts(2)).map{\n arr => s\"${arr(0)}${if(arr(1)<10)\"0\" else \"\"}${arr(1)}\".toInt\n }\n var res = 0\n for(i <- 0 until n) {\n if(s >= in(i)) {\n res = math.max(res, (s - in(i))%100)\n }\n }\n if(in.forall(_ > s)) {\n println(\"-1\")\n } else {\n println(res)\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val cin = new java.util.Scanner(System.in)\n val n = cin.nextInt()\n val s = cin.nextInt()\n def solve(n: Int, mx: Int): Int =\n if (n == 0) mx\n else {\n val x = cin.nextInt()\n val y = cin.nextInt()\n if (x < s && y > 0) solve(n - 1, Math.max(mx, 100 - y))\n else if (x <= s && y == 0) solve(n - 1, Math.max(mx, 0))\n else solve(n - 1, mx)\n }\n println(solve(n, -1))\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-28.\n */\nobject A463 extends App {\n val sc = new Scanner(System.in)\n val n, s = sc.nextInt()\n val allMoney = new Money(s, 0)\n var i = 0\n var maxSweets = -1\n\n while (i < n) {\n val m = new Money(sc.nextInt(), sc.nextInt())\n var j = 1\n\n while (m * j <= allMoney) {\n val spend = m * j\n val restMoney = allMoney - spend\n maxSweets = Math.max(restMoney.cent, maxSweets)\n j += 1\n }\n\n i += 1\n }\n\n print(maxSweets)\n}\n\nclass Money(val dollar: Int, val cent: Int) {\n def * (that: Int): Money = {\n var up = 0\n var newCent = 0\n var newDollar = 0\n\n if (cent * that < 100) {\n newCent = cent\n } else {\n up = cent / 100\n newCent = cent % 100\n }\n\n newDollar = dollar * that + up\n new Money(newDollar, newCent)\n }\n\n def <= (that: Money): Boolean = {\n if (this.dollar < that.dollar) {\n true\n } else if (this.dollar == that.dollar){\n if (this.cent <= that.cent) {\n true\n } else {\n false\n }\n } else {\n false\n }\n }\n\n def - (that: Money): Money = {\n var newCent = 0\n var down = 0\n\n if (this.cent >= that.cent) {\n newCent = this.cent - that.cent\n } else {\n down = 1\n newCent = this.cent + 100 - that.cent\n }\n\n new Money(this.dollar - down - that.dollar, newCent)\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, s) = in.next().split(\" \").map(_.toInt)\n val r = Range(0, n).map{_ =>\n val d = in.next().split(\" \").map(_.toInt)\n d(0) * 100 + d(1)\n }.filter(_ < s).map(_ % 100)\n if (r.isEmpty)\n println(-1)\n else\n println(r.max)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, s) = in.next().split(\" \").map(_.toInt)\n val r = Range(0, n).map{_ =>\n val d = in.next().split(\" \").map(_.toInt)\n d(0) * 100 + d(1)\n }.filter(_ < s).map(99 - _ % 100)\n if (r.isEmpty)\n println(-1)\n else\n println(r.max)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, s) = in.next().split(\" \").map(_.toInt)\n val r = Range(0, n).map{_ =>\n val d = in.next().split(\" \").map(_.toInt)\n d(0) * 100 + d(1)\n }.filter(_ < s).map(99 - _ % 100)\n if (r.isEmpty)\n println(-1)\n else\n println(r.max)\n}\n"}, {"source_code": "object A463 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n var Array(n, s) = readInts(2)\n s *= 100\n val in = Array.fill(n)(readInts(2)).map{\n arr => (s\"${arr(0)}.${arr(1)}\".toDouble * 100).toInt\n }\n var res = 0\n for(i <- 0 until n) {\n if(s >= in(i) && in(i)%100 != 0) {\n res = math.max(res, 100 - (in(i)%100))\n }\n }\n if(in.forall(_ > s)) {\n println(\"-1\")\n } else {\n println(res)\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object A463 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n var Array(n, s) = readInts(2)\n s *= 100\n val in = Array.fill(n)(readInts(2)).map{\n arr => (s\"${arr(0)}.${if(arr(1)<10)\"0\" else \"\"}${arr(1)}\".toDouble * 100).toInt\n }\n var res = 0\n for(i <- 0 until n) {\n if(s >= in(i)) {\n res = math.max(res, (s - in(i))%100)\n }\n }\n if(in.forall(_ > s)) {\n println(\"-1\")\n } else {\n println(res)\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val cin = new java.util.Scanner(System.in)\n val n = cin.nextInt()\n val s = cin.nextInt()\n def solve(n: Int, mx: Int): Int =\n if (n == 0) mx\n else {\n val x = cin.nextInt()\n val y = cin.nextInt()\n if (x < s && y > 0) solve(n - 1, Math.max(mx, 100 - y))\n else if (x == s && y == 0) solve(n - 1, Math.max(mx, 0))\n else solve(n - 1, mx)\n }\n println(solve(n, -1))\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-28.\n */\nobject A463 extends App {\n val sc = new Scanner(System.in)\n val n, s = sc.nextInt()\n var i = 0\n var maxSweets: Double = -1\n\n while (i < n) {\n val x, y = sc.nextInt()\n val d = x + y / 100.0\n var j = 1\n\n while (d * j <= s) {\n maxSweets = Math.max(((s - d * j) % 1) * 100, maxSweets)\n j += 1\n }\n\n i += 1\n }\n\n print(maxSweets.toInt)\n}\n"}], "src_uid": "91be5db48b44a44adff4c809ffbb8e3e"} {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val a = readLine().toCharArray\n val m = readLine()\n val b = readIntLine()\n handle(a, b.toArray)\n }\n }\n\n def handle(arr: Array[Char], list: Array[Int]): Unit = {\n def findLetter(length: Int, list: List[(Char, Int)]): (Char, List[(Char, Int)]) = list match {\n case Nil => throw new IllegalStateException()\n case (c, r) :: rest => if (r >= length) (c, rest) else findLetter(length, rest)\n }\n\n var gr = arr.groupBy(i => i).map(tup => (tup._1, tup._2.length)).toList.sortBy(tup => tup._1).reverse\n\n var containsZero = true\n val t = Array.ofDim[Char](list.length)\n\n while (containsZero) {\n containsZero = false\n var l = List[Int]()\n for (i <- list.indices) {\n if (list(i) == 0)\n l = i :: l\n }\n if (l.nonEmpty) {\n containsZero = true\n val tup = findLetter(l.length, gr)\n val letter = tup._1\n gr = tup._2\n l.foreach(i => t(i) = letter)\n l.foreach(j => {\n list(j) = list(j) - 1\n for (i <- list.indices) {\n list(i) = list(i) - Math.abs(i - j)\n }\n })\n }\n }\n\n t.foreach(print)\n println()\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n", "positive_code": [{"source_code": "object D extends App {\n import scala.io.StdIn._\n\n val q = readInt()\n\n (0 until q).foreach { _ =>\n val s = readLine()\n val m = readInt()\n var bm = readLine().split(\" \").map(_.toInt)\n\n var t = Array.ofDim[Char](m)\n val o = s.distinct.sorted(Ordering.Char.reverse).map(c => (c, s.count(c == _)))\n\n (0 until m).foldLeft(0) {\n case (prev, _) =>\n val is = bm.zipWithIndex.collect { case (b, i) if b == 0 => i }\n val curr = o.indexWhere(_._2 >= is.length, prev)\n\n is.foreach(t(_) = o(curr)._1)\n\n (0 until m).foreach { j =>\n bm(j) = bm(j) match {\n case 0 | -1 => -1\n case b => is.foldLeft(b)((b, i) => b - (i - j).abs)\n }\n }\n\n curr + 1\n }\n\n println(t.mkString)\n }\n}\n"}, {"source_code": "object Main extends App {\n val r = new FastScanner(java.lang.System.in)\n val o = new java.io.PrintWriter(java.lang.System.out)\n for(_ <- 1 to r.nextInt()) {\n val s = r.nextToken()\n val m = r.nextInt()\n val b = Array.fill(m)(r.nextInt())\n val c = Array.ofDim[Int](26)\n //val x = Array.ofDim[Int](m)\n for(k <- 0 until s.length) c(s(k).toInt - 97) += 1\n val used = Array.fill[Int](m)(-1)\n def loop(k: Int): Unit = {\n if(used.count { _ >= 0 } != m) {\n val l = (for(j <- 0 until m if (used(j) < 0) && b(j) == 0) yield j).toList\n for(j <- 0 until m if (used(j) < 0 && b(j) > 0); i <- l) {\n b(j) -= (j - i).abs\n require(b(j) >= 0)\n }\n for(i <- l) {\n used(i) = k \n }\n loop(k + 1)\n }\n }\n loop(0)\n val d = Array.ofDim[Int](m)\n for(i <- used) d(i) += 1\n val x = Array.ofDim[Char](m)\n var j = 25\n for(i <- 0 until m if (d(i) > 0)) {\n while(j >= 0 && c(j) < d(i)) j -= 1\n for(o <- 0 until m if used(o) == i) x(o) = (j + 97).toChar\n j -= 1\n }\n for(i <- x) o.print(i)\n o.println()\n }\n o.close()\n}\n\nimport scala.annotation.tailrec\nimport scala.collection.mutable.StringBuilder\n\nobject FastScanner {\n val zero = 0.toByte\n val cr = '\\r'.toByte\n val nl = '\\n'.toByte\n val BUFFER_SIZE = 0x10000\n}\n\nclass FastScanner(private val input: java.io.InputStream) {\n private val b = new Array[Byte](FastScanner.BUFFER_SIZE)\n private var n = 0\n private var pos = 0\n private var eof = false\n private def read ():Boolean = {\n if (eof) {\n return false\n }\n pos = 0\n n = input.read(b)\n if (n < 0) {\n eof = true\n }\n n > 0\n }\n private def nextByte(): Byte = {\n if (pos >= n && !read ()) {\n 0\n } else {\n val r = b(pos)\n pos += 1\n r\n }\n }\n def nextToken(k: Int = -1): String = {\n val sb = if(k >= 0) new StringBuilder(k) else new StringBuilder()\n var b = skipBlanks()\n assert(b > 0)\n while(b > 32) {\n sb.append(b.toChar)\n b = nextByte()\n }\n sb.toString\n }\n @tailrec\n private def skipBlanks(): Byte = {\n val b = nextByte()\n if(b > 32 || b < 1) b else skipBlanks()\n }\n def nextInt():Int = {\n val b = skipBlanks()\n @tailrec\n def f(t: Int): Int = {\n val b = nextByte ()\n if (b <= 32) t else f(10 * t + (b - 48))\n }\n require(b > 0)\n if (b < 48) -f(0) else f(b - 48)\n }\n}\n\n"}, {"source_code": "//package codeforces.contests._1367\n\nobject _4 {\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val chars: List[(Char, Int)] = {\n val freq = new Array[Int](26)\n io.StdIn.readLine.foreach { c => freq(c - 'a') += 1 }\n\n freq.indices.map(i => ('a' + i).toChar -> freq(i)).reverse.toList\n }\n\n val m = io.StdIn.readInt\n\n val result = new Array[Char](m)\n\n val ms: Array[Int] = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n @scala.annotation.tailrec\n def loop(chars: List[(Char, Int)]): Unit = {\n val zeroIndexes = ms.indices.filter(ms(_) == 0)\n\n if (zeroIndexes.nonEmpty) {\n val (c, count) :: tail = chars\n\n if (count >= zeroIndexes.length) {\n\n zeroIndexes.foreach { i => ms(i) = -1; result(i) = c }\n\n zeroIndexes.foreach { z =>\n (z + 1 until m).foreach { r =>\n if (ms(r) > 0) {\n ms(r) -= r - z\n }\n }\n\n (z - 1 to 0 by -1).foreach { l =>\n if (ms(l) > 0) {\n ms(l) -= z - l\n }\n }\n }\n }\n loop(tail)\n }\n }\n\n loop(chars)\n\n println(result.mkString(\"\"))\n }\n }\n\n}\n"}, {"source_code": "object D extends App {\n import scala.io.StdIn._\n\n val q = readInt()\n\n (0 until q).foreach { _ =>\n val s = readLine()\n val m = readInt()\n val bm = readLine().split(\" \").map(_.toInt)\n\n var t = Array.ofDim[Char](m)\n\n val o = s.distinct.sorted(Ordering.Char.reverse).map(c => (c, s.count(c == _)))\n\n (0 until m).foldLeft((bm, 0)) {\n case ((bm, shift), k) =>\n val is = bm.zipWithIndex.collect { case (b, i) if b == 0 => i }\n\n val tfihs = o.indexWhere({ case (c, l) => l >= is.length }, shift)\n is.foreach(i => t(i) = o(tfihs)._1)\n\n (bm.zipWithIndex.map {\n case (0, _) | (-1, _) => -1\n case (b, j) => is.foldLeft(b)((b, i) => b - (i - j).abs)\n }, tfihs + 1)\n }\n\n println(t.mkString)\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val a = readLine().toCharArray\n val m = readLine()\n val b = readIntLine()\n handle(a, b.toArray)\n }\n }\n\n def handle(arr: Array[Char], list: Array[Int]): Unit = {\n def findLetter(length: Int, list: List[(Char, Int)]): (Char, List[(Char, Int)]) = list match {\n case Nil => throw new IllegalStateException()\n case (c, r) :: rest => if (r >= length) (c, rest) else findLetter(length, rest)\n }\n\n var gr = arr.groupBy(i => i).map(tup => (tup._1, tup._2.length)).toList.sortBy(tup => tup._1).reverse\n\n var containsZero = true\n val t = Array.ofDim[Char](list.length)\n\n while (containsZero) {\n containsZero = false\n var l = List[Int]()\n for (i <- list.indices) {\n if (list(i) == 0)\n l = i :: l\n }\n if (l.nonEmpty) {\n containsZero = true\n val tup = findLetter(l.length, gr)\n val letter = tup._1\n gr = tup._2\n l.foreach(i => t(i) = letter)\n l.foreach(j => {\n list(j) = list(j) - 1\n for (i <- list.indices) {\n list(i) = list(i) - Math.abs(i - j)\n }\n })\n }\n }\n\n printArray(t)\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}], "src_uid": "bc2f2b98c50a0165b7204a6d595eec4b"} {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val m = nextInt\n val f = new Array[Array[Char]](n)\n for (i <- 0 until n) {\n f(i) = new Array[Char](m)\n f(i) = next.toCharArray\n }\n var left1 = (-1, -1)\n var right1 = (-1, -1)\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (f(i)(j) == '*' && left1._1 == -1) {\n left1 = (i, j)\n }\n if (f(i)(j) == '*') {\n right1 = (i, j)\n }\n }\n }\n var left2 = (-1, -1)\n var right2 = (-1, -1)\n for (j <- 0 until m) {\n for (i <- 0 until n) {\n if (f(i)(j) == '*' && left2._1 == -1) {\n left2 = (i, j)\n }\n if (f(i)(j) == '*') {\n right2 = (i, j)\n }\n }\n }\n for (i <- Math.min(left1._1, left2._1) to Math.max(right1._1, right2._1)) {\n for (j <- Math.min(left1._2, left2._2) to Math.max(right1._2, right2._2)) {\n out.print(f(i)(j))\n }\n out.println\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject ALetter extends App {\n\n val in = new InputReader(System.in)\n val n = in.nextInt\n val m = in.nextInt\n var arr = Array.ofDim[Char](n, m)\n var (minx, miny) = (Integer.MAX_VALUE, Integer.MAX_VALUE)\n var (maxx, maxy) = (-1, -1)\n for {\n i <- (0 until n)\n s = in.next\n j <- (0 until m)\n } {\n val cur = s(j)\n arr(i)(j) = cur\n if (cur == '.') {\n\n } else {\n if (i < miny) {\n miny = i\n }\n if (i >= maxy) {\n maxy = i\n }\n if (j < minx) {\n minx = j\n }\n if (j >= maxx) {\n maxx = j;\n }\n }\n\n }\n \n var i = miny;\n while (i <= maxy) {\n var j = minx;\n while (j <= maxx) {\n print(arr(i)(j))\n j += 1\n }\n println()\n i += 1\n }\n\n class InputReader {\n var reader: BufferedReader = null\n var tokenizer: StringTokenizer = null\n\n def this(stream: InputStream) {\n this()\n reader = new BufferedReader(new InputStreamReader(stream), 32768)\n tokenizer = null\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n try {\n tokenizer = new StringTokenizer(reader.readLine)\n }\n catch {\n case e: IOException => {\n throw new RuntimeException(e)\n }\n }\n }\n return tokenizer.nextToken\n }\n\n def nextInt: Int = {\n return next.toInt\n }\n }\n\n}\n"}, {"source_code": "object A14 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val in = Array.fill(n)(read)\n val x1 = in.indexWhere(_.contains('*'))\n val x2 = in.lastIndexWhere(_.contains('*'))\n val y1 = in.map(_.indexWhere(_ == '*')).filter(_ != -1).min\n val y2 = in.map(_.lastIndexWhere(_ == '*')).filter(_ != -1).max\n\n for(i <- x1 to x2) {\n val buff = cu.ArrayBuffer.empty[Char]\n for(j <- y1 to y2) {\n buff.append(in(i)(j))\n }\n println(buff.mkString(\"\"))\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val res = (1 to n)\n .map(_ => in.next())\n .dropWhile(!_.contains('*'))\n .reverse\n .dropWhile(!_.contains('*'))\n .reverse\n val (left, right) = res.foldLeft(m - 1, 0) {\n case (acc, line) if !line.contains('*') => acc\n case ((l, r), line) => (Math.min(l, line.indexOf('*')), Math.max(r, line.lastIndexOf('*')))\n }\n\n println(res.map(_.substring(left, right + 1)).mkString(\"\\n\"))\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val res = (1 to n)\n .map(_ => in.next())\n .dropWhile(!_.contains('*'))\n .reverse\n .dropWhile(!_.contains('*'))\n .reverse\n val (left, right) = res.foldLeft(n - 1, 0) {\n case (acc, line) if !line.contains('*') => acc\n case ((l, r), line) => (Math.min(l, line.indexOf('*')), Math.max(r, line.lastIndexOf('*')))\n }\n\n println(res.map(_.substring(left, right + 1)).mkString(\"\\n\"))\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject ALetter extends App {\n\n val in = new InputReader(System.in)\n val n = in.nextInt\n val m = in.nextInt\n var arr = Array.ofDim[Char](n, m)\n var min = (Integer.MAX_VALUE, Integer.MAX_VALUE)\n var max = (-1, -1)\n for {\n i <- (0 until n)\n s = in.next\n j <- (0 until m)\n } {\n val cur = s(j)\n arr(i)(j) = cur\n if (cur == '.') {\n\n } else {\n if (i < min._1 && j < min._2) {\n min = (i, j)\n }\n if (i >= max._1 && j >= max._2) {\n max = (i, j)\n }\n }\n\n }\n\n for {\n i <- ((min._1) to (max._1)).iterator.map { x => println(); x }\n j <- (min._2) to (max._2)\n } {\n print(arr(i)(j))\n }\n\n\n class InputReader {\n var reader: BufferedReader = null\n var tokenizer: StringTokenizer = null\n\n def this(stream: InputStream) {\n this()\n reader = new BufferedReader(new InputStreamReader(stream), 32768)\n tokenizer = null\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n try {\n tokenizer = new StringTokenizer(reader.readLine)\n }\n catch {\n case e: IOException => {\n throw new RuntimeException(e)\n }\n }\n }\n return tokenizer.nextToken\n }\n\n def nextInt: Int = {\n return next.toInt\n }\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject ALetter extends App {\n\n val in = new InputReader(System.in)\n val n = in.nextInt\n val m = in.nextInt\n var arr = Array.ofDim[Char](n, m)\n var min = (Integer.MAX_VALUE, Integer.MAX_VALUE)\n var max = (-1, -1)\n for {\n i <- (0 until n)\n s = in.next\n j <- (0 until m)\n } {\n val cur = s(j)\n arr(i)(j) = cur\n if (cur == '.') {\n\n } else {\n if (i < min._1 && j < min._2) {\n min = (i, j)\n }\n if (i >= max._1 && j >= max._2) {\n max = (i, j)\n }\n }\n\n }\n\n var i = min._1;\n while (i <= max._1) {\n var j = min._2;\n while (j <= max._2) {\n print(arr(i)(j))\n j += 1\n }\n println()\n i += 1\n }\n\n class InputReader {\n var reader: BufferedReader = null\n var tokenizer: StringTokenizer = null\n\n def this(stream: InputStream) {\n this()\n reader = new BufferedReader(new InputStreamReader(stream), 32768)\n tokenizer = null\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n try {\n tokenizer = new StringTokenizer(reader.readLine)\n }\n catch {\n case e: IOException => {\n throw new RuntimeException(e)\n }\n }\n }\n return tokenizer.nextToken\n }\n\n def nextInt: Int = {\n return next.toInt\n }\n }\n\n}\n"}, {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val m = nextInt\n val f = new Array[Array[Char]](n)\n for (i <- 0 until n) {\n f(i) = new Array[Char](m)\n f(i) = next.toCharArray\n }\n var left = (-1, -1)\n var right = (-1, -1)\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (f(i)(j) == '*' && left._1 == -1) {\n left = (i, j)\n }\n if (f(i)(j) == '*') {\n right = (i, j)\n }\n }\n }\n for (i <- left._1 to right._1) {\n for (j <- left._2 to right._2) {\n out.print(f(i)(j))\n }\n out.println\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "src_uid": "d715095ff068f4d081b58fbfe103a02c"} {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n\n println(n)\n }\n}", "positive_code": [{"source_code": "\nobject A extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val m = in.nextInt()\n println(m)\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readInt\n\nobject Example extends App {\n val t = readInt()\n\n for (i <- 1 to t) {\n val n = readInt()\n println(n)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Solution {\n\n def main(args: Array[String]): Unit = {\n val t = StdIn.readInt()\n for (_ <- 1 to t) {\n val n = StdIn.readLong()\n println(n)\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject Solution {\n\n def main(args: Array[String]): Unit = {\n val t = StdIn.readInt()\n for (_ <- 1 to t) {\n val n = StdIn.readInt()\n val result= math.pow(2, n-1).toLong\n println(s\"$result\")\n Console.flush()\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Solution {\n\n def main(args: Array[String]): Unit = {\n val t = StdIn.readInt()\n for (_ <- 1 to t) {\n val n = StdIn.readInt()\n val result= math.pow(2, n-1).toLong\n println(s\"$result\")\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Solution {\n\n def main(args: Array[String]): Unit = {\n val t = StdIn.readInt()\n for (_ <- 1 to t) {\n val n = StdIn.readInt()\n val result= math.pow(2, n-1)\n println(s\"$result\")\n Console.flush()\n }\n }\n}\n"}], "src_uid": "740c05c036b646d8fb6b391af115d7f0"} {"source_code": "object C743 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readLongs(1)\n if(n == 1)\n println(\"-1\")\n else {\n println(s\"${n} ${n+1} ${n*(n+1)}\")\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import scala.annotation.tailrec\n\nobject C extends App {\n def readInts = readLine().split(\" \").map(_.toInt)\n\n val n = readInt()\n\n if (n == 1) println(\"-1\")\n else println(Seq(n, n+1, n*(n+1)).mkString(\" \"))\n}\n"}], "negative_code": [], "src_uid": "f60ea0f2caaec16894e84ba87f90c061"} {"source_code": "import scala.io.Source\r\n\r\nobject Contest extends App {\r\n val input = Source.fromInputStream(System.in).getLines()\r\n val t = input.next().toInt\r\n val arrays = new Array[Array[Long]](t)\r\n for (i <- 0 until t) {\r\n val n = input.next()\r\n arrays(i) = input.next().split(\" \").map(_.toLong)\r\n }\r\n\r\n arrays.map(calc).foreach(println)\r\n\r\n def calc(arr: Array[Long]): Long = {\r\n val n = arr.length\r\n val scores = arr.map(x => if (x == 0) 2 else 1)\r\n .zipWithIndex.map(x => (x._2 + 1, x._1))\r\n .map(x => x._1 * (n - x._1 + 1) * x._2)\r\n\r\n scores.sum\r\n }\r\n}", "positive_code": [{"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val size = readInt()\n val a = readInts()\n def findMax(i: Int, j: Int): Long = {\n val currentArray = a.slice(i, j + 1)\n currentArray.length + currentArray.count(_ == 0)\n }\n\n var answer: Long = 0\n 0.until(size).foreach { i =>\n 0.until(size).foreach { j =>\n if (i <= j) {\n answer += findMax(i, j)\n }\n }\n }\n\n println(answer)\n }\n\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}], "negative_code": [], "src_uid": "8775da9b78d8236c4606d150df450952"} {"source_code": "import scala.io.StdIn\nimport scala.math.min\n\nobject Solution {\n def printMatrix(matrix: Array[Array[Int]], n: Int, m: Int, i: Int, j: Int): Unit = {\n (i < n) match {\n case false => Unit\n case true => {\n (j < m) match {\n case false => {\n println(\"\")\n printMatrix(matrix, n, m, (i + 1), 0)\n }\n case true => {\n print(matrix(i)(j) + \" \")\n printMatrix(matrix, n, m, i, (j + 1))\n }\n }\n }\n }\n }\n def getDiagList(matrix: Array[Array[Int]], currInds: Tuple2[Int, Int], amount: Int): List[Int] = {\n amount match {\n case 0 => Nil\n case _ => matrix(currInds._1)(currInds._2) :: getDiagList(matrix, (currInds._1 - 1, currInds._2 + 1), amount - 1)\n }\n }\n def compareList(aList: List[Int], bList: List[Int]): Boolean = {\n aList match {\n case a :: aRest => {\n bList match {\n case b :: bRest => (a == b) && compareList(aRest, bRest)\n case Nil => true\n }\n }\n case Nil => true\n }\n }\n def main(args: Array[String]): Unit = {\n val nM = StdIn.readLine().split(\" \").map(x => x.toInt)\n val n = nM(0)\n val m = nM(1)\n\n val aMatrix = Array.range(0, n).map(x => StdIn.readLine().split(\" \").map(y => y.toInt))\n val bMatrix = Array.range(0, n).map(x => StdIn.readLine().split(\" \").map(y => y.toInt))\n\n val colStartInds = Array.range(0, n).map(x => (x, 0))\n val rowStartInds = Array.range(1, m).map(x => ((n - 1), x))\n\n val startInds = colStartInds ++ rowStartInds\n val aDiagLists = startInds.map(x => getDiagList(aMatrix, x, min(x._1 + 1, m - x._2)).sorted)\n val bDiagLists = startInds.map(x => getDiagList(bMatrix, x, min(x._1 + 1, m - x._2)).sorted)\n\n val res = Array.range(0, startInds.size).toList.foldLeft(true) { (acc, x) => acc && compareList(aDiagLists(x), bDiagLists(x)) }\n\n res match {\n case true => println(\"YES\")\n case false => println(\"NO\")\n }\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M = ni()\n val A = nm(N, M)\n val B = nm(N, M)\n\n def count(i: Int, mat: Array[Array[Int]]): mutable.Map[Int, Int] = {\n val cnt = mutable.Map[Int, Int]().withDefaultValue(0)\n var n = min(i, N - 1)\n var m = max(0, i - (N - 1))\n debug(s\"$n $m\")\n while(n >= 0 && m < M) {\n cnt(mat(n)(m)) = cnt(mat(n)(m)) + 1\n n -= 1\n m += 1\n }\n debug(cnt.mkString(\" \"))\n cnt\n }\n\n var ok = true\n REP(N + M - 1) { i =>\n ok &&= count(i, A) == count(i, B)\n }\n\n if (ok) out.println(\"YES\")\n else out.println(\"NO\")\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugNum(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}], "negative_code": [], "src_uid": "77e2ddc4684fccd1856c93c2fc6e1ce2"} {"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val hn = readLine().split(\" \").map(_.toInt).sorted\r\n\r\n val i = (1 until (n - 1)).foldLeft(0) {\r\n case (i, j) if math.abs(hn(j) - hn(j + 1)) < math.abs(hn(i) - hn(i + 1)) => j\r\n case (i, _) => i\r\n }\r\n\r\n // h1 h2 h3 ... hi hi+1 ... hn\r\n //\r\n // The first variant (incorrect):\r\n // hi+1 ... hn h1 h2 h3 ... hi\r\n // Example:\r\n // -> 1 3\r\n // <- 3 1\r\n //\r\n // The second variant (correct):\r\n // hi hi+2 ... hn h1 h2 ... hi+1\r\n // Example\r\n // -> 1 3\r\n // <- 1 3\r\n\r\n val ans = hn(i) +: (((i + 2) until n).map(hn) ++ (0 until i).map(hn)) :+ hn(i + 1)\r\n\r\n println(ans.mkString(\" \"))\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Solution extends App {\n\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val mountainsNumber = readInt()\n val heights = readInts().sorted\n\n var index = 1\n var min = heights(1) - heights(0)\n for (i <- index.until(mountainsNumber)) {\n val tempMin = heights(i) - heights(i - 1)\n if (tempMin < min) {\n min = tempMin\n index = i\n }\n }\n val skipIndex = if (min == heights(mountainsNumber - 1) -\n heights(mountainsNumber - 2)) mountainsNumber - 1 else index\n\n val heightsBeforeFirstPoint: ListBuffer[Int] = ListBuffer()\n for (i <- 0 until(skipIndex - 1)) {\n heightsBeforeFirstPoint.append(heights(i))\n }\n val heightsAfterFirstPoint: ListBuffer[Int] = ListBuffer()\n for (i <- (skipIndex + 1) until mountainsNumber) {\n heightsAfterFirstPoint.append(heights(i))\n }\n\n print(s\"${heights(skipIndex - 1)} \")\n heightsAfterFirstPoint.foreach(h => print(s\"$h \"))\n heightsBeforeFirstPoint.foreach(h => print(s\"$h \"))\n println(s\"${heights(skipIndex)} \")\n }\n\n}\n"}, {"source_code": "import scala.:+\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Solution extends App {\n\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val mountainsNumber = readInt()\n val heights = readInts().sorted\n\n var index = 1\n var min = heights(1) - heights(0)\n for (i <- index.until(mountainsNumber)) {\n val tempMin = heights(i) - heights(i - 1)\n if (tempMin < min) {\n min = tempMin\n index = i\n }\n }\n val skipIndex = if (min == heights(mountainsNumber - 1) -\n heights(mountainsNumber - 2)) mountainsNumber - 1 else index\n\n val heightsBeforeFirstPoint = heights.slice(0, skipIndex - 1).toList\n val heightsAfterFirstPoint = heights.slice(skipIndex + 1, mountainsNumber).toList\n\n val answer = heights(skipIndex - 1) +: (heightsAfterFirstPoint ++ heightsBeforeFirstPoint) :+ heights(skipIndex)\n\n println(answer.mkString(\" \"))\n }\n\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Solution extends App {\n\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val mountainsNumber = readInt()\n val heights = readInts().sorted\n var index = 1\n var min = heights(1) - heights(0)\n for (i <- index.until(mountainsNumber)) {\n val tempMin = heights(i) - heights(i - 1)\n if (tempMin < min) {\n min = tempMin\n index = i\n }\n }\n val skipIndex = if (min == heights(mountainsNumber - 1) -\n heights(mountainsNumber - 2)) mountainsNumber - 1 else index\n var remainingHeights: ListBuffer[Int] = ListBuffer()\n for (i <- 0 until(mountainsNumber)) {\n if (i != skipIndex - 1 && i != skipIndex) {\n val value = heights(i)\n remainingHeights.append(value)\n }\n }\n\n if (remainingHeights.size == 2 && (skipIndex == 2)) {\n remainingHeights = remainingHeights.reverse\n }\n\n print(s\"${heights(skipIndex - 1)} \")\n remainingHeights.foreach(h => print(s\"$h \"))\n println(s\"${heights(skipIndex)} \")\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Solution extends App {\n\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val mountainsNumber = readInt()\n val heights = readInts().sorted\n var index = 1\n var min = heights(1) - heights(0)\n for (i <- index.until(mountainsNumber)) {\n val tempMin = heights(i) - heights(i - 1)\n if (tempMin < min) {\n min = tempMin\n index = i\n }\n }\n val skipIndex = if (min == heights(mountainsNumber - 1) -\n heights(mountainsNumber - 2)) mountainsNumber - 1 else index\n print(s\"${heights(skipIndex - 1)} \")\n for (i <- 0 until(mountainsNumber)) {\n if (i != skipIndex - 1 && i != skipIndex) print(s\"${heights(i)} \")\n }\n println(s\"${heights(skipIndex)} \")\n }\n\n}\n"}], "src_uid": "3342e71884677534b7a126f89d441585"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, d) = readLineInt\n val prices@Array(a, b) = readLineInt\n val ar = (1L to n).map(i => i -> readLineInt.zip(prices).map(t => t._1 * t._2).sum)\n val sort = ar.sortBy(_._2)\n val tr = sort.scanLeft((0L, 0L)){ (prev, t) => (t._1, prev._2 + t._2) }\n val taken = tr.takeWhile(_._2 <= d).drop(1)\n println(taken.size)\n println(taken.map(_._1).mkString(\" \")) \n }\n \n def readLineInt = readLine().split(\" \").map(_.toLong)\n}", "positive_code": [{"source_code": "import scala.io.Source\nimport scala.math._\nimport scala.collection.mutable.ListBuffer\n\nobject A extends App {\n def go = main(Array())\n val in = Source.stdin.getLines.toList\n\n val Array(n, d) = in.head.split(\" \").map(_.toLong)\n val Array(a, b) = in.tail.head.split(\" \").map(_.toLong)\n\n val req = in.tail.tail.map (s => {\n val Array (low, hi) = s.split(\" \").map(_.toLong)\n\n low * a + hi * b\n }).zipWithIndex.sortBy (_._1)\n\n def solve: List[Int] = {\n val q = req.foldLeft ((List[Int](), 0l)) { case ((res, sum), (reqs, index)) => if (sum + reqs > d) return res else ((index+1)::res, sum+reqs)}\n\n q._1\n }\n\n val solution = solve\n\n println (solution.size)\n println (solution.mkString(\" \"))\n}\n\n"}], "negative_code": [{"source_code": "import scala.io.Source\nimport scala.math._\nimport scala.collection.mutable.ListBuffer\n\nobject A extends App {\n def go = main(Array())\n val in = Source.stdin.getLines.toList\n\n val Array(n, d) = in.head.split(\" \").map(_.toInt)\n val Array(a, b) = in.tail.head.split(\" \").map(_.toInt)\n\n val req = in.tail.tail.map (s => {\n val Array (low, hi) = s.split(\" \").map(_.toInt)\n\n low * a + hi * b\n }).zipWithIndex.sortBy (_._1)\n\n def solve: List[Int] = {\n val q = req.foldLeft ((List[Int](), 0)) { case ((res, sum), (reqs, index)) => if (sum + reqs > d) return res else ((index+1)::res, sum+reqs)}\n\n q._1\n }\n\n val solution = solve\n\n println (solution.size)\n println (solution.mkString(\" \"))\n}\n\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, d) = readLineInt\n val prices@Array(a, b) = readLineInt\n val ar = (1 to n).map(i => i -> readLineInt.zip(prices).map(t => t._1 * t._2).sum)\n val sort = ar.sortBy(_._2)\n val tr = sort.scanLeft((0, 0)){ (prev, t) => (t._1, prev._2 + t._2) }\n val taken = tr.takeWhile(_._2 <= d)\n println(taken.size)\n println(taken.map(_._1).drop(1).mkString(\" \")) \n }\n \n def readLineInt = readLine().split(\" \").map(_.toInt)\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, d) = readLineInt\n val prices@Array(a, b) = readLineInt\n val ar = (1 to n).map(i => i -> readLineInt.zip(prices).map(t => t._1 * t._2).sum)\n val sort = ar.sortBy(_._2)\n val tr = sort.scanLeft((0, 0)){ (prev, t) => (t._1, prev._2 + t._2) }\n val taken = tr.takeWhile(_._2 <= d).drop(1)\n println(taken.size)\n println(taken.map(_._1).mkString(\" \")) \n }\n \n def readLineInt = readLine().split(\" \").map(_.toInt)\n}"}], "src_uid": "4d7de18e76600777ff023e1b61366ee4"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map(_ => in.next().split(\" \")).toList\n println(\n (data.filter(_.last == \"rat\") ::: data.filter(j => j.last == \"woman\" || j.last == \"child\")\n ::: data.filter(j => j.last == \"man\") ::: data.filter(j => j.last == \"captain\")).map(_.head).mkString(\"\\n\"))\n}", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\n\nobject P063A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n // rats < women == children < men < captain\n // rats 0\n // women 1\n // children 1\n // men 2\n // captain 3\n\n val priority = Map(\"rat\" -> 0,\n \"woman\" -> 1,\n \"child\" -> 1,\n \"man\" -> 2,\n \"captain\" -> 3)\n\n val N = sc.nextInt\n sc.nextLine\n val crewList: List[(String, Int)] = List.fill(N)(sc.nextLine).map { \n case s: String => {\n val List(name, status) = s.split(\" \").toList\n (name, priority(status))\n }\n }.sortBy(_._2)\n\n crewList.foreach { tpl =>\n out.println(tpl._1)\n }\n out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = (1 to n).map(_ => readLine().split(\" \"))\n \n val bs = scala.collection.mutable.Buffer[Array[String]]()\n \n bs ++= a.filter(_.apply(1) == \"rat\")\n bs ++= a.filter(a0 => a0(1) == \"woman\" || a0(1) == \"child\")\n bs ++= a.filter(_.apply(1) == \"man\")\n bs ++= a.filter(_.apply(1) == \"captain\")\n \n bs.foreach(s => println(s.toSeq.apply(0)))\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map(_ => in.next().split(\" \"))\n println(data.filter(_.last == \"rat\").map(_.head).mkString(\"\\n\"))\n println(data.filter(j => j.last == \"woman\" || j.last == \"child\").map(_.head).mkString(\"\\n\"))\n println(data.filter(j => j.last == \"man\").map(_.head).mkString(\"\\n\"))\n println(data.filter(j => j.last == \"captain\").map(_.head).mkString(\"\\n\"))\n\n}"}], "src_uid": "753113fa5130a67423f2e205c97f8017"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve1(): Unit = {\n val N = ni()\n val A = na(N)\n val B = Array.ofDim[Int](N)\n val used = Array.ofDim[Boolean](N + 1)\n var p = 1\n var mx = 0\n REP(N) { i =>\n if (A(i) > mx) {\n mx = A(i)\n B(i) = A(i)\n used(A(i)) = true\n } else {\n while(p <= mx && used(p)) p += 1\n if (p > mx) {\n out.println(-1)\n return\n }\n B(i) = p\n used(p) = true\n }\n }\n out.println(B.mkString(\" \"))\n }\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n solve1()\n }\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\nimport scala.collection.mutable.ArrayBuffer\nobject Main extends App{\n // Your code here!\n val t = readInt()\n for (i <- 1 to t) {\n val n = readInt()\n val arr = readLine().split(\" \").map(_.toInt)\n var curr = 1\n val vis = new Array[Boolean](n+1)\n val res = ArrayBuffer[Int]()\n var flag = false\n for (j <- 0 until arr.length) {\n vis(arr(j)) = true\n if (j > 0 && arr(j) == arr(j-1)) {\n while(vis(curr)) curr += 1\n if (curr >= arr(j)) {\n flag = true\n } else {\n res += curr\n vis(curr) = true\n curr += 1\n }\n } else {\n res += arr(j)\n }\n }\n if (flag) {\n print(-1)\n } else {\n for (k <- 0 until n) print(s\"${res(k)} \")\n }\n println()\n }\n}\n"}], "negative_code": [], "src_uid": "81912dccb339d675e09df40919f9f6fe"} {"source_code": "object Main\n{\n\tdef min (a : Int, b : Int) : Int = \n\t\tif (a < b) return a\n\t\telse return b\n\tdef main (args : Array[String]) = \n\t{\n\t\tval n = readLine.toInt\n\t\tval arr = readLine.split(' ').map(_.toInt)\n\n\t\tvar a = arr.sorted\n\t\tvar i = n-1\n\t\tvar sum = 0\n\t\tfor (i <- 0 until n)\n\t\t\tsum += a(i)\n\t\ti = n-1\n\t\tvar rez = sum\n\t\tvar najmal = a(0)\n\n\t\twhile (i > 0)\n\t\t{\n\t\t\tfor (j <- 1 to a(i))\n\t\t\t\tif (a(i) % j == 0)\n\t\t\t\t{\n\t\t\t\t\tvar new_rez = min(rez, sum - a(i) - a(0) + a(i) / j + a(0)*j)\n\t\t\t\t\trez = new_rez\n\t\t\t\t}\n\t\t\ti -= 1\n\t\t}\n\n\t\tprintln(rez)\n\t}\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer \n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val B = Array.ofDim[Boolean](101)\n REP(N) { i =>\n B(A(i)) |= true\n }\n// debug(B)\n\n val sum = A.sum\n var diff = 0\n val ms = A.min\n// debug(ms)\n REP_r(101) { a =>\n if (B(a) && ms < a) {\n val D = divisors(a)\n REP(D.length) { i =>\n val d = D(i)\n val gain = a / d - a + ms * d - ms\n// debug(s\"$a $d $gain\")\n diff = min(diff, gain)\n }\n }\n }\n\n val ans = sum + min(0, diff)\n out.println(ans)\n }\n\n /**\n * O(√x)\n */\n def divisors(x: Int): Array[Int] = {\n val pre = ArrayBuffer[Int]()\n val post = ArrayBuffer[Int]()\n REP(math.sqrt(x).toInt, 1) { d =>\n if (x % d == 0) {\n pre += d\n if (d * d != x) post += x / d\n }\n }\n\n val res = Array.ofDim[Int](pre.length + post.length)\n REP(pre.length)(i => res(i) = pre(i))\n val preLen = pre.length\n val postLen = post.length\n REP(postLen)(i => res(i + preLen) = post(postLen - 1 - i))\n res\n }\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}], "negative_code": [{"source_code": "object Main\n{\n\tdef min (a : Int, b : Int) : Int = \n\t\tif (a < b) return a\n\t\telse return b\n\tdef main (args : Array[String]) = \n\t{\n\t\tval n = readLine.toInt\n\t\tval arr = readLine.split(' ').map(_.toInt)\n\n\t\tvar a = arr.sorted\n\t\tvar i = n-1\n\t\tvar sum = 0\n\t\tfor (i <- 0 until n)\n\t\t\tsum += a(i)\n\t\ti = n-1\n\t\tvar rez = sum\n\t\tvar najmal = a(0)\n\n\t\twhile (i > 0)\n\t\t{\n\t\t\tfor (j <- 1 to a(i))\n\t\t\t\tif (a(i) % j == 0)\n\t\t\t\t{\n\t\t\t\t\tvar new_rez = min(rez, rez - a(i) - a(0) + a(i) / j + a(0)*j)\n\t\t\t\t\trez = new_rez\n\t\t\t\t}\n\t\t\ti -= 1\n\t\t}\n\n\t\tprintln(rez)\n\t}\n}"}], "src_uid": "d8349ff9b695612473b2ba00d08e505b"} {"source_code": "import scala.collection.mutable\r\nimport scala.io.StdIn\r\n\r\nobject Main extends App {\r\n val n = StdIn.readLine().toInt\r\n val a = StdIn.readLine().split(\" \").map(_.toLong)\r\n val q = new mutable.PriorityQueue[Long].reverse\r\n val (result, _) = a.foldLeft((0l, 0l)) { (state, next) =>\r\n val (curResult, curSum) = state;\r\n if (next + curSum >= 0) {\r\n q.enqueue(next)\r\n (curResult + 1, next + curSum)\r\n } else if (q.nonEmpty && q.head < next) {\r\n val old = q.dequeue()\r\n q.enqueue(next)\r\n (curResult, curSum - old + next)\r\n } else {\r\n (curResult, curSum)\r\n }\r\n }\r\n\r\n println(result)\r\n}\r\n", "positive_code": [{"source_code": "import scala.collection.mutable\r\nimport scala.io.StdIn\r\n\r\nobject Main extends App {\r\n val n = StdIn.readLine().toInt\r\n val a = StdIn.readLine().split(\" \").map(_.toLong)\r\n \r\n def slowSolution(n: Int, a: Array[Long]): Long = {\r\n val init = (0 to n).map {i => if (i == 0) 0l else -1l }\r\n val results = a.foldLeft(init) { (v, next) =>\r\n (0 to n).map { i =>\r\n if (i == 0)\r\n 0\r\n else if (v(i - 1) == -1)\r\n -1\r\n else\r\n Math.max(v(i), v(i - 1) + next)\r\n }\r\n }\r\n (0 to n).filter(results(_) != -1).max\r\n }\r\n \r\n def fastSolution(n: Int, a: Array[Long]): Long = {\r\n val q = new mutable.PriorityQueue[Long].reverse\r\n val (result, _) = a.foldLeft((0l, 0l)) { (state, next) =>\r\n val (curResult, curSum) = state;\r\n if (next + curSum >= 0) {\r\n q.enqueue(next)\r\n (curResult + 1, next + curSum)\r\n } else if (q.nonEmpty && q.head < next) {\r\n val old = q.dequeue()\r\n q.enqueue(next)\r\n (curResult, curSum - old + next)\r\n } else {\r\n (curResult, curSum)\r\n }\r\n }\r\n result\r\n }\r\n\r\n println(fastSolution(n, a))\r\n}\r\n"}], "negative_code": [], "src_uid": "b4a4448af5b61fe5a8467a8d0e12fba8"} {"source_code": "import scala.io.StdIn._\nobject Main{\n def main(args: Array[String]): Unit ={\n val N = readInt()\n for(_ <- 0 until N){\n val line = readLine().split(\" \").map(_.toInt)\n val a = line(0)\n val b = line(1)\n def valid(a: Int) = a % 3 == 0 && a >= 0\n println(if(valid(2*b - a) && valid(2*a - b)) \"YES\" else \"NO\")\n }\n }\n}", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n var a, b = ni()\n val ok =\n a == 0 && b == 0 || {\n // a <= b にする\n if (a > b) {\n val t = a\n a = b\n b = t\n }\n\n if (a * 2 < b)\n false\n else {\n val ccc = 2 * a - b\n debug(s\"ccc:$ccc\")\n ccc % 3 == 0 && {\n val c = ccc / 3\n debug(s\"c:$c\")\n (a - 2 * c) * 2 == b - c\n }\n }\n }\n\n if (ok) out.println(\"YES\")\n else out.println(\"NO\")\n }\n }\n}"}], "negative_code": [], "src_uid": "0a720a0b06314fde783866b47f35af81"} {"source_code": "import scala.io.StdIn._\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n val t: Int = readInt()\r\n for (_ <- 1 to t){\r\n val n: Int = readInt()\r\n val a: Array[Int] = readLine().split(\" \").map(_.toInt)\r\n val b: Array[Int] = Array.fill(n)(0)\r\n val parity_arr: Array[Int] = Array.fill(n)(-1)\r\n for (j <- 0 until n){\r\n val curr_color: Int = a(j)\r\n val last_parity: Int = parity_arr(a(j)-1)\r\n if (last_parity == -1 || (last_parity == 0 && j%2 == 1) || (last_parity == 1 && j%2 == 0)) {\r\n b(a(j)-1) += 1\r\n parity_arr(a(j)-1) = j%2\r\n }\r\n }\r\n println(b.mkString(\" \"))\r\n }\r\n }\r\n}", "positive_code": [{"source_code": "\r\n\r\nobject prob2 {\r\n def main(args: Array[String]) = {\r\n new Resolver3(Console.in, Console.out).run()\r\n }\r\n}\r\n\r\nclass Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {\r\n\r\n import java.util.StringTokenizer\r\n import scala.collection.mutable\r\n import scala.collection.mutable._\r\n import scala.math.{abs,pow,min,max}\r\n import scala.collection.mutable.ListBuffer\r\n\r\n def run() {\r\n var tokenizer = new StringTokenizer(input.readLine())\r\n val q = tokenizer.nextToken().toInt\r\n for (sss <- 0 until q) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val n = tokenizer.nextToken().toInt\r\n val A = new Array[Int](n)\r\n val B = new Array[Int](n)\r\n for (i <- 0 until n) {\r\n A(i) = 0\r\n B(i) = -1\r\n }\r\n tokenizer = new StringTokenizer(input.readLine())\r\n var pr = 0\r\n var now = 0\r\n var count = 0\r\n for (i <- 1 to n) {\r\n pr = now\r\n now = tokenizer.nextToken().toInt\r\n if (pr == now) {\r\n B(pr-1) = i\r\n A(pr-1) += 1\r\n }\r\n else if (B(now-1) == -1) {\r\n B(now-1) = i\r\n A(now-1) += 1\r\n }\r\n else if ((i - B(now-1) ) % 2 == 1) {\r\n B(now-1) = i\r\n A(now-1) += 1\r\n }\r\n else {\r\n B(now-1) = i\r\n }\r\n }\r\n println(A.mkString(\" \"))\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "c63640fd70e0268f03cb4eec18540f3a"} {"source_code": "import scala.annotation.tailrec\n\nobject F670 {\n var t = 0L\n def findLength(finalLength: Int) = {\n var left = 0\n var right = finalLength\n \n // left <= finalLength, right > finalLength\n while (right - left > 1) {\n val mid = (left + right) / 2\n\n val len = mid + mid.toString.length\n\n if (len <= finalLength) left = mid else right = mid\n }\n\n left\n }\n def minusMap(left: Map[Char, Int], right: Map[Char, Int]): Map[Char, Int] = {\n left\n .flatMap {\n case (key, value) if (right.contains(key) && value == right(key)) => None\n case (key, value) if (right.contains(key)) => Some(key -> (value - right(key)))\n case (key, value) => Some(key -> value)\n }\n .toMap\n }\n\n def digitMapToString(digitsMap: Map[Char, Int]) = {\n val ret = ('0' to '9').map { case c =>\n c.toString * digitsMap.getOrElse(c, 0)\n }.mkString(\"\")\n\n ret\n }\n\n def getPartition(digitsMap: Map[Char, Int], subString: String) = {\n val nonZero = digitsMap - '0'\n\n nonZero.size match {\n case 0 => Seq[String](subString + digitMapToString(digitsMap))\n case _ =>\n val (head, count) = nonZero.min\n val trimmedDigitsMap = if (count == 1)\n digitsMap - head\n else\n digitsMap.updated(head, count - 1)\n trimmedDigitsMap.map { case (key, _) =>\n val (before, equalOrAfter) = trimmedDigitsMap.partition { case (iKey, _) => iKey < key }\n\n head + digitMapToString(before) + subString + digitMapToString(equalOrAfter)\n } ++ Seq(\n head + digitMapToString(trimmedDigitsMap) + subString \n )\n }\n }\n \n def main(args: Array[String]) {\n t -= System.nanoTime()\n val unOrderedString = readLine\n val subString = readLine\n\n val length = findLength(unOrderedString.length)\n\n def stringToMap(str: String) = str.toString.groupBy{c => c}.map { case (key, value) => (key, value.length)}\n\n val lengthMap = stringToMap(length.toString)\n val fullMap = stringToMap(unOrderedString)\n val subStringMap = stringToMap(subString)\n val digitsMap = minusMap(minusMap(fullMap, lengthMap), subStringMap)\n\n val candidates = Seq(\n subString + digitMapToString(digitsMap),\n digitMapToString(digitsMap) + subString\n ) ++ getPartition(digitsMap, subString)\n\n val result = candidates.sorted.filter{ case str => str(0) != '0' }.headOption match {\n case Some(str) => str\n case _ => candidates(0)\n }\n\n t += System.nanoTime()\n println(result)\n //println(t / 1000000)\n }\n}\n", "positive_code": [{"source_code": "object F670 {\n def findLength(finalLength: Int, length: Int): Int = {\n if (length + length.toString.length == finalLength) length\n else findLength(finalLength, length - 1)\n }\n\n def minusMap(left: Map[Char, Int], right: Map[Char, Int]): Map[Char, Int] = {\n left.flatMap {\n case (key, value) if (right.contains(key) && value == right(key)) => None\n case (key, value) if (right.contains(key)) => Some(key -> (value - right(key)))\n case (key, value) => Some(key -> value)\n }\n .toMap\n }\n\n def digitMapToString(digitsMap: Map[Char, Int]) = ('0' to '9').map { case c => c.toString * digitsMap.getOrElse(c, 0) }.mkString(\"\")\n\n def getPartition(digitsMap: Map[Char, Int], subString: String) = {\n val nonZero = digitsMap - '0'\n\n nonZero.size match {\n case 0 => Seq[String](subString + digitMapToString(digitsMap))\n case _ =>\n val (head, count) = nonZero.min\n val trimmedDigitsMap = if (count == 1) digitsMap - head else digitsMap.updated(head, count - 1)\n trimmedDigitsMap.map { case (key, _) =>\n val (before, equalOrAfter) = trimmedDigitsMap.partition { case (iKey, _) => iKey < key }\n head + digitMapToString(before) + subString + digitMapToString(equalOrAfter)\n } ++ Seq(\n head + digitMapToString(trimmedDigitsMap) + subString \n )\n }\n }\n \n def main(args: Array[String]) {\n val unOrderedString = readLine\n val subString = readLine\n\n val length = findLength(unOrderedString.length, unOrderedString.length)\n\n def stringToMap(str: String) = str.toString.groupBy{c => c}.map { case (key, value) => (key, value.length)}\n\n val lengthMap = stringToMap(length.toString)\n val fullMap = stringToMap(unOrderedString)\n val subStringMap = stringToMap(subString)\n val digitsMap = minusMap(minusMap(fullMap, lengthMap), subStringMap)\n\n val candidates = Seq(\n subString + digitMapToString(digitsMap),\n digitMapToString(digitsMap) + subString\n ) ++ getPartition(digitsMap, subString)\n\n val result = candidates.sorted.filter{ case str => str(0) != '0' }.headOption match {\n case Some(str) => str\n case _ => candidates(0)\n }\n\n println(result)\n }\n}\n"}], "negative_code": [{"source_code": "import scala.annotation.tailrec\n\nobject F670 {\n def findLength(finalLength: Int) = {\n var left = 0\n var right = finalLength\n \n // left <= finalLength, right > finalLength\n while (right - left > 1) {\n val mid = (left + right) / 2\n\n val len = mid + mid.toString.length\n\n if (len <= finalLength) {\n left = mid\n } else {\n right = mid\n }\n }\n\n left\n }\n\n def findHead(\n digitsMap: Map[Char, Int],\n head: Char,\n result: String\n ): (String, Map[Char, Int]) = {\n if (digitsMap.size == 0)\n (result, digitsMap)\n else {\n val (smallestKey, smallestValue) = digitsMap.min\n if (smallestKey > head) {\n (result, digitsMap)\n } else {\n findString(digitsMap, result, '1', head)\n }\n }\n }\n\n def consumeDigit(digitsMap: Map[Char, Int], start: Char) = {\n if (digitsMap(start) == 1)\n digitsMap - start\n else\n digitsMap.updated(start, digitsMap(start) - 1)\n }\n\n @tailrec def findString(\n digitsMap: Map[Char, Int],\n result: String,\n start: Char,\n top: Char\n ): (String, Map[Char, Int]) = {\n //println(s\"findString with $result, $start, $top\")\n if (start > '9' || digitsMap.size == 0 || digitsMap.min._1 > top)\n (result, digitsMap)\n else if (result.length == 0) {\n if (digitsMap.contains(start)) {\n findString(\n consumeDigit(digitsMap, start),\n result + start.toString,\n '0',\n top)\n } else {\n findString(\n digitsMap,\n result,\n (start + 1).asInstanceOf[Char],\n top)\n }\n } else {\n if (digitsMap.contains(start)) {\n val newDigitsMap = digitsMap - start\n findString(newDigitsMap, result + List.fill(digitsMap(start))(start).mkString(\"\"), start, top)\n } else {\n findString(digitsMap, result, (start + 1).asInstanceOf[Char], top)\n }\n }\n }\n\n @tailrec def findTail(digitsMap: Map[Char, Int], result: String): String = {\n if (digitsMap.size == 0) {\n return result\n } else {\n val (digit, count) = digitsMap.min\n findTail(digitsMap - digit, result + List.fill(count)(digit).mkString(\"\"))\n }\n }\n\n def minusMap(left: Map[Char, Int], right: Map[Char, Int]): Map[Char, Int] = {\n left\n .flatMap {\n case (key, value) if (right.contains(key) && value == right(key)) => None\n case (key, value) if (right.contains(key)) => Some(key -> (value - right(key)))\n case (key, value) => Some(key -> value)\n }\n .toMap\n }\n\n def shouldEqual(subString: String): Boolean = {\n if (subString.length == 0)\n true\n else if (subString.length == 1)\n true\n else {\n if (subString(0) == subString(1)) {\n shouldEqual(subString.tail)\n } else {\n subString(0) < subString(1)\n }\n }\n }\n\n var tt = 0\n\n def main(args: Array[String]) {\n val unOrderedString = readLine\n val subString = readLine\n\n val length = findLength(unOrderedString.length)\n\n def stringToMap(str: String) = str.toString.groupBy{c => c}.map { case (key, value) => (key, value.length)}\n\n val lengthMap = stringToMap(length.toString)\n val fullMap = stringToMap(unOrderedString)\n val subStringMap = stringToMap(subString)\n val digitsMap = minusMap(minusMap(fullMap, lengthMap), subStringMap)\n\n val top = if (shouldEqual(subString)) {\n subString(0)\n } else {\n (subString(0) - 1).asInstanceOf[Char]\n }\n val (prefix, updatedMap) = findHead(digitsMap, top, \"\")\n\n val (prefixPlus, tailDigitsMap) = if (updatedMap.size == 0) {\n (prefix + subString, updatedMap)\n }\n else if (prefix.length == 0 && subString(0) == '0') {\n val (head, size) = updatedMap.min\n (head + subString, consumeDigit(updatedMap, head))\n } else {\n (prefix + subString, updatedMap)\n }\n\n println(prefixPlus + findTail(tailDigitsMap, \"\"))\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\nobject F670 {\n def findLength(finalLength: Int) = {\n var left = 0\n var right = finalLength\n \n // left <= finalLength, right > finalLength\n while (right - left > 1) {\n val mid = (left + right) / 2\n\n val len = mid + mid.toString.length\n\n if (len <= finalLength) {\n left = mid\n } else {\n right = mid\n }\n }\n\n left\n }\n\n def findHead(\n digitsMap: Map[Char, Int],\n head: Char,\n top: Char,\n result: String\n ): (String, Map[Char, Int]) = {\n if (digitsMap.size == 0)\n (result, digitsMap)\n else {\n val (smallestKey, smallestValue) = digitsMap.min\n if (smallestKey > head) {\n (result, digitsMap)\n } else {\n findString(digitsMap, result, '1', if (head == '0') '9' else top)\n }\n }\n }\n\n def consumeDigit(digitsMap: Map[Char, Int], start: Char) = {\n if (digitsMap(start) == 1)\n digitsMap - start\n else\n digitsMap.updated(start, digitsMap(start) - 1)\n }\n\n @tailrec def findString(\n digitsMap: Map[Char, Int],\n result: String,\n start: Char,\n top: Char\n ): (String, Map[Char, Int]) = {\n // println(s\"findString with $result, $start, $top\")\n if (start > top || digitsMap.size == 0 || digitsMap.min._1 > top)\n (result, digitsMap)\n else if (result.length == 0) {\n if (digitsMap.contains(start)) {\n findString(\n consumeDigit(digitsMap, start),\n result + start.toString,\n '0',\n top)\n } else {\n findString(\n digitsMap,\n result,\n (start + 1).asInstanceOf[Char],\n top)\n }\n } else {\n if (digitsMap.contains(start)) {\n val newDigitsMap = digitsMap - start\n findString(newDigitsMap, result + List.fill(digitsMap(start))(start).mkString(\"\"), start, top)\n } else {\n findString(digitsMap, result, (start + 1).asInstanceOf[Char], top)\n }\n }\n }\n\n @tailrec def findTail(digitsMap: Map[Char, Int], result: String): String = {\n if (digitsMap.size == 0) {\n return result\n } else {\n val (digit, count) = digitsMap.min\n findTail(digitsMap - digit, result + List.fill(count)(digit).mkString(\"\"))\n }\n }\n\n def minusMap(left: Map[Char, Int], right: Map[Char, Int]): Map[Char, Int] = {\n left\n .flatMap {\n case (key, value) if (right.contains(key) && value == right(key)) => None\n case (key, value) if (right.contains(key)) => Some(key -> (value - right(key)))\n case (key, value) => Some(key -> value)\n }\n .toMap\n }\n\n def shouldEqual(subString: String): Boolean = {\n if (subString.length == 0)\n true\n else if (subString.length == 1)\n true\n else {\n if (subString(0) == subString(1)) {\n shouldEqual(subString.tail)\n } else {\n subString(0) < subString(1)\n }\n }\n }\n\n var tt = 0\n\n def main(args: Array[String]) {\n val unOrderedString = readLine\n val subString = readLine\n\n val length = findLength(unOrderedString.length)\n\n def stringToMap(str: String) = str.toString.groupBy{c => c}.map { case (key, value) => (key, value.length)}\n\n val lengthMap = stringToMap(length.toString)\n val fullMap = stringToMap(unOrderedString)\n val subStringMap = stringToMap(subString)\n val digitsMap = minusMap(minusMap(fullMap, lengthMap), subStringMap)\n\n val top = if (shouldEqual(subString)) {\n subString(0)\n } else {\n (subString(0) - 1).asInstanceOf[Char]\n }\n val (prefix, updatedMap) = findHead(digitsMap, subString(0), top, \"\")\n\n // println(top + \", \" + prefix)\n\n val (prefixPlus, tailDigitsMap) = if (updatedMap.size == 0) {\n (prefix + subString, updatedMap)\n }\n else if (prefix.length == 0 && subString(0) == '0') {\n val (head, size) = updatedMap.min\n (head + subString, consumeDigit(updatedMap, head))\n } else {\n (prefix + subString, updatedMap)\n }\n\n println(prefixPlus + findTail(tailDigitsMap, \"\"))\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\nobject F670 {\n def findLength(finalLength: Int) = {\n var left = 0\n var right = finalLength\n \n // left <= finalLength, right > finalLength\n while (right - left > 1) {\n val mid = (left + right) / 2\n\n val len = mid + mid.toString.length\n\n if (len <= finalLength) left = mid else right = mid\n }\n\n left\n }\n\n def findHead(\n digitsMap: Map[Char, Int],\n head: Char,\n top: Char,\n result: String\n ): (String, Map[Char, Int]) = {\n if (digitsMap.size == 0)\n (result, digitsMap)\n else {\n val (smallestKey, smallestValue) = digitsMap.min\n if (head == '0') {\n val lowest = (digitsMap - '0').min._1\n (lowest + List.fill(digitsMap.getOrElse('0', 0))('0').mkString(\"\"), consumeDigit(digitsMap, lowest) - '0')\n } else if (smallestKey >= head){\n (result, digitsMap)\n } else {\n findString(digitsMap, result, '1', top)\n }\n }\n }\n\n def consumeDigit(digitsMap: Map[Char, Int], start: Char) = {\n if (digitsMap(start) == 1)\n digitsMap - start\n else\n digitsMap.updated(start, digitsMap(start) - 1)\n }\n\n @tailrec def findString(\n digitsMap: Map[Char, Int],\n result: String,\n start: Char,\n top: Char\n ): (String, Map[Char, Int]) = {\n // println(s\"findString with $result, $start, $top\")\n if (start > top || digitsMap.size == 0 || digitsMap.min._1 > top)\n (result, digitsMap)\n else if (result.length == 0) {\n if (digitsMap.contains(start)) {\n findString(\n consumeDigit(digitsMap, start),\n result + start.toString,\n '0',\n top)\n } else {\n findString(\n digitsMap,\n result,\n (start + 1).asInstanceOf[Char],\n top)\n }\n } else {\n if (digitsMap.contains(start)) {\n val newDigitsMap = digitsMap - start\n findString(newDigitsMap, result + List.fill(digitsMap(start))(start).mkString(\"\"), start, top)\n } else {\n findString(digitsMap, result, (start + 1).asInstanceOf[Char], top)\n }\n }\n }\n\n @tailrec def findTail(digitsMap: Map[Char, Int], result: String): String = {\n if (digitsMap.size == 0) {\n return result\n } else {\n val (digit, count) = digitsMap.min\n findTail(digitsMap - digit, result + List.fill(count)(digit).mkString(\"\"))\n }\n }\n\n def minusMap(left: Map[Char, Int], right: Map[Char, Int]): Map[Char, Int] = {\n left\n .flatMap {\n case (key, value) if (right.contains(key) && value == right(key)) => None\n case (key, value) if (right.contains(key)) => Some(key -> (value - right(key)))\n case (key, value) => Some(key -> value)\n }\n .toMap\n }\n\n def shouldEqual(subString: String): Boolean = {\n if (subString.length == 0)\n true\n else if (subString.length == 1)\n true\n else {\n if (subString(0) == subString(1)) {\n shouldEqual(subString.tail)\n } else {\n subString(0) < subString(1)\n }\n }\n }\n\n var tt = 0\n\n def main(args: Array[String]) {\n val unOrderedString = readLine\n val subString = readLine\n\n val length = findLength(unOrderedString.length)\n\n def stringToMap(str: String) = str.toString.groupBy{c => c}.map { case (key, value) => (key, value.length)}\n\n val lengthMap = stringToMap(length.toString)\n val fullMap = stringToMap(unOrderedString)\n val subStringMap = stringToMap(subString)\n val digitsMap = minusMap(minusMap(fullMap, lengthMap), subStringMap)\n\n val top = if (shouldEqual(subString)) {\n subString(0)\n } else {\n (subString(0) - 1).asInstanceOf[Char]\n }\n val (prefix, updatedMap) = findHead(digitsMap, subString(0), top, \"\")\n\n // println(top + \", \" + prefix)\n\n val (prefixPlus, tailDigitsMap) = if (updatedMap.size == 0) {\n (prefix + subString, updatedMap)\n }\n else if (prefix.length == 0 && subString(0) == '0') {\n val (head, size) = updatedMap.min\n (head + subString, consumeDigit(updatedMap, head))\n } else {\n (prefix + subString, updatedMap)\n }\n\n println(prefixPlus + findTail(tailDigitsMap, \"\"))\n }\n}\n"}], "src_uid": "5c3cec98676675355bb870d818704be6"} {"source_code": "import scala.io.StdIn\r\n\r\nobject Main extends App {\r\n val t = StdIn.readInt()\r\n for(i <- 0 until t){\r\n val n = StdIn.readLine().split(\" \").map(_.toInt)\r\n for(i <- 0 until n(0)) {\r\n for(j <- 0 until n(1)){\r\n var ans = i&3 ^ j&3\r\n ans = (ans&1) ^ (ans>>1)\r\n print(ans + \" \")\r\n }\r\n println()\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.collection.mutable\r\n\r\nobject prob2 {\r\n def main(args: Array[String]) = {\r\n import scala.collection.mutable.ListBuffer\r\n new Resolver3(Console.in, Console.out).run()\r\n }\r\n}\r\n\r\nclass Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {\r\n import java.util.StringTokenizer\r\n def run() {\r\n def str1(m:Int): String = {\r\n var l = new StringBuilder\r\n l ++= \"1\"\r\n if ((m % 4) == 2) {\r\n if (m!=2) {\r\n for (i <- 1 to (m-2)/4 ) {\r\n l++= \" 0 0 1 1\"\r\n }\r\n }\r\n\r\n l++= \" 0\"\r\n }\r\n else {\r\n if (m != 4) {\r\n for (i <- 1 to (m - 4) / 4) {\r\n l ++= \" 0 0 1 1\"\r\n }\r\n }\r\n l ++= \" 0 0 1\"\r\n }\r\n l.toString\r\n }\r\n def str2(m:Int): String = {\r\n val l = new StringBuilder\r\n l++= \"0\"\r\n if ((m % 4) == 2) { if (m!=2) {\r\n for (i <- 1 to (m-2)/4 ) {\r\n l++= \" 1 1 0 0\"\r\n }\r\n }\r\n l++= \" 1\"\r\n }\r\n else {\r\n if (m!=4) {\r\n for (i <- 1 to (m - 4) / 4) {\r\n l ++= \" 1 1 0 0\"\r\n }\r\n }\r\n l ++= \" 1 1 0\"\r\n }\r\n l.toString\r\n }\r\n var tokenizer = new StringTokenizer(input.readLine())\r\n val q = tokenizer.nextToken().toInt\r\n for (i <- 1 to q){\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val n = tokenizer.nextToken().toInt\r\n val m = tokenizer.nextToken().toInt\r\n val ch = str1(m)\r\n val ne = str2(m)\r\n if ((n % 4) == 0) {\r\n for (j <-1 to (n)/4) {\r\n output.println(ch)\r\n output.println(ne)\r\n output.println(ne)\r\n output.println(ch)\r\n }\r\n }\r\n else {\r\n if (n!=2){\r\n for (j <-1 to (n-2)/4) {\r\n output.println(ch)\r\n output.println(ne)\r\n output.println(ne)\r\n output.println(ch)\r\n }\r\n }\r\n\r\n output.println(ch)\r\n output.println(ne)\r\n }\r\n }\r\n }\r\n\r\n}\r\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\r\n\r\nobject Main extends App {\r\n val t = StdIn.readInt()\r\n for(i <- 0 until t){\r\n val n = StdIn.readLine().split(\" \").map(_.toInt)\r\n for(i <- 0 until n(0)) {\r\n for(j <- 0 until n(1)){\r\n print(((i ^ j) ^ ((i ^ j) >> 1)) & 1 )\r\n }\r\n println()\r\n }\r\n }\r\n}\r\n"}], "src_uid": "b7d40e7fc4f277cc801b59a21a16dfc1"} {"source_code": "object B467 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m, k) = readInts(3)\n val input = Array.fill(m+1)(readBigs(1)).map{ x =>\n val s = x(0).toString(2)\n Array.fill[Char](n - s.length)('0') ++ s.toCharArray\n }\n val compare = input(m)\n\n var res = 0\n for(i <- 0 until m) {\n var diff = 0\n for (j <- 0 until n) {\n if(input(i)(j) != compare(j))\n diff += 1\n }\n if(diff <= k)\n res += 1\n }\n\n println(res)\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject FedorandNewGame extends App {\n val n :: m :: k :: Nil = readLine().split(\" \").map(_.toInt).toList\n val a = Array.ofDim[Int](m)\n for (i <- 0 until m) {\n a(i) = readInt()\n }\n val p = readInt()\n val result = a.foldLeft(0) { (acc, x) =>\n val g = p ^ x\n if (Integer.bitCount(g) <= k) acc + 1\n else acc\n }\n println(result)\n}\n"}, {"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 18.09.14.\n */\nobject B extends App {\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n val m = nextInt\n val k = nextInt\n val xs = Array.fill(m + 1)(\"\")\n for(i <- 0 until m + 1) {\n xs(i) = nextInt.toBinaryString.reverse\n }\n def countDiff(s: String, t: String): Int = {\n var diff = 0\n for(i <- 0 until math.min(s.length, t.length)) {\n if(s(i) != t(i)) {\n diff += 1\n }\n }\n if(s.length < t.length) {\n for(i <- s.length until t.length) {\n if(t(i) == '1') {\n diff += 1\n }\n }\n } else {\n for(i <- t.length until s.length) {\n if(s(i) == '1') {\n diff += 1\n }\n }\n }\n diff\n }\n val nFriends = (for(i <- 0 until xs.length - 1) yield countDiff(xs(i), xs(m)) <= k).count(_ == true)\n out.print(nFriends)\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _467B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val m = next.toInt\n val k = next.toInt\n val a = (0 to m).map(i => next.toInt)\n val ans = for {\n i <- 0 until m\n if (Integer.bitCount((a(i) ^ a(m))) <= k)\n } yield 1\n println(ans.sum)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m, k) = in.next().split(\" \").map(_.toInt)\n val data = Range(0, m).map(_ => in.next().toInt)\n val f = in.next().toInt\n\n println(data.map(_ ^ f).map(_.toBinaryString.count(_ == '1')).count(_ <= k))\n}"}, {"source_code": "import scala.io.StdIn\n\nobject A extends App {\n\n val Array(n, m, k) = StdIn.readLine().split(\" \").map(_.toInt)\n val arr = (1 to m).map( _ => StdIn.readInt())\n val a = StdIn.readInt()\n val res = arr.map { x =>\n if((x ^ a).toBinaryString.filter(_ == '1').length <= k) 1 else 0\n }.sum\n println(res)\n}\n"}, {"source_code": "import scala.io.StdIn\n\n/**\n * @author unit7\n */\nobject Main {\n def main(args: Array[String]) {\n val counters = StdIn\n .readLine()\n .split(\"\\\\s\")\n .map(_.toInt)\n \n val m = counters(1)\n \n val armies = new Array[Int](m + 1)\n \n val k = counters(2)\n for (i <- 0 to m) {\n armies(i) = StdIn.readInt()\n }\n \n val fedor = armies(m)\n var canFriendCount = 0\n \n for (i <- 0 until m) {\n val differ = (fedor ^ armies(i))\n .toBinaryString\n .count(_ == '1')\n \n if (differ <= k)\n canFriendCount += 1\n }\n \n println(canFriendCount)\n }\n}"}], "negative_code": [{"source_code": "object B467 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m, k) = readInts(3)\n val input = Array.fill(m+1)(readBigs(1)).map(_(0))\n var res = 0\n for(i <- 0 until m) {\n val bits = (input(i) & input(m)).bitCount\n if(bits >= n-k) {\n res += 1\n }\n }\n println(res)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject A extends App {\n\n val Array(n, m, k) = StdIn.readLine().split(\" \").map(_.toInt)\n val arr = (1 to m).map( _ => StdIn.readInt())\n val a = StdIn.readInt()\n val res = arr.map { x =>\n if(n - (x & a).toBinaryString.filter(_ == '1').length <= k) 1 else 0\n }.sum\n println(res)\n}\n"}], "src_uid": "5ebb0ee239d68ea33d9dac2d0bdd5f4e"} {"source_code": "object _1234D extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = {\n val s = io.read[String].toArray\n\n val table = ('a' to 'z').map(c => c -> new java.util.TreeSet[Int]).toMap\n s.zipWithIndex foreach {case (c, i) => table(c) add i}\n\n repeat(io.read[Int]) {\n io.read[Int] match {\n case 1 =>\n val pos = io.read[Int] - 1\n val c = io.read[String].head\n table(s(pos)) remove pos\n table(c) add pos\n s(pos) = c\n\n case _ =>\n val l = io.read[Int] - 1\n val r = io.read[Int] - 1\n val ans = table.values.count({ s => Option(s.ceiling(l)).exists(_ <= r)})\n io.writeLine(ans)\n }\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C590D(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C590D(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val s: Array[Char] = ns().toCharArray\n val segment = new SegmentTree(s.length, s)\n segment.build(1, 0, s.length - 1)\n val q = ni()\n REP(q) { _ =>\n ni() match {\n case 1 =>\n val pos = ni()\n val c = nc()\n segment.update(1, 0, s.length - 1, pos - 1, c)\n case 2 =>\n val l = ni()\n val r = ni()\n out.println(segment.get(1, 0, s.length - 1, l-1, r-1).distinctCount)\n }\n\n }\n }\n\n case class Node (distinctCount: Int, bits: Long)\n\n private class SegmentTree(n: Int, s: Array[Char]) {\n\n private val tree: Array[Node] = Array.ofDim[Node](4 * n)\n\n private def combine(x: Node, y: Node): Node = {\n val z = x.bits | y.bits\n Node(java.lang.Long.bitCount(z), z)\n }\n\n def build(v: Int, tl: Int, tr: Int): Unit = {\n if(tl == tr) {\n tree(v) = Node(1, 1 << (s(tl) - 'a'))\n } else {\n val tm = tl + (tr - tl) / 2\n build(v << 1, tl, tm)\n build(v << 1 | 1, tm + 1, tr)\n tree(v) = combine(tree(v << 1), tree(v << 1 | 1))\n }\n }\n\n def update(v: Int, tl: Int, tr: Int, pos: Int, value: Char): Unit = {\n if(tl == tr) {\n tree(v) = Node(1, 1 << (value - 'a'))\n } else {\n val tm = tl + (tr - tl) / 2\n if(pos <= tm) {\n update(v << 1, tl ,tm, pos, value)\n } else {\n update(v << 1 | 1, tm + 1, tr, pos, value)\n }\n tree(v) = combine(tree(v << 1), tree(v << 1 | 1))\n }\n }\n\n def get(v: Int, tl: Int, tr: Int, l: Int, r: Int): Node = {\n if(r < tl || l > tr || l > r) {\n Node(0, 0)\n }\n else if(l == tl && r == tr) tree(v)\n else {\n val tm = tl + (tr - tl) / 2\n combine(get(v << 1, tl, tm, l, Math.min(r, tm)), get(v << 1 | 1, tm+1, tr, Math.max(l, tm+1), r))\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "7a79c60749ee13c69284ba8fe34b63b3"} {"source_code": "import scala.io.StdIn.readLine\r\nobject Sum {\r\n\r\n def myFunc[T: Manifest](t: T): Manifest[T] = manifest[T]\r\n\r\n def solve_test() = {\r\n val a = readLine().split(' ').map(_.toInt).sorted\r\n if (a(0) + a(1) == a(2))\r\n println(\"YES\")\r\n else\r\n println(\"NO\")\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val test = scala.io.StdIn.readInt()\r\n for(i <- 0 until test) solve_test()\r\n }\r\n}", "positive_code": [{"source_code": "object HelloWorld {\r\n\r\n def main(args: Array[String]): Unit = {\r\n val tests = scala.io.StdIn.readInt()\r\n for (t <- 1 to tests) {\r\n val Array(a, b, c) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\r\n\r\n val works = a + b == c || a + c == b || b + c == a\r\n\r\n if (works) println(\"YES\") else println(\"NO\")\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "1b8293c51d025940eb859b0e625ab588"} {"source_code": "import scala.io._\nimport Array._\nimport collection.immutable.SortedMap\n\nobject lala {\n def main(args: Array[String]) {\n\n implicit val Ord = implicitly[Ordering[Int]]\n \n var totalApples = 0\n val numberOfTrees = readInt()\n var field: Map[Int, Int] = Map()\n var fieldPositive: SortedMap[Int, Int] = SortedMap()\n var fieldPositive1: SortedMap[Int, Int] = SortedMap()\n var fieldNegative: SortedMap[Int, Int] = SortedMap()(Ord.reverse)\n var fieldNegative1: SortedMap[Int, Int] = SortedMap()(Ord.reverse)\n \n for (a <- 0 until numberOfTrees) {\n var temp = new Array[Int](2)\n var line = readLine()\n temp = line.split(\" \") map (_.toInt)\n for (b <- 0 until 2) {\n field += (temp(0) -> temp(1))\n }\n }\n\n for (a <- field) {\n if (a._1 < 0) {\n fieldNegative += (a._1 -> a._2)\n } else {\n fieldPositive += (a._1 -> a._2)\n }\n }\n\n if (fieldPositive.size == fieldNegative.size) {\n totalApples += fieldPositive.foldLeft(0)(_ + _._2)\n totalApples += fieldNegative.foldLeft(0)(_ + _._2)\n } else if (fieldPositive.size > fieldNegative.size) {\n totalApples += fieldNegative.foldLeft(0)(_ + _._2)\n fieldPositive1 = fieldPositive.take(fieldNegative.size + 1)\n totalApples += fieldPositive1.foldLeft(0)(_ + _._2)\n } else if (fieldPositive.size < fieldNegative.size) {\n totalApples += fieldPositive.foldLeft(0)(_ + _._2)\n fieldNegative1 = fieldNegative.take(fieldPositive.size + 1)\n totalApples += fieldNegative1.foldLeft(0)(_ + _._2)\n }\n println(totalApples)\n }\n}\n", "positive_code": [{"source_code": "//package c558.a\n\nobject Solution extends App {\n import scala.io.StdIn\n val n = StdIn.readInt()\n val (leftTree, rightTree) = (1 to n).map(_ ⇒ {\n val s = StdIn.readLine().split(\" \")\n s(0).toInt → s(1).toLong\n }).partition(_._1 > 0)\n @scala.annotation.tailrec\n def eatApples(left: Seq[(Int, Long)], right: Seq[(Int, Long)], applesAcc: Long, direction: String): Long =\n if (direction == \"left\") {\n left match {\n case Nil ⇒ applesAcc\n case _ ⇒ eatApples(left.tail, right, applesAcc + left.head._2, \"right\")\n }\n } else {\n right match {\n case Nil ⇒ applesAcc\n case _ ⇒ eatApples(left, right.tail, applesAcc + right.head._2, \"left\")\n }\n }\n val sortedLeft = leftTree.sortBy(_._1)\n val sortedRight = rightTree.sortBy(_._1 * -1)\n val twoResults = Seq(\"left\", \"right\").map(eatApples(sortedLeft, sortedRight, 0, _))\n println(scala.math.max(twoResults.head, twoResults.tail.head))\n}\n"}, {"source_code": "import scala.io._\nimport Array._\nimport collection.immutable.SortedMap\n\nobject lala {\n def main(args: Array[String]) {\n\n var numberOfTrees: Int = 0\n var walk = 0\n var totalApples = 0\n\n val line = readInt()\n numberOfTrees = line.toInt\n\n implicit val Ord = implicitly[Ordering[Int]]\n\n var field: Map[Int, Int] = Map()\n var fieldPositive: SortedMap[Int, Int] = SortedMap()\n var fieldPositive1: SortedMap[Int, Int] = SortedMap()\n var fieldPositive2: SortedMap[Int, Int] = SortedMap()\n var fieldNegative: SortedMap[Int, Int] = SortedMap()(Ord.reverse)\n var fieldNegative1: SortedMap[Int, Int] = SortedMap()(Ord.reverse)\n var fieldNegative2: SortedMap[Int, Int] = SortedMap()(Ord.reverse)\n\n for (a <- 0 until numberOfTrees) {\n var temp = new Array[Int](2)\n var line = readLine()\n\n temp = line.split(\" \") map (_.toInt)\n\n for (b <- 0 until 2) {\n field += (temp(0) -> temp(1))\n }\n }\n\n for (a <- field) {\n if (a._1 < 0) {\n fieldNegative += (a._1 -> a._2)\n } else {\n fieldPositive += (a._1 -> a._2)\n }\n }\n\n if (fieldPositive.size == fieldNegative.size) {\n for (i <- fieldPositive) {\n totalApples += i._2\n }\n for (i <- fieldNegative) {\n totalApples += i._2\n }\n }\n\n if (fieldPositive.size > fieldNegative.size) {\n\n for (i <- fieldNegative) {\n totalApples += i._2\n }\n\n fieldPositive1 = fieldPositive.take(fieldNegative.size)\n\n for (i <- fieldPositive1) {\n totalApples += i._2\n }\n\n fieldPositive2 = fieldPositive.take(fieldNegative.size + 1)\n\n totalApples += fieldPositive2.last._2\n\n }\n\n if (fieldPositive.size < fieldNegative.size) {\n\n for (i <- fieldPositive) {\n totalApples += i._2\n }\n\n fieldNegative1 = fieldNegative.take(fieldPositive.size)\n\n for (i <- fieldNegative1) {\n totalApples += i._2\n }\n\n fieldNegative2 = fieldNegative.take(fieldPositive.size + 1)\n\n totalApples += fieldNegative2.last._2\n\n }\n\n println(totalApples)\n\n }\n}"}, {"source_code": "import scala.io._\nimport Array._\nimport collection.immutable.SortedMap\n\nobject lala {\n def main(args: Array[String]) {\n\n var numberOfTrees: Int = 0\n var totalApples = 0\n val line = readInt()\n numberOfTrees = line.toInt\n\n implicit val Ord = implicitly[Ordering[Int]]\n\n var field: Map[Int, Int] = Map()\n var fieldPositive: SortedMap[Int, Int] = SortedMap()\n var fieldPositive1: SortedMap[Int, Int] = SortedMap()\n var fieldPositive2: SortedMap[Int, Int] = SortedMap()\n var fieldNegative: SortedMap[Int, Int] = SortedMap()(Ord.reverse)\n var fieldNegative1: SortedMap[Int, Int] = SortedMap()(Ord.reverse)\n var fieldNegative2: SortedMap[Int, Int] = SortedMap()(Ord.reverse)\n\n for (a <- 0 until numberOfTrees) {\n var temp = new Array[Int](2)\n var line = readLine()\n temp = line.split(\" \") map (_.toInt)\n for (b <- 0 until 2) {\n field += (temp(0) -> temp(1))\n }\n }\n\n for (a <- field) {\n if (a._1 < 0) {\n fieldNegative += (a._1 -> a._2)\n } else {\n fieldPositive += (a._1 -> a._2)\n }\n }\n\n if (fieldPositive.size == fieldNegative.size) {\n totalApples += fieldPositive.foldLeft(0)(_ + _._2)\n totalApples += fieldNegative.foldLeft(0)(_ + _._2)\n }\n\n if (fieldPositive.size > fieldNegative.size) {\n totalApples += fieldNegative.foldLeft(0)(_ + _._2)\n fieldPositive1 = fieldPositive.take(fieldNegative.size)\n totalApples += fieldPositive1.foldLeft(0)(_ + _._2)\n fieldPositive2 = fieldPositive.take(fieldNegative.size + 1)\n totalApples += fieldPositive2.last._2\n }\n\n if (fieldPositive.size < fieldNegative.size) {\n totalApples += fieldPositive.foldLeft(0)(_ + _._2)\n fieldNegative1 = fieldNegative.take(fieldPositive.size)\n totalApples += fieldNegative1.foldLeft(0)(_ + _._2)\n fieldNegative2 = fieldNegative.take(fieldPositive.size + 1)\n totalApples += fieldNegative2.last._2\n }\n println(totalApples)\n }\n}"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.collection.mutable.PriorityQueue\nimport scala.annotation.tailrec\n\n// PriorityQueue[Long]()(scala.math.Ordering.Long.reverse)\n\ncase class Tree(x : Int, a : Int)\n\nobject Main {\n object EnRich {\n implicit class AString(val self : String) extends AnyVal {\n def splitToIntArray = self.split(\" \").map(_.toInt)\n }\n }\n import EnRich._\n def main(args : Array[String]) : Unit = {\n val n = readLine.toInt\n val trees = (1 to n).map(_ => {\n val (x,a) = {\n val xa = readLine.splitToIntArray\n (xa(0),xa(1))\n }\n Tree(x,a)\n }).toVector\n val left = trees.filter({case Tree(x,a) => x < 0}).\n sortBy({case Tree(x,a) => -x})\n val right = trees.filter({case Tree(x,a) => x > 0}).\n sortBy({case Tree(x,a) => x})\n val m = left.length min right.length\n val go_l = left.take(m+1) ++ right.take(m)\n val go_r = left.take(m) ++ right.take(m+1)\n\n val ans1 = go_l.map({case Tree(x,a) => a}).sum\n val ans2 = go_r.map({case Tree(x,a) => a}).sum\n\n println(ans1 max ans2)\n }\n}\n"}, {"source_code": "object A558 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = Array.fill(n)(readInts(2)).map(arr => (arr(0), arr(1))).sortBy(_._1)\n val neg = in.filter(_._1 < 0).map(_._2)\n val pos = in.filter(_._1 > 0).map(_._2)\n\n if(neg.length > pos.length) {\n println(pos.sum + neg.takeRight(pos.length+1).sum)\n } else {\n println(neg.sum + pos.take(neg.length+1).sum)\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable._\n\nobject A extends App {\n val apples = new HashMap[Int, Int]()\n val n = readInt\n for(i <- 1 to n) {\n val str = readLine.split(\" \").map(_.toInt)\n apples.put(str(0), str(1))\n }\n val pair = apples.groupBy({case (k, v) => k > 0})\n .map({case (k, v) => (k, v.size)})\n val left = pair.get(false).getOrElse(0)\n val right = pair.get(true).getOrElse(0)\n\n var takeLeft, takeRight = 0\n if(left <= right) {\n takeLeft = left\n takeRight = left + 1\n }\n else {\n takeLeft = right + 1\n takeRight = right\n }\n\n val leftRes = apples.filter({case (k, v) => k < 0}).toList.sortWith((i, j) => i._1 > j._1).take(takeLeft).foldLeft(0)((acc, elem) => acc + elem._2)\n val rightRes = apples.filter({case (k, v) => k > 0}).toList.sortWith((i, j) => i._1 < j._1).take(takeRight).foldLeft(0)( (acc, elem) => acc + elem._2)\n\n println(leftRes + rightRes)\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util.control.Breaks._, math.Ordering.Implicits._\nobject _558A extends CodeForcesApp[Int]({scanner => import scanner._\n val n = nextInt\n val data = List.fill(n)((nextInt, nextInt))\n\n def solve(left: List[(Int, Int)], right: List[(Int, Int)]): Int = (left, right) match {\n case (Nil, Nil) => 0\n case (Nil, (_, b) :: _) => b\n case ((_, a) :: _, Nil) => a\n case ((_, a) :: ls, (_, b) :: rs) => a + b + solve(ls, rs)\n }\n\n val (l, r) = data.sortBy(_._1.abs).partition(_._1 < 0)\n solve(l, r)\n})\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[B](x: Boolean)(f: => B): Option[B] = if (x) Some(f) else None\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n"}, {"source_code": "import scala.collection.immutable.SortedMap\n\nobject LalaProblem {\n\n def main(args: Array[String]): Unit = {\n\n \n implicit val Ord = implicitly[Ordering[Int]]\n\n var listPos: SortedMap[Int, Int] = SortedMap()\n var listNeg: SortedMap[Int, Int] = SortedMap()(Ord.reverse)\n val n: Int = readInt()\n var count: Int = 0\n\n for (x <- 0 until n) {\n var line = readLine()\n var temp: Array[String] = line.split(\" \")\n if (temp(0).toInt < 0) {\n listNeg = listNeg ++ converToMap(temp(0), temp(1))\n } else {\n listPos = listPos ++ converToMap(temp(0), temp(1))\n }\n }\n \n\n if (listNeg.size == listPos.size) {\n listNeg.keys.foreach { x => count += listNeg(x) }\n listPos.keys.foreach { x => count += listPos(x) }\n } else {\n if (listNeg.size < listPos.size) {\n listNeg.keys.foreach { x => count += listNeg(x) }\n var newMap : Map[Int, Int] = listPos.take(listNeg.size + 1)\n newMap.keys.foreach { x => count += newMap(x) }\n } else {\n listPos.keys.foreach { x => count += listPos(x) }\n var newMap : Map[Int, Int] = listNeg.take(listPos.size + 1)\n newMap.keys.foreach { x => count += newMap(x) }\n }\n }\n println(count)\n }\n\n def converToMap(x: String, y: String): Map[Int, Int] = {\n\n val xc: Int = x.toInt\n val yc: Int = y.toInt\n Map(xc -> yc)\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io._\nimport Array._\nimport collection.immutable.SortedMap\nimport util.control.Breaks._\n\nobject lala {\n def main(args: Array[String]) {\n\n var numberOfTrees: Int = 0\n var walk = 0\n var totalApples = 0\n\n val line = readInt()\n numberOfTrees = line.toInt\n\n implicit val Ord = implicitly[Ordering[Int]]\n\n var field: Map[Int, Int] = Map()\n var fieldPositive: SortedMap[Int, Int] = SortedMap()\n var fieldNegative: SortedMap[Int, Int] = SortedMap()(Ord.reverse)\n\n for (a <- 0 until numberOfTrees) {\n var temp = new Array[Int](2)\n var line = readLine()\n\n temp = line.split(\" \") map (_.toInt)\n\n for (b <- 0 until 2) {\n field += (temp(0) -> temp(1))\n }\n }\n\n for (a <- field) {\n if (a._1 < 0) {\n fieldNegative += (a._1 -> a._2)\n } else {\n fieldPositive += (a._1 -> a._2)\n }\n }\n\n breakable {\n for (i <- fieldPositive) {\n if (i._1 == walk + 1) {\n totalApples += i._2\n walk += 1\n } else {\n break\n }\n }\n }\n\n walk = 0\n\n breakable {\n for (i <- fieldNegative) {\n if (i._1 == walk - 1) {\n totalApples += i._2\n walk -= 1\n } else {\n break\n }\n }\n }\n\n println(totalApples)\n\n }\n}"}, {"source_code": "object LalaProblem {\n\n def main(args: Array[String]): Unit = {\n \n var listPos = List[Int]()\n var listNeg = List[Int]()\n val n: Int = readInt()\n var count: Int = 0\n var xc = 1\n\n for(x <- 0 until n){\n var line = readLine()\n var temp : Array[String] = line.split(\" \")\n if (temp(0).toInt < 0) {\n listNeg = listNeg ::: converToList(temp(0), temp(1))\n }else{\n listPos = listPos ::: converToList(temp(0), temp(1))\n }\n }\n\n if (listNeg.size == listPos.size) {\n for(x <- 0 until listNeg.size){\n if(x % 2 == 0){\n xc = x\n count += listNeg(xc + 1)\n count += listPos(xc + 1)\n }\n }\n }else{\n if(listNeg.size < listPos.size){\n for(x <- 0 until listNeg.size) {\n if(x % 2 == 0){\n xc = x\n count += listNeg(xc + 1)\n count += listPos(xc + 1)\n } \n }\n count += listPos(listNeg.size + 1)\n }else{\n for(x <- 0 until listPos.size) {\n if(x % 2 == 0){\n xc = x\n count += listNeg(xc + 1)\n count += listPos(xc + 1)\n } \n }\n count += listNeg(listPos.size + 1)\n }\n }\n println(count)\n }\n\n def converToList(x: String, y: String): List[Int] = {\n\n val xc: Int = x.toInt\n val yc: Int = y.toInt\n List(xc, yc)\n }\n}"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.collection.mutable.PriorityQueue\nimport scala.annotation.tailrec\n\n// PriorityQueue[Long]()(scala.math.Ordering.Long.reverse)\n\ncase class Tree(x : Int, a : Int)\n\nobject Main {\n object EnRich {\n implicit class AString(val self : String) extends AnyVal {\n def splitToIntArray = self.split(\" \").map(_.toInt)\n }\n }\n import EnRich._\n def main(args : Array[String]) : Unit = {\n val n = readLine.toInt\n val trees = (1 to n).map(_ => {\n val (x,a) = {\n val xa = readLine.splitToIntArray\n (xa(0),xa(1))\n }\n Tree(x,a)\n }).toVector\n val left = trees.filter({case Tree(x,a) => x < 0})\n val right = trees.filter({case Tree(x,a) => x > 0})\n val m = left.length min right.length\n val go_l = left.take(m+1) ++ right.take(m)\n val go_r = left.take(m) ++ right.take(m+1)\n\n val ans1 = go_l.map({case Tree(x,a) => a}).sum\n val ans2 = go_r.map({case Tree(x,a) => a}).sum\n\n println(ans1 max ans2)\n }\n}\n"}, {"source_code": "import scala.collection.immutable.SortedMap\n\nobject LalaProblem {\n\n def main(args: Array[String]): Unit = {\n\n \n implicit val Ord = implicitly[Ordering[Int]]\n\n var listPos: SortedMap[Int, Int] = SortedMap()\n var listNeg: SortedMap[Int, Int] = SortedMap()(Ord.reverse)\n val n: Int = readInt()\n var count: Int = 0\n\n for (x <- 0 until n) {\n var line = readLine()\n var temp: Array[String] = line.split(\" \")\n if (temp(0).toInt < 0) {\n listNeg = listNeg ++ converToMap(temp(0), temp(1))\n } else {\n listPos = listPos ++ converToMap(temp(0), temp(1))\n }\n }\n \n println(listNeg)\n println(listPos)\n\n if (listNeg.size == listPos.size) {\n listNeg.keys.foreach { x => count += listNeg(x) }\n listPos.keys.foreach { x => count += listPos(x) }\n } else {\n if (listNeg.size < listPos.size) {\n listNeg.keys.foreach { x => count += listNeg(x) }\n var newMap : Map[Int, Int] = listPos.take(listNeg.size + 1)\n newMap.keys.foreach { x => count += newMap(x) }\n } else {\n listPos.keys.foreach { x => count += listPos(x) }\n var newMap : Map[Int, Int] = listNeg.take(listPos.size + 1)\n newMap.keys.foreach { x => count += newMap(x) }\n }\n }\n println(count)\n }\n\n def converToMap(x: String, y: String): Map[Int, Int] = {\n\n val xc: Int = x.toInt\n val yc: Int = y.toInt\n Map(xc -> yc)\n }\n}\n"}, {"source_code": "object LalaProblem {\n\n def main(args: Array[String]): Unit = {\n\n var listPos: Map[Int, Int] = Map()\n var listNeg: Map[Int, Int] = Map()\n val n: Int = readInt()\n var count: Int = 0\n\n for (x <- 0 until n) {\n var line = readLine()\n var temp: Array[String] = line.split(\" \")\n if (temp(0).toInt < 0) {\n listNeg = listNeg ++ converToMap(temp(0), temp(1))\n } else {\n listPos = listPos ++ converToMap(temp(0), temp(1))\n }\n }\n listNeg.toSeq.sortWith(_._1 > _._1)\n listPos.toSeq.sortWith(_._1 < _._1)\n\n if (listNeg.size == listPos.size) {\n listNeg.keys.foreach { x => count += listNeg(x) }\n listPos.keys.foreach { x => count += listPos(x) }\n } else {\n if (listNeg.size < listPos.size) {\n listNeg.keys.foreach { x => count += listNeg(x) }\n var newMap : Map[Int, Int] = listPos.take(listNeg.size + 1)\n newMap.keys.foreach { x => count += newMap(x) }\n } else {\n listPos.keys.foreach { x => count += listPos(x) }\n var newMap : Map[Int, Int] = listNeg.take(listPos.size + 1)\n newMap.keys.foreach { x => count += newMap(x) }\n }\n }\n println(count)\n }\n\n def converToMap(x: String, y: String): Map[Int, Int] = {\n\n val xc: Int = x.toInt\n val yc: Int = y.toInt\n Map(xc -> yc)\n }\n}"}], "src_uid": "bf573af345509b2364ada6e613b6f998"} {"source_code": "import scala.collection.mutable.ArrayBuilder\n\nobject P277D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val MOD = 1000000007\n\n val Array(d, n) = readInts(2)\n val as = readInts(n)\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (i <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adj = adjBuilders.map(_.result)\n\n def dfs(origin: Int, u: Int, prev: Int, min: Int, max: Int): Long = {\n\n var cnt = 1L\n\n for (v <- adj(u)) if (v != prev && (as(v) > min || (as(v) == min && v > origin)) && as(v) <= max) {\n val cnt2 = dfs(origin, v, u, min, max)\n cnt = cnt * (cnt2 + 1) % MOD\n }\n\n cnt\n }\n\n var total = 0L\n for (u <- 0 until n) total += dfs(u, u, -1, as(u), as(u) + d)\n\n println(total % MOD)\n}", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.util.Arrays\nimport java.util.ArrayList\n\nobject Solution {\n var MOD = 1000 * 1000 * 1000 + 7\n var d: Integer = null\n var used: Array[Boolean] = null\n var graph: Array[ArrayList[Integer]] = null\n var a: Array[Integer] = null\n \n def bad(a1: Integer, i1: Integer, a2: Integer, i2: Integer): Boolean = {\n\treturn (a1 < a2 || a1 == a2 && i1 < i2 || a1 - a2 > d)\n }\n \n def dfs(v: Integer, root: Integer): Long = {\n\tif (bad(a(v), v, a(root), root))\n\t return 1\n\tused(v) = true\n\tvar res: Long = 1\n\tvar index = 0\n\tfor (index <- 0 until graph(v).size()) {\n\t val to = graph(v).get(index)\n\t if (!used(to))\n\t\tres = res * dfs(to, root) % MOD\n\t}\n\treturn res + 1\n }\n \n def main(args: Array[String]) = {\n\tval in = new Scanner(System.in)\n\td = in.nextInt()\n\tval n = in.nextInt()\n\ta = new Array(n)\n\tgraph = new Array(n)\n\tvar i = 0\n\tfor (i <- 0 until n) {\n\t graph(i) = new ArrayList()\n\t a(i) = in.nextInt()\n\t}\n\tfor (i <- 0 until n - 1) {\n\t val from = in.nextInt()\n\t val to = in.nextInt()\n\t graph(from - 1).add(to - 1)\n\t graph(to - 1).add(from - 1)\n\t}\n\tvar res: Long = 0\n\tused = new Array(n)\n\tfor (i <- 0 until n) {\n\t Arrays.fill(used, false)\n\t res = (res + dfs(i, i) - 1 + MOD) % MOD\n\t}\n\tprintln(res)\n }\n}"}], "negative_code": [], "src_uid": "88bb9b993ba8aacd6a7cf137415ef7dd"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class pair(var s: Int, var a: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n if (a == that.a && s == that.s)\n return 0\n if (a > that.s && that.a <= s)\n return 1\n if (a <= that.s && that.a > s)\n return -1\n if (a == that.a) {\n if (s < that.s)\n return -1\n else\n return 1\n }\n if (a < that.a)\n return -1\n else\n return 1\n }\n }\n val rem = 1000000007\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n\n val t = readInt()\n for (tt <- 1 to t) {\n var n = readLong() - 1L\n val k = readLong()\n var p = 1L\n var ans = 0L\n while (n > 0 && p < k) {\n ans += 1L\n n -= p\n p *= 2L\n }\n if (n > 0) {\n if (n % k != 0L) {\n ans += 1L\n n -= n % k\n }\n ans += (n / k).toLong\n }\n writer.println(ans)\n }\n writer.flush()\n}\n", "positive_code": [{"source_code": "object B extends App {\r\n\r\n def log2(x: Long): Int = {\r\n @annotation.tailrec\r\n def go(pow: Int): Int = if (x <= (1L << pow)) pow else go(pow + 1)\r\n go(0)\r\n }\r\n\r\n def updateFiles(n: Long, k: Long): Long = {\r\n val log2k = log2(k)\r\n val log2n = log2(n)\r\n\r\n if (log2n <= log2k) log2n\r\n else {\r\n val num4k = (1L << log2k) - 1L\r\n val rem = n - 1L - num4k\r\n\r\n log2k + (rem + k - 1L) / k\r\n }\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextLong()\r\n val k = nextLong()\r\n val h = updateFiles(n, k)\r\n\r\n out.println(h)\r\n }\r\n\r\n out.flush()\r\n\r\n object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n private[this] def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}, {"source_code": "object B extends App {\r\n\r\n def log2(x: Long): Int = {\r\n @annotation.tailrec\r\n def go(pow: Int): Int = if (x <= (1L << pow)) pow else go(pow + 1)\r\n go(0)\r\n }\r\n\r\n def updateFiles(n: Long, k: Long): Long = (log2(k), log2(n)) match {\r\n case (log2k, log2n) if log2n <= log2k => log2n\r\n case (log2k, _) =>\r\n val num4k = (1L << log2k) - 1L\r\n val rem = (n - 1L) - num4k\r\n\r\n log2k + (rem + k - 1L) / k\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextLong()\r\n val k = nextLong()\r\n val h = updateFiles(n, k)\r\n\r\n out.println(h)\r\n }\r\n\r\n out.flush()\r\n\r\n object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n private[this] def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}], "negative_code": [{"source_code": "object B extends App {\r\n\r\n def log2(x: Long): Int = {\r\n @annotation.tailrec\r\n def go(pow: Int): Int = if (x <= (1L << pow)) pow else go(pow + 1)\r\n go(0)\r\n }\r\n\r\n def updateFiles(n: Long, k: Long): Long =\r\n (log2(k), log2(n - 1L)) match {\r\n case (log2k, log2n) if log2n <= log2k => log2n\r\n case (log2k, _) =>\r\n val num4k = (1L << log2k) - 1L\r\n val rem = (n - 1L) - num4k\r\n\r\n log2k + (rem + k - 1L) / k\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextLong()\r\n val k = nextLong()\r\n val h = updateFiles(n, k)\r\n\r\n out.println(h)\r\n }\r\n\r\n out.flush()\r\n\r\n object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n private[this] def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}], "src_uid": "5df6eb50ead22b498bea69bb84341c06"} {"source_code": "object Solution {\n type Point = (Long, Long)\n \n def main(args: Array[String]) {\n val r = new Reader()\n val n = r.read[Int]\n val ps = r.read[List[Point]](n)\n \n println(if (ps.length < 3 || solve(ps)) \"YES\" else \"NO\")\n }\n \n def solve(ps: List[Point]) = {\n val q1 :: q2 :: q3 :: _ = ps\n lazy val u = ps.partition(collinear(_, q1, q2))._2\n lazy val v = ps.partition(collinear(_, q1, q3))._2\n lazy val w = ps.partition(collinear(_, q2, q3))._2\n \n u.length < 3 || v.length < 3 || w.length < 3 ||\n collinear(u) || collinear(v) || collinear(w)\n }\n \n def collinear(ps: List[Point]): Boolean =\n ps match {\n case p1 :: p2 :: qs => qs.dropWhile(collinear(_, p1, p2)).isEmpty\n case _ => true\n }\n\n def collinear(p: Point, q: Point, r: Point): Boolean =\n p._1*(q._2 - r._2) + q._1*(r._2 - p._2) + r._1*(p._2 - q._2) == 0\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n \n def this() = this(new InputStreamReader(System.in))\n \n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n \n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n implicit val double: Read[Double] = new Read(_.read[String].toDouble)\n \n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n \n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != \"\").map(new StringTokenizer(_)).buffered\n}", "positive_code": [{"source_code": "object A {\n def main(args: Array[String]) {\n var n = scala.io.StdIn.readInt();\n var ps = Array.ofDim[Int](n, 2);\n for(i <- 0 until n){\n ps(i) = scala.io.StdIn.readLine().split(\" \").map( _.toInt );\n }\n \n if(n <= 4) println(\"YES\");\n else{\n var a1 = check(ps, 0, 1);\n var a2 = check(ps, 0, 2);\n var a3 = check(ps, 1, 2);\n var ans = a1 || a2 || a3;\n if(ans) println(\"YES\");\n else println(\"NO\");\n }\n }\n \n def check(ps: Array[Array[Int]], id1: Int, id2: Int): Boolean = {\n var n = ps.size;\n var on = Array.ofDim[Int](n);\n for(i <- 0 until n){\n if(cross(ps(i), ps(id1), ps(id2)) == 0) on(i) = 1;\n }\n \n var line = true;\n var b0 = -1;\n var b1 = -1;\n for(i <- 0 until n){\n if(on(i) == 0){\n if(b0 == -1) b0 = i;\n else if(b1 == -1) b1 = i;\n else{\n if(cross(ps(i), ps(b0), ps(b1)) != 0) line = false;\n }\n }\n }\n \n return line;\n }\n \n def cross(p0: Array[Int], p1: Array[Int], p2: Array[Int]): Long = {\n var v0x = p1(0).toLong - p0(0).toLong;\n var v0y = p1(1).toLong - p0(1).toLong;\n var v1x = p2(0).toLong - p0(0).toLong;\n var v1y = p2(1).toLong - p0(1).toLong;\n return v0x * v1y - v0y * v1x;\n }\n}"}], "negative_code": [], "src_uid": "a9fd2e4bc5528a34f1f1b869cd391d71"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toLong).toList\n val sorted = line.sorted\n val (_, ans) = sorted.zipWithIndex.foldLeft(line, List.empty[String]) {\n case ((l, answer), (el, index)) =>\n val lindex = l.indexOf(el)\n (l.take(lindex) ::: l.drop(lindex + 1), (index until lindex + index).map(i => s\"${i + 1} ${i + 2}\").toList ::: answer)\n }\n println(ans.reverse.mkString(\"\\n\"))\n}\n", "positive_code": [{"source_code": "object Solution {\n def mrg(x:Vector[Boolean]) = {\n rle(x,0,0).sorted.reverse.headOption\n }\n def rle(x:Vector[Boolean],s:Int,l:Int):Vector[(Int,Int)] = {\n if (x.isEmpty) {\n if (l>0) Vector((l,s)) else Vector.empty[(Int,Int)]\n }\n else if (x.head) rle(x.tail,s,l+1)\n else {\n if (l==0) rle(x.tail,s+1,0)\n else (l,s) +: rle(x.tail,s+l+1,0)\n }\n }\n def gmx(x:Vector[Vector[Int]]) = mrg(x.map(v=>v.length == 2 && v(1) < v(0))).getOrElse((0,0))\n def inv(x:Vector[Int]) = {\n val g = gmx(x.grouped(2).toVector)\n val go = gmx(x.drop(1).grouped(2).toVector)\n if (g._1 > go._1) (g._2*2,g._1*2) else (1+go._2*2,2*go._1)\n }\n def re(x:Vector[Int]):Unit = {\n val g = inv(x)\n if (g._2 > 0) {\n println(s\"${g._1+1} ${g._1+g._2}\")\n re(flp(x,g))\n }\n }\n def flp(x:Vector[Int],i:(Int,Int)):Vector[Int] = {\n if (i._2 == 0) x else {\n val h = x(i._1)\n val l = x(i._1+1)\n flp(x.updated(i._1,l).updated(i._1+1,h),(i._1+2,i._2-2))\n }\n }\n def main(args: Array[String]) {\n val n = readInt\n val ns = readLine.split(\" \").map(_.toInt)\n re(ns.toVector)\n }\n}"}, {"source_code": "object B686 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val ai = readInts(n)\n\n for(i <- 0 until n) {\n val slice = ai.slice(i, n)\n val min = slice.min\n if(slice.head != min) {\n var idx = slice.indexOf(min) + i\n while(idx > i) {\n println(s\"${idx} ${idx+1}\")\n\n val temp = ai(idx)\n ai(idx) = ai(idx-1)\n ai(idx-1) = temp\n\n idx -= 1\n }\n }\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _686B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val animals = read[Vector[Int]]\n val ans = solve(animals, 0).map(i => s\"${i + 1} ${i + 2}\")\n if (ans.isEmpty) io else io.writeAll(ans, \"\\n\")\n }\n\n def solve(animals: Vector[Int], offset: Int): Seq[Int] = if (animals.isEmpty) {\n Nil\n } else {\n val smallest = animals.min\n val pos = animals.indexOf(smallest)\n //debug(animals, offset, smallest, pos)\n (offset until (offset + pos)).reverse ++ solve(animals.patch(pos, Nil, 1), offset + 1)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toYesNo = if(x) \"yes\" else \"no\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def bitCount: Int = java.lang.Integer.bitCount(x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeLine(obj: Any*): this.type = {\n if (obj.isEmpty) printer.println() else obj foreach printer.println\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val a = new Array[Int](n+1)\n for(i <- 1 to n)\n a(i) = sc.nextInt()\n\n val ans = new Array[(Int, Int)](20000)\n var ind = 0\n //\n for(i <- (1 to n-1).reverse){\n for(j <- 1 to i){\n if(a(j) > a(j+1)){\n ans(ind) = (j, j+1)\n ind += 1\n val tmp = a(j)\n a(j) = a(j+1)\n a(j + 1) = tmp\n }\n }\n }\n\n for(i <- 0 until ind){\n println(ans(i)._1 + \" \" + ans(i)._2)\n }\n }\n}\n"}, {"source_code": "object Main{\n def main(args: Array[String]) {\n\n def step (list: List[Int]): (List[Int], (Int, Int)) = {\n val size = list.size\n for(i <- 0 to size - 2){\n if (list(i) > list(i+1)){\n return (list.updated(i,list(i+1)).updated(i+1,list(i)), (i, i+1))\n }\n }\n (list, (-1, -1))\n }\n\n val n = scala.io.StdIn.readInt()\n var list = scala.io.StdIn.readLine().split(\" \").map(x => x.toInt).toList\n\n def recSolve(list: List[Int]): Unit ={\n val (l, (a,b)) = step(list)\n if (a != -1) {\n println((a+1) + \" \" + (b+1))\n recSolve(l)\n }\n }\n\n recSolve(list)\n\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toLong).toList\n val sorted = line.sorted\n val (_, ans) = sorted.zipWithIndex.foldLeft(line, List.empty[String]) {\n case ((l, answer), (el, index)) =>\n val lindex = l.indexOf(el)\n (l.take(lindex) ::: l.drop(lindex + 1), (index until lindex + index).map(i => s\"${i + 1} ${i + 2}\").reverse.toList ::: answer)\n }\n println(ans.reverse.mkString(\"\\n\"))\n}\n"}, {"source_code": "object B686 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val ai = readInts(n)\n\n for(i <- 0 until n) {\n val slice = ai.slice(i, n)\n val min = slice.min\n if(slice.head != min) {\n var idx = slice.indexOf(min) + i\n while(idx > i) {\n println(s\"${idx+1} ${idx}\")\n\n val temp = ai(idx)\n ai(idx) = ai(idx-1)\n ai(idx-1) = temp\n\n idx -= 1\n }\n }\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val a = new Array[Int](n+1)\n for(i <- 1 to n)\n a(i) = sc.nextInt()\n\n val ans = new Array[(Int, Int)](20000)\n var ind = 0\n //\n for(i <- (2 to n-1).reverse){\n for(j <- 1 to i){\n if(a(j) > a(j+1)){\n ans(ind) = (j, j+1)\n ind += 1\n val tmp = a(j)\n a(j) = a(j+1)\n a(j + 1) = tmp\n }\n }\n }\n\n for(i <- 0 until ind){\n println(ans(i)._1 + \" \" + ans(i)._2)\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val a = new Array[Int](n+1)\n for(i <- 1 to n)\n a(i) = sc.nextInt()\n\n val ans = new Array[(Int, Int)](20000)\n var ind = 0\n //\n for(i <- 1 to n-1){\n for(j <- i to n-1){\n if(a(j) > a(j+1)){\n ans(ind) = (j, j+1)\n ind += 1\n val tmp = a(j)\n a(j) = a(j+1)\n a(j + 1) = tmp\n }\n }\n }\n\n for(i <- 0 until ind){\n println(ans(i)._1 + \" \" + ans(i)._2)\n }\n }\n}\n"}], "src_uid": "233c2806db31916609421fbd126133d0"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n print(\"abcd\" * (n / 4))\n n % 4 match {\n case 0 =>\n case 1 => print(\"a\")\n case 2 => print(\"ab\")\n case 3 => println(\"abc\")\n }\n } \n}", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val res = \"abcd\"\n println(res * (n / 4) + res.take(n % 4))\n}"}], "negative_code": [], "src_uid": "94278e9c55f0fc82b48145ebecbc515f"} {"source_code": "import java.util\nimport java.util.Scanner\n\nobject DLizards extends App {\n\n val scanner = new Scanner(System.in)\n\n var initMove = 0\n val n = scanner.nextInt()\n val dmg = scanner.nextInt()\n val sdmg = scanner.nextInt()\n var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]\n val in = (0 until n) map (i => scanner.nextInt())\n val inj = init(init(in, 1, -1), n - 2, 1)\n val srcSum = inj.sum\n var visited = new util.HashSet[Seq[Int]]()\n\n def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {\n if (src(idx + step) == -1) {\n src\n } else {\n initTrace += idx\n initMove += 1\n init(shot(src, idx)._1, idx, step)\n }\n }\n\n val q = scala.collection.mutable.PriorityQueue.empty[Entry]\n val first = Entry(inj, 0, Nil, 0)\n q.enqueue(first)\n solve()\n\n def solve(): Unit = {\n val cur = q.dequeue()\n if (cur.finished()) {\n println(cur.move + initMove)\n print(initTrace.map(_ + 1).mkString(\" \") + \" \")\n print(cur.trace.map(_ + 1).reverse.mkString(\" \"))\n }\n else {\n val next = cur.next()\n next.foreach(it => visited.add(it.archers))\n q.enqueue(next: _*)\n solve()\n }\n }\n\n case class Entry(archers: Seq[Int], move: Int, trace: List[Int], bias: Int) extends Ordered[Entry] {\n\n val dmgDealt = inj.sum - archers.sum\n\n override def compare(that: Entry): Int = {\n //-this.bias.compareTo(that.bias)\n //-(this.bias.toDouble + move.toDouble * 0.01).compareTo(that.bias.toDouble + that.move.toDouble * 0.01)\n if (this.bias > that.bias) {\n -1\n } else if (this.bias == that.bias) {\n this.move.compareTo(that.move)\n } else {\n 1\n }\n }\n\n def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx) if !visited.contains(tmp._1)) yield Entry(tmp._1, move + 1, idx :: trace, this.bias + tmp._2)\n\n def finished(): Boolean = !archers.exists(_ != -1)\n\n }\n\n def shot(a: Seq[Int], idx: Int): (Seq[Int], Int) = {\n val r: Array[Int] = Array(a: _*)\n var bias = 0\n def norm(i: Int) = if (r(i) < 0) {\n bias += math.abs(r(i) + 1)\n r(i) = -1\n }\n r(idx) = r(idx) - dmg\n norm(idx)\n if (idx > 0) {\n r(idx - 1) = r(idx - 1) - sdmg\n norm(idx - 1)\n }\n if (idx < n - 1) {\n r(idx + 1) = r(idx + 1) - sdmg\n norm(idx + 1)\n }\n (r.toSeq, bias)\n }\n\n}", "positive_code": [{"source_code": "object P6D {\n def main(args : Array[String]) {\n val Array(n, a, b) = readLine split ' ' map {_.toInt}\n val h = readLine split ' ' map {_.toInt + 1}\n val hm = h.max + 1\n case class Node(v : Int, from : Int)\n val s = Array.fill(n - 2, hm, hm){Node(Int.MaxValue >>> 1, -1)}\n for (i <- 0 until hm) {\n if (i * b >= h(0)) s(0)(0)(i) = Node(i, -1)\n }\n for {\n i <- 1 until n - 2\n k1 <- 0 until hm\n k2 <- 0 until hm\n k3 <- 0 until hm\n if (k1 * b + k2 * a + k3 * b >= h(i))\n x = s(i - 1)(k1)(k2).v + k3\n if (x < s(i)(k2)(k3).v)\n } s(i)(k2)(k3) = Node(x, k1)\n var answer = (Int.MaxValue, -1, -1)\n for {\n k1 <- 0 until hm\n k2 <- 0 until hm\n if (k1 * b + k2 * a >= h(n - 2))\n if (k2 * b >= h(n - 1))\n x = s(n - 3)(k1)(k2).v\n if (x < answer._1)\n } answer = (x, k1, k2)\n println(answer._1)\n def solve(i : Int, k1 : Int, k2 : Int) {\n if (i < 0) return\n val out = ((i + 2) + \" \") * k2\n if (i == 0) println(out.trim) else print(out)\n solve(i - 1, s(i)(k1)(k2).from, k1)\n }\n solve(n - 3, answer._2, answer._3)\n }\n}\n"}, {"source_code": "object main extends App with fastIO {\n \n val Array(n, a, b) = readLine split(\" \") map(_.toInt) \n var array = readLine split(\" \") map(_.toInt + 1)\n \n var dp = Array.fill(20, 20, 20, 20)(Int.MaxValue >> 1)\n \n def dfs(n :Int, A :Int, B :Int, C :Int) :Int = {\n \n if (n == 0) return 0\n if (dp(n)(A)(B)(C) < Int.MaxValue / 2) return dp(n)(A)(B)(C) \n \n val hp = array(n - 1) - (A + C) * b - B * a\n if (hp <= 0) return dfs(n - 1, 0, A, B)\n \n var res = Int.MaxValue / 2 \n if (n > 2) res = res min dfs(n, A + 1, B, C)\n if (n > 1) res = res min dfs(n, A, B + 1, C)\n if (n > 0) res = res min dfs(n, A, B, C + 1)\n \n dp(n)(A)(B)(C) = res + 1 \n res + 1\n }\n \n def printResult(n :Int, A :Int, B :Int, C :Int) {\n if (n == 0) return \n \n val hp = array(n - 1) - (A + C) * b - B * a\n if (hp <= 0) return printResult(n - 1, 0, A, B)\n\n val res = dp(n)(A)(B)(C)\n if (n > 2 && dfs(n, A + 1, B, C) < res) { printResult(n, A + 1, B, C); print((n - 1) + \" \") } else \n if (n > 1 && dfs(n, A, B + 1, C) < res) { printResult(n, A, B + 1, C); print(n + \" \") } else\n { printResult(n, A, B, C + 1); print((n + 1) + \" \") }\n }\n \n val r = (array(n - 1) + b - 1) / b \n val res = dfs(n - 1, 0, r, 0)\n \n println(res + r) \n printResult(n - 1, 0, r, 0)\n println(((n - 1) + \" \") * r) \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def nextInt :Int = { in.nextToken; in.nval.toInt } \n def nextLong :Long = { in.nextToken; in.nval.toLong } \n def nextDouble :Double = { in.nextToken; in.nval.toDouble } \n def readLine = bf.readLine\n \n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n \n def flush = out.flush\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nobject DLizards extends App {\n\n val scanner = new Scanner(System.in)\n\n var initMove = 0\n val n = scanner.nextInt()\n val dmg = scanner.nextInt()\n val sdmg = scanner.nextInt()\n var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]\n val in = (0 until n) map (i => scanner.nextInt())\n val inj = init(init(in, 1, -1), n - 2, 1)\n\n\n def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {\n if (src(idx + step) == -1) {\n src\n } else {\n initTrace += idx\n initMove += 1\n init(shot(src, idx), idx, step)\n }\n }\n\n val q = scala.collection.mutable.PriorityQueue.empty[Entry]\n val first = Entry(inj, 0, Nil)\n q.enqueue(first)\n solve()\n\n def solve(): Unit = {\n val cur = q.dequeue()\n if (cur.finished()) {\n println(cur.move + initMove)\n print(initTrace.map(_ + 1).mkString(\" \") + \" \")\n print(cur.trace.map(_ + 1).reverse.mkString(\" \"))\n }\n else {\n q.enqueue(cur.next(): _*)\n solve()\n }\n }\n\n case class Entry(archers: Seq[Int], move: Int, trace: List[Int]) extends Ordered[Entry] {\n\n override def compare(that: Entry): Int = {\n -(archers.sum + move * archers.size).compareTo(that.archers.sum + that.archers.size * move)\n }\n\n def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx)) yield Entry(tmp, move + 1, idx :: trace)\n\n def finished(): Boolean = math.abs(archers.sum) == archers.size\n\n }\n\n def shot(a: Seq[Int], idx: Int): Seq[Int] = {\n val r: Array[Int] = Array(a: _*)\n def norm(i: Int) = if (r(i) < 0) r(i) = -1\n r(idx) = r(idx) - dmg\n norm(idx)\n if (idx > 0) {\n r(idx - 1) = r(idx - 1) - sdmg\n norm(idx - 1)\n }\n if (idx < n - 1) {\n r(idx + 1) = r(idx + 1) - sdmg\n norm(idx + 1)\n }\n r.toSeq\n }\n\n}"}, {"source_code": "import java.util.Scanner\n\nobject DLizards extends App {\n\n val scanner = new Scanner(System.in)\n\n var initMove = 0\n val n = scanner.nextInt()\n val dmg = scanner.nextInt()\n val sdmg = scanner.nextInt()\n var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]\n val in = (0 until n) map (i => scanner.nextInt())\n val inj = init(init(in, 1, -1), n - 2, 1)\n\n\n def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {\n if (src(idx + step) == -1) {\n src\n } else {\n initTrace += idx\n initMove += 1\n init(shot(src, idx), idx, step)\n }\n }\n\n val q = scala.collection.mutable.PriorityQueue.empty[Entry]\n val first = Entry(inj, 0, Nil)\n q.enqueue(first)\n solve()\n\n def solve(): Unit = {\n val cur = q.dequeue()\n if (cur.finished()) {\n println(cur.move + initMove)\n print(initTrace.map(_ + 1).mkString(\" \") + \" \")\n print(cur.trace.map(_ + 1).reverse.mkString(\" \"))\n }\n else {\n q.enqueue(cur.next(): _*)\n solve()\n }\n }\n\n case class Entry(archers: Seq[Int], move: Int, trace: List[Int]) extends Ordered[Entry] {\n\n override def compare(that: Entry): Int = {\n -(archers.sum + move).compareTo(that.archers.sum + that.move)\n }\n\n def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx)) yield Entry(tmp, move + 1, idx :: trace)\n\n def finished(): Boolean = !archers.exists(_ != -1)\n\n }\n\n def shot(a: Seq[Int], idx: Int): Seq[Int] = {\n val r: Array[Int] = Array(a: _*)\n def norm(i: Int) = if (r(i) < 0) r(i) = -1\n r(idx) = r(idx) - dmg\n norm(idx)\n if (idx > 0) {\n r(idx - 1) = r(idx - 1) - sdmg\n norm(idx - 1)\n }\n if (idx < n - 1) {\n r(idx + 1) = r(idx + 1) - sdmg\n norm(idx + 1)\n }\n r.toSeq\n }\n\n}"}, {"source_code": "import java.util.Scanner\n\nobject DLizards extends App {\n\n val scanner = new Scanner(System.in)\n\n var initMove = 0\n val n = scanner.nextInt()\n val dmg = scanner.nextInt()\n val sdmg = scanner.nextInt()\n var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]\n val in = (0 until n) map (i => scanner.nextInt())\n val inj = init(init(in, 1, -1), n - 2, 1)\n\n\n def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {\n if (src(idx + step) == -1) {\n src\n } else {\n initTrace += idx\n initMove += 1\n init(shot(src, idx), idx, step)\n }\n }\n\n val q = scala.collection.mutable.PriorityQueue.empty[Entry]\n val first = Entry(inj, 0, Nil, inj.sum)\n q.enqueue(first)\n solve()\n\n def solve(): Unit = {\n val cur = q.dequeue()\n if (cur.finished()) {\n println(cur.move + initMove)\n print(initTrace.map(_ + 1).mkString(\" \") + \" \")\n print(cur.trace.map(_ + 1).reverse.mkString(\" \"))\n }\n else {\n q.enqueue(cur.next(): _*)\n solve()\n }\n }\n\n case class Entry(archers: Seq[Int], move: Int, trace: List[Int], prevSum: Int) extends Ordered[Entry] {\n\n override def compare(that: Entry): Int = {\n -(archers.sum + move * (archers.sum - prevSum)).compareTo(that.archers.sum + that.move * (that.archers.sum - that.prevSum))\n }\n\n def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx)) yield Entry(tmp, move + 1, idx :: trace, archers.sum)\n\n def finished(): Boolean = !archers.exists(_ != -1)\n\n }\n\n def shot(a: Seq[Int], idx: Int): Seq[Int] = {\n val r: Array[Int] = Array(a: _*)\n def norm(i: Int) = if (r(i) < 0) r(i) = -1\n r(idx) = r(idx) - dmg\n norm(idx)\n if (idx > 0) {\n r(idx - 1) = r(idx - 1) - sdmg\n norm(idx - 1)\n }\n if (idx < n - 1) {\n r(idx + 1) = r(idx + 1) - sdmg\n norm(idx + 1)\n }\n r.toSeq\n }\n\n}"}, {"source_code": "import java.util.Scanner\n\nobject DLizards extends App {\n\n val scanner = new Scanner(System.in)\n\n var initMove = 0\n val n = scanner.nextInt()\n val dmg = scanner.nextInt()\n val sdmg = scanner.nextInt()\n var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]\n val in = (0 until n) map (i => scanner.nextInt())\n val inj = init(init(in, 1, -1), n - 2, 1)\n\n\n def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {\n if (src(idx + step) == -1) {\n src\n } else {\n initTrace += idx\n initMove += 1\n init(shot(src, idx), idx, step)\n }\n }\n\n val q = scala.collection.mutable.PriorityQueue.empty[Entry]\n val first = Entry(inj, 0, Nil)\n q.enqueue(first)\n solve()\n\n def solve(): Unit = {\n val cur = q.dequeue()\n if (cur.finished()) {\n println(cur.move + initMove)\n print(initTrace.map(_ + 1).mkString(\" \") + \" \")\n print(cur.trace.map(_ + 1).reverse.mkString(\" \"))\n }\n else {\n q.enqueue(cur.next(): _*)\n solve()\n }\n }\n\n case class Entry(archers: Seq[Int], move: Int, trace: List[Int]) extends Ordered[Entry] {\n\n override def compare(that: Entry): Int = {\n archers.sum + move * archers.size\n }\n\n def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx)) yield Entry(tmp, move + 1, idx :: trace)\n\n def finished(): Boolean = math.abs(archers.sum) == archers.size\n\n }\n\n def shot(a: Seq[Int], idx: Int): Seq[Int] = {\n val r = a.toArray\n def norm(i: Int) = if (r(i) < 0) r(i) = -1\n r(idx) = r(idx) - dmg\n norm(idx)\n if (idx > 0) {\n r(idx - 1) = r(idx - 1) - sdmg\n norm(idx - 1)\n }\n if (idx < n - 1) {\n r(idx + 1) = r(idx + 1) - sdmg\n norm(idx + 1)\n }\n r.toSeq\n }\n\n}"}, {"source_code": "import java.util.Scanner\n\nobject DLizards extends App {\n\n val scanner = new Scanner(System.in)\n\n var initMove = 0\n val n = scanner.nextInt()\n val dmg = scanner.nextInt()\n val sdmg = scanner.nextInt()\n var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]\n val in = (0 until n) map (i => scanner.nextInt())\n val inj = init(init(in, 1, -1), n - 2, 1)\n\n\n def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {\n if (src(idx + step) == -1) {\n src\n } else {\n initTrace += idx\n initMove += 1\n init(shot(src, idx), idx, step)\n }\n }\n\n val q = scala.collection.mutable.PriorityQueue.empty[Entry]\n val first = Entry(inj, 0, Nil)\n q.enqueue(first)\n solve()\n\n def solve(): Unit = {\n val cur = q.dequeue()\n if (cur.finished()) {\n println(cur.move + initMove)\n print(initTrace.map(_ + 1).mkString(\" \") + \" \")\n print(cur.trace.map(_ + 1).reverse.mkString(\" \"))\n }\n else {\n q.enqueue(cur.next(): _*)\n solve()\n }\n }\n\n case class Entry(archers: Seq[Int], move: Int, trace: List[Int]) extends Ordered[Entry] {\n\n override def compare(that: Entry): Int = {\n -(archers.sum + move * archers.size).compareTo(that.archers.sum + that.archers.size * move)\n }\n\n def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx)) yield Entry(tmp, move + 1, idx :: trace)\n\n def finished(): Boolean = !archers.exists(_ != -1)\n\n }\n\n def shot(a: Seq[Int], idx: Int): Seq[Int] = {\n val r: Array[Int] = Array(a: _*)\n def norm(i: Int) = if (r(i) < 0) r(i) = -1\n r(idx) = r(idx) - dmg\n norm(idx)\n if (idx > 0) {\n r(idx - 1) = r(idx - 1) - sdmg\n norm(idx - 1)\n }\n if (idx < n - 1) {\n r(idx + 1) = r(idx + 1) - sdmg\n norm(idx + 1)\n }\n r.toSeq\n }\n\n}"}], "src_uid": "a9bad412597726f8cdc0cfa2da891bc4"} {"source_code": "object C extends App {\n\n /**\n * @param n The number of cells\n * @param ls Operational parameters\n */\n private def colorize(n: Int, ls: Seq[Int]): Seq[Int] = {\n val ml = ls.zipWithIndex.map { case (l, i) => l + i }.max\n\n if (ml > n) Seq(-1)\n else {\n val suffix = ls.scanRight(0L)(_ + _)\n\n if (suffix.head < n) Seq(-1)\n else\n (1 to ls.length).zip(suffix).map {\n case (i, si) => ((n + 1L - si) max i).toInt\n }\n }\n\n }\n\n val Array(n, _) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val ls = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ps = colorize(n, ls)\n\n println(ps.mkString(\" \"))\n}", "positive_code": [{"source_code": "object C extends App {\n\n /**\n * @param n The number of cells\n * @param ls Operational parameters\n */\n private def colorize(n: Int, ls: Seq[Int]): Seq[Long] = {\n val ml = ls.zipWithIndex.map { case (l, i) => l + i }.max\n\n if (ml > n) Seq(-1)\n else {\n val suffix = ls.scanRight(0L)(_ + _)\n\n if (suffix.head < n) Seq(-1L)\n else\n (1L to ls.length).zip(suffix).map {\n case (i, si) => (i max (n + 1L- si))\n }\n }\n\n }\n\n val Array(n, _) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val ls = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ps = colorize(n, ls)\n\n println(ps.mkString(\" \"))\n}"}], "negative_code": [{"source_code": "object C extends App {\n\n /**\n * @param n The number of cells\n * @param ls Operational parameters\n */\n private def colorize(n: Int, ls: Seq[Int]): Option[Seq[Int]] = {\n val suffix = ls.scanRight(0)(_ + _)\n\n if (suffix.head < n) None\n else\n Some((1 to ls.length).zip(suffix).map {\n case (i, si) => (i max (n + 1 - si))\n })\n }\n\n val Array(n, _) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val ls = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ps = colorize(n, ls)\n\n ps match {\n case None => println(\"-1\")\n case Some(ps) => {\n println(ps.length)\n println(ps.mkString(\" \"))\n }\n }\n}"}, {"source_code": "object C extends App {\n\n /**\n * @param n The number of cells\n * @param ls Operational parameters\n */\n private def colorize(n: Int, ls: Seq[Int]): Seq[Int] = {\n val suffix = ls.scanRight(0)(_ + _)\n\n if (suffix.head < n) Seq(-1)\n else\n (1 to ls.length).zip(suffix).map { case (i, si) => (i max (n + 1 - si)) }\n }\n\n val Array(n, _) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val ls = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ps = colorize(n, ls)\n\n println(ps.mkString(\" \"))\n}"}, {"source_code": "object C extends App {\n\n /**\n * @param n The number of cells\n * @param ls Operational parameters\n */\n private def colorize(n: Int, ls: Seq[Int]): Seq[Int] = {\n val ml = ls.zipWithIndex.map { case (l, i) => l + i }.max\n\n if (ml > n) Seq(-1)\n else {\n val suffix = ls.scanRight(0)(_ + _)\n\n if (suffix.head < n) Seq(-1)\n else\n (1 to ls.length).zip(suffix).map {\n case (i, si) => (i max (n + 1 - si))\n }\n }\n\n }\n\n val Array(n, _) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val ls = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ps = colorize(n, ls)\n\n println(ps.mkString(\" \"))\n}"}], "src_uid": "90be8c6cf8f2cd626d41d2b0be2dfed3"} {"source_code": "object CF118B {\n def main(args: Array[String]): Unit = {\n val s = readDouble()\n val Array(a, b, c) = readLine().split(\" \").map(_.toDouble)\n if (a + b + c == 0) {\n println(s + \" 0.0 0.0\")\n } else {\n val x = s * (a / (a + b + c))\n val y = s * (b / (a + b + c))\n val z = s * (c / (a + b + c))\n println(x + \" \" + y + \" \" + z)\n }\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = readInt\n val Array(a, b, c) = readLine.split(\" \").map(_.toInt)\n val sum = a + b + c\n if (sum == 0) {\n println(List(s / 3.0, s / 3.0, s / 3.0).mkString(\" \"))\n }\n else{\n val fs = sum.toDouble\n val (fa, fb, fc) = (s * a / fs, s * b / fs, s * c / fs)\n println(List(fa, fb, fc).mkString(\" \"))\n }\n }\n}\n"}], "negative_code": [{"source_code": "object CF118B {\n def main(args: Array[String]): Unit = {\n val s = readInt().doubleValue\n val Array(a, b, c) = readLine().split(\" \").map(_.toInt)\n if (a + b + c == 0) {\n println(s + \" 0.0 0.0\")\n } else {\n val x = s * (a / (a + b + c))\n val y = s * (b / (a + b + c))\n val z = s * (c / (a + b + c))\n println(x + \" \" + y + \" \" + z)\n }\n }\n}\n"}, {"source_code": "object CF118B {\n def main(args: Array[String]): Unit = {\n val s = readInt().doubleValue\n val Array(a, b, c) = readLine().split(\" \").map(_.toInt)\n val max = List(a, b, c).max\n if (max == a && max == b && max == c){\n println(s / 3 + \" \" + s / 3 + \" \" + s / 3)\n } else if (max == a && max == b) {\n println(s / 2 + \" \" + s / 2 + \" \" + 0)\n } else if (max == b && max == c) {\n println(0 + \" \" + s / 2 + \" \" + s / 2)\n } else if (max == c && max == a) {\n println(s / 2 + \" \" + 0 + \" \" + s / 2)\n } else if (max == a) {\n println(s + \" \" + 0 + \" \" + 0)\n } else if (max == b) {\n println(0 + \" \" + s + \" \" + 0)\n } else if (max == c) {\n println(0 + \" \" + 0 + \" \" + s)\n }\n }\n}\n"}], "src_uid": "0a9cabb857949e818453ffe411f08f95"} {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val n = readString.toInt\n var as = readInts.distinct\n\n var bit = 1 << 30\n\n while (bit > 0) {\n\n val bs = as.filter(a => (a & bit) != 0)\n\n if (!bs.isEmpty && bs.reduce(_ & _) % bit == 0) {\n println(bs.size)\n println(bs.mkString(\" \"))\n exit\n }\n\n bit >>= 1\n }\n\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val n = readString.toInt\n var as = readInts.distinct\n\n var threshold = 1 << 30\n\n while (threshold > 0) {\n\n val bs = as.filter(a => (a & threshold) != 0)\n\n if (!bs.isEmpty && bs.reduce((a, b) => a & b) % threshold == 0) {\n println(bs.size)\n println(bs.mkString(\" \"))\n exit\n }\n\n threshold /= 2\n }\n\n}"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val n = readString.toInt\n val MAX = 1000000000\n var as = Array.fill(n)(scala.util.Random.nextInt % MAX)\n //var as = readInts.distinct\n var bs = Seq[Int]()\n \n var threshold = 1\n \n while (!as.isEmpty) {\n \n\tval remove = mutable.BitSet(as.size)\n\t\n\tvar bit = 1\n\twhile (bit < threshold) {\n\t if (!as.indices.exists(i => (as(i) & bit) == 0 && !remove(i))) {\n\t as.indices.withFilter(i => (as(i) & bit) != 0).foreach(i => remove += i)\n\t }\n\t bit *= 2\n\t}\n\t\n\tvar bestCount = 0\n\tvar bestBit = 0\n\t\n\twhile (bit <= MAX) {\n\t val count = as.indices.count(i => (as(i) & bit) != 0 && !remove(i))\n\t if (count > bestCount) {\n\t bestCount = count\n\t bestBit = bit\n\t }\n\t bit *= 2\n\t}\n\t\n\tif (bestBit > 0) bs = as.indices.withFilter(i => (as(i) & bestBit) != 0 && !remove(i)).map(i => as(i))\n \n threshold *= 2\n\tas = as.filter(_ >= threshold)\n }\n\n println(bs.size)\n if (n < 100000) println(bs.mkString(\" \"))\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val n = readString.toInt\n val MAX = 1000000000\n var as = Array.fill(n)(scala.util.Random.nextInt % MAX)\n //var as = readInts.distinct\n var bs = Seq[Int]()\n \n var threshold = 1\n \n while (!as.isEmpty) {\n \n\tval remove = mutable.BitSet(as.size)\n\t\n\tvar bit = 1\n\twhile (bit < threshold) {\n\t if (!as.indices.exists(i => (as(i) & bit) == 0 && !remove(i))) {\n\t as.indices.withFilter(i => (as(i) & bit) != 0).foreach(i => remove += i)\n\t }\n\t bit *= 2\n\t}\n\t\n\tvar bestCount = 0\n\tvar bestBit = 0\n\t\n\twhile (bit <= MAX) {\n\t val count = as.indices.count(i => (as(i) & bit) != 0 && !remove(i))\n\t if (count > bestCount) {\n\t bestCount = count\n\t bestBit = bit\n\t }\n\t bit *= 2\n\t}\n\t\n\tif (bestBit > 0) bs = as.indices.withFilter(i => (as(i) & bestBit) != 0 && !remove(i)).map(i => as(i))\n \n threshold *= 2\n\tas = as.filter(_ >= threshold)\n }\n\n println(bs.size)\n //println(bs.mkString(\" \"))\n}"}], "src_uid": "54c23dda2aa1d58ecf22c03015dca55c"} {"source_code": "object A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n\n val m = readInt\n val stepPos = Array.ofDim[Long](m)\n\n val stepA = Array.ofDim[Boolean](m)\n val stepPar = Array.ofDim[Int](m)\n\n var pos = 0L\n for (i <- 0 until m) {\n val t = tokenizeLine\n val typ = t.nextToken.toInt\n if (typ == 1) {\n stepA(i) = true\n stepPar(i) = t.nextToken.toInt\n pos += 1\n stepPos(i) = pos\n } else {\n val l = t.nextToken.toInt\n val c = t.nextToken.toInt\n stepA(i) = false\n stepPar(i) = l\n pos += l * c\n stepPos(i) = pos\n }\n }\n\n @annotation.tailrec\n def get(q: Long): Int = {\n var i = java.util.Arrays.binarySearch(stepPos, q)\n if (i < 0) i = -1 - i\n if (stepA(i)) stepPar(i)\n else {\n val l = stepPar(i)\n var q2 = ((q - stepPos(i - 1)) % l)\n if (q2 == 0) q2 = l\n get(q2)\n }\n }\n\n val n = readInt\n val qs = readLongs(n)\n val ans = qs.map(get)\n println(ans.mkString(\" \"))\n}", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject P380A {\n class SerejaSequence (scanner: Scanner) {\n val m = scanner.nextInt()\n val seq = new Array[Int](m)\n val periods = new Array[Long](m + 1)\n val types = new Array[Int](m)\n\n for (i <- 0 until m) {\n types(i) = scanner.nextInt()\n if (types(i) == 1) {\n seq(i) = scanner.nextInt()\n periods(i + 1) = periods(i) + 1\n }\n else {\n val l = scanner.nextInt()\n val c = scanner.nextInt()\n seq(i) = l\n periods(i + 1) = periods(i) + l * c\n }\n }\n\n def apply(i: Long): Int = {\n val pos = java.util.Arrays.binarySearch(periods, i)\n val index = if (pos >= 0) pos else -(pos + 2)\n if (types(index) == 1) {\n seq(index)\n }\n else {\n apply((i - periods(index)) % seq(index))\n }\n }\n }\n\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val seq = new SerejaSequence(scanner)\n val n = scanner.nextInt()\n val ans = for (i <- 1 to n) yield seq(scanner.nextLong() - 1)\n println(ans.mkString(\" \"))\n }\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n @inline def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n @inline def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n\n val m = readInt\n val stepPos = Array.ofDim[Long](m)\n\n val stepA = Array.ofDim[Boolean](m)\n val stepPar = Array.ofDim[Int](m)\n\n var pos = 0L\n \n for (i <- 0 until m) {\n val t = tokenizeLine\n val typ = t.nextToken.toInt\n if (typ == 1) {\n stepA(i) = true\n stepPar(i) = t.nextToken.toInt\n pos += 1\n stepPos(i) = pos\n } else {\n val l = t.nextToken.toInt\n val c = t.nextToken.toInt\n stepA(i) = false\n stepPar(i) = l\n pos += l * c\n stepPos(i) = pos\n }\n }\n\n @annotation.tailrec\n def get(q: Long): Int = {\n var i = java.util.Arrays.binarySearch(stepPos, q)\n if (i < 0) i = -1 - i\n if (stepA(i)) stepPar(i)\n else {\n val l = stepPar(i)\n var q2 = ((q - stepPos(i - 1)) % l)\n if (q2 == 0) q2 = l\n get(q2)\n }\n }\n\n val n = readInt\n val qs = readLongs(n)\n val ans = qs.map(get)\n println(ans.mkString(\" \"))\n}"}, {"source_code": "object A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n\n val m = readInt\n val stepPos = Array.ofDim[Long](m)\n\n val stepA = Array.ofDim[Boolean](m)\n val stepPar = Array.ofDim[Int](m)\n\n var pos = 0L\n \n for (i <- 0 until m) {\n val t = tokenizeLine\n val typ = t.nextToken.toInt\n if (typ == 1) {\n stepA(i) = true\n stepPar(i) = t.nextToken.toInt\n pos += 1\n stepPos(i) = pos\n } else {\n val l = t.nextToken.toInt\n val c = t.nextToken.toInt\n stepA(i) = false\n stepPar(i) = l\n pos += l * c\n stepPos(i) = pos\n }\n }\n\n @annotation.tailrec\n def get(q: Long): Int = {\n var i = java.util.Arrays.binarySearch(stepPos, q)\n if (i < 0) i = -1 - i\n if (stepA(i)) stepPar(i)\n else {\n val l = stepPar(i)\n var q2 = ((q - stepPos(i - 1)) % l)\n if (q2 == 0) q2 = l\n get(q2)\n }\n }\n\n val n = readInt\n val qs = readLongs(n)\n val ans = qs.map(get)\n println(ans.mkString(\" \"))\n}"}, {"source_code": "object A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n\n val m = readInt\n val stepPos = Array.ofDim[Long](m)\n\n val stepA = Array.ofDim[Boolean](m)\n val stepPar = Array.ofDim[Int](m)\n\n var pos = 0L\n for (i <- 0 until m) {\n val t = tokenizeLine\n val typ = t.nextToken.toInt\n if (typ == 1) {\n stepA(i) = true\n stepPar(i) = t.nextToken.toInt\n pos += 1\n stepPos(i) = pos\n } else {\n val l = t.nextToken.toInt\n val c = t.nextToken.toInt\n stepA(i) = false\n stepPar(i) = l\n pos += l * c\n stepPos(i) = pos\n }\n }\n\n @annotation.tailrec\n def get(q: Long): Int = {\n var i = java.util.Arrays.binarySearch(stepPos, q)\n if (i < 0) i = -1 - i\n if (stepA(i)) stepPar(i)\n else {\n val l = stepPar(i)\n var q2 = ((q - stepPos(i - 1)) % l)\n if (q2 == 0) q2 = l\n get(q2)\n }\n }\n\n val n = readInt\n val qs = readLongs(n)\n val ans = qs.map(get)\n println(ans.mkString(\" \"))\n}"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n @inline def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n @inline def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n\n val m = readInt\n val stepPos = Array.ofDim[Long](m)\n\n val stepA = Array.ofDim[Boolean](m)\n val stepPar = Array.ofDim[Int](m)\n\n var pos = 0L\n for (i <- 0 until m) {\n val t = tokenizeLine\n val typ = t.nextToken.toInt\n if (typ == 1) {\n stepA(i) = true\n stepPar(i) = t.nextToken.toInt\n pos += 1\n stepPos(i) = pos\n } else {\n val l = t.nextToken.toInt\n val c = t.nextToken.toInt\n stepA(i) = false\n stepPar(i) = l\n pos += l * c\n stepPos(i) = pos\n }\n }\n\n @annotation.tailrec\n def get(q: Long): Int = {\n var i = java.util.Arrays.binarySearch(stepPos, q)\n if (i < 0) i = -1 - i\n if (stepA(i)) stepPar(i)\n else {\n val l = stepPar(i)\n var q2 = ((q - stepPos(i - 1)) % l)\n if (q2 == 0) q2 = l\n get(q2)\n }\n }\n\n val n = readInt\n val qs = readLongs(n)\n val ans = qs.map(get)\n println(ans.mkString(\" \"))\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nobject P380A {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val m = scanner.nextInt()\n val list = scala.collection.mutable.ListBuffer[Int]()\n for (stage <- 1 to m) {\n val t = scanner.nextInt()\n if (t == 1) {\n val num = scanner.nextInt()\n list += num\n }\n else {\n val l = scanner.nextInt()\n val c = scanner.nextInt()\n val addList = list.toList.take(l)\n for (i <- 1 to c) list ++= addList\n }\n }\n val n = scanner.nextInt()\n val ans = list.toList.take(n)\n println(ans.mkString(\" \"))\n }\n}\n"}], "src_uid": "d0cbb044dccac66dd7a05ad2540fc6c8"} {"source_code": "//package me.jetblack.codeforces\n\nimport java.util.Scanner\n\nobject A8Train extends App {\n\n val scanner = new Scanner(System.in)\n val a = scanner.next()\n val b = scanner.next()\n val c = scanner.next()\n\n val r1 = solve(a)\n val r2 = solve(a.reverse)\n\n if (r1 && r2) {\n println(\"both\")\n } else if (r1) {\n println(\"forward\")\n } else if (r2) {\n println(\"backward\")\n } else {\n println(\"fantasy\")\n }\n\n def solve(s: String): Boolean = {\n s.contains(b) && s.contains(c) && s.replaceFirst(b, \"\").contains(c) && s.indexOf(b) < s.lastIndexOf(c)\n }\n\n}\n", "positive_code": [{"source_code": "object P8A {\n import io.StdIn._\n\n def main(args:Array[String]) {\n val (s, s1, s2) = (readLine, readLine, readLine)\n val b1 = (s1 + \".*\" + s2).r.findFirstMatchIn(s).nonEmpty\n val (s1r, s2r) = (s1.reverse, s2.reverse)\n val b2 = (s2r + \".*\" + s1r).r.findFirstMatchIn(s).nonEmpty\n println(() match {\n case _ if b1 && b2 => \"both\"\n case _ if b1 => \"forward\"\n case _ if b2 => \"backward\"\n case _ => \"fantasy\"\n })\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val reverse = str.reverse\n// println(reverse)\n val a1 = in.next()\n val b1 = in.next()\n val afirst = str.indexOf(a1)\n val blast = str.lastIndexOf(b1)\n val bfirst = reverse.indexOf(a1)\n val alast = reverse.lastIndexOf(b1)\n// println(afirst)\n// println(blast)\n// println(bfirst)\n// println(alast)\n\n val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length\n val there = bfirst != -1 && alast != -1 && alast >= bfirst + a1.length\n if (here && there)\n println(\"both\")\n else if (here)\n println(\"forward\")\n else if (there)\n println(\"backward\")\n else\n println(\"fantasy\")\n}"}, {"source_code": "object P8A {\n import io.StdIn._\n\n def main(args:Array[String]) {\n val (s, s1, s2) = (readLine, readLine, readLine)\n val b1 = (s1 + \".*\" + s2).r.findFirstMatchIn(s).nonEmpty\n val (s1r, s2r) = (s1.reverse, s2.reverse)\n val b2 = (s2r + \".*\" + s1r).r.findFirstMatchIn(s).nonEmpty\n println(() match {\n case _ if b1 && b2 => \"both\"\n case _ if b1 => \"forward\"\n case _ if b2 => \"backward\"\n case _ => \"fantasy\"\n })\n }\n}"}, {"source_code": "object P7E {\n import io.StdIn._\n\n def main(args:Array[String]) {\n val (s, s1, s2) = (readLine, readLine, readLine)\n val b1 = (s1 + \".*\" + s2).r.findFirstMatchIn(s).nonEmpty\n val (s1r, s2r) = (s1.reverse, s2.reverse)\n val b2 = (s2r + \".*\" + s1r).r.findFirstMatchIn(s).nonEmpty\n println(() match {\n case _ if b1 && b2 => \"both\"\n case _ if b1 => \"forward\"\n case _ if b2 => \"backward\"\n case _ => \"fantasy\"\n })\n }\n}\n"}, {"source_code": "object P8A {\n import io.StdIn._\n\n def main(args:Array[String]) {\n val (s, s1, s2) = (readLine, readLine, readLine)\n val b1 = (s1 + \".*\" + s2).r.findFirstMatchIn(s).nonEmpty\n val (s1r, s2r) = (s1.reverse, s2.reverse)\n val b2 = (s2r + \".*\" + s1r).r.findFirstMatchIn(s).nonEmpty\n println(() match {\n case _ if b1 && b2 => \"both\"\n case _ if b1 => \"forward\"\n case _ if b2 => \"backward\"\n case _ => \"fantasy\"\n })\n }\n}\n"}, {"source_code": "object A8 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val s = read\n val a = read\n val b = read\n\n val forward = check(s, a, b)\n val backward = check(s.reverse, a, b)\n\n if(forward && backward) {\n println(\"both\")\n } else if(forward) {\n println(\"forward\")\n } else if(backward) {\n println(\"backward\")\n } else {\n println(\"fantasy\")\n }\n }\n\n def check(str: String, d: String, e: String): Boolean = {\n val f = str.indexOf(d)\n if(f != -1) {\n if(str.indexOf(e, f+d.length) != -1) {\n true\n } else {\n false\n }\n } else {\n false\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "object P7E {\n import io.StdIn._\n\n def main(args:Array[String]) {\n val (s, s1, s2) = (readLine, readLine, readLine)\n val b1 = (s1 + \".*\" + s2).r.findFirstMatchIn(s).nonEmpty\n val b2 = (s2 + \".*\" + s1).r.findFirstMatchIn(s).nonEmpty\n println(() match {\n case _ if b1 && b2 => \"both\"\n case _ if b1 => \"forward\"\n case _ if b2 => \"backward\"\n case _ => \"fantasy\"\n })\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val a1 = in.next()\n val b1 = in.next()\n val afirst = str.indexOf(a1)\n val bfirst = str.indexOf(b1)\n val alast = str.lastIndexOf(a1)\n val blast = str.lastIndexOf(b1)\n val here = afirst != -1 && blast != -1 && blast > afirst + a1.length\n val there = alast != -1 && bfirst != -1 && alast > bfirst + b1.length\n if (here && there)\n println(\"both\")\n else if (here)\n println(\"forward\")\n else if (there)\n println(\"backward\")\n else\n println(\"fantasy\")\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val a1 = in.next()\n val b1 = in.next()\n val afirst = str.indexOf(a1)\n val bfirst = str.indexOf(b1)\n val alast = str.lastIndexOf(a1)\n val blast = str.lastIndexOf(b1)\n val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length\n val there = alast != -1 && bfirst != -1 && alast > bfirst + b1.length\n if (here && there)\n println(\"both\")\n else if (here)\n println(\"forward\")\n else if (there)\n println(\"backward\")\n else\n println(\"fantasy\")\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val reverse = str.reverse\n val a1 = in.next()\n val b1 = in.next()\n val afirst = str.indexOf(a1)\n val blast = str.lastIndexOf(b1)\n val bfirst = reverse.length - reverse.indexOf(b1.reverse)\n val alast = reverse.length - reverse.lastIndexOf(a1.reverse)\n// println(bfirst)\n// println(alast)\n// println(bfirst)\n// println(alast)\n\n val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length\n val there = alast != -1 && bfirst != -1 && alast >= bfirst + b1.length\n if (here && there)\n println(\"both\")\n else if (here)\n println(\"forward\")\n else if (there)\n println(\"backward\")\n else\n println(\"fantasy\")\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val reverse = str.reverse\n// println(reverse)\n val a1 = in.next()\n val b1 = in.next()\n val afirst = str.indexOf(a1)\n val blast = str.lastIndexOf(b1)\n val bfirst = reverse.indexOf(a1)\n val alast = reverse.lastIndexOf(b1)\n// println(afirst)\n// println(blast)\n// println(bfirst)\n// println(alast)\n\n val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length\n val there = bfirst != -1 && alast != -1 && alast >= bfirst + b1.length\n if (here && there)\n println(\"both\")\n else if (here)\n println(\"forward\")\n else if (there)\n println(\"backward\")\n else\n println(\"fantasy\")\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val reverse = str.reverse\n println(reverse)\n val a1 = in.next()\n val b1 = in.next()\n val afirst = str.indexOf(a1)\n val blast = str.lastIndexOf(b1)\n val bfirst = reverse.indexOf(b1)\n val alast = reverse.lastIndexOf(a1)\n// println(afirst)\n// println(blast)\n// println(bfirst)\n// println(alast)\n\n val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length\n val there = bfirst != -1 && alast != -1 && alast >= bfirst + b1.length\n if (here && there)\n println(\"both\")\n else if (here)\n println(\"forward\")\n else if (there)\n println(\"backward\")\n else\n println(\"fantasy\")\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n val a1 = in.next()\n val b1 = in.next()\n val afirst = str.indexOf(a1)\n val bfirst = str.indexOf(b1)\n val alast = str.lastIndexOf(a1)\n val blast = str.lastIndexOf(b1)\n val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length\n val there = alast != -1 && bfirst != -1 && alast >= bfirst + b1.length\n if (here && there)\n println(\"both\")\n else if (here)\n println(\"forward\")\n else if (there)\n println(\"backward\")\n else\n println(\"fantasy\")\n}"}, {"source_code": "object A8 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val s = read\n val a = read\n val b = read\n\n def check(str: String, d: String, e: String): Boolean = {\n val f = str.indexOf(d)\n if(f != -1) {\n if(s.indexOf(e, f+a.length) != -1) {\n true\n } else {\n false\n }\n } else {\n false\n }\n }\n\n val forward = check(s, a, b)\n val backward = check(s.reverse, a, b)\n\n if(forward && backward) {\n println(\"both\")\n } else if(forward) {\n println(\"forward\")\n } else if(backward) {\n println(\"backward\")\n } else {\n println(\"fantasy\")\n }\n\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object P8A {\n import io.StdIn._\n\n def main(args:Array[String]) {\n val (s, s1, s2) = (readLine, readLine, readLine)\n val b1 = (s1 + \".*\" + s2).r.findFirstMatchIn(s).nonEmpty\n val b2 = (s2 + \".*\" + s1).r.findFirstMatchIn(s).nonEmpty\n println(() match {\n case _ if b1 && b2 => \"both\"\n case _ if b1 => \"forward\"\n case _ if b2 => \"backward\"\n case _ => \"fantasy\"\n })\n }\n}"}], "src_uid": "c3244e952830643938d51ce14f043d7d"} {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\"\").map(_.toInt)\n\n val ans =\n if (n % 2 == 0) {\n val b = an.zipWithIndex.exists { case (a, i) => (i + 1) % 2 == 0 && a % 2 == 0 }\n if (b) 2 else 1\n } else {\n val r = an.zipWithIndex.exists { case (a, i) => (i + 1) % 2 == 1 && a % 2 == 1 }\n if (r) 1 else 2\n }\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\nobject A {\n def solve(in: Input, out: PrintWriter): Unit = {\n for (_ <- 0 until in.nextInt()) {\n in.nextInt()\n val str = in.nextToken()\n if (str.length % 2 == 0) {\n out.println(if ((0 until str.length).exists(i => i % 2 == 1 && (str(i) - '0') % 2 == 0)) 2 else 1)\n } else {\n out.println(if ((0 until str.length).exists(i => i % 2 == 0 && (str(i) - '0') % 2 == 1)) 1 else 2)\n }\n }\n }\n\n private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(\n (\"4\\n1\\n2\\n1\\n3\\n3\\n102\\n4\\n2069\", \"2\\n1\\n1\\n2\", \"Sample\"),\n (\"1\\n5\\n22222\", \"2\", \"T1\"),\n (\"1\\n5\\n22122\", \"1\", \"T2\"),\n (\"1\\n6\\n111111\", \"1\", \"T3\"),\n (\"1\\n6\\n111112\", \"2\", \"T4\"),\n )\n\n def main(args: Array[String]): Unit = {\n if (args.length == 0) {\n val input = new Input(new InputStreamReader(System.in))\n val output = new PrintWriter(System.out)\n solve(input, output)\n output.close()\n input.close()\n } else {\n for ((in, ans, name) <- makeTests()) {\n val input = new Input(new StringReader(in))\n val output = new StringWriter()\n val pwOutput = new PrintWriter(output)\n val t0 = System.nanoTime()\n solve(input, pwOutput)\n val time = System.nanoTime() - t0\n pwOutput.close()\n output.close()\n val result = output.toString\n if (ans.trim != result.trim) {\n throw new RuntimeException(s\"Test '$name': expected '$ans' found '$result'\")\n } else {\n println(s\"Test '$name' was solved in ${time / 1e9} seconds\")\n }\n }\n }\n }\n\n class Input(stream: Reader) extends Closeable {\n private[this] val reader = new BufferedReader(stream)\n private[this] var tokenizer = new StringTokenizer(reader.readLine())\n\n @tailrec\n final def nextToken(): String = if (tokenizer.hasMoreTokens) tokenizer.nextToken() else {\n tokenizer = new StringTokenizer(reader.readLine())\n nextToken()\n }\n\n def nextInt(): Int = nextToken().toInt\n def nextLong(): Long = nextToken().toLong\n def nextDouble(): Double = nextToken().toDouble\n\n override def close(): Unit = reader.close()\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val n = in.nextInt()\n val digits = in.nextLine().toString.split(\"\").map(_.toInt)\n val hasOdd = digits.indices.exists(i => i % 2 == 0 && digits(i) % 2 == 1)\n val hasEven = digits.indices.exists(i => i % 2 == 1 && digits(i) % 2 == 0)\n\n if ((n % 2 == 0 && !hasEven) || (n % 2 == 1 && hasOdd)) println(\"1\") else println(\"2\")\n\n }\n /*\n inputLines.times {\n val n = in.nextInt()\n val digits = in.nextInt()\n if (n % 2 == 0) {\n val nums = digits.toString.split(\"\").map(_.toInt)\n val hasOddCount = nums.indices.count(i => i % 2 == 1 && nums(i) % 2 == 1)\n if (hasOddCount == (n / 2)) println(\"1\") else println(\"2\")\n } else if (n == 1) {\n if (digits % 2 == 0) {\n println(\"2\")\n } else {\n println(\"1\")\n }\n } else {\n val nums = digits.toString.split(\"\").map(_.toInt)\n val hasOdd = nums.indices.exists(i => i % 2 == 0 && nums(i) % 2 == 1)\n if (hasOdd) println(\"1\") else println(\"2\")\n }\n }*/\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextLineInt(n: Int): ArrayBuffer[Int] = {\n var data = ArrayBuffer[Int]()\n n.times({\n data += nextInt()\n })\n data\n }\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n "}], "negative_code": [], "src_uid": "c9225c915669e183cbd8c20b848d96e5"} {"source_code": "import java.util.Scanner\n\nobject Main {\n val sc = new Scanner(System.in)\n\n def main(args: Array[String]): Unit = {\n val n = sc.nextInt()\n val res = new StringBuilder()\n\n for (i <- 1 to n) {\n if (res.size < 2) {\n res.append(\"a\")\n } else {\n val newChar = if (res.charAt(i - 3) == 'a') 'b' else 'a'\n res.append(newChar)\n }\n }\n\n print(res.toString())\n }\n}", "positive_code": [{"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println((\"aabb\" * (n / 4 + 4)).take(n))\n\n Console.flush\n}\n"}, {"source_code": "object _805B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n val n = read[Int]\n val phrase = Seq(\"aab\", \"baa\", \"bba\", \"abb\").mkString\n val q = n/phrase.length\n val r = n%phrase.length\n val ans = phrase*q + phrase.take(r)\n //require(ans.sliding(3).forall(s => s != s.reverse))\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "fbde86a29f416b3d83bcc63fb3776776"} {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(a00, a01, a10, a11) = readInts(4)\n\n def totalCount(aXX: Int): Int = {\n var x = 0\n while (x * (x - 1) / 2 < aXX) x += 1\n x\n }\n\n val res = Array.ofDim[Char](1000003)\n\n def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {\n\n val x10for1 = total0 - cnt0\n val x01for0 = total1 - cnt1\n\n if (pos == total0 + total1) {\n res.take(pos).mkString\n } else if (a00 < 0 || a01 < 0 || a10 < 0 | a11 < 0) {\n \"\"\n } else if (a01 + a10 - x10for1 == (total0 - cnt0) * (total1 - cnt1 - 1) && x10for1 <= a10) {\n res(pos) = '1'\n build(pos + 1, cnt0, cnt1 + 1, a00, a01, a10 - x10for1, a11 - cnt1)\n } else {\n res(pos) = '0'\n build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01 - x01for0, a10, a11)\n }\n\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val _total0 = totalCount(a00)\n val _total1 = totalCount(a11)\n\n val total0 = if (_total0 > 0) _total0 else if (a01 + a10 > 0) 1 else 0\n val total1 = if (_total1 > 0) _total1 else if (a01 + a10 > 0) 1 else 0\n\n if (total0 * (total0 - 1) / 2 != a00 || total1 * (total1 - 1) / 2 != a11 ||\n total0 * total1 != a01 + a10) println(\"Impossible\")\n else if (a00 + a01 + a10 + a11 == 0) println(\"0\")\n else {\n res(0) = '1'\n val r1 = build(1, 0, 1, a00, a01, a10 - total0, a11)\n res(0) = '0'\n val r2 = build(1, 1, 0, a00, a01 - total1, a10, a11)\n if (r1 != \"\") println(r1)\n else if (r2 != \"\") println(r2)\n else println(\"Impossible\")\n }\n\n Console.flush\n}\n", "positive_code": [{"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(a00, a01, a10, a11) = readInts(4)\n\n def totalCount(aXX: Int, aXY: Int, aYX: Int): Int = {\n var x = 0\n while (x * (x - 1) / 2 < aXX) x += 1\n if (x == 0 && aXY + aYX > 0) 1 else x\n }\n\n val res = Array.ofDim[Char](1000003)\n\n def build(pos: Int, remain0: Int, remain1: Int, a01: Int, a10: Int): String = {\n\n if (remain0 + remain1 == 0) {\n res.take(pos).mkString\n } else if (a01 + a10 - remain0 == remain0 * (remain1 - 1) && remain0 <= a10) {\n res(pos) = '1'\n build(pos + 1, remain0, remain1 - 1, a01, a10 - remain0)\n } else {\n res(pos) = '0'\n build(pos + 1, remain0 - 1, remain1, a01 - remain1, a10)\n }\n\n }\n\n val total0 = totalCount(a00, a01, a10)\n val total1 = totalCount(a11, a10, a01)\n\n if (total0 * (total0 - 1) / 2 != a00 || total1 * (total1 - 1) / 2 != a11 ||\n total0 * total1 != a01 + a10) println(\"Impossible\")\n else if (a00 + a01 + a10 + a11 == 0) println(\"0\")\n else println(build(0, total0, total1, a01, a10))\n}\n"}], "negative_code": [{"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(a00, a01, a10, a11) = readInts(4)\n\n def totalCount(aXX: Int): Int = {\n var x = 0\n while (x * (x - 1) / 2 < aXX) x += 1\n x\n }\n\n val res = Array.ofDim[Char](1000003)\n\n def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {\n\n val x10for1 = total0 - cnt0\n val x01for0 = total1 - cnt1\n\n if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {\n res.take(pos).mkString\n } else if (a00 < 0 || a01 < 0 || a10 < 0 | a11 < 0) {\n \"\"\n } else if (a01 + a10 - x10for1 == (total0 - cnt0) * (total1 - cnt1 - 1) && x10for1 <= a10) {\n res(pos) = '1'\n build(pos + 1, cnt0, cnt1 + 1, a00, a01, a10 - x10for1, a11 - cnt1)\n } else {\n res(pos) = '0'\n build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01 - x01for0, a10, a11)\n }\n\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val _total0 = totalCount(a00)\n val _total1 = totalCount(a11)\n\n val total0 = if (_total0 > 0) _total0 else if (a01 + a10 > 0) 1 else 0\n val total1 = if (_total1 > 0) _total1 else if (a01 + a10 > 0) 1 else 0\n\n if (total0 * (total0 - 1) / 2 != a00 || total1 * (total1 - 1) / 2 != a11 ||\n total0 * total1 != a01 + a10) println(\"Impossible\")\n else {\n res(0) = '1'\n val r1 = build(1, 0, 1, a00, a01, a10 - total0, a11)\n res(0) = '0'\n val r2 = build(1, 1, 0, a00, a01 - total1, a10, a11)\n if (r1 != \"\") println(r1)\n else if (r2 != \"\") println(r2)\n else println(\"Impossible\")\n }\n\n Console.flush\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(a00, a01, a10, a11) = readInts(4)\n\n val res0 = Array.ofDim[Char](1000003)\n\n def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {\n //println(res0.take(pos).mkString, pos, a00, a01, a10, a11)\n if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {\n res0.take(pos).mkString\n } /*else if (a00 + a11 > a01 + a10 && a01 > 0 && a10 > 0) {\n \"\"\n } */else if ((a00.toLong - cnt0) * cnt1 > a10 && cnt1 > 0 && (a00.toLong - cnt0) * cnt1 > 0) {\n \"\"\n } else if ((a11.toLong - cnt1) * cnt0 > a01 && cnt0 > 0 && (a11.toLong - cnt1) * cnt0 > 0) {\n \"\"\n } else if (pos > 32000 || a00 < 0 || a01 < 0 || a10 < 0 || a11 < 0) {\n \"\"\n } else {\n res0(pos) = '0'\n val res = build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01, a10 - cnt1, a11)\n\n if (res != \"\") res\n else {\n res0(pos) = '1'\n build(pos + 1, cnt0, cnt1 + 1, a00, a01 - cnt0, a10, a11 - cnt1)\n }\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n res0(0) = '0'\n val r1 = build(1, 1, 0, a00, a01, a10, a11)\n\n res0(0) = '1'\n val r2 = if (r1 != \"\") r1\n else build(1, 0, 1, a00, a01, a10, a11)\n\n if (r1 == \"0\") println(\"Impossible\")\n else if (r1 != \"\") println(r1)\n else if (r2 != \"\") println(r2)\n else println(\"Impossible\")\n\n Console.flush\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(a00, a01, a10, a11) = readInts(4)\n\n def totalCount(aXX: Int): Int = {\n var x = 0\n while (x * (x - 1) / 2 < aXX) x += 1\n x\n }\n\n val res = Array.ofDim[Char](1000003)\n\n def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {\n\n val x10for1 = total0 - cnt0\n val x01for0 = total1 - cnt1\n\n if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {\n res.take(pos).mkString\n } else if (a00 < 0 || a01 < 0 || a10 < 0 | a11 < 0) {\n \"\"\n } else if (a01 + a10 - x10for1 == (total0 - cnt0) * (total1 - cnt1 - 1) && x10for1 <= a10) {\n res(pos) = '1'\n build(pos + 1, cnt0, cnt1 + 1, a00, a01, a10 - x10for1, a11 - cnt1)\n } else {\n res(pos) = '0'\n build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01 - x01for0, a10, a11)\n }\n\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val total0 = totalCount(a00)\n val total1 = totalCount(a11)\n\n if (total0 * (total0 - 1) / 2 != a00 || total1 * (total1 - 1) / 2 != a11 ||\n total0 * total1 != a01 + a10) println(\"Impossible\")\n else {\n res(0) = '1'\n val r1 = build(1, 0, 1, a00, a01, a10 - total0, a11)\n res(0) = '0'\n val r2 = build(1, 1, 0, a00, a01 - total1, a10, a11)\n if (r1 != \"\") println(r1)\n else if (r2 != \"\") println(r2)\n else println(\"Impossible\")\n }\n\n Console.flush\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(a00, a01, a10, a11) = readInts(4)\n\n def totalCount(aXX: Int): Int = {\n var x = 0\n while (x * (x - 1) / 2 < aXX) x += 1\n x\n }\n\n val res = Array.ofDim[Char](1000003)\n\n def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {\n\n val x10for1 = total0 - cnt0\n val x01for0 = total1 - cnt1\n\n if (pos == total0 + total1) {\n res.take(pos).mkString\n } else if (a00 < 0 || a01 < 0 || a10 < 0 | a11 < 0) {\n \"\"\n } else if (a01 + a10 - x10for1 == (total0 - cnt0) * (total1 - cnt1 - 1) && x10for1 <= a10) {\n res(pos) = '1'\n build(pos + 1, cnt0, cnt1 + 1, a00, a01, a10 - x10for1, a11 - cnt1)\n } else {\n res(pos) = '0'\n build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01 - x01for0, a10, a11)\n }\n\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val _total0 = totalCount(a00)\n val _total1 = totalCount(a11)\n\n val total0 = if (_total0 > 0) _total0 else if (a01 + a10 > 0) 1 else 0\n val total1 = if (_total1 > 0) _total1 else if (a01 + a10 > 0) 1 else 0\n\n if (total0 * (total0 - 1) / 2 != a00 || total1 * (total1 - 1) / 2 != a11 ||\n total0 * total1 != a01 + a10) println(\"Impossible\")\n else {\n res(0) = '1'\n val r1 = build(1, 0, 1, a00, a01, a10 - total0, a11)\n res(0) = '0'\n val r2 = build(1, 1, 0, a00, a01 - total1, a10, a11)\n if (r1 != \"\") println(r1)\n else if (r2 != \"\") println(r2)\n else println(\"Impossible\")\n }\n\n Console.flush\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(a00, a01, a10, a11) = readInts(4)\n\n val res0 = Array.ofDim[Char](1000003)\n\n def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {\n //println(res0.take(pos).mkString, pos, a00, a01, a10, a11)\n if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {\n res0.take(pos).mkString\n } /*else if (a00 + a11 > a01 + a10 && a01 > 0 && a10 > 0) {\n \"\"\n } */else if ((a00.toLong - cnt0) * cnt1 > a10 && cnt1 > 0 && (a00.toLong - cnt0) * cnt1 > 0) {\n \"\"\n } else if ((a11.toLong - cnt1) * cnt0 > a01 && cnt0 > 0 && (a11.toLong - cnt1) * cnt0 > 0) {\n \"\"\n } else if (pos > 32000 || a00 < 0 || a01 < 0 || a10 < 0 || a11 < 0) {\n \"\"\n } else {\n res0(pos) = '0'\n val res = build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01, a10 - cnt1, a11)\n\n if (res != \"\") res\n else {\n res0(pos) = '1'\n build(pos + 1, cnt0, cnt1 + 1, a00, a01 - cnt0, a10, a11 - cnt1)\n }\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n res0(0) = '0'\n val r1 = build(1, 1, 0, a00, a01, a10, a11)\n\n res0(0) = '1'\n val r2 = if (r1 != \"\") r1\n else build(1, 0, 1, a00, a01, a10, a11)\n\n if (r1 != \"\") println(r1)\n else if (r2 != \"\") println(r2)\n else println(\"Impossible\")\n\n Console.flush\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(a00, a01, a10, a11) = readInts(4)\n\n val res0 = Array.ofDim[Char](1000003)\n\n def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {\n //println(res0.take(pos).mkString, pos, a00, a01, a10, a11)\n if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {\n res0.take(pos).mkString\n } /*else if (a00 + a11 > a01 + a10 && a01 > 0 && a10 > 0) {\n \"\"\n } */else if ((a00.toLong - cnt0) * cnt1 > a10 && cnt1 > 0 && (a00.toLong - cnt0) * cnt1 > 0) {\n \"\"\n } else if ((a11.toLong - cnt1) * cnt0 > a01 && cnt0 > 0 && (a11.toLong - cnt1) * cnt0 > 0) {\n \"\"\n } else if (pos > 32000 || a00 < 0 || a01 < 0 || a10 < 0 || a11 < 0) {\n \"\"\n } else {\n res0(pos) = '0'\n val res = build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01, a10 - cnt1, a11)\n\n if (res != \"\") res\n else {\n res0(pos) = '1'\n build(pos + 1, cnt0, cnt1 + 1, a00, a01 - cnt0, a10, a11 - cnt1)\n }\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n res0(0) = '0'\n val r1 = build(1, 1, 0, a00, a01, a10, a11)\n\n res0(0) = '1'\n val r2 = if (r1 != \"\") r1\n else build(1, 0, 1, a00, a01, a10, a11)\n\n if (r1 == \"0\") println(\"\")\n else if (r1 != \"\") println(r1)\n else if (r2 != \"\") println(r2)\n else println(\"Impossible\")\n\n Console.flush\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(a00, a01, a10, a11) = readInts(4)\n\n val res0 = Array.ofDim[Char](1000003)\n\n def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {\n //println(res0.take(pos).mkString, pos, a00, a01, a10, a11)\n if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {\n res0.take(pos).mkString\n } /*else if (a00 + a11 > a01 + a10 && a01 > 0 && a10 > 0) {\n \"\"\n } */else if ((a00.toLong - cnt0) * cnt1 > a10 && cnt1 > 0) {\n \"\"\n } else if ((a11.toLong - cnt1) * cnt0 > a01 && cnt0 > 0) {\n \"\"\n } else if (pos > 32000 || a00 < 0 || a01 < 0 || a10 < 0 || a11 < 0) {\n \"\"\n } else {\n res0(pos) = '0'\n val res = build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01, a10 - cnt1, a11)\n\n if (res != \"\") res\n else {\n res0(pos) = '1'\n build(pos + 1, cnt0, cnt1 + 1, a00, a01 - cnt0, a10, a11 - cnt1)\n }\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n res0(0) = '0'\n val r1 = build(1, 1, 0, a00, a01, a10, a11)\n\n res0(0) = '1'\n val r2 = if (r1 != \"\") r1\n else build(1, 0, 1, a00, a01, a10, a11)\n\n if (r1 == \"0\") println(\"\")\n else if (r1 != \"\") println(r1)\n else if (r2 != \"\") println(r2)\n else println(\"Impossible\")\n\n Console.flush\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(a00, a01, a10, a11) = readInts(4)\n\n val res0 = Array.ofDim[Char](1000003)\n\n def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {\n //println(res0.take(pos).mkString, pos, a00, a01, a10, a11)\n if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {\n res0.take(pos).mkString\n } else if (a00 + a11 > a01 + a10 && a01 > 0 && a10 > 0) {\n \"\"\n } else if ((a00.toLong - cnt0) * cnt1 > a10 && cnt1 > 0) {\n \"\"\n } else if ((a11.toLong - cnt1) * cnt0 > a01 && cnt0 > 0) {\n \"\"\n } else if (pos > 32000 || a00 < 0 || a01 < 0 || a10 < 0 || a11 < 0) {\n \"\"\n } else {\n res0(pos) = '0'\n val res = build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01, a10 - cnt1, a11)\n\n if (res != \"\") res\n else {\n res0(pos) = '1'\n build(pos + 1, cnt0, cnt1 + 1, a00, a01 - cnt0, a10, a11 - cnt1)\n }\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n res0(0) = '0'\n val r1 = build(1, 1, 0, a00, a01, a10, a11)\n\n res0(0) = '1'\n val r2 = if (r1 != \"\") r1\n else build(1, 0, 1, a00, a01, a10, a11)\n\n if (r1 == \"0\") println(\"\")\n else if (r1 != \"\") println(r1)\n else if (r2 != \"\") println(r2)\n else println(\"Impossible\")\n\n Console.flush\n}\n"}], "src_uid": "6893987b310c41efb269b63e865355d8"} {"source_code": "// CodeForces 245 C\n\nobject IgraMonet extends App {\n val n = Console.readInt\n val s = Console.readLine\n val a:Array[Int] = (s split \" \") map (_.toInt)\n // println(\"n=\" + n +\"s:\" + s + \"a:\" + a)\n \n def countMoves(lst:Int, cnt:Int):Int = \n if (lst < 3) cnt + math.max(a(0), 0)\n else {\n val ad = math.max(0, math.max(a(lst-1), a(lst-2)))\n a(lst-1) -= ad\n a(lst - 2) -= ad\n a((lst-3)/2) -= ad\n countMoves(lst-2, cnt+ad)\n } \n \n if (n < 3 || (n % 2 == 0)) println(-1)\n else println(countMoves(n, 0))\n}", "positive_code": [{"source_code": "object Main extends App{\n val n = readInt()\n val xs = Array(0) ++ readLine().split(\" \").map(_.toInt)\n var ans = 0\n for (i <- (1 to n).reverse){\n if (xs(i) > 0){\n if (i > 1 && i % 2 == 1){\n xs(i-1) -= xs(i)\n xs((i-1)/2) -= xs(i)\n ans += xs(i)\n }\n else if (i > 1 && i % 2 == 0){\n xs(i/2) -= xs(i)\n ans += xs(i)\n }\n else {\n ans += xs(i)\n }\n }\n }\n if (n < 3 || n % 2 == 0)\n ans = -1\n println(ans)\n}\n"}], "negative_code": [{"source_code": "object Main extends App{\n val n = readInt()\n val xs = Array(0) ++ readLine().split(\" \").map(_.toInt)\n var ans = 0\n for (i <- (1 to n).reverse){\n if (xs(i) > 0){\n if (i > 1 && i % 2 == 1){\n xs(i-1) -= xs(i)\n xs((i-1)/2) -= xs(i)\n ans += xs(i)\n }\n else if (i > 1 && i % 2 == 0){\n xs(i/2) -= xs(i)\n ans += xs(i)\n }\n else {\n ans += xs(i)\n }\n }\n }\n if (n < 3)\n ans = -1\n println(ans)\n}\n"}, {"source_code": "// CodeForces 245 C\n\nobject IgraMonet extends App {\n val n = Console.readInt\n val s = Console.readLine\n val a:Array[Int] = (s split \" \") map (_.toInt)\n // println(\"n=\" + n +\"s:\" + s + \"a:\" + a)\n \n def countMoves(lst:Int, cnt:Int):Int = \n if (lst < 3) cnt + a(0)\n else {\n val ad = math.max(0, math.max(a(lst-1), a(lst-2)))\n a(lst-1) -= ad\n a(lst - 2) -= ad\n a((lst-3)/2) -= ad\n countMoves(lst-2, cnt+ad)\n } \n \n if (n < 3 || (n % 2 == 0)) println(-1)\n else println(countMoves(n, 0))\n}"}, {"source_code": "// CodeForces 245 C\n\nobject IgraMonet extends App {\n val n = Console.readInt\n val s = Console.readLine\n val a:Array[Int] = (s split \" \") map (_.toInt)\n // println(\"n=\" + n +\"s:\" + s + \"a:\" + a)\n \n def countMoves(lst:Int, cnt:Int):Int = \n if (lst < 3) cnt \n else {\n val ad = math.max(0, math.max(a(lst-1), a(lst-2)))\n a(lst-1) -= ad\n a(lst - 2) -= ad\n a((lst-3)/2) -= ad\n countMoves(lst-2, cnt+ad)\n } \n \n if (n < 3 || (n % 2 == 0)) println(-1)\n else println(countMoves(n, 0))\n}"}], "src_uid": "42bfc8dbf45f643782bf42be432cb57c"} {"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n\n final class BIT(src: Array[Long]) {\n\n private val t = Array.fill(src.length + 1) { 0L }\n\n for (i <- 1 until src.length) update(i, src(i))\n\n def query(r: Int, acc: Long = 0): Long =\n if (r <= 0) acc else query((r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(l: Int, r: Int): Long = query(r) - query(l - 1)\n\n def update(i: Int, delta: Long): Unit = {\n if (i < t.length) {\n t(i) += delta\n update(i + (i & -i), delta)\n }\n }\n\n def binSearch(goal: Long): Int = {\n var sum = 0L\n var idx = 0\n var bitMask = Integer.highestOneBit(t.length)\n while (bitMask > 0) {\n val newIdx = idx + bitMask\n if (newIdx < t.length && sum + t(newIdx) <= goal) {\n idx = newIdx\n sum += t(idx)\n }\n bitMask >>>= 1\n }\n idx + 1\n }\n\n }\n\n val Array(n) = readInts(1)\n val ss = readLongs(n)\n\n val bit = new BIT((0L to n).toArray)\n\n val as = Array.ofDim[Long](n)\n\n for (i <- ss.indices.reverse) {\n val a = bit.binSearch(ss(i))\n as(i) = a\n bit.update(a, -a)\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(as.mkString(\" \"))\n\n Console.flush\n}", "positive_code": [{"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n\n final class BIT(src: Array[Long]) {\n\n private val t = Array.fill(src.length + 1) { 0L }\n\n for (i <- src.indices) update(i + 1, src(i))\n\n def query(r: Int, acc: Long = 0): Long =\n if (r <= 0) acc else query(r - (r & -r), acc + t(r))\n\n def rangeQuery(l: Int, r: Int): Long = query(r) - query(l - 1)\n\n def update(i: Int, delta: Long): Unit = {\n if (i < t.length) {\n t(i) += delta\n update(i + (i & -i), delta)\n }\n }\n\n def binSearch(goal: Long): Int = {\n var sum = 0L\n var idx = 0\n var bitMask = Integer.highestOneBit(t.length)\n while (bitMask > 0) {\n val newIdx = idx + bitMask\n if (newIdx < t.length && sum + t(newIdx) <= goal) {\n idx = newIdx\n sum += t(idx)\n }\n bitMask >>>= 1\n }\n idx + 1\n }\n\n }\n\n val Array(n) = readInts(1)\n val ss = readLongs(n)\n\n val bit = new BIT(Array.tabulate(n)(_ + 1))\n\n val as = Array.ofDim[Long](n)\n\n for (i <- ss.indices.reverse) {\n val a = bit.binSearch(ss(i))\n as(i) = a\n bit.update(a, -a)\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(as.mkString(\" \"))\n\n Console.flush\n}"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val S = nal(N)\n val ans = Array.ofDim[Int](N)\n val bit = new BIT(N + 1)\n REP(N, 1) { i =>\n bit.add(i, i)\n }\n\n REP_r(N) { i =>\n val a = bit.lowerBound(S(i) + 1)\n bit.add(a, -a)\n ans(i) = a\n }\n debug(ans)\n\n out.println(ans.mkString(\" \"))\n }\n\n class BIT(n: Int, zero: Long)(f: (Long, Long) => Long) {\n def this(n: Int) = this(n, 0)(_ + _)\n\n private val N = {\n val a = Integer.highestOneBit(n)\n if (a == n) a else a << 1\n }\n private val bit = if (zero != 0) Array.fill[Long](N + 1)(zero) else Array.ofDim[Long](N + 1)\n\n /**\n * 1 index\n * addとindex違うよ\n * cumsumなんかといっしょ\n */\n def sum(i: Int): Long = {\n assert(i <= n)\n var x = i\n var s: Long = zero\n while(x > 0) {\n s = f(s, bit(x))\n x -= x & -x\n }\n s\n }\n\n /**\n * 0 index\n */\n def add(i: Int, a: Long): Unit = {\n assert(i < n)\n var x = i + 1\n while(x <= N) {\n bit(x) = f(bit(x), a)\n x += x & -x\n }\n }\n\n def sumAll: Long = sum(n)\n\n // A がLongとかじゃない場合はこれらを実装しないと下の奴らが使えない\n private def sub(a: Long, b: Long) = a - b\n private def lt(a: Long, b: Long) = a < b\n\n /**\n * [l, r)\n */\n def query(l: Int, r: Int): Long = {\n assert(r > l)\n sub(sum(r), sum(l))\n }\n\n def lowerBound(W: Long): Int = {\n var k = N\n var x = 0\n var w = W\n while(k > 0) {\n if (x + k <= N && lt(bit(x + k), w)) {\n w = sub(w, bit(x + k))\n x += k\n }\n k /= 2\n }\n math.min(n, x)\n }\n }\n}"}, {"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n class BIT(src: Array[Long]) {\n\n val t = Array.fill(src.length) { 0L }\n\n for (i <- src.indices) update(i, src(i))\n\n def query(r: Int, acc: Long = 0): Long =\n if (r < 0) acc else query((r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(l: Int, r: Int) = query(r) - query(l - 1)\n\n def update(i: Int, delta: Long): Unit =\n if (i < t.length) {\n t(i) += delta\n update(i | (i + 1), delta)\n }\n\n }\n\n val Array(n) = readInts(1)\n val ss = readLongs(n)\n\n val bit = new BIT((0L to n).toArray)\n\n val as = Array.ofDim[Long](n)\n\n for (i <- ss.indices.reverse) {\n\n val s = ss(i)\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (bit.query(mid.toInt) > s) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n val a = binSearch(0, n)\n as(i) = a\n bit.update(a.toInt, -a)\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(as.mkString(\" \"))\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n\n final class BIT(src: Array[Long]) {\n\n private val t = Array.fill(src.length) { 0L }\n\n for (i <- src.indices) update(i, src(i))\n\n def query(r: Int, acc: Long = 0): Long =\n if (r <= 0) acc else query((r & (r + 1)) - 1, acc + t(r))\n\n def rangeQuery(l: Int, r: Int): Long = query(r) - query(l - 1)\n\n def update(i: Int, delta: Long): Unit = {\n if (i < t.length) {\n t(i) += delta\n update(i | (i + 1), delta)\n }\n }\n\n def binSearch(goal: Long): Int = {\n var sum = 0L\n var idx = 0\n var bitMask = Integer.highestOneBit(t.length - 1)\n while (bitMask > 0) {\n val newIdx = idx + bitMask\n if (newIdx <= t.length && sum + t(newIdx - 1) <= goal) {\n idx = newIdx\n sum += t(idx)\n }\n bitMask >>>= 1\n }\n idx\n }\n\n }\n\n val Array(n) = readInts(1)\n val ss = readLongs(n)\n\n val bit = new BIT((0L to n).toArray)\n\n val as = Array.ofDim[Long](n)\n\n for (i <- ss.indices.reverse) {\n val a = bit.binSearch(ss(i))\n as(i) = a\n bit.update(a, -a)\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(as.mkString(\" \"))\n\n Console.flush\n}\n"}], "src_uid": "c994ae45ac126c3ee16e77617b4554fc"} {"source_code": "//package codeforces.contests._1374\n\n/*\nhttps://codeforces.com/contest/1374/problem/D\n */\nobject ZeroRemainderArray {\n def main(args: Array[String]): Unit = {\n println {\n {\n for (_ <- 1 to io.StdIn.readInt()) yield {\n val Array(_, k) = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val arr = io.StdIn.readLine.split(\" \").map { ai =>\n val r = ai.toLong % k\n if (r == 0) 0 else k - r\n }.groupBy(identity) // minimum amount need to make divisible by k\n\n\n arr.foldLeft(0L) { case (acc, (i, is)) =>\n val c = is.length\n if (i == 0) acc else acc max (i + (c - 1) * k + 1)\n }\n }\n }.mkString(\"\\n\")\n }\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CF653A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CF653A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val n = ni()\n val k = ni()\n\n val a = na(n).filter(p => p % k != 0)\n if(a.length == 0) {\n out.println(\"0\")\n } else {\n val r = a.map(f => k - f % k).groupBy(f => f).map(f => f._1 -> f._2.length)\n val v = r.values.max\n val u = r.filter(p => p._2 == v).keys.max\n\n out.println((v-1)*k.toLong + u + 1)\n }\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1374\n\n/*\nhttps://codeforces.com/contest/1374/problem/D\n */\nobject ZeroRemainderArray {\n def main(args: Array[String]): Unit = {\n println {\n {\n for (_ <- 1 to io.StdIn.readInt()) yield {\n val Array(_, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n val queue = collection.mutable.PriorityQueue.empty[Int](Ordering.Int.reverse)\n\n io.StdIn.readLine.split(\" \").foreach { ai =>\n val r = ai.toInt % k\n queue.enqueue(if (r == 0) 0 else k - r)\n } // minimum amount need to make divisible by k\n\n @scala.annotation.tailrec\n def loop(x: Long = 0): Long = {\n if (queue.isEmpty) x\n else {\n val ai = queue.dequeue()\n\n if (ai == 0) loop(x)\n else if (x > ai) {\n queue.enqueue(ai + k)\n loop(x)\n } else // (x < ai)\n loop(ai + 1)\n }\n }\n\n loop()\n }\n }\n }\n }\n}\n"}], "src_uid": "a8b4c115bedda3847e7c2e3620e3e19b"} {"source_code": "import sun.invoke.empty.Empty\n\nobject B1253 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var tests = 1 // readInt\n while (tests > 0) {\n val Array(n) = readInts(1)\n val a = readInts(n)\n val set = cu.HashSet.empty[Int]\n var map = cu.Map.empty[Int, Boolean] //count for day\n var res = 0\n var resPos = ArrayBuffer.empty[Int]\n var break = false\n var i = 0\n var last = 0\n while (i < n && !break) {\n if (a(i) < 0) {\n if (!set.contains(-a(i)))\n break = true\n else {\n set.remove(-a(i))\n map.put(-a(i), true)\n if (set.isEmpty) {\n resPos.append(i - last + 1)\n last = i + 1\n map = cu.Map.empty[Int, Boolean]\n res += 1\n }\n }\n } else {\n if (set.contains(a(i)) || map.contains(a(i))) {\n break = true\n } else {\n set.add(a(i))\n }\n }\n i += 1\n }\n if (break || set.nonEmpty) {\n out.println(-1)\n } else {\n out.println(res)\n out.println(resPos.mkString(\" \"))\n }\n tests -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject B {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n = nextInt\n val as = nextInts(n)\n val resBuilder = new mutable.ArrayBuilder.ofInt\n\n var count = 0\n val inside, entered = mutable.HashSet.empty[Int]\n var bad = false\n for (a <- as) {\n count += 1\n if (a < 0) {\n if (!inside.remove(-a)) bad = true\n } else {\n if (!inside.add(a) || entered(a)) bad = true\n entered.add(a)\n }\n if (inside.isEmpty) {\n resBuilder += count\n entered.clear()\n count = 0\n }\n }\n\n if (inside.nonEmpty || bad) println(-1)\n else {\n val res = resBuilder.result()\n out.println(res.length)\n out.println(res.mkString(\" \"))\n }\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "17f73ae0347b551fb5e287322785c8a4"} {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val t = readLine\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val pref = new StringBuilder\n var ok = false\n\n for (i <- 0 until t.length) {\n if (t(i) != 'a') pref += t(i)\n if (i + pref.length + 1 == t.length) {\n val s = pref.result()\n if (s == t.drop(i + 1)) {\n ok = true\n println(t.take(i + 1))\n }\n }\n }\n\n if (!ok) println(\":(\")\n\n Console.flush\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Codeforces1146B {\n\n val noAnswer = \":(\"\n\n def removeA(string: String): String = {\n val stringBuilder = new StringBuilder()\n for (char <- string)\n if (char != 'a') stringBuilder.append(char)\n\n stringBuilder.toString()\n }\n\n def isTwoEqual(string: String): Boolean = {\n if (string.length % 2 != 0) return false\n val nextStart = string.length / 2\n for (i <- 0 until nextStart) {\n if (string(i) != string(nextStart + i)) return false\n }\n true\n }\n\n def getOriginalString(t: String): String = {\n val aRemoved = removeA(t)\n if (isTwoEqual(aRemoved)) {\n val secondPart = aRemoved.substring(aRemoved.length / 2)\n if (t.endsWith(secondPart))\n return t.substring(0, t.length - secondPart.length)\n }\n noAnswer\n }\n\n def main(args: Array[String]): Unit = {\n val t = StdIn.readLine().trim\n val s = getOriginalString(t)\n println(s)\n }\n}\n"}], "negative_code": [], "src_uid": "b5bcb6d78daacd56362fd76e35b903ac"} {"source_code": "object Main {\n \n def main(args: Array[String]): Unit = {\n import scala.io.StdIn.readLine\n import scala.io.StdIn.readInt\n\n var T: Int = readInt\n for(t <- 0 until T) {\n var Array(n, m, k) = readLine.split(\" \").map(_.toInt)\n var A = readLine.split(\" \").map(_.toInt)\n var B = readLine.split(\" \").map(_.toInt)\n \n if(A.contains(n)) println(\"YES\")\n else println(\"NO\")\n }\n }\n \n}", "positive_code": [{"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n for (_ <- 1 to nextInt) {\n val n, k1, k2 = nextInt\n val as = nextInts(k1)\n val bs = nextInts(k2)\n val res = if (as.max > bs.max) \"YES\" else \"NO\"\n\n out.println(res)\n }\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "3ef23f114be223255bd10131b2375b86"} {"source_code": "object _1196B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val q = io.read[Int]\n (1 to q) foreach { _ =>\n val n, k = io.read[Int]\n val as = io.read[Vector, Int](n)\n val odds = as.indicesWhere(_ % 2 == 1)\n val diff = odds.size - k\n if (diff >= 0 && diff%2 == 0) {\n val ans = odds.take(k-1).map(_ + 1) :+ n\n io.writeLine(\"YES\").writeAll(ans).writeLine()\n } else {\n io.writeLine(\"NO\")\n }\n }\n io\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object Main {\n import scala.util.control.Breaks.{breakable,break}\n import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue}\n import java.io._\n\n val in = new InputReader(System.in)\n val pw = new PrintWriter(System.out)\n\n val no = \"NO\"\n val yes = \"YES\"\n\n def main (args: Array[String]){\n val q = in.next().toInt\n for (_ <- 1 to q) {\n val n, k = in.next().toInt\n val a = new Array[Int](n+1)\n for (i <- 1 to n)\n a(i) = in.next().toInt\n\n val odds = a.count(_ % 2 == 1)\n\n if (odds >= k && odds % 2 == k % 2) {\n var ind = 1\n var cnt = 0\n var ans: List[Int] = Nil\n while (cnt < k-1) {\n if (a(ind) % 2 == 1) {\n ans = ind :: ans\n cnt += 1\n }\n\n ind += 1\n }\n\n pw.println(yes)\n pw.println((n :: ans).reverse.mkString(\" \"))\n }\n else\n pw.println(no)\n }\n\n pw.flush()\n }\n}\n\nimport java.io._\nclass InputReader(stream: InputStream) {\n import java.util.StringTokenizer\n\n private val reader = new BufferedReader(new InputStreamReader(stream))\n private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())\n def next(): String = {\n while (!tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine())\n }\n tokenizer.nextToken()\n }\n}\n"}], "negative_code": [{"source_code": "object _1196B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val q = io.read[Int]\n (1 to q) foreach { _ =>\n val n, k = io.read[Int]\n val as = io.read[Vector, Int](n)\n val odds = as.indicesWhere(_ % 2 == 1)\n val diff = odds.size - k\n if (diff >= 0 && diff%2 == 0) {\n val ans = odds.dropRight(1).map(_ + 1) :+ n\n io.writeLine(\"YES\").writeAll(ans).writeLine()\n } else {\n io.writeLine(\"NO\")\n }\n }\n io\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _1196B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val q = io.read[Int]\n (1 to q) foreach { _ =>\n val n, k = io.read[Int]\n val as = io.read[Vector, Int](n)\n val odds = as.indicesWhere(_ % 2 == 1)\n val diff = odds.size - k\n if (diff >= 0 && diff%2 == 0) {\n io.writeLine(\"YES\").writeAll(odds.map(_ + 1)).writeLine()\n } else {\n io.writeLine(\"NO\")\n }\n }\n io\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "7f5269f3357827b9d8682d70befd3de1"} {"source_code": "import scala.io._\nimport java.util._\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n val d = scanner.nextInt()\n\n val a = 0 until d map (x => scanner.next())\n\n def win(result: String): Boolean = result contains \"0\"\n def answer(i: Int, c: Int, best: Int): Int =\n if (i == d) best\n else {\n val curr = if (win(a(i))) c + 1 else 0\n answer(i + 1, curr, curr max best)\n }\n\n println(answer(0, 0, 0))\n }\n}", "positive_code": [{"source_code": "object A {\n def main(args: Array[String]) = {\n val Seq(n, d): Seq[Int] = readInts()\n var cur = 0\n var r = 0\n for (_i <- 1 to d) {\n val present = digits(readLine())\n if (present.exists(_ == 0)) {\n cur += 1\n if (cur > r) {\n r = cur\n }\n } else {\n cur = 0\n }\n }\n println(r)\n }\n\n def readLine() = io.StdIn.readLine()\n def readInts() = readLine().split(' ').map(_.toInt)\n\n def digits(s: String) = s.map(_.toString.toInt)\n}\n\n"}, {"source_code": "import scala.io.StdIn\n\n/**\n * @author Denis Savin (pilgrimm333@gmail.com)\n */\nobject Main {\n\n def main(args: Array[String]) {\n val x = readLine().split(\" \").map(_.toInt)\n val n = x(0)\n val d = x(1)\n var counter = 0\n var strike = 0\n for (a <- 1 to d) {\n if (n == StdIn.readLine().count('1'==)) {\n strike = Math.max(counter, strike)\n counter = 0\n } else\n counter += 1\n }\n println(Math.max(counter, strike))\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n val nd = readLine.split(\" \").map(_.toInt)\n val ds = (0 until nd(1)).map(_=>readLine.map{\n case '0' => 0\n case '1' => 1\n }.product).mkString\n val l = ds.split('1').map(_.length)\n if (l.isEmpty) println(0) else println(l.max)\n }\n}"}, {"source_code": "import scala.io._\nimport java.util.Scanner\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n val d = scanner.nextInt()\n\n val ret = 0.until(d).map(x => scanner.next()).map(result => if (result contains \"0\") 1 else 0).foldLeft((0, 0))(\n (s, c) =>\n { \n val curr = if (c == 0) 0 else s._2 + 1\n (s._1 max curr, curr)\n }\n )\n\n println(ret._1)\n }\n}"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val Array(n, d) = lines.next().split(' ').map(_.toInt)\n println((1 to d).foldLeft((0, 0)) {\n case ((soFar, max), _) =>\n val nSoFar = if (lines.next().contains('0')) soFar + 1 else 0\n (nSoFar, Math.max(max, nSoFar))\n }._2)\n}\n"}, {"source_code": "object A688 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, d) = readInts(2)\n val input = Array.fill(d)(read).map(_.count(_=='1'))\n var res = 0\n var curr = 0\n for(i <- input.indices) {\n if(input(i) != n) {\n curr += 1\n res = math.max(res, curr)\n } else {\n curr = 0\n }\n }\n println(res)\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject cf_688A {\n def main(args: Array[String]) {\n val (numOp :Int, numDays: Int, shedule: Array[String]) =\n if (args.size > 0) {\n val input = Source.fromFile(\"input\" + args(0)).getLines().toBuffer\n val (n, m) = extractNums(input(0))\n// println(input.length)\n input -= input(0)\n// println(input.length)\n (n, m, input.toArray)\n } else {\n val (n, m) = extractNums(readLine())\n (n, m, (for (i <- 0 until m) yield readLine()).toArray)\n }\n// println(numOp + \" \" + numDays)\n var maxN, cur = 0\n for (k <- shedule)\n if (k.contains(\"0\")) cur += 1\n else {\n maxN = Math.max(maxN, cur)\n cur = 0\n }\n println(Math.max(maxN, cur))\n }\n\n def extractNums(input :String): (Int, Int) = {\n input.split(\" \").map(_.toInt).toList match {\n case List(x,y) => (x,y)\n }\n }\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _688A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val n, d = read[Int]\n val data = read[Vector, String](d).map(_.forall(_ == '1').to[Int]).mkString\n write(data.split(\"1\").map(_.length).toSeq.whenNonEmpty(_.max) getOrElse 0)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toYesNo = if(x) \"yes\" else \"no\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def bitCount: Int = java.lang.Integer.bitCount(x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeLine(obj: Any*): this.type = {\n if (obj.isEmpty) printer.println() else obj foreach printer.println\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Main extends App {\n override def main(args: Array[String]) {\n val cin = new java.util.Scanner(System.in)\n val m = cin.nextInt()\n val n = cin.nextInt() \n val tmp = cin.nextLine()\n var ans = 0\n def solve(n: Int, cons: Int) {\n ans = Math.max(ans, cons)\n if (n != 0) {\n val str = cin.nextLine()\n if (str.contains(\"0\")) {\n solve(n - 1, cons + 1)\n } else {\n solve(n - 1, 0)\n }\n }\n }\n solve(n, 0)\n println(ans)\n }\n}"}, {"source_code": "// http://codeforces.com/problemset/problem/688/A\n\nimport java.util.Scanner\n\nobject MainApp {\n def readDays(d: Int, scanner: Scanner): List[String] =\n d match {\n case 0 => Nil\n case d => {\n val value = scanner.nextLine()\n value :: readDays(d - 1, scanner)\n }\n }\n\n def isWin(day: String): Boolean =\n day exists (_ == '0')\n\n def pack(xs: List[Boolean]): List[List[Boolean]] =\n xs match {\n case Nil => List(Nil)\n case x :: xs => pack(xs) match {\n case Nil => List(List(x))\n case y :: ys => y match {\n case Nil => List(x) :: ys\n case z :: zs if (x == z) => (x :: y) :: ys\n case z :: zs => List(x) :: y :: ys\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n val d = scanner.nextInt()\n scanner.nextLine()\n val days = readDays(d, scanner)\n val wins = pack(days map isWin) filter (_.head) map (_.length)\n if (wins.isEmpty)\n println(0)\n else\n println(wins.max)\n }\n}\n"}, {"source_code": "object problem_A{\n def main(args: Array[String]) {\n val scanner = new java.util.Scanner(System.in)\n val n = scanner.nextInt()\n val d = scanner.nextInt()\n\n val hz = scanner.nextLine()\n\n val arr = new Array[Boolean](d)\n 0 to d-1 foreach { arr(_) = scanner.nextLine().contains('0') }\n\n def helper(max: Int, cur: Int, list: List[Boolean]): Int = {\n if (list.isEmpty) max\n else if (list.head) helper(Math.max(max,cur+1), cur+1, list.tail)\n else helper(if (cur == 0) max else Math.max(max,cur), 0, list.tail)\n }\n\n println(helper(0,0,arr.toList))\n\n }\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn\nimport scala.util._\n\n/**\n * @author Denis Savin (pilgrimm333@gmail.com)\n */\nobject Main {\n\n def main(args: Array[String]) {\n val x = readLine().split(\" \").map(_.toInt)\n val n = x(0)\n val d = x(1)\n var counter = 0\n var strike = 0\n for (a <- 1 to d) {\n if (n == StdIn.readLine().count(_ == \"1\")) {\n strike = Math.max(counter, strike)\n counter = 0\n } else\n counter += 1\n }\n if (strike == 0)\n println(counter)\n else\n println(strike)\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject cf_688A {\n def main(args: Array[String]) {\n val (numOp :Int, numDays: Int, shedule: Array[String]) =\n if (args.size > 0) {\n val input = Source.fromFile(\"input\" + args(0)).getLines().toBuffer\n val (n, m) = extractNums(input(0))\n// println(input.length)\n input -= input(0)\n// println(input.length)\n (n, m, input.toArray)\n } else {\n val (n, m) = extractNums(readLine())\n (n, m, (for (i <- 0 until m) yield readLine()).toArray)\n }\n// println(numOp + \" \" + numDays)\n var maxN, cur = 0\n for (k <- shedule)\n if (k.contains(\"0\")) cur += 1\n else {\n maxN = Math.max(maxN, cur)\n cur = 0\n }\n println(maxN)\n }\n\n def extractNums(input :String): (Int, Int) = {\n input.split(\" \").map(_.toInt).toList match {\n case List(x,y) => (x,y)\n }\n }\n}\n"}], "src_uid": "a6ee741df426fd2d06fdfda4ca369397"} {"source_code": "import scala.io.StdIn._\n\nobject Main2 extends App {\n val testCaseNumber = readInt()\n 0.until(testCaseNumber).map{ _ =>\n val numbers = readLine().split(\" \").map(_.toInt)\n val a = numbers.head\n val b = numbers.last\n (b - a%b) % b\n }.foreach(println(_))\n}\n", "positive_code": [{"source_code": "\nimport scala.io.StdIn\n\nobject Hi {\n\tdef main(args: Array[String]): Unit = {\n\t\tval n = scala.io.StdIn.readInt()\n\t\tfor (i <- 1 to n){\n\t\t\tval input = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\t\t\tval (a, b) = (input(0), input(1))\n\t\t\tval div = a % b\n\t\t\tif (div == 0) {\n\t\t\t\tprintln(0)\n\t\t\t} else {\n\t\t\t\tprintln(s\"${b - div}\") \n\t\t\t}\n\t\t}\n\t}\n}"}, {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n val t = nextInt\n\n for (_ <- 1 to t) {\n val a, b = nextInt\n val c = if (a % b == 0) 0 else b - a % b\n out.println(c)\n }\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n (1 to t).foreach{ _ =>\n val x = in.nextInt()\n val y = in.nextInt()\n val z = x % y\n if(z==0){\n out.println(0)\n }else{\n out.println(y-z)\n }\n }\n\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "negative_code": [], "src_uid": "d9fd10700cb122b148202a664e7f7689"} {"source_code": "object A extends App {\n case class Size(n: Int, m: Int)\n\n implicit def arr2size(arr: Array[Int]): Size = arr match {\n case Array(n, m) => Size(n, m)\n case _ => throw new IllegalArgumentException\n }\n\n private def colorize(s: Size): Seq[Seq[Char]] = {\n val Size(n, m) = s\n\n if (n > m) colorize(Size(m, n)).transpose\n else (0 until n).map(i => List.fill(m - i)('B') ::: List.fill(i)('W'))\n }\n\n val t = scala.io.StdIn.readInt()\n\n val sizes = (0 until t).foldLeft(List.empty[Size]) { (acc, _) =>\n val size = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n size :: acc\n }.reverse\n\n val answers = sizes.map(colorize)\n\n answers.foreach { answer =>\n println(answer.map(_.mkString(\"\")).mkString(\"\\n\"))\n }\n}", "positive_code": [{"source_code": "object A extends App {\n case class Size(n: Int, m: Int)\n\n implicit def arr2size(arr: Array[Int]): Size = arr match {\n case Array(n, m) => Size(n, m)\n case _ => throw new IllegalArgumentException\n }\n\n private def colorize(s: Size): Seq[Seq[Char]] = {\n val Size(n, m) = s\n\n for (i <- 0 until n) yield {\n for (j <- 0 until m) yield if (i + j == 0) 'W' else 'B'\n }\n }\n\n val t = scala.io.StdIn.readInt()\n\n val sizes = (0 until t)\n .foldLeft(List.empty[Size]) { (acc, _) =>\n val size = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n size :: acc\n }\n .reverse\n\n val answers = sizes.map(colorize)\n\n answers.foreach { answer =>\n println(answer.map(_.mkString(\"\")).mkString(\"\\n\"))\n }\n}"}], "negative_code": [], "src_uid": "2b37f27a98ec8f80d0bff3f7ae8f2cff"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n rep(ni()) { _ =>\n val d = ni()\n if (d == 0 || d >= 4) {\n val c2 = d.toDouble * d / 4 - d\n val a = math.sqrt(c2) + d.toDouble / 2\n val b = d - a\n// System.err.println(b + a - b * a)\n out.println(f\"Y $a%.9f $b%.9f\")\n } else {\n out.println(\"N\")\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object CF1076c extends App {\n val in = new java.util.Scanner(System.in)\n val out = new java.io.PrintWriter(System.out)\n\n import scala.math._\n\n // a + b == d && a * b == d\n // a, b is the root of x^2 - d x + d == 0\n def resolve(d: Double) : Option[(Double, Double)] = {\n if (d <= 0 || d >= 4) {\n val del = d*d/4-d\n Some(d/2-sqrt(del), d/2+sqrt(del))\n } else {\n None\n }\n }\n\n val n = in.nextInt\n 1 to n foreach ((_: Int) => {\n val d = in.nextInt\n resolve(d.toDouble) match {\n case Some((a, b)) => println(s\"Y $a $b\")\n case None => println(\"N\")\n }\n })\n out.flush;out.close;\n}\n"}], "negative_code": [], "src_uid": "6f5d41346419901c830233b3bf5c9e65"} {"source_code": "import java.util.TreeSet\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val hs = readInts(n)\n\n case class Tower(h: Int, i: Int) extends java.lang.Comparable[Tower] {\n\n override def compareTo(other: Tower): Int = {\n if (this.h < other.h) -1\n else if (this.h > other.h) 1\n else Integer.compare(this.i, other.i)\n }\n\n }\n\n val ts = hs.zipWithIndex.map { case (h, i) => Tower(h, i) }\n val tree = new TreeSet[Tower]\n for (t <- ts) tree.add(t)\n\n var blocks = 0\n var from = 0\n while (from < n) {\n blocks += 1\n var minTower = tree.lower(Tower(ts(from).h, -1))\n if (minTower == null) {\n tree.remove(ts(from))\n from += 1\n } else {\n var to = minTower.i\n while (from <= to) {\n val minTower2 = tree.lower(Tower(ts(from).h, -1))\n if (minTower2 != null) {\n minTower = minTower2\n to = minTower.i max to\n }\n tree.remove(ts(from))\n from += 1\n }\n }\n }\n\n println(blocks)\n}\n", "positive_code": [{"source_code": "object C{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val n=nextInt\n val h=for(i<-0 until n) yield nextInt\n val hs0=(for(i<-0 until n) yield(h(i),i))\n val hs=scala.util.Sorting.stableSort(hs0)\n\n val (_,ind)=hs unzip\n \n var l=0\n var count=0\n \n while(l (blocks + 1, Map.empty[Int, Int], Map.empty[Int, Int])\n case ((blocks, m1, m2), (el1, el2)) if m1.isEmpty => (blocks + 1, Map(el1 -> 1), Map(el2 -> 1))\n case ((blocks, m1, m2), (el1, el2)) =>\n val m1Map = m1 + (el1 -> (m1.getOrElse(el1, 0) + 1))\n val m2Map = m2 + (el2 -> (m2.getOrElse(el2, 0) + 1))\n if (m1Map == m2Map)\n (blocks, Map.empty, Map.empty)\n else\n (blocks, m1Map, m2Map)\n }\n println(res._1)\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n val A = readLine().split(\" \").map(_.toLong)\n\n val S = Array.ofDim[(Long, Long)](n)\n\n var max = Long.MinValue\n for (i <- 0 until n) {\n max = Math.max(max, A(i))\n S(i) = (max, Integer.MAX_VALUE)\n }\n\n var min = Long.MaxValue\n for (i <- n - 1 to 0 by -1) {\n min = Math.min(min, A(i))\n S(i) = (S(i)._1, min)\n }\n\n var counter = 1\n\n for (i <- 1 until n) {\n if (S(i - 1)._1 <= S(i)._2) {\n counter += 1\n }\n }\n\n// println(S.mkString(\",\"))\n println(counter)\n\n}\n"}], "negative_code": [{"source_code": "import java.util.TreeSet\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val hs = readInts(n)\n \n if (n == 100000 && hs.head == 2) println(hs.takeRight(200).mkString(\" \")) \n\n case class Tower(h: Int, i: Int) extends java.lang.Comparable[Tower] {\n\n override def compareTo(other: Tower): Int = {\n if (this.h < other.h) -1\n else if (this.h > other.h) 1\n else Integer.compare(this.i, other.i)\n }\n\n }\n\n val ts = hs.zipWithIndex.map { case (h, i) => Tower(h, i) }\n val tree = new TreeSet[Tower]\n for (t <- ts) tree.add(t)\n\n var blocks = 0\n\n var from = 0\n while (from < n) {\n blocks += 1\n var minTower = tree.lower(Tower(ts(from).h, -1))\n if (minTower == null) {\n tree.remove(ts(from))\n from += 1\n } else {\n var to = minTower.i\n while (from <= to) {\n if (ts(from).h >= minTower.h) {\n val minTower2 = tree.lower(Tower(ts(from).h, -1))\n if (minTower2 != null) {\n minTower = minTower2\n to = minTower.i\n }\n }\n tree.remove(ts(from))\n from += 1\n }\n }\n }\n\n println(blocks)\n}\n"}, {"source_code": "import scala.collection._\nimport java.util.TreeSet\nimport scala.util.Random\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n //val hs = Array.tabulate(n){ identity }\n val hs = readInts(n)\n\n case class Tower(h: Int, i: Int) extends java.lang.Comparable[Tower] {\n\n override def compareTo(other: Tower): Int = {\n if (this.h < other.h) -1\n else if (this.h > other.h) 1\n else Integer.compare(this.i, other.i)\n }\n\n }\n\n val ts = hs.zipWithIndex.map { case (h, i) => Tower(h, i) }\n val tree = new TreeSet[Tower]\n for (t <- ts) tree.add(t)\n\n var blocks = 0\n\n var from = 0\n while (from < n) {\n blocks += 1\n var minTower = tree.lower(Tower(ts(from).h, -1))\n if (minTower == null) {\n tree.remove(ts(from))\n from += 1\n } else {\n var to = minTower.i\n while (from <= to) {\n if (ts(from).h >= minTower.h) {\n val minTower2 = tree.lower(Tower(ts(from).h, -1))\n if (minTower2 != null) {\n minTower = minTower2\n to = minTower.i\n }\n }\n tree.remove(ts(from))\n from += 1\n }\n }\n }\n\n println(blocks)\n}\n"}, {"source_code": "import java.util.TreeSet\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val hs = readInts(n)\n \n if (n == 100000 && hs.head == 2) println(hs.takeRight(200)) \n\n case class Tower(h: Int, i: Int) extends java.lang.Comparable[Tower] {\n\n override def compareTo(other: Tower): Int = {\n if (this.h < other.h) -1\n else if (this.h > other.h) 1\n else Integer.compare(this.i, other.i)\n }\n\n }\n\n val ts = hs.zipWithIndex.map { case (h, i) => Tower(h, i) }\n val tree = new TreeSet[Tower]\n for (t <- ts) tree.add(t)\n\n var blocks = 0\n\n var from = 0\n while (from < n) {\n blocks += 1\n var minTower = tree.lower(Tower(ts(from).h, -1))\n if (minTower == null) {\n tree.remove(ts(from))\n from += 1\n } else {\n var to = minTower.i\n while (from <= to) {\n if (ts(from).h >= minTower.h) {\n val minTower2 = tree.lower(Tower(ts(from).h, -1))\n if (minTower2 != null) {\n minTower = minTower2\n to = minTower.i\n }\n }\n tree.remove(ts(from))\n from += 1\n }\n }\n }\n\n println(blocks)\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n val n = readInt()\n val A = readLine().split(\" \").map(_.toLong)\n\n val S = new scala.collection.mutable.Stack[(Long, Long)] // value, min\n\n for (i <- A.length - 1 to 0 by - 1) {\n if (S.isEmpty) {\n S.push((A(i), A(i)))\n } else {\n val curMin = S.top._2\n S.push((A(i), Math.min(curMin, A(i))))\n }\n }\n\n println(S.toArray.map(_._2).distinct.length)\n\n}\n"}], "src_uid": "c1158d23d3ad61c346c345f14e63ede4"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CF644(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CF644(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val a = ni()\n val b = ni()\n\n val mn = math.min(a, b)\n val mx = math.max(a, b)\n\n if(2 * mn > mx) {\n out.println(4 * mn * mn)\n } else out.println(mx * mx)\n }\n }\n}\n", "positive_code": [{"source_code": "\n\nobject CodeforcesRound644a {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val Array(a, b) = rll_long\n val res = sqr(Math.max(Math.max(Math.min(a * 2, b * 2), a), b))\n writer.println(res)\n }\n\n def sqr(a: Long): Long = a * a\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject A {\n\n import scala.math._\n def solution(a: Int, b: Int): Int = {\n val (mi, ma) = (min(a, b), max(a, b))\n val c = max(mi*2, ma)\n c * c\n }\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val Seq(n, k) = readLine.split(\" \").toSeq.map(_.toInt)\n println(solution(n, k))\n }\n }\n}"}, {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val c = (2 * (a min b)) max (a max b)\n\n println(c * c)\n\n }\n}\n"}], "negative_code": [{"source_code": "\n\nobject CodeforcesRound644a {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val Array(a,b) = rll_long\n val res = Math.pow(Math.min(Math.max(3,b*2), Math.max(a*2,b)), 2).toLong\n writer.println(res)\n }\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}"}, {"source_code": "\n\nobject CodeforcesRound644a {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val Array(a,b) = rll_long\n val res = (Math.min(a,b) * 2) * (Math.min(a,b) * 2)\n writer.println(res)\n }\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}"}], "src_uid": "3bb093fb17d6b76ae340fab44b08fcb8"} {"source_code": "object CF_522_2_B {\n\n case class Output(rows: Int, columns: Int, table: Seq[String])\n\n def solve(in: String): Output = {\n val n = in.length\n val rows = ceil(n,20)\n val cols = ceil(n, rows)\n val tableSize = rows * cols\n val remainder = tableSize - n\n def make(r: Int, s: String, out: Seq[String]): Seq[String] = r match {\n case 0 => out\n case _ =>\n val len = if (r <= remainder) cols - 1 else cols\n val (first, last) = s.splitAt(len)\n make(r - 1, last, out :+ first.padTo(cols,'*'))\n }\n val table = make(rows, in, Seq.empty)\n Output(rows, cols, table)\n }\n\n def solution(i: Input) = solve(i.string)\n\n \n// ~~~ Boilerplate ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n def main(args: Array[String]) {\n val out = new java.io.PrintWriter(System.out)\n val sol = solution(new Input(System.in))\n out.println(sol.rows + \" \" + sol.columns + \"\\n\" + sol.table.mkString(\"\\n\"))\n out.close()\n }\n\n// ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n import java.util.Scanner\n class Input(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def string = sc.next()\n def nextLine = sc.nextLine() \n // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n }\n\n def ceil(a: Int, b: Int) = (a - 1) / b + 1\n def ceil(a: Long, b: Long) = (a - 1) / b + 1\n}", "positive_code": [{"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val s = readLine\n val n = s.length\n\n var rows = 1\n while (rows < 6) {\n if (rows * 20 >= n) {\n val colsMin = n / rows\n val rem = n % rows\n if (rem == 0) {\n println(s\"$rows $colsMin\")\n s.grouped(colsMin).foreach(println)\n } else {\n val cols = colsMin + 1\n val left = s.take(rem * cols)\n val right = s.drop(rem * cols)\n println(s\"$rows $cols\")\n left.grouped(cols).foreach(println)\n right.grouped(colsMin).foreach(x => println(x + \"*\"))\n }\n rows = 100\n }\n rows += 1\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S = ns()\n val n = S.length\n val rowCnt = (n - 1) / 20 + 1\n val colCnt = (n - 1) / rowCnt + 1\n val minus = colCnt * rowCnt - n\n var l = 0\n\n out.println(s\"$rowCnt $colCnt\")\n\n rep(rowCnt) { r =>\n if (r < rowCnt - minus) {\n val r = l + colCnt\n out.println(S.substring(l, r))\n l = r\n } else {\n val r = l + colCnt - 1\n out.println(s\"${S.substring(l, r)}*\")\n l = r\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object CF_522_2_B {\n\n case class Output(rows: Int, columns: Int, table: Seq[String])\n\n def solve(in: String): Output = {\n val n = in.length\n val rows = ceil(n,20)\n val cols = ceil(n, rows)\n val tableSize = rows * cols\n val remainder = tableSize - n\n def make(r: Int, s: String, out: Seq[String]): Seq[String] = r match {\n case 0 => out\n case _ =>\n val len = if (r < remainder) cols - 1 else cols\n val (first, last) = s.splitAt(len)\n make(r - 1, last, out :+ first.padTo(cols,'*'))\n }\n val table = make(rows, in, Seq.empty)\n Output(rows, cols, table)\n }\n\n def solution(i: Input) = solve(i.string)\n\n \n// ~~~ Boilerplate ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n def main(args: Array[String]) {\n val out = new java.io.PrintWriter(System.out)\n val sol = solution(new Input(System.in))\n out.println(sol.rows + \" \" + sol.columns + \"\\n\" + sol.table.mkString(\"\\n\"))\n out.close()\n }\n\n// ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n import java.util.Scanner\n class Input(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def string = sc.next()\n def nextLine = sc.nextLine() \n // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n }\n\n def ceil(a: Int, b: Int) = (a - 1) / b + 1\n def ceil(a: Long, b: Long) = (a - 1) / b + 1\n}"}], "src_uid": "ac047ceede246b40892c80dbd696e6b4"} {"source_code": "import scala.collection.mutable.ArrayBuffer\r\n\r\nobject C {\r\n\r\n import java.io._\r\n\r\n val out: OutputPrinter = new BufferedOutputPrinter\r\n //val out: OutputPrinter = new OutputPrinter\r\n val input = new InputReader(new InputStreamReader(System.in))\r\n// val input = new InputReader(new StringReader(\r\n// \"\"\"4\r\n// 7\r\n// 1 2 1 2 1 2 1\r\n// 6 8 3 1 5 1 5\r\n// 10\r\n// 1 1 1 2 2 2 2 3 3 3\r\n// 3435 3014 2241 2233 2893 2102 2286 2175 1961 2567\r\n// 6\r\n// 3 3 3 3 3 3\r\n// 5 9 6 7 9 7\r\n// 1\r\n// 1\r\n// 3083\r\n// \"\"\"))\r\n\r\n def main(args: Array[String]): Unit = {\r\n val startTime = System.currentTimeMillis()\r\n\r\n val executor = new Solution\r\n executor.solve()\r\n\r\n out.flush()\r\n val elapsed = System.currentTimeMillis() - startTime\r\n //println(s\"Elapsed: $elapsed\")\r\n }\r\n\r\n class Solution {\r\n\r\n def solve(): Unit = {\r\n val tasks = input.nextInt\r\n for (_ <- 0 until tasks) {\r\n val n = input.nextInt\r\n val st = new Array[Int](n)\r\n input.forInts(n) { (idx, u) => st(idx) = u - 1 }\r\n val ub = Array.fill[List[Int]](n)(Nil)\r\n input.forInts(n) { (idx, s) =>\r\n val un = st(idx)\r\n ub(un) ::= s\r\n }\r\n val uns = ub.filter(_.nonEmpty).map { l =>\r\n val ar = new Array[Long](l.length)\r\n val it = l.iterator\r\n for (i <- ar.indices) {\r\n ar(i) = it.next()\r\n }\r\n val arr = ar.sortBy(-_)\r\n var s = 0L\r\n for (len <- arr.indices) {\r\n s += arr(len)\r\n arr(len) = s\r\n }\r\n arr\r\n }\r\n\r\n val ans = new Array[Long](n)\r\n\r\n for (i <- uns.indices) {\r\n for (k <- 1 to uns(i).length) {\r\n val len = uns(i).length\r\n if (len >= k) {\r\n ans(k - 1) += uns(i)(len / k * k - 1);\r\n }\r\n }\r\n }\r\n\r\n for (i <- 0 until n) out.print(s\"${ans(i)} \")\r\n\r\n out.flush()\r\n }\r\n }\r\n }\r\n\r\n\r\n\r\n class Solution1 {\r\n\r\n def solve(): Unit = {\r\n val tasks = input.nextInt\r\n for (_ <- 0 until tasks) {\r\n val n = input.nextInt\r\n\r\n val s = new Array[Int](n)\r\n val u = new Array[Int](n)\r\n\r\n input.forInts(n) { (idx, i) => s(idx) = i - 1 }\r\n input.forInts(n) { (idx, i) => u(idx) = i }\r\n\r\n val bst = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())\r\n for (i <- 0 until n) bst(s(i)) += u(i)\r\n for (i <- 0 until n) bst(i) = bst(i).sortBy(-_)\r\n\r\n val pr = Array.fill[ArrayBuffer[Long]](n)(new ArrayBuffer[Long]() += 0)\r\n\r\n for (i <- 0 until n) {\r\n bst(i).foreach(x => pr(i) += pr(i).last + x)\r\n }\r\n\r\n val ans = new Array[Long](n)\r\n\r\n for (i <- 0 until n) {\r\n for (k <- 1 to bst(i).length) {\r\n ans(k - 1) += pr(i)(bst(i).length / k * k);\r\n }\r\n }\r\n\r\n for (i <- 0 until n) out.print(s\"${ans(i)} \")\r\n\r\n out.flush()\r\n }\r\n }\r\n }\r\n\r\n\r\n class Solution2 {\r\n\r\n def solve(): Unit = {\r\n val tasks = input.nextInt\r\n for (_ <- 0 until tasks) {\r\n val n = input.nextInt\r\n val st = new Array[Int](n)\r\n input.forInts(n)((idx, u) => st(idx) = u - 1)\r\n\r\n val bst = Array.fill[ArrayBuffer[Long]](n)(new ArrayBuffer[Long]())\r\n input.forInts(n)((idx, s) => bst(st(idx)) += s)\r\n\r\n for (i <- 0 until n) bst(i) = bst(i).sortBy(-_)\r\n\r\n for (i <- 0 until n) {\r\n val arr = bst(i)\r\n var s = 0L\r\n for (len <- arr.indices) {\r\n s += arr(len)\r\n arr(len) = s\r\n }\r\n }\r\n\r\n\r\n val ans = new Array[Long](n)\r\n\r\n for (i <- 0 until n) {\r\n for (k <- 1 to bst(i).length) {\r\n val len = bst(i).length\r\n if (len >= k) {\r\n ans(k - 1) += bst(i)(len / k * k - 1);\r\n }\r\n }\r\n }\r\n\r\n for (i <- 0 until n) out.print(s\"${ans(i)} \")\r\n\r\n out.flush()\r\n }\r\n }\r\n }\r\n\r\n\r\n class Solution3 {\r\n\r\n def solve(): Unit = {\r\n val tasks = input.nextInt\r\n for (_ <- 0 until tasks) {\r\n val n = input.nextInt\r\n val st = new Array[Int](n)\r\n input.forInts(n) { (idx, u) => st(idx) = u - 1 }\r\n\r\n val bst = Array.fill[ArrayBuffer[Long]](n)(new ArrayBuffer[Long]())\r\n input.forInts(n)((idx, s) => bst(st(idx)) += s)\r\n\r\n for (i <- 0 until n) {\r\n val arr = bst(i).sortBy(-_)\r\n var s = 0L\r\n for (len <- arr.indices) {\r\n s += arr(len)\r\n arr(len) = s\r\n }\r\n bst(i) = arr\r\n }\r\n\r\n val ans = new Array[Long](n)\r\n\r\n\r\n for (k <- 1 to n) {\r\n var s = 0L\r\n bst.foreach { u =>\r\n val teams = u.length / k\r\n if (teams > 0) {\r\n s += u(teams * k - 1)\r\n }\r\n }\r\n out.print(s.toString)\r\n out.print(' ')\r\n }\r\n out.flush()\r\n }\r\n }\r\n }\r\n\r\n\r\n\r\n // ===========================================================================\r\n // --------- TOOLS ---------------------------------------------------------\r\n // ===========================================================================\r\n\r\n class InputReader(reader: Reader) {\r\n\r\n import java.io.BufferedReader\r\n import java.util.StringTokenizer\r\n\r\n private val buffer = new BufferedReader(reader)\r\n private var parser: StringTokenizer = _\r\n\r\n private def next = {\r\n if (parser == null || !parser.hasMoreElements) {\r\n parser = new StringTokenizer(buffer.readLine)\r\n }\r\n parser.nextToken\r\n }\r\n\r\n def endl(): Unit = {\r\n parser = null\r\n }\r\n\r\n def nextByte = next.toByte\r\n\r\n def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)\r\n\r\n def nextInt = next.toInt\r\n\r\n def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)\r\n\r\n def nextLong = next.toLong\r\n\r\n def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)\r\n\r\n def nextDouble = next.toDouble\r\n\r\n def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)\r\n\r\n def nextString = next\r\n\r\n def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)\r\n\r\n private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {\r\n for (index <- 0 until num) op(index, readOp)\r\n }\r\n }\r\n\r\n class OutputPrinter {\r\n private val buffer = new StringBuilder() // faster if exists\r\n\r\n def print(c: Char): Unit = {}\r\n\r\n def print(i: Int): Unit = {}\r\n\r\n def print(s: String): Unit = {}\r\n\r\n def endl(): Unit = {}\r\n\r\n def flush(): Unit = {}\r\n }\r\n\r\n class StringOutputPrinter(capacity: Int = 1024) extends OutputPrinter {\r\n private val buffer = new StringBuilder(capacity)\r\n\r\n override def print(c: Char): Unit = buffer.append(c)\r\n\r\n override def print(i: Int): Unit = buffer.append(i)\r\n\r\n override def print(s: String): Unit = buffer.append(s)\r\n\r\n override def endl(): Unit = buffer.append(\"\\n\")\r\n\r\n override def flush(): Unit = {\r\n if (buffer.nonEmpty) {\r\n println(buffer.result())\r\n buffer.clear()\r\n }\r\n }\r\n }\r\n\r\n class BufferedOutputPrinter extends OutputPrinter {\r\n private val buffer = new PrintWriter(System.out)\r\n\r\n override def print(c: Char): Unit = buffer.print(c)\r\n\r\n override def print(i: Int): Unit = buffer.print(i)\r\n\r\n override def print(s: String): Unit = buffer.print(s)\r\n\r\n override def endl(): Unit = buffer.println()\r\n\r\n override def flush(): Unit = {\r\n endl()\r\n buffer.flush()\r\n }\r\n }\r\n\r\n}\r\n", "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\r\n\r\nobject C {\r\n\r\n import java.io._\r\n\r\n val out: OutputPrinter = new BufferedOutputPrinter\r\n //val out: OutputPrinter = new OutputPrinter\r\n val input = new InputReader(new InputStreamReader(System.in))\r\n// val input = new InputReader(new StringReader(\r\n// \"\"\"4\r\n// 7\r\n// 1 2 1 2 1 2 1\r\n// 6 8 3 1 5 1 5\r\n// 10\r\n// 1 1 1 2 2 2 2 3 3 3\r\n// 3435 3014 2241 2233 2893 2102 2286 2175 1961 2567\r\n// 6\r\n// 3 3 3 3 3 3\r\n// 5 9 6 7 9 7\r\n// 1\r\n// 1\r\n// 3083\r\n// \"\"\"))\r\n\r\n def main(args: Array[String]): Unit = {\r\n val startTime = System.currentTimeMillis()\r\n\r\n val executor = new Solution2\r\n executor.solve()\r\n\r\n out.flush()\r\n val elapsed = System.currentTimeMillis() - startTime\r\n //println(s\"Elapsed: $elapsed\")\r\n }\r\n\r\n\r\n class Solution1 {\r\n\r\n def solve(): Unit = {\r\n val tasks = input.nextInt\r\n for (_ <- 0 until tasks) {\r\n val n = input.nextInt\r\n\r\n val s = new Array[Int](n)\r\n val u = new Array[Int](n)\r\n\r\n input.forInts(n) { (idx, i) => s(idx) = i - 1 }\r\n input.forInts(n) { (idx, i) => u(idx) = i }\r\n\r\n val bst = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())\r\n for (i <- 0 until n) bst(s(i)) += u(i)\r\n for (i <- 0 until n) bst(i) = bst(i).sortBy(-_)\r\n\r\n val pr = Array.fill[ArrayBuffer[Long]](n)(new ArrayBuffer[Long]() += 0)\r\n\r\n for (i <- 0 until n) {\r\n bst(i).foreach(x => pr(i) += pr(i).last + x)\r\n }\r\n\r\n val ans = new Array[Long](n)\r\n\r\n for (i <- 0 until n) {\r\n for (k <- 1 to bst(i).length) {\r\n ans(k - 1) += pr(i)(bst(i).length / k * k);\r\n }\r\n }\r\n\r\n for (i <- 0 until n) out.print(s\"${ans(i)} \")\r\n\r\n out.flush()\r\n }\r\n }\r\n }\r\n\r\n\r\n class Solution2 {\r\n\r\n def solve(): Unit = {\r\n val tasks = input.nextInt\r\n for (_ <- 0 until tasks) {\r\n val n = input.nextInt\r\n val st = new Array[Int](n)\r\n input.forInts(n)((idx, u) => st(idx) = u - 1)\r\n\r\n val bst = Array.fill[ArrayBuffer[Long]](n)(new ArrayBuffer[Long]())\r\n input.forInts(n)((idx, s) => bst(st(idx)) += s)\r\n\r\n for (i <- 0 until n) bst(i) = bst(i).sortBy(-_)\r\n\r\n for (i <- 0 until n) {\r\n val arr = bst(i)\r\n var s = 0L\r\n for (len <- arr.indices) {\r\n s += arr(len)\r\n arr(len) = s\r\n }\r\n }\r\n\r\n\r\n val ans = new Array[Long](n)\r\n\r\n for (i <- 0 until n) {\r\n for (k <- 1 to bst(i).length) {\r\n val len = bst(i).length\r\n if (len >= k) {\r\n ans(k - 1) += bst(i)(len / k * k - 1);\r\n }\r\n }\r\n }\r\n\r\n for (i <- 0 until n) out.print(s\"${ans(i)} \")\r\n\r\n out.flush()\r\n }\r\n }\r\n }\r\n\r\n class Solution3 {\r\n\r\n def solve(): Unit = {\r\n val tasks = input.nextInt\r\n for (_ <- 0 until tasks) {\r\n val n = input.nextInt\r\n val st = new Array[Int](n)\r\n input.forInts(n) { (idx, u) => st(idx) = u - 1 }\r\n val ub = Array.fill[List[Int]](n)(Nil)\r\n input.forInts(n) { (idx, s) =>\r\n val un = st(idx)\r\n ub(un) ::= s\r\n }\r\n val uns = ub.filter(_.nonEmpty).map { l =>\r\n val ar = new Array[Long](l.length)\r\n val it = l.iterator\r\n for (i <- ar.indices) {\r\n ar(i) = it.next()\r\n }\r\n val arr = ar.sortBy(-_)\r\n var s = 0L\r\n for (len <- arr.indices) {\r\n s += arr(len)\r\n arr(len) = s\r\n }\r\n arr\r\n }\r\n for (k <- 1 to n) {\r\n var s = 0L\r\n uns.foreach { u =>\r\n val teams = u.length / k\r\n if (teams > 0) {\r\n s += u(teams * k - 1)\r\n }\r\n }\r\n out.print(s.toString)\r\n out.print(' ')\r\n }\r\n out.flush()\r\n }\r\n }\r\n }\r\n\r\n\r\n\r\n // ===========================================================================\r\n // --------- TOOLS ---------------------------------------------------------\r\n // ===========================================================================\r\n\r\n class InputReader(reader: Reader) {\r\n\r\n import java.io.BufferedReader\r\n import java.util.StringTokenizer\r\n\r\n private val buffer = new BufferedReader(reader)\r\n private var parser: StringTokenizer = _\r\n\r\n private def next = {\r\n if (parser == null || !parser.hasMoreElements) {\r\n parser = new StringTokenizer(buffer.readLine)\r\n }\r\n parser.nextToken\r\n }\r\n\r\n def endl(): Unit = {\r\n parser = null\r\n }\r\n\r\n def nextByte = next.toByte\r\n\r\n def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)\r\n\r\n def nextInt = next.toInt\r\n\r\n def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)\r\n\r\n def nextLong = next.toLong\r\n\r\n def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)\r\n\r\n def nextDouble = next.toDouble\r\n\r\n def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)\r\n\r\n def nextString = next\r\n\r\n def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)\r\n\r\n private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {\r\n for (index <- 0 until num) op(index, readOp)\r\n }\r\n }\r\n\r\n class OutputPrinter {\r\n private val buffer = new StringBuilder() // faster if exists\r\n\r\n def print(c: Char): Unit = {}\r\n\r\n def print(i: Int): Unit = {}\r\n\r\n def print(s: String): Unit = {}\r\n\r\n def endl(): Unit = {}\r\n\r\n def flush(): Unit = {}\r\n }\r\n\r\n class StringOutputPrinter(capacity: Int = 1024) extends OutputPrinter {\r\n private val buffer = new StringBuilder(capacity)\r\n\r\n override def print(c: Char): Unit = buffer.append(c)\r\n\r\n override def print(i: Int): Unit = buffer.append(i)\r\n\r\n override def print(s: String): Unit = buffer.append(s)\r\n\r\n override def endl(): Unit = buffer.append(\"\\n\")\r\n\r\n override def flush(): Unit = {\r\n if (buffer.nonEmpty) {\r\n println(buffer.result())\r\n buffer.clear()\r\n }\r\n }\r\n }\r\n\r\n class BufferedOutputPrinter extends OutputPrinter {\r\n private val buffer = new PrintWriter(System.out)\r\n\r\n override def print(c: Char): Unit = buffer.print(c)\r\n\r\n override def print(i: Int): Unit = buffer.print(i)\r\n\r\n override def print(s: String): Unit = buffer.print(s)\r\n\r\n override def endl(): Unit = buffer.println()\r\n\r\n override def flush(): Unit = {\r\n endl()\r\n buffer.flush()\r\n }\r\n }\r\n\r\n}\r\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\r\n\r\nobject C {\r\n\r\n import java.io._\r\n\r\n val out: OutputPrinter = new BufferedOutputPrinter\r\n //val out: OutputPrinter = new OutputPrinter\r\n val input = new InputReader(new InputStreamReader(System.in))\r\n // val input = new InputReader(new StringReader(\r\n // \"\"\"4\r\n // 7\r\n // 1 2 1 2 1 2 1\r\n // 6 8 3 1 5 1 5\r\n // 10\r\n // 1 1 1 2 2 2 2 3 3 3\r\n // 3435 3014 2241 2233 2893 2102 2286 2175 1961 2567\r\n // 6\r\n // 3 3 3 3 3 3\r\n // 5 9 6 7 9 7\r\n // 1\r\n // 1\r\n // 3083\r\n // \"\"\"))\r\n\r\n def main(args: Array[String]): Unit = {\r\n val startTime = System.currentTimeMillis()\r\n\r\n val executor = new Solution1\r\n executor.solve()\r\n\r\n out.flush()\r\n val elapsed = System.currentTimeMillis() - startTime\r\n //println(s\"Elapsed: $elapsed\")\r\n }\r\n\r\n\r\n class Solution1 {\r\n //\r\n // int main() {\r\n // int t;\r\n // scanf(\"%d\", &t);\r\n // forn(_, t){\r\n // int n;\r\n // scanf(\"%d\", &n);\r\n // vector s(n), u(n);\r\n // forn(i, n){\r\n // scanf(\"%d\", &s[i]);\r\n // --s[i];\r\n // }\r\n // forn(i, n){\r\n // scanf(\"%d\", &u[i]);\r\n // }\r\n // vector> bst(n);\r\n // forn(i, n) bst[s[i]].push_back(u[i]);\r\n // forn(i, n) sort(bst[i].begin(), bst[i].end(), greater());\r\n\r\n // vector> pr(n, vector(1, 0));\r\n\r\n // forn(i, n) for (int x : bst[i]) pr[i].push_back(pr[i].back() + x);\r\n // vector ans(n);\r\n // forn(i, n) for (int k = 1; k <= int(bst[i].size()); ++k)\r\n // ans[k - 1] += pr[i][bst[i].size() / k * k];\r\n // forn(i, n)\r\n // printf(\"%lld \", ans[i]);\r\n // puts(\"\");\r\n // }\r\n // return 0;\r\n // }\r\n //\r\n def solve(): Unit = {\r\n val tasks = input.nextInt\r\n for (_ <- 0 until tasks) {\r\n val n = input.nextInt\r\n\r\n val s = new Array[Int](n)\r\n val u = new Array[Int](n)\r\n\r\n input.forInts(n) { (idx, i) => s(idx) = i - 1 }\r\n input.forInts(n) { (idx, i) => u(idx) = i }\r\n\r\n val bst = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())\r\n for (i <- 0 until n) bst(s(i)) += u(i)\r\n for (i <- 0 until n) bst(i) = bst(i).sortBy(-_)\r\n\r\n val pr = Array.fill[ArrayBuffer[Long]](n)(new ArrayBuffer[Long]() += 0)\r\n\r\n for (i <- 0 until n) {\r\n bst(i).foreach(x => pr(i) += pr(i).last + x)\r\n }\r\n\r\n val ans = new Array[Long](n)\r\n\r\n for (i <- 0 until n) {\r\n for (k <- 1 to bst(i).length) {\r\n ans(k - 1) += pr(i)(bst(i).length / k * k);\r\n }\r\n }\r\n\r\n for (i <- 0 until n) out.print(s\"${ans(i)} \")\r\n\r\n out.flush()\r\n }\r\n }\r\n }\r\n\r\n class Solution2 {\r\n //\r\n // int main() {\r\n // int t;\r\n // scanf(\"%d\", &t);\r\n // forn(_, t){\r\n // int n;\r\n // scanf(\"%d\", &n);\r\n // vector s(n), u(n);\r\n // forn(i, n){\r\n // scanf(\"%d\", &s[i]);\r\n // --s[i];\r\n // }\r\n // forn(i, n){\r\n // scanf(\"%d\", &u[i]);\r\n // }\r\n // vector> bst(n);\r\n // forn(i, n) bst[s[i]].push_back(u[i]);\r\n // forn(i, n) sort(bst[i].begin(), bst[i].end(), greater());\r\n // vector> pr(n, vector(1, 0));\r\n // forn(i, n) for (int x : bst[i]) pr[i].push_back(pr[i].back() + x);\r\n // vector ans(n);\r\n // forn(i, n) for (int k = 1; k <= int(bst[i].size()); ++k)\r\n // ans[k - 1] += pr[i][bst[i].size() / k * k];\r\n // forn(i, n)\r\n // printf(\"%lld \", ans[i]);\r\n // puts(\"\");\r\n // }\r\n // return 0;\r\n // }\r\n //\r\n def solve(): Unit = {\r\n val tasks = input.nextInt\r\n for (_ <- 0 until tasks) {\r\n val n = input.nextInt\r\n val st = new Array[Int](n)\r\n input.forInts(n) { (idx, u) => st(idx) = u - 1 }\r\n val ub = Array.fill[List[Int]](n)(Nil)\r\n input.forInts(n) { (idx, s) =>\r\n val un = st(idx)\r\n ub(un) ::= s\r\n }\r\n val uns = ub.filter(_.nonEmpty).map { l =>\r\n val ar = new Array[Long](l.length)\r\n val it = l.iterator\r\n for (i <- ar.indices) {\r\n ar(i) = it.next()\r\n }\r\n val arr = ar.sortBy(-_)\r\n var s = 0L\r\n for (len <- arr.indices) {\r\n s += arr(len)\r\n arr(len) = s\r\n }\r\n arr\r\n }\r\n for (k <- 1 to n) {\r\n var s = 0L\r\n uns.foreach { u =>\r\n val teams = u.length / k\r\n if (teams > 0) {\r\n s += u(teams * k - 1)\r\n }\r\n }\r\n out.print(s.toString)\r\n out.print(' ')\r\n }\r\n out.flush()\r\n }\r\n }\r\n }\r\n\r\n\r\n\r\n // ===========================================================================\r\n // --------- TOOLS ---------------------------------------------------------\r\n // ===========================================================================\r\n\r\n class InputReader(reader: Reader) {\r\n\r\n import java.io.BufferedReader\r\n import java.util.StringTokenizer\r\n\r\n private val buffer = new BufferedReader(reader)\r\n private var parser: StringTokenizer = _\r\n\r\n private def next = {\r\n if (parser == null || !parser.hasMoreElements) {\r\n parser = new StringTokenizer(buffer.readLine)\r\n }\r\n parser.nextToken\r\n }\r\n\r\n def endl(): Unit = {\r\n parser = null\r\n }\r\n\r\n def nextByte = next.toByte\r\n\r\n def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)\r\n\r\n def nextInt = next.toInt\r\n\r\n def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)\r\n\r\n def nextLong = next.toLong\r\n\r\n def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)\r\n\r\n def nextDouble = next.toDouble\r\n\r\n def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)\r\n\r\n def nextString = next\r\n\r\n def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)\r\n\r\n private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {\r\n for (index <- 0 until num) op(index, readOp)\r\n }\r\n }\r\n\r\n class OutputPrinter {\r\n private val buffer = new StringBuilder() // faster if exists\r\n\r\n def print(c: Char): Unit = {}\r\n\r\n def print(i: Int): Unit = {}\r\n\r\n def print(s: String): Unit = {}\r\n\r\n def endl(): Unit = {}\r\n\r\n def flush(): Unit = {}\r\n }\r\n\r\n class StringOutputPrinter(capacity: Int = 1024) extends OutputPrinter {\r\n private val buffer = new StringBuilder(capacity)\r\n\r\n override def print(c: Char): Unit = buffer.append(c)\r\n\r\n override def print(i: Int): Unit = buffer.append(i)\r\n\r\n override def print(s: String): Unit = buffer.append(s)\r\n\r\n override def endl(): Unit = buffer.append(\"\\n\")\r\n\r\n override def flush(): Unit = {\r\n if (buffer.nonEmpty) {\r\n println(buffer.result())\r\n buffer.clear()\r\n }\r\n }\r\n }\r\n\r\n class BufferedOutputPrinter extends OutputPrinter {\r\n private val buffer = new PrintWriter(System.out)\r\n\r\n override def print(c: Char): Unit = buffer.print(c)\r\n\r\n override def print(i: Int): Unit = buffer.print(i)\r\n\r\n override def print(s: String): Unit = buffer.print(s)\r\n\r\n override def endl(): Unit = buffer.println()\r\n\r\n override def flush(): Unit = {\r\n endl()\r\n buffer.flush()\r\n }\r\n }\r\n\r\n}\r\n"}], "negative_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\r\n\r\nobject C {\r\n\r\n import java.io._\r\n\r\n val out: OutputPrinter = new BufferedOutputPrinter\r\n //val out: OutputPrinter = new OutputPrinter\r\n val input = new InputReader(new InputStreamReader(System.in))\r\n// val input = new InputReader(new StringReader(\r\n// \"\"\"4\r\n// 7\r\n// 1 2 1 2 1 2 1\r\n// 6 8 3 1 5 1 5\r\n// 10\r\n// 1 1 1 2 2 2 2 3 3 3\r\n// 3435 3014 2241 2233 2893 2102 2286 2175 1961 2567\r\n// 6\r\n// 3 3 3 3 3 3\r\n// 5 9 6 7 9 7\r\n// 1\r\n// 1\r\n// 3083\r\n// \"\"\"))\r\n\r\n def main(args: Array[String]): Unit = {\r\n val startTime = System.currentTimeMillis()\r\n\r\n val executor = new Solution1\r\n executor.solve()\r\n\r\n out.flush()\r\n val elapsed = System.currentTimeMillis() - startTime\r\n //println(s\"Elapsed: $elapsed\")\r\n }\r\n\r\n\r\n class Solution1 {\r\n //\r\n // int main() {\r\n // int t;\r\n // scanf(\"%d\", &t);\r\n // forn(_, t){\r\n // int n;\r\n // scanf(\"%d\", &n);\r\n // vector s(n), u(n);\r\n // forn(i, n){\r\n // scanf(\"%d\", &s[i]);\r\n // --s[i];\r\n // }\r\n // forn(i, n){\r\n // scanf(\"%d\", &u[i]);\r\n // }\r\n // vector> bst(n);\r\n // forn(i, n) bst[s[i]].push_back(u[i]);\r\n // forn(i, n) sort(bst[i].begin(), bst[i].end(), greater());\r\n\r\n // vector> pr(n, vector(1, 0));\r\n\r\n // forn(i, n) for (int x : bst[i]) pr[i].push_back(pr[i].back() + x);\r\n // vector ans(n);\r\n // forn(i, n) for (int k = 1; k <= int(bst[i].size()); ++k)\r\n // ans[k - 1] += pr[i][bst[i].size() / k * k];\r\n // forn(i, n)\r\n // printf(\"%lld \", ans[i]);\r\n // puts(\"\");\r\n // }\r\n // return 0;\r\n // }\r\n //\r\n def solve(): Unit = {\r\n val tasks = input.nextInt\r\n for (_ <- 0 until tasks) {\r\n val n = input.nextInt\r\n\r\n\r\n val s = new Array[Int](n)\r\n val u = new Array[Int](n)\r\n\r\n input.forInts(n) { (idx, i) => s(idx) = i - 1 }\r\n input.forInts(n) { (idx, i) => u(idx) = i }\r\n\r\n val bst = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())\r\n for (i <- 0 until n) bst(s(i)) += u(i)\r\n for (i <- 0 until n) bst(i).sortBy(-_)\r\n\r\n val pr = Array.fill[ArrayBuffer[Long]](n)(new ArrayBuffer[Long]() += 0)\r\n\r\n for (i <- 0 until n) {\r\n bst(i).foreach(x => pr(i) += pr(i).last + x)\r\n }\r\n\r\n val ans = new Array[Long](n)\r\n\r\n for (i <- 0 until n) {\r\n for (k <- 1 to bst(i).length) {\r\n ans(k - 1) += pr(i)(bst(i).length / k * k);\r\n }\r\n }\r\n\r\n for (i <- 0 until n) out.print(s\"${ans(i)} \")\r\n\r\n out.flush()\r\n }\r\n }\r\n }\r\n\r\n class Solution2 {\r\n //\r\n // int main() {\r\n // int t;\r\n // scanf(\"%d\", &t);\r\n // forn(_, t){\r\n // int n;\r\n // scanf(\"%d\", &n);\r\n // vector s(n), u(n);\r\n // forn(i, n){\r\n // scanf(\"%d\", &s[i]);\r\n // --s[i];\r\n // }\r\n // forn(i, n){\r\n // scanf(\"%d\", &u[i]);\r\n // }\r\n // vector> bst(n);\r\n // forn(i, n) bst[s[i]].push_back(u[i]);\r\n // forn(i, n) sort(bst[i].begin(), bst[i].end(), greater());\r\n // vector> pr(n, vector(1, 0));\r\n // forn(i, n) for (int x : bst[i]) pr[i].push_back(pr[i].back() + x);\r\n // vector ans(n);\r\n // forn(i, n) for (int k = 1; k <= int(bst[i].size()); ++k)\r\n // ans[k - 1] += pr[i][bst[i].size() / k * k];\r\n // forn(i, n)\r\n // printf(\"%lld \", ans[i]);\r\n // puts(\"\");\r\n // }\r\n // return 0;\r\n // }\r\n //\r\n def solve(): Unit = {\r\n val tasks = input.nextInt\r\n for (_ <- 0 until tasks) {\r\n val n = input.nextInt\r\n val st = new Array[Int](n)\r\n input.forInts(n) { (idx, u) => st(idx) = u - 1 }\r\n val ub = Array.fill[List[Int]](n)(Nil)\r\n input.forInts(n) { (idx, s) =>\r\n val un = st(idx)\r\n ub(un) ::= s\r\n }\r\n val uns = ub.filter(_.nonEmpty).map { l =>\r\n val ar = new Array[Long](l.length)\r\n val it = l.iterator\r\n for (i <- ar.indices) {\r\n ar(i) = it.next()\r\n }\r\n val arr = ar.sortBy(-_)\r\n var s = 0L\r\n for (len <- arr.indices) {\r\n s += arr(len)\r\n arr(len) = s\r\n }\r\n arr\r\n }\r\n for (k <- 1 to n) {\r\n var s = 0L\r\n uns.foreach { u =>\r\n val teams = u.length / k\r\n if (teams > 0) {\r\n s += u(teams * k - 1)\r\n }\r\n }\r\n out.print(s.toString)\r\n out.print(' ')\r\n }\r\n out.flush()\r\n }\r\n }\r\n }\r\n\r\n\r\n\r\n // ===========================================================================\r\n // --------- TOOLS ---------------------------------------------------------\r\n // ===========================================================================\r\n\r\n class InputReader(reader: Reader) {\r\n\r\n import java.io.BufferedReader\r\n import java.util.StringTokenizer\r\n\r\n private val buffer = new BufferedReader(reader)\r\n private var parser: StringTokenizer = _\r\n\r\n private def next = {\r\n if (parser == null || !parser.hasMoreElements) {\r\n parser = new StringTokenizer(buffer.readLine)\r\n }\r\n parser.nextToken\r\n }\r\n\r\n def endl(): Unit = {\r\n parser = null\r\n }\r\n\r\n def nextByte = next.toByte\r\n\r\n def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)\r\n\r\n def nextInt = next.toInt\r\n\r\n def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)\r\n\r\n def nextLong = next.toLong\r\n\r\n def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)\r\n\r\n def nextDouble = next.toDouble\r\n\r\n def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)\r\n\r\n def nextString = next\r\n\r\n def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)\r\n\r\n private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {\r\n for (index <- 0 until num) op(index, readOp)\r\n }\r\n }\r\n\r\n class OutputPrinter {\r\n private val buffer = new StringBuilder() // faster if exists\r\n\r\n def print(c: Char): Unit = {}\r\n\r\n def print(i: Int): Unit = {}\r\n\r\n def print(s: String): Unit = {}\r\n\r\n def endl(): Unit = {}\r\n\r\n def flush(): Unit = {}\r\n }\r\n\r\n class StringOutputPrinter(capacity: Int = 1024) extends OutputPrinter {\r\n private val buffer = new StringBuilder(capacity)\r\n\r\n override def print(c: Char): Unit = buffer.append(c)\r\n\r\n override def print(i: Int): Unit = buffer.append(i)\r\n\r\n override def print(s: String): Unit = buffer.append(s)\r\n\r\n override def endl(): Unit = buffer.append(\"\\n\")\r\n\r\n override def flush(): Unit = {\r\n if (buffer.nonEmpty) {\r\n println(buffer.result())\r\n buffer.clear()\r\n }\r\n }\r\n }\r\n\r\n class BufferedOutputPrinter extends OutputPrinter {\r\n private val buffer = new PrintWriter(System.out)\r\n\r\n override def print(c: Char): Unit = buffer.print(c)\r\n\r\n override def print(i: Int): Unit = buffer.print(i)\r\n\r\n override def print(s: String): Unit = buffer.print(s)\r\n\r\n override def endl(): Unit = buffer.println()\r\n\r\n override def flush(): Unit = {\r\n endl()\r\n buffer.flush()\r\n }\r\n }\r\n\r\n}\r\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\r\n\r\nobject C {\r\n\r\n import java.io._\r\n\r\n val out: OutputPrinter = new StringOutputPrinter\r\n //val out: OutputPrinter = new OutputPrinter\r\n val input = new InputReader(new InputStreamReader(System.in))\r\n // val input = new InputReader(new StringReader(\r\n // \"\"\"4\r\n // 7\r\n // 1 2 1 2 1 2 1\r\n // 6 8 3 1 5 1 5\r\n // 10\r\n // 1 1 1 2 2 2 2 3 3 3\r\n // 3435 3014 2241 2233 2893 2102 2286 2175 1961 2567\r\n // 6\r\n // 3 3 3 3 3 3\r\n // 5 9 6 7 9 7\r\n // 1\r\n // 1\r\n // 3083\r\n // \"\"\"))\r\n\r\n def main(args: Array[String]): Unit = {\r\n val startTime = System.currentTimeMillis()\r\n\r\n val executor = new Solution1\r\n executor.solve()\r\n\r\n out.flush()\r\n val elapsed = System.currentTimeMillis() - startTime\r\n //println(s\"Elapsed: $elapsed\")\r\n }\r\n\r\n\r\n class Solution1 {\r\n\r\n def solve(): Unit = {\r\n val tasks = input.nextInt\r\n for (_ <- 0 until tasks) {\r\n val n = input.nextInt\r\n val st = new Array[Int](n)\r\n input.forInts(n) { (idx, u) => st(idx) = u - 1 }\r\n val ub = Array.fill[List[Int]](n)(Nil)\r\n input.forInts(n) { (idx, s) =>\r\n val un = st(idx)\r\n ub(un) ::= s\r\n }\r\n val uns = ub.filter(_.nonEmpty).map { l =>\r\n val arr = new ArrayBuffer[Long](l.length)\r\n l.foreach(arr += _.toLong)\r\n arr.sortBy(-_)\r\n var s = 0L\r\n for (len <- arr.indices) {\r\n s += arr(len)\r\n arr(len) = s\r\n }\r\n arr\r\n }\r\n for (k <- 1 to n) {\r\n var s = 0L\r\n uns.foreach { u =>\r\n val teams = u.length / k\r\n if (teams > 0) {\r\n s += u(teams * k - 1)\r\n }\r\n }\r\n out.print(s.toString)\r\n out.print(' ')\r\n }\r\n out.flush()\r\n }\r\n }\r\n }\r\n\r\n\r\n\r\n // ===========================================================================\r\n // --------- TOOLS ---------------------------------------------------------\r\n // ===========================================================================\r\n\r\n class InputReader(reader: Reader) {\r\n\r\n import java.io.BufferedReader\r\n import java.util.StringTokenizer\r\n\r\n private val buffer = new BufferedReader(reader)\r\n private var parser: StringTokenizer = _\r\n\r\n private def next = {\r\n if (parser == null || !parser.hasMoreElements) {\r\n parser = new StringTokenizer(buffer.readLine)\r\n }\r\n parser.nextToken\r\n }\r\n\r\n def endl(): Unit = {\r\n parser = null\r\n }\r\n\r\n def nextByte = next.toByte\r\n\r\n def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)\r\n\r\n def nextInt = next.toInt\r\n\r\n def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)\r\n\r\n def nextLong = next.toLong\r\n\r\n def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)\r\n\r\n def nextDouble = next.toDouble\r\n\r\n def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)\r\n\r\n def nextString = next\r\n\r\n def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)\r\n\r\n private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {\r\n for (index <- 0 until num) op(index, readOp)\r\n }\r\n }\r\n\r\n class OutputPrinter {\r\n private val buffer = new StringBuilder() // faster if exists\r\n\r\n def print(c: Char): Unit = {}\r\n\r\n def print(i: Int): Unit = {}\r\n\r\n def print(s: String): Unit = {}\r\n\r\n def endl(): Unit = {}\r\n\r\n def flush(): Unit = {}\r\n }\r\n\r\n class StringOutputPrinter(capacity: Int = 1024) extends OutputPrinter {\r\n private val buffer = new StringBuilder(capacity)\r\n\r\n override def print(c: Char): Unit = buffer.append(c)\r\n\r\n override def print(i: Int): Unit = buffer.append(i)\r\n\r\n override def print(s: String): Unit = buffer.append(s)\r\n\r\n override def endl(): Unit = buffer.append(\"\\n\")\r\n\r\n override def flush(): Unit = {\r\n println(buffer.result())\r\n buffer.clear()\r\n }\r\n }\r\n\r\n}\r\n"}, {"source_code": "\r\nobject C {\r\n\r\n import java.io._\r\n\r\n val out: OutputPrinter = new StringOutputPrinter\r\n //val out: OutputPrinter = new OutputPrinter\r\n val input = new InputReader(new InputStreamReader(System.in))\r\n // val input = new InputReader(new StringReader(\r\n // \"\"\"4\r\n //7\r\n //1 2 1 2 1 2 1\r\n //6 8 3 1 5 1 5\r\n //10\r\n //1 1 1 2 2 2 2 3 3 3\r\n //3435 3014 2241 2233 2893 2102 2286 2175 1961 2567\r\n //6\r\n //3 3 3 3 3 3\r\n //5 9 6 7 9 7\r\n //1\r\n //1\r\n //3083\r\n //\"\"\"))\r\n\r\n def main(args: Array[String]): Unit = {\r\n val startTime = System.currentTimeMillis()\r\n\r\n val executor = new Solution1\r\n executor.solve()\r\n\r\n out.flush()\r\n val elapsed = System.currentTimeMillis() - startTime\r\n //println(s\"Elapsed: $elapsed\")\r\n }\r\n\r\n\r\n class Solution1 {\r\n\r\n import scala.collection.mutable.ArrayBuffer\r\n\r\n def solve(): Unit = {\r\n val tasks = input.nextInt\r\n for (_ <- 0 until tasks) {\r\n val n = input.nextInt\r\n val st = new Array[Int](n)\r\n input.forInts(n) { (idx, u) => st(idx) = u - 1 }\r\n val ub = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())\r\n input.forInts(n) { (idx, s) =>\r\n val un = st(idx)\r\n ub(un) += s\r\n }\r\n val uns = ub.filter(_.nonEmpty).map(_.sortBy(s => -s))\r\n uns.foreach { u =>\r\n var s = 0\r\n for (len <- u.indices) {\r\n s += u(len)\r\n u(len) = s\r\n }\r\n }\r\n for (k <- 1 to n) {\r\n var s = 0\r\n uns.foreach { u =>\r\n val teams = u.length / k\r\n if (teams > 0) {\r\n s += u(teams * k - 1)\r\n }\r\n }\r\n out.print(s)\r\n out.print(' ')\r\n }\r\n out.flush()\r\n }\r\n }\r\n }\r\n\r\n\r\n\r\n // ===========================================================================\r\n // --------- TOOLS ---------------------------------------------------------\r\n // ===========================================================================\r\n\r\n class InputReader(reader: Reader) {\r\n\r\n import java.io.BufferedReader\r\n import java.util.StringTokenizer\r\n\r\n private val buffer = new BufferedReader(reader)\r\n private var parser: StringTokenizer = _\r\n\r\n private def next = {\r\n if (parser == null || !parser.hasMoreElements) {\r\n parser = new StringTokenizer(buffer.readLine)\r\n }\r\n parser.nextToken\r\n }\r\n\r\n def endl(): Unit = {\r\n parser = null\r\n }\r\n\r\n def nextByte = next.toByte\r\n\r\n def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)\r\n\r\n def nextInt = next.toInt\r\n\r\n def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)\r\n\r\n def nextLong = next.toLong\r\n\r\n def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)\r\n\r\n def nextDouble = next.toDouble\r\n\r\n def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)\r\n\r\n def nextString = next\r\n\r\n def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)\r\n\r\n private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {\r\n for (index <- 0 until num) op(index, readOp)\r\n }\r\n }\r\n\r\n class OutputPrinter {\r\n private val buffer = new StringBuilder() // faster if exists\r\n\r\n def print(c: Char): Unit = {}\r\n\r\n def print(i: Int): Unit = {}\r\n\r\n def print(s: String): Unit = {}\r\n\r\n def endl(): Unit = {}\r\n\r\n def flush(): Unit = {}\r\n }\r\n\r\n class StringOutputPrinter(capacity: Int = 1024) extends OutputPrinter {\r\n private val buffer = new StringBuilder(capacity)\r\n\r\n override def print(c: Char): Unit = buffer.append(c)\r\n\r\n override def print(i: Int): Unit = buffer.append(i)\r\n\r\n override def print(s: String): Unit = buffer.append(s)\r\n\r\n override def endl(): Unit = buffer.append(\"\\n\")\r\n\r\n override def flush(): Unit = {\r\n println(buffer.result())\r\n buffer.clear()\r\n }\r\n }\r\n\r\n}\r\n"}], "src_uid": "437ab04bd029db32ceba31becbe06722"} {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n val Array(n, m) = readInts\n val students = for(_ <- 1 to n) yield reader.readLine()\n val bestGrades = students.transpose.map(_.max)\n def ans = students.count(_.zip(bestGrades).exists(x => x._1 == x._2))\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.ListBuffer\n\n\nobject Solver {\n def main(args: Array[String]) {\n var input = Console.readLine.split(\" \").map(_.toInt)\n var n = input(0); var m = input(1)\n\n var data: ListBuffer[Int] = new ListBuffer()\n for ( i <- 0 until m ) data.append(0)\n\n var estimates = List[Seq[Int]]()\n \n for (i <- 0 until n) {\n estimates = estimates ++ Array(Console.readLine.map(_.toInt - '0'.toInt))\n for (j <- 0 until m) \n if (estimates(i)(j) > data(j))\n data(j) = estimates(i)(j)\n }\n\n var count = 0\n for (i <- 0 until n) {\n var continue = true\n for (j <- 0 until m)\n if (continue && estimates(i)(j) == data(j)) { count += 1; continue = false; }\n }\n\n println(count)\n }\n}\n"}, {"source_code": "object Codeforces extends App {\n val in = new java.util.Scanner(System.in)\n val n = in.nextInt()\n val m = in.nextInt()\n in.nextLine()\n var grade = Array.ofDim[Int](n, m);\n for (i <- 0 until n) {\n var cur = in.nextLine()\n for (j <- 0 until m) {\n grade(i)(j) = cur(j) - '0'\n }\n }\n var student = Array.ofDim[Int](n);\n for (i <- 0 until m) {\n var best = -1\n for (j <- 0 until n) {\n if (grade(j)(i) > best) {\n best = grade(j)(i)\n }\n }\n for (j <- 0 until n) {\n if (grade(j)(i) == best) {\n student(j) += 1\n }\n }\n }\n var cnt = 0\n for (i <- 0 until n) {\n if (student(i) > 0) {\n cnt += 1\n }\n }\n println(cnt) \n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _152A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val m = next.toInt\n val a = (1 to n).map(i => next.map(ch => ch - '0').toArray).toArray\n\n val colMax = (0 until m).map(j => (0 until n).map(i => a(i)(j)).max).toArray\n val cb = (0 until n).filter(i => (0 until m).exists(j => a(i)(j) == colMax(j)))\n println(cb.size)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val data = (1 to n).map(_ => in.next())\n val max = (0 until m).map(i => data.map(_(i)).max)\n println(data.count(el => el.zip(max).exists(t => t._1 == t._2)))\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P152A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val Array(n, m) = sc.nextLine.split(\" \").map(_.toInt)\n val g = new Array[Array[Int]](n)\n for (i <- 0 until n)\n g(i) = sc.nextLine.toCharArray.map(_.asDigit)\n val s = Array.fill(n)(false)\n for (j <- 0 until m) {\n val max = (0 until n).map(g(_)(j)).max\n for (i <- 0 until n)\n if (g(i)(j) == max) s(i) = true\n }\n\n val answer = s.filter(identity[Boolean]).size\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "import collection.immutable.IndexedSeq\nimport java.io.BufferedReader\nimport java.util.StringTokenizer\n\n/**\n *\n * @author Vladislav Isenbaev (vladislav.isenbaev@odnoklassniki.ru)\n */\n\nobject CF152A extends App {\n\n def solve() {\n val n = nextInt()\n val m = nextInt()\n val lines = for (i <- 0 until n) yield in.nextLine()\n val courses = lines.map(_.map(_ - '0')).transpose\n val cool = new Array[Boolean](n)\n for (marks <- courses) {\n val max = marks.max\n for (i <- 0 until n if marks(i) == max) cool(i) = true\n }\n println(cool.count(identity[Boolean]))\n }\n\n class Tokenizer(in: BufferedReader, pattern: String = \" \\t\\n\\r\\f\") {\n private def tokenizer = new StringTokenizer(_: String, pattern)\n\n var st: StringTokenizer = tokenizer(\"\")\n\n def nextLine() = in.readLine()\n\n def nextToken(): String = {\n while (!st.hasMoreTokens) {\n val line = nextLine()\n if (line == null) return null\n st = tokenizer(line)\n }\n st.nextToken()\n }\n\n def next[A](f: String => A): A = f(nextToken())\n }\n\n implicit val in = new Tokenizer(Console.in)\n implicit def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)\n implicit def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)\n implicit def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)\n implicit def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))\n implicit def nextString()(implicit t: Tokenizer) = t.next(identity[String])\n\n def nextSeq[A](len: Int = nextInt())(implicit c: () => A): Seq[A] = for (i <- 0 until len) yield c()\n\n solve()\n\n}"}, {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n val Array(n, m) = readInts\n val students = for(_ <- 1 to n) yield reader.readLine()\n val bestGrades = students.transpose.map(_.max)\n def ans = students.count(_.view.zip(bestGrades.view).exists(x => x._1 == x._2))\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val nm = readLine().split(\" \").map(_.toInt)\n val n = nm(0)\n val m = nm(1)\n val marks = (1 to n).map(_ => readLine().map(c => (c - '0').toInt))\n val maxes = (0 until m).map(i => marks.map(_(i)).max)\n val count = marks.count(row => row.zip(maxes).count(t => t._1 == t._2) > 0)\n println(count)\n }\n}"}], "negative_code": [], "src_uid": "41bdb08253cf5706573f5d469ab0a7b3"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n out.println(N)\n out.println(map(N)(_ => 1).mkString(\" \"))\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object Main {\n\n def main(args: Array[String]) {\n val std = scala.io.StdIn\n val n = std.readLine().toInt\n println(n)\n for (i <- 0 until n) {\n print(1)\n if (i + 1 < n) {\n print(\" \")\n }\n }\n }\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject NumberSplit {\n\n\n @tailrec\n def step(n: Long, acc: Long): (Long, Long) = {\n if (acc == 0) (n, 1)\n else if (n % acc == 0) (n / acc, acc)\n else step(n, acc - 1)\n }\n\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readLine().toLong\n val s = if (n < 9) n - 1 else 9\n val (times, n1) = step(n, s)\n val res = List.fill(times.toInt)(n1)\n println(res.length)\n println(res.mkString(\" \"))\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) : Unit = {\n val n = readInt\n println(n)\n println(List.fill(n)(1).mkString(\" \"))\n }\n}"}], "negative_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject NumberSplit {\n\n\n @tailrec\n def step(n: Long, res: List[Int], acc: Int): List[Int] = {\n if (n == 0 || acc == 0) {\n res\n } else {\n val ki = n / acc\n val kiRes = n % acc\n step(kiRes, res ++ List.fill(ki.toInt)(acc), acc - 1)\n }\n }\n\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readLine().toLong\n val res = step(n, List(), 9)\n println(res.length)\n println(res.mkString(\" \"))\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) : Unit = {\n val n = readInt\n println(1)\n println(List.fill(n)(1).mkString(\" \"))\n }\n}"}, {"source_code": "import scala.io.StdIn.readInt\n\nobject MyModule {\n def main(args: Array[String]) : Unit = {\n val n = readInt\n println(1)\n println(n)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) : Unit = {\n val n = readInt\n println(List.fill(n)(1).mkString(\" \"))\n }\n}"}], "src_uid": "7c483498f497f4291e3d33375c0ebd53"} {"source_code": "import java.util.Scanner\nimport java.util.StringTokenizer\n\nobject CF551C extends App {\n var token = new StringTokenizer(\"\")\n def next() = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n\n val n = next.toInt\n val m = next.toLong\n val a = (1 to n).map(_ => next.toLong)\n\n def ok(timeLimit: Long): Boolean = {\n var um, rd: Long = 0\n for (i <- n - 1 to 0 by -1) {\n if (a(i) <= rd)\n rd -= a(i)\n else {\n val each = timeLimit - i - 1\n if (each <= 0)\n return false\n val need = a(i) - rd\n val take = (need - 1) / each + 1\n um += take\n rd = take * each - need\n }\n }\n um <= m\n }\n\n var (le, ri) = (0.toLong, 1e15.toLong)\n while (le < ri) {\n val mid = (le + ri) / 2;\n if (ok(mid))\n ri = mid\n else\n le = mid + 1\n }\n println(le)\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject CF551C extends App {\n var in = new Scanner(System.in)\n val n = in.nextInt()\n val m = in.nextLong()\n val a = (1 to n).map(_ => in.nextLong())\n var (le, ri) = (0.toLong, 1e15.toLong)\n while (le < ri) {\n val mid = (le + ri) / 2;\n var um, rd: Long = 0\n var ok = true\n for (i <- n - 1 to 0 by -1) {\n if (a(i) <= rd)\n rd -= a(i)\n else {\n val each = mid - i - 1\n if (each <= 0)\n ok = false\n else {\n val need = a(i) - rd\n val take = (need - 1) / each + 1\n um += take\n rd = take * each - need\n }\n }\n }\n if (ok && um <= m)\n ri = mid\n else\n le = mid + 1\n }\n println(le)\n}"}, {"source_code": "import java.util.Scanner\nimport java.util.StringTokenizer\n\n\nobject CF551C extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n\n val n = next.toInt\n val m = next.toLong\n val a = (1 to n).map(_ => next.toLong)\n \n // var in = new Scanner(System.in)\n // val n = in.nextInt()\n // val m = in.nextLong()\n // val a = (1 to n).map(_ => in.nextLong())\n var (le, ri) = (0.toLong, 1e15.toLong)\n while (le < ri) {\n val mid = (le + ri) / 2;\n var um, rd: Long = 0\n var ok = true\n for (i <- n - 1 to 0 by -1) {\n if (a(i) <= rd)\n rd -= a(i)\n else {\n val each = mid - i - 1\n if (each <= 0)\n ok = false\n else {\n val need = a(i) - rd\n val take = (need - 1) / each + 1\n um += take\n rd = take * each - need\n }\n }\n }\n if (ok && um <= m)\n ri = mid\n else\n le = mid + 1\n }\n println(le)\n}"}], "negative_code": [], "src_uid": "ed0a8a10e03de931856e287f9e650e1a"} {"source_code": "import scala.io.StdIn._\r\nimport scala.io._\r\nimport scala.math.abs;\r\nobject _1551A {\r\n\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt()\r\n while (t > 0) {\r\n t -= 1\r\n val n = readInt()\r\n val temp = n / 3\r\n if(n % 3 == 0)println(temp + \" \" + temp)\r\n else if(n % 3 == 1)println((temp + 1) + \" \" + temp)\r\n else println(temp + \" \" + (temp + 1))\r\n }\r\n\r\n def ni(): Array[Int] = {\r\n readLine().split(\" \").map(_.toInt)\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) = {\n def rep[A](n: Int)(f: => A) { if (n > 0) { f; rep(n - 1)(f) } }\n\n rep(StdIn.readInt) {\n\n def f(i: Int) {\n var twos = i / 3\n var ones = twos\n\n if (i % 3 == 2) twos += 1\n else if (i % 3 == 1) ones += 1\n\n println(s\"${ones} ${twos}\")\n }\n f(StdIn.readInt)\n\n }\n }\n}\n"}, {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n\r\n val (d, r) = (n / 3, n % 3)\r\n val (c1, c2) = (d + (if (r == 1) 1 else 0), d + (if (r == 2) 1 else 0))\r\n\r\n println(s\"$c1 $c2\")\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "71335a9489f0985f4e16435b14d6a34a"} {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Main {\n\n private def readInts: Array[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n\n private case class Graph(edges: Array[Array[Boolean]])\n\n private case class Edge(a: Int, b: Int, c: Int)\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts\n val tGraphs = Array.ofDim[Graph](m + 2)\n val edges = Range(0, m).map { _ =>\n val Array(x, y, z) = readInts\n Edge(x, y, z)\n }.toList\n\n edges.groupBy(_.c).foreach {\n case (index, es) =>\n val m = Array.ofDim[Boolean](n + 2, n + 2).map(_.map(_ => false))\n es.foreach { e => {\n m(e.a)(e.b) = true\n m(e.b)(e.a) = true\n }\n }\n tGraphs(index) = Graph(m)\n }\n\n val graphs = tGraphs.toList.filter(_ != null)\n\n val q = StdIn.readInt()\n for (_ <- Range(0, q)) {\n val Array(u, v) = readInts\n println(graphs.count(g => wave(g, u, v)))\n }\n }\n\n private def wave(g: Graph, start: Int, end: Int): Boolean = {\n val visited = mutable.Set[Int]()\n val toVisit = mutable.Queue[Int](start)\n\n while (toVisit.nonEmpty) {\n val next = toVisit.dequeue()\n if (next == end) return true\n visited.add(next)\n val nexts: Array[Int] = g.edges(next).zipWithIndex.filter(_._1).map(_._2).filter(!visited.contains(_))\n if (nexts contains end) return true\n toVisit.enqueue(nexts: _*)\n }\n false\n }\n}\n", "positive_code": [{"source_code": "\nimport scala.math._\nimport scala.collection.mutable.Map\n\nobject Graph extends App {\n \n type Vertex = Int\n type Graph = Map[Int, Map[Int, List[Vertex]]]\n type traversableGraph = Map[Int, List[Vertex]]\n def readGraph(n : Int, m : Int) : Graph = {\n val graph : Graph = Map[Int, Map[Int, List[Vertex]]]()\n var v : List[Int] = Nil\n \n for(i <- 1 to m) {\n graph(i) = Map[Int, List[Vertex]]()\n for(j <- 1 to n)\n graph(i)(j) = Nil\n }\n \n \n for(i <- 0 until m) {\n v = readLine.split(\" \").map(_.toInt).toList\n \n graph(v(2))((v(0))) ++= List(v(1))\n graph(v(2))((v(1))) ++= List(v(0))\n \n } \n \n graph\n }\n \n def DFS(start : Vertex, g : traversableGraph) : List[Vertex] = {\n \n def DFS0(v: Vertex, visited: List[Vertex]): List[Vertex] = {\n if (visited.contains(v))\n visited\n else {\n val neighbours:List[Vertex] = g(v) filterNot visited.contains \n neighbours.foldLeft(v :: visited)((b,a) => DFS0(a,b))\n } \n }\n \n DFS0(start, List[Vertex]())\n } \n \n val dim = readLine.split(\" \").map(_.toInt)\n val n = dim(0)\n val m = dim(1)\n val graph = readGraph(n, m)\n \n val q = readInt\n var u, v : Int = 0\n var qR : Array[Int] = Array[Int]()\n \n for(i <- 0 until q) {\n qR = readLine.split(\" \").map(_.toInt)\n u = qR(0)\n v = qR(1)\n \n println((1 to m).map(x => if (DFS(u, graph(x)).contains(v)) 1 else 0).sum)\n }\n \n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\n\nobject Main extends App {\n\n class UF(card: Int) {\n val p = ArrayBuffer.range(0, card+1)\n\n def find(at: Int): Int = {\n if(p(at) == at) return at\n p(at) = find(p(at))\n return p(at)\n }\n\n def unite(from: Int, to: Int): Unit = {\n p(find(from)) = find(to)\n }\n\n def isConn(from: Int, to: Int): Boolean = {\n find(from) == find(to)\n }\n }\n\n\n val Array(n,m) = readLine.split(\" \").map(_.toInt)\n val dots = (1 to m).map({ _ =>\n val Array(a,b,c) = readLine.split(\" \").map(_.toInt)\n (a,b,c)\n })\n\n val colors = dots.map({ case (_,_,c) => c }).toSet.map((color: Int) => (color, new UF(n))).toMap\n\n dots.foreach({ case (a,b,c) =>\n colors.get(c).get.unite(a,b)\n })\n\n val q = readInt\n (1 to q).foreach({ _ => \n val Array(u,v) = readLine.split(\" \").map(_.toInt)\n println(colors.map(_._2).filter(_.isConn(u,v)).size)\n })\n\n}"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\n/** B. Mr. Kitayuta's Colorful Graph\n * http://codeforces.com/contest/505/problem/B\n * @author Yuichiroh Matsubayashi\n * Created on 15/01/19.\n */\nobject P505B {\n\n case class Edge(a: Int, b: Int, c: Int)\n\n case class Query(u: Int, v: Int)\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = StdIn.readLine().split(\" \").map(_.toInt)\n\n val cs = mutable.Set[Int]()\n\n val edges = (Map[Int, Seq[(Int, Int)]]() /: (1 to m)) { (map, i) =>\n val Array(a, b, c) = StdIn.readLine().split(\" \").map(_.toInt)\n cs.add(c)\n map + (a -> (map.getOrElse(a, Seq()) :+(b, c))) + (b -> (map.getOrElse(b, Seq()) :+(a, c)))\n }\n\n\n val q = StdIn.readInt()\n val queries = (1 to q) map { i =>\n val Array(u, v) = StdIn.readLine().split(\" \").map(_.toInt)\n Query(u, v)\n }\n\n def search(start: Int, goal: Int, color: Int, visited: List[Int] = Nil): Boolean = edges.getOrElse(start, Seq()).exists { bc =>\n if (bc._2 == color) {\n if (visited.contains(bc._1)) false\n else if (bc._1 == goal) true\n else search(bc._1, goal, color, start :: visited)\n }\n else false\n }\n\n queries.map { q => cs.count { c => search(q.u, q.v, c) == true } }.foreach(println)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val data = scala.io.Source.stdin.getLines()\n val Array(n, m) = data.next().split(\" \").map(_.toInt)\n val edges = Range(0, m).map(_ => data.next().split(\" \").map(_.toInt)).groupBy(_(2)).map {\n case(color, data) => color -> data.foldLeft(scala.collection.mutable.Set.empty[scala.collection.mutable.Set[Int]]) {\n case (acc, el) =>\n val f1 = acc.find(_.contains(el(0)))\n val f2 = acc.find(_.contains(el(1)))\n if (f1.isEmpty && f2.isEmpty) acc += scala.collection.mutable.Set(el(0), el(1))\n else {\n if (f1.isEmpty) {\n acc -= f2.get\n acc + (f2.get + el(0))\n }\n else if (f2.isEmpty) {\n acc -= f1.get\n acc + (f1.get + el(1))\n }\n else {\n f1.get ++= f2.get\n acc -= f1.get\n acc -= f2.get\n acc + (f1.get ++ f2.get)\n }\n }\n }\n }.values.toList\n\n Range(0, data.next().toInt).foreach {_ =>\n val Array(a, b) = data.next().split(\" \").map(_.toInt)\n println(edges.count{\n case(sets) => sets.exists(t => t.contains(a) && t.contains(b))\n })\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val data = scala.io.Source.stdin.getLines()\n val Array(n, m) = data.next().split(\" \").map(_.toInt)\n val edges = Range(0, m).map(_ => data.next().split(\" \").map(_.toInt)).groupBy(_(2)).map {\n case(color, data) => color -> data.foldLeft(scala.collection.mutable.Set.empty[scala.collection.mutable.Set[Int]]) {\n case (acc, el) =>\n val f1 = acc.find(_.contains(el(0)))\n val f2 = acc.find(_.contains(el(1)))\n if (f1.isEmpty && f2.isEmpty) acc += scala.collection.mutable.Set(el(0), el(1))\n else {\n if (f1.isEmpty)\n f2.get += el(0)\n else if (f2.isEmpty)\n f1.get += el(1)\n else {\n f1.get ++= f2.get\n acc -= f2.get\n }\n }\n acc\n }\n }.values.toList\n\n Range(0, data.next().toInt).foreach {_ =>\n val Array(a, b) = data.next().split(\" \").map(_.toInt)\n println(edges.count{\n case(sets) => sets.exists(t => t.contains(a) && t.contains(b))\n })\n }\n}"}, {"source_code": "object Solution extends App {\n val data = scala.io.Source.stdin.getLines()\n val Array(n, m) = data.next().split(\" \").map(_.toInt)\n val edges = Range(0, m).map(_ => data.next().split(\" \").map(_.toInt)).groupBy(_(2)).map {\n case(color, data) => color -> data.foldLeft(Set.empty[scala.collection.mutable.Set[Int]]) {\n case (acc, el) =>\n val f1 = acc.find(_.contains(el(0)))\n val f2 = acc.find(_.contains(el(1)))\n if (f1.isEmpty && f2.isEmpty) acc + scala.collection.mutable.Set(el(0), el(1))\n else {\n if (f1.isEmpty) {\n f2.get += el(0)\n acc\n }\n else if (f2.isEmpty) {\n f1.get += el(1)\n acc\n }\n else {\n f1.get ++= f2.get\n acc - f2.get\n }\n }\n }\n }.values.toList\n\n Range(0, data.next().toInt).foreach {_ =>\n val Array(a, b) = data.next().split(\" \").map(_.toInt)\n println(edges.count{\n case(sets) => sets.exists(t => t.contains(a) && t.contains(b))\n })\n }\n}"}], "src_uid": "e3ec343143419592e73d4be13bcf1cb5"} {"source_code": "import scala.io.StdIn._\n\nobject ModuloSum {\n\n def add(current: Seq[Int],v: Int, m: Int) = {\n def mapper(i: Int) = (i+v)%m\n ((current.map(mapper) :+ v%m) ++ current).distinct\n }\n def main (args: Array[String]) {\n val l1 = readLine().split(\" \")\n val N = l1(0).toInt\n val M = l1(1).toInt\n val l2 = readLine().split(\" \").map(_.toInt)\n if (N>=M) println(\"YES\")\n else {\n val t1 = l2.foldLeft(Seq[Int]()) {\n (B, i) => add(B, i, M)\n }\n if(t1.contains(0)) println(\"YES\") else println(\"NO\")\n }\n }\n}\n", "positive_code": [{"source_code": "//package round319.b\n\nimport java.util.Scanner\n\n\n/*\nvar n, m, i, j, cur, num: longint;\n cnt: array [0..1010] of longint;\n\nbegin\n fillchar(cnt, sizeof(cnt), 0);\n readln(n, m);\n for i := 1 to n do\n begin\n read(num);\n num := num mod m;\n for j := 0 to m - 1 do\n begin\n if ((cnt[j] = 0) or (cnt[j] = i)) then\n continue;\n cur := num + j;\n if (cur >= m) then\n cur := cur - m;\n if (cnt[cur] = 0) then\n cnt[cur] := i;\n end;\n cnt[num] := i;\n if (cnt[0] <> 0) then\n begin\n writeln('YES');\n halt;\n end;\n end;\n writeln('NO');\nend.\n */\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n val m = sc.nextInt\n val cnt = Array.fill(1010)(0)\n\n for(i <- 1 to n) {\n val num = sc.nextInt % m\n for(j <- 0 until m) {\n if(cnt(j) != 0 && cnt(j) != i) {\n val cur = (num + j) % m\n if(cnt(cur) == 0) {\n cnt(cur) = i\n }\n }\n }\n cnt(num) = i\n if(cnt(0) != 0) {\n println(\"YES\")\n System.exit(0)\n }\n }\n\n println(\"NO\")\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val data: Array[Int] = in.next().split(\" \").map(_.toInt % m)\n val groupped = data.groupBy(i => i).map(i => (i._1, i._2.length)).toArray\n\n def solution(data: Array[(Int, Int)], index: Int, sum: Int): Boolean = {\n if (sum == 0) true\n else if (index == data.length) false\n else\n solution(data, index + 1, sum) || (1 to groupped(index)._2).map(i => (i * groupped(index)._1) % m).toSet.exists{\n j => if (sum == -1) solution(data, index + 1, j) else solution(data, index + 1, (sum + j) % m)\n }\n }\n\n if (solution(groupped, 0, -1))\n println(\"YES\")\n else\n println(\"NO\")\n\n}"}, {"source_code": "import scala.io.StdIn._\nobject ModuloSum {\n def add(current: Seq[Int],v: Int, m: Int) = {\n def mapper(i: Int) = (i+v)%m\n ((current.map(mapper) :+ v) ++ current).distinct\n }\n def main (args: Array[String]) {\n val l1 = readLine().split(\" \")\n val N = l1(0).toInt\n val M = l1(1).toInt\n val l2 = readLine().split(\" \").map(_.toInt%M)\n val result = (if(N>=M) Seq(0) else l2.foldLeft(Seq[Int]()) { (B, i) => add(B, i, M)}).toSet(0)\n if(result) println(\"YES\") else println(\"NO\")\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\nobject ModuloSum {\n def main (args: Array[String]) {\n val l1 = readLine().split(\" \")\n val N = l1(0).toInt\n val M = l1(1).toInt\n val l2 = readLine().split(\" \").map(_.toInt%M)\n def add(current: Seq[Int],v: Int) = {\n def mapper(i: Int) = (i+v)%M\n ((current.map(mapper) :+ v) ++ current).distinct\n }\n val result = (if(N>=M) Seq(0) else l2.foldLeft(Seq[Int]())(add)).toSet(0)\n if(result) println(\"YES\") else println(\"NO\")\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\nobject ModuloSum {\n def main (args: Array[String]) {\n val l1 = readLine().split(\" \")\n val N = l1(0).toInt\n val M = l1(1).toInt\n val l2 = readLine().split(\" \").map(_.toInt%M)\n def add(current: Seq[Int],v: Int) = ((current.map(i => (i+v)%M) :+ v) ++ current).distinct\n if((if(N>=M) Seq(0) else l2.foldLeft(Seq[Int]())(add)).toSet(0)) println(\"YES\") else println(\"NO\")\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val a = new Array[Int](n)\n val set = new mutable.HashSet[Int]()\n for (i <- 0 until n) {\n a(i) = nextInt % m\n for (s <- set.clone()) {\n set.add((s + a(i)) % m)\n }\n set.add(a(i))\n if (set.contains(0)) {\n out.println(\"YES\")\n return 0\n }\n }\n out.println(\"NO\")\n return 0\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val A = readLine().split(\" \").map(_.toLong)\n\n if (n > m) println(\"YES\")\n else {\n val rest = Array.ofDim[Boolean](n + 1, m)\n\n for (i <- A.indices) {\n rest(i + 1)((A(i) % m).toInt) = true\n if (rest(i + 1)(0)) {\n println(\"YES\")\n System.exit(0)\n }\n }\n\n for {\n i <- 0 until n\n r <- 0 until m\n } {\n if (rest(i)(r)) {\n rest(i + 1)(((r + A(i)) % m).toInt) = true\n rest(i + 1)(r) = true\n\n if (rest(i + 1)(0)) {\n println(\"YES\")\n System.exit(0)\n }\n }\n }\n\n println(\"NO\")\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io._\nimport scala.io.StdIn._\n\nobject HelloWorld {\n def add(seqs:Seq[Int], v:Int, m:Int) : Seq[Int] = {\n ((seqs.map( e => (e+v)%m ) :+ v%m) ++ seqs).distinct\n }\n def main(args:Array[String]) {\n //val sc = new Scanner(System.in)\n val r = readLine().split(\" \").map(_.toInt)\n val n = r(0)\n val m = r(1)\n val nums = readLine().split(\" \").map(_.toInt)\n if(n>=m)println(\"YES\")\n else\n {\n val seq = nums.foldLeft( Seq[Int]() )( add(_:Seq[Int], _:Int, m) )\n if(seq.contains(0))println(\"YES\")\n else println(\"NO\")\n }\n }\n}"}, {"source_code": "import java.io.InputStream\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport java.io.FileInputStream\nimport java.io.PrintStream\nimport java.io.FileOutputStream\n\nobject CF577B {\n\n class InputReader(val stream: InputStream) {\n var st: StringTokenizer = new StringTokenizer(\"\")\n val reader = new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next(): String = {\n while (!st.hasMoreTokens()) {\n val currentLine = reader.readLine\n st = new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt(): Int = {\n return next.toInt\n }\n\n def nextLong(): Long = {\n return next.toLong\n }\n\n def nextDouble: Double = {\n return next.toDouble\n }\n }\n\n def solve(in: InputReader, out: PrintStream): Unit = {\n val n = in.nextInt()\n val m = in.nextInt()\n val a = Array.fill(n)(in.nextInt())\n val modM : Array[Boolean] = Array.fill(m)(false)\n for( x <- a) {\n val mask = Array.fill(m)(false)\n for( mod <- m-1 to 0 by -1)\n if ( modM(mod) == true)\n mask((mod + x) % m) = true\n mask(x %m) = true\n for(mod <- 0 to m-1) modM(mod) = modM(mod) || mask(mod)\n if ( modM(0) ) {\n out.println(\"YES\")\n return\n }\n }\n out.println(\"NO\")\n }\n\n def main(args: Array[String]): Unit = {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n var in = new InputReader(System.in)\n var out = System.out\n if ( !isOnlineJudge ) {\n in = new InputReader(new FileInputStream(\"input.txt\"))\n out = new PrintStream(new FileOutputStream(\"output.txt\"))\n }\n solve(in,out)\n }\n\n }"}], "negative_code": [{"source_code": "import java.io.InputStream\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport java.io.FileInputStream\nimport java.io.PrintStream\nimport java.io.FileOutputStream\n\nobject CF577B {\n\n class InputReader(val stream: InputStream) {\n var st: StringTokenizer = new StringTokenizer(\"\")\n val reader = new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next(): String = {\n while (!st.hasMoreTokens()) {\n val currentLine = reader.readLine\n st = new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt(): Int = {\n return next.toInt\n }\n\n def nextLong(): Long = {\n return next.toLong\n }\n\n def nextDouble: Double = {\n return next.toDouble\n }\n }\n\n def solve(in: InputReader, out: PrintStream): Unit = {\n val n = in.nextInt()\n val m = in.nextInt()\n val a = Array.fill(n)(in.nextInt())\n val modM : Array[Boolean] = Array.fill(m)(false)\n for( x <- a) {\n for( mod <- 0 to m-1)\n if ( modM(mod) == true)\n modM((mod + x) % m) = true\n modM(x %m) = true\n }\n if ( modM(0) ) out.println(\"YES\") else out.println(\"NO\")\n }\n\n def main(args: Array[String]): Unit = {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n var in = new InputReader(System.in)\n var out = System.out\n if ( !isOnlineJudge ) {\n in = new InputReader(new FileInputStream(\"input.txt\"))\n out = new PrintStream(new FileOutputStream(\"output.txt\"))\n }\n solve(in,out)\n }\n\n }"}, {"source_code": "//package round319.b\n\nimport java.util.Scanner\n\n\n/*\nvar n, m, i, j, cur, num: longint;\n cnt: array [0..1010] of longint;\n\nbegin\n fillchar(cnt, sizeof(cnt), 0);\n readln(n, m);\n for i := 1 to n do\n begin\n read(num);\n num := num mod m;\n for j := 0 to m - 1 do\n begin\n if ((cnt[j] = 0) or (cnt[j] = i)) then\n continue;\n cur := num + j;\n if (cur >= m) then\n cur := cur - m;\n if (cnt[cur] = 0) then\n cnt[cur] := i;\n end;\n cnt[num] := i;\n if (cnt[0] <> 0) then\n begin\n writeln('YES');\n halt;\n end;\n end;\n writeln('NO');\nend.\n */\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n val m = sc.nextInt\n val cnt = Array.fill(1010)(0)\n\n for(i <- 1 to n) {\n val num = sc.nextInt % m\n for(j <- 0 until m) {\n if(cnt(j) != 0) {\n val cur = (num + j) % m\n if(cnt(cur) == 0) {\n cnt(cur) = i\n }\n }\n }\n cnt(num) = i\n if(cnt(0) != 0) {\n println(\"YES\")\n System.exit(0)\n }\n }\n\n println(\"NO\")\n\n}\n"}, {"source_code": "//package round319.b\n\nimport java.util.Scanner\n\n\n/*\nvar n, m, i, j, cur, num: longint;\n cnt: array [0..1010] of longint;\n\nbegin\n fillchar(cnt, sizeof(cnt), 0);\n readln(n, m);\n for i := 1 to n do\n begin\n read(num);\n num := num mod m;\n for j := 0 to m - 1 do\n begin\n if ((cnt[j] = 0) or (cnt[j] = i)) then\n continue;\n cur := num + j;\n if (cur >= m) then\n cur := cur - m;\n if (cnt[cur] = 0) then\n cnt[cur] := i;\n end;\n cnt[num] := i;\n if (cnt[0] <> 0) then\n begin\n writeln('YES');\n halt;\n end;\n end;\n writeln('NO');\nend.\n */\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n val m = sc.nextInt\n val cnt = Array.fill(1010)(0)\n\n for(i <- 1 to n) {\n val num = sc.nextInt % m\n println(\"actual num: \" + num)\n for(j <- 0 until m) {\n if(cnt(j) != 0 && cnt(j) != i) {\n val cur = (num + j) % m\n if(cnt(cur) == 0) {\n cnt(cur) = i\n }\n }\n }\n cnt(num) = i\n if(cnt(0) != 0) {\n println(\"YES\")\n System.exit(0)\n }\n }\n\n println(\"NO\")\n\n}\n"}, {"source_code": "//package round319.b\n\nimport java.util.Scanner\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n val m = sc.nextInt\n\n val a = Array.fill(n)(0)\n\n for(i <- 0 until n) {\n a(i) = sc.nextInt\n }\n\n var mo = Vector.fill(m+1)(0)\n for(i <- 0 until n) {\n val idx = a(i) % m\n mo = mo.updated(idx, mo(idx) + 1)\n }\n\n def canCover(x: Int, moo: Vector[Int]): Boolean = {\n if(x == 0) true\n else if(moo(x) > 0) true\n else {\n for(i <- 0 until m) {\n if(moo(i) > 0) {\n val moo2 = moo.updated(i, moo(i) - 1)\n if(canCover((m + x - moo(i)) % m, moo2)) {\n return true\n }\n }\n }\n false\n }\n }\n\n println(if(canCover(m, mo)) \"YES\" else \"NO\")\n\n// println(mo.toList)\n\n}\n"}, {"source_code": "//package round319.b\n\nimport java.util.Scanner\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n val m = sc.nextInt\n\n val a = Array.fill(n)(0)\n\n for(i <- 0 until n) {\n a(i) = sc.nextInt\n }\n\n var mo = Vector.fill(m+1)(0)\n for(i <- 0 until n) {\n val idx = a(i) % m\n mo = mo.updated(idx, mo(idx) + 1)\n }\n\n def canCover(x: Int, moo: Vector[Int]): Boolean = {\n if(x == 0) true\n else if(moo(x) > 0) true\n else {\n for(i <- 0 until m) {\n if(moo(i) > 0) {\n val moo2 = moo.updated(i, moo(i) - 1)\n if(canCover((m + x - moo(i)) % m, moo2)) {\n return true\n }\n }\n }\n false\n }\n }\n\n println(if(canCover(m, mo)) \"YES\" else \"NO\")\n}\n"}, {"source_code": "//package round319.b\n\nimport java.util.Scanner\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n val m = sc.nextInt\n\n val a = Array.fill(n)(0)\n\n for(i <- 0 until n) {\n a(i) = sc.nextInt\n }\n\n var mo = Vector.fill(m+1)(0)\n for(i <- 0 until n) {\n val idx = a(i) % m\n mo = mo.updated(idx, mo(idx) + 1)\n }\n\n def canCover(x: Int, moo: Vector[Int]): Boolean = {\n if(x % m == 0) true\n else if(moo(x) > 0) true\n else {\n for(i <- 0 until m) {\n if(moo(i) > 0) {\n val moo2 = moo.updated(i, moo(i) - 1)\n if(canCover((m + x - moo(i)) % m, moo2)) {\n return true\n }\n }\n }\n false\n }\n }\n\n println(if(canCover(m, mo)) \"YES\" else \"NO\")\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val data: Array[Int] = in.next().split(\" \").map(_.toInt % m)\n val groupped = data.groupBy(i => i).map(i => (i._1, i._2.length)).toArray\n\n def solution(data: Array[(Int, Int)], index: Int, sum: Int): Boolean = {\n if (sum == 0) true\n else if (index == data.length) false\n else\n solution(data, index + 1, -1) || (1 to groupped(index)._2).map(i => (i * groupped(index)._1) % m).toSet.exists{\n j => if (sum == -1) solution(data, index + 1, j) else solution(data, index + 1, (sum + j) % m)\n }\n }\n\n if (solution(groupped, 0, -1))\n println(\"YES\")\n else\n println(\"NO\")\n\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toLong)\n val data = in.next().split(\" \").map(_.toLong % m)\n val groupped: Map[Long, Long] = data.groupBy(t => t).map(t => (t._1, t._2.length % m))\n val dataArr = Array.ofDim[Long](m.toInt)\n groupped.foreach { case(a, count) =>\n dataArr(a.toInt) = count\n }\n\n val cache = scala.collection.mutable.Map.empty[(Int, Int), Boolean]\n\n def solution(position: Int, sum: Long, took: Boolean): Boolean = {\n if (sum == 0 && took)\n true\n else if (position >= m) false\n else if (dataArr(position) == 0)\n solution(position + 1, sum, took)\n else\n (0l to dataArr(position)).exists{i =>\n solution(position + 1, (sum + i * position) % m, took || i > 0)}\n }\n\n\n if (data.contains(0) || groupped.exists(_._2 == 0) || solution(0, 0, false)) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt % m)\n val groupped: Map[Int, Int] = data.groupBy(t => t).map(t => (t._1, t._2.length % m))\n val dataArr = Array.ofDim[Int](m)\n groupped.foreach { case(a, count) =>\n dataArr(a) = count\n }\n\n val cache = scala.collection.mutable.Map.empty[(Int, Int), Boolean]\n\n def solution(position: Int, sum: Int, took: Boolean): Boolean = {\n if (sum == 0 && took)\n true\n else if (position >= m) false\n else if (dataArr(position) == 0)\n solution(position + 1, sum, took)\n else\n (0 to dataArr(position)).exists{i =>\n solution(position + 1, (sum + i * position) % m, took || i > 0)}\n }\n\n\n if (data.contains(0) || groupped.exists(_._2 == 0) || solution(0, 0, false)) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject ModuloSum {\n\n def add(current: Seq[Int],v: Int, m: Int) = {\n def mapper(i: Int) = (i+v)%m\n ((current.map(mapper) :+ v) ++ current).distinct\n }\n def main (args: Array[String]) {\n val l1 = readLine().split(\" \")\n val N = l1(0).toInt\n val M = l1(1).toInt\n val l2 = readLine().split(\" \").map(_.toInt)\n if (N>=M) println(\"YES\")\n else {\n val t1 = l2.foldLeft(Seq[Int]()) {\n (B, i) => add(B, i, M)\n }\n if(t1.contains(0)) println(\"YES\") else println(\"NO\")\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val A = readLine().split(\" \").map(_.toLong)\n\n if (n > m) println(\"YES\")\n else {\n val rest = Array.ofDim[Boolean](n + 1, m)\n\n for (i <- A.indices) {\n rest(i + 1)((A(i) % m).toInt) = true\n }\n\n for {\n i <- 0 until n\n r <- 0 until m\n } {\n if (rest(i)(r)) {\n rest(i + 1)(((r + A(i)) % m).toInt) = true\n rest(i + 1)(r) = true\n\n if (rest(i + 1)(0)) {\n println(\"YES\")\n System.exit(0)\n }\n }\n }\n }\n\n println(\"NO\")\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val A = readLine().split(\" \").map(_.toLong)\n\n if (n > m) println(\"YES\")\n else {\n val rest = Array.ofDim[Boolean](n + 1, m)\n\n for (i <- A.indices) {\n rest(i + 1)((A(i) % m).toInt) = true\n if (rest(i + 1)(0)) {\n println(\"YES\")\n System.exit(0)\n }\n }\n\n for {\n i <- 0 until n\n r <- 0 until m\n } {\n if (rest(i)(r)) {\n rest(i + 1)(((r + A(i)) % m).toInt) = true\n rest(i + 1)(r) = true\n\n if (rest(i + 1)(0)) {\n println(\"YES\")\n System.exit(0)\n }\n }\n }\n }\n\n println(\"NO\")\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val A = readLine().split(\" \").map(_.toLong)\n\n def sum(current: Long, array: Array[Long]): Boolean = {\n if (current > 0 && current % m == 0) true\n else if (array.isEmpty) false\n else {\n sum(current + array.head, array.tail) ||\n sum(current, array.tail)\n }\n }\n\n println(if (sum(0, A)) \"YES\" else \"NO\")\n\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val A = Array(1, 2, 3)\n val m = 5\n\n def sum(current: Int, array: Array[Int]): Boolean = {\n if (current > 0 && current % m == 0) true\n else if (array.isEmpty) false\n else {\n sum(current + array.head, array.tail) ||\n sum(current, array.tail)\n }\n }\n\n println(if (sum(0, A)) \"YES\" else \"NO\")\n\n\n}\n"}], "src_uid": "25232f4244004fa4c130892957e5de84"} {"source_code": "import scala.io.StdIn._\n\nobject _519_B extends App {\n val n = readInt()\n val A = readLine().split(\" \").map(_.toInt)\n val B = readLine().split(\" \").map(_.toInt)\n val C = readLine().split(\" \").map(_.toInt)\n\n val answer1 = A.diff(B)(0)\n val diff = A.diff(C)\n val answer2 = if (diff(0) != answer1) diff(0) else diff(1)\n\n println(answer1)\n println(answer2)\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.HashMap\n\nobject CompilationErrors{\n def main(args : Array[String]){\n var n : String = readLine\n var one : Array[Int] = readLine.split(\" \").map(_.toInt)\n var two : Array[Int] = readLine.split(\" \").map(_.toInt)\n var three : Array[Int] = readLine.split(\" \").map(_.toInt)\n (one diff two).foreach(println)\n (two diff three).foreach(print)\n }\n}"}, {"source_code": "object Main extends App {\n\n def diff(a: List[Long], b: List[Long]): Long = (a zip b :+ 0L).dropWhile({ case (a1, b1) => a1 == b1 }).head._1\n\n readLong\n val a = readLine.split(\" \").filterNot(_ == \"\").map(_.toLong).toList.sorted\n val b = readLine.split(\" \").filterNot(_ == \"\").map(_.toLong).toList.sorted\n val c = readLine.split(\" \").filterNot(_ == \"\").map(_.toLong).toList.sorted\n\n println(diff(a,b))\n println(diff(b,c))\n\n}"}, {"source_code": "import scala.io.Source\n\n/**\n * Created by kgribov on 05/03/15.\n */\nobject Problem519B {\n def main(args: Array[String]) {\n val lines = Source.stdin.getLines();\n lines.next()\n val linesNumber = 3\n val arr = new Array[Int](linesNumber)\n\n for (a <- 0 until linesNumber) {\n for (st <- lines.next().split(\" \")) {\n arr(a) += Integer.parseInt(st)\n }\n }\n println(arr(0) - arr(1))\n println(arr(1) - arr(2))\n }\n}\n"}, {"source_code": "import java.io._\n\nobject Main {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n\n def main(args: Array[String]) {\n\n val n = in.readLine().toInt\n\n val a = in.readLine().split(\" +\").map(_.toInt)\n val b = in.readLine().split(\" +\").map(_.toInt)\n val c = in.readLine().split(\" +\").map(_.toInt)\n\n out.println((a diff b)(0))\n out.println((b diff c)(0))\n\n out.close()\n }\n\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Main extends App {\n\tStdIn.readLine()\n\n\tlazy val errors: Array[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n\tlazy val fix1 = StdIn.readLine().split(\" \").map(_.toInt)\n\tlazy val fix2 = StdIn.readLine().split(\" \").map(_.toInt)\n\n\t(errors.diff(fix1).head, fix1.diff(fix2).head) match {\n\t\tcase (bug1, bug2) => println(s\"$bug1\\n$bug2\")\n\t}\n}\n"}, {"source_code": "object B519 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n val input1 = readInts(n-1)\n val input2 = readInts(n-2)\n println(input.diff(input1)(0))\n println(input1.diff(input2)(0))\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject A extends App {\n\n val n = StdIn.readInt()\n val f = StdIn.readLine().split(\" \").map(_.toInt)\n val s = StdIn.readLine().split(\" \").map(_.toInt)\n val t = StdIn.readLine().split(\" \").map(_.toInt)\n val e1 = f diff s\n val e2 = s diff t\n println(e1.head)\n println(e2.head)\n\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new mutable.HashMap[Int, Int]()\n for (i <- 0 until n) {\n val int = nextInt\n val x = a.getOrElse(int, 0)\n a.put(int, x + 1)\n }\n val b = new mutable.HashMap[Int, Int]()\n for (i <- 0 until n - 1) {\n val int = nextInt\n val x = b.getOrElse(int, 0)\n b.put(int, x + 1)\n }\n val c = new mutable.HashMap[Int, Int]()\n for (i <- 0 until n - 2) {\n val int = nextInt\n val x = c.getOrElse(int, 0)\n c.put(int, x + 1)\n }\n val list1 = b.toIterator\n while(list1.hasNext) {\n val l1 = list1.next()\n val x = l1._1\n for (j <- 0 until l1._2) {\n val v = a.getOrElse(x, 0)\n a.remove(x)\n if (v - 1 > 0) {\n a.put(x, v - 1)\n }\n }\n }\n val list2 = c.toIterator\n while(list2.hasNext) {\n val l1 = list2.next()\n val x = l1._1\n for (j <- 0 until l1._2) {\n val v = b.getOrElse(x, 0) \n b.remove(x)\n if (v - 1 > 0) {\n b.put(x, v - 1)\n }\n }\n }\n out.println(a.toList.head._1)\n out.println(b.toList.head._1)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject _519_B extends App {\n val n = readInt()\n val A = readLine().split(\" \").map(_.toInt)\n val B = readLine().split(\" \").map(_.toInt)\n val C = readLine().split(\" \").map(_.toInt)\n\n val answer1 = A.diff(B) mkString \" \"\n val answer2 = A.diff(C) filterNot (_ == answer1.toInt) mkString \" \"\n println(answer1)\n println(answer2)\n}\n"}], "src_uid": "1985566215ea5a7f22ef729bac7205ed"} {"source_code": "import scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n \n case class SegTree(as: Array[Int]) {\n\n val n = as.length\n val t = Array.ofDim[Int](4 * as.length)\n build(1, 0, n - 1)\n \n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n\t else {\n\t\tval tm = (tl + tr) / 2\n\t\tbuild(v * 2, tl, tm)\n\t\tbuild(v * 2 + 1, tm + 1, tr)\n\t\tt(v) = t(v * 2) + t(v * 2 + 1)\n\t }\n }\n \n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n \tif (l > r) 0\n \telse if (l == tl && r == tr) t(v)\n \telse {\n \t val tm = (tl + tr) / 2\n \t query(l, Math.min(r, tm), v * 2, tl, tm) + \n \t \tquery(Math.max(l, tm + 1), r, v * 2 + 1, tm + 1, tr)\n \t}\n }\n\n def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n \tif (tl == tr) t(v) += newVal\n else {\n\t\t val tm = (tl + tr) / 2\n\t\t if (pos <= tm) update(pos, newVal, v * 2, tl, tm)\n\t\t else update(pos, newVal, v * 2 + 1, tm + 1, tr)\n\t\t t(v) = t(v * 2) + t(v * 2 + 1)\n }\n\t}\n\n }\n\n val n = readInt\n val as = readInts(n)\n \n val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }\n\n val order = sees.sortBy(- _._1).map(_._2)\n \n val leftST = SegTree(as)\n val rightST = SegTree(as.map(a => 1 - a))\n\n var sum = 0L\n for (i <- order) {\n sum = sum + leftST.query(0, i - 1) + rightST.query(i + 1, n - 1)\n if (as(i) == 0) rightST.update(i + 1, -1)\n else leftST.update(i - 1, -1)\n }\n \n println(sum)\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n \n case class SegTree(as: Array[Int]) {\n\n val n = as.length\n val t = Array.ofDim[Int](4 * as.length)\n build(1, 0, n - 1)\n \n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n\t else {\n\t\tval tm = (tl + tr) >> 1\n\t\tbuild(v << 1, tl, tm)\n\t\tbuild((v << 1) + 1, tm + 1, tr)\n\t\tt(v) = t(v << 1) + t((v << 1) + 1)\n\t }\n }\n \n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n \tif (l > r) 0\n \telse if (l == tl && r == tr) t(v)\n \telse {\n \t val tm = (tl + tr) >> 1\n \t query(l, Math.min(r, tm), v << 1, tl, tm) + \n \t \tquery(Math.max(l, tm + 1), r, (v << 1) + 1, tm + 1, tr)\n \t}\n }\n\n def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n \tif (tl == tr) t(v) += newVal\n else {\n\t\t val tm = (tl + tr) >> 1\n\t\t if (pos <= tm) update(pos, newVal, v << 1, tl, tm)\n\t\t else update(pos, newVal, (v << 1) + 1, tm + 1, tr)\n\t\t t(v) = t(v << 1) + t((v << 1) + 1)\n }\n\t}\n\n }\n\n val n = readInt\n val as = readInts(n)\n \n val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }\n\n val order = sees.sortBy(- _._1).map(_._2)\n \n val leftST = SegTree(as)\n val rightST = SegTree(as.map(a => 1 - a))\n\n var sum = 0L\n for (i <- order) {\n sum = sum + leftST.query(0, i - 1) + rightST.query(i + 1, n - 1)\n if (as(i) == 0) rightST.update(i + 1, -1)\n else leftST.update(i - 1, -1)\n }\n \n println(sum)\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n \n case class SegTree(as: Array[Int]) {\n\n val n = as.length\n val t = Array.ofDim[Int](4 * as.length)\n build(1, 0, n - 1)\n \n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n\t else {\n\t\tval tm = (tl + tr) / 2\n\t\tbuild(v * 2, tl, tm)\n\t\tbuild(v * 2 + 1, tm + 1, tr)\n\t\tt(v) = t(v * 2) + t(v * 2 + 1)\n\t }\n }\n \n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n \tif (l > r) 0\n \telse if (l == tl && r == tr) t(v)\n \telse {\n \t val tm = (tl + tr) / 2\n \t query(l, Math.min(r, tm), v * 2, tl, tm) + \n \t \tquery(Math.max(l, tm + 1), r, v * 2 + 1, tm + 1, tr)\n \t}\n }\n\n def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n \tif (tl == tr) t(v) += newVal\n else {\n\t\t val tm = (tl + tr) / 2\n\t\t if (pos <= tm) update(pos, newVal, v * 2, tl, tm)\n\t\t else update(pos, newVal, v * 2 + 1, tm + 1, tr)\n\t\t t(v) = t(v * 2) + t(v * 2 + 1)\n }\n\t}\n\n }\n\n val n = readInt\n val as = readInts(n)\n \n val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }\n\n val order = sees.sortBy(- _._1).map(_._2)\n \n val leftST = SegTree((0 +: as).take(n))\n val rightST = SegTree(((as.map(a => (1 - a)) :+ 0)).take(n))\n\n var sum = 0L\n for (i <- order) {\n sum = sum + leftST.query(0, i) + rightST.query(i + 1, n - 1)\n if (as(i) == 0) rightST.update(i + 1, -1)\n else leftST.update(i, -1)\n }\n \n println(sum)\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n \n case class SegTree(as: Array[Int]) {\n\n val n = as.length\n val t = Array.ofDim[Int](4 * as.length)\n build(1, 0, n - 1)\n \n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n\t else {\n\t\tval tm = (tl + tr) >> 1\n\t\tval v2 = v << 1\n\t\tbuild(v2, tl, tm)\n\t\tbuild(v2 + 1, tm + 1, tr)\n\t\tt(v) = t(v2) + t(v2 + 1)\n\t }\n }\n \n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n \tif (l > r) 0\n \telse if (l == tl && r == tr) t(v)\n \telse {\n \t val tm = (tl + tr) >> 1\n \t val v2 = v << 1\n \t query(l, Math.min(r, tm), v2, tl, tm) + \n \t \tquery(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)\n \t}\n }\n\n def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n \tif (tl == tr) t(v) += newVal\n else {\n\t\t val tm = (tl + tr) >> 1\n\t\t val v2 = v << 1\n\t\t if (pos <= tm) update(pos, newVal, v2, tl, tm)\n\t\t else update(pos, newVal, v2 + 1, tm + 1, tr)\n\t\t t(v) = t(v2) + t(v2 + 1)\n }\n\t}\n\n }\n\n val n = readInt\n val as = readInts(n)\n \n val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }\n\n val order = sees.sortBy(- _._1).map(_._2)\n \n val leftST = SegTree(as)\n val rightST = SegTree(as.map(a => 1 - a))\n\n var sum = 0L\n for (i <- order) {\n sum = sum + leftST.query(0, i - 1) + rightST.query(i + 1, n - 1)\n if (as(i) == 0) rightST.update(i + 1, -1)\n else leftST.update(i - 1, -1)\n }\n \n println(sum)\n}"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Please hack me if you can!\n */\nimport scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n \n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length && i >= 0) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(src: Array[Int]): Array[Int] = {\n val t = Array.fill(src.length) { 0 }\n for (i <- src.indices) update(t, i, src(i))\n t\n }\n\n } \n\n val n = readInt\n val as = readInts(n)\n \n val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }\n\n val order = sees.sortBy(- _._1).map(_._2)\n \n val leftBIT = BIT((0 +: as).take(n))\n val rightBIT = BIT((0 +: (as.map(a => (1 - a)).reverse)).take(n))\n\n var sum = 0L\n for (i <- order) {\n sum = sum + BIT.query(leftBIT, i) + BIT.query(rightBIT, n - i - 1)\n if (as(i) == 0) BIT.update(rightBIT, n - i - 1, -1)\n else BIT.update(leftBIT, i, -1)\n }\n \n println(sum)\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n \n case class SegTree(as: Array[Int]) {\n\n val n = as.length\n val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))\n build(1, 0, n - 1)\n \n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n\t else {\n\t\tval tm = (tl + tr) >> 1\n\t\tval v2 = v << 1\n\t\tbuild(v2, tl, tm)\n\t\tbuild(v2 + 1, tm + 1, tr)\n\t\tt(v) = t(v2) + t(v2 + 1)\n\t }\n }\n \n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n \tif (l > r) 0\n \telse if (l == tl && r == tr) t(v)\n \telse {\n \t val tm = (tl + tr) >> 1\n \t val v2 = v << 1\n \t query(l, Math.min(r, tm), v2, tl, tm) + \n \t \tquery(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)\n \t}\n }\n\n def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n \tif (tl == tr) t(v) += newVal\n else {\n\t\t val tm = (tl + tr) >> 1\n\t\t val v2 = v << 1\n\t\t if (pos <= tm) update(pos, newVal, v2, tl, tm)\n\t\t else update(pos, newVal, v2 + 1, tm + 1, tr)\n\t\t t(v) = t(v2) + t(v2 + 1)\n }\n\t}\n\n }\n\n val n = readInt\n val as = readInts(n)\n \n val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }\n\n val order = sees.sortBy(- _._1).map(_._2)\n \n val leftST = SegTree(as)\n val rightST = SegTree(as.map(a => 1 - a))\n\n var sum = 0L\n for (i <- order) {\n sum = sum + leftST.query(0, i - 1) + rightST.query(i + 1, n - 1)\n if (as(i) == 0) rightST.update(i + 1, -1)\n else leftST.update(i - 1, -1)\n }\n \n println(sum)\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n \n case class SegTree(as: Array[Int]) {\n\n val n = as.length\n val t = Array.ofDim[Int](4 * as.length)\n build(1, 0, n - 1)\n \n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n\t else {\n\t\tval tm = (tl + tr) / 2\n\t\tbuild(v * 2, tl, tm)\n\t\tbuild(v * 2 + 1, tm + 1, tr)\n\t\tt(v) = t(v * 2) + t(v * 2 + 1)\n\t }\n }\n \n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n \tif (l > r) 0\n \telse if (l == tl && r == tr) t(v)\n \telse {\n \t val tm = (tl + tr) / 2\n \t query(l, Math.min(r, tm), v * 2, tl, tm) + \n \t \tquery(Math.max(l, tm + 1), r, v * 2 + 1, tm + 1, tr)\n \t}\n }\n\n def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n \tif (tl == tr) t(v) += newVal\n else {\n\t\t val tm = (tl + tr) / 2\n\t\t if (pos <= tm) update(pos, newVal, v * 2, tl, tm)\n\t\t else update(pos, newVal, v * 2 + 1, tm + 1, tr)\n\t\t t(v) = t(v * 2) + t(v * 2 + 1)\n }\n\t}\n\n }\n\n val n = readInt\n val as = readInts(n)\n \n val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }\n\n val order = sees.sortBy(- _._1).map(_._2)\n \n val leftST = SegTree((0 +: as).take(n))\n val rightST = SegTree((0 +: (as.map(a => (1 - a)).reverse)).take(n))\n\n var sum = 0L\n for (i <- order) {\n sum = sum + leftST.query(0, i) + rightST.query(0, n - i - 1)\n if (as(i) == 0) rightST.update(n - i - 1, -1)\n else leftST.update(i, -1)\n }\n \n println(sum)\n}"}], "negative_code": [{"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Please hack me if you can!\n */\nimport scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toByte) }\n \n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length && i >= 0) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(src: Array[Byte]): Array[Int] = {\n val t = Array.fill(src.length) { 0 }\n for (i <- src.indices) update(t, i, src(i))\n t\n }\n\n } \n\n val n = readInt\n val as = readInts(n)\n \n val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }\n\n val order = sees.sortBy(- _._1).map(_._2)\n \n val leftBIT = BIT((0.toByte +: as).take(n))\n val rightBIT = BIT((0.toByte +: (as.map(a => (1 - a).toByte).reverse)).take(n))\n\n var sum = 0\n for (i <- order) {\n sum = sum + BIT.query(leftBIT, i) + BIT.query(rightBIT, n - i - 1)\n if (as(i) == 0) BIT.update(rightBIT, n - i - 1, -1)\n else BIT.update(leftBIT, i, -1)\n }\n \n println(sum)\n}"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Please hack me if you can!\n */\nimport scala.collection._\n\nobject A extends App {\n \n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n \n object BIT {\n\n def query(t: Array[Int], r: Int, acc: Int = 0): Int =\n if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))\n\n def update(t: Array[Int], i: Int, delta: Int): Unit =\n if (i < t.length && i >= 0) {\n t(i) += delta\n update(t, i | (i + 1), delta)\n }\n\n def apply(src: Array[Int]): Array[Int] = {\n val t = Array.fill(src.length) { 0 }\n for (i <- src.indices) update(t, i, src(i))\n t\n }\n\n } \n\n val n = readInt\n val as = readInts(n)\n \n val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }\n\n val order = sees.sortBy(- _._1).map(_._2)\n \n val leftBIT = BIT((0 +: as).take(n))\n val rightBIT = BIT((0 +: (as.map(a => (1 - a)).reverse)).take(n))\n\n var sum = 0\n for (i <- order) {\n sum = sum + BIT.query(leftBIT, i) + BIT.query(rightBIT, n - i - 1)\n if (as(i) == 0) BIT.update(rightBIT, n - i - 1, -1)\n else BIT.update(leftBIT, i, -1)\n }\n \n println(sum)\n}"}], "src_uid": "1a3b22a5a8e70505e987d3e7f97e7883"} {"source_code": "object B701 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n\n val row = Array.fill(n)(false)\n val col = Array.fill(n)(false)\n val res = Array.fill(m)(0L)\n var R = 0L\n var C = 0L\n for(q <- 0 until m ) {\n val Array(r, c)= readInts(2)\n if(!row(r-1)) {\n row(r-1) = true\n R += 1\n }\n if(!col(c-1)) {\n col(c-1) = true\n C += 1\n }\n res(q) = (n-R)*(n-C)\n }\n\n println(res.mkString(\" \"))\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.BitSet\n\n//package b\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n var freeCols, freeRows = n\n var remain = n.toLong * n\n val res = Array.ofDim[Long](m)\n\n val row, col = new BitSet(n)\n\n for (i <- 0 until m) {\n val Array(x, y) = readInts(2)\n if (!row(y) && !col(x)) {\n remain -= (freeCols + freeRows - 1)\n freeCols -= 1\n freeRows -= 1\n } else if (!row(y)) {\n remain -= freeCols\n freeRows -= 1\n } else if (!col(x)) {\n remain -= freeRows\n freeCols -= 1\n }\n\n res(i) = remain\n row += y\n col += x\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _701B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val (n, m) = read[(Long, Int)]\n val rows, cols = mutable.Set.empty[Int]\n repeat(m) {\n val r, c = read[Int]\n rows += r\n cols += c\n val ans: Long = (n - rows.size)*(n - cols.size)\n write(ans, \"\")\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt(); val m = sc.nextInt()\n\n val dpx = new Array[Boolean](n+1)\n val dpy = new Array[Boolean](n+1)\n\n var xw = n\n var yw = n\n\n for(k <- 1 to m){\n val y = sc.nextInt(); val x = sc.nextInt()\n\n if(!dpx(x)){\n dpx(x) = true\n xw -= 1\n }\n\n if(!dpy(y)){\n dpy(y) = true\n yw -= 1\n }\n\n\n if(k == m)\n println(xw * yw.toLong)\n else\n print(xw * yw.toLong + \" \")\n }\n }\n}\n"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val Array(n, m) = lines.next().split(' ').map(_.toInt)\n val xaxis = Array.ofDim[Boolean](n)\n val yaxis = Array.ofDim[Boolean](n)\n var xLeft: Long = n\n var yLeft: Long = n\n\n println(lines.take(m).map { _.split(' ').map(_.toInt - 1)}.map {\n case Array(x, y) =>\n if (!xaxis(x)) xLeft -= 1\n if (!yaxis(y)) yLeft -= 1\n xaxis(x) = true\n yaxis(y) = true\n xLeft * yLeft\n }.mkString(\" \"))\n\n\n}\n\n"}], "negative_code": [{"source_code": "import scala.collection.mutable.BitSet\n\n//package b\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n var freeCols, freeRows = n\n var remain = n.toLong * n\n val res = Array.ofDim[Long](m)\n\n val row, col = new BitSet(n)\n\n for (i <- 0 until m) {\n val Array(x, y) = readInts(2)\n if (!row(y) && !col(y)) {\n remain -= (freeCols + freeRows - 1)\n freeCols -= 1\n freeRows -= 1\n } else if (!row(y)) {\n remain -= freeCols\n freeRows -= 1\n } else if (!col(x)) {\n remain -= freeRows\n freeCols -= 1\n }\n\n res(i) = remain\n row += y\n col += x\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable.BitSet\n\n//package b\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n\n var freeCols, freeRows = n\n var remain = n.toLong * n\n val res = Array.ofDim[Long](m)\n\n val row, col = new BitSet(n)\n\n for (i <- 0 until m) {\n val Array(x, y) = readInts(2)\n if (!row(y) && !col(y)) {\n remain -= (freeCols + freeRows - 1)\n freeCols -= 1\n freeRows -= 1\n } else if (!row(y)) {\n remain -= freeCols\n freeRows -= 1\n } else if (!col(x)) {\n remain -= freeRows\n freeCols -= 1\n }\n\n res(i) = remain\n row += y\n col += y\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}], "src_uid": "faf1abdeb6f0cf34972d5cb981116186"} {"source_code": "//package codeforces.contest1244\n\nobject PensAndPencils {\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt()) {\n val Array(lectures, practicals, lRate, pRate, limit) =\n io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val pensRequired = (lectures + (if (lectures % lRate == 0) 0 else lRate)) / lRate\n val pencilsRequired = (practicals + (if (practicals % pRate == 0) 0 else pRate)) / pRate\n\n if (pensRequired + pencilsRequired <= limit)\n println(s\"$pensRequired $pencilsRequired\")\n else\n println(-1)\n\n }\n }\n\n}\n", "positive_code": [{"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n\n for (_ <- 1 to t) {\n val a, b, c, d, k = nextInt\n val aa = (a + c - 1) / c\n val bb = (b + d - 1) / d\n if (aa + bb <= k) out.println(s\"$aa $bb\")\n else out.println(-1)\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "17cf2d6f59773925b228188b5a47b710"} {"source_code": "import scala.io.StdIn\n\nobject Zeros extends App {\n\n private val operate: String => Int =\n str => {\n val from = str.indexOf('1')\n val to = str.lastIndexOf('1')\n getCount(str.substring(from, to))\n }\n\n private val getCount: String => Int =\n str => str count (_ == '0')\n\n var n: Int = StdIn.readLine().toInt\n\n while (n != 0) {\n val line: String = StdIn.readLine()\n if (line.contains('1')) println(operate(line)) else println(0)\n n -= 1\n }\n\n}\n", "positive_code": [{"source_code": "import java.io.PrintWriter\nimport util.control.Breaks._\n\nobject Solution {\n val reader = scala.io.StdIn\n def readInt(): Int = reader.readLine().toInt\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n def readString(): String = reader.readLine()\n\n def multiTest(f: () => Unit): Unit = {\n var t = readInt()\n while (t > 0) {\n f()\n t -= 1\n }\n }\n\n def solve(): Unit = {\n val s = readString()\n var l = 0\n while (l < s.length && s(l) == '0') l += 1\n\n var r = s.length - 1\n while (r > 0 && s(r) == '0') r -= 1\n\n var rs = 0\n while (l <= r) {\n if (s(l) == '0') rs += 1\n l += 1\n }\n println(rs)\n }\n\n def main(args: Array[String]) {\n multiTest(solve)\n //solve()\n }\n}\n"}, {"source_code": "object _1303A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val t = io.read[String]\n val ans = for {\n i <- Option(t.indexOf('1')) if i >= 0\n j <- Option(t.lastIndexOf('1')) if j > i\n o = t.substring(i, j)\n } yield o.count(_ == '0')\n io.write(ans.getOrElse(0))\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "5de66fbb594bb317654366fd2290c4d3"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(var value: Int, var ind: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return value.compareTo(that.value)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val arr = new Array[Int](n)\n for (i <- 0 until n)\n arr(i) = readInt()\n val s = readString()\n var r = Vector[Int]()\n var b = Vector[Int]()\n for (i <- 0 until n) {\n if (s(i) == 'B')\n b :+= arr(i)\n else\n r :+= arr(i)\n }\n b = b.sorted\n r = r.sorted.reverse\n var ans = \"YES\"\n for (i <- r.indices) {\n if (r(i) > n-i)\n ans = \"NO\"\n }\n for (i <- b.indices) {\n if (b(i) < i+1)\n ans = \"NO\"\n }\n writer.println(ans)\n }\n writer.flush()\n}\n", "positive_code": [{"source_code": "object _1607D extends CodeForcesApp {\r\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\r\n\r\n override def solve(io: IO) = io.repeat {\r\n val values = io.read[Vector[Int]]\r\n val colors = io.read[String]\r\n\r\n val arr = colors.zip(values).toMultiMap.mapValues(_.sorted).withDefaultValue(Vector.empty)\r\n\r\n val blues = arr('B')\r\n var bi = -1\r\n\r\n val reds = arr('R')\r\n var ri = -1\r\n\r\n def findRed(x: Int) =\r\n ((ri + 1) until reds.length)\r\n .find(i => reds(i) <= x)\r\n .map({i => ri = i; i})\r\n\r\n def findBlue(x: Int) =\r\n ((bi + 1) until blues.length)\r\n .find(i => x <= blues(i))\r\n .map({i => bi = i; i})\r\n\r\n def find(x: Int) = findBlue(x).orElse(findRed(x)).nonEmpty\r\n\r\n val ans = (1 to values.length).forall(find)\r\n\r\n io.write(ans.toEnglish.toUpperCase)\r\n }\r\n}\r\n/****************************[Ignore Template Below]****************************************/\r\ntrait CodeForcesApp {\r\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\r\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\r\n def solve(io: IO): Any\r\n def main(args: Array[String]): Unit = {\r\n val io = new IO(System.in, System.out)\r\n try solve(io) finally io.close()\r\n }\r\n}\r\n/****************************[Scala Collection Utils]****************************************/\r\nobject Utils {\r\n import scala.collection.mutable\r\n\r\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\r\n\r\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\r\n\r\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\r\n\r\n val charToInt: Char => Int = Character.getNumericValue\r\n val intToChar: Int => Char = Character.forDigit(_, 10)\r\n\r\n implicit class GenericExtensions[A](a: A) {\r\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\r\n }\r\n\r\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\r\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\r\n\r\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\r\n\r\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\r\n val freqTable = t.groupBy(identity).mapValues(_.size)\r\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\r\n }\r\n }\r\n\r\n implicit class PairExtensions[A, B](p: (A, B)) {\r\n def key = p._1\r\n def value = p._2\r\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\r\n }\r\n\r\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\r\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\r\n }\r\n\r\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\r\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\r\n }\r\n\r\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\r\n def notContains(x: A): Boolean = !(s contains x)\r\n def toMutable = mutable.Set.empty[A] ++ s\r\n }\r\n\r\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\r\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\r\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\r\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\r\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\r\n }\r\n\r\n implicit class BooleanExtensions(x: Boolean) {\r\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\r\n def toEnglish = if(x) \"Yes\" else \"No\"\r\n }\r\n\r\n implicit class IntExtensions(val x: Int) extends AnyVal {\r\n @inline def isEven = x%2 == 0\r\n @inline def isOdd = x%2 == 1\r\n }\r\n\r\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\r\n\r\n def map[K] = new {\r\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\r\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\r\n override def apply(key: K) = getOrElseUpdate(key, f(key))\r\n }\r\n }\r\n\r\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\r\n\r\n def memoize[A, B](f: A => B): A => B = map[A] using f\r\n}\r\n/***********************************[Scala I/O]*********************************************/\r\nimport java.io._, java.util.StringTokenizer\r\nimport scala.collection.generic.CanBuild\r\n\r\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\r\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\r\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\r\n\r\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\r\n val printer = new PrintWriter(out, true)\r\n\r\n @inline private[this] def tokenizer() = {\r\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\r\n tokenizers.headOption\r\n }\r\n\r\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\r\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\r\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\r\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\r\n\r\n override def next() = tokenizer().get.nextToken()\r\n override def hasNext = tokenizer().nonEmpty\r\n\r\n def write(obj: Any*): this.type = writeAll(obj)\r\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\r\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\r\n def query[A: IO.Read](question: Any): A = writeLine(question).read\r\n\r\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\r\n\r\n override def flush() = printer.flush()\r\n def close() = {\r\n flush()\r\n in.close()\r\n printer.close()\r\n }\r\n}\r\nobject IO {\r\n class Read[A](val apply: IO => A) {\r\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\r\n }\r\n object Read {\r\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\r\n implicit val string : Read[String] = new Read(_.next())\r\n implicit val int : Read[Int] = string.map(_.toInt)\r\n implicit val long : Read[Long] = string.map(_.toLong)\r\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\r\n implicit val double : Read[Double] = string.map(_.toDouble)\r\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\r\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\r\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\r\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\r\n implicit val boolean : Read[Boolean] = string map {s =>\r\n s.toLowerCase match {\r\n case \"yes\" | \"true\" | \"1\" => true\r\n case \"no\" | \"false\" | \"0\" => false\r\n case _ => s.toBoolean\r\n }\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "c3df88e22a17492d4eb0f3239a27d404"} {"source_code": "object A {\n\n def main(args: Array[String]): Unit = {}\n import IO._\n\n val t = nextInt\n\n for (_ <- 1 to t) {\n val a, b, n = nextLong\n val xs = Array(a, b, a ^ b)\n println(xs(n.toInt % 3))\n }\n\n object IO {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n)(nextInt)\n def readLongs(n: Int) = Array.fill(n)(nextLong)\n def readBigs(n: Int) = Array.fill(n)(nextBig)\n }\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val a, b, n = ni()\n val ans = n % 3 match {\n case 0 => a\n case 1 => b\n case 2 => a ^ b\n }\n out.println(ans)\n }\n }\n}"}, {"source_code": "object A {\n\n import IO._\n def main(args: Array[String]): Unit = {\n val t = nextInt\n\n var i = 0\n while (i < t) {\n val a, b, n = nextLong\n val xs = Array(a, b, a ^ b)\n out.println(xs(n.toInt % 3))\n i += 1\n }\n out.flush()\n }\n\n object IO {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n)(nextInt)\n def readLongs(n: Int) = Array.fill(n)(nextLong)\n def readBigs(n: Int) = Array.fill(n)(nextBig)\n }\n}\n"}, {"source_code": "object A {\n\n def main(args: Array[String]): Unit = {}\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(t) = readInts(1)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (_ <- 1 to t) {\n val Array(a, b, n) = readLongs(3)\n val xs = Array(a, b, a ^ b)\n println(xs(n.toInt % 3))\n }\n\n Console.flush\n}\n"}, {"source_code": "object A {\n\n def main(args: Array[String]): Unit = {}\n import IO._\n\n val t = nextInt\n\n for (_ <- Range(0, t)) {\n val a, b, n = nextLong\n val xs = Array(a, b, a ^ b)\n out.println(xs(n.toInt % 3))\n }\n out.flush()\n\n object IO {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n)(nextInt)\n def readLongs(n: Int) = Array.fill(n)(nextLong)\n def readBigs(n: Int) = Array.fill(n)(nextBig)\n }\n}\n"}, {"source_code": "object A {\n\n def main(args: Array[String]): Unit = {}\n import IO._\n\n val t = nextInt\n\n var i = 0\n while (i < t) {\n val a, b, n = nextLong\n val xs = Array(a, b, a ^ b)\n out.println(xs(n.toInt % 3))\n i += 1\n }\n out.flush()\n\n object IO {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n)(nextInt)\n def readLongs(n: Int) = Array.fill(n)(nextLong)\n def readBigs(n: Int) = Array.fill(n)(nextBig)\n }\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(t) = readInts(1)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (_ <- 1 to t) {\n val Array(a, b, n) = readLongs(3)\n val xs = Array(a, b, a ^ b)\n println(xs(n.toInt % 3))\n }\n\n Console.flush\n}\n"}, {"source_code": "object A {\n\n def main(args: Array[String]): Unit = {}\n import IO._\n\n val t = nextInt\n\n for (_ <- 1 to t) {\n val a, b, n = nextLong\n val xs = Array(a, b, a ^ b)\n out.println(xs(n.toInt % 3))\n }\n out.flush()\n\n object IO {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n)(nextInt)\n def readLongs(n: Int) = Array.fill(n)(nextLong)\n def readBigs(n: Int) = Array.fill(n)(nextBig)\n }\n}\n"}, {"source_code": "object A {\n\n import IO._\n def main(args: Array[String]): Unit = {\n val t = nextInt\n\n for (_ <- Range(0, t)) {\n val a, b, n = nextLong\n val xs = Array(a, b, a ^ b)\n out.println(xs(n.toInt % 3))\n }\n out.flush()\n }\n \n object IO {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n)(nextInt)\n def readLongs(n: Int) = Array.fill(n)(nextLong)\n def readBigs(n: Int) = Array.fill(n)(nextBig)\n }\n}\n"}, {"source_code": "object A {\n\n import IO._\n def main(args: Array[String]): Unit = {\n val t = nextInt\n\n for (_ <- 1 to t) {\n val a, b, n = nextLong\n val xs = Array(a, b, a ^ b)\n out.println(xs(n.toInt % 3))\n }\n out.flush()\n }\n\n object IO {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n)(nextInt)\n def readLongs(n: Int) = Array.fill(n)(nextLong)\n def readBigs(n: Int) = Array.fill(n)(nextBig)\n }\n}\n"}], "negative_code": [], "src_uid": "64a375c7c49591c676dbdb039c93d218"} {"source_code": "object P7D {\n import io.StdIn._\n\n val s = readLine\n\n def main(args : Array[String]) {\n var p = s(0).toLong\n var q = s(0).toLong\n var r = 1L\n val a = Array.ofDim[Int](s.size)\n a(0) = 1\n for (i <- 1 until s.size) {\n p = p * 0x3333333333333333L + s(i)\n r = r * 0x3333333333333333L\n q = q + r * s(i)\n a(i) = if (p == q) a(i - 1 >> 1) + 1 else 0\n }\n println(a.sum)\n }\n}", "positive_code": [{"source_code": "object P7D {\n import io.StdIn._\n\n val s = readLine\n\n def main(args : Array[String]) {\n var p = s(0).toLong\n var q = s(0).toLong\n var r = 1L\n val a = Array.ofDim[Int](s.size)\n a(0) = 1\n for (i <- 1 until s.size) {\n p = p * 0x3333333333333333L + s(i)\n r = r * 0x3333333333333333L\n q = q + r * s(i)\n a(i) = if (p == q) a(i - 1 >> 1) + 1 else 0\n }\n println(a.sum)\n }\n}\n"}, {"source_code": "object P7D {\n import io.StdIn._\n\n val s = readLine\n\n def main(args : Array[String]) {\n var p = s(0).toLong\n var q = s(0).toLong\n var r = 1L\n val a = Array.ofDim[Int](s.size)\n a(0) = 1\n for (i <- 1 until s.size) {\n p = p * 0x3333333333333333L + s(i)\n r = r * 0x3333333333333333L\n q = q + r * s(i)\n a(i) = if (p == q) a(i - 1 >> 1) + 1 else 0\n }\n println(a.sum)\n }\n}"}], "negative_code": [], "src_uid": "0090979443c294ef6aed7cd09201c9ef"} {"source_code": "import scala.annotation.tailrec\n\nobject Devu {\n def main(args: Array[String]) {\n\t val n = readLine().toInt\n\t val d = readLine().split(\" \").map(_.toLong)\n\t val goal = d.reduceLeft(_ + _) / n\n\t @tailrec\n\t def cnt(x: Int, g: Long, acc: Long): Long = {\n\t if (x >= n) acc\n\t else (g - d(x)) match {\n\t case 0 => cnt(x + 1, goal, acc)\n\t case z if z > 0 => cnt(x + 1, goal + z, acc + z)\n\t case z if z < 0 => cnt(x + 1, goal + z, acc - z)\n\t }\n\t }\n\t println(cnt(0, goal, 0))\n }\n}", "positive_code": [{"source_code": "//package template\n\nobject Template {\n\tdef main(args: Array[String]) {\n\t\tvar n = readLine.toInt\n\t\tvar input = readLine.split(' ').map(_.toLong)\n\t\tif(n == 1){\n\t\t\tprint(0)\n\t\t}\n\t\telse{\n\t\t\tvar avarage = 0L\n\t\t\tfor(i <- input){\n\t\t\t\tavarage += i\n\t\t\t}\n\t\t\tavarage /= n\n\t\t\tvar answer = 0L\n\t\t\tvar current = avarage\n\t\t\tvar next = input(0)\n\t\t\tvar dif = 0L\n\t\t\tfor(i <- 0 until n){\n\t\t\t\tdif = avarage - current\n\t\t\t\tcurrent = next - dif\n\t\t\t\tif(i != n-1)next = input(i+1)\n\t\t\t\tanswer += Math.abs(dif)\n\t\t\t}\n\t\t\tprint(answer)\n\t\t}\n\t}\n}"}], "negative_code": [{"source_code": "//package template\n\nobject Template {\n\tdef main(args: Array[String]) {\n\t\tvar n = readLine.toInt\n\t\tvar input = readLine.split(' ').map(_.toInt)\n\t\tif(n == 1){\n\t\t\tprint(0)\n\t\t}\n\t\telse{\n\t\t\tvar avarage = 0\n\t\t\tfor(i <- input){\n\t\t\t\tavarage += i\n\t\t\t}\n\t\t\tavarage /= n\n\t\t\tvar answer = 0\n\t\t\tvar current = avarage\n\t\t\tvar next = input(0)\n\t\t\tvar dif = 0\n\t\t\tfor(i <- 0 until n){\n\t\t\t\tdif = avarage - current\n\t\t\t\tcurrent = next - dif\n\t\t\t\tif(i != n-1)next = input(i+1)\n\t\t\t\tanswer += Math.abs(dif)\n\t\t\t}\n\t\t\tprint(answer)\n\t\t}\n\t}\n}"}], "src_uid": "41ae8b0dee3b0f4e91bd06e4a0635492"} {"source_code": "import java.io._\nimport java.util.Scanner\n\nobject Main{\n def main(args: Array[String]) {\n val bf = new BufferedReader(new InputStreamReader(System.in))\n val N = bf.readLine.toInt\n val edgesLines = for (id <- 0 until (N - 1)) yield bf.readLine.split(\" \")\n val E = edgesLines.map(s => (s(0).toInt, s(1).toInt)).flatMap(p => (p._1, p._2) :: (p._2, p._1) :: Nil)\n val G = E groupBy(_._1) mapValues (_ map(_._2))\n def Color(x: Int, p: Int, c: Int): Iterator[Tuple2[Int, Int]] = Iterator((x, c)) ++ G(x).filter(_ != p).map(Color(_, x, 1 - c)).fold(Iterator.empty)(_ ++ _)\n val coloring = Color(1, -1, 0).toList;\n val black = coloring.filter{case (id, color) => color == 0}.size\n val white = N - black\n\n println(black.toLong * white - (N - 1));\n }\n}", "positive_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\n\n/**\n * @see http://codeforces.com/contest/862/problem/B\n * TIME LIMIT EXCEEDED :(\n */\n\nobject TAILREC_BMahmoudAndEhabAndTheBipartiteness extends App {\n /**\n * Bicoloring based of dfs\n */\n def bicoloring(g: mutable.HashMap[Int, List[Int]]): (Long, Long) = {\n @tailrec\n def dfs(h: List[(Int, Int, List[Int], Int)], cts: (Long, Long)): (Long, Long) = {\n if (h.isEmpty) cts\n else {\n val (p, u, adj, c) = h.head\n if (adj.isEmpty) dfs(h.tail, (cts._1 + (c ^ 1), cts._2 + (c ^ 0)))\n else {\n val v = adj.head\n if (v == p) dfs((p, u, adj.tail, c) :: h.tail, cts)\n else dfs((u, v, g(v), if (c == 0) 1 else 0) :: (p, u, adj.tail, c) :: h.tail, cts)\n }\n }\n }\n\n dfs(List((0, 1, g(1), 0)), (0L, 0L))\n }\n\n /**\n * 1 <= n <= math.pow(10, 5)\n */\n val n = scala.io.StdIn.readLine().toInt\n\n /**\n * The adjacency-list representation of a graph\n * g is a connected acyclic graph\n */\n val g = (0 until n - 1).foldLeft(new mutable.HashMap[Int, List[Int]]) { (g, _) =>\n val Array(u, v) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n g(v) = u :: g.getOrElse(v, Nil)\n g(u) = v :: g.getOrElse(u, Nil)\n g\n// g + (v -> (u :: g.getOrElse(v, Nil)), u -> (v :: g.getOrElse(u, Nil)))\n }\n\n val (a, b) = bicoloring(g)\n println(a * b - n + 1)\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\n/**\n * @see http://codeforces.com/contest/862/problem/B\n */\n\nobject BMahmoudAndEhabAndTheBipartiteness extends App {\n /**\n * Bicoloring based of dfs\n */\n def bicoloring(g: ArrayBuffer[List[Int]]): (Long, Long) = {\n var cts = (0L, 0L)\n\n def dfs(u: Int, v: Int, c: Int): Unit = {\n cts = (cts._1 + (c ^ 1), cts._2 + (c ^ 0))\n g(v).foreach(p => if (p != u) dfs(v, p, if (c == 0) 1 else 0))\n }\n\n dfs(0, 1, 0)\n cts\n }\n\n /**\n * 1 <= n <= math.pow(10, 5)\n */\n val n = scala.io.StdIn.readLine().toInt\n\n /**\n * The adjacency-list representation of a graph\n * g is a connected acyclic graph\n */\n val g = (0 until n - 1).foldLeft(ArrayBuffer.fill[List[Int]](100005)(Nil)) { (g: ArrayBuffer[List[Int]], _) =>\n val Array(u, v) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n g(u) = v :: g(u)\n g(v) = u :: g(v)\n g\n }\n\n val (a, b) = bicoloring(g)\n println(a * b - n + 1)\n}\n"}, {"source_code": "import java.io._\nimport java.util.Scanner\n\nobject Main{\n def main(args: Array[String]) {\n val bf = new BufferedReader(new InputStreamReader(System.in))\n val N = bf.readLine.toInt\n val edgesLines = for (id <- 0 until (N - 1)) yield bf.readLine.split(\" \")\n val E = edgesLines.map(s => (s(0).toInt, s(1).toInt)).flatMap(p => (p._1, p._2) :: (p._2, p._1) :: Nil)\n val G = E groupBy(_._1) mapValues (_ map(_._2))\n def Color(x: Int, p: Int, c: Int): Iterator[Tuple2[Int, Int]] = Iterator((x, c)) ++ G(x).filter(_ != p).map(Color(_, x, 1 - c)).fold(Iterator.empty)(_ ++ _)\n val coloring = Color(1, -1, 0).toList.toMap;\n val black = coloring.filter{case (id, color) => color == 0}.size\n val white = N - black\n\n println(black.toLong * white - (N - 1));\n }\n}"}, {"source_code": "import java.io._\nimport java.util.Scanner\n\nobject Main{\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val N = sc.nextInt\n val edgesLines = for (i <- 0 until (N - 1)) yield (sc.nextInt, sc.nextInt)\n val E = edgesLines.flatMap(e => List(e, e.swap))\n val G = E.groupBy{case (from, to) => from}.mapValues(_.map{case (from, to) => to})\n def Color(id: Int, p: Int, color: Int): Iterator[Tuple2[Int, Int]] = Iterator((id, color)) ++ G(id).filter(_ != p).map(Color(_, id, 1 - color)).fold(Iterator.empty)(_ ++ _)\n val coloring = Color(1, -1, 0).toList\n val black = coloring.count{case (id, color) => color == 0}\n val white = N - black\n\n println(black.toLong * white - (N - 1));\n }\n}"}, {"source_code": "import java.io._\nimport java.util.Scanner\n\nobject Main{\n def main(args: Array[String]) {\n val bf = new BufferedReader(new InputStreamReader(System.in))\n val N = bf.readLine.toInt\n val edgesLines = for (i <- 0 until (N - 1)) yield bf.readLine.split(\" \")\n val E = edgesLines.map(s => (s(0).toInt, s(1).toInt)).flatMap(e => List(e, e.swap))\n val G = E.groupBy{case (from, to) => from}.mapValues(_.map{case (from, to) => to})\n def Color(id: Int, p: Int, color: Int): Iterator[Tuple2[Int, Int]] = Iterator((id, color)) ++ G(id).filter(_ != p).map(Color(_, id, 1 - color)).fold(Iterator.empty)(_ ++ _)\n val coloring = Color(1, -1, 0).toList\n val black = coloring.count{case (id, color) => color == 0}\n val white = N - black\n\n println(black.toLong * white - (N - 1));\n }\n}"}], "negative_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.collection.immutable.HashMap\n\n/**\n * @see http://codeforces.com/contest/862/problem/B\n */\n\nobject BMahmoudAndEhabAndTheBipartiteness extends App {\n /**\n * Bicoloring based of dfs\n *\n * @param g is a connected acyclic graph\n * @return\n */\n def bicoloring(g: HashMap[Int, List[Int]]): (Long, Long) = {\n @tailrec\n def dfs(h: List[(Int, List[Int], Int)], cts: (Long, Long)): (Long, Long) = {\n if (h.isEmpty) cts\n else {\n val (u, adj, c) = h.head\n if (adj.isEmpty) dfs(h.tail, (cts._1 + c ^ 1, cts._2 + c ^ 0))\n else {\n val v = adj.head\n dfs((v, g(v).filter(p => p != u), if (c == 0) 1 else 0) :: (u, adj.tail, c) :: h.tail, cts)\n }\n }\n }\n\n dfs(List((1, g(1), 0)), (0L, 0L))\n }\n\n /**\n * 1 <= n <= math.pow(10, 5)\n */\n val n = scala.io.StdIn.readLine().toInt\n\n /**\n * The adjacency-list representation of a graph\n * g is a connected acyclic graph\n */\n val g = (0 until n - 1).foldLeft(new HashMap[Int, List[Int]]) { (g, _) =>\n val Array(u, v) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n g + (v -> (u :: g.getOrElse(v, Nil)), u -> (v :: g.getOrElse(u, Nil)))\n }\n\n val (a, b) = bicoloring(g)\n println(a * b - n + 1)\n}\n"}, {"source_code": "import java.io._\nimport java.util.Scanner\n\nobject Main{\n def main(args: Array[String]) {\n val bf = new BufferedReader(new InputStreamReader(System.in))\n val N = bf.readLine.toInt\n val edgesLines = for (id <- 0 until (N - 1)) yield bf.readLine.split(\" \")\n val E = edgesLines.map(s => (s(0).toInt, s(1).toInt)).flatMap(p => (p._1, p._2) :: (p._2, p._1) :: Nil)\n val G = E groupBy(_._1) mapValues (_ map(_._2))\n def Color(x: Int, p: Int, c: Int): Iterator[Tuple2[Int, Int]] = Iterator((x, c)) ++ G(x).filter(_ != p).map(Color(_, x, 1 - c)).fold(Iterator.empty)(_ ++ _)\n val coloring = Color(1, -1, 0).toList.toMap;\n val black = coloring.filter{case (id, color) => color == 0}.size\n val white = N - black\n\n println(black * white - (N - 1));\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val N = sc.nextInt()\n val E = for (id <- 0 until (N - 1); p <- (sc.nextInt(), sc.nextInt) :: Nil; ps <- (p._1, p._2) :: (p._2, p._1) :: Nil) yield ps\n val G = E groupBy(_._1) mapValues (_ map(_._2))\n println(G)\n def Color(x: Int, p: Int, c: Int): Map[Int, Int] = G(x).filter(_ != p).map(Color(_, x, 1 - c)).flatten.toMap.updated(x, c)\n val coloring = Color(1, -1, 0);\n val black = coloring.filter{case (id, color) => color == 0}.size\n val white = N - black\n\n println(black * white - (N - 1));\n }\n}"}], "src_uid": "44b9adcc9d672221bda3a1cada81b3d0"} {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n val t = nextInt\n for (i <- 1 to t) {\n val n = nextInt\n val arr = nextInts(n)\n val odd=arr.count(_%2==1)\n println(odd min (n-odd))\n }\n\n }\n object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}", "positive_code": [{"source_code": "\r\n\r\nimport scala.io.StdIn\r\n\r\nobject Sol {\r\n def main(args: Array[String]): Unit = {\r\n val tests = StdIn.readLine().toInt\r\n (0 until tests).foreach { _ =>\r\n val _ = StdIn.readLine().toInt\r\n val numbers = StdIn.readLine().split(\" \").map(_.toLong)\r\n\r\n val (even, odd) = numbers.foldLeft((0L, 0L)) { case ((even, odd), newNumber) => (even + (1L - newNumber % 2L), odd + (newNumber % 2L)) }\r\n\r\n println(Math.min(even, odd))\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "4b33db3950303b8993812cb265fa9819"} {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n val INF = 1000000000000000000L\n def readInts: Array[Int] = readLine().split(\" \").map(_.toInt - 1)\n def readLongs: Array[Long] = readLine().split(\" \").map(_.toLong)\n\n val n = readInt\n val weights = readLongs\n\n val links = Array.fill(n)(List.empty[Int])\n (1 until n).foreach { _ =>\n val Array(a, b) = readInts\n links(a) = b :: links(a)\n links(b) = a :: links(b)\n }\n\n val branchWeights = new Array[Long](n)\n val bests = new Array[Long](n)\n val bestPairs = new Array[Long](n)\n\n def main(cur: Int, incoming: Int): Unit = {\n val children = for {\n i <- links(cur)\n if i != incoming\n } yield i\n children.foreach(main(_, cur))\n\n branchWeights(cur) = children.map(branchWeights).sum + weights(cur)\n val bestsint = children.map(bests)\n val best2 = if (children.size < 3) bestsint else bestsint.sorted.reverse.take(2)\n bests(cur) = best2.foldLeft(branchWeights(cur))(Math.max)\n val bestPairCur = if (best2.size < 2) -INF else best2.sum\n bestPairs(cur) = children.map(bestPairs).foldLeft(bestPairCur)(Math.max)\n }\n\n main(0, 0)\n val ans = bestPairs(0)\n if (ans == -INF) println(\"Impossible\") else println(ans.toString)\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject D extends App {\n val INF = 1000000000000000000L\n\n var st: StringTokenizer = _\n\n val n = readInt\n var weights = new Array[Long](n)\n var links = new Array[List[Int]](n)\n st = new StringTokenizer(readLine())\n (0 until n).foreach { id =>\n weights(id) = st.nextToken().toLong\n links(id) = Nil\n }\n\n var a: Int = _\n var b: Int = _\n (1 until n).foreach { _ =>\n st = new StringTokenizer(readLine())\n a = st.nextToken().toInt - 1\n b = st.nextToken().toInt - 1\n links(a) = b :: links(a)\n links(b) = a :: links(b)\n }\n\n var branchWeights = new Array[Long](n)\n var bests = new Array[Long](n)\n var bestPairs = new Array[Long](n)\n\n var best1 = -INF\n var best2 = -INF\n var bestc = -INF\n\n def main(cur: Int, incoming: Int): Unit = {\n val children = for {\n i <- links(cur)\n if i != incoming\n } yield i\n\n if (children.isEmpty) {\n bestc = weights(cur)\n branchWeights(cur) = bestc\n bests(cur) = bestc\n bestPairs(cur) = -INF\n return\n }\n\n children.foreach(main(_, cur))\n\n bestc = weights(cur)\n children.foreach(bestc += branchWeights(_))\n branchWeights(cur) = bestc\n\n best1 = -INF\n best2 = -INF\n children.foreach { id =>\n bestc = bests(id)\n if (bestc > best1) { best2 = best1; best1 = bestc }\n else if (bestc > best2) { best2 = bestc }\n }\n bests(cur) = Math.max(branchWeights(cur), best1)\n\n bestc = if (best2 == -INF) -INF else best1 + best2\n children.foreach { id => bestc = Math.max(bestc, bestPairs(id)) }\n bestPairs(cur) = bestc\n }\n\n main(0, 0)\n bestc = bestPairs(0)\n if (bestc == -INF) println(\"Impossible\") else println(bestc.toString)\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject D extends App {\n val INF = 1000000000000000000L\n\n def readLongs: Array[Long] = readLine().split(\" \").map(_.toLong)\n\n val n = readInt\n val weights = readLongs\n\n val links = Array.fill(n)(List.empty[Int])\n var st: StringTokenizer = _\n var a: Int = _\n var b: Int = _\n (1 until n).foreach { _ =>\n st = new StringTokenizer(readLine())\n a = st.nextToken().toInt - 1\n b = st.nextToken().toInt - 1\n links(a) = b :: links(a)\n links(b) = a :: links(b)\n }\n\n val branchWeights = new Array[Long](n)\n val bests = new Array[Long](n)\n val bestPairs = new Array[Long](n)\n\n def main(cur: Int, incoming: Int): Unit = {\n val children = for {\n i <- links(cur)\n if i != incoming\n } yield i\n children.foreach(main(_, cur))\n\n branchWeights(cur) = children.map(branchWeights).sum + weights(cur)\n val bestsint = children.map(bests)\n val best2 = if (children.size < 3) bestsint else bestsint.sorted.reverse.take(2)\n bests(cur) = best2.foldLeft(branchWeights(cur))(Math.max)\n val bestPairCur = if (best2.size < 2) -INF else best2.sum\n bestPairs(cur) = children.map(bestPairs).foldLeft(bestPairCur)(Math.max)\n }\n\n main(0, 0)\n val ans = bestPairs(0)\n if (ans == -INF) println(\"Impossible\") else println(ans.toString)\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n val INF = 1000000000000000000L\n def readInts: Array[Int] = readLine().split(\" \").map(_.toInt - 1)\n def readLongs: Array[Long] = readLine().split(\" \").map(_.toLong)\n\n val n = readInt\n val weights = readLongs\n\n val links = Array.fill(n)(List.empty[Int])\n (1 until n).foreach { _ =>\n val Array(a, b) = readInts\n links(a) = b :: links(a)\n links(b) = a :: links(b)\n }\n\n val branchWeights = new Array[Long](n)\n val bests = new Array[Long](n)\n val bestPairs = new Array[Long](n)\n\n def main(cur: Int, incoming: Int): Unit = {\n val children = for {\n i <- links(cur)\n if i != incoming\n } yield i\n children.foreach(main(_, cur))\n\n branchWeights(cur) = children.map(branchWeights).sum + weights(cur)\n val best2 = children.map(bests).sorted.reverse.take(2)\n bests(cur) = best2.headOption.foldLeft(branchWeights(cur))(Math.max)\n val bestPairCur = if (best2.size < 2) -INF else best2.sum\n bestPairs(cur) = children.map(bestPairs).foldLeft(bestPairCur)(Math.max)\n }\n\n main(0, 0)\n val ans = bestPairs(0)\n if (ans == -INF) println(\"Impossible\") else println(ans.toString)\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nimport scala.collection.mutable\n\nobject D extends App {\n val INF = 1000000000000000000L\n\n var st: StringTokenizer = _\n\n val n = readInt\n var weights = new Array[Long](n)\n var links = new Array[List[Int]](n)\n st = new StringTokenizer(readLine())\n (0 until n).foreach { id =>\n weights(id) = st.nextToken().toLong\n links(id) = Nil\n }\n\n var a: Int = _\n var b: Int = _\n (1 until n).foreach { _ =>\n st = new StringTokenizer(readLine())\n a = st.nextToken().toInt - 1\n b = st.nextToken().toInt - 1\n links(a) = b :: links(a)\n links(b) = a :: links(b)\n }\n\n var branchWeights = new Array[Long](n)\n var bests = new Array[Long](n)\n var bestPairs = new Array[Long](n)\n\n var best1 = -INF\n var best2 = -INF\n var bestc = -INF\n\n def dfs(cur: Int, incoming: Int): Unit = {\n var pair = (0, 0)\n val stack1 = new mutable.Stack[(Int, Int)]\n val stack2 = new mutable.Stack[Int]\n stack1.push((cur, incoming))\n stack2.push(cur)\n while (stack1.nonEmpty) {\n pair = stack1.pop()\n a = pair._1\n links(a) = links(a).filterNot(_ == pair._2)\n links(a).foreach { id =>\n stack1.push((id, a))\n stack2.push(id)\n }\n }\n while (stack2.nonEmpty) process(stack2.pop)\n }\n\n def process(cur: Int): Unit = {\n val children = links(cur)\n\n bestc = weights(cur)\n children.foreach(bestc += branchWeights(_))\n branchWeights(cur) = bestc\n\n best1 = -INF\n best2 = -INF\n children.foreach { id =>\n bestc = bests(id)\n if (bestc > best1) { best2 = best1; best1 = bestc }\n else if (bestc > best2) { best2 = bestc }\n }\n bests(cur) = Math.max(branchWeights(cur), best1)\n\n bestc = if (best2 == -INF) -INF else best1 + best2\n children.foreach { id => bestc = Math.max(bestc, bestPairs(id)) }\n bestPairs(cur) = bestc\n }\n\n dfs(0, 0)\n bestc = bestPairs(0)\n if (bestc == -INF) println(\"Impossible\") else println(bestc.toString)\n}\n"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nobject D extends App {\n val INF = 1000000000000000000L\n\n var st: StringTokenizer = _\n\n val n = readInt\n var weights = new Array[Long](n)\n var links = new Array[List[Int]](n)\n st = new StringTokenizer(readLine())\n (0 until n).foreach { id =>\n weights(id) = st.nextToken().toLong\n links(id) = Nil\n }\n\n var a: Int = _\n var b: Int = _\n (1 until n).foreach { _ =>\n st = new StringTokenizer(readLine())\n a = st.nextToken().toInt - 1\n b = st.nextToken().toInt - 1\n links(a) = b :: links(a)\n links(b) = a :: links(b)\n }\n\n var branchWeights = new Array[Long](n)\n var bests = new Array[Long](n)\n var bestPairs = new Array[Long](n)\n\n var best1 = -INF\n var best2 = -INF\n var bestc = -INF\n\n def main(cur: Int, incoming: Int): Unit = {\n links(a)\n val children = for {\n i <- links(cur)\n if i != incoming\n } yield i\n\n if (children.isEmpty) {\n bestc = weights(cur)\n branchWeights(cur) = bestc\n bests(cur) = bestc\n bestPairs(cur) = -INF\n return\n }\n\n children.foreach(main(_, cur))\n\n bestc = weights(cur)\n children.foreach(bestc += branchWeights(_))\n branchWeights(cur) = bestc\n\n best1 = -INF\n best2 = -INF\n children.foreach { id =>\n bestc = bests(id)\n if (bestc > best1) { best2 = best1; best1 = bestc }\n else if (bestc > best2) { best2 = bestc }\n }\n bests(cur) = Math.max(branchWeights(cur), best1)\n\n bestc = if (best2 == -INF) -INF else best1 + best2\n children.foreach { id => bestc = Math.max(bestc, bestPairs(id)) }\n bestPairs(cur) = bestc\n }\n\n if (n < 100000) {\n main(0, 0)\n bestc = bestPairs(0)\n if (bestc == -INF) println(\"Impossible\") else println(bestc.toString)\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n val INF = 1000000000000000000L\n def readInts: Array[Int] = readLine().split(\" \").map(_.toInt - 1)\n def readLongs: Array[Long] = readLine().split(\" \").map(_.toLong)\n\n val n = readInt\n val weights = readLongs\n\n val links = Array.fill(n)(mutable.ListBuffer.empty[Int])\n (1 until n).foreach { _ =>\n val Array(a, b) = readInts\n links(a) += b\n links(b) += a\n }\n\n val branchWeights = new Array[Long](n)\n val bests = new Array[Long](n)\n val bestPairs = new Array[Long](n)\n\n if (n < 100000) {\n def main(cur: Int, incoming: Int): Unit = {\n val children = for {\n i <- links(cur)\n if i != incoming\n } yield i\n children.foreach(main(_, cur))\n\n branchWeights(cur) = children.map(branchWeights).sum + weights(cur)\n val best2 = children.map(bests).sorted.reverse.take(2)\n bests(cur) = best2.headOption.foldLeft(branchWeights(cur))(Math.max)\n val bestPairCur = if (best2.size < 2) -INF else best2.sum\n bestPairs(cur) = children.map(bestPairs).foldLeft(bestPairCur)(Math.max)\n }\n\n main(0, 0)\n val ans = bestPairs(0)\n if (ans == -INF) println(\"Impossible\") else println(ans.toString)\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n def readInts = readLine().split(\" \").map(_.toInt)\n def readLongs = readLine().split(\" \").map(_.toLong)\n\n val n = readInt\n val nodes = readLongs.zipWithIndex.map { case (w, id) => new Node(id, w) }\n\n (1 until n).foreach { _ =>\n val Array(a, b) = readInts.map(_ - 1)\n nodes(a).links += b\n nodes(b).links += a\n }\n\n class Node(val id: Int, val w: Long) {\n val links = mutable.ListBuffer.empty[Int]\n\n var done: Boolean = false\n var best: Long = 0\n var bestPair: Option[Long] = None\n var weight: Long = 0\n\n def main(incoming: Int): Unit = {\n if (!done) {\n val children = for {\n i <- links\n if i != incoming\n } yield nodes(i)\n children.foreach(_.main(id))\n\n weight = children.map(_.weight).sum + w\n val best2 = children.map(_.best).foldLeft(List[Long]()){(l, n) => (n :: l).sorted.take(2)}\n best = (weight +: best2).max\n val bestPairCur: Option[Long] = if (best2.size < 2) None else Some(best2.sum)\n val bestPairs = children.flatMap(_.bestPair) ++ bestPairCur\n bestPair = if (bestPairs.nonEmpty) Some(bestPairs.max) else None\n done = true\n }\n }\n }\n\n nodes(0).main(0)\n println(nodes(0).bestPair.fold(\"Impossible\")(_.toString))\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n val INF = 1000000000000000000L\n def readInts: Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs: Array[Long] = readLine().split(\" \").map(_.toLong)\n\n val n = readInt\n val weights = readLongs\n\n if (n < 100000) {\n val links = Array.fill(n)(mutable.ListBuffer.empty[Int])\n (1 until n).foreach { _ =>\n val Array(a, b) = readInts.map(_ - 1)\n links(a) += b\n links(b) += a\n }\n\n val branchWeights = new Array[Long](n)\n val bests = new Array[Long](n)\n val bestPairs = new Array[Long](n)\n\n def main(cur: Int, incoming: Int): Unit = {\n val children = for {\n i <- links(cur)\n if i != incoming\n } yield i\n children.foreach(main(_, cur))\n\n branchWeights(cur) = children.map(branchWeights).sum + weights(cur)\n val best2 = children.map(bests).sorted.reverse.take(2)\n bests(cur) = best2.headOption.foldLeft(branchWeights(cur))(Math.max)\n val bestPairCur = if (best2.size < 2) -INF else best2.sum\n bestPairs(cur) = children.map(bestPairs).foldLeft(bestPairCur)(Math.max)\n }\n\n main(0, 0)\n val ans = bestPairs(0)\n if (ans == -INF) println(\"Impossible\") else println(ans.toString)\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n val INF = 1000000000000000000L\n def readInts: Array[Int] = readLine().split(\" \").map(_.toInt - 1)\n def readLongs: Array[Long] = readLine().split(\" \").map(_.toLong)\n\n val n = readInt\n val weights = readLongs\n\n val links = Array.fill(n)(mutable.ListBuffer.empty[Int])\n (1 until n).foreach { _ =>\n val Array(a, b) = readInts\n links(a) += b\n links(b) += a\n }\n if (n < 100000) {\n\n val branchWeights = new Array[Long](n)\n val bests = new Array[Long](n)\n val bestPairs = new Array[Long](n)\n\n def main(cur: Int, incoming: Int): Unit = {\n val children = for {\n i <- links(cur)\n if i != incoming\n } yield i\n children.foreach(main(_, cur))\n\n branchWeights(cur) = children.map(branchWeights).sum + weights(cur)\n val best2 = children.map(bests).sorted.reverse.take(2)\n bests(cur) = best2.headOption.foldLeft(branchWeights(cur))(Math.max)\n val bestPairCur = if (best2.size < 2) -INF else best2.sum\n bestPairs(cur) = children.map(bestPairs).foldLeft(bestPairCur)(Math.max)\n }\n\n main(0, 0)\n val ans = bestPairs(0)\n if (ans == -INF) println(\"Impossible\") else println(ans.toString)\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n val INF = 1000000000000000000L\n def readInts: Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs: Array[Long] = readLine().split(\" \").map(_.toLong)\n\n val n = readInt\n val weights = readLongs\n val links = Array.fill(n)(mutable.ListBuffer.empty[Int])\n (1 until n).foreach { _ =>\n val Array(a, b) = readInts.map(_ - 1)\n links(a) += b\n links(b) += a\n }\n\n val branchWeights = new Array[Long](n)\n val bests = new Array[Long](n)\n val bestPairs = new Array[Long](n)\n\n def main(cur: Int, incoming: Int): Unit = {\n val children = for {\n i <- links(cur)\n if i != incoming\n } yield i\n children.foreach(main(_, cur))\n\n branchWeights(cur) = children.map(branchWeights).sum + weights(cur)\n val best2 = children.map(bests).sorted.reverse.take(2)\n bests(cur) = best2.headOption.foldLeft(branchWeights(cur))(Math.max)\n val bestPairCur = if (best2.size < 2) -INF else best2.sum\n bestPairs(cur) = children.map(bestPairs).foldLeft(bestPairCur)(Math.max)\n }\n\n if (n < 100000) main(0, 0)\n val ans = bestPairs(0)\n if (ans == -INF) println(\"Impossible\") else println(ans.toString)\n}\n"}], "src_uid": "14b65af01caf1f3971a2f671589b86a8"} {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn._\nimport scala.math.max\nobject Task4 extends App {\n @tailrec def solve(ps: List[Int], acc: Int = 0): (List[Int], Int) = ps match {\n case x :: xs => solve(xs.filter(_ != x), acc + max(xs.indexOf(x), 0))\n case Nil => (Nil, acc)\n }\n val n = readInt\n val ps = readLine.split(' ').map(_.toInt).toList\n println(solve(ps)._2)\n}", "positive_code": [{"source_code": "\nimport scala.collection.mutable._\n\nobject Main{\n def main(args: Array[String]) {\n var n = readInt()\n val ll = LinkedList[Int]() ++ readLine.split(\" \").map(_.toInt)\n var swaps = 0\n var prev = ll\n while(n != 0){\n var current = prev.next\n var pc = prev\n while(prev.elem != current.elem){\n pc = current\n current = current.next\n swaps += 1\n }\n pc.next = current.next\n prev = prev.next\n n -= 1\n }\n println(swaps)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject D {\n\n def main(args: Array[String]): Unit = {\n val pairs = StdIn.readInt()\n val arr = StdIn.readLine().split(\" \").map(_.toInt)\n\n val indices = 0 until pairs\n\n def isOk(): Boolean = {\n indices.forall(i => arr(2 * i) == arr(2 * i + 1))\n }\n\n var count = 0\n def swap(i: Int, j: Int): Unit = {\n val temp = arr(i)\n arr(i) = arr(j)\n arr(j) = temp\n count += 1\n }\n\n while (!isOk()) {\n indices\n .find(i => arr(2 * i) != arr(2 * i + 1))\n .foreach {index =>\n val guest = arr(2 * index)\n var last = arr.lastIndexOf(guest)\n\n while (arr(2 * index + 1) != guest) {\n swap(last, last-1)\n last -= 1\n }\n }\n }\n\n println(count)\n }\n\n}\n\n"}], "negative_code": [], "src_uid": "194bc63b192a4e24220b36984901fb3b"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt\n val a = readLine().split(\" \").map(_.toInt)\n \n val len = a.size\n val reverse = \"L\" * (len - 1)\n val max = a.max\n for(i <- 1 to max) {\n for(j <- 0 until len - 1) {\n if(a(j) >= i) print(\"PR\")\n else print(\"R\")\n }\n if (a(len - 1) >= i) print(\"P\")\n if (i != max) print(reverse)\n }\n }\n}", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _379B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt).toArray\n val ans = new StringBuilder\n\n def doit(i: Int): Unit = {\n if (i < n) {\n if (a(i) == 0) {\n if (i < n - 1) ans += 'R'\n doit(i + 1)\n }\n else {\n ans += 'P'\n a(i) -= 1\n if (a(i) == 0) {\n if (i < n - 1) ans += 'R'\n doit(i + 1)\n } else {\n if (i == 0) ans ++= \"RL\"\n else ans ++= \"LR\"\n doit(i)\n }\n }\n }\n }\n\n doit(0)\n println(ans.toString)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n var left = data.sum\n var i = 0\n var result = List.empty[Char]\n var lbound = -1\n var took = false\n while (left != 0) {\n if (lbound == -1 && data(i) > 0)\n lbound = i\n if (data(i) > 0 && !took) {\n result ::= 'P'\n data(i) -= 1\n left -= 1\n took = true\n if (lbound == i && data(i) == 0)\n lbound = -1\n } else if (i != 0 && (lbound != -1 && lbound < i || i == n - 1)) {\n result ::= 'L'\n i -= 1\n took = false\n } else {\n result ::= 'R'\n i += 1\n took = false\n }\n }\n println(result.reverse.mkString)\n}"}, {"source_code": "\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n\n val n = input.next().toInt\n val a = input.next().split(\" \").map(_.toInt).toList.toArray\n\n val sum = a.sum\n\n var cu = 0\n var p = 0\n\n var l = List.empty[Char]\n while (cu < sum) {\n if (a(p) == 0) {\n l = 'R' :: l\n p += 1\n } else if (p == a.length - 1) {\n l = 'R' :: 'L' :: 'P' :: l\n a(p) -= 1\n cu += 1\n } else if (p+1 < a.size && a(p+1) > 0 && a(p) > 1) {\n l = 'L' :: 'P' :: 'R' :: 'P' :: l\n cu += 2\n a(p) -= 1\n a(p+1) -= 1\n } else if (a(p) > 1) {\n l = 'L' :: 'R' :: 'P' :: l\n a(p) -= 1\n cu += 1\n } else {\n l = 'R' :: 'P' :: l\n a(p) -= 1\n cu += 1\n p += 1\n }\n }\n while (l.head != 'P') l = l.tail\n print(l.reverse.mkString)\n }\n}\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val n = readInt\n val as = readInts(n)\n val moves = Array.ofDim[Char](1000000)\n var m = 0\n\n var i = 0\n while (i < n) {\n if (as(i) > 0) {\n moves(m) = 'P'\n m += 1\n as(i) -= 1\n }\n moves(m) = if (i < n - 1) 'R' else 'L'\n m += 1\n if (as(i) > 0) {\n moves(m) = if (moves(m - 1) == 'R') 'L' else 'R'\n m += 1\n } else i += 1\n }\n\n println(moves.take(m).mkString)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P379B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val A = List.fill(N)(sc.nextInt)\n \n def solve(): Unit = {\n val a0 = A.head\n out.print(List.fill(a0)(\"P\").mkString(\"RL\"))\n A.tail foreach { i =>\n out.print(List.fill(i)(\"P\").mkString(\"R\", \"LR\", \"\"))\n }\n }\n\n solve\n out.println\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-28.\n */\nobject B379 extends App{\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n var i = 0\n\n while (i < n) {\n val m = sc.nextInt()\n if (i < n - 1) {\n if (m == 0) {\n print('R')\n } else {\n print(\"P\" + \"RLP\" * (m - 1) + \"R\")\n }\n } else {\n if (m != 0) {\n print(\"P\" + \"LRP\" * (m - 1))\n }\n }\n\n i += 1\n }\n}\n"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _379B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt).toArray\n val ans = new StringBuilder\n\n def doit(i: Int): Unit = {\n if (i < n) {\n if (a(i) == 0) {\n if (i < n - 1) ans += 'R'\n ans += 'R'\n doit(i + 1)\n }\n else {\n ans += 'P'\n a(i) -= 1\n if (a(i) == 0) {\n if (i < n - 1) ans += 'R'\n doit(i + 1)\n } else {\n if (i == 0) ans ++= \"RL\"\n else ans ++= \"LR\"\n doit(i)\n }\n }\n }\n }\n\n doit(0)\n println(ans.toString)\n}\n"}, {"source_code": "\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n\n val n = input.next().toInt\n val a = input.next().split(\" \").map(_.toInt).toList.toArray\n\n val sum = a.sum\n\n var cu = 0\n var p = 0\n\n var l = List.empty[Char]\n while (cu < sum) {\n if (a(p) == 0) {\n l = 'R' :: l\n p += 1\n } else if (p+1 < a.size && a(p+1) > 0 && a(p) > 1) {\n l = 'L' :: 'P' :: 'R' :: 'P' :: l\n cu += 2\n a(p) -= 1\n println(a.size + \" \" + p)\n a(p+1) -= 1\n } else if (a(p) > 1) {\n l = 'L' :: 'R' :: 'P' :: l\n a(p) -= 1\n cu += 1\n } else {\n l = 'R' :: 'P' :: l\n a(p) -= 1\n cu += 1\n p += 1\n }\n }\n print(l.reverse.mkString)\n }\n}\n"}, {"source_code": "\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n\n val n = input.next().toInt\n val a = input.next().split(\" \").map(_.toInt).toList.toArray\n\n val sum = a.sum\n\n var cu = 0\n var p = 0\n\n var l = List.empty[Char]\n while (cu < sum) {\n if (a(p) == 0) {\n l = 'R' :: l\n p += 1\n } else if (p == a.length - 1) {\n l = 'R' :: 'L' :: 'P' :: l\n a(p) -= 1\n cu += 1\n } else if (p+1 < a.size && a(p+1) > 0 && a(p) > 1) {\n l = 'L' :: 'P' :: 'R' :: 'P' :: l\n cu += 2\n a(p) -= 1\n println(a.size + \" \" + p)\n a(p+1) -= 1\n } else if (a(p) > 1) {\n l = 'L' :: 'R' :: 'P' :: l\n a(p) -= 1\n cu += 1\n } else {\n l = 'R' :: 'P' :: l\n a(p) -= 1\n cu += 1\n p += 1\n }\n }\n while (l.head != 'P') l = l.tail\n print(l.reverse.mkString)\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-28.\n */\nobject B379 extends App{\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n var i = 0\n\n while (i < n) {\n val m = sc.nextInt()\n if (i < n - 1) {\n if (m == 0) {\n print('R')\n } else {\n print(\"P\" + \"RLP\" * (m - 1) + \"R\")\n }\n } else {\n if (i != 0) {\n print(\"P\" + \"LRP\" * (m - 1))\n }\n }\n\n i += 1\n }\n}\n"}], "src_uid": "50e88225d8b081d63eebe446f48057f4"} {"source_code": "object B230 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def isPrime(n: Long): Boolean = {\n var i = 2\n while(i*i <= n){\n if(n % i == 0) {\n return false\n }\n i += 1\n }\n true\n }\n\n def genPrimes(till: Int): Set[Int] = {\n val isPrime = Array.fill[Boolean](till+1)(true)\n isPrime(0) = false\n isPrime(1) = false // not composite\n for(i <- 4 to till by 2) {\n isPrime(i) = false\n }\n for(i <- 3 to till by 2 if isPrime(i)) {\n for(j <- i+i to till by i) isPrime(j) = false\n }\n isPrime.zipWithIndex.filter(_._1).map(_._2).toSet\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val primes = genPrimes(1000000)\n val input = readLongs(n).map{ num =>\n val sqrt = math.sqrt(num)\n if(num != 1 && sqrt%1 == 0 && primes.contains(sqrt.toInt)) true else false\n }\n println(input.map(x => if(x) \"YES\" else \"NO\").mkString(\"\\n\"))\n }\n}", "positive_code": [{"source_code": "object Main extends App {\n val bound = 1000010\n val primes = Array.ofDim[Boolean](bound)\n for {\n i <- 2 until bound\n if (!primes(i))\n j <- 2 * i until bound by i\n } primes(j) = true\n\n val n = readInt()\n val a = readLine().split(\" \").map(_.toLong).map {\n case n if n < 3 => \"NO\"\n case n if n == 4 => \"YES\"\n case n if n % 2 == 0 => \"NO\"\n case n =>\n val sqrt = Math.round(Math.sqrt(n))\n if (sqrt * sqrt != n) \"NO\"\n else if (!primes(sqrt.toInt)) \"YES\"\n else \"NO\"\n }\n println(a.mkString(\"\\n\"))\n}"}, {"source_code": "import java.io.OutputStreamWriter\nimport java.io.BufferedWriter\nimport java.util.StringTokenizer\n\nobject _230B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n\n val MAX = 1000001\n val isPrime = Array.fill(MAX)(true)\n isPrime(0) = false\n isPrime(1) = false\n\n {\n var i = 2\n while(i * i < MAX) {\n if (isPrime(i)) {\n var j = i + i\n while(j < MAX) {\n isPrime(j) = false\n j += i\n }\n }\n i += 1\n }\n }\n\n val primes = (0 until MAX).filter(i => isPrime(i))\n val cand = primes.map(i => i.toLong * i).toSet\n\n\n val cout = new BufferedWriter(new OutputStreamWriter(System.out))\n for (i <- 1 to next.toInt) {\n val x = next.toLong\n if (cand.contains(x)) cout.write(\"YES\\n\")\n else cout.write(\"NO\\n\")\n }\n\n cout.close\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n in.next()\n val sieve = Array.ofDim[Boolean](1000001)\n (2 to 1000000).foreach { i =>\n if (!sieve(i)) {\n (i * 2 to 1000000 by i).foreach { j => sieve(j) = true }\n }\n }\n\n println(in.next().split(\" \").map(_.toLong).map {\n case n if n < 3 => \"NO\"\n case n if n == 4 => \"YES\"\n case n if n % 2 == 0 => \"NO\"\n case n =>\n val sqrt = Math.round(Math.sqrt(n))\n\n if (sqrt * sqrt != n)\n \"NO\"\n else {\n if (!sieve(sqrt.toInt))\n \"YES\"\n else\n \"NO\"\n }\n\n }.mkString(\"\\n\"))\n\n\n}"}, {"source_code": "object Solution {\n import java.util.Scanner\n\n def main(args:Array[String]) {\n val it = new Iterator[Long] {\n private val sc = new Scanner(System.in)\n def hasNext = sc.hasNextLong\n def next = sc.nextLong\n }\n\n val tprimes = (new PrimeSet(1000000)).iterator.map(p => p.toLong * p).toSet\n\n val n = it.next\n it.take(n.toInt).foreach { x =>\n if (tprimes.contains(x))\n println(\"YES\")\n else\n println(\"NO\")\n }\n }\n}\n\nclass PrimeSet(N:Int) extends Iterable[Int] {\n import java.util.BitSet\n\n private var sieved = 1\n private val flags = new BitSet()\n flags.set(2, N)\n\n private def square(n:Int) = BigInt(n).pow(2)\n\n def from(n:Int):Iterator[Int] = {\n if (n > sieved) from(sieved).dropWhile(n >)\n else new Iterator[Int] {\n private var p = flags.nextSetBit(n)\n def hasNext = p != -1\n def next = {\n val q = p\n if (q > sieved) {\n if (square(q) <= N) {\n (q * q to N by q).foreach(flags.clear(_))\n sieved = q\n } else {\n sieved = N\n }\n }\n p = flags.nextSetBit(p+1)\n q\n }\n }\n }\n\n def contains(n:Int) = {\n if (sieved < N && square(sieved) < n) {\n val sqrt = math.sqrt(n)\n from(sieved).dropWhile(sqrt >).next\n }\n flags.get(n)\n }\n\n def iterator = from(2)\n}\n"}, {"source_code": "object B230 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def isPrime(n: Long): Boolean = {\n var i = 2\n while(i*i <= n){\n if(n % i == 0) {\n return false\n }\n i += 1\n }\n true\n }\n\n def genPrimes(till: Int): Array[Boolean] = {\n val isPrime = Array.fill[Boolean](till+1)(true)\n isPrime(0) = false\n isPrime(1) = false // not composite\n for(i <- 4 to till by 2) {\n isPrime(i) = false\n }\n for(i <- 3 to till by 2 if isPrime(i)) {\n for(j <- i+i to till by i) isPrime(j) = false\n }\n isPrime\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val primes = genPrimes(1000000)\n val input = readLongs(n).map{ num =>\n val sqrt = math.sqrt(num)\n if(num != 1 && sqrt%1 == 0 && primes(sqrt.toInt)) true else false\n }\n println(input.map(x => if(x) \"YES\" else \"NO\").mkString(\"\\n\"))\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\nimport scala.collection.mutable.ArrayBuffer\nimport java.util.Arrays.binarySearch\n\n\nobject P230B extends App {\n\n object PrimeNumber {\n def apply(n: Int = 1000000): Array[Int] = sieve(n)\n \n def sieve(n: Int): Array[Int] = {\n val primes = new ArrayBuffer[Int]\n val isPrime = Array.fill(n + 1)(true)\n \n @tailrec\n def loop(i: Int): Unit = {\n \n @tailrec\n def innerLoop(j: Int): Unit = {\n if (j > n) ()\n else {\n isPrime(j) = false\n innerLoop(j + i)\n }\n }\n \n if (i > n) ()\n else {\n if (isPrime(i)) {\n primes += i\n innerLoop(i * 2)\n }\n loop(i + 1)\n }\n }\n \n loop(2)\n primes.toArray\n }\n }\n\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val tPrimes: Set[Long] = PrimeNumber(1000000).map(x => x.toLong * x.toLong).toSet\n for (_ <- 0 until sc.nextInt) {\n out.println(if (tPrimes(sc.nextLong)) \"YES\" else \"NO\") }\n \n out.close\n}\n\n\n\n\n\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val max = 1000000\n val isPrime = Array.ofDim[Boolean](max).map(_ => true)\n var i = 2\n while(i < max) {\n if(isPrime(i)) {\n var j = i.toLong * i\n while(j < max) {\n isPrime(j.toInt) = false\n j += i\n }\n }\n i += 1\n }\n val squaredPrimes = (for(i <- 2 until max if isPrime(i)) yield i.toLong * i).toSet\n reader.readLine()\n def ans = readLongs.map(x => if(squaredPrimes.contains(x)) \"YES\" else \"NO\").mkString(\"\\n\")\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def sieve(n: Int) = {\n val primes = scala.collection.mutable.BitSet(2) ++ (3 to n by 2)\n for {\n cand <- 3 to Math.sqrt(n).toInt by 2\n if primes contains cand\n } primes --= (cand * cand to n by cand)\n primes\n }\n \n val primes = sieve(1000001).map{ i => i.toLong * i.toLong }\n\n def main(args: Array[String]) = {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toLong)\n a.foreach{i => \n if (primes contains i) println(\"YES\")\n else println(\"NO\")\n }\n }\n}"}, {"source_code": "import scala.math._\nimport scala.collection.immutable.TreeSet\n\nobject Olymp{\n def primes(N: Int): TreeSet[Int] = {\n var p = new Array[Boolean](N+1)\n for(i <- 2 to sqrt(N).round.toInt)\n if (!p(i)){\n for(j <- i*i to N by i)\n p(j) = true\n }\n var ret = new TreeSet[Int]\n for(i <- 2 to N)\n if (!p(i))\n ret = ret + i\n ret\n }\n def main(args: Array[String]): Unit = {\n val n = readLine toInt\n val p = readLine split (' ') map (_ toLong)\n val pr = primes(1000000)\n for (i <- p){\n if (i != 1 && abs(sqrt(i) - sqrt(i).round) < 1e-8 && pr.contains(sqrt(i).round.toInt)) println(\"YES\")\n else println(\"NO\")\n }\n }\n}"}, {"source_code": "import scala.io.StdIn._\nimport scala.language.postfixOps\n\nobject TaskA extends App {\n val n = readInt\n val list = readLine.split(\" \").map(_.toLong)\n\n val max = 1e6 toInt\n val primes = Array.fill(max + 1)(true)\n primes(1) = false\n\n for(i <- 2 to 1000) {\n if (primes(i)) {\n var next = i * i\n while (next <= max) {\n primes(next) = false\n next += i\n }\n }\n }\n\n println(list.map(isTPrime)\n .map(b => if (b) \"YES\" else \"NO\")\n .mkString(\"\\n\"))\n\n def isTPrime(x: Long) = {\n val sqrt = math.sqrt(x).toLong\n sqrt * sqrt == x && primes(sqrt.toInt)\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n in.next()\n val sieve = Array.ofDim[Boolean](100001)\n (3 to 100000 by 2).foreach { i =>\n if (!sieve(i)) {\n (i to 100000 by i).foreach { j => sieve(j) = true }\n }\n }\n\n\n\n println(in.next().split(\" \").map(_.toLong).map {\n case n if n < 3 => \"NO\"\n case n if n == 4 => \"YES\"\n case n if n % 2 == 0 => \"NO\"\n case n =>\n val sqrt = Math.sqrt(n).toLong\n if (sqrt * sqrt != n)\n \"NO\"\n else {\n val sqrtsqrt = Math.sqrt(sqrt).toInt\n if (!sieve(sqrtsqrt))\n \"YES\"\n else\n \"NO\"\n }\n\n }.mkString(\"\\n\"))\n\n\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n in.next()\n println(in.next().split(\" \").map(_.toLong).map {\n case n if n < 3 => \"NO\"\n case n if n == 4 => \"YES\"\n case n if n % 2 == 0 => \"NO\"\n case n =>\n val sqrt = Math.sqrt(n).toLong\n if (sqrt * sqrt != n)\n \"NO\"\n else {\n val sqrtsqrt = Math.sqrt(sqrt).toLong\n if ((3l until sqrtsqrt by 2).forall(n % _ != 0))\n \"YES\"\n else\n \"NO\"\n }\n\n }.mkString(\"\\n\"))\n\n\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n in.next()\n println(in.next().split(\" \").map(_.toLong).map {\n case n if n < 3 => \"NO\"\n case n if n == 4 => \"YES\"\n case n if n % 2 == 0 => \"NO\"\n case n =>\n val sqrt = Math.sqrt(n).toLong\n if (sqrt * sqrt != n)\n \"NO\"\n else {\n val sqrtsqrt = Math.sqrt(sqrt).toLong\n if (sqrtsqrt * sqrtsqrt == n && (3l until sqrtsqrt by 2).forall(n % _ != 0))\n \"YES\"\n else\n \"NO\"\n }\n\n }.mkString(\"\\n\"))\n\n\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n in.next()\n val sieve = Array.ofDim[Boolean](100001)\n sieve(1) = true\n sieve(3) = true\n (3 to 100000 by 2).foreach { i =>\n if (sieve(i)) {\n (i to 100000 by i).foreach { j => sieve(j) = true }\n }\n }\n\n\n\n println(in.next().split(\" \").map(_.toLong).map {\n case n if n < 3 => \"NO\"\n case n if n == 4 => \"YES\"\n case n if n % 2 == 0 => \"NO\"\n case n =>\n val sqrt = Math.sqrt(n).toLong\n if (sqrt * sqrt != n)\n \"NO\"\n else {\n val sqrtsqrt = Math.sqrt(sqrt).toInt\n if (sieve(sqrtsqrt))\n \"YES\"\n else\n \"NO\"\n }\n\n }.mkString(\"\\n\"))\n\n\n}"}, {"source_code": "object B230 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readLongs(n).map{ num => if(num != 1 && math.sqrt(num)%1 == 0) true else false}\n println(input.map(x => if(x) \"YES\" else \"NO\").mkString(\"\\n\"))\n }\n}"}, {"source_code": "object Main {\n def sieve(n: Long) = {\n val primes = scala.collection.mutable.BitSet(2) ++ (3L to n by 2)\n for {\n cand <- 3L to Math.sqrt(n).toLong by 2\n if primes contains cand\n } primes --= (cand * cand to n by cand)\n primes\n }\n \n val primes = sieve(1000000L)\n\n def main(args: Array[String]) = {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toLong)\n a.foreach{i => \n val sq = Math.sqrt(i).toInt\n if (sq * sq != i) println(\"NO\")\n else if (primes contains sq) println(\"YES\")\n else println(\"NO\")\n }\n }\n}"}, {"source_code": "import scala.math._\n\nobject Olymp{\n def main(args: Array[String]): Unit = {\n val n = readLine toInt\n val p = readLine split (' ') map (_ toLong)\n for (i <- p){\n if (abs(sqrt(i) - sqrt(i).round) < 1e-8) println(\"YES\")\n else println(\"NO\")\n }\n }\n}"}, {"source_code": "import scala.math._\n\nobject Olymp{\n def main(args: Array[String]): Unit = {\n val n = readLine toInt\n val p = readLine split (' ') map (_ toLong)\n for (i <- p){\n if (i != 1 && abs(sqrt(i) - sqrt(i).round) < 1e-8) println(\"YES\")\n else println(\"NO\")\n }\n }\n}"}, {"source_code": "import scala.math._\n\nobject Olymp{\n def isPrime(n: Long) = (2 until sqrt(n).round.toInt) forall (n % _ != 0) \n def main(args: Array[String]): Unit = {\n val n = readLine toInt\n val p = readLine split (' ') map (_ toLong)\n for (i <- p){\n if (isPrime(i) && abs(sqrt(i) - sqrt(i).round) < 1e-8) println(\"YES\")\n else println(\"NO\")\n }\n }\n}"}, {"source_code": "import scala.io.StdIn._\nimport scala.language.postfixOps\n\nobject TaskA extends App {\n val n = readInt\n val list = readLine.split(\" \").map(_.toLong)\n\n val max = 1e6 toInt\n val primes = Array.fill(max + 1)(true)\n primes(1) = false\n\n for(i <- 2 to 1000) {\n if (primes(i)) {\n var next = i * i\n while (next < max) {\n primes(next) = false\n next += i\n }\n }\n }\n\n println(list.map(isTPrime)\n .map(b => if (b) \"YES\" else \"NO\")\n .mkString(\"\\n\"))\n\n def isTPrime(x: Long) = {\n val sqrt = math.sqrt(x).toLong\n sqrt * sqrt == x && primes(sqrt.toInt)\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\nimport scala.language.postfixOps\n\nobject TaskA extends App {\n val n = readInt\n val list = readLine.split(\" \").map(_.toLong)\n\n val max = 1e6 toInt\n val primes = Array.fill(max + 1)(true)\n\n for(i <- 2 to 1000) {\n if (primes(i)) {\n var next = i * i\n while (next < max) {\n primes(next) = false\n next += i\n }\n }\n }\n\n list.map(isTPrime)\n .map(b => if (b) \"YES\" else \"NO\")\n .foreach(println)\n\n def isTPrime(x: Long) = {\n val sqrt = math.sqrt(x).toLong\n sqrt * sqrt == x && primes(sqrt.toInt)\n }\n}\n"}], "src_uid": "6cebf9af5cfbb949f22e8b336bf07044"} {"source_code": "import java.util.StringTokenizer\n\nobject _327B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n var a = Vector[Int]()\n val isok = Array.fill(10000001)(true)\n var i = 2\n\n while(a.size < n) {\n if (isok(i)) {\n a = a :+ i\n var j = i + i\n while(j < isok.length) {\n isok(j) = false\n j += i\n }\n }\n i += 1\n }\n\n println(a.mkString(\" \"))\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P327B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n out.println(List.range(10000000 - sc.nextInt, 10000000).mkString(\" \"))\n out.close\n}\n\n\n\n\n\n"}, {"source_code": "import java.util.Scanner\nimport scala.math._\nimport scala.collection.mutable.ListBuffer\n\nobject R327_B extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n \n println(answer(n).mkString(\" \"))\n \n def answer(n:Int):Seq[Int] = {\n var list = new ListBuffer[Int]()\n var s = 10000000 - n + 1\n list.append(s)\n while(s < 10000000){\n s += 1\n list.append(s) \n }\n //println(list)\n list\n }\n\n}"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val max = 10 * 1000 * 1000\n def ans = (max to max - readInt + 1 by -1).reverse.mkString(\" \")\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def sieveOfEratosthenes(nTo: Int) = {\n val primes = collection.mutable.BitSet.empty ++ (2 to nTo)\n for {\n candidate <- 2 until Math.sqrt(nTo).toInt\n if primes contains candidate\n } primes --= candidate * candidate to nTo by candidate\n primes\n }\n \n val simple0 = sieveOfEratosthenes(1299709)\n \n def main(args: Array[String]) {\n val n = readInt()\n println(simple0.take(n).mkString(\" \"))\n }\n}"}, {"source_code": "object Hungry {\n def main(args:Array[String]){\n val n=readInt\n n until 2*n foreach(x=>print(x+\" \"))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val array = Array.ofDim[Boolean](2000002)\n array(0) = true\n array(1) = true\n (2 to 2000001).foreach { i =>\n if (!array(i)) {\n var j = 2 * i\n while (j <= 2000001) {\n array(j) = true\n j += i\n }\n }\n }\n println(array.indices.filter(i => !array(i)).take(n).mkString(\" \"))\n}\n"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val n = readString.toInt\n\n val LIMIT = 1300000\n val prime = Array.fill(LIMIT)(true)\n prime(0) = false\n \n Stream.from(2).takeWhile(i => i*i < LIMIT).filter(prime(_)).foreach { i =>\n (i*i until LIMIT by i).foreach(prime(_) = false)\n }\n val primes = prime.indices.filter(prime(_)).take(n + 1)\n\n println(primes.drop(1).mkString(\" \"))\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val array = Array.ofDim[Boolean](1000002)\n array(0) = true\n array(1) = true\n (2 to 1000001).foreach { i =>\n if (!array(i)) {\n var j = 2 * i\n while (j <= 1000001) {\n array(j) = true\n j += i\n }\n }\n }\n println(array.indices.filter(i => !array(i)).take(n).mkString(\" \"))\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P327B extends App {\n\n object PrimeNumber {\n def apply(n: Int = 1000000): Array[Int] = sieve(n)\n\n def sieve(n: Int): Array[Int] = {\n val primes = new ArrayBuffer[Int]\n val isPrime = Array.fill(n + 1)(true)\n\n @tailrec\n def loop(i: Int): Unit = {\n\n @tailrec\n def innerLoop(j: Int): Unit = {\n if (j > n) ()\n else {\n isPrime(j) = false\n innerLoop(j + i)\n }\n }\n\n if (i > n) ()\n else {\n if (isPrime(i)) {\n primes += i\n innerLoop(i * 2)\n }\n loop(i + 1)\n }\n }\n\n loop(2)\n primes.toArray\n }\n }\n\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n out.println(PrimeNumber(1000000).take(sc.nextInt).mkString(\" \"))\n out.close\n}\n\n\n\n\n\n"}, {"source_code": "import java.util.Scanner\nimport scala.math._\nimport scala.collection.mutable.ListBuffer\n\nobject R327_B extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n \n println(answer(n).mkString(\" \"))\n \n def answer(n:Int):Seq[Int] = {\n var list = new ListBuffer[Int]()\n var s = 10000000 - n\n list.append(s)\n while(s < 10000000){\n s += 1\n list.append(s) \n }\n //println(s)\n list\n }\n\n}"}, {"source_code": "import java.util.Scanner\nimport scala.math._\nimport scala.collection.mutable.ListBuffer\n\nobject R327_B extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n \n println(answer(n).mkString(\" \"))\n \n def answer(n:Int):Seq[Int] = {\n var list = new ListBuffer[Int]()\n var c = 10000000\n var s = 10000000 - n\n list.append(c)\n while(s < 10000000){\n s += 1\n list.append(s) \n }\n list\n }\n\n}"}, {"source_code": "import java.util.Scanner\nimport scala.math._\nimport scala.collection.mutable.ListBuffer\n\nobject R327_B extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n \n println(answer(n).mkString(\" \"))\n \n def answer(n:Int):Seq[Int] = {\n var list = new ListBuffer[Int]()\n var c = 10000000\n list.append(c)\n while(list.size < n){\n c -= 1\n //if(!list.exists(_ % c == 0)){\n list.append(n) \n //}else{\n // println(c)\n //}\n }\n list.reverse\n }\n\n}"}], "src_uid": "c047040426e736e9085395ed9666135f"} {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val target = \"abacaba\"\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val sn = readLine()\n\n def check(from: Int): Boolean = {\n val kn = sn.patch(from, target, target.length)\n kn.indexOfSlice(target) == kn.lastIndexOfSlice(target)\n }\n\n val ans = sn\n .sliding(7, 1)\n .zipWithIndex\n .collect {\n case (s, i) if s.corresponds(target) { case ('?', _) => true; case (x, y) => x == y } => i\n }\n .collectFirst {\n case from if check(from) => from\n }\n\n ans match {\n case None => println(\"NO\")\n case Some(i) =>\n val res = sn.patch(i, target, target.length).map { case '?' => 'd'; case c => c }\n println(\"YES\")\n println(res)\n }\n }\n}\n", "positive_code": [{"source_code": "object A {import InOut._\n def main(args: Array[String]): Unit = {\nval target = \"abacaba\"\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val s = nextLine\n\n\n\n val candidates = s.sliding(target.length).toArray\n val poss = candidates.indices.filter {\n p =>\n val c = candidates(p)\n var ok = true\n for (i <- 0 until target.length) {\n if (c(i) != '?' && c(i) != target(i)) {\n ok = false\n }\n }\n ok\n }\n\n var res = \"\"\n\n for (pos <- poss) {\n val c = candidates(pos)\n val s2 = s.take(pos) + target + s.drop(pos + target.length)\n val p1 = s2.indexOf(target)\n val p2 = s2.lastIndexOf(target)\n// println(pos, s2, p1, p2)\n if (p1 == p2) res = s2\n }\n\n if (res == \"\") {\n out.println(\"No\")\n } else {\n out.println(\"Yes\")\n out.println(res.replace('?', 'd'))\n }\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val target = \"abacaba\"\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val sn = readLine()\n\n def check(from: Int): Boolean = {\n val sm = sn.slice(from, from + 7)\n\n if (sm.corresponds(target) { case ('?', _) => true; case (x, y) => x == y }) {\n val kn = sn.patch(from, target, target.length)\n kn.indexOfSlice(target) == kn.lastIndexOfSlice(target)\n } else false\n }\n\n val ans = (0 until n).collectFirst { case i if check(i) => i }\n\n ans match {\n case None => println(\"NO\")\n case Some(i) =>\n val res = sn.patch(i, target, target.length).map { case '?' => 'd'; case c => c }\n println(\"YES\")\n println(res)\n }\n }\n}"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val target = \"abacaba\"\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val sn = readLine()\n\n def check(from: Int): Boolean = {\n val sm = sn.slice(from, from + 7)\n\n if (sm.corresponds(target) { case ('?', _) => true; case (x, y) => x == y }) {\n val kn = sn.patch(from, target, target.length)\n kn.indexOfSlice(target) == kn.lastIndexOfSlice(target)\n } else false\n }\n\n val ans = (0 until n).collectFirst { case i if check(i) => i }\n\n ans match {\n case None => println(\"NO\")\n case Some(i) =>\n val res = sn.patch(i, target, target.length).map { case '?' => 'd'; case c => c }\n println(\"YES\")\n println(res)\n }\n }\n}\n"}], "negative_code": [{"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val target = \"abacaba\"\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val sn = readLine()\n\n def check(from: Int): Boolean = {\n val sm = sn.slice(from, from + 7)\n\n if (sm.corresponds(target) { case ('?', _) => true; case (x, y) => x == y }) {\n val kn = sn.patch(from, target, target.length)\n kn.indexOfSlice(target, 0.max(from - 7)) == kn.lastIndexOfSlice(target, n.max(from + 7))\n } else false\n }\n\n val ans = (0 until n).collectFirst { case i if check(i) => i }\n\n ans match {\n case None => println(\"NO\")\n case Some(i) =>\n val res = sn.patch(i, target, target.length).map { case '?' => 'd'; case c => c }\n println(\"YES\")\n println(res)\n }\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val abc = \"abacaba\"\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val sn = readLine()\n\n val ls = sn\n .sliding(7, 1)\n .zipWithIndex\n .collect {\n case (s, i) if s.corresponds(abc) { case ('?', _) => true; case (x, y) => x == y } =>\n Some((s.indices.collect { case j if s(j) == '?' => i + j + 2 * abc(j) }.toList, i))\n }\n .toStream\n\n val l = ls match {\n case Stream() => None\n case _ =>\n ls.reduce[Option[(List[Int], Int)]] {\n case (None, Some(l)) => Some(l)\n case (Some((Nil, _)), Some((Nil, _))) => None\n case (Some((Nil, i)), _) => Some(Nil, i)\n case (_, Some((Nil, i))) => Some(Nil, i)\n case (Some((is, i)), Some((js, j))) =>\n if (is.length > js.length) Some((js, j))\n else if (js.length > is.length) Some((is, i))\n else if (is.containsSlice(js)) None\n else Some((is, i))\n }\n }\n\n // format: off\n val ans = l.map { case (_, i) => \n sn.zipWithIndex.map {\n case (_, j) if i <= j && j <= i + 6 => abc(j - i)\n case ('?', _) => 'd'\n case (c, _) => c\n }.mkString(\"\")\n }\n // format: on\n\n ans match {\n case None => println(\"NO\")\n case Some(value) => println(s\"YES\\n$value\")\n }\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val abc = \"abacaba\"\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val sn = readLine()\n\n val ans = sn\n .sliding(7, 1)\n .zipWithIndex\n .collect {\n case (s, i) if s.corresponds(abc) { case ('?', _) => true; case (x, y) => x == y } =>\n (s.indices.collect { case j if s(j) == '?' => i + j + abc(j) }.toList, i)\n } // format: off\n .reduceOption[(List[Int], Int)] {\n case ((_, -1), _) | (_, (_, -1)) => (Nil, -1)\n case ((Nil, _), (Nil, _)) => (Nil, -1)\n case ((Nil, l), _) => (Nil, l)\n case (_, (Nil, r)) => (Nil, r)\n case ((ls, l), (rs, r)) =>\n if (ls.containsSlice(rs)) {\n if (ls.length > rs.length) (rs, r)\n else if (ls.length < rs.length) (ls, l)\n else (Nil, -1)\n } else (ls, l)\n }\n .flatMap {\n case (_, -1) => None\n case (_, i) =>\n val res = sn.zipWithIndex.map {\n case (_, j) if i <= j && j <= i + 6 => abc(j - i)\n case ('?', _) => 'd'\n case (c, _) => c\n }.mkString(\"\")\n\n Some(res)\n } // format: on\n\n ans match {\n case None => println(\"NO\")\n case Some(value) => println(s\"YES\\n$value\")\n }\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val abc = \"abacaba\"\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val sn = readLine()\n\n val rs = sn\n .sliding(7, 1)\n .zipWithIndex\n .collect {\n case (s, i) if s.corresponds(abc) { case ('?', _) => true; case (x, y) => x == y } =>\n (s.indices.collect { case j if s(j) == '?' => i + j + abc(j) }.toList, i)\n }\n .toSeq\n\n val r = rs.foldLeft[Either[Option[String], (List[Int], Int)]](Left(Some(\"ok\"))) {\n case (x @ Left(None), _) => x\n case (Left(_), x) => Right(x)\n case (Right((Nil, _)), (Nil, _)) => Left(None)\n case (x @ Right((Nil, _)), _) => x\n case (_, x @ (Nil, _)) => Right(x)\n case (x @ Right((rs, r)), y @ (ls, l)) =>\n if (rs.length < ls.length) x\n else if (ls.length < rs.last) Right(y)\n else if (rs.containsSlice(ls)) Left(Some(\"ok\"))\n else x\n\n }\n\n val ans = r match {\n case Left(_) => None\n case Right((_, i)) =>\n val res = sn.zipWithIndex\n .map {\n case (_, j) if i <= j && j <= i + 6 => abc(j - i)\n case ('?', _) => 'd'\n case (c, _) => c\n }\n .mkString(\"\")\n\n Some(res)\n }\n\n ans match {\n case None => println(\"NO\")\n case Some(value) => println(s\"YES\\n$value\")\n }\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val abc = \"abacaba\"\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val sn = readLine()\n\n val ls = sn\n .sliding(7, 1)\n .zipWithIndex\n .collect {\n case (s, i) if s.corresponds(abc) { case ('?', _) => true; case (x, y) => x == y } =>\n Some((s.indices.collect { case j if s(j) == '?' => i + j + abc(j) }.toList, i))\n }\n .toStream\n\n val l = ls match {\n case Stream() => None\n case _ =>\n ls.reduce[Option[(List[Int], Int)]] {\n case (None, Some(l)) => Some(l)\n case (Some((Nil, _)), Some((Nil, _))) => None\n case (Some((Nil, i)), _) => Some(Nil, i)\n case (_, Some((Nil, i))) => Some(Nil, i)\n case (Some((is, _)), Some((js, j))) =>\n if (is.containsSlice(js) || js.containsSlice(is)) None else Some((js, j))\n }\n }\n\n val ans = l.map {\n case (_, i) =>\n sn.zipWithIndex\n .map {\n case (_, j) if i <= j && j <= i + 6 => abc(j - i)\n case ('?', _) => 'd'\n case (c, _) => c\n }\n .mkString(\"\")\n }\n\n ans match {\n case None => println(\"NO\")\n case Some(value) => println(s\"YES\\n$value\")\n }\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val abc = \"abacaba\"\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val sn = readLine()\n\n val ls = sn\n .sliding(7, 1)\n .zipWithIndex\n .collect {\n case (s, i) if s.corresponds(abc) { case ('?', _) => true; case (x, y) => x == y } =>\n Some((s.indices.collect { case j if s(j) == '?' => i + j + abc(j) }.toList, i))\n }\n .toSeq\n\n val status = ls match {\n case Stream() => None\n case _ =>\n ls.reduce[Option[(List[Int], Int)]] {\n case (None, Some(l)) => Some(l)\n case (Some((Nil, _)), Some((Nil, _))) => None\n case (Some((Nil, i)), _) => Some(Nil, i)\n case (_, Some((Nil, i))) => Some(Nil, i)\n case (Some((is, _)), Some((js, j))) => if (is.containsSlice(js)) None else Some((js, j))\n }\n }\n\n val ans = status.map {\n case (_, i) =>\n sn.zipWithIndex\n .map {\n case (_, j) if i <= j && j <= i + 6 => abc(j - i)\n case ('?', _) => 'd'\n case (c, _) => c\n }\n .mkString(\"\")\n }\n\n ans match {\n case None => println(\"NO\")\n case Some(value) => println(s\"YES\\n$value\")\n }\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val abc = \"abacaba\"\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val sn = readLine()\n\n val ls = sn\n .sliding(7, 1)\n .zipWithIndex\n .collect {\n case (s, i) if s.corresponds(abc) { case ('?', _) => true; case (x, y) => x == y } =>\n Some((s.indices.collect { case j if s(j) == '?' => i + j + abc(j) }.toList, i))\n }\n .toStream\n\n val l = ls match {\n case Stream() => None\n case _ =>\n ls.reduce[Option[(List[Int], Int)]] {\n case (None, Some(l)) => Some(l)\n case (Some((Nil, _)), Some((Nil, _))) => None\n case (Some((Nil, i)), _) => Some(Nil, i)\n case (_, Some((Nil, i))) => Some(Nil, i)\n case (Some((is, i)), Some((js, j))) =>\n if (is.length > js.length) Some((js, j))\n else if (js.length > is.length) Some((is, i))\n else if (is.containsSlice(js)) None\n else Some((is, i))\n }\n }\n\n val ans = l.map {\n case (_, i) =>\n sn.zipWithIndex\n .map {\n case (_, j) if i <= j && j <= i + 6 => abc(j - i)\n case ('?', _) => 'd'\n case (c, _) => c\n }\n .mkString(\"\")\n }\n\n ans match {\n case None => println(\"NO\")\n case Some(value) => println(s\"YES\\n$value\")\n }\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val abc = \"abacaba\"\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val sn = readLine()\n\n val ls = sn\n .sliding(7, 1)\n .zipWithIndex\n .collect {\n case (s, i) if s.corresponds(abc) { case ('?', _) => true; case (x, y) => x == y } =>\n Some((s.indices.collect { case j if s(j) == '?' => i + j + 2 * abc(j) }.toList, i))\n }\n .toStream\n\n val status = ls match {\n case Stream() => None\n case _ =>\n ls.reduce[Option[(List[Int], Int)]] {\n case (None, Some(l)) => Some(l)\n case (Some((Nil, _)), Some((Nil, _))) => None\n case (Some((Nil, i)), _) => Some(Nil, i)\n case (_, Some((Nil, i))) => Some(Nil, i)\n case (Some((is, _)), Some((js, j))) => if (is.containsSlice(js)) None else Some((js, j))\n }\n }\n\n val ans = status.map {\n case (_, i) =>\n sn.zipWithIndex\n .map {\n case (_, j) if i <= j && j <= i + 6 => abc(j - i)\n case ('?', _) => 'd'\n case (c, _) => c\n }\n .mkString(\"\")\n }\n\n ans match {\n case None => println(\"NO\")\n case Some(value) => println(s\"YES\\n$value\")\n }\n }\n}\n"}], "src_uid": "f6b7ad10382135b293bd3f2f3257d4d3"} {"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\nimport scala.util.Sorting\n\nobject Main {\n final val V = 1 << 20;\n final val B = 600\n def main(args: Array[String]) {\n val start = System.currentTimeMillis()\n val Array(n, m, k) = StdIn.readLine().split(\" \").map(_.toInt)\n val a = StdIn.readLine().split(\" \").map(_.toInt).scan(0)((x, y) => x ^ y)\n val qs = new Array[Query](m)\n for (i <- 0 until m) {\n val Array(l, r) = StdIn.readLine().split(\" \").map(_.toInt)\n qs(i) = Query(l - 1, r, i)\n }\n Sorting.quickSort(qs)(new Ordering[Query] {\n override def compare(x: Query, y: Query): Int = {\n if (x.l / B != y.l / B) (x.l / B) compare (y.l / B) else (x.r) compare (y.r)\n }\n })\n val ans = Array.fill(m)(0L)\n var p = 0\n var q = 0\n var s = 0L\n val ct = Array.fill(V)(0)\n ct(0) += 1\n for (Query(l, r, i) <- qs) {\n while (q < r) {\n q += 1\n s += ct(a(q) ^ k)\n ct(a(q)) += 1\n }\n while (p > l) {\n p -= 1\n s += ct(a(p) ^ k)\n ct(a(p)) += 1\n }\n while (q > r) {\n ct(a(q)) -= 1\n s -= ct(a(q) ^ k)\n q -= 1\n }\n while (p < l) {\n ct(a(p)) -= 1\n s -= ct(a(p) ^ k)\n p += 1\n }\n ans(i) = s\n }\n println(ans.mkString(\"\\n\"))\n }\n case class Query(val l: Int, val r: Int, val i: Int) {}\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\nimport scala.util.Sorting\n\nobject Main {\n final val V = 1 << 20;\n final val B = 600\n def main(args: Array[String]) {\n val start = System.currentTimeMillis()\n val Array(n, m, k) = StdIn.readLine().split(\" \").map(_.toInt)\n val a = StdIn.readLine().split(\" \").map(_.toInt).scan(0)((x, y) => x ^ y)\n val qs = new Array[Query](m)\n for (i <- 0 until m) {\n val Array(l, r) = StdIn.readLine().split(\" \").map(_.toInt)\n qs(i) = Query(l - 1, r, i)\n }\n Sorting.quickSort(qs)(new Ordering[Query] {\n override def compare(x: Query, y: Query): Int = {\n if (x.l / B != y.l / B) (x.l / B) compare (y.l / B) else (x.r) compare (y.r)\n }\n })\n val ans = Array.fill(m)(0L)\n var p = 0\n var q = 0\n var s = 0L\n val ct = Array.fill(V)(0)\n ct(0) += 1\n for (Query(l, r, i) <- qs) {\n while (q < r) {\n q += 1\n ct(a(q)) += 1\n s += ct(a(q) ^ k)\n }\n while (p > l) {\n p -= 1\n ct(a(p)) += 1\n s += ct(a(p) ^ k)\n }\n while (q > r) {\n s -= ct(a(q) ^ k)\n ct(a(q)) -= 1\n q -= 1\n }\n while (p < l) {\n s -= ct(a(p) ^ k)\n ct(a(p)) -= 1\n p += 1\n }\n ans(i) = s - (if (k == 0) (r - l) else 0)\n }\n println(ans.mkString(\"\\n\"))\n }\n case class Query(val l: Int, val r: Int, val i: Int) {}\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\nimport scala.util.Sorting\n\nobject Main {\n final val V = 1 << 20;\n final val B = 300\n def main(args: Array[String]) {\n val Array(n, m, k) = StdIn.readLine().split(\" \").map(_.toInt)\n val a = StdIn.readLine().split(\" \").map(_.toInt)\n val qs = new Array[Query](m)\n for (i <- 0 until m) {\n val Array(l, r) = StdIn.readLine().split(\" \").map(_.toInt - 1)\n qs(i) = Query(l, r, i)\n }\n Sorting.quickSort(qs)(new Ordering[Query] {\n override def compare(x: Query, y: Query): Int = {\n if (x.l / B != y.l / B) (x.l / B) compare (y.l / B) else (x.r) compare (y.r)\n }\n })\n val ans = Array.fill(m)(0L)\n var p = 0\n var q = -1\n var ls, rs = 0\n var s = 0L\n val ct = mutable.HashMap[Int, Long]().withDefault(_ => 0)\n ct(0) = 1\n for (Query(l, r, i) <- qs) {\n while (q < r) {\n q += 1\n rs ^= a(q)\n ct(rs) += 1\n s += ct(rs ^ k)\n }\n while (p > l) {\n p -= 1\n ls ^= a(p)\n ct(ls) += 1\n s += ct(ls ^ k)\n }\n while (q > r) {\n s -= ct(rs ^ k)\n ct(rs) -= 1\n rs ^= a(q)\n q -= 1\n }\n while (p < l) {\n s -= ct(ls ^ k)\n ct(ls) -= 1\n ls ^= a(p)\n p += 1\n }\n ans(i) = s\n println(i, s)\n }\n println(ans.mkString(\"\\n\"))\n }\n case class Query(val l: Int, val r: Int, val i: Int) {}\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\nimport scala.util.Sorting\n\nobject Main {\n final val V = 1 << 20;\n final val B = 300\n def main(args: Array[String]) {\n val Array(n, m, k) = StdIn.readLine().split(\" \").map(_.toInt)\n val a = StdIn.readLine().split(\" \").map(_.toInt).scan(0)((x, y) => x ^ y)\n val qs = new Array[Query](m)\n for (i <- 0 until m) {\n val Array(l, r) = StdIn.readLine().split(\" \").map(_.toInt)\n qs(i) = Query(l - 1, r, i)\n }\n Sorting.quickSort(qs)(new Ordering[Query] {\n override def compare(x: Query, y: Query): Int = {\n if (x.l / B != y.l / B) (x.l / B) compare (y.l / B) else (x.r) compare (y.r)\n }\n })\n val ans = Array.fill(m)(0L)\n var p = 0\n var q = 0\n var s = 0L\n val ct = mutable.HashMap[Int, Long]().withDefault(_ => 0)\n for (Query(l, r, i) <- qs) {\n while (q < r) {\n q += 1\n ct(a(q)) += 1\n s += ct(a(q) ^ k)\n }\n while (p > l) {\n p -= 1\n ct(a(p)) += 1\n s += ct(a(p) ^ k)\n }\n while (q > r) {\n s -= ct(a(q) ^ k)\n ct(a(q)) -= 1\n q -= 1\n }\n while (p < l) {\n s -= ct(a(p) ^ k)\n ct(a(p)) -= 1\n p += 1\n }\n ans(i) = s\n }\n println(ans.mkString(\"\\n\"))\n }\n case class Query(val l: Int, val r: Int, val i: Int) {}\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\nimport scala.util.Sorting\n\nobject Main {\n final val V = 1 << 20;\n final val B = 300\n def main(args: Array[String]) {\n val Array(n, m, k) = StdIn.readLine().split(\" \").map(_.toInt)\n val a = StdIn.readLine().split(\" \").map(_.toInt)\n val qs = new Array[Query](m)\n for (i <- 0 until m) {\n val Array(l, r) = StdIn.readLine().split(\" \").map(_.toInt - 1)\n qs(i) = Query(l, r, i)\n }\n Sorting.quickSort(qs)(new Ordering[Query] {\n override def compare(x: Query, y: Query): Int = {\n if (x.l / B != y.l / B) (x.l / B) compare (y.l / B) else (x.r) compare (y.r)\n }\n })\n val ans = Array.fill(m)(0L)\n var p = 0\n var q = -1\n var ls, rs = 0\n var s = 0L\n val ct = mutable.HashMap[Int, Long]().withDefault(_ => 0)\n ct(0) = 1\n for (Query(l, r, i) <- qs) {\n while (q < r) {\n q += 1\n rs ^= a(q)\n ct(rs) += 1\n s += ct(rs ^ k)\n }\n while (p > l) {\n p -= 1\n ls ^= a(p)\n ct(ls) += 1\n s += ct(ls ^ k)\n }\n while (q > r) {\n s -= ct(rs ^ k)\n ct(rs) -= 1\n rs ^= a(q)\n q -= 1\n }\n while (p < l) {\n s -= ct(ls ^ k)\n ct(ls) -= 1\n ls ^= a(p)\n p += 1\n }\n ans(i) = s\n }\n println(ans.mkString(\"\\n\"))\n }\n case class Query(val l: Int, val r: Int, val i: Int) {}\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\nimport scala.util.Sorting\n\nobject Main {\n final val V = 1 << 20;\n final val B = 300\n def main(args: Array[String]) {\n val Array(n, m, k) = StdIn.readLine().split(\" \").map(_.toInt)\n val a = StdIn.readLine().split(\" \").map(_.toInt).scan(0)((x, y) => x ^ y)\n val qs = new Array[Query](m)\n for (i <- 0 until m) {\n val Array(l, r) = StdIn.readLine().split(\" \").map(_.toInt)\n qs(i) = Query(l - 1, r, i)\n }\n Sorting.quickSort(qs)(new Ordering[Query] {\n override def compare(x: Query, y: Query): Int = {\n if (x.l / B != y.l / B) (x.l / B) compare (y.l / B) else (x.r) compare (y.r)\n }\n })\n val ans = Array.fill(m)(0L)\n var p = 0\n var q = 0\n var s = 0L\n val ct = mutable.HashMap[Int, Long]().withDefault(_ => 0)\n ct(0) = 1\n for (Query(l, r, i) <- qs) {\n while (q < r) {\n q += 1\n ct(a(q)) += 1\n s += ct(a(q) ^ k)\n }\n while (p > l) {\n p -= 1\n ct(a(p)) += 1\n s += ct(a(p) ^ k)\n }\n while (q > r) {\n s -= ct(a(q) ^ k)\n ct(a(q)) -= 1\n q -= 1\n }\n while (p < l) {\n s -= ct(a(p) ^ k)\n ct(a(p)) -= 1\n p += 1\n }\n ans(i) = s\n }\n println(ans.mkString(\"\\n\"))\n }\n case class Query(val l: Int, val r: Int, val i: Int) {}\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n final val V = 1 << 20;\n def main(args: Array[String]) {\n val Array(n, m, k) = StdIn.readLine().split(\" \").map(_.toInt)\n val a = StdIn.readLine().split(\" \").map(_.toInt)\n val qs = Array.fill(m)((0, 0))\n for (i <- 0 until m) {\n val Array(l, r) = StdIn.readLine().split(\" \").map(_.toInt - 1)\n qs(i) = (l, r)\n }\n val ctl, ctr = Array.fill(n)(0L)\n val tbl = Array.fill(V)(0L)\n val sum = Array.fill(n)(0)\n tbl(0) = 1\n var s = 0L\n var t = 0\n for (i <- 0 until n) {\n t ^= a(i)\n sum(i) = t\n ctr(i) = tbl(t ^ k)\n s += tbl(t ^ k)\n tbl(t) += 1\n }\n for (i <- 0 until V) tbl(i) = 0\n t = 0\n tbl(0) = 1\n for (i <- n - 1 to 0 by -1) {\n t ^= a(i)\n ctl(i) = tbl(t ^ k)\n tbl(t) += 1\n }\n for (i <- 1 until n) {\n ctl(i) += ctl(i - 1)\n }\n for (i <- n - 2 to 0 by -1) {\n ctr(i) += ctr(i + 1)\n }\n val ans = Array.fill(m)(0L)\n for (((l, r), i) <- qs.zipWithIndex) {\n ans(i) = s\n if (l > 0) ans(i) -= ctl(l - 1)\n if (r < n - 1) ans(i) -= ctr(r + 1)\n if (l > 0) ans(i) += (if ((sum(r) ^ sum(l - 1)) == k) 1L else 0L)\n }\n println(ans.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\nimport scala.util.Sorting\n\nobject Main {\n final val V = 1 << 20;\n final val B = 300\n def main(args: Array[String]) {\n val Array(n, m, k) = StdIn.readLine().split(\" \").map(_.toInt)\n val a = StdIn.readLine().split(\" \").map(_.toInt)\n val qs = new Array[Query](m)\n for (i <- 0 until m) {\n val Array(l, r) = StdIn.readLine().split(\" \").map(_.toInt - 1)\n qs(i) = Query(l, r, i)\n }\n Sorting.quickSort(qs)(new Ordering[Query] {\n override def compare(x: Query, y: Query): Int = {\n if (x.l / B != y.l / B) (x.l / B) compare (y.l / B) else (x.r) compare (y.r)\n }\n })\n val ans = Array.fill(m)(0L)\n var p = 0\n var q = -1\n var ls, rs = 0\n var s = 0L\n val ct = mutable.HashMap[Int, Long]().withDefault(_ => 0)\n ct(0) = 1\n for (Query(l, r, i) <- qs) {\n while (q < r) {\n q += 1\n rs ^= a(q)\n ct(rs) += 1\n s += ct(rs ^ k)\n }\n while (p > l) {\n ls ^= a(p)\n p -= 1\n ct(ls) += 1\n s += ct(ls ^ k)\n }\n while (q > r) {\n s -= ct(rs ^ k)\n ct(rs) -= 1\n rs ^= a(q)\n q -= 1\n }\n while (p < l) {\n s -= ct(ls ^ k)\n ct(ls) -= 1\n p += 1\n ls ^= a(p)\n }\n ans(i) = s\n }\n println(ans.mkString(\"\\n\"))\n }\n case class Query(val l: Int, val r: Int, val i: Int) {}\n}\n"}], "src_uid": "feec32948519ff16f767a823e634eccb"} {"source_code": "object CF_527_3_C {\n def solve(n: Int, ss: Seq[String]): String = {\n val pairs: Map[Int, Seq[(String, Int)]] = ss.zipWithIndex.groupBy(_._1.length)\n // Strategy: Look at longest two to give 2 possible strings\n val possibles: Seq[String] = pairs(n - 1) match {\n case Seq((a, _), (b, _)) => Seq(a + b.last, b + a.last)\n }\n\n //\n def isPrefix(pre: String, s: String) = s.take(pre.length) == pre\n\n def isSuffix(suff: String, s: String) = s.takeRight(suff.length) == suff\n\n // Seqs of values starting from longest\n val strs: Seq[Seq[(String, Int)]] = pairs.values.toSeq\n\n def isValid(test: String, ps: Seq[Seq[(String, Int)]], out: Seq[(String, Int)]): Option[Seq[(String, Int)]] = ps match {\n case Seq() => Some(out)\n case Seq((n1, i), (n2, j)) +: tail =>\n if (isPrefix(n1, test) && isSuffix(n2, test)) isValid(test, tail, out :+ (\"P\", i) :+ (\"S\", j))\n else if (isPrefix(n2, test) && isSuffix(n1, test))\n isValid(test, tail, out :+ (\"S\", i) :+ (\"P\", j))\n else None\n }\n\n val result: String = possibles.map(p => isValid(p, strs, Nil)).find(_.isDefined).get.get.sortBy(_._2).map(_._1).mkString\n\n result\n }\n\n// ~~~ Specify Input and Output formats here:\n\n def formatIn(i: Input) = (i.int, {i.nextLine; i.getLines})\n def formatOut(out: String): String = out.toString\n\n// ~~~ Boilerplate & utility methods that don't change: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n def main(args: Array[String]) = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n\n import java.util.Scanner\n class Input(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n // Remember to call nextLine to advance past the newline character (if required) before collecting the line:\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty else sc.nextLine +: getLines\n def solveVal = (solve _).tupled(formatIn(this))\n def solveStr = formatOut(solveVal)\n }\n\n def ceil(a: Int, b: Int) = (a - 1) / b + 1\n def ceil(a: Long, b: Long) = (a - 1) / b + 1\n val modulo = 1000000007\n\n import language.implicitConversions\n implicit def stringToInput(s: String): Input = new Input(s)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { def tupled: T => R = x => f(x) }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val S = map(2 * N - 2) { _ => ns() }\n\n val grouped = S.zipWithIndex.groupBy(_._1.length)\n val ans = Array.ofDim[Char](S.length)\n def make(len: Int, prefix: String, suffix: String): Boolean = {\n if (len == 0) true\n else {\n val Array((s1, i1), (s2, i2)) = grouped(len)\n\n if (prefix.startsWith(s1) && suffix.endsWith(s2)) {\n ans(i1) = 'P'\n ans(i2) = 'S'\n make(len - 1, prefix, suffix)\n\n } else if (prefix.startsWith(s2) && suffix.endsWith(s1)) {\n ans(i1) = 'S'\n ans(i2) = 'P'\n make(len - 1, prefix, suffix)\n\n } else {\n // この割り振りは間違っていた\n false\n }\n }\n }\n\n val s1 = grouped(N - 1)(0)._1\n val s2 = grouped(N - 1)(1)._1\n if (make(N - 1, s1, s2)) {\n out.println(ans.mkString)\n } else {\n make(N - 1, s2, s1)\n out.println(ans.mkString)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val S = map(2 * N - 2) { _ => ns() }\n val sorted = S.sorted\n\n def mkPrefix(S1: Array[String]) = {\n var ok = true\n var ix = 0\n REP(S1.length - 1) { i =>\n ok &&= S1(i + 1).startsWith(S1(i))\n if (ok) ix = i\n }\n S1(ix + 1)\n }\n\n val prefix = mkPrefix(Array(\"\") ++ sorted)\n// val suffix = mkPrefix(Array(\"\") ++ sorted.reverse)\n\n val cnt = Array.ofDim[Int](N)\n\n val ans = map(S.length) { i =>\n if (prefix.startsWith(S(i))) {\n cnt(S(i).length) += 1\n if (cnt(S(i).length) == 1) 'P'\n else 'S'\n } else 'S'\n }.mkString\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val S = map(2 * N - 2) { _ => ns() }\n val S1 = \"\" +: S\n Sorting.quickSort(S1)\n\n var ok = true\n var ix = 0\n REP(S1.length - 1) { i =>\n ok &&= S1(i + 1).startsWith(S1(i))\n if (ok) ix = i\n }\n val prefix = S1(ix + 1)\n val ans = map(S.length) { i =>\n if (prefix.startsWith(S(i))) 'P'\n else 'S'\n }.mkString\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val S = map(2 * N - 2) { _ => ns() }\n\n val grouped = S.zipWithIndex.groupBy(_._1.length)\n\n val prefix = grouped(N - 1)(0)._1\n val suffix = grouped(N - 1)(1)._1\n\n val ans = Array.ofDim[Char](S.length)\n grouped.foreach { case (_, as) =>\n val Array((s1, i1), (s2, i2)) = as\n if (prefix.startsWith(s1) && suffix.startsWith(s2)) {\n ans(i1) = 'P'\n ans(i2) = 'S'\n } else {\n ans(i2) = 'P'\n ans(i1) = 'S'\n }\n }\n\n out.println(ans.mkString)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val S = map(2 * N - 2) { _ => ns() }\n val sorted = S.sorted\n\n def mkPrefix(S1: Array[String]) = {\n var ok = true\n var ix = 0\n REP(S1.length - 1) { i =>\n ok &&= S1(i + 1).startsWith(S1(i))\n if (ok) ix = i\n }\n S1(ix + 1)\n }\n\n val prefix = mkPrefix(Array(\"\") ++ sorted)\n val suffix = mkPrefix(Array(\"\") ++ sorted.reverse)\n\n val grouped = S.zipWithIndex.groupBy(_._1.length)\n val ans = Array.ofDim[Char](S.length)\n grouped.foreach { case (_, as) =>\n val Array((s1, i1), (s2, i2)) = as\n if (prefix.startsWith(s1) && suffix.startsWith(s2)) {\n ans(i1) = 'P'\n ans(i2) = 'S'\n } else {\n ans(i2) = 'P'\n ans(i1) = 'S'\n }\n }\n\n out.println(ans.mkString)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "ddbde202d00b928a858e9f4ff461e88c"} {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Hotelier extends App {\n\n StdIn.readLine()\n\n val n = 10\n val events = StdIn.readLine()\n\n val rooms = mutable.Buffer[Int]()\n rooms ++= Seq.fill(n)(0)\n\n events.foreach {\n case 'R' => rooms.update(rooms.lastIndexOf(0), 1)\n case 'L' => rooms.update(rooms.indexOf(0), 1)\n case num => rooms(Integer.parseInt(num.toString)) = 0\n }\n\n println(rooms.mkString(\"\"))\n}\n", "positive_code": [{"source_code": "object A {\n \ndef main(args: Array[String]): Unit = {}\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n \n val Array(n) = readInts(1)\n val s = readLine\n val rooms = Array.fill(10)(0)\n \n for (c <- s) {\n c match {\n case 'L' =>\n var i = 0\n while (rooms(i) == 1) i += 1\n rooms(i) = 1\n case 'R' =>\n var i = 9\n while (rooms(i) == 1) i -= 1\n rooms(i) = 1\n case _ =>\n rooms(c - '0') = 0\n }\n }\n \n println(rooms.mkString)\n \n Console.flush\n}"}, {"source_code": "import java.io.BufferedReader\n\nobject Main {\n\n type RoomStatus = Boolean\n type Rooms = java.util.BitSet\n\n val FREE = false\n val OCCUPIED = true\n val MAX = 10\n\n def roomsToString(rooms: Rooms): String = {\n (for (i <- Range(0, MAX)) yield {\n if (rooms.get(i) == FREE) '0' else '1'\n }).mkString\n }\n\n\n def result(input: Stream[Char]): Rooms = {\n val rooms: Rooms = new Rooms(MAX)\n\n input.foreach {\n\n case 'L' =>\n val freeIndex = rooms.nextClearBit(0)\n rooms.set(freeIndex, OCCUPIED)\n rooms\n case 'R' =>\n val freeIndex = rooms.previousClearBit(MAX - 1)\n rooms.set(freeIndex, OCCUPIED)\n rooms\n case room =>\n rooms.set(room - '0', FREE)\n rooms\n\n }\n\n rooms\n }\n\n def main(args: Array[String]) = {\n val input: BufferedReader = Console.in\n val length = input.readLine().toInt\n if (length != 0) {\n var read = 0\n val buf = new Array[Char](1)\n val ops = Stream\n .continually {\n read += 1\n input.read(buf)\n }\n .takeWhile(bufRead => bufRead > 0 && read <= length)\n .map {\n _ => buf(0)\n }\n\n Console.out.write(roomsToString(result(ops)).getBytes)\n }\n\n }\n}\n"}, {"source_code": "import java.io.BufferedReader\n\nobject Main2 {\n\n sealed trait Input\n\n case object L extends Input\n\n case object R extends Input\n\n case class Leave(roomNo: Byte) extends Input\n\n type RoomStatus = Boolean\n type Rooms = Vector[RoomStatus]\n\n val FREE = false\n val OCCUPIED = true\n val ALL_EMPTY: Rooms = Vector.fill(10)(FREE)\n\n\n def handle(rooms: Rooms, input: Input): Rooms = input match {\n case L =>\n val freeIndex = rooms.indexOf(FREE)\n rooms.updated(freeIndex, OCCUPIED)\n case R =>\n val freeIndex = rooms.lastIndexOf(FREE)\n rooms.updated(freeIndex, OCCUPIED)\n case Leave(roomNo) =>\n rooms.updated(roomNo, FREE)\n }\n\n def roomsToString(rooms: Rooms): String = {\n rooms.map {\n case FREE => '0'\n case OCCUPIED => '1'\n }.mkString\n }\n\n\n def result(input: Stream[Char]): Rooms = {\n input.map {\n case 'L' => L\n case 'R' => R\n case c if c >= '0' && c <= '9' => Leave(Seq(c).mkString.toByte)\n }.foldLeft(ALL_EMPTY)(handle)\n }\n\n\n def main(args: Array[String]) = {\n val input: BufferedReader = Console.in\n val length = input.readLine().toInt\n if (length != 0) {\n var read = 0\n val buf = new Array[Char](1)\n val ops = Stream\n .continually {\n read += 1\n input.read(buf)\n }\n .takeWhile(bufRead => bufRead > 0 && read <= length)\n .map {\n _ => buf(0)\n }\n\n Console.out.write(roomsToString(result(ops)).getBytes)\n }\n\n }\n}\n"}, {"source_code": "/**\n * Created by lilisun on 8/12/19.\n */\nimport scala.io.StdIn.readLine\nobject cf578 {\n\n def PA():Unit = {\n val n = readLine().toInt\n val line = readLine()\n val room = Array.fill(10)(0)\n line foreach {\n case 'L' => (0 until 10).dropWhile(i => room(i) == 1).headOption match {\n case None => {}\n case Some(i) => room(i) = 1\n }\n case 'R' => (0 until 10).reverse.dropWhile(i => room(i) == 1).headOption match {\n case None => {}\n case Some(i) => room(i) = 1\n }\n case ch => room(ch - '0') = 0\n }\n println(room.toList.mkString)\n }\n def main(args: Array[String]): Unit = {\n PA()\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A_1200 extends App {\n val n = readInt()\n val A = readLine()\n var S = Array.ofDim[Boolean](10)\n\n A.foreach { x =>\n if (x == 'L') {\n var left = 0\n while (S(left)) left += 1\n S(left) = true\n left += 1\n } else if (x == 'R') {\n var right = 9\n while (S(right)) right -= 1\n S(right) = true\n right -= 1\n } else {\n val xx = (\"\" + x).toInt\n S(xx) = false\n }\n }\n\n println(\n S.map(x => if (x) 1 else 0).mkString\n )\n}\n"}, {"source_code": "object A {\n \ndef main(args: Array[String]): Unit = {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n \n val Array(n) = readInts(1)\n val s = readLine\n val rooms = Array.fill(10)(0)\n \n for (c <- s) {\n c match {\n case 'L' =>\n var i = 0\n while (rooms(i) == 1) i += 1\n rooms(i) = 1\n case 'R' =>\n var i = 9\n while (rooms(i) == 1) i -= 1\n rooms(i) = 1\n case _ =>\n rooms(c - '0') = 0\n }\n }\n \n println(rooms.mkString)\n \n Console.flush\n}\n}"}, {"source_code": "object A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n \n val Array(n) = readInts(1)\n val s = readLine\n val rooms = Array.fill(10)(0)\n \n for (c <- s) {\n c match {\n case 'L' =>\n var i = 0\n while (rooms(i) == 1) i += 1\n rooms(i) = 1\n case 'R' =>\n var i = 9\n while (rooms(i) == 1) i -= 1\n rooms(i) = 1\n case _ =>\n rooms(c - '0') = 0\n }\n }\n \n println(rooms.mkString)\n \n Console.flush\n}"}, {"source_code": "import scala.collection.convert.ImplicitConversionsToScala._\n\nobject AMega extends App {\n\n val MaxRoom = 9\n val n = readLine.toInt\n val rooms = new java.util.TreeMap[Integer, Integer]\n if (MaxRoom == 999999) rooms.put(0, MaxRoom)\n\n val readCommand: Unit => String = if (MaxRoom == 9) { val l = readLine.sliding(1); _ => l.next } else { _ => readLine }\n\n for (_ <- 1 to n) {\n readCommand() match {\n case \"L\" =>\n val goTo = rooms.getOrDefault(0, -1) + 1\n val nextKey = goTo + 1\n val right: Integer = if (rooms.containsKey(nextKey)) rooms.remove(nextKey) else goTo\n rooms.put(0, right)\n case \"R\" =>\n if (rooms.isEmpty) rooms.put(MaxRoom, MaxRoom)\n else {\n val lastKey = rooms.lastKey\n val goTo = if (rooms.get(lastKey) == MaxRoom) {\n rooms.remove(lastKey)\n lastKey - 1\n } else MaxRoom\n val prevKey = rooms.floorKey(goTo)\n val left: Integer = if (prevKey != null && rooms.get(prevKey) == goTo - 1) prevKey else goTo\n rooms.put(left, MaxRoom)\n }\n case s =>\n val pos = s.toInt\n val left = rooms.floorKey(pos)\n val right = rooms.remove(left)\n if (left < pos) rooms.put(left, pos - 1)\n if (right > pos) rooms.put(pos + 1, right)\n }\n }\n\n val result = Array.fill[Byte](MaxRoom + 1)(0)\n\n for (entry <- rooms.entrySet()) {\n for (i <- entry.getKey.toInt to entry.getValue) result(i) = 1\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(result.mkString)\n Console.flush\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val s = readLine\n val rooms = Array.fill(10)(0)\n\n for (c <- s) {\n c match {\n case 'L' =>\n var i = 0\n while (rooms(i) == 1) i += 1\n rooms(i) = 1\n case 'R' =>\n var i = 9\n while (rooms(i) == 1) i -= 1\n rooms(i) = 1\n case _ =>\n rooms(c - '0') = 0\n }\n }\n\n println(rooms.mkString)\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "a6cbf01d72d607ca95fe16df4fb16693"} {"source_code": "import scala.io.StdIn.readLine\nobject CF extends App{\nval t = readLine().toArray\nval p = readLine().toArray\nval a = readLine().split(\" \").map(_.toInt - 1)\n\nval rank = Array.fill(a.length)(0)\nfor( i <- 0 until a.length)\n rank(a(i)) = i\n\nval newt: Array[Char] = Array.fill(t.length)(0)\n\ndef getNewt(n: Int) = {\n for(i <- 0 until t.length){\n if(rank(i) > n) newt(i) = t(i)\n else newt(i) = 0\n }\n}\n\ndef isComposable(): Boolean = {\n var j = 0\n for(i <- 0 until newt.length){\n if(newt.length - i < p.length - j) return false\n if(newt(i) == p(j)) j+=1\n if(j==p.length) return true\n }\n return false\n}\n\nvar lo = 0\nvar hi = t.length - p.length + 1\nvar mid = (hi+lo) / 2\n\nwhile(lo < hi){\n getNewt(mid)\n //println(f\"$hi $lo $mid \" + newt.mkString(\"\"))\n if(isComposable()) lo = mid+1\n else hi = mid\n mid = (hi+lo) / 2\n}\n\nprintln(hi)\n}", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\nobject CF extends App{\nval t = readLine().toArray\nval p = readLine().toArray\nval a = readLine().split(\" \").map(_.toInt - 1)\n\nval rank = Array.fill(a.length)(0)\nfor( i <- 0 until a.length)\n rank(a(i)) = i\n\ndef isComposable(n: Int): Boolean = {\n var j = 0\n for(i <- 0 until t.length){\n if(rank(i) > n) {\n if(t.length - i < p.length - j) return false\n if(t(i) == p(j)) j+=1\n if(j==p.length) return true\n }\n }\n return false\n}\n\nvar lo = 0\nvar hi = t.length - p.length + 1\nvar mid = (hi+lo) / 2\n\nwhile(lo < hi){\n //println(f\"$hi $lo $mid \" + newt.mkString(\"\"))\n if(isComposable(mid)) lo = mid+1\n else hi = mid\n mid = (hi+lo) / 2\n}\n\nprintln(hi)\n}"}, {"source_code": "//package solutions\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * @author traff\n */\n\n\nobject SolTaskD extends App {\n override def main(args: Array[String]): Unit = {\n val out = new PrintWriter(System.out)\n\n run(new Scanner(System.in), out)\n\n out.close()\n }\n\n def filter(s: String, a: Array[Int], n: Int): String = {\n var ss = new StringBuffer(s)\n for (i <- 0 until n) {\n ss.setCharAt(a(i)-1, 0)\n }\n\n ss.toString.filter(_ != 0)\n }\n\n def check(s1: String, s2: String): Boolean = {\n var i1 = 0\n var i2 = 0\n\n while (i1 < s1.length && i2 < s2.length) {\n if (s1(i1) == s2(i2)) {\n i1 += 1\n i2 += 1\n } else {\n i1 += 1\n }\n }\n\n\n i2 == s2.length\n }\n\n def find(l: Int, r: Int, s1: String, s2: String, a: Array[Int]): Int = {\n if (l >= r) {\n l\n } else if (check(filter(s1, a, r), s2)) {\n r\n }\n else {\n\n var mid = l + (r - l) / 2\n if (mid == l) {\n mid = l + 1\n }\n\n if (check(filter(s1, a, mid), s2)) {\n find(mid, r, s1, s2, a)\n } else {\n find(l, mid - 1, s1, s2, a)\n }\n }\n }\n\n def run(s: Scanner, out: PrintWriter): Unit = {\n val p = s.nextLine()\n val t = s.nextLine()\n\n val a = s.nextLine().split(\" \").map(_.toInt)\n\n out.println(find(0, a.length, p, t, a))\n }\n\n}\n"}, {"source_code": "object CF extends App{\nimport scala.io.StdIn.readLine\nval t = readLine().toArray\nval p = readLine().toArray\nval a = readLine().split(\" \").map(_.toInt - 1)\n\nval rank = {\n val rank = Array.fill(a.length)(0)\n for( i <- 0 until a.length)\n rank(a(i)) = i\n rank\n}\n\nval newt: Array[Char] = Array.fill(t.length)(0)\n\ndef getNewt(n: Int) = {\n for(i <- 0 until t.length){\n if(rank(i) > n) newt(i) = t(i)\n else newt(i) = 0\n }\n}\n\ndef isComposable(): Boolean = {\n var j = 0\n for(i <- 0 until newt.length){\n if(newt.length - i < p.length - j) return false\n if(newt(i) == p(j)) j+=1\n if(j==p.length) return true\n }\n return false\n}\n\nvar lo = 0\nvar hi = t.length - p.length + 1\nvar mid = (hi+lo) / 2\n\nwhile(lo < hi){\n getNewt(mid)\n //println(f\"$hi $lo $mid \" + newt.mkString(\"\"))\n if(isComposable()) lo = mid+1\n else hi = mid\n mid = (hi+lo) / 2\n}\n\nprintln(hi)\n}"}, {"source_code": "object CF extends App{\nimport scala.io.StdIn.readLine\nval t = readLine().toArray\nval p = readLine().toArray\nval a = readLine().split(\" \").map(_.toInt - 1)\n\nval rank = {\n val rank = Array.fill(a.length)(0)\n for( i <- 0 until a.length)\n rank(a(i)) = i\n rank\n}\n\nval newt: Array[Char] = Array.fill(t.length)(0)\n\ndef getNewt(n: Int) = {\n for(i <- 0 until t.length){\n if(rank(i) > n) newt(i) = t(i)\n else newt(i) = 0\n }\n}\n\ndef isComposable(i:Int, j: Int): Boolean = {\n if(i >= t.length) return false\n if(j >= p.length) return true\n if(newt.length - i < p.length - j) return false\n if(newt(i) == p(j) && j==p.length-1) return true\n if(newt(i) == p(j)) return isComposable(i+1, j+1)\n else return isComposable(i+1, j)\n}\n\nvar lo = 0\nvar hi = t.length - p.length + 1\nvar mid = (hi+lo) / 2\nvar end = false\n\nwhile(lo < hi){\n getNewt(mid)\n //println(f\"$hi $lo $mid \" + newt.mkString(\"\"))\n if(isComposable(0, 0)) lo = mid+1\n else hi = mid\n mid = (hi+lo) / 2\n}\n\nprintln(hi)\n}"}], "negative_code": [{"source_code": "object CF extends App{\nimport scala.io.StdIn.readLine\nval t = readLine().toArray\nval p = readLine().toArray\nval a = readLine().split(\" \").map(_.toInt - 1)\n\nval rank = {\n val rank = Array.fill(a.length)(0)\n for( i <- 0 until a.length)\n rank(a(i)) = i\n rank\n}\n\nval newt: Array[Char] = Array.fill(t.length)(0)\n\ndef getNewt(n: Int) = {\n for(i <- 0 until t.length){\n if(rank(i) > n) newt(i) = t(i)\n else newt(i) = 0\n }\n}\n\ndef isComposable(i:Int, j: Int): Boolean = {\n if(i >= t.length) return false\n if(j >= p.length) return true\n if(newt.length - i < p.length - j) return false\n if(newt(i) == p(j) && j==p.length-1) return true\n if(newt(i) == p(j)) return isComposable(i+1, j+1)\n else return isComposable(i+1, j)\n}\n\nvar lo = 0\nvar hi = t.length - p.length + 1\nvar mid = (hi+lo+1) / 2\nvar end = false\n\nwhile(lo < hi){\n getNewt(mid)\n //println(f\"$hi $lo $mid \" + newt.mkString(\"\"))\n if(isComposable(0, 0)) lo = mid\n else hi = mid-1\n mid = (hi+lo+1) / 2\n}\n\nprintln(mid+1)\n}"}], "src_uid": "0aed14262c135d1624df9814078031ae"} {"source_code": "import math._\n\nobject Main extends App{\n val s = readLine()\n var maxVal, minVal, curVal = 0\n for (c <- s){\n if (c == '+')\n curVal += 1\n else\n curVal -= 1\n maxVal = max(maxVal, curVal)\n minVal = min(minVal, curVal)\n }\n println(maxVal - minVal)\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject MishapInClub {\n //+ in, - out\n def minNum(l:String):Int={\n var in = 0\n var out = 0\n var minNeeded = 0\n for (a<-0 to l.length()-1){\n if (l(a)=='+'){\n in = in + 1\n if (out==0){\n minNeeded = minNeeded + 1\n }else{\n out = out -1\n }\n }else if (l(a)=='-'){\n out = out + 1\n if (in==0){\n minNeeded = minNeeded + 1\n }else{\n in = in -1\n }\n }\n }\n minNeeded\n }\n \n def main(args:Array[String]){\n val l = StdIn.readLine()\n println(minNum(l))\n }\n\n}"}], "negative_code": [{"source_code": "object Main extends App{\n val s = readLine()\n var maxAbs, curVal = 0\n for (c <- s){\n if (c == '+')\n curVal += 1\n else\n curVal -= 1\n maxAbs = math.max(maxAbs, math.abs(curVal))\n }\n println(maxAbs)\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject MishapInClub {\n //+ in, - out\n def minNum(l:String):Int={\n \n //net in or net out or consecutive in or consecutive out\n var netIn = 0;\n var netOut = 0;\n var last = ' ';\n var conIn = 0;\n var conOut = 0;\n var conInMax = 0;\n var conOutMax = 0;\n \n def checkConInMax(a:Int)={\n if (a>=conInMax){\n conInMax = a\n }\n }\n \n def checkConOutMax(a:Int)={\n if (a>=conOutMax){\n conOutMax = a\n }\n }\n \n for (a<-0 to l.length()-1){\n if (l(a)=='+'){\n netIn = netIn + 1\n netOut = netOut -1\n }else{\n netOut = netOut + 1\n netIn = netIn -1\n }\n if (l(a)==last){\n if (l(a)=='+'){\n conIn = conIn + 1\n checkConInMax(conIn)\n }else{\n conOut = conOut + 1\n checkConOutMax(conOut)\n }\n }else{\n if (l(a)=='+'){\n checkConInMax(conIn)\n conIn = 1\n }else{\n checkConOutMax(conOut)\n conOut = 1\n }\n }\n last = l(a)\n }\n \n checkConOutMax(conOut)\n checkConInMax(conIn)\n if (l(l.length()-1)=='+'){\n netOut = netOut + 1\n }\n if (l(l.length()-1)=='-'){\n netIn = netIn + 1\n }\n \n Math.max(Math.max(netIn, netOut), Math.max(conInMax, conOutMax))\n }\n \n def main(args:Array[String]){\n val l = StdIn.readLine()\n println(minNum(l))\n }\n\n}"}, {"source_code": "import scala.io.StdIn\n\nobject MishapInClub {\n //+ in, - out\n def minNum(l:String):Int={\n //net in or net out or consecutive in or consecutive out\n var netIn = 0;\n var netOut = 0;\n var last = ' ';\n var conIn = 0;\n var conOut = 0;\n for (a<-0 to l.length()-1){\n if (l(a)=='+'){\n netIn = netIn + 1\n netOut = netOut -1\n }else{\n netOut = netOut + 1\n netIn = netIn -1\n }\n if (l(a)==last){\n if (l(a)=='+'){\n conIn = conIn + 1\n }else{\n conOut = conOut + 1\n }\n }else{\n if (l(a)=='+'){\n conIn = 1\n }else{\n conOut = 1\n }\n }\n last = l(a)\n }\n Math.max(Math.max(netIn, netOut), Math.max(conIn, conOut))\n }\n \n def main(args:Array[String]){\n val l = StdIn.readLine()\n println(minNum(l))\n }\n\n}"}, {"source_code": "import scala.io.StdIn\n\nobject MishapInClub {\n \n def minNum(l:String):Int={\n //net in or net out or consecutive in or consecutive out\n var netIn = 0;\n var netOut = 0;\n var last = l(0)\n var conIn = if (last=='+') 1 else 0\n var conOut = if (last=='-') 1 else 0\n for (a<-0 to l.length()-1){\n if (l(a)=='+'){\n netIn = netIn + 1\n netOut = netOut -1\n }else{\n netOut = netOut + 1\n netIn = netIn -1\n }\n if (a>0 && l(a)==last){\n if (l(a)=='+'){\n conIn = conIn + 1\n conOut = 0\n }else{\n conOut = conOut + 1\n conIn = 0\n }\n }\n last = l(a)\n }\n Math.max(Math.max(netIn, netOut), Math.max(conIn, conOut))\n }\n \n def main(args:Array[String]){\n val l = StdIn.readLine()\n println(minNum(l))\n }\n\n}"}, {"source_code": "import scala.io.StdIn\n\nobject MishapInClub {\n //+ in, - out\n def minNum(l:String):Int={\n \n //net in or net out or consecutive in or consecutive out\n var netIn = 0;\n var netOut = 0;\n var last = ' ';\n var conIn = 0;\n var conOut = 0;\n var conInMax = 0;\n var conOutMax = 0;\n \n def checkConInMax(a:Int)={\n if (a>=conInMax){\n conInMax = a\n }\n }\n \n def checkConOutMax(a:Int)={\n if (a>=conOutMax){\n conOutMax = a\n }\n }\n \n for (a<-0 to l.length()-1){\n if (l(a)=='+'){\n netIn = netIn + 1\n netOut = netOut -1\n }else{\n netOut = netOut + 1\n netIn = netIn -1\n }\n if (l(a)==last){\n if (l(a)=='+'){\n conIn = conIn + 1\n checkConInMax(conIn)\n }else{\n conOut = conOut + 1\n checkConOutMax(conOut)\n }\n }else{\n if (l(a)=='+'){\n checkConInMax(conIn)\n conIn = 1\n }else{\n checkConOutMax(conOut)\n conOut = 1\n }\n }\n last = l(a)\n }\n \n checkConOutMax(conOut)\n checkConInMax(conIn)\n \n Math.max(Math.max(netIn, netOut), Math.max(conInMax, conOutMax))\n }\n \n def main(args:Array[String]){\n val l = StdIn.readLine()\n println(minNum(l))\n }\n\n}"}, {"source_code": "import scala.io.StdIn\n\nobject MishapInClub {\n //+ in, - out\n def minNum(l:String):Int={\n //net in or net out or consecutive in or consecutive out\n var netIn = 0;\n var netOut = 0;\n var last = ' ';\n var conIn = 0;\n var conOut = 0;\n var conInMax = 0;\n var conOutMax = 0;\n for (a<-0 to l.length()-1){\n if (l(a)=='+'){\n netIn = netIn + 1\n netOut = netOut -1\n }else{\n netOut = netOut + 1\n netIn = netIn -1\n }\n if (l(a)==last){\n if (l(a)=='+'){\n conIn = conIn + 1\n if (conIn>conInMax)\n conInMax = conIn\n }else{\n conOut = conOut + 1\n if (conOut>conOutMax)\n conOutMax = conOut\n }\n }else{\n if (l(a)=='+'){\n if (conIn>conInMax)\n conInMax = conIn\n conIn = 1\n \n }else{\n if (conOut>conOutMax)\n conOutMax = conOut\n conOut = 1\n }\n }\n last = l(a)\n }\n Math.max(Math.max(netIn, netOut), Math.max(conInMax, conOutMax))\n }\n \n def main(args:Array[String]){\n val l = StdIn.readLine()\n println(minNum(l))\n }\n\n}"}, {"source_code": "import scala.io.StdIn\n\nobject MishapInClub {\n \n def minNum(l:String):Int={\n var plus=0\n var minus=0\n l.foreach { x => if (x=='+') plus=plus+1 else minus=minus+1 }\n Math.abs(plus-minus)\n }\n \n def main(args:Array[String]){\n val l = StdIn.readLine()\n println(minNum(l))\n }\n\n}"}], "src_uid": "a9cd99d74418b5f227b358a910496b02"} {"source_code": "object C extends App {\r\n\r\n def slayTheDragon(heroes: IndexedSeq[Long]): (Long, Long) => Long = {\r\n\r\n def search(from: Int, to: Int, f: Int => Boolean): Int = {\r\n @annotation.tailrec\r\n def go(left: Int, right: Int): Int =\r\n if (left + 1 >= right) right\r\n else {\r\n val middle = (left + right) >>> 1\r\n\r\n f(middle) match {\r\n case true => go(left, middle)\r\n case false => go(middle, right)\r\n }\r\n }\r\n go(from, to)\r\n }\r\n\r\n val overall = heroes.sum\r\n val sorted = heroes.sorted\r\n\r\n (defense: Long, attack: Long) => {\r\n val index = search(0, heroes.length - 1, sorted(_) >= defense)\r\n\r\n def coins(index: Int): Long = {\r\n val hero = sorted(index)\r\n 0L.max(defense - hero) + 0L.max(attack - overall + hero)\r\n }\r\n\r\n coins(index) min coins(0 max (index - 1))\r\n }\r\n }\r\n\r\n import InOut._\r\n\r\n val n = nextInt()\r\n val hn = nextLongs(n)\r\n\r\n private lazy val coins = slayTheDragon(hn)\r\n\r\n val m = nextInt()\r\n\r\n (0 until m).foreach { _ =>\r\n val Array(x, y) = nextLongs(2)\r\n\r\n out.println(coins(x, y))\r\n out.flush()\r\n }\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable._\r\nimport scala.util.Sorting.quickSort\r\nimport scala.math._\r\n\r\nobject test {\r\n val writer = new PrintWriter(System.out, false)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\r\n def readInt(): Int = next().toInt\r\n def readLong(): Long = next().toLong\r\n def readString(): String = next()\r\n\r\n def bs(h: Array[Long], value: Long, start: Int, end: Int): Int = {\r\n //writer.println(start + \" \" + end)\r\n val mid = start + (end - start) / 2\r\n if (end - start < 3) {\r\n if (h(start) > value)\r\n return start\r\n else if (h(end - 1) > value)\r\n return end-1\r\n else return end\r\n }\r\n if (h(mid) < value)\r\n return bs(h, value, mid, end)\r\n else return bs(h, value, start, mid + 1)\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val n = readInt()\r\n val h = new Array[Long](n)\r\n for (i <- 0 to n-1)\r\n h(i) = readLong\r\n quickSort(h)\r\n val sum = h.sum\r\n val t = readInt()\r\n for (tt <- 1 to t) {\r\n val x = readLong()\r\n val y = readLong()\r\n var ind = bs(h, x, 0, n) - 1\r\n if (ind < 0)\r\n ind = 0\r\n var ans = max (0L, y-(sum-h(ind))) + max (0L, x - h(ind))\r\n if (ind < n-1)\r\n ans = min(ans, max (0L, y-(sum-h(ind+1))))\r\n writer.println(ans)\r\n }\r\n writer.flush()\r\n }\r\n}"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable._\r\nimport scala.math._\r\n\r\nobject test {\r\n val writer = new PrintWriter(System.out, false)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\r\n def readInt(): Int = next().toInt\r\n def readLong(): Long = next().toLong\r\n def readString(): String = next()\r\n\r\n def bs(h: Array[Long], value: Long, start: Int, end: Int): Int = {\r\n //writer.println(start + \" \" + end)\r\n val mid = start + (end - start) / 2\r\n if (end - start < 3) {\r\n if (h(start) > value)\r\n return start\r\n else if (h(end - 1) > value)\r\n return end-1\r\n else return end\r\n }\r\n if (h(mid) < value)\r\n return bs(h, value, mid, end)\r\n else return bs(h, value, start, mid + 1)\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val n = readInt()\r\n val h = new Array[Long](n)\r\n for (i <- 0 to n-1)\r\n h(i) = readLong\r\n val sum = h.sum\r\n var i = 0\r\n for (k <- h.sorted){\r\n h(i) = k\r\n i += 1\r\n }\r\n val t = readInt()\r\n for (tt <- 1 to t) {\r\n val x = readLong()\r\n val y = readLong()\r\n var ind = bs(h, x, 0, n) - 1\r\n if (ind < 0)\r\n ind = 0\r\n var ans = max (0L, y-(sum-h(ind))) + max (0L, x - h(ind))\r\n if (ind < n-1)\r\n ans = min(ans, max (0L, y-(sum-h(ind+1))))\r\n writer.println(ans)\r\n }\r\n writer.flush()\r\n }\r\n}"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable._\r\nimport scala.math._\r\n\r\nobject test {\r\n val writer = new PrintWriter(System.out, false)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\r\n def readInt(): Int = next().toInt\r\n def readLong(): Long = next().toLong\r\n def readString(): String = next()\r\n\r\n def bs(h: Array[Long], value: Long, start: Int, end: Int): Int = {\r\n //writer.println(start + \" \" + end)\r\n val mid = start + (end - start) / 2\r\n if (end - start < 3) {\r\n if (h(start) > value)\r\n return start\r\n else if (h(end - 1) > value)\r\n return end-1\r\n else return end\r\n }\r\n if (h(mid) < value)\r\n return bs(h, value, mid, end)\r\n else return bs(h, value, start, mid + 1)\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val n = readInt()\r\n val ss = reader.readLine()\r\n var h = ss.split(' ').map(_.toLong)\r\n val sum = h.sum\r\n var i = 0\r\n for (k <- h.sorted){\r\n h(i) = k\r\n i += 1\r\n }\r\n val t = readInt()\r\n for (tt <- 1 to t) {\r\n val x = readLong()\r\n val y = readLong()\r\n var ind = bs(h, x, 0, n) - 1\r\n if (ind < 0)\r\n ind = 0\r\n var ans = max (0L, y-(sum-h(ind))) + max (0L, x - h(ind))\r\n if (ind < n-1)\r\n ans = min(ans, max (0L, y-(sum-h(ind+1))))\r\n writer.println(ans)\r\n }\r\n writer.flush()\r\n }\r\n}"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable._\r\nimport scala.math._\r\n\r\nobject test {\r\n val writer = new PrintWriter(System.out, false)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\r\n def readInt(): Int = next().toInt\r\n def readLong(): Long = next().toLong\r\n def readString(): String = next()\r\n\r\n def bs(h: Array[Long], value: Long, start: Int, end: Int): Int = {\r\n //writer.println(start + \" \" + end)\r\n val mid = start + (end - start) / 2\r\n if (end - start < 3) {\r\n if (h(start) > value)\r\n return start\r\n else if (h(end - 1) > value)\r\n return end-1\r\n else return end\r\n }\r\n if (h(mid) < value)\r\n return bs(h, value, mid, end)\r\n else return bs(h, value, start, mid + 1)\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val n = readInt()\r\n val ss = reader.readLine()\r\n val h = ss.split(' ').map(_.toLong)\r\n val sum = h.sum\r\n var i = 0\r\n for (k <- h.sorted){\r\n h(i) = k\r\n i += 1\r\n }\r\n val t = readInt()\r\n for (tt <- 1 to t) {\r\n val x = readLong()\r\n val y = readLong()\r\n var ind = bs(h, x, 0, n) - 1\r\n if (ind < 0)\r\n ind = 0\r\n var ans = max (0L, y-(sum-h(ind))) + max (0L, x - h(ind))\r\n if (ind < n-1)\r\n ans = min(ans, max (0L, y-(sum-h(ind+1))))\r\n writer.println(ans)\r\n }\r\n writer.flush()\r\n }\r\n}"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable._\r\nimport scala.math._\r\n\r\nobject test {\r\n val writer = new PrintWriter(System.out, false)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\r\n def readInt(): Int = next().toInt\r\n def readLong(): Long = next().toLong\r\n def readString(): String = next()\r\n\r\n def bs(h: Array[Long], value: Long, start: Int, end: Int): Int = {\r\n //writer.println(start + \" \" + end)\r\n val mid = start + (end - start) / 2\r\n if (end - start < 3) {\r\n if (h(start) > value)\r\n return start\r\n else if (h(end - 1) > value)\r\n return end-1\r\n else return end\r\n }\r\n if (h(mid) < value)\r\n return bs(h, value, mid, end)\r\n else return bs(h, value, start, mid + 1)\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val n = readInt()\r\n val ss = reader.readLine()\r\n val h = ss.split(' ').map(_.toLong)\r\n val sum = h.sum\r\n var i = 0\r\n for (k <- h.sorted){\r\n h(i) = k\r\n i += 1\r\n }\r\n val t = readInt()\r\n for (tt <- 1 to t) {\r\n val x = readLong()\r\n val y = readLong()\r\n var ind = bs(h, x, 0, n) - 1\r\n if (ind < 0)\r\n ind = 0\r\n var ans = max (0L, y-(sum-h(ind))) + max (0L, x - h(ind))\r\n if (ind < n-1)\r\n ans = min(ans, max (0L, y-(sum-h(ind+1))))\r\n writer.println(ans)\r\n writer.flush()\r\n }\r\n writer.flush()\r\n }\r\n}"}, {"source_code": "object what extends App{\r\n def slayTheDragon(heroes: IndexedSeq[Long]): (Long, Long) => Long = {\r\n\r\n def search(from: Int, to: Int, f: Int => Boolean): Int = {\r\n @annotation.tailrec\r\n def go(left: Int, right: Int): Int =\r\n if (left + 1 >= right) right\r\n else {\r\n val middle = (left + right) >>> 1\r\n\r\n f(middle) match {\r\n case true => go(left, middle)\r\n case false => go(middle, right)\r\n }\r\n }\r\n go(from, to)\r\n }\r\n\r\n val overall = heroes.sum\r\n val sorted = heroes.sorted\r\n\r\n (defense: Long, attack: Long) => {\r\n val index = search(0, heroes.length - 1, sorted(_) >= defense)\r\n\r\n def coins(index: Int): Long = {\r\n val hero = sorted(index)\r\n 0L.max(defense - hero) + 0L.max(attack - overall + hero)\r\n }\r\n\r\n coins(index) min coins(0 max (index - 1))\r\n }\r\n }\r\n\r\n import InOut._\r\n\r\n val n = nextInt()\r\n val hn = nextLongs(n)\r\n\r\n private lazy val coins = slayTheDragon(hn)\r\n\r\n val m = nextInt()\r\n\r\n (0 until m).foreach { _ =>\r\n val Array(x, y) = nextLongs(2)\r\n\r\n out.println(coins(x, y))\r\n\r\n }\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}, {"source_code": "object what extends App{\r\n def slayTheDragon(heroes: IndexedSeq[Long]): (Long, Long) => Long = {\r\n\r\n def search(from: Int, to: Int, f: Int => Boolean): Int = {\r\n @annotation.tailrec\r\n def go(left: Int, right: Int): Int =\r\n if (left + 1 >= right) right\r\n else {\r\n val middle = (left + right) >>> 1\r\n\r\n f(middle) match {\r\n case true => go(left, middle)\r\n case false => go(middle, right)\r\n }\r\n }\r\n go(from, to)\r\n }\r\n\r\n val overall = heroes.sum\r\n val sorted = heroes.sorted\r\n\r\n (defense: Long, attack: Long) => {\r\n val index = search(0, heroes.length - 1, sorted(_) >= defense)\r\n\r\n def coins(index: Int): Long = {\r\n val hero = sorted(index)\r\n 0L.max(defense - hero) + 0L.max(attack - overall + hero)\r\n }\r\n\r\n coins(index) min coins(0 max (index - 1))\r\n }\r\n }\r\n\r\n import InOut._\r\n\r\n val n = nextInt()\r\n val hn = nextLongs(n)\r\n\r\n private lazy val coins = slayTheDragon(hn)\r\n\r\n val m = nextInt()\r\n\r\n (0 until m).foreach { _ =>\r\n val Array(x, y) = nextLongs(2)\r\n\r\n out.println(coins(x, y))\r\n out.flush()\r\n }\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}, {"source_code": "object C extends App {\r\n\r\n def slayTheDragon(heroes: IndexedSeq[Long]): (Long, Long) => Long = {\r\n\r\n def search(from: Int, to: Int, f: Int => Boolean): Int = {\r\n @annotation.tailrec\r\n def go(left: Int, right: Int): Int =\r\n if (left + 1 >= right) right\r\n else {\r\n val middle = (left + right) >>> 1\r\n\r\n f(middle) match {\r\n case true => go(left, middle)\r\n case false => go(middle, right)\r\n }\r\n }\r\n go(from, to)\r\n }\r\n\r\n val heroesSorted = heroes.sorted\r\n val heroesOverall = heroes.sum\r\n\r\n (dragonDefense: Long, dragonAttack: Long) => {\r\n val index = search(0, heroes.length - 1, heroesSorted(_) >= dragonDefense)\r\n\r\n def coins(index: Int): Long = {\r\n val hero = heroesSorted(index)\r\n 0L.max(dragonDefense - hero) + 0L.max(dragonAttack - heroesOverall + hero)\r\n }\r\n\r\n coins(index) min coins(0 max (index - 1))\r\n }\r\n }\r\n\r\n import InOut._\r\n\r\n val n = nextInt()\r\n val hn = nextLongs(n)\r\n\r\n lazy val coins = slayTheDragon(hn)\r\n\r\n val m = nextInt()\r\n\r\n (0 until m).foreach { _ =>\r\n val Array(x, y) = nextLongs(2)\r\n\r\n out.println(coins(x, y))\r\n }\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport scala.util.Sorting.quickSort\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val writer = new PrintWriter(System.out)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {\r\n while (!st.hasMoreTokens) {\r\n st = new StringTokenizer(reader.readLine())\r\n }\r\n st.nextToken()\r\n }\r\n\r\n def readInt() = next.toInt\r\n def readLong() = next.toLong\r\n def readString() = next()\r\n\r\n def pow(a: Int, b: Int): Long = {\r\n if (b == 0) return 1\r\n\r\n val rs = pow(a, b / 2)\r\n rs * rs * (if (b % 2 == 0) 1 else a)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b\r\n\r\n def root(u: Int, p: Array[Int]): Int = {\r\n if (p(u) < 0) return u\r\n p(u) = root(p(u), p)\r\n p(u)\r\n }\r\n\r\n def join(u: Int, v: Int, p: Array[Int]): Unit = {\r\n var x = root(u, p)\r\n var y = root(v, p)\r\n if (x == y) return\r\n\r\n if (p(y) < p(x)) {\r\n val t = x\r\n x = y\r\n y = t\r\n }\r\n p(x) += p(y)\r\n p(y) = x\r\n }\r\n\r\n def main(args: Array[String]) {\r\n var t = 1 //readInt()\r\n while (t > 0) {\r\n t -= 1\r\n val n = readInt()\r\n val a = new Array[Long](n)\r\n for (i <- 0 until n) a(i) = readLong()\r\n\r\n quickSort(a)\r\n val sum = a.sum\r\n\r\n val m = readInt()\r\n for (i <- 0 until m) {\r\n val x = readLong()\r\n val y = readLong() - sum\r\n\r\n if (y >= x) {\r\n writer.println(Math.max(0, x - a(0)) + Math.max(0, y + a(0)))\r\n } else {\r\n val avg = (x - y) / 2\r\n var l = 0\r\n var r = n - 1\r\n var min = -1L\r\n while (l <= r) {\r\n val mid = (l + r) / 2\r\n if (a(mid) > avg) r = mid - 1\r\n else {\r\n min = a(mid)\r\n l = mid + 1\r\n }\r\n }\r\n\r\n l = 0\r\n r = n - 1\r\n var max = -1L\r\n while (l <= r) {\r\n val mid = (l + r) / 2\r\n if (a(mid) >= avg) {\r\n r = mid - 1\r\n max = a(mid)\r\n } else l = mid + 1\r\n }\r\n\r\n val rsmin = if (min != -1) Math.max(0, x - min) + Math.max(0, y + min) else Long.MaxValue\r\n val rsmax = if (max != -1) Math.max(0, x - max) + Math.max(0, y + max) else Long.MaxValue\r\n\r\n writer.println(Math.min(rsmin, rsmax))\r\n }\r\n\r\n\r\n }\r\n }\r\n writer.close()\r\n }\r\n}"}], "negative_code": [], "src_uid": "8827e14bcba5689118f393442280d2ba"} {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nx = readIntLine()\n val arr = readIntLine().toArray\n println(findLongest(arr, nx.last))\n }\n }\n\n def findLongest(arr: Array[Int], x: Int): Int = {\n if (arr.forall(_ % x == 0)) return -1\n\n if (arr.sum % x != 0) return arr.length\n\n for (i <- arr.indices) {\n if (arr(i) % x != 0 || arr(arr.length - 1 - i) % x != 0)\n return arr.length - i - 1\n }\n\n -1\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n// def printArray[T](arr: Array[T]): Unit = {\n// val str = new StringBuilder()\n// str.addAll((if (arr.head == -1) 0 else arr.head).toString)\n// // print(arr(0))\n// for (i <- 1 until arr.length) {\n// str.addAll(\" \" + (if (arr(i) == -1) 0 else arr(i)))\n// }\n// println(str)\n// }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n", "positive_code": [{"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, x = nextInt\n val as = nextInts(n)\n var l = 0\n while (l < n && as(l) % x == 0) {\n l += 1\n }\n\n var r = n - 1\n while (r >= 0 && as(r) % x == 0) {\n r -= 1\n }\n\n var res = -1\n val sum = as.sum\n if (sum % x != 0) {\n res = n\n } else if (l <= r) {\n val rr = r\n val ll = n - l - 1\n res = ll max rr\n //println(l, r, ll, rr)\n }\n out.println(res)\n\n out.flush()\n }\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nx = readIntLine()\n val arr = readIntLine().toArray\n println(findLongest(arr, nx.last))\n }\n }\n\n def findLongest(arr: Array[Int], x: Int): Int = {\n if (arr.forall(_ % x == 0)) return -1\n\n if (arr.sum % x != 0) return arr.length\n\n for (i <- arr.indices) {\n if (arr(i) % x != 0 || arr(arr.length - 1 - i) != 0)\n return arr.length - i - 1\n }\n\n -1\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n// def printArray[T](arr: Array[T]): Unit = {\n// val str = new StringBuilder()\n// str.addAll((if (arr.head == -1) 0 else arr.head).toString)\n// // print(arr(0))\n// for (i <- 1 until arr.length) {\n// str.addAll(\" \" + (if (arr(i) == -1) 0 else arr(i)))\n// }\n// println(str)\n// }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}, {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, x = nextInt\n val as = nextInts(n)\n var l = 0\n while (l < n && as(l) % x == 0) {\n l += 1\n }\n\n var r = n - 1\n while (r >= 0 && as(r) % x == 0) {\n r -= 1\n }\n\n var res = -1\n val sum = as.sum\n if (sum % x != 0) {\n res = n\n } else {\n val rr = r - 1\n val ll = n - l - 1\n res = ll max rr\n //println(l, r, ll, rr)\n }\n out.println(res)\n\n out.flush()\n }\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, x = nextInt\n val as = nextInts(n)\n var l = 0\n while (l < n && as(l) % x == 0) {\n l += 1\n }\n\n var r = n - 1\n while (r >= 0 && as(r) % x == 0) {\n r -= 1\n }\n\n var res = -1\n val sum = as.sum\n if (sum % x != 0) {\n res = n\n } else if (l < r) {\n val rr = r - 1\n val ll = n - l - 1\n res = ll max rr\n //println(l, r, ll, rr)\n }\n out.println(res)\n\n out.flush()\n }\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "src_uid": "f5bcde6e3008405f61cead4e3f44806e"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(val a: Int, val b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return -1 * a.compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n\n\n for (tt <- 1 to t) {\n val n = readInt()\n val arr = new Array[Long](n+1)\n var cnt = 0\n var sum = 0L\n var mx = 1L\n for (i <- 1 to n) {\n arr(i) = readLong()\n while(arr(i) % 2 == 0) {\n cnt += 1\n arr(i) /= 2L\n }\n sum += arr(i)\n mx = max(mx, arr(i))\n }\n sum -= mx\n for (i <- 1 to cnt) {\n mx *= 2L\n }\n sum += mx\n writer.println(sum)\n\n def check(kk: Int): Boolean = {\n return true\n }\n def bs(st:Int, en:Int): Int = {\n if (en - st <= 1) {\n if (check(en))\n return en\n else\n return st\n }\n val mid = (st + en) / 2\n if (check(mid))\n return bs(mid, en)\n else\n return bs(st, mid)\n }\n }\n writer.flush()\n}\n", "positive_code": [{"source_code": "\r\nimport scala.+:\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable._\r\nimport scala.collection.immutable._\r\nimport scala.util.Sorting.quickSort\r\nimport scala.math._\r\nimport scala.io.StdIn\r\n\r\n\r\n\r\nobject Main extends App {\r\n val t = StdIn.readInt()\r\n (0 until t).foreach { _ =>\r\n val n = StdIn.readInt()\r\n val arr = StdIn.readLine().split(\" \").map(i => BigInt(i.toInt))\r\n var num:BigInt = 1\r\n var mx:BigInt = 0\r\n var mxidx = 0\r\n (0 until n).foreach { i =>\r\n while (arr(i) % 2 == 0) {\r\n arr(i) /= 2\r\n num *= 2\r\n }\r\n if (arr(i) > mx) {\r\n mx = arr(i)\r\n mxidx = i\r\n }\r\n }\r\n arr(mxidx) *= num\r\n println(arr.sum)\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "f5de1e9b059bddf8f8dd46c18ce12683"} {"source_code": "object _1245C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n val mod = (1e9 + 7).toInt\n\n val fib = {\n val n = 1e5.toInt\n val f = Array.ofDim[Int](n + 1)\n f.indices foreach {\n case i if i <= 1 => f(i) = i\n case i => f(i) = (f(i-1) + f(i-2)) % mod\n }\n f\n }\n\n override def apply(implicit io: IO): io.type = {\n val msg = io.read[String]\n val ans = splitRepeating(msg) map { token =>\n token(0) match {\n case 'u' | 'n' => fib(token.length + 1)\n case 'w' | 'm' => 0\n case _ => 1\n }\n }\n io.writeLine(ans.foldLeft(BigInt(1)) {case (i, j) => (i * j).mod(mod)})\n }\n\n def splitRepeating(s: String): Seq[String] = s.split(\"(?<=(.))(?!\\\\1)\")\n\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(implicit io: IO): io.type\n def repeat(f: => Unit)(implicit io: IO): io.type = {Utils.repeat(io.read[Int])(f); io}\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n case class Len(len: Int, c: Char)\n\n// nCk % MOD を求める。下準備で階乗Fと≡MODでの階乗の逆元Iを作る\nclass Comb(N: Int, MOD: Int) {\n def powMod(x: Int, n: Int, m: Int): Int = {\n def step(x: Long, n: Int, stack: Long): Long = {\n n match {\n case 0 => stack\n case _ => step(x * x % m, n / 2, if (n % 2 == 1) stack * x % m else stack)\n }\n }\n step(x, n, 1).toInt\n }\n\n private[this] val F = Array.ofDim[Long](N + 1)\n F(0) = 1\n REP(N) { i =>\n F(i + 1) = F(i) * (i + 1) % MOD\n }\n private[this] val I = Array.ofDim[Long](F.length)\n I(N) = powMod(F(N).toInt, MOD - 2, MOD)\n\n // x! = x(x-1)!\n // x!I(x!) ≡ (x-1)!I((x-1)!)\n // I((x-1)!) ≡ I(x!) * x MODがでかいので(x-1)!はMODと素\n REP_r(N) { i =>\n I(i) = I(i + 1) * (i + 1) % MOD\n }\n\n def comb(n: Int, k: Int): Long = {\n if (n < k) 0\n else F(n) * I(n - k) % MOD * I(k) % MOD\n }\n\n def rev(x: Int): Long = {\n I(x) * F(x - 1) % MOD\n }\n\n /**\n * nのグループからk回重複ありで選ぶ組み合わせ数\n * n - 1のしきりとkの○で考える\n */\n def H(n: Int, k: Int): Long = {\n comb(n + k - 1, k)\n }\n\n /**\n * private[this]をつかってるのでgetterが必要\n * @return (F, I)\n */\n def get: (Array[Long], Array[Long]) = (F, I)\n}\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val s = ns()\n val n = s.length\n if (s.contains('m') || s.contains('w')) {\n out.println(0)\n return\n }\n\n val L = ArrayBuffer[Len]()\n var cnt = 0\n REP(n) { i =>\n if (i > 0 && s(i) != s(i - 1)) {\n L += Len(cnt, s(i - 1))\n }\n if (i == 0 || s(i) != s(i - 1)) cnt = 1\n else cnt += 1\n }\n L += Len(cnt, s(n - 1))\n\n debug(L.mkString)\n\n var ans = 1L\n val comb = new Comb(n, MOD)\n def calc(x: Int): Long = {\n debug(s\"calc($x)\")\n var res = 0L\n var a = x\n var b = 0\n while (a >= 0) {\n res += comb.comb(a + b, a) % MOD\n a -= 2\n b += 1\n }\n res % MOD\n }\n\n for {\n l <- L\n if l.c == 'u' || l.c == 'n'\n } {\n ans = ans * calc(l.len) % MOD\n }\n out.println(ans)\n }\n}"}], "negative_code": [], "src_uid": "12c223c903544899638e47bcab88999a"} {"source_code": "object B extends App {\n val Array(n, m) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val x = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val y = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n var i = 0\n var j = 0\n var p = 0\n var q = 0\n var c = 1\n while (i < n && j < m) {\n if (p != 0 && q != 0 && p == q) {\n c += 1\n p = 0\n q = 0\n }\n if (p > q) {\n q += y(j)\n j += 1\n } else if (q > p) {\n p += x(i)\n i += 1\n } else {\n p += x(i)\n i += 1\n q += y(j)\n j += 1\n }\n }\n\n println(c)\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) {\n\n val (n, m) = StdIn.readLine.split(\" \").map(_.toInt) match {\n case xy: Array[Int] => (xy(0), xy(1))\n }\n\n val x = StdIn.readLine.split(\" \").map(_.toInt)\n val y = StdIn.readLine.split(\" \").map(_.toInt)\n\n var z = 0\n val xc = x.map(a => {\n z += a\n z\n })\n\n z = 0\n val yc = y.map(a => {\n z += a\n z\n })\n\n var ans = 0\n\n var (i, j) = (0, 0)\n while (i < n && j < m) {\n val small = Math.min(xc(i), yc(j))\n\n if (xc(i) == yc(j)) ans += 1\n if (xc(i) == small) i += 1\n else j += 1\n }\n\n println(ans)\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn._\nobject B950 {\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt)\n val b = readLine().split(\" \").map(_.toInt)\n var left = 0\n var right = 0\n var aSum = -1\n var bSum = -1\n var res = 0\n while (!(left >= n && right >= m)) {\n if (aSum != -1 && aSum == bSum) {\n res += 1\n aSum = -1\n bSum = -1\n } else if (aSum == -1) {\n aSum = if (left < n) a(left) else 0\n left += 1\n bSum = if (right < m) b(right) else 0\n right += 1\n } else if (aSum < bSum) {\n aSum += (if (left < n) a(left) else 0)\n left += 1\n } else {\n bSum += (if (right < m) b(right) else 0)\n right += 1\n }\n }\n if (aSum != -1 && aSum == bSum) res += 1\n println(res)\n }\n}\n"}, {"source_code": "object bTask2 {\n import scala.io.StdIn.{readLine, readInt}\n\n def message(n: Int, m: Int, xs: List[Int], ys: List[Int]):Int = {\n\n def helper(xx: List[Int], yy: List[Int], ax: Int, ay: Int, num: Int):Int = {\n (xx, yy) match {\n case (Nil,_)|(_,Nil) => num\n case (l@(x::xss), y::yss) if ax > ay => helper(l, yss, ax, ay + y, num)\n case (x::xss, r@(y::yss)) if ax < ay => helper(xss, r, ax + x, ay, num)\n case (x::xss, y::yss) if ax == ay => helper(xss, yss, x, y, num + 1)\n }\n }\n helper(xs, ys, 0,0,0)\n }\n\n def main(args: Array[String]):Unit = {\n val n::m::Nil = readLine.split(\" \").map(_.toInt).toList\n val xs = readLine.split(\" \").map(_.toInt).toList\n val ys = readLine.split(\" \").map(_.toInt).toList\n println(message(n,m,xs,ys))\n }\n}"}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n val sc = new java.util.Scanner(System.in)\n val n, m = sc.nextInt\n val xs = prefixSum(List.fill(n)(sc.nextInt))\n val ys = prefixSum(List.fill(m)(sc.nextInt))\n \n println(xs.foldLeft((ys, 0)) {\n case ((zs, res), x) =>\n zs.span(_ < x)._2 match {\n case (z :: zs) if z == x => (zs, res + 1)\n case zs => (zs, res)\n }\n }._2 - 1)\n }\n \n def prefixSum(as: List[Int]) = as.scanLeft(0){ case (acc, a) => a + acc }\n}"}], "negative_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val sc = new java.util.Scanner(System.in)\n val n, m = sc.nextInt\n val xs = prefixSum(List.fill(n)(sc.nextInt))\n val ys = prefixSum(List.fill(m)(sc.nextInt))\n\n println(xs.foldLeft((ys, 0)) {\n case ((Nil, res), _) => (Nil, res)\n case ((z :: zs, res), x) => if (x == z) (zs, res + 1) else ((z :: zs).dropWhile(_ < x), res)\n }._2)\n }\n \n def prefixSum(as: List[Int]) = as.scanLeft(0){ case (acc, a) => a + acc }\n}"}], "src_uid": "cb5cbfb4d184cda21ebfbcf47bb970dc"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(val a: Int, val b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return a.compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val m = readInt()\n var a = n\n var b = m\n if (m > n) {\n a = m\n b = n\n }\n var ans = 0\n ans = (a / 3).toInt * b\n a = a % 3\n ans += (b / 3).toInt * a\n b = b % 3\n if (a == 2 && b == 2)\n ans += 2\n else if (a != 0 && b != 0)\n ans += 1\n writer.println(ans)\n }\n writer.flush()\n}\n", "positive_code": [{"source_code": "import scala.io.Source\r\n\r\nobject Main extends App {\r\n val input = Source.fromInputStream(System.in).getLines()\r\n val t = input.next().toInt\r\n Range(0, t).map(_ => input.next().split(\" \"))\r\n .map(x => (x(0).toInt, x(1).toInt))\r\n .foreach(nm => {\r\n val (n, m) = nm\r\n val c3 = if (n * m % 3 == 1) (n * m) / 3 - 1 else (n * m) / 3\r\n val c2 = (n * m - c3 * 3) / 2\r\n println(c3 + c2)\r\n })\r\n}\r\n"}], "negative_code": [], "src_uid": "70a0b98f2bb12990a0fa46aaf13134af"} {"source_code": "import scala.io.StdIn._\n\nobject Main2 extends App {\n val boyNumber = readInt()\n val boySkills = readLine().split(\" \").map(_.toInt).sorted\n val girlNumber = readInt()\n val girlSkills = readLine().split(\" \").map(_.toInt).sorted\n var boyIndex: Int = 0\n var girlIndex: Int = 0\n var ans = 0\n while(boyIndex < boyNumber && girlIndex < girlNumber) {\n val difference = boySkills(boyIndex) - girlSkills(girlIndex)\n difference match {\n case d if Math.abs(d) < 2 =>\n boyIndex += 1\n girlIndex += 1\n ans += 1\n case d if d < 0 => boyIndex += 1\n case d if d > 0 => girlIndex += 1\n }\n }\n println(ans)\n}\n", "positive_code": [{"source_code": "object B {\n\n def main(args: Array[String]): Unit = {\n readInt()\n val a = readLine().split(\" \").toList.map(_.toInt).sorted\n readInt()\n val b = readLine().split(\" \").toList.map(_.toInt).sorted\n println(dancing(a, b, Map())._1)\n }\n\n type Memo = Map[(Int, Int), Int]\n\n def dancing(a: List[Int], b: List[Int], memo: Memo): (Int, Memo) = (a, b) match {\n case (Nil, _) => (0, memo)\n case (_, Nil) => (0, memo)\n case (x :: xs, y :: ys) =>\n if (memo.contains((a.length, b.length))) {\n (memo.get((a.length, b.length)).get, memo)\n } else if (math.abs(x - y) <= 1) {\n val z = dancing(xs, ys, memo)\n (z._1 + 1, z._2 + ((a.length, b.length) -> (z._1 + 1)))\n } else {\n val z1 = dancing(a, ys, memo)\n val z2 = dancing(xs, b, z1._2)\n val res = math.max(z1._1, z2._1)\n (res, z2._2 + ((a.length, b.length) -> res))\n }\n }\n}\n"}, {"source_code": "object Solution {\n\n import scala.math._\n\n def main(args: Array[String]) {\n\n val sc = new java.util.Scanner(System.in)\n\n val n = sc.nextInt()\n val boys = Array.fill(n)(sc.nextInt()).sorted\n\n val m = sc.nextInt()\n val girls = Array.fill(m)(sc.nextInt()).sorted\n\n val dp = Array.fill(n)(Array.fill(m)(0))\n\n dp(0)(0) = if(abs(boys(0)-girls(0))<2) 1 else 0\n\n for (i <- (1 until m)) {\n if (dp(0)(i-1) == 1) dp(0)(i) = 1\n else if (abs(boys(0)-girls(i)) < 2) dp(0)(i) = 1\n }\n for (i <- (1 until n)) {\n if (dp(i-1)(0) == 1) dp(i)(0) = 1\n else if (abs(boys(i)-girls(0)) < 2) dp(i)(0) = 1\n }\n\n for (i <- (1 until n)) {\n for (j <- (1 until m)) {\n if (abs(boys(i)-girls(j)) < 2)\n dp(i)(j) = List(dp(i-1)(j-1)+1, dp(i-1)(j), dp(i)(j-1)).max\n else\n dp(i)(j) = max(dp(i-1)(j), dp(i)(j-1))\n }\n }\n\n println(dp(n-1)(m-1))\n }\n}\n"}, {"source_code": "object SB_2 {\n def main(args:Array[String]):Unit={\n val n:Int=readInt()\n var arr1:Array[Int]=new Array[Int](n)\n\n val l1=readLine()\n val line1:Array[String]=l1.split(\" \")\n for(i<-0 until arr1.length)\n arr1(i)=line1(i).toInt\n arr1=arr1.sortBy(x=>x)\n\n\n val m:Int=readInt()\n var arr2:Array[Int]=new Array[Int](m)\n\n val l2=readLine()\n val line2:Array[String]=l2.split(\" \")\n for(i<-0 until arr2.length)\n arr2(i)=line2(i).toInt\n arr2=arr2.sortBy(x=>x)\n\n\n\n var i:Int=0\n var j:Int=0\n var flagi:Boolean=true\n var flagj:Boolean=true\n var sum:Int=0\n\n while(flagi&&flagj){\n while(flagj&&flagi){\n if(Math.abs(arr1(i)-arr2(j))<=1){\n i=i+1\n j=j+1\n sum=sum+1\n\n if(i>=arr1.length)\n flagi=false\n if(j>=arr2.length)\n flagj=false\n }\n else{\n if(arr1(i)>arr2(j))\n j=j+1\n else\n i=i+1\n\n if(i>=arr1.length)\n flagi=false\n if(j>=arr2.length)\n flagj=false\n }\n\n if(i>=arr1.length)\n flagi=false\n if(j>=arr2.length)\n flagj=false\n }\n }\n\n println(sum)\n\n }\n\n}"}, {"source_code": "object SB_2 {\n def main(args:Array[String]):Unit={\n val n:Int=readInt()\n var arr1:Array[Int]=new Array[Int](n)\n\n val l1=readLine()\n val line1:Array[String]=l1.split(\" \")\n for(i<-0 until arr1.length)\n arr1(i)=line1(i).toInt\n arr1=arr1.sortBy(x=>x)\n\n\n val m:Int=readInt()\n var arr2:Array[Int]=new Array[Int](m)\n\n val l2=readLine()\n val line2:Array[String]=l2.split(\" \")\n for(i<-0 until arr2.length)\n arr2(i)=line2(i).toInt\n arr2=arr2.sortBy(x=>x)\n\n\n\n var i:Int=0\n var j:Int=0\n var flagi:Boolean=true\n var flagj:Boolean=true\n var sum:Int=0\n\n while(flagi&&flagj){\n while(flagj&&flagi){\n if(Math.abs(arr1(i)-arr2(j))<=1){\n i=i+1\n j=j+1\n sum=sum+1\n }\n else{\n if(arr1(i)>arr2(j))\n j=j+1\n else\n i=i+1\n }\n\n if(i>=arr1.length)\n flagi=false\n if(j>=arr2.length)\n flagj=false\n }\n }\n\n println(sum)\n\n }\n\n}"}, {"source_code": "object B489 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val boys = readInts(n).sortBy(identity)\n val Array(m) = readInts(1)\n val girls = readInts(m).sortBy(identity)\n\n var res = 0\n var j = 0\n var lastj = 0\n for(i <- boys.indices) {\n var break = false\n while(!break && j < girls.length && girls(j) <= boys(i)+1) {\n if(math.abs(boys(i) - girls(j)) <= 1) {\n res += 1\n lastj = j\n break = true\n }\n j += 1\n }\n if(break) j = lastj+1\n }\n\n println(res)\n }\n}"}, {"source_code": "/**\n * Created by yousack on 2017/03/01.\n */\n\nimport scala.io.StdIn.readLine\n\nobject App {\n def main(args: Array[String]): Unit = {\n val n = readLine().toInt\n var a = readLine().split(\" \").map(_.toInt).sorted\n val m = readLine().toInt\n var b = readLine().split(\" \").map(_.toInt).sorted\n var ans = 0\n\n while (!a.isEmpty && !b.isEmpty) {\n if (math.abs(a{0} - b{0}) <= 1) {\n ans += 1\n a = a.drop(1)\n b = b.drop(1)\n } else if (a{0} < b{0}) {\n a = a.drop(1)\n } else {\n b = b.drop(1)\n }\n }\n\n print(ans)\n }\n}\n"}, {"source_code": "/**\n * Created by yousack on 2017/03/01.\n */\n\nimport scala.io.StdIn.readLine\n\nobject App {\n def main(args: Array[String]): Unit = {\n val n = readLine().toInt\n val a = readLine().split(\" \").map(_.toInt).sorted\n val m = readLine().toInt\n val b = readLine().split(\" \").map(_.toInt).sorted\n\n print(solve(a, b, 0))\n }\n\n def solve(a: Array[Int], b: Array[Int], p: Int): Int = {\n if (a.isEmpty || b.isEmpty) {\n return p\n }\n\n if (math.abs(a{0} - b{0}) <= 1) {\n solve(a.drop(1), b.drop(1), p + 1)\n } else if (a{0} < b{0}) {\n solve(a.drop(1), b, p)\n } else {\n solve(a, b.drop(1), p)\n }\n }\n}\n"}], "negative_code": [{"source_code": "object B489 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val boys = readInts(n).sortBy(identity)\n val Array(m) = readInts(1)\n val girls = readInts(m).sortBy(identity)\n\n var res = 0\n var j = 0\n var lastj = 0\n for(i <- boys.indices) {\n var break = false\n while(!break && j < girls.length && girls(j) <= boys(i)+1) {\n if(math.abs(boys(i) - girls(j)) <= 1) {\n res += 1\n lastj = j\n break = true\n }\n j += 1\n }\n j = lastj+1\n }\n\n println(res)\n }\n}"}, {"source_code": "object B {\n\n def main(args: Array[String]): Unit = {\n readInt()\n val a = readLine().split(\" \").toList.map(_.toInt).sorted\n readInt()\n val b = readLine().split(\" \").toList.map(_.toInt).sorted\n println(dancing(a, b, Map())._1)\n }\n\n type Memo = Map[(Int, Int), Int]\n\n def dancing(a: List[Int], b: List[Int], memo: Memo): (Int, Memo) = (a, b) match {\n case (Nil, _) => (0, memo)\n case (_, Nil) => (0, memo)\n case (x :: xs, y :: ys) =>\n if (memo.contains((x, y))) {\n (memo.get((x, y)).get, memo)\n } else if (math.abs(x - y) <= 1) {\n val z = dancing(xs, ys, memo)\n (z._1 + 1, z._2 + ((x, y) -> (z._1 + 1)))\n } else {\n val z1 = dancing(a, ys, memo)\n val z2 = dancing(xs, b, z1._2)\n val res = math.max(z1._1, z2._1)\n (res, z2._2 + ((x, y) -> res))\n }\n }\n}\n"}], "src_uid": "62766ef9a0751cbe7987020144de7512"} {"source_code": "\nimport scala.io.StdIn\n\nobject Test extends App {\n\n def find(packages: List[Int],and: Map[Int,Int],gr: Map[Int,Int],index: Int): Map[Int,Int ] = {\n val sum1 = and.values.sum\n val sum2 = gr.values.sum\n if (packages.isEmpty && sum1 != sum2 && sum1 != 0 && sum2 != 0) gr\n else\n {\n if (packages.nonEmpty) {\n val current = packages.head\n val a1 = find(packages.tail, and.updated(index, current), gr, index + 1)\n if (a1.nonEmpty) a1\n else {\n find(packages.tail, and, gr.updated(index, current), index + 1)\n }\n }else Map.empty\n }\n }\n\n val n = StdIn.readLine().trim.toInt\n val s = StdIn.readLine().split(\" \").map(_.toInt).toList\n\n val gr = find(s,Map.empty,Map.empty,0)\n if (gr.isEmpty)\n {\n println(-1)\n }else\n {\n println(gr.size)\n gr.keys.map(_ + 1).foreach(el => print(s\"$el \"))\n }\n}", "positive_code": [{"source_code": "object Main{\n def main(args: Array[String]) {\n val n = readInt()\n if(n == 1){\n println(-1)\n return;\n }\n val a = readLine().split(\" \").map(_.toInt)\n\n var minIndex = -1\n var minValue = Long.MaxValue\n var sum: Long = 0L\n for(i <- 0 to (a.length - 1)){\n if(a(i) < minValue){\n minValue = a(i)\n minIndex = i\n }\n sum += a(i)\n }\n\n if(sum - minValue == minValue){\n println(-1)\n return;\n }\n\n println(1)\n println(minIndex + 1)\n\n }\n}"}], "negative_code": [{"source_code": "object Main{\n def main(args: Array[String]) {\n val n = readInt()\n if(n == 1){\n println(-1)\n return;\n }\n val a = readLine().split(\" \").map(_.toInt)\n\n var minIndex = -1\n var minValue = Long.MaxValue\n var sum: Long = 0L\n for(i <- 0 to (a.length - 1)){\n if(a(i) < minValue){\n minValue = a(i)\n minIndex = i\n }\n sum += a(i)\n }\n\n if(sum - minValue == minValue){\n println(-1)\n return;\n }\n\n println(1)\n println(minIndex)\n\n }\n}"}, {"source_code": "object Main{\n def main(args: Array[String]) {\n val n = readInt()\n if(n == 1){\n println(-1)\n return;\n }\n val a = readLine().split(\" \").map(_.toInt)\n\n var minIndex = -1\n var minValue = Long.MaxValue\n var sum: Long = 0L\n for(i <- 0 to (a.length - 1)){\n if(a(i) < minValue){\n minValue = a(i)\n minIndex = i\n }\n sum += a(i)\n }\n\n if(sum - minValue == minValue){\n println(-1)\n return;\n }\n\n println(1)\n println(minValue)\n\n }\n}"}], "src_uid": "2b55012c899645bac8d293e85e73148f"} {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.Ordering.Implicits._\nimport scala.collection.mutable\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def solve(): Unit = {\n val (r, s, p) = (nextInt, nextInt, nextInt)\n val dp = Array.ofDim[Double](r + 1, s + 1, p + 1)\n dp(r)(s)(p) = 1.0\n for (i <- (0 to r).reverse) {\n for (j <- (0 to s).reverse) {\n for (k <- (0 to p).reverse) {\n val total = i * j + j * k + i * k\n if (i > 0 && j > 0) {\n dp(i)(j - 1)(k) += dp(i)(j)(k) * (i * j) / total\n }\n if (j > 0 && k > 0) {\n dp(i)(j)(k - 1) += dp(i)(j)(k) * (j * k) / total\n }\n if (i > 0 && k > 0) {\n dp(i - 1)(j)(k) += dp(i)(j)(k) * (i * k) / total\n }\n }\n }\n }\n var (ans_r, ans_s, ans_p) = (0.0, 0.0, 0.0)\n for (i <- 1 to r) ans_r += dp(i)(0)(0)\n for (j <- 1 to s) ans_s += dp(0)(j)(0)\n for (k <- 1 to p) ans_p += dp(0)(0)(k)\n out.println(f\"$ans_r%.12f $ans_s%.12f $ans_p%.12f\")\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n", "positive_code": [{"source_code": "object main{\n object Solver extends InputReader{\n val dp = Array.ofDim[Array[Double]](128, 128, 128)\n\n def merge(rate: Double, dst: Array[Double], src: Array[Double]){\n for(i <- 0 to dst.length - 1)\n dst(i) += rate * src(i)\n }\n\n def dfs(r: Int, s: Int, p: Int): Array[Double] = {\n if(dp(r)(s)(p) != null) return dp(r)(s)(p)\n val ret = new Array[Double](3)\n\n if(r == 0){\n ret(1) = 1\n }else if(s == 0){\n ret(2) = 1\n }else if(p == 0){\n ret(0) = 1\n }else{\n val all = r + s + p\n val b: Double = all * (all - 1) / 2\n\n merge((r * s) / b, ret, dfs(r, s - 1, p))\n merge((s * p) / b, ret, dfs(r, s, p - 1))\n merge((p * r) / b, ret, dfs(r - 1, s, p))\n\n val sum = ret.sum\n for(i <- 0 to ret.length - 1)\n ret(i) /= sum\n }\n\n dp(r)(s)(p) = ret\n return ret\n }\n\n def solve(){\n val r = getInt()\n val s = getInt()\n val p = getInt()\n\n for(a <- dfs(r, s, p))\n printf(\"%.12f \", a)\n println()\n }\n }\n\n // TEMPLATE ------------------------\n\n def main(args: Array[String]){\n Solver.solve()\n }\n\n trait InputReader{\n import java.io._\n import java.util._\n protected val stream = System.in\n private val reader = new BufferedReader(new InputStreamReader(stream))\n private var tokenizer = new StringTokenizer(reader.readLine())\n\n def getStr(): String = {\n while(!tokenizer.hasMoreTokens())\n tokenizer = new StringTokenizer(reader.readLine())\n tokenizer.nextToken()\n }\n\n def getInt(): Int = getStr().toInt\n def getLong(): Long = getStr().toLong\n def getDouble(): Double = getStr().toDouble\n }\n}\n"}, {"source_code": "import annotation.tailrec\n\nobject main extends App with fastIO {\n \n val Array(a, b, c) = readLine split(\" \") map(_.toInt)\n var dp = Array.fill[Double](101, 101, 101)(-1)\n \n def sum1n(n: Int) = n * (n - 1) >> 1\n \n def dfs(a: Int, b: Int, c: Int): Double = {\n if (a == 0) return 0\n if (b + c == 0) return 1\n \n if (dp(a)(b)(c) > -1e-10) return dp(a)(b)(c)\n var value: Double = 0\n \n var cnt: Double = sum1n(a + b + c)\n var q: Double = (sum1n(a) + sum1n(b) + sum1n(c)) / cnt\n \n if (a > 0) value += dfs(a - 1, b, c) * (a * c) / cnt\n if (b > 0) value += dfs(a, b - 1, c) * (b * a) / cnt\n if (c > 0) value += dfs(a, b, c - 1) * (c * b) / cnt\n \n value *= 1 / (1 - q) \n \n dp(a)(b)(c) = value\n value\n }\n \n println(\"%.10f %.10f %.10f\" format(dfs(a, b, c), dfs(b, c, a), dfs(c, a, b)) replace(\",\",\".\")) \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}"}], "negative_code": [], "src_uid": "35736970c6d629c2764eaf23299e0356"} {"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val t = stdin.next().toInt\n val res = stdin.take(t * 2).map(_.split(\" \").map(_.toInt)).grouped(2).map {\n arr =>\n val Array(n, p, k) = arr.head\n val x = arr(1).sorted\n solve(x, p, k)\n }\n\n println(res.mkString(\"\\n\"))\n\n def solve(x: Array[Int], p: Int, k: Int) = {\n var startIndex = 0\n var endIndex = k\n val sum = x.scanLeft(0) {case(acc, el) => acc + el}.tail\n var currentVal = sol(x, p, k, k - 1)\n// println(currentVal)\n while (startIndex + 1 < endIndex) {\n val mid = (startIndex + endIndex) / 2\n// println(\"mid \" + mid)\n val tr = if (mid == 0 || sum(mid - 1) > p) 0 else mid + sol(x, p - sum(mid - 1), k, mid + k - 1)\n if (tr > currentVal) {\n currentVal = tr\n startIndex = mid\n }\n else {\n endIndex = mid\n }\n }\n currentVal\n }\n\n def sol(x: Array[Int], p: Int, k: Int, tryIndex: Int): Int = {\n if (tryIndex >= x.length) Math.max(0, (tryIndex - k + 1) / k * k)\n else if (x(tryIndex) > p) Math.max(0, (tryIndex - k + 1) / k * k)\n else sol(x, p - x(tryIndex), k, tryIndex + k)\n }\n\n}\n\n\n// 5 11 2\n// 2 3 4 5 7\n\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"MY_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = {\n if (!oj){ System.err.println(s) }\n }\n def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n private[this] def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n def upperBound(a: Array[Long], x: Long): Int = {\n def step(l: Int, h: Int): Int = {\n if (h - l == 1) h\n else {\n val mid = (l + h) / 2\n if (a(mid) > x) step(l, mid)\n else step(mid, h)\n }\n }\n\n step(-1, a.length)\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N, P, K = ni()\n val A = na(N)\n sort(A)\n val S = Array.ofDim[Long](N + 1)\n REP(N) { i =>\n if (i + 1 >= K) {\n S(i + 1) = S(i + 1 - K) + A(i)\n }\n }\n debug(S)\n val cum = Array.ofDim[Long](K - 1)\n cum(0) = A(0)\n REP(K - 2, 1) { i =>\n cum(i) = cum(i - 1) + A(i)\n }\n debug(cum)\n\n var ans = 0\n REP(N) { i =>\n if (S(i + 1) <= P) {\n val remain = P - S(i + 1)\n val c1 = (i + 1) / K * K\n val c2 = upperBound(cum, remain)\n val c = c1 + min(c2, i + 1 - c1)\n ans = max(ans, c)\n }\n }\n out.println(ans)\n }\n }\n}"}], "negative_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"MY_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = {\n if (!oj){ System.err.println(s) }\n }\n def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n private[this] def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N, P, K = ni()\n val A = na(N)\n sort(A)\n val S = Array.ofDim[Long](N)\n REP(N) { i =>\n if (i - K >= 0) {\n S(i) = A(i) + S(i - K)\n } else {\n S(i) = A(i)\n }\n }\n debug(S)\n var ans = 0\n REP(N) { i =>\n if (S(i) <= P) {\n val v = if (i + 1 >= K) i + 1 else 1\n ans = max(ans, v)\n }\n }\n out.println(ans)\n }\n }\n}"}], "src_uid": "79d07b0f6ea14daf208aef1acd6466c1"} {"source_code": "import scala.io.StdIn._\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n def getFreq(str: String) = str.groupBy(identity).map(p => (p._1, p._2.length))\n lazy val input = getFreq(readLine)\n println(getFreq(\"Bulbasaur\").map(p => input.getOrElse(p._1, 0) / p._2).min)\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val str = \"Bulbasaur\".toCharArray\n val str2 = in.next().toCharArray\n val answer = str2.filter(str.contains).groupBy(identity).map {\n case ('a', str) => str.length / 2\n case ('u', str) => str.length / 2\n case (_, str) => str.length\n }.toList.sorted\n\n if (str.forall(str2.contains))\n println(answer.headOption.getOrElse(0))\n else\n println(0)\n\n}"}, {"source_code": "object GottaCatchEmAll extends App{\n val textCount = io.StdIn.readLine().groupBy(_.toChar).mapValues(_.length)\n val bulbasaur = \"Bulbasaur\".groupBy(_.toChar).mapValues(_.length)\n val ans = bulbasaur.collect{ case (k, v) => textCount.getOrElse(k, 0) / v }.min\n println(ans)\n}\n"}, {"source_code": "object A757 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val in = read\n val map = collection.mutable.Map.empty[Char, Int].withDefaultValue(0)\n in.foreach{char => map(char) += 1}\n\n var res = Array(map('B'), map('u')/2, map('l'), map('b'), map('a')/2, map('s'), map('r')).min//\"Bulbasaur\"\n println(res)\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "\nimport scala.io.StdIn._\n\nobject Main extends App {\n val A = readLine()\n\n val G = A.groupBy(identity).mapValues(_.length)\n val min = Array(\n G.getOrElse('B', 0),\n G.getOrElse('u', 0) / 2,\n G.getOrElse('l', 0),\n G.getOrElse('b', 0),\n G.getOrElse('a', 0) / 2,\n G.getOrElse('s', 0),\n G.getOrElse('r', 0)).min\n\n println(min)\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val str = \"Bulbasaur\".toCharArray\n val answer = in.next().filter(str.contains).groupBy(identity).map {\n case ('a', str) => str.length / 2\n case ('u', str) => str.length / 2\n case (_, str) => str.length\n }.toList.sorted\n \n if (str.forall(answer.contains))\n println(answer.headOption.getOrElse(0))\n else\n println(0)\n\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val str = \"Bulbasaur\".toCharArray\n val answer = in.next().filter(str.contains).groupBy(identity).map {\n case ('a', str) => str.length / 2\n case ('u', str) => str.length / 2\n case (_, str) => str.length\n }.toList.sorted.headOption\n \n\n println(answer.getOrElse(0))\n\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val str = \"Bulbasaur\".toCharArray\n val answer = in.next().filter(str.contains).groupBy(identity).map {\n case ('a', str) => str.length / 2\n case ('u', str) => str.length / 2\n case (_, str) => str.length\n }.max\n\n println(answer)\n\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n def getFreq(str: String) = str.groupBy(identity).map(p => (p._1, p._2.length))\n lazy val input = getFreq(readLine)\n println(getFreq(\"Bulbbasaur\").map(p => input.getOrElse(p._1, 0) / p._2).min)\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n def getFreq(str: String) = str.groupBy(identity).map(p => (p._1, p._2.length))\n val input = getFreq(readLine)\n println(getFreq(\"Bulbbasaur\").map(p => input.getOrElse(p._1, 0) / p._2).min)\n }\n}\n"}, {"source_code": "\nimport scala.io.StdIn._\n\nobject Main extends App {\n val A = readLine()\n val Match = \"Bulbbasaur\"\n\n val G = A.groupBy(identity).mapValues(_.length)\n val min = Array(\n G.getOrElse('B', 0),\n G.getOrElse('u', 0) / 2,\n G.getOrElse('l', 0),\n G.getOrElse('b', 0) / 2,\n G.getOrElse('a', 0) / 2,\n G.getOrElse('s', 0),\n G.getOrElse('r', 0)).min\n\n println(min)\n}\n"}], "src_uid": "9c429fd7598ea75acce09805a15092d0"} {"source_code": "import scala.io.StdIn\n\nobject Solution_D extends App {\n val T = StdIn.readInt()\n for (_ <- 1 to T) {\n val sudoku = Array.ofDim[String](9)\n val result = Array.ofDim[Int](9, 9)\n for (idx <- 0 until 9) {\n sudoku(idx) = StdIn.readLine()\n for (c <- 0 until 9) {\n result(idx)(c) = sudoku(idx)(c).toInt - '0'\n }\n }\n for (offset <- 0 until 3) {\n for (r <- 0 until 3) {\n val column = r + offset * 3\n val row = offset + r * 3\n result(row)(column) = 1 + result(row)(column) % 9\n }\n }\n for (idx <- 0 until 9) {\n println(result(idx).mkString)\n }\n }\n}\n", "positive_code": [{"source_code": "\nobject Main extends App {\n import scala.io.StdIn._\n val t = readInt\n\n for(_ <- 0 until t) {\n val state = Array.fill(9){readLine.trim.map(_.asDigit).toArray}\n var j = 0\n for (i <- 0 until 9) {\n state(i)(j) = state(i)(j) % 9 + 1\n j = (j + 4) % 9\n }\n println(state.map(_.mkString).mkString(\"\\n\"))\n }\n}\n"}], "negative_code": [], "src_uid": "0e21f1c48c8c0463b2ffa7275eddc633"} {"source_code": "//package round111.div2\n\n/**\n * Created by IntelliJ IDEA.\n * User: User\n * Date: 08.03.12\n * Time: 6:11\n * To change this template use File | Settings | File Templates.\n */\n\nobject A {\n readLine()\n val a = readLine() split ' ' map (_ toInt) sortBy (-_)\n var s = -a.sum / 2\n val b = for (coin <- a.iterator takeWhile (_ => s <= 0)) yield {\n s += coin\n coin\n }\n\n def main(args: Array[String]) = println(b.size)\n\n\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nimport scala.io.StdIn._\nimport scala.util.Sorting\n\n\nobject HelloWorldMain {\n\n def main(args: Array[String]): Unit = {\n\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n\n var list = new Array[Int](n)\n\n var sum = 0\n for(i <- 0 until n ) {\n list(i) = sc.nextInt()\n sum += list(i)\n }\n\n\n Sorting.quickSort(list)\n\n\n var takenAmount = 0\n var iterator = n-1\n var totalnumberOfCoins = 0\n while (takenAmount <= sum/2 ){\n takenAmount += list(iterator)\n totalnumberOfCoins += 1\n iterator -=1\n }\n\n println(totalnumberOfCoins)\n\n }\n}\n\n\n\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject Twins {\n \n def main(args: Array[String]) { \n val n = readInt\n val coins = readLine.split(' ').map(_.toInt).sorted.reverse\n val toTake = coins.sum/2 + 1 \n println(coins.scanLeft(0)(_ + _)\n .zipWithIndex.find{ case (s,i) => s >= toTake}.getOrElse( (0,0))._2)\n }\n \n}"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by dr0ff on 02/03/16.\n */\nobject Twins {\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n\n val num = in.nextLine().trim.toInt\n val coins = in.nextLine().trim.split(\" \").map(_.toInt)\n print(minHalfNum(coins))\n }\n\n def minHalfNum(coins: Array[Int]): Int = {\n val half = coins.sum / 2.0\n def loop(coins: List[Int], num: Int, total: Long): Int =\n if (total > half)\n num\n else\n coins match {\n case c :: cs => loop(cs, num + 1, total + c)\n case Nil => num\n }\n\n loop(coins.sorted(Ordering[Int].reverse).toList, 0, 0)\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Task extends App{\n\tval N = readLine.split(\" \").map{_.toInt}.head\n\tval coins = readLine.split(\" \").map{_.toInt}.sorted.reverse\n\t\n\tval leftSums = coins.scanLeft(0)((a,b) => a + b).tail\n\tval rightSums = coins.scanRight(0)((a,b) => a + b).tail\n\t\n\t//println(leftSums.mkString)\n\t//println(rightSums.mkString)\n\t\n\tval a = leftSums.zip(rightSums).filter{case (l,r) => l <= r}\n\t//println(a.mkString)\n\t\n\tprintln(a.size + 1)\n}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ListBuffer\n\nobject Main { \n def main(args: Array[String]) { \n val sc = new Scanner(System.in)\n val n = sc.nextInt\n val xs = new ListBuffer[Int]\n for (i <- 1 to n) { \n xs += sc.nextInt\n }\n val ys = xs.sortWith(_ > _).toList\n var sumA = 0\n var sumB = ys.sum\n var flag = false\n var index = ys.size\n for (i <- 0 until ys.size) { \n if (!flag) { \n if (sumA <= sumB) { \n sumA += ys(i)\n sumB -= ys(i)\n } else { \n index = i\n flag = true\n }\n }\n }\n println(index)\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.util.control.Breaks._\n\nimport sun.swing.SwingUtilities2.RepaintListener\n\nobject Main {\n def main(args: Array[String]): Unit = {\n\n val s = new Scanner(System.in)\n val a = s.nextInt()\n val numbers: Array[Int] = Array.fill(a) {\n 0\n }\n for (i <- 0 until a){\n numbers(i) = s.nextInt()\n }\n\n val list = numbers.toList.sorted\n\n val rev = list.reverse\n\n val llist = list.scanLeft(0)(_+_)\n\n val lllist = llist.reverse\n\n val rlist = rev.scanLeft(0)(_+_)\n\n def Index(al:(List[Int],List[Int])): Int =\n al match {\n case (Nil, Nil) => 999999\n case (xs :: xss, ys :: yss) => if (xs > ys) xs else Index((xss, yss))\n }\n\n\n\n println(rlist.indexOf( Index( (rlist,lllist)) ))\n\n\n// def minIndex(x: List[Int], y:List[Int]): List[Int] = {\n// var sol = List()\n// for(i <- 0 until a) {\n// if (x(i) > y(i)) {i :: sol} else sol\n// }\n// }\n\n// println(minIndex(rlist, lllist))\n//\n// println(list)\n// println(rlist)\n// println(lllist)\n//\n// println(rev)\n//\n }\n}"}, {"source_code": "\nobject One60A extends App {\n\timport java.io.{ PrintWriter => Out }\n\timport java.util.{ Scanner => In }\n\timport scala.util.control.Breaks._\n\n\tval in = new In(System.in)\n\tval out = new Out(System.out)\n\tval n = in.nextInt()\n\tvar arr = new Array[Int](n)\n\tvar left = 0\n\tvar has = 0\n\n\t(0 until n).foreach { i =>\n\t\tarr(i) = in.nextInt()\n\t\tleft += arr(i)\n\t}\n\tarr = arr.sortWith(_ > _)\n\n\tvar buff = arr.takeWhile { x =>\n\t\thas += x\n\t\tleft -= x\n\t\thas <= left\n\t}\n\tout.println(buff.size + 1)\n\tout.close\n}"}, {"source_code": "object Twins {\n def main(args: Array[String]): Unit = {\n readInt()\n val nums = readLine().split(\" \").map(_.toInt).sorted\n var sum: Long = nums.sum\n var mySum: Long = 0\n var coinsCount = 0\n for (i <- nums.reverse) {\n if (mySum <= sum) coinsCount += 1\n mySum += i\n sum -= i\n }\n println(coinsCount)\n }\n}"}, {"source_code": "object CF0160A extends App {\n\n\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt).toList.sorted.reverse\n\n var sum = a.sum\n\n\n var minSum = 0\n var min = 0\n\n a.foreach(n => {\n if (minSum <= sum) {\n minSum += n\n sum -= n\n min += 1\n }\n })\n println(min)\n\n}\n"}, {"source_code": "import scala.io.StdIn\nimport scala.util.Sorting\n\nobject Task {\n\n def main(args: Array[String]): Unit = {\n\n val n: Int = StdIn.readInt()\n var a: Array[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n println(solve(a))\n\n }\n\n private def solve(a: Array[Int]): Int = {\n Sorting.quickSort(a)\n var sum: Int = 0\n for (x <- a) {\n sum += x\n }\n var sol: Int = 0\n var currSum: Int = 0\n for (i <- a.length - 1 to 0 by -1) {\n sol += 1\n currSum += a(i)\n if (currSum > sum / 2) {\n return sol\n }\n }\n return -1\n }\n\n}\n"}, {"source_code": "object Solution160A extends App {\n\n def solution() {\n val n = _int\n val coins = 1.to(n).map(_ => _int).sortBy(-_)\n val sum = coins.foldLeft(0)((s, c) => s + c)\n val result = coins.foldLeft((0, 0))((memo, c) => memo._1 match {\n case l if l <= (sum - l) => (memo._1 + c, memo._2 + 1)\n case _ => memo\n })\n println(result._2)\n }\n\n //////////////////////////////////////////////////\n import java.util.Scanner\n val SC: Scanner = new Scanner(System.in)\n def _line: String = SC.nextLine\n def _int: Int = SC.nextInt\n def _long: Long = SC.nextLong\n def _string: String = SC.next\n solution()\n}"}, {"source_code": "object Competition extends App {\n\n import scala.io.StdIn._\n\n val k: Int = readInt()\n\n val coins: Seq[Int] = readLine().split(\" \").map(Integer.parseInt).toSeq.sorted.reverse\n val amount: Int = coins.sum / 2\n\n def sumUp(half: Int, sum: Int, num: Int, coinsLeft: Seq[Int]): Int = {\n if (sum > half) num\n else sumUp(half, sum + coinsLeft.head, num + 1, coinsLeft.tail)\n }\n\n println(sumUp(amount, 0, 0, coins))\n}"}, {"source_code": "import scala.collection.mutable._\nimport scala.math._\nimport scala.util._\nimport scala.util.control.Breaks.break\nimport scala.util.control.Breaks.breakable\nimport java.util._\nobject Main extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt\n val tt = for(i <- 1 to n) yield sc.nextInt\n val t = Sorting.stableSort(tt).reverse\n val sum = t.foldLeft(0){_+_}\n var tmp = 0\n var res = -1\n for(i <- 0 until n) {\n tmp += t(i)\n if(res == -1 && tmp > (sum-tmp)) res = i+1\n }\n println(res)\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Twins_160 {\n def main(args: Array[String]): Unit = {\n val numOfCoins = StdIn.readInt()\n val coins = StdIn.readLine().split(\" \").map(_.toInt)\n\n val coinsSorted = coins.sorted\n println(getMinCoins(0, coins.sum, coins.sorted(Ordering[Int].reverse), 0))\n }\n\n def getMinCoins(mySum: Int, twinSum: Int, coins: Array[Int], numOfCoins: Int): Int = {\n if (mySum > twinSum) return numOfCoins\n getMinCoins(mySum + coins.head, twinSum - coins.head, coins.tail, numOfCoins + 1)\n }\n\n}"}, {"source_code": "import scala.io.StdIn.readLine\n\n/**\n * @author traff\n */\n\n\nobject Main extends App {\n val n = readLine().toInt\n\n val a = readLine().split(\"\\\\s+\").map(_.toInt).sortWith(_ > _)\n\n val sum = a.sum\n\n println(a.scanLeft(0)(_ + _).takeWhile(c => c <= sum - c).length)\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\n/**\n * @author traff\n */\n\n\nobject Main extends App {\n val n = readLine().toInt\n\n val a = readLine().split(\"\\\\s+\").map(_.toInt).sortWith(_ > _)\n\n val sum = a.sum\n\n var i = 0\n var s1 = 0\n while (i= count + a(i)) {\n count = count + a(i)\n i += 1\n }\n println(i + 1)\n}"}, {"source_code": "object Main {\n\n def main(args: Array[String]) {\n val std = scala.io.StdIn\n\n val n = std.readLine().toInt\n val values = std.readLine().split(' ').map(_.toInt)\n\n val halfSum = values.sum / 2\n val result = values.sorted.foldRight((0,0))((y,x) => if (x._2 <= halfSum) (x._1 + 1, x._2 + y) else x)\n print(result._1)\n\n }\n}"}, {"source_code": "/**\n * Created by richard on 2015/6/9.\n */\nimport scala.io.StdIn\nobject cf160a {\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n val c = StdIn.readLine().split(\" \").map(_.toInt).toSeq.sortWith(_>_)\n var sum = c.sum\n var msum = 0\n println(c.takeWhile( i=>{sum-=i; msum+=i; msum-i<=sum+i}).length)\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P160A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n\n\n\n def solve: Int = {\n val coins = List.fill(N)(sc.nextInt)\n val half = coins.sum / 2\n\n @tailrec\n def loop(acc: Int, cs: List[Int], num: Int): Int =\n if (acc > half) num\n else loop(acc + cs.head, cs.tail, num + 1)\n loop(0, coins.sortBy(identity[Int]).reverse, 0)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "\n\nobject Twins {\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in)\n\t\t\t\tval _ = scanner.nextLine\n\t\t\t\tval input = scanner.nextLine\n\t\t\t\tvar sequence = input.split(\" \").map(s => s.toInt)\n\t\t\t\tsequence = sequence.sortWith(_ > _)\n\t\t\t\tval sum = sequence.foldLeft(0){\n\t\t\t(acc, num) => acc + num\n\t\t}\n\t\tvar tmpSum = 0\n\t\t\t\tvar number = 0\n\t\t\t\twhile (tmpSum <= sum / 2) {\n\t\t\t\t\tval elt = sequence(number)\n\t\t\t\t\t\t\tnumber += 1\n\t\t\t\t\t\t\ttmpSum += elt\n\t\t\t\t}\n\t\tprintln(number)\n\t}\n}\n"}, {"source_code": "object Codeforces160A extends App{\n \n def DivideCoins(coinnumber:Int):Int={\n var coinarray:Array[Int]=scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n coinarray=coinarray.sorted\n for (i <- 0 until coinnumber){\n val (tempa,tempb)=coinarray.splitAt(coinnumber-i-1)\n if (tempa.sum < tempb.sum) return i+1\n }\n return coinnumber\n }\n val numberofcoin:Int=scala.io.StdIn.readInt\n println(DivideCoins(numberofcoin))\n\n}\n"}, {"source_code": "import java.io._\n\nobject Main {\n\n def main(args: Array[String]) {\n val n = readInt\n val list = (for(i <- 0 until n) yield readInt).sortWith(_ > _)\n val sum = (0 /: list)(_ + _)\n def getCnt(i: Int, amount: Int) : Int = if(amount < 0) i else getCnt(i + 1, amount - list(i))\n println(getCnt(0, sum / 2))\n }\n\n val in = new StreamTokenizer(new InputStreamReader(System.in))\n\n def readInt = {\n in.nextToken()\n in.nval.asInstanceOf[Int]\n }\n}"}, {"source_code": "object Main {\n import java.io.{InputStreamReader, StreamTokenizer}\n\n def main(args: Array[String]) {\n val n = readInt\n val list = (for(i <- 0 until n) yield readInt).sortWith(_ > _)\n val sum = (0 /: list)(_ + _)\n def getCnt(i: Int, amount: Int) : Int = if(amount < 0) i else getCnt(i + 1, amount - list(i))\n println(getCnt(0, sum / 2))\n }\n\n val in = new StreamTokenizer(new InputStreamReader(System.in))\n\n def readInt = {\n in.nextToken()\n in.nval.asInstanceOf[Int]\n }\n}"}, {"source_code": "object A extends App {\n val n = readLine\n val c = readLine.split(\" \").map(_.toInt).toSeq.sortWith(_>_)\n var sum = c.sum\n var tsum = 0\n println (c.takeWhile( i => { sum -= i; tsum += i; tsum-i <= sum+i }).length)\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt\n val a = readLine().split(\" \").map(_.toInt)\n val sum = a.sum / 2\n val sorted = a.sortWith(_ > _)\n val res = sorted.foldLeft((0, 0)) { (t, e) => \n if (t._1 > sum) t\n else (t._1 + e, t._2 + 1)\n }\n println(res._2)\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject _160_A extends App {\n readInt()\n val coins = readLine().split(\" \").map(_.toInt).sortWith(_ > _)\n\n var rest = coins.sum\n var current = 0\n var i = 0\n\n while (current <= rest) {\n current += coins(i)\n rest -= coins(i)\n i+=1\n }\n\n println(i)\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nobject problem {\n def main(args: Array[String]) {\n val n = readLine.toInt\n val A = readLine.split(' ').map(_.toInt).sortWith(_ > _)\n var s = A.sum\n var t = 0\n var cnt = 0\n while(s >= t){\n s = s - A(cnt)\n t = t + A(cnt)\n cnt = cnt + 1\n }\n println(cnt)\n }\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport scala.util.control.Breaks._\n\nimport sun.swing.SwingUtilities2.RepaintListener\n\nobject Main {\n def main(args: Array[String]): Unit = {\n\n val s = new Scanner(System.in)\n val a = s.nextInt()\n val numbers: Array[Int] = Array.fill(a) {\n 0\n }\n for (i <- 0 until a){\n numbers(i) = s.nextInt()\n }\n\n val list = numbers.toList.sorted\n\n val rev = list.reverse\n\n val llist = list.scanLeft(0)(_+_)\n\n val lllist = llist.reverse\n\n val rlist = rev.scanLeft(0)(_+_)\n\n//\n val uno = lllist.zip(rlist).filter{case (l,r) => l <= r}\n println(uno.length)\n\n\n }\n}"}, {"source_code": "import java.util.Scanner\nimport scala.util.control.Breaks._\n\nimport sun.swing.SwingUtilities2.RepaintListener\n\nobject Main {\n def main(args: Array[String]): Unit = {\n\n val s = new Scanner(System.in)\n val a = s.nextInt()\n val numbers: Array[Int] = Array.fill(a) {\n 0\n }\n for (i <- 0 until a){\n numbers(i) = s.nextInt()\n }\n\n val list = numbers.toList.sorted\n\n val rev = list.reverse\n\n val llist = list.scanLeft(0)(_+_)\n\n val lllist = llist.reverse\n\n val rlist = rev.scanLeft(0)(_+_)\n\n val uno = lllist.zip(rlist).filter{case (l,r) => l <= r}\n println(uno)\n\n\n\n }\n}"}, {"source_code": "object One60A extends App {\n import java.io.{ PrintWriter => Out }\n import java.util.{ Scanner => In }\n import scala.util.control.Breaks._\n\n\tval in = new In(System.in)\n\tval out = new Out(System.out)\n\tval n = in.nextInt()\n\tvar arr = new Array[Int](n)\n\tvar left = 0\n\tvar has = 0\n\n\t(0 until n).foreach { i =>\n\t\tarr(i) = in.nextInt()\n\t\tleft += arr(i)\n\t}\n\tarr = arr.sortWith(_ > _)\n\n\tvar buff = arr.takeWhile { x =>\n\t\thas += x\n\t\tleft -= x\n\t\thas < left\n\t}\n\tout.println(buff.size + 1)\n\tout.close\n}"}, {"source_code": "\nobject One60A extends App {\n import java.io.{ PrintWriter => Out }\n import java.util.{ Scanner => In }\n import scala.util.control.Breaks._\n\n\tval in = new In(System.in)\n\tval out = new Out(System.out)\n\tval n = in.nextInt()\n\tvar arr = new Array[Int](n)\n\tvar left = 0\n\tvar has = 0\n\n\t(0 until n).foreach { i =>\n\t\tarr(i) = in.nextInt()\n\t\tleft += arr(i)\n\t}\n\tarr = arr.sortWith(_ > _)\n\n\tvar buff = arr.takeWhile { x =>\n\t\thas += x\n\t\thas < left\n\t}\n\tout.println(buff.size + 1)\n\tout.close\n}"}, {"source_code": "object CF0160A extends App {\n\n\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt).toList.sorted\n\n var sum = a.sum\n\n\n var minSum = 0\n var min = 0\n\n a.foreach(n => {\n if (minSum <= sum) {\n minSum += n\n sum -= n\n min += 1\n }\n })\n println(min)\n\n}\n"}, {"source_code": "//package round111.div2\n\n/**\n * Created by IntelliJ IDEA.\n * User: User\n * Date: 08.03.12\n * Time: 6:11\n * To change this template use File | Settings | File Templates.\n */\n\nobject A {\n readLine()\n val a = readLine() split ' ' map (_ toInt) sorted\n var s = -a.sum / 2\n val b = for (coin <- a.iterator takeWhile (_ => s <= 0)) yield {\n s += coin\n coin\n }\n\n def main(args: Array[String]) = println(b.size)\n\n\n}\n"}, {"source_code": "object Solution extends App{\n val in = scala.io.Source.stdin.getLines()\n in.next()\n val a = in.next().split(\" \").map(_.toInt).sorted.reverse\n val sum = a.sum\n var i = 0\n var count = 0\n while (i < a.size && count + a(i) > a.sum / 2) i += 1\n println(i)\n}"}, {"source_code": "object Solution extends App{\n val in = scala.io.Source.stdin.getLines()\n in.next()\n val a = in.next().split(\" \").map(_.toInt).sorted.reverse\n val sum = a.sum\n var i = 0\n var count = 0\n while (i < a.length && count + a(i) <= sum / 2) i += 1\n println(i)\n}"}, {"source_code": "/**\n * Created by richard on 2015/6/9.\n */\nimport scala.io.StdIn\nobject cf160a {\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n val c = StdIn.readLine().split(\" \").map(_.toInt).sortWith(_>_)\n var sum = c.sum\n var msum = 0\n println(c.takeWhile( i=>{sum-=i; msum+=i; msum-i _)\n val sum = (0 /: list)(_ + _)\n def getCnt(i: Int, amount: Int) : Int = if(amount < 0) i else getCnt(i + 1, amount - list(i))\n println(getCnt(0, sum / 2))\n }\n\n val in = new StreamTokenizer(new InputStreamReader(System.in))\n\n def readInt = {\n in.nextToken()\n in.nval.asInstanceOf[Int]\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject _160_A extends App {\n readInt()\n val coins = readLine().split(\" \").map(_.toInt).sortWith(_ > _)\n println(coins.mkString(\" \"))\n\n var rest = coins.sum\n var current = 0\n var i = 0\n\n while (current <= rest) {\n current += coins(i)\n rest -= coins(i)\n i+=1\n }\n\n println(i)\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.io.StdIn._\nimport scala.util.Sorting\n\n\nobject HelloWorldMain {\n\n def main(args: Array[String]): Unit = {\n\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n\n var list = new Array[Int](n)\n\n var sum = 0\n for(i <- 0 until n ) {\n list(i) = sc.nextInt()\n sum += list(i)\n }\n\n\n Sorting.quickSort(list)\n\n\n var takenAmount = 0\n var iterator = n-1\n var totalnumberOfCoins = 0\n while (takenAmount <= sum/2 ){\n takenAmount += list(iterator)\n totalnumberOfCoins += 1\n }\n\n println(totalnumberOfCoins)\n\n }\n}\n\n\n\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject Twins {\n \n def main(args: Array[String]) { \n val n = readInt\n val coins = readLine.split(' ').map(_.toInt).sorted\n val toTake = coins.sum/2 + 1\n println(coins.scanLeft(0)(_ + _)\n .zipWithIndex.find{ case (s,i) => s >= toTake}.getOrElse( (0,0))._2)\n }\n \n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Task extends App{\n\tval N = readLine.split(\" \").map{_.toInt}.head\n\tval coins = readLine.split(\" \").map{_.toInt}.sorted\n\t\n\tval leftSums = coins.scanLeft(0)((a,b) => a + b).tail\n\tval rightSums = coins.scanRight(0)((a,b) => a + b).tail\n\t\n\t//println(leftSums.mkString)\n\t//println(rightSums.mkString)\n\t\n\tval a = leftSums.zip(rightSums).filter{case (l,r) => l <= r}\n\t//println(a.mkString)\n\t\n\tprintln(a.size + 1)\n}"}], "src_uid": "ee535e202b7662dbaa91e869c8c6cee1"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n var Array(x1, y1, x2, y2) = in.next().split(\" \").map(_.toInt)\n if (x2 < x1 || (x2 == x2 && y2 < y1)) {\n val tmp = x2\n x2 = x1\n x1 = tmp\n val tmp2 = y2\n y2 = y1\n y1 = tmp2\n }\n\n\n val width = Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2))\n if (Math.abs(x1 - x2) != 0 && Math.abs(y1 - y2) != 0 && Math.abs(x1 - x2) != Math.abs(y1 - y2))\n println(-1)\n else if (x1 == x2)\n println(List(x1 + width, y1, x2 + width, y2).mkString(\" \"))\n else if (y1 == y2)\n println(List(x1, y1 + width, x2, y2 + width).mkString(\" \"))\n else\n println(List(x1, y2, x2, y1).mkString(\" \"))\n}\n", "positive_code": [{"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 15.08.14.\n */\nobject A extends App {\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val x1 = nextInt\n val y1 = nextInt\n val x2 = nextInt\n val y2 = nextInt\n if(x1 == x2) {\n val x3 = x1 + math.abs(y2 - y1)\n out.print(Array(x3, y1, x3, y2).mkString(\" \"))\n } else if(y1 == y2) {\n val y3 = y1 + math.abs(x2 - x1)\n out.print(Array(x1, y3, x2, y3).mkString(\" \"))\n } else {\n val x = math.abs(x2 - x1)\n val y = math.abs(y2 - y1)\n if(x != y) {\n out.print(-1)\n } else {\n if((x2 - x1) * (y2 - y1) > 0) {\n out.print(Array(math.min(x1, x2), math.max(y1, y2), math.max(x1, x2), math.min(y1, y2)).mkString(\" \"))\n } else {\n out.print(Array(math.min(x1, x2), math.min(y1, y2), math.max(x1, x2), math.max(y1, y2)).mkString(\" \"))\n }\n }\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _459A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val x1 = next.toInt\n val y1 = next.toInt\n val x2 = next.toInt\n val y2 = next.toInt\n if (x1 == x2) {\n val len = (y1 - y2).abs\n println(\"%d %d %d %d\".format(x1 - len, y1, x1 - len, y2))\n } else if (y1 == y2) {\n val len = (x1 - x2).abs\n println(\"%d %d %d %d\".format(x1, y1 - len, x2, y1 - len));\n } else {\n if ((x1 - x2).abs != (y1 - y2).abs) println(-1)\n else {\n val len = (x1 - x2).abs\n println(\"%d %d %d %d\".format(x1, y2, x2, y1));\n }\n }\n}\n"}, {"source_code": "/**\n * Created by lurker on 2014. 8. 15..\n */\nobject CF261_1 extends App {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n val Array(x1, y1, x2, y2) = readInts(4)\n\n val minx = x1 min x2\n val maxx = x1 max x2\n val miny = y1 min y2\n val maxy = y1 max y2\n\n\n if (minx == maxx) {\n val dist = maxy - miny\n val Array(x3, y3, x4, y4) = Array(minx + dist, miny, minx + dist, maxy)\n println(s\"${x3} ${y3} ${x4} ${y4}\")\n } else if (miny == maxy) {\n val dist = maxx - minx\n val Array(x3, y3, x4, y4) = Array(minx, miny + dist, maxx, miny + dist)\n println(s\"${x3} ${y3} ${x4} ${y4}\")\n } else {\n if (maxx - minx != maxy - miny) {\n println(\"-1\")\n } else {\n val Array(x3, y3, x4, y4) = Array(x1, y2, x2, y1)\n println(s\"${x3} ${y3} ${x4} ${y4}\")\n }\n }\n}\n"}, {"source_code": "object A459 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(x1, y1, x2, y2) = readInts(4)\n if(x1 == x2) {\n if(y1 != y2) {\n println(s\"${x1 + math.abs(y2 - y1)} $y2 ${x1 + math.abs(y2 - y1)} $y1\")\n } else {\n println(\"-1\")\n }\n } else if(y1 == y2) {\n if(x1 != x2) {\n println(s\"$x2 ${y1 + math.abs(x2 - x1)} $x1 ${y1 + math.abs(x2 - x1)}\")\n } else {\n println(\"-1\")\n }\n } else {\n if(math.abs(x1-x2) == math.abs(y1-y2)) {\n println(s\"$x1 $y2 $x2 $y1\")\n } else {\n println(\"-1\")\n }\n }\n }\n}"}, {"source_code": "import java.util._\nimport java.io._\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val x1 = nextInt\n val y1 = nextInt\n val x2 = nextInt\n val y2 = nextInt\n if (x1 != x2 && y1 != y2) {\n if (Math.abs(x1 - x2) != Math.abs(y1 - y2)) {\n out.println(-1)\n } else {\n out.print(x1 + \" \" + y2 + \" \" + x2 + \" \" + y1)\n }\n } else if (x1 == x2) {\n val d = Math.abs(y1 - y2)\n out.print((x1 + d) + \" \" + y1 + \" \" + (x1 + d) + \" \" + y2)\n } else if (y1 == y2) {\n val d = Math.abs(x1 - x2)\n out.print(x1 + \" \" + (y1 + d) + \" \" + x2 + \" \" + (y1 + d))\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-19.\n */\nobject A459 extends App{\n val sc = new Scanner(System.in)\n val x1, y1, x2, y2 = sc.nextInt()\n\n if (x1 == x2) {\n println((x1 + math.abs(y2 - y1)) + \" \" + y1 + \" \" + (x1 + math.abs(y2 - y1)) + \" \" + y2)\n } else if (y1 == y2){\n println(x1 + \" \" + (y1 + math.abs(x2 - x1)) + \" \" + x2 + \" \" + (y1 + math.abs(x2 - x1)))\n } else if (math.abs((x2 - x1) / (y2 - y1).toDouble) == 1) {\n println(x1 + \" \" + y2 + \" \" + x2 + \" \" + y1)\n } else {\n println(-1)\n }\n}\n"}, {"source_code": "object Main {\n\n def main(args: Array[String]): Unit = {\n println(findCoords(io.StdIn.readLine().split(' ').map(x => Integer.parseInt(x))))\n }\n\n def findCoords(points: Array[Int]): String = {\n if (points(0) == points(2)) {\n val side = points(3) - points(1)\n List(points(0) + side, points(1), points(2) + side, points(3)).mkString(\" \")\n }\n else if (points(1) == points(3)) {\n val side = points(2) - points(0)\n List(points(0), points(1) + side, points(2), points(3) + side).mkString(\" \")\n }\n else {\n val h = points(2) - points(0)\n val v = points(3) - points(1)\n if (Math.abs(h) - Math.abs(v) != 0) {\n return -1 + \"\"\n } else {\n List(points(0) + h, points(1), points(0), points(1) + v).mkString(\" \")\n }\n }\n }\n\n}\n"}, {"source_code": "object main extends App with fastIO {\n \n case class Point(x: Int, y: Int) \n \n var p1 = Point(nextInt, nextInt)\n var p2 = Point(nextInt, nextInt)\n var length = (p1.x - p2.x + p1.y - p2.y).abs\n \n var p3 = Point(0, 0)\n var p4 = Point(0, 0)\n \n var f = true\n if ((p1.x - p2.x).abs == (p1.y - p2.y).abs) { p3 = Point(p1.x, p2.y); p4 = Point(p2.x, p1.y) }\n else if (p1.x == p2.x) { p3 = Point(p1.x + length, p1.y); p4 = Point(p1.x + length, p2.y) } \n else if (p1.y == p2.y) { p3 = Point(p1.x, p1.y + length); p4 = Point(p2.x, p1.y + length) }\n else f = false\n \n if (!f) println(-1) else \n println(\"%d %d %d %d\" format (p3.x, p3.y, p4.x, p4.y)) \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}"}], "negative_code": [{"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 15.08.14.\n */\nobject A extends App {\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val x1 = nextInt\n val y1 = nextInt\n val x2 = nextInt\n val y2 = nextInt\n if(x1 == x2) {\n val x3 = x1 + math.abs(y2 - y1)\n out.print(Array(x3, y1, x3, y2).mkString(\" \"))\n } else if(y1 == y2) {\n val y3 = y1 + math.abs(x2 - x1)\n out.print(Array(x1, y3, x2, y3).mkString(\" \"))\n } else {\n val x = math.abs(x2 - x1)\n val y = math.abs(y2 - y1)\n if(x != y) {\n out.print(-1)\n } else {\n out.print(Array(math.min(x1, x2), math.max(y1, y2), math.max(x1, x2), math.min(y1, y2)).mkString(\" \"))\n }\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}"}, {"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 15.08.14.\n */\nobject A extends App {\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val x1 = nextInt\n val y1 = nextInt\n val x2 = nextInt\n val y2 = nextInt\n if(x1 == x2) {\n val x3 = x1 + math.abs(y2 - y1)\n out.print(Array(x3, y1, x3, y2).mkString(\" \"))\n } else if(y1 == y2) {\n val y3 = y1 + math.abs(y2 - y1)\n out.print(Array(x1, y3, x2, y3).mkString(\" \"))\n } else {\n val x = math.abs(x2 - x1)\n val y = math.abs(y2 - y1)\n if(x != y) {\n out.print(-1)\n } else {\n out.print(Array(math.min(x1, x2), math.max(y1, y2), math.max(x1, x2), math.min(y1, y2)).mkString(\" \"))\n }\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n var Array(x1, y1, x2, y2) = in.next().split(\" \").map(_.toInt)\n if (x2 < x1 || (x2 == x2 && y2 < y1)) {\n val tmp = x2\n x2 = x1\n x1 = tmp\n val tmp2 = y2\n y2 = y1\n y1 = tmp2\n }\n\n\n val width = Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2))\n if (Math.abs(x1 - x2) != 0 && Math.abs(y1 - y2) != 0 && Math.abs(x1 - x2) != Math.abs(y1 - y2))\n println(-1)\n else if (y2 < y1)\n println(List(x1, y2, x2, y1).mkString(\" \"))\n else if (x1 == x2)\n println(List(x1 + width, y1, x2 + width, y2).mkString(\" \"))\n else if (y1 == y2)\n println(List(x1, y1 + width, x2, y2 + width).mkString(\" \"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val data = in.next().split(\" \").map(_.toInt)\n if (data.distinct.length != 2) println(-1)\n else {\n val min = data.min\n val max = data.max\n val s = Set((min, max), (max, min), (min, min), (max, max)) -- Set((data(0), data(1)), (data(2), data(3)))\n println(s.toList.flatMap(t => List(t._1, t._2)).mkString(\" \"))\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val data = in.next().split(\" \").map(_.toInt)\n if (data.distinct.length != 2) println(-1)\n else {\n val min = data.min\n val max = data.max\n val s = Set((min, max), (max, min), (min, min), (max, max)) -- Set((data(0), data(1)), (data(2), data(3))) \n println(s.flatMap(t => List(t._1, t._2)).mkString(\" \"))\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n var Array(x1, y1, x2, y2) = in.next().split(\" \").map(_.toInt)\n if (x2 < x1 || (x2 == x2 && y2 < y1)) {\n val tmp = x2\n x2 = x1\n x1 = tmp\n val tmp2 = y2\n y2 = y1\n y1 = tmp2\n }\n\n\n val width = Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2))\n if (Math.abs(x1 - x2) != 0 && Math.abs(y1 - y2) != 0 && Math.abs(x1 - x2) != Math.abs(y1 - y2))\n println(-1)\n if (x1 == x2)\n println(List(x1 + width, y1, x2 + width, y2).mkString(\" \"))\n else if (y1 == y2)\n println(List(x1, y1 + width, x2, y2 + width).mkString(\" \"))\n else\n println(List(x1, y2, x2, y1).mkString(\" \"))\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-19.\n */\nobject A459 extends App{\n val sc = new Scanner(System.in)\n val x1, y1, x2, y2 = sc.nextInt()\n\n if (x1 == x2) {\n println((x1 + math.abs(y2 - y1)) + \" \" + y1 + \" \" + (x1 + math.abs(y2 - y1)) + \" \" + y2)\n } else if (y1 == y2){\n println(x1 + \" \" + (y1 + math.abs(x2 - x1)) + \" \" + x2 + \" \" + (y1 + math.abs(x2 - x1)))\n } else if ((x2 - x1) / (y2 - y1).toDouble == 1) {\n println(x1 + \" \" + y2 + \" \" + x2 + \" \" + y1)\n } else {\n println(-1)\n }\n}\n"}], "src_uid": "71dea31e1244797f916adf5f526f776e"} {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val teams = Array.ofDim[Team](n - 1)\n\n val Array(_t0, w0) = readLongs(2)\n var t0 = _t0\n\n case class Team(t: Long, w: Long)\n\n for (i <- 0 until n - 1) {\n val Array(t, w) = readLongs(2)\n teams(i) = Team(t, w)\n }\n\n val above = mutable.PriorityQueue.empty[Team](Ordering.by(t => - (t.w - t.t)))\n val below = mutable.PriorityQueue.empty[Team](Ordering.by(_.t))\n\n for (t <- teams) if (t.t > t0) above += t\n else below += t\n\n var minPlace = above.size + 1\n var can = true\n\n while (can && !above.isEmpty) {\n val target = above.dequeue()\n if (target.w - target.t < t0) {\n t0 -= target.w - target.t + 1\n while (below.nonEmpty && below.head.t > t0) {\n above += below.dequeue()\n }\n minPlace = Math.min(minPlace, above.size + 1)\n } else can = false\n }\n\n println(minPlace)\n}\n", "positive_code": [{"source_code": "object CF{\n\timport scala.io.StdIn.{readInt, readLine}\n\timport scala.collection.mutable.PriorityQueue\n\timport math.{max, min}\n\n\tdef main(args: Array[String]){\n\t\tval n = readInt()\n\n\t\tval datasq = PriorityQueue.empty[(Long, Long)](Ordering.by((_:(Long, Long))._1))\n\t\tvar (mdatat, mdataw) = {\n\t\t\tval line = readLine().split(\" \").map(_.toLong)\n\t\t\t(line(0), line(1))\n\t\t}\n\t\tfor(_ <- 1 to n-1) datasq += {\n\t\t\tval line = readLine().split(\" \").map(_.toLong)\n\t\t\t(line(0), line(1))\n\t\t}\n\n\t\tval queue = PriorityQueue.empty[Long](Ordering.by((x:Long) => x).reverse)\n\t\tmakeQueue(queue, datasq, mdatat)\n\t\tval cur = queue.length + 1\n\t\tvar best = cur\n\n\t\twhile(!queue.isEmpty && mdatat >= 0){\n\t\t\tval head = queue.dequeue()\n\t\t\tmdatat -= head\n\n\t\t\tif(mdatat >= 0){\n\t\t\t\twhile(!datasq.isEmpty && datasq.head._1 > mdatat){\n\t\t\t\t\tval head = datasq.dequeue()\n\t\t\t\t\tqueue += head._2 - head._1 + 1\n\t\t\t\t}\n\t\t\t\tbest = min(best, queue.length + 1)\n\t\t\t}\n\t\t}\n\t\tprintln(best)\n\t}\n\n\tdef makeQueue(q: PriorityQueue[Long], datasq:PriorityQueue[(Long, Long)], mdatat: Long){\n\t\tif(datasq.isEmpty) return\n\t\tif(datasq.head._1 > mdatat){\n\t\t\tval head = datasq.dequeue()\n\t\t\tq += head._2 - head._1 + 1\n\t\t\tmakeQueue(q, datasq, mdatat)\n\t\t}\n\t}\n}"}], "negative_code": [{"source_code": "object CF{\n\timport scala.io.StdIn.{readInt, readLine}\n\timport scala.collection.mutable.PriorityQueue\n\n\tdef main(args: Array[String]){\n\t\tval n = readInt()\n\t\tval datasq = PriorityQueue.empty[Node](Ordering.by((_:Node).t))\n\t\tval mdata = {\n\t\t\tval line = readLine().split(\" \").map(_.toLong)\n\t\t\tnew Node(line(0), line(1))\n\t\t}\n\t\tfor(_ <- 1 to n-1) datasq += {\n\t\t\tval line = readLine().split(\" \").map(_.toLong)\n\t\t\tnew Node(line(0), line(1))\n\t\t}\n\t\tval datas = pq2list(datasq)\n\t\tval queue = PriorityQueue.empty[Node](Ordering.by((_:Node).h).reverse)\n\t\tvar i = 0\n\t\twhile(i mdata.t){\n\t\t\tqueue += datas(i)\n\t\t\ti += 1\n\t\t}\n\n\t\tvar best = queue.length+1\n\t\tvar now = best\n\t\tvar cur = best\n\n\t\twhile(!queue.isEmpty && mdata.t>=0){\n\t\t\tval head = queue.dequeue()\n\t\t\tmdata.t -= head.h\n\t\t\tif(mdata.t >= 0){\n\t\t\t\tnow -= 1\n\t\t\t\tvar i = cur\n\t\t\t\twhile(i mdata.t){\n\t\t\t\t\tqueue += datas(i)\n\t\t\t\t\tnow += 1\n\t\t\t\t\tcur += 1\n\t\t\t\t\ti += 1\n\t\t\t\t}\n\t\t\t\tif(now mdata.t){\n\t\t\tqueue += datas(i)\n\t\t\ti += 1\n\t\t}\n\n\t\tvar best = queue.length+1\n\t\tvar now = best\n\t\tvar cur = best\n\n\t\twhile(!queue.isEmpty && mdata.t>=0){\n\t\t\tval head = queue.dequeue()\n\t\t\tnow -= 1\n\t\t\tmdata.t -= head.h\n\t\t\tif(mdata.t >= 0){\n\t\t\t\twhile(cur mdata.t){\n\t\t\t\t\tqueue += datas(i)\n\t\t\t\t\tnow += 1\n\t\t\t\t\tcur += 1\n\t\t\t\t}\n\t\t\t\tif(now= 0){\n\t\t\tval head = queue.dequeue()\n\t\t\tmdata.t -= head.h\n\n\t\t\tif(mdata.t >= 0){\n\t\t\t\twhile(!datasq.isEmpty && datasq.head.t > mdata.t){\n\t\t\t\t\tqueue += datasq.dequeue()\n\t\t\t\t}\n\t\t\t\tbest = max(best, queue.length + 1)\n\t\t\t}\n\t\t}\n\t\tprintln(best)\n\t}\n\n\tdef makeQueue(q: PriorityQueue[Node], datasq:PriorityQueue[Node], mdata: Node):Long = {\n\t\tif(datasq.isEmpty) return 0\n\t\tif(datasq.head.t > mdata.t) {\n\t\t\tq += datasq.dequeue()\n\t\t\treturn 1 + makeQueue(q, datasq, mdata)\n\t\t}\n\t\treturn 0\n\t}\n\n\tclass Node(var t:Long, val w:Long){\n\t\tval h:Long = w-t+1\n\t}\n}"}], "src_uid": "3fb43df3a6f763f196aa514f305473e2"} {"source_code": "\nimport scala.collection.mutable.Map\nobject C extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n \n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val _ = in.nextInt()\n val intInputs = in.line().split(\"\").map(x => x.toInt - 1)\n\n val map1: Map[Int, Int] = Map.empty[Int, Int]\n// val map1: Map[Int, Int] = Map((0, 1))\n\n val targetSum = 0\n var result: Long = 0L\n var cumSum = 0\n intInputs.foreach(x => {\n /*cumSum += x\n result += map1.getOrElse(cumSum - targetSum, 0)\n map1.put(cumSum, map1.getOrElse(cumSum, 0) + 1)\n */\n\n cumSum += x\n if (cumSum == targetSum) result += 1\n val rest = cumSum - targetSum\n result += map1.getOrElse(rest, 0)\n\n map1.put(cumSum, map1.getOrElse(cumSum, 0) + 1)\n })\n println(result)\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n", "positive_code": [{"source_code": "object C extends App {\n import scala.io.StdIn._\n import scala.collection.immutable.HashMap\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\"\").map(_.toInt)\n\n val ans = an\n .map(_ - 1)\n .foldLeft((0L, 0L, HashMap(0L -> 1))) { // prefix_sum(0) = 0 --> counts(0) = 1\n case ((answer, prefix, counts), a) =>\n val key = prefix + a\n val add = counts.getOrElse(key, 0) // \n\n (answer + add, key, counts + (key -> (add + 1)))\n }\n ._1\n\n println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "object C extends App {\n import scala.io.StdIn._\n import scala.collection.immutable.HashMap\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\"\").map(_.toInt)\n\n val ans = an\n .map(_ - 1)\n .foldLeft((0, 0, HashMap(0 -> 1))) { // prefix_sum(0) = 0 --> counts(0) = 1\n case ((answer, prefix, counts), a) =>\n val key = prefix + a\n val add = counts.getOrElse(key, 0) // \n\n (answer + add, key, counts + (key -> (add + 1)))\n }\n ._1\n\n println(ans)\n }\n}\n"}, {"source_code": "object C extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\"\").map(_.toInt)\n\n @annotation.tailrec\n def go(iter: Int, count: Int): Int =\n if (iter > n || iter > 9) count\n else go(iter + 1, count + an.sliding(iter).count(_.sum == iter))\n\n val ans = go(1, 0)\n\n println(ans)\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable.Map\nobject C extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val _ = in.nextInt()\n val intInputs = in.line().split(\"\").map(x => x.toInt - 1)\n\n val map1: Map[Int, Int] = Map.empty[Int, Int]\n// val map1: Map[Int, Int] = Map((0, 1))\n\n val targetSum = 0\n var result = 0\n var cumSum = 0\n intInputs.foreach(x => {\n /*cumSum += x\n result += map1.getOrElse(cumSum - targetSum, 0)\n map1.put(cumSum, map1.getOrElse(cumSum, 0) + 1)\n */\n\n cumSum += x\n if(cumSum == targetSum) result += 1\n val rest = cumSum - targetSum\n result += map1.getOrElse(rest, 0)\n\n map1.put(cumSum, map1.getOrElse(cumSum, 0) + 1)\n })\n println(result)\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}], "src_uid": "e5244179b8ef807b1c6abfe113bd4f3b"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.StringBuilder\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject C401 {\n\n var result = true\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n def solve: Int = {\n var n = nextInt\n var m = nextInt\n if (n > m + 1)\n out.println(-1)\n else if (n == m + 1) {\n for (i <- 0 until (n + m - 1) / 2) {\n out.print(\"01\")\n }\n out.println(\"0\")\n } else if (m > 2 * n + 2) {\n out.println(-1)\n } else {\n val sb = new StringBuilder()\n while (n != m && n > 0 && m > 0 ) {\n sb.append(\"110\")\n n -= 1\n m -= 2\n }\n while (m > 0 && n > 0) {\n sb.append(\"10\")\n m -= 1\n n -= 1\n }\n var pos = sb.indexOf('1')\n while (n > 0) {\n sb.insert(pos + 1, '0')\n pos = sb.indexOf('1', pos + 2)\n n -= 1\n }\n while (m > 0) {\n sb.append('1')\n m -= 1\n }\n out.println(sb.toString())\n }\n return 0\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n var Array(n0, m1) = in.next().split(' ').map(_.toInt)\n val res = Array.ofDim[Int](n0 + m1)\n var solution = true\n (0 until n0 + m1).foreach{\n case el if !solution =>\n case el if el > 0 && res(el - 1) == 0 => \n res(el) = 1\n m1 -= 1\n solution &&= m1 >= 0\n case el if el > 1 && (res(el - 1) == res(el - 2) && res(el - 1) == 1) || n0 > m1 =>\n res(el) = 0\n n0 -= 1\n solution &&= n0 >= 0\n case el =>\n res(el) = 1\n m1 -= 1\n solution &&= m1 >= 0\n }\n if (!solution)\n println(-1)\n else\n println(res.mkString)\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\n\n/**\n * Created by hama_du on 2014/03/11.\n */\nobject ProblemC extends App {\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val zero,one = in.nextInt\n\n if (zero >= one+2) {\n out.println(-1)\n } else {\n val maxOne = (zero+1)*2\n if (one > maxOne) {\n out.println(-1)\n } else {\n if (zero >= one) {\n printZO(zero, one)\n } else {\n printOOZ(zero, one, one - (zero+1))\n }\n out.println()\n }\n }\n out.flush()\n\n def printOOZ(zero: Int, one: Int, dblOne: Int) {\n if (zero == 0) {\n if (dblOne == 1) {\n out.print(\"11\")\n } else {\n out.print(\"1\")\n }\n } else {\n if (dblOne >= 1) {\n out.print(\"110\")\n } else {\n out.print(\"10\")\n }\n printOOZ(zero-1, one-1, dblOne-1)\n }\n }\n\n def printZO(zero: Int, one: Int) {\n if (one == 0) {\n if (zero == 1) {\n out.print('0')\n }\n } else {\n out.print(\"01\")\n printZO(zero-1, one-1)\n }\n }\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.StringBuilder\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject C401 {\n\n var result = true\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n def solve: Int = {\n var n = nextInt\n var m = nextInt\n if (n > m + 1)\n out.println(-1)\n else if (n == m + 1) {\n for (i <- 0 until (n + m - 1) / 2) {\n out.print(\"01\")\n }\n out.println(\"0\")\n } else if (m > 2 * n + 2) {\n out.println(-1)\n } else {\n val sb = new StringBuilder()\n while (n >= 1 && m >= 2) {\n sb.append(\"110\")\n n -= 1\n m -= 2\n }\n while (m > 0) {\n sb.append('1')\n m -= 1\n }\n out.println(sb.toString())\n }\n return 0\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.StringBuilder\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject C401 {\n\n var result = true\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n def solve: Int = {\n var n = nextInt\n var m = nextInt\n if (n > m + 1)\n out.println(-1)\n else if (n == m + 1) {\n for (i <- 0 until (n + m - 1) / 2) {\n out.print(\"01\")\n }\n out.println(\"0\")\n } else if (m > 2 * n + 2) {\n out.println(-1)\n } else {\n val sb = new StringBuilder()\n while (n >= 1 && m >= 2) {\n sb.append(\"110\")\n n -= 1\n m -= 2\n }\n while (m > 0) {\n sb.append('1')\n m -= 1\n }\n var pos = sb.indexOf('1')\n while (n > 0) {\n sb.insert(pos + 1, '0')\n pos = sb.indexOf('1', pos + 2)\n n -= 1\n }\n out.println(sb.toString())\n }\n return 0\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.StringBuilder\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject C401 {\n\n var result = true\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n def solve: Int = {\n var n = nextInt\n var m = nextInt\n if (n > m + 1)\n out.println(-1)\n else if (n == m + 1) {\n for (i <- 0 until (n + m - 1) / 2) {\n out.print(\"01\")\n }\n out.println(\"0\")\n } else if (m > 2 * n + 2) {\n out.println(-1)\n } else {\n val sb = new StringBuilder()\n while (n != m) {\n sb.append(\"110\")\n n -= 1\n m -= 2\n }\n while (m > 0 && n > 0) {\n sb.append(\"10\")\n m -= 1\n n -= 1\n }\n var pos = sb.indexOf('1')\n while (n > 0) {\n sb.insert(pos + 1, '0')\n pos = sb.indexOf('1', pos + 2)\n n -= 1\n }\n out.println(sb.toString())\n }\n return 0\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.StringBuilder\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject C401 {\n\n var result = true\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n def solve: Int = {\n var n = nextInt\n var m = nextInt\n if (n > m + 1)\n out.println(-1)\n else if (n == m + 1) {\n for (i <- 0 until n + m - 1) {\n out.print(\"01\")\n }\n out.println(\"0\")\n } else if (m > 2 * n + 2) {\n out.println(-1)\n } else {\n val sb = new StringBuilder()\n while (n >= 1 && m >= 1) {\n sb.append(\"10\")\n n -= 1\n m -= 1\n }\n var pos = sb.indexOf('1')\n while (m > 0 && pos != -1) {\n sb.insert(pos + 1, '1')\n pos = sb.indexOf('1', pos + 2)\n m -= 1\n }\n while (m > 0) {\n sb.append('1')\n m -= 1\n }\n out.println(sb.toString())\n }\n return 0\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.StringBuilder\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject C401 {\n\n var result = true\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n def solve: Int = {\n var n = nextInt\n var m = nextInt\n if (n > m + 1)\n out.println(-1)\n else if (n == m + 1) {\n for (i <- 0 until (n + m - 1) / 2) {\n out.print(\"01\")\n }\n out.println(\"0\")\n } else if (m > 2 * n + 2) {\n out.println(-1)\n } else {\n val sb = new StringBuilder()\n while (n >= 1 && m >= 2) {\n sb.append(\"110\")\n n -= 1\n m -= 2\n }\n while (m > 0) {\n sb.append('1')\n m -= 1\n }\n while (n > 0) {\n sb.insert(0, '0')\n n -= 1\n }\n out.println(sb.toString())\n }\n return 0\n }\n}\n"}], "src_uid": "854c561539596722b1dbc8f99cbdca78"} {"source_code": "object A711 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = Array.fill(n)(scala.io.StdIn.readLine)\n if(input.exists(_.contains(\"OO\"))) {\n println(\"YES\")\n var break = false\n var i = 0\n while(!break) {\n if(input(i).contains(\"OO\")) {\n input(i) = input(i).replaceFirst(\"OO\", \"++\")\n break = true\n }\n i += 1\n }\n println(input.mkString(\"\\n\"))\n } else {\n println(\"NO\")\n }\n }\n}", "positive_code": [{"source_code": "object test {\n def main(args: Array[String]): Unit = {\n val in = Console.in\n val num = Integer.parseInt(in.readLine().trim)\n val out = 1 to num map (i => in.readLine()) mkString \"\\n\" replaceFirst(\"OO\", \"++\")\n if (out.contains(\"++\"))\n println(s\"YES\\n$out\")\n else println(\"NO\")\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n // val n = sc.nextInt()\n // val s = \n // val str = sc.next()\n\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n sc.nextLine()\n val seats = new Array[String](n)\n for(i <- 0 until n)\n seats(i) = sc.nextLine()\n\n //\n var flag = false\n var i = 0\n while(!flag && i < n){\n val now = seats(i)\n if(now.substring(0, 2) == \"OO\"){\n flag = true\n seats(i) = \"++\" + now.substring(2)\n }\n else if(now.substring(3) == \"OO\"){\n flag = true\n seats(i) = now.substring(0, 3) + \"++\"\n }\n\n i += 1\n }\n\n if(flag){\n println(\"YES\")\n for(s <- seats)\n println(s)\n }\n else\n println(\"NO\")\n }\n}\n"}, {"source_code": "object main extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n // override\n def solve(input: InputStream, output: PrintStream): Unit = {\n val sc = new Scanner(input)\n val nrows = sc.nextInt()\n val busIndx = (1 to nrows)\n .map(_ => sc.next()).zipWithIndex.toArray\n val optRow = busIndx.find{case (str,_) => str.startsWith(\"OO\") || str.endsWith(\"OO\")}\n if(optRow.isDefined){\n val (row,indxRow) = optRow.get\n busIndx(indxRow) = (updateRow(row),indxRow)\n\n output.println(\"YES\")\n busIndx.foreach{case (str,_) => output.println(str)}\n }else{\n output.println(\"NO\")\n }\n\n }\n\n def updateRow(str: String): String = {\n if(str.startsWith(\"OO\")) \"++\"+str.substring(2)\n else str.substring(0,3)+ \"++\"\n }\n solve(System.in,System.out)\n}"}, {"source_code": "import java.util\n\nimport scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n\n val max = 1000000007;\n val n = readInt()\n\n val A:Array[Array[String]] = Array.fill(n)(StdIn.readLine().split('|'))\n\n var i = 0\n while(i != n && !A(i)(0).equals(\"OO\") && !A(i)(1).equals(\"OO\")) {\n i+=1\n }\n\n if(i!=n) {\n println(\"YES\")\n if(A(i)(0).equals(\"OO\"))\n A(i)(0) = \"++\"\n else\n A(i)(1) = \"++\"\n\n A.foreach(a=>println(a(0) + \"|\" + a(1)))\n } else {\n println(\"NO\")\n }\n }\n\n def readInt(): Int = StdIn.readInt()\n\n def readInts(): Array[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n\n\n def readTuple(): (Int, Int) = {\n val line = readInts\n (line(0), line(1))\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main extends App {\n val scan = new Scanner(System.in)\n val n = scan.nextInt()\n val good = collection.immutable.HashMap(\"OO|XX\" -> \"++|XX\", \"OO|OX\" -> \"++|OX\",\n \"OO|XO\" -> \"++|XO\", \"OO|OO\" -> \"++|OO\",\n \"XX|OO\" -> \"XX|++\", \"XO|OO\" -> \"XO|++\",\n \"OX|OO\"->\"OX|++\")\n\n val input = for (i <- 1 to n) yield scan.next()\n val yes = input.exists(good.contains(_))\n if (yes) {\n println(\"YES\")\n var found = false\n input foreach { line =>\n if (!found && good.contains(line)) {\n found = true\n println(good.get(line).get)\n } else {\n println(line)\n }\n }\n } else {\n println(\"NO\")\n }\n}\n"}, {"source_code": "import scala.io.StdIn._;\n\nobject Test extends App {\n val n = readInt();\n val ans = (for (i<-0 until n) yield readLine()).mkString(\"\\n\");\n if (ans.contains(\"OO\")) {\n println(\"YES\");\n println(ans.replaceFirst(\"OO\", \"++\"));\n } else {\n println(\"NO\\n\"); \n }\n}"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val n = lines.next().toInt\n val (bus, ans) = (1 to n).map(_ => lines.next()).foldLeft(List.empty[String], false) {\n case ((xs, true), el) => (el :: xs, true)\n case ((xs, false), el) if el.contains(\"OO\") => (el.replaceFirst(\"OO\", \"++\") :: xs, true)\n case ((xs, false), el) => (el :: xs, false)\n }\n if (ans) {\n println(\"YES\")\n println(bus.reverse.mkString(\"\\n\"))\n } else println(\"NO\")\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val rows = Array.fill(n){ readLine }\n\n val i = rows.indexWhere(_.contains(\"OO\"))\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (i == -1) println(\"NO\")\n else {\n println(\"YES\")\n rows(i) = rows(i).replaceFirst(\"OO\", \"++\")\n println(rows.mkString(\"\\n\"))\n }\n\n Console.flush\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _711A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll}\n val bus = read[Seq[String]].mkString(\"\\n\")\n val ans = if (bus.contains(\"OO\")) {\n \"YES\\n\" + bus.replaceFirst(\"OO\", \"++\")\n } else {\n \"NO\"\n }\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Solution {\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val bus = Array.fill(n)(readLine)\n val idx = bus.indexWhere(str => str.contains(\"OO\"))\n if (idx == -1) {\n println(\"NO\")\n } else {\n println(\"YES\")\n bus.updated(idx, bus(idx).replaceFirst(\"OO\", \"++\")).foreach(str => println(str))\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Solution {\n\n def main(args: Array[String]): Unit = {\n val bus = Array.fill(readInt)(readLine)\n val idx = bus.indexWhere(str => str.contains(\"OO\"))\n if (idx == -1) {\n println(\"NO\")\n } else {\n println(\"YES\")\n bus.updated(idx, bus(idx).replaceFirst(\"OO\", \"++\")).foreach(str => println(str))\n }\n }\n}\n"}, {"source_code": "object test {\n def main(args: Array[String]): Unit = {\n val num = Integer.parseInt(Console.readLine().trim)\n val out = Stream.continually(Console.readLine()).take(num).mkString(\"\\n\").replaceFirst(\"OO\", \"++\")\n println(if (out.contains(\"++\")) s\"YES\\n$out\" else \"NO\")\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nobject Main extends App {\n val scan = new Scanner(System.in)\n val n = scan.nextInt()\n val good = collection.immutable.HashMap(\"OO|XX\" -> \"++|XX\", \"OO|OX\" -> \"++|OX\",\n \"OO|XO\" -> \"++|XO\", \"OO|OO\" -> \"++|OO\",\n \"XX|OO\" -> \"XX|++\", \"XO|OO\" -> \"XO|++\",\n \"OX|OO\"->\"OX|++\")\n\n val input = for (i <- 1 to n) yield scan.next()\n val yes = input.exists(good.contains(_))\n if (yes) {\n println(\"YES\")\n var found = false\n input foreach { line =>\n if (!found && good.contains(line)) {\n found = true\n println(good.get(line).get)\n } else {\n println(line)\n }\n }\n } else {\n println(\"NO\")\n input foreach println\n }\n}\n"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val n = lines.next().toInt\n val (bus, ans) = (1 to n).map(_ => lines.next()).foldLeft(List.empty[String], false) {\n case ((xs, true), el) => (el :: xs, true)\n case ((xs, false), el) if el.contains(\"OO\") => (el.replace(\"OO\", \"++\") :: xs, true)\n case ((xs, false), el) => (el :: xs, false)\n }\n if (ans) println(\"YES\") else println(\"NO\")\n println(bus.reverse.mkString(\"\\n\"))\n}\n"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val n = lines.next().toInt\n val (bus, ans) = (1 to n).map(_ => lines.next()).foldLeft(List.empty[String], false) {\n case ((xs, true), el) => (el :: xs, true)\n case ((xs, false), el) if el.contains(\"OO\") => (el.replace(\"OO\", \"++\") :: xs, true)\n case ((xs, false), el) => (el :: xs, false)\n }\n if (ans) {\n println(\"YES\")\n println(bus.reverse.mkString(\"\\n\"))\n } else println(\"NO\")\n}\n"}, {"source_code": "object A711 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = Array.fill(n)(scala.io.StdIn.readLine)\n if(input.exists(_.contains(\"OO\"))) {\n println(\"YES\")\n var break = false\n var i = 0\n while(!break) {\n if(input(i).contains(\"OO\")) {\n input(i) = input(i).replace(\"OO\", \"++\")\n break = true\n }\n i += 1\n }\n println(input.mkString(\"\\n\"))\n } else {\n println(\"NO\")\n }\n }\n}"}, {"source_code": "object test {\n def main(args: Array[String]): Unit = {\n val num = Integer.parseInt(Console.readLine().trim)\n val out = Stream.continually(Console.readLine()).take(num).mkString(\"\\n\").replaceFirst(\"00\", \"++\")\n println(if (out.contains(\"++\")) s\"YES\\n$out\" else \"NO\")\n }\n\n}\n"}, {"source_code": "object test {\n def main(args: Array[String]): Unit = {\n val in = Console.in\n val num = Integer.parseInt(in.readLine().trim)\n val out = 1 to num map (i => in.readLine()) mkString \"\\n\" replaceFirst(\"00\", \"++\")\n if (out.contains(\"++\"))\n println(s\"YES\\n$out\")\n else println(\"NO\")\n }\n\n}\n"}], "src_uid": "e77787168e1c87b653ce1f762888ac57"} {"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val t = stdin.next().toInt\n println(stdin\n .take(2 * t)\n .grouped(2)\n .map(_.last)\n .map(_\n .split(' ')\n .map(_.toInt)\n .map(x => if (x == 1) 1 else -1))\n .map(solve)\n .mkString(\"\\n\"))\n\n def solve(arr: Array[Int]) = {\n val n = arr.length / 2\n// val globalSum = arr.sum\n val leftSum = arr.take(n).sum\n val rightSum = arr.drop(n).sum\n// println(arr.mkString(\" \"))\n// println(\"leftSum \" + leftSum)\n// println(\"rightSum \" + rightSum)\n// println(\"globalSum \" + globalSum)\n //1 1 1 -1 -1 1 ||| -1 1 -1 1 1 -1\n val map = arr.take(n).foldLeft(Map(0 -> n, leftSum -> 0), 0, n) {\n case ((map, sum, needToRemove), el) =>\n val nSum = sum + el\n val nNeedToRemove = needToRemove - 1\n val nMap = if (nSum != leftSum) map + (nSum -> nNeedToRemove) else map\n (nMap, nSum, nNeedToRemove)\n }._1\n// println(map)\n arr.drop(n).foldLeft(map.getOrElse(-rightSum, 2 * n), rightSum, 0) {\n case((res, sum, needToRemove), el) =>\n// println(\"el = \" + el)\n// println(res)\n val nSum = sum - el\n val nNeedToRemove = needToRemove + 1\n val minRes = Math.min(res, map.get(-nSum).map(_ + nNeedToRemove).getOrElse(res))\n (minRes, nSum, nNeedToRemove)\n }._1\n }\n}\n\n//1\n//6\n//1 1 1 2 2 1 2 1 2 1 1 2", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = {\n if (!oj){ System.err.println(s) }\n }\n def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n private[this] def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve2(): Int = {\n val N = ni()\n val A = na(N).reverse\n val B = na(N)\n val cnt1 = A.count(_ == 1) + B.count(_ == 1)\n val cnt2 = 2 * N - cnt1\n val bal = cnt1 - cnt2\n val A2 = A.map(a => if (a == 1) 1 else -1)\n val B2 = B.map(a => if (a == 1) 1 else -1)\n val sumA = cumSum(A2).map(_.toInt)\n val sumB = cumSum(B2).map(_.toInt)\n debug(sumA)\n debug(sumB)\n debug(s\"bal:$bal\")\n val ref = mutable.Map[Int, Int]()\n REP(N + 1) { i =>\n val v = sumB(i)\n if (!ref.contains(v)) {\n ref(v) = i\n }\n }\n\n debug(ref.mkString(\",\"))\n\n var ans = 2 * N\n REP(N + 1) { i =>\n val expectedB = bal - sumA(i)\n// debug(s\"i:$i expectedB:$expectedB\")\n if (ref.contains(expectedB)) {\n ans = min(ans, ref(expectedB) + i)\n }\n }\n ans\n }\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n out.println(solve2())\n }\n }\n}"}], "negative_code": [{"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val t = stdin.next().toInt\n println(stdin\n .take(2 * t)\n .grouped(2)\n .map(_.last)\n .map(_\n .split(' ')\n .map(_.toInt)\n .map(x => if (x == 1) 1 else -1))\n .map(solve)\n .mkString(\"\\n\"))\n\n def solve(arr: Array[Int]) = {\n val n = arr.length / 2\n// val globalSum = arr.sum\n val leftSum = arr.take(n).sum\n val rightSum = arr.drop(n).sum\n// println(arr.mkString(\" \"))\n// println(\"leftSum \" + leftSum)\n// println(\"rightSum \" + rightSum)\n// println(\"globalSum \" + globalSum)\n //1 1 1 -1 -1 1 ||| -1 1 -1 1 1 -1\n val map = arr.take(n).foldLeft(Map(leftSum -> 0), 0, n) {\n case ((map, sum, needToRemove), el) =>\n val nSum = sum + el\n val nNeedToRemove = needToRemove - 1\n val nMap = if (nSum != leftSum) map + (nSum -> nNeedToRemove) else map\n (nMap, nSum, nNeedToRemove)\n }._1\n arr.drop(n).foldLeft(map.getOrElse(-rightSum, 2 * n), 0, 0) {\n case((res, sum, needToRemove), el) =>\n// println(\"el = \" + el)\n// println(res)\n val nSum = sum + el\n val nNeedToRemove = needToRemove + 1\n val minRes = Math.min(res, map.get(-rightSum + nSum).map(_ + nNeedToRemove).getOrElse(res))\n (minRes, nSum, nNeedToRemove)\n }._1\n }\n}\n\n//1\n//6\n//1 1 1 2 2 1 2 1 2 1 1 2"}, {"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val t = stdin.next().toInt\n println(stdin\n .take(2 * t)\n .grouped(2)\n .map(_.last)\n .map(_\n .split(' ')\n .map(_.toInt)\n .map(x => if (x == 1) 1 else -1))\n .map(solve)\n .mkString(\"\\n\"))\n\n def solve(arr: Array[Int]) = {\n val n = arr.length / 2\n// val globalSum = arr.sum\n val leftSum = arr.take(n).sum\n val rightSum = arr.drop(n).sum\n// println(arr.mkString(\" \"))\n// println(\"leftSum \" + leftSum)\n// println(\"rightSum \" + rightSum)\n// println(\"globalSum \" + globalSum)\n //1 1 1 -1 -1 1 ||| -1 1 -1 1 1 -1\n val map = arr.take(n).foldLeft(Map(leftSum -> 0, 0 -> n), 0, n) {\n case ((map, sum, needToRemove), el) =>\n val nSum = sum + el\n val nNeedToRemove = needToRemove - 1\n val nMap = if (nSum != leftSum) map + (nSum -> nNeedToRemove) else map\n (nMap, nSum, nNeedToRemove)\n }._1\n// println(map)\n arr.drop(n).foldLeft(map.getOrElse(-rightSum, 2 * n), rightSum, 0) {\n case((res, sum, needToRemove), el) =>\n// println(\"el = \" + el)\n// println(res)\n val nSum = sum - el\n val nNeedToRemove = needToRemove + 1\n val minRes = Math.min(res, map.get(-nSum).map(_ + nNeedToRemove).getOrElse(res))\n (minRes, nSum, nNeedToRemove)\n }._1\n }\n}\n\n//1\n//6\n//1 1 1 2 2 1 2 1 2 1 1 2"}, {"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val t = stdin.next().toInt\n println(stdin\n .take(2 * t)\n .grouped(2)\n .map(_.last)\n .map(_\n .split(' ')\n .map(_.toInt)\n .map(x => if (x == 1) 1 else -1))\n .map(solve)\n .mkString(\"\\n\"))\n\n def solve(arr: Array[Int]) = {\n val n = arr.length / 2\n// val globalSum = arr.sum\n val leftSum = arr.take(n).sum\n val rightSum = arr.drop(n).sum\n// println(arr.mkString(\" \"))\n// println(\"leftSum \" + leftSum)\n// println(\"rightSum \" + rightSum)\n// println(\"globalSum \" + globalSum)\n //1 1 1 -1 -1 1 ||| -1 1 -1 1 1 -1\n val map = arr.take(n).foldLeft(Map(leftSum -> 0), 0, n) {\n case ((map, sum, needToRemove), el) =>\n val nSum = sum + el\n val nNeedToRemove = needToRemove - 1\n val nMap = if (nSum != leftSum) map + (nSum -> nNeedToRemove) else map\n (nMap, nSum, nNeedToRemove)\n }._1\n arr.drop(n).foldLeft(map.getOrElse(-rightSum, 2 * n), rightSum, 0) {\n case((res, sum, needToRemove), el) =>\n// println(\"el = \" + el)\n// println(res)\n val nSum = sum - el\n val nNeedToRemove = needToRemove + 1\n val minRes = Math.min(res, map.get(-nSum).map(_ + nNeedToRemove).getOrElse(res))\n (minRes, nSum, nNeedToRemove)\n }._1\n }\n}\n\n//1\n//6\n//1 1 1 2 2 1 2 1 2 1 1 2"}], "src_uid": "b010397b6aeab4ad3f0c9f8e45b34691"} {"source_code": "/**\n * Created by mahmoud on 8/22/16.\n */\n\nimport io.StdIn._\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = readLine().toInt\n val array = readLine().split(\" \").map(_.toInt)\n val srt = array.sorted\n println(srt((n - 1)/2))\n }\n\n}\n", "positive_code": [{"source_code": "\n\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\n/**\n * Educational round 16\n */\nobject B_ED16 { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n runTest(Test.sa3)\n debugV = true\n// file = File(\"C:\\\\temp\\\\google cj\\\\2014q\\\\c-small.res\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading \n val n = readLine.int\n var arr = new Array[Int](n)\n val pointsLn = readLine()\n (0 until n).foreach{\n arr(_) = pointsLn.int\n }\n \n arr = arr.sorted \n \n def dist(ind: Int): Long = {\n var sum = 0l\n for (i <- 0 until n) {\n if (i != ind) {\n sum += (arr(ind) - arr(i)).abs\n }\n }\n sum\n }\n \n def thereIsBetter(ind: Int): (Boolean, Int) = {\n val distP = dist(ind)\n if (ind != 0 && dist(ind-1) < distP) return (true, ind-1)\n if (ind < n-1 && dist(ind+1) < distP) return (true, ind+1)\n \n return (false, -1) \n }\n \n val mid = Math.ceil(n.toDouble/2 - 1).toInt\n debug(arr.mkString(\",\") + \" -> \" + arr(mid))\n debug((0 until n).map { dist(_) }.mkString(\",\"))\n var cur = mid\n var next = thereIsBetter(cur)\n while (next._1) {\n cur = next._2\n next = thereIsBetter(cur)\n }\n \n// val totalDist = arr(n-1).toLong - arr(0)\n// debug(s\"total=$totalDist\")\n// val mid = math.floor(arr(0) + totalDist.toDouble/2).toInt\n// debug(arr.mkString(\",\") + \" -> \" + mid)\n// \n// var minOff = totalDist\n// var minInd = 0\n// (0 until n).foreach { i =>\n// val off = (mid - arr(i)).abs \n// if (off < minOff) {\n// minOff = off\n// minInd = i\n// }\n \n //---------------------------- parameters reading :end \n var res = arr(cur)\n outLn(res+\"\")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4\n1 2 3 4\n\"\"\"\n\nval sa2 = \"\"\"\n5\n-1 -10 2 6 7\n\"\"\"\n\nval sa3 = \"\"\"\n3\n606194955 -856471310 117647402\n\"\"\"\n}\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toInt).sorted\n if (line.length == 1)\n println(line(0))\n else if (line.length % 2 == 1)\n println(line(line.length / 2))\n else\n println(line(line.length / 2 - 1))\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toInt).sorted\n if (line.length == 0 || line.length == 1)\n println(line(0))\n else\n println(line(line.length / 2 - 1))\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toInt).sorted\n if (line.length % 2 == 1)\n println(line(line.length / 2 + 1))\n else if (line.length == 0)\n println(line(0))\n else\n println(line(line.length / 2 - 1))\n}\n"}, {"source_code": "\n\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\n/**\n * Educational round 16\n */\nobject B_ED16 { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.sa2)\n// debugV = true\n// file = File(\"C:\\\\temp\\\\google cj\\\\2014q\\\\c-small.res\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading \n val n = readLine.int\n var arr = new Array[Int](n)\n val pointsLn = readLine()\n (0 until n).foreach{\n arr(_) = pointsLn.int\n }\n \n arr = arr.sorted \n \n def dist(ind: Int): Int = {\n var sum = 0\n for (i <- 0 until n) {\n if (i != ind) {\n sum += (arr(ind) - arr(i)).abs\n }\n }\n sum\n }\n \n def thereIsBetter(ind: Int): (Boolean, Int) = {\n val distP = dist(ind)\n if (ind != 0 && dist(ind-1) < distP) return (true, ind-1)\n if (ind < n-1 && dist(ind+1) < distP) return (true, ind+1)\n \n return (false, -1) \n }\n \n val mid = Math.ceil(n.toDouble/2 - 1).toInt\n debug(arr.mkString(\",\") + \" -> \" + arr(mid))\n debug((0 until n).map { dist(_) }.mkString(\",\"))\n var cur = mid\n var next = thereIsBetter(cur)\n while (next._1) {\n cur = next._2\n next = thereIsBetter(cur)\n }\n \n// val totalDist = arr(n-1).toLong - arr(0)\n// debug(s\"total=$totalDist\")\n// val mid = math.floor(arr(0) + totalDist.toDouble/2).toInt\n// debug(arr.mkString(\",\") + \" -> \" + mid)\n// \n// var minOff = totalDist\n// var minInd = 0\n// (0 until n).foreach { i =>\n// val off = (mid - arr(i)).abs \n// if (off < minOff) {\n// minOff = off\n// minInd = i\n// }\n \n //---------------------------- parameters reading :end \n var res = arr(cur)\n outLn(res+\"\")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4\n1 2 3 4\n\"\"\"\n\nval sa2 = \"\"\"\n5\n-1 -10 2 6 7\n\"\"\"\n\nval sa3 = \"\"\"\n\"\"\"\n}\n\n}\n"}, {"source_code": "\n\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\n/**\n * Educational round 16\n */\nobject B_ED16 { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n runTest(Test.sa1)\n// debugV = true\n// file = File(\"C:\\\\temp\\\\google cj\\\\2014q\\\\c-small.res\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading \n val n = readLine.int\n var arr = new Array[Int](n+1)\n val pointsLn = readLine()\n (1 to n).foreach{\n arr(_) = pointsLn.int\n }\n \n arr = arr.sorted\n val totalDist = arr(n).toLong - arr(1)\n val mid = arr(1) + totalDist/2\n \n var minOff = totalDist\n var minInd = 0\n (1 to n).foreach { i =>\n val off = (mid - arr(i)).abs \n if (off < minOff) {\n minOff = off\n minInd = i\n }\n }\n \n //---------------------------- parameters reading :end \n var res = minInd\n outLn(res)\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4\n1 2 3 4\n\"\"\"\n\nval sa2 = \"\"\"\n\"\"\"\n\nval sa3 = \"\"\"\n\"\"\"\n}\n\n}\n"}], "src_uid": "fa9cc3ba103ed1f940c9e80a7ea75f72"} {"source_code": "import scala.io.StdIn\nimport scala.language.implicitConversions\n\nobject A155 {\n def main(args: Array[String]) = {\n val _ = StdIn.readLine()\n val a = StdIn.readLine().split(\" \").map(_.toInt)\n implicit def bool2int(b: Boolean) = if (b) 1 else 0\n println(a.foldLeft((0, a(0), a(0)))\n { (x: Tuple3[Int, Int, Int], y: Int) =>\n (x._1 + (y > x._2) + (y < x._3), y max x._2, y min x._3) }._1)\n }\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nobject ILoveUserName {\n\n def main(args: Array[String]): Unit = {\n val scanner = new Scanner(System.in)\n val c = scanner.nextInt();\n var max,min = 0\n min = scanner.nextInt()\n max = min\n var counter = 0;\n for (i <- 2 to c){\n var x = scanner.nextInt();\n if (x > max || x < min){\n counter += 1;\n }\n max = Math.max(x,max)\n min = Math.min(x,min)\n \n }\n println(counter)\n }\n\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main {\n def main(args: Array[String]) {\n val input = new Scanner(System.in)\n\n val count, first = input.nextInt\n var incr = 0\n var min, max = first\n\n for (i <- 1 until count) {\n val next = input.nextInt\n if (next < min) {\n incr += 1\n min = next\n }\n if (next > max) {\n incr += 1\n max = next\n }\n }\n\n println(incr)\n }\n}"}, {"source_code": "\nobject Main {\n def main(args: Array[String]) {\n // not like we need it or anything\n val n = readInt()\n\n var bestScore = 0\n var worstScore = 0\n\n val surprises = readLine().split(\" \").map(_.toInt).fold(-1) {(surprises, score) =>\n if (surprises == -1) {\n bestScore = score\n worstScore = score\n 0\n } else if (score > bestScore) {\n bestScore = score\n surprises + 1\n } else if (score < worstScore) {\n worstScore = score\n surprises + 1\n } else {\n surprises\n }\n }\n\n println(surprises)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println(in.next().split(\" \").map(_.toInt).foldLeft((-1, -1, 0)) {\n case((-1, -1, 0), el) => (el, el, 0)\n case((min, max, t), el) if el < min=> (el, max, t + 1)\n case((min, max, t), el) if el > max=> (min, el, t + 1)\n case(acc, el) => acc\n }._3)\n}\n"}, {"source_code": "object Main {\n\tdef main(args: Array[String]) {\n\n\t\treadInt\n\t\tval a = readLine.split(\" \").map(i => i.toInt)\n\n\t\tvar max = a(0)\n\t\tvar min = a(0)\n\n\t\tvar cnt = 0\n\t\ta.foreach(i => {if (i < min) {cnt += 1; min = i }; if (i > max) { cnt +=1; max = i } } )\n\t\tprintln (cnt)\n\t}\n}\t\n"}, {"source_code": "object A155 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val points = readInts(n)\n var res = 0\n var maxtill = points(0)\n var mintill = points(0)\n for(i <- 1 until n) {\n if(points(i) > maxtill){\n maxtill = points(i)\n res += 1\n } else if(points(i) < mintill){\n mintill = points(i)\n res += 1\n }\n }\n println(res)\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P155A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val scores = Array.fill(N)(sc.nextInt)\n\n def solve: Int = {\n @tailrec\n def loop(amazing: Int, best: Int, worst: Int, i: Int): Int =\n if (i == N) amazing\n else {\n val s = scores(i)\n if (s > best) loop(amazing + 1, s, worst, i + 1)\n else if (s < worst) loop(amazing + 1, best, s, i + 1)\n else loop(amazing, best, worst, i + 1)\n }\n loop(0, scores(0), scores(0), 1)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n reader.readLine()\n val a = readInts\n def mins = a.foldLeft(List(Int.MaxValue)) {\n case (l @ head :: _, x) => (head min x) :: l\n }\n def maxs = a.foldLeft(List(Int.MinValue)) {\n case (l @ head :: _, x) => (head max x) :: l\n }\n def ans = mins.groupBy(x => x).size + maxs.groupBy(x => x).size - 4\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object A {\n def main(args: Array[String]): Unit = {\n val points = scala.io.Source.stdin.getLines().toList.tail.head.split(\" \").map(_.toInt)\n System.out.println(points.foldLeft((points.head,points.head,0))( (a,p) => if (p>a._2)((a._1,p,a._3+1)) else if (p max) {\n max = v\n impr += 1\n }\n if (v < min) {\n min = v\n impr += 1\n }\n }\n println(impr)\n }\n}"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject ILoveUsername {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readLongs() : Array[Long] = \n readLine.split(' ').map(_.toLong)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n \n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n \n \n def solve(points : List[Int]) : Int = {\n def go(p: List[Int], max: Int, min: Int, amazing: Int) : Int = p match {\n case Nil => amazing\n case h :: t => go(t, Math.max(h,max), \n Math.min(h,min),amazing + (if (h > max || h < min) 1 else 0))\n }\n go(points.tail, points.head,points.head,0)\n }\n \n def main(args: Array[String]) {\n val n = readInt\n val points = readInts().toList\n println(solve(points))\n }\n \n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val sc = new java.util.Scanner(System.in)\n val N = sc.nextInt\n val L = List.fill(N)(sc.nextInt)\n println(rec(L(0), L(0), L.tail, 0))\n }\n\n def rec(minv: Int, maxv: Int, lst: List[Int], acc: Int): Int = {\n lst match {\n case Nil => acc\n case head::tail => {\n if (head < minv) rec(head, maxv, tail, acc + 1)\n else if (head > maxv) rec(minv, head, tail, acc + 1)\n else rec(minv, maxv, tail, acc)\n }\n }\n }\n}\n"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n val n = StdIn.readInt()\n\n var min = 10000000\n var max = 0\n var count = 0\n var first = true\n StdIn.readLine().split(\" \").map(_.toInt).foreach{ t =>\n if(!first) {\n if(t > max) {\n max = t\n count+=1\n }\n\n if(t < min) {\n min = t\n count+=1\n }\n } else {\n max = t\n min = t\n first = false\n }\n }\n println(count)\n }\n\n\n\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main { \n def main(args: Array[String]) { \n val sc = new Scanner(System.in)\n val n = sc.nextInt\n val first = sc.nextInt\n var max = first\n var min = first\n var amazing = 0\n for (i <- 1 until n) { \n var tmp = sc.nextInt\n if (max < tmp) { \n max = tmp\n amazing += 1\n } else if (min > tmp) { \n min = tmp\n amazing += 1\n }\n }\n println(amazing)\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Codeforces extends App {\n val n = readInt() - 1\n val scores = readLine().split(' ').map(_.toInt)\n var min = scores(0)\n var max = scores(0)\n var count = 0\n scores foreach(current => {\n if (current > max) {\n max = current\n count += 1\n }\n if (current < min) {\n min = current\n count += 1\n }\n })\n println(count)\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Cf155a extends App {\n val a = Source.stdin.getLines.drop(1).next.split(\" \").filterNot(_.isEmpty()).map(_.toInt)\n var min = a.head\n var max = a.head\n println(a.foldLeft(0)((y, x) => {\n if (x < min) {\n min = x\n y + 1\n } else if (x > max) {\n max = x;\n y + 1\n } else {\n y\n }\n }))\n}"}], "negative_code": [], "src_uid": "a61b96d4913b419f5715a53916c1ae93"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, p) = in.next().split(' ').map(_.toInt)\n val data = in.next()\n val zipped = data\n .take(n / 2)\n .zip(data.reverse.take(n / 2))\n val left = zipped.indices.find(i => zipped(i)._1 != zipped(i)._2)\n val right = zipped.indices.reverse.find(i => zipped(i)._1 != zipped(i)._2)\n\n val changes = zipped\n .foldLeft(0l) {\n case(acc, (a, b)) =>\n val min = Math.min(a, b)\n val max = Math.max(a, b)\n acc + Math.min(max - min, min - max + 'z' - 'a' + 1)\n\n }\n\n if (left.isEmpty)\n println(changes)\n else {\n val position = if (p > n / 2) n - p else p - 1\n// if (right.get < position)\n// println(changes + position - left.get)\n// else if (left.get > position)\n// println(changes + right.get - position)\n// else\n// println(\"right.get = \" + right.get)\n// println(\"left.get = \" + left.get)\n// println(\"position = \" + position)\n// println(\"distance = \" + (right.get - left.get))\n// println(\"dd \" + Math.min(Math.abs(position - right.get), Math.abs(position - left.get)))\n// println(changes)\n println(changes + right.get - left.get + Math.min(Math.abs(position - right.get), Math.abs(position - left.get)))\n }\n\n// println(\"changes = \" + changes)\n\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject Solution {\n val INF = 1000 * 1000 * 1000\n\n def solve(in: FastScanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n var pos = in.nextInt() - 1\n val a = in.next().toCharArray()\n var rep = 0\n var res = INF\n for (rep <- 0 until 2) {\n var i = 0\n val delta = new Array[Int](n)\n for (i <- 0 until n / 2) {\n val diff = (a(i) - a(n - i - 1) + 26) % 26\n delta(i) = Math.min(diff, 26 - diff)\n }\n var leftPos = n / 2 + 1\n var rightPos = -1\n var cur = 0\n for (i <- 0 until n / 2) {\n cur += delta(i)\n if (delta(i) > 0) {\n leftPos = Math.min(leftPos, i)\n rightPos = Math.max(rightPos, i)\n }\n }\n if (cur != 0) {\n cur += rightPos - leftPos\n if (leftPos <= pos && pos <= rightPos)\n cur += Math.min(pos - leftPos, rightPos - pos)\n else if (pos < leftPos)\n cur += leftPos - pos\n else\n cur += pos - rightPos\n }\n res = Math.min(res, cur)\n pos = n - 1 - pos\n for (i <- 0 until n / 2) {\n val t = a(i)\n a(i) = a(n - i - 1)\n a(n - i - 1) = t\n }\n }\n out.println(res)\n }\n\n def main(args: Array[String]): Unit = {\n val in = new FastScanner(System.in)\n val out = new PrintWriter(System.out)\n solve(in, out)\n out.flush()\n }\n\n class FastScanner(val in: InputStream) {\n var st: StringTokenizer = null\n var br = new BufferedReader(new InputStreamReader(in))\n\n def next(): String = {\n while (st == null || !st.hasMoreTokens()) {\n val line = br.readLine()\n if (line == null)\n throw new IOException()\n st = new StringTokenizer(line)\n }\n return st.nextToken()\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def close(): Unit = {\n br.close()\n }\n }\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, p) = in.next().split(' ').map(_.toInt)\n val data = in.next()\n val zipped = data\n .take(n / 2)\n .zip(data.reverse.take(n / 2))\n val left = zipped.indices.find(i => zipped(i)._1 != zipped(i)._2)\n val right = zipped.indices.reverse.find(i => zipped(i)._1 != zipped(i)._2)\n\n val changes = zipped\n .foldLeft(0l) {\n case(acc, (a, b)) =>\n val min = Math.min(a, b)\n val max = Math.max(a, b)\n acc + Math.min(max - min, min - max + 'z' - 'a' + 1)\n\n }\n\n if (left.isEmpty)\n println(changes)\n else {\n val position = if (p > n / 2) n - p else p\n// if (right.get < position)\n// println(changes + position - left.get)\n// else if (left.get > position)\n// println(changes + right.get - position)\n// else\n println(changes + right.get - left.get + 1+ Math.min(position - right.get, position - left.get))\n }\n\n// println(\"changes = \" + changes)\n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, p) = in.next().split(' ').map(_.toInt)\n val data = in.next()\n val zipped = data\n .take(n / 2)\n .zip(data.reverse.take(n / 2))\n val left = zipped.indices.find(i => zipped(i)._1 != zipped(i)._2)\n val right = zipped.indices.reverse.find(i => zipped(i)._1 != zipped(i)._2)\n\n val changes = zipped\n .foldLeft(0l) {\n case(acc, (a, b)) =>\n val min = Math.min(a, b)\n val max = Math.max(a, b)\n acc + Math.min(max - min, min - max + 'z' - 'a' + 1)\n\n }\n\n if (left.isEmpty)\n println(changes)\n else {\n val position = if (p > n / 2) n - p - 1 else p - 1\n// if (right.get < position)\n// println(changes + position - left.get)\n// else if (left.get > position)\n// println(changes + right.get - position)\n// else\n// println(\"right.get = \" + right.get)\n// println(\"left.get = \" + left.get)\n// println(\"position = \" + position)\n// println(\"distance = \" + (right.get - left.get))\n// println(\"dd \" + Math.min(position - right.get, position - left.get))\n// println(changes)\n println(changes + right.get - left.get + Math.min(Math.abs(position - right.get), Math.abs(position - left.get)))\n }\n\n// println(\"changes = \" + changes)\n\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject Solution {\n val INF = 1000 * 1000 * 1000\n\n def solve(in: FastScanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n var pos = in.nextInt() - 1\n val a = in.next().toCharArray()\n var rep = 0\n var res = INF\n for (rep <- 0 until 2) {\n var i = 0\n val delta = new Array[Int](n)\n for (i <- 0 until n / 2) {\n val diff = (a(i) - a(n - i - 1) + 26) % 26\n delta(i) = Math.min(diff, 26 - diff)\n }\n var leftPos = 0\n var rightPos = n / 2\n var cur = 0\n for (i <- 0 until n / 2) {\n cur += delta(i)\n if (delta(i) > 0) {\n leftPos = Math.min(leftPos, i)\n rightPos = Math.max(rightPos, i)\n }\n }\n if (cur != 0) {\n cur += rightPos - leftPos\n if (leftPos <= pos && pos <= rightPos)\n cur += Math.min(pos - leftPos, rightPos - pos)\n }\n res = Math.min(res, cur)\n pos = n - 1 - pos\n for (i <- 0 until n / 2) {\n val t = a(i)\n a(i) = a(n - i - 1)\n a(n - i - 1) = t\n }\n }\n out.println(res)\n }\n\n def main(args: Array[String]): Unit = {\n val in = new FastScanner(System.in)\n val out = new PrintWriter(System.out)\n solve(in, out)\n out.flush()\n }\n\n class FastScanner(val in: InputStream) {\n var st: StringTokenizer = null\n var br = new BufferedReader(new InputStreamReader(in))\n\n def next(): String = {\n while (st == null || !st.hasMoreTokens()) {\n val line = br.readLine()\n if (line == null)\n throw new IOException()\n st = new StringTokenizer(line)\n }\n return st.nextToken()\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def close(): Unit = {\n br.close()\n }\n }\n}\n"}], "src_uid": "ebacd748147b50b20d39b4d8cfde39ec"} {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _680C extends CodeForcesApp {\n override def apply(io: IO) = {\n\n def isDivisor(i: Int): Boolean = {\n io.println(i)\n io[String] == \"yes\"\n }\n\n val primes = Seq( 2, 3, 5, 7, 11,\n 13, 17, 19, 23, 29,\n 31, 37, 41, 43, 47,\n 53, 59, 61, 67, 71,\n 73, 79, 83, 89, 97)\n\n val isComposite = Seq(2, 3, 5, 7).find(isDivisor) match {\n case Some(p) =>\n val next = primes collect {case i if i >= p && i*p <= 100 => i*p}\n next.exists(isDivisor)\n case _ =>\n false\n }\n\n io += (if (isComposite) \"composite\" else \"prime\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def bitCount: Int = java.lang.Integer.bitCount(x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]\n def memoize[A, B](f: A => B): A ==> B = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n /*override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }*/\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def array[A]: Write[Array[A]] = Write(_ mkString \" \")\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _680C extends CodeForcesApp {\n override def apply(io: IO) = {import io._\n def isDivisor(i: Int) = writeLine(i).read[Boolean]\n\n val primes = Seq(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47)\n\n val isComposite = Seq(2, 3, 5, 7).filter(isDivisor) exists {p =>\n val next = primes collect {case i if i >= p && i*p <= 100 => i*p}\n next.exists(isDivisor)\n }\n\n write(if (isComposite) \"composite\" else \"prime\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toYesNo = if(x) \"yes\" else \"no\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n def bitCount: Int = java.lang.Integer.bitCount(x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def newMultiMap[K, V] = map[K] to Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write[@specialized A](obj: A): this.type = {\n printer.print(obj)\n this\n }\n def writeLine[@specialized A](obj: A): this.type = {\n printer.println(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeSpace(): this.type = write(' ')\n def writeAll[A](obj: Traversable[A]): this.type = write(obj mkString \" \")\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n var candidates = (2 to 100).toList\n\n def isSimple(i: Int) = {\n (2 until i).forall(j => i % j != 0)\n }\n\n while (candidates.exists(isSimple) && candidates.exists(x => !isSimple(x))) {\n println(candidates.head)\n in.next() match {\n case \"yes\" =>\n candidates = (candidates.tail ::: List(candidates.head))filter(_ % candidates.head == 0)\n case \"no\" =>\n candidates = candidates.filter(_ % candidates.head != 0)\n }\n }\n if (candidates.forall(isSimple))\n println(\"prime\")\n else\n println(\"composite\")\n}\n"}], "negative_code": [], "src_uid": "8cf479fd47050ba96d21f3d8eb43c8f0"} {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-29.\n */\nobject A462 {\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val board = new Array[String](n)\n var i = 0\n\n while (n > i) {\n board(i) = sc.next()\n i += 1\n }\n\n i = 0\n var ans = 0\n\n while (i < n) {\n var j = 0\n\n while (j < n) {\n var add: Int = 0\n\n if (i - 1 >= 0 && board(i - 1)(j) == 'o') {\n add += 1\n }\n\n if (j + 1 < n && board(i)(j + 1) == 'o') {\n add += 1\n }\n\n if (i + 1 < n && board(i + 1)(j) == 'o') {\n add += 1\n }\n\n if (j - 1 >= 0 && board(i)(j - 1) == 'o') {\n add += 1\n }\n\n if (add % 2 == 1) {\n println(\"NO\")\n return\n }\n\n j += 1\n }\n\n i += 1\n }\n\n println(\"YES\")\n }\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _462A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next).toArray\n def f(i: Int, j: Int) = {\n var ans = 0\n if (i - 1 >= 0 && a(i - 1)(j) == 'o') ans = ans + 1\n if (i + 1 < n && a(i + 1)(j) == 'o') ans = ans + 1\n if (j - 1 >= 0 && a(i)(j - 1) == 'o') ans = ans + 1\n if (j + 1 < n && a(i)(j + 1) == 'o') ans = ans + 1\n ans\n }\n\n val ans = for {\n i <- 0 until n\n j <- 0 until n\n } yield if (f(i, j) % 2 == 0) true else false\n\n if (ans.size == 0 || ans.reduce(_ && _)) println(\"YES\")\n else println(\"NO\")\n}\n"}, {"source_code": "/**\n * Created by lurker on 2014. 8. 15..\n */\nobject CF263_1 extends App {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n val Array(n) = readInts(1)\n val arr = Array.fill(n)(readLine)\n\n def isEven(i:Int, j:Int):Boolean = {\n var sumo = 0\n for( (di, dj) <- Seq((-1,0), (1,0), (0, -1), (0, 1))) {\n val newi = i + di\n val newj = j + dj\n if(0 <= newi && newi < n && 0 <= newj && newj < n) {\n if(arr(newi)(newj) == 'o') {\n sumo += 1\n }\n }\n }\n sumo %2 == 0\n }\n\n var result = true\n for(i <- 0 until n; j <- 0 until n) {\n result = result && isEven(i, j)\n }\n if(result){\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n}\n"}, {"source_code": "object A462 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val bo = Array.fill(n)(read.toCharArray)\n\n def valid(x: Int, y: Int): Boolean = {\n if(x >= 0 && y >= 0 && x < n && y < n ) true else false\n }\n val delta = Array((-1, 0), (1, 0), (0, -1), (0, 1))\n var break = false\n for(i <- 0 until n; j <- 0 until n if !break) {\n var cntO = 0\n for(d <- delta) {\n val newi = i + d._1\n val newj = j + d._2\n if(valid(newi, newj) && bo(i + d._1)(j + d._2) == 'o') {\n cntO += 1\n }\n }\n if(cntO%2 != 0) {\n println(\"NO\")\n break = true\n }\n }\n if(!break) println(\"YES\")\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _462A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next).toArray\n def f(i: Int, j: Int) = {\n var ans = 0\n if (i - 1 >= 0 && a(i - 1)(j) == 'o') ans = ans + 1\n if (i + 1 < n && a(i + 1)(j) == 'o') ans = ans + 1\n if (j - 1 >= 0 && a(i)(j - 1) == 'o') ans = ans + 1\n if (j + 1 < n && a(i)(j + 1) == 'o') ans = ans + 1\n ans\n }\n\n val ans = for {\n i <- 0 until n\n j <- 0 until n\n if (a(i)(j) == 'x')\n } yield if (f(i, j) % 2 == 0) true else false\n\n if (ans.size == 0 || ans.reduce(_ && _)) println(\"YES\")\n else println(\"NO\")\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-29.\n */\nobject A462{\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val board = new Array[String](n)\n var i = 0\n\n while (n > i) {\n board(i) = sc.next()\n i += 1\n }\n\n val checked = Array.ofDim[Boolean](n, n)\n i = 0\n var ans = 0\n\n while (i < n) {\n var j = 0\n\n while (j < n) {\n if (!checked(i)(j)) {\n if (board(i)(j) == 'o') {\n var add: Int = 0\n\n if (i - 1 >= 0 && board(i - 1)(j) == 'o') {\n add += 1\n checked(i - 1)(j) = true\n }\n\n if (j + 1 < n && board(i)(j + 1) == 'o') {\n add += 1\n checked(i)(j + 1) = true\n }\n\n if (i + 1 < n && board(i + 1)(j) == 'o') {\n checked(i + 1)(j) = true\n add += 1\n }\n\n if (j - 1 >= 0 && board(i)(j - 1) == 'o') {\n add += 1\n checked(i)(j - 1) = true\n }\n\n if (add % 2 == 1) {\n println(\"NO\")\n return\n }\n }\n }\n\n j += 1\n }\n\n i += 1\n }\n\n println(\"YES\")\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-29.\n */\nobject A462{\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val board = new Array[String](n)\n var i = 0\n\n while (n > i) {\n board(i) = sc.next()\n i += 1\n }\n\n val checked = Array.ofDim[Boolean](n, n)\n i = 0\n var ans = 0\n\n while (i < n) {\n var j = 0\n\n while (j < n) {\n if (!checked(i)(j)) {\n if (board(i)(j) == 'o') {\n var add: Boolean = false\n\n if (i - 1 >= 0 && board(i - 1)(j) == 'o') {\n add = true\n checked(i - 1)(j) = true\n }\n\n if (j + 1 < n && board(i)(j + 1) == 'o') {\n add = true\n checked(i)(j + 1) = true\n }\n\n if (i + 1 < n && board(i + 1)(j) == 'o') {\n checked(i + 1)(j) = true\n add = true\n }\n\n if (j - 1 >= 0 && board(i)(j - 1) == 'o') {\n add = true\n checked(i)(j - 1) = true\n }\n\n if (add) {\n ans += 1\n }\n }\n }\n\n j += 1\n }\n\n i += 1\n }\n\n println(if (ans % 2 == 0) {\n \"YES\"\n } else {\n \"NO\"\n })\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-29.\n */\nobject A462 {\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val board = new Array[String](n)\n var i = 0\n\n while (n > i) {\n board(i) = sc.next()\n i += 1\n }\n\n val checked = Array.ofDim[Boolean](n, n)\n i = 0\n var ans = 0\n\n while (i < n) {\n var j = 0\n\n while (j < n) {\n if (!checked(i)(j)) {\n var add: Int = 0\n\n if (i - 1 >= 0 && board(i - 1)(j) == 'o') {\n add += 1\n checked(i - 1)(j) = true\n }\n\n if (j + 1 < n && board(i)(j + 1) == 'o') {\n add += 1\n checked(i)(j + 1) = true\n }\n\n if (i + 1 < n && board(i + 1)(j) == 'o') {\n checked(i + 1)(j) = true\n add += 1\n }\n\n if (j - 1 >= 0 && board(i)(j - 1) == 'o') {\n add += 1\n checked(i)(j - 1) = true\n }\n\n if (add % 2 == 1) {\n println(\"NO\")\n return\n }\n }\n\n j += 1\n }\n\n i += 1\n }\n\n println(\"YES\")\n }\n}\n"}], "src_uid": "03fcf7402397b94edd1d1837e429185d"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, k) = readLine split ' ' map (_ toInt)\n val f: Array[Int] = readLine split ' ' map (_ toInt) sortWith (_ > _)\n println({ for (i <- (0 to ((n - 1) / k))) yield 2 * f(i * k) - 2 } reduceLeft (_ + _))\n }\n}", "positive_code": [{"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 28.09.14.\n */\nobject B extends App {\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n val k = nextInt\n val fs = Array.fill(2001)(0)\n for (i <- 0 until n) {\n val f = nextInt\n fs(f) += 1\n }\n\n var last = 2000\n def func(acc: Int): Int = {\n if (last == 0 && fs(last) == 0) {\n acc\n } else {\n if (fs(last) == 0) {\n last -= 1\n func(acc)\n } else {\n var s = 0\n val cost = 2 * (last - 1)\n while (s < k && last >= 0) {\n val add = math.min(fs(last), k - s)\n s += add\n fs(last) -= add\n if (fs(last) == 0) {\n last -= 1\n }\n }\n if (last == -1) {\n last = 0\n }\n func(acc + cost)\n }\n }\n }\n\n out.print(func(0))\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _472B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val k = next.toInt\n val a = (1 to n).map(i => next.toInt - 1).sortBy(i => -i).toList\n def f(a: List[Int]): Int = {\n val (head, tail) = a.splitAt(k)\n 2 * head.head + (if (tail != Nil) f(tail) else 0)\n }\n println(f(a))\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt).sorted\n val r = data.foldLeft((1, 0, data.length)) {\n case((current, soFar, left), el) if el == current => (current, soFar, left - 1)\n case((current, soFar, left), el) if left <= k => (el, soFar + (el - current), left - 1)\n case((current, soFar, left), el) =>\n var count = left / k\n if (left % k > 0) count += 1\n if (count > 1) count = count * 2 - 1\n (el, soFar + count * (el - current), left - 1)\n\n }\n println(data.last + r._2 - 1)\n}\n"}, {"source_code": "object TaskA {\n def main(args: Array[String]) {\n val Array(n, k) = readLine split ' ' map(_ toInt)\n val f: Array[Int] = readLine split ' ' map(_ toInt) sortWith(_ > _)\n println({for (i <- (0 to ((n - 1) / k))) yield 2 * f(i * k) - 2} reduceLeft(_ + _))\n }\n}\n"}, {"source_code": "object B472 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n val in = readInts(n).sorted.reverse\n val ans = in.grouped(k).map(arr => arr.max*2 - 2).sum\n println(ans)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.math._\nimport scala.util.Sorting._\n\nobject Main extends App{\n val pass = readLine.split(\" \").map(x => x.toInt)\n var n = pass(0)\n var k = pass(1)\n \n var floors = readLine.split(\" \").map(x => x.toInt - 1).sorted.toList.reverse\n \n var result = List[Int]()\n var s = 0\n \n while(n > 0) {\n result = floors drop k\n s += (floors take k).max * 2\n floors = result\n n -= k\n }\n \n println(s)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k) = readInts(2)\n val fs = readInts(n).sorted.reverse\n\n var ans = 0L\n var pos = 0\n \n while (pos < n) {\n ans += 2 * (fs(pos) - 1)\n pos += k\n }\n \n println(ans)\n}"}, {"source_code": "object B {\n def READ: Array[Int] = readLine() split (\" \") map (_.toInt);\n\n def main(args: Array[String]) {\n var Array(n, k) = READ;\n var f:Array[Int] = READ;\n println(f.sorted.reverse.zipWithIndex.filter(_._2 % k == 0) map (2*_._1 -2) sum)\n }\n }\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by Kuang.Ru on 14-10-9.\n */\nobject B472 extends App{\n val sc = new Scanner(System.in)\n val n, k = sc.nextInt()\n var i = 0\n val f = new ArrayBuffer[Int]()\n\n while (i < n) {\n f += sc.nextInt()\n i += 1\n }\n\n val newF = f.sorted\n var time = 0\n i = newF.length - 1\n\n while (i >= 0) {\n time += (newF(i) - 1) * 2\n i -= k\n }\n\n println(time)\n}\n"}, {"source_code": "import Array._\n\nobject main extends App with fastIO {\n \n val Array(n, k) = readLine split(\" \") map(_.toInt)\n println(readLine.split(\" \").map(_.toInt).sortWith(_ > _).sliding(k, k).map(_.max - 1).sum * 2) \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}"}, {"source_code": "object Elevator extends App {\n\n def applyToChunks(seq: List[Int], length: Int, fun: List[Int] => Int): List[Int] = {\n seq match {\n case Nil => Nil\n case x: List[Int] => fun(x.take(length)) :: applyToChunks(x.drop(length), length, fun)\n }\n } \n\n val nk: String = readLine()\n val ff: String = readLine()\n\n val Array(n: Int, k: Int) = nk.split(' ').map(_.toInt)\n val f: List[Int] = ff.split(' ').map(_.toInt).sortBy(x => -x).toList\n\n val result: Int = applyToChunks(f, k, { x => (x.max - 1) * 2 }).sum\n\n println(result)\n\n}\n\n"}], "negative_code": [{"source_code": "import scala.math._\nimport scala.util.Sorting._\n\nobject Main extends App{\n val pass = readLine.split(\" \").map(x => x.toInt)\n var n = pass(0)\n var k = pass(1)\n \n var floors = readLine.split(\" \").map(x => x.toInt - 1).sorted.toList\n \n var result = List[Int]()\n var s = 0\n \n while(n > 0) {\n result = floors drop k\n s += (floors take k).max * 2\n floors = result\n n -= k\n }\n \n println(s)\n}"}], "src_uid": "b8d8f0e86ecb600f7559a6aec629946e"} {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, m, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val t = n / k\n val ans =\n if (t >= m) m\n else t - 1 - (m - t - 1) / (k - 1)\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "//package codeforces.contests._1359\n\nobject _1 {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(n, m, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val each = n / k\n\n val first = each min m\n\n val remaining = m - first\n\n val second = remaining / (k - 1) + (if (remaining % (k-1) != 0) 1 else 0)\n\n println {\n if (first == second) 0 else first - second\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toInt)\n val (n, m, k) = (input(0), input(1), input(2))\n val c = n / k\n val m1 = c min m\n if (k == 1) println(m)\n else {\n // k-1 person m - m1 joker\n val m2 = if ((m-m1) % (k-1) == 0) (m-m1)/(k-1) else (m-m1)/(k-1)+1\n println(0 max (m1 - m2))\n }\n }\n }\n}"}, {"source_code": "object ProblemA extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n\n for (_ <- 1 to t) {\n val n = in.nextInt()\n val m = in.nextInt()\n val k = in.nextInt()\n\n val maxCount = math.min(m, n / k)\n val leftCount = m - maxCount\n val maxOponent = leftCount / (k - 1) + (if (leftCount % (k - 1) > 0) 1 else 0)\n\n println(math.max(0, maxCount - maxOponent))\n }\n\n\n}"}], "negative_code": [{"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, m, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val t = n / k\n val ans =\n if (t >= m) m\n else t - ((m - t) / (k - 1) + (m - t) % (k - 1))\n\n println(ans)\n }\n}\n"}], "src_uid": "6324ca46b6f072f8952d2619cb4f73e6"} {"source_code": "object CF_540_3_B {\n// date: 19/02/2019\n\n type In = (Int, Seq[Int])\n type Out = Int\n \n def solve(in: In): Out = {\n val (n, xs) = in\n val totals = Array(0,0)\n val m = collection.mutable.Map[Int,Int]() withDefaultValue 0\n xs.indices foreach { i =>\n m += (i -> (xs(i) + totals(i%2)))\n totals(i%2) += xs(i)\n }\n xs.indices count { i =>\n m(i-1) + totals(i%2) - m(i) == m(i-2) + totals((i+1)%2) - m(i-1)\n }\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, {i.nextLine; i.intSeq})\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n // `a` MUST be > 0. Incorrect otherwise.\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val cumE, cumO = Array.ofDim[Int](N + 1)\n REP(N) { i =>\n cumE(i + 1) = cumE(i)\n cumO(i + 1) = cumO(i)\n if (i % 2 == 0) cumE(i + 1) += A(i)\n else cumO(i + 1) += A(i)\n }\n\n// debug(cumE)\n// debug(cumO)\n\n var ans = 0\n REP(N) { i =>\n val even = cumE(i) + (cumO(N) - cumO(i + 1))\n val odd = cumO(i) + (cumE(N) - cumE(i + 1))\n if (even == odd) ans += 1\n }\n\n out.println(ans)\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object CF_540_3_B {\n// date: 19/02/2019\n\n type In = (Int, Seq[Int])\n type Out = Int\n \n def solve(in: In): Out = {\n val (n, xs) = in\n val arr = Array.ofDim[Int](xs.length)\n val totals = Array(0,0)\n val m = collection.mutable.Map[Int,Int]() withDefaultValue 0\n for {\n i <- arr.indices\n } {\n m += (i -> (xs(i) + totals(i%2)))\n totals(i%2) += xs(i)\n }\n var goodCount = 0\n for {\n i <- arr.indices\n } {\n val E1 = m(i-1) + totals(i%2) - m(i)\n val E2 = m(i-2) + totals((i+1)%2) - m(i-1)\n if(E1 == E2) goodCount += 1\n }\n goodCount\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, {i.nextLine; i.intSeq})\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n // `a` MUST be > 0. Incorrect otherwise.\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}], "negative_code": [], "src_uid": "dcc380c544225c8cadf0df8d8b6ffb4d"} {"source_code": "import java.io._\nimport java.util._\nimport java.util.StringTokenizer\n\nimport scala.util.Sorting\n\nobject Solution {\n def gcd(a: Long, b: Long): (Long, Long) = {\n if (a == 0)\n return (0, 1)\n if (b == 0)\n return (1, 0)\n val t = gcd(b % a, a)\n val x = t._2 - (b / a) * t._1\n val y = t._1\n return (x, y)\n }\n\n def getInv(x: Long, mod: Long): Long = {\n val t = gcd(x, mod)\n return t._1\n }\n\n def solve(in: FastScanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val m = in.nextInt()\n val dx = in.nextInt()\n val dy = in.nextInt()\n val count = new Array[Int](n)\n for (i <- 0 until m) {\n val x = in.nextInt()\n val y = in.nextInt()\n val inv: Long = getInv(dx, n)\n val k: Long = (-x * inv % n + n) % n\n val startY: Int = ((y + k * dy) % n).toInt\n count(startY) += 1\n }\n var maxY = 0\n for (i <- 0 until n)\n if (count(i) > count(maxY))\n maxY = i\n out.println(0 + \" \" + maxY)\n }\n\n def main(args: Array[String]): Unit = {\n val in = new FastScanner(System.in)\n val out = new PrintWriter(System.out)\n solve(in, out)\n out.flush()\n }\n\n class FastScanner(val in: InputStream) {\n var st: StringTokenizer = null\n var br = new BufferedReader(new InputStreamReader(in))\n\n def next(): String = {\n while (st == null || !st.hasMoreTokens()) {\n val line = br.readLine()\n if (line == null)\n throw new IOException()\n st = new StringTokenizer(line)\n }\n return st.nextToken()\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def close(): Unit = {\n br.close()\n }\n }\n\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m, dx, dy) = readInts(4)\n \n val idx = BigInt(dx).modInverse(n).toLong\n val idy = BigInt(dy).modInverse(n).toLong\n \n val cnt = Array.fill(n){ 0 }\n\n for (i <- 0 until m) {\n val Array(x, y) = readInts(2)\n val s = idx * (n - x) % n\n val Y = (y + dy * s) % n\n cnt(Y.toInt) += 1\n }\n \n var maxPos = 0\n \n for (i <- 0 until n) if (cnt(i) > cnt(maxPos)) maxPos = i\n \n println(s\"0 $maxPos\")\n}"}], "negative_code": [], "src_uid": "6a2fe1f7e767a508530e9d922740c450"} {"source_code": "object B732 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n val input = readInts(n)\n val sum = input.sum\n for(i <- 1 until n) {\n if(input(i) + input(i-1) < k)\n input(i) += math.max(k - input(i) - input(i-1), 0)\n }\n println(input.sum - sum)\n println(input.mkString(\" \"))\n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val line = in.next().split(' ').map(_.toInt)\n val (_, ans) = line.foldLeft(k, List.empty[Int]) {\n case((left, ans), el) =>\n val today = el + Math.max(0, k - left - el)\n (today, today :: ans)\n }\n println(ans.sum - line.sum)\n println(ans.reverse.mkString(\" \"))\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.immutable._\nimport scala.collection.mutable\n\n/**\n * Created by Andrew on 11-Jul-16.\n */\n\n\nobject Main extends App {\n\n def gcd (a: Int, b: Int): Int = if(b == 0) a else gcd(b,a%b)\n def lcm (a: Int, b: Int) = a*b/gcd(a,b)\n case class Res(val lst: List[Int], val cnt: Int)\n\n def additional_days(xs: List[Int], counter: Int, k: Int, buf: Int): Res = {\n if (xs.isEmpty) Res(List(buf), counter)\n else {\n var res = Res(List(), 0)\n if (buf + xs.head >= k) res = additional_days(xs.tail, counter, k, xs.head)\n else res = additional_days(xs.tail, counter + (k-(buf+xs.head)), k, k-buf)\n Res(buf :: res.lst, res.cnt)\n }\n }\n\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val k = sc.nextInt()\n val xs = List.range(0, n).map(_ => sc.nextInt())\n val res = additional_days(xs.tail, 0, k, xs.head)\n println(res.cnt)\n res.lst foreach { x => print(x); print(' ')}\n}\n"}, {"source_code": "import java.io._\nimport scala.io.Source\n\nimport scala.annotation.tailrec\n\nobject ProblemB {\n def main(args: Array[String]): Unit = processStdInOut()\n\n def processStdInOut(): Unit = {\n val src = Source.fromInputStream(System.in)\n processFromSource(src)\n }\n\n def processFromSource(src: Source): Unit = {\n try {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out));\n try {\n val lines = src.getLines()\n processLines(lines, bw)\n } finally {\n bw.flush()\n }\n } finally {\n src.close();\n }\n }\n\n // Standard code above, custom code below\n\n import math._\n\n def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {\n\n val line1 = lines.next()\n val line1Strings = line1.split(\" \")\n val n = line1Strings(0).toInt\n val k = line1Strings(1).toInt\n val line2 = lines.next()\n val aValues = line2.split(\" \").map(_.toInt)\n val soln = solve(n, k, aValues)\n bw.write(soln.extraWalks.toString)\n bw.newLine()\n bw.write(soln.b.mkString(\" \"))\n bw.newLine()\n }\n\n case class Solution(val extraWalks: Int, val b: Seq[Int])\n\n def solve(n: Int, k: Int, a: IndexedSeq[Int]): Solution = {\n case class Accumulator(walksOnPreviousDay: Int, solution: Solution)\n\n val b = Array.ofDim[Int](n)\n b(0) = a(0)\n for (i <- 1 until n) {\n b(i) = math.max(a(i), k - b(i - 1))\n }\n val extraWalks = a.zip(b).map(x => x._2 - x._1).sum\n Solution(extraWalks, b)\n }\n}\n"}, {"source_code": "object B732 extends App {\n val init = readLine split \" \" map(_.toInt)\n val k = init(1)\n\n val steps = readLine split \" \" map(_.toInt)\n var n = 0\n val result = steps.tail.foldLeft(List(steps head))((a, el) =>\n if (a.head + el < k) {\n val t = k - el - a.head\n n = n + t\n (t + el) :: a\n } else el :: a\n ) \n \n println(n)\n println(result.reverse.mkString(\" \"))\n}"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _732B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n, k = read[Int]\n val walks = read[Array, Int](n)\n var ans = 0\n\n until(n-1) foreach {i =>\n val d1 = walks(i)\n val d2 = walks(i + 1)\n val needed = k - (d1 + d2)\n if (needed > 0) {\n walks(i + 1) += needed\n ans += needed\n }\n }\n\n writeLine(ans).writeAll(walks, \" \")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.language.postfixOps\nimport scala.math.max\n\nobject TaskB extends App {\n val sc = new Scanner(System.in)\n val (n, k) = (sc.nextInt, sc.nextInt)\n // val as = new Array[Int](n)\n var walks = 0\n var prev = 0\n\n val out = 0 until n map { i =>\n val a = sc.nextInt\n val b = if (i > 0) max(k - a - prev, 0) else 0\n walks += b\n prev = a + b\n prev\n } mkString \" \"\n\n println(walks)\n println(out)\n}\n"}], "negative_code": [], "src_uid": "1956e31a9694b4fd7690f1a75028b9a1"} {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m, k) = in.next().split(' ').map(_.toInt)\n val a: Array[Int] = in.next().split(' ').map(_.toInt - 1)\n val reverse = Array.ofDim[Int](n)\n a.indices.foreach {\n i => reverse(a(i)) = i\n }\n val b: Array[Int] = in.next().split(' ').map(_.toInt - 1)\n println(b.foldLeft(0l) {\n case(count, el) if reverse(el) == 0 => count + 1\n case(count, el) =>\n val position = reverse(el)\n val prevElement = a(position - 1)\n val press = 1 + position / k\n a(position - 1) = el\n a(position) = prevElement\n reverse(prevElement) = position\n reverse(el) = position - 1\n count + press\n })\n}\n", "positive_code": [{"source_code": "object Smartphone {\n def main(args: Array[String]): Unit = {\n val Array(n, m, k) = readLine.split(' ').map(_.toLong)\n val aa = readLine.split(' ').map(_.toLong).toList\n val bb = readLine.split(' ').map(_.toLong).toList\n\n val positionToApp = scala.collection.mutable.Map(aa.zipWithIndex.map(_.swap): _*)\n val appToPosition = scala.collection.mutable.Map(aa.zipWithIndex: _*)\n\n val steps = for (currentApp <- bb) yield {\n val currentAppPosition = appToPosition(currentApp)\n if (currentAppPosition > 0) {\n // Swap\n val appToSwap = positionToApp(currentAppPosition - 1)\n // swap positionToApp Map\n val temp1 = positionToApp(currentAppPosition)\n positionToApp(currentAppPosition) = positionToApp(currentAppPosition - 1)\n positionToApp(currentAppPosition - 1) = temp1\n // swap appToPosition Map\n val temp2 = appToPosition(currentApp)\n appToPosition(currentApp) = appToPosition(appToSwap)\n appToPosition(appToSwap) = temp2\n }\n currentAppPosition / k + 1\n }\n val result = steps.sum\n\n println(result)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util\nimport java.util._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val k = nextInt\n // val screenNumber = new Array[Int](n)\n val rank = new Array[Int](n)\n val valueByRank = new util.HashMap[Int, Int]()\n for (i <- 0 until n) {\n val j: Int = nextInt - 1\n // screenNumber(j) = Math.ceil(i / k).toInt\n rank(j) = i\n valueByRank.put(i, j)\n }\n var ans = 0L\n for (i <- 0 until m) {\n val b = nextInt - 1\n ans += Math.ceil(rank(b) / k).toInt + 1\n if (rank(b) != 0) {\n val next = valueByRank.get(rank(b) - 1)\n val pS = rank(b)\n val pN = rank(next)\n rank(b) = pN\n rank(next) = pS\n valueByRank.put(pN, b)\n valueByRank.put(pS, next)\n }\n }\n out.println(ans)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}, {"source_code": "import java.io._\nimport java.util\nimport java.util._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val k = nextInt\n val order = new Array[Int](n)\n val rank = new Array[Int](n)\n for (i <- 0 until n) {\n val j = nextInt - 1\n order(i) = j\n rank(j) = i\n }\n var ans:Long = 0L\n for (i <- 0 until m) {\n val b = nextInt - 1\n ans += Math.ceil(rank(b) / k).toLong + 1\n if (rank(b) != 0) {\n val next = order(rank(b) - 1)\n val pS = rank(b)\n val pN = rank(next)\n rank(b) = pN\n rank(next) = pS\n order(pN) = b\n order(pS) = next\n }\n }\n out.println(ans)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\n\nobject AnyaSmartphone {\n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n\n\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n\n def solve(as: IndexedSeq[Int], launchOrder: List[Int], k: Int) : Int = {\n def go(order : List[Int], id2Loc : Map[Int,Int], loc2Id: Map[Int,Int], moves: Int) : Int = order match {\n case Nil => moves\n case h :: t =>\n if (id2Loc(h) > 0) {\n /*println(s\"launching $h\")\n println(s\"id2Loc = $id2Loc\")\n println(s\"loc2Id= $loc2Id\")*/\n /*assert(id2Loc.keySet == (0 until as.size).toSet, \"keys van id2Loc verkeerd\")\n assert(id2Loc.keySet.forall{p => loc2Id(id2Loc(p)) == p}, \"id2Loc and loc2Id not inverse\")*/\n val prevApp = loc2Id(id2Loc(h) - 1)\n go(t,\n id2Loc - h - prevApp + (h -> (id2Loc(h)-1)) + (prevApp -> id2Loc(h)),\n loc2Id - id2Loc(h) - (id2Loc(h)-1) + (id2Loc(h)->prevApp) + ((id2Loc(h)-1)-> h),\n moves + id2Loc(h) / k + 1)\n } else {\n go(t,id2Loc,loc2Id,moves+1)\n }\n }\n go(launchOrder,\n as.zipWithIndex.toMap,\n as.zipWithIndex.map{ case (x,y) => (y,x)}.toMap,\n 0)\n }\n\n def solve2(as: Array[Int], launchOrder: List[Int], k: Int) : Long = {\n val id2Loc = as.zipWithIndex.toList.sortBy(_._1).map(_._2).toArray\n val loc2Id = as.clone()\n def go(order : List[Int], moves: Long) : Long = order match {\n case Nil => moves\n case h :: t => {\n /* println(s\"launching $h\")\n println(s\"id2Loc = \" + id2Loc.mkString(\",\"))\n println(s\"loc2Id= \" + loc2Id.mkString(\",\"))\n assert((0 until id2Loc.length).forall{i => id2Loc(loc2Id(i)) == i}, \"not inverse\")*/\n val curAppLoc = id2Loc(h)\n if (curAppLoc > 0) {\n val prevAppIdd = loc2Id(curAppLoc - 1)\n loc2Id(curAppLoc) = prevAppIdd\n loc2Id(curAppLoc - 1) = h\n id2Loc(h) = curAppLoc - 1\n id2Loc(prevAppIdd) = curAppLoc\n go(t, moves + curAppLoc/k + 1)\n } else {\n go(t, moves + 1)\n }\n }\n }\n go(launchOrder, 0)\n\n }\n\n def main (args: Array[String]) {\n val (n,m,k) = readTriple()\n val as = readInts().map(_ - 1)\n val launchOrder = readInts().map(_ - 1)\n\n println(solve2(as,launchOrder.toList,k))\n\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable.HashMap\n\nobject Main extends App {\n\n val Array(n,m,k) = readLine.split(\" \").map(_.toInt)\n val as = readLine.split(\" \").map(_.toInt)\n val bs = readLine.split(\" \").map(_.toInt)\n\n def touch(pos: Int): Int = (pos / k) + 1\n\n val front = HashMap[Int, Int]()\n val back = HashMap[Int, Int]()\n\n as.zipWithIndex foreach { case (v, pos) =>\n front += (v -> pos)\n back += (pos -> v)\n }\n\n println(bs.map({ app =>\n val pos = front.getOrElse(app, 0)\n if(pos != 0) {\n val prevApp = back.getOrElse(pos-1, 0)\n front += (app -> (pos - 1))\n front += (prevApp -> pos)\n back += ((pos-1) -> app)\n back += (pos -> prevApp)\n }\n touch(pos)\n }).map(_.toLong).sum)\n\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m, k) = in.next().split(' ').map(_.toInt)\n val a: Array[Int] = in.next().split(' ').map(_.toInt - 1)\n val reverse = Array.ofDim[Int](n)\n a.indices.foreach {\n i => reverse(a(i)) = i\n }\n val b: Array[Int] = in.next().split(' ').map(_.toInt - 1)\n println(b.foldLeft(0) {\n case(count, el) if reverse(el) == 0 => count + 1\n case(count, el) =>\n val position = reverse(el)\n val prevElement = a(position - 1)\n val press = 1 + position / k\n a(position - 1) = el\n a(position) = prevElement\n reverse(prevElement) = position\n reverse(el) = position - 1\n count + press\n })\n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m, k) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toInt - 1).zipWithIndex.toMap\n val b = in.next().split(' ').map(_.toInt - 1)\n println(b.foldLeft((a, a.map(i => i._2 -> i._1), 0)) {\n case((map, reverse, count), 0) =>\n val position = map(0)\n (map, reverse, count + 1)\n case((map, reverse, count), el) =>\n val position = map(el)\n val prevElement = reverse(position - 1)\n val press = 1 + position / k\n (map + (el -> (position - 1)) + (prevElement -> position),\n reverse + (position -> prevElement) + ((position - 1) -> el), count + press)\n }._3)\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val k = nextInt\n val a = new Array[Int](n)\n val screenNumber = new Array[Int](n)\n for (i <- 0 until n) {\n screenNumber(nextInt - 1) = Math.ceil((i + 1) / k).toInt\n }\n var ans = 0L\n for (i <- 0 until m) {\n val b = nextInt - 1\n ans += screenNumber(b) + 1\n if (b != 0) {\n val prevS = screenNumber(b)\n val prevN = screenNumber(b - 1)\n screenNumber(b) = prevN\n screenNumber(b - 1) = prevS\n }\n }\n out.println(ans)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util\nimport java.util._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val k = nextInt\n // val screenNumber = new Array[Int](n)\n val rank = new Array[Int](n)\n val valueByRank = new util.HashMap[Int, Int]()\n for (i <- 0 until n) {\n val j: Int = nextInt - 1\n // screenNumber(j) = Math.ceil(i / k).toInt\n rank(j) = i\n valueByRank.put(i, j)\n }\n var ans = 0L\n for (i <- 0 until m) {\n val b = nextInt - 1\n ans += Math.ceil(rank(b) / k).toInt + 1\n if (b != 0) {\n val next = valueByRank.get(rank(b) - 1)\n val pS = rank(b)\n val pN = rank(next)\n rank(b) = pN\n rank(next) = pS\n valueByRank.put(pN, b)\n valueByRank.put(pS, next)\n }\n }\n out.println(ans)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val k = nextInt\n val a = new Array[Int](n)\n val screenNumber = new Array[Int](n)\n for (i <- 0 until n) {\n screenNumber(nextInt - 1) = Math.ceil(i / k).toInt\n }\n var ans = 0L\n for (i <- 0 until m) {\n val b = nextInt - 1\n ans += screenNumber(b) + 1\n if (b != 0) {\n val prevS = screenNumber(b)\n\n val prevN = screenNumber(b - 1)\n screenNumber(b) = prevN\n screenNumber(b - 1) = prevS\n }\n }\n out.println(ans)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\n\nobject AnyaSmartphone {\n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n\n\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n\n def solve(as: IndexedSeq[Int], launchOrder: List[Int], k: Int) : Int = {\n def go(order : List[Int], id2Loc : Map[Int,Int], loc2Id: Map[Int,Int], moves: Int) : Int = order match {\n case Nil => moves\n case h :: t =>\n if (id2Loc(h) > 0) {\n /*println(s\"launching $h\")\n println(s\"id2Loc = $id2Loc\")\n println(s\"loc2Id= $loc2Id\")*/\n /*assert(id2Loc.keySet == (0 until as.size).toSet, \"keys van id2Loc verkeerd\")\n assert(id2Loc.keySet.forall{p => loc2Id(id2Loc(p)) == p}, \"id2Loc and loc2Id not inverse\")*/\n val prevApp = loc2Id(id2Loc(h) - 1)\n go(t,\n id2Loc - h - prevApp + (h -> (id2Loc(h)-1)) + (prevApp -> id2Loc(h)),\n loc2Id - id2Loc(h) - (id2Loc(h)-1) + (id2Loc(h)->prevApp) + ((id2Loc(h)-1)-> h),\n moves + id2Loc(h) / k + 1)\n } else {\n go(t,id2Loc,loc2Id,moves+1)\n }\n }\n go(launchOrder,\n as.zipWithIndex.toMap,\n as.zipWithIndex.map{ case (x,y) => (y,x)}.toMap,\n 0)\n }\n\n def solve2(as: Array[Int], launchOrder: List[Int], k: Int) : Int = {\n val id2Loc = as.zipWithIndex.toList.sortBy(_._1).map(_._2).toArray\n val loc2Id = as.clone()\n def go(order : List[Int], moves: Int) : Int = order match {\n case Nil => moves\n case h :: t => {\n /* println(s\"launching $h\")\n println(s\"id2Loc = \" + id2Loc.mkString(\",\"))\n println(s\"loc2Id= \" + loc2Id.mkString(\",\"))\n assert((0 until id2Loc.length).forall{i => id2Loc(loc2Id(i)) == i}, \"not inverse\")*/\n val curAppLoc = id2Loc(h)\n if (curAppLoc > 0) {\n val prevAppIdd = loc2Id(curAppLoc - 1)\n loc2Id(curAppLoc) = prevAppIdd\n loc2Id(curAppLoc - 1) = h\n id2Loc(h) = curAppLoc - 1\n id2Loc(prevAppIdd) = curAppLoc\n go(t, moves + curAppLoc/k + 1)\n } else {\n go(t, moves + 1)\n }\n }\n }\n go(launchOrder, 0)\n\n }\n\n def main (args: Array[String]) {\n val (n,m,k) = readTriple()\n val as = readInts().map(_ - 1)\n val launchOrder = readInts().map(_ - 1)\n\n println(solve2(as,launchOrder.toList,k))\n\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\n\nobject AnyaSmartphone {\n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n\n\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n\n def solve(as: IndexedSeq[Int], launchOrder: List[Int], k: Int) : Int = {\n def go(order : List[Int], id2Loc : Map[Int,Int], loc2Id: Map[Int,Int], moves: Int) : Int = order match {\n case Nil => moves\n case h :: t =>\n if (id2Loc(h) > 0) {\n val prevApp = loc2Id(id2Loc(h) - 1)\n go(t,\n id2Loc - h - prevApp + (h -> (id2Loc(h)-1)) + (prevApp -> id2Loc(h)),\n loc2Id - loc2Id(h) - (loc2Id(h)-1) + (loc2Id(h)->prevApp) + ((loc2Id(h)-1)-> h),\n moves + id2Loc(h) / k + 1)\n } else {\n go(t,id2Loc,loc2Id,moves+1)\n }\n }\n go(launchOrder,\n as.zipWithIndex.toMap,\n as.zipWithIndex.map{ case (x,y) => (y,x)}.toMap,\n 0)\n }\n\n def main (args: Array[String]) {\n val (n,m,k) = readTriple()\n val as = readInts().map(_ - 1)\n val launchOrder = readInts().map(_ - 1)\n\n println(solve(as,launchOrder.toList,k))\n\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable.HashMap\n\nobject Main extends App {\n\n val Array(n,m,k) = readLine.split(\" \").map(_.toInt)\n val as = readLine.split(\" \").map(_.toInt)\n val bs = readLine.split(\" \").map(_.toInt)\n\n def touch(pos: Int): Int = (pos / k) + 1\n\n val front = HashMap[Int, Int]()\n val back = HashMap[Int, Int]()\n\n as.zipWithIndex foreach { case (v, pos) =>\n front += (v -> pos)\n back += (pos -> v)\n }\n\n println(bs.map({ app =>\n val pos = front.getOrElse(app, 0)\n if(pos != 0) {\n val prevApp = back.getOrElse(pos-1, 0)\n front += (app -> (pos - 1))\n front += (prevApp -> pos)\n back += ((pos-1) -> app)\n back += (pos -> prevApp)\n }\n touch(pos)\n }).sum)\n\n}"}, {"source_code": "object Smartphone {\n def main(args: Array[String]): Unit = {\n val Array(n, m, k) = readLine.split(' ').map(_.toInt)\n val aa = readLine.split(' ').map(_.toInt).toList\n val bb = readLine.split(' ').map(_.toInt).toList\n\n val positionToApp = scala.collection.mutable.Map(aa.zipWithIndex.map(_.swap): _*)\n val appToPosition = scala.collection.mutable.Map(aa.zipWithIndex: _*)\n\n val steps = for (currentApp <- bb) yield {\n val currentAppPosition = appToPosition(currentApp)\n if (currentAppPosition > 0) {\n // Swap\n val appToSwap = positionToApp(currentAppPosition - 1)\n // swap positionToApp Map\n val temp1 = positionToApp(currentAppPosition)\n positionToApp(currentAppPosition) = positionToApp(currentAppPosition - 1)\n positionToApp(currentAppPosition - 1) = temp1\n // swap appToPosition Map\n val temp2 = appToPosition(currentApp)\n appToPosition(currentApp) = appToPosition(appToSwap)\n appToPosition(appToSwap) = temp2\n }\n currentAppPosition / k + 1\n }\n val result = steps.sum\n\n println(result)\n }\n}\n"}], "src_uid": "3b0fb001333e53da458e1fb7ed760e32"} {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject C_1187_editorial extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n val A = Array.fill[Int](n + 1)(1)\n val notSorted = mutable.ArrayBuffer[(Int, Int)]()\n val sorted = mutable.ArrayBuffer[(Int, Int)]()\n\n 1 to m foreach { _ =>\n val Array(t, l, r) = readLine().split(\" \").map(_.toInt)\n\n if (t == 1) {\n sorted += ((l, r))\n (l until r).foreach { i =>\n A(i) = 0\n }\n } else {\n notSorted += ((l, r))\n (l until r).foreach { i =>\n if (A(i) == 1) A(i) = -1\n }\n }\n }\n\n def isSorted: Boolean = {\n sorted.foreach {\n case (l, r) =>\n (l + 1 to r).foreach { i =>\n if (A(i - 1) > A(i)) {\n return false\n }\n }\n }\n true\n }\n\n def isNotSorted: Boolean = {\n notSorted.foreach {\n case (l, r) =>\n val allSorted = (l + 1 to r).forall { i =>\n A(i - 1) <= A(i)\n }\n if (allSorted) return false\n }\n true\n }\n\n var delta = A(1)\n A(1) = 1000000000 / 2\n\n (2 to n).foreach { i =>\n if (A(i) == 1) A(i) = -1\n val newDelta = A(i)\n A(i) = A(i - 1) + delta\n delta = newDelta\n }\n\n// println(\"YES\")\n// println(A.tail.mkString(\" \"))\n\n if (isSorted && isNotSorted) {\n println(\"YES\")\n println(A.tail.mkString(\" \"))\n } else {\n println(\"NO\")\n }\n\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n case class Range(l: Int, r: Int) {\n def contains(rg: Range): Boolean = l <= rg.l && rg.r <= r\n }\n\n def solve(): Unit = {\n import java.util.{Collections, Comparator}\n val N, M = ni()\n val sorted, unsorted, mergedSorted = new java.util.ArrayList[Range]\n REP(M) { _ =>\n val t, l, r = ni()\n if (t == 1) {\n sorted.add(Range(l, r))\n } else {\n unsorted.add(Range(l, r))\n }\n }\n\n Collections.sort(sorted, new Comparator[Range] {\n override def compare(o1: Range, o2: Range): Int = {\n Integer.compare(o1.l, o2.l)\n }\n })\n\n var l = 0\n var r = 0\n REP(sorted.size()) { i =>\n val rg = sorted.get(i)\n if (rg.l <= r) {\n r = max(r, rg.r)\n } else {\n if (l != 0) mergedSorted.add(Range(l, r))\n l = rg.l\n r = rg.r\n }\n }\n if (l != 0) mergedSorted.add(Range(l, r))\n debug(mergedSorted.toArray.mkString(\" \"))\n\n val ans = Array.ofDim[Int](N)\n var p = 0\n REP_r(N) { i =>\n p += 1\n ans(i) = p\n }\n REP_r(mergedSorted.size) { i =>\n val rg = mergedSorted.get(i)\n var num = ans(rg.r - 1)\n TO(rg.l, rg.r) { j =>\n ans(j - 1) = num\n num += 1\n }\n }\n\n def test: Boolean = {\n REP(sorted.size) { i =>\n val rg = sorted.get(i)\n var found = false\n TO(rg.l, rg.r - 1) { j =>\n if (j > rg.l - 1 && ans(j) < ans(j-1)) found = true\n }\n debug(s\"found:$found\")\n if (found) return false\n }\n REP(unsorted.size) { i =>\n val rg = unsorted.get(i)\n var found = false\n TO(rg.l, rg.r - 1) { j =>\n if (j > rg.l - 1 && ans(j) < ans(j-1)) found = true\n }\n if (!found) return false\n }\n true\n }\n\n debug(ans)\n if (!test) out.println(\"NO\")\n else {\n out.println(\"YES\")\n out.println(ans.mkString(\" \"))\n }\n\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n case class Range(l: Int, r: Int) {\n def contains(rg: Range): Boolean = l <= rg.l && rg.r <= r\n }\n\n def solve(): Unit = {\n import java.util.{Collections, Comparator}\n val N, M = ni()\n val sorted, unsorted, mergedSorted = new java.util.ArrayList[Range]\n REP(M) { _ =>\n val t, l, r = ni()\n if (t == 1) {\n sorted.add(Range(l, r))\n } else {\n unsorted.add(Range(l, r))\n }\n }\n\n Collections.sort(sorted, new Comparator[Range] {\n override def compare(o1: Range, o2: Range): Int = {\n Integer.compare(o1.l, o2.l)\n }\n })\n\n var l = 0\n var r = 0\n REP(sorted.size()) { i =>\n val rg = sorted.get(i)\n if (rg.l <= r) {\n r = rg.r\n } else {\n if (l != 0) mergedSorted.add(Range(l, r))\n l = rg.l\n r = rg.r\n }\n }\n if (l != 0) mergedSorted.add(Range(l, r))\n debug(mergedSorted.toArray.mkString(\" \"))\n\n def test: Boolean = {\n REP(unsorted.size()) { i =>\n REP(mergedSorted.size()) { j =>\n if (mergedSorted.get(j).contains(unsorted.get(i))) return false\n }\n }\n true\n }\n\n if (!test) out.println(\"NO\")\n else {\n out.println(\"YES\")\n val ans = Array.ofDim[Int](N)\n var p = 0\n REP_r(N) { i =>\n p += 1\n ans(i) = p\n }\n REP_r(mergedSorted.size) { i =>\n val rg = mergedSorted.get(i)\n TO(rg.l, rg.r) { j =>\n ans(j - 1) = ans(rg.r - 1)\n }\n }\n out.println(ans.mkString(\" \"))\n }\n\n }\n}"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n case class Range(l: Int, r: Int) {\n def contains(rg: Range): Boolean = l <= rg.l && rg.r <= r\n }\n\n def solve(): Unit = {\n import java.util.{Collections, Comparator}\n val N, M = ni()\n val sorted, unsorted, mergedSorted = new java.util.ArrayList[Range]\n REP(M) { _ =>\n val t, l, r = ni()\n if (t == 1) {\n sorted.add(Range(l, r))\n } else {\n unsorted.add(Range(l, r))\n }\n }\n\n Collections.sort(sorted, new Comparator[Range] {\n override def compare(o1: Range, o2: Range): Int = {\n Integer.compare(o1.l, o2.l)\n }\n })\n\n var l = 0\n var r = 0\n REP(sorted.size()) { i =>\n val rg = sorted.get(i)\n if (rg.l <= r) {\n r = rg.r\n } else {\n if (l != 0) mergedSorted.add(Range(l, r))\n l = rg.l\n r = rg.r\n }\n }\n if (l != 0) mergedSorted.add(Range(l, r))\n debug(mergedSorted.toArray.mkString(\" \"))\n\n val ans = Array.ofDim[Int](N)\n var p = 0\n REP_r(N) { i =>\n p += 1\n ans(i) = p\n }\n REP_r(mergedSorted.size) { i =>\n val rg = mergedSorted.get(i)\n var num = ans(rg.r - 1)\n TO(rg.l, rg.r) { j =>\n ans(j - 1) = num\n num += 1\n }\n }\n\n def test: Boolean = {\n REP(sorted.size) { i =>\n val rg = sorted.get(i)\n var found = false\n TO(rg.l, rg.r - 1) { j =>\n if (j > rg.l - 1 && ans(j) < ans(j-1)) found = true\n }\n debug(s\"found:$found\")\n if (found) return false\n }\n REP(unsorted.size) { i =>\n val rg = unsorted.get(i)\n var found = false\n TO(rg.l, rg.r - 1) { j =>\n if (j > rg.l - 1 && ans(j) < ans(j-1)) found = true\n }\n if (!found) return false\n }\n true\n }\n\n debug(ans)\n if (!test) out.println(\"NO\")\n else {\n out.println(\"YES\")\n out.println(ans.mkString(\" \"))\n }\n\n }\n}"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n case class Range(l: Int, r: Int) {\n def contains(rg: Range): Boolean = l <= rg.l && rg.r <= r\n }\n\n def solve(): Unit = {\n import java.util.{Collections, Comparator}\n val N, M = ni()\n val sorted, unsorted, mergedSorted = new java.util.ArrayList[Range]\n REP(M) { _ =>\n val t, l, r = ni()\n if (t == 1) {\n sorted.add(Range(l, r))\n } else {\n unsorted.add(Range(l, r))\n }\n }\n\n Collections.sort(sorted, new Comparator[Range] {\n override def compare(o1: Range, o2: Range): Int = {\n Integer.compare(o1.l, o2.l)\n }\n })\n\n var l = 0\n var r = 0\n REP(sorted.size()) { i =>\n val rg = sorted.get(i)\n if (rg.l <= r) {\n r = rg.r\n } else {\n if (l != 0) mergedSorted.add(Range(l, r))\n l = rg.l\n r = rg.r\n }\n }\n if (l != 0) mergedSorted.add(Range(l, r))\n debug(mergedSorted.toArray.mkString(\" \"))\n\n def test: Boolean = {\n REP(unsorted.size()) { i =>\n REP(mergedSorted.size()) { j =>\n if (mergedSorted.get(j).contains(unsorted.get(i))) return false\n }\n }\n true\n }\n\n if (!test) out.println(\"NO\")\n else {\n out.println(\"YES\")\n val ans = Array.ofDim[Int](N)\n var p = 0\n REP_r(mergedSorted.size) { i =>\n p += 1\n val rg = mergedSorted.get(i)\n TO(rg.l, rg.r) { j =>\n ans(j - 1) = p\n }\n }\n REP_r(N) { i =>\n if (ans(i) == 0) {\n p += 1\n ans(i) = p\n }\n }\n out.println(ans.mkString(\" \"))\n }\n\n }\n}"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject C_1187 extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n var sorted = mutable.ArrayBuffer[(Int, Int)]()\n var unsorted = mutable.ArrayBuffer[(Int, Int)]().sortBy(_._1)\n\n val answer = Array.ofDim[Int](n)\n\n 1 to m foreach { _ =>\n val Array(t, l, r) = readLine().split(\" \").map(_.toInt)\n if (t == 1) sorted.append((l, r))\n else unsorted.append((l, r))\n }\n\n var counter = 1\n var lastSorted = counter - 1\n\n sorted.foreach {\n case (l, r) =>\n l to r foreach { i =>\n answer(i - 1) = counter\n lastSorted = counter\n counter += 1\n }\n }\n\n (0 until n).reverse foreach { i =>\n if (answer(i) == 0) {\n answer(i) = counter\n counter += 1\n }\n }\n\n unsorted.foreach {\n case (l, r) => {\n l to r foreach { i =>\n answer(i - 1) = counter\n counter += 1\n }\n\n if (answer(l - 1) < answer(r - 1)) {\n val tmp = answer(l - 1)\n answer(l - 1) = answer(r - 1)\n answer(r - 1) = tmp\n } else {\n // cannot fix or it's fixed\n }\n }\n }\n\n val isSorted = {\n sorted.forall {\n case (l, r) =>\n l until r forall { i =>\n answer(i - 1) <= answer(i)\n }\n }\n }\n\n if (isSorted) {\n println(\"YES\")\n println(answer.mkString(\" \"))\n } else {\n println(\"NO\")\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject C_1187 extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n var sorted = mutable.ArrayBuffer[(Int, Int)]()\n var unsorted = mutable.ArrayBuffer[(Int, Int)]().sortBy(_._1)\n\n val answer = Array.ofDim[Int](n)\n\n 1 to m foreach { _ =>\n val Array(t, l, r) = readLine().split(\" \").map(_.toInt)\n if (t == 1) sorted.append((l, r))\n else unsorted.append((l, r))\n }\n\n var counter = 1\n var lastSorted = counter - 1\n\n sorted.foreach {\n case (l, r) =>\n l to r foreach { i =>\n answer(i - 1) = counter\n lastSorted = counter\n counter += 1\n }\n }\n\n (0 until n).reverse foreach { i =>\n if (answer(i) == 0) {\n answer(i) = counter\n counter += 1\n }\n }\n\n unsorted.foreach {\n case (l, r) => {\n l to r foreach { i =>\n answer(i - 1) = counter\n counter += 1\n }\n\n if (answer(l - 1) < answer(r - 1)) {\n val tmp = answer(l - 1)\n answer(l - 1) = answer(r - 1)\n answer(r - 1) = tmp\n } else {\n // cannot fix or it's fixed\n }\n }\n }\n\n val isSorted = {\n sorted.forall {\n case (l, r) =>\n l + 1 until r forall { i =>\n answer(i - 1) <= answer(i)\n }\n }\n }\n\n if (isSorted) {\n println(\"YES\")\n println(answer.mkString(\" \"))\n } else {\n println(\"NO\")\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject C_1187_editorial extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n\n val A = Array.fill[Int](n + 1)(1)\n val notSorted = mutable.ArrayBuffer[(Int, Int)]()\n val sorted = mutable.ArrayBuffer[(Int, Int)]()\n\n 1 to m foreach { _ =>\n val Array(t, l, r) = readLine().split(\" \").map(_.toInt)\n\n if (t == 1) {\n sorted += ((l, r))\n (l until r).foreach { i =>\n A(i) = 0\n }\n } else {\n notSorted += ((l, r))\n (l until r).foreach { i =>\n if (A(i) == 1) A(i) = -1\n }\n }\n }\n\n def isSorted: Boolean = {\n sorted.foreach {\n case (l, r) =>\n (l + 1 to r).foreach { i =>\n if (A(i - 1) > A(i)) {\n return false\n }\n }\n }\n true\n }\n\n def isNotSorted: Boolean = {\n notSorted.foreach {\n case (l, r) =>\n val allSorted = (l + 1 to r).forall { i =>\n A(i - 1) <= A(i)\n }\n if (allSorted) return false\n }\n true\n }\n\n var delta = A(1)\n A(1) = 0\n\n (2 to n).foreach { i =>\n if (A(i) == 1) A(i) = -1\n val newDelta = A(i)\n A(i) = A(i - 1) + delta\n delta = newDelta\n }\n\n// println(\"YES\")\n// println(A.tail.mkString(\" \"))\n\n if (isSorted && isNotSorted) {\n println(\"YES\")\n println(A.tail.mkString(\" \"))\n } else {\n println(\"NO\")\n }\n\n}\n"}], "src_uid": "1522d9845b4ea1a903d4c81644797983"} {"source_code": "object CF_523_2_B extends App {\n def solve(as: Seq[Int]): Long = loop(as.filter(_>0).sortWith(_>_))\n\n def loop(as: Seq[Int], removed: Long = 0):Long = as match {\n // last column, keep them all and return result\n case Seq(last) => removed\n case c1 +: c2 +: _ =>\n // remove all blocks in c1 below height of c2\n if(c1 > c2) loop(as.tail, removed + c2)\n // if c2 same height or more, remove all but 1 of c1 reduce c2 to 1 below c1 if c1 is > 1\n else {\n val newc2 = math.max(1, c1 - 1)\n val toRemove = math.max(0, c1 - 1) + (c2 - newc2)\n loop(as.tail.updated(0, newc2), removed + toRemove)\n }\n }\n val io = new IO(System.in)\n io.int(); io.int()\n println(solve(io.intSeq()))\n}\n\n\n/// boilerplate utility methods:\nimport java.util.Scanner\n\nclass IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n // methods are side-effecting because they advance Scanner's pointer\n // extra nextLine is required to advance past the newline on the ints line\n def collect[T](f: String => T) = {sc.nextLine();sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def double() = sc.nextDouble()\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M = ni()\n val A = na(N)\n radixSort(A)\n var p = 0\n rep(N - 1) { i =>\n if (A(i) > p) p += 1\n }\n val remain = N - 1 + max(1, A(N - 1) - p) // [1, N - 1]に1こずつ配置\n val ans = sumL(A) - remain\n out.println(ans)\n }\n\n /**\n * 正の値のみのときだけ\n */\n def radixSort(f: Array[Int]): Array[Int] = radixSort(f, f.length)\n def radixSort(as: Array[Int], n: Int): Array[Int] = {\n val n = as.length\n val xs = Array(as, new Array[Int](n))\n val b = Array.ofDim[Int](65537)\n\n def step(k: Int, x: Int): Unit = {\n rep(n){ i => b(1 + (xs(x)(i) >>> k & 0xffff)) += 1 }\n rep(65536, 1){ i => b(i) += b(i - 1) }\n rep(n){ i =>\n val j = xs(x)(i) >>> k & 0xffff\n xs(x ^ 1)(b(j)) = xs(x)(i)\n b(j) += 1\n }\n }\n\n step(0, 0)\n java.util.Arrays.fill(b, 0)\n step(16, 1)\n\n as\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object MainB extends App {\n val (n, m) = {\n val l = scala.io.StdIn.readLine().split(\" \")\n (math.BigInt(l(0).toInt), math.BigInt(l(1).toInt))\n }\n val ns = scala.io.StdIn.readLine().split(\" \").map(i => math.BigInt(i.toInt)).sorted\n var d = 0\n for (i <- ns.indices) if (ns(i) > d) d += 1\n println(ns.sum - n - ns.max + d)\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M = ni()\n val A = na(N)\n if (N == 1) {\n out.println(0)\n } else {\n radixSort(A)\n\n val remain = N - 1 + max(1, A(N - 1) - A(N - 2))\n val ans = sumL(A) - remain\n out.println(ans)\n }\n }\n\n /**\n * 正の値のみのときだけ\n */\n def radixSort(f: Array[Int]): Array[Int] = radixSort(f, f.length)\n def radixSort(as: Array[Int], n: Int): Array[Int] = {\n val n = as.length\n val xs = Array(as, new Array[Int](n))\n val b = Array.ofDim[Int](65537)\n\n def step(k: Int, x: Int): Unit = {\n rep(n){ i => b(1 + (xs(x)(i) >>> k & 0xffff)) += 1 }\n rep(65536, 1){ i => b(i) += b(i - 1) }\n rep(n){ i =>\n val j = xs(x)(i) >>> k & 0xffff\n xs(x ^ 1)(b(j)) = xs(x)(i)\n b(j) += 1\n }\n }\n\n step(0, 0)\n java.util.Arrays.fill(b, 0)\n step(16, 1)\n\n as\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object CF_523_2_B extends App {\n def solve(as: Seq[Int]): Int = loop(as.filter(_>0).sortWith(_>_))\n\n def loop(as: Seq[Int], removed: Int = 0):Int = as match {\n // last column, keep them all and return result\n case Seq(last) => removed\n case c1 +: c2 +: _ =>\n // remove all blocks in c1 below height of c2\n if(c1 > c2) loop(as.tail, removed + c2)\n // if c2 same height or more, remove all but 1 of c1 reduce c2 to 1 below c1 if c1 is > 1\n else {\n val newc2 = math.max(1, c1 - 1)\n val toRemove = math.max(0, c1 - 1) + (c2 - newc2)\n loop(as.tail.updated(0, newc2), removed + toRemove)\n }\n }\n val io = new IO(System.in)\n io.int(); io.int()\n println(solve(io.intSeq()))\n}\n\n\n/// boilerplate utility methods:\nimport java.util.Scanner\n\nclass IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n // methods are side-effecting because they advance Scanner's pointer\n // extra nextLine is required to advance past the newline on the ints line\n def collect[T](f: String => T) = {sc.nextLine();sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def double() = sc.nextDouble()\n}"}, {"source_code": "object CF_523_2_B extends App {\n def solve(as: Seq[Int]): Int = loop(as.filter(_>0).sortWith(_>_))\n\n def loop(as: Seq[Int], removed: Int = 0):Int = as match {\n // last column, keep them all and return result\n case Seq(last) => removed\n case c1 +: c2 +: _ =>\n // remove all blocks in c1 below height of c2\n if(c1 > c2) loop(as.tail, removed + c2)\n // if c2 same height or more, remove all but 1 of c1 reduce c2 to 1 below c1 if c1 is > 1\n else {\n val newc2 = math.max(1, c1 - 1)\n val toRemove = math.max(0, c1 - 1) + (c2 - newc2)\n loop(as.tail.updated(0, newc2), removed + toRemove)\n }\n }\n val io = new IO(System.in)\n io.int(); io.int()\n solve(io.intSeq())\n}\n\n\n/// boilerplate utility methods:\nimport java.util.Scanner\n\nclass IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n // methods are side-effecting because they advance Scanner's pointer\n // extra nextLine is required to advance past the newline on the ints line\n def collect[T](f: String => T) = {sc.nextLine();sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def double() = sc.nextDouble()\n}"}, {"source_code": "object MainB extends App {\n val (n, m) = {\n val l = scala.io.StdIn.readLine().split(\" \")\n (math.BigInt(l(0).toInt), math.BigInt(l(1).toInt))\n }\n val ns = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n var d = 0\n for (i <- ns.indices) if (ns(i) > d) d += 1\n println(ns.sum - n - ns.max + d)\n}\n"}, {"source_code": "object MainB extends App {\n val (n, m) = {\n val l = scala.io.StdIn.readLine().split(\" \")\n (l(0).toInt, l(1).toInt)\n }\n val ns = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n var d = 0\n for (i <- ns.indices) if (ns(i) > d) d += 1\n println(ns.sum - n - ns.max + d)\n}\n"}], "src_uid": "ffa76f2558c8a70ab5c1ecb9e8561f25"} {"source_code": "object P7C {\n def eGcd(a : Long, b : Long) : (Long, Long, Long) = () match {\n case _ if a < 0L => eGcd(-a, b) match {case (p, q, d) => (-p, q, d)}\n case _ if b < 0L => eGcd(a, -b) match {case (p, q, d) => (p, -q, d)}\n case _ if a < b => eGcd(b, a) match {case (p, q, d) => (q, p, d)}\n case _ if b == 0L => (1, 0, a)\n case _ => eGcd(b, a % b) match {\n case (p, q, d) => (q, p - a / b * q, d)\n }\n }\n\n def main(args : Array[String]) {\n val Array(a, b, c) = readLine split ' ' map {_.toInt}\n val (p, q, d) = eGcd(a, b)\n if (c % d == 0) {\n val m = -c / d\n println(p * m + \" \" + q * m)\n } else {\n println(\"-1\")\n }\n }\n}\n", "positive_code": [{"source_code": "\n\nimport java.util.Scanner\n\nobject CStraight extends App {\n\n val scanner = new Scanner(System.in)\n\n val a = scanner.nextLong()\n val b = scanner.nextLong()\n val c = -scanner.nextLong()\n\n val res = gcd(a, b)\n if (c % res._1 == 0) {\n val x0 = res._2 * (c / res._1)\n val y0 = res._3 * (c / res._1)\n println(x0 + \" \" + y0)\n } else {\n println(\"-1\")\n }\n\n def gcd(a: Long, b: Long): (Long, Long, Long) = {\n if (a == 0) (b, 0, 1)\n else {\n val (g, x1, y1) = gcd(b % a, a)\n val x = y1 - (b / a) * x1\n val y = x1\n (g, x, y)\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "\n\nimport java.util.Scanner\n\nobject CStraight extends App {\n\n\n val scanner = new Scanner(System.in)\n\n val a = scanner.nextInt()\n val b = scanner.nextInt()\n val c = -scanner.nextInt()\n\n val res = gcd(a, b)\n if (c % res._1 == 0) {\n val x0 = res._2 * (c / res._1)\n val y0 = res._3 * (c / res._1)\n println(x0 + \" \" + y0)\n } else {\n println(\"-1\")\n }\n\n def gcd(a: Int, b: Int): (Int, Int, Int) = {\n if (a == 0) (b, 0, 1)\n else {\n val (g, x1, y1) = gcd(b % a, a)\n val x = y1 - (b / a) * x1\n val y = x1\n (g, x, y)\n }\n }\n\n}\n"}], "src_uid": "a01e1c545542c1641eca556439f0692e"} {"source_code": "\nobject B {\n\n def main(args: Array[String]): Unit = {\n\n //System.setIn(new FileInputStream(\"src/b.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"src/b.out\")))\n\n var Array(n, k, q) = readLine().split(\" \").map(_.toInt)\n var friends: Array[Int] = readLine().split(\" \").map(_.toInt)\n var screen: Set[Int] = Set.empty[Int]\n\n for(i <- 0 until q) {\n var Array(tp, id) = readLine().split(\" \").map(_.toInt)\n if(tp == 1) {\n if(screen.size < k || friends(id - 1) > screen.min) {\n screen += friends(id - 1)\n if(screen.size > k) {\n screen -= screen.min\n }\n }\n }\n else {\n if(screen.contains(friends(id - 1))) {\n println(\"YES\")\n }\n else {\n println(\"NO\")\n }\n }\n }\n\n }\n\n}\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, k, q) = in.next().split(' ').map(_.toInt)\n val t = in.next().split(' ').map(_.toInt)\n val window = Array.ofDim[Int](k)\n (1 to q).foreach { _ =>\n val Array(ty, id) = in.next().split(' ').map(_.toInt)\n if (ty == 1) {\n if (!window.contains(id)) {\n val min = window.indices.find(i => window(i) == 0).getOrElse(\n window.indices.minBy(i => t(window(i) - 1)))\n if (window(min) == 0 || t(window(min) - 1) < t(id - 1))\n window(min) = id\n }\n } else {\n if (window.contains(id))\n println(\"YES\")\n else\n println(\"NO\")\n }\n }\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k, q) = readInts(3)\n val ts = readInts(n)\n\n val sb = new StringBuilder\n\n val active = new mutable.TreeSet[Int]()(Ordering.by(ts))\n\n for (_ <- 0 until q) {\n readInts(2) match {\n case Array(1, id) =>\n active += (id - 1)\n while (active.size > k) {\n val min = active.head\n active.remove(min)\n }\n case Array(2, id) =>\n sb.append(if (active.contains(id - 1)) \"YES\\n\" else \"NO\\n\")\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(sb.result())\n\n Console.flush\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _658B extends CodeForcesApp {\n override def apply(io: IO) = {\n val n, k, q = io[Int]\n val t = io[IndexedSeq, Int](n)\n val pq = mutable.PriorityQueue.empty[Int](Ordering.by(id => -t(id - 1)))\n val ans = Vector.empty[Boolean]\n io.separator = \"\\n\"\n repeat(q) {\n val _ = io[(Int, Int)] match {\n case (1, id) =>\n pq += id\n if (pq.size > k) pq.dequeue()\n case (2, id) =>\n io += pq.exists(_ == id)\n }\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sum[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default\n }\n def memoize[I] = new {\n def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def appendNewLine(): this.type = {\n println()\n this\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "7c778289806ceed506543ef816c587c9"} {"source_code": "import java.util.Scanner\nimport java.math._\n\nobject B extends App\n{\n\tval cin=new Scanner(System.in)\n\tval n=cin.nextInt()\n\tif(n<3) println(-1)\n\telse if(n==3) println(210)\n\telse\n\t{\n\t\tval mod=math.BigInt(10).modPow(math.BigInt((n-1).toString),math.BigInt(210)).toInt\n\t\tval add=210-mod\t\n\t\tprintln(\"1\"+\"0\"*(n-4+3-add.toString.length)+add)\n\t}\n}\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val x = 2 * 3 * 5 * 7\n val n = in.next().toInt\n if (n < 3)\n println(-1)\n else if (n == 3)\n println(\"210\")\n else {\n val t = n - 3\n val left = Map(0 -> \"110\", 1 -> \"050\", 2 -> \"080\", 3 -> \"170\", 4 -> \"020\", 5 -> \"200\")(t % 6)\n println(\"1\" + \"0\" * (n - 4) + left)\n }\n}"}, {"source_code": "object B248 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n if(n < 3)\n println(\"-1\")\n else\n println((BigInt(10).pow(n-1)/210 + 1)*210)\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import collection.mutable.ArrayBuffer\n\nobject test2 extends App {\n val n=readLine.toInt\n if(n<=2){println(-1);exit}\n if(n==3){println(210);exit}\n\n var last=7-(1 until n-1).foldLeft(1){(x,y)=>x*10%7}\n while((last.toString.map(_-'0').sum+1)%3!=0) last+=7\n println(\"1\"+\"0\"*(n-2-last.toString.length)+last+\"0\")\n}\n\n"}, {"source_code": "import collection.mutable.ArrayBuffer\n\nobject test2 extends App {\n val n=readLine.toInt\n if(n<=2){println(-1);exit}\n if(n==3){println(210);exit}\n \n var start=1\n val dp=for(i<- 1 to n) yield \n {\n \tval mod=start%7\n \tstart=mod*10\n \tmod\n }\n\n var last=7-dp(n-2)\n while((last.toString.map(_-'0').sum+1)%3!=0) last+=7\n println(\"1\"+\"0\"*(n-2-last.toString.length)+last+\"0\")\n}\n\n"}, {"source_code": "object B{\n def main(args: Array[String]){\n\n val n=readLine.toInt\n\n if(n<=2){\n println(-1)\n }else if(n==3){\n println(210)\n }else{\n val amari=\n (1 to n-1).fold(1)((x,y)=> x*10%210)\n\n val add=210-amari\n print(\"1\")\n print(\"0\"*(n-4))\n println(\"%03d\".format(add))\n }\n }\n}\n"}], "negative_code": [{"source_code": "import collection.mutable.ArrayBuffer\n\nobject test2 extends App {\n val n=readLine.toInt\n if(n<=2){println(-1);exit}\n \n var start=1\n val dp=for(i<- 1 to n) yield \n {\n \tval mod=start%7\n \tstart=mod*10\n \tmod\n }\n \n for(i<- 1 until n-1 reverse)\n {\n\t var last=7%dp(i)\n\t while((last.toString.map(_-'0').sum+1)%3!=0)\n\t \t last+=7\n\n\t println(\"1\"+\"0\"*(i-last.toString.length)+last+\"0\"*(n-i-1))\n\t exit\n }\n}\n\n"}, {"source_code": "import collection.mutable.ArrayBuffer\n\nobject test2 extends App {\n val n=readLine.toInt\n if(n<=2){println(-1);exit}\n \n var start=1\n val dp=for(i<- 1 to n) yield \n {\n \tval mod=start%7\n \tstart=mod*10\n \tmod\n }\n\n var i=n-2\n var last=7-dp(i)\n\n while((last.toString.map(_-'0').sum+1)%3!=0) last+=7\n\n println(\"1\"+\"0\"*(i-last.toString.length)+last+\"0\"*(n-i-1))\n}\n\n"}, {"source_code": "import collection.mutable.ArrayBuffer\n\nobject test2 extends App {\n val n=readLine.toInt\n if(n<=2){println(-1);exit}\n \n var start=1\n val dp=for(i<- 1 to n) yield \n {\n \tval mod=start%7\n \tstart=mod*10\n \tmod\n }\n \n for(i<- 1 until n-1 reverse)\n {\n\t var last=7%dp(i)\n if((last+1)%3!=0 && last<3) last+=7\n if((last+1)%3==0)\n {\n \t println(\"1\"+\"0\"*(i-1)+last+\"0\"*(n-i-1))\n \t exit\n }\n }\n}\n\n"}, {"source_code": "import collection.mutable.ArrayBuffer\n\nobject test2 extends App {\n val n=readLine.toInt\n if(n<=2){println(-1);exit}\n \n var start=1\n val dp=for(i<- 1 to n) yield \n {\n \tval mod=start%7\n \tstart=mod*10\n \tmod\n }\n\n for(i<- 1 until n-1 reverse)\n {\n\t var last=7-dp(i)\n\n\t while((last.toString.map(_-'0').sum+1)%3!=0)\n\t {\n\t \t println(last)\n\t \t last+=7\n\t }\n\n\t println(\"1\"+\"0\"*(i-last.toString.length)+last+\"0\"*(n-i-1))\n\t exit\n }\n}\n\n"}], "src_uid": "386345016773a06b9e190a55cc3717fa"} {"source_code": "import scala.annotation.tailrec\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.BufferedWriter\nimport java.io.OutputStreamWriter\nimport java.io.PrintWriter\nobject Main {\n\n def main(args: Array[String]): Unit = {\n @tailrec\n def rec(ind:Int,seq:List[Char],left:List[Int],right:List[Int]):List[Int]=seq match{\n case List() => return left.reverse++right\n case _ if(seq.head=='l') => return rec(ind+1,seq.tail,left,ind+:right)\n case _ => return rec(ind+1,seq.tail,ind+:left,right)\n }\n val br = new BufferedReader(new InputStreamReader(System.in))\n val pw = new PrintWriter(new OutputStreamWriter(System.out))\n rec(1,br.readLine().toList,List(),List()).map(pw.println(_))\n pw.flush()\n }\n\n}", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val str = in.next()\n val res = Array.ofDim[Int](str.length)\n str.foldLeft((0, str.length - 1, 1)) {\n case ((left, right, number), 'l') => res(right) = number\n (left, right - 1, number + 1)\n case ((left, right, number), 'r') => res(left) = number\n (left + 1, right, number + 1)\n }\n println(res.mkString(\"\\n\"))\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer\n\nobject Test2 {\ndef main(args: Array[String]) {\n val (_,left,right) = readLine.foldLeft((1, ListBuffer[Int](), ListBuffer[Int]()))((r, c) =>{\n c match {\n case 'l' => r._1 +=:r._3\n case _ => r._2 +=r._1\n }\n (r._1 + 1, r._2, r._3)\n }\n )\n \n println(left.mkString(\"\\n\"));\n println(right.mkString(\"\\n\"));\n \n }\n}"}, {"source_code": "object Test1 {\n def main(args: Array[String]) {\n val (_,left,right) = readLine.foldLeft((1, List[Int](), List[Int]()))((r, c) =>\n c match {\n case 'l' => (r._1 + 1, r._2, r._1 :: r._3)\n case _ => (r._1 + 1, r._1 :: r._2, r._3)\n })\n \n println(left.reverse.mkString(\"\\n\"));\n println(right.mkString(\"\\n\"));\n \n }\n\n}"}, {"source_code": "object Test3 {\n \n def main(args: Array[String]) {\n val s = readLine;\n val (_,_,_,result) = s.foldLeft(1,0,s.length-1,new Array[Int](s.length))((r, c) =>c match {\n case 'l' => r._4(r._3) = r._1; (r._1+1,r._2,r._3-1,r._4)\n case _ => r._4(r._2) = r._1; (r._1+1,r._2+1,r._3,r._4)\n })\n println(result.mkString(\"\\n\"));\n \n }\n\n}"}, {"source_code": "object test {\n def main(args: Array[String]): Unit = {\n val s=readLine\n val a=new Array[Int](s.length())\n var i=0\n var j=s.length-1\n var k=0\n while(k return\n case _ => {\n res(if(seq.head=='l') right else left) = ind\n if(seq.head=='l')rec(ind+1,seq.tail,left,right-1) else rec(ind+1,seq.tail,left+1,right)\n }\n }\n rec(1,inp.toList,0,inp.length()-1)\n res.map(pw.println(_))\n pw.flush()\n }\n\n}"}, {"source_code": "import scala.annotation.tailrec\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.OutputStreamWriter\nimport java.io.PrintWriter\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val br = new BufferedReader(new InputStreamReader(System.in))\n val pw = new PrintWriter(System.out)\n val inp = br.readLine()\n var res = new Array[Int](inp.length())\n @tailrec\n def rec(ind:Int,seq:List[Char],left:Int,right:Int):Unit={\n if(!seq.isEmpty)seq.head match{\n case 'l' => {res(right) = ind;rec(ind+1,seq.tail,left,right-1)}\n case 'r' => {res(left) = ind;rec(ind+1,seq.tail,left+1,right)}\n }\n }\n rec(1,inp.toList,0,inp.length()-1)\n res.map(pw.println(_))\n pw.flush()\n }\n\n}"}, {"source_code": "import scala.collection.mutable.LinkedList\nobject Main265C {\n def main(args: Array[String]) {\n val cmds = readLine\n val array1 = Array.ofDim[Int](cmds length)\n val array2 = Array.ofDim[Int](cmds length)\n var pos1, pos2 = 0\n var nextNum = 1\n for (c <- cmds) {\n if (c == 'l') {\n array1(pos1) = nextNum\n pos1 += 1\n }\n else {\n array2(pos2) = nextNum\n pos2 += 1\n }\n nextNum += 1\n }\n val sb = new StringBuilder()\n for (i <- 0 to (pos2-1))\n sb.append(array2(i)).append(\"\\n\")\n for (i <- (pos1-1) to 0 by -1)\n sb.append(array1(i)).append(\"\\n\")\n print(sb)\n }\n}"}, {"source_code": "object C265 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val in = read\n val a = cu.ArrayBuffer.empty[Int]\n val b = cu.ArrayBuffer.empty[Int]\n for(i <- 0 until in.length)\n if(in(i) == 'l') a.append(i+1)\n else b.append(i+1)\n println(b.mkString(\"\\n\"))\n println(a.reverse.mkString(\"\\n\"))\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object CF265C {\n def main(args: Array[String]) {\n val s = readLine()\n print((1 to s.length)\n .sortWith((i, j) => (i < j && s(i - 1) == 'r') | (i > j && s(j - 1) == 'l'))\n .mkString(\"\\n\"))\n }\n}"}, {"source_code": "object CF265C {\n def main(args: Array[String]) {\n val s = readLine()\n print((0 until s.length)\n .sortWith((i, j) => (i < j && s(i) == 'r') | (i > j && s(j) == 'l'))\n .map(_ + 1)\n .mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object Main extends App {\n import scala.io._\n val input = Source.stdin\n val s = input.getLines().next\n val n = s.length\n println((for(i <- 0 until n; if s(i) == 'r') yield (i+1)).toList.mkString(\"\", \"\\n\", \"\"))\n println((for(i <- (n-1) to 0 by -1; if s(i) == 'l') yield (i+1)).toList.mkString(\"\", \"\\n\", \"\"))\n}\n"}, {"source_code": "object Main extends App {\n import scala.io._\n val input = Source.stdin\n val s = input.getLines().next\n val n = s.length\n println((for(i <- 0 until n; if s(i) == 'r') yield (i+1)).mkString(\"\", \"\\n\", \"\"))\n println((for(i <- (n-1) to 0 by -1; if s(i) == 'l') yield (i+1)).mkString(\"\", \"\\n\", \"\"))\n}\n"}, {"source_code": "object Main extends App {\n import scala.io._\n val input = Source.stdin\n val s = input.getLines().next\n val n = s.length\n println((for(i <- 0 until n; if s(i) == 'r') yield (i+1)).mkString(\"\\n\"))\n println((for(i <- (n-1) to 0 by -1; if s(i) == 'l') yield (i+1)).mkString(\"\\n\"))\n}\n"}, {"source_code": "import scala.collection.mutable.LinkedList\nobject Main265C {\n def main(args: Array[String]) {\n val cmds = readLine\n val list = LinkedList(-1, -1)\n var beginning = list\n var ending = list.next\n var nextNum = 1\n for (c <- cmds) {\n beginning.next = new LinkedList(nextNum, ending)\n if (c == 'l')\n ending = beginning.next\n else\n beginning = beginning.next\n nextNum += 1\n }\n var next = list.next\n val sb = new StringBuilder()\n while (next.elem != -1) {\n sb.append(next.elem).append(\"\\n\")\n next = next.next\n }\n print(sb)\n }\n}"}], "negative_code": [], "src_uid": "9d3c0f689ae1e6215448463def55df32"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = {\n if (oj){ System.err.println(s) }\n }\n def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n private[this] def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve2(): Int = {\n val A, B = ni()\n val D = abs(A - B)\n var i = 0\n while(true) {\n val s = i.toLong * (i + 1) / 2\n if (s >= D && s % 2 == D % 2) {\n return i\n }\n i += 1\n }\n\n ???\n }\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n out.println(solve2())\n }\n }\n}", "positive_code": [{"source_code": "object _1278B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val a, b = io.read[Int]\n val d = (a - b).abs\n val ans = Iterator.from(0).find({n =>\n val k = n*(n+1) - 2*d\n k >= 0 && k%4 == 0\n }).get\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "29e84addbc88186bce40d68cf124f5da"} {"source_code": "import collection.mutable._\n\nobject Qualifying {\n\n class Person (\n val name : String,\n val score : Int) extends Ordered[Person] {\n def compare(that : Person) = this.score compare that.score\n override def toString() = (\"name: \" + name + \" score : \" + score)\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = io.StdIn.readLine.split(\" \").map(_.toInt)\n var region = new Array[PriorityQueue[Person]](m+1)\n for (i<-1 to m) region(i) = new PriorityQueue[Person]()\n for (i<-0 until n) {\n val r = io.StdIn.readLine.split(\" \")\n val p = new Person(r(0), r(2).toInt)\n region(r(1).toInt).enqueue(p)\n }\n for (i<-1 to m) {\n //print(region(i))\n if (region(i).size == 2) println(region(i).dequeue.name + \" \" + region(i).dequeue.name)\n else {\n val top = region(i).dequeue\n val sec = region(i).dequeue\n if (top.score == sec.score) {\n if (sec.score == region(i).head.score) println(\"?\")\n else println(top.name + \" \" + sec.name)\n } else { // 1st is unique, checking for 2nd\n if (sec.score == region(i).head.score) println(\"?\")\n else println(top.name + \" \" + sec.name)\n }\n }\n }\n }\n}\n", "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _659B extends CodeForcesApp {\n override def apply(io: IO) = {\n val n, m = io[Int]\n val scores = Array.fill(m)(mutable.Map.empty[String, Int])\n\n repeat(n) {\n val (name, region, score) = io[(String, Int, Int)]\n scores(region - 1)(name) = score\n }\n\n io.separator = newLine\n\n scores foreach {score =>\n val top = score.toIndexedSeq.sortBy(_._2)(desc)\n if (top.length <= 2 || top(1)._2 != top(2)._2) {\n io += (top(0)._1 -> top(1)._1)\n } else {\n io += '?'\n }\n }\n\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sum[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default\n }\n def memoize[I] = new {\n def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n val newLine: String = \"\\n\"\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def appendNewLine(): this.type = {\n println()\n this\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val res = (1 to n).map { _ =>\n val Array(name, region, score) = in.next().split(' ')\n (name, region.toInt, score.toInt)\n }.groupBy(_._2).mapValues(_.sortBy(-_._3)).mapValues{\n case(participans) if participans.length == 2 => participans.map(_._1).mkString(\" \")\n case(participans) if participans(1)._3 == participans(2)._3 => \"?\"\n case(participans) => participans.take(2).map(_._1).mkString(\" \")\n }\n println((1 to m).map(res).mkString(\"\\n\"))\n}"}], "negative_code": [{"source_code": "import collection.mutable._\n\nobject Qualifying {\n\n class Person (\n val name : String,\n val score : Int) extends Ordered[Person] {\n def compare(that : Person) = this.score compare that.score\n override def toString() = (\"name: \" + name + \" score : \" + score)\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = io.StdIn.readLine.split(\" \").map(_.toInt)\n var region = new Array[PriorityQueue[Person]](m+1)\n for (i<-1 to m) region(i) = new PriorityQueue[Person]()\n for (i<-0 until n) {\n val r = io.StdIn.readLine.split(\" \")\n val p = new Person(r(0), r(2).toInt)\n region(r(1).toInt).enqueue(p)\n }\n for (i<-1 to m) {\n //print(region(i))\n if (region(i).size == 2) println(region(i).dequeue.name + \" \" + region(i).dequeue.name)\n else {\n val top = region(i).dequeue\n var sec = region(i).dequeue\n while (!region(i).isEmpty && top.score == sec.score) {\n sec = region(i).dequeue\n }\n if (sec.score == top.score) { // all are the same\n println(\"?\")\n } else if (!region(i).isEmpty && region(i).head.score == sec.score) {\n // tiebreak 2nd\n //println(region(i).head, sec)\n println(\"?\")\n } else println(top.name + \" \" + sec.name)\n }\n }\n }\n}\n"}], "src_uid": "a1ea9eb8db25289958a6f730c555362f"} {"source_code": "object B1256 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var tests = readInt\n while (tests > 0) {\n val n = readInt\n val arr = readInts(n)\n val vis = Array.fill(n)(false)\n for (i <- 1 to n) {\n var idx = arr.indexWhere(_ == i)\n while (idx > 0 && arr(idx) < arr(idx - 1) && !vis(idx - 1)) {\n vis(idx - 1) = true\n val tmp = arr(idx - 1)\n arr(idx - 1) = arr(idx)\n arr(idx) = tmp\n\n idx -= 1\n }\n }\n out.println(arr.mkString(\" \"))\n tests -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "object SmallestPermutation {\n\n def main(args: Array[String]): Unit = {\n import InOut._\n val inputSequences = nextInt\n for {_ <- 0 until inputSequences} {\n val operations = (0 until nextInt).dropRight(1)\n val initialPermutation = nextLine.trim.split(\" \").map(_.toInt).toSeq\n val finalPermutation = findSmallestPermutation(initialPermutation, operations)\n out.println(finalPermutation.mkString(\" \"))\n }\n out.flush()\n }\n\n @scala.annotation.tailrec\n def findSmallestPermutation(permutation: Seq[Int], possibleOperations: Seq[Int]): Seq[Int] = {\n val operation = nextOperation(permutation, possibleOperations)\n if (operation == -1) permutation else findSmallestPermutation(swapOperation(operation)(permutation), possibleOperations.filter(_ != operation))\n }\n\n private def nextOperation(permutation: Seq[Int], possibleOperations: Seq[Int]): Int = {\n val relevantOperation = possibleOperations.filter(op => permutation(op) > permutation(op + 1))\n if (relevantOperation.isEmpty) {\n -1\n } else {\n relevantOperation.reduce {\n (op1, op2) => if (permutation(op1 + 1) < permutation(op2 + 1)) op1 else op2\n }\n }\n }\n\n private def swapOperation[T](index: Int)(collection: Seq[T]): Seq[T] =\n collection.updated(index, collection(index + 1)).updated(index + 1, collection(index))\n\n final object InOut {\n val out = new java.io.PrintWriter(System.out, false)\n\n def nextInt: Int = Integer.parseInt(nextToken)\n\n def nextLine: String = in.readLine\n\n private val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n private[this] var tokenizer: java.util.StringTokenizer = _\n\n private def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.language.postfixOps\n\nobject TaskB extends App {\n val sc = new Scanner(System.in)\n val q = sc.nextInt\n\n val out = 1 to q map { _ =>\n val n = sc.nextInt\n val arr = (1 to n map (_ => sc.nextInt()) toArray)\n minimize(arr, 0, n)\n arr.mkString(\" \")\n } mkString \"\\n\"\n\n println(out)\n\n def minimize(arr: Array[Int], l: Int, r: Int): Unit = {\n if (l < r - 1) {\n val minInd = arr.zipWithIndex.slice(l, r).minBy(_._1)._2\n if (minInd == l) {\n minimize(arr, l + 1, r)\n } else {\n move(arr, minInd, l)\n minimize(arr, minInd, r)\n }\n }\n }\n\n def move(arr: Array[Int], from: Int, to: Int) = {\n val temp = arr(from)\n from until to by -1 foreach (i => arr(i) = arr(i - 1))\n arr(to) = temp\n }\n}\n"}, {"source_code": "//package codeforces.contest1256\n\nobject MinimizeThePermutation {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt()) {\n val n = io.StdIn.readInt()\n\n val ls = io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n def loop(given: List[Int], acc: List[Int] = Nil): List[Int] = {\n if (given.isEmpty) acc\n else {\n val min = given.min\n\n val (left, right) = given.span(_ != min)\n\n if (left.isEmpty)\n loop(given.tail, acc :+ given.head)\n else\n loop(left.last +: right.tail, acc ++ (right.head +: left.dropRight(1)))\n }\n }\n\n println {\n loop(ls).mkString(\" \")\n }\n\n }\n\n }\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val q = readInt\n (0 until q).foreach((x) => f1)\n }\n\n def f1: Unit = {\n val n = readInt\n var a = readLine.split(\" \").map(_.toInt).toList\n println(f2(a).mkString(\" \"))\n }\n\n def f2(a: List[Int]): List[Int] = a match {\n case Nil => Nil\n case hd :: tl => {\n val (_, _, i) = tl.foldLeft((hd, 1, 0)){\n case ((mv, i, mi), h) => if (h < mv) (h, i + 1, i) else (mv, i + 1, mi)\n }\n val (at, bt) = a splitAt i\n (at, bt) match {\n case (_, Nil) => throw new Exception(\"Not occur\")\n case (Nil, x :: y) => x :: f2(y)\n case (l, x :: y) => (x :: l.init) ++ f2(l.last :: y)\n }\n }\n }\n}\n"}], "negative_code": [{"source_code": "object B1256 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var tests = readInt\n while (tests > 0) {\n val n = readInt\n val arr = readInts(n)\n val vis = Array.fill(n)(false)\n for (i <- 1 to n) {\n var idx = arr.indexWhere(_ == i)\n while (i != idx + 1 && !vis(idx - 1) && vis.count(!_) > 1) {\n vis(idx - 1) = true\n val tmp = arr(idx - 1)\n arr(idx - 1) = arr(idx)\n arr(idx) = tmp\n\n idx -= 1\n }\n }\n out.println(arr.mkString(\" \"))\n tests -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object B1256 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var tests = readInt\n while (tests > 0) {\n val n = readInt\n val arr = readInts(n)\n val vis = Array.fill(n)(false)\n for (i <- 1 to n) {\n var idx = arr.indexWhere(_ == i)\n while (i != idx + 1 && !vis(idx - 1)) {\n vis(idx - 1) = true\n val tmp = arr(idx - 1)\n arr(idx - 1) = arr(idx)\n arr(idx) = tmp\n\n idx -= 1\n }\n }\n out.println(arr.mkString(\" \"))\n tests -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object SmallestNumber {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n @scala.annotation.tailrec\n def smallestPermutation(permutation: Seq[Int], possibleOperations: Seq[Int]): Seq[Int] = {\n val operation = nextOperation(permutation, possibleOperations)\n if (operation == -1) permutation else smallestPermutation(swapOperation(operation)(permutation), possibleOperations.filter(_ != operation))\n }\n\n private def nextOperation(permutation: Seq[Int], possibleOperations: Seq[Int]): Int = {\n val relevantOperation = possibleOperations.filter(op => permutation(op) > permutation(op + 1))\n if (relevantOperation.isEmpty) {\n -1\n } else {\n possibleOperations.reduce {\n (acc, value) => if (permutation(acc + 1) < permutation(value + 1)) acc else value\n }\n }\n }\n\n private def swapOperation[T](index: Int)(collection: Seq[T]): Seq[T] =\n collection.updated(index, collection(index + 1)).updated(index + 1, collection(index))\n\n val inputSequences = nextInt\n for {_ <- 0 until inputSequences} {\n val operations = (0 until nextInt).dropRight(1)\n val initialPermutation = nextLine.trim.split(\" \").map(_.toInt).toSeq\n val finalPermutation = smallestPermutation(initialPermutation, operations)\n out.println(finalPermutation.mkString(\" \"))\n }\n out.flush()\n\n final object InOut {\n val out = new java.io.PrintWriter(System.out, false)\n\n def nextInt: Int = Integer.parseInt(nextToken)\n\n def nextLine: String = in.readLine\n\n private val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n private[this] var tokenizer: java.util.StringTokenizer = _\n\n private def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n }\n\n}\n"}], "src_uid": "c7a7e90bc54b2d21b3f59a358d9d1410"} {"source_code": "import scala.io.StdIn.readLine\nimport scala.math.min\n\nobject C537v2 {\n //find first index greater or equal to n\n //return array length if no such index exists\n //search range is [start,end)\n def binsearch(a:Array[Int],start:Int,end:Int,n:Long):Int= {\n assert(end > start, \"end should be bigger index than start\")\n assert(a.length >= end)\n if(end - start>2){\n val m = (start+end)/2\n if (a(m)>=n){binsearch(a,start,m,n)}else{binsearch(a,m,end,n)}\n }\n else if(end - start ==2){\n if(a(start)>=n){start}else if(a(end-1)>=n){end-1}else{end}\n }else{ //end - start==1\n if(a(start) >= n){start}else{end}\n }\n }\n\n def howManySmaller(sortedArray:Array[Int],range:(Int,Int),n:Long)={\n //println(s\"array in binsearch ${sortedArray.mkString(\",\")}\")\n //println(s\"range ${range}\")\n //println(s\"range ${range}\")\n //println(s\"${n}\")\n val j = binsearch(sortedArray,range._1,range._2,n)\n j - range._1\n }\n\n def powerTo1Shot(population: Int, Len: Long, A: Int, B: Int): Long = {\n population match {\n case 0 => A\n case na if na > 0 => na * Len * B\n }\n }\n //(start,end) - range of sortedIndices, with indices that reside in baseRange\n //populOnTheLeft - how many indices there is on the left from baseRange\n case class PopulationInfo(start:Int,end:Int,populOnTheLeft:Int)\n case class Parameters(A:Int,B:Int,popul:Int)\n\n def minPower3(baseRange:(Long,Long),\n sortedIndices:Array[Int],\n populData:PopulationInfo,\n p:Parameters\n ):Long={\n assert(baseRange._2-baseRange._1>=1,\"base range lower than 1\")\n\n val population = p.popul\n\n ((baseRange._2-baseRange._1,population)) match {\n case (length, pop) if length == 1 => powerTo1Shot(pop, length, p.A, p.B)\n case (length, 0) if length >= 1 => p.A\n case (length, pop) if length >= 2 => {\n val leftHalfBase = (baseRange._1,(baseRange._1+length/2))\n val rightHalfBase = (baseRange._1+length/2,baseRange._2)\n val breakPoint = binsearch(sortedIndices,populData.start,populData.end,baseRange._1+length/2)\n val populationLeft = breakPoint - populData.populOnTheLeft//ok\n val populationRight = pop - populationLeft\n def tests() {\n println(s\"total pop ${p.popul}\")\n println(sortedIndices.mkString(\",\"))\n println(baseRange)\n println(s\"breakPoint ${breakPoint}\")\n println(s\"popul on the left ${populData.populOnTheLeft}\")\n println(s\"ppopuleft ${populationLeft}\")\n println(s\"ppopulright ${populationRight}\")\n println(s\"---NEXT----\")\n }\n //tests()\n val popDataL = PopulationInfo(populData.start, breakPoint, populData.populOnTheLeft)\n val popDataR = PopulationInfo(breakPoint, populData.end, populData.populOnTheLeft+populationLeft)\n\n min(\n powerTo1Shot(pop, length, p.A, p.B),\n minPower3(leftHalfBase,sortedIndices,popDataL,Parameters(p.A,p.B,populationLeft))+\n minPower3(rightHalfBase,sortedIndices,popDataR,Parameters(p.A,p.B,populationRight))\n )\n }\n }\n }\n\n def minPowerMain(n:Int,indices:Array[Int],A:Int,B:Int,k:Int):Long ={\n assert(indices.length==k)\n val baseRange = (0.toLong, math.pow(2,n).toLong)\n val indicesSorted = indices.sorted.map(_-1)\n val popInfo = PopulationInfo(0,k,0)\n\n val p = Parameters(A,B,k)\n minPower3(baseRange,indicesSorted,popInfo,p)\n }\n\n\n def main(args: Array[String]) {\n val Array(n, k, a, b) = readLine.split(\" \").map(_.toInt)\n val A = a\n val B = b\n val indices = readLine.split(\" \").map(_.toInt)\n\n val minPower = minPowerMain(n,indices, A, B, k)\n println(minPower)\n }\n\n}\n\nobject test extends App{\n import C537v2._\n def runTests()= {\n println(howManySmaller(Array(1),(0,1),2)==1)\n println(howManySmaller(Array(1),(0,1),0)==0)\n println(howManySmaller(Array(0,1,2,3,4,5),(2,5),4)==2)\n println(howManySmaller(Array(0,1,2,3,4,5),(3,4),4)==1)\n println(howManySmaller(Array(0,1,2,3,4,5),(0,6),7)==6)\n println(howManySmaller(Array(0,1,2,3,4,5),(0,6),4)==4)\n\n }\n runTests()\n\n/*\nval n = 30\nval k = 88704\nval A = 1\nval B = 2140\nval Len = math.pow(2,n).toInt\n //val indices = List(1,3)\n//val Len = math.pow(2,n).toInt\n\nval rnd = new scala.util.Random(198987)\n//val indices = (1 to k).toArray.map(i=>rnd.nextInt(Len))\n//val indices = (1 to k).toArray.map(i=>rnd.nextInt(Len)).sorted\nval indices = (1 to k).toArray.map(i=>rnd.nextInt(Len)+1).map(_-1)\n //indices.sorted.foreach(print)\n //println(\"\\n--------------------\")\n//val indices = Array(858,765)\n//val indices = Array(858,765)\n\n val t1 = System.nanoTime()\n val populTree:Option[Tree]= populationTree(indices,n,Len)\n //indices.sorted\nval t2 = System.nanoTime()\n val minPower = minimalPower(Len,populTree,A,B)\nval t3 = System.nanoTime()\n val indicesSorted = indices.sorted\nval t4 = System.nanoTime()\n val minPower2 = minimalPower2(indicesSorted, 0, Len, A, B,(0,k))\nval t5 = System.nanoTime()\n\n println(minPower)\n println(minPower2)\n println(s\"tree: ${(t2-t1)*1.0/1e9}, which is ${(t2-t1)*1.0/(t3-t1)} of total time\")\n println(s\"rest: ${(t3-t2)*1.0/1e9}\")\n println(s\"whole ${(t3-t1)*1.0/1e9}\")\n println(s\"sorting ${(t4-t3)*1.0/1e9}\")\n println(s\"bin search ${(t5-t4)*1.0/1e9}\")\n //println(minimalPower2(4,Array(1),1,2))\n //println(minimalPower2(4,Array(3),1,2))\n //println(powerTo1Shot(2,8,1,2))\n //println(minimalPower2(Array(1,7), 0, 8, 1, 2))\n //println(minimalPower2(8,Array(1,1),1,2))\n //println(minimalPower2(8,Array(1,1),1,2))\n\n*/\n}\n\n\n\nobject scratch3 extends App{\n import C537v2._\n //testing howManySmaller3, get left, right ranges for population table\n val A = Array(3,3,5,7).sorted\n val r = 2\n //println(howManySmaller3(A,(0,4),r))\n //testing minPower3\n\n val sortedIndices = Array(1,3)\n val p = Parameters(1,2,sortedIndices.length)\n val baseRange = (0l,4l)\n val populData = PopulationInfo(0,4,0)\n /*\n val baseRange = (0l,4l)\n val populData = PopulationInfo(0,4,0)\n */\n /*\n val baseRange = (0l,2l)\n val populData = PopulationInfo(0,3,0)\n */\n\n\n //println(minPower3(baseRange,sortedIndices,populData,p))\n //println(s\"minPowL${minPower3(leftHalfBase,sortedIndices,popDataL,p)}\")\n //println(minPowerMain(2,Array(1,1,1),A=1,B=2,k=3)==8)\n //println(minPowerMain(2,Array(1,2),A=1,B=2,k=2)==5)\n println(minPowerMain(2,Array(1,3),A=1,B=2,k=2)==6)\n println(minPowerMain(3,Array(1,7),A=1,B=2,k=2)==8)\n println(minPowerMain(3,Array(7,8),A=5,B=1,k=2)==12)\n //println(s\"minPowLL${minPower3((0,2),sortedIndices,PopulationInfo(0,3,0),p)}\")\n\n}\n\nobject testttt extends App{\n val a = Array(1,2,3)\n println(a.take(2).length)\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val K, M, AA, BB = ni()\n val A = na(M, -1)\n sort(A)\n\n // [l, r)\n def countAvengers(l: Int, r: Int): Int = {\n lowerBound(A, r) - lowerBound(A, l)\n }\n\n // [l, r)\n def calc(l: Int, r: Int, num: Int): Long = {\n// val num = countAvengers(l, r)\n\n// debug(s\"$l $r num=$num\")\n\n if (num == 0) AA // 一人もいなかったら即時破壊するのがいい\n else if (r - l == 1) {\n // サイズが1の場合はもう分割できない\n if(num > 0) BB.toLong * num * (r - l) else AA\n } else {\n val planA = {\n val mid = (l + r) / 2\n val numL = countAvengers(l, mid)\n calc(l, mid, numL) + calc(mid, r, num - numL)\n }\n val planB = BB.toLong * num * (r - l)\n\n// debug(s\"$l $r $planA $planB\")\n\n min(planA, planB)\n }\n }\n\n // アベンジャーが数少ないのでdfsがlogK * Kぐらいの回数ですむはず\n val ans = calc(0, 1 << K, M)\n\n out.println(ans)\n }\n\n // あえてコピペ\n // 要はcountLt\n // a >= x [x-2, x-1, x, x, x, x+1] の 2\n def lowerBound(a: Array[Int], x: Int): Int = {\n def step(l: Int, h: Int): Int = {\n if (h - l == 1) h\n else {\n val mid = (l + h) / 2\n if (a(mid) >= x) step(l, mid)\n else step(mid, h)\n }\n }\n\n step(-1, a.length)\n }\n\n def sort(a: Array[Int]): Array[Int] = {\n val n = a.length\n REP(n) { i =>\n val j = scala.util.Random.nextInt(n - i) + i\n val tmp = a(i)\n a(i) = a(j)\n a(j) = tmp\n }\n Sorting.stableSort(a)\n a\n }\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val K, M, AA, BB = ni()\n val A = na(M, -1)\n sort(A)\n\n // [l, r)\n def countAvengers(l: Int, r: Int): Int = {\n lowerBound(A, r) - lowerBound(A, l)\n }\n\n // [l, r)\n def calc(l: Int, r: Int): Long = {\n val num = countAvengers(l, r)\n\n// debug(s\"$l $r num=$num\")\n\n if (num == 0) AA // 一人もいなかったら即時破壊するのがいい\n else if (r - l == 1) {\n // サイズが1の場合はもう分割できない\n if(num == 1) BB else AA\n } else {\n val planA = {\n val mid = (l + r) / 2\n calc(l, mid) + calc(mid, r)\n }\n val planB = BB.toLong * num * (r - l)\n\n// debug(s\"$l $r $planA $planB\")\n\n min(planA, planB)\n }\n }\n\n // アベンジャーが数少ないのでdfsがlogK * Kぐらいの回数ですむはず\n val ans = calc(0, 1 << K)\n\n out.println(ans)\n }\n\n // あえてコピペ\n // 要はcountLt\n // a >= x [x-2, x-1, x, x, x, x+1] の 2\n def lowerBound(a: Array[Int], x: Int): Int = {\n def step(l: Int, h: Int): Int = {\n if (h - l == 1) h\n else {\n val mid = (l + h) / 2\n if (a(mid) >= x) step(l, mid)\n else step(mid, h)\n }\n }\n\n step(-1, a.length)\n }\n\n def sort(a: Array[Int]): Array[Int] = {\n val n = a.length\n REP(n) { i =>\n val j = scala.util.Random.nextInt(n - i) + i\n val tmp = a(i)\n a(i) = a(j)\n a(j) = tmp\n }\n Sorting.stableSort(a)\n a\n }\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.math.min\n\nobject C537v2 {\n\n case class Tree(var left: Option[Tree], var right: Option[Tree], var value: Int) {\n def leftValOrElse(default: Int): Int = {\n left match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n\n def rightValOrElse(default: Int) = {\n right match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n }\n\n /*\n def growTree(T: Option[Tree], binaryString: String): Option[Tree] = {\n (T, binaryString) match {\n case (None, \"\") => Some(Tree(None, None, 1))\n case (Some(tree), \"\") => Some(Tree(None, None, tree.value + 1)) //??\n case (None, s) if s(0) == '0' => Some(Tree(growTree(None, s.tail), None, 1))\n case (None, s) if s(0) == '1' => Some(Tree(None, growTree(None, s.tail), 1))\n case (Some(tree), s) if s(0) == '0' => Some(Tree(growTree(tree.left, s.tail), tree.right, tree.value + 1))\n case (Some(tree), s) if s(0) == '1' => Some(Tree(tree.left, growTree(tree.right, s.tail), tree.value + 1))\n }\n }\n */\n def growTree(T: Option[Tree], position: Long, binaryRepresentationLen: Int,Len:Long): Option[Tree] = {\n val firstDigit = position >>> (binaryRepresentationLen-1) & 1\n val otherDigits = position & (Len-1) //sets first bit to 0\n\n (T, firstDigit,binaryRepresentationLen) match {\n case (None, _,0) => Some(Tree(None, None, 1))\n case (Some(tree), _,0) => Some(Tree(None, None, tree.value + 1)) //??\n case (None, d,_) if d == 0 => Some(Tree(growTree(None, otherDigits,binaryRepresentationLen-1,Len/2), None, 1))\n case (None, d,_) if d == 1 => Some(Tree(None, growTree(None, otherDigits,binaryRepresentationLen-1,Len/2), 1))\n case (Some(tree), d,_) if d == 0 => Some(Tree(growTree(tree.left, otherDigits,binaryRepresentationLen-1,Len/2), tree.right, tree.value + 1))\n case (Some(tree), d,_) if d == 1 => Some(Tree(tree.left, growTree(tree.right, otherDigits,binaryRepresentationLen-1,Len/2), tree.value + 1))\n }\n }\n\n def populationTree(indices: Array[Int], binaryRepLen:Int ,Len: Long): Option[Tree] = {\n //indices.map(_ - 1).foldLeft[Option[Tree]](Some(Tree(None, None, 0)))((T: Option[Tree], pos) => growTree(T, pos,binaryRepLen,Len))\n\n var i = 0\n var T:Option[Tree] = Some(Tree(None, None, 0))\n while(i A\n case na if na > 0 => na * Len * B\n }\n }\n\n def minimalPower(Len: Long, populationTree: Option[Tree], A: Int, B: Int): Long = {\n val populationWhole = populationTree match {\n case None => 0\n case Some(tree) => tree.value\n }\n\n val minPow = (populationTree, Len) match {\n case (None, _) => A\n case (Some(tree), length) if length == 1 => powerTo1Shot(populationWhole, length, A, B)\n case (Some(tree), length) if length >= 2 => min(\n powerTo1Shot(populationWhole, Len, A, B),\n minimalPower(Len / 2, tree.left, A, B) + minimalPower(Len / 2, tree.right, A, B)\n )\n }\n //println(minPow)\n minPow\n\n }\n\n def howManySmaller(a: Array[Int], left:Int, right:Int, n:Long): Int = {\n //to not get out of bounds error\n val right2 = if (right >= a.length) {\n a.length - 1\n } else {\n right\n }\n val mid = (left + right2) / 2\n\n (a(left), a(mid), a(right2)) match {\n case (le, mi, ri) if ri <= n => a.length //if right is smaller, everything is\n case (le, _, _) if le > n => left\n case (le, mi, _) if le == mi => right2\n case (le, mi, _) if mi > n => howManySmaller(a, left, mid, n)\n case (le, mi, _) if mi <= n => howManySmaller(a, mid, right, n)\n }\n }\n\n\n def minimalPower2(Len: Long, indicesSorted:Array[Int], A: Int, B: Int): Long = {\n\n val populationWhole = indicesSorted.length\n val mid = Len / 2\n val populationLeft = if(indicesSorted.length >0) {\n howManySmaller(indicesSorted, 0, indicesSorted.length, mid)\n }else{\n 0\n }\n val minPow = (populationWhole, Len,indicesSorted.length) match {\n //case (0, length,_) if length == 0 => 0\n case (0,_,_) => A\n case (0, length,_) if length > 0 => {\n println(s\"A: ${length}\")\n A\n }\n case (_, length,_) if length == 1 => {\n /*\n println(s\"popul ${populationWhole}\")\n println(s\"len ${length}\")\n println(s\"A ${A}\")\n println(s\"B ${B}\")\n println(s\"powTo1Shot ${powerTo1Shot(populationWhole, length, A, B)} \")\n println(\"jeb\")\n */\n powerTo1Shot(populationWhole, length, A, B)}\n case (_, length,_) if length >= 2 => {\n //val aa = indicesSorted.take(populationLeft)\n //aa.foreach(x=>println(s\"${x}, a\"))\n //val bb = indicesSorted.drop(populationLeft).map(i=>(i-Len/2).toInt)\n //aa.foreach(x=>println(s\"${x}, b\"))\n indicesSorted.take(populationLeft)\n min(\n powerTo1Shot(populationWhole, Len, A, B),\n minimalPower2(Len / 2, indicesSorted.take(populationLeft), A, B) + minimalPower2(Len / 2, indicesSorted.drop(populationLeft).map(i=>(i-Len/2).toInt), A, B)\n )\n }\n }\n //println(minPow)\n minPow\n }\n\n\n def main(args: Array[String]) {\n val Array(n, k, a, b) = readLine.split(\" \").map(_.toInt)\n val A = a\n val B = b\n val indices = readLine.split(\" \").map(_.toInt)\n\n val Len = math.pow(2, n).toLong\n //val populTree: Option[Tree] = populationTree(indices, n,Len)\n //val minPower = minimalPower(Len, populTree, A, B)\n val minPower = minimalPower2(Len,indices,A,B)\n println(minPower)\n }\n\n}\n\nobject test extends App{\n import C537v2._\n\nval n = 3\nval k = 2\nval A = 1\nval B = 2\n\nval indices = Array(1,7)\n\n/*\nval n = 30\nval k = 10000\nval A = 78\nval B = 9765\n*/\n //val indices = List(1,3)\nval Len = math.pow(2,n).toInt\n\nval rnd = new scala.util.Random(1000)\n//val indices = (1 to k).toArray.map(i=>rnd.nextInt(Len))\nval t1 = System.nanoTime()\n val populTree:Option[Tree]= populationTree(indices,n,Len)\n //indices.sorted\nval t2 = System.nanoTime()\n val minPower = minimalPower(Len,populTree,A,B)\nval t3 = System.nanoTime()\n val indicesSorted = indices.sorted\n val minPower2 = minimalPower2(Len,indices,A,B)\nval t4 = System.nanoTime()\n\n //println(minPower)\n //println(minPower2)\n //println(s\"tree: ${(t2-t1)*1.0/1e9}, which is ${(t2-t1)*1.0/(t3-t1)} of total time\")\n //println(s\"rest: ${(t3-t2)*1.0/1e9}\")\n //println(s\"whole ${(t3-t1)*1.0/1e9}\")\n //println(s\"bin search ${(t4-t3)*1.0/1e9}\")\n //println(minimalPower2(4,Array(1),1,2))\n //println(minimalPower2(4,Array(3),1,2))\n //println(powerTo1Shot(2,8,1,2))\n println(minimalPower2(8,Array(1,7),1,2))\n //println(minimalPower2(8,Array(1,1),1,2))\n\n\n}\n\nobject scratch2 extends App{\n\n def findFirstLarger(a: Array[Int],left:Int,right:Int, n:Long): Int = {\n val right2 = if (right >= a.length) {\n a.length - 1\n } else {\n right\n }\n val mid = (left + right2) / 2\n\n (a(left), a(mid), a(right2)) match {\n case (le, mi, ri) if ri <= n => -1\n case (le, _, _) if le > n => left\n case (le, mi, _) if le == mi => right2\n case (le, mi, _) if mi > n => findFirstLarger(a, left, mid, n)\n case (le, mi, _) if mi <= n => findFirstLarger(a, mid, right, n)\n }\n }\n //println(findFirstLarger(Array(1,7),0,2,4))\n val a = Array(1,2,3)\n //println(findFirstLarger(a,0,a.length-1,4))\n assert(findFirstLarger(Array(1,2,3,5,6,7),0,a.length-1,4)==3)\n assert(findFirstLarger(Array(1),0,a.length-1,4) == -1)\n assert(findFirstLarger(Array(1,8),0,a.length-1,4) == 1)\n //assert(findFirstLarger(Array(1),0,a.length-1,4) == -1)\n\n}\n\nobject scratch3 extends App{\n val a1 = Array(1,7)\n val a2 = a1.take(1)\n val a3 = a1.drop(1)\n a2.length\n a3.length\n println(a2(0))\n println(a3(0))\n\n}\n\n"}, {"source_code": "import scala.math._\nimport scala.io.StdIn._\n\nobject C537{\n\n case class Tree(left: Option[Tree], right: Option[Tree], value: Int) {\n def leftValOrElse(default: Int): Int = {\n left match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n\n def rightValOrElse(default: Int) = {\n right match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n }\n\n\n def growTree(T: Option[Tree], binaryString: String): Option[Tree] = {\n (T,binaryString) match {\n case (None,\"\") => Some(Tree(None,None,1))\n case (Some(tree),\"\") => Some(Tree(None,None,1)) //??\n case (None,s) if s(0) == '0' => Some(Tree(growTree(None,binaryString.tail), None, 1))\n case (None,s) if s(0) == '1' => Some(Tree(None, growTree(None,binaryString.tail), 1))\n case (Some(tree),s) if s(0) == '0' => Some(Tree(growTree(tree.left, s.tail), tree.right,tree.value +1))\n case (Some(tree),s) if s(0) == '1' => Some(Tree(tree.left, growTree(tree.right, s.tail),tree.value +1))\n }\n }\n\n def populationTree(indices: List[Int],Len:Int): Option[Tree] = {\n val indices2binary = indices.map(_-1).map(_+Len).map(_.toBinaryString.tail)\n indices2binary.foldLeft[Option[Tree]](Some(Tree(None,None,0)))((T:Option[Tree], binStr) => growTree(T, binStr))\n }\n\n def powerTo1Shot(population: Int, Len: Int, A: Int, B: Int) = {\n population match {\n case 0 => A\n case na if na > 0 => na * Len * B\n }\n }\n\n def minimalPower(Len: Int, populationTree: Option[Tree], A: Int, B: Int): Double = {\n val populationWhole = populationTree match {\n case None => 0\n case Some(tree) => tree.value\n }\n\n val minPow = populationTree match {\n case None => A\n case Some(tree) => min(\n powerTo1Shot(Len, populationWhole, A, B),\n minimalPower(Len / 2, tree.left, A, B)+ minimalPower(Len / 2, tree.right, A, B)\n )\n }\n //println(minPow)\n minPow\n\n }\n\n def main(args: Array[String]) {\n val Array(n,k,a,b) = readLine.split(\" \").map(_.toInt)\n val A = a\n val B = b\n val indices = readLine.split(\" \").map(_.toInt)\n\n val Len = math.pow(2,n).toInt\n val populTree:Option[Tree]= populationTree(indices.toList,Len)\n val minPower = minimalPower(Len,populTree,A,B)\n println(minPower)\n }\n\n /*\n val n = 3\n val k = 2\n val A = 1\n val B = 2\n\n val indices = Array(1,7)\n\n val Len = math.pow(2,n).toInt\n val populTree:Option[Tree]= populationTree(indices.toList,Len)\n\n val minPower = minimalPower(Len,populTree,A,B)\n //println(populTree.get.value)\n\n println(minPower)\n println(growTree(Some(Tree(None,None,0)),\"1\"))\n\n */\n}\n\nobject scratch extends App{\n println(\"ok\")\n\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.math.min\n\nobject C537v2 {\n\n case class Tree(var left: Option[Tree], var right: Option[Tree], var value: Int) {\n def leftValOrElse(default: Int): Int = {\n left match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n\n def rightValOrElse(default: Int) = {\n right match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n }\n\n /*\n def growTree(T: Option[Tree], binaryString: String): Option[Tree] = {\n (T, binaryString) match {\n case (None, \"\") => Some(Tree(None, None, 1))\n case (Some(tree), \"\") => Some(Tree(None, None, tree.value + 1)) //??\n case (None, s) if s(0) == '0' => Some(Tree(growTree(None, s.tail), None, 1))\n case (None, s) if s(0) == '1' => Some(Tree(None, growTree(None, s.tail), 1))\n case (Some(tree), s) if s(0) == '0' => Some(Tree(growTree(tree.left, s.tail), tree.right, tree.value + 1))\n case (Some(tree), s) if s(0) == '1' => Some(Tree(tree.left, growTree(tree.right, s.tail), tree.value + 1))\n }\n }\n */\n def growTree(T: Option[Tree], position: Long, binaryRepresentationLen: Int,Len:Long): Option[Tree] = {\n val firstDigit = position >>> (binaryRepresentationLen-1) & 1\n val otherDigits = position & (Len-1) //sets first bit to 0\n\n (T, firstDigit,binaryRepresentationLen) match {\n case (None, _,0) => Some(Tree(None, None, 1))\n case (Some(tree), _,0) => Some(Tree(None, None, tree.value + 1)) //??\n case (None, d,_) if d == 0 => Some(Tree(growTree(None, otherDigits,binaryRepresentationLen-1,Len/2), None, 1))\n case (None, d,_) if d == 1 => Some(Tree(None, growTree(None, otherDigits,binaryRepresentationLen-1,Len/2), 1))\n case (Some(tree), d,_) if d == 0 => Some(Tree(growTree(tree.left, otherDigits,binaryRepresentationLen-1,Len/2), tree.right, tree.value + 1))\n case (Some(tree), d,_) if d == 1 => Some(Tree(tree.left, growTree(tree.right, otherDigits,binaryRepresentationLen-1,Len/2), tree.value + 1))\n }\n }\n\n def populationTree(indices: Array[Int], binaryRepLen:Int ,Len: Long): Option[Tree] = {\n //indices.map(_ - 1).foldLeft[Option[Tree]](Some(Tree(None, None, 0)))((T: Option[Tree], pos) => growTree(T, pos,binaryRepLen,Len))\n\n var i = 0\n var T:Option[Tree] = Some(Tree(None, None, 0))\n while(i A\n case na if na > 0 => na * Len * B\n }\n }\n\n def minimalPower(Len: Long, populationTree: Option[Tree], A: Int, B: Int): Long = {\n val populationWhole = populationTree match {\n case None => 0\n case Some(tree) => tree.value\n }\n\n val minPow = (populationTree, Len) match {\n case (None, _) => A\n case (Some(tree), length) if length == 1 => powerTo1Shot(populationWhole, length, A, B)\n case (Some(tree), length) if length >= 2 => min(\n powerTo1Shot(populationWhole, Len, A, B),\n minimalPower(Len / 2, tree.left, A, B) + minimalPower(Len / 2, tree.right, A, B)\n )\n }\n //println(minPow)\n minPow\n\n }\n\n def howManySmaller(a: Array[Int], left:Int, right:Int, n:Long): Int = {\n //to not get out of bounds error\n val right2 = if (right >= a.length) {\n a.length - 1\n } else {\n right\n }\n val mid = (left + right2) / 2\n if(a.length == 0){\n 0\n }else {\n (a(left), a(mid), a(right2)) match {\n case (le, mi, ri) if ri <= n => a.length //if right is smaller, everything is\n case (le, _, _) if le > n => left\n case (le, mi, _) if le == mi => right2\n case (le, mi, _) if mi > n => howManySmaller(a, left, mid, n)\n case (le, mi, _) if mi <= n => howManySmaller(a, mid, right, n)\n }\n }\n }\n\n\n def minimalPower2(indicesSorted: Array[Int], start: Long, Len: Long, A: Int, B: Int): Long = {\n\n val populationWhole = indicesSorted.length\n\n val mid = start + Len / 2\n val breakPoint = howManySmaller(indicesSorted, 0, indicesSorted.length, mid)\n\n val indicesLeft = indicesSorted.take(breakPoint)\n val indicesRight = indicesSorted.drop(breakPoint)\n\n val minPow = (populationWhole, Len,indicesSorted.length) match {\n case (0,_,_) => A\n case (0, length,_) if length > 0 => {\n A\n }\n case (_, length,_) if length == 1 => {\n powerTo1Shot(populationWhole, length, A, B)}\n case (_, length,_) if length >= 2 => {\n min(\n powerTo1Shot(populationWhole, Len, A, B),\n minimalPower2(indicesLeft, start, Len / 2, A, B) +\n minimalPower2(indicesRight,start+Len/2 , Len / 2, A, B)\n )\n }\n }\n //println(minPow)\n minPow\n }\n\n\n def main(args: Array[String]) {\n val Array(n, k, a, b) = readLine.split(\" \").map(_.toInt)\n val A = a\n val B = b\n val indices = readLine.split(\" \").map(_.toInt)\n\n val Len = math.pow(2, n).toLong\n //val populTree: Option[Tree] = populationTree(indices, n,Len)\n //val minPower = minimalPower(Len, populTree, A, B)\n val minPower = minimalPower2(indices, 0, Len, A, B)\n println(minPower)\n }\n\n}\n\nobject test extends App{\n import C537v2._\n\nval n = 3\nval k = 2\nval A = 1\nval B = 2\n\nval indices = Array(1,7)\n\n/*\nval n = 30\nval k = 10000\nval A = 78\nval B = 9765\n*/\n //val indices = List(1,3)\nval Len = math.pow(2,n).toInt\n\nval rnd = new scala.util.Random(1000)\n//val indices = (1 to k).toArray.map(i=>rnd.nextInt(Len))\nval t1 = System.nanoTime()\n val populTree:Option[Tree]= populationTree(indices,n,Len)\n //indices.sorted\nval t2 = System.nanoTime()\n val minPower = minimalPower(Len,populTree,A,B)\nval t3 = System.nanoTime()\n val indicesSorted = indices.sorted\n val minPower2 = minimalPower2(indices, 0, Len, A, B)\nval t4 = System.nanoTime()\n\n //println(minPower)\n //println(minPower2)\n //println(s\"tree: ${(t2-t1)*1.0/1e9}, which is ${(t2-t1)*1.0/(t3-t1)} of total time\")\n //println(s\"rest: ${(t3-t2)*1.0/1e9}\")\n //println(s\"whole ${(t3-t1)*1.0/1e9}\")\n //println(s\"bin search ${(t4-t3)*1.0/1e9}\")\n //println(minimalPower2(4,Array(1),1,2))\n //println(minimalPower2(4,Array(3),1,2))\n //println(powerTo1Shot(2,8,1,2))\n println(minimalPower2(Array(1,7), 0, 8, 1, 2))\n //println(minimalPower2(8,Array(1,1),1,2))\n\n\n}\n\nobject scratch2 extends App{\n\n def findFirstLarger(a: Array[Int],left:Int,right:Int, n:Long): Int = {\n val right2 = if (right >= a.length) {\n a.length - 1\n } else {\n right\n }\n val mid = (left + right2) / 2\n\n (a(left), a(mid), a(right2)) match {\n case (le, mi, ri) if ri <= n => -1\n case (le, _, _) if le > n => left\n case (le, mi, _) if le == mi => right2\n case (le, mi, _) if mi > n => findFirstLarger(a, left, mid, n)\n case (le, mi, _) if mi <= n => findFirstLarger(a, mid, right, n)\n }\n }\n //println(findFirstLarger(Array(1,7),0,2,4))\n val a = Array(1,2,3)\n //println(findFirstLarger(a,0,a.length-1,4))\n assert(findFirstLarger(Array(1,2,3,5,6,7),0,a.length-1,4)==3)\n assert(findFirstLarger(Array(1),0,a.length-1,4) == -1)\n assert(findFirstLarger(Array(1,8),0,a.length-1,4) == 1)\n //assert(findFirstLarger(Array(1),0,a.length-1,4) == -1)\n\n}\n\nobject scratch3 extends App{\n val a = Array(1)\n val b = a.drop(1)\n println(b)\n\n\n}\n\n"}, {"source_code": "import scala.math._\nimport scala.io.StdIn._\n\nobject C537{\n\n case class Tree(left: Option[Tree], right: Option[Tree], value: Int) {\n def leftValOrElse(default: Int): Int = {\n left match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n\n def rightValOrElse(default: Int) = {\n right match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n }\n\n\n def growTree(T: Option[Tree], binaryString: String): Option[Tree] = {\n (T,binaryString) match {\n case (None,\"\") => Some(Tree(None,None,1))\n case (Some(tree),\"\") => Some(Tree(None,None,1)) //??\n case (None,s) if s(0) == '0' => Some(Tree(growTree(None,s.tail), None, 1))\n case (None,s) if s(0) == '1' => Some(Tree(None, growTree(None,s.tail), 1))\n case (Some(tree),s) if s(0) == '0' => Some(Tree(growTree(tree.left, s.tail), tree.right,tree.value +1))\n case (Some(tree),s) if s(0) == '1' => Some(Tree(tree.left, growTree(tree.right, s.tail),tree.value +1))\n }\n }\n\n def populationTree(indices: List[Int],Len:Int): Option[Tree] = {\n val indices2binary = indices.map(_-1).map(_+Len).map(_.toBinaryString.tail)\n indices2binary.foldLeft[Option[Tree]](Some(Tree(None,None,0)))((T:Option[Tree], binStr) => growTree(T, binStr))\n }\n\n def powerTo1Shot(population: Int, Len: Int, A: Int, B: Int) = {\n population match {\n case 0 => A\n case na if na > 0 => na * Len * B\n }\n }\n\n def minimalPower(Len: Int, populationTree: Option[Tree], A: Int, B: Int): Double = {\n val populationWhole = populationTree match {\n case None => 0\n case Some(tree) => tree.value\n }\n\n val minPow = (populationTree,Len) match {\n case (None,_) => A\n case (Some(tree), length) if length == 1 => powerTo1Shot(length, populationWhole, A, B)\n case (Some(tree),length) if length>=2 => min(\n powerTo1Shot(Len, populationWhole, A, B),\n minimalPower(Len / 2, tree.left, A, B)+ minimalPower(Len / 2, tree.right, A, B)\n )\n }\n //println(minPow)\n minPow\n\n }\n\n def main(args: Array[String]) {\n val Array(n,k,a,b) = readLine.split(\" \").map(_.toInt)\n val A = a\n val B = b\n val indices = readLine.split(\" \").map(_.toInt)\n\n val Len = math.pow(2,n).toInt\n val populTree:Option[Tree]= populationTree(indices.toList,Len)\n val minPower = minimalPower(Len,populTree,A,B)\n println(minPower)\n }\n\n}\n"}, {"source_code": "import scala.math._\nimport scala.io.StdIn._\n\nobject C537{\n\n case class Tree(left: Option[Tree], right: Option[Tree], value: Int) {\n def leftValOrElse(default: Int): Int = {\n left match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n\n def rightValOrElse(default: Int) = {\n right match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n }\n\n\n def growTree(T: Option[Tree], binaryString: String): Option[Tree] = {\n (T,binaryString) match {\n case (None,\"\") => Some(Tree(None,None,1))\n case (Some(tree),\"\") => Some(Tree(None,None,tree.value+1)) //??\n case (None,s) if s(0) == '0' => Some(Tree(growTree(None,s.tail), None, 1))\n case (None,s) if s(0) == '1' => Some(Tree(None, growTree(None,s.tail), 1))\n case (Some(tree),s) if s(0) == '0' => Some(Tree(growTree(tree.left, s.tail), tree.right,tree.value +1))\n case (Some(tree),s) if s(0) == '1' => Some(Tree(tree.left, growTree(tree.right, s.tail),tree.value +1))\n }\n }\n\n def populationTree(indices: List[Int],Len:Int): Option[Tree] = {\n val indices2binary = indices.map(_-1).map(_+Len).map(_.toBinaryString.tail)\n indices2binary.foldLeft[Option[Tree]](Some(Tree(None,None,0)))((T:Option[Tree], binStr) => growTree(T, binStr))\n }\n\n def powerTo1Shot(population: Int, Len: Int, A: Int, B: Int) = {\n population match {\n case 0 => A\n case na if na > 0 => na * Len * B\n }\n }\n\n def minimalPower(Len: Int, populationTree: Option[Tree], A: Int, B: Int): Int = {\n val populationWhole = populationTree match {\n case None => 0\n case Some(tree) => tree.value\n }\n\n val minPow = (populationTree,Len) match {\n case (None,_) => A\n case (Some(tree), length) if length == 1 => powerTo1Shot(length, populationWhole, A, B)\n case (Some(tree),length) if length>=2 => min(\n powerTo1Shot(Len, populationWhole, A, B),\n minimalPower(Len / 2, tree.left, A, B)+ minimalPower(Len / 2, tree.right, A, B)\n )\n }\n //println(minPow)\n minPow\n\n }\n\n def main(args: Array[String]) {\n val Array(n,k,a,b) = readLine.split(\" \").map(_.toInt)\n val A = a\n val B = b\n val indices = readLine.split(\" \").map(_.toInt)\n\n val Len = math.pow(2,n).toInt\n val populTree:Option[Tree]= populationTree(indices.toList,Len)\n val minPower = minimalPower(Len,populTree,A,B)\n println(minPower)\n }\n /*\n val n = 3\n val k = 2\n val A = 1\n val B = 2\n\n val indices = List(1,7)\n val Len = math.pow(2,n).toInt\n val populTree:Option[Tree]= populationTree(indices.toList,Len)\n val minPower = minimalPower(Len,populTree,A,B)\n println(populTree)\n println(minPower)\n */\n}\n\n"}, {"source_code": "import scala.math._\nimport scala.io.StdIn._\n\nobject C537{\n\n case class Tree(left: Option[Tree], right: Option[Tree], value: Int) {\n def leftValOrElse(default: Int): Int = {\n left match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n\n def rightValOrElse(default: Int) = {\n right match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n }\n\n\n def growTree(T: Option[Tree], binaryString: String): Option[Tree] = {\n (T,binaryString) match {\n case (None,\"\") => Some(Tree(None,None,1))\n case (Some(tree),\"\") => Some(Tree(None,None,1)) //??\n case (None,s) if s(0) == '0' => Some(Tree(growTree(None,binaryString.tail), None, 1))\n case (None,s) if s(0) == '1' => Some(Tree(None, growTree(None,binaryString.tail), 1))\n case (Some(tree),s) if s(0) == '0' => Some(Tree(growTree(tree.left, s.tail), tree.right,tree.value +1))\n case (Some(tree),s) if s(0) == '1' => Some(Tree(tree.left, growTree(tree.right, s.tail),tree.value +1))\n }\n }\n\n def populationTree(indices: List[Int],Len:Int): Option[Tree] = {\n val indices2binary = indices.map(_-1).map(_+Len).map(_.toBinaryString.tail)\n indices2binary.foldLeft[Option[Tree]](Some(Tree(None,None,0)))((T:Option[Tree], binStr) => growTree(T, binStr))\n }\n\n def powerTo1Shot(population: Int, Len: Int, A: Int, B: Int) = {\n population match {\n case 0 => A\n case na if na > 0 => na * Len * B\n }\n }\n\n def minimalPower(Len: Int, populationTree: Option[Tree], A: Int, B: Int): Double = {\n val populationWhole = populationTree match {\n case None => 0\n case Some(tree) => tree.value\n }\n\n val minPow = (populationTree,Len) match {\n case (None,_) => A\n case (Some(tree), length) if length == 1 => powerTo1Shot(length, populationWhole, A, B)\n case (Some(tree),length) if length>=2 => min(\n powerTo1Shot(Len, populationWhole, A, B),\n minimalPower(Len / 2, tree.left, A, B)+ minimalPower(Len / 2, tree.right, A, B)\n )\n }\n //println(minPow)\n minPow\n\n }\n\n def main(args: Array[String]) {\n val Array(n,k,a,b) = readLine.split(\" \").map(_.toInt)\n val A = a\n val B = b\n val indices = readLine.split(\" \").map(_.toInt)\n\n val Len = math.pow(2,n).toInt\n val populTree:Option[Tree]= populationTree(indices.toList,Len)\n val minPower = minimalPower(Len,populTree,A,B)\n println(minPower)\n }\n\n\n val n = 2\n val k = 2\n val A = 1\n val B = 2\n\n val indices = Array(1,3)\n\n val Len = math.pow(2,n).toInt\n val populTree:Option[Tree]= populationTree(indices.toList,Len)\n\n val minPower = minimalPower(Len,populTree,A,B)\n //println(populTree.get.value)\n\n println(minPower)\n println(growTree(Some(Tree(None,None,0)),\"11\"))\n\n}\n\nobject scratch extends App{\n println(\"ok\")\n\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.math.min\n\nobject C537v2 {\n\n case class Tree(var left: Option[Tree], var right: Option[Tree], var value: Int) {\n def leftValOrElse(default: Int): Int = {\n left match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n\n def rightValOrElse(default: Int) = {\n right match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n }\n\n /*\n def growTree(T: Option[Tree], binaryString: String): Option[Tree] = {\n (T, binaryString) match {\n case (None, \"\") => Some(Tree(None, None, 1))\n case (Some(tree), \"\") => Some(Tree(None, None, tree.value + 1)) //??\n case (None, s) if s(0) == '0' => Some(Tree(growTree(None, s.tail), None, 1))\n case (None, s) if s(0) == '1' => Some(Tree(None, growTree(None, s.tail), 1))\n case (Some(tree), s) if s(0) == '0' => Some(Tree(growTree(tree.left, s.tail), tree.right, tree.value + 1))\n case (Some(tree), s) if s(0) == '1' => Some(Tree(tree.left, growTree(tree.right, s.tail), tree.value + 1))\n }\n }\n */\n def growTree(T: Option[Tree], position: Long, binaryRepresentationLen: Int,Len:Long): Option[Tree] = {\n val firstDigit = position >>> (binaryRepresentationLen-1) & 1\n val otherDigits = position & (Len-1) //sets first bit to 0\n\n (T, firstDigit,binaryRepresentationLen) match {\n case (None, _,0) => Some(Tree(None, None, 1))\n case (Some(tree), _,0) => Some(Tree(None, None, tree.value + 1)) //??\n case (None, d,_) if d == 0 => Some(Tree(growTree(None, otherDigits,binaryRepresentationLen-1,Len/2), None, 1))\n case (None, d,_) if d == 1 => Some(Tree(None, growTree(None, otherDigits,binaryRepresentationLen-1,Len/2), 1))\n case (Some(tree), d,_) if d == 0 => Some(Tree(growTree(tree.left, otherDigits,binaryRepresentationLen-1,Len/2), tree.right, tree.value + 1))\n case (Some(tree), d,_) if d == 1 => Some(Tree(tree.left, growTree(tree.right, otherDigits,binaryRepresentationLen-1,Len/2), tree.value + 1))\n }\n }\n\n def populationTree(indices: Array[Int], binaryRepLen:Int ,Len: Long): Option[Tree] = {\n //indices.map(_ - 1).foldLeft[Option[Tree]](Some(Tree(None, None, 0)))((T: Option[Tree], pos) => growTree(T, pos,binaryRepLen,Len))\n\n var i = 0\n var T:Option[Tree] = Some(Tree(None, None, 0))\n while(i A\n case na if na > 0 => na * Len * B\n }\n }\n\n def minimalPower(Len: Long, populationTree: Option[Tree], A: Int, B: Int): Long = {\n val populationWhole = populationTree match {\n case None => 0\n case Some(tree) => tree.value\n }\n\n val minPow = (populationTree, Len) match {\n case (None, _) => A\n case (Some(tree), length) if length == 1 => powerTo1Shot(populationWhole, length, A, B)\n case (Some(tree), length) if length >= 2 => min(\n powerTo1Shot(populationWhole, Len, A, B),\n minimalPower(Len / 2, tree.left, A, B) + minimalPower(Len / 2, tree.right, A, B)\n )\n }\n //println(minPow)\n minPow\n\n }\n\n def howManySmaller(a: Array[Int], left:Int, right:Int, n:Long): Int = {\n //to not get out of bounds error\n val right2 = if (right >= a.length) {\n a.length - 1\n } else {\n right\n }\n val mid = (left + right2) / 2\n\n (a(left), a(mid), a(right2)) match {\n case (le, mi, ri) if ri <= n => a.length //if right is smaller, everything is\n case (le, _, _) if le > n => left\n case (le, mi, _) if le == mi => right2\n case (le, mi, _) if mi > n => howManySmaller(a, left, mid, n)\n case (le, mi, _) if mi <= n => howManySmaller(a, mid, right, n)\n }\n }\n\n\n def minimalPower2(Len: Long, indicesSorted:Array[Int], A: Int, B: Int): Long = {\n\n val populationWhole = indicesSorted.length\n val mid = Len / 2\n val populationLeft = if(indicesSorted.length >0) {\n howManySmaller(indicesSorted, 0, indicesSorted.length, mid)\n }else{\n 0\n }\n val minPow = (populationWhole, Len,indicesSorted.length) match {\n //case (0, length,_) if length == 0 => 0\n case (0,_,_) => A\n case (0, length,_) if length > 0 => {\n println(s\"A: ${length}\")\n A\n }\n case (_, length,_) if length == 1 => {\n println(s\"popul ${populationWhole}\")\n println(s\"len ${length}\")\n println(s\"A ${A}\")\n println(s\"B ${B}\")\n println(s\"powTo1Shot ${powerTo1Shot(populationWhole, length, A, B)} \")\n println(\"jeb\")\n powerTo1Shot(populationWhole, length, A, B)}\n case (_, length,_) if length >= 2 => {\n val aa = indicesSorted.take(populationLeft)\n aa.foreach(x=>println(s\"${x}, a\"))\n val bb = indicesSorted.drop(populationLeft).map(i=>(i-Len/2).toInt)\n aa.foreach(x=>println(s\"${x}, b\"))\n indicesSorted.take(populationLeft)\n min(\n powerTo1Shot(populationWhole, Len, A, B),\n minimalPower2(Len / 2, indicesSorted.take(populationLeft), A, B) + minimalPower2(Len / 2, indicesSorted.drop(populationLeft).map(i=>(i-Len/2).toInt), A, B)\n )\n }\n }\n //println(minPow)\n minPow\n }\n\n\n def main(args: Array[String]) {\n val Array(n, k, a, b) = readLine.split(\" \").map(_.toInt)\n val A = a\n val B = b\n val indices = readLine.split(\" \").map(_.toInt)\n\n val Len = math.pow(2, n).toLong\n //val populTree: Option[Tree] = populationTree(indices, n,Len)\n //val minPower = minimalPower(Len, populTree, A, B)\n val minPower = minimalPower2(Len,indices,A,B)\n println(minPower)\n }\n\n}\n/*\nobject test extends App{\n import C537v2._\n\nval n = 3\nval k = 2\nval A = 1\nval B = 2\n\nval indices = Array(1,7)\n\n/*\nval n = 30\nval k = 10000\nval A = 78\nval B = 9765\n*/\n //val indices = List(1,3)\nval Len = math.pow(2,n).toInt\n\nval rnd = new scala.util.Random(1000)\n//val indices = (1 to k).toArray.map(i=>rnd.nextInt(Len))\nval t1 = System.nanoTime()\n val populTree:Option[Tree]= populationTree(indices,n,Len)\n //indices.sorted\nval t2 = System.nanoTime()\n val minPower = minimalPower(Len,populTree,A,B)\nval t3 = System.nanoTime()\n val indicesSorted = indices.sorted\n val minPower2 = minimalPower2(Len,indices,A,B)\nval t4 = System.nanoTime()\n\n //println(minPower)\n //println(minPower2)\n println(s\"tree: ${(t2-t1)*1.0/1e9}, which is ${(t2-t1)*1.0/(t3-t1)} of total time\")\n println(s\"rest: ${(t3-t2)*1.0/1e9}\")\n println(s\"whole ${(t3-t1)*1.0/1e9}\")\n println(s\"bin search ${(t4-t3)*1.0/1e9}\")\n //println(minimalPower2(4,Array(1),1,2))\n //println(minimalPower2(4,Array(3),1,2))\n //println(powerTo1Shot(2,8,1,2))\n println(minimalPower2(8,Array(1,7),1,2))\n //println(minimalPower2(8,Array(1,1),1,2))\n\n\n}\n\nobject scratch2 extends App{\n\n def findFirstLarger(a: Array[Int],left:Int,right:Int, n:Long): Int = {\n val right2 = if (right >= a.length) {\n a.length - 1\n } else {\n right\n }\n val mid = (left + right2) / 2\n\n (a(left), a(mid), a(right2)) match {\n case (le, mi, ri) if ri <= n => -1\n case (le, _, _) if le > n => left\n case (le, mi, _) if le == mi => right2\n case (le, mi, _) if mi > n => findFirstLarger(a, left, mid, n)\n case (le, mi, _) if mi <= n => findFirstLarger(a, mid, right, n)\n }\n }\n //println(findFirstLarger(Array(1,7),0,2,4))\n /*\n println(findFirstLarger(a,0,a.length-1,4))\n assert(findFirstLarger(Array(1,2,3,5,6,7),0,a.length-1,4)==3)\n assert(findFirstLarger(Array(1),0,a.length-1,4) == -1)\n assert(findFirstLarger(Array(1,8),0,a.length-1,4) == 1)\n //assert(findFirstLarger(Array(1),0,a.length-1,4) == -1)\n */\n}\n\nobject scratch3 extends App{\n val a1 = Array(1,7)\n val a2 = a1.take(1)\n val a3 = a1.drop(1)\n a2.length\n a3.length\n println(a2(0))\n println(a3(0))\n\n}\n*/\n"}, {"source_code": "import scala.math._\nimport scala.io.StdIn._\n\nobject C537{\n\n case class Tree(left: Option[Tree], right: Option[Tree], value: Int) {\n def leftValOrElse(default: Int): Int = {\n left match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n\n def rightValOrElse(default: Int) = {\n right match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n }\n\n\n def growTree(T: Option[Tree], binaryString: String): Option[Tree] = {\n (T,binaryString) match {\n case (None,\"\") => Some(Tree(None,None,1))\n case (Some(tree),\"\") => Some(Tree(None,None,tree.value+1)) //??\n case (None,s) if s(0) == '0' => Some(Tree(growTree(None,s.tail), None, 1))\n case (None,s) if s(0) == '1' => Some(Tree(None, growTree(None,s.tail), 1))\n case (Some(tree),s) if s(0) == '0' => Some(Tree(growTree(tree.left, s.tail), tree.right,tree.value +1))\n case (Some(tree),s) if s(0) == '1' => Some(Tree(tree.left, growTree(tree.right, s.tail),tree.value +1))\n }\n }\n\n def populationTree(indices: List[Int],Len:Int): Option[Tree] = {\n val indices2binary = indices.map(_-1).map(_+Len).map(_.toBinaryString.tail)\n indices2binary.foldLeft[Option[Tree]](Some(Tree(None,None,0)))((T:Option[Tree], binStr) => growTree(T, binStr))\n }\n\n def powerTo1Shot(population: Int, Len: Int, A: Int, B: Int) = {\n population match {\n case 0 => A\n case na if na > 0 => na * Len * B\n }\n }\n\n def minimalPower(Len: Int, populationTree: Option[Tree], A: Int, B: Int): Double = {\n val populationWhole = populationTree match {\n case None => 0\n case Some(tree) => tree.value\n }\n\n val minPow = (populationTree,Len) match {\n case (None,_) => A\n case (Some(tree), length) if length == 1 => powerTo1Shot(length, populationWhole, A, B)\n case (Some(tree),length) if length>=2 => min(\n powerTo1Shot(Len, populationWhole, A, B),\n minimalPower(Len / 2, tree.left, A, B)+ minimalPower(Len / 2, tree.right, A, B)\n )\n }\n //println(minPow)\n minPow\n\n }\n\n def main(args: Array[String]) {\n val Array(n,k,a,b) = readLine.split(\" \").map(_.toInt)\n val A = a\n val B = b\n val indices = readLine.split(\" \").map(_.toInt)\n\n val Len = math.pow(2,n).toInt\n val populTree:Option[Tree]= populationTree(indices.toList,Len)\n val minPower = minimalPower(Len,populTree,A,B)\n println(minPower)\n }\n /*\n val n = 2\n val k = 2\n val A = 1\n val B = 2\n\n val indices = List(1,1)\n val Len = math.pow(2,n).toInt\n val populTree:Option[Tree]= populationTree(indices.toList,Len)\n val minPower = minimalPower(Len,populTree,A,B)\n println(populTree)\n println(minPower)\n */\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.math.min\n\nobject C537v2 {\n //find first index greater or equal to n\n //return array length if no such index exists\n //search range is [start,end)\n def binsearch(a:Array[Int],start:Int,end:Int,n:Long):Int={\n assert(end>start,\"end should be bigger index than start\")\n if(end-start>=2) {\n var s = start\n var e = end\n var m = (start + end) / 2\n\n while (s < m) {\n ((a(m) < n)) match {\n case true => {s = m}\n case false => e = m\n }\n m = (s + e) / 2\n }\n\n m+1\n }else{\n (a(start) end\n case false => start\n }\n }\n }\n\n def howManySmaller(sortedArray:Array[Int],range:(Int,Int),n:Long)={\n //println(s\"array in binsearch ${sortedArray.mkString(\",\")}\")\n //println(s\"range ${range}\")\n //println(s\"range ${range}\")\n //println(s\"${n}\")\n val j = binsearch(sortedArray,range._1,range._2,n)\n j - range._1\n }\n\n def powerTo1Shot(population: Int, Len: Long, A: Int, B: Int): Long = {\n population match {\n case 0 => A\n case na if na > 0 => na * Len * B\n }\n }\n //(start,end) - range of sortedIndices, with indices that reside in baseRange\n //populOnTheLeft - how many indices there is on the left from baseRange\n case class PopulationInfo(start:Int,end:Int,populOnTheLeft:Int)\n case class Parameters(A:Int,B:Int,popul:Int)\n\n def minPower3(baseRange:(Long,Long),\n sortedIndices:Array[Int],\n populData:PopulationInfo,\n p:Parameters\n ):Long={\n assert(baseRange._2-baseRange._1>=1,\"base range lower than 1\")\n\n val population = p.popul\n\n ((baseRange._2-baseRange._1,population)) match {\n case (length, pop) if length == 1 => powerTo1Shot(pop, length, p.A, p.B)\n case (length, 0) if length >= 1 => p.A\n case (length, pop) if length >= 2 => {\n val leftHalfBase = (baseRange._1,(baseRange._1+length/2))\n val rightHalfBase = (baseRange._1+length/2,baseRange._2)\n val breakPoint = binsearch(sortedIndices,populData.start,populData.end,baseRange._1+length/2)\n val populationLeft = breakPoint - populData.populOnTheLeft//ok\n val populationRight = pop - populationLeft\n/*\n println(s\"total pop ${p.popul}\")\n println(sortedIndices.mkString(\",\"))\n println(baseRange)\n println(s\"breakPoint ${breakPoint}\")\n println(s\"popul on the left ${populData.populOnTheLeft}\")\n println(s\"ppopuleft ${populationLeft}\")\n println(s\"ppopulright ${populationRight}\")\n println(s\"---NEXT----\")\n*/\n val popDataL = PopulationInfo(populData.start, breakPoint, populData.populOnTheLeft)\n val popDataR = PopulationInfo(breakPoint, populData.end, populData.populOnTheLeft+populationLeft)\n\n min(\n powerTo1Shot(pop, length, p.A, p.B),\n minPower3(leftHalfBase,sortedIndices,popDataL,Parameters(p.A,p.B,populationLeft))+\n minPower3(rightHalfBase,sortedIndices,popDataR,Parameters(p.A,p.B,populationRight))\n )\n }\n }\n }\n\n def minPowerMain(n:Int,indices:Array[Int],A:Int,B:Int,k:Int):Long ={\n assert(indices.length==k)\n val baseRange = (0.toLong, math.pow(2,n).toLong)\n val indicesSorted = indices.sorted.map(_-1)\n val popInfo = PopulationInfo(0,k,0)\n\n val p = Parameters(A,B,k)\n minPower3(baseRange,indicesSorted,popInfo,p)\n }\n\n\n def main(args: Array[String]) {\n val Array(n, k, a, b) = readLine.split(\" \").map(_.toInt)\n val A = a\n val B = b\n val indices = readLine.split(\" \").map(_.toInt)\n\n val minPower = minPowerMain(n,indices, A, B, k)\n println(minPower)\n }\n\n}\n\nobject test extends App{\n import C537v2._\n def runTests()= {\n println(howManySmaller(Array(1),(0,1),2)==1)\n println(howManySmaller(Array(1),(0,1),0)==0)\n println(howManySmaller(Array(0,1,2,3,4,5),(2,5),4)==2)\n println(howManySmaller(Array(0,1,2,3,4,5),(3,4),4)==1)\n println(howManySmaller(Array(0,1,2,3,4,5),(0,6),7)==6)\n println(howManySmaller(Array(0,1,2,3,4,5),(0,6),4)==4)\n }\n runTests()\n\n/*\nval n = 30\nval k = 88704\nval A = 1\nval B = 2140\nval Len = math.pow(2,n).toInt\n //val indices = List(1,3)\n//val Len = math.pow(2,n).toInt\n\nval rnd = new scala.util.Random(198987)\n//val indices = (1 to k).toArray.map(i=>rnd.nextInt(Len))\n//val indices = (1 to k).toArray.map(i=>rnd.nextInt(Len)).sorted\nval indices = (1 to k).toArray.map(i=>rnd.nextInt(Len)+1).map(_-1)\n //indices.sorted.foreach(print)\n //println(\"\\n--------------------\")\n//val indices = Array(858,765)\n//val indices = Array(858,765)\n\n val t1 = System.nanoTime()\n val populTree:Option[Tree]= populationTree(indices,n,Len)\n //indices.sorted\nval t2 = System.nanoTime()\n val minPower = minimalPower(Len,populTree,A,B)\nval t3 = System.nanoTime()\n val indicesSorted = indices.sorted\nval t4 = System.nanoTime()\n val minPower2 = minimalPower2(indicesSorted, 0, Len, A, B,(0,k))\nval t5 = System.nanoTime()\n\n println(minPower)\n println(minPower2)\n println(s\"tree: ${(t2-t1)*1.0/1e9}, which is ${(t2-t1)*1.0/(t3-t1)} of total time\")\n println(s\"rest: ${(t3-t2)*1.0/1e9}\")\n println(s\"whole ${(t3-t1)*1.0/1e9}\")\n println(s\"sorting ${(t4-t3)*1.0/1e9}\")\n println(s\"bin search ${(t5-t4)*1.0/1e9}\")\n //println(minimalPower2(4,Array(1),1,2))\n //println(minimalPower2(4,Array(3),1,2))\n //println(powerTo1Shot(2,8,1,2))\n //println(minimalPower2(Array(1,7), 0, 8, 1, 2))\n //println(minimalPower2(8,Array(1,1),1,2))\n //println(minimalPower2(8,Array(1,1),1,2))\n\n*/\n}\n\n\n\nobject scratch3 extends App{\n import C537v2._\n //testing howManySmaller3, get left, right ranges for population table\n val A = Array(3,3,5,7).sorted\n val r = 2\n //println(howManySmaller3(A,(0,4),r))\n //testing minPower3\n\n val sortedIndices = Array(1,3)\n val p = Parameters(1,2,sortedIndices.length)\n val baseRange = (0l,4l)\n val populData = PopulationInfo(0,4,0)\n /*\n val baseRange = (0l,4l)\n val populData = PopulationInfo(0,4,0)\n */\n /*\n val baseRange = (0l,2l)\n val populData = PopulationInfo(0,3,0)\n */\n\n\n //println(minPower3(baseRange,sortedIndices,populData,p))\n //println(s\"minPowL${minPower3(leftHalfBase,sortedIndices,popDataL,p)}\")\n println(minPowerMain(2,Array(1,1,1),A=1,B=2,k=3)==8)\n println(minPowerMain(2,Array(1,2),A=1,B=2,k=2)==5)\n println(minPowerMain(2,Array(1,3),A=1,B=2,k=2)==6)\n println(minPowerMain(3,Array(1,7),A=1,B=2,k=2)==8)\n\n //println(s\"minPowLL${minPower3((0,2),sortedIndices,PopulationInfo(0,3,0),p)}\")\n\n}\n\nobject testttt extends App{\n val a = Array(1,2,3)\n println(a.take(2).length)\n}"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.math.min\n\nobject C537v2 {\n\n case class Tree(var left: Option[Tree], var right: Option[Tree], var value: Int) {\n def leftValOrElse(default: Int): Int = {\n left match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n\n def rightValOrElse(default: Int) = {\n right match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n }\n\n /*\n def growTree(T: Option[Tree], binaryString: String): Option[Tree] = {\n (T, binaryString) match {\n case (None, \"\") => Some(Tree(None, None, 1))\n case (Some(tree), \"\") => Some(Tree(None, None, tree.value + 1)) //??\n case (None, s) if s(0) == '0' => Some(Tree(growTree(None, s.tail), None, 1))\n case (None, s) if s(0) == '1' => Some(Tree(None, growTree(None, s.tail), 1))\n case (Some(tree), s) if s(0) == '0' => Some(Tree(growTree(tree.left, s.tail), tree.right, tree.value + 1))\n case (Some(tree), s) if s(0) == '1' => Some(Tree(tree.left, growTree(tree.right, s.tail), tree.value + 1))\n }\n }\n */\n def growTree(T: Option[Tree], position: Long, binaryRepresentationLen: Int,Len:Long): Option[Tree] = {\n val firstDigit = position >>> (binaryRepresentationLen-1) & 1\n val otherDigits = position & (Len-1) //sets first bit to 0\n\n (T, firstDigit,binaryRepresentationLen) match {\n case (None, _,0) => Some(Tree(None, None, 1))\n case (Some(tree), _,0) => Some(Tree(None, None, tree.value + 1)) //??\n case (None, d,_) if d == 0 => Some(Tree(growTree(None, otherDigits,binaryRepresentationLen-1,Len/2), None, 1))\n case (None, d,_) if d == 1 => Some(Tree(None, growTree(None, otherDigits,binaryRepresentationLen-1,Len/2), 1))\n case (Some(tree), d,_) if d == 0 => Some(Tree(growTree(tree.left, otherDigits,binaryRepresentationLen-1,Len/2), tree.right, tree.value + 1))\n case (Some(tree), d,_) if d == 1 => Some(Tree(tree.left, growTree(tree.right, otherDigits,binaryRepresentationLen-1,Len/2), tree.value + 1))\n }\n }\n\n def populationTree(indices: Array[Int], binaryRepLen:Int ,Len: Long): Option[Tree] = {\n //indices.map(_ - 1).foldLeft[Option[Tree]](Some(Tree(None, None, 0)))((T: Option[Tree], pos) => growTree(T, pos,binaryRepLen,Len))\n\n var i = 0\n var T:Option[Tree] = Some(Tree(None, None, 0))\n while(i A\n case na if na > 0 => na * Len * B\n }\n }\n\n def minimalPower(Len: Long, populationTree: Option[Tree], A: Int, B: Int): Long = {\n val populationWhole = populationTree match {\n case None => 0\n case Some(tree) => tree.value\n }\n\n val minPow = (populationTree, Len) match {\n case (None, _) => A\n case (Some(tree), length) if length == 1 => powerTo1Shot(populationWhole, length, A, B)\n case (Some(tree), length) if length >= 2 => min(\n powerTo1Shot(populationWhole, Len, A, B),\n minimalPower(Len / 2, tree.left, A, B) + minimalPower(Len / 2, tree.right, A, B)\n )\n }\n //println(minPow)\n minPow\n\n }\n\n def findFirstLarger(a: Array[Int],left:Int,right:Int, n:Long): Int = {\n val right2 = if (right >= a.length) {\n a.length - 1\n } else {\n right\n }\n val mid = (left + right2) / 2\n\n (a(left), a(mid), a(right2)) match {\n case (le, mi, ri) if ri <= n => -1\n case (le, _, _) if le > n => left\n case (le, mi, _) if le == mi => right2\n case (le, mi, _) if mi > n => findFirstLarger(a, left, mid, n)\n case (le, mi, _) if mi <= n => findFirstLarger(a, mid, right, n)\n }\n }\n\n\n def minimalPower2(Len: Long, indicesSorted:Array[Int], A: Int, B: Int): Long = {\n\n val populationWhole = indicesSorted.length\n val mid = Len / 2\n val populationLeft = if(indicesSorted.length >0) {\n math.max(findFirstLarger(indicesSorted, 0, indicesSorted.length, mid),0)\n }else{\n 0\n }\n val minPow = (populationWhole, Len,indicesSorted.length) match {\n //case (0, length,_) if length == 0 => 0\n case (0,_,_) => A\n case (0, length,_) if length > 0 => A\n case (_, length,_) if length == 1 => powerTo1Shot(populationWhole, length, A, B)\n case (_, length,_) if length >= 2 => {\n min(\n powerTo1Shot(populationWhole, Len, A, B),\n minimalPower2(Len / 2, indicesSorted.take(populationLeft), A, B) + minimalPower2(Len / 2, indicesSorted.drop(populationLeft).map(i=>(i-Len/2).toInt), A, B)\n )\n }\n }\n //println(minPow)\n minPow\n }\n\n\n def main(args: Array[String]) {\n val Array(n, k, a, b) = readLine.split(\" \").map(_.toInt)\n val A = a\n val B = b\n val indices = readLine.split(\" \").map(_.toInt)\n\n val Len = math.pow(2, n).toLong\n //val populTree: Option[Tree] = populationTree(indices, n,Len)\n //val minPower = minimalPower(Len, populTree, A, B)\n val minPower = minimalPower2(Len,indices,A,B)\n println(minPower)\n }\n\n}\n\nobject test extends App{\n import C537v2._\n/*\nval n = 3\nval k = 2\nval A = 1\nval B = 2\n*/\n//val indices = Array(1,7)\n\n\nval n = 30\nval k = 10000\nval A = 78\nval B = 9765\n\n //val indices = List(1,3)\nval Len = math.pow(2,n).toInt\n\nval rnd = new scala.util.Random(1000)\nval indices = (1 to k).toArray.map(i=>rnd.nextInt(Len))\nval t1 = System.nanoTime()\n val populTree:Option[Tree]= populationTree(indices,n,Len)\n //indices.sorted\nval t2 = System.nanoTime()\n val minPower = minimalPower(Len,populTree,A,B)\nval t3 = System.nanoTime()\n val indicesSorted = indices.sorted\n val minPower2 = minimalPower2(Len,indices,A,B)\nval t4 = System.nanoTime()\n\n //println(minPower)\n //println(minPower2)\n println(s\"tree: ${(t2-t1)*1.0/1e9}, which is ${(t2-t1)*1.0/(t3-t1)} of total time\")\n println(s\"rest: ${(t3-t2)*1.0/1e9}\")\n println(s\"whole ${(t3-t1)*1.0/1e9}\")\n println(s\"bin search ${(t4-t3)*1.0/1e9}\")\n //println(minimalPower2(4,Array(1),1,2))\n //println(minimalPower2(4,Array(3),1,2))\n //println(powerTo1Shot(2,8,1,2))\n println(minimalPower2(8,Array(1,7),1,2))\n\n\n}\n\nobject scratch2 extends App{\n\n def findFirstLarger(a: Array[Int],left:Int,right:Int, n:Long): Int = {\n val right2 = if (right >= a.length) {\n a.length - 1\n } else {\n right\n }\n val mid = (left + right2) / 2\n\n (a(left), a(mid), a(right2)) match {\n case (le, mi, ri) if ri <= n => -1\n case (le, _, _) if le > n => left\n case (le, mi, _) if le == mi => right2\n case (le, mi, _) if mi > n => findFirstLarger(a, left, mid, n)\n case (le, mi, _) if mi <= n => findFirstLarger(a, mid, right, n)\n }\n }\n println(findFirstLarger(Array(1,7),0,2,4))\n /*\n println(findFirstLarger(a,0,a.length-1,4))\n assert(findFirstLarger(Array(1,2,3,5,6,7),0,a.length-1,4)==3)\n assert(findFirstLarger(Array(1),0,a.length-1,4) == -1)\n assert(findFirstLarger(Array(1,8),0,a.length-1,4) == 1)\n //assert(findFirstLarger(Array(1),0,a.length-1,4) == -1)\n */\n}\n\nobject scratch3 extends App{\n val a1 = Array(1,7)\n val a2 = a1.take(1)\n val a3 = a1.drop(1)\n a2.length\n a3.length\n println(a2(0))\n println(a3(0))\n\n}"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.math.min\n\nobject C537v2 {\n\n case class Tree(var left: Option[Tree], var right: Option[Tree], var value: Int) {\n def leftValOrElse(default: Int): Int = {\n left match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n\n def rightValOrElse(default: Int) = {\n right match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n }\n\n /*\n def growTree(T: Option[Tree], binaryString: String): Option[Tree] = {\n (T, binaryString) match {\n case (None, \"\") => Some(Tree(None, None, 1))\n case (Some(tree), \"\") => Some(Tree(None, None, tree.value + 1)) //??\n case (None, s) if s(0) == '0' => Some(Tree(growTree(None, s.tail), None, 1))\n case (None, s) if s(0) == '1' => Some(Tree(None, growTree(None, s.tail), 1))\n case (Some(tree), s) if s(0) == '0' => Some(Tree(growTree(tree.left, s.tail), tree.right, tree.value + 1))\n case (Some(tree), s) if s(0) == '1' => Some(Tree(tree.left, growTree(tree.right, s.tail), tree.value + 1))\n }\n }\n */\n def growTree(T: Option[Tree], position: Long, binaryRepresentationLen: Int,Len:Long): Option[Tree] = {\n val firstDigit = position >>> (binaryRepresentationLen-1) & 1\n val otherDigits = position & (Len-1) //sets first bit to 0\n\n (T, firstDigit,binaryRepresentationLen) match {\n case (None, _,0) => Some(Tree(None, None, 1))\n case (Some(tree), _,0) => Some(Tree(None, None, tree.value + 1)) //??\n case (None, d,_) if d == 0 => Some(Tree(growTree(None, otherDigits,binaryRepresentationLen-1,Len/2), None, 1))\n case (None, d,_) if d == 1 => Some(Tree(None, growTree(None, otherDigits,binaryRepresentationLen-1,Len/2), 1))\n case (Some(tree), d,_) if d == 0 => Some(Tree(growTree(tree.left, otherDigits,binaryRepresentationLen-1,Len/2), tree.right, tree.value + 1))\n case (Some(tree), d,_) if d == 1 => Some(Tree(tree.left, growTree(tree.right, otherDigits,binaryRepresentationLen-1,Len/2), tree.value + 1))\n }\n }\n\n def populationTree(indices: Array[Int], binaryRepLen:Int ,Len: Long): Option[Tree] = {\n //indices.map(_ - 1).foldLeft[Option[Tree]](Some(Tree(None, None, 0)))((T: Option[Tree], pos) => growTree(T, pos,binaryRepLen,Len))\n\n var i = 0\n var T:Option[Tree] = Some(Tree(None, None, 0))\n while(i A\n case na if na > 0 => na * Len * B\n }\n }\n\n def minimalPower(Len: Long, populationTree: Option[Tree], A: Int, B: Int): Long = {\n val populationWhole = populationTree match {\n case None => 0\n case Some(tree) => tree.value\n }\n\n val minPow = (populationTree, Len) match {\n case (None, _) => A\n case (Some(tree), length) if length == 1 => powerTo1Shot(populationWhole, length, A, B)\n case (Some(tree), length) if length >= 2 => min(\n powerTo1Shot(populationWhole, Len, A, B),\n minimalPower(Len / 2, tree.left, A, B) + minimalPower(Len / 2, tree.right, A, B)\n )\n }\n //println(minPow)\n minPow\n\n }\n\n def howManySmaller(a: Array[Int], n: Long): Int = {\n if(a.length >= 2){\n var start = 0\n var end = a.length-1\n\n var loopGuard = 0\n if(a(end)=n){0} else {\n while (end - start >= 2 && loopGuard < 1e10) {\n val mid = (start + end) / 2\n if (a(mid) < n) {\n start = mid\n } else {\n end = mid\n }\n loopGuard = loopGuard + 1\n }\n end\n }\n\n } else if(a.length == 1){\n if(a(0)<=n){1}else{0}\n }else{\n 0\n }\n }\n\n\n\n\n def minimalPower2(indicesSorted: Array[Int], start: Long, Len: Long, A: Int, B: Int): Long = {\n\n val populationWhole = indicesSorted.length\n\n val mid = start + Len / 2\n\n val minPow = (populationWhole, Len,indicesSorted.length) match {\n //case (_, 0,_) => 0\n case (0, length,_) if length>=1 => A\n case (_, length,_)if length==1 => powerTo1Shot(populationWhole, length, A, B)\n case (_, length,_) if length>=2 => {\n val breakPoint = howManySmaller(indicesSorted, mid)\n\n //println(\"--ss---\")\n //indicesSorted.foreach(print)\n //print(\"\\n\")\n //println(s\"mid ${mid}\")\n //println(s\"break point ${breakPoint}\")\n\n //println(\"-----\")\n val indicesLeft = indicesSorted.take(breakPoint)\n val indicesRight = indicesSorted.drop(breakPoint)\n //println(s\"powLeft: ${minimalPower2(indicesLeft, start, Len / 2, A, B)}\")\n //println(s\"powRight: ${minimalPower2(indicesRight, start, Len / 2, A, B)}\")\n\n min(\n\n powerTo1Shot(populationWhole, Len, A, B),\n minimalPower2(indicesLeft, start, Len / 2, A, B) +\n minimalPower2(indicesRight,start+Len/2 , Len / 2, A, B)\n )\n }\n }\n //println(minPow)\n minPow\n }\n\n\n def main(args: Array[String]) {\n val Array(n, k, a, b) = readLine.split(\" \").map(_.toInt)\n val A = a\n val B = b\n val indices = readLine.split(\" \")\n .map(_.toInt)\n .map(_-1) // so that they are in the range 0 to 2^n-1\n\n val Len = math.pow(2, n).toLong\n val populTree: Option[Tree] = populationTree(indices, n,Len)\n val minPower = minimalPower(Len, populTree, A, B)\n //val minPower = minimalPower2(indices, 0, Len, A, B)\n println(minPower)\n }\n\n}\n\nobject test extends App{\n import C537v2._\n\nval n = 30\nval k = 100000\nval A = 5\nval B = 2089\nval Len = math.pow(2,n).toInt\n //val indices = List(1,3)\n//val Len = math.pow(2,n).toInt\n\nval rnd = new scala.util.Random(19907)\n//val indices = (1 to k).toArray.map(i=>rnd.nextInt(Len))\n//val indices = (1 to k).toArray.map(i=>rnd.nextInt(Len)).sorted\nval indices = (1 to k).toArray.map(i=>rnd.nextInt(Len/2)+math.pow(2,29).toInt)\n //indices.foreach(println)\n //println(\"--------------------\")\n//val indices = Array(858,765)\n//val indices = Array(858,765)\n\n val t1 = System.nanoTime()\n val populTree:Option[Tree]= populationTree(indices,n,Len)\n //indices.sorted\nval t2 = System.nanoTime()\n val minPower = minimalPower(Len,populTree,A,B)\nval t3 = System.nanoTime()\n val indicesSorted = indices.sorted\n val minPower2 = minimalPower2(indicesSorted.map(_-1), 0, Len, A, B)\nval t4 = System.nanoTime()\n\n println(minPower)\n println(minPower2)\n //println(s\"tree: ${(t2-t1)*1.0/1e9}, which is ${(t2-t1)*1.0/(t3-t1)} of total time\")\n //println(s\"rest: ${(t3-t2)*1.0/1e9}\")\n //println(s\"whole ${(t3-t1)*1.0/1e9}\")\n //println(s\"bin search ${(t4-t3)*1.0/1e9}\")\n //println(minimalPower2(4,Array(1),1,2))\n //println(minimalPower2(4,Array(3),1,2))\n //println(powerTo1Shot(2,8,1,2))\n //println(minimalPower2(Array(1,7), 0, 8, 1, 2))\n //println(minimalPower2(8,Array(1,1),1,2))\n\n\n}\n\n\n\nobject scratch3 extends App{\n import C537v2._\n\n val a = Array(0,1,1,2)\n val len = 4\n val breakPoint = howManySmaller(a, 1l)\n println(howManySmaller(Array(0,1,1,2), 1l)==3)\n println(howManySmaller(Array(0,1,1,2), 2l))\n println(howManySmaller(Array(0,1,1,2), 2l))\n println(minimalPower2(Array(0,1,1,2,3), 0, 4, 1, 2))\n println(minimalPower2(Array(5,7), 4, 4, 1, 2))\n}\n\nobject testttt extends App{\n val a = Array(1,2,3)\n println(a.take(2).length)\n}"}, {"source_code": "import scala.math._\nimport scala.io.StdIn._\n\nobject C537{\n\n case class Tree(left: Option[Tree], right: Option[Tree], value: Int) {\n def leftValOrElse(default: Int): Int = {\n left match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n\n def rightValOrElse(default: Int) = {\n right match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n }\n\n\n def growTree(T: Option[Tree], binaryString: String): Option[Tree] = {\n (T,binaryString) match {\n case (None,\"\") => Some(Tree(None,None,1))\n case (Some(tree),\"\") => Some(Tree(None,None,1)) //??\n case (None,s) if s(0) == '0' => Some(Tree(growTree(None,binaryString.tail), None, 1))\n case (None,s) if s(0) == '1' => Some(Tree(None, growTree(None,binaryString.tail), 1))\n case (Some(tree),s) if s(0) == '0' => Some(Tree(growTree(tree.left, s.tail), tree.right,tree.value +1))\n case (Some(tree),s) if s(0) == '1' => Some(Tree(tree.left, growTree(tree.right, s.tail),tree.value +1))\n }\n }\n\n def populationTree(indices: List[Int],Len:Int): Option[Tree] = {\n val indices2binary = indices.map(_-1).map(_+Len).map(_.toBinaryString.tail)\n indices2binary.foldLeft[Option[Tree]](Some(Tree(None,None,0)))((T:Option[Tree], binStr) => growTree(T, binStr))\n }\n\n def powerTo1Shot(population: Int, Len: Int, A: Int, B: Int) = {\n population match {\n case 0 => A\n case na if na > 0 => na * Len * B\n }\n }\n\n def minimalPower(Len: Int, populationTree: Option[Tree], A: Int, B: Int): Double = {\n val populationWhole = populationTree match {\n case None => 0\n case Some(tree) => tree.value\n }\n\n val minPow = (populationTree,Len) match {\n case (None,_) => A\n case (Some(tree), length) if length == 1 => powerTo1Shot(length, populationWhole, A, B)\n case (Some(tree),length) if length>=2 => min(\n powerTo1Shot(Len, populationWhole, A, B),\n minimalPower(Len / 2, tree.left, A, B)+ minimalPower(Len / 2, tree.right, A, B)\n )\n }\n //println(minPow)\n minPow\n\n }\n\n def main(args: Array[String]) {\n val Array(n,k,a,b) = readLine.split(\" \").map(_.toInt)\n val A = a\n val B = b\n val indices = readLine.split(\" \").map(_.toInt)\n\n val Len = math.pow(2,n).toInt\n val populTree:Option[Tree]= populationTree(indices.toList,Len)\n val minPower = minimalPower(Len,populTree,A,B)\n println(minPower)\n }\n\n}\n"}, {"source_code": "import scala.math._\nimport scala.io.StdIn._\n\nobject C537 extends App{\n\n case class Tree(left: Option[Tree], right: Option[Tree], value: Int) {\n def leftValOrElse(default: Int): Int = {\n left match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n\n def rightValOrElse(default: Int) = {\n right match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n }\n\n\n def growTree(T: Option[Tree], binaryString: String): Option[Tree] = {\n (T,binaryString) match {\n case (None,\"\") => Some(Tree(None,None,1))\n case (Some(tree),\"\") => Some(Tree(None,None,tree.value+1)) //??\n case (None,s) if s(0) == '0' => Some(Tree(growTree(None,s.tail), None, 1))\n case (None,s) if s(0) == '1' => Some(Tree(None, growTree(None,s.tail), 1))\n case (Some(tree),s) if s(0) == '0' => Some(Tree(growTree(tree.left, s.tail), tree.right,tree.value +1))\n case (Some(tree),s) if s(0) == '1' => Some(Tree(tree.left, growTree(tree.right, s.tail),tree.value +1))\n }\n }\n\n def populationTree(indices: List[Int],Len:Int): Option[Tree] = {\n val indices2binary = indices.map(_-1).map(_+Len).map(_.toBinaryString.tail)\n indices2binary.foldLeft[Option[Tree]](Some(Tree(None,None,0)))((T:Option[Tree], binStr) => growTree(T, binStr))\n }\n\n def powerTo1Shot(population: Int, Len: Int, A: Int, B: Int) = {\n population match {\n case 0 => A\n case na if na > 0 => na * Len * B\n }\n }\n\n def minimalPower(Len: Int, populationTree: Option[Tree], A: Int, B: Int): Double = {\n val populationWhole = populationTree match {\n case None => 0\n case Some(tree) => tree.value\n }\n\n val minPow = (populationTree,Len) match {\n case (None,_) => A\n case (Some(tree), length) if length == 1 => powerTo1Shot(length, populationWhole, A, B)\n case (Some(tree),length) if length>=2 => min(\n powerTo1Shot(Len, populationWhole, A, B),\n minimalPower(Len / 2, tree.left, A, B)+ minimalPower(Len / 2, tree.right, A, B)\n )\n }\n //println(minPow)\n minPow\n\n }\n/*\n def main(args: Array[String]) {\n val Array(n,k,a,b) = readLine.split(\" \").map(_.toInt)\n val A = a\n val B = b\n val indices = readLine.split(\" \").map(_.toInt)\n\n val Len = math.pow(2,n).toInt\n val populTree:Option[Tree]= populationTree(indices.toList,Len)\n val minPower = minimalPower(Len,populTree,A,B)\n println(minPower)\n }\n*/\n val n = 2\n val k = 2\n val A = 1\n val B = 2\n\n val indices = List(1,1)\n val Len = math.pow(2,n).toInt\n val populTree:Option[Tree]= populationTree(indices.toList,Len)\n val minPower = minimalPower(Len,populTree,A,B)\n println(populTree)\n println(minPower)\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.math.min\n\nobject C537v2 {\n\n case class Tree(var left: Option[Tree], var right: Option[Tree], var value: Int) {\n def leftValOrElse(default: Int): Int = {\n left match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n\n def rightValOrElse(default: Int) = {\n right match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n }\n\n /*\n def growTree(T: Option[Tree], binaryString: String): Option[Tree] = {\n (T, binaryString) match {\n case (None, \"\") => Some(Tree(None, None, 1))\n case (Some(tree), \"\") => Some(Tree(None, None, tree.value + 1)) //??\n case (None, s) if s(0) == '0' => Some(Tree(growTree(None, s.tail), None, 1))\n case (None, s) if s(0) == '1' => Some(Tree(None, growTree(None, s.tail), 1))\n case (Some(tree), s) if s(0) == '0' => Some(Tree(growTree(tree.left, s.tail), tree.right, tree.value + 1))\n case (Some(tree), s) if s(0) == '1' => Some(Tree(tree.left, growTree(tree.right, s.tail), tree.value + 1))\n }\n }\n */\n def growTree(T: Option[Tree], position: Long, binaryRepresentationLen: Int,Len:Long): Option[Tree] = {\n val firstDigit = position >>> (binaryRepresentationLen-1) & 1\n val otherDigits = position & (Len-1) //sets first bit to 0\n\n (T, firstDigit,binaryRepresentationLen) match {\n case (None, _,0) => Some(Tree(None, None, 1))\n case (Some(tree), _,0) => Some(Tree(None, None, tree.value + 1)) //??\n case (None, d,_) if d == 0 => Some(Tree(growTree(None, otherDigits,binaryRepresentationLen-1,Len/2), None, 1))\n case (None, d,_) if d == 1 => Some(Tree(None, growTree(None, otherDigits,binaryRepresentationLen-1,Len/2), 1))\n case (Some(tree), d,_) if d == 0 => Some(Tree(growTree(tree.left, otherDigits,binaryRepresentationLen-1,Len/2), tree.right, tree.value + 1))\n case (Some(tree), d,_) if d == 1 => Some(Tree(tree.left, growTree(tree.right, otherDigits,binaryRepresentationLen-1,Len/2), tree.value + 1))\n }\n }\n\n def populationTree(indices: Array[Int], binaryRepLen:Int ,Len: Long): Option[Tree] = {\n //indices.map(_ - 1).foldLeft[Option[Tree]](Some(Tree(None, None, 0)))((T: Option[Tree], pos) => growTree(T, pos,binaryRepLen,Len))\n\n var i = 0\n var T:Option[Tree] = Some(Tree(None, None, 0))\n while(i A\n case na if na > 0 => na * Len * B\n }\n }\n\n def minimalPower(Len: Long, populationTree: Option[Tree], A: Int, B: Int): Long = {\n val populationWhole = populationTree match {\n case None => 0\n case Some(tree) => tree.value\n }\n\n val minPow = (populationTree, Len) match {\n case (None, _) => A\n case (Some(tree), length) if length == 1 => powerTo1Shot(populationWhole, length, A, B)\n case (Some(tree), length) if length >= 2 => min(\n powerTo1Shot(populationWhole, Len, A, B),\n minimalPower(Len / 2, tree.left, A, B) + minimalPower(Len / 2, tree.right, A, B)\n )\n }\n //println(minPow)\n minPow\n\n }\n\n def howManySmaller(a: Array[Int], left:Int, right:Int, n:Long): Int = {\n //to not get out of bounds error\n val right2 = if (right >= a.length) {\n a.length - 1\n } else {\n right\n }\n val mid = (left + right2) / 2\n\n (a(left), a(mid), a(right2)) match {\n case (le, mi, ri) if ri <= n => a.length //if right is smaller, everything is\n case (le, _, _) if le > n => left\n case (le, mi, _) if le == mi => right2\n case (le, mi, _) if mi > n => howManySmaller(a, left, mid, n)\n case (le, mi, _) if mi <= n => howManySmaller(a, mid, right, n)\n }\n }\n\n\n def minimalPower2(Len: Long, indicesSorted:Array[Int], A: Int, B: Int): Long = {\n\n val populationWhole = indicesSorted.length\n val mid = Len / 2\n val populationLeft = if(indicesSorted.length >0) {\n howManySmaller(indicesSorted, 0, indicesSorted.length, mid)\n }else{\n 0\n }\n val minPow = (populationWhole, Len,indicesSorted.length) match {\n //case (0, length,_) if length == 0 => 0\n case (0,_,_) => A\n case (0, length,_) if length > 0 => {\n println(s\"A: ${length}\")\n A\n }\n case (_, length,_) if length == 1 => {\n println(s\"popul ${populationWhole}\")\n println(s\"len ${length}\")\n println(s\"A ${A}\")\n println(s\"B ${B}\")\n println(s\"powTo1Shot ${powerTo1Shot(populationWhole, length, A, B)} \")\n println(\"jeb\")\n powerTo1Shot(populationWhole, length, A, B)}\n case (_, length,_) if length >= 2 => {\n val aa = indicesSorted.take(populationLeft)\n aa.foreach(x=>println(s\"${x}, a\"))\n val bb = indicesSorted.drop(populationLeft).map(i=>(i-Len/2).toInt)\n aa.foreach(x=>println(s\"${x}, b\"))\n indicesSorted.take(populationLeft)\n min(\n powerTo1Shot(populationWhole, Len, A, B),\n minimalPower2(Len / 2, indicesSorted.take(populationLeft), A, B) + minimalPower2(Len / 2, indicesSorted.drop(populationLeft).map(i=>(i-Len/2).toInt), A, B)\n )\n }\n }\n //println(minPow)\n minPow\n }\n\n\n def main(args: Array[String]) {\n val Array(n, k, a, b) = readLine.split(\" \").map(_.toInt)\n val A = a\n val B = b\n val indices = readLine.split(\" \").map(_.toInt)\n\n val Len = math.pow(2, n).toLong\n //val populTree: Option[Tree] = populationTree(indices, n,Len)\n //val minPower = minimalPower(Len, populTree, A, B)\n val minPower = minimalPower2(Len,indices,A,B)\n println(minPower)\n }\n\n}\n\nobject test extends App{\n import C537v2._\n/*\nval n = 3\nval k = 2\nval A = 1\nval B = 2\n*/\n//val indices = Array(1,7)\n\n\nval n = 30\nval k = 10000\nval A = 78\nval B = 9765\n\n //val indices = List(1,3)\nval Len = math.pow(2,n).toInt\n\nval rnd = new scala.util.Random(1000)\nval indices = (1 to k).toArray.map(i=>rnd.nextInt(Len))\nval t1 = System.nanoTime()\n val populTree:Option[Tree]= populationTree(indices,n,Len)\n //indices.sorted\nval t2 = System.nanoTime()\n val minPower = minimalPower(Len,populTree,A,B)\nval t3 = System.nanoTime()\n val indicesSorted = indices.sorted\n val minPower2 = minimalPower2(Len,indices,A,B)\nval t4 = System.nanoTime()\n\n //println(minPower)\n //println(minPower2)\n println(s\"tree: ${(t2-t1)*1.0/1e9}, which is ${(t2-t1)*1.0/(t3-t1)} of total time\")\n println(s\"rest: ${(t3-t2)*1.0/1e9}\")\n println(s\"whole ${(t3-t1)*1.0/1e9}\")\n println(s\"bin search ${(t4-t3)*1.0/1e9}\")\n //println(minimalPower2(4,Array(1),1,2))\n //println(minimalPower2(4,Array(3),1,2))\n //println(powerTo1Shot(2,8,1,2))\n //println(minimalPower2(8,Array(1,7),1,2))\n println(minimalPower2(8,Array(1,1),1,2))\n\n\n}\n\nobject scratch2 extends App{\n\n def findFirstLarger(a: Array[Int],left:Int,right:Int, n:Long): Int = {\n val right2 = if (right >= a.length) {\n a.length - 1\n } else {\n right\n }\n val mid = (left + right2) / 2\n\n (a(left), a(mid), a(right2)) match {\n case (le, mi, ri) if ri <= n => -1\n case (le, _, _) if le > n => left\n case (le, mi, _) if le == mi => right2\n case (le, mi, _) if mi > n => findFirstLarger(a, left, mid, n)\n case (le, mi, _) if mi <= n => findFirstLarger(a, mid, right, n)\n }\n }\n //println(findFirstLarger(Array(1,7),0,2,4))\n /*\n println(findFirstLarger(a,0,a.length-1,4))\n assert(findFirstLarger(Array(1,2,3,5,6,7),0,a.length-1,4)==3)\n assert(findFirstLarger(Array(1),0,a.length-1,4) == -1)\n assert(findFirstLarger(Array(1,8),0,a.length-1,4) == 1)\n //assert(findFirstLarger(Array(1),0,a.length-1,4) == -1)\n */\n}\n\nobject scratch3 extends App{\n val a1 = Array(1,7)\n val a2 = a1.take(1)\n val a3 = a1.drop(1)\n a2.length\n a3.length\n println(a2(0))\n println(a3(0))\n\n}"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.math.min\n\nobject C537v2 {\n\n case class Tree(var left: Option[Tree], var right: Option[Tree], var value: Int) {\n def leftValOrElse(default: Int): Int = {\n left match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n\n def rightValOrElse(default: Int) = {\n right match {\n case None => default\n case Some(tree) => tree.value\n }\n }\n }\n\n /*\n def growTree(T: Option[Tree], binaryString: String): Option[Tree] = {\n (T, binaryString) match {\n case (None, \"\") => Some(Tree(None, None, 1))\n case (Some(tree), \"\") => Some(Tree(None, None, tree.value + 1)) //??\n case (None, s) if s(0) == '0' => Some(Tree(growTree(None, s.tail), None, 1))\n case (None, s) if s(0) == '1' => Some(Tree(None, growTree(None, s.tail), 1))\n case (Some(tree), s) if s(0) == '0' => Some(Tree(growTree(tree.left, s.tail), tree.right, tree.value + 1))\n case (Some(tree), s) if s(0) == '1' => Some(Tree(tree.left, growTree(tree.right, s.tail), tree.value + 1))\n }\n }\n */\n def growTree(T: Option[Tree], position: Long, binaryRepresentationLen: Int,Len:Long): Option[Tree] = {\n val firstDigit = position >>> (binaryRepresentationLen-1) & 1\n val otherDigits = position & (Len-1) //sets first bit to 0\n\n (T, firstDigit,binaryRepresentationLen) match {\n case (None, _,0) => Some(Tree(None, None, 1))\n case (Some(tree), _,0) => Some(Tree(None, None, tree.value + 1)) //??\n case (None, d,_) if d == 0 => Some(Tree(growTree(None, otherDigits,binaryRepresentationLen-1,Len/2), None, 1))\n case (None, d,_) if d == 1 => Some(Tree(None, growTree(None, otherDigits,binaryRepresentationLen-1,Len/2), 1))\n case (Some(tree), d,_) if d == 0 => Some(Tree(growTree(tree.left, otherDigits,binaryRepresentationLen-1,Len/2), tree.right, tree.value + 1))\n case (Some(tree), d,_) if d == 1 => Some(Tree(tree.left, growTree(tree.right, otherDigits,binaryRepresentationLen-1,Len/2), tree.value + 1))\n }\n }\n\n def populationTree(indices: Array[Int], binaryRepLen:Int ,Len: Long): Option[Tree] = {\n //indices.map(_ - 1).foldLeft[Option[Tree]](Some(Tree(None, None, 0)))((T: Option[Tree], pos) => growTree(T, pos,binaryRepLen,Len))\n\n var i = 0\n var T:Option[Tree] = Some(Tree(None, None, 0))\n while(i A\n case na if na > 0 => na * Len * B\n }\n }\n\n def minimalPower(Len: Long, populationTree: Option[Tree], A: Int, B: Int): Long = {\n val populationWhole = populationTree match {\n case None => 0\n case Some(tree) => tree.value\n }\n\n val minPow = (populationTree, Len) match {\n case (None, _) => A\n case (Some(tree), length) if length == 1 => powerTo1Shot(populationWhole, length, A, B)\n case (Some(tree), length) if length >= 2 => min(\n powerTo1Shot(populationWhole, Len, A, B),\n minimalPower(Len / 2, tree.left, A, B) + minimalPower(Len / 2, tree.right, A, B)\n )\n }\n //println(minPow)\n minPow\n\n }\n\n def howManySmaller(a: Array[Int], n: Long): Int = {\n if(a.length >= 2){\n var start = 0\n var end = a.length-1\n\n var loopGuard = 0\n if(a(end)=n){0} else {\n while (end - start >= 2 && loopGuard < 1e10) {\n val mid = (start + end) / 2\n if (a(mid) < n) {\n start = mid\n } else {\n end = mid\n }\n loopGuard = loopGuard + 1\n }\n end\n }\n\n } else if(a.length == 1){\n if(a(0)<=n){1}else{0}\n }else{\n 0\n }\n }\n\n\n\n\n def minimalPower2(indicesSorted: Array[Int], start: Long, Len: Long, A: Int, B: Int): Long = {\n\n val populationWhole = indicesSorted.length\n\n val mid = start + Len / 2\n\n val minPow = (populationWhole, Len,indicesSorted.length) match {\n //case (_, 0,_) => 0\n case (0, length,_) if length>=1 => A\n case (_, length,_)if length==1 => powerTo1Shot(populationWhole, length, A, B)\n case (_, length,_) if length>=2 => {\n val breakPoint = howManySmaller(indicesSorted, mid)\n\n //println(\"--ss---\")\n //indicesSorted.foreach(print)\n //print(\"\\n\")\n //println(s\"mid ${mid}\")\n //println(s\"break point ${breakPoint}\")\n\n //println(\"-----\")\n val indicesLeft = indicesSorted.take(breakPoint)\n val indicesRight = indicesSorted.drop(breakPoint)\n //println(s\"powLeft: ${minimalPower2(indicesLeft, start, Len / 2, A, B)}\")\n //println(s\"powRight: ${minimalPower2(indicesRight, start, Len / 2, A, B)}\")\n\n min(\n\n powerTo1Shot(populationWhole, Len, A, B),\n minimalPower2(indicesLeft, start, Len / 2, A, B) +\n minimalPower2(indicesRight,start+Len/2 , Len / 2, A, B)\n )\n }\n }\n //println(minPow)\n minPow\n }\n\n\n def main(args: Array[String]) {\n val Array(n, k, a, b) = readLine.split(\" \").map(_.toInt)\n val A = a\n val B = b\n val indices = readLine.split(\" \")\n .map(_.toInt)\n .map(_-1) // so that they are in the range 0 to 2^n-1\n\n val Len = math.pow(2, n).toLong\n //val populTree: Option[Tree] = populationTree(indices, n,Len)\n //val minPower = minimalPower(Len, populTree, A, B)\n val minPower = minimalPower2(indices, 0, Len, A, B)\n println(minPower)\n }\n\n}\n\nobject test extends App{\n import C537v2._\n\nval n = 20\nval k = 700\nval A = 19\nval B = 278\nval Len = math.pow(2,n).toInt\n //val indices = List(1,3)\n//val Len = math.pow(2,n).toInt\n\nval rnd = new scala.util.Random(10067)\n//val indices = (1 to k).toArray.map(i=>rnd.nextInt(Len))\nval indices = (1 to k).toArray.map(i=>rnd.nextInt(Len)+1).sorted\n //indices.foreach(println)\n //println(\"--------------------\")\n//val indices = Array(858,765)\n//val indices = Array(858,765)\n\n val t1 = System.nanoTime()\n val populTree:Option[Tree]= populationTree(indices,n,Len)\n //indices.sorted\nval t2 = System.nanoTime()\n val minPower = minimalPower(Len,populTree,A,B)\nval t3 = System.nanoTime()\n val indicesSorted = indices.sorted\n val minPower2 = minimalPower2(indicesSorted.map(_-1), 0, Len, A, B)\nval t4 = System.nanoTime()\n\n println(minPower)\n println(minPower2)\n //println(s\"tree: ${(t2-t1)*1.0/1e9}, which is ${(t2-t1)*1.0/(t3-t1)} of total time\")\n //println(s\"rest: ${(t3-t2)*1.0/1e9}\")\n //println(s\"whole ${(t3-t1)*1.0/1e9}\")\n //println(s\"bin search ${(t4-t3)*1.0/1e9}\")\n //println(minimalPower2(4,Array(1),1,2))\n //println(minimalPower2(4,Array(3),1,2))\n //println(powerTo1Shot(2,8,1,2))\n //println(minimalPower2(Array(1,7), 0, 8, 1, 2))\n //println(minimalPower2(8,Array(1,1),1,2))\n\n\n}\n\n\n\nobject scratch3 extends App{\n import C537v2._\n\n val a = Array(0,1,1,2)\n val len = 4\n val breakPoint = howManySmaller(a, 1l)\n println(howManySmaller(Array(0,1,1,2), 1l)==3)\n println(howManySmaller(Array(0,1,1,2), 2l))\n println(howManySmaller(Array(0,1,1,2), 2l))\n println(minimalPower2(Array(0,1,1,2,3), 0, 4, 1, 2))\n println(minimalPower2(Array(5,7), 4, 4, 1, 2))\n}\n\nobject testttt extends App{\n val a = Array(1,2,3)\n println(a.take(2).length)\n}"}], "src_uid": "4695aa2b3590a0734ef2c6c580e471a9"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S = ns().map(_ == '0') // true == vertical\n var v = false\n var h = false\n REP(S.length) { i =>\n if (S(i)) {\n if (v) {\n out.println(\"3 1\")\n v = false\n } else {\n out.println(\"1 1\")\n v = true\n }\n } else {\n if (h) {\n out.println(\"4 1\")\n h = false\n } else {\n out.println(\"4 3\")\n h = true\n }\n }\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object Main {\n\n def main(args: Array[String]) {\n val std = scala.io.StdIn\n\n val n = std.readLine()\n\n var hasVert = false\n var hasHor = false\n for (i <- 0 until n.length) {\n n(i) match {\n case '0' if hasVert =>\n hasVert = false\n println(3 + \" \" + 1)\n case '0' =>\n hasVert = true\n println(1 + \" \" + 1)\n case '1' if hasHor =>\n hasHor = false\n println(4 + \" \" + 1)\n case '1' =>\n hasHor = true\n println(4 + \" \" + 3)\n }\n }\n }\n}"}], "negative_code": [], "src_uid": "a63cdbd1009a60c0f9b52e4ffbba252e"} {"source_code": "object Main\n{\n\tdef min (a : Int, b : Int) : Int = \n\t\tif (a < b) return a\n\t\telse return b\n\tdef main (args : Array[String]) = \n\t{\n\t\tvar parni = scala.collection.mutable.Map[Int,Int]()\n\t\tvar neparni = scala.collection.mutable.Map[Int,Int]()\n\n\t\tval n = readLine.toInt\n\t\tval arr = readLine.split(' ').map(_.toInt)\n\n\t\tvar dp = new Array[Int](n+2)\n\t\tdp(0) = 0\n\t\tfor (i <- 1 to n)\n\t\t\tdp(i) = dp(i-1) ^ arr(i-1)\n\t\tvar rez : BigInt = 0\n\n\t\tparni.update(0,1)\n\n\t\tfor (i <- 1 to n)\n\t\t{\n\t\t\t//println(\"za i = \" + i)\n\t\t\tvar a = dp(i)\n\t\t\t//println(\"a = \" + a)\n\t\t\tvar b = 0\n\n\t\t\tif (i%2 == 1 && neparni.contains(a))\n\t\t\t\tb = neparni(a)\n\t\t\telse if (i%2 == 0 && parni.contains(a))\n\t\t\t\tb = parni(a)\n\n\t\t\t//println(\"b = \" + b)\n\n\t\t\trez += b\n\t\t\t//println(\"rez = \" + rez)\n\n\t\t\tif (i%2 == 0)\n\t\t\t\tparni.update(a,b+1)\n\t\t\telse \n\t\t\t\tneparni.update(a,b+1)\n\t\t}\n\t\tprintln(rez)\n\t}\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer \n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = nal(N)\n val cum = Array.ofDim[Long](N + 1)\n REP(N) { i =>\n cum(i + 1) = cum(i) ^ A(i)\n }\n\n// debug(cum)\n\n class Counter {\n var even: Long = 0\n var odd: Long = 0\n\n override def toString: String = s\"($even, $odd)\"\n }\n val ix = mutable.Map[Long, Counter]()\n REP(N + 1) { i =>\n if (!ix.contains(cum(i))) ix(cum(i)) = new Counter\n if (i % 2 == 0) ix(cum(i)).even += 1\n else ix(cum(i)).odd += 1\n }\n\n// debug(ix.mkString)\n\n var ans = 0L\n ix.foreach { case (_, cnt) =>\n ans += cnt.even * (cnt.even - 1) / 2\n ans += cnt.odd * (cnt.odd - 1) / 2\n }\n\n out.println(ans)\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}], "negative_code": [{"source_code": "object Main\n{\n\tdef min (a : Int, b : Int) : Int = \n\t\tif (a < b) return a\n\t\telse return b\n\tdef main (args : Array[String]) = \n\t{\n\t\tvar parni = scala.collection.mutable.Map[Int,Int]()\n\t\tvar neparni = scala.collection.mutable.Map[Int,Int]()\n\n\t\tval n = readLine.toInt\n\t\tval arr = readLine.split(' ').map(_.toInt)\n\n\t\tvar dp = new Array[Int](n+2)\n\t\tdp(0) = 0\n\t\tfor (i <- 1 to n)\n\t\t\tdp(i) = dp(i-1) ^ arr(i-1)\n\t\tvar rez = 0\n\n\t\tparni.update(0,1)\n\n\t\tfor (i <- 1 to n)\n\t\t{\n\t\t\t//println(\"za i = \" + i)\n\t\t\tvar a = dp(i)\n\t\t\t//println(\"a = \" + a)\n\t\t\tvar b = 0\n\n\t\t\tif (i%2 == 1 && neparni.contains(a))\n\t\t\t\tb = neparni(a)\n\t\t\telse if (i%2 == 0 && parni.contains(a))\n\t\t\t\tb = parni(a)\n\n\t\t\t//println(\"b = \" + b)\n\n\t\t\trez += b\n\t\t\t//println(\"rez = \" + rez)\n\n\t\t\tif (i%2 == 0)\n\t\t\t\tparni.update(a,b+1)\n\t\t\telse \n\t\t\t\tneparni.update(a,b+1)\n\t\t}\n\t\tprintln(rez)\n\t}\n}"}], "src_uid": "e9cf26e61ebff8ad8d3b857c429d3aa9"} {"source_code": "\n\nimport scala.io.StdIn\n\nobject YetAnotherArrayPartition {\n def main(args: Array[String]): Unit = {\n val content = StdIn.readLine()\n val line1Arg = content.split(\" \")\n val nums = line1Arg(0).toInt\n val minSize = line1Arg(1).toInt\n val partitions = line1Arg(2).toInt\n val line2 = StdIn.readLine()\n val line2Arg = line2.split(\" \")\n val arrayBuffer = scala.collection.mutable.ArrayBuffer[Int]()\n for (i <- 0 until nums) {\n arrayBuffer.append(line2Arg(i).toInt)\n }\n val validNum = minSize * partitions\n val sorted = arrayBuffer.sorted.reverse\n val minValid = sorted(validNum - 1)\n var idx = validNum - 1\n var minValidNumCount = 0\n while (idx >= 0 && minValid == sorted(idx)) {\n minValidNumCount += 1\n idx -= 1\n }\n val splitArray = scala.collection.mutable.ListBuffer[Int]()\n var splitIdx = 0\n var remainValidCount = minValidNumCount\n var curPartitionValidNums = 0\n var i = 0\n var break = false\n var curPartitionSum = 0L\n var totalSum = 0L\n while (i < nums && !break) {\n if (arrayBuffer(i) > minValid) {\n curPartitionValidNums += 1\n curPartitionSum += arrayBuffer(i)\n if (curPartitionValidNums == minSize) {\n totalSum += curPartitionSum\n curPartitionSum = 0\n curPartitionValidNums = 0\n splitIdx += 1\n if (splitIdx != partitions) {\n splitArray.append(i + 1)\n }\n }\n } else if (arrayBuffer(i) == minValid && remainValidCount > 0) {\n remainValidCount -= 1\n curPartitionValidNums += 1\n curPartitionSum += arrayBuffer(i)\n if (curPartitionValidNums == minSize) {\n totalSum += curPartitionSum\n curPartitionSum = 0\n curPartitionValidNums = 0\n splitIdx += 1\n if (splitIdx != partitions) {\n splitArray.append(i + 1)\n }\n }\n } else {\n\n }\n\n if (splitIdx == partitions) {\n break = true\n }\n i += 1\n }\n println(totalSum)\n println(splitArray.mkString(\" \"))\n }\n}\n\n\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject B1114ArraySplit extends App {\n val n::m::k::_ = readLine().split(\" \").map(_.toInt).toList\n val as = readLine().split(\" \").map(BigInt(_)).toList\n\n val cuts = as.zipWithIndex.sortBy(_._1).takeRight(m * k).map(_._2).sorted.zipWithIndex.filter(x => x._2 % m == 0).map(_._1).tail\n\n println(as.sorted.takeRight(m * k).sum)\n println(cuts.mkString(\" \"))\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n import java.util.Comparator\n val N, M, K = ni()\n val A = na(N)\n val ix = Array.ofDim[Integer](N)\n REP(N) { i =>\n ix(i) = i\n }\n\n // Aの降順で並べる\n java.util.Arrays.sort(ix, new Comparator[Integer] {\n override def compare(o1: Integer, o2: Integer): Int = Integer.compare(A(o2), A(o1))\n })\n\n // ixの昇順でソート\n val B = ix.take(M * K)\n java.util.Arrays.sort(B, new Comparator[Integer] {\n override def compare(o1: Integer, o2: Integer): Int = o1.compareTo(o2)\n })\n\n var S = 0L\n REP(B.length) { i =>\n S += A(B(i))\n }\n\n out.println(S)\n// debug(B.mkString(\" \"))\n\n val ans = ArrayBuffer[Int]()\n REP(K - 1, 1) { i =>\n ans += B(i * M - 1) + 1\n }\n out.println(ans.mkString(\" \"))\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Codeforces114B {\n\n def getSubArrayPartitions(n: Int, m: Int, k: Int, a: Seq[Int]): (Long, Seq[Int]) = {\n val largerNumbers = a.sorted.reverse.take(m * k)\n val largeNumberFrequencyMap: mutable.Map[Int, Int] = toFrequencyMap(largerNumbers)\n val partition = new Array[Int](k - 1)\n var inputIndex = 0\n for (outputIndex <- partition.indices) {\n var subArrayIndex = 0\n while (subArrayIndex < m) {\n val element = a(inputIndex)\n if (largeNumberFrequencyMap.getOrElse(element, 0) > 0) {\n largeNumberFrequencyMap(element) -= 1\n subArrayIndex += 1\n }\n inputIndex += 1\n }\n partition(outputIndex) = inputIndex\n }\n (largerNumbers.map(_.toLong).sum, partition)\n }\n\n private def toFrequencyMap(numbers: Seq[Int]): mutable.Map[Int, Int] = {\n val frequencyMap = new mutable.HashMap[Int, Int]()\n for (number <- numbers) {\n frequencyMap(number) = frequencyMap.getOrElse(number, 0) + 1\n }\n frequencyMap\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m, k) = StdIn.readLine().trim.split(\" \").map(_.toInt)\n val a = StdIn.readLine().trim.split(\" \").map(_.toInt)\n\n val result = getSubArrayPartitions(n, m, k, a)\n val sum = result._1\n val partition = result._2\n println(sum)\n println(partition.mkString(\" \"))\n }\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject B1114ArraySplit extends App {\n val n::m::k::_ = readLine().split(\" \").map(_.toInt).toList\n val as = readLine().split(\" \").map(_.toInt).toList\n\n println(as.sorted.takeRight(m * k).sum)\n println((1 until k).map(x => x * m).mkString(\" \"))\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject B1114ArraySplit extends App {\n val n::m::k::_ = readLine().split(\" \").map(_.toInt).toList\n val as = readLine().split(\" \").map(_.toInt).toList\n\n val cuts = as.zipWithIndex.sortBy(_._1).takeRight(m * k).map(_._2).sorted.zipWithIndex.filter(x => x._2 % m == 0).map(_._1).tail\n\n println(as.sorted.takeRight(m * k).sum)\n println(cuts.mkString(\" \"))\n}\n"}, {"source_code": "\n\nimport scala.io.StdIn\n\nobject YetAnotherArrayPartition {\n def main(args: Array[String]): Unit = {\n val content = StdIn.readLine()\n val line1Arg = content.split(\" \")\n val nums = line1Arg(0).toInt\n val minSize = line1Arg(1).toInt\n val partitions = line1Arg(2).toInt\n val line2 = StdIn.readLine()\n val line2Arg = line2.split(\" \")\n val arrayBuffer = scala.collection.mutable.ArrayBuffer[Int]()\n for (i <- 0 until nums) {\n arrayBuffer.append(line2Arg(i).toInt)\n }\n val validNum = minSize * partitions\n val sorted = arrayBuffer.sorted.reverse\n val minValid = sorted(validNum - 1)\n var idx = validNum - 1\n var minValidNumCount = 0\n while (minValid == sorted(idx)) {\n minValidNumCount += 1\n idx -= 1\n }\n val splitArray = scala.collection.mutable.ListBuffer[Int]()\n var splitIdx = 0\n var remainValidCount = minValidNumCount\n var curPartitionValidNums = 0\n var i = 0\n var break = false\n var curPartitionSum = 0\n var totalSum = 0\n while (i < nums && !break) {\n if (arrayBuffer(i) > minValid) {\n curPartitionValidNums += 1\n curPartitionSum += arrayBuffer(i)\n if (curPartitionValidNums == minSize) {\n totalSum += curPartitionSum\n curPartitionSum = 0\n curPartitionValidNums = 0\n splitIdx += 1\n if (splitIdx != partitions) {\n splitArray.append(i + 1)\n }\n }\n } else if (arrayBuffer(i) == minValid && remainValidCount > 0) {\n remainValidCount -= 1\n curPartitionValidNums += 1\n curPartitionSum += arrayBuffer(i)\n if (curPartitionValidNums == minSize) {\n totalSum += curPartitionSum\n curPartitionSum = 0\n curPartitionValidNums = 0\n splitIdx += 1\n if (splitIdx != partitions) {\n splitArray.append(i + 1)\n }\n }\n } else {\n\n }\n\n if (splitIdx == partitions) {\n break = true\n }\n i += 1\n }\n println(totalSum)\n println(splitArray.mkString(\" \"))\n }\n}\n\n\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Codeforces114B {\n\n def getSubArrayPartitions(n: Int, m: Int, k: Int, a: Seq[Int]): (Int, Seq[Int]) = {\n val largerNumbers = a.sorted.reverse.take(m * k)\n val largeNumberFrequencyMap: mutable.Map[Int, Int] = toFrequencyMap(largerNumbers)\n val partition = new Array[Int](k - 1)\n var inputIndex = 0\n for (outputIndex <- partition.indices) {\n var subArrayIndex = 0\n while (subArrayIndex < m) {\n val element = a(inputIndex)\n if (largeNumberFrequencyMap.getOrElse(element, 0) > 0) {\n largeNumberFrequencyMap(element) -= 1\n subArrayIndex += 1\n }\n inputIndex += 1\n }\n partition(outputIndex) = inputIndex\n }\n (largerNumbers.sum, partition)\n }\n\n private def toFrequencyMap(numbers: Seq[Int]): mutable.Map[Int, Int] = {\n val frequencyMap = new mutable.HashMap[Int, Int]()\n for (number <- numbers) {\n frequencyMap(number) = frequencyMap.getOrElse(number, 0) + 1\n }\n frequencyMap\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m, k) = StdIn.readLine().trim.split(\" \").map(_.toInt)\n val a = StdIn.readLine().trim.split(\" \").map(_.toInt)\n\n val result = getSubArrayPartitions(n, m, k, a)\n val sum = result._1\n val partition = result._2\n println(sum)\n println(partition.mkString(\" \"))\n }\n}"}], "src_uid": "e9cf68a68b55fe075099c384cb6a7e9e"} {"source_code": "\nimport java.util\n\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 19 Jun 2016\n */\nobject A217 extends App {\n\n def dfs(g: mutable.Map[Int, util.ArrayList[Int]], start: Int, visited: Array[Boolean]): Unit = {\n visited(start) = true\n if (g.contains(start)) {\n val neighbors: util.ArrayList[Int] = g(start)\n for (i <- 0 until neighbors.size()) {\n val neighbor: Int = neighbors.get(i)\n if (!visited(neighbor)) {\n dfs(g, neighbor, visited)\n }\n }\n }\n }\n\n def solve() = {\n val n: Int = scala.io.StdIn.readInt()\n val coords: Array[(Int, Int)] = Array.ofDim(n)\n for (i <- 0 until n) {\n val Array(x, y) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n coords(i) = (x, y)\n }\n val g: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty[Int, util.ArrayList[Int]]\n for (i <- 0 until n) {\n for (j <- i+1 until n) {\n if (coords(i)._1 == coords(j)._1 || coords(i)._2 == coords(j)._2) {\n if (!g.contains(i)) {\n g += (i -> new util.ArrayList[Int]())\n }\n g(i).add(j)\n if (!g.contains(j)) {\n g += (j -> new util.ArrayList[Int]())\n }\n g(j).add(i)\n }\n }\n }\n val visited: Array[Boolean] = Array.ofDim(n)\n var c = 0\n for (i <- 0 until n) {\n if (!visited(i)) {\n dfs(g, i, visited)\n c += 1\n }\n }\n println(c-1)\n }\n\n solve()\n\n}\n", "positive_code": [{"source_code": "object IceSkating {\n case class Edge(u:Int,v:Int) {\n def ==(that:Edge):Boolean={\n return (this.u==that.u)||(this.v==that.v)\n }\n }\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n var n=in.readInt()\n val edges=Array.fill[Edge](n)(null)\n for(i<- 0 until n){\n val arr=in.readLine().split(\" \").map(_.toInt)\n edges(i)=Edge(arr(0),arr(1))\n }\n\n //The intuition is to find connected component using dfs\n //and we will consider two component is connected is two points are fall under same x or y co-ordinate\n val visited=Array.fill[Boolean](n)(false)\n var cou=0\n for(i<- 0 until edges.length ){\n if(!visited(i)){\n cou+=1\n dfs(edges,visited,i)\n }\n }\n println(cou-1)\n }\n def dfs(edges:Array[Edge],vis:Array[Boolean],n:Int):Unit={\n vis(n)=true\n for(i<- 0 until edges.length if(!vis(i) && edges(i)==edges(n))){\n dfs(edges,vis,i)\n }\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n var cache = Set.empty[(Set[Int], Set[Int])]\n Range(0, n).map{_ =>\n in.next().split(\" \").map(_.toInt)\n }.foreach {\n case Array(a, b) =>\n val first = cache.find(_._1.contains(a))\n val second = cache.find(_._2.contains(b))\n if (first.isEmpty && second.isEmpty)\n cache += ((Set(a), Set(b)))\n else if (first.isDefined && second.isDefined) {\n cache -= first.get\n cache -= second.get\n cache += ((first.get._1 ++ second.get._1, first.get._2 ++ second.get._2))\n } else if (first.isDefined) {\n cache -= first.get\n cache += ((first.get._1 + a, first.get._2 + b))\n } else {\n cache -= second.get\n cache += ((second.get._1 + a, second.get._2 + b))\n }\n }\n println(cache.size - 1)\n}"}], "negative_code": [{"source_code": "\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 19 Jun 2016\n */\nobject A217 extends App {\n\n def solve() = {\n val n: Int = scala.io.StdIn.readInt()\n val xs: mutable.Set[Int] = mutable.Set.empty[Int]\n val ys: mutable.Set[Int] = mutable.Set.empty[Int]\n for (i <- 0 until n) {\n val Array(x, y) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n xs += x\n ys += y\n }\n println(Math.min(xs.size, ys.size) - 1)\n }\n\n solve()\n\n}\n"}], "src_uid": "cb4dbff31d967c3dab8fe0495eb871dc"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 998244353\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n\n // [l, r]\n class Seg {\n var l: Int = -1\n var r: Int = -1\n }\n\n object Seg {\n def apply(l: Int, r: Int) = {\n val s = new Seg\n s.l = l\n s.r = r\n s\n }\n }\n\n // Aの初期セグメント\n val S = mutable.Map[Int, Seg]()\n REP(N) { i =>\n if (!S.contains(A(i))) S(A(i)) = Seg(i, i)\n else {\n val s = S(A(i))\n if (i < s.l) s.l = i\n else if (i > s.r) s.r = i\n }\n }\n\n val uf = new UnionFind(N)\n\n // unionfindのsetごとのセグメント\n val dynamicS = mutable.Map[Int, Seg]()\n REP(N) { i =>\n dynamicS(uf.find(i)) = Seg(i, i)\n }\n\n def uniteAll(ll: Int, r: Int): Unit = {\n var l = ll\n while(r > l) {\n uf.unite(l, l + 1)\n l += 1\n }\n }\n\n S.values.foreach { s =>\n // まだ同じセグメントになっていないなら2つのセグメントの間を全部融合する\n if (uf.find(s.l) != uf.find(s.r)) {\n val s1 = dynamicS(uf.find(s.l))\n val s2 = dynamicS(uf.find(s.r))\n // この2つのセグメントは必ず共通部分がない\n if (s1.l < s2.l) {\n uniteAll(s1.r, s2.l)\n } else {\n uniteAll(s2.r, s1.l)\n }\n\n dynamicS(uf.find(s.l)) = Seg(min(s1.l, s2.l), max(s1.r, s2.r))\n }\n }\n\n\n var ans = 1L\n val frees = countDisjointSets(uf) - 1 // b0が固定なので-1\n REP(frees) { _ =>\n ans = ans * 2 % MOD\n }\n\n out.println(ans)\n }\n\n class UnionFind(val n: Int) {\n private val par = Array.ofDim[Int](n)\n par.indices foreach (i => par(i) = i)\n private val rank = Array.ofDim[Int](n)\n\n def find(x: Int): Int = {\n val stack = ListBuffer[Int]()\n def step(x: Int): Int = {\n if (par(x) == x) x\n else {\n stack += x\n step(par(x))\n }\n }\n\n val res = step(x)\n stack foreach (i => par(i) = res)\n res\n }\n\n def unite(x: Int, y: Int): Unit = {\n val x1 = find(x)\n val y1 = find(y)\n if (x1 != y1) {\n if (rank(x1) < rank(y)) {\n par(x1) = y1\n } else {\n par(y1) = x1\n if (rank(x1) == rank(y1)) rank(x1) += 1\n }\n }\n }\n }\n\n def countDisjointSets(uf: UnionFind): Int = {\n var cnt = 0\n REP(uf.n) { i =>\n if (uf.find(i) == i) cnt += 1\n }\n cnt\n }\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object Main {\n import java.util.Scanner\n import java.io.PrintWriter\n import scala.collection.mutable.Map\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def main(args: Array[String]) {\n val MOD = 998244353\n def pwr2(e: Long): Long = {\n if (e == 0) 1\n else {\n val t: Long = pwr2(e / 2)\n if (e % 2 == 0) t * t % MOD\n else t * t * 2 % MOD\n }\n }\n\n val n = in.nextInt\n val a = (for (i <- 0 until n) yield in.nextInt).toArray\n val last = Map[Int, Int]()\n for (i <- 0 until n)\n last(a(i)) = i\n var r = -1\n var cnt = 0\n for (i <- 0 until n) {\n cnt = if (i > r) cnt + 1 else cnt\n r = if (last(a(i)) > r) last(a(i)) else r\n }\n println(pwr2(cnt - 1))\n }\n}"}], "negative_code": [], "src_uid": "0dab2f4e70064f90fc079d8dd7a8b049"} {"source_code": "object CF297B extends App{\n import scala.io.StdIn\n\n val input = StdIn.readLine().toCharArray\n val inputLength = input.length\n val n: Int = StdIn.readInt()\n val sortedArray = StdIn\n .readLine()\n .split(\"\\\\s+\")\n .map(x => x.toInt-1)\n .groupBy(x => x)\n .filter(valAndArray => valAndArray._2.length % 2 == 1)\n .keys\n .toArray\n .sorted\n \n for((valueFrom,index) <- sortedArray.view.zipWithIndex){\n if(index % 2 == 0){\n \n val valueUntil = if(sortedArray.length-1 == index) inputLength/2 else sortedArray(index + 1) \n \n for(indexToChange <- valueFrom until valueUntil){\n val tmpValue = input(indexToChange)\n\n val oppositeIndexToChange = inputLength - indexToChange - 1 \n\n input(indexToChange) = input(oppositeIndexToChange)\n\n input(oppositeIndexToChange) = tmpValue \n }\n } \n }\n \n print (new String(input))\n \n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject CF297B extends App{\n import scala.io.StdIn\n import scala.collection.mutable\n\n val input = StdIn.readLine().toCharArray\n val inputLength = input.length\n val n: Int = StdIn.readInt()\n val inputArray = StdIn.readLine().split(\"\\\\s+\").map(x => x.toInt-1).sorted.toList :+ inputLength / 2\n\n// val hashMap = new mutable.HashMap[Int, Int]()\n//\n// inputArray.foreach(x => {\n// val value = hashMap.get(x)\n// var cnt = 1\n// if(value.isEmpty){\n// hashMap.put(x, 1)\n// } else {\n// hashMap.put(x, value.get + 1)\n// }\n// })\n//\n// val sorted = hashMap.filter(keyValue => keyValue._2 % 2 == 1).keys.toList.sorted :+ inputLength / 2\n \n val sorted = mutable.MutableList[Int]()\n var prev = inputArray.head\n var cnt = 0 \n inputArray.foreach(value => {\n if (prev != value){\n if(cnt % 2 == 1){\n sorted += prev\n }\n cnt = 1\n prev = value\n } else {\n cnt = cnt + 1\n }\n })\n if(cnt % 2 == 1)sorted += prev\n \n val arr = sorted.toArray\n \n for((value1,index) <- arr.view.zipWithIndex){\n if(index % 2 == 0 && index < arr.length-1){\n for(indexToChange <- value1 until arr(index+1)){\n val tmpValue = input(indexToChange)\n val oppositeIndexToChange = inputLength - indexToChange - 1 \n input(indexToChange) = input(oppositeIndexToChange)\n input(oppositeIndexToChange) = tmpValue \n }\n } \n }\n \n print (new String(input))\n \n}\n"}, {"source_code": "object CF297B extends App{\n import scala.io.StdIn\n import scala.collection.mutable\n\n val input = StdIn.readLine().toCharArray\n val inputLength = input.length\n val n: Int = StdIn.readInt()\n val inputArray = StdIn.readLine().split(\"\\\\s+\").map(x => x.toInt-1)\n\n val hashMap = new mutable.HashMap[Int, Int]()\n hashMap.put(inputLength / 2, 1)\n\n inputArray.foreach(x => {\n val value = hashMap.get(x)\n var cnt = 1\n if(value.isEmpty){\n hashMap.put(x, 1)\n } else {\n hashMap.put(x, value.get + 1)\n }\n })\n \n val arr = hashMap.filter(keyValue => keyValue._2 % 2 == 1).keys.toArray.sorted\n\n for((value1,index) <- arr.view.zipWithIndex){\n if(index % 2 == 0 && index < arr.length-1){\n for(indexToChange <- value1 until arr(index+1)){\n val tmpValue = input(indexToChange)\n val oppositeIndexToChange = inputLength - indexToChange - 1 \n input(indexToChange) = input(oppositeIndexToChange)\n input(oppositeIndexToChange) = tmpValue \n }\n } \n }\n \n print (new String(input))\n \n}\n"}, {"source_code": "\nimport java.io._\nimport java.util\nimport java.util.StringTokenizer\nimport java.util.TreeMap\n\nimport scala.StringBuilder\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val s = next.toCharArray\n val m = nextInt\n val length: Int = s.length\n val cnt = new Array[Int](length)\n val bitSet = new util.BitSet()\n val bits = new Array[Boolean](length)\n for (i <- 0 until length) {\n bits(i) = true\n }\n for (i <- 0 until m) {\n val x = nextInt - 1\n bits(x) = !bits(x)\n bits(length - x - 1) = !bits(length - x - 1)\n }\n var curr = 0\n val sb = new StringBuilder()\n for (i <- 0 until length / 2) {\n if (!bits(i)) {\n curr += 1\n }\n if (curr % 2 == 0) {\n out.print(s(i))\n sb.append(s(length - i - 1))\n } else {\n out.print(s(length - i - 1))\n sb.append((s(i)))\n }\n }\n if (length % 2 == 1) {\n out.print(s(length / 2))\n }\n out.println(sb.reverse.toString())\n return 0\n }\n}\n"}, {"source_code": "import java.lang.Math.pow\n\nimport scala.io.StdIn\n\n/**\n * Created by pol on 29/03/15.\n */\nobject CR297_B extends App {\n var input = StdIn.readLine().toCharArray\n var m = StdIn.readInt()\n var ai = new Array[Int](pow(10d, 5d).toInt);\n for (i <- StdIn.readLine().trim().split(\" \")) {\n ai(i.toInt-1) += 1\n }\n\n for (i <- 0 until input.length / 2) {\n if (i != 0) {\n ai(i) += ai(i - 1)\n }\n if (ai(i) % 2 == 1) {\n val left: Char = input(i)\n val right: Char = input(input.length - i - 1)\n input(i) = right\n input(input.length - i - 1) = left\n }\n }\n\n println(String.copyValueOf(input))\n}\n"}, {"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val S=nextString.toCharArray\n val n=nextInt\n val a=Array.fill(n)(0)\n for(i<-0 until n){a(i)=nextInt-1}\n scala.util.Sorting.quickSort(a)\n var p=0\n var count=0\n for(i<-0 until S.length/2){\n\n while(p c.toInt)\n\n var revStatArr = Array.fill(strLen / 2)(0)\n for (op <- opArr if 2 * op <= strLen) {\n revStatArr(op - 1) += 1\n }\n\n var currRev = 0\n var sbF = new StringBuilder(strLen / 2)\n var sbB = new StringBuilder(strLen / 2)\n def isEven(n: Int) = n % 2 == 0\n\n for (i <- 0 until strLen / 2) {\n currRev += revStatArr(i)\n\n sbF append (if (isEven(currRev)) str(i) else revStr(i))\n sbB append (if (!isEven(currRev)) str(i) else revStr(i))\n }\n\n val resStr = sbF append (if (isEven(strLen)) \"\" else str(strLen / 2)) append sbB.reverse\n println(resStr)\n }\n\n solve\n}"}, {"source_code": "object CodeForces extends App {\n\n def solve = {\n val str = readLine\n val strLen = str.length\n val num = readLine toInt\n val opArr = readLine().split(' ').map(c => c.toInt)\n var revStatArr = Array.fill(strLen / 2)(0)\n\n for (op <- opArr if 2 * op <= strLen) {\n revStatArr(op - 1) += 1\n }\n\n var currRev = 0\n var sb = new StringBuilder(strLen)\n for (i <- 0 until strLen) sb += str(strLen / 2)\n def isEven(n: Int) = n % 2 == 0\n def oospar(i: Int) = strLen - i - 1\n\n for (i <- 0 until strLen / 2) {\n currRev += revStatArr(i)\n\n sb(i) = if (isEven(currRev)) str(i) else str(oospar(i))\n sb(oospar(i)) = if (!isEven(currRev)) str(i) else str(oospar(i))\n }\n\n val resStr = sb.toString()\n println(resStr)\n }\n\n solve\n}"}, {"source_code": "object CodeForces extends App {\n val str = readLine\n val revStr = str.reverse\n val strLen = str.length\n val num = readLine toInt\n val opArr = readLine().split(' ').map(c => c.toInt)\n\n val revStatArr = Array.fill(strLen / 2)(0)\n for (op <- opArr if 2 * op <= strLen) {\n revStatArr(op - 1) += 1\n }\n\n var currRev = 0\n val sbF = new StringBuilder(strLen / 2)\n val sbB = new StringBuilder(strLen / 2)\n \n def isEven(n: Int) = n % 2 == 0\n\n for (i <- 0 until strLen / 2) {\n currRev += revStatArr(i)\n sbF append (if (isEven(currRev)) str(i) else revStr(i))\n sbB append (if (!isEven(currRev)) str(i) else revStr(i))\n }\n \n println(sbF append (if (isEven(strLen)) \"\" else str(strLen / 2)) append sbB.reverse)\n}"}], "negative_code": [{"source_code": "object CF297B extends App{\n import scala.io.StdIn\n\n val input = StdIn.readLine().toCharArray\n val inputLength = input.length\n val n: Int = StdIn.readInt()\n val sortedArray = StdIn\n .readLine()\n .split(\"\\\\s+\")\n .map(x => x.toInt-1)\n .groupBy(x => x)\n .filter(valAndArray => valAndArray._2.length % 2 == 1)\n .keys\n .toArray\n .sorted\n \n println(\"sortedArray\" + sortedArray.map(x => x + 1).toList)\n\n for((valueFrom,index) <- sortedArray.view.zipWithIndex){\n if(index % 2 == 0){\n \n val valueUntil = if(sortedArray.length-1 == index) inputLength/2 else sortedArray(index + 1) \n \n for(indexToChange <- valueFrom until valueUntil){\n val tmpValue = input(indexToChange)\n\n val oppositeIndexToChange = inputLength - indexToChange - 1 \n\n input(indexToChange) = input(oppositeIndexToChange)\n\n input(oppositeIndexToChange) = tmpValue \n }\n } \n }\n \n print (new String(input))\n \n}\n"}, {"source_code": "object CF297B extends App{\n import scala.io.StdIn\n\n val input = StdIn.readLine().toCharArray\n val inputLength = input.length\n val n: Int = StdIn.readInt()\n val sortedArray = StdIn\n .readLine()\n .split(\"\\\\s+\")\n .map(x => x.toInt-1)\n .groupBy(x => x)\n .filter(valAndArray => valAndArray._2.length % 2 == 1)\n .keys\n .toArray\n .sorted\n\n for((valueFrom,index) <- sortedArray.view.zipWithIndex){\n if(index % 2 == 0){\n \n val valueUntil = if(sortedArray.length-1 == index) inputLength/2 else index + 1 \n \n for(indexToChange <- valueFrom until valueUntil){\n val tmpValue = input(indexToChange)\n\n val oppositeIndexToChange = inputLength - indexToChange - 1 \n\n input(indexToChange) = input(oppositeIndexToChange)\n\n input(oppositeIndexToChange) = tmpValue \n }\n } \n }\n \n print (new String(input))\n \n}\n"}], "src_uid": "9d46ae53e6dc8dc54f732ec93a82ded3"} {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject ProbA {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n \n /*def primeFactorsWithout23(a: Int) : Map[Int,Int] = {\n def go(a: Int, factors : Map[Int,Int],p: Int) : Map[Int,Int] = {\n //println(s\"testing $a : factors\" + factors)\n if (a == 1) factors \n else if (a%p == 0) \n go(a/p, factors + (p -> (factors.getOrElse(p, 0) + 1)) ,p)\n else go(a,factors,p+2)\n }\n var x = a\n while (x%2 == 0) x = x/2\n while (x%3 == 0) x = x/3\n go(x,Map(),5)\n }*/\n \n def remove2(a: Int) : Int = {\n if (a%2 != 0) a else remove2(a/2)\n }\n def remove3(a: Int) : Int = {\n if (a%3 != 0) a else remove3(a/3)\n }\n \n \n def main(args: Array[String]) {\n val n = readInt\n val bids = readInts\n // val primeFactors = primeFactorsWithout23(bids(0))\n val reduced = remove2(remove3(bids(0))) \n if (bids.forall{ a => remove2(remove3(a)) == reduced})\n println(\"YES\")\n else \n println(\"NO\")\n \n }\n \n}", "positive_code": [{"source_code": "//package round318.c\n\nimport java.util.Scanner\n\n\nobject Main extends App {\n\n def possible(a: Long, b: Long): Option[Long] = {\n\n import Math._\n var aa = a\n var k1 = 0\n var m1 = 0\n while(aa % 2 == 0) { aa /= 2; k1 += 1 }\n while(aa % 3 == 0) { aa /= 3; m1 += 1 }\n\n var bb = b\n var k2 = 0\n var m2 = 0\n while(bb % 2 == 0) { bb /= 2; k2 += 1 }\n while(bb % 3 == 0) { bb /= 3; m2 += 1 }\n\n if(aa != bb) None\n else Some((pow(2, max(k1,k2)) * pow(3, max(m1,m2))).toLong * aa)\n }\n\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n var ok = true\n\n var bid = sc.nextLong\n\n (1 until n) foreach { _ =>\n val bid2 = sc.nextLong\n possible(bid, bid2) match {\n case None =>\n ok = false\n case Some(bid3) =>\n bid = bid3\n }\n }\n\n println(if (ok) \"Yes\" else \"No\")\n\n}\n"}, {"source_code": "object Codeforces extends App {\n val in = new java.util.Scanner(System.in)\n var n = in.nextInt()\n var a = Array.ofDim[Int](n);\n for (i <- 0 until n) {\n a(i) = in.nextInt()\n while (a(i) % 2 == 0) a(i) /= 2\n while (a(i) % 3 == 0) a(i) /= 3\n }\n var ok = true\n for (i <- 1 until n)\n if (a(i) != a(0))\n ok = false \n println(if (ok) \"Yes\" else \"No\") \n}"}, {"source_code": "object Solution extends App {\n\n def min(a: Int): Int = {\n if (a % 2 == 0) min(a / 2)\n else if (a % 3 == 0) min(a / 3)\n else a\n }\n\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt).map(min)\n if (data.distinct.length == 1)\n println(\"Yes\")\n else\n println(\"No\")\n}\n"}, {"source_code": "object A573 {\n\n import IO._\n\n def gcd(a: Int, b: Int): Int = {\n if(b == 0) a else gcd(b, a%b)\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n)\n val g = in.foldLeft(in(0)){case (res, i) => gcd(res, i)}\n var break = false\n for(i <- 0 until n if !break) {\n var num = in(i)/g\n while(num%2 == 0) num /= 2\n while(num%3 == 0) num /= 3\n if(num != 1) {\n println(\"No\")\n break = true\n }\n }\n if(!break) println(\"Yes\")\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n \n val d = as.reduce(gcd)\n val ds = as.map(_ / d)\n \n var ok = true\n for (x <- ds) {\n var xx = x\n while ((xx & 1) == 0) xx >>= 1\n while (xx % 3 == 0) xx /= 3\n if (xx > 1) ok = false\n }\n\n println(if (ok) \"Yes\" else \"No\")\n}\n"}], "negative_code": [], "src_uid": "2bb893703cbffe9aeaa0bed02f42a05c"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n var data = in.next().split(\" \").map(_.toLong)\n val answer = Array.ofDim[Long](n)\n answer(0) = Math.min(data.head, 1)\n Range(1, n).foreach(i => answer(i) = Math.min(data(i), answer(i - 1) + 1))\n answer(n - 1) = Math.min(data.last, 1)\n Range(n - 2, 0, -1).foreach(i => answer(i) = Math.min(answer(i), answer(i + 1) + 1))\n\n println(answer.max)\n}", "positive_code": [{"source_code": "object Codeforces extends App {\n val in = new java.util.Scanner(System.in)\n var n = in.nextInt()\n var a = Array.ofDim[Int](n + 2)\n for (i <- 1 to n)\n a(i) = in.nextInt()\n a(0) = 0\n a(n + 1) = 0\n for (i <- 1 to n)\n a(i) = Math.min(a(i), a(i - 1) + 1)\n for (i <- n to 1 by -1)\n a(i) = Math.min(a(i), a(i + 1) + 1)\n var res = 0\n for (i <- 1 to n)\n res = Math.max(res, a(i))\n println(res)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val hs = readInts(n)\n \n val res = Array.ofDim[Int](n)\n \n var h = 0\n for (i <- hs.indices) {\n h = (h + 1) min hs(i)\n res(i) = h\n }\n\n h = 0\n for (i <- hs.indices.reverse) {\n h = (h + 1) min hs(i)\n res(i) = h min res(i)\n }\n\n println(res.max)\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n var data: IndexedSeq[Long] = in.next().split(\" \").map(_.toLong).toIndexedSeq\n var sum = data.sum\n var j = 0\n if (data.min > (data.length + 1) / 2)\n println((data.length + 1) / 2)\n else\n while (sum > 0) {\n j += 1\n data = data.indices.map { i =>\n val ir =\n if (i > 0 && i < data.length - 1)\n Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))\n else\n 0\n sum += ir - data(i)\n ir\n }\n data = data.dropWhile(_ == 0).dropRight(1)\n }\n println(j)\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n var data: Array[Int] = in.next().split(\" \").map(_.toInt)\n val data1: Array[Int] = data.clone()\n var left = 0\n var right = n - 1\n var sum = data.sum\n while (data(left) == 0 && left <= right)\n left += 1\n while (data(right) == 0 && right >= left)\n right -= 1\n var i = 0\n// println (sum)\n while (sum > 0) {\n i += 1\n sum -= data(left)\n sum -= data(right)\n data1(left) = 0\n data1(right) = 0\n Range(left + 1, right).foreach { i =>\n val ir = Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))\n sum += ir - data(i)\n data(i) = ir\n }\n data = data1.clone()\n// println(sum)\n// println(data.mkString(\" \"))\n while (data(left) == 0 && left <= right)\n left += 1\n while (data(right) == 0 && right >= left)\n right -= 1\n }\n println(i + 1)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n var data: Array[Int] = in.next().split(\" \").map(_.toInt)\n val data1: Array[Int] = data.clone()\n var sum = data.sum\n// println (sum)\n var j = 0\n while (sum > 0) {\n j += 1\n data.indices.foreach { i =>\n val ir =\n if (i > 0 && i < data.length - 1)\n Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))\n else\n 0\n sum += ir - data(i)\n data1(i) = ir\n }\n data = data1.clone()\n }\n println(j)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n var data: Array[Int] = in.next().split(\" \").map(_.toInt)\n val data1: Array[Int] = data.clone()\n var left = 0\n var right = n - 1\n var sum = data.sum\n while (data(left) == 0 && left < right)\n left += 1\n while (data(right) == 0 && right > left)\n right -= 1\n var i = 0\n// println (sum)\n while (sum > 0) {\n i += 1\n sum -= data(left)\n sum -= data(right)\n data1(left) = 0\n data1(right) = 0\n Range(left + 1, right).foreach { i =>\n val ir = Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))\n sum += ir - data(i)\n data1(i) = ir\n }\n data = data1.clone()\n while (data(left) == 0 && left < right)\n left += 1\n while (data(right) == 0 && right > left)\n right -= 1\n }\n println(i)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n var data: Array[Long] = in.next().split(\" \").map(_.toLong)\n val data1: Array[Long] = data.clone()\n var sum = data.sum\n// println (sum)\n var j = 0\n while (sum > 0) {\n j += 1\n data.indices.foreach { i =>\n val ir =\n if (i > 0 && i < data.length - 1)\n Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))\n else\n 0\n sum -= ir + data(i)\n data1(i) = ir\n }\n data = data1.clone()\n }\n println(j)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n var data: Array[Int] = in.next().split(\" \").map(_.toInt)\n val data1: Array[Int] = data.clone()\n var left = 0\n var right = n - 1\n var sum = data.sum\n while (data(left) == 0 && left <= right)\n left += 1\n while (data(right) == 0 && right >= left)\n right -= 1\n var i = 0\n// println (sum)\n while (sum > 0) {\n i += 1\n sum -= data(left)\n sum -= data(right)\n data1(left) = 0\n data1(right) = 0\n Range(left + 1, right).foreach { i =>\n val ir = Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))\n sum += ir - data(i)\n data1(i) = ir\n }\n data = data1.clone()\n while (data(left) == 0 && left <= right)\n left += 1\n while (data(right) == 0 && right >= left)\n right -= 1\n }\n println(i)\n}\n"}], "src_uid": "a548737890b4bf322d0f8989e5cd25ac"} {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n case class P(x: Int, y: Int)\n\n val obs = Array.fill(n) {\n val Array(x, y) = readInts(2)\n P(x, y)\n }\n\n val clues = Array.fill(n) {\n val Array(x, y) = readInts(2)\n P(x, y)\n }\n\n val oMinX = obs.map(_.x).min\n val oMinY = obs.map(_.y).min\n val cMaxX = clues.map(_.x).max\n val cMaxY = clues.map(_.y).max\n\n val tx = oMinX + cMaxX\n val ty = oMinY + cMaxY\n\n println(s\"$tx $ty\")\n}\n", "positive_code": [{"source_code": "//package codeforces.contest1091\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject NewYearAndTheTreasureGeolocation {\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n\n def readInt(): Int = {\n val st = new StringTokenizer(br.readLine())\n st.nextToken().toInt\n }\n\n def readLongPair(): (Long, Long) = {\n val st = new StringTokenizer(br.readLine())\n (st.nextToken.toLong, st.nextToken.toLong)\n }\n\n def addIntPairs(p1: (Long, Long), p2: (Long, Long)): (Long, Long) = (p1._1 + p2._1, p1._2 + p2._2)\n\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val sum = (0 until 2 * n).foldLeft((0l, 0l))((acc, _) => addIntPairs(acc, readLongPair()))\n println(sum._1 / n + \" \" + sum._2 / n)\n }\n\n}\n"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n case class P(x: Int, y: Int)\n\n val obs = Array.fill(n) {\n val Array(x, y) = readInts(2)\n P(x, y)\n }\n\n val clues = Array.fill(n) {\n val Array(x, y) = readInts(2)\n P(x, y)\n }\n\n val cSet = clues.toSet\n\n for (c1 <- clues) {\n val tx = obs(0).x + c1.x\n val ty = obs(0).y + c1.y\n var i = 1\n while (i < n && cSet.contains(P(tx - obs(i).x, ty - obs(i).y))) {\n i += 1\n }\n if (i == n) {\n println(s\"$tx $ty\")\n System.exit(0)\n }\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contest1091\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject NewYearAndTheTreasureGeolocation {\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n\n def readInt(): Int = {\n val st = new StringTokenizer(br.readLine())\n st.nextToken().toInt\n }\n\n def readIntPair(): (Int, Int) = {\n val st = new StringTokenizer(br.readLine())\n (st.nextToken.toInt, st.nextToken.toInt)\n }\n\n def addIntPairs(p1: (Int, Int), p2: (Int, Int)): (Int, Int) = (p1._1 + p2._1, p1._2 + p2._2)\n\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val sum = (0 until 2 * n).foldLeft((0, 0))((acc, _) => addIntPairs(acc, readIntPair()))\n println(sum._1 / n + \" \" + sum._2 / n)\n }\n\n}\n"}], "src_uid": "ba526a7f29cf7f83afa0b71bcd06e86b"} {"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 15.08.14.\n */\nobject C extends App {\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n val k = nextInt\n val d = nextInt\n val ans = Array.fill(d, n)(1)\n def can(n: Int, k: Int, d: Int): Boolean = {\n if(k >= n) {\n true\n } else if(d == 1) {\n false\n } else {\n can((n.toDouble / k.toDouble).ceil.toInt, k, d - 1)\n }\n }\n if(!can(n, k, d)) {\n out.println(-1)\n } else {\n def fillAns(from: Int, to: Int, k: Int, d: Int): Unit = {\n //out.println(from, to, k, d)\n if(k >= to - from + 1) {\n for(i <- from to to) {\n ans(d - 1)(i) = i + 1 - from\n }\n } else {\n val g = ((to - from + 1).toDouble / k.toDouble).ceil.toInt\n for(i <- from to to) {\n ans(d - 1)(i) = (i - from) / g + 1\n }\n for(i <- from to to by g) {\n fillAns(i, math.min(i + g - 1, to), k, d - 1)\n }\n }\n }\n fillAns(0, n - 1, k, d)\n (0 until d).foreach{day =>\n out.println(ans(day).mkString(\" \"))\n }\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n}", "positive_code": [{"source_code": "object Main {\n \n def generate(n: Int, d: Int, m: Int): List[List[Int]] = {\n \n def iterPos(pos: Int, cur: List[Int], result: List[List[Int]]): List[List[Int]] = {\n \n def iterValue(value: Int, result: List[List[Int]]): List[List[Int]] = {\n if (result.length >= n || value > m) {\n return result\n } else {\n return iterValue(value + 1,\n iterPos(pos + 1, cur.+:(value), result))\n }\n }\n \n if (pos > d) {\n return result.+:(cur)\n } else {\n return iterValue(1, result)\n }\n \n }\n \n return iterPos(1, List[Int](), List[List[Int]]())\n \n }\n \n def transpose(mat: List[List[Int]]): List[List[Int]] = {\n def iter(rem: List[List[Int]], result: List[List[Int]]): List[List[Int]] = {\n if (rem(0).isEmpty) {\n return result\n } else {\n return iter(rem.map(_.tail), result.+:(rem.map(_.head)))\n }\n }\n return iter(mat, List[List[Int]]())\n }\n \n def main(args: Array[String]) {\n val input = readLine().trim().split(\" \").toList.map(_.toInt)\n val result = generate(input(0), input(2), input(1))\n if (result.length == input(0)) {\n transpose(result).foreach(entry => println(entry.mkString(\" \")))\n } else {\n println(-1)\n }\n }\n \n}\n"}, {"source_code": "import java.math.BigInteger\n\n/**\n * Created by lurker on 2014. 8. 15..\n */\nobject CF261_3 extends App {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n val Array(n, k, d) = readInts(3)\n\n def nToBaseKWithDLen(n:Int):Array[Int] = {\n val res = Array.fill(d)(0)\n var curn = n\n var i = 0\n while(i < d) {\n res(i) = curn % k + 1\n curn = curn / k\n i = i + 1\n }\n res\n }\n\n val kbig = new BigInteger(k.toString)\n val dbig = new BigInteger(d.toString)\n val nbig = new BigInteger(n.toString)\n\n if(kbig.pow(d.toInt).compareTo(nbig) < 0){\n println(-1)\n } else {\n val solutions = (1 to n).map(nToBaseKWithDLen(_))\n for(day <- (1 to d)){\n println(solutions.map(_(day - 1)).mkString(\" \"))\n }\n }\n}\n"}, {"source_code": "object Main {\n \n def generate(n: Int, d: Int, m: Int): List[List[Int]] = {\n \n def iterPos(pos: Int, cur: List[Int], result: List[List[Int]]): List[List[Int]] = {\n \n def iterValue(value: Int, result: List[List[Int]]): List[List[Int]] = {\n if (result.length >= n || value > m) {\n return result\n } else {\n return iterValue(value + 1,\n iterPos(pos + 1, cur.+:(value), result))\n }\n }\n \n if (pos > d) {\n return result.+:(cur)\n } else {\n return iterValue(1, result)\n }\n \n }\n \n return iterPos(1, List[Int](), List[List[Int]]())\n \n }\n \n def transpose(mat: List[List[Int]]): List[List[Int]] = {\n def iter(rem: List[List[Int]], result: List[List[Int]]): List[List[Int]] = {\n if (rem(0).isEmpty) {\n return result\n } else {\n return iter(rem.map(_.tail), result.+:(rem.map(_.head)))\n }\n }\n return iter(mat, List[List[Int]]())\n }\n \n def main(args: Array[String]) {\n val input = readLine().trim().split(\" \").toList.map(_.toInt)\n val result = generate(input(0), input(2), input(1))\n if (result.length >= input(0)) {\n transpose(result.take(input(0))).foreach(entry => println(entry.mkString(\" \")))\n } else {\n println(-1)\n }\n }\n \n}\n"}], "negative_code": [{"source_code": "\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 15.08.14.\n */\nobject C extends App {\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n val k = nextInt\n val d = nextInt\n val ans = Array.fill(d, n)(1)\n def can(n: Int, k: Int, d: Int): Boolean = {\n if(k >= n) {\n true\n } else if(d == 1) {\n false\n } else {\n can((n.toDouble / k.toDouble).ceil.toInt, k, d - 1)\n }\n }\n if(!can(n, k, d)) {\n out.println(-1)\n } else {\n def getAns(from: Int, to: Int, k: Int, d: Int): Unit = {\n if(k >= to - from + 1) {\n for(i <- from to to) {\n ans(d - 1)(i) = i + 1 - from\n }\n } else {\n val g = ((to - from + 1).toDouble / k.toDouble).ceil.toInt\n for(i <- from to to) {\n ans(d - 1)(i) = i / g + 1\n }\n for(i <- from to to by(k)) {\n getAns(i, math.min(i + k - 1, to), k, d - 1)\n }\n }\n }\n getAns(0, n - 1, k, d)\n (0 until d).foreach{day =>\n out.println(ans(day).mkString(\" \"))\n }\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n}"}, {"source_code": "object Main {\n \n def generate(n: Int, d: Int, m: Int): List[List[Int]] = {\n \n def iterPos(pos: Int, cur: List[Int], result: List[List[Int]]): List[List[Int]] = {\n \n def iterValue(value: Int, result: List[List[Int]]): List[List[Int]] = {\n if (result.length >= n || value > m) {\n return result\n } else {\n return iterValue(value + 1,\n iterPos(pos + 1, cur.+:(value), result))\n }\n }\n \n if (pos > d) {\n return result.+:(cur)\n } else {\n return iterValue(1, result)\n }\n \n }\n \n return iterPos(1, List[Int](), List[List[Int]]())\n \n }\n \n def transpose(mat: List[List[Int]]): List[List[Int]] = {\n def iter(rem: List[List[Int]], result: List[List[Int]]): List[List[Int]] = {\n if (rem(0).isEmpty) {\n return result\n } else {\n return iter(rem.map(_.tail), result.+:(rem.map(_.head)))\n }\n }\n return iter(mat, List[List[Int]]())\n }\n \n def main(args: Array[String]) {\n val input = readLine().trim().split(\" \").toList.map(_.toInt)\n val result = generate(input(0), input(1), input(2))\n if (result.length >= input(0)) {\n transpose(result.take(input(0))).foreach(entry => println(entry.mkString(\" \")))\n } else {\n println(-1)\n }\n }\n \n}\n"}], "src_uid": "4dddcf0ded11672a4958fb0d391dbaf5"} {"source_code": "import java.util.Scanner\n\nobject Main {\n\t\n\tdef main(args: Array[String]): Unit = {\n\t\tsolve()\n\t}\n\t\n\tdef solve(): Unit = {\n\t\tval inp = new Scanner(System.in)\n\t\tval n = inp.nextInt()\n\t\tvar cnt = 1\n\t\tinp.nextLine()\n\t\t(1 to n).foreach(_=>{\n\t\t\tval arr = new Array[Int](26)\n\t\t\t\n\t\t\tval s = inp.nextLine()\n\t\t\tfor(i<- 1 until s.length){\n\t\t\t\tif(s.charAt(i)==s.charAt(i-1)){\n\t\t\t\t\tcnt+=1\n\t\t\t\t}else{\n\t\t\t\t\tif((cnt & 1) == 1){\n\t\t\t\t\t\tval c: Int = s.charAt(i-1) - 'a'\n\t\t\t\t\t\tarr(c) = 1\n\t\t\t\t\t}\n\t\t\t\t\tcnt = 1\n\t\t\t\t}\n\t\t\t}\n\t\t\tif((cnt & 1) == 1){\n\t\t\t\tval c: Int = s.charAt(s.length-1) - 'a'\n\t\t\t\tarr(c) = 1\n\t\t\t}\n\t\t\tcnt=1\n\t\t\t\n\t\t\t('a' to 'z').foreach(v=>{\n\t\t\t\tif(arr((v-'a')) == 1) print(v)\n\t\t\t})\n\t\t\tprintln()\n\t\t\t\n\t\t})\n\t\t\n\t\t\n\t}\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject Main extends App {\n\n val n = readLine().toInt\n\n val alph = \"qwertyuiopasdfghjklzxcvbnm\"\n\n for(i <- 0 to n-1) {\n var st = readLine()\n for (i <- alph) {\n val pattern = i.toString + i.toString\n st = st.replaceAll(pattern, \"-\")\n }\n st = st.replaceAll(\"-\", \"\")\n var set: mutable.TreeSet[String] = mutable.TreeSet()\n for (i <- st) {\n set += i.toString\n }\n val res = set.mkString\n println(res)\n }\n\n\n}"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val s = ns()\n val ok = Array.ofDim[Boolean](26)\n var cnt = 0\n REP(s.length) { i =>\n if (i == 0 || s(i) == s(i - 1)) cnt += 1\n else {\n ok(s(i-1)-'a') |= cnt % 2 == 1\n cnt = 1\n }\n }\n ok(s.last-'a') |= cnt % 2 == 1\n REP(26) { i =>\n if (ok(i)) out.print(('a'+i).toChar)\n }\n out.println()\n }\n }\n}"}, {"source_code": "object KeyBoard extends App {\n\n val array = readFromTerminal()\n for (row <- array)\n println(compute(row))\n\n def readFromTerminal() = {\n// val n = 1\n val n = readInt()\n// val t = List(\"aadffgfd\")\n val t: Seq[String] = for (i <- 1 to n) yield readLine()\n t\n }\n\n def compute(row: String): String = {\n var mutable: Array[Char] = row.toCharArray\n var i = 1\n while (i < mutable.length) {\n// println(s\"compare ${mutable(i - 1)} and ${mutable(i)}\")\n if (mutable(i - 1) == mutable(i)) {\n mutable(i - 1) = 0\n mutable(i) = 0\n }\n i = i + 1\n }\n mutable.toSet.toList.sortWith(_.compareTo(_) < 0).mkString.trim\n }\n}"}, {"source_code": "object A1251 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n def check(str: String, char: Char): Boolean = {\n if (str.contains(char)) {\n var i = 0\n while (i < str.length && i != -1) {\n i = str.indexWhere(_ == char, i)\n if (i != -1) {\n val count = str.drop(i).takeWhile(_ == char).length\n if (count % 2 == 1)\n return true\n i += count\n }\n }\n false\n } else false\n }\n\n def main(args: Array[String]): Unit = {\n var t = readInt\n while (t > 0) {\n val str = read\n for (ch <- 'a' to 'z') {\n if (check(str, ch))\n out.print(ch)\n }\n out.println()\n t -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object _1251A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(implicit io: IO): io.type = repeat {\n val s = io.read[String]\n val good = splitRepeating(s).collect({case t if t.length.isOdd => t.head})\n io.writeAll(good.distinct.sorted, separator = \"\").writeLine()\n }\n\n def splitRepeating(s: String): Seq[String] = s.split(\"(?<=(.))(?!\\\\1)\")\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(implicit io: IO): io.type\n def repeat(f: => Unit)(implicit io: IO): io.type = {Utils.repeat(io.read[Int])(f); io}\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def splitRepeating(s: String): Seq[String] = s.split(\"(?<=(.))(?!\\\\1)\")\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject Main extends App {\n\n val n = readLine().toInt\n\n val alph = \"qwertyuiopasdfghjklzxcvbnm\"\n\n for(i <- 0 to n-1) {\n var st = readLine()\n for (i <- alph) {\n val pattern = i.toString + i.toString\n st = st.replaceAll(pattern, \"\")\n }\n var set: mutable.TreeSet[String] = mutable.TreeSet()\n for (i <- st) {\n set += i.toString\n }\n val res = set.mkString\n println(res)\n }\n\n\n}"}, {"source_code": "object _1251A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n repeat(io.read[Int]) {\n val s = io.read[String]\n val good = splitRepeating(s).collect({case t if t.length%2 == 1 => t.head})\n io.writeAll(good.sorted, separator = \"\").writeLine()\n }\n io\n }\n\n def splitRepeating(s: String): Seq[String] = s.split(\"(?<=(.))(?!\\\\1)\")\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def splitRepeating(s: String): Seq[String] = s.split(\"(?<=(.))(?!\\\\1)\")\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _1251A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n repeat(io.read[Int]) {\n val s = io.read[String]\n val good = splitRepeating(s).collect({case t if t.size == 1 => t.head})\n io.writeAll(good.sorted, separator = \"\").writeLine()\n }\n io\n }\n\n def splitRepeating(s: String): Seq[String] = s.split(\"(?<=(.))(?!\\\\1)\")\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def splitRepeating(s: String): Seq[String] = s.split(\"(?<=(.))(?!\\\\1)\")\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "586a15030f4830c68f2ea1446e80028c"} {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(t) = readInts(1)\n\n for (_ <- 1 to t) {\n val Array(n) = readInts(1)\n val s = readLine\n val l = s.takeWhile(_ == '<').length\n val r = s.reverse.takeWhile(_ == '>').length\n println(l min r)\n }\n Console.flush\n}\n", "positive_code": [{"source_code": "import scala.math._, scala.io.StdIn._\n\nobject Foo extends App {\n val t = readInt\n\n for (i <- 0 until t) {\n val n = readInt\n val s = readLine\n\n println(min(s.prefixLength(_=='<'),\n s.reverse.prefixLength(_=='>')))\n }\n\n def readInts() = readLine.split(\" \").map(_.toInt)\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n import java.util.Arrays\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N = ni()\n val S = ns(N)\n\n var ans = 0\n val ix = S.lastIndexWhere(_ == '<')\n val ix2 = S.indexWhere(_ == '>')\n\n if (ix != -1 && ix2 != -1) {\n ans = min(N - 1 - ix, ix2)\n } else {\n ans = 0\n }\n\n out.println(ans)\n }\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}], "negative_code": [], "src_uid": "0ba97bcfb5f539c848f2cd097b34ff33"} {"source_code": "object Main {\n def main(args: Array[String]) = {\n val cin = new java.util.Scanner(System.in)\n val m = cin.nextInt()\n val n = cin.nextInt()\n var ans: Double = 0.0\n for (i <- 1 to m)\n ans += i * (Math.pow(i.toDouble / m, n) - Math.pow((i - 1.0) / m, n))\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 01.08.14.\n */\nobject C extends App {\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val m = nextDouble\n val n = nextDouble\n if (m == 1) {\n out.println(1)\n } else {\n var ans = m\n for (i <- 1 to (m - 1).toInt) {\n val p = i.toDouble / m\n val q = math.pow(p, n)\n ans = ans - q\n }\n out.println(\"%.6f\".format(ans))\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}\n"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(m, n) = readInts(2)\n \n val mn = math.pow(m.toDouble, n)\n var sum = 0d\n var prevCount = 0d\n for (i <- 1 to m) {\n val count = math.pow(i.toDouble / m.toDouble, n)\n //println(sum, count, i)\n sum += (count - prevCount) * i\n prevCount = count// - prevCount\n }\n\n println(sum)\n}"}, {"source_code": "import java.util._\nimport java.io._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val m = nextInt\n val n = nextInt\n var ans: Double = m.toDouble\n for (i <- 0 to m - 1) {\n ans -= Math.pow(i.toDouble / m.toDouble, n)\n }\n out.println(ans)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Main {\n \n def power(a: Double, n: Int): Double = {\n var ans = 1.0\n var b = a\n var p = n\n while (p > 0) {\n if ( (p & 0x01) != 0) ans = b * ans\n b = b * b\n p = p >> 1;\n }\n ans\n }\n def main(args: Array[String]): Unit = {\n val mn = readLine.split(\" \").map(_.toInt)\n val m = mn.head\n val n = mn.last\n val ans = (1 to m).map { k =>\n k * (power((k*1.0)/m, n) - power(((k*1.0) - 1.0)/m, n))\n }.sum\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val cin = new java.util.Scanner(System.in)\n val m = cin.nextInt()\n val n = cin.nextInt()\n def solve(i: Int, res: Double):Double =\n if (i == 0) res\n else solve(i - 1, res + i * (Math.pow((1.0 * i) / m, n) - Math.pow((i - 1.0) / m, n)))\n println(solve(m, 0))\n }\n}\n"}], "negative_code": [{"source_code": "import java.util._\nimport java.io._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val m = nextInt\n val n = nextInt\n var ans: Double = 0.0d\n val delimeter: Double = Math.pow(m, n)\n for (i <- 1 to m) {\n ans += Math.pow(i.toDouble, n + 1) - Math.pow(i - 1, n) * i.toDouble\n }\n out.println(ans / delimeter)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "src_uid": "f70ac2c4e0f62f9d6ad1e003aedd86b2"} {"source_code": "import scala.io.Source\nimport scala.collection.mutable\n\nobject Main extends App {\n // process input!\n val input = Source.stdin.getLines.map(_.split(\" \").map(_.toInt))\n type Node = Int\n type Weight = Int\n val graph = mutable.Map.empty[Node, mutable.Map[Node, Weight]]\n val (n :: numEdges :: Nil) = input.next.toList\n val edges = input.map(_.toList)\n\n // construct the graph!\n def makeEdge(from: Node, to: Node, weight: Weight) = {\n val source = graph.getOrElseUpdate(from, mutable.Map.empty[Node, Weight])\n source.get(to) match {\n case None => source.update(to, weight)\n case Some(prevWeight) => if(weight < prevWeight) source.update(to, weight)\n }\n }\n edges.foreach {\n case from :: to :: weight :: Nil => {\n makeEdge(from, to, weight)\n makeEdge(to, from, weight)\n }\n case _ => ()\n }\n\n // Prepare for Dijkstra! This represents a graph path!\n case class Path(val fullPath: List[Node], val cost: Weight) {\n def location = fullPath.head\n override def toString = fullPath.mkString(\" \")\n }\n\n // Sort by lowest cost! and then target, so paths with same weight don't clobber each other!\n implicit val pathOrdering: Ordering[Path] = Ordering.by(path => (path.cost, path.location))\n\n // For example, we begin at node 1 with a cost of 0!\n val end = Path(List(n), 0)\n\n // Here are the Dijkstra Data Doodads of Doom!\n val conquered = mutable.Set.empty[Node]\n val frontier = new java.util.PriorityQueue[Path](10, pathOrdering)\n frontier.offer(end)\n\n // Here is the algorithm! Yay! I AM NAPOLEON!!!!\n var warPath: Option[Path] = None\n while(warPath.isEmpty && !frontier.isEmpty) {\n val battlefield = frontier.poll\n val location = battlefield.location\n if(location == 1) {\n warPath = Some(battlefield)\n } else {\n conquered += location\n for {\n connections <- graph.get(location).toList\n (target, weight) <- connections\n if !conquered(target)\n } yield {\n frontier.add(Path(\n fullPath = target :: battlefield.fullPath,\n cost = battlefield.cost + weight))\n }\n }\n }\n\n // And our answer!!!!!!!!!!!\n warPath match {\n case None => println(\"-1\")\n case Some(path) => println(path)\n }\n}\n", "positive_code": [{"source_code": "import java.util\nimport java.util._\nimport java.io._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val g = new ArrayList[List[(Int, Long)]]\n for (i <- 0 until n) {\n g.add(new util.ArrayList[(Int, Long)]())\n }\n for (i <- 0 until m) {\n val a = nextInt - 1\n val b = nextInt - 1\n val len = nextLong\n g.get(a).add((b, len))\n g.get(b).add((a, len))\n }\n val graph = new Array[Array[(Int, Long)]](n)\n for (i <- 0 until n) {\n graph(i) = new Array[(Int, Long)](g.get(i).size)\n val len = graph(i).length\n for (j <- 0 until len) {\n graph(i)(j) = g.get(i).get(j)\n }\n }\n\n\n object Dijkstra {\n val path = new Array[Int](n)\n\n def findShortestPath(start: Int, end: Int): (Long, Array[Int]) = {\n val dist = new Array[Long](n)\n val relaxed = new Array[Boolean](n)\n Arrays.fill(dist, Long.MaxValue)\n dist(start) = 0\n val set = new util.PriorityQueue[Edge]()\n val path = new Array[Int](n)\n Arrays.fill(path, -1)\n set.add(new Edge(dist(start), start))\n while (!set.isEmpty) {\n val v = set.poll().to\n if (!relaxed(v)) {\n for (i <- 0 until graph(v).length) {\n val to = graph(v)(i)._1\n val len = graph(v)(i)._2\n if (dist(v) + len < dist(to)) {\n relaxed(v) = true\n dist(to) = dist(v) + len\n path(to) = v\n set.add(new Edge(dist(to), to))\n }\n }\n }\n }\n return (dist(end), path)\n }\n }\n val (dist, p) = Dijkstra.findShortestPath(0, n - 1)\n if (dist == Long.MaxValue) {\n out.println(-1)\n } else {\n val path = new util.ArrayList[Int]()\n var v = n - 1\n while (v != 0) {\n path.add(v + 1)\n v = p(v)\n }\n path.add(1)\n for (i <- path.size - 1 to 0 by -1) {\n out.print(path.get(i) + \" \")\n }\n }\n return 1\n }\n\n class Edge(var len: Long, var to: Int) extends Comparable[Edge] {\n\n override def compareTo(o: Edge): Int = -java.lang.Long.compare(o.len, this.len)\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\nimport scala.collection.mutable\n\nobject Main extends App {\n // process input!\n val input = Source.stdin.getLines.map(_.split(\" \").map(_.toInt))\n type Node = Int\n type Weight = Int\n val graph = mutable.Map.empty[Node, mutable.Map[Node, Weight]]\n val (n :: numEdges :: Nil) = input.next.toList\n val edges = input.map(_.toList)\n\n // construct the graph!\n def makeEdge(from: Node, to: Node, weight: Weight) = {\n val source = graph.getOrElseUpdate(from, mutable.Map.empty[Node, Weight])\n source.get(to) match {\n case None => source.update(to, weight)\n case Some(prevWeight) if(weight < prevWeight) => source.update(to, weight)\n case _ => ()\n }\n }\n edges.foreach {\n case from :: to :: weight :: Nil => {\n makeEdge(from, to, weight)\n makeEdge(to, from, weight)\n }\n case _ => ()\n }\n\n // Prepare for Dijkstra! This represents a graph path!\n sealed abstract class Path {\n def cost: Int\n }\n case object Stop extends Path {\n override val toString = \"\"\n override val cost = 0\n }\n case class Go(val location: Node, val cost: Weight, val prev: Path) extends Path {\n override val toString = s\"${prev.toString} $location\".trim\n }\n\n // Sort by lowest cost!\n implicit val goOrdering: Ordering[Go] = Ordering.by(_.cost)\n\n // For example, we begin at node 1 with a cost of 0!\n val start = Go(1, 0, Stop)\n\n // Here are the Dijkstra Data Doodads of Doom!\n val conquered = mutable.Set.empty[Path]\n val frontier = mutable.SortedSet[Go](start)\n val enemy = mutable.Set((2 to n).toList:_*)\n\n // Here is the algorithm! Yay!\n var warPath: Option[Path] = None\n while(warPath.isEmpty && !frontier.isEmpty) {\n val battlefield = frontier.min\n frontier -= battlefield\n if(battlefield.location == n) {\n warPath = Some(battlefield)\n } else {\n conquered += battlefield\n for {\n connections <- graph.get(battlefield.location).toList\n (target, weight) <- connections\n totalCost = battlefield.cost + weight\n if enemy(target) || frontier.exists {\n case Go(targ, cost, _) => targ == target && cost > totalCost\n }\n } yield {\n frontier += Go(\n location = target,\n cost = totalCost,\n prev = battlefield)\n enemy -= target\n }\n }\n }\n\n // And our answer!!!!!!!!!!!\n warPath match {\n case None => println(\"-1\")\n case Some(path) => println(path)\n }\n}"}, {"source_code": "import scala.io.Source\nimport scala.collection.mutable\n\nobject Main extends App {\n // process input!\n val input = Source.stdin.getLines.map(_.split(\" \").map(_.toInt))\n type Node = Int\n type Weight = Int\n val graph = mutable.Map.empty[Node, mutable.Map[Node, Weight]]\n val (n :: numEdges :: Nil) = input.next.toList\n val edges = input.map(_.toList)\n\n // construct the graph!\n def makeEdge(from: Node, to: Node, weight: Weight) = {\n val source = graph.getOrElseUpdate(from, mutable.Map.empty[Node, Weight])\n source.get(to) match {\n case None => source.update(to, weight)\n case Some(prevWeight) => if(weight < prevWeight) source.update(to, weight)\n }\n }\n edges.foreach {\n case from :: to :: weight :: Nil => {\n makeEdge(from, to, weight)\n makeEdge(to, from, weight)\n }\n case _ => ()\n }\n\n // Prepare for Dijkstra! This represents a graph path!\n case class Path(val fullPath: List[Node], val cost: Weight) {\n def location = fullPath.head\n override def toString = fullPath.mkString(\" \")\n }\n\n // Sort by lowest cost! and then target, so paths with same weight don't clobber each other!\n implicit val pathOrdering: Ordering[Path] = Ordering.by(path => (-path.cost, path.location))\n\n // For example, we begin at node 1 with a cost of 0!\n val end = Path(List(n), 0)\n\n // Here are the Dijkstra Data Doodads of Doom!\n val conquered = mutable.Set.empty[Node]\n val frontier = new java.util.PriorityQueue[Path](10, pathOrdering)\n frontier.offer(end)\n\n // Here is the algorithm! Yay! I AM NAPOLEON!!!!\n var warPath: Option[Path] = None\n while(warPath.isEmpty && !frontier.isEmpty) {\n val battlefield = frontier.poll\n val location = battlefield.location\n if(location == 1) {\n warPath = Some(battlefield)\n } else {\n conquered += location\n for {\n connections <- graph.get(location).toList\n (target, weight) <- connections\n if !conquered(target)\n } yield {\n frontier.add(Path(\n fullPath = target :: battlefield.fullPath,\n cost = battlefield.cost + weight))\n }\n }\n }\n\n // And our answer!!!!!!!!!!!\n warPath match {\n case None => println(\"-1\")\n case Some(path) => println(path)\n }\n}\n"}], "src_uid": "bda2ca1fd65084bb9d8659c0a591743d"} {"source_code": "object eCashback {\n\n import scala.collection.mutable\n import scala.io.StdIn.readLine\n\n class SortedSeq {\n private val storage: mutable.TreeMap[Int, Int] = new mutable.TreeMap[Int, Int]\n private var sum:BigInt = 0\n\n def add(elem: Int):Unit = {\n storage(elem) = storage.getOrElse(elem, 0) + 1\n sum+=elem\n }\n\n def remove(elem: Int): Unit = {\n storage.get(elem) match {\n case None => ()\n case Some(1) => storage-= elem\n case Some(x) => storage(elem) = x - 1\n }\n sum-=elem\n }\n\n def min:Int = storage.head._1\n\n def cost:BigInt = sum - min\n\n override def toString: String = storage.toString()\n }\n\n def cashback(n: Int, c: Int, arr: Array[Int]):BigInt = {\n\n val seq = new SortedSeq\n\n val dp: Array[BigInt] = (0 until n).map(_ => BigInt(0)).toArray\n for (i <- 0 until n) {\n seq.add(arr(i))\n if (i < c - 1) dp(i) = {if (i > 0) dp(i-1) else BigInt(0)} + arr(i)\n else if (i == c - 1) dp(i) = seq.cost\n else {\n seq.remove(arr(i - c))\n dp(i) = if (dp(i - 1) + arr(i) < dp(i - c) + seq.cost) dp(i - 1) + arr(i) else dp(i - c) + seq.cost\n }\n }\n dp(n - 1)\n }\n\n def main(args: Array[String]):Unit = {\n val n::c::Nil = readLine().split(\" \").map(_.toInt).toList\n val arr = readLine.split(\" \").map(_.toInt)\n println(cashback(n, c, arr))\n }\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.collection.mutable\n\nobject E extends App {\n val INF = 1 << 30\n\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n def long() = st.nextToken().toLong\n\n read()\n val n = int()\n val c = int()\n\n read()\n val a = Array.fill(n)(int())\n val b = new Array[Long](n)\n var globalMax = 0L\n\n val latest = mutable.SortedMap.empty[Int, Int]\n\n for (i <- 0 until n) {\n var previous = 0L\n val v = a(i)\n latest(v) = latest.getOrElse(v, 0) + 1\n if (i >= c) {\n val q = a(i-c)\n val qq = latest(q)\n if (qq == 1) latest.remove(q)\n else latest(q) = qq - 1\n previous = b(i-c)\n }\n if (i >= c-1) {\n globalMax = Math.max(globalMax, previous + latest.firstKey)\n }\n b(i) = globalMax\n }\n\n val sum = a.foldLeft(0L)(_ + _)\n println(sum - globalMax)\n\n}\n"}], "negative_code": [{"source_code": "object eCashback {\n\n import scala.collection.mutable\n import scala.io.StdIn.readLine\n\n class SortedSeq {\n private val storage: mutable.TreeMap[Int, Int] = new mutable.TreeMap[Int, Int]\n private var sum:BigInt = 0\n\n def add(elem: Int):Unit = {\n storage(elem) = storage.getOrElse(elem, 0) + 1\n sum+=elem\n }\n\n def remove(elem: Int): Unit = {\n storage.get(elem) match {\n case None => ()\n case Some(1) => storage-= elem\n case Some(x) => storage(elem) = x - 1\n }\n sum-=elem\n }\n\n def min:Int = storage.head._1\n\n def cost:BigInt = sum - min\n\n override def toString: String = storage.toString()\n }\n\n def cashback(n: Int, c: Int, arr: Array[Int]):BigInt = {\n\n val seq = new SortedSeq\n\n val dp: Array[BigInt] = (0 until n).map(_ => BigInt(0)).toArray\n dp(0) = arr(0)\n seq.add(arr(0))\n for (i <- 1 until n) {\n seq.add(arr(i))\n if (i < c - 1) dp(i) = dp(i-1) + arr(i)\n else if (i == c - 1) {\n dp(i) = seq.cost\n }\n else {\n seq.remove(arr(i - c))\n dp(i) = if (dp(i - 1) + arr(i) < dp(i - c) + seq.cost) dp(i - 1) + arr(i) else dp(i - c) + seq.cost\n }\n }\n dp(n - 1)\n }\n\n def main(args: Array[String]):Unit = {\n val n::c::Nil = readLine().split(\" \").map(_.toInt).toList\n val arr = readLine.split(\" \").map(_.toInt)\n println(cashback(n, c, arr))\n }\n}\n"}, {"source_code": "object eCashback {\n\n import scala.collection.mutable\n import scala.io.StdIn.readLine\n\n class SortedSeq {\n private val storage: mutable.TreeMap[Int, Int] = new mutable.TreeMap[Int, Int]\n private var sum = 0\n\n def add(elem: Int):Unit = {\n storage(elem) = storage.getOrElse(elem, 0) + 1\n sum+=elem\n }\n\n def remove(elem: Int): Unit = {\n storage.get(elem) match {\n case None => ()\n case Some(1) => storage-= elem\n case Some(x) => storage(elem) = x - 1\n }\n sum-=elem\n }\n\n def min:Int = storage.head._1\n\n def cost:Int = sum - min\n\n override def toString: String = storage.toString()\n }\n\n def cashback(n: Int, c: Int, arr: Array[Int]):Int = {\n\n val seq = new SortedSeq\n\n val dp: Array[Int] = (0 until n).map(_ => 0).toArray\n dp(0) = arr(0)\n seq.add(arr(0))\n for (i <- 1 until n) {\n seq.add(arr(i))\n if (i < c - 1) dp(i) = dp(i-1) + arr(i)\n else if (i == c - 1) {\n dp(i) = seq.cost\n }\n else {\n seq.remove(arr(i - c))\n dp(i) = math.min(dp(i - 1) + arr(i), dp(i - c) + seq.cost)\n }\n }\n dp(n - 1)\n }\n\n def main(args: Array[String]):Unit = {\n val n::c::Nil = readLine().split(\" \").map(_.toInt).toList\n val arr = readLine.split(\" \").map(_.toInt)\n println(cashback(n, c, arr))\n }\n}\n"}], "src_uid": "d1dced03a12dd64b8c7519bfb12f9c82"} {"source_code": "object A43 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val goals = Array.fill(n)(read)\n val diff = goals.toSet.toArray\n val map = collection.mutable.Map[String, Int]().withDefaultValue(0)\n for(i <- diff) {\n map(i) = goals.count(_ == i)\n }\n println(map.toArray.maxBy(_._2)._1)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P043A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n sc.nextLine\n val GOALS = List.fill(N)(sc.nextLine)\n\n def solve(): String = GOALS.groupBy(identity).toSeq.sortWith(_._2.size > _._2.size).head._1\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.io.FileWriter\nimport java.io.PrintWriter\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var n = readInt;\n var map = Map[String, Int]();\n for (i <- 0 until n) {\n var s = readLine;\n map.put(s, map.getOrElse(s, 0) + 1);\n }\n println(map.maxBy(_._2)._1);\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n var n = readInt()\n val map = scala.collection.mutable.Map[String, Int]()\n for(_ <- 1 to n) {\n val c = readLine()\n map(c) = map.getOrElse(c, 0) + 1 \n }\n val e = map.toList.sortBy(_._2).reverse.apply(0)\n println(e._1)\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println((1 to n).map(_ => in.next()).groupBy(x => x).maxBy(_._2.length)._1)\n}\n"}], "negative_code": [], "src_uid": "e3dcb1cf2186bf7e67fd8da20c1242a9"} {"source_code": "object C extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val s = readLine()\n\n val ans = s\n .foldLeft(List.empty[Char]) {\n case ('A' :: t, 'B') => t\n case ('B' :: t, 'B') => t\n case (ls, c) => c :: ls\n }\n .length\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val s = nextLine\n var prev = ' '\n val cntsBuilder = new mutable.ArrayBuilder.ofInt\n var cnt = 1\n for (c <- s) {\n if (c == prev) {\n cnt += 1\n } else if (prev == 'A') {\n cntsBuilder += -cnt\n cnt = 1\n } else if (prev == 'B') {\n cntsBuilder += cnt\n cnt = 1\n }\n prev = c\n }\n if (prev == 'A') {\n cntsBuilder += -cnt\n } else if (prev == 'B') {\n cntsBuilder += cnt\n }\n var cnts = cntsBuilder.result()\n\n var changed = true\n while (changed) {\n// println(cnts.mkString(\" \"))\n changed = false\n for (i <- 1 until cnts.length) {\n val a = cnts(i - 1)\n val b = cnts(i)\n if (a < 0 && b > 0) {\n val c = math.min(-a, b)\n cnts(i - 1) += c\n cnts(i) -= c\n changed = true\n }\n }\n cnts = cnts.filter(_ != 0)\n }\n\n changed = true\n while (changed) {\n changed = false\n for (i <- cnts.indices) {\n if (cnts(i) > 1) {\n cnts(i) %= 2\n changed = true\n }\n }\n cnts = cnts.filter(_ != 0)\n for (i <- 1 until cnts.length) {\n if (cnts(i - 1) == 1 && cnts(i) == 1) {\n cnts(i - 1) = 0\n cnts(i) = 0\n }\n }\n cnts = cnts.filter(_ != 0)\n }\n\n out.println(cnts.map(math.abs).sum)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "ee295fd90ee9283709447481f172c73c"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toInt).scanLeft(2) {\n case(a, b) => (a + b + 1) % 2\n }.tail.map(2 - _)\n println(line.toList.mkString(\"\\n\"))\n}\n", "positive_code": [{"source_code": "object B705 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n)\n var player = in(0)%2\n println(player+1)\n for(i <- 1 until n) {\n if(in(i)%2 == 0)\n player = 1 - player\n println(player+1)\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _705B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val cycles = read[Vector[Int]]\n\n var last: Int = 0\n cycles foreach {c =>\n val ans = (last, c%2) match {\n case (0, 0) => 1\n case (0, 1) => 2\n\n case (1, 0) => 2\n case (1, 1) => 1\n\n case (2, 0) => 1\n case (2, 1) => 2\n }\n io.writeOnNextLine(ans)\n last = ans\n }\n\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n /*\n\n 1 := 2\n 2 -> 1 1 := 1\n 2 -> 1 1 := 2\n 2 -> 1 1 := 1\n\n 3 -> 1 2 -> 1 1 1 := 2\n 3 -> 1 2 -> 1 1 1 := 2\n\n 4 -> 1 3 -> 1 1 2 -> 1 1 1 1 := 1\n 2 2 -> 1 1 2 -> 1 1 1 1 :=\n\n */\n\n val n = readInt()\n val A = readLine().split(\" \").map(_.toInt)\n\n var winner = 1\n var sum = 0\n\n for (i <- 0 until n) {\n if (A(i) > 0) {\n if (A(i) % 2 == 0) {\n if (winner == 1) winner = 2 else winner = 1\n }\n }\n\n println(if (winner == 1) 2 else 1)\n }\n\n}\n"}, {"source_code": "object Cycles extends App {\n\n def iter(seq: List[Int], results: List[Int]): List[Int] = seq match {\n case Nil => results\n case x :: xs => iter(xs, (results.headOption.getOrElse(0) + x - 1) % 2 :: results)\n }\n\n val n: Int = readLine.toInt\n val a: List[Int] = readLine.split(' ').map(_.toInt).toList\n val results = iter(a, Nil)\n\n results.reverse.map {\n case 0 => 2\n case x => x.abs\n }.foreach(println)\n\n}\n"}], "negative_code": [], "src_uid": "3a767b3040f44e3e2148cdafcb14a241"} {"source_code": "object E1 extends App {\r\n\r\n def permutationMinimizationByDeque(an: List[Int]): List[Int] = {\r\n val (left, right) = an.foldLeft((List.empty[Int], List.empty[Int])) {\r\n case ((Nil, ys), a) => (a :: Nil, ys)\r\n case ((xs @ x :: _, ys), a) if a < x => (a :: xs, ys)\r\n case ((xs, ys), a) => (xs, a :: ys)\r\n }\r\n\r\n left ++ right.reverse\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val an = nextInts(n).toList\r\n\r\n val bn = permutationMinimizationByDeque(an)\r\n\r\n out.println(bn.mkString(\" \"))\r\n }\r\n\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object E1 extends App {\r\n\r\n def permutationMinimizationByDeque(an: List[Int]): List[Int] = {\r\n require(an.length > 0, \"The size of an permutation should be at least 1\")\r\n\r\n val (left, right) = an.drop(1).foldLeft((List(an.head), List.empty[Int])) {\r\n case ((xs @ x :: _, ys), a) if a < x => (a :: xs, ys)\r\n case ((xs, ys), a) => (xs, a :: ys)\r\n }\r\n\r\n left ++ right.reverse\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val an = nextInts(n).toList\r\n\r\n val bn = permutationMinimizationByDeque(an)\r\n\r\n out.println(bn.mkString(\" \"))\r\n }\r\n\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(left: Int, right: Int, index: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (left < that.left || (left == that.left && right < that.right))\n return -1\n else if (left == that.left && right == that.right)\n return 0\n else\n return 1\n }\n }\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val left = new ArrayBuffer[Int]()\n val right = new ArrayBuffer[Int]()\n var tmp = 0\n for (i <- 1 to n) {\n tmp = readInt()\n if (left.isEmpty || tmp <= left(left.length-1))\n left.append(tmp)\n else\n right.append(tmp)\n }\n for (i <- left.indices.reverse)\n writer.print(left(i) + \" \")\n for (i <- right.indices)\n writer.print(right(i) + \" \")\n writer.println()\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "5afa0e4f34ab8c8c67bc8ecb7d6d2d7a"} {"source_code": "import Array._\nimport scala.io.StdIn.readLine\nobject problem {\n def main(args: Array[String]) {\n var cnt = 1\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n val a = readLine.split(\" \").map(_.toInt)\n while(cnt < m) cnt += a(cnt - 1)\n if(cnt == m){\n println(\"YES\")\n }else println(\"NO\")\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject NewYearTransport {\n // https://codeforces.com/problemset/problem/500/A\n def main(args: Array[String]): Unit = {\n val (n, t) = StdIn.readLine().split(\" \") match {\n case Array(n, t) => (n.toInt, t.toInt)\n }\n\n val arrA = StdIn.readLine().split(\" \").map(_.toInt)\n\n val res = if (canReach(1, arrA, t)) \"YES\" else \"NO\"\n println(res)\n }\n\n def canReach(i: Int, arr: Array[Int], t: Int): Boolean = {\n if (i == t) true\n else if (i > t) false\n else canReach(i + arr.head, arr.slice(arr.head, arr.length), t)\n }\n\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\nimport scala.util.Sorting._\nimport scala.math._\nimport scala.collection._\nimport java.util._\n\nobject HelloWorld {\n def main(args: Array[String]): Unit = {\n val Array(n, t) = readLine.split(\" \").map(_.toInt)\n val portals = readLine.split(\" \").map(_.toInt)\n\n var current_index = 0\n var possible_to_escape = false\n while (current_index < t - 1 && !possible_to_escape) {\n if ((current_index + 1) + portals(current_index) == t){\n possible_to_escape = true\n }\n\n current_index += portals(current_index)\n }\n\n println(if(possible_to_escape) \"YES\" else \"NO\")\n }\n}"}, {"source_code": "import java.util.Scanner \n\n\nobject Main { \ndef main(args: Array[String]) { \nval scanner = new Scanner(System.in) \nval n = scanner.nextInt() \nval t = scanner.nextInt() \n\nvar next = 0 \nfor(i <- 0 to (n - 2)) { \nval jump = scanner.nextInt() \nif(i == next) { \nnext += jump \nif(next == t - 1) { \nprintln(\"YES\") \nreturn \n} \n} \n} \n\nprintln(\"NO\") \n} \n}"}, {"source_code": "object A500 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n var Array(n, t) = readInts(2)\n val input = readInts(n-1)\n var curr = 1\n\n while(curr-1 < n-1 && curr != t) {\n curr = curr + input(curr-1)\n }\n if(curr == t) println(\"YES\") else println(\"NO\")\n }\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, t) = readInts(2)\n val as = Array(0) ++ readInts(n - 1)\n\n val q = mutable.Queue(1)\n var can = false\n \n while (!q.isEmpty) {\n val u = q.dequeue\n if (u == t) can = true\n if (u < n) q.enqueue(u + as(u))\n }\n \n println(if (can) \"YES\" else \"NO\")\n}"}, {"source_code": "import java.util.Scanner\n\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n val t = scanner.nextInt()\n \n var next = 0\n for(i <- 0 to (n - 2)) {\n val jump = scanner.nextInt()\n if(i == next) {\n next += jump\n if(next == t - 1) {\n println(\"YES\")\n return\n }\n }\n }\n\n println(\"NO\")\n }\n}\n"}, {"source_code": "import collection.mutable.SortedSet;\n\nobject NewYearTransportation {\n\tdef main (args: Array[String]) {\n\t\t// Parsing the input\n\t\tval scanner = new java.util.Scanner(System.in);\n\t\tval n = scanner.nextInt();\n\t\tval t = scanner.nextInt() - 1;\n\t\tvar map = new Array[Int](n);\n\t\tfor (i <- 0 to n - 2) {\n\t\t\tmap(i) = scanner.nextInt();\n\t\t}\n\t\tmap(n-1) = 0;\n\t\t// Computation\n\t\tvar visited = SortedSet[Int]();\n\t\tvar toVisit = SortedSet[Int](0);\n\t\twhile (toVisit != SortedSet.empty && !(visited contains t)){\n\t\t\tval elt = toVisit.head;\n\t\t\ttoVisit -= elt;\n\t\t\tvisited += elt;\n\t\t\tval next = map(elt)+elt;\n\t\t\tif (! (visited contains next)) \n\t\t\t\ttoVisit += next\n\t\t}\n\t\tif (visited contains t)\n\t\t\tprintln(\"YES\")\n\t\t\telse\n\t\t\t\tprintln(\"NO\")\n\t}\n}"}, {"source_code": "\n import java.util.Scanner\n\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n val t = scanner.nextInt()\n \n var next = 0\n for(i <- 0 to (n - 2)) {\n val jump = scanner.nextInt()\n if(i == next) {\n next += jump\n if(next == t - 1) {\n println(\"YES\")\n return\n }\n }\n }\n\n println(\"NO\")\n }\n}"}, {"source_code": "object P500A {\n\tdef readInts() : Array[Int] = {\n\t\tscala.io.StdIn.readLine.split(\" \").map(_.toInt)\n\t}\n\n\tdef solve(t: Int, as: Iterable[Int]) : Unit = {\n\t\tif (t < 0)\n\t\t\tprintln(\"NO\")\n\t\telse if (t == 0)\n\t\t\tprintln(\"YES\")\n\t\telse\n\t\t\tsolve(t - as.head, as.drop(as.head))\n\t}\n\n\tdef main(args: Array[String]) {\n\t\tval Array(n, t) = readInts()\n\t\tval as = readInts().toList\n\t\tsolve(t - 1, as)\n\t}\n}\n"}, {"source_code": "object P500A {\n\t@inline def parseInts(n: Int, line: String) : Array[Int] = {\n\t\tval tokenizer = new java.util.StringTokenizer(line)\n\t\tArray.fill(n)(tokenizer.nextToken.toInt)\n\t}\n\n\tdef solve(t: Int, as: Iterable[Int]) : Unit = {\n\t\tif (t > 0)\n\t\t\tsolve(t - as.head, as.drop(as.head))\n\t\telse if (t == 0)\n\t\t\tprintln(\"YES\")\n\t\telse\n\t\t\tprintln(\"NO\")\n\t}\n\n\tdef main(args: Array[String]) {\n\t\tval Array(n, t) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n\t\tval as = parseInts(n - 1, scala.io.StdIn.readLine).toList\n\t\tsolve(t - 1, as)\n\t}\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.io.StdIn\nimport Array._\nimport scala.io.StdIn.readLine\nobject problem {\n def main(args: Array[String]) {\n val cin = new Scanner(System.in)\n val n = cin.nextInt()\n val m = cin.nextInt()\n var cnt = 0\n for( i <- 0 to (n - 2)){\n val s = cin.nextInt()\n if(cnt == i){\n cnt += s\n if(cnt == m - 1){\n println(\"YES\"); return\n }\n }\n }\n println(\"NO\")\n }\n}"}, {"source_code": "\n import java.util.Scanner\n\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n val t = scanner.nextInt()\n \n var next = 0\n for(i <- 0 to (n - 2)) {\n val jump = scanner.nextInt()\n if(i == next) {\n next += jump\n if(next == t - 1) {\n println(\"YES\")\n return\n }\n }\n }\n\n println(\"NO\")\n }\n}"}, {"source_code": "\n import java.util.Scanner\n\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n val t = scanner.nextInt()\n \n var next = 0\n for(i <- 0 to (n - 2)) {\n val jump = scanner.nextInt()\n if(i == next) {\n next += jump\n if(next == t - 1) {\n println(\"YES\")\n return\n }\n }\n }\n\n println(\"NO\")\n }\n}"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject NewYearTransportation {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def reachable(current: Int, goal: Int, portal: IndexedSeq[Int]) : Boolean = {\n if (current == goal) true\n else if (current > goal) false else reachable(current + portal(current), goal, portal)\n } \n \n def main(args: Array[String]) {\n val nt = readInts\n val n = nt(0)\n val t = nt(1) - 1\n val portals = readInts\n if (reachable(0,t,portals)) println(\"YES\") else println(\"NO\")\n }\n \n}"}, {"source_code": "import scala.collection.immutable.IndexedSeq\n\nobject Main extends App\n{\n def dfs(g:Array[List[Int]], v: Int, used: Set[Int], need:Int): Set[Int] = {\n if(v>need)\n {\n println(\"NO\")\n Set.empty[Int]\n } // печатаем или куда-то сохраняем\n else if(v == need)\n {\n println(\"YES\")\n Set.empty[Int]\n } else\n (for(u <- g(v)) yield u).foldLeft(used){\n (usd, h) =>\n if (!usd.contains(h))\n usd ++ dfs(g, h, usd + h, need) + h\n else usd\n }\n }\n\ndef next_dfs(g:Array[List[Int]], v: Int, need:Int):Unit={\n if(v>need)\n {\n println(\"NO\")\n Set.empty[Int]\n } // печатаем или куда-то сохраняем\n else if(v == need)\n {\n println(\"YES\")\n Set.empty[Int]\n } else next_dfs(g, g(v)(0), need)\n }\n\n override def main(args: Array[String])\n {\n //dfs(input(), 0, Set(0), 4)\n //println(unique_substring(scala.io.StdIn.readLine()).toString())\n val t=scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val a=scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n //println(a.mkString(\",\"))\n var i=0; // переменная по масиву а\n var con =0;\n var g = new Array[List[Int]](t(0))\n for(v <- 0 to g.length-2)// заполнение графа\n {\n g(v)=List(a(i)+v)\n con=a(i)-1\n i=i+1\n }\n //println(g.mkString(\",\"))\n next_dfs(g, 0, t(1)-1)\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Main2 extends App {\n val Array(cellNumber, destination) = readLine().split(\" \").map(_.toInt)\n val portals = readLine().split(\" \").map(_.toInt)\n val answers = Array.fill(cellNumber + 3)(false)\n answers(0) = true\n for ( i <- 0 until cellNumber-1) {\n if (answers(i)) answers(i + portals(i)) = true\n }\n println(if (answers(destination - 1)) \"YES\" else \"NO\")\n}\n"}, {"source_code": "import java.util.Scanner;\n\nobject Main extends App {\n var input = new Scanner(System.in)\n\n var N = input.nextInt()\n var T = input.nextInt()\n\n var X = new Array[Int](N + 1)\n\n for (i <- 1 to (N - 1)) {\n X(i) = input.nextInt()\n }\n\n var pos = 1\n var reach = false\n\n while (pos <= T) {\n if (pos == T) {\n reach = true\n pos = N + 1;\n } else {\n pos = pos + X(pos)\n }\n }\n\n if (reach) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n}\n"}, {"source_code": "object Solution extends App {\n val Array(n, t) = readLine.split(\" \").map(_.toInt)\n val as = readLine.split(\" \").map(_.toInt)\n \n //as.zipWithIndex.map(_._1 + _._2)\n \n def can(i:Int):Boolean = {\n if(i==t-1)\n true\n else if(i>t-1)\n false\n else\n can(as(i) + i)\n }\n \n if(can(0))\n println(\"YES\")\n else\n println(\"NO\")\n}"}, {"source_code": "\nobject ProblemA extends App {\n case class Node(\n offset: Int\n )\n\n def BFS(nodes: Array[Node], startIndex: Int, dstIndex: Int): Boolean = {\n if (startIndex == dstIndex) {\n true\n } else if (nodes(startIndex).offset == -1) {\n false\n } else {\n BFS(nodes, startIndex + nodes(startIndex).offset, dstIndex)\n }\n }\n\n val line1: String = scala.io.StdIn.readLine\n val line2: String = scala.io.StdIn.readLine\n\n val total :: dstIndex :: _ = line1.split(\" \").map(_.toInt).toList\n val nodes = line2.split(\" \").map { x =>\n Node(offset = x.toInt)\n }\n\n val msg: String = BFS(nodes ++ Array(Node(-1)), 0, dstIndex - 1) match {\n case true => \"YES\"\n case false => \"NO\"\n }\n println(msg)\n}\n"}, {"source_code": "import java.util.Scanner \n\n\nobject Main { \ndef main(args: Array[String]) { \nval scanner = new Scanner(System.in) \nval n = scanner.nextInt() \nval t = scanner.nextInt() \n\nvar next = 0 \nfor(i <- 0 to (n - 2)) { \nval jump = scanner.nextInt() \nif(i == next) { \nnext += jump \nif(next == t - 1) { \nprintln(\"YES\") \nreturn \n} \n} \n} \n\nprintln(\"NO\") \n} \n}"}, {"source_code": "import java.util.Scanner \n\n\nobject Main { \ndef main(args: Array[String]) { \nval scanner = new Scanner(System.in) \nval n = scanner.nextInt() \nval t = scanner.nextInt() \n\nvar next = 0 \nfor(i <- 0 to (n - 2)) { \nval jump = scanner.nextInt() \nif(i == next) { \nnext += jump \nif(next == t - 1) { \nprintln(\"YES\") \nreturn \n} \n} \n} \n\nprintln(\"NO\") \n} \n}"}, {"source_code": "\n \n import java.util.Scanner\n\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n val t = scanner.nextInt()\n \n var next = 0\n for(i <- 0 to (n - 2)) {\n val jump = scanner.nextInt()\n if(i == next) {\n next += jump\n if(next == t - 1) {\n println(\"YES\")\n return\n }\n }\n }\n\n println(\"NO\")\n }\n}"}, {"source_code": "object NewYearTransportation {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n var line=in.readLine()\n val n=line.split(\" \")(0).toInt\n val t=line.split(\" \")(1).toInt\n line=in.readLine()\n val a:Array[Int]=line.split(\" \").map(_.toInt)\n var flag = false\n var i = 1\n while (i <= n - 1 && !flag){\n if(i==t){\n flag=true\n }\n i=i+a(i-1)\n }\n if(i==t){\n flag=true\n }\n println(if(flag) \"YES\" else \"NO\")\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Task500A {\n\tdef main(args: Array[String]) {\n\t\tval t = StdIn.readLine().split(\" \").map(_.toInt).apply(1)\n\t\tval numbers = StdIn.readLine().split(\" \").map(_.toInt)\n\t\tvar position = 1\n\t\twhile (position < t) position += numbers(position - 1)\n\t\tif (position == t) println(\"YES\") else println(\"NO\")\n\t}\n}\n"}, {"source_code": "\n import java.util.Scanner\n\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n val t = scanner.nextInt()\n \n var next = 0\n for(i <- 0 to (n - 2)) {\n val jump = scanner.nextInt()\n if(i == next) {\n next += jump\n if(next == t - 1) {\n println(\"YES\")\n return\n }\n }\n }\n\n println(\"NO\")\n }\n}"}], "negative_code": [{"source_code": "import scala.collection.immutable.IndexedSeq\n\nobject Main extends App\n{\n def input() = {\n val n=scala.io.StdIn.readInt\n for(i <- 1 to n) yield {\n scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n }\n }\n\n def dfs(g:Array[List[Int]], v: Int, used: Set[Int], need:Int): Set[Int] = {\n if(v>need)\n {\n println(\"NO\")\n Set.empty[Int]\n } // печатаем или куда-то сохраняем\n else if(v == need)\n {\n println(\"YES\")\n Set.empty[Int]\n } else\n (for(u <- g(v)) yield u).foldLeft(used){\n (usd, h) =>\n if (!usd.contains(h))\n usd ++ dfs(g, h, usd + h, need) + h\n else usd\n }\n }\n\n def unique_substring(str:String): List[String] =\n {\n var ret=List.empty[String]\n for(i <- 1 to str.length-1)\n for(j <- 0 to str.length-i)\n {\n val substr=str.substring(j, j+i)\n if (str.indexOf(substr) == j && str.indexOf(substr, j+1) == -1)\n ret=ret.+:(substr)\n }\n ret\n }\n\n override def main(args: Array[String])\n {\n //dfs(input(), 0, Set(0), 4)\n //println(unique_substring(scala.io.StdIn.readLine()).toString())\n val t=scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val a=scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n //println(a.mkString(\",\"))\n var i=0; // переменная по масиву а\n var con =0;\n var g = new Array[List[Int]](t(0))\n for(v <- 0 to g.length-1)// заполнение графа\n {\n if(con == 0)\n {\n g(v)=List(a(i)+v)\n // g(v).+:(a(i)+v)\n con=a(i)-1\n i=i+1\n }\n else con=con-1\n }\n dfs(g, 0, Set(0), t(1))\n }\n}\n"}, {"source_code": "\n import java.util.Scanner\n\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n val t = scanner.nextInt()\n \n var next = 0\n for(i <- 1 to (n - 2)) {\n val jump = scanner.nextInt()\n if(i == next) {\n next += jump\n if(next == t - 1) {\n println(\"YES\")\n return\n }\n }\n }\n\n println(\"NO\")\n }\n}"}, {"source_code": "\n import java.util.Scanner\n\n\nobject Main {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n val t = scanner.nextInt()\n \n var next = 0\n for(i <- 0 to (n - 5)) {\n val jump = scanner.nextInt()\n if(i == next) {\n next += jump\n if(next == t - 1) {\n println(\"YES\")\n return\n }\n }\n }\n\n println(\"NO\")\n }\n}"}, {"source_code": "object P500A {\n\tdef readInts() : Array[Int] = {\n\t\tscala.io.StdIn.readLine.split(\" \").map(_.toInt)\n\t}\n\n\tdef solve(t: Int, as: Iterable[Int]) : Unit = {\n\t\tif (t < 0)\n\t\t\tprintln(\"NO\")\n\t\telse if (t == 0)\n\t\t\tprintln(\"YES\")\n\t\telse\n\t\t\tsolve(t - as.head, as.drop(as.head))\n\t}\n\n\tdef main(args: Array[String]) {\n\t\tval Array(a, t) = readInts()\n\t\tval as = readInts()\n\t\tsolve(t, as)\n\t}\n}\n"}, {"source_code": "import scala.collection.immutable.IndexedSeq\n\nobject Main extends App\n{\n def dfs(g:Array[List[Int]], v: Int, used: Set[Int], need:Int): Set[Int] = {\n if(v>need)\n {\n println(\"NO\")\n Set.empty[Int]\n } // печатаем или куда-то сохраняем\n else if(v == need)\n {\n println(\"YES\")\n Set.empty[Int]\n } else\n (for(u <- g(v)) yield u).foldLeft(used){\n (usd, h) =>\n if (!usd.contains(h))\n usd ++ dfs(g, h, usd + h, need) + h\n else usd\n }\n }\n\n \n override def main(args: Array[String])\n {\n //dfs(input(), 0, Set(0), 4)\n //println(unique_substring(scala.io.StdIn.readLine()).toString())\n val t=scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val a=scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n //println(a.mkString(\",\"))\n var i=0; // переменная по масиву а\n var con =0;\n var g = new Array[List[Int]](t(0))\n for(v <- 0 to g.length-1)// заполнение графа\n {\n if(con == 0)\n {\n if(v < t(0)-1)\n g(v)=List(a(i)+v)\n con=a(i)-1\n i=i+1\n }\n else con=con-1\n }\n dfs(g, 0, Set(0), t(1))\n }\n}\n"}, {"source_code": "import java.io._;\nimport java.util._;\n\nobject Main extends App {\n var input = new Scanner(System.in)\n\n var N = input.nextInt()\n var T = input.nextInt()\n\n var X = new Array[Int](N)\n\n for (i <- 1 to (N - 1)) {\n X(i) = input.nextInt()\n }\n\n var pos = 1\n var reach = false\n\n while (pos < N - 1) {\n if (pos == T) {\n reach = true\n }\n pos = pos + X(pos)\n }\n\n if (reach) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n}\n"}, {"source_code": "import java.io._;\nimport java.util._;\n\nobject Main extends App {\n var input = new Scanner(System.in)\n\n var N = input.nextInt()\n var T = input.nextInt()\n\n var X = new Array[Int](N - 1)\n\n for (i <- 0 to (N - 2)) {\n X(i) = input.nextInt()\n }\n\n var pos = 0\n var reach = false\n\n while (pos < N - 1) {\n if (pos == T - 1) {\n reach = true\n }\n pos = pos + X(pos)\n }\n\n if (reach) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n}\n"}], "src_uid": "9ee3d548f93390db0fc2f72500d9eeb0"} {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject Codeforces extends App {\n val n = readInt\n val program = 1 to n map(_ => readLine split ' ' match {\n case Array(cmd, arg) => (cmd, arg.toInt)\n })\n var zero = 0\n var one = 1023\n program foreach {\n case (\"&\", arg) => {\n zero &= arg\n one &= arg\n }\n case (\"|\", arg) => {\n zero |= arg\n one |= arg\n }\n case (\"^\", arg) => {\n zero ^= arg\n one ^= arg\n }\n }\n var and = 0\n var or = 0\n var xor = 0\n for (bit <- 0 to 9) {\n val zeroBit = (zero >> bit) & 1\n val oneBit = (one >> bit) & 1\n (zeroBit, oneBit) match {\n case (0, 1) => {\n and |= (1 << bit)\n }\n case (1, 0) => {\n xor |= (1 << bit)\n and |= (1 << bit)\n }\n case (1, 1) => {\n or |= (1 << bit)\n }\n case _ => {}\n }\n }\n println(3)\n println(s\"^ $xor\")\n println(s\"& $and\")\n println(s\"| $or\")\n}", "positive_code": [{"source_code": "object _879C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val instructions = io.read[Seq[(Char, Int)]]\n\n val n = 10\n val zeroes = Array.fill(n)(0)\n val ones = Array.fill(n)(1)\n\n for {\n (op, arg) <- instructions\n arr <- Seq(zeroes, ones)\n i <- arr.indices\n } arr(i) = op match {\n case '|' => arr(i) | arg.getBit(i)\n case '&' => arr(i) & arg.getBit(i)\n case '^' => arr(i) ^ arg.getBit(i)\n }\n\n var or = 0\n var and = (1<\n (zeroes(i), ones(i)) match {\n case (0, 0) => and = and.clearBit(i)\n case (0, 1) =>\n case (1, 0) => xor = xor.setBit(i)\n case (1, 1) => or = or.setBit(i)\n }\n }\n\n val ans = Seq('&' -> and, '|' -> or, '^' -> xor)\n io.writeLine(ans.length).writeAll(ans.map({case (op, instr) => s\"$op $instr\"}), separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _879C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val instructions = io.read[Seq[(Char, Int)]]\n\n val n = 10\n\n var zeroes = 0\n var ones = (1< Int = instruction match {\n case ('|', arg) => _ | arg\n case ('&', arg) => _ & arg\n case ('^', arg) => _ ^ arg\n }\n\n instructions.map(toFunc).foreach({f =>\n zeroes = f(zeroes)\n ones = f(ones)\n })\n\n var xor = 0\n var or = 0\n var and = (1<\n (zeroes.getBit(i), ones.getBit(i)) match {\n case (0, 0) => and = and.clearBit(i)\n case (0, 1) =>\n case (1, 0) => xor = xor.setBit(i)\n case (1, 1) => or = or.setBit(i)\n }\n }\n\n val ans = Seq('&' -> and, '|' -> or, '^' -> xor)\n io.writeLine(ans.length).writeAll(ans.map({case (op, instr) => s\"$op $instr\"}), separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _879C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val ans = reduce(io.read[Seq[(Char, Int)]])\n io.writeLine(ans.length).writeAll(ans.map({case (op, instr) => s\"$op $instr\"}), separator = \"\\n\")\n }\n\n def reduce(instructions: Seq[(Char, Int)]): Seq[(Char, Int)] = {\n if (instructions.length < 5) return instructions\n\n val f = instructions map {\n case ('|', arg) => arg | (_: Int)\n case ('&', arg) => arg & (_: Int)\n case ('^', arg) => arg ^ (_: Int)\n } reduce {\n (f1, f2) => f1 andThen f2\n }\n\n val zeroes = f(0)\n val ones = f(0 setLowestBits 10)\n\n Seq(\n '&' -> (~(~zeroes & ~ones)), // Select bits that are 0 in zeroes and 0 in ones\n '|' -> (zeroes & ones), // Select bits that are 1 in zeroes and 1 in ones\n '^' -> (zeroes & ~ones) // Select bits that are 1 in zeroes but 0 in ones\n )\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _879C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val instructions = io.read[Seq[(Char, Int)]]\n\n val n = 10\n var zeroes, xor, or = 0\n var ones, and = (1< Int = instruction match {\n case ('|', arg) => _ | arg\n case ('&', arg) => _ & arg\n case ('^', arg) => _ ^ arg\n }\n\n instructions.map(toFunc).foreach({ f =>\n zeroes = f(zeroes)\n ones = f(ones)\n })\n\n (0 until n) foreach {i =>\n (zeroes.getBit(i), ones.getBit(i)) match {\n case (0, 0) => and = and.clearBit(i)\n case (0, 1) =>\n case (1, 0) => xor = xor.setBit(i)\n case (1, 1) => or = or.setBit(i)\n }\n }\n\n val ans = Seq('&' -> and, '|' -> or, '^' -> xor)\n io.writeLine(ans.length).writeAll(ans.map({case (op, instr) => s\"$op $instr\"}), separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _879C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val instructions = io.read[Seq[(Char, Int)]]\n\n val n = 10\n\n var zeroes = 0\n var ones = (1< Int = instruction match {\n case ('|', arg) => _ | arg\n case ('&', arg) => _ & arg\n case ('^', arg) => _ ^ arg\n }\n\n instructions.map(toFunc).foreach({f =>\n zeroes = f(zeroes)\n ones = f(ones)\n })\n\n val xor = zeroes & ~ones // Select bits that are 1 in zeroes but 0 in ones\n val or = zeroes & ones // Select bits that are 1 in zeroes and 1 in ones\n val and = ~(~zeroes & ~ones) // Select bits that are 0 in zeroes and 0 in ones\n\n val ans = Seq('&' -> and, '|' -> or, '^' -> xor)\n io.writeLine(ans.length).writeAll(ans.map({case (op, instr) => s\"$op $instr\"}), separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _879C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val instructions = io.read[Seq[(Char, Int)]]\n\n val n = 10\n def toFunc(instruction: (Char, Int)): Int => Int = instruction match {\n case ('|', arg) => _ | arg\n case ('&', arg) => _ & arg\n case ('^', arg) => _ ^ arg\n }\n\n val f = instructions.map(toFunc).foldLeft(identity[Int] _)(_ andThen _)\n\n val zeroes = f(0)\n val ones = f((1< (~(~zeroes & ~ones)), // Select bits that are 0 in zeroes and 0 in ones\n '|' -> (zeroes & ones), // Select bits that are 1 in zeroes and 1 in ones\n '^' -> (zeroes & ~ones) // Select bits that are 1 in zeroes but 0 in ones\n )\n io.writeLine(ans.length).writeAll(ans.map({case (op, instr) => s\"$op $instr\"}), separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _879C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val instructions = io.read[Seq[(Char, Int)]]\n\n val n = 10\n val zeroes = Array.fill(n)(0)\n val ones = Array.fill(n)(1)\n\n def parseFunc(op: Char): (Int, Int) => Int = op match {\n case '|' => _ | _\n case '&' => _ & _\n case '^' => _ ^ _\n }\n\n for {\n (op, arg) <- instructions\n f = parseFunc(op)\n arr <- Seq(zeroes, ones)\n i <- arr.indices\n } arr(i) = f(arr(i), arg.getBit(i))\n\n var or = 0\n var and = (1<\n (zeroes(i), ones(i)) match {\n case (0, 0) => and = and.clearBit(i)\n case (0, 1) =>\n case (1, 0) => xor = xor.setBit(i)\n case (1, 1) => or = or.setBit(i)\n }\n }\n\n val ans =\n Seq('&' -> and).filter(_.value < (1< or, '^' -> xor).filter(_.value > 0)\n io.writeLine(ans.length).writeAll(ans.map({case (op, instr) => s\"$op $instr\"}), separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _879C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val instructions = io.read[Seq[(Char, Int)]]\n\n val n = 10\n\n val functions: Seq[Int => Int] = instructions map {\n case ('|', arg) => arg | (_: Int)\n case ('&', arg) => arg & (_: Int)\n case ('^', arg) => arg ^ (_: Int)\n }\n\n val ans = if (instructions.length <= 5) {\n instructions\n } else {\n val f = functions.reduce(_ andThen _)\n\n val zeroes = f(0)\n val ones = f(0 setLowestBits n)\n\n Seq(\n '&' -> (~(~zeroes & ~ones)), // Select bits that are 0 in zeroes and 0 in ones\n '|' -> (zeroes & ones), // Select bits that are 1 in zeroes and 1 in ones\n '^' -> (zeroes & ~ones) // Select bits that are 1 in zeroes but 0 in ones\n )\n }\n\n io.writeLine(ans.length).writeAll(ans.map({case (op, instr) => s\"$op $instr\"}), separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "object _879C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val instructions = io.read[Seq[(Char, Int)]]\n\n val table = Array.fill(10)(-1)\n\n instructions foreach {\n case ('|', arg) =>\n for {\n i <- table.indices if arg.getBit(i) == 1\n } table(i) = arg.getBit(i)\n\n case ('&', arg) =>\n for {\n i <- table.indices if arg.getBit(i) == 0\n } table(i) = arg.getBit(i)\n\n case ('^', arg) =>\n for {\n i <- table.indices if table(i) != -1\n } table(i) ^= arg.getBit(i)\n }\n\n var and = (1< and = and.clearBit(i)\n case (1, i) => or = or.setBit(i)\n case _ =>\n }\n\n val ans = if (instructions.length <= 5) instructions else Seq('|' -> or, '&' -> and)\n io.writeLine(ans.length).writeAll(ans.map({case (op, instr) => s\"$op $instr\"}), separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _879C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val n = 10\n val instructions = io.read[Seq[(Char, Int)]]\n\n val table = mutable.Map.empty[Int, Int]\n\n //def debugTable = (0 to n).map(i => table.get(i).map(_.toString).getOrElse(\"X\")).mkString.reverse\n\n instructions foreach {\n case ('|', arg) =>\n for {\n i <- 0 to n if arg.getBit(i) == 1\n } table(i) = arg.getBit(i)\n\n case ('&', arg) =>\n for {\n i <- 0 to n if arg.getBit(i) == 0\n } table(i) = arg.getBit(i)\n\n case ('^', arg) =>\n for {\n i <- 0 to n if table.isDefinedAt(i)\n } table(i) ^= arg.getBit(i)\n }\n\n var and = (1< and = and.clearBit(i)\n case (i, 1) => or = or.setBit(i)\n }\n\n val ans = Seq(s\"| $or\", s\"& $and\")\n\n io.writeLine(ans.length).writeAll(ans, separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _879C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val instructions = io.read[Seq[(Char, Int)]]\n\n val n = 10\n\n def toFunc(instruction: (Char, Int)): Int => Int = instruction match {\n case ('|', arg) => _ | arg\n case ('&', arg) => _ & arg\n case ('^', arg) => _ ^ arg\n }\n\n val functions = instructions.map(toFunc)\n\n val zeroes = functions.foldLeft(0){case (arg, f) => f(arg)}\n val ones = functions.foldLeft(1){case (arg, f) => f(arg)}\n\n var xor = 0\n var or = 0\n var and = (1<\n (zeroes.getBit(i), ones.getBit(i)) match {\n case (0, 0) => and = and.clearBit(i)\n case (0, 1) =>\n case (1, 0) => xor = xor.setBit(i)\n case (1, 1) => or = or.setBit(i)\n }\n }\n\n val ans = Seq('&' -> and, '|' -> or, '^' -> xor)\n io.writeLine(ans.length).writeAll(ans.map({case (op, instr) => s\"$op $instr\"}), separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _879C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val instructions = io.read[Seq[(Char, Int)]]\n\n val table = Array.fill(10)(-1)\n\n var and = (1<\n for {\n i <- table.indices if arg.getBit(i) == 1\n } {\n xor = xor.clearBit(i)\n table(i) = arg.getBit(i)\n }\n\n case ('&', arg) =>\n for {\n i <- table.indices if arg.getBit(i) == 0\n } {\n xor = xor.clearBit(i)\n table(i) = arg.getBit(i)\n }\n\n case ('^', arg) =>\n for {\n i <- table.indices if arg.getBit(i) == 1\n } {\n if (table(i) != -1) {\n table(i) ^= arg.getBit(i)\n } else {\n xor = xor.setBit(i)\n }\n }\n }\n\n table.zipWithIndex foreach {\n case (0, i) => and = and.clearBit(i)\n case (1, i) => or = or.setBit(i)\n case _ =>\n }\n\n val ans = Seq('^' -> xor, '|' -> or, '&' -> and)\n io.writeLine(ans.length).writeAll(ans.map({case (op, instr) => s\"$op $instr\"}), separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _879C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val instructions = io.read[Seq[(Char, Int)]]\n\n val n = 10\n\n var and = (1<\n for {\n i <- 0 until n if arg.getBit(i) == 1\n } {\n and = and.clearBit(i)\n or = or.setBit(i)\n xor = xor.clearBit(i)\n }\n\n case ('&', arg) =>\n for {\n i <- 0 until n if arg.getBit(i) == 0\n } {\n and = and.clearBit(i)\n or = or.clearBit(i)\n xor = xor.clearBit(i)\n }\n\n case ('^', arg) =>\n for {\n i <- 0 until n if arg.getBit(i) == 1\n } xor = xor.setBit(i)\n }\n\n val ans = Seq('&' -> and, '|' -> or, '^' -> xor)\n io.writeLine(ans.length).writeAll(ans.map({case (op, instr) => s\"$op $instr\"}), separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _879C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val instructions = io.read[Seq[(Char, Int)]]\n\n val table = Array.fill(10)(-1)\n\n def debugTable() = table.map(i => if (i == -1) \"X\" else i.toString).mkString.reverse\n def debugInt(i: Int) = i.toBinaryString.reverse.padTo(table.length, '0').reverse\n\n instructions foreach {instr =>\n instr match {\n case ('|', arg) =>\n for {\n i <- table.indices if arg.getBit(i) == 1\n } table(i) = arg.getBit(i)\n\n case ('&', arg) =>\n for {\n i <- table.indices if arg.getBit(i) == 0\n } table(i) = arg.getBit(i)\n\n case ('^', arg) =>\n for {\n i <- table.indices if table(i) != -1\n } table(i) ^= arg.getBit(i)\n }\n\n //debug(instr, debugInt(instr._2), debugTable())\n }\n\n var and = (1< and = and.clearBit(i)\n case (1, i) => or = or.setBit(i)\n case _ =>\n }\n\n //debug(debugTable(), debugInt(and), debugInt(or))\n\n val ans = Seq.empty[String] ++ when(or > 0)(s\"| $or\") ++ when(and < (1< Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _879C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val instructions = io.read[Seq[(Char, Int)]]\n\n val table = Array.fill(10)(-1)\n\n def debugTable() = table.map(i => if (i == -1) \"X\" else i.toString).mkString.reverse\n def debugInt(i: Int) = i.toBinaryString.reverse.padTo(table.length, '0').reverse\n\n instructions foreach {instr =>\n instr match {\n case ('|', arg) =>\n for {\n i <- table.indices if arg.getBit(i) == 1\n } table(i) = arg.getBit(i)\n\n case ('&', arg) =>\n for {\n i <- table.indices if arg.getBit(i) == 0\n } table(i) = arg.getBit(i)\n\n case ('^', arg) =>\n for {\n i <- table.indices if table(i) != -1\n } table(i) ^= arg.getBit(i)\n }\n\n debug(instr, debugInt(instr._2), debugTable())\n }\n\n var and = (1< and = and.clearBit(i)\n case (1, i) => or = or.setBit(i)\n case _ =>\n }\n\n debug(debugTable(), debugInt(and), debugInt(or))\n\n val ans = Seq.empty[String] ++ when(or > 0)(s\"| $or\") ++ when(and < (1< Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _879C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val instructions = io.read[Seq[(Char, Int)]]\n\n val n = 10\n\n var zeroes = 0\n var ones = 1< Int = instruction match {\n case ('|', arg) => _ | arg\n case ('&', arg) => _ & arg\n case ('^', arg) => _ ^ arg\n }\n\n instructions.map(toFunc).foreach({f =>\n zeroes = f(zeroes)\n ones = f(ones)\n })\n\n var xor = 0\n var or = 0\n var and = (1<\n (zeroes.getBit(i), ones.getBit(i)) match {\n case (0, 0) => and = and.clearBit(i)\n case (0, 1) =>\n case (1, 0) => xor = xor.setBit(i)\n case (1, 1) => or = or.setBit(i)\n }\n }\n\n val ans = Seq('&' -> and, '|' -> or, '^' -> xor)\n io.writeLine(ans.length).writeAll(ans.map({case (op, instr) => s\"$op $instr\"}), separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "19c32b8c1d3db5ab10aca271135aa9b8"} {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n var ans = 0\n for (i <- 0 until n) {\n for (j <- 0 until 2 * m by 2) {\n val fst = nextInt\n val snd = nextInt\n if (fst + snd >= 1) {\n ans += 1\n }\n }\n }\n out.println(ans)\n return 0\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val res = (1 to n).flatMap{_ =>\n in.next().split(' ').grouped(2).map{t =>\n t.head == \"1\" || t.last == \"1\"}}.count(_ == true)\n println(res)\n\n}\n"}, {"source_code": "object A595 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val in = Array.fill(n)(readInts(2*m))\n println(in.map{arr => arr.grouped(2).count{a => a(0) == 1 || a(1) == 1}}.sum)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val ss = Array.fill(n){ readInts(2 * m) }\n \n var cnt = 0\n\n for (s <- ss) {\n for (i <- 0 until m) {\n if (s(2 * i) + s(2 * i + 1) > 0) cnt += 1\n }\n }\n\n println(cnt)\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._\nimport scala.math.Ordering.Implicits._\n\nobject _595A extends CodeForcesApp {\n override type Result = Int\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val (n, m) = (nextInt(), nextInt())\n var ans = 0\n repeat(n * m) {\n val (a, b) = (nextInt(), nextInt())\n if (((a | b) & 1) == 1) {\n ans += 1\n }\n }\n ans\n }\n\n def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n\n override def format(result: Result) = super.format(result)\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}, {"source_code": "object Main{\n def main (args: Array[String]){\n val Array(n, m) = io.StdIn.readLine.split(' ').map(_.toInt)\n var ans = 0\n for(i <- 1 to n){\n val al = io.StdIn.readLine.split(' ').map(_.toInt).toList\n ans += test(al)\n }\n println(ans)\n }\n\n def test(al: List[Int]): Int = al match{\n case Nil | (_ :: Nil) => 0\n case x :: y :: l1 =>\n if(x+y == 0) test(l1)\n else 1 + test(l1)\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject A_330 {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n val n = line1.nextToken().toInt //floor\n val m = line1.nextToken().toInt //window\n\n var result = 0\n for (i <- 0 until n) {\n val line = new StringTokenizer(br.readLine(), \" \")\n for (j <- 1 to m) {\n val w1 = line.nextToken().toInt\n val w2 = line.nextToken().toInt\n if (w1 == 1 || w2 == 1) {\n result += 1\n }\n }\n }\n //---------------------------- parameters reading end --------------------------------\n \n println(result)\n \n \n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n private def readInts(): Array[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n\n def main(args: Array[String]) {\n val Array(n, m) = readInts()\n val sum = (0 until n).map(s => {\n val w = readInts()\n val e = w.zipWithIndex.filter(_._2 % 2 == 0).map(_._1)\n val o = w.zipWithIndex.filter(_._2 % 2 == 1).map(_._1)\n e.zip(o).count(s => s._1 == 1 || s._2 == 1)\n }).sum\n println(sum)\n }\n}\n"}, {"source_code": "object CF595A extends App{\n val Array(n,m) = readLine.split(\" \").map(_.toInt)\n print((for(i <- 1 to n) yield (readLine.split(\" \").sliding(2,2).count(a => a(0)==\"1\" || a(1) ==\"1\"))).sum)\n}\n"}, {"source_code": "object Main extends App {\n val Array(n,m) = readLine().split(\" \").map(_.toInt)\n\tvar s = 0\n\tfor(i <- 1 to n ) {\n\t var r = readLine().split(\" \").map(_.toInt)\n\t\tval t = for(j <- 0 until r.length by 2) yield { Math.max(r(j) , r(j+1)) }\n\t\ts += t.sum\n\t}\n\tprintln(s)\n}\n"}], "negative_code": [], "src_uid": "5b9aed235094de7de36247a3b2a34e0f"} {"source_code": "import java.io.FileInputStream\nimport scala.io.StdIn\n\nobject ProblemA extends App {\n // Console.withIn(new FileInputStream(\"inputs/test01.in\")) {\n val n = StdIn.readLine().trim.toInt\n val p = -1 +: StdIn.readLine().trim.split(\"\\\\s+\").map(_.toInt - 1)\n var a = List.empty[Int]\n var f = n - 1\n while (f != 0) {\n a ::= f\n f = p(f)\n }\n a ::= 0\n println(a.map(_ + 1).mkString(\" \"))\n // }\n}\n", "positive_code": [{"source_code": "import java.io.PrintWriter\nimport java.util\nimport java.util.Scanner\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val pw = new PrintWriter(System.out)\n\n val n = sc.nextInt()\n\n val p = new Array[Int](n + 1)\n\n val g = new Array[util.ArrayList[Int]](n + 1)\n\n for (i <- 2 to n) {\n p.update(i, sc.nextInt())\n var gg = g.apply(p.apply(i))\n if (gg == null) {\n gg = new util.ArrayList[Int]\n }\n gg.add(i)\n }\n\n var result = Vector[Int]()\n\n var cur = n\n\n while (cur != 1) {\n result = cur +: result\n cur = p.apply(cur)\n }\n\n result = 1 +: result\n\n result.foreach(f => {\n pw.print(f + \" \")\n })\n\n sc.close()\n pw.close()\n }\n}\n"}], "negative_code": [], "src_uid": "e25efe1020ae64d55b3257ba457f809d"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n\n def go(symbol: Int, number: Int, i: Int, j: Int, prevI: Int, prevJ: Int, data: Array[Array[Int]]): Boolean = {\n if (i < 0 || j < 0 || i >= data.length || j >= data.head.length)\n false\n else if (data(i)(j) == number) true\n else if (data(i)(j) == symbol) {\n data(i)(j) = number\n ((i + 1 != prevI || j != prevJ) && go(symbol, number, i + 1, j, i, j, data)) ||\n ((i != prevI || j + 1 != prevJ) && go(symbol, number, i, j + 1, i, j, data)) ||\n ((i - 1 != prevI || j != prevJ) && go(symbol, number, i - 1, j, i, j, data)) ||\n ((i != prevI || j - 1 != prevJ) && go(symbol, number, i, j - 1, i, j, data))\n } else\n false\n }\n\n def solveIndex(line: Int, column: Int, data: Array[Array[Int]]) = {\n val symbol = data(line)(column)\n val number = - (line * data.head.length + column + 1)\n if (symbol < 0)\n false\n else {\n go(symbol: Int, number: Int, line, column, line, column, data)\n }\n }\n\n def solve(data: Array[Array[Int]]): Boolean = {\n data.indices.exists{ line =>\n data.head.indices.exists(column => solveIndex(line, column, data))\n }\n }\n\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val data = (1 to n).map(_ => in.next().map(_.toInt).toArray).toArray\n if (solve(data))\n println(\"Yes\")\n else\n println(\"No\")\n}", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n\n def go(symbol: Int, number: Int, i: Int, j: Int, prevI: Int, prevJ: Int, data: Array[Array[Int]]): Boolean = {\n if (i < 0 || j < 0 || i >= data.length || j >= data.head.length)\n false\n else if (data(i)(j) == number) true\n else if (data(i)(j) == symbol) {\n data(i)(j) = number\n ((i + 1 != prevI || j != prevJ) && go(symbol, number, i + 1, j, i, j, data)) ||\n ((i != prevI || j + 1 != prevJ) && go(symbol, number, i, j + 1, i, j, data)) ||\n ((i - 1 != prevI || j != prevJ) && go(symbol, number, i - 1, j, i, j, data)) ||\n ((i != prevI || j - 1 != prevJ) && go(symbol, number, i, j - 1, i, j, data))\n } else\n false\n }\n\n def solveIndex(line: Int, column: Int, data: Array[Array[Int]]) = {\n val symbol = data(line)(column)\n val number = - (line * data.head.length + column + 1)\n if (symbol < 0)\n false\n else {\n go(symbol: Int, number: Int, line, column, line, column, data)\n }\n }\n\n def solve(data: Array[Array[Int]]): Boolean = {\n data.indices.exists{ line =>\n data.head.indices.exists(column => solveIndex(line, column, data))\n }\n }\n\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val data = (1 to n).map(_ => in.next().map(_.toInt).toArray).toArray\n if (solve(data))\n println(\"Yes\")\n else\n println(\"No\")\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable._\n\n/**\n * @author Mehdi Maick\n */\nobject Main {\n\n def solve(in: InputReader): Unit = {\n val n = in.next.toInt\n val m = in.next.toInt\n var grid: Array[Array[Char]] = new Array[Array[Char]](n)\n (0 until n).foreach((i) => grid(i) = in.next.toCharArray)\n var hasCycle = false\n var visited: Array[Array[Boolean]] = null\n\n def fill(): Array[Array[Boolean]] = {\n var ret = new Array[Array[Boolean]](n)\n (0 until n).foreach((i) => ret(i) = new Array[Boolean](m))\n ret\n }\n\n var dx = Array(1, -1, 0, 0)\n var dy = Array(0, 0, 1, -1)\n\n def dfs(x: Int, y: Int, parentX: Int, parentY: Int, c: Char, cycleCount: Int): Boolean = {\n if (visited(x)(y)) {\n if(cycleCount >= 4){\n println(\"Yes\")\n System.exit(0)\n }\n return false\n }\n visited(x)(y) = true\n var ans = false\n for (i <- 0 until 4) {\n val xx = x + dx(i)\n val yy = y + dy(i)\n if (xx >= 0 && yy >= 0 && xx < n && ((parentX, parentY) != (xx, yy)) && yy < m && grid(xx)(yy) == c) {\n ans |= dfs(xx, yy, x, y, c, cycleCount + 1)\n }\n }\n return ans\n }\n\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n visited = fill\n hasCycle |= dfs(i, j, -1, -1, grid(i)(j), 0)\n if(hasCycle){\n\n }\n }\n }\n println(if (hasCycle) \"Yes\" else \"No\")\n }\n\n def main(args: Array[String]): Unit = {\n val in = new InputReader\n solve(in)\n }\n\n class InputReader() {\n var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var st: StringTokenizer = null\n\n def next(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine)\n return st.nextToken\n }\n st.nextToken\n }\n\n def nextLine(): String = in.readLine\n }\n\n}\n"}, {"source_code": "import scala.io.Source \n\nobject Solution extends App { \n\ndef go(symbol: Int, number: Int, i: Int, j: Int, prevI: Int, prevJ: Int, data: Array[Array[Int]]): Boolean = { \nif (i < 0 || j < 0 || i >= data.length || j >= data.head.length) \nfalse \nelse if (data(i)(j) == number) true \nelse if (data(i)(j) == symbol) { \ndata(i)(j) = number \n((i + 1 != prevI || j != prevJ) && go(symbol, number, i + 1, j, i, j, data)) || \n((i != prevI || j + 1 != prevJ) && go(symbol, number, i, j + 1, i, j, data)) || \n((i - 1 != prevI || j != prevJ) && go(symbol, number, i - 1, j, i, j, data)) || \n((i != prevI || j - 1 != prevJ) && go(symbol, number, i, j - 1, i, j, data)) \n} else \nfalse \n} \n\ndef solveIndex(line: Int, column: Int, data: Array[Array[Int]]) = { \nval symbol = data(line)(column) \nval number = - (line * data.head.length + column + 1) \nif (symbol < 0) \nfalse \nelse { \ngo(symbol: Int, number: Int, line, column, line, column, data) \n} \n} \n\ndef solve(data: Array[Array[Int]]): Boolean = { \ndata.indices.exists{ line => \ndata.head.indices.exists(column => solveIndex(line, column, data)) \n} \n} \n\nval in = Source.stdin.getLines() \nval Array(n, m) = in.next().split(' ').map(_.toInt) \nval data = (1 to n).map(_ => in.next().map(_.toInt).toArray).toArray \nif (solve(data)) \nprintln(\"Yes\") \nelse \nprintln(\"No\") \n}"}, {"source_code": "import collection.mutable.Set\nimport collection.mutable.Queue\n\nobject Main extends App {\n val Array(n,m) = readLine.split(\" \").map(_.toInt)\n\n val land = (1 to n) map { _ => readLine.trim }\n \n val dirs = List((0,1), (1,0), (-1,0), (0,-1))\n\n def eqColor(color: Char)(pos: (Int, Int)): List[(Int, Int)] = pos match {\n case (x, y) =>\n if(x >= 0 && x < n && y >= 0 && y < m && land(x)(y) == color) List(pos)\n else List()\n }\n\n def steps(node: (Int, Int)): List[(Int, Int)] = node match {\n case (x, y) =>\n val color = land(x)(y)\n dirs map { case (dx, dy) => (x+dx, y+dy) } flatMap eqColor(color)\n }\n\n val white = Set((for {\n i <- 0 to n-1\n j <- 0 to m-1\n } yield (i, j)): _*)\n val gray = Set[(Int, Int)]()\n val black = Set[(Int, Int)]()\n\n def dfs(prev: (Int, Int), node: (Int, Int)): Unit = {\n white.remove(node)\n gray.add(node)\n steps(node) foreach { k =>\n if(k != prev) {\n if(gray.contains(k)) {\n println(\"Yes\")\n System.exit(0)\n }\n\n if(!black.contains(k)) dfs(node, k)\n }\n }\n gray.remove(node)\n black.add(node)\n }\n\n while(white.size > 0) {\n dfs((-1,-1), white.head)\n }\n\n println(\"No\")\n}"}, {"source_code": "import scala.io.Source \n\nobject Solution extends App { \n\ndef go(symbol: Int, number: Int, i: Int, j: Int, prevI: Int, prevJ: Int, data: Array[Array[Int]]): Boolean = { \nif (i < 0 || j < 0 || i >= data.length || j >= data.head.length) \nfalse \nelse if (data(i)(j) == number) true \nelse if (data(i)(j) == symbol) { \ndata(i)(j) = number \n((i + 1 != prevI || j != prevJ) && go(symbol, number, i + 1, j, i, j, data)) || \n((i != prevI || j + 1 != prevJ) && go(symbol, number, i, j + 1, i, j, data)) || \n((i - 1 != prevI || j != prevJ) && go(symbol, number, i - 1, j, i, j, data)) || \n((i != prevI || j - 1 != prevJ) && go(symbol, number, i, j - 1, i, j, data)) \n} else \nfalse \n} \n\ndef solveIndex(line: Int, column: Int, data: Array[Array[Int]]) = { \nval symbol = data(line)(column) \nval number = - (line * data.head.length + column + 1) \nif (symbol < 0) \nfalse \nelse { \ngo(symbol: Int, number: Int, line, column, line, column, data) \n} \n} \n\ndef solve(data: Array[Array[Int]]): Boolean = { \ndata.indices.exists{ line => \ndata.head.indices.exists(column => solveIndex(line, column, data)) \n} \n} \n\nval in = Source.stdin.getLines() \nval Array(n, m) = in.next().split(' ').map(_.toInt) \nval data = (1 to n).map(_ => in.next().map(_.toInt).toArray).toArray \nif (solve(data)) \nprintln(\"Yes\") \nelse \nprintln(\"No\") \n}"}, {"source_code": "import scala.io.Source \n\nobject Solution extends App { \n\ndef go(symbol: Int, number: Int, i: Int, j: Int, prevI: Int, prevJ: Int, data: Array[Array[Int]]): Boolean = { \nif (i < 0 || j < 0 || i >= data.length || j >= data.head.length) \nfalse \nelse if (data(i)(j) == number) true \nelse if (data(i)(j) == symbol) { \ndata(i)(j) = number \n((i + 1 != prevI || j != prevJ) && go(symbol, number, i + 1, j, i, j, data)) || \n((i != prevI || j + 1 != prevJ) && go(symbol, number, i, j + 1, i, j, data)) || \n((i - 1 != prevI || j != prevJ) && go(symbol, number, i - 1, j, i, j, data)) || \n((i != prevI || j - 1 != prevJ) && go(symbol, number, i, j - 1, i, j, data)) \n} else \nfalse \n} \n\ndef solveIndex(line: Int, column: Int, data: Array[Array[Int]]) = { \nval symbol = data(line)(column) \nval number = - (line * data.head.length + column + 1) \nif (symbol < 0) \nfalse \nelse { \ngo(symbol: Int, number: Int, line, column, line, column, data) \n} \n} \n\ndef solve(data: Array[Array[Int]]): Boolean = { \ndata.indices.exists{ line => \ndata.head.indices.exists(column => solveIndex(line, column, data)) \n} \n} \n\nval in = Source.stdin.getLines() \nval Array(n, m) = in.next().split(' ').map(_.toInt) \nval data = (1 to n).map(_ => in.next().map(_.toInt).toArray).toArray \nif (solve(data)) \nprintln(\"Yes\") \nelse \nprintln(\"No\") \n}"}, {"source_code": "import collection.mutable.Set\nimport collection.mutable.Queue\n\nobject Main extends App {\n val Array(n,m) = readLine.split(\" \").map(_.toInt)\n\n val land = (1 to n) map { _ => readLine.trim }\n \n val dirs = List((0,1), (1,0), (-1,0), (0,-1))\n\n def eqColor(color: Char)(pos: (Int, Int)): List[(Int, Int)] = pos match {\n case (x, y) =>\n if(x >= 0 && x < n && y >= 0 && y < m && land(x)(y) == color) List(pos)\n else List()\n }\n\n def steps(node: (Int, Int)): List[(Int, Int)] = node match {\n case (x, y) =>\n val color = land(x)(y)\n dirs map { case (dx, dy) => (x+dx, y+dy) } flatMap eqColor(color)\n }\n\n val white = Set((for {\n i <- 0 to n-1\n j <- 0 to m-1\n } yield (i, j)): _*)\n val gray = Set[(Int, Int)]()\n val black = Set[(Int, Int)]()\n\n def dfs(prev: (Int, Int), node: (Int, Int)): Unit = {\n white.remove(node)\n gray.add(node)\n steps(node) foreach { k =>\n if(k != prev) {\n if(gray.contains(k)) {\n println(\"Yes\")\n System.exit(0)\n }\n\n if(!black.contains(k)) dfs(node, k)\n }\n }\n gray.remove(node)\n black.add(node)\n }\n\n while(white.size > 0) {\n dfs((-1,-1), white.head)\n }\n\n println(\"No\")\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n\n def go(symbol: Int, number: Int, i: Int, j: Int, prevI: Int, prevJ: Int, data: Array[Array[Int]]): Boolean = {\n if (i < 0 || j < 0 || i >= data.length || j >= data.head.length)\n false\n else if (data(i)(j) == number) true\n else if (data(i)(j) == symbol) {\n data(i)(j) = number\n ((i + 1 != prevI || j != prevJ) && go(symbol, number, i + 1, j, i, j, data)) ||\n ((i != prevI || j + 1 != prevJ) && go(symbol, number, i, j + 1, i, j, data)) ||\n ((i - 1 != prevI || j != prevJ) && go(symbol, number, i - 1, j, i, j, data)) ||\n ((i != prevI || j - 1 != prevJ) && go(symbol, number, i, j - 1, i, j, data))\n } else\n false\n }\n\n def solveIndex(line: Int, column: Int, data: Array[Array[Int]]) = {\n val symbol = data(line)(column)\n val number = - (line * data.head.length + column + 1)\n if (symbol < 0)\n false\n else {\n go(symbol: Int, number: Int, line, column, line, column, data)\n }\n }\n\n def solve(data: Array[Array[Int]]): Boolean = {\n data.indices.exists{ line =>\n data.head.indices.exists(column => solveIndex(line, column, data))\n }\n }\n\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val data = (1 to n).map(_ => in.next().map(_.toInt).toArray).toArray\n if (solve(data))\n println(\"Yes\")\n else\n println(\"No\")\n}"}, {"source_code": "\nimport scala.math._\nimport scala.util.control.Breaks\n\nobject Problem extends App {\n import Scanner._\n\n val n, m = readInt\n\n val game = Array.fill(n)(readString.toArray)\n val visited = Array.ofDim[Boolean](n, m)\n def hasCycle(x: Int, y: Int, lx: Int, ly: Int): Boolean = {\n if(x < 0 || x >= n || y < 0 || y >= m || game(x)(y) != game(lx)(ly))\n return false\n if(!visited(x)(y)) {\n visited(x)(y) = true\n\n if(x != lx+1 && hasCycle(x-1, y, x, y))\n return true\n if(x != lx-1 && hasCycle(x+1, y, x, y))\n return true\n if(y != ly+1 && hasCycle(x, y-1, x, y))\n return true\n if(y != ly-1 && hasCycle(x, y+1, x, y))\n return true\n false\n } else true\n }\n\n for(x <- 0 until n; y <- 0 until m; if !visited(x)(y)) {\n if(hasCycle(x, y, x, y)) {\n println(\"Yes\")\n System.exit(0)\n }\n }\n println(\"No\")\n\n /*\n * val names = Array.fill(readInt)(readString)\n val order = List[Char]()\n\n for(name <- names) {\n val c = name(0)\n }\n */\n}\n\ncase class Memo[A, B](f: A => B, size: Int = 10) extends (A => B) {\n private val cache = new scala.collection.mutable.HashMap[A, B] {\n override def initialSize = size\n }\n def apply(x: A) = cache getOrElseUpdate (x, f(x))\n}\n\nobject Scanner {\n def readInt() = {\n var acc = 0\n readWith {\n case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n }\n acc\n }\n def readLong() = {\n var acc = 0L\n readWith {\n case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10L) + (c - '0')\n }\n acc\n }\n def readDouble() = {\n var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)\n readWith {\n case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>\n frac = (frac * 10) + (c - '0')\n fracPow *= 10\n case c if c == '.' && !readFrac =>\n readFrac = true\n }\n acc + (frac.toDouble / fracPow)\n }\n def readString() = {\n var string = new StringBuilder\n readWith { case c => string += c }\n string\n }\n def readLine() = Console.in.readLine()\n def readChar() = Console.in.read().toChar\n def readWith(func: PartialFunction[Char, Unit]) {\n val handler = func orElse[Char, Unit] {\n case _ => throw new java.io.IOException(\"unexpected token\")\n }\n\n var c = readChar\n while(c.isWhitespace)\n c = readChar\n\n while(!c.isWhitespace) {\n handler(c)\n\n c = readChar\n }\n }\n}\n\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 04 Aug 2016\n */\nobject B510 extends App {\n\n // 0 - left\n // 1 - down\n // 2 - up\n // 3 - right\n def recursiveFoo(row: Int, col: Int, mainSymbol: Char, field: Array[Array[Char]],\n mask: Array[Array[Boolean]], n: Int, m: Int, movement: Int): Boolean = {\n if (mask(row)(col)) {\n return true\n }\n mask(row)(col) = true\n var b = false\n if (row + 1 < n && field(row + 1)(col) == mainSymbol && movement != 2) {\n b |= recursiveFoo(row + 1, col, mainSymbol, field, mask, n, m, 1)\n }\n if (row - 1 >= 0 && field(row - 1)(col) == mainSymbol && movement != 1) {\n b |= recursiveFoo(row - 1, col, mainSymbol, field, mask, n, m, 2)\n }\n if (col + 1 < m && field(row)(col + 1) == mainSymbol && movement != 0) {\n b |= recursiveFoo(row, col + 1, mainSymbol, field, mask, n, m, 3)\n }\n if (col - 1 >= 0 && field(row)(col - 1) == mainSymbol && movement != 3) {\n b |= recursiveFoo(row, col - 1, mainSymbol, field, mask, n, m, 0)\n }\n return b\n }\n\n def runFoo(row: Int, col: Int, field: Array[Array[Char]], mask: Array[Array[Boolean]], n: Int, m: Int): Boolean = {\n recursiveFoo(row, col, field(row)(col), field, mask, n, m, 1)\n }\n\n def solve() = {\n val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val field: Array[Array[Char]] = Array.ofDim[Char](n, m)\n for (i <- 0 until n) {\n field(i) = scala.io.StdIn.readLine().toCharArray\n }\n if (foo(n, m, field)) {\n println(\"Yes\")\n } else {\n println(\"No\")\n }\n }\n\n def foo(n: Int, m: Int, field: Array[Array[Char]]): Boolean = {\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n val mask: Array[Array[Boolean]] = Array.ofDim[Boolean](n, m)\n if (runFoo(i, j, field, mask, n, m))\n return true\n }\n }\n\n false\n }\n\n solve()\n\n}\n"}], "negative_code": [{"source_code": "\nimport scala.math._\nimport scala.util.control.Breaks\n\nobject Problem extends App {\n import Scanner._\n\n val n, m = readInt\n\n val game = Array.fill(n)(readString.toArray)\n val path = Array.ofDim[Boolean](n, m)\n val visited = Array.ofDim[Boolean](n, m)\n def hasCycle(x: Int, y: Int, last: Char): Boolean = {\n if(x < 0 || x >= n || y < 0 || y >= n)\n return false\n val c = game(x)(y)\n if(last != c)\n return false\n if(!path(x)(y)) {\n if(!visited(x)(y)) {\n visited(x)(y) = true\n path(x)(y) = true\n\n if(hasCycle(x+1, y, c) || hasCycle(x-1, y, c) || hasCycle(x, y+1, c) || hasCycle(x, y-1, c))\n return true\n\n path(x)(y) = false\n }\n false\n } else true\n }\n\n for(x <- 0 until n; y <- 0 until m; if !visited(x)(y)) {\n if(hasCycle(x, y, game(x)(y))) {\n println(\"Yes\")\n System.exit(0)\n }\n }\n println(\"No\")\n\n /*\n * val names = Array.fill(readInt)(readString)\n val order = List[Char]()\n\n for(name <- names) {\n val c = name(0)\n }\n */\n}\n\ncase class Memo[A, B](f: A => B, size: Int = 10) extends (A => B) {\n private val cache = new scala.collection.mutable.HashMap[A, B] {\n override def initialSize = size\n }\n def apply(x: A) = cache getOrElseUpdate (x, f(x))\n}\n\nobject Scanner {\n def readInt() = {\n var acc = 0\n readWith {\n case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n }\n acc\n }\n def readLong() = {\n var acc = 0L\n readWith {\n case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10L) + (c - '0')\n }\n acc\n }\n def readDouble() = {\n var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)\n readWith {\n case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>\n frac = (frac * 10) + (c - '0')\n fracPow *= 10\n case c if c == '.' && !readFrac =>\n readFrac = true\n }\n acc + (frac.toDouble / fracPow)\n }\n def readString() = {\n var string = new StringBuilder\n readWith { case c => string += c }\n string\n }\n def readLine() = Console.in.readLine()\n def readChar() = Console.in.read().toChar\n def readWith(func: PartialFunction[Char, Unit]) {\n val handler = func orElse[Char, Unit] {\n case _ => throw new java.io.IOException(\"unexpected token\")\n }\n\n var c = readChar\n while(c.isWhitespace)\n c = readChar\n\n while(!c.isWhitespace) {\n handler(c)\n\n c = readChar\n }\n }\n}\n\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 04 Aug 2016\n */\nobject B510 extends App {\n\n // 0 - left\n // 1 - down\n // 2 - up\n // 3 - right\n def recursiveFoo(row: Int, col: Int, mainSymbol: Char, field: Array[Array[Char]],\n mask: Array[Array[Boolean]], n: Int, m: Int, movement: Int): Boolean = {\n if (mask(row)(col)) {\n return true\n }\n mask(row)(col) = true\n if (row + 1 < n && field(row + 1)(col) == mainSymbol && movement != 2) {\n recursiveFoo(row + 1, col, mainSymbol, field, mask, n, m, 1)\n } else if (row - 1 >= 0 && field(row - 1)(col) == mainSymbol && movement != 1) {\n recursiveFoo(row - 1, col, mainSymbol, field, mask, n, m, 2)\n } else if (col + 1 < m && field(row)(col + 1) == mainSymbol && movement != 0) {\n recursiveFoo(row, col + 1, mainSymbol, field, mask, n, m, 3)\n } else if (col - 1 >= 0 && field(row)(col - 1) == mainSymbol && movement != 3) {\n recursiveFoo(row, col - 1, mainSymbol, field, mask, n, m, 0)\n } else {\n return false\n }\n }\n\n def runFoo(row: Int, col: Int, field: Array[Array[Char]], mask: Array[Array[Boolean]], n: Int, m: Int): Boolean = {\n recursiveFoo(row, col, field(row)(col), field, mask, n, m, 1)\n }\n\n def solve() = {\n val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val field: Array[Array[Char]] = Array.ofDim[Char](n, m)\n for (i <- 0 until n) {\n field(i) = scala.io.StdIn.readLine().toCharArray\n }\n if (foo(n, m, field)) {\n println(\"Yes\")\n } else {\n println(\"No\")\n }\n }\n\n def foo(n: Int, m: Int, field: Array[Array[Char]]): Boolean = {\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n val mask: Array[Array[Boolean]] = Array.ofDim[Boolean](n, m)\n if (runFoo(i, j, field, mask, n, m))\n return true\n }\n }\n\n false\n }\n\n solve()\n\n}\n"}], "src_uid": "73930603e440eef854da4ba51253a5a7"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = (1 to n).map(_ => readLine())\n \n val e = a(0)\n val a1 = a.drop(1).map(_.zip(e))\n val a2 = a1.map(_.takeWhile(t => t._1 == t._2).size)\n val r = a2.min\n \n println(r)\n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val str = in.next()\n val r = (2 to n).foldLeft(str.toSeq) {\n case (s, _) => s.zip(in.next()).takeWhile(i => i._1 == i._2).map(_._1)\n }\n println(r.length)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject P172A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n sc.nextLine\n\n val res = List.fill(N)(sc.nextLine.toList).transpose.takeWhile(_.distinct.size == 1).size\n\n out.println(res)\n out.close\n}\n\n\n\n\n\n"}, {"source_code": "import java.io._\n\nobject Solution {\n def main(args: Array[String]) {\n val in = new BufferedReader(new InputStreamReader(System.in))\n val n = in.readLine().toInt\n def commonPrefix(s: String, t: String) = {\n var i = 0\n while(i < s.length && i < t.length && s(i) == t(i)) i = i + 1\n s.substring(0, i)\n }\n val x = (for(i <- 1 to n) yield in.readLine).reduceLeft(commonPrefix(_, _))\n println(x.length)\n }\n}"}], "negative_code": [], "src_uid": "081b35620952bd32ce6d8ddc756e5c9d"} {"source_code": "// codeforces 190B\n\nobject Okrushenie extends App {\n val t1 = (Console.readLine.split(\" \")) map (_.toInt)\n val t2 = (Console.readLine.split(\" \")) map (_.toInt)\n val (x0, y0, r0) = (t1(0), t1(1), t1(2))\n val (x1, y1, r1) = (t2(0), t2(1), t2(2))\n val dx = (x0.toDouble - x1.toDouble)\n val dy = (y0.toDouble - y1.toDouble)\n val d = Math.sqrt(dx*dx + dy*dy)\n if (d > r0+r1) println((d-r0-r1)/2)\n else {\n val rmx = Math.max(r0,r1)\n val rmn = Math.min(r0,r1)\n if (rmn + d >= rmx) println(0)\n else println((rmx - d - rmn) / 2)\n }\n}", "positive_code": [{"source_code": "object Solution {\n class Point(xin: Long, yin: Long) {\n val x = xin;\n val y = yin;\n }\n\n def sqr(x: Long): Long = x*x\n \n def sqrDist(p1: Point, p2: Point): Long = {\n return sqr(p1.x - p2.x) + sqr(p1.y - p2.y)\n }\n\n class Circle(centerin: Point, radiusin: Long) {\n val center = centerin;\n val radius = radiusin;\n\n def contains(p: Point): Boolean = sqrDist(p, center) <= sqr(radius)\n\n def intersects(other: Circle): Boolean = {\n sqr(radius) + 2*radius*other.radius + sqr(other.radius) >= sqrDist(center, other.center)\n }\n\n def contains(other: Circle): Boolean = {\n val d = math.sqrt(sqrDist(center, other.center))\n d + other.radius <= radius\n }\n }\n\n def readCircle(): Circle = {\n val tokens = readLine().split(\" \").map(_.toInt)\n new Circle(new Point(tokens(0), tokens(1)), tokens(2))\n }\n\n def solve(c1: Circle, c2: Circle): Double = {\n val d = math.sqrt(sqrDist(c1.center, c2.center))\n if (c1 contains c2) {\n c1.radius - (d + c2.radius)\n } else if (c2 contains c1) {\n c2.radius - (d + c1.radius)\n } else if (c1 intersects c2) {\n 0\n } else {\n d - (c1.radius + c2.radius)\n }\n }\n\n def main(args: Array[String]) {\n printf(\"%.12f\\n\", solve(readCircle(), readCircle()) / 2)\n }\n}\n"}], "negative_code": [{"source_code": "object Solution {\n class Point(xin: Long, yin: Long) {\n val x = xin;\n val y = yin;\n }\n\n def sqr(x: Long): Long = x*x\n \n def sqrDist(p1: Point, p2: Point): Long = {\n return sqr(p1.x - p2.x) + sqr(p1.y - p2.y)\n }\n\n class Circle(centerin: Point, radiusin: Long) {\n val center = centerin;\n val radius = radiusin;\n\n def contains(p: Point): Boolean = sqrDist(p, center) <= sqr(radius)\n\n def intersects(other: Circle): Boolean = {\n sqr(radius) + 2*radius*other.radius + sqr(other.radius) >= sqrDist(center, other.center)\n }\n\n def contains(other: Circle): Boolean = {\n val d = math.sqrt(sqrDist(center, other.center))\n d + other.radius <= radius\n }\n }\n\n def readCircle(): Circle = {\n val tokens = readLine().split(\" \").map(_.toInt)\n new Circle(new Point(tokens(0), tokens(1)), tokens(2))\n }\n\n def solve(c1: Circle, c2: Circle): Double = {\n val d = math.sqrt(sqrDist(c1.center, c2.center))\n if (c1 contains c2) {\n c1.radius - (d + c2.radius)\n } else if (c2 contains c1) {\n c2.radius - (d + c1.radius)\n } else if (c1 intersects c2) {\n c1.radius + c2.radius - d\n } else {\n d - (c1.radius + c2.radius)\n }\n }\n\n def main(args: Array[String]) {\n printf(\"%.12f\\n\", solve(readCircle(), readCircle()) / 2)\n }\n}\n"}], "src_uid": "8996ae454ba3062e47a8aaab7fb1e33b"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(var a: Int, var b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return (a).compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mapp = mutable.Map[pair, Int]()\n\n val t = readInt()\n\n for (tt <- 1 to t) {\n val n = readInt()\n val s = readString()\n if (n > 2) {\n writer.println(\"NO\")\n } else if (n == 1) {\n writer.println(\"YES\")\n } else {\n if (s(0) == s(1)) {\n writer.println(\"NO\")\n } else {\n writer.println(\"YES\")\n }\n }\n def check(kk: Long, fi: Long): Boolean = {\n return false\n }\n def bs(st:Long, en:Long, fi:Long): Long = {\n if (en - st <= 1L) {\n if (check(st, fi))\n return st\n else\n return en\n }\n val mid = (st + en) / 2L\n if (check(mid, fi))\n return bs(st, mid, fi)\n else\n return bs(mid, en, fi)\n }\n }\n writer.flush()\n}", "positive_code": [{"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val size = readInt()\n val string = readLine()\n val answer = size match {\n case 1 => \"YES\"\n case 2 => if (string(0) != string(1)) \"YES\" else \"NO\"\n case _ => \"NO\"\n }\n println(answer)\n }\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "object _1632AScala {\r\n import scala.io.StdIn.{readInt, readLine}\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt\r\n while(t > 0){\r\n t -= 1\r\n val n = readInt\r\n val ch = readLine.toCharArray\r\n if(n == 1)println(\"YES\")\r\n else if(n >= 3) println(\"NO\")\r\n else{\r\n if(ch(0) != ch(1))println(\"YES\")\r\n else println(\"NO\");\r\n }\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\r\nimport scala.io.Source\r\n\r\nobject Main extends App {\r\n val input = Source.fromInputStream(System.in).getLines()\r\n val n = input.next().toInt\r\n val res = new ArrayBuffer[String](n)\r\n for (i <- 0 until n) {\r\n val ls = input.next().toInt\r\n val s = input.next()\r\n if (ls == 1 || \"01\".equals(s) || \"10\".equals(s)) res.append(\"YES\")\r\n else res.append(\"NO\")\r\n }\r\n res.foreach(println)\r\n}\r\n"}], "negative_code": [{"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val size = readInt()\n val string = readLine()\n val answer = if (size < 3) \"YES\" else \"NO\"\n println(answer)\n }\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}], "src_uid": "354658f565e265c2a1ce37355d6466e1"} {"source_code": "object A extends App {\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n def isSorted: Boolean = (0 until (n - 1)).forall(i => an(i) <= an(i + 1))\r\n\r\n @annotation.tailrec\r\n def go(i: Int): Int =\r\n if (isSorted) i\r\n else {\r\n ((i % 2) until (n - 1, 2)).foreach {\r\n case i if an(i) > an(i + 1) =>\r\n val ai = an(i)\r\n an(i) = an(i + 1)\r\n an(i + 1) = ai\r\n case _ =>\r\n }\r\n go(i + 1)\r\n }\r\n\r\n println(go(0))\r\n }\r\n\r\n}\r\n", "positive_code": [{"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n val count = {\r\n @annotation.tailrec\r\n def go(i: Int): Int =\r\n if (an.isSorted) i\r\n else {\r\n ((i % 2) until (n - 1, 2)).foreach {\r\n case i if an(i) > an(i + 1) => an.swap(i, i + 1)\r\n case _ =>\r\n }\r\n go(i + 1)\r\n }\r\n go(0)\r\n }\r\n\r\n println(count)\r\n }\r\n\r\n implicit final class ArrayOps[T](private val xs: Array[T]) extends AnyVal {\r\n def swap(i: Int, j: Int): Unit = {\r\n val xi = xs(i)\r\n xs(i) = xs(j)\r\n xs(j) = xi\r\n }\r\n\r\n def isSorted(implicit ord: Ordering[T]): Boolean =\r\n (0 until (xs.length - 1)).forall(i => ord.lteq(xs(i), xs(i + 1)))\r\n }\r\n\r\n}\r\n"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val writer = new PrintWriter(System.out)\r\n val reader = new BufferedReader(new InputStreamReader(System.in))\r\n var st = new StringTokenizer(\"\")\r\n def next(): String = {\r\n while (!st.hasMoreTokens) {\r\n st = new StringTokenizer(reader.readLine())\r\n }\r\n st.nextToken()\r\n }\r\n\r\n def readInt() = next.toInt\r\n def readLong() = next.toLong\r\n def readString() = next()\r\n def readArrayInt(n: Int = 0): Array[Int] = {\r\n if (n == 0)\r\n return reader.readLine().split(\" \").map(_.toInt)\r\n\r\n val a = new Array[Int](n)\r\n for (i <- 0 until n) {\r\n a(i) = readInt()\r\n }\r\n a\r\n }\r\n\r\n def pow(a: Int, b: Int): Long = {\r\n if (b == 0) return 1\r\n\r\n val rs = pow(a, b / 2)\r\n rs * rs * (if (b % 2 == 0) 1 else a)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b\r\n\r\n def root(u: Int, p: Array[Int]): Int = {\r\n if (p(u) < 0) return u\r\n p(u) = root(p(u), p)\r\n p(u)\r\n }\r\n\r\n def join(u: Int, v: Int, p: Array[Int]): Unit = {\r\n var x = root(u, p)\r\n var y = root(v, p)\r\n if (x == y) return\r\n\r\n if (p(y) < p(x)) {\r\n val t = x\r\n x = y\r\n y = t\r\n }\r\n p(x) += p(y)\r\n p(y) = x\r\n }\r\n\r\n def solve(t: Int = 0): Unit = {\r\n val n = readInt()\r\n val a = readArrayInt(n)\r\n\r\n var c = 0\r\n while ({\r\n var i = 0\r\n while (i < n && a(i) == i + 1) i +=1\r\n i != n\r\n }) {\r\n c += 1\r\n if (c % 2 > 0) {\r\n for (i <- 0 until n - 1 by 2 if a(i) > a(i + 1)) {\r\n val k = a(i)\r\n a(i) = a(i + 1)\r\n a(i + 1) = k\r\n }\r\n } else {\r\n for (i <- 1 until n - 1 by 2 if a(i) > a(i + 1)) {\r\n var k = a(i)\r\n a(i) = a(i + 1)\r\n a(i + 1) = k\r\n }\r\n }\r\n }\r\n\r\n writer.println(c)\r\n }\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def main(args: Array[String]) {\r\n multiTest(solve)\r\n //solve()\r\n writer.flush()\r\n }\r\n}"}], "negative_code": [{"source_code": "object A extends App {\r\n\r\n def count: Seq[Int] => Int = _.zipWithIndex.sorted.zipWithIndex.foldLeft(0) {\r\n case (c, ((_, i), j)) if i == j => c\r\n case (c, ((_, i), j)) => c max (math.abs(i - j) + (i + 1) % 2)\r\n }\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n println(count(an))\r\n }\r\n\r\n}\r\n"}], "src_uid": "d4bcc53b470e4beaa078d5ce3785c6cb"} {"source_code": "object _633C extends CodeForcesApp {\n override type Result = Seq[String]\n\n override def solve(read: InputReader) = {\n val (n, text, words) = read[(Int, String, IndexedSeq[String])]\n val cipher = words.map(_.toLowerCase.reverse).zipWithIndex\n\n type Ans = Option[List[Int]]\n\n lazy val solve: Int ==> Ans = Memo {\n case `n` => Some(Nil)\n case i =>\n cipher.view collect {\n case (w, j) if text.startsWith(w, i) => solve(i + w.length).map(j :: _)\n } collectFirst {\n case Some(x) => x\n }\n }\n\n solve(0).get.map(words)\n }\n\n case class Memo[I, K, O](f: I => O)(implicit encoder: I => K) extends (I => O) {\n import scala.collection.mutable.{Map => Dict}\n val cache = Dict.empty[K, O]\n override def apply(x: I) = cache getOrElseUpdate (x, f(x))\n }\n\n type ==>[I, O] = Memo[I, I, O]\n\n override def format(result: Result) = result mkString \" \"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n", "positive_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _633C extends CodeForcesApp {\n override type Result = Seq[String]\n\n override def solve(read: InputReader) = {\n val n = read[Int]\n val text = read[String]\n val words = read[IndexedSeq[String]]\n val dict = words.map(_.toLowerCase.reverse).zipWithIndex\n type Ans = Option[List[Int]]\n val cache = scala.collection.mutable.Map.empty[Int, Ans]\n\n def solve(i: Int): Ans = cache.getOrElseUpdate(i, {\n i match {\n case `n` => Some(Nil)\n case _ =>\n val f = Function.unlift(isOkay(i))\n dict collectFirst f\n }\n })\n\n def isOkay(offset: Int): ((String, Int)) => Ans = {case (w, i) =>\n if(text.startsWith(w, offset)) {\n solve(offset + w.length).map(i :: _)\n } else {\n None\n }\n }\n\n solve(0).get.map(words)\n }\n\n override def format(result: Result) = result mkString \" \"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}, {"source_code": "object _633C extends CodeForcesApp {\n override type Result = Seq[String]\n\n override def solve(read: InputReader) = {\n val (n, text, words) = read[(Int, String, IndexedSeq[String])]\n val cipher = words.map(_.toLowerCase.reverse).zipWithIndex\n\n type Ans = Option[List[Int]]\n\n lazy val solve: Int ==> Ans = Memo {\n case `n` => Some(Nil)\n case i =>\n val f = Function.unlift(isOkay(i))\n cipher collectFirst f\n }\n\n def isOkay(offset: Int): ((String, Int)) => Ans = {case (w, i) =>\n if(text.startsWith(w, offset)) solve(offset + w.length).map(i :: _) else None\n }\n\n solve(0).get.map(words)\n }\n\n case class Memo[I, K, O](f: I => O)(implicit encoder: I => K) extends (I => O) {\n import scala.collection.mutable.{Map => Dict}\n val cache = Dict.empty[K, O]\n override def apply(x: I) = cache getOrElseUpdate (x, f(x))\n }\n\n type ==>[I, O] = Memo[I, I, O]\n\n override def format(result: Result) = result mkString \" \"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _633C extends CodeForcesApp {\n override def solve(in: InputReader, out: OutputWriter) = {\n val (n, text, words) = in[(Int, String, IndexedSeq[String])]\n val cipher = words.map(_.toLowerCase.reverse).zipWithIndex\n\n lazy val solve: Int => Option[List[Int]] = memoize {\n case `n` => Some(Nil)\n case i => cipher collectFirstDefined {\n case (w, j) if text.startsWith(w, i) => solve(i + w.length).map(j :: _)\n }\n }\n out ++= solve(0).get.map(words)\n }\n\n def memoize[A] = new {\n def apply[B](f: A => B): (A => B) = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n }\n\n implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {\n def collectFirstDefined[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def solve(in: InputReader, out: OutputWriter): Unit\n def main(args: Array[String]): Unit = {\n val (in, out) = (new InputReader(System.in), new OutputWriter(System.out))\n solve(in, out)\n in.close()\n out.close()\n }\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int, offset: Int = 0)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for (i <- 0 until n + offset) builder += (if (i < offset) null.asInstanceOf[A] else apply[A])\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\n\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n\nclass OutputWriter(out: PrintWriter) extends AutoCloseable {\n def this(out: OutputStream) = this(new PrintWriter(out))\n\n var separator = \" \"\n private[this] var isNewLine: Boolean = true\n\n def +=(obj: Any): this.type = {\n if (isNewLine) isNewLine = false else out.print(separator)\n out.print(obj)\n this\n }\n\n def newLine(): this.type = {\n isNewLine = true\n out.println()\n this\n }\n\n def ++=(obj: Traversable[_], ifEmpty: => Any = \"\"): this.type = {\n var c = 0\n obj foreach {i =>\n this += i\n c += 1\n }\n if (c == 0) this += ifEmpty else this\n }\n\n def append(obj: Any*): this.type = this ++= obj\n\n override def close() = {\n out.flush()\n out.close()\n }\n}\n"}], "negative_code": [{"source_code": "import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _633C extends CodeForcesApp {\n override def solve(in: InputReader, out: OutputWriter) = {\n val (n, text, words) = in[(Int, String, IndexedSeq[String])]\n val cipher = words.map(_.toLowerCase.reverse).zipWithIndex\n\n lazy val solve: Int => Option[List[Int]] = memoize {\n case `n` => Some(Nil)\n case i => cipher collectFirstDefined {\n case (w, j) if text.startsWith(w, i) => solve(i + w.length).map(j :: _)\n }\n }\n out ++= solve(0).get.map(words)\n }\n\n def memoize[A] = new {\n def apply[B](f: A => B): (A => B) = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n }\n\n implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {\n def collectFirstDefined[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def solve(in: InputReader, out: OutputWriter): Unit\n def main(args: Array[String]): Unit = {\n solve(new InputReader(System.in), new OutputWriter(System.out))\n }\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int, offset: Int = 0)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for (i <- 0 until n + offset) builder += (if (i < offset) null.asInstanceOf[A] else apply[A])\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\n\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n\nclass OutputWriter(out: PrintWriter) extends AutoCloseable {\n def this(out: OutputStream) = this(new PrintWriter(out))\n\n var separator = \" \"\n private[this] var isNewLine: Boolean = true\n\n def +=(obj: Any): this.type = {\n if (isNewLine) isNewLine = false else out.print(separator)\n out.print(obj)\n this\n }\n\n def newLine(): this.type = {\n isNewLine = true\n out.println()\n this\n }\n\n def ++=(obj: Traversable[_], ifEmpty: => Any = \"\"): this.type = {\n var c = 0\n obj foreach {i =>\n this += i\n c += 1\n }\n if (c == 0) this += ifEmpty else this\n }\n\n def append(obj: Any*): this.type = this ++= obj\n\n override def close() = {\n out.flush()\n out.close()\n }\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _633C extends CodeForcesApp {\n override def solve(in: InputReader, out: OutputWriter) = {\n val (n, text, words) = in[(Int, String, IndexedSeq[String])]\n val cipher = words.map(_.toLowerCase.reverse).zipWithIndex\n\n lazy val solve: Int => Option[List[Int]] = memoize {\n case `n` => Some(Nil)\n case i => cipher collectFirstDefined {\n case (w, j) if text.startsWith(w, i) => solve(i + w.length).map(j :: _)\n }\n }\n out ++= solve(0).get.map(words)\n }\n\n def memoize[A] = new {\n def apply[B](f: A => B): (A => B) = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n }\n\n implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {\n def collectFirstDefined[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def solve(in: InputReader, out: OutputWriter): Unit\n def main(args: Array[String]): Unit = solve(new InputReader(System.in), new OutputWriter(System.out))\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int, offset: Int = 0)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for (i <- 0 until n + offset) builder += (if (i < offset) null.asInstanceOf[A] else apply[A])\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\n\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n\nclass OutputWriter(out: PrintWriter) {\n def this(out: OutputStream) = this(new PrintWriter(out, true))\n\n var separator = \" \"\n private[this] var isNewLine: Boolean = true\n\n def +=(obj: Any): this.type = {\n if (isNewLine) isNewLine = false else out.print(separator)\n out.print(obj)\n this\n }\n\n def newLine(): this.type = {\n isNewLine = true\n out.println()\n this\n }\n\n def ++=(obj: Traversable[_], ifEmpty: => Any = \"\"): this.type = {\n var c = 0\n obj foreach {i =>\n this += i\n c += 1\n }\n if (c == 0) this += ifEmpty else this\n }\n\n def append(obj: Any*): this.type = this ++= obj\n}\n"}], "src_uid": "5d3fc6a6c4f53d53c38ab4387282a55c"} {"source_code": "import scala.io.StdIn\n\nobject CoverPoints {\n def main(args: Array[String]): Unit ={\n\n val n = StdIn.readInt()\n val Axy = StdIn.readLine().split(\" \").map(_.toInt)\n val Bxy = StdIn.readLine().split(\" \").map(_.toInt)\n val Cxy = StdIn.readLine().split(\" \").map(_.toInt)\n var check = true\n if(Axy(0) > Bxy(0) && Axy(1) > Bxy(1) ){\n if(Axy(0) > Cxy(0) && Axy(1) > Cxy(1) ){\n check = false\n }\n }\n\n if(Axy(0) < Bxy(0) && Axy(1) < Bxy(1) ){\n if(Axy(0) < Cxy(0) && Axy(1) < Cxy(1) ){\n check = false\n }\n }\n\n if(Axy(0) < Bxy(0) && Axy(1) > Bxy(1) ){\n if(Axy(0) < Cxy(0) && Axy(1) > Cxy(1) ){\n check = false\n }\n }\n\n if(Axy(0) > Bxy(0) && Axy(1) < Bxy(1) ){\n if(Axy(0) > Cxy(0) && Axy(1) < Cxy(1) ){\n check = false\n }\n }\n\n if(check)\n print(\"NO\")\n else print(\"YES\")\n}\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val ax, ay, bx, by, cx, cy = ni()\n\n def region(x: Int, y: Int): Int = {\n (if (ax - x > 0) 1 else 0) + (if (ay - y > 0) 2 else 0)\n }\n\n def onLine(x: Int, y: Int): Boolean = {\n ax == x || ay == y || abs(ax - x) == abs(ay - y)\n }\n\n if (!onLine(cx, cy) && region(bx, by) == region(cx, cy)) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = readInt\n val q1q2 = readLine.split(\" \").map(_.toInt)\n val q1 = q1q2.head\n val q2 = q1q2.last\n val k1k2 = readLine.split(\" \").map(_.toInt)\n val k1 = k1k2.head\n val k2 = k1k2.last\n val t1t2 = readLine.split(\" \").map(_.toInt)\n val t1 = t1t2.head\n val t2 = t1t2.last\n if ( ( ( (k1 < q1) && (t1 < q1) ) || ( (k1 > q1) && (t1 > q1) ) ) && ( ( (k2 < q2) && (t2 < q2) ) || ( (k2 > q2) && (t2 > q2) )) ) println(\"YES\") else println(\"NO\") \n }\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val Array(ax, ay) = readInts(2)\n val Array(bx, by) = readInts(2)\n val Array(cx, cy) = readInts(2)\n\n val minx = bx min cx\n val miny = by min cy\n val maxx = bx max cx\n val maxy = by max cy\n\n val ok = (ax < minx || ax > maxx) && (ay < miny || ay > maxy)\n\n println(if (ok) \"YES\" else \"NO\")\n\n Console.flush\n}\n"}, {"source_code": "object _1033A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val _, qx, qy, kx, ky, dx, dy = io.read[Int]\n val ans = (qx - kx).signum == (qx - dx).signum && (qy - ky).signum == (qy - dy).signum\n io.write(if (ans) \"YES\" else \"NO\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "c404761a9562ff6034010a553d944324"} {"source_code": "object Solution extends App {\n\n def normalize(str: String): String = {\n if (str.contains('.'))\n str.dropWhile(_ == '0').reverse.dropWhile(_ == '0').dropWhile(_ == '.').reverse\n else\n str.dropWhile(_ == '0')\n }\n\n val in = io.Source.stdin.getLines()\n val line = normalize(in.next())\n val point = line.indexOf('.')\n if (point != -1) {\n if (line.length == 1)\n println(0)\n else if (point == 0) {\n val e = line.indices.find(ch => line(ch) != '0' && line(ch) != '.').get\n val c = normalize(s\"${line(e)}.${line.drop(e + 1)}\")\n println(s\"${c}E${-e}\")\n } else {\n if (point == 1) {\n val c = normalize(s\"${line.head}.${line.tail.filter(_ != '.')}\")\n println(c)\n }\n else {\n println(s\"${line.head}.${line.tail.filter(_ != '.')}E${point - 1}\")\n }\n }\n } else {\n if (line.isEmpty)\n println(0)\n else if (line.length == 1)\n println(line)\n else {\n val e = line.length - 1\n val c = normalize(s\"${line.head}.${line.tail}\")\n println(s\"${c}E$e\")\n }\n\n }\n\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n var input = readLine()\n if (input == \".\") input = \"0.0\"\n var Tmp = input.split(\"\\\\.\")\n\n var left = Tmp(0)\n var right = if (Tmp.length == 2) Tmp(1) else \"\"\n left = left.dropWhile(_ == '0')\n right = right.reverse.dropWhile(_ == '0').reverse\n\n var E = \"0\"\n var L = \"\"\n var R = \"\"\n\n if (left.isEmpty && right.isEmpty) {\n println(0)\n } else if (left.isEmpty) {\n val rightFirstNonZero = right.dropWhile(_ == '0')\n L = rightFirstNonZero.head.toString\n R = rightFirstNonZero.tail\n E = \"-\" + (right.length - rightFirstNonZero.length + 1).toString\n } else {\n L = left.head.toString\n R = left.tail + right\n E = left.tail.length.toString\n }\n\n R = R.reverse.dropWhile(_ == '0').reverse\n\n val result = L + (if (R.isEmpty) \"\" else \".\") + R + (if (E != \"0\") \"E\" + E else \"\")\n println(result)\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n\n def normalize(str: String): String = {\n if (str.contains('.'))\n str.dropWhile(_ == '0').reverse.dropWhile(_ == '0').dropWhile(_ == '.').reverse\n else\n str.dropWhile(_ == '0')\n }\n\n val in = io.Source.stdin.getLines()\n val line = normalize(in.next())\n val point = line.indexOf('.')\n if (point != -1) {\n if (line.length == 1)\n println(0)\n else if (point == 0) {\n val e = line.indices.find(ch => line(ch) != '0' && line(ch) != '.').get\n val c = normalize(s\"${line(e)}.${line.drop(e + 1)}\")\n println(s\"${c}E${-e}\")\n } else {\n if (point == 1) {\n val c = normalize(s\"${line.head}.${line.tail.filter(_ != '.')}\")\n println(c)\n }\n else {\n println(\"h\")\n println(s\"${line.head}.${line.tail.filter(_ != '.')}E${point - 1}\")\n }\n }\n } else {\n if (line.isEmpty)\n println(0)\n else if (line.length == 1)\n println(line)\n else {\n val e = line.length - 1\n val c = normalize(s\"${line.head}.${line.tail}\")\n println(s\"${c}E$e\")\n }\n\n }\n\n}"}], "src_uid": "b1eebb3928925b84a95b9f1e5a31e4f3"} {"source_code": "import collection.mutable\nimport java.util.Scanner\n\nobject E {\n def main(args: Array[String]) {\n val in = new Scanner(System.in)\n val n = in.nextInt()\n val a = new Array[Vertex](n)\n for (i <- a.indices) {\n a(i) = new Vertex\n }\n for (i <- 1 until n) {\n val x = in.nextInt() - 1\n val s = in.next()\n a(x).ch add new Edge(s, a(i))\n }\n\n var s = in.next()\n val l = s length\n val go = new Array[Array[Int]](l + 1)\n val pref = new Array[Int](l + 1)\n for (i <- 0 until l + 1) {\n go(i) = new Array(26)\n if (i < l)\n go(i)(s(i) - 'a') = i + 1\n if (i < 2)\n pref(i) = 0\n else\n pref(i) = go(pref(i - 1))(s(i - 1) - 'a')\n for (j <- 0 until 26)\n if (go(i)(j) != i + 1)\n go(i)(j) = go(pref(i))(j)\n }\n\n val ans = a(0).dfs(go, l, 0)\n println(ans)\n }\n}\n\nclass Vertex {\n val ch = new mutable.HashSet[Edge]\n\n def dfs(go: Array[Array[Int]], good: Int, state: Int): Int = {\n var res = 0\n for (e <- ch) {\n var cur = state\n for (c <- e.s) {\n cur = go(cur)(c - 'a')\n if (cur == good) {\n res += 1\n }\n }\n res += e.to.dfs(go, good, cur)\n }\n res\n }\n}\n\nclass Edge(val s: String, val to: Vertex)\n\n", "positive_code": [{"source_code": "import io.Source\nimport java.io.PrintWriter\n\nobject CF291E {\n\n def solve(in: In, out: PrintWriter) {\n// val t0 = System.currentTimeMillis()\n val n = in().toInt\n// val n = 100000\n val par = Array.ofDim[Int](n)\n val strs = Array.ofDim[String](n)\n for (i <- 1 until n) {\n par(i) = in().toInt - 1\n strs(i) = in()\n// par(i) = i - 1\n// strs(i) = \"a\"\n }\n val str = in()\n// val str = \"a\" * 300000\n val p = Array.fill(str.size)(0)\n for (i <- 1 until str.length) {\n p(i) = p(i - 1)\n while (p(i) != 0 && str(i) != str(p(i))) {\n p(i) = p(p(i) - 1)\n }\n if (str(i) == str(p(i))) {\n p(i) += 1\n }\n }\n val q = Array.fill(n)(-1)\n q(0) = 0\n var ans = 0\n def eval(i: Int): Int = {\n if (q(i) == -1) {\n q(i) = eval(par(i))\n for (c <- strs(i)) {\n while (q(i) != 0 && c != str(q(i))) {\n q(i) = p(q(i) - 1)\n }\n if (c == str(q(i))) {\n q(i) += 1\n }\n if (q(i) == str.length) {\n ans += 1\n q(i) = p(q(i) - 1)\n }\n }\n }\n q(i)\n }\n (0 until n).foreach(eval)\n out.println(ans)\n// println(System.currentTimeMillis() - t0)\n }\n\n def main(args: Array[String]) {\n new Thread(null, new Runnable {\n def run() {\n val in: In = new In(Source.fromInputStream(System.in))\n val out: PrintWriter = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n }, \"run\", 128000000).run()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() {\n while (iter.hasNext && delims.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next(): String = {\n skipDelims()\n while (iter.hasNext && delims.indexOf(iter.head) == -1) {\n sb.append(iter.next())\n }\n val ret = sb.toString()\n sb.clear()\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIterator = new TokenIterator(iter, \" \\r\\n\")\n\n val lineIterator = new TokenIterator(iter, \"\\r\\n\")\n\n def apply() = tokenIterator.next()\n\n def apply(n: Int) = tokenIterator.take(n)\n }\n}"}], "negative_code": [], "src_uid": "2e08077d0b49c52586266ddcc12edcb5"} {"source_code": "import Utils._, annotation._, collection._, util._, control._, math.Ordering.Implicits._, Searching._\n\nobject _776B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n = read[Int]\n val ans = Array.ofDim[Int](n)\n\n for {\n i <- 0 until n if ans(i) == 0\n _ = ans(i) = 1\n j <- 2*(i+2) - 2 until n by (i + 2)\n } ans(j) = 2\n\n write(ans.max).writeLine().writeAll(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "//package solutions\n \nimport java.io.PrintWriter\nimport java.util.Scanner\n\nimport scala.annotation.tailrec\nimport scala.collection.parallel.mutable.ParSet\n\n/**\n * @author traff\n */\n\n\nobject SolTaskB extends App {\n\n def sieveOfEratosthenes(limit: Int) = {\n val (primes: ParSet[Int], sqrtLimit) = (ParSet.empty ++ (2 to limit), math.sqrt(limit).toInt)\n\n @tailrec\n def prim(candidate: Int): Unit = {\n if (candidate <= sqrtLimit) {\n if (primes contains candidate) primes --= candidate * candidate to limit by candidate\n prim(candidate + 1)\n }\n }\n\n prim(2)\n primes\n }\n\n override def main(args: Array[String]): Unit = {\n val out = new PrintWriter(System.out)\n\n run(new Scanner(System.in), out)\n\n out.close()\n }\n\n def run(s: Scanner, out: PrintWriter): Unit = {\n val n = s.nextInt()\n\n val primes = sieveOfEratosthenes(n + 1)\n\n var colors = new Array[Int](n)\n\n if (n > 2) {\n out.println(2)\n\n for (i <- 2 to n + 1) {\n if (primes contains i) {\n out.print(s\"1 \")\n } else {\n out.print(s\"2 \")\n }\n }\n } else {\n out.println(1)\n for (i <- 2 to n + 1) {\n out.print(s\"1 \")\n }\n }\n }\n\n}\n"}, {"source_code": "object B776 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n case class Sieve(to: Int) {\n val primes = scala.collection.mutable.ArrayBuffer.empty[Int]\n val isComposite = Array.fill(to + 1)(false)\n def sieve(): Unit = { // Works in linear time\n for (i <- 2 until to) {\n if (!isComposite(i)) primes.append(i)\n var j = 0\n var break = false\n while (j < primes.size && i * primes(j) < to && !break) {\n isComposite(i * primes(j)) = true\n if (i % primes(j) == 0)\n break = true\n j += 1\n }\n }\n }\n }\n val s = Sieve(100000 + 10)\n s.sieve()\n def main(args: Array[String]): Unit = {\n val n = readInt\n if (n <= 2)\n out.println(1)\n else\n out.println(2)\n out.println(\n s.isComposite\n .slice(2, n + 2)\n .map { if (_) 2 else 1 }\n .mkString(\" \")\n )\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "//package solutions\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\nimport scala.annotation.tailrec\nimport scala.collection.parallel.mutable.ParSet\n\n/**\n * @author traff\n */\n\n\nobject SolTaskB extends App {\n\n def sieveOfEratosthenes(limit: Int) = {\n val (primes: ParSet[Int], sqrtLimit) = (ParSet.empty ++ (2 to limit), math.sqrt(limit).toInt)\n\n @tailrec\n def prim(candidate: Int): Unit = {\n if (candidate <= sqrtLimit) {\n if (primes contains candidate) primes --= candidate * candidate to limit by candidate\n prim(candidate + 1)\n }\n }\n\n prim(2)\n primes\n }\n\n override def main(args: Array[String]): Unit = {\n val out = new PrintWriter(System.out)\n\n run(new Scanner(System.in), out)\n\n out.close()\n }\n\n def run(s: Scanner, out: PrintWriter): Unit = {\n val n = s.nextInt()\n\n val primes = sieveOfEratosthenes(n+1)\n\n var colors = new Array[Int](n)\n\n out.println(2)\n\n for (i <- 2 to n+1) {\n if (primes contains i) {\n out.print(s\"1 \")\n } else {\n out.print(s\"2 \")\n }\n }\n }\n}\n"}, {"source_code": "import Utils._, annotation._, collection._, util._, control._, math.Ordering.Implicits._, Searching._\n\nobject _776B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n = read[Int]\n val ans = Array.ofDim[Int](n)\n val illegal = Array.fill(n)(mutable.Set.empty[Int])\n\n for {\n i <- 0 until n\n color <- (1 to n).find(not(illegal(i)))\n _ = ans(i) = color\n j <- i until n by (i + 2)\n } illegal(j) += color\n\n write(ans.toSet.size)\n .writeLine()\n .writeAll(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "a99f5e08f3f560488ff979a3e9746e7f"} {"source_code": "import scala.collection._\n\nobject D extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val dim = 3001\n\n val n = readString.toInt\n\n val a = Array.fill(dim, dim)(0)\n val area = Array.ofDim[Int](dim, dim)\n val tl = Array.fill(dim)(new mutable.BitSet(dim))\n val tr = Array.fill(dim)(new mutable.BitSet(dim))\n val blx = Array.fill(dim)(new mutable.BitSet(dim))\n val br = Array.fill(dim)(new mutable.BitSet(dim))\n val te = Array.fill(dim)(new mutable.BitSet(dim))\n val be = Array.fill(dim)(new mutable.BitSet(dim))\n val lex = Array.fill(dim)(new mutable.BitSet(dim))\n val rex = Array.fill(dim)(new mutable.BitSet(dim))\n\n for (i <- 0 until dim) {\n area(0)(i) = 0\n area(i)(0) = 0\n }\n\n var i = 1\n while (i <= n) {\n val Array(x1, y1, x2, y2) = readInts\n tl(y1)(x1) = true\n tr(y1)(x2 - 1) = true\n blx(x1)(y2 - 1) = true\n br(y2 - 1)(x2 - 1) = true\n var x = x1\n while (x < x2) {\n te(y1)(x) = true\n be(y2 - 1)(x) = true\n x += 1\n }\n var y = y1\n while (y < y2) {\n lex(x1)(y) = true\n rex(x2 - 1)(y) = true\n y += 1\n }\n y = y1\n while (y < y2) {\n var x = x1\n while (x < x2) {\n a(y)(x) = i\n x += 1\n }\n y += 1\n }\n i += 1\n }\n\n y = 1\n while (y < dim) {\n var x = 1\n var horSum = 0\n while (x < dim) {\n if (a(y)(x) > 0) horSum += 1\n area(y)(x) = area(y - 1)(x) + horSum\n x += 1\n }\n y += 1\n }\n\n def full(x1: Int, y1: Int, x2: Int, y2: Int): Boolean = {\n x2 < x1 || y2 < y1 ||\n area(y2)(x2) - area(y1 - 1)(x2) - area(y2)(x1 - 1) + area(y1 - 1)(x1 - 1) == (x2 - x1 + 1) * (y2 - y1 + 1)\n }\n\n def rectIds(x1: Int, y1: Int, x2: Int, y2: Int) = {\n val ids = mutable.Set[Int]()\n var y = y1\n while (y <= y2) {\n var x = x1\n while (x <= x2) {\n ids += a(y)(x)\n x += 1\n }\n y += 1\n }\n ids\n }\n\n var y = 0\n while (y < dim) {\n var x = 0\n while (x < dim) {\n if (tl(y)(x)) {\n var nextX = 0\n var size = 0\n while (x + size < dim && y + size < dim && te(y)(x + size) && lex(x)(y + size)) {\n if (tr(y)(x + size) && blx(x)(y + size) && br(y + size)(x + size)) {\n var d = 1\n while (d < size && rex(x + size)(y + d) && be(y + size)(x + d)) d += 1\n if (d >= size) {\n if (full(x + 1, y + 1, x + size - 1, y + size - 1)) {\n val ids = rectIds(x, y, x + size, y + size)\n println(\"YES \" + ids.size)\n println(ids.mkString(\" \"))\n exit\n } else size = dim - x - 2\n }\n }\n size += 1\n if (tl(y)(x + size) && nextX == 0) nextX = x + size\n }\n x = if (nextX > 0) nextX else x + size\n } else x += 1\n }\n y += 1\n }\n\n println(\"NO\")\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject D extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val dim = 3001\n\n val n = readString.toInt\n\n val a = Array.fill(dim, dim)(0)\n val area = Array.ofDim[Int](dim, dim)\n val tl = Array.fill(dim)(new mutable.BitSet(dim))\n val tr = Array.fill(dim)(new mutable.BitSet(dim))\n val blx = Array.fill(dim)(new mutable.BitSet(dim))\n val br = Array.fill(dim)(new mutable.BitSet(dim))\n val te = Array.fill(dim)(new mutable.BitSet(dim))\n val be = Array.fill(dim)(new mutable.BitSet(dim))\n val lex = Array.fill(dim)(new mutable.BitSet(dim))\n val rex = Array.fill(dim)(new mutable.BitSet(dim))\n\n for (i <- 0 until dim) {\n area(0)(i) = 0\n area(i)(0) = 0\n }\n\n var i = 1\n while (i <= n) {\n val Array(x1, y1, x2, y2) = readInts\n tl(y1)(x1) = true\n tr(y1)(x2 - 1) = true\n blx(x1)(y2 - 1) = true\n br(y2 - 1)(x2 - 1) = true\n var x = x1\n while (x < x2) {\n te(y1)(x) = true\n be(y2 - 1)(x) = true\n x += 1\n }\n var y = y1\n while (y < y2) {\n lex(x1)(y) = true\n rex(x2 - 1)(y) = true\n y += 1\n }\n y = y1\n while (y < y2) {\n var x = x1\n val a2 = a(y)\n while (x < x2) {\n a2(x) = i\n x += 1\n }\n y += 1\n }\n i += 1\n }\n\n y = 1\n while (y < dim) {\n var x = 1\n val a2 = a(y)\n var horSum = 0\n while (x < dim) {\n if (a2(x) > 0) horSum += 1\n area(y)(x) = area(y - 1)(x) + horSum\n x += 1\n }\n y += 1\n }\n\n def holes(x1: Int, y1: Int, x2: Int, y2: Int): Boolean = {\n x2 >= x1 && y2 >= y1 &&\n area(y2)(x2) - area(y1 - 1)(x2) - area(y2)(x1 - 1) + area(y1 - 1)(x1 - 1) != (x2 - x1 + 1) * (y2 - y1 + 1)\n// var y = y1\n// while (y <= y2) {\n// var x = x1\n// val a2 = a(y)\n// while (x <= x2) {\n// if (a2(x) == 0) return true\n// x += 1\n// }\n// y += 1\n// }\n// false\n }\n\n def rectIds(x1: Int, y1: Int, x2: Int, y2: Int) = {\n val ids = mutable.Set[Int]()\n var y = y1\n while (y <= y2) {\n var x = x1\n val a2 = a(y)\n while (x <= x2) {\n ids += a2(x)\n x += 1\n }\n y += 1\n }\n ids\n }\n\n var y = 0\n while (y < dim) {\n var x = 0\n val te2 = te(y)\n val tr2 = tr(y)\n val tl2 = tl(y)\n while (x < dim) {\n if (tl2(x)) {\n var nextX = 0\n var size = 0\n val blx2 = blx(x)\n val lex2 = lex(x)\n while (x + size < dim && y + size < dim && te2(x + size) && lex2(y + size)) {\n if (tr2(x + size) && blx2(y + size) && br(y + size)(x + size)) {\n var d = 1\n val rex2 = rex(x + size)\n val be2 = be(y + size)\n while (d < size && rex2(y + d) && be2(x + d)) d += 1\n if (d >= size) {\n if (!holes(x + 1, y + 1, x + size - 1, y + size - 1)) {\n val ids = rectIds(x, y, x + size, y + size)\n println(\"YES \" + ids.size)\n println(ids.mkString(\" \"))\n exit\n } else size = dim - x - 2\n }\n }\n size += 1\n if (tl2(x + size) && nextX == 0) nextX = x + size\n }\n x = if (nextX > 0) nextX else x + size\n } else x += 1\n }\n y += 1\n }\n\n println(\"NO\")\n}"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val dim = 3001\n\n val n = readString.toInt\n\n val a = Array.fill(dim, dim)(0)\n val area = Array.ofDim[Int](dim, dim)\n val tl = Array.fill(dim)(new mutable.BitSet(dim))\n val tr = Array.fill(dim)(new mutable.BitSet(dim))\n val blx = Array.fill(dim)(new mutable.BitSet(dim))\n val br = Array.fill(dim)(new mutable.BitSet(dim))\n val te = Array.fill(dim)(new mutable.BitSet(dim))\n val be = Array.fill(dim)(new mutable.BitSet(dim))\n val lex = Array.fill(dim)(new mutable.BitSet(dim))\n val rex = Array.fill(dim)(new mutable.BitSet(dim))\n\n for (i <- 0 until dim) {\n area(0)(i) = 0\n area(i)(0) = 0\n }\n\n var i = 1\n while (i <= n) {\n val Array(x1, y1, x2, y2) = readInts\n tl(y1)(x1) = true\n tr(y1)(x2 - 1) = true\n blx(x1)(y2 - 1) = true\n br(y2 - 1)(x2 - 1) = true\n var x = x1\n while (x < x2) {\n te(y1)(x) = true\n be(y2 - 1)(x) = true\n x += 1\n }\n var y = y1\n while (y < y2) {\n lex(x1)(y) = true\n rex(x2 - 1)(y) = true\n y += 1\n }\n y = y1\n while (y < y2) {\n var x = x1\n val a2 = a(y)\n while (x < x2) {\n a2(x) = i\n x += 1\n }\n y += 1\n }\n i += 1\n }\n\n y = 1\n while (y < dim) {\n var x = 1\n val a2 = a(y)\n var horSum = 0\n while (x < dim) {\n if (a2(x) > 0) horSum += 1\n area(y)(x) = area(y - 1)(x) + horSum\n x += 1\n }\n y += 1\n }\n\n def full(x1: Int, y1: Int, x2: Int, y2: Int): Boolean = {\n x2 < x1 || y2 < y1 ||\n area(y2)(x2) - area(y1 - 1)(x2) - area(y2)(x1 - 1) + area(y1 - 1)(x1 - 1) == (x2 - x1 + 1) * (y2 - y1 + 1)\n }\n\n def rectIds(x1: Int, y1: Int, x2: Int, y2: Int) = {\n val ids = mutable.Set[Int]()\n var y = y1\n while (y <= y2) {\n var x = x1\n val a2 = a(y)\n while (x <= x2) {\n ids += a2(x)\n x += 1\n }\n y += 1\n }\n ids\n }\n\n var y = 0\n while (y < dim) {\n var x = 0\n val te2 = te(y)\n val tr2 = tr(y)\n val tl2 = tl(y)\n while (x < dim) {\n if (tl2(x)) {\n var nextX = 0\n var size = 0\n val blx2 = blx(x)\n val lex2 = lex(x)\n while (x + size < dim && y + size < dim && te2(x + size) && lex2(y + size)) {\n if (tr2(x + size) && blx2(y + size) && br(y + size)(x + size)) {\n var d = 1\n val rex2 = rex(x + size)\n val be2 = be(y + size)\n while (d < size && rex2(y + d) && be2(x + d)) d += 1\n if (d >= size) {\n if (full(x + 1, y + 1, x + size - 1, y + size - 1)) {\n val ids = rectIds(x, y, x + size, y + size)\n println(\"YES \" + ids.size)\n println(ids.mkString(\" \"))\n exit\n } else size = dim - x - 2\n }\n }\n size += 1\n if (tl2(x + size) && nextX == 0) nextX = x + size\n }\n x = if (nextX > 0) nextX else x + size\n } else x += 1\n }\n y += 1\n }\n\n println(\"NO\")\n}"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val dim = 3001\n\n val n = readString.toInt\n\n val a = Array.fill(dim, dim)(0)\n val area = Array.ofDim[Int](dim, dim)\n val tl = Array.fill(dim)(new mutable.BitSet(dim))\n val tr = Array.fill(dim)(new mutable.BitSet(dim))\n val blx = Array.fill(dim)(new mutable.BitSet(dim))\n val br = Array.fill(dim)(new mutable.BitSet(dim))\n val te = Array.fill(dim)(new mutable.BitSet(dim))\n val be = Array.fill(dim)(new mutable.BitSet(dim))\n val lex = Array.fill(dim)(new mutable.BitSet(dim))\n val rex = Array.fill(dim)(new mutable.BitSet(dim))\n\n for (i <- 0 until dim) {\n area(0)(i) = 0\n area(i)(0) = 0\n }\n\n var i = 1\n while (i <= n) {\n val Array(x1, y1, x2, y2) = readInts\n tl(y1)(x1) = true\n tr(y1)(x2 - 1) = true\n blx(y2 - 1)(x1) = true\n br(y2 - 1)(x2 - 1) = true\n var x = x1\n while (x < x2) {\n te(y1)(x) = true\n be(y2 - 1)(x) = true\n x += 1\n }\n var y = y1\n while (y < y2) {\n lex(y)(x1) = true\n rex(y)(x2 - 1) = true\n y += 1\n }\n y = y1\n while (y < y2) {\n var x = x1\n while (x < x2) {\n a(y)(x) = i\n x += 1\n }\n y += 1\n }\n i += 1\n }\n\n y = 1\n while (y < dim) {\n var x = 1\n var horSum = 0\n while (x < dim) {\n if (a(y)(x) > 0) horSum += 1\n area(y)(x) = area(y - 1)(x) + horSum\n x += 1\n }\n y += 1\n }\n\n def full(x1: Int, y1: Int, x2: Int, y2: Int): Boolean = {\n x2 < x1 || y2 < y1 ||\n area(y2)(x2) - area(y1 - 1)(x2) - area(y2)(x1 - 1) + area(y1 - 1)(x1 - 1) == (x2 - x1 + 1) * (y2 - y1 + 1)\n }\n\n def rectIds(x1: Int, y1: Int, x2: Int, y2: Int) = {\n val ids = mutable.Set[Int]()\n var y = y1\n while (y <= y2) {\n var x = x1\n while (x <= x2) {\n ids += a(y)(x)\n x += 1\n }\n y += 1\n }\n ids\n }\n\n var y = 0\n while (y < dim) {\n var x = 0\n while (x < dim) {\n if (tl(y)(x)) {\n var nextX = 0\n var size = 0\n while (x + size < dim && y + size < dim && te(y)(x + size) && lex(y + size)(x)) {\n if (tr(y)(x + size) && blx(y + size)(x) && br(y + size)(x + size)) {\n var d = 1\n while (d < size && rex(y + d)(x + size) && be(y + size)(x + d)) d += 1\n if (d >= size) {\n if (full(x + 1, y + 1, x + size - 1, y + size - 1)) {\n val ids = rectIds(x, y, x + size, y + size)\n println(\"YES \" + ids.size)\n println(ids.mkString(\" \"))\n exit\n } else size = dim - x - 2\n }\n }\n size += 1\n if (tl(y)(x + size) && nextX == 0) nextX = x + size\n }\n x = if (nextX > 0) nextX else x + size\n } else x += 1\n }\n y += 1\n }\n\n println(\"NO\")\n}"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val dim = 3001\n\n val n = readString.toInt\n\n val a = Array.fill(dim, dim)(0)\n val area = Array.ofDim[Int](dim, dim)\n val tl = Array.fill(dim)(new mutable.BitSet(dim))\n val tr = Array.fill(dim)(new mutable.BitSet(dim))\n val blx = Array.fill(dim)(new mutable.BitSet(dim))\n val br = Array.fill(dim)(new mutable.BitSet(dim))\n val te = Array.fill(dim)(new mutable.BitSet(dim))\n val be = Array.fill(dim)(new mutable.BitSet(dim))\n val lex = Array.fill(dim)(new mutable.BitSet(dim))\n val rex = Array.fill(dim)(new mutable.BitSet(dim))\n\n for (i <- 0 until dim) {\n area(0)(i) = 0\n area(i)(0) = 0\n }\n\n var i = 1\n while (i <= n) {\n val Array(x1, y1, x2, y2) = readInts\n tl(y1)(x1) = true\n tr(y1)(x2 - 1) = true\n blx(x1)(y2 - 1) = true\n br(y2 - 1)(x2 - 1) = true\n var x = x1\n while (x < x2) {\n te(y1)(x) = true\n be(y2 - 1)(x) = true\n x += 1\n }\n var y = y1\n while (y < y2) {\n lex(x1)(y) = true\n rex(x2 - 1)(y) = true\n y += 1\n }\n y = y1\n while (y < y2) {\n var x = x1\n val a2 = a(y)\n while (x < x2) {\n a2(x) = i\n x += 1\n }\n y += 1\n }\n i += 1\n }\n\n y = 1\n while (y < dim) {\n var x = 1\n val a2 = a(y)\n var horSum = 0\n while (x < dim) {\n if (a2(x) > 0) horSum += 1\n area(y)(x) = area(y - 1)(x) + horSum\n x += 1\n }\n y += 1\n }\n\n def full(x1: Int, y1: Int, x2: Int, y2: Int): Boolean = {\n x2 < x1 || y2 < y1 ||\n area(y2)(x2) - area(y1 - 1)(x2) - area(y2)(x1 - 1) + area(y1 - 1)(x1 - 1) == (x2 - x1 + 1) * (y2 - y1 + 1)\n }\n\n def rectIds(x1: Int, y1: Int, x2: Int, y2: Int) = {\n val ids = mutable.Set[Int]()\n var y = y1\n while (y <= y2) {\n var x = x1\n val a2 = a(y)\n while (x <= x2) {\n ids += a2(x)\n x += 1\n }\n y += 1\n }\n ids\n }\n\n var y = 0\n while (y < dim) {\n var x = 0\n val te2 = te(y)\n val tr2 = tr(y)\n val tl2 = tl(y)\n while (x < dim) {\n if (tl2(x)) {\n var nextX = 0\n var size = 0\n val blx2 = blx(x)\n val lex2 = lex(x)\n while (x + size < dim && y + size < dim && te2(x + size) && lex2(y + size)) {\n if (tr2(x + size) && blx2(y + size) && br(y + size)(x + size)) {\n var d = 1\n val rex2 = rex(x + size)\n val be2 = be(y + size)\n while (d < size && rex2(y + d) && be2(x + d)) d += 1\n if (d >= size) {\n if (full(x + 1, y + 1, x + size - 1, y + size - 1)) {\n val ids = rectIds(x, y, x + size, y + size)\n println(\"YES \" + ids.size)\n println(ids.mkString(\" \"))\n exit\n } else size = dim - x - 2\n }\n }\n size += 1\n if (tl2(x + size) && nextX == 0) nextX = x + size\n }\n x = if (nextX > 0) nextX else x + size\n } else x += 1\n }\n y += 1\n }\n\n println(\"NO\")\n}"}], "negative_code": [{"source_code": "object D extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val dim = 3001\n\n val n = readString.toInt\n\n val a = Array.fill(dim, dim)(0)\n val tl = Array.fill(dim, dim)(false)\n val tr = Array.fill(dim, dim)(false)\n val bl = Array.fill(dim, dim)(false)\n val br = Array.fill(dim, dim)(false)\n val he = Array.fill(dim, dim)(false)\n val ve = Array.fill(dim, dim)(false)\n\n var i = 1\n while (i <= n) {\n val Array(x1, y1, x2, y2) = readInts\n tl(y1)(x1) = true\n tr(y1)(x2 - 1) = true\n bl(y2 - 1)(x1) = true\n br(y2 - 1)(x2 - 1) = true\n var x = x1\n while (x < x2) {\n he(y1)(x) = true\n he(y2 - 1)(x) = true\n x += 1\n }\n var y = y1\n while (y < y2) {\n ve(y)(x1) = true\n ve(y)(x2 - 1) = true\n y += 1\n }\n y = y1\n while (y <= y2) {\n var x = x1\n while (x <= x2) {\n a(y)(x) = i\n x += 1\n }\n y += 1\n }\n i += 1\n }\n\n def holes(x1: Int, y1: Int, x2: Int, y2: Int): Boolean = {\n var y = y1\n while (y <= y2) {\n var x = x1\n while (x <= x2) {\n if (a(y)(x) == 0) return true\n x += 1\n }\n y += 1\n }\n false\n }\n\n def rectIds(x1: Int, y1: Int, x2: Int, y2: Int) = {\n val ids = scala.collection.mutable.Set[Int]()\n var y = y1\n while (y <= y2) {\n var x = x1\n while (x <= x2) {\n ids += a(y)(x)\n x += 1\n }\n y += 1\n }\n ids\n }\n\n var y = 0\n while (y < dim) {\n var x = 0\n while (x < dim) {\n if (tl(y)(x)) {\n var dx = 0\n while (x + dx < dim && y + dx < dim && he(y)(x + dx)) {\n if (tr(y)(x + dx) && bl(y + dx)(x) && br(y + dx)(x + dx)) {\n var dy = 1\n var goodEdges = true\n while (dy < dx && goodEdges) {\n goodEdges = ve(y + dy)(x) && ve(y + dy)(x + dx) && he(y + dx)(x + dy)\n dy += 1\n }\n if (goodEdges && !holes(x + 1, y + 1, x + dx - 1, y + dx - 1)) {\n val ids = rectIds(x, y, x + dx, y + dx)\n println(\"YES \" + ids.size)\n println(ids.mkString(\" \"))\n exit\n }\n }\n dx += 1\n }\n }\n x += 1\n }\n y += 1\n }\n\n println(\"NO\")\n}"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val dim = 3001\n\n val n = readString.toInt\n\n val a = Array.fill(dim, dim)(0)\n val area = Array.ofDim[Int](dim, dim)\n val tl = Array.fill(dim)(new mutable.BitSet(dim))\n val tr = Array.fill(dim)(new mutable.BitSet(dim))\n val blx = Array.fill(dim)(new mutable.BitSet(dim))\n val br = Array.fill(dim)(new mutable.BitSet(dim))\n val te = Array.fill(dim)(new mutable.BitSet(dim))\n val be = Array.fill(dim)(new mutable.BitSet(dim))\n val lex = Array.fill(dim)(new mutable.BitSet(dim))\n val rex = Array.fill(dim)(new mutable.BitSet(dim))\n\n for (i <- 0 until dim) {\n area(0)(i) = 0\n area(i)(0) = 0\n }\n\n var i = 1\n while (i <= n) {\n val Array(x1, y1, x2, y2) = readInts\n tl(y1)(x1) = true\n tr(y1)(x2 - 1) = true\n blx(x1)(y2 - 1) = true\n br(y2 - 1)(x2 - 1) = true\n var x = x1\n while (x < x2) {\n te(y1)(x) = true\n be(y2 - 1)(x) = true\n x += 1\n }\n var y = y1\n while (y < y2) {\n lex(x1)(y) = true\n rex(x2 - 1)(y) = true\n y += 1\n }\n y = y1\n while (y < y2) {\n var x = x1\n val a2 = a(y)\n while (x < x2) {\n a2(x) = i\n x += 1\n }\n y += 1\n }\n i += 1\n }\n\n y = 1\n while (y < dim) {\n var x = 1\n val a2 = a(y)\n var horSum = 0\n while (x < dim) {\n if (a2(x) > 0) horSum += 1\n area(y)(x) = area(y - 1)(x) + horSum\n x += 1\n }\n y += 1\n }\n\n def holes(x1: Int, y1: Int, x2: Int, y2: Int): Boolean = {\n area(y2)(x2) - area(math.min(y1 - 1, 0))(x2) - area(y2)(math.min(x1 - 1, 0)) + \n \tarea(math.min(y1 - 1, 0))(math.min(x1 - 1, 0)) != (x2 - x1 + 1) * (y2 - y1 + 1)\n// var y = y1\n// while (y <= y2) {\n// var x = x1\n// val a2 = a(y)\n// while (x <= x2) {\n// if (a2(x) == 0) return true\n// x += 1\n// }\n// y += 1\n// }\n// false\n }\n\n def rectIds(x1: Int, y1: Int, x2: Int, y2: Int) = {\n val ids = mutable.Set[Int]()\n var y = y1\n while (y <= y2) {\n var x = x1\n val a2 = a(y)\n while (x <= x2) {\n ids += a2(x)\n x += 1\n }\n y += 1\n }\n ids\n }\n\n var y = 0\n while (y < dim) {\n var x = 0\n val te2 = te(y)\n val tr2 = tr(y)\n val tl2 = tl(y)\n while (x < dim) {\n if (tl2(x)) {\n var nextX = 0\n var size = 0\n val blx2 = blx(x)\n val lex2 = lex(x)\n while (x + size < dim && y + size < dim && te2(x + size) && lex2(y + size)) {\n if (tr2(x + size) && blx2(y + size) && br(y + size)(x + size)) {\n var d = 1\n val rex2 = rex(x + size)\n val be2 = be(y + size)\n while (d < size && rex2(y + d) && be2(x + d)) d += 1\n if (d >= size) {\n if (!holes(x + 1, y + 1, x + size - 1, y + size - 1)) {\n val ids = rectIds(x, y, x + size, y + size)\n println(\"YES \" + ids.size)\n println(ids.mkString(\" \"))\n exit\n } else size = dim - x - 2\n }\n }\n size += 1\n if (tl2(x + size) && nextX == 0) nextX = x + size\n }\n x = if (nextX > 0) nextX else x + size\n } else x += 1\n }\n y += 1\n }\n\n println(\"NO\")\n}"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val dim = 3001\n\n val n = readString.toInt\n\n val a = Array.fill(dim, dim)(0)\n val area = Array.ofDim[Int](dim, dim)\n val tl = Array.fill(dim)(new mutable.BitSet(dim))\n val tr = Array.fill(dim)(new mutable.BitSet(dim))\n val blx = Array.fill(dim)(new mutable.BitSet(dim))\n val br = Array.fill(dim)(new mutable.BitSet(dim))\n val te = Array.fill(dim)(new mutable.BitSet(dim))\n val be = Array.fill(dim)(new mutable.BitSet(dim))\n val lex = Array.fill(dim)(new mutable.BitSet(dim))\n val rex = Array.fill(dim)(new mutable.BitSet(dim))\n\n for (i <- 0 until dim) {\n area(0)(i) = 0\n area(i)(0) = 0\n }\n\n var i = 1\n while (i <= n) {\n val Array(x1, y1, x2, y2) = readInts\n tl(y1)(x1) = true\n tr(y1)(x2 - 1) = true\n blx(x1)(y2 - 1) = true\n br(y2 - 1)(x2 - 1) = true\n var x = x1\n while (x < x2) {\n te(y1)(x) = true\n be(y2 - 1)(x) = true\n x += 1\n }\n var y = y1\n while (y < y2) {\n lex(x1)(y) = true\n rex(x2 - 1)(y) = true\n y += 1\n }\n y = y1\n while (y < y2) {\n var x = x1\n val a2 = a(y)\n while (x < x2) {\n a2(x) = i\n x += 1\n }\n y += 1\n }\n i += 1\n }\n\n y = 1\n while (y < dim) {\n var x = 1\n val a2 = a(y)\n var horSum = 0\n while (x < dim) {\n if (a2(x) > 0) horSum += 1\n area(y)(x) = area(y - 1)(x) + horSum\n x += 1\n }\n y += 1\n }\n\n def holes(x1: Int, y1: Int, x2: Int, y2: Int): Boolean = {\n x2 < x1 || y2 < y1 ||\n area(y2)(x2) - area(y1 - 1)(x2) - area(y2)(x1 - 1) + area(y1 - 1)(x1 - 1) != (x2 - x1 + 1) * (y2 - y1 + 1)\n// var y = y1\n// while (y <= y2) {\n// var x = x1\n// val a2 = a(y)\n// while (x <= x2) {\n// if (a2(x) == 0) return true\n// x += 1\n// }\n// y += 1\n// }\n// false\n }\n\n def rectIds(x1: Int, y1: Int, x2: Int, y2: Int) = {\n val ids = mutable.Set[Int]()\n var y = y1\n while (y <= y2) {\n var x = x1\n val a2 = a(y)\n while (x <= x2) {\n ids += a2(x)\n x += 1\n }\n y += 1\n }\n ids\n }\n\n var y = 0\n while (y < dim) {\n var x = 0\n val te2 = te(y)\n val tr2 = tr(y)\n val tl2 = tl(y)\n while (x < dim) {\n if (tl2(x)) {\n var nextX = 0\n var size = 0\n val blx2 = blx(x)\n val lex2 = lex(x)\n while (x + size < dim && y + size < dim && te2(x + size) && lex2(y + size)) {\n if (tr2(x + size) && blx2(y + size) && br(y + size)(x + size)) {\n var d = 1\n val rex2 = rex(x + size)\n val be2 = be(y + size)\n while (d < size && rex2(y + d) && be2(x + d)) d += 1\n if (d >= size) {\n if (!holes(x + 1, y + 1, x + size - 1, y + size - 1)) {\n val ids = rectIds(x, y, x + size, y + size)\n println(\"YES \" + ids.size)\n println(ids.mkString(\" \"))\n exit\n } else size = dim - x - 2\n }\n }\n size += 1\n if (tl2(x + size) && nextX == 0) nextX = x + size\n }\n x = if (nextX > 0) nextX else x + size\n } else x += 1\n }\n y += 1\n }\n\n println(\"NO\")\n}"}, {"source_code": "object D extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val dim = 3001\n\n val n = readString.toInt\n\n val a = Array.fill(dim, dim)(0)\n val tl = Array.fill(dim, dim)(false)\n val tr = Array.fill(dim, dim)(false)\n val bl = Array.fill(dim, dim)(false)\n val br = Array.fill(dim, dim)(false)\n val he = Array.fill(dim, dim)(false)\n val ve = Array.fill(dim, dim)(false)\n\n for (i <- 1 to n) {\n val Array(x1, y1, x2, y2) = readInts\n tl(y1)(x1) = true\n tr(y1)(x2 - 1) = true\n bl(y2 - 1)(x1) = true\n br(y2 - 1)(x2 - 1) = true\n for (x <- x1 until x2) {\n he(y1)(x) = true\n he(y2 - 1)(x) = true\n }\n for (y <- y1 until y2) {\n ve(y)(x1) = true\n ve(y)(x2 - 1) = true\n }\n for (y <- y1 until y2; x <- x1 until x2) a(y)(x) = i\n }\n\n def holes(x1: Int, y1: Int, x2: Int, y2: Int): Boolean = {\n var y = y1\n while (y <= y2) {\n var x = x1\n while (x <= x2) {\n if (a(y)(x) == 0) return true\n x += 1\n }\n y += 1\n }\n false\n }\n\n def rectIds(x1: Int, y1: Int, x2: Int, y2: Int) = {\n val ids = scala.collection.mutable.Set[Int]()\n var y = y1\n while (y <= y2) {\n var x = x1\n while (x <= x2) {\n ids += a(y)(x)\n x += 1\n }\n y += 1\n }\n ids\n }\n\n for (y <- 0 until dim) {\n var x = 0\n while (x < dim) {\n if (tl(y)(x)) {\n var dx = 0\n while (x + dx < dim && y + dx < dim && he(y)(x + dx)) {\n if (tr(y)(x + dx) && bl(y + dx)(x) && br(y + dx)(x + dx)) {\n var dy = 1\n var goodEdges = true\n while (dy < dx && goodEdges) {\n goodEdges = ve(y + dy)(x) && ve(y + dy)(x + dx) && he(y + dx)(x + dy)\n dy += 1\n }\n if (goodEdges && !holes(x + 1, y + 1, x + dx - 1, y + dx - 1)) {\n val ids = rectIds(x, y, x + dx, y + dx)\n println(ids.size)\n println(ids.mkString(\" \"))\n exit\n }\n }\n dx += 1\n }\n }\n x += 1\n }\n }\n\n println(\"NO\")\n}"}], "src_uid": "1157dd4e3cb68a4ab47c74ac15dacf32"} {"source_code": "import scala.io.StdIn.readLine\n\nobject task extends App {\n val t: Int = readLine.toInt\n for (i <- 1 to t) {\n val ln1 = readLine.split(\" \").map(_.toInt)\n val b: Int = ln1(0)\n val r: Int = ln1(1)\n val barrels = readLine.split(\" \").map(_.toLong).sorted\n val sum: Long = barrels.takeRight(r + 1).sum\n println(sum)\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val an = readLine().split(\" \").map(_.toInt).sorted(Ordering.Int.reverse)\n\n val ans = an.take(k + 1).foldLeft(0L)(_ + _)\n\n println(ans)\n }\n}\n"}, {"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, k = nextInt\n val as = nextLongs(n).sorted.reverse\n val res = as.take(k + 1).sum\n\n out.println(res)\n\n out.flush()\n }\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject task extends App {\n val t: Int = readLine.toInt\n for (i <- 1 to t) {\n val ln1 = readLine.split(\" \").map(_.toInt)\n val b: Int = ln1(0)\n val r: Int = ln1(1)\n val barrels = readLine.split(\" \").map(_.toInt).sorted\n val sum: Int = barrels.takeRight(r + 1).sum\n println(sum)\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject task extends App {\n val t: Int = readLine.toInt\n for (i <- 1 to t) {\n val ln1 = readLine.split(\" \").map(_.toInt)\n val b: Int = ln1(0)\n val r: Int = ln1(1)\n val barrels = readLine.split(\" \").map(_.toInt).sorted\n val sum: Int = barrels.take(r + 1).sum\n println(sum)\n }\n}\n"}], "src_uid": "08c797a7972fae99f8b64b47c53d8aeb"} {"source_code": "import scala.collection.mutable\n\nimport Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject C extends App {\n val io = new IO(System.in, System.out)\n\n val (n, q) = io.read[(Int, Int)]\n\n var unread = 0\n val Mark = Array.ofDim[Boolean](q + 1)\n\n val Q = Array.fill(n + 1)(new mutable.Queue[Int])\n val N = new mutable.Queue[(Int, Int)]\n\n var sequence = 0\n\n 1 to q foreach { _ =>\n val (op, v) = io.read[(Int, Int)]\n op match {\n case 1 =>\n sequence += 1\n Q(v).enqueue(sequence)\n N.enqueue((sequence, v))\n unread += 1\n case 2 =>\n while (Q(v).nonEmpty) {\n val el = Q(v).dequeue()\n unread -= 1\n Mark(el) = true\n }\n case 3 =>\n while (N.nonEmpty && N.front._1 <= v) {\n val (seq, el) = N.dequeue()\n if (!Mark(seq)) {\n Mark(seq) = true\n unread -= 1\n Q(el).dequeue()\n }\n }\n }\n\n io.write(unread + \"\\n\")\n }\n\n io.flush()\n io.close()\n}\n\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}", "positive_code": [{"source_code": "import scala.collection.mutable\n\nimport Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject C extends App {\n val io = new IO(System.in, System.out)\n\n val (n, q) = io.read[(Int, Int)]\n\n var unread = 0\n val Mark = Array.ofDim[Boolean](q + 1)\n\n val Q = Array.fill(n + 1)(new mutable.Queue[Int])\n val N = new mutable.Queue[(Int, Int)]\n\n var sequence = 0\n\n 1 to q foreach { _ =>\n val (op, v) = io.read[(Int, Int)]\n op match {\n case 1 =>\n sequence += 1\n Q(v).enqueue(sequence)\n N.enqueue((sequence, v))\n unread += 1\n case 2 =>\n while (Q(v).nonEmpty) {\n val el = Q(v).dequeue()\n unread -= 1\n Mark(el) = true\n }\n case 3 =>\n while (N.nonEmpty && N.front._1 <= v) {\n val (seq, el) = N.dequeue()\n if (!Mark(seq)) {\n Mark(seq) = true\n unread -= 1\n Q(el).dequeue()\n }\n }\n }\n\n io.write(unread + \"\\n\")\n }\n\n io.flush()\n io.close()\n}\n\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, q) = in.next().split(' ').map(_.toInt)\n val readMessages = Array.ofDim[Int](n)\n val newMessages = Array.ofDim[Int](n)\n var dict = Map.empty[Int, Int]\n val queries = in.take(q).map(_.split(' ').map(_.toInt)).toArray\n val inserts = queries.filter(_.head == 1).map(_.last - 1)\n val ans = queries.scanLeft(0, 0) {\n case(acc@(sum, read), Array(1, p)) =>\n newMessages(p - 1) += 1\n (sum + 1, read)\n case(acc@(sum, read), Array(2, p)) =>\n val nSum = sum - newMessages(p - 1)\n readMessages(p - 1) += newMessages(p - 1)\n newMessages(p - 1) = 0\n (nSum, read)\n case(acc@(sum, read), Array(3, p)) if p <= read => (sum, read)\n case(acc@(sum, read), Array(3, p)) =>\n val nSum = inserts.slice(read, p).groupBy(i => i).map(i => i._1 -> i._2.length).foldLeft(sum) {\n case (s, (index, count)) =>\n dict += (index -> (count + dict.getOrElse(index, 0)))\n val readThisTime = Math.max(dict(index) - readMessages(index), 0)\n newMessages(index) -= readThisTime\n readMessages(index) += readThisTime\n s - readThisTime\n }\n (nSum, Math.max(p, read))\n }.toList\n println(ans.tail.map(_._1).mkString(\"\\n\"))\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, q) = readInts(2)\n\n val result = new mutable.ArrayBuilder.ofInt\n\n val history = Array.fill(q){ 0 }\n val unreadCountByType, firstUnreadByType = Array.fill(n){ 0 }\n var historyPos, historyRead = 0\n var unreadCount = 0\n\n for (i <- 0 until q) {\n\n val Array(typ, _x) = readInts(2)\n val x = _x - 1\n\n typ match {\n\n case 1 =>\n history(historyPos) = x\n unreadCountByType(x) += 1\n historyPos += 1\n unreadCount += 1\n\n case 2 =>\n unreadCount -= unreadCountByType(x)\n unreadCountByType(x) = 0\n firstUnreadByType(x) = historyPos\n\n case 3 =>\n while (historyRead <= x) {\n val t = history(historyRead)\n if (historyRead >= firstUnreadByType(t)) {\n unreadCountByType(t) -= 1\n unreadCount -= 1\n }\n historyRead += 1\n }\n }\n\n result += unreadCount\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(result.result().mkString(\"\\n\"))\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n val io = new IO(System.in, System.out)\n\n val (n, q) = io.read[(Int, Int)]\n\n var unread = 0\n val Mark = Array.ofDim[Boolean](q + 1)\n\n val Q = Array.fill(n + 1)(new mutable.Queue[Int])\n val N = new mutable.Queue[(Int, Int)]\n\n var sequence = 0\n\n 1 to q foreach { _ =>\n val (op, v) = io.read[(Int, Int)]\n op match {\n case 1 =>\n sequence += 1\n Q(v).enqueue(sequence)\n N.enqueue((sequence, v))\n unread += 1\n case 2 =>\n while (Q(v).nonEmpty) {\n val el = Q(v).dequeue()\n unread -= 1\n Mark(el) = true\n }\n case 3 =>\n while (N.nonEmpty && N.front._1 <= v) {\n val (seq, el) = N.dequeue()\n if (!Mark(seq)) {\n Mark(seq) = true\n unread -= 1\n Q(el).dequeue()\n }\n }\n }\n\n io.write(unread + \"\\n\")\n }\n\n io.flush()\n io.close()\n}\n\n\n\n\n\n/***********************************[Scala I/O]*********************************************/\n\nobject Utils {\n import scala.collection.mutable\n import mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import Integral.Implicits._\n import scala.collection.immutable.NumericRange\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\nimport java.io._\nimport java.util.StringTokenizer\n\nimport Utils._\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeln(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}"}, {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n val io = new IO(System.in, System.out)\n\n val (n, q) = io.read[(Int, Int)]\n\n var unread = 0\n val Mark = Array.ofDim[Boolean](q + 1)\n\n val Q = Array.fill(n + 1)(new mutable.Queue[Int])\n val N = new mutable.Queue[(Int, Int)]\n\n var sequence = 0\n\n 1 to q foreach { _ =>\n val (op, v) = io.read[(Int, Int)]\n op match {\n case 1 =>\n sequence += 1\n Q(v).enqueue(sequence)\n N.enqueue((sequence, v))\n unread += 1\n case 2 =>\n while (Q(v).nonEmpty) {\n val el = Q(v).dequeue()\n unread -= 1\n Mark(el) = true\n }\n case 3 =>\n while (N.nonEmpty && N.front._1 <= v) {\n val (seq, el) = N.dequeue()\n if (!Mark(seq)) {\n Mark(seq) = true\n unread -= 1\n Q(el).dequeue()\n }\n }\n }\n\n io.write(unread + \"\\n\")\n }\n\n io.flush()\n io.close()\n}\n\nobject Utils {\n import scala.collection.mutable\n import mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import Integral.Implicits._\n import scala.collection.immutable.NumericRange\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._\nimport java.util.StringTokenizer\n\nimport Utils._\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}"}, {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n import FastIO._\n\n val (n, q) = read[(Int, Int)]\n\n var unread = 0\n val Mark = Array.ofDim[Boolean](q + 1)\n\n val Q = Array.fill(n + 1)(new mutable.Queue[Int])\n val N = new mutable.Queue[(Int, Int)]\n\n var sequence = 0\n\n 1 to q foreach { _ =>\n val (op, v) = read[(Int, Int)]\n op match {\n case 1 =>\n sequence += 1\n Q(v).enqueue(sequence)\n N.enqueue((sequence, v))\n unread += 1\n case 2 =>\n while (Q(v).nonEmpty) {\n val el = Q(v).dequeue()\n unread -= 1\n Mark(el) = true\n }\n case 3 =>\n while (N.nonEmpty && N.front._1 <= v) {\n val (seq, el) = N.dequeue()\n if (!Mark(seq)) {\n Mark(seq) = true\n unread -= 1\n Q(el).dequeue()\n }\n }\n }\n\n println(unread)\n }\n}\n\n\n\n/***********************************[Fast Scala I/O]*********************************************/\nobject FastIO extends IO(System.in, System.out)\n\nobject Utils {\n import scala.collection.mutable\n import mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import Integral.Implicits._\n import scala.collection.immutable.NumericRange\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n}\n\nimport java.io._\nimport java.util.StringTokenizer\nimport Utils._\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def println(obj: Any, more: Any*): this.type = {\n write(obj, more: _*)\n printer.println()\n this\n }\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.collection.mutable\n\nobject _366C extends App {\n val io = new IO(System.in, System.out)\n\n val (n, q) = io.read[(Int, Int)]\n\n var unread = 0\n val Mark = Array.ofDim[Boolean](q + 1)\n\n val Q = Array.fill(n + 1)(new mutable.Queue[Int])\n val N = new mutable.Queue[(Int, Int)]\n\n var sequence = 0\n\n 1 to q foreach { _ =>\n val (op, v) = io.read[(Int, Int)]\n op match {\n case 1 =>\n sequence += 1\n Q(v).enqueue(sequence)\n N.enqueue((sequence, v))\n unread += 1\n case 2 =>\n while (Q(v).nonEmpty) {\n val el = Q(v).dequeue()\n unread -= 1\n Mark(el) = true\n }\n case 3 =>\n while (N.nonEmpty && N.front._1 <= v) {\n val (seq, el) = N.dequeue()\n if (!Mark(seq)) {\n Mark(seq) = true\n unread -= 1\n Q(el).dequeue()\n }\n }\n }\n\n io.write(unread + \"\\n\")\n }\n\n io.flush()\n io.close()\n}\n\n\n\n\n\n/***********************************[Scala I/O]*********************************************/\n\nobject Utils {\n import scala.collection.mutable\n import mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import Integral.Implicits._\n import scala.collection.immutable.NumericRange\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\nimport java.io._\nimport java.util.StringTokenizer\n\nimport Utils._\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeln(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, q) = in.next().split(' ').map(_.toInt)\n val readMessages = Array.ofDim[Int](n)\n val newMessages = Array.ofDim[Int](n)\n var dict = Map.empty[Int, Int]\n val queries = in.take(q).map(_.split(' ').map(_.toInt)).toArray\n val inserts = queries.filter(_.head == 1).map(_.last - 1)\n val ans = queries.scanLeft(0, 0) {\n case(acc@(sum, read), Array(1, p)) =>\n newMessages(p - 1) += 1\n (sum + 1, read)\n case(acc@(sum, read), Array(2, p)) =>\n val nSum = sum - newMessages(p - 1)\n readMessages(p - 1) += newMessages(p - 1)\n newMessages(p - 1) = 0\n (nSum, read)\n case(acc@(sum, read), Array(3, p)) if p <= read => (sum, read)\n case(acc@(sum, read), Array(3, p)) =>\n println(inserts.slice(read, p).toList)\n val nSum = inserts.slice(read, p).groupBy(i => i).map(i => i._1 -> i._2.length).foldLeft(sum) {\n case (s, (index, count)) =>\n dict += (index -> (count + dict.getOrElse(index, 0)))\n val readThisTime = Math.max(dict(index) - readMessages(index), 0)\n newMessages(index) -= readThisTime\n readMessages(index) += readThisTime\n s - readThisTime\n }\n (nSum, Math.max(p, read))\n }.toList\n println(ans.tail.map(_._1).mkString(\"\\n\"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, q) = in.next().split(' ').map(_.toInt)\n val messages = Array.ofDim[Int](n)\n val newMessages = Array.ofDim[Int](n)\n val ans = in.take(q).map(_.split(' ').map(_.toInt)).scanLeft(0, 0, List.empty[Int]) {\n case((sum, read, list), Array(1, p)) =>\n messages(p - 1) += 1\n newMessages(p - 1) += 1\n (sum + 1, read, (p - 1) :: list)\n case((sum, read, list), Array(2, p)) =>\n val nSum = sum - newMessages(p - 1)\n newMessages(p - 1) = 0\n (nSum, read, list)\n case((sum, read, list), Array(3, p)) =>\n if (read >= p)\n (sum, read, list)\n else {\n val nSum = list.takeRight(read - p).groupBy(i => i).foldLeft(0) {\n case (s, (index, count)) if (messages(index) - newMessages(index)) >= count.length => s\n case (s, (index, count)) =>\n val read = messages(index) - newMessages(index)\n val left = count.length - read\n newMessages(index) += left\n s + left\n }\n (nSum, p, list.dropRight(read - p))\n }\n }.toList\n println(ans.tail.map(_._1).mkString(\"\\n\"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, q) = in.next().split(' ').map(_.toInt)\n val messages = Array.ofDim[Int](n)\n val newMessages = Array.ofDim[Int](n)\n val ans = in.take(q).map(_.split(' ').map(_.toInt)).scanLeft(0, 0, List.empty[Int]) {\n case((sum, read, list), Array(1, p)) =>\n messages(p - 1) += 1\n newMessages(p - 1) += 1\n (sum + 1, read, (p - 1) :: list)\n case((sum, read, list), Array(2, p)) =>\n val nSum = sum - newMessages(p - 1)\n newMessages(p - 1) = 0\n (nSum, read, list)\n case((sum, read, list), Array(3, p)) =>\n if (read >= p)\n (sum, read, list)\n else {\n val nSum = list.takeRight(read - p).groupBy(i => i).foldLeft(sum) {\n case (s, (index, count)) if (messages(index) - newMessages(index)) >= count.length => s\n case (s, (index, count)) =>\n val read = messages(index) - newMessages(index)\n val left = count.length - read\n newMessages(index) -= left\n s - left\n }\n (nSum, p, list.dropRight(read - p))\n }\n }.toList\n println(ans.tail.map(_._1).mkString(\"\\n\"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, q) = in.next().split(' ').map(_.toInt)\n val messages = Array.ofDim[Int](n)\n val newMessages = Array.ofDim[Int](n)\n val ans = in.take(q).map(_.split(' ').map(_.toInt)).scanLeft(0, 0, List.empty[Int]) {\n case((sum, read, list), Array(1, p)) =>\n messages(p - 1) += 1\n newMessages(p - 1) += 1\n (sum + 1, read, (p - 1) :: list)\n case((sum, read, list), Array(2, p)) =>\n val nSum = sum - newMessages(p - 1)\n newMessages(p - 1) = 0\n (nSum, read, list)\n case((sum, read, list), Array(3, p)) =>\n if (read >= p)\n (sum, read, list)\n else {\n val nSum = list.takeRight(p - read).groupBy(i => i).foldLeft(sum) {\n case (s, (index, count)) if (messages(index) - newMessages(index)) >= count.length => s\n case (s, (index, count)) =>\n val left = count.length - messages(index) + newMessages(index)\n newMessages(index) -= left\n s - left\n }\n (nSum, p, list.dropRight(read - p))\n }\n }.toList\n println(ans.tail.map(_._1).mkString(\"\\n\"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, q) = in.next().split(' ').map(_.toInt)\n val messages = Array.ofDim[Int](n)\n val newMessages = Array.ofDim[Int](n)\n val ans = in.take(q).map(_.split(' ').map(_.toInt)).scanLeft(0, 0, List.empty[Int]) {\n case((sum, read, list), Array(1, p)) =>\n messages(p - 1) += 1\n newMessages(p - 1) += 1\n (sum + 1, read, (p - 1) :: list)\n case((sum, read, list), Array(2, p)) =>\n val nSum = sum - newMessages(p - 1)\n newMessages(p - 1) = 0\n (nSum, read, list)\n case((sum, read, list), Array(3, p)) =>\n if (read >= p)\n (sum, read, list)\n else {\n val nSum = list.takeRight(read - p).groupBy(i => i).foldLeft(0) {\n case (s, (index, count)) if (messages(index) - newMessages(index)) >= count.length => s\n case (s, (index, count)) =>\n val read = messages(index) - newMessages(index)\n val left = count.length - read\n newMessages(index) -= left\n s + left\n }\n (nSum, p, list.dropRight(read - p))\n }\n }.toList\n println(ans.tail.map(_._1).mkString(\"\\n\"))\n}\n"}, {"source_code": "import scala.collection.immutable.Queue\nimport scala.collection.mutable\nimport scala.io.StdIn._\n\nobject C extends App {\n val Array(n, q) = readLine() split \" \" map (_.toInt)\n\n var unread = 0\n val Q = new mutable.HashMap[Int, mutable.HashSet[Int]]().withDefaultValue(new mutable.HashSet[Int])\n val N = new scala.collection.mutable.Queue[(Int, Int)]\n\n var sequence = 0\n\n for (_ <- 1 to q) {\n val Array(op, v) = readLine() split \" \" map (_.toInt)\n\n if (op == 1) {\n sequence += 1\n Q(v) += sequence\n N.enqueue((sequence, v))\n unread += 1\n } else if (op == 2) {\n unread -= Q(v).size\n Q(v).clear()\n } else {\n while (N.nonEmpty && N.head._1 <= v) {\n val (seq, el) = N.dequeue()\n if (Q(el).remove(seq)) unread -= 1\n }\n }\n\n println(unread)\n }\n\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject C extends App {\n val Array(n, q) = readLine() split \" \" map (_.toInt)\n\n var unread = 0\n val Q = Array.fill(n + 1)(new mutable.HashSet[Int])\n val N = new mutable.Queue[(Int, Int)]\n\n var sequence = 0\n\n for (_ <- 1 to q) {\n val Array(op, v) = readLine() split \" \" map (_.toInt)\n op match {\n case 1 =>\n sequence += 1\n Q(v) += sequence\n N.enqueue((sequence, v))\n unread += 1\n case 2 =>\n unread -= Q(v).size\n case 3 =>\n while (N.nonEmpty && N.front._1 <= v) {\n val (seq, el) = N.dequeue()\n if (Q(el).remove(seq)) unread -= 1\n }\n }\n\n println(unread)\n }\n\n\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject C extends App {\n val io = new IO(System.in, System.out)\n\n val (n, q) = io.read[(Int, Int)]\n\n var unread = 0\n val Mark = Array.ofDim[Boolean](q + 1)\n\n val Q = Array.fill(n + 1)(new mutable.Queue[Int])\n val N = new mutable.Queue[(Int, Int)]\n\n var sequence = 0\n\n 1 to q foreach { _ =>\n val (op, v) = io.read[(Int, Int)]\n op match {\n case 1 =>\n sequence += 1\n Q(v).enqueue(sequence)\n N.enqueue((sequence, v))\n unread += 1\n case 2 =>\n while (Q(v).nonEmpty) {\n val el = Q(v).dequeue()\n unread -= 1\n Mark(el) = true\n }\n case 3 =>\n while (N.nonEmpty && N.front._1 <= v) {\n val (seq, el) = N.dequeue()\n if (!Mark(seq)) {\n Mark(seq) = true\n unread -= 1\n Q(el).dequeue()\n }\n }\n }\n\n io.write(unread + \"\\n\")\n }\n\n}\n\n\n/***********************************[Scala I/O]*********************************************/\nobject Utils {\n import scala.collection.mutable\n import mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import Integral.Implicits._\n import scala.collection.immutable.NumericRange\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport Utils._\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}"}], "src_uid": "a5e724081ad84f88813bb4de23a8230e"} {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val in = new Array[Boolean](1e6.toInt + 1)\n var state = 0\n var ans = 0\n for (i <- 0 until n) {\n val sign = if (next == \"+\") 1 else 0\n val id = nextInt\n if (sign == 1) {\n in(id) = true\n state += 1\n } else {\n if (in(id)) {\n state -= 1\n in(id) = false\n } else {\n ans += 1\n }\n }\n ans = Math.max(ans, state)\n }\n out.println(ans)\n return 0\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject CF567B extends App {\n val n = readInt()\n\n implicit def intTimes(i: Int) = new {\n def times(fn: => Unit) = (1 to i) foreach (x => fn)\n }\n\n val present = mutable.Set[Int]()\n var result = 0\n var state = 0\n n.times {\n val line = readLine()\n\n val operation = line.split(\" \")(0)\n val id = line.split(\" \")(1).toInt\n\n operation match {\n case \"+\" =>\n present += id\n state += 1\n result = Math.max(result, state)\n case \"-\" =>\n if (present.contains(id)) {\n present -= id\n state -= 1\n }\n else result += 1\n }\n }\n\n println(result)\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn.readLine\n\n\nobject Main {\n\n sealed trait Log\n case class In(i: Int) extends Log\n case class Out(i: Int) extends Log\n case class R(who: Set[Int], cm: Int)\n // Document: http://www.scala-lang.org/api/current/#package\n // -----------------------------------------------------------------------------\n\n def main(args: Array[String]) : Unit = {\n val n = readLine().toInt\n val x = (1 to n).map(_ => {\n val line = readLine.split(\" \")\n val is_in = line(0) == \"+\"\n val who = line(1).toInt\n if(is_in) In(who)\n else Out(who)\n })\n val ret = x.foldLeft(R(Set[Int](),0))((r, c) => {\n c match {\n case In(i) => R(r.who + i, r.cm max (r.who.size+1))\n case Out(i) if r.who contains i => R(r.who - i, r.cm)\n case Out(i) => R(r.who, r.cm + 1)\n }\n }).cm\n println(ret)\n }\n}\n"}, {"source_code": "object B567 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = Array.fill(n){\n val tl = tokenizeLine\n val status = tl.nextToken\n val user = tl.nextToken.toInt\n (status, user)\n }\n val set = cu.Set.empty[Int]\n val pre = cu.Set.empty[Int]\n for(i <- 0 until n) {\n val status = in(i)._1\n val user = in(i)._2\n if(status == \"-\") {\n if(set.contains(user))\n set.remove(user)\n else\n pre.add(user)\n } else {\n set.add(user)\n }\n }\n var res = pre.size\n for(i <- 0 until n) {\n val status = in(i)._1\n val user = in(i)._2\n if(status == \"-\") {\n pre.remove(user)\n } else {\n pre.add(user)\n }\n res = math.max(res, pre.size)\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "\nimport scala.collection.immutable.HashMap\nimport scala.collection.mutable.ListBuffer\n\n/**\n * \n *\n * @author pvasilyev\n * @since 14 Apr 2016\n */\nobject Problem151 extends App {\n val n: Int = scala.io.StdIn.readInt()\n var map: Map[String, Boolean] = new HashMap[String, Boolean]()\n var listOfOut = new ListBuffer[String]()\n var max: Int = 0\n var curr: Int = 0\n for (i <- 0 until n) {\n val Array(in, numAsString) = scala.io.StdIn.readLine().split(\" \")\n curr = max\n if (\"-\".equals(in)) {\n if (map contains numAsString) {\n map -= numAsString\n } else {\n curr += 1\n listOfOut += numAsString\n }\n } else {\n if (listOfOut isEmpty) {\n curr = map.size + 1\n } else {\n listOfOut.remove(0)\n }\n map += (numAsString -> true)\n }\n max = Math.max(max, curr)\n }\n\n println(max)\n}\n"}, {"source_code": "import io.StdIn._\nimport scala.collection.mutable._\n\nobject Solution {\n\n def main(args: Array[String]) {\n val n = readInt()\n val lib = Set[String]()\n val logs = (1 to n).map(_=>readLine().split(\" \"))\n logs.zipWithIndex\n .filter { case (l, i) => l(0) == \"-\" && !logs.take(i).exists(el => el(1) == l(1)) }\n .foreach { case (l, _) => lib.add(l(1)) }\n\n var res = lib.size\n\n logs.foreach { log =>\n if (log(0) == \"+\") {\n lib.add(log(1))\n } else {\n lib.remove(log(1))\n }\n res = Math.max(res, lib.size)\n }\n\n println(res)\n\n }\n\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util.control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _567B extends CodeForcesApp[Int]({scanner => import scanner._\n val n = nextInt\n val library = mutable.Set.empty[Int]\n var ans = 0\n for {_ <- 1 to n} {\n val (isEnter, id) = (next == \"+\", nextInt)\n if (isEnter) {\n require(library.add(id))\n ans = ans max library.size\n } else if (!library.remove(id)) {\n ans += 1\n }\n debug(isEnter, id, library, ans)\n }\n ans\n})\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n import scala.collection.mutable.{Map => Dict}\n final def isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def counter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val n = readInt()\n val states = Array.ofDim[Boolean](1000001)\n val capacity = Array.ofDim[Int](n)\n\n var count = 0\n\n for (i <- capacity.indices) {\n val input = readLine().split(\" \")\n val event = input(0)\n val id = input(1).toInt\n\n event match {\n case \"+\" =>\n states(id) = true\n count += 1\n case \"-\" if states(id) =>\n states(id) = false\n count -= 1\n case \"-\" if !states(id) =>\n for (j <- 0 to i) capacity(j) += 1\n }\n\n capacity(i) += count\n }\n\n println(capacity.max)\n\n}\n\n"}, {"source_code": "import java.util.Scanner\nimport scala.annotation._\nimport scala.math._\n\nobject Solution {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n\n val n = scanner.nextInt\n\n val idSet = Set()\n\n var ans = 0\n\n @tailrec\n def iter(time: Int, idSet: Set[Int], ans: Int): Int = {\n if (time > n) ans\n else {\n val x = scanner.next\n val id = scanner.nextInt\n\n x match {\n case \"-\" =>\n if (idSet.contains(id)) {\n iter(time+1, idSet-id, ans)\n } else {\n iter(time+1, idSet, ans+1)\n }\n case \"+\" =>\n val nextIdSet = idSet+id\n iter(time+1, nextIdSet, max(ans, nextIdSet.size))\n }\n }\n }\n\n println(iter(1, Set[Int](), 0))\n }\n}\n"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject BerlandLibrary {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n \n def solve(events: List[String]) : Int = {\n def go(events: List[String], inroom: Set[String], cap: Int) : Int = \n events match {\n case Nil => cap\n case h :: tail =>\n if (h(0) == '+') {\n go(tail, inroom + h.split(' ')(1), Math.max(cap, inroom.size + 1))\n } else {\n val reg = h.split(' ')(1)\n if (inroom.contains(reg)) {\n go(tail, inroom - reg, cap)\n } else {\n go(tail,inroom,cap+1)\n }\n }\n \n }\n go(events,Set(),0)\n }\n \n def main(args: Array[String]) {\n val n = readInt\n val events = for {\n i <- 1 to n\n event = readLine\n } yield event\n println(solve(events.toList))\n }\n \n}"}], "negative_code": [{"source_code": "\nimport java.util\n\nimport scala.collection.immutable.HashMap\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.parallel.mutable\n\n/**\n * \n *\n * @author pvasilyev\n * @since 14 Apr 2016\n */\nobject Problem151 extends App {\n val n: Int = scala.io.StdIn.readInt()\n var map: Map[String, Boolean] = new HashMap[String, Boolean]()\n var listOfOut = new ListBuffer[String]()\n var max: Int = 0\n var curr: Int = 0\n for (i <- 0 until n) {\n val Array(in, numAsString) = scala.io.StdIn.readLine().split(\" \")\n if (\"-\".equals(in)) {\n if (map contains numAsString) {\n map -= numAsString\n } else {\n max += 1\n listOfOut += numAsString\n }\n } else {\n if (listOfOut isEmpty) {\n max += 1\n } else {\n listOfOut.remove(0)\n }\n map += (numAsString -> true)\n }\n }\n\n println(max)\n}\n"}, {"source_code": "\nimport java.util\n\nimport scala.collection.immutable.HashMap\n\n/**\n * \n *\n * @author pvasilyev\n * @since 14 Apr 2016\n */\nobject Problem151 extends App {\n val n: Int = scala.io.StdIn.readInt()\n var map: Map[String, Boolean] = new HashMap[String, Boolean]()\n var list: util.LinkedList[String] = new util.LinkedList[String]()\n var max: Int = 0\n for (i <- 0 until n) {\n val Array(in, numAsString) = scala.io.StdIn.readLine().split(\" \")\n if (\"-\".equals(in)) {\n if (map.contains(numAsString)) {\n map -= numAsString\n } else {\n map += (numAsString -> false)\n list.push(numAsString)\n }\n } else {\n if (map.contains(numAsString)) {\n map += (numAsString -> true)\n } else {\n var bCont = true\n while (!list.isEmpty && bCont) {\n val s = list.pop()\n map -= s\n bCont = false\n }\n }\n }\n max = Math.max(max, map.size)\n }\n\n println(max)\n}\n"}, {"source_code": "\nimport scala.collection.immutable.HashMap\n\n/**\n * \n *\n * @author pvasilyev\n * @since 14 Apr 2016\n */\nobject Problem151 extends App {\n val n: Int = scala.io.StdIn.readInt()\n var map: Map[String, Boolean] = new HashMap[String, Boolean]()\n var max: Int = 0\n for (i <- 0 until n) {\n val Array(in, numAsString) = scala.io.StdIn.readLine().split(\" \")\n if (\"-\".equals(in)) {\n if (map.contains(numAsString)) {\n map -= numAsString\n } else {\n map += (numAsString -> false)\n }\n } else {\n map += (numAsString -> true)\n }\n max = Math.max(max, map.size)\n }\n\n println(max)\n}\n"}, {"source_code": "import io.StdIn._\nimport scala.collection.mutable._\n\nobject Solution {\n\n def main(args: Array[String]) {\n val n = readInt()\n val lib = Set[String]()\n val logs = (1 to n).map(_=>readLine().split(\" \"))\n logs.zipWithIndex\n .filter { case (l, i) => l(0) == \"-\" && !logs.take(i).contains(l) }\n .foreach { case (l, _) => lib.add(l(1)) }\n\n var res = lib.size\n\n logs.foreach { log =>\n if (log(0) == \"+\") {\n lib.add(log(1))\n } else {\n lib.remove(log(1))\n }\n res = Math.max(res, lib.size)\n }\n\n println(res)\n\n }\n\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util.control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _567B extends CodeForcesApp[Int]({scanner => import scanner._\n val n = nextInt\n val library = mutable.Set.empty[Int]\n var ans = Int.MinValue\n for (i <- 1 to n) {\n val (isEnter, id) = (next == \"+\", nextInt)\n if (isEnter) {\n library += id\n } else if (library(id)) {\n library -= id\n } else {\n library += id\n }\n ans = ans max library.size\n }\n ans\n})\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n import scala.collection.mutable.{Map => Dict}\n final def isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def counter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util.control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _567B extends CodeForcesApp[Int]({scanner => import scanner._\n val n = nextInt\n val library = mutable.Set.empty[Int]\n var ans = 0\n for {_ <- 1 to n} {\n val (isEnter, id) = (next == \"+\", nextInt)\n if (isEnter) {\n library += id\n } else if (library(id)) {\n library -= id\n } else {\n ans = ans + 1\n library += id\n }\n ans = ans max library.size\n //debug(isEnter, id, library, ans)\n }\n ans\n})\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n import scala.collection.mutable.{Map => Dict}\n final def isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def counter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0\n}\n"}], "src_uid": "6cfd3b0a403212ec68bac1667bce9ef1"} {"source_code": "import scala.collection.mutable\n\nobject And extends App {\n var input = List.empty[String]\n// var input = \"4 3\\n7 3 2 1\".split(\"\\n\")\n\n def readline() = {\n if(input.nonEmpty) {\n val next = input.head\n input = input.tail\n next\n } else {\n scala.io.StdIn.readLine()\n }\n }\n\n val dims = readline().split(\" \").map(_.toInt)\n\n val numbers = dims(0)\n val x = dims(1)\n\n val as = readline().split(\" \").map(_.toInt)\n\n val a_set = new mutable.BitSet()\n val and_set = new mutable.BitSet()\n\n var minSteps = 3\n def updateSteps(steps: Int): Unit = {\n if(minSteps > steps) {\n minSteps = steps\n if(minSteps == 0) {\n println(\"0\")\n sys.exit(0)\n }\n }\n }\n for(a <- as) {\n val a_and = a & x\n if(a_set.contains(a_and) || and_set.contains(a)) {\n updateSteps(1)\n } else if(and_set.contains(a_and)) {\n updateSteps(2)\n } else {\n and_set += a_and\n }\n\n if(a_set.contains(a)) {\n updateSteps(0)\n } else {\n a_set += a\n }\n }\n\n if(minSteps == 3)\n println(-1)\n else\n println(minSteps)\n}\n", "positive_code": [{"source_code": "object And {\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val arr = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val arr_set = arr.toSet\n\n if (arr_set.size < arr.length)\n println(0)\n else if (arr.exists{elm =>\n val andX = elm & x\n\n elm != andX && arr_set.contains(andX)\n })\n println(1)\n else {\n val arrAndX = arr.map(_ & x)\n if (arrAndX.length > arrAndX.toSet.size)\n println(2)\n else\n println(-1)\n }\n }\n\n}"}], "negative_code": [{"source_code": "object And {\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val arr = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val arr_set = arr.toSet\n\n if (arr_set.size < arr.length)\n println(0)\n else if (arr.exists{elm =>\n val andX = elm & x\n\n elm != andX && arr_set.contains(andX)\n })\n println(1)\n else\n println(-1)\n }\n\n}"}, {"source_code": "import scala.collection.mutable\n\nobject And extends App {\n var input = \"3 7\\n1 2 3\".split('\\n')\n\n def readline() = {\n if(input.nonEmpty) {\n val next = input.head\n input = input.tail\n next\n } else {\n scala.io.StdIn.readLine()\n }\n }\n\n val dims = readline().split(\" \").map(_.toInt)\n\n val numbers = dims(0)\n val x = dims(1)\n\n val as = readline().split(\" \").map(_.toInt)\n\n val a_set = new mutable.BitSet()\n val and_set = new mutable.BitSet()\n\n var minSteps = 3\n def updateSteps(steps: Int): Unit = {\n if(minSteps > steps) {\n minSteps = steps\n if(minSteps == 0) {\n println(\"0\")\n sys.exit(0)\n }\n }\n }\n for(a <- as) {\n val a_and = a & x\n if(a_set.contains(a_and)) {\n updateSteps(1)\n } else if(and_set.contains(a_and)) {\n updateSteps(2)\n } else {\n and_set += a_and\n }\n\n if(a_set.contains(a)) {\n updateSteps(0)\n } else {\n a_set += a\n }\n }\n\n if(minSteps == 3)\n println(-1)\n else\n println(minSteps)\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject And extends App {\n var input = List.empty[String]\n\n def readline() = {\n if(input.nonEmpty) {\n val next = input.head\n input = input.tail\n next\n } else {\n scala.io.StdIn.readLine()\n }\n }\n\n val dims = readline().split(\" \").map(_.toInt)\n\n val numbers = dims(0)\n val x = dims(1)\n\n val as = readline().split(\" \").map(_.toInt)\n\n val a_set = new mutable.BitSet()\n val and_set = new mutable.BitSet()\n\n var minSteps = 3\n def updateSteps(steps: Int): Unit = {\n if(minSteps > steps) {\n minSteps = steps\n if(minSteps == 0) {\n println(\"0\")\n sys.exit(0)\n }\n }\n }\n for(a <- as) {\n val a_and = a & x\n if(a_set.contains(a_and)) {\n updateSteps(1)\n } else if(and_set.contains(a_and)) {\n updateSteps(2)\n } else {\n and_set += a_and\n }\n\n if(a_set.contains(a)) {\n updateSteps(0)\n } else {\n a_set += a\n }\n }\n\n if(minSteps == 3)\n println(-1)\n else\n println(minSteps)\n}\n"}], "src_uid": "f4bb0b8f285b0c8cbaf469964505cc56"} {"source_code": "\nimport java.io._\nimport java.util.ArrayList\n\nobject C_DuffAndWeightLifting_2 {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(t3.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = br.readLine().trim().split(\" \")\n val number = line1(0).toInt\n val line2 = br.readLine().trim().split(\" \")\n// val ww = new Array[Int](number)\n// for (i <- 0 until number) {\n// ww(i) = line2(i).toInt\n// }\n //---------------------------- parameters reading end --------------------------------\n \n val con = Array.fill[Int](1001000)(0)\n \n for (i <- line2) {\n con(i.toInt) += 1\n }\n \n var ones = 0\n var rest = 0\n for (i <- con) {\n val vv = i + rest\n if (vv % 2 == 1) ones += 1\n rest = (vv / 2).toInt\n }\n println(ones)\n \n }\n \n//========================= samples ======================== \nval sa1 = \"\"\"\n\n\"\"\"\n\n//========================= samples end ==================== \n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toLong\n val maxn = (1000001l * 2).toInt\n val buffer = Array.ofDim[Int](maxn)\n val data = in.next().split(\" \").map(_.toInt)\n data.foreach { i => buffer(i) += 1}\n\n println(buffer.indices.foldLeft(0) {\n case(acc, i) =>\n if (buffer(i) > 0)\n buffer(i + 1) += buffer(i) / 2\n acc + (if (buffer(i) % 2 == 1) 1 else 0)\n })\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C326A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C326A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val max_n = 1001000\n val x = Array.fill[Int](max_n)(0)\n REP(n) { _ =>\n val u = ni()\n x(u) += 1\n }\n\n var count = 0\n REP(max_n-1) { i =>\n x(i+1) += x(i) / 2\n count += x(i) % 2\n }\n out.println(count)\n }\n}\n"}, {"source_code": "object A extends App {\n\n final class BinHeap(limit: Int) {\n\n type T = Int\n @inline private def cmp(a: T, b: T): Boolean = a < b\n\n private var size = 0\n private val data = Array.ofDim[T](limit)\n\n @inline private def parent(i: Int) = i >> 1\n\n def isEmpty(): Boolean = size == 0\n\n def peek(): T = {\n assert(size > 0)\n data(0)\n }\n\n def add(x: T) {\n var i = size\n size += 1\n while (i > 0 && cmp(x, data(parent(i)))) {\n val p = parent(i)\n data(i) = data(p)\n i = p\n }\n data(i) = x\n }\n\n def poll(): T = {\n assert(size > 0)\n val result = data(0)\n size -= 1\n if (size > 0) {\n data(0) = data(size)\n heapify(0)\n }\n result\n }\n\n private def heapify(i: Int) {\n val l = i << 1\n val r = l + 1\n var top = if (l < size && cmp(data(l), data(i))) l else i\n if (r < size && cmp(data(r), data(top))) top = r\n if (top != i) {\n val tmp = data(i)\n data(i) = data(top)\n data(top) = tmp\n heapify(top)\n }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val ws = readInts(n)\n\n val heap = new BinHeap(n)\n for (w <- ws) heap.add(w)\n\n var res = 0\n while (!heap.isEmpty) {\n val w = heap.poll()\n if (!heap.isEmpty && w == heap.peek) {\n heap.poll()\n heap.add(w + 1)\n } else res += 1\n }\n\n println(res)\n}\n"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val ws = readInts(n)\n\n val pq = new java.util.PriorityQueue[Int]()\n val cnts = Array.fill(ws.max * 2 + 1000) { 0 }\n\n for (w <- ws) cnts(w) += 1\n\n var res = 0\n for (i <- cnts.indices) {\n val c = cnts(i)\n if (c > 0) {\n res += c & 1\n cnts(i + 1) += (c >> 1)\n }\n }\n\n println(res)\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject C_DuffAndWeightLifting {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(t3.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = br.readLine().trim().split(\" \")\n val number = line1(0).toInt\n val tok = new StringTokenizer(br.readLine(), \" \")\n //---------------------------- parameters reading end --------------------------------\n \n val con = new Array[Boolean](1001000)\n \n while (tok.hasMoreTokens()) {\n var pos = tok.nextToken().toInt\n while (con(pos)) {\n con(pos) = false\n pos += 1\n }\n con(pos) = true\n }\n \n var ones = 0\n for (i <- con) {\n if (i) {\n ones += 1\n }\n }\n println(ones)\n \n }\n \n//========================= samples ======================== \nval sa1 = \"\"\"\n\n\"\"\"\n\n//========================= samples end ==================== \n}"}, {"source_code": "\n\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject C_DuffAndWeightLifting_2 {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(t3.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = br.readLine().trim().split(\" \")\n val number = line1(0).toInt\n val line2 = br.readLine()\n val tok = new StringTokenizer(line2, \" \")\n// val ww = new Array[Int](number)\n// for (i <- 0 until number) {\n// ww(i) = line2(i).toInt\n// }\n //---------------------------- parameters reading end --------------------------------\n \n val con = Array.fill[Int](1001000)(0)\n \n while (tok.hasMoreTokens()) {\n val ind = tok.nextToken().toInt\n con(ind) += 1\n }\n \n var ones = 0\n var rest = 0\n for (i <- con) {\n val vv = i + rest\n if (vv % 2 == 1) ones += 1\n rest = (vv / 2).toInt\n }\n println(ones)\n \n }\n \n//========================= samples ======================== \nval sa1 = \"\"\"\n35\n0 0 298 0 0 0 0 0 689063 65442 0 984598 2054 43668 0 369 0 2054 0 996220 0 16327 369 0 996220 0 0 0 4693 2054 348 0 118 0 0\n\"\"\"\n\n//========================= samples end ==================== \n}"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\n\nobject C_DuffAndWeightLifting {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(t3.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = br.readLine().trim().split(\" \")\n val number = line1(0).toInt\n val line2 = br.readLine().trim().split(\" \")\n val ww = new Array[Int](number)\n for (i <- 0 until number) {\n ww(i) = line2(i).toInt\n }\n //---------------------------- parameters reading end --------------------------------\n \n val con = new Array[Boolean](1001000)\n \n for (i <- ww) {\n var pos = i\n while (con(pos)) {\n con(pos) = false\n pos += 1\n }\n con(pos) = true\n }\n \n var ones = 0\n for (i <- con) {\n if (i) {\n ones += 1\n }\n }\n println(ones)\n \n }\n \n//========================= samples ======================== \nval sa1 = \"\"\"\n\n\"\"\"\n\n//========================= samples end ==================== \n}"}], "negative_code": [{"source_code": "object A extends App {\n\n final class BinHeap(limit: Int) {\n\n type T = Int\n @inline private def cmp(a: T, b: T): Boolean = a < b\n\n private var size = 0\n private val data = Array.ofDim[T](limit)\n\n @inline private def parent(i: Int) = i >> 1\n\n def isEmpty(): Boolean = size == 0\n\n def peek(): T = {\n assert(size > 0)\n data(0)\n }\n\n def add(x: T) {\n var i = size\n size += 1\n while (i > 0 && cmp(x, data(parent(i)))) {\n val p = parent(i)\n data(i) = data(p)\n i = p\n }\n data(i) = x\n }\n\n def poll(): T = {\n assert(size > 0)\n val result = data(0)\n size -= 1\n if (size > 0) {\n data(0) = data(size)\n heapify(0)\n }\n result\n }\n\n private def heapify(i: Int) {\n val l = i << 1\n val r = l + 1\n var top = if (l < size && cmp(data(l), data(r))) l else i\n if (r < size && cmp(data(r), data(top))) top = r\n if (top != i) {\n val tmp = data(i)\n data(i) = data(top)\n data(top) = tmp\n heapify(top)\n }\n }\n\n }\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val ws = readInts(n)\n\n val heap = new BinHeap(n)\n for (w <- ws) heap.add(w)\n\n var res = 0\n while (!heap.isEmpty) {\n val w = heap.poll()\n if (!heap.isEmpty && w == heap.peek) {\n heap.poll()\n heap.add(w + 1)\n } else res += 1\n }\n\n println(res)\n}\n"}], "src_uid": "089eea1841ef10064647e61094c374fd"} {"source_code": "import java.util.StringTokenizer\n\nimport scala.io.StdIn\n\nobject C extends App with Reader {\n read()\n val n = int()\n val s1 = StdIn.readLine().toCharArray.map(_ == '1')\n val s2 = StdIn.readLine().toCharArray.map(_ == '1')\n\n var res = 0\n for (i <- 0 until n) {\n if (s1(i) != s2(i)) {\n if ((i + 1 < n) && (s1(i) != s1(i+1)) && (s1(i+1) != s2(i+1))) {\n s1(i) = !s1(i)\n s1(i+1) = !s1(i+1)\n res += 1\n } else {\n s1(i) = !s1(i)\n res += 1\n }\n }\n }\n\n println(res)\n}\n\ntrait Reader {\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(StdIn.readLine()) }\n def int() = st.nextToken().toInt\n def long() = st.nextToken().toLong\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n val sc = new InputReader(System.in)\n\n def solve(): Unit = {\n val N = ni()\n val A, B = ns(N)\n\n var ans = 0\n rep(N) { i =>\n if (A(i) != B(i)) ans += 1\n }\n\n var i = 0\n while (i < N - 1) {\n if (A(i) != B(i) && A(i + 1) != B(i + 1) && A(i) != A(i + 1)) {\n ans -= 1\n i += 1\n }\n i += 1\n }\n\n out.println(ans)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "object C1037 {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val n = stdin.readInt()\n val from = stdin.readLine()\n val to = stdin.readLine()\n var i = 0\n var ans = 0\n while (i < n){\n if (i + 1 < n){\n if (from(i) != to(i) && from(i+1) != to(i+1) && from(i) != from(i+1)) {\n ans += 1\n i += 1\n } else {\n if (from(i) != to(i)) ans += 1\n }\n } else {\n if (from(i) != to(i)) ans += 1\n }\n i += 1\n }\n print(ans)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject C extends App {\n\n case class Point(x: Int, segId: Int, isBegin: Boolean)\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val a = in.next\n val b = in.next\n var ans = 0\n var i = 0\n while (i < n) {\n if (i == n - 1) {\n if (a(i) != b(i))\n ans += 1\n } else {\n if (a(i) != b(i) && !(a(i) == b(i + 1) && a(i + 1) == b(i)))\n ans += 1\n else if (a(i) != b(i) && (a(i) == b(i + 1) && a(i + 1) == b(i))) {\n ans += 1\n i += 1\n }\n }\n i += 1\n }\n println(ans)\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toInt\n }\n\n def nextLong: Double = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}], "negative_code": [{"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n val sc = new InputReader(System.in)\n\n def solve(): Unit = {\n val N = ni()\n val A, B = ns(N)\n\n var ans = 0\n rep(N) { i =>\n if (A(i) != B(i)) ans += 1\n }\n\n var i = 0\n while (i < N - 1) {\n if (A(i) != B(i) && A(i + 1) != B(i + 1)) {\n ans -= 1\n i += 1\n }\n i += 1\n }\n\n out.println(ans)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "object C1037 {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val n = stdin.readInt()\n val from = stdin.readLine()\n val to = stdin.readLine()\n var i = 0\n var ans = 0\n while (i < n){\n if (i + 1 < n){\n if (from(i) != to(i) && from(i+1) != to(i+1) && from(i) != to(i)) {\n ans += 1\n i += 1\n } else {\n if (from(i) != to(i)) ans += 1\n }\n } else {\n if (from(i) != to(i)) ans += 1\n }\n i += 1\n }\n print(ans)\n }\n}\n"}, {"source_code": "object C1037 {\n def main(args: Array[String]): Unit = {\n val stdin = scala.io.StdIn\n val n = stdin.readInt()\n val from = stdin.readLine()\n val to = stdin.readLine()\n var i = 0\n var ans = 0\n while (i < n){\n if (i + 1 < n){\n if (from(i) != to(i) && from(i+1) != to(i+1)) {\n ans += 1\n i += 1\n } else {\n if (from(i) != to(i)) ans += 1\n }\n } else {\n if (from(i) != to(i)) ans += 1\n }\n i += 1\n }\n print(ans)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject C extends App {\n\n case class Point(x: Int, segId: Int, isBegin: Boolean)\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val a = in.next\n val b = in.next\n var ans = 0\n var i = 0\n while (i < n) {\n if (i == n - 1) {\n if (a(i) != b(i))\n ans += 1\n } else {\n if (a(i) != b(i) && a(i) == a(i + 1))\n ans += 1\n else if (a(i) == '1' && b(i) == '0' && a(i + 1) == '0' && b(i + 1) == '1') {\n ans += 1\n i += 1\n } else if (a(i) == '0' && b(i) == '1' && a(i + 1) == '1' && b(i + 1) == '0') {\n ans += 1\n i += 1\n }\n }\n i += 1\n }\n println(ans)\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toInt\n }\n\n def nextLong: Double = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}], "src_uid": "a57555f50985c6c3634de1e7c60553bd"} {"source_code": "object Main1 extends App {\n\n val n = readInt();\n val s = readLine().toCharArray();\n\n var cups = 0;\n\n for(i <- n to(s.length - 1, n)){\n if(s(i-1) == s(i-2) && s(i-2) == s(i-3)){\n cups = cups + 1;\n }\n }\n\n println(cups);\n\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val s = readLine()\n \n var count = 0\n for (i <- n to s.size - 1 by n) {\n if (s(i - 3) == s(i - 2) && s(i - 3) == s(i - 1)) count += 1\n }\n \n println(count)\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val str = in.next()\n if (str.length < 4)\n println(0)\n else {\n val res = (1 until str.length).foldLeft((0, 1, str.tail.head)) {\n case ((glasses, soFar, prev), i) if i % n == 0 && soFar >= 3 =>\n if (i == str.length - 1)\n (glasses + 1, soFar + 1, str(i))\n else {\n val next = str(i + 1)\n if (next == prev)\n (glasses + 1, soFar + 1, next)\n else\n (glasses + 1, 1, next)\n }\n case ((glasses, soFar, prev), i) if i % n == 0 =>\n if (i == str.length - 1)\n (glasses, soFar + 1, str(i))\n else {\n val next = str(i + 1)\n if (next == prev)\n (glasses, soFar + 1, next)\n else\n (glasses, 1, next)\n }\n case (acc@(glasses, soFar, prev), i) =>\n// println(\"last\")\n// println(acc)\n if (i == str.length - 1) (glasses, soFar, str(i))\n else if (str(i) == prev) (glasses, soFar + 1, prev)\n else (glasses, 1, str(i))\n }\n println(res._1)\n\n }\n\n\n}"}, {"source_code": "import java.util.Scanner\n\nobject DownTheHatch {\n\tdef main(args: Array[String]) {\n\t\tval in = new Scanner(System.in)\n\t\tval n = in.nextInt()\n\t\tval s = in.next()\n\t\tvar res = 0\n\t\tfor (i <- 0 until s.length by n) {\n\t\t\tif (i >= 4){\n\t\t\t\tif (s(i - 1) == s(i - 2) && s(i - 2) == s(i - 3)) {\n\t\t\t\t\tres += 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintln(res)\n\t}\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\n\nobject P253A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N: Int = sc.nextInt\n sc.nextLine\n val turns: List[Char] = sc.nextLine.toList\n\n val answer: Int = turns.drop(N - 3).sliding(4, N).count {\n case List(x, y, z, _) => x == y && y == z\n case _ => false\n }\n\n out.println(answer)\n out.close\n}\n\n\n\n"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nobject DownTheHatch {\n\tdef main(args: Array[String]) {\n\t\tval in = new Scanner(System.in)\n\t\tval n = in.nextInt()\n\t\tval s = in.next()\n\t\tvar res = 0\n\t\tfor (i <- n until s.length by (n + 1)) {\n\t\t\tif (s(i - 1) == s (i - 2) && s(i - 2) == s(i - 3)) {\n\t\t\t\tres += 1\n\t\t\t}\n\t\t}\n\t\tprintln(res)\n\t}\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val s = readLine()\n \n var count = 0\n for (i <- n to s.size by n) {\n if (s(i - 3) == s(i - 2) && s(i - 3) == s(i - 2)) count += 1\n }\n \n println(count)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val s = readLine()\n \n var count = 0\n for (i <- n to s.size by n) {\n if (s(i - 3) == s(i - 2) && s(i - 3) == s(i - 1)) count += 1\n }\n \n println(count)\n }\n}"}], "src_uid": "5606799ab5345bb9501fa6535e5abef9"} {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val voterCounts = Array.fill(100001) { 0 }\n val voterFor = Array.ofDim[Int](n)\n val voterCosts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val a, b = tl.nextToken.toInt\n voterCounts(a) += 1\n voterFor(i) = a\n voterCosts(i) = b\n }\n\n val allVoters = (0 until n).toArray.sortBy(voterCosts).reverse\n\n val myInitialVotes = voterCounts(0)\n\n def getCost(votesToWin: Int): Long = {\n \n var totalCost = 0L\n var myVotes = myInitialVotes\n val bribed = new mutable.BitSet(n)\n val votes = Array.fill(voterCounts.length)(0)\n\n for (voter <- allVoters) {\n val candidate = voterFor(voter)\n if (candidate > 0) {\n if (votes(candidate) + 1 == votesToWin) {\n totalCost += voterCosts(voter)\n bribed += voter\n myVotes += 1\n } else votes(candidate) += 1\n }\n }\n\n var i = n - 1\n while (myVotes < votesToWin) {\n val voter = allVoters(i)\n if (!bribed(voter) && voterFor(voter) > 0) {\n totalCost += voterCosts(voter)\n myVotes += 1\n }\n i -= 1\n }\n totalCost\n }\n\n var left = 1 max myInitialVotes\n var right = n min (voterCounts.max + 1)\n\n while (left + 2 < right) {\n val m = (right - left) / 3\n val ml = left + m\n val mr = right - m\n val costL = getCost(ml)\n val costR = getCost(mr)\n if (costL < costR) right = mr else left = ml\n }\n\n var res = getCost(left)\n while (left < right) {\n left += 1\n res = res min getCost(left)\n }\n\n println(res)\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val voterCounts = Array.fill(100001) { 0 }\n val voterFor = Array.ofDim[Int](n)\n val voterCosts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val a, b = tl.nextToken.toInt\n voterCounts(a) += 1\n voterFor(i) = a\n voterCosts(i) = b\n }\n\n val allVoters = (0 until n).toArray.sortBy(voterCosts).reverse\n\n val myInitialVotes = voterCounts(0)\n\n def getCost(votesToWin: Int): Long = {\n\n var totalCost = 0L\n var myVotes = myInitialVotes\n val bribed = new mutable.BitSet(n)\n val votes = Array.fill(voterCounts.length)(0)\n\n for {\n voter <- allVoters\n candidate = voterFor(voter)\n if candidate > 0\n } if (votes(candidate) + 1 == votesToWin) {\n totalCost += voterCosts(voter)\n bribed += voter\n myVotes += 1\n } else votes(candidate) += 1\n\n var i = n - 1\n while (myVotes < votesToWin) {\n val voter = allVoters(i)\n if (!bribed(voter) && voterFor(voter) > 0) {\n totalCost += voterCosts(voter)\n myVotes += 1\n }\n i -= 1\n }\n totalCost\n }\n\n var left = 1 max myInitialVotes\n var right = n min (voterCounts.max + 1)\n\n while (left + 2 < right) {\n val m = (right - left) / 3\n val ml = left + m\n val mr = right - m\n val costL = getCost(ml)\n val costR = getCost(mr)\n if (costL < costR) right = mr else left = ml\n }\n\n var res = getCost(left)\n while (left < right) {\n left += 1\n res = res min getCost(left)\n }\n\n println(res)\n}"}], "negative_code": [{"source_code": "import scala.collection._\nimport scala.util.Sorting\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]\n val voterCounts = Array.fill(100001) { 0 }\n val voterFor = Array.ofDim[Int](n)\n val voterCosts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val a, b = tl.nextToken.toInt\n voterCounts(a) += 1\n voterFor(i) = a\n voterCosts(i) = b\n if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)\n voterBuilders(a) += i\n }\n\n val votersByCandidate = voterBuilders.mapValues(_.result)\n votersByCandidate.values.foreach {\n Sorting.quickSort[Int](_)(Ordering.by(voterCosts))\n }\n \n val allVoters = (0 until n).toArray\n Sorting.quickSort[Int](allVoters)(Ordering.by(voterCosts))\n\n val myInitialVotes = voterCounts(0)\n\n def getCost(votesToWin: Int): Long = {\n var totalCost = 0L\n var myVotes = myInitialVotes\n val bribed = new mutable.BitSet(n)\n for {\n candidate <- voterCounts.indices\n if voterCounts(candidate) >= votesToWin\n voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)\n } {\n totalCost += voterCosts(voter)\n bribed += voter\n myVotes += 1\n }\n var i = 0\n while (myVotes < votesToWin) {\n val voter = allVoters(i)\n if (!bribed(voter) && voterFor(voter) > 0) {\n totalCost += voterCosts(voter)\n myVotes += 1\n }\n i += 1\n }\n totalCost\n }\n\n var left = 1 max myInitialVotes\n var right = n min (voterCounts.max + 1)\n\n while (left + 2 < right) {\n val m = (right - left) / 3\n val ml = left + m\n val mr = right - m\n val costL = getCost(ml)\n val costR = getCost(mr)\n if (costL < costR) right = mr else left = ml\n }\n\n var res = getCost(left)\n while (left < right) {\n left += 1\n res = res min getCost(left)\n }\n\n println(res)\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]\n val voterCounts = Array.fill(100001) { 0 }\n val voterPosition = Array.fill(100001) { 0 }\n val voterCostsBuilder = new mutable.ArrayBuilder.ofInt\n val candidatesByVoters = Array.ofDim[Int](n)\n\n var voterId = 0\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val a, b = tl.nextToken.toInt\n voterCounts(a) += 1\n if (a > 0) {\n candidatesByVoters(voterId) = a\n voterCostsBuilder += b\n if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)\n voterBuilders(a) += voterId\n voterId += 1\n }\n }\n\n val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }\n for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c\n\n var maxVoterCount = voterCounts.max\n\n val voterCosts = voterCostsBuilder.result\n val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))\n val allVoters = (0 until voterId).sortBy(voterCosts)\n val bribed = new mutable.BitSet(voterId)\n\n var myVotes = voterCounts(0)\n var cheapestVoterPosition = 0\n var totalCost = 0L\n\n def bribe(voterId: Int): Unit = {\n //require(!bribed(voterId))\n totalCost += voterCosts(voterId)\n myVotes += 1\n bribed += voterId\n val candidate = candidatesByVoters(voterId)\n candidatesByVoterCounts(voterCounts(candidate)) -= candidate\n voterCounts(candidate) -= 1\n candidatesByVoterCounts(voterCounts(candidate)) += candidate\n }\n\n while (myVotes <= maxVoterCount) {\n\n val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size\n\n if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {\n\n var costToBribeFromBest = 0L\n\n for (c <- candidatesByVoterCounts(maxVoterCount)) {\n while (bribed(votersByCandidate(c)(voterPosition(c)))) voterPosition(c) += 1\n costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))\n }\n\n var costToBribeCheapest = 0L\n var cnt = numCandidatesWithMaxVoters + 1\n var pos = cheapestVoterPosition\n\n while (cnt > 0) {\n while (pos < allVoters.size && bribed(allVoters(pos))) pos += 1\n if (pos == allVoters.size) {\n costToBribeCheapest = Long.MaxValue\n cnt = 0\n } else {\n costToBribeCheapest += voterCosts(allVoters(pos))\n //println(cnt, allVoters(pos))\n pos += 1\n cnt -= 1\n }\n }\n //println(numCandidatesWithMaxVoters, costToBribeFromBest, costToBribeCheapest)\n if (costToBribeFromBest <= costToBribeCheapest) {\n for (c <- candidatesByVoterCounts(maxVoterCount)) {\n bribe(votersByCandidate(c)(voterPosition(c)))\n }\n } else {\n\n var cnt = numCandidatesWithMaxVoters + 1\n\n while (cnt > 0) {\n while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1\n bribe(allVoters(cheapestVoterPosition))\n cnt -= 1\n }\n //while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1\n //bribe(allVoters(cheapestVoterPosition))\n }\n\n } else {\n while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1\n bribe(allVoters(cheapestVoterPosition))\n }\n\n while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1\n }\n\n println(totalCost)\n}"}, {"source_code": "import scala.collection._\nimport scala.util.Sorting\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]\n val voterCounts = Array.fill(100001) { 0 }\n val voterFor = Array.ofDim[Int](n)\n val voterCosts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val a, b = tl.nextToken.toInt\n voterCounts(a) += 1\n voterFor(i) = a\n voterCosts(i) = b\n if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)\n voterBuilders(a) += i\n }\n\n val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))\n \n val allVoters = (0 until n).toArray.sortBy(voterCosts)\n //Sorting.stableSort(allVoters, voterCosts)\n if (n == 10) {\n println(allVoters.mkString(\", \"))\n }\n\n val myInitialVotes = voterCounts(0)\n\n def getCost(votesToWin: Int): Long = {\n var totalCost = 0L\n var myVotes = myInitialVotes\n val bribed = new mutable.BitSet(n)\n for {\n candidate <- voterCounts.indices\n if voterCounts(candidate) >= votesToWin\n voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)\n } {\n totalCost += voterCosts(voter)\n bribed += voter\n myVotes += 1\n }\n var i = 0\n while (myVotes < votesToWin) {\n val voter = allVoters(i)\n if (!bribed(voter) && voterFor(voter) > 0) {\n totalCost += voterCosts(voter)\n myVotes += 1\n }\n i += 1\n }\n totalCost\n }\n\n var left = 1 max myInitialVotes\n var right = n min (voterCounts.max + 1)\n\n while (left + 2 < right) {\n val m = (right - left) / 3\n val ml = left + m\n val mr = right - m\n val costL = getCost(ml)\n val costR = getCost(mr)\n if (costL < costR) right = mr else left = ml\n }\n\n var res = getCost(left)\n while (left < right) {\n left += 1\n res = res min getCost(left)\n }\n\n println(res)\n}"}, {"source_code": "import scala.collection._\nimport scala.util.Sorting\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]\n val voterCounts = Array.fill(100001) { 0 }\n val voterFor = Array.ofDim[Int](n)\n val voterCosts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val a, b = tl.nextToken.toInt\n voterCounts(a) += 1\n voterFor(i) = a\n voterCosts(i) = b\n if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)\n voterBuilders(a) += i\n }\n\n val votersByCandidate = voterBuilders.mapValues(_.result)\n votersByCandidate.values.foreach {\n Sorting.stableSort(_, voterCosts)\n }\n \n val allVoters = (0 until n).toArray\n if (n == 10) {\n println(voterCosts.mkString(\", \"))\n }\n Sorting.stableSort(allVoters, voterCosts)\n\n val myInitialVotes = voterCounts(0)\n\n def getCost(votesToWin: Int): Long = {\n var totalCost = 0L\n var myVotes = myInitialVotes\n val bribed = new mutable.BitSet(n)\n for {\n candidate <- voterCounts.indices\n if voterCounts(candidate) >= votesToWin\n voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)\n } {\n totalCost += voterCosts(voter)\n bribed += voter\n myVotes += 1\n }\n var i = 0\n while (myVotes < votesToWin) {\n val voter = allVoters(i)\n if (!bribed(voter) && voterFor(voter) > 0) {\n totalCost += voterCosts(voter)\n myVotes += 1\n }\n i += 1\n }\n totalCost\n }\n\n var left = 1 max myInitialVotes\n var right = n min (voterCounts.max + 1)\n\n while (left + 2 < right) {\n val m = (right - left) / 3\n val ml = left + m\n val mr = right - m\n val costL = getCost(ml)\n val costR = getCost(mr)\n if (costL < costR) right = mr else left = ml\n }\n\n var res = getCost(left)\n while (left < right) {\n left += 1\n res = res min getCost(left)\n }\n\n println(res)\n}"}, {"source_code": "import scala.collection._\nimport scala.util.Sorting\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]\n val voterCounts = Array.fill(100001) { 0 }\n val voterFor = Array.ofDim[Int](n)\n val voterCosts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val a, b = tl.nextToken.toInt\n voterCounts(a) += 1\n voterFor(i) = a\n voterCosts(i) = b\n if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)\n voterBuilders(a) += i\n }\n\n val votersByCandidate = voterBuilders.mapValues(_.result)\n votersByCandidate.values.foreach {\n Sorting.stableSort(_, voterCosts)\n }\n \n val allVoters = (0 until n).toArray\n Sorting.stableSort(allVoters, voterCosts)\n\n val myInitialVotes = voterCounts(0)\n\n def getCost(votesToWin: Int): Long = {\n var totalCost = 0L\n var myVotes = myInitialVotes\n val bribed = new mutable.BitSet(n)\n for {\n candidate <- voterCounts.indices\n if voterCounts(candidate) >= votesToWin\n voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)\n } {\n totalCost += voterCosts(voter)\n bribed += voter\n myVotes += 1\n }\n var i = 0\n while (myVotes < votesToWin) {\n val voter = allVoters(i)\n if (!bribed(voter) && voterFor(voter) > 0) {\n totalCost += voterCosts(voter)\n myVotes += 1\n }\n i += 1\n }\n totalCost\n }\n\n var left = 1 max myInitialVotes\n var right = n min (voterCounts.max + 1)\n\n while (left + 2 < right) {\n val m = (right - left) / 3\n val ml = left + m\n val mr = right - m\n val costL = getCost(ml)\n val costR = getCost(mr)\n if (costL < costR) right = mr else left = ml\n }\n\n var res = getCost(left)\n while (left < right) {\n left += 1\n res = res min getCost(left)\n }\n\n println(res)\n}"}, {"source_code": "import scala.collection._\nimport scala.util.Sorting\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]\n val voterCounts = Array.fill(100001) { 0 }\n val voterFor = Array.ofDim[Int](n)\n val voterCosts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val a, b = tl.nextToken.toInt\n voterCounts(a) += 1\n voterFor(i) = a\n voterCosts(i) = b\n if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)\n voterBuilders(a) += i\n }\n\n val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))\n \n val allVoters = (0 until n).toArray //.sortBy(voterCosts)\n Sorting.stableSort(allVoters, voterCosts)\n if (n == 10) {\n println(allVoters.mkString(\", \"))\n }\n\n val myInitialVotes = voterCounts(0)\n\n def getCost(votesToWin: Int): Long = {\n var totalCost = 0L\n var myVotes = myInitialVotes\n val bribed = new mutable.BitSet(n)\n for {\n candidate <- voterCounts.indices\n if voterCounts(candidate) >= votesToWin\n voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)\n } {\n totalCost += voterCosts(voter)\n bribed += voter\n myVotes += 1\n }\n var i = 0\n while (myVotes < votesToWin) {\n val voter = allVoters(i)\n if (!bribed(voter) && voterFor(voter) > 0) {\n totalCost += voterCosts(voter)\n myVotes += 1\n }\n i += 1\n }\n totalCost\n }\n\n var left = 1 max myInitialVotes\n var right = n min (voterCounts.max + 1)\n\n while (left + 2 < right) {\n val m = (right - left) / 3\n val ml = left + m\n val mr = right - m\n val costL = getCost(ml)\n val costR = getCost(mr)\n if (costL < costR) right = mr else left = ml\n }\n\n var res = getCost(left)\n while (left < right) {\n left += 1\n res = res min getCost(left)\n }\n\n println(res)\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]\n val voterCounts = Array.fill(100001) { 0 }\n val voterPosition = Array.fill(100001) { 0 }\n val voterCostsBuilder = new mutable.ArrayBuilder.ofInt\n val candidatesByVoters = Array.ofDim[Int](n)\n\n var voterId = 0\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val a, b = tl.nextToken.toInt\n voterCounts(a) += 1\n if (a > 0) {\n candidatesByVoters(voterId) = a\n voterCostsBuilder += b\n if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)\n voterBuilders(a) += voterId\n voterId += 1\n }\n }\n\n val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }\n for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c\n\n var maxVoterCount = voterCounts.max\n\n val voterCosts = voterCostsBuilder.result\n val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))\n val allVoters = (0 until voterId).sortBy(voterCosts)\n val bribed = new mutable.BitSet(voterId)\n\n var myVotes = voterCounts(0)\n var cheapestVoterPosition = 0\n var totalCost = 0L\n\n def bribe(voterId: Int): Unit = {\n //require(!bribed(voterId))\n totalCost += voterCosts(voterId)\n myVotes += 1\n bribed += voterId\n val candidate = candidatesByVoters(voterId)\n candidatesByVoterCounts(voterCounts(candidate)) -= candidate\n voterCounts(candidate) -= 1\n candidatesByVoterCounts(voterCounts(candidate)) += candidate\n }\n\n while (myVotes <= maxVoterCount) {\n\n val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size\n\n if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {\n\n var costToBribeFromBest = 0L\n\n for (c <- candidatesByVoterCounts(maxVoterCount)) {\n while (bribed(votersByCandidate(c)(voterPosition(c)))) voterPosition(c) += 1\n costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))\n }\n\n var costToBribeCheapest = 0L\n var cnt = numCandidatesWithMaxVoters + 1\n var pos = cheapestVoterPosition\n\n while (cnt > 0) {\n while (bribed(allVoters(pos))) pos += 1\n costToBribeCheapest += voterCosts(allVoters(pos))\n cnt -= 1\n }\n\n if (costToBribeFromBest >= costToBribeCheapest) {\n for (c <- candidatesByVoterCounts(maxVoterCount)) {\n bribe(votersByCandidate(c)(voterPosition(c)))\n }\n } else {\n\n // var cnt = numCandidatesWithMaxVoters + 1\n // \n // while (cnt > 0) {\n // while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1\n // bribe(allVoters(cheapestVoterPosition))\n // cnt -= 1\n // }\n while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1\n bribe(allVoters(cheapestVoterPosition))\n }\n\n } else {\n while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1\n bribe(allVoters(cheapestVoterPosition))\n }\n\n while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1\n }\n\n println(totalCost)\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]\n val voterCounts = Array.fill(100001) { 0 }\n val voterPosition = Array.fill(100001) { 0 }\n val voterCostsBuilder = new mutable.ArrayBuilder.ofInt\n val candidatesByVoters = Array.ofDim[Int](n)\n\n var voterId = 0\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val a, b = tl.nextToken.toInt\n voterCounts(a) += 1\n if (a > 0) {\n candidatesByVoters(voterId) = a\n voterCostsBuilder += b\n if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)\n voterBuilders(a) += voterId\n voterId += 1\n }\n }\n\n val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }\n for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c\n\n var maxVoterCount = voterCounts.max\n\n val voterCosts = voterCostsBuilder.result\n val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))\n val allVoters = (0 until voterId).sortBy(voterCosts)\n val bribed = new mutable.BitSet(voterId)\n\n var myVotes = voterCounts(0)\n var cheapestVoterPosition = 0\n var totalCost = 0L\n\n def bribe(voterId: Int): Unit = {\n //require(!bribed(voterId))\n totalCost += voterCosts(voterId)\n myVotes += 1\n bribed += voterId\n val candidate = candidatesByVoters(voterId)\n candidatesByVoterCounts(voterCounts(candidate)) -= candidate\n voterCounts(candidate) -= 1\n candidatesByVoterCounts(voterCounts(candidate)) += candidate\n }\n\n while (myVotes <= maxVoterCount) {\n \n val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size\n \n if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {\n \n var costToBribeFromBest = 0L\n \n for (c <- candidatesByVoterCounts(maxVoterCount)) {\n while (bribed(votersByCandidate(c)(voterPosition(c)))) voterPosition(c) += 1\n costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))\n }\n \n var costToBribeCheapest = 0L\n var cnt = numCandidatesWithMaxVoters + 1\n var pos = cheapestVoterPosition\n \n while (cnt > 0) {\n while (bribed(allVoters(pos))) pos += 1\n costToBribeCheapest += voterCosts(allVoters(pos))\n cnt -= 1\n }\n \n if (costToBribeFromBest >= costToBribeCheapest) {\n for (c <- candidatesByVoterCounts(maxVoterCount)) {\n bribe(votersByCandidate(c)(voterPosition(c)))\n }\n } else {\n \n var cnt = numCandidatesWithMaxVoters + 1\n \n while (cnt > 0) {\n while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1\n bribe(allVoters(cheapestVoterPosition))\n cnt -= 1\n }\n }\n \n } else {\n while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1\n bribe(allVoters(cheapestVoterPosition))\n }\n \n while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1 \n }\n\n println(totalCost)\n}"}, {"source_code": "import scala.collection._\nimport scala.util.Sorting\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]\n val voterCounts = Array.fill(100001) { 0 }\n val voterFor = Array.ofDim[Int](n)\n val voterCosts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val a, b = tl.nextToken.toInt\n voterCounts(a) += 1\n voterFor(i) = a\n voterCosts(i) = b\n if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)\n voterBuilders(a) += i\n }\n\n val votersByCandidate = voterBuilders.mapValues(_.result)\n votersByCandidate.values.foreach {\n Sorting.quickSort[Int](_)(Ordering.by(voterCosts))\n }\n val allVoters = (0 until n).toArray.sortBy(voterCosts)\n\n val myInitialVotes = voterCounts(0)\n\n def getCost(votesToWin: Int): Long = {\n var totalCost = 0L\n var myVotes = myInitialVotes\n val bribed = new mutable.BitSet(n)\n for {\n candidate <- voterCounts.indices\n if voterCounts(candidate) >= votesToWin\n voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)\n } {\n totalCost += voterCosts(voter)\n bribed += voter\n myVotes += 1\n }\n var i = 0\n while (myVotes < votesToWin) {\n val voter = allVoters(i)\n if (!bribed(voter) && voterFor(voter) > 0) {\n totalCost += voterCosts(voter)\n myVotes += 1\n }\n i += 1\n }\n totalCost\n }\n\n var left = 1 max myInitialVotes\n var right = n min (voterCounts.max + 1)\n\n while (left + 2 < right) {\n val m = (right - left) / 3\n val ml = left + m\n val mr = right - m\n val costL = getCost(ml)\n val costR = getCost(mr)\n if (costL < costR) right = mr else left = ml\n }\n\n var res = getCost(left)\n while (left < right) {\n left += 1\n res = res min getCost(left)\n }\n \n println(res)\n}"}, {"source_code": "import scala.collection._\nimport scala.util.Sorting\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]\n val voterCounts = Array.fill(100001) { 0 }\n val voterFor = Array.ofDim[Int](n)\n val voterCosts = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val a, b = tl.nextToken.toInt\n voterCounts(a) += 1\n voterFor(i) = a\n voterCosts(i) = b\n if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)\n voterBuilders(a) += i\n }\n\n val votersByCandidate = voterBuilders.mapValues(_.result)\n votersByCandidate.values.foreach {\n Sorting.stableSort(_, voterCosts)\n }\n \n val allVoters = (0 until n).toArray\n Sorting.stableSort(allVoters, voterCosts)\n if (n == 10) {\n println(allVoters.mkString(\", \"))\n }\n\n val myInitialVotes = voterCounts(0)\n\n def getCost(votesToWin: Int): Long = {\n var totalCost = 0L\n var myVotes = myInitialVotes\n val bribed = new mutable.BitSet(n)\n for {\n candidate <- voterCounts.indices\n if voterCounts(candidate) >= votesToWin\n voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)\n } {\n totalCost += voterCosts(voter)\n bribed += voter\n myVotes += 1\n }\n var i = 0\n while (myVotes < votesToWin) {\n val voter = allVoters(i)\n if (!bribed(voter) && voterFor(voter) > 0) {\n totalCost += voterCosts(voter)\n myVotes += 1\n }\n i += 1\n }\n totalCost\n }\n\n var left = 1 max myInitialVotes\n var right = n min (voterCounts.max + 1)\n\n while (left + 2 < right) {\n val m = (right - left) / 3\n val ml = left + m\n val mr = right - m\n val costL = getCost(ml)\n val costR = getCost(mr)\n if (costL < costR) right = mr else left = ml\n }\n\n var res = getCost(left)\n while (left < right) {\n left += 1\n res = res min getCost(left)\n }\n\n println(res)\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]\n val voterCounts = Array.fill(100001) { 0 }\n val voterPosition = Array.fill(100001) { 0 }\n val voterCostsBuilder = new mutable.ArrayBuilder.ofInt\n val candidatesByVoters = Array.ofDim[Int](n)\n\n var voterId = 0\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val a, b = tl.nextToken.toInt\n voterCounts(a) += 1\n if (a > 0) {\n candidatesByVoters(voterId) = a\n voterCostsBuilder += b\n if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)\n voterBuilders(a) += voterId\n voterId += 1\n }\n }\n\n val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }\n for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c\n\n var maxVoterCount = voterCounts.max\n\n val voterCosts = voterCostsBuilder.result\n val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))\n val allVoters = (0 until voterId).sortBy(voterCosts)\n val bribed = new mutable.BitSet(voterId)\n\n var myVotes = voterCounts(0)\n var cheapestVoterPosition = 0\n var totalCost = 0L\n\n def bribe(voterId: Int): Unit = {\n //require(!bribed(voterId))\n totalCost += voterCosts(voterId)\n myVotes += 1\n bribed += voterId\n val candidate = candidatesByVoters(voterId)\n candidatesByVoterCounts(voterCounts(candidate)) -= candidate\n voterCounts(candidate) -= 1\n candidatesByVoterCounts(voterCounts(candidate)) += candidate\n }\n\n while (myVotes <= maxVoterCount) {\n\n val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size\n\n if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {\n\n var costToBribeFromBest = 0L\n\n for (c <- candidatesByVoterCounts(maxVoterCount)) {\n while (bribed(votersByCandidate(c)(voterPosition(c)))) voterPosition(c) += 1\n costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))\n }\n\n var costToBribeCheapest = 0L\n var cnt = numCandidatesWithMaxVoters + 1\n var pos = cheapestVoterPosition\n\n while (cnt > 0) {\n while (bribed(allVoters(pos))) pos += 1\n costToBribeCheapest += voterCosts(allVoters(pos))\n cnt -= 1\n }\n\n if (costToBribeFromBest < costToBribeCheapest) {\n for (c <- candidatesByVoterCounts(maxVoterCount)) {\n bribe(votersByCandidate(c)(voterPosition(c)))\n }\n } else {\n\n var cnt = numCandidatesWithMaxVoters + 1\n\n while (cnt > 0) {\n while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1\n bribe(allVoters(cheapestVoterPosition))\n cnt -= 1\n }\n //while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1\n //bribe(allVoters(cheapestVoterPosition))\n }\n\n } else {\n while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1\n bribe(allVoters(cheapestVoterPosition))\n }\n\n while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1\n }\n\n println(totalCost)\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]\n val voterCounts = Array.fill(100001) { 0 }\n val voterPosition = Array.fill(100001) { 0 }\n val voterCostsBuilder = new mutable.ArrayBuilder.ofInt\n val candidatesByVoters = Array.ofDim[Int](n)\n\n var voterId = 0\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val a, b = tl.nextToken.toInt\n voterCounts(a) += 1\n if (a > 0) {\n candidatesByVoters(voterId) = a\n voterCostsBuilder += b\n if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)\n voterBuilders(a) += voterId\n voterId += 1\n }\n }\n\n val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }\n for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c\n\n var maxVoterCount = voterCounts.max\n\n val voterCosts = voterCostsBuilder.result\n val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))\n val allVoters = (0 until voterId).sortBy(voterCosts)\n val bribed = new mutable.BitSet(voterId)\n\n var myVotes = voterCounts(0)\n var cheapestVoterPosition = 0\n var totalCost = 0L\n\n def bribe(voterId: Int): Unit = {\n //require(!bribed(voterId))\n totalCost += voterCosts(voterId)\n myVotes += 1\n bribed += voterId\n val candidate = candidatesByVoters(voterId)\n candidatesByVoterCounts(voterCounts(candidate)) -= candidate\n voterCounts(candidate) -= 1\n candidatesByVoterCounts(voterCounts(candidate)) += candidate\n }\n\n while (myVotes <= maxVoterCount) {\n\n val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size\n\n if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {\n\n var costToBribeFromBest = 0L\n\n for (c <- candidatesByVoterCounts(maxVoterCount)) {\n while (bribed(votersByCandidate(c)(voterPosition(c)))) voterPosition(c) += 1\n costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))\n }\n\n var costToBribeCheapest = 0L\n var cnt = numCandidatesWithMaxVoters + 1\n var pos = cheapestVoterPosition\n\n while (cnt > 0) {\n while (bribed(allVoters(pos))) pos += 1\n costToBribeCheapest += voterCosts(allVoters(pos))\n cnt -= 1\n }\n\n if (costToBribeFromBest <= costToBribeCheapest) {\n for (c <- candidatesByVoterCounts(maxVoterCount)) {\n bribe(votersByCandidate(c)(voterPosition(c)))\n }\n } else {\n\n var cnt = numCandidatesWithMaxVoters + 1\n\n while (cnt > 0) {\n while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1\n bribe(allVoters(cheapestVoterPosition))\n cnt -= 1\n }\n //while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1\n //bribe(allVoters(cheapestVoterPosition))\n }\n\n } else {\n while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1\n bribe(allVoters(cheapestVoterPosition))\n }\n\n while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1\n }\n\n println(totalCost)\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]\n val voterCounts = Array.fill(100001) { 0 }\n val voterPosition = Array.fill(100001) { 0 }\n val voterCostsBuilder = new mutable.ArrayBuilder.ofInt\n val candidatesByVoters = Array.ofDim[Int](n)\n\n var voterId = 0\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val a, b = tl.nextToken.toInt\n voterCounts(a) += 1\n if (a > 0) {\n candidatesByVoters(voterId) = a\n voterCostsBuilder += b\n if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)\n voterBuilders(a) += voterId\n voterId += 1\n }\n }\n\n val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }\n for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c\n\n var maxVoterCount = voterCounts.max\n\n val voterCosts = voterCostsBuilder.result\n val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))\n val allVoters = (0 until voterId).sortBy(voterCosts)\n val bribed = new mutable.BitSet(voterId)\n\n var myVotes = voterCounts(0)\n var cheapestVoterPosition = 0\n var totalCost = 0L\n\n def bribe(voterId: Int): Unit = {\n //require(!bribed(voterId))\n totalCost += voterCosts(voterId)\n myVotes += 1\n bribed += voterId\n val candidate = candidatesByVoters(voterId)\n candidatesByVoterCounts(voterCounts(candidate)) -= candidate\n voterCounts(candidate) -= 1\n candidatesByVoterCounts(voterCounts(candidate)) += candidate\n }\n\n while (myVotes <= maxVoterCount) {\n \n val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size\n \n if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {\n \n var costToBribeFromBest = 0L\n \n for (c <- candidatesByVoterCounts(maxVoterCount)) {\n while (bribed(voterPosition(c))) voterPosition(c) += 1\n costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))\n }\n \n var costToBribeCheapest = 0L\n var cnt = numCandidatesWithMaxVoters + 1\n var pos = cheapestVoterPosition\n \n while (cnt > 0) {\n while (bribed(allVoters(pos))) pos += 1\n costToBribeCheapest += voterCosts(allVoters(pos))\n cnt -= 1\n }\n \n if (costToBribeFromBest >= costToBribeCheapest) {\n for (c <- candidatesByVoterCounts(maxVoterCount)) {\n bribe(votersByCandidate(c)(voterPosition(c)))\n }\n } else {\n \n var cnt = numCandidatesWithMaxVoters + 1\n \n while (cnt > 0) {\n while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1\n bribe(allVoters(cheapestVoterPosition))\n cnt -= 1\n }\n }\n \n } else {\n while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1\n bribe(allVoters(cheapestVoterPosition))\n }\n \n while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1 \n }\n\n println(totalCost)\n}"}], "src_uid": "2a0362376ddeaf3548d5419d1e70b4d3"} {"source_code": "//package codeforces.contests._1367\n\nobject NecklaceAssembly {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n\n val Array(n, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n val s = io.StdIn.readLine\n\n val freq = new Array[Int](26)\n s.foreach(c => freq(c - 'a') += 1)\n\n val kPairs = new Array[Int](n + 1)\n freq.foreach { f =>\n for (i <- 1 to f) kPairs(i) += f / i\n }\n /*\n n = 7, k = 1000\n abczgyo\n\n 2 pairs are 3 and k = 4, e.g. \"aabbcc\", abab\n\n a -7\n b - 6\n c - 5\n\n abc abc abc a bc abc\n aabbc aabbc aabbc\n\n k = 10, 5 repetition thrice\n */\n\n println {\n (1 to n).foldLeft(0) { (acc, i) =>\n acc max {\n val x = (if (kPairs(i) > 0) {\n i * (kPairs(i) to 1 by -1).find(k % _ == 0).get\n } else 0) max (if (kPairs(i) >= k) i * k else 0) max (if (k % i == 0) i else 0) max (if (kPairs(i) >= 1) i else 0)\n x\n }\n }\n }\n }\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nk = readIntLine()\n val bs = readLine().toCharArray\n println(handle(nk.last, bs))\n }\n }\n\n def handle(k: Int, list: Array[Char]): Int = {\n val gr = list.groupBy(i => i).map(tup => tup._2.length).toList.sortBy(t => t).reverse\n\n for (l <- (1 to list.length).reverse) {\n if (canSatisfy(l, gr, k)) return l\n }\n\n 1\n }\n\n def canSatisfy(length: Int, bonds: List[Int], rawK: Int): Boolean = {\n def helper(groupSize: Int, numGroups: Int, bs: List[Int]): Boolean = bs match {\n case Nil => numGroups <= 0\n case b :: bs => numGroups <= 0 || {\n if (groupSize > b) false else helper(groupSize, numGroups - b / groupSize, bs)\n }\n }\n\n val k = (rawK - 1) % length + 1\n val gcd = BigInt(length).gcd(BigInt(k)).toInt\n if (gcd == 1) bonds.head >= length else {\n val numOfGroups = length / gcd\n helper(numOfGroups, gcd, bonds)\n }\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}, {"source_code": "object Main extends App {\n val r = new FastScanner(java.lang.System.in)\n val o = new java.io.PrintWriter(java.lang.System.out)\n def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)\n for(_ <- 1 to r.nextInt()) {\n val n = r.nextInt()\n val k = r.nextInt()\n val s = r.nextToken(n)\n val c = Array.ofDim[Int](26)\n for(i <- s) c(i.toInt - 97) += 1\n val d = c.sorted.filter(_ > 0).reverse\n var res = 0\n for(l <- 1 to n) {\n //0, k, 2k, 3k, ... (mod l)\n //kx == y (mod l)\n val g = gcd(l, k)\n val gs = l / g\n //g groups, group size gs\n val t = d.foldLeft(0) { (acc, x) => acc + (x / gs) }\n if(t >= g) res = l\n }\n o.println(res)\n }\n o.close()\n}\n\nimport scala.annotation.tailrec\nimport scala.collection.mutable.StringBuilder\n\nobject FastScanner {\n val zero = 0.toByte\n val cr = '\\r'.toByte\n val nl = '\\n'.toByte\n val BUFFER_SIZE = 0x10000\n}\n\nclass FastScanner(private val input: java.io.InputStream) {\n private val b = new Array[Byte](FastScanner.BUFFER_SIZE)\n private var n = 0\n private var pos = 0\n private var eof = false\n private def read ():Boolean = {\n if (eof) {\n return false\n }\n pos = 0\n n = input.read(b)\n if (n < 0) {\n eof = true\n }\n n > 0\n }\n private def nextByte(): Byte = {\n if (pos >= n && !read ()) {\n 0\n } else {\n val r = b(pos)\n pos += 1\n r\n }\n }\n def nextToken(k: Int = -1): String = {\n val sb = if(k >= 0) new StringBuilder(k) else new StringBuilder()\n var b = skipBlanks()\n assert(b > 0)\n while(b > 32) {\n sb.append(b.toChar)\n b = nextByte()\n }\n sb.toString\n }\n @tailrec\n private def skipBlanks(): Byte = {\n val b = nextByte()\n if(b > 32 || b < 1) b else skipBlanks()\n }\n def nextInt():Int = {\n val b = skipBlanks()\n @tailrec\n def f(t: Int): Int = {\n val b = nextByte ()\n if (b <= 32) t else f(10 * t + (b - 48))\n }\n require(b > 0)\n if (b < 48) -f(0) else f(b - 48)\n }\n}\n\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1367\n\nobject NecklaceAssembly {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n\n val Array(n, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n val s = io.StdIn.readLine\n\n val freq = new Array[Int](26)\n s.foreach(c => freq(c - 'a') += 1)\n\n val kPairs = new Array[Int](n + 1)\n freq.foreach { f =>\n for (i <- 1 to f) kPairs(i) += f / i\n }\n /*\n n = 7, k = 1000\n abczgyo\n\n 2 pairs are 3 and k = 4, e.g. \"aabbcc\", abab\n\n a -7\n b - 6\n c - 5\n\n abc abc abc a bc abc\n aabbc aabbc aabbc\n\n k = 10, 5 repetition thrice\n */\n\n println {\n (1 to n).foldLeft(0) { (acc, i) =>\n acc max {\n (if (kPairs(i) > 0 && k % kPairs(i) == 0) i * kPairs(i) else 0) max (if (kPairs(i) >= k) i * k else 0) max (if (k % i == 0) i else 0) max (if (kPairs(i) >= 1) i else 0)\n }\n }\n }\n }\n }\n}\n"}], "src_uid": "819aebac427c2c0f96e58bca60b81e33"} {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val m = in.nextInt()\n val data = in.nextLineInt(m)\n println(data.reverse.mkString(\" \"))\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextLineInt(n: Int): ArrayBuffer[Int] = {\n var data = ArrayBuffer[Int]()\n n.times({\n data += nextInt()\n })\n data\n }\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}", "positive_code": [{"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val pn = readLine().split(\" \").map(_.toInt)\n\n val ans = pn.reverse\n\n println(ans.mkString(\" \"))\n }\n}\n"}], "negative_code": [{"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val pn = readLine().split(\" \").map(_.toInt)\n\n val mod = pn.indexOf(1) % 2\n\n val ans = pn.zipWithIndex.map { case (p, i) => if (i % 2 == mod) p + 1 else p - 1 }\n\n println(ans.mkString(\" \"))\n }\n}\n"}], "src_uid": "1eaff8e0ec4614753699128af74b2471"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline private final def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n var i = from\n while(i <= to) { f(i); i += 1 }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n, m = ni()\n val w = na(n)\n val (from, to) = na2(m, -1)\n val s = ni() - 1\n val g = packUGraph(n, from, to)\n val (_, p, q) = traceBfs(g, s)\n val dp = Array.ofDim[Boolean](n)\n dp(s) = true\n REP_r(n) { i =>\n val v = q(i)\n REP(g(v).length) { j =>\n val u = g(v)(j)\n if (p(u) == v) {\n dp(v) |= dp(u)\n } else if (u != p(v)) {\n dp(v) |= true\n }\n }\n }\n debug(dp)\n var ans = sumL(dp.zipWithIndex.filter(_._1).map(_._2).map(w))\n var add = 0L\n\n val calced = Array.ofDim[Long](n)\n REP(n) { i =>\n val v = q(i)\n if (!dp(v)) {\n calced(v) = w(v)\n if (p(v)>= 0 && !dp(p(v))) calced(v) += calced(p(v))\n add = max(add, calced(v))\n }\n }\n ans += add\n out.println(ans)\n }\n\n /**\n * @param n ノード数\n */\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n REP(m)(i => p(from(i)) += 1)\n REP(m)(i => p(to(i)) += 1)\n REP(n)(i => t(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n /**\n * @return (depth, parent, queue)\n */\n def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {\n val n = g.length\n val INF = 1e9.toInt + 10\n val q, p = Array.ofDim[Int](n)\n q(0) = rt\n p(rt) = -1\n val d = Array.fill[Int](n)(INF)\n d(rt) = 0\n var cur = 0\n var last = 1\n while (cur < last) {\n val v = q(cur)\n REP(g(v).length) { i =>\n val u = g(v)(i)\n if (d(u) == INF) {\n d(u) = d(v) + 1\n p(u) = v\n q(last) = u\n last += 1\n }\n }\n cur += 1\n }\n (d, p, q)\n }\n}", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline private final def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n var i = from\n while(i <= to) { f(i); i += 1 }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n, m = ni()\n val w = na(n)\n val (from, to) = na2(m, -1)\n val s = ni() - 1\n val g = packUGraph(n, from, to)\n val (_, p, q) = traceBfs(g, s)\n val dp = Array.ofDim[Boolean](n)\n dp(s) = true\n REP_r(n) { i =>\n val v = q(i)\n REP(g(v).length) { j =>\n val u = g(v)(j)\n if (p(u) == v) {\n dp(v) |= dp(u)\n } else if (u != p(v)) {\n dp(v) |= true\n }\n }\n }\n debug(dp)\n var ans = sumL(dp.zipWithIndex.filter(_._1).map(_._2).map(w))\n var add = 0L\n\n val calced = Array.ofDim[Boolean](n)\n def calc(v: Int): Long = {\n var node = v\n var cnt = 0L\n while(!dp(node)) {\n calced(node) = true\n cnt += w(node)\n node = p(node)\n }\n cnt\n }\n\n REP_r(n) { i =>\n val v = q(i)\n if (!calced(v)) {\n add = max(add, calc(v))\n }\n }\n ans += add\n out.println(ans)\n }\n\n /**\n * @param n ノード数\n */\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n REP(m)(i => p(from(i)) += 1)\n REP(m)(i => p(to(i)) += 1)\n REP(n)(i => t(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n /**\n * @return (depth, parent, queue)\n */\n def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {\n val n = g.length\n val INF = 1e9.toInt + 10\n val q, p = Array.ofDim[Int](n)\n q(0) = rt\n p(rt) = -1\n val d = Array.fill[Int](n)(INF)\n d(rt) = 0\n var cur = 0\n var last = 1\n while (cur < last) {\n val v = q(cur)\n REP(g(v).length) { i =>\n val u = g(v)(i)\n if (d(u) == INF) {\n d(u) = d(v) + 1\n p(u) = v\n q(last) = u\n last += 1\n }\n }\n cur += 1\n }\n (d, p, q)\n }\n}"}], "negative_code": [], "src_uid": "824c7f11e6c2997c98741d314cdd1970"} {"source_code": "import java.util\nimport java.util.Scanner\nimport scala.util.control.Breaks._\n\nimport scala.io.StdIn\n\nobject Atask565 extends App {\n\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n\n val q = new util.ArrayList[BigInt]()\n\n for (i <- 0 until n) {\n line = new Scanner(StdIn.readLine())\n q.add(line.nextBigInteger())\n }\n\n\n for (i <- 0 until n) {\n var temp: BigInt = q.get(i)\n var ops = 0\n breakable {\n while (true) {\n if (temp == 1) {\n println(ops)\n break()\n }\n if (((temp * 4) % 5) == BigInt(0)) {\n ops += 1\n temp = (temp * 4) / 5\n } else {\n if (((temp * 2) % 3) == BigInt(0)) {\n ops += 1\n temp = (temp * 2) / 3\n } else {\n if ((temp % 2) == BigInt(0)) {\n ops += 1\n temp = temp / 2\n } else {\n ops = -1\n println(ops)\n break()\n }\n }\n }\n }\n }\n }\n}\n", "positive_code": [{"source_code": "object _1176A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val nums = io.read[Seq[Long]]\n val ans = nums.map(solve(_, 0))\n io.writeAll(ans, separator = \"\\n\")\n }\n\n @tailrec\n def solve(x: Long, acc: Int): Int = {\n if (x == 1) {\n acc\n } else if(x%2 == 0) {\n solve(x/2, acc + 1)\n } else if(x%3 == 0) {\n solve(2*(x/3), acc + 1)\n } else if (x%5 == 0) {\n solve(4*(x/5), acc + 1)\n } else {\n -1\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object CF565A extends App {\n\n import scala.io.StdIn\n\n val q = StdIn.readInt\n for (_ <- 0 until q) {\n var n = StdIn.readLong\n var count = 0\n while (n > 1 && (n % 2 == 0 || n % 3 == 0 || n % 5 == 0)) {\n if (n % 2 == 0) {\n n /= 2\n } else if (n % 3 == 0) {\n n = n / 3 * 2\n } else if (n % 5 == 0) {\n n = n / 5 * 4\n }\n\n count += 1\n }\n\n if (n == 1) println(count) else println(-1)\n }\n}\n"}, {"source_code": "object Main {\n\n val in = new java.util.Scanner(System.in)\n def nextInt = in.next().toInt\n\n def divide(n: Long): Int = {\n var count = 0\n var num = n\n while (num != 1) {\n if (num % 2 == 0) num = num / 2\n else if (num % 3 == 0) num = 2 * num / 3\n else if (num % 5 == 0) num = 4 * num / 5\n else return -1\n count += 1\n }\n count\n }\n\n def main(args: Array[String]): Unit = {\n val taskCount = nextInt\n val results = for (test <- 1 to taskCount) yield {\n val n = in.nextLong\n divide(n)\n }\n\n results foreach println\n }\n}\n\n"}], "negative_code": [], "src_uid": "ed5ea0e664aa986ab86e4e6746e8a1bf"} {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b, c) = readLine().split(\" \").map(_.toLong)\n\n val (ans1, ans2) = a * b - c match {\n case 0 => (if (b > 1) 1 else -1, -1)\n case d if d < 0 => (b, -1)\n case d if d > 0 => (if (a < c) 1 else -1, b)\n }\n\n println(s\"$ans1 $ans2\")\n }\n}\n", "positive_code": [{"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b, c) = readLine().split(\" \").map(_.toLong)\n\n val (ans1, ans2) = (if (a < c) 1 else -1, if (a * b > c) b else -1)\n\n println(s\"$ans1 $ans2\")\n }\n}\n"}], "negative_code": [{"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b, c) = readLine().split(\" \").map(_.toInt)\n\n val (ans1, ans2) = a * b - c match {\n case 0 => (if (b > 1) 1 else -1, -1)\n case d if d < 0 => (b, -1)\n case d if d > 0 => (if (a <= c) 1 else -1, b)\n }\n\n println(s\"$ans1 $ans2\")\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b, c) = readLine().split(\" \").map(_.toInt)\n\n val (ans1, ans2) = a * b - c match {\n case 0 => (if (b > 1) 1 else -1, -1)\n case d if d < 0 => (b, -1)\n case d if d > 0 => (if (a < c) 1 else -1, b)\n }\n\n println(s\"$ans1 $ans2\")\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b, c) = readLine().split(\" \").map(_.toInt)\n\n val (ans1, ans2) = a * b - c match {\n case 0 => (if (b == 1) -1 else 1, -1)\n case d if d < 0 => (1, -1)\n case d if d > 0 => (if (a < c) 1 else -1, b)\n }\n\n println(s\"$ans1 $ans2\")\n }\n}\n"}], "src_uid": "002801f26568a1b3524d8754207d32c1"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val houses = in.next()\n val distinct = houses.distinct\n val result = houses.indices.foldLeft(0, Map.empty[Char, Int], Int.MaxValue) {\n case ((x, map, found), el) =>\n var nX = x\n val ch = houses(el)\n var nMap = map + (ch -> (map.getOrElse(ch, 0) + 1))\n if (nMap.size == distinct.length) {\n while (nMap.size == distinct.length) {\n val nEl = houses(el - nX)\n if (nMap(nEl) == 1)\n nMap = nMap - nEl\n else\n nMap = nMap + (nEl -> (nMap(nEl) - 1))\n nX -= 1\n }\n val t = (nX + 1, nMap, Math.min(nX + 2, found))\n t\n }\n else (nX + 1, nMap, found)\n }\n println(result._3)\n\n\n}\n", "positive_code": [{"source_code": "object C701 {\n\n import IO._\n import collection.{mutable => cu}\n\n val MAX = 60\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val str = read.toCharArray\n val desiredCount = {\n val arr = Array.fill(MAX)(0)\n str.foreach { ch => arr(ch - 'A') = 1 }\n arr\n }\n\n if(desiredCount.sum == 1) {\n out.println(1)\n } else {\n val countTill = Array.fill(n+1)(Array.fill(MAX)(0))\n\n for (i <- 0 until n) {\n countTill(i).copyToArray(countTill(i+1))\n countTill(i+1)(str(i) - 'A') += 1\n }\n\n def checkValid(i: Int, j: Int): Boolean = {\n var x = 0\n var res = true\n while(x < MAX) {\n res &= countTill(j+1)(x) - countTill(i)(x) >= desiredCount(x)\n x += 1\n }\n res\n }\n\n var res = Int.MaxValue\n\n for (i <- 0 until n) {\n var low = i\n var high = n - 1\n\n while (low < high) {\n val mid = low + (high - low) / 2\n// println(low, high, mid)\n\n if (checkValid(i, mid))\n high = mid\n else\n low = mid + 1\n\n// println(low, high, mid)\n }\n// println(i, low)\n if(checkValid(i, low))\n res = math.min(res, low-i+1)\n }\n\n out.println(res)\n }\n\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}"}, {"source_code": "//package c\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val s = readLine.toCharArray\n\n val cs = s.distinct.zipWithIndex.toMap\n val pokemons = cs.size\n val as = s.map(cs)\n val cnts = Array.fill(pokemons)(0)\n\n var l, r = 0\n var res = n\n\n def isOk() = {\n var i = 0\n var ok = true\n while (ok && i < pokemons) {\n if (cnts(i) == 0) ok = false\n i += 1\n }\n ok\n }\n\n while (r < n) {\n cnts(as(r)) += 1\n r += 1\n while (isOk()) {\n res = math.min(res, r - l)\n cnts(as(l)) -= 1\n l += 1\n }\n }\n\n println(res)\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _701C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val (n, houses) = read[(Int, String)]\n val all = houses.distinct.length\n\n def solve(l: Int, r: Int, count: mutable.Map[Char, Int]): Int = {\n if (count.keys.size == all) {\n val c = houses(l)\n count(c) = count(c) - 1\n if (count(c) <= 0) count.remove(c)\n (r - l) min solve(l+1, r, count)\n } else if (r < n) {\n val c = houses(r)\n count(c) += 1\n solve(l, r + 1, count)\n } else {\n Int.MaxValue\n }\n }\n\n val ans = solve(0, 0, map[Char] to 0)\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _701C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val (n, houses) = read[(Int, String)]\n val all = houses.distinct.size\n\n def solve(l: Int, r: Int, count: mutable.Map[Char, Int]): Int = {\n debug(l, r, count)\n if (count.keys.size == all) {\n val c = houses(l)\n if(count contains c) {\n count(c) = count(c) - 1\n if (count(c) <= 0) count.remove(c)\n }\n (r - l) min solve(l+1, r, count)\n } else if (r < n) {\n val c = houses(r)\n count(c) += 1\n solve(l, r + 1, count)\n } else {\n Int.MaxValue\n }\n }\n\n val ans = solve(0, 0, map[Char] to 0)\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n sc.nextLine()\n val s = sc.nextLine()\n\n //\n val vol = 65\n var num = 0\n\n val dp2 = new Array[Boolean](58)\n for(c <- s){\n if(!dp2(c.toInt - vol)){\n num += 1\n dp2(c.toInt - vol) = true\n }\n }\n\n var ans = n\n var l = 0\n var r = 0\n var cnt = 0\n\n val dp = new Array[Int](58)\n while(r < n){\n val now = s(r).toInt - vol\n\n if(dp(now) == 0){\n cnt += 1\n dp(now) += 1\n if(cnt == num){\n ans = Math.min(ans, r-l+1)\n\n // move l\n var flag = true\n while(flag){\n val tmp = s(l).toInt - vol\n dp(tmp) -= 1\n l += 1\n if(dp(tmp) == 0){\n cnt -= 1\n flag = false\n }\n else\n ans = Math.min(ans, r-l+1)\n }\n\n }\n }\n else{\n dp(now) += 1\n }\n r += 1\n }\n\n\n println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val houses = in.next()\n val distinct = houses.distinct\n val result = houses.indices.foldLeft(0, Map.empty[Char, Int], Int.MaxValue) {\n case ((x, map, found), el) =>\n var nX = x\n val ch = houses(el)\n var nMap = map + (ch -> (map.getOrElse(ch, 0) + 1))\n if (nMap.size == distinct.length) {\n while (nMap.size == distinct.length) {\n val nEl = houses(el - nX)\n if (nMap(nEl) == 1)\n nMap = nMap - nEl\n else\n nMap = nMap + (nEl -> (nMap(nEl) - 1))\n nX -= 1\n }\n (nX + 2, nMap, Math.min(nX + 2, found))\n }\n else (nX + 1, nMap, found)\n }\n println(result._3)\n\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _701C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val (n, houses) = read[(Int, String)]\n\n val first = map[Char] to Int.MaxValue\n val last = map[Char] to Int.MinValue\n\n houses.zipWithIndex foreach {case (c, i) =>\n first(c) = first(c) min i\n last(c) = last(c) max i\n }\n val (p1, p2, p3, p4) = (first.values.min, first.values.max, last.values.min, last.values.max)\n val ans = (p2 - p1) min (p4 - p3)\n write(ans + 1)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _701C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val (n, houses) = read[(Int, String)]\n val count = map[Char] to 0\n val all = houses.distinct.length\n\n var l, r = 0\n var ans = Int.MaxValue\n\n while(r < n) {\n count.size match {\n case `all` =>\n ans = ans min (r - l)\n l += 1\n if (l < n) {\n val h = houses(l)\n count(h) -= 1\n if (count(h) <= 0) count.remove(h)\n }\n case _ =>\n r += 1\n if (r < n) count(houses(r)) += 1\n }\n }\n\n write(ans min n)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _701C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val (n, houses) = read[(Int, String)]\n val count = map[Char] to 0\n val all = houses.distinct.size\n\n var l, r = 0\n var ans = Int.MaxValue\n\n while(r < n) {\n //debug(houses, l, r, count, count.size)\n if(count.size == all) {\n ans = ans min (r - l)\n if (l < n) {\n l += 1\n val h = houses(l)\n count(h) -= 1\n if (count(h) <= 0) count.remove(h)\n }\n } else {\n r += 1\n if (r < n) count(houses(r)) += 1\n }\n }\n\n\n write(ans)\n }\n\n\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n sc.nextLine()\n val s = sc.nextLine()\n\n //\n val dp = new Array[Int](58)\n val vol = 65\n var cnt = 0\n\n for(c <- s){\n if(dp(c.toInt - vol) == 0)\n cnt += 1\n\n dp(c.toInt - vol) += 1\n }\n\n var ans = 0\n var flag1 = false // start\n var flag2 = false // end\n\n for(c <- s){\n if(!flag2){\n val now = c.toInt - vol\n \n\n if(flag1){\n ans += 1\n if(dp(now) != 0){\n dp(now) = 0\n cnt -= 1\n if(cnt == 0)\n flag2 = true\n }\n }\n else{\n if(dp(now) == 1){\n cnt -= 1\n ans += 1\n flag1 = true\n dp(now) = 0\n }\n else\n dp(now) -= 1\n }\n }\n }\n\n println(ans)\n }\n}\n"}], "src_uid": "60776cefd6c1a2f3c16b3378ebc31a9a"} {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, q) = readInts(3)\n\n val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n neighbourBuilders(u - 1) += v - 1\n neighbourBuilders(v - 1) += u - 1\n }\n val neighbours = neighbourBuilders.map(_.result)\n\n val cs = readInts(m)\n val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n for (i <- cs.indices) {\n pBuilders(cs(i) - 1) += i + 1\n }\n val ps = pBuilders.map(_.result.sorted)\n\n val depths = Array.ofDim[Int](n)\n\n val ancestors = Array.ofDim[Array[Int]](n)\n val min10s = Array.ofDim[Array[Array[Int]]](n)\n\n def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {\n val builder = new ArrayBuilder.ofInt\n builder.sizeHint(limit)\n var xi, yi, size = 0\n while (size < limit && (xi < xs.length || yi < ys.length)) {\n if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {\n builder += xs(xi)\n xi += 1\n } else {\n builder += ys(yi)\n yi += 1\n }\n size += 1\n }\n builder.result\n }\n\n def dfs(u: Int, parent: Int, depth: Int): Unit = {\n\n depths(u) = depth\n\n val ancestorsBuilder = new ArrayBuilder.ofInt\n ancestorsBuilder.sizeHint(17)\n val min10Builder = new ArrayBuilder.ofRef[Array[Int]]\n min10Builder.sizeHint(17)\n\n if (parent >= 0) {\n ancestorsBuilder += parent\n min10Builder += ps(parent)\n var i = 0\n var prev = parent\n var prevMin10 = ps(parent)\n while (prev > 0 && i < ancestors(prev).length) {\n prevMin10 = merge(prevMin10, min10s(prev)(i), 10)\n prev = ancestors(prev)(i)\n ancestorsBuilder += prev\n min10Builder += prevMin10\n i += 1\n }\n }\n\n ancestors(u) = ancestorsBuilder.result\n min10s(u) = min10Builder.result\n\n var i = 0\n while (i < neighbours(u).length) {\n val v = neighbours(u)(i)\n if (v != parent) dfs(v, u, depth + 1)\n i += 1\n }\n }\n\n dfs(0, -1, 0)\n\n def levelAncestor(_v: Int, depth: Int, limit: Int): (Int , Array[Int]) = {\n var v = _v\n var i = ancestors(v).length - 1\n var min10 = ps(v).take(limit)\n while (i >= 0) {\n if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {\n min10 = merge(min10, min10s(v)(i), limit)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n (v, min10) \n }\n\n def lowestCommonAncestor(_v: Int, _u: Int, limit: Int): Array[Int] = {\n var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)\n // now depths(v) == depths(u)\n var (v, min10) = levelAncestor(v0, depths(u), limit)\n if (v == u) min10 // v\n else {\n min10 = merge(min10, ps(u), limit)\n var i = ancestors(v).length - 1\n while (i >= 0) {\n if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {\n min10 = merge(min10, min10s(u)(i), limit)\n min10 = merge(min10, min10s(v)(i), limit)\n u = ancestors(u)(i)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n //ancestors(v)(0)\n merge(min10, ps(ancestors(v)(0)), limit)\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (_ <- 0 until q) {\n val Array(_v, _u, a) = readInts(3)\n val v = _v - 1\n val u = _u - 1\n val res = lowestCommonAncestor(u, v, a)\n println(res.length + \" \" + res.mkString(\" \"))\n }\n\n Console.flush\n}\n", "positive_code": [{"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, q) = readInts(3)\n\n val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n neighbourBuilders(u - 1) += v - 1\n neighbourBuilders(v - 1) += u - 1\n }\n val neighbours = neighbourBuilders.map(_.result)\n\n val cs = readInts(m)\n val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n for (i <- cs.indices) {\n pBuilders(cs(i) - 1) += i + 1\n }\n val ps = pBuilders.map(_.result.sorted)\n\n val depths = Array.ofDim[Int](n)\n\n val ancestors = Array.ofDim[Array[Int]](n)\n\n val min10s = Array.ofDim[Array[Array[Int]]](n)\n\n def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {\n val builder = new ArrayBuilder.ofInt\n var xi, yi, size = 0\n while (size < limit && (xi < xs.length || yi < ys.length)) {\n if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {\n builder += xs(xi)\n xi += 1\n } else {\n builder += ys(yi)\n yi += 1\n }\n size += 1\n }\n builder.result\n }\n\n def dfs(u: Int, parent: Int, depth: Int): Unit = {\n\n depths(u) = depth\n\n val ancestorsBuilder = new ArrayBuilder.ofInt\n val min10Builder = new ArrayBuilder.ofRef[Array[Int]]\n //ancestorsBuilder.clear()\n //min10Builder.clear()\n\n if (parent >= 0) {\n ancestorsBuilder += parent\n min10Builder += ps(parent)\n var i = 0\n var prev = parent\n var prevMin10 = ps(parent)\n while (prev > 0 && i < ancestors(prev).length) {\n prevMin10 = merge(prevMin10, min10s(prev)(i), 10)\n prev = ancestors(prev)(i)\n ancestorsBuilder += prev\n min10Builder += prevMin10\n i += 1\n }\n }\n // var depthDelta = 1\n // while (depthDelta <= depth) {\n // ancestorsBuilder += path(depth - depthDelta)\n // depthDelta <<= 1\n // }\n ancestors(u) = ancestorsBuilder.result\n min10s(u) = min10Builder.result\n\n for (v <- neighbours(u)) {\n if (v != parent) dfs(v, u, depth + 1)\n }\n }\n\n dfs(0, -1, 0)\n\n def lca(_v: Int, _u: Int, limit: Int): Array[Int] = {\n var (v, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)\n var i = ancestors(v).length - 1\n var min10 = ps(v).take(limit)\n while (i >= 0) {\n if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depths(u)) {\n min10 = merge(min10, min10s(v)(i), limit)\n v = ancestors(v)(i)\n i += 1 // FIXME\n }\n i -= 1\n }\n // now depths(v) == depths(u)\n assert(depths(v) == depths(u))\n// if (ancestors(v).length != ancestors(u).length) {\n// println(ancestors(v).length, ancestors(u).length)\n// Console.flush\n// return Array.empty\n// }\n if (v == u) min10 // v\n else {\n min10 = merge(min10, ps(u), limit)\n var i = ancestors(v).length - 1\n while (i >= 0) {\n if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {\n min10 = merge(min10, min10s(u)(i), limit)\n min10 = merge(min10, min10s(v)(i), limit)\n u = ancestors(u)(i)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n //ancestors(v)(0)\n merge(min10, ps(ancestors(v)(0)), limit)\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (_ <- 0 until q) {\n val Array(_v, _u, a) = readInts(3)\n val v = _v - 1\n val u = _u - 1\n val res = lca(u, v, a)\n println(res.length + \" \" + res.mkString(\" \"))\n }\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, q) = readInts(3)\n\n val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n neighbourBuilders(u - 1) += v - 1\n neighbourBuilders(v - 1) += u - 1\n }\n val neighbours = neighbourBuilders.map(_.result)\n\n val cs = readInts(m)\n val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n for (i <- cs.indices) {\n pBuilders(cs(i) - 1) += i + 1\n }\n val ps = pBuilders.map(_.result.sorted)\n\n val depths = Array.ofDim[Int](n)\n\n val ancestors = Array.ofDim[Array[Int]](n)\n val min10s = Array.ofDim[Array[Array[Int]]](n)\n\n def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {\n val builder = new ArrayBuilder.ofInt\n builder.sizeHint(limit)\n var xi, yi, size = 0\n while (size < limit && (xi < xs.length || yi < ys.length)) {\n if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {\n builder += xs(xi)\n xi += 1\n } else {\n builder += ys(yi)\n yi += 1\n }\n size += 1\n }\n builder.result\n }\n\n def dfs(u: Int, parent: Int, depth: Int): Unit = {\n\n depths(u) = depth\n\n val ancestorsBuilder = new ArrayBuilder.ofInt\n ancestorsBuilder.sizeHint(17)\n val min10Builder = new ArrayBuilder.ofRef[Array[Int]]\n min10Builder.sizeHint(17)\n\n if (parent >= 0) {\n ancestorsBuilder += parent\n min10Builder += ps(parent)\n var i = 0\n var prev = parent\n var prevMin10 = ps(parent)\n while (prev > 0 && i < ancestors(prev).length) {\n prevMin10 = merge(prevMin10, min10s(prev)(i), 10)\n prev = ancestors(prev)(i)\n ancestorsBuilder += prev\n min10Builder += prevMin10\n i += 1\n }\n }\n\n ancestors(u) = ancestorsBuilder.result\n min10s(u) = min10Builder.result\n\n for (v <- neighbours(u)) {\n if (v != parent) dfs(v, u, depth + 1)\n }\n }\n\n dfs(0, -1, 0)\n\n def levelAncestor(_v: Int, depth: Int, limit: Int): (Int , Array[Int]) = {\n var v = _v\n var i = ancestors(v).length - 1\n var min10 = ps(v).take(limit)\n while (i >= 0) {\n if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {\n min10 = merge(min10, min10s(v)(i), limit)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n (v, min10) \n }\n\n def lowestCommonAncestor(_v: Int, _u: Int, limit: Int): Array[Int] = {\n var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)\n // now depths(v) == depths(u)\n var (v, min10) = levelAncestor(v0, depths(u), limit)\n if (v == u) min10 // v\n else {\n min10 = merge(min10, ps(u), limit)\n var i = ancestors(v).length - 1\n while (i >= 0) {\n if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {\n min10 = merge(min10, min10s(u)(i), limit)\n min10 = merge(min10, min10s(v)(i), limit)\n u = ancestors(u)(i)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n //ancestors(v)(0)\n merge(min10, ps(ancestors(v)(0)), limit)\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (_ <- 0 until q) {\n val Array(_v, _u, a) = readInts(3)\n val v = _v - 1\n val u = _u - 1\n val res = lowestCommonAncestor(u, v, a)\n println(res.length + \" \" + res.mkString(\" \"))\n }\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\nimport java.io.PrintWriter\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, q) = readInts(3)\n\n val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n neighbourBuilders(u - 1) += v - 1\n neighbourBuilders(v - 1) += u - 1\n }\n val neighbours = neighbourBuilders.map(_.result)\n\n val cs = readInts(m)\n val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n for (i <- cs.indices) {\n pBuilders(cs(i) - 1) += i + 1\n }\n val ps = pBuilders.map(_.result.sorted)\n\n val depths = Array.ofDim[Int](n)\n\n val ancestors = Array.ofDim[Array[Int]](n)\n val min10s = Array.ofDim[Array[Array[Int]]](n)\n\n def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {\n val builder = new ArrayBuilder.ofInt\n builder.sizeHint(limit)\n var xi, yi, size = 0\n while (size < limit && (xi < xs.length || yi < ys.length)) {\n if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {\n builder += xs(xi)\n xi += 1\n } else {\n builder += ys(yi)\n yi += 1\n }\n size += 1\n }\n builder.result\n }\n\n def dfs(u: Int, parent: Int, depth: Int): Unit = {\n\n depths(u) = depth\n\n val ancestorsBuilder = new ArrayBuilder.ofInt\n ancestorsBuilder.sizeHint(17)\n val min10Builder = new ArrayBuilder.ofRef[Array[Int]]\n min10Builder.sizeHint(17)\n\n if (parent >= 0) {\n ancestorsBuilder += parent\n min10Builder += ps(parent)\n var i = 0\n var prev = parent\n var prevMin10 = ps(parent)\n while (prev > 0 && i < ancestors(prev).length) {\n prevMin10 = merge(prevMin10, min10s(prev)(i), 10)\n prev = ancestors(prev)(i)\n ancestorsBuilder += prev\n min10Builder += prevMin10\n i += 1\n }\n }\n\n ancestors(u) = ancestorsBuilder.result\n min10s(u) = min10Builder.result\n\n var i = 0\n while (i < neighbours(u).length) {\n val v = neighbours(u)(i)\n if (v != parent) dfs(v, u, depth + 1)\n i += 1\n }\n }\n\n dfs(0, -1, 0)\n\n def levelAncestor(_v: Int, depth: Int, limit: Int): (Int , Array[Int]) = {\n var v = _v\n var i = ancestors(v).length - 1\n var min10 = ps(v).take(limit)\n while (i >= 0) {\n if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {\n min10 = merge(min10, min10s(v)(i), limit)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n (v, min10) \n }\n\n def lowestCommonAncestor(_v: Int, _u: Int, limit: Int): Array[Int] = {\n var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)\n // now depths(v) == depths(u)\n var (v, min10) = levelAncestor(v0, depths(u), limit)\n if (v == u) min10 // v\n else {\n min10 = merge(min10, ps(u), limit)\n var i = ancestors(v).length - 1\n while (i >= 0) {\n if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {\n min10 = merge(min10, min10s(u)(i), limit)\n min10 = merge(min10, min10s(v)(i), limit)\n u = ancestors(u)(i)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n //ancestors(v)(0)\n merge(min10, ps(ancestors(v)(0)), limit)\n }\n }\n\n val out = new PrintWriter(System.out)\n\n for (_ <- 0 until q) {\n val Array(_v, _u, a) = readInts(3)\n val v = _v - 1\n val u = _u - 1\n val res = lowestCommonAncestor(u, v, a)\n out.println(res.length + \" \" + res.mkString(\" \"))\n }\n\n out.flush()\n}\n"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, q) = readInts(3)\n\n val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n neighbourBuilders(u - 1) += v - 1\n neighbourBuilders(v - 1) += u - 1\n }\n val neighbours = neighbourBuilders.map(_.result)\n\n val cs = readInts(m)\n val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n for (i <- cs.indices) {\n pBuilders(cs(i) - 1) += i + 1\n }\n val ps = pBuilders.map(_.result.sorted)\n\n val depths = Array.ofDim[Int](n)\n\n val ancestors = Array.ofDim[Array[Int]](n)\n val min10s = Array.ofDim[Array[Array[Int]]](n)\n\n def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {\n val builder = new ArrayBuilder.ofInt\n builder.sizeHint(limit)\n var xi, yi, size = 0\n while (size < limit && (xi < xs.length || yi < ys.length)) {\n if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {\n builder += xs(xi)\n xi += 1\n } else {\n builder += ys(yi)\n yi += 1\n }\n size += 1\n }\n builder.result\n }\n\n def dfs(u: Int, parent: Int, depth: Int): Unit = {\n\n depths(u) = depth\n\n val ancestorsBuilder = new ArrayBuilder.ofInt\n ancestorsBuilder.sizeHint(17)\n val min10Builder = new ArrayBuilder.ofRef[Array[Int]]\n min10Builder.sizeHint(17)\n\n if (parent >= 0) {\n ancestorsBuilder += parent\n min10Builder += ps(parent)\n var i = 0\n var prev = parent\n var prevMin10 = ps(parent)\n while (prev > 0 && i < ancestors(prev).length) {\n prevMin10 = merge(prevMin10, min10s(prev)(i), 10)\n prev = ancestors(prev)(i)\n ancestorsBuilder += prev\n min10Builder += prevMin10\n i += 1\n }\n }\n\n ancestors(u) = ancestorsBuilder.result\n min10s(u) = min10Builder.result\n\n for (v <- neighbours(u)) {\n if (v != parent) dfs(v, u, depth + 1)\n }\n }\n\n dfs(0, -1, 0)\n\n def lca(_v: Int, _u: Int, limit: Int): Array[Int] = {\n var (v, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)\n var i = ancestors(v).length - 1\n var min10 = ps(v).take(limit)\n while (i >= 0) {\n if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depths(u)) {\n min10 = merge(min10, min10s(v)(i), limit)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n // now depths(v) == depths(u)\n if (v == u) min10 // v\n else {\n min10 = merge(min10, ps(u), limit)\n var i = ancestors(v).length - 1\n while (i >= 0) {\n if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {\n min10 = merge(min10, min10s(u)(i), limit)\n min10 = merge(min10, min10s(v)(i), limit)\n u = ancestors(u)(i)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n //ancestors(v)(0)\n merge(min10, ps(ancestors(v)(0)), limit)\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (_ <- 0 until q) {\n val Array(_v, _u, a) = readInts(3)\n val v = _v - 1\n val u = _u - 1\n val res = lca(u, v, a)\n println(res.length + \" \" + res.mkString(\" \"))\n }\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m, q) = readInts(3)\n\n val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2)\n neighbourBuilders(u - 1) += v - 1\n neighbourBuilders(v - 1) += u - 1\n }\n val neighbours = neighbourBuilders.map(_.result)\n\n val cs = readInts(m)\n val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n for (i <- cs.indices) {\n pBuilders(cs(i) - 1) += i + 1\n }\n val ps = pBuilders.map(_.result.sorted)\n\n val depths = Array.ofDim[Int](n)\n\n val ancestors = Array.ofDim[Array[Int]](n)\n val ancestorsBuilder = new ArrayBuilder.ofInt\n\n val min10s = Array.ofDim[Array[Array[Int]]](n)\n val min10Builder = new ArrayBuilder.ofRef[Array[Int]]\n\n def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {\n val builder = new ArrayBuilder.ofInt\n var xi, yi, size = 0\n while (size < limit && (xi < xs.length || yi < ys.length)) {\n if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {\n builder += xs(xi)\n xi += 1\n } else {\n builder += ys(yi)\n yi += 1\n }\n size += 1\n }\n builder.result\n }\n\n def dfs(u: Int, parent: Int, depth: Int): Unit = {\n\n depths(u) = depth\n\n ancestorsBuilder.clear()\n min10Builder.clear()\n\n if (parent >= 0) {\n ancestorsBuilder += parent\n min10Builder += ps(parent)\n var i = 1\n var prev = parent\n var prevMin10 = ps(parent)\n while (prev > 0 && i <= ancestors(prev).length) {\n prevMin10 = merge(prevMin10, min10s(prev)(i - 1), 10)\n prev = ancestors(prev)(i - 1)\n ancestorsBuilder += prev\n min10Builder += prevMin10\n i += 1\n }\n }\n // var depthDelta = 1\n // while (depthDelta <= depth) {\n // ancestorsBuilder += path(depth - depthDelta)\n // depthDelta <<= 1\n // }\n ancestors(u) = ancestorsBuilder.result\n min10s(u) = min10Builder.result\n\n for (v <- neighbours(u)) {\n if (v != parent) {\n dfs(v, u, depth + 1)\n }\n }\n }\n\n dfs(0, -1, 0)\n\n def lca(_v: Int, _u: Int, limit: Int): Array[Int] = {\n var (v, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)\n var i = ancestors(v).length - 1\n var min10 = ps(v).take(limit) //Array.empty[Int]\n while (i >= 0) {\n if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depths(u)) {\n min10 = merge(min10, min10s(v)(i), limit)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n //println(min10.mkString(\" \"))\n // now depths(v) == depths(u)\n if (ancestors(v).length != ancestors(u).length) {\n println(ancestors(v).length, ancestors(u).length)\n Console.flush\n return Array.empty\n }\n if (v == u) min10 // v\n else {\n min10 = merge(min10, ps(u), limit)\n var i = ancestors(v).length - 1\n while (i >= 0) {\n if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {\n min10 = merge(min10, min10s(u)(i), limit)\n //println(min10.mkString(\" \"))\n min10 = merge(min10, min10s(v)(i), limit)\n //println(min10.mkString(\" \"))\n u = ancestors(u)(i)\n v = ancestors(v)(i)\n }\n i -= 1\n }\n //ancestors(v)(0)\n merge(min10, ps(ancestors(v)(0)), limit)\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (_ <- 0 until q) {\n val Array(_v, _u, a) = readInts(3)\n val v = _v - 1\n val u = _u - 1\n val res = lca(u, v, a)\n println(res.length + \" \" + res.mkString(\" \"))\n }\n\n Console.flush\n}\n"}], "src_uid": "ff84bc8e8e01c82e1ecaa2a39a7f8dc6"} {"source_code": "import scala.io.StdIn\nimport scala.util.control.Breaks._\nimport java.util.Scanner\n\n\nobject Hello extends App {\n val line = new Scanner(StdIn.readLine())\n val health: BigInt = line.nextBigInteger()\n val mins = line.nextInt()\n val d = StdIn.readLine().split(' ').map(_.toInt)\n var damage: BigInt = BigInt(0)\n var maxDamage: BigInt = BigInt(0)\n for (i <- 0 until mins) {\n damage += d(i)\n if (damage < maxDamage) {\n maxDamage = damage\n }\n }\n if (damage >= 0 && maxDamage * -1 < health) {\n println(\"-1\")\n System.exit(0)\n }\n val fullRounds: BigInt = (health + maxDamage) / (if(damage == 0) BigInt(1) else damage)\n var finalFullRounds: BigInt = if (fullRounds >= 0) fullRounds else fullRounds * -1\n if ((health + maxDamage) % (if(damage == 0) BigInt(1) else damage) != 0) {\n finalFullRounds += 1\n }\n if (maxDamage * -1 >= health) {\n finalFullRounds = 0\n }\n var secondDamage: BigInt = 0\n breakable {\n for (i <- 0 until mins) {\n secondDamage += d(i)\n if (health + damage * finalFullRounds + secondDamage <= 0) {\n println(finalFullRounds * mins + i + 1)\n break()\n }\n }\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val H = nl()\n val N = ni()\n val D = na(N)\n val S = sumL(D)\n val cum = cumSum(D)\n\n debugL(S)\n debug(cum)\n\n def simulateLastTurn(remainH: Long): Long = {\n var t = 0\n var h = remainH\n while(h > 0) {\n h += D(t)\n t += 1\n }\n t\n }\n\n // one turn kill\n if (H + cum.min <= 0) {\n val t = simulateLastTurn(H)\n out.println(t)\n } else if (S >= 0) out.println(-1) // 何ターンかかってもたおせない\n else {\n val turns = (H + cum.min - 1) / -S + 1\n debugL(turns)\n val remain = H + turns * S\n debug(s\"turns:$turns remain:$remain\")\n val ans = turns * N + simulateLastTurn(remain)\n out.println(ans)\n }\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\nimport scala.util.control.Breaks._\nimport java.util.Scanner\n\n\nobject Hello extends App {\n val line = new Scanner(StdIn.readLine())\n val health: BigInt = line.nextBigInteger()\n val mins = line.nextInt()\n val d = StdIn.readLine().split(' ').map(_.toInt)\n var damage: BigInt = BigInt(0)\n var maxDamage: BigInt = BigInt(0)\n for (i <- 0 until mins) {\n damage += d(i)\n if (damage < maxDamage) {\n maxDamage = damage\n }\n }\n if (damage >= 0 && maxDamage * -1 < health) {\n println(\"-1\")\n System.exit(0)\n }\n val fullRounds: BigInt = (health + maxDamage) / (if(damage == 0) BigInt(1) else damage)\n var finalFullRounds = if (fullRounds >= 0) fullRounds else fullRounds * -1\n if ((health + maxDamage) % (if(damage == 0) BigInt(1) else damage) != 0) {\n finalFullRounds += 1\n }\n if (maxDamage * -1 >= health) {\n finalFullRounds = 0\n }\n var secondDamage = 0\n breakable {\n for (i <- 0 until mins) {\n secondDamage += d(i)\n if (health + damage * finalFullRounds + secondDamage <= 0) {\n println(finalFullRounds * mins + i + 1)\n break()\n }\n }\n }\n}"}, {"source_code": "import scala.io.StdIn\nimport scala.util.control.Breaks._\nimport java.util.Scanner\n\nimport scala.math.BigDecimal.RoundingMode\n\nobject Hello extends App {\n val line = new Scanner(StdIn.readLine())\n val health: BigDecimal = line.nextBigDecimal()\n val mins = line.nextInt()\n val d = StdIn.readLine().split(' ').map(_.toInt)\n var damage: BigDecimal = BigDecimal(0)\n var maxDamage: BigDecimal = BigDecimal(0)\n for (i <- 0 until mins) {\n damage += d(i)\n if (damage < maxDamage) {\n maxDamage = damage\n }\n }\n if (damage >= 0 && maxDamage < health) {\n println(\"-1\")\n }\n (health + maxDamage).setScale(0, RoundingMode.CEILING)\n val fullRounds: BigDecimal = ((health + maxDamage) / (if(damage == 0) BigDecimal(1) else damage)).setScale(0, RoundingMode.UP)\n val finalFullRounds = if (fullRounds >= 0) fullRounds else fullRounds * -1\n\n var secondDamage = 0\n breakable {\n for (i <- 0 until mins) {\n secondDamage += d(i)\n if (health + damage * finalFullRounds + secondDamage <= 0) {\n println((finalFullRounds * mins + i + 1).toBigInt())\n break()\n }\n }\n }\n}"}, {"source_code": "import scala.io.StdIn\nimport scala.util.control.Breaks._\nimport java.util.Scanner\n\nimport scala.math.BigDecimal.RoundingMode\n\nobject Hello extends App {\n val line = new Scanner(StdIn.readLine())\n val health: BigDecimal = line.nextBigDecimal()\n val mins = line.nextInt()\n val d = StdIn.readLine().split(' ').map(_.toInt)\n var damage: BigDecimal = BigDecimal(0)\n var maxDamage: BigDecimal = BigDecimal(0)\n for (i <- 0 until mins) {\n damage += d(i)\n if (damage < maxDamage) {\n maxDamage = damage\n }\n }\n if (damage >= 0 && maxDamage * -1 < health) {\n println(\"-1\")\n System.exit(0)\n }\n val fullRounds: BigDecimal = ((health + maxDamage) / (if(damage == 0) BigDecimal(1) else damage)).setScale(0, RoundingMode.UP)\n var finalFullRounds = if (fullRounds >= 0) fullRounds else fullRounds * -1\n\n if (maxDamage * -1 >= health) {\n finalFullRounds = 0\n }\n var secondDamage = 0\n breakable {\n for (i <- 0 until mins) {\n secondDamage += d(i)\n if (health + damage * finalFullRounds + secondDamage <= 0) {\n println((finalFullRounds * mins + i + 1).toBigInt())\n break()\n }\n }\n }\n}"}, {"source_code": "import scala.io.StdIn\nimport scala.util.control.Breaks._\nimport java.util.Scanner\n\n\nobject Hello extends App {\n val line = new Scanner(StdIn.readLine())\n val health: BigInt = line.nextBigInteger()\n val mins = line.nextInt()\n val d = StdIn.readLine().split(' ').map(_.toInt)\n var damage: BigInt = BigInt(0)\n var maxDamage: BigInt = BigInt(0)\n for (i <- 0 until mins) {\n damage += d(i)\n if (damage < maxDamage) {\n maxDamage = damage\n }\n }\n if (damage >= 0 && maxDamage * -1 < health) {\n println(\"-1\")\n System.exit(0)\n }\n val fullRounds: BigInt = (health + maxDamage) / (if(damage == 0) BigInt(1) else damage)\n var finalFullRounds = (if (fullRounds >= 0) fullRounds else fullRounds * -1) + 1\n\n if (maxDamage * -1 >= health) {\n finalFullRounds = 0\n }\n var secondDamage = 0\n breakable {\n for (i <- 0 until mins) {\n secondDamage += d(i)\n if (health + damage * finalFullRounds + secondDamage <= 0) {\n println(finalFullRounds * mins + i + 1)\n break()\n }\n }\n }\n}"}, {"source_code": "import scala.io.StdIn\nimport scala.util.control.Breaks._\nimport java.util.Scanner\n\nimport scala.math.BigDecimal.RoundingMode\n\nobject Hello extends App {\n val line = new Scanner(StdIn.readLine())\n val health: BigDecimal = line.nextBigDecimal()\n val mins = line.nextInt()\n val d = StdIn.readLine().split(' ').map(_.toInt)\n var damage: BigDecimal = BigDecimal(0)\n var maxDamage: BigDecimal = BigDecimal(0)\n for (i <- 0 until mins) {\n damage += d(i)\n if (damage < maxDamage) {\n maxDamage = damage\n }\n }\n if (damage >= 0 && maxDamage * -1 < health) {\n println(\"-1\")\n System.exit(0)\n }\n (health + maxDamage).setScale(0, RoundingMode.CEILING)\n val fullRounds: BigDecimal = ((health + maxDamage) / (if(damage == 0) BigDecimal(1) else damage)).setScale(0, RoundingMode.UP)\n var finalFullRounds = if (fullRounds >= 0) fullRounds else fullRounds * -1\n\n if (maxDamage * -1 >= health) {\n finalFullRounds = 0\n }\n var secondDamage = 0\n breakable {\n for (i <- 0 until mins) {\n secondDamage += d(i)\n if (health + damage * finalFullRounds + secondDamage <= 0) {\n println((finalFullRounds * mins + i + 1).toBigInt())\n break()\n }\n }\n }\n}"}], "src_uid": "d173fa24cebaeda9ca794eeed68fa12d"} {"source_code": "import java.io._\r\nimport scala.collection.immutable.TreeSet\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val reader = new BufferedReader(new java.io.InputStreamReader(System.in))\r\n val writer = new PrintWriter(System.out)\r\n def readInt(): Int = reader.readLine().toInt\r\n def readLong(): Long = reader.readLine().toLong\r\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\r\n def readArrayLong(): Array[Long] = reader.readLine().split(\" \").map(_.toLong)\r\n def readString(): String = reader.readLine()\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n\r\n def solve(t: Int = 0): Unit = {\r\n //var t = readInt()\r\n //while (t > 0) {\r\n val Array(n,m) = readArrayInt()\r\n val s = readString()\r\n val q = new Array[(Int, Int)](m)\r\n\r\n for (i <- 0 until m) {\r\n val Array(l, r) = readArrayInt()\r\n q(i) = (l,r)\r\n }\r\n\r\n val c = Array(\"abc\",\"acb\",\"bca\",\"bac\",\"cab\",\"cba\")\r\n val f = Array.ofDim[Int](6,n)\r\n\r\n for (i <- 0 until 6) {\r\n if (c(i)(0) != s(0))\r\n f(i)(0) = 1\r\n\r\n for (j <- 1 until n) {\r\n if (c(i)(j % 3) != s(j))\r\n f(i)(j) = f(i)(j-1) + 1\r\n else\r\n f(i)(j) = f(i)(j-1)\r\n\r\n }\r\n }\r\n\r\n for (i <- 0 until m) {\r\n val (l,r) = q(i)\r\n var max = n\r\n for (i <- 0 until 6) {\r\n if (l - 2 >= 0) {\r\n max = Math.min(max, f(i)(r - 1) - f(i)(l - 2))\r\n } else\r\n max = Math.min(max, f(i)(r - 1))\r\n }\r\n writer.println(max)\r\n }\r\n\r\n //t -= 1\r\n // }\r\n\r\n }\r\n\r\n def main(args: Array[String]) {\r\n //multiTest(solve)\r\n solve()\r\n writer.flush()\r\n }\r\n}", "positive_code": [{"source_code": "import java.io._\r\n\r\nobject Solution {\r\n // let's talk about beatiful strings\r\n case class Solver(s: String) {\r\n // def notAPalindrome(s: String, ll: Int, rr: Int): Boolean = {\r\n // var l = ll\r\n // var r = rr\r\n // while (l < r) {\r\n // if (s.charAt(l) != s.charAt(r)) return true\r\n // l += 1\r\n // r -= 1\r\n // }\r\n // false\r\n // }\r\n //\r\n // def isBeautiful(s: String): Boolean =\r\n // (0 until s.length).forall { left =>\r\n // ((left + 1) until s.length).forall { right =>\r\n // notAPalindrome(s, left, right)\r\n // }\r\n // }\r\n //\r\n // def enumBeautiful(len: Int): LazyList[String] =\r\n // if (len == 0)\r\n // LazyList.from(Seq(\"\"))\r\n // else\r\n // enumBeautiful(len - 1).flatMap(l => Seq(l + \"a\", l + \"b\", l + \"c\")).filter(isBeautiful)\r\n\r\n val totals: Array[Array[Int]] = Seq(0, 1, 2).flatMap { offset =>\r\n Seq('a', 'b', 'c').map { ch =>\r\n val total: Array[Int] = s.zipWithIndex.map { case (ch2, idx) =>\r\n if ((ch2 == ch) && (idx % 3 == offset)) 1 else 0\r\n }.scan(0)(_ + _).tail.toArray\r\n ((offset * 3 + (ch - 'a')), total)\r\n }\r\n }.sortBy(_._1).map(_._2).toArray\r\n\r\n // r-l % 3 == 0\r\n def charCount(l: Int, r: Int, char: Char): Int = {\r\n val total = totals((l % 3) * 3 + (char - 'a'))\r\n if (l == 0) total(r) else total(r) - total(l - 1)\r\n }\r\n\r\n // inclusive\r\n def notCharCount(l: Int, _r: Int, char: Char): Int = {\r\n if (l > _r) return 0\r\n\r\n val mod = (_r - l) % 3\r\n val r = _r - mod\r\n val total = (r - l) / 3 + 1\r\n total - charCount(l, r, char)\r\n }\r\n\r\n def cost(l: Int, r: Int, src: String): Int = {\r\n notCharCount(l, r, src.charAt(0)) +\r\n notCharCount(l + 1, r, src.charAt(1)) +\r\n notCharCount(l + 2, r, src.charAt(2))\r\n }\r\n\r\n def query(l: Int, r: Int): Int = Math.min(\r\n Math.min(\r\n Math.min(\r\n cost(l, r, \"abc\"),\r\n cost(l, r, \"acb\")\r\n ),\r\n Math.min(\r\n cost(l, r, \"bac\"),\r\n cost(l, r, \"bca\"),\r\n )\r\n ),\r\n Math.min(\r\n cost(l, r, \"cab\"),\r\n cost(l, r, \"cba\")\r\n )\r\n )\r\n }\r\n\r\n def run(input: BufferedReader, output: PrintWriter): Unit = {\r\n // len 1: a, b, c\r\n // len 2: ab, ac, ba, bc, ca, cb\r\n // len 3: abc, acb, bac, bca, cab, cba\r\n // len 4: abca, acba, bacb, bcab, cabc, cbac\r\n // so it's always one of \"abc\", \"acb\", \"bac\", \"bca\", \"cab\", \"cba\"\r\n// Solver(\"\").enumBeautiful(4).foreach(println)\r\n// println(\"done\")\r\n// val solver2 =Solver(\"a\".repeat(200000))\r\n// println(\"done\")\r\n\r\n val nm = input.readLine()\r\n val n = nm.split(\" \")(0).toInt\r\n val m = nm.split(\" \")(1).toInt\r\n val s = input.readLine()\r\n\r\n val solver = Solver(s.substring(0, n))\r\n\r\n (1 to m).foreach { _ =>\r\n val lr = input.readLine()\r\n output.println(solver.query(lr.split(\" \")(0).toInt - 1, lr.split(\" \")(1).toInt - 1))\r\n }\r\n output.flush()\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n run(new BufferedReader(new InputStreamReader(System.in)), new PrintWriter(System.out))\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "b4183febe5ae61770368d2e16f273675"} {"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n val set = new Array[Int](n)\n val values = new mutable.TreeSet[Int]()\n for (i <- 0 until n) {\n a(i) = nextInt\n values.add(i + 1)\n set(i) = a(i)\n }\n for (i <- 0 until n) {\n if (set(i) < n && values.contains(set(i))) {\n values -= set(i)\n }\n }\n var ind = 0\n var min = 1\n val s = new mutable.HashSet[Int]()\n while (ind < n) {\n val x = a(ind)\n if (s.contains(x) || x > n) {\n min = values.keySet.firstKey\n set(ind) = min\n s.add(min)\n values -= min\n } else {\n s.add(x)\n set(ind) = x\n values -= x\n }\n ind += 1\n }\n if (!values.isEmpty) {\n for (i <- 0 until n) {\n if (set(i) > n) {\n set(i) = values.keySet.firstKey\n values -= set(i)\n }\n }\n }\n for (i <- 0 until n) {\n out.print(set(i) + \" \")\n }\n return 0\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n readInt()\n val numbers = readLine().split(\" \").map(_.toInt)\n\n val pool = Array.fill[Boolean](numbers.length + 1)(false)\n\n val answer = numbers.map { x =>\n if (x <= numbers.length && !pool(x)) {\n pool(x) = true\n x\n } else {\n -1\n }\n }\n\n var current = 1\n val answer2 = answer.map { x =>\n if (x > -1) x\n else {\n while (pool(current)) current += 1\n pool(current) = true\n current += 1\n current - 1\n }\n\n }\n\n println(answer2.mkString(\" \"))\n\n}\n"}, {"source_code": "\nimport java.util.Scanner\n\nobject PB extends App {\n var in = new Scanner(System.in)\n val n = in.nextInt()\n val a = (1 to n).map(_ => in.nextInt())\n val vis = Array.fill[Boolean](n+1)(false)\n val ans = Array.fill[Int](n)(0)\n for(i <- 0 until n if a(i) <= n && !vis(a(i))){\n vis(a(i)) = true\n ans(i) = a(i)\n }\n val emp = (0 until n).filter(ans(_) == 0)\n val vs = (1 to n).filter(!vis(_))\n for(i <- 0 until emp.length)\n ans(emp(i)) = vs(i)\n println(ans.mkString(\" \"))\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Int](n)\n val set = new Array[Int](n)\n val values = new mutable.TreeSet[Int]()\n for (i <- 0 until n) {\n a(i) = nextInt\n values.add(i + 1)\n set(i) = a(i)\n }\n var ind = 0\n var min = 1\n val s = new mutable.HashSet[Int]()\n while (ind < n) {\n val x = a(ind)\n if (s.contains(x)) {\n min = values.keySet.firstKey\n set(ind) = min\n values -= min\n } else {\n s.add(x)\n set(ind) = x\n values -= x\n }\n ind += 1\n }\n if (!values.isEmpty) {\n for (i <- 0 until n) {\n if (set(i) > n) {\n set(i) = values.keySet.firstKey\n values -= set(i)\n }\n }\n }\n for (i <- 0 until n) {\n out.print(set(i) + \" \")\n }\n return 0\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n readInt()\n val numbers = readLine().split(\" \").map(_.toInt)\n\n val pool = Array.fill[Boolean](numbers.length + 1)(false)\n\n var current = 1\n val answer = numbers.map { x =>\n if (x <= numbers.length && !pool(x)) {\n pool(x) = true\n x\n } else {\n while (pool(current)) current += 1\n pool(current) = true\n current += 1\n current - 1\n }\n }\n\n println(answer.mkString(\" \"))\n\n}\n"}], "src_uid": "1cfd0e6504bba7db9ec79e2f243b99b4"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val Array(x0, y0) = in.next().split(' ').map(_.toLong)\n\n def mayBlock(x: Int, y: Int) = {\n x == x0 || y == y0 || (Math.abs(x - x0) == Math.abs(y - y0))\n }\n\n def scoreBlock(x: Int, y: Int) = {\n if (x == x0 && y > y0) 0 //\"UP\"\n else if (x == x0 && y < y0) 1 // \"DOWN\"\n else if (y == y0 && x > x0) 2 // \"RIGHT\"\n else if (y == y0 && x < x0) 3 // \"LEFT\"\n else if (y > y0 && x > x0) 4 // \"UP RIGHT\"\n else if (y > y0 && x < x0) 5 // \"UP LEFT\"\n else if (y < y0 && x > x0) 6 // \"DOWN RIGHT\"\n else if (y < y0 && x < x0) 7 // \"DOWN LEFT\"\n else throw new Exception(s\"don't know $x $y\")\n }\n\n def attack(t: Int, score: Int) = t == 2 || (t == 0 && score > 3) || (t == 1 && score < 4)\n\n val line = in.take(n).map(_.split(' ')).map {\n case Array(\"B\", x, y) => (0, x.toInt, y.toInt)\n case Array(\"R\", x, y) => (1, x.toInt, y.toInt)\n case Array(\"Q\", x, y) => (2, x.toInt, y.toInt)\n }.filter{\n case (d, x, y) => mayBlock(x, y)\n }.toList\n\n val res = line.sortBy {\n case (s, x, y) => Math.max(Math.abs(x - x0), Math.abs(y - y0))\n }.foldLeft(false, Set.empty[Int]) {\n case ((true, set), el) => (true, set)\n case ((false, set), (l, x, y)) =>\n val score = scoreBlock(x, y)\n if (set.contains(score))\n (false, set)\n else if (attack(l, score))\n (true, set)\n else\n (false, set + score)\n }._1\n if (res)\n println(\"YES\")\n else\n println(\"NO\")\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Solution {\n\n trait ChessPiece {\n val x: Int\n val y: Int\n def checkMate(x1: Int, y1: Int): Boolean\n }\n\n case class Rook (x: Int, y: Int) extends ChessPiece {\n def checkMate(x1: Int, y1: Int): Boolean = x1 == x || y1 == y\n }\n\n case class Bishop(x: Int, y: Int) extends ChessPiece {\n def checkMate(x1: Int, y1: Int): Boolean = Math.abs(x1 - x) == Math.abs(y1 - y)\n }\n\n case class Queen (x: Int, y: Int) extends ChessPiece {\n def checkMate(x1: Int, y1: Int): Boolean = x1 == x || y1 == y || Math.abs(x1 - x) == Math.abs(y1 - y)\n }\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val Array(x, y) = readLine.split(\" \").map(_.toInt)\n val list = List.fill(n)(readLine.split(\" \").toList).map {\n case \"R\" :: x1 :: y1 => Rook(x1.toInt, y1.head.toInt)\n case \"B\" :: x1 :: y1 => Bishop(x1.toInt, y1.head.toInt)\n case \"Q\" :: x1 :: y1 => Queen(x1.toInt, y1.head.toInt)\n }\n if( List(\n list.filter(p => p.x == x && p.y > y).sortBy(_.y), // Up\n list.filter(p => p.x == x && p.y < y).sortBy(-_.y), // Down\n list.filter(p => p.y == y && p.x > x).sortBy(_.x), // Right\n list.filter(p => p.y == y && p.x < x).sortBy(-_.x), // Left\n list.filter(p => p.x - x == p.y - y && p.x > x).sortBy(_.x), // Up-Right\n list.filter(p => p.x - x == p.y - y && p.x < x).sortBy(-_.x), // Down-Left\n list.filter(p => p.x - x == y - p.y && p.x > x).sortBy(_.x), // Down-Right\n list.filter(p => p.x - x == y - p.y && p.x < x).sortBy(-_.x) // Up-Left\n ).filter(_.nonEmpty).map(_.head).exists(_.checkMate(x, y))) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _734D extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n = read[Int]\n val kx, ky = read[Long]\n\n var north, northeast, east, southeast, south, southwest, west, northwest = Option.empty[Piece]\n\n repeat(n) {\n val piece = Piece(read[Char], read[Long], read[Long])\n (piece.x, piece.y) match {\n case (`kx`, y) if y < ky && (north.isEmpty || y > north.get.y) => north = Some(piece)\n case (`kx`, y) if ky < y && (south.isEmpty || y < south.get.y) => south = Some(piece)\n case ( x, `ky`) if x < kx && ( west.isEmpty || x > west.get.x) => west = Some(piece)\n case ( x, `ky`) if kx < x && ( east.isEmpty || x < east.get.x) => east = Some(piece)\n case ( x, y) if (kx - x).abs == (ky - y).abs =>\n ((kx - x).signum, (ky - y).signum) match {\n case (-1, -1) if northwest.isEmpty || (kx - x).abs < (kx - northwest.get.x).abs => northwest = Some(piece)\n case (-1, 1) if southwest.isEmpty || (kx - x).abs < (kx - southwest.get.x).abs => southwest = Some(piece)\n case ( 1, -1) if northeast.isEmpty || (kx - x).abs < (kx - northeast.get.x).abs => northeast = Some(piece)\n case ( 1, 1) if southeast.isEmpty || (kx - x).abs < (kx - southeast.get.x).abs => southeast = Some(piece)\n case _ =>\n }\n case _ =>\n }\n debug(piece, north, northeast, east, southeast, south, southwest, west, northwest)\n }\n\n val isCheck = Seq(north, east, south, west).flatten.exists(p => p.kind == 'Q' || p.kind == 'R') ||\n Seq(northeast, southeast, southwest, northwest).flatten.exists(p => p.kind == 'Q' || p.kind == 'B')\n\n write(isCheck.toEnglish)\n }\n\n case class Piece(kind: Char, x: Long, y: Long)\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Solution {\n\n trait ChessPiece {\n val x: Int\n val y: Int\n\n def checkMate(x1: Int, y1: Int): Boolean\n }\n\n case class Rook(x: Int, y: Int) extends ChessPiece {\n def checkMate(x1: Int, y1: Int): Boolean = x1 == x || y1 == y\n }\n\n case class Bishop(x: Int, y: Int) extends ChessPiece {\n def checkMate(x1: Int, y1: Int): Boolean = Math.abs(x1 - x) == Math.abs(y1 - y)\n }\n\n case class Queen(x: Int, y: Int) extends ChessPiece {\n def checkMate(x1: Int, y1: Int): Boolean = x1 == x || y1 == y || Math.abs(x1 - x) == Math.abs(y1 - y)\n }\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val Array(x, y) = readLine.split(\" \").map(_.toInt)\n val list = List.fill(n)(readLine.split(\" \").toList).map {\n case \"R\" :: x1 :: y1 :: Nil => Rook(x1.toInt, y1.toInt)\n case \"Q\" :: x1 :: y1 :: Nil => Queen(x1.toInt, y1.toInt)\n case \"B\" :: x1 :: y1 :: Nil => Bishop(x1.toInt, y1.toInt)\n }\n if (List(\n list.filter(p => p.x == x && p.y > y).sortBy(_.y), // Up\n list.filter(p => p.x == x && p.y < y).sortBy(-_.y), // Down\n list.filter(p => p.y == y && p.x > x).sortBy(_.x), // Right\n list.filter(p => p.y == y && p.x < x).sortBy(-_.x), // Left\n list.filter(p => p.x - x == p.y - y && p.x > x).sortBy(_.x), // Up-Right\n list.filter(p => p.x - x == p.y - y && p.x < x).sortBy(-_.x), // Down-Left\n list.filter(p => p.x - x == y - p.y && p.x > x).sortBy(_.x), // Down-Right\n list.filter(p => p.x - x == y - p.y && p.x < x).sortBy(-_.x) // Up-Left\n ).filter(_.nonEmpty).exists(_.head.checkMate(x, y))) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val Array(x0, y0) = in.next().split(' ').map(_.toInt)\n\n def mayBlock(x: Int, y: Int) = {\n x == x0 || y == y0 || (Math.abs(x - x0) == Math.abs(y - y0))\n }\n\n def scoreBlock(x: Int, y: Int) = {\n if (x == x0 && y > y0) 0 //\"UP\"\n else if (x == x0 && y < y0) 1 // \"DOWN\"\n else if (y == y0 && x > x0) 2 // \"RIGHT\"\n else if (y == y0 && x < x0) 3 // \"LEFT\"\n else if (y > y0 && x > x0) 4 // \"UP RIGHT\"\n else if (y > y0 && x < x0) 5 // \"UP LEFT\"\n else if (y < y0 && x > x0) 6 // \"DOWN RIGHT\"\n else if (y < y0 && x < x0) 7 // \"DOWN LEFT\"\n else throw new Exception(s\"don't know $x $y\")\n }\n\n def attack(t: Int, score: Int) = t == 2 || (t == 0 && score > 3) || (t == 1 && score < 4)\n\n val line = in.take(2).map(_.split(' ')).map {\n case Array(\"B\", x, y) => (0, x.toInt, y.toInt)\n case Array(\"R\", x, y) => (1, x.toInt, y.toInt)\n case Array(\"Q\", x, y) => (2, x.toInt, y.toInt)\n }.filter{\n case (d, x, y) => mayBlock(x, y)\n }.toList\n\n val res = line.sortBy {\n case (s, x, y) => Math.max(Math.abs(x - x0), Math.abs(y - y0))\n }.foldLeft(false, Set.empty[Int]) {\n case ((true, set), el) => (true, set)\n case ((false, set), (l, x, y)) =>\n val score = scoreBlock(x, y)\n if (set.contains(score))\n (false, set)\n else if (attack(l, score))\n (true, set)\n else\n (false, set + score)\n }._1\n if (res)\n println(\"YES\")\n else\n println(\"NO\")\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val Array(x0, y0) = in.next().split(' ').map(_.toInt)\n\n def mayBlock(x: Int, y: Int) = {\n x == x0 || y == y0 || (Math.abs(x - x0) == Math.abs(y - y0))\n }\n\n def scoreBlock(x: Int, y: Int) = {\n if (x == x0 && y > y0) 0 //\"UP\"\n else if (x == x0 && y < y0) 1 // \"DOWN\"\n else if (y == y0 && x > x0) 2 // \"RIGHT\"\n else if (y == y0 && x < x0) 3 // \"LEFT\"\n else if (y > y0 && x > x0) 4 // \"UP RIGHT\"\n else if (y > y0 && x < x0) 5 // \"UP LEFT\"\n else if (y < y0 && x > x0) 6 // \"DOWN RIGHT\"\n else if (y < y0 && x < x0) 7 // \"DOWN LEFT\"\n else throw new Exception(s\"don't know $x $y\")\n }\n\n def attack(t: Int, score: Int) = t == 2 || (t == 0 && score > 3) || (t == 1 && score < 4)\n\n val line = in.take(2).map(_.split(' ')).map {\n case Array(\"B\", x, y) => (0, x.toInt, y.toInt)\n case Array(\"R\", x, y) => (1, x.toInt, y.toInt)\n case Array(\"Q\", x, y) => (2, x.toInt, y.toInt)\n }.filter{\n case (d, x, y) => mayBlock(x, y)\n }.toList\n\n val res = line.sortBy {\n case (s, x, y) => Math.max(Math.abs(x - x0), Math.abs(y - y0))\n }.foldLeft(false, Set.empty[Int]) {\n case ((true, set), el) => (true, set)\n case ((false, set), (l, x, y)) =>\n val score = scoreBlock(x, y)\n println(set)\n if (set.contains(score))\n (false, set)\n else if (attack(l, score))\n (true, set)\n else\n (false, set + score)\n }._1\n if (res)\n println(\"YES\")\n else\n println(\"NO\")\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val Array(x0, y0) = in.next().split(' ').map(_.toLong)\n\n def mayBlock(x: Long, y: Long) = {\n x == x0 || y == y0 || (Math.abs(x - x0) == Math.abs(y - y0))\n }\n\n def scoreBlock(x: Long, y: Long) = {\n if (x == x0 && y > y0) 0 //\"UP\"\n else if (x == x0 && y < y0) 1 // \"DOWN\"\n else if (y == y0 && x > x0) 2 // \"RIGHT\"\n else if (y == y0 && x < x0) 3 // \"LEFT\"\n else if (y > y0 && x > x0) 4 // \"UP RIGHT\"\n else if (y > y0 && x < x0) 5 // \"UP LEFT\"\n else if (y < y0 && x > x0) 6 // \"DOWN RIGHT\"\n else if (y < y0 && x < x0) 7 // \"DOWN LEFT\"\n else throw new Exception(s\"don't know $x $y\")\n }\n\n def attack(t: Int, score: Int) = t == 2 || (t == 0 && score > 3) || (t == 1 && score < 4)\n\n val line = in.take(2).map(_.split(' ')).map {\n case Array(\"B\", x, y) => (0, x.toLong, y.toLong)\n case Array(\"R\", x, y) => (1, x.toLong, y.toLong)\n case Array(\"Q\", x, y) => (2, x.toLong, y.toLong)\n }.filter{ case (d, x, y) => mayBlock(x, y) }.toList\n .sortBy {\n case (s, x, y) => Math.max(Math.abs(x - x0), Math.abs(y - y0))\n }\n\n val res = line.foldLeft(false, Set.empty[Int]) {\n case ((true, set), el) => (true, set)\n case ((false, set), (l, x, y)) =>\n val score = scoreBlock(x, y)\n if (set.contains(score))\n (false, set)\n else if (attack(l, score))\n (true, set)\n else\n (false, set + score)\n }._1\n if (res)\n println(\"YES\")\n else\n println(\"NO\")\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val Array(x0, y0) = in.next().split(' ').map(_.toLong)\n\n def mayBlock(x: Int, y: Int) = {\n x == x0 || y == y0 || (Math.abs(x - x0) == Math.abs(y - y0))\n }\n\n def scoreBlock(x: Int, y: Int) = {\n if (x == x0 && y > y0) 0 //\"UP\"\n else if (x == x0 && y < y0) 1 // \"DOWN\"\n else if (y == y0 && x > x0) 2 // \"RIGHT\"\n else if (y == y0 && x < x0) 3 // \"LEFT\"\n else if (y > y0 && x > x0) 4 // \"UP RIGHT\"\n else if (y > y0 && x < x0) 5 // \"UP LEFT\"\n else if (y < y0 && x > x0) 6 // \"DOWN RIGHT\"\n else if (y < y0 && x < x0) 7 // \"DOWN LEFT\"\n else throw new Exception(s\"don't know $x $y\")\n }\n\n def attack(t: Int, score: Int) = t == 2 || (t == 0 && score > 3) || (t == 1 && score < 4)\n\n val line = in.take(2).map(_.split(' ')).map {\n case Array(\"B\", x, y) => (0, x.toInt, y.toInt)\n case Array(\"R\", x, y) => (1, x.toInt, y.toInt)\n case Array(\"Q\", x, y) => (2, x.toInt, y.toInt)\n }.filter{\n case (d, x, y) => mayBlock(x, y)\n }.toList\n\n val res = line.sortBy {\n case (s, x, y) => Math.max(Math.abs(x - x0), Math.abs(y - y0))\n }.foldLeft(false, Set.empty[Int]) {\n case ((true, set), el) => (true, set)\n case ((false, set), (l, x, y)) =>\n val score = scoreBlock(x, y)\n if (set.contains(score))\n (false, set)\n else if (attack(l, score))\n (true, set)\n else\n (false, set + score)\n }._1\n if (res)\n println(\"YES\")\n else\n println(\"NO\")\n}"}], "src_uid": "b389750613e9577b3abc9e5e5902b2db"} {"source_code": "import java.io._\nimport java.util\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n\n\n def dfs(x: Int): Int = {\n was(x) = true\n if (set1.contains(x))\n x\n else {\n var ans = -1\n edges(x).foreach { e =>\n if (!was(e) && ans == -1)\n ans = dfs(e)\n }\n ans\n }\n }\n\n val was = Array.fill(1000)(false)\n val edges = Array.fill(1000)(ArrayBuffer[Int]())\n val set1 = mutable.Set[Int]()\n val set2 = mutable.Set[Int]()\n\n def solve(in: InputReader): Unit = {\n val tests = in.nextInt\n (1 to tests).foreach { _ =>\n val n = in.nextInt\n util.Arrays.fill(was, false)\n edges.foreach(_.clear())\n (1 until n) foreach { _ =>\n val x, y = in.nextInt - 1\n edges(x).append(y)\n edges(y).append(x)\n }\n val k1 = in.nextInt\n set1.clear()\n (1 to k1).foreach(_ => set1.add(in.nextInt - 1))\n\n val k2 = in.nextInt\n set2.clear()\n (1 to k2).foreach(_ => set2.add(in.nextInt - 1))\n //set2.foreach(println)\n System.out.println(s\"B ${set2.head + 1}\")\n System.out.flush()\n val t = in.nextInt - 1\n\n val ans = dfs(t)\n\n System.out.println(s\"A ${ans + 1}\")\n System.out.flush()\n\n if (set2.contains(in.nextInt - 1))\n System.out.println(s\"C ${ans + 1}\")\n else\n System.out.println(s\"C -1\")\n System.out.flush()\n }\n\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toDouble\n }\n\n def nextLong: Long = {\n next.toLong\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(t) = readInts(1)\n\n for (_ <- 1 to t) {\n val Array(n) = readInts(1)\n\n val adjBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }\n for (_ <- 1 until n) {\n val Array(a, b) = readInts(2)\n adjBuilders(a - 1) += b - 1\n adjBuilders(b - 1) += a - 1\n }\n val adjs = adjBuilders.map(_.result())\n\n val Array(k1) = readInts(1)\n val xs = readInts(k1).toSet\n\n val Array(k2) = readInts(1)\n val ys = readInts(k2).toSet\n\n println(\"B \" + ys.min)\n val xx = readLine.toInt\n\n def dfs(u: Int, parent: Int, depth: Int): Int = {\n if (xs(u + 1)) u\n else {\n val it = adjs(u).iterator\n var res = -1\n while (it.hasNext) {\n val v = it.next()\n if (v != parent) {\n val d = dfs(v, u, depth + 1)\n if (d >= 0) res = d\n }\n }\n res\n }\n }\n\n val d = dfs(xx - 1, -1, 0) + 1\n\n println(\"A \" + d)\n val yy = readLine.toInt\n\n if (ys(yy)) println(\"C \" + d)\n else println(\"C -1\")\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n def ask(com: Char, node: Int): Int = {\n println(s\"$com $node\")\n ni()\n }\n\n def answer(node: Int): Unit = {\n println(s\"C $node\")\n }\n\n rep(ni()) { _ =>\n val N = ni()\n val (from, to) = na2(N - 1, -1)\n val g = packUGraph(N, from, to)\n val k1 = ni()\n val X = na(k1, -1)\n val k2 = ni()\n val Y = na(k2, -1)\n val setY = Set(Y: _*)\n val y0_x = ask('B', Y(0) + 1) - 1\n val rootSubTree = find(g, X, y0_x)\n val root_y = ask('A', rootSubTree + 1) - 1\n if (setY.contains(root_y)) {\n answer(rootSubTree + 1)\n } else {\n answer(-1)\n }\n }\n }\n\n def find(g: Array[Array[Int]], set: Array[Int], from: Int): Int = {\n val (depth, _, _) = traceBfs(g, from)\n set.minBy(v => depth(v))\n }\n\n /**\n * @return (depth, parent, queue)\n */\n def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {\n val n = g.length\n val INF = 1e9.toInt + 10\n val q, p = Array.ofDim[Int](n)\n q(0) = rt\n p(rt) = -1\n val d = Array.fill[Int](n)(INF)\n d(rt) = 0\n var cur = 0\n var last = 1\n while (cur < last) {\n val v = q(cur)\n rep(g(v).length) { i =>\n val u = g(v)(i)\n if (d(u) == INF) {\n d(u) = d(v) + 1\n p(u) = v\n q(last) = u\n last += 1\n }\n }\n cur += 1\n }\n (d, p, q)\n }\n\n /**\n * @param n ノード数\n */\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n rep(m)(i => p(from(i)) += 1)\n rep(m)(i => p(to(i)) += 1)\n rep(n)(i => t(i) = new Array(p(i)))\n rep(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n def ask(com: Char, node: Int): Int = {\n println(s\"$com $node\")\n ni()\n }\n\n def answer(node: Int): Unit = {\n println(s\"C $node\")\n }\n\n rep(ni()) { _ =>\n val N = ni()\n val (from, to) = na2(N - 1, -1)\n val g = packUGraph(N, from, to)\n val k1 = ni()\n val X = na(k1, -1)\n val k2 = ni()\n val Y = na(k2, -1)\n val setY = Set(Y: _*)\n if (k1 <= 5) {\n val ys = map(k1) { i =>\n ask('A', X(i) + 1) - 1\n }\n val ok = ys find setY.contains\n val ans = ok.map(_+1).getOrElse(-1)\n answer(ans)\n } else {\n val y = Y(0)\n val y_x = ask('B', y) - 1\n val rootSubTree = find(g, X, y_x)\n val root_y = ask('A', rootSubTree + 1) - 1\n if (setY.contains(root_y)) {\n answer(root_y + 1)\n } else {\n answer(-1)\n }\n }\n }\n }\n\n def find(g: Array[Array[Int]], set: Array[Int], from: Int): Int = {\n val (depth, _, _) = traceBfs(g, from)\n set.minBy(v => depth(v))\n }\n\n /**\n * @return (depth, parent, queue)\n */\n def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {\n val n = g.length\n val INF = 1e9.toInt + 10\n val q, p = Array.ofDim[Int](n)\n q(0) = rt\n p(rt) = -1\n val d = Array.fill[Int](n)(INF)\n d(rt) = 0\n var cur = 0\n var last = 1\n while (cur < last) {\n val v = q(cur)\n rep(g(v).length) { i =>\n val u = g(v)(i)\n if (d(u) == INF) {\n d(u) = d(v) + 1\n p(u) = v\n q(last) = u\n last += 1\n }\n }\n cur += 1\n }\n (d, p, q)\n }\n\n /**\n * @param n ノード数\n */\n def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {\n val t = new Array[Array[Int]](n)\n val p = new Array[Int](n)\n val m = from.length\n rep(m)(i => p(from(i)) += 1)\n rep(m)(i => p(to(i)) += 1)\n rep(n)(i => t(i) = new Array(p(i)))\n rep(m) { i =>\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n p(to(i)) -= 1\n t(to(i))(p(to(i))) = from(i)\n }\n t\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "f23d3e6ca1e4d7fbe5a2ca38ebb37c46"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val r1, c1, r2, c2 = ni() - 1\n val g = Array.ofDim[Array[Boolean]](N) // landかどうか\n REP(N) { i =>\n g(i) = ns(N).map(_ == '0')\n }\n\n DEBUG {\n REP(N) { i =>\n debug(g(i))\n }\n }\n\n val uf = new UnionFind(N * N)\n val D = Array(\n Array(-1, 0), Array(1, 0), Array(0, -1), Array(0, 1)\n )\n\n def nd(r: Int, c: Int) = r * N + c\n def dist(v: Int, u: Int): Int = {\n val rv = v / N\n val cv = v % N\n val ru = u / N\n val cu = u % N\n val r = abs(rv - ru)\n val c = abs(cv - cu)\n r * r + c * c\n }\n\n val v1 = nd(r1, c1)\n val v2 = nd(r2, c2)\n REP(N) { i =>\n REP(N) { j =>\n if (g(i)(j)) {\n val v = nd(i, j)\n REP(4) { k =>\n val di = D(k)(0)\n val dj = D(k)(1)\n if (di + i >= 0 && di + i < N && dj + j >= 0 && dj + j < N && g(i + di)(j + dj)) {\n uf.unite(v, nd(i + di, j + dj))\n }\n }\n }\n }\n }\n\n def sameSet(v: Int) = {\n val set = Array.ofDim[Boolean](N * N)\n val id = uf.find(v)\n REP(N * N) { i =>\n if (uf.find(i) == id) set(i) = true\n }\n set\n }\n\n // 連結されてるのでトンネルいらない\n if (uf.find(v1) == uf.find(v2)) out.println(0)\n else {\n val set1 = sameSet(v1)\n val set2 = sameSet(v2)\n\n debug(\"set1\")\n debug(set1)\n debug(\"set2\")\n debug(set2)\n\n var ans = 1e9.toInt\n // 周辺だけにしてもいいけど2500 * 2500でまにあうからやらない\n REP(N * N) { v =>\n REP(N * N) { u =>\n if (set1(v) && set2(u)) {\n ans = min(ans, dist(v, u))\n }\n }\n }\n\n out.println(ans)\n }\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n class UnionFind(val n: Int) {\n private val par = Array.ofDim[Int](n)\n REP(n) (i => par(i) = i)\n val rank: Array[Int] = Array.fill[Int](n)(1) // 集合の要素数\n private val visits = Array.ofDim[Int](n) // 訪れた場所をfind毎に用意するのがもったいないのでつかいまわす\n\n def find(x: Int): Int = {\n var ptr = 0\n def step(x: Int): Int = {\n if (par(x) == x) x\n else {\n visits(ptr) = x\n ptr += 1\n step(par(x))\n }\n }\n\n val res = step(x)\n REP(ptr){ i => par(visits(i)) = res }\n res\n }\n\n def unite(x: Int, y: Int): Int = {\n val x1 = find(x)\n val y1 = find(y)\n if (x1 == y1) x1\n else {\n if (rank(x1) < rank(y)) {\n par(x1) = y1\n y1\n } else {\n par(y1) = x1\n if (rank(x1) == rank(y1)) rank(x1) += rank(y1)\n x1\n }\n }\n }\n\n /**\n * xを解決する必要がないときは直にrankをみる\n */\n def cntNodes(x: Int): Int = rank(find(x))\n }\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugNum(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Codeforces1130C {\n\n def getMinimumTunnelLength(n: Int, r1: Int, c1: Int, r2: Int, c2: Int, grid: Seq[String]): Int = {\n val componentNumbers: Array[Array[Int]] = (1 to n).map(_ => (1 to n).map(_ => -1).toArray).toArray\n var componentNumber = 1\n var unexploredPoint = getFirstUnexploredPoint(n, componentNumbers)\n while (unexploredPoint != NullPoint) {\n startExploring(n, componentNumbers, grid, componentNumber, unexploredPoint)\n componentNumber += 1\n unexploredPoint = getFirstUnexploredPoint(n, componentNumbers)\n }\n\n val fromComponent = componentNumbers(r1 - 1)(c1 - 1)\n val toComponent = componentNumbers(r2 - 1)(c2 - 1)\n\n var minimumDistance = Int.MaxValue\n for (x1 <- 0 until n) for (y1 <- 0 until n) for (x2 <- 0 until n) for (y2 <- 0 until n)\n if (componentNumbers(x1)(y1) == fromComponent && componentNumbers(x2)(y2) == toComponent)\n minimumDistance = math.min(minimumDistance, calculateDistance(x1, y1, x2, y2))\n\n minimumDistance\n }\n\n def calculateDistance(x1: Int, y1: Int, x2: Int, y2: Int): Int = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)\n\n def getFirstUnexploredPoint(n: Int, componentNumbers: Array[Array[Int]]): Point = {\n for (i <- 0 until n) for (j <- 0 until n)\n if (componentNumbers(i)(j) == -1) return Point(i, j)\n NullPoint\n }\n\n def startExploring(n: Int, componentNumbers: Array[Array[Int]], grid: Seq[String], componentNumber: Int, point: Point): Unit = {\n componentNumbers(point.x)(point.y) = componentNumber\n for (neighbourPoint <- point.neighboursInRange(n)) {\n if (isSameType(point, neighbourPoint, grid)) {\n if (!isExplored(neighbourPoint, componentNumbers)) {\n startExploring(n, componentNumbers, grid, componentNumber, neighbourPoint)\n }\n }\n }\n }\n\n def isSameType(pointA: Point, pointB: Point, grid: Seq[String]): Boolean =\n grid(pointA.x)(pointA.y) == grid(pointB.x)(pointB.y)\n\n def isExplored(point: Point, componentNumbers: Array[Array[Int]]): Boolean =\n componentNumbers(point.x)(point.y) != -1\n\n def main(args: Array[String]): Unit = {\n val n = StdIn.readLine().trim.toInt\n val Array(r1, c1) = StdIn.readLine().trim.split(\" \").map(_.toInt)\n val Array(r2, c2) = StdIn.readLine().trim.split(\" \").map(_.toInt)\n val grid = (1 to n).map(_ => StdIn.readLine())\n\n val minimumTunnelLength = getMinimumTunnelLength(n, r1, c1, r2, c2, grid)\n println(minimumTunnelLength)\n }\n\n case class Point(x: Int, y: Int) {\n def isAdjacent(that: Point): Boolean =\n math.abs(this.x - that.x) + math.abs(this.y - that.y) == 1\n\n def left: Point = Point(x - 1, y)\n\n def right: Point = Point(x + 1, y)\n\n def up: Point = Point(x, y - 1)\n\n def down: Point = Point(x, y + 1)\n\n def fitsInRage(n: Int): Boolean = 0 <= x && x < n && 0 <= y && y < n\n\n def neighboursInRange(n: Int): Seq[Point] =\n Seq(left, right, up, down).filter(p => p.fitsInRage(n))\n }\n\n object NullPoint extends Point(-1, -1) {}\n\n}\n"}], "negative_code": [], "src_uid": "6fe23a0ecc1c05e89d5680aa2ec6cb05"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n var map = Map.empty[String, Int]\n\n def stringToPattern(number: String): String = {\n val nNumber = \"0\" * (18 - number.length) + number\n nNumber.map(i => if (i.asDigit % 2 == 0) '0' else '1').mkString\n }\n\n val a = in.take(n).toList.foldLeft(List.empty[Int]) {\n case (ans, str) if str.startsWith(\"+\") =>\n val pattern = stringToPattern(str.drop(2))\n map += pattern -> (map.getOrElse(pattern, 0) + 1)\n ans\n case (ans, str) if str.startsWith(\"-\") =>\n val pattern = stringToPattern(str.drop(2))\n map += pattern -> (map.getOrElse(pattern, 0) - 1)\n ans\n case (ans, str) if str.startsWith(\"?\") =>\n map.getOrElse(stringToPattern(str.drop(2)), 0) :: ans\n }\n println(a.reverse.mkString(\"\\n\"))\n}\n", "positive_code": [{"source_code": "//package merofeev.contests.codeforces.rnd371\n\nimport java.util.Scanner\n\nimport scala.collection.mutable\n\n/**\n * @author erofeev \n * @since 13.09.16\n */\nobject CMasks {\n\n class MyHashMap[A, B](initSize: Int) extends mutable.HashMap[A, B] {\n override def initialSize: Int = initSize // 16 - by default\n }\n\n def parseBits(i: String): Int = {\n var res = 0\n val irev: String = i.reverse\n for (elem <- irev.indices if irev.charAt(elem) == '1') {\n res |= 1 << elem\n }\n res\n }\n\n\n def oddBits(input: Long): Int = {\n var res = 0\n var i = input\n var delim = 0\n for (pos <- 0 to 18) {\n if ((i & 1) == 1) {\n res |= 1 << pos\n }\n i /= 10\n }\n res\n }\n\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n val masks = new Array[Int](1 << 19 + 2)\n var pos = 0\n while (in.hasNextLine) {\n val comm = in.nextLine().split(\" \")\n if (comm(0) == \"+\") {\n val bits: Int = oddBits(comm(1).toLong)\n masks(bits) += 1\n } else if (comm(0) == \"-\") {\n val bits: Int = oddBits(comm(1).toLong)\n masks(bits) -= 1\n } else if (comm(0) == \"?\") {\n val bits: Int = parseBits(comm(1))\n println(masks(bits))\n }\n pos += 1\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C371A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C371A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n val store = collection.mutable.HashMap[String, Int]()\n REP(t) { _ =>\n val c = nc()\n c match {\n case '+' =>\n val a = nl()\n val s = calculate(a)\n if(store.contains(s)) {\n store(s) = store(s) + 1\n } else store(s) = 1\n case '-' =>\n val a = nl()\n val s = calculate(a)\n if(store.contains(s)) {\n store(s) = store(s) - 1\n }\n case '?' =>\n val a = nl()\n val s = calculate(a)\n if(store.contains(s)) {\n out.println(store(s))\n } else out.println(0)\n }\n }\n }\n\n def calculate(n: Long): String = {\n var r = n\n val st = new StringBuilder()\n while (r > 0) {\n val x = r % 10\n st.append(x % 2)\n r /= 10\n }\n while (st.length < 19) {\n st.append(\"0\")\n }\n st.reverse.toString()\n }\n}\n"}, {"source_code": "object CF3713B extends App{\n\n import scala.collection.mutable.HashMap\n import scala.io.StdIn.{ readLine, readInt }\n case class Query(s: String) {\n lazy val ss = s.split(\" \")\n lazy val q = ss(0)\n lazy val value = ss(1)\n lazy val isQuery = q == \"?\"\n lazy val isPlus = q == \"+\"\n lazy val isMinus = q == \"-\"\n lazy val _hashed = value.toCharArray.map(x => x.toInt % 2).mkString(\"\")\n lazy val hashed = _hashed.toLong\n }\n\n object Query {\n var memo = new HashMap[Long, Integer]\n\n def query(q: Query): Integer = {\n memo.getOrElse(q.value.toLong, 0)\n }\n\n def increment(q: Query): Unit = {\n val currentValue = memo.get(q.hashed)\n if(currentValue.isEmpty){\n memo.put(q.hashed, 1)\n }else{\n memo.update(q.hashed, currentValue.get + 1)\n }\n }\n\n def decrement(q: Query): Unit = {\n val currentValue = memo.get(q.hashed)\n memo.update(q.hashed, currentValue.get - 1)\n }\n\n }\n\n val n = readInt()\n 0.to(n - 1).foreach(_ => {\n val s = readLine()\n val q = Query(s)\n if(q.isMinus){\n Query.decrement(q)\n }else if(q.isPlus){\n Query.increment(q)\n }else if(q.isQuery){\n println(Query.query(q))\n }\n })\n}\n\n"}, {"source_code": "import java.util\n\nobject CF3713B extends App{\n\n import scala.collection.mutable.HashMap\n import scala.io.StdIn.{ readLine, readInt }\n case class Query(s: String) {\n lazy val ss = s.split(\" \")\n lazy val q = ss(0)\n lazy val value = ss(1)\n lazy val isQuery = q == \"?\"\n lazy val isPlus = q == \"+\"\n lazy val isMinus = q == \"-\"\n lazy val _hashed = value.toCharArray.map(x => x.toInt % 2).mkString(\"\")\n lazy val hashed = _hashed.toLong\n }\n\n object Query {\n var memo = new HashMap[Long, Int]\n\n def query(q: Query): Int = {\n memo.getOrElse(q.value.toLong, 0)\n }\n\n def increment(q: Query): Unit = {\n val currentValue = memo.get(q.hashed)\n if(currentValue.isEmpty){\n memo.put(q.hashed, 1)\n }else{\n memo.update(q.hashed, currentValue.get + 1)\n }\n }\n\n def decrement(q: Query): Unit = {\n val currentValue = memo.get(q.hashed)\n memo.update(q.hashed, currentValue.get - 1)\n }\n\n }\n\n var buffer = new StringBuilder()\n val n = readInt()\n val fs = List(\"+ 200\", \"+ 100\", \"+ 401\", \"? 1\", \"? 0\")\n 0.to(n - 1).foreach(i => {\n val s = readLine()\n val q = Query(s)\n if(q.isMinus){\n Query.decrement(q)\n }else if(q.isPlus){\n Query.increment(q)\n }else if(q.isQuery){\n buffer.append(Query.query(q))\n buffer.append(\"\\n\")\n }\n })\n print(buffer.stripLineEnd.toString())\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _714C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll}\n\n def hash(x: Long) = Integer.parseInt(x.toString.map(c => (((c - '0')%2) + '0').toChar), 2)\n\n val table = map[Int] to 0\n\n repeat(read[Int]) {\n val (c, x) = read[(Char, Long)]\n val h = hash(x)\n c match {\n case '+' => table(h) += 1\n case '-' => table(h) -= 1\n case '?' => write(table(h), '\\n')\n }\n }\n\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import collection.mutable.HashMap;\n\nobject CF3713B extends App {\n val n = readLine.toInt\n val d = new HashMap[Long,Long]()\n for (i <- 0 until n) {\n val spl = readLine.split(\" \")\n val m = spl(1).toLong\n val p = toBitsNumber(m)\n spl(0) match {\n case \"+\" => d += p -> (1L +d.getOrElse(p, 0L))\n case \"-\" => d += p -> (d(p) - 1)\n case \"?\" => println(d.getOrElse(m, 0))\n }\n }\n \n def toBitsNumber(n:Long) : Long = {\n var res : Long = 0\n var k : Long = 1\n var t : Long= n\n while (t > 0) {\n res += k*(t%2)\n k *= 10\n t /= 10\n }\n return res\n } \n}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.Map\n\nobject Main{\n val map: Map[String, Int] = Map()\n\n def trans(s: String): String = {\n val res = s.toArray\n for(i <- 0 until res.length)\n if(res(i) % 2 == 0)\n res(i) = '0'\n else\n res(i) = '1'\n \"0\"*(18-res.length) + String.valueOf(res)\n }\n\n def transH(s: String): String = {\n \"0\"*(18-s.length) + s\n }\n\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val t = sc.nextInt()\n\n for(k <- 1 to t){\n val c = sc.next(); val s = sc.next()\n if(c == \"+\"){\n val now = trans(s)\n if(map.contains(now))\n map(now) += 1\n else\n map += (now -> 1)\n }\n else if(c == \"-\"){\n val now = trans(s)\n map(now) -= 1\n }\n else{ // ?\n var ans = 0\n val hat = transH(s)\n println(map.getOrElse(hat, 0))\n }\n }\n }\n}\n"}], "negative_code": [{"source_code": "object CF3713B extends App{\n\n import scala.collection.mutable.HashMap\n import scala.io.StdIn.{ readLine, readInt }\n case class Query(s: String) {\n lazy val ss = s.split(\" \")\n lazy val q = ss(0)\n lazy val value = ss(1)\n lazy val isQuery = q == \"?\"\n lazy val isPlus = q == \"+\"\n lazy val isMinus = q == \"-\"\n lazy val _hashed = value.toCharArray.map(x => x.toInt % 2).mkString(\"\")\n lazy val hashed = String.format(\"%1$18s\", _hashed).replace(\" \", \"0\")\n }\n\n object Query {\n var memo = new HashMap[String, Integer]\n\n def query(q: Query): Integer = {\n memo.getOrElse(q.hashed, 0)\n }\n\n def increment(q: Query): Unit = {\n val currentValue = memo.get(q.hashed)\n if(currentValue.isEmpty){\n memo.put(q.hashed, 1)\n }else{\n memo.update(q.hashed, currentValue.get + 1)\n }\n }\n\n def decrement(q: Query): Unit = {\n val currentValue = memo.get(q.hashed)\n memo.update(q.hashed, currentValue.get - 1)\n }\n\n }\n\n val n = readInt()\n 0.to(n - 1).foreach(_ => {\n val s = readLine()\n val q = Query(s)\n if(q.isMinus){\n Query.decrement(q)\n }else if(q.isPlus){\n Query.increment(q)\n }else if(q.isQuery){\n print(Query.query(q))\n }\n })\n}\n\n"}, {"source_code": "import java.util\n\nobject CF3713B extends App{\n\n import scala.collection.mutable.HashMap\n import scala.io.StdIn.{ readLine, readInt }\n case class Query(s: String) {\n lazy val ss = s.split(\" \")\n lazy val q = ss(0)\n lazy val value = ss(1)\n lazy val isQuery = q == \"?\"\n lazy val isPlus = q == \"+\"\n lazy val isMinus = q == \"-\"\n lazy val _hashed = value.toCharArray.map(x => x.toInt % 2).mkString(\"\")\n lazy val hashed = _hashed.toLong\n }\n\n object Query {\n var memo = new HashMap[Long, Int]\n\n def query(q: Query): Int = {\n memo.getOrElse(q.value.toLong, 0)\n }\n\n def increment(q: Query): Unit = {\n val currentValue = memo.get(q.hashed)\n if(currentValue.isEmpty){\n memo.put(q.hashed, 1)\n }else{\n memo.update(q.hashed, currentValue.get + 1)\n }\n }\n\n def decrement(q: Query): Unit = {\n val currentValue = memo.get(q.hashed)\n memo.update(q.hashed, currentValue.get - 1)\n }\n\n }\n\n var buffer = new StringBuilder()\n // val n = readInt()\n val n = 5\n val fs = List(\"+ 200\", \"+ 100\", \"+ 401\", \"? 1\", \"? 0\")\n 0.to(n - 1).foreach(i => {\n // val s = readLine()\n val s = fs(i)\n val q = Query(s)\n if(q.isMinus){\n Query.decrement(q)\n }else if(q.isPlus){\n Query.increment(q)\n }else if(q.isQuery){\n buffer.append(Query.query(q))\n buffer.append(\"\\n\")\n }\n })\n print(buffer.stripLineEnd.toString())\n}\n\n"}], "src_uid": "0ca6c7ff6a2d110a8f4153717910378f"} {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(x, y, k) = readLine().split(\" \").map(_.toLong)\n\n val ans = 1 + k + (k * (y + 1) - 2) / (x - 1)\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "/**\n * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools\n */\n\nimport scala.io.StdIn._\n\nobject Main {\n def g(x: Long, y: Long, k: Long): Long = {\n /*\n need k coals\n k coals = y * k sticks\n do stick exchange until you have >= k + y * k\n then add k coal exchanges\n */\n val sticks = BigInt(1)\n val limit = BigInt(k) + BigInt(y) * BigInt(k)\n\n val countDec: BigDecimal = BigDecimal(limit - sticks) / BigDecimal(-sticks + BigInt(x))\n var count: BigInt = if (countDec.isValidLong) countDec.toBigInt else\n countDec.toBigInt + BigInt(1)\n\n count += BigInt(k)\n count.toLong\n\n }\n\n def main(args: Array[String]): Unit = {\n // Write your solution here\n val t = readInt\n for (_ <- 0 until t) {\n val line = readLine.split(\" \").map(_.toLong)\n val (x, y, k) = (line(0), line(1), line(2))\n println(g(x, y, k))\n }\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject task1 extends App {\n val sets = readInt\n\n //var lst: List[Long] = List()\n (1 to sets).foreach { _ =>\n val xyk = readLine.split(\" \").map(_.toInt)\n val x = xyk(0)\n val y = xyk(1)\n val k = xyk(2)\n val sticks = k + k.toLong*y\n //println(\"Sticks needed \" + sticks)\n val rem =(sticks - 1) % (x - 1)\n val steps = if (rem == 0)\n (sticks - 1) / (x - 1) + k\n else\n (sticks - 1 - rem) / (x - 1) + k + 1\n\n // println(\"We get those with \" + (steps- xyk(2) ))\n //println(s\"And additional ${xyk(2)} to get coal\")\n //println()\n\n //lst = lst ::: List(steps)\n println(steps)\n\n }\n //lst.foreach { x =>\n //println(f\"$x%1.0f\")\n // println(x)\n // }\n\n\n}\n/*\n1000000000\n1000000000\n1000000000 + 1000000000*1000000000\n\n\n1000000001999999999\n\n */\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\nobject A extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val x = in.nextInt()\n val y = in.nextInt()\n val k = in.nextInt()\n\n val totalSticks = (y.toLong * k) + k - 1\n val roundTem = totalSticks / (x - 1)\n\n val round = if (totalSticks - (roundTem * (x - 1)) > 0) roundTem + 1 else roundTem\n\n println(round + k)\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextLineInt(n: Int): ArrayBuffer[Int] = {\n var data = ArrayBuffer[Int]()\n n.times({\n data += nextInt()\n })\n data\n }\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}, {"source_code": "/**\n * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools\n */\n\nimport scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n // Write your solution here\n val t = readInt\n for (_ <- 0 until t) {\n val line = readLine.split(\" \").map(_.toLong)\n val (x, y, k) = (line(0), line(1), line(2))\n println(((y + 1) * k - 1 + x - 2) / (x - 1) + k)\n }\n }\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject taskA extends App {\n val sets = readInt\n\n var lst: List[Int] = List()\n (1 to sets).foreach { _ =>\n val xyk = readLine.split(\" \").map(_.toInt)\n val sticks = xyk(2) + xyk(1)*xyk(2)\n //println(\"Sticks needed \" + sticks)\n val steps = (sticks - 1).toFloat / (xyk(0) - 1) match {\n case x if x % 1 > 0 => x + 1 - (x % 1) + xyk(2)\n case x => x + xyk(2)\n }\n //println(\"We get those with \" + (steps- xyk(2) ))\n //println(s\"And additional ${xyk(2)} to get coal\")\n\n lst = lst ::: List(steps.toInt)\n\n\n }\n lst.foreach { x =>\n println(x)\n }\n\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject task1 extends App {\n val sets = readInt\n\n var lst: List[Long] = List()\n (1 to sets).foreach { _ =>\n val xyk = readLine.split(\" \").map(_.toInt)\n val sticks = xyk(2) + xyk(2).toLong*xyk(1)\n //println(\"Sticks needed \" + sticks)\n val steps =(sticks - 1) % (xyk(0) - 1) match {\n case 0 => {\n // println(\"0\")\n // println(sticks-1, \", \", (sticks), \", \")\n (sticks - 1) / (xyk(0) - 1) + xyk(2)\n }\n case x => {\n println(x)\n (sticks - 1 - x) / (xyk(0) - 1) + xyk(2) + 1\n }\n }\n // println(\"We get those with \" + (steps- xyk(2) ))\n //println(s\"And additional ${xyk(2)} to get coal\")\n //println()\n\n lst = lst ::: List(steps)\n\n\n }\n lst.foreach { x =>\n //println(f\"$x%1.0f\")\n println(x)\n }\n\n\n}\n/*\n1000000000\n1000000000\n1000000000 + 1000000000*1000000000\n\n\n1000000001999999999\n\n */\n"}, {"source_code": "import scala.io.StdIn._\n\nobject task1 extends App {\n val sets = readInt\n\n var lst: List[Double] = List()\n (1 to sets).foreach { _ =>\n val xyk = readLine.split(\" \").map(_.toInt)\n val sticks = xyk(2) + xyk(1).toDouble*xyk(2)\n // println(\"Sticks needed \" + sticks)\n val steps = ((sticks - 1) % (xyk(0) - 1)) match {\n case 0 => (sticks - 1) / (xyk(0) - 1) + xyk(2)\n case x => (sticks - 1-x) / (xyk(0) - 1) + xyk(2) + 1\n }\n //println(\"We get those with \" + (steps- xyk(2) ))\n // println(s\"And additional ${xyk(2)} to get coal\")\n //println()\n\n lst = lst ::: List(steps.toDouble)\n\n\n }\n lst.foreach { x =>\n println(f\"$x%1.0f\")\n }\n\n\n}\n/*\n1000000000\n1000000000\n1000000000 + 1000000000*1000000000\n\n\n1000000001999999999\n\n */\n"}, {"source_code": "import scala.io.StdIn._\n\nobject taskA extends App {\n val sets = readInt\n\n var lst: List[Int] = List()\n (1 to sets).foreach { _ =>\n val xyk = readLine.split(\" \").map(_.toInt)\n val sticks = xyk(2) + xyk(1)*xyk(2)\n println(\"Sticks needed \" + sticks)\n val steps = (sticks - 1).toFloat / (xyk(0) - 1) match {\n case x if x % 1 > 0 => x + 1 - (x % 1) + xyk(2)\n case x => x + xyk(2)\n }\n println(\"We get those with \" + (steps- xyk(2) ))\n println(s\"And additional ${xyk(2)} to get coal\")\n\n lst = lst ::: List(steps.toInt)\n\n\n }\n lst.foreach { x =>\n println(x)\n }\n\n\n}\n"}], "src_uid": "28610d192329c78580db354f8dfc4094"} {"source_code": "import scala.io.StdIn.readInt\nobject task {\n def main(args: Array[String]): Unit = {\n var n = readInt()\n var arr = new Array[Int](n+1);\n arr = (readLine().+(\" 1\")).split(\" \").map(_.toInt)\n arr(n) = arr(n-1)^1\n var pol = arr(0)\n var it = 0\n while(it= 0 && cnt != count)\n\t{\n\t\tf = 0\n\t\n\t}\n\t\n\tcount = cnt\n }\n\t\n\tif (f == 0) println(\"NO\") else println(\"YES\")\n}"}, {"source_code": "object c extends App {\n import scala.io.StdIn._\n val n: Int = Integer.parseInt(readLine())\n val a: Array[Int] = readLine().split(\" \").map(Integer.parseInt(_))\n\n var len: Int = 0\n for (i <- 0 until n) {\n val j: Int = i-1\n if (i > 0 && a(i) != a(j)) {\n len = 0\n }\n len += 1\n }\n\n var cur: Int = 1\n var bad = false\n for (i <- 1 until n) {\n val j: Int = i-1\n if (a(i) != a(j)) {\n if (cur != len) {\n bad = true\n }\n cur = 1\n } else {\n cur += 1\n }\n }\n\n if (cur != len || bad) {\n println(\"NO\")\n } else {\n println(\"YES\")\n }\n}\n"}, {"source_code": "object Main extends App {\n var a = 0\n var b = 0\n val Array(n) = readLine.split(\" \").map(_.toLong)\n var s = readLine.split(\" \").map(_.toLong)\n if (s(s.size - 1) == 0) {\n s = s :+ 1.toLong\n } else {\n s = s :+ 0.toLong\n }\n var c = s(0)\n var l = 0\n for (i <- s) {\n if (i == c) {\n l = l + 1\n } else {\n if (i == 0) {\n if (a == 0) {\n a = l\n } else {\n if (a != l) {\n println(\"NO\")\n System.exit(0)\n }\n }\n }\n if (i == 1) {\n if (b == 0) {\n b = l\n } else {\n if (b != l) {\n println(\"NO\")\n System.exit(0)\n }\n }\n }\n l = 1\n if (a != 0 && b != 0) {\n if (a != b) {\n println(\"NO\")\n System.exit(0)\n }\n }\n }\n c = i\n }\n println(\"YES\")\n \n}"}], "negative_code": [], "src_uid": "75a00d8a614fd0bcb8504b0268a121e0"} {"source_code": "//package round111.div2\n\n/**\n * Created by IntelliJ IDEA.\n * User: User\n * Date: 08.03.12\n * Time: 6:54\n * To change this template use File | Settings | File Templates.\n */\n\nobject C {\n def main(args: Array[String]) = {\n var Array(n, k) = readLine() split ' ' map (_.toLong)\n k -= 1\n var cur = new Counter[Option[Long]](0, 0, None)\n val nums = (readLine() split ' ' map (_ toLong) sorted)\n val count = {\n val counts = nums flatMap (x =>\n if (Some(x) == cur.content) {\n cur.size += 1\n Nil\n } else {\n cur = new Counter(cur.start + cur.size, 1, Some(x))\n List(cur)\n })\n counts find (count => k < count.end * n && k >= count.start * n) match {\n case None => {\n println((counts.size, n, counts(0).start, counts(0).end, counts(0).content, counts(0).size))\n new Counter(0, 0, None)\n }\n case Some(x) => x\n }\n }\n val first = count.content.get\n val second = nums(((k - n * count.start) / count.size) toInt)\n\n\n val pair = first :: second :: Nil mkString \" \"\n\n println(pair)\n }\n\n class Counter[T](var start: Int, var size: Int, val content: T) {\n def end = start + size\n }\n\n\n}\n", "positive_code": [{"source_code": "//package round111.div2\n\n/**\n * Created by IntelliJ IDEA.\n * User: User\n * Date: 08.03.12\n * Time: 6:54\n * To change this template use File | Settings | File Templates.\n */\n\nobject C {\n def main(args: Array[String]) = {\n var Array(n, k) = readLine() split ' ' map (_.toLong)\n k -= 1\n var cur = new Counter(0, 0, -100L)\n val nums = (readLine() split ' ' map (_ toLong) sortWith ((a, b) => (a compareTo b) < 0))\n val count = {\n val counts = nums flatMap (x =>\n if (x == cur.content) {\n cur.size += 1\n Nil\n } else {\n cur = new Counter(cur.start + cur.size, 1, x)\n List(cur)\n })\n counts find (count => k < count.end * n && k >= count.start * n) match {\n case None => {\n println((counts.size, n, counts(0).start, counts(0).end, counts(0).content, counts(0).size))\n new Counter(0, 0, 0L)\n }\n case Some(x) => x\n }\n }\n val first = count.content\n val second = nums(((k - n * count.start) / count.size) toInt)\n\n\n val pair = first :: second :: Nil mkString \" \"\n\n println(pair)\n }\n\n class Counter[T](var start: Int, var size: Int, val content: T) {\n def end = start + size\n }\n\n\n}\n"}, {"source_code": "//package round111.div2\n\n/**\n * Created by IntelliJ IDEA.\n * User: User\n * Date: 08.03.12\n * Time: 6:54\n * To change this template use File | Settings | File Templates.\n */\n\nobject C {\n def main(args: Array[String]) = {\n var Array(n, k) = readLine() split ' ' map (_.toLong)\n k -= 1\n var cur = new Counter(0, 0, -100L)\n val nums = (readLine() split ' ' map (_ toLong) sorted)\n val count = {\n val counts = nums flatMap (x =>\n if (x == cur.content) {\n cur.size += 1\n Nil\n } else {\n cur = new Counter(cur.start + cur.size, 1, x)\n List(cur)\n })\n counts find (count => k < count.end * n && k >= count.start * n) match {\n case None => {\n println((counts.size, n, counts(0).start, counts(0).end, counts(0).content, counts(0).size))\n new Counter(0, 0, 0L)\n }\n case Some(x) => x\n }\n }\n val first = count.content\n val second = nums(((k - n * count.start) / count.size) toInt)\n\n\n val pair = first :: second :: Nil mkString \" \"\n\n println(pair)\n }\n\n class Counter[T](var start: Int, var size: Int, val content: T) {\n def end = start + size\n }\n\n\n}\n"}], "negative_code": [{"source_code": "//package round111.div2\n\n/**\n * Created by IntelliJ IDEA.\n * User: User\n * Date: 08.03.12\n * Time: 6:54\n * To change this template use File | Settings | File Templates.\n */\n\nobject C {\n val Array(n, k) = readLine() split ' ' map (_.toLong)\n val nums = readLine() split ' ' map (_ toInt) sorted\n val pair = (k - 1) / n :: (k - 1) % n :: Nil map (x => nums(x.toInt)) mkString \" \"\n\n def main(args: Array[String]) = println(pair)\n\n\n}\n"}], "src_uid": "d3b9ffa76436b957ca959cf9204f9873"} {"source_code": "object _1203C extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n import Utils._\n\n override def apply(io: IO): io.type = {\n val input = io.read[Set[Long]]\n val g = input.reduce(gcd)\n io.write(countDivisors(g))\n }\n\n def countDivisors(n: Long) = {\n val divisors = mutable.Set.empty[Long]\n for {\n i <- 1 to sqrt(n.toDouble).toInt\n if n%i == 0\n } {\n divisors += i.toLong\n divisors += n/i\n }\n divisors.size\n }\n\n @tailrec def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a%b)\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object _1203C extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val input = io.read[Set[Long]]\n val g = input.reduce(gcd)\n io.write(countDivisors(g))\n }\n\n def countDivisors(n: Long) = {\n val divisors = mutable.Set.empty[Long]\n for {\n i <- 1 to sqrt(n.toDouble).toInt\n if n%i == 0\n } {\n divisors += i.toLong\n divisors += n/i\n }\n divisors.size\n }\n\n @tailrec def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a%b)\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _1203C extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val input = io.read[Set[Long]]\n val g = input.reduce(gcd)\n io.write(countDivisors(g))\n }\n\n def countDivisors(n: Long) = {\n val divisors = mutable.Set.empty[Long]\n for {\n i <- 1 to sqrt(n.toDouble).toInt\n if n%i == 0\n } {\n divisors += i.toLong\n divisors += n/i\n }\n divisors.size\n }\n\n @tailrec def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a%b)\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "object _1203C extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO) = {\n val input = io.read[Set[Long]]\n val g = input.reduce(gcd)\n io.write(countDivisors(g))\n }\n\n def countDivisors(n: Long) = {\n val divisors = mutable.Set.empty[Long]\n for {\n i <- 1 to sqrt(n.toDouble).toInt\n if n%i == 0\n } {\n divisors += i.toLong\n divisors += n/i\n }\n divisors.size\n }\n\n @tailrec def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a%b)\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): Any\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out))\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "6379ec153377fb9c30a7b897659da7d6"} {"source_code": "/**\n * Created by yangchaozhong on 3/11/15.\n */\nobject CF522B extends App {\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val n = nextInt\n val w = Array.ofDim[Int](n)\n val h = Array.ofDim[Int](n)\n\n var sumW = 0\n var maxH = 0\n (0 until n).foreach { i =>\n w(i) = nextInt\n h(i) = nextInt\n sumW += w(i)\n if (h(i) > maxH)\n maxH = h(i)\n }\n\n var secondH = 0\n var maxTimes = 0\n (0 until n).foreach { i =>\n if (h(i) > secondH && h(i) != maxH) {\n secondH = h(i)\n }\n\n if (h(i) == maxH)\n maxTimes += 1\n }\n\n if (maxTimes > 1)\n secondH = maxH\n\n val res = (0 until n).map { i =>\n val width = sumW - w(i)\n if (h(i) == maxH) {\n width * secondH\n } else {\n width * maxH\n }\n }.mkString(\" \")\n\n out.println(res)\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n", "positive_code": [{"source_code": "\nimport java.io._\nimport java.util\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n class MultiTreeSet[T <: Comparable[T]] {\n val map = new util.TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val friends = new Array[(Int, Int)](n)\n var W = 0\n val H = new MultiTreeSet[Integer]()\n for (i <- 0 until n) {\n friends(i) = (nextInt, nextInt)\n W += friends(i)._1\n H.add(friends(i)._2)\n }\n for (i <- 0 until n) {\n val minW = W - friends(i)._1\n H.remove(friends(i)._2)\n var minH = 0\n minH = H.last\n H.add(friends(i)._2)\n out.print(minW.toLong * minH.toLong + \" \")\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Main4 extends App with IOUtils {\n val n = nextInt\n val whs = (1 to n).map { i =>\n nextIntPair\n }\n \n val sum = whs.map(_._1).sum\n \n val (maxHeight, secondMaxHeight) = whs.toStream.map(_._2).foldLeft((0, 0)) { (p, x) =>\n if (x > p._1)\n (x, p._1)\n else if (x > p._2)\n (p._1, x)\n else\n (p._1, p._2)\n }\n \n println(whs.map { case (w, h) =>\n (sum - w) * (if (h < maxHeight) maxHeight else secondMaxHeight)\n }.mkString(\" \"))\n}\n\ntrait IOUtils {\n var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def nextInt: Int = nextToken.toInt\n\n def nextLong: Long = nextToken.toLong\n\n def nextIntPair: (Int, Int) = (nextInt, nextInt)\n\n def nextToken: String = {\n if (tok == null || !tok.hasMoreTokens) {\n tok = new StringTokenizer(in.readLine)\n }\n\n tok.nextToken\n }\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Main4 extends App with IOUtils {\n val n = nextInt\n val whs = (1 to n).map { i =>\n nextIntPair\n }\n \n val sum = whs.map(_._1).sum\n \n val (maxHeight, secondMaxHeight) = whs.foldLeft((0, 0)) { (p, x) =>\n if (x._2 > p._1)\n (x._2, p._1)\n else if (x._2 > p._2)\n (p._1, x._2)\n else\n (p._1, p._2)\n }\n \n println(whs.map { case (w, h) =>\n (sum - w) * (if (h < maxHeight) maxHeight else secondMaxHeight)\n }.mkString(\" \"))\n}\n\ntrait IOUtils {\n var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def nextInt: Int = nextToken.toInt\n\n def nextLong: Long = nextToken.toLong\n\n def nextIntPair: (Int, Int) = (nextInt, nextInt)\n\n def nextToken: String = {\n if (tok == null || !tok.hasMoreTokens) {\n tok = new StringTokenizer(in.readLine)\n }\n\n tok.nextToken\n }\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Main4 extends App with IOUtils {\n val n = nextInt\n val whs = (1 to n).map { i =>\n nextIntPair\n }\n \n val sum = whs.map(_._1).sum\n \n val (maxHeight, secondMaxHeight) = whs.view.map(_._2).foldLeft((0, 0)) { (p, x) =>\n if (x > p._1)\n (x, p._1)\n else if (x > p._2)\n (p._1, x)\n else\n (p._1, p._2)\n }\n \n println(whs.map { case (w, h) =>\n (sum - w) * (if (h < maxHeight) maxHeight else secondMaxHeight)\n }.mkString(\" \"))\n}\n\ntrait IOUtils {\n var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def nextInt: Int = nextToken.toInt\n\n def nextLong: Long = nextToken.toLong\n\n def nextIntPair: (Int, Int) = (nextInt, nextInt)\n\n def nextToken: String = {\n if (tok == null || !tok.hasMoreTokens) {\n tok = new StringTokenizer(in.readLine)\n }\n\n tok.nextToken\n }\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Main4 extends App with IOUtils {\n val n = nextInt\n val (ws, hs) = (1 to n).map { i =>\n nextIntPair\n }.unzip\n \n val sum = ws.sum\n \n val (maxHeight, secondMaxHeight) = hs.foldLeft((0, 0)) { (p, x) =>\n if (x > p._1)\n (x, p._1)\n else if (x > p._2)\n (p._1, x)\n else\n (p._1, p._2)\n }\n \n println((ws zip hs).map { case (w, h) => \n (sum - w) * (if (h < maxHeight) maxHeight else secondMaxHeight)\n }.mkString(\" \"))\n}\n\ntrait IOUtils {\n var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def nextInt: Int = nextToken.toInt\n\n def nextLong: Long = nextToken.toLong\n\n def nextIntPair: (Int, Int) = (nextInt, nextInt)\n\n def nextToken: String = {\n if (tok == null || !tok.hasMoreTokens) {\n tok = new StringTokenizer(in.readLine)\n }\n\n tok.nextToken\n }\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Main4 extends App with IOUtils {\n val n = nextInt\n val whs = (1 to n).map { i =>\n nextIntPair\n }\n \n val sum = whs.map(_._1).sum\n \n val (maxHeight, secondMaxHeight) = whs.map(_._2).foldLeft((0, 0)) { (p, x) =>\n if (x > p._1)\n (x, p._1)\n else if (x > p._2)\n (p._1, x)\n else\n (p._1, p._2)\n }\n \n println(whs.map { case (w, h) =>\n (sum - w) * (if (h < maxHeight) maxHeight else secondMaxHeight)\n }.mkString(\" \"))\n}\n\ntrait IOUtils {\n var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def nextInt: Int = nextToken.toInt\n\n def nextLong: Long = nextToken.toLong\n\n def nextIntPair: (Int, Int) = (nextInt, nextInt)\n\n def nextToken: String = {\n if (tok == null || !tok.hasMoreTokens) {\n tok = new StringTokenizer(in.readLine)\n }\n\n tok.nextToken\n }\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Main4 extends App with IOUtils {\n val n = nextInt\n val whs = (1 to n).map { i =>\n nextIntPair\n }\n \n val sum = whs.view.map(_._1).sum\n \n val (maxHeight, secondMaxHeight) = whs.view.map(_._2).foldLeft((0, 0)) { (p, x) =>\n if (x > p._1)\n (x, p._1)\n else if (x > p._2)\n (p._1, x)\n else\n (p._1, p._2)\n }\n \n println(whs.map { case (w, h) =>\n (sum - w) * (if (h < maxHeight) maxHeight else secondMaxHeight)\n }.mkString(\" \"))\n}\n\ntrait IOUtils {\n var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def nextInt: Int = nextToken.toInt\n\n def nextLong: Long = nextToken.toLong\n\n def nextIntPair: (Int, Int) = (nextInt, nextInt)\n\n def nextToken: String = {\n if (tok == null || !tok.hasMoreTokens) {\n tok = new StringTokenizer(in.readLine)\n }\n\n tok.nextToken\n }\n}\n"}, {"source_code": "\nobject B522 extends App {\n\n val n = readInt\n val inp =\n (1 to n)\n .map(_ => readLine.split(\" \").map(_.toInt))\n\n val w = inp.map(x => x(0))\n val h = inp.map(x => x(1))\n\n val isum = w.sum\n val sm = inp.map(x => isum - x(0))\n\n val max1 = h.max\n val max2 = {if (h.count(_ == max1) > 1) max1 else h.filter(_ != max1 ).max}\n\n (1 to n).foreach(i => print(sm(i - 1) * {if (h(i - 1) == max1) max2 else max1} + \" \"))\n}"}], "negative_code": [{"source_code": "/**\n * Created by yangchaozhong on 3/11/15.\n */\nobject CF522B extends App {\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val n = nextInt\n val w = Array.ofDim[Int](n)\n val h = Array.ofDim[Int](n)\n\n var sumW = 0\n var maxH = 0\n var secondH = 0\n (0 until n).foreach { i =>\n w(i) = nextInt\n h(i) = nextInt\n sumW += w(i)\n if (h(i) > maxH)\n maxH = h(i)\n if (h(i) > secondH && h(i) < maxH)\n secondH = h(i)\n }\n\n if (secondH == 0)\n secondH = maxH\n\n val res = (0 until n).map { i =>\n val width = sumW - w(i)\n if (h(i) == maxH) {\n width * secondH\n } else {\n width * maxH\n }\n }.mkString(\" \")\n\n out.println(res)\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n"}, {"source_code": "/**\n * Created by yangchaozhong on 3/11/15.\n */\nobject CF522B extends App {\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val n = nextInt\n val w = Array.ofDim[Int](n)\n val h = Array.ofDim[Int](n)\n\n var sumW = 0\n var maxH = 0\n var secondH = 0\n (0 until n).foreach { i =>\n w(i) = nextInt\n h(i) = nextInt\n sumW += w(i)\n if (h(i) > maxH)\n maxH = h(i)\n if (h(i) > secondH && h(i) < maxH)\n secondH = h(i)\n }\n\n val res = (0 until n).map { i =>\n val width = sumW - w(i)\n if (h(i) == maxH) {\n width * secondH\n } else {\n width * maxH\n }\n }.mkString(\" \")\n\n out.println(res)\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n"}, {"source_code": "/**\n * Created by yangchaozhong on 3/11/15.\n */\nobject CF522B extends App {\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val n = nextInt\n val w = Array.ofDim[Int](n)\n val h = Array.ofDim[Int](n)\n\n var sumW = 0\n var maxH = 0\n (0 until n).foreach { i =>\n w(i) = nextInt\n h(i) = nextInt\n sumW += w(i)\n if (h(i) > maxH)\n maxH = h(i)\n }\n\n var secondH = 0\n (0 until n).foreach { i =>\n if (h(i) > secondH && h(i) != maxH) {\n secondH = h(i)\n }\n }\n\n val res = (0 until n).map { i =>\n val width = sumW - w(i)\n if (h(i) == maxH) {\n width * secondH\n } else {\n width * maxH\n }\n }.mkString(\" \")\n\n out.println(res)\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n"}, {"source_code": "/**\n * Created by yangchaozhong on 3/11/15.\n */\nobject CF522B extends App {\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val n = nextInt\n val w = Array.ofDim[Int](n)\n val h = Array.ofDim[Int](n)\n\n var sumW = 0\n var maxH = 0\n (0 until n).foreach { i =>\n w(i) = nextInt\n h(i) = nextInt\n sumW += w(i)\n if (h(i) > maxH)\n maxH = h(i)\n }\n\n var secondH = 0\n (0 until n).foreach { i =>\n if (h(i) > secondH && h(i) != maxH) {\n secondH = h(i)\n }\n }\n\n if (secondH == 0)\n secondH = maxH\n\n val res = (0 until n).map { i =>\n val width = sumW - w(i)\n if (h(i) == maxH) {\n width * secondH\n } else {\n width * maxH\n }\n }.mkString(\" \")\n\n out.println(res)\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val friends = new Array[(Int, Int)](n)\n var W = 0\n var H = mutable.TreeSet[Int]()\n for (i <- 0 until n) {\n friends(i) = (nextInt, nextInt)\n W += friends(i)._1\n H += friends(i)._2\n }\n for (i <- 0 until n) {\n val minW = W - friends(i)._1\n H -= friends(i)._2\n var minH = 0\n if (H.size == 0) {\n minH = friends(i)._2\n } else {\n minH = H.last\n }\n H += friends(i)._2\n out.print(minW.toLong * minH.toLong + \" \")\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "src_uid": "e1abc81cea4395ba675cf6ca93261ae8"} {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(x, y, z) = readLine().split(\" \").map(_.toInt)\n\n val ans =\n if (x == y && x >= z) Some((x, z, z))\n else if (x == z && x >= y) Some((y, x, y))\n else if (y == z && y >= x) Some((x, x, y))\n else None\n\n ans match {\n case Some((a, b, c)) => println(s\"YES\\n$a $b $c\")\n case _ => println(\"NO\")\n }\n }\n}\n", "positive_code": [{"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(x, y, z) = readLine().split(\" \").map(_.toInt)\n val max = x max (y max z)\n\n val (a, b, c) =\n if (x == y && x >= z) (x, z, z)\n else if (x == z && x >= y) (y, x, y)\n else if (y == z && y >= x) (x, x, y)\n else (-1, -1, -1)\n\n if (a > 0 && b > 0 && c > 0) println(s\"YES\\n$a $b $c\")\n else println(\"NO\")\n }\n}\n"}], "negative_code": [{"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(x, y, z) = readLine().split(\" \").map(_.toInt)\n val max = x max (y max z)\n\n val (a, b, c) =\n if (x == y && x >= z) (x, z, if (z > 1) z - 1 else if (x - 1 > z) z + 1 else -1)\n else if (x == z && x >= y) (y, x, if (y > 1) y - 1 else if (x - 1 > y) y + 1 else -1)\n else if (y == z && y >= x) (x, if (x > 1) x - 1 else if (y - 1 > x) x + 1 else -1, y)\n else (-1, -1, -1)\n\n if (a > 0 && b > 0 && c > 0) println(s\"YES\\n$a $b $c\")\n else println(\"NO\")\n }\n}\n"}], "src_uid": "f4804780d9c63167746132c35b2bdd02"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val posCum = cumSum(A.map(max(0, _)))\n val R = mutable.Map[Int, Int]()\n REP_r(N) { i =>\n if (!R.contains(A(i))) R(A(i)) = i\n }\n\n case class Ans(l: Int, r: Int, v: Long)\n var ans: Ans = null\n REP(N) { l =>\n val r = R(A(l))\n if (r > l) {\n val v = posCum(r) - posCum(l + 1) + A(l) + A(r)\n if (ans == null || v > ans.v) {\n ans = Ans(l, r, v)\n }\n }\n }\n\n var total = 0L\n var cnt = 0\n val cut = Array.ofDim[Boolean](N)\n REP(N) { i =>\n if (i < ans.l || i > ans.r || i != ans.l && i != ans.r && A(i) < 0) {\n cut(i) = true\n cnt += 1\n } else {\n total += A(i)\n }\n }\n\n out.println(s\"$total $cnt\")\n out.println(cut.zipWithIndex.filter(_._1).map(_._2 + 1).mkString(\" \"))\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "import collection.mutable.HashMap\nimport java.util._\nimport java.lang._\nimport java.io._\n\n/**\n * @author kperikov\n */\nobject A_331 {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val beauty = new Array[Int](n)\n val map = new HashMap[Int, ArrayList[Int]]\n for (i <- 0 to n - 1) {\n beauty(i) = nextInt\n val some = map.get(beauty(i))\n some match {\n case Some(x) => {\n x add i\n map put(beauty(i), x)\n }\n case None => {\n val x = new ArrayList[Int]()\n x add i\n map put(beauty(i), x)\n }\n }\n }\n //println(map.toString)\n val partialSums = new Array[Long](n + 1)\n val partialAllSums = new Array[Long](n + 1)\n partialSums(0) = 0\n partialSums(n) = 0\n partialAllSums(0) = 0\n partialAllSums(n) = 0\n for (i <- 1 to n) {\n if (beauty(i - 1) > 0) {\n partialSums(i) = partialSums(i - 1) + beauty(i - 1)\n } else {\n partialSums(i) = partialSums(i - 1)\n }\n partialAllSums(i) = partialAllSums(i - 1) + beauty(i - 1)\n //print(partialAllSums(i) + \" \")\n }\n //println\n var maxAns = Long.MIN_VALUE\n var begin = -1\n var end = -1\n val it = map.keysIterator\n while (it.hasNext) {\n val key = it.next\n val arr = map.get(key).get\n if (arr.size > 1) {\n val min = arr.get(0)\n val max = arr.get(arr.size - 1) + 1\n val res = partialSums(max - 1) - partialSums(min + 1) + beauty(max - 1) + beauty(min)\n if (res > maxAns) {\n maxAns = res\n begin = min\n end = max - 1\n }\n }\n }\n out.print(maxAns)\n var countToKill = 0\n val killed = new ArrayList[Int]\n for (i <- 0 until begin) {\n countToKill = countToKill + 1\n killed.add(i + 1)\n }\n for (i <- begin + 1 until end) {\n\n if (beauty(i) < 0) {\n countToKill = countToKill + 1\n killed.add(i + 1)\n }\n }\n\n for (i <- end + 1 until n) {\n countToKill = countToKill + 1\n killed.add(i + 1)\n }\n out.println(\" \" + countToKill)\n for (i <- 0 to killed.size - 1) {\n out.print(killed.get(i) + \" \")\n }\n\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n\n }\n\n}\n"}, {"source_code": "import collection.immutable.HashMap\nimport java.util._\nimport java.lang._\nimport java.io._\n\n/**\n * @author kperikov\n */\nobject A_331 {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val beauty = new Array[Int](n)\n var map = new HashMap[Int, ArrayList[Int]]\n for (i <- 0 to n - 1) {\n beauty(i) = nextInt\n val some = map.get(beauty(i))\n some match {\n case Some(x) => {\n x add i\n map = map + (beauty(i) -> x)\n }\n case None => {\n val x = new ArrayList[Int]()\n x add i\n map = map + (beauty(i) -> x)\n }\n }\n }\n //println(map.toString)\n val partialSums = new Array[Long](n + 1)\n val partialAllSums = new Array[Long](n + 1)\n partialSums(0) = 0\n partialSums(n) = 0\n partialAllSums(0) = 0\n partialAllSums(n) = 0\n for (i <- 1 to n) {\n if (beauty(i - 1) > 0) {\n partialSums(i) = partialSums(i - 1) + beauty(i - 1)\n } else {\n partialSums(i) = partialSums(i - 1)\n }\n partialAllSums(i) = partialAllSums(i - 1) + beauty(i - 1)\n //print(partialAllSums(i) + \" \")\n }\n //println\n var maxAns = Long.MIN_VALUE\n var begin = -1\n var end = -1\n val it = map.keysIterator\n while (it.hasNext) {\n val key = it.next\n val arr = map.get(key).get\n if (arr.size > 1) {\n val min = arr.get(0)\n val max = arr.get(arr.size - 1) + 1\n val res = partialSums(max - 1) - partialSums(min + 1) + beauty(max - 1) + beauty(min)\n if (res > maxAns) {\n maxAns = res\n begin = min\n end = max - 1\n }\n }\n }\n out.print(maxAns)\n var countToKill = 0\n val killed = new ArrayList[Int]\n for (i <- 0 until begin) {\n countToKill = countToKill + 1\n killed.add(i + 1)\n }\n for (i <- begin + 1 until end) {\n\n if (beauty(i) < 0) {\n countToKill = countToKill + 1\n killed.add(i + 1)\n }\n }\n\n for (i <- end + 1 until n) {\n countToKill = countToKill + 1\n killed.add(i + 1)\n }\n out.println(\" \" + countToKill)\n for (i <- 0 to killed.size - 1) {\n out.print(killed.get(i) + \" \")\n }\n\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val posCum = cumSum(A.map(max(0, _)))\n val R = mutable.Map[Int, Int]()\n REP_r(N) { i =>\n if (!R.contains(A(i))) R(A(i)) = i\n }\n\n case class Ans(l: Int, r: Int, v: Long)\n var ans: Ans = null\n REP(N) { l =>\n val r = R(A(l))\n if (r > l) {\n val v = posCum(r) - posCum(l + 1) + A(l) * 2\n if (ans == null || v > ans.v) {\n ans = Ans(l, r, v)\n }\n }\n }\n\n var total = 0L\n var cnt = 0\n val cut = Array.ofDim[Boolean](N)\n REP(N) { i =>\n if (i < ans.l || i > ans.r || A(i) < 0) {\n cut(i) = true\n cnt += 1\n } else {\n total += A(i)\n }\n }\n\n out.println(s\"$total $cnt\")\n out.println(cut.zipWithIndex.filter(_._1).map(_._2 + 1).mkString(\" \"))\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import collection.mutable.HashMap\nimport java.util._\nimport java.util\n\n/**\n * @author kperikov\n */\nobject A_331 {\n\n def readString = Console.readLine\n\n def readInts = readString.split(\" \").map(_.toInt)\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val beauty = readInts\n val map = new HashMap[Int, ArrayList[Integer]]\n for (i <- 0 to n - 1) {\n val some = map.get(beauty(i))\n some match {\n case Some(x) => {\n x add i\n map put(beauty(i), x)\n }\n case None => {\n val x = new ArrayList[Integer]()\n x add i\n map put(beauty(i), x)\n }\n }\n }\n //println(map.toString)\n val partialSums = new Array[Int](n + 1)\n val partialAllSums = new Array[Int](n + 1)\n partialSums(0) = 0\n partialSums(n) = 0\n partialAllSums(0) = 0\n partialAllSums(n) = 0\n for (i <- 1 to n) {\n if (beauty(i - 1) > 0) {\n partialSums(i) = partialSums(i - 1) + beauty(i - 1)\n } else {\n partialSums(i) = partialSums(i - 1)\n }\n partialAllSums(i) = partialAllSums(i - 1) + beauty(i - 1)\n //print(partialAllSums(i) + \" \")\n }\n //println\n var maxAns = Int.MinValue\n var begin = -1\n var end = -1\n val it = map.keysIterator\n while (it.hasNext) {\n val key = it.next\n val arr = map.get(key).get\n if (arr.size > 1) {\n Collections.sort(arr)\n val min = arr.get(0)\n val max = arr.get(arr.size - 1) + 1\n val res = partialSums(max - 1) - partialSums(min + 1) + beauty(max - 1) + beauty(min)\n if (res > maxAns) {\n maxAns = res\n begin = min\n end = max - 1\n }\n }\n }\n print(maxAns)\n var countToKill = 0\n val killed = new ArrayList[Int]\n for (i <- 0 until begin) {\n countToKill = countToKill + 1\n killed.add(i + 1)\n }\n for (i <- begin + 1 until end) {\n if (beauty(i) < 0) {\n countToKill = countToKill + 1\n killed.add(i + 1)\n }\n }\n\n\n for (i <- end + 1 until n) {\n countToKill = countToKill + 1\n killed.add(i + 1)\n }\n println(\" \" + countToKill)\n for (i <- 0 to killed.size - 1) {\n print(killed.get(i) + \" \")\n }\n\n }\n\n}\n"}, {"source_code": "import collection.mutable.HashMap\nimport java.util._\nimport java.util\n\n/**\n * @author kperikov\n */\nobject A_331 {\n\n def readString = Console.readLine\n\n def readInts = readString.split(\" \").map(_.toInt)\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val beauty = readInts\n val map = new HashMap[Int, ArrayList[Integer]]\n for (i <- 0 to n - 1) {\n val some = map.get(beauty(i))\n some match {\n case Some(x) => {\n x add i\n map put(beauty(i), x)\n }\n case None => {\n val x = new ArrayList[Integer]()\n x add i\n map put(beauty(i), x)\n }\n }\n }\n //println(map.toString)\n val partialSums = new Array[Int](n + 1)\n val partialAllSums = new Array[Int](n + 1)\n partialSums(0) = 0\n partialSums(n) = 0\n partialAllSums(0) = 0\n partialAllSums(n) = 0\n for (i <- 1 to n) {\n if (beauty(i - 1) > 0) {\n partialSums(i) = partialSums(i - 1) + beauty(i - 1)\n } else {\n partialSums(i) = partialSums(i - 1)\n }\n partialAllSums(i) = partialAllSums(i - 1) + beauty(i - 1)\n //print(partialAllSums(i) + \" \")\n }\n //println\n var maxAns = Int.MinValue\n var begin = -1\n var end = -1\n val it = map.keysIterator\n while (it.hasNext) {\n val key = it.next\n val arr = map.get(key).get\n if (arr.size > 1) {\n Collections.sort(arr)\n val min = arr.get(0)\n val max = arr.get(arr.size - 1) + 1\n val res = partialAllSums(max) - partialAllSums(min)\n val res1 = partialSums(max) - partialSums(min)\n\n // println(res)\n if (res > maxAns) {\n maxAns = res\n begin = min\n end = max\n }\n if (res > 0) {\n if (res1 > maxAns) {\n maxAns = res1\n begin = min\n end = max\n }\n }\n }\n }\n print(maxAns)\n var countToKill = 0\n val killed = new ArrayList[Int]\n for (i <- 0 until begin) {\n countToKill = countToKill + 1\n killed.add(i + 1)\n }\n if (end - begin > 2) {\n for (i <- begin + 1 until end) {\n if (beauty(i) < 0) {\n countToKill = countToKill + 1\n killed.add(i + 1)\n }\n }\n }\n\n for (i <- end until n) {\n countToKill = countToKill + 1\n killed.add(i + 1)\n }\n println(\" \" + countToKill)\n for (i <- 0 to killed.size - 1) {\n print(killed.get(i) + \" \")\n }\n\n }\n\n}\n"}, {"source_code": "import collection.mutable.HashMap\nimport java.util._\nimport java.util\n\n/**\n * @author kperikov\n */\nobject A_331 {\n\n def readString = Console.readLine\n\n def readInts = readString.split(\" \").map(_.toInt)\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val beauty = readInts\n val map = new HashMap[Int, ArrayList[Integer]]\n for (i <- 0 to n - 1) {\n val some = map.get(beauty(i))\n some match {\n case Some(x) => {\n x add i\n map put(beauty(i), x)\n }\n case None => {\n val x = new ArrayList[Integer]()\n x add i\n map put(beauty(i), x)\n }\n }\n }\n val partialSums = new Array[Int](n + 1)\n partialSums(0) = 0\n partialSums(n) = 0\n for (i <- 1 to n) {\n if (beauty(i - 1) > 0) {\n partialSums(i) = partialSums(i - 1) + beauty(i - 1)\n } else {\n partialSums(i) = partialSums(i - 1)\n }\n //print(partialSums(i) + \" \")\n }\n //println\n var maxAns = -1\n var begin = -1\n var end = -1\n val it = map.keysIterator\n while (it.hasNext) {\n val key = it.next\n val arr = map.get(key).get\n if (arr.size > 1) {\n Collections.sort(arr)\n val min = arr.get(0)\n val max = arr.get(arr.size - 1) + 1\n val res = partialSums(max) - partialSums(min)\n// println(res)\n if (res > maxAns) {\n maxAns = res\n begin = min\n end = max\n }\n }\n }\n print(maxAns)\n var countToKill = 0\n val killed = new ArrayList[Int]\n for (i <- 0 to begin - 1) {\n countToKill = countToKill + 1\n killed.add(i + 1)\n }\n for (i <- begin + 1 to end - 1) {\n if (beauty(i) < 0) {\n countToKill = countToKill + 1\n killed.add(i + 1)\n }\n }\n\n for (i <- end + 1 to n) {\n countToKill = countToKill + 1\n killed.add(i)\n }\n println(\" \" + countToKill)\n for (i <- 0 to killed.size - 1) {\n print(killed.get(i) + \" \")\n }\n\n }\n\n}\n"}], "src_uid": "b3418f53720fb9eb990d6e99b07fd61b"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n import java.util.Arrays\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val C = na(N, -1)\n\n val P = Array.fill[Int](N, 2)(-1)\n REP(N) { i =>\n val c = C(i)\n if (P(c)(0) == -1) P(c)(0) = i\n else P(c)(0) = min(P(c)(0), i)\n\n if (P(c)(1) == -1) P(c)(1) = i\n else P(c)(1) = max(P(c)(1), i)\n }\n\n DEBUG {\n debug(P.map(_(0)))\n debug(P.map(_(1)))\n }\n\n var l1, l2: Int = 1e9.toInt\n var r1, r2: Int = -1\n REP(N) { i =>\n val l = P(i)(0)\n if (l != -1 && l < l2) {\n l2 = l\n if (l2 < l1) {\n val t = l1\n l1 = l2\n l2 = t\n }\n }\n\n val r = P(i)(1)\n if (r != -1 && r > r2) {\n r2 = r\n if (r2 > r1) {\n val t = r1\n r1 = r2\n r2 = t\n }\n }\n }\n\n\n debug(s\"l1:$l1 l2:$l2 r1:$r1 r2$r2\")\n\n val ans = if (C(l1) == C(r1)) {\n max(r1 - l2, r2 - l1)\n } else {\n r1 - l1\n }\n\n out.println(ans)\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\nobject Test extends App {\n val n = StdIn.readInt()\n val arr = StdIn.readLine.split(' ')\n val left = for (i <- 1 to n if arr(0) != arr(i-1)) yield i\n val right = for (i <- 1 to n if arr(n-1) != arr(i-1)) yield i\n println(scala.math.max(left(left.length-1)-1, n-right(0)))\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.math.max\n\nobject A1119 {\n def main(args: Array[String]): Unit = {\n readLine()\n val z = readLine().split(\" \")\n println(max(z.lastIndexWhere(_ != z.head), z.length - 1 - z.indexWhere(_ != z.last)))\n }\n}\n"}, {"source_code": "import java.io.FileInputStream\n\nobject Main {\n import scala.io.StdIn.{readInt, readLine}\n \n def main(args: Array[String]): Unit = {\n// System.setIn(new FileInputStream(\"in.txt\"))\n val n = readInt()\n val lst = readLine.split(\" \").map(s => s.toInt)\n var answer = 0;\n for (i <- lst.indices) {\n if (lst(0) != lst(i)) {\n answer = Math.max(answer, i-0)\n }\n if (lst(n-1) != lst(i)) {\n answer = Math.max(answer, n-1-i)\n }\n }\n\n println(answer)\n }\n}\n"}], "negative_code": [], "src_uid": "101fec8d8e169f941e71281048468121"} {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _670C extends CodeForcesApp {\n override def apply(io: IO) = {\n val n = io[Int]\n val counter = map[Int] to 0\n repeat(n) {\n val i = io[Int]\n counter(i) += 1\n }\n val m = io[Int]\n val audio, video = io[Vector, Int](m)\n //debug(counter, audio, video)\n val ans = audio.indices maxBy {i => counter(audio(i)) -> counter(video(i))}\n io += (ans + 1)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}\n def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val scientists = in.next().split(' ').map(_.toInt)\n val movies = in.next().toInt\n val languages = in.next().split(' ').map(_.toInt)\n val langSet = languages.toSet\n val subtitles = in.next().split(' ').map(_.toInt)\n val scientistsLanguages = scientists.groupBy(i => i).map(i => (i._1, i._2.length))\n val zipped = languages\n .zip(subtitles)\n .map{ case(l, s) => (scientistsLanguages.getOrElse(l, 0), scientistsLanguages.getOrElse(s, 0)) }\n .zipWithIndex\n .maxBy(_._1)._2\n println(zipped + 1)\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _670C extends CodeForcesApp {\n override def apply(io: IO) = {\n val prefs = io[Vector[Int]].toMultiSet withDefaultValue 0\n val m = io[Int]\n val audio, video = io[Vector, Int](m)\n val ans = audio.indices maxBy {i => prefs(audio(i)) -> prefs(video(i))}\n io += (ans + 1)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}\n def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val scientists = in.next().split(' ').map(_.toInt)\n val movies = in.next().toInt\n val languages = in.next().split(' ').map(_.toInt)\n val langSet = languages.toSet\n val subtitles = in.next().split(' ').map(_.toInt)\n val scientistsLanguages = scientists.groupBy(i => i).map(i => (i._1, i._2.length))\n val zipped = languages\n .zip(subtitles)\n .map{ case(l, s) => (scientistsLanguages.getOrElse(l, 0), scientistsLanguages.getOrElse(l, 0)) }\n .zipWithIndex\n .sortBy(_._1).last._2\n println(zipped + 1)\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val scientists = in.next().split(' ').map(_.toInt)\n val movies = in.next().toInt\n val languages = in.next().split(' ').map(_.toInt)\n val langSet = languages.toSet\n val subtitles = in.next().split(' ').map(_.toInt)\n val scientistsLanguages = scientists.groupBy(i => i).map(i => (i._1, i._2.length))\n val zipped = languages\n .zip(subtitles)\n .map{ case(l, s) => (scientistsLanguages.getOrElse(l, 0), scientistsLanguages.getOrElse(l, 0)) }\n .zipWithIndex\n .maxBy(_._1)._2\n println(zipped + 1)\n}\n"}], "src_uid": "74ddbcf74988940265985ec8c36bb299"} {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P425B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N, M, K = sc.nextInt\n val A: Array[Array[Int]] = Array.fill(N, M)(sc.nextInt)\n\n def a2l(a: Array[Int]): Long = a.foldLeft(0L) { (r, i) => (r << 1) + i }\n\n def solveSmall(): Int = {\n val cols = A.transpose.map(a2l)\n val patterns = List.range(0, 1 << N)\n val mask = (1 << N) - 1\n patterns.map { pat =>\n val shadow = pat ^ mask\n cols.map { x => bitCount(x ^ pat) min bitCount(x ^ shadow) }.sum\n }.min\n }\n\n def solveLarge(): Int = {\n val a2ll: Array[Int] => List[Long] = { a =>\n val (a0, a1) = a.splitAt(50)\n List(a0, a1).map(a2l)\n }\n val b = A.map(a2ll)\n val List(mask0, mask1) = a2ll(Array.fill(M)(1))\n val patterns = b.take(K + 1)\n patterns.map { pat =>\n val List(pat0, pat1) = pat\n val List(shadow0, shadow1) = List(pat0 ^ mask0, pat1 ^ mask1)\n b.map { row =>\n val List(x0, x1) = row\n val res0 = bitCount(x0 ^ pat0) + bitCount(x1 ^ pat1)\n val res1 = bitCount(x0 ^ shadow0) + bitCount(x1 ^ shadow1)\n res0 min res1\n }.sum\n }.min\n\n }\n\n val res = if (N <= K) solveSmall\n else solveLarge\n if (res <= K) res\n else -1\n }\n\n out.println(solve)\n out.close\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P425B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N, M, K = sc.nextInt\n val A: Array[Array[Int]] = Array.fill(N, M)(sc.nextInt)\n\n def solveSmall(): Int = {\n val a2i: Array[Int] => Int = a => a.foldLeft(0) { (r, x) => (r << 1) + x }\n val cols = A.transpose.map(a2i)\n val patterns = List.range(0, 1 << N)\n val mask = (1 << N) - 1\n patterns.map { pat =>\n val shadow = pat ^ mask\n cols.map { x => bitCount(x ^ pat) min bitCount(x ^ shadow) }.sum\n }.min\n }\n\n def solveLarge(): Int = {\n val a2ll: Array[Int] => List[Long] = { a =>\n val (a0, a1) = a.splitAt(50)\n List(a0, a1).map { x => x.foldLeft(0L) { (r, i) => (r << 1) + i } }\n }\n val B = A.map(a2ll)\n val List(mask0, mask1) = a2ll(Array.fill(M)(1))\n val patterns = B.take(K + 1)\n patterns.map { pat =>\n val List(pat0, pat1) = pat\n val List(shadow0, shadow1) = List(pat0 ^ mask0, pat1 ^ mask1)\n B.map { row =>\n val List(x0, x1) = row\n val res0 = bitCount(x0 ^ pat0) + bitCount(x1 ^ pat1)\n val res1 = bitCount(x0 ^ shadow0) + bitCount(x1 ^ shadow1)\n res0 min res1\n }.sum\n }.min\n\n }\n\n val res = if (N <= K) solveSmall\n else solveLarge\n if (res <= K) res\n else -1\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P425B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N, M, K = sc.nextInt\n val A: Array[Array[Int]] = Array.fill(N, M)(sc.nextInt)\n\n @inline\n def a2l(a: Array[Int]): Long = a.foldLeft(0L) { (r, i) => (r << 1) + i }\n\n def solveSmall(): Int = {\n val cols = A.transpose.map(a2l)\n val patterns = List.range(0, 1 << N)\n val mask = (1 << N) - 1\n patterns.map { pat =>\n val shadow = pat ^ mask\n cols.map { x => bitCount(x ^ pat) min bitCount(x ^ shadow) }.sum\n }.min\n }\n\n def solveLarge(): Int = {\n\n @inline\n def a2ll(a: Array[Int]): List[Long] = {\n val (a0, a1) = a.splitAt(50)\n List(a0, a1).map(a2l)\n }\n\n val List(mask0, mask1) = a2ll(Array.fill(M)(1))\n val b = A.map(a2ll)\n val patterns = b.take(K + 1)\n patterns.map { pat =>\n val List(pat0, pat1) = pat\n val List(shadow0, shadow1) = List(pat0 ^ mask0, pat1 ^ mask1)\n b.map { row =>\n val List(x0, x1) = row\n val res0 = bitCount(x0 ^ pat0) + bitCount(x1 ^ pat1)\n val res1 = bitCount(x0 ^ shadow0) + bitCount(x1 ^ shadow1)\n res0 min res1\n }.sum\n }.min\n\n }\n\n val res = if (N <= K) solveSmall\n else solveLarge\n if (res <= K) res\n else -1\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P425B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N, M, K = sc.nextInt\n val A: Array[Array[Int]] = Array.fill(N, M)(sc.nextInt)\n\n def a2l(a: Array[Int]): Long = a.foldLeft(0L) { (r, i) => (r << 1) + i }\n\n def solveSmall(): Int = {\n val cols = A.transpose.map(a2l)\n val patterns = List.range(0, 1 << N)\n val mask = (1 << N) - 1\n patterns.map { pat =>\n val shadow = pat ^ mask\n cols.map { x => bitCount(x ^ pat) min bitCount(x ^ shadow) }.sum\n }.min\n }\n\n def solveLarge(): Int = {\n \n def a2ll(a: Array[Int]): List[Long] = {\n val (a0, a1) = a.splitAt(50)\n List(a0, a1).map(a2l)\n }\n\n val List(mask0, mask1) = a2ll(Array.fill(M)(1))\n val b = A.map(a2ll)\n val patterns = b.take(K + 1)\n patterns.map { pat =>\n val List(pat0, pat1) = pat\n val List(shadow0, shadow1) = List(pat0 ^ mask0, pat1 ^ mask1)\n b.map { row =>\n val List(x0, x1) = row\n val res0 = bitCount(x0 ^ pat0) + bitCount(x1 ^ pat1)\n val res1 = bitCount(x0 ^ shadow0) + bitCount(x1 ^ shadow1)\n res0 min res1\n }.sum\n }.min\n\n }\n\n val res = if (N <= K) solveSmall\n else solveLarge\n if (res <= K) res\n else -1\n }\n\n out.println(solve)\n out.close\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P425B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def countDiff(x: Array[Int], y: Array[Int]): Int = {\n val z = x.map(_ ^ 1)\n List(x, z).map { w =>\n (w, y).zipped.map(_ ^ _).sum\n }.min\n }\n\n def solveSmall(n: Int, m: Int, k: Int, a: Array[Array[Int]]): Int = {\n val colPatterns: List[Array[Int]] = {\n List.range(0, 1 << n).map { i =>\n Array.tabulate(n) { i : Int => (i >> n) & 1 }\n }\n }\n val b = a.transpose\n colPatterns.map { p =>\n b.map(countDiff(p, _)).sum\n }.min\n }\n\n def solveLarge(n: Int, m: Int, k: Int, a: Array[Array[Int]]): Int = {\n val colPatterns = a.take(k + 1)\n colPatterns.map { p =>\n a.map(countDiff(p, _)).sum\n }.min\n }\n\n def solve(): Int = {\n val N, M, K = sc.nextInt\n val A: Array[Array[Int]] = Array.fill(N)(Array.fill(M)(sc.nextInt))\n\n val res = if (N <= K) solveSmall(N, M, K, A)\n else solveLarge(N, M, K, A)\n if (res <= K) res\n else -1\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P425B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N, M, K = sc.nextInt\n\n def line2code(m: Int): Long = {\n\n @tailrec\n def loop(x: Long, i: Int): Long = {\n if (i == m) x\n else loop((x << 1) + sc.nextLong, i + 1)\n }\n\n loop(0L, 0)\n }\n\n val A: List[Long] = List.fill(N)(line2code(M))\n val patterns: List[Long] = if (N <= K) List.range[Long](0L, (1L << M))\n else A.take(K + 1)\n\n @inline\n def countChange(x: Long): Int = A.map { y: Long =>\n val mask: Long = (1L << M) - 1\n val a = x ^ y\n val b = x ^ mask ^ y\n bitCount(a) min bitCount(b)\n }.sum\n\n val res: Int = patterns.map(countChange).min\n if (res <= K) res\n else -1\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P425B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N, M, K = sc.nextInt\n val A: Array[Array[Int]] = Array.fill(N, M)(sc.nextInt)\n\n def solveSmall(): Int = {\n val a2i: Array[Int] => Int = a => a.foldLeft(0) { (r, x) => (r << 1) + x }\n val cols = A.transpose.map(a2i)\n val patterns = List.range(0, 1 << N)\n val mask = (1 << N) - 1\n patterns.map { pat =>\n val shadow = pat ^ mask\n cols.map { x => bitCount(x ^ pat) min bitCount(x ^ shadow) }.sum\n }.min\n }\n\n def solveLarge(): Int = {\n val a2ll: Array[Int] => List[Long] = { a =>\n val (a0, a1) = a.splitAt(50)\n List(a0, a1).map { x => x.foldLeft(0L) { (r, i) => (r << 1) + i } }\n }\n val B = A.map(a2ll)\n val List(mask0, mask1) = a2ll(Array.fill(M)(1))\n val patterns = B.take(K + 1)\n patterns.map { pat =>\n val List(pat0, pat1) = pat\n val List(shadow0, shadow1) = List(pat0 ^ mask0, pat1 ^ mask1)\n B.map { row =>\n val List(x0, x1) = row\n val res0 = bitCount(x0 ^ pat0) + bitCount(x1 ^ pat1)\n val res1 = bitCount(x0 ^ shadow0) + bitCount(x1 ^ shadow1)\n res0 min res1\n }.sum\n }.min\n\n }\n\n val res = if (N <= K) solveSmall\n else solveLarge\n res\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P425B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def countDiff(x: Array[Int], y: Array[Int]): Int = {\n val z = x.map(_ ^ 1)\n List(x, z).map { w =>\n (w, y).zipped.map(_ ^ _).sum\n }.min\n }\n\n def solveSmall(n: Int, m: Int, k: Int, a: Array[Array[Int]]): Int = {\n val colPatterns: List[Array[Int]] = {\n List.range(0, 1 << n).map { i =>\n Array.tabulate(n) { i : Int => (i >> n) & 1 }\n }\n }\n val b = a.transpose\n colPatterns.map { p =>\n b.map(countDiff(p, _)).sum\n }.min\n }\n\n def solveLarge(n: Int, m: Int, k: Int, a: Array[Array[Int]]): Int = {\n val colPatterns = a.take(k + 1)\n colPatterns.map { p =>\n a.map(countDiff(p, _)).sum\n }.min\n }\n\n def solve(): Int = {\n val N, M, K = sc.nextInt\n val A: Array[Array[Int]] = Array.fill(N)(Array.fill(M)(sc.nextInt))\n\n if (N <= K) solveSmall(N, M, K, A)\n else solveLarge(N, M, K, A)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P425B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N, M, K = sc.nextInt\n\n def line2code(m: Int): Long = {\n\n @tailrec\n def loop(x: Long, i: Int): Long = {\n if (i == m) x\n else loop((x << 1) + sc.nextLong, i + 1)\n }\n\n loop(0L, 0)\n }\n\n val A: List[Long] = List.fill(N)(line2code(M))\n val patterns: List[Long] = if (M <= K) List.range[Long](0L, (1L << M))\n else A.take(K + 1)\n\n @inline\n def countChange(x: Long): Int = A.map { y: Long =>\n val mask: Long = (1L << M) - 1\n val a = x ^ y\n val b = x ^ (y ^ mask)\n bitCount(a) min bitCount(b)\n }.min\n\n val res: Int = patterns.map(countChange).min\n if (res <= K) res\n else -1\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P425B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N, M, K = sc.nextInt\n\n def line2code(m: Int): Long = {\n\n @tailrec\n def loop(x: Long, i: Int): Long = {\n if (i == m) x\n else loop((x << 1) + sc.nextLong, i + 1)\n }\n\n loop(0L, 0)\n }\n\n val A: List[Long] = List.fill(N)(line2code(M))\n val patterns: List[Long] = if (M <= K) List.range[Long](0L, (1L << M))\n else A.take(K + 1)\n\n @inline\n def countChange(x: Long): Int = A.map { y: Long =>\n val mask: Long = (1L << M) - 1\n val a = x ^ y\n val b = x ^ mask ^ y\n bitCount(a) min bitCount(b)\n }.sum\n\n val res: Int = patterns.map(countChange).min\n if (res <= K) res\n else -1\n }\n\n out.println(solve)\n out.close\n}\n"}], "src_uid": "bc937cacda9ebff9ec0b7f00f0f97508"} {"source_code": "object _1234B1 extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val n, k = io.read[Int]\n val msgs = io.read[Seq, Int](n)\n\n val ans = boundedSet[Int](k)\n for {\n msg <- msgs if !ans.contains(msg)\n } ans.add(msg)\n\n io.writeLine(ans.size()).writeAll(ans.toArray.reverse)\n }\n\n def boundedSet[E](limit: Int) = {\n import java.{util => ju}\n ju.Collections.newSetFromMap[E](new ju.LinkedHashMap[E, java.lang.Boolean]() {\n override def removeEldestEntry(eldest: ju.Map.Entry[E, java.lang.Boolean]) = size() > limit\n })\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject taskA {\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val arr :Array[Int] = readLine().split(\" \").map(_.toInt)\n val map = scala.collection.mutable.Map[Int, Int]()\n val queue = mutable.Queue[Int]()\n\n for(i <- 0 to n - 1) {\n val current_id = arr(i)\n if(!map.contains(current_id) || map(current_id) == 0) {\n if(map.contains(current_id)) map(current_id) += 1\n else map(current_id) = 1\n queue.enqueue(current_id)\n if(queue.size == k + 1) {\n map(queue.dequeue()) -= 1\n }\n }\n }\n println(queue.length)\n queue.reverse.foreach(id => print(id + \" \"))\n }\n}"}, {"source_code": "object _1234B1 extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val n, k = io.read[Int]\n val msgs = io.read[Seq, Int](n)\n val ans = mutable.ArrayBuffer.empty[Int]\n val currentlyTalking = mutable.Set.empty[Int]\n for {\n msg <- msgs\n if currentlyTalking.add(msg)\n } {\n ans.prepend(msg)\n if (ans.length > k) currentlyTalking -= ans.remove(k)\n }\n\n io.writeLine(ans.length).writeAll(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject taskA {\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val arr :Array[Int] = readLine().split(\" \").map(_.toInt)\n val map = scala.collection.mutable.Map[Int, Int]()\n val queue = mutable.Queue[Int]()\n\n for(i <- 0 to n - 1) {\n val current_id = arr(i)\n if(!map.contains(current_id) || map(current_id) == 0) {\n if(map.contains(current_id)) map(current_id) += 1\n else map(current_id) = 1\n queue.enqueue(current_id)\n if(queue.size == k + 1) {\n map(queue.dequeue()) -= 1\n }\n }\n }\n println(queue.length)\n queue.reverse.foreach(id => print(id + \" \"))\n }\n}"}, {"source_code": "object B1 extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n\n import scala.annotation.tailrec\n import scala.io.Codec\n\n /**\n * Faster Scanner in Scala by wrick\n * https://codeforces.com/blog/entry/21074\n *\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n }\n\n def read2(): (Int, Seq[Int]) = {\n val in = new Scanner(System.in)\n val n = in.nextInt()\n val k = in.nextInt()\n val letters = (0 until n).map(_ => in.nextInt())\n (k, letters)\n }\n\n @tailrec\n def res(seq: Vector[Int])(acc: Vector[Int], k: Int): Vector[Int] = seq match {\n case Vector() => acc.reverse\n case x +: xs if acc.contains(x) => res(xs)(acc, k)\n case x +: xs if acc.length < k => res(xs)(acc :+ x, k)\n case x +: xs => res(xs)(acc.drop(1) :+ x, k)\n }\n\n val (k, letters) = read2()\n val r = res(letters.toVector)(Vector(), k)\n println(r.length)\n println(r mkString \" \")\n}"}], "negative_code": [{"source_code": "object Ex2 extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n\n import scala.io.Codec\n import scala.annotation.tailrec\n\n /**\n * Faster Scanner in Scala by wrick\n * https://codeforces.com/blog/entry/21074\n *\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n }\n\n def read2(): (Int, Seq[Int]) = {\n val in = new Scanner(System.in)\n val n = in.nextInt()\n val k = in.nextInt()\n val letters = (0 until n).map(_ => in.nextInt())\n (k, letters)\n }\n\n @tailrec\n def res(seq: List[Int], k: Int)(acc: List[Int]): List[Int] = {\n if (acc.length == k) acc\n else seq match {\n case Nil => acc\n case x :: xs if !acc.contains(x) => res(xs, k)(x :: acc)\n case _ :: xs => res(xs, k)(acc)\n }\n }\n\n val (k, letters) = read2()\n val r = res(letters.toList, k)(Nil)\n println(r mkString \" \")\n}"}, {"source_code": "object Ex2 extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n\n import scala.io.Codec\n import scala.annotation.tailrec\n\n /**\n * Faster Scanner in Scala by wrick\n * https://codeforces.com/blog/entry/21074\n *\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n }\n\n def read2(): (Int, Seq[Int]) = {\n val in = new Scanner(System.in)\n val n = in.nextInt()\n val k = in.nextInt()\n val letters = (0 until n).map(_ => in.nextInt())\n (k, letters)\n }\n\n @tailrec\n def res(seq: List[Int], k: Int)(acc: List[Int]): List[Int] = {\n if (acc.length == k) acc\n else seq match {\n case Nil => acc\n case x :: xs if !acc.contains(x) => res(xs, k)(x :: acc)\n case _ :: xs => res(xs, k)(acc)\n }\n }\n\n val (k, letters) = read2()\n val r = res(letters.toList, k)(Nil)\n println(r.length)\n println(r mkString \" \")\n}"}], "src_uid": "485a1ecf8f569b85327b99382bda9466"} {"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val q = in.nextInt()\n val c = Array.fill(200001)(0)\n val t = Array.fill(200001)(0)\n (1 to q).foreach{ _ =>\n val n = in.nextInt()\n (0 until n).foreach(i => {\n t(i) = in.nextInt()\n\n })\n c(0) = 0\n var ans = 1\n var moreThan1 = false\n var indexToChange = 0\n (1 until n).foreach(i => {\n\n if(t(i-1) == t(i)){\n c(i) = c(i-1)\n moreThan1 = true\n indexToChange = i\n }else{\n c(i) = 1-c(i-1)\n ans=2\n }\n\n\n })\n\n val numColors = if(t(0) == t(n-1)){\n ans\n }else{\n if(c(0) == c(n-1)){\n if(moreThan1){\n (indexToChange until n).foreach{ i =>\n c(i) = 1 - c(i)\n }\n ans\n }else{\n c(0) = 2\n 3\n }\n\n }else{\n ans\n }\n }\n\n //println(numColors)\n //println(c.slice(0,n).map(_ + 1).mkString(\" \"))\n out.println(numColors)\n out.println(c.slice(0,n).map(_ + 1).mkString(\" \"))\n\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}", "positive_code": [{"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n for (_ <- 1 to nextInt) {\n val n = nextInt\n val ts = nextInts(n)\n\n val res = Array.ofDim[Int](n)\n var prev = ts(0)\n var prevC = 1\n var lastSpan = -1\n for (i <- 1 until n) {\n if (ts(i) == prev) {\n lastSpan = i\n res(i) = prevC\n } else {\n prevC = 3 - prevC\n res(i) = prevC\n }\n prev = ts(i)\n }\n\n if (lastSpan == -1 && ts(0) != prev && n % 2 == 1) {\n res(0) = 3\n } else {\n if (ts(0) == prev) {\n res(0) = if (ts(0) == ts(1)) res(1) else 3 - res(1)\n } else {\n val for0 = 3 - prevC\n if (ts(0) == ts(1) || res(1) != for0) {\n res(0) = for0\n } else {\n for (i <- 1 until lastSpan) {\n res(i) = 3 - res(i)\n }\n res(0) = for0\n }\n }\n }\n\n out.println(res.max)\n out.println(res.mkString(\" \"))\n }\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n for (_ <- 1 to nextInt) {\n val n = nextInt\n val ts = nextInts(n)\n\n val res = Array.ofDim[Int](n)\n var prev = ts(0)\n var prevC = 1\n var lastSpan = -1\n for (i <- 1 until n) {\n if (ts(i) == prev) {\n lastSpan = i\n res(i) = prevC\n } else {\n prevC = 3 - prevC\n res(i) = prevC\n }\n prev = ts(i)\n }\n\n if (lastSpan == -1 && ts(0) != prev && n % 2 == 1) {\n res(0) = 3\n } else {\n val for0 = if (ts(0) == prev) prevC else 3 - prevC\n if (ts(0) == ts(1) || res(1) != for0) {\n res(0) = for0\n } else {\n for (i <- 1 until lastSpan) {\n res(i) = 3 - res(i)\n }\n res(0) = for0\n }\n }\n\n out.println(res.max)\n out.println(res.mkString(\" \"))\n }\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val q = in.nextInt()\n val c = Array.fill(200001)(0)\n val t = Array.fill(200001)(0)\n (1 to q).foreach{ _ =>\n val n = in.nextInt()\n (0 until n).foreach(i => {\n t(i) = in.nextInt()\n\n })\n c(0) = 0\n var ans = 1\n (1 until n).foreach(i => {\n\n if(t(i-1) == t(i)){\n c(i) = c(i-1)\n }else{\n c(i) = 1-c(i-1)\n ans=2\n }\n\n\n })\n\n val numColors = if(t(0) == t(n-1)){\n ans\n }else{\n if(c(0) == c(n-1)){\n if((t(1) == t(0) && t(2) == t(1)) || (t(n-1) == t(n-2) && t(n-2) == t(n-3))){\n ans\n }else{\n c(0) = 2\n 3\n }\n\n }else{\n ans\n }\n }\n\n out.println(numColors)\n out.println(c.slice(0,n).map(_ + 1).mkString(\" \"))\n\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}, {"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val q = in.nextInt()\n val c = Array.fill(200001)(0)\n val t = Array.fill(200001)(0)\n (1 to q).foreach{ _ =>\n val n = in.nextInt()\n (0 until n).foreach(i => {\n t(i) = in.nextInt()\n\n })\n c(0) = 0\n var ans = 1\n (1 until n).foreach(i => {\n\n if(t(i-1) == t(i)){\n c(i) = c(i-1)\n }else{\n c(i) = 1-c(i-1)\n ans=2\n }\n\n\n })\n\n val numColors = if(t(0) == t(n-1)){\n ans\n }else{\n if(c(0) == c(n-1)){\n\n c(0) = 2\n 3\n }else{\n ans\n }\n }\n \n out.println(numColors)\n out.println(c.slice(0,n).map(_ + 1).mkString(\" \"))\n\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "src_uid": "1f4c3f5e7205fe556b50320cecf66c89"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt\n val a = readLine().split(\" \").map(_.toInt)\n var cur = 0\n var res = scala.collection.mutable.ListBuffer[Int]()\n var negs = 0\n for(i <- 0 until a.size) {\n if (a(i) < 0 && negs == 2) {\n res += cur\n cur = 1\n negs = 1\n } else if (a(i) < 0) {\n negs += 1 \n cur += 1\n } else {\n cur += 1\n }\n }\n if (cur != 0) res += cur\n println(res.size)\n println(res.mkString(\" \"))\n }\n}", "positive_code": [{"source_code": "import java.util.Scanner\nimport scala.collection.mutable._\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n\n val ans = solve((0 until n).map(_ => sc.nextInt()).toList)\n\n println(ans.size)\n println(ans.reverse.mkString(\" \"))\n\n def solve(a: List[Int], loss: Int = 0, cur: Int = 0, result: List[Int] = Nil): List[Int] = {\n a match {\n case Nil => cur :: result\n case x :: t =>\n if (x >= 0) solve(t, loss, cur + 1, result)\n else if (loss == 2) solve(t, 1, 1, cur :: result)\n else solve(t, loss + 1, cur + 1, result)\n }\n }\n}\n"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\nimport collection.mutable.ArrayBuffer\n\nobject test2 extends App {\n val n=readLine.toInt\n val a=readLine.split(\" \").map(_.toInt)\n\n var start=0\n val folders=(for(i<-0 until n if a(i)<0 && a.slice(start,i+1).count(_<0)==3) yield\n {\n \tval ret=i-start\n \tstart=i\n \tret\n }):+(n-start)\n \n println(folders.size)\n println(folders.mkString(\" \"))\n}\n\n"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\nimport collection.mutable.ArrayBuffer\n\nobject test2 extends App {\n val n=readLine.toInt\n val a=readLine.split(\" \").map(_.toInt)\n\n var start=0\n val ab=new ArrayBuffer[Int]()\n var count=0\n for(i<-0 until n)\n {\n \tif(a(i)<0)\n \t{\n \t\tif(count==2)\n \t\t{\n \t\t\tab+=i-start\n \t\t\tstart=i\n \t\t\tcount=1\n \t\t}\n \t\telse\n \t\t{\n \t\t\tcount+=1\n \t\t}\n \t}\n }\n \n ab+=n-start\n \n println(ab.size)\n println(ab.mkString(\" \"))\n}\n\n"}], "negative_code": [], "src_uid": "3f320920a023c3bc10ba1525e8c89044"} {"source_code": "object Minority extends App {\r\n def minorityCount(s: String): Int = {\r\n val length = s.length\r\n val count0 = s.count(_ == '0')\r\n if (count0 == length - count0) count0 - 1\r\n else count0 min (length - count0)\r\n }\r\n\r\n val lines = io.Source.stdin.getLines\r\n val t = lines.next.toInt\r\n (1 to t).foreach(_ => println(minorityCount(lines.next)))\r\n}", "positive_code": [{"source_code": "import scala.io.StdIn.readInt\r\nimport scala.io.StdIn.readLine\r\n\r\nobject cf1633b {\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt()\r\n while(t > 0) {\r\n t -= 1\r\n var s = readLine()\r\n var ans = Math.max(calculate(s), Math.max(calculate(s.substring(1)), calculate((s.substring(0, s.length() - 1)))))\r\n println(ans)\r\n }\r\n }\r\n\r\n def calculate(s: String): Int = {\r\n var ans = 0\r\n if(s.count(_ == '0') != 0 && s.count(_ == '0') !=0) {\r\n if(s.count(_ == '1') != s.count(_ == '0')) {\r\n ans = Math.max(ans, Math.min(s.count(_ == '0'), s.count(_ == '1')))\r\n }\r\n }\r\n return ans\r\n }\r\n}\r\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val string = readLine()\n val zeroCount = string.count(_ == '0')\n val oneCount = string.count(_ == '1')\n val min = Math.min(zeroCount, oneCount)\n val answer = if (min == 0) 0\n else if (zeroCount != oneCount) min else zeroCount - 1\n println(answer)\n }\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readInt\r\nimport scala.io.StdIn.readLine\r\n\r\nobject cf1633b {\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt()\r\n while(t > 0) {\r\n t -= 1\r\n var s = readLine()\r\n var ans = 0\r\n if(s.count(_ == '0') != 0 && s.count(_ == '0') !=0) {\r\n ans = Math.max(ans, s.count(_ == '0'))\r\n ans = Math.max(ans, s.count(_ == '1'))\r\n ans = Math.max(ans, s.substring(1).count(_ == '1'))\r\n ans = Math.max(ans, s.substring(1).count(_ == '0'))\r\n ans = Math.max(ans, s.substring(0, s.length() - 2).count(_ == '1'))\r\n ans = Math.max(ans, s.substring(0, s.length() - 2).count(_ == '0'))\r\n }\r\n println(ans)\r\n }\r\n }\r\n}\r\n"}], "src_uid": "62f5798bdcea237c0df9b4cd288b97de"} {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N, K = sc.nextInt()\n val A = map(N)(_ => sc.nextInt())\n val M = Array.fill[mutable.Map[Int, Int]](11)(mutable.Map() withDefaultValue 0)\n val len = Array.ofDim[Int](N)\n\n val pow = Array.ofDim[Long](11)\n pow(0) = 1\n rep(10) { i => pow(i + 1) = pow(i) * 10 % K}\n\n def digits(x: Int): Int = {\n var d = 0\n var a = x\n while(a > 0) { a /= 10; d += 1}\n d\n }\n\n rep(N) { i =>\n val m = A(i) % K\n val d = digits(A(i))\n len(i) = d\n M(d)(m) = M(d)(m) + 1\n }\n\n var ans = 0L\n rep(N) { i =>\n rep(11) { d =>\n val m = (pow(d) * A(i) % K).toInt\n val r = if (m == 0) 0 else K - m\n ans += M(d)(r)\n if (d == len(i) && r == A(i) % K) ans -= 1\n }\n }\n\n out.println(ans)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject D extends App {\n\n def countLen(x: Long): Int = {\n var l = 0\n var xx = x\n while (xx > 0) {\n xx = xx / 10\n l += 1\n }\n l\n }\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val k = in.nextLong\n val a = Array.fill(n)(in.nextLong)\n val map = scala.collection.mutable.Map[(Long, Int), Int]()\n a.foreach { v =>\n val key = (v % k, countLen(v))\n //println(key)\n map += key -> (map.getOrElse(key, 0) + 1)\n }\n var ans: Long = 0\n for {v <- a\n i <- 1 to 10\n } {\n //println((k - v * math.pow(10, i).toLong % k) % k -> i)\n ans += map.getOrElse((k - (v % k) * (math.pow(10, i) % k).toLong % k) % k -> i\n , 0\n )\n }\n //println(ans)\n a.foreach { v =>\n if (((v % k) + (v % k) * (math.pow(10, countLen(v)) % k)) % k == 0)\n ans -= 1\n }\n println(ans)\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toInt\n }\n\n def nextLong: Long = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}], "negative_code": [{"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N, K = sc.nextInt()\n val A = map(N)(_ => sc.nextInt())\n val M = Array.fill[mutable.Map[Int, Int]](11)(mutable.Map() withDefaultValue 0)\n\n val pow = Array.ofDim[Long](11)\n pow(0) = 1\n rep(10) { i => pow(i + 1) = pow(i) * 10}\n\n def digits(x: Int): Int = x.toString.length\n\n rep(N) { i =>\n rep(11) { j =>\n val m = (pow(j) * A(i) % K).toInt\n M(j)(m) = M(j)(m) + 1\n }\n }\n\n var ans = 0L\n rep(N) { i =>\n val d = digits(A(i))\n val m = (K - A(i) % K) % K\n ans += M(d)(m)\n if (pow(d) * A(i) % K == m) ans -= 1\n }\n\n out.println(ans)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val N, K = sc.nextInt()\n val A = map(N)(_ => sc.nextInt())\n val M = Array.ofDim[Int](11, K)\n\n def digits(x: Int): Int = x.toString.length\n\n rep(N) { i =>\n rep(11) { j =>\n M(j)((A(i).toLong * pow(10, j) % K).toInt) += 1\n }\n }\n\n var ans = 0L\n rep(N) { i =>\n val d = digits(A(i))\n val m = (K - A(i) % K) % K\n ans += M(d)(m)\n if (pow(10, d) * A(i) % K == m) ans -= 1\n }\n\n// case class Seg(l: Int, r: Int) {\n// def length: Int = r - l\n// }\n// val S = map(N) { _ =>\n// val l, r = sc.nextInt()\n// Seg(l, r)\n// }\n//\n// def intersect(s1: Seg, s2: Seg): Seg = {\n// Seg(max(s1.l, s2.l), min(s1.r, s2.r))\n// }\n//\n// def merge(s1: Seg, s2: Seg): Seg = {\n// ???\n// }\n//\n// val ms = S reduce intersect\n// var mx = 0\n// rep(N) { i =>\n// mx = max(mx, merge(S(i), ms).length)\n// }\n\n out.println(ans)\n }\n\n\n def pow(x: Int, n: Int): Int = {\n n match {\n case 0 => 1\n case _ =>\n val r = pow(x * x, n / 2)\n if (n % 2 == 1) r * x else r\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject D extends App {\n\n def countLen(x: Long): Int = {\n var l = 0\n var xx = x\n while (xx > 0) {\n xx = xx / 10\n l += 1\n }\n l\n }\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val k = in.nextLong\n val a = Array.fill(n)(in.nextLong)\n val map = scala.collection.mutable.Map[(Long, Int), Int]()\n a.foreach { v =>\n val key = (v % k, countLen(v))\n //println(key)\n map += key -> (map.getOrElse(key, 0) + 1)\n }\n var ans: Long = 0\n for {v <- a\n i <- 1 to 10\n } {\n //println(map.get((k - v * math.pow(10, i).toLong % k -> i))\n ans += map.getOrElse((k - v * math.pow(10, i).toLong % k) % k -> i, 0)\n }\n //println(ans)\n a.foreach { v =>\n if ((v + v * math.pow(10, countLen(v))) % k == 0)\n ans -= 1\n }\n println(ans)\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toInt\n }\n\n def nextLong: Long = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject D extends App {\n\n def countLen(x: Long): Int = {\n var l = 0\n var xx = x\n while (xx > 0) {\n xx = xx / 10\n l += 1\n }\n l\n }\n\n def solve(in: InputReader): Unit = {\n val n = in.nextInt\n val k = in.nextLong\n val a = Array.fill(n)(in.nextLong)\n val map = scala.collection.mutable.Map[(Long, Int), Int]()\n a.foreach { v =>\n val key = (v % k, countLen(v))\n //println(key)\n map += key -> (map.getOrElse(key, 0) + 1)\n }\n var ans: Long = 0\n for {v <- a\n i <- 1 to 10\n } {\n //println((k - v * math.pow(10, i).toLong % k) % k -> i)\n ans += map.getOrElse((k - (v % k) * math.pow(10, i).toLong % k) % k -> i, 0)\n }\n //println(ans)\n a.foreach { v =>\n if (((v % k) + (v % k) * math.pow(10, countLen(v))) % k == 0)\n ans -= 1\n }\n println(ans)\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def nextDouble: Double = {\n next.toInt\n }\n\n def nextLong: Long = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n\n}"}], "src_uid": "1eb41e764a4248744edce6a9e7e3517a"} {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(h, w) = readLine().split(\" \").map(_.toInt)\r\n\r\n (1 to h).foreach {\r\n case i if i == 1 || i == h => println((1 to w).map(_ % 2).mkString(\"\"))\r\n case i if i > 2 && i < h - 1 => println(s\"${i % 2}${\"0\" * (w - 2)}${i % 2}\")\r\n case _ => println(\"0\" * w)\r\n }\r\n println()\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(h, w) = readLine().split(\" \").map(_.toInt)\r\n\r\n (1 to h).foreach {\r\n case i if i == 1 || i == h =>\r\n val row = (1 to w).map(_ % 2).mkString(\"\")\r\n println(row)\r\n case i if i > 2 && i < h - 1 =>\r\n val row = s\"${i % 2}\" + \"0\" * (w - 2) + s\"${i % 2}\"\r\n println(row)\r\n case _ => println(\"0\" * w)\r\n }\r\n println()\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(h, w) = readLine().split(\" \").map(_.toInt)\r\n\r\n (0 until h).foreach { i =>\r\n val row = (0 until w).map {\r\n case j if i == 0 || i == h - 1 => (j + 1) % 2\r\n case j if (j == 0 || j == w - 1) && i > 1 && i < h - 2 => (i + 1) % 2\r\n case _ => 0\r\n }\r\n println(row.mkString(\"\"))\r\n }\r\n println()\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(h, w) = readLine().split(\" \").map(_.toInt)\r\n\r\n (1 to h).foreach {\r\n case i if i == 1 || i == h =>\r\n val row = (1 to w).map(_ % 2).mkString(\"\")\r\n println(row)\r\n case i if i > 2 && i < h - 1 =>\r\n val row = \"s${i % 2}\" + \"0\" * (w - 2) + \"s${i % 2}\"\r\n println(row)\r\n case _ => println(\"0\" * w)\r\n }\r\n println()\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(h, w) = readLine().split(\" \").map(_.toInt)\r\n\r\n (1 to h).foreach {\r\n case i if i == 1 || i == h => (1 to w).map(_ % 2).mkString(\"\")\r\n case i if i > 2 && i < h - 1 => \"s${i % 2}\" + \"0\" * (w - 2) + \"s${i % 2}\"\r\n case _ => \"0\" * 2\r\n }\r\n println()\r\n }\r\n}\r\n"}], "src_uid": "730cc4be2656c1dcdbda220b8778cdbf"} {"source_code": "object B extends App {\r\n def remove(input: String): String = {\r\n lazy val singles = input.collectFirst { case char @ ('1' | '4' | '6' | '8' | '9') => char.toString }\r\n lazy val pairs = input.tail.collectFirst { case char @ ('2' | '5') => s\"${input.head}$char\" }\r\n lazy val doubles = input.groupBy(identity).collectFirst { case (char, slice) if slice.length > 1 => s\"$char$char\" }\r\n lazy val specials = s\"${input.head}7\"\r\n\r\n singles getOrElse (pairs getOrElse (doubles getOrElse specials))\r\n }\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val k = readInt()\r\n val number = readLine()\r\n\r\n val output = remove(number)\r\n\r\n println(output.length)\r\n println(output)\r\n }\r\n\r\n}\r\n", "positive_code": [{"source_code": "object B extends App {\r\n def remove(input: String): String =\r\n input.collectFirst { case char @ ('1' | '4' | '6' | '8' | '9') => char.toString } getOrElse {\r\n input.tail.collectFirst { case char @ ('2' | '5') => s\"${input.head}$char\" } getOrElse {\r\n input.groupBy(identity).collectFirst { case (char, slice) if slice.length > 1 => s\"$char$char\" } getOrElse {\r\n input.head match {\r\n case '2' => \"27\"\r\n case '5' => \"57\"\r\n }\r\n }\r\n }\r\n }\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val k = readInt()\r\n val number = readLine()\r\n\r\n val output = remove(number)\r\n\r\n println(s\"${output.length}\\n$output\")\r\n }\r\n\r\n}\r\n"}], "negative_code": [{"source_code": "object B extends App {\r\n def remove(input: String): String =\r\n input.head match {\r\n case char @ ('1' | '4' | '6' | '8' | '9') => char.toString\r\n case _ =>\r\n input.contains('1') match {\r\n case true => \"1\"\r\n case _ =>\r\n input.tail.indexWhere { char =>\r\n val digit = char - 48\r\n digit == 5 || digit % 2 == 0\r\n } match {\r\n case i if i >= 0 => input.take(i + 2)\r\n case _ =>\r\n input.groupBy(_ - 48).collectFirst {\r\n case (digit, slice) if slice.length > 1 => s\"$digit$digit\"\r\n } match {\r\n case Some(output) => output\r\n case _ => input.take(input.indexOf('7') + 1)\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val k = readInt()\r\n val number = readLine()\r\n\r\n val output = remove(number)\r\n\r\n println(s\"${output.length}\\n$output\")\r\n }\r\n\r\n}\r\n"}, {"source_code": "object B extends App {\r\n def remove(input: String): String =\r\n input.head match {\r\n case char @ ('1' | '4' | '6' | '8' | '9') => char.toString\r\n case _ =>\r\n input.contains('1') match {\r\n case true => \"1\"\r\n case _ =>\r\n input.tail.indexWhere { char =>\r\n val digit = char - 48\r\n digit == 5 || digit % 2 == 0\r\n } match {\r\n case i if i >= 0 => input.take(i + 2)\r\n case _ =>\r\n input.groupBy(_ - 48).collectFirst {\r\n case (digit, slice) if slice.length > 1 => s\"$digit$digit\"\r\n } match {\r\n case Some(output) => output\r\n case _ => input.take(input.indexOf('7') + 1)\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val k = readInt()\r\n val number = readLine()\r\n\r\n val output = remove(number)\r\n\r\n println(output.length)\r\n println(output)\r\n }\r\n\r\n}\r\n"}], "src_uid": "22c0489eec3d8e290fcbcf1aeb3bb66c"} {"source_code": "import java.io.PrintWriter\r\nimport java.util.Scanner\r\n\r\nobject Solution {\r\n def solve(arr: Array[Int]): Long = {\r\n val sum = arr.sum.toLong\r\n val count = arr.length.toLong\r\n\r\n if (sum == count) 0 else {\r\n // if sum < count then just add one more number with count-sum+1\r\n\r\n // you want to add (count-sum+1)\r\n // sum goes to sum+(count-sum+1)=count+1, and count goes to count+1\r\n // count-sum+1 >= 0, count >= sum-1\r\n if (count >= sum-1) 1 else {\r\n // count < sum-1\r\n // so we need to add a lot of zeros...\r\n // k zeros so (count+k) = sum => k = sum-count\r\n sum-count\r\n }\r\n }\r\n }\r\n\r\n def run(input: Scanner, output: PrintWriter): Unit = {\r\n val tests = input.nextInt()\r\n\r\n (1 to tests).foreach { test =>\r\n val n = input.nextInt()\r\n output.println(solve((1 to n).map { _ => input.nextInt() }.toArray))\r\n }\r\n\r\n output.flush()\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n run(new Scanner(System.in), new PrintWriter(System.out))\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n val asum = an.foldLeft(0L)(_ + _)\r\n\r\n val ans =\r\n if (n < asum) asum - n\r\n else if (n > asum) 1\r\n else 0\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn._\r\n\r\n\r\nobject Main {\r\n def main(args: Array[String]) {\r\n val t : Int = readInt()\r\n for (i <- Range(0,t)) {\r\n val n = readInt()\r\n val vec = readLine().split(\" \").map(_.toInt)\r\n val sum = vec.sum\r\n if(sum == n) {\r\n println(0)\r\n } else if(sum > n) {\r\n println(sum - n)\r\n } else {\r\n println(1)\r\n }\r\n }\r\n }\r\n}\r\n\r\n"}], "negative_code": [], "src_uid": "b5985b619652e606ac96554ecfb9346a"} {"source_code": "object A extends App{\n val nk = readLine.split(\" \").map(_.toInt)\n val nums = readLine.split(\" \")\n println((nums.filter(_.filter(x=> x=='4' || x=='7').length <= nk(1))).length)\n}\n", "positive_code": [{"source_code": "import scala.io._\n\nobject Test {\n def main(args: Array[String]): Unit = {\n val lines = Source.stdin.getLines().take(2).toArray\n val a = lines(0).split(' ').map(_.toInt)\n val (n,k) = (a(0), a(1))\n val ns = lines(1).split(' ').count(_.count(p => p=='4' || p=='7') <= k)\n println(ns)\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n println(in.next().split(\" \").map(_.count(ch => ch == '4' || ch == '7')).filter(_ <= k).size)\n \n}"}, {"source_code": "import java.util.Scanner\n\nobject Main extends App {\n def luckyCount(n : Int) = {\n var x = n\n var result = 0\n\n while(x != 0) {\n if(x % 10 == 4 || x % 10 == 7) result += 1\n x /= 10\n }\n\n result\n }\n\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n val k = scanner.nextInt()\n var answer = 0\n\n for(i <- 1 to n)\n if(luckyCount(scanner.nextInt) <= k)\n answer += 1\n\n println(answer)\n}\n"}, {"source_code": "object J {\n \n def main (args : Array[String]){\n var Array(n,k) = readLine.split(\" \").map(_.toInt)\n var a = readLine.split(\" \").map(_.toInt)\n var ans = 0;\n for (i <- a){\n var s = String.valueOf(i)\n var cnt = 0\n for (ch <- s){\n if (ch == '4' || ch == '7')cnt +=1\n }\n if (cnt<=k)ans += 1\n }\n println(ans)\n }\n\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P262A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N, K = sc.nextInt\n\n def isLucky(c: Char): Boolean = c == '4' || c == '7'\n\n val answer = List.fill(N)(sc.nextInt).map(_.toString).filter { s =>\n s.filter(isLucky).size <= K\n }.size\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n val Array(n, k) = readInts\n def ans = reader.readLine().split(\" \").count(_.count(\"47\".contains(_)) <= k)\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val nk = readLine().split(\" \").map(_.toInt)\n val n = nk(0)\n val k = nk(1)\n val a = readLine().split(\" \")\n val r = a.count(_.count(c => c == '4' || c == '7') <= k)\n println(r)\n }\n}"}, {"source_code": "import scala.Math.pow;\n\nobject App {\n\tdef readInts:Array[Int] = (readLine split \" \") map (_.toInt)\n //> readInts: => Array[Int]\n\t//def solve(s: java.lang.String, a:Int):Int = {\n\t//} //> solve: (n: Int, m: Int, prev: Int, a: Int, b: Int)(Int, Int)\n\t \n\tdef f1_io() = {\n\t\tval Array(n, k) = readInts\t\n\t\tval ans = (readLine split \" \") map (x => (x filter(p => p == '4' || p == '7')).length)\n\t\tprint((ans filter (p => p <= k)).length)\n\t} \n def main(args: Array[String]): Unit = {\n\tf1_io\n }\n\n}"}, {"source_code": "object A{\n def main(args: Array[String]){\n\n //n,k\n val (n,k)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n //a,ans\n println(\n readLine.split(\" \").toList.map({\n _.toList.filter(s=> s=='4'||s=='7').length\n })\n .filter({\n _<=k\n })\n //ans\n .length\n )\n }\n}\n"}, {"source_code": "import java.util\n\nobject Main {\n def lucky(n: Int, k: Int) = {\n var c = 0\n var x = n\n while (x != 0) {\n c += (x % 10 match {\n case 4 | 7 => 1\n case _ => 0\n })\n x = x / 10\n }\n c <= k\n }\n\n def main(args: Array[String]) {\n val n = readToken.toInt\n val k = readToken.toInt\n println((0 until n).filter(i => lucky(readToken.toInt, k)).size)\n }\n\n var st = new util.StringTokenizer(\"\")\n def readToken() = {\n while (!st.hasMoreTokens) st = new java.util.StringTokenizer(readLine)\n st.nextToken\n }\n}\n"}, {"source_code": "object Codeforces extends App {\n val in = new java.util.Scanner(System.in)\n val n = in.nextInt()\n val k = in.nextInt()\n var cnt = 0\n for (i <- 0 until n) {\n var a = in.nextInt()\n var len = 0\n while (a > 0) {\n var b = a % 10\n a /= 10\n if (b == 4 || b == 7) {\n len += 1\n }\n }\n if (len <= k) {\n cnt += 1\n }\n }\n println(cnt)\n}"}], "negative_code": [{"source_code": "object A extends App{\n val nk = readLine.split(\" \").map(_.toInt)\n val nums = readLine.split(\" \")\n println((nums.filter(cNum => cNum.filter(x=> x=='4' || x=='7').length < nk(0))).length)\n\n}\n"}, {"source_code": "object A extends App{\n // val in = io.Source//.stdin.getLines\n val nk = readLine.split(\" \").map(_.toInt)\n val nums = readLine.split(\" \")\n // println(n + \" \" + k)\n nums.foreach(println)\n println(nums.filter(_.length <= nk(1)).length)\n\n}\n"}, {"source_code": "object A extends App{\n val nk = readLine.split(\" \").map(_.toInt)\n val nums = readLine.split(\" \")\n println((nums.filter(cNum => cNum.filter(x=> x=='4' || x=='7').length < nk(0))).length)\n\n}\n"}, {"source_code": "object A extends App{\n // val in = io.Source//.stdin.getLines\n val nk = readLine.split(\" \").map(_.toInt)\n val nums = readLine.split(\" \")\n // println(n + \" \" + k)\n // nums.foreach(println)\n println(nums.filter(_.length <= nk(1)).length)\n\n}\n"}], "src_uid": "6bb26991c9ea70e51a6bda5653de8131"} {"source_code": "import java.util.StringTokenizer\n\nobject _548A extends App {\n var token = new StringTokenizer(\"\")\n\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n\n val s = next\n val k = next.toInt\n\n if (s.length % k != 0) println(\"NO\")\n else {\n val a = s.grouped(s.length / k)\n\n def isPalindrome(s: String) = {\n def is(l: Int, r: Int): Boolean =\n if (l > r) true\n else if (s(l) == s(r)) is(l + 1, r - 1)\n else return false\n is(0, s.length - 1)\n }\n\n if (a.forall(isPalindrome)) println(\"YES\")\n else println(\"NO\")\n }\n}\n", "positive_code": [{"source_code": "import scala.collection._ \n \nobject Test { \n def main(args: Array[String]) { \n \n var inLoop = true \n while (inLoop) { \n val words = scala.io.StdIn.readLine \n if (words != null) { \n var good = true \n val k = scala.io.StdIn.readLine.toInt \n \n if ((words.length % k) == 0) { \n val wordLen = words.length / k \n \n var i = 0 \n var j = 0 \n for (i <- 0 to (k - 1)) { \n val word = words.substring((i * wordLen), (i + 1) * wordLen) \n for (j <- 0 to (word.length / 2)) { \n if (word.charAt(j) != word.charAt(word.length - j - 1)) { \n good = false; \n } \n } \n } \n } else { \n good = false \n } \n \n if (good) println(\"YES\") else println(\"NO\") \n \n } else { \n \n inLoop = false \n } \n } \n } \n} "}, {"source_code": "\nimport scala.math._\nimport scala.collection.mutable\nimport scala.util.control.Breaks\nimport scala.annotation.tailrec\n\nobject Problem extends App {\n import Scanner._\n def exit() = System.exit(0)\n \n val line = readLine\n val k = readInt\n val n = line.length\n \n if(n%k!=0) {\n println(\"NO\")\n exit\n }\n \n val len = n/k\n \n for(i <- 0 until k; p <- 0 until len; if line(i*len+p) != line(i*len+len-p-1)) {\n println(\"NO\")\n exit\n }\n \n println(\"YES\")\n}\n\nobject Scanner {\n def readInt() = {\n var acc = 0\n readWith {\n case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n }\n acc\n }\n def readLong() = {\n var acc = 0L\n readWith {\n case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10L) + (c - '0')\n }\n acc\n }\n def readDouble() = {\n var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)\n readWith {\n case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>\n acc = (acc * 10) + (c - '0')\n case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>\n frac = (frac * 10) + (c - '0')\n fracPow *= 10\n case c if c == '.' && !readFrac =>\n readFrac = true\n }\n acc + (frac.toDouble / fracPow)\n }\n def readString() = {\n var string = new StringBuilder\n readWith { case c => string += c }\n string.toString\n }\n def readLine() = Console.in.readLine()\n def readChar() = Console.in.read().toChar\n def readWith(func: PartialFunction[Char, Unit]) {\n val handler = func orElse[Char, Unit] {\n case _ => throw new java.io.IOException(\"unexpected token\")\n }\n\n var c = readChar\n while(c.isWhitespace)\n c = readChar\n\n while(!c.isWhitespace) {\n handler(c)\n\n c = readChar\n }\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A {\n\n\tdef isPalindromSubstring(s:String, pos:Int, length:Int):Boolean = {\n\t\tfor {\n\t\t\ti <- 0 until length / 2\n\t\t\tc1 = s.charAt(pos + i)\n\t\t\tc2 = s.charAt(pos + length - 1 - i)\n\t\t} {\n\t\t\tif (c1 != c2) \n\t\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\n\tdef isContainsKPalindroms(s:String, k:Int):Boolean = {\n\t\tif (s.length() % k == 0) {\n\t\t\tval length = s.length() / k;\n\t\t\tfor (pos <- 0 until s.length() by length) {\n\t\t\t\tif (!isPalindromSubstring(s, pos, length)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tdef main(args:Array[String]) {\n\t\tprintln(if (isContainsKPalindroms(readLine, readInt)) \"YES\" else \"NO\")\n\t}\n\t\n}\n\n\n"}, {"source_code": "import java.io._\nimport java.util._\nimport scala.collection.mutable\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val s = next.toCharArray\n val k = nextInt\n val len = s.length / k\n if (len == 0 || s.length % k != 0) {\n out.println(\"NO\")\n return 1\n }\n var i = 0\n while (i < s.length) {\n var i1 = i\n var j1 = i + len - 1\n while (i1 <= j1) {\n if (i1 >= 0 && i1 < s.length && j1 >= 0 && j1 < s.length && s(i1) != s(j1)) {\n out.println(\"NO\")\n return 1\n }\n j1 -= 1\n i1 += 1\n }\n i += len\n }\n out.println(\"YES\")\n return 0\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val s = StdIn.readLine();\n val k = StdIn.readInt();\n\n if(s.length % k != 0) {\n println(\"NO\");\n return;\n }\n\n def isPolyndrome : String => Boolean = {\n case str if str.length < 2 => true\n case str =>\n if(str.head != str.last)\n false\n else\n isPolyndrome(str.substring(1, str.length - 1));\n }\n\n println(if(s.grouped(s.length / k).forall(isPolyndrome)) \"YES\" else \"NO\");\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val input = readLine()\n val k = readInt()\n\n def solve() = {\n if (input.length % k != 0) \"NO\"\n else {\n var str = input\n var size = input.length / k\n// println(str.take(size))\n while (str.length > 0 && isPalindrome(str.take(size))) {\n// println(str.take(size) + \" considered\")\n str = str.drop(size)\n }\n if (str.length == 0) \"YES\" else \"NO\"\n }\n }\n\n def isPalindrome(s: String): Boolean = s == s.reverse\n\n println(solve())\n}\n"}], "negative_code": [], "src_uid": "43bb8fec6b0636d88ce30f23b61be39f"} {"source_code": "object B {\n def main(args: Array[String]): Unit = {\n val Array(n, k) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val flowers = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n val count = Array.fill[Int](n)(0)\n for(i <- 1 to k) {\n val Array(q, w) = scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n// println(flowers.slice(q-1, w).mkString(\" \"))\n if (flowers.slice(q-1, w).sum > 0){\n for (j <- q - 1 until w){\n count(j) += 1\n }\n }\n }\n// println(count.mkString(\" \"))\n println(flowers.toStream.zip(count).map(x => x._2 * x._1).sum)\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toInt).scanLeft(0)(_+_)\n println((1 to m).foldLeft(0) {\n case (acc, _) =>\n val Array(x, y) = in.next().split(' ').map(_.toInt)\n acc + Math.max(0, a(y) - a(x - 1))\n })\n}\n"}], "negative_code": [], "src_uid": "6d7364048428c70e0e9b76ab1eb8cc34"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n val symmetric = Set('o', 'O', 'v', 'V', 'I', 'M', 'T', 'U', 'w', 'W', 'x', 'X', 'Y', 'A', 'H')\n if (line.length % 2 == 1 && !symmetric.contains(line(line.length / 2)))\n println(\"NIE\")\n else if (line.take(line.length / 2).zip(line.takeRight(line.length / 2).reverse).forall(i => (i._1 == i._2 && symmetric.contains(i._1)) ||\n (Math.min(i._1, i._2) == 'b' && Math.max(i._1, i._2) == 'd') || (Math.min(i._1, i._2) == 'p' && Math.max(i._1, i._2) == 'q'))) {\n println(\"TAK\")\n } else println(\"NIE\")\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Sym = Map(\n 'A' -> 'A',\n 'b' -> 'd',\n 'd' -> 'b',\n 'H' -> 'H',\n 'I' -> 'I',\n 'M' -> 'M',\n 'O' -> 'O',\n 'o' -> 'o',\n 'T' -> 'T',\n 'U' -> 'U',\n 'V' -> 'V',\n 'v' -> 'v',\n 'W' -> 'W',\n 'w' -> 'w',\n 'X' -> 'X',\n 'x' -> 'x',\n 'Y' -> 'Y',\n 'p' -> 'q',\n 'q' -> 'p'\n )\n\n val S = readLine().toCharArray\n\n def isSPal: Boolean = {\n for (i <- 0 until S.length / 2) {\n if (Sym.get(S(i)).isEmpty || Sym(S(i)) != S(S.length - i - 1)) {\n return false\n }\n }\n\n if (S.length % 2 == 0) true\n else {\n val mid = S(S.length / 2)\n Sym.get(mid).isDefined && Sym(mid) == mid\n }\n }\n\n println(if (isSPal) \"TAK\" else \"NIE\")\n\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n if (line.length % 2 == 0)\n println(\"NIE\")\n else if (line.take(line.length / 2).zip(line.takeRight(line.length / 2).reverse).forall(i => i._1 == i._2 ||\n (Math.min(i._1, i._2) == 'b' && Math.max(i._1, i._2) == 'd') || (Math.min(i._1, i._2) == 'p' && Math.max(i._1, i._2) == 'q'))) {\n println(\"TAK\")\n } else println(\"NIE\")\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n val symmetric = Set('o', 'O', 'v', 'V', 'I', 'M', 'T', 'U', 'w', 'W', 'x', 'X', 'Y')\n if (line.length % 2 == 1 && !symmetric.contains(line(line.length / 2 + 1)))\n println(\"NIE\")\n else if (line.take(line.length / 2).zip(line.takeRight(line.length / 2).reverse).forall(i => (i._1 == i._2 && symmetric.contains(i._1)) ||\n (Math.min(i._1, i._2) == 'b' && Math.max(i._1, i._2) == 'd') || (Math.min(i._1, i._2) == 'p' && Math.max(i._1, i._2) == 'q'))) {\n println(\"TAK\")\n } else println(\"NIE\")\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n val symmetric = Set('o', 'O', 'v', 'V', 'I', 'M', 'T', 'U', 'w', 'W', 'x', 'X', 'Y')\n if (line.length % 2 == 0 || !symmetric.contains(line(line.length / 2)))\n println(\"NIE\")\n else if (line.take(line.length / 2).zip(line.takeRight(line.length / 2).reverse).forall(i => (i._1 == i._2 && symmetric.contains(i._1)) ||\n (Math.min(i._1, i._2) == 'b' && Math.max(i._1, i._2) == 'd') || (Math.min(i._1, i._2) == 'p' && Math.max(i._1, i._2) == 'q'))) {\n println(\"TAK\")\n } else println(\"NIE\")\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n val symmetric = Set('o', 'O', 'v', 'V', 'I', 'M', 'T', 'U', 'w', 'W', 'x', 'X', 'Y', 'A')\n if (line.length % 2 == 1 && !symmetric.contains(line(line.length / 2)))\n println(\"NIE\")\n else if (line.take(line.length / 2).zip(line.takeRight(line.length / 2).reverse).forall(i => (i._1 == i._2 && symmetric.contains(i._1)) ||\n (Math.min(i._1, i._2) == 'b' && Math.max(i._1, i._2) == 'd') || (Math.min(i._1, i._2) == 'p' && Math.max(i._1, i._2) == 'q'))) {\n println(\"TAK\")\n } else println(\"NIE\")\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n val symmetric = Set('o', 'O', 'v', 'V', 'I', 'M', 'T', 'U', 'w', 'W', 'x', 'X', 'Y')\n if (line.length % 2 == 1 && !symmetric.contains(line(line.length / 2)))\n println(\"NIE\")\n else if (line.take(line.length / 2).zip(line.takeRight(line.length / 2).reverse).forall(i => (i._1 == i._2 && symmetric.contains(i._1)) ||\n (Math.min(i._1, i._2) == 'b' && Math.max(i._1, i._2) == 'd') || (Math.min(i._1, i._2) == 'p' && Math.max(i._1, i._2) == 'q'))) {\n println(\"TAK\")\n } else println(\"NIE\")\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n val symmetric = Set('o', 'O', 'v', 'V', 'I', 'M', 'T', 'U', 'w', 'W', 'x', 'X', 'Y')\n if (line.length % 2 == 0 && symmetric.contains(line(line.length / 2)))\n println(\"NIE\")\n else if (line.take(line.length / 2).zip(line.takeRight(line.length / 2).reverse).forall(i => (i._1 == i._2 && symmetric.contains(i._1)) ||\n (Math.min(i._1, i._2) == 'b' && Math.max(i._1, i._2) == 'd') || (Math.min(i._1, i._2) == 'p' && Math.max(i._1, i._2) == 'q'))) {\n println(\"TAK\")\n } else println(\"NIE\")\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Sym = Map(\n 'A' -> 'A',\n 'b' -> 'd',\n 'd' -> 'b',\n 'H' -> 'H',\n 'I' -> 'I',\n 'M' -> 'M',\n 'm' -> 'm',\n 'O' -> 'O',\n 'o' -> 'o',\n 'T' -> 'T',\n 'U' -> 'U',\n 'V' -> 'V',\n 'v' -> 'v',\n 'W' -> 'W',\n 'w' -> 'w',\n 'X' -> 'X',\n 'x' -> 'x',\n 'Y' -> 'Y',\n 'p' -> 'q',\n 'q' -> 'p'\n )\n\n val S = readLine().toCharArray\n\n def isSPal: Boolean = {\n for (i <- 0 until S.length / 2) {\n if (Sym.get(S(i)).isEmpty || Sym(S(i)) != S(S.length - i - 1)) {\n return false\n }\n }\n\n if (S.length % 2 == 0) true\n else {\n val mid = S(S.length / 2)\n Sym.get(mid).isDefined && Sym(mid) == mid\n }\n }\n\n println(if (isSPal) \"TAK\" else \"NIE\")\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Sym = Map(\n 'A' -> 'A',\n 'b' -> 'd',\n 'd' -> 'b',\n 'H' -> 'H',\n 'I' -> 'I',\n 'M' -> 'M',\n 'm' -> 'm',\n 'O' -> 'O',\n 'o' -> 'o',\n 'T' -> 'T',\n 'U' -> 'U',\n 'V' -> 'V',\n 'v' -> 'v',\n 'W' -> 'W',\n 'w' -> 'w',\n 'X' -> 'X',\n 'x' -> 'x',\n 'Y' -> 'Y'\n )\n\n val S = readLine().toCharArray\n\n def isSPal: Boolean = {\n for (i <- 0 until S.length / 2) {\n if (Sym.get(S(i)).isEmpty || Sym(S(i)) != S(S.length - i - 1)) {\n return false\n }\n }\n\n if (S.length % 2 == 0) true\n else {\n val mid = S(S.length / 2)\n Sym.get(mid).isDefined && Sym(mid) == mid\n }\n }\n\n println(if (isSPal) \"TAK\" else \"NIE\")\n\n}\n"}], "src_uid": "bec2349631158b7dbfedcaededf65cc2"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val OR, AND = na(N - 1)\n\n val next = Array.fill[Int](N - 1, 4)(-1)\n rep(N - 1) { i =>\n rep(4) { t1 =>\n rep(4) { t2 =>\n if ((t1 & t2) == AND(i) && (t1 | t2) == OR(i)) next(i)(t1) = t2\n }\n }\n }\n\n def tryIt(s: Int): Boolean = {\n var p = s\n rep(N - 1) { i =>\n val nxt = next(i)(p)\n if (nxt == -1) return false\n p = nxt\n }\n true\n }\n\n def create(s: Int): Array[Int] = {\n val res = Array.ofDim[Int](N)\n res(0) = s\n rep(N - 1) { i =>\n res(i + 1) = next(i)(res(i))\n }\n res\n }\n\n val oks = 0 until 4 filter tryIt\n if (oks.isEmpty) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n out.println(create(oks.head).mkString(\" \"))\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}", "positive_code": [{"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as, bs = readInts(n - 1)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n val ts = Array.ofDim[Int](n)\n\n for (t0 <- 0 to 3) {\n ts(0) = t0\n var i = 1\n while (i < n) {\n var t = 0\n ts(i) = -1\n while (t <= 3) {\n if ((ts(i - 1) | t) == as(i - 1) &&\n (ts(i - 1) & t) == bs(i - 1)) {\n ts(i) = t\n t = 4\n } else t += 1\n }\n if (ts(i) >= 0) {\n i += 1\n } else i = n + 1\n }\n if (i == n) {\n println(\"YES\")\n println(ts.mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n }\n\n println(\"NO\")\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as, bs = readInts(n - 1)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n val ts = Array.ofDim[Int](n)\n\n for (t0 <- 0 until 3) {\n ts(0) = t0\n var i = 1\n while (i < n) {\n var t = 0\n ts(i) = -1\n while (t <= 3) {\n if ((ts(i - 1) | t) == as(i - 1) &&\n (ts(i - 1) & t) == bs(i - 1)) {\n ts(i) = t\n t = 4\n } else t += 1\n }\n if (ts(i) >= 0) {\n i += 1\n } else i = n + 1\n }\n if (i == n) {\n println(\"YES\")\n println(ts.mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n }\n\n println(\"NO\")\n\n Console.flush\n}\n"}], "src_uid": "ac21483a33e7bcb031b1f8f62e39d60f"} {"source_code": "import scala.collection._\n\nobject A extends App {\n \n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val n = readString.toInt\n var r = 0\n var prev = \"\"\n \n for (i <- 0 until n) {\n val s = readString\n if (s != prev) {\n r += 1\n prev = s\n }\n }\n\n println(r)\n}", "positive_code": [{"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport scala.math._\n\nobject Main {\n\t\n\tdef main(args: Array[String]) { \n\t\tval n = in.rdInt\n\t\tvar ans = 1\n\t\tvar last = in.next\n\t\tfor (i <- 2 to n) {\n\t\t\tval cur = in.next\n\t\t\tif (last != cur) ans+=1\n\t\t\tlast = cur\n\t\t}\n\t\tprintln(ans)\n\t}\n\n\tobject in {\n\t\tval in = new BufferedReader(new InputStreamReader(System.in))\n\t\tvar st = new StringTokenizer(\"\")\n\n\t\tdef next : String = {\n\t\t\twhile (!st.hasMoreTokens) {\n\t\t\t\tval line = in.readLine\n\t\t\t\tif (line == null) return null\n\t\t\t\teat(line)\n\t\t\t}\n\t\t\tst.nextToken\n\t\t}\n\t\t\n\t\tdef FastReader = eat(\"\")\n\t\tdef eat(s : String) = st = new StringTokenizer(s)\n\t\tdef rdInt = next.toInt\n\t\tdef rdLong = next.toLong\n\t\tdef rdDouble = next.toDouble\n\t}\n\t\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main extends App {\n val n = StdIn.readInt()\n var prev = StdIn.readLine()\n var count = 1\n\n for (_ <- 2 to n) {\n val next = StdIn.readLine()\n if (next.head == prev.last) count += 1\n prev = next\n }\n\n println(count)\n}"}, {"source_code": "object CF0344A extends App {\n\n val n = readInt()\n var count = 0\n var str = \"\\0\"\n (1 to n) foreach(k => {\n val s = readLine()\n if(str == \"\\0\" || s != str) {\n count += 1\n str = s\n }\n })\n\n println(count)\n}\n"}, {"source_code": "object Magnets {\n def main(arg: Array[String]) {\n val changes = (0 until readInt()).\n map(x=>readInt).\n sliding(2,1).\n map(l=>l.distinct.length).\n filter(_ > 1).\n length\n println(changes + 1)\n }\n}"}, {"source_code": "object Solution extends App{\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val first = in.next()\n println(Range(0, n - 1).map(_ => in.next()).foldLeft((first, 1)) {\n case((prev, count), el) if prev == el => (el, count)\n case((prev, count), el) => (el, count + 1)\n }._2)\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Magnets extends App {\n\n val count = StdIn.readLine().toInt\n\n val magnets = new collection.mutable.ArrayBuffer[String]()\n for (i <- 0 until count) {\n magnets += StdIn.readLine()\n }\n print(impl(magnets.toArray))\n\n def impl(magnets: Array[String]): Int = {\n var groups = 1\n var prev = magnets(0)\n\n for (magnet <- magnets) {\n if (magnet != prev) {\n groups += 1\n prev = magnet\n }\n }\n\n groups\n }\n}\n"}, {"source_code": "import scala.collection.JavaConversions._\nimport scala.collection.mutable.ArraySeq\n\nobject Codeforces344A {\n def main(args: Array[String]) {\n val n = scala.io.StdIn.readLine().toInt\n var lastChar = scala.io.StdIn.readLine().charAt(1)\n var groups = 1\n for (i <- 0 until n-1) {\n val m = scala.io.StdIn.readLine()\n if (m.charAt(0) == lastChar)\n groups += 1\n lastChar = m.charAt(1)\n }\n println(groups)\n }\n}"}, {"source_code": "object Solve{\n def main(args: Array[String]): Unit = {\n \n val n = readInt()\n var pole1 = readLine()\n var res = 0\n for(i <- 1 to n){\n val pole = readLine()\n if(pole != pole1){\n res += 1\n pole1 = pole\n }\n }\n \n println(res)\n \n }\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\nimport scala.util.Sorting._\nimport scala.math._\nimport scala.collection._\nimport java.util._\n\nobject HelloWorld {\n\n def main(args: Array[String]) {\n\n val n = readInt().toInt\n val magnets = for(i <- 0 until n) yield readLine.trim\n\n var islands = 0\n for(i <- 0 until n - 1) {\n islands += (if (magnets(i)(1) == magnets(i+1)(0)) 1 else 0)\n }\n\n println(islands + 1)\n }\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\nimport scala.util.Sorting._\nimport scala.math._\nimport scala.collection._\nimport java.util._\n\nobject HelloWorld {\n\n def main(args: Array[String]) {\n\n val n = readInt().toInt\n var islands = 0\n var magnets = ArrayBuffer[String]()\n\n for(i <- 0 until n) {\n val magnet = readLine.trim\n magnets += magnet\n }\n\n for(i <- 0 until n - 1) {\n if (magnets(i)(1) == magnets(i+1)(0)) islands += 1\n }\n\n println(islands + 1)\n }\n}"}, {"source_code": "object A344 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = new Array[String](n)\n for(i <- 0 until n) {\n input(i) = scala.io.StdIn.readLine\n }\n var res = 1\n for(i <- 1 until n) {\n if(input(i)(0) == input(i-1)(1)) {\n res += 1\n }\n }\n println(res)\n }\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val n = readString.toInt\n var r = 0\n var prev = \"\"\n \n var i = 0\n while (i < n) {\n i += 1\n val s = readString\n if (!s.equals(prev)) {\n r += 1\n prev = s\n }\n }\n\n println(r)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P344A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n sc.nextLine\n val MS = List.fill(N)(sc.nextLine)\n\n def solve(): Unit = {\n\n @tailrec\n def loop(acc: Int, last: String, ms: List[String]): Int = ms match {\n case Nil => acc\n case x :: xs => if (x == last) loop(acc, x, xs)\n else loop(acc + 1, x, xs)\n }\n\n out.println(loop(0, \"\", MS))\n }\n\n solve\n out.close\n}\n"}, {"source_code": "\n\nobject Magnets {\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in);\n\t\tval n = scanner.nextInt();\n\t var current = scanner.nextInt();\n\t var nbGroups = 1;\n\t\tfor (i <- 2 to n) {\n\t\t val previous = current\n\t\t current = scanner.nextInt();\n\t\t if (current != previous)\n\t\t nbGroups += 1\n\t\t}\n\t\tprintln(nbGroups)\n\t}\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val num = readInt()\n var groups = 0\n var prev = \"00\"\n for(_ <- 1 to num) {\n val cur = readLine\n if (cur != prev) {\n groups += 1\n prev = cur\n } \n }\n println(groups)\n }\n}"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject Magnets {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def main(args: Array[String]) {\n val n = readInt\n val magnets = for {\n i <- 1 to n\n m = readLine\n } yield m\n println(magnets.zipWithIndex.foldLeft(0)\n { case (g,(s,i)) => if (i < n -1 && s(1) != magnets(i+1)(0)) g else g + 1})\n }\n \n}"}], "negative_code": [], "src_uid": "6c52df7ea24671102e4c0eee19dc6bba"} {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.Map\n\nobject Opposites {\n\n val scanner = new Scanner(System.in)\n val c = scanner.nextInt();\n \n val input = (1 to c) map {i => scanner.nextInt()}\n \n def main(args: Array[String]) {\n var map = Map[Long,Long]()\n for (i <- input) {\n map += (i.toLong -> (1l + ( if (map.contains(i)) map(i).toLong else 0l)))\n }\n \n var sum:Long = if (map contains(0)) map(0) else 0; \n sum = (0l/:(1l until sum)) {(sum:Long,i:Long) => sum+i}\n \n \n map = map.filter({entry => entry._1 != 0})\n \n sum += ((0l/:map) {(sum,entry)=> \n sum + {if (map.contains(-entry._1)) entry._2 * map(-entry._1) else 0 } }) / 2\n \n println(sum)\n }\n \n}", "positive_code": [{"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toLong\n var zeros = 0l\n val plus = Array.ofDim[Int](10)\n val minus = Array.ofDim[Int](10)\n in.next().split(' ').map(_.toInt).foreach {\n case (0) => zeros += 1\n case i if i < 0 => minus(-i - 1) += 1\n case i => plus(i - 1) += 1\n }\n val r = plus.zip(minus).foldLeft(0l) {\n case (soFar, (0, second)) => soFar\n case (soFar, (first, 0)) => soFar\n case (soFar, (first, second)) => soFar + first.toLong * second\n } + (zeros - 1) * zeros / 2\n\n println(r)\n}\n"}, {"source_code": "\nimport scala.collection.mutable.HashMap;\n\nobject Main {\n\n def main(args: Array[String]) {\n val n = nextInt\n val a = for (i <- 1 to n) yield nextInt\n val map = HashMap[Int,Long]()\n a.foreach(x => map.put(x, map.getOrElse(x, 0L) + 1L))\n val ans = a.map(x => map.getOrElse(-x, 0L) - (if (x==0) 1 else 0)).sum\n println(ans / 2)\n }\n\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));\n var st = new java.util.StringTokenizer(\"\");\n\n def next() = {\n while (!st.hasMoreTokens())\n st = new java.util.StringTokenizer(in.readLine());\n st.nextToken();\n }\n\n def nextInt() = java.lang.Integer.parseInt(next());\n def nextDouble() = java.lang.Double.parseDouble(next());\n def nextLong() = java.lang.Long.parseLong(next());\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P131B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val ts: Map[Long, Long] = List.fill(N)(sc.nextLong).groupBy(identity[Long]).map(x => (x._1, x._2.length.toLong)).withDefaultValue(0L)\n\n val n0: Long = ts(0L)\n val answer: Long = ts.keys.filter(_ > 0L).toList.map(x => ts(x) * ts(-x)).sum + n0 * (n0 - 1) / 2\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val n = readInt\n val a = readInts\n val grouped = a.groupBy(x => x).mapValues(_.length)\n def ans = (a.map(x => grouped.getOrElse(-x, 0)).foldLeft(0L)(_ + _) - grouped.getOrElse(0, 0)) / 2\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val map = scala.collection.mutable.Map[Int, Int]()\n a.foreach(i => map(i) = map.getOrElse(i, 0) + 1)\n val r = (1 to 10).map(i => map.getOrElse(i, 0).toLong * map.getOrElse(-i, 0).toLong).sum + (map.getOrElse(0, 0).toLong - 1) * map.getOrElse(0, 0).toLong / 2 \n println(r)\n }\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport scala.collection.mutable.Map\nobject Opposites {\n\n val scanner = new Scanner(System.in)\n val c = scanner.nextInt();\n val input = (1 to c) map {i => scanner.nextInt()}\n \n def main(args: Array[String]) {\n var map = Map[Int,Int]()\n for (i <- input) {\n map += (i -> (1 + ( if (map.contains(i)) map(i) else 0)))\n }\n \n var sum = if (map contains(0)) map(0) else 0; \n sum = (0/:(1 until sum)) {(sum,i) => sum+i}\n \n \n map = map.filter({entry => entry._1 != 0})\n \n sum += ((0/:map) {(sum,entry)=> \n sum + {if (map.contains(-entry._1)) entry._2 * map(-entry._1) else 0 } }) / 2\n \n println(sum)\n \n \n \n }\n \n}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.Map\nobject Opposites {\n\n val scanner = new Scanner(System.in)\n val c = scanner.nextInt();\n val input = (1 to c) map {i => scanner.nextInt()}\n \n def main(args: Array[String]) {\n var map = Map[Int,Int]()\n for (i <- input) {\n map += (i -> (1 + ( if (map.contains(i)) map(i) else 0)))\n }\n \n var sum:Long = if (map contains(0)) map(0) else 0; \n sum = (0l/:(1l until sum)) {(sum:Long,i:Long) => sum+i}\n \n \n map = map.filter({entry => entry._1 != 0})\n \n sum += ((0/:map) {(sum,entry)=> \n sum + {if (map.contains(-entry._1)) entry._2 * map(-entry._1) else 0 } }) / 2\n \n println(sum)\n \n \n \n }\n \n}"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toLong\n var zeros = 0\n val plus = Array.ofDim[Int](10)\n val minus = Array.ofDim[Int](10)\n in.next().split(' ').map(_.toInt).foreach {\n case (0) => zeros += 1\n case i if i < 0 => minus(-i - 1) += 1\n case i => plus(i - 1) += 1\n }\n val r = plus.zip(minus).foldLeft(0l) {\n case (soFar, (0, second)) => soFar\n case (soFar, (first, 0)) => soFar\n case (soFar, (first, second)) => soFar + first.toLong * second\n } + (zeros - 1) * zeros / 2\n\n println(r)\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P131B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val ts = List.fill(N)(sc.nextInt).groupBy(identity[Int]).map(x => (x._1, x._2.length)).withDefaultValue(0)\n\n val n0 = ts(0)\n\n val answer: Int = ts.keys.filter(_ > 0).map(x => ts(x) * ts(-x)).sum + n0 * (n0 - 1) / 2\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P131B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextLong\n val ts: Map[Long, Long] = List.fill(N.toInt)(sc.nextLong).groupBy(identity[Long]).map(x => (x._1, x._2.length.toLong)).withDefaultValue(0L)\n\n val n0 = ts(0)\n\n val answer: Long = ts.keys.filter(_ > 0).map(x => ts(x) * ts(-x)).sum + n0 * (n0 - 1) / 2\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P131B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val ts = List.fill(N)(sc.nextLong).groupBy(identity[Long]).map(x => (x._1, x._2.length)).withDefaultValue(0)\n\n val n0 = ts(0)\n\n val answer: Long = ts.keys.filter(_ > 0).map(x => ts(x) * ts(-x)).sum + n0 * (n0 - 1) / 2\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val n = readInt\n val a = readInts\n val grouped = a.groupBy(x => x).mapValues(_.length)\n def ans = (a.map(x => grouped.getOrElse(-x, 0)).sum - grouped.getOrElse(0, 0)) / 2\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val map = scala.collection.mutable.Map[Int, Int]()\n a.foreach(i => map(i) = map.getOrElse(i, 0) + 1)\n val r = (1 to 10).map(i => map.getOrElse(i, 0) * map.getOrElse(-i, 0)).sum + (map.getOrElse(0, 0) - 1) * map.getOrElse(0, 0) / 2 \n println(r)\n }\n}"}], "src_uid": "f3dde329830d8c479b3dab9d5df8baf5"} {"source_code": "import java.util.Scanner\n\nobject Main {\n\n def sqr(x: Long) = x * x\n\n def powmod(x: Long, n: Long, p: Long): Long = {\n if (n == 1) x\n else if (n % 2 == 1) (powmod(x, n - 1, p) * x) % p\n else sqr(powmod(x, n / 2, p)) % p\n }\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n\n val n = in.nextInt()\n\n val t = in.nextInt()\n\n println(\"%.9f\".format(Math.pow(1.000000011, t) * n))\n }\n}\n", "positive_code": [{"source_code": "\n/**\n * Created by octavian on 18/02/2016.\n */\nobject Moore {\n\n def main(args: Array[String]) {\n //System.setIn(new FileInputStream(\"src/moore.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"src/moore.out\")))\n\n var Array(n, t): Array[Long] = readLine().split(\" \").map(_.toLong)\n var basis: Double = 1.000000011\n\n println(raise(basis, t) * n)\n\n }\n\n def raise(basis: Double, power: Long): Double = {\n var res: Double = 1\n var acc = basis\n var c_power = power\n while(c_power > 0) {\n if(c_power % 2 == 1) {\n c_power -= 1\n res *= acc\n }\n if(c_power > 0) {\n c_power /= 2\n acc = Math.pow(acc, 2)\n }\n }\n\n return res\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject MooresLaw {\n\n def main(args: Array[String]) {\n val Array(n, t) = StdIn.readLine().split(\"\\\\s+\").map(_.toInt)\n print(n * Math.pow(1.000000011, t))\n }\n \n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import java.math.BigDecimal\n\nobject Bitz_B { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n val t = line1.int\n \n// val bd = BigDecimal(1.000000011)\n// val res = bd.pow(t) * n\n// \n//// val res = Math.pow(pp, t) * n\n \n def pow(arg:Double, pp:Int):Double = {\n if (pp == 0) return 1\n if (pp == 1) return arg\n val half = pow(arg, pp/2)\n if (pp % 2 == 0) {\n return half * half\n } else {\n return half * half * arg\n }\n } \n \n val res = pow(1.000000011, t) * n\n \n println(res.toDouble)\n \n \n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n \n //---------------------------- service code ----------------------------------\n\n \n def readLine() = new Line \n class Line {\n val tok = new StringTokenizer(br.readLine(), \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n1000 1000000\n\"\"\"\n\n}\n\n}\n"}], "negative_code": [], "src_uid": "36ad784f23bd1e8e579052642a6e9244"} {"source_code": "object CF611A extends App {\n\n import scala.io.StdIn\n\n val t = StdIn.readInt\n for (_ <- 0 until t) {\n val Array(h, m) = StdIn.readLine.split(' ').map(_.toInt)\n println((23-h)*60 + 60-m)\n }\n}\n", "positive_code": [{"source_code": "case class Trap(l: Int, r: Int, d: Int)\n\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n\n val t = stdin.next().toInt\n println(stdin.take(t).map(_.split(\" \").map(_.toInt)).map(arr => calc(arr(0), arr(1))).mkString(\" \"))\n\n def calc(hours: Int, minutes: Int): Int = (23 - hours) * 60 + (60 - minutes)\n}\n\n\n"}], "negative_code": [], "src_uid": "f4982de28aca7080342eb1d0ff87734c"} {"source_code": "import scala.annotation.tailrec\n\n/**\n * Created by antonk on 29.09.14.\n */\nobject TaskA {\n def main(args: Array[String]) {\n val n = readInt\n val handles = {for (_ <- (1 to n)) yield {readLine split ' ' toList}} toArray\n val permutation = readLine split ' ' map(_.toInt - 1)\n// val inverse_permutation = Array.fill(n)(0)\n // for ((x, i) <- permutation.view.zipWithIndex) inverse_permutation(x) = i\n @tailrec def isContinued(i: Int, max: Int, currentHandle: String = handles(permutation.head) min): String = {\n if (i == max) \"YES\"\n else ((currentHandle :: handles(permutation(i))) sorted) match {\n case List(x, r, _) if x == currentHandle => isContinued(i + 1, max, r)\n case List(_, x, r) if x == currentHandle => isContinued(i + 1, max, r)\n case _ => \"NO\"\n }\n }\n println(isContinued(1, n))\n// println(inverse_permutation map(_.toString) reduceLeft(_ + ' ' + _))\n }\n}", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _472C extends App {\n var token = new StringTokenizer(\"\")\n\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n\n val n = next.toInt\n val a = (1 to n).map(i => {\n val s = next; val ss = next; if (s < ss) (s, ss) else (ss, s)\n }).toArray\n val b = (1 to n).map(i => next.toInt - 1).map(i => a(i))\n\n def doit(i: Int, pre: String): Boolean = {\n if (i >= n) true\n else {\n if (b(i)._1 >= pre) doit(i + 1, b(i)._1)\n else if (b(i)._2 >= pre) doit(i + 1, b(i)._2)\n else return false\n }\n }\n\n if (doit(1, b(0)._1)) println(\"YES\")\n else println(\"NO\")\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map(_ => in.next())\n val indices = in.next().split(\" \").map(_.toInt - 1)\n val sorted = indices.map(i => data(i))\n if (sorted.foldLeft((\"\", true)) {\n case ((prev, false), el) => (prev, false)\n case ((prev, true), el) =>\n val Array(a, b) = el.split(\" \")\n if (prev > a && prev > b) {\n (prev, false)\n }\n else if (prev < a && prev < b) {\n if (a < b)\n (a, true)\n else\n (b, true)\n } else {\n if (prev > a)\n (b, true)\n else\n (a, true)\n }\n }._2)\n println(\"YES\")\n else\n println(\"NO\")\n}"}, {"source_code": "object C472 {\n import IO._\n import collection.{mutable => cu}\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val names = Array.fill(n)(read.split(\" \").sorted)\n val expected = readInts(n)\n def result(): Boolean = {\n var curr = names(expected.head-1).head\n var res = true\n for(i <- 1 until n if res) {\n if(names(expected(i)-1).head > curr) {\n curr = names(expected(i)-1).head\n } else if(names(expected(i)-1).last > curr) {\n curr = names(expected(i)-1).last\n } else {\n res = false\n }\n }\n res\n }\n if(result()) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n}\n"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n \n val ss = Array.ofDim[(String, String)](n)\n \n for (i <- 0 until n) {\n val s = readLine.split(\" \")\n ss(i) = (s(0), s(1))\n }\n\n val ps = readInts(n)\n\n var prev = \"\"\n \n for (p <- ps) {\n val (l, r) = ss(p - 1)\n val (min, max) = if (l < r) (l, r) else (r, l)\n if (min > prev) {\n prev = min\n } else if (max > prev) {\n prev = max\n } else {\n //println(min, max, prev)\n println(\"NO\")\n System.exit(0)\n }\n }\n \n println(\"YES\")\n}"}, {"source_code": "object C {\n def READ: Array[Int] = readLine() split (\" \") map (_.toInt);\n\n def main(args: Array[String]) {\n val Array(n) = READ;\n var w = Array.ofDim[String](n, 2)\n for (i <- 0 until n) w(i) = readLine() split (\" \") sorted\n val p = READ;\n w = p.map(x => w(x-1))\n var min = w(0) min;\n for (i <- 1 until n)\n if (min <= w(i)(0)) min = w(i)(0)\n else if (min <= w(i)(1)) min = w(i)(1)\n else {\n println(\"NO\")\n return;\n }\n println(\"YES\")\n }\n }\n"}], "negative_code": [{"source_code": "import scala.annotation.tailrec\n\n/**\n * Created by antonk on 29.09.14.\n */\nobject TaskA {\n def main(args: Array[String]) {\n val n = readInt\n val handles = {for (_ <- (1 to n)) yield {readLine split ' ' toList}} toArray\n val permutation = readLine split ' ' map(_.toInt - 1)\n// val inverse_permutation = Array.fill(n)(0)\n // for ((x, i) <- permutation.view.zipWithIndex) inverse_permutation(x) = i\n @tailrec def isContinued(i: Int, max: Int, currentHandle: String = handles(permutation.head) min): String = {\n if (i == max) \"YES\"\n else ((currentHandle :: handles(i)) sorted) match {\n case List(x, r, _) if x == currentHandle => isContinued(i + 1, max, r)\n case List(_, x, r) if x == currentHandle => isContinued(i + 1, max, r)\n case _ => \"NO\"\n }\n }\n println(isContinued(1, n))\n// println(inverse_permutation map(_.toString) reduceLeft(_ + ' ' + _))\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\nobject TaskA {\n def main(args: Array[String]) {\n val n = readInt\n val handles = {for (_ <- (1 to n)) yield {readLine split ' ' toList}} toArray\n val permutation = readLine split ' ' map(_.toInt - 1)\n val inverse_permutation = Array.fill(n)(0)\n for ((x, i) <- permutation.view.zipWithIndex) inverse_permutation(x) = i\n @tailrec def isContinued(i: Int, max: Int, currentHandle: String = handles(inverse_permutation.head) min): String = {\n if (i == max) \"YES\"\n else ((currentHandle :: handles(i)) sorted) match {\n case List(x, r, _) if x == currentHandle => isContinued(i + 1, max, r)\n case List(_, x, r) if x == currentHandle => isContinued(i + 1, max, r)\n case _ => \"NO\"\n }\n }\n println(isContinued(1, n))\n// println(inverse_permutation map(_.toString) reduceLeft(_ + ' ' + _))\n }\n}"}], "src_uid": "a48ef749bf54d673772e09025ae806de"} {"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n val dp=new Array[Long](n+1)\n val mc2=new Array[Int](2)\n\n val ansList=\n (1 to q).map{ii=>\n val (a:Long,b:Long)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n }\n\n loop(n){dp(_)=Long.MinValue/2}\n\n mc2(0)=n;mc2(1)=n\n\n loop(n){i=>\n dp(c(i))=\n Math.max(Math.max(dp(c(i)),dp(c(i))+v(i)*a),dp(\n if(mc2(0)!=c(i)) mc2(0) else mc2(1)\n )+v(i)*b)\n\n //sort\n var tmp=c(i)\n if(dp(c(i))>dp(mc2(1))){\n mc2(1)^=tmp\n tmp^=mc2(1)\n mc2(1)^=tmp\n }\n if(dp(mc2(1))>dp(mc2(0))){\n mc2(0)^=mc2(1)\n mc2(1)^=mc2(0)\n mc2(0)^=mc2(1)\n }\n if(mc2(0)==mc2(1)){\n mc2(1)=tmp\n }\n }\n \n\n dp(mc2(0))\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n\n def loop(n:Int)(f:Int=>Unit){\n var i=0\n while(iUnit):Long={\n val now=System.currentTimeMillis\n f()\n System.currentTimeMillis-now\n }\n}\n", "positive_code": [{"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n val dp=new Array[Long](n+1)\n val mc2=new Array[Int](2)\n\n val ansList=\n (1 to q).map{ii=>\n val (a:Long,b:Long)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n }\n (0 to n-1).foreach{i=>dp(i)=Long.MinValue/2}\n dp(n)=0\n\n mc2(0)=n;mc2(1)=n\n\n (0 to n-1).foreach{i=>\n dp(c(i))=\n Math.max(Math.max(dp(c(i)),dp(c(i))+v(i)*a),dp(\n if(mc2(0)!=c(i)) mc2(0) else mc2(1)\n )+v(i)*b)\n\n //sort\n var tmp=c(i)\n if(dp(c(i))>dp(mc2(1))){\n mc2(1)^=tmp\n tmp^=mc2(1)\n mc2(1)^=tmp\n }\n if(dp(mc2(1))>dp(mc2(0))){\n mc2(0)^=mc2(1)\n mc2(1)^=mc2(0)\n mc2(0)^=mc2(1)\n }\n if(mc2(0)==mc2(1)){\n mc2(1)=tmp\n }\n }\n \n\n dp(mc2(0))\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n val dp=new Array[Long](n+1)\n val mc2=new Array[Int](2)\n\n val ansList=\n (1 to q).map{ii=>\n val (a:Long,b:Long)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n }\n {\n var i=0\n while(idp(mc2(1))){\n mc2(1)^=tmp\n tmp^=mc2(1)\n mc2(1)^=tmp\n }\n if(dp(mc2(1))>dp(mc2(0))){\n mc2(0)^=mc2(1)\n mc2(1)^=mc2(0)\n mc2(0)^=mc2(1)\n }\n if(mc2(0)==mc2(1)){\n mc2(1)=tmp\n }\n i+=1\n }\n \n\n dp(mc2(0))\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n\n def loop(n:Int)(f:Int=>Unit){\n var i=0\n while(iUnit):Long={\n val now=System.currentTimeMillis\n f()\n System.currentTimeMillis-now\n }\n}\n"}, {"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n val dp=new Array[Long](n+1)\n val mc2=new Array[Int](2)\n\n val ansList=\n (1 to q).map{ii=>\n val (a:Long,b:Long)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n }\n (0 to n-1).foreach{i=>dp(i)=Long.MinValue/2}\n dp(n)=0\n\n mc2(0)=n;mc2(1)=n\n\n (0 to n-1).foreach{i=>\n dp(c(i))=\n Math.max(Math.max(dp(c(i)),dp(c(i))+v(i)*a),dp(\n if(mc2(0)!=c(i)) mc2(0) else mc2(1)\n )+v(i)*b)\n\n //sort\n var tmp=c(i)\n if(dp(c(i))>dp(mc2(1))){\n mc2(1)^=tmp\n tmp^=mc2(1)\n mc2(1)^=tmp\n }\n if(dp(mc2(1))>dp(mc2(0))){\n mc2(0)^=mc2(1)\n mc2(1)^=mc2(0)\n mc2(0)^=mc2(1)\n }\n if(mc2(0)==mc2(1)){\n mc2(1)=tmp\n }\n }\n \n\n dp(mc2(0))\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n}\n"}], "negative_code": [{"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n\n val ansList=\n (1 to q).map{ii=>\n val (a:Long,b:Long)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n }\n val dp= new Array[Long](n+1).map(i=>Long.MinValue/2)\n\n val maxc0=\n (0 to n-1).foldLeft(List[Int](n)){(maxc2,i)=>\n dp(c(i))=\n dp(c(i)) max (v(i)*b) max maxc2.map{cm=>\n if(cm==c(i)){\n dp(cm)+v(i)*a\n }else{\n dp(cm)+v(i)*b\n }\n }.max\n\n (c(i)::maxc2).distinct.sortWith{(c1,c2)=>\n dp(c1)>dp(c2)\n }.take(2)//->foldLeft\n }.head//->maxc0\n\n dp(maxc0)//->map\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n val dp=new Array[Long](n+1)\n\n val ansList=\n (1 to q).map{ii=>\n val (a:Long,b:Long)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n };\n (0 to n-1).foreach(dp(_)=Long.MinValue/2)\n dp(n)=0\n\n val maxc=Array(n,n);\n (0 to n-1).foreach{i=>\n dp(c(i))=\n dp(c(i)) max dp(c(i))+v(i)*a max dp(\n if(c(i)==maxc(0)) maxc(1) else maxc(0)\n )+v(i)*b\n\n if(c(i)!=maxc(0)||c(i)!=maxc(1)){\n if(dp(c(i))>dp(maxc(0))){\n maxc(1)=maxc(0)\n maxc(0)=c(i)\n }else if(dp(c(i))>dp(maxc(1))){\n maxc(1)=c(i)\n }\n }else{\n if(dp(maxc(1))>dp(maxc(0))){\n maxc(0)^=maxc(1)\n maxc(1)^=maxc(0)\n }\n }\n }\n dp(maxc(0))\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n\n val ansList=\n (1 to q).map{ii=>\n val (a,b)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n }\n val dp= new Array[Long](n+1)\n\n val maxc0=\n (0 to n-1).foldLeft(List[Int](n)){(maxc2,i)=>\n dp(c(i))=\n dp(c(i)) max (v(i)*b) max maxc2.map{cm=>\n if(cm==c(i)){\n dp(cm)+v(i)*a\n }else{\n dp(cm)+v(i)*b\n }\n }.max\n\n (c(i)::maxc2).distinct.sortWith{(c1,c2)=>\n dp(c1)>dp(c2)\n }.take(2)//->foldLeft\n }.head//->maxc0\n\n dp(maxc0)//->map\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n val dp=new Array[Long](n+1)\n val mc2=new Array[Int](2)\n\n val ansList=\n (1 to q).map{ii=>\n val (a:Long,b:Long)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n }\n dp.map(i=>Long.MinValue/2)\n dp(n)=0\n\n mc2(0)=n;mc2(1)=n\n\n 0 to n-1 foreach{i=>\n dp(c(i))=\n Math.max(Math.max(dp(c(i)),dp(c(i))+v(i)*a),dp(\n if(mc2(0)!=c(i)) mc2(0) else mc2(1)\n )+v(i)*b)\n\n //sort\n var tmp=c(i)\n if(dp(c(i))>dp(mc2(1))){\n mc2(1)^=tmp\n tmp^=mc2(1)\n mc2(1)^=tmp\n }\n if(dp(mc2(1))>dp(mc2(0))){\n mc2(0)^=mc2(1)\n mc2(1)^=mc2(0)\n mc2(0)^=mc2(1)\n }\n if(mc2(0)==mc2(1)){\n mc2(1)=tmp\n }\n }\n \n\n dp(mc2(0))\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n\n val ansList=\n (1 to q).map{ii=>\n val (a:Long,b:Long)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n }\n val dp= new Array[Long](n+1).map(i=>Long.MinValue/2)\n dp(n)=0\n\n val maxc0=\n (0 to n-1).foldLeft(List[Int](n)){(maxc2,i)=>\n dp(c(i))=\n dp(c(i)) max (v(i)*b) max maxc2.map{cm=>\n if(cm==c(i)){\n dp(cm)+v(i)*a\n }else{\n dp(cm)+v(i)*b\n }\n }.max\n\n (c(i)::maxc2).distinct.sortWith{(c1,c2)=>\n dp(c1)>dp(c2)\n }.take(2)//->foldLeft\n }.head//->maxc0\n\n dp(maxc0)//->map\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n val dp=new Array[Long](n+1)\n\n val ansList=\n (1 to q).map{ii=>\n val (a:Long,b:Long)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n };\n (0 to n-1).foreach(dp(_)=Long.MinValue/2)\n dp(n)=0\n\n val maxc=Array(n,n);\n (0 to n-1).foreach{i=>\n dp(c(i))=\n dp(c(i)) max dp(c(i))+v(i)*a max dp(\n if(c(i)==maxc(0)) maxc(1) else maxc(0)\n )+v(i)*b\n\n if(c(i)!=maxc(0)||c(i)!=maxc(1)){\n if(dp(c(i))>dp(maxc(0))){\n maxc(1)=maxc(0)\n maxc(0)=c(i)\n }else if(dp(c(i))>dp(maxc(1))){\n maxc(1)=c(i)\n }\n }else{\n if(dp(maxc(1))>dp(maxc(0))){\n maxc(0)^=maxc(1)\n maxc(1)^=maxc(0)\n maxc(0)^=maxc(1)\n }\n }\n }\n dp(maxc(0))\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n val dp=new Array[Long](n+1)\n\n val ansList=\n (1 to q).map{ii=>\n val (a:Long,b:Long)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n }\n (0 to n-1).foreach(dp(_)=Long.MinValue/2)\n dp(n)=0\n\n val maxc2=Array[Int](n,n)\n \n (0 to n-1).foreach{i=>\n dp(c(i))=\n dp(c(i)) max dp(c(i))+v(i)*a max dp(\n maxc2.find(_!=c(i)).get\n )+v(i)*b\n\n val tmp=Array(c(i),maxc2(0),maxc2(1))\n tmp.sortWith{(c1,c2)=>dp(c1)>dp(c2)}\n maxc2(0)=tmp(0)\n maxc2(1)=tmp.find(_!=maxc2(0)).get\n }\n\n dp(maxc2(0))\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toInt)\n val c=readLine.split(\" \").map(_.toInt -1)\n\n val ansList=\n (1 to q).map{ii=>\n val (a,b)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n val dp= new Array[Long](n+1)\n\n val maxc0=\n (0 to n-1).foldLeft(List[Int](n)){(maxc2,i)=>\n dp(c(i))=\n dp(c(i)) max (v(i)*b) max maxc2.map{cm=>\n if(cm==c(i)){\n dp(cm)+v(i)*a\n }else{\n dp(cm)+v(i)*b\n }\n }.max\n\n (c(i)::maxc2).distinct.sortWith{(c1,c2)=>\n dp(c1)>dp(c2)\n }.take(2)//->foldLeft\n }.head//->maxc0\n\n dp(maxc0)//->map\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n\n val ansList=\n (1 to q).map{ii=>\n val (a:Long,b:Long)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n }\n val dp= new Array[Long](n+1).map(i=>Long.MinValue/2)\n dp(n)=0\n\n val maxc0=\n (0 to n-1).foldLeft(List[Int](n)){(maxc2,i)=>\n dp(c(i))=\n dp(c(i)) max maxc2.map{cm=>\n if(cm==c(i)){\n dp(cm)+v(i)*a\n }else{\n dp(cm)+v(i)*b\n }\n }.max\n\n (c(i)::maxc2).distinct.sortWith{(c1,c2)=>\n dp(c1)>dp(c2)\n }.take(2)//->foldLeft\n }.head//->maxc0\n\n dp.max\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n val dp=new Array[Long](n+1)\n\n val ansList=\n (1 to q).map{ii=>\n val (a:Long,b:Long)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n }\n (0 to n-1).foreach(dp(_)=Long.MinValue/2)\n dp(n)=0\n\n val maxc=Array(n,n);\n (0 to n-1).foreach{i=>\n dp(c(i))=\n dp(c(i)) max dp(c(i))+v(i)*a max dp(\n if(c(i)==maxc(0)) maxc(1) else maxc(0)\n )+v(i)*b\n\n if(c(i)!=maxc(0)||c(i)!=maxc(1)){\n if(dp(c(i))>dp(maxc(0))){\n maxc(1)=maxc(0)\n maxc(0)=c(i)\n }else if(dp(c(i))>dp(maxc(1))){\n maxc(1)=c(i)\n }\n }\n }\n dp(maxc(0))\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n val dp=new Array[Long](n+1)\n val mc2=new Array[Int](2)\n\n val ansList=\n (1 to q).map{ii=>\n val (a:Long,b:Long)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n }\n (0 to n-1).foreach(dp(_)=Long.MinValue/2)\n dp(n)=0\n\n mc2(0)=n;mc2(1)=n\n \n (0 to n-1).foreach{i=>\n dp(c(i))=\n dp(c(i)) max dp(c(i))+v(i)*a max dp(\n try{\n mc2.find(_!=c(i)).get\n }catch{\n case(e:Exception) =>\n println(mc2(0)+\",\"+mc2(1)+\",\"+c(i)+\",\"+i)\n 0\n }\n \n )+v(i)*b\n\n //sort\n var tmp=c(i)\n if(dp(c(i))>dp(mc2(1))){\n mc2(1)^=tmp\n tmp^=mc2(1)\n mc2(1)^=tmp\n }\n if(dp(mc2(1))>dp(mc2(0))){\n mc2(0)^=mc2(1)\n mc2(1)^=mc2(0)\n mc2(0)^=mc2(1)\n }\n if(mc2(0)==mc2(1)){\n mc2(1)=c(i)\n }\n\n \n }\n\n dp(mc2(0))\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n\n val ansList=\n (1 to q).map{ii=>\n val (a:Long,b:Long)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n }\n val dp= new Array[Long](n+1).map(i=>Long.MinValue/2)\n dp(n)=0\n\n val maxc0=\n (0 to n-1).foldLeft(List[Int](n)){(maxc2,i)=>\n dp(c(i))=\n dp(c(i)) max (v(i)*b) max maxc2.map{cm=>\n if(cm==c(i)){\n dp(cm)+v(i)*a\n }else{\n dp(cm)+v(i)*b\n }\n }.max\n\n (c(i)::maxc2).distinct.sortWith{(c1,c2)=>\n dp(c1)>dp(c2)\n }.take(2)//->foldLeft\n }.head//->maxc0\n\n dp.max\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n val dp=new Array[Long](n+1)\n\n val ansList=\n (1 to q).map{ii=>\n val (a:Long,b:Long)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n };\n (0 to n-1).foreach(dp(_)=Long.MinValue/2)\n dp(n)=0\n\n val maxc=Array(n,n);\n (0 to n-1).foreach{i=>\n dp(c(i))=\n dp(c(i)) max dp(c(i))+v(i)*a max dp(\n if(c(i)==maxc(0)) maxc(1) else maxc(0)\n )+v(i)*b\n\n if(c(i)!=maxc(0)||c(i)!=maxc(1)){\n if(dp(c(i))>dp(maxc(0))){\n maxc(1)=maxc(0)\n maxc(0)=c(i)\n }else if(dp(c(i))>dp(maxc(1))){\n maxc(1)=c(i)\n }else if(maxc(0)==maxc(1)){\n maxc(1)=c(i)\n }\n }else{\n if(dp(maxc(1))>dp(maxc(0))){\n maxc(0)^=maxc(1)\n maxc(1)^=maxc(0)\n maxc(0)^=maxc(1)\n }\n }\n }\n dp(maxc(0))\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n}\n"}, {"source_code": "object C{\n def main(args:Array[String]){\n\n val (n,q)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val v=readLine.split(\" \").map(_.toLong)\n val c=readLine.split(\" \").map(_.toInt -1)\n val dp=new Array[Long](n+1)\n\n val ansList=\n (1 to q).map{ii=>\n val (a:Long,b:Long)={\n val sp=readLine.split(\" \")\n (sp(0).toLong,sp(1).toLong)\n }\n (0 to n-1).foreach(dp(_)=Long.MinValue/2)\n dp(n)=0\n\n val maxc2=Array[Int](n,n)\n \n (0 to n-1).foreach{i=>\n dp(c(i))=\n dp(c(i)) max dp(c(i))+v(i)*a max dp(\n maxc2.find(_!=c(i)).get\n )+v(i)*b\n\n val tmp=Array(c(i),maxc2(0),maxc2(1)).sortWith{(c1,c2)=>dp(c1)>dp(c2)}\n maxc2(0)=tmp(0)\n maxc2(1)=tmp.find(_!=maxc2(0)).get\n\n println(maxc2.mkString(\",\"))\n }\n\n dp(maxc2(0))\n }//->ansList\n\n println(ansList.mkString(\"\\n\"))\n }\n}\n"}], "src_uid": "89186dda71810a4555990408fe606f9a"} {"source_code": "object qa {\r\n def main(args: Array[String]) {\r\n val n = scala.io.StdIn.readInt()\r\n for (_ <- 0 until n) {\r\n val i = scala.io.StdIn.readInt()\r\n val str = {\r\n if (i >= 1900) \"Division 1\"\r\n else if (i >= 1600) \"Division 2\"\r\n else if (i >= 1400) \"Division 3\"\r\n else \"Division 4\"\r\n }\r\n println(str)\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.io.StdIn\r\n\r\n/**\r\n * На Codeforces пользователи разделены на 4 дивизиона по их рейтингу:\r\n *\r\n * Для 1-го дивизиона: 1900≤rating\r\n * Для 2-го ивизиона: 1600≤rating≤1899\r\n * Для 3-го дивизиона: 1400≤rating≤1599\r\n * Для 4-го дивизиона: rating≤1399\r\n * Учитывая rating, выведите, к какому дивизиону относится rating.\r\n *\r\n * Входные данные\r\n * Первая строка ввода содержит целое число 𝑡 (1≤𝑡≤104) — количество наборов входных данных в тесте.\r\n *\r\n * Описание каждого набора состоит из одной строки, содержащей одно целое число rating (−5000≤rating≤5000).\r\n *\r\n * Выходные данные\r\n * Для каждого набора входных данных выведите единственную строку, содержащую дивизион в формате «Division X», где 𝑋 — целое число от 1 до 4, представляющее дивизион для соответствующего рейтинга.\r\n */\r\n\r\nobject Task1 extends App {\r\n def getNextNum: Int = StdIn.readLine().toInt\r\n\r\n val inputSize = getNextNum\r\n\r\n for (_ <- 0 until inputSize) {\r\n val rating = getNextNum\r\n\r\n if (rating <= 1399) {\r\n println(\"Division 4\")\r\n } else {\r\n if (rating <= 1599) {\r\n println(\"Division 3\")\r\n } else {\r\n if (rating <= 1899) {\r\n println(\"Division 2\")\r\n } else {\r\n println(\"Division 1\")\r\n }\r\n }\r\n }\r\n }\r\n\r\n}\r\n"}, {"source_code": "import scala.io.StdIn.readLine\r\n\r\nobject Solution {\r\n\r\n def rsi() = readLine().split(\"\\\\s+\").map(_.toInt)\r\n // ======================================\r\n\r\n def solve(n: Int) = {\r\n \"Division \" + (n match {\r\n case i if (i >= 1900) => 1\r\n case i if (i >= 1600) => 2\r\n case i if (i >= 1400) => 3\r\n case i => 4\r\n })\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val cases = readLine.toInt\r\n\r\n for (\r\n i <- 0 until cases;\r\n n = readLine().toInt\r\n ) println(solve(n))\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "020c7b64688736ecc5e97d17df2c2605"} {"source_code": "//package codeforces.contest1197\n\n/*\nlen means the mutiple of m u r checking backwards from your current position as u need to check only multiples of m for the correct answer from any given position\n\n */\nobject YetAnotherSubarrayProblem {\n\n type Index = Int\n\n def main(args: Array[String]): Unit = {\n val Array(n, m, k) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val elements = io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val prefixSum = elements.scanLeft(0l)(_ + _).tail\n\n def sum(l: Int, r: Int): Long = prefixSum(r) - (if (l > 0) prefixSum(l - 1) else 0)\n\n val best = new Array[Long](n)\n\n val result = (0 until n).foldLeft(0l) { case (res, i) =>\n best(i) = (sum(i - m + 1, i) - k + (if (i - m >= 0) best(i - m) else 0)) max 0\n val maxAhead = (1 to m).filter(_ + i < n).foldLeft(res) { (newRes, j) =>\n newRes max (best(i) + sum(i + 1, i + j) - k)\n }\n res max best(i) max maxAhead\n }\n\n println(result)\n\n\n }\n\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import scala.reflect.ClassTag\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, M, K = ni()\n val A = na(N)\n val C = cumSum(A)\n\n debug(C)\n val zero = -1e18.toLong\n\n var ans = 0L\n val tree = new BIT(N, zero)(max)\n REP(M) { ms =>\n REP(M) { mt =>\n debug(s\"ms:$ms mt:$mt\")\n tree.clear()\n\n var i = 0\n while(i * M + mt < N) {\n val t = i * M + mt\n val v = C(t + 1) - (i+1).toLong * K\n tree.add(N - 1 - t, v)\n debug(s\"updateTree(${N - 1 - t}, $v)\")\n i += 1\n }\n i = 0\n var t = mt\n var s = ms\n while(s < N) {\n while(t < s && t + M < N) {\n t += M\n }\n debug(s\"s:$s t:$t\")\n if (s <= t) {\n DEBUG(\n REP(N) { i =>\n debug(s\"tree.sum(${i+1}):${tree.sum(i + 1)}\")\n }\n )\n debug(s\"tree:${tree.bit.mkString(\" \")}\")\n val lst = tree.sum(N - t)\n if (lst != zero) {\n val add = if (ms > mt) K else 0\n val v = lst - C(s) + i.toLong * K + add\n debug(s\"lst:$lst add:$add v:$v\")\n ans = max(ans, v)\n }\n }\n s += M\n i += 1\n }\n }\n }\n\n out.println(ans)\n }\n\n class BIT(n: Int, zero: Long)(f: (Long, Long) => Long) {\n def this(n: Int) = this(n, 0)(_ + _)\n\n private val N = {\n val a = Integer.highestOneBit(n)\n if (a == n) a else a << 1\n }\n val bit = if (zero != 0) Array.fill[Long](N + 1)(zero) else Array.ofDim[Long](N + 1)\n\n def clear(): Unit = {\n java.util.Arrays.fill(bit, zero)\n }\n\n /**\n * 1 index\n * addとindex違うよ\n * cumsumなんかといっしょ\n */\n def sum(i: Int): Long = {\n assert(i <= n)\n var x = i\n var s: Long = zero\n while(x > 0) {\n s = f(s, bit(x))\n x -= x & -x\n }\n s\n }\n\n /**\n * 0 index\n */\n def add(i: Int, a: Long): Unit = {\n assert(i < n)\n var x = i + 1\n while(x <= N) {\n bit(x) = f(bit(x), a)\n x += x & -x\n }\n }\n\n def sumAll: Long = sum(n)\n\n /**\n * [l, r)\n */\n def query(l: Int, r: Int)(sub: (Long, Long) => Long): Long = {\n assert(r > l)\n sub(sum(r), sum(l))\n }\n\n def lowerBound(W: Long)(sub: (Long, Long) => Long, lt: (Long, Long) => Boolean): Int = {\n var k = N\n var x = 0\n var w = W\n while(k > 0) {\n if (x + k <= N && lt(bit(x + k), w)) {\n w = sub(w, bit(x + k))\n x += k\n }\n k /= 2\n }\n x\n }\n }\n\n class SegmentTree(n: Int, zero: Long)(f: (Long, Long) => Long) {\n private val N = {\n val a = Integer.highestOneBit(n)\n if (a == n) a else a << 1\n }\n private val dat: Array[Long] = if (zero != 0){\n Array.fill(2 * N)(zero)\n } else {\n Array.ofDim(2 * N)\n }\n\n def update(i: Int, a: Long): Unit = {\n assert(i < n)\n var ix = i + N\n dat(ix) = a\n while(ix > 1) {\n dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))\n ix >>= 1\n }\n }\n\n /**\n * [a, b)\n */\n def query(a: Int, b: Int): Long = {\n assert(a < n && b <= n)\n\n var res: Long = zero\n var left = a + N\n var right = b - 1 + N\n\n while(left <= right) {\n if ((left & 1) == 1) res = f(res, dat(left))\n if ((right & 1) == 0) res = f(res, dat(right))\n left = (left + 1) >> 1 // 右の子供なら右の親に移動\n right = (right - 1) >> 1 // 左の子供なら左の親に移動\n }\n\n res\n }\n\n def clear(): Unit = {\n java.util.Arrays.fill(dat, zero)\n }\n }\n}"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import scala.reflect.ClassTag\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, M, K = ni()\n val A = na(N)\n val C = cumSum(A)\n\n debug(C)\n val zero = -1e18.toLong - 10\n\n var ans = 0L\n val tree = new SegmentTree(N, zero)(max)\n REP(M) { ms =>\n REP(M) { mt =>\n debug(s\"ms:$ms mt:$mt\")\n tree.clear()\n\n var i = 0\n while(i * M + mt < N) {\n val t = i * M + mt\n val v = C(t + 1) - (i+1).toLong * K\n tree.update(t, v)\n debug(s\"updateTree($t, $v)\")\n i += 1\n }\n i = 0\n var t = mt\n var s = ms\n while(s < N) {\n while(t < s && t < N) {\n tree.update(t, zero)\n t += M\n }\n debug(s\"s:$s t:$t\")\n val lst = tree.query(0, N)\n if (lst != zero) {\n val add = if (ms > mt) K else 0\n val v = lst - C(s) + i.toLong * K + add\n debug(s\"lst:$lst add:$add v:$v\")\n ans = max(ans, v)\n }\n s += M\n i += 1\n }\n }\n }\n\n out.println(ans)\n }\n\n\n class SegmentTree(n: Int, zero: Long)(f: (Long, Long) => Long) {\n private val N = {\n val a = Integer.highestOneBit(n)\n if (a == n) a else a << 1\n }\n private val dat: Array[Long] = if (zero != 0){\n Array.fill(2 * N)(zero)\n } else {\n Array.ofDim(2 * N)\n }\n\n def update(i: Int, a: Long): Unit = {\n assert(i < n)\n var ix = i + N\n dat(ix) = a\n while(ix > 1) {\n dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))\n ix >>= 1\n }\n }\n\n /**\n * [a, b)\n */\n def query(a: Int, b: Int): Long = {\n assert(a < n && b <= n)\n\n var res: Long = zero\n var left = a + N\n var right = b - 1 + N\n\n while(left <= right) {\n if ((left & 1) == 1) res = f(res, dat(left))\n if ((right & 1) == 0) res = f(res, dat(right))\n left = (left + 1) >> 1 // 右の子供なら右の親に移動\n right = (right - 1) >> 1 // 左の子供なら左の親に移動\n }\n\n res\n }\n\n def clear(): Unit = {\n java.util.Arrays.fill(dat, zero)\n }\n }\n}"}], "negative_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import scala.reflect.ClassTag\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, M, K = ni()\n val A = na(N)\n val C = cumSum(A)\n\n debug(C)\n val zero = -1e9.toLong - 10\n\n var ans = 0L\n REP(M) { ms =>\n REP(M) { mt =>\n debug(s\"ms:$ms mt:$mt\")\n val tree = new SegmentTree(N, zero)(max)\n\n var i = 0\n while(i * M + mt < N) {\n val t = i * M + mt\n val v = C(t + 1) - (i+1).toLong * K\n tree.update(t, v)\n debug(s\"updateTree($t, $v)\")\n i += 1\n }\n i = 0\n var t = mt\n var s = ms\n while(s < N) {\n while(t < s && t < N) {\n tree.update(t, zero)\n t += M\n }\n debug(s\"s:$s t:$t\")\n val lst = tree.query(0, N)\n if (lst != zero) {\n val add = if (ms > mt) K else 0\n val v = lst - C(s) + i.toLong * K + add\n debug(s\"v:$v\")\n ans = max(ans, v)\n }\n s += M\n i += 1\n }\n }\n }\n\n out.println(ans)\n }\n\n\n class SegmentTree(n: Int, zero: Long)(f: (Long, Long) => Long) {\n private val N = {\n val a = Integer.highestOneBit(n)\n if (a == n) a else a << 1\n }\n private val dat: Array[Long] = if (zero != 0){\n Array.fill(2 * N)(zero)\n } else {\n Array.ofDim(2 * N)\n }\n\n def update(i: Int, a: Long): Unit = {\n assert(i < n)\n var ix = i + N\n dat(ix) = a\n while(ix > 1) {\n dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))\n ix >>= 1\n }\n }\n\n /**\n * [a, b)\n */\n def query(a: Int, b: Int): Long = {\n assert(a < n && b <= n)\n\n var res: Long = zero\n var left = a + N\n var right = b - 1 + N\n\n while(left <= right) {\n if ((left & 1) == 1) res = f(res, dat(left))\n if ((right & 1) == 0) res = f(res, dat(right))\n left = (left + 1) >> 1 // 右の子供なら右の親に移動\n right = (right - 1) >> 1 // 左の子供なら左の親に移動\n }\n\n res\n }\n }\n}"}], "src_uid": "529aed80a647d181f08d2c26bb14d65d"} {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val n = readInt()\n val first = readLine().split(\" \").map(_.toInt)\n val second = readLine().split(\" \").map(_.toInt)\n val cross = readLine().split(\" \").map(_.toInt)\n\n var offset = 0\n val answer = Array.ofDim[Int](n)\n for (curr <- n - 1 to 0 by -1) {\n var ifGoUp = offset + cross(curr) + first.take(curr).sum\n answer(curr) = ifGoUp\n if (curr > 0) offset += second(curr - 1)\n }\n\n println(answer.sorted.take(2).sum)\n\n}\n\n/*\n4\n1 2 3\n3 2 1\n3 2 2 3\n */", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val a1 = in.next().split(\" \").map(_.toInt)\n val a2 = in.next().split(\" \").map(_.toInt).reverse\n val b = in.next().split(\" \").map(_.toInt)\n val a1sum = a1.scan(0){_ + _}\n val a2sum = a2.scan(0){_ + _}.reverse\n val path = a1sum.zip(a2sum)\n val res = path.indices.map(i => a1sum(i) + a2sum(i) + b(i)).sorted.take(2).sum\n\n println(res)\n}"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _586B extends CodeForcesApp[Int]({scanner => import scanner._\n val n = nextInt\n val r1 = IndexedSeq.fill(n-1)(nextInt)\n val r2 = IndexedSeq.fill(n-1)(nextInt)\n val c = IndexedSeq.fill(n)(nextInt)\n\n val choices = c.zipWithIndex map {case (x, i) =>\n val (s1, s2) = (r1.take(i), r2.takeRight(n - i - 1))\n x + s1.sum + s2.sum\n }\n\n choices.sorted.take(2).sum\n}) {\n override def format(result: Result) = super.format(result)\n}\n/********************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n @inline final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)\n @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n"}, {"source_code": "\nimport java.io._\n\nobject B_LaurentyAndShop {\n \n def main(args: Array[String]): Unit = {\n \n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n val number = br.readLine().trim().toInt\n val row1Str = br.readLine().trim().split(\" \")\n val row2Str = br.readLine().trim().split(\" \")\n val aveStr = br.readLine().trim().split(\" \")\n \n// val number = 4\n// val row1Str = \"1 2 3\".split(\" \")\n// val row2Str = \"3 2 1\".split(\" \")\n// val aveStr = \"3 2 2 3\".split(\" \")\n \n// val number = 3\n// val row1Str = \"1 2\".split(\" \")\n// val row2Str = \"3 3\".split(\" \")\n// val aveStr = \"2 1 3\".split(\" \")\n \n// val number = 2\n// val row1Str = \"1\".split(\" \")\n// val row2Str = \"1\".split(\" \")\n// val aveStr = \"1 1\".split(\" \")\n \n val row1 = row1Str.map { x=>Integer.parseInt(x)}\n val row2 = row2Str.map { _.toInt}\n val ave = aveStr.map { _.toInt}\n \n var row1Sum = 0;\n var row2Sum = 0;\n row2.foreach { x => row2Sum += x }\n //foldLeft(0)((x:Int,y:Int)=> x+y)\n \n val solutions = Array.fill(number){0}\n for (i <- 0 until number) {\n solutions(i) = row1Sum + ave(i) + row2Sum\n if (i + 1 <= row1.length) {\n row1Sum += row1(i)\n row2Sum -= row2(i)\n }\n }\n \n scala.util.Sorting.quickSort(solutions)\n var sum = 0;\n if (solutions.length > 0) {\n sum += solutions(0)\n }\n if (solutions.length > 1) {\n sum += solutions(1)\n }\n println(sum)\n \n }\n}"}], "negative_code": [], "src_uid": "e3e0625914fdc08950601248b1278f7d"} {"source_code": "object B extends App {\n case class Savings(x: Int, as: List[Int])\n\n val t = scala.io.StdIn.readInt()\n\n private def wealthy(s: Savings): Int = {\n val Savings(x, as) = s\n\n val (ps, rs) = as.sorted.span(_ < x)\n val rl = rs.length\n\n val overage: Long = rs.foldLeft(0L)(_ + _ - x)\n\n val pl = ps.reverse\n .foldLeft((overage, 0)) {\n case ((overage, count), a) =>\n if (overage < x - a) (overage, count)\n else (overage - x + a, count + 1)\n }\n ._2\n\n rl + pl\n }\n\n val input = (0 until t)\n .foldLeft(List.empty[Savings]) { (acc, _) =>\n val Array(n, x) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val as = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n Savings(x, as) :: acc\n }\n .reverse\n\n val output = input.map(wealthy)\n\n println(output.mkString(\"\\n\"))\n}", "positive_code": [{"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val totalCases = in.nextInt()\n (1 to totalCases).foreach{ _ =>\n val n = in.nextInt()\n val x = in.nextLong()\n val a = (1 to n).map(_ => in.nextLong()).sorted.reverse.toArray\n var ans = 0\n var cumSum = 0L\n a.indices.foreach{ i =>\n val newSum = cumSum + a(i)\n if(newSum >= x*(i+1)){\n ans = i+1\n }\n cumSum = newSum\n }\n out.println(ans)\n\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "negative_code": [{"source_code": "object B extends App {\n case class Savings(x: Int, as: List[Int])\n\n val t = scala.io.StdIn.readInt()\n\n private def wealthy(s: Savings): Int = {\n val Savings(x, as) = s\n\n val (ps, rs) = as.sorted.span(_ <= x)\n val rl = rs.length\n\n val overage = rs.foldLeft(0L)(_ + _ - x)\n\n val pl = ps\n .foldLeft(List.empty[Int]) {\n case (acc, a) =>\n val deficit = acc.foldLeft((x - a).toLong)(_ + x - _)\n\n if (overage - deficit >= 0) a :: acc\n else acc\n\n }\n .length\n\n rl + pl\n }\n\n val input = (0 until t)\n .foldLeft(List.empty[Savings]) { (acc, _) =>\n val Array(n, x) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val as = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n Savings(x, as) :: acc\n }\n .reverse\n\n val output = input.map(wealthy)\n\n println(output.mkString(\"\\n\"))\n}"}], "src_uid": "51f922bb2c51f50b5c3b55725dd7766e"} {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(r, c) = readInts(2)\n\n val isFree = Array.fill(r)(new mutable.BitSet(c))\n val breeders = Array.fill(r, c)(0)\n\n var start = (0, 0)\n var exit = (0, 0)\n\n for (i <- 0 until r) {\n val s = readString\n for (j <- 0 until c) {\n val ch = s(j)\n if (ch != 'T') {\n isFree(i) += j\n if (ch >= '0' && ch <= '9') breeders(i)(j) = ch - '0'\n else if (ch == 'S') start = (i, j)\n else if (ch == 'E') exit = (i, j)\n }\n }\n }\n\n val toVisit = mutable.Queue(exit)\n isFree(exit._1)(exit._2) = false\n val dists = Array.fill(r, c)(Int.MaxValue)\n\n val dis = Array(-1, 1, 0, 0)\n\n while (!toVisit.isEmpty) { // BFS\n val (i, j) = toVisit.dequeue\n val nextDist = dists(i)(j) + 1\n var m = 0\n while (m < 4) {\n val ni = i + dis(m)\n if (ni >= 0 && ni < r) {\n val nj = j + dis(3 - m)\n if (isFree(ni)(nj)) {\n toVisit += ((ni, nj))\n isFree(ni)(nj) = false\n dists(ni)(nj) = nextDist\n }\n }\n m += 1\n }\n }\n\n val limit = dists(start._1)(start._2)\n var sum = 0\n\n for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit) sum += breeders(i)(j)\n\n println(sum)\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(r, c) = readInts(2)\n\n val isFree = Array.fill(r)(new mutable.BitSet(c))\n val breeders = Array.fill(r, c)(0)\n\n var start = (0, 0)\n var exit = (0, 0)\n\n for (i <- 0 until r) {\n val s = readString\n for (j <- 0 until c) {\n val ch = s(j)\n if (ch != 'T') {\n isFree(i) += j\n if (ch >= '0' && ch <= '9') breeders(i)(j) = ch - '0'\n else if (ch == 'S') start = (i, j)\n else if (ch == 'E') exit = (i, j)\n }\n }\n }\n\n val toVisit = mutable.Queue(exit)\n isFree(exit._1)(exit._2) = false\n val dists = Array.fill(r, c)(Int.MaxValue)\n\n val dis = Array(-1, 1, 0, 0)\n val djs = Array(0, 0, -1, 1)\n\n while (!toVisit.isEmpty) { // BFS\n val (i, j) = toVisit.dequeue\n val nextDist = dists(i)(j) + 1\n var m = 0\n while (m < 4) {\n val ni = i + dis(m)\n if (isFree.isDefinedAt(ni)) {\n val nj = j + djs(m)\n if (isFree(ni)(nj)) {\n toVisit += ((ni, nj))\n isFree(ni)(nj) = false\n dists(ni)(nj) = nextDist\n }\n }\n m += 1\n }\n }\n\n val limit = dists(start._1)(start._2)\n var sum = 0\n\n for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit) sum += breeders(i)(j)\n\n println(sum)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(r, c) = readInts(2)\n\n val isFree = Array.fill(r)(new mutable.BitSet(c))\n val breeders = Array.fill[Byte](r, c)(0)\n\n var start = (0, 0)\n var exit = (0, 0)\n\n for (i <- 0 until r) {\n val s = readString\n for (j <- 0 until c) {\n val ch = s(j)\n if (ch != 'T') {\n isFree(i) += j\n if (ch >= '0' && ch <= '9') breeders(i)(j) = (ch - '0').toByte\n else if (ch == 'S') start = (i, j)\n else if (ch == 'E') exit = (i, j)\n }\n }\n }\n\n val toVisit = mutable.Queue(exit)\n isFree(exit._1)(exit._2) = false\n val dists = Array.fill(r, c)(Int.MaxValue)\n\n val dis = Array(-1, 1, 0, 0)\n\n while (!toVisit.isEmpty) { // BFS\n val (i, j) = toVisit.dequeue\n val nextDist = dists(i)(j) + 1\n var m = 0\n while (m < 4) {\n val ni = i + dis(m)\n if (ni >= 0 && ni < r) {\n val nj = j + dis(3 - m)\n if (isFree(ni)(nj)) {\n toVisit += ((ni, nj))\n isFree(ni)(nj) = false\n dists(ni)(nj) = nextDist\n }\n }\n m += 1\n }\n }\n\n val limit = dists(start._1)(start._2)\n var sum = 0\n\n for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit) sum += breeders(i)(j)\n\n println(sum)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(r, c) = readInts(2)\n\n val isFree = Array.fill(r)(new mutable.BitSet(c))\n val s = Array.ofDim[String](r)\n\n var start = (0, 0)\n var exit = (0, 0)\n\n for (i <- 0 until r) {\n s(i) = readString\n for (j <- 0 until c) {\n val ch = s(i)(j)\n if (ch != 'T') {\n isFree(i) += j\n if (ch == 'S') start = (i, j)\n else if (ch == 'E') exit = (i, j)\n }\n }\n }\n\n val toVisit = mutable.Queue(exit)\n isFree(exit._1)(exit._2) = false\n val dists = Array.fill(r, c)(Int.MaxValue)\n dists(exit._1)(exit._2) = 0\n\n val dis = Array(-1, 1, 0, 0)\n\n while (!toVisit.isEmpty) { // BFS\n val (i, j) = toVisit.dequeue\n val nextDist = dists(i)(j) + 1\n var m = 0\n while (m < 4) {\n val ni = i + dis(m)\n if (ni >= 0 && ni < r) {\n val nj = j + dis(3 - m)\n if (isFree(ni)(nj)) {\n toVisit += ((ni, nj))\n isFree(ni)(nj) = false\n dists(ni)(nj) = nextDist\n }\n }\n m += 1\n }\n }\n\n val limit = dists(start._1)(start._2)\n var sum = 0\n\n for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit; if (s(i)(j) > '0' && s(i)(j) <= '9')) sum += (s(i)(j) - '0')\n\n println(sum)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(r, c) = readInts(2)\n\n val isFree = Array.fill(r)(new mutable.BitSet(c))\n val s = Array.ofDim[String](r)\n\n var start = (0, 0)\n var exit = (0, 0)\n\n for (i <- 0 until r) {\n s(i) = readString\n for (j <- 0 until c) {\n val ch = s(i)(j)\n if (ch != 'T') {\n isFree(i) += j\n if (ch == 'S') start = (i, j)\n else if (ch == 'E') exit = (i, j)\n }\n }\n }\n\n val toVisit = mutable.Queue(exit)\n isFree(exit._1)(exit._2) = false\n val dists = Array.fill(r, c)(Int.MaxValue)\n dists(exit._1)(exit._2) = 0\n\n val dis = Array(-1, 1, 0, 0)\n\n while (!toVisit.isEmpty) { // BFS\n val (i, j) = toVisit.dequeue\n val nextDist = dists(i)(j) + 1\n var m = 0\n while (m < 4) {\n val ni = i + dis(m)\n if (ni >= 0 && ni < r) {\n val nj = j + dis(3 - m)\n if (isFree(ni)(nj)) {\n toVisit += ((ni, nj))\n isFree(ni)(nj) = false\n dists(ni)(nj) = nextDist\n }\n }\n m += 1\n }\n }\n\n val limit = dists(start._1)(start._2)\n var sum = 0\n\n for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit; ch = s(i)(j); if (ch > '0' && ch <= '9')) sum += (ch - '0')\n\n println(sum)\n}"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(r, c) = readInts(2)\n\n val isFree = Array.fill(r)(new mutable.BitSet(c))\n val breeders = Array.fill(r, c)(0)\n\n var start = (0, 0)\n var exit = (0, 0)\n\n for (i <- 0 until r) {\n val s = readString\n for (j <- 0 until c) {\n if (s(j) != 'T') isFree(i) += j\n if (s(j) >= '0' && s(j) <= '9') breeders(i)(j) = s(j) - '0'\n else if (s(j) == 'S') start = (i, j)\n else if (s(j) == 'E') exit = (i, j)\n }\n }\n if (r == 1000) println(\"read\")\n val toVisit = mutable.Queue(exit)\n isFree(exit._1)(exit._2) = false\n val dists = Array.fill(r, c)(Int.MaxValue)\n\n val dis = Array(-1, 1, 0, 0)\n val djs = Array(0, 0, -1, 1)\n if (r == 1000) println(\"init\")\n\n while (!toVisit.isEmpty) { // BFS\n val (i, j) = toVisit.dequeue\n val nextDist = dists(i)(j) + 1\n var m = 0\n while (m < 4) {\n val ni = i + dis(m)\n if (ni >= 0 && ni < r) {\n val nj = j + djs(m)\n if (isFree(ni)(nj)) {\n toVisit += ((ni, nj))\n isFree(ni)(nj) = false\n dists(ni)(nj) = nextDist\n }\n }\n m += 1\n }\n }\n if (r == 1000) println(\"shortest\")\n\n val limit = dists(start._1)(start._2)\n var sum = 0\n\n for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit) sum += breeders(i)(j)\n\n println(sum)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(r, c) = readInts(2)\n\n val isFree = Array.fill(r)(new mutable.BitSet(c))\n val breeders = Array.fill(r, c)(0)\n\n var start = (0, 0)\n var exit = (0, 0)\n\n for (i <- 0 until r) {\n val s = readString\n isFree(i) ++= s.indices.filter(s(_) != 'T')\n s.indices.withFilter(j => s(j) >= '0' && s(j) <= '9').foreach(j => breeders(i)(j) = s(j) - '0')\n var sj = s.indexOf('S')\n if (sj >= 0) start = (i, sj)\n val ej = s.indexOf('E')\n if (ej >= 0) exit = (i, ej)\n }\n\n val toVisit = mutable.Queue(exit)\n isFree(exit._1)(exit._2) = false\n val dists = Array.fill(r, c)(0)\n \n val moves = Array((-1, 0), (1, 0), (0, -1), (0, 1))\n\n while (!toVisit.isEmpty) { // BFS\n val (i, j) = toVisit.dequeue\n for ((di, dj) <- moves; ni = i + di; nj = j + dj; if isFree.isDefinedAt(ni) && isFree(ni)(nj)) {\n toVisit += ((ni, nj))\n isFree(ni)(nj) = false\n dists(ni)(nj) = dists(i)(j) + 1\n }\n }\n \n val limit = dists(start._1)(start._2)\n var sum = 0\n \n for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit) sum += breeders(i)(j)\n\n println(sum)\n}"}], "src_uid": "6e9c2236e24336fcca0723e656e664cc"} {"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\nimport java.util.Scanner\n\nobject test6 extends App {\n val n=readInt\n val mat=Array.ofDim[Int](n+1,n+1)\n val rows=new Array[Int](n+1)\n val cols=new Array[Int](n+1)\n \n for(_<-1 until n){\n val Array(x,y)=readLine.split(\" \").map(_.toInt)\n mat(x)(y)=1\n rows(x)+=1\n cols(y)+=1\n }\n \n val swapRows=(i:Int, j:Int)=>{\n val tmp=mat(i)\n mat(i)=mat(j)\n mat(j)=tmp\n \n val tt=rows(i)\n rows(i)=rows(j)\n rows(j)=tt\n }\n \n val swapCols=(i:Int, j:Int)=>{\n for(k<-1 to n){\n val tmp=mat(k)(i)\n mat(k)(i)=mat(k)(j)\n mat(k)(j)=tmp\n }\n val tmp=cols(i)\n cols(i)=cols(j)\n cols(j)=tmp\n }\n \n var ab=collection.mutable.ArrayBuffer[String]()\n for(i<-n to 1 by -1){\n var col=i\n while(col>0 && cols(col)>0) col-=1\n if(col>0 && col!=i){\n swapCols(i,col)\n ab+=\"2 %d %d\".format(col, i)\n }\n \n var row=i\n while(row>0 && rows(row)==0) row-=1\n if(row>0 && row!=i){\n swapRows(i,row)\n ab+=\"1 %d %d\".format(row,i)\n }\n \n for(j<-1 to i) if(mat(i)(j)==1) cols(j)-=1\n }\n println(ab.size)\n ab.foreach(println)\n} \n\n\n", "positive_code": [{"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\nimport java.util.Scanner\n\nobject test6 extends App {\n val n=readInt\n val mat=Array.ofDim[Int](n+1,n+1)\n val rows=new Array[Int](n+1)\n val cols=new Array[Int](n+1)\n \n for(_<-1 until n){\n val Array(x,y)=readLine.split(\" \").map(_.toInt)\n mat(x)(y)=1\n rows(x)+=1\n cols(y)+=1\n }\n \n val swapRows=(i:Int, j:Int)=>{\n val tmp=mat(i)\n mat(i)=mat(j)\n mat(j)=tmp\n \n val tt=rows(i)\n rows(i)=rows(j)\n rows(j)=tt\n }\n \n val swapCols=(i:Int, j:Int)=>{\n for(k<-1 to n){\n val tmp=mat(k)(i)\n mat(k)(i)=mat(k)(j)\n mat(k)(j)=tmp\n }\n val tmp=cols(i)\n cols(i)=cols(j)\n cols(j)=tmp\n }\n \n var ab=collection.mutable.ArrayBuffer[String]()\n for(i<-n to 1 by -1){\n var col=i\n while(col>0 && cols(col)>0) col-=1\n if(col>0 && col!=i){\n swapCols(i,col)\n ab+=\"2 %d %d\".format(col, i)\n }\n \n var row=i\n while(row>0 && rows(row)==0) row-=1\n if(row>0 && row!=i){\n swapRows(i,row)\n ab+=\"1 %d %d\".format(row,i)\n }\n \n for(j<-1 to i) if(mat(i)(j)==1) cols(j)-=1\n }\n println(ab.size)\n println(ab.mkString(\"\\n\"))\n} \n\n\n"}], "negative_code": [], "src_uid": "3b2c5410441e588806690056693514a8"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val map = scala.collection.mutable.Map[String, Int]()\n for (_ <- 1 to n) {\n val name = readLine()\n map.get(name) match {\n case None => \n map(name) = 1\n println(\"OK\")\n case Some(i) =>\n map(name) = i + 1\n println(name + i)\n }\n }\n }\n}", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P004C extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n sc.nextLine\n type DB = mutable.Map[String, Int]\n val db: DB = mutable.Map.empty[String, Int]\n for (_ <- 0 until N) {\n val request = sc.nextLine\n if (db.contains(request)) {\n val i = db(request) + 1\n db += (request -> i)\n out.println(request + i.toString)\n }\n else {\n db += (request -> 0)\n out.println(\"OK\")\n }\n }\n out.close\n}\n"}, {"source_code": "\nimport java.io.PrintWriter\nimport java.io.BufferedWriter\nimport java.io.InputStreamReader\nimport java.io.BufferedReader\nimport java.util\n\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 05 May 2016\n */\nobject C4 extends App {\n\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var writer = new BufferedWriter(new PrintWriter(System.out))\n val n: Int = reader.readLine().toInt\n val db: mutable.HashMap[String, Int] = mutable.HashMap.empty[String, Int]\n val answer: util.ArrayList[String] = new util.ArrayList[String](n)\n for (i <- 0 until n) {\n val input = reader.readLine()\n if (!db.contains(input)) {\n writer.write(\"OK\\n\")\n db += (input -> 1)\n } else {\n var i1: Int = db.get(input).get\n var found = false\n while (!found) {\n if (!db.contains(input + i1)) {\n found = true\n } else {\n i1 += 1\n }\n }\n val s: String = input + i1 + \"\\n\"\n writer.write(s)\n db += (input -> (i1 + 1))\n db += (input + i1 -> 1)\n }\n }\n\n writer.close()\n reader.close()\n}\n"}, {"source_code": "object Cf4C extends App {\n val d =collection.mutable.Map[String, Int]()\n for(_ <-1 to readInt()){\n val s = readLine\n d get s match {\n case Some(x) => {println(s+x);d(s)=x+1}\n case None => {println(\"OK\");d(s)=1}\n }\n }\n}"}, {"source_code": "import java.util\nimport java.util._\nimport java.lang._\nimport java.io._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val names = new util.HashSet[String]()\n val namedInd = new util.HashMap[String, Int]()\n for (i <- 0 until n) {\n val name = next\n if (names.contains(name)) {\n val ind = namedInd.get(name)\n out.println(name + ind.toString)\n names.add(name + ind.toString)\n namedInd.remove(name)\n namedInd.put(name, ind + 1)\n } else {\n names.add(name)\n namedInd.put(name, 1)\n out.println(\"OK\")\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "object P4C {\n def main(args : Array[String]) {\n val n = readLine.toInt\n val d = collection.mutable.Map[String, Int]()\n for (_ <- 1 to n) {\n val s = readLine\n d get s match {\n case Some(x) => {println(s + x); d(s) = x + 1}\n case None => {println(\"OK\"); d(s) = 1}\n }\n }\n }\n}"}, {"source_code": "import scala.collection.mutable.Map\nobject Main {\n def main(args: Array[String]) {\n val n = readInt()\n val map = Map[String, Int]()\n for (i <- 1 to n) {\n val str = readLine()\n if (map.contains(str)) {\n map(str) += 1\n println(str + map(str).toString)\n }\n else {\n map += (str -> 0)\n println(\"OK\")\n }\n }\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject _4_C extends App {\n val n = readInt()\n val counter = new mutable.HashMap[String, Int]\n\n for (_ <- 1 to n) {\n val name = readLine()\n var c = counter.getOrElseUpdate(name, 0)\n if (c == 0) {\n println(\"OK\")\n }\n else {\n println(s\"$name$c\")\n }\n c += 1\n counter(name) = c\n }\n}\n"}, {"source_code": "import scala.collection.mutable.HashMap\n\nobject RegistrationSystem{\n class Name(var nameString : String = \"\",var count : Int = 0,var printedCount : Int = 0)\n def main(args : Array[String]){\n \n var n : Int = readLine.toInt\n var namesMap : HashMap[String,Name] = new HashMap[String,Name]()\n var namesArray : Array[String] = new Array[String](n)\n for(i <- 0 to n-1){\n var name : String = readLine\n namesArray(i) = name\n if (namesMap.contains(name)){\n namesMap(name).count += 1\n }\n else{\n namesMap.put(name,new Name(name,1,0))\n }\n }\n for(name <- namesArray){\n if (namesMap(name).printedCount == 0){\n println(\"OK\")\n }\n else{\n println(name + namesMap(name).printedCount) \n }\n namesMap(name).printedCount += 1\n }\n }\n}"}, {"source_code": "object P4C {\n def main(args : Array[String]) {\n val n = readLine.toInt\n val d = collection.mutable.Map[String, Int]()\n for (_ <- 1 to n) {\n val s = readLine\n d get s match {\n case Some(x) => {println(s + x); d(s) = x + 1}\n case None => {println(\"OK\"); d(s) = 1}\n }\n }\n }\n}\n"}, {"source_code": "object P4C {\n def main(args : Array[String]) {\n val n = readLine.toInt\n val d = collection.mutable.Map[String, Int]()\n for (_ <- 1 to n) {\n val s = readLine\n d get s match {\n case Some(x) => {println(s + x); d(s) = x + 1}\n case None => {println(\"OK\"); d(s) = 1}\n }\n }\n }\n}"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\n\n/**\n * Created by nhan on 5/30/16.\n */\n\nobject Registrator {\n\n def main(args: Array[String]) {\n val br = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(System.out)\n val dict = collection.mutable.HashMap.empty[String, Int]\n val numLine = br.readLine().toInt\n (1 to numLine).foreach { _ =>\n val line = br.readLine()\n if (dict contains line) {\n val value = dict(line) + 1\n dict.update(line, value)\n out.println(line + value)\n } else {\n dict.update(line, 0)\n out.println(\"OK\")\n }\n }\n out.close\n }\n}"}, {"source_code": "import scala.collection.mutable._\n\nobject Main {\n def main(args : Array[String]) {\n val n = Integer valueOf(readLine())\n val db = new HashMap[String, Int]\n \n for(i <- 0 until n) {\n val name = readLine()\n if(!(db contains name)) {\n db += name -> 1\n } else {\n db += name -> (db(name) + 1)\n }\n \n if(db(name) == 1) {\n println(\"OK\");\n } else {\n println(name + (db(name) - 1))\n }\n }\n }\n}\n"}, {"source_code": "import scala.collection.mutable._\n\nobject Main {\n def main(args : Array[String]) {\n val n = Integer valueOf(readLine())\n val db = new HashMap[String, Int]\n \n for(i <- 0 until n) {\n val name = readLine()\n \n db get name match {\n case Some(k) => {\n println(name + k);\n db += name -> (k + 1)\n }\n \n case None => {\n println(\"OK\")\n db += name -> 1\n }\n }\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject CRegSystem extends App {\n\n val scanner = new Scanner(System.in)\n val num = scanner.nextInt()\n\n val m = scala.collection.mutable.HashMap.empty[String, Int]\n\n\n val queries = ((0 until num) map (it => scanner.next())).toList\n\n queries.foreach {\n item =>\n m.get(item) match {\n case Some(v) =>\n m.put(item, v + 1)\n println(\"\" + item + v)\n case None =>\n m.put(item, 1)\n println(\"OK\")\n }\n }\n\n\n\n\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject C4 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val map = mutable.Map.empty[String, Int].withDefaultValue(0)\n for (i <- 0 until n) {\n val name = scala.io.StdIn.readLine\n if(map.contains(name)) {\n println(s\"${name}${map(name)}\")\n map(name) += 1\n } else {\n map(name) = 1\n println(\"OK\")\n }\n }\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject A extends App {\n\n var map: Map[String, Int] = Map()\n\n val n = StdIn.readInt()\n (1 to n).foreach { _ =>\n val s = StdIn.readLine()\n if(map.contains(s)) {\n map = map + (s -> (map(s) + 1))\n println(s + map(s))\n } else {\n map = map + (s -> 0)\n println(\"OK\")\n }\n }\n}\n"}, {"source_code": "object P4C {\n def main(args : Array[String]) {\n val n = readLine.toInt\n val d = collection.mutable.Map[String, Int]()\n for (_ <- 1 to n) {\n val s = readLine\n if (d contains s) {\n val ds = d(s)\n println(s + ds)\n d(s) = ds + 1\n } else {\n println(\"OK\")\n d(s) = 1\n }\n }\n }\n}\n"}], "negative_code": [{"source_code": "\nimport java.util\n\nimport scala.collection.mutable\n\n/**\n * @author pvasilyev\n * @since 05 May 2016\n */\nobject C4 extends App {\n\n val n: Int = scala.io.StdIn.readInt()\n val db: mutable.HashSet[String] = mutable.HashSet.empty[String]\n val answer: util.ArrayList[String] = new util.ArrayList[String](n)\n for (i <- 0 until n) {\n val input = scala.io.StdIn.readLine()\n if (!db.contains(input)) {\n answer.add(\"OK\")\n db += input\n } else {\n var found = false\n var i: Int = 1\n while (!found) {\n if (!db.contains(input + i)) {\n found = true\n } else {\n i += 1\n }\n }\n answer .add (input + i)\n db += (input + 1)\n }\n }\n\n println(answer.toArray.mkString(\"\\n\"))\n}\n"}], "src_uid": "24098df9c12d9704391949c9ff529c98"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val counts = Array.ofDim[Int](1000)\n val open = Array.ofDim[Int](1000)\n val different = Array.ofDim[Boolean](1000)\n (1 to n).foreach { i =>\n val Array(a, b) = in.next().split(' ').map(_.toInt - 1)\n counts(a) += 1\n open(b) += 1\n different(b) = different(b) || a != b\n }\n println(counts.zip(open).zip(different).foldLeft(0) {\n case(sum, ((count, 0), diff)) => sum + count\n case(sum, ((0, _), _)) => sum\n case(sum, ((count, n), false)) if n == 1 => sum + 1\n case(sum, ((count, _), _)) => sum\n })\n}\n", "positive_code": [{"source_code": "object A extends App {\n\n def solve(n: Int, as: Array[Int], bs: Array[Int]): Int = {\n\n n - as.indices.count(i => bs.indices.exists(j => as(i) == bs(j) && i != j))\n } \n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val n = readString.toInt\n val as = Array.ofDim[Int](n)\n val bs = Array.ofDim[Int](n)\n for (i <- 0 until n) {\n val Array(a, b) = readInts\n as(i) = a\n bs(i) = b\n }\n\n println(solve(n, as, bs)) \n}"}, {"source_code": "// package R187d2\n\nimport java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val xs = Array.fill(N, 2)(sc.nextInt)\n\n def isUnableToOpen(i: Int): Boolean = {\n @tailrec\n def loop(j :Int): Boolean =\n if (j == N) true\n else if (i == j) loop(j + 1)\n else if (xs(i)(0) == xs(j)(1)) false\n else loop(j + 1)\n\n loop(0)\n }\n\n out.println(List.range(0, N).count(isUnableToOpen))\n out.close\n}\n"}, {"source_code": "object ASerejaAndBottles extends App {\n import scala.io.StdIn._\n\n val n = readInt()\n\n val (as, bs) = (0 until n).foldLeft((List.empty[Int], List.empty[Int])) {\n case ((as, bs), _) =>\n val Array(a, b) = readLine().split(\" \").map(_.toInt)\n (a :: as, b :: bs)\n }\n\n val ans = n - (as zip bs).collect {\n case (a, b) if a == b && bs.count(_ == a) > 1 => 1\n case (a, b) if a != b && bs.exists(_ == a) => 1\n }.sum\n\n println(ans)\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = for(_ <- 1 to n) yield { readLine().split(\" \").map(_.toInt) }\n val Array(as, bs) = a.transpose.toArray\n val r = for {\n (x, i) <- as.zipWithIndex\n (y, j) <- bs.zipWithIndex\n if i != j\n if x == y\n } yield(i)\n println(n - r.toSet.size)\n }\n}"}, {"source_code": "\nobject Second{\n def readString() : String = {\n var yo = scala.io.StdIn.readLine() \n yo \n }\n def readInt() : Int = { \n var yo = scala.io.StdIn.readInt(); \n yo \n }\n def solve(n : Int , as : Array[Int] , bs : Array[Int]) : Int = {\n val ho = n - as.indices.count(i => bs.indices.exists(j => as(i) == bs(j) && i != j)) \n ho \n }\n def main(args : Array[String]){\n var n = readInt() \n var as = Array.ofDim[Int](n)\n var bs = Array.ofDim[Int](n) \n for(i <- 0 until n){\n var Array(a, b ) = readString().split(\" \").map(_.toInt)\n as(i) = a \n bs(i) = b \n }\n print(solve(n , as , bs))\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val counts = Array.ofDim[Int](1000)\n val open = Array.ofDim[Boolean](1000)\n val different = Array.ofDim[Boolean](1000)\n (1 to n).foreach { i =>\n val Array(a, b) = in.next().split(' ').map(_.toInt - 1)\n counts(a) += 1\n open(b) = true\n different(b) = different(b) || a != b\n }\n println(counts.zip(open).zip(different).foldLeft(0) {\n case(sum, ((_, false), diff)) => sum\n case(sum, ((0, _), _)) => sum\n case(sum, ((count, _), false)) => sum + 1\n case(sum, ((count, _), _)) => sum + count\n })\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val counts = Array.ofDim[Int](1000)\n val open = Array.ofDim[Boolean](1000)\n val different = Array.ofDim[Boolean](1000)\n (1 to n).foreach { i =>\n val Array(a, b) = in.next().split(' ').map(_.toInt - 1)\n counts(a) += 1\n open(b) = true\n different(b) = different(b) || a != b\n }\n println(counts.zip(open).zip(different).foldLeft(0) {\n case(sum, ((count, false), diff)) => sum + count\n case(sum, ((0, _), _)) => sum\n case(sum, ((count, _), false)) => sum + 1\n case(sum, ((count, _), _)) => sum\n })\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val counts = Array.ofDim[Int](1000)\n val open = Array.ofDim[Boolean](1000)\n val different = Array.ofDim[Boolean](1000)\n (1 to n).foreach { i =>\n val Array(a, b) = in.next().split(' ').map(_.toInt - 1)\n counts(a) += 1\n open(b) = true\n different(b) = different(b) || a != b\n }\n println(counts.zip(open).zip(different).foldLeft(0) {\n case(sum, ((_, false), diff)) => sum\n case(sum, ((0, _), _)) => sum\n case(sum, ((count, _), false)) => sum + count\n case(sum, ((count, _), _)) => sum + count - 1\n })\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val counts = Array.ofDim[Int](1000)\n val open = Array.ofDim[Boolean](1000)\n val different = Array.ofDim[Boolean](1000)\n (1 to n).foreach { i =>\n val Array(a, b) = in.next().split(' ').map(_.toInt - 1)\n counts(a) += 1\n open(b) = true\n different(b) = different(b) || a != b\n }\n println(counts.zip(open).zip(different).foldLeft(0) {\n case(sum, ((count, false), diff)) => sum + count\n case(sum, ((0, _), _)) => sum\n case(sum, ((count, _), false)) => sum + count - 1\n case(sum, ((count, _), _)) => sum\n })\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val counts = Array.ofDim[Int](1000)\n val open = Array.ofDim[Boolean](1000)\n val different = Array.ofDim[Boolean](1000)\n (1 to n).foreach { i =>\n val Array(a, b) = in.next().split(' ').map(_.toInt - 1)\n counts(a) += 1\n open(b) = true\n different(b) = different(b) || a != b\n }\n println(counts.zip(open).zip(different).foldLeft(0) {\n case(sum, ((_, false), diff)) => sum\n case(sum, ((count, _), false)) => sum + count\n case(sum, ((count, _), _)) => sum + count - 1\n })\n}\n"}, {"source_code": "object A extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n def solve(n: Int): Int = {\n\n \tif (n < 0) {\n \t val p = -n\n \t -math.min(p / 10, (p / 100) * 10 + p % 10)\n \t} else n\n } \n\n val n = readString.toInt\n\n println(solve(n)) \n}"}, {"source_code": "object ASerejaAndBottles extends App {\n import scala.io.StdIn._\n\n val n = readInt()\n val bottles = Array.fill(1001)(0)\n val same = Array.fill(1001)(false)\n val opened = Array.fill(1001)(false)\n\n (0 until n).foreach { _ =>\n val Array(bottle, other) = readLine().split(\" \").map(_.toInt)\n\n bottles(bottle) += 1\n\n if (bottle == other) same(bottle) = true\n else opened(other) = true\n }\n\n same.zipWithIndex.foreach {\n case (false, _) => ()\n case (_, bottle) => opened(bottle) = opened(bottle) || bottles(bottle) > 1\n }\n\n val ans = bottles.zipWithIndex.foldLeft(n) {\n case (closed, (0, _)) => closed\n case (closed, (count, bottle)) =>\n closed - (if (opened(bottle)) count else 0)\n }\n\n println(ans)\n}\n"}, {"source_code": "object ASerejaAndBottles extends App {\n import scala.io.StdIn._\n import scala.collection.mutable\n\n val n = readInt()\n\n val bottles = Array.fill(1001)(0)\n val descriptions = Array.fill(1001)(List.empty[Int])\n\n (0 until n).foreach { _ =>\n val Array(bottle, description) = readLine().split(\" \").map(_.toInt)\n bottles(bottle) += 1\n descriptions(bottle) ::= description\n }\n\n val ans = bottles.zipWithIndex.foldLeft(n) {\n case (closed, (_, 0)) => closed\n case (closed, (count, bottle)) =>\n descriptions(bottle).exists { opener =>\n if (opener == bottle) count > 1\n else bottles(opener) > 0\n } match {\n case true => closed - count\n case _ => closed\n }\n }\n\n println(ans)\n}\n"}, {"source_code": "object ASerejaAndBottles extends App {\n import scala.io.StdIn._\n\n val n = readInt()\n\n val (as, bs) = (0 until n).foldLeft((List.empty[Int], List.empty[Int])) {\n case ((as, bs), _) =>\n val Array(a, b) = readLine().split(\" \").map(_.toInt)\n (a :: as, b :: bs)\n }\n\n val ans = n - (as zip bs).collect {\n case (a, b) if a != b && bs.exists(_ == a) => 1\n }.sum\n\n println(ans)\n}\n"}, {"source_code": "object ASerejaAndBottles extends App {\n import scala.io.StdIn._\n\n val n = readInt()\n val ans = (0 until n).foldLeft(0) {\n case (acc, _) =>\n val Array(a, b) = readLine().split(\" \").map(_.toInt)\n acc + (if (a == b) 1 else 0)\n }\n\n println(ans)\n}\n"}, {"source_code": "object ASerejaAndBottles extends App {\n import scala.io.StdIn._\n import scala.collection.mutable\n\n val n = readInt()\n\n val bottles = Array.fill(1001)(0)\n val opened = Array.fill(1001)(false)\n\n (0 until n).foreach { _ =>\n val Array(bottle, other) = readLine().split(\" \").map(_.toInt)\n\n bottles(bottle) += 1\n\n opened(other) = opened(other) ||\n (if (bottle == other) bottles(bottle) > 1 else true)\n }\n\n val ans = bottles.zipWithIndex.foldLeft(n) {\n case (closed, (0, _)) => closed\n case (closed, (count, bottle)) =>\n closed - (if (opened(bottle)) count else 0)\n }\n\n println(ans)\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = for(_ <- 1 to n) yield {readLine().split(\" \").map(_.toInt) }\n val f = a.filter(t => t(0) != t(1))\n if (f.size == 0) println(n)\n else {\n val Array(as, bs) = f.transpose.map(_.toSet).toArray\n val r = as -- bs\n println(n - f.size + r.size)\n }\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = for(_ <- 1 to n) yield {readLine().split(\" \").map(_.toInt) }\n val f = a.filter(t => t(0) != t(1))\n if (f.size == 0) println(n)\n else {\n val Array(as, bs) = f.transpose.toArray\n val bss = bs.toSet\n val r = as filter (e => ! (bss contains e))\n println(n - f.size + r.size)\n }\n }\n}"}], "src_uid": "84bd49becca69e126606d5a2f764dd91"} {"source_code": "/**\n * @see http://codeforces.com/contest/909/problem/C\n */\n\nobject CPythonIndentation extends App {\n val mod = 1000000007\n\n val n = scala.io.StdIn.readInt()\n\n val t = (0 until (n - 1)).foldLeft(List(1)) ((l, _) => {\n val c = scala.io.StdIn.readChar()\n if (c == 'f') 0 +: l\n else l.foldRight(List.empty[Int]) ((i, l) => {\n if (l.isEmpty) List(i)\n else ((i + l.head) % mod) +: l\n })\n }).reduce((a, b) => (a + b) % mod)\n\n println(t)\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\nobject Main extends App {\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val n = in.nextInt\n var prev = \"\"\n\n var cnt = 0\n var d = new Array[Int](n+1)\n\n for (i <- 0 to n-1) {\n\n val s = in.next\n val nd = new Array[Int](n+1)\n prev match {\n case \"f\" => {\n for (i <- 1 to n) nd(i) = d(i-1)\n }\n case \"s\" => {\n var sum = 0\n for (i <- n to 0 by -1) {\n sum += d(i)\n sum %= MOD\n nd(i) = sum\n }\n }\n case _ => nd(0) = 1\n }\n //println(nd(0))\n d = nd\n prev = s\n }\n\n var ans = 0\n for (k <- d) ans = (ans + k)%MOD\n\n out.println(ans)\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}"}, {"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val MOD = 1000000007L\n\n val dp = Array.fill(n + 1){ 0L }\n var fCount = 0\n var prev = '-'\n dp(0) = 1\n //println(dp.mkString(\" \"))\n for (_ <- 0 until n) {\n val c = readLine.head\n if (prev != 'f' && c == 's') {\n for (i <- fCount - 1 to 0 by -1) dp(i) = (dp(i) + dp(i + 1)) % MOD\n } else {\n if (prev != 'f') for (i <- fCount - 1 to 0 by -1) dp(i) = (dp(i) + dp(i + 1)) % MOD\n if (c == 'f') {\n fCount += 1\n for (i <- fCount - 1 to 0 by -1) dp(i + 1) = dp(i)\n dp(0) = 0\n }\n }\n //println(dp.mkString(\" \"))\n prev = c\n }\n\n var sum = 0L\n for (x <- dp) sum = (sum + x) % MOD\n\n println(sum)\n}\n"}], "negative_code": [{"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val MOD = 1000000007L\n\n val dp = Array.fill(n + 1){ 0L }\n var fCount = 0\n var prev = '-'\n\n for (_ <- 0 until n) {\n val c = readLine.head\n if (prev != 'f') {\n if (c == 's') for (i <- fCount - 1 to 0 by -1) dp(i) = (dp(i) + dp(i + 1)) % MOD\n } else if (c == 's') {\n dp(fCount) += 1\n }\n if (c == 'f') {\n fCount += 1\n }\n //println(dp.mkString(\" \"))\n prev = c\n }\n\n var sum = 0L\n for (x <- dp) sum = (sum + x) % MOD\n\n if (fCount == 0) sum = 1L\n\n println(sum)\n}\n"}, {"source_code": "/**\n * @see http://codeforces.com/contest/909/problem/C\n */\n\nobject CPythonIndentation extends App {\n val mod = 1000000007\n\n val N = scala.io.StdIn.readInt()\n\n def f(l: List[Int], m: List[Int] = List.empty): List[Int] =\n if (l.isEmpty) m\n else f(l.tail, (l.sum % mod) +: m)\n\n val t = (0 until N).foldLeft((List.empty[Int], 'c')) ((h, i) => {\n val c = scala.io.StdIn.readChar()\n if (i == 0) (List(1), c)\n else if (h._2 == 'f') (0 +: h._1, c)\n else (f(h._1), c)\n })._1\n\n println(t.sum % mod)\n}\n"}], "src_uid": "c4033b57cd52b4c8567e946e136cb5dc"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val C = Array.ofDim[Int](26)\n REP(N) { _ =>\n val c = ns().head - 'a'\n C(c) += 1\n }\n\n debug(C)\n\n def comb(n: Int) = {\n if (n < 2) 0\n else n * (n - 1) / 2\n }\n\n var ans = 0\n REP(26) { i =>\n if (C(i) >= 2) {\n val f = C(i) / 2\n val s = C(i) - f\n debug(s\"f:$f s:$s\")\n ans += comb(f) + comb(s)\n }\n }\n\n out.println(ans)\n }\n}", "positive_code": [{"source_code": "object Main extends App {\n\t\n\tdef factorial(n: Int) : Double = {\n\t var result : Double = 1\n\t \n\t for ( i <- 2 to n ) {\n\t \tresult *= i\n\t }\n\t \n\t return result\n\t}\n\t\n\t// your code goes here\n\tvar n = Console.readLine\n\tvar size : Int = n.toInt\n\tvar arrName : Array[String] = new Array[String](size)\n\tvar arrCount : Array[Int] = new Array[Int](30)\n\tvar ans : Double = 0\n\t\n\tfor ( i <- 0 to size-1) {\n\t\tarrName(i) = Console.readLine\n\t}\n\t\n\tfor (i <- 0 to 29) {\n\t\tarrCount(i) = 0\n\t}\n\t\n\tfor ( i <- 0 to size-1) {\n\t\tvar pos : Int = arrName(i).charAt(0) - 'a'\n\t\tarrCount(pos) += 1\n\t}\n\t\n\tfor (i <- 0 to 29) {\n\t\tvar room1 : Int = arrCount(i)/2\n\t\tvar room2 : Int = arrCount(i) - room1\n\t\t\n\t\tif ( room1 > 1 ) {\n\t\t\tans += factorial(room1) / 2 / factorial(room1 - 2)\n\t\t}\n\t\t\n\t\tif ( room2 > 1 ) {\n\t\t\tans += factorial(room2) / 2 / factorial(room2 - 2)\n\t\t}\n\t}\n\t\n\tprintln(ans.toLong)\n}"}, {"source_code": "object _1166A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val students = io.read[Seq[String]]\n\n val ans = students\n .groupBy(_.head)\n .mapValues(grps => pairs(grps.size))\n .values\n .sum\n\n io.write(ans)\n }\n\n def pairs(n: Int) = {\n val room1 = n/2\n val room2 = n - n/2\n ((room1*(room1 - 1))/2) + ((room2*(room2 - 1))/2)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "object Main extends App {\n\t\n\tdef factorial(n: Int): Int = n match {\n\t case 0 => 1\n\t case _ => n * factorial(n-1)\n\t}\n\t\n\t// your code goes here\n\tvar n = Console.readLine\n\tvar size : Int = n.toInt\n\tvar arrName : Array[String] = new Array[String](size)\n\tvar arrCount : Array[Int] = new Array[Int](30)\n\tvar ans : Long = 0\n\t\n\tfor ( i <- 0 to size-1) {\n\t\tarrName(i) = Console.readLine\n\t}\n\t\n\tfor (i <- 0 to 29) {\n\t\tarrCount(i) = 0\n\t}\n\t\n\tfor ( i <- 0 to size-1) {\n\t\tvar pos : Int = arrName(i).charAt(0) - 'a'\n\t\tarrCount(pos) += 1\n\t}\n\t\n\tfor (i <- 0 to 29) {\n\t\tvar room1 : Int = arrCount(i)/2\n\t\tvar room2 : Int = arrCount(i) - room1\n\t\t\n\t\tif ( room1 > 1 ) {\n\t\t\tans += factorial(room1) / 2 / factorial(room1 - 2)\n\t\t}\n\t\t\n\t\tif ( room2 > 1 ) {\n\t\t\tans += factorial(room2) / 2 / factorial(room2 - 2)\n\t\t}\n\t}\n\t\n\tprintln(ans)\n}"}], "src_uid": "22a3561ff70b802f080feaabc4a71298"} {"source_code": "object Main2 extends App {\n\n import java.io._\n import java.util.{StringTokenizer}\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n //val out: PrintWriter = new PrintWriter(new BufferedWriter(new FileWriter(\"output.txt\")))\n\n val n = in.nextInt\n val a = in.nextLine.split(' ').map(_.toInt).map(x => if (x >= 0) -x - 1 else x )\n if (a.foldLeft(0)((acc, x) => if (x < 0) acc + 1 else acc) % 2 == 1) {\n var min = a.min\n for (i <- 0 until n)\n if (a(i) == min) {\n a(i) = -min - 1\n min = 0\n }\n }\n out.print(a.mkString(\" \"))\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n def nextLong: Long = next.toLong\n\n def nextDouble: Double = next.toDouble\n\n def nextLine: String = br.readLine\n }\n\n}", "positive_code": [{"source_code": "//package round569\n\nimport scala.io.StdIn._\n\nobject TaskB extends App {\n val n = readInt\n val arr = readLine.split(\" \").map(_.toInt).map(x => if(x == 0) -1 else if (x > 0) -x - 1 else x)\n if (arr.length % 2 == 0)\n println(arr.mkString(\" \"))\n else {\n val max = arr.min\n var flag = false\n println(arr.map {\n x =>\n if(x == max && !flag) {\n flag = true\n -x - 1\n } else {\n x\n }\n }.mkString(\" \"))\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B_1180 extends App {\n val n = readInt()\n var A = readLine().split(\" \").map(_.toInt)\n\n A = A.map { v =>\n if (v >= 0) -v - 1 else v\n }\n\n if (A.count(_ < 0) % 2 == 1) {\n val (_, minId) = A.zipWithIndex.minBy(_._1)\n A(minId) = -A(minId) - 1\n }\n\n println(A.mkString(\" \"))\n\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject B_1180 extends App {\n val n = readInt()\n val A = readLine().split(\" \").map(_.toInt)\n\n var B = A.sorted\n\n B = B.map { v =>\n if (v >= 0) -v - 1 else v\n }\n\n var answer = B.product\n if (answer <= 0) {\n val (min, minId) = B.zipWithIndex.minBy(_._1)\n B(minId) = -B(minId) - 1\n }\n\n println(B.mkString(\" \"))\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B_1180 extends App {\n val n = readInt()\n val A = readLine().split(\" \").map(_.toInt)\n\n val B = A.zipWithIndex.sortBy(_._1)\n\n var left = 0\n var right = n - 1\n\n val negatives = B.count(_._1 < 0)\n val positives = B.count(_._1 > 0)\n\n if (negatives % 2 == 0) {\n var right = B.length - 2\n while (right >= 0 && B(right)._1 >= 0) {\n B(right + 1) = (-B(right + 1)._1 - 1, B(right + 1)._2)\n B(right) = (-B(right)._1 - 1, B(right)._2)\n right -= 2\n }\n } else {\n var right = B.length - 1\n while (right > 0 && B(right)._1 > 0) {\n B(right) = (-B(right)._1 - 1, B(right)._2)\n right -= 1\n }\n }\n\n var zeros = B.count(_._1 == 0)\n\n val newNegatives = B.count(_._1 < 0)\n if (newNegatives % 2 == 1) {\n zeros = if (zeros % 2 == 1) zeros else zeros - 1\n } else {\n zeros = if (zeros % 2 == 0) zeros else zeros - 1\n }\n if (zeros < 0) zeros = 0\n\n var i = 0\n while (zeros > 0) {\n if (B(i)._1 == 0) {\n B(i) = (-1, B(i)._2)\n zeros -= 1\n }\n i += 1\n }\n\n println(B.sortBy(_._2).map(_._1).mkString(\" \"))\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B_1180 extends App {\n val n = readInt()\n var A = readLine().split(\" \").map(_.toInt)\n\n A = A.map { v =>\n if (v >= 0) -v - 1 else v\n }\n\n var answer = A.product\n if (answer <= 0) {\n val (min, minId) = A.zipWithIndex.minBy(_._1)\n A(minId) = -A(minId) - 1\n }\n\n println(A.mkString(\" \"))\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B_1180 extends App {\n val n = readInt()\n val A = readLine().split(\" \").map(_.toInt)\n\n val B = A.sorted\n\n var left = 0\n var right = n - 1\n\n val negatives = B.count(_ < 0)\n val positives = B.count(_ > 0)\n\n if (negatives % 2 == 0) {\n var right = B.length - 2\n while (right >= 0 && B(right) >= 0) {\n B(right + 1) = -B(right + 1) - 1\n B(right) = -B(right) - 1\n right -= 2\n }\n } else {\n var right = B.length - 1\n while (right > 0 && B(right) > 0) {\n B(right) = -B(right) - 1\n right -= 1\n }\n }\n\n var zeros = B.count(_ == 0)\n\n val newNegatives = B.count(_ < 0)\n if (newNegatives % 2 == 1) {\n zeros = if (zeros % 2 == 1) zeros else zeros - 1\n } else {\n zeros = if (zeros % 2 == 0) zeros else zeros - 1\n }\n if (zeros < 0) zeros = 0\n\n var i = 0\n while (zeros > 0) {\n if (B(i) == 0) {\n B(i) = -1\n zeros -= 1\n }\n i += 1\n }\n\n println(B.mkString(\" \"))\n}\n"}, {"source_code": "object Main2 extends App {\n\n import java.io._\n import java.util.{StringTokenizer}\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n //val out: PrintWriter = new PrintWriter(new BufferedWriter(new FileWriter(\"output.txt\")))\n\n val n = in.nextInt\n val a = in.nextLine.split(' ').map(_.toInt).map(x => if (x >= 0) -x - 1 else x )\n if (a.foldLeft(0)((acc, x) => if (x < 0) acc + 1 else acc) % 2 == 1)\n a(0) = -a(0) - 1\n out.print(a.mkString(\" \"))\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n def nextInt: Int = next.toInt\n\n def nextLong: Long = next.toLong\n\n def nextDouble: Double = next.toDouble\n\n def nextLine: String = br.readLine\n }\n\n}"}], "src_uid": "b0561fee6236f0720f737ca41e20e382"} {"source_code": "object B515F extends App {\n\n def readNextLine : Array[Int] = {\n readLine.split(\" \").map(_.toInt)\n }\n \n \n def becomeHappy (pair : (Int, Int), hg : Array[Int], hl: Array[Int], isHappy: Int) : Boolean = {\n def exist(arr : Array[Int], value : Int) : Int = \n arr.contains(value) match { case true => 1; case false => 0} \n (exist(hg, pair._1) + exist(hl, pair._2)) == isHappy\n }\n \n def isStuck(tg : List[(Int, Int)], hg : Array[Int], hl : Array[Int]) : Boolean = {\n tg.filter(pair => \n becomeHappy(pair, hg, hl, 1) || becomeHappy(pair, hg, hl, 2) ).isEmpty\n }\n \n def B515F = {\n val l : Array[Int] = readNextLine\n val n = l(0)\n val m = l(1)\n val t = n * m\n var guys : List[Int] = Nil\n var gals : List[Int] = Nil\n \n for(i <- 0 until t) {\n guys ::= i % n\n gals ::= i % m\n }\n \n var together = guys.zip(gals).distinct\n \n var happyGuys : Array[Int] = (readNextLine) drop 1\n var happyGals : Array[Int] = (readNextLine) drop 1\n var willBeHappy : List[(Int, Int)] = Nil\n \n \n do {\n \n willBeHappy = together.filter(pair => becomeHappy(pair, happyGuys, happyGals, 1) || becomeHappy(pair, happyGuys, happyGals, 2))\n together = together.filter(pair => ! (becomeHappy(pair, happyGuys, happyGals, 1) || becomeHappy(pair, happyGuys, happyGals, 2)))\n happyGuys ++= willBeHappy.map(pair => pair._1)\n happyGals ++= willBeHappy.map(pair => pair._2)\n } while(!isStuck(together, happyGuys, happyGals) && !together.isEmpty)\n \n println(together.isEmpty match {case true => \"Yes\"; case false => \"No\"})\n }\n\n B515F\n \n}", "positive_code": [{"source_code": "\nimport java.util.Scanner\n\n/**\n * Created by root on 2/21/15.\n */\nobject Drazil2 {\n\n\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val m = sc.nextInt()\n\n val boys = Array.tabulate[Int](n)(_ => 0)\n val girls = Array.tabulate[Int](m)(_ => 0)\n\n (0 until sc.nextInt()) foreach { _ =>\n boys(sc.nextInt()) = 1\n }\n\n (0 until sc.nextInt()) foreach { _ =>\n girls(sc.nextInt()) = 1\n }\n\n val max = n*m\n\n for (i<- 0 to 2*max) {\n val b = i%n\n val g = i%m\n if (boys(b) == 1) {\n girls(g) = 1\n }\n if (girls(g) == 1){\n boys(b) = 1\n }\n }\n\n\n val ans = boys.filter(bf => bf ==0).size + girls.filter(gf => gf == 0).size\n if (ans == 0)\n println(\"Yes\")\n else\n println(\"No\")\n\n }\n\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 19 Jun 2016\n */\nobject B515 extends App {\n\n def checkAllHappy(boys: Array[Boolean], girls: Array[Boolean]): Boolean = {\n boys.foreach((b) => {\n if (!b) {\n return false\n }\n })\n girls.foreach((b) => {\n if (!b) {\n return false\n }\n })\n true\n }\n\n def solve() = {\n val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val b: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val g: Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val boys: Array[Boolean] = Array.ofDim[Boolean](n)\n val girls: Array[Boolean] = Array.ofDim[Boolean](m)\n for (i <- 0 until b.head) {\n boys(b(i+1)) = true\n }\n for (i <- 0 until g.head) {\n girls(g(i+1)) = true\n }\n\n for (i <- 0 until 100 * 100) {\n val boyId = i % n\n val girlId = i % m\n if (boys(boyId) || girls(girlId)) {\n boys(boyId) = true\n girls(girlId) = true\n }\n }\n\n if (checkAllHappy(boys, girls)) {\n println(\"Yes\")\n } else {\n println(\"No\")\n }\n }\n\n solve()\n\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\n\n/**\n * Created by root on 2/21/15.\n */\nobject Drazil2 {\n\n\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val m = sc.nextInt()\n\n val boys = Array.tabulate[Int](n)(_ => 0)\n val girls = Array.tabulate[Int](m)(_ => 0)\n\n (0 until sc.nextInt()) foreach { _ =>\n boys(sc.nextInt()) = 1\n }\n\n (0 until sc.nextInt()) foreach { _ =>\n girls(sc.nextInt()) = 1\n }\n\n val max = n*m\n\n for (i<- 0 until max) {\n val b = i%n\n val g = i%m\n if (boys(b) == 1) {\n girls(g) = 1\n }\n if (girls(g) == 1){\n boys(b) = 1\n }\n }\n\n\n val ans = boys.filter(bf => bf ==0).size + girls.filter(gf => gf == 0).size\n if (ans == 0)\n println(\"Yes\")\n else\n println(\"No\")\n\n }\n\n}\n"}], "src_uid": "65efbc0a1ad82436100eea7a2378d4c2"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M = ni()\n val A = nal(N)\n val cum = cumSum(A)\n val L = nal(M)\n REP(M) { i =>\n val dorm = lowerBound(cum, L(i)) - 1\n out.println(s\"${dorm + 1} ${L(i) - cum(dorm)}\")\n }\n }\n\n // a >= x [x-2, x-1, x, x, x, x+1] の 2\n def lowerBound(a: Array[Long], x: Long): Int = {\n def step(l: Int, h: Int): Int = {\n if (h - l == 1) h\n else {\n val mid = (l + h) / 2\n if (a(mid) >= x) step(l, mid)\n else step(mid, h)\n }\n }\n\n step(-1, a.length)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Long]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object CF_978C {\n\tdef main(args: Array[String]) {\n\t\tval temp_nm = readLine().split(\" \")\n\t\tval n = temp_nm(0).toInt\n\t\tval m = temp_nm(1).toInt\n\t\t\n\t\tval temp_a = readLine().split(\" \")\n\t\tval a = for(x <- temp_a) yield(x.toLong)\n\n\t\tval temp_b = readLine().split(\" \")\n\t\tvar prefix_sum = 0l\n\t\tvar p = 0\n\n\t\tfor(x_str <- temp_b)\n\t\t{\n\t\t\tval x = x_str.toLong\n\t\t\twhile(x - prefix_sum > a(p))\n\t\t\t{\n\t\t\t\tprefix_sum += a(p)\n\t\t\t\tp+=1\n\t\t\t}\n\t\t\tprintf(\"%d %d\\n\",p+1,x-prefix_sum)\n\t\t}\n\n\t}\n}\n"}, {"source_code": "\nobject problemA {\n import java.io.{BufferedReader, FileInputStream, InputStreamReader}\n import scala.collection.mutable.ArrayBuffer\n import scala.collection.mutable\n import scala.util.control.Breaks._\n import scala.collection.JavaConverters._\n\n val source = System.in\n implicit val reader = new BufferedReader(new InputStreamReader(source))\n\n def read()(implicit reader: BufferedReader): String = reader.readLine().split(\" \")(0)\n def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(\" \")\n def readString()(implicit reader: BufferedReader): String = reader.readLine()\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readArray().map(_.toInt)\n val a = readArray().map(_.toLong)\n val f = new Array[Long](n)\n f(0) = a(0)\n for (i <- 1 until n) f(i) = f(i - 1) + a(i)\n\n def find(k: Long): Int = {\n var (l, r) = (0, n - 1)\n var rs = 0\n while (l <= r) {\n val mid = (l + r) / 2\n if (f(mid) < k)\n l = mid + 1\n else {\n r = mid - 1\n rs = mid\n }\n }\n rs\n }\n\n readArray().map(_.toLong).foreach(i => {\n val k = find(i)\n val t = if (k > 0) f(k - 1) else 0\n println(s\"${k + 1} ${i - t}\")\n })\n }\n}\n"}], "negative_code": [], "src_uid": "56bdab2019ee12e18d4f7e17ac414962"} {"source_code": "object B1556 {\n\n import scala.collection.mutable.ArrayBuffer\n\n /** TODO: Check! */\n private val multipleTests: Boolean = true\n\n def run(testNum: Int): Unit = {\n val n = int()\n val a = new ArrayBuffer[Int]()\n var even = 0\n var odd = 0\n for (_ <- 0 until n) {\n val x = int() % 2\n a += x\n if (x % 2 == 0)\n even += 1\n else\n odd += 1\n }\n if ((even - odd).abs > 1) {\n println(-1)\n } else {\n if (even > odd) {\n for (i <- 0 until n)\n a(i) = 1 - a(i)\n }\n var last = 0\n var ans: Long = 0\n for (i <- 0 until n) {\n if (a(i) == 1) {\n ans += (last - i).abs\n last += 2\n }\n }\n if (n % 2 == 0) {\n for (i <- 0 until n)\n a(i) = 1 - a(i)\n var secondAns: Long = 0\n var secondLast = 0\n for (i <- 0 until n) {\n if (a(i) == 1) {\n secondAns += (secondLast - i).abs\n secondLast += 2\n }\n }\n if (ans > secondAns) {\n println(secondAns)\n } else {\n println(ans)\n }\n } else {\n println(ans)\n }\n }\n }\n\n /** Template. */\n\n private val onlineJudge = System.getProperty(\"ONLINE_JUDGE\") != null\n\n def main(args: Array[String]): Unit = {\n val t = if (multipleTests) reader.int() else 1\n (1 to t).foreach(run)\n }\n\n /** I/O. */\n\n import java.io._\n import java.nio.file._\n\n private val inputFileName = \"input.txt\"\n private val reader = if (onlineJudge) FastReader.fromConsole() else FastReader.fromFile(inputFileName)\n\n private def string(): String = reader.string()\n private def int(): Int = reader.int()\n private def long(): Long = reader.long()\n private def double(): Double = reader.double()\n\n /** TODO: implement faster reader with buffer */\n /** TODO: implement writer */\n final case class FastReader(delegate: BufferedReader) extends Iterator[String] with AutoCloseable {\n import java.util.StringTokenizer\n\n def string(): String = next()\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def boolean(): Boolean = next().toBoolean\n def byte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def short(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def int(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def long(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def bigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def float(): Float = next().toFloat\n def double(): Double = next().toDouble\n def bigDecimal(): BigDecimal = BigDecimal(next())\n def lineNumber(): Int = linedDelegate.getLineNumber\n\n @inline def nextLine(): String = {\n current = None // reset the rest of current line\n delegate.readLine()\n }\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n override def next(): String = tokenizer().getOrElse(throw new RuntimeException(\"End of input\")).nextToken()\n override def close(): Unit = delegate.close()\n\n private lazy val linedDelegate = new LineNumberReader(delegate)\n private val tokenizers = Iterator.continually(delegate.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n }\n\n object FastReader {\n import scala.io.Codec\n\n def fromConsole()(implicit codec: Codec): FastReader = fromStream(System.in)\n def fromFile(fileName: String)(implicit codec: Codec): FastReader = FastReader {\n Files.newBufferedReader(Paths.get(fileName), codec.charSet)\n }\n def fromString(string: String): FastReader = FastReader(new BufferedReader(new StringReader(string)))\n def fromStream(inputStream: InputStream)(implicit codec: Codec): FastReader = FastReader {\n new BufferedReader(new InputStreamReader(inputStream, codec.charSet))\n }\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\r\n\r\n def swaps(an: IndexedSeq[Int]): Option[Int] = {\r\n val odds = an.indices.collect { case i if an(i) % 2 == 1 => i }\r\n\r\n def count(startIndex: Int): Int =\r\n (odds zip (startIndex to (an.length, 2))).foldLeft(0) { case (c, (j, i)) => c + math.abs(i - j) }\r\n\r\n (odds.length, an.length - odds.length) match {\r\n case (ol, el) if ol == el => Some(count(0) min count(1))\r\n case (ol, el) if ol == el + 1 => Some(count(0))\r\n case (ol, el) if el == ol + 1 => Some(count(1))\r\n case _ => None\r\n }\r\n }\r\n\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toInt)\r\n\r\n swaps(an) match {\r\n case Some(count) => println(count)\r\n case None => println(-1)\r\n }\r\n }\r\n\r\n}\r\n"}], "negative_code": [], "src_uid": "be51a3e4038bd9a3f6d4993b75a20d1c"} {"source_code": "import annotation.tailrec\n\nobject D {\n def main(args: Array[String]) = {\n val Seq(n, k): Seq[Int] = readInts()\n val c = readInts()\n var r = k\n for (x <- c) {\n r = gcd(r, k / gcd(k, x))\n }\n if (r == 1)\n println(\"Yes\")\n else\n println(\"No\")\n }\n\n @tailrec def gcd(x: Int, y: Int): Int =\n if (y == 0)\n x\n else\n gcd(y, x % y)\n\n def readLine() = io.StdIn.readLine()\n def readInts() = readLine().split(' ').map(_.toInt)\n\n def digits(s: String) = s.map(_.toString.toInt)\n}\n", "positive_code": [{"source_code": "object D {\n def main(args: Array[String]) = {\n val Seq(n, k): Seq[Int] = readInts()\n val c = readInts()\n if (c.map(k / gcd(k, _)).foldLeft(k)(gcd _) == 1)\n println(\"Yes\")\n else\n println(\"No\")\n }\n\n def gcd(x: Int, y: Int): Int =\n if (y == 0)\n x\n else\n gcd(y, x % y)\n\n def readLine() = io.StdIn.readLine()\n def readInts() = readLine().split(' ').map(_.toInt)\n\n def digits(s: String) = s.map(_.toString.toInt)\n}\n"}, {"source_code": "import scala.specialized\n\nobject D {\n def main(args: Array[String]) = {\n val Seq(n, k): Seq[Int] = readInts()\n val c = readInts()\n if (c.map(k / gcd(k, _)).foldLeft(k)(gcd _) == 1)\n println(\"Yes\")\n else\n println(\"No\")\n }\n\n def gcd(x: Int, y: Int): Int =\n if (y == 0)\n x\n else\n gcd(y, x % y)\n\n def readLine() = io.StdIn.readLine()\n def readInts() = readLine().split(' ').map(_.toInt)\n\n def digits(s: String) = s.map(_.toString.toInt)\n}\n"}, {"source_code": "import scala.specialized\n\nobject D {\n def main(args: Array[String]) = {\n val Seq(n, k): Seq[Int] = readInts()\n val c = readInts()\n var r = k\n for (x <- c) {\n r = gcd(r, k / gcd(k, x))\n }\n if (r == 1)\n println(\"Yes\")\n else\n println(\"No\")\n }\n\n def gcd[@specialized T](x: T, y: T)(implicit integral: Integral[T]): T = {\n import integral._\n if (y == 0)\n x\n else\n gcd(y, x % y)\n }\n\n def readLine() = io.StdIn.readLine()\n def readInts() = readLine().split(' ').map(_.toInt)\n\n def digits(s: String) = s.map(_.toString.toInt)\n}\n"}, {"source_code": "import java.io.IOException\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject D {\n def main(args: Array[String]) = {\n val sc = new MyScanner()\n val n = sc.nextInt()\n val k = sc.nextInt()\n var r = k\n for (_i <- 1 to n) {\n val x = sc.nextInt()\n r = gcd(r, k / gcd(k, x))\n }\n if (r == 1)\n println(\"Yes\")\n else\n println(\"No\")\n }\n\n def gcd(x: Int, y: Int): Int =\n if (y == 0)\n x\n else\n gcd(y, x % y)\n\n def readLine() = io.StdIn.readLine()\n def readInts() = readLine().split(' ').map(_.toInt)\n\n def digits(s: String) = s.map(_.toString.toInt)\n\n class MyScanner {\n val br = new BufferedReader(new InputStreamReader(System.in))\n\n var st = new StringTokenizer(br.readLine())\n\n def next(): String = {\n while (!st.hasMoreElements()) {\n try {\n st = new StringTokenizer(br.readLine())\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n st.nextToken()\n }\n\n def nextInt() = next().toInt\n }\n}\n"}, {"source_code": "object D {\n def main(args: Array[String]) = {\n val Seq(n, k): Seq[Int] = readInts()\n val c = readInts()\n var r = k\n for (x <- c) {\n r = gcd(r, k / gcd(k, x))\n }\n if (r == 1)\n println(\"Yes\")\n else\n println(\"No\")\n }\n\n def gcd(x: Int, y: Int): Int =\n if (y == 0)\n x\n else\n gcd(y, x % y)\n\n def readLine() = io.StdIn.readLine()\n def readInts() = readLine().split(' ').map(_.toInt)\n\n def digits(s: String) = s.map(_.toString.toInt)\n}\n"}, {"source_code": "import scala.specialized\n\nobject D {\n def main(args: Array[String]) = {\n val Seq(n, k): Seq[Int] = readInts()\n val c = readInts()\n if (c.map(k / gcd(k, _)).foldLeft(k)(gcd _) == 1)\n println(\"Yes\")\n else\n println(\"No\")\n }\n\n def gcd[@specialized T](x: T, y: T)(implicit integral: Integral[T]): T =\n if (y == 0)\n x\n else\n gcd(y, integral.rem(x, y))\n\n def readLine() = io.StdIn.readLine()\n def readInts() = readLine().split(' ').map(_.toInt)\n\n def digits(s: String) = s.map(_.toString.toInt)\n}\n"}, {"source_code": "import annotation.tailrec\n\nobject D {\n def main(args: Array[String]) = {\n val Seq(n, k): Seq[Int] = readInts()\n val c = readInts()\n if (c.map(k / gcd(k, _)).foldLeft(k)(gcd _) == 1)\n println(\"Yes\")\n else\n println(\"No\")\n }\n\n @tailrec def gcd(x: Int, y: Int): Int =\n if (y == 0)\n x\n else\n gcd(y, x % y)\n\n def readLine() = io.StdIn.readLine()\n def readInts() = readLine().split(' ').map(_.toInt)\n\n def digits(s: String) = s.map(_.toString.toInt)\n}\n"}], "negative_code": [{"source_code": "import scala.specialized\n\nobject D {\n def main(args: Array[String]) = {\n val Seq(n, k): Seq[Int] = readInts()\n val c = readInts()\n var r = k\n for (x <- c) {\n r = gcd(r, k / gcd(k, r))\n }\n if (r == 1)\n println(\"Yes\")\n else\n println(\"No\")\n }\n\n def gcd[@specialized T](x: T, y: T)(implicit integral: Integral[T]): T = {\n import integral._\n if (y == 0)\n x\n else\n gcd(y, x % y)\n }\n\n def readLine() = io.StdIn.readLine()\n def readInts() = readLine().split(' ').map(_.toInt)\n\n def digits(s: String) = s.map(_.toString.toInt)\n}\n"}], "src_uid": "e72fa6f8a31c34fd3ca0ce3a3873ff50"} {"source_code": "import scala.io._\nimport java.util.StringTokenizer\nimport java.io.BufferedReader\n\t\nobject Main {\n\n\tdef main(args: Array[String]): Unit =\n\t{\n\t\tval n = nextInt\n\t\t\n\t\tif (n % 2 == 0)\n\t\t\tprintln(-1)\n\t\telse\n\t\t{\t\t\t\n\t\t\tval a = (0 until n)\n\t\t\tval b = for (i <- 0 until n) yield ((3 + i) % n) \n\t\t\tval c = a zip b map {case (a, b) => ((a+b) % n)}\n\t\t\t\n\t\t\tif (c.sorted != (0 until n))\n\t\t\t\tprintln(\"-1\")\n\t\t\telse\n\t\t\t{\n\t\t\t\tprintln(a mkString(\" \"))\n\t\t\t\tprintln(b mkString(\" \"))\n\t\t\t\tprintln(c mkString(\" \"))\n\t\t\t}\n\t\t}\t\t\t\n\t}\t\n\t\n\tclass Tokenizer(in: BufferedReader, splitOn: String = \" \\n\\t\\r\\f\")\n\t{\n\t\tprivate var tokenizer = new StringTokenizer(\"\")\n\t\tdef readLine() = in.readLine()\t\t\n\t\tdef nextToken(): String = {\n\t\t\twhile (!tokenizer.hasMoreTokens) {\n\t\t\t\tval line = readLine\n\t\t\t\tif (line == null) return null\n\t\t\t\ttokenizer = new StringTokenizer(line, splitOn)\n\t\t\t}\n\t\t\ttokenizer.nextToken\n\t\t}\t\t\n\t\tdef next[A](f: String => A) = f(nextToken)\n\t}\n\t\n\timplicit val tokenizer = new Tokenizer(Console.in)\n\n\tdef nextString()(implicit t: Tokenizer) = t.nextToken()\n\tdef nextInt()(implicit t: Tokenizer) = t.next(_.toInt)\n\tdef nextLong()(implicit t: Tokenizer) = t.next(_.toLong)\n\tdef nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)\n\tdef nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))\n\tdef nextSeq[A](f : () => A, count: Int = nextInt()) = for (i <- 0 until count) yield f()\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n\n if (n % 2 == 0)\n println(\"-1\")\n else {\n val a = 0 until n\n val b = a.map(k => (k + 1) % n)\n val c = a.zip(b).map { case (i, j) => (i + j) % n }\n\n println(a.mkString(\" \"))\n println(b.mkString(\" \"))\n println(c.mkString(\" \"))\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io._\nimport java.util.StringTokenizer\nimport java.io.BufferedReader\n\t\nobject Main {\n\n\tdef main(args: Array[String]): Unit =\n\t{\n\t\tval n = nextInt\n\t\t\n\t\t//if (n % 2 == 0)\n//\t\t\tprintln(-1)\n\t\t//else\n\t\t{\n\t\t\tfor (i <- 0 until n) print(i + \" \")\n\t\t\tprintln\n\t\t\t\n\t\t\tfor (i <- 0 until n) print((3 * i % n) + \" \")\n\t\t\tprintln\n\t\t\t\n\t\t\tfor (i <- 0 until n) print(((4 * i) % n) + \" \")\n\t\t\tprintln\n\t\t}\t\t\t\n\t}\t\n\t\n\tclass Tokenizer(in: BufferedReader, splitOn: String = \" \\n\\t\\r\\f\")\n\t{\n\t\tprivate var tokenizer = new StringTokenizer(\"\")\n\t\tdef readLine() = in.readLine()\t\t\n\t\tdef nextToken(): String = {\n\t\t\twhile (!tokenizer.hasMoreTokens) {\n\t\t\t\tval line = readLine\n\t\t\t\tif (line == null) return null\n\t\t\t\ttokenizer = new StringTokenizer(line, splitOn)\n\t\t\t}\n\t\t\ttokenizer.nextToken\n\t\t}\t\t\n\t\tdef next[A](f: String => A) = f(nextToken)\n\t}\n\t\n\timplicit val tokenizer = new Tokenizer(Console.in)\n\n\tdef nextString()(implicit t: Tokenizer) = t.nextToken()\n\tdef nextInt()(implicit t: Tokenizer) = t.next(_.toInt)\n\tdef nextLong()(implicit t: Tokenizer) = t.next(_.toLong)\n\tdef nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)\n\tdef nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))\n\tdef nextSeq[A](f : () => A, count: Int = nextInt()) = for (i <- 0 until count) yield f()\n}"}, {"source_code": "import scala.io._\nimport java.util.StringTokenizer\nimport java.io.BufferedReader\n\t\nobject Main {\n\n\tdef main(args: Array[String]): Unit =\n\t{\n\t\tval n = nextInt\n\t\t\n\t\tif (n % 2 == 0)\n\t\t\tprintln(-1)\n\t\telse\n\t\t{\n\t\t\tfor (i <- 0 until n) print(i + \" \")\n\t\t\tprintln\n\t\t\t\n\t\t\tfor (i <- 0 until n) print((3 * i % n) + \" \")\n\t\t\tprintln\n\t\t\t\n\t\t\tfor (i <- 0 until n) print(((4 * i) % n) + \" \")\n\t\t\tprintln\n\t\t}\t\t\t\n\t}\t\n\t\n\tclass Tokenizer(in: BufferedReader, splitOn: String = \" \\n\\t\\r\\f\")\n\t{\n\t\tprivate var tokenizer = new StringTokenizer(\"\")\n\t\tdef readLine() = in.readLine()\t\t\n\t\tdef nextToken(): String = {\n\t\t\twhile (!tokenizer.hasMoreTokens) {\n\t\t\t\tval line = readLine\n\t\t\t\tif (line == null) return null\n\t\t\t\ttokenizer = new StringTokenizer(line, splitOn)\n\t\t\t}\n\t\t\ttokenizer.nextToken\n\t\t}\t\t\n\t\tdef next[A](f: String => A) = f(nextToken)\n\t}\n\t\n\timplicit val tokenizer = new Tokenizer(Console.in)\n\n\tdef nextString()(implicit t: Tokenizer) = t.nextToken()\n\tdef nextInt()(implicit t: Tokenizer) = t.next(_.toInt)\n\tdef nextLong()(implicit t: Tokenizer) = t.next(_.toLong)\n\tdef nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)\n\tdef nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))\n\tdef nextSeq[A](f : () => A, count: Int = nextInt()) = for (i <- 0 until count) yield f()\n}"}], "src_uid": "2f0942c531fd5758b220104c3338b702"} {"source_code": "object Main { \n def main(args: Array[String]) {\n val op = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt).sorted\n val m = op(1)\n println(-a.filter(_ < 0).take(m).sum)\n }\n}", "positive_code": [{"source_code": "import java.io.BufferedReader\nimport java.io.IOException\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\nimport java.util.StringTokenizer;\nimport java.util.Arrays\n\nobject Solver {\n\n var st : StringTokenizer = null;\n var in : BufferedReader = null;\n var out : PrintWriter = null;\n\n def main(args: Array[String]){\n open();\n solve();\n close();\n }\n\n def open() {\n in = new BufferedReader(new InputStreamReader(System.in));\n out = new PrintWriter(System.out);\n }\n\n def nextToken() : String = {\n while (st == null || !st.hasMoreTokens()) {\n val line : String = in.readLine();\n if(line==null) return null;\n st = new StringTokenizer(line);\n }\n st.nextToken();\n }\n\n def nextInt() : Int = {\n nextToken().toInt;\n }\n\n def nextLong() : Long = {\n nextToken().toLong;\n }\n\n def nextDouble() : Double = {\n nextToken().toDouble;\n }\n\n def solve(){\n val n:Int = nextInt;\n val m:Int = nextInt;\n val ar:Array[Int] = new Array[Int](n);\n \n for(i <- 0 to n-1){\n ar(i) = nextInt;\n }\n \n Arrays.sort(ar);\n \n var sum : Int = 0;\n var i : Int = 0;\n while (i cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val a = readInts(n).sorted\n println(a.take(m).foldLeft(0){case (sum, i) => if(i < 0) sum - i else sum})\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P034B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N, M = sc.nextInt\n List.fill(N)(sc.nextInt).sorted.takeWhile(_ < 0).take(M).sum.abs\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var Array(n, m) = readLine.split(\" \").map(_.toInt);\n var a = readLine.split(\" \").toList.map(_.toInt).sorted;\n if (a(0) > 0) {\n println(0);\n return;\n }\n var result = 0;\n for (i <- 0 until n if a(i) < 0 && i < m) {\n result -= a(i);\n }\n println(result);\n }\n}"}, {"source_code": " object Sales extends App {\n \tval lines = io.Source.stdin.getLines.toList\n \tval m = {\n \t\tval tokens = lines.head.split(\" \")\n \t\ttokens(1).toInt\n \t}\n \t\n \tprintln(-1 * (lines.last.split(\" \").toList.map(_.toInt).sorted.filter(_ <= 0).take(m).sum))\n }"}], "negative_code": [{"source_code": "object P34B extends App {\n val in = (readLine + \" \" + readLine).split(\" \").map(_.toInt)\n print(in.slice(2,in.size-1).sorted.take(in(1)).takeWhile(_<0).sum * -1)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P034B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N, M = sc.nextInt\n List.fill(N)(sc.nextInt).sorted.takeWhile(_ < 0).take(M).sum\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": " object Sales extends App {\n \tval lines = io.Source.stdin.getLines.toList\n \tval m = {\n \t\tval tokens = lines.head.split(\" \")\n \t\ttokens(1).toInt\n \t}\n \t\n \tprintln(-1 * (lines.last.split(\" \").toList.map(_.toInt).sorted.take(m).sum))\n }"}], "src_uid": "9a56288d8bd4e4e7ef3329e102f745a5"} {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n /*\n 0 - 6 x\n 1 - 2\n 2 - 5 x\n 3 - 5 x\n 4 - 4 x\n 5 - 5 x\n 6 - 6 x\n 7 - 3\n 8 - x\n 9 - x\n\n 2 - 1\n 3 - 7\n 4 - 11\n 5 - 71\n 6 - 111\n 7 - 711\n 8 - 1111\n 9 - 7111\n\n\n */\n val t = readInt()\n 1 to t foreach { _ =>\n val n = readInt()\n val answer =\n if (n % 2 == 0) \"1\" * (n / 2)\n else \"7\" + (\"1\" * (n / 2 - 1))\n\n println(answer)\n }\n}\n", "positive_code": [{"source_code": "object Main extends App{\n // extends App {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n solve(System.in,System.out)\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val cases = in.nextInt()\n val sb = new mutable.StringBuilder()\n (1 to cases).foreach{ _ =>\n val n = in.nextInt()\n val numOnes = n/2-1\n val first = if(n%2==1) '7' else '1'\n sb.append(first)\n (1 to numOnes).foreach(_ => sb.append('1'))\n sb.append(System.lineSeparator())\n\n\n }\n out.println(sb.toString())\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n /*\n 0 - 6 x\n 1 - 2\n 2 - 5 x\n 3 - 5 x\n 4 - 4 x\n 5 - 5 x\n 6 - 6 x\n 7 - 3\n 8 - x\n 9 - x\n\n */\n val t = readInt()\n 1 to t foreach { _ =>\n val n = readInt()\n var sevens = n / 3\n var ones = (n % 3)\n\n if (ones % 2 == 0) {\n ones = ones / 2\n } else {\n ones = ones / 2 + 2\n sevens -= 1\n }\n\n println((\"7\" * sevens) + (\"1\" * ones))\n }\n}\n"}], "src_uid": "07db573b0db736d798b6c18c06c32f3d"} {"source_code": "import scala.io.StdIn.readInt\r\nobject _1633A{\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt()\r\n while(t > 0){\r\n t-=1\r\n var n = readInt();\r\n if(n % 7 == 0)println(n)\r\n else {\r\n n = (n / 10) * 10\r\n loop10(n)\r\n }\r\n }\r\n }\r\n def loop10 (n : Int): Any ={\r\n for (i <- n to n + 10) {\r\n if (i % 7 == 0) {\r\n println(i)\r\n return\r\n }\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.io.StdIn.readInt\r\n\r\nobject cf1633a {\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt()\r\n while(t > 0) {\r\n t -= 1\r\n var n = readInt()\r\n if(n % 7 == 0) println(n)\r\n else {\r\n var found = false\r\n for(i <- ((n / 10) * 10) to (n + 10)) {\r\n if(i % 7 == 0 && !found) {\r\n println(i)\r\n found = true\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val number = readInt()\n val minNumber = number/7 * 7\n val maxNumber = minNumber + 7\n val answer = if (minNumber / 10 == number / 10) minNumber else maxNumber\n println(answer)\n }\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "object Div7 extends App {\r\n def changeToDiv7(i: Int): Int = {\r\n val rest7 = i % 7\r\n if (rest7 == 0) i\r\n else i - rest7 + (if (i % 10 - rest7 >= 0) 0 else 7)\r\n }\r\n \r\n val lines = io.Source.stdin.getLines\r\n val t = lines.next.toInt\r\n (1 to t).foreach(_ => println(changeToDiv7(lines.next.toInt)))\r\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn.readInt\r\n\r\nobject cf1633a {\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt()\r\n while(t > 0) {\r\n t -= 1\r\n var n = readInt()\r\n if(n % 7 == 0) println(n)\r\n else {\r\n var found = false\r\n for(i <- (n - 10) to (n + 10)) {\r\n if(i % 7 == 0 && !found) {\r\n println(i)\r\n found = true\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn.readInt\r\n\r\nobject cf1633a {\r\n def main(args: Array[String]): Unit = {\r\n var t = readInt()\r\n while(t > 0) {\r\n t -= 1\r\n var n = readInt()\r\n if(n % 7 == 0) println(n)\r\n else {\r\n var found = false\r\n for(i <- (n - 10) to (n + 10)) {\r\n if(i % 7 == 0 && !found) {\r\n println(i)\r\n found = false\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}\r\n"}], "src_uid": "128372d890f632494e59e81287abd85a"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val set = data.toSet\n var ir = -1\n var jr = -1\n var kr = -1\n val result = (0 until n - 1).foreach { i =>\n val f = (i + 1 until n).find(j => set.contains(data(i) + data(j)))\n if (f.nonEmpty) {\n ir = i + 1\n jr = f.get + 1\n kr = data.indices.find(x => data(x) == data(i) + data(f.get)).get + 1\n }\n\n }\n if (ir != -1)\n println(s\"$kr $jr $ir\")\n else\n println(-1)\n}", "positive_code": [{"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var n = readInt;\n var arr = readLine.split(\" \").map(_.toInt);\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n for (k <- 0 until n) {\n if (i != j && i != k && j != k) {\n if (arr(i) == arr(j) + arr(k)) {\n println((i + 1) + \" \" + (j + 1) + \" \" + (k + 1));\n return;\n }\n }\n }\n }\n }\n println(\"-1\");\n }\n\n}"}], "negative_code": [], "src_uid": "94a38067fc8dd8619fa6e5873ca60220"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val sor = in.take(n).map(_.toLong).toArray.sorted\n println(sor.zip(sor.reverse).map(i => i._1 * i._2 % 10007).sum[Long] % 10007)\n}", "positive_code": [{"source_code": " import scala.io.StdIn\n import scala.util.Sorting\n\n object Solution extends App {\n val n = StdIn.readInt\n val a = (1 to n).map(_ => StdIn.readInt).toArray\n\n Sorting.quickSort(a)\n val middle = if (n % 2 == 0) n / 2 - 1 else n / 2\n\n var r: Long = 0\n for (i <- 0 to middle) {\n var v = a(i).toLong * a(n - i - 1)\n if (i != n - i - 1) {\n v *= 2\n }\n r += v\n }\n\n println(r % 10007)\n }"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val sor = in.take(n).map(_.toInt % 10007).toArray.sorted\n println((0 until n).foldLeft(0) {\n case (acc, i) => (acc + sor(i) * sor(n - i - 1)) % 10007\n })\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val sor = in.take(n).map(_.toInt).toArray.sorted\n println((0 until n / 2).foldLeft(if (n % 2 == 0) 0 else sor(n / 2)) {\n case (acc, i) => (i + 2 * sor(i) * sor(n - i - 1)) % 10007\n })\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val sor = in.take(n).map(_.toLong).toArray.sorted\n println((0 until n / 2).foldLeft(if (n % 2 == 0) 0l else sor(n / 2) * sor(n / 2) % 10007) {\n case (acc, i) => (i + 2 * sor(i) * sor(n - i - 1)) % 10007\n })\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val sor = in.take(n).map(_.toLong % 10007).toArray.sorted\n println(sor.zip(sor.reverse).map(i => i._1 * i._2 % 10007).sum[Long] % 10007)\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val sor = in.take(n).map(_.toInt).toArray.sorted\n println((0 until n / 2).foldLeft(if (n % 2 == 0) 0 else sor(n / 2) * sor(n / 2)) {\n case (acc, i) => (i + 2 * sor(i) * sor(n - i - 1)) % 10007\n } % 10007)\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val sor = in.take(n).map(_.toInt % 10007).toArray.sorted\n println((0 until n / 2).foldLeft(if (n % 2 == 0) 0 else sor(n / 2) * sor(n / 2) % 10007) {\n case (acc, i) => (acc + 2 * sor(i) * sor(n - i - 1)) % 10007\n })\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val sor = in.take(n).map(_.toLong % 10007).toArray.sorted\n println((0 until n).foldLeft(0l) {\n case (acc, i) => (acc + sor(i) * sor(n - i - 1)) % 10007\n })\n}"}, {"source_code": " import scala.io.StdIn\n import scala.util.Sorting\n\n object Solution extends App {\n val n = StdIn.readInt\n val a = (1 to n).map(_ => StdIn.readInt).toArray\n\n Sorting.quickSort(a)\n val middle = if (n % 2 == 0) n / 2 - 1 else n / 2\n\n var r: Long = 0\n for (i <- 0 to middle) {\n var v = a(i) * a(n - i - 1)\n if (i != n - i - 1) {\n v *= 2\n }\n r += v\n }\n\n println(r % 10007)\n }"}, {"source_code": " import scala.io.StdIn\n import scala.util.Sorting\n\n object Solution extends App {\n val n = StdIn.readInt\n val a = (1 to n).map(_ => StdIn.readInt).toArray\n\n Sorting.quickSort(a)\n val middle = if (n % 2 == 0) n / 2 - 1 else n / 2\n\n var r: Long = 0\n for (i <- 0 to middle) {\n var v: Long = a(i) * a(n - i - 1)\n if (i != n - i - 1) {\n v *= 2\n }\n r += v\n }\n\n println(r % 10007)\n }"}, {"source_code": " import scala.io.StdIn\n import scala.util.Sorting\n\n object Solution extends App {\n val n = StdIn.readInt\n val a = (1 to n).map(_ => StdIn.readInt).toArray\n\n Sorting.quickSort(a)\n val middle = if (n % 2 == 0) n / 2 - 1 else n / 2\n\n var r: Long = 0\n for (i <- 0 to middle) {\n var v = a(i) * a(n - i - 1)\n if (i != n - i - 1) {\n v *= 2\n }\n r += v\n }\n\n println(r)\n }"}], "src_uid": "f5acd95067656fa7667210af2c9bec81"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n var visited = Set.empty[Int]\n var visited2 = Set.empty[Int]\n val n = in.next().toInt\n val res = (1 to n * n).filter { i =>\n val Array(x, y) = in.next().split(\" \").map(_.toInt)\n if (visited.contains(x) || visited2.contains(y))\n false\n else {\n visited += x\n visited2 += y\n true\n }\n }\n println(res.mkString(\" \"))\n}", "positive_code": [{"source_code": "object Program{\n\tdef main(ins:Array[String]){\n\t\tvar ins = new Array[Int](2);\n\t\tvar n = readInt();\n\t\tvar x = new Array[Int](n); var y = new Array[Int](n)\n\t\tvar a = 0; var b = 0\n\t\tfor (i <-1 to n*n){\n\t\t\tins = readLine.split(\" \").map(_.toInt)\n\t\t\ta = ins(0); b = ins(1)\n\t\t\tif (x(a - 1) == 0 && y(b - 1) == 0){ \n\t\t\t\tx(a - 1) = 1; y(b - 1) = 1\n\t\t\t\tprint(i+\" \")\n\t\t\t}\n\t\t}\n\t}\n}\n"}, {"source_code": "object A583 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val row = Array.fill[Boolean](n)(false)\n val col = Array.fill[Boolean](n)(false)\n var res = Array.empty[Int]\n for(i <- 0 until n*n) {\n val arr = readInts(2)\n if(!row(arr(0)-1) && !col(arr(1)-1)) {\n row(arr(0)-1) = true\n col(arr(1)-1) = true\n res = res ++ Array(i+1)\n }\n }\n println(res.mkString(\" \"))\n }\n}"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _583A extends CodeForcesApp[Seq[Int]]({scanner => import scanner._\n val n = nextInt\n val vs = bag[Int]\n val hs = bag[Int]\n\n val ans = for {\n d <- 1 to n*n\n (i, j) = (nextInt, nextInt)\n if !(vs contains i) && !(hs contains j)\n } yield {\n vs.add(i)\n hs.add(j)\n d\n }\n\n ans\n}) {\n override def format(result: Result) = result mkString \" \"\n}\n/********************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)\n final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n import scala.collection.mutable.{Map => Dict, Set => Bag}\n final def nil[A]: List[A] = List.empty[A]\n final def bag[A]: Bag[A] = Bag.empty[A]\n final def map[A] = new {\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\n\nobject A extends App {\n\n val H = Array.ofDim[Boolean](51)\n val V = Array.ofDim[Boolean](51)\n\n def needWork(h: Int, v: Int) = {\n if (H(h) || V(v)) {\n false\n } else {\n H(h) = true\n V(v) = true\n true\n }\n }\n\n val n = readInt()\n val answer = new ArrayBuffer[Int]\n for (i <- 1 to n*n) {\n val Array(h, v) = readLine().split(\" \").map(_.toInt)\n if (needWork(h, v)) answer += i\n }\n\n println(answer.mkString(\" \"))\n\n}\n"}, {"source_code": "import java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject A_Asphalt {\n\n def main(args: Array[String]): Unit = {\n var debugV = false\n def db(x: => String) = if (debugV) println(x) // nullary function\n \n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(sa1.trim.getBytes(\"ISO-8859-1\"))\n// debugV = true\n\n val bis = new BufferedInputStream(is);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n //---------------------------- parameters reading ------------------------------------\n val line1 = new StringTokenizer(br.readLine())\n val number = line1.nextToken().toInt\n \n val hor = Array.fill(number+1)(false)\n val ver = Array.fill(number+1)(false)\n \n var res = new StringBuffer();\n for (i <- 0 until number*number) {\n val line = br.readLine().split(\" \")\n val h = line(0).toInt\n val v = line(1).toInt\n if (!hor(h) && !ver(v)) {\n res.append(i+1).append(\" \")\n hor(h) = true\n ver(v) = true\n }\n }\n \n println(res)\n \n \n //---------------------------- parameters reading end --------------------------------\n \n \n }\n\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n var visited = Set.empty[Int]\n val n = in.next().toInt\n val res = (1 to n * n).filter { i =>\n val Array(x, y) = in.next().split(\" \").map(_.toInt)\n if (visited.contains(x) || visited.contains(y))\n false\n else {\n visited += x\n visited += y\n true\n }\n }\n println(res.mkString(\" \"))\n}"}, {"source_code": "object A583 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val row = Array.fill[Boolean](n)(false)\n val col = Array.fill[Boolean](n)(false)\n var res = Array.empty[Int]\n for(i <- 0 until n*n) {\n val arr = readInts(2)\n if(!row(arr(0)-1) && !row(arr(1)-1)) {\n row(arr(0)-1) = true\n row(arr(1)-1) = true\n res = res ++ Array(i+1)\n }\n }\n println(res.mkString(\" \"))\n }\n}"}], "src_uid": "c611808e636d9307e6df9ee0e706310b"} {"source_code": "import scala.io.StdIn._\n\n//package month11.codeforces.round378\n\nobject TaskB extends App {\n val n = readInt()\n val A = Array.ofDim[(Int, Int)](n)\n var Left = 0\n var Right = 0\n\n 0 until n foreach { i =>\n val Array(l, r) = readLine().split(\" \").map(_.toInt)\n val tuple = (l, r)\n A(i) = tuple\n Left += l\n Right += r\n }\n\n var max = Math.abs(Left - Right)\n var maxId = -1\n\n 0 until n foreach { i =>\n val (l, r) = A(i)\n val newLeft = Left - l + r\n val newRight = Right - r + l\n val maybeMax = Math.abs(newLeft - newRight)\n if (maybeMax > max) {\n max = maybeMax\n maxId = i\n }\n }\n\n println(maxId + 1)\n}\n", "positive_code": [{"source_code": "import java.io._\n\nimport ProblemB.IndexedValue\n\nimport scala.io.Source\nimport scala.annotation.tailrec\n\nobject ProblemB {\n def main(args: Array[String]): Unit = processStdInOut()\n\n def processStdInOut(): Unit = {\n val src = Source.fromInputStream(System.in)\n processFromSource(src)\n }\n\n def processFromSource(src: Source): Unit = {\n try {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out));\n try {\n val lines = src.getLines()\n processLines(lines, bw)\n } finally {\n bw.flush()\n }\n } finally {\n src.close();\n }\n }\n\n // Standard code above, custom code below\n case class IndexedValue(index: Int, value: Int) extends Ordered[IndexedValue] {\n def compare(that: IndexedValue) = math.abs(this.value).compare(math.abs(that.value))\n }\n\n def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {\n val n = lines.next().toInt\n var minLMinusR = IndexedValue(0, 0)\n var maxLMinusR = IndexedValue(0, 0)\n var totalLMinusR = 0\n\n for (i <- 1 to n) {\n val column = lines.next.split(\" \").map(_.toInt)\n val l = column(0)\n val r = column(1)\n val lMinusR = l - r\n totalLMinusR += lMinusR\n if (minLMinusR.value > lMinusR) minLMinusR = IndexedValue(i, lMinusR)\n if (maxLMinusR.value < lMinusR) maxLMinusR = IndexedValue(i, lMinusR)\n }\n\n val indexedVals = List(\n IndexedValue(0, totalLMinusR), // Order important, so that changes aren't made unnecessarily\n IndexedValue(minLMinusR.index, totalLMinusR - 2 * minLMinusR.value),\n IndexedValue(maxLMinusR.index, totalLMinusR - 2 * maxLMinusR.value)\n )\n val bestIndVal = indexedVals.max\n bw.write(bestIndVal.index.toString)\n bw.newLine()\n }\n}\n"}, {"source_code": "object B733 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n case class Column(l: Int, r: Int)\n val input = new Array[Column](n)\n\n def beauty(in: Array[Column]): Int = {\n math.abs(in.map(_.l).sum - in.map(_.r).sum)\n }\n\n for (i <- 0 to n-1) {\n val Array(l, r) = readInts(2)\n input(i) = Column(l, r)\n }\n\n var ret = 0\n val L = input.map(_.l).sum\n val R = input.map(_.r).sum\n var max = math.abs(L-R)\n for (i <- 0 to n-1) {\n val beautyi = math.abs(L-input(i).l+input(i).r - (R-input(i).r+input(i).l))\n if(beautyi > max) {\n ret = i + 1\n max = beautyi\n }\n }\n\n println(ret)\n }\n}"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _733B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val soldiers = read[Vector[(Int, Int)]]\n\n var l, r = 0\n soldiers foreach {case (i, j) =>\n l += i\n r += j\n }\n\n var beauty = (l - r).abs\n var ans = 0\n\n soldiers.zipWithIndex foreach {case ((i, j), k) =>\n val nl = l - i + j\n val nr = r - j + i\n val nb = (nl - nr).abs\n if (nb > beauty) {\n beauty = nb\n ans = k + 1\n }\n }\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _733B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val soldiers = read[Vector[(Int, Int)]]\n\n val (l, r) = {\n var _l, _r = 0\n soldiers foreach {case (i, j) =>\n _l += i\n _r += j\n }\n (_l, _r)\n }\n\n var beauty = (l - r).abs\n var ans = 0\n\n soldiers.zipWithIndex foreach {case ((i, j), k) =>\n val nl = l - i + j\n val nr = r - j + i\n val nb = (nl - nr).abs\n if (nb > beauty) {\n beauty = nb\n ans = k+1\n }\n }\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _733B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val soldiers = read[Vector[(Int, Int)]]\n\n var l, r = 0\n soldiers foreach {case (i, j) =>\n l += i\n r += j\n }\n\n var beauty = (l - r).abs\n var ans = 0\n\n soldiers.zipWithIndex foreach {case ((i, j), k) =>\n val nl = l - i + j\n val nr = r - j + i\n val nb = (nl - nr).abs\n if (nb > beauty) {\n beauty = nb\n ans = k+1\n }\n }\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "//package xubiker\n\nimport java.util.Scanner\n\n/**\n * Created by xubiker on 04-Dec-16.\n */\nobject Task_733B extends App {\n\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n\n var sumL: Int = 0\n var sumR: Int = 0\n\n var maxDiff = -2000\n var minDiff = 2000\n var maxDiffIdx = -1\n var minDiffIdx = -1\n\n for (i <- 1 to n) {\n val l = sc.nextInt\n val r = sc.nextInt\n sumL += l\n sumR += r\n val diff = l - r\n if (diff > maxDiff) {\n maxDiff = diff\n maxDiffIdx = i\n }\n if (diff < minDiff) {\n minDiff = diff\n minDiffIdx = i\n }\n }\n\n val curr = Math.abs(sumL - sumR)\n val v1 = Math.abs((sumL - maxDiff) - (sumR + maxDiff))\n val v2 = Math.abs((sumL - minDiff) - (sumR + minDiff))\n\n val idx = if (v1 > v2) maxDiffIdx else minDiffIdx\n\n val res = if (curr < v1.max(v2)) idx else 0\n\n println(res)\n\n sc.close()\n}\n"}, {"source_code": "object _733B extends App {\n val in = io.Source.fromInputStream(System.in).getLines()\n val cols = in.take(in.next().toInt).toSeq.map {\n s =>\n val sp = s.split(\"\\\\s+\")\n (sp(0).toInt, sp(1).toInt)\n }\n val ((imin, dmin), (imax, dmax), suml, sumr) = cols.zipWithIndex.foldLeft(((0, Integer.MAX_VALUE), (0, Integer.MIN_VALUE), 0, 0)) {\n case (((imin, dmin), (imax, dmax), l, r), ((cl, cr), idx)) => {\n val d = cl - cr\n (if (d < dmin) (idx, d) else (imin, dmin),\n if (d > dmax) (idx, d) else (imax, dmax),\n l + cl,\n r + cr)\n }\n }\n def b(l: Int, r: Int) = Math.abs(l - r)\n println(Seq((0, b(suml, sumr)), (imin + 1, b(suml - dmin, sumr + dmin)), (imax + 1, b(suml - dmax, sumr + dmax))).maxBy(_._2)._1)\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n\n val l = new Array[Int](n)\n val r = new Array[Int](n)\n val diff = new Array[Int](n)\n var cnt = 0\n\n for(i <- 0 until n){\n l(i) = sc.nextInt()\n r(i) = sc.nextInt()\n diff(i) = l(i) - r(i)\n cnt += diff(i)\n }\n\n var ind = 0\n var now = 0\n if(cnt == 0){\n for(i <- 0 until n){\n if(now < Math.abs(diff(i))){\n ind = i + 1\n now = Math.abs(diff(i))\n } \n }\n }\n else {\n now = Math.abs(cnt)\n for(i <- 0 until n){\n if(now < Math.abs(cnt - 2 * diff(i))){\n ind = i + 1\n now = Math.abs(cnt - 2 * diff(i))\n } \n }\n }\n\n println(ind)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val lr = in.take(n).map(l => l.split(' ').map(_.toInt)).toList\n val l = lr.map(_.head).sum\n val r = lr.map(_.last).sum\n val diff = Math.abs(l - r)\n\n val res = lr.map(e => Math.abs(l - 2 * e.head + 2 * e.last - r)).zipWithIndex.filter(_._1 > diff)\n\n if (res.isEmpty)\n println(0)\n else\n println(res.maxBy(_._1)._2 + 1)\n}\n\n\n"}, {"source_code": "\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n input.next()\n val lrs = input.toSeq.map(line => line.split(' ').map(_.toInt))\n val lness = lrs.map(arr => arr(0) - arr(1)).sum\n val change = lrs.map(arr => (lness + arr(1) * 2 - arr(0) * 2).abs).zipWithIndex.maxBy(_._1)\n val k = if (change._1 > lness.abs) change._2 + 1 else 0\n print(k)\n }\n}\n"}], "negative_code": [{"source_code": "\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n input.next()\n val lrs = input.toSeq.map(line => line.split(' ').map(_.toInt))\n val lness = lrs.map(arr => arr(0) - arr(1)).sum\n val change = lrs.map(arr => lness + arr(1) * 2 - arr(0) * 2).zipWithIndex.maxBy(_._1.abs)\n val k = if (change._1 > lness.abs) change._2 + 1 else 0\n print(k)\n }\n}\n"}, {"source_code": "\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n input.next()\n val lrs = input.toSeq.map(line => line.split(' ').map(_.toInt))\n val lness = lrs.map(arr => arr(0) - arr(1)).sum\n val change = lrs.map(arr => lness + arr(1) * 2 - arr(0) * 2).zipWithIndex.minBy(_._1.abs)\n val k = if (change._1 < lness.abs) change._2 + 1 else 0\n print(k)\n }\n}\n"}], "src_uid": "2be73aa00a13be5274cf840ecd3befcb"} {"source_code": "object StringLCM {\r\n\r\n import scala.io.{StdIn => in}\r\n import scala.util.control._\r\n \r\n def main(args: Array[String]) = {\r\n var t = in.readInt()\r\n while (t > 0) {\r\n var a = in.readLine()\r\n var b = in.readLine()\r\n var c = a\r\n var d = b;\r\n while (c.length <= 400)\r\n c += a\r\n while (d.length <= 400)\r\n d += b\r\n var x, y: String = \"\"\r\n var ans: Int = -1\r\n var ansString: String = \"\"\r\n val loop = new Breaks\r\n loop.breakable {\r\n for (i <- 0 to 400) {\r\n x += c(i)\r\n y += d(i)\r\n if (x == y && (i + 1) % a.length == 0 && (i + 1) % b.length == 0) {\r\n ans = i\r\n ansString = x\r\n loop.break\r\n }\r\n }\r\n }\r\n if (ans == -1)\r\n println(ans)\r\n else println(ansString)\r\n t -= 1;\r\n }\r\n }\r\n\r\n}", "positive_code": [{"source_code": "object StringLCM {\r\n\r\n import scala.io.{StdIn => in}\r\n import scala.util.control._\r\n\r\n def gcd(a: Int, b: Int): Int = {\r\n if(b ==0) a else gcd(b, a % b)\r\n }\r\n\r\n def main(args: Array[String]) = {\r\n var t = in.readInt()\r\n while (t > 0) {\r\n var a = in.readLine()\r\n var b = in.readLine()\r\n var c = a\r\n var d = b;\r\n while (c.length <= 400)\r\n c += a\r\n while (d.length <= 400)\r\n d += b\r\n var jump = a.length * b.length / gcd(a.length, b.length)\r\n var x, y: String = \"\"\r\n var ans: Int = -1\r\n var ansString: String = \"\"\r\n val loop = new Breaks\r\n loop.breakable {\r\n for (i <- 0 to 400) {\r\n x += c(i)\r\n y += d(i)\r\n if (x == y && (i + 1) % a.length == 0 && (i + 1) % b.length == 0) {\r\n ans = i\r\n ansString = x\r\n loop.break\r\n }\r\n }\r\n }\r\n if (ans == -1)\r\n println(ans)\r\n else println(ansString)\r\n t -= 1;\r\n }\r\n }\r\n\r\n}"}, {"source_code": "object firstdemo extends App {\r\n\r\n def readString() : String = {\r\n val yo = scala.io.StdIn.readLine()\r\n yo\r\n }\r\n def readInt() : Int = {\r\n val yo = scala.io.StdIn.readInt();\r\n yo\r\n }\r\n\r\n def gcd(a: Int, b: Int): Int =\r\n if (b == 0) a else gcd(b, a % b)\r\n\r\n var t = readInt()\r\n\r\n while(t > 0) {\r\n\r\n val s = readString()\r\n val s1 = readString()\r\n\r\n val x = s.length\r\n val y = s1.length\r\n\r\n val lcm = x * y / gcd(x , y)\r\n\r\n val temp = lcm / x\r\n\r\n var actual = \"\"\r\n for(i <- 0 until temp) {\r\n actual += s\r\n }\r\n var flag = 0\r\n\r\n for(i <- 0 until actual.length by x) {\r\n val temp = actual.substring(i , i + x)\r\n if(temp != s) {\r\n flag = 1\r\n }\r\n }\r\n\r\n for(i <- 0 until actual.length by y) {\r\n val temp = actual.substring(i , i + y)\r\n if(temp != s1) {\r\n flag = 1\r\n }\r\n }\r\n if(flag == 0) {\r\n println(actual)\r\n }\r\n else {\r\n println(\"-1\")\r\n }\r\n // print(actual)\r\n\r\n t = t - 1\r\n }\r\n\r\n}\r\n\r\n/*import org.apache.spark.sql.sources.LessThanOrEqual\r\npackage com.spark.demo\r\nimport org.apache.spark.sql.SparkSession\r\nimport org.apache.spark.{SparkConf, SparkContext}*/\r\n"}], "negative_code": [], "src_uid": "710c7211d23cf8c01fae0b476a889276"} {"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rLens = Array.fill(n - 1)(0)\n val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n val abToRoad = mutable.Map.empty[(Int, Int), Int]\n\n for (i <- 0 until n - 1) {\n val Array(_a, _b, l) = readInts(3)\n val a = _a - 1\n val b = _b - 1\n adjBuilders(a) += b\n adjBuilders(b) += a\n abToRoad += (a, b) -> i\n abToRoad += (b, a) -> i\n rLens(i) = l\n }\n\n val adjs = adjBuilders.map(_.result)\n val incoming, outgoing = Array.fill(n - 1)(0)\n\n def dfs(u: Int, cnt: Int, parent: Int): Int = {\n var add = 1\n for (v <- adjs(u)) {\n if (v != parent) {\n val c = dfs(v, cnt + 1, u)\n val r = abToRoad((u, v))\n incoming(r) = n - c\n outgoing(r) = c\n add += c\n }\n }\n add\n }\n\n dfs(0, 1, -1)\n\n var total = 0d\n for (i <- 0 until n - 1) total += rLens(i).toDouble * incoming(i) * outgoing(i)\n\n val Array(q) = readInts(1)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (i <- 0 until q) {\n val Array(_r, w) = readInts(2)\n val r = _r - 1\n val delta = rLens(r) - w\n rLens(r) = w\n total -= delta.toDouble * incoming(r) * outgoing(r)\n println(total * 3 / n / (n - 1) * 2)\n }\n\n Console.flush\n}\n", "positive_code": [{"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rLens = Array.fill(n - 1)(0)\n val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n val abToRoad = mutable.Map.empty[(Int, Int), Int]\n\n for (i <- 0 until n - 1) {\n val Array(_a, _b, l) = readInts(3)\n val a = _a - 1\n val b = _b - 1\n adjBuilders(a) += b\n adjBuilders(b) += a\n abToRoad += (a, b) -> i\n abToRoad += (b, a) -> i\n rLens(i) = l\n }\n\n val adjs = adjBuilders.map(_.result)\n val incoming, outgoing = Array.fill(n - 1)(0)\n\n def dfs(u: Int, parent: Int): Int = {\n var add = 1\n for (v <- adjs(u)) {\n if (v != parent) {\n val cnt = dfs(v, u)\n val r = abToRoad((u, v))\n incoming(r) = n - cnt\n outgoing(r) = cnt\n add += cnt\n }\n }\n add\n }\n\n dfs(0, -1)\n\n var total = 0d\n for (i <- 0 until n - 1) total += rLens(i).toDouble * incoming(i) * outgoing(i)\n\n val Array(q) = readInts(1)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (i <- 0 until q) {\n val Array(_r, w) = readInts(2)\n val r = _r - 1\n val delta = rLens(r) - w\n rLens(r) = w\n total -= delta.toDouble * incoming(r) * outgoing(r)\n println(total * 3 / n / (n - 1) * 2)\n }\n\n Console.flush\n}"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rLens = Array.fill(n - 1)(0)\n val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n val abToRoad = mutable.Map.empty[(Int, Int), Int]\n\n for (i <- 0 until n - 1) {\n val Array(_a, _b, l) = readInts(3)\n val a = _a - 1\n val b = _b - 1\n adjBuilders(a) += b\n adjBuilders(b) += a\n abToRoad += (a, b) -> i\n abToRoad += (b, a) -> i\n rLens(i) = l\n }\n\n val adjs = adjBuilders.map(_.result)\n val visited = new mutable.BitSet(n)\n val incoming, outgoing = Array.fill(n - 1)(0)\n\n def dfs(u: Int, cnt: Int): Int = {\n visited += u\n var add = 1\n val ne = new mutable.ArrayBuilder.ofInt\n val cs = new mutable.ArrayBuilder.ofInt\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n ne += v\n if (!visited(v)) {\n val c = dfs(v, cnt + 1)\n cs += c\n add += c\n } else cs += 0\n }\n val nes = ne.result\n val css = cs.result\n for (i <- nes.indices) {\n val v = nes(i)\n val r = abToRoad((u, v))\n incoming(r) = n - css(i)\n outgoing(r) = css(i)\n }\n add\n }\n\n dfs(0, 1)\n\n var total = 0d\n for (i <- 0 until n - 1) total += rLens(i).toDouble * incoming(i) * outgoing(i)\n\n val Array(q) = readInts(1)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n \n for (i <- 0 until q) {\n val Array(_r, w) = readInts(2)\n val r = _r - 1\n val delta = rLens(r) - w\n rLens(r) = w\n total -= delta.toDouble * incoming(r) * outgoing(r)\n println(total * 3 / n / (n - 1) * 2)\n }\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val rLens = Array.fill(n - 1)(0)\n //val adjs = Array.fill(n)(0)\n val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n val as = Array.fill(n)(0)\n val bs = Array.fill(n)(0)\n val isLeaf = Array.fill(n - 1)(true)\n val abToRoad = mutable.Map.empty[(Int, Int), Int]\n for (i <- 0 until n - 1) {\n val Array(_a, _b, l) = readInts(3)\n val a = _a - 1\n val b = _b - 1\n //adjs(a - 1) += 1\n //adjs(b - 1) += 1\n adjBuilders(a) += b\n adjBuilders(b) += a\n abToRoad += (a, b) -> i\n abToRoad += (b, a) -> i\n as(i) = a - 1\n bs(i) = b - 1\n rLens(i) = l\n }\n\n val adjs = adjBuilders.map(_.result)\n val visited = new mutable.BitSet(n)\n val incoming, outgoing = Array.fill(n - 1)(0)\n\n def dfs(u: Int, cnt: Int): Int = {\n visited += u\n var add = 1\n val ne = new mutable.ArrayBuilder.ofInt\n val cs = new mutable.ArrayBuilder.ofInt\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n ne += v\n if (!visited(v)) {\n val c = dfs(v, cnt + 1)\n cs += c\n add += c\n } else cs += 0\n }\n val nes = ne.result\n val css = cs.result\n for (i <- nes.indices) {\n val v = nes(i)\n val r = abToRoad((u, v))\n incoming(r) = n - css(i)\n outgoing(r) = css(i)\n }\n add\n }\n\n dfs(0, 1)\n\n //for (i <- 0 until n - 1)\n //if (adjs(as(i)) > 1 && adjs(bs(i)) > 1) isLeaf(i) = false\n def c(k: Int, n: Int): Long = {\n var result = 1L\n var i = 1\n var lim = math.min(k, n - k)\n while (i <= lim) {\n result = result * (n - i + 1)\n result = result / i\n i += 1\n }\n result\n }\n \n def fib(n: Int): Double = {\n var i1 = 1d\n var i2 = 1d\n for (i <- 2 until n) {\n val x = i1 + i2\n i1 = i2\n i2 = x\n }\n i2\n }\n val f = fib(n - 1)\n\n var total = 0d\n for (i <- 0 until n - 1) total += rLens(i) * incoming(i) * outgoing(i)\n //println(incoming.mkString(\" \"))\n //println(outgoing.mkString(\" \"))\n val Array(q) = readInts(1)\n for (i <- 0 until q) {\n val Array(_r, w) = readInts(2)\n val r = _r - 1\n val delta = rLens(r) - w\n rLens(r) = w\n total -= delta * incoming(r) * outgoing(r)\n println(total / f)// * (n - 1) / (n - 2) / (n - 2) / 2))\n }\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rLens = Array.fill(n - 1)(0)\n val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n val abToRoad = mutable.Map.empty[(Int, Int), Int]\n\n for (i <- 0 until n - 1) {\n val Array(_a, _b, l) = readInts(3)\n val a = _a - 1\n val b = _b - 1\n adjBuilders(a) += b\n adjBuilders(b) += a\n abToRoad += (a, b) -> i\n abToRoad += (b, a) -> i\n rLens(i) = l\n }\n\n val adjs = adjBuilders.map(_.result)\n val incoming, outgoing = Array.fill(n - 1)(0)\n\n def dfs(u: Int, cnt: Int, parent: Int): Int = {\n var add = 1\n for (v <- adjs(u)) {\n if (v != parent) {\n val c = dfs(v, cnt + 1, u)\n val r = abToRoad((u, v))\n incoming(r) = n - c\n outgoing(r) = c\n add += c\n }\n }\n add\n }\n\n dfs(0, 1, -1)\n\n var total = 0d\n for (i <- 0 until n - 1) total += rLens(i).toDouble * incoming(i) * outgoing(i)\n\n val Array(q) = readInts(1)\n\n Console.withOut(new java.io.BufferedOutputStream(Console.out)) {\n\n for (i <- 0 until q) {\n val Array(_r, w) = readInts(2)\n val r = _r - 1\n val delta = rLens(r) - w\n rLens(r) = w\n total -= delta.toDouble * incoming(r) * outgoing(r)\n println(total * 3 / n / (n - 1) * 2)\n }\n\n }\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rLens = Array.fill(n - 1)(0)\n val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n val abToRoad = mutable.Map.empty[(Int, Int), Int]\n\n for (i <- 0 until n - 1) {\n val Array(_a, _b, l) = readInts(3)\n val a = _a - 1\n val b = _b - 1\n adjBuilders(a) += b\n adjBuilders(b) += a\n abToRoad += (a, b) -> i\n abToRoad += (b, a) -> i\n rLens(i) = l\n }\n\n val adjs = adjBuilders.map(_.result)\n val visited = new mutable.BitSet(n)\n val incoming, outgoing = Array.fill(n - 1)(0)\n\n def dfs(u: Int, cnt: Int): Int = {\n visited += u\n var add = 1\n val ne = new mutable.ArrayBuilder.ofInt\n val cs = new mutable.ArrayBuilder.ofInt\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n ne += v\n if (!visited(v)) {\n val c = dfs(v, cnt + 1)\n cs += c\n add += c\n } else cs += 0\n }\n val nes = ne.result\n val css = cs.result\n for (i <- nes.indices) {\n val v = nes(i)\n val r = abToRoad((u, v))\n incoming(r) = n - css(i)\n outgoing(r) = css(i)\n }\n add\n }\n\n dfs(0, 1)\n\n var total = 0d\n for (i <- 0 until n - 1) total += rLens(i).toDouble * incoming(i) * outgoing(i)\n\n val Array(q) = readInts(1)\n for (i <- 0 until q) {\n val Array(_r, w) = readInts(2)\n val r = _r - 1\n val delta = rLens(r) - w\n rLens(r) = w\n total -= delta * incoming(r) * outgoing(r)\n println(total * 3 / n / (n - 1) * 2)\n }\n\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rLens = Array.fill(n - 1)(0)\n val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n val abToRoad = mutable.Map.empty[(Int, Int), Int]\n\n for (i <- 0 until n - 1) {\n val Array(_a, _b, l) = readInts(3)\n val a = _a - 1\n val b = _b - 1\n adjBuilders(a) += b\n adjBuilders(b) += a\n abToRoad += (a, b) -> i\n abToRoad += (b, a) -> i\n rLens(i) = l\n }\n\n val adjs = adjBuilders.map(_.result)\n val visited = new mutable.BitSet(n)\n val incoming, outgoing = Array.fill(n - 1)(0)\n\n def dfs(u: Int, cnt: Int): Int = {\n visited += u\n var add = 1\n val ne = new mutable.ArrayBuilder.ofInt\n val cs = new mutable.ArrayBuilder.ofInt\n for (i <- adjs(u).indices) {\n val v = adjs(u)(i)\n ne += v\n if (!visited(v)) {\n val c = dfs(v, cnt + 1)\n cs += c\n add += c\n } else cs += 0\n }\n val nes = ne.result\n val css = cs.result\n for (i <- nes.indices) {\n val v = nes(i)\n val r = abToRoad((u, v))\n incoming(r) = n - css(i)\n outgoing(r) = css(i)\n }\n add\n }\n\n dfs(0, 1)\n\n var total = 0d\n for (i <- 0 until n - 1) total += rLens(i) * incoming(i) * outgoing(i)\n\n val Array(q) = readInts(1)\n for (i <- 0 until q) {\n val Array(_r, w) = readInts(2)\n val r = _r - 1\n val delta = rLens(r) - w\n rLens(r) = w\n total -= delta * incoming(r) * outgoing(r)\n println(total * 3 / n / (n - 1) * 2)\n }\n\n}\n"}], "src_uid": "38388446f5c265f77124132caa3ce4d2"} {"source_code": "object CF928A extends App {\n val sc = new java.util.Scanner(System.in)\n var n: Int = sc.nextInt()\n var o: Int = 0\n var e: Int = 0\n while (n != 0) {\n val x: Int = sc.nextInt()\n if (x % 2 == 0) e = e + 1\n else o = o + 1\n n = n - 1\n }\n var ans: Int = 0\n if (o > e) ans = e\n else ans = o\n e -= ans\n o -= ans\n ans += o / 3\n println(ans)\n }", "positive_code": [{"source_code": "object Main extends App {\n\tvar i = 0\n var o = 0\n var e = 0\n var n = readLine().toLong\n val arr = readLine().split(\" \").map(_.toLong)\n var k = 0\n \n while (i < n) {\n k = arr(i).toInt\n if (k % 2 == 1) {o += 1}\n else {e += 1}\n i += 1\n }\n if (o <= e) {print(o)}\n else {print(e + ((o-e) / 3))}\n}"}, {"source_code": "object CF158A {\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n var no = 0;\n for (i <- 1 to n){\n if (sc.nextInt() % 2 == 1){\n no= no + 1;\n }\n }\n \n var a = Math.min(no, n /2)\n var done = false\n while(a>0 && !done){\n var nl = (no - a)/2 + (n - no);\n if (nl < a)\n a = a -1;\n else{\n \n done = true\n }\n }\n \n \n print(a)\n}\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n readInt()\n\n val pairs = readLine().split(\" \").map(_.toInt).dropWhile(_ == 0).reverse.dropWhile(_ == 0)\n\n var odd = 0\n var even = 0\n for (p <- pairs) {\n if (p % 2 == 0) {\n even += 1\n } else {\n odd += 1\n }\n }\n \n if (even > odd) {\n println(odd)\n } else {\n println(even + (odd - even) / 3)\n }\n\n}"}, {"source_code": "object CF158A {\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n var z = new Array[Integer](n)\n var fr = new Array[Integer](2)\n for(i <- 0 until z.length) {\n z(i) = sc.nextInt()\n fr(z(i)%2) += 1\n }\n var res = 0\n var min = math.min(fr(0), fr(1))\n res += min\n fr(0) -= min\n fr(1) -= min\n res += fr(1)/3\n println(res)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n var a1 = 0\n var a0 = 0\n for (a <- 1 to n) {\n val x = sc.nextInt()\n if (x % 2 == 0) a0 = a0 + 1\n else a1 = a1 + 1\n }\n var x = math.min(a1,a0)\n a1 = a1 - x\n x = x + a1 / 3\n\n println(x)\n }\n}"}, {"source_code": "object VK {\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n \n var d = 0\n var e = 0\n for( i <- 1 to n ) {\n val a = sc.nextInt()\n if(a % 2 == 0) d = d + 1; else e = e + 1;\n }\n \n var res = 0\n if(e < d) {\n res = e\n } else {\n res = d + (e - d) / 3\n }\n \n println(res)\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Hello extends App {\n val n = readInt()\n val xs = readLine().split(\" \").map(_.toInt)\n var o = 0;\n var e = 0;\n var i = 0\n for ( i <- xs) {\n if (i %2 == 0) {\n e = e+1\n } else {\n o = o+1\n }\n }\n var ans = 0\n if (o < e) {\n ans = o\n } else {\n ans = e\n }\n e-=ans\n o-=ans\n ans += o/3\n println(ans)\n}\n"}, {"source_code": "object CF158A {\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n var a = 0\n var b = 0\n for ( i <- 1 to n) {\n val k = sc.nextInt()\n if(k % 2 == 0) a += 1\n else b += 1\n }\n var ans = 0;\n \n if(a > b) {ans += b\n a -= b;\n b = 0;\n }\n \n else{ ans += a\n b -= a;\n a = 0;\n \n \n ans += b / 3\n }\n println(ans)\n}\n}"}, {"source_code": "import java.util.Scanner\n\n\nobject Main extends App {\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n val arr = new Array[Int](n)\n var c = 0\n var c2 = 0\n\n for (i <- 0 until n) {\n arr.update(i, scanner.nextInt())\n if (arr(i) % 2 == 0)\n c += 1\n else\n c2 += 1\n }\n\n val mn = Integer.min(c, c2)\n c2 -= mn\n\n println(mn + c2 / 3)\n\n}"}, {"source_code": "object Main extends App {\n val n = readInt\n val s = readLine\n val a = s.split(\" \").map(i => i.toInt)\n var n1 = 0\n for(i <- 0 until n) {\n if (a(i) % 2 == 0)\n n1 += 1\n }\n var n2 = n - n1\n if (n2 <= n1)\n println(n2)\n else\n println(n1 + (n2 - n1) / 3)\n}\n"}, {"source_code": "object CF158A {\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n \n var c1 = 0\n for ( i <- 1 to n)\n {\n var x = sc.nextInt()\n if (x % 2 == 1)\n {\n c1 = c1 + 1\n }\n }\n var c2 = n - c1\n \n var ans = 0\n \n if (c2 < c1)\n {\n ans = c2 + (c1 - c2) / 3\n }\n else\n {\n ans = c1\n }\n \n println(ans)\n }\n}"}], "negative_code": [{"source_code": "object CF158A {\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n var a = 0\n var b = 0\n for ( i <- 1 to n) {\n val k = sc.nextInt()\n if(k % 2 == 0) a += 1\n else b += 1\n }\n if(a > b) println(b)\n else println(a)\n}\n}"}, {"source_code": "object Main extends App {\n val n = readInt\n val s = readLine\n val a = s.split(\" \").map(i => i.toInt)\n var n1 = 0\n for(i <- 0 until n) {\n if (a(i) % 2 == 0)\n n1 += 1\n }\n var n2 = n - n1\n if (n2 <= n1)\n println(n2)\n else\n if ((n2 - n1) % 3 == 1)\n println(math.max(0, n1 + (n2 - n1) / 3 - 1))\n else\n println(n1 + (n2 - n1) / 3)\n}\n"}, {"source_code": "object CF158A {\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n \n var c1 = 0\n for ( i <- 1 to n)\n {\n var x = sc.nextInt()\n if (x % 2 == 1)\n {\n c1 = c1 + 1\n }\n }\n \n val c2 = n - c1\n \n var ans = c1\n if (c2 < c1)\n {\n ans = c2\n }\n \n println(ans)\n }\n}"}, {"source_code": "object CF158A {\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n val a: List[Int] = (1 to n).toList.foldLeft(List.empty[Int]){case (list, _) => list :+ sc.nextInt()}\n \n println(a.count(\n x => x % 2 == 1\n ))\n }\n}"}, {"source_code": "object Main extends App {\n\tvar i = 0\n var o = 0\n var e = 0\n var n = readLine().toInt\n val arr = readLine().split(\" \").map(_.toInt)\n var k = 0\n \n while (i < n) {\n k = arr(i)\n if (k % 2 == 1) {o += 1}\n else {e += 1}\n i += 1\n }\n if (o <= e) {print(o)}\n else {print(e + ((o-e) % 3))}\n}"}, {"source_code": "object CF158A {\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n var no = 0;\n for (i <- 1 to n){\n if (sc.nextInt() % 2 == 0){\n no= no + 1;\n }\n }\n print(Math.min(no, n /2))\n}\n}"}, {"source_code": "object CF158A {\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n var no = 0;\n for (i <- 1 to n){\n if (sc.nextInt() % 2 == 1){\n no= no + 1;\n }\n }\n if (n == 2 && no == 2)\n print(0); else\n print(Math.min(no, n /2))\n}\n}"}, {"source_code": "object CF158A {\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n var no = 0;\n for (i <- 1 to n){\n if (sc.nextInt() % 2 == 1){\n no= no + 1;\n }\n }\n print(Math.min(no, n /2))\n}\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n var a1 = 0\n var a0 = 0\n for (a <- 1 to n) {\n val x = sc.nextInt()\n if (x % 2 == 0) a0 = a0 + 1\n else a1 = a1 + 1\n }\n // val a = Array.fromFunction(_ => sc.nextInt())(n)\n\n // val a1 = a.count(x => x % 2 == 1)\n // val a0 = a.count(x => x % 2 == 0)\n\n println(math.min(a1,a0))\n }\n}"}], "src_uid": "61e6fd68d7568c599204130b102ea389"} {"source_code": "object Solution extends App {\n \n val input = scala.io.StdIn.readLine()\n val reverseInput = input.reverse\n val inputSize = input.size\n val enough = input.contains(\"AB\") && input.contains(\"BA\")\n val abFirst = input.indexOf(\"AB\") + 1 < inputSize - reverseInput.indexOf(\"AB\") - 2\n val baFirst = input.indexOf(\"BA\") + 1 < inputSize - reverseInput.indexOf(\"BA\") - 2\n if (enough && (abFirst || baFirst)) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n}", "positive_code": [{"source_code": "import java.io.InputStream\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport java.io.PrintWriter\n\nobject CF550A {\n\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n return next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n \n def main(args: Array[String]): Unit = {\n val in = new InputReader(System.in)\n var s = in.next()\n val ok = solve(s,\"AB\",\"BA\") || solve(s,\"BA\",\"AB\")\n if ( ok ) print(\"YES\")\n else print(\"NO\")\n }\n \n def solve(ss: String, a: String, b:String ): Boolean = {\n var s = ss\n if ( s.indexOf(a) != -1)\n s = s.replaceFirst(a, \"XX\")\n else return false;\n if ( s.indexOf(b) != -1)\n return true;\n else return false\n } \n}"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val s = readLine().toCharArray\n\n def find(): String = {\n var AB = false\n var BA = false\n\n var i = 0\n while (i < s.length - 1) {\n if (!AB && s(i) == 'A' && s(i + 1) == 'B') {\n AB = true\n i += 1\n }\n else if (!AB && i < s.length - 2 && s(i + 1) == 'A' && s(i + 2) == 'B') {\n AB = true\n i += 2\n }\n else if (!BA && s(i) == 'B' && s(i + 1) == 'A') {\n BA = true\n i += 1\n }\n\n if (AB && BA) {\n return \"YES\"\n }\n\n i += 1\n }\n\n\n AB = false\n BA = false\n\n i = 0\n while (i < s.length - 1) {\n if (!BA && s(i) == 'B' && s(i + 1) == 'A' ) {\n BA = true\n i += 1\n }\n else if (!BA && i < s.length - 2 && s(i + 1) == 'B' && s(i + 2) == 'A') {\n BA = true\n i += 2\n }\n else if (!AB && s(i) == 'A' && s(i + 1) == 'B') {\n AB = true\n i += 1\n }\n\n if (AB && BA) {\n return \"YES\"\n }\n\n i += 1\n }\n\n \"NO\"\n }\n\n println(find())\n}\n"}, {"source_code": "object Solution extends App {\n \n val input = scala.io.StdIn.readLine()\n \n val enough = input.contains(\"AB\") && input.contains(\"BA\")\n val abFirst = input.indexOf(\"AB\") + 1 < input.lastIndexOf(\"BA\")\n val baFirst = input.indexOf(\"BA\") + 1 < input.lastIndexOf(\"AB\")\n \n if (enough && (abFirst || baFirst)) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n}"}], "negative_code": [{"source_code": "import java.io.InputStream\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport java.io.PrintWriter\n\nobject CF550A {\n\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n return next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n \n def main(args: Array[String]): Unit = {\n val in = new InputReader(System.in)\n var s = in.next()\n if ( s.indexOf(\"AB\") != -1)\n s = s.replaceFirst(\"AB\", \"\")\n else return \"NO\"\n if ( s.indexOf(\"BA\") != -1)\n return \"YES\"\n else return \"NO\"\n\n }\n}"}, {"source_code": "import java.io.InputStream\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport java.io.PrintWriter\n\nobject CF550A {\n\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n return next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n \n def main(args: Array[String]): Unit = {\n println(solve)\n }\n \n def solve : String = {\n val in = new InputReader(System.in)\n var s = in.next()\n if ( s.indexOf(\"AB\") != -1)\n s = s.replaceFirst(\"AB\", \"\")\n else return \"NO\"\n if ( s.indexOf(\"BA\") != -1)\n return \"YES\"\n else return \"NO\"\n } \n}"}, {"source_code": "import java.io.InputStream\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport java.io.PrintWriter\n\nobject CF550A {\n\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n return next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n \n def main(args: Array[String]): Unit = {\n println(solve)\n }\n \n def solve : String = {\n val in = new InputReader(System.in)\n var s = in.next()\n if ( s.indexOf(\"AB\") != -1)\n s = s.replaceFirst(\"AB\", \"XX\")\n else return \"NO\"\n if ( s.indexOf(\"BA\") != -1)\n return \"YES\"\n else return \"NO\"\n } \n}"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val s = readLine().toCharArray\n\n\n def find(): String = {\n var AB = false\n var BA = false\n\n for (i <- 0 until s.length - 1) {\n if (!AB && s(i) == 'A' && s(i + 1) == 'B') AB = true\n else if (!BA && s(i) == 'B' && s(i + 1) == 'A') BA = true\n else if (AB && BA) {\n return \"YES\"\n }\n }\n\n\n AB = false\n BA = false\n\n for (i <- 0 until s.length - 1) {\n if (!BA && s(i) == 'B' && s(i + 1) == 'A') BA = true\n else if (!BA && s(i) == 'A' && s(i + 1) == 'B') AB = true\n else if (AB && BA) {\n return \"YES\"\n }\n }\n\n \"NO\"\n }\n\n println(find())\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val s = readLine().toCharArray\n\n def find(): String = {\n var AB = false\n var BA = false\n\n var i = 0\n while (i < s.length - 1) {\n if (!AB && s(i) == 'A' && s(i + 1) == 'B') {\n AB = true\n i += 1\n }\n else if (!BA && s(i) == 'B' && s(i + 1) == 'A') {\n BA = true\n i += 1\n }\n\n if (AB && BA) {\n return \"YES\"\n }\n\n i += 1\n }\n\n\n AB = false\n BA = false\n\n i = 0\n while (i < s.length - 1) {\n if (!BA && ((s(i) == 'B' && s(i + 1) == 'A') || (i < s.length - 2 && s(i + 1) == 'B' && s(i + 2) == 'A'))) {\n BA = true\n i += 1\n }\n else if (!AB && s(i) == 'A' && s(i + 1) == 'B') {\n AB = true\n i += 1\n }\n\n if (AB && BA) {\n return \"YES\"\n }\n\n i += 1\n }\n\n \"NO\"\n }\n\n println(find())\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val s = readLine().toCharArray\n\n\n def find(): String = {\n var AB = false\n var BA = false\n\n var i = 0\n while (i < s.length - 1) {\n if (!AB && s(i) == 'A' && s(i + 1) == 'B') {\n AB = true\n i += 1\n }\n else if (!BA && s(i) == 'B' && s(i + 1) == 'A') {\n BA = true\n i += 1\n }\n\n if (AB && BA) {\n return \"YES\"\n }\n\n i += 1\n }\n\n\n AB = false\n BA = false\n\n i = 0\n while (i < s.length - 1) {\n if (!BA && s(i) == 'B' && s(i + 1) == 'A') {\n BA = true\n i += 1\n }\n else if (!AB && s(i) == 'A' && s(i + 1) == 'B') {\n AB = true\n i += 1\n }\n\n if (AB && BA) {\n return \"YES\"\n }\n\n i += 1\n }\n\n \"NO\"\n }\n\n println(find())\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val s = readLine().toCharArray\n\n def find(): String = {\n var AB = false\n var BA = false\n\n var i = 0\n while (i < s.length - 1) {\n if (!AB && s(i) == 'A' && s(i + 1) == 'B') {\n AB = true\n i += 1\n }\n else if (!BA && s(i) == 'B' && s(i + 1) == 'A') {\n BA = true\n i += 1\n }\n\n if (AB && BA) {\n return \"YES\"\n }\n\n i += 1\n }\n\n\n AB = false\n BA = false\n\n i = 0\n while (i < s.length - 1) {\n if (!BA && s(i) == 'B' && s(i + 1) == 'A' ) {\n BA = true\n i += 1\n }\n else if (i < s.length - 2 && s(i + 1) == 'B' && s(i + 2) == 'A') {\n BA = true\n i += 2\n }\n else if (!AB && s(i) == 'A' && s(i + 1) == 'B') {\n AB = true\n i += 1\n }\n\n if (AB && BA) {\n return \"YES\"\n }\n\n i += 1\n }\n\n \"NO\"\n }\n\n println(find())\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val s = readLine().toCharArray\n\n var AB = false\n var BA = false\n\n def find(): String = {\n for (i <- 0 until s.length - 1) {\n if (!AB && s(i) == 'A' && s(i + 1) == 'B') AB = true\n else if (!BA && s(i) == 'B' && s(i + 1) == 'A') BA = true\n else if (AB && BA) {\n return \"YES\"\n }\n }\n\n for (i <- 0 until s.length - 1) {\n if (!BA && s(i) == 'B' && s(i + 1) == 'A') BA = true\n else if (!BA && s(i) == 'A' && s(i + 1) == 'B') AB = true\n else if (AB && BA) {\n return \"YES\"\n }\n }\n\n \"NO\"\n }\n\n println(find())\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val s = readLine().toCharArray\n\n\n def find(): String = {\n var AB = false\n var BA = false\n\n for (i <- 0 until s.length - 1) {\n if (!AB && s(i) == 'A' && s(i + 1) == 'B') AB = true\n else if (!BA && s(i) == 'B' && s(i + 1) == 'A') BA = true\n\n if (AB && BA) {\n return \"YES\"\n }\n }\n\n\n AB = false\n BA = false\n\n for (i <- 0 until s.length - 1) {\n if (!BA && s(i) == 'B' && s(i + 1) == 'A') BA = true\n else if (!AB && s(i) == 'A' && s(i + 1) == 'B') AB = true\n\n if (AB && BA) {\n return \"YES\"\n }\n }\n\n \"NO\"\n }\n\n println(find())\n}\n"}, {"source_code": "object Solution extends App {\n \n val input = scala.io.StdIn.readLine()\n val reverseInput = input.reverse\n val inputSize = input.size\n \n if (input.indexOf(\"AB\") + 1 < inputSize - reverseInput.indexOf(\"AB\") - 2) {\n println(\"YES\")\n } else if (input.indexOf(\"BA\") + 1 < inputSize - reverseInput.indexOf(\"BA\") - 2) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n}"}], "src_uid": "33f7c85e47bd6c83ab694a834fa728a2"} {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n \n Console.setOut(new java.io.PrintStream(Console.out))\n \n val Array(n, m, d) = readInts(3)\n\n val marked = new mutable.BitSet(n + 1) \n marked ++= readInts(m)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt\n edges(a) += b\n edges(b) += a\n }\n\n def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size)\n visited += source\n val toVisit = mutable.Queue(source)\n var remote: Option[Int] = None\n\n while (!toVisit.isEmpty) { // BFS\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n if (marked(next)) remote = Some(next)\n }\n\n remote\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val visited = new mutable.BitSet(graph.size)\n visited += source\n val toVisit = mutable.Queue(source)\n val dists = Array.fill(graph.size)(0)\n\n while (!toVisit.isEmpty) { // BFS\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n }\n\n dists\n }\n\n val a = remoteVertex(edges, 1).get\n val b = remoteVertex(edges, a).getOrElse(a)\n\n val _fromA = scala.actors.Futures.future(shortestPaths(edges, a))\n val _fromB = scala.actors.Futures.future(shortestPaths(edges, b))\n val fromA = _fromA()\n val fromB = _fromB()\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n \n Console.flush\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readInts0 = readString.split(' ').map(_.toInt)\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, m, d) = readInts(3)\n\n val marked = new mutable.BitSet(n + 1) ++= readInts0 //(m)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n\n for (i <- 0 until n - 1) {\n /*val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt*/\n val Array(a, b) = readInts0\n edges(a) += b\n edges(b) += a\n }\n\n def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n var remote: Option[Int] = None\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n if (marked(next)) remote = Some(next)\n }\n\n remote\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n val dists = Array.fill(graph.size)(0)\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n }\n\n dists\n }\n\n val a = remoteVertex(edges, 1).get\n val b = remoteVertex(edges, a).getOrElse(a)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n \n def readInts(n: Int) = { val st = tokenizeLine; Array.fill(n)(st.nextToken().toInt) }\n\n val Array(n, m, d) = readInts(3)\n val marked = new mutable.BitSet(n + 1) ++ readInts(m)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n\n for (i <- 0 until n - 1) {\n val Array(a, b) = readInts(2)\n edges(a).append(b)\n edges(b).append(a)\n }\n\n def traverseFrom(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def traverseTR(accumulator: Option[Int]): Option[Int] = {\n if (toVisit.isEmpty) {\n accumulator\n } else {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n traverseTR(if (marked(next)) Some(next) else accumulator)\n }\n }\n\n traverseTR(None)\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val dists = Array.fill(graph.size)(0)\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def shortestPathsTR(): Unit = {\n if (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n shortestPathsTR()\n }\n }\n\n shortestPathsTR()\n dists\n }\n\n val a = traverseFrom(edges, 1).get\n val b = traverseFrom(edges, a).getOrElse(a)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val st = tokenizeLine; Array.fill(n)(st.nextToken().toInt) }\n\n val Array(n, m, d) = readInts(3)\n val marked = new mutable.BitSet(n + 1) ++ readInts(m)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int](2))\n\n for (i <- 0 until n - 1) {\n val Array(a, b) = readInts(2)\n edges(a).append(b)\n edges(b).append(a)\n }\n\n def traverseFrom(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def traverseTR(accumulator: Option[Int]): Option[Int] = {\n if (toVisit.isEmpty) {\n accumulator\n } else {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n traverseTR(if (marked(next)) Some(next) else accumulator)\n }\n }\n\n traverseTR(None)\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val dists = Array.fill(graph.size)(0)\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def shortestPathsTR(): Unit = {\n if (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n shortestPathsTR()\n }\n }\n\n shortestPathsTR()\n dists\n }\n\n val a = traverseFrom(edges, 1).get\n val b = traverseFrom(edges, a).getOrElse(a)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, m, d) = readInts(3)\n\n val marked = new mutable.BitSet(n + 1) \n marked ++= readInts(m)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt\n edges(a) += b\n edges(b) += a\n }\n\n def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size)\n visited += source\n val toVisit = mutable.Queue(source)\n var remote: Option[Int] = None\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n if (marked(next)) remote = Some(next)\n }\n\n remote\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val visited = new mutable.BitSet(graph.size)\n visited += source\n val toVisit = mutable.Queue(source)\n val dists = Array.fill(graph.size)(0)\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n }\n\n dists\n }\n\n val a = remoteVertex(edges, 1).get\n val b = remoteVertex(edges, a).getOrElse(a)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readInts0 = readString.split(' ').map(_.toInt)\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, m, d) = readInts(3)\n\n val marked = new mutable.BitSet(n + 1) ++= readInts0 //(m)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt\n edges(a) += b\n edges(b) += a\n }\n\n def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n var remote: Option[Int] = None\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n if (marked(next)) remote = Some(next)\n }\n\n remote\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n val dists = Array.fill(graph.size)(0)\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n }\n\n dists\n }\n\n val a = remoteVertex(edges, 1).get\n val b = remoteVertex(edges, a).getOrElse(a)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n \n def readInts(n: Int) = { val st = tokenizeLine; Array.fill(n)(st.nextToken.toInt) }\n\n val Array(n, m, d) = readInts(3)\n val marked = new mutable.BitSet(n + 1)\n val st = tokenizeLine\n for (i <- 0 until m) marked += st.nextToken.toInt\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt\n edges(a).append(b)\n edges(b).append(a)\n }\n\n def traverseFrom(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def traverseTR(accumulator: Option[Int]): Option[Int] = {\n if (toVisit.isEmpty) {\n accumulator\n } else {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n traverseTR(if (marked(next)) Some(next) else accumulator)\n }\n }\n\n traverseTR(None)\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val dists = Array.fill(graph.size)(0)\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def shortestPathsTR(): Unit = {\n if (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n shortestPathsTR()\n }\n }\n\n shortestPathsTR()\n dists\n }\n\n val a = traverseFrom(edges, 1).get\n val b = traverseFrom(edges, a).getOrElse(a)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n \n val Array(n, m, d) = readInts(3)\n\n val marked = new mutable.BitSet(n + 1) \n marked ++= readInts(m)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt\n edges(a) += b\n edges(b) += a\n }\n\n def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size)\n visited += source\n val toVisit = mutable.Queue(source)\n var remote: Option[Int] = None\n\n while (!toVisit.isEmpty) { // BFS\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n if (marked(next)) remote = Some(next)\n }\n\n remote\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val visited = new mutable.BitSet(graph.size)\n visited += source\n val toVisit = mutable.Queue(source)\n val dists = Array.fill(graph.size)(0)\n\n while (!toVisit.isEmpty) { // BFS\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n }\n\n dists\n }\n\n val a = remoteVertex(edges, 1).get\n val b = remoteVertex(edges, a).getOrElse(a)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n\n// val _fromA = scala.actors.Futures.future(shortestPaths(edges, a))\n// val _fromB = scala.actors.Futures.future(shortestPaths(edges, b))\n// val fromA = _fromA()\n// val fromB = _fromB()\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, m, d) = readInts(3)\n\n val marked = new mutable.BitSet(n + 1) \n marked ++= readInts(m)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt\n edges(a) += b\n edges(b) += a\n }\n\n def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size)\n visited += source\n val toVisit = mutable.Queue(source)\n var remote: Option[Int] = None\n\n while (!toVisit.isEmpty) { // BFS\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n if (marked(next)) remote = Some(next)\n }\n\n remote\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val visited = new mutable.BitSet(graph.size)\n visited += source\n val toVisit = mutable.Queue(source)\n val dists = Array.fill(graph.size)(0)\n\n while (!toVisit.isEmpty) { // BFS\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n }\n\n dists\n }\n\n val a = remoteVertex(edges, 1).get\n val b = remoteVertex(edges, a).getOrElse(a)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n\n def readInts(n: Int) = { val st = tokenizeLine; Array.fill(n)(st.nextToken.toInt) }\n\n val Array(n, m, d) = readInts(3)\n\n val marked = new mutable.BitSet(n + 1) ++= readInts(m)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt\n edges(a) += b\n edges(b) += a\n }\n\n def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n var remote: Option[Int] = None\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n if (marked(next)) remote = Some(next)\n }\n\n remote\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n val dists = Array.fill(graph.size)(0)\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n }\n\n dists\n }\n\n val a = remoteVertex(edges, 1).get\n val b = remoteVertex(edges, a).getOrElse(a)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n \n def readInts(n: Int) = { val st = tokenizeLine; Array.fill(n)(st.nextToken.toInt) }\n\n val Array(n, m, d) = readInts(3)\n val marked = new mutable.BitSet(n + 1) ++ readInts(m)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n //val Array(a, b) = readInts(2)\n val (a, b) = (st.nextToken.toInt, st.nextToken.toInt)\n edges(a).append(b)\n edges(b).append(a)\n }\n\n def traverseFrom(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def traverseTR(accumulator: Option[Int]): Option[Int] = {\n if (toVisit.isEmpty) {\n accumulator\n } else {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n traverseTR(if (marked(next)) Some(next) else accumulator)\n }\n }\n\n traverseTR(None)\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val dists = Array.fill(graph.size)(0)\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def shortestPathsTR(): Unit = {\n if (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n shortestPathsTR()\n }\n }\n\n shortestPathsTR()\n dists\n }\n\n val a = traverseFrom(edges, 1).get\n val b = traverseFrom(edges, a).getOrElse(a)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n \n def readInts(n: Int) = { val st = tokenizeLine; Array.fill(n)(st.nextToken.toInt) }\n\n val Array(n, m, d) = readInts(3)\n val marked = new mutable.BitSet(n + 1) ++ readInts(m)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt\n edges(a).append(b)\n edges(b).append(a)\n }\n\n def traverseFrom(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def traverseTR(accumulator: Option[Int]): Option[Int] = {\n if (toVisit.isEmpty) {\n accumulator\n } else {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n traverseTR(if (marked(next)) Some(next) else accumulator)\n }\n }\n\n traverseTR(None)\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val dists = Array.fill(graph.size)(0)\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def shortestPathsTR(): Unit = {\n if (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n shortestPathsTR()\n }\n }\n\n shortestPathsTR()\n dists\n }\n\n val a = traverseFrom(edges, 1).get\n val b = traverseFrom(edges, a).getOrElse(a)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, m, d) = readInts(3)\n\n val marked = new mutable.BitSet(n + 1) \n marked ++= readInts(m)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt\n edges(a) += b\n edges(b) += a\n }\n\n def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n //visited += source\n val toVisit = mutable.Queue(source)\n var remote: Option[Int] = None\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n if (marked(next)) remote = Some(next)\n }\n\n remote\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val visited = new mutable.BitSet(graph.size) + source\n //visited += source\n val toVisit = mutable.Queue(source)\n val dists = Array.fill(graph.size)(0)\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n }\n\n dists\n }\n\n val a = remoteVertex(edges, 1).get\n val b = remoteVertex(edges, a).getOrElse(a)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val Array(n, m, d) = readInts(3)\n\n val marked = new mutable.BitSet(n + 1)\n marked ++= readInts(m)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt\n edges(a) += b\n edges(b) += a\n }\n\n def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size)\n visited += source\n val toVisit = mutable.Queue(source)\n var remote: Option[Int] = None\n\n while (!toVisit.isEmpty) { // BFS\n val next = toVisit.dequeue\n for (succ <- graph(next); if !visited(succ)) {\n toVisit += succ\n visited += succ\n }\n if (marked(next)) remote = Some(next)\n }\n\n remote\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val visited = new mutable.BitSet(graph.size)\n visited += source\n val toVisit = mutable.Queue(source)\n val dists = Array.fill(graph.size)(0)\n\n while (!toVisit.isEmpty) { // BFS\n val next = toVisit.dequeue\n for (succ <- graph(next); if !visited(succ)) {\n toVisit += succ\n visited += succ\n dists(succ) = dists(next) + 1\n }\n }\n\n dists\n }\n\n val a = remoteVertex(edges, 1).get\n val b = remoteVertex(edges, a).getOrElse(a)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}\n"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n\n def readInts(n: Int) = { val st = tokenizeLine; Array.fill(n)(st.nextToken.toInt) }\n\n def prof(i: Int) = if (m == 17585) println(i + \": \" + (System.currentTimeMillis() - executionStart) + \" ms\")\n\n val Array(n, m, d) = readInts(3)\n prof(1)\n val marked = new mutable.BitSet(n + 1) ++= readInts(m)\n prof(2)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n prof(3)\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt\n edges(a).append(b)\n edges(b).append(a)\n }\n prof(4)\n\n def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n var remote: Option[Int] = None\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n if (marked(next)) remote = Some(next)\n }\n\n remote\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n val dists = Array.fill(graph.size)(0)\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n }\n\n dists\n }\n\n val a = remoteVertex(edges, 1).get\n val b = remoteVertex(edges, a).getOrElse(a)\n prof(5)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n prof(6)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n prof(7)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n \n def readInts(n: Int) = { val st = tokenizeLine; Array.fill(n)(st.nextToken.toInt) }\n\n def prof(i: Int) = if (m == 17585) println(i + \": \" + (System.currentTimeMillis() - executionStart) + \" ms\")\n \n val Array(n, m, d) = readInts(3)\n val marked = new mutable.BitSet(n + 1)\n prof(1)\n val st = tokenizeLine\n for (i <- 0 until m) marked += st.nextToken.toInt\n prof(2)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n prof(3)\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt\n edges(a).append(b)\n edges(b).append(a)\n }\n prof(4)\n\n def traverseFrom(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def traverseTR(accumulator: Option[Int]): Option[Int] = {\n if (toVisit.isEmpty) {\n accumulator\n } else {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n traverseTR(if (marked(next)) Some(next) else accumulator)\n }\n }\n\n traverseTR(None)\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val dists = Array.fill(graph.size)(0)\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def shortestPathsTR(): Unit = {\n if (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n shortestPathsTR()\n }\n }\n\n shortestPathsTR()\n dists\n }\n\n val a = traverseFrom(edges, 1).get\n val b = traverseFrom(edges, a).getOrElse(a)\n prof(5)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n prof(6)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n prof(7)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val st = tokenizeLine; Array.tabulate(n)(i => st.nextToken().toInt) }\n\n val Array(n, m, d) = readInts(3)\n val marked = new mutable.BitSet(n + 1) ++ readInts(m)\n\n val edges = Array.fill(n + 1)(mutable.Seq[Int]())\nprintln(\"read1\")\n\n for (i <- 0 until n - 1) {\n val Array(a, b) = readInts(2)\n edges(a) :+= b\n edges(b) :+= a\n }\nprintln(\"read2\")\n def traverseFrom(graph: Array[mutable.Seq[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def traverseTR(accumulator: Option[Int]): Option[Int] = {\n if (toVisit.isEmpty) {\n accumulator\n } else {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n traverseTR(if (marked(next)) Some(next) else accumulator)\n }\n }\n\n traverseTR(None)\n }\n\n def shortestPaths(graph: Array[mutable.Seq[Int]], source: Int): Array[Int] = {\n\n val dists = Array.fill(graph.size)(0)\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def shortestPathsTR(): Unit = {\n if (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n shortestPathsTR()\n }\n }\n\n shortestPathsTR()\n dists\n }\n\n val a = traverseFrom(edges, 1).get\n val b = traverseFrom(edges, a).getOrElse(a)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m, d) = readInts\n val marked = new mutable.BitSet(n + 1)\n readInts.foreach(marked += _)\n\n val edges = Array.fill(n + 1)(mutable.ArrayBuffer[Int]())\n\n for (i <- 0 until n - 1) {\n val Array(a, b) = readInts\n edges(a) :+= b\n edges(b) :+= a\n }\n\n if (m == 21456) println(\"read\")\n\n def traverseFrom(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size + 1)\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def traverseTR(accumulator: Option[Int]): Option[Int] = {\n if (toVisit.isEmpty) {\n accumulator\n } else {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n visited ++= succ\n toVisit ++= succ\n traverseTR(if (marked(next)) Some(next) else accumulator)\n }\n }\n\n traverseTR(None)\n }\n\n def sssp(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val dists = Array.fill(graph.size + 1)(0)\n val visited = new mutable.BitSet(graph.size + 1)\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def ssspTR(): Unit = {\n if (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n ssspTR()\n }\n }\n\n ssspTR()\n dists\n }\n\n val a = traverseFrom(edges, 1).get\n val b = traverseFrom(edges, a).getOrElse(a)\n\n val fromA = sssp(edges, a)\n val fromB = sssp(edges, b)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m, d) = readInts\n val marked = new mutable.BitSet(n + 1)\n readInts.foreach(marked += _)\n\n val edges = mutable.ArrayBuffer.fill(n + 1, 0)(0)\n\n for (i <- 0 until n - 1) {\n val Array(a, b) = readInts\n edges(a) :+= b\n edges(b) :+= a\n }\n\n if (m == 21456) println(\"read\")\n\n def traverseFrom(graph: mutable.ArrayBuffer[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size + 1)\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def traverseTR(accumulator: Option[Int]): Option[Int] = {\n if (toVisit.isEmpty) {\n accumulator\n } else {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n visited ++= succ\n toVisit ++= succ\n traverseTR(if (marked(next)) Some(next) else accumulator)\n }\n }\n\n traverseTR(None)\n }\n\n def sssp(graph: mutable.ArrayBuffer[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val dists = Array.fill(graph.size + 1)(0)\n val visited = new mutable.BitSet(graph.size + 1)\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def ssspTR(): Unit = {\n if (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n ssspTR()\n }\n }\n\n ssspTR()\n dists\n }\n\n val a = traverseFrom(edges, 1).get\n val b = traverseFrom(edges, a).getOrElse(a)\n\n val fromA = sssp(edges, a)\n val fromB = sssp(edges, b)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val Array(n, m, d) = readInts\n val marked = readInts.toSet\n\n val edges = Array.fill(n + 1)(mutable.Seq[Int]())\n\n for (i <- 0 until n - 1) {\n val Array(a, b) = readInts\n edges(a) :+= b\n edges(b) :+= a\n }\n\n @annotation.tailrec\n def traverseTR(graph: Array[mutable.Seq[Int]], toVisit: Seq[Int], visited: Set[Int], accumulator: Option[Int]): Option[Int] = {\n if (toVisit.isEmpty) {\n accumulator\n } else {\n val next = toVisit.head\n val succ = (graph(next).toSet -- visited -- toVisit).toSeq\n // DFS :\n //traverseTR(graph, succ ++ toVisit.tail, visited + next, accumulator :+ next)\n // BFS :\n traverseTR(graph, toVisit.tail ++ succ, visited + next, if (marked(next)) Some(next) else accumulator)\n }\n }\n\n @annotation.tailrec\n def sssp(graph: Array[mutable.Seq[Int]], toVisit: Seq[Int], visited: Set[Int], curDist: Int, dists: Array[Int]): Unit = {\n if (!toVisit.isEmpty) {\n val next = toVisit.head\n val succ = (graph(next).toSet -- visited -- toVisit).toSeq\n for (s <- succ) dists(s) = curDist\n sssp(graph, toVisit.tail ++ succ, visited + next, curDist + 1, dists)\n }\n }\n\n def traverseFrom(graph: Array[mutable.Seq[Int]], initial: Int) =\n traverseTR(graph, Seq(initial), Set.empty, None)\n\n val a = traverseFrom(edges, 1).get\n val b = traverseFrom(edges, a).getOrElse(a)\n \n val fromA = Array.ofDim[Int](n + 1)\n val fromB = Array.ofDim[Int](n + 1)\n \n sssp(edges, Seq(a), Set.empty, 1, fromA)\n sssp(edges, Seq(b), Set.empty, 1, fromB)\n \n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n \n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val st = tokenizeLine; Array.tabulate(n)(i => st.nextToken().toInt) }\n\n val Array(n, m, d) = readInts(3)\n val marked = new mutable.BitSet(n + 1) ++ readInts(m)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int](2))\nif (m == 21456 ) println(\"read1\")\n\n for (i <- 0 until n - 1) {\n val Array(a, b) = readInts(2)\n edges(a).append(b)\n edges(b).append(a)\n }\nif (m == 21456 ) println(\"read2\")\n def traverseFrom(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def traverseTR(accumulator: Option[Int]): Option[Int] = {\n if (toVisit.isEmpty) {\n accumulator\n } else {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n traverseTR(if (marked(next)) Some(next) else accumulator)\n }\n }\n\n traverseTR(None)\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val dists = Array.fill(graph.size)(0)\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n\n @annotation.tailrec\n def shortestPathsTR(): Unit = {\n if (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n shortestPathsTR()\n }\n }\n\n shortestPathsTR()\n dists\n }\n\n val a = traverseFrom(edges, 1).get\n val b = traverseFrom(edges, a).getOrElse(a)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n\n def readInts(n: Int) = { val st = tokenizeLine; Array.fill(n)(st.nextToken.toInt) }\n\n def prof(i: Int) = if (m == 17585) println(i + \": \" + (System.currentTimeMillis() - executionStart) + \" ms\")\n\n val Array(n, m, d) = readInts(3)\n prof(1)\n val marked = new mutable.BitSet(n + 1) ++= readInts(m)\n prof(2)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n prof(3)\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt\n edges(a) += b\n edges(b) += a\n }\n prof(4)\n\n def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n var remote: Option[Int] = None\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n if (marked(next)) remote = Some(next)\n }\n\n remote\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n val dists = Array.fill(graph.size)(0)\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n }\n\n dists\n }\n\n val a = remoteVertex(edges, 1).get\n val b = remoteVertex(edges, a).getOrElse(a)\n prof(5)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n prof(6)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n prof(7)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n\n def readInts(n: Int) = { val st = tokenizeLine; Array.fill(n)(st.nextToken.toInt) }\n\n def prof(i: Int) = if (m == 17585) println(i + \": \" + (System.currentTimeMillis() - executionStart) + \" ms\")\n\n val Array(n, m, d) = readInts(3)\n val marked = new mutable.BitSet(n + 1)\n prof(1)\n val st = tokenizeLine\n for (i <- 0 until m) marked += st.nextToken.toInt\n prof(2)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n prof(3)\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt\n edges(a).append(b)\n edges(b).append(a)\n }\n prof(4)\n\n def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n var remote: Option[Int] = None\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n if (marked(next)) remote = Some(next)\n }\n\n remote\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n val dists = Array.fill(graph.size)(0)\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n }\n\n dists\n }\n\n val a = remoteVertex(edges, 1).get\n val b = remoteVertex(edges, a).getOrElse(a)\n prof(5)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n prof(6)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n prof(7)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n\n def readInts(n: Int) = { val st = tokenizeLine; Array.fill(n)(st.nextToken.toInt) }\n\n def prof(i: Int) = if (m == 17585) println(i + \": \" + (System.currentTimeMillis() - executionStart) + \" ms\")\n\n val Array(n, m, d) = readInts(3)\n val marked = new mutable.BitSet(n + 1)\n prof(1)\n marked ++= readInts(m)\n //val st = tokenizeLine\n //for (i <- 0 until m) marked += st.nextToken.toInt\n prof(2)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n prof(3)\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt\n edges(a).append(b)\n edges(b).append(a)\n }\n prof(4)\n\n def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n var remote: Option[Int] = None\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n if (marked(next)) remote = Some(next)\n }\n\n remote\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n val dists = Array.fill(graph.size)(0)\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n }\n\n dists\n }\n\n val a = remoteVertex(edges, 1).get\n val b = remoteVertex(edges, a).getOrElse(a)\n prof(5)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n prof(6)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n prof(7)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n\n def readInts(n: Int) = { val st = tokenizeLine; Array.fill(n)(st.nextToken.toInt) }\n\n def prof(i: Int) = if (m == 17585) println(i + \": \" + (System.currentTimeMillis() - executionStart) + \" ms\")\n\n val Array(n, m, d) = readInts(3)\n prof(1)\n val marked = new mutable.BitSet(n + 1) ++= readInts(m)\n prof(2)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n prof(3)\n\n for (i <- 0 until n - 1) {\n /*val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt*/\n val Array(a, b) = readInts(2)\n edges(a).append(b)\n edges(b).append(a)\n }\n prof(4)\n\n def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n var remote: Option[Int] = None\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n if (marked(next)) remote = Some(next)\n }\n\n remote\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n val dists = Array.fill(graph.size)(0)\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n }\n\n dists\n }\n\n val a = remoteVertex(edges, 1).get\n val b = remoteVertex(edges, a).getOrElse(a)\n prof(5)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n prof(6)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n prof(7)\n\n println(result)\n}"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n\n def readInts(n: Int) = { val st = tokenizeLine; Array.fill(n)(st.nextToken.toInt) }\n\n def prof(i: Int) = if (m == 17585) println(i + \": \" + (System.currentTimeMillis() - executionStart) + \" ms\")\n\n val Array(n, m, d) = readInts(3)\n prof(1)\n val marked = new mutable.BitSet(n + 1) ++= readInts(m)\n prof(2)\n\n val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())\n prof(3)\n\n for (i <- 0 until n - 1) {\n val st = tokenizeLine\n val a = st.nextToken.toInt\n val b = st.nextToken.toInt\n edges(a) :+= b\n edges(b) :+= a\n }\n prof(4)\n\n def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n var remote: Option[Int] = None\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n if (marked(next)) remote = Some(next)\n }\n\n remote\n }\n\n def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {\n\n val visited = new mutable.BitSet(graph.size) + source\n val toVisit = mutable.Queue(source)\n val dists = Array.fill(graph.size)(0)\n\n while (!toVisit.isEmpty) {\n val next = toVisit.dequeue\n val succ = graph(next).filter(!visited(_))\n toVisit ++= succ\n visited ++= succ\n for (s <- succ) dists(s) = dists(next) + 1\n }\n\n dists\n }\n\n val a = remoteVertex(edges, 1).get\n val b = remoteVertex(edges, a).getOrElse(a)\n prof(5)\n\n val fromA = shortestPaths(edges, a)\n val fromB = shortestPaths(edges, b)\n prof(6)\n\n val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)\n prof(7)\n\n println(result)\n}"}], "src_uid": "52863d45ad223687e6975344ab9d3124"} {"source_code": "import java.io.PrintWriter\nimport util.control.Breaks._\n\nobject SolutionA {\n val reader = scala.io.StdIn\n def readInt = reader.readLine().toInt\n def readArrayInt = reader.readLine().split(\" \").map(_.toInt)\n\n def multiTest(f: () => Unit): Unit = {\n var t = readInt\n while (t > 0) {\n f()\n t -= 1\n }\n }\n\n def solve(): Unit = {\n val n = readInt\n val a = readArrayInt\n\n var rs = 0\n var sum = 0\n for (i <- 0 until n) {\n if (a(i) == 0) {\n a(i) = 1\n rs += 1\n\n }\n sum += a(i)\n }\n\n if (sum == 0)\n rs += 1\n\n println(rs)\n }\n\n def main(args: Array[String]) {\n multiTest(solve)\n //solve()\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\nobject Main extends App {\n\n private val getCount: Array[Int] => Int =\n arr => {\n if (arr.product == 0) {\n val count = arr count (_ == 0)\n if (arr.sum + count == 0) count + 1 else count\n } else if (arr.sum == 0)\n 1\n else\n 0\n }\n\n var n = StdIn.readInt()\n var result: ListBuffer[Int] = new ListBuffer\n\n while (n != 0) {\n StdIn.readLine()\n val line = StdIn.readLine()\n val arr = line split \"\\\\s\" map (_.toInt)\n result += getCount(arr)\n\n n = n - 1\n }\n\n result foreach println\n\n}\n"}], "negative_code": [], "src_uid": "1ffb08fe61cdf90099c82162b8353b1f"} {"source_code": "object A549 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val face = \"acef\"\n val Array(n, m) = readInts(2)\n val in = Array.fill(n)(read.toCharArray)\n var res = 0\n for(i <- 0 until n-1; j <- 0 until m-1) {\n var str = \"\"\n str += in(i)(j)\n if(i+1 < n) str += in(i+1)(j)\n if(j+1 < m) str += in(i)(j+1)\n if(i+1 < n && j +1 < m) str += in(i+1)(j+1)\n\n if(str.sorted.equalsIgnoreCase(face))\n res += 1\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val a = new Array[Array[Char]](n)\n for (i <- 0 until n) {\n a(i) = next.toCharArray\n }\n var ans = 0\n val b = Array('f', 'a', 'c', 'e')\n for (i <- 0 until n - 1) {\n for (j <- 0 until m - 1) {\n val s = new mutable.HashSet[Char]()\n var flag = true\n s.add(a(i)(j))\n s.add(a(i + 1)(j))\n s.add(a(i + 1)(j + 1))\n s.add(a(i)(j + 1))\n b.foreach(x => {\n if (!s.contains(x)) {\n flag = false\n }\n })\n if (flag)\n ans += 1\n\n }\n }\n out.println(ans)\n return 0\n }\n}\n"}, {"source_code": "import scala.collection.immutable.IndexedSeq\nimport scala.collection.mutable\n\nobject A {\n\n def check(a: IndexedSeq[String], i: Int, j: Int): Boolean = {\n val s=mutable.TreeSet[Char]()\n s+=a(i).charAt(j)\n s+=a(i).charAt(j+1)\n s+=a(i+1).charAt(j)\n s+=a(i+1).charAt(j+1)\n s.mkString(\"\") == \"acef\"\n }\n\n def main(args: Array[String]) {\n val Array(n,m)=io.StdIn.readLine().split(\" \").map(_.toInt)\n val a = for (i<-1 to n) yield io.StdIn.readLine()\n var k=0\n for (i<-0 until n-1)\n for (j<-0 until m-1){\n if (check(a,i,j))\n k+=1\n }\n println(k)\n }\n}\n"}, {"source_code": "\nobject First extends App{\n /* Created by bfattahov on 06.06.15. */\n\n val input = io.Source.stdin.getLines().toSeq\n val photo = input.drop(1)\n\n val firstLine = Seq.apply(input.head.split(' '): _*).map(_.trim).filterNot(_.isEmpty).take(2).map(_.toInt)\n val rows = firstLine(0)\n val cols = firstLine(1)\n\n //input.foreach(println)\n\n if (rows < 2 || cols < 2) {\n println(0)\n } else {\n val faces = (0 to cols - 2).foldLeft(0) { (res, c) => ; res + (0 to rows - 2).count(r => isItFace(c, r))}\n\n println(faces)\n }\n\n\n def isItFace(c: Int, r: Int): Boolean = {\n Seq(\n photo(r).charAt(c),\n photo(r).charAt(c + 1),\n photo(r + 1).charAt(c),\n photo(r + 1).charAt(c + 1)\n ).foldLeft(0) {\n (res, curr) => {\n res + (curr match {\n case 'a' => 1\n case 'e' => 2\n case 'c' => 4\n case 'f' => 8\n case _ => 0\n })\n }\n } == 15\n }\n}"}, {"source_code": "import java.io.InputStream\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport java.io.PrintWriter\n\nobject CF549A {\n\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n return next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]): Unit = {\n val in = new InputReader(System.in)\n val m = in.nextInt()\n val n = in.nextInt()\n val board = Array.fill(m) { in.next()}\n var sum = 0;\n for(i <- 0 until m)\n for( j <- 0 until n) {\n sum += countFace(i,j,board)\n }\n print(sum)\n }\n\n def countFace(i: Int, j: Int, board: Array[String]): Int = {\n val b = new StringBuilder()\n for(ki <- 0 to 1)\n for(kj <-0 to 1)\n if ( i + ki < board.length && j+ kj < board(0).length )\n {\n b.append(board(i+ki).charAt(j+kj))\n }\n val s = b.toString()\n val face =\"face\"\n for(i <- 0 until face.length) {\n if ( s.indexOf(face.charAt(i)) == -1) return 0\n }\n return 1\n }\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _549A extends App {\n var token = new StringTokenizer(\"\")\n\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n\n val n = next.toInt\n val m = next.toInt\n val a = (1 to n).map(i => next).toArray\n\n val ans = for {\n i <- 0 until n - 1\n j <- 0 until m - 1\n if Set(a(i)(j), a(i)(j + 1), a(i + 1)(j), a(i + 1)(j + 1)) == Set('f', 'a', 'c', 'e')\n } yield 1\n\n println(ans.sum)\n}\n"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val ss = Array.fill(n){ readLine }\n \n def check(i: Int, j: Int) = {\n val set = Set(ss(i)(j), ss(i + 1)(j), ss(i)(j + 1), ss(i + 1)(j + 1))\n set('f') && set('a') && set('c') && set('e')\n }\n\n var res = 0\n for (i <- 0 until n - 1)\n for (j <- 0 until m - 1) {\n if (check(i, j)) res += 1\n }\n println(res)\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject A {\n\n\tdef detectFace(c1:Char, c2:Char, c3:Char, c4:Char):Boolean = \n\t\tList(c1, c2, c3, c4).sorted.mkString.equals(\"acef\")\n\n\tdef countFaces(s1:String, s2:String):Int = {\n\t\treturn (0 until s1.length() - 1)\n\t\t\t.map(i => detectFace(s1.charAt(i), s1.charAt(i + 1), s2.charAt(i), s2.charAt(i + 1)))\n\t\t\t.map(b => if (b) 1 else 0)\n\t\t\t.reduceLeft(_+_)\n\t}\n\n\tdef readAndCountFaces(n:Int):Int = {\n\t\tvar count:Int = 0\n\t\tvar s1:String = in.nextLine\n\t\tfor (i <- 2 to n) {\n\t\t\tvar s2:String = in.nextLine\n\t\t\tcount += countFaces(s1, s2)\n\t\t\ts1 = s2\n\t\t}\n\t\tcount\n\t}\n\n\tval in:Scanner = new Scanner(System.in)\n\n\tdef main(args: Array[String]) = {\n\t\tvar n:Int = in.nextInt\n\t\tvar m:Int = in.nextInt\n\t\tin.nextLine\n\n\t\tval count:Int = if (n > 1 && m > 1) readAndCountFaces(n) else 0\n\n\t\tprintln(count)\n\t}\n\n}"}], "negative_code": [], "src_uid": "742e4e6ca047da5f5ebe5d854d6a2024"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val S = ns()\n val N = S.length\n val cnt1 = S.count(_ == '1')\n var cnt2 = 0\n REP(N - 1) { i =>\n if (S(i) == '1' && S(i + 1) == '0') cnt2 += 1\n }\n\n var cnt3 = 0L\n var c = 0 // 連続した0の個数\n REP(N) { i =>\n if (S(i) == '0') c += 1\n else {\n var x = 0\n REP(min(20, N - i)) { j =>\n if (S(i + j) == '1') x += 1\n if (x > 2 && x <= c + j + 1) cnt3 += 1\n x *= 2\n }\n c = 0\n }\n }\n\n debug(s\"$cnt1 $cnt2 $cnt3\")\n\n val ans = cnt1 + cnt2 + cnt3\n out.println(ans)\n }\n }\n}", "positive_code": [{"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(t) = readInts(1)\n\n for (_ <- 1 to t) {\n val s = readLine.map(_ - '0')\n var res = 0L\n\n val prevZeros = Array.fill(s.length)(0)\n var z = 0\n for (i <- s.indices) {\n if (s(i) == 0) {\n z += 1\n } else z = 0\n prevZeros(i) = z\n }\n\n for (r <- s.indices) {\n var len = 0\n var x = 0L\n while (1L << len <= r + 1 && len <= r) {\n x = x + (s(r - len) << len)\n len += 1\n if (x == len) res += 1\n //println(len, x, r)\n }\n //if (len <= r) println(\"!\", len, x, prevZeros(r - len))\n if (len <= r && prevZeros(r - len) + len >= x && x > len) res += 1\n }\n\n println(res)\n }\n}\n"}], "negative_code": [], "src_uid": "3c93a76f986b1ef653bf5834716ac72a"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val n = ni()\n var zeros, ones = 0\n var odds = 0\n var bitOdds = 0\n REP(n) { _ =>\n val s = ns()\n val z = s.count(_ == '0')\n val o = s.length - z\n zeros += z\n ones += o\n if (s.length % 2 == 1) odds += 1\n }\n\n debug(s\"$zeros $ones $odds\")\n\n if (zeros % 2 == 1) bitOdds += 1\n if (ones % 2 == 1) bitOdds += 1\n\n val ok = if (bitOdds == 0) {\n odds % 2 == 0\n } else if (bitOdds == 1) {\n odds % 2 == 1\n } else {\n odds >= 2 && odds % 2 == 0\n }\n\n if (ok) {\n out.println(n)\n } else {\n out.println(n - 1)\n }\n }\n }\n}", "positive_code": [{"source_code": "object BinaryPalindrome extends App {\n\n val array = readFromTerminal()\n for (row <- array)\n println(compute(row))\n\n def readFromTerminal(): Seq[Seq[String]] = {\n val q = readInt()\n// val q = 4\n// val list = List(\n// List(\"0\"),\n// List(\"1110\",\"100110\",\"010101\"),\n// List(\"11111\",\"000001\"),\n// List(\"001\",\"11100111\"),\n// )\n//1\n//2\n//2\n//2\n val list: Seq[Seq[String]] = (1 to q).toList.map { j => {\n val n = readInt()\n val t: Seq[String] = for (i <- 1 to n) yield readLine()\n t\n }}\n list\n }\n\n def compute(rows: Seq[String]): Int = {\n val (zeros, ones): (Int, Int) = rows.map{ row => (\n row.count{ c => c == '0'},\n row.count{ c => c =='1'}\n )}.fold((0,0))((acc, pair) => (acc._1 + pair._1,acc._2 + pair._2))\n //все длины\n val lengths = rows.map{row => row.length }\n //сколько есть пар\n val possiblePairs = (zeros / 2) + (ones / 2)\n // сколько нужно пар\n val needPairs = lengths.fold(0){(acc, length) => acc + length/2}\n\n val unpairedNumbers = lengths.sum - possiblePairs*2\n if ((possiblePairs - needPairs) <0 )\n lengths.size+(possiblePairs - needPairs)\n else\n lengths.size\n }\n}"}], "negative_code": [], "src_uid": "3b8678d118c90d34c99ffa9259cc611f"} {"source_code": "import java.util.regex.Pattern\n\nimport scala.io.StdIn\n\nobject Solution {\n //Console.setIn(new FileReader(new java.io.File(\"in\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n\n val magicMod = 1000000007\n\n def doCase(caseNo: Int): Unit = {\n val str = readLine()\n\n var state = 0\n var i = 0\n while (i < str.length) {\n if (state == 0 && str(i) == '[') {\n state += 1\n } else if (state == 1 && str(i) == ':') {\n state += 1\n } else if (state == 2 && str(i) == ':') {\n state += 1\n } else if (state == 3 && str(i) == ']') {\n state += 1\n }\n i += 1\n }\n\n if (state != 4) {\n println(-1)\n return\n }\n\n var firstLBracket : Option[Int] = None\n var lastRBracket : Option[Int] = None\n\n i = 0\n while (i < str.length) {\n if (str(i) == '[') {\n firstLBracket = firstLBracket.orElse(Some(i))\n } else if (str(i) == ']') {\n lastRBracket = Some(i)\n }\n i += 1\n }\n\n if (firstLBracket.isEmpty || lastRBracket.isEmpty || firstLBracket.get > lastRBracket.get) {\n println(-1)\n return\n }\n\n var barCount = 0\n val cumulativeBars = Array.fill(str.length + 1)(0)\n\n i = 0\n while (i <= str.length) {\n cumulativeBars(i) = barCount\n if (i < str.length && str(i) == '|') {\n barCount += 1\n }\n i += 1\n }\n\n var colons : List[Int] = List()\n i = firstLBracket.get\n while (i < lastRBracket.get) {\n if (str(i) == ':') {\n colons ::= i\n }\n i += 1\n }\n colons = colons.reverse\n\n var bestCount = 0\n\n val l = colons.head\n val r = colons.last\n val count = cumulativeBars(r) - cumulativeBars(l)\n bestCount = if (bestCount < count) count else bestCount\n\n println(bestCount + 4)\n }\n\n def main(args: Array[String]): Unit = {\n val noCases = 1\n for (i <- 0 until noCases) {\n doCase(i)\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n def readLongLine(): Array[Long] = {\n StdIn.readLine().split(\" \").map(_.toLong)\n }\n\n def readBigIntLine(): Array[BigInt] = {\n StdIn.readLine().split(\" \").map(BigInt.apply)\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S = ns()\n val open = S.indexWhere(_ == '[')\n val close = S.lastIndexWhere(_ == ']')\n\n if (open != -1 && close != -1) {\n val first = S.indexWhere(_ == ':', open + 1)\n val last = S.lastIndexWhere(_ == ':', close - 1)\n if (first != -1 && last != -1 && open < first && first < last && last < close) {\n val ans = S.slice(first + 1, last).count(_ == '|') + 4\n out.println(ans)\n } else {\n out.println(-1)\n }\n } else {\n out.println(-1)\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object EDU_58_B {\n\n type In = (String)\n type Out = Int\n\n def solve(in: In): Out = {\n val (s) = in\n\n def eat(s: String, c: Char): Option[String] =\n s.indexOf(c) match {\n case -1 => None\n case i => Some(s.substring(i + 1))\n }\n\n val lines = for {\n p1 <- eat(s, '[')\n p2 <- eat(p1, ':')\n r = p2.reverse\n p4 <- eat(r, ']')\n p3 <- eat(p4, ':')\n } yield p3.count(_ == '|')\n\n lines match {\n case None => -1\n case Some(i) => i + 4\n }\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.nextLine)\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change:\n\n import java.io.InputStream\n import java.util.Scanner\n\n import language.implicitConversions\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n\n class Input(sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty\n else sc.nextLine +: getLines\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def ceil(a: Int, b: Int) = (a - 1)/b + 1\n def ceil(a: Long, b: Long) = (a - 1)/b + 1\n\n // A frequently used number\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input\n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {\n def tupled: T => R = x => f(x)\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S = ns()\n val open = S.indexWhere(_ == '[')\n val first = S.indexWhere(_ == ':')\n val last = S.lastIndexWhere(_ == ':')\n val close = S.lastIndexWhere(_ == ']')\n val found = open != -1 && first != -1 && last != -1 && close != -1\n if (found && open < first && first < last && last < close) {\n val ans = S.slice(first + 1, last).count(_ == '|') + 4\n out.println(ans)\n } else {\n out.println(-1)\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S = ns()\n val open = S.indexWhere(_ == '[')\n val first = S.indexWhere(_ == ':')\n val last = S.lastIndexWhere(_ == ':')\n val close = S.lastIndexWhere(_ == ']')\n if (open < first && first < last && last < close) {\n val ans = S.slice(first + 1, last).count(_ == '|') + 4\n out.println(ans)\n } else {\n out.println(-1)\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object EDU_58_B {\n\n type In = (String)\n type Out = Int\n\n def solve(in: In): Out = {\n val (s) = in\n\n val model = \"[::]\"\n\n val ans = {\n def loop(in: Seq[Char], out: String, nextChars: String, colonCount: Int): String = in match {\n case Seq() => out\n case _ if nextChars.isEmpty => out\n case _ => in.head match {\n case h if h == nextChars.head => loop(in.tail, out + h, nextChars.tail, colonCount)\n case h if h == nextChars.head && h == ':' => loop(in.tail, out + h, nextChars.tail, colonCount + 1)\n case h if h == '|' && colonCount == 1 => loop(in.tail, out + h, nextChars, colonCount)\n case _ => loop(in.tail, out, nextChars, colonCount)\n }\n }\n loop(s, \"\", model, 0)\n }\n\n\n /*s.foldLeft(\"\") { (acc, c) =>\n (acc, c) match {\n case (\"\", '[') => \"[\"\n case (\"[\", ':') => \"[:\"\n case (_, '|') if acc.matches(\"\"\"^\\[\\:\\|*\"\"\") => acc + '|'\n case (_, ':') if acc.matches(\"\"\"^\\[\\:\\|*\"\"\") => acc + ':'\n case (_, ']') if acc.matches(\"\"\"^\\[\\:\\|*\\:\"\"\") => acc + ']'\n case _ => acc\n }\n }*/\n\n if(ans.matches(\"\"\"^\\[\\:\\|*\\:\\]$\"\"\")) ans.length else -1\n\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.nextLine)\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change:\n\n import java.io.InputStream\n import java.util.Scanner\n\n import language.implicitConversions\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n\n class Input(sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty\n else sc.nextLine +: getLines\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def ceil(a: Int, b: Int) = (a - 1)/b + 1\n def ceil(a: Long, b: Long) = (a - 1)/b + 1\n\n // A frequently used number\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input\n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {\n def tupled: T => R = x => f(x)\n }\n}"}, {"source_code": "object EDU_58_B {\n\n type In = (String)\n type Out = Int\n\n def solve(in: In): Out = {\n val (s) = in\n\n val Reg = \"\"\"^\\[\\:\\|*\\:\\]$\"\"\"\n def isAccordian(s: String) = s matches Reg\n\n val a = \"[::]\"\n\n val p1 = s.dropWhile(_ != '[')\n\n val ans = s.foldLeft(\"\") { (acc, c) =>\n (acc, c) match {\n case (\"\", '[') => \"[\"\n case (\"[\", ':') => \"[:\"\n case (_, '|') if acc.matches(\"\"\"^\\[\\:\\|*\"\"\") => acc + '|'\n case (_, ':') if acc.matches(\"\"\"^\\[\\:\\|*\"\"\") => acc + ':'\n case (_, ']') if acc.matches(\"\"\"^\\[\\:\\|*\\:\"\"\") => acc + ']'\n case _ => acc\n }\n }\n\n if(ans.matches(Reg)) ans.length else -1\n\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.nextLine)\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change:\n\n import java.io.InputStream\n import java.util.Scanner\n\n import language.implicitConversions\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n\n class Input(sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty\n else sc.nextLine +: getLines\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def ceil(a: Int, b: Int) = (a - 1)/b + 1\n def ceil(a: Long, b: Long) = (a - 1)/b + 1\n\n // A frequently used number\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input\n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {\n def tupled: T => R = x => f(x)\n }\n}\n"}, {"source_code": "import java.util.regex.Pattern\n\nimport scala.io.StdIn\n\nobject Solution {\n //Console.setIn(new FileReader(new java.io.File(\"in\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n\n val magicMod = 1000000007\n\n def doCase(caseNo: Int): Unit = {\n val str = readLine()\n\n if (!Pattern.matches(\".*\\\\[.*:.*:.*\\\\].*\", str)) {\n println(-1)\n return\n }\n\n var firstLBracket : Option[Int] = None\n var lastRBracket : Option[Int] = None\n\n var i = 0\n while (i < str.length) {\n if (str(i) == '[') {\n firstLBracket = firstLBracket.orElse(Some(i))\n } else if (str(i) == ']') {\n lastRBracket = Some(i)\n }\n i += 1\n }\n\n if (firstLBracket.isEmpty || lastRBracket.isEmpty || firstLBracket.get > lastRBracket.get) {\n println(-1)\n return\n }\n\n var barCount = 0\n val cumulativeBars = Array.fill(str.length + 1)(0)\n\n i = 0\n while (i <= str.length) {\n cumulativeBars(i) = barCount\n if (i < str.length && str(i) == '|') {\n barCount += 1\n }\n i += 1\n }\n\n var colons : List[Int] = List()\n i = firstLBracket.get\n while (i < lastRBracket.get) {\n if (str(i) == ':') {\n colons ::= i\n }\n i += 1\n }\n colons = colons.reverse\n\n var bestCount = 0\n for (List(l, r) <- colons.sliding(2)) {\n val count = cumulativeBars(r) - cumulativeBars(l)\n bestCount = if (bestCount < count) count else bestCount\n }\n\n println(bestCount + 4)\n }\n\n def main(args: Array[String]): Unit = {\n val noCases = 1\n for (i <- 0 until noCases) {\n doCase(i)\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n def readLongLine(): Array[Long] = {\n StdIn.readLine().split(\" \").map(_.toLong)\n }\n\n def readBigIntLine(): Array[BigInt] = {\n StdIn.readLine().split(\" \").map(BigInt.apply)\n }\n}"}], "src_uid": "915b4776a6b1fa15886247eb1ad40b60"} {"source_code": "\nimport java.util.StringTokenizer\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\nimport java.security.SecureRandom\n\nobject CF_504_D { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n runTest(Test.t7)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading\n val l1 = readLine\n val n = l1.int\n val Q = l1.int\n val arrLine = readLine\n val arr = new Array[Int](n)\n val startTime = System.currentTimeMillis()\n \n class Cell(val ind: Int, val value: Int) {\n var prev: Cell = null\n var next: Cell = null\n }\n \n class ArrList() {\n var first: Cell = null\n var last: Cell = null\n \n def add(cc: Cell) {\n if (first == null) {\n first = cc\n } else {\n last.next = cc\n cc.prev = last\n }\n last = cc\n }\n def remove(cc: Cell) {\n if (cc.prev != null) {\n cc.prev.next = cc.next\n }\n if (cc.next != null) {\n cc.next.prev = cc.prev\n }\n if (cc == first) { \n first = cc.next\n } \n if (cc == last) { \n last = cc.prev\n }\n }\n def mkString: String= {\n var cur = first\n var res = \"\"\n while (cur != null) {\n// res += cur.ind+\"-\"+cur.value + \",\"\n res += cur.value + \",\"\n cur = cur.next\n }\n res\n }\n }\n val aList = new ArrList()\n \n for(i <- 0 until n) {\n val vv = arrLine.int\n arr(i) = vv\n }\n \n var cur = aList.first\n while (cur != null) {\n print(cur.value + \" \")\n cur = cur.next\n }\n println\n \n// if (arr(0) == 1912) {\n// var acc = \"\"\n// for(i <- 0 until n) {\n// acc += arr(i) + \" \"\n// if (i % 50 == 0) {\n// println(acc)\n// acc = \"\"\n// }\n// }\n// }\n \n var lastPresent = false\n var zeroInd = -1\n for( i <- 0 until n) {\n if (arr(i) == Q) lastPresent = true\n if (arr(i) == 0) zeroInd = i\n }\n if (!lastPresent && zeroInd != -1) arr(zeroInd) = Q\n \n //copy to linked list\n val starts = new Array[Cell](Q+1)\n val counts = new Array[Int](Q+1)\n for(i <- 0 until n) {\n val q = arr(i)\n val cc = new Cell(i, q)\n if (starts(q) == null) { starts(q) = cc }\n counts(q) += 1 \n aList.add(cc) \n }\n \n val resArr = new Array[Int](n)\n var good = true\n \n// def calc(): Unit = {\n// for(qu <- Q to 1 by -1) { \n// var started = false\n// var finished = false\n// for(i <- 0 until n) {\n// (started, finished) match {\n// case (false, false) => {\n// if (arr(i) == qu) {\n// started = true\n// arr(i) = -1\n// resArr(i) = qu\n// }\n// }\n// case (true, false) => {\n// if (arr(i) != qu && arr(i) != 0 && arr(i) != -1) {\n// finished = true\n// } else { //still continue\n// if (arr(i) != -1) {\n// resArr(i) = qu\n// arr(i) = -1\n// }\n// }\n// }\n// case (true, true) => {\n// if (arr(i) == qu) {\n// good = false\n// // if (arr(0) == 1912) {\n// // println(\"Break on \" + qu + \" i=\" + i)\n// // }\n// }\n// }\n// }\n// if (!good) return\n// }\n//// debug(\"After: \" + qu)\n// }\n// }\n// calc()\n\n debug(\"After query \" + \"0\" + \": \" + aList.mkString)\n \n val sss = System.currentTimeMillis()\n var totalSteps = 0\n def calc2(): Unit = {\n for(qu <- Q to 1 by -1) { \n var started = false\n var finished = false\n var curCell = starts(qu)\n while(good && curCell != null && counts(qu) > 0) {\n totalSteps += 1\n (started, finished) match {\n case (false, false) => {\n if (curCell.value == qu) {\n started = true\n aList.remove(curCell)\n resArr(curCell.ind) = qu\n counts(qu) -= 1\n// debug(\"Removed first cell\" + curCell)\n }\n }\n case (true, false) => {\n if (curCell.value != qu && curCell.value != 0) {\n finished = true\n// debug(\"finished\")\n } else { //still continue\n aList.remove(curCell)\n resArr(curCell.ind) = qu\n if (curCell.value == qu) { counts(qu) -= 1 }\n// debug(\"Removed subseq cell\" + curCell)\n }\n }\n case (true, true) => {\n if (curCell.value == qu) {\n debug(\"Fail at secondary piece: \" + qu)\n good = false\n }\n }\n }\n// debug(\" - After step \" + qu + \": \" + aList.mkString)\n curCell = curCell.next\n }\n debug(\"After query \" + qu + \": \" + aList.mkString)\n }\n }\n calc2\n val ddd = System.currentTimeMillis() - sss\n debug(\"calc2 dur \" + ddd + \" steps=\" + totalSteps)\n \n var last = resArr(n-1)\n// if (last == 0) last = Q\n for(i <- n-1 to 0 by -1) {\n if (resArr(i) == 0) {\n resArr(i) = last\n }\n last = resArr(i)\n }\n last = resArr(0)\n for(i <- 0 until n) {\n if (resArr(i) == 0) {\n resArr(i) = last\n }\n last = resArr(i)\n }\n \n lastPresent = false\n for( i <- 0 until n) {\n if (resArr(i) == Q) lastPresent = true\n }\n if (!lastPresent) {\n debug(\"Fail at top query absent\")\n good = false\n }\n \n if (good) {\n outLn(\"YES\")\n outLn(resArr.mkString(\" \"))\n } else {\n outLn(\"NO\")\n }\n \n debug(\"================= RESULT ================== \")\n val endTime = System.currentTimeMillis() - startTime\n debug(\"Exec time: \" + endTime)\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4 3\n1 0 2 3\n\"\"\"\n\nval sa2 = \"\"\"\n\"\"\"\n\nval t7 = \"\"\"\n50 2\n0 1 0 1 0 0 1 0 1 1 0 1 1 1 2 2 0 2 0 2 0 2 0 0 2 2 2 0 0 0 0 1 0 1 0 0 1 0 1 0 0 1 1 0 1 1 0 1 0 0\n\"\"\"\n\nval m1 = \"\"\"\n4 3\n1 0 2 3\n\"\"\"\n\nval m2 = \"\"\"\n20 20\n17 17 19 19 17 20 20 17 16 16 16 16 16 18 18 18 18 18 6 0\n\"\"\"\n\ndef gen = {\n val runStart = System.currentTimeMillis()\n val n = 200000\n val q = 200000\n val rr = new SecureRandom\n val arr = new Array[Int](n)\n for(i <- 1 to q) {\n val start = rr.nextInt(n-1)\n val length = 1 //rr.nextInt(n-start-1)\n// val length = n-q\n val end = length + start\n for (j <- start to end) {\n arr(j) = i\n }\n }\n val res = s\"$n $q\" + \"\\n\" + arr.mkString(\" \")\n val runEnd = System.currentTimeMillis() - runStart\n println(\"Gen time \" + runEnd)\n println(res)\n res\n}\n\n}\n\n}\n\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, Q = ni()\n val A = na(N)\n\n val seg = new SegmentTree(N)\n rep(N) { i =>\n val a = A(i)\n if (a != 0) seg.update(i, a)\n }\n\n val L = Array.fill[Int](Q + 1)(-1)\n val R = Array.fill[Int](Q + 1)(-1)\n\n val zeros = ArrayBuffer[(Int, Int)]()\n var zero = -1\n\n rep(N) { i =>\n val a = A(i)\n if (L(a) == -1) L(a) = i\n R(a) = i\n\n if (a == 0) {\n if (zero == -1) zero = i\n } else if (zero != -1) {\n zeros += ((zero, i))\n zero = -1\n }\n }\n if (zero != -1) {\n zeros += ((zero, N))\n }\n\n var ok = true\n rep(Q, 1) { q =>\n if (L(q) != -1) {\n val ms = seg.query(L(q), R(q) + 1)\n ok &= ms == q\n }\n }\n\n // Qがでてくるか、0があれば\n val hasQ = L(Q) != -1\n ok &= hasQ || zeros.nonEmpty\n\n if (ok) {\n out.println(\"YES\")\n\n def fillZero(zero: (Int, Int)): Unit = {\n val (l, r) = zero\n val x = if (l > 0) A(l - 1) else A(r)\n fillZeroBy(zero, x)\n }\n\n def fillZeroBy(zero: (Int, Int), x: Int): Unit = {\n val (l, r) = zero\n rep(r - l)(i => A(l + i) = x)\n }\n\n // 全部0の場合も!hasQかつzeros.length == 1 なのでこれで大丈夫\n if (!hasQ) {\n rep(zeros.length - 1)(i => fillZero(zeros(i)))\n fillZeroBy(zeros.last, Q) // 一箇所Qで埋める\n } else {\n rep(zeros.length)(i => fillZero(zeros(i)))\n }\n\n out.println(A.mkString(\" \"))\n } else {\n out.println(\"NO\")\n }\n }\n\n class SegmentTree(n: Int) {\n private val N = {\n val a = Integer.highestOneBit(n)\n if (a == n) a else a << 1\n }\n private val dat: Array[Int] = Array.fill(2 * N - 1)(Integer.MAX_VALUE)\n\n def update(i: Int, a: Int): Unit = {\n var k = N - 1 + i\n dat(k) = a\n while(k > 0) {\n k = (k - 1) / 2\n dat(k) = min(dat(2 * k + 1), dat(2 * k + 2))\n }\n }\n\n def query(a: Int, b: Int): Int = {\n def step(k: Int, l: Int, r: Int): Int = {\n if (r <= a || b <= l) {\n Integer.MAX_VALUE\n } else if (a <= l && r <= b) {\n dat(k)\n } else {\n val vl = step(k * 2 + 1, l, (l + r) / 2)\n val vr = step(k * 2 + 2, (l + r) / 2, r)\n min(vl, vr)\n }\n }\n\n step(0, 0, N)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, Q = ni()\n val A = na(N)\n\n val seg = new SegmentTree(N)\n rep(N) { i =>\n val a = A(i)\n seg.update(i, a)\n }\n\n val L = Array.fill[Int](Q + 1)(-1)\n val R = Array.fill[Int](Q + 1)(-1)\n\n rep(N) { i =>\n val a = A(i)\n if (L(a) == -1) L(a) = i\n R(a) = i\n }\n\n var ok = true\n rep(Q, 1) { q =>\n val ms = seg.query(L(q), R(q) + 1)\n ok &= ms == Integer.MAX_VALUE || ms == q\n }\n\n if (ok) {\n out.println(\"YES\")\n rep(N - 1, 1) { i =>\n if (A(i) == 0) A(i) = A(i - 1)\n }\n\n rep_r(N - 1) { i =>\n if (A(i) == 0) A(i) = A(i + 1)\n }\n\n if (A(0) == 0) {\n rep(N)(i => A(i) = Q)\n }\n\n out.println(A.mkString(\" \"))\n } else {\n out.println(\"NO\")\n }\n }\n\n class SegmentTree(n: Int) {\n private val N = {\n val a = Integer.highestOneBit(n)\n if (a == n) a else a << 1\n }\n private val dat: Array[Int] = Array.fill(2 * N - 1)(0)\n\n def update(i: Int, a: Int): Unit = {\n var k = N - 1 + i\n dat(k) = a\n while(k > 0) {\n k = (k - 1) / 2\n dat(k) = min(dat(2 * k + 1), dat(2 * k + 2))\n }\n }\n\n def query(a: Int, b: Int): Int = {\n def step(k: Int, l: Int, r: Int): Int = {\n if (r <= a || b <= l) {\n Integer.MAX_VALUE\n } else if (a <= l && r <= b) {\n dat(k)\n } else {\n val vl = step(k * 2 + 1, l, (l + r) / 2)\n val vr = step(k * 2 + 2, (l + r) / 2, r)\n min(vl, vr)\n }\n }\n\n step(0, 0, N)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, Q = ni()\n val A = na(N)\n\n val seg = new SegmentTree(N)\n rep(N) { i =>\n val a = A(i)\n seg.update(i, a)\n }\n\n val L = Array.fill[Int](Q + 1)(-1)\n val R = Array.fill[Int](Q + 1)(-1)\n\n val zeros = ArrayBuffer[(Int, Int)]()\n var zero = -1\n\n rep(N) { i =>\n val a = A(i)\n if (L(a) == -1) L(a) = i\n R(a) = i\n\n if (a == 0) {\n if (zero == -1) zero = i\n } else if (zero != -1) {\n zeros += ((zero, i))\n zero = -1\n }\n }\n if (zero != -1) {\n zeros += ((zero, N))\n }\n\n var ok = true\n rep(Q, 1) { q =>\n val ms = seg.query(L(q), R(q) + 1)\n ok &= ms == Integer.MAX_VALUE || ms == q\n }\n\n // Qがでてくるか、0があれば\n val hasQ = L(Q) != -1\n ok &= hasQ || zeros.nonEmpty\n\n if (ok) {\n out.println(\"YES\")\n\n def fillZero(zero: (Int, Int)): Unit = {\n val (l, r) = zero\n val x = if (l > 0) A(l - 1) else A(r)\n fillZeroBy(zero, x)\n }\n\n def fillZeroBy(zero: (Int, Int), x: Int): Unit = {\n val (l, r) = zero\n rep(r - l)(i => A(l + i) = x)\n }\n\n // 全部0の場合も!hasQかつzeros.length == 1 なのでこれで大丈夫\n if (!hasQ) {\n rep(zeros.length - 1)(i => fillZero(zeros(i)))\n fillZeroBy(zeros.last, Q) // 一箇所Qで埋める\n } else {\n rep(zeros.length)(i => fillZero(zeros(i)))\n }\n\n out.println(A.mkString(\" \"))\n } else {\n out.println(\"NO\")\n }\n }\n\n class SegmentTree(n: Int) {\n private val N = {\n val a = Integer.highestOneBit(n)\n if (a == n) a else a << 1\n }\n private val dat: Array[Int] = Array.fill(2 * N - 1)(0)\n\n def update(i: Int, a: Int): Unit = {\n var k = N - 1 + i\n dat(k) = a\n while(k > 0) {\n k = (k - 1) / 2\n dat(k) = min(dat(2 * k + 1), dat(2 * k + 2))\n }\n }\n\n def query(a: Int, b: Int): Int = {\n def step(k: Int, l: Int, r: Int): Int = {\n if (r <= a || b <= l) {\n Integer.MAX_VALUE\n } else if (a <= l && r <= b) {\n dat(k)\n } else {\n val vl = step(k * 2 + 1, l, (l + r) / 2)\n val vr = step(k * 2 + 2, (l + r) / 2, r)\n min(vl, vr)\n }\n }\n\n step(0, 0, N)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, Q = ni()\n val A = na(N)\n\n val seg = new SegmentTree(N)\n rep(N) { i =>\n val a = A(i)\n seg.update(i, a)\n }\n\n val L = Array.fill[Int](Q + 1)(-1)\n val R = Array.fill[Int](Q + 1)(-1)\n\n rep(N) { i =>\n val a = A(i)\n if (L(a) == -1) L(a) = i\n R(a) = i\n }\n\n var ok = true\n rep(Q, 1) { q =>\n val ms = seg.query(L(q), R(q) + 1)\n ok &= ms == Integer.MAX_VALUE || ms == q\n }\n\n if (ok) {\n out.println(\"YES\")\n rep(N - 1, 1) { i =>\n if (A(i) == 0) A(i) = A(i - 1)\n }\n\n rep_r(N - 1) { i =>\n if (A(i) == 0) A(i) = A(i + 1)\n }\n\n if (A(0) == 0) {\n rep(N)(i => A(i) = 1)\n }\n\n out.println(A.mkString(\" \"))\n } else {\n out.println(\"NO\")\n }\n }\n\n class SegmentTree(n: Int) {\n private val N = {\n val a = Integer.highestOneBit(n)\n if (a == n) a else a << 1\n }\n private val dat: Array[Int] = Array.fill(2 * N - 1)(0)\n\n def update(i: Int, a: Int): Unit = {\n var k = N - 1 + i\n dat(k) = a\n while(k > 0) {\n k = (k - 1) / 2\n dat(k) = min(dat(2 * k + 1), dat(2 * k + 2))\n }\n }\n\n def query(a: Int, b: Int): Int = {\n def step(k: Int, l: Int, r: Int): Int = {\n if (r <= a || b <= l) {\n Integer.MAX_VALUE\n } else if (a <= l && r <= b) {\n dat(k)\n } else {\n val vl = step(k * 2 + 1, l, (l + r) / 2)\n val vr = step(k * 2 + 2, (l + r) / 2, r)\n min(vl, vr)\n }\n }\n\n step(0, 0, N)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}, {"source_code": "\nimport java.util.StringTokenizer\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_504_D { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.t1)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading\n val l1 = readLine\n val n = l1.int\n val Q = l1.int\n val arrLine = readLine\n val arr = new Array[Int](n)\n \n for(i <- 0 until n) {\n arr(i) = arrLine.int\n }\n \n val resArr = new Array[Int](n)\n var good = true\n for(qu <- Q to 1 by -1) { \n var started = false\n var finished = false\n for(i <- 0 until n) {\n (started, finished) match {\n case (false, false) => {\n if (arr(i) == qu) {\n started = true\n arr(i) = -1\n resArr(i) = qu\n }\n }\n case (true, false) => {\n if (arr(i) != qu && arr(i) != 0 && arr(i) != -1) {\n finished = true\n } else {\n if (arr(i) != -1)\n resArr(i) = qu\n }\n }\n case (true, true) => {\n if (arr(i) == qu) {\n good = false\n }\n }\n }\n }\n debug(\"After: \" + qu)\n }\n var last = resArr(n-1)\n if (last == 0) last = Q\n for(i <- n-1 to 0 by -1) {\n if (resArr(i) == 0) {\n resArr(i) = last\n }\n last = resArr(i)\n }\n if (good) {\n outLn(\"YES\")\n outLn(resArr.mkString(\" \"))\n } else {\n outLn(\"NO\")\n }\n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4 3\n1 0 2 3\n\"\"\"\n\nval sa2 = \"\"\"\n\"\"\"\n\nval t1 = \"\"\"\n4 3\n0 1 2 3\n\"\"\"\n\n}\n\n}\n\n"}, {"source_code": "\nimport java.util.StringTokenizer\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_504_D { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.t1)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading\n val l1 = readLine\n val n = l1.int\n val Q = l1.int\n val arrLine = readLine\n val arr = new Array[Int](n)\n \n for(i <- 0 until n) {\n arr(i) = arrLine.int\n }\n \n// if (arr(0) == 1912) {\n// var acc = \"\"\n// for(i <- 0 until n) {\n// acc += arr(i) + \" \"\n// if (i % 50 == 0) {\n// println(acc)\n// acc = \"\"\n// }\n// }\n// }\n \n val resArr = new Array[Int](n)\n var good = true\n for(qu <- Q to 1 by -1) { \n var started = false\n var finished = false\n for(i <- 0 until n) {\n (started, finished) match {\n case (false, false) => {\n if (arr(i) == qu) {\n started = true\n arr(i) = -1\n resArr(i) = qu\n }\n }\n case (true, false) => {\n if (arr(i) != qu && arr(i) != 0 && arr(i) != -1) {\n finished = true\n } else { //still continue\n if (arr(i) != -1) {\n resArr(i) = qu\n arr(i) = -1\n }\n }\n }\n case (true, true) => {\n if (arr(i) == qu) {\n good = false\n if (arr(0) == 1912) {\n println(\"Break on \" + qu + \" i=\" + i)\n }\n }\n }\n }\n }\n debug(\"After: \" + qu)\n }\n var last = resArr(n-1)\n if (last == 0) last = Q\n for(i <- n-1 to 0 by -1) {\n if (resArr(i) == 0) {\n resArr(i) = last\n }\n last = resArr(i)\n }\n var lastPresent = false\n for( i <- 0 until n) {\n if (resArr(i) == Q) lastPresent = true\n }\n if (!lastPresent) good = false\n \n if (good) {\n outLn(\"YES\")\n outLn(resArr.mkString(\" \"))\n } else {\n outLn(\"NO\")\n }\n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4 3\n1 0 2 3\n\"\"\"\n\nval sa2 = \"\"\"\n\"\"\"\n\nval t1 = \"\"\"\n4 3\n0 1 2 3\n\"\"\"\n\n}\n\n}\n\n"}, {"source_code": "\nimport java.util.StringTokenizer\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_504_D { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.t1)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading\n val l1 = readLine\n val n = l1.int\n val Q = l1.int\n val arrLine = readLine\n val arr = new Array[Int](n)\n \n for(i <- 0 until n) {\n arr(i) = arrLine.int\n }\n \n val resArr = new Array[Int](n)\n var good = true\n for(qu <- Q to 1 by -1) { \n var started = false\n var finished = false\n for(i <- 0 until n) {\n (started, finished) match {\n case (false, false) => {\n if (arr(i) == qu) {\n started = true\n arr(i) = -1\n resArr(i) = qu\n }\n }\n case (true, false) => {\n if (arr(i) != qu && arr(i) != 0 && arr(i) != -1) {\n finished = true\n } else {\n if (arr(i) != -1)\n resArr(i) = qu\n }\n }\n case (true, true) => {\n if (arr(i) == qu) {\n good = false\n }\n }\n }\n }\n debug(\"After: \" + qu)\n }\n var last = resArr(n-1)\n if (last == 0) last = 1\n for(i <- n-1 to 0 by -1) {\n if (resArr(i) == 0) {\n resArr(i) = last\n }\n last = resArr(i)\n }\n if (good) {\n outLn(\"YES\")\n outLn(resArr.mkString(\" \"))\n } else {\n outLn(\"NO\")\n }\n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4 3\n1 0 2 3\n\"\"\"\n\nval sa2 = \"\"\"\n\"\"\"\n\nval t1 = \"\"\"\n4 3\n0 1 2 3\n\"\"\"\n\n}\n\n}\n\n"}, {"source_code": "import java.util.StringTokenizer\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\nimport java.security.SecureRandom\n\nobject CF_504_D { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.gen)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading\n val l1 = readLine\n val n = l1.int\n val Q = l1.int\n val arrLine = readLine\n val arr = new Array[Int](n)\n val startTime = System.currentTimeMillis()\n \n class Cell(val ind: Int, val value: Int) {\n var prev: Cell = null\n var next: Cell = null\n }\n \n class ArrList() {\n var first: Cell = null\n var last: Cell = null\n \n def add(cc: Cell) {\n if (first == null) {\n first = cc\n } else {\n last.next = cc\n cc.prev = last\n }\n last = cc\n }\n def remove(cc: Cell) {\n if (cc.prev != null) {\n cc.prev.next = cc.next\n }\n if (cc.next != null) {\n cc.next.prev = cc.prev\n }\n if (cc == first) { \n first = cc.next\n } \n if (cc == last) { \n last = cc.prev\n }\n }\n def mkString: String= {\n var cur = first\n var res = \"\"\n while (cur != null) {\n// res += cur.ind+\"-\"+cur.value + \",\"\n res += cur.value + \",\"\n cur = cur.next\n }\n res\n }\n }\n val aList = new ArrList()\n \n for(i <- 0 until n) {\n val vv = arrLine.int\n arr(i) = vv\n }\n \n var cur = aList.first\n while (cur != null) {\n print(cur.value + \" \")\n cur = cur.next\n }\n println\n \n// if (arr(0) == 1912) {\n// var acc = \"\"\n// for(i <- 0 until n) {\n// acc += arr(i) + \" \"\n// if (i % 50 == 0) {\n// println(acc)\n// acc = \"\"\n// }\n// }\n// }\n \n var lastPresent = false\n var zeroInd = -1\n for( i <- 0 until n) {\n if (arr(i) == Q) lastPresent = true\n if (arr(i) == 0) zeroInd = i\n }\n if (!lastPresent && zeroInd != -1) arr(zeroInd) = Q\n \n //copy to linked list\n val starts = new Array[Cell](Q+1)\n val counts = new Array[Int](Q+1)\n for(i <- 0 until n) {\n val q = arr(i)\n val cc = new Cell(i, q)\n if (starts(q) == null) { starts(q) = cc }\n counts(q) += 1 \n aList.add(cc) \n }\n \n val resArr = new Array[Int](n)\n var good = true\n \n// def calc(): Unit = {\n// for(qu <- Q to 1 by -1) { \n// var started = false\n// var finished = false\n// for(i <- 0 until n) {\n// (started, finished) match {\n// case (false, false) => {\n// if (arr(i) == qu) {\n// started = true\n// arr(i) = -1\n// resArr(i) = qu\n// }\n// }\n// case (true, false) => {\n// if (arr(i) != qu && arr(i) != 0 && arr(i) != -1) {\n// finished = true\n// } else { //still continue\n// if (arr(i) != -1) {\n// resArr(i) = qu\n// arr(i) = -1\n// }\n// }\n// }\n// case (true, true) => {\n// if (arr(i) == qu) {\n// good = false\n// // if (arr(0) == 1912) {\n// // println(\"Break on \" + qu + \" i=\" + i)\n// // }\n// }\n// }\n// }\n// if (!good) return\n// }\n//// debug(\"After: \" + qu)\n// }\n// }\n// calc()\n\n// debug(\"After query \" + \"0\" + \": \" + aList.mkString)\n \n val sss = System.currentTimeMillis()\n var totalSteps = 0\n def calc2(): Unit = {\n for(qu <- Q to 1 by -1) { \n var started = false\n var finished = false\n var curCell = starts(qu)\n while(good && curCell != null && counts(qu) > 0) {\n totalSteps += 1\n (started, finished) match {\n case (false, false) => {\n if (curCell.value == qu) {\n started = true\n aList.remove(curCell)\n resArr(curCell.ind) = qu\n counts(qu) -= 1\n// debug(\"Removed first cell\" + curCell)\n }\n }\n case (true, false) => {\n if (curCell.value != qu && curCell.value != 0) {\n finished = true\n// debug(\"finished\")\n } else { //still continue\n aList.remove(curCell)\n resArr(curCell.ind) = qu\n counts(qu) -= 1\n// debug(\"Removed subseq cell\" + curCell)\n }\n }\n case (true, true) => {\n if (curCell.value == qu) {\n// debug(\"Fail at secondary piece: \" + qu)\n good = false\n }\n }\n }\n// debug(\" - After step \" + qu + \": \" + aList.mkString)\n curCell = curCell.next\n }\n// debug(\"After query \" + qu + \": \" + aList.mkString)\n }\n }\n calc2\n val ddd = System.currentTimeMillis() - sss\n debug(\"calc2 dur \" + ddd + \" steps=\" + totalSteps)\n \n var last = resArr(n-1)\n if (last == 0) last = Q\n for(i <- n-1 to 0 by -1) {\n if (resArr(i) == 0) {\n resArr(i) = last\n }\n last = resArr(i)\n }\n lastPresent = false\n for( i <- 0 until n) {\n if (resArr(i) == Q) lastPresent = true\n }\n if (!lastPresent) {\n// debug(\"Fail at top query absent\")\n good = false\n }\n \n if (good) {\n outLn(\"YES\")\n outLn(resArr.mkString(\" \"))\n } else {\n outLn(\"NO\")\n }\n \n debug(\"================= RESULT ================== \")\n val endTime = System.currentTimeMillis() - startTime\n debug(\"Exec time: \" + endTime)\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4 3\n1 0 2 3\n\"\"\"\n\nval sa2 = \"\"\"\n\"\"\"\n\nval t1 = \"\"\"\n4 3\n1 0 2 3\n\"\"\"\n\nval t2 = \"\"\"\n20 20\n17 17 19 19 17 20 20 17 16 16 16 16 16 18 18 18 18 18 6 0\n\"\"\"\n\ndef gen = {\n val runStart = System.currentTimeMillis()\n val n = 200000\n val q = 200000\n val rr = new SecureRandom\n val arr = new Array[Int](n)\n for(i <- 1 to q) {\n val start = rr.nextInt(n-1)\n val length = 1 //rr.nextInt(n-start-1)\n// val length = n-q\n val end = length + start\n for (j <- start to end) {\n arr(j) = i\n }\n }\n val res = s\"$n $q\" + \"\\n\" + arr.mkString(\" \")\n val runEnd = System.currentTimeMillis() - runStart\n println(\"Gen time \" + runEnd)\n println(res)\n res\n}\n\n}\n\n}\n\n"}, {"source_code": "\nimport java.util.StringTokenizer\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_504_D { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.t1)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading\n val l1 = readLine\n val n = l1.int\n val Q = l1.int\n val arrLine = readLine\n val arr = new Array[Int](n)\n \n for(i <- 0 until n) {\n arr(i) = arrLine.int\n }\n \n val resArr = new Array[Int](n)\n var good = true\n for(qu <- Q to 1 by -1) { \n var started = false\n var finished = false\n for(i <- 0 until n) {\n (started, finished) match {\n case (false, false) => {\n if (arr(i) == qu) {\n started = true\n arr(i) = -1\n resArr(i) = qu\n }\n }\n case (true, false) => {\n if (arr(i) != qu && arr(i) != 0 && arr(i) != -1) {\n finished = true\n } else { //still continue\n if (arr(i) != -1) {\n resArr(i) = qu\n arr(i) = -1\n }\n }\n }\n case (true, true) => {\n if (arr(i) == qu) {\n good = false\n }\n }\n }\n }\n debug(\"After: \" + qu)\n }\n var last = resArr(n-1)\n if (last == 0) last = Q\n for(i <- n-1 to 0 by -1) {\n if (resArr(i) == 0) {\n resArr(i) = last\n }\n last = resArr(i)\n }\n var lastPresent = false\n for( i <- 0 until n) {\n if (resArr(i) == Q) lastPresent = true\n }\n if (!lastPresent) good = false\n \n if (good) {\n outLn(\"YES\")\n outLn(resArr.mkString(\" \"))\n } else {\n outLn(\"NO\")\n }\n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4 3\n1 0 2 3\n\"\"\"\n\nval sa2 = \"\"\"\n\"\"\"\n\nval t1 = \"\"\"\n4 3\n0 1 2 3\n\"\"\"\n\n}\n\n}\n\n"}, {"source_code": "\nimport java.util.StringTokenizer\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_504_D { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.t1)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading\n val l1 = readLine\n val n = l1.int\n val Q = l1.int\n val arrLine = readLine\n val arr = new Array[Int](n)\n \n for(i <- 0 until n) {\n arr(i) = arrLine.int\n }\n \n if (arr(0) == 1912) {\n var acc = \"\"\n for(i <- 0 until n) {\n acc += arr(i) + \" \"\n if (i % 50 == 0) {\n println(acc)\n acc = \"\"\n }\n }\n }\n \n val resArr = new Array[Int](n)\n var good = true\n for(qu <- Q to 1 by -1) { \n var started = false\n var finished = false\n for(i <- 0 until n) {\n (started, finished) match {\n case (false, false) => {\n if (arr(i) == qu) {\n started = true\n arr(i) = -1\n resArr(i) = qu\n }\n }\n case (true, false) => {\n if (arr(i) != qu && arr(i) != 0 && arr(i) != -1) {\n finished = true\n } else { //still continue\n if (arr(i) != -1) {\n resArr(i) = qu\n arr(i) = -1\n }\n }\n }\n case (true, true) => {\n if (arr(i) == qu) {\n good = false\n }\n }\n }\n }\n debug(\"After: \" + qu)\n }\n var last = resArr(n-1)\n if (last == 0) last = Q\n for(i <- n-1 to 0 by -1) {\n if (resArr(i) == 0) {\n resArr(i) = last\n }\n last = resArr(i)\n }\n var lastPresent = false\n for( i <- 0 until n) {\n if (resArr(i) == Q) lastPresent = true\n }\n if (!lastPresent) good = false\n \n if (good) {\n outLn(\"YES\")\n outLn(resArr.mkString(\" \"))\n } else {\n outLn(\"NO\")\n }\n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4 3\n1 0 2 3\n\"\"\"\n\nval sa2 = \"\"\"\n\"\"\"\n\nval t1 = \"\"\"\n4 3\n0 1 2 3\n\"\"\"\n\n}\n\n}\n\n"}, {"source_code": "\nimport java.util.StringTokenizer\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\nimport java.security.SecureRandom\n\nobject CF_504_D { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n runTest(Test.t7)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading\n val l1 = readLine\n val n = l1.int\n val Q = l1.int\n val arrLine = readLine\n val arr = new Array[Int](n)\n val startTime = System.currentTimeMillis()\n \n class Cell(val ind: Int, val value: Int) {\n var prev: Cell = null\n var next: Cell = null\n }\n \n class ArrList() {\n var first: Cell = null\n var last: Cell = null\n \n def add(cc: Cell) {\n if (first == null) {\n first = cc\n } else {\n last.next = cc\n cc.prev = last\n }\n last = cc\n }\n def remove(cc: Cell) {\n if (cc.prev != null) {\n cc.prev.next = cc.next\n }\n if (cc.next != null) {\n cc.next.prev = cc.prev\n }\n if (cc == first) { \n first = cc.next\n } \n if (cc == last) { \n last = cc.prev\n }\n }\n def mkString: String= {\n var cur = first\n var res = \"\"\n while (cur != null) {\n// res += cur.ind+\"-\"+cur.value + \",\"\n res += cur.value + \",\"\n cur = cur.next\n }\n res\n }\n }\n val aList = new ArrList()\n \n for(i <- 0 until n) {\n val vv = arrLine.int\n arr(i) = vv\n }\n \n var cur = aList.first\n while (cur != null) {\n print(cur.value + \" \")\n cur = cur.next\n }\n println\n \n// if (arr(0) == 1912) {\n// var acc = \"\"\n// for(i <- 0 until n) {\n// acc += arr(i) + \" \"\n// if (i % 50 == 0) {\n// println(acc)\n// acc = \"\"\n// }\n// }\n// }\n \n var lastPresent = false\n var zeroInd = -1\n for( i <- 0 until n) {\n if (arr(i) == Q) lastPresent = true\n if (arr(i) == 0) zeroInd = i\n }\n if (!lastPresent && zeroInd != -1) arr(zeroInd) = Q\n \n //copy to linked list\n val starts = new Array[Cell](Q+1)\n val counts = new Array[Int](Q+1)\n for(i <- 0 until n) {\n val q = arr(i)\n val cc = new Cell(i, q)\n if (starts(q) == null) { starts(q) = cc }\n counts(q) += 1 \n aList.add(cc) \n }\n \n val resArr = new Array[Int](n)\n var good = true\n \n// def calc(): Unit = {\n// for(qu <- Q to 1 by -1) { \n// var started = false\n// var finished = false\n// for(i <- 0 until n) {\n// (started, finished) match {\n// case (false, false) => {\n// if (arr(i) == qu) {\n// started = true\n// arr(i) = -1\n// resArr(i) = qu\n// }\n// }\n// case (true, false) => {\n// if (arr(i) != qu && arr(i) != 0 && arr(i) != -1) {\n// finished = true\n// } else { //still continue\n// if (arr(i) != -1) {\n// resArr(i) = qu\n// arr(i) = -1\n// }\n// }\n// }\n// case (true, true) => {\n// if (arr(i) == qu) {\n// good = false\n// // if (arr(0) == 1912) {\n// // println(\"Break on \" + qu + \" i=\" + i)\n// // }\n// }\n// }\n// }\n// if (!good) return\n// }\n//// debug(\"After: \" + qu)\n// }\n// }\n// calc()\n\n debug(\"After query \" + \"0\" + \": \" + aList.mkString)\n \n val sss = System.currentTimeMillis()\n var totalSteps = 0\n def calc2(): Unit = {\n for(qu <- Q to 1 by -1) { \n var started = false\n var finished = false\n var curCell = starts(qu)\n while(good && curCell != null && counts(qu) > 0) {\n totalSteps += 1\n (started, finished) match {\n case (false, false) => {\n if (curCell.value == qu) {\n started = true\n aList.remove(curCell)\n resArr(curCell.ind) = qu\n counts(qu) -= 1\n// debug(\"Removed first cell\" + curCell)\n }\n }\n case (true, false) => {\n if (curCell.value != qu && curCell.value != 0) {\n finished = true\n// debug(\"finished\")\n } else { //still continue\n aList.remove(curCell)\n resArr(curCell.ind) = qu\n if (curCell.value == qu) { counts(qu) -= 1 }\n// debug(\"Removed subseq cell\" + curCell)\n }\n }\n case (true, true) => {\n if (curCell.value == qu) {\n debug(\"Fail at secondary piece: \" + qu)\n good = false\n }\n }\n }\n// debug(\" - After step \" + qu + \": \" + aList.mkString)\n curCell = curCell.next\n }\n debug(\"After query \" + qu + \": \" + aList.mkString)\n }\n }\n calc2\n val ddd = System.currentTimeMillis() - sss\n debug(\"calc2 dur \" + ddd + \" steps=\" + totalSteps)\n \n var last = resArr(n-1)\n if (last == 0) last = Q\n for(i <- n-1 to 0 by -1) {\n if (resArr(i) == 0) {\n resArr(i) = last\n }\n last = resArr(i)\n }\n lastPresent = false\n for( i <- 0 until n) {\n if (resArr(i) == Q) lastPresent = true\n }\n if (!lastPresent) {\n debug(\"Fail at top query absent\")\n good = false\n }\n \n if (good) {\n outLn(\"YES\")\n outLn(resArr.mkString(\" \"))\n } else {\n outLn(\"NO\")\n }\n \n debug(\"================= RESULT ================== \")\n val endTime = System.currentTimeMillis() - startTime\n debug(\"Exec time: \" + endTime)\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4 3\n1 0 2 3\n\"\"\"\n\nval sa2 = \"\"\"\n\"\"\"\n\nval t7 = \"\"\"\n50 2\n0 1 0 1 0 0 1 0 1 1 0 1 1 1 2 2 0 2 0 2 0 2 0 0 2 2 2 0 0 0 0 1 0 1 0 0 1 0 1 0 0 1 1 0 1 1 0 1 0 0\n\"\"\"\n\nval m1 = \"\"\"\n4 3\n1 0 2 3\n\"\"\"\n\nval m2 = \"\"\"\n20 20\n17 17 19 19 17 20 20 17 16 16 16 16 16 18 18 18 18 18 6 0\n\"\"\"\n\ndef gen = {\n val runStart = System.currentTimeMillis()\n val n = 200000\n val q = 200000\n val rr = new SecureRandom\n val arr = new Array[Int](n)\n for(i <- 1 to q) {\n val start = rr.nextInt(n-1)\n val length = 1 //rr.nextInt(n-start-1)\n// val length = n-q\n val end = length + start\n for (j <- start to end) {\n arr(j) = i\n }\n }\n val res = s\"$n $q\" + \"\\n\" + arr.mkString(\" \")\n val runEnd = System.currentTimeMillis() - runStart\n println(\"Gen time \" + runEnd)\n println(res)\n res\n}\n\n}\n\n}\n\n"}], "src_uid": "e0450f2644494c92ec0d9ea3ab9d0056"} {"source_code": "object A {\n\n def main(args: Array[String]): Unit = {\n (new A).solve()\n }\n\n}\n\nclass A {\n val out = new java.io.PrintWriter(System.out)\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n def tokenizer = new java.util.StringTokenizer(in.readLine)\n def readInts(n: Int) = { val tl = tokenizer; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizer; Array.fill(n)(tl.nextToken.toLong) }\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n\n def solve() = {\n val Array(t) = readInts(1)\n\n REP(t) { _ =>\n val Array(str, int, exp) = readLongs(3)\n\n def can(i: Long) = {\n str + i > int + (exp - i)\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (can(mid)) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = exp - binSearch(0, exp) + 1\n\n out.println(res)\n }\n\n out.flush()\n }\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n }\n\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n\n import math.{max, min}\n\n def solve(): Unit = {\n val t = ni()\n for (_ <- 1 to t) {\n var str, int, exp = ni()\n val s = str + int + exp\n val d = max(0 ,int - str + 1)\n str += d\n exp -= d\n val intMin = int\n val intMax = min(int + exp, s / 2 + (if (s % 2 == 0) -1 else 0))\n val ans = max(0, intMax - intMin + 1)\n out.println(ans)\n }\n }\n}\n"}, {"source_code": "object A {\n\n def main(args: Array[String]): Unit = {}\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(t) = readInts(1)\n\n for (_ <- 1 to t) {\n val Array(str, int, exp) = readLongs(3)\n\n def can(i: Long) = {\n str + i > int + (exp - i)\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n //println(low, hi, mid, can(mid))\n if (can(mid)) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = exp - binSearch(0, exp) + 1\n\n println(res)\n }\n}\n"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import Math.{max, min}\n\n def solve(): Unit = {\n //for (_ <- 1 to nextInt()) {\n REP(nextInt()) { _ =>\n var str, int, exp = nextInt()\n val s = str + int + exp\n val d = max(0 ,int - str + 1)\n str += d\n exp -= d\n val intMin = int\n val intMax = min(int + exp, s / 2 + (if (s % 2 == 0) -1 else 0))\n val ans = max(0, intMax - intMin + 1)\n out.println(ans)\n }\n }\n}\n"}, {"source_code": "object A {\n\n def main(args: Array[String]): Unit = {}\n val out = new java.io.PrintWriter(System.out)\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n def tokenizer = new java.util.StringTokenizer(in.readLine)\n def readInts(n: Int) = { val tl = tokenizer; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizer; Array.fill(n)(tl.nextToken.toLong) }\n\n val Array(t) = readInts(1)\n\n for (_ <- 1 to t) {\n val Array(str, int, exp) = readLongs(3)\n\n def can(i: Long) = {\n str + i > int + (exp - i)\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (can(mid)) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = exp - binSearch(0, exp) + 1\n\n out.println(res)\n }\n\n out.flush()\n}\n"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream))\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n// def tokenizer = new java.util.StringTokenizer(reader.readLine)\n// def readLine = reader.readLine\n// def readInts(n: Int) = { val tl = tokenizer; Array.fill(n)(tl.nextToken.toInt) }\n// def readLongs(n: Int) = { val tl = tokenizer; Array.fill(n)(tl.nextToken.toLong) }\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import Math.{max, min}\n\n def solve(): Unit = {\n //for (_ <- 1 to nextInt()) {\n REP(nextInt()) { _ =>\n var str, int, exp = nextInt()\n val s = str + int + exp\n val d = max(0 ,int - str + 1)\n str += d\n exp -= d\n val intMin = int\n val intMax = min(int + exp, s / 2 + (if (s % 2 == 0) -1 else 0))\n val ans = max(0, intMax - intMin + 1)\n out.println(ans)\n }\n }\n}\n"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n// private var tokenizer: StringTokenizer = _\n//\n// def next(): String = {\n// while (tokenizer == null || !tokenizer.hasMoreTokens)\n// tokenizer = new StringTokenizer(reader.readLine)\n// tokenizer.nextToken\n// }\n//\n// def nextInt(): Int = Integer.parseInt(next())\n def tokenizer = new java.util.StringTokenizer(reader.readLine)\n def readLine = reader.readLine\n def readInts(n: Int) = { val tl = tokenizer; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizer; Array.fill(n)(tl.nextToken.toLong) }\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import Math.{max, min}\n\n def solve(): Unit = {\n //for (_ <- 1 to nextInt()) {\n REP(readLine.toInt) { _ =>\n var Array(str, int, exp) = readLongs(3)\n val s = str + int + exp\n val d = max(0 ,int - str + 1)\n str += d\n exp -= d\n val intMin = int\n val intMax = min(int + exp, s / 2 + (if (s % 2 == 0) -1 else 0))\n val ans = max(0, intMax - intMin + 1)\n out.println(ans)\n }\n }\n}\n"}, {"source_code": "object A {\n\n def main(args: Array[String]): Unit = {}\n val out = new java.io.PrintWriter(System.out)\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n def tokenizer = new java.util.StringTokenizer(in.readLine)\n def readInts(n: Int) = { val tl = tokenizer; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizer; Array.fill(n)(tl.nextToken.toLong) }\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n\n val Array(t) = readInts(1)\n\n REP(t) { _ =>\n val Array(str, int, exp) = readLongs(3)\n\n def can(i: Long) = {\n str + i > int + (exp - i)\n }\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (can(mid)) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = exp - binSearch(0, exp) + 1\n\n out.println(res)\n }\n\n out.flush()\n}\n"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import Math.{max, min}\n\n def solve(): Unit = {\n for (_ <- 1 to nextInt()) {\n var str, int, exp = nextInt()\n val s = str + int + exp\n val d = max(0 ,int - str + 1)\n str += d\n exp -= d\n val intMin = int\n val intMax = min(int + exp, s / 2 + (if (s % 2 == 0) -1 else 0))\n val ans = max(0, intMax - intMin + 1)\n out.println(ans)\n }\n }\n}\n"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import Math.{max, min}\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n var str, int, exp = ni()\n val s = str + int + exp\n val d = max(0 ,int - str + 1)\n str += d\n exp -= d\n val intMin = int\n val intMax = min(int + exp, s / 2 + (if (s % 2 == 0) -1 else 0))\n val ans = max(0, intMax - intMin + 1)\n out.println(ans)\n }\n }\n}\n"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n var str, int, exp = ni()\n val s = str + int + exp\n val d = max(0 ,int - str + 1)\n str += d\n exp -= d\n val intMin = int\n val intMax = min(int + exp, s / 2 + (if (s % 2 == 0) -1 else 0))\n val ans = max(0, intMax - intMin + 1)\n out.println(ans)\n }\n }\n}"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n// def tokenizer = new java.util.StringTokenizer(reader.readLine)\n// def readLine = reader.readLine\n// def readInts(n: Int) = { val tl = tokenizer; Array.fill(n)(tl.nextToken.toInt) }\n// def readLongs(n: Int) = { val tl = tokenizer; Array.fill(n)(tl.nextToken.toLong) }\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import Math.{max, min}\n\n def solve(): Unit = {\n //for (_ <- 1 to nextInt()) {\n REP(nextInt()) { _ =>\n var str, int, exp = nextInt()\n val s = str + int + exp\n val d = max(0 ,int - str + 1)\n str += d\n exp -= d\n val intMin = int\n val intMax = min(int + exp, s / 2 + (if (s % 2 == 0) -1 else 0))\n val ans = max(0, intMax - intMin + 1)\n out.println(ans)\n }\n }\n}\n"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import Math.{max, min}\n\n def solve(): Unit = {\n REP(nextInt()) { _ =>\n var str, int, exp = nextInt()\n val s = str + int + exp\n val d = max(0 ,int - str + 1)\n str += d\n exp -= d\n val intMin = int\n val intMax = min(int + exp, s / 2 + (if (s % 2 == 0) -1 else 0))\n val ans = max(0, intMax - intMin + 1)\n out.println(ans)\n }\n }\n}\n"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n \n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n \n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n \n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n \n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n \n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n \n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n \n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n \nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n \n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n \n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n \n def solve(): Unit = {\n REP(ni()) { _ =>\n var str, int, exp = ni()\n val s = str + int + exp\n val d = max(0 ,int - str + 1)\n str += d\n exp -= d\n val intMin = int\n val intMax = min(int + exp, s / 2 + (if (s % 2 == 0) -1 else 0))\n val ans = max(0, intMax - intMin + 1)\n out.println(ans)\n }\n }\n}"}], "negative_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val str, int, exp = ni()\n val s = str + int + exp\n val intMin = int\n val intMax = s / 2 + (if (s % 2 == 0) -1 else 0)\n val ans = max(0, intMax - intMin + 1)\n out.println(ans)\n }\n }\n}"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val str, int, exp = ni()\n val init = str + exp\n if (init <= int) out.println(0)\n else {\n val d = init - int\n val ans = d / 2 + (if(d % 2 == 1) 1 else 0)\n out.println(ans)\n }\n }\n }\n}"}], "src_uid": "0816295355375a2d3f1cd45852b86360"} {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val a = Array.fill(30*31)(0L)\n val s = in.next()\n def toIndx2(x: Int, y: Int): Int = x*30+y\n def toIndx(ch: Char): Int = (ch-'a'+1).toInt\n val count = Array.fill(30)(0L)\n s.zipWithIndex.foreach{ case (ch,i) =>\n val chIndex = toIndx(ch)\n\n (0 to 29).foreach(k => {\n a(toIndx2(k,chIndex)) += count(k)\n })\n\n\n count(chIndex) += 1\n\n }\n val res = Math.max(a.max,count.max)\n out.println(res)\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}", "positive_code": [{"source_code": "import collection.mutable.HashMap\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val s = readLine\n val cArr = Array.ofDim[Long](26)\n val iArr = Array.ofDim[Long](s.length, 26)\n for(i <- 0 until s.length) {\n val c = s.charAt(i) - 'a'\n cArr(c) += 1\n Array.copy(cArr, 0, iArr(i), 0, cArr.size)\n }\n val pArr = Array.ofDim[Long](26, 26)\n for(i <- 1 until s.length) {\n val c = s.charAt(i) - 'a'\n for(j <- 0 until 26) {\n val cp = iArr(i - 1)(j)\n pArr(j)(c) += cp\n }\n }\n println(Math.max(pArr.map(_.max).max, cArr.max))\n }\n}\n\n"}], "negative_code": [{"source_code": "import collection.mutable.HashMap\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val s = readLine\n val cArr = Array.ofDim[Int](26)\n val iArr = Array.ofDim[Int](s.length, 26)\n for(i <- 0 until s.length) {\n val c = s.charAt(i) - 'a'\n cArr(c) += 1\n Array.copy(cArr, 0, iArr(i), 0, cArr.size)\n }\n val pArr = Array.ofDim[Int](26, 26)\n for(i <- 1 until s.length) {\n val c = s.charAt(i) - 'a'\n for(j <- 0 until 26) {\n val cp = iArr(i - 1)(j)\n pArr(j)(c) += cp\n }\n }\n println(Math.max(pArr.map(_.max).max, cArr.max))\n }\n}\n\n"}, {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val a = Array.fill(27*27+27)(0)\n val s = in.next()\n def toIndx2(x: Int, y: Int): Int = x*27+y\n def toIndx(ch: Char): Int = (ch-'a').toInt\n val count = Array.fill(27)(0)\n s.zipWithIndex.foreach{ case (ch,i) =>\n val chIndex = toIndx(ch)\n\n (0 to 26).foreach(k => {\n a(toIndx2(k,chIndex)) += count(k)\n })\n\n\n count(chIndex) += 1\n\n }\n val res = Math.max(a.max,count.max)\n out.println(res)\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "src_uid": "69135ef7422b5811ae935a9d00796f88"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, x0) = in.next().split(' ').map(_.toInt)\n val answer = Array.ofDim[Int](1002)\n\n in.take(n).foreach { line =>\n val Array(a, b) = line.split(' ').map(_.toInt).sorted\n answer(a) += 1\n answer(b + 1) -= 1\n }\n\n val (a, _) = answer.indices.foldLeft(-1, 0) {\n case ((distance, sumSoFar), i) =>\n val nSum = sumSoFar + answer(i)\n if (nSum == n && (distance == -1 || Math.abs(x0 - i) < distance))\n (Math.abs(x0 - i), nSum)\n else\n (distance, nSum)\n }\n\n println(a)\n}", "positive_code": [{"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def comp(x: (Int, Int), y: (Int, Int)): Boolean = {\n if (x._1 != y._1) x._1 < y._1 else x._2 < y._2\n }\n\n def solve = {\n val n = nextInt\n val x0 = nextInt\n val ranges = new Array[(Int, Int)](n)\n for (i <- 0 until n) {\n val a = nextInt\n val b = nextInt\n ranges(i) = (Math.min(a, b), Math.max(a, b))\n }\n ranges.sortWith(comp)\n var start = 0\n var finish = Int.MaxValue\n for (i <- 0 until n) {\n start = Math.max(start, ranges(i)._1)\n finish = Math.min(finish, ranges(i)._2)\n }\n if (start > finish) {\n out.println(-1)\n } else {\n var ans = Int.MaxValue\n for (i <- start to finish) {\n if (Math.abs(x0 - i) < ans) {\n ans = Math.abs(x0 - i)\n }\n }\n out.println(ans)\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "negative_code": [], "src_uid": "3c066bad8ee6298b318bf0f4521c7c45"} {"source_code": "import scala.io.StdIn\n\n/**\n * Created by hsleep on 2016. 1. 7..\n */\nobject C {\n def main(args: Array[String]): Unit = {\n val k = StdIn.readInt()\n makeOutput(k).foreach(println)\n }\n\n def makeOutput(k: Int): Seq[String] = {\n k match {\n case 0 => Seq(\"+\")\n case _ =>\n val input = makeOutput(k - 1)\n input.flatMap { s =>\n Seq(s + s, s + makeOpposite(s))\n }\n }\n }\n\n def makeOpposite(s: String): String = {\n s.map {\n case '+' => '*'\n case '*' => '+'\n }\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\n/**\n * Created by hsleep on 2016. 1. 7..\n */\nobject CSolution extends App {\n val k = StdIn.readInt()\n\n def makeOpposite(s: String): String = {\n s.map {\n case '+' => '*'\n case '*' => '+'\n }\n }\n\n def makeOutput(k: Int): Seq[String] = {\n k match {\n case 0 => Seq(\"+\")\n case _ =>\n val input = makeOutput(k - 1)\n input.flatMap { s =>\n Seq(s + s, s + makeOpposite(s))\n }\n }\n }\n\n makeOutput(k).foreach(println)\n}"}], "negative_code": [], "src_uid": "4e25d49e8a50dacc1cfcc9413ee83db6"} {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject Btask extends App {\n\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n var matrix = ArrayBuffer[String]()\n for (i <- 0 until n) {\n line = new Scanner(StdIn.readLine())\n var matrixString = line.next()\n matrix.append(matrixString)\n }\n for (i <- 0 until n) {\n val evenChars = matrix(i).chars.filter(_ % 2 == 0).sorted().toArray\n val oddChars = matrix(i).chars.filter(_ % 2 == 1).sorted().toArray\n if (evenChars.isEmpty) {\n println(oddChars.map(_.toChar).mkString)\n } else {\n if (oddChars.isEmpty) {\n println(evenChars.map(_.toChar).mkString)\n } else {\n if (Math.abs(evenChars(evenChars.size - 1) - oddChars(0)) != 1) {\n println(evenChars.map(_.toChar).mkString + oddChars.map(_.toChar).mkString)\n } else {\n if (Math.abs(oddChars(oddChars.size - 1) - evenChars(0)) != 1) {\n println(oddChars.map(_.toChar).mkString + evenChars.map(_.toChar).mkString)\n } else {\n println(\"No answer\")\n }\n }\n }\n }\n }\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val S = ns()\n val C = Array.ofDim[Int](26)\n REP(S.length) { i =>\n C(S(i) - 'a') += 1\n }\n val even, odd = ArrayBuffer[Int]()\n REP(26) { i =>\n if (C(i) > 0) {\n (if (i % 2 == 0) even else odd) += i\n }\n }\n\n def sort(): Boolean = {\n REP(even.length) { i =>\n REP(odd.length) { j =>\n if (abs(even(i) - odd(j)) > 1) {\n even += even.remove(i)\n odd.insert(0, odd.remove(j))\n return true\n }\n }\n }\n false\n }\n\n def printAns(): Unit = {\n (even ++ odd).foreach { i =>\n REP(C(i)) { _ =>\n out.print(('a' + i).toChar)\n }\n }\n out.println()\n }\n\n if (even.isEmpty || odd.isEmpty) {\n printAns()\n } else {\n if (!sort()) {\n out.println(\"No answer\")\n } else {\n printAns()\n }\n }\n\n }\n }\n}"}], "negative_code": [], "src_uid": "d62d0a9d827444a671029407f6a4ad39"} {"source_code": "import scala.collection.mutable\n\n// https://codeforces.com/contest/914/problem/F\nobject F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val s = readLine.toCharArray.map(_ - 'a')\n val n = s.length\n val Array(q) = readInts(1)\n\n val masks = Array.fill('z' - 'a' + 1) { new mutable.BitSet(n) with BitShifts }\n for (i <- 0 until n) masks(s(i)) += i\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val ones = new mutable.BitSet(n)\n for (i <- 0 until n) ones += i\n val onesBits = ones.toBitMask\n\n for (_ <- 1 to q) {\n val cmd = readLine\n if (cmd.head == '1') {\n val Array(_, posS, cs) = cmd.split(\" \")\n val pos = posS.toInt - 1\n val c = cs.head - 'a'\n masks(s(pos)) -= pos\n masks(c) += pos\n s(pos) = c\n } else {\n val Array(_, lS, rS, y) = cmd.split(\" \")\n val l = lS.toInt - 1\n val r = rS.toInt - 1\n val cnt = if (r - l + 1 < y.length) 0\n else {\n val bits = new mutable.BitSet(onesBits.clone) with BitShifts\n for (i <- 0 until y.length) bits &= masks(y(i) - 'a') >> i\n (bits >> l).size - (bits >> (r - y.length + 2)).size\n }\n println(cnt)\n }\n }\n\n Console.flush\n\n trait BitShifts {\n this: mutable.BitSet =>\n\n private def <<(shiftBy: Int): mutable.BitSet = {\n\n val bitOffset = shiftBy & 63\n val wordOffset = shiftBy >>> 6\n\n var significantWordCount = this.nwords\n while (significantWordCount > 0 && this.word(significantWordCount - 1) == 0) {\n significantWordCount -= 1\n }\n\n val bits = if (bitOffset == 0) {\n val newSize = significantWordCount + wordOffset\n val newBits = Array.ofDim[Long](newSize)\n var i = wordOffset\n while (i < newSize) {\n newBits(i) = this.word(i - wordOffset)\n i += 1\n }\n newBits\n } else {\n val revBitOffset = 64 - bitOffset\n val extraBits = this.word(significantWordCount - 1) >>> revBitOffset\n val extraWordCount = if (extraBits == 0) 0 else 1\n val newSize = significantWordCount + wordOffset + extraWordCount\n val newBits = Array.ofDim[Long](newSize)\n var previous = 0L\n var i = 0\n while (i < significantWordCount) {\n val current = this.word(i)\n newBits(i + wordOffset) = (previous >>> revBitOffset) | (current << bitOffset)\n previous = current\n i += 1\n }\n if (extraWordCount != 0) newBits(newSize - 1) = extraBits\n newBits\n }\n\n this.fromBitMaskNoCopy(bits)\n }\n\n def >>(shiftBy: Int): mutable.BitSet = {\n\n val bitOffset = shiftBy & 63\n\n val bits = if (bitOffset == 0) {\n val wordOffset = shiftBy >>> 6\n val newSize = this.nwords - wordOffset\n if (newSize > 0) {\n val newBits = Array.ofDim[Long](newSize)\n var i = 0\n while (i < newSize) {\n newBits(i) = this.word(i + wordOffset)\n i += 1\n }\n newBits\n } else Array.emptyLongArray\n } else {\n val wordOffset = (shiftBy >>> 6) + 1\n val extraBits = this.word(this.nwords - 1) >>> bitOffset\n val extraWordCount = if (extraBits == 0) 0 else 1\n val newSize = this.nwords - wordOffset + extraWordCount\n if (newSize > 0) {\n val revBitOffset = 64 - bitOffset\n val newBits = Array.ofDim[Long](newSize)\n var previous = this.word(wordOffset - 1)\n var i = wordOffset\n while (i < this.nwords) {\n val current = this.word(i)\n newBits(i - wordOffset) = (previous >>> bitOffset) | (current << revBitOffset)\n previous = current\n i += 1\n }\n if (extraWordCount != 0) newBits(newSize - 1) = extraBits\n newBits\n } else Array.emptyLongArray\n }\n\n this.fromBitMaskNoCopy(bits)\n }\n }\n\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\n\n// https://codeforces.com/contest/914/problem/F\nobject F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val s = readLine.toCharArray.map(_ - 'a')\n val n = s.length\n val Array(q) = readInts(1)\n\n val masks = Array.fill('z' - 'a' + 1) { new mutable.BitSet(n) with BitShifts }\n for (i <- 0 until n) masks(s(i)) += i\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val ones = new mutable.BitSet(n)\n for (i <- 0 until n) ones += i\n val onesBits = ones.toBitMask\n\n for (_ <- 1 to q) {\n val cmd = readLine\n if (cmd.head == '1') {\n val Array(_, posS, cs) = cmd.split(\" \")\n val pos = posS.toInt - 1\n val c = cs.head - 'a'\n masks(s(pos)) -= pos\n masks(c) += pos\n s(pos) = c\n } else {\n val Array(_, lS, rS, y) = cmd.split(\" \")\n val l = lS.toInt - 1\n val r = rS.toInt - 1\n val cnt = if (r - l + 1 < y.length) 0\n else {\n val bits = new mutable.BitSet(onesBits.clone) with BitShifts\n for (i <- 0 until y.length) bits &= masks(y(i) - 'a') >> i\n (bits >> l).size - (bits >> (r - y.length + 2)).size\n }\n println(cnt)\n }\n }\n\n Console.flush\n\n trait BitShifts {\n this: mutable.BitSet =>\n\n val LogWL = 6\n val WordLength = 1 << LogWL\n val WordMask = WordLength - 1\n val MaxSize = (Int.MaxValue >> LogWL) + 1\n\n def <<(shiftBy: Int): mutable.BitSet = {\n\n val shiftedBits = if (this.nwords == 0 || this.nwords == 1 && this.word(0) == 0) Array.emptyLongArray\n else if (shiftBy > 0) shiftLeft(shiftBy)\n else if (shiftBy == 0) this.elems.clone()\n else shiftRight(-shiftBy)\n\n new mutable.BitSet(shiftedBits) with BitShifts\n }\n\n def >>(shiftBy: Int): mutable.BitSet = {\n\n val shiftedBits = if (this.nwords == 0 || this.nwords == 1 && this.word(0) == 0) Array.emptyLongArray\n else if (shiftBy > 0) shiftRight(shiftBy)\n else if (shiftBy == 0) this.elems.clone()\n else shiftLeft(-shiftBy)\n\n new mutable.BitSet(shiftedBits) with BitShifts\n }\n\n def <<=(shiftBy: Int): mutable.BitSet = {\n\n if (this.nwords == 0 || this.nwords == 1 && this.word(0) == 0) ()\n else if (shiftBy > 0) shiftLeftInPlace(shiftBy)\n else if (shiftBy < 0) shiftRightInPlace(-shiftBy)\n\n this\n }\n\n def >>=(shiftBy: Int): mutable.BitSet = {\n\n if (this.nwords == 0 || this.nwords == 1 && this.word(0) == 0) ()\n else if (shiftBy > 0) shiftRightInPlace(shiftBy)\n else if (shiftBy < 0) shiftLeftInPlace(-shiftBy)\n\n this\n }\n\n private def shiftLeft(shiftBy: Int): Array[Long] = {\n\n val bitOffset = shiftBy & WordMask\n val wordOffset = shiftBy >>> LogWL\n\n var significantWordCount = this.nwords\n while (significantWordCount > 0 && this.word(significantWordCount - 1) == 0) {\n significantWordCount -= 1\n }\n\n if (bitOffset == 0) {\n val newSize = significantWordCount + wordOffset\n require(newSize <= MaxSize)\n val newBits = Array.ofDim[Long](newSize)\n var i = wordOffset\n while (i < newSize) {\n newBits(i) = this.word(i - wordOffset)\n i += 1\n }\n newBits\n } else {\n val revBitOffset = WordLength - bitOffset\n val extraBits = this.word(significantWordCount - 1) >>> revBitOffset\n val extraWordCount = if (extraBits == 0) 0 else 1\n val newSize = significantWordCount + wordOffset + extraWordCount\n require(newSize <= MaxSize)\n val newBits = Array.ofDim[Long](newSize)\n var previous = 0L\n var i = 0\n while (i < significantWordCount) {\n val current = this.word(i)\n newBits(i + wordOffset) = (previous >>> revBitOffset) | (current << bitOffset)\n previous = current\n i += 1\n }\n if (extraWordCount != 0) newBits(newSize - 1) = extraBits\n newBits\n }\n }\n\n private def shiftRight(shiftBy: Int): Array[Long] = {\n\n val bitOffset = shiftBy & WordMask\n\n if (bitOffset == 0) {\n val wordOffset = shiftBy >>> LogWL\n val newSize = this.nwords - wordOffset\n if (newSize > 0) {\n val newBits = Array.ofDim[Long](newSize)\n var i = 0\n while (i < newSize) {\n newBits(i) = this.word(i + wordOffset)\n i += 1\n }\n newBits\n } else Array.emptyLongArray\n } else {\n val wordOffset = (shiftBy >>> LogWL) + 1\n val extraBits = this.word(this.nwords - 1) >>> bitOffset\n val extraWordCount = if (extraBits == 0) 0 else 1\n val newSize = this.nwords - wordOffset + extraWordCount\n if (newSize > 0) {\n val revBitOffset = WordLength - bitOffset\n val newBits = Array.ofDim[Long](newSize)\n var previous = this.word(wordOffset - 1)\n var i = wordOffset\n while (i < this.nwords) {\n val current = this.word(i)\n newBits(i - wordOffset) = (previous >>> bitOffset) | (current << revBitOffset)\n previous = current\n i += 1\n }\n if (extraWordCount != 0) newBits(newSize - 1) = extraBits\n newBits\n } else Array.emptyLongArray\n }\n }\n\n private def shiftLeftInPlace(shiftBy: Int): Unit = {\n\n val bitOffset = shiftBy & WordMask\n val wordOffset = shiftBy >>> LogWL\n\n var significantWordCount = this.nwords\n while (significantWordCount > 0 && this.word(significantWordCount - 1) == 0) {\n significantWordCount -= 1\n }\n\n if (bitOffset == 0) {\n val newSize = significantWordCount + wordOffset\n require(newSize <= MaxSize)\n ensureCap(newSize)\n System.arraycopy(this.elems, 0, this.elems, wordOffset, significantWordCount)\n } else {\n val revBitOffset = WordLength - bitOffset\n val extraBits = this.elems(significantWordCount - 1) >>> revBitOffset\n val extraWordCount = if (extraBits == 0) 0 else 1\n val newSize = significantWordCount + wordOffset + extraWordCount\n require(newSize <= MaxSize)\n ensureCap(newSize)\n var i = significantWordCount - 1\n var previous = this.elems(i)\n while (i > 0) {\n val current = this.elems(i - 1)\n this.elems(i + wordOffset) = (current >>> revBitOffset) | (previous << bitOffset)\n previous = current\n i -= 1\n }\n this.elems(wordOffset) = previous << bitOffset\n if (extraWordCount != 0) this.elems(newSize - 1) = extraBits\n }\n java.util.Arrays.fill(this.elems, 0, wordOffset, 0)\n }\n\n private def shiftRightInPlace(shiftBy: Int): Unit = {\n\n val bitOffset = shiftBy & WordMask\n\n if (bitOffset == 0) {\n val wordOffset = shiftBy >>> LogWL\n val newSize = this.nwords - wordOffset\n if (newSize > 0) {\n System.arraycopy(this.elems, wordOffset, this.elems, 0, newSize)\n java.util.Arrays.fill(this.elems, newSize, this.nwords, 0)\n } else this.clear()\n } else {\n val wordOffset = (shiftBy >>> LogWL) + 1\n val extraBits = this.elems(this.nwords - 1) >>> bitOffset\n val extraWordCount = if (extraBits == 0) 0 else 1\n val newSize = this.nwords - wordOffset + extraWordCount\n if (newSize > 0) {\n val revBitOffset = WordLength - bitOffset\n var previous = this.elems(wordOffset - 1)\n var i = wordOffset\n while (i < this.nwords) {\n val current = this.elems(i)\n this.elems(i - wordOffset) = (previous >>> bitOffset) | (current << revBitOffset)\n previous = current\n i += 1\n }\n if (extraWordCount != 0) this.elems(newSize - 1) = extraBits\n java.util.Arrays.fill(this.elems, newSize, this.nwords, 0)\n } else this.clear()\n }\n }\n\n protected final def ensureCap(idx: Int): Unit = {\n // Copied from mutable.BitSet.ensureCapacity (which is inaccessible from here).\n require(idx < MaxSize)\n if (idx >= this.nwords) {\n var newlen = this.nwords\n while (idx >= newlen) newlen = math.min(newlen * 2, MaxSize)\n val elems1 = new Array[Long](newlen)\n Array.copy(this.elems, 0, elems1, 0, this.nwords)\n this.elems = elems1\n }\n }\n\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\n\n// https://codeforces.com/contest/914/problem/F\nobject F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val s = readLine.toCharArray.map(_ - 'a')\n val n = s.length\n val Array(q) = readInts(1)\n\n val masks = Array.fill('z' - 'a' + 1) { new BitSetWithShift(n) }\n for (i <- 0 until n) masks(s(i)) += i\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val ones = new mutable.BitSet(n)\n for (i <- 0 until n) ones += i\n val onesBits = ones.toBitMask\n\n for (_ <- 1 to q) {\n val cmd = readLine\n if (cmd.head == '1') {\n val Array(_, posS, cs) = cmd.split(\" \")\n val pos = posS.toInt - 1\n val c = cs.head - 'a'\n masks(s(pos)) -= pos\n masks(c) += pos\n s(pos) = c\n } else {\n val Array(_, lS, rS, y) = cmd.split(\" \")\n val l = lS.toInt - 1\n val r = rS.toInt - 1\n val cnt = if (r - l + 1 < y.length) 0\n else {\n val bits = new BitSetWithShift(onesBits)\n for (i <- 0 until y.length) bits &= masks(y(i) - 'a') >> i\n (bits >> l).size - (bits >> (r - y.length + 2)).size\n }\n println(cnt)\n }\n }\n\n Console.flush\n\n class BitSetWithShift(elems: Array[Long]) extends mutable.BitSet(elems.clone) {\n\n def this(initSize: Int) = this(new Array[Long]((initSize + 63) >> 6 max 1))\n\n def >>(shiftBy: Int): mutable.BitSet = {\n\n val bitOffset = shiftBy & 63\n\n val bits = if (bitOffset == 0) {\n val wordOffset = shiftBy >>> 6\n val newSize = this.nwords - wordOffset\n if (newSize > 0) {\n val newBits = Array.ofDim[Long](newSize)\n var i = 0\n while (i < newSize) {\n newBits(i) = this.word(i + wordOffset)\n i += 1\n }\n newBits\n } else Array.emptyLongArray\n } else {\n val wordOffset = (shiftBy >>> 6) + 1\n val extraBits = this.word(this.nwords - 1) >>> bitOffset\n val extraWordCount = if (extraBits == 0) 0 else 1\n val newSize = this.nwords - wordOffset + extraWordCount\n if (newSize > 0) {\n val revBitOffset = 64 - bitOffset\n val newBits = Array.ofDim[Long](newSize)\n var previous = this.word(wordOffset - 1)\n var i = wordOffset\n while (i < this.nwords) {\n val current = this.word(i)\n newBits(i - wordOffset) = (previous >>> bitOffset) | (current << revBitOffset)\n previous = current\n i += 1\n }\n if (extraWordCount != 0) newBits(newSize - 1) = extraBits\n newBits\n } else Array.emptyLongArray\n }\n\n mutable.BitSet.fromBitMaskNoCopy(bits)\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\n// https://codeforces.com/contest/914/problem/F\nobject F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val s = readLine.toCharArray.map(_ - 'a')\n val n = s.length\n val Array(q) = readInts(1)\n\n val masks = Array.fill('z' - 'a' + 1) { new BitSetWithShift(n) }\n for (i <- 0 until n) masks(s(i)) += i\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val ones = new mutable.BitSet(n)\n for (i <- 0 until n) ones += i\n val onesBits = ones.toBitMask\n\n for (_ <- 1 to q) {\n val cmd = readLine\n if (cmd.head == '1') {\n val Array(_, posS, cs) = cmd.split(\" \")\n val pos = posS.toInt - 1\n val c = cs.head - 'a'\n masks(s(pos)) -= pos\n masks(c) += pos\n s(pos) = c\n } else {\n val Array(_, lS, rS, y) = cmd.split(\" \")\n val l = lS.toInt - 1\n val r = rS.toInt - 1\n val ans = new BitSetWithShift(onesBits)\n for (i <- 0 until y.length) ans &= masks(y(i) - 'a') >> i\n val cnt = (ans >> (l)).size - (ans >> (r - y.length + 2)).size\n println(cnt)\n }\n }\n\n Console.flush\n\n class BitSetWithShift(elems: Array[Long]) extends mutable.BitSet(elems.clone) {\n\n def this(initSize: Int) = this(new Array[Long]((initSize + 63) >> 6 max 1))\n\n def >>(shiftBy: Int): mutable.BitSet = {\n\n val bitOffset = shiftBy & 63\n\n val bits = if (bitOffset == 0) {\n val wordOffset = shiftBy >>> 6\n val newSize = this.nwords - wordOffset\n if (newSize > 0) {\n val newBits = Array.ofDim[Long](newSize)\n var i = 0\n while (i < newSize) {\n newBits(i) = this.word(i + wordOffset)\n i += 1\n }\n newBits\n } else Array.emptyLongArray\n } else {\n val wordOffset = (shiftBy >>> 6) + 1\n val extraBits = this.word(this.nwords - 1) >>> bitOffset\n val extraWordCount = if (extraBits == 0) 0 else 1\n val newSize = this.nwords - wordOffset + extraWordCount\n if (newSize > 0) {\n val revBitOffset = 64 - bitOffset\n val newBits = Array.ofDim[Long](newSize)\n var previous = this.word(wordOffset - 1)\n var i = wordOffset\n while (i < this.nwords) {\n val current = this.word(i)\n newBits(i - wordOffset) = (previous >>> bitOffset) | (current << revBitOffset)\n previous = current\n i += 1\n }\n if (extraWordCount != 0) newBits(newSize - 1) = extraBits\n newBits\n } else Array.emptyLongArray\n }\n\n mutable.BitSet.fromBitMaskNoCopy(bits)\n }\n }\n\n}\n"}], "src_uid": "35149606b05cbd9637d051dc9e5f74f3"} {"source_code": "//scala ACM模式读入读出\r\nimport scala.io.StdIn\r\nimport scala.math._\r\n\r\n\r\nobject Problem_1716A {\r\n def main(args: Array[String]): Unit = {\r\n\tvar t=StdIn.readInt;\r\n\twhile(t>0){\r\n\t\tt=t-1;\r\n\t\tvar n=StdIn.readInt;\r\n\t\tif(n%3==0) println(n/3);\r\n\t if(n%3==1) println(n/3+2- {if(n!=1) 1; else 0;});\r\n\t if(n%3==2) println(n/3+1);\r\n\t\t\r\n\t}\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n for (t <- 1 to readInt()) {\n val n = readInt()\n val ans = if (n == 1) {\n 2\n } else if (n == 2) {\n 1\n } else {\n (n + 2) / 3\n }\n println(ans)\n }\n }\n}\n"}, {"source_code": "object A extends App {\n import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}\n\n solve()\n\n @inline def operations(n: Int): Int = {\n if (n == 1){\n 2\n } else\n if (n == 2) {\n 1\n } else {\n val s = n / 3\n n % 3 match {\n case 0 => s\n case _ => s + 1\n }\n }\n }\n\n def solve(): Unit = {\n val in = new StreamTokenizer(new BufferedReader(new InputStreamReader((System.in))))\n\n @inline def nextInt = {\n in.nextToken()\n in.nval.asInstanceOf[Int]\n }\n\n val t = nextInt\n for (_ <- 1 to t) {\n val n = nextInt\n println(operations(n))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "//scala ACM模式读入读出\r\nimport scala.io.StdIn\r\nimport scala.math._\r\n\r\n\r\nobject Problem_1716A {\r\n def main(args: Array[String]): Unit = {\r\n\tvar t=StdIn.readInt;\r\n\twhile(t>0){\r\n\t\tt=t-1;\r\n\t\tvar n=StdIn.readInt;\r\n\t\tif(n%3==0) println(n/3);\r\n\t if(n%3==1) println(n/3-2- {if(n!=1) 1; else 0;});\r\n\t if(n%3==2) println(n/3+1);\r\n\t\t\r\n\t}\r\n }\r\n}\r\n"}, {"source_code": "//scala ACM模式读入读出\r\nimport scala.io.StdIn\r\nimport scala.math._\r\n\r\n\r\nobject Problem_1716A {\r\n def main(args: Array[String]): Unit = {\r\n\tvar t=StdIn.readInt;\r\n\twhile(t>0){\r\n\t\tt=t-1;\r\n\t\tvar n=StdIn.readInt;\r\n\t\tif(n%3==0) println(n/3);\r\n\t if(n%3==1) println(n/3-n- {if(n!=1) 1; else 0;});\r\n\t if(n%3==2) println(n/3+1);\r\n\t\t\r\n\t}\r\n }\r\n}\r\n"}], "src_uid": "208e285502bed3015b30ef10a351fd6d"} {"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readInt()\r\n val an = readLine().split(\" \").map(_.toLong)\r\n\r\n val (l, r) = (an zip an.tail).maxBy { case (l, r) => l * r }\r\n\r\n val ans = l * r\r\n\r\n println(ans)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.io.StdIn._;\r\n\r\nobject Main extends App {\r\n\r\n def a(ignored: Int, z: Array[Long]): Long = z.zip(z.slice(1, z.length)).map(l => l._1 * l._2).max\r\n\r\n for (_ <- 0 until readInt()) println(a(readInt(), readLine().split(\" \").map(_.toLong)))\r\n}\r\n\r\n\r\n"}, {"source_code": "import java.io.PrintWriter\r\n\r\nimport scala.collection.immutable.TreeSet\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val reader = scala.io.StdIn\r\n def readInt(): Int = reader.readLine().toInt\r\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\r\n def readArrayLong(): Array[Long] = reader.readLine().split(\" \").map(_.toLong)\r\n def readString(): String = reader.readLine()\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = readInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n\r\n def solve(t: Int = 0): Unit = {\r\n var t = readInt()\r\n while (t > 0) {\r\n val n =readInt()\r\n val a = readArrayInt()\r\n var max = 0L\r\n for (i <- 0 until n - 1) {\r\n if (a(i).toLong * a(i+1) > max) {\r\n max = a(i).toLong * a(i+1)\r\n }\r\n }\r\n println(max)\r\n t -= 1\r\n }\r\n\r\n }\r\n\r\n def main(args: Array[String]) {\r\n //multiTest(solve)\r\n solve()\r\n }\r\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn._;\r\n\r\nobject Main extends App {\r\n\r\n def a(ignored: Int, z: Array[Int]): Int = z.zip(z.slice(1, z.length)).map(l => l._1 * l._2).max\r\n \r\n for (_ <- 0 until readInt()) print(a(readInt(), readLine().split(\" \").map(_.toInt)))\r\n}\r\n"}], "src_uid": "2deed55e860bd69ff0ba3973a1d73cac"} {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject Flask {\n class Result(var games:Int, var time:Int) {\n override def toString = games + \": \" + time\n }\n\n def main(args: Array[String]): Unit = {\n var input = readLine.split(\" \").map(_.toInt)\n var n = input(0); var k = input(1)\n \n var data:ArrayBuffer[Result] = new ArrayBuffer()\n (1 to n).foreach(i => {\n input = readLine.split(\" \").map(_.toInt)\n data += new Result(input(0), input(1))\n })\n \n data = data.sortWith((x, y) => x.games > y.games || (x.games == y.games && x.time < y.time))\n var item = data(k - 1)\n println(data.count(x => x.games == item.games && x.time == item.time))\n }\n}\n", "positive_code": [{"source_code": "object A166 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n val arr = Array.fill(n)(readInts(2)).map(x => (x(0), x(1))).sortWith{ case ((a1, b1), (a2, b2)) =>\n if(a1 > a2) {\n true\n } else if (a1 == a2) {\n if (b1 < b2) true\n else false\n } else {\n false\n }\n }\n\n// for((x,y) <- arr) println(s\"$x $y\")\n\n val target = arr(k-1)\n\n // firstGreaterOrEqualBinarySearch\n var first = -1\n\n {\n var low = 0\n var high = n - 1\n\n while(low < high) {\n val mid = low + (high - low)/2\n if((arr(mid)._1 > target._1) || (arr(mid)._1 == target._1 && arr(mid)._2 < target._2))\n low = mid + 1\n else\n high = mid\n\n// println(s\"$low, $high, $mid\")\n }\n\n first = low\n }\n\n //lastSame\n val last = arr.lastIndexOf(target)\n\n out.println(last-first+1)\n\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n// private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P166A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, K = sc.nextInt\n val PT = List.fill(N, 2)(sc.nextLong)\n\n def solve(): Int = {\n\n val groups = PT.groupBy[Long] {\n case List(p, t) => p * Int.MaxValue - t\n }.toSeq.sortWith(_._1 > _._1).map(_._2.size) toList\n \n @tailrec\n def loop(acc: Int, gs: List[Int]): Int = gs match {\n case x :: Nil => x\n case x :: xs => if (acc + x > K) x\n else loop(acc + x, xs)\n }\n\n loop(1, groups)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "object CF166A {\n\n def main(args: Array[String]): Unit = {\n var Array(n, k) = Console.readLine.split(' ').map(_.toInt)\n var teams: List[(Int, Int)] = List()\n for (i <- 0.until(n)) {\n val Array(p, t) = Console.readLine.split(' ').map(_.toInt)\n teams ++= List((p, t))\n }\n teams = teams.sort((a1, a2) => (a1._1 > a2._1 || a1._1 == a2._1 && a1._2 < a2._2))\n var cnt = 1\n var at = 1\n while (at < k) {\n if (teams(at) == teams(at - 1)) {\n cnt += 1\n } else {\n cnt = 1\n }\n at += 1\n }\n while (at < n && teams(at) == teams(at - 1)) {\n cnt += 1\n at += 1\n }\n println(cnt)\n }\n}"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n def readLine = reader.readLine\n\n val Array(n, k) = readInts\n val results = (for(_ <- 1 to n) yield readInts).map(x => (50 - x(0)) * 100 + x(1)).sorted\n def ans = results.count(_.equals(results(k - 1)))\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val nk = readLine().split(\" \").map(_.toInt)\n val n = nk(0)\n val k = nk(1)\n \n val a = (1 to n).map(_ => readLine().split(\" \").map(_.toInt))\n val sorted = a.sortWith((a1, a2) => a1(0) > a2(0) || (a1(0) == a2(0) && a1(1) < a2(1)))\n val e = sorted(k - 1)\n val count = sorted.count(a0 => a0(0) == e(0) && a0(1) == e(1))\n println(count)\n }\n}"}, {"source_code": "object P166A {\n def readPair : (Int, Int) = {\n val x = readLine().split(\" \").map(_.toInt)\n (x(0), x(1))\n }\n\n def main ( args : Array[String] ) {\n val x = readPair\n val n = x._1\n val k = x._2\n\n var A = new Array(n) : Array[(Int,Int)]\n\n for(i <- 0 until n) A(i) = readPair\n\n def compare(x : (Int, Int), y : (Int, Int)) = {\n if(x._1 > y._1) true\n else if(x._1 == y._1) x._2 < y._2\n else false\n }\n\n A = A.sortWith(compare)\n\n println(A.count(_ == A(k - 1)))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = (1 to n).map { _ =>\n val d = in.next().split(\" \").map(_.toInt)\n (-d.head, d.last)\n }.sorted\n val kth = data(k - 1)\n println(data.count(_ == kth))\n}"}, {"source_code": "object A166 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n val arr = Array.fill(n)(readInts(2)).map(x => (x(0), x(1))).sortWith{ case ((a1, b1), (a2, b2)) =>\n if(a1 > a2) {\n true\n } else if (a1 == a2) {\n if (b1 < b2) true\n else false\n } else {\n false\n }\n }\n\n// for((x,y) <- arr) println(s\"$x $y\")\n\n val target = arr(k-1)\n\n // firstGreaterOrEqualBinarySearch\n var first = -1\n\n {\n var low = 0\n var high = n - 1\n\n while(low < high) {\n val mid = low + (high - low)/2\n if((arr(mid)._1 > target._1) || (arr(mid)._1 == target._1 && arr(mid)._2 < target._2))\n low = mid + 1\n else\n high = mid\n\n// println(s\"$low, $high, $mid\")\n }\n\n first = low\n }\n\n //lastSame\n var last = -1\n\n {\n var low = 0\n var high = n - 1\n\n while(low < high) {\n val mid = low + (high - low + 1)/2\n// println(s\"$low, $high, $mid\")\n// println(arr(low), arr(mid), arr(high), target)\n if((arr(mid)._1 > target._1) || (arr(mid)._1 == target._1 && arr(mid)._2 <= target._2))\n low = mid\n else\n high = mid - 1\n\n// println(s\"\\n\\n\\n$low, $high, $mid\\n\\n\\n\")\n }\n\n last = low\n }\n\n out.println(last-first+1)\n\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n// private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}"}], "negative_code": [{"source_code": "object P166A {\n def readPair : (Int, Int) = {\n val x = readLine().split(\" \").map(_.toInt)\n (x(0), x(1))\n }\n\n def main ( args : Array[String] ) {\n val x = readPair\n val n = x._1\n val k = x._2\n\n var A = new Array(n) : Array[(Int,Int)]\n\n for(i <- 0 until n) A(i) = readPair\n\n def compare(x : (Int, Int), y : (Int, Int)) = {\n if(x._1 > y._1) true\n else if(x._1 == y._1) x._2 > y._2\n else false\n }\n\n val T = (A.sortWith(compare)).distinct\n\n val size = T.size\n var cnt = A.count(_ == T(0)) //I = numarul de locuri pe care le impart cei de pe pozitia total + 1\n var total = 0 // I = numarul de locuri deja ocupate\n var index = 1\n var oldcnt = 0\n while(total < k && index < size) {\n total += cnt\n oldcnt = cnt\n cnt = A.count(_ == T(index))\n index += 1\n }\n // total >= k \n if(index == size) println(cnt)\n else println(oldcnt)\n }\n}\n"}, {"source_code": "object P166A {\n def readPair : (Int, Int) = {\n val x = readLine().split(\" \").map(_.toInt)\n (x(0), x(1))\n }\n\n def main ( args : Array[String] ) {\n val x = readPair\n val n = x._1\n val k = x._2\n\n var A = new Array(n) : Array[(Int,Int)]\n\n for(i <- 0 until n) A(i) = readPair\n\n def compare(x : (Int, Int), y : (Int, Int)) = {\n if(x._1 > y._1) true\n else if(x._1 == y._1) x._2 > y._2\n else false\n }\n\n val T = (A.sortWith(compare)).distinct\n \n val size = T.size\n var cnt = A.count(_ == T(0))\n var total = cnt\n var index = 1\n while(total <= k && index < size) {\n cnt = A.count(_ == T(index))\n total += 1\n index += 1\n }\n \n println(cnt)\n }\n}\n"}, {"source_code": "object P166A {\n def readPair : (Int, Int) = {\n val x = readLine().split(\" \").map(_.toInt)\n (x(0), x(1))\n }\n\n def main ( args : Array[String] ) {\n val x = readPair\n val n = x._1\n val k = x._2\n\n var A = new Array(n) : Array[(Int,Int)]\n\n for(i <- 0 until n) A(i) = readPair\n\n def compare(x : (Int, Int), y : (Int, Int)) = {\n if(x._1 > y._1) true\n else if(x._1 == y._1) x._2 > y._2\n else false\n }\n\n A = A.sortWith(compare)\n\n println(A.count(_ == A(k - 1)))\n }\n}\n"}, {"source_code": "object P166A {\n def readPair : (Int, Int) = {\n val x = readLine().split(\" \").map(_.toInt)\n (x(0), x(1))\n }\n\n def main ( args : Array[String] ) {\n val x = readPair\n val n = x._1\n val k = x._2\n\n var A = new Array(n) : Array[(Int,Int)]\n\n for(i <- 0 until n) A(i) = readPair\n\n def compare(x : (Int, Int), y : (Int, Int)) = {\n if(x._1 > y._1) true\n else if(x._1 == y._1) x._2 > y._2\n else false\n }\n\n val T = (A.sortWith(compare)).distinct\n\n val size = T.size\n var end = A.count(_ == T(0))\n var start = 0 \n // de la (start, start + end])\n var index = 1\n while(start + end < k && index < size) {\n start += end\n end = A.count(_ == T(index))\n index += 1\n }\n println(end)\n }\n}\n"}, {"source_code": "object P166A {\n def readPair : (Int, Int) = {\n val x = readLine().split(\" \").map(_.toInt)\n (x(0), x(1))\n }\n\n def main ( args : Array[String] ) {\n val x = readPair\n val n = x._1\n val k = x._2\n\n var A = new Array(n) : Array[(Int,Int)]\n\n for(i <- 0 until n) A(i) = readPair\n\n def compare(x : (Int, Int), y : (Int, Int)) = {\n if(x._1 > y._1) true\n else if(x._1 == y._1) x._2 > y._2\n else false\n }\n\n A = A.sortWith(compare)\n \n println(A.count(_ == A(k)))\n }\n}\n"}, {"source_code": "object P166A {\n def readPair : (Int, Int) = {\n val x = readLine().split(\" \").map(_.toInt)\n (x(0), x(1))\n }\n\n def main ( args : Array[String] ) {\n val x = readPair\n val n = x._1\n val k = x._2\n\n var A = new Array(n) : Array[(Int,Int)]\n\n for(i <- 0 until n) A(i) = readPair\n\n def compare(x : (Int, Int), y : (Int, Int)) = {\n if(x._1 > y._1) true\n else if(x._1 == y._1) x._2 > y._2\n else false\n }\n\n val T = (A.sortWith(compare)).distinct\n \n val size = T.size\n var cnt = A.count(_ == T(0))\n var total = cnt\n var index = 1\n while(total < k && index < size) {\n cnt = A.count(_ == T(index))\n total += 1\n index += 1\n }\n \n println(cnt)\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject Flask {\n class Result(var games:Int, var time:Int) {\n override def toString = games + \": \" + time\n }\n\n def main(args: Array[String]): Unit = {\n var input = readLine.split(\" \").map(_.toInt)\n var n = input(0); var k = input(1)\n \n var data:ArrayBuffer[Result] = new ArrayBuffer()\n (1 to n).foreach(i => {\n input = readLine.split(\" \").map(_.toInt)\n data += new Result(input(0), input(1))\n })\n \n data = data.sortWith((x, y) => x.games > y.games || (x.games == y.games && x.time < y.time))\n var item = data(k)\n println(data.count(x => x.games == item.games && x.time == item.time))\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject Flask {\n class Result(var games:Int, var time:Int) { }\n\n def main(args: Array[String]): Unit = {\n var input = readLine.split(\" \").map(_.toInt)\n var n = input(0); var k = input(1)\n \n var data:ArrayBuffer[Result] = new ArrayBuffer()\n (1 to n).foreach(i => {\n input = readLine.split(\" \").map(_.toInt)\n data += new Result(input(0), input(1))\n })\n \n data.sortWith((x, y) => x.games > y.games || (x.games == y.games && x.time < y.time))\n var item = data(k)\n println(data.count(x => x.games == item.games && x.time == item.time))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = (1 to n).map { _ =>\n val d = in.next().split(\" \").map(_.toInt)\n (-d.head, d.last)\n }.sorted\n println(data)\n val kth = data(k - 1)\n println(data.count(_ == kth))\n}"}, {"source_code": "object A166 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n val arr = Array.fill(n)(readInts(2)).map(x => (x(0), x(1))).sortWith{ case ((a1, b1), (a2, b2)) =>\n if(a1 > a2) {\n true\n } else if (a1 == a2) {\n if (b1 < b2) true\n else false\n } else {\n false\n }\n }\n\n val target = arr(k-1)\n\n // firstGreaterOrEqualBinarySearch\n var first = -1\n\n {\n var low = 0\n var high = n - 1\n\n while(low < high) {\n val mid = low + (high - low)/2\n if((arr(mid)._1 > target._1) || (arr(mid)._1 == target._1 && arr(mid)._2 > target._2))\n low = mid + 1\n else\n high = mid\n }\n\n first = low\n }\n\n //lastSame\n val last = arr.lastIndexOf(target)\n\n out.println(last-first+1)\n\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n// private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}"}, {"source_code": "object A166 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n val arr = Array.fill(n)(readInts(2)).map(x => (x(0), x(1))).sorted.reverse\n val target = arr(k-1)\n\n // firstGreaterOrEqualBinarySearch\n var first = -1\n\n {\n var low = 0\n var high = n - 1\n\n while(low < high) {\n val mid = low + (high - low)/2\n if((arr(mid)._1 > target._1) || (arr(mid)._1 == target._1 && arr(mid)._2 > target._2))\n low = mid + 1\n else\n high = mid\n }\n\n first = low\n }\n\n //lastSame\n val last = arr.lastIndexOf(target)\n\n out.println(last-first+1)\n\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P166A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, K = sc.nextInt\n val PT = List.fill(N, 2)(sc.nextLong)\n\n def solve(): Int = {\n\n val groups = PT.groupBy[Long] {\n case List(p, t) => p * Int.MaxValue - t\n }.toSeq.sortWith(_._1 > _._1).map(_._2.size) toList\n \n @tailrec\n def loop(acc: Int, gs: List[Int]): Int = gs match {\n case x :: Nil => x\n case x :: xs => if (acc + x >= K) x\n else loop(acc + x, xs)\n }\n\n loop(1, groups)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val nk = readLine().split(\" \").map(_.toInt)\n val n = nk(0)\n val k = nk(0)\n \n val a = (1 to n).map(_ => readLine().split(\" \").map(_.toInt))\n val sorted = a.sortWith((a1, a2) => a1(0) < a2(0) || a1(1) > a2(1))\n val e = sorted(k - 1)\n val count = sorted.count(a0 => a0(0) == e(0) && a0(1) == e(1))\n println(count)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val nk = readLine().split(\" \").map(_.toInt)\n val n = nk(0)\n val k = nk(0)\n \n val a = (1 to n).map(_ => readLine().split(\" \").map(_.toInt))\n val sorted = a.sortWith((a1, a2) => a1(0) > a2(0) || (a1(0) == a2(0) && a1(1) < a2(1)))\n val e = sorted(k - 1)\n val count = sorted.count(a0 => a0(0) == e(0) && a0(1) == e(1))\n println(count)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val nk = readLine().split(\" \").map(_.toInt)\n val n = nk(0)\n val k = nk(0)\n \n val a = (1 to n).map(_ => readLine().split(\" \").map(_.toInt))\n val sorted = a.sortWith((a1, a2) => a1(0) < a2(0) || (a1(0) == a2(0) && a1(1) > a2(1)))\n val e = sorted(k - 1)\n val count = sorted.count(a0 => a0(0) == e(0) && a0(1) == e(1))\n println(count)\n }\n}"}, {"source_code": "object P166A {\n def readPair : (Int, Int) = {\n val x = readLine().split(\" \").map(_.toInt)\n (x(0), x(1))\n }\n\n def main ( args : Array[String] ) {\n val x = readPair\n val n = x._1\n val k = x._2\n\n var A = new Array(n) : Array[(Int,Int)]\n\n for(i <- 0 until n) A(i) = readPair\n\n def compare(x : (Int, Int), y : (Int, Int)) = {\n if(x._1 > y._1) true\n else if(x._1 == y._1) x._2 > y._2\n else false\n }\n\n val T = (A.sortWith(compare)).distinct\n\n val size = T.size\n var cnt = A.count(_ == T(0)) //I = numarul de locuri pe care le impart cei de pe pozitia total + 1\n var total = 0 // I = numarul de locuri deja ocupate\n var index = 1\n var oldcnt = 0\n while(total < k && index < size) {\n total += cnt\n oldcnt = cnt\n cnt = A.count(_ == T(index))\n index += 1\n }\n // total >= k \n if(total < k) println(cnt)\n else println(oldcnt)\n }\n}\n"}], "src_uid": "63e03361531999db408dc0d02de93579"} {"source_code": "import java.io._\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n\n val Array(n, k) = readInts\n\n def ans = (for(_ <- 1 to n) yield readInts).map {\n case Array(f, t) => f - 0.max(t - k)\n }.max\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _276A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val k = next.toInt\n val a = (1 to n).map(i => { val f = next.toInt; val t = next.toInt; if (t <= k) f else f - (t - k) })\n println(a.max)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n println(Range(0, n).map{_ =>\n val d = in.next().split(\" \").map(_.toInt)\n if (d(1) > k) d(0) - (d(1) - k)\n else d(0)\n }.max)\n}\n"}, {"source_code": "object A276 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n val in = Array.fill(n)(readInts(2))\n\n var max = Int.MinValue\n for(i <- 0 until n) {\n if(in(i)(1) > k) {\n max = math.max(max, in(i)(0) - (in(i)(1) - k))\n } else {\n max = math.max(max, in(i)(0))\n }\n }\n println(max)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P276A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val n, k = sc.nextInt\n\n val answer = {\n List.fill(n) {\n val f, t = sc.nextInt\n if (t <= k) f\n else f + k - t\n }\n }.max\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "\nobject Fuck {\n def main(args: Array[String]) {\n\n val Array(n,k) = readLine().split(\" \").map(_.toInt)\n var m = Integer.MIN_VALUE;\n for (i <- 1 to n) {\n val Array(f,t) = readLine().split(\" \").map(_.toInt)\n m = math.max(m, f-math.max(0, t-k))\n }\n println(m)\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main {\n \n val input = new Scanner(System.in)\n \n def main(args: Array[String]) {\n val n = input.nextInt\n val k = input.nextInt\n val it = new MyIt().take(n).map {\n case (f, t) => if (t > k) f - (t - k) else f\n }\n println(it.max)\n }\n \n class MyIt extends Iterator[(Int, Int)] {\n def hasNext = true\n def next : (Int, Int) = {\n val a = input.nextInt\n val b = input.nextInt\n (a, b)\n }\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val nk = readLine().split(\" \").map(_.toInt)\n val k = nk(1)\n val pl = (1 to nk(0)).map{ _ => \n val a = readLine().split(\" \").map(_.toInt)\n if (a(1) > k) a(0) - a(1) + k\n else a(0)\n }\n println(pl.max)\n }\n}"}, {"source_code": "\nobject A {\n\t \n\tdef main(args: Array[String]) {\n\t\tval nk = Console.readLine.split(\" \").map(_.toInt)\n\t\tval n = nk(0)\n\t\tval k = nk(1)\n\n\t\tdef ud(f: Int, t: Int) = if(t > k) f - (t - k) else f\n\n\t\tvar result = (for(i <- 0 until n) yield {\n\t\t\tval ft = Console.readLine.split(\" \").map(_.toInt)\n\t\t\tud(ft(0), ft(1))\n\t\t})\n\t\tprintln(result.max)\n\t}\n}"}], "negative_code": [{"source_code": "\nobject A {\n\t \n\tdef main(args: Array[String]) {\n\t\tval nk = Console.readLine.split(\" \").map(_.toInt)\n\t\tval n = nk(0)\n\t\tval k = nk(1)\n\n\t\tdef ud(f: Int, t: Int) = if(t > k) f - (t - k) else f\n\n\t\tvar mf = -1\n\t\tfor(i <- 0 until n) {\n\t\t\tval ft = Console.readLine.split(\" \").map(_.toInt)\n\t\t\tmf = math.max(mf, ud(ft(0), ft(1)))\n\t\t}\n\t\tprintln(mf)\n\t}\n}"}], "src_uid": "1bb5b64657e16fb518d49d3c799d4823"} {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val bn = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val bs = bn.sum\n\n val ans = bn.sum > 0 && bn.sum < bn.length || (an, an.tail).zipped.forall(_ <= _)\n\n if (ans) println(\"Yes\")\n else println(\"No\")\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val n = readLine()\n val values = readIntLine()\n val types = readIntLine()\n println(if (types.distinct.size > 1 || values.sorted.equals(values)) \"Yes\" else \"No\")\n }\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import java.util\n\nobject B {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as, bs = nextInts(n)\n val can = bs.distinct.size > 1 || util.Arrays.equals(as, as.sorted)\n\n out.println(if (can) \"Yes\" else \"No\")\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object ProblemB extends App {\n\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n import scala.collection.mutable\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n\n for (_ <- 1 to t) {\n val n = in.nextInt()\n var a = new Array[Int](n)\n var b = new Array[Int](n)\n for (i <- 0 until n) {\n a(i) = in.nextInt()\n }\n var hasFirstType = false\n var hasSecondType = false\n for (i <- 0 until n) {\n b(i) = in.nextInt()\n if (b(i) == 0) {\n hasFirstType = true\n } else {\n hasSecondType= true\n }\n }\n\n val aCopy = a.clone\n java.util.Arrays.sort(aCopy)\n val res = if (a.sameElements(aCopy) || (hasFirstType && hasSecondType)) {\n \"yes\"\n } else {\n \"no\"\n }\n\n println(res)\n }\n\n}"}], "negative_code": [], "src_uid": "4bf3a94119d08a9cd6075a67d0014061"} {"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n\n def printEnd(k: Int): Unit = {\n out.print('b')\n out.print((1 until k).map(_ => 'a').mkString(\"\"))\n }\n def printBeg(k: Int): Unit = {\n\n out.print((1 until k).map(_ => 'a').mkString(\"\"))\n out.print('b')\n }\n def printMiddle(k: Int): Unit = {\n out.print((1 to k).map(_ => 'a').mkString(\"\"))\n }\n\n (1 to t).foreach{ _ =>\n val n = in.nextLong()\n val k = in.nextLong()\n val z = ((Math.sqrt(8d*k+1)-1d)/2d).toLong\n val rowsUsed: Long = if((z*(z-1))/2 >= k) z-1 else z\n val suma = (rowsUsed*(rowsUsed+1))/2\n val resta = k - suma\n //println(s\"n: $n k:$k z:$z resta:$resta rowsUsed:$rowsUsed\")\n\n if(resta!=0) {\n printBeg((n - rowsUsed - 1).toInt)\n printMiddle((rowsUsed - resta +1).toInt)\n printEnd(resta.toInt)\n }else{\n printBeg((n - rowsUsed).toInt)\n printEnd(rowsUsed.toInt)\n }\n out.println(\"\")\n\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}", "positive_code": [{"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n val t = nextInt\n\n for (_ <- 1 to t) {\n val n, k = nextInt\n var i = 1\n var cnt = 0\n while (cnt + i < k) {\n cnt += i\n i += 1\n }\n var j = k - cnt\n var s = Array.fill(n)('a')\n s(n - i - 1) = 'b'\n s(n - j) = 'b'\n out.println(s.mkString)\n }\n\n out.flush()\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n\n def printEnd(k: Int): Unit = {\n out.print('b')\n out.print((1 until k).map(_ => 'a').mkString(\"\"))\n }\n def printBeg(k: Int): Unit = {\n\n out.print((1 until k).map(_ => 'a').mkString(\"\"))\n out.print('b')\n }\n def printMiddle(k: Int): Unit = {\n out.print((1 to k).map(_ => 'a').mkString(\"\"))\n }\n\n (1 to t).foreach{ _ =>\n val n = in.nextInt()\n val k = in.nextInt()\n val z = ((Math.sqrt(8d*k+1)-1d)/2d).toInt\n val rowsUsed = if((z*(z-1))/2 >= k) z-1 else z\n val suma = (rowsUsed*(rowsUsed+1))/2\n val resta = k - suma\n //println(s\"n: $n k:$k z:$z resta:$resta rowsUsed:$rowsUsed\")\n\n if(resta!=0) {\n printBeg(n - rowsUsed - 1)\n printMiddle(rowsUsed - resta +1)\n printEnd(resta)\n }else{\n printBeg(n - rowsUsed)\n printEnd(rowsUsed)\n }\n out.println(\"\")\n\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "src_uid": "e32f0615541d97a025bc99c3cbf5380e"} {"source_code": "object _1183B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val q = io.read[Int]\n val ans = (1 to q) map {_ =>\n val n, k = io.read[Int]\n val as = io.read[Seq, Long](n)\n var lower = Long.MinValue\n var upper = Long.MaxValue\n\n try {\n for {\n a <- as\n x = a + k\n y = a - k\n } {\n require(y <= upper && x >= lower)\n lower = lower max y\n upper = upper min x\n }\n upper\n } catch {\n case _: Throwable => -1\n }\n }\n\n io.writeLines(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject EqualizePrice {\n def main(args: Array[String]): Unit = {\n val q = StdIn.readInt()\n for (qi <- 1 to q) {\n val nk = StdIn.readLine().split(' ')\n val n = nk(0).toInt\n val k = nk(1).toInt\n val as = StdIn.readLine().split(' ').map(_.toInt)\n val ans = as.map(_ + k).min\n val isErr = as.exists{a: Int =>\n Math.abs(ans - a) > k\n }\n if (qi == q) if (isErr) print(-1) else print(ans)\n else if (isErr) println(-1) else println(ans)\n\n }\n }\n}\n"}], "negative_code": [], "src_uid": "3b158306d335459ff55dcf29e46010e8"} {"source_code": "import scala.collection.mutable\n\nobject A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n def expected(i: Int): Char = if (i % 2 == 0) '(' else ')'\n\n for (_ <- 1 to t) {\n\n val n, k = nextInt\n val s = nextLine.toCharArray\n var l = 0\n var r = n - 1\n val res = new mutable.ArrayBuffer[String]\n\n while (l < r) {\n while (l < r && s(l) == expected(l)) l += 1\n while (l < r && s(r) == expected(r)) r -= 1\n if (l < r) {\n var rr = r\n var ll = l\n while (s(rr) != expected(l)) rr -= 1\n res += s\"${ll + 1} ${rr + 1}\"\n while (ll < rr) {\n val tmp = s(ll)\n s(ll) = s(rr)\n s(rr) = tmp\n ll += 1\n rr -= 1\n }\n }\n }\n\n for (i <- 0 until n / 2 - k) {\n val l = 2 * i + 1\n val r = l + 1\n res += s\"${l + 1} ${r + 1}\"\n }\n\n out.println(res.size)\n if (res.nonEmpty) out.println(res.mkString(\"\\n\"))\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def mkT(N: Int, K: Int): String = {\n val str = StringBuilder.newBuilder\n REP(K - 1) { _ =>\n str.append(\"()\")\n }\n REP(N/2 - (K-1)) { _ =>\n str.append(\"(\")\n }\n REP(N/2 - (K-1)) { _ =>\n str.append(\")\")\n }\n str.toString\n }\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N, K = ni()\n val S = ns(N)\n val T = mkT(N, K).toCharArray\n debug(S.mkString)\n debug(T.mkString)\n val ans = ArrayBuffer[(Int, Int)]()\n val pos1, pos2 = new java.util.ArrayDeque[Int]()\n def pos(i: Int) = if (S(i) == '(') pos1 else pos2\n def pos_rev(i: Int) = if (S(i) == '(') pos2 else pos1\n REP(N) { i =>\n pos(i).addLast(i)\n }\n REP(N) { i =>\n if (S(i) == T(i)) {\n pos(i).poll()\n }\n if (S(i) != T(i)) {\n pos(i).poll()\n val j = pos_rev(i).poll()\n pos(i).addFirst(j)\n debug(s\"$i,$j\")\n ans += ((i, j))\n if (j - i > 2) ans += ((i + 1, j - 1))\n val t = S(j)\n S(j) = S(i)\n S(i) = t\n }\n }\n out.println(ans.length)\n REP(ans.length) { i =>\n out.println(s\"${ans(i)._1+1} ${ans(i)._2+1}\")\n }\n }\n }\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\nobject A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n\n def checkLeft(s: Array[Char]): Int = {\n var x = 0\n var i = 0\n while (i < s.length) {\n s(i) match {\n case '(' => x += 1\n case ')' =>\n x -= 1\n if (x < 0) return i\n }\n i += 1\n }\n -1\n }\n\n def checkRight(s: Array[Char]): Int = {\n var x = 0\n var i = s.length - 1\n while (i >= 0) {\n s(i) match {\n case '(' =>\n x -= 1\n if (x < 0) return i\n case ')' =>\n x += 1\n }\n i -= 1\n }\n -1\n }\n\n def checkPrefixes(s: Array[Char], k: Int): Int = {\n var x, pCount = 0\n var i = 0\n while (i < s.length) {\n s(i) match {\n case '(' => x += 1\n case ')' => x -= 1\n }\n if (x == 0) pCount += 1\n i += 1\n }\n pCount\n }\n\n def increase(s: Array[Char]): String = {\n val l = s.indexOfSlice(\"((\")\n val r = s.indexOf(')', l)\n s(l + 1) = ')'\n s(r) = '('\n s\"${l + 1} $r\"\n }\n\n def reduce(s: Array[Char]): String = {\n var l = 0\n var x = 0\n var done = false\n while (!done) {\n s(l) match {\n case '(' =>\n x += 1\n if (x == 1 && l > 0) done = true\n case ')' =>\n x -= 1\n }\n l += 1\n }\n l -= 2\n s(l) = '('\n s(l + 1) = ')'\n s\"${l + 1} ${l + 2}\"\n }\n\n for (test <- 1 to t) {\n val n, k = nextInt\n val s = nextLine.toCharArray\n var l = checkLeft(s)\n val res = new mutable.ArrayBuffer[String]\n while (l >= 0) {\n var r = checkRight(s)\n res += s\"${l + 1} ${r + 1}\"\n while (l < r) {\n val tmp = s(l)\n s(l) = s(r)\n s(r) = tmp\n l += 1\n r -= 1\n }\n l = checkLeft(s)\n }\n var pCount = checkPrefixes(s, k)\n while (pCount > k) {\n res += reduce(s)\n pCount = checkPrefixes(s, k)\n }\n while (pCount < k) {\n res += increase(s)\n pCount = checkPrefixes(s, k)\n }\n out.println(res.size)\n if (res.nonEmpty) out.println(res.mkString(\"\\n\"))\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n\n def checkLeft(s: Array[Char]): Int = {\n var x = 0\n var i = 0\n while (i < s.length) {\n s(i) match {\n case '(' => x += 1\n case ')' =>\n x -= 1\n if (x < 0) return i\n }\n i += 1\n }\n -1\n }\n\n def checkRight(s: Array[Char]): Int = {\n var x = 0\n var i = s.length - 1\n while (i >= 0) {\n s(i) match {\n case '(' =>\n x -= 1\n if (x < 0) return i\n case ')' =>\n x += 1\n }\n i -= 1\n }\n -1\n }\n\n def checkPrefixes(s: Array[Char], k: Int): Int = {\n var x, pCount = 0\n var i = 0\n while (i < s.length) {\n s(i) match {\n case '(' => x += 1\n case ')' => x -= 1\n }\n if (x == 0) pCount += 1\n i += 1\n }\n pCount\n }\n\n def increase(s: Array[Char]): String = {\n val l = s.indexOfSlice(\"((\")\n val r = s.indexOf(')', l)\n s(l) = ')'\n s(l + 1) = '('\n s\"${l + 1} ${l + 2}\"\n }\n\n def reduce(s: Array[Char]): String = {\n var l = 0\n var x = 0\n var done = false\n while (!done) {\n s(l) match {\n case '(' =>\n x += 1\n if (x == 1 && l > 0) done = true\n case ')' =>\n x -= 1\n }\n l += 1\n }\n l -= 2\n s(l) = '('\n s(l + 1) = ')'\n s\"${l + 1} ${l + 2}\"\n }\n\n for (test <- 1 to t) {\n val n, k = nextInt\n val s = nextLine.toCharArray\n var l = checkLeft(s)\n val res = new mutable.ArrayBuffer[String]\n while (l >= 0) {\n var r = checkRight(s)\n res += s\"${l + 1} ${r + 1}\"\n while (l < r) {\n val tmp = s(l)\n s(l) = s(r)\n s(r) = tmp\n l += 1\n r -= 1\n }\n l = checkLeft(s)\n }\n var pCount = checkPrefixes(s, k)\n while (pCount > k) {\n res += reduce(s)\n pCount = checkPrefixes(s, k)\n }\n while (pCount < k) {\n res += increase(s)\n pCount = checkPrefixes(s, k)\n }\n out.println(res.size)\n if (res.nonEmpty) out.println(res.mkString(\"\\n\"))\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n\n def checkLeft(s: Array[Char]): Int = {\n var x = 0\n var i = 0\n while (i < s.length) {\n s(i) match {\n case '(' => x += 1\n case ')' =>\n x -= 1\n if (x < 0) return i\n }\n i += 1\n }\n -1\n }\n\n def checkRight(s: Array[Char]): Int = {\n var x = 0\n var i = s.length - 1\n while (i >= 0) {\n s(i) match {\n case '(' =>\n x -= 1\n if (x < 0) return i\n case ')' =>\n x += 1\n }\n i -= 1\n }\n -1\n }\n\n def checkPrefixes(s: Array[Char], k: Int): Int = {\n var x, pCount = 0\n var i = 0\n while (i < s.length) {\n s(i) match {\n case '(' => x += 1\n case ')' => x -= 1\n }\n if (x == 0) {\n pCount += 1\n }\n i += 1\n }\n pCount\n }\n\n def increase(s: Array[Char]): String = {\n var l = 0\n var x = 0\n var done = false\n while (!done) {\n s(l) match {\n case '(' => x += 1\n case ')' =>\n x -= 1\n if (x > 0) {\n done = true\n }\n }\n l += 1\n }\n l -= 2\n s(l) = ')'\n s(l + 1) = '('\n s\"${l + 1} ${l + 2}\"\n }\n\n def reduce(s: Array[Char]): String = {\n var l = 0\n while (s(l) != ')' || s(l + 1) != '(') l += 1\n s(l) = '('\n s(l + 1) = ')'\n s\"${l + 1} ${l + 2}\"\n }\n\n for (test <- 1 to t) {\n val n, k = nextInt\n val s = nextLine.toCharArray\n if (s.length == 2000) {\n println(s.drop(1533).mkString)\n System.exit(0)\n }\n var l = checkLeft(s)\n val res = new mutable.ArrayBuffer[String]\n while (l >= 0) {\n var r = checkRight(s)\n res += s\"${l + 1} ${r + 1}\"\n while (l < r) {\n val tmp = s(l)\n s(l) = s(r)\n s(r) = tmp\n l += 1\n r -= 1\n }\n l = checkLeft(s)\n }\n var pCount = checkPrefixes(s, k)\n while (pCount > k) {\n res += reduce(s)\n pCount = checkPrefixes(s, k)\n }\n while (pCount < k) {\n res += increase(s)\n pCount = checkPrefixes(s, k)\n }\n out.println(res.size)\n if (res.nonEmpty) out.println(res.mkString(\"\\n\"))\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n\n for (_ <- 1 to t) {\n\n val n, k = nextInt\n val s = nextLine.toCharArray\n var l = 0\n val res = new mutable.ArrayBuffer[String]\n\n while (l < n) {\n val left = if (l % 2 == 0) '(' else ')'\n if (s(l) != left) {\n var r = n - 1\n while (s(r) != left) r -= 1\n res += s\"${l + 1} ${r + 1}\"\n var ll = l\n var rr = r\n while (ll < rr) {\n val tmp = s(ll)\n s(ll) = s(rr)\n s(rr) = tmp\n ll += 1\n rr -= 1\n }\n }\n l += 1\n }\n\n for (i <- 0 until n / 2 - k) {\n val l = 2 * i + 1\n val r = l + 1\n res += s\"${l + 1} ${r + 1}\"\n }\n\n out.println(res.size)\n if (res.nonEmpty) out.println(res.mkString(\"\\n\"))\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n\n def checkLeft(s: Array[Char]): Int = {\n var x = 0\n var i = 0\n while (i < s.length) {\n s(i) match {\n case '(' => x += 1\n case ')' =>\n x -= 1\n if (x < 0) return i\n }\n i += 1\n }\n -1\n }\n\n def checkRight(s: Array[Char]): Int = {\n var x = 0\n var i = s.length - 1\n while (i >= 0) {\n s(i) match {\n case '(' =>\n x -= 1\n if (x < 0) return i\n case ')' =>\n x += 1\n }\n i -= 1\n }\n -1\n }\n\n def checkPrefixes(s: Array[Char], k: Int): Int = {\n var x, pCount = 0\n var i = 0\n while (i < s.length) {\n s(i) match {\n case '(' => x += 1\n case ')' => x -= 1\n }\n if (x == 0) {\n pCount += 1\n }\n i += 1\n }\n pCount\n }\n\n def increase(s: Array[Char]): String = {\n var l = 0\n var x = 0\n var done = false\n while (!done) {\n s(l) match {\n case '(' => x += 1\n case ')' =>\n x -= 1\n if (x > 0) {\n done = true\n }\n }\n l += 1\n }\n l -= 2\n s(l) = ')'\n s(l + 1) = '('\n s\"${l + 1} ${l + 2}\"\n }\n\n def reduce(s: Array[Char]): String = {\n var l = 0\n while (s(l) != ')' || s(l + 1) != '(') l += 1\n s(l) = '('\n s(l + 1) = ')'\n s\"${l + 1} ${l + 2}\"\n }\n\n for (test <- 1 to t) {\n val n, k = nextInt\n val s = nextLine.toCharArray\n if (s.length == 2000) {\n println(s.mkString)\n System.exit(0)\n }\n var l = checkLeft(s)\n val res = new mutable.ArrayBuffer[String]\n while (l >= 0) {\n var r = checkRight(s)\n res += s\"${l + 1} ${r + 1}\"\n while (l < r) {\n val tmp = s(l)\n s(l) = s(r)\n s(r) = tmp\n l += 1\n r -= 1\n }\n l = checkLeft(s)\n }\n var pCount = checkPrefixes(s, k)\n while (pCount > k) {\n res += reduce(s)\n pCount = checkPrefixes(s, k)\n }\n while (pCount < k) {\n res += increase(s)\n pCount = checkPrefixes(s, k)\n }\n out.println(res.size)\n if (res.nonEmpty) out.println(res.mkString(\"\\n\"))\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n\n def checkLeft(s: Array[Char]): Int = {\n var x = 0\n var i = 0\n while (i < s.length) {\n s(i) match {\n case '(' => x += 1\n case ')' =>\n x -= 1\n if (x < 0) return i\n }\n i += 1\n }\n -1\n }\n\n def checkRight(s: Array[Char]): Int = {\n var x = 0\n var i = s.length - 1\n while (i >= 0) {\n s(i) match {\n case '(' =>\n x -= 1\n if (x < 0) return i\n case ')' =>\n x += 1\n }\n i -= 1\n }\n -1\n }\n\n def checkPrefixes(s: Array[Char], k: Int): Int = {\n var x, pCount = 0\n var i = 0\n while (i < s.length) {\n s(i) match {\n case '(' => x += 1\n case ')' => x -= 1\n }\n if (x == 0) {\n pCount += 1\n }\n i += 1\n }\n pCount\n }\n\n def increase(s: Array[Char]): String = {\n var l = 0\n var x = 0\n var done = false\n while (!done) {\n s(l) match {\n case '(' => x += 1\n case ')' =>\n x -= 1\n if (x > 0) {\n done = true\n }\n }\n l += 1\n }\n l -= 2\n s(l) = ')'\n s(l + 1) = '('\n s\"${l + 1} ${l + 2}\"\n }\n\n def reduce(s: Array[Char]): String = {\n var l = 0\n while (s(l) != ')' || s(l + 1) != '(') l += 1\n s(l) = '('\n s(l + 1) = ')'\n s\"${l + 1} ${l + 2}\"\n }\n\n for (test <- 1 to t) {\n val n, k = nextInt\n val s = nextLine.toCharArray\n if (s.length == 2000) {\n println(s.drop(511).mkString)\n System.exit(0)\n }\n var l = checkLeft(s)\n val res = new mutable.ArrayBuffer[String]\n while (l >= 0) {\n var r = checkRight(s)\n res += s\"${l + 1} ${r + 1}\"\n while (l < r) {\n val tmp = s(l)\n s(l) = s(r)\n s(r) = tmp\n l += 1\n r -= 1\n }\n l = checkLeft(s)\n }\n var pCount = checkPrefixes(s, k)\n while (pCount > k) {\n res += reduce(s)\n pCount = checkPrefixes(s, k)\n }\n while (pCount < k) {\n res += increase(s)\n pCount = checkPrefixes(s, k)\n }\n out.println(res.size)\n if (res.nonEmpty) out.println(res.mkString(\"\\n\"))\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n\n def checkLeft(s: Array[Char]): Int = {\n var x = 0\n var i = 0\n while (i < s.length) {\n s(i) match {\n case '(' => x += 1\n case ')' =>\n x -= 1\n if (x < 0) return i\n }\n i += 1\n }\n -1\n }\n\n def checkRight(s: Array[Char]): Int = {\n var x = 0\n var i = s.length - 1\n while (i >= 0) {\n s(i) match {\n case '(' =>\n x -= 1\n if (x < 0) return i\n case ')' =>\n x += 1\n }\n i -= 1\n }\n -1\n }\n\n def checkPrefixes(s: Array[Char], k: Int): Int = {\n var x, pCount = 0\n var i = 0\n while (i < s.length) {\n s(i) match {\n case '(' => x += 1\n case ')' => x -= 1\n }\n if (x == 0) {\n pCount += 1\n }\n i += 1\n }\n pCount\n }\n\n def increase(s: Array[Char]): String = {\n var l = 0\n var x = 0\n var done = false\n while (!done) {\n s(l) match {\n case '(' => x += 1\n case ')' =>\n x -= 1\n if (x > 0) {\n done = true\n }\n }\n l += 1\n }\n l -= 2\n s(l) = ')'\n s(l + 1) = '('\n s\"${l + 1} ${l + 2}\"\n }\n\n def reduce(s: Array[Char]): String = {\n var l = 0\n while (s(l) != ')' || s(l + 1) != '(') l += 1\n s(l) = '('\n s(l + 1) = ')'\n s\"${l + 1} ${l + 2}\"\n }\n\n for (test <- 1 to t) {\n val n, k = nextInt\n val s = nextLine.toCharArray\n if (s.length == 2000) {\n println(s.drop(1022).mkString)\n System.exit(0)\n }\n var l = checkLeft(s)\n val res = new mutable.ArrayBuffer[String]\n while (l >= 0) {\n var r = checkRight(s)\n res += s\"${l + 1} ${r + 1}\"\n while (l < r) {\n val tmp = s(l)\n s(l) = s(r)\n s(r) = tmp\n l += 1\n r -= 1\n }\n l = checkLeft(s)\n }\n var pCount = checkPrefixes(s, k)\n while (pCount > k) {\n res += reduce(s)\n pCount = checkPrefixes(s, k)\n }\n while (pCount < k) {\n res += increase(s)\n pCount = checkPrefixes(s, k)\n }\n out.println(res.size)\n if (res.nonEmpty) out.println(res.mkString(\"\\n\"))\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n\n for (_ <- 1 to t) {\n\n val n, k = nextInt\n val s = nextLine.toCharArray\n var l = 0\n var r = n - 1\n val res = new mutable.ArrayBuffer[String]\n\n while (l < r) {\n val left = if (l % 2 == 0) '(' else ')'\n if (s(l) != left) {\n while (s(r) != left) r -= 1\n res += s\"${l + 1} ${r + 1}\"\n var ll = l\n var rr = r\n while (ll < rr) {\n val tmp = s(ll)\n s(ll) = s(rr)\n s(rr) = tmp\n ll += 1\n rr -= 1\n }\n }\n l += 1\n }\n\n for (i <- 0 until n / 2 - k) {\n val l = 2 * i + 1\n val r = l + 1\n res += s\"${l + 1} ${r + 1}\"\n }\n\n out.println(res.size)\n if (res.nonEmpty) out.println(res.mkString(\"\\n\"))\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n\n def checkLeft(s: Array[Char]): Int = {\n var x = 0\n var i = 0\n while (i < s.length) {\n s(i) match {\n case '(' => x += 1\n case ')' =>\n x -= 1\n if (x < 0) return i\n }\n i += 1\n }\n -1\n }\n\n def checkRight(s: Array[Char]): Int = {\n var x = 0\n var i = s.length - 1\n while (i >= 0) {\n s(i) match {\n case '(' =>\n x -= 1\n if (x < 0) return i\n case ')' =>\n x += 1\n }\n i -= 1\n }\n -1\n }\n\n def checkPrefixes(s: Array[Char], k: Int): Int = {\n var x, pCount = 0\n var i = 0\n while (i < s.length) {\n s(i) match {\n case '(' => x += 1\n case ')' => x -= 1\n }\n if (x == 0) {\n pCount += 1\n }\n i += 1\n }\n pCount\n }\n\n def increase(s: Array[Char]): String = {\n var l = 0\n var x = 0\n var done = false\n while (!done) {\n s(l) match {\n case '(' => x += 1\n case ')' =>\n x -= 1\n if (x > 0) {\n done = true\n }\n }\n l += 1\n }\n l -= 2\n s(l) = ')'\n s(l + 1) = '('\n s\"${l + 1} ${l + 2}\"\n }\n\n def reduce(s: Array[Char]): String = {\n var l = 0\n var x = 0\n var done = false\n while (!done) {\n s(l) match {\n case '(' =>\n x += 1\n if (x == 1 && l > 0) {\n done = true\n }\n case ')' =>\n x -= 1\n }\n l += 1\n }\n l -= 2\n s(l) = '('\n s(l + 1) = ')'\n s\"${l + 1} ${l + 2}\"\n }\n\n for (test <- 1 to t) {\n val n, k = nextInt\n val s = nextLine.toCharArray\n var l = checkLeft(s)\n val res = new mutable.ArrayBuffer[String]\n while (l >= 0) {\n var r = checkRight(s)\n res += s\"${l + 1} ${r + 1}\"\n while (l < r) {\n val tmp = s(l)\n s(l) = s(r)\n s(r) = tmp\n l += 1\n r -= 1\n }\n l = checkLeft(s)\n }\n var pCount = checkPrefixes(s, k)\n while (pCount > k) {\n res += reduce(s)\n pCount = checkPrefixes(s, k)\n }\n while (pCount < k) {\n res += increase(s)\n pCount = checkPrefixes(s, k)\n }\n out.println(res.size)\n if (res.nonEmpty) out.println(res.mkString(\"\\n\"))\n out.flush()\n }\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "src_uid": "27faaaba7a79b7d4ba7f330cb13c0704"} {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject ChatOnline {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n def overlap(i1 : (Int,Int), i2: (Int,Int)) : Boolean = { \n return Math.max(i1._1,i2._1) <= Math.min(i1._2,i2._2) \n }\n \n def main(args: Array[String]) {\n val (p,q,l,r) = readQuad()\n val ab = for {\n i <- 1 to p\n t = readTuple()\n } yield t\n val cd = for {\n i <- 1 to q\n t = readTuple()\n } yield t\n /* val zschedule = new Array[Boolean](ab.last._2 + 1)\n for (i <- 1 to zschedule.size) {\n val cur = ab(i)\n for (j <- cur._1 to cur._2) zschedule(j) = true\n }\n val xschedule = new Array[Boolean](ab.last._2 + 1)\n for (i <- 1 to xschedule.size) {\n val cur = cd(i)\n for (j <- cur._1 to cur._2) zschedule(j) = true\n }*/\n var t = l\n var sum = 0\n var bool = false\n while (t <= r) {\n var i = 0\n var ok = false\n while (i < ab.size && !ok) {\n var j = 0 \n while (j < cd.size && !ok) {\n val ccd = (cd(j)._1+t, cd(j)._2+t)\n if (overlap(ab(i),ccd)) {\n sum += 1\n ok = true\n }\n j +=1\n }\n i += 1\n }\n t+=1\n \n }\n println(sum)\n \n \n }\n \n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(p, q, l, r) = in.next().split(\" \").map(_.toInt)\n val first = (1 to p).map{ _ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt)\n (a, b)\n }\n val second = (1 to q).map{ _ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt)\n (a, b)\n }\n\n def intersect(a: Seq[(Int, Int)], b: Seq[(Int, Int)]): Boolean = {\n if (a.isEmpty || b.isEmpty) false\n else if ((a.head._1 >= b.head._1 && a.head._1 <= b.head._2) ||\n (a.head._2 >= b.head._1 && a.head._2 <= b.head._2) ||\n (b.head._1 >= a.head._1 && b.head._1 <= a.head._2) ||\n (b.head._2 >= a.head._1 && b.head._2 <= a.head._2)) {\n true\n } else {\n if (b.head._2 > a.head._2)\n intersect(a.tail, b)\n else\n intersect(a, b.tail)\n }\n }\n\n val res = (l to r).count(i => intersect(first, second.map(t => (t._1 + i, t._2 + i))))\n println(res)\n}"}, {"source_code": "object Main extends App {\n val Array(p, q, l, r) = readLine.split(\" \").map(_.toInt)\n \n def readSegments(count: Int) = {\n (1 to count).map(i => {\n val Array(v1, v2) = readLine.split(\" \").map(_.toInt)\n (v1, v2)\n })\n }\n \n val pSegments = readSegments(p)\n val qSegments = readSegments(q)\n \n def intersect(seg1: (Int, Int), seg2: (Int, Int)) = {\n seg1._1 <= seg2._2 && seg1._2 >= seg2._1\n }\n\n def commonMoment(shift: Int) = {\n qSegments.map(x => (x._1 + shift, x._2 + shift))\n .exists(qSeg => pSegments.exists(pSeg => intersect(pSeg, qSeg)))\n }\n \n println((l to r).count(commonMoment))\n}"}], "negative_code": [], "src_uid": "aa77158bf4c0854624ddd89aa8b424b3"} {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\n/**\n * Created by dmitry on 11.02.17.\n */\nobject Main3 {\n def main(args: Array[String]) {\n val graphMap: mutable.Map[Int, mutable.MutableList[Int]] = mutable.HashMap()\n /*graphMap += (1 -> graph)*/\n val n: Int = StdIn.readInt()\n for (i <- 0 until n - 1) {\n val input: List[Int] = StdIn.readLine().split(\" \").toStream.map(_.toInt).toList\n formGraph(graphMap, input.head, input.last)\n formGraph(graphMap, input.last, input.head)\n }\n val inputColors: List[Int] = StdIn.readLine().split(\" \").toStream.map(_.toInt).toList\n val colorsMap: mutable.Map[Int, Int] = mutable.HashMap()\n var j: Int = 1\n for (i <- inputColors) {\n colorsMap += (j -> i)\n j += 1\n }\n for (entry <- graphMap) {\n for (connectedVert <- entry._2) {\n if (colorsMap.get(entry._1).get != colorsMap.get(connectedVert).get) {\n var rz = solve(graphMap, colorsMap, entry._1, n)\n if (rz._1.equals(\"YES\")) {\n println(rz._1 + \"\\n\" + rz._2)\n return\n }\n rz = solve(graphMap, colorsMap, connectedVert, n)\n if (rz._1.equals(\"YES\")) {\n println(rz._1 + \"\\n\" + rz._2)\n return\n } else {\n println(\"NO\")\n return\n }\n }\n }\n }\n for (entry <- graphMap) {\n for (connectedVert <- entry._2) {\n println(\"YES\\n\" + connectedVert)\n return\n }\n }\n }\n\n def formGraph(graphMap: mutable.Map[Int, mutable.MutableList[Int]], a: Int, b: Int): Unit = {\n if (!graphMap.contains(a))\n graphMap += (a -> (new mutable.MutableList[Int] += b))\n else {\n val listOfVertex: mutable.MutableList[Int] = graphMap.get(a).get\n listOfVertex += b\n }\n }\n\n def solve(graphMap: mutable.Map[Int, mutable.MutableList[Int]], colorGraph: mutable.Map[Int, Int], start: Int, size: Int): (String, Int) = {\n //usedVertexes(start) = true\n val linkedVertexes = new mutable.Queue[Int]\n linkedVertexes ++= graphMap.get(start).get\n val q: mutable.Queue[Int] = new mutable.Queue[Int]\n val setOfColors: mutable.HashSet[Int] = new mutable.HashSet\n val usedVertexes: Array[Boolean] = new Array(size + 1)\n while (linkedVertexes.nonEmpty) {\n usedVertexes(start) = true\n q.clear()\n setOfColors.clear()\n q.enqueue(linkedVertexes.dequeue())\n while (q.nonEmpty) {\n val vert = q.dequeue()\n if (!usedVertexes(vert)) {\n setOfColors += colorGraph.get(vert).get\n if (setOfColors.size > 1)\n return (\"NO\", -1)\n val lv = graphMap.get(vert).get\n for (v <- lv)\n q.enqueue(v)\n usedVertexes(vert) = true\n }\n }\n }\n (\"YES\", start)\n }\n}\n", "positive_code": [{"source_code": "import Utils._, annotation._, collection._, util._, control._, math.Ordering.Implicits._, Searching._\n\nobject _764C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n = read[Int]\n val edges = newMultiMap[Int, Int]\n repeat(n - 1) {\n val u, v = read[Int]\n edges(u) += v\n edges(v) += u\n }\n val colors = read[Vector, Int](n)\n /************************************/\n\n val cache = mutable.Map.empty[(Int, Int), Option[Int]]\n\n def singleColor(u: Int, parent: Int): Option[Int] = cache.getOrElseUpdate((u, parent), {\n val myColor = colors(u - 1)\n val isOkay = edges(u).forall(v => v == parent || singleColor(v, parent = u).contains(myColor))\n //debug(parent, u, isOkay)\n when(isOkay)(myColor)\n })\n\n def isOkay(root: Int) = edges(root).forall(u => singleColor(u, parent = root).isDefined)\n\n val out = (1 to n).find(isOkay) match {\n case Some(i) => s\"YES\\n$i\"\n case _ => \"NO\"\n }\n\n write(out)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\n/**\n * Created by dmitry on 11.02.17.\n */\nobject Main3 {\n def main(args: Array[String]) {\n val graphMap: mutable.Map[Int, mutable.MutableList[Int]] = mutable.HashMap()\n /*graphMap += (1 -> graph)*/\n val n: Int = StdIn.readInt()\n for (i <- 0 until n - 1) {\n val input: List[Int] = StdIn.readLine().split(\" \").toStream.map(_.toInt).toList\n formGraph(graphMap, input.head, input.last)\n formGraph(graphMap, input.last, input.head)\n }\n for (entry <- graphMap) {\n //println(entry._1 + \" \" + entry._2.toString())\n }\n val inputColors: List[Int] = StdIn.readLine().split(\" \").toStream.map(_.toInt).toList\n val colorsMap: mutable.Map[Int, Int] = mutable.HashMap()\n var j: Int = 1\n for (i <- inputColors) {\n colorsMap += (j -> i)\n j += 1\n }\n for (entry <- colorsMap) {\n //println(entry._1 + \" \" + entry._2.toString())\n }\n for (entry <- graphMap) {\n for (connectedVert <- entry._2) {\n if (colorsMap.get(entry._1).get != colorsMap.get(connectedVert).get) {\n var rz = solve(graphMap, colorsMap, entry._1, n)\n if (rz._1.equals(\"YES\")) {\n println(rz._1 + \"\\n\" + rz._2)\n return\n }\n rz = solve(graphMap, colorsMap, connectedVert, n)\n if (rz._1.equals(\"YES\")) {\n println(rz._1 + \"\\n\" + rz._2)\n return\n } else {\n println(\"NO\")\n return\n }\n }\n\n }\n }\n }\n\n def formGraph(graphMap: mutable.Map[Int, mutable.MutableList[Int]], a: Int, b: Int): Unit = {\n if (!graphMap.contains(a))\n graphMap += (a -> (new mutable.MutableList[Int] += b))\n else {\n val listOfVertex: mutable.MutableList[Int] = graphMap.get(a).get\n listOfVertex += b\n }\n }\n\n def solve(graphMap: mutable.Map[Int, mutable.MutableList[Int]], colorGraph: mutable.Map[Int, Int], start: Int, size: Int): Tuple2[String, Int] = {\n var q: mutable.Queue[Int] = new mutable.Queue[Int]\n q += start\n val usedVertexes: Array[Boolean] = Array.fill(size + 1)(false)\n usedVertexes(start) = true\n val linkedVertexes = graphMap.get(start).get\n for (v <- linkedVertexes)\n q.enqueue(v)\n val setOfColors: mutable.HashSet[Int] = new mutable.HashSet\n while (q.nonEmpty) {\n val vert = q.dequeue()\n if (!usedVertexes(vert)) {\n setOfColors += colorGraph.get(vert).get\n if (setOfColors.size > 1)\n return (\"NO\", -1)\n val linkedVertexes = graphMap.get(vert).get\n for (v <- linkedVertexes)\n q.enqueue(v)\n usedVertexes(vert) = true\n }\n }\n (\"YES\", start)\n }\n}"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\n/**\n * Created by dmitry on 11.02.17.\n */\nobject Main3 {\n def main(args: Array[String]) {\n val graphMap: mutable.Map[Int, mutable.MutableList[Int]] = mutable.HashMap()\n /*graphMap += (1 -> graph)*/\n val n: Int = StdIn.readInt()\n for (i <- 0 until n - 1) {\n val input: List[Int] = StdIn.readLine().split(\" \").toStream.map(_.toInt).toList\n formGraph(graphMap, input.head, input.last)\n formGraph(graphMap, input.last, input.head)\n }\n for (entry <- graphMap) {\n //println(entry._1 + \" \" + entry._2.toString())\n }\n val inputColors: List[Int] = StdIn.readLine().split(\" \").toStream.map(_.toInt).toList\n val colorsMap: mutable.Map[Int, Int] = mutable.HashMap()\n var j: Int = 1\n for (i <- inputColors) {\n colorsMap += (j -> i)\n j += 1\n }\n for (entry <- colorsMap) {\n //println(entry._1 + \" \" + entry._2.toString())\n }\n for (entry <- graphMap) {\n for (connectedVert <- entry._2) {\n if (colorsMap.get(entry._1).get != colorsMap.get(connectedVert).get) {\n var rz = solve(graphMap, colorsMap, entry._1, n)\n if (rz._1.equals(\"YES\")) {\n println(rz._1 + \"\\n\" + rz._2)\n return\n }\n rz = solve(graphMap, colorsMap, connectedVert, n)\n if (rz._1.equals(\"YES\")) {\n println(rz._1 + \"\\n\" + rz._2)\n return\n } else {\n println(\"NO\")\n return\n }\n }\n }\n }\n }\n\n def formGraph(graphMap: mutable.Map[Int, mutable.MutableList[Int]], a: Int, b: Int): Unit = {\n if (!graphMap.contains(a))\n graphMap += (a -> (new mutable.MutableList[Int] += b))\n else {\n val listOfVertex: mutable.MutableList[Int] = graphMap.get(a).get\n listOfVertex += b\n }\n }\n\n def solve(graphMap: mutable.Map[Int, mutable.MutableList[Int]], colorGraph: mutable.Map[Int, Int], start: Int, size: Int): Tuple2[String, Int] = {\n //usedVertexes(start) = true\n val linkedVertexes = new mutable.Queue[Int]\n linkedVertexes ++= graphMap.get(start).get\n while (linkedVertexes.nonEmpty) {\n val usedVertexes: Array[Boolean] = Array.fill(size + 1)(false)\n usedVertexes(start) = true\n val q: mutable.Queue[Int] = new mutable.Queue[Int]\n val setOfColors: mutable.HashSet[Int] = new mutable.HashSet\n q.enqueue(linkedVertexes.dequeue())\n while (q.nonEmpty) {\n val vert = q.dequeue()\n if (!usedVertexes(vert)) {\n setOfColors += colorGraph.get(vert).get\n if (setOfColors.size > 1)\n return (\"NO\", -1)\n val lv = graphMap.get(vert).get\n for (v <- lv)\n q.enqueue(v)\n usedVertexes(vert) = true\n }\n }\n }\n (\"YES\", start)\n }\n\n}"}], "src_uid": "aaca5d07795a42ecab210327c1cf6be9"} {"source_code": "import java.util.Scanner\n\nobject A {\n\n def main(args: Array[String]): Unit = {\n var scan = new Scanner(System.in)\n var T = scan.nextLine.toInt\n var s = scan.nextLine\n var fl = s.indexOf('L')\n var fr = s.indexOf('R')\n if (fl == -1) {\n println((fr+1) + \" \" + (s.lastIndexOf('R')+2))\n } else if (fr == -1) {\n println ((fl+1)+ \" \" + fl)\n }\n else println ((fr+1)+ \" \" +fl)\n \n\n }\n\n}", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val str = in.next()\n if (str.contains('R') && !str.contains('L'))\n println(s\"${str.indexOf('R') + 1} ${str.lastIndexOf('R') + 2}\")\n else if (str.contains('R'))\n println(s\"${str.indexOf('R') + 1} ${str.lastIndexOf('R') + 1}\")\n else\n println(s\"${str.lastIndexOf('L') + 1} ${str.indexOf('L')}\")\n}"}, {"source_code": "import scala.io.Source\n\nobject D {\n\n def solve(s:String) = {\n val fl = s.indexOf('L')\n val fr = s.indexOf('R')\n val lr = s.lastIndexOf('R')\n def ret(a:Int, b:Int) = a+\" \"+b\n if (fl == -1) ret(fr, lr+1)\n else if (fr == -1) ret(fl, fl-1)\n else ret(fr, fl-1)\n }\n\n def main(args: Array[String]) {\n val x = Source.stdin.getLines.toList.last\n println(solve('.' + x))\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val s = readLine()\n val tr = s.zipWithIndex.filter(t => t._1 == 'R' || t._1 == 'L')\n if (tr(0)._1 == 'R') {\n val first = tr(0)._2 + 1\n val last = tr.find(_._1 == 'L') match {\n case Some(t) => t._2\n case None => tr.last._2 + 2\n }\n println(first + \" \" + last)\n } else {\n val first = tr.last._2 + 1\n val last = tr.head._2\n println(first + \" \" + last)\n }\n }\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val str = in.next()\n if (str.contains('R'))\n println(s\"${str.indexOf('R') + 1} ${str.lastIndexOf('R') + 1}\")\n else\n println(s\"${str.lastIndexOf('L') + 1} ${str.indexOf('L') + 1}\")\n}"}, {"source_code": "import java.util.Scanner\n\nobject A {\n\n def main(args: Array[String]): Unit = {\n var scan = new Scanner(System.in)\n var T = scan.nextLine.toInt\n var s = scan.nextLine\n var fl = s.indexOf('L')\n var fr = s.indexOf('R')\n if (fl == -1) {\n println(fr + \" \" + (s.lastIndexOf('R')+1))\n } else if (fr == -1) {\n println (fl+ \" \" + (fl-1))\n }\n else println (fr+ \" \" +(fl-1))\n \n\n }\n\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val s = readLine()\n val tr = s.zipWithIndex.filter(t => t._1 == 'R' || t._1 == 'L')\n if (tr(0)._1 == 'R') {\n val first = tr(0)._2 + 1\n val last = tr.find(_._1 == 'L') match {\n case Some(t) => t._2\n case None => tr.last._2 + 2\n }\n println(first + \" \" + last)\n } else {\n val first = tr.last._2 + 2\n val last = tr.head._2\n println(first + \" \" + last)\n }\n }\n}"}], "src_uid": "3053cba2426ebd113fcd70a9b026dad0"} {"source_code": "// Looksery Cup 2015 :: D\n\nimport java.util.Scanner\n\nobject D {\n\n\tvar n:Int = _\n\tvar m:Int = _\n\tvar w:Array[Array[Int]] = _\n\n\tdef read() = {\n\t\tn = in.nextInt\n\t\tm = in.nextInt\n\t\tin.nextLine\n\n\t\tw = (0 until n).map(i => in.nextLine().toCharArray().map(c => if (c == 'W') 1 else -1).toArray).toArray\n\t}\n\n\tval in:Scanner = new Scanner(System.in)\n\n\tdef main(args: Array[String]) = {\n\t\tread()\n\n\t\tval targetValue:Int = w(n - 1)(m - 1)\n\n\t\tvar add:Array[Int] = Array.fill(m)(0)\n\n\t\tvar count:Int = 0\n\n\t\tfor (i <- n - 1 to 0 by -1) {\n\t\t\tfor (j <- m - 1 to 0 by -1) {\n\t\t\t\tvar value = w(i)(j) + add(j)\n\t\t\t\tif (value != targetValue) {\n\t\t\t\t\tfor (k <- 0 to j) {\n\t\t\t\t\t\tadd(k) += targetValue - value\n\t\t\t\t\t}\n\t\t\t\t\tcount += 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprintln(count + 1)\n\t}\n\n}", "positive_code": [{"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val ss = Array.fill(n) { readLine }\n\n def get(i: Int, j: Int): Int = {\n if (i == n || j == m) 0\n else if (ss(i)(j) == 'W') 1 else -1\n }\n\n var res = 0\n \n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (get(i, j) != get(i + 1, j) + get(i, j + 1) - get(i + 1, j + 1)) res += 1\n }\n }\n\n println(res)\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject D {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n var ft1: Array[Array[Int]] = _\n var ft2: Array[Array[Int]] = _\n var in: Array[Array[Char]] = _\n var bValue: Int = -1\n var wValue: Int = 1\n\n def invert1(x: Int, y: Int, diff: Int) = {\n for (i <- 0 to x)\n for (j <- 0 to y) {\n ft1(i)(j) += diff\n }\n }\n\n// def invert2(x: Int, y: Int) = {\n// for (i <- 0 to x)\n// for (j <- 0 to y) {\n// ft2(i)(j) = !ft2(i)(j)\n// }\n// }\n\n def check1(): Boolean = {\n val n = ft1.length\n val m = ft1(0).length\n for (i <- n - 1 to 0 by -1) {\n for (j <- m - 1 to 0 by -1) {\n if (in(i)(j) == 'B' && ft1(i)(j) != bValue) {\n invert1(i, j, bValue - ft1(i)(j))\n return false\n }\n if (in(i)(j) == 'W' && ft1(i)(j) != wValue) {\n invert1(i, j, wValue - ft1(i)(j))\n return false\n }\n }\n }\n true\n }\n\n// def check2(): Boolean = {\n// val n = ft2.length\n// val m = ft2(0).length\n// for (i <- n - 1 to 0 by -1) {\n// for (j <- m - 1 to 0 by -1) {\n// if ((in(i)(j) == 'B' && ft2(i)(j) != bValue) || (in(i)(j) == 'W' && ft2(i)(j) != wValue)) {\n// invert2(i, j)\n// return false\n// }\n// }\n// }\n// true\n// }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n ft1 = new Array[Array[Int]](n)\n ft2 = new Array[Array[Int]](n)\n in = new Array[Array[Char]](n)\n for (i <- 0 until n) {\n ft1(i) = new Array[Int](m)\n ft2(i) = new Array[Int](m)\n in(i) = next.toCharArray\n }\n var ans1 = 0\n while (!check1 && ans1 <= 10000) {\n ans1 += 1\n }\n out.println(ans1)\n return 0\n }\n}"}, {"source_code": "import scala.io.StdIn\n\n/**\n * @author chengyi\n */\nobject HaarFeatures {\n \n //find the corner from sr, sc in decreasing order, b against a\n def getCorner(a:Array[Array[Int]], b:Array[Array[Int]], sr:Int, sc:Int):(Int,Int)={\n (sc to 0 by -1).foreach(c=>({\n var rsr = 0\n if (c==sc) rsr = sr else rsr = b.length-1\n (rsr to 0 by -1).foreach(r=>({\n if (b(r)(c)!=a(r)(c)) return (r,c)\n }))\n }\n ))\n \n return (-1,-1)\n }\n \n //update b to make corner match a's\n def update(a:Array[Array[Int]], b:Array[Array[Int]], r:Int, c:Int) = {\n val delta = a(r)(c) - b(r)(c)\n (0 to r).foreach(rr=>((0 to c).foreach(cc=>(b(rr)(cc)=b(rr)(cc)+delta))))\n }\n \n def minOp(input:Array[String]):Int={\n val r = input.length\n val c = input(0).length\n val iinput:Array[Array[Int]]=Array.fill(r, c)(0)\n (1 to r).foreach(i=>{\n (1 to c).foreach(j=>if (input(i-1)(j-1)=='W') iinput(i-1)(j-1)=1 else iinput(i-1)(j-1)= -1)\n })\n \n //println(iinput.deep.mkString(\"\\n\"))\n \n val cur = Array.fill(r, c)(0)\n val sr = r-1\n val sc = c-1\n var (cr, cc) = getCorner(iinput, cur, sr, sc)\n \n //println(\"corner:\" + cr + \", \" + cc)\n \n var times = 1\n while (cr!= -1){\n update(iinput, cur, cr, cc);\n \n //println(cur.deep.mkString(\"\\n\"))\n \n val corner = getCorner(iinput, cur, cr, cc)\n cr = corner._1\n cc = corner._2\n \n //println(\"corner:\" + cr + \", \" + cc)\n \n times = times + 1\n }\n return times-1\n }\n \n def main(args:Array[String]){\n val rc = StdIn.readLine().split(\" \").map { x => x.toInt }\n val r = rc(0)\n val c = rc(1)\n val input = Array.fill(r)(\"\")\n (1 to r).foreach(i=>input(i-1) = StdIn.readLine())\n println(minOp(input))\n }\n}"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val ss = Array.fill(n) { readLine }\n\n val cntB = Array.fill(n, m) { 0 }\n\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n val up = if (i == 0) 0 else cntB(i - 1)(j)\n val left = if (j == 0) 0 else cntB(i)(j - 1)\n val upLeft = if (j == 0 || i == 0) 0 else cntB(i - 1)(j - 1)\n val prev = up + left - upLeft\n cntB(i)(j) = prev + (if (ss(i)(j) == 'B') 1 else 0)\n }\n }\n\n val res = Array.fill(n, m) { 0 }\n res(0)(0) = 1\n\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n val ops = if (i == 0 && j == 0) 1\n else if (i == 0 && j > 0) res(i)(j - 1) + (if (ss(i)(j) != ss(i)(j - 1)) 1 else 0)\n else if (i > 0 && j == 0) res(i - 1)(j) + (if (ss(i)(j) != ss(i - 1)(j)) 1 else 0)\n else {\n val a = ss(i - 1)(j - 1)\n val b = ss(i)(j - 1)\n val c = ss(i - 1)(j)\n val d = ss(i)(j)\n val aR = res(i - 1)(j - 1)\n val bR = res(i)(j - 1)\n val cR = res(i - 1)(j)\n if (a == b && b == c && c == d) bR max cR\n else if (d == b && d == c) bR + cR - 2 * aR + 1\n else if (a == b && d == c) bR max cR\n else if (a == c && d == b) bR max cR\n else if (a == d && c == b) bR + cR - aR + 1\n else if (a == b && a == c) bR + cR + 2\n else 0\n }\n //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) != ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) + res(i - 1)(j - 1) + 1\n //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) == ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) - res(i - 1)(j - 1) + 1\n //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1)) res(i - 1)(j - 1) + 3\n //else if (ss(i)(j) == ss(i - 1)(j - 1)) ((res(i - 1)(j) max res(i)(j - 1)))\n //else ((res(i - 1)(j) max res(i)(j - 1)))\n //println(i, j, ops)\n res(i)(j) = ops\n }\n }\n \n // for (x <- res) println(x.mkString(\" \"))\n \n println(res.last.last)\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val ss = Array.fill(n) { readLine }\n\n val cntB = Array.fill(n, m) { 0 }\n\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n val up = if (i == 0) 0 else cntB(i - 1)(j)\n val left = if (j == 0) 0 else cntB(i)(j - 1)\n val upLeft = if (j == 0 || i == 0) 0 else cntB(i - 1)(j - 1)\n val prev = up + left - upLeft\n cntB(i)(j) = prev + (if (ss(i)(j) == 'B') 1 else 0)\n }\n }\n\n val res = Array.fill(n, m) { 0 }\n res(0)(0) = 1\n\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n val ops = if (i == 0 && j == 0) 1\n else if (i == 0 && j > 0) {\n // println(res(i)(j - 1))\n res(i)(j - 1) + (if (ss(i)(j) != ss(i)(j - 1)) 1 else 0)\n }\n else if (i > 0 && j == 0) res(i - 1)(j) + (if (ss(i)(j) != ss(i - 1)(j)) 1 else 0)\n //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) != ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) + res(i - 1)(j - 1) + 1\n //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) == ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) - res(i - 1)(j - 1) + 1\n else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1)) res(i - 1)(j - 1) + 3\n else (res(i - 1)(j) max res(i)(j - 1))\n //println(i, j, ops)\n res(i)(j) = ops\n }\n }\n \n //for (x <- res) println(x.mkString(\" \"))\n \n println(res.last.last)\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val ss = Array.fill(n) { readLine }\n\n val cntB = Array.fill(n, m) { 0 }\n\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n val up = if (i == 0) 0 else cntB(i - 1)(j)\n val left = if (j == 0) 0 else cntB(i)(j - 1)\n val upLeft = if (j == 0 || i == 0) 0 else cntB(i - 1)(j - 1)\n val prev = up + left - upLeft\n cntB(i)(j) = prev + (if (ss(i)(j) == 'B') 1 else 0)\n }\n }\n\n val res = Array.fill(n, m) { 0 }\n res(0)(0) = 1\n\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n val ops = if (i == 0 && j == 0) 1\n else if (i == 0 && j > 0) res(i)(j - 1) + (if (ss(i)(j) != ss(i)(j - 1)) 1 else 0)\n else if (i > 0 && j == 0) res(i - 1)(j) + (if (ss(i)(j) != ss(i - 1)(j)) 1 else 0)\n else {\n val a = ss(i - 1)(j - 1)\n val b = ss(i)(j - 1)\n val c = ss(i - 1)(j)\n val d = ss(i)(j)\n val aR = res(i - 1)(j - 1)\n val bR = res(i)(j - 1)\n val cR = res(i - 1)(j)\n if (a == b && b == c && c == d) bR max cR\n else if (d == b && d == c) (bR max cR)\n else if (a == b && d == c) bR max cR\n else if (a == c && d == b) bR max cR\n else if (a == d && c == b) bR + cR - aR + 1\n else if (a == b && a == c) bR + cR + 2\n else 0\n }\n //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) != ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) + res(i - 1)(j - 1) + 1\n //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) == ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) - res(i - 1)(j - 1) + 1\n //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1)) res(i - 1)(j - 1) + 3\n //else if (ss(i)(j) == ss(i - 1)(j - 1)) ((res(i - 1)(j) max res(i)(j - 1)))\n //else ((res(i - 1)(j) max res(i)(j - 1)))\n //println(i, j, ops)\n res(i)(j) = ops\n }\n }\n \n //for (x <- res) println(x.mkString(\" \"))\n \n println(res.last.last)\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val ss = Array.fill(n) { readLine }\n\n val cntB = Array.fill(n, m) { 0 }\n\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n val up = if (i == 0) 0 else cntB(i - 1)(j)\n val left = if (j == 0) 0 else cntB(i)(j - 1)\n val upLeft = if (j == 0 || i == 0) 0 else cntB(i - 1)(j - 1)\n val prev = up + left - upLeft\n cntB(i)(j) = prev + (if (ss(i)(j) == 'B') 1 else 0)\n }\n }\n\n val res = Array.fill(n, m) { 0 }\n res(0)(0) = 1\n\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n val ops = if (i == 0 && j == 0) 1\n else if (i == 0 && j > 0) {\n // println(res(i)(j - 1))\n res(i)(j - 1) + (if (ss(i)(j) != ss(i)(j - 1)) 1 else 0)\n }\n else if (i > 0 && j == 0) res(i - 1)(j) + (if (ss(i)(j) != ss(i - 1)(j)) 1 else 0)\n else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) != ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) + res(i - 1)(j - 1) + 1\n else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) == ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) - res(i - 1)(j - 1) + 1\n else (res(i - 1)(j) max res(i)(j - 1))\n //println(i, j, ops)\n res(i)(j) = ops\n }\n }\n \n //for (x <- res) println(x.mkString(\" \"))\n \n println(res.last.last)\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val ss = Array.fill(n) { readLine }\n\n val cntB = Array.fill(n, m) { 0 }\n\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n val up = if (i == 0) 0 else cntB(i - 1)(j)\n val left = if (j == 0) 0 else cntB(i)(j - 1)\n val upLeft = if (j == 0 || i == 0) 0 else cntB(i - 1)(j - 1)\n val prev = up + left - upLeft\n cntB(i)(j) = prev + (if (ss(i)(j) == 'B') 1 else 0)\n }\n }\n\n val res = Array.fill(n, m) { 0 }\n res(0)(0) = 1\n\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n val ops = if (i == 0 && j == 0) 1\n else if (i == 0 && j > 0) res(i)(j - 1) + (if (ss(i)(j) != ss(i)(j - 1)) 1 else 0)\n else if (i > 0 && j == 0) res(i - 1)(j) + (if (ss(i)(j) != ss(i - 1)(j)) 1 else 0)\n else {\n val a = ss(i - 1)(j - 1)\n val b = ss(i)(j - 1)\n val c = ss(i - 1)(j)\n val d = ss(i)(j)\n val aR = res(i - 1)(j - 1)\n val bR = res(i)(j - 1)\n val cR = res(i - 1)(j)\n if (a == b && b == c && c == d) bR max cR\n else if (d == b && d == c) bR max cR\n else if (a == b && d == c) bR max cR\n else if (a == c && d == b) bR max cR\n else if (a == d && c == b) bR + cR - aR + 1\n else if (a == b && a == c) bR + cR + 2\n else 0\n }\n //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) != ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) + res(i - 1)(j - 1) + 1\n //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) == ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) - res(i - 1)(j - 1) + 1\n //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1)) res(i - 1)(j - 1) + 3\n //else if (ss(i)(j) == ss(i - 1)(j - 1)) ((res(i - 1)(j) max res(i)(j - 1)))\n //else ((res(i - 1)(j) max res(i)(j - 1)))\n //println(i, j, ops)\n res(i)(j) = ops\n }\n }\n \n //for (x <- res) println(x.mkString(\" \"))\n \n println(res.last.last)\n}\n"}, {"source_code": "import scala.collection._\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val ss = Array.fill(n) { readLine }\n\n val cntB = Array.fill(n, m) { 0 }\n\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n val up = if (i == 0) 0 else cntB(i - 1)(j)\n val left = if (j == 0) 0 else cntB(i)(j - 1)\n val upLeft = if (j == 0 || i == 0) 0 else cntB(i - 1)(j - 1)\n val prev = up + left - upLeft\n cntB(i)(j) = prev + (if (ss(i)(j) == 'B') 1 else 0)\n }\n }\n\n val res = Array.fill(n, m) { 0 }\n res(0)(0) = 1\n\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n val ops = if (i == 0 && j == 0) 1\n else if (i == 0 && j > 0) res(i)(j - 1) + (if (ss(i)(j) != ss(i)(j - 1)) 1 else 0)\n else if (i > 0 && j == 0) res(i - 1)(j) + (if (ss(i)(j) != ss(i - 1)(j)) 1 else 0)\n else {\n val a = ss(i - 1)(j - 1)\n val b = ss(i)(j - 1)\n val c = ss(i - 1)(j)\n val d = ss(i)(j)\n val aR = res(i - 1)(j - 1)\n val bR = res(i)(j - 1)\n val cR = res(i - 1)(j)\n if (a == b && b == c && c == d) bR max cR\n else if (d == b && d == c) bR + cR - 2 * aR + 1\n else if (a == b && d == c) bR max cR\n else if (a == c && d == b) bR max cR\n else if (a == d && c == b) bR + cR - aR + 1\n else if (a == b && a == c) bR + cR + 2\n else 0\n }\n //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) != ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) + res(i - 1)(j - 1) + 1\n //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) == ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) - res(i - 1)(j - 1) + 1\n //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1)) res(i - 1)(j - 1) + 3\n //else if (ss(i)(j) == ss(i - 1)(j - 1)) ((res(i - 1)(j) max res(i)(j - 1)))\n //else ((res(i - 1)(j) max res(i)(j - 1)))\n //println(i, j, ops)\n res(i)(j) = ops\n }\n }\n \n //for (x <- res) println(x.mkString(\" \"))\n \n println(res.last.last)\n}\n"}], "src_uid": "ce6b65ca755d2d860fb76688b3d775db"} {"source_code": "object D {\n\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n, m = nextInt\n val grid = new Array[Array[Char]](n)\n for (i <- 0 until n) {\n grid(i) = nextToken.toCharArray\n }\n\n def dfs1(r: Int, c: Int): Boolean = {\n if (r == n - 1 && c == m - 1) true\n else {\n grid(r)(c) = '*'\n var done = false\n if (c < m - 1 && grid(r)(c + 1) == '.') {\n done = dfs1(r, c + 1)\n }\n if (!done && r < n - 1 && grid(r + 1)(c) == '.') {\n done = dfs1(r + 1, c)\n }\n done\n }\n }\n\n def dfs2(r: Int, c: Int): Boolean = {\n if (r == n - 1 && c == m - 1) true\n else {\n grid(r)(c) = '*'\n var done = false\n if (r < n - 1 && grid(r + 1)(c) == '.') {\n done = dfs2(r + 1, c)\n }\n if (!done && c < m - 1 && grid(r)(c + 1) == '.') {\n done = dfs2(r, c + 1)\n }\n done\n }\n }\n\n val can1 = dfs1(0, 0)\n val can2 = dfs2(0, 0)\n var res = 0\n if (can1) res += 1\n if (can2) res += 1\n\n out.println(res)\n out.flush()\n\n object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n)(nextInt)\n def readLongs(n: Int) = Array.fill(n)(nextLong)\n def readBigs(n: Int) = Array.fill(n)(nextBig)\n }\n}\n", "positive_code": [{"source_code": "object D {\n\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n, m = nextInt\n val grid = Array.fill(n)(nextToken.toCharArray)\n\n def dfs1(r: Int, c: Int): Boolean = {\n if (r == n - 1 && c == m - 1) true\n else {\n grid(r)(c) = '*'\n var done = false\n if (c < m - 1 && grid(r)(c + 1) == '.') {\n done = dfs1(r, c + 1)\n }\n if (!done && r < n - 1 && grid(r + 1)(c) == '.') {\n done = dfs1(r + 1, c)\n }\n done\n }\n }\n\n def dfs2(r: Int, c: Int): Boolean = {\n if (r == n - 1 && c == m - 1) true\n else {\n grid(r)(c) = '*'\n var done = false\n if (r < n - 1 && grid(r + 1)(c) == '.') {\n done = dfs2(r + 1, c)\n }\n if (!done && c < m - 1 && grid(r)(c + 1) == '.') {\n done = dfs2(r, c + 1)\n }\n done\n }\n }\n\n val can1 = dfs1(0, 0)\n val can2 = dfs2(0, 0)\n var res = 0\n if (can1) res += 1\n if (can2) res += 1\n\n out.println(res)\n out.flush()\n\n object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n)(nextInt)\n def readLongs(n: Int) = Array.fill(n)(nextLong)\n def readBigs(n: Int) = Array.fill(n)(nextBig)\n }\n}\n"}, {"source_code": "object D {\n\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n, m = nextInt\n val grid = new Array[Array[Char]](n)\n var i = 0\n while (i < n) {\n grid(i) = nextToken.toCharArray\n i += 1\n }\n\n def dfs1(r: Int, c: Int): Boolean = {\n if (r == n - 1 && c == m - 1) true\n else {\n grid(r)(c) = '*'\n var done = false\n if (c < m - 1 && grid(r)(c + 1) == '.') {\n done = dfs1(r, c + 1)\n }\n if (!done && r < n - 1 && grid(r + 1)(c) == '.') {\n done = dfs1(r + 1, c)\n }\n done\n }\n }\n\n def dfs2(r: Int, c: Int): Boolean = {\n if (r == n - 1 && c == m - 1) true\n else {\n grid(r)(c) = '*'\n var done = false\n if (r < n - 1 && grid(r + 1)(c) == '.') {\n done = dfs2(r + 1, c)\n }\n if (!done && c < m - 1 && grid(r)(c + 1) == '.') {\n done = dfs2(r, c + 1)\n }\n done\n }\n }\n\n val can1 = dfs1(0, 0)\n val can2 = dfs2(0, 0)\n var res = 0\n if (can1) res += 1\n if (can2) res += 1\n\n out.println(res)\n out.flush()\n\n object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n)(nextInt)\n def readLongs(n: Int) = Array.fill(n)(nextLong)\n def readBigs(n: Int) = Array.fill(n)(nextBig)\n }\n}\n"}, {"source_code": "object D {\n\n def main(args: Array[String]): Unit = {}\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n val grid = Array.fill(n)(readLine.toCharArray.map(_ == '#'))\n\n def dfs1(r: Int, c: Int): Boolean = {\n if (r == n - 1 && c == m - 1) true\n else {\n grid(r)(c) = true\n var done = false\n if (c < m - 1 && !grid(r)(c + 1)) {\n done = dfs1(r, c + 1)\n }\n if (!done && r < n - 1 && !grid(r + 1)(c)) {\n done = dfs1(r + 1, c)\n }\n done\n }\n }\n\n def dfs2(r: Int, c: Int): Boolean = {\n if (r == n - 1 && c == m - 1) true\n else {\n grid(r)(c) = true\n var done = false\n if (r < n - 1 && !grid(r + 1)(c)) {\n done = dfs2(r + 1, c)\n }\n if (!done && c < m - 1 && !grid(r)(c + 1)) {\n done = dfs2(r, c + 1)\n }\n done\n }\n }\n\n val can1 = dfs1(0, 0)\n val can2 = dfs2(0, 0)\n var res = 0\n if (can1) res += 1\n if (can2) res += 1\n\n println(res)\n}\n"}, {"source_code": "object D {\n\n import IO._\n def main(args: Array[String]): Unit = {}\n\n val n, m = nextInt\n val grid = Array.fill(n)(nextToken.toCharArray.map(_ == '#'))\n\n def dfs1(r: Int, c: Int): Boolean = {\n if (r == n - 1 && c == m - 1) true\n else {\n grid(r)(c) = true\n var done = false\n if (c < m - 1 && !grid(r)(c + 1)) {\n done = dfs1(r, c + 1)\n }\n if (!done && r < n - 1 && !grid(r + 1)(c)) {\n done = dfs1(r + 1, c)\n }\n done\n }\n }\n\n def dfs2(r: Int, c: Int): Boolean = {\n if (r == n - 1 && c == m - 1) true\n else {\n grid(r)(c) = true\n var done = false\n if (r < n - 1 && !grid(r + 1)(c)) {\n done = dfs2(r + 1, c)\n }\n if (!done && c < m - 1 && !grid(r)(c + 1)) {\n done = dfs2(r, c + 1)\n }\n done\n }\n }\n\n val can1 = dfs1(0, 0)\n val can2 = dfs2(0, 0)\n var res = 0\n if (can1) res += 1\n if (can2) res += 1\n\n out.println(res)\n out.flush()\n\n object IO {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n)(nextInt)\n def readLongs(n: Int) = Array.fill(n)(nextLong)\n def readBigs(n: Int) = Array.fill(n)(nextBig)\n }\n}\n"}, {"source_code": "object D {\n\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n, m = nextInt\n val grid = new Array[Array[Char]](n)\n var i = 0\n while (i < n) {\n grid(i) = in.readLine.toCharArray\n i += 1\n }\n\n def dfs1(r: Int, c: Int): Boolean = {\n if (r == n - 1 && c == m - 1) true\n else {\n grid(r)(c) = '*'\n var done = false\n if (c < m - 1 && grid(r)(c + 1) == '.') {\n done = dfs1(r, c + 1)\n }\n if (!done && r < n - 1 && grid(r + 1)(c) == '.') {\n done = dfs1(r + 1, c)\n }\n done\n }\n }\n\n def dfs2(r: Int, c: Int): Boolean = {\n if (r == n - 1 && c == m - 1) true\n else {\n grid(r)(c) = '*'\n var done = false\n if (r < n - 1 && grid(r + 1)(c) == '.') {\n done = dfs2(r + 1, c)\n }\n if (!done && c < m - 1 && grid(r)(c + 1) == '.') {\n done = dfs2(r, c + 1)\n }\n done\n }\n }\n\n val can1 = dfs1(0, 0)\n val can2 = dfs2(0, 0)\n var res = 0\n if (can1) res += 1\n if (can2) res += 1\n\n out.println(res)\n out.flush()\n\n object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n)(nextInt)\n def readLongs(n: Int) = Array.fill(n)(nextLong)\n def readBigs(n: Int) = Array.fill(n)(nextBig)\n }\n}\n"}], "negative_code": [], "src_uid": "5b20c29b7170b139a64f84d414515a9d"} {"source_code": "import java.util.Scanner\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\nimport java.lang.Long.bitCount\nimport java.nio.CharBuffer\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.annotation.switch\nimport scala.annotation.unchecked\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.PriorityQueue\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject P282B extends App {\n // val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n object Input {\n import java.lang.Character._\n\n lazy val in = new BufferedReader(new InputStreamReader(java.lang.System.in))\n var buf: Array[Char] = Array()\n var pos: Int = 0\n\n def next(): String = {\n while (pos == buf.length) {\n buf = in.readLine.toArray\n pos = 0\n }\n while (isWhitespace(buf(pos))) {\n pos += 1\n }\n while (pos == buf.length) {\n buf = in.readLine.toArray\n pos = 0\n }\n val s = pos\n while (pos < buf.length && !isWhitespace(buf(pos))) {\n pos += 1\n }\n new java.lang.String(buf, s, pos - s)\n }\n\n def nextInt(): Int = next.toInt\n\n def nextLong(): Long = next.toLong\n\n def nextFloat(): Float = next.toFloat\n\n def nextDouble(): Double = next.toDouble\n\n val nextString: () => String = next _\n }\n\n import Input._\n\n def solve(): String = {\n val N = nextInt\n val buf = CharBuffer.allocate(N)\n \n @tailrec\n def loop(n: Int, d: Int): Unit = {\n if (n == N) ()\n else {\n val a, g = nextInt\n if (d + a <= 500) {\n buf.put('A')\n loop(n + 1, d + a)\n }\n else {\n buf.put('G')\n loop(n + 1, d - g)\n }\n }\n }\n\n loop(0, 0)\n buf.flip\n buf.toString\n }\n \n out.println(solve)\n out.flush\n}\n", "positive_code": [{"source_code": "object CF173Div2B {\n def main(args: Array[String]){\n val n = readLine.toInt\n val pay = (1 to n).map(_ => readLine.split(\" \").map(_.toInt))\n val (_,res) = pay.foldLeft((0,new StringBuilder))((b,a)=>if(b._1 + a(0) <= 500) (b._1+a(0),b._2+'A') else (b._1-a(1),b._2+'G'))\n println(res.toString)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n def n = readInt\n var dif = 0\n for(_ <- 1 to n) {\n val a = readLine().split(\" \").map(_.toInt)\n if(dif + a(0) > 500) {\n print(\"G\")\n dif -= a(1) \n } else {\n print(\"A\")\n dif += a(0)\n }\n }\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val res = (1 to n).map(_ => in.next().split(' ').map(_.toInt)).foldLeft(0, 0, List.empty[Char]) {\n case ((a, b, list), Array(f, s)) if a + f - b > 500 => (a, b + s, 'G' :: list)\n case ((a, b, list), Array(f, s)) => (a + f, b, 'A' :: list)\n }\n if (Math.abs(res._1 - res._2) <= 500)\n println(res._3.reverse.mkString)\n else\n println(-1)\n\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val res = (1 to n).foldLeft(0, 0, List.empty[Char]) {\n case ((a, b, list), _) if a > b => (a, b + in.next().split(' ').last.toInt, 'G' :: list)\n case ((a, b, list), _) => (a + in.next().split(' ').last.toInt, b, 'A' :: list)\n }\n if (Math.abs(res._1 - res._2) <= 500)\n println(res._3.reverse.mkString)\n else\n println(-1)\n\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P282A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextLine.toInt\n\n @tailrec\n def loop(acc: Int, i: Int): Int =\n if (i == N) acc\n else {\n val l = sc.nextLine\n if (l == \"X++\" || l == \"++X\") loop(acc + 1, i + 1)\n else loop(acc - 1, i + 1)\n }\n\n def solve: Int = loop(0, 0)\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.nio.CharBuffer\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject P282B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n \n def solve(): Unit = {\n val N = sc.nextInt\n //val buf = CharBuffer.allocate(N)\n\n var d = 0\n for (_ <- 0 until N) {\n val a, g = sc.nextInt\n if (d + a <= 500) {\n out.print(\"A\")\n //buf.put('A')\n d += a\n }\n else {\n out.print(\"G\")\n //buf.put('G')\n d -= a\n }\n }\n\n //buf.flip\n //buf.toString\n }\n \n solve\n out.flush\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.nio.CharBuffer\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.collection.JavaConversions._\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject P282B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = sc.nextInt\n val buf = CharBuffer.allocate(N)\n\n var sa, sg = 0\n for (_ <- 0 until N) {\n val a, g = sc.nextInt\n if ((sa + a - sg).abs <= 500) {\n buf.put('A')\n sa += a\n }\n else {\n buf.put('G')\n sg += g\n }\n }\n\n buf.flip\n buf.toString\n }\n \n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.nio.CharBuffer\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.immutable.TreeSet\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject P282B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n \n def solve(): String = {\n val N = sc.nextInt\n val buf = CharBuffer.allocate(N)\n\n\n @tailrec\n def loop(n: Int, d: Int): Unit = {\n if (n == N) ()\n else {\n val a, g = sc.nextInt\n if (d + a <= 500) {\n buf.put('A')\n loop(n + 1, d + a)\n }\n else {\n buf.put('G')\n loop(n + 1, d - a)\n }\n }\n }\n\n loop(0, 0)\n buf.flip\n buf.toString\n }\n \n println(solve.toString)\n // out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n def n = readInt\n var dif = 0\n for(_ <- 1 to n) {\n val a = readLine().split(\" \").map(_.toInt)\n if(dif + a(0) > 500) {\n print(\"G\")\n dif -= a(1) \n } else {\n print(\"A\")\n dif -= a(0)\n }\n }\n }\n}"}], "src_uid": "24fe280b88575516ec679ff78641440e"} {"source_code": "object Main {\n def main(args: Array[String]) = {\n val a = readLine()\n val b = readLine()\n\n def countOnes(a: String) = a.count(_ == '1')\n def parity(a: String) = countOnes(a) % 2\n\n println(if (countOnes(a) + parity(a) >= countOnes(b)) \"YES\" else \"NO\")\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line1 = in.next().count(_ == '1')\n val line2 = in.next().count(_ == '1')\n\n if ((line1 + line1 % 2) >= line2)\n println(\"YES\")\n else\n println(\"NO\")\n\n}"}, {"source_code": "import java.util.Scanner\n\n\nobject C {\n\n def main(args: Array[String]): Unit = {\n val scan = new Scanner(System.in)\n var s1 = scan.next\n var s2 = scan.next\n var c1 = s1.count(c => c=='1')\n var c2 = s2.count(c => c=='1')\n if( c1>= c2)println( \"YES\")\n else if(c1+1==c2 && c1%2==1)println( \"YES\")\n else println(\"NO\")\n \n }\n\n}"}], "negative_code": [], "src_uid": "cf86add6c92fa8a72b8e23efbdb38613"} {"source_code": "import scala.collection.immutable.HashMap\n\nobject Main {\n def main(args: Array[String]) = {\n val t = readInt\n (0 until t).foreach((x) => f1)\n }\n def f1(): Unit = {\n val n = readInt\n val as = (0 until n).map((x) => (readLine, x + 1))\n val (has0, has1, hasl, zo, oz) = as.foldLeft((false, false, false, HashMap[String, Int](), HashMap[String, Int]())){\n case ((h0, h1, hl, zo, oz), (s, i)) => (s(0), s(s.length - 1)) match {\n case ('0', '0') => (true, h1, hl, zo, oz)\n case ('1', '1') => (h0, true, hl, zo, oz)\n case ('1', '0') => if (zo.contains(s.reverse)){\n (h0, h1, true, zo - s.reverse, oz)\n }\n else {\n (h0, h1, hl, zo, oz + (s -> i))\n }\n case ('0', '1') => if (oz.contains(s.reverse)){\n (h0, h1, true, zo, oz - s.reverse)\n } else {\n (h0, h1, hl, zo + (s -> i), oz)\n }\n case _ => throw new Exception(\"\")\n }\n }\n if (zo.size == 0 && oz.size == 0) {\n if (hasl || ((has0 && !has1) || (!has0 && has1))) {\n println(0)\n println(\"\")\n } else {\n println(-1)\n }\n }\n else {\n val total = zo.size + oz.size\n val (s1, s2) = (total / 2, total - (total / 2))\n val (k, il) = if (zo.size < oz.size) {\n (oz.size - s2, oz.values.take(oz.size - s2))\n } else {\n (zo.size - s2, zo.values.take(zo.size - s2))\n }\n println(k)\n println(il.mkString(\" \"))\n }\n }\n }", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject D {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n for (_ <- 1 to t) {\n val n = nextInt\n val have01, have10 = mutable.Map.empty[String, Int]\n var have00, have11, haveMixed = false\n var i = 1\n while (i <= n) {\n val s = nextLine\n val l = s.length - 1\n if (s(0) == '0' && s(l) == '0') have00 = true\n else if (s(0) == '1' && s(l) == '1') have11 = true\n else {\n haveMixed = true\n val rev = s.reverse\n if (s(0) == '0' && s(l) == '1') {\n if (have10.contains(rev)) have10 -= rev\n else have01 += s -> i\n } else {\n if (have01.contains(rev)) have01 -= rev\n else have10 += s -> i\n }\n }\n i += 1\n }\n if (have00 && have11 && !haveMixed) out.println(-1)\n else {\n val need = Math.abs(have01.size - have10.size) / 2\n out.println(need)\n val res = if (have01.size > have10.size) have01 else have10\n out.println(res.values.toIterator.take(need).mkString(\" \"))\n }\n }\n\n out.println()\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.immutable.HashMap\n\nobject Main {\n def main(args: Array[String]) = {\n val t = readInt\n (0 until t).foreach((x) => f1)\n }\n def f1(): Unit = {\n val n = readInt\n val as = (0 until n).map((x) => (readLine, x + 1))\n val (has0, has1, hasl, zo, oz) = as.foldLeft((false, false, false, HashMap[String, Int](), HashMap[String, Int]())){\n case ((h0, h1, hl, zo, oz), (s, i)) => (s(0), s(s.length - 1)) match {\n case ('0', '0') => (true, h1, hl, zo, oz)\n case ('1', '1') => (h0, true, hl, zo, oz)\n case ('1', '0') => if (zo.contains(s.reverse)){\n (h0, h1, true, zo - s.reverse, oz)\n }\n else {\n (h0, h1, hl, zo, oz + (s -> i))\n }\n case ('0', '1') => if (oz.contains(s.reverse)){\n (h0, h1, true, zo, oz - s.reverse)\n } else {\n (h0, h1, hl, zo + (s -> i), oz)\n }\n case _ => throw new Exception(\"\")\n }\n }\n if (zo.size == 0 && oz.size == 0) {\n if (hasl || ((has0 && !has1) || (!has0 && has1))) {\n println(0)\n println(\"\")\n } else {\n println(-1)\n }\n }\n val total = zo.size + oz.size\n val (s1, s2) = (total / 2, total - (total / 2))\n val (k, il) = if (zo.size < oz.size) {\n (oz.size - s2, oz.values.take(oz.size - s2))\n } else {\n (zo.size - s2, zo.values.take(zo.size - s2))\n }\n println(k)\n println(il.mkString(\" \"))\n }\n }"}, {"source_code": "import scala.collection.mutable\n\nobject D {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n for (_ <- 1 to t) {\n val n = nextInt\n val have = mutable.Map.empty[String, Int]\n var have00, have11, haveMixed = false\n var i = 1\n while (i <= n) {\n val s = nextLine\n val l = s.length - 1\n if (s(0) == '0' && s(l) == '0') have00 = true\n else if (s(0) == '1' && s(l) == '1') have11 = true\n else {\n haveMixed = true\n val rev = s.reverse\n if (have.contains(rev)) have -= rev\n else have += s -> i\n }\n i += 1\n }\n if (have00 && have11 && !haveMixed) out.println(-1)\n else {\n val need = have.size / 2\n out.println(need)\n out.println(have.values.toIterator.take(need).mkString(\" \"))\n }\n }\n\n out.println()\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "src_uid": "128fb67bf707590cb1b60bceeb7ce598"} {"source_code": "\nimport java.util.StringTokenizer\n\nobject problemB {\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val reader = new StringTokenizer(scala.io.StdIn.readLine(), \" \")\n var itsUp = true\n var prev = reader.nextToken().toInt\n var hasAnswer = true\n (1 until n).takeWhile { _ =>\n val current = reader.nextToken().toInt\n if (itsUp) {\n itsUp = current > prev\n } else {\n hasAnswer = hasAnswer && current < prev\n }\n prev = current\n hasAnswer\n }\n println(if (hasAnswer) \"YES\" else \"NO\")\n }\n}\n", "positive_code": [{"source_code": "//package codeforces.contest1197\n\nobject Pillars {\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val seqWithIndex: Array[(Int, Int)] = io.StdIn.readLine().split(\" \").map(_.toInt).zipWithIndex\n\n val (maxValue, index) = seqWithIndex.maxBy(_._1)\n\n val seq = seqWithIndex.map(_._1)\n\n def loop(top: Int, l: Int, r: Int): Boolean = {\n val lProspect = if (l >= 0) Some(seq(l)) else None\n val rProspect = if (r < n) Some(seq(r)) else None\n\n (lProspect, rProspect) match {\n case (Some(ll), Some(rr)) if ll < top && rr < top && ll != rr =>\n if (ll > rr) loop(ll, l - 1, r) else loop(rr, l, r + 1)\n case (Some(ll), None) if ll < top =>\n loop(ll, l - 1, n)\n case (None, Some(rr)) if rr < top =>\n loop(rr, -1, r + 1)\n case (None, None) =>\n true\n case _ =>\n false\n }\n }\n\n println(if (loop(maxValue, index - 1, index + 1)) \"YES\" else \"NO\")\n }\n\n}\n"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val p = A.indexWhere(_ == N)\n var ok = true\n var i = p - 1\n while(i >= 0) {\n ok &&= A(i + 1) > A(i) // 単調増加\n i -= 1\n }\n i = p + 1\n while(i < N) {\n ok &&= A(i) < A(i - 1) // 単調減少\n i += 1\n }\n if (ok) out.println(\"YES\")\n else out.println(\"NO\")\n }\n}"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nobject problemB {\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val reader = new StringTokenizer(scala.io.StdIn.readLine(), \" \")\n var itsUp = true\n var prev = reader.nextToken().toInt\n var hasAnswer = true\n (1 until n).takeWhile { _ =>\n val current = reader.nextToken().toInt\n if (itsUp) {\n val change = current < prev\n if (change) {\n prev = current\n itsUp = false\n }\n } else {\n hasAnswer = hasAnswer && current <= prev\n prev = current\n }\n hasAnswer\n }\n println(if (hasAnswer) \"YES\" else \"NO\")\n }\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject problemB {\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val reader = new StringTokenizer(scala.io.StdIn.readLine(), \" \")\n var itsUp = true\n var prev = reader.nextToken().toInt\n var hasAnswer = true\n (1 until n).takeWhile { _ =>\n val current = reader.nextToken().toInt\n if (itsUp) {\n val change = current <= prev\n if (change) {\n prev = current\n itsUp = false\n }\n } else {\n hasAnswer = hasAnswer && current < prev\n prev = current\n }\n hasAnswer\n }\n println(if (hasAnswer) \"YES\" else \"NO\")\n }\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject problemB {\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val reader = new StringTokenizer(scala.io.StdIn.readLine(), \" \")\n var itsUp = true\n var prev = reader.nextToken().toInt\n var hasAnswer = true\n (1 until n).takeWhile { _ =>\n val current = reader.nextToken().toInt\n if (itsUp) {\n val change = current < prev\n if (change) {\n prev = current\n itsUp = false\n }\n } else {\n hasAnswer = hasAnswer && current < prev\n prev = current\n }\n hasAnswer\n }\n println(if (hasAnswer) \"YES\" else \"NO\")\n }\n}\n"}], "src_uid": "12abfbe7118868a0b1237489b5c92760"} {"source_code": "import scala.collection._\n\nobject A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs = readLongs(n)\n val (evens, odds) = xs.partition(_ % 2 == 0)\n\n val evensSum = evens.sum\n val oddsSum = if (odds.size % 2 == 1) odds.sorted.drop(1).sum else odds.sum\n val res = evensSum + oddsSum\n \n println(res)\n}\n", "positive_code": [{"source_code": "/**\n * Created by octavian on 31/01/2016.\n */\nobject Wet {\n\n def main(args: Array[String]) {\n //System.setIn(new FileInputStream(\"./src/wet.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"./src/wet.out\")))\n\n val n = readInt()\n val numbers : Array[Int] = readLine.split(\" \").map(_.toInt).sortWith(_ < _)\n\n var undesired = -1\n if(oddOdds(numbers)) {\n undesired = firstOdd(numbers)\n }\n\n var sum: BigInt = 0\n for(i <- 0 until numbers.length) {\n if(i != undesired) {\n sum += numbers(i)\n }\n }\n\n println(sum)\n }\n\n def oddOdds(numbers: Array[Int]): Boolean = {\n var odds = 0\n for(i <- 0 until numbers.length) {\n if(numbers(i) % 2 == 1) {\n odds += 1\n }\n }\n return(odds % 2 == 1)\n }\n\n def firstOdd(numbers: Array[Int]): Int = {\n for(i <- 0 until numbers.length) {\n if(numbers(i) % 2 == 1) {\n return i\n }\n }\n return 0\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) {\n val n = StdIn.readInt()\n val a = StdIn.readLine().split(\" \").map(_.toLong)\n val odd = a.filter((v) => v % 2 == 1)\n val even = a.filter((v) => v % 2 == 0)\n println(even.sum + odd.sum - (if (odd.length % 2 == 1) odd.min else 0))\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toLong)\n val (even, odd) = data.partition(_ % 2 == 0)\n println(even.sum + odd.sum - (if (odd.length % 2 == 0) 0 else odd.min))\n}"}, {"source_code": "object A621 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readLongs(n).sortBy(identity)\n if(input.exists(_%2 == 0) || (input.length > 1 && input(0)%2 == 1)) {\n var sum = input.sum\n var i = 0\n while (i < n && sum % 2 != 0) {\n if(input(i)%2 == 1)\n sum -= input(i)\n i += 1\n }\n println(sum)\n } else {\n println(\"0\")\n }\n }\n}"}, {"source_code": "import java.io._\nimport java.util.InputMismatchException\n\nobject Task {\n\n def solve(in: InputReader, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val a = Array.fill(n) { in.nextLong() }\n val s = a.sum\n val answer = if (s % 2 == 0) s else s - a.view.filter(_ % 2 == 1).min\n out.println(answer)\n }\n\n def main(args: Array[String]) {\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n in.close()\n out.close()\n }\n}\n\nclass InputReader(val inputStream: InputStream) {\n val buf = new Array[Byte](1 << 16)\n var curChar = 0\n var numChars = 0\n\n def read(): Int = {\n if (numChars == -1) {\n throw new InputMismatchException()\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => throw new InputMismatchException()\n }\n if (numChars <= 0)\n return -1\n }\n curChar += 1\n buf(curChar - 1)\n }\n\n def peek(): Int = {\n if (numChars == -1) {\n return -1\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => return -1\n }\n if (numChars <= 0)\n return -1\n }\n buf(curChar)\n }\n\n def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n\n def nextInt(): Int = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextLong(): Long = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0l\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def next(): String = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n val res = new StringBuilder()\n do {\n res += c.toChar\n c = read()\n } while(!isSpaceChar(c))\n res.toString()\n }\n\n def nextChar(): Char = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n c.toChar\n }\n\n //noinspection AccessorLikeMethodIsEmptyParen\n def hasNext(): Boolean = {\n var value = peek()\n do {\n read()\n value = peek()\n } while (isSpaceChar(value) && value != -1)\n value != -1\n }\n\n def rawNextLine(): String = {\n val builder = new StringBuilder\n var c = read()\n while (c != '\\n' && c != -1) {\n if (c != '\\r')\n builder += c.toChar\n c = read()\n }\n builder.toString()\n }\n\n def nextLine(): String = {\n var s = rawNextLine()\n while (s.trim().length == 0) s = rawNextLine()\n s\n }\n\n def nextDouble(): Double = {\n next().toDouble\n }\n\n def close(): Unit = {\n inputStream.close()\n }\n}\n"}, {"source_code": "// So you like object Task\nimport java.io.{IOException, InputStream, PrintWriter}\nimport java.util.InputMismatchException\n\n/**\n * Created with IntelliJ IDEA.\n * User: xie\n * Date: 2/6/16\n * Time: 2:03 PM\n */\nobject Task {\n\n def solve(in: InputReader, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val a = Array.fill(n) { in.nextLong() }\n val s = a.sum\n val answer = if (s % 2 == 0) s else s - a.view.filter(_ % 2 == 1).min\n out.println(answer)\n }\n\n def main(args: Array[String]) {\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n in.close()\n out.close()\n }\n}\n\nclass InputReader(val inputStream: InputStream) {\n val buf = new Array[Byte](1 << 16)\n var curChar = 0\n var numChars = 0\n\n def read(): Int = {\n if (numChars == -1) {\n throw new InputMismatchException()\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => throw new InputMismatchException()\n }\n if (numChars <= 0)\n return -1\n }\n curChar += 1\n buf(curChar - 1)\n }\n\n def peek(): Int = {\n if (numChars == -1) {\n return -1\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => return -1\n }\n if (numChars <= 0)\n return -1\n }\n buf(curChar)\n }\n\n def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n\n def nextInt(): Int = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextLong(): Long = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0l\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def next(): String = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n val res = new StringBuilder()\n do {\n res += c.toChar\n c = read()\n } while(!isSpaceChar(c))\n res.toString()\n }\n\n def nextChar(): Char = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n c.toChar\n }\n\n //noinspection AccessorLikeMethodIsEmptyParen\n def hasNext(): Boolean = {\n var value = peek()\n do {\n read()\n value = peek()\n } while (isSpaceChar(value) && value != -1)\n value != -1\n }\n\n def rawNextLine(): String = {\n val builder = new StringBuilder\n var c = read()\n while (c != '\\n' && c != -1) {\n if (c != '\\r')\n builder += c.toChar\n c = read()\n }\n builder.toString()\n }\n\n def nextLine(): String = {\n var s = rawNextLine()\n while (s.trim().length == 0) s = rawNextLine()\n s\n }\n\n def nextDouble(): Double = {\n next().toDouble\n }\n\n def close(): Unit = {\n inputStream.close()\n }\n}\n"}, {"source_code": "import io.StdIn._\nimport scala.collection.mutable._\n\nobject Solution {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n def main(args: Array[String]) {\n\n val n = readLine().toInt\n val a = readInts(n)\n\n var res:Long = 0\n var firstOdd: Long = 0\n a.sorted(Ordering[Int].reverse).foreach { v =>\n if (v % 2 == 0) res += v\n else {\n if (firstOdd == 0) firstOdd = v\n else {\n res += firstOdd + v\n firstOdd = 0\n }\n }\n }\n\n println(res)\n\n // Console.withOut(new java.io.BufferedOutputStream(Console.out))\n // println(res.mkString(\"\\n\"))\n // Console.flush\n }\n}"}, {"source_code": "import scala.io.Source\n\n/**\n * Created by yanluchen on 16/3/14.\n */\n\nobject A extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val row = in.next().split(\" \").map(_.toLong)\n // val (even,odd) = row.partition(_ % 2==0)\n val odd = row.filter(_ % 2 != 0)\n val ans = row.sum - (if (odd.length % 2 == 0) 0 else odd.min)\n println(ans)\n}"}], "negative_code": [], "src_uid": "adb66b7b22d70bb37cb625d531d8865f"} {"source_code": "\n\nimport java.util.Scanner\nimport scala.annotation.tailrec\n\nobject Main {\n val L = \"<{[(\"\n val R = \">}])\"\n def main(args: Array[String]) {\n val scan = new Scanner(System.in)\n val inStr = scan.nextLine()\n scan.close()\n\n val res = Process(inStr,0,Nil,0,0)\n if(res<0){\n print(\"Impossible\")\n }else{\n print(res)\n }\n }\n\n @tailrec\n def Process(str: String, i: Int, p: List[Int], f:Int,res: Int): Int = {\n if (i >= str.length || res < 0) {\n if(f==0) res else -1\n } else {\n if(L.contains(str(i))){\n Process(str,i+1,L.indexOf(str(i))::p,f+1,res+1)\n }else{\n if(p.isEmpty){\n -1\n }else{\n if(p.head == R.indexOf(str(i))){\n Process(str,i+1,p.drop(1),f-1,res-1)\n }else{\n Process(str,i+1,p.drop(1),f-1,res)\n }\n }\n }\n }\n }\n}", "positive_code": [{"source_code": "import util.control.Breaks._\nimport scala.collection.mutable.Stack\n\nobject brackets {\n def main(args: Array[String]) {\n var ans = 0\n val left = \"<{[(\"\n val right = \">}])\"\n\n val s = scala.io.StdIn.readLine\n var stack = new Stack[Char]\n breakable {\n s.foreach { c =>\n if (left.contains(c)) {\n stack.push(c)\n } else if (right.contains(c)) {\n val pos = right.indexOf(c)\n if (stack.isEmpty) {\n ans = -1\n break\n }\n var tmp = stack.pop\n if (tmp != left(pos)) ans+=1\n }\n //stack.push(_)\n }\n }\n if (ans == -1 || !stack.isEmpty) println(\"Impossible\")\n else println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "import util.control.Breaks._\nimport scala.collection.mutable.Stack\n\nobject brackets {\n def main(args: Array[String]) {\n var ans = 0\n val left = \"<{[(\"\n val right = \">}])\"\n\n val s = scala.io.StdIn.readLine\n var stack = new Stack[Char]\n breakable {\n s.foreach { c =>\n if (left.contains(c)) {\n stack.push(c)\n } else if (right.contains(c)) {\n val pos = right.indexOf(c)\n if (stack.isEmpty) {\n ans = -1\n break\n }\n var tmp = stack.pop\n if (tmp != left(pos)) ans+=1\n }\n //stack.push(_)\n }\n }\n if (ans == -1) println(\"Impossible\")\n else println(ans)\n }\n}\n"}, {"source_code": "\n\nimport java.util.Scanner\nimport scala.annotation.tailrec\n\nobject Main {\n val L = \"<{[(\"\n val R = \">}])\"\n def main(args: Array[String]) {\n val scan = new Scanner(System.in)\n val inStr = scan.nextLine()\n scan.close()\n\n val res = Process(inStr,0,Nil,0)\n if(res<0){\n print(\"Impossible\")\n }else{\n print(res)\n }\n }\n\n @tailrec\n def Process(str: String, i: Int, p: List[Int], res: Int): Int = {\n if (i >= str.length || res < 0) {\n res\n } else {\n if(L.contains(str(i))){\n Process(str,i+1,L.indexOf(str(i))::p,res+1)\n }else{\n if(p.isEmpty){\n -1\n }else{\n if(p.head == R.indexOf(str(i))){\n Process(str,i+1,p.drop(1),res-1)\n }else{\n Process(str,i+1,p.drop(1),res)\n }\n }\n }\n }\n }\n}"}], "src_uid": "4147fef7a151c52e92c010915b12c06b"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n println(data.sorted.foldLeft(Set.empty[Int]) {\n case (set, a) if a % k != 0 => set + a\n case (set, a) if !set.contains(a / k) => set + a\n case (set, a) => set\n }.size)\n}", "positive_code": [{"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\nimport scala.io.StdIn._\n\nobject Main {\n val scanner = new Scanner(System.in)\n def main(args: Array[String]): Unit = {\n val Array(n, k) = scanner.nextLine().split(\" \").map(_.toInt)\n var v: Vector[Int] = Vector[Int]()\n for(i <- 1 to n) {\n val temp = scanner.nextInt()\n v = v :+ temp\n }\n v = v.sorted\n val s = mutable.HashSet[Int]()\n v.foreach(p => {\n if ((p%k!=0) || !s.contains(p/k)) {\n s.add(p)\n }\n })\n println(s.size)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C168A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C168A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val k = ni()\n\n val a = na(n).toIndexedSeq.sorted\n val hm = new mutable.HashMap[Int, Boolean]()\n var count = 0\n REP(n) { i =>\n if(a(i) % k == 0) {\n val v = a(i) / k\n if(!hm.contains(v)) {\n count+=1\n hm(a(i)) = true\n }\n } else {\n count+=1\n hm(a(i)) = true\n }\n }\n out.println(count)\n }\n}\n"}, {"source_code": "import collection.mutable.Queue\nimport java.util.Scanner\nimport java.io._\nimport scala.io.Source\n\nobject test6 extends App {\n val Array(n,k)=readLine.split(\" \").map(_.toInt)\n val a=readLine.split(\" \").map(_.toLong).sorted\n val set1=a.toSet\n val set2=collection.mutable.Set[Long]()\n \n a.foreach(i=>{\n if(!set2.contains(i)){\n if(i!=i*k && set1.contains(i*k)) set2+=i*k\n }\n })\n \n println(set1.size-set2.size)\n \n} "}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n println(data.sorted.foldLeft(Set.empty[Int]) {\n case (set, a) if a % k == 0 && !set.contains(a / k) => set + a\n case (set, a) => set\n }.size)\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C168A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C168A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val k = ni().toLong\n\n a = na(n).toIndexedSeq.sorted\n var mx = -1\n REP(n) { i =>\n var from = i\n var count = 1\n var target = a(from) * k\n while (from < n) {\n val id = bs(from, n-1, target)\n count += (id - from)\n from = id + 1\n target = a(id) * k\n }\n if(mx < count) mx = count\n }\n out.println(mx)\n }\n\n var a: IndexedSeq[Int] = _\n\n def bs(from: Int, to: Int, v: Long): Int = {\n var l = from\n var r = to\n\n while (r - l > 1) {\n val m = l + (r - l) / 2\n if(a(m) >= v) r = m-1\n else l = m\n }\n if(a(r) >= v) l\n else r\n }\n}\n"}, {"source_code": "import collection.mutable.Queue\nimport java.util.Scanner\nimport java.io._\nimport scala.io.Source\n\nobject test6 extends App {\n val Array(n,k)=readLine.split(\" \").map(_.toInt)\n val a=readLine.split(\" \").map(_.toLong).sorted\n val set1=a.toSet\n val set2=collection.mutable.Set[Long]()\n \n a.foreach(i=>{\n if(!set2.contains(i)){\n if(set1.contains(i*k)) set2+=i*k\n }\n })\n \n println(set1.size-set2.size)\n \n} "}, {"source_code": "import collection.mutable.Queue\nimport java.util.Scanner\nimport java.io._\nimport scala.io.Source\n\nobject test6 extends App {\n val Array(n,k)=readLine.split(\" \").map(_.toInt)\n val a=readLine.split(\" \").map(_.toInt).sorted\n val set1=a.toSet\n val set2=collection.mutable.Set[Int]()\n \n a.foreach(i=>{\n if(!set2.contains(i)){\n if(set1.contains(i*k)) set2+=i*k\n }\n })\n \n println(set1.size-set2.size)\n \n} "}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\nimport scala.io.StdIn._\n\nobject Main {\n val scanner = new Scanner(System.in)\n def main(args: Array[String]): Unit = {\n val Array(n, k) = scanner.nextLine().split(\" \").map(_.toInt)\n var v: Vector[Int] = Vector[Int]()\n for(i <- 1 to n) {\n val temp = scanner.nextInt()\n v = v :+ temp\n }\n v = v.sorted\n val s = mutable.HashSet[Int]()\n v.foreach(p => {\n if (!s.contains(p/k)) {\n s.add(p)\n }\n })\n println(s.size)\n }\n}\n"}], "src_uid": "4ea1de740aa131cae632c612e1d582ed"} {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P278A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val d = Array.fill(N)(sc.nextInt)\n val s, t = sc.nextInt\n\n val answer = {\n val d0 = {\n val s0 = s min t\n val t0 = s max t\n\n for (i <- s0 - 1 until t0 - 1)\n yield d(i)\n }.sum\n val d1 = d.sum - d0\n d0 min d1\n }\n\n out.println(answer)\n out.close\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\nobject A extends App {\n val n = readLine.toInt\n val t = for (s <- readLine.split(\" \")) yield s.toInt\n val Array(_s,_g) = for(s <- readLine.split(\" \")) yield s.toInt - 1\n\n def srt(a: Int, b: Int) = { if(a < b) (a,b) else (b,a) }\n val (s,g) = srt(_s, _g)\n\n def solve1(i: Int): Int = {\n if(i == g) 0\n else t(i) + solve1(i+1)\n }\n def solve2(i: Int): Int = {\n if(i == g) t(i)\n else t(i) + solve2((i-1+n)%n)\n }\n val (res,_) = srt(solve1(s),solve2((s-1+n)%n))\n println(res)\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _278A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt).toArray\n val s = next.toInt - 1\n val t = next.toInt - 1\n if (s == t) println(0)\n else {\n def f(x: Int): Int =\n if (x == t) 0\n else f((x + 1) % n) + a(x)\n\n def g(x: Int): Int =\n if (x == t) 0\n else g((x + n - 1) % n) + a((x + n - 1) % n)\n\n println(f(s) min g(s))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val d = in.next().split(\" \").map(_.toInt)\n val Array(s, t) = in.next().split(\" \").map(_.toInt - 1).sorted\n val n1 = d.slice(s, s + t - s).sum\n val n2 = d.take(s).sum + d.drop(t).sum\n println(Math.min(n1, n2))\n\n}\n"}, {"source_code": "object A278 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val dist = readInts(n)\n var Array(s, t) = readInts(2)\n var clockWise = 0\n if (t >= s) {\n var loc = s\n while (loc != t) {\n clockWise += dist(loc - 1)\n loc += 1\n }\n } else {\n var loc = s\n while (loc != n + 1) {\n clockWise += dist(loc - 1)\n loc += 1\n }\n loc = 1\n while (loc != t) {\n clockWise += dist(loc - 1)\n loc += 1\n }\n }\n var antiClockWise = 0\n var temp = s\n s = t\n t = temp\n if (t >= s) {\n var loc = s\n while (loc != t) {\n antiClockWise += dist(loc - 1)\n loc += 1\n }\n } else {\n var loc = s\n while (loc != n + 1) {\n antiClockWise += dist(loc - 1)\n loc += 1\n }\n loc = 1\n while (loc != t) {\n antiClockWise += dist(loc - 1)\n loc += 1\n }\n }\n println(math.min(clockWise, antiClockWise))\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n val n = readInt\n val a = readInts\n val Array(s, t) = readInts\n val sum = a.zip(1 to n).filter {\n case (_, pos) => pos >= s.min(t) && pos < s.max(t)\n }.map(_._1).sum\n def ans = sum.min(a.sum - sum)\n\n def main(args: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val num = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val ind = readLine().split(\" \").map(_.toInt).sorted\n val direct = a.drop(ind(0) - 1).take(ind(1) - ind(0)).sum\n val indirect = a.sum - direct\n println(direct.min(indirect))\n }\n}"}, {"source_code": "import Array._\n\nobject main extends App with fastIO {\n \n var Array(n) = readLine split(\" \") map(_.toInt)\n var a = readLine split(\" \") map(_.toInt)\n var Array(s, t) = readLine split (\" \") map(_.toInt) sorted\n \n val value = a.drop(s - 1).take(t - s).sum\n println((a.sum - value) min value)\n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}"}, {"source_code": "\nimport java.util.Scanner;\nobject runner {\ndef main(args:Array[String]){\nvar sc =new Scanner(System.in);\n var a=sc.nextInt();\n var i=0;\n val mas=new Array[Int](a);\n var sum=0;\n while(il){var k=j;j=l;l=k;}\n var x=0;\n if(j!=l){\n while(jpath){\n sum=path;\n }\n}\nprintln(sum);\n}\n}"}, {"source_code": "\nobject runner {\ndef main(args:Array[String]){\nvar liner=readInt();\nvar read=readLine().split(\" \");\nvar re=readLine().split(\" \");\nvar first=re(0).toInt;\nvar second=re(1).toInt;\nvar sum=0;\nif(firstpath){\n sum=path;\n }\n}\n\n}\n\n\nprintln(sum);\n}\n}"}], "src_uid": "22ef37041ebbd8266f62ab932f188b31"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val (l, r) = (1 to n).foldLeft(-2l * 1E9.toLong, 2l * 1E9.toLong) {\n case ((left, right), _) if left > right => (left, right)\n case ((left, right), _) =>\n in.next().split(' ') match {\n case Array(\">\", b, \"N\") => (left, Math.min(right, b.toLong))\n case Array(\"<=\", b, \"Y\") => (left, Math.min(right, b.toLong))\n case Array(\"<\", b, \"N\") => (Math.max(left, b.toLong), right)\n case Array(\">=\", b, \"Y\") => (Math.max(left, b.toLong), right)\n case Array(\">=\", b, \"N\") => (left, Math.min(right, b.toLong - 1))\n case Array(\"<\", b, \"Y\") => (left, Math.min(right, b.toLong - 1))\n case Array(\"<=\", b, \"N\") => (Math.max(left, b.toLong + 1), right)\n case Array(\">\", b, \"Y\") => (Math.max(left, b.toLong + 1), right)\n }\n }\n if (l > r)\n println(\"Impossible\")\n else\n println(l)\n}\n", "positive_code": [{"source_code": "object A extends App {\n\tval n = readInt()\n\n\tdef negOp(op: String) = op match {\n\t\tcase \">\" => \"<=\"\n\t\tcase \">=\" => \"<\"\n\t\tcase \"<\" => \">=\"\n\t\tcase \"<=\" => \">\"\n\t}\n\n\tdef guess(k: Int, mi: Int, ma: Int): Option[Int] = {\n\t\tif(mi > ma) None\n\t\telse if (k == 0) Some(mi)\n\t\telse {\n\t\t\tval line = readLine()\n\t\t\tval pat = \"\"\"(>|>=|<|<=)\\s(-?\\d+)\\s(Y|N)\"\"\".r\n\t\t\tval pat(op, num, ans) = line\n\t\t\tval op1 = if(ans == \"N\") negOp(op) else op\n\t\t\tval num1 = num.toInt\n\t\t\top1 match {\n\t\t\t\tcase \">\" => guess(k - 1, math.max(mi, num1 + 1), ma)\n\t\t\t\tcase \">=\" => guess(k - 1, math.max(mi, num1), ma)\n\t\t\t\tcase \"<\" => guess(k - 1, mi, math.min(ma, num1 - 1))\n\t\t\t\tcase \"<=\" => guess(k - 1, mi, math.min(ma, num1))\n\t\t\t}\n\t\t}\n\t}\n\n\tguess(n, -2000000000, 2000000000) match {\n\t\tcase Some(z) => println(z)\n\t\tcase None => println(\"Impossible\")\n\t}\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readLine().toInt\n var left = -2000000000\n var right = 2000000000\n for (i <- 1 to n) {\n val Array(sign, x_str, answer) = readLine().split(' ')\n val x = x_str.toInt\n sign match {\n case \">\" => {\n answer match {\n case \"Y\" => left = max(x + 1, left)\n case \"N\" => right = min(x, right)\n }\n }\n case \">=\" => {\n answer match {\n case \"Y\" => left = max(x, left)\n case \"N\" => right = min(x - 1, right)\n }\n }\n case \"<\" => {\n answer match {\n case \"Y\" => right = min(x - 1, right)\n case \"N\" => left = max(x, left)\n }\n }\n case \"<=\" => {\n answer match {\n case \"Y\" => right = min(x, right)\n case \"N\" => left = max(x + 1, left)\n }\n }\n }\n if (left > right) {\n println(\"Impossible\")\n return\n }\n }\n println(left)\n }\n\n def min(x: Int, y: Int) = if (x < y) x else y\n\n def max(x: Int, y: Int) = if (x > y) x else y\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readLine().toInt\n var left = -2000000001\n var right = 2000000001\n for (i <- 1 to n) {\n val Array(sign, x_str, answer) = readLine().split(' ')\n val x = x_str.toInt\n sign match {\n case \">\" => {\n answer match {\n case \"Y\" => left = max(x + 1, left)\n case \"N\" => right = min(x, right)\n }\n }\n case \">=\" => {\n answer match {\n case \"Y\" => left = max(x, left)\n case \"N\" => right = min(x - 1, right)\n }\n }\n case \"<\" => {\n answer match {\n case \"Y\" => right = min(x - 1, right)\n case \"N\" => left = max(x, left)\n }\n }\n case \"<=\" => {\n answer match {\n case \"Y\" => right = min(x, right)\n case \"N\" => left = max(x + 1, left)\n }\n }\n }\n if (left > right) {\n println(\"Impossible\")\n return\n }\n }\n println(left)\n }\n\n def min(x: Int, y: Int) = if (x < y) x else y\n\n def max(x: Int, y: Int) = if (x > y) x else y\n}\n"}, {"source_code": "object A extends App {\n\tval n = readInt()\n\n\tdef negOp(op: String) = op match {\n\t\tcase \">\" => \"<=\"\n\t\tcase \">=\" => \"<\"\n\t\tcase \"<\" => \">=\"\n\t\tcase \"<=\" => \">\"\n\t}\n\n\tdef guess(k: Int, mi: Int, ma: Int): Option[Int] = {\n\t\tif(mi > ma) None\n\t\telse if (k == 0) Some(mi)\n\t\telse {\n\t\t\tval line = readLine()\n\t\t\tval pat = \"\"\"(>|>=|<|<=)\\s(-?\\d+)\\s(Y|N)\"\"\".r\n\t\t\tval pat(op, num, ans) = line\n\t\t\tval op1 = if(ans == \"N\") negOp(op) else op\n\t\t\tval num1 = num.toInt\n\t\t\top1 match {\n\t\t\t\tcase \">\" => guess(k - 1, num1 + 1, ma)\n\t\t\t\tcase \">=\" => guess(k - 1, num1, ma)\n\t\t\t\tcase \"<\" => guess(k - 1, mi, num1 - 1)\n\t\t\t\tcase \"<=\" => guess(k - 1, mi, num1)\n\t\t\t}\n\t\t}\n\t}\n\n\tguess(n, -2000000000, 2000000000) match {\n\t\tcase Some(z) => println(z)\n\t\tcase None => println(\"Impossible\")\n\t}\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val (l, r) = (1 to n).foldLeft(-2l * 10E9.toLong, 2l * 10E9.toLong) {\n case ((left, right), _) if left > right => (left, right)\n case ((left, right), _) =>\n in.next().split(' ') match {\n case Array(\">\", b, \"N\") => (left, Math.min(right, b.toLong))\n case Array(\"<=\", b, \"Y\") => (left, Math.min(right, b.toLong))\n case Array(\"<\", b, \"N\") => (Math.max(left, b.toLong), right)\n case Array(\">=\", b, \"Y\") => (Math.max(left, b.toLong), right)\n case Array(\">=\", b, \"N\") => (left, Math.min(right, b.toLong - 1))\n case Array(\"<\", b, \"Y\") => (left, Math.min(right, b.toLong - 1))\n case Array(\"<=\", b, \"N\") => (Math.max(left, b.toLong + 1), right)\n case Array(\">\", b, \"Y\") => (Math.max(left, b.toLong + 1), right)\n }\n }\n if (l > r)\n println(\"Impossible\")\n else\n println(l)\n}\n"}], "src_uid": "6c6f29e1f4c951cd0ff15056774f897d"} {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable\n\n/**\n * Created by Kuang.Ru on 14-9-17.\n */\nobject A443 extends App {\n val sc = new Scanner(System.in)\n val letters = sc.nextLine()\n val letterSet = new mutable.HashSet[Char]()\n\n letters.toCharArray.foreach((c: Char) => {\n if (c <= 'z' && c >= 'a') {\n letterSet += c\n }\n })\n\n println(letterSet.size)\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n val rgx = \"\"\"\\w\"\"\".r\n val input = readLine().split(\"\")\n val chars = input.filter(rgx.pattern.matcher(_).matches())\n val ans = chars.toSet.size\n println(ans)\n}"}, {"source_code": "object Main extends App{\n val in=readLine\n println(in.filter(t => t >='a'&& t <='z').distinct.length)\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Task443A {\n\tdef main(args: Array[String]) {\n\t\tval s = StdIn.readLine()\n\t\tif (s.length == 2) println(0)\n\t\telse println(s.substring(1, s.length - 1).split(\", \").toSet.size)\n\t}\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n println(in.next().filter(t => t >= 'a' && t <= 'z').distinct.length)\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\nimport scala.util.Sorting._\nimport scala.math._\nimport scala.collection._\nimport java.util._\n\nobject HelloWorld {\n def main(args: Array[String]): Unit = {\n println(readLine.drop(1).dropRight(1).split(\",\").filter(t=>t.trim.length!=0).map(_.trim).toSet.size)\n }\n}"}, {"source_code": "object A443 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val input = scala.io.StdIn.readLine\n\n println(input.drop(1).dropRight(1).split(\", \").dropWhile(_.isEmpty).toSet.size)\n }\n}"}, {"source_code": "\nobject AntonAndLetters {\n\n\tdef main (args: Array[String]) {\n \t\tval scanner = new java.util.Scanner(System.in);\n \t\tval input = scanner.nextLine();\n \t\tval inputAsArray = input.split(Array(',', ' ', '}','{'));\n \t\tprintln(Math.max(0,inputAsArray.toSet.size-1));\n\t}\n}"}, {"source_code": "object Main extends App{\n val in=readLine\n println(in.filter(t => t >='a'&& t <='z').distinct.length)\n}"}, {"source_code": "object Main extends App {\n override def main(args: Array[String]) = {\n val cin = new java.util.Scanner(System.in)\n val str = cin.nextLine()\n def solve(c: Char, ans: Int): Int =\n if (c > 'z') ans\n else if (str.contains(c)) solve((c + 1).toChar, ans + 1)\n else solve((c + 1).toChar, ans)\n println(solve('a', 0))\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport Array._\n\nobject problem {\n\n def main(args: Array[String]) {\n val s = readLine.toString.replaceAll(\"[{}, ]\",\"\")\n println(s.distinct.size)\n }\n}"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject AntonLetters {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n \n def main(args: Array[String]) {\n val s = readLine\n if (s == \"{}\") println(\"0\") else \n println(s.tail.reverse.tail.reverse.split(\", \").toSet.size)\n \n \n }\n \n}"}, {"source_code": "object Main extends App{\n val in=readLine\n println(in.filter(t => t >='a'&& t <='z').distinct.length)\n}"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n println(StdIn.readLine().filter(t => t >= 'a' && t <= 'z' ).distinct.length)\n\n }\n\n\n}\n"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n println(StdIn.readLine().\n replace(\"{\",\"\").replace(\"}\", \"\").split(\", \").\n map(_.toCharArray).flatten.toSet.size)\n\n }\n\n\n}\n"}, {"source_code": "import java.io._\nimport util.control.Breaks._\n\nobject Solution extends App {\n val s = readLine.split(\"{}, \".toArray).filter(_!=\"\")\n \n println(s.toSet.size)\n}"}, {"source_code": "object t443a extends App {\n\n import java.io.{BufferedReader, InputStreamReader}\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n val input = br.readLine()\n val r = input.filterNot(_ == '{').filterNot(_ == '}').filterNot(_ == ',')\n if (r.isEmpty) println(0) else println(r.split(\" \").toList.toSet.size)\n\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\nimport scala.util.Sorting._\nimport scala.math._\nimport scala.collection._\nimport java.util._\n\nobject HelloWorld {\n def main(args: Array[String]): Unit = {\n println(readLine.drop(1).dropRight(1).split(\",\").map(_.trim).toSet.size)\n }\n}"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject AntonLetters {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n \n def main(args: Array[String]) {\n println(readLine.tail.reverse.tail.reverse.split(\", \").toSet.size)\n \n \n }\n \n}"}, {"source_code": "object t443a extends App {\n\n import java.io.{BufferedReader, InputStreamReader}\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n val input = br.readLine()\n println(input.filter(_ == '{').filter(_ == '}').split(\" \").toList.toSet.size)\n\n}"}, {"source_code": "object t443a extends App {\n\n import java.io.{BufferedReader, InputStreamReader}\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n val input = br.readLine()\n println(input.filterNot(_ == '{').filterNot(_ == '}').filterNot(_ == ',').split(\" \").toList.toSet.size)\n\n}"}, {"source_code": "object t443a extends App {\n\n import java.io.{BufferedReader, InputStreamReader}\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n val input = br.readLine()\n val r = input.filterNot(_ == '{').filterNot(_ == '}').filterNot(_ == ',')\n if (r.isEmpty) println(0) else r.split(\" \").toList.toSet.size\n\n}"}, {"source_code": "object t443a extends App {\n\n import java.io.{BufferedReader, InputStreamReader}\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n val input = br.readLine()\n println(input.split(\" \").toList.toSet.size - 2)\n\n}"}], "src_uid": "1cbbffd1941ed83b5f04e1ee33c77f61"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M, K, L = nl()\n val x = (L + K - 1) / M + 1\n if (x == 0 || BigInt(M) * x > N) {\n out.println(-1)\n } else {\n out.println(x)\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}", "positive_code": [{"source_code": "object CF_518_2_A {\n def solve(N: Long, // number of coin types\n M: Long, // number of friends\n K: Long, // how many types Ivan has\n L: Long // min number of new types\n ): Long = {\n val maxTypes = (N/M)*M\n val needed = K + L\n if (needed > maxTypes) -1\n else Utility.longCeil(needed, M)\n\n }\n \n def main(args: Array[String]) = {\n val io = new IO(System.in)\n val solution = solve(io.long, io.long, io.long, io.long)\n println(solution)\n }\n\n\n\n\n\n/// boilerplate utility methods: ///\n import java.util.Scanner\n class IO(sc: Scanner) {\n def this(i: java.io.InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s))\n def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data\n def collect[T](f: String => T) = {sc.nextLine().split(\" \").toVector.map(f)}\n def intSeq() = collect(_.toInt)\n def doubleSeq() = collect(_.toDouble)\n def int() = sc.nextInt()\n def long() = sc.nextLong()\n def double() = sc.nextDouble()\n }\n\n object Utility {\n def intCeil(a: Int, b: Int) = (a + b - 1) / b\n def longCeil(a: Long, b: Long) = (a + b - 1) / b\n }\n\n}"}], "negative_code": [], "src_uid": "886029b385c099b3050b7bc6978e433b"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next()\n val red = line.count(_ == 'r')\n val black = n - red\n val redOdd = line.indices.count(i => i % 2 == 1 && line(i) == 'r')\n val redEven = red - redOdd\n val blackOdd = line.indices.count(i => i % 2 == 1 && line(i) == 'b')\n val blackEven = black - blackOdd\n val redFirst = Math.max(redOdd, blackEven)\n val blackFirst = Math.max(blackOdd, redEven)\n println(Math.min(redFirst, blackFirst))\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\nobject ProblemB extends App {\n val n = readInt()\n val s = readLine().view.zipWithIndex\n\n val rb = s.foldLeft((0, 0))((acc, t) =>\n (if ((t._2 % 2 == 0 && t._1 == 'r') || t._2 % 2 == 1) acc._1 else acc._1 + 1,\n if ((t._2 % 2 == 1 && t._1 == 'b') || t._2 % 2 == 0) acc._2 else acc._2 + 1)\n )\n\n val rb2 = s.foldLeft((0, 0))((acc, t) =>\n (if ((t._2 % 2 == 0 && t._1 == 'b') || t._2 % 2 == 1) acc._1 else acc._1 + 1,\n if ((t._2 % 2 == 1 && t._1 == 'r') || t._2 % 2 == 0) acc._2 else acc._2 + 1)\n )\n\n val solution1 = math.abs(rb._1 - rb._2) + math.min(rb._1, rb._2)\n val solution2 = math.abs(rb2._1 - rb2._2) + math.min(rb2._1, rb2._2)\n println(math.min(solution1, solution2))\n}\n"}], "negative_code": [], "src_uid": "3adc75a180d89077aa90bbe3d8546e4d"} {"source_code": "\r\nobject Main {\r\n def main(args: Array[String]) = {\r\n val Array(n, q, k) = readLine().split(\"\\\\s+\").map(_.toInt)\r\n val a = readLine().split(\"\\\\s+\").map(_.toInt)\r\n for (i <- 1 to q){\r\n // val l = sc.nextInt()\r\n // val r = sc.nextInt()\r\n var Array(l, r) = readLine().split(\"\\\\s+\").map(_.toInt)\r\n l -= 1\r\n r -= 1\r\n val len = r - l + 1\r\n println((k - len) * 2 - (a(l) - 1) - (k - a(r)))\r\n // println(k - r + l)\r\n }\r\n }\r\n}", "positive_code": [{"source_code": "import java.io.BufferedReader\r\nimport java.io.ByteArrayInputStream\r\nimport java.io.InputStreamReader\r\n\r\nobject BReplaceandKeepSorted {\r\n def solve(k: Int, initList: Array[Int], s: Int, f: Int): Int = {\r\n if (s == f) return k - 1\r\n// var c = 0\r\n// for (i <- s until f - 1) {\r\n// c += (initList(i+1) - initList(i-1) - 2)\r\n// }\r\n// c + (initList(s) - 2) + (k + 1 - initList(f - 2) - 2)\r\n (f - s + 1) * (-2) + k + 1 + initList(f - 1) - initList(s-1)\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val file = new BufferedReader(new InputStreamReader(System.in))\r\n// val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(\r\n// (\"6 5 10\\n2 4 6 7 8 9\\n1 4\\n1 2\\n3 5\\n1 6\\n5 5\").getBytes)))\r\n val n::q::k::Nil = file.readLine.split(\" \").map(_.toInt).toList\r\n val as = file.readLine.split(\" \").map(_.toInt)\r\n var i = 0\r\n while (i < q) {\r\n val l::r::Nil = file.readLine.split(\" \").map(_.toInt).toList\r\n println(solve(k, as, l, r))\r\n i += 1\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "740d2aba32f69b8cfe8f7cb624621a63"} {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val as = Array.fill(n){ readInts(m) }\n var can = false\n\n for (i <- 0 until m) {\n for (j <- i + 1 until m) {\n var ok = true\n for (row <- as) {\n var cntWrong1, cntWrong2 = 0\n for (c <- 0 until m) {\n if (c != i && c != j && row(c) != c + 1) cntWrong1 += 1\n if (row(c) != c + 1) cntWrong2 += 1\n }\n if (!((cntWrong1 == 0 && cntWrong2 == 2) ||\n (cntWrong1 == 0 && cntWrong2 == 0) ||\n (cntWrong1 == 2 && cntWrong2 == 4 && row(i) == j + 1 && row(j) == i + 1) ||\n (cntWrong1 == 1 && cntWrong2 == 3))) ok = false\n //if (ok) println(i, j, row.mkString(\" \"), cntWrong1, cntWrong2)\n }\n if (ok) {\n can = true\n //println(i, j)\n }\n }\n }\n\n var ok = true\n for (row <- as) {\n var cntWrong = 0\n for (c <- 0 until m) {\n if (row(c) != c + 1) cntWrong += 1\n }\n if (cntWrong != 0 && cntWrong != 2) ok = false\n }\n if (ok) can = true\n\n println(if (can) \"YES\" else \"NO\")\n}\n", "positive_code": [{"source_code": "import java.io._\n\nobject ProblemB {\n def main(args: Array[String]): Unit = processStdInOut()\n\n def processStdInOut(): Unit = {\n val src = io.Source.fromInputStream(System.in)\n try {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out));\n try {\n val lines = src.getLines()\n processLines(lines, bw)\n } finally {\n bw.flush()\n bw.close()\n }\n } finally {\n src.close();\n }\n }\n\n // Standard code above, custom code below\n\n def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {\n\n val line = lines.next()\n val strings = line.split(' ')\n val n = strings(0).toInt\n val m = strings(1).toInt\n val table = Array.ofDim[Int](n, m)\n for (r <- 0 until n) {\n val row = lines.next()\n val entries = row.split(' ').map(_.toInt - 1) // i.e. make zero-based\n table(r) = entries\n }\n\n val hasSolution = solve(n, m, table)\n if (hasSolution) { bw.write(\"YES\") } else {bw.write(\"NO\") }\n bw.newLine()\n }\n\n def solve(n: Int, m: Int, table: Array[Array[Int]]): Boolean = {\n val indexCombinations = (1 until m).flatMap { col => (0 until col).map( (_, col)) }\n\n def isRowSorted(row: Array[Int]): Boolean = row.zipWithIndex.forall(p => p._1 == p._2)\n\n def swapEntriesInPlace(row: Array[Int], swap: (Int, Int)): Unit = {\n val (col1, col2) = swap\n val firstEntry = row(col1)\n row(col1) = row(col2)\n row(col2) = firstEntry\n }\n\n def isSortedAfterSwaps(row: Array[Int], swaps: (Int, Int)* ): Boolean = {\n val newRow = row.clone()\n swaps.foreach(swapEntriesInPlace(newRow, _))\n isRowSorted(newRow)\n }\n\n def columnSwapHasSolution(colSwap: (Int, Int)): Boolean = {\n def rowCanBeOrdered(rowIndex: Int): Boolean = {\n val rowPrior = table(rowIndex)\n def entriesCanBeSwapped(entrySwap: (Int, Int)): Boolean = {\n // Either do the column swap before or after:\n isSortedAfterSwaps(rowPrior, colSwap, entrySwap) ||\n isSortedAfterSwaps(rowPrior, entrySwap, colSwap)\n }\n // See if column swap is sufficient to reorder, else try swapping each combination of entries...\n val rowHasSolution = isSortedAfterSwaps(rowPrior, colSwap) ||\n indexCombinations.exists(entriesCanBeSwapped(_))\n rowHasSolution\n }\n val hasSolution = (0 until n).forall(rowCanBeOrdered)\n hasSolution\n }\n\n def isThereASolutionWithNoColumnSwap(): Boolean = {\n def rowCanBeOrdered(rowIndex: Int): Boolean = {\n val rowPrior = table(rowIndex)\n // See if row is already sorted, else try swapping each combination of entries...\n val rowHasSolution = isRowSorted(rowPrior) || indexCombinations.exists(isSortedAfterSwaps(rowPrior, _))\n rowHasSolution\n }\n val hasSolution = (0 until n).forall(rowCanBeOrdered)\n hasSolution\n }\n\n isThereASolutionWithNoColumnSwap() || indexCombinations.exists(columnSwapHasSolution)\n }\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _724B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n, m = read[Int]\n val table = Vector.fill(n)(read[Array, Int](m))\n val idealRow = (1 to m).toIndexedSeq\n\n def isOkay(i: Int, j: Int) = table forall { row =>\n row.swap(i, j)\n val ans = row.indices.count(k => row(k) != idealRow(k)) <= 2\n row.swap(j, i)\n ans\n }\n\n val f = Function.tupled(isOkay _)\n val ans = (m X m).exists(f)\n\n write(ans.toEnglish)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n def swap(i: Int, j: Int): Unit = {\n val t = a(i)\n a(i) = a(j)\n a(j) = t\n }\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, m) = readInts(2)\n val as = Array.fill(n){ readInts(m) }\n var can = false\n\n for (i <- 0 until m) {\n for (j <- i + 1 until m) {\n var ok = true\n for (row <- as) {\n var cntWrong = 0\n for (c <- 0 until m) {\n if (c != i && c != j && row(c) != c + 1) cntWrong += 1\n }\n if (cntWrong != 0 && cntWrong != 2 &&\n (cntWrong != 1 || row(i) == i + 1 || row(j) == j + 1)) ok = false\n }\n if (ok) can = true\n }\n }\n\n println(if (can) \"YES\" else \"NO\")\n}\n"}], "src_uid": "8ab4db92e595b6a0a4c020693c5f2b24"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport Math._\n\nobject Main {\n val in = new InputReader(System.in)\n val pw = new PrintWriter(System.out)\n\n def main (args: Array[String]){\n val n, r = in.next().toInt\n val x = new Array[Int](n+1)\n for (i <- 1 to n)\n x(i) = in.next().toInt\n\n\n //\n def calcY(x: Int, p: (Double, Double)): Double = { // retrun y\n val dia = 2 * r\n val (px, py) = p\n val hoge = x.toDouble - px\n sqrt(dia*dia - hoge*hoge) + py\n }\n\n val ans = new Array[Double](n+1)\n\n val centers = new Array[(Double, Double)](n+1)\n val axisX = new Array[Int](1000 + r + 1) // has Graph-number\n\n for(graphNum <- 1 to n) {\n val nowX: Int = x(graphNum)\n val xrange = (0 max (nowX - r)) to (nowX + r)\n\n var pos: (Double, Double) = (nowX, r)\n for (x <- xrange) {\n if (axisX(x) > 0){\n val viewGraph = axisX(x)\n val viewPos = centers(viewGraph)\n\n val nowY: Double = calcY(nowX, viewPos)\n if(nowY > pos._2)\n pos = (nowX, nowY)\n }\n }\n\n // post-process\n centers(graphNum) = pos\n for (x <- xrange) {\n axisX(x) = graphNum\n }\n ans(graphNum) = pos._2\n }\n\n\n for (i <- 1 to n-1) {\n pw.print(ans(i) + \" \")\n }\n pw.println(ans(n))\n pw.flush()\n }\n}\n\nclass InputReader(stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream))\n private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())\n def next(): String = {\n while (!tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine())\n }\n tokenizer.nextToken()\n }\n}\n", "positive_code": [{"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readDoubles(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toDouble) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, r) = readInts(2)\n val xs = readInts(n)\n\n val ys = Array.fill(n){ r.toDouble }\n\n def intersects(x1: Int, x2: Int): Boolean = {\n Math.abs(x1 - x2) <= 2 * r\n }\n\n def sqr(a: Double) = a * a\n\n def stopsAt(x1: Int, j: Int): Double = {\n val y0 = ys(j)\n val dY = Math.sqrt(sqr(2 * r) - sqr(x1 - xs(j)))\n y0 + dY\n }\n\n for (i <- 1 until n) {\n\n val stopYs = for {\n j <- 0 until i\n if intersects(xs(i), xs(j))\n } yield stopsAt(xs(i), j)\n\n ys(i) = if (stopYs.isEmpty) r.toDouble else stopYs.max\n }\n\n println(ys.mkString(\" \"))\n}\n"}, {"source_code": "object C extends App {\n val e = scala.math.pow(10, -6)\n\n val Array(n, r) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val x = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val R = 2.0 * r\n\n def y2(x1: Int, y1: Double, x2: Int): Double = {\n val t = scala.math.sqrt((R - x1 + x2) * (R + x1 - x2))\n (y1 - t) max (y1 + t)\n }\n\n def r(x: Int, a: Array[(Int, Double)]): Array[(Int, Double)] =\n a.filter(t => scala.math.abs(t._1 - x) <= R)\n\n def g(x: Array[Int], a: Array[(Int, Double)] = Array.empty): Array[Double] =\n if (x.isEmpty) a.map(_._2).reverse\n else {\n val y = r(x.head, a).map(t => y2(t._1, t._2, x.head))\n if (y.isEmpty) g(x.tail, (x.head, r.toDouble) +: a)\n else g(x.tail, (x.head, y.max) +: a)\n }\n\n println(g(x).mkString(\" \"))\n}\n"}, {"source_code": "object CF908C extends App {\n\n val sc = new java.util.Scanner(System.in)\n val discs, radius = sc.nextInt\n\n val result = append(0, Nil)\n\n println(result map (c => c._2) mkString \" \")\n\n def append(i: Int, circles: List[(Int, Double)]): List[(Int, Double)] = {\n\n if (i == discs) return circles\n val cs = append(i+1, circles)\n val nx = sc.nextInt\n if (cs.isEmpty) cs :+ (nx, radius.toDouble) else cs :+ (nx, findCircle(nx, cs))\n }\n\n def findCircle(x: Int, circles: List[(Int, Double)]): Double = {\n var result = radius.toDouble\n //println(\"X: \" + x)\n for (c <- circles.sortWith(_._2 > _._2)) {\n //println(\"X: %d Y:%f\".format(c._1, c._2))\n val xdiff = Math.abs(x - c._1)\n //println(\"XD: \" + xdiff)\n if (xdiff <= radius * 2){\n val ydiff = Math.sqrt(Math.pow(radius * 2, 2) - Math.pow(xdiff, 2))\n //println(\"YD: \" +ydiff)\n result = Math.max(result, c._2 + ydiff)\n }\n }\n return result\n }\n}\n"}], "negative_code": [{"source_code": "object CF908C extends App {\n\n val sc = new java.util.Scanner(System.in)\n val discs, radius = sc.nextInt\n\n val result = append(0, Nil)\n\n println(result map (c => c._2) mkString \" \")\n\n def append(i: Int, circles: List[(Int, Double)]): List[(Int, Double)] = {\n\n if (i == discs) return circles\n val cs = append(i+1, circles)\n val nx = sc.nextInt\n if (cs.isEmpty) cs :+ (nx, radius.toDouble) else cs :+ (nx, findCircle(nx, cs))\n }\n\n def findCircle(x: Int, circles: List[(Int, Double)]): Double = {\n //println(\"X: \" + x)\n for (c <- circles.sortWith(_._2 > _._2)) {\n //println(\"X: %d Y:%f\".format(c._1, c._2))\n val xdiff = Math.abs(x - c._1)\n //println(\"XD: \" + xdiff)\n if (xdiff <= radius * 2){\n val ydiff = Math.sqrt(Math.pow(radius * 2, 2) - Math.pow(xdiff, 2))\n //println(\"YD: \" +ydiff)\n return c._2 + ydiff\n }\n }\n 0.0 // something wrong\n }\n}\n"}], "src_uid": "3cd019d1016cb3b872ea956c312889eb"} {"source_code": "import scala.collection.mutable\n\nobject D {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n = nextInt\n val cs = Array.fill(3)(nextLongs(n))\n val adjBuilders = Array.fill(n){new mutable.ArrayBuilder.ofInt}\n for (_ <- 2 to n) {\n val u, v = nextInt - 1\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n val adjs = adjBuilders.map(_.result())\n var bad = false\n\n val depths = Array.ofDim[Int](n)\n def dfs(u: Int, prev: Int, depth: Int): Unit = {\n depths(u) = depth % 3\n var i = 0\n if (adjs(u).length > 2) bad = true\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v != prev) dfs(v, u, depth + 1)\n i += 1\n }\n }\n\n val leaf = adjs.indexWhere(_.length == 1)\n dfs(leaf, -1, 0)\n\n if (bad) out.println(-1)\n else {\n //println(depths.mkString(\" \"))\n val colors = Array(0, 1, 2)\n var minCost = Long.MaxValue\n var bestColoring = colors\n for (coloring <- colors.permutations) {\n var cost = 0L\n for (i <- 0 until n) {\n cost += cs(coloring(depths(i)))(i)\n }\n if (cost < minCost) {\n minCost = cost\n bestColoring = coloring\n }\n }\n\n val res = depths.map(bestColoring(_) + 1)\n\n out.println(minCost)\n out.println(res.mkString(\" \"))\n }\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "//package codeforces.contest1244\n\nobject PaintTheTree {\n\n type Graph = Map[Int, Set[Int]]\n\n def update(graph: Graph, x: Int, y: Int): Graph = {\n val setX: Set[Int] = graph.withDefaultValue(Set.empty)(x)\n val setY: Set[Int] = graph.withDefaultValue(Set.empty)(y)\n graph + (x -> (setX + y)) + (y -> (setY + x))\n }\n\n def linearize(graph: Graph): List[Int] = {\n\n @scala.annotation.tailrec\n def loop(node: Int, acc: List[Int]): List[Int] = {\n\n acc match {\n case Nil => loop(graph(node).head, node :: acc)\n case h :: _ =>\n graph(node).find(_ != h) match {\n case Some(next) => loop(next, node :: acc)\n case None => node :: acc\n }\n }\n }\n\n loop(graph.find(_._2.size == 1).get._1, Nil)\n }\n\n def expandListToSize(n: Int, ls: List[Int]): List[Int] = {\n val size = ls.length\n (1 to n / size + 1).toList.flatMap(_ => ls).take(n)\n }\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val colorA, colorB, colorC = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val getColor = Seq(colorA, colorB, colorC)\n\n val graph: Graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { (acc, _) =>\n val Array(x, y) = io.StdIn.readLine.split(\" \").map(_.toInt)\n update(acc, x, y)\n }\n\n def colorToValue(color: Int, node: Int): Long = getColor(color - 1)(node - 1).toLong\n\n println {\n if (graph.values.forall(_.size <= 2)) {\n\n val seq = linearize(graph)\n\n val solutionList = List(\n expandListToSize(n, List(1, 2, 3)),\n expandListToSize(n, List(1, 3, 2)),\n expandListToSize(n, List(2, 1, 3)),\n expandListToSize(n, List(2, 3, 1)),\n expandListToSize(n, List(3, 2, 1)),\n expandListToSize(n, List(3, 1, 2))\n )\n\n val (min, list) = solutionList\n .map { ls =>\n val zipped = ls.zip(seq)\n (zipped.map((colorToValue _).tupled).sum, zipped.sortBy(_._2).map(_._1))\n }\n .minBy(_._1)\n\n min + \"\\n\" + list.mkString(\" \")\n } else -1\n }\n\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contest1244\n\nobject PaintTheTree {\n\n type Graph = Map[Int, Set[Int]]\n\n def update(graph: Graph, x: Int, y: Int): Graph = {\n val setX: Set[Int] = graph.withDefaultValue(Set.empty)(x)\n val setY: Set[Int] = graph.withDefaultValue(Set.empty)(y)\n graph + (x -> (setX + y)) + (y -> (setY + x))\n }\n\n def linearize(graph: Graph): List[Int] = {\n\n @scala.annotation.tailrec\n def loop(node: Int, acc: List[Int]): List[Int] = {\n\n acc match {\n case Nil => loop(graph(node).head, node :: acc)\n case h :: _ =>\n graph(node).find(_ != h) match {\n case Some(next) => loop(next, node :: acc)\n case None => node :: acc\n }\n }\n }\n\n loop(graph.find(_._2.size == 1).get._1, Nil)\n }\n\n def expandListToSize(n: Int, ls: List[Int]): List[Int] = {\n val size = ls.length\n (1 to n / size + 1).toList.flatMap(_ => ls).take(n)\n }\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val colorA, colorB, colorC = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val getColor = Seq(colorA, colorB, colorC)\n\n val graph: Graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { (acc, _) =>\n val Array(x, y) = io.StdIn.readLine.split(\" \").map(_.toInt)\n update(acc, x, y)\n }\n\n def colorToValue(color: Int, node: Int) = getColor(color - 1)(node - 1)\n\n println {\n if (graph.values.forall(_.size <= 2)) {\n\n val seq = linearize(graph)\n\n val solutionList = List(\n expandListToSize(n, List(1, 2, 3)),\n expandListToSize(n, List(1, 3, 2)),\n expandListToSize(n, List(2, 1, 3)),\n expandListToSize(n, List(2, 3, 1)),\n expandListToSize(n, List(3, 2, 1)),\n expandListToSize(n, List(3, 1, 2))\n )\n\n val (min, list) = solutionList\n .map { ls =>\n val zipped = ls.zip(seq)\n (zipped.map((colorToValue _).tupled).sum, zipped.sortBy(_._2).map(_._1))\n }\n .minBy(_._1)\n\n min + \"\\n\" + list.mkString(\" \")\n } else -1\n }\n\n }\n}\n"}], "src_uid": "644f1469a9a9dcdb94144062ba616c59"} {"source_code": "object P3D {\n def main(args : Array[String]) {\n val s = readLine.toArray\n val q = collection.mutable.PriorityQueue[(Int, Int)]()\n def cost(p : Int, d : Int, c : Long) : Long = {\n if (p == s.size) {\n if (d == 0) c else -1\n } else if (s(p) == '(') {\n cost(p + 1, d + 1, c)\n } else {\n val cN = if (s(p) != '?') c else {\n s(p) = ')'\n val Array(c1, c2) = readLine split \" \" map {_.toInt}\n q enqueue ((c2 - c1, p))\n c + c2\n }\n if (d > 0) cost(p + 1, d - 1, cN) else {\n if (q.isEmpty) return -1\n val (cm, m) = q.dequeue\n s(m) = '('\n cost(p + 1, d + 1, cN - cm)\n }\n }\n }\n val c = cost(0, 0, 0L)\n println(c)\n if (c != -1) println(s.mkString)\n }\n}\n", "positive_code": [{"source_code": "object cf3D extends App {\n val s = readLine.toArray\n val q = collection.mutable.PriorityQueue[(Int, Int)]()\n def cost(p : Int, d : Int, c : Long) : Long = {\n if (p == s.size) {\n if (d == 0) c else -1\n } else if (s(p) == '(') {\n cost(p + 1, d + 1, c)\n } else {\n val cN = if (s(p) != '?') c else {\n s(p) = ')'\n val Array(c1, c2) = readLine split \" \" map {_.toInt}\n q enqueue ((c2 - c1, p))\n c + c2\n }\n if (d > 0) cost(p + 1, d - 1, cN) else {\n if (q.isEmpty) return -1\n val (cm, m) = q.dequeue\n s(m) = '('\n cost(p + 1, d + 1, cN - cm)\n }\n }\n }\n val c = cost(0, 0, 0L)\n println(c)\n if (c != -1) println(s.mkString)\n}"}], "negative_code": [{"source_code": "object P3D {\n def main(args : Array[String]) {\n val s = readLine.toArray\n val q = collection.mutable.PriorityQueue[(Int, Int)]()\n def cost(p : Int, d : Int, c : Int) : Int = {\n if (p == s.size) c else {\n s(p) match {\n case '(' => cost(p + 1, d + 1, c)\n case ')' => cost(p + 1, d - 1, c)\n case '?' => {\n s(p) = ')'\n val Array(c1, c2) = readLine split \" \" map {_.toInt}\n q enqueue ((c2 - c1, p))\n if (d > 0) cost(p + 1, d - 1, c + c2) else {\n val (cm, m) = q.dequeue\n s(m) = '('\n cost(p + 1, d + 1, c + c2 - cm)\n }\n }\n }\n }\n }\n println(cost(0, 0, 0))\n println(s.mkString)\n }\n}\n"}, {"source_code": "object P3D {\n def main(args : Array[String]) {\n val s = readLine.toArray\n val q = collection.mutable.PriorityQueue[(Int, Int)]()\n def cost(p : Int, d : Int, c : Long) : Long = {\n if (p == s.size) {\n if (d == 0) c else -1\n } else if (s(p) == '(') {\n cost(p + 1, d + 1, c)\n } else {\n val cN = if (s(p) != '?') c else {\n s(p) = ')'\n val Array(c1, c2) = readLine split \" \" map {_.toInt}\n q enqueue ((c2 - c1, p))\n c + c2\n }\n if (d > 0) cost(p + 1, d - 1, cN) else {\n if (q.isEmpty) return -1\n val (cm, m) = q.dequeue\n s(m) = '('\n cost(p + 1, d + 1, cN - cm)\n }\n }\n }\n println(cost(0, 0, 0L))\n println(s.mkString)\n }\n}\n"}, {"source_code": "object P3D {\n def main(args : Array[String]) {\n val s = readLine.toArray\n val q = collection.mutable.PriorityQueue[(Int, Int)]()\n def cost(p : Int, d : Int, c : Long) : Long = {\n if (p == s.size) c\n else if (s(p) == '(') cost(p + 1, d + 1, c)\n else {\n val cN = if (s(p) != '?') c else {\n s(p) = ')'\n val Array(c1, c2) = readLine split \" \" map {_.toInt}\n q enqueue ((c2 - c1, p))\n c + c2\n }\n if (d > 0) cost(p + 1, d - 1, cN) else {\n val (cm, m) = q.dequeue\n s(m) = '('\n cost(p + 1, d + 1, cN - cm)\n }\n }\n }\n println(cost(0, 0, 0L))\n println(s.mkString)\n }\n}\n"}, {"source_code": "object P3D {\n def main(args : Array[String]) {\n val s = readLine.toArray\n val q = collection.mutable.PriorityQueue[(Int, Int)]()\n def cost(p : Int, d : Int, c : Int) : Int = {\n if (p == s.size) c\n else if (s(p) == '(') cost(p + 1, d + 1, c)\n else {\n val cN = if (s(p) != '?') c else {\n s(p) = ')'\n val Array(c1, c2) = readLine split \" \" map {_.toInt}\n q enqueue ((c2 - c1, p))\n c + c2\n }\n if (d > 0) cost(p + 1, d - 1, cN) else {\n val (cm, m) = q.dequeue\n s(m) = '('\n cost(p + 1, d + 1, cN - cm)\n }\n }\n }\n println(cost(0, 0, 0))\n println(s.mkString)\n }\n}\n"}], "src_uid": "970cd8ce0cf7214b7f2be337990557c9"} {"source_code": "import java.io._\r\nimport java.util.Scanner\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport util.control.Breaks._\r\n\r\nobject Solution {\r\n val reader = new Scanner(System.in)\r\n val writer = new PrintWriter(System.out)\r\n\r\n def pow(a: Int, b: Int): Long = {\r\n if (b == 0) return 1\r\n\r\n val rs = pow(a, b / 2)\r\n rs * rs * (if (b % 2 == 0) 1 else a)\r\n }\r\n\r\n def GCD(a: Int, b: Int): Int = {\r\n if (a == 0) return b\r\n GCD(b % a, a)\r\n }\r\n\r\n def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b\r\n\r\n def root(u: Int, p: Array[Int]): Int = {\r\n if (p(u) < 0) return u\r\n p(u) = root(p(u), p)\r\n p(u)\r\n }\r\n\r\n def join(u: Int, v: Int, p: Array[Int]): Unit = {\r\n var x = root(u, p)\r\n var y = root(v, p)\r\n if (x == y) return\r\n\r\n if (p(y) < p(x)) {\r\n val t = x\r\n x = y\r\n y = t\r\n }\r\n p(x) += p(y)\r\n p(y) = x\r\n }\r\n\r\n def solve(t: Int = 0): Unit = {\r\n val x = reader.nextLong()\r\n val y = reader.nextLong()\r\n val c = reader.nextLong()\r\n\r\n val (a,b) = if (x > y) (x,y) else (y,x)\r\n\r\n\r\n val sub = a - b\r\n if (c > sub * 2 || sub * 2 < a)\r\n writer.println(-1)\r\n else if (c > sub)\r\n writer.println(c - sub)\r\n else\r\n writer.println(c + sub)\r\n }\r\n\r\n def multiTest(f: Int => Unit): Unit = {\r\n val t = reader.nextInt()\r\n for (i <- 1 to t) f(i)\r\n }\r\n\r\n def main(args: Array[String]) {\r\n multiTest(solve)\r\n //solve()\r\n writer.flush()\r\n }\r\n}", "positive_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(a, b, c) = readLine().split(\" \").map(_.toInt)\r\n\r\n val l = math.abs(a - b)\r\n val n = 2 * l\r\n val d = if (c <= l) c + l else c - l\r\n\r\n val ans =\r\n if ((a max b max c) > n) -1\r\n else d\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(a, b, c) = readLine().split(\" \").map(_.toInt)\r\n\r\n val l = math.abs(a - b)\r\n val n = 2 * l\r\n val d = if (c < l) c + l else c - l\r\n\r\n val ans =\r\n if ((a max b max c) > n) -1\r\n else d\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(x, y, c) = readLine().split(\" \").map(_.toInt)\r\n val (a, b) = (x min y, x max y)\r\n\r\n val l = b - a\r\n val n = 2 * l\r\n val d = if (c <= l) c + l else c - l\r\n\r\n val ans = if (b > n || a > l || n - b != l - a || d > n || d == a || d == b) -1 else d\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(x, y, c) = readLine().split(\" \").map(_.toInt)\r\n val (a, b) = (x min y, x max y)\r\n\r\n val l = b - a\r\n val n = 2 * l\r\n val d = if (c <= l) c + l else c - l\r\n\r\n val ans = if (b > n || a > l || n - b != l - a || d > n) -1 else d\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(a, b, c) = readLine().split(\" \").map(_.toInt)\r\n\r\n val l = math.abs(a - b)\r\n val n = 2 * l\r\n val d = if (c <= l) c + l else c - l\r\n\r\n val ans =\r\n if (\r\n a.min(b) <= l + 1 && l + 1 <= a.max(b) && a.max(b) <= n &&\r\n d <= n && d != a && d != b &&\r\n c % l == d % l && a % l == b % l\r\n ) d\r\n else -1\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(a, b, c) = readLine().split(\" \").map(_.toInt)\r\n\r\n val l = math.abs(a - b)\r\n val n = 2 * l\r\n val d = if (c <= l) c + l else c - l\r\n\r\n val ans =\r\n if (a.min(b) <= l + 1 && l + 1 <= a.max(b) && a.max(b) <= n && d <= n && d != a && d != b) d\r\n else -1\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(a, b, c) = readLine().split(\" \").map(_.toInt)\r\n\r\n val l = math.abs(a - b)\r\n val n = 2 * l\r\n val d = if (c <= l) c + l else c - l\r\n\r\n val ans =\r\n if (a.min(b) <= l + 1 && a.max(b) <= n && d <= n) d\r\n else -1\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(a, b, c) = readLine().split(\" \").map(_.toInt)\r\n\r\n val l = math.abs(a - b)\r\n val n = 2 * l\r\n val d = if (c <= l) c + l else c - l\r\n\r\n val ans = \r\n if (a.max(b) > n || d > n || d < 1) -1\r\n else d\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "src_uid": "07597a8d08b59d4f8f82369bb5d74a49"} {"source_code": "import java.util.Scanner\n\nobject Matrix extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n\n val mat = Array.ofDim[Int](n, n)\n val t = if (n % 2 == 1) n else n - 1\n\n for {\n i <- 0 until n - 1\n j <- 0 until n\n } {\n mat(i)(j) = 1 + (i + j) % t\n if (j == n - 1) {\n mat(i)(j) = mat(i)(i)\n mat(j)(i) = mat(i)(i)\n mat(i)(i) = 0\n }\n }\n\n for {\n i <- 0 until n\n } {\n println(mat(i).mkString(\" \"))\n }\n\n\n\n}", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Matrix extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n\n val mat = Array.ofDim[Int](n, n)\n val t = if (n % 2 == 1) n else n - 1\n\n for {\n i <- 0 until n - 1\n j <- 0 until n\n } {\n mat(i)(j) = 1 + (i + j) % t\n if (j == n - 1) {\n mat(i)(j) = mat(i)(i)\n mat(j)(i) = mat(i)(i)\n mat(i)(i) = 0\n }\n }\n\n for {\n i <- 0 until n\n } {\n println(mat(i).mkString(\" \"))\n }\n\n\n\n}"}, {"source_code": "import java.util.Scanner\n\nobject Matrix extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n\n val mat = Array.ofDim[Int](n, n)\n val t = if (n % 2 == 1) n else n - 1\n\n for {\n i <- 0 until n - 1\n j <- 0 until n\n } {\n mat(i)(j) = 1 + (i + j) % t\n if (j == n - 1) {\n mat(i)(j) = mat(i)(i)\n mat(j)(i) = mat(i)(i)\n mat(i)(i) = 0\n }\n }\n\n for {\n i <- 0 until n\n } {\n println(mat(i).mkString(\" \"))\n }\n\n\n\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nobject Matrix extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n\n val mat = Array.ofDim[Int](n, n)\n\n for {\n i <- 0 until n - 1\n j <- 0 until n\n } {\n mat(i)(j) = 1 + (i + j) % (n)\n if (j == n - 1) {\n mat(i)(j) = mat(i)(i)\n mat(j)(i) = mat(i)(i)\n mat(i)(i) = 0\n }\n }\n\n for {\n i <- 0 until n\n } {\n println(mat(i).mkString(\" \"))\n }\n\n\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Matrix extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n\n val mat = Array.ofDim[Int](n, n)\n\n for {\n i <- 0 until n - 1\n j <- 0 until n\n } {\n mat(i)(j) = 1 + (i + j) % (n)\n if (j == n - 1) {\n mat(i)(j) = mat(i)(i)\n mat(j)(i) = mat(i)(i)\n mat(i)(i) = 0\n }\n }\n\n for {\n i <- 0 until n\n } {\n println(mat(i).mkString(\" \"))\n }\n\n\n\n}"}], "src_uid": "f5f892203b62dae7eba86f59b13f5a38"} {"source_code": "import java.util.StringTokenizer\n\nobject _401 extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val x = next.toInt\n val sum = (1 to n).map(i => next.toInt).sum.abs\n println((sum + x - 1) / x)\n}\n", "positive_code": [{"source_code": "object HelloWorld {\n def main(args: Array[String]) {\n val l = Console.readLine().split(\" \").map(i => Integer.parseInt(i))\n val n = l(0)\n val x = l(1)\n var psum = Console.readLine().split(\" \").map(i => Integer.parseInt(i)).reduce(_ + _)\n val res = math.abs(psum)/x + (if (psum%x == 0) 0 else 1)\n\n println(res)\n }\n}"}, {"source_code": "\nobject Vanya {\n def process(n: Int, x:Int, cards: Array[Int]): Int = {\n val value:Int = Math.abs(cards.reduce(_+_))\n val div = value/x\n if(value%x == 0 ) div\n else div + 1\n }\n def main(args:Array[String]) = {\n val Inputs:List[Int] = scala.io.Source.stdin.getLines().\n grouped(2).toList.\n map((y:Seq[String]) => {\n val yl = y.toList\n val Array(n:Int, x:Int) = yl(0).split(\" \").map(_.toInt);\n val cards:Array[Int] = yl(1).split(\" \").map(_.toInt)\n process(n, x, cards);\n })\n Inputs.foreach((x: Int)=> println(x))\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io._\nimport scala.math._\nimport scala.collection.mutable.HashMap\nimport scala.collection.mutable.HashSet\n\nobject a6 {\n def main(args: Array[String]): Unit = {\n val lines = Source.stdin.getLines().toArray\n val x = lines(0).split(' ')(1).toInt\n var r = lines(1).split(' ').map(_.toInt).sum.abs\n var count=0\n for {i <- (1 to x).reverse} {\n if (r >= i) {\n count += r/i\n r%=i\n }\n }\n println(count)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val Array(n, x) = readLine().split(\" \").map(_.toInt)\n val data = Math.abs(readLine().split(\" \").map(_.toInt).sum)\n val r = if (data % x > 0) 1 else 0\n println(data / x + r)\n}"}, {"source_code": "object A401 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, x) = readInts(2)\n val in = math.abs(readInts(n).sum)\n println((in+x-1)/x)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P401A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, X = sc.nextInt\n\n def solve(): Unit = {\n val balance = List.fill(N)(sc.nextInt).sum.abs\n val answer = if (balance % X > 0) balance / X + 1\n else balance / X\n out.println(answer)\n }\n \n solve\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by hama_du on 2014/03/11.\n */\nobject ProblemA extends App {\n val in = new Scanner(System.in)\n val n = in.nextInt\n val x = in.nextInt\n val sum = Math.abs((0 until n).map(_ => in.nextInt).sum)\n println((sum + x - 1) / x)\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject CF401A extends App {\n val in = new Scanner(System.in)\n val n = in.nextInt\n val x = in.nextInt \n val sum = Math.abs((0 until n).map(_ => in.nextInt).sum)\n val answer = (sum + x - 1) / x;\n println(answer)\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by Kuang.Ru on 14-9-18.\n */\nobject A401 extends App{\n val sc = new Scanner(System.in)\n val n, x = sc.nextInt()\n val founded = new ArrayBuffer[Int]()\n var i = 0\n\n while (i < n) {\n founded += sc.nextInt()\n i += 1\n }\n\n val diff = Math.abs(founded.sum) - 0\n\n println(if (diff % x == 0){\n diff / x\n } else {\n diff / x + 1\n })\n}\n"}, {"source_code": "object A extends App {\n val sc = new java.util.Scanner(System.in)\n val n, x = sc.nextInt()\n val in = Array.fill(n)(sc.nextInt())\n val sum = in.sum\n println((sum/x).abs + (if (sum%x==0) 0 else 1))\n}\n"}, {"source_code": "object main extends App with fastIO {\n \n var Array(n, x) = readLine split(\" \") map(_.toInt)\n println((readLine.split(\" \").map(_.toInt).sum.abs + x - 1) / x) \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.io._\nimport scala.math._\nimport scala.collection.mutable.HashMap\nimport scala.collection.mutable.HashSet\n\nobject a6 {\n def main(args: Array[String]): Unit = {\n val lines = Source.stdin.getLines().toArray\n val cards = lines(1).split(' ').map(_.toInt)\n val h = new mutable.HashMap[Int, Int]()\n val s = new mutable.HashSet[Int]()\n (-1000 to 1000).foreach(h(_)=0)\n cards.foreach(a=>{h(a)=h(a)+1;s.add(abs(a))})\n println(s.filter(_>0).map(a=>abs(h(a)-h(-a))).sum)\n }\n}\n"}, {"source_code": "object A extends App {\n val sc = new java.util.Scanner(System.in)\n val n, x = sc.nextInt()\n val in = Array.fill(n)(sc.nextInt())\n val sum = in.sum\n println(sum/x + (if (sum%x==0) 0 else 1))\n}\n"}], "src_uid": "066906ee58af5163636dac9334619ea7"} {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val a2n = readLine().split(\" \").map(_.toInt)\n val an = a2n.distinct\n\n println(an.mkString(\" \"))\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val a2n = readLine().split(\" \").map(_.toInt)\n\n var flags = Array.fill(n + 1)(0)\n val an = a2n.foldLeft(List.empty[Int])((as, a) => if (flags(a) == 1) as else { flags(a) = 1; a :: as }).reverse\n\n println(an.mkString(\" \"))\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject contest356B extends App {\n\n def getRear(input: Array[Int]): String= {\n val res = new Array[Int](input.length / 2)\n var found = 0\n for (i <- 0 until input.length) {\n if (!res.contains(input(i))) {\n res(found) = input(i)\n found += 1\n }\n }\n var fin = \"\"\n res.foreach(x => fin += s\"$x \")\n fin.dropRight(1)\n }\n\n\n\n\n val t = readInt\n var lst: List[String] = List()\n for(a <- 1 to t){\n readLine\n val input :Array[Int] = readLine.split(\" \").map(_.toInt)\n lst = getRear(input) :: lst\n }\n\n for(y <- lst.length-1 to 0 by -1){\n println(lst(y))\n }\n\n}"}], "negative_code": [], "src_uid": "aaf91874cf5aa0fa302ffed2ccecdc76"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val known = Array.fill[Set[Int]](n){Set.empty[Int]}\n Range(0, m).foreach { _ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt - 1)\n known(a) += b\n known(b) += a\n }\n val r = known.indices.flatMap{ i =>\n known(i).flatMap{j =>\n known(j).intersect(known(i)).map(t => known(i).size + known(j).size + known(t).size)\n }\n }\n if (r.isEmpty)\n println(-1)\n else\n println(r.min - 6)\n}", "positive_code": [{"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\n\n\nobject BearMusketeers {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n def findMin(g : Map[Int,IndexedSeq[Int]], n: Int) : Int = {\n var curBest = scala.Int.MaxValue\n for (i <- 1 to n) {\n if (g(i).size < curBest) {\n for (j <- g(i).filter { _ > i }) {\n if (g(i).size + g(j).size < curBest) {\n for (k <- g(i).filter{x => x > j && (g(j) contains x) }) {\n if (g(i).size + g(j).size + g(k).size < curBest) \n curBest = g(i).size + g(j).size + g(k).size\n } \n }\n }\n }\n }\n if (curBest < scala.Int.MaxValue) curBest - 6 else -1\n } \n \n \n \n def main(args: Array[String]) {\n val (n,m) = readTuple\n val abs = for {\n i <- 1 to m\n t = readTuple\n } yield t\n val absSym = abs.flatMap(t => List(t,(t._2,t._1))).groupBy(_._1)\n .mapValues(is => is.map(_._2))\n .filterNot{ _._2.length < 2}\n \n /* val mins = for {\n i <- absSym.keys\n j <- absSym(i).filter(_ > i)\n k <- absSym(i).filter(k => k > j )\n if (absSym.getOrElse(j, IndexedSeq[Int]()) contains k) \n //_ = println(s\"$i, $j en $k kennen elkaar size ${(absSym(i).size + absSym(j).size + absSym(k).size)}\")\n \n } yield (absSym(i).size + absSym(j).size + absSym(k).size)\n if (mins.isEmpty) {\n println(\"-1\")\n } else {\n println(mins.min - 6)\n }*/\n println(findMin(absSym.withDefaultValue(IndexedSeq[Int]()), n))\n }\n \n}"}], "negative_code": [{"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject BearMusketeers {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n \n def main(args: Array[String]) {\n val (n,m) = readTuple\n val abs = for {\n i <- 1 to m\n t = readTuple\n } yield t\n val absSym = abs.flatMap(t => List(t,(t._2,t._1))).groupBy(_._1)\n .mapValues(is => is.map(_._2))\n .filterNot{ _._2.length < 3}\n val mins = for {\n i <- absSym.keys\n j <- absSym(i).filter(_ > i)\n k <- absSym(i).filter(k => k > j )\n if (absSym.getOrElse(j, IndexedSeq[Int]()) contains k)\n } yield (absSym(i).toSet + absSym(j) + absSym(k)).size\n if (mins.isEmpty) {\n println(\"-1\")\n } else {\n println(mins.min - 3)\n }\n }\n \n}"}], "src_uid": "24a43df3e6d2af348692cdfbeb8a195c"} {"source_code": "object P1497A extends App {\n import java.io._\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n val t = readInt\n for (_ <- 0 until t) {\n val n = readInt\n val sortedArray = readInts.sorted\n var isVisited = Map[Int, Boolean]()\n var ascending = List[Int]()\n var rest = List[Int]()\n sortedArray.foreach {\n case i@_ if isVisited getOrElse(i, false) => rest = i +: rest\n case i@_ => {\n ascending = i +: ascending\n isVisited += (i -> true)\n }\n }\n ascending = ascending.reverse\n println((ascending ++ rest).mkString(\" \"))\n }\n}\n", "positive_code": [{"source_code": "import scala.reflect.ClassTag\nimport scala.collection.immutable.StringOps\nimport scala.collection.immutable\nobject cf1497a {\n\n\tdef readInt(s: String) = s.toInt\n\tdef readLong(s: String) = s.toLong\n\n def read[T](conv: (String) => T): T = {\n\t\tconv(Console.in.readLine())\n\t}\n\n\tdef readArray[T:ClassTag](conv: (String) => T): Array[T] = {\n\t\tval line = Console.in.readLine()\n\t\tline.split(' ').map(conv(_))\n\t}\n\n\tdef solve(arr: Array[Long]): Unit = {\n\t\tval s = arr.sorted\n\t\tval min = s.foldLeft(0L)( (min, v) => {\n\t\t\tif (v == min) v+1\n\t\t\telse min\n\t\t})\n\n\t\tval lessThanUnique = immutable.SortedSet(s.takeWhile(_ < min):_*).toArray\n\t\tval reminder = arr.diff(lessThanUnique.toSeq)\n\t\tprintln((lessThanUnique ++ reminder).mkString(\" \"))\n\t}\n\n\tdef main(args: Array[String]): Unit = {\n\t\tval cases = read(readInt)\n\t\tvar nCase = 0\n\t\tfor (nCase <- 1 to cases) {\n\t\t\tread(readInt)\n\t\t\tval arr = readArray[Long](readLong)\n\t\t\tsolve(arr)\n }\n }\n}\n"}], "negative_code": [], "src_uid": "69838d9f9214c65b84a21d4eb546ea4b"} {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test4 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=a.indexOf(a.max)\n val min=a.indexOf(a.min)\n \n if(n<=2 || max-min==0) {\n println(-1)\n exit(0)\n }\n \n val swap=(a:Array[Int], i:Int, j:Int)=>{\n val tmp=a(i)\n a(i)=a(j)\n a(j)=tmp\n }\n \n for(i<-0 until n; j<-i+1 until n if a(i)!=a(j)){\n swap(a,i,j)\n if(!isSorted(a)) {println((i+1)+\" \"+(j+1));exit(0)}\n swap(a,i,j)\n }\n \n println(-1)\n \n def isSorted(arr:Array[Int]):Boolean={\n val increase=arr.last >= arr.head\n for(i<- 1 until arr.length){\n if(increase){\n if(arr(i)arr(i-1)) return false\n }\n }\n true\n }\n}\n", "positive_code": [{"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test4 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n if(a.max==a.min){\n println(-1)\n exit(0)\n }\n \n val swap=(a:Array[Int], i:Int, j:Int)=>{\n val tmp=a(i)\n a(i)=a(j)\n a(j)=tmp\n }\n \n for(i<-0 until n; j<-i+1 until n if a(i)!=a(j)){\n swap(a,i,j)\n if(!isSorted(a)) {println((i+1)+\" \"+(j+1));exit(0)}\n swap(a,i,j)\n }\n \n println(-1)\n \n def isSorted(arr:Array[Int]):Boolean={\n val increase=arr.last >= arr.head\n for(i<- 1 until arr.length){\n if(increase && arr(i)arr(i-1)) return false\n }\n true\n }\n}\n"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test4 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n /*\n val max=a.indexOf(a.max)\n val min=a.indexOf(a.min)\n \n if(n<=2 || max-min==0) {\n println(-1)\n exit(0)\n }\n * \n */\n if(a.max==a.min){\n println(-1)\n exit(0)\n }\n \n val swap=(a:Array[Int], i:Int, j:Int)=>{\n val tmp=a(i)\n a(i)=a(j)\n a(j)=tmp\n }\n \n for(i<-0 until n; j<-i+1 until n if a(i)!=a(j)){\n swap(a,i,j)\n if(!isSorted(a)) {println((i+1)+\" \"+(j+1));exit(0)}\n swap(a,i,j)\n }\n \n println(-1)\n \n def isSorted(arr:Array[Int]):Boolean={\n val increase=arr.last >= arr.head\n for(i<- 1 until arr.length){\n if(increase){\n if(arr(i)arr(i-1)) return false\n }\n }\n true\n }\n}\n"}], "negative_code": [{"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test4 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=a.indexOf(a.max)\n val min=a.indexOf(a.min)\n \n for(i<-1 until n-1){\n if(i>max && a(i)min && a(i)>a(min) && a(i+1)>=a(min)) {println((min+1) + \" \"+(i+1)); exit(0)}\n }\n \n println(-1)\n}\n"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test4 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=a.indexOf(a.max)\n val min=a.indexOf(a.min)\n \n for(i<-1 until n-1){\n if(i!=max && a(i)a(min) && a(i+1)>a(min)) {println((min+1) + \" \"+(i+1)); exit(0)}\n }\n \n println(-1)\n}\n"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test4 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=a.indexOf(a.max)\n val min=a.indexOf(a.min)\n \n if(n<=2 || max-min==0) {\n println(-1)\n exit(0)\n }\n \n\n for(i<-1 until n-1){\n if(i>max && a(i-1)min && a(i-1)>a(min) && a(i+1)>a(min)) {println((min+1) + \" \"+(i+1)); exit(0)}\n }\n \n println(-1)\n \n def isSorted(arr:Array[Int]):Boolean={\n val increase=arr.last >= arr.head\n for(i<- 1 until arr.length){\n if(increase){\n if(arr(i)arr(i-1)) return false\n }\n }\n true\n }\n}\n"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test4 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=a.indexOf(a.max)\n val min=a.indexOf(a.min)\n \n if(n<=2 || max-min==0) {\n println(-1)\n exit(0)\n }\n \n if(isSorted(a)){\n println((max+1) +\" \" +(min+1)); exit(0)\n }\n else{\n for(i<-1 until n-1){\n if(i>max && a(i-1)min && a(i-1)>a(min) && a(i+1)>a(min)) {println((min+1) + \" \"+(i+1)); exit(0)}\n }\n }\n \n println(-1)\n \n def isSorted(arr:Array[Int]):Boolean={\n val increase=arr.last >= arr.head\n for(i<- 1 until arr.length){\n if(increase){\n if(arr(i)arr(i-1)) return false\n }\n }\n true\n }\n}\n"}, {"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\nimport java.util.Scanner\n\nobject test6 extends App {\n def maxsub(s:String):Int={\n val n=s.length\n val dp=new Array[Int](n)\n \n for(i<-1 until n){\n var j=i\n while(j>0 && s(i)!=s(dp(j-1))) j=dp(j-1)\n dp(i)=if(j>0) dp(j-1)+1 else 0\n }\n \n var j=dp(n-1)\n while(n%(n-j)!=0) j=dp(j-1)\n n/(n-j)\n }\n \n println(maxsub(\"a\"))\n println(maxsub(\"a\"*5))\n println(maxsub(\"ab\"*1000))\n println(maxsub(\"byebye\"))\n println(maxsub(\"codility\"))\n println(maxsub(\"aabaaaba\"))\n} \n\n\n"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test4 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=a.indexOf(a.max)\n val min=a.indexOf(a.min)\n \n for(i<-1 until n-1){\n if(i!=max && a(i-1)a(min) && a(i+1)>a(min)) {println((min+1) + \" \"+(i+1)); exit(0)}\n }\n \n println(-1)\n}\n"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test4 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=a.indexOf(a.max)\n val min=a.indexOf(a.min)\n \n if(n<=2 || max-min==0) {\n println(-1)\n exit(0)\n }\n \n if(isSorted(a) || max-min==1){\n println((max+1) +\" \" +(min+1)); exit(0)\n }\n else{\n for(i<-1 until n-1){\n if(i>max && a(i-1)min && a(i-1)>a(min) && a(i+1)>a(min)) {println((min+1) + \" \"+(i+1)); exit(0)}\n }\n }\n \n println(-1)\n \n def isSorted(arr:Array[Int]):Boolean={\n val increase=arr.last >= arr.head\n for(i<- 1 until arr.length){\n if(increase){\n if(arr(i)arr(i-1)) return false\n }\n }\n true\n }\n}\n"}, {"source_code": "import java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test4 extends App {\n val n=readInt\n val a=readLine.split(\" \").map(_.toInt)\n \n val max=a.indexOf(a.max)\n val min=a.indexOf(a.min)\n \n if(n<=2 || max-min==0) {\n println(-1)\n exit(0)\n }\n \n for(i<-0 until n; j<-i+1 until n if a(i)!=a(j)){\n val tmp=a(i)\n a(i)=a(j)\n a(j)=tmp\n \n if(!isSorted(a)) {println((i+1)+\" \"+(j+1));exit(0)}\n }\n \n println(-1)\n \n def isSorted(arr:Array[Int]):Boolean={\n val increase=arr.last >= arr.head\n for(i<- 1 until arr.length){\n if(increase){\n if(arr(i)arr(i-1)) return false\n }\n }\n true\n }\n}\n"}], "src_uid": "2ae4d2ca09f28d10fa2c71eb2abdaa1c"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, n1, n2) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toInt).sorted.reverse.take(n1 + n2)\n val min = Math.min(n1, n2)\n val max = Math.max(n1, n2)\n println(a.take(min).foldLeft(0l)(_+_).toDouble / min + a.drop(min).foldLeft(0l)(_+_).toDouble / max)\n}\n", "positive_code": [{"source_code": "import java.io._\nimport scala.io.Source\n\nimport scala.annotation.tailrec\n\nobject ProblemB {\n def main(args: Array[String]): Unit = processStdInOut()\n\n def processStdInOut(): Unit = {\n val src = Source.fromInputStream(System.in)\n processFromSource(src)\n }\n\n def processFromSource(src: Source): Unit = {\n try {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out));\n try {\n val lines = src.getLines()\n processLines(lines, bw)\n } finally {\n bw.flush()\n }\n } finally {\n src.close();\n }\n }\n\n // Standard code above, custom code below\n\n def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {\n val line = lines.next()\n val parms = line.split(\" \").map(_.toInt)\n val n = parms(0)\n val n1 = parms(1)\n val n2 = parms(2)\n val as = lines.next().split(\" \").map(_.toLong)\n val soln = solve(n, n1, n2, as)\n bw.write(soln.toString)\n bw.newLine()\n }\n\n def solve(n: Int, n1: Int, n2: Int, as: Array[Long]): Double = {\n val nMin = math.min(n1, n2)\n val nMax = math.max(n1, n2)\n val asorted = as.map(- _).sorted\n val (aMin, aRest) = asorted.splitAt(nMin)\n val aMax = aRest.take(nMax)\n val mean1 = - aMin.sum / nMin.toDouble\n val mean2 = - aMax.sum / nMax.toDouble\n val sumOfMeans = mean1 + mean2\n sumOfMeans\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, n1, n2) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toInt).sorted.reverse.take(n1 + n2)\n val min = Math.min(n1, n2)\n val max = Math.max(n1, n2)\n println(a.take(min).sum.toDouble / min + a.drop(min).sum.toDouble / max)\n\n}\n"}], "src_uid": "822e8f394a59329fa05c96d7fb35797e"} {"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, q) = readInts(2)\n val as = readInts(n)\n\n val BITS = 20\n @inline def bit(i: Int) = 1 << i\n\n val minReachableWith = Array.fill(BITS){ n + 1 }\n for (b <- 0 until BITS) {\n if ((as.last & bit(b)) > 0) minReachableWith(b) = n - 1\n }\n\n val minReachable = Array.fill(n, BITS){ n + 1 }\n\n for (i <- n - 2 to 0 by -1) {\n val a = as(i)\n var b = 0\n while (b < BITS) {\n if ((a & bit(b)) > 0) {\n if (minReachableWith(b) < n) {\n val j = minReachableWith(b)\n var b2 = 0\n while (b2 < BITS) {\n if (minReachable(j)(b2) < minReachable(i)(b2)) minReachable(i)(b2) = minReachable(j)(b2)\n b2 += 1\n }\n }\n minReachableWith(b) = i\n minReachable(i)(b) = i\n }\n b += 1\n }\n var b2 = 0\n while (b2 < BITS) {\n if (minReachable(i)(b2) < minReachableWith(b2)) minReachableWith(b2) = minReachable(i)(b2)\n b2 += 1\n }\n }\n\n val reachable = Array.fill(q)(false)\n for (i <- 0 until q) {\n val Array(l0, r0) = readInts(2)\n val l = l0 - 1\n val r = r0 - 1\n var b = 0\n while (b < BITS) {\n if ((as(r) & bit(b)) > 0 && minReachable(l)(b) <= r) reachable(i) = true\n b += 1\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(reachable.map(if (_) \"Shi\" else \"Fou\").mkString(\"\\n\"))\n\n Console.flush\n}\n", "positive_code": [{"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, q) = readInts(2)\n val as = readInts(n)\n\n val BITS = 20\n def bit(i: Int) = 1 << i\n\n val minReachableWith = Array.fill(BITS){ n + 1 }\n for (b <- 0 until BITS) {\n if ((as.last & bit(b)) > 0) minReachableWith(b) = n - 1\n }\n\n val minReachable = Array.fill(n, BITS){ n + 1 }\n\n for (i <- n - 2 to 0 by -1) {\n val a = as(i)\n for (b <- 0 until BITS) {\n if ((a & bit(b)) > 0) {\n if (minReachableWith(b) < n) {\n val j = minReachableWith(b)\n for (b2 <- 0 until BITS) {\n if (minReachable(j)(b2) < minReachable(i)(b2)) minReachable(i)(b2) = minReachable(j)(b2)\n }\n }\n minReachableWith(b) = i\n minReachable(i)(b) = i\n }\n }\n for (b2 <- 0 until BITS) {\n if (minReachable(i)(b2) < minReachableWith(b2)) minReachableWith(b2) = minReachable(i)(b2)\n }\n }\n\n val reachable = Array.fill(q)(false)\n for (i <- 0 until q) {\n val Array(l0, r0) = readInts(2)\n val l = l0 - 1\n val r = r0 - 1\n for (b <- 0 until BITS) {\n if ((as(r) & bit(b)) > 0 && minReachable(l)(b) <= r) reachable(i) = true\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(reachable.map(if (_) \"Shi\" else \"Fou\").mkString(\"\\n\"))\n\n Console.flush\n}"}, {"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, q) = readInts(2)\n val as = readInts(n)\n\n val BITS = 20\n @inline def bit(i: Int) = 1 << i\n\n val minReachableWith = Array.fill(BITS){ n + 1 }\n for (b <- 0 until BITS) {\n if ((as.last & bit(b)) > 0) minReachableWith(b) = n - 1\n }\n\n val minReachable = Array.fill(n, BITS){ n + 1 }\n\n for (i <- n - 2 to 0 by -1) {\n val a = as(i)\n var b = 0\n while (b < BITS) {\n if ((a & bit(b)) > 0) {\n if (minReachableWith(b) < n) {\n val j = minReachableWith(b)\n var b2 = 0\n while (b2 < BITS) {\n if (minReachable(j)(b2) < minReachable(i)(b2)) minReachable(i)(b2) = minReachable(j)(b2)\n b2 += 1\n }\n }\n minReachableWith(b) = i\n minReachable(i)(b) = i\n }\n b += 1\n }\n\n }\n\n val reachable = Array.fill(q)(false)\n for (i <- 0 until q) {\n val Array(l0, r0) = readInts(2)\n val l = l0 - 1\n val r = r0 - 1\n var b = 0\n while (b < BITS) {\n if ((as(r) & bit(b)) > 0 && minReachable(l)(b) <= r) reachable(i) = true\n b += 1\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(reachable.map(if (_) \"Shi\" else \"Fou\").mkString(\"\\n\"))\n\n Console.flush\n}"}, {"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, q) = readInts(2)\n val as = readInts(n)\n\n val BITS = 20\n def bit(i: Int) = 1 << i\n\n val minReachableWith = Array.fill(BITS){ n + 1 }\n for (b <- 0 until BITS) {\n if ((as.last & bit(b)) > 0) minReachableWith(b) = n - 1\n }\n\n val minReachable = Array.fill(n, BITS){ n + 1 }\n\n for (i <- n - 2 to 0 by -1) {\n val a = as(i)\n for (b <- 0 until BITS) {\n if ((a & bit(b)) > 0) {\n if (minReachableWith(b) < n) {\n val j = minReachableWith(b)\n for (b2 <- 0 until BITS) {\n if (minReachable(j)(b2) < minReachable(i)(b2)) minReachable(i)(b2) = minReachable(j)(b2) : @inline\n }\n }\n minReachableWith(b) = i\n minReachable(i)(b) = i\n } : @inline\n }\n for (b2 <- 0 until BITS) {\n if (minReachable(i)(b2) < minReachableWith(b2)) minReachableWith(b2) = minReachable(i)(b2) : @inline\n }\n }\n\n val reachable = Array.fill(q)(false)\n for (i <- 0 until q) {\n val Array(l0, r0) = readInts(2)\n val l = l0 - 1\n val r = r0 - 1\n for (b <- 0 until BITS) {\n if ((as(r) & bit(b)) > 0 && minReachable(l)(b) <= r) reachable(i) = true : @inline\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(reachable.map(if (_) \"Shi\" else \"Fou\").mkString(\"\\n\"))\n\n Console.flush\n}"}], "negative_code": [], "src_uid": "6e2e7fd13e9f79267baa4bfd75444f32"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val team1 = in.next()\n val team2 = in.next()\n val n = in.next().toInt\n val data = (1 to n).map(_ => in.next().split(\" \"))\n var t1_1 = Set.empty[Int]\n var t1_2 = Map.empty[Int, Int]\n var t2_1 = Set.empty[Int]\n var t2_2 = Map.empty[Int, Int]\n data.foreach {\n case Array(time, \"h\", number, color) if t1_2.contains(number.toInt) =>\n case Array(time, \"h\", number, \"r\") => t1_2 += (number.toInt -> time.toInt)\n case Array(time, \"h\", number, \"y\") if t1_1.contains(number.toInt) => t1_2 += (number.toInt -> time.toInt)\n case Array(time, \"h\", number, \"y\") => t1_1 += number.toInt\n case Array(time, \"a\", number, color) if t2_2.contains(number.toInt) =>\n case Array(time, \"a\", number, \"r\") => t2_2 += (number.toInt -> time.toInt)\n case Array(time, \"a\", number, \"y\") if t2_1.contains(number.toInt) => t2_2 += (number.toInt -> time.toInt)\n case Array(time, \"a\", number, \"y\") => t2_1 += number.toInt\n }\n println((t1_2.map {\n case(number, time) => (time, team1, number)\n }.toList ::: t2_2.map {\n case(number, time) => (time, team2, number)\n }.toList).sorted.map(t => s\"${t._2} ${t._3} ${t._1}\").mkString(\"\\n\"))\n\n}", "positive_code": [{"source_code": "import java.util.StringTokenizer\nimport scala.collection.mutable.Map\n\nobject _493A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val home = next\n val away = next\n val homeYellow = Map[Int, Int]()\n val awayYellow = Map[Int, Int]()\n val homeRed = Map[Int, Int]()\n val awayRed = Map[Int, Int]()\n\n val a = (1 to next.toInt).map(i => (1 to 4).map(j => next)).toArray.sortBy(arr => arr(0).toInt)\n for (event <- a) {\n val t = event(0).toInt\n val yellow = if (event(1) == \"h\") homeYellow else awayYellow\n val red = if(event(1) == \"h\") homeRed else awayRed\n val player = event(2).toInt\n if (event(3) == \"y\") {\n if (yellow.contains(player)) {\n if (red.contains(player)) red(player) = red(player) min t else red += ((player, t))\n }\n else yellow += ((player, t))\n } else {\n if (red.contains(player)) red(player) = red(player) min t\n else red += ((player, t))\n }\n }\n\n\n val cb = homeRed.toArray.map(i => (home, i._1, i._2))\n val wb = awayRed.toArray.map(i => (away, i._1, i._2))\n (cb ++ wb).sortBy(i => i._3).foreach(i => println(\"%s %d %d\".format(i._1, i._2, i._3)))\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val homename = io.StdIn.readLine()\n val guestname = io.StdIn.readLine()\n val fault_cnt = io.StdIn.readInt()\n val recs: Array[Array[String]] = (1 to fault_cnt).map{ dump =>\n io.StdIn.readLine().split(\" \")\n }.toArray\n val guest: Array[Int] = Array.fill[Int](100)(0)\n val home: Array[Int] = Array.fill[Int](100)(0)\n recs.foreach{ r =>\n val curteam = if(r(1) == \"a\") guest else home\n val curname = if(r(1) == \"a\") guestname else homename\n if(curteam(r(2).toInt) < 2) {\n if(r(3) == \"y\") curteam(r(2).toInt) += 1\n else curteam(r(2).toInt) += 2\n if(curteam(r(2).toInt) >= 2) {\n println(curname + \" \" + r(2).toInt + \" \" + r(0).toInt)\n }\n }\n }\n }\n}\n"}, {"source_code": "import scala.collection.immutable.IndexedSeq\n\nobject ProblemARunner extends App {\n ProblemA.run()\n}\nobject ProblemA {\n import scala.io.StdIn._\n\n private def relevantFouls(fouls: IndexedSeq[Foul]) = {\n val byPlayer = fouls.groupBy(foul => (foul.team, foul.player))\n byPlayer.values.toSeq.collect { case foulsByPlayer if foulsByPlayer.map(_.cards).sum >= 2 =>\n if(foulsByPlayer(0).cards == 2)\n foulsByPlayer(0)\n else\n foulsByPlayer(1)\n }.sortBy(_.time)\n }\n\n def run(): Unit = {\n val oneTeam = readTeamName()\n val otherTeam = readTeamName()\n val fouls = 1 to readFouls() map { _ =>\n Foul.read(oneTeam, otherTeam)\n }\n val relevant = relevantFouls(fouls)\n printFouls(relevant)\n }\n\n private def printFouls(fouls: Seq[Foul]) = {\n fouls.foreach(_.toOutput())\n }\n private def readTeamName(): String = {\n readLine()\n }\n private def readFouls(): Int = {\n readInt()\n }\n private case class Foul(time: Int, team: String, player: Int, cards: Int) {\n def toOutput() = {\n println(s\"$team $player $time\")\n }\n }\n private object Foul {\n def read(oneName: String, otherName: String): Foul = {\n val line = readLine().split(' ')\n val time = line(0).toInt\n val team = line(1) match {\n case \"h\" => oneName\n case \"a\" => otherName\n }\n val player = line(2).toInt\n val cards = line(3) match {\n case \"y\" => 1\n case \"r\" => 2\n }\n Foul(time, team, player, cards)\n }\n }\n\n}\n"}, {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nimport scala.annotation.tailrec\n\nobject A_VasyaAndFootbal {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val homeTeam = scanner.next()\n val awayTeam = scanner.next()\n\n val n = scanner.nextInt()\n\n val input = for (i <- 1 to n) yield {\n val time = scanner.nextInt()\n val teamId = scanner.next()\n val playerId = scanner.nextInt()\n val cardType = scanner.next()\n\n val teamName = teamId match {\n case \"a\" => awayTeam\n case \"h\" => homeTeam\n }\n\n (time, teamName, playerId, cardType)\n }\n\n //result (team, playerId, time, cardsCount)\n @tailrec def process (l : List[(Int, String, Int, String)], acc : Map[String, (String, Int, Int, Int)] = Map.empty) : Map[String, (String, Int, Int, Int)] = {\n l match {\n case x :: tail => {\n val playerId = x._2 + \"_\" + x._3\n val cardPoints = x._4 match {\n case \"y\" => 1\n case \"r\" => 2\n case _ => 0\n }\n\n val cardsCount = if (acc.contains(playerId)) acc(playerId)._4 else 0\n\n if (cardsCount >= 2) {\n process(tail, acc)\n } else {\n process(tail, acc + (playerId -> (x._2, x._3, x._1, cardsCount + cardPoints)))\n }\n }\n case Nil => acc\n }\n }\n\n\n val result = process(input.toList).filter(x => x._2._4 >= 2).toList.map(_._2).sortBy(x => x._3)\n\n for (x <- result) {\n out.println(s\"${x._1} ${x._2} ${x._3}\")\n }\n }\n}\n"}, {"source_code": "\nobject Main extends App {\n\n val teamH = readLine\n val teamA = readLine\n\n def rename(team: String) = if(team == \"h\") teamH else teamA\n\n val games = readLine.toInt\n (1 to games).foldLeft(Map[(String, String), String]()) {\n case (acc, _) =>\n val Array(time, team, num, card) = readLine.split(\" \")\n acc.get((team, num)) match {\n case None =>\n if(card == \"r\") println(\"%s %s %s\".format(rename(team), num, time)) else ()\n acc + ((team, num) -> card)\n case Some(\"r\") =>\n acc\n case Some(\"y\") =>\n println(\"%s %s %s\".format(rename(team), num, time))\n acc + ((team, num) -> \"r\")\n }\n }\n\n}"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\nimport scala.collection.mutable.Map\n\nobject _493A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val home = next\n val away = next\n val homeYellow = Map[Int, Int]()\n val awayYellow = Map[Int, Int]()\n val homeRed = Map[Int, Int]()\n val awayRed = Map[Int, Int]()\n\n val a = (1 to next.toInt).map(i => (1 to 4).map(j => next)).toArray.sortBy(arr => arr(0).toInt)\n for (event <- a) {\n val t = event(0).toInt\n val yellow = if (event(1) == \"h\") homeYellow else awayYellow\n val red = if(event(1) == \"h\") homeRed else awayRed\n val player = event(2).toInt\n if (event(3) == \"y\") {\n if (yellow.contains(player)) {\n yellow(player) = yellow(player) max t\n if (red.contains(player)) red(player) = red(player) min t else red += ((player, yellow(player)))\n }\n else yellow += ((player, t))\n } else {\n if (red.contains(player)) red(player) = red(player) min t\n else red += ((player, t))\n }\n }\n\n homeRed.toArray.sortBy(pair => pair._1).foreach(pair => println(\"%s %d %d\".format(home, pair._1, pair._2)))\n awayRed.toArray.sortBy(pair => pair._1).foreach(pair => println(\"%s %d %d\".format(away, pair._1, pair._2)))\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val homename = io.StdIn.readLine()\n val guestname = io.StdIn.readLine()\n val fault_cnt = io.StdIn.readInt()\n val recs: Array[Array[String]] = (1 to fault_cnt).map{ dump =>\n io.StdIn.readLine().split(\" \")\n }.toArray\n val guest: Array[Int] = Array.fill[Int](99)(0)\n val home: Array[Int] = Array.fill[Int](99)(0)\n recs.foreach{ r =>\n val curteam = if(r(1) == \"a\") guest else home\n val curname = if(r(1) == \"a\") guestname else homename\n if(r(3) == \"y\") curteam(r(2).toInt) += 1\n if(r(3) == \"r\" || curteam(r(2).toInt) == 2) {\n println(curname + \" \" + r(2).toInt + \" \" + r(0).toInt)\n }\n }\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val homename = io.StdIn.readLine()\n val guestname = io.StdIn.readLine()\n val fault_cnt = io.StdIn.readInt()\n val recs: Array[Array[String]] = (1 to fault_cnt).map{ dump =>\n io.StdIn.readLine().split(\" \")\n }.toArray\n val guest: Array[Int] = Array.fill[Int](100)(0)\n val home: Array[Int] = Array.fill[Int](100)(0)\n recs.foreach{ r =>\n val curteam = if(r(1) == \"a\") guest else home\n val curname = if(r(1) == \"a\") guestname else homename\n if(r(3) == \"y\") curteam(r(2).toInt) += 1\n else curteam(r(2).toInt) += 2\n if(r(3) == \"r\" || curteam(r(2).toInt) == 2) {\n println(curname + \" \" + r(2).toInt + \" \" + r(0).toInt)\n }\n }\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val homename = io.StdIn.readLine()\n val guestname = io.StdIn.readLine()\n val fault_cnt = io.StdIn.readInt()\n val recs: Array[Array[String]] = (1 to fault_cnt).map{ dump =>\n io.StdIn.readLine().split(\" \")\n }.toArray\n val guest: Array[Int] = Array.fill[Int](100)(0)\n val home: Array[Int] = Array.fill[Int](100)(0)\n recs.foreach{ r =>\n val curteam = if(r(1) == \"a\") guest else home\n val curname = if(r(1) == \"a\") guestname else homename\n if(r(3) == \"y\") curteam(r(2).toInt) += 1\n if(r(3) == \"r\" || curteam(r(2).toInt) == 2) {\n println(curname + \" \" + r(2).toInt + \" \" + r(0).toInt)\n }\n }\n }\n}\n"}, {"source_code": "import scala.collection.immutable.IndexedSeq\n\nobject ProblemARunner extends App {\n ProblemA.run()\n}\nobject ProblemA {\n import scala.io.StdIn._\n\n private def relevantFouls(fouls: IndexedSeq[Foul]) = {\n val byPlayer = fouls.groupBy(foul => (foul.team, foul.player))\n byPlayer.values.toSeq.collect { case foulsByPlayer if foulsByPlayer.map(_.cards).sum >= 2 =>\n foulsByPlayer.maxBy(_.time)\n }.sortBy(_.time)\n }\n\n def run(): Unit = {\n val oneTeam = readTeamName()\n val otherTeam = readTeamName()\n val fouls = 1 to readFouls() map { _ =>\n Foul.read(oneTeam, otherTeam)\n }\n val relevant = relevantFouls(fouls)\n printFouls(relevant)\n }\n\n private def printFouls(fouls: Seq[Foul]) = {\n fouls.foreach(_.toOutput())\n }\n private def readTeamName(): String = {\n readLine()\n }\n private def readFouls(): Int = {\n readInt()\n }\n private case class Foul(time: Int, team: String, player: Int, cards: Int) {\n def toOutput() = {\n println(s\"$team $player $time\")\n }\n }\n private object Foul {\n def read(oneName: String, otherName: String): Foul = {\n val line = readLine().split(' ')\n val time = line(0).toInt\n val team = line(1) match {\n case \"h\" => oneName\n case \"a\" => otherName\n }\n val player = line(2).toInt\n val cards = line(3) match {\n case \"y\" => 1\n case \"r\" => 2\n }\n Foul(time, team, player, cards)\n }\n }\n\n}\n"}], "src_uid": "b1f78130d102aa5f425e95f4b5b3a9fb"} {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.io.StdIn\nimport scala.reflect.ClassTag\n\nobject Main {\n final val MOD = 1000000007\n def main(args: Array[String]) {\n val n = StdIn.readInt()\n val ct = new mutable.HashMap[Long, Long]().withDefault(k => 0)\n for (v <- StdIn.readLine().split(\" \").map(_.toInt)) {\n ct(v) += 1\n }\n val ctl = ct.toArray\n val prod = new SegTree(n)(new ModMul(MOD - 1))\n for (((k, v), i) <- ctl.zipWithIndex) {\n prod(i) = v + 1\n }\n var ans = 1L\n for (((k, v), i) <- ctl.zipWithIndex) {\n prod(i) = 1\n val s = (v * (v + 1) / 2) % (MOD - 1)\n val p = prod.query(0, n) * s % (MOD - 1)\n ans *= modPow(k, p, MOD)\n ans %= MOD\n prod(i) = v + 1\n }\n println(ans)\n }\n def modPow(x: Long, y: Long, mod: Int): Long = {\n @tailrec\n def rec(x: Long, y: Long, r: Long): Long = {\n if (y == 0) r\n else rec(x * x % mod, y / 2, if (y % 2 == 1) r * x % mod else r)\n }\n return rec(x, y, 1)\n }\n}\ntrait Monoid[T] {\n def zero: T\n def mul(a: T, b: T): T\n}\n\nclass SegTree[T: ClassTag](n0: Int)(m: Monoid[T]) {\n\n val n = {\n var n1 = 1\n while (n1 < n0) n1 <<= 1\n n1\n }\n\n val t: Array[T] = Array.fill[T](2 * n - 1)(m.zero)\n\n def set(a: Array[T]): Unit = {\n def rec(k: Int, l: Int, r: Int): T = {\n if (r - l == 1) {\n if (l < a.length) t(k) = a(l)\n else t(k) = m.zero\n return t(k)\n } else {\n t(k) = m.mul(\n rec(2 * k + 1, l, (l + r) / 2),\n rec(2 * k + 2, (l + r) / 2, r)\n )\n return t(k)\n }\n }\n rec(0, 0, n)\n }\n\n def update(k0: Int, v: T): Unit = {\n var k = k0 + (n - 1)\n t(k) = v\n while (k > 0) {\n k = (k - 1) / 2\n t(k) = m.mul(t(2 * k + 1), t(2 * k + 2))\n }\n }\n\n def get(k0: Int): T = {\n return t(k0 + (n - 1))\n }\n\n def query(a: Int, b: Int): T = {\n def rec(k: Int, l: Int, r: Int): T = {\n if (b <= l || r <= a) {\n return m.zero\n } else if (a <= l && r <= b) {\n return t(k)\n } else {\n return m.mul(\n rec(2 * k + 1, l, (l + r) / 2),\n rec(2 * k + 2, (l + r) / 2, r)\n )\n }\n }\n return rec(0, 0, n)\n }\n}\n\nclass ModMul(mod: Int) extends Monoid[Long] {\n def zero = 1L\n def mul(a: Long, b: Long) = a * b % mod\n}\n\n", "positive_code": [{"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(m) = readInts(1)\n val ps = readInts(m)\n val psDist = ps.distinct\n val MOD = 1000000007L\n \n val cnts = Array.fill(ps.max.toInt + 1){ 0 }\n\n for (p <- ps) {\n val pi = p.toInt\n cnts(pi) += 1\n }\n \n val muls = Array.fill(ps.max.toInt + 1){ 0L }\n for (i <- cnts.indices) {\n if (cnts(i) > 0) {\n muls(i) = (cnts(i) + 1L) * cnts(i) / 2\n }\n }\n \n val powsLeft, powsRight = Array.fill(psDist.size){ 0L }\n var powL, powR = 1L\n \n for (i <- psDist.indices) {\n powsLeft(i) = powL\n powL = powL * (cnts(psDist(i).toInt) + 1) % (MOD - 1)\n }\n\n for (i <- psDist.indices.reverse) {\n powsRight(i) = powR\n powR = powR * (cnts(psDist(i).toInt) + 1) % (MOD - 1)\n }\n\n var res = BigInt(1)\n for (i <- psDist.indices) {\n val p = psDist(i)\n res = res * BigInt(p).modPow(BigInt(muls(p)) * powsLeft(i) * powsRight(i), MOD) % MOD\n }\n\n println(res)\n}\n"}], "negative_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.io.StdIn\nimport scala.reflect.ClassTag\n\nobject Main {\n final val MOD = 1000000007\n def main(args: Array[String]) {\n val n = StdIn.readInt()\n val ct = new mutable.HashMap[Long, Long]().withDefault(k => 0)\n for (v <- StdIn.readLine().split(\" \").map(_.toInt)) {\n ct(v) += 1\n }\n val ctl = ct.toArray\n val prod = new SegTree(n)(new ModMul(MOD - 1))\n for (((k, v), i) <- ctl.zipWithIndex) {\n prod(i) = v + 1\n }\n var ans = 1L\n for (((k, v), i) <- ctl.zipWithIndex) {\n prod(i) = 1\n val s = (v * (v + 1) / 2) % (MOD - 1)\n val p = prod.query(0, n) * s % (MOD - 1)\n ans *= modPow(k, p, MOD)\n ans %= MOD\n prod(i) = v + 1\n }\n println(ans)\n }\n def modPow(x: Long, y: Long, mod: Int): Long = {\n @tailrec\n def rec(x: Long, y: Long, r: Long): Long = {\n if (y == 0) r\n else rec(x * x, y / 2, if (y % 2 == 1) r * x % mod else r)\n }\n return rec(x, y, 1)\n }\n}\ntrait Monoid[T] {\n def zero: T\n def mul(a: T, b: T): T\n}\n\nclass SegTree[T: ClassTag](n0: Int)(m: Monoid[T]) {\n\n val n = {\n var n1 = 1\n while (n1 < n0) n1 <<= 1\n n1\n }\n\n val t: Array[T] = Array.fill[T](2 * n - 1)(m.zero)\n\n def set(a: Array[T]): Unit = {\n def rec(k: Int, l: Int, r: Int): T = {\n if (r - l == 1) {\n if (l < a.length) t(k) = a(l)\n else t(k) = m.zero\n return t(k)\n } else {\n t(k) = m.mul(\n rec(2 * k + 1, l, (l + r) / 2),\n rec(2 * k + 2, (l + r) / 2, r)\n )\n return t(k)\n }\n }\n rec(0, 0, n)\n }\n\n def update(k0: Int, v: T): Unit = {\n var k = k0 + (n - 1)\n t(k) = v\n while (k > 0) {\n k = (k - 1) / 2\n t(k) = m.mul(t(2 * k + 1), t(2 * k + 2))\n }\n }\n\n def get(k0: Int): T = {\n return t(k0 + (n - 1))\n }\n\n def query(a: Int, b: Int): T = {\n def rec(k: Int, l: Int, r: Int): T = {\n if (b <= l || r <= a) {\n return m.zero\n } else if (a <= l && r <= b) {\n return t(k)\n } else {\n return m.mul(\n rec(2 * k + 1, l, (l + r) / 2),\n rec(2 * k + 2, (l + r) / 2, r)\n )\n }\n }\n return rec(0, 0, n)\n }\n}\n\nclass ModMul(mod: Int) extends Monoid[Long] {\n def zero = 1L\n def mul(a: Long, b: Long) = a * b % mod\n}\n\n"}, {"source_code": "import scala.collection._\nimport scala.util.Random\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(m) = readInts(1)\n val ps = readBigs(m)\n //val ps = Array.fill(m){ BigInt(Random.nextInt(200000) + 2) }\n val MOD = 1000000007L\n\n var res = BigInt(1)\n for (p <- ps) {\n res = res * p.modPow(m, MOD) % MOD\n }\n\n println(res)\n}\n"}, {"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(m) = readInts(1)\n val ps = readBigs(m)\n val MOD = 1000000007L\n \n val cnts = Array.fill(ps.max.toInt + 1){ 0 }\n var pow = ps.size.toLong\n\n for (p <- ps) {\n val pi = p.toInt\n cnts(pi) += 1\n }\n \n val muls = Array.fill(ps.max.toInt + 1){ 0L }\n for (i <- cnts.indices) {\n if (cnts(i) > 0) {\n muls(i) = (cnts(i) + 1L) * cnts(i) / 2\n }\n }\n\n var res = BigInt(1)\n for (p <- ps.distinct) {\n val pi = p.toInt\n res = res * p.modPow(muls(pi) * (pow - cnts(pi) + 1), MOD) % MOD\n }\n\n println(res)\n}\n"}, {"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(m) = readInts(1)\n val ps = readInts(m)\n val psDist = ps.distinct\n val MOD = 1000000007L\n \n val cnts = Array.fill(ps.max.toInt + 1){ 0 }\n\n for (p <- ps) {\n val pi = p.toInt\n cnts(pi) += 1\n }\n \n val muls = Array.fill(ps.max.toInt + 1){ 0L }\n for (i <- cnts.indices) {\n if (cnts(i) > 0) {\n muls(i) = (cnts(i) + 1L) * cnts(i) / 2\n }\n }\n \n val powsLeft, powsRight = Array.fill(psDist.size){ 0L }\n var powL, powR = 1L\n \n for (i <- psDist.indices) {\n powsLeft(i) = powL\n powL = powL * (cnts(ps(i).toInt) + 1) % (MOD - 1)\n }\n\n for (i <- psDist.indices.reverse) {\n powsRight(i) = powR\n powR = powR * (cnts(ps(i).toInt) + 1) % (MOD - 1)\n }\n\n var res = BigInt(1)\n for (i <- psDist.indices) {\n val p = ps(i)\n res = res * BigInt(p).modPow(BigInt(muls(p)) * powsLeft(i) * powsRight(i), MOD) % MOD\n }\n\n println(res)\n}\n"}], "src_uid": "9a5bd9f937da55c3d26d5ecde6e50280"} {"source_code": "import scala.collection.mutable\n\n/**\n * Created by yangchaozhong on 3/10/15.\n */\nobject CF6B extends App {\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n val n = nextInt\n val m = nextInt\n val c = nextString.charAt(0)\n val matrix = Array.ofDim[Char](n, m)\n\n var minX = -1\n var minY = -1\n var maxX = -1\n var maxY = -1\n\n (0 until n).foreach { i =>\n val s = nextString\n (0 until m).foreach { j =>\n matrix(i)(j) = s.charAt(j)\n\n if (matrix(i)(j) == c) {\n if (minX == -1 && minY == -1) {\n minX = i\n minY = j\n }\n\n maxX = i\n maxY = j\n }\n }\n }\n\n val topLeft = (minX, minY)\n val bottomLeft = (maxX, minY)\n val topRight = (minX, maxY)\n val bottomRight = (maxX, maxY)\n\n var count = 0\n\n // top\n if (minX > 0) {\n val set = mutable.HashSet[Char]()\n (minY to maxY).foreach { j =>\n val color = matrix(minX - 1)(j)\n if (color != '.')\n set += color\n }\n count += set.size\n }\n\n // left\n if (minY > 0) {\n val set = mutable.HashSet[Char]()\n (minX to maxX).foreach { i =>\n val color = matrix(i)(minY - 1)\n if (color != '.')\n set += color\n }\n\n count += set.size\n }\n\n // bottom\n if (maxX < n - 1) {\n val set = mutable.HashSet[Char]()\n (minY to maxY).foreach { j =>\n val color = matrix(maxX + 1)(j)\n if (color != '.')\n set += color\n }\n\n count += set.size\n }\n\n // right\n if (maxY < m - 1) {\n val set = mutable.HashSet[Char]()\n (minX to maxX).foreach { i =>\n val color = matrix(i)(maxY + 1)\n if (color != '.')\n set += color\n }\n count += set.size\n }\n\n out.println(count)\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject BPresidentRoom extends App {\n\n val scanner = new Scanner(System.in)\n\n val rows = scanner.nextInt()\n val cols = scanner.nextInt()\n val col = scanner.next()(0)\n\n val room = Array.ofDim[Char](rows, cols)\n\n for (y <- 0 until rows) yield {\n room(y) = scanner.next().toCharArray\n }\n\n val c = for (y <- 0 until rows;\n x <- 0 until cols;\n p = (y, x) if room(y)(x) == col) yield neighbours(p._1, p._2)\n\n val res: List[(Int, Int)] = c.flatten.toList\n\n println(res.map(i => room(i._1)(i._2)).filter(p => p != '.' && p != col).distinct.size)\n\n def neighbours(x: Int, y: Int): List[(Int, Int)] = {\n def n(a: Int, b: Int): List[(Int, Int)] = if (a < 0 || b < 0 || a >= rows || b >= cols) Nil else List((a, b))\n n(x - 1, y) ++ n(x + 1, y) ++ n(x, y - 1) ++ n(x, y + 1)\n }\n\n}\n"}, {"source_code": "object B6 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m, c) = {\n val tl = tokenizeLine\n Array(tl.nextToken.toInt, tl.nextToken.toInt, tl.nextToken.head)\n }\n val set = cu.Set.empty[Int]\n val room = Array.fill(n)(read.toCharArray)\n val delta = Array((0,1), (-1,0), (1,0), (0,-1))\n for(i <- 0 until n; j <- 0 until m if room(i)(j) == c) {\n for((dx, dy) <- delta) {\n if(i+dx >= 0 && i+dx < n && j+dy >= 0 && j+dy < m && !Array('.', c).contains(room(i+dx)(j+dy)))\n set.add(room(i+dx)(j+dy))\n }\n }\n println(set.size)\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util\nimport java.util._\nimport java.lang._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def solve = {\n val n = nextInt\n val m = nextInt\n val presidentColor = next.toCharArray()(0)\n val cabinet = new Array[Array[Char]](n + 2)\n for (i <- 0 until n + 2) {\n cabinet(i) = new Array[Char](m + 2)\n Arrays.fill(cabinet(i), '.')\n }\n for (i <- 1 to n) {\n val str = next.toCharArray\n for (j <- 1 to m) {\n cabinet(i)(j) = str(j - 1)\n }\n }\n var ans = 0\n val colors = new util.HashSet[Char]()\n val dx = Array(-1, 1, 0, 0)\n val dy = Array(0, 0, -1, 1)\n for (i <- 1 to n) {\n for (j <- 1 to m) {\n if (cabinet(i)(j) == presidentColor) {\n for (k <- 0 until 4) {\n val testedColor = cabinet(i + dx(k))(j + dy(k))\n if (testedColor != presidentColor && testedColor != '.' && !colors.contains(testedColor)) {\n ans += 1\n colors.add(testedColor)\n }\n }\n }\n }\n }\n out.println(ans)\n\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}"}, {"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var in = readLine.split(\" \")\n var Array(n, m) = Array(in(0).toInt, in(1).toInt);\n var c = in(2).head;\n var arr = Array.ofDim[Char](n, m);\n for (i <- 0 until n) {\n arr(i) = readLine.toCharArray();\n }\n //doSomething(array, i, j)\n var set = Set[Char]();\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (arr(i)(j) == c) {\n if (j < m - 1 && arr(i)(j + 1) != '.' && arr(i)(j + 1) != c) {\n set.add(arr(i)(j + 1));\n }\n if (j > 0 && arr(i)(j - 1) != '.' && arr(i)(j - 1) != c) {\n set.add(arr(i)(j - 1));\n }\n if (i < n - 1 && arr(i + 1)(j) != '.' && arr(i + 1)(j) != c) {\n set.add(arr(i + 1)(j));\n }\n if (i > 0 && arr(i - 1)(j) != '.' && arr(i - 1)(j) != c) {\n set.add(arr(i - 1)(j));\n }\n }\n }\n }\n println(set.size);\n }\n\n}"}, {"source_code": "object main extends App with fastIO {\n \n val dx = Array(-1, 0, 1, 0)\n val dy = Array(0, -1, 0, 1)\n \n val Array(n :Int, m :Int, p :String) = readLine split(\" \") map(s => if (s(0).isDigit) s.toInt else s) \n val a = Array.fill(n)(readLine)\n \n def ok(x :Int, y :Int) = x >= 0 && y >= 0 && x < n && y < m \n \n var set = Set[Char]() \n for (i <- 0 until n; j <- 0 until m if a(i)(j) == p(0)) \n for (k <- 0 until 4 if ok(i + dx(k), j + dy(k))) \n set += a(i + dx(k))(j + dy(k))\n \n println(set count(c => c != '.' && c != p(0)))\n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def nextInt :Int = { in.nextToken; in.nval.toInt } \n def nextLong :Long ={ in.nextToken; in.nval.toLong } \n def nextDouble :Double = { in.nextToken; in.nval.toDouble } \n def readLine = bf.readLine\n \n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n \n def flush = out.flush\n}"}, {"source_code": "object P6B {\n def main(args : Array[String]) {\n val Array(nS, mS, cS) = readLine split ' '\n val (n, m, c) = (nS.toInt, mS.toInt, cS.head)\n val a = Array.fill(n){readLine}\n val d = for {\n x <- 0 until n\n y <- 0 until m\n if (a(x)(y) == c)\n (xA, yA) <- Array((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1))\n if (0 <= xA && xA < n)\n if (0 <= yA && yA < m)\n z = a(xA)(yA)\n if (z != '.' && z != c)\n } yield z\n println(d.distinct.size)\n }\n}\n"}, {"source_code": "object P6B {\n def main(args : Array[String]) {\n val Array(nS, mS, cS) = readLine split ' '\n val (n, m, c) = (nS.toInt, mS.toInt, cS.head)\n val a = Array.fill(n){readLine}\n val d = for {\n x <- 0 until n\n y <- 0 until m\n if (a(x)(y) == c)\n (xA, yA) <- Array((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1))\n if (0 <= xA && xA < n)\n if (0 <= yA && yA < m)\n z = a(xA)(yA)\n if (z != '.' && z != c)\n } yield z\n println(d.distinct.size)\n }\n}"}, {"source_code": "import java.util._\nobject B {\n def main(args: Array[String]) = {\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt\n val m = scanner.nextInt\n val color = scanner.nextLine.trim\n val input = for {\n i <- 0 until n\n } yield scanner.nextLine.trim.split(\"\").toVector\n val desks = for {\n i <- 0 until n\n j <- 0 until m\n if input(i)(j) == color\n x <- (i-1).max(0) to (i+1).min(n-1)\n y <- (j-1).max(0) to (j+1).min(m-1)\n if (x - i).abs != (y - j).abs\n } yield input(x)(y)\n println(desks.toSet.filter(c => c != \".\" && c != color).size)\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m, rs) = in.next().split(' ')\n val r = rs.head\n val data = (1 to n.toInt).map(_ => in.next().toCharArray)\n val lineSet = data.foldLeft(Set.empty[Char]) {\n case (set, line) => line.sliding(2).foldLeft(set) {\n case (nSet, Array(x, y)) if x == r || y == r => nSet + y + x\n case (nSet, _) => nSet\n }\n }\n val res = (0 until m.toInt).foldLeft(lineSet) {\n case (set, column) => data.map(_(column)).toArray.sliding(2).foldLeft(set) {\n case (nSet, Array(x, y)) if x == r || y == r => nSet + y + x\n case (nSet, _) => nSet\n }\n } - r - '.'\n println(res.size)\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m, rs) = in.next().split(' ')\n val r = rs.head\n val data = (1 to n.toInt).map(_ => in.next().toCharArray)\n val lineSet = data.foldLeft(Set.empty[Char]) {\n case (set, line) => line.sliding(2).foldLeft(set) {\n case (nSet, Array(x, y)) if (x == r || y == r) && x != '.' && y != '.' => nSet + y + x\n case (nSet, _) => nSet\n }\n }\n val res = (0 until m.toInt).foldLeft(lineSet) {\n case (set, column) => data.map(_(column)).toArray.sliding(2).foldLeft(set) {\n case (nSet, Array(x, y)) if x == r || y == r && x != '.' && y != '.' => nSet + y + x\n case (nSet, _) => nSet\n }\n } - r\n println(res.size)\n}"}, {"source_code": "import java.util.Scanner\n\nobject BPresidentRoom extends App {\n\n val scanner = new Scanner(System.in)\n\n val rows = scanner.nextInt()\n val cols = scanner.nextInt()\n val col = scanner.next()(0)\n\n val room = Array.ofDim[Char](rows, cols)\n\n for (y <- 0 until rows) yield {\n room(y) = scanner.next().toCharArray\n }\n\n val c = for (y <- 0 until rows;\n x <- 0 until cols;\n p = (y, x) if room(y)(x) == col) yield neighbours(p._1, p._2)\n\n val res: List[(Int, Int)] = c.flatten.toList\n\n println(res.map(i => room(i._1)(i._2)).filter(p => p != '.' && p != col).distinct.size)\n\n def neighbours(x: Int, y: Int): List[(Int, Int)] = {\n def n(a: Int, b: Int): List[(Int, Int)] = if (a < 0 || b < 0 || a >= cols || b >= rows) Nil else List((a, b))\n n(x - 1, y) ++ n(x + 1, y) ++ n(x, y - 1) ++ n(x, y + 1)\n }\n\n}\n"}, {"source_code": "object main extends App with fastIO {\n \n val dx = Array(-1, 0, 1, 0)\n val dy = Array(0, -1, 0, 1)\n \n val Array(n :Int, m :Int, p :String) = readLine split(\" \") map(s => if (s(0).isDigit) s.toInt else s) \n val a = Array.fill(n)(readLine)\n \n def ok(x :Int, y :Int) = x >= 0 && y >= 0 && x < n && y < m \n \n var set = Set[Char]() \n for (i <- 0 until n; j <- 0 until m if a(i)(j) == p(0)) \n for (k <- 0 until 4 if ok(i + dx(k), j + dy(k)))\n set += a(i + dx(k))(j + dy(k))\n \n println(set.size)\n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def nextInt :Int = { in.nextToken; in.nval.toInt } \n def nextLong :Long ={ in.nextToken; in.nval.toLong } \n def nextDouble :Double = { in.nextToken; in.nval.toDouble } \n def readLine = bf.readLine\n \n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n \n def flush = out.flush\n}"}], "src_uid": "d7601c9bb06a6852f04957fbeae54925"} {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\nobject B extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val m = in.nextInt()\n val data = in.nextLineInt(m)\n\n var (largest1, largest2, largest3, largest4, largest5) =\n (Int.MinValue, Int.MinValue, Int.MinValue, Int.MinValue, Int.MinValue)\n var (smallest1, smallest2, smallest3, smallest4) = (Int.MaxValue, Int.MaxValue, Int.MaxValue, Int.MaxValue)\n\n data.foreach(d => {\n if (d <= smallest1) {\n smallest4 = smallest3\n smallest3 = smallest2\n smallest2 = smallest1\n smallest1 = d\n } else if (d <= smallest2) {\n smallest4 = smallest3\n smallest3 = smallest2\n smallest2 = d\n } else if (d <= smallest3) {\n smallest4 = smallest3\n smallest3 = d\n } else if (d <= smallest4) {\n smallest4 = d\n }\n if (d >= largest1) {\n largest5 = largest4\n largest4 = largest3\n largest3 = largest2\n largest2 = largest1\n largest1 = d\n } else if (d >= largest2) {\n largest5 = largest4\n largest4 = largest3\n largest3 = largest2\n largest2 = d\n } else if (d >= largest3) {\n largest5 = largest4\n largest4 = largest3\n largest3 = d\n } else if (d >= largest4) {\n largest5 = largest4\n largest4 = d\n } else if (d >= largest5) {\n largest5 = d\n }\n })\n val r1 = smallest1.toLong * smallest2 * smallest3 * smallest4 * largest1\n val r2 = smallest1.toLong * smallest2 * largest1 * largest2 * largest3\n val r3 = largest1.toLong * largest2 * largest3 * largest4 * largest5\n\n /*println((largest1, largest2, largest3, largest4, largest5))\n println((smallest1, smallest2, smallest3, smallest4))\n println(r1, r2, r3)*/\n\n val r = math.max(math.max(r1, r2), r3)\n println(r)\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextLineInt(n: Int): ArrayBuffer[Int] = {\n var data = ArrayBuffer[Int]()\n n.times({\n data += nextInt()\n })\n data\n }\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt).sorted\n\n val ans = (0 until 5)\n .foldLeft(List.empty[Int])((is, i) => i :: (n - i - 1) :: is)\n .distinct\n .combinations(5)\n .foldLeft(Long.MinValue)(_ max _.foldLeft(1L)(_ * an(_)))\n\n println(ans)\n\n }\n}\n"}], "negative_code": [{"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toLong).sorted\n\n // format: off\n val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {\n case Array(a, b) => a * b\n }.toList\n\n val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {\n case Array(a, b) => a * b\n }.toList\n // format: on\n\n val ans = xs.indices.foldLeft(Long.MinValue) {\n case (ans, i) if ys.length >= 1 - i =>\n val x = xs.take(i + 1).product\n val y = ys.takeRight(1 - i).product\n val z = an(n + 2 * i - 3)\n ans max (x * y * z)\n case (ans, _) => ans\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n // format: off\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toLong).sorted\n\n val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {\n case Array(a, b) => a * b\n }.toList\n\n val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {\n case Array(a, b) => a * b\n }.toList\n\n val zs =\n if (xs.length == 2 && ys.length == 1) xs\n else (xs ++ ys).sorted(Ordering.Long.reverse).take(2)\n\n val ans = an(n - 2 * zs.diff(xs).length - 1) * zs.product\n\n println(ans)\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n \n val t = readInt()\n \n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toLong).sorted\n \n val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {\n case Array(a, b) => a * b\n }.toList\n \n val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {\n case Array(a, b) => a * b\n }.toList\n \n val zs = (xs ++ ys).sorted(Ordering.Long.reverse).take(2)\n \n val ans = an(n - 2 * zs.diff(xs).length - 1) * zs.product\n \n println(ans)\n }\n}"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n \n val t = readInt()\n \n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toLong).sorted\n \n val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {\n case Array(a, b) => a * b\n }.toList\n \n val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {\n case Array(a, b) => a * b\n }.toList\n \n \nval zs = \n if (ys.length == 1) \n xs.sorted(Ordering.Long.reverse)\n else \n (xs ++ ys).sorted(Ordering.Long.reverse).take(2)\n\n \n val ans = an(n - 2 * zs.diff(xs).length - 1) * zs.product\n \n println(ans)\n }\n}"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n \n val t = readInt()\n \n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toLong).sorted\n \n val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {\n case Array(a, b) => a * b\n }.toList\n \n val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {\n case Array(a, b) => a * b\n }.toList\n \n val zs = (xs ++ ys).sorted(Ordering.Long.reverse).take(2)\n \n val ans = an(n - zs.diff(xs).length - 1) * zs.product\n \n println(ans)\n }\n}"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt).sorted\n\n val ans = (0 until 4)\n .foldLeft(List.empty[Int])((is, i) => i :: (n - i - 1) :: is)\n .distinct\n .combinations(5)\n .map(_.foldLeft(1L)((p, i) => p * an(i)))\n .toList\n .sorted(Ordering.Long.reverse)\n .head\n\n println(ans)\n\n }\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toLong).sorted\n\n // format: off\n val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {\n case Array(a, b) => a * b\n }.toList\n\n val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {\n case Array(a, b) => a * b\n }.toList\n // format: on\n\n val ans = (0 to xs.length).foldLeft(Long.MinValue) {\n case (product, count) =>\n val x = xs.take(2 - (2 - count).min(ys.length)).product\n val y = ys.takeRight(2 - count).product\n val z = an(n - 2 * (2 - count).min(ys.length) - 1)\n product max (x * y * z)\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\nobject B extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val m = in.nextInt()\n val data = in.nextLineInt(m)\n\n var (largest1, largest2, largest3, largest4, largest5) =\n (Int.MinValue, Int.MinValue, Int.MinValue, Int.MinValue, Int.MinValue)\n var (smallest1, smallest2, smallest3, smallest4) = (Int.MaxValue, Int.MaxValue, Int.MaxValue, Int.MaxValue)\n\n data.foreach(d => {\n if (d <= smallest1) {\n smallest4 = smallest3\n smallest3 = smallest2\n smallest2 = smallest1\n smallest1 = d\n } else if (d <= smallest2) {\n smallest4 = smallest3\n smallest3 = smallest2\n smallest2 = d\n } else if (d <= smallest3) {\n smallest4 = smallest3\n smallest3 = d\n } else if (d <= smallest4) {\n smallest4 = d\n }\n if (d >= largest1) {\n largest5 = largest4\n largest4 = largest3\n largest3 = largest2\n largest2 = largest1\n largest1 = d\n } else if (d >= largest2) {\n largest5 = largest4\n largest4 = largest3\n largest3 = largest2\n largest2 = d\n } else if (d >= largest3) {\n largest5 = largest4\n largest4 = largest3\n largest3 = d\n } else if (d >= largest4) {\n largest5 = largest4\n largest4 = d\n } else if (d >= largest5) {\n largest5 = d\n }\n })\n\n val r1 = smallest1 * smallest2 * smallest3 * smallest4 * largest1\n val r2 = smallest1 * smallest2 * largest1 * largest2 * largest3\n val r3 = largest1 * largest2 * largest3 * largest4 * largest5\n\n /* println((largest1, largest2, largest3, largest4, largest5))\n println((smallest1, smallest2, smallest3, smallest4))\n println(r1, r2, r3)*/\n\n val r = math.max(math.max(r1, r2), r3)\n println(r)\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextLineInt(n: Int): ArrayBuffer[Int] = {\n var data = ArrayBuffer[Int]()\n n.times({\n data += nextInt()\n })\n data\n }\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}], "src_uid": "a3a64c3c7e9349d6e663c2d8113d2676"} {"source_code": "import scala.collection.mutable\n\nobject D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val ys = readInts(n)\n\n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (can(mid)) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val xs = Array.ofDim[Int](n)\n\n def can(limit: Long): Boolean = {\n var i = 0\n val isUsed = mutable.HashSet.empty[Int]\n var ok = true\n while (i < n) {\n var y = ys(i)\n //println(limit, y)\n while (y > 1 && (y > limit || isUsed(y))) {\n //y = if ((y & 1) == 0) y / 2 else (y - 1) / 2\n y >>= 1\n }\n if (isUsed(y)) {\n ok = false\n i = n\n } else {\n xs(i) = y\n isUsed += y\n }\n i += 1\n }\n ok\n }\n\n val max = binSearch(n, ys.max)\n can(max)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(xs.mkString(\" \"))\n\n Console.flush\n}\n", "positive_code": [{"source_code": "object CF{\n\timport scala.io.StdIn.{readLine, readInt}\n\timport scala.collection.mutable.{Set, PriorityQueue}\n\n\tdef main(args: Array[String]){\n\t\tval n:Int = readInt()\n\t\tval Y: List[Int] = readLine().split(\" \").map(_.toInt).toList\n\n\t\tval s: Set[Int] = Set[Int](Y:_*)\n\t\tval pq: PriorityQueue[Int] = PriorityQueue[Int](Y:_*)\n\n\t\tval fpq = finalpq(pq, s)\n\n\t\tfpq.foreach(println(_))\n\t}\n\n\tdef transform(s:Set[Int], y:Int): Int = y match{\n\t\tcase 0 => 0\n\t\tcase _ if s.contains(y) => transform(s, y/2)\n\t\tcase _ => {\n\t\t\ts += y\n\t\t\ty\n\t\t}\n\t}\n\t\n\tdef finalpq(pq:PriorityQueue[Int], s:Set[Int]): PriorityQueue[Int] = {\n\t\tval head = pq.head\n\t\tval at = transform(s, head)\n\t\tat match{\n\t\t\tcase 0 => pq\n\t\t\tcase _ => {\n\t\t\t\tpq.dequeue()\n\t\t\t\tpq += at\n\t\t\t\tfinalpq(pq, s)\n\t\t\t}\n\t\t}\n\t}\n\t\n}\n"}], "negative_code": [{"source_code": "object CF{\n\timport scala.io.StdIn.{readLine, readInt}\n\timport scala.collection.mutable.{Set, PriorityQueue}\n\n\tdef main(args: Array[String]){\n\t\tval n:Int = readInt()\n\t\tval Y: List[Int] = readLine().split(\" \").map(_.toInt).toList\n\n\t\tval s: Set[Int] = Set[Int](Y:_*)\n\t\tvar pq: PriorityQueue[Int] = PriorityQueue[Int](Y:_*)\n\n\t\tvar at = transform(s, pq.head)\n\n\t\tfinalpq(pq, s)\n\n\t\tpq.foreach(println(_))\n\t}\n\n\tdef transform(s:Set[Int], y:Int): Int = y match{\n\t\tcase 0 => 0\n\t\tcase _ if s.contains(y) => transform(s, y/2)\n\t\tcase _ => {\n\t\t\ts += y\n\t\t\ty\n\t\t}\n\t}\n\t\n\tdef finalpq(pq:PriorityQueue[Int], s:Set[Int]): PriorityQueue[Int] = {\n\t\tval head = pq.head\n\t\tval at = transform(s, head)\n\t\tat match{\n\t\t\tcase 0 => pq\n\t\t\tcase _ => {\n\t\t\t\tpq.dequeue()\n\t\t\t\tpq += at\n\t\t\t\tfinalpq(pq, s)\n\t\t\t}\n\t\t}\n\t}\n\t\n}\n"}], "src_uid": "1ccbcc5986bf7e7272b7dd65e061d66d"} {"source_code": "object Solution extends App{\n val in = scala.io.Source.stdin.getLines()\n in.next()\n val Array(k, m) = in.next().split(\" \").map(_.toInt)\n val a = in.next().split(\" \").map(_.toInt).sorted.take(k).max\n val b = in.next().split(\" \").map(_.toInt).sorted.reverse.take(m).min\n if (a < b) println(\"YES\")\n else println(\"NO\")\n}\n\n ", "positive_code": [{"source_code": "import java.util.Scanner\nimport Array._\n\nobject Codeforces extends App { \n val in = new Scanner(System.in)\n val na = in.nextInt()\n val nb = in.nextInt()\n val k = in.nextInt()\n val m = in.nextInt()\n var a = ofDim[Int](na)\n var b = ofDim[Int](nb)\n for (i <- 0 until na) {\n a(i) = in.nextInt()\n }\n for (i <- 0 until nb) {\n b(i) = in.nextInt()\n }\n if (a(k - 1) < b(nb - m)) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n}"}, {"source_code": "object A572 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(na, nb) = readInts(2)\n val Array(k, m) = readInts(2)\n\n val a = readInts(na)\n val b = readInts(nb)\n\n if(a(k-1) < b(nb-m)) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n}"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _572A extends CodeForcesApp[String]({scanner => import scanner._\n val (na, nb, k, m) = (nextInt, nextInt, nextInt, nextInt)\n val (a, b) = (IndexedSeq.fill(na)(nextInt), IndexedSeq.fill(nb)(nextInt))\n val maxA = a(k-1)\n val remB = b.dropWhile(_ <= maxA)\n if (remB.size >= m) \"YES\" else \"NO\"\n})\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n import scala.collection.mutable.{Map => Dict}\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val Array(na, nb) = readLine().split(\" \").map(_.toInt)\n val Array(k, m) = readLine().split(\" \").map(_.toInt)\n val A = readLine().split(\" \").map(_.toInt)\n val B = readLine().split(\" \").map(_.toInt)\n\n if (k > A.length || m > B.length || A.take(k).last >= B.takeRight(m).head) println(\"NO\") else println(\"YES\")\n}\n"}, {"source_code": "import scala.util.control.Breaks._\n\nobject GukiZ {\n def main(args: Array[String]) {\n val firstLine = scala.io.StdIn.readLine()\n val arraysLength = firstLine.split(\" \") map (_.toInt)\n val aLength: Int = arraysLength(0)\n val bLength: Int = arraysLength(1)\n val secondLine = scala.io.StdIn.readLine()\n val limits = secondLine.split(\" \") map (_.toInt)\n val k: Int = limits(0)\n val m: Int = limits(1)\n val thirdLine = scala.io.StdIn.readLine()\n val arrayA = thirdLine.split(\" \") map (_.toInt)\n val fourthLine = scala.io.StdIn.readLine()\n val arrayB = fourthLine.split(\" \") map (_.toInt)\n var mayor = false\n \n for (i <- 0 until k) {\n breakable{for(j <- (bLength-m) until bLength){\n if (arrayA(i) >= arrayB(j))\n mayor = true\n break\n }}\n \n }\n if (mayor)\n println(\"NO\")\n else\n println(\"YES\")\n\n }\n\n}"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject Vraag1 {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def main(args: Array[String]) {\n val _ = readInts()\n val km = readInts()\n val a = readInts\n val b = readInts\n val k = km(0)\n val m = km(1)\n if (a(k-1) < b.reverse(m-1)) println(\"YES\") else println(\"NO\")\n \n \n }\n \n}"}], "negative_code": [{"source_code": "object A572 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(na, nb) = readInts(2)\n val Array(k, m) = readInts(2)\n\n val a = readInts(na)\n val b = readInts(nb)\n\n if(a(m-1) < b(nb-m)) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n// val Array(na, nb) = readLine().split(\" \").map(_.toInt)\n// val Array(k, m) = readLine().split(\" \").map(_.toInt)\n// val A = readLine().split(\" \").map(_.toInt)\n// val B = readLine().split(\" \").map(_.toInt)\n val k = 5\n val m = 2\n val A = Array(1, 1, 1, 1, 1)\n val B = Array(2, 2)\n\n if (k > A.length || m > B.length || A.take(k).last >= B.takeRight(m).head) println(\"NO\") else println(\"YES\")\n}\n"}, {"source_code": "object GukiZ {\n def main(args: Array[String]) {\n val firstLine = scala.io.StdIn.readLine()\n val arraysLength = firstLine.split(\" \") map (_.toInt)\n val aLength: Int = arraysLength(0)\n val bLength: Int = arraysLength(1)\n val secondLine = scala.io.StdIn.readLine()\n val limits = secondLine.split(\" \") map (_.toInt)\n val k: Int = limits(0)\n val m: Int = limits(1)\n val thirdLine = scala.io.StdIn.readLine()\n val arrayA = thirdLine.split(\" \") map (_.toInt)\n val fourthLine = scala.io.StdIn.readLine()\n val arrayB = fourthLine.split(\" \") map (_.toInt)\n var mayor = false\n \n for (i <- 0 until k) {\n for(j <- 0 until m){\n if (arrayA(i) >= arrayB(j))\n mayor = true\n }\n \n }\n if (mayor)\n println(\"NO\")\n else\n println(\"YES\")\n\n }\n\n}"}, {"source_code": "object GukiZ {\n def main(args:Array[String]){\n val firstLine = scala.io.StdIn.readLine()\n val arraysLength = firstLine.split(\" \") map (_.toInt)\n val aLength:Int = arraysLength(0)\n val bLength:Int = arraysLength(1)\n val secondLine = scala.io.StdIn.readLine() \n val limits = secondLine.split(\" \") map (_.toInt)\n val k:Int = limits(0)\n val m:Int = limits(1)\n val thirdLine = scala.io.StdIn.readLine() \n val arrayA = thirdLine.split(\" \") map (_.toInt)\n val fourthLine = scala.io.StdIn.readLine() \n val arrayB = fourthLine.split(\" \") map (_.toInt)\n \n if(arrayA(k-1) >= arrayB(0))\n println(\"NO\")\n else println(\"YES\")\n }\n \n}"}, {"source_code": "object GukiZ {\n def main(args: Array[String]) {\n val firstLine = scala.io.StdIn.readLine()\n val arraysLength = firstLine.split(\" \") map (_.toInt)\n val aLength: Int = arraysLength(0)\n val bLength: Int = arraysLength(1)\n val secondLine = scala.io.StdIn.readLine()\n val limits = secondLine.split(\" \") map (_.toInt)\n val k: Int = limits(0)\n val m: Int = limits(1)\n val thirdLine = scala.io.StdIn.readLine()\n val arrayA = thirdLine.split(\" \") map (_.toInt)\n val fourthLine = scala.io.StdIn.readLine()\n val arrayB = fourthLine.split(\" \") map (_.toInt)\n var mayor = false\n val startFor = aLength - (k)\n \n for (i <- 0 until k) {\n for(j <- 0 until m){\n if (arrayA(i) >= arrayB(j))\n mayor = true\n }\n \n }\n if (mayor)\n println(\"NO\")\n else\n println(\"YES\")\n\n }\n\n}"}], "src_uid": "8e0581cce19d6bf5eba30a0aebee9a08"} {"source_code": "//package codeforces.contests._1407\n\nobject Ahahahahahahahaha {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n\n val n = io.StdIn.readInt()\n val seq = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val ones = seq.count(_ == 1)\n\n if (ones <= n / 2) {\n println(s\"${n / 2}\\n${(1 to n/2).map(_ => 0).mkString(\" \")}\")\n } else {\n val req = if ((n / 2) % 2 == 0) n / 2 else n / 2 + 1\n println(s\"$req\\n${(1 to req).map(_ => 1).mkString(\" \")}\")\n }\n }\n }\n}\n", "positive_code": [{"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val m = n / 2\n val an = readLine()\n\n val zeros = an.count(_ == '0')\n\n if (zeros >= m) {\n println(m)\n println(\"0 \" * m)\n } else {\n // format: off\n println(m + m % 2)\n println(\"1 \" * (m + m % 2))\n }\n }\n}\n"}, {"source_code": "/**\n * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools\n */\n\nimport scala.io.StdIn._\n\nobject Main {\n def f(ayes: Array[Int]): Array[Int] = {\n val n = ayes.length\n val cnt1 = ayes.count(x => x == 1)\n val cnt0 = n - cnt1\n\n val res = if (cnt1 <= n / 2)\n for (_ <- 0 until cnt0) yield 0\n else\n for (_ <- 0 until (cnt1 - cnt1 % 2)) yield 1\n\n res.toArray\n }\n\n def main(args: Array[String]): Unit = {\n // Write your solution here\n val t = readInt\n\n for (_ <- 0 until t) {\n val _ = readInt\n val ayes = readLine.split(\" \").map(_.toInt)\n val result = f(ayes)\n println(result.length)\n println(result.mkString(\" \"))\n }\n }\n}"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val m = n / 2\n val an = readLine()\n\n val (ones, zeros) = (an.count(_ == '1'), an.count(_ == '0'))\n\n if (zeros >= m) {\n println(m)\n println(\"0 \" * m)\n } else if (m % 2 == 0) {\n println(m)\n println(\"1 \" * m)\n } else {\n println(m + 1)\n println(\"1 \" * (m + 1))\n }\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1407\n\nobject Ahahahahahahahaha {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n\n val n = io.StdIn.readInt()\n val seq = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val ones = seq.count(_ == 1)\n\n if (ones <= n / 2) {\n println(s\"${n / 2}\\n${(1 to n/2).map(_ => 0).mkString(\" \")}\")\n } else {\n val req = if ((n / 2) % 2 == 0) n / 2 else n / 2 + 1\n println(s\"${n / 2}\\n${(1 to req).map(_ => 1).mkString(\" \")}\")\n }\n }\n }\n}\n"}, {"source_code": "/**\n* Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools\n*/\n\nimport scala.io.StdIn._\n\nobject Main {\n def isAha(ayes: Array[Int]): Boolean = {\n val n = ayes.length\n\n if (n == 1) {\n ayes(0) == 0\n } else {\n val flippedOthers = for ((a, i) <- ayes.zipWithIndex) yield\n if (i % 2 == 0) a else -a\n flippedOthers.sum == 0\n }\n }\n\n def f(n: Int, ayes: Array[Int]): Array[Int] = {\n if (n == 2) {\n if (isAha(ayes.slice(0, 1))) ayes.slice(0, 1)\n else ayes.slice(1, 2)\n } else if (isAha(ayes)){\n ayes\n } else {\n ayes.slice(2, n)\n }\n }\n\n def main(args: Array[String]): Unit = {\n // Write your solution here\n val t = readInt\n\n for (_ <- 0 until t) {\n val n = readInt\n val ayes = readLine.split(\" \").map(_.toInt)\n val result = f(n, ayes)\n println(result.length)\n println(result.mkString(\" \"))\n }\n }\n}"}, {"source_code": "/**\n * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools\n */\n\nimport scala.io.StdIn._\n\nobject Main {\n def f(ayes: Array[Int]): Array[Int] = {\n val n = ayes.length\n val cnt1 = ayes.count(x => x == 1)\n val cnt0 = n - cnt1\n\n val res = if (cnt1 <= n / 2)\n for (_ <- 0 until cnt0) yield 0\n else\n for (_ <- 0 until (cnt1 - cnt1 % 2)) yield 0\n\n res.toArray\n }\n\n def main(args: Array[String]): Unit = {\n // Write your solution here\n val t = readInt\n\n for (_ <- 0 until t) {\n val _ = readInt\n val ayes = readLine.split(\" \").map(_.toInt)\n val result = f(ayes)\n println(result.length)\n println(result.mkString(\" \"))\n }\n }\n}"}, {"source_code": "/**\n* Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools\n*/\n\nimport scala.io.StdIn._\n\nobject Main {\n def f(n: Int, ayes: Array[Int]): Array[Int] = {\n Array(0)\n }\n\n def main(args: Array[String]): Unit = {\n // Write your solution here\n val t = readInt\n\n for (_ <- 0 until t) {\n val n = readInt\n val ayes = readLine.split(\" \").map(_.toInt)\n val result = f(n, ayes)\n println(result.length)\n println(result.mkString(\" \"))\n }\n }\n}"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine()\n\n val (ones, zeros) = (an.count(_ == '1'), an.count(_ == '0'))\n\n if (n == 2) {\n if (zeros > 0) println(\"1\\n0\")\n else println(\"2\\n1 1\")\n } else {\n if (ones > zeros) println(s\"${n / 2}\\n${\"1 \" * (n / 2)}\")\n else println(s\"${n / 2}\\n${\"0 \" * (n / 2)}\")\n }\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n val (ones, zeros) = (an.count(_ == 1), an.count(_ == 0))\n\n val base = if (ones > zeros) 1 else 0\n val ans = an\n .foldLeft((List.empty[Int], n / 2)) {\n case ((bs, 0), a) => (a :: bs, 0)\n case ((bs, r), a) => if (a == base) (bs, r - 1) else (a :: bs, r)\n }\n ._1\n .reverse\n\n println(n / 2)\n println(ans.mkString(\" \"))\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine()\n\n val (ones, zeros) = (an.count(_ == '1'), an.count(_ == '0'))\n\n val ans = (if (ones > zeros) \"1 \" else \"0 \") * (n / 2)\n\n println(n / 2)\n println(ans.trim)\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine()\n\n val (ones, zeros) = (an.count(_ == '1'), an.count(_ == '0'))\n\n val ans = (if (ones > zeros) \"1 \" else \"0 \") * (n / 2)\n\n println(n / 2)\n println(ans)\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n val (ones, zeros) = (an.count(_ == 1), an.count(_ == 0))\n\n val ans =\n if (ones > zeros) List.fill(n / 2)(1)\n else List.fill(n / 2)(0)\n\n println(n / 2)\n println(ans.mkString(\" \"))\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val m = n / 2\n val an = readLine()\n\n val (ones, zeros) = (an.count(_ == '1'), an.count(_ == '0'))\n\n if (zeros > m) {\n println(m)\n println(\"0 \" * m)\n } else if (m % 2 == 0) {\n println(m)\n println(\"1 \" * m)\n } else {\n println(m + 1)\n println(\"1 \" * (m + 1))\n }\n }\n}\n"}, {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val an = readLine().split(\" \").map(_.toInt)\n\n val (ones, zeros) = (an.count(_ == 1), an.count(_ == 0))\n\n val ans =\n if (ones == n) List.fill(n)(1)\n else if (ones > zeros) List.fill(n / 2)(1)\n else List.fill(n / 2)(0)\n\n println(n / 2)\n println(ans.mkString(\" \"))\n }\n}\n"}], "src_uid": "eca92beb189c4788e8c4744af1428bc7"} {"source_code": "object C1183 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var q = readInt\n while (q > 0) {\n val Array(k, n, a, b) = readLongs(4)\n var res = -1L\n var s = 0L\n var e = math.min(n, k / a)\n while (s <= e) {\n val mid = (e + s) / 2\n if (k > (mid * a) + ((n - mid) * b)) {\n res = mid\n s = mid + 1\n } else {\n e = mid - 1\n }\n }\n out.println(res)\n q -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "object _1183C extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val queries = io.read[Seq[(Long, Long, Long, Long)]]\n\n val ans = queries map { case (k, n, a, b) =>\n val x = ((k - b*n)/(1.0 * (a - b))).ceil.toLong - 1\n (x max - 1) min n\n }\n\n io.writeLines(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "2005224ffffb90411db3678ac4996f84"} {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = StdIn.readLine.toInt\n val a = (0 until n).map(_ => StdIn.readLine)\n val b = a.sortWith((x, y) => x.length < y.length)\n val result = !(1 until n).exists(i => !b(i).contains(b(i-1)))\n if (result) {\n println(\"YES\")\n b.foreach(println(_))\n } else {\n println(\"NO\")\n }\n }\n}\n", "positive_code": [{"source_code": "\nobject problemA {\n import java.io.{BufferedReader, FileInputStream, InputStreamReader}\n import scala.collection.mutable.ArrayBuffer\n import scala.collection.mutable\n import scala.util.control.Breaks._\n import scala.collection.JavaConverters._\n\n val source = System.in\n implicit val reader = new BufferedReader(new InputStreamReader(source))\n\n def read()(implicit reader: BufferedReader): String = reader.readLine().split(\" \")(0)\n def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(\" \")\n def readString()(implicit reader: BufferedReader): String = reader.readLine()\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readArray().map(_.toInt)\n var a = new Array[String](n)\n for (i <- 0 until n) a(i) = readString()\n\n a = a.sortWith((p1, p2) => p1.length < p2.length)\n for (i <- 0 until n - 1) {\n if (!a(i + 1).contains(a(i))) {\n print(\"NO\")\n return\n }\n }\n\n println(\"YES\")\n a.foreach(println(_))\n }\n}\n"}, {"source_code": "/**\n * @author ShankarShastri\n * Algorithm: CF_486_DIV3_B (http://codeforces.com/contest/988/problem/B)\n */\n\nimport scala.io.StdIn._\nimport scala.annotation.tailrec\n\nobject CF_486_DIV3_B {\n\n @tailrec\n def subStringVerifier(list: List[String]): Boolean = {\n if(list.length == 0 || list.length == 1) true\n else if(list.length == 2) {\n if(list.last.contains(list.head)) true\n else false\n } else {\n list match {\n case head :: tail if tail.head.contains(head)=> subStringVerifier(tail)\n case _ => false\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n val n = readInt()\n\n val list = (1 to n).map{ _ =>\n readLine\n }.toList\n val createdList = list.sortBy(_.length)\n if(subStringVerifier(createdList)) {\n println(\"YES\")\n createdList.map(println)\n } else {\n println(\"NO\")\n }\n }\n}\n"}], "negative_code": [], "src_uid": "5c33d1f970bcc2ffaea61d5407b877b2"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, p) = in.next().split(' ').map(_.toInt)\n val str = in.next()\n if (n == 1) {\n val candidate = (str.head + 1).toChar\n if (candidate - 'a' >= p)\n println(\"NO\")\n else\n println(candidate)\n } else if (n == 2) {\n println((str.last + 1 until ('a' + p)).find(i => i != str.head) match {\n case Some(x) => str.head.toString + x\n case None if str.head + 1 < 'a' + p => (str.head + 1).toChar.toString + 'a'\n case None => \"NO\"\n })\n } else {\n println(str.indices.reverse.find{\n case (index) =>\n (str(index) + 1 until ('a' + p)).exists(i => index == 0 ||\n (str(index - 1) != i && (index == 1 || str(index - 2) != i)))\n } match {\n case None => \"NO\"\n case Some(index) =>\n val l = (str(index) + 1 until ('a' + p)).find(i => index == 0 ||\n (str(index - 1) != i && (index == 1 || str(index - 2) != i))).map(_.toChar).get\n val prefix = l :: str.toCharArray.take(index).toList.reverse\n (index + 1 until n).foldLeft(prefix) {\n case (pref, i) => ('a' to ('a' + p).toChar).find(i => !pref.take(2).contains(i)).get :: pref\n }.reverse.mkString\n })\n }\n\n\n}", "positive_code": [{"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 07.09.14.\n */\nobject C extends App {\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n val p = nextInt\n val s = nextString\n val as = \"qwertyuiopasdfghjklzxcvbnm\".sorted.take(p)\n if(p == 1) {\n out.print(\"NO\")\n } else {\n def getCandidates(s: String, start: Char) = s.length match {\n case 0 => as.dropWhile(_ < start)\n case 1 => as.dropWhile(_ < start).filterNot(c => c == s(0))\n case n => as.dropWhile(_ < start).filterNot(c => c == s(n - 1) || c == s(n - 2))\n }\n def tryFill(s: String, start: Char, size: Int): (String, Boolean) = {\n if(size == 0) {\n (s, true)\n } else {\n val cs = getCandidates(s, start)\n if(cs.isEmpty) {\n (\"\", false)\n } else {\n var found = false\n var res = (\"\", false)\n for(i <- 0 until cs.length if(!found)) {\n val trySuffix = tryFill(s + cs(i), 'a', size - 1)\n if(trySuffix._2 == true) {\n found = true\n res = trySuffix\n }\n }\n res\n }\n }\n }\n var found = false\n var res = (\"NO\", false)\n for(i <- n - 2 to -1 by(-1) if(!found)) {\n val start = (s(i + 1).toInt + 1).toChar\n val trySuffix = tryFill(s.take(i + 1), start, n - i - 1)\n if(trySuffix._2 == true) {\n found = true\n res = trySuffix\n }\n }\n out.print(res._1)\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, p) = in.next().split(' ').map(_.toInt)\n val str = in.next()\n if (n == 1) {\n val candidate = (str.head + 1).toChar\n if (candidate - 'a' >= p)\n println(\"NO\")\n else\n println(candidate)\n } else if (n == 2) {\n println((str.last + 1 until ('a' + p)).find(i => i != str.head) match {\n case Some(x) => str.head.toString + x\n case None if str.head + 1 < 'a' + p => (str.head + 1).toChar.toString + 'a'\n case None => \"NO\"\n })\n } else {\n println(str.reverse.sliding(3).zipWithIndex.find{\n case (str, index) =>\n (str.head + 1 until ('a' + p)).exists(i => i != str(1) && i != str(2))\n } match {\n case None => \"NO\"\n case Some((_, index)) =>\n val l = (str(index) + 1 until ('a' + p)).find(i => i != str(1) && i != str(2)).map(_.toChar).get\n val prefix = l :: str.toCharArray.take(n - index - 1).toList.reverse\n (0 until index).foldLeft(prefix) {\n case (pref, i) => ('a' to ('a' + p).toChar).find(i => !pref.take(2).contains(i)).get :: pref\n }.reverse.mkString\n })\n }\n\n\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, p) = in.next().split(' ').map(_.toInt)\n val str = in.next()\n if (n == 1) {\n val candidate = (str.head + 1).toChar\n if (candidate - 'a' >= p)\n println(\"NO\")\n else\n println(candidate)\n } else if (n == 2) {\n println((str.last + 1 until ('a' + p)).find(i => i != str.head) match {\n case Some(x) => str.head.toString + x\n case None if str.head + 1 < 'a' + p => (str.head + 1).toChar.toString + 'a'\n case None => \"NO\"\n })\n } else {\n println(str.indices.reverse.find{\n case (index) =>\n (str(index) + 1 until ('a' + p)).exists(i => index == 0 ||\n ((str(index - 1) != i) && (index == 1 || str(index - 2) != i)))\n } match {\n case None => \"NO\"\n case Some(index) =>\n val l = (str(index) + 1 until ('a' + p)).find(i => index == 0 ||\n ((index == 1 || str(index - 1) != i) && (index == 2 || str(index - 2) != i))).map(_.toChar).get\n val prefix = l :: str.toCharArray.take(index).toList.reverse\n (index + 1 until n).foldLeft(prefix) {\n case (pref, i) => ('a' to ('a' + p).toChar).find(i => !pref.take(2).contains(i)).get :: pref\n }.reverse.mkString\n })\n }\n\n\n}"}], "src_uid": "788ae500235ca7b7a7cd320f745d1070"} {"source_code": "import scala.io.StdIn\nimport scala.util.control.Breaks\n\nobject Main extends App{\n\n val k = StdIn.readLine.toInt\n for (i <- 0 until k) {\n val n = StdIn.readLine.toInt\n val arr = StdIn.readLine.split(\" \").map(_.toInt).sorted(Ordering.Int.reverse)\n\n var res = 0\n var key = true\n var j = 0\n while (key && j < n) {\n if ( j < arr(j) )\n res += 1\n else\n key = false\n j += 1\n }\n\n// arr.foreach(it => print(s\"$it \"))\n println(res)\n }\n\n}\n", "positive_code": [{"source_code": "object A {\n def main(args: Array[String]): Unit = {\n val k = scala.io.StdIn.readInt()\n val result = for (i <- 1 to k) yield {\n val test = new A\n test.solution\n }\n println(result.mkString(\"\\n\"))\n }\n}\n\nclass A {\n\n def solution(): Int = {\n val n = scala.io.StdIn.readInt()\n val numbers = scala.io.StdIn.readLine().split(\" \")\n val planks = for (number <- numbers) yield number.toInt\n maxSquare(planks.sortWith(_ < _), 0)\n }\n\n private def maxSquare(planks: Array[Int], i: Int): Int = {\n if (i >= planks.length) 0\n else (planks.length - i).min(planks(i)).max(maxSquare(planks, i + 1))\n }\n\n}\n\n"}, {"source_code": "\n\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_599_A { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n //runTest(Test.sa1)\n //debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading \n val k = readLine.int\n \n for(i <- 1 to k) {\n val n = readLine.int\n val planks = new Array[Int](n)\n val lp = readLine\n for (p <- 0 until n) {\n planks(p) = lp.int\n }\n \n val st = planks.sorted.reverse\n var res = 0\n var min = st(0)\n for(p <- 0 until st.size) {\n if (st(p) < min) min = st(p)\n if (min >= (p+1)) res = p+1 \n }\n outLn(res)\n }\n \n// debug(\"n = \" + n)\n \n //---------------------------- parameters reading :end \n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Long) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n Console.flush()\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4\n5\n4 3 1 4 5\n4\n4 4 4 4\n3\n1 1 1\n5\n5 5 1 1 5\n\"\"\"\n\nval sa2 = \"\"\"\n101\n\"\"\"\n\nval sa3 = \"\"\"\n10100\n\"\"\"\n }\n}\n\n"}, {"source_code": "object _1243A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val plans = io.read[Vector[Int]].sorted(desc[Int])\n\n val ans = plans.zipWithIndex map {\n case (l, i) => l min (i + 1)\n }\n\n io.write(ans.max)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {printer.print(obj); this}\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "09236a3faa7fce573a4e5e758287040f"} {"source_code": "/**\n * @author ShankarShastri\n * Algorithm: CF_485_DIV_2_1 (http://codeforces.com/contest/987/problem/A)\n */\n\n//package programming\n\nimport scala.io.StdIn._\nimport scala.annotation.tailrec\n\nobject CF_485_DIV_2_1 {\n\n// the Power Gem of purple color,\n// the Time Gem of green color,\n// the Space Gem of blue color,\n// the Soul Gem of orange color,\n// the Reality Gem of red color,\n// the Mind Gem of yellow color.\n\n\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val thanosMap = Map[String, String]((\"purple\", \"Power\"), (\"green\", \"Time\"), (\"blue\", \"Space\"),\n (\"orange\", \"Soul\"), (\"red\", \"Reality\"), (\"yellow\",\"Mind\"))\n if(n == 0) {\n println(thanosMap.size)\n thanosMap.values.map(println(_))\n } else {\n val mapResult = (0 until n).foldLeft(thanosMap)((a,b) => {\n val k = readLine\n a - k\n })\n println(mapResult.size)\n mapResult.values.map(println(_))\n }\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val dist = Map(\"purple\" -> \"Power\", \"green\" -> \"Time\", \"blue\" -> \"Space\",\n \"orange\" -> \"Soul\", \"red\" -> \"Reality\", \"yellow\" -> \"Mind\")\n val m = StdIn.readLine.toInt\n val noNeed = (0 until m).map(_ => StdIn.readLine).map(dist(_))\n val all = dist.values\n val need = all.map(item => if (noNeed.contains(item)) None else Some(item))\n println(need.count(_.isDefined))\n need.foreach(_.foreach(println(_)))\n }\n}\n"}, {"source_code": "object tanya extends App{\nvar a = readInt\nvar sum = 7 \nval stones = scala.collection.mutable.Map(\"purple\" -> \"Power\", \"green\" -> \"Time\", \"blue\" -> \"Space\", \"orange\" -> \"Soul\", \"red\" -> \"Reality\", \"yellow\" -> \"Mind\")\n\nfor(i <- 0 to a){\n val stone = readLine\n stones -= stone\n sum = sum - 1\n}\nprintln(sum)\nstones.values.map(println(_))\n}\n\n"}, {"source_code": "object A extends App {\n val l = List(\n \"purple\" -> \"Power\",\n \"green\" -> \"Time\",\n \"blue\" -> \"Space\",\n \"orange\" -> \"Soul\",\n \"red\" -> \"Reality\",\n \"yellow\" -> \"Mind\"\n )\n\n val n = scala.io.StdIn.readInt()\n val cs = (0 until n).foldLeft(List.empty[String])((cs, _) => scala.io.StdIn.readLine() :: cs)\n\n val m = l.foldLeft(List.empty[String]) { case (rs, (c, r)) =>\n if (cs.contains(c)) rs\n else r :: rs\n }\n\n println(m.length)\n println(m.mkString(\"\\n\"))\n}\n\n"}], "negative_code": [{"source_code": "/**\n * @author ShankarShastri\n * Algorithm: CF_485_DIV_2_1 (http://codeforces.com/contest/987/problem/A)\n */\n\n//package programming\n\nimport scala.io.StdIn._\nimport scala.annotation.tailrec\n\nobject CF_485_DIV_2_1 {\n\n// the Power Gem of purple color,\n// the Time Gem of green color,\n// the Space Gem of blue color,\n// the Soul Gem of orange color,\n// the Reality Gem of red color,\n// the Mind Gem of yellow color.\n\n\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val thanosMap = Map[String, String]((\"purple\", \"Power\"), (\"green\", \"Time\"), (\"blue\", \"Space\"),\n (\"orange\", \"Soul\"), (\"red\", \"Reality\"), (\"yellow\",\"Mind\"))\n if(n == 0) {\n println(thanosMap.size)\n thanosMap.values.map(println(_))\n } else {\n val mapResult = (0 until n).foldLeft(thanosMap)((a,b) => {\n val k = readLine\n println(a - k)\n a - k\n })\n println(mapResult.size)\n mapResult.values.map(println(_))\n }\n }\n}\n"}], "src_uid": "7eff98fbcf4e4a3284e2d2f98351fe4a"} {"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val s = readLine()\r\n\r\n def definitely(pf: PartialFunction[(Char, Int), Int]): Seq[Int] = s.zipWithIndex.collect(pf)\r\n\r\n val first =\r\n definitely {\r\n case ('0' | '?', i) if i % 2 == 1 => i\r\n case ('1' | '?', i) if i % 2 == 0 => i\r\n } applyOrElse (5, (_: Int) => 9)\r\n\r\n val second =\r\n definitely {\r\n case ('0' | '?', i) if i % 2 == 0 => i\r\n case ('1' | '?', i) if i % 2 == 1 => i\r\n } applyOrElse (5, (_: Int) => 9)\r\n\r\n val answer = (first min second) + 1\r\n\r\n println(answer)\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val s = readLine()\r\n\r\n val a = s.zipWithIndex.collect {\r\n case ('0' | '?', i) if i % 2 == 1 => i\r\n case ('1' | '?', i) if i % 2 == 0 => i\r\n }\r\n val b = s.zipWithIndex.collect {\r\n case ('0' | '?', i) if i % 2 == 0 => i\r\n case ('1' | '?', i) if i % 2 == 1 => i\r\n }\r\n\r\n val ans = (a.applyOrElse(5, (_: Int) => 9) min b.applyOrElse(5, (_: Int) => 9)) + 1\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "ba1aa2483f88164c1f281eebaab2cfbd"} {"source_code": "object A extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(x1, y1, x2, y2) = readLine().split(\" \").map(_.toInt)\n\n val t1 = (x2 - x1).abs\n val t2 = (y2 - y1).abs\n\n val ans = t1 + t2 + (if (t1 == 0 || t2 == 0) 0 else 2)\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val x1, y1, x2, y2 = nextLong\n val dx = Math.abs(x1 - x2)\n val dy = Math.abs(y1 - y2)\n val n = if (dx == 0) dy\n else if (dy == 0) dx\n else dx + dy + 2\n\n out.println(n)\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "6a333044e2ed8f9f4fa44bc16b994418"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N, X = ni()\n var lastBlow, eachHit = -1e9.toInt\n REP(N) { _ =>\n val d, h = ni()\n lastBlow = max(d, lastBlow)\n eachHit = max(eachHit, d - h)\n }\n debug(s\"lastBlow:$lastBlow eachHit:$eachHit\")\n if (eachHit <= 0 && X > lastBlow) out.println(-1)\n else {\n val remain = X - lastBlow\n if (remain > 0) {\n val ans = (remain + eachHit - 1) / eachHit + 1\n out.println(ans)\n } else {\n out.println(1)\n }\n }\n }\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val input = new Scanner(System.in);\n val t = input.nextInt()\n for (_ <- 0 until t) {\n val n = input.nextInt()\n val x = input.nextInt()\n val d = new Array[Int](n)\n val h = new Array[Int](n)\n\n for (i <- 0 until n) {\n d(i) = input.nextInt()\n h(i) = input.nextInt()\n }\n var max = Int.MinValue;\n for (i <- 0 until n) {\n max = Math.max(max, d(i))\n }\n var max2 = Int.MinValue;\n for (i <- 0 until n) {\n max2 = Math.max(max2, d(i) - h(i))\n }\n var ans = 0\n if(max >= x){\n ans = 1\n }else /* max < x */{\n if(max2 <= 0){\n ans = -1;\n }else{\n val rem = x - max;\n ans = 1\n ans += (rem + max2 -1)/max2\n }\n }\n\n System.out.println(ans)\n\n }\n }\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n\n import scala.io.Codec\n class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next() = tokenizer().get.nextToken()\n\n override def hasNext = tokenizer().nonEmpty\n\n override def close() = reader.close()\n }\n\n}"}, {"source_code": "object B {\n\n def main(args: Array[String]): Unit = {}\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(t) = readInts(1)\n\n for (_ <- 1 to t) {\n val Array(n, x) = readInts(2)\n val blows = Array.fill(n) {\n readLongs(2)\n }\n val maxD = blows.map(_.head).max\n val maxKill = blows.map(b => b(0) - b(1)).max\n val rem = x - maxD\n val res = if (rem <= 0) 1 else if (maxKill <= 0) -1 else 1 + (rem + maxKill - 1) / maxKill\n println(res)\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\n\nobject Main extends App {\n import scala.io.StdIn._\n val t = readInt()\n for (_ ← 0 until t) {\n val Array(n, x) = readLine.trim.split(' ').map(_.toInt)\n val blows = Array.fill(n){\n val Array(d, h) = readLine.trim.split(' ').map(_.toInt)\n Blow(d, h)\n }\n val fatal = blows.maxBy{_.damage}.damage\n if (x > fatal) {\n blows.filter(b ⇒ b.damage > b.heal) match {\n case e if e.nonEmpty ⇒\n val efficient = e.maxBy(_.pureDamage)\n println((x - fatal + efficient.pureDamage - 1) / efficient.pureDamage + 1)\n case _ ⇒ println(-1)\n }\n }else {\n println(1)\n }\n }\n}\ncase class Blow(damage: Long, heal: Long) {\n def pureDamage: Long = damage - heal\n}"}], "negative_code": [], "src_uid": "36099a612ec5bbec1b95f2941e759c00"} {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val s = scala.io.StdIn.readLine().sorted\n\n val (a, b) = s.splitAt(k)\n val (ah, al) = (a.head.toString, a.last.toString)\n\n val ans =\n if (ah != al || b.isEmpty) al\n else {\n val (bh, bl) = (b.head.toString, b.last.toString)\n\n ah + (if (bh != bl) b else bh * ((n - 1) / k))\n }\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val s = scala.io.StdIn.readLine().sorted\n\n val ans =\n if (s(0) != s(k - 1) || k == n) s(k - 1).toString\n else if (s(k) != s(n - 1)) s(0).toString + s.slice(k, n)\n else s(0) + s(k).toString * ((n - 1) / k)\n\n println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val s = scala.io.StdIn.readLine().sorted\n\n def lexical(str: String, pref: String = \"\"): String =\n if (str.isEmpty) pref\n else {\n val (l, r) = str.splitAt(k)\n\n lexical(r, pref + l.last)\n }\n\n val ans = lexical(s)\n\n println(ans)\n }\n}\n"}], "src_uid": "df778e55a2c676acca7311d885f61d7a"} {"source_code": "//package solutions\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\nimport scala.collection.mutable\n\n/**\n * @author traff\n */\n\n\nobject SolTaskC extends App {\n override def main(args: Array[String]): Unit = {\n val out = new PrintWriter(System.out)\n\n run(new Scanner(System.in), out)\n\n out.close()\n }\n\n def run(s: Scanner, out: PrintWriter): Unit = {\n\n val n = s.nextInt()\n val k = s.nextInt()\n\n\n val a = new Array[Int](n)\n val b = new Array[Int](n)\n\n for (i <- a.indices) {\n a(i) = s.nextInt()\n }\n\n for (i <- b.indices) {\n b(i) = s.nextInt()\n }\n\n val d = a.zip(b).map(d => d._1 - d._2).zipWithIndex.sortWith((a, b) => a._1 < b._1)\n\n var res = 0\n d.take(k).foreach(t => {\n res += a(t._2)\n b(t._2) = Integer.MAX_VALUE\n a(t._2) = 0\n })\n\n res += a.zip(b).foldLeft(0)((s, b) => s + math.min(b._1, b._2))\n\n out.println(res)\n\n }\n\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\n/**\n * Created by huangdongfa on 17/3/7.\n */\nobject App {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt\n val k = scanner.nextInt\n val a = new Array[Int](n)\n val b = new Array[Int](n)\n for (i <- a.indices) a(i) = scanner.nextInt\n for (j <- b.indices) b(j) = scanner.nextInt\n\n val sum = a.zip(b).sortWith((a, b) => a._1 - a._2 < b._1 - b._2).zipWithIndex.foldLeft(0) {(s, c) => {\n if (c._2 < k || c._1._1 - c._1._2 < 0) {\n s + c._1._1\n }\n else {\n s + c._1._2\n }\n }}\n System.out.println(sum)\n }\n}\n"}], "negative_code": [], "src_uid": "b5355e1f4439b198d2cc7dea01bc4bc3"} {"source_code": "import scala.io.Source\n\nobject CF338A {\n def main(args: Array[String]) {\n val r = Source.stdin.bufferedReader()\n var ss = r.readLine().split(\" \")\n val n = ss(0).toInt\n val m = ss(1).toInt\n val b = new Array[Boolean](m)\n for (i <- 0 until n) {\n ss = r.readLine().split(\" \")\n val k = ss(0).toInt\n for (j <- 1 until k + 1) {\n val index = ss(j).toInt\n b(index - 1) = true\n }\n }\n var result = \"YES\"\n for (i <- 0 until m) {\n if (!b(i)) {\n result = \"NO\"\n }\n }\n println(result)\n }\n}\n", "positive_code": [{"source_code": "/*\nimport java.io.FileInputStream\nimport java.io.PrintStream\nimport java.io.FileOutputStream\n*/\n\nobject bulbs{\n val MAX_M = 105\n\n def main(args: Array[String]): Unit = {\n\n //System.setIn(new FileInputStream(\"src/bulbs.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"src/bulbs.out\")))\n\n\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n var open = Array.fill[Boolean](MAX_M)(false)\n for(i <- 1 to n) {\n val (Array(nb), bulbs) = readLine.split(\" \").map(_.toInt).splitAt(1)\n for(j <- 0 until nb) {\n open(bulbs(j)) = true\n }\n }\n\n var close_all = \"YES\"\n for(i <- 1 to m) {\n if(!open(i)) {\n close_all = \"NO\"\n }\n }\n println(close_all)\n }\n}"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) {\n val Array(n, m) = StdIn.readLine().split(\" \").map(_.toInt)\n val s = new mutable.BitSet()\n for (i <- 0 until n) {\n StdIn.readLine().split(\" \").map(_.toInt - 1).drop(1).foreach(s.add(_))\n }\n println(if (s.size == m) \"YES\" else \"NO\")\n }\n}\n"}, {"source_code": "\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject Main extends App {\n val arr = Console.in.readLine().split(' ')\n val n = arr(0).toInt\n val q = arr(1).toInt\n val bulbsState = new Array[Boolean](q)\n for(i <- 0 until n){\n val arr = Console.in.readLine().split(' ')\n val c = arr(0).toInt\n for(j <- 1 to c){\n bulbsState(arr(j).toInt - 1) = true\n }\n }\n var flag = true\n for(b <- bulbsState if b == false) flag = false\n println(if(flag) \"YES\" else \"NO\")\n}"}, {"source_code": "import scala.collection.immutable.HashSet\nimport scala.io.StdIn\n\n/**\n * Created by shvedchikov on 13.01.16.\n */\nobject Codeforces extends App {\n override def main(args: Array[String]) {\n lamps()\n }\n\n // http://codeforces.com/problemset/problem/615/A\n def lamps(): Unit = {\n val Array(n, m) = StdIn.readLine().split(\" \").map(_.toInt)\n (1 to n)\n .map(_ => StdIn.readLine().split(\" \").map(_.toInt))\n .foldLeft(HashSet.empty[Int])((all, cur) => all ++ (cur match {\n case Array(xi: Int, rest @_*) if rest.length.equals(xi) => rest\n case _ => Seq.empty[Int]\n })).size match {\n case `m` => print(\"YES\")\n case _ => print(\"NO\")\n }\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\n/**\n * Created by hsleep on 2016. 1. 8..\n */\nobject ASolution extends App {\n val Array(numOfButtons, numberOfBulbs) = StdIn.readLine().split(' ').map(_.toInt)\n\n val setOfBulbs: mutable.Set[Int] = mutable.Set[Int]()\n for {\n i <- 0 until numOfButtons\n if setOfBulbs.size != numberOfBulbs\n } {\n setOfBulbs ++= StdIn.readLine().split(' ').map(_.toInt).tail\n }\n\n setOfBulbs.size == numberOfBulbs match {\n case true => println(\"YES\")\n case _ => println(\"NO\")\n }\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m) = readInts(2)\n \n val lamps = mutable.Set.empty[Int]\n \n for (_ <- 1 to n) {\n lamps ++= readLine.split(\" \").map(_.toInt).drop(1)\n }\n\n println(if (lamps.size == m) \"YES\" else \"NO\")\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val lamps = Array.ofDim[Boolean](m)\n (1 to n).foreach { _ =>\n in.next().split(' ').map(_.toInt - 1).tail.foreach(j => lamps(j) = true)\n }\n if (lamps.forall(_ == true))\n println(\"YES\")\n else\n println(\"NO\")\n}\n"}, {"source_code": "object A615 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val isOn = Array.fill(m)(false)\n for(i <- 0 until n) {\n val tl = tokenizeLine\n val number = tl.nextToken.toInt\n val input = Array.fill(number)(tl.nextToken.toInt)\n for(j <- input.indices) {\n isOn(input(j)-1) = true\n }\n }\n\n println(if(isOn.forall(identity)) \"YES\" else \"NO\")\n }\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _615A extends CodeForcesApp {\n override type Result = Boolean\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val (n, m) = (nextInt(), nextInt())\n val bulbs = ((1 to n) flatMap {i =>\n Seq.fill(nextInt())(nextInt())\n }).toSet\n (1 to m) forall bulbs.contains\n }\n\n override def format(result: Boolean) = if (result) \"YES\" else \"NO\"\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n val mod: Int = 1000000007\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Author: Svyatoslav Ilinskiy\n * Date: 08.01.16.\n */\nobject Problem1 {\n\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val numButtons = sc.nextInt()\n val numBulbs = sc.nextInt()\n val bulbs = new Array[Boolean](numBulbs)\n (0 until numButtons).foreach { _ =>\n val numBulbsByThisButton = sc.nextInt()\n (0 until numBulbsByThisButton).foreach { _ =>\n bulbs.update(sc.nextInt() - 1, true)\n }\n }\n val res =\n if (bulbs.forall(b => b)) \"YES\"\n else \"NO\"\n println(res)\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val m = sc.nextInt()\n sc.nextLine()\n\n var bulb = new Array[Boolean](m+1)\n for(i <- 1 to n){\n val x = sc.nextInt()\n for(j <- 1 to x){\n val tmp = sc.nextInt()\n bulb(tmp) = true\n }\n }\n\n var flag = true\n for(i <- 1 to m)\n flag &= bulb(i)\n\n if(flag)\n println(\"YES\")\n else\n println(\"NO\")\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\n/**\n * Created by hsleep on 2016. 1. 8..\n */\nobject ASolution extends App {\n val Array(numOfButtons, numberOfBulbs) = StdIn.readLine().split(' ').map(_.toInt)\n\n val setOfBulbs: mutable.Set[Int] = mutable.Set[Int]()\n for {\n i <- 0 until numOfButtons\n if setOfBulbs.size != numberOfBulbs\n } {\n setOfBulbs ++= StdIn.readLine().split(' ').map(_.toInt)\n }\n\n setOfBulbs.size == numberOfBulbs match {\n case true => println(\"YES\")\n case _ => println(\"NO\")\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val m = sc.nextInt()\n sc.nextLine()\n\n var bulb = new Array[Boolean](m+1)\n for(i <- 1 to n){\n val x = sc.nextLine().split(' ').map(_.toInt)\n\n for(e <- x)\n bulb(e) = true\n }\n\n var flag = true\n for(i <- 1 to m)\n flag &= bulb(i)\n\n if(flag)\n println(\"YES\")\n else\n println(\"NO\")\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val m = sc.nextInt()\n sc.nextLine()\n\n var bulb = new Array[Boolean](m+1)\n for(i <- 1 to n){\n try{\n val x = sc.nextLine().split(' ').map(_.toInt)\n for(e <- x)\n bulb(e) = true\n }\n catch{\n case e: NumberFormatException => ()\n }\n }\n\n var flag = true\n for(i <- 1 to m)\n flag &= bulb(i)\n\n if(flag)\n println(\"YES\")\n else\n println(\"NO\")\n }\n}\n"}], "src_uid": "9438ce92e10e846dd3ab7c61a1a2e3af"} {"source_code": "import io.StdIn.readLine\n\nobject testing {\n def main(args: Array[String]): Unit = {\n val T = readLine().toInt\n for(_ <- 1 to T) {\n val N = readLine().toLong\n if((N & (N-1)) == 0){\n println(\"NO\")\n }else{\n println(\"YES\")\n }\n }\n }\n}", "positive_code": [{"source_code": "object Main {\r\n\r\n def main(args: Array[String]): Unit = {\r\n import io.StdIn.readLine\r\n\r\n val t = readLine().toInt\r\n for (_ <- 1 to t) {\r\n val n = readLine().toLong\r\n val answer =\r\n if ((n & (n - 1)) == 0)\r\n \"NO\"\r\n else\r\n \"YES\"\r\n println(answer)\r\n }\r\n }\r\n\r\n}"}], "negative_code": [], "src_uid": "f4958b4833cafa46fa71357ab1ae41af"} {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val s = readLine\n\n var res = 0L\n var w = 0L\n var wo = 0L\n\n for (i <- 1 until s.length) {\n if (s(i) == 'v' && s(i - 1) == 'v') {\n res += wo\n w += 1\n } else if (s(i) == 'o') {\n wo += w\n }\n }\n\n println(res)\n}\n", "positive_code": [{"source_code": "object _1178B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val s = io.read[String]\n .replace(\"ovo\", \"oo\")\n .replace(\"ov\", \"o,v\")\n .replace(\"vo\", \"v,o\")\n .split(\",\")\n .view\n .map(t => if (t.startsWith(\"v\")) ('w', t.length - 1) else ('o', t.length))\n\n @tailrec\n def solve(i: Int, wc: Long, owc: Long, wowc: Long): Long = {\n if (i < 0) {\n wowc\n } else {\n s(i) match {\n case ('w', w) => solve(i - 1, wc = wc + w, owc = owc , wowc = wowc + w*owc)\n case ('o', o) => solve(i - 1, wc = wc , owc = owc + o*wc, wowc = wowc)\n case _ => throw new IllegalStateException()\n }\n }\n }\n\n val ans = solve(i = s.length - 1, wc = 0, owc = 0, wowc = 0)\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "6cc6db6f426bb1bce59f23bfcb762b08"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 998244353\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n var cur, next = Array.ofDim[Long](4, 2001) // 0: BB, 1: BW, 2: WB, 3:WW\n cur(0)(1) = 1\n cur(1)(2) = 1\n cur(2)(2) = 1\n cur(3)(1) = 1\n\n rep(N - 1) { x =>\n rep(4) { i =>\n rep(4) { j =>\n rep(x * 2 + 3) { k =>\n val pls =\n if (i == 1 || i == 2) {\n // BW\n // WB\n if (i == 1 && j == 2 || i == 2 && j == 1) 2\n // BB\n // WB\n else 0\n } else {\n // Ww\n // WB\n if (i != j) 1\n // Ww\n // WW\n else 0\n }\n\n if (k + pls <= 2000) next(j)(k + pls) = (next(j)(k + pls) + cur(i)(k)) % MOD\n }\n }\n }\n\n val t = cur\n cur = next\n next = t\n rep(4)(i => java.util.Arrays.fill(next(i), 0))\n }\n\n val ans = cur.map(_(K)).sum\n out.println(ans % MOD)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 998244353\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n var cur, next = Array.ofDim[Long](4, 2001) // 0: BB, 1: BW, 2: WB, 3:WW\n cur(0)(1) = 1\n cur(1)(2) = 1\n cur(2)(2) = 1\n cur(3)(1) = 1\n\n rep(N - 1) { _ =>\n rep(4) { i =>\n rep(4) { j =>\n rep(2001) { k =>\n val pls =\n if (i == 1 || i == 2) {\n // BW\n // WB\n if (i == 1 && j == 2 || i == 2 && j == 1) 2\n // BB\n // WB\n else 0\n } else {\n // Ww\n // WB\n if (i != j) 1\n // Ww\n // WW\n else 0\n }\n\n if (k + pls <= 2000) next(j)(k + pls) = (next(j)(k + pls) + cur(i)(k)) % MOD\n }\n }\n }\n\n val t = cur\n cur = next\n next = t\n rep(4)(i => java.util.Arrays.fill(next(i), 0))\n }\n\n val ans = cur.map(_(K)).sum\n out.println(ans % MOD)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}], "negative_code": [], "src_uid": "7e6a2329633ee283e3327413114901d1"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.util.Sorting\n\n/**\n * @author Arthur Gazizov (Cinarra Systems)\n * Created on 24.06.17.\n */\nobject Main {\n def main(args: Array[String]): Unit = {\n var out: PrintWriter = null\n var in: CodeforcesReader = null\n out = new PrintWriter(new OutputStreamWriter(System.out))\n in = new CodeforcesReaderWithStringTokenizerImpl(new BufferedReader(new InputStreamReader(System.in)))\n IOUtils.init(in)\n val solver = new Solver()\n solver.solve(1, in, out)\n in.close()\n out.close()\n }\n\n class Solver {\n def calculateSum(cost: Array[Long], m: Int): Long = {\n var tmp = cost.clone()\n for (i <- cost.indices) {\n tmp(i) += (i + 1L) * m\n }\n Sorting.quickSort(tmp)\n var sum = 0L\n for (i <- 0 until m) {\n sum += tmp(i)\n }\n sum\n }\n\n def f(cost: Array[Long], m: Int, have: Long): Boolean = {\n calculateSum(cost, m) <= have\n }\n\n def solve(testNumber: Int, in: CodeforcesReader, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val have = in.nextLong()\n val cost = IOUtils.nextLongArray(n)\n var hi = n\n var lo = 0\n while (hi - lo > 3) {\n var m = (hi + lo) / 2\n if (!f(cost, m, have)) {\n hi = m\n } else {\n lo = m\n }\n }\n while (lo < n && f(cost, lo + 1, have)) {\n lo += 1\n }\n out.print(lo + \" \" + calculateSum(cost, lo))\n }\n }\n\n class CodeforcesReaderWithStringTokenizerImpl(reader: BufferedReader) extends CodeforcesReader {\n private var tokenizer: StringTokenizer = _\n\n override def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(reader.readLine())\n }\n tokenizer.nextToken()\n }\n\n override def nextInt(): Int = {\n next().toInt\n }\n\n override def nextLong(): Long = {\n next().toLong\n }\n\n override def nextDouble(): Double = {\n next().toDouble\n }\n override def close(): Unit = {\n tokenizer = null\n reader.close()\n }\n }\n\n abstract class CodeforcesReader() extends Closeable {\n def next(): String\n\n def nextInt(): Int\n\n def nextLong(): Long\n\n def nextDouble(): Double\n }\n\n object IOUtils {\n private var in: CodeforcesReader = _\n\n def init(codeforcesReader: CodeforcesReader): Unit = {\n this.in = codeforcesReader\n }\n\n def nextIntArray(size: Int): Array[Int] = {\n val ret = new Array[Int](size)\n for (i <- ret.indices) {\n ret(i) = in.nextInt()\n }\n ret\n }\n\n def nextLongArray(size: Int): Array[Long] = {\n val ret = new Array[Long](size)\n for (i <- ret.indices) {\n ret(i) = in.nextLong()\n }\n ret\n }\n\n def nextDoubleArray(size: Int): Array[Double] = {\n val ret = new Array[Double](size)\n for (i <- ret.indices) {\n ret(i) = in.nextDouble()\n }\n ret\n }\n\n def nextStringArray(size: Int): Array[String] = {\n val ret = new Array[String](size)\n for (i <- ret.indices) {\n ret(i) = in.next()\n }\n ret\n }\n }\n\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.util.Sorting\n\n/**\n * @author Arthur Gazizov (Cinarra Systems)\n * Created on 24.06.17.\n */\nobject Main {\n def main(args: Array[String]): Unit = {\n var out: PrintWriter = null\n var in: CodeforcesReader = null\n out = new PrintWriter(new OutputStreamWriter(System.out))\n in = new CodeforcesReaderWithStringTokenizerImpl(new BufferedReader(new InputStreamReader(System.in)))\n IOUtils.init(in)\n val solver = new Solver()\n solver.solve(1, in, out)\n in.close()\n out.close()\n }\n\n class Solver {\n def calculateSum(cost: Array[Long], m: Int): Long = {\n var tmp = cost.clone()\n for (i <- cost.indices) {\n tmp(i) += (i + 1L) * m\n }\n Sorting.quickSort(tmp)\n var sum = 0L\n for (i <- 0 until m) {\n sum += tmp(i)\n }\n sum\n }\n\n def f(cost: Array[Long], m: Int, have: Long): Boolean = {\n calculateSum(cost, m) <= have\n }\n\n def solve(testNumber: Int, in: CodeforcesReader, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val have = in.nextLong()\n val cost = IOUtils.nextLongArray(n)\n var hi = n\n var lo = 0\n while (hi - lo > 3) {\n var m = (hi + lo) / 2\n if (!f(cost, m, have)) {\n hi = m\n } else {\n lo = m\n }\n }\n while (lo < n && f(cost, lo + 1, have)) {\n lo += 1\n }\n out.print(lo + \" \" + calculateSum(cost, lo))\n }\n }\n\n class CodeforcesReaderWithStringTokenizerImpl(reader: BufferedReader) extends CodeforcesReader {\n private var tokenizer: StringTokenizer = _\n\n override def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(reader.readLine())\n }\n tokenizer.nextToken()\n }\n\n override def nextInt(): Int = {\n next().toInt\n }\n\n override def nextLong(): Long = {\n next().toLong\n }\n\n override def nextDouble(): Double = {\n next().toDouble\n }\n\n override def close(): Unit = {\n tokenizer = null\n reader.close()\n }\n }\n\n abstract class CodeforcesReader() extends Closeable {\n def next(): String\n\n def nextInt(): Int\n\n def nextLong(): Long\n\n def nextDouble(): Double\n }\n\n object IOUtils {\n private var in: CodeforcesReader = _\n\n def init(codeforcesReader: CodeforcesReader): Unit = {\n this.in = codeforcesReader\n }\n\n def nextIntArray(size: Int): Array[Int] = {\n val ret = new Array[Int](size)\n for (i <- ret.indices) {\n ret(i) = in.nextInt()\n }\n ret\n }\n\n def nextLongArray(size: Int): Array[Long] = {\n val ret = new Array[Long](size)\n for (i <- ret.indices) {\n ret(i) = in.nextLong()\n }\n ret\n }\n\n def nextDoubleArray(size: Int): Array[Double] = {\n val ret = new Array[Double](size)\n for (i <- ret.indices) {\n ret(i) = in.nextDouble()\n }\n ret\n }\n\n def nextStringArray(size: Int): Array[String] = {\n val ret = new Array[String](size)\n for (i <- ret.indices) {\n ret(i) = in.next()\n }\n ret\n }\n }\n\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.util.Sorting\n\n/**\n * @author Arthur Gazizov (Cinarra Systems)\n * Created on 24.06.17.\n */\nobject Main {\n def main(args: Array[String]): Unit = {\n var out: PrintWriter = null\n var in: CodeforcesReader = null\n out = new PrintWriter(new OutputStreamWriter(System.out))\n in = new CodeforcesReaderWithStringTokenizerImpl(new BufferedReader(new InputStreamReader(System.in)))\n IOUtils.init(in)\n val solver = new Solver()\n solver.solve(1, in, out)\n in.close()\n out.close()\n }\n\n class Solver {\n def calculateSum(cost: Array[Long], m: Int): Long = {\n var tmp = cost.clone()\n for (i <- cost.indices) {\n tmp(i) += (i + 1L) * m\n }\n Sorting.quickSort(tmp)\n var sum = 0L\n for (i <- 0 until m) {\n sum += tmp(i)\n }\n sum\n }\n\n def f(cost: Array[Long], m: Int, have: Long): Boolean = {\n calculateSum(cost, m) <= have\n }\n\n def solve(testNumber: Int, in: CodeforcesReader, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val have = in.nextLong()\n val cost = IOUtils.nextLongArray(n)\n var hi = n\n var lo = 0\n while (hi - lo > 3) {\n var m = (hi + lo) / 2\n if (!f(cost, m, have)) {\n hi = m\n } else {\n lo = m\n }\n }\n while (lo < n && f(cost, lo + 1, have)) {\n lo += 1\n }\n out.print(lo + \" \" + calculateSum(cost, lo))\n }\n }\n\n class CodeforcesReaderWithStringTokenizerImpl(reader: BufferedReader) extends CodeforcesReader {\n private var tokenizer: StringTokenizer = _\n\n override def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(reader.readLine())\n }\n tokenizer.nextToken()\n }\n\n override def nextInt(): Int = {\n next().toInt\n }\n\n override def nextLong(): Long = {\n next().toLong\n }\n\n override def nextDouble(): Double = {\n next().toDouble\n }\n override def close(): Unit = {\n tokenizer = null\n reader.close()\n }\n }\n\n abstract class CodeforcesReader() extends Closeable {\n def next(): String\n\n def nextInt(): Int\n\n def nextLong(): Long\n\n def nextDouble(): Double\n }\n\n object IOUtils {\n private var in: CodeforcesReader = _\n\n def init(codeforcesReader: CodeforcesReader): Unit = {\n this.in = codeforcesReader\n }\n\n def nextIntArray(size: Int): Array[Int] = {\n val ret = new Array[Int](size)\n for (i <- ret.indices) {\n ret(i) = in.nextInt()\n }\n ret\n }\n\n def nextLongArray(size: Int): Array[Long] = {\n val ret = new Array[Long](size)\n for (i <- ret.indices) {\n ret(i) = in.nextLong()\n }\n ret\n }\n\n def nextDoubleArray(size: Int): Array[Double] = {\n val ret = new Array[Double](size)\n for (i <- ret.indices) {\n ret(i) = in.nextDouble()\n }\n ret\n }\n def nextStringArray(size: Int): Array[String] = {\n val ret = new Array[String](size)\n for (i <- ret.indices) {\n ret(i) = in.next()\n }\n ret\n }\n }\n\n}"}], "negative_code": [], "src_uid": "b1fd037d5ac6023ef3250fc487656db5"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val t = ni()\n rep(t) { _ =>\n val s, a, b, c = nl()\n val d = s / c\n val ans = (d / a) * b + d\n out.println(ans)\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}", "positive_code": [{"source_code": "object CF1065A extends App {\n\n val t = readInt()\n\n (1 to t) foreach(n => {\n val Array(s, a, b, c) = readLine().split(\" \").map(_.toLong)\n\n var count = s/c + ((s/c)/a)*b\n\n println(count)\n\n })\n}\n"}], "negative_code": [], "src_uid": "ec8060260a6c7f4ff3e6afc9fd248afc"} {"source_code": "import scala.collection.mutable\n\nobject A extends App {\n def readInts = readLine().split(\" \").map(_.toInt)\n\n val Array(n, a, b) = readInts\n val s = readLine\n\n val c1 = s(a-1)\n val c2 = s(b-1)\n\n if (c1 == c2) println(\"0\") else println(\"1\")\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject A extends App {\n\n val Array(n, a, b) = readLine.split(\"\\\\s+\").map(_.toInt - 1)\n\n val airports = readLine.map(e => if (e == '0') 0 else 1)\n\n val sameAirport = airports(a) == airports(b)\n\n val result = if (sameAirport) 0 else 1\n\n println(result)\n\n}\n"}, {"source_code": "object A743 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n var Array(n,a,b) = readInts(3)\n a -= 1\n b -= 1\n val in = read\n if(in(a) == in(b))\n println(\"0\")\n else\n println(\"1\")\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _743A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n, a, b = read[Int]\n val airports = read[String]\n val start = airports(a - 1)\n val end = airports(b - 1)\n\n val ans = if (start == end) 0 else 1\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject A_384 { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n runTest(Test.sa2)\n debugV = true\n// file = File(\"C:\\\\temp\\\\google cj\\\\2014q\\\\c-small.res\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading\n val line1 = readLine \n val n = line1.int\n val a = line1.int\n val b = line1.int\n \n val line2 = readLine.string\n \n val res = if (line2(a-1) == line2(b-1)) 0 else 1\n \n outLn(res)\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n4 1 4\n1010\n\"\"\"\n\nval sa2 = \"\"\"\n5 5 2\n10110\n\"\"\"\n\nval sa3 = \"\"\"\n\"\"\"\n}\n\n}\n\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject A extends App{\n\n val Array(n: Int, a: Int, b: Int) = readLine().split(\"\\\\s+\").map(_.toInt - 1)\n\n// val airports = readLine.map(_.toInt)\n val airports = readLine.map(e => if ( e == '0') 0 else 1)\n\n// println(s\"n $n a: $a b: $b\")\n// println(airports.mkString(\",\"))\n\n val sameAirport = airports(a) == airports(b)\n// println(s\"sameAriport: $sameAirport\")\n\n if (sameAirport)\n println(0)\n else {\n val start = a min b\n val stop = a max b\n// println(s\"start: $start, stop: $stop\")\n\n val trip = (airports.drop(start)).dropRight(n - stop)\n// println(trip.mkString(\",\"))\n\n val c1 = trip.head\n val c2 = trip.last\n val cost1 = trip.indexOf(c2)\n val cost2 = trip.reverse.indexOf(c1)\n println( cost1 min cost2)\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject A extends App{\n\n val Array(n: Int, a: Int, b: Int) = readLine().split(\"\\\\s+\").map(_.toInt - 1)\n\n val airports = readLine.map(_.toInt)\n\n// println(s\"n $n a: $a b: $b\")\n// println(airports.mkString(\",\"))\n\n val sameAirport = airports(a) == airports(b)\n// println(s\"sameAriport: $sameAirport\")\n\n if (sameAirport)\n println(0)\n else {\n val start = a min b\n val stop = a max b\n// println(s\"start: $start, stop: $stop\")\n\n val trip = airports.drop(start).dropRight(n + 1 - stop)\n// println(trip.mkString(\",\"))\n\n val c1 = trip.head\n val c2 = trip.last\n val cost1 = trip.indexOf(c2)\n val cost2 = trip.reverse.indexOf(c1)\n println( cost1 min cost2)\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject A extends App{\n\n val Array(n: Int, a: Int, b: Int) = readLine().split(\"\\\\s+\").map(_.toInt - 1)\n\n val airports = readLine.map(_.toInt)\n\n val sameAirport = airports(a) == airports(b)\n\n if (sameAirport)\n println(0)\n else {\n val start = a min b\n val stop = a max b\n val trip = airports.drop(start).dropRight(n - stop)\n val c1 = trip.head\n val c2 = trip.last\n val cost1 = trip.indexOf(c2)\n val cost2 = trip.reverse.indexOf(c1)\n println( cost1 min cost2)\n }\n}\n"}], "src_uid": "081f30ac27739002855e9d2aebe804c7"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n val x = line.count(_ == 'x')\n val y = line.length - x\n\n println(\"x\" * (x - y) + \"y\" * (y - x))\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val s = readLine()\n val xs = s.count(_ == 'x')\n val ys = s.count(_ == 'y')\n \n println(\"x\" * (xs - ys) + \"y\" * (ys - xs))\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n println(line.replaceAll(\"yx\", \"\").replaceAll(\"xy\", \"\"))\n}\n"}], "src_uid": "528459e7624f90372cb2c3a915529a23"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val stones = in.take(n).map(_.split(' ').map(_.toInt).sorted.reverse).toArray\n val map = stones.indices.foldLeft(Map.empty[(Int, Int), List[(Int, Int)]]) {\n case (map, i) =>\n val Array(a, b, c) = stones(i)\n if (a != b && b != c)\n map +\n ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +\n ((a, c) -> ((b -> i) :: map.getOrElse((a, c), Nil))) +\n ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))\n else if (a != b)\n map +\n ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +\n ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))\n else if (b != c)\n map +\n ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +\n ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))\n else\n map +\n ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil)))\n }.map(i => i._1 -> i._2.sortBy(_._1).reverse)\n\n val oneStoneSolution = stones.indices.maxBy(i => stones(i).last)\n val twoStoneSolution = stones.indices.flatMap{ i =>\n val Array(a, b, c) = stones(i)\n List((a, b, c), (b, c, a), (a, c, b))\n .flatMap(pair => map((pair._1, pair._2)).find(j => j._2 != i).map(el => Math.min(pair._2, pair._3 + el._1) -> (i, el._2)))\n }\n\n if (twoStoneSolution.nonEmpty) {\n val twoStoneS = twoStoneSolution.maxBy(_._1)\n if (twoStoneS._1 > stones(oneStoneSolution).min) {\n println(2)\n println(s\"${twoStoneS._2._1 + 1} ${twoStoneS._2._2 + 1}\")\n }\n else {\n println(1)\n println(s\"${oneStoneSolution + 1}\")\n }\n }\n else {\n println(1)\n println(s\"${oneStoneSolution + 1}\")\n }\n\n\n\n}\n\n\n", "positive_code": [{"source_code": "\nimport java.io._\n\nimport scala.util._\n\nobject Main {\n\n def main(args: Array[String]) = {\n\n var debug: Object => Unit = null\n\n if (!args.isEmpty && args.head == \"test\") {\n debug = println\n val TEST =\n \"\"\"\n |7\n |10 7 8\n |5 10 3\n |4 2 6\n |5 5 5\n |10 2 8\n |4 2 1\n |7 7 7\n |\"\"\".stripMargin.trim\n\n System.setIn(new ByteArrayInputStream(TEST.getBytes))\n } else {\n debug = a => Unit\n }\n\n val input = scala.io.Source.stdin.getLines()\n\n\n input.next()\n val ps = input.toSeq.map(_.split(' ').map(_.toInt).toSeq.sorted)\n\n val hash = scala.collection.mutable.HashMap.empty[(Int, Int), Seq[Int]]\n\n def put(k: (Int, Int), p: Int) = {\n hash.get(k) match {\n case None => hash.put(k, Seq(p))\n case Some(a) =>\n if (a.length >= 2) {\n if (a(0) < p) hash.put(k, Seq(p, a(0)))\n else if (a(1) < p) hash.put(k, Seq(a(0), p))\n } else if (a.length == 1) {\n if (a(0) < p) hash.put(k, Seq(p, a(0)))\n else hash.put(k, Seq(a(0), p))\n }\n }\n }\n for (p <- ps) {\n val k1 = (p(0), p(1))\n val p1 = p(2)\n val k2 = (p(0), p(2))\n val p2 = p(1)\n val k3 = (p(1), p(2))\n val p3 = p(0)\n put(k1, p1)\n if (k2 != k1) put(k2, p2)\n if (k3 != k1 && k3 != k2) put(k3, p3)\n }\n\n val pair = hash.maxBy(e=> Seq(e._1._1, e._1._2, e._2.sum).min)\n\n val first = ps.indexOf(Seq(pair._1._1, pair._1._2, pair._2(0)).sorted)\n\n debug(pair)\n debug(Seq(pair._1._1, pair._1._2, pair._2(0)).mkString)\n debug(first + \"\")\n\n val sol = if (pair._2.size == 2) {\n val second = ps.zipWithIndex.find(p => p._1 == Seq(pair._1._1, pair._1._2, pair._2(1)).sorted && p._2 != first).get._2\n \"2\\n\" + (first + 1) + \" \" + (second + 1)\n } else {\n \"1\\n\" + (first + 1)\n }\n\n println(sol)\n }\n}\n\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val stones = in.take(n).map(_.split(' ').map(_.toInt).sorted).toArray\n val map = stones.indices.foldLeft(Map.empty[(Int, Int), List[(Int, Int)]]) {\n case (map, i) =>\n val Array(a, b, c) = stones(i)\n if (a != b && b != c)\n map +\n ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +\n ((a, c) -> ((b -> i) :: map.getOrElse((a, c), Nil))) +\n ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))\n else if (a != b)\n map +\n ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +\n ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))\n else if (b != c)\n map +\n ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +\n ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))\n else\n map +\n ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil)))\n }.map(i => i._1 -> i._2.sortBy(_._1).reverse)\n\n val oneStoneSolution = stones.indices.maxBy(i => stones(i).last)\n val twoStoneSolution = stones.indices.flatMap{ i =>\n val Array(a, b, c) = stones(i)\n List((a, b, c), (b, c, a), (a, c, b))\n .flatMap(pair => map((pair._1, pair._2)).find(j => j._2 != i).map(el => Math.min(pair._2, pair._3 + el._1) -> (i, el._2)))\n }\n\n if (twoStoneSolution.nonEmpty) {\n val twoStoneS = twoStoneSolution.maxBy(_._1)\n if (twoStoneS._1 > stones(oneStoneSolution).min) {\n println(2)\n println(s\"${twoStoneS._2._1 + 1} ${twoStoneS._2._2 + 1}\")\n }\n else {\n println(1)\n println(s\"${oneStoneSolution + 1}\")\n }\n }\n else {\n println(1)\n println(s\"${oneStoneSolution + 1}\")\n }\n\n\n\n}\n\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val stones = in.take(n).map(_.split(' ').map(_.toInt).sorted).toArray\n val map = stones.indices.foldLeft(Map.empty[(Int, Int), List[(Int, Int)]]) {\n case (map, i) =>\n val Array(a, b, c) = stones(i)\n if (a != b && b != c)\n map +\n ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +\n ((a, c) -> ((b -> i) :: map.getOrElse((a, c), Nil))) +\n ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))\n else if (a != b)\n map +\n ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +\n ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))\n else if (b != c)\n map +\n ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +\n ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))\n else\n map +\n ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil)))\n }.map(i => i._1 -> i._2.sortBy(_._1))\n\n val oneStoneSolution = stones.indices.maxBy(i => stones(i).last)\n val twoStoneSolution = stones.indices.flatMap{ i =>\n val Array(a, b, c) = stones(i)\n List((a, b, c), (b, c, a), (a, c, b))\n .flatMap(pair => map((pair._1, pair._2)).find(j => j._2 != i).map(el => Math.min(pair._2, pair._2 + el._1) -> (i, el._2)))\n }\n\n if (twoStoneSolution.nonEmpty) {\n val twoStoneS = twoStoneSolution.maxBy(_._1)\n if (twoStoneS._1 > stones(oneStoneSolution).min) {\n println(2)\n println(s\"${twoStoneS._2._1 + 1} ${twoStoneS._2._2 + 1}\")\n }\n else {\n println(1)\n println(s\"${oneStoneSolution + 1}\")\n }\n }\n else {\n println(1)\n println(s\"${oneStoneSolution + 1}\")\n }\n\n\n\n}\n\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val stones = in.take(n).map(_.split(' ').map(_.toInt).sorted).toArray\n val map = stones.indices.foldLeft(Map.empty[(Int, Int), List[(Int, Int)]]) {\n case (map, i) =>\n val Array(a, b, c) = stones(i)\n if (a != b && b != c)\n map +\n ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +\n ((a, c) -> ((b -> i) :: map.getOrElse((a, c), Nil))) +\n ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))\n else if (a != b)\n map +\n ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +\n ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))\n else if (b != c)\n map +\n ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +\n ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))\n else\n map +\n ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil)))\n }.map(i => i._1 -> i._2.sortBy(_._1).reverse)\n\n val oneStoneSolution = stones.indices.maxBy(i => stones(i).last)\n val twoStoneSolution = stones.indices.flatMap{ i =>\n val Array(a, b, c) = stones(i)\n List((a, b, c), (b, c, a), (a, c, b))\n .flatMap(pair => map((pair._1, pair._2)).find(j => j._2 != i).map(el => Math.min(pair._2, pair._2 + el._1) -> (i, el._2)))\n }\n\n if (twoStoneSolution.nonEmpty) {\n val twoStoneS = twoStoneSolution.maxBy(_._1)\n if (twoStoneS._1 > stones(oneStoneSolution).min) {\n println(2)\n println(s\"${twoStoneS._2._1 + 1} ${twoStoneS._2._2 + 1}\")\n }\n else {\n println(1)\n println(s\"${oneStoneSolution + 1}\")\n }\n }\n else {\n println(1)\n println(s\"${oneStoneSolution + 1}\")\n }\n\n\n\n}\n\n\n"}, {"source_code": "\nimport java.io._\n\nimport scala.util._\n\nobject Main {\n\n def main(args: Array[String]) = {\n\n var debug: Object => Unit = null\n\n if (!args.isEmpty && args.head == \"test\") {\n debug = println\n val TEST =\n \"\"\"\n |7\n |10 7 8\n |5 10 3\n |4 2 6\n |5 5 5\n |10 2 8\n |4 2 1\n |7 7 7\n |\"\"\".stripMargin.trim\n\n System.setIn(new ByteArrayInputStream(TEST.getBytes))\n } else {\n debug = a => Unit\n }\n\n val input = scala.io.Source.stdin.getLines()\n\n\n input.next()\n val ps = input.toSeq.map(_.split(' ').map(_.toInt).toSeq.sorted)\n\n val hash = scala.collection.mutable.HashMap.empty[(Int, Int), Seq[Int]]\n\n def put(k: (Int, Int), p: Int) = {\n hash.get(k) match {\n case None => hash.put(k, Seq(p))\n case Some(a) =>\n if (a.length >= 2) {\n if (a(0) < p) hash.put(k, Seq(p, a(0)))\n else if (a(1) < p) hash.put(k, Seq(a(0), p))\n } else if (a.length == 1) {\n if (a(0) < p) hash.put(k, Seq(p, a(0)))\n else hash.put(k, Seq(a(0), p))\n }\n }\n }\n for (p <- ps) {\n val k1 = (p(0), p(1))\n val p1 = p(2)\n val k2 = (p(0), p(2))\n val p2 = p(1)\n val k3 = (p(1), p(2))\n val p3 = p(0)\n put(k1, p1)\n if (k2 != k1) put(k2, p2)\n if (k3 != k1 && k3 != k2) put(k3, p3)\n }\n\n val pair = hash.maxBy(e=> e._1._1 * e._1._2 * (e._2.sum))\n\n val first = ps.indexOf(Seq(pair._1._1, pair._1._2, pair._2(0)).sorted)\n\n debug(pair)\n debug(Seq(pair._1._1, pair._1._2, pair._2(0)).mkString)\n debug(first + \"\")\n\n val sol = if (pair._2.size == 2) {\n val second = ps.zipWithIndex.find(p => p._1 == Seq(pair._1._1, pair._1._2, pair._2(1)).sorted && p._2 != first).get._2\n \"2\\n\" + (first + 1) + \" \" + (second + 1)\n } else {\n \"1\\n\" + (first + 1)\n }\n\n println(sol)\n }\n}\n\n"}, {"source_code": "\nimport java.io._\n\nimport scala.util._\n\nobject Main {\n\n def main(args: Array[String]) = {\n\n var debug: Object => Unit = null\n\n if (!args.isEmpty && args.head == \"test\") {\n debug = println\n val TEST =\n \"\"\"\n |7\n |10 7 8\n |5 10 3\n |4 2 6\n |5 5 5\n |10 2 8\n |4 2 1\n |7 7 7\n |\"\"\".stripMargin.trim\n\n System.setIn(new ByteArrayInputStream(TEST.getBytes))\n } else {\n debug = a => Unit\n }\n\n val input = scala.io.Source.stdin.getLines()\n\n\n input.next()\n val ps = input.toSeq.map(_.split(' ').map(_.toInt).toSeq.sorted)\n\n if (ps.length > 72483) {\n println(ps(26990))\n println(ps(72482))\n println(ps(57878))\n println(ps(17744))\n }\n\n val hash = scala.collection.mutable.HashMap.empty[(Int, Int), Seq[Int]]\n\n def put(k: (Int, Int), p: Int) = {\n hash.get(k) match {\n case None => hash.put(k, Seq(p))\n case Some(a) =>\n if (a.length >= 2) {\n if (a(0) < p) hash.put(k, Seq(p, a(0)))\n else if (a(1) < p) hash.put(k, Seq(a(0), p))\n } else if (a.length == 1) {\n if (a(0) < p) hash.put(k, Seq(p, a(0)))\n else hash.put(k, Seq(a(0), p))\n }\n }\n }\n for (p <- ps) {\n val k1 = (p(0), p(1))\n val p1 = p(2)\n val k2 = (p(0), p(2))\n val p2 = p(1)\n val k3 = (p(1), p(2))\n val p3 = p(0)\n put(k1, p1)\n if (k2 != k1) put(k2, p2)\n if (k3 != k1 && k3 != k2) put(k3, p3)\n }\n\n val pair = hash.maxBy(e=> e._1._1 * e._1._2 * (e._2.sum))\n\n val first = ps.indexOf(Seq(pair._1._1, pair._1._2, pair._2(0)).sorted)\n\n debug(pair)\n debug(Seq(pair._1._1, pair._1._2, pair._2(0)).mkString)\n debug(first + \"\")\n\n val sol = if (pair._2.size == 2) {\n val second = ps.zipWithIndex.find(p => p._1 == Seq(pair._1._1, pair._1._2, pair._2(1)).sorted && p._2 != first).get._2\n \"2\\n\" + (first + 1) + \" \" + (second + 1)\n } else {\n \"1\\n\" + (first + 1)\n }\n\n println(sol)\n }\n}\n\n"}, {"source_code": "\nimport java.io._\n\nimport scala.util._\n\nobject Main {\n\n def main(args: Array[String]) = {\n\n var debug: Object => Unit = null\n\n if (!args.isEmpty && args.head == \"test\") {\n debug = println\n val TEST =\n \"\"\"\n |7\n |10 7 8\n |5 10 3\n |4 2 6\n |5 5 5\n |10 2 8\n |4 2 1\n |7 7 7\n |\"\"\".stripMargin.trim\n\n System.setIn(new ByteArrayInputStream(TEST.getBytes))\n } else {\n debug = a => Unit\n }\n\n val input = scala.io.Source.stdin.getLines()\n\n\n input.next()\n val ps = input.toSeq.map(_.split(' ').map(_.toInt).toSeq.sorted)\n\n if (ps.length > 72483) {\n println(ps(26990))\n println(ps(72482))\n }\n\n val hash = scala.collection.mutable.HashMap.empty[(Int, Int), Seq[Int]]\n\n def put(k: (Int, Int), p: Int) = {\n hash.get(k) match {\n case None => hash.put(k, Seq(p))\n case Some(a) =>\n if (a.length >= 2) {\n if (a(0) < p) hash.put(k, Seq(p, a(0)))\n else if (a(1) < p) hash.put(k, Seq(a(0), p))\n } else if (a.length == 1) {\n if (a(0) < p) hash.put(k, Seq(p, a(0)))\n else hash.put(k, Seq(a(0), p))\n }\n }\n }\n for (p <- ps) {\n val k1 = (p(0), p(1))\n val p1 = p(2)\n val k2 = (p(0), p(2))\n val p2 = p(1)\n val k3 = (p(1), p(2))\n val p3 = p(0)\n put(k1, p1)\n if (k2 != k1) put(k2, p2)\n if (k3 != k1 && k3 != k2) put(k3, p3)\n }\n\n val pair = hash.maxBy(e=> e._1._1 * e._1._2 * (e._2.sum))\n\n val first = ps.indexOf(Seq(pair._1._1, pair._1._2, pair._2(0)).sorted)\n\n debug(pair)\n debug(Seq(pair._1._1, pair._1._2, pair._2(0)).mkString)\n debug(first + \"\")\n\n val sol = if (pair._2.size == 2) {\n val second = ps.zipWithIndex.find(p => p._1 == Seq(pair._1._1, pair._1._2, pair._2(1)).sorted && p._2 != first).get._2\n \"2\\n\" + (first + 1) + \" \" + (second + 1)\n } else {\n \"1\\n\" + (first + 1)\n }\n\n println(sol)\n }\n}\n\n"}], "src_uid": "ef82292a6591de818ddda9f426208291"} {"source_code": "object main extends App with fastIO {\n \n val Array(n, k) = readLine split(\" \") map(_.toInt)\n println(readLine.split(\" \").map(_.toInt).count( x => 5 - x >= k) / 3) \n \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}", "positive_code": [{"source_code": "object Solution extends App{\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt).filter(_ <= 5 - k)\n println(data.length / 3)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io._\n\nobject A {\n\n val TEST = false\n\n val in = new java.util.Scanner(System.in)\n\n def nextInt = in.next().toInt\n\n def main(args: Array[String]) {\n val n = nextInt\n val k = nextInt\n\n val arr = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n arr(i) = nextInt\n }\n\n val limit = 5 - k\n val eligible = arr.filter(_ <= limit).length / 3\n println(eligible)\n }\n\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _432A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val k = next.toInt\n val a = (1 to n).map(i => next.toInt).filter(i => i <= 5 - k)\n val ans = a.length / 3\n println(ans)\n}\n"}, {"source_code": "object Solution extends App{\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt).filter(_ <= 5 - k)\n println(data.length / 3)\n}\n"}, {"source_code": "/**\n * Created by andrew on 15.5.14.\n */\nimport io.Source\nimport java.io.PrintWriter\n\nobject cf432a {\n\n def solve(in: In, out: PrintWriter) {\n val n = in().toInt\n val k = in().toInt\n var sum = 0\n for (i <- 1 to n) {\n val x = in().toInt\n if (5 - x >= k) sum += 1\n }\n out.print(sum / 3)\n }\n\n\n def main(args: Array[String]) {\n new Thread(null, new Runnable {\n override def run(): Unit = {\n val in = new In(Source.fromInputStream(System.in))\n val out = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n }, \"cf432a\", 64000000).run()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delim: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() = {\n while (iter.hasNext && delim.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next() = {\n skipDelims()\n\n while (iter.hasNext && delim.indexOf(iter.head) == -1) {\n sb.append(iter.next)\n }\n\n val ret = sb.toString()\n sb.clear()\n\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIter = new TokenIterator(iter, \" \\n\\r\");\n\n def apply() = tokenIter.next()\n }\n}\n"}, {"source_code": "/**\n * Created by andrew on 15.5.14.\n */\nimport io.Source\nimport java.io.PrintWriter\n\nobject cf432a {\n\n def solve(in: In, out: PrintWriter) {\n val n = in().toInt\n val k = in().toInt\n val ans = in(n).map(x => x.toInt).filter(x => 5 - x >= k).size / 3\n out.print(ans)\n }\n\n\n def main(args: Array[String]) {\n new Thread(null, new Runnable {\n override def run(): Unit = {\n val in = new In(Source.fromInputStream(System.in))\n val out = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n }, \"cf432a\", 64000000).run()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delim: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() = {\n while (iter.hasNext && delim.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next() = {\n skipDelims()\n\n while (iter.hasNext && delim.indexOf(iter.head) == -1) {\n sb.append(iter.next)\n }\n\n val ret = sb.toString()\n sb.clear()\n\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIter = new TokenIterator(iter, \" \\n\\r\");\n\n def apply() = tokenIter.next()\n\n def apply(n: Int) = tokenIter.take(n)\n }\n}\n"}, {"source_code": "/**\n * Created by andrew on 15.5.14.\n */\nimport io.Source\nimport java.io.PrintWriter\n\nobject cf432a {\n\n def solve(in: In, out: PrintWriter) {\n val n = in().toInt\n val k = in().toInt\n var sum = 0\n for (i <- 1 to n) {\n val x = in().toInt\n if (5 - x >= k) sum += 1\n }\n out.print(sum / 3)\n }\n\n\n def main(args: Array[String]) {\n /*new Thread(null, new Runnable {\n override def run(): Unit = {\n val in = new In(Source.fromInputStream(System.in))\n val out = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n }, \"cf432a\", 64000000).run()*/\n val in = new In(Source.fromInputStream(System.in))\n val out = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delim: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() = {\n while (iter.hasNext && delim.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next() = {\n skipDelims()\n\n while (iter.hasNext && delim.indexOf(iter.head) == -1) {\n sb.append(iter.next)\n }\n\n val ret = sb.toString()\n sb.clear()\n\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIter = new TokenIterator(iter, \" \\n\\r\");\n\n def apply() = tokenIter.next()\n }\n}\n"}, {"source_code": "object Bla {\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readLine.split(\" \").map(_.toLong)\n// \t\t def roundUp(x: Long) = x / a + (if (x % a > 0) 1 else 0)\n// \t\t println(n * m)\n var a = readLine.split(\" \").map(_.toLong)\n var count = 0\n for (i <- a)\n \t if (5-i>=k)\n \t \t{count = count + 1}\n print(count / 3) \t\n }\n\n}"}, {"source_code": "object A432 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readInts(2)\n val input = readInts(n).map(5-_).count(_ >= k)\n println(input/3)\n }\n}"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by hama_du on 2014/05/18.\n */\nobject ProblemA extends App {\n val in = new Scanner(System.in)\n val n, k = in.nextInt()\n val a = (0 until n).map(_ => in.nextInt()).filter(x => (x+k <= 5))\n println(a.size / 3)\n}\n"}, {"source_code": "// http://codeforces.com/contest/432/problem/A\nobject A extends App {\n val sc = new java.util.Scanner(System.in)\n val n, k = sc.nextInt()\n val p = Array.fill(n)(sc.nextInt()).count(_ <= 5-k)\n println(p / 3)\n}\n"}], "negative_code": [{"source_code": "object Main extends App{\n val in = readLine\n val Array(n, k) = in.split(\" \").map(_.toInt)\n val data = in.split(\" \").map(_.toInt).filter(_ <= 5 - k)\n println(data.length / 3)\n}"}, {"source_code": "object Solution extends App{\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt).filter(_ < 5 - k)\n println(data.length / 3)\n}\n"}], "src_uid": "fbde1e2ee02055592ff72fb04366812b"} {"source_code": "import scala.io.StdIn._\r\nobject Solution {\r\n def main(args: Array[String]): Unit = {\r\n val tcases = readInt\r\n for (tcase <- 1 to tcases) {\r\n val n = readInt\r\n val a = readLine.split(\" \").map(_.toInt)\r\n val m = readInt\r\n// println(readLine.split(\" \").map(_.toInt).reduce((x, y) => x + y) % n)\r\n println(a(readLine.split(\" \").map(_.toInt).reduce((x, y) => (x + y) % n) % n))\r\n }\r\n }\r\n /**/\r\n\r\n /*\r\n * 3 1 4 2\r\n * 1 4 2 3\r\n * 3 1 4 2\r\n * 2 1 5 4 3 (0)\r\n *\r\n * 4 3 2 1 5 (3)\r\n * 2 1 5 4 3\r\n *\r\n *\r\n * 4 3 2 1 5 (3)\r\n * 2 1 5 4 3 (2)\r\n * 1 5 4 3 2 (1)\r\n * 4 3 2 1 5 (2)\r\n * 3 2 1 5 4 (1)\r\n *\r\n * */\r\n}", "positive_code": [{"source_code": "import scala.collection.mutable\r\nimport scala.io.StdIn\r\n\r\nobject Main extends App {\r\n var sb = new mutable.StringBuilder()\r\n val t = StdIn.readLine().toInt\r\n for (_ <- 0 until t) {\r\n val n = StdIn.readLine().toInt\r\n val a = StdIn.readLine().split(\" \").map(_.toInt)\r\n val m = StdIn.readLine().toInt\r\n val b = StdIn.readLine().split(\" \").map(_.toInt)\r\n var index = 0\r\n for (bb <- b) index = (index + bb) % a.length\r\n println(a(index))\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "c9da10199ad1a5358195b693325e628b"} {"source_code": "// To execute Scala code, please define an object named Solution that extends App\r\nimport scala.io.StdIn._\r\nobject Solution extends App {\r\n\r\n private def solve(): Unit = {\r\n val line = readLine().split(\" \").map(_.toInt)\r\n val (n, x, y) = (line(0), line(1), line(2))\r\n\r\n def printResult(streak: Int): Unit = {\r\n var currentWinner = 1\r\n for(i <- 2 to n) {\r\n print(s\"$currentWinner \")\r\n if((i - 1) % streak == 0)\r\n currentWinner = i + 1\r\n\r\n }\r\n println()\r\n }\r\n\r\n if(y != 0 && x == 0 && (n - 1) % y == 0)\r\n printResult(y)\r\n else if(x != 0 && y == 0 && (n - 1) % x == 0)\r\n printResult(x)\r\n else\r\n println(\"-1\")\r\n }\r\n\r\n val test_cases: Int = readInt()\r\n for(i <- 0 until test_cases)\r\n solve()\r\n}\r\n", "positive_code": [{"source_code": "object _1733B extends CodeForcesApp {\n override def solve(io: IO) = io.repeat() {\n val n, x, y = io.nextInt()\n val ans = (x max y, x min y) match {\n case (a, 0) if a > 0 && (n-1)%a == 0 =>\n Seq.tabulate(n-1)(i => 2 + a*(i/a))\n case _ => Nil\n }\n io.printLine(if (ans.isEmpty) -1 else ans.mkString(\" \"))\n }\n}\n/**************************** [Ignore Template Below] **************************************/\ntrait CodeForcesApp {\n def debug(x: => Any): Unit = if (!sys.props.contains(\"ONLINE_JUDGE\")) println(s\">>> DEBUG: $x\")\n def run(io: IO): Unit = try solve(io) finally io.close()\n def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))\n def solve(io: IO): Any\n}\n// Java I/O wrapper\nimport java.io._\nclass IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {\n def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))\n\n val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))\n\n def nextLine(): String = in.readLine()\n def nextStr(): String = tokens.next()\n def nextInt(): Int = nextStr().toInt\n def nextLong(): Long = nextStr().toLong\n def nextDouble(): Double = nextStr().toDouble\n def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }\n\n def print(xs: Any*): this.type = { out.print(xs.mkString(\" \")); this }\n def printLine(xs: Any*): this.type = { out.println(xs.mkString(\" \")); this }\n def printLines(xs: Any*): this.type = { if (xs.isEmpty) out.println() else xs.foreach(out.println); this }\n\n override def close() = out.close()\n}\n"}, {"source_code": "object _1733B extends CodeForcesApp {\n override def solve(io: IO) = io.repeat() {\n val n, x, y = io.nextInt()\n val ans = (x max y, x min y) partialMatch {\n case (a, 0) if a > 0 && (n-1)%a == 0 =>\n var victories = 0\n var winner = 1\n var loser = 2\n\n Seq.fill(n-1) {\n if (victories == a) {\n victories = 0\n winner = loser\n }\n victories += 1\n loser += 1\n winner\n }\n }\n\n io.printLine(ans.map(_.mkString(\" \")).getOrElse(-1))\n }\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n}\n/**************************** [Ignore Template Below] **************************************/\ntrait CodeForcesApp {\n def debug(x: => Any): Unit = if (!sys.props.contains(\"ONLINE_JUDGE\")) println(s\">>> DEBUG: $x\")\n def run(io: IO): Unit = try solve(io) finally io.close()\n def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))\n def solve(io: IO): Any\n}\n// Java I/O wrapper\nimport java.io._\nclass IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {\n def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))\n\n val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))\n\n def nextLine(): String = in.readLine()\n def nextStr(): String = tokens.next()\n def nextInt(): Int = nextStr().toInt\n def nextLong(): Long = nextStr().toLong\n def nextDouble(): Double = nextStr().toDouble\n def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }\n\n def print(xs: Any*): this.type = { out.print(xs.mkString(\" \")); this }\n def printLine(xs: Any*): this.type = { out.println(xs.mkString(\" \")); this }\n def printLines(xs: Any*): this.type = { if (xs.isEmpty) out.println() else xs.foreach(out.println); this }\n\n override def close() = out.close()\n}\n"}], "negative_code": [{"source_code": "// To execute Scala code, please define an object named Solution that extends App\r\nimport scala.io.StdIn._\r\nobject Solution extends App {\r\n\r\n private def solve(): Unit = {\r\n val line = readLine().split(\" \").map(_.toInt)\r\n val (n, x, y) = (line(0), line(1), line(2))\r\n\r\n def printResult(streak: Int): Unit = {\r\n var currentWinner = 1\r\n for(i <- 1 until n) {\r\n print(s\"$currentWinner \")\r\n if(i % streak == 0)\r\n currentWinner += streak + 1\r\n\r\n }\r\n println()\r\n }\r\n\r\n if(y != 0 && x == 0 && (n - 1) % y == 0)\r\n printResult(y)\r\n else if(x != 0 && y == 0 && (n - 1) % x == 0)\r\n printResult(x)\r\n else\r\n println(\"-1\")\r\n }\r\n\r\n val test_cases: Int = readInt()\r\n for(i <- 0 until test_cases)\r\n solve()\r\n}\r\n"}, {"source_code": "// To execute Scala code, please define an object named Solution that extends App\r\nimport scala.io.StdIn._\r\nobject Solution extends App {\r\n\r\n private def solve(): Unit = {\r\n val line = readLine().split(\" \").map(_.toInt)\r\n val (n, x, y) = (line(0), line(1), line(2))\r\n\r\n def printResult(streak: Int): Unit = {\r\n var currentWinner = 1\r\n for(i <- 2 to n) {\r\n print(s\"$currentWinner \")\r\n if(i % streak == 1)\r\n currentWinner = i + 1\r\n\r\n }\r\n println()\r\n }\r\n\r\n if(y != 0 && x == 0 && (n - 1) % y == 0)\r\n printResult(y)\r\n else if(x != 0 && y == 0 && (n - 1) % x == 0)\r\n printResult(x)\r\n else\r\n println(\"-1\")\r\n }\r\n\r\n val test_cases: Int = readInt()\r\n for(i <- 0 until test_cases)\r\n solve()\r\n}\r\n"}, {"source_code": "// To execute Scala code, please define an object named Solution that extends App\r\nimport scala.io.StdIn._\r\nobject Solution extends App {\r\n\r\n private def solve(): Unit = {\r\n val line = readLine().split(\" \").map(_.toInt)\r\n val (n, x, y) = (line(0), line(1), line(2))\r\n\r\n def printResult(streak: Int): Unit = {\r\n var currentWinner = 1\r\n for(i <- 1 to (n - 1)) {\r\n print(s\"$currentWinner \")\r\n if(i % streak == 0)\r\n currentWinner = i + 1\r\n }\r\n println()\r\n }\r\n\r\n if(y != 0 && x == 0 && (n - 1) % y == 0)\r\n printResult(y)\r\n else if(x != 0 && y == 0 && (n - 1) % x == 0)\r\n printResult(x)\r\n else\r\n println(\"-1\")\r\n }\r\n\r\n val test_cases: Int = readInt()\r\n for(i <- 0 until test_cases)\r\n solve()\r\n}\r\n"}], "src_uid": "024d7b1d5f7401080560174003456037"} {"source_code": "\nobject ThreeEightSevenB {\n\n\tdef main(args: Array[String]): Unit = {\n\t\tvar Array(n,m)=readLine.split(' ').map(_.toInt)\n\t\tvar a=readLine.split(' ').map(_.toInt)\n\t\tvar b=readLine.split(' ').map(_.toInt)\n\t\tvar total=n;\n\t\tvar i,j=0;\n\t\twhile(i soFar\n case(first, Nil) => soFar + first.length\n case(x :: xs, y :: ys) if y >= x => count(xs, ys, soFar)\n case(x :: xs, y) => count(xs, y, soFar + 1)\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toInt).sorted.toList.reverse\n val b = in.next().split(' ').map(_.toInt).sorted.toList.reverse\n println(count(a, b, 0))\n}\n"}], "negative_code": [], "src_uid": "bf0422de4347a308d68a52421fbad0f3"} {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn.readLine\nimport scala.collection.immutable.TreeSet\n\n\n\n// object Main {\n// case class Range(s: Long, l: Long) extends Ordered[Range] {\n// def compare(that: Range) = {\n// val t = s + l\n// val tt = that.s + that.l\n// if((s <= that.s && tt <= t) || (that.s <= s && t <= tt))\n// 0\n// else\n// (s - that.s).toInt\n// }\n// }\n// case class State(ts: TreeSet[Range], size: Long)\n// def howMany(r: Range, a: Long) : Long =\n// r match {\n// case Range(s, l) => {\n// val h = l / (a+1)\n// val r = l % (a+1)\n// h + (if(r == a) 1 else 0)\n// }\n// }\n// def split(r: Range, i: Long) : List[Range] =\n// if(r.l == 1)\n// List()\n// else if(r.s == i)\n// List(Range(i+1,r.l-1))\n// else if(r.s+r.l-1 == i)\n// List(Range(r.s,r.l-1))\n// else\n// List(Range(r.s,i-r.s), Range(i+1,r.l-(i-r.s+1)))\n\n// // Document: http://www.scala-lang.org/api/current/#package\n// // -----------------------------------------------------------------------------\n// def main(args: Array[String]) : Unit = {\n// val (n,k,a) = {\n// val nka = readLine().split(\" \").map(_.toLong)\n// (nka(0), nka(1), nka(2))\n// }\n// val m = readLine().toLong\n// val x = readLine().split(\" \").map(_.toLong-1)\n// val ini = Range(0,n)\n// var index = 0\n// var kotae = -1\n// val ans = x.foldLeft(State(TreeSet[Range](ini), howMany(ini,a)))(\n// (state,x) => state match {\n// case State(ts, size) => {\n// index += 1\n// val r = ts.iteratorFrom(Range(x,1)).next()\n// val sub = howMany(r,a)\n// val add_range = split(r,x)\n// val add_cnt = add_range.map(howMany(_,a)).sum\n// val new_ts = add_range.foldLeft(ts-r)((t,a) => t+a)\n// val cnt = size - sub + add_cnt\n// if(cnt < k && kotae == -1){\n// kotae = index\n// }\n// State(new_ts, cnt)\n// }})\n// println(kotae)\n// }\n// }\n\n\nobject Main {\n import scala.collection.mutable.TreeSet\n case class Range(s: Int, l: Int) extends Ordered[Range] {\n def compare(that: Range) = {\n val t = s + l\n val tt = that.s + that.l\n if((s <= that.s && tt <= t) || (that.s <= s && t <= tt))\n 0\n else\n (s - that.s).toInt\n }\n }\n @inline\n def howMany(r: Range, a: Int) : Int =\n r match {\n case Range(s, l) => {\n val h = l / (a+1)\n val r = l % (a+1)\n h + (if(r == a) 1 else 0)\n }\n }\n @inline\n def split(r: Range, i: Int) : List[Range] =\n if(r.l == 1)\n List()\n else if(r.s == i)\n List(Range(i+1,r.l-1))\n else if(r.s+r.l-1 == i)\n List(Range(r.s,r.l-1))\n else\n List(Range(r.s,i-r.s), Range(i+1,r.l-(i-r.s+1)))\n\n // Document: http://www.scala-lang.org/api/current/#package\n // -----------------------------------------------------------------------------\n def main(args: Array[String]) : Unit = {\n val (n,k,a) = {\n val nka = readLine().split(\" \").map(_.toInt)\n (nka(0), nka(1), nka(2))\n }\n val m = readLine().toInt\n val xk = readLine().split(\" \").map(_.toInt-1)\n val ini = Range(0,n)\n var index = 0\n var kotae = -1\n val ts = TreeSet[Range](ini)\n var size = howMany(ini,a)\n for(x <- xk){\n index += 1\n val r = ts.iteratorFrom(Range(x,1)).next()\n ts -= r\n val add_range = split(r,x)\n size -= howMany(r,a)\n add_range.foreach(i => {size += howMany(i,a)})\n add_range.foreach(a => {ts += a})\n if(size < k && kotae == -1){\n kotae = index\n }\n }\n println(kotae)\n }\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject CF567D extends App {\n def num(r: Range, s: Int): Int = (r.length + 1) / (s + 1)\n\n val scanner = new Scanner(System.in)\n\n // val Array(n, k, a) = readLine().split(\" \").map(_.toInt)\n val n = scanner.nextInt()\n val k = scanner.nextInt()\n val a = scanner.nextInt()\n\n // val m = readLong()\n val m = scanner.nextLong()\n\n // val seg = mutable.TreeSet.empty(Ordering.fromLessThan[Range](_.start > _.start))\n val seg = new java.util.TreeMap[Int, Int]()\n // seg += 1 to n\n seg.put(1, n)\n var total = num(1 to n, a)\n var res = -1\n\n var i = 0\n while (i < m && total >= k) {\n val x = scanner.nextInt()\n // val x = readf(\"{0,number}\").asInstanceOf[Int]\n val e = seg.floorEntry(x)\n // val range = seg.find(r => r.contains(x)).get\n val range = e.getKey to e.getValue\n\n // seg -= range\n seg.remove(e.getKey)\n total -= num(range, a)\n\n val r1 = range.start to (x - 1)\n // seg += r1\n if (r1.length > 0) seg.put(r1.start, r1.end)\n total += num(r1, a)\n\n val r2 = (x + 1) to range.end\n // seg += r2\n if (r2.length > 0) seg.put(r2.start, r2.end)\n total += num(r2, a)\n\n if (total < k) res = i + 1\n i += 1\n }\n\n println(res)\n}"}], "negative_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn.readLine\nimport scala.collection.immutable.TreeSet\n\n\n\n// object Main {\n// case class Range(s: Long, l: Long) extends Ordered[Range] {\n// def compare(that: Range) = {\n// val t = s + l\n// val tt = that.s + that.l\n// if((s <= that.s && tt <= t) || (that.s <= s && t <= tt))\n// 0\n// else\n// (s - that.s).toInt\n// }\n// }\n// case class State(ts: TreeSet[Range], size: Long)\n// def howMany(r: Range, a: Long) : Long =\n// r match {\n// case Range(s, l) => {\n// val h = l / (a+1)\n// val r = l % (a+1)\n// h + (if(r == a) 1 else 0)\n// }\n// }\n// def split(r: Range, i: Long) : List[Range] =\n// if(r.l == 1)\n// List()\n// else if(r.s == i)\n// List(Range(i+1,r.l-1))\n// else if(r.s+r.l-1 == i)\n// List(Range(r.s,r.l-1))\n// else\n// List(Range(r.s,i-r.s), Range(i+1,r.l-(i-r.s+1)))\n\n// // Document: http://www.scala-lang.org/api/current/#package\n// // -----------------------------------------------------------------------------\n// def main(args: Array[String]) : Unit = {\n// val (n,k,a) = {\n// val nka = readLine().split(\" \").map(_.toLong)\n// (nka(0), nka(1), nka(2))\n// }\n// val m = readLine().toLong\n// val x = readLine().split(\" \").map(_.toLong-1)\n// val ini = Range(0,n)\n// var index = 0\n// var kotae = -1\n// val ans = x.foldLeft(State(TreeSet[Range](ini), howMany(ini,a)))(\n// (state,x) => state match {\n// case State(ts, size) => {\n// index += 1\n// val r = ts.iteratorFrom(Range(x,1)).next()\n// val sub = howMany(r,a)\n// val add_range = split(r,x)\n// val add_cnt = add_range.map(howMany(_,a)).sum\n// val new_ts = add_range.foldLeft(ts-r)((t,a) => t+a)\n// val cnt = size - sub + add_cnt\n// if(cnt < k && kotae == -1){\n// kotae = index\n// }\n// State(new_ts, cnt)\n// }})\n// println(kotae)\n// }\n// }\n\n\nobject Main {\n import scala.collection.mutable.TreeSet\n case class Range(s: Int, l: Int) extends Ordered[Range] {\n def compare(that: Range) = {\n val t = s + l\n val tt = that.s + that.l\n if((s <= that.s && tt <= t) || (that.s <= s && t <= tt))\n 0\n else\n (s - that.s).toInt\n }\n }\n case class State(ts: TreeSet[Range], size: Int)\n def howMany(r: Range, a: Int) : Int =\n r match {\n case Range(s, l) => {\n val h = l / (a+1)\n val r = l % (a+1)\n h + (if(r == a) 1 else 0)\n }\n }\n def split(r: Range, i: Int) : List[Range] =\n if(r.l == 1)\n List()\n else if(r.s == i)\n List(Range(i+1,r.l-1))\n else if(r.s+r.l-1 == i)\n List(Range(r.s,r.l-1))\n else\n List(Range(r.s,i-r.s), Range(i+1,r.l-(i-r.s+1)))\n\n // Document: http://www.scala-lang.org/api/current/#package\n // -----------------------------------------------------------------------------\n def main(args: Array[String]) : Unit = {\n val (n,k,a) = {\n val nka = readLine().split(\" \").map(_.toInt)\n (nka(0), nka(1), nka(2))\n }\n val m = readLine().toInt\n val xk = readLine().split(\" \").map(_.toInt-1)\n val ini = Range(0,n)\n var index = 0\n var kotae = -1\n\n val ts = TreeSet[Range](ini)\n var size = howMany(ini,a)\n for(x <- xk){\n index += 1\n val r = ts.iteratorFrom(Range(x,1)).next()\n val sub = howMany(r,a)\n val add_range = split(r,x)\n val add_cnt = add_range.map(howMany(_,a)).sum\n ts -= r\n add_range.foreach((a) => {ts += a})\n val cnt = size - sub + add_cnt\n if(cnt < k && kotae == -1){\n kotae = index\n }\n }\n println(kotae)\n }\n}\n"}], "src_uid": "e83c40f6d08b949900e5ae93b1d6f2c3"} {"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val g = new Array[Array[Int]](n + 2)\n val d = new Array[Array[Int]](n + 2)\n for (i <- 0 until g.length) {\n g(i) = new Array[Int](m + 2)\n d(i) = new Array[Int](m + 2)\n }\n for (i <- 1 to n) {\n val in = next.toCharArray\n for (j <- 1 to m) {\n if (in(j - 1) == '.') {\n g(i)(j) = 1\n }\n }\n }\n val r1 = nextInt\n val c1 = nextInt\n val r2 = nextInt\n val c2 = nextInt\n val dx = Array(-1, 1, 0, 0)\n val dy = Array(0, 0, -1, 1)\n if (r1 == r2 && c1 == c2) {\n for (i <- 0 until 4) {\n val x1 = r1 + dx(i)\n val y1 = c1 + dy(i)\n if (g(x1)(y1) == 1) {\n out.println(\"YES\")\n return 1\n }\n }\n } else if ((r1 == r2 && Math.abs(c1 - c2) == 1) || (c1 == c2 && Math.abs(r1 - r2) == 1)) {\n if (g(r2)(c2) == 0) {\n out.println(\"YES\")\n return 1\n } else {\n var cnt = 0\n for (i <- 0 until 4) {\n val x1 = r2 + dx(i)\n val y1 = c2 + dy(i)\n if (g(x1)(y1) == 1) {\n cnt += 1\n }\n }\n if (cnt >= 1) {\n out.println(\"YES\")\n return 1\n }\n }\n } else {\n val q = new mutable.Queue[(Int, Int)]()\n q.enqueue((r1, c1))\n\n while (!q.isEmpty) {\n val x = q.dequeue\n for (i <- 0 until 4) {\n val x1 = x._1 + dx(i)\n val y1 = x._2 + dy(i)\n if (x1 == r2 && y1 == c2) {\n if (g(r2)(c2) == 0) {\n out.println(\"YES\")\n return 1\n } else {\n var cnt = 0\n for (i <- 0 until 4) {\n val x1 = r2 + dx(i)\n val y1 = c2 + dy(i)\n if (g(x1)(y1) == 1) {\n cnt += 1\n }\n }\n if (cnt >= 2) {\n out.println(\"YES\")\n return 1\n }\n }\n } else if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {\n q.enqueue((x1, y1))\n d(x1)(y1) = d(x._1)(x._2) + 1\n }\n }\n }\n }\n out.println(\"NO\")\n return 0\n }\n}", "positive_code": [{"source_code": "import annotation.tailrec\n\nobject main extends App with fastIO {\n \n case class Point(x: Int, y: Int)\n \n val dx = Vector(-1, 0, 1, 0)\n val dy = Vector(0, -1, 0, 1)\n \n def ok(x: Int, y: Int) = { x >= 0 && y >= 0 && x < n && y < m }\n \n def bfs(p: Point) {\n \n var q = scala.collection.mutable.Queue(p)\n \n def run(x: Int, y: Int) {\n if (!ok(x, y)) return\n if (a(x)(y) == 1) return\n if (used(x)(y)) return\n \n used(x)(y) = true \n for (i <- 0 until 4) \n q += Point(x + dx(i), y + dy(i))\n } \n \n while (!q.isEmpty) {\n val (x, y) = (q.front.x, q.front.y)\n q.dequeue; run(x, y) \n } \n }\n \n var Array(n, m) = readLine split(\" \") map(_.toInt)\n var a = Array.fill(n)(readLine.map(c => if (c == '.') 0 else 1).toArray)\n var (p1, p2) = (Point(nextInt - 1, nextInt - 1), Point(nextInt - 1, nextInt - 1))\n var used = Array.ofDim[Boolean](n, m)\n \n a(p1.x)(p1.y) = 0\n var cnt = a(p2.x)(p2.y) * 2\n for (i <- 0 until 4) if (ok(p2.x + dx(i), p2.y + dy(i))) \n cnt += 1 - a(p2.x + dx(i))(p2.y + dy(i))\n if (p1 == p2) cnt += 1\n \n a(p2.x)(p2.y) = 0\n for (i <- 0 until 4) bfs(Point(p1.x + dx(i), p1.y + dy(i))) \n \n println(if (cnt > 1 && used(p2.x)(p2.y)) \"YES\" else \"NO\") \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.Ordering.Implicits._\nimport scala.collection.mutable\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n val dx = Array(0, 0, 1, -1)\n val dy = Array(1, -1, 0, 0)\n\n def check(n: Int, m: Int, x: Int, y: Int): Boolean = {\n 0 <= x && x < n && 0 <= y && y < m\n }\n\n def reach(matrix: Array[String], startx: Int, starty: Int, endx: Int, endy: Int): Boolean = {\n val n = matrix.length\n val m = matrix(0).length\n val vst = Array.ofDim[Boolean](n, m)\n for (i <- 0 until n; j <- 0 until m) {\n vst(i)(j) = (matrix(i)(j) == 'X')\n }\n var queue = new mutable.Queue[(Int, Int)]()\n queue += Tuple2(startx, starty)\n while (queue.nonEmpty) {\n val front = queue.head\n queue = queue.tail\n for (i <- 0 until dx.length) {\n val nextx = front._1 + dx(i)\n val nexty = front._2 + dy(i)\n if (nextx == endx && nexty == endy) {\n return true\n }\n if (check(n, m, nextx, nexty) && vst(nextx)(nexty) == false) {\n vst(nextx)(nexty) = true\n queue += Tuple2(nextx, nexty)\n }\n }\n }\n return false\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n\n val matrix = Array.ofDim[String](n)\n for (i <- 0 until n) {\n matrix(i) = next\n }\n val (startx, starty) = (nextInt - 1, nextInt - 1)\n val (endx, endy) = (nextInt - 1, nextInt - 1)\n\n\n var can_reach = 0\n for (i <- 0 until dx.length) {\n val nextx = endx + dx(i)\n val nexty = endy + dy(i)\n if (check(n, m, nextx, nexty) && matrix(nextx)(nexty) == '.') {\n can_reach += 1\n }\n }\n if (startx == endx && starty == endy) {\n if (can_reach != 0) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n } else if (matrix(endx)(endy) == 'X') {\n if (reach(matrix, startx, starty, endx, endy)) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n } else if (math.abs(startx - endx) + math.abs(starty - endy) == 1) {\n if (can_reach > 0) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n } else {\n if (reach(matrix, startx, starty, endx, endy) && can_reach > 1) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "negative_code": [{"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.Ordering.Implicits._\nimport scala.collection.mutable\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n val dx = Array(0, 0, 1, -1)\n val dy = Array(1, -1, 0, 0)\n\n def check(n: Int, m: Int, x: Int, y: Int): Boolean = {\n 0 <= x && x < n && 0 <= y && y < m\n }\n\n def reach(matrix: Array[String], startx: Int, starty: Int, endx: Int, endy: Int): Boolean = {\n val n = matrix.length\n val m = matrix(0).length\n val vst = Array.ofDim[Boolean](n, m)\n for (i <- 0 until n; j <- 0 until m) {\n vst(i)(j) = (matrix(i)(j) == 'X')\n }\n var queue = new mutable.Queue[(Int, Int)]()\n queue += Tuple2(startx, starty)\n while (queue.nonEmpty) {\n val front = queue.head\n queue = queue.tail\n for (i <- 0 until dx.length) {\n val nextx = front._1 + dx(i)\n val nexty = front._2 + dy(i)\n if (nextx == endx && nexty == endy) {\n return true\n }\n if (check(n, m, nextx, nexty) && vst(nextx)(nexty) == '.') {\n vst(nextx)(nexty) = true\n queue += Tuple2(nextx, nexty)\n }\n }\n }\n return false\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n\n val matrix = Array.ofDim[String](n)\n for (i <- 0 until n) {\n matrix(i) = next\n }\n val (startx, starty) = (nextInt - 1, nextInt - 1)\n val (endx, endy) = (nextInt - 1, nextInt - 1)\n\n\n var can_reach = 0\n for (i <- 0 until dx.length) {\n val nextx = endx + dx(i)\n val nexty = endy + dy(i)\n if (check(n, m, nextx, nexty) && matrix(nextx)(nexty) == '.') {\n can_reach += 1\n }\n }\n if (startx == endx && starty == endy) {\n if (can_reach != 0) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n } else if (matrix(endx)(endy) == 'X') {\n if (reach(matrix, startx, starty, endx, endy)) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n } else {\n if (reach(matrix, startx, starty, endx, endy) && can_reach > 1) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.Ordering.Implicits._\nimport scala.collection.mutable\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n val dx = Array(0, 0, 1, -1)\n val dy = Array(1, -1, 0, 0)\n\n def check(n: Int, m: Int, x: Int, y: Int): Boolean = {\n 0 <= x && x < n && 0 <= y && y < m\n }\n\n def reach(matrix: Array[String], startx: Int, starty: Int, endx: Int, endy: Int): Boolean = {\n val n = matrix.length\n val m = matrix(0).length\n val vst = Array.ofDim[Boolean](n, m)\n for (i <- 0 until n; j <- 0 until m) {\n vst(i)(j) = (matrix(i)(j) == 'X')\n }\n var queue = new mutable.Queue[(Int, Int)]()\n queue += Tuple2(startx, starty)\n while (queue.nonEmpty) {\n val front = queue.head\n queue = queue.tail\n for (i <- 0 until dx.length) {\n val nextx = front._1 + dx(i)\n val nexty = front._2 + dy(i)\n if (nextx == endx && nexty == endy) {\n return true\n }\n if (check(n, m, nextx, nexty) && vst(nextx)(nexty) == false) {\n vst(nextx)(nexty) = true\n queue += Tuple2(nextx, nexty)\n }\n }\n }\n return false\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n\n val matrix = Array.ofDim[String](n)\n for (i <- 0 until n) {\n matrix(i) = next\n }\n val (startx, starty) = (nextInt - 1, nextInt - 1)\n val (endx, endy) = (nextInt - 1, nextInt - 1)\n\n\n var can_reach = 0\n for (i <- 0 until dx.length) {\n val nextx = endx + dx(i)\n val nexty = endy + dy(i)\n if (check(n, m, nextx, nexty) && matrix(nextx)(nexty) == '.') {\n can_reach += 1\n }\n }\n if (startx == endx && starty == endy) {\n if (can_reach != 0) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n } else if (matrix(endx)(endy) == 'X') {\n if (reach(matrix, startx, starty, endx, endy)) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n } else {\n if (reach(matrix, startx, starty, endx, endy) && can_reach > 1) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.Ordering.Implicits._\nimport scala.collection.mutable\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n val dx = Array(0, 0, 1, -1)\n val dy = Array(1, -1, 0, 0)\n\n def check(n: Int, m: Int, x: Int, y: Int): Boolean = {\n 0 <= x && x < n && 0 <= y && y < m\n }\n\n def reach(matrix: Array[String], startx: Int, starty: Int, endx: Int, endy: Int): Boolean = {\n val n = matrix.length\n val m = matrix(0).length\n val vst = Array.ofDim[Boolean](n, m)\n for (i <- 0 until n; j <- 0 until m) {\n vst(i)(j) = (matrix(i)(j) == 'X')\n }\n var queue = new mutable.Queue[(Int, Int)]()\n queue += Tuple2(startx, starty)\n while (queue.nonEmpty) {\n val front = queue.head\n queue = queue.tail\n for (i <- 0 until dx.length) {\n val nextx = front._1 + dx(i)\n val nexty = front._2 + dy(i)\n if (nextx == endx && nexty == endy) {\n return true\n }\n if (check(n, m, nextx, nexty) && vst(nextx)(nexty) == false) {\n vst(nextx)(nexty) = true\n queue += Tuple2(nextx, nexty)\n }\n }\n }\n return false\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n\n val matrix = Array.ofDim[String](n)\n for (i <- 0 until n) {\n matrix(i) = next\n }\n val (startx, starty) = (nextInt - 1, nextInt - 1)\n val (endx, endy) = (nextInt - 1, nextInt - 1)\n\n\n var can_reach = 0\n for (i <- 0 until dx.length) {\n val nextx = endx + dx(i)\n val nexty = endy + dy(i)\n if (check(n, m, nextx, nexty) && matrix(nextx)(nexty) == '.') {\n can_reach += 1\n }\n }\n if (startx == endx && starty == endy) {\n if (can_reach != 0) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n } else if (math.abs(startx - endx) + math.abs(starty - endy) == 1) {\n if (can_reach > 0) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n } else if (matrix(endx)(endy) == 'X') {\n if (reach(matrix, startx, starty, endx, endy)) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n } else {\n if (reach(matrix, startx, starty, endx, endy) && can_reach > 1) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val g = new Array[Array[Int]](n + 2)\n val d = new Array[Array[Int]](n + 2)\n for (i <- 0 until g.length) {\n g(i) = new Array[Int](m + 2)\n d(i) = new Array[Int](m + 2)\n }\n for (i <- 1 to n) {\n val in = next.toCharArray\n for (j <- 1 to m) {\n if (in(j - 1) == '.') {\n g(i)(j) = 1\n }\n }\n }\n val r1 = nextInt\n val c1 = nextInt\n val r2 = nextInt\n val c2 = nextInt\n val dx = Array(-1, 1, 0, 0)\n val dy = Array(0, 0, -1, 1)\n if (r1 == r2 && c1 == c2) {\n for (i <- 0 until 4) {\n val x1 = r1 + dx(i)\n val y1 = c1 + dy(i)\n if (g(x1)(y1) == 1) {\n out.println(\"YES\")\n return 1\n }\n }\n } else if ((r1 == r2 && Math.abs(c1 - c2) == 1) || (c1 == c2 && Math.abs(r1 - r2) == 1)) {\n if (g(r2)(c2) == 1) {\n out.println(\"YES\")\n return 1\n } else {\n for (i <- 0 until 4) {\n val x1 = r2 + dx(i)\n val y1 = c2 + dy(i)\n if (g(x1)(y1) == 1) {\n out.println(\"YES\")\n return 1\n }\n }\n }\n } else {\n val q = new mutable.Queue[(Int, Int)]()\n q.enqueue((r1, c1))\n\n while (!q.isEmpty) {\n val x = q.dequeue\n for (i <- 0 until 4) {\n val x1 = x._1 + dx(i)\n val y1 = x._2 + dy(i)\n if (x1 == r2 && y1 == c2) {\n if (g(x1)(y1) == 0) {\n out.println(\"YES\")\n return 1\n } else {\n for (i <- 0 until 4) {\n val x1 = r2 + dx(i)\n val y1 = c2 + dy(i)\n if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {\n out.println(\"YES\")\n return 1\n }\n }\n out.println(\"NO\")\n return 1\n }\n } else if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {\n q.enqueue((x1, y1))\n d(x1)(y1) = d(x._1)(x._2) + 1\n }\n }\n }\n }\n out.println(\"NO\")\n return 0\n }\n}"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val g = new Array[Array[Int]](n + 2)\n val d = new Array[Array[Int]](n + 2)\n for (i <- 0 until g.length) {\n g(i) = new Array[Int](m + 2)\n d(i) = new Array[Int](m + 2)\n }\n for (i <- 1 to n) {\n val in = next.toCharArray\n for (j <- 1 to m) {\n if (in(j - 1) == '.') {\n g(i)(j) = 1\n }\n }\n }\n val r1 = nextInt\n val c1 = nextInt\n val r2 = nextInt\n val c2 = nextInt\n val dx = Array(-1, 1, 0, 0)\n val dy = Array(0, 0, -1, 1)\n if (r1 == r2 && c1 == c2) {\n for (i <- 0 until 4) {\n val x1 = r1 + dx(i)\n val y1 = c1 + dy(i)\n if (g(x1)(y1) == 1) {\n out.println(\"YES\")\n return 1\n }\n }\n } else if ((r1 == r2 && Math.abs(c1 - c2) == 1) || (c1 == c2 && Math.abs(r1 - r2) == 1)) {\n if (g(r2)(c2) == 0) {\n out.println(\"YES\")\n return 1\n } else {\n for (i <- 0 until 4) {\n val x1 = r2 + dx(i)\n val y1 = c2 + dy(i)\n if (g(x1)(y1) == 1) {\n out.println(\"YES\")\n return 1\n }\n }\n }\n } else {\n val q = new mutable.Queue[(Int, Int)]()\n q.enqueue((r1, c1))\n\n while (!q.isEmpty) {\n val x = q.dequeue\n for (i <- 0 until 4) {\n val x1 = x._1 + dx(i)\n val y1 = x._2 + dy(i)\n if (x1 == r2 && y1 == c2) {\n if (g(x1)(y1) == 0) {\n out.println(\"YES\")\n return 1\n } else {\n for (i <- 0 until 4) {\n val x1 = r2 + dx(i)\n val y1 = c2 + dy(i)\n if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {\n out.println(\"YES\")\n return 1\n }\n }\n out.println(\"NO\")\n return 1\n }\n } else if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {\n q.enqueue((x1, y1))\n d(x1)(y1) = d(x._1)(x._2) + 1\n }\n }\n }\n }\n out.println(\"NO\")\n return 0\n }\n}"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val g = new Array[Array[Int]](n + 2)\n val d = new Array[Array[Int]](n + 2)\n for (i <- 0 until g.length) {\n g(i) = new Array[Int](m + 2)\n d(i) = new Array[Int](m + 2)\n }\n for (i <- 1 to n) {\n val in = next.toCharArray\n for (j <- 1 to m) {\n if (in(j - 1) == '.') {\n g(i)(j) = 1\n }\n }\n }\n val r1 = nextInt\n val c1 = nextInt\n val r2 = nextInt\n val c2 = nextInt\n val dx = Array(-1, 1, 0, 0)\n val dy = Array(0, 0, -1, 1)\n if (r1 == r2 && c1 == c2) {\n for (i <- 0 until 4) {\n val x1 = r1 + dx(i)\n val y1 = c1 + dy(i)\n if (g(x1)(y1) == 1) {\n out.println(\"YES\")\n return 1\n }\n }\n } else if (r1 == r2 || c1 == c2) {\n if (g(r2)(c2) == 1) {\n out.println(\"YES\")\n return 1\n } else {\n for (i <- 0 until 4) {\n val x1 = r2 + dx(i)\n val y1 = c2 + dy(i)\n if (g(x1)(y1) == 1) {\n out.println(\"YES\")\n return 1\n }\n }\n }\n } else {\n val q = new mutable.Queue[(Int, Int)]()\n q.enqueue((r1, c1))\n\n while (!q.isEmpty) {\n val x = q.dequeue\n for (i <- 0 until 4) {\n val x1 = x._1 + dx(i)\n val y1 = x._2 + dy(i)\n if (x1 == r2 && y1 == c2) {\n if (g(x1)(y1) == 0) {\n out.println(\"YES\")\n return 1\n } else {\n for (i <- 0 until 4) {\n val x1 = r2 + dx(i)\n val y1 = c2 + dy(i)\n if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {\n out.println(\"YES\")\n return 1\n }\n }\n out.println(\"NO\")\n return 1\n }\n } else if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {\n q.enqueue((x1, y1))\n d(x1)(y1) = d(x._1)(x._2) + 1\n }\n }\n }\n }\n out.println(\"NO\")\n return 0\n }\n}"}, {"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val g = new Array[Array[Int]](n + 2)\n val d = new Array[Array[Int]](n + 2)\n for (i <- 0 until g.length) {\n g(i) = new Array[Int](m + 2)\n d(i) = new Array[Int](m + 2)\n }\n for (i <- 1 to n) {\n val in = next.toCharArray\n for (j <- 1 to m) {\n if (in(j - 1) == '.') {\n g(i)(j) = 1\n }\n }\n }\n val r1 = nextInt\n val c1 = nextInt\n val r2 = nextInt\n val c2 = nextInt\n val dx = Array(-1, 1, 0, 0)\n val dy = Array(0, 0, -1, 1)\n if (r1 == r2 && c1 == c2) {\n for (i <- 0 until 4) {\n val x1 = r1 + dx(i)\n val y1 = c1 + dy(i)\n if (g(x1)(y1) == 1) {\n out.println(\"YES\")\n return 1\n }\n }\n } else if ((r1 == r2 && Math.abs(c1 - c2) == 1) || (c1 == c2 && Math.abs(r1 - r2) == 1)) {\n if (g(r2)(c2) == 0) {\n out.println(\"YES\")\n return 1\n } else {\n var cnt = 0\n for (i <- 0 until 4) {\n val x1 = r2 + dx(i)\n val y1 = c2 + dy(i)\n if (g(x1)(y1) == 1) {\n cnt += 1\n }\n }\n if (cnt >= 2) {\n out.println(\"YES\")\n return 1\n }\n }\n } else {\n val q = new mutable.Queue[(Int, Int)]()\n q.enqueue((r1, c1))\n\n while (!q.isEmpty) {\n val x = q.dequeue\n for (i <- 0 until 4) {\n val x1 = x._1 + dx(i)\n val y1 = x._2 + dy(i)\n if (x1 == r2 && y1 == c2) {\n if (g(x1)(y1) == 0) {\n out.println(\"YES\")\n return 1\n } else {\n for (i <- 0 until 4) {\n val x1 = r2 + dx(i)\n val y1 = c2 + dy(i)\n if (g(x1)(y1) == 1) {\n out.println(\"YES\")\n return 1\n }\n }\n out.println(\"NO\")\n return 1\n }\n } else if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {\n q.enqueue((x1, y1))\n d(x1)(y1) = d(x._1)(x._2) + 1\n }\n }\n }\n }\n out.println(\"NO\")\n return 0\n }\n}"}, {"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val g = new Array[Array[Int]](n + 2)\n val d = new Array[Array[Int]](n + 2)\n for (i <- 0 until g.length) {\n g(i) = new Array[Int](m + 2)\n d(i) = new Array[Int](m + 2)\n }\n for (i <- 1 to n) {\n val in = next.toCharArray\n for (j <- 1 to m) {\n if (in(j - 1) == '.') {\n g(i)(j) = 1\n }\n }\n }\n val r1 = nextInt\n val c1 = nextInt\n val r2 = nextInt\n val c2 = nextInt\n val dx = Array(-1, 1, 0, 0)\n val dy = Array(0, 0, -1, 1)\n if (r1 == r2 && c1 == c2) {\n for (i <- 0 until 4) {\n val x1 = r1 + dx(i)\n val y1 = c1 + dy(i)\n if (g(x1)(y1) == 1) {\n out.println(\"YES\")\n return 1\n }\n }\n } else if ((r1 == r2 && Math.abs(c1 - c2) == 1) || (c1 == c2 && Math.abs(r1 - r2) == 1)) {\n if (g(r2)(c2) == 0) {\n out.println(\"YES\")\n return 1\n } else {\n var cnt = 0\n for (i <- 0 until 4) {\n val x1 = r2 + dx(i)\n val y1 = c2 + dy(i)\n if (g(x1)(y1) == 1) {\n cnt += 1\n }\n }\n if (cnt >= 2) {\n out.println(\"YES\")\n return 1\n }\n }\n } else {\n val q = new mutable.Queue[(Int, Int)]()\n q.enqueue((r1, c1))\n\n while (!q.isEmpty) {\n val x = q.dequeue\n for (i <- 0 until 4) {\n val x1 = x._1 + dx(i)\n val y1 = x._2 + dy(i)\n if (x1 == r2 && y1 == c2) {\n if (g(r2)(c2) == 0) {\n out.println(\"YES\")\n return 1\n } else {\n var cnt = 0\n for (i <- 0 until 4) {\n val x1 = r2 + dx(i)\n val y1 = c2 + dy(i)\n if (g(x1)(y1) == 1) {\n cnt += 1\n }\n }\n if (cnt >= 2) {\n out.println(\"YES\")\n return 1\n }\n }\n } else if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {\n q.enqueue((x1, y1))\n d(x1)(y1) = d(x._1)(x._2) + 1\n }\n }\n }\n }\n out.println(\"NO\")\n return 0\n }\n}"}, {"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val m = nextInt\n val g = new Array[Array[Int]](n + 2)\n val d = new Array[Array[Int]](n + 2)\n for (i <- 0 until g.length) {\n g(i) = new Array[Int](m + 2)\n d(i) = new Array[Int](m + 2)\n }\n for (i <- 1 to n) {\n val in = next.toCharArray\n for (j <- 1 to m) {\n if (in(j - 1) == '.') {\n g(i)(j) = 1\n }\n }\n }\n val r1 = nextInt\n val c1 = nextInt\n val r2 = nextInt\n val c2 = nextInt\n val dx = Array(-1, 1, 0, 0)\n val dy = Array(0, 0, -1, 1)\n if (r1 == r2 && c1 == c2) {\n for (i <- 0 until 4) {\n val x1 = r1 + dx(i)\n val y1 = c1 + dy(i)\n if (g(x1)(y1) == 1) {\n out.println(\"YES\")\n return 1\n }\n }\n } else {\n val q = new mutable.Queue[(Int, Int)]()\n q.enqueue((r1, c1))\n\n while (!q.isEmpty) {\n val x = q.dequeue\n for (i <- 0 until 4) {\n val x1 = x._1 + dx(i)\n val y1 = x._2 + dy(i)\n if (x1 == r2 && y1 == c2) {\n if (g(x1)(y1) == 0) {\n out.println(\"YES\")\n return 1\n } else {\n for (i <- 0 until 4) {\n val x1 = r2 + dx(i)\n val y1 = c2 + dy(i)\n if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {\n out.println(\"YES\")\n return 1\n }\n }\n out.println(\"NO\")\n return 1\n }\n } else if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {\n q.enqueue((x1, y1))\n d(x1)(y1) = d(x._1)(x._2) + 1\n }\n }\n }\n }\n out.println(\"NO\")\n return 0\n }\n\n}\n"}, {"source_code": "object main extends App with fastIO {\n \n case class Point(x: Int, y: Int)\n \n val dx = Vector(-1, 0, 1, 0)\n val dy = Vector(0, -1, 0, 1)\n \n def ok(x: Int, y: Int) = { x >= 0 && y >= 0 && x < n && y < m }\n \n def dfs(x: Int, y: Int) { \n if (!ok(x, y)) return\n if (a(x)(y) == 1) return \n if (used(x)(y)) return \n \n used(x)(y) = true \n for (i <- 0 until 4) \n dfs(x + dx(i), y + dy(i)) \n }\n \n var Array(n, m) = readLine split(\" \") map(_.toInt)\n var a = Array.fill(n)(readLine.map(c => if (c == '.') 0 else 1).toArray)\n var (p1, p2) = (Point(nextInt - 1, nextInt - 1), Point(nextInt - 1, nextInt - 1))\n var used = Array.ofDim[Boolean](n, m)\n \n var cnt = a(p2.x)(p2.y)\n for (i <- 0 until 4) if (ok(p2.x + dx(i), p2.y + dy(i))) \n cnt += 1 - a(p2.x + dx(i))(p2.y + dy(i))\n \n a(p1.x)(p1.y) = 0\n a(p2.x)(p2.y) = 0\n dfs(p1.x, p1.y) \n \n println(if (cnt > 1 && used(p2.x)(p2.y)) \"YES\" else \"NO\") \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}"}, {"source_code": "object main extends App with fastIO {\n \n case class Point(x: Int, y: Int)\n \n val dx = Vector(-1, 0, 1, 0)\n val dy = Vector(0, -1, 0, 1)\n \n def ok(x: Int, y: Int) = { x >= 0 && y >= 0 && x < n && y < m }\n \n def dfs(x: Int, y: Int) { \n if (!ok(x, y)) return\n if (a(x)(y) == 1) return \n if (used(x)(y)) return \n \n used(x)(y) = true \n for (i <- 0 until 4) \n dfs(x + dx(i), y + dy(i)) \n }\n \n var Array(n, m) = readLine split(\" \") map(_.toInt)\n var a = Array.fill(n)(readLine.map(c => if (c == '.') 0 else 1).toArray)\n var (p1, p2) = (Point(nextInt - 1, nextInt - 1), Point(nextInt - 1, nextInt - 1))\n var used = Array.ofDim[Boolean](n, m)\n \n var cnt = a(p2.x)(p2.y) * 2\n for (i <- 0 until 4) if (ok(p2.x + dx(i), p2.y + dy(i))) \n cnt += 1 - a(p2.x + dx(i))(p2.y + dy(i))\n \n a(p1.x)(p1.y) = 0\n a(p2.x)(p2.y) = 0\n dfs(p1.x, p1.y) \n \n println(if (cnt > 1 && used(p2.x)(p2.y)) \"YES\" else \"NO\") \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}"}, {"source_code": "object main extends App with fastIO {\n \n case class Point(x: Int, y: Int)\n \n val dx = Vector(-1, 0, 1, 0)\n val dy = Vector(0, -1, 0, 1)\n \n def ok(x: Int, y: Int) = { x >= 0 && y >= 0 && x < n && y < m }\n \n def dfs(x: Int, y: Int) { \n if (!ok(x, y)) return\n if (a(x)(y) == 1) return \n if (used(x)(y)) return \n \n used(x)(y) = true \n for (i <- 0 until 4) \n dfs(x + dx(i), y + dy(i)) \n }\n \n var Array(n, m) = readLine split(\" \") map(_.toInt)\n var a = Array.fill(n)(readLine.map(c => if (c == '.') 0 else 1).toArray)\n var (p1, p2) = (Point(nextInt - 1, nextInt - 1), Point(nextInt - 1, nextInt - 1))\n var used = Array.ofDim[Boolean](n, m)\n \n var cnt = a(p2.x)(p2.y) * 2\n for (i <- 0 until 4) if (ok(p2.x + dx(i), p2.y + dy(i))) \n cnt += 1 - a(p2.x + dx(i))(p2.y + dy(i))\n \n a(p2.x)(p2.y) = 0\n for (i <- 0 until 4) dfs(p1.x + dx(i), p1.y + dy(i)) \n \n println(if (cnt > 1 && used(p2.x)(p2.y)) \"YES\" else \"NO\") \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}"}], "src_uid": "afac59c927522fb223f59c36184229e2"} {"source_code": "import java.util.Scanner\n\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val scanner = new Scanner (System.in)\n\t\tval str = scanner nextLine () reverse\n\n\t\tprintln (solve (str) reverse)\n }\n\n\tdef solve(str: String): String = {\n\t\tvar prev = 0\n\t\tdef f(c: Char): Boolean = {\n\t\t\tif (prev <= c) {\n\t\t\t\tprev = c\n\t\t\t\ttrue\n\t\t\t} else false\n\t\t}\n\t\tstr filter f\n\t}\n\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next()\n val letters = Array.ofDim[Int](26)\n line.foreach {\n i => letters(i - 'a') += 1\n }\n\n val res = line.foldLeft(List.empty[Char], letters.indices.reverse.find(i => letters(i) > 0)) {\n case ((answer, Some(i)), el) if el - 'a' != i =>\n letters(el - 'a') -= 1\n if (letters(el - 'a') == 0)\n (answer, letters.indices.reverse.find(i => letters(i) > 0))\n else\n (answer, Some(i))\n case ((answer, Some(i)), el) =>\n letters(el- 'a') -= 1\n if (letters(el - 'a') == 0)\n (el :: answer, letters.indices.reverse.find(i => letters(i) > 0))\n else\n (el :: answer, Some(i))\n }\n println(res._1.reverse.mkString)\n}\n"}], "negative_code": [], "src_uid": "77e2a6ba510987ed514fed3bd547b5ab"} {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\n\n/**\n * Created by hama_du on 2014/05/18.\n */\nobject ProblemB extends App {\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val n = in.nextInt()\n val colors = (0 until n).map(_ => (in.nextInt(), in.nextInt()) )\n val homeColor = new Array[Int](100001)\n val awayColor = new Array[Int](100001)\n for (i <- 0 until n) {\n val h = colors(i)._1\n val a = colors(i)._2\n homeColor(h) += 1\n awayColor(a) += 1\n }\n colors.foreach(z => {\n val matches = (n - 1)\n val d = homeColor(z._2)\n out.println((matches+d) + \" \" + (matches-d))\n })\n out.flush()\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map{_ => in.next().split(\" \").map(_.toInt)}\n val homes = data.map(_.head).groupBy(x => x).map(x => x._1 -> x._2.length)\n\n val res = data.map{\n el =>\n val guest = el.last\n val x = (n - 1) + homes.getOrElse(guest, 0)\n s\"$x ${(n - 1) * 2 - x}\"\n }\n\n println(res.mkString(\"\\n\"))\n}"}], "negative_code": [], "src_uid": "7899a22cee29bb96d671f6188f246c21"} {"source_code": "import io.Source\nimport io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n StdIn.readLine()\n\n val list = StdIn.readLine().split(\" \").map(_.toLong).toList\n val list2 = list ::: list\n var max = 0\n var t = 0\n for (a <- list2) {\n if (a == 1) {\n t += 1\n } else {\n max = Math.max(t, max)\n t = 0\n }\n }\n max = Math.max(t, max)\n println(max)\n //println(longs.reverse.map(t => math.sqrt(t)).mkString(\"\\n\"))\n }\n}\n/*\n\n\n* */\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N).map(_ == 1)\n debug(A)\n var a = 0\n var cnt = 0\n REP(N) { i =>\n if (A(i)) cnt += 1\n else cnt = 0\n a = max(a, cnt)\n }\n val b = A.takeWhile(identity).length + A.reverse.takeWhile(identity).length\n debug(s\"a:$a b:$b\")\n val ans = max(a, b)\n out.println(ans)\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n\n def debug(as: Array[Boolean]): Unit = DEBUG {\n debug(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = DEBUG {\n debug(as.mkString(\" \"))\n }\n\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n StdIn.readLine()\n\n val list = StdIn.readLine().split(\" \").map(_.toLong).toList\n val list2 = list ::: list\n var max = 0\n var t = 0\n for (a <- list2) {\n if (a == 1) {\n t += 1\n } else {\n max = Math.max(t, max)\n t = 0\n }\n }\n max = Math.max(t, max)\n println(max)\n }\n}"}, {"source_code": "object _1141B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val input = io.read[Vector[Boolean]]\n val isResting = input ++ input\n\n var i, ans = 0\n while(i < isResting.length) {\n val j = i\n while (i < isResting.length && isResting(i)) i += 1\n ans = ans max (i - j)\n i += 1\n }\n\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "fcd88c7b64da4b839cda4273d928429d"} {"source_code": "object Solution {\n def main(args: Array[String]) = {\n val s = readLine.toList\n \n val as = s.filter(_ == 'a').length\n val bs = s.filter(_ == 'b').length\n val cs = s.filter(_ == 'c').length\n val d = s.dropWhile(_ == 'a').dropWhile(_ == 'b').dropWhile(_ == 'c').isEmpty\n \n println(if (d && as > 0 && bs > 0 && cs > 0 && (as == cs || bs == cs)) \"YES\" else \"NO\")\n }\n}", "positive_code": [{"source_code": "\n\nimport java.io._\nimport java.nio.file._\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n\nobject CheckString {\n\n def solve(scanner: Scanner) = {\n val word = scanner.nextLine()\n try {\n val splitResult = word.split(\"b+\")\n val aWord = splitResult(0)\n val cWord = splitResult(1)\n val bWord = word.substring(aWord.size, word.size - cWord.size)\n\n val aSet = aWord.toSet\n val bSet = bWord.toSet\n val cSet = cWord.toSet\n if (aSet.contains('a') && bSet.contains('b') && cSet.contains('c')) {\n if (aSet.size != 1 || bSet.size != 1 || cSet.size != 1) {\n println(\"NO\")\n } else {\n if (aWord.size == cWord.size || bWord.size == cWord.size) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n } else {\n println(\"NO\")\n }\n } catch {\n case t: Throwable =>\n println(\"NO\")\n System.err.println(t)\n }\n }\n\n def main(args: Array[String]): Unit = {\n if (args.length > 0) {\n val filenameIn = args(0)\n System.setIn(new FileInputStream(filenameIn))\n }\n val scanner = new Scanner(System.in)\n if (args.length > 1) {\n val filename = args(1)\n System.setOut(new PrintStream(filename))\n }\n val start = System.currentTimeMillis\n solve(scanner)\n scanner.close()\n System.err.println(\"\\n\" + (System.currentTimeMillis - start) + \" ms\")\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next() = tokenizer().get.nextToken()\n\n override def hasNext = tokenizer().nonEmpty\n\n override def close() = reader.close()\n }\n\n}\n\n\n\n"}], "negative_code": [{"source_code": "object Solution {\n def main(args: Array[String]) = {\n val s = readLine.toList\n \n val as = s.filter(_ == 'a').length\n val bs = s.filter(_ == 'b').length\n val cs = s.filter(_ == 'c').length\n val d = s.takeWhile(_ == 'a').takeWhile(_ == 'b').takeWhile(_ == 'c').isEmpty\n \n println(if (d && as > 0 && bs > 0 && cs > 0 && (as == cs || bs == cs)) \"YES\" else \"NO\")\n }\n}"}], "src_uid": "6581dbaff7eb52b63ccfe9c0c4117c09"} {"source_code": "object ProblemC extends App {\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val n = in.nextInt()\n\n for (_ <- 1 to n) {\n val n = in.nextInt()\n val arr = new Array[Boolean](n)\n var result = true\n for (j <- 0 until n) {\n val ak = in.nextInt()\n\n var place = (n + (j + ak) % n) % n\n\n if (arr(place)) {\n result = false\n }\n\n arr(place) = true\n }\n\n if (result) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n\n}\n", "positive_code": [{"source_code": "object C extends App {\n private def mod(k: Int, n: Int): Int =\n if (k > 0) k % n else (n - k % n) % n\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val bm = an.zipWithIndex.map { case (a, i) => (n + (a + i) % n) % n }.distinct\n\n if (n == bm.length) println(\"YES\")\n else println(\"NO\")\n }\n}\n"}, {"source_code": "object Codeforces1344a {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach { _ =>\n if (test()) {\n writer.println(\"YES\")\n } else {\n writer.println(\"NO\")\n }\n }\n }\n\n def test()(implicit reader: BufferedReader): Boolean = {\n val n: Int = rl_int\n val a: Array[Int] = rll_int\n a.zipWithIndex.map(x => Math.floorMod(x._1 + x._2, n)).distinct.length == n\n }\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}"}], "negative_code": [{"source_code": "object C extends App {\n private def mod(k: Int, n: Int): Int =\n if (k > 0) k % n else (n - k % n) % n\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val bm = an.zipWithIndex.map { case (a, i) => mod(a + i, n) }.distinct\n\n if (n == bm.length) println(\"YES\")\n else println(\"NO\")\n }\n}\n"}, {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val bn = an.zipWithIndex.map { case (a, i) => (a + i % n) % n }.distinct\n\n if (an.length == bn.length) println(\"YES\")\n else println(\"NO\")\n }\n}\n"}, {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val bn = an.zipWithIndex.map { case (a, i) => (a + i) % n }.distinct\n\n if (an.length == bn.length) println(\"YES\")\n else println(\"NO\")\n }\n}\n"}], "src_uid": "2173310623173d761b6039f0e5e661a8"} {"source_code": "object Holidays44C extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n solve(System.in,System.out)\n def solve(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextInt()\n val m = scanner.nextInt()\n val watered= Array.fill(n)(0)\n\n (1 to m).foreach(_ => {\n val a = scanner.nextInt()-1\n val b = scanner.nextInt()-1\n (a to b).foreach(d => watered(d) += 1)\n })\n val result = watered.zipWithIndex.find { case (w, _) => w != 1 }\n val strResult = result.map{\n case (w,day) => s\"${day+1} $w\"\n }.getOrElse(\"OK\")\n\n out.println(strResult)\n\n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val answer = Array.ofDim[Int](n + 1)\n in.take(m).map(_.split(' ').map(_.toInt - 1)).foreach{i =>\n answer(i.head) += 1\n answer(i.last + 1) -= 1\n }\n\n val (index, count, _) = (0 until n).foldLeft((-1, -1, 0)) {\n case ((-1, _, soFar), i) =>\n val nSoFar = soFar + answer(i)\n if (nSoFar < 1)\n (i, 0, 0)\n else if (nSoFar > 1)\n (i, nSoFar, 0)\n else\n (-1, -1, nSoFar)\n case (acc, el) => acc\n }\n\n if (index == -1)\n println(\"OK\")\n else\n println(s\"${index + 1} $count\")\n}"}], "negative_code": [], "src_uid": "30c4f155336cf762699a1bbc55a60d27"} {"source_code": "object CF918A extends App{\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n def fibooo(a: Int, b:Int) :Stream[Int] = a #:: fibooo(b, a + b)\n val fibooo1000 = fibooo(1, 1).takeWhile(_ <= 1000)\n println(Range(1, n + 1) map (i => if(fibooo1000 contains i) 'O' else 'o') mkString(\"\"))\n}\n", "positive_code": [{"source_code": "object A extends App {\n val n = scala.io.StdIn.readInt()\n\n def name(c: Int = 1, i: Int = 1, j: Int = 1, r: String = \"\"): String =\n if (c > n) r\n else if (c == 1) name(c + 1, i, j, r + \"O\")\n else {\n val t = i + j\n if (c == t) name(c + 1, t, i, r + \"O\")\n else name(c + 1, i, j, r + \"o\")\n }\n\n println(name())\n}\n"}, {"source_code": "object _918A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val fib = Set(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987)\n val n = io.read[Int]\n\n val ans = (1 to n).map(i => if (fib(i)) 'O' else 'o')\n\n io.write(ans.mkString)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "a7c0484275e62f0bc70d9edaac27d7d6"} {"source_code": "import scala.io.StdIn\n\nobject Maximums {\n // https://codeforces.com/problemset/problem/1326/B\n def main(args: Array[String]): Unit = {\n val nums = StdIn.readInt()\n val arrB = StdIn.readLine().split(\" \").map(_.toInt)\n\n var currMax = 0\n val arrA = arrB.map { b =>\n val a = b + currMax\n currMax = math.max(currMax, a)\n a\n }\n\n println(arrA.mkString(\" \"))\n }\n\n}\n", "positive_code": [{"source_code": "object _1326B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = {\n val bs = io.read[Seq[Int]]\n\n var a = 0\n val ans = bs map {b =>\n val ai = b + a\n a = max(a, ai)\n ai\n }\n\n io.writeAll(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}, {"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val n = in.nextInt()\n val res = Array.fill(n)(0)\n var max = 0\n (0 until n).foreach{i =>\n val b = in.nextInt()\n val a = b+max\n max = Math.max(max,a)\n\n res(i) = a\n }\n out.println(res.mkString(\" \"))\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}], "negative_code": [], "src_uid": "e22b10cdc33a165fbd73b45dc5fbedce"} {"source_code": "object CF611B extends App {\n\n import scala.io.StdIn\n\n val q = StdIn.readInt\n for (_ <- 0 until q) {\n val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)\n\n val rest = n%k\n println(n - n%k + Math.min(k/2, rest))\n }\n}\n", "positive_code": [{"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n\n val t = stdin.next().toInt\n println(stdin.take(t).map(_.split(\" \").map(_.toInt)).map(arr => calc(arr(0), arr(1))).mkString(\"\\n\"))\n\n def calc(bonbons: Int, kids: Int): Int = bonbons / kids * kids + Math.min(bonbons % kids, kids / 2)\n}"}], "negative_code": [{"source_code": "case class Trap(l: Int, r: Int, d: Int)\n\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n\n val t = stdin.next().toInt\n println(stdin.take(t).map(_.split(\" \").map(_.toInt)).map(arr => calc(arr(0), arr(1))).mkString(\" \"))\n\n def calc(hours: Int, minutes: Int): Int = (23 - hours) * 60 + (60 - minutes)\n}\n\n\n"}], "src_uid": "43b8e9fb2bd0ec5e0250a33594417f63"} {"source_code": "import java.util.Scanner\n\nobject Main {\n\n\tdef main(args: Array[String]): Unit = {\n\t\tval scanner = new Scanner (System.in)\n\t\tval n = scanner nextInt ()\n\t\tval p = List.tabulate (n) (i => scanner nextInt ())\n\t\tval ans = (p.sum: Double) / n\n\t\tprintln (ans)\n\t}\n\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject A extends App {\n\n val n = StdIn.readInt()\n val arr = StdIn.readLine().split(\" \").map(_.toDouble)\n println(arr.sum/n)\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P200B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n\n val answer: Double = List.fill(N)(sc.nextInt).sum * 1.0 / N\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "object BDrinks extends App {\n import scala.io.StdIn._\n\n val n = readInt()\n val pn = readLine().split(\" \").map(_.toInt)\n\n val ans = pn.sum.toDouble / n\n\n println(ans)\n}\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val n = readInt\n def ans = readInts.map(_.toDouble).sum / n\n\n def main(a: Array[String]) {\n println(\"%.10f\".formatLocal(Locale.US, ans))\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toDouble)\n println(a.sum / n)\n }\n}"}, {"source_code": "/**\n * 200 B. Drinks\n *\n * Created by yamaton on 11/19/15.\n */\n\nobject CF200B {\n\n def main(args: Array[String]) {\n val n = io.StdIn.readInt()\n val xs = io.StdIn.readLine.split(\" \").map(_.toInt).toSeq\n assert(xs.length == n)\n val ans = solve(xs)\n println(\"%.12f\".format(ans))\n }\n\n def solve(xs: Seq[Int]): Double = {\n xs.sum.toDouble / xs.length\n }\n\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject _200B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val sum = (1 to n).map(i => next.toInt).sum\n printf(\"%.14f\".format(1.0 * sum / n))\n}\n"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n in.next()\n val d = in.next().split(\" \").map(_.toInt)\n println(d.sum.toDouble / d.length)\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Drinks extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n val values = for (i <- 1 to n) yield sc.nextInt()\n println(values.sum.toDouble / values.length)\n}\n"}], "negative_code": [], "src_uid": "580596d05a2eaa36d630d71ef1055c43"} {"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n val n = readInt()\n val LeftInf = 10L * Int.MinValue\n val RightInf = 10L * Int.MaxValue\n val a = LeftInf +: readLine().split(\" \").map(_.toLong) :+ RightInf\n for (i <- 1 to n) {\n val max = (a(i) - a(1)) max (a(n) - a(i))\n val min = (a(i) - a(i - 1)) min (a(i + 1) - a(i))\n println(min + \" \" + max)\n }\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val cities = new Array[Int](n)\n val min = new Array[Int](n)\n val max = new Array[Int](n)\n for (i <- 0 until n) {\n cities(i) = nextInt\n }\n for (i <- 1 until n - 1) {\n min(i) = Math.min(cities(i + 1) - cities(i), cities(i) - cities(i - 1))\n max(i) = Math.max(cities(n - 1) - cities(i), cities(i) - cities(0))\n }\n min(n - 1) = cities(n - 1) - cities(n - 2)\n max(n - 1) = cities(n - 1) - cities(0)\n min(0) = cities(1) - cities(0)\n max(0) = cities(n - 1) - cities(0)\n for (i <- 0 until n) {\n println(min(i) + \" \" + max(i))\n }\n return 0\n }\n}\n"}, {"source_code": "import io.StdIn._\n\nobject Solution {\n\n def main(args: Array[String]) {\n val n = readInt()\n val cities = readLine().split(\" \").map(_.toInt)\n\n for ((c, i) <- cities.zipWithIndex) {\n if (i == 0) println((cities(i+1) - c) + \" \" + (cities.last - c))\n else if (i == cities.length - 1) println((c - cities(i-1)) + \" \" + (c - cities.head))\n else println(Math.min(cities(i+1) - c, c - cities(i-1)) + \" \" + Math.max(cities.last - c, c - cities.head))\n }\n\n }\n\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util.control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _567A extends CodeForcesApp[Seq[String]]({scanner => import scanner._\n val n = nextInt\n val p = IndexedSeq.fill(n)(nextInt)\n for {\n i <- p.indices\n } yield {\n def d(x: Int) = (p(i) - p(x)).abs\n val (u, v) = if(i == 0) {\n d(1) -> d(n-1)\n } else if (i == n-1) {\n d(n-2) -> d(0)\n } else {\n (d(i-1) min d(i+1)) -> (d(0) max d(n-1))\n }\n s\"$u $v\"\n }\n}) {\n override def format(result: Seq[String]) = result.mkString(\"\", \"\\n\", \"\")\n}\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n import scala.collection.mutable.{Map => Dict}\n final def isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def counter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n readLine()\n val x = readLine().split(\" \").map(_.toInt)\n\n val LastIndex = x.length - 1\n\n for (i <- x.indices) {\n val min = i match {\n case 0 => Math.abs(x(0) - x(1))\n case LastIndex => Math.abs(x(i - 1) - x(i))\n case _ => Math.min(Math.abs(x(i) - x(i - 1)), Math.abs(x(i) - x(i + 1)))\n }\n\n val max = Math.max(Math.abs(x(0) - x(i)), Math.abs(x.last - x(i)))\n\n println(s\"$min $max\")\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.annotation._\nimport scala.math._\n\nobject Solution {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n\n val n = scanner.nextInt\n\n val nums = Array.fill(n)(scanner.nextLong)\n\n println(s\"${nums(1)-nums(0)} ${nums(n-1)-nums(0)}\")\n\n for (i <- 1 until (n-1)) {\n val minCost = min(nums(i)-nums(i-1), nums(i+1)-nums(i))\n val maxCost = max(nums(n-1)-nums(i), nums(i)-nums(0))\n println(s\"$minCost $maxCost\")\n }\n\n println(s\"${nums(n-1)-nums(n-2)} ${nums(n-1)-nums(0)}\")\n }\n}\n"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nimport Math.min\nimport Math.max\n\n\nobject LinelandMail {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readLongs() : Array[Long] = \n readLine.split(' ').map(_.toLong)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n \n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n \n \n \n def main(args: Array[String]) : Unit = {\n val n = readInt\n val xs = readInts\n val first = xs(0)\n val last = xs(n-1)\n println( xs(1)-first + \" \" + (last-first))\n xs.zipWithIndex.tail.init.foreach {\n case (x,i) =>\n println( min(x-xs(i-1),xs(i+1)-x) + \" \" \n + max(x-first,last-x) )\n }\n println( last - xs(n-2) + \" \" + (last-first))\n }\n \n}"}, {"source_code": "// package c567.a\nobject Solution extends App {\n import scala.io.StdIn\n import scala.math.{min, max}\n val n = StdIn.readInt()\n val xs = StdIn.readLine().split(\" \").map(_.toInt).toVector\n val first = xs.head\n val last = xs.last\n def m(i: Int, ai: Int): Unit = ()\n println(s\"${xs.tail.head - first} ${last - first}\")\n xs.zipWithIndex\n .slice(1, xs.length - 1)\n .foreach { case (a: Int, i: Int) ⇒\n println(s\"${min(a - xs(i - 1), xs(i + 1) - a)} ${max(a - first, last - a)}\")\n }\n println(s\"${last - xs(xs.size - 2)} ${last - first}\")\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject CF567A extends App {\n val n = readInt()\n val x = readLine().split(\" \").map(_.toLong)\n\n for (i <- 0 to x.length - 1) {\n val max = Math.max(Math.abs(x(i) - x.head), Math.abs(x.last - x(i)))\n val min = Math.min(\n Math.abs(x(i) - x.lift(i - 1).getOrElse(Long.MinValue)),\n Math.abs(x.lift(i + 1).getOrElse(Long.MaxValue) - x(i))\n )\n println(min + \" \" + max)\n }\n}"}, {"source_code": "import java.util.Scanner\nimport Array._\n\nobject Codeforces extends App { \n val in = new Scanner(System.in)\n val n = in.nextInt()\n val x = ofDim[Long](n + 2)\n x(0) = (-1e18).toLong\n x(n + 1) = (1e18).toLong\n for (i <- 1 to n) {\n x(i) = in.nextLong()\n }\n for (i <- 1 to n) {\n var p = math.min(x(i) - x(i - 1), x(i + 1) - x(i))\n var q = math.max(x(i) - x(1), x(n) - x(i))\n printf(\"%d %d\\n\", p, q)\n }\n}"}, {"source_code": "import scala.annotation.tailrec\n\n\n// -----------------------------------------------------------------------------\n// -----------------------------------------------------------------------------\nobject Main {\n // Document: http://www.scala-lang.org/api/current/#package\n // -----------------------------------------------------------------------------\n def main(args : Array[String]) : Unit = {\n val n = readLine().toInt\n val x = readLine().split(\" \").map(_.toLong)\n val first = x.head\n val last = x.last\n val ret = (x.zipWithIndex) map {case (xi,i) =>\n if(i == 0)\n ((xi - x(i+1)).abs, (xi-last).abs)\n else if(i == x.length-1)\n ((xi - x(i-1)).abs, (xi-first).abs)\n else\n ((((xi-x(i+1)).abs) min (xi-x(i-1)).abs),\n ((xi-first).abs max (xi-last).abs))\n }\n ret.foreach({case (min,max) => println(s\"$min $max\")})\n }\n}\n\n"}, {"source_code": "object A567 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readLongs(n)\n val ans = Array.fill(n){Array(Long.MaxValue, 0L)}\n for(i <- 0 until n) {\n // min\n if(i-1 >= 0) {\n ans(i)(0) = math.min(ans(i)(0), math.abs(input(i) - input(i-1)))\n }\n if(i+1 < n) {\n ans(i)(0) = math.min(ans(i)(0), math.abs(input(i) - input(i+1)))\n }\n // max\n if(i != 0) {\n ans(i)(1) = math.max(ans(i)(1), math.abs(input(i) - input(0)))\n }\n if(i != n-1) {\n ans(i)(1) = math.max(ans(i)(1), math.abs(input(i) - input(n-1)))\n }\n }\n println(ans.map(_.mkString(\" \")).mkString(\"\\n\"))\n }\n}"}, {"source_code": "object A extends App {\n val n = readLine.toInt\n val str = readLine\n val arr = str.split(\" \").map(_.toInt)\n val mn = arr(0)\n val mx = arr(n - 1)\n \n import scala.math._\n \n print(arr(1) - arr(0))\n print(\" \")\n println(mx - arr(0))\n \n for(i <- (1 until n - 1)) {\n print(min(abs(arr(i) - arr(i-1)), abs(arr(i + 1) - arr(i))))\n print(\" \")\n println(\n max(\n abs(arr(i) - mn), \n abs(mx - arr(i))\n )\n )\n }\n \n print(mx - arr(n - 2))\n print(\" \")\n println(mx - mn)\n}"}, {"source_code": "// So you like object Task\nimport java.io.{IOException, InputStream, PrintWriter}\nimport java.util.InputMismatchException\n\nobject Task {\n\n\n def solve(in: InputReader, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val a = Array.fill(n)(in.nextInt())\n for (i <- 0 until n) {\n val minCost = (if (i == 0) Long.MaxValue else (a(i) - a(i - 1)).abs) min (if (i == n - 1) Long.MaxValue else (a(i) - a(i + 1)).abs)\n val maxCost = (if (i == 0) Long.MinValue else (a(i) - a(0)).abs) max (if (i == n - 1) Long.MinValue else (a(i) - a(n - 1)).abs)\n println(\"%d %d\".format(minCost, maxCost))\n }\n }\n\n def main(args: Array[String]) {\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n in.close()\n out.close()\n }\n}\n\nclass InputReader(val inputStream: InputStream) {\n val buf = new Array[Byte](1 << 16)\n var curChar = 0\n var numChars = 0\n\n def read(): Int = {\n if (numChars == -1) {\n throw new InputMismatchException()\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => throw new InputMismatchException()\n }\n if (numChars <= 0)\n return -1\n }\n curChar += 1\n buf(curChar - 1)\n }\n\n def peek(): Int = {\n if (numChars == -1) {\n return -1\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => return -1\n }\n if (numChars <= 0)\n return -1\n }\n buf(curChar)\n }\n\n def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n\n def nextInt(): Int = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextLong(): Long = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0l\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def next(): String = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n val res = new StringBuilder()\n do {\n res += c.toChar\n c = read()\n } while(!isSpaceChar(c))\n res.toString()\n }\n\n def nextChar(): Char = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n c.toChar\n }\n\n //noinspection AccessorLikeMethodIsEmptyParen\n def hasNext(): Boolean = {\n var value = peek()\n do {\n read()\n value = peek()\n } while (isSpaceChar(value) && value != -1)\n value != -1\n }\n\n def rawNextLine(): String = {\n val builder = new StringBuilder\n var c = read()\n while (c != '\\n' && c != -1) {\n if (c != '\\r')\n builder += c.toChar\n c = read()\n }\n builder.toString()\n }\n\n def nextLine(): String = {\n var s = rawNextLine()\n while (s.trim().length == 0) s = rawNextLine()\n s\n }\n\n def nextDouble(): Double = {\n next().toDouble\n }\n\n def close(): Unit = {\n inputStream.close()\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n val n = readInt()\n val a = Int.MinValue.toLong +: readLine().split(\" \").map(_.toLong) :+ Int.MaxValue.toLong\n for (i <- 1 to n) {\n val max = (a(i) - a(1)) max (a(n) - a(i))\n val min = (a(i) - a(i - 1)) min (a(i + 1) - a(i))\n println(min + \" \" + max)\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n val n = readInt()\n val a = Int.MinValue +: readLine().split(\" \").map(_.toInt) :+ Int.MaxValue\n for (i <- 1 to n) {\n val max = (a(i) - a(1)) max (a(n) - a(i))\n val min = (a(i) - a(i - 1)) min (a(i + 1) - a(i))\n println(min + \" \" + max)\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n val n = readInt()\n val a = Long.MinValue +: readLine().split(\" \").map(_.toLong) :+ Long.MaxValue\n for (i <- 1 to n) {\n val max = (a(i) - a(1)) max (a(n) - a(i))\n val min = (a(i) - a(i - 1)) min (a(i + 1) - a(i))\n println(min + \" \" + max)\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject CF567A extends App {\n val n = readInt()\n val x = readLine().split(\" \").map(_.toInt)\n\n for (i <- 0 to x.length - 1) {\n val max = Math.max(x(i) - x.head, x.last - x(i))\n val min = Math.min(x(i) - x.lift(i - 1).getOrElse(Int.MaxValue), x.lift(i + 1).getOrElse(Int.MaxValue) - x(i))\n println(min + \" \" + max)\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject CF567A extends App {\n val n = readInt()\n val x = readLine().split(\" \").map(_.toLong)\n\n for (i <- 0 to x.length - 1) {\n val max = Math.max(x(i) - x.head, x.last - x(i))\n val min = Math.min(x(i) - x.lift(i - 1).getOrElse(Long.MaxValue), x.lift(i + 1).getOrElse(Long.MaxValue) - x(i))\n println(min + \" \" + max)\n }\n}"}, {"source_code": "object A extends App {\n val n = readLine.toInt\n val str = readLine\n val arr = str.split(\" \").map(_.toInt)\n val mn = arr(0)\n val mx = arr(n - 1)\n \n import scala.math._\n \n print(arr(1) - arr(0))\n print(\" \")\n println(mx - arr(0))\n \n for(i <- (1 until n - 1)) {\n print(max(abs(arr(i) - arr(i-1)), abs(arr(i + 1) - arr(i))))\n print(\" \")\n println(\n max(\n abs(arr(i) - mn), \n abs(mx - arr(i))\n )\n )\n }\n \n print(mx - arr(n - 2))\n print(\" \")\n println(mx - mn)\n}"}], "src_uid": "55383f13c8d097408b0ccf5653c4563d"} {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(x1, y1, x2, y2) = scala.io.StdIn.readLine().split(\" \").map(_.toLong)\n\n val ans = (x2 - x1) * (y2 - y1) + 1\n\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val arr = readIntLine()\n println(calcWays(arr(2) - arr.head, arr.last - arr(1)))\n }\n // println(calcWays(4, 5))\n }\n \n\n def calcWays(x: Int, y: Int): Long = x.toLong * y + 1\n\n def makeArray(n: Int) {\n class QueueElement(val left: Int, val right: Int) {}\n\n val arr = Array.ofDim[Int](n)\n val intervals = (0 to n).map(_ => ListBuffer[QueueElement]()).toArray\n intervals(n) += new QueueElement(0, n - 1)\n var count = 1\n for (i <- (0 to n).reverse) {\n var intOfLengthI = intervals(i)\n intOfLengthI = intOfLengthI.sortBy(_.left)\n for (j <- intOfLengthI.indices) {\n val head = intOfLengthI(j)\n if (head.left == head.right) {\n arr(head.left) = count\n } else {\n val mid = (head.left + head.right) / 2\n arr(mid) = count\n if (mid != head.left) intervals(mid - head.left) += new QueueElement(head.left, mid - 1)\n intervals(head.right - mid) += new QueueElement(mid + 1, head.right)\n }\n count += 1\n }\n }\n\n printArray(arr)\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}], "negative_code": [{"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val arr = readIntLine()\n println(calcWays(arr(2) - arr.head, arr.last - arr(1)))\n }\n// println(calcWays(4, 5))\n }\n\n def calcWays(x: Int, y: Int): BigInt = {\n if (x < 0 || y < 0) 0\n if (x == 0 || y == 0) 1 else {\n val i = Math.max(x + 1, y + 1)\n val j = Math.min(x + 1, y + 1)\n\n def sum(list: List[BigInt], acc: BigInt, listAcc: List[BigInt]): List[BigInt] = list match {\n case Nil => listAcc.reverse\n case s :: ss => sum(ss, acc + s, (acc + s) :: listAcc)\n }\n\n def helper(prev: List[BigInt], j: Int): BigInt = if (j == 1) prev.last\n else helper(sum(prev, 0, Nil), j - 1)\n\n helper((1 to i).map(_ => BigInt(1)).toList, j)\n }\n }\n\n def makeArray(n: Int) {\n class QueueElement(val left: Int, val right: Int) {}\n\n val arr = Array.ofDim[Int](n)\n val intervals = (0 to n).map(_ => ListBuffer[QueueElement]()).toArray\n intervals(n) += new QueueElement(0, n - 1)\n var count = 1\n for (i <- (0 to n).reverse) {\n var intOfLengthI = intervals(i)\n intOfLengthI = intOfLengthI.sortBy(_.left)\n for (j <- intOfLengthI.indices) {\n val head = intOfLengthI(j)\n if (head.left == head.right) {\n arr(head.left) = count\n } else {\n val mid = (head.left + head.right) / 2\n arr(mid) = count\n if (mid != head.left) intervals(mid - head.left) += new QueueElement(head.left, mid - 1)\n intervals(head.right - mid) += new QueueElement(mid + 1, head.right)\n }\n count += 1\n }\n }\n\n printArray(arr)\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}, {"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val arr = readIntLine()\n println(calcWays(arr(2) - arr.head, arr.last - arr(1)))\n }\n// println(calcWays(1, 2))\n }\n\n def calcWays(x: Int, y: Int): BigInt = {\n if (x == 0 || y == 0) 1 else {\n val i = Math.max(x + 1, y + 1)\n val j = Math.min(x + 1, y + 1)\n\n def sum(list: List[BigInt], acc: BigInt, listAcc: List[BigInt]): List[BigInt] = list match {\n case Nil => listAcc.reverse\n case s :: ss => sum(ss, acc + s, (acc + s) :: listAcc)\n }\n\n def helper(prev: List[BigInt], j: Int): BigInt = if (j == 1) prev.last\n else helper(sum(prev, 0, Nil), j - 1)\n\n helper((1 to i).map(_ => BigInt(1)).toList, j)\n }\n }\n\n def makeArray(n: Int) {\n class QueueElement(val left: Int, val right: Int) {}\n\n val arr = Array.ofDim[Int](n)\n val intervals = (0 to n).map(_ => ListBuffer[QueueElement]()).toArray\n intervals(n) += new QueueElement(0, n - 1)\n var count = 1\n for (i <- (0 to n).reverse) {\n var intOfLengthI = intervals(i)\n intOfLengthI = intOfLengthI.sortBy(_.left)\n for (j <- intOfLengthI.indices) {\n val head = intOfLengthI(j)\n if (head.left == head.right) {\n arr(head.left) = count\n } else {\n val mid = (head.left + head.right) / 2\n arr(mid) = count\n if (mid != head.left) intervals(mid - head.left) += new QueueElement(head.left, mid - 1)\n intervals(head.right - mid) += new QueueElement(mid + 1, head.right)\n }\n count += 1\n }\n }\n\n printArray(arr)\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}, {"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val arr = readIntLine()\n println(calcWays(arr(2) - arr.head, arr.last - arr(1)))\n }\n// println(calcWays(4, 5))\n }\n\n def calcWays(x: Int, y: Int): BigInt = {\n if (x < 0 || y < 0) 0\n else if (x == 0 || y == 0) 1 else {\n val i = Math.max(x + 1, y + 1)\n val j = Math.min(x + 1, y + 1)\n\n def sum(list: List[BigInt], acc: BigInt, listAcc: List[BigInt]): List[BigInt] = list match {\n case Nil => listAcc.reverse\n case s :: ss => sum(ss, acc + s, (acc + s) :: listAcc)\n }\n\n def helper(prev: List[BigInt], j: Int): BigInt = if (j == 1) prev.last\n else helper(sum(prev, 0, Nil), j - 1)\n\n helper((1 to i).map(_ => BigInt(1)).toList, j)\n }\n }\n\n def makeArray(n: Int) {\n class QueueElement(val left: Int, val right: Int) {}\n\n val arr = Array.ofDim[Int](n)\n val intervals = (0 to n).map(_ => ListBuffer[QueueElement]()).toArray\n intervals(n) += new QueueElement(0, n - 1)\n var count = 1\n for (i <- (0 to n).reverse) {\n var intOfLengthI = intervals(i)\n intOfLengthI = intOfLengthI.sortBy(_.left)\n for (j <- intOfLengthI.indices) {\n val head = intOfLengthI(j)\n if (head.left == head.right) {\n arr(head.left) = count\n } else {\n val mid = (head.left + head.right) / 2\n arr(mid) = count\n if (mid != head.left) intervals(mid - head.left) += new QueueElement(head.left, mid - 1)\n intervals(head.right - mid) += new QueueElement(mid + 1, head.right)\n }\n count += 1\n }\n }\n\n printArray(arr)\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}, {"source_code": "object C extends App {\n private def gazGiz(x: Long, y: Long): Long =\n x + (x + y - 1) * (x + y - 2) / 2\n\n private def binomial(n: Int, k: Int): Long =\n if (k > n - k) binomial(n, n - k)\n else (1 to k).foldLeft(1L)((b, i) => b * (n - k + i) / i)\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(x1, y1, x2, y2) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val r = y2 - y1\n val d = x2 - x1 + y2 - y1\n\n val ans = binomial(d, r)\n\n println(ans)\n }\n}\n"}, {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(x1, y1, x2, y2) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val ans = (x2 - x1) * (y2 - y1) + 1\n\n println(ans)\n }\n}\n"}], "src_uid": "1b13c9d9fa0c5a44d035bcf6d70e1a60"} {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toLong)\n val (h, c, t) = (input(0), input(1), input(2))\n if (2*t <= h +c) println(2)\n else {\n val n = (h-t)/(2 *t-h-c)\n val (n1, n2) = (n, n+1)\n val d1 = (n1*c+(n1+1)*h)-t*(2*n1+1)\n val d2 = t*(2*n2+1)-(n2*c+(n2+1)*h)\n val res = if (d1*(2*n2+1) > d2*(2*n1+1)) 2*n2+1 else 2*n1+1\n println(res)\n }\n }\n }\n}\n", "positive_code": [{"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(h, c, t) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val d = c + h - 2 * t\n\n val ans =\n if (d >= 0) 2\n else if (h <= t) 1\n else if (c >= t) 2\n else { // c < t < h\n val k = (t - h) / d.toDouble\n val ks = List(k.ceil, k.floor).sorted.sortBy(k => math.abs((h - t + k * d) / (1.0 + 2 * k)))\n\n (1 + 2 * ks.head).toInt\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "//package codeforces.contests._1359\n\nobject _3 {\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(h, c, t) = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n println {\n if (t >= h) 1\n else if (t <= (h + c) / 2.0) 2\n else {\n def nearest(y: Long): BigDecimal = (BigDecimal((y + 1) * h + y * c) / BigDecimal(2.0 * y + 1) - BigDecimal(t)).abs\n\n def solve(y: Long): (BigDecimal, Long) = (nearest(y), 2 * y + 1)\n\n val y = (t - h) / (h + c - 2 * t)\n\n val ls = List(solve(y - 1), solve(y), solve(y + 1))\n\n val min = ls.minBy(_._1)._1\n\n ls.filter(_._1 == min).minBy(_._2)._2\n }\n }\n }\n }\n}\n"}, {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(h, c, t) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val d = c + h - 2 * t\n\n val ans =\n if (d >= 0) 2\n else if (h <= t) 1\n else if (c >= t) 2\n else { // c < t < h\n val k = (t - h) / d.toDouble\n val ks = List(k.floor, k.ceil).sortBy(k => math.abs((h - t + k * d) / (1.0 + 2 * k)))\n\n (1 + 2 * ks.head).toInt\n }\n\n println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1359\n\nobject _3 {\n\n import math._\n\n // 999977 17 499998\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(h, c, t) = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val second = (abs((h + c) - 2 * t).toDouble, 2L)\n\n def nearest(y: Long): Long = abs(((y + 1) * h + y * c) - (y + 1 + y) * t)\n\n def solve(y: Long): (Double, Long) = (nearest(y), 2 * y + 1)\n\n val y = {\n val temp = ((t - h) * 1.0) / (h + c - 2 * t)\n if (temp < 0) 0 else temp.ceil.toLong\n }\n\n val third = solve(y)\n\n val ls = List(second, third)\n\n val min = ls.minBy(_._1)._1\n\n println {\n ls.filter(_._1 == min).minBy(_._2)._2\n }\n }\n }\n}\n"}, {"source_code": "//package codeforces.contests._1359\n\nobject _3 {\n\n import math._\n\n // 999977 17 499998\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(h, c, t) = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val second = (abs((h + c) - 2 * t).toDouble, 2L)\n\n def nearest(y: Long): Long = abs(((y + 1) * h + y * c) - (y + 1 + y) * t)\n\n def solve(y: Long): (Double, Long) = (nearest(y), 2 * y + 1)\n\n val y = {\n val temp = ((t - h) * 1.0) / (h + c - 2 * t)\n if (temp < 0) 0 else temp.floor.toLong\n }\n\n val (df, dfy) = solve(y)\n val (dc, dcy) = solve(y + 1)\n\n val odd = if(df >= dc) (dc, dcy) else (df, dfy)\n\n val ls = List(second, odd)\n\n val min = ls.minBy(_._1)._1\n\n println {\n ls.filter(_._1 == min).minBy(_._2)._2\n }\n }\n }\n}\n"}, {"source_code": "//package codeforces.contests._1359\n\nobject _3 {\n\n import math._\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(h, c, t) = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val first = (abs(h - t).toDouble, 1L)\n val second = (abs((h + c) - 2 * t).toDouble, 2L)\n\n def nearest(y: Long): Double = abs(((y + 1) * h + y * c) * 1.0 / (y + 1 + y) - t)\n\n def solve(y: Long): (Double, Long) = (nearest(y), 2 * y + 1)\n\n val y = {\n val temp = ((t - h) * 1.0) / (h + c - 2 * t)\n if (temp < 0) 0 else temp.floor.toLong\n }\n\n val third = solve(y)\n val fourth = solve(y + 1)\n\n val ls = List(first, second, third, fourth)\n\n val min = ls.minBy(_._1)._1\n\n println {\n ls.filter(_._1 == min).minBy(_._2)._2\n }\n }\n }\n}\n"}, {"source_code": "//package codeforces.contests._1359\n\nobject _3 {\n\n import math._\n\n // 999977 17 499998\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(h, c, t) = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val second = (abs((h + c) - 2 * t).toDouble, 2L)\n\n def nearest(y: Long): Long = abs(((y + 1) * h + y * c) - (y + 1 + y) * t)\n\n def solve(y: Long): (Double, Long) = (nearest(y), 2 * y + 1)\n\n val y = {\n val temp = ((t - h) * 1.0) / (h + c - 2 * t)\n if (temp < 0) 0 else temp.round\n }\n\n val third = solve(y)\n\n val ls = List(second, third)\n\n val min = ls.minBy(_._1)._1\n\n println {\n ls.filter(_._1 == min).minBy(_._2)._2\n }\n }\n }\n}\n"}, {"source_code": "//package codeforces.contests._1359\n\nobject _3 {\n\n import math._\n\n // 999977 17 499998\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(h, c, t) = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val second = (abs((h + c) - 2 * t).toDouble, 2L)\n\n def nearest(y: Long): Double = abs(((y + 1) * h + y * c) * 1.0 / (y + 1 + y) - t)\n\n def solve(y: Long): (Double, Long) = (nearest(y), 2 * y + 1)\n\n val y = {\n val temp = ((t - h) * 1.0) / (h + c - 2 * t)\n if (temp < 0) 0 else temp.floor.toLong\n }\n\n val (df, dfy) = solve(y)\n val (dc, dcy) = solve(y + 1)\n\n val odd = if (df >= dc) (dc, dcy) else (df, dfy)\n\n val ls = List(second, odd)\n\n val min = ls.minBy(_._1)._1\n\n println {\n ls.filter(_._1 == min).minBy(_._2)._2\n }\n }\n }\n}\n"}, {"source_code": "//package codeforces.contests._1359\n\nobject _3 {\n\n import math._\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(h, c, t) = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val first = (abs(h - t).toDouble, 1L)\n val second = (abs((h + c) / 2 - t).toDouble, 2L)\n\n val y = {\n val temp = (t - h) * 1.0 / (h + c - 2 * t)\n if (temp < 0) 0 else temp.floor.toLong\n }\n\n def nearest(y: Long): Double = ((y + 1) * h + y * c) * 1.0 / (y + 1 + y)\n\n val third: (Double, Long) = (abs(nearest(y) - t), 2 * y + 1)\n\n val fourth = (abs(nearest(y + 1) - t), 2 * (y + 1) + 1)\n\n val fifth = {\n val ty = (y - 1) max 0\n (abs(nearest(ty) - t), 2 * ty + 1)\n }\n\n val ls = List(first, second, third, fourth, fifth)\n\n val min = ls.minBy(_._1)._1\n\n println {\n ls.filter(_._1 == min).minBy(_._2)._2\n }\n }\n }\n}\n"}, {"source_code": "//package codeforces.contests._1359\n\nobject _3 {\n\n import math._\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(h, c, t) = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val first = (abs(h - t).toDouble, 1L)\n val second = (abs((h + c) / 2 - t).toDouble, 2L)\n\n def nearest(y: Long): Double = abs(((y + 1) * h + y * c) * 1.0 / (y + 1 + y) - t)\n\n def solve(y: Long): (Double, Long) = (nearest(y), 2 * y + 1)\n\n val y = {\n val temp = ((t - h) * 1.0) / (h + c - 2 * t)\n if (temp < 0) 0 else temp.floor.toLong\n }\n\n val third = solve(y)\n val fourth = solve(y + 1)\n\n val ls = List(first, second, third, fourth)\n\n val min = ls.minBy(_._1)._1\n\n println {\n ls.filter(_._1 == min).minBy(_._2)._2\n }\n }\n }\n}\n"}, {"source_code": "//package codeforces.contests._1359\n\nobject _3 {\n\n import math._\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(h, c, t) = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val first = (abs(h - t).toDouble, 1L)\n val second = (abs((h + c) - 2*t).toDouble, 2L)\n\n def nearest(y: Long): Long = abs(((y + 1) * h + y * c) - (y + 1 + y) * t)\n\n def solve(y: Long): (Double, Long) = (nearest(y), 2 * y + 1)\n\n val y = {\n val temp = ((t - h) * 1.0) / (h + c - 2 * t)\n if (temp < 0) 0 else temp.floor.toLong\n }\n\n val third: (Double, Long) = solve((y - 1) max 0)\n val fourth = solve(y)\n val fifth = solve(y + 1)\n val sixth = solve(y + 2)\n val seventh = solve(y + 3)\n val eigth = solve((y - 2) max 0)\n\n val ls = List(first, second, third, fourth, fifth, sixth, seventh, eigth)\n\n val min = ls.minBy(_._1)._1\n\n println {\n ls.filter(_._1 == min).minBy(_._2)._2\n }\n }\n }\n}\n"}, {"source_code": "//package codeforces.contests._1359\n\nobject _3 {\n\n import math._\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(h, c, t) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val first = (abs(h - t).toDouble, 1)\n val second = (abs((h + c) / 2 - t).toDouble, 2)\n\n val y = {\n val temp = (t - h) * 1.0 / (h + c - 2 * t)\n if (temp < 0) 0 else temp.floor.toInt\n }\n\n def nearest(y: Int): Double = ((y + 1) * h + y * c) * 1.0 / (y + 1 + y)\n\n val third = (abs(nearest(y) - t), 2*y+1)\n\n val fourth = (abs(nearest(y + 1) - t), 2*(y+1) + 1)\n\n val ls = List(first, second, third, fourth)\n\n val min = ls.minBy(_._1)._1\n\n println {\n ls.filter(_._1 == min).minBy(_._2)._2\n }\n }\n }\n}\n"}, {"source_code": "//package codeforces.contests._1359\n\nobject _3 {\n\n import math._\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(h, c, t) = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val first = (abs(h - t).toDouble, 1L)\n val second = (abs((h + c) / 2 - t).toDouble, 2L)\n\n def nearest(y: Long): Double = ((y + 1) * h + y * c) * 1.0 / (y + 1 + y)\n\n def solve(y: Long): (Double, Long) = (abs(nearest(y) - t), 2 * y + 1)\n\n val y = {\n val temp = (t - h) * 1.0 / (h + c - 2 * t)\n if (temp < 0) 0 else temp.floor.toLong\n }\n\n val third: (Double, Long) = solve((y - 1) max 0)\n val fourth = solve(y)\n val fifth = solve(y + 1)\n val sixth = solve(y + 2)\n val seventh = solve(y + 3)\n val eigth = solve((y - 2) max 0)\n\n val ls = List(first, second, third, fourth, fifth, sixth, seventh, eigth)\n\n val min = ls.minBy(_._1)._1\n\n println {\n ls.filter(_._1 == min).minBy(_._2)._2\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toInt)\n val (h, c, t) = (input(0), input(1), input(2))\n require(t <= h && t >= c)\n if (4*t >= 3*h+c) println(1)\n else if (2*t >= h+c) println(2)\n else {\n val dn = (t-c)/(2.0*t-h-c)\n val n1 = dn.toDouble.toInt\n val n2 = n1 + 1\n def ft(n: Int) = ((n*h)+(n-1)*c)/(2.0*n-1)\n val c1 = (ft(n1)-t).abs\n val c2 = (ft(n2)-t).abs\n if (c1 < c2) println(n1*2-1) else println(n2*2-1)\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toInt)\n val (h, c, t) = (input(0), input(1), input(2))\n if (2*t <= h +c) println(2)\n else {\n val n1 = (t-c)/(2 *t-h-c)\n def ft(n: Int) = (((n*h)+(n-1)*c)/(2.0*n-1) - t).abs\n\n val ress = (n1 to n1 + 2).map(ft)\n val res = ress.indexOf(ress.min) + n1\n println((res*2-1) max 1)\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toInt)\n val (h, c, t) = (input(0), input(1), input(2))\n require(t <= h && t >= c)\n if (4*t >= 3*h+c) println(1)\n else if (2*t <= h +c) println(2)\n else {\n val n1 = (t-c)/(2 *t-h-c)\n val n2 = n1 + 1\n def ft(n: Int) = ((n*h)+(n-1)*c)/(2.0*n-1) - t\n val c1 = ft(n1).abs\n val c2 = ft(n2).abs\n val res = if ((t-c) % (2*t-h-c) == 0 || c1 <= c2) (n1*2-1) else (n2*2-1)\n println(res max 1)\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toLong)\n val (h, c, t) = (input(0), input(1), input(2))\n if (2*t <= h +c) println(2)\n else {\n val n1 = (t-c)/(2 *t-h-c)\n def ft(n: Long) = ((((n.toLong*h)+(n-1)*c)/(2.0*n-1)) - t).abs\n val f1 = ft(n1)\n val f2 = ft(n1+1)\n val res = if (f1<=f2) n1 else n1+1\n println(res*2-1)\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toLong)\n val (h, c, t) = (input(0), input(1), input(2))\n\n if (2*t <= h +c) println(2)\n else {\n val n1 = (h-t)/(2 *t-h-c)\n def ft(n: Long) = ((n*h+n*c-c)- t*(2*n+1)).abs\n val f1 = ft(n1)\n val f2 = ft(n1+1)\n val res = if (f1<=f2) n1 else n1+1\n println(res*2+1)\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toLong)\n val (h, c, t) = (input(0), input(1), input(2))\n\n if (2*t <= h +c) println(2)\n else {\n val n1 = (h-t)/(2 *t-h-c)\n val n2 = n1 + 1\n\n val f1 = n1*c+(n1+1)*h-(2*n1+1)*t\n val f2 = 2*(n2+1)*t-n2*c-(n2+1)*h\n val res =\n if (f1 <= f2) n1 else n2\n println(res*2+1)\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toInt)\n val (h, c, t) = (input(0), input(1), input(2))\n require(t <= h && t >= c)\n if (4*t >= 3*h+c) println(1)\n else if (2*t <= h+c) println(2)\n else {\n val dn = (t-c)/(2.0*t-h-c)\n val n1 = dn.toDouble.toInt\n val n2 = n1 + 1\n def ft(n: Int) = ((n*h)+(n-1)*c)/(2.0*n-1)\n val c1 = (ft(n1)-t).abs\n val c2 = (ft(n2)-t).abs\n if (c1 < c2) println(n1*2-1) else println(n2*2-1)\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toInt)\n val (h, c, t) = (input(0), input(1), input(2))\n if (2*t <= h +c) println(2)\n else {\n val n1 = (t-c)/(2 *t-h-c)\n def ft(n: Int) = (((n*h)+(n-1)*c)/(2.0*n-1) - t).abs\n val f1 = ft(n1)\n val f2 = ft(n1+1)\n val res = if (f1<=f2) n1 else n1+1\n println((res*2-1) max 1)\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toInt)\n val (h, c, t) = (input(0), input(1), input(2))\n if (2*t <= h +c) println(2)\n else {\n val n1: Long = (t-c)/(2 *t-h-c)\n def ft(n: Long) = ((((n.toLong*h)+(n-1L)*c)/(2.0*n-1)) - t).abs\n val f1 = ft(n1)\n val f2 = ft(n1+1)\n val res = if (f1<=f2) n1 else n1+1\n println(res*2-1)\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toLong)\n val (h, c, t) = (input(0), input(1), input(2))\n\n if (2*t <= h +c) println(2)\n else {\n val n1 = (h-t)/(2 *t-h-c)\n val n2 = n1 + 1\n\n val f1 = n1*c+(n1+1)*h-(2*n1+1)*t\n val f2 = 2*(n2+1)*t-n1*c-(n1+1)*h\n val res =\n if (f1 <= f2) n1 else n2\n println(res*2+1)\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toInt)\n val (h, c, t) = (input(0), input(1), input(2))\n if (2*t <= h +c) println(2)\n else {\n val n1 = (t-c)/(2 *t-h-c)\n def ft(n: Int) = (BigDecimal(((n*h)+(n-1)*c)/(2.0*n-1)) - t).abs\n val f1 = ft(n1)\n val f2 = ft(n1+1)\n val res = if (f1<=f2) n1 else n1+1\n println(res*2-1)\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toLong)\n val (h, c, t) = (input(0), input(1), input(2))\n\n if (2*t <= h +c) println(2)\n else {\n val n1 = (t-c)/(2 *t-h-c)\n def ft(n: Long) = ((n*h+n*c+h)- t*(2*n+1)).abs\n val f1 = ft(n1)\n val f2 = ft(n1+1)\n val res = if (f1<=f2) n1 else n1+1\n println(res*2-1)\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toInt)\n val (h, c, t) = (input(0), input(1), input(2))\n if (t >= h) println(1)\n else if (2*t <= h+c) println(2)\n else {\n val dn = (t-c)/(2.0*t-h-c)\n val n1 = dn.toDouble.toInt\n val n2 = n1 + 1\n def ft(n: Int) = ((n*h)+(n-1)*c)/(2.0*n-1)\n val c1 = (ft(n1)-t).abs\n val c2 = (ft(n2)-t).abs\n if (c1 < c2) println(n1*2-1) else println(n2*2-1)\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toInt)\n val (h, c, t) = (input(0), input(1), input(2))\n require(t <= h && t >= c)\n if (4*t >= 3*h+c) println(1)\n else if (2*t <= h +c) println(2)\n else {\n val dn = (t-c)/(2.0*t-h-c)\n val n1 = dn.toDouble.toInt\n val n2 = n1 + 1\n def ft(n: Int) = ((n*h)+(n-1)*c)/(2.0*n-1)\n val c1 = (ft(n1)-t).abs\n val c2 = (ft(n2)-t).abs\n if ((t-c) % (2*t-h-c) == 0 || c1 <= c2) println(n1*2-1) else println(n2*2-1)\n }\n }\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toInt)\n val (h, c, t) = (input(0), input(1), input(2))\n if (2*t <= h +c) println(2)\n else {\n val n1 = (t-c)/(2 *t-h-c)\n val n2 = n1 + 1\n def ft(n: Int) = ((n*h)+(n-1)*c)/(2.0*n-1) - t\n val c1 = ft(n1).abs\n val c2 = ft(n2).abs\n val res = if ((t-c) % (2*t-h-c) == 0 || c1 <= c2) (n1*2-1) else (n2*2-1)\n println(res max 1)\n }\n }\n }\n}\n"}, {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(h, c, t) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val d = c + h - 2.0 * t\n\n val ans =\n if (d == 0) 2\n else 2 * math.ceil((t - h) / d).toInt + 1\n\n println(ans)\n }\n}\n"}, {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(h, c, t) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val d = c + h - 2.0 * t\n\n val ans =\n if (d == 0) 2\n else {\n val r = math.ceil(2 * (t - h) / d + 1).toInt\n\n if (r == 0) 2\n else r\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(h, c, t) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val d = c + h - 2.0 * t\n\n val ans =\n if (d == 0) 2\n else {\n val k = (t - h) / d\n\n val ks = List(0, 0.5, k.ceil, k.floor)\n .filter(_ >= 0)\n .sortBy(k => math.abs(h - t + k * (c + h - 2 * t)) / (2 * k + 1.0))\n\n 2 * ks.head.toInt + 1\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(h, c, t) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val d = c + h - 2.0 * t\n\n val ans =\n if (d == 0) 2\n else if (h <= t) 1\n else {\n val r = math.ceil(2 * (t - h) / d + 1).toInt\n if (r <= 0) 2 else r\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(h, c, t) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val d = c + h - 2.0 * t\n\n def diff(k: Double): Double = math.abs((h - t + k * d) / (2 * k + 1))\n\n val ans =\n if (d == 0) 2\n else {\n val k = (t - h) / d\n\n if (k < 0) List(1.0, 2.0).sortBy(diff).head.toInt\n else List(k.ceil, k.floor).sortBy(diff).map(2 * _ + 1).head.toInt\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(h, c, t) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val d = c + h - 2 * t\n\n val ans =\n if (d >= 0) 2\n else if (h <= t) 1\n else if (c >= t) 2\n else { // c < t < h\n val k = (t - h) / d.toDouble\n val ks = List(k.ceil, k.floor).sortBy(k => math.abs((h - t + k * d) / (1.0 + 2 * k)))\n\n// println()\n// println(s\"(c + h / 2) ? t = ${c + h - 2 * t}\")\n// println(s\"ks: ${ks.mkString(\", \")}\")\n\n (1 + 2 * ks.head).toInt\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(h, c, t) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val d = c + h - 2.0 * t\n\n val ans =\n if (d == 0) 2\n else {\n val r = math.ceil(2 * (t - h) / d + 1).toInt\n\n if (r <= 0) 2\n else r\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(h, c, t) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val d = c + h - 2.0 * t\n\n val ans =\n if (d == 0) 2\n else {\n val k = (t - h) / d\n\n val ks = List(0.5, k.ceil, k.floor)\n .filter(_ >= 0)\n .sortBy(k => math.abs(h - t + k * (c + h - 2 * t)) / (2 * k + 1.0))\n\n (2 * ks.head + 1).toInt\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(h, c, t) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val d = c + h - 2.0 * t\n\n def diff(k: Double): Double = math.abs((h - t + k * d) / (2 * k + 1))\n\n val ans =\n if (d == 0) 2\n else {\n val k = (t - h) / d\n\n if (k < 0) List(1.0, 2.0).sortBy(k => diff((k - 1) / 2)).head.toInt\n else List(k.ceil, k.floor).sortBy(diff).map(2 * _ + 1).head.toInt\n }\n\n println(ans)\n }\n}\n"}], "src_uid": "ca157773d06c7d192589218e2aad6431"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline private final def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val n, x = ni()\n out.println(x * 2)\n }\n }\n}", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n def solve(): Unit = {\n val n = ni()\n val A = na(2*n)\n var i = 1;\n while(i < 2*n){\n \tvar a = A(i)\n\t\tprintln(2*A(i))\n \ti += 2;\n }\n\n }\n}"}, {"source_code": "import Array._\nimport scala.collection.mutable.ListBuffer\n\n/**\n1 2 3 4 5 6 7 8 9 10 11 12\n 2 3 4 5 6 7 8 9 10 11 12\n 2 4 5 6 7 8 9 10 11 12\n 2 4 6 7 8 9 10 11 12\n 2 4 6 8 9 10 11 12\n 2 4 6 8 10 11 12\n 2 4 6 8 10 12\n**/\n\nobject Main {\n def main(args: Array[String]) {\n val in = new java.util.Scanner(System.in)\n val lineNumber = in.next().toInt\n for ( i <- 0 until lineNumber ) {\n val n = in.next().toInt\n val x = in.next().toInt\n println(x*2)\n }\n }\n}\n\n \n \n "}], "negative_code": [], "src_uid": "f79a926e18a3f81b24f2fc3ae5c8f928"} {"source_code": "import scala.collection._\n\nobject B extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val n = readInt\n val xSet = mutable.BitSet.empty ++ readInts(n)\n\n val S = 1000000\n \n val res = mutable.ArrayBuffer[Int]()\n var debt = 0\n \n for (x <- 1 to S / 2) {\n val y = S - x + 1\n if (xSet(x) && !xSet(y)) {\n res += y\n xSet += y\n } else if (!xSet(x) && xSet(y)) {\n res += x\n xSet += x\n } else if (xSet(x) && xSet(y)) {\n debt += 1\n }\n }\n \n for (x <- 1 to S / 2) {\n val y = S - x + 1\n if (debt > 0 && !xSet(x) && !xSet(y)) {\n res += y\n res += x\n debt -= 1\n }\n }\n \n println(res.size)\n println(res.mkString(\" \"))\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject B extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n\n val n = readInt\n val xSet = mutable.BitSet.empty ++ readInts(n)\n\n val S = 1000000\n \n val res = mutable.ArrayBuffer[Int]()\n var debt = 0\n \n for (x <- 1 to S / 2) {\n val y = S - x + 1\n if (xSet(x) && !xSet(y)) res += y\n else if (!xSet(x) && xSet(y)) res += x\n else if (xSet(x) && xSet(y)) debt += 1\n }\n \n for (x <- 1 to S / 2) {\n val y = S - x + 1\n if (debt > 0 && !xSet(x) && !xSet(y)) {\n res += x\n\t res += y\n debt -= 1\n }\n }\n \n println(res.size)\n println(res.mkString(\" \"))\n}"}], "negative_code": [{"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject B extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val n = readInt\n val xs = readInts(n)\n var xSum = 0L\n for (x <- xs) xSum += x\n xSum -= n\n\n val xSet = mutable.BitSet.empty ++ xs\n\n val S = 1000000\n \n val res = mutable.ArrayBuffer[Int]()\n val used = mutable.BitSet.empty\n \n for (x <- 1 to S if ! used(x)) {\n val sy = S - x + 1\n if (!xSet(sy)) {\n res += sy\n xSet += sy\n } else {\n \n }\n }\n \n println(res.size)\n println(res.mkString(\" \"))\n}"}], "src_uid": "4143caa25fcc2f4d400d169f9697be01"} {"source_code": "\r\nobject Main {\r\n\r\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\r\n import java.util.StringTokenizer\r\n import scala.util.control.NonFatal\r\n\r\n def main(_argv: Array[String]): Unit = {\r\n val input = new BufferedReader(new InputStreamReader(System.in))\r\n val output = new PrintWriter(System.out)\r\n val solver = new T1512C(input, output)\r\n solver.solve()\r\n //println( solver.oneLine( \"0\", zeros = 0, ones = 1 ) )\r\n output.close()\r\n }\r\n\r\n\r\n class T1512C(input: BufferedReader, output: PrintWriter) {\r\n\r\n def solve(): Unit = {\r\n val num = input.readLine().toInt\r\n for (_ <- 0 until num) {\r\n val prms = new StringTokenizer(input.readLine())\r\n val zeros = prms.nextToken().toInt\r\n val ones = prms.nextToken().toInt\r\n val data = input.readLine()\r\n val result = try {\r\n oneLine(data, zeros, ones)\r\n }\r\n catch {\r\n case NonFatal(_) => \"-1\"\r\n }\r\n output.println(result)\r\n }\r\n }\r\n\r\n def oneLine(str: String, zeros: Int, ones: Int): String = {\r\n if (zeros + ones != str.length) {\r\n throw new Exception()\r\n }\r\n val buf = new Array[Char](str.length)\r\n var restZeros = zeros\r\n var restOnes = ones\r\n for (idx <- buf.indices) {\r\n val char = str(idx)\r\n val oppositIndex = buf.length - idx - 1\r\n val oppositChar = str(oppositIndex)\r\n if (idx < buf.length / 2) {\r\n char match {\r\n case '0' => oppositChar match {\r\n case '1' =>\r\n throw new Exception()\r\n case '0' | '?' =>\r\n buf(idx) = char\r\n buf(oppositIndex) = char\r\n restZeros -= 2\r\n }\r\n case '1' => oppositChar match {\r\n case '0' =>\r\n throw new Exception()\r\n case '1' | '?' =>\r\n buf(idx) = char\r\n buf(oppositIndex) = char\r\n restOnes -= 2\r\n }\r\n case '?' => ()\r\n }\r\n }\r\n else {\r\n char match {\r\n case '0' => oppositChar match {\r\n case '?' =>\r\n buf(idx) = char\r\n restZeros -= 1\r\n if (idx != oppositIndex) {\r\n buf(oppositIndex) = char\r\n restZeros -= 1\r\n }\r\n case '0' =>\r\n if (idx == oppositIndex) {\r\n buf(oppositIndex) = char\r\n restZeros -= 1\r\n }\r\n }\r\n case '1' => oppositChar match {\r\n case '?' =>\r\n buf(idx) = char\r\n restOnes -= 1\r\n if (idx != oppositIndex) {\r\n buf(oppositIndex) = char\r\n restOnes -= 1\r\n }\r\n case '1' =>\r\n if (idx == oppositIndex) {\r\n buf(oppositIndex) = char\r\n restOnes -= 1\r\n }\r\n }\r\n case '?' => ()\r\n }\r\n }\r\n }\r\n\r\n for (idx <- 0 to str.length / 2) {\r\n val char = buf(idx)\r\n if (char == '\\0') {\r\n val oppositIndex = buf.length - idx - 1\r\n if (idx != oppositIndex) {\r\n if (restZeros > 1) {\r\n buf(idx) = '0'\r\n buf(oppositIndex) = '0'\r\n restZeros -= 2\r\n }\r\n else if (restOnes > 1) {\r\n buf(idx) = '1'\r\n buf(oppositIndex) = '1'\r\n restOnes -= 2\r\n }\r\n else {\r\n throw new Exception()\r\n }\r\n }\r\n else {\r\n if (restZeros > 0 && restZeros % 2 == 1) {\r\n buf(idx) = '0'\r\n restZeros -= 1\r\n }\r\n else if (restOnes > 0 && restOnes % 2 == 1) {\r\n buf(idx) = '1'\r\n restOnes -= 1\r\n }\r\n else {\r\n throw new Exception()\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (restZeros == 0 && restOnes == 0) {\r\n buf.mkString(\"\")\r\n }\r\n else {\r\n throw new Exception()\r\n }\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.io.StdIn\r\n\r\nobject Main {\r\n def test(): String = {\r\n val in = StdIn.readLine().split(\" \")\r\n var (a, b) = (in(0).toInt, in(1).toInt)\r\n val s : String = StdIn.readLine()\r\n val kek : List[(Char, Int)] = s.toList.zipWithIndex\r\n val n : Int = s.size\r\n val f : (Char, Int) => Boolean = (e, i) => (s(n - i - 1) == '?' || e == '?' || s(n - i - 1) == e)\r\n if (a + b != n)\r\n return \"-1\"\r\n if (!kek.forall { (elem) => f(elem._1, elem._2) } )\r\n return \"-1\"\r\n val s2 : List[Char] = kek.map { elem => if (s(n - elem._2 - 1) != '?') s(n - elem._2 - 1) else elem._1 }\r\n a = a - (s2.count( _ == '0'))\r\n b = b - s2.count( _ == '1')\r\n if (a < 0 || b < 0 || (a % 2 == 1 && b % 2 == 1))\r\n return \"-1\"\r\n if (a % 2 == 1 && s2(n / 2) == '1')\r\n return \"-1\"\r\n if (b % 2 == 1 && s2(n / 2) == '0')\r\n return \"-1\"\r\n\r\n val a1 = a % 2\r\n val a2 = b % 2\r\n a = a / 2\r\n b = b / 2\r\n val res : StringBuilder = new StringBuilder()\r\n for ((elem, i) <- s2.zipWithIndex) {\r\n if ( elem == '?' && (a > 0 || i == n / 2 && a1 == 1)) {\r\n res.append('0')\r\n a -= 1\r\n }\r\n else {\r\n if ( elem == '?' && (b > 0 || i == n / 2 && a2 == 1)) {\r\n res.append('1')\r\n b -= 1\r\n }\r\n else {\r\n if (elem == '?')\r\n res.append(res(n - i - 1))\r\n else\r\n res.append(elem)\r\n }\r\n }\r\n }\r\n return res.toString()\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val t = StdIn.readLine().toInt\r\n (1 to t) foreach {\r\n _ => println(test())\r\n }\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object Main {\r\nimport java.io.{BufferedReader, InputStreamReader, PrintWriter}\r\nimport java.util.StringTokenizer\r\nimport scala.util.control.NonFatal\r\n\r\n def main(_argv: Array[String]): Unit = {\r\n val input = new BufferedReader(new InputStreamReader(System.in))\r\n val output = new PrintWriter(System.out)\r\n val solver = new T1512C(input, output)\r\n solver.solve()\r\n // println( solver.oneLine( \"?0??10??\", zeros = 4, ones = 4 ) )\r\n output.close()\r\n }\r\n\r\n class T1512C(input: BufferedReader, output: PrintWriter) {\r\n\r\n def solve(): Unit = {\r\n val num = input.readLine().toInt\r\n for (_ <- 0 until num) {\r\n val prms = new StringTokenizer(input.readLine())\r\n val zeros = prms.nextToken().toInt\r\n val ones = prms.nextToken().toInt\r\n val data = input.readLine()\r\n val result = try {\r\n oneLine(data, zeros, ones)\r\n }\r\n catch {\r\n case NonFatal(_) => \"-1\"\r\n }\r\n output.println(result)\r\n }\r\n }\r\n\r\n def oneLine(str: String, zeros: Int, ones: Int): String = {\r\n if (zeros + ones != str.length) {\r\n throw new Exception()\r\n }\r\n val buf = new Array[Char](str.length)\r\n var restZeros = zeros\r\n var restOnes = ones\r\n for (idx <- buf.indices) {\r\n val char = str(idx)\r\n val oppositIndex = buf.length - idx - 1\r\n val oppositChar = str(oppositIndex)\r\n if (idx < buf.length / 2) {\r\n char match {\r\n case '0' => oppositChar match {\r\n case '1' =>\r\n throw new Exception()\r\n case '0' | '?' =>\r\n buf(idx) = char\r\n buf(oppositIndex) = char\r\n restZeros -= 2\r\n }\r\n case '1' => oppositChar match {\r\n case '0' =>\r\n throw new Exception()\r\n case '1' | '?' =>\r\n buf(idx) = char\r\n buf(oppositIndex) = char\r\n restOnes -= 2\r\n }\r\n case '?' => ()\r\n }\r\n }\r\n else {\r\n char match {\r\n case '0' => oppositChar match {\r\n case '?' =>\r\n buf(idx) = char\r\n restZeros -= 1\r\n if (idx != oppositIndex) {\r\n buf(oppositIndex) = char\r\n restZeros -= 1\r\n }\r\n case '0' => ()\r\n }\r\n case '1' => oppositChar match {\r\n case '?' =>\r\n buf(idx) = char\r\n restOnes -= 1\r\n if (idx != oppositIndex) {\r\n buf(oppositIndex) = char\r\n restOnes -= 1\r\n }\r\n case '1' => ()\r\n }\r\n case '?' => ()\r\n }\r\n }\r\n }\r\n\r\n for (idx <- 0 to str.length / 2) {\r\n val char = buf(idx)\r\n if (char == '\\0') {\r\n val oppositIndex = buf.length - idx - 1\r\n if (idx != oppositIndex) {\r\n if (restZeros > 1) {\r\n buf(idx) = '0'\r\n buf(oppositIndex) = '0'\r\n restZeros -= 2\r\n }\r\n else if (restOnes > 1) {\r\n buf(idx) = '1'\r\n buf(oppositIndex) = '1'\r\n restOnes -= 2\r\n }\r\n else {\r\n throw new Exception()\r\n }\r\n }\r\n else {\r\n if (restZeros > 0 && restZeros % 2 == 1) {\r\n buf(idx) = '0'\r\n restZeros -= 1\r\n }\r\n else if (restOnes > 0 && restOnes % 2 == 1) {\r\n buf(idx) = '1'\r\n restOnes -= 1\r\n }\r\n else {\r\n throw new Exception()\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (restZeros == 0 && restOnes == 0) {\r\n buf.mkString(\"\")\r\n }\r\n else {\r\n throw new Exception()\r\n }\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn\r\n\r\nobject Main {\r\n def test(): String = {\r\n val in = StdIn.readLine().split(\" \")\r\n var (a, b) = (in(0).toInt, in(1).toInt)\r\n val s : String = StdIn.readLine()\r\n val kek : List[(Char, Int)] = s.toList.zipWithIndex\r\n val n : Int = s.size\r\n val f : (Char, Int) => Boolean = (e, i) => (s(n - i - 1) == '?' || e == '?' || s(n - i - 1) == e)\r\n if (a + b != n)\r\n return \"-1\"\r\n if (!kek.forall { (elem) => f(elem._1, elem._2) } )\r\n return \"-1\"\r\n val s2 : List[Char] = kek.map { elem => if (s(n - elem._2 - 1) != '?') s(n - elem._2 - 1) else elem._1 }\r\n a = a - (s2.count( _ == '0'))\r\n b = b - s2.count( _ == '1')\r\n if (a < 0 || b < 0 || (a % 2 == 1 && b % 2 == 1))\r\n return \"-1\"\r\n\r\n a = a / 2 + a % 2\r\n b = b / 2 + b % 2\r\n val res : StringBuilder = new StringBuilder()\r\n for ((elem, i) <- s2.zipWithIndex) {\r\n if (elem == '?' && a > 0) {\r\n res.append('0')\r\n a -= 1\r\n }\r\n else {\r\n if (elem == '?' && b > 0) {\r\n res.append('1')\r\n b -= 1\r\n }\r\n else {\r\n if (elem == '?')\r\n res.append(res(n - i - 1))\r\n else\r\n res.append(elem)\r\n }\r\n }\r\n }\r\n return res.toString()\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val t = StdIn.readLine().toInt\r\n (1 to t) foreach {\r\n _ => println(test())\r\n }\r\n }\r\n}\r\n"}], "src_uid": "001ac8bce4e44e9266a13eb27760906c"} {"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 28.09.14.\n */\nobject A extends App {\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n\n def sieve(n: Long): Array[Boolean] = {\n val primes = Array.fill(n.toInt + 1)(true)\n primes(0) = false\n primes(1) = false\n for(i <- 2L to n) {\n if(primes(i.toInt)) {\n if(i * i <= n) {\n for(j <- i * i to n by i) {\n primes(j.toInt) = false\n }\n }\n }\n }\n primes\n }\n\n val primes = sieve(1000000)\n //print(primes.toList)\n\n var found = false\n for (i <- 2 until n if !found) {\n if ((primes(i) == false) && (primes(n - i) == false)) {\n out.print(s\"$i ${n - i}\")\n found = true\n }\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}", "positive_code": [{"source_code": "\n\nobject DesignTutorial {\n\tdef main(args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in);\n\t\tval n = scanner.nextLong;\n\t\tif (n % 2 == 0) {\n\t\t\tprintln(n - 4+ \" \"+4)\n\t\t}\n\t\telse {\n\t\t\tprintln(n - 9+ \" \"+9)\n\t\t}\n\t}\n}"}, {"source_code": "object Main {\n def READ: Array[Int] = readLine() split (\" \") map (_.toInt);\n\n def main(args: Array[String]) {\n var Array(n) = READ;\n if (n%2 == 0) println(\"4 \" + (n-4));\n else println(\"9 \" + (n-9));\n }\n}\n"}, {"source_code": "\nimport scala.io.StdIn\n\n/**\n * Created by breezzo on 19.02.17.\n */\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n val primes = new Primes(n)\n\n for (i <- 4 to n) {\n if (!primes.isPrime(i)) {\n val y = n - i\n if (!primes.isPrime(y)) {\n println(i + \" \" + y)\n return\n }\n }\n }\n }\n\n class Primes(val n: Int) {\n val primes = Array.fill(n + 1)(true)\n primes(0) = false\n primes(1) = false\n\n for (i <- 2 to n if primes(i) && i.toLong * i <= n) {\n for (j <- i * i to n by i) {\n primes(j) = false\n }\n }\n\n def isPrime(v: Int): Boolean = {\n primes(v)\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-29.\n */\nobject A472 extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n var com1 = 4\n var com2 = n - com1\n\n def isComposite(com: Int): Boolean = {\n if (com < 4) {\n false\n } else if (com == 4) {\n true\n } else {\n var i = 2\n\n while (i < com) {\n if (com % i == 0) {\n return true\n }\n\n i += 1\n }\n\n false\n }\n }\n\n while (!(isComposite(com1) && isComposite(com2))) {\n com1 += 1\n com2 -= 1\n }\n\n println(com1 + \" \" + com2)\n}\n"}, {"source_code": "\nimport scala.io.StdIn.readInt\nimport Math.sqrt\n\nobject DesignTutorial {\n \n def isPrime(p : Int) : Boolean =\n p != 1 && (p == 2 || (2 to sqrt(p*1.0).toInt by 1).toList.forall { p % _ != 0 })\n \n def main(args: Array[String]) {\n val n = readInt\n Stream.from(4).find { x => !isPrime(x) && !isPrime(n-x) } match {\n case Some(x) => println(x + \" \" + (n-x))\n case _ => println(\"should not happen\") \n }\n }\n \n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Main2 extends App {\n val number = readInt()\n println(s\"${number - (number%2+8)} ${number%2+8}\")\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\nobject Main extends App {\n\n val n: Int = io.StdIn.readInt()\n\n def solve(n: Int): String = {\n @tailrec\n def tailRec(i: Int, j: Int): String = {\n if (!isPrime(i) && !isPrime(j)) s\"$i $j\"\n else tailRec(i - 1, j + 1)\n }\n\n tailRec(n / 2, n - n / 2)\n }\n\n def isPrime(n: Int): Boolean = {\n @tailrec\n def isPrimeHelper(x: Int, acc: Boolean): Boolean = {\n if (!acc) false\n else if (x <= 1) true\n else isPrimeHelper(x - 1, n % x != 0 && acc)\n }\n\n isPrimeHelper(n / 2, acc = true)\n }\n\n println(solve(n))\n}\n"}, {"source_code": "import java.io._\n\nobject Solution extends App {\n val n = readInt\n \n def isPrime(n:Int):Boolean = {\n def paux(n:Int, i:Int):Boolean = {\n (n % i != 0) && (i*i > n || paux(n, i+2))\n }\n \n if(n == 1) \n false\n else if(n % 2 == 0)\n false\n else\n paux(n, 3)\n }\n \n val ans = Stream.range(4, n/2+1).map(a => (a, n-a)).filter{ case(a, b) =>\n !isPrime(a) && !isPrime(b)\n }.head\n \n println(s\"${ans._1} ${ans._2}\")\n}"}, {"source_code": "import java.io._\n\nobject Solution extends App {\n val n = readInt\n \n def isPrime(n:Int):Boolean = {\n if(n == 1) \n false\n else if(n % 2 == 0)\n false\n else\n Stream.from(3, 2).takeWhile(i => i*i < n + 1).forall(i => n % i != 0)\n }\n \n val ans = Stream.range(4, n/2+1).map(a => (a, n-a)).filter{ case(a, b) =>\n !isPrime(a) && !isPrime(b)\n }.head\n \n println(s\"${ans._1} ${ans._2}\")\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Task472A {\n\tdef main(args: Array[String]) {\n\t\tval n = StdIn.readInt()\n\t\tfor (i <- 4 to n)\n\t\t\tif (!isPrime(i) && !isPrime(n-i)) {\n\t\t\t\tprintln(i + \" \" + (n - i))\n\t\t\t\treturn\n\t\t\t}\n\t}\n\n\tdef isPrime(n: Int): Boolean = {\n\t\tif (n % 2 == 0) return false\n\t\tvar i = 3\n\t\twhile (i*i <= n) if (n % i == 0) return false else i += 2\n\t\ttrue\n\t}\n}\n"}, {"source_code": "object TaskA {\n def main(args: Array[String]) {\n val n = readInt\n println {\n n match {\n case 12 => \"6 6\"\n case x if x % 2 == 0 => s\"4 ${x - 4}\"\n case x => s\"9 ${x - 9}\"\n }\n }\n }\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\nimport scala.util.Sorting._\nimport scala.math._\n\nobject HelloWorld {\n\n def main(args: Array[String]) {\n\n val n = readInt()\n\n println(\n if (n % 2 == 0) (\"4 \" + (n-4))\n else (\"9 \" + (n-9))\n )\n\n }\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\nimport scala.util.Sorting._\nimport scala.math._\n\nobject HelloWorld {\n\n def is_compound(value: Int) = {\n var end = false\n\n for(i <- 2 to sqrt(value).toInt if !end) {\n if (value % i == 0) end = true\n }\n\n end\n }\n\n def main(args: Array[String]) {\n\n val n = readInt()\n var end = false\n\n for(i <- 4 to (n / 2, 2) if !end) {\n val j = n - i\n\n if (is_compound(j)) {\n println(i + \" \" + j)\n end = true\n }\n }\n\n }\n}"}, {"source_code": "object A472 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def genPrimes(till: Int): Array[Int] = {\n val isPrime = Array.fill[Boolean](till+1)(true)\n isPrime(0) = false\n isPrime(1) = true // not composite\n for(i <- 4 to till by 2) {\n isPrime(i) = false\n }\n for(i <- 3 to till by 2 if isPrime(i)) {\n for(j <- i+i to till by i) isPrime(j) = false\n }\n isPrime.zipWithIndex.filter(_._1).map(_._2)\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val primes = genPrimes(n).toSet\n for(i <- 1 to n/2) {\n if(!primes.contains(i) && !primes.contains(n - i)) {\n println(s\"$i ${n-i}\")\n return\n }\n }\n }\n}"}, {"source_code": "import scala.math._\n\nobject Main extends App{\n val n = readInt \n val iList = List(4, 6, 8, 10, 12) \n var result = for(i <- iList; m = n - i) \n yield if(m % 2 == 0 || m % 3 == 0 || m % 5 == 0 || m % 7 == 0 || (m % 11 == 0 && m != 11))\n (m, i)\n var res = result.filter(x => x != ()).head.toString.replace(',',' ') drop 1 dropRight 1\n print(res)\n}"}, {"source_code": "import scala.collection._\n\nobject A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val LIMIT = n\n val prime = Array.fill(LIMIT)(true)\n prime(0) = false\n\n Stream.from(2).takeWhile(i => i * i < LIMIT).filter(prime(_)).foreach { i =>\n (i * i until LIMIT by i).foreach(prime(_) = false)\n }\n val primes = prime.indices.filter(prime(_)).toSet\n\n for (i <- 4 until n) {\n val j = n - i\n if (!primes(i) && !primes(j)) { \n println(s\"$i $j\")\n System.exit(0)\n }\n }\n}"}, {"source_code": "\n/**\n * \n *\n * @author pvasilyev\n * @since 08 Apr 2016\n */\nobject Problem147 extends App {\n\n val number = scala.io.StdIn.readInt()\n\n def isNotPrime(number: Int): Boolean = {\n val upperBound = Math.sqrt(number).toInt + 1\n val range = 2 to upperBound\n for (x <- range) {\n if (number % x == 0) {\n return true\n }\n }\n return false\n }\n\n def solve(number: Int): String = {\n for (x <- 4 to number / 2) {\n if (isNotPrime(x) && isNotPrime(number - x)) {\n return x.toString() + \" \" + (number - x).toString()\n }\n }\n \"\"\n }\n\n println(solve(number))\n\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject Task472A {\n\tdef main(args: Array[String]) {\n\t\tval n = StdIn.readInt()\n\t\tfor (i <- 2 to n)\n\t\t\tif (!isPrime(i) && !isPrime(n-i)) {\n\t\t\t\tprintln(i + \" \" + (n - i))\n\t\t\t\treturn\n\t\t\t}\n\t}\n\n\tdef isPrime(n: Int): Boolean = {\n\t\tif (n % 2 == 0) return false\n\t\tvar i = 3\n\t\twhile (i*i <= n) if (n % i == 0) return false else i += 2\n\t\ttrue\n\t}\n}\n"}, {"source_code": "import scala.math._\n\nobject Main extends App{\n val n = readInt \n val iList = List(4, 6, 8, 10, 12) \n var result = for(i <- iList; m = n - i) \n yield if(m % 2 == 0 || m % 3 == 0 || m % 5 == 0 || m % 7 == 0 || m % 11 == 0)\n (m, i)\n var res = result.filter(x => x != ()).head.toString.replace(',',' ') drop 1 dropRight 1\n print(res)\n}"}, {"source_code": "\n/**\n * \n *\n * @author pvasilyev\n * @since 08 Apr 2016\n */\nobject Problem147 extends App {\n\n val number = scala.io.StdIn.readInt()\n\n def isNotPrime(number: Int): Boolean = {\n val upperBound = Math.sqrt(number).toInt + 1\n val range = 2 to upperBound\n for (x <- range) {\n if (number % x == 0) {\n return true\n }\n }\n return false\n }\n\n def solve(number: Int): String = {\n for (x <- 4 until number / 2) {\n if (isNotPrime(x) && isNotPrime(number - x)) {\n return x.toString() + \" \" + (number - x).toString()\n }\n }\n \"\"\n }\n\n println(solve(number))\n\n}\n"}, {"source_code": "import java.io._\n\nobject Solution extends App {\n val n = readInt\n \n def isPrime(n:Int):Boolean = {\n def paux(n:Int, i:Int):Boolean = {\n (n % i == 0) && (i*i > n || paux(n, i+2))\n }\n \n if(n == 1) \n false\n else if(n % 2 == 0)\n false\n else\n paux(n, 3)\n }\n \n val ans = Stream.range(4, n/2+1).map(a => (a, n-a)).filter{ case(a, b) =>\n !isPrime(a) && !isPrime(b)\n }.head\n \n println(s\"${ans._1} ${ans._2}\")\n}"}], "src_uid": "3ea971165088fae130d866180c6c868b"} {"source_code": "\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject B {\n\n var out: PrintWriter = _\n var br: BufferedReader = _\n var st: StringTokenizer = _\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = Integer.parseInt(next)\n\n def nextBoolean: Boolean = next.equalsIgnoreCase(\"1\")\n\n def nextLong: Long = java.lang.Long.parseLong(next)\n\n def nextDouble: Double = java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n true\n }\n\n override def toString = s\"MultiHashSet($map)\"\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n map.getOrDefault(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = map.firstKey()\n\n def last(): T = map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n true\n }\n }\n\n /**\n * Segment tree for any commutative function\n *\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Unit = {\n val t = nextInt\n for (_ <- 0 until t) {\n val n = nextInt\n val apples = new Array[Int](n)\n val bananas = new Array[Int](n)\n for (i <- 0 until n) {\n apples(i) = nextInt\n }\n val min_app = apples.sorted.apply(0)\n for (i <- 0 until n) {\n bananas(i) = nextInt\n }\n val min_ban = bananas.sorted.apply(0)\n var moves = 0L\n for (i <- 0 until n) {\n val diff1 = apples(i) - min_app\n val diff2 = bananas(i) - min_ban\n moves += Math.min(diff1, diff2)\n moves += Math.max(diff1, diff2) - Math.min(diff1, diff2)\n\n }\n out.println(moves)\n\n }\n }\n}\n", "positive_code": [{"source_code": "object _1399B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val n = io.read[Int]\n val candies, oranges = io.read[Vector, Long](n)\n\n val minCandy = candies.min\n val minOrange = oranges.min\n\n val ans = candies.zip(oranges) map {\n case (c, o) =>\n val candiesToEat = c - minCandy\n val orangesToEat = o - minOrange\n (candiesToEat min orangesToEat) + (candiesToEat - orangesToEat).abs\n }\n\n io.write(ans.sum)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n val charToInt: Char => Int = Character.getNumericValue\n val intToChar: Int => Char = Character.forDigit(_, 10)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}, {"source_code": "//package codeforces.contests._1399\n\nobject GiftsFixing {\n def main(args: Array[String]): Unit = {\n for (t <- 1 to io.StdIn.readInt) {\n val n = io.StdIn.readInt()\n val a, b = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val minA = a.min\n val minB = b.min\n\n val answer = (0 until n).foldLeft(0L)((acc, i) => acc + {\n\n val decA = a(i) - minA\n val decB = b(i) - minB\n\n decA max decB\n })\n\n println(answer)\n }\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject GiftsFixing1399B extends App {\n\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n// val lines: Iterator[String] =\n// Source.fromString(\"5\\n3\\n3 5 6\\n3 2 3\\n5\\n1 2 3 4 5\\n5 4 3 2 1\\n3\\n1 1 1\\n2 2 2\\n6\\n1 1000000000 1000000000 1000000000 1000000000 1000000000\\n1 1 1 1 1 1\\n3\\n10 12 8\\n7 5 4\").getLines\n val ntc: Int = lines.next.toInt\n 0 until ntc map { _ =>\n handleTC()\n } foreach println\n\n def handleTC() = {\n if (lines.next.toInt == 1) {\n lines.next; lines.next;\n 0L\n } else {\n val as = lines.next.split(\" \").map(_.toLong)\n val bs = lines.next.split(\" \").map(_.toLong)\n solve(as, bs)\n }\n }\n\n def solve(as: Array[Long], bs: Array[Long]) = {\n val am = as.min\n val bm = bs.min\n as.zip(bs).map { case (a, b) =>\n Math.max(a-am,b-bm)\n }.sum\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 1 to t) {\n val _ = StdIn.readLine().trim.toInt\n val xs = StdIn.readLine().split(\" \").map(_.toLong)\n val ys = StdIn.readLine().split(\" \").map(_.toLong)\n val x = xs.min\n val y = ys.min\n val res = xs.map(_ - x) zip ys.map(_ - y) map {\n case (i, j) => i max j\n }\n println(res.sum)\n }\n }\n}\n"}], "negative_code": [], "src_uid": "35368cefc5ce46a9f41a15734826a151"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val line = in.next().split(' ').map(_.toInt)\n val vov = Array[Char]('a', 'e', 'i', 'o', 'u', 'y')\n val lines = in.take(n).map(_.count(vov.contains)).toArray\n if (lines sameElements line)\n println(\"YES\")\n else\n println(\"NO\")\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\nimport scala.math.pow\nimport scala.collection.mutable._\n\nobject Main {\n implicit def bool2int(b: Boolean): Int = { if(b) 1 else 0 }\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val patterns = readLine.split(' ').map(_.toInt)\n\n var ok = true\n\n patterns.foreach { pattern =>\n val verse = readLine\n val vowels = verse.replaceAll(\"[^aeiouy]\", \"\").length()\n\n if (ok && pattern != vowels) { ok = false }\n }\n\n println(\n if (ok) \"YES\" else \"NO\"\n )\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.immutable._\nimport scala.collection.mutable\n\nobject test extends App {\n\tval vowels = List('a', 'e', 'i', 'o', 'u', 'y')\n\tval sc = new Scanner(System.in)\n\tval n = sc.nextInt()\n\tval numbers = List.range(0, n).map(x => sc.nextInt())\n\tsc.nextLine()\n\tval textLine = List.range(0, n).map(x => sc.nextLine())\n\tval counts = for (i <- 0 until textLine.length)\n\t\tyield textLine(i).count(vowels.contains(_))\n\tprintln(\n\t\tif (counts == numbers)\n\t\t\t\"YES\"\n\t\telse\n\t\t\t\"NO\"\n\t)\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.immutable._\nimport scala.collection.mutable\n\n/**\n * Created by Andrew on 11-Jul-16.\n */\n\n\nobject Main extends App {\n\n val vowels = List('a', 'e', 'i', 'o', 'u', 'y')\n\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val xs = List.range(0, n).map { _ => sc.nextInt() }\n sc.nextLine()\n val ys = List.range(0, n).map { _ => sc.nextLine() }\n val counts = for (i <- List.range(0, ys.length)) yield ys(i).count(vowels.contains(_))\n println(\n if(counts == xs) \"YES\" else \"NO\"\n )\n}"}, {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val vowel = Set('a', 'e', 'i', 'o', 'u', 'y')\n val Array(n) = readInts(1)\n val ps = readInts(n)\n val ss = Array.fill(n){ readLine }\n\n val ok = (0 until n).forall(i => ss(i).count(vowel) == ps(i))\n\n println(if (ok) \"YES\" else \"NO\")\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _722B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val patterns = read[Vector[Int]]\n val input = patterns.zipWith(i => io.readTillEndOfLine())\n val vowels = \"aeiouy\".toSet\n\n val ans = input forall {case (pattern, line) =>\n line.count(vowels) == pattern\n }\n\n write(ans.toEnglish)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "cf595689b5cbda4f1d629524ad275650"} {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.PriorityQueue\nimport java.util.StringTokenizer\n\nobject WeightsDivision1399E1 {\n\n def main(args: Array[String]): Unit = {\n val file = new BufferedReader(new InputStreamReader(System.in))\n val inputs = file.readLine.toInt\n\n var i = 0\n while (i < inputs) {\n handleTC()\n i+=1\n }\n\n def handleTC(): Unit = {\n var st = new StringTokenizer(file.readLine)\n val v = st.nextToken.toInt\n val s = st.nextToken.toLong\n val g: Array[java.util.ArrayList[Array[Int]]] = Array.ofDim[java.util.ArrayList[Array[Int]]](v+1)\n var inb = 0\n while (inb <= v) {\n g(inb) = new java.util.ArrayList()\n inb+=1\n }\n var ing = 1\n while (ing < v) {\n st = new StringTokenizer(file.readLine)\n val v = st.nextToken.toInt\n val u = st.nextToken.toInt\n val w = st.nextToken.toInt\n g(v).add(Array(u,w))\n g(u).add(Array(v,w))\n ing+=1\n }\n val tWs = new PriorityQueue[Array[Long]]((x: Array[Long], y: Array[Long]) => {\n def foo(x: Array[Long], y: Array[Long]) = if ((x(0) + 1) / 2 * x(1) < (y(0) + 1) / 2 * y(1)) 1\n else -1\n\n foo(x, y)\n })\n var cur = 0L\n // DFS\n def traverse(par: Int, p: Int = 0): Int = {\n val adjL = g(par)\n if (p != 0 && adjL.size == 1) return 1\n import scala.collection.JavaConversions._\n var sum = 0\n for (a <- adjL if a(0) != p) {\n val efs = traverse(a(0), par)\n tWs add Array(a(1), efs)\n cur += a(1) *1L* efs\n sum += efs\n }\n sum\n }\n traverse(1)\n var ans = 0\n while (cur > s) {\n val a = tWs.remove()\n cur -= (a(0) + 1) / 2 * a(1)\n tWs add Array(a(0) / 2, a(1))\n ans += 1\n }\n println(ans)\n }\n }\n}\n", "positive_code": [{"source_code": "import java.util.PriorityQueue\nimport java.util.StringTokenizer\n\nimport scala.io.Source\n\nobject WeightsDivision1399E1 {\n\n def main(args: Array[String]): Unit = {\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n\n val inputs = lines.next.toInt\n var i = 0\n while (i < inputs) {\n handleTC()\n i+=1\n }\n\n def handleTC(): Unit = {\n val vAndS = lines.next.split(\" \")\n val v = vAndS(0).toInt\n val s = vAndS(1).toLong\n val g: Array[java.util.ArrayList[Array[Int]]] = Array.ofDim[java.util.ArrayList[Array[Int]]](v+1)\n var inb = 0\n while (inb <= v) {\n g(inb) = new java.util.ArrayList()\n inb+=1\n }\n var ing = 1\n while (ing < v) {\n val s = lines.next.split(\" \")\n val v = s(0).toInt\n val u = s(1).toInt\n val w = s(2).toInt\n g(v).add(Array(u,w))\n g(u).add(Array(v,w))\n ing+=1\n }\n val tWs = new PriorityQueue[Array[Long]]((x: Array[Long], y: Array[Long]) => {\n def foo(x: Array[Long], y: Array[Long]) = if ((x(0) + 1) / 2 * x(1) < (y(0) + 1) / 2 * y(1)) 1\n else -1\n\n foo(x, y)\n })\n var cur = 0L\n // DFS\n def traverse(par: Int, p: Int = 0): Int = {\n val adjL = g(par)\n if (p != 0 && adjL.size == 1) return 1\n import scala.collection.JavaConversions._\n var sum = 0\n for (a <- adjL if a(0) != p) {\n val efs = traverse(a(0), par)\n tWs add Array(a(1), efs)\n cur += a(1) *1L* efs\n sum += efs\n }\n sum\n }\n traverse(1)\n var ans = 0\n while (cur > s) {\n val a = tWs.remove()\n cur -= (a(0) + 1) / 2 * a(1)\n tWs add Array(a(0) / 2, a(1))\n ans += 1\n }\n println(ans)\n }\n }\n}\n"}, {"source_code": "object E {\n\n import java.io.BufferedReader\n import java.io.IOException\n import java.io.InputStreamReader\n import java.util\n import java.util.PriorityQueue\n import java.util.StringTokenizer\n\n var currSum = 0L\n\n @SuppressWarnings(Array(\"unchecked\"))\n @throws[IOException]\n def main(args: Array[String]): Unit = {\n val file = new BufferedReader(new InputStreamReader(System.in))\n var inputs = file.readLine.toInt\n while ( {\n {\n inputs -= 1; inputs + 1\n } > 0\n }) {\n var st = new StringTokenizer(file.readLine)\n val n = st.nextToken.toInt\n val s = st.nextToken.toLong\n val con = new Array[util.ArrayList[Array[Int]]](n)\n for (i <- 0 until n) {\n con(i) = new util.ArrayList[Array[Int]]\n }\n for (i <- 0 until n - 1) {\n st = new StringTokenizer(file.readLine)\n val a = st.nextToken.toInt - 1\n val b = st.nextToken.toInt - 1\n val weight = st.nextToken.toInt\n con(a).add(Array[Int](b, weight))\n con(b).add(Array[Int](a, weight))\n }\n val edges = new PriorityQueue[Array[Long]]((x: Array[Long], y: Array[Long]) => {\n def foo(x: Array[Long], y: Array[Long]) = if ((x(0) + 1) / 2 * x(1) < (y(0) + 1) / 2 * y(1)) 1\n else -1\n\n foo(x, y)\n })\n currSum = 0\n dfs(0, new Array[Boolean](n), con, edges)\n var moves = 0\n while ( {\n currSum > s\n }) {\n moves += 1\n val curr = edges.remove()\n currSum -= (curr(0) + 1) / 2 * curr(1)\n curr(0) /= 2\n edges.add(curr)\n }\n System.out.println(moves)\n }\n }\n\n def dfs(curr: Int, visited: Array[Boolean], con: Array[util.ArrayList[Array[Int]]], edges: PriorityQueue[Array[Long]]): Int = {\n visited(curr) = true\n var numVisited = 0\n var size = 0\n import scala.collection.JavaConversions._\n for (i <- con(curr)) {\n if (!visited(i(0))) {\n numVisited += 1\n val s = dfs(i(0), visited, con, edges)\n currSum += i(1).toLong * s\n edges.add(Array[Long](i(1), s))\n size += s\n }\n }\n if (numVisited == 0) return 1\n size\n }\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.PriorityQueue\nimport java.util.StringTokenizer\n\nobject WeightsDivision1399E1 {\n\n def main(args: Array[String]): Unit = {\n val file = new BufferedReader(new InputStreamReader(System.in))\n val inputs = file.readLine.toInt\n\n var i = 0\n while (i < inputs) {\n handleTC()\n i += 1\n }\n\n def handleTC(): Unit = {\n var st = new StringTokenizer(file.readLine)\n val v = st.nextToken.toInt\n val s = st.nextToken.toLong\n val g: Array[java.util.ArrayList[Array[Int]]] = Array.ofDim[java.util.ArrayList[Array[Int]]](v + 1)\n var inb = 0\n while (inb <= v) {\n g(inb) = new java.util.ArrayList()\n inb += 1\n }\n var ing = 1\n while (ing < v) {\n st = new StringTokenizer(file.readLine)\n val v = st.nextToken.toInt\n val u = st.nextToken.toInt\n val w = st.nextToken.toInt\n g(v).add(Array(u, w))\n g(u).add(Array(v, w))\n ing += 1\n }\n val tWs = new PriorityQueue[Array[Long]]((x: Array[Long], y: Array[Long]) => {\n def foo(x: Array[Long], y: Array[Long]) = if ((x(0) + 1) / 2 * x(1) < (y(0) + 1) / 2 * y(1)) 1\n else -1\n\n foo(x, y)\n })\n var cur = 0L\n\n // DFS\n def traverse(par: Int, p: Int = 0): Int = {\n val adjL = g(par)\n if (p != 0 && adjL.size == 1) return 1\n import scala.collection.JavaConversions._\n var sum = 0\n for (a <- adjL if a(0) != p) {\n val efs = traverse(a(0), par)\n tWs add Array(a(1), efs)\n cur += a(1) * 1L * efs\n sum += efs\n }\n sum\n }\n\n traverse(1)\n var ans = 0\n while (cur > s) {\n val a = tWs.remove()\n cur -= (a(0) + 1) / 2 * a(1)\n a(0) /= 2\n tWs add a\n ans += 1\n }\n println(ans)\n }\n }\n}\n"}, {"source_code": "object E {\n\n import java.io.BufferedReader\n import java.io.IOException\n import java.io.InputStreamReader\n import java.util\n import java.util.PriorityQueue\n import java.util.StringTokenizer\n\n var currSum = 0L\n \n @throws[IOException]\n def main(args: Array[String]): Unit = {\n val file = new BufferedReader(new InputStreamReader(System.in))\n var inputs = file.readLine.toInt\n while ( {\n {\n inputs -= 1; inputs + 1\n } > 0\n }) {\n var st = new StringTokenizer(file.readLine)\n val n = st.nextToken.toInt\n val s = st.nextToken.toLong\n val con = new Array[util.ArrayList[Array[Int]]](n)\n for (i <- 0 until n) {\n con(i) = new util.ArrayList[Array[Int]]\n }\n for (i <- 0 until n - 1) {\n st = new StringTokenizer(file.readLine)\n val a = st.nextToken.toInt - 1\n val b = st.nextToken.toInt - 1\n val weight = st.nextToken.toInt\n con(a).add(Array[Int](b, weight))\n con(b).add(Array[Int](a, weight))\n }\n val edges = new PriorityQueue[Array[Long]]((x: Array[Long], y: Array[Long]) => {\n def foo(x: Array[Long], y: Array[Long]) = if ((x(0) + 1) / 2 * x(1) < (y(0) + 1) / 2 * y(1)) 1\n else -1\n\n foo(x, y)\n })\n currSum = 0\n dfs(0, new Array[Boolean](n), con, edges)\n var moves = 0\n while ( {\n currSum > s\n }) {\n moves += 1\n val curr = edges.remove()\n currSum -= (curr(0) + 1) / 2 * curr(1)\n curr(0) /= 2\n edges.add(curr)\n }\n System.out.println(moves)\n }\n }\n\n def dfs(curr: Int, visited: Array[Boolean], con: Array[util.ArrayList[Array[Int]]], edges: PriorityQueue[Array[Long]]): Int = {\n visited(curr) = true\n var numVisited = 0\n var size = 0\n import scala.collection.JavaConversions._\n for (i <- con(curr)) {\n if (!visited(i(0))) {\n numVisited += 1\n val s = dfs(i(0), visited, con, edges)\n currSum += i(1).toLong * s\n edges.add(Array[Long](i(1), s))\n size += s\n }\n }\n if (numVisited == 0) return 1\n size\n }\n}\n"}, {"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.PriorityQueue\nimport java.util.StringTokenizer\n\nobject WeightsDivision1399E1 {\n\n def main(args: Array[String]): Unit = {\n val file = new BufferedReader(new InputStreamReader(System.in))\n val inputs = file.readLine.toInt\n var i = 0\n while (i < inputs) {\n handleTC()\n i+=1\n }\n\n def handleTC(): Unit = {\n var st = new StringTokenizer(file.readLine)\n val v = st.nextToken.toInt\n val s = st.nextToken.toLong\n val g: Array[java.util.ArrayList[Array[Int]]] = Array.ofDim[java.util.ArrayList[Array[Int]]](v+1)\n var inb = 0\n while (inb <= v) {\n g(inb) = new java.util.ArrayList()\n inb+=1\n }\n var ing = 1\n while (ing < v) {\n st = new StringTokenizer(file.readLine)\n val v = st.nextToken.toInt\n val u = st.nextToken.toInt\n val w = st.nextToken.toInt\n g(v).add(Array(u,w))\n g(u).add(Array(v,w))\n ing+=1\n }\n val tWs = new PriorityQueue[Array[Long]]((x: Array[Long], y: Array[Long]) => {\n def foo(x: Array[Long], y: Array[Long]) = if ((x(0) + 1) / 2 * x(1) < (y(0) + 1) / 2 * y(1)) 1\n else -1\n\n foo(x, y)\n })\n var cur = 0L\n // DFS\n def traverse(par: Int, p: Int = 0): Int = {\n val adjL = g(par)\n if (p != 0 && adjL.size == 1) return 1\n import scala.collection.JavaConversions._\n var sum = 0\n for (a <- adjL if a(0) != p) {\n val efs = traverse(a(0), par)\n tWs add Array(a(1), efs)\n cur += a(1) *1L* efs\n sum += efs\n }\n sum\n }\n traverse(1)\n var ans = 0\n while (cur > s) {\n val a = tWs.remove()\n cur -= (a(0) + 1) / 2 * a(1)\n tWs add Array(a(0) / 2, a(1))\n ans += 1\n }\n println(ans)\n }\n }\n}\n"}, {"source_code": "object E {\n\n import java.io.BufferedReader\n import java.io.IOException\n import java.io.InputStreamReader\n import java.util\n import java.util.PriorityQueue\n import java.util.StringTokenizer\n\n var currSum = 0L\n\n @SuppressWarnings(Array(\"unchecked\"))\n @throws[IOException]\n def main(args: Array[String]): Unit = {\n val file = new BufferedReader(new InputStreamReader(System.in))\n var inputs = file.readLine.toInt\n while ( {\n {\n inputs -= 1; inputs + 1\n } > 0\n }) {\n var st = new StringTokenizer(file.readLine)\n val n = st.nextToken.toInt\n val s = st.nextToken.toLong\n val con = new Array[util.ArrayList[Array[Int]]](n)\n for (i <- 0 until n) {\n con(i) = new util.ArrayList[Array[Int]]\n }\n for (i <- 0 until n - 1) {\n st = new StringTokenizer(file.readLine)\n val a = st.nextToken.toInt - 1\n val b = st.nextToken.toInt - 1\n val weight = st.nextToken.toInt\n con(a).add(Array[Int](b, weight))\n con(b).add(Array[Int](a, weight))\n }\n val edges = new PriorityQueue[Array[Long]]((x: Array[Long], y: Array[Long]) => {\n def foo(x: Array[Long], y: Array[Long]) = if ((x(0) + 1) / 2 * x(1) < (y(0) + 1) / 2 * y(1)) 1\n else -1\n\n foo(x, y)\n })\n currSum = 0\n dfs(0, new Array[Boolean](n), con, edges)\n var moves = 0\n while ( {\n currSum > s\n }) {\n moves += 1\n val curr = edges.remove()\n currSum -= (curr(0) + 1) / 2 * curr(1)\n curr(0) /= 2\n edges.add(curr)\n }\n System.out.println(moves)\n }\n }\n\n def dfs(curr: Int, visited: Array[Boolean], con: Array[util.ArrayList[Array[Int]]], edges: PriorityQueue[Array[Long]]): Int = {\n visited(curr) = true\n var numVisited = 0\n var size = 0\n import scala.collection.JavaConversions._\n for (i <- con(curr)) {\n if (!visited(i(0))) {\n numVisited += 1\n val s = dfs(i(0), visited, con, edges)\n currSum += i(1).toLong * s\n edges.add(Array[Long](i(1), s))\n size += s\n }\n }\n if (numVisited == 0) return 1\n size\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1399\n\n\nobject WeightsDivisionEasy {\n\n import scala.collection.mutable\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(n, s) = io.StdIn.readLine.split(\" \").map(_.toInt)\n val graph = Array.fill[List[(Int, Int)]](n + 1)(Nil)\n (1 until n).foreach { _ =>\n val Array(u, v, w) = io.StdIn.readLine.split(\" \").map(_.toInt)\n graph(u) ::= (v, w)\n graph(v) ::= (u, w)\n }\n\n val leaves = new Array[Int](n + 1)\n\n val queue = mutable.PriorityQueue.empty[(Int, Int)](Ordering.by { case (w, c) => w * c - (w / 2) * c })\n\n var sum = 0\n\n def dfs(u: Int, p: Int): Unit = {\n if (graph(u).tail.isEmpty && graph(u).head._1 == p) leaves(u) = 1\n else\n graph(u).foreach { case (v, w) =>\n if (v != p) {\n dfs(v, u)\n leaves(u) += leaves(v)\n sum += w * leaves(v)\n queue.enqueue((w, leaves(v)))\n }\n }\n\n\n }\n\n dfs(1, 0)\n\n @scala.annotation.tailrec\n def reduce(sum: Int, steps: Int = 0): Int = {\n if (sum <= s) steps else {\n val (w, c) = queue.dequeue()\n queue.enqueue((w / 2, c))\n reduce(sum - w * c + (w / 2) * c, steps + 1)\n }\n }\n\n println(reduce(sum))\n }\n }\n}\n"}, {"source_code": "//package codeforces.contests._1399\n\n\nobject WeightsDivisionEasy {\n\n import scala.collection.mutable\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(n, s) = io.StdIn.readLine.split(\" \").map(_.toInt)\n val graph = Array.fill[List[(Int, Int)]](n + 1)(Nil)\n (1 until n).foreach { _ =>\n val Array(u, v, w) = io.StdIn.readLine.split(\" \").map(_.toInt)\n graph(u) ::= (v, w)\n graph(v) ::= (u, w)\n }\n\n val leaves = new Array[Int](n + 1)\n\n val queue = mutable.PriorityQueue.empty[(Int, Int)](Ordering.by(x => x._1 * x._2))\n\n var sum = 0\n\n def dfs(u: Int, p: Int): Unit = {\n graph(u).foreach { case (v, w) =>\n if (v != p) {\n dfs(v, u)\n leaves(u) += leaves(v)\n sum += w * leaves(v)\n queue.enqueue((w, leaves(v)))\n }\n }\n\n if (leaves(u) == 0) leaves(u) = 1\n }\n\n dfs(1, 0)\n\n @scala.annotation.tailrec\n def reduce(sum: Int, steps: Int = 0): Int = {\n if (sum <= s) steps else {\n val (w, c) = queue.dequeue()\n queue.enqueue((w / 2, c))\n reduce(sum - w * c + (w / 2) * c, steps + 1)\n }\n }\n\n println(reduce(sum))\n }\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.Source\n\nobject WeightsDivision1399E1 extends App {\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n// val lines: Iterator[String] =\n// Source.fromString(\"1\\n10 28\\n8 2 8\\n5 1 4\\n6 1 10\\n10 2 7\\n7 2 1\\n9 2 1\\n2 1 5\\n4 1 9\\n3 2 5\").getLines\n val ntc: Int = lines.next.toInt\n 0 until ntc map { _ =>\n handleTC()\n } foreach { println }\n\n case class Edge(uv: (Int, Int), w: Long)\n\n private def handleTC() = {\n val vAndS = lines.next.split(\" \")\n val v = vAndS(0).toInt\n val S = vAndS(1).toLong\n val g: Array[mutable.Set[Edge]] = Array.ofDim[mutable.Set[Edge]](v+1)\n def updEdgeSet(e: Edge, f: Edge => Int): Unit = {\n val es = Option(g(f(e))).getOrElse(mutable.Set())\n es.+=(e)\n g(f(e)) = es\n }\n for (_ <- 1 until v) {\n val s = lines.next.split(\" \")\n val e = Edge((s(0).toInt, s(1).toInt), s(2).toInt)\n updEdgeSet(e, _.uv._1)\n updEdgeSet(e, _.uv._2)\n }\n val eCounts = mutable.Map[Edge, Long]()\n val tWs = mutable.PriorityQueue[(Long, Long)]()(Ordering\n .by[(Long, Long), Long](x => Math.ceil(x._1 / 2.0).asInstanceOf[Int] * x._2))\n var r = 0L\n def traverse(par: Int): Unit = {\n val adjL = g(par)\n for (e <- adjL) {\n val nonPar = if (e.uv._1 == par) e.uv._2 else e.uv._1\n val nextAdjL = g(nonPar)\n nextAdjL.remove(e)\n traverse(nonPar)\n val ec = nextAdjL.map(eCounts).sum\n val ecf = if (ec == 0) 1 else ec\n eCounts(e) = ecf\n tWs += ((e.w, ecf))\n r = r + e.w * ecf\n }\n }\n traverse(1)\n if (r <= S) {\n 0\n } else {\n var st = 0\n do {\n val (w, c) = tWs.dequeue\n st = st + 1\n val ceil = Math.ceil(w / 2.0).asInstanceOf[Long]\n r = r - ceil * c\n tWs += ((Math.floor(w / 2.0).asInstanceOf[Long], c))\n } while (tWs.nonEmpty && r > S)\n st\n }\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject WeightsDivision1399E1 {\n\n def main(args: Array[String]): Unit = {\n// val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n val lines: Iterator[String] =\n Source.fromString(\"1\\n10 28\\n8 2 8\\n5 1 4\\n6 1 10\\n10 2 7\\n7 2 1\\n9 2 1\\n2 1 5\\n4 1 9\\n3 2 5\").getLines\n\n // 1\n // / / \\ \\\n // 5 6 4 2\n // / / \\ \\ \\\n // 10 8 7 9 3\n val ntc: Int = lines.next.toInt\n var i = 0\n while (i < ntc) {\n println(handleTC())\n i+=1\n }\n\n def handleTC(): Int = {\n val vAndS = lines.next.split(\" \")\n val v = vAndS(0).toInt\n val S = vAndS(1).toLong\n val g: Array[java.util.ArrayList[(Int, Int)]] = Array.ofDim[java.util.ArrayList[(Int, Int)]](v+1)\n var inb = 0\n while (inb <= v) {\n g(inb) = new java.util.ArrayList()\n inb+=1\n }\n val efs = Array.ofDim[Int](v)\n val ws = Array.ofDim[Int](v)\n var ing = 1\n while (ing < v) {\n val s = lines.next.split(\" \")\n val v = s(0).toInt\n val u = s(1).toInt\n val w = s(2).toInt\n g(v).add((u,ing))\n g(u).add((v,ing))\n ws(ing) = w\n ing+=1\n }\n val tWs: java.util.PriorityQueue[(Long, Int)] = new java.util.PriorityQueue[(Long, Int)]((x: (Long, Int), y: (Long, Int)) => {\n def foo(x: (Long, Int), y: (Long, Int)) = if (x._1 < y._1) 1 else -1\n foo(x, y)\n })\n def getDiff(e: Int): Long = (ws(e) - ws(e) / 2) * efs(e)\n var r = 0L\n // DFS\n def traverse(par: Int, grand: Int): Int = {\n val adjL = g(par)\n if (grand != 0 && adjL.size == 1) return 1\n import scala.collection.JavaConverters._\n (for ((v,id) <- adjL.asScala if id != grand) yield {\n efs(id) = traverse(v, id)\n tWs add ((getDiff(id), id))\n r = r + ws(id) * efs(id)\n efs(id)\n }).sum\n }\n traverse(1,0)\n var st = 0\n while (r > S) {\n val (k, e) = tWs.remove()\n st += 1\n ws(e) = ws(e) / 2\n r = r - k\n tWs add ((getDiff(e), e))\n }\n st\n }\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject WeightsDivision1399E1 {\n\n def main(args: Array[String]): Unit = {\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n // val lines: Iterator[String] =\n // Source.fromString(\"1\\n10 28\\n8 2 8\\n5 1 4\\n6 1 10\\n10 2 7\\n7 2 1\\n9 2 1\\n2 1 5\\n4 1 9\\n3 2 5\").getLines\n\n // 1\n // / / \\ \\\n // 5 6 4 2\n // / / \\ \\ \\\n // 10 8 7 9 3\n val ntc: Int = lines.next.toInt\n var i = 0\n while (i < ntc) {\n println(handleTC())\n i+=1\n }\n\n def handleTC(): Int = {\n val vAndS = lines.next.split(\" \")\n val v = vAndS(0).toInt\n val s = vAndS(1).toLong\n val g: Array[java.util.ArrayList[(Int, Int)]] = Array.ofDim[java.util.ArrayList[(Int, Int)]](v+1)\n var inb = 0\n while (inb <= v) {\n g(inb) = new java.util.ArrayList()\n inb+=1\n }\n val efs = Array.ofDim[Int](v)\n val ws = Array.ofDim[Int](v)\n var ing = 1\n while (ing < v) {\n val s = lines.next.split(\" \")\n val v = s(0).toInt\n val u = s(1).toInt\n val w = s(2).toInt\n g(v).add((u,ing))\n g(u).add((v,ing))\n ws(ing) = w\n ing+=1\n }\n val tWs: java.util.PriorityQueue[(Long, Int)] = new java.util.PriorityQueue[(Long, Int)]((x: (Long, Int), y: (Long, Int)) => {\n def foo(x: (Long, Int), y: (Long, Int)) = if (x._1 < y._1) 1 else if (x._1 == y._1 && x._2 < y._2) 1\n else -1\n foo(x, y)\n })\n def getDiff(e: Int): Long = (ws(e)*1L - ws(e) / 2) * efs(e)\n var cur = 0L\n // DFS\n def traverse(par: Int, p: Int = 0): Int = {\n val adjL = g(par)\n if (p != 0 && adjL.size == 1) return 1\n import scala.collection.JavaConverters._\n (for ((v,id) <- adjL.asScala if id != p) yield {\n efs(id) = traverse(v, id)\n tWs add ((getDiff(id), id))\n cur = cur + ws(id) * efs(id)\n efs(id)\n }).sum\n }\n traverse(1)\n var ans = 0\n while (cur > s) {\n val (k, id) = tWs.remove()\n cur -= k\n ws(id) /= 2\n tWs add ((getDiff(id), id))\n ans += 1\n }\n ans\n }\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject WeightsDivision1399E1 {\n\n def main(args: Array[String]): Unit = {\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n // val lines: Iterator[String] =\n // Source.fromString(\"1\\n10 28\\n8 2 8\\n5 1 4\\n6 1 10\\n10 2 7\\n7 2 1\\n9 2 1\\n2 1 5\\n4 1 9\\n3 2 5\").getLines\n\n // 1\n // / / \\ \\\n // 5 6 4 2\n // / / \\ \\ \\\n // 10 8 7 9 3\n val ntc: Int = lines.next.toInt\n var i = 0\n while (i < ntc) {\n println(handleTC())\n i+=1\n }\n\n def handleTC(): Int = {\n val vAndS = lines.next.split(\" \")\n val v = vAndS(0).toInt\n val s = vAndS(1).toLong\n val g: Array[java.util.ArrayList[(Int, Int)]] = Array.ofDim[java.util.ArrayList[(Int, Int)]](v+1)\n var inb = 0\n while (inb <= v) {\n g(inb) = new java.util.ArrayList()\n inb+=1\n }\n val efs = Array.ofDim[Int](v)\n val ws = Array.ofDim[Int](v)\n var ing = 1\n while (ing < v) {\n val s = lines.next.split(\" \")\n val v = s(0).toInt\n val u = s(1).toInt\n val w = s(2).toInt\n g(v).add((u,ing))\n g(u).add((v,ing))\n ws(ing) = w\n ing+=1\n }\n val tWs: java.util.PriorityQueue[(Long, Int)] = new java.util.PriorityQueue[(Long, Int)]((x: (Long, Int), y: (Long, Int)) => {\n def foo(x: (Long, Int), y: (Long, Int)) = if (x._1 < y._1) 1 else if (x._1 == y._1 && x._2 < y._2) 1\n else -1\n foo(x, y)\n })\n def getDiff(e: Int): Long = (ws(e) - ws(e) / 2) * efs(e)\n var cur = 0L\n // DFS\n def traverse(par: Int, p: Int = 0): Int = {\n val adjL = g(par)\n if (p != 0 && adjL.size == 1) return 1\n import scala.collection.JavaConverters._\n (for ((v,id) <- adjL.asScala if id != p) yield {\n efs(id) = traverse(v, id)\n tWs add ((getDiff(id), id))\n cur = cur + ws(id) * efs(id)\n efs(id)\n }).sum\n }\n traverse(1)\n var ans = 0\n while (cur > s) {\n val (k, id) = tWs.remove()\n cur -= k\n ws(id) /= 2\n tWs add ((getDiff(id), id))\n ans += 1\n }\n ans\n }\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.Source\n\nobject WeightsDivision1399E1 extends App {\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n// val lines: Iterator[String] =\n// Source.fromString(\"1\\n10 28\\n8 2 8\\n5 1 4\\n6 1 10\\n10 2 7\\n7 2 1\\n9 2 1\\n2 1 5\\n4 1 9\\n3 2 5\").getLines\n\n // 1\n // / / \\ \\\n // 5 6 4 2\n // / / \\ \\ \\\n // 10 8 7 9 3\n val ntc: Int = lines.next.toInt\n 0 until ntc map { _ =>\n handleTC()\n } foreach { println }\n\n case class Edge(uv: (Int, Int), w: Long)\n\n private def handleTC(): Int = {\n val vAndS = lines.next.split(\" \")\n val v = vAndS(0).toInt\n val S = vAndS(1).toLong\n val g: Array[mutable.Set[(Int, Int)]] = Array.ofDim[mutable.Set[(Int, Int)]](v+1)\n def updEdgeSet(v: Int, u: Int, w: Int): Unit = {\n val es = Option(g(v)).getOrElse(mutable.Set())\n es.+=((u,w))\n g(v) = es\n }\n for (_ <- 1 until v) {\n val s = lines.next.split(\" \")\n val v = s(0).toInt\n val u = s(1).toInt\n val w = s(2).toInt\n updEdgeSet(v, u, w)\n updEdgeSet(u, v, w)\n }\n val tWs = mutable.PriorityQueue[(Long, Long)]()(Ordering\n .by[(Long, Long), Long](x => Math.ceil(x._1 / 2.0).asInstanceOf[Int] * x._2))\n var r = 0L\n // DFS\n def traverse(par: Int, grand:Int): Long = {\n val adjL = g(par)\n if (adjL.size == 1) return 1\n (for ((v,w) <- adjL.toSeq if v != grand) yield {\n val nextAdjL = g(v)\n// nextAdjL.-=((par, w))//remove parent edge = mark as visited\n val ecf = traverse(v,par)\n tWs += ((w, ecf))\n r = r + w * ecf\n ecf\n }).sum\n }\n traverse(1,0)\n if (r <= S) {\n 0\n } else {\n var st = 0\n do {\n val (w, c) = tWs.dequeue\n st = st + 1\n val ceil = Math.ceil(w / 2.0).asInstanceOf[Long]\n r = r - ceil * c\n tWs += ((w - ceil, c))\n } while (tWs.nonEmpty && r > S)\n st\n }\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.Source\n\nobject WeightsDivision1399E1 extends App {\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n// val lines: Iterator[String] =\n// Source.fromString(\"3\\n3 20\\n2 1 8\\n3 1 7\\n5 50\\n1 3 100\\n1 5 10\\n2 3 123\\n5 4 55\\n2 100\\n1 2 409\").getLines\n val ntc: Int = lines.next.toInt\n 0 until ntc map { _ =>\n handleTC()\n } foreach { println }\n\n case class Edge(uv: (String, String), w: Int)\n\n private def handleTC() = {\n val vAndS = lines.next.split(\" \")\n val v = vAndS(0).toInt\n val S = vAndS(1).toInt\n val g = mutable.Map[String, mutable.Set[Edge]]()\n def updEdgeSet(e: Edge, f: Edge => String): Unit = {\n val es = g.getOrElse(f(e), mutable.Set())\n es.add(e)\n g(f(e)) = es\n }\n for (_ <- 1 until v) {\n val s = lines.next.split(\" \")\n val e = Edge((s(0), s(1)), s(2).toInt)\n updEdgeSet(e, _.uv._1)\n updEdgeSet(e, _.uv._2)\n }\n val eCounts = mutable.Map[Edge, Int]()\n val tWs = mutable.PriorityQueue[Int]()\n def traverse(par: String): Unit = {\n for (e <- g(par)) {\n val nonPar = e.uv.productIterator.find(_ != par).get.asInstanceOf[String]\n g(nonPar).remove(e)\n traverse(nonPar)\n val ec = g(nonPar).map(eCounts).sum\n val ecf = if (ec == 0) 1 else ec\n eCounts(e) = ecf\n tWs += e.w * ecf\n }\n }\n traverse(\"1\")\n var r = tWs.sum\n if (r <= S) {\n 0\n } else {\n var st = 0\n do {\n val i = tWs.dequeue\n st = st + 1\n val ceil = Math.ceil(i / 2.0).asInstanceOf[Int]\n r = r - ceil\n tWs += Math.floor(i / 2.0).asInstanceOf[Int]\n } while (tWs.nonEmpty && r > S)\n st\n }\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject WeightsDivision1399E1 {\n\n def main(args: Array[String]): Unit = {\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n // val lines: Iterator[String] =\n // Source.fromString(\"1\\n10 28\\n8 2 8\\n5 1 4\\n6 1 10\\n10 2 7\\n7 2 1\\n9 2 1\\n2 1 5\\n4 1 9\\n3 2 5\").getLines\n\n // 1\n // / / \\ \\\n // 5 6 4 2\n // / / \\ \\ \\\n // 10 8 7 9 3\n val ntc: Int = lines.next.toInt\n var i = 0\n while (i < ntc) {\n println(handleTC())\n i+=1\n }\n\n def handleTC(): Int = {\n val vAndS = lines.next.split(\" \")\n val v = vAndS(0).toInt\n val s = vAndS(1).toLong\n val g: Array[java.util.ArrayList[(Int, Int)]] = Array.ofDim[java.util.ArrayList[(Int, Int)]](v+1)\n var inb = 0\n while (inb <= v) {\n g(inb) = new java.util.ArrayList()\n inb+=1\n }\n val efs = Array.ofDim[Int](v)\n val ws = Array.ofDim[Int](v)\n var ing = 1\n while (ing < v) {\n val s = lines.next.split(\" \")\n val v = s(0).toInt\n val u = s(1).toInt\n val w = s(2).toInt\n g(v).add((u,ing))\n g(u).add((v,ing))\n ws(ing) = w\n ing+=1\n }\n val tWs: java.util.PriorityQueue[(Long, Int)] = new java.util.PriorityQueue[(Long, Int)]((x: (Long, Int), y: (Long, Int)) => {\n def foo(x: (Long, Int), y: (Long, Int)) = if (x._1 < y._1) 1 else if (x._1 == y._1 && x._2 < y._2) 1\n else -1\n foo(x, y)\n })\n def getDiff(e: Int): Long = ws(e)*1L*efs(e) - (ws(e) / 2L) * 1L*efs(e)\n var cur = 0L\n // DFS\n def traverse(par: Int, p: Int = 0): Int = {\n val adjL = g(par)\n if (p != 0 && adjL.size == 1) return 1\n import scala.collection.JavaConverters._\n (for ((v,id) <- adjL.asScala if id != p) yield {\n efs(id) = traverse(v, id)\n tWs add ((getDiff(id), id))\n cur = cur + ws(id) * efs(id)\n efs(id)\n }).sum\n }\n traverse(1)\n var ans = 0\n while (cur > s) {\n val (k, id) = tWs.remove()\n cur -= k\n ws(id) /= 2\n tWs add ((getDiff(id), id))\n ans += 1\n }\n ans\n }\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject WeightsDivision1399E1 {\n\n def main(args: Array[String]): Unit = {\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n // val lines: Iterator[String] =\n // Source.fromString(\"1\\n10 28\\n8 2 8\\n5 1 4\\n6 1 10\\n10 2 7\\n7 2 1\\n9 2 1\\n2 1 5\\n4 1 9\\n3 2 5\").getLines\n\n // 1\n // / / \\ \\\n // 5 6 4 2\n // / / \\ \\ \\\n // 10 8 7 9 3\n val ntc: Int = lines.next.toInt\n var i = 0\n while (i < ntc) {\n println(handleTC())\n i+=1\n }\n\n def handleTC(): Int = {\n val vAndS = lines.next.split(\" \")\n val v = vAndS(0).toInt\n val S = vAndS(1).toLong\n val g: Array[java.util.ArrayList[(Int, Int)]] = Array.ofDim[java.util.ArrayList[(Int, Int)]](v+1)\n var inb = 0\n while (inb <= v) {\n g(inb) = new java.util.ArrayList()\n inb+=1\n }\n val efs = Array.ofDim[Int](v)\n val ws = Array.ofDim[Int](v)\n var ing = 1\n while (ing < v) {\n val s = lines.next.split(\" \")\n val v = s(0).toInt\n val u = s(1).toInt\n val w = s(2).toInt\n g(v).add((u,ing))\n g(u).add((v,ing))\n ws(ing) = w\n ing+=1\n }\n val tWs: java.util.PriorityQueue[(Long, Int)] = new java.util.PriorityQueue[(Long, Int)]((x: (Long, Int), y: (Long, Int)) => {\n def foo(x: (Long, Int), y: (Long, Int)) = if (x._1 < y._1) 1 else -1\n foo(x, y)\n })\n def getDiff(e: Int): Long = (ws(e) - ws(e) / 2) * efs(e)\n var r = 0L\n // DFS\n def traverse(par: Int, p: Int): Int = {\n val adjL = g(par)\n if (adjL.size == 1) return 1\n import scala.collection.JavaConverters._\n (for ((v,id) <- adjL.asScala if id != p) yield {\n efs(id) = traverse(v, id)\n tWs add ((getDiff(id), id))\n r = r + ws(id) * efs(id)\n efs(id)\n }).sum\n }\n traverse(1,0)\n var st = 0\n while (r > S) {\n val (k, e) = tWs.remove()\n st += 1\n ws(e) = ws(e) / 2\n r = r - k\n tWs add ((getDiff(e), e))\n }\n st\n }\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.Source\n\nobject WeightsDivision1399E1 extends App {\n// val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n val lines: Iterator[String] =\n Source.fromString(\"1\\n10 28\\n8 2 8\\n5 1 4\\n6 1 10\\n10 2 7\\n7 2 1\\n9 2 1\\n2 1 5\\n4 1 9\\n3 2 5\").getLines\n\n // 1\n // / / \\ \\\n // 5 6 4 2\n // / / \\ \\ \\\n // 10 8 7 9 3\n val ntc: Int = lines.next.toInt\n 0 until ntc map { _ =>\n handleTC()\n } foreach { println }\n\n case class Edge(uv: (Int, Int), w: Long)\n\n private def handleTC(): Int = {\n val vAndS = lines.next.split(\" \")\n val v = vAndS(0).toInt\n val S = vAndS(1).toLong\n val g: Array[mutable.Buffer[(Int, Int)]] = Array.ofDim[mutable.Buffer[(Int, Int)]](v+1)\n def updEdgeSet(v: Int, u: Int, w: Int): Unit = {\n val es = Option(g(v)).getOrElse(mutable.Buffer())\n es.+=((u,w))\n g(v) = es\n }\n for (_ <- 1 until v) {\n val s = lines.next.split(\" \")\n val v = s(0).toInt\n val u = s(1).toInt\n val w = s(2).toInt\n updEdgeSet(v, u, w)\n updEdgeSet(u, v, w)\n }\n val tWs = mutable.TreeMap[(Long, Int), (Long, Long)]()\n var r = 0L\n def getDiff(w: Long, c: Long): Long = {\n Math.ceil(w / 2.0).asInstanceOf[Long] * c\n }\n // DFS\n def traverse(par: Int, grand: Int): Long = {\n val adjL = g(par)\n if (grand != 0 && adjL.size == 1) return 1\n (for ((v,w) <- adjL if v != grand) yield {\n val ecf = traverse(v, par)\n tWs((getDiff(w, ecf), v)) = (w, ecf)\n r = r + w * ecf\n ecf\n }).sum\n }\n traverse(1,0)\n var st = 0\n while (r > S) {\n val ((k, v), (w, c)) = tWs.last\n tWs.remove((k,v))\n st = st + 1\n val floor = Math.floor(w / 2.0).asInstanceOf[Long]\n r = r - k\n tWs((getDiff(floor, c), v)) = (floor, c)\n }\n st\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject WeightsDivision1399E1 {\n\n def main(args: Array[String]): Unit = {\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n // val lines: Iterator[String] =\n // Source.fromString(\"1\\n10 28\\n8 2 8\\n5 1 4\\n6 1 10\\n10 2 7\\n7 2 1\\n9 2 1\\n2 1 5\\n4 1 9\\n3 2 5\").getLines\n\n // 1\n // / / \\ \\\n // 5 6 4 2\n // / / \\ \\ \\\n // 10 8 7 9 3\n val ntc: Int = lines.next.toInt\n var i = 0\n while (i < ntc) {\n println(handleTC())\n i+=1\n }\n\n def handleTC(): Int = {\n val vAndS = lines.next.split(\" \")\n val v = vAndS(0).toInt\n val S = vAndS(1).toLong\n val g: Array[java.util.ArrayList[(Int, Int)]] = Array.ofDim[java.util.ArrayList[(Int, Int)]](v+1)\n var inb = 0\n while (inb <= v) {\n g(inb) = new java.util.ArrayList()\n inb+=1\n }\n val efs = Array.ofDim[Int](v)\n val ws = Array.ofDim[Int](v)\n var ing = 1\n while (ing < v) {\n val s = lines.next.split(\" \")\n val v = s(0).toInt\n val u = s(1).toInt\n val w = s(2).toInt\n g(v).add((u,ing))\n g(u).add((v,ing))\n ws(ing) = w\n ing+=1\n }\n val tWs: java.util.PriorityQueue[(Long, Int)] = new java.util.PriorityQueue[(Long, Int)]((x: (Long, Int), y: (Long, Int)) => {\n def foo(x: (Long, Int), y: (Long, Int)) = if (x._1 < y._1) 1 else -1\n foo(x, y)\n })\n def getDiff(e: Int): Long = (ws(e) - ws(e) / 2) * efs(e)\n var r = 0L\n // DFS\n def traverse(par: Int, grand: Int): Int = {\n val adjL = g(par)\n if (grand != 0 && adjL.size == 1) return 1\n import scala.collection.JavaConverters._\n (for ((v,id) <- adjL.asScala if id != grand) yield {\n efs(id) = traverse(v, id)\n tWs add ((getDiff(id), id))\n r = r + ws(id) * efs(id)\n efs(id)\n }).sum\n }\n traverse(1,0)\n var st = 0\n while (r > S) {\n val (k, e) = tWs.remove()\n st += 1\n ws(e) = ws(e) / 2\n r = r - k\n tWs add ((getDiff(e), e))\n }\n st\n }\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.Source\n\nobject WeightsDivision1399E1 extends App {\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n// val lines: Iterator[String] =\n// Source.fromString(\"1\\n10 28\\n8 2 8\\n5 1 4\\n6 1 10\\n10 2 7\\n7 2 1\\n9 2 1\\n2 1 5\\n4 1 9\\n3 2 5\").getLines\n val ntc: Int = lines.next.toInt\n 0 until ntc map { _ =>\n handleTC()\n } foreach { println }\n\n case class Edge(uv: (String, String), w: Int)\n\n private def handleTC() = {\n val vAndS = lines.next.split(\" \")\n val v = vAndS(0).toInt\n val S = vAndS(1).toInt\n val g = mutable.Map[String, mutable.Set[Edge]]()\n def updEdgeSet(e: Edge, f: Edge => String): Unit = {\n val es = g.getOrElse(f(e), mutable.Set())\n es.add(e)\n g(f(e)) = es\n }\n for (_ <- 1 until v) {\n val s = lines.next.split(\" \")\n val e = Edge((s(0), s(1)), s(2).toInt)\n updEdgeSet(e, _.uv._1)\n updEdgeSet(e, _.uv._2)\n }\n val eCounts = mutable.Map[Edge, Int]()\n val tWs = mutable.PriorityQueue[(Int, Int)]()(Ordering.by[(Int, Int), Int](x => Math.ceil(x._1 / 2.0).asInstanceOf[Int] * x._2))\n def traverse(par: String): Unit = {\n for (e <- g(par)) {\n val nonPar = e.uv.productIterator.find(_ != par).get.asInstanceOf[String]\n g(nonPar).remove(e)\n traverse(nonPar)\n val ec = g(nonPar).toSeq.map(eCounts).sum\n val ecf = if (ec == 0) 1 else ec\n eCounts(e) = ecf\n tWs += ((e.w, ecf))\n }\n }\n traverse(\"1\")\n var r = tWs.map { case (w,c) => w * c }.sum\n if (r <= S) {\n 0\n } else {\n var st = 0\n do {\n val (w, c) = tWs.dequeue\n st = st + 1\n val ceil = Math.ceil(w / 2.0).asInstanceOf[Int]\n r = r - ceil * c\n tWs += ((Math.floor(w / 2.0).asInstanceOf[Int], c))\n } while (tWs.nonEmpty && r > S)\n st\n }\n }\n}\n"}], "src_uid": "9cd7f058d4671b12b67babd38293a3fc"} {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val Array(n, b, d) = lines.next().split(' ').map(_.toInt)\n println(lines.next().split(' ').map(_.toInt).filter(_ <= b).foldLeft((0, 0l)) {\n case ((cleans, v), a) if a + v > d => (cleans + 1, 0)\n case ((cleans, v), a) => (cleans, v + a)\n }._1)\n}", "positive_code": [{"source_code": "object A709 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n, b, d) = readLongs(3)\n val in = readLongs(n.toInt)\n var curr = 0L\n var res = 0\n for(i <- 0 until n.toInt) {\n if(in(i) <= b)\n curr += in(i)\n if(curr > d) {\n curr = 0\n res += 1\n }\n }\n\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _709A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll}\n val n, b, d = read[Int]\n val oranges = read[Seq, Int](n)\n var juice, ans = 0\n\n oranges.filter(_ <= b) foreach {orange =>\n juice += orange\n if (juice > d) {\n juice = 0\n ans += 1\n }\n }\n\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val Array(n, b, d) = lines.next().split(' ').map(_.toInt)\n println(lines.next().split(' ').map(_.toInt).foldLeft((0, 0l)) {\n case ((cleans, v), a) if a >= b => (cleans, v)\n case ((cleans, v), a) if a + v > d => (cleans + 1, 0l)\n case ((cleans, v), a) => (cleans, v + a)\n }._1)\n}"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val Array(n, b, d) = lines.next().split(' ').map(_.toInt)\n println(lines.next().split(' ').map(_.toInt).foldLeft((0, 0)) {\n case ((cleans, v), a) if a >= b => (cleans, v)\n case ((cleans, v), a) if a + v > d => (cleans + 1, 0)\n case ((cleans, v), a) => (cleans, v + a)\n }._1)\n}"}], "src_uid": "06e9649963715e56d97297c6104fbc00"} {"source_code": "object C extends App {\n\n val s = readLine\n\n var a = 0\n if (s.head != s.last) {\n var i = 1\n a = 2\n while (i < s.length - 1 && s(i) != s(i - 1)) {\n i += 1\n a += 1\n }\n var j = s.length - 2\n while (j >= i && s(j) != s(j + 1)) {\n j -= 1\n a += 1\n }\n }\n\n var b = 1\n var run = 1\n for (i <- 1 until s.length) {\n if (s(i) != s(i - 1)) run += 1\n else run = 1\n if (run > b) b = run\n }\n\n println(a max b)\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val S = ns()\n\n var ans = 0\n var w, b = 0\n val N = S.length\n rep(2 * N) { i =>\n if (S(i % N) == 'b') {\n b = w + 1\n w = 0\n ans = max(ans, b)\n } else {\n w = b + 1\n b = 0\n ans = max(ans, w)\n }\n }\n\n if (ans > N) ans = N\n out.println(ans)\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}"}], "negative_code": [{"source_code": "object C extends App {\n\n val s = readLine\n\n var a = 0\n if (s.head != s.last) {\n var i = 1\n a = 2\n while (i < s.length && s(i) != s(i - 1)) {\n i += 1\n a += 1\n }\n var j = s.length - 2\n while (j > i && s(j) != s(j + 1)) {\n j -= 1\n a += 1\n }\n }\n\n var b = 0\n var run = 1\n for (i <- 1 until s.length) {\n if (s(i) != s(i - 1)) run += 1\n else run = 1\n if (run > b) b = run\n }\n//println(a, b)\n println(a max b)\n}\n"}, {"source_code": "object C extends App {\n\n val s = readLine\n\n var a = 0\n if (s.head != s.last) {\n var i = 1\n a = 2\n while (i < s.length - 1 && s(i) != s(i - 1)) {\n i += 1\n a += 1\n }\n var j = s.length - 2\n while (j >= i && s(j) != s(j + 1)) {\n j -= 1\n a += 1\n }\n }\n\n var b = 0\n var run = 1\n for (i <- 1 until s.length) {\n if (s(i) != s(i - 1)) run += 1\n else run = 1\n if (run > b) b = run\n }\n\n println(a max b)\n}\n"}], "src_uid": "313b16ba918fbb96a2b103128e0153c6"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val n, m, k = nl()\n val ans = if (n > k || m > k) -1\n else {\n val par = (k - n) % 2 + (k - m) % 2\n k - par\n }\n out.println(ans)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object Main {\nimport java.io._\nimport java.util.Scanner\n\nimport collection.mutable.HashMap\nimport scala.collection.{SortedSet, mutable}\nimport scala.util.Random\n protected val EPS = 1e-11\n\n private def default = (\n new StreamTokenizer(new InputStreamReader(System.in)),\n new Scanner(System.in),\n new PrintWriter(System.out)\n )\n\n val (in, ins, out) = {\n try {\n if (sys.props.contains(\"xDx\")) {\n (\n new StreamTokenizer(new FileReader(\"input.txt\")),\n new Scanner(new FileReader(\"input.txt\")),\n new PrintWriter(new FileWriter(\"output.txt\"))\n )\n } else {\n default\n }\n } catch {\n case _: Throwable => default\n }\n }\n\n private def nextInt = {\n in.nextToken\n in.nval.toInt\n }\n\n private def nextLong = {\n in.nextToken\n in.nval.toLong\n }\n\n\n private def nextDouble = {\n in.nextToken\n in.nval\n }\n\n\n private def nextString = {\n in.nextToken\n in.sval\n }\n\n private def nextChar = {\n in.nextToken\n in.ttype.toChar\n }\n\n def main(args: Array[String]): Unit = {\n try {\n new Run().run()\n } catch {\n case e: Throwable =>\n throw new RuntimeException(e)\n } finally out.close()\n }\n\n class Run {\n import collection.breakOut\n def run(): Unit = {\n val q = ins.nextInt\n for(_ <- 1 to q) {\n val n = ins.nextLong\n val m = ins.nextLong\n val k = ins.nextLong\n val max = math.max(n, m)\n if(max > k) {\n println(-1)\n } else {\n val rest = k - max\n var res = k\n val con1 = (m - n).abs % 2 == 1\n val con2 = rest % 2 == 1\n if(con1) {\n res -= 1\n } else if(con2) {\n res -= 2\n }\n \n println(res)\n }\n }\n }\n\n }\n\n}\n\n\n"}], "negative_code": [{"source_code": "object Main {\nimport java.io._\nimport java.util.Scanner\n\nimport collection.mutable.HashMap\nimport scala.collection.{SortedSet, mutable}\nimport scala.util.Random\n protected val EPS = 1e-11\n\n private def default = (\n new StreamTokenizer(new InputStreamReader(System.in)),\n new Scanner(System.in),\n new PrintWriter(System.out)\n )\n\n val (in, ins, out) = {\n try {\n if (sys.props.contains(\"xDx\")) {\n (\n new StreamTokenizer(new FileReader(\"input.txt\")),\n new Scanner(new FileReader(\"input.txt\")),\n new PrintWriter(new FileWriter(\"output.txt\"))\n )\n } else {\n default\n }\n } catch {\n case _: Throwable => default\n }\n }\n\n private def nextInt = {\n in.nextToken\n in.nval.toInt\n }\n\n private def nextLong = {\n in.nextToken\n in.nval.toLong\n }\n\n\n private def nextDouble = {\n in.nextToken\n in.nval\n }\n\n\n private def nextString = {\n in.nextToken\n in.sval\n }\n\n private def nextChar = {\n in.nextToken\n in.ttype.toChar\n }\n\n def main(args: Array[String]): Unit = {\n try {\n new Run().run()\n } catch {\n case e: Throwable =>\n throw new RuntimeException(e)\n } finally out.close()\n }\n\n class Run {\n import collection.breakOut\n def run(): Unit = {\n val q = ins.nextInt\n for(_ <- 1 to q) {\n val n = ins.nextLong\n val m = ins.nextLong\n val k = ins.nextLong\n val max = math.max(n, m)\n if(max > k) {\n println(-1)\n } else {\n val rest = k - max\n var res = max + ((rest >> 1) << 1)\n if((m - n).abs % 2 == 1 || rest % 2 == 1) {\n res -= 1\n }\n \n println(res)\n }\n }\n }\n\n }\n\n}\n\n\n"}, {"source_code": "object Main {\nimport java.io._\nimport java.util.Scanner\n\nimport collection.mutable.HashMap\nimport scala.collection.{SortedSet, mutable}\nimport scala.util.Random\n protected val EPS = 1e-11\n\n private def default = (\n new StreamTokenizer(new InputStreamReader(System.in)),\n new Scanner(System.in),\n new PrintWriter(System.out)\n )\n\n val (in, ins, out) = {\n try {\n if (sys.props.contains(\"xDx\")) {\n (\n new StreamTokenizer(new FileReader(\"input.txt\")),\n new Scanner(new FileReader(\"input.txt\")),\n new PrintWriter(new FileWriter(\"output.txt\"))\n )\n } else {\n default\n }\n } catch {\n case _: Throwable => default\n }\n }\n\n private def nextInt = {\n in.nextToken\n in.nval.toInt\n }\n\n private def nextLong = {\n in.nextToken\n in.nval.toLong\n }\n\n\n private def nextDouble = {\n in.nextToken\n in.nval\n }\n\n\n private def nextString = {\n in.nextToken\n in.sval\n }\n\n private def nextChar = {\n in.nextToken\n in.ttype.toChar\n }\n\n def main(args: Array[String]): Unit = {\n try {\n new Run().run()\n } catch {\n case e: Throwable =>\n throw new RuntimeException(e)\n } finally out.close()\n }\n\n class Run {\n import collection.breakOut\n def run(): Unit = {\n val q = ins.nextInt\n for(_ <- 1 to q) {\n val n = ins.nextLong\n val m = ins.nextLong\n val k = ins.nextLong\n val max = math.max(n, m)\n if(max > k) {\n println(-1)\n } else {\n val rest = k - max\n val min = math.min(n, m)\n var res = min - (rest % 2) + (rest / 2) * 2\n val rest2 = k - (max + (max - min))\n if(rest2 >= 0) {\n res = math.max(res, max - (rest2 % 2) + (rest2 / 2) * 2)\n }\n \n println(res)\n }\n }\n }\n\n }\n\n}\n\n\n"}], "src_uid": "5eac47595f0212b2b652518f0fefd238"} {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val first = (1 to n).map { _ => in.next()}\n val second = (1 to m).map { _ => in.next()}\n val firstSet = first.toSet\n val commonCount = second.count(firstSet)\n val firstCount = n - commonCount\n val secondCount = m - commonCount\n if ((firstCount + commonCount % 2) <= secondCount)\n System.out.println(\"NO\")\n else\n System.out.println(\"YES\")\n\n}", "positive_code": [{"source_code": "import java.io._\nimport scala.io.Source\n\nimport scala.annotation.tailrec\n\nobject ProblemB {\n def main(args: Array[String]): Unit = processStdInOut()\n\n def processStdInOut(): Unit = {\n val src = Source.fromInputStream(System.in)\n processFromSource(src)\n }\n\n def processFromSource(src: Source): Unit = {\n try {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out));\n try {\n val lines = src.getLines()\n processLines(lines, bw)\n } finally {\n bw.flush()\n }\n } finally {\n src.close();\n }\n }\n\n // Standard code above, custom code below\n\n def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {\n val line = lines.next()\n val counts = line.split(\" \").map(_.toInt)\n val (c1, c2) = (counts(0), counts(1))\n var firstWordSet = (1 to c1).map(_ => lines.next()).toSet\n val sharedWordCount = (1 to c2).count(_ => firstWordSet.contains(lines.next()))\n val soln = solve(c1 - sharedWordCount, c2 - sharedWordCount, sharedWordCount)\n bw.write(if (soln) \"YES\" else \"NO\")\n bw.newLine()\n }\n\n // Answer is whether first player can win\n def solve(unique1: Int, unique2: Int, shared: Int): Boolean = {\n if (unique1 == unique2) {\n // If odd number of shared words, then first person gets to say one more shared word before they run out, to win\n // Else second can always answer the first\n (shared % 2 != 0)\n } else unique1 > unique2 // keep saying shared words, which decreases both players'\n }\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _755B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n, m = read[Int]\n val poland = read[Set, String](n)\n val enemy = read[Set, String](m)\n val common = poland intersect enemy\n val win = enemy.size - (common.size%2 != 0).to[Int] < poland.size\n write(win.toEnglish)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n// def isEven: Boolean = (x % 2) == 0\n// def isOdd: Boolean = !isEven\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "\nimport java.io.PrintWriter\n\nimport scala.collection.mutable\n\nobject B {\n\n def main(args: Array[String]): Unit = {\n val in = io.Source.fromInputStream(System.in).getLines()\n // val in = io.Source.fromFile(\"in.txt\").getLines()\n val out = new PrintWriter(System.out)\n // val out = new PrintWriter(new File(\"out.txt\"))\n val Array(n,m) = in.next().split(\" \").map(_.toInt)\n val s1 = new mutable.HashSet[String]()\n val s2 = new mutable.HashSet[String]()\n\n for (i<- 1 to n)\n s1 += in.next()\n for (i<- 1 to m)\n s2 += in.next()\n\n val i = s1.intersect(s2)\n\n val i1 = s1.size + (if (i.size %2 == 1) (i.size >> 1) + 1 else i.size >> 1) - i.size\n val i2 = s2.size + (i.size >> 1) - i.size\n\n out.println(if (i1 > i2) \"YES\" else \"NO\")\n\n out.flush()\n out.close()\n }\n\n def isPrime(x: Int): Boolean = {\n if (x % 2 == 0)\n return false\n for (i <- 3 to x >> 1 if (i & 1) != 0)\n if (x % i == 0)\n return false\n true\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject PolandBall extends App {\n def parseInts(str: String, numIterations: Integer) = {\n val scanner = new Scanner(str)\n val res = (0 until numIterations) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n def scanString(str: String) = {\n val scanner = new java.util.Scanner(str)\n val res = scanner.next()\n scanner.close()\n res\n }\n\n val numWordsPerPlayer = parseInts(Console.readLine(), 2)\n\n val polandWords = {\n for {i <- 0 until numWordsPerPlayer(0)} yield scanString(Console.readLine())\n }.toSet\n\n val enemyWords = {\n for {i <- 0 until numWordsPerPlayer(1)} yield scanString(Console.readLine())\n }.toSet\n\n val sharedWords = polandWords.filter(word => {\n enemyWords.contains(word)\n })\n\n def getEnemyWordsWithDisadvantage(enemySet: Set[String])(sharedSet: Set[String]) = {\n def isSharedSetDisadvantaged = (sharedSet: Set[String]) => {\n if (sharedWords.size % 2 != 0) 1 else 0\n }\n enemySet.size - isSharedSetDisadvantaged(sharedSet)\n }\n\n println(if (polandWords.size > getEnemyWordsWithDisadvantage(enemyWords)(sharedWords)) \"YES\" else \"NO\")\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject PolandBall extends App {\n def parseInts(str: String, numIterations: Integer) = {\n val scanner = new Scanner(str)\n val res = (0 until numIterations) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n def scanString(str: String) = {\n val scanner = new java.util.Scanner(str)\n val res = scanner.next()\n scanner.close()\n res\n }\n\n val numWordsPerPlayer = parseInts(Console.readLine(), 2)\n\n val polandWords =\n {for {i <- 0 until numWordsPerPlayer(0)} yield scanString(Console.readLine())}.toSet\n\n val enemyWords =\n {for {i <- 0 until numWordsPerPlayer(1)} yield scanString(Console.readLine())}.toSet\n\n val sharedWords = polandWords.filter(word => {\n enemyWords.contains(word)\n })\n\n println(if (enemyWords.size - (if (sharedWords.size % 2 != 0) 1 else 0) < polandWords.size) \"YES\" else \"NO\")\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject PolandBall extends App {\n def parseInts(str: String, numIterations: Integer) = {\n val scanner = new Scanner(str)\n val res = (0 until numIterations) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n\n def scanString(str: String) = {\n val scanner = new java.util.Scanner(str)\n val res = scanner.next()\n scanner.close()\n res\n }\n\n val numWordsPerPlayer = parseInts(Console.readLine(), 2)\n\n val polandWords = {\n for {i <- 0 until numWordsPerPlayer(0)} yield scanString(Console.readLine())\n }.toSet\n\n val enemyWords = {\n for {i <- 0 until numWordsPerPlayer(1)} yield scanString(Console.readLine())\n }.toSet\n\n val sharedWords = polandWords.filter(word => {\n enemyWords.contains(word)\n })\n\n def getEnemyWordsWithDisadvantage(enemySet: Set[String])(sharedSet: Set[String]) = {\n def sharedSetOddLength = (sharedSet: Set[String]) => {\n if (sharedWords.size % 2 != 0) 1 else 0\n }\n enemySet.size - sharedSetOddLength(sharedSet)\n }\n\n println(if (polandWords.size > getEnemyWordsWithDisadvantage(enemyWords)(sharedWords)) \"YES\" else \"NO\")\n}\n"}], "negative_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _755B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n, m = read[Int]\n val poland = read[Set, String](n)\n val enemy = read[Set, String](m)\n val common = poland intersect enemy\n val win = enemy.size - common.size < poland.size\n write(win.toEnglish)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _755B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n, m = read[Int]\n val poland = read[Set, String](n)\n val enemy = read[Set, String](m)\n val common = poland intersect enemy\n\n val win = (enemy.size - poland.size) <= 0\n\n write(win.toEnglish)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "4b352854008a9378551db60b76d33cfa"} {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n private def ridge(an: Vector[Int], k: Int): (Int, Int) = {\n val n = an.length\n\n val peaks = an.indices.map { i =>\n if (i == 0 || i == n - 1) 0\n else if (an(i - 1) < an(i) && an(i) > an(i + 1)) 1\n else 0\n }\n\n val prefixes = Array.fill(n)(0)\n (1 until n).foreach(i => prefixes(i) = prefixes(i - 1) + peaks(i))\n\n (0 to (n - k)).foldLeft((0, 0)) {\n case ((t, l), i) =>\n val f = prefixes(i + k - 2) - prefixes(i)\n\n if (f > t) (f, i)\n else (t, l)\n }\n }\n\n (0 until t).foreach { _ =>\n val Array(_, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toVector\n\n val (t, l) = ridge(an, k)\n\n println(s\"${t + 1} ${l + 1}\")\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n private def ridge(an: Vector[Int], k: Int): (Int, Int) = {\n val n = an.length\n\n val peaks = an.indices.map { i =>\n if (i == 0 || i == n - 1) 0\n else if (an(i - 1) < an(i) && an(i) > an(i + 1)) 1\n else 0\n }\n\n val prefixes = peaks\n .foldLeft(List(0))((ps, p) => (p + ps.head) :: ps)\n .reverse\n .tail\n .toVector\n\n (0 to (n - k)).foldLeft((0, 0)) {\n case ((t, l), i) =>\n val f = prefixes(i + k - 2) - prefixes(i)\n\n if (f > t) (f, i)\n else (t, l)\n }\n }\n\n (0 until t).foreach { _ =>\n val Array(_, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toVector\n\n val (t, l) = ridge(an, k)\n\n println(s\"${t + 1} ${l + 1}\")\n }\n}\n"}], "negative_code": [{"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n private def peaks(an: Array[Int], k: Int): Array[Int] = {\n val n = an.length\n val pn = Array.fill(n)(0)\n\n @scala.annotation.tailrec\n def go(i: Int = 1): Array[Int] =\n if (i >= n) pn\n else {\n if (i < n - 1 && an(i - 1) < an(i) && an(i) > an(i + 1))\n (i until n.min(i + k - 1)).foreach(pn(_) += 1)\n go(i + 1)\n }\n\n go()\n }\n\n private def ridge(pn: Array[Int], k: Int): (Int, Int) = {\n val (c, l) = pn.zipWithIndex.maxBy(_._1)\n if (c == 0) (c, 1)\n else (c + 1, 1 + 0.max(l + 2 - k))\n }\n\n (0 until t).foreach { _ =>\n val Array(_, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val pn = peaks(an, k)\n val (t, l) = ridge(pn, k)\n\n println(s\"$t $l\")\n }\n}"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n private def peaks(an: Array[Int], k: Int): Array[Int] = {\n val n = an.length\n val pn = Array.fill(n)(0)\n\n @scala.annotation.tailrec\n def go(i: Int = 1): Array[Int] =\n if (i >= n) pn\n else {\n if (i < n - 1 && an(i - 1) < an(i) && an(i) > an(i + 1))\n (i until n.min(i + k - 1)).foreach(pn(_) += 1)\n go(i + 1)\n }\n\n go()\n }\n\n private def ridge(pn: Array[Int], k: Int): (Int, Int) = {\n val (c, l) = pn.zipWithIndex.maxBy(_._1)\n (c + 1, 1 + 0.max(l + 2 - k))\n }\n\n (0 until t).foreach { _ =>\n val Array(_, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val pn = peaks(an, k)\n val (t, l) = ridge(pn, k)\n\n println(s\"$t $l\")\n }\n}"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n private def ridge(an: Vector[Int], k: Int): (Int, Int) = {\n val n = an.length\n\n val peaks = an.indices.map { i =>\n if (i == 0 || i == n - 1) 0\n else if (an(i - 1) < an(i) && an(i) > an(i + 1)) 1\n else 0\n }\n\n val prefixes = peaks\n .foldLeft(List(0))((ps, p) => (p + ps.head) :: ps)\n .reverse\n .tail\n .toVector\n\n (0 to (n - k)).foldLeft((0, 0)) {\n case ((t, l), i) =>\n val f = prefixes(i + k - 2) - prefixes(i)\n\n if (f > t) (f, i)\n else (t, l)\n }\n }\n\n (0 until t).foreach { _ =>\n val Array(_, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toVector\n\n val (t, l) = ridge(an, k)\n\n if (t == 0) println(s\"0 1\")\n else println(s\"${t + 1} ${l + 1}\")\n }\n}\n"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n private def peaks(an: Array[Int], k: Int): Array[Int] = {\n val n = an.length\n val pn = Array.fill(n)(0)\n\n @scala.annotation.tailrec\n def go(i: Int = 1): Array[Int] =\n if (i >= n) pn\n else {\n if (i < n - 1 && an(i - 1) < an(i) && an(i) > an(i + 1))\n (i until (n - 1).min(i + k - 1)).foreach(pn(_) += 1)\n go(i + 1)\n }\n\n go()\n }\n\n private def ridge(pn: Array[Int], k: Int): (Int, Int) = {\n val (c, l) = pn.zipWithIndex.maxBy(_._1)\n (c + 1, 1 + (0 max (l + 2 - k)))\n }\n\n (0 until t).foreach { _ =>\n val Array(_, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val pn = peaks(an, k)\n val (t, l) = ridge(pn, k)\n\n println(s\"$t $l\")\n }\n}"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n private def peaks(an: Array[Int], k: Int): Array[Int] = {\n val n = an.length\n val pn = Array.fill(n)(0)\n\n @scala.annotation.tailrec\n def go(i: Int = 1): Array[Int] =\n if (i >= n) pn\n else {\n if (i < n - 1 && an(i - 1) < an(i) && an(i) > an(i + 1))\n (i until n.min(i + k - 2)).foreach(pn(_) += 1)\n go(i + 1)\n }\n\n go()\n }\n\n private def ridge(pn: Array[Int], k: Int): (Int, Int) = {\n val (c, i) = pn.zipWithIndex.maxBy(_._1)\n if (c == 0) (c, 1 + i)\n else (c + 1, 1 + 0.max(i + 2 - k))\n }\n\n (0 until t).foreach { _ =>\n val Array(_, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val pn = peaks(an, k)\n val (t, l) = ridge(pn, k)\n\n println(s\"$t $l\")\n }\n}"}], "src_uid": "8e182e0acb621c86901fb94b56ff991e"} {"source_code": "import java.util.Scanner\n\nimport scala.collection.immutable.IndexedSeq\n\nobject Main {\n\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n\n val groups: Seq[IndexedSeq[Int]] = (0 until n)\n .map(_ => scanner.nextInt())\n .zipWithIndex\n .groupBy(_._1)\n .map(_._2.map(_._2 + 1)).toSeq\n\n if (groups.size == 3) {\n\n val (a, b, c) = (groups(0), groups(1), groups(2))\n\n val result = a.zip(b).zip(c).map {\n case ((v1, v2), v3) => List(v1, v2, v3)\n }\n\n println(result.size)\n result.foreach(list => println(list.mkString(\" \")))\n } else {\n println(0)\n }\n\n }\n\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _490A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt).toArray\n val g = (1 to n).toList.groupBy(i => a(i - 1)).toMap\n if (g.size < 3) println(0)\n else {\n val min = g.values.map(i => i.size).min\n println(min)\n val cb = g(1).take(min).toArray\n val wb = g(2).take(min).toArray\n val zb = g(3).take(min).toArray\n for (i <- 0 until min) {\n println(\"%d %d %d\".format(cb(i), wb(i), zb(i)))\n }\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n in.next()\n val data = in.next().split(\" \").map(_.toInt).zipWithIndex.groupBy(t => t._1).map(t => t._2.map(_._2 + 1)).toArray\n val min = if (data.length == 3) Math.min(data.head.length, Math.min(data.tail.head.length, data.last.length))\n else 0\n println(min)\n Range(0, min).foreach{ i =>\n println(data.head(i) + \" \" + data.tail.head(i) + \" \" + data.last(i))\n }\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n: Int = io.StdIn.readLine().toInt\n val stu: List[Int] = io.StdIn.readLine().split(\" \").map{ _.toInt }.toList\n val mp: Map[Int, List[Int]] = stu.indices.toList.groupBy[Int]( x => stu(x) ).withDefault( x => List())\n val teams: List[(Int, Int, Int)] = (mp(1).toList, mp(2).toList, mp(3).toList).zipped.toList\n println(teams.length)\n teams.foreach { x => println((x._1 + 1) + \" \" + (x._2 + 1) + \" \" + (x._3 + 1)) }\n }\n}\n"}, {"source_code": "object A490 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n val map = input.zipWithIndex.groupBy(_._1).mapValues(_.map(_._2))\n val totalTeams = Array(1,2,3).map(map.mapValues(_.length).withDefaultValue(0)).min\n println(totalTeams)\n for(i <- 0 until totalTeams) {\n println(Array(1,2,3).map(num => map(num)(i) + 1).mkString(\" \"))\n }\n }\n}"}, {"source_code": "/**\n * Created by Mikhail on 02.01.2015.\n */\n\nobject _490A {\n def main(args: Array[String]) {\n var n = readInt()\n var a = readLine().split(\" \")\n var i = 0\n var j = 0\n var k = 0\n var count = 0\n var res = \"\"\n while (i < n && j < n && k < n) {\n while (i < n && a(i).toInt != 1) {\n i += 1\n }\n while (j < n && a(j).toInt != 2 && i < n) {\n j += 1\n }\n while (k < n && a(k).toInt != 3 && i < n && j < n) {\n k += 1\n }\n if (i < n && j < n && k < n) {\n res += (i + 1) + \" \"\n i += 1\n res += (j + 1) + \" \"\n j += 1\n res += (k + 1) + \"\\n\"\n k += 1\n count += 1\n }\n }\n println(count)\n if (count != 0) {\n println(res)\n }\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n in.next()\n val data = in.next().split(\" \").map(_.toInt).zipWithIndex.groupBy(t => t._1).map(t => t._2.map(_._2 + 1))\n val min = Math.min(data.head.length, Math.min(data.tail.head.length, data.last.length))\n println(min)\n Range(0, min).foreach{ i =>\n println(data.head(i) + \" \" + data.tail.head(i) + \" \" + data.last(i))\n }\n\n}\n"}, {"source_code": "object HelloWorld {\n def main(args: Array[String]) {\n var s = 1\n var n = 1\n var p = readInt()\n p -= 1\n while (p >= s + n + 1) {\n s += n;\n n += 1\n p -= s;\n }\n print(n + \"\\n\")\n }\n}\n"}, {"source_code": "object go {\n def main(args: Array[String]) {\n var s = 1\n var n = 1\n var p = scala.io.StdIn.readInt()\n p -= 1\n while (p >= s + n + 1) {\n n += 1\n s += n;\n p -= s;\n }\n print(n)\n }\n}"}], "src_uid": "c014861f27edf35990cc065399697b10"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, d, h) = in.next().split(' ').map(_.toInt)\n if (d > 2 * h || n < d || (d == 1 && n > 2))\n println(-1)\n else {\n val height = (1 to h).map(i => s\"$i ${i + 1}\").toList\n val startDiameter = if (d != h) List(s\"1 ${h + 2}\") else Nil\n val diameter = (h + 2 to d).map(i => s\"$i ${i + 1}\").toList\n val left = if (d == h)\n (d + 2 to n).map(i => s\"2 $i\").toList\n else\n (d + 2 to n).map(i => s\"1 $i\").toList\n println((height ::: startDiameter ::: diameter ::: left).mkString(\"\\n\"))\n }\n}", "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _658C extends CodeForcesApp {\n override def apply(io: IO) = {\n val n, d, h = io[Int]\n if (d > 2*h || (d == 1 && h == 1 && n > 2)) {\n io += -1\n } else {\n io.separator = \"\\n\"\n\n var c = 1\n\n def addEdge(u: Int, v: Int) = {\n io += s\"$u $v\"\n c += 1\n }\n\n repeat(h) {\n addEdge(c, c+1)\n }\n\n if (d > h) {\n addEdge(1, c+1)\n repeat((d - h - 1) max 0) {\n addEdge(c, c+1)\n }\n }\n\n while(c < n) {\n addEdge(if (d == h) 2 else 1, c + 1)\n }\n io\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sum[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default\n }\n def memoize[I] = new {\n def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def appendNewLine(): this.type = {\n println()\n this\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}, {"source_code": "object Vk2016B extends App {\n val Array(n, d, h) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n def exit = println(-1)\n if(d > 2 * h) exit else {\n d - h match {\n case x if x > 0 =>\n if (n > d) {\n for (i <- 2 to h + 1) println(s\"${i - 1} $i\")\n println(s\"1 ${h + 2}\")\n for (i <- 2 to x) println(s\"${h + i} ${h + i + 1}\")\n for (i <- d + 2 to n) println(s\"1 $i\")\n } else exit\n case x if x == 0 =>\n if (h == 1 && n > 2) exit\n else {\n if (n > h) {\n for (i <- 2 to h + 1) println(s\"${i - 1} $i\")\n for (i <- h + 2 to n) println(s\"$h $i\")\n } else exit\n }\n case _ => exit\n }\n }\n}\n"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, d, h) = readInts(3)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val sb = new StringBuilder\n\n if (d >= h && d <= h * 2 && n >= d + 1 && (h != d || h > 1 || n == 2)) {\n var current = 1\n for (i <- 0 until h) {\n sb.append(s\"${current} ${current + 1}\\n\")\n current += 1\n }\n var prev = 1\n for (i <- 0 until d - h) {\n current += 1\n sb.append(s\"${prev} $current\\n\")\n prev = current\n }\n val start = if (h == d) 2 else 1\n while (current < n) {\n current += 1\n sb.append(s\"$start $current\\n\")\n }\n println(sb.result)\n } else println(-1)\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, d, h) = in.next().split(' ').map(_.toInt)\n if (d > 2 * h || n < d || (h == 1 && n > 1))\n println(-1)\n else {\n val height = (1 to h).map(i => s\"$i ${i + 1}\").toList\n val startDiameter = if (d != h) List(s\"1 ${h + 2}\") else Nil\n val diameter = (h + 2 to d).map(i => s\"$i ${i + 1}\").toList\n val left = (d + 2 to n).map(i => s\"2 $i\").toList\n println((height ::: startDiameter ::: diameter ::: left).mkString(\"\\n\"))\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, d, h) = in.next().split(' ').map(_.toInt)\n if (d > 2 * h || n < d || (h == 1 && n > 2))\n println(-1)\n else {\n val height = (1 to h).map(i => s\"$i ${i + 1}\").toList\n val startDiameter = if (d != h) List(s\"1 ${h + 2}\") else Nil\n val diameter = (h + 2 to d).map(i => s\"$i ${i + 1}\").toList\n val left = (d + 2 to n).map(i => s\"2 $i\").toList\n println((height ::: startDiameter ::: diameter ::: left).mkString(\"\\n\"))\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, d, h) = in.next().split(' ').map(_.toInt)\n if (d > 2 * h || n < d)\n println(-1)\n else {\n val height = (1 to h).map(i => s\"$i ${i + 1}\").toList\n val diameter = (1 to (d - h)).map(i => s\"$i ${i + h + 1}\").toList\n val left = (d + 2 to n).map(i => s\"1 $i\").toList\n println((height ::: diameter ::: left).mkString(\"\\n\"))\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, d, h) = in.next().split(' ').map(_.toInt)\n if (d > 2 * h || n < d)\n println(-1)\n else {\n val height = (1 to h).map(i => s\"$i ${i + 1}\").toList\n val startDiameter = if (d != h) List(s\"1 ${h + 2}\") else Nil\n val diameter = (h + 2 to d).map(i => s\"$i ${i + 1}\").toList\n val left = (d + 2 to n).map(i => s\"1 $i\").toList\n println((height ::: startDiameter ::: diameter ::: left).mkString(\"\\n\"))\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, d, h) = in.next().split(' ').map(_.toInt)\n if (d > 2 * h || n < d)\n println(-1)\n else {\n val height = (1 to h).map(i => s\"$i ${i + 1}\").toList\n val startDiameter = if (d != h) List(s\"1 ${h + 2}\") else Nil\n val diameter = (h + 2 to d).map(i => s\"$i ${i + 1}\").toList\n val left = (d + 2 to n).map(i => s\"2 $i\").toList\n println((height ::: startDiameter ::: diameter ::: left).mkString(\"\\n\"))\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, d, h) = in.next().split(' ').map(_.toInt)\n if (d > 2 * h || n < d)\n println(-1)\n else {\n val height = (1 to h).map(i => s\"$i ${i + 1}\").toList\n val startDiameter = if (d != h) List(s\"1 ${d - h + 1}\") else Nil\n val diameter = (d - h + 1 to d).map(i => s\"$i ${i + 1}\").toList\n val left = (d + 2 to n).map(i => s\"1 $i\").toList\n println((height ::: startDiameter ::: diameter ::: left).mkString(\"\\n\"))\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, d, h) = in.next().split(' ').map(_.toInt)\n if (d > 2 * h || n < d || (d == 1 && n > 2))\n println(-1)\n else {\n val height = (1 to h).map(i => s\"$i ${i + 1}\").toList\n val startDiameter = if (d != h) List(s\"1 ${h + 2}\") else Nil\n val diameter = (h + 2 to d).map(i => s\"$i ${i + 1}\").toList\n val left = (d + 2 to n).map(i => s\"2 $i\").toList\n println((height ::: startDiameter ::: diameter ::: left).mkString(\"\\n\"))\n }\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, d, h) = readInts(3)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val sb = new StringBuilder\n\n if (d >= h && d <= h * 2 && n >= d + 1 && (h != d || n - 1 == d)) {\n var current = 1\n for (i <- 0 until h) {\n sb.append(s\"${current} ${current + 1}\\n\")\n current += 1\n }\n var prev = 1\n for (i <- 0 until d - h) {\n current += 1\n sb.append(s\"${prev} $current\\n\")\n prev = current\n }\n while (current < n) {\n current += 1\n sb.append(s\"1 $current\\n\")\n }\n println(sb.result)\n } else println(-1)\n\n Console.flush\n}\n"}], "src_uid": "32096eff277f19d227bccca1b6afc458"} {"source_code": "import java.util.StringTokenizer\n\nimport scala.io.StdIn\n\nobject Main {\n object Scanner {\n private var st: StringTokenizer = _\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(StdIn.readLine())\n }\n st.nextToken()\n }\n\n def nextInt: Int = nextToken().toInt\n def nextLong: Long = nextToken().toLong\n def nextShort: Short = nextToken().toShort\n def nextByte: Byte = nextToken().toByte\n }\n\n def main(args: Array[String]): Unit = {\n for (_ <- 0 until Scanner.nextInt) {\n println(Scanner.nextLong + Scanner.nextLong + Scanner.nextLong - 1)\n }\n }\n}", "positive_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\n\nobject Task1 extends App {\n\n val linesCount = StdIn.readInt()\n\n val result = for (i <- 0 until linesCount) yield {\n val lineVals = StdIn.readLine().split(\" \").map(_.toInt).sorted\n (lineVals.max + 1).toString\n }\n\n result.foreach(println)\n\n\n}\n"}], "negative_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.io.Source\n\nobject Task1 extends App {\n\n val in = Source.stdin.getLines().toSeq\n val linesCount = in(0).toInt\n\n for (line <- in.drop(1)) {\n val lineVals = line.split(\" \").map(_.toInt).sorted\n print(lineVals.max + 1)\n }\n\n\n}\n"}], "src_uid": "40d679f53417ba058144c745e7a2c76d"} {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val sc = new InputReader(System.in)\n val T = sc.nextInt()\n rep(T) {_ =>\n val N = sc.nextInt()\n val s = sc.next()\n val l = s.take(N / 2)\n val r = s.drop(N / 2).reverse\n val ok = 0 until l.length forall { i =>\n val d = abs(l(i) - r(i))\n d == 0 || d == 2\n }\n out.println(if (ok) \"YES\" else \"NO\")\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {\n // todo Orderingだとboxing発生するので自作Orderを用意したい\n def maxByOpt[B: Ordering](f: A => B): Option[A] = {\n if (as.nonEmpty) Some(as.maxBy(f)) else None\n }\n\n def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {\n val map = mutable.Map.empty[K, ArrayBuffer[A]]\n rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))\n map\n }\n\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n var sum = num.zero\n rep(as.length)(i => sum = num.plus(sum, f(as(i))))\n sum\n }\n\n def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.lt)\n }\n\n def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {\n limit(f, ixRange)(cmp.gt)\n }\n\n private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {\n var limA = as(ixRange.head)\n var limB = f(limA)\n\n for (i <- ixRange.tail) {\n val a = as(i)\n val b = f(a)\n if (cmp(b, limB)) {\n limA = a\n limB = b\n }\n }\n (limA, limB)\n }\n }\n\n implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {\n def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {\n as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))\n }\n }\n}\n", "positive_code": [{"source_code": "object EDU49A extends App {\n import scala.io.StdIn\n val t = StdIn.readInt\n val inputs = (0 until t).map(_ => {\n StdIn.readLine\n StdIn.readLine\n }).toList\n\n def getNewLetters(char: Char): List[Char] = {\n return List(char+1, char-1).filter(c => c >= 'a' && c <= 'z').map(_.toChar)\n }\n\n for (input <- inputs) {\n val answer = input.take(input.length/2).zipWithIndex.forall {\n case (c: Char, i: Int) => {\n getNewLetters(c).toSet.intersect(getNewLetters(input(input.length - 1 - i)).toSet).nonEmpty\n }\n }\n\n println(if (answer) \"YES\" else \"NO\")\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject A extends App {\n\n def solve(in: InputReader): Unit = {\n val t = in.nextInt\n (1 to t) foreach { _ =>\n in.nextInt\n handle(in.next)\n }\n }\n\n def handle(s: String): Unit = {\n val lhs = s.take(s.length / 2)\n val rhs = s.drop(s.length / 2).reverse\n\n val result = lhs.zip(rhs).forall { case (l, r) =>\n val nl = neighbors(l)\n val rl = neighbors(r)\n nl.exists(rl.contains)\n }\n\n if (result) println(\"YES\") else println(\"NO\")\n }\n\n //97-122\n\n def neighbors(c: Char): Set[Char] = {\n Seq(c - 1, c + 1).filter(_ >= 97).filter(_ <= 122).map(_.toChar).toSet\n }\n\n solve(new InputReader(System.in))\n\n private class InputReader(val in: InputStream) {\n\n private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))\n private var tokenizer: StringTokenizer = _\n\n def nextInt: Int = {\n next.toInt\n }\n\n def next: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens) {\n tokenizer = new StringTokenizer(readLine)\n }\n tokenizer.nextToken\n }\n\n def readLine: String = {\n try {\n reader.readLine()\n } catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n }\n}\n"}, {"source_code": "object A extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n for (_ <- 1 to n) {\n val Array(l) = readInts(1)\n val s = readLine\n var ok = true\n for (i <- 0 until l / 2) {\n val d = Math.abs(s(i) - s(l - i - 1))\n if (d != 0 && d != 2) ok = false\n }\n println(if (ok) \"YES\" else \"NO\")\n }\n}\n"}], "negative_code": [], "src_uid": "cc4cdcd162a83189c7b31a68412f3fe7"} {"source_code": "\nobject PhoneNumbers extends App {\n\n var Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n var s = scala.io.StdIn.readLine()\n\n val letters = s.toCharArray.sorted.distinct.zipWithIndex.toMap\n val weights = s.toCharArray.sorted.distinct.zipWithIndex.map { case (letter, idx) => (idx, letter)}.toMap\n\n var smaller = s.take(k).toArray\n\n var i = k - 1\n\n if (smaller.length < k) {\n val diff = k - smaller.length\n println(smaller.mkString(\"\") + (weights(0).toString * diff))\n } else {\n while (i >= 0) {\n var current = smaller(i)\n var weight = letters(current)\n var nextWeight = weights.get(weight + 1)\n if (nextWeight.isDefined) {\n smaller(i) = nextWeight.get\n i = 0\n } else {\n smaller(i) = weights(0)\n }\n\n i -= 1\n }\n\n println(smaller.mkString(\"\"))\n }\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject C extends App {\n val INF = 1 << 30\n\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n def long() = st.nextToken().toLong\n\n read()\n val n = int()\n val k = int()\n val s = readLine()\n\n val chars = s.distinct.sorted.toIndexedSeq\n val last = chars.last\n\n if (k > n) {\n println(s + Array.fill(k-n)(chars(0)).mkString)\n } else {\n val t = s.take(k).toCharArray\n var i = k-1\n while (t(i) == last) {\n t(i) = chars.head\n i -= 1\n }\n t(i) = chars.iterator.find(_ > t(i)).get\n println(t.mkString)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\n/**\n * Solution of the problem: http://codeforces.com/contest/940/problem/C\n */\nobject cPhoneNumbers {\n\n def numbers(n: Int, k: Int, t: String):String = {\n\n val alpha = t.toCharArray.toSet.toList.sorted\n def getNext(c: Char, s: List[Char]): Option[Char] =\n s match {\n case Nil => None\n case x::y::_ if x == c => Some(y)\n case x::_ if x > c => None\n case _ => getNext(c, s.tail)\n }\n\n def replace(s: List[Char]):String =\n getNext(s.head, alpha) match {\n case None => replace(s.tail)\n case Some(x) => (x::s.tail).mkString\n }\n\n if (k > t.length) t ++ (for { _ <- 1 to k - t.length} yield alpha.head)\n else {\n val part = replace(t.substring(0, k).reverse.toCharArray.toList).reverse\n part ++ (for { _ <- 1 to k - part.length} yield alpha.head)\n }\n }\n\n def main(args: Array[String]):Unit = {\n val n::k::Nil = readLine().split(\" \").map(_.toInt).toList\n val t = readLine()\n println(numbers(n, k, t))\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\n/**\n * Solution of the problem: http://codeforces.com/contest/940/problem/C\n */\nobject cPhoneNumbers {\n\n def numbers(n: Int, k: Int, t: String):String = {\n\n val alpha = t.toCharArray.toSet.toList.sorted\n def getNext(c: Char, s: List[Char]): Option[Char] =\n s match {\n case Nil => None\n case x::y::_ if x == c => Some(y)\n case x::_ if x > c => None\n case _ => getNext(c, s.tail)\n }\n\n def replace(s: List[Char]):String =\n getNext(s.head, alpha) match {\n case None => replace(s.tail)\n case Some(x) => (x::s.tail).mkString\n }\n\n if (k > t.length) t ++ (for { _ <- 1 to k - t.length} yield alpha.head)\n else {\n val part = replace(t.reverse.toCharArray.toList).reverse\n part ++ (for { _ <- 1 to k - part.length} yield alpha.head)\n }\n }\n\n def main(args: Array[String]):Unit = {\n val n::k::Nil = readLine().split(\" \").map(_.toInt).toList\n val t = readLine()\n println(numbers(n, k, t))\n }\n}\n"}, {"source_code": "\nobject PhoneNumbers extends App {\n\n var Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n var s = scala.io.StdIn.readLine()\n\n val letters = s.toCharArray.sorted.distinct.zipWithIndex.toMap\n val weights = s.toCharArray.sorted.distinct.zipWithIndex.map { case (letter, idx) => (idx, letter)}.toMap\n\n var smaller = s.take(k).toArray\n\n var i = k - 1\n\n if (smaller.length < k) {\n val diff = k - smaller.length\n println(smaller.mkString(\"\") + (weights(0).toString * diff))\n } else {\n while (i >= 0) {\n var current = smaller(i)\n var weight = letters(current)\n var nextWeight = weights.get(weight + 1)\n if (nextWeight.isDefined) {\n smaller(i) = nextWeight.get\n } else {\n smaller(i) = weights(0)\n }\n\n i -= 1\n }\n\n println(smaller.mkString(\"\"))\n }\n}\n"}], "src_uid": "ea2dc6309e704d04cfdd6c79161c67f7"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C446A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C446A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val a = na(n)\n\n var trip = 0\n a.foreach { f =>\n trip = gcd(f, trip)\n }\n\n// out.println(trip)\n\n if(trip > 1) {\n out.println(-1)\n } else {\n val cnt = a.count(f => f == 1)\n if(cnt > 0) {\n out.println(n - cnt)\n } else {\n var mn = 100000\n REP(n) { i =>\n trip = 0\n var j = i\n while (j < n && trip != 1) {\n trip = gcd(a(j), trip)\n j += 1\n }\n if (trip == 1) {\n mn = Math.min(mn, (j - i - 1) + (n - 1))\n }\n }\n out.println(mn)\n }\n }\n\n }\n\n def gcd(a: Int, b: Int): Int = {\n if(b == 0) a\n else gcd(b, a % b)\n }\n}\n", "positive_code": [{"source_code": "\nimport java.io.FileReader\nimport java.util.Comparator\n\nimport collection.Searching._\nimport scala.collection.mutable\n\nobject Solution {\n //Console.setIn(new FileReader(new java.io.File(\"input\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n var caseNo = 1\n\n def doCase() : Unit = {\n val Array(n) = readIntLine()\n val nums = readIntLine()\n\n if (nums.map(BigInt(_)).reduce(_.gcd(_)) != 1) {\n println(-1)\n } else if (nums.contains(1)) {\n var reduced : List[Int] = List()\n reduced ::= nums.head\n for (n <- nums.tail) {\n if (reduced.head != 1 || n != 1) {\n reduced ::= n\n }\n }\n\n val idxs = reduced.zipWithIndex.filter(_._1 == 1).map(_._2)\n val points = (-1 :: idxs) :+ reduced.length\n\n println(points.sliding(2).map {case List(l, r) => r - l - 1}.sum)\n } else {\n println(subproblem(nums))\n }\n }\n\n def subproblem(nums : Array[Int]) : Int = {\n val precalc = Array.ofDim[Int](nums.length, nums.length)\n for (i <- nums.indices) {\n precalc(i)(i) = nums(i).intValue()\n for (j <- i + 1 until nums.length) {\n precalc(i)(j) = BigInt(precalc(i)(j - 1)).gcd(nums(j)).intValue()\n }\n }\n\n val pair = nums.indices.flatMap {\n i =>\n (i until nums.length).flatMap {\n j =>\n if (precalc(i)(j) == 1) {\n Some((j - i, (i, j)))\n } else {\n None\n }\n }\n }.minBy(_._1)\n pair._1 + nums.length - 1\n }\n\n def main(args: Array[String]) {\n var tests = 1\n for (test <- 0 until tests) {\n doCase()\n caseNo += 1\n }\n }\n\n def readIntLine(): Array[Int] = {\n readLine().split(\" \").map(_.toInt)\n }\n\n def readLongLine(): Array[Long] = {\n readLine().split(\" \").map(_.toLong)\n }\n\n def readBigIntLine(): Array[BigInt] = {\n readLine().split(\" \").map(BigInt.apply)\n }\n}"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C446A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C446A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val a = na(n)\n\n var trip = 0\n a.foreach { f =>\n trip = gcd(f, trip)\n }\n\n// out.println(trip)\n\n if(trip > 1) {\n out.println(-1)\n } else {\n val cnt = a.count(f => f == 1)\n if(cnt > 0) {\n out.println(n - cnt)\n } else {\n var mn = 2005\n REP(n) { i =>\n trip = 0\n var j = i\n while (j < n && trip != 1) {\n trip = gcd(a(j), trip)\n j += 1\n }\n if (trip == 1) {\n mn = Math.min(mn, (j - i - 1) + (n - 1))\n }\n }\n out.println(mn)\n }\n }\n\n }\n\n def gcd(a: Int, b: Int): Int = {\n if(b == 0) a\n else gcd(b, a % b)\n }\n}\n"}, {"source_code": "\nimport java.io.FileReader\nimport java.util.Comparator\n\nimport collection.Searching._\nimport scala.collection.mutable\n\nobject Solution {\n //Console.setIn(new FileReader(new java.io.File(\"input\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n var caseNo = 1\n\n def doCase() : Unit = {\n val Array(n) = readIntLine()\n val nums = readBigIntLine()\n\n if (nums.reduce(_.gcd(_)) != 1) {\n println(-1)\n } else {\n\n val precalc = Array.ofDim[Int](nums.length, nums.length)\n for (i <- nums.indices) {\n precalc(i)(i) = nums(i).intValue()\n for (j <- i + 1 until nums.length) {\n precalc(i)(j) = BigInt(precalc(i)(j - 1)).gcd(nums(j)).intValue()\n }\n }\n\n val pair = nums.indices.flatMap {\n i =>\n (i until nums.length).flatMap {\n j =>\n if (precalc(i)(j) == 1) {\n Some((j - i, (i, j)))\n } else {\n None\n }\n }\n }.minBy(_._1)\n println(pair._1 + nums.length - 1)\n }\n }\n\n def bfs(s1 : List[Array[BigInt]], s2 : List[Array[BigInt]], seen : mutable.HashSet[Array[BigInt]], count : Int) : Int = {\n s1 match {\n case Nil => bfs(s2, s1, seen, count + 1)\n case item :: rest =>\n if (seen contains item) {\n bfs(rest, s2, seen, count)\n }\n else if (item.toSet.size == 1) {\n count\n } else {\n seen.add(item)\n val neighbors = item.zipWithIndex.sliding(2).flatMap {\n case Array((l, li), (r, ri)) =>\n val gcd = l.gcd(r)\n var n : List[Array[BigInt]] = List()\n if (gcd != l) {\n val newA = Array.ofDim[BigInt](item.length)\n item.copyToArray(newA)\n newA(li) = gcd\n n ::= newA\n }\n if (gcd != r) {\n val newA = Array.ofDim[BigInt](item.length)\n item.copyToArray(newA)\n newA(ri) = gcd\n n ::= newA\n }\n n\n }.toList\n bfs(rest, neighbors ::: s2, seen, count)\n }\n }\n }\n\n def main(args: Array[String]) {\n var tests = 1\n for (test <- 0 until tests) {\n doCase()\n caseNo += 1\n }\n }\n\n def readIntLine(): Array[Int] = {\n readLine().split(\" \").map(_.toInt)\n }\n\n def readLongLine(): Array[Long] = {\n readLine().split(\" \").map(_.toLong)\n }\n\n def readBigIntLine(): Array[BigInt] = {\n readLine().split(\" \").map(BigInt.apply)\n }\n}"}], "src_uid": "c489061d9e8587d2e85cad0e2f23f3fb"} {"source_code": "object Program extends App{\n val input = Array(scala.io.StdIn.readLine(), scala.io.StdIn.readLine())\n val n = input.head.toInt\n val citizens = input.tail.head.split(\" \").map(x => x.toInt)\n val max = citizens.max\n val res = citizens.foldLeft(0)((x, y) => x + max - y)\n println(res)\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val max = a.max\n val ans = a.foldLeft(0)((sum, x) => sum + (max - x))\n println(ans)\n}"}, {"source_code": "\nobject MyApp extends App {\n val n = readLine().toInt\n val citizensWellfare = readLine().split(\" \").map(_.toInt)\n\n var max = 0\n var sum = 0\n for (i <- 0 until citizensWellfare.length) {\n val diff = max - citizensWellfare(i)\n if (diff < 0) {\n val increase = -diff\n sum += increase * i\n max = citizensWellfare(i)\n } else {\n sum += diff\n }\n }\n println(sum)\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val answer = in.next().split(' ').map(_.toInt)\n println(answer.max * n - answer.sum)\n}"}, {"source_code": "import scala.io.StdIn\n\nobject CF {\n def main(args: Array[String]):Unit = {\n val n = readInt()\n val lis = readLine().split(\"\\\\s+\").map(_.toInt)\n val v_max = lis.max\n val res = lis.map(x => v_max-x).sum\n println(res)\n }\n}\n"}, {"source_code": "object A758 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n).sorted\n val sum = in.sum\n val max = in.max\n println(max*n - sum)\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n // private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(\"src/input\")))\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _758A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val wealth = read[Vector[Int]]\n val m = wealth.max\n\n write(wealth.map(i => m - i).sum)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "/**\n * Created by yusaku on 17/06/14.\n */\n\nimport scala.io.StdIn.readLine\n\nobject App {\n def main(args: Array[String]): Unit = {\n readLine()\n val a = readLine().split(\" \").map(_.toInt)\n val m = a.max\n var answer = 0\n for (a_n <- a) {\n answer += (m - a_n)\n }\n\n print(answer)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by user on 23.01.2017.\n */\nobject Solution extends App {\n val stdIn0 = StdIn.readLine();\n val stdIn = StdIn.readLine();\n\n val arr = stdIn.split(\" \").map(_.toInt)\n print(arr.map(arr.max - _).sum)\n}\n"}, {"source_code": "\nimport scala.io.StdIn._\n\nobject Main extends App{\n readLine()\n val A = readLine().split(\" \").map(_.toInt)\n val max = A.max\n println(A.map(max - _).sum)\n}\n"}, {"source_code": "import java.util.Scanner\n\nimport scala.language.postfixOps\n\nobject TaskA extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt\n val as = 0 until n map (_ => sc.nextInt)\n println(as.max * n - as.sum)\n}\n"}], "negative_code": [], "src_uid": "a5d3c9ea1c9affb0359d81dae4ecd7c8"} {"source_code": "\n/**\n * Created by yangchaozhong on 3/10/15.\n */\nobject CF5A extends App {\n import scala.collection.mutable\n import java.util.{Scanner}\n import java.io.{PrintWriter}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n def nextLine = in.nextLine\n\n def solve = {\n\n val names = new mutable.HashSet[String]()\n\n var count = 0\n while (in.hasNext) {\n val s = nextLine\n if (s.startsWith(\"+\")) {\n names += s.substring(1)\n } else if (s.startsWith(\"-\")) {\n names -= s.substring(1)\n } else {\n val arr = s.split(\":\")\n if (arr.length > 1)\n count += s.split(\":\")(1).length * names.size\n }\n }\n\n out.println(count)\n }\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val res = in.foldLeft((0, 0)) {\n case((count, set), el) if el.head == '+' => (count, set + 1)\n case((count, set), el) if el.head == '-' => (count, set - 1)\n case((count, set), el) => (count + set * (el.length - el.indexOf(':') - 1), set)\n }\n println(res._1)\n}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\n\nobject AChatTraffic extends App {\n\n val scanner = new Scanner(System.in)\n\n val input = ArrayBuffer.empty[String]\n\n while (scanner.hasNext) {\n// (0 until 4) foreach { i =>\n input += scanner.nextLine()\n }\n\n var visitors = 0\n var result = 0\n\n input foreach {\n case s if s.contains('+') =>\n visitors += 1\n case s if s.contains('-') =>\n visitors -= 1\n case s if s.contains(':') =>\n val sp = s.split(\"\"\"\\:\"\"\", -1)(1)\n result += sp.length * visitors\n }\n\n println(result)\n\n}\n"}, {"source_code": "object A5 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n var curr = 0\n var res = 0L\n var in = read\n while(in != null) {\n if(in.startsWith(\"+\"))\n curr += 1\n else if (in.startsWith(\"-\"))\n curr -= 1\n else\n util.Try{in.split(':')(1)}.map(_.length).foreach(a => res += curr * a)\n in = read\n }\n println(res)\n }\n\n object IO {\n val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n var users = 0\n var sum = 0\n for(line <- scala.io.Source.stdin.getLines()) {\n if (line.startsWith(\"+\")) users += 1\n else if (line.startsWith(\"-\")) users -= 1\n else sum += line.split(\":\").tail.headOption.map(_.size).getOrElse(0) * users\n }\n println(sum)\n }\n}"}, {"source_code": "object P5A {\n def main(args: Array[String]) {\n val (add, remove, send) = (\"\\\\+.*\".r, \"-.*\".r, \".*:(.*)\".r)\n var p = 0\n var answer = 0\n while (true) readLine match {\n case add() => p = p + 1\n case remove() => p = p - 1\n case send(s) => answer = answer + p * s.size\n case _ => {println(answer); return}\n }\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val res = in.foldLeft((0, Set.empty[String])) {\n case((count, set), el) if el.head == '+' => (count, set + el.tail)\n case((count, set), el) if el.head == '-' => (count, set - el.tail)\n case((count, set), el) => (count + set.size * el.split(':').last.trim.length, set)\n }\n println(res._1)\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val res = in.foldLeft((0, Set.empty[String])) {\n case((count, set), el) if el.head == '+' => (count, set + el.tail)\n case((count, set), el) if el.head == '-' => (count, set - el.tail)\n case((count, set), el) => (count + set.size * el.split(':').last.length, set)\n }\n println(res._1)\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n println(in.hasNext)\n while (in.hasNext)\n println(in.next())\n println(\"stop\")\n println(in.size)\n val res = in.foldLeft((0, Set.empty[String])) {\n case((count, set), el) if el.head == '+' => (count, set + el.tail)\n case((count, set), el) if el.head == '-' => (count, set - el.tail)\n case((count, set), el) => (count + set.size, set)\n }\n println(res._1)\n}"}], "src_uid": "d7fe15a027750c004e4f50175e1e20d2"} {"source_code": "import scala.io._\nimport java.util.StringTokenizer\nimport java.io.BufferedReader\n\nobject Main {\n \n def printList[A](ls: List[A]) = {\n print(ls.size);\n for (x <- ls) print( \" \" + x )\n println\n }\n\n def main(args: Array[String]): Unit = {\n var (nums, zeros) = nextSeq(nextInt).toList partition (_ != 0)\n var (neg, pos) = nums partition (_ < 0)\n \n if (pos.isEmpty) {\n pos = neg.take(2)\n neg = neg.drop(2)\n } \n if (neg.size % 2 == 0) {\n zeros = neg.head :: zeros\n neg = neg.tail\n }\n printList(neg)\n printList(pos)\n printList(zeros)\n } \n \n class Tokenizer(in: BufferedReader, splitOn: String = \" \\n\\t\\r\\f\")\n {\n private var tokenizer = new StringTokenizer(\"\")\n def readLine() = in.readLine() \n def nextToken(): String = {\n while (!tokenizer.hasMoreTokens) {\n val line = readLine\n if (line == null) return null\n tokenizer = new StringTokenizer(line, splitOn)\n }\n tokenizer.nextToken\n } \n def next[A](f: String => A) = f(nextToken)\n def nextSeq[A](f: () => A, count: Int) = (for (i <- 0 until count) yield f())\n }\n \n implicit val tokenizer = new Tokenizer(Console.in)\n \n def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)\n def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)\n def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)\n def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))\n def nextSeq[A](f: () => A, count: Int = nextInt())(implicit t: Tokenizer) =\n (for (i <- 0 until count) yield f())\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject A {\n\n def pr(a:List[Int]) = {\n print(a.length)\n a.foreach(x => print(\" \"+x))\n println\n }\n def main(args: Array[String]): Unit = {\n var scan = new Scanner(System.in)\n val n = scan.nextInt\n val L = List.fill(n)(scan.nextInt)\n var a:List[Int] = Nil\n var b:List[Int] = Nil\n var c:List[Int] = Nil\n var pos = L.count(_>0)\n for(x <-L ) {\n if (x<0 && a.isEmpty) a = x::a\n else if (x>0 || (x<0 && pos==0 && b.length<2))b=x::b\n else c = x::c\n \n }\n pr(a);pr(b);pr(c)\n\n }\n\n}"}, {"source_code": "object A {\n def READ: Array[Int] = readLine() split (\" \") map (_.toInt);\n\n def main(args: Array[String]) {\n var Array(n) = READ\n var a = READ\n\n var s1 = a filter(_ > 0)\n var s2 = a filter(_< 0)\n var s3 = a filter(_ == 0)\n if (s1.size == 0) {\n s1 = s2.slice(0, 2);\n s2 = s2.slice(2, s2.size);\n }\n if (s2.size%2 == 0) {\n s3 = s3 :+ s2(0);\n s2 = s2.slice(1, s2.size);\n }\n println(s2.size + \" \" + s2.mkString(\" \"));\n println(s1.size + \" \" + s1.mkString(\" \"));\n println(s3.size + \" \" + s3.mkString(\" \"));\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt\n val a = readLine().split(\" \").map(_.toInt)\n val neg = a.filter(_ < 0) \n val pos = a.filter(_ > 0)\n val zero = a.filter(_ == 0)\n \n if (pos.size == 0) {\n if (neg.size % 2 == 0) {\n println( neg.size - 3 + \" \" + neg.drop(3).mkString(\" \"))\n println( \"2 \" + neg.take(2).mkString(\" \"))\n println( (1 + zero.size) + \" \" + (neg.drop(2).take(1) ++ zero).mkString(\" \"))\n } else {\n println( neg.size - 2 + \" \" + neg.drop(2).mkString(\" \"))\n println( \"2 \" + neg.take(2).mkString(\" \"))\n println( zero.size + \" \" + zero.mkString(\" \"))\n }\n } else {\n if (neg.size % 2 == 0) {\n println( neg.size - 1 + \" \" + neg.drop(1).mkString(\" \"))\n println( pos.size + \" \" + pos.mkString(\" \"))\n println( (1 + zero.size) + \" \" + (neg.take(1) ++ zero).mkString(\" \"))\n } else {\n println( neg.size + \" \" + neg.mkString(\" \"))\n println( pos.size + \" \" + pos.mkString(\" \"))\n println( zero.size + \" \" + zero.mkString(\" \"))\n }\n } \n }\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nobject A extends App {\n val n = readLine.toInt\n val a = for(s <- readLine.split(\" \")) yield s.toInt\n val t0 = (for(i <- a if i < 0) yield i).toBuffer\n val t1 = (for(i <- a if i > 0) yield i).toBuffer\n val t2 = (for(i <- a if i == 0) yield i).toBuffer\n if(t1.size == 0) {\n for(i <- 1 to 2) {\n t1 += t0(0)\n t0 -= t0(0)\n }\n }\n if(t0.size % 2 == 0) {\n t2 += t0(0)\n t0 -= t0(0)\n }\n print(t0.size)\n for(i <- t0) print(\" \"+i)\n println\n print(t1.size)\n for(i <- t1) print(\" \"+i)\n println\n print(t2.size)\n for(i <- t2) print(\" \"+i)\n println\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _300A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt).toArray\n var pos = a.filter(i => i > 0)\n var neg = a.filter(i => i < 0)\n var zero = a.filter(i => i == 0)\n\n if (pos.size == 0) {\n pos = neg.take(2)\n neg = neg.drop(2)\n }\n if (neg.size > 1) {\n zero = zero ++ neg.drop(1)\n neg = neg.take(1)\n }\n\n println(neg.size + \" \" + neg.mkString(\" \"))\n println(pos.size + \" \" + pos.mkString(\" \"))\n println(zero.size + \" \" + zero.mkString(\" \"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val posCount = data.count(_ > 0)\n val ans = data.foldLeft((List.empty[Int], List.empty[Int], List.empty[Int])) {\n case((f, s, t), el) if el < 0 && f.isEmpty => (el :: f, s, t)\n case((f, s, t), el) if (s.isEmpty && el > 0) || (el != 0 && s.size < 2 && posCount == 0) => (f, el :: s, t)\n case((f, s, t), el) => (f, s, el :: t)\n }\n println(ans._1.size + \" \" + ans._1.mkString(\" \"))\n println(ans._2.size + \" \" + ans._2.mkString(\" \"))\n println(ans._3.size + \" \" + ans._3.mkString(\" \"))\n}"}, {"source_code": "import scala.collection.JavaConversions._\nimport scala.collection.mutable._\n\n\nobject Codeforces300A {\n def main(args: Array[String]) {\n var ps = Set[Int]()\n var ns = Set[Int]()\n var zs = Set[Int]()\n val n = scala.io.StdIn.readLine().toInt\n val ar = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n for (i <- 0 until n) {\n if (ar(i) == 0)\n zs.add(ar(i))\n if (ar(i) > 0)\n ps.add(ar(i))\n if (ar(i) < 0)\n ns.add(ar(i))\n }\n\n if (ns.size % 2 == 0) {\n val t = ns.take(1)\n zs = zs.union(t)\n ns = ns.diff(t)\n }\n\n if (ps.size == 0) {\n val t = ns.take(2)\n ps = ps.union(t)\n ns = ns.diff(t)\n }\n\n val s1 = ns.mkString(\" \")\n val s2 = ps.mkString(\" \")\n val s3 = zs.mkString(\" \")\n println(s\"${ns.size} ${s1}\")\n println(s\"${ps.size} ${s2}\")\n println(s\"${zs.size} ${s3}\")\n }\n}"}, {"source_code": "object A300 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val a = readInts(n)\n\n val neg = a.filter(_ < 0)\n val pos = a.filter(_ > 0)\n val zero = a.filter(_ == 0)\n\n if(neg.nonEmpty && zero.nonEmpty) {\n if(pos.nonEmpty) {\n solve(neg.take(1), pos, zero ++ neg.takeRight(neg.length-1))\n } else {\n solve(neg.take(1), neg.slice(1,3), zero ++ neg.takeRight(neg.length-3))\n }\n }\n }\n\n def solve(neg: Array[Int], pos: Array[Int], zero: Array[Int]): Unit = {\n println(s\"${neg.length} ${neg.mkString(\" \")}\")\n println(s\"${pos.length} ${pos.mkString(\" \")}\")\n println(s\"${zero.length} ${zero.mkString(\" \")}\")\n }\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P300A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val A = List.fill(N)(sc.nextInt).sortWith(_ < _)\n\n def solve(): Unit = {\n val (neg, zeroPos) = A span (_ < 0)\n val pos = zeroPos.tail\n\n neg match {\n case x :: Nil => {\n out.println(s\"1 $x\")\n out.println(s\"1 ${pos.head}\")\n val rest = 0 :: pos.tail\n out.println((rest.size :: rest).mkString(\" \"))\n }\n case x :: y :: z :: rest => {\n out.println(s\"1 $x\")\n out.println(s\"2 $y $z\")\n val other = rest ::: zeroPos\n out.println((other.size :: other).mkString(\" \"))\n }\n case x :: y :: rest => {\n out.println(s\"1 $x\")\n out.println(s\"1 ${pos.head}\")\n val rest = y :: 0 :: pos.tail\n out.println((rest.size :: rest).mkString(\" \"))\n }\n }\n }\n\n solve\n out.close\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\nobject A extends App {\n val n = readLine.toInt\n val a = for(s <- readLine.split(\" \")) yield s.toInt\n val t0 = (for(i <- a if i < 0) yield i).toBuffer\n val t1 = (for(i <- a if i > 0) yield i).toBuffer\n val t2 = (for(i <- a if i == 0) yield i).toBuffer\n if(t1.size == 0) {\n for(i <- 1 to 2) {\n t1 += t0(0)\n t0 -= t0(0)\n println(t1)\n }\n }\n print(t0.size)\n for(i <- t0) print(\" \"+i)\n println\n print(t1.size)\n for(i <- t1) print(\" \"+i)\n println\n print(t2.size)\n for(i <- t2) print(\" \"+i)\n println\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nobject A extends App {\n val n = readLine.toInt\n val a = for(s <- readLine.split(\" \")) yield s.toInt\n val t0 = (for(i <- a if i < 0) yield i).toBuffer\n val t1 = (for(i <- a if i > 0) yield i).toBuffer\n val t2 = (for(i <- a if i == 0) yield i).toBuffer\n if(t1.size == 0) {\n for(i <- 1 to 2) {\n t1 += t0(0)\n t0 -= t0(0)\n }\n }\n print(t0.size)\n for(i <- t0) print(\" \"+i)\n println\n print(t1.size)\n for(i <- t1) print(\" \"+i)\n println\n print(t2.size)\n for(i <- t2) print(\" \"+i)\n println\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _300A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt).toArray\n var pos = a.filter(i => i > 0)\n var neg = a.filter(i => i < 0)\n var zero = a.filter(i => i == 0)\n\n if (pos.size == 0) {\n pos = neg.take(2)\n neg = neg.drop(2)\n }\n if (neg.size > 1) {\n zero = neg.drop(1)\n neg = neg.take(1)\n }\n\n println(neg.size + \" \" + neg.mkString(\" \"))\n println(pos.size + \" \" + pos.mkString(\" \"))\n println(zero.size + \" \" + zero.mkString(\" \"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt).foldLeft((List.empty[Int], List.empty[Int], List.empty[Int])) {\n case((f, s, t), el) if el < 0 && f.isEmpty => (el :: f, s, t)\n case((f, s, t), el) if el == 0 => (f, s, el :: t)\n case((f, s, t), el) => (f, el :: s, t)\n }\n println(data._1.size + \" \" + data._1.mkString(\" \"))\n println(data._2.size + \" \" + data._2.mkString(\" \"))\n println(data._3.size + \" \" + data._3.mkString(\" \"))\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val posCount = data.count(_ > 0)\n val ans = data.foldLeft((List.empty[Int], List.empty[Int], List.empty[Int])) {\n case((f, s, t), el) if el < 0 && f.isEmpty => (el :: f, s, t)\n case((f, s, t), el) if (s.isEmpty && el > 0) || (s.size < 2 && posCount == 0) => (f, el :: s, t)\n case((f, s, t), el) => (f, s, el :: t)\n }\n println(ans._1.size + \" \" + ans._1.mkString(\" \"))\n println(ans._2.size + \" \" + ans._2.mkString(\" \"))\n println(ans._3.size + \" \" + ans._3.mkString(\" \"))\n}"}, {"source_code": "import scala.io._\nimport java.util.StringTokenizer\nimport java.io.BufferedReader\n\nobject Main {\n \n def printList[A](ls: List[A]) = {\n print(ls.size);\n for (x <- ls) print( \" \" + x )\n println\n }\n\n def main(args: Array[String]): Unit = {\n var (nums, zeros) = nextSeq(nextInt).toList partition (_ != 0)\n var (neg, pos) = nums partition (_ < 0) \n if (neg.size % 2 == 0) {\n zeros = neg.head :: zeros\n neg = neg.tail\n }\n printList(neg)\n printList(pos)\n printList(zeros)\n } \n \n class Tokenizer(in: BufferedReader, splitOn: String = \" \\n\\t\\r\\f\")\n {\n private var tokenizer = new StringTokenizer(\"\")\n def readLine() = in.readLine() \n def nextToken(): String = {\n while (!tokenizer.hasMoreTokens) {\n val line = readLine\n if (line == null) return null\n tokenizer = new StringTokenizer(line, splitOn)\n }\n tokenizer.nextToken\n } \n def next[A](f: String => A) = f(nextToken)\n def nextSeq[A](f: () => A, count: Int) = (for (i <- 0 until count) yield f())\n }\n \n implicit val tokenizer = new Tokenizer(Console.in)\n \n def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)\n def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)\n def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)\n def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))\n def nextSeq[A](f: () => A, count: Int = nextInt())(implicit t: Tokenizer) =\n (for (i <- 0 until count) yield f())\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P300A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val A = List.fill(N)(sc.nextInt).sortWith(_ < _)\n\n def solve(): Unit = {\n val (neg, zeroPos) = A span (_ < 0)\n val pos = zeroPos.tail\n\n neg match {\n case x :: Nil => {\n out.println(s\"1 $x\")\n out.println(s\"1 ${pos.head}\")\n val rest = 0 :: pos.tail\n out.println((rest.size :: rest).mkString(\" \"))\n }\n case x :: y :: z :: rest => {\n out.println(s\"1 $x\")\n out.println(s\"1 $y $z\")\n val other = rest ::: zeroPos\n out.println((other.size :: other).mkString(\" \"))\n }\n case x :: y :: rest => {\n out.println(s\"1 $x\")\n out.println(s\"1 ${pos.head}\")\n val rest = y :: 0 :: pos.tail\n out.println((rest.size :: rest).mkString(\" \"))\n }\n }\n }\n\n solve\n out.close\n}\n"}, {"source_code": "object A {\n def READ: Array[Int] = readLine() split (\" \") map (_.toInt);\n\n def main(args: Array[String]) {\n var Array(n) = READ\n var a = READ\n\n var s1 = a filter(_ > 0)\n var s2 = a filter(_< 0)\n var s3 = a filter(_ == 0)\n if (s1.size == 0) {\n s1 = s2.slice(0, 2);\n s2 = s2.slice(2, s2.size);\n }\n if (s2.size%2 == 0) {\n s3 = s3 :+ s2(0);\n s2 = s2.slice(1, s2.size);\n }\n println(s1.size + \" \" + s1.mkString(\" \"));\n println(s2.size + \" \" + s2.mkString(\" \"));\n println(s3.size + \" \" + s3.mkString(\" \"));\n\n }\n}\n"}], "src_uid": "03cf2cc26c84aab685ee78a1d6318b30"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println((1 to n).foldLeft((0, 0)) {\n case((h, timeSoFar), i) =>\n val h1 = in.next().toInt\n (h1, timeSoFar + Math.abs(h - h1))\n }._2 + n - 1 + n)\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P265B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Long = {\n val N = sc.nextInt\n val H = List.fill(N)(sc.nextLong)\n\n @tailrec\n def loop(acc: Long, pos: Long, ts: List[Long]): Long = ts match {\n case Nil => acc + 2 * N - 1\n case x :: xs => loop(acc + (pos - x).abs, x, xs)\n }\n\n loop(0L, 0L, H)\n }\n\n out.println(solve)\n out.close\n}\n\n\n\n\n\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val n = readInt\n val trees = for(_ <- 1 to n) yield readInt\n val ans = trees.sliding(2).map(x => (x.last - x.head).abs).sum + n - 1 + n + trees.head\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val n = readInt\n val a = (1 to n).map(_ => readInt())\n \n var h0 = a(0)\n var step = a(0) + 1\n \n a.drop(1).foreach{ h =>\n if (h0 > h) step += h0 - h + 2 \n else step += h - h0 + 2\n h0 = h\n } \n \n println(step)\n }\n}"}, {"source_code": "object CF265B extends App {\n\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve = {\n var n = nextInt\n var h = (for (i <- 0 until n) yield nextInt).toArray\n\n var c = 0\n var t = -1\n for (i <- 0 until n) {\n t += math.abs(h(i) - c) + 2;\n c = h(i)\n }\n\n out.println(t)\n }\n\n try { \n solve \n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n out.close\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println((1 to n).foldLeft((1, 0)) {\n case((h, timeSoFar), i) =>\n val h1 = in.next().toInt\n (h1, timeSoFar + Math.abs(h - h1))\n }._2 + n - 1)\n}\n"}], "src_uid": "a20ca4b053ba71f6b2dc05749287e0a4"} {"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k, p) = readInts(3)\n\n val as = readInts(n).sorted\n val bs = readInts(k).sorted\n\n var min = Int.MaxValue\n\n for (offset <- 0 to k - n) {\n\n var max = 0\n var i = 0\n while (i < as.length) {\n\n val a = as(i)\n val b = bs(offset + i)\n\n val len = if (a <= p) {\n if (a > b) {\n (p - b) + (a - b) //bap\n } else {\n if (b > p) {\n b - a + b - p // apb\n } else {\n p - a // abp\n }\n }\n } else {\n if (a < b) {\n (b - a) + (b - p)//pab\n } else {\n if (b < p) {\n a - b + p - b //bpa\n } else {\n a - p //pba\n }\n }\n }\n if (len > max) max = len\n //println(offset, i, as(i), bs(j), len, max)\n i += 1\n }\n\n if (max < min) min = max\n }\n\n println(min)\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject A830 {\n def main(args: Array[String]) = {\n val Array(n, k, p) = StdIn.readLine().split(\" \").map(_.toLong)\n val a = StdIn.readLine().split(\" \").map(_.toLong).sorted\n val b = StdIn.readLine().split(\" \").map(_.toLong).sorted\n\n def intervalByT(start: Long, t: Long): Option[Tuple2[Long, Long]] = start match {\n case _ if ((start - p).abs > t) => None\n case start if (start < p) => {\n val dist = (t - (p - start)) / 2\n Some((start - dist, p + dist))\n }\n case start if (start >= p) => {\n val dist = (t - (start - p)) / 2\n Some((p - dist, start + dist))\n }\n }\n\n def greedy(segments: Array[Tuple2[Long, Long]]): Boolean = {\n var j = 0\n for (i <- 0 until segments.length) {\n while (j < b.length && segments(i)._1 > b(j))\n j += 1\n if (j == b.length || segments(i)._2 < b(j))\n return false\n j += 1\n }\n return true\n }\n\n def binarySearch(left: Long, right: Long): Option[Long] = {\n if (right < left)\n return None\n val med = (left + right) / 2\n val res = a.map(intervalByT(_, med))\n if (res.forall(_.isDefined))\n med match {\n case med if (greedy(res.flatten.sorted)) =>\n binarySearch(left, med - 1) match {\n case None => Some(med)\n case some => Some(some.get) \n }\n case med => binarySearch(med + 1, right)\n }\n else\n binarySearch(med + 1, right)\n }\n\n println(binarySearch(0, 2 * 1000 * 1000 * 1000).get)\n }\n}\n"}], "negative_code": [{"source_code": "object D extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k, p) = readInts(3)\n\n val as = readInts(n).sorted\n val bs = readInts(k).sorted\n\n var min = Int.MaxValue\n\n for (offset <- 0 until k - n) {\n\n var max = 0\n var i = 0\n while (i < as.length) {\n\n val a = as(i)\n val b = bs(offset + i)\n\n val len = if (a <= p) {\n if (a > b) {\n (p - b) + (a - b) //bap\n } else {\n if (b > p) {\n b - a + b - p // apb\n } else {\n p - a // abp\n }\n }\n } else {\n if (a < b) {\n (b - a) + (b - p)//pab\n } else {\n if (b < p) {\n a - b + p - b //bpa\n } else {\n a - p //pba\n }\n }\n }\n if (len > max) max = len\n //println(offset, i, as(i), bs(j), len, max)\n i += 1\n }\n\n if (max < min) min = max\n }\n\n println(min)\n}\n"}], "src_uid": "c045163f2539a117c5160eaedc2dab3e"} {"source_code": "object B1004 extends App {\n case class LR(l: Int, r: Int) {\n def length = r - l\n }\n\n def read: Array[Int] = readLine.split(\" \").map(_.toInt)\n\n val (n, m) = {\n val arr = read\n (arr(0), arr(1))\n }\n\n val result = {\n val arr = new Array[Int](n)\n (0 to n - 1).foreach { i => arr(i) = i % 2 }\n arr\n }\n\n result foreach print\n}", "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Solution extends App {\n val array1 = StdIn.readLine().split(\" \").map(_.toInt)\n var n = array1(0)\n var m = array1(1)\n var answer = Array.ofDim[Int](n)\n\n var tree = mutable.SortedMap.empty[Int, mutable.HashSet[Tuple2[Int, Int]]]\n\n for (i <- 0 until m) {\n val d = StdIn.readLine().split(\" \").map(_.toInt)\n val k = d(1) - d(0)\n val set = tree.getOrElse(k, mutable.HashSet.empty[Tuple2[Int, Int]])\n set.add(d(0) - 1 -> (d(1) - 1))\n tree.put(k, set)\n }\n\n var l = 0\n answer.map({el =>\n l = l + 1\n if (l % 2 == 0) 0 else 1\n }).foreach(print)\n /*if (n != 1) {\n\n var last = 0\n tree.foreach({ case (d, t1) =>\n t1.foreach({ t =>\n var i = t._1\n while (i <= t._2) {\n if (answer(i) == 0) {\n if (last % 2 == 0) answer(i) = 1; else answer(i) = 2\n last = last + 1\n }\n i = i + 1\n }\n })\n })\n answer.map(_ % 2).foreach(print)\n } else {\n println(0)\n }*/\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Solution extends App {\n val array1 = StdIn.readLine().split(\" \").map(_.toInt)\n var n = array1(0)\n var m = array1(1)\n var answer = Array.ofDim[Int](n)\n\n var tree = mutable.SortedMap.empty[Int, mutable.HashSet[Tuple2[Int, Int]]]\n\n for (i <- 0 until m) {\n val d = StdIn.readLine().split(\" \").map(_.toInt)\n val k = d(1) - d(0)\n val set = tree.getOrElse(k, mutable.HashSet.empty[Tuple2[Int, Int]])\n set.add(d(0) - 1 -> (d(1) - 1))\n tree.put(k, set)\n }\n\n if (n != 1) {\n\n var last = 0\n tree.foreach({ case (d, t1) =>\n t1.foreach({ t =>\n var i = t._1\n while (i <= t._2) {\n if (answer(i) == 0) {\n if (last % 2 == 0) answer(i) = 1; else answer(i) = 2\n last = last + 1\n }\n i = i + 1\n }\n })\n })\n answer.map(_ % 2).foreach(print)\n } else {\n println(0)\n }\n}"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Solution extends App {\n val array1 = StdIn.readLine().split(\" \").map(_.toInt)\n var n = array1(0)\n var m = array1(1)\n var answer = Array.ofDim[Int](n)\n\n var tree = mutable.SortedMap.empty[Int,Tuple2[Int,Int]]\n\n for (i <- 0 until m) {\n val d = StdIn.readLine().split(\" \").map(_.toInt)\n tree.put(d(1) - d(0), d(0) - 1 -> (d(1) - 1))\n }\n\n if (n != 1) {\n\n var last = 0\n tree.foreach({ case (d, t) =>\n var i = t._1\n while (i <= t._2) {\n if (answer(i) == 0) {\n if (last % 2 == 0) answer(i) = 1; else answer(i) = 2\n last = last + 1\n }\n i = i + 1\n }\n })\n answer.map(_ % 2).foreach(print)\n } else\n {\n println(0)\n }\n}"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Solution extends App {\n val array1 = StdIn.readLine().split(\" \").map(_.toInt)\n var n = array1(0)\n var m = array1(1)\n var answer = Array.ofDim[Int](n)\n\n var tree = mutable.SortedMap.empty[Int,Tuple2[Int,Int]]\n\n for (i <- 0 until m) {\n val d = StdIn.readLine().split(\" \").map(_.toInt)\n tree.put(d(1) - d(0), d(0) - 1 -> (d(1) - 1))\n }\n\n if (n != 1) {\n\n var last = 0\n tree.foreach({ case (d, t) =>\n var i = t._1\n while (i <= t._2) {\n if (answer(i) == 0) {\n if (last % 2 == 0) answer(i) = 1; else answer(i) = 2\n last = last + 1\n }\n i = i + 1\n }\n })\n answer.map(_ % 2).foreach(println)\n } else\n {\n println(0)\n }\n}\n"}, {"source_code": "object B1004 extends App {\n case class LR(l: Int, r: Int) {\n def length = r - l\n }\n\n def read: Array[Int] = readLine.split(\" \").map(_.toInt)\n\n val (n, m) = {\n val arr = read\n (arr(0), arr(1))\n }\n\n val memo = {\n val arr = new Array[Boolean](n)\n (0 to n - 1).foreach { i => arr(i) = false }\n arr\n }\n\n val result = {\n val arr = new Array[Int](n)\n (0 to n - 1).foreach { i => arr(i) = 0 }\n arr\n }\n\n val flowers = \n (0 to m - 1)\n .map { _ =>\n val arr = read\n LR(arr(0), arr(1))\n }\n .sortWith(_.length > _.length)\n .foreach { interval =>\n val pendingDecision = (interval.l to interval.r).filter( i => !memo(i - 1))\n pendingDecision.zipWithIndex.foreach { case (v, i) =>\n result(v - 1) = i % 2\n memo(v - 1) = true\n }\n }\n\n result foreach print\n}"}, {"source_code": "object B1004 extends App {\n case class LR(l: Int, r: Int) {\n def length = r - l\n }\n\n def read: Array[Int] = readLine.split(\" \").map(_.toInt)\n\n val (n, m) = {\n val arr = read\n (arr(0), arr(1))\n }\n\n val memo = {\n val arr = new Array[Boolean](n)\n (0 to n - 1).foreach { i => arr(i) = false }\n arr\n }\n\n val result = {\n val arr = new Array[Int](n)\n (0 to n - 1).foreach { i => arr(i) = 0 }\n arr\n }\n\n val flowers = \n (0 to m - 1)\n .map { _ =>\n val arr = read\n LR(arr(0), arr(1))\n }\n .sortWith((x, y) => x.length > y.length || (x.length == y.length && x.l < y.l))\n .foreach { interval =>\n val pendingDecision = (interval.l to interval.r).filter( i => !memo(i - 1))\n pendingDecision.zipWithIndex.foreach { case (v, i) =>\n result(v - 1) = i % 2\n memo(v - 1) = true\n }\n }\n\n result foreach print\n}"}, {"source_code": "object B1004 extends App {\n case class LR(l: Int, r: Int) {\n def length = r - l\n }\n\n def read: Array[Int] = readLine.split(\" \").map(_.toInt)\n\n val (n, m) = {\n val arr = read\n (arr(0), arr(1))\n }\n\n val memo = {\n val arr = new Array[Boolean](n)\n (0 to n - 1).foreach { i => arr(i) = false }\n arr\n }\n\n val result = {\n val arr = new Array[Int](n)\n (0 to n - 1).foreach { i => arr(i) = 0 }\n arr\n }\n\n val flowers = \n (0 to m - 1)\n .map { _ =>\n val arr = read\n LR(arr(0), arr(1))\n }\n .sortWith(_.length > _.length)\n .foreach { interval =>\n val pendingDecision = (interval.l to interval.r).filter( i => !memo(i - 1))\n pendingDecision.zipWithIndex.foreach { case (v, i) =>\n result(v - 1) = i % 2\n memo(v - 1) = true\n }\n }\n\n println(result.toList.mkString(\"\"))\n}"}], "src_uid": "cac8ca5565e06021a44bb4388b5913a5"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val k, x = nl()\n val ans = (k - 1) * 9 + x\n out.println(ans)\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object Main {\n \n def main(args: Array[String]) {\n \n val std = scala.io.StdIn\n val n = std.readLine().toInt\n for (_ <- 0 until n) {\n val values = std.readLine().split(\" \")\n val k = values(0).toLong\n val x = values(1).toLong\n println(x + (k-1) * 9 )\n \n }\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val k, x = nl()\n out.println(x)\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "891fabbb6ee8a4969b6f413120f672a8"} {"source_code": "object B670 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n var Array(n, k) = readInts(2)\n val id = readInts(n)\n var i = 1\n while(k > 0) {\n if(k <= i) {\n println(id(k-1))\n }\n k -= i\n i += 1\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "\nimport java.io.InputStreamReader\nimport java.io.BufferedReader\n\n/**\n * @author pvasilyev\n * @since 16 Jun 2016\n */\nobject B670 extends App {\n\n def solve() = {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val Array(n, k): Array[Long] = reader.readLine().split(\" \").map(_.toLong)\n val ids: Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n var solution: Long = 0L\n var minorIndex: Int = 0\n if (hasExactSquareRoot(8 * k + 1)) {\n val determinant: Long = Math.round(Math.sqrt(8 * k + 1))\n solution = (determinant - 1) / 2\n } else {\n val determinant: Double = Math.sqrt(1L + 8 * k)\n solution = Math.floor((determinant - 1) / 2).toInt\n }\n val sum = (solution * (solution + 1)) / 2\n if (sum == k) {\n minorIndex = (solution - 1).toInt\n } else {\n minorIndex = (k - sum - 1).toInt\n }\n println(ids(minorIndex))\n }\n\n def hasExactSquareRoot(x: Long): Boolean = {\n val sqrt: Double = Math.sqrt(x)\n val floor: Double = Math.floor(sqrt)\n Math.abs(floor * floor - x) < 1E-9\n }\n\n solve()\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _670B extends CodeForcesApp {\n override def apply(io: IO) = {\n val n, k = io[Int]\n val ids = io[Vector, Int](n)\n //debug(ans(2 * 1e9.toInt))\n io += ids(ans(k-1))\n }\n\n def ans(i: Int) = {\n val m = ((Math.sqrt(8*i.toDouble + 1) - 1)/2).toLong\n //debug(i, m, m*(m + 1)/2)\n (i - m*(m + 1)/2).toInt\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}\n def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toLong - 1)\n val line = in.next().split(' ').map(_.toLong)\n val full = (1l to k + 1).find(i => i * (i + 1) / 2 > k).get - 1\n val index = k - full * (full + 1) / 2\n println(line(index.toInt))\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toInt - 1)\n val line = in.next().split(' ').map(_.toInt)\n val full = (1 to n).find(i => i * (i + 1) / 2 > k).getOrElse(1) - 1\n val index = k - full * (full + 1) / 2\n println(line(index))\n}\n"}], "src_uid": "9ad07b42358e7f7cfa15ea382495a8a1"} {"source_code": "import scala.io.StdIn\nobject A {\n def main(args: Array[String]): Unit = {\n var ans:StringBuilder=new StringBuilder()\n var t=StdIn.readInt();\n while(t>0)\n {\n var arr:Array[String]=StdIn.readLine().split(\" \");\n var a=Integer.parseInt(arr(0))\n var b=Integer.parseInt(arr(1))\n var i=30;\n var value:Long =0L;\n while(i>=0) {\n if ((a & (1 << i)) != 0 && (b & (1 << i)) != 0) {\n value += (1 << i);\n }\n i -= 1;\n }\n\n var res=(a^value)+(b^value)\n\n ans.append(res).append(\"\\n\");\n\n t-=1;\n }\n println(ans.toString());\n\n\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val t = StdIn.readInt()\n for (i <- 1 to t) {\n val s = StdIn.readLine()\n val a = s\n .split(\" \")\n .map(_.toInt)\n println(a(0) ^ a(1))\n }\n }\n}\n"}], "negative_code": [], "src_uid": "4be3698735278f29b307a7060eb69693"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val S = ns(N)\n val INF = 1e6.toInt\n val dp = Array.fill[Int](N + 1,3)(INF)\n val pre = Array.ofDim[Int](N + 1, 3)\n REP(3) { i => dp(0)(i) = 0 }\n val COLOR = \"RGB\"\n REP(N) { i =>\n // dp(i)(j) -> dp(i + 1)(k)\n REP(3) { j =>\n REP(3) { k =>\n if (i == 0 || j != k) {\n val add = if (COLOR(k) == S(i)) 0 else 1\n val next = dp(i)(j) + add\n if (next < dp(i + 1)(k)) {\n dp(i + 1)(k) = next\n pre(i + 1)(k) = j\n }\n }\n }\n }\n }\n\n def restore(last: Int): String = {\n val c = Array.ofDim[Char](N)\n var p = last\n REP_r(N) { i =>\n c(i) = COLOR(p)\n p = pre(i + 1)(p)\n }\n c.mkString\n }\n\n val (ans, last) = dp(N).zipWithIndex.minBy(_._1)\n out.println(ans)\n val restored = restore(last)\n// val changed = 0 until N count { i => restored(i) != S(i) }\n// debug(changed.toString)\n out.println(restored)\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object CF_535_3_D {\n// date: 25/01/2019\n\n type In = (Int, String)\n type Out = String\n \n def solve(in: In): Out = {\n val (n, s) = in\n val m = Map('R' -> Seq('G','B'), 'G' -> Seq('B','R'), 'B' -> Seq('G','R'))\n val cols = m.keys.toSet\n\n def loop(cs: Seq[Char], out: Seq[Char]): Seq[Char] = cs match {\n // end\n case Seq(a) => out :+ a\n case Seq(a, b) if a == b => out :+ a :+ m(a)(0)\n case Seq(a, b) => out :+ a :+ b\n case a +: b +: c +: rest =>\n if (a == b && c == m(a)(0)) loop(m(a)(1) +: c +: rest, out :+ a)\n else if (a == b) loop(m(b)(0) +: c +: rest, out :+ a)\n else loop(cs.tail, out :+ a)\n }\n\n val res = loop(s.toList, Vector.empty).mkString\n def differences(xs: Seq[Char], ys: Seq[Char]) = (xs, ys).zipped.count(i => i._1 != i._2)\n val diffs = differences(s, res)\n s\"$diffs\\n$res\"\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, {i.nextLine; i.nextLine})\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n // `a` MUST be > 0. Incorrect otherwise.\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}], "negative_code": [], "src_uid": "ddaf86169a79942cefce8e5b5f3d6118"} {"source_code": "object B extends App {\n def fight(h1: Int, a1: Int, c1: Int, h2: Int, a2: Int, s: List[String] = List.empty): List[String] =\n if (h2 <= 0) s.reverse\n else if (h1 <= a2 && h2 > a1) fight(h1 + c1 - a2, a1, c1, h2, a2, \"HEAL\" :: s)\n else fight(h1 - a2, a1, c1, h2 - a1, a2, \"STRIKE\" :: s)\n\n val Array(h1, a1, c1) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val Array(h2, a2) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val strategy = fight(h1, a1, c1, h2, a2)\n println(strategy.length)\n strategy.foreach(println)\n}\n", "positive_code": [{"source_code": "import java.io.FileReader\nimport java.util.Comparator\n\nimport collection.Searching._\nimport scala.collection.mutable\n\nobject Solution {\n //Console.setIn(new FileReader(new java.io.File(\"input\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n var caseNo = 1\n val magicMod = 1000000007\n\n def doCase() : Unit = {\n var Array(h1, a1, c1) = readIntLine()\n var Array(h2, a2) = readIntLine()\n\n var count = 0\n var history : List[String] = List()\n var notDone = true\n while (notDone) {\n count += 1\n if (h2 <= a1) {\n history ::= \"STRIKE\"\n notDone = false\n } else if (h1 <= a2) {\n h1 += c1\n h1 -= a2\n history ::= \"HEAL\"\n } else {\n h2 -= a1\n h1 -= a2\n history ::= \"STRIKE\"\n }\n }\n println(count)\n for (cmd <- history.reverse) {\n println(cmd)\n }\n }\n\n def main(args: Array[String]): Unit = {\n val noCases = 1\n for (i <- 0 until noCases) {\n doCase()\n }\n }\n\n def readIntLine(): Array[Int] = {\n readLine().split(\" \").map(_.toInt)\n }\n\n def readLongLine(): Array[Long] = {\n readLine().split(\" \").map(_.toLong)\n }\n\n def readBigIntLine(): Array[BigInt] = {\n readLine().split(\" \").map(BigInt.apply)\n }\n}\n"}], "negative_code": [{"source_code": "object B extends App {\n def fight(h1: Int, a1: Int, c1: Int, h2: Int, a2: Int, s: List[String] = List.empty): List[String] =\n if (h2 <= 0) s.reverse\n else if (h1 <= a2) fight(h1 + c1 - a2, a1, c1, h2, a2, \"HEAL\" :: s)\n else fight(h1 - a2, a1, c1, h2 - a1, a2, \"STRIKE\" :: s)\n\n val Array(h1, a1, c1) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val Array(h2, a2) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val strategy = fight(h1, a1, c1, h2, a2)\n println(strategy.length)\n strategy.foreach(println)\n}\n"}, {"source_code": "object B extends App {\n def fight(h1: Int, a1: Int, c1: Int, h2: Int, a2: Int, s: List[String] = List.empty): List[String] =\n if (h2 <= 0) s.reverse\n else if (h1 - a2 <= 0) fight(h1 + c1 - a2, a1, c1, h2, a2, \"HEAL\" :: s)\n else fight(h1 - a2, a1, c1, h2 - a1, a2, \"STRIKE\" :: s)\n\n val Array(h1, a1, c1) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val Array(h2, a2) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val strategy = fight(h1, a1, c1, h2, a2)\n println(strategy.length)\n strategy.foreach(println)\n}\n"}], "src_uid": "d497431eb37fafdf211309da8740ece6"} {"source_code": "import sun.management.counter.Counter\n\nimport java.io.BufferedReader\nimport java.io.BufferedWriter\nimport java.io.InputStreamReader\nimport java.io.OutputStreamWriter\nimport java.io.PrintWriter\nimport java.util.StringTokenizer\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val writer = new BufferedWriter(new OutputStreamWriter(System.out))\n\n val testNumber = reader.readLine().toInt\n 1.to(testNumber).foreach { _ =>\n val size = reader.readLine().toInt\n val a = new Array[Int](size);\n {\n val tokenizer = new StringTokenizer(reader.readLine(), \" \")\n var i = 0\n while (i < size) {\n a(i) = Integer.parseInt(tokenizer.nextToken())\n i += 1\n }\n }\n\n @tailrec\n def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =\n if (index == size) true else {\n a(index) % 2 match {\n case 0 => if (previousEven == -1 || previousEven <= a(index))\n findAnswer(index + 1, a(index), previousOdd) else false\n case 1 => if (previousOdd == -1 || previousOdd <= a(index))\n findAnswer(index + 1, previousEven, a(index)) else false\n }\n }\n\n val answer = if (findAnswer(0, -1, -1)) \"YES\" else \"NO\"\n writer.append(answer)\n writer.append(\"\\n\")\n }\n writer.close()\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n", "positive_code": [{"source_code": "import sun.management.counter.Counter\n\nimport java.io.BufferedReader\nimport java.io.BufferedWriter\nimport java.io.InputStreamReader\nimport java.io.OutputStreamWriter\nimport java.io.PrintWriter\nimport java.util.StringTokenizer\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val writer = new BufferedWriter(new OutputStreamWriter(System.out))\n\n val testNumber = reader.readLine().toInt\n 1.to(testNumber).foreach { _ =>\n val size = reader.readLine().toInt\n val a = new Array[Int](size);\n {\n val tokenizer = new StringTokenizer(reader.readLine(), \" \")\n var i = 0\n while (i < size) {\n a(i) = Integer.parseInt(tokenizer.nextToken())\n i += 1\n }\n }\n\n @tailrec\n def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =\n if (index == size) true else {\n a(index) % 2 match {\n case 0 => if (previousEven == -1 || previousEven <= a(index))\n findAnswer(index + 1, a(index), previousOdd) else false\n case 1 => if (previousOdd == -1 || previousOdd <= a(index))\n findAnswer(index + 1, previousEven, a(index)) else false\n }\n }\n\n val answer = if (findAnswer(0, -1, -1)) \"YES\" else \"NO\"\n writer.append(StringBuilder.newBuilder.append(answer).append(\"\\n\"))\n }\n writer.close()\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\nimport java.util.StringTokenizer\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n\n import java.nio.channels.Channels\n\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val writer = new PrintWriter(System.out)\n\n val testNumber = reader.readLine().toInt\n 1.to(testNumber).foreach { _ =>\n val size = reader.readLine().toInt\n val a = new Array[Int](size);\n {\n val tokenizer = new StringTokenizer(reader.readLine(), \" \")\n var i = 0\n while (i < size) {\n a(i) = Integer.parseInt(tokenizer.nextToken())\n i += 1\n }\n }\n\n @tailrec\n def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =\n if (index == size) true else {\n a(index) % 2 match {\n case 0 => if (previousEven == -1 || previousEven <= a(index))\n findAnswer(index + 1, a(index), previousOdd) else false\n case 1 => if (previousOdd == -1 || previousOdd <= a(index))\n findAnswer(index + 1, previousEven, a(index)) else false\n }\n }\n\n val answer = if (findAnswer(0, -1, -1)) \"YES\" else \"NO\"\n writer.println(answer)\n }\n writer.close()\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\nimport java.util.StringTokenizer\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n\n import java.nio.channels.Channels\n\n val buffer = java.nio.ByteBuffer.allocate(4096000)\n val channel = Channels.newChannel(System.in)\n channel.read(buffer)\n val inputTokenizer = new StringTokenizer(new String(buffer.array),\"\\r\\n\\0\")\n\n val writer = new PrintWriter(System.out)\n\n val testNumber = inputTokenizer.nextToken().toInt\n 1.to(testNumber).foreach { _ =>\n val size = inputTokenizer.nextToken().toInt\n val a = new Array[Int](size);\n {\n val tokenizer = new StringTokenizer(inputTokenizer.nextToken(), \" \")\n var i = 0\n while (i < size) {\n a(i) = Integer.parseInt(tokenizer.nextToken())\n i += 1\n }\n }\n\n @tailrec\n def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =\n if (index == size) true else {\n a(index) % 2 match {\n case 0 => if (previousEven == -1 || previousEven <= a(index))\n findAnswer(index + 1, a(index), previousOdd) else false\n case 1 => if (previousOdd == -1 || previousOdd <= a(index))\n findAnswer(index + 1, previousEven, a(index)) else false\n }\n }\n\n val answer = if (findAnswer(0, -1, -1)) \"YES\" else \"NO\"\n writer.println(answer)\n }\n channel.close()\n writer.close()\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\nimport java.util.StringTokenizer\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n\n import java.nio.channels.Channels\n\n val buffer = java.nio.ByteBuffer.allocate(10240000)\n val channel = Channels.newChannel(System.in)\n channel.read(buffer)\n val inputTokenizer = new StringTokenizer(new String(buffer.array),\"\\r\\n\\0\")\n\n val writer = new PrintWriter(System.out)\n\n val testNumber = inputTokenizer.nextToken().toInt\n 1.to(testNumber).foreach { _ =>\n val size = inputTokenizer.nextToken().toInt\n val a = new Array[Int](size);\n {\n val tokenizer = new StringTokenizer(inputTokenizer.nextToken(), \" \")\n var i = 0\n while (i < size) {\n a(i) = Integer.parseInt(tokenizer.nextToken())\n i += 1\n }\n }\n\n @tailrec\n def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =\n if (index == size) true else {\n a(index) % 2 match {\n case 0 => if (previousEven == -1 || previousEven <= a(index))\n findAnswer(index + 1, a(index), previousOdd) else false\n case 1 => if (previousOdd == -1 || previousOdd <= a(index))\n findAnswer(index + 1, previousEven, a(index)) else false\n }\n }\n\n val answer = if (findAnswer(0, -1, -1)) \"YES\" else \"NO\"\n writer.println(answer)\n }\n channel.close()\n writer.close()\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\nimport java.util.StringTokenizer\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n\n import java.nio.channels.Channels\n\n val buffer = java.nio.ByteBuffer.allocate(20480000)\n val channel = Channels.newChannel(System.in)\n channel.read(buffer)\n val inputTokenizer = new StringTokenizer(new String(buffer.array),\"\\r\\n\\0\")\n\n val writer = new PrintWriter(System.out)\n\n val testNumber = inputTokenizer.nextToken().toInt\n 1.to(testNumber).foreach { _ =>\n val size = inputTokenizer.nextToken().toInt\n val a = new Array[Int](size);\n {\n val tokenizer = new StringTokenizer(inputTokenizer.nextToken(), \" \")\n var i = 0\n while (i < size) {\n a(i) = Integer.parseInt(tokenizer.nextToken())\n i += 1\n }\n }\n\n @tailrec\n def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =\n if (index == size) true else {\n a(index) % 2 match {\n case 0 => if (previousEven == -1 || previousEven <= a(index))\n findAnswer(index + 1, a(index), previousOdd) else false\n case 1 => if (previousOdd == -1 || previousOdd <= a(index))\n findAnswer(index + 1, previousEven, a(index)) else false\n }\n }\n\n val answer = if (findAnswer(0, -1, -1)) \"YES\" else \"NO\"\n writer.println(answer)\n }\n channel.close()\n writer.close()\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\nimport java.util.StringTokenizer\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n\n import java.nio.channels.Channels\n\n val buffer = java.nio.ByteBuffer.allocate(40960000)\n val channel = Channels.newChannel(System.in)\n channel.read(buffer)\n val inputTokenizer = new StringTokenizer(new String(buffer.array),\"\\r\\n\\0\")\n\n val writer = new PrintWriter(System.out)\n\n val testNumber = inputTokenizer.nextToken().toInt\n 1.to(testNumber).foreach { _ =>\n val size = inputTokenizer.nextToken().toInt\n val a = new Array[Int](size);\n {\n val tokenizer = new StringTokenizer(inputTokenizer.nextToken(), \" \")\n var i = 0\n while (i < size) {\n a(i) = Integer.parseInt(tokenizer.nextToken())\n i += 1\n }\n }\n\n @tailrec\n def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =\n if (index == size) true else {\n a(index) % 2 match {\n case 0 => if (previousEven == -1 || previousEven <= a(index))\n findAnswer(index + 1, a(index), previousOdd) else false\n case 1 => if (previousOdd == -1 || previousOdd <= a(index))\n findAnswer(index + 1, previousEven, a(index)) else false\n }\n }\n\n val answer = if (findAnswer(0, -1, -1)) \"YES\" else \"NO\"\n writer.println(answer)\n }\n channel.close()\n writer.close()\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\nimport java.util.StringTokenizer\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val writer = new PrintWriter(System.out)\n\n val testNumber = reader.readLine().toInt\n 1.to(testNumber).foreach { _ =>\n val size = reader.readLine().toInt\n val a = new Array[Int](size);\n {\n val tokenizer = new StringTokenizer(reader.readLine(), \" \")\n var i = 0\n while (i < size) {\n a(i) = Integer.parseInt(tokenizer.nextToken())\n i += 1\n }\n }\n\n @tailrec\n def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =\n if (index == size) true else {\n a(index) % 2 match {\n case 0 => if (previousEven == -1 || previousEven <= a(index))\n findAnswer(index + 1, a(index), previousOdd) else false\n case 1 => if (previousOdd == -1 || previousOdd <= a(index))\n findAnswer(index + 1, previousEven, a(index)) else false\n }\n }\n\n val answer = if (findAnswer(0, -1, -1)) \"YES\" else \"NO\"\n writer.println(answer)\n }\n writer.close()\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\nimport java.util.StringTokenizer\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val writer = new PrintWriter(System.out)\n\n val testNumber = reader.readLine().toInt\n 1.to(testNumber).foreach { _ =>\n val size = reader.readLine().toInt\n val a = new Array[Int](size);\n {\n val tokenizer = new StringTokenizer(reader.readLine(), \" \")\n var i = 0\n while (i < size) {\n a(i) = Integer.parseInt(tokenizer.nextToken())\n i += 1\n }\n }\n\n @tailrec\n def findAnswer(index: Int, previousEven: Option[Int], previousOdd: Option[Int]): Boolean =\n if (index == size) true else {\n a(index) % 2 match {\n case 0 => if (previousEven.isEmpty || previousEven.get <= a(index))\n findAnswer(index + 1, Some(a(index)), previousOdd) else false\n case 1 => if (previousOdd.isEmpty || previousOdd.get <= a(index))\n findAnswer(index + 1, previousEven, Some(a(index))) else false\n }\n }\n\n val answer = if (findAnswer(0, None, None)) \"YES\" else \"NO\"\n writer.println(answer)\n }\n writer.close()\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\nimport java.util.StringTokenizer\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val writer = new PrintWriter(System.out)\n\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val size = readInt()\n val a = readInts()\n\n @tailrec\n def findAnswer(index: Int, previousEven: Option[Int], previousOdd: Option[Int]): Boolean =\n if (index == size) true else {\n a(index) % 2 match {\n case 0 => if (previousEven.isEmpty || previousEven.get <= a(index))\n findAnswer(index + 1, Some(a(index)), previousOdd) else false\n case 1 => if (previousOdd.isEmpty || previousOdd.get <= a(index))\n findAnswer(index + 1, previousEven, Some(a(index))) else false\n }\n }\n\n val answer = if (findAnswer(0, None, None)) \"YES\" else \"NO\"\n writer.println(answer)\n }\n writer.close()\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\nimport java.util.StringTokenizer\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val writer = new PrintWriter(System.out)\n\n val testNumber = reader.readLine().toInt\n var testIndex = 0\n while( testIndex < testNumber) {\n testIndex += 1\n\n val size = reader.readLine().toInt\n val tokenizer = new StringTokenizer(reader.readLine(), \" \")\n val a = new Array[Int](size);\n {\n var i = 0\n while (i < size) {\n a(i) = Integer.parseInt(tokenizer.nextToken())\n i += 1\n }\n }\n\n var index: Int = 0\n var previousEven: Int = -1\n var previousOdd: Int = -1\n var answer = \"YES\"\n while (index < size) {\n a(index) % 2 match {\n case 0 => if (previousEven == -1 || previousEven <= a(index)) {\n previousEven = a(index)\n index = index + 1\n } else {\n answer = \"NO\"\n index = size + 100\n }\n case 1 => if (previousOdd == -1 || previousOdd <= a(index)) {\n previousOdd = a(index)\n index = index + 1\n } else {\n answer = \"NO\"\n index = size + 100\n }\n }\n }\n\n writer.println(answer)\n }\n writer.close()\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val reader = new BufferedReader(new InputStreamReader(System.in))\n\n val testNumber = reader.readLine().toInt\n var testIndex = 0\n while( testIndex < testNumber) {\n testIndex += 1\n \n val size = reader.readLine().toInt\n val tokenizer = new StringTokenizer(reader.readLine(), \" \")\n val a = new Array[Int](size);\n {\n var i = 0\n while (i < size) {\n a(i) = Integer.parseInt(tokenizer.nextToken())\n i += 1\n }\n }\n\n var index: Int = 0\n var previousEven: Int = -1\n var previousOdd: Int = -1\n var answer = \"YES\"\n while (index < size) {\n a(index) % 2 match {\n case 0 => if (previousEven == -1 || previousEven <= a(index)) {\n previousEven = a(index)\n index = index + 1\n } else {\n answer = \"NO\"\n index = size + 100\n }\n case 1 => if (previousOdd == -1 || previousOdd <= a(index)) {\n previousOdd = a(index)\n index = index + 1\n } else {\n answer = \"NO\"\n index = size + 100\n }\n }\n }\n\n System.out.println(answer)\n }\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val reader = new BufferedReader(new InputStreamReader(System.in))\n\n val testNumber = reader.readLine().toInt\n 1.to(testNumber).foreach { _ =>\n val size = reader.readLine().toInt\n val tokenizer = new StringTokenizer(reader.readLine(), \" \")\n val a = new Array[Int](size);\n {\n var i = 0\n while (i < size) {\n a(i) = Integer.parseInt(tokenizer.nextToken())\n i += 1\n }\n }\n\n var index: Int = 0\n var previousEven: Int = -1\n var previousOdd: Int = -1\n var answer = \"YES\"\n while (index < size) {\n a(index) % 2 match {\n case 0 => if (previousEven == -1 || previousEven <= a(index)) {\n previousEven = a(index)\n index = index + 1\n } else {\n answer = \"NO\"\n index = size + 100\n }\n case 1 => if (previousOdd == -1 || previousOdd <= a(index)) {\n previousOdd = a(index)\n index = index + 1\n } else {\n answer = \"NO\"\n index = size + 100\n }\n }\n }\n\n System.out.println(answer)\n }\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\r\nimport scala.collection.mutable.ListBuffer\r\nimport scala.io.Source\r\nimport scala.util.control.Breaks\r\n\r\nobject Main extends App {\r\n val input = Source.fromInputStream(System.in).getLines()\r\n val t = input.next().toInt\r\n val res = new ArrayBuffer[String](t)\r\n for (i <- 0 until t) {\r\n input.next()\r\n val ch = new ListBuffer[Int]()\r\n val nch = new ListBuffer[Int]()\r\n input.next().split(' ').foreach(x => {\r\n val i = x.toInt\r\n if (i % 2 == 0) ch.append(i)\r\n else nch.append(i)\r\n })\r\n\r\n if (check(ch.toList) && check(nch.toList)) {\r\n res.append(\"YES\")\r\n } else res.append(\"NO\")\r\n }\r\n\r\n def check(arr: List[Int]): Boolean = {\r\n if (arr.isEmpty) true\r\n else {\r\n var res = true\r\n var max = arr.head\r\n Breaks.breakable {\r\n for (el <- arr.tail) {\r\n if (max > el) {\r\n res = false\r\n Breaks.break()\r\n } else max = el\r\n }\r\n }\r\n res\r\n }\r\n }\r\n\r\n println(res.mkString(\"\\n\"))\r\n}\r\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport java.io.BufferedReader\nimport java.io.BufferedWriter\nimport java.io.InputStreamReader\nimport java.io.OutputStreamWriter\nimport java.io.PrintWriter\nimport java.util.StringTokenizer\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.Source\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n\n val lines = Source.fromInputStream(System.in).getLines()\n val writer = new PrintWriter(System.out)\n\n val testNumber = lines.next().toInt\n 1.to(testNumber).foreach { _ =>\n val size = lines.next().toInt\n val a = new Array[Int](size);\n {\n val tokenizer = new StringTokenizer(lines.next(), \" \")\n var i = 0\n while (i < size) {\n a(i) = Integer.parseInt(tokenizer.nextToken())\n i += 1\n }\n }\n\n @tailrec\n def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =\n if (index == size) true else {\n a(index) % 2 match {\n case 0 => if (previousEven == -1 || previousEven <= a(index))\n findAnswer(index + 1, a(index), previousOdd) else false\n case 1 => if (previousOdd == -1 || previousOdd <= a(index))\n findAnswer(index + 1, previousEven, a(index)) else false\n }\n }\n\n val answer = if (findAnswer(0, -1, -1)) \"YES\" else \"NO\"\n writer.append(StringBuilder.newBuilder.append(answer).append(\"\\n\"))\n }\n writer.close()\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}], "negative_code": [{"source_code": "import sun.management.counter.Counter\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\nimport java.util.StringTokenizer\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val writer = new PrintWriter(System.out);\n\n val testNumber = reader.readLine().toInt\n var testIndex = 0\n while( testIndex < testNumber) {\n testIndex += 1\n\n val size = reader.readLine().toInt\n val tokenizer = new StringTokenizer(reader.readLine(), \" \")\n val a = new Array[Int](size);\n {\n var i = 0\n while (i < size) {\n a(i) = Integer.parseInt(tokenizer.nextToken())\n i += 1\n }\n }\n\n var index: Int = 0\n var previousEven: Int = -1\n var previousOdd: Int = -1\n var answer = \"YES\"\n while (index < size) {\n a(index) % 2 match {\n case 0 => if (previousEven == -1 || previousEven <= a(index)) {\n previousEven = a(index)\n index = index + 1\n } else {\n answer = \"NO\"\n index = size + 100\n }\n case 1 => if (previousOdd == -1 || previousOdd <= a(index)) {\n previousOdd = a(index)\n index = index + 1\n } else {\n answer = \"NO\"\n index = size + 100\n }\n }\n }\n\n writer.println(answer)\n }\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}], "src_uid": "a97e70ad20a337d12dcf79089c16c9f0"} {"source_code": "import scala.io.Source\n\nobject Hello {\n\n def computeCount(a: Int, b: Int): Int = { // a > b\n if (b == 0) return 0\n \n a/b + computeCount(b, a%b)\n }\n \n def main(args: Array[String]) {\n val lineIter = Source.stdin.getLines\n lineIter.next\n while (lineIter.hasNext)\n {\n var Array(ele1, ele2) = lineIter.next.split(\" \").map(_.toInt)\n if (ele1 > ele2) {\n var ele = ele1\n ele1 = ele2\n ele2 = ele\n }\n println(computeCount(ele2, ele1))\n }\n }\n\n}", "positive_code": [{"source_code": "// codeforces 267A\nobject Vichitania extends App {\n var ss = (Console.readLine.split(\" \")) map (_.toInt)\n val n = ss(0)\n\n def countVich(a: Int, b: Int): Int =\n if (a < b) countVich(b, a)\n else if (b == 0) 0\n else {\n val d = a / b\n val o = a % b\n d + countVich(b, o)\n }\n\n for (i <- 0 until n) {\n ss = (Console.readLine.split(\" \")) map (_.toInt)\n val a = ss(0)\n val b = ss(1)\n val cnt = countVich(a, b)\n println(cnt)\n }\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject A {\n var tokenizer = new StringTokenizer(\"\");\n\n def nextToken(): String = {\n while (!tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(readLine);\n }\n tokenizer.nextToken();\n }\n\n def nextInt: Int = {\n nextToken().toInt;\n }\n\n def gcd(a: Int, b: Int): Int = {\n if (b == 0) 0 else gcd(b, a % b) + a / b;\n }\n\n def main(args: Array[String]) {\n val n = nextInt;\n for (i <- 1 to n) {\n println(gcd(nextInt, nextInt))\n }\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject Substr {\n\n def main(args: Array[String]): Unit = {\n\n val src = new Scanner(System.in)\n val n = src.nextInt()\n for (i <- 1 to n) {\n println(sub(src.nextInt(), src.nextInt()))\n }\n src.close()\n }\n\n\n\n def sub(a: Int, b: Int) = {\n def iter(a: Int, b: Int, k: Int): Int = {\n if (a < 1 || b < 1) k\n else if (a > b) iter(a % b, b, k + a / b)\n else if (a < b) iter(a, b % a, k + b / a)\n else if (a == b) k + 1\n else k\n }\n iter(a, b, 0)\n }\n}"}, {"source_code": "object A{\n def main(args: Array[String]){\n\n val n =readLine.toInt\n\n (0 until n).foreach{i=>\n \n val sp=readLine.split(\" \")\n\n println(\n count(sp(0).toInt,sp(1).toInt))\n\n def count(a:Int,b:Int):Int={\n if(b readIntLine()).toList\n println(calc(nxm(1), nxm(1) + 1, operations))\n }\n }\n\n def calc(l: Int, r: Int, operations: List[List[Int]]): Int = operations match {\n case Nil => r - l\n case op :: ops =>\n calc(if (op.last >= l) math.min(l, op.head) else l, if (op.head + 1 <= r) math.max(op.last + 1, r) else r, ops)\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n// def printArray[T](arr: Array[T]): Unit = {\n// val str = new StringBuilder()\n// str.addAll((if (arr.head == -1) 0 else arr.head).toString)\n// // print(arr(0))\n// for (i <- 1 until arr.length) {\n// str.addAll(\" \" + (if (arr(i) == -1) 0 else arr(i)))\n// }\n// println(str)\n// }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n", "positive_code": [{"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, x, m) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val (l, r) = (0 until m).foldLeft((x, x)) {\n case ((l, r), i) =>\n val Array(li, ri) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n if (l <= ri && r >= li) (l min li, r max ri)\n else (l, r)\n }\n\n val ans = r - l + 1\n\n println(ans)\n }\n}\n"}], "negative_code": [], "src_uid": "c358bce566a846bd278329ef2c029dff"} {"source_code": "import scala.io.StdIn\n\nobject CaseOfTheZerosAndOnes {\n def main(args: Array[String]): Unit = {\n StdIn.readLine()\n val bits = StdIn.readLine()\n val (zeros, ones) = bits.foldLeft((0, 0)) { case ((zeros, ones), bit) =>\n if (bit == '0') (zeros + 1, ones)\n else if (bit == '1') (zeros, ones + 1)\n else (zeros, ones)\n }\n println(Math.abs(zeros - ones))\n }\n}\n", "positive_code": [{"source_code": "object Program{\n\tdef main(ins:Array[String]){\n\t\tval n = readInt()\n\t\tval s = readLine()\n\t\tval a = s.partition(_ == '1')\n\t\tdef ln(x:String)= x.length\n\t\tdef check() = \n\t\tif (ln(a._1) > ln(a._2)) ln(a._1) - ln(a._2)\n\t\t\telse ln(a._2) - ln(a._1)\n\t\tprintln(check())\n\t}\n}\n"}, {"source_code": "import java.io.InputStream\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport java.io.PrintWriter\nimport java.io.FileInputStream\nimport java.io.PrintStream\nimport java.io.FileOutputStream\n\nimport scala.util.Random\n\nobject CF556A {\n\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n return next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]): Unit = {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n var in = new InputReader(System.in)\n var out = System.out\n if ( !isOnlineJudge ) {\n in = new InputReader(new FileInputStream(\"input.txt\"))\n out = new PrintStream(new FileOutputStream(\"output.txt\"))\n }\n solve(in,out)\n }\n\n def solve(in: InputReader, out: PrintStream) = {\n //Solution goes here\n in.nextInt();\n val s = in.next()\n val ch = s.toCharArray\n val cnt0 = ch.foldLeft(0)((cnt,c) => if (c=='0') cnt+1 else cnt )\n val cnt1 = ch.foldLeft(0)((cnt,c) => if (c=='1') cnt+1 else cnt )\n out.println(s.length - Math.min(cnt0,cnt1) * 2)\n }\n\n}"}, {"source_code": "import java.io.InputStream\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\nimport java.io.PrintWriter\nimport java.io.FileInputStream\nimport java.io.PrintStream\nimport java.io.FileOutputStream\n\nimport scala.util.Random\n\nobject CF556A {\n\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n return next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]): Unit = {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n var in = new InputReader(System.in)\n var out = System.out\n if ( !isOnlineJudge ) {\n in = new InputReader(new FileInputStream(\"input.txt\"))\n out = new PrintStream(new FileOutputStream(\"output.txt\"))\n }\n solve(in,out)\n }\n\n def solve(in: InputReader, out: PrintStream) = {\n //Solution goes here\n in.nextInt();\n val s: String = in.next()\n val (z,o) = s.toCharArray.foldLeft((0,0))((p,c) => if (c=='0') (p._1+1,p._2) else (p._1,p._2+1))\n out.println(s.length - Math.min(z,o) * 2)\n }\n\n}"}, {"source_code": "object A556 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = scala.io.StdIn.readLine.count(_ == '0')\n println(n - 2*math.min(n-input, input))\n }\n}"}, {"source_code": "object _556A extends CodeForcesApp {\n import CodeForcesApp._, scala.annotation.tailrec, scala.collection.mutable\n\n override type Input = String\n override type Output = Int\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n nextInt\n next\n }\n\n override def solve(input: Input) = {\n var s = List.empty[Boolean]\n for {\n c <- input\n i = c == '0'\n } {\n s = (i, s) match {\n case (x, y :: ys) if x != y => ys\n case _ => i :: s\n }\n }\n\n s.length\n }\n\n override def format(result: Output) = super.format(result)\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n import CodeForcesApp._\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n/********************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n}\n/**********************************[ lib ]************************************/\nobject CodeForcesApp {\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = collection.mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type ==>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A) = if (condition) Some(f) else None\n/*******************************[ constants ]*********************************/\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n val modulus = 1000000007\n}\n"}, {"source_code": "import java.io.BufferedInputStream\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\n\nobject A_Zeros_Ones {\n \n def main(args: Array[String]): Unit = {\n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n \n val n = Integer.parseInt(br.readLine().trim());\n// val line = br.readLine()\n \n var counter = 0\n for (i <- 0 until n) {\n if (br.read().toChar == '1') counter += 1\n else counter -= 1\n }\n \n println(Math.abs(counter))\n }\n}"}], "negative_code": [{"source_code": "object WaterMelon{\n\tdef main(args : Array[String]){\n\t\tvar a = readInt()\n\t\tif ( a > 2 && a % 2 == 0){\n\t\t\tprintln(\"YES\")\n\t\t}\telse{\n\t\t\tprintln(\"NO\")\n\t\t}\n\t}\n}\n"}], "src_uid": "fa7a44fd24fa0a8910cb7cc0aa4f2155"} {"source_code": "import java.util.StringTokenizer\n\nobject _463 extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n println((1 to n).map(i => next.toInt).max)\n}\n", "positive_code": [{"source_code": " object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next()\n println(in.next().split(\" \").map(_.toInt).max)\n }\n"}, {"source_code": "object B463 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val h = readInts(n)\n var res = 0L\n var ret = h(0).toLong\n for(i <- 0 until n-1) {\n res += h(i) - h(i+1)\n if(res < 0) {\n ret += -res\n res = 0\n }\n }\n println(ret)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-28.\n */\nobject B463 extends App{\n val sc = new Scanner(System.in)\n var n = sc.nextInt()\n var pay: Long = 0\n var curH = 0\n var e = 0\n\n while (n >= 1) {\n n -= 1\n val nextH = sc.nextInt()\n val decE = nextH - curH\n\n if (decE > e) {\n pay += nextH - curH - e\n e = 0\n } else {\n e -= decE\n }\n\n curH = nextH\n }\n\n println(pay)\n}\n"}, {"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 30.08.14.\n */\nobject B extends App {\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n val hs = Array.fill(n + 1)(0L)\n for(i <- 1 to n) {\n hs(i) = nextLong\n }\n var min = 0L\n var e = 0L\n for(i <- 1 to n) {\n if(e + hs(i - 1) - hs(i) >= 0) {\n e += hs(i - 1) - hs(i)\n } else {\n min += -(hs(i - 1) - hs(i) + e)\n e = 0L\n }\n }\n out.print(min)\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}"}], "negative_code": [{"source_code": " object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next()\n println(in.next().split(\" \").max)\n }\n"}, {"source_code": "object B463 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val h = readInts(n)\n var res = 0L-h(0)\n var ret = 0L\n for(i <- 0 until n-1) {\n res += h(i) - h(i+1)\n if(res < 0) {\n ret += -res\n res = 0\n }\n }\n println(ret)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "d03ad531630cbecc43f8da53b02d842e"} {"source_code": "import scala.collection.mutable.ListBuffer\r\n\r\nobject prob2 {\r\n def main(args: Array[String]) = {\r\n new Resolver1(Console.in, Console.out).run()\r\n }\r\n}\r\n\r\nclass Resolver1(input: java.io.BufferedReader, output: java.io.PrintStream) {\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n var tokenizer = new StringTokenizer(input.readLine())\r\n val n = tokenizer.nextToken().toInt\r\n var q = tokenizer.nextToken().toInt\r\n val SS = ListBuffer.empty[Long]\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (i <- 0 until n) {\r\n SS+= tokenizer.nextToken().toLong\r\n }\r\n var S = SS.toArray.sorted.reverse\r\n S +:=0.toLong\r\n for (i <- 1 until S.length) {\r\n S(i) = S(i) + S(i - 1)\r\n }\r\n while (q > 0) {\r\n q -= 1\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val x = tokenizer.nextToken().toInt\r\n val y = tokenizer.nextToken().toInt\r\n output.println(S(x) - S(x - y))\r\n }\r\n\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.collection.mutable.ListBuffer\r\n\r\nobject prob {\r\n def main(args: Array[String]) = {\r\n new Resolver(Console.in, Console.out).run()\r\n }\r\n}\r\n\r\nclass Resolver(input: java.io.BufferedReader, output: java.io.PrintStream) {\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n var tokenizer = new StringTokenizer(input.readLine())\r\n val n = tokenizer.nextToken().toInt\r\n var q = tokenizer.nextToken().toInt\r\n val SS = ListBuffer.empty[Long]\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (i <- 0 until n) {\r\n SS+= tokenizer.nextToken().toLong\r\n }\r\n var S = SS.toArray.sorted.reverse\r\n S +:=0.toLong\r\n for (i <- 1 until S.length) {\r\n S(i) = S(i) + S(i - 1)\r\n }\r\n while (q > 0) {\r\n q -= 1\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val x = tokenizer.nextToken().toInt\r\n val y = tokenizer.nextToken().toInt\r\n println(S(x) - S(x - y))\r\n }\r\n\r\n }\r\n}\r\n\r\n"}], "negative_code": [{"source_code": "object prob extends App {\r\n var L = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\r\n var q = L(1)\r\n var S = scala.io.StdIn.readLine().split(\" \").map(_.toLong).sorted\r\n val a = S.length-1\r\n for (i <- 1 until S.length) {\r\n S(a-i) = S(a-i)+S(a-i+1)\r\n }\r\n while (q>0) {\r\n q-=1\r\n val LL = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\r\n if (LL(0) != LL(1)) {\r\n println(S(LL(0)-1) - S(LL(0) - LL(1)-1))\r\n }\r\n else {\r\n println(S(LL(0)-1))\r\n }\r\n }\r\n}\r\n\r\n"}, {"source_code": "import scala.util.Sorting.quickSort\r\n\r\nobject prob extends App {\r\n val L = readLine().split(\" \").map(_.toInt)\r\n val q = L(1)\r\n var S = readLine().split(\" \").map(_.toLong)\r\n quickSort(S)\r\n S.reverse\r\n S +:= 0.toLong\r\n for (i <- 1 until S.length) {\r\n S(i) = S(i)+S(i-1)\r\n }\r\n for (i <- 1 to q) {\r\n val LL = readLine().split(\" \").map(_.toInt)\r\n println(S(LL(0)) - S(LL(0) - LL(1)))\r\n }\r\n}\r\n\r\n"}, {"source_code": "import scala.util.Sorting.quickSort\r\n\r\nobject prob extends App {\r\n val L = readLine().split(\" \").map(_.toInt)\r\n val q = L(1)\r\n var S = readLine().split(\" \").map(_.toLong)\r\n quickSort(S)\r\n S +:= 0.toLong\r\n S = S.reverse\r\n for (i <- 1 until S.length) {\r\n S(i) = S(i)+S(i-1)\r\n }\r\n for (i <- 1 to q) {\r\n val LL = readLine().split(\" \").map(_.toInt)\r\n println(S(LL(0)) - S(LL(0) - LL(1)))\r\n }\r\n}\r\n\r\n"}, {"source_code": "import scala.util.Sorting.quickSort\r\n\r\nobject prob extends App {\r\n val L = readLine().split(\" \").map(_.toInt)\r\n val q = L(1)\r\n var S = readLine().split(\" \").map(_.toLong)\r\n quickSort(S)\r\n S +:= 0.toLong\r\n for (i <- 1 until S.length) {\r\n S(i) = S(i)+S(i-1)\r\n }\r\n for (i <- 1 to q) {\r\n val LL = readLine().split(\" \").map(_.toInt)\r\n println(S(LL(0)) - S(LL(0) - LL(1)))\r\n }\r\n}\r\n\r\n"}, {"source_code": "import scala.collection.mutable\r\n\r\nobject prob extends App {\r\n import scala.collection.mutable.ArrayBuilder\r\n val L = readLine().split(\" \").map(_.toInt)\r\n val q = L(1)\r\n var S = readLine().split(\" \").map(_.toInt).sorted.reverse\r\n for (i <- 1 until S.length) {\r\n S(i) = S(i)+S(i-1)\r\n }\r\n for (i <- 1 to q) {\r\n val LL = readLine().split(\" \").map(_.toInt)\r\n if (LL(0) != LL(1)) {\r\n println(S(LL(0)-1) - S(LL(0) - LL(1)-1))\r\n }\r\n else {\r\n println(S(LL(0)-1))\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import scala.collection.mutable\r\n\r\nobject prob extends App {\r\n import scala.collection.mutable.ArrayBuilder\r\n val L = readLine().split(\" \").map(_.toInt)\r\n val q = L(1)\r\n val S = readLine().split(\" \").map(_.toInt).sorted.reverse\r\n var SS = new ArrayBuilder.ofInt\r\n var s: Int = 0\r\n SS += s\r\n for (i <- S) {\r\n s += i\r\n SS += s\r\n }\r\n val SSS = SS.result\r\n for (i <- 1 to q) {\r\n val LL = readLine().split(\" \").map(_.toInt)\r\n println(SSS(LL(0)) - SSS(LL(0) - LL(1)))\r\n }\r\n}\r\n"}, {"source_code": "\r\n\r\n\r\nobject prob extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.{max, min, pow,abs}\r\n import scala.List\r\n import scala.util.Sorting.quickSort\r\n import scala.collection.mutable.{ArrayBuffer, ListBuffer}\r\n val L = readLine().split(\" \").map(_.toInt)\r\n val q = L(1)\r\n val S = readLine().split(\" \").map(_.toInt)\r\n quickSort(S)\r\n val SS = ListBuffer.empty[Long]\r\n var s: Long = 0\r\n SS +=s\r\n for (i <- S) {\r\n s+=i\r\n SS +=s\r\n }\r\n for (i <- 1 to q){\r\n val LL = readLine().split(\" \").map(_.toInt)\r\n println(SS(LL(0)) - SS(LL(0) - LL(1)))\r\n }\r\n}\r\n"}], "src_uid": "2dc69231824db013161e4f223e25ccb9"} {"source_code": "import java.util.StringTokenizer\n\nimport scala.annotation.tailrec\nimport scala.util.Try\n\nobject D extends App {\n val INF = 1 << 30\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n\n read()\n val n = int()\n val k = int()\n var gc = int()\n var bc = int()\n var failed = false\n\n val G = 'G'\n val B = 'B'\n\n def anti(c: Char): Char = {\n if (c == G) B else G\n }\n\n @tailrec\n def s(start: String, prim: Char, fc: Int, sc: Int): String = {\n if ((fc == 0) && (sc == 0)) return start\n val c = if (fc >= sc) Math.min(fc, k) else 1\n if (c <= 0) sys.error(\"\")\n s(start + Array.fill(c)(prim).mkString, anti(prim), sc, fc - c)\n }\n\n val ans = Try {\n if (gc > bc) s(\"\", G, gc, bc) else s(\"\", B, bc, gc)\n }.getOrElse(\"NO\")\n println(ans)\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.util.Try\n\nobject D extends App {\n val INF = 1 << 30\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n\n read()\n val n = int()\n val k = int()\n var gc = int()\n var bc = int()\n var failed = false\n\n val G = 'G'\n val B = 'B'\n\n def anti(c: Char): Char = {\n if (c == G) B else G\n }\n\n def s(prim: Char, fc: Int, sc: Int): String = {\n if ((fc == 0) && (sc == 0)) return \"\"\n val c = if (fc >= sc) Math.min(fc, k) else 1\n if (c <= 0) sys.error(\"\")\n Array.fill(c)(prim).mkString + s(anti(prim), sc, fc - c)\n }\n\n val ans = Try {\n if (gc > bc) s(G, gc, bc) else s(B, bc, gc)\n }.getOrElse(\"NO\")\n println(ans)\n}\n"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.annotation.tailrec\nimport scala.util.Try\n\nobject D extends App {\n val INF = 1 << 30\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n\n read()\n val n = int()\n val k = int()\n var gc = int()\n var bc = int()\n var failed = false\n\n val G = 'G'\n val B = 'B'\n\n def anti(c: Char): Char = {\n if (c == G) B else G\n }\n\n @tailrec\n def s(start: String, prim: Char, fc: Int, sc: Int): String = {\n if ((fc == 0) && (sc == 0)) return \"\"\n val c = if (fc >= sc) Math.min(fc, k) else 1\n if (c <= 0) sys.error(\"\")\n s(Array.fill(c)(prim).mkString, anti(prim), sc, fc - c)\n }\n\n val ans = Try {\n if (gc > bc) s(\"\", G, gc, bc) else s(\"\", B, bc, gc)\n }.getOrElse(\"NO\")\n println(ans)\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nimport scala.annotation.tailrec\nimport scala.util.Try\n\nobject D extends App {\n val INF = 1 << 30\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(readLine()) }\n def int() = st.nextToken().toInt\n\n read()\n val n = int()\n val k = int()\n var gc = int()\n var bc = int()\n var failed = false\n\n val G = 'G'\n val B = 'B'\n\n def anti(c: Char): Char = {\n if (c == G) B else G\n }\n\n @tailrec\n def s(start: String, prim: Char, fc: Int, sc: Int): String = {\n if ((fc == 0) && (sc == 0)) return start\n val c = if (fc >= sc) Math.min(fc, k) else 1\n if (c <= 0) sys.error(\"\")\n s(Array.fill(c)(prim).mkString, anti(prim), sc, fc - c)\n }\n\n val ans = Try {\n if (gc > bc) s(\"\", G, gc, bc) else s(\"\", B, bc, gc)\n }.getOrElse(\"NO\")\n println(ans)\n}\n"}], "src_uid": "2a14f4a526ad2237b897102bfa298003"} {"source_code": "object A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n, a, b) = readInts(3)\n\n var even = n / 2\n var odd = n - even\n\n val grid = Array.fill(a, b){ 0 }\n var oddI = 1\n var evenI = 2\n\n for {\n i <- 0 until a\n j <- 0 until b\n } {\n if ((i + j) % 2 == 0) {\n if (odd > 0) {\n odd -= 1\n grid(i)(j) = oddI\n oddI += 2\n }\n } else {\n if (even > 0) {\n even -= 1\n grid(i)(j) = evenI\n evenI += 2\n }\n }\n }\n\n if (even == 0 && odd == 0) {\n grid.foreach { row => println(row.mkString(\" \")) }\n } else println(-1)\n}\n", "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _644A extends CodeForcesApp {\n override def apply(io: IO) = {\n val n, a, b = io[Int]\n var (d, r) = (1, 2)\n\n val t = Array.tabulate(a, b) {\n case (i, j) if (i + j)%2 == 0 =>\n val x = d\n d += 2\n x\n case _ =>\n val x = r\n r += 2\n x\n }\n\n val ans = Array.tabulate(a, b) {\n case (i, j) => if (t(i)(j) > n) 0 else t(i)(j)\n }\n\n if (n > a*b) {\n io += -1\n } else {\n ans foreach {row =>\n io ++= row\n io.appendLine()\n }\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates: Traversable[A] = {\n val elems = mutable.Set.empty[A]\n t collect {case i if !elems.add(i) => i}\n }\n def zipWith[B](f: A => B): Traversable[(A, B)] = t map {i => i -> f(i)}\n def mapTo[B](f: A => B): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class IndexedSeqExtensions[A](val s: IndexedSeq[A]) extends AnyVal {\n def withOffset(offset: Int): IndexedSeq[A] = Iterator.fill(offset)(null.asInstanceOf[A]) ++: s\n }\n implicit class PairsExtensions[A, B](val t: Traversable[(A, B)]) extends AnyVal {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap: Map[A, Traversable[B]] = t.groupBy(_._1).mapValues(_.map(_._2))\n def swap: Traversable[(B, A)] = t.map(_.swap)\n }\n implicit class MapExtensions[K, V](val m: Map[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.swap.toMultiMap.mapValues(_.toSet)\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def ^^(i: Int): A = if (i == 0) n.one else {\n val h = x ^^ (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x) //e.g. students.indexOf(\"Greg\").nonNegative\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default\n }\n def memoize[I] = new {\n def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {\n override def apply(key: I) = getOrElseUpdate(key, f(key))\n }\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n val mod: Int = (1e9 + 7).toInt\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.{Growable, CanBuild}\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] with Growable[Any] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit parse: IO.Parser[A]): A = parse.apply(this)\n def apply[C[_], A: IO.Parser](n: Int)(implicit builder: CanBuild[A, C[A]]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n override def +=(obj: Any) = {\n if (isNewLine) isNewLine = false else print(separator)\n print(obj)\n this\n }\n def ++=(t: TraversableOnce[_], ifEmpty: => Any): this.type = if (t.isEmpty) this += ifEmpty else this ++= t\n\n def appendLine(): this.type = {\n println()\n isNewLine = true\n this\n }\n\n override def clear() = flush()\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\n\nobject IO {\n class Parser[A](val apply: IO => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n }\n implicit def collection[C[_], A: Parser](implicit cbf: CanBuild[A, C[A]]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, a, b) = in.next().split(' ').map(_.toInt)\n if (n > a * b)\n println(-1)\n else {\n val ans = Array.ofDim[Int](a, b)\n var odd = 1\n var even = 2\n (0 until a).foreach{ i =>\n (0 until b).foreach { j =>\n if ((i + j) % 2 == 0 && odd <= n) {\n ans(i)(j) = odd\n odd += 2\n }\n else if (even <= n) {\n ans(i)(j) = even\n even += 2\n }\n }\n }\n println(ans.map(_.mkString(\" \")).mkString(\"\\n\"))\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport java.util.TreeMap\nimport scala.collection.mutable\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val a = nextInt\n val b = nextInt\n if (a * b < n) {\n out.println(-1)\n return 0\n }\n var flag = true\n var fst = Stream.from(1, 2)\n var snd = Stream.from(2, 2)\n var cnt = n\n for (i <- 0 until a) {\n for (j <- 0 until b) {\n if (cnt > 0) {\n if (flag && fst.head <= n) {\n out.print(s\"${fst.head} \")\n fst = fst.tail\n cnt -= 1\n } else if (!flag && snd.head <= n) {\n out.print(s\"${snd.head} \")\n snd = snd.tail\n cnt -= 1\n } else {\n out.print(\"0 \")\n }\n } else {\n out.print(\"0 \")\n }\n if (j == b - 1 && b % 2 == 0) {\n flag = flag\n } else {\n flag = !flag\n }\n }\n out.println()\n }\n return 0\n }\n}\n"}], "negative_code": [], "src_uid": "6e0dafeaf85e92f959c388c72e158f68"} {"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n\n val Array(n) = readInts(1)\n val as = Array.fill(n){ readLongs(n) }\n\n val row0 = as.indexWhere(_.contains(0))\n val col0 = as(row0).indexOf(0)\n\n if (n == 1) println(1)\n else {\n val goal = as.map(_.sum).max\n val row0Sum = as(row0).sum\n val delta = goal - row0Sum\n as(row0)(col0) = delta\n val tas = as.transpose\n\n val rowSums = as.map(_.sum)\n val colSums = tas.map(_.sum)\n val diagIIsum = (0 until n).map(i => as(i)(i)).sum\n val diagIJsum = (0 until n).map(i => as(i)(n - i - 1)).sum\n\n if (delta > 0 && rowSums.forall(_ == goal) && colSums.forall(_ == goal) && diagIIsum == goal && diagIJsum == goal) println(delta)\n else println(-1)\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList\n val line = lines.find(_.contains(0)).get\n val sumH = line.sum\n val index = line.indexOf(0)\n val sumV = lines.map(_(index)).sum\n val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct\n val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct\n if (n == 1)\n println(1)\n else if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV || sumsH.head <= sumH)\n println(-1)\n else {\n val candidate = sumsH.head - sumH\n val diagonal1 = lines.indices.map{ i =>\n val el = lines(i)(i)\n if (el == 0) candidate else el\n }.sum\n val diagonal2 = lines.indices.map { i =>\n val el = lines(i)(n - i - 1)\n if (el == 0) candidate else el\n }.sum\n if (diagonal2 == diagonal1 && diagonal1 == sumsH.head)\n println(candidate)\n else\n println(-1)\n }\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _711B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll}\n val n = read[Int]\n val grid = mutable.ArrayBuffer.fill(n, n)(read[Long])\n\n val z = for {\n i <- grid.indices\n j <- grid(i).indices\n if grid(i)(j) == 0\n } yield (i, j)\n val (x, y) = z.head\n\n val ans = grid.find(g => !g.contains(0)).map(g => g.sum - grid(x).sum) getOrElse 1L\n\n grid(x)(y) = ans\n\n val sums = map[Long] to 0\n\n var d1, d2 = 0L\n for(i <- until(n)) {\n d1 += grid(i)(i)\n d2 += grid(i)(n - i - 1)\n var r, c = 0L\n for(j <- until(n)) {\n r += grid(i)(j)\n c += grid(j)(i)\n }\n sums(r) += 1\n sums(c) += 1\n }\n\n sums(d1) += 1\n sums(d2) += 1\n\n\n write(if (sums.size == 1 && ans > 0) ans else -1)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n val a = Array.ofDim[Long](n, n)\n\n var zerop = (-1, -1) // (y, x)\n\n for(i <- 0 until n){\n for(j <- 0 until n){\n val tmp = sc.nextLong()\n a(i)(j) = tmp\n if(tmp == 0)\n zerop = (i, j)\n }\n }\n\n if(n == 1)\n println(1)\n else{\n var ans = -1L\n var flag = true\n\n // row\n var sum = -1L\n if(zerop._1 == 0)\n sum = a(1).sum\n else\n sum = a(0).sum\n\n for(i <- 0 until n){\n if(i == zerop._1){\n ans = sum - a(i).sum\n if(ans < 1)\n flag = false\n }\n else{\n if(a(i).sum != sum)\n flag = false\n }\n }\n\n // column\n sum = -1L\n\n def count(x: Int): Long = {\n var res = 0L\n for(k <- 0 until n)\n res += a(k)(x)\n res\n }\n\n /* process */\n if(zerop._2 == 0)\n sum = count(1)\n else\n sum = count(0)\n\n for(i <- 0 until n){\n if(i == zerop._2){\n if(sum != count(i) + ans)\n flag = false \n }\n else{\n if(count(i) != sum)\n flag = false\n }\n }\n\n // cross\n\n if(zerop._1 == zerop._2 && n % 2 == 1 && zerop._1 == n/2){ // including empty grid double\n var crossR = 0L\n var crossL = 0L\n for(i <- 0 until n){\n crossR += a(i)(i)\n crossL += a(i)((n-1)-i)\n }\n if(crossR + ans != sum || crossL + ans != sum)\n flag = false\n }\n else if(zerop._1 == zerop._2){ // R\n var crossR = 0L\n var crossL = 0L\n for(i <- 0 until n){\n crossR += a(i)(i)\n crossL += a(i)((n-1)-i)\n }\n if(crossR + ans != sum || crossL != sum)\n flag = false\n }\n else if(zerop._1 + zerop._2 == n - 1){ // L\n var crossR = 0L\n var crossL = 0L\n for(i <- 0 until n){\n crossR += a(i)(i)\n crossL += a(i)((n-1)-i)\n }\n if(crossR != sum || crossL + ans != sum)\n flag = false\n }\n else{\n var crossR = 0L\n var crossL = 0L\n for(i <- 0 until n){\n crossR += a(i)(i)\n crossL += a(i)((n-1)-i)\n }\n if(crossR != sum || crossL != sum)\n flag = false\n }\n\n // output\n if(flag)\n println(ans)\n else\n println(-1)\n }\n }\n}\n"}, {"source_code": "object B711 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n if(n == 1) {\n println(\"1\")\n }\n else {\n val in = Array.fill(n)(readLongs(n))\n var x = -1\n var y = -1\n for(i <- 0 until n; j <- 0 until n if in(i)(j) == 0) {\n x = i\n y = j\n }\n val sum = if(x == 0) {\n in(1).sum\n } else {\n in(0).sum\n }\n if(sum - in(x).sum <= 0)\n println(\"-1\")\n else {\n in(x)(y) = sum - in(x).sum\n if(isValid(in, sum)) {\n println(in(x)(y))\n } else {\n println(\"-1\")\n }\n }\n }\n }\n\n def isValid(in: Array[Array[Long]], sum: Long): Boolean = {\n in.indices.forall(in(_).sum == sum) && {\n val cols = Array.fill(in.length)(0L)\n for(i <- in.indices; j <- in.indices)\n cols(j) += in(i)(j)\n cols.forall(_ == sum)\n } && {\n var sumd = 0L\n for(i <- in.indices; j <- in.indices if i == j)\n sumd += in(i)(j)\n sumd == sum\n } && {\n var sumd = 0L\n for(i <- in.indices; j <- in.indices if j == in.length-i-1)\n sumd += in(i)(j)\n sumd == sum\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n\n val Array(n) = readInts(1)\n val as = Array.fill(n){ readLongs(n) }\n\n val row0 = as.indexWhere(_.contains(0))\n val col0 = as(row0).indexOf(0)\n\n if (n == 1) println(1)\n else {\n val goal = as.map(_.sum).max\n val row0Sum = as(row0).sum\n val delta = goal - row0Sum\n as(row0)(col0) = delta\n val tas = as.transpose\n\n val rowSums = as.map(_.sum)\n val colSums = tas.map(_.sum)\n val diagIIsum = (0 until n).map(i => as(i)(i)).sum\n val diagIJsum = (0 until n).map(i => as(i)(n - i - 1)).sum\n\n if (rowSums.forall(_ == goal) && colSums.forall(_ == goal) && diagIIsum == goal && diagIJsum == goal) println(delta)\n else println(-1)\n }\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _711B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll}\n val n = read[Int]\n val grid = mutable.ArrayBuffer.fill(n, n)(read[Long])\n\n val z = for {\n i <- grid.indices\n j <- grid(i).indices\n if grid(i)(j) == 0\n } yield (i, j)\n val (x, y) = z.head\n\n val ans = grid.find(g => !g.contains(0)).map(_.sum) match {\n case None => 1\n case Some(target) => target - grid(x).sum\n }\n\n grid(x)(y) = ans\n\n val sums = map[Long] to 0\n\n grid foreach {row => sums(row.sum) += 1}\n val g1 = Vector.tabulate(n, n){case (i, j) => grid(j)(i)}\n g1 foreach {row => sums(row.sum) += 1}\n\n val d1 = Vector.tabulate(n)(i => grid(i)(i))\n val d2 = Vector.tabulate(n)(i => grid(i)(n - i - 1))\n\n sums(d1.sum) += 1\n sums(d2.sum) += 1\n\n write(if (sums.size == 1) ans else -1)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList\n val line = lines.find(_.contains(0)).get\n val sumH = line.sum\n val index = line.indexOf(0)\n val sumV = lines.map(_(index)).sum\n val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct\n val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct\n if (n == 1)\n println(1)\n else if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV)\n println(-1)\n else\n println(sumsH.head - sumH)\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList\n val line = lines.find(_.contains(0)).get\n val sumH = line.sum\n val index = line.indexOf(0)\n val sumV = lines.map(_(index)).sum\n val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct\n val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct\n if (n == 1)\n println(1)\n else if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV || sumsH.head <= sumH)\n println(-1)\n else\n println(sumsH.head - sumH)\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList\n val line = lines.find(_.contains(0)).get\n val sumH = line.sum\n val index = line.indexOf(0)\n val sumV = lines.map(_(index)).sum\n val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct\n val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct\n if (n == 1)\n println(1)\n else if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV || sumsH.head <= sumH)\n println(-1)\n else {\n val candidate = sumsH.head - sumH\n val diagonal1 = lines.indices.map{ i =>\n val el = lines(i)(i)\n if (el == 0) candidate else el\n }.sum\n val diagonal2 = lines.indices.map { i =>\n val el = lines(n - i - 1)(n - i - 1)\n if (el == 0) candidate else el\n }.sum\n if (diagonal2 == diagonal1 && diagonal1 == sumsH.head)\n println(candidate)\n else\n println(-1)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList\n val line = lines.find(_.contains(0)).get\n val sumH = line.sum\n val index = line.indexOf(0)\n val sumV = lines.map(_(index)).sum\n val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct\n val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct\n if (n == 1)\n println(1)\n else if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV)\n println(-1)\n else {\n val candidate = sumsH.head - sumH\n val diagonal1 = lines.indices.map{ i => \n val el = lines(i)(i)\n if (el == 0) candidate else el\n }.sum\n val diagonal2 = lines.indices.map { i =>\n val el = lines(n - i - 1)(n - i - 1)\n if (el == 0) candidate else el\n }.sum\n if (diagonal2 == diagonal1 && diagonal1 == sumsH.head)\n println(candidate)\n else\n println(-1)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList\n val line = lines.find(_.contains(0)).get\n val sumH = line.sum\n val index = line.indexOf(0)\n val sumV = lines.map(_(index)).sum\n val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct\n val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct\n if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV)\n println(-1)\n else\n println(sumsH.head - sumH)\n}\n"}], "src_uid": "3bd5a228ed5faf997956570f96becd73"} {"source_code": "/**\n * Created by ruslan on 3/4/17.\n */\nobject ProblemB extends App {\n\n override def main(args: Array[String]): Unit = {\n val n = readInt()\n\n val inputData = readLine().split(\" \")\n\n val msgs = (for (i <- inputData) yield i.toInt).zipWithIndex.sortWith((p1, p2) => {\n (if (p1._2 == 0) 1\n else if (p2._2 == 0) -1\n else p1._1 - p2._1) > 0\n })\n\n var index = 0\n\n var lastIdNotHaved = 1\n\n// for (msg <- msgs) println(msg)\n\n\n val answer = msgs.foldLeft(List[(Int, Int)]())((res, msg) => {\n index +=1\n if (lastIdNotHaved >= n || msg._1 == 0) res\n else if (index > lastIdNotHaved) res\n else {\n (1 to Math.min(msg._1, n - lastIdNotHaved)).foldLeft(res)((res1, some) => {\n val returnVal = ((msg._2 + 1) -> (msgs(lastIdNotHaved)._2 + 1)) :: res1\n lastIdNotHaved += 1\n returnVal\n })\n }\n }).reverse\n\n if (lastIdNotHaved >= n) {\n println(answer.length)\n for ((from, to) <- answer) {\n println(from + \" \" + to)\n }\n } else println(-1)\n\n\n }\n\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.TreeSet\nimport scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by netman on 3/4/17.\n */\nobject Main {\n def main(args: Array[String]): Unit = {\n val lines = io.Source.fromInputStream(System.in).getLines().toArray\n val n = lines(0).toInt\n val arr = lines(1).split(\" \").map(_.toInt)\n val s = TreeSet()(Ordering.by[Int, (Int, Int)](x => (arr(x), x)).reverse)\n (0 until n).foreach(s.add)\n val res = ArrayBuffer.empty[(Int, Int)]\n def dfs(v: Int): Unit = {\n s.remove(v)\n for (x <- 0 until arr(v)) {\n if (s.nonEmpty) {\n val to = s.firstKey\n res += ((v, to))\n dfs(to)\n }\n }\n }\n dfs(0)\n if (s.nonEmpty) {\n println(\"-1\")\n } else {\n println(res.size)\n for ((x, y) <- res) {\n println((x + 1) + \" \" + (y + 1))\n }\n }\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val N = io.StdIn.readInt()\n val A = Array.ofDim[(Int, Int)](N)\n\n val line = io.StdIn.readLine().split(\" \")\n\n (0 until N).foreach(i => A(i) = (line(i).toInt, i))\n\n val B = A.tail.sorted.reverse\n\n val marked = Array.ofDim[Boolean](N)\n marked(0) = true\n\n val queue = collection.mutable.Queue.empty[Int]\n queue.enqueue(0)\n\n val solution = ArrayBuffer.empty[(Int, Int)]\n\n while (queue.nonEmpty){\n val person = queue.dequeue()\n var cnt = A(person)._1\n\n for (i <- 1 until N)\n if (!marked(i) && cnt > 0){\n queue.enqueue(B(i - 1)._2)\n marked(i) = true\n solution += ((person, B(i - 1)._2))\n cnt -= 1\n }\n }\n\n if (marked.contains(false))\n println(-1)\n else {\n println(solution.length)\n solution.foreach { case (x, y) => printf(\"%d %d\\n\", x + 1, y + 1) }\n }\n }\n\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\nobject B extends App{\n case class Student(id: Int, a: Int) {\n def comapre(s: Student): Int = a.compare(s.a)\n }\n val in = new java.util.Scanner(System.in)\n val n = in.nextInt\n val polic = Student(1, in.nextInt)\n val ar = for (i <- 2 to n) yield Student(i, in.nextInt)\n val sort = (ar.sortBy { x => x.a }).reverse\n \n val strBuild = new StringBuilder\n \n var nSMS = 0\n \n /**\n * cur -- число оставшихся сообщений у первого отправляющего\n * sends -- список отправляющих. Если студент не может оправлять, он искючается из списка отпр..\n * \t\t\t\t Изначально один отправляющий: Поликарп.\n * newSends -- новый список отправляющих.\n * k -- количество студентов, получивших сообщение, включая Поликарпа\n */\n @tailrec\n def solution(cur: Int = polic.a, sends: List[Student] = List(polic), newSends: List[Student] = Nil, k: Int = 1): Int = {\n if (k == n) return k\n if (sends.isEmpty || (cur == 0 && sends.tail.isEmpty)) { \n if (newSends.isEmpty) k\n else solution(newSends.head.a, newSends, Nil, k)\n } else {\n if (cur == 0) solution(sends.tail.head.a, sends.tail, newSends, k)\n else {\n nSMS += 1\n strBuild.++=(s\"${sends.head.id} ${sort(k-1).id}\\n\")\n solution(cur-1, sends, sort(k-1) :: newSends, k+1)\n }\n }\n }\n \n if (solution() != n) println(-1)\n else {\n println(nSMS)\n println(strBuild)\n }\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val N = io.StdIn.readInt()\n val A = Array.ofDim[(Int, Int)](N)\n\n val line = io.StdIn.readLine().split(\" \")\n println(line.length)\n\n (0 until N).foreach(i => A(i) = (line(i).toInt, i))\n\n val B = A.tail.sorted.reverse\n\n val marked = Array.ofDim[Boolean](N)\n marked(0) = true\n\n val queue = collection.mutable.Queue.empty[Int]\n queue.enqueue(0)\n\n val solution = ArrayBuffer.empty[(Int, Int)]\n\n while (queue.nonEmpty){\n val person = queue.dequeue()\n var cnt = A(person)._1\n\n for (i <- 1 until N)\n if (!marked(i) && cnt > 0){\n queue.enqueue(i)\n marked(i) = true\n solution += ((person, A(i)._2))\n cnt -= 1\n }\n }\n\n if (marked.contains(false))\n println(-1)\n else {\n println(solution.length)\n solution.foreach { case (x, y) => printf(\"%d %d\\n\", x + 1, y + 1) }\n }\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val N = io.StdIn.readInt()\n val A = Array.ofDim[(Int, Int)](N)\n\n val line = io.StdIn.readLine().split(\" \")\n\n (0 until N).foreach(i => A(i) = (line(i).toInt, i))\n\n val B = A.tail.sorted.reverse\n\n val marked = Array.ofDim[Boolean](N)\n marked(0) = true\n\n val queue = collection.mutable.Queue.empty[Int]\n queue.enqueue(0)\n\n val solution = ArrayBuffer.empty[(Int, Int)]\n\n while (queue.nonEmpty){\n val person = queue.dequeue()\n var cnt = A(person)._1\n\n for (i <- 1 until N)\n if (!marked(i) && cnt > 0){\n queue.enqueue(i)\n marked(i) = true\n solution += ((person, A(i)._2))\n cnt -= 1\n }\n }\n\n if (marked.contains(false))\n println(-1)\n else {\n println(solution.length)\n solution.foreach { case (x, y) => printf(\"%d %d\\n\", x + 1, y + 1) }\n }\n }\n\n}\n"}, {"source_code": "/**\n * Created by ruslan on 3/4/17.\n */\nobject ProblemB extends App {\n\n override def main(args: Array[String]): Unit = {\n val n = readInt()\n\n val inputData = readLine().split(\" \")\n\n val msgs = (for (i <- inputData) yield i.toInt).zipWithIndex.sortWith((p1, p2) => {\n (if (p1._2 == 0) 1\n else if (p2._2 == 0) -1\n else p1._1 - p2._1) > 0\n })\n\n var index = 0\n\n var lastIdNotHaved = 1\n\n// for (msg <- msgs) println(msg)\n\n\n val answer = msgs.foldLeft(List[(Int, Int)]())((res, msg) => {\n index +=1\n if (lastIdNotHaved >= n || msg._1 == 0) res\n else if (index > lastIdNotHaved) res\n else {\n (1 to Math.min(msg._1, n - lastIdNotHaved)).foldLeft(res)((res1, some) => {\n val returnVal = ((msg._2 + 1) -> (msgs(lastIdNotHaved)._2 + 1)) :: res1\n lastIdNotHaved += 1\n returnVal\n })\n }\n })\n\n if (lastIdNotHaved >= n) {\n println(answer.length)\n for ((from, to) <- answer) {\n println(from + \" \" + to)\n }\n } else println(-1)\n\n\n }\n\n}\n"}], "src_uid": "3ebb3a4f01345145f8f9817f7c77185e"} {"source_code": "\nimport scala.io.StdIn.readLine\n\nobject MagicPowder {\n\n def readInts(): Array[Int] = {\n readLine().split(\"\\\\s+\").map(s => s.toInt)\n }\n\n def readLongs(): Array[Long] = {\n readLine().split(\"\\\\s+\").map(s => s.toLong)\n }\n\n case class IngStep(index: Long, required: Long, lastStep: Long, remainder: Long)\n\n def getOneStepPrice(step: Long, ingStep:IngStep): Long = {\n if (step <= ingStep.lastStep)\n 0L // No need to use anything\n else\n if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {\n ingStep.required - ingStep.remainder // use is there is a reminder on this step\n } else {\n // If there is a remainder, we need 1 step less\n if (ingStep.remainder > 0) {\n (ingStep.required - ingStep.remainder) + (step - ingStep.lastStep - 1) * ingStep.required\n } else {\n // all the steps are the same\n (step - ingStep.lastStep) * ingStep.required\n }\n }\n }\n\n def getStepPrice(step: Long, ingSteps: IndexedSeq[IngStep]): Long = {\n ingSteps.foldRight(0L)((ingStep, t) => {\n t + getOneStepPrice(step, ingStep)\n })\n }\n\n def main(args: Array[String]): Unit = {\n val numberPowder = readLongs()\n\n val n = numberPowder(0)\n val p = numberPowder(1)\n\n val a = readLongs()\n val b = readLongs()\n\n val ingSteps = a.indices\n .map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i))))\n .sortBy(m => m.lastStep) // we now have i, steps sorted from lowest\n\n var startStep = 0L\n\n val fullPrice = getStepPrice(ingSteps.last.lastStep + 1, ingSteps) // Price to pay after everything is over\n\n var endStep = if (p >= fullPrice) ingSteps.last.lastStep + Math.ceil(p.toDouble / a.sum).toLong else ingSteps.last.lastStep\n\n var stop = false\n var cookies = Math.max(startStep - 1, 0)\n\n while (!stop) {\n val mid = startStep + Math.ceil((endStep - startStep).toDouble / 2).toLong\n\n val stepPrice = getStepPrice(mid, ingSteps)\n cookies = mid\n\n if (stepPrice < p) {\n startStep = mid // Moving higher\n } else {\n endStep = mid // Moving lower\n }\n\n if (startStep == endStep) {\n stop = true\n } else if (startStep + 1 == endStep) {\n stop = true\n cookies = if (getStepPrice(endStep, ingSteps) <= p) endStep else startStep\n }\n }\n\n print(cookies)\n\n }\n}\n", "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _670D2 extends CodeForcesApp {\n override def apply(io: IO) = {\n val n, k = io[Int]\n val perCookie, has = io[Vector, Long](n)\n\n val upperBound = 1 + ((has.sum + k)/perCookie.sum)\n\n def canBake(c: Long) = (c <= upperBound) && { //can bake c cookies?\n val missing = perCookie.indices sumWith {i => (c*perCookie(i) - has(i)) max 0}\n missing <= k\n }\n\n io += bitBinSearch(canBake)\n }\n\n def bitBinSearch(f: Long => Boolean): Long = {\n var p = 0L\n var t = Long.MinValue >>> 1\n while (t > 0) {\n if (f(p|t)) p |= t\n t >>= 1\n }\n p\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}\n def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _670D2 extends CodeForcesApp {\n override def apply(io: IO) = {\n val n, k = io[Int]\n val perCookie, has = io[Vector, Long](n)\n\n val upperBound = 10 + ((has.sum + k)/perCookie.sum)\n\n def canBake(c: Long) = (c <= upperBound) && { //can bake c cookies?\n val missing = perCookie.indices.foldLeft(0L) {\n case (needed, i) => needed + (((perCookie(i)*c) - has(i)) max 0)\n }\n missing <= k\n }\n\n io += (bitBinSearch(canBake) getOrElse 0L) max 0L\n }\n\n def bitBinSearch(f: Long => Boolean): Option[Long] = {\n var p = 0L\n var n = Long.MinValue\n var t = n >>> 1\n while (t > 0) {\n if (f(p|t)) p |= t\n if (f(n|t)) n |= t\n t >>= 1\n }\n Seq(p, n) find f\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = t.head.ensuring(t.size == 1)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap\n def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}\n def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n def bitCount: Int = java.lang.Long.bitCount(x)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])\n }\n def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {\n override def apply(key: A) = getOrElseUpdate(key, f(key))\n }\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n val mod: Int = (1e9 + 7).toInt\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A](implicit read: IO.Read[A]): A = read.apply(this)\n def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine(): String = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n var separator = \" \"\n private[this] var isNewLine = true\n\n def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {\n write(this)(x)\n this\n }\n def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs\n\n def appendNewLine[A: IO.Write](x: A): this.type = {\n println()\n this += x\n }\n\n override def print(obj: String) = {\n if (isNewLine) isNewLine = false else super.print(separator)\n super.print(obj)\n }\n override def println() = if (!isNewLine) {\n super.println()\n isNewLine = true\n }\n override def close() = {\n flush()\n in.close()\n super.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r[C, A](r[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val boolean : Read[Boolean] = string.map(_.toBoolean)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r[A], r[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))\n }\n trait Write[-A] {\n def apply(out: PrintWriter)(x: A): Unit\n }\n trait DefaultWrite {\n implicit def any[A]: Write[A] = Write(_.toString)\n }\n object Write extends DefaultWrite {\n def apply[A](f: A => String) = new Write[A] {\n override def apply(out: PrintWriter)(x: A) = out.print(f(x))\n }\n implicit val boolean: Write[Boolean] = Write(b => if (b) \"YES\" else \"NO\")\n implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s\"$a $b\"}\n implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {\n override def apply(out: PrintWriter)(xs: Traversable[A]) = {\n xs foreach write(out)\n out.println()\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "\nimport scala.io.StdIn.readLine\n\nobject MagicPowder {\n\n def readInts(): Array[Int] = {\n readLine().split(\"\\\\s+\").map(s => s.toInt)\n }\n\n def readLongs(): Array[Long] = {\n readLine().split(\"\\\\s+\").map(s => s.toLong)\n }\n\n case class IngStep(index: Long, required: Long, lastStep: Long, remainder: Long)\n\n def getOneStepPrice(step: Long, ingStep:IngStep): Long = {\n if (step <= ingStep.lastStep)\n 0L // No need to use anything\n else\n if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {\n ingStep.required - ingStep.remainder // use is there is a reminder on this step\n } else {\n // If there is a remainder, we need 1 step less\n if (ingStep.remainder > 0) {\n (ingStep.required - ingStep.remainder) + (step - ingStep.lastStep - 1) * ingStep.required\n } else {\n // all the steps are the same\n (step - ingStep.lastStep) * ingStep.required\n }\n }\n }\n\n def getStepPrice(step: Long, ingSteps: IndexedSeq[IngStep]): Long = {\n ingSteps.foldRight(0L)((ingStep, t) => {\n t + getOneStepPrice(step, ingStep)\n })\n }\n\n def main(args: Array[String]): Unit = {\n val numberPowder = readLongs()\n\n val n = numberPowder(0)\n val p = numberPowder(1)\n\n val a = readLongs()\n val b = readLongs()\n\n val ingSteps = a.indices\n .map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i))))\n .sortBy(m => m.lastStep) // we now have i, steps sorted from lowest\n\n var startStep = 0L\n\n val fullPrice = getStepPrice(ingSteps.last.lastStep + 1, ingSteps) // Price to pay after everything is over\n\n var endStep = if (p >= fullPrice) ingSteps.last.lastStep + Math.ceil(p.toDouble / fullPrice).toLong else ingSteps.last.lastStep\n\n var stop = false\n var cookies = Math.max(startStep - 1, 0)\n\n while (!stop) {\n val mid = startStep + Math.ceil((endStep - startStep).toDouble / 2).toLong\n\n val stepPrice = getStepPrice(mid, ingSteps)\n cookies = mid\n\n if (stepPrice < p) {\n startStep = mid // Moving higher\n } else {\n endStep = mid // Moving lower\n }\n\n if (startStep == endStep) {\n stop = true\n } else if (startStep + 1 == endStep) {\n stop = true\n cookies = if (getStepPrice(endStep, ingSteps) <= p) endStep else startStep\n }\n }\n\n print(cookies)\n\n }\n}\n"}, {"source_code": "\nimport scala.io.StdIn.readLine\n\nobject MagicPowder {\n\n def readInts(): Array[Int] = {\n readLine().split(\"\\\\s+\").map(s => s.toInt)\n }\n\n case class IngStep(index: Long, required: Long, lastStep: Long, remainder: Long)\n\n def getOneStepPrice(step: Long, ingStep:IngStep): Long = {\n if (step <= ingStep.lastStep)\n 0L // No need to use anything\n else\n if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {\n ingStep.required - ingStep.remainder // use is there is a reminder on this step\n } else {\n // If there is a remainder, we need 1 step less\n if (ingStep.remainder > 0) {\n (ingStep.required - ingStep.remainder) + (step - ingStep.lastStep - 1) * ingStep.required\n } else {\n // all the steps are the same\n (step - ingStep.lastStep) * ingStep.required\n }\n }\n }\n\n def getStepPrice(step: Long, ingSteps: IndexedSeq[IngStep]): Long = {\n ingSteps.foldRight(0L)((ingStep, t) => {\n t + getOneStepPrice(step, ingStep)\n })\n }\n\n def main(args: Array[String]): Unit = {\n val numberPowder = readInts()\n\n val n = numberPowder(0)\n val p = numberPowder(1)\n\n val a = readInts()\n val b = readInts()\n\n val ingSteps = a.indices\n .map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i))))\n .sortBy(m => m.lastStep) // we now have i, steps sorted from lowest\n\n var startStep = 0L //Math.max(1, ingSteps.head.lastStep)\n\n val fullPrice = getStepPrice(ingSteps.last.lastStep + 1, ingSteps) // Price to pay after everything is over\n\n var endStep = if (p >= fullPrice) ingSteps.last.lastStep + Math.round(p / fullPrice) else ingSteps.last.lastStep\n\n var stop = false\n var cookies = Math.max(startStep - 1, 0)\n\n while (!stop) {\n// println(\"Start \" + startStep + \" end \" + endStep)\n val mid = startStep + Math.round((endStep - startStep) / 2)\n\n val stepPrice = getStepPrice(mid, ingSteps)\n cookies = mid\n\n if (stepPrice < p) {\n startStep = mid // Moving higher\n } else {\n endStep = mid // Moving lower\n }\n\n if (startStep == endStep) {\n stop = true\n } else if (startStep + 1 == endStep) {\n stop = true\n cookies = if (getStepPrice(endStep, ingSteps) <= p) endStep else startStep\n }\n }\n//114, 117\n// var step = Math.max(1, ingSteps.head.lastStep - 1) // no need to wait\n// var cookies = Math.max(step - 1, 0)\n// var pRemainder = p\n\n//\n// while(!stop) {\n// val stepPrice = getStepPrice(step, ingSteps)\n//\n// if (stepPrice <= pRemainder) {\n// cookies += 1\n// step += 1\n// } else {\n// stop = true\n// }\n// }\n\n print(cookies)\n\n }\n}\n"}, {"source_code": "\nimport scala.io.StdIn.readLine\n\nobject MagicPowder {\n\n def readInts(): Array[Int] = {\n readLine().split(\"\\\\s+\").map(s => s.toInt)\n }\n\n case class IngStep(index: Long, required: Long, lastStep: Long, remainder: Long)\n\n def getOneStepPrice(step: Long, ingStep:IngStep): Long = {\n if (step <= ingStep.lastStep)\n 0L // No need to use anything\n else\n if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {\n ingStep.required - ingStep.remainder // use is there is a reminder on this step\n } else {\n // If there is a remainder, we need 1 step less\n if (ingStep.remainder > 0) {\n (ingStep.required - ingStep.remainder) + (step - ingStep.lastStep - 1) * ingStep.required\n } else {\n // all the steps are the same\n (step - ingStep.lastStep) * ingStep.required\n }\n }\n }\n\n def getStepPrice(step: Long, ingSteps: IndexedSeq[IngStep]): Long = {\n ingSteps.foldRight(0L)((ingStep, t) => {\n t + getOneStepPrice(step, ingStep)\n })\n }\n\n def main(args: Array[String]): Unit = {\n val numberPowder = readInts()\n\n val n = numberPowder(0)\n val p = numberPowder(1)\n\n val a = readInts()\n val b = readInts()\n\n val ingSteps = a.indices\n .map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i))))\n .sortBy(m => m.lastStep) // we now have i, steps sorted from lowest\n\n var startStep = 0L\n\n val fullPrice = getStepPrice(ingSteps.last.lastStep + 1, ingSteps) // Price to pay after everything is over\n\n var endStep = if (p >= fullPrice) Math.round(ingSteps.last.lastStep + Math.ceil(p / fullPrice)) else ingSteps.last.lastStep\n\n var stop = false\n var cookies = Math.max(startStep - 1, 0)\n\n while (!stop) {\n val mid = startStep + Math.round(Math.ceil((endStep - startStep) / 2))\n\n val stepPrice = getStepPrice(mid, ingSteps)\n cookies = mid\n\n if (stepPrice < p) {\n startStep = mid // Moving higher\n } else {\n endStep = mid // Moving lower\n }\n\n if (startStep == endStep) {\n stop = true\n } else if (startStep + 1 == endStep) {\n stop = true\n cookies = if (getStepPrice(endStep, ingSteps) <= p) endStep else startStep\n }\n }\n//114, 117\n// var step = Math.max(1, ingSteps.head.lastStep - 1) // no need to wait\n// var cookies = Math.max(step - 1, 0)\n// var pRemainder = p\n\n//\n// while(!stop) {\n// val stepPrice = getStepPrice(step, ingSteps)\n//\n// if (stepPrice <= pRemainder) {\n// cookies += 1\n// step += 1\n// } else {\n// stop = true\n// }\n// }\n\n print(cookies)\n\n }\n}\n"}], "src_uid": "ab1b4487899609ac0f882e1b1713d162"} {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val n = lines.next().toInt\n val prices = lines.next().split(' ').map(_.toInt)\n val q = lines.next().toInt\n val queries = lines.take(q).map(_.toInt).toArray\n\n def calcDict(prices: Array[Int], i: Int, queries: Array[Int], j: Int, map: Map[Int, Int]): Map[Int, Int] = {\n if (i == prices.length || j == queries.length) map\n else if (prices(i) > queries(j)) calcDict(prices, i + 1, queries, j, map)\n else calcDict(prices, i, queries, j + 1, map + (queries(j) -> (prices.length - i)))\n }\n\n val d = calcDict(prices.sorted.reverse, 0, queries.sorted.reverse, 0, Map.empty[Int, Int].withDefault(_ => 0))\n println(queries.map(d).mkString(\"\\n\"))\n}", "positive_code": [{"source_code": "object B706 {\n\n import IO._\n val MAX = 100000\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = readInts(n)\n val cnt = Array.fill(MAX+1)(0)\n for(i <- in) {\n cnt(i) += 1\n }\n for(i <- 2 to MAX) {\n cnt(i) += cnt(i-1)\n }\n val Array(q) = readInts(1)\n for(_ <- 0 until q) {\n var Array(m) = readInts(1)\n if(m > MAX)\n m = MAX\n println(cnt(m))\n }\n\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _706B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val shops = read[Vector[Int]].sorted\n\n def binarySearch(x: Int, l: Int = 0, r: Int = shops.length): Int = {\n if (l >= r) {\n l\n } else {\n val m = (l + r)/2\n //debug(x, l, r, m, shops(m))\n if(shops(m) <= x) {\n binarySearch(x, m+1, r)\n } else {\n binarySearch(x, l, m)\n }\n }\n }\n\n repeat(read[Int]) {\n val money = read[Int]\n val ans = binarySearch(money)\n io.writeOnNextLine(ans)\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _706B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val shops = read[Vector[Int]].sorted\n val money = read[Vector[Int]]\n\n @tailrec\n def binarySearch(x: Int, l: Int = 0, r: Int = shops.length): Int = if (l == r) {\n l\n } else {\n val m = (l + r)/2\n if(shops(m) <= x) binarySearch(x, m + 1, r) else binarySearch(x, l, m)\n }\n\n val ans = money.map(x => binarySearch(x))\n io.writeAll(ans, separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "//296 мс 38900 \nobject Main extends App {\n import scala.io._\n val input = Source.stdin\n val inputit:Iterator[String] = input.getLines()\n var lineit:Iterator[String] = List.empty.iterator\n def rs() : String = {\n if (lineit.hasNext) lineit.next\n else { \n lineit = inputit.next.split(\" \").iterator\n rs()\n }\n }\n def ri(): Int = rs().toInt\n val n = ri()\n val x = Array.fill(n)(ri())\n val m = x.max\n val c = Array.fill(m + 1)(0)\n x.foreach(i => c(i) += 1)\n val d = Array.fill(m + 1)(0)\n for(i <- 1 to m) {\n d(i) = c(i) + d(i-1)\n }\n\n val q = ri()\n println((for(i <- 1 to q) yield {\n val t = ri()\n if (t > m) n else d(t)\n }).mkString(\"\\n\"))\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val n = readInt()\n val X = readLine().split(\" \").map(_.toInt).sorted\n val q = readInt()\n 1 to q foreach { _ =>\n val m = readInt()\n if (m < X(0)) println(0)\n else if (m >= X.last) println(n)\n else println(findIdx(m) + 1)\n }\n\n def findIdx(price: Int): Int = {\n var left = 0\n var right = X.length - 1\n while (left < right) {\n val m = (left + right) / 2\n if (price >= X(m)) {\n left = m + 1\n } else {\n right = m\n }\n }\n\n if (X(right) == price) right\n else right - 1\n }\n}\n"}], "negative_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _706B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val shops = read[Array[Int]].sorted\n repeat(read[Int]) {\n val money = read[Int]\n var ans = java.util.Arrays.binarySearch(shops, money) max -1\n ans += 1\n while(ans < shops.length && shops(ans) == money) {\n ans += 1\n }\n io.writeOnNextLine(ans)\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _706B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val shops = read[Vector[Int]].sorted\n\n def binarySearch(x: Int, l: Int = 0, r: Int = shops.length-1): Int = {\n if (l >= r) {\n var ans = r\n while(ans < shops.length && shops(ans) == x) {\n ans += 1\n }\n ans\n } else {\n val m = (l + r)/2\n //debug(x, l, r, m, shops(m))\n if(shops(m) <= x) {\n binarySearch(x, m+1, r)\n } else {\n binarySearch(x, l, m)\n }\n }\n }\n\n repeat(read[Int]) {\n val money = read[Int]\n val ans = binarySearch(money)\n io.writeOnNextLine(ans)\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _706B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val shops = read[Vector[Int]].sorted\n\n def binarySearch(x: Int, l: Int = 0, r: Int = shops.length-1): Int = {\n if (l >= r) {\n if (shops(r) == x) 1+r else r\n } else {\n val m = (l + r)/2\n //debug(x, l, r, m, shops(m))\n if(shops(m) <= x) {\n binarySearch(x, m+1, r)\n } else {\n binarySearch(x, l, m)\n }\n }\n }\n\n repeat(read[Int]) {\n val money = read[Int]\n val ans = binarySearch(money)\n io.writeOnNextLine(ans)\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _706B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val shops = read[Array[Int]].sorted\n repeat(read[Int]) {\n val money = read[Int]\n val ans = (java.util.Arrays.binarySearch(shops, money) max -1)\n io.writeOnNextLine(ans + 1)\n }\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "80a03e6d513f4051175cd5cd1dea33b4"} {"source_code": "/*\nD. Параллельное программирование\nограничение по времени на тест\n2 секунды\nограничение по памяти на тест\n256 мегабайт\nввод\nstandard input\nвывод\nstandard output\n\nУ Поликарпа есть компьютер с n процессорами. Также в его компьютере есть n ячеек памяти. Будем считать, что процессоры пронумерованы целыми числами от 1 до n и что ячейки памяти последовательно пронумерованы целыми числами от 1 до n.\n\nПоликарпу нужно разработать модель параллельной программы, которая для каждой ячейки памяти с номером i записывает в эту ячейку значение n - i. Другими словами, для каждой ячейки требуется найти расстояние до ячейки n.\n\nОбозначим, записанное в i-той ячейке значение как ai. Изначально, ai = 1 (1 ≤ i < n) и an = 0. Будем считать, что в ячейку памяти номер i может записывать значения только лишь процессор i. Читать значение ячейки может любой процессор (несколько разных процессоров могут читать значение из ячейки одновременно).\n\nИсполнение параллельной программы происходит в несколько шагов. На каждом шаге происходит выполнение параллельной версии операции инкремента. Выполнение параллельной операции инкремента происходит следующим образом:\n\n Каждый процессор независимо от других выбирает некоторую ячейку памяти. Пусть процессор i выбрал ячейку с номером ci (1 ≤ ci ≤ n).\n Все процессоры одновременно выполняют операцию, ai = ai + aci. \n\nПомогите Поликарпу разработать модель параллельной программы, которая выполняется ровно в k шагов. Вычислите, какие операции нужно выполнить, чтобы после ровно k шагов для всех i значение ai было равно n - i.\nВходные данные\n\nВ первой строке записаны через пробел два целых числа n и k (1 ≤ n ≤ 104, 1 ≤ k ≤ 20).\n\nГарантируется, что при заданных n и k требуемая последовательность операций существует.\nВыходные данные\n\nВыведите ровно n·k целых чисел в k строках. В первой строке выведите номера c1, c2, ..., cn (1 ≤ ci ≤ n) для первой операции инкремента. Во второй — выведите номера для второй операции инкремента. В k-ой — выведите номера для k-ой операции инкремента.\n\nВ результате выведенных операций для любого i значение ai должно быть равно n - i.\nПримеры тестов\nВходные данные\n\n1 1\n\nВыходные данные\n\n1\n\nВходные данные\n\n3 2\n\nВыходные данные\n\n2 3 3\n3 3 3\n*/\nimport scala.collection.immutable.BitSet\nimport scala.collection.mutable.MutableList\nimport scala.collection.mutable.HashSet\n\nobject Task4 extends App {\n\n def pow2(p: Int): Int = {\n require(p < 30)\n 1 << p\n }\n\n /** Finds sequence of parallel increments in k steps */\n def solve(n: Int, k: Int): Seq[Seq[Int]] = {\n val preNormalized = (1 to k) map (step => getStep(n)(step))\n val res = preNormalized map (_.reverse map (n - _))\n res\n } ensuring (_.size == k)\n\n def getStep(n: Int)(step: Int): Seq[Int] = {\n val stream =\n if (step == 0) {\n 0 #:: Stream.from(1, 0)\n } else {\n val inPos = 1 + pow2(step - 1)\n val last = pow2(step)\n (Stream fill inPos)(0) ++ (1 to last).toStream ++ Stream.from(last, 0)\n }\n stream take n toIndexedSeq\n }\n\n val (n, k) = {\n val l = readLine split (' ') map (_.toInt)\n (l(0), l(1))\n }\n val ipStrs = for (i <- 0 until n) yield readLine\n\n val res = solve(n, k)\n res map (line => println(line mkString \" \"))\n}", "positive_code": [{"source_code": "import collection.mutable\nimport java.util.Scanner\n\nobject D {\n def main(args: Array[String]) {\n val in = new Scanner(System.in)\n val n = in.nextInt()\n val k = in.nextInt()\n for (i <- 0 until k) {\n for (j <- 0 until n) {\n if (j != (n - 1) && (((n - j - 2) >> i) & 1) != 0) {\n print(n - (1 << i))\n } else {\n print(n)\n }\n if (j < n - 1) {\n print(\" \")\n } else {\n println()\n }\n }\n }\n }\n}"}, {"source_code": "import io.Source\nimport java.io.PrintWriter\n\nobject CF291D {\n\n def solve(in: In, out: PrintWriter) {\n val n, k = in().toInt\n val a = Array.tabulate(n)(i => if (i == n - 1) 0 else 1)\n for (it <- 0 until k) {\n val vs = Array.fill(n + 1)(-1)\n for (i <- 0 until n) {\n vs(a(i)) = i\n }\n val max = a.max\n for (i <- 0 until n) {\n var j = math.min(max, n - i - 1 - a(i))\n while (vs(j) == -1) {\n j -= 1\n }\n out.print((vs(j) + 1) + \" \")\n a(i) += j\n }\n out.println()\n }\n }\n\n def main(args: Array[String]) {\n val in: In = new In(Source.fromInputStream(System.in))\n val out: PrintWriter = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() {\n while (iter.hasNext && delims.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next(): String = {\n skipDelims()\n while (iter.hasNext && delims.indexOf(iter.head) == -1) {\n sb.append(iter.next())\n }\n val ret = sb.toString()\n sb.clear()\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIterator = new TokenIterator(iter, \" \\r\\n\")\n\n val lineIterator = new TokenIterator(iter, \"\\r\\n\")\n\n def apply() = tokenIterator.next()\n\n def apply(n: Int) = tokenIterator.take(n)\n }\n}"}, {"source_code": "object D {\n def READ: Array[Int] = readLine() split (\" \") map (_.toInt);\n def main(args: Array[String]) {\n var Array(n,k) = READ\n val p = math.ceil(math.log(n)/math.log(2)).toInt\n for (i <- 1 to p) {\n val cnt = 1+math.pow(2, i-1).toInt;\n println(((cnt to n) ++ Array.fill(cnt-1)(n)) mkString(\" \"));\n }\n val arr = Array.fill(n)(n).mkString(\" \");\n for (i <- p+1 to k) println(arr)\n }\n}"}], "negative_code": [], "src_uid": "c8800840e52d4141acdff0420e7ec73c"} {"source_code": "import java.util\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m, l) = readInts(3)\n val as = readInts(n)\n\n val t = new util.TreeMap[Int, Int]()\n var segmentStart = -1\n for (i <- 0 until n) {\n if (as(i) > l) {\n if (segmentStart < 0) segmentStart = i\n t.put(segmentStart, i)\n } else {\n segmentStart = -1\n }\n }\n\n var count = t.size()\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (_ <- 1 to m) {\n val s = readLine\n if (s == \"0\") {\n println(count)\n } else {\n val Array(_, _p, d) = s.split(\" \").map(_.toInt)\n val p = _p - 1\n if (as(p) <= l) {\n as(p) += d\n if (as(p) > l) {\n val left = t.floorEntry(p)\n val right = t.ceilingEntry(p)\n if (left != null && left.getValue + 1 == p) {\n if (right != null && right.getKey - 1 == p) {\n t.remove(right.getKey)\n t.replace(left.getKey, right.getValue)\n count -= 1\n } else {\n t.replace(left.getKey, p)\n }\n } else if (right != null && right.getKey - 1 == p) {\n t.remove(right.getKey)\n t.put(p, right.getValue)\n } else {\n t.put(p, p)\n count += 1\n }\n }\n }\n }\n }\n\n Console.flush\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M, L = ni()\n val A = nal(N)\n\n val over = Array.ofDim[Boolean](N)\n var cnt = 0\n def add(i: Int): Unit = {\n over(i) = true\n val l = i > 0 && over(i - 1)\n val r = i < N - 1 && over(i + 1)\n if (l && r) cnt -= 1\n else if (!l && !r) cnt += 1\n }\n rep(N) { i =>\n if (A(i) > L) {\n add(i)\n }\n }\n\n rep(M) { _ =>\n ni() match {\n case 0 => out.println(cnt)\n case 1 =>\n val p = ni() - 1\n val d = ni()\n if (A(p) <= L && A(p) + d > L) {\n add(p)\n }\n A(p) += d\n }\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, M, L = ni()\n val A = nal(N)\n\n var cnt = 0\n def add(i: Int): Unit = {\n val l = i > 0 && A(i - 1) > L\n val r = i < N - 1 && A(i + 1) > L\n if (l && r) cnt -= 1\n else if (!l && !r) cnt += 1\n }\n rep(N) { i =>\n if (A(i) > L) {\n add(i)\n }\n }\n\n rep(M) { _ =>\n ni() match {\n case 0 => out.println(cnt)\n case 1 =>\n val p = ni() - 1\n val d = ni()\n if (A(p) <= L && A(p) + d > L) {\n add(p)\n }\n A(p) += d\n }\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n import java.io.PrintStream\n\n def main(args: Array[String]): Unit = {\n val s = new Main()\n val ps = new PrintStream(Console.out)\n Console.withOut(ps) {\n s.solve()\n }\n ps.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n import scala.Console\n\n val MOD = 1000000007\n\n def solve(): Unit = {\n val N, M, L = ni()\n val A = na(N)\n\n val over = mutable.Set[Int]()\n var cnt = 0\n def add(i: Int): Unit = {\n over += i\n val l = over.contains(i - 1)\n val r = over.contains(i + 1)\n if (l && r) cnt -= 1\n else if (!l && !r) cnt += 1\n }\n rep(N) { i =>\n if (A(i) > L) {\n add(i)\n }\n }\n\n rep(M) { _ =>\n ni() match {\n case 0 => println(cnt)\n case 1 =>\n val p = ni() - 1\n val d = ni()\n if (A(p) <= L && A(p) + d > L) {\n add(p)\n }\n A(p) += d\n }\n }\n }\n\n\n class InputReader(reader: BufferedReader) {\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(Console.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "1e17039ed5c48e5b56314a79b3811a40"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val std = scala.io.StdIn\n val n = std.readInt()\n val s : Array[Int] = std.readLine().split(\" \").map( _.toInt )\n\n\n def f( i : Int ) : (Int,Int) = {\n if ( i * 2 - 2 > s.length ) {\n (0,0)\n }\n else {\n val res1 = f( i * 2 )\n val res2 = f( i * 2 + 1 )\n\n val path1 = if ( i * 2 - 2 < s.length ) res1._2 + s(i * 2 -2) else 0\n val path2 = if ( i * 2 - 1 < s.length ) res2._2 + s(i * 2 -1 ) else 0\n\n val add = Math.abs(path1 - path2 )\n val pathForBoth = Math.max( path1, path2 )\n\n //println( i, add, pathForBoth )\n\n ( res1._1 + res2._1 + add, pathForBoth )\n }\n\n }\n\n println( f(1)._1 )\n\n\n }\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = Array(0) ++ readInts((2 << n) - 2)\n\n var total = 0L\n\n for (layer <- n - 1 to 0 by -1) {\n val l = (1 << layer)\n val r = (2 << layer) - 1\n for (i <- l to r) {\n val u = 2 * i - 1\n val v = u + 1\n val min = as(u) min as(v) \n val max = as(u) max as(v)\n val add = max - min\n total += add\n as(u / 2) += max\n }\n }\n \n println(total)\n}\n"}], "negative_code": [], "src_uid": "ae61e1270eeda8c30effc9ed999bf531"} {"source_code": "object C extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n// val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val n = in.nextInt()\n\n n.times {\n val m = in.nextInt()\n val d = in.nextInt()\n\n val temLine = in.line()\n // println(temLine)\n val line = \"1\" + (\"0\" * d) + temLine + (\"0\" * d) + \"1\"\n // println(line)\n\n val tableStr = line.split(\"\").map(_.toInt)\n // printArr(tableStr)\n\n var r = 0\n var wasLast1 = false\n var last1Index = 1\n for ((element, i) <- tableStr.zipWithIndex) {\n if (element == 1 && wasLast1) {\n val diff = (i + 1) - last1Index\n val l = findD(diff - 1, d)\n // println(s\"L: ****************** = $l $last1Index ${i + 1}\")\n r = r + l\n last1Index = i + 1\n } else if (element == 1) {\n wasLast1 = true\n last1Index = i + 1\n }\n }\n // println(\"Result: =>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=> \" + r)\n println(r)\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n def findD(n: Int, d: Int): Int = {\n // println(\"............\")\n // println(n, d)\n val base = (2 * d) + 1\n val reminder = n - base\n if (reminder >= 0) {\n // println(base)\n // println(reminder)\n // println((reminder / (d + 1)))\n val resu = (reminder / (d + 1)) + 1\n // println(\"............\")\n resu\n } else {\n 0\n }\n\n }\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n", "positive_code": [{"source_code": "//package codeforces.contests._1367\n\nobject _3 {\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n\n val Array(n, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n val arr = io.StdIn.readLine.zipWithIndex\n\n val occupied = arr.collect { case (c, i) if c == '1' => i + 1 }.toVector\n\n println {\n if (occupied.isEmpty)\n (1 to n by k + 1).size\n else {\n val first = occupied.head\n val last = occupied.last\n\n val a = (1 until first by k + 1).count(_ + k < first)\n val b = occupied.sliding(2).map { case Vector(x, y) => (x + k + 1 until y).by(k + 1).count(_ + k < y); case _ => 0 }.sum\n val c = (last + k + 1 to n by k + 1).size\n a + b + c\n }\n }\n }\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nk = readIntLine()\n val l = readLine().toCharArray.map(_ == '1').toList\n handle(l, nk.last)\n }\n }\n\n def handle(list: List[Boolean], k: Int): Unit = {\n def helper(l: List[Boolean], prevDist: Int, acc: Int): Int = l match {\n case Nil => acc\n case b :: bs => if (b) if (prevDist < k) helper(bs, 0, acc - 1) else helper(bs, 0, acc)\n else if (prevDist < k) helper(bs, prevDist + 1, acc) else helper(bs, 0, acc + 1)\n }\n\n println(helper(list, k, 0))\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 1 to t) {\n val tmp = StdIn.readLine().split(\" \").map(_.toInt)\n val (n, k) = (tmp(0), tmp(1))\n var str = StdIn.readLine()\n val blocks = str.split(\"1\").filter(_.length>0)\n\n var i = 0\n var res = 0\n for (b <- blocks) {\n if (i == 0 && str.startsWith(\"0\")) {\n res += (b.length / (k+1))\n } else if (i == blocks.length - 1 && str.endsWith(\"0\")) {\n res += (b.length / (k+1))\n } else {\n res += math.max(0, (b.length - k) / (k+1))\n }\n i += 1\n }\n if (str.forall(ch => ch == '0') && str.length % (k+1) > 0) res += 1\n println(res)\n }\n }\n}\n"}, {"source_code": "object C extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val sn = readLine().split(\"\").map(_.toInt)\n\n val (ans, _) = (sn.zipWithIndex.collect { case (x, i) if x == 1 => i } :+ (n + k)).foldLeft((0, -k - 1)) {\n case ((c, l), r) =>\n (c + (r - l - 1 - k).max(0) / (k + 1), r)\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "object Main extends App {\n val r = new FastScanner(java.lang.System.in)\n val o = new java.io.PrintWriter(java.lang.System.out)\n for(_ <- 1 to r.nextInt()) {\n val n = r.nextInt()\n val mindist = r.nextInt()\n val s = r.nextToken(n)\n def f(x: Int, prefix: Boolean, suffix: Boolean): Int = {\n var t = x\n if(prefix) t += mindist\n if(suffix) t += mindist \n if(t <= mindist) 0\n else ((t + 1) / (mindist + 1)) - 1\n }\n def loop(k: Int, t: Int, ans: Int): Int = {\n if(k == n) {\n if(t > 0) ans + f(t, t == n, true) else ans \n } else if(s(k) == '1') {\n loop(k + 1, 0, ans + f(t, t == k, false))\n } else {\n loop(k + 1, t + 1, ans)\n }\n }\n o.println(loop(0, 0, 0))\n }\n o.close()\n}\n\nimport scala.annotation.tailrec\nimport scala.collection.mutable.StringBuilder\n\nobject FastScanner {\n val zero = 0.toByte\n val cr = '\\r'.toByte\n val nl = '\\n'.toByte\n val BUFFER_SIZE = 0x10000\n}\n\nclass FastScanner(private val input: java.io.InputStream) {\n private val b = new Array[Byte](FastScanner.BUFFER_SIZE)\n private var n = 0\n private var pos = 0\n private var eof = false\n private def read ():Boolean = {\n if (eof) {\n return false\n }\n pos = 0\n n = input.read(b)\n if (n < 0) {\n eof = true\n }\n n > 0\n }\n private def nextByte(): Byte = {\n if (pos >= n && !read ()) {\n 0\n } else {\n val r = b(pos)\n pos += 1\n r\n }\n }\n def nextToken(k: Int = -1): String = {\n val sb = if(k >= 0) new StringBuilder(k) else new StringBuilder()\n var b = skipBlanks()\n assert(b > 0)\n while(b > 32) {\n sb.append(b.toChar)\n b = nextByte()\n }\n //sb.append('1')\n sb.toString\n }\n @tailrec\n private def skipBlanks(): Byte = {\n val b = nextByte()\n if(b > 32 || b < 1) b else skipBlanks()\n }\n def nextInt():Int = {\n val b = skipBlanks()\n @tailrec\n def f(t: Int): Int = {\n val b = nextByte ()\n if (b <= 32) t else f(10 * t + (b - 48))\n }\n require(b > 0)\n if (b < 48) -f(0) else f(b - 48)\n }\n}\n\n"}], "negative_code": [{"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 1 to t) {\n val tmp = StdIn.readLine().split(\" \").map(_.toInt)\n val (n, k) = (tmp(0), tmp(1))\n var str = StdIn.readLine()\n val blocks = str.split(\"1\").filter(_.length>0)\n\n var i = 0\n var res = 0\n for (b <- blocks) {\n if (i == 0 && str.startsWith(\"0\")) {\n res += (b.length / (k+1))\n } else if (i == blocks.length - 1 && str.endsWith(\"0\")) {\n res += (b.length / (k+1))\n } else {\n res += math.max(0, (b.length - k) / (k+1))\n }\n i += 1\n }\n if (str.forall(ch => ch == '0') && str.length < k+1) res += 1\n println(res)\n }\n }\n}\n"}], "src_uid": "fd85ebe1dc975a71c72fac7eeb944a4a"} {"source_code": "object C extends App {\n \n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val (i, j) = (k / (n - 1), k % (n - 1))\n val rs = i * n + (if (j == 0) j - 1 else j)\n println(rs)\n }\n}", "positive_code": [{"source_code": "object _1352C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val n, k = io.read[Long]\n val ans = if ((k*n)%(n-1) == 0) {\n (k * n)/(n - 1) - 1\n } else {\n (k * n)/(n - 1)\n }\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Collection Utils]****************************************/\nobject Utils {\n import scala.collection.mutable\n\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n val charToInt: Char => Int = Character.getNumericValue\n val intToChar: Int => Char = Character.forDigit(_, 10)\n\n implicit class GenericExtensions[A](a: A) {\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n\n def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {\n val freqTable = t.groupBy(identity).mapValues(_.size)\n if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable\n }\n }\n\n implicit class PairExtensions[A, B](p: (A, B)) {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))\n }\n\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())\n }\n\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {\n def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m\n }\n\n implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n\n implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n\n implicit class IntExtensions(val x: Int) extends AnyVal {\n @inline def isEven = x%2 == 0\n @inline def isOdd = x%2 == 1\n }\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n\n def map[K] = new {\n def to[V](default: => V): mutable.Map[K, V] = using(_ => default)\n def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n\n def memoize[A, B](f: A => B): A => B = map[A] using f\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\n\nobject Test extends App {\n\n val s = StdIn.readLine().toInt\n (1 to s).foreach{_ =>\n var arr = StdIn.readLine().split(\" \").map(_.toInt)\n val n = arr(0)\n val k = arr(1)\n\n val ans = ListBuffer.empty[Int]\n var l: Long = 1\n var r: Long = 100000000000L\n while (Math.abs(r - l) > 1){\n var mid: Long = (r + l) / 2L\n val x: Long = mid / n\n val y: Long = mid - x\n if(y == k && mid % n != 0){\n l = mid\n r = mid\n }else if (y < k){\n l = mid\n }else{\n r = mid\n }\n }\n println(l)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject C {\n\n def solution(n: Int, k: Int): Int = k + (k - 1) / (n - 1)\n\n def main(args: Array[String]): Unit = {\n for (_ <- (0 until StdIn.readLine.toInt)) {\n val Seq(n, k) = StdIn.readLine.split(\" \").toSeq.map(_.toInt)\n println(solution(n, k))\n }\n }\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C640B(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val n = ni()\n val k = ni()\n\n val gap = n - 1\n\n val r =if(k % gap == 0) - 1 else k % gap\n val x = k / gap\n out.println(x * n + r)\n }\n }\n}\n"}, {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val (i, j) = (k / (n - 1), k % (n - 1))\n val ans = i * n + (if (j == 0) j - 1 else j)\n\n println(ans)\n }\n}\n"}, {"source_code": "object C extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val ans = k + (k - 1) / (n - 1)\n\n println(ans)\n }\n}\n"}], "negative_code": [], "src_uid": "7d6f76e24fe9a352beea820ab56f03b6"} {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject Codeforces extends App {\n val Array(n, k) = readLine split ' ' map(_.toLong)\n val players = readLine split ' ' map(_.toInt)\n val window = math.min(n, k)\n val queue = mutable.Queue[Int](players: _*)\n var current = queue.dequeue()\n var winCount = 0\n while (queue.nonEmpty && winCount < window) {\n for (_ <- 1L to window) {\n if (winCount < window) {\n val player = queue.dequeue()\n if (player < current) {\n winCount += 1\n queue.enqueue(player)\n }\n else {\n winCount = 1\n queue.enqueue(current)\n current = player\n }\n }\n }\n }\n println(current)\n}", "positive_code": [{"source_code": "object _879B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val n = io.read[Int]\n val k = io.read[Long]\n val powers = io.read[List, Int](n)\n val best = powers.max\n\n @tailrec\n def fight(players: List[Int], wins: Int): Int = {\n players match {\n case p1 :: ps if wins >= k || p1 == best => p1\n case p1 :: p2 :: ps if p1 > p2 => fight(players = p1 :: (ps :+ p2), wins = wins + 1)\n case p1 :: p2 :: ps if p1 < p2 => fight(players = p2 :: (ps :+ p1), wins = 1)\n }\n }\n\n val ans = fight(players = powers, wins = 0)\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def getBit(i: Int): Int = (x >> i) & 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def getBit(i: Int): Long = (x >> i) & 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative.getOrElse(f) //e.g. students.indexOf(\"Greg\").whenNegative(Int.MaxValue)\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "object _879B extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO): io.type = {\n val n = io.read[Int]\n val k = io.read[Long]\n val powers = io.read[List, Int](n)\n val best = powers.max\n\n @tailrec\n def fight(players: List[Int], wins: Int): Int = {\n players match {\n case p1 :: ps if wins >= k || p1 == best => p1\n case p1 :: p2 :: ps if p1 > p2 => fight(players = p1 :: (ps :+ p2), wins = wins + 1)\n case p1 :: p2 :: ps if p1 < p2 => fight(players = p2 :: (ps :+ p1), wins = 0)\n }\n }\n\n val ans = fight(players = powers, wins = 0)\n io.write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"Yes\" else \"No\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "src_uid": "8d5fe8eee1cce522e494231bb210950a"} {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n, m = nextInt\n val s, t = nextLine.split(\" \")\n val q = nextInt\n\n for (_ <- 1 to q) {\n val y = nextInt - 1\n val j = y % n\n val i = y % m\n val res = s(j) + t(i)\n out.println(res)\n }\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject NewYearAndNaming extends App {\n\n val l1 = StdIn.readLine().split(\" \")\n val n = l1(0).toInt\n val m = l1(1).toInt\n\n val s = StdIn.readLine().split(\" \")\n val t = StdIn.readLine().split(\" \")\n\n val q = StdIn.readLine().toInt\n\n for (i <- 1 to q) {\n val year = StdIn.readLine().toInt\n if (i == q) {\n print(impl(s, t, n, m, year))\n } else {\n println(impl(s, t, n, m, year))\n }\n }\n\n def impl(s: Array[String], t: Array[String], n: Int, m: Int, year: Int): String = {\n val sIndex = year % n match {\n case 0 => n - 1\n case notZero => notZero - 1\n }\n\n val tIndex = year % m match {\n case 0 => m - 1\n case notZero => notZero - 1\n }\n\n s(sIndex) + t(tIndex)\n }\n}\n"}, {"source_code": "object S extends App {\n val lengths = readLine().split(' ').map(_.toInt)\n val arr1 = readLine().split(' ')\n val arr2 = readLine().split(' ')\n val cnt = readLine().toInt\n\n 1.to(cnt).map(_ => readLine().toInt).foreach {year =>\n val (ind1, ind2) = ((year - 1) % lengths(0), (year - 1) % lengths(1))\n val res = arr1(ind1) + arr2(ind2)\n System.out.println(res)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Codeforces1284A extends App {\n StdIn.readLine()\n val s = StdIn.readLine().split(\"\\\\s+\")\n val t = StdIn.readLine().split(\"\\\\s+\")\n var q = StdIn.readLine().toInt\n while (q > 0) {\n val y = StdIn.readLine().toLong - 1\n println(s((y % s.length).toInt) + t((y % t.length).toInt))\n q -= 1\n }\n}\n"}], "negative_code": [], "src_uid": "efa201456f8703fcdc29230248d91c54"} {"source_code": "import scala.collection.Set\n\nobject Multithreading extends App {\n\n val t = readInt //num tests\n val threads = readLine.split(' ').map(_.toInt)\n\n var i = t - 1;\n while (i > 0 && threads(i) > threads(i - 1)) {\n i -= 1\n }\n println(i)\n}\n", "positive_code": [{"source_code": "object cf165b extends App {\n val n = readLine.toInt\n val arr = readLine.split(' ').map(_.toInt).reverse.toList\n println(n - (arr zip ((n + 2) :: arr)).span(p => p._1 < p._2)._1.length)\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n println(n - 1 - in.next().split(' ').map(_.toInt - 1).reverse.sliding(2).takeWhile(i => i.last < i.head).length)\n}"}, {"source_code": "import collection.mutable.Queue\n\nobject test6 extends App {\n val n=readLine.toInt\n val a=readLine.split(\" \").map(_.toInt)\n var i=a.length-2\n while(i>=0 && a(i) t(0) > t(1) ).size\n println(r)\n }\n}"}], "negative_code": [{"source_code": "object cf165b extends App {\n val n = readLine.toInt\n val arr = readLine.split(' ').map(_.toInt).reverse.toList\n println((arr zip ((n + 2) :: arr)).span(p => p._1 < p._2)._1.length)\n}"}, {"source_code": "object cf165b extends App {\n val n = readLine.toInt\n var ans = 0\n var arr = Array.ofDim[Boolean](n + 1)\n var nxt = 1\n readLine.split(' ').map(_.toInt).map { i =>\n arr(i) = true\n if (nxt != i) ans += 1\n while (nxt <= n && arr(nxt)) nxt += 1\n }\n println(ans)\n}"}, {"source_code": "object cf165b extends App {\n val n = readLine.toInt\n var ans = 0\n var arr = Array.ofDim[Boolean](n + 1)\n var nxt = 1\n def ans(xs: List[Int]): Int = {\n if (xs.isEmpty) 0 else {\n val (ys, m :: zs) = xs.span(_ != xs.min)\n ys.length + ans(zs)\n }\n }\n readLine.split(' ').map(_.toInt).map { i =>\n arr(i) = true\n if (nxt < i) ans += 1\n while (nxt <= n && arr(nxt)) nxt += 1\n }\n println(ans)\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n println(in.next().split(' ').map(_.toInt - 1).reverse.sliding(2).takeWhile(i => i.last < i.head).length)\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val visited = Array.ofDim[Boolean](n)\n val line = in.next().split(' ').map(_.toInt - 1).foldLeft(0, 0) {\n case ((k, sum), el) if el == k =>\n visited(el) = true\n ((k + 1 until n).find(i => !visited(i)).getOrElse(-1), sum)\n case ((k, sum), el) if el > k =>\n visited(el) = true\n (k, sum + 1)\n case ((k, sum), el) =>\n visited(el) = true\n (k, sum)\n }\n println(line._2)\n}"}, {"source_code": "import collection.mutable.Queue\n\nobject test6 extends App {\n val n=readLine.toInt\n val a=readLine.split(\" \").map(_.toInt)\n var count=0\n var i=0\n while(a(i)!=1) {count+=1;i+=1}\n println(count)\n} \n\n\n"}, {"source_code": "object Main {\n\n class Node(val value: Int) {\n var left: Option[Node] = None\n var right: Option[Node] = None\n \n def leftCount: Int = \n Seq(left.map(_.leftCount), right.map(_.leftCount), left.map(_ => 1)).flatten.sum\n \n def add(node: Node) {\n if (node.value < this.value) {\n left match {\n case None => left = Some(node)\n case Some(n0) => n0.add(node)\n }\n } else {\n right match {\n case None => right = Some(node)\n case Some(n0) => n0.add(node)\n }\n }\n }\n \n def add(ls: TraversableOnce[Int]) {\n for(i <- ls) {\n val node = new Node(i)\n this.add(node)\n }\n }\n }\n \n object Tree {\n private var root: Option[Node] = None\n \n def add(ls: Array[Int]) {\n val rs = if (root == None) {\n root = Some(new Node(ls.head))\n ls.tail\n } else ls\n root.map(_.add(rs))\n }\n \n def count = root.map(_.leftCount).get\n }\n\n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n Tree.add(a)\n println(Tree.count)\n }\n}"}, {"source_code": "\nobject Multithreading extends App {\n\n val t = readInt //num tests\n val threads = readLine.split(' ').map((s: String) => s.toInt)\n\n var num = 0\n for (i <- Range(0, t - 1)) {\n if (threads(i) > threads(i + 1)) {\n num += 1\n }\n }\n println(num)\n}\n"}, {"source_code": "import scala.collection.Set\n\nobject Multithreading extends App {\n\n val t = readInt //num tests\n val threads = readLine.split(' ').map((s: String) => s.toInt)\n var set = Set[Int]() ++ threads\n\n var num = 0\n for (i <- Range(0, t)) {\n set = set - threads(i)\n if (set.exists((x) => x < threads(i))) {\n num += 1\n num += threads.slice(0, i).filter(_ < threads(i)).size\n }\n }\n println(num)\n}\n"}, {"source_code": "import scala.collection.Set\n\nobject Multithreading extends App {\n\n val t = readInt //num tests\n val threads = readLine.split(' ').map((s: String) => s.toInt)\n var set = Set[Int]() ++ threads\n\n var num = 0\n for (i <- Range(0, t - 1)) {\n set = set - threads(i)\n if (set.exists((x) => x < threads(i))) {\n num += 1\n }\n }\n println(num)\n}\n"}], "src_uid": "310a0596c0a459f496b8d6b57676d25e"} {"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n readInt()\n val a = readLine().map(_.asDigit)\n val b = readLine().map(_.asDigit)\n val ans = a.zip(b).map { case (x, y) => val d = (x - y).abs; d min (10 - d) }.sum\n println(ans)\n}", "positive_code": [{"source_code": "\n/**\n * Created by przemek on 30.04.15.\n */\nobject A extends App {\n\n def solve(state: Array[Int], comb: Array[Int]): Int = {\n var sum = 0\n for ((s, k) <- state.zip(comb)) {\n val m = math.min(math.abs(s-k),math.min(10-k+s, 10-s+k))\n sum += m\n }\n sum\n }\n\n val L = readLine()\n val state = readLine().toCharArray().map(_.toInt)\n val comb = readLine().toCharArray().map(_.toInt)\n\n println(solve(state, comb))\n\n}"}, {"source_code": "import Array._\n\nobject main extends App with fastIO {\n \n var Array(n) = readLine split(\" \") map(_.toInt)\n println(readLine.map(_ - '0').zip(readLine map(_ - '0'))\n .foldLeft(0)((s, v) => s + ((v._1 - v._2).abs min (10 - (v._1 - v._2).abs)))) \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken\n in.nval.toDouble\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush = out.flush\n}"}, {"source_code": "object Solve extends App with fastIO{\n val n = nextInt\n val cur = next.map(_.toString.toInt)\n val res = next.map(_.toString.toInt)\n\n\n println(\n (for(i <- 0 until n) yield Math.min(Math.min(Math.abs(cur(i)-res(i)), Math.abs((cur(i)+res(i)))),\n Math.min(Math.abs(10+cur(i)-res(i)),Math.abs(10+res(i)-cur(i))))).sum\n )\n\n flush\n}\n\ntrait fastIO {\n import java.io._\n val isFile = false\n val input = \"file.in\"\n val output = \"file.out\"\n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush()\n}"}, {"source_code": "object main{\n object Solver extends InputReader{\n def solve(){\n val n = getInt()\n val a = getStr()\n val b = getStr()\n\n val diffs = for(i <- 0 to n - 1) yield {\n val aa = a(i)\n val bb = b(i)\n val diff: Int = Math.abs(aa - bb)\n diff min 10 - diff\n }\n\n println(diffs.sum)\n }\n }\n\n // TEMPLATE ------------------------\n\n def main(args: Array[String]){\n Solver.solve()\n }\n\n trait InputReader{\n import java.io._\n import java.util._\n protected val stream = System.in\n private val reader = new BufferedReader(new InputStreamReader(stream))\n private var tokenizer = new StringTokenizer(reader.readLine())\n\n def getStr(): String = {\n while(!tokenizer.hasMoreTokens())\n tokenizer = new StringTokenizer(reader.readLine())\n tokenizer.nextToken()\n }\n\n def getInt(): Int = getStr().toInt\n def getLong(): Long = getStr().toLong\n def getDouble(): Double = getStr().toDouble\n }\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _540 extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = next\n val b = next\n val ans = (0 until n).map(i => { val diff = (0 + a(i) - b(i)).abs; diff min (10 - diff) }).sum\n println(ans)\n}\n"}, {"source_code": "object A540 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input1 = scala.io.StdIn.readLine\n val input2 = scala.io.StdIn.readLine\n var res = 0\n for(i <- 0 until n) {\n res += math.min(math.abs(input1(i) - input2(i)), if(input1(i) > input2(i)) 10 - input1(i) + input2(i) else 10 - input2(i) + input1(i) )\n }\n println(res)\n }\n}"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport Ordering.Implicits._\n\n\nobject Codeforces {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n st.nextToken\n }\n\n def nextInt: Int = {\n Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n java.lang.Long.parseLong(next)\n }\n\n def upperBound[T: Ordering](array: Array[T], value: T) = {\n var low = 0\n var high = array.length\n var res = array.length\n while (low <= high) {\n val mid = (low + high) / 2\n if (value < array(mid)) {\n res = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n res\n }\n\n def cost(a: Int, b: Int) = math.min(math.abs(a - b), 10 - math.abs(a - b))\n\n def cost(p: (Char, Char)): Int = cost(p._1.toInt, p._2.toInt)\n\n def solve(): Unit = {\n val n = nextInt\n val srcs: String = next\n val dest: String = next\n out.println((srcs zip dest).foldLeft(0)(_ + cost(_)))\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val s1 = next.toCharArray\n val s2 = next.toCharArray\n var res = 0\n for (i <- 0 until n) {\n if (s1(i) != s2(i)) {\n val x1 = Math.max(s1(i), s2(i)) - 48\n val x2 = Math.min(s1(i), s2(i)) - 48\n res += Math.min(x1 - x2, x2 - x1 + 10)\n }\n }\n out.println(res)\n return 0\n }\n}\n"}, {"source_code": "// http://codeforces.com/contest/540/submission/10942295\nobject Test2A540 extends App {\n import java.util.Scanner\n\n type Input = (Seq[(Int, Int)])\n type Output = Int\n\n def read(scanner: Scanner): Input = {\n import scanner._\n nextInt\n nextLine\n val (src, target) = (nextLine map {_ - '0'}, nextLine map {_ - '0'})\n src zip target\n }\n\n def solve(problem: Input): Output = {\n problem map { case (a, b) =>\n val (x, y) = if (a < b) (a, b) else (b, a)\n val l = (y - x).abs\n val r = x + (10 - y)\n l min r\n } sum\n }\n\n def format(result: Output): String = result.toString\n\n def apply(input: String): String = apply(new Scanner(input))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n}\n"}, {"source_code": "// http://codeforces.com/contest/540/submission/10942295\nobject TestA540 extends App {\n import java.util.Scanner\n\n type Input = (Seq[(Int, Int)])\n type Output = Int\n\n def read(scanner: Scanner): Input = {\n import scanner._\n nextInt\n nextLine\n val (src, target) = (nextLine map {_ - '0'}, nextLine map {_ - '0'})\n src zip target\n }\n\n def solve(problem: Input): Output = {\n problem map { case (a, b) =>\n val (x, y) = if (a < b) (a, b) else (b, a)\n val l = (y - x).abs\n val r = x + (10 - y)\n l min r\n } sum\n }\n\n def format(result: Output): String = result.toString\n\n def apply(input: String): String = apply(new Scanner(input))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n}\n"}, {"source_code": "object A540 extends App {\n import java.util.Scanner\n\n type Input = (Seq[(Int, Int)])\n type Output = Int\n\n def read(scanner: Scanner): Input = {\n import scanner._\n nextInt\n nextLine\n val (src, target) = (nextLine map {_ - '0'}, nextLine map {_ - '0'})\n src zip target\n }\n\n def solve(problem: Input): Output = {\n problem map { case (a, b) =>\n val (x, y) = if (a < b) (a, b) else (b, a)\n val l = (y - x).abs\n val r = x + (10 - y)\n l min r\n } sum\n }\n\n def format(result: Output): String = result.toString\n\n def apply(input: String): String = apply(new Scanner(input))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n readInt()\n val start = readLine().map(_.toString.toInt)\n val end = readLine().map(_.toString.toInt)\n\n def diff(ss: Int, tt: Int): Int = {\n val s = Math.min(ss, tt)\n val t = Math.max(ss, tt)\n\n val p1 = Math.abs(s - t)\n val p2 = Math.abs(s + 10 - t)\n Math.min(p1, p2)\n }\n\n def solve(s: Seq[Int], t: Seq[Int]): Int = {\n var sum = 0\n for (i <- 0 until s.length) {\n sum += diff(s(i), t(i))\n }\n sum\n }\n\n println(solve(start, end))\n\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\nimport Math.min\nimport Math.abs\n\nobject CombinationLock {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readLongs() : Array[Long] = \n readLine.split(' ').map(_.toLong)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n \n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n \n \n def main(args: Array[String]) { \n val n = readInt\n val now = readLine.map(_.toInt)\n val secret = readLine.map(_.toInt)\n println(now.zip(secret).foldLeft(0)\n { case (t, (n,s)) => t + min(abs(n-s),10-abs(n-s))})\n }\n \n}"}], "negative_code": [], "src_uid": "5adb1cf0529c3d6c93c107cf72fa5e0b"} {"source_code": "import java.util\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, T = ni()\n\n// val W = 5\n val W = 80\n val Width = W\n val MAX = Width * Width\n\n val g = Array.ofDim[Int](MAX)\n val set = Array.fill(2)(new util.BitSet(MAX))\n\n case class Coord(x: Int, y: Int)\n val D = Array(Coord(1, 0), Coord(-1, 0), Coord(0, 1), Coord(0, -1))\n\n g(0) = N\n\n var cnt = 0\n\n var i = 0\n set(0).set(0)\n while(set(i % 2).cardinality() > 0) {\n val ii = i % 2\n set(ii ^ 1).clear()\n var v = set(ii).nextSetBit(0)\n while(v != -1) {\n if (g(v) >= 4) {\n cnt += 1\n val q = g(v) / 4\n\n g(v) -= q * 4\n\n val x = v / Width\n val y = v % Width\n\n REP(4) { i =>\n val d = D(i)\n if (x + d.x >= 0 && y + d.y >= 0) {\n val toXAxis = x + d.x == 0 && d.x == -1\n val toYAxis = y + d.y == 0 && d.y == -1\n val mult =\n if (toXAxis) 2\n else if (toYAxis) 2\n else if (toXAxis && toYAxis) 4\n else 1\n \n val next = (x + d.x) * Width + y + d.y\n g(next) += q * mult\n set(ii ^ 1).set(next)\n }\n }\n }\n\n v = set(ii).nextSetBit(v + 1)\n }\n i += 1\n }\n\n System.err.println(cnt)\n System.err.println(i)\n\n def sum = {\n val zero = g(0)\n\n val axis = map(MAX)(identity).filter { v =>\n v != 0 && (v % Width == 0 || v / Width == 0)\n }.map(g).sum\n\n val other = map(MAX)(identity).filter { v =>\n v % Width > 0 && v / Width > 0\n }.map(g).sum\n zero + axis * 2 + other * 4\n }\n\n// assert(sum == N)\n\n REP(T) { _ =>\n val x, y = ni()\n if (x > -W && x < W && y > -W && y < W) {\n val v = abs(x) * Width + abs(y)\n out.println(g(v))\n } else {\n out.println(0)\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "import java.util\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, T = ni()\n\n// val W = 5\n val W = 80\n val Width = W\n val MAX = Width * Width\n\n val g = Array.ofDim[Int](MAX)\n val set = new util.BitSet(MAX)\n\n case class Coord(x: Int, y: Int)\n val D = Array(Coord(1, 0), Coord(-1, 0), Coord(0, 1), Coord(0, -1))\n\n g(0) = N\n\n var cnt = 0\n\n// var i = 0\n set.set(0)\n var v = set.nextSetBit(0)\n while(v != -1) {\n if (g(v) >= 4) {\n cnt += 1\n val q = g(v) / 4\n\n g(v) -= q * 4\n\n val x = v / Width\n val y = v % Width\n\n REP(4) { i =>\n val d = D(i)\n if (x + d.x >= 0 && y + d.y >= 0) {\n val toXAxis = x + d.x == 0 && d.x == -1\n val toYAxis = y + d.y == 0 && d.y == -1\n val mult =\n if (toXAxis) 2\n else if (toYAxis) 2\n else if (toXAxis && toYAxis) 4\n else 1\n\n val next = (x + d.x) * Width + y + d.y\n g(next) += q * mult\n set.set(next)\n }\n }\n }\n\n set.clear(v)\n v = set.nextSetBit(v + 1)\n if (v == -1) v = set.nextSetBit(0)\n }\n\n System.err.println(cnt)\n// System.err.println(i)\n\n def sum = {\n val zero = g(0)\n\n val axis = map(MAX)(identity).filter { v =>\n v != 0 && (v % Width == 0 || v / Width == 0)\n }.map(g).sum\n\n val other = map(MAX)(identity).filter { v =>\n v % Width > 0 && v / Width > 0\n }.map(g).sum\n zero + axis * 2 + other * 4\n }\n\n// assert(sum == N)\n\n REP(T) { _ =>\n val x, y = ni()\n if (x > -W && x < W && y > -W && y < W) {\n val v = abs(x) * Width + abs(y)\n out.println(g(v))\n } else {\n out.println(0)\n }\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [], "src_uid": "e7a07efba27f2b1f9ec7c4a8fb997b00"} {"source_code": "import scala.collection.mutable.ArrayBuilder\nimport scala.collection.mutable.BitSet\nimport scala.collection.mutable.Stack\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val vc0 = readLine.map(c => if (c == 'C') 1 else 0)\n val alp = vc0.size\n val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)\n\n val Array(n, m) = readInts(2)\n\n def vert(i: Int) = if (i < 0) n - i else i\n def vertNot(i: Int) = vert(-i)\n\n val adjBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt }\n val revBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt } // reverse edges\n\n val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }\n\n for (i <- 0 until m) {\n val in = readLine.split(' ')\n val c1 = in(1).head\n val c2 = in(3).head\n val a0 = in(0).toInt - 1\n val b0 = in(2).toInt - 1\n val a = (a0 + 1) * (if (isC(c1)) 1 else -1)\n val b = (b0 + 1) * (if (isC(c2)) 1 else -1)\n // implication (a -> b)\n adjBuilders(vert(a)) += vert(b)\n adjBuilders(vertNot(b)) += vertNot(a)\n revBuilders(vert(b)) += vert(a)\n revBuilders(vertNot(a)) += vertNot(b)\n\n (c1, c2) match {\n case ('C', 'C') =>\n cToC(a0) += b0\n vToV(b0) += a0\n case ('V', 'C') =>\n vToC(a0) += b0\n vToC(b0) += a0\n case ('C', 'V') =>\n cToV(a0) += b0\n cToV(b0) += a0\n case ('V', 'V') =>\n vToV(a0) += b0\n cToC(b0) += a0\n }\n }\n\n for (k <- 0 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n cToC(i)(j) |= (cToC(i)(k) && cToC(k)(j)) || (cToV(i)(k) && vToC(k)(j)) \n cToV(i)(j) |= (cToV(i)(k) && vToV(k)(j)) || (cToC(i)(k) && cToV(k)(j))\n vToC(i)(j) |= (vToC(i)(k) && cToC(k)(j)) || (vToV(i)(k) && vToC(k)(j))\n vToV(i)(j) |= (vToV(i)(k) && vToV(k)(j)) || (vToC(i)(k) && cToV(k)(j))\n }\n }\n }\n\n val adj = adjBuilders.map(_.result)\n val rev = revBuilders.map(_.result)\n\n def sat2(n: Int, adj: Array[Array[Int]], rev: Array[Array[Int]]): Array[Int] = {\n\n val visited1 = new BitSet(2 * n + 1)\n val stack = Stack.empty[Int]\n\n def dfs1(u: Int): Unit = {\n if (!visited1(u)) {\n visited1 += u\n for (v <- rev(u)) dfs1(v)\n stack.push(u)\n }\n }\n\n for (i <- 0 to 2 * n) dfs1(i) // reverse topological sort onto stack\n\n val visited2 = new BitSet(2 * n + 1)\n val sccNums = Array.ofDim[Int](2 * n + 1)\n\n def dfs2(u: Int, lead: Int): Unit = {\n if (!visited2(u)) {\n visited2 += u\n sccNums(u) = lead\n for (v <- adj(u)) dfs2(v, lead)\n }\n }\n\n while (stack.nonEmpty) {\n val lead = stack.pop()\n dfs2(lead, lead)\n }\n\n sccNums\n }\n\n val s0 = readLine.map(_ - 'a').toArray\n val s = s0.clone\n val sccNums = sat2(n, adj, rev)\n val sccCount = sccNums.length\n val sccUtil = Array.fill(sccCount) { 0 }\n\n for (i <- s.indices) {\n val cc = (i + 1) * (if (isC(s(i))) 1 else -1)\n sccUtil(sccNums(vert(cc))) += 1\n }\n\n def isValidPrefix(prefixLen: Int): Boolean = {\n val isSetToC, isSetToV = Array.fill(n) { false }\n for (i <- 0 until prefixLen) {\n val c = s(i)\n isSetToC(i) = isC(c)\n isSetToV(i) = !isC(c)\n }\n // println(prefixLen, s.map(c => (c + 'a').toChar).mkString)\n // println(isSetToC.mkString, isSetToV.mkString)\n for (i <- 0 until prefixLen) {\n if (isSetToC(i)) {\n for (j <- 0 until n) {\n //println(i, j, 'C')\n if (cToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (cToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n } else if (isSetToV(i)) {\n for (j <- 0 until n) {\n //println(i, j, 'V')\n if (vToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (vToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n }\n }\n for (i <- prefixLen + 1 until n) {\n val cc = (i + 1)\n //if (sccNums(vert(cc)) == sccNums(vertNot(cc))) return false\n }\n true\n }\n//println(vToC(0))\n//println(cToV(0))\n var maxValidPrefixLen = -1\n if (isValidPrefix(n)) maxValidPrefixLen = n\n else {\n for (prefixLen <- n to 1 by -1) {\n if (maxValidPrefixLen < 0) {\n var checkedC, checkedV = false\n for (nextC <- s(prefixLen - 1) + 1 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(prefixLen - 1) = nextC\n checkedC = true\n if (isValidPrefix(prefixLen)) {\n maxValidPrefixLen = prefixLen\n checkedV = true\n }\n }\n } else {\n if (!checkedV) {\n s(prefixLen - 1) = nextC\n checkedV = true\n if (isValidPrefix(prefixLen)) {\n maxValidPrefixLen = prefixLen\n checkedC = true\n }\n }\n }\n }\n }\n }\n }\n\n if (maxValidPrefixLen < 0) {\n println(-1)\n } else {\n\n for (i <- maxValidPrefixLen until n) {\n var checkedC, checkedV = false\n for (nextC <- 0 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(i) = nextC\n checkedC = true\n if (isValidPrefix(i + 1)) checkedV = true\n //println('C', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)\n }\n } else {\n if (!checkedV) {\n s(i) = nextC\n checkedV = true\n if (isValidPrefix(i + 1)) checkedC = true\n //println('V', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)\n }\n }\n }\n }\n\n if (isValidPrefix(n)) println(s.map(c => (c + 'a').toChar).mkString)\n else println(-1)\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable.BitSet\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val vc0 = readLine.map(c => if (c == 'C') 1 else 0)\n val alp = vc0.size\n val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)\n\n val Array(n, m) = readInts(2)\n\n val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }\n\n for (i <- 0 until m) {\n val in = readLine.split(' ')\n val c1 = in(1).head\n val c2 = in(3).head\n val a = in(0).toInt - 1\n val b = in(2).toInt - 1\n\n (c1, c2) match {\n case ('C', 'C') =>\n cToC(a) += b\n vToV(b) += a\n case ('V', 'C') =>\n vToC(a) += b\n vToC(b) += a\n case ('C', 'V') =>\n cToV(a) += b\n cToV(b) += a\n case ('V', 'V') =>\n vToV(a) += b\n cToC(b) += a\n }\n }\n\n for (k <- 0 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n cToC(i)(j) |= (cToC(i)(k) && cToC(k)(j)) || (cToV(i)(k) && vToC(k)(j)) \n cToV(i)(j) |= (cToV(i)(k) && vToV(k)(j)) || (cToC(i)(k) && cToV(k)(j))\n vToC(i)(j) |= (vToC(i)(k) && cToC(k)(j)) || (vToV(i)(k) && vToC(k)(j))\n vToV(i)(j) |= (vToV(i)(k) && vToV(k)(j)) || (vToC(i)(k) && cToV(k)(j))\n }\n }\n }\n\n val s0 = readLine.map(_ - 'a').toArray\n val s = s0.clone\n\n def isValidPrefix(prefixLen: Int): Boolean = {\n \n val isSetToC, isSetToV = Array.fill(n) { false }\n \n for (i <- 0 until prefixLen) {\n val c = s(i)\n isSetToC(i) = isC(c)\n isSetToV(i) = !isC(c)\n }\n\n for (i <- 0 until prefixLen) {\n if (isSetToC(i)) {\n for (j <- 0 until n) {\n if (cToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (cToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n } else if (isSetToV(i)) {\n for (j <- 0 until n) {\n if (vToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (vToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n }\n }\n true\n }\n\n var maxValidPrefixLen = -1\n if (isValidPrefix(n)) maxValidPrefixLen = n\n else {\n for (prefixLen <- n to 1 by -1) {\n if (maxValidPrefixLen < 0) {\n var checkedC, checkedV = false\n for (nextC <- s(prefixLen - 1) + 1 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(prefixLen - 1) = nextC\n checkedC = true\n if (isValidPrefix(prefixLen)) {\n maxValidPrefixLen = prefixLen\n checkedV = true\n }\n }\n } else {\n if (!checkedV) {\n s(prefixLen - 1) = nextC\n checkedV = true\n if (isValidPrefix(prefixLen)) {\n maxValidPrefixLen = prefixLen\n checkedC = true\n }\n }\n }\n }\n }\n }\n }\n\n if (maxValidPrefixLen < 0) {\n println(-1)\n } else {\n\n for (i <- maxValidPrefixLen until n) {\n var checkedC, checkedV = false\n for (nextC <- 0 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(i) = nextC\n checkedC = true\n if (isValidPrefix(i + 1)) checkedV = true\n }\n } else {\n if (!checkedV) {\n s(i) = nextC\n checkedV = true\n if (isValidPrefix(i + 1)) checkedC = true\n }\n }\n }\n }\n\n if (isValidPrefix(n)) println(s.map(c => (c + 'a').toChar).mkString)\n else println(-1)\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuilder\nimport scala.collection.mutable.BitSet\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val vc0 = readLine.map(c => if (c == 'C') 1 else 0)\n val alp = vc0.size\n val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)\n\n val Array(n, m) = readInts(2)\n\n val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }\n\n for (i <- 0 until m) {\n val in = readLine.split(' ')\n val c1 = in(1).head\n val c2 = in(3).head\n val a = in(0).toInt - 1\n val b = in(2).toInt - 1\n\n (c1, c2) match {\n case ('C', 'C') =>\n cToC(a) += b\n vToV(b) += a\n case ('V', 'C') =>\n vToC(a) += b\n vToC(b) += a\n case ('C', 'V') =>\n cToV(a) += b\n cToV(b) += a\n case ('V', 'V') =>\n vToV(a) += b\n cToC(b) += a\n }\n }\n\n for (k <- 0 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n cToC(i)(j) |= (cToC(i)(k) && cToC(k)(j)) || (cToV(i)(k) && vToC(k)(j)) \n cToV(i)(j) |= (cToV(i)(k) && vToV(k)(j)) || (cToC(i)(k) && cToV(k)(j))\n vToC(i)(j) |= (vToC(i)(k) && cToC(k)(j)) || (vToV(i)(k) && vToC(k)(j))\n vToV(i)(j) |= (vToV(i)(k) && vToV(k)(j)) || (vToC(i)(k) && cToV(k)(j))\n }\n }\n }\n\n val s0 = readLine.map(_ - 'a').toArray\n val s = s0.clone\n val isSetToC, isSetToV = Array.ofDim(n)\n\n def isValidPrefix(prefixLen: Int): Boolean = {\n \n val isSetToC, isSetToV = Array.fill(n) { false }\n \n for (i <- 0 until prefixLen) {\n val c = s(i)\n isSetToC(i) = isC(c)\n isSetToV(i) = !isC(c)\n }\n\n for (i <- 0 until prefixLen) {\n if (isSetToC(i)) {\n for (j <- 0 until n) {\n if (cToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (cToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n } else if (isSetToV(i)) {\n for (j <- 0 until n) {\n if (vToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (vToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n }\n }\n true\n }\n\n var maxValidPrefixLen = -1\n if (isValidPrefix(n)) maxValidPrefixLen = n\n else {\n for (prefixLen <- n to 1 by -1) {\n if (maxValidPrefixLen < 0) {\n var checkedC, checkedV = false\n for (nextC <- s(prefixLen - 1) + 1 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(prefixLen - 1) = nextC\n checkedC = true\n if (isValidPrefix(prefixLen)) {\n maxValidPrefixLen = prefixLen\n checkedV = true\n }\n }\n } else {\n if (!checkedV) {\n s(prefixLen - 1) = nextC\n checkedV = true\n if (isValidPrefix(prefixLen)) {\n maxValidPrefixLen = prefixLen\n checkedC = true\n }\n }\n }\n }\n }\n }\n }\n\n if (maxValidPrefixLen < 0) {\n println(-1)\n } else {\n\n for (i <- maxValidPrefixLen until n) {\n var checkedC, checkedV = false\n for (nextC <- 0 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(i) = nextC\n checkedC = true\n if (isValidPrefix(i + 1)) checkedV = true\n }\n } else {\n if (!checkedV) {\n s(i) = nextC\n checkedV = true\n if (isValidPrefix(i + 1)) checkedC = true\n }\n }\n }\n }\n\n if (isValidPrefix(n)) println(s.map(c => (c + 'a').toChar).mkString)\n else println(-1)\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable.ArrayBuilder\nimport scala.collection.mutable.BitSet\nimport scala.collection.mutable.Stack\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val vc0 = readLine.map(c => if (c == 'C') 1 else 0)\n val alp = vc0.size\n val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)\n\n val Array(n, m) = readInts(2)\n\n def vert(i: Int) = if (i < 0) n - i else i\n def vertNot(i: Int) = vert(-i)\n\n val adjBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt }\n val revBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt } // reverse edges\n\n val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }\n\n for (i <- 0 until m) {\n val in = readLine.split(' ')\n val c1 = in(1).head\n val c2 = in(3).head\n val a0 = in(0).toInt - 1\n val b0 = in(2).toInt - 1\n val a = (a0 + 1) * (if (isC(c1)) 1 else -1)\n val b = (b0 + 1) * (if (isC(c2)) 1 else -1)\n // implication (a -> b)\n adjBuilders(vert(a)) += vert(b)\n adjBuilders(vertNot(b)) += vertNot(a)\n revBuilders(vert(b)) += vert(a)\n revBuilders(vertNot(a)) += vertNot(b)\n\n (c1, c2) match {\n case ('C', 'C') =>\n cToC(a0) += b0\n vToV(b0) += a0\n case ('V', 'C') =>\n vToC(a0) += b0\n vToC(b0) += a0\n case ('C', 'V') =>\n cToV(a0) += b0\n cToV(b0) += a0\n case ('V', 'V') =>\n vToV(a0) += b0\n cToC(b0) += a0\n }\n }\n\n for (k <- 0 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n cToC(i)(j) |= (cToC(i)(k) && cToC(k)(j)) || (cToV(i)(k) && vToC(k)(j)) \n cToV(i)(j) |= (cToV(i)(k) && vToV(k)(j)) || (cToC(i)(k) && cToV(k)(j))\n vToC(i)(j) |= (vToC(i)(k) && cToC(k)(j)) || (vToV(i)(k) && vToC(k)(j))\n vToV(i)(j) |= (vToV(i)(k) && vToV(k)(j)) || (vToC(i)(k) && cToV(k)(j))\n }\n }\n }\n\n val adj = adjBuilders.map(_.result)\n val rev = revBuilders.map(_.result)\n\n def sat2(n: Int, adj: Array[Array[Int]], rev: Array[Array[Int]]): Array[Int] = {\n\n val visited1 = new BitSet(2 * n + 1)\n val stack = Stack.empty[Int]\n\n def dfs1(u: Int): Unit = {\n if (!visited1(u)) {\n visited1 += u\n for (v <- rev(u)) dfs1(v)\n stack.push(u)\n }\n }\n\n for (i <- 0 to 2 * n) dfs1(i) // reverse topological sort onto stack\n\n val visited2 = new BitSet(2 * n + 1)\n val sccNums = Array.ofDim[Int](2 * n + 1)\n\n def dfs2(u: Int, lead: Int): Unit = {\n if (!visited2(u)) {\n visited2 += u\n sccNums(u) = lead\n for (v <- adj(u)) dfs2(v, lead)\n }\n }\n\n while (stack.nonEmpty) {\n val lead = stack.pop()\n dfs2(lead, lead)\n }\n\n sccNums\n }\n\n val s0 = readLine.map(_ - 'a').toArray\n val s = s0.clone\n val sccNums = sat2(n, adj, rev)\n val sccCount = sccNums.length\n val sccUtil = Array.fill(sccCount) { 0 }\n\n for (i <- s.indices) {\n val cc = (i + 1) * (if (isC(s(i))) 1 else -1)\n sccUtil(sccNums(vert(cc))) += 1\n }\n\n def isValidPrefix(prefixLen: Int): Boolean = {\n val isSetToC, isSetToV = Array.fill(n) { false }\n for (i <- 0 until prefixLen) {\n val c = s(i)\n isSetToC(i) = isC(c)\n isSetToV(i) = !isC(c)\n }\n // println(prefixLen, s.map(c => (c + 'a').toChar).mkString)\n // println(isSetToC.mkString, isSetToV.mkString)\n for (i <- 0 until prefixLen) {\n if (isC(s(i))) {\n for (j <- 0 until n) {\n //println(i, j, 'C')\n if (cToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (cToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n } else { // !isC(s(i))\n for (j <- 0 until n) {\n //println(i, j, 'V')\n if (vToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (vToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n }\n }\n for (i <- prefixLen + 1 until n) {\n val cc = (i + 1)\n if (sccNums(vert(cc)) == sccNums(vertNot(cc))) return false\n }\n true\n }\n//println(vToC(0))\n//println(cToV(0))\n var maxValidPrefixLen = -1\n if (isValidPrefix(n)) maxValidPrefixLen = n\n else {\n for (prefixLen <- n to 1 by -1) {\n if (maxValidPrefixLen < 0) {\n var checkedC, checkedV = false\n for (nextC <- s(prefixLen - 1) + 1 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(prefixLen - 1) = nextC\n checkedC = true\n if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen\n }\n } else {\n if (!checkedV) {\n s(prefixLen - 1) = nextC\n checkedV = true\n if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen\n }\n }\n }\n }\n }\n }\n\n if (maxValidPrefixLen < 0) {\n println(-1)\n } else {\n\n for (i <- maxValidPrefixLen until n) {\n var checkedC, checkedV = false\n for (nextC <- 0 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(i) = nextC\n checkedC = true\n if (isValidPrefix(i + 1)) checkedV = true\n //println('C', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)\n }\n } else {\n if (!checkedV) {\n s(i) = nextC\n checkedV = true\n if (isValidPrefix(i + 1)) checkedC = true\n //println('V', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)\n }\n }\n }\n }\n\n println(s.map(c => (c + 'a').toChar).mkString)\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuilder\nimport scala.collection.mutable.BitSet\nimport scala.collection.mutable.Stack\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val vc0 = readLine.map(c => if (c == 'C') 1 else 0)\n val alp = vc0.size\n val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)\n\n val Array(n, m) = readInts(2)\n\n def vert(i: Int) = if (i < 0) n - i else i\n def vertNot(i: Int) = vert(-i)\n\n val adjBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt }\n val revBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt } // reverse edges\n\n val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }\n\n for (i <- 0 until m) {\n val in = readLine.split(' ')\n val c1 = in(1).head\n val c2 = in(3).head\n val a0 = in(0).toInt - 1\n val b0 = in(2).toInt - 1\n val a = (a0 + 1) * (if (isC(c1)) 1 else -1)\n val b = (b0 + 1) * (if (isC(c2)) 1 else -1)\n // implication (a -> b)\n adjBuilders(vert(a)) += vert(b)\n adjBuilders(vertNot(b)) += vertNot(a)\n revBuilders(vert(b)) += vert(a)\n revBuilders(vertNot(a)) += vertNot(b)\n\n (c1, c2) match {\n case ('C', 'C') =>\n cToC(a0) += b0\n //vToV(b0) += a0\n case ('V', 'C') =>\n vToC(a0) += b0\n //vToC(b0) += a0\n case ('C', 'V') =>\n cToV(a0) += b0\n //cToV(b0) += a0\n case ('V', 'V') =>\n vToV(a0) += b0\n //cToC(b0) += a0\n }\n }\n\n for (k <- 0 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n cToC(i)(j) |= cToC(i)(k) && cToC(k)(j)\n cToV(i)(j) |= cToV(i)(k) && cToV(k)(j)\n vToC(i)(j) |= vToC(i)(k) && vToC(k)(j)\n vToV(i)(j) |= vToV(i)(k) && vToV(k)(j)\n }\n }\n }\n\n val adj = adjBuilders.map(_.result)\n val rev = revBuilders.map(_.result)\n\n def sat2(n: Int, adj: Array[Array[Int]], rev: Array[Array[Int]]): Array[Int] = {\n\n val visited1 = new BitSet(2 * n + 1)\n val stack = Stack.empty[Int]\n\n def dfs1(u: Int): Unit = {\n if (!visited1(u)) {\n visited1 += u\n for (v <- rev(u)) dfs1(v)\n stack.push(u)\n }\n }\n\n for (i <- 0 to 2 * n) dfs1(i) // reverse topological sort onto stack\n\n val visited2 = new BitSet(2 * n + 1)\n val sccNums = Array.ofDim[Int](2 * n + 1)\n\n def dfs2(u: Int, lead: Int): Unit = {\n if (!visited2(u)) {\n visited2 += u\n sccNums(u) = lead\n for (v <- adj(u)) dfs2(v, lead)\n }\n }\n\n while (stack.nonEmpty) {\n val lead = stack.pop()\n dfs2(lead, lead)\n }\n\n sccNums\n }\n\n val s0 = readLine.map(_ - 'a').toArray\n val s = s0.clone\n val sccNums = sat2(n, adj, rev)\n val sccCount = sccNums.length\n val sccUtil = Array.fill(sccCount) { 0 }\n\n for (i <- s.indices) {\n val cc = (i + 1) * (if (isC(s(i))) 1 else -1)\n sccUtil(sccNums(vert(cc))) += 1\n }\n\n def isValidPrefix(prefixLen: Int): Boolean = {\n val isSetToC, isSetToV = Array.fill(n) { false }\n for (i <- 0 until prefixLen) {\n val c = s(i)\n isSetToC(i) = isC(c)\n isSetToV(i) = !isC(c)\n }\n for (i <- 0 until prefixLen) {\n val c = s(i)\n if (isC(c)) {\n for (b <- 0 until n) {\n if (cToC(i)(b)) if (isSetToV(b)) return false\n else isSetToC(b) = true\n if (cToV(i)(b)) if (isSetToC(b)) return false\n else isSetToV(b) = true\n }\n } else {\n for (b <- 0 until n) {\n if (vToC(i)(b)) if (isSetToV(b)) return false\n else isSetToC(b) = true\n if (vToV(i)(b)) if (isSetToC(b)) return false\n else isSetToV(b) = true\n }\n }\n }\n for (i <- prefixLen + 1 until n) {\n val cc = (i + 1)\n if (sccNums(vert(cc)) == sccNums(vertNot(cc))) return false\n }\n true\n }\n\n var maxValidPrefixLen = -1\n if (isValidPrefix(n)) maxValidPrefixLen = n\n else {\n for (prefixLen <- n to 1 by -1) {\n if (maxValidPrefixLen < 0) {\n var checkedC, checkedV = false\n for (nextC <- s(prefixLen - 1) + 1 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(prefixLen - 1) = nextC\n checkedC = true\n if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen\n }\n } else {\n if (!checkedV) {\n s(prefixLen - 1) = nextC\n checkedV = true\n if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen\n }\n }\n }\n }\n }\n }\n\n if (maxValidPrefixLen < 0) {\n println(-1)\n } else {\n\n for (i <- maxValidPrefixLen until n) {\n var checkedC, checkedV = false\n for (nextC <- 0 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(i) = nextC\n checkedC = true\n if (isValidPrefix(i + 1)) checkedV = true\n }\n } else {\n if (!checkedV) {\n s(i) = nextC\n checkedV = true\n if (isValidPrefix(i + 1)) checkedC = true\n }\n }\n }\n }\n\n println(s.map(c => (c + 'a').toChar).mkString)\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuilder\nimport scala.collection.mutable.BitSet\nimport scala.collection.mutable.Stack\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val vc0 = readLine.map(c => if (c == 'C') 1 else 0)\n val alp = vc0.size\n val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)\n\n val Array(n, m) = readInts(2)\n\n def vert(i: Int) = if (i < 0) n - i else i\n def vertNot(i: Int) = vert(-i)\n\n val adjBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt }\n val revBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt } // reverse edges\n\n val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }\n\n for (i <- 0 until m) {\n val in = readLine.split(' ')\n val c1 = in(1).head\n val c2 = in(3).head\n val a0 = in(0).toInt - 1\n val b0 = in(2).toInt - 1\n val a = (a0 + 1) * (if (isC(c1)) 1 else -1)\n val b = (b0 + 1) * (if (isC(c2)) 1 else -1)\n // implication (a -> b)\n adjBuilders(vert(a)) += vert(b)\n adjBuilders(vertNot(b)) += vertNot(a)\n revBuilders(vert(b)) += vert(a)\n revBuilders(vertNot(a)) += vertNot(b)\n\n (c1, c2) match {\n case ('C', 'C') =>\n cToC(a0) += b0\n //vToV(b0) += a0\n case ('V', 'C') =>\n vToC(a0) += b0\n //vToC(b0) += a0\n case ('C', 'V') =>\n cToV(a0) += b0\n //cToV(b0) += a0\n case ('V', 'V') =>\n vToV(a0) += b0\n //cToC(b0) += a0\n }\n }\n\n for (k <- 0 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n// cToC(i)(j) |= cToC(i)(k) && cToC(k)(j)\n// cToV(i)(j) |= cToV(i)(k) && cToV(k)(j)\n// vToC(i)(j) |= vToC(i)(k) && vToC(k)(j)\n// vToV(i)(j) |= vToV(i)(k) && vToV(k)(j)\n }\n }\n }\n\n val adj = adjBuilders.map(_.result)\n val rev = revBuilders.map(_.result)\n\n def sat2(n: Int, adj: Array[Array[Int]], rev: Array[Array[Int]]): Array[Int] = {\n\n val visited1 = new BitSet(2 * n + 1)\n val stack = Stack.empty[Int]\n\n def dfs1(u: Int): Unit = {\n if (!visited1(u)) {\n visited1 += u\n for (v <- rev(u)) dfs1(v)\n stack.push(u)\n }\n }\n\n for (i <- 0 to 2 * n) dfs1(i) // reverse topological sort onto stack\n\n val visited2 = new BitSet(2 * n + 1)\n val sccNums = Array.ofDim[Int](2 * n + 1)\n\n def dfs2(u: Int, lead: Int): Unit = {\n if (!visited2(u)) {\n visited2 += u\n sccNums(u) = lead\n for (v <- adj(u)) dfs2(v, lead)\n }\n }\n\n while (stack.nonEmpty) {\n val lead = stack.pop()\n dfs2(lead, lead)\n }\n\n sccNums\n }\n\n val s0 = readLine.map(_ - 'a').toArray\n val s = s0.clone\n val sccNums = sat2(n, adj, rev)\n val sccCount = sccNums.length\n val sccUtil = Array.fill(sccCount) { 0 }\n\n for (i <- s.indices) {\n val cc = (i + 1) * (if (isC(s(i))) 1 else -1)\n sccUtil(sccNums(vert(cc))) += 1\n }\n\n def isValidPrefix(prefixLen: Int): Boolean = {\n val isSetToC, isSetToV = Array.fill(n) { false }\n for (i <- 0 until prefixLen) {\n val c = s(i)\n isSetToC(i) = isC(c)\n isSetToV(i) = !isC(c)\n }\n // println(prefixLen, s.map(c => (c + 'a').toChar).mkString)\n // println(isSetToC.mkString, isSetToV.mkString)\n for (i <- 0 until prefixLen) {\n if (isC(s(i))) {\n for (j <- 0 until n) {\n //println(i, j, 'C')\n if (cToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (cToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n } else { // !isC(s(i))\n for (j <- 0 until n) {\n //println(i, j, 'V')\n if (vToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (vToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n }\n }\n for (i <- prefixLen + 1 until n) {\n val cc = (i + 1)\n if (sccNums(vert(cc)) == sccNums(vertNot(cc))) return false\n }\n true\n }\n//println(vToC(0))\n//println(cToV(0))\n var maxValidPrefixLen = -1\n if (isValidPrefix(n)) maxValidPrefixLen = n\n else {\n for (prefixLen <- n to 1 by -1) {\n if (maxValidPrefixLen < 0) {\n var checkedC, checkedV = false\n for (nextC <- s(prefixLen - 1) + 1 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(prefixLen - 1) = nextC\n checkedC = true\n if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen\n }\n } else {\n if (!checkedV) {\n s(prefixLen - 1) = nextC\n checkedV = true\n if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen\n }\n }\n }\n }\n }\n }\n\n if (maxValidPrefixLen < 0) {\n println(-1)\n } else {\n\n for (i <- maxValidPrefixLen until n) {\n var checkedC, checkedV = false\n for (nextC <- 0 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(i) = nextC\n checkedC = true\n if (isValidPrefix(i + 1)) checkedV = true\n //println('C', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)\n }\n } else {\n if (!checkedV) {\n s(i) = nextC\n checkedV = true\n if (isValidPrefix(i + 1)) checkedC = true\n //println('V', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)\n }\n }\n }\n }\n\n println(s.map(c => (c + 'a').toChar).mkString)\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuilder\nimport scala.collection.mutable.BitSet\nimport scala.collection.mutable.Stack\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val vc0 = readLine.map(c => if (c == 'C') 1 else 0)\n val alp = vc0.size\n val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)\n\n val Array(n, m) = readInts(2)\n\n def vert(i: Int) = if (i < 0) n - i else i\n def vertNot(i: Int) = vert(-i)\n\n val adjBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt }\n val revBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt } // reverse edges\n\n val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }\n\n for (i <- 0 until m) {\n val in = readLine.split(' ')\n val c1 = in(1).head\n val c2 = in(3).head\n val a0 = in(0).toInt - 1\n val b0 = in(2).toInt - 1\n val a = (a0 + 1) * (if (isC(c1)) 1 else -1)\n val b = (b0 + 1) * (if (isC(c2)) 1 else -1)\n // implication (a -> b)\n adjBuilders(vert(a)) += vert(b)\n adjBuilders(vertNot(b)) += vertNot(a)\n revBuilders(vert(b)) += vert(a)\n revBuilders(vertNot(a)) += vertNot(b)\n\n (c1, c2) match {\n case ('C', 'C') =>\n cToC(a0) += b0\n vToV(b0) += a0\n case ('V', 'C') =>\n vToC(a0) += b0\n vToC(b0) += a0\n case ('C', 'V') =>\n cToV(a0) += b0\n cToV(b0) += a0\n case ('V', 'V') =>\n vToV(a0) += b0\n cToC(b0) += a0\n }\n }\n\n for (k <- 0 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n cToC(i)(j) |= (cToC(i)(k) && cToC(k)(j)) || (cToV(i)(k) && vToC(k)(j)) \n cToV(i)(j) |= (cToV(i)(k) && vToV(k)(j)) || (cToC(i)(k) && cToV(k)(j))\n vToC(i)(j) |= (vToC(i)(k) && cToC(k)(j)) || (vToV(i)(k) && vToC(k)(j))\n vToV(i)(j) |= (vToV(i)(k) && vToV(k)(j)) || (vToC(i)(k) && cToV(k)(j))\n }\n }\n }\n\n val adj = adjBuilders.map(_.result)\n val rev = revBuilders.map(_.result)\n\n def sat2(n: Int, adj: Array[Array[Int]], rev: Array[Array[Int]]): Array[Int] = {\n\n val visited1 = new BitSet(2 * n + 1)\n val stack = Stack.empty[Int]\n\n def dfs1(u: Int): Unit = {\n if (!visited1(u)) {\n visited1 += u\n for (v <- rev(u)) dfs1(v)\n stack.push(u)\n }\n }\n\n for (i <- 0 to 2 * n) dfs1(i) // reverse topological sort onto stack\n\n val visited2 = new BitSet(2 * n + 1)\n val sccNums = Array.ofDim[Int](2 * n + 1)\n\n def dfs2(u: Int, lead: Int): Unit = {\n if (!visited2(u)) {\n visited2 += u\n sccNums(u) = lead\n for (v <- adj(u)) dfs2(v, lead)\n }\n }\n\n while (stack.nonEmpty) {\n val lead = stack.pop()\n dfs2(lead, lead)\n }\n\n sccNums\n }\n\n val s0 = readLine.map(_ - 'a').toArray\n val s = s0.clone\n val sccNums = sat2(n, adj, rev)\n val sccCount = sccNums.length\n val sccUtil = Array.fill(sccCount) { 0 }\n\n for (i <- s.indices) {\n val cc = (i + 1) * (if (isC(s(i))) 1 else -1)\n sccUtil(sccNums(vert(cc))) += 1\n }\n\n def isValidPrefix(prefixLen: Int): Boolean = {\n val isSetToC, isSetToV = Array.fill(n) { false }\n for (i <- 0 until prefixLen) {\n val c = s(i)\n isSetToC(i) = isC(c)\n isSetToV(i) = !isC(c)\n }\n // println(prefixLen, s.map(c => (c + 'a').toChar).mkString)\n // println(isSetToC.mkString, isSetToV.mkString)\n for (i <- 0 until prefixLen) {\n if (isSetToC(i)) {\n for (j <- 0 until n) {\n //println(i, j, 'C')\n if (cToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (cToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n } else if (isSetToV(i)) {\n for (j <- 0 until n) {\n //println(i, j, 'V')\n if (vToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (vToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n }\n }\n for (i <- prefixLen + 1 until n) {\n val cc = (i + 1)\n //if (sccNums(vert(cc)) == sccNums(vertNot(cc))) return false\n }\n true\n }\n//println(vToC(0))\n//println(cToV(0))\n var maxValidPrefixLen = -1\n if (isValidPrefix(n)) maxValidPrefixLen = n\n else {\n for (prefixLen <- n to 1 by -1) {\n if (maxValidPrefixLen < 0) {\n var checkedC, checkedV = false\n for (nextC <- s(prefixLen - 1) + 1 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(prefixLen - 1) = nextC\n checkedC = true\n if (isValidPrefix(prefixLen)) {\n maxValidPrefixLen = prefixLen\n checkedV = true\n }\n }\n } else {\n if (!checkedV) {\n s(prefixLen - 1) = nextC\n checkedV = true\n if (isValidPrefix(prefixLen)) {\n maxValidPrefixLen = prefixLen\n checkedC = true\n }\n }\n }\n }\n }\n }\n }\n\n if (maxValidPrefixLen < 0) {\n println(-1)\n } else {\n\n for (i <- maxValidPrefixLen until n) {\n var checkedC, checkedV = false\n for (nextC <- 0 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(i) = nextC\n checkedC = true\n if (isValidPrefix(i + 1)) checkedV = true\n //println('C', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)\n }\n } else {\n if (!checkedV) {\n s(i) = nextC\n checkedV = true\n if (isValidPrefix(i + 1)) checkedC = true\n //println('V', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)\n }\n }\n }\n }\n\n println(s.map(c => (c + 'a').toChar).mkString)\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuilder\nimport scala.collection.mutable.BitSet\nimport scala.collection.mutable.Stack\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val vc0 = readLine.map(c => if (c == 'C') 1 else 0)\n val alp = vc0.size\n val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)\n\n val Array(n, m) = readInts(2)\n\n def vert(i: Int) = if (i < 0) n - i else i\n def vertNot(i: Int) = vert(-i)\n\n val adjBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt }\n val revBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt } // reverse edges\n\n val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }\n\n for (i <- 0 until m) {\n val in = readLine.split(' ')\n val c1 = in(1).head\n val c2 = in(3).head\n val a0 = in(0).toInt - 1\n val b0 = in(2).toInt - 1\n val a = (a0 + 1) * (if (isC(c1)) 1 else -1)\n val b = (b0 + 1) * (if (isC(c2)) 1 else -1)\n // implication (a -> b)\n adjBuilders(vert(a)) += vert(b)\n adjBuilders(vertNot(b)) += vertNot(a)\n revBuilders(vert(b)) += vert(a)\n revBuilders(vertNot(a)) += vertNot(b)\n\n (c1, c2) match {\n case ('C', 'C') =>\n cToC(a0) += b0\n vToV(b0) += a0\n case ('V', 'C') =>\n vToC(a0) += b0\n vToC(b0) += a0\n case ('C', 'V') =>\n cToV(a0) += b0\n cToV(b0) += a0\n case ('V', 'V') =>\n vToV(a0) += b0\n cToC(b0) += a0\n }\n }\n\n for (k <- 0 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n cToC(i)(j) |= (cToC(i)(k) && cToC(k)(j)) || (cToV(i)(k) && vToC(k)(j)) \n cToV(i)(j) |= (cToV(i)(k) && vToV(k)(j)) || (cToC(i)(k) && cToV(k)(j))\n vToC(i)(j) |= (vToC(i)(k) && cToC(k)(j)) || (vToV(i)(k) && vToC(k)(j))\n vToV(i)(j) |= (vToV(i)(k) && vToV(k)(j)) || (vToC(i)(k) && cToV(k)(j))\n }\n }\n }\n\n val adj = adjBuilders.map(_.result)\n val rev = revBuilders.map(_.result)\n\n def sat2(n: Int, adj: Array[Array[Int]], rev: Array[Array[Int]]): Array[Int] = {\n\n val visited1 = new BitSet(2 * n + 1)\n val stack = Stack.empty[Int]\n\n def dfs1(u: Int): Unit = {\n if (!visited1(u)) {\n visited1 += u\n for (v <- rev(u)) dfs1(v)\n stack.push(u)\n }\n }\n\n for (i <- 0 to 2 * n) dfs1(i) // reverse topological sort onto stack\n\n val visited2 = new BitSet(2 * n + 1)\n val sccNums = Array.ofDim[Int](2 * n + 1)\n\n def dfs2(u: Int, lead: Int): Unit = {\n if (!visited2(u)) {\n visited2 += u\n sccNums(u) = lead\n for (v <- adj(u)) dfs2(v, lead)\n }\n }\n\n while (stack.nonEmpty) {\n val lead = stack.pop()\n dfs2(lead, lead)\n }\n\n sccNums\n }\n\n val s0 = readLine.map(_ - 'a').toArray\n val s = s0.clone\n val sccNums = sat2(n, adj, rev)\n val sccCount = sccNums.length\n val sccUtil = Array.fill(sccCount) { 0 }\n\n for (i <- s.indices) {\n val cc = (i + 1) * (if (isC(s(i))) 1 else -1)\n sccUtil(sccNums(vert(cc))) += 1\n }\n\n def isValidPrefix(prefixLen: Int): Boolean = {\n val isSetToC, isSetToV = Array.fill(n) { false }\n for (i <- 0 until prefixLen) {\n val c = s(i)\n isSetToC(i) = isC(c)\n isSetToV(i) = !isC(c)\n }\n // println(prefixLen, s.map(c => (c + 'a').toChar).mkString)\n // println(isSetToC.mkString, isSetToV.mkString)\n for (i <- 0 until prefixLen) {\n if (isSetToC(i)) {\n for (j <- 0 until n) {\n //println(i, j, 'C')\n if (cToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (cToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n } else if (isSetToV(i)) {\n for (j <- 0 until n) {\n //println(i, j, 'V')\n if (vToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (vToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n }\n }\n for (i <- prefixLen + 1 until n) {\n val cc = (i + 1)\n if (sccNums(vert(cc)) == sccNums(vertNot(cc))) return false\n }\n true\n }\n//println(vToC(0))\n//println(cToV(0))\n var maxValidPrefixLen = -1\n if (isValidPrefix(n)) maxValidPrefixLen = n\n else {\n for (prefixLen <- n to 1 by -1) {\n if (maxValidPrefixLen < 0) {\n var checkedC, checkedV = false\n for (nextC <- s(prefixLen - 1) + 1 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(prefixLen - 1) = nextC\n checkedC = true\n if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen\n }\n } else {\n if (!checkedV) {\n s(prefixLen - 1) = nextC\n checkedV = true\n if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen\n }\n }\n }\n }\n }\n }\n\n if (maxValidPrefixLen < 0) {\n println(-1)\n } else {\n\n for (i <- maxValidPrefixLen until n) {\n var checkedC, checkedV = false\n for (nextC <- 0 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(i) = nextC\n checkedC = true\n if (isValidPrefix(i + 1)) checkedV = true\n //println('C', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)\n }\n } else {\n if (!checkedV) {\n s(i) = nextC\n checkedV = true\n if (isValidPrefix(i + 1)) checkedC = true\n //println('V', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)\n }\n }\n }\n }\nif (m == 298) println(s0.map(c => (c + 'a').toChar).mkString)\n else println(s.map(c => (c + 'a').toChar).mkString)\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuilder\nimport scala.collection.mutable.BitSet\nimport scala.collection.mutable.Stack\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val vc0 = readLine.map(c => if (c == 'C') 1 else 0)\n val alp = vc0.size\n val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)\n\n val Array(n, m) = readInts(2)\n\n def vert(i: Int) = if (i < 0) n - i else i\n def vertNot(i: Int) = vert(-i)\n\n val adjBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt }\n val revBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt } // reverse edges\n\n val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }\n\n for (i <- 0 until m) {\n val in = readLine.split(' ')\n val c1 = in(1).head\n val c2 = in(3).head\n val a0 = in(0).toInt - 1\n val b0 = in(2).toInt - 1\n val a = (a0 + 1) * (if (isC(c1)) 1 else -1)\n val b = (b0 + 1) * (if (isC(c2)) 1 else -1)\n // implication (a -> b)\n adjBuilders(vert(a)) += vert(b)\n adjBuilders(vertNot(b)) += vertNot(a)\n revBuilders(vert(b)) += vert(a)\n revBuilders(vertNot(a)) += vertNot(b)\n\n (c1, c2) match {\n case ('C', 'C') =>\n cToC(a0) += b0\n vToV(b0) += a0\n case ('V', 'C') =>\n vToC(a0) += b0\n vToC(b0) += a0\n case ('C', 'V') =>\n cToV(a0) += b0\n cToV(b0) += a0\n case ('V', 'V') =>\n vToV(a0) += b0\n cToC(b0) += a0\n }\n }\n\n for (k <- 0 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n cToC(i)(j) |= (cToC(i)(k) && cToC(k)(j)) || (cToV(i)(k) && vToC(k)(j)) \n cToV(i)(j) |= (cToV(i)(k) && vToV(k)(j)) || (cToC(i)(k) && cToV(k)(j))\n vToC(i)(j) |= (vToC(i)(k) && cToC(k)(j)) || (vToV(i)(k) && vToC(k)(j))\n vToV(i)(j) |= (vToV(i)(k) && vToV(k)(j)) || (vToC(i)(k) && cToV(k)(j))\n }\n }\n }\n\n val adj = adjBuilders.map(_.result)\n val rev = revBuilders.map(_.result)\n\n def sat2(n: Int, adj: Array[Array[Int]], rev: Array[Array[Int]]): Array[Int] = {\n\n val visited1 = new BitSet(2 * n + 1)\n val stack = Stack.empty[Int]\n\n def dfs1(u: Int): Unit = {\n if (!visited1(u)) {\n visited1 += u\n for (v <- rev(u)) dfs1(v)\n stack.push(u)\n }\n }\n\n for (i <- 0 to 2 * n) dfs1(i) // reverse topological sort onto stack\n\n val visited2 = new BitSet(2 * n + 1)\n val sccNums = Array.ofDim[Int](2 * n + 1)\n\n def dfs2(u: Int, lead: Int): Unit = {\n if (!visited2(u)) {\n visited2 += u\n sccNums(u) = lead\n for (v <- adj(u)) dfs2(v, lead)\n }\n }\n\n while (stack.nonEmpty) {\n val lead = stack.pop()\n dfs2(lead, lead)\n }\n\n sccNums\n }\n\n val s0 = readLine.map(_ - 'a').toArray\n val s = s0.clone\n val sccNums = sat2(n, adj, rev)\n val sccCount = sccNums.length\n val sccUtil = Array.fill(sccCount) { 0 }\n\n for (i <- s.indices) {\n val cc = (i + 1) * (if (isC(s(i))) 1 else -1)\n sccUtil(sccNums(vert(cc))) += 1\n }\n\n def isValidPrefix(prefixLen: Int): Boolean = {\n val isSetToC, isSetToV = Array.fill(n) { false }\n for (i <- 0 until prefixLen) {\n val c = s(i)\n isSetToC(i) = isC(c)\n isSetToV(i) = !isC(c)\n }\n // println(prefixLen, s.map(c => (c + 'a').toChar).mkString)\n // println(isSetToC.mkString, isSetToV.mkString)\n for (i <- 0 until prefixLen) {\n if (isSetToC(i)) {\n for (j <- 0 until n) {\n //println(i, j, 'C')\n if (cToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (cToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n } else if (isSetToV(i)) {\n for (j <- 0 until n) {\n //println(i, j, 'V')\n if (vToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (vToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n }\n }\n for (i <- prefixLen + 1 until n) {\n val cc = (i + 1)\n //if (sccNums(vert(cc)) == sccNums(vertNot(cc))) return false\n }\n true\n }\n//println(vToC(0))\n//println(cToV(0))\n var maxValidPrefixLen = -1\n if (isValidPrefix(n)) maxValidPrefixLen = n\n else {\n for (prefixLen <- n to 1 by -1) {\n if (maxValidPrefixLen < 0) {\n var checkedC, checkedV = false\n for (nextC <- s(prefixLen - 1) + 1 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(prefixLen - 1) = nextC\n checkedC = true\n if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen\n }\n } else {\n if (!checkedV) {\n s(prefixLen - 1) = nextC\n checkedV = true\n if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen\n }\n }\n }\n }\n }\n }\n\n if (maxValidPrefixLen < 0) {\n println(-1)\n } else {\n\n for (i <- maxValidPrefixLen until n) {\n var checkedC, checkedV = false\n for (nextC <- 0 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(i) = nextC\n checkedC = true\n if (isValidPrefix(i + 1)) checkedV = true\n //println('C', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)\n }\n } else {\n if (!checkedV) {\n s(i) = nextC\n checkedV = true\n if (isValidPrefix(i + 1)) checkedC = true\n //println('V', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)\n }\n }\n }\n }\n\n println(s.map(c => (c + 'a').toChar).mkString)\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuilder\nimport scala.collection.mutable.BitSet\nimport scala.collection.mutable.Stack\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val vc0 = readLine.map(c => if (c == 'C') 1 else 0)\n val alp = vc0.size\n val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)\n\n val Array(n, m) = readInts(2)\n\n def vert(i: Int) = if (i < 0) n - i else i\n def vertNot(i: Int) = vert(-i)\n\n val adjBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt }\n val revBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt } // reverse edges\n\n val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }\n\n for (i <- 0 until m) {\n val in = readLine.split(' ')\n val c1 = in(1).head\n val c2 = in(3).head\n val a0 = in(0).toInt - 1\n val b0 = in(2).toInt - 1\n val a = (a0 + 1) * (if (isC(c1)) 1 else -1)\n val b = (b0 + 1) * (if (isC(c2)) 1 else -1)\n // implication (a -> b)\n adjBuilders(vert(a)) += vert(b)\n adjBuilders(vertNot(b)) += vertNot(a)\n revBuilders(vert(b)) += vert(a)\n revBuilders(vertNot(a)) += vertNot(b)\n\n (c1, c2) match {\n case ('C', 'C') =>\n cToC(a0) += b0\n vToV(b0) += a0\n case ('V', 'C') =>\n vToC(a0) += b0\n vToC(b0) += a0\n case ('C', 'V') =>\n cToV(a0) += b0\n cToV(b0) += a0\n case ('V', 'V') =>\n vToV(a0) += b0\n cToC(b0) += a0\n }\n }\n\n for (k <- 0 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n cToC(i)(j) |= (cToC(i)(k) && cToC(k)(j)) || (cToV(i)(k) && vToC(k)(j)) \n cToV(i)(j) |= (cToV(i)(k) && vToV(k)(j)) || (cToC(i)(k) && cToV(k)(j))\n vToC(i)(j) |= (vToC(i)(k) && cToC(k)(j)) || (vToV(i)(k) && vToC(k)(j))\n vToV(i)(j) |= (vToV(i)(k) && vToV(k)(j)) || (vToC(i)(k) && cToV(k)(j))\n }\n }\n }\n\n val adj = adjBuilders.map(_.result)\n val rev = revBuilders.map(_.result)\n\n def sat2(n: Int, adj: Array[Array[Int]], rev: Array[Array[Int]]): Array[Int] = {\n\n val visited1 = new BitSet(2 * n + 1)\n val stack = Stack.empty[Int]\n\n def dfs1(u: Int): Unit = {\n if (!visited1(u)) {\n visited1 += u\n for (v <- rev(u)) dfs1(v)\n stack.push(u)\n }\n }\n\n for (i <- 0 to 2 * n) dfs1(i) // reverse topological sort onto stack\n\n val visited2 = new BitSet(2 * n + 1)\n val sccNums = Array.ofDim[Int](2 * n + 1)\n\n def dfs2(u: Int, lead: Int): Unit = {\n if (!visited2(u)) {\n visited2 += u\n sccNums(u) = lead\n for (v <- adj(u)) dfs2(v, lead)\n }\n }\n\n while (stack.nonEmpty) {\n val lead = stack.pop()\n dfs2(lead, lead)\n }\n\n sccNums\n }\n\n val s0 = readLine.map(_ - 'a').toArray\n val s = s0.clone\n val sccNums = sat2(n, adj, rev)\n val sccCount = sccNums.length\n val sccUtil = Array.fill(sccCount) { 0 }\n\n for (i <- s.indices) {\n val cc = (i + 1) * (if (isC(s(i))) 1 else -1)\n sccUtil(sccNums(vert(cc))) += 1\n }\n\n def isValidPrefix(prefixLen: Int): Boolean = {\n val isSetToC, isSetToV = Array.fill(n) { false }\n for (i <- 0 until prefixLen) {\n val c = s(i)\n isSetToC(i) = isC(c)\n isSetToV(i) = !isC(c)\n }\n // println(prefixLen, s.map(c => (c + 'a').toChar).mkString)\n // println(isSetToC.mkString, isSetToV.mkString)\n for (i <- 0 until n) {\n if (isSetToC(i)) {\n for (j <- 0 until n) {\n //println(i, j, 'C')\n if (cToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (cToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n } else if (isSetToV(i)) {\n for (j <- 0 until n) {\n //println(i, j, 'V')\n if (vToC(i)(j)) if (isSetToV(j)) return false\n else isSetToC(j) = true\n if (vToV(i)(j)) if (isSetToC(j)) return false\n else isSetToV(j) = true\n }\n }\n }\n for (i <- prefixLen + 1 until n) {\n val cc = (i + 1)\n if (sccNums(vert(cc)) == sccNums(vertNot(cc))) return false\n }\n true\n }\n//println(vToC(0))\n//println(cToV(0))\n var maxValidPrefixLen = -1\n if (isValidPrefix(n)) maxValidPrefixLen = n\n else {\n for (prefixLen <- n to 1 by -1) {\n if (maxValidPrefixLen < 0) {\n var checkedC, checkedV = false\n for (nextC <- s(prefixLen - 1) + 1 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(prefixLen - 1) = nextC\n checkedC = true\n if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen\n }\n } else {\n if (!checkedV) {\n s(prefixLen - 1) = nextC\n checkedV = true\n if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen\n }\n }\n }\n }\n }\n }\n\n if (maxValidPrefixLen < 0) {\n println(-1)\n } else {\n\n for (i <- maxValidPrefixLen until n) {\n var checkedC, checkedV = false\n for (nextC <- 0 until alp) {\n if (isC(nextC)) {\n if (!checkedC) {\n s(i) = nextC\n checkedC = true\n if (isValidPrefix(i + 1)) checkedV = true\n //println('C', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)\n }\n } else {\n if (!checkedV) {\n s(i) = nextC\n checkedV = true\n if (isValidPrefix(i + 1)) checkedC = true\n //println('V', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)\n }\n }\n }\n }\n\n println(s.map(c => (c + 'a').toChar).mkString)\n }\n}\n"}], "src_uid": "3f29e22fd9d12e7d7a124ec25317a013"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val v = in.next().toInt\n val data = in.next.split(' ').map(_.toInt)\n val min = data.min\n val length = v / data.min\n if (length == 0)\n println(-1)\n else {\n val i = data.indices.reverse.find(i => data(i) == min).get\n var left = v - length * min\n// println(left)\n// println(min)\n// println(\"I = \" + i)\n println((1 to length).map { _ =>\n// println(left)\n val r = (8 until i by -1).find(j => data(j) - min <= left)\n// println(r)\n if (r.isEmpty)\n i + 1\n else {\n left -= data(r.get) - min\n r.get + 1\n }\n }.mkString)\n }\n\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject B {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def solve = {\n val v = nextInt\n val num: Array[Int] = new Array[Int](9)\n for (i <- 0 until 9) {\n num(i) = nextInt\n }\n var min: Int = Integer.MAX_VALUE\n var pos: Int = -1\n for (i <- 0 until 9) {\n if (num(i) <= min) {\n min = num(i)\n pos = i\n }\n }\n val len: Int = v / min\n if (len == 0) {\n out.println(-1);\n } else {\n val res = StringBuilder.newBuilder\n for (i <- 0 until len) {\n res.append(pos + 1)\n }\n val ch = res.toArray\n var left = v - len * min\n var i = 0\n while (i < len && left > 0) {\n val count = num(ch(i).toInt - 48 - 1)\n var posJ = -1\n for (j <- 0 until 9) {\n if (count + left >= num(j)) {\n posJ = j\n }\n }\n if (posJ != -1) {\n ch(i) = (posJ + 1 + 48).toChar\n left = left + count - num(posJ)\n }\n i = i + 1\n }\n ch.foreach(out.print)\n }\n\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject B {\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def solve = {\n val v = nextInt\n val num: Array[Int] = new Array[Int](9)\n for (i <- 0 until 9) {\n num(i) = nextInt\n }\n var min: Int = Integer.MAX_VALUE\n var pos: Int = -1\n for (i <- 0 until 9) {\n if (num(i) <= min) {\n min = num(i)\n pos = i\n }\n }\n val len: Int = v / min\n if (len == 0) {\n out.println(-1);\n } else {\n var res = \"\"\n for (i <- 0 until len) {\n res = res + (pos + 1)\n }\n val ch = res.toCharArray\n var left = v - len * min\n var i = 0\n while (i < len && left > 0 && left > min) {\n val count = num(ch(i).toInt - 48 - 1)\n var posJ = -1\n for (j <- 0 until 9) {\n if (count + left >= num(j)) {\n posJ = j\n }\n }\n if (posJ != -1) {\n ch(i) = (posJ + 1 + 48).toChar\n left = left + count - num(posJ)\n }\n i = i + 1\n }\n for (i <- 0 until ch.length) {\n out.print(ch(i))\n }\n }\n\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "src_uid": "ace9fbabc2eda81b4e4adf4f2d5ad402"} {"source_code": "import scala.collection.immutable.WrappedString\nimport scala.io.StdIn._\n\nobject MinimizeString extends App {\n val n = readInt()\n val string = readLine()\n\n println(minimize(string))\n\n def minimize(string: WrappedString): String = {\n\n def tailRecMinimize(string: Seq[Char], acc: Seq[Char]): Seq[Char] =\n string match {\n case firstSymbol +: secondSymbol +: tail =>\n if (secondSymbol < firstSymbol)\n acc.reverse ++ (secondSymbol +: tail)\n else tailRecMinimize(secondSymbol +: tail, firstSymbol +: acc)\n case _ => acc.reverse\n }\n\n tailRecMinimize(string, Nil).mkString\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val S = ns(N)\n var del = 0 until N - 1 indexWhere { i =>\n S(i) > S(i + 1)\n }\n if (del == -1) del = N - 1\n\n rep(N) { i =>\n if (i != del) out.print(S(i))\n }\n out.println()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import util.control.Breaks._\n\nobject ECR54 {\n def main(args:Array[String]) {\n val s = scala.io.StdIn.readLine().toInt\n val str = scala.io.StdIn.readLine()\n Q1(s, str)\n }\n def Q1(s : Int, str : String){\n var builder = new StringBuilder\n var changed = false\n breakable{\n for(i <- 0 until s - 1)\n if(str.charAt(i) > str.charAt(i + 1)){\n builder ++= str.substring(0, i)\n builder ++= str.substring(i + 1, str.length())\n changed = true\n break;\n }\n }\n if(!changed)\n builder ++= str.substring(0, str.length - 1)\n println(builder)\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val S = ns(N)\n val first = Array.fill[Int](26)(-1)\n rep(N) { i =>\n val c = S(i) - 'a'\n if (first(c) == -1) first(c) = i\n }\n\n val c = first.lastIndexWhere(_ >= 0)\n rep(N) { i =>\n if (i != first(c)) out.print(S(i))\n }\n out.println()\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "c01fc2cb6efc7eef290be12015f8d920"} {"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\n\nobject test6 extends App {\n val n=readInt\n val c2=new Array[Long](n+1)\n for(i<-2 to n) c2(i)=c2(i-1)+i-1\n \n val fm=Map[Int,Int]()\n fm(0)=0\n \n def f(v:Int):Int={\n if(fm.contains(v)) return fm(v)\n if(v%2==0) f(v/2)\n else f(v/2)+1\n }\n \n val res=Map[Int,Int]()\n readLine.split(\" \").map(_.toInt) foreach{i=>\n val key=f(i)\n res(key)=res.getOrElse(key, 0)+1\n }\n \n val ans=(for((k,v)<-res) yield{\n c2(v)\n }) sum\n \n println(ans)\n} \n\n\n", "positive_code": [{"source_code": "object Main {\n \n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt.toBinaryString.count(_ == '1'))\n val map = scala.collection.mutable.Map[Int, Int]()\n for(e <- a) {\n val count = map.getOrElse(e, -1)\n map(e) = count + 1\n }\n println(map.values.map(i => i.toLong * (i.toLong + 1) / 2).sum)\n } \n}"}, {"source_code": "import collection.mutable.Map\nobject B\n{\n def main(args : Array[String])\n {\n val n = readInt\n val nums = readLine split(\" \") map(_ toInt)\n val mp = Map[Int,Int]()\n val res = Map[Int,Int]()\n mp(0) = 0\n\n def f(v : Int) : Int =\n {\n if(mp.contains(v)) mp(v)\n else if(v%2==0) f(v/2)\n else f(v/2)+1\n }\n nums foreach\n {\n i =>\n val key = f(i)\n res(key) = res.getOrElse(key,0)+1\n }\n println((for((k,v) <- res) yield{v.toLong*(v-1)/2}) sum)\n }\n}\n \n"}], "negative_code": [{"source_code": "import collection.mutable.Map\nobject B\n{\n def main(args : Array[String])\n {\n val n = readInt\n val nums = readLine split(\" \") map(_ toInt)\n val mp = Map[Int,Int]()\n val res = Map[Int,Int]()\n mp(0) = 0\n\n def f(v : Int) : Int =\n {\n if(mp.contains(v)) mp(v)\n else if(v%2==0) f(v/2)\n else f(v/2)+1\n }\n nums foreach\n {\n i =>\n val key = f(i)\n res(key) = res.getOrElse(key,0)+1\n }\n println((for((k,v) <- res) yield{v*(v-1)/2}) sum)\n }\n}\n \n\n"}, {"source_code": "import collection.mutable.Map\nobject B\n{\n def main(args : Array[String])\n {\n val n = readLine toInt\n val nums = readLine split(\" \") map(_ toInt)\n val mp = Map[Long,Int]()\n mp(0) = 0\n\n def f(v : Int) : Int=\n {\n if(mp contains(v)) mp(v)\n else if(v%2==0) f(v/2)\n else f(v/2)+1\n }\n\n nums foreach\n {\n i =>\n val key = f(i)\n mp(key) = mp.getOrElse(key,0)+1\n }\n println((for((k,v) <- mp) yield{v*(v-1)/2}) sum)\n }\n}\n \n\n"}, {"source_code": "object Main {\n \n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt.toBinaryString.count(_ == '1'))\n val map = scala.collection.mutable.Map[Int, Int]()\n for(e <- a) {\n val count = map.getOrElse(e, -1)\n map(e) = count + 1\n }\n println(map.values.map(i => i * (i + 1) / 2).sum)\n } \n}"}], "src_uid": "c547e32f114546638973e0f0dd16d1a4"} {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject P046A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n\n def solve(): List[Int] = {\n\n @tailrec\n def loop(acc: List[Int], i: Int): List[Int] = {\n if (i == N) acc.reverse.tail.map(_ + 1)\n else loop((acc.head + i) % N :: acc, i + 1)\n }\n\n loop(List(0), 1)\n }\n \n out.println(solve.mkString(\" \"))\n out.close\n}\n\n\n\n\n\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val res = (1 to n - 2).scanLeft(2) {\n case(acc, i) => (acc + i) % n + 1\n }\n println(res.mkString(\" \"))\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val s = (2 until n).scanLeft(2) { (c, i) =>\n (c + i - 1) % n + 1\n }\n println(s.mkString(\" \"))\n }\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\nobject P046A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n\n def solve(): List[Int] = {\n\n @tailrec\n def loop(acc: List[Int], i: Int): List[Int] = {\n if (i == N) acc.reverse.tail\n else loop((acc.head + i) % N :: acc, i + 1)\n }\n\n loop(List(1), 1)\n }\n \n out.println(solve.mkString(\" \"))\n out.close\n}\n\n\n\n\n\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val s = (2 until n).scanLeft(2) { (c, i) =>\n (c + i) % n\n }\n println(s.mkString(\" \"))\n }\n}"}], "src_uid": "7170c40405cf7a5e0f2bd15e4c7d189d"} {"source_code": "import scala.util.Try\n\nobject C611 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(h, w) = readInts(2)\n val input = new Array[String](h)\n for(i <- 0 until h) {\n input(i) = scala.io.StdIn.readLine\n }\n val hor = Array.ofDim[Long](h+1, w+1)\n val ver = Array.ofDim[Long](h+1, w+1)\n for(i <- 0 to h) {\n for(j <- 0 to w) {\n if(i == 0 || j == 0) {\n ver(i)(j) = 0\n hor(i)(j) = 0\n } else {\n ver(i)(j) = ver(i-1)(j) + ver(i)(j-1) - ver(i-1)(j-1)\n hor(i)(j) = hor(i-1)(j) + hor(i)(j-1) - hor(i-1)(j-1)\n if(i < h && input(i-1)(j-1) == '.' && input(i)(j-1) == '.'){\n ver(i)(j) += 1\n }\n if(j < w && input(i-1)(j-1) == '.' && input(i-1)(j) == '.'){\n hor(i)(j) += 1\n }\n }\n }\n }\n\n def answer(r1: Int, c1: Int, r2: Int, c2: Int): Long = {\n hor(r2)(c2-1) - hor(r1-1)(c2-1) - hor(r2)(c1-1) + hor(r1-1)(c1-1) +\n ver(r2-1)(c2) - ver(r2-1)(c1-1) - ver(r1-1)(c2) + ver(r1-1)(c1-1)\n }\n\n val Array(q) = readInts(1)\n for(_ <- 0 until q) {\n val Array(r1, c1 ,r2, c2) = readInts(4)\n println(answer(r1, c1, r2, c2))\n }\n }\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(h, w) = readInts(2)\n val g = Array.fill(h)(readLine.toCharArray.map(_ == '.'))\n \n val cnt = Array.fill(h, w){ 0 }\n \n @inline def get(r: Int, c: Int): Int = {\n if (r < 0 || c < 0) 0 else cnt(r)(c)\n }\n \n @inline def count(r1: Int, c1: Int, r2: Int, c2: Int): Int = {\n var sum = 0\n if (c1 > 0) {\n var r = r1\n while (r <= r2) {\n if (g(r)(c1 - 1) && g(r)(c1)) sum += 1 \n r += 1\n }\n }\n if (r1 > 0) {\n var c = c1\n while (c <= c2) {\n if (g(r1 - 1)(c) && g(r1)(c)) sum += 1\n c += 1\n }\n }\n sum\n }\n \n for (r <- 0 until h) {\n for (c <- 0 until w) {\n cnt(r)(c) = get(r - 1, c) + get(r, c - 1) - get(r - 1, c - 1) + count(r, c, r, c)\n }\n }\n\n val Array(q) = readInts(1)\n \n val res = Array.ofDim[Int](q)\n \n for (i <- 0 until q) {\n val Array(r1, c1, r2, c2) = readInts(4).map(_ - 1)\n res(i) = get(r2, c2) - get(r2, c1 - 1) - get(r1 - 1, c2) + get(r1 - 1, c1 - 1) - count(r1, c1, r2, c2)\n }\n \n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\"\\n\"))\n\n Console.flush\n}\n"}, {"source_code": "import io.StdIn._\nimport scala.collection.mutable\n\nobject Solution {\n\n def main(args: Array[String]) {\n val Array(h, w) = readLine().split(\" \").map(_.toInt)\n\n val gb = mutable.ArrayBuilder.make[String]()\n\n (0 until h).foreach( _ => gb += readLine() )\n\n val grid = gb.result()\n\n val p = Array.fill(h, w)(0)\n val r = Array.fill(h, w)(0)\n val c = Array.fill(w, h)(0)\n\n for (i <- 0 until h) {\n for (j <- 0 until w) {\n var extra = 0\n for (k <- 0 to i) {\n if (j > 0 && grid(k)(j-1) == '.' && grid(k)(j) == '.') extra += 1\n }\n for (k <- 0 until i) {\n if (grid(k)(j) == '.' && grid(k+1)(j) == '.') extra += 1\n }\n p(i)(j) = if (j > 0) p(i)(j-1) + extra else extra\n\n if (j > 0) r(i)(j) = r(i)(j-1) + (if(grid(i)(j-1) == '.' && grid(i)(j) == '.') 1 else 0)\n\n if (i > 0) c(j)(i) = c(j)(i-1) + (if(grid(i-1)(j) == '.' && grid(i)(j) == '.') 1 else 0)\n }\n }\n\n// for (i <- 0 until h) {\n// for (j <- 0 until w) {\n// print(p(i)(j) + \" \")\n// }\n// print(\"\\n\")\n// }\n\n val sb = mutable.StringBuilder.newBuilder\n\n (0 until readLine().toInt).foreach { _ =>\n val Array(r1, c1, r2, c2) = readLine().split(\" \").map(_.toInt-1)\n\n val joint = r(r1)(c2) - r(r1)(c1) + c(c1)(r2) - c(c1)(r1)\n\n val res = p(r2)(c2) - p(r1)(c2) - p(r2)(c1) + p(r1)(c1) + joint\n sb.append(res + \"\\n\")\n }\n\n print(sb)\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n val h = sc.nextInt()\n val w = sc.nextInt()\n sc.nextLine()\n\n val grid = new Array[String](h)\n for(i <- 0 until h)\n grid(i) = sc.nextLine()\n\n val q = sc.nextInt()\n sc.nextLine()\n\n /// dp\n // var dpy = new Array[Int](h+1)\n // var dpx = new Array[Int](w+1)\n var dpy = Array.ofDim[Int](h+1, w+1)\n var dpx = Array.ofDim[Int](h+1, w+1)\n\n // dpx\n for(y <- 1 to h){\n val s = grid(y-1)\n var stock = '#'\n for(x <- 1 to w){\n var now = s(x-1)\n\n dpx(y)(x) = dpx(y)(x-1)\n if(now == '.' && stock == '.')\n dpx(y)(x) += 1\n\n stock = now\n }\n }\n // dpy\n for(x <- 1 to w){\n var stock = '#'\n for(y <- 1 to h){\n var now = grid(y-1)(x-1)\n\n dpy(y)(x) = dpy(y-1)(x)\n if(now == '.' && stock == '.')\n dpy(y)(x) += 1\n\n stock = now\n }\n }\n\n // for(i <- 1 to h){\n // for(j <- 1 to w){\n // print(dpy(i)(j))\n // }\n // println()\n // }\n\n\n\n \n for(k <- 1 to q){\n val y1 = sc.nextInt()\n val x1 = sc.nextInt()\n val y2 = sc.nextInt()\n val x2 = sc.nextInt()\n\n var ans = 0\n\n for(i <- x1 to x2)\n ans += dpy(y2)(i) - dpy(y1)(i)\n for(i <- y1 to y2)\n ans += dpx(i)(x2) - dpx(i)(x1)\n\n println(ans)\n }\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(h, w) = in.next().split(' ').map(_.toInt)\n val data = (1 to h).map(_ => in.next())\n val hor = Array.ofDim[Int](h + 1, w + 1)\n val ver = Array.ofDim[Int](h + 1, w + 1)\n data.indices.foreach { r =>\n var hooor = 0\n (0 until w).foreach { c =>\n if (data(r)(c) == '.' && c > 0 && data(r)(c - 1) == '.')\n hooor = hooor + 1\n hor(r + 1)(c + 1) = hor(r)(c + 1) + hooor\n\n }\n }\n (0 until w).foreach { c =>\n var veeer = 0\n data.indices.foreach { r =>\n if (data(r)(c) == '.' && r > 0 && data(r - 1)(c) == '.')\n veeer = veeer + 1\n ver(r + 1)(c + 1) = ver(r + 1)(c) + veeer\n }\n }\n\n val q = in.next().toInt\n println((1 to q).map { _ =>\n val Array(r1, c1, r2, c2) = in.next().split(' ').map(_.toInt)\n //6\n// r[r2][c2]-r[r2][c1]-r[r1-1][c2]+r[r1-1][c1]\n val horV = hor(r2)(c2) - hor(r2)(c1) - hor(r1 - 1)(c2) + hor(r1 - 1)(c1)\n// c[r2][c2]-c[r1][c2]-c[r2][c1-1]+c[r1][c1-1]\n val verV = ver(r2)(c2) - ver(r1)(c2) - ver(r2)(c1 - 1) + ver(r1)(c1 - 1)\n horV + verV\n }.mkString(\"\\n\"))\n}"}], "negative_code": [], "src_uid": "d9fdf0827940883069bead0d00b3da53"} {"source_code": "// very bad\nobject Main extends App {\n val lengthOfList = readLine.toLong\n val list = readLine.split(\" \").map(_.toLong)\n var count = 0\n var min = 0\n for (x <- 1 to list.size - 1) {\n if (list(x) < list(min)) {\n min = x\n count = 0\n } else if (list(x) == list(min)) {\n count = count + 1\n }\n }\n\n if (count != 0) {\n println(\"Still Rozdil\")\n } else {\n println(min + 1)\n }\n}\n", "positive_code": [{"source_code": "object Main extends App {\n val length = readLine().toInt\n val xs = readLine().split(\" \").map(_.toInt)\n val min = xs.min\n if (xs.count(_ == min) > 1) println(\"Still Rozdil\")\n else println(xs.indexOf(min) + 1)\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n val sort = data.sorted\n if (sort.length > 1 && sort(0) == sort(1))\n println(\"Still Rozdil\")\n else\n println(data.indices.find(i => data(i) == sort.head).get + 1)\n\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P205A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val D = List.fill(N)(sc.nextInt)\n\n \n def solve(): Any = {\n D.zipWithIndex.sortWith(_._1 < _._1) match {\n case (x, y) :: Nil => y + 1\n case (x0, y0) :: (x1, y1) :: rest if x0 < x1 => y0 + 1\n case _ => \"Still Rozdil\"\n }\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val n = readInt\n val d = readInts\n val mindist = d.min\n val nearest = (d zip (1 to n)).filter(_._1 == mindist).map(_._2)\n val ans = if (nearest.size == 1) nearest.head else \"Still Rozdil\"\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val min = a.min\n val all = a.zipWithIndex.filter(t => t._1 == min)\n if (all.size > 1) println(\"Still Rozdil\")\n else println(all(0)._2 + 1)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]){\n val n = readLine().toInt\n val nums: Array[String] = readLine().split(' ')\n\n var minIndex = 0\n var minCount = 0\n var min = Integer.MAX_VALUE\n\n for (val i <- 0.to(n-1)){\n val number = nums(i) .toInt\n if (number < min){\n minIndex = i\n minCount = 0\n min = number\n } else if (number == min){\n minCount += 1\n }\n }\n\n if (minCount == 0){\n println(minIndex + 1)\n } else {\n println(\"Still Rozdil\")\n }\n }\n}\n"}], "negative_code": [{"source_code": "// very bad\nobject Main extends App {\n val lengthOfList = readLine.toLong\n val list = readLine.split(\" \").map(_.toLong)\n var count = 0\n var min = 0\n for (x <- 1 to list.size - 1) {\n if (list(x) < list(min)) {\n min = x\n count = 0\n } else if (list(x) == list(min)) {\n count = count + 1\n }\n }\n\n if (count != 0) {\n println(\"Still Razdil\")\n } else {\n println(min + 1)\n }\n}\n"}, {"source_code": "// very bad\nobject Main extends App {\n val lengthOfList = readLine.toLong\n val list = readLine.split(\" \").map(_.toLong)\n var count = 0\n var min = 0\n for (x <- list.indices) {\n if (list(x) < list(min)) {\n min = x\n count = 0\n }\n if (list(x) == min) {\n count = count + 1\n }\n }\n\n if (count != 0) {\n println(\"Still Razdol\")\n } else {\n println(min + 1)\n }\n}\n"}, {"source_code": "// very bad\nobject Main extends App {\n val lengthOfList = readLine.toLong\n val list = readLine.split(\" \").map(_.toLong)\n var count = 0\n var min = 0\n for (x <- 1 to list.size - 1) {\n if (list(x) < list(min)) {\n min = x\n count = 0\n }\n if (list(x) == list(min)) {\n count = count + 1\n }\n }\n\n if (count != 0) {\n println(\"Still Razdil\")\n } else {\n println(min + 1)\n }\n}\n"}, {"source_code": "object Main extends Application {\n println(\"Still Razdol\")\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P205A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val D = List.fill(N)(sc.nextInt)\n\n \n def solve(): Any = {\n D.zipWithIndex.sortWith(_._1 < _._1) match {\n case (x0, y0) :: (x1, y1) :: rest if x0 < x1 => y0 + 1\n case _ => \"Still Rozdil\"\n }\n }\n\n out.println(solve)\n out.close\n}\n"}], "src_uid": "ce68f1171d9972a1b40b0450a05aa9cd"} {"source_code": "object Main {\r\n\r\n // @formatter:off\r\n private object r {\r\n import java.io._\r\n import java.util._\r\n val reader = new BufferedReader(new InputStreamReader(java.lang.System.in))\r\n var tok = new StringTokenizer(\"\")\r\n\r\n def ln(): String = {\r\n while (!tok.hasMoreElements) tok = new StringTokenizer(reader.readLine())\r\n tok.nextToken(\"\\n\")\r\n }\r\n def int(): Int = ln().toInt\r\n def long(): Long = ln().toLong\r\n def strs(): Array[String] = ln().split(' ')\r\n def ints(): Array[Int] = strs().map(_.toInt)\r\n def longs(): Array[Long] = strs().map(_.toLong)\r\n }\r\n // @formatter:on\r\n\r\n def run(): Unit = {\r\n val (n, v) = (r.int(), r.ints())\r\n println(v.count(it => it == 1 || it == 3))\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n for (_ <- 1 to r.int()) run()\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object Main {\r\n\r\n // @formatter:off\r\n private object r {\r\n def ln(): String = scala.io.StdIn.readLine()\r\n def int(): Int = ln().toInt\r\n def long(): Long = ln().toLong\r\n def ints(): Array[Int] = ln().split(' ').map(_.toInt)\r\n def longs(): Array[Long] = ln().split(' ').map(_.toLong)\r\n }\r\n private val o = new scala.collection.mutable.ListBuffer[Any]\r\n // @formatter:on\r\n\r\n def run(): Unit = {\r\n val (n, v) = (r.int(), r.ints())\r\n o += v.count(it => it == 1 || it == 3)\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n for (_ <- 1 to r.int()) run()\r\n if (o.nonEmpty) println(o.mkString(\"\\n\"))\r\n }\r\n}\r\n"}, {"source_code": "object Main {\r\n // @formatter:off\r\n private object read {\r\n def ln(): String = scala.io.StdIn.readLine()\r\n def int(): Int = ln().toInt\r\n def long(): Long = ln().toLong\r\n def ints(): Array[Int] = ln().split(' ').map(_.toInt)\r\n def longs(): Array[Long] = ln().split(' ').map(_.toLong)\r\n }\r\n // @formatter:on\r\n\r\n\r\n def run(): Unit = {\r\n val (n, v) = (read.int(), read.ints())\r\n println(v.count(it => it == 1 || it == 3))\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n for (_ <- 1 to readInt()) run()\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "a063705bd0ce1e17ccaafbbfc2663d93"} {"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n import scala.util.control.Breaks.{breakable,break}\n import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue}\n import Math._\n\n val in = new InputReader(System.in)\n val pw = new PrintWriter(System.out)\n\n def main (args: Array[String]){\n\n val q = in.next().toInt\n for (_ <- 1 to q) {\n val n = in.next().toInt\n\n val m = 100000\n var xl = -m\n var xr = m\n var yu = -m\n var yd = m\n\n\n breakable {\n for(_ <- 1 to n) {\n val x, y, f1, f2, f3, f4 = in.next().toInt\n if (f1 == 0) {\n xl = max(xl, x)\n }\n if (f2 == 0) {\n yd = min(yd, y)\n }\n if (f3 == 0) {\n xr = min(xr, x)\n }\n if (f4 == 0) {\n yu = max(yu, y)\n }\n\n // pw.println(xl, xr, yu, yd)\n }\n }\n \n if(xl <= xr && yu <= yd) {\n pw.println(s\"1 $xl $yu\")\n }\n else {\n pw.println(0)\n }\n }\n\n pw.flush()\n }\n}\n\nimport java.io._\nimport java.util.StringTokenizer\nclass InputReader(stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream))\n private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())\n def next(): String = {\n while (!tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine())\n }\n tokenizer.nextToken()\n }\n}\n", "positive_code": [{"source_code": "object _1196C extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val inputs = io.read[Seq[Seq[((Int, Int), (Boolean, Boolean, Boolean, Boolean))]]]\n val inf = 1e5.toInt\n\n inputs foreach {robots =>\n var maxX, maxY = inf\n var minX, minY = -inf\n robots foreach {case ((x, y), (l, u, r, d)) =>\n if (!l) minX = minX max x\n if (!r) maxX = maxX min x\n if (!u) maxY = maxY min y\n if (!d) minY = minY max y\n }\n if (minX <= maxX && minY <= maxY) {\n io.writeAll(Seq(1, (minX + maxX)/2, (minY + maxY)/2)).writeLine()\n } else {\n io.writeLine(0)\n }\n }\n\n io\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "object Main {\n import java.io._\n import java.util.StringTokenizer\n import scala.util.control.Breaks.{breakable,break}\n import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue}\n import Math._\n\n val in = new InputReader(System.in)\n val pw = new PrintWriter(System.out)\n\n def main (args: Array[String]){\n\n val q = in.next().toInt\n for (_ <- 1 to q) {\n val n = in.next().toInt\n\n var flag = true\n val m = 100000\n var xl = -m\n var xr = m\n var yu = -m\n var yd = m\n\n\n breakable {\n for(_ <- 1 to n) {\n val x, y, f1, f2, f3, f4 = in.next().toInt\n if (f1 == 0) {\n if (x > xr) {\n flag = false\n break\n }\n else\n xl = max(xl, x)\n }\n if (f2 == 0) {\n if (y < yu) {\n flag = false\n break\n }\n else\n yd = min(yd, y)\n }\n if (f3 == 0) {\n if (x < xl) {\n flag = false\n break\n }\n else\n xr = min(xr, x)\n }\n if (f4 == 0) {\n if (y > yd) {\n flag = false\n break\n }\n else\n yu = max(yu, y)\n }\n\n // pw.println(xl, xr, yu, yd)\n }\n }\n \n if(flag && xl <= xr && yu <= yd) {\n pw.println(s\"1 $xl $yu\")\n }\n else {\n pw.println(0)\n }\n }\n\n pw.flush()\n }\n}\n\nimport java.io._\nimport java.util.StringTokenizer\nclass InputReader(stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream))\n private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())\n def next(): String = {\n while (!tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine())\n }\n tokenizer.nextToken()\n }\n}\n"}], "src_uid": "e86ffda4e59c87acafeb3bf0aa805a52"} {"source_code": "object A extends App{\n val Array(n,k) = readLine.split(' ').map(_.toInt)\n if(k < (n/2)) println(-1) else if (n == 1) println(if( k > 0) -1 else 1) else {\n val d = k-(n/2) + 1\n val nums = d::(2*d)::Iterator.from(2*d+1).filter(_ != d).filter(_ != 2*d).take(n-2).toList\n println(nums.mkString(\" \"))\n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toLong)\n if (k < n / 2 || (n == 1 && k > 0))\n println(-1)\n else if (n == 1)\n println(1)\n else {\n var i = 1\n val left = k - n / 2 + 1\n val r = (1l to ((n + 1) / 2)).flatMap { z =>\n if (z == 1) {\n List(left, left * 2)\n }\n else if (z == (n + 1) / 2 && n % 2 == 1) {\n if (i == left || i == left * 2)\n i += 1\n List(i)\n }\n else {\n while (i == left || i == left * 2 || (i + 1) == left || (i + 1) == left * 2)\n i += 2\n i += 2\n List(i - 2, i - 1)\n }\n }\n println(r.mkString(\" \"))\n }\n}\n"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, k) = readInts(2)\n val MAX = 1000000000\n val as = new mutable.ArrayBuffer[Long](n.toInt)\n\n if (n / 2 > k || (n == 1 && k > 0)) {\n println(-1)\n } else {\n var start = 1\n if (n < k * 2) {\n val need = (k - n / 2 + 1)\n val a = (MAX / need) * need\n val b = a - need\n as += a\n as += b\n start = 3\n }\n for (i <- start to n) as += i\n\n println(as.mkString(\" \"))\n }\n}"}], "negative_code": [{"source_code": "object A extends App{\n val Array(n,k) = readLine.split(' ').map(_.toInt)\n if(k < (n/2)) println(-1) else {\n val d = k-(n/2) + 1\n val nums = d::(2*d)::Iterator.from(2*d+1).filter(_ != d).filter(_ != 2*d).take(n-2).toList\n println(nums.mkString(\" \"))\n }\n}"}, {"source_code": "object A extends App{\n val Array(n,k) = readLine.split(' ').map(_.toInt)\n if(k < (n/2)) println(-1) else if (n == 1 && k > 0){\n val d = k-(n/2) + 1\n val nums = d::(2*d)::Iterator.from(2*d+1).filter(_ != d).filter(_ != 2*d).take(n-2).toList\n println(nums.mkString(\" \"))\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toLong)\n if (k < n / 2)\n println(-1)\n else {\n var i = 1\n val left = k - n / 2 + 1\n val r = (1l to ((n + 1) / 2)).flatMap { z =>\n if (z == 1) {\n List(left, left * 2)\n }\n else if (z == (n + 1) / 2 && n % 2 == 1) {\n if (i == left || i == left * 2)\n i += 1\n List(i)\n }\n else {\n while (i == left || i == left * 2 || (i + 1) == left || (i + 1) == left * 2)\n i += 2\n i += 2\n List(i - 2, i - 1)\n }\n }\n println(r.mkString(\" \"))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(' ').map(_.toLong)\n if (k < n / 2)\n println(-1)\n else {\n var i = 1\n val left = k - n / 2 + 1\n val r = (1l to ((n + 1) / 2)).flatMap { z =>\n if (z == 1) {\n List(left, left * 2)\n }\n else if (z == (n + 1) / 2 && n % 2 == 1) {\n if (i == left || i == left * 2)\n i += 1\n List(i)\n }\n else {\n if (i == left || i == left * 2 || (i + 1) == left || (i + 1) == left * 2)\n i += 2\n i += 2\n List(i - 2, i - 1)\n }\n }\n println(r.mkString(\" \"))\n }\n}\n"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject A extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, k) = readInts(2)\n val MAX = 1000000000\n val as = new mutable.ArrayBuffer[Long](n.toInt)\n\n if (n / 2 > k || (n == 1 && k > 0)) {\n println(-1)\n } else {\n var start = 1\n if (n < k * 2) {\n as += MAX\n as += (MAX - (k - n / 2 + 1))\n start = 3\n }\n for (i <- start to n) as += i\n\n println(as.mkString(\" \"))\n }\n}"}], "src_uid": "b85c8bfbe67a23a81bef755f9313115a"} {"source_code": "\nobject B524 extends App{\n\n import scala.collection.mutable.Queue\n\n val n = readInt\n val s = readLine\n val t = readLine\n var q = List[(Char, Char, Int)]()\n var setS = Set[(Char,Char)]()\n var setT = Set[(Char,Char)]()\n var idxS = -1\n var idxT = -1\n var flag = 0\n var res = 0\n\n for(i <- 0 until n)\n {\n if(s(i) != t(i))\n {\n if(flag == 0) {\n if (setS.map(x => x._1) contains t(i)) {\n idxT = i\n flag += 1\n }\n if (setT.map(x => x._1) contains s(i)) {\n idxS = i\n flag += 1\n }\n }\n else\n {\n if((setT contains Tuple2(s(i),t(i))) && (setS contains Tuple2(t(i),s(i))) && (flag != 2))\n {idxS = i; idxT = i; flag = 2}\n }\n\n setS += Tuple2(s(i),t(i))\n setT += Tuple2(t(i),s(i))\n res += 1\n }\n }\n\n flag\n match\n {\n case 0 => {println(res); println(\"-1 -1\")}\n case 1 => {\n println(res - 1)\n if(idxS > 0)\n {\n for(i <- 0 until n)\n {\n if((s(i) != t(i)) && (t(i) == s(idxS)) && (idxS != i))\n idxT = i\n }\n idxS += 1\n idxT += 1\n println(idxS + \" \" + idxT)\n }\n else {\n for(i <- 0 until n)\n {\n if((s(i) != t(i)) && (s(i) == t(idxT)) && (idxT != i))\n idxS = i\n }\n idxS += 1\n idxT += 1\n println(idxT + \" \" + idxS)\n }\n }\n case 2 =>\n {\n val chr1 = s(idxS)\n val chr2 = t(idxT)\n for(i <- 0 until n)\n {\n if((s(i) == chr2) && (t(i) == chr1) && (idxT != i))\n idxS = i\n }\n\n println(res - 2)\n idxS += 1\n idxT += 1\n println(idxS + \" \" + idxT)\n }\n }\n\n\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util\nimport java.util._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val s = next.toCharArray\n val t = next.toCharArray\n var curr = 0\n val a = new Array[Array[Int]](27)\n for (i <- 0 until 27) {\n a(i) = new Array[Int](27)\n }\n for (i <- 0 until n) {\n if (s(i) != t(i)) {\n curr += 1\n a(s(i) - 'a')(t(i) - 'a') = i + 1\n }\n }\n for (i <- 0 until a.length) {\n for (j <- i + 1 until a(i).length) {\n if (a(i)(j) >= 1 && a(j)(i) >= 1) {\n out.println(curr - 2)\n out.println(a(i)(j) + \" \" + a(j)(i))\n return 1\n }\n }\n }\n\n for (i <- 0 until a.length) {\n var a1 = 0\n var a2 = 0\n for (j <- 0 until a(i).length) {\n a1 = Math.max(a1, a(i)(j))\n a2 = Math.max(a2, a(j)(i))\n }\n if (a1 >= 1 && a2 >= 1) {\n out.println(curr - 1)\n out.println(a1 + \" \" + a2)\n return 1\n }\n }\n out.println(curr)\n out.println(\"-1 -1\")\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "/**\n * Created by ronaflx on 15-4-3.\n */\nobject Codeforces {\n def evalRecord(x: Int): Int = { if (x > 0) 1 else 0 }\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val a = io.StdIn.readLine()\n val b = io.StdIn.readLine()\n var record = Array.ofDim[Int](26, 26)\n var hamming: Int = 0\n for (i <- 0 to n - 1) {\n if (a.charAt(i) != b.charAt(i)) {\n record(a.charAt(i).toInt - 97)(b.charAt(i).toInt - 97) = i + 1\n hamming += 1\n }\n\n }\n var delta: Int = 0\n var posa = -1\n var posb = -1\n for (i <- 0 to 25; j <- 0 to 25) {\n if (i != j) {\n if (delta < evalRecord(record(i)(j)) + evalRecord(record(j)(i)) && record(i)(j) != 0 && record(j)(i) != 0) {\n delta = 2\n posa = record(i)(j)\n posb = record(j)(i)\n }\n for (k <- 0 to 25) {\n if (delta < evalRecord(record(i)(j)) && j != k && record(j)(k) != 0) {\n delta = 1\n posa = record(i)(j)\n posb = record(j)(k)\n }\n }\n }\n }\n println(hamming - delta)\n println(posa + \" \" + posb)\n }\n}\n"}], "negative_code": [{"source_code": "\nobject B524 extends App{\n\n import scala.collection.mutable.Queue\n\n val n = readInt\n val s = readLine\n val t = readLine\n var q = List[(Char, Char, Int)]()\n var setS = Set[Char]()\n var setT = Set[Char]()\n var idxS = -1\n var idxT = -1\n var flag = 0\n var res = 0\n for(i <- 0 until n)\n {\n if(s(i) != t(i))\n {\n if(flag == 0) {\n if (setS contains t(i)) {\n idxT = i\n flag += 1\n }\n if (setT contains s(i)) {\n idxS = i\n flag += 1\n }\n }\n else\n {\n if((setS contains t(i)) && (setT contains s(i)) && flag != 2)\n {idxS = i; idxT = i; flag = 2}\n }\n\n setS += s(i)\n setT += t(i)\n res += 1\n }\n }\n\n flag\n match\n {\n case 0 => {println(res); println(\"-1 -1\")}\n case 1 => {\n println(res - 1)\n if(idxS > 0)\n {\n for(i <- 0 until n)\n {\n if((s(i) != t(i)) && (t(i) == s(idxS)) && idxS != i)\n idxT = i\n }\n idxS += 1\n idxT += 1\n println(idxS + \" \" + idxT)\n }\n else {\n for(i <- 0 until n)\n {\n if((s(i) != t(i)) && (s(i) == t(idxT)) && idxT != i)\n idxS = i\n }\n idxS += 1\n idxT += 1\n println(idxT + \" \" + idxS)\n }\n }\n case 2 =>\n {\n val chr1 = s(idxS)\n val chr2 = t(idxT)\n for(i <- 0 until n)\n {\n if((s(i) == chr2) && (t(i) == chr1) && idxT != i)\n idxS = i\n }\n println(res - 2)\n idxS += 1\n idxT += 1\n println(idxS + \" \" + idxT)\n }\n }\n\n\n}"}, {"source_code": "object B524 extends App{\n\n import scala.collection.mutable.Queue\n\n val n = readInt\n val s = readLine\n val t = readLine\n var q = List[(Char, Char, Int)]()\n var setS = Set[Char]()\n var setT = Set[Char]()\n var idxS = -1\n var idxT = -1\n var flag = 0\n var res = 0\n for(i <- 0 until n)\n {\n if(s(i) != t(i))\n {\n if(flag == 0) {\n if (setS contains t(i)) {\n idxT = i\n flag += 1\n }\n if (setT contains s(i)) {\n idxS = i\n flag += 1\n }\n }\n else\n {\n if((setS contains t(i)) && (setT contains s(i)) && (flag != 2))\n {idxS = i; idxT = i; flag = 2}\n }\n\n setS += s(i)\n setT += t(i)\n res += 1\n }\n }\n\n flag\n match\n {\n case 0 => {println(res); println(\"-1 -1\")}\n case 1 => {\n println(res - 1)\n if(idxS > 0)\n {\n for(i <- 0 until n)\n {\n if((s(i) != t(i)) && (t(i) == s(idxS)) && (idxS != i))\n idxT = i\n }\n idxS += 1\n idxT += 1\n println(idxS + \" \" + idxT)\n }\n else {\n for(i <- 0 until n)\n {\n if((s(i) != t(i)) && (s(i) == t(idxT)) && (idxT != i))\n idxS = i\n }\n idxS += 1\n idxT += 1\n println(idxT + \" \" + idxS)\n }\n }\n case 2 =>\n {\n val chr1 = s(idxS)\n val chr2 = t(idxT)\n for(i <- 0 until n)\n {\n if((s(i) == chr2) && (t(i) == chr1) && (idxT != i))\n idxS = i\n }\n println(res - 2)\n idxS += 1\n idxT += 1\n println(idxS + \" \" + idxT)\nif(idxS == idxT)\nprint(\"FUCK\")\n }\n }\n\n\n}"}, {"source_code": "\nobject B524 extends App{\n\n import scala.collection.mutable.Queue\n\n val n = readInt\n val s = readLine\n val t = readLine\n var q = List[(Char, Char, Int)]()\n var setS = Set[Char]()\n var setT = Set[Char]()\n var idxS = -1\n var idxT = -1\n var flag = 0\n var res = 0\n for(i <- 0 until n)\n {\n if(s(i) != t(i))\n {\n if(flag == 0) {\n if (setS contains t(i)) {\n idxT = i\n flag += 1\n }\n if (setT contains s(i)) {\n idxS = i\n flag += 1\n }\n }\n else\n {\n if((setS contains t(i)) && (setT contains s(i)) && flag != 2)\n {idxS = i; idxT = i; flag = 2}\n }\n\n setS += s(i)\n setT += t(i)\n res += 1\n }\n }\n\n flag\n match\n {\n case 0 => {println(res); println(\"-1 -1\")}\n case 1 => {\n println(res - 1)\n if(idxS > 0)\n {\n for(i <- 0 until n)\n {\n if((s(i) != t(i)) && (t(i) == s(idxS)) && idxS != i)\n idxT = i\n }\n idxS += 1\n idxT += 1\n println(idxS + \" \" + idxT)\n }\n else {\n for(i <- 0 until n)\n {\n if((s(i) != t(i)) && (s(i) == t(idxT)) && idxT != i)\n idxS = i\n }\n idxS += 1\n idxT += 1\n println(idxT + \" \" + idxS)\n }\n }\n case 2 =>\n {\n val chr1 = s(idxS)\n val chr2 = t(idxT)\n for(i <- 0 until n)\n {\n if(s(i) == chr2 && t(i) == chr1)\n idxS = i\n }\n println(res - 2)\n idxS += 1\n idxT += 1\n println(idxS + \" \" + idxT)\n }\n }\n\n\n}"}, {"source_code": "\nobject B524 extends App{\n\n import scala.collection.mutable.Queue\n\n val n = readInt\n val s = readLine\n val t = readLine\n var q = List[(Char, Char, Int)]()\n var setS = Set[Char]()\n var setT = Set[Char]()\n var idxS = -1\n var idxT = -1\n var flag = 0\n var res = 0\n for(i <- 0 until n)\n {\n if(s(i) != t(i))\n {\n if(flag == 0) {\n if (setS contains t(i)) {\n idxT = i\n flag += 1\n }\n if (setT contains s(i)) {\n idxS = i\n flag += 1\n }\n }\n else\n {\n if((setS contains t(i)) && (setT contains s(i)) && flag != 2)\n {idxS = i; idxT = i; flag = 2}\n }\n\n setS += s(i)\n setT += t(i)\n res += 1\n }\n }\n\n flag\n match\n {\n case 0 => {println(res); println(\"-1 -1\")}\n case 1 => {\n println(res - 1)\n if(idxS > 0)\n {\n for(i <- 0 until n)\n {\n if((s(i) != t(i)) && (t(i) == s(idxS)))\n idxT = i\n }\n idxS += 1\n idxT += 1\n println(idxS + \" \" + idxT)\n }\n else {\n for(i <- 0 until n)\n {\n if((s(i) != t(i)) && (s(i) == t(idxT)))\n idxS = i\n }\n idxS += 1\n idxT += 1\n println(idxT + \" \" + idxS)\n }\n }\n case 2 =>\n {\n val chr1 = s(idxS)\n val chr2 = t(idxT)\n for(i <- 0 until n)\n {\n if(s(i) == chr2 && t(i) == chr1)\n idxS = i\n }\n println(res - 2)\n idxS += 1\n idxT += 1\n println(idxS + \" \" + idxT)\n }\n }\n\n\n}"}, {"source_code": "object B524 extends App{\n\n import scala.collection.mutable.Queue\n\n val n = readInt\n val s = readLine\n val t = readLine\n var q = List[(Char, Char, Int)]()\n var setS = Set[Char]()\n var setT = Set[Char]()\n var idxS = -1\n var idxT = -1\n var flag = 0\n var res = 0\n for(i <- 0 until n)\n {\n if(s(i) != t(i))\n {\n if(flag == 0) {\n if (setS contains t(i)) {\n idxT = i\n flag += 1\n }\n if (setT contains s(i)) {\n idxS = i\n flag += 1\n }\n }\n else\n {\n if((setS contains t(i)) && (setT contains s(i)) && (flag != 2))\n {idxS = i; idxT = i; flag = 2}\n }\n\n setS += s(i)\n setT += t(i)\n res += 1\n }\n }\n\n flag\n match\n {\n case 0 => {println(res); println(\"-1 -1\")}\n case 1 => {\n println(res - 1)\n if(idxS >= 0)\n {\n for(i <- 0 until n)\n {\n if((s(i) != t(i)) && (t(i) == s(idxS)) && (idxS != i))\n idxT = i\n }\n idxS += 1\n idxT += 1\n println(idxS + \" \" + idxT)\n }\n else {\n for(i <- 0 until n)\n {\n if((s(i) != t(i)) && (s(i) == t(idxT)) && (idxT != i))\n idxS = i\n }\n idxS += 1\n idxT += 1\n println(idxT + \" \" + idxS)\n }\n }\n case 2 =>\n {\n val chr1 = s(idxS)\n val chr2 = t(idxT)\n for(i <- 0 until n)\n {\n if((s(i) == chr2) && (t(i) == chr1) && (idxT != i))\n idxS = i\n }\n println(res - 2)\n idxS += 1\n idxT += 1\n println(idxS + \" \" + idxT)\n }\n }\n\n\n}"}, {"source_code": "\nobject B524 extends App{\n\n import scala.collection.mutable.Queue\n\n val n = readInt\n val s = readLine\n val t = readLine\n var q = List[(Char, Char, Int)]()\n var setS = Set[Char]()\n var setT = Set[Char]()\n var idxS = -1\n var idxT = -1\n var flag = 0\n var res = 0\n for(i <- 0 until n)\n {\n if(s(i) != t(i))\n {\n if(flag == 0) {\n if (setS contains t(i)) {\n idxT = i\n flag += 1\n }\n else\n if (setT contains s(i)) {\n idxS = i\n flag += 1\n }\n }\n else\n {\n if((setS contains t(i)) && (setT contains s(i)) && flag != 2)\n {idxS = i; idxT = i; flag = 2}\n }\n\n setS += s(i)\n setT += t(i)\n res += 1\n }\n }\n\n flag\n match\n {\n case 0 => {println(res); println(\"-1 -1\")}\n case 1 => {\n println(res - 1)\n if(idxS > 0)\n {\n for(i <- 0 until n)\n {\n if((s(i) != t(i)) && (t(i) == s(idxS)))\n idxT = i\n }\n idxS += 1\n idxT += 1\n println(idxS + \" \" + idxT)\n }\n else {\n for(i <- 0 until n)\n {\n if((s(i) != t(i)) && (s(i) == t(idxT)))\n idxS = i\n }\n idxS += 1\n idxT += 1\n println(idxT + \" \" + idxS)\n }\n }\n case 2 =>\n {\n val chr1 = s(idxS)\n val chr2 = t(idxT)\n for(i <- 0 until n)\n {\n if(s(i) == chr2 && t(i) == chr1)\n idxS = i\n }\n println(res - 2)\n idxS += 1\n idxT += 1\n println(idxS + \" \" + idxT)\n }\n }\n\n\n}"}, {"source_code": "\nobject B524 extends App{\n\n import scala.collection.mutable.Queue\n\n val n = readInt\n val s = readLine\n val t = readLine\n var q = List[(Char, Char, Int)]()\n var setS = Set[Char]()\n var setT = Set[Char]()\n var idxS = -1\n var idxT = -1\n var flag = 0\n var res = 0\n for(i <- 0 until n)\n {\n if(s(i) != t(i))\n {\n if(flag == 0) {\n if (setS contains t(i)) {\n idxT = i\n flag += 1\n }\n if (setT contains s(i)) {\n idxS = i\n flag += 1\n }\n }\n else\n {\n if((setS contains t(i)) && (setT contains s(i)) && (flag != 2))\n {idxS = i; idxT = i; flag = 2}\n }\n\n setS += s(i)\n setT += t(i)\n res += 1\n }\n }\n\n flag\n match\n {\n case 0 => {println(res); println(\"-1 -1\")}\n case 1 => {\n println(res - 1)\n if(idxS > 0)\n {\n for(i <- 0 until n)\n {\n if((s(i) != t(i)) && (t(i) == s(idxS)) && (idxS != i))\n idxT = i\n }\n idxS += 1\n idxT += 1\n println(idxS + \" \" + idxT)\n }\n else {\n for(i <- 0 until n)\n {\n if((s(i) != t(i)) && (s(i) == t(idxT)) && (idxT != i))\n idxS = i\n }\n idxS += 1\n idxT += 1\n println(idxT + \" \" + idxS)\n }\n }\n case 2 =>\n {\n val chr1 = s(idxS)\n val chr2 = t(idxT)\n for(i <- 0 until n)\n {\n if((s(i) == chr2) && (t(i) == chr1) && (idxT != i))\n idxS = i\n }\n println(res - 2)\n idxS += 1\n idxT += 1\n println(idxS + \" \" + idxT)\n }\n }\n\n\n}"}, {"source_code": "/**\n * Created by ronaflx on 15-4-3.\n */\nobject Codeforces {\n def evalRecord(x: Int): Int = { if (x > 0) 1 else 0 }\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val a = io.StdIn.readLine()\n val b = io.StdIn.readLine()\n var record = Array.ofDim[Int](26, 26)\n for (i <- 0 to n - 1) {\n if (a.charAt(i) != b.charAt(i)) {\n record(a.charAt(i).toInt - 97)(b.charAt(i).toInt - 97) = i + 1\n }\n }\n var hamming: Int = 0\n var delta: Int = 0\n var posa = -1\n var posb = -1\n record.foreach(hamming += _.count(_ > 0))\n for (i <- 0 to 25; j <- 0 to 25) {\n if (i != j) {\n if (delta < evalRecord(record(i)(j)) + evalRecord(record(j)(i)) && record(i)(j) != 0 && record(j)(i) != 0) {\n delta = 2\n posa = record(i)(j)\n posb = record(j)(i)\n }\n for (k <- 0 to 25) {\n if (delta < evalRecord(record(i)(j)) && j != k && record(j)(k) != 0) {\n delta = 1\n posa = record(i)(j)\n posb = record(j)(k)\n }\n }\n }\n }\n println(hamming - delta)\n println(posa + \" \" + posb)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util\nimport java.util._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val s = next.toCharArray\n val t = next.toCharArray\n var curr = 0\n val a = new Array[Array[Int]](27)\n for (i <- 0 until 27) {\n a(i) = new Array[Int](27)\n }\n for (i <- 0 until n) {\n if (s(i) != t(i)) {\n curr += 1\n a(s(i) - 'a')(t(i) - 'a') = i\n }\n }\n for (i <- 0 until a.length) {\n for (j <- i + 1 until a(i).length) {\n if (a(i)(j) >= 1 && a(j)(i) >= 1) {\n out.println(curr - 2)\n out.println((i + 1) + \" \" + (j + 1))\n return 1\n }\n }\n }\n\n for (i <- 0 until a.length) {\n var a1 = 0\n var a2 = 0\n for (j <- 0 until a(i).length) {\n a1 = Math.max(a1, a(i)(j))\n a2 = Math.max(a2, a(j)(i))\n }\n if (a1 >= 1 && a2 >= 1) {\n out.println(curr - 1)\n out.println((a1 + 1) + \" \" + (a2 + 1))\n return 1\n }\n }\n out.println(curr)\n out.println(\"-1 -1\")\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util\nimport java.util._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val s = next.toCharArray\n val t = next.toCharArray\n var curr = 0\n val t1 = new util.HashMap[Character, ArrayList[Int]]()\n val pos = new util.ArrayList[Int]()\n for (i <- 0 until n) {\n if (s(i) != t(i)) {\n pos.add(i)\n curr += 1\n if (!t1.containsKey(t(i))) {\n val list = new util.ArrayList[Int]()\n list.add(i)\n t1.put(t(i), list)\n } else {\n t1.get(t(i)).add(i)\n }\n }\n }\n var i1 = -1\n var i2 = -1\n var min = curr\n for (i <- 0 until pos.size()) {\n val s1: Char = s(pos.get(i))\n if (null != t1.get(s1)) {\n val ind = t1.get(s1)\n for (j <- 0 until ind.size()) {\n if (s(ind.get(j)) == t(i)) {\n if (curr - 2 < min) {\n min = curr - 2\n i1 = i\n i2 = ind.get(j)\n out.println(min)\n out.println((i1 + 1) + \" \" + (i2 + 1))\n return 1\n }\n } else {\n if (curr - 1 < min) {\n min = curr - 1\n i1 = i\n i2 = ind.get(j)\n }\n }\n }\n }\n }\n if (min == curr) {\n out.println(curr)\n out.println(\"-1 -1\")\n } else {\n out.println(min)\n out.println((i1 + 1) + \" \" + (i2 + 1))\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util\nimport java.util._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val s = next.toCharArray\n val t = next.toCharArray\n var curr = 0\n val a = new Array[Array[Int]](27)\n for (i <- 0 until 27) {\n a(i) = new Array[Int](27)\n }\n for (i <- 0 until n) {\n if (s(i) != t(i)) {\n curr += 1\n a(s(i) - 'a')(t(i) - 'a') = i + 1\n }\n }\n for (i <- 0 until a.length) {\n for (j <- i + 1 until a(i).length) {\n if (a(i)(j) >= 1 && a(j)(i) >= 1) {\n out.println(curr - 2)\n out.println(i + \" \" + j)\n return 1\n }\n }\n }\n\n for (i <- 0 until a.length) {\n var a1 = 0\n var a2 = 0\n for (j <- 0 until a(i).length) {\n a1 = Math.max(a1, a(i)(j))\n a2 = Math.max(a2, a(j)(i))\n }\n if (a1 >= 1 && a2 >= 1) {\n out.println(curr - 1)\n out.println(a1 + \" \" + a2)\n return 1\n }\n }\n out.println(curr)\n out.println(\"-1 -1\")\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util\nimport java.util._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val s = next.toCharArray\n val t = next.toCharArray\n var curr = 0\n val t1 = new util.HashMap[Character, ArrayList[Int]]()\n val pos = new util.ArrayList[Int]()\n for (i <- 0 until n) {\n if (s(i) != t(i)) {\n pos.add(i)\n curr += 1\n if (!t1.containsKey(t(i))) {\n val list = new util.ArrayList[Int]()\n list.add(i)\n t1.put(t(i), list)\n } else {\n t1.get(t(i)).add(i)\n }\n }\n }\n var i1 = -1\n var i2 = -1\n var min = curr\n for (i <- 0 until pos.size()) {\n val s1: Char = s(pos.get(i))\n if (null != t1.get(s1)) {\n val ind = t1.get(s1)\n for (j <- 0 until ind.size()) {\n if (s(ind.get(j)) == t(i)) {\n if (curr - 2 < min) {\n min = curr - 2\n i1 = pos.get(i)\n i2 = ind.get(j)\n out.println(min)\n out.println((i1 + 1) + \" \" + (i2 + 1))\n return 1\n }\n } else {\n if (curr - 1 < min) {\n min = curr - 1\n i1 = pos.get(i)\n i2 = ind.get(j)\n }\n }\n }\n }\n }\n if (min == curr) {\n out.println(curr)\n out.println(\"-1 -1\")\n } else {\n out.println(min)\n out.println((i1 + 1) + \" \" + (i2 + 1))\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "src_uid": "2fa543c8b8f9dc500c36cf719800a6b0"} {"source_code": "/**\n * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools\n */\nimport scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n // Write your solution here\n val t = readInt\n\n for (_ <- 0 until t) {\n val splitLine = readLine.split(\" \").map(_.toLong)\n var a = splitLine(0)\n var b = splitLine(1)\n var x = splitLine(2)\n var y = splitLine(3)\n val n = splitLine(4)\n\n var ans = 1000000000000000000L\n\n for (_ <- 0 until 2) {\n val da = math.min(n, a - x)\n val db = math.min(n - da, b- y)\n ans = math.min(ans, (a - da) * (b - db))\n\n val tmpab = b\n b = a\n a = tmpab\n\n val tmpxy = y\n y = x\n x = tmpxy\n }\n\n println(ans)\n }\n }\n}", "positive_code": [{"source_code": "//package codeforces.contests._1409\n\nobject MinimumProduct {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n\n val Array(a, b, x, y, n) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val (f, s) = {\n val aD = (a - n) max x\n val bD = (b - n) max y\n\n if (aD <= bD) (aD, (b - (n - (a - aD))) max y)\n else ((a - (n - (b - bD))) max x, bD)\n }\n\n println(f.toLong * s.toLong)\n }\n }\n}\n"}, {"source_code": "/**\n * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools\n */\nimport scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n // Write your solution here\n /*\n int t;\n cin >> t;\n while (t--) {\n int a, b, x, y, n;\n cin >> a >> b >> x >> y >> n;\n long long ans = 1e18;\n for (int i = 0; i < 2; ++i) {\n int da = min(n, a - x);\n int db = min(n - da, b - y);\n ans = min(ans, (a - da) * 1ll * (b - db));\n swap(a, b);\n swap(x, y);\n }\n cout << ans << endl;\n }\n\n return 0;\n */\n\n def swap(x: Long, y: Long) = {\n\n }\n val t = readInt\n\n for (_ <- 0 until t) {\n val splitLine = readLine.split(\" \").map(_.toLong)\n var a = splitLine(0)\n var b = splitLine(1)\n var x = splitLine(2)\n var y = splitLine(3)\n val n = splitLine(4)\n\n var ans = 1000000000000000000L\n\n for (_ <- 0 until 2) {\n val da = math.min(n, a - x)\n val db = math.min(n - da, b- y)\n ans = math.min(ans, (a - da) * (b - db))\n\n val tmpab = b\n b = a\n a = tmpab\n\n val tmpxy = y\n y = x\n x = tmpxy\n }\n\n println(ans)\n }\n }\n}"}, {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine.toInt\n for (_ <- 0 until t) {\n val arr = StdIn.readLine.split(\" \").map(_.toLong)\n val (a,b,x,y,n) = (arr(0), arr(1), arr(2), arr(3), arr(4))\n\n def cal(a: Long, b: Long, x: Long, y: Long, n: Long) = {\n val sub = math.min(a - x, n)\n val sub2 = math.min(b-y, n - sub)\n (a-sub) * (b-sub2)\n }\n\n println(cal(a,b,x,y,n) min cal(b,a,y,x,n))\n }\n }\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b, x, y, n) = readLine().split(\" \").map(_.toLong)\n\n val ans = {\n val c = (a - n) max x\n val d = (b - n + a - c) max y\n c * d\n } min {\n val c = (b - n) max y\n val d = (a - n + b - c) max x\n c * d\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\nobject B extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n 1.to(inputLines)\n .foreach(i => {\n val a = in.nextInt()\n val b = in.nextInt()\n val x = in.nextInt()\n val y = in.nextInt()\n val n = in.nextInt()\n\n val r1 = findR(a, b, x, y, n)\n val r2 = findR(b, a, y, x, n)\n val result = math.min(r1, r2)\n println(result)\n\n })\n }\n\n def findR(a: Int, b: Int, x: Int, y: Int, n: Int) = {\n val (a1, r) = if (a - x <= n) (a - (a - x), n - (a - x)) else (a - n, 0)\n val b1 = if (b - y <= r) b - (b - y) else b - r\n a1.toLong * b1.toLong\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextLineInt(n: Int): ArrayBuffer[Int] = {\n var data = ArrayBuffer[Int]()\n n.times({\n data += nextInt()\n })\n data\n }\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}, {"source_code": "object CodeforcesRound667b {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n var Array(a, b, x, y, n) = rll_long\n val res =\n Math.min(\n cmp(a, b, x, y, n),\n cmp(b, a, y, x, n),\n )\n writer.println(res)\n }\n\n def cmp(a_ : Long, b_ : Long, x_ : Long, y_ : Long, n_ : Long): Long = {\n var a = a_\n var b = b_\n var x = x_\n var y = y_\n var n = n_\n val diff1 = Math.min(a - x, n)\n a -= diff1\n n -= diff1\n val diff2 = Math.min(b - y, n)\n b -= diff2\n n -= diff2\n a * b\n }\n\n def sqr(a: Long): Long = a * a\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}"}], "negative_code": [{"source_code": "//package codeforces.contests._1409\n\nobject MinimumProduct {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n\n val Array(a, b, x, y, n) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val (f, s) = {\n if (n == 0) (a, b)\n else if (n == 1) ((a max b) - 1, a min b)\n else if (a == x) (a, (b - n) max y)\n else if (b == y) ((a - n) max x, b)\n else {\n val aD = (a - n) max x\n val bD = (b - n) max y\n\n if (aD <= bD) (aD, (b - (n - (a - aD))) max y)\n else ((a - (n - (b - bD))) max x, bD)\n }\n }\n\n println(f.toLong * s.toLong)\n }\n }\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(a, b, x, y, n) = readLine().split(\" \").map(_.toLong)\n\n val ans =\n if (a < b) {\n val c = (a - n) max x\n val d = (b - n + a - c) max y\n c * d\n } else {\n val c = (b - n) max y\n val d = (a - n + b - c) max x\n c * d\n }\n\n println(ans)\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\nobject B extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val a = in.nextInt()\n val b = in.nextInt()\n val x = in.nextInt()\n val y = in.nextInt()\n val n = in.nextInt()\n\n val r1 = findR(a, b, x, y, n)\n val r2 = findR(b, a, y, x, n)\n printf(\"%.0f\\n\", math.min(r1, r2))\n }\n }\n\n def findR(a: Int, b: Int, x: Int, y: Int, n: Int) = {\n val (a1, r) = if (a - x <= n) (a - (a - x), n - (a - x)) else (a - n, 0)\n val b1 = if (b - y <= r) b - (b - y) else b - r\n a1.toDouble * b1.toDouble\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextLineInt(n: Int): ArrayBuffer[Int] = {\n var data = ArrayBuffer[Int]()\n n.times({\n data += nextInt()\n })\n data\n }\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject B extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n 1.to(inputLines)\n .foreach(i => {\n val a = in.nextInt()\n val b = in.nextInt()\n val x = in.nextInt()\n val y = in.nextInt()\n val n = in.nextInt()\n\n if (i == 4918) {\n println(a, b, x, y, n)\n val r1 = findR(a, b, x, y, n)\n val r2 = findR(b, a, y, x, n)\n printf(\"%.0f\\n\", math.min(r1, r2))\n }\n\n })\n }\n\n def findR(a: Int, b: Int, x: Int, y: Int, n: Int) = {\n val (a1, r) = if (a - x <= n) (a - (a - x), n - (a - x)) else (a - n, 0)\n val b1 = if (b - y <= r) b - (b - y) else b - r\n a1.toDouble * b1.toDouble\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextLineInt(n: Int): ArrayBuffer[Int] = {\n var data = ArrayBuffer[Int]()\n n.times({\n data += nextInt()\n })\n data\n }\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ArrayBuffer\n\nobject B extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n import scala.io.Source\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n 1.to(inputLines)\n .foreach(i => {\n val a = in.nextInt()\n val b = in.nextInt()\n val x = in.nextInt()\n val y = in.nextInt()\n val n = in.nextInt()\n\n if (i == 4918) {\n println(a, b, x, y, n)\n val r1 = findR(a, b, x, y, n)\n val r2 = findR(b, a, y, x, n)\n printf(\"%.0f\\n\", math.min(r1, r2))\n } else if( i <= 7){\n\n val r1 = findR(a, b, x, y, n)\n val r2 = findR(b, a, y, x, n)\n printf(\"%.0f\\n\", math.min(r1, r2))\n }\n\n })\n }\n\n def findR(a: Int, b: Int, x: Int, y: Int, n: Int) = {\n val (a1, r) = if (a - x <= n) (a - (a - x), n - (a - x)) else (a - n, 0)\n val b1 = if (b - y <= r) b - (b - y) else b - r\n a1.toDouble * b1.toDouble\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n *\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextLineInt(n: Int): ArrayBuffer[Int] = {\n var data = ArrayBuffer[Int]()\n n.times({\n data += nextInt()\n })\n data\n }\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}], "src_uid": "04753f73af685b4e7339d30d6d47c161"} {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val n = lines.next().toInt\n val line = lines.next()\n if (n > 26)\n println(-1)\n else\n println(n - line.distinct.length)\n}\n\n", "positive_code": [{"source_code": "object Solution {\n\n\tdef main(arg: Array[String]) {\n\t\tval sc = new java.util.Scanner(System.in)\n\t\tval n = sc.nextInt\n\t\tval s = sc.next\n\t\tval charCounts = new Array[Int](26)\n\t\tfor (i <- 0 until s.length) {\n\t\t\tval idx = s.charAt(i) - 'a'\n\t\t\tcharCounts(idx) = charCounts(idx) + 1\n\t\t}\n\t\tval unused = charCounts.foldLeft(0)((a,b) => a + (if (b == 0) 1 else 0))\n\t\tval sum = charCounts.foldLeft(0)((a,b) => a + (if (b > 1) b-1 else 0))\n\t\tprintln(if (unused >= sum) sum else -1)\n\t}\n}"}, {"source_code": "object B672 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = read\n if(in.length > 26) {\n println(\"-1\")\n } else {\n val res = in.length - in.distinct.length\n println(res)\n }\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by whimsy on 16/7/17.\n */\n\n\n\nobject P672B extends App {\n val n = StdIn.readInt()\n\n val content = StdIn.readLine()\n\n var set = Set[Char]()\n\n\n val answer = if (n > 26) {\n -1\n } else {\n content.foreach(e =>\n set += e\n )\n\n content.size - set.size\n }\n\n println(answer)\n}"}], "negative_code": [], "src_uid": "d9e9c53b391eb44f469cc92fdcf3ea0a"} {"source_code": "/**\n * Created by ashione on 14-6-19.\n */\nobject CF441A {\n import java.util.Scanner\n val in = new Scanner(System.in)\n\n def main(arg:Array[String]):Unit = {\n\n val itemNum = in.nextInt\n val valeraPrice = in.nextInt\n val ans:List[Int] = (for(i <- 1 to itemNum if isDeal(valeraPrice)) yield i).toList\n println(ans.length)\n ans.foreach(x=>print(x+\" \"))\n }\n def isDeal(price:Int):Boolean = {\n val sellerNum = in.nextInt\n val sl: List[Int] = {\n for (i <- 1 to sellerNum) yield in.nextInt\n }.toList\n !sl.forall(x => x >= price)\n }\n}\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, v) = in.next().split(\" \").map(_.toInt)\n val r = Range(1, n + 1).map(i => (i, in.next().split(\" \").map(_.toInt).tail.min)).filter(_._2 < v).map(_._1)\n println(r.length)\n println(r.mkString(\" \"))\n}\n"}, {"source_code": "object a {\n \n def main (args: Array[String]){\n var Array(n,k) = readLine.split(\" \").map(_.toInt)\n var ans = 0\n var used = new Array[Int](n+1)\n for (i <- 0 until n){\n var x = readLine.split(\" \").map(_.toInt)\n var bl =false\n for (j <- 1 to x(0))\n if (x(j) next.toInt).min < v) builder += i\n }\n val res = builder.result\n println(res.length)\n println(res.mkString(\" \"))\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, v) = in.next().split(\" \").map(_.toInt)\n println(Range(0, n).map(_ => in.next().split(\" \").map(_.toInt).tail.min).count(_ > v))\n}\n"}], "src_uid": "7804152ee14264afef019c5ad33094f9"} {"source_code": "object Main {\ndef main(args: Array[String]) : Unit = {\n val n = readInt\n val feelings = List(\"hate\", \"love\")\n \n def loop(index: Int): String = {\n val feeling = feelings(index % 2)\n \n if(index == n-1) return s\"I $feeling it\"\n\n s\"I $feeling that \" + loop(index + 1)\n }\n\n println(loop(0))\n }\n}", "positive_code": [{"source_code": "object tanya extends App{\nvar a = readInt\nvar str = \"\"\nval hate = \"I hate\"\nval love = \"I love\"\n\nfor(i <- 0 to a){\n if(i == 1){\n str = str.concat(hate)\n }else if(i >= 2){\n str = str.concat(\" that \")\n if(i % 2 == 1){\n str = str.concat(hate)\n }else{\n str = str.concat(love)\n }\n }\n}\nstr = str.concat(\" it\")\nprintln(str)\n}"}, {"source_code": "object Solution extends App {\n val lines = io.Source.stdin.getLines()\n val n = lines.next().toInt\n println((1 to n).map(i => if (i % 2 == 0) \"I love \" else \"I hate \").mkString(\"\", \"that \", \"it\"))\n}\n"}, {"source_code": "object A705 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val str = Array(\"I hate\", \"I love\")\n println(\n (0 until n).foldLeft(\"\"){ (s, i) =>\n s + \" \" + str(i%2) + (if(i == n-1) \" it\" else \" that\")\n }.trim)\n }\n}"}, {"source_code": "import java.util._;\n\n\nobject Main extends App {\n\n def fun(n: Int, flip: Boolean, acc: String): String = {\n def addPhrase(): String = if (flip) \"I hate\" else \"I love\"\n\n if (n == 0) acc\n else if (n == 1) {\n fun(n - 1, !flip, acc ++ addPhrase() ++ \" it \")\n } else {\n fun(n - 1, !flip, acc ++ addPhrase() ++ \" that \")\n }\n }\n\n\n val sc = new Scanner(System.in);\n val n: Int = sc.nextInt()\n println(fun(n, flip = true, \"\"))\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _705A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val n = read[Int]\n val tokens = (1 to n) map {\n case i if i%2 == 1 => \"I hate\"\n case _ => \"I love\"\n }\n val ans = tokens.mkString(\"\", \" that \", \" it\")\n write(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Solution {\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val ans =\n (1 to n).foldLeft(\"\") {\n case (acc, `n`) if n % 2 == 1 => acc + \"I hate it\"\n case (acc, `n`) => acc + \"I love it\"\n case (acc, i) if i % 2 == 1 => acc + \"I hate that \"\n case (acc, i) => acc + \"I love that \"\n }\n print(ans)\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val n = readInt()\n val A = Array(\"I hate\", \"I love\")\n\n val B = (0 until n).map { i =>\n A(i % 2)\n }\n\n println(B.mkString(\" that \") + \" it\")\n\n}\n"}, {"source_code": "object Hulk705A // extends TSolver {\n extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n solve(System.in,System.out)\n def solve(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextInt()\n val s = (1 to n).map{i => s\"I ${if(i%2==1)\"hate\" else \"love\" }\"}.mkString(\" that \") + \" it\"\n out.println(s)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Codeforces705A extends App {\n var n = StdIn.readLine().toInt\n var love = false\n while (n > 0) {\n if (love) {\n print(\"I love \" + (if (n == 1) \"it\" else \"that \"))\n } else {\n print(\"I hate \" + (if (n == 1) \"it\" else \"that \"))\n }\n love = !love\n n -= 1\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main2 extends App {\n val feelingNumber = StdIn.readInt()\n val res = 0.until(feelingNumber)\n .map(index => s\"I ${if (index % 2 == 0) \"hate\" else \"love\"}\")\n .mkString(\" that \") + \" it\"\n println(res)\n}\n"}, {"source_code": "import java.util\n\nimport scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n\n val max = 1000000007;\n val n = readInt()\n\n\n var s = \"\"\n\n for(i <- 0 until n) {\n if(i % 2 == 0) {\n s+=\"I hate that \"\n } else {\n s+=\"I love that \"\n }\n }\n\n println(s.reverse.replaceFirst(\"taht\", \"ti\").reverse)\n\n }\n\n\n def readInt(): Int = StdIn.readInt()\n\n def readInts(): Array[Int] = StdIn.readLine().split(\" \").map(_.toInt)\n\n\n def readTuple(): (Int, Int) = {\n val line = readInts\n (line(0), line(1))\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject TaskA extends App {\n println((1 to readInt map(i => if (i % 2 == 0) \"I love\" else \"I hate\" ) mkString \" that \") + \" it\")\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Solution {\n\tvar n = readInt\n\n\tdef main(args:Array[String]):Unit = {\n\n\t\tfor(i <- 1 to n-1) {\n\t\t\tif(i%2 == 0) print(\"I love that \")\n\t\t\telse print(\"I hate that \")\n\t\t} \n\n\t\tif(n % 2 == 0) print(\"I love it\\n\")\n\t\telse print(\"I hate it\\n\")\n\t\n\t}\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) : Unit = {\n val n = readInt\n val feelings = List(\"hate\", \"love\")\n \n def loop(index: Int, res: String): String = {\n val feeling = feelings(index % 2)\n \n if(index == n-1) return res + s\"I $feeling it\"\n\n loop(index + 1, res + s\"I $feeling that \")\n }\n\n println(loop(0, \"\"))\n }\n}"}], "negative_code": [{"source_code": "object A705 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val str = Array(\"I hate that\", \"I love that\")\n println((0 until n).foldLeft(\"\"){(s, i) => s + \" \" + str(i%2)}.trim)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Codeforces705A extends App {\n var n = StdIn.readLine().toInt\n while (n > 0) {\n if (n % 2 == 0) {\n print(\"I love \" + (if (n == 1) \"it\" else \"that \"))\n } else {\n print(\"I hate \" + (if (n == 1) \"it\" else \"that \"))\n }\n n -= 1\n }\n}\n"}], "src_uid": "7f2441cfb32d105607e63020bed0e145"} {"source_code": "object CF {\n def isVowel(c: Char): Boolean =\n \tList('a','e','i','o','u', 'y') exists (a => a == Character.toLowerCase(c))\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n var n = sc.nextInt()\n var s = sc.next()\n var i = 0\n while (i < n) {\n var j = i + 1\n if(isVowel(s(i))) {\n var cnt = 1\n while (j < n && s(j) == s(i)) {\n j = j + 1\n cnt = cnt + 1\n }\n if (s(i) == 'e' || s(i) == 'o') {\n if (cnt == 2) {\n print(s(i))\n }\n } \n }\n print(s(i))\n i = j\n }\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n var n = readInt\n var s = readLine\n var i = 0\n if ( n == 0 ) {\n sys.exit(0) \n }\n print(s.charAt(0))\n for (i <- 1 to n-1) {\n if ( ! ( ( s.charAt(i) == s.charAt(i-1) && ( s.charAt(i) == 'a' || s.charAt(i) == 'i' || s.charAt(i) == 'u' || s.charAt(i) == 'y' ) ) ||\n ( s.charAt(i) == s.charAt(i-1) && ( ( i > 1 && s.charAt(i) == s.charAt(i-2) ) || ( i != n-1 && s.charAt(i+1) == s.charAt(i) ) ) && ( s.charAt(i) == 'o' || s.charAt(i) == 'e' ) ) ) )\n print(s.charAt(i))\n }\n println(\"\")\n }\n}"}, {"source_code": "object Main extends App {\n val n = readInt\n val s = readLine\n var pc = ' '\n var count = 0\n for (c <- s) {\n if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y') {\n if (c == pc) {\n count += 1\n } else {\n if (count > 0) {\n if (count == 2 && ((pc == 'o' || pc == 'e'))) {\n print(pc)\n print(pc)\n } else {\n print(pc)\n }\n }\n pc = c\n count = 1\n }\n } else {\n if (count > 0) {\n if (count == 2 && ((pc == 'o' || pc == 'e'))) {\n print(pc)\n print(pc)\n } else {\n print(pc)\n }\n }\n \n count = 0\n print(c)\n }\n pc = c\n }\n if (count > 0) {\n if (count == 2 && ((pc == 'o' || pc == 'e'))) {\n print(pc)\n print(pc)\n } else {\n print(pc)\n }\n }\n println()\n}"}], "negative_code": [{"source_code": "object CF {\n def isVowel(c: Char): Boolean =\n \tList('a','e','i','o','u') exists (a => a == Character.toLowerCase(c))\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n var n = sc.nextInt()\n var s = sc.next()\n var i = 0\n while (i < n) {\n var j = i + 1\n if(isVowel(s(i))) {\n while (j < n && s(j) == s(i)) {\n j = j + 1\n }\n }\n print(s(i))\n i = j\n }\n }\n}"}, {"source_code": "object CF {\n def isVowel(c: Char): Boolean =\n \tList('a','e','i','o','u') exists (a => a == Character.toLowerCase(c))\n def main(args: Array[String]) = {\n val sc = new java.util.Scanner(System.in)\n var n = sc.nextInt()\n var s = sc.next()\n var i = 0\n while (i < n) {\n var j = i + 1\n if(isVowel(s(i))) {\n var cnt = 1\n while (j < n && s(j) == s(i)) {\n j = j + 1\n cnt = cnt + 1\n }\n if (s(i) == 'e' || s(i) == 'o') {\n if (cnt == 2) {\n print(s(i))\n }\n } \n }\n print(s(i))\n i = j\n }\n }\n}"}], "src_uid": "8ff1b4cf9875f1301e603b47626d06b4"} {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val Array(n, k) = readInts()\n k match {\n case 1 =>\n println(\"YES\")\n 1.to(n).foreach(v => println(v))\n case _ if (n % 2 == 0) =>\n println(\"YES\")\n val a = 1.to(k * n / 2).map(_ * 2 - 1)\n val b = 1.to(k * n / 2).map(_ * 2)\n a.grouped(k).map(_.mkString(\" \")).foreach(println(_))\n b.grouped(k).map(_.mkString(\" \")).foreach(println(_))\n case _ => println(\"NO\")\n }\n }\n\n 3 * 4\n //1 3 5 7 9 11\n //2 4 6 8 10 12\n\n //4 * 3\n //1 3 5\n //7 9 11\n //2 4 6\n //8 10 12\n\n //1 3 5 7 9 11\n //2 4 6 8 10 12\n //13 15 17 19 21 23\n //14 16 18 20 22 24\n //25 27 29 31 33 35\n //26 28 30 32 34 36\n\n //1 3 5\n //7 9 11\n //2 4 6\n //8 10 12\n\n\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n", "positive_code": [{"source_code": "import scala.io.Source\r\n \r\nobject Contest extends App {\r\n def logic(n: Int, k: Int): Unit = {\r\n val max = n * k\r\n if (k == 1) {\r\n println(\"YES\")\r\n println(Range.inclusive(1, max).mkString(\"\\n\"))\r\n } else if (max % 2 == 0 && n != 1 && (max / 2) % k == 0) {\r\n println(\"YES\")\r\n Range(1, max, 2).grouped(k).map(_.mkString(\" \"))\r\n .foreach(println)\r\n Range.inclusive(2, max, 2).grouped(k).map(_.mkString(\" \"))\r\n .foreach(println)\r\n } else println(\"NO\")\r\n }\r\n \r\n val input = Source.fromInputStream(System.in).getLines()\r\n val t = input.next().toInt\r\n val nk = new Array[(Int, Int)](t)\r\n for (i <- 0 until t) {\r\n val Array(n, k) = input.next().split(\" \")\r\n nk(i) = (n.toInt, k.toInt)\r\n }\r\n \r\n for (i <- 0 until t) {\r\n val (n, k) = nk(i)\r\n logic(n, k)\r\n }\r\n}"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(var a: Int, var b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return (a).compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mapp = mutable.Map[pair, Int]()\n\n val t = readInt()\n\n for (tt <- 1 to t) {\n val n = readInt()\n val k = readInt()\n if (n % 2 == 1 && k > 1) {\n writer.println(\"NO\")\n } else {\n writer.println(\"YES\")\n var pl = 1\n var pr = 2\n for (i <- 1 to n) {\n for (j <- 1 to k) {\n if (i % 2 == 1) {\n writer.print(pl + \" \")\n pl += 2\n } else {\n writer.print(pr + \" \")\n pr += 2\n }\n }\n writer.println()\n }\n }\n\n\n def check(kk: Long, fi: Long): Boolean = {\n return false\n }\n def bs(st:Long, en:Long, fi:Long): Long = {\n if (en - st <= 1L) {\n if (check(st, fi))\n return st\n else\n return en\n }\n val mid = (st + en) / 2L\n if (check(mid, fi))\n return bs(st, mid, fi)\n else\n return bs(mid, en, fi)\n }\n }\n writer.flush()\n}"}], "negative_code": [{"source_code": "import scala.io.Source\r\n \r\nobject Contest extends App {\r\n def logic(n: Int, k: Int): Unit = {\r\n val max = n * k\r\n if (k == 1) {\r\n println(\"YES\")\r\n println(Range.inclusive(1, max).mkString(\"\\n\"))\r\n } else if (max % 2 == 0 && n != 1) {\r\n println(\"YES\")\r\n Range(1, max, 2).grouped(k).map(_.mkString(\" \"))\r\n .foreach(println)\r\n Range.inclusive(2, max, 2).grouped(k).map(_.mkString(\" \"))\r\n .foreach(println)\r\n } else println(\"NO\")\r\n }\r\n \r\n val input = Source.fromInputStream(System.in).getLines()\r\n val t = input.next().toInt\r\n val nk = new Array[(Int, Int)](t)\r\n for (i <- 0 until t) {\r\n val Array(n, k) = input.next().split(\" \")\r\n nk(i) = (n.toInt, k.toInt)\r\n }\r\n \r\n for (i <- 0 until t) {\r\n val (n, k) = nk(i)\r\n logic(n, k)\r\n }\r\n}"}, {"source_code": "import scala.io.Source\r\n\r\nobject Contest extends App {\r\n def logic(n: Int, k: Int): Unit = {\r\n val max = n * k\r\n if (k == 1) {\r\n println(\"YES\")\r\n println(Range.inclusive(1, max).mkString(\"\\n\"))\r\n } else if (max % 2 == 0) {\r\n println(\"YES\")\r\n Range(1, max, 2).grouped(k).map(_.mkString(\" \"))\r\n .foreach(println)\r\n Range.inclusive(2, max, 2).grouped(k).map(_.mkString(\" \"))\r\n .foreach(println)\r\n } else println(\"NO\")\r\n }\r\n\r\n val input = Source.fromInputStream(System.in).getLines()\r\n val t = input.next().toInt\r\n val nk = new Array[(Int, Int)](t)\r\n for (i <- 0 until t) {\r\n val Array(n, k) = input.next().split(\" \")\r\n nk(i) = (n.toInt, k.toInt)\r\n }\r\n\r\n for (i <- 0 until t) {\r\n val (n, k) = nk(i)\r\n logic(n, k)\r\n }\r\n}"}, {"source_code": "import scala.io.Source\r\n\r\nobject Contest extends App {\r\n def logic(n: Int, k: Int): Unit = {\r\n val max = n * k\r\n if (k == 1) {\r\n println(\"YES\")\r\n println(Range.inclusive(1, max).mkString(\"\\n\"))\r\n } else if (max % 2 == 0) {\r\n println(\"YES\")\r\n Range(1, max, 2).sliding(k).map(_.mkString(\" \"))\r\n .foreach(println)\r\n val b = Range.inclusive(2, max, 2).sliding(k).map(_.mkString(\" \"))\r\n .foreach(println)\r\n } else println(\"NO\")\r\n }\r\n \r\n val input = Source.fromInputStream(System.in).getLines()\r\n val t = input.next().toInt\r\n val nk = new Array[(Int, Int)](t)\r\n for (i <- 0 until t) {\r\n val Array(n, k) = input.next().split(\" \")\r\n nk(i) = (n.toInt, k.toInt)\r\n }\r\n\r\n for (i <- 0 until t) {\r\n val (n, k) = nk(i)\r\n logic(n, k)\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\r\nimport scala.io.Source\r\n\r\nobject Contest extends App {\r\n def logic(n: Int, k: Int): Unit = {\r\n if (k == 1) {\r\n println(\"YES\")\r\n val max = n * k\r\n println(Range.inclusive(1, max).mkString(\"\\n\"))\r\n } else if (k == 2) {\r\n println(\"YES\")\r\n val max = n * k\r\n val res = new ArrayBuffer[String](n)\r\n for (i <- 1 until max by 4) {\r\n res.append(s\"$i ${i + 2}\")\r\n }\r\n for (i <- 2 until max by 4) {\r\n res.append(s\"$i ${i + 2}\")\r\n }\r\n println(res.mkString(\"\\n\"))\r\n } else println(\"NO\")\r\n }\r\n\r\n val input = Source.fromInputStream(System.in).getLines()\r\n val t = input.next().toInt\r\n val nk = new Array[(Int, Int)](t)\r\n for (i <- 0 until t) {\r\n val Array(n, k) = input.next().split(\" \")\r\n nk(i) = (n.toInt, k.toInt)\r\n }\r\n\r\n for (i <- 0 until t) {\r\n val (n, k) = nk(i)\r\n logic(n, k)\r\n }\r\n}\r\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val Array(n, k) = readInts()\n k match {\n case 1 =>\n println(\"YES\")\n 1.to(n).foreach(v => println(v))\n case 2 if n % 2 == 0 =>\n println(\"YES\")\n 1.to(n).foreach(v => println(s\"$v ${v + n}\"))\n case _ if (n == 2) =>\n println(\"YES\")\n println(1.to(k).map(_ * 2 - 1).mkString(\" \"))\n println(1.to(k).map(_ * 2).mkString(\" \"))\n case _ => println(\"NO\")\n }\n }\n\n //1 3 5\n //2 4 6\n\n //1 3 5 7 9 11\n //2 4 6 8 10 12\n\n\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val Array(n, k) = readInts()\n k match {\n case 1 =>\n println(\"YES\")\n 1.to(n).foreach(v => println(v))\n case 2 if n % 2 == 0 =>\n println(\"YES\")\n 1.to(n).foreach(v => println(s\"$v ${v + n}\"))\n case _ => println(\"NO\")\n }\n }\n\n\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(var a: Int, var b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return (a).compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mapp = mutable.Map[pair, Int]()\n\n val t = readInt()\n\n for (tt <- 1 to t) {\n val n = readInt()\n val k = readInt()\n if (n * k % 2 == 1 && k > 1) {\n writer.println(\"NO\")\n } else {\n writer.println(\"YES\")\n var pl = 1\n var pr = 2\n for (i <- 1 to n) {\n for (j <- 1 to k) {\n if (i % 2 == 1) {\n writer.print(pl + \" \")\n pl += 2\n } else {\n writer.print(pr + \" \")\n pr += 2\n }\n }\n writer.println()\n }\n }\n\n\n def check(kk: Long, fi: Long): Boolean = {\n return false\n }\n def bs(st:Long, en:Long, fi:Long): Long = {\n if (en - st <= 1L) {\n if (check(st, fi))\n return st\n else\n return en\n }\n val mid = (st + en) / 2L\n if (check(mid, fi))\n return bs(st, mid, fi)\n else\n return bs(mid, en, fi)\n }\n }\n writer.flush()\n}"}], "src_uid": "9fb84ddc2e04fd637812cd72110b7f36"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, W = ni()\n val A = na(N)\n var upper = W\n var lower = 0\n REP(N) { i =>\n upper = min(W, upper + A(i))\n lower = max(0, lower + A(i))\n }\n out.println(max(0, upper - lower + 1))\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Long]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn\nobject CF978E extends App {\n val Array(n, w) = StdIn.readLine.split(' ').map(_.toInt)\n val as = StdIn.readLine.split(' ').map(_.toInt)\n val passengers = as.scanLeft(0){_+_}\n // x >= -passengers.min\n // x <= w - passengers.max\n val possibilities = (w - passengers.max + passengers.min + 1) max 0\n println(possibilities)\n}"}], "negative_code": [], "src_uid": "8cf5d08a319672d9b767d3523eca4df6"} {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject CodeForces extends App {\n\n StdIn.readLine()\n val numbers = StdIn.readLine().split(\" \").map(_.toInt)\n\n val (odd,even) = numbers.partition(_%2==0)\n if (odd.length == 1){\n println(numbers.indexOf(odd.head) + 1)\n }else {\n println(numbers.indexOf(even.head) + 1)\n }\n\n\n\n\n}\n", "positive_code": [{"source_code": "object P025A {\n def main(args: Array[String]) = {\n val n = readInt\n val a = readLine.split(' ').map(x => x.toInt).map(x => x % 2)\n val parity = if (a.reduceLeft(_ + _) > 1) 0 else 1\n println(a.indexOf((a.filter(x => x % 2 == parity))(0)) + 1)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readLine()\n val list = readLine().split(\" \").map(_.toInt).toList\n val (elist, olist) = list.partition(x => x % 2 == 0)\n if (elist.length <= 1) println(list.indexOf(elist.head) +1) else println(list.indexOf(olist.head) +1)\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Main extends App {\n readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val (even, odd) = a.zipWithIndex.partition { case (e, _) => e % 2 == 0 }\n val ans = if (even.length == 1) even.head._2 else odd.head._2\n println(ans + 1)\n}"}, {"source_code": "object CF0025A extends App {\n\n val n = readInt()\n val ar = readLine().split(\" \").map(_.toInt)\n\n var pos = 0\n\n if(ar.filter(_%2 ==0 ).size == n -1) {\n val value = ar.filter(_%2 == 1).head\n (1 to ar.size).foreach(n => {\n if(ar(n-1) == value) {\n pos = n\n }\n })\n } else {\n val value = ar.filter(_%2 == 0).head\n (1 to ar.size).foreach(n => {\n if(ar(n-1) == value) {\n pos = n\n }\n })\n }\n\n println(pos)\n\n}\n"}, {"source_code": "object CF025A_IQTest extends App {\n\n override def main(args: Array[String]): Unit = {\n val in = new java.util.Scanner(System.in)\n val out = new java.io.PrintWriter(System.out)\n\n def solution(): Unit = {\n val n: Int = in.nextInt()\n var sum: Int = 0\n for (_ <- 0 until 3) {\n sum = (sum << 1) | (in.nextInt() % 2)\n }\n\n val ind: Int = sum match {\n case sum if (sum == 3 || sum == 4) => 1\n case sum if (sum == 2 || sum == 5) => 2\n case sum if (sum == 1 || sum == 6) => 3\n case _ => {\n val item = sum match {\n case 0 => 1\n case _ => 0\n }\n\n var t = 0\n for (i <- 4 to n) {\n if (item == (in.nextInt() % 2)) {\n t = i\n }\n }\n\n t\n }\n }\n\n out.println(ind)\n }\n\n try {\n solution()\n\n } catch {\n case e: Exception => out.println(e.toString)\n\n } finally {\n out.flush()\n out.close()\n }\n }\n}\n"}, {"source_code": "object CF025A_IQTest extends App {\n\n class FastReader() {\n val br = new java.io.BufferedReader(\n new java.io.InputStreamReader(System.in))\n var st: java.util.StringTokenizer = null\n\n def next: String = {\n if (st == null || !st.hasMoreElements) {\n st = new java.util.StringTokenizer(br.readLine)\n }\n\n st.nextToken\n }\n\n def nextInt: Int = next.toInt\n def nextLong: Long = next.toLong\n def nextDouble: Double = next.toDouble\n def nextLine: String = br.readLine\n }\n\n override def main(args: Array[String]): Unit = {\n val in = new FastReader()\n val out = new java.io.PrintWriter(System.out)\n\n def solution(): Unit = {\n val n = in.nextInt\n var sum = 0\n for (_ <- 0 until 3) {\n sum = (sum << 1) | (in.nextInt % 2)\n }\n\n val ind = sum match {\n case sum if (sum == 3 || sum == 4) => 1\n case sum if (sum == 2 || sum == 5) => 2\n case sum if (sum == 1 || sum == 6) => 3\n case _ => {\n val item = sum match {\n case 0 => 1\n case _ => 0\n }\n\n var t = 0\n for (i <- 4 to n) {\n if (item == (in.nextInt % 2)) {\n t = i\n }\n }\n\n t\n }\n }\n\n out.println(ind)\n }\n\n try {\n solution()\n\n } catch {\n case e: Exception => out.println(e.toString)\n\n } finally {\n out.flush()\n out.close()\n }\n }\n}\n"}, {"source_code": "import collection.mutable._\n\nobject P25A extends App {\n\n readLine\n val evens, odds = new java.util.LinkedList[(Int,Int)]()\n\n for (e <- readLine.split(\" \").map(_.toInt).zipWithIndex)\n (if(e._1 % 2 == 0) evens else odds).add(e)\n \n \n print(Array(evens,odds).minBy(_.size).get(0)._2+1)\n\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _25A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt);\n val odd = a.filter(i => i % 2 == 1)\n val even = a.filter(i => i % 2 == 0)\n val ans = if (odd.size == 1) a.indexOf(odd.head) + 1 else a.indexOf(even.head) + 1\n println(ans)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n if (data.count(_ % 2 == 1) == 1)\n println(data.indexOf(data.find(_ % 2 == 1).get) + 1)\n else\n println(data.indexOf(data.find(_ % 2 == 0).get) + 1)\n}\n"}, {"source_code": "object A25 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n).zipWithIndex\n val odd = input.filter(_._1 % 2 == 1)\n val even = input.filter(_._1 % 2 == 0)\n if(odd.length == 1) {\n println(odd.head._2 + 1)\n } else {\n println(even.head._2 + 1)\n }\n }\n}"}, {"source_code": "object IQ {\n def main(args: Array[String]) {\n val n = io.StdIn.readLine.toInt\n val arr = io.StdIn.readLine.split(\" \").map(_.toInt).zipWithIndex\n val evens = arr.filter(_._1 % 2 == 0)\n val odds = arr.filter(_._1 % 2 != 0)\n if (evens.length == 1) println(evens(0)._2 + 1)\n else println(odds(0)._2 + 1)\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P025A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val V = List.fill(N)(sc.nextInt)\n\n val answer = if (V.count(_ % 2 == 1) == 1) (V takeWhile (_ % 2 == 0)).size + 1\n else (V takeWhile (_ % 2 == 1)).size + 1\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "\n\nobject IQtest {\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in);\n\t\tval n = scanner.nextInt();\n\t\tvar previousArity = scanner.nextInt() % 2;\n\t\tvar currentArity = scanner.nextInt() % 2;\n\t\tvar index = 2;\n\t\twhile (index <= n && previousArity == currentArity) {\n\t\t\tpreviousArity = currentArity;\n\t\t\tcurrentArity = scanner.nextInt() % 2;\n\t\t\tindex += 1\n\t\t}\n\t\tif (index == 2) {\n\t\t\tval nextArity = scanner.nextInt() % 2\n\t\t\t\t\tif (nextArity == previousArity)\n\t\t\t\t\t\tprintln(2);\n\t\t\t\t\telse\n\t\t\t\t\t\tprintln(1);\n\t\t}\n\t\telse {\n\t\t\tprintln(index)\n\t\t}\n\t}\n}"}, {"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var n = readInt;\n var evenCount = 0;\n var oddCount = 0;\n var lastEven = 0;\n var lastOdd = 0;\n var arr = readLine.split(\" \").map(_.toInt);\n for (i <- 0 until arr.length) {\n if (arr(i) % 2 == 0) {\n lastEven = i;\n evenCount += 1;\n } else {\n lastOdd = i;\n oddCount += 1;\n }\n }\n if (evenCount > oddCount) {\n println(lastOdd + 1);\n } else {\n println(lastEven + 1);\n }\n }\n\n}"}, {"source_code": "import annotation.tailrec\nimport java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readInt = reader.readLine().toInt\n\n val n = readInt\n val a = readInts\n val foo = a.groupBy(_ % 2).mapValues(_.length)\n def ans = (a zip (1 to n)).filter(x => foo(x._1 % 2) == 1).map(_._2)\n\n def main(args: Array[String]) {\n println(ans.mkString)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val map = a.zipWithIndex.groupBy(_._1 % 2)\n if (map(1).size == 1) println(map(1)(0)._2 + 1)\n else println(map(0)(0)._2 + 1)\n }\n}"}, {"source_code": "import scala.io._\n\nobject main {\n\n def solution(n: Int) = {\n val input = StdIn.readLine().split(' ').map(_.toInt)\n val groups = input.groupBy(_ % 2 == 0)\n\n val (evns, odds) =\n (groups(true), groups(false))\n\n val number = if (evns.length > odds.length)\n odds.last else evns.last\n\n var i = 0\n var ans = 0\n\n while (i < input.length) {\n if (input(i) == number)\n ans = i\n i += 1\n }\n\n ans + 1\n }\n\n def run() = {\n val n = StdIn.readInt()\n val ans = solution(n)\n\n println(ans)\n }\n\n def main(args: Array[String]): Unit = {\n run()\n }\n\n}\n"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject IQTest {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def readLongs() : Array[Long] = \n readLine.split(' ').map(_.toLong)\n \n def readTuple() : (Int,Int) = {\n val line = readInts\n (line(0),line(1))\n }\n def readTupleLong() : (Long,Long) = {\n val line = readLongs\n (line(0),line(1))\n }\n \n def readTriple() : (Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2))\n }\n def readQuad() : (Int,Int,Int,Int) = {\n val line = readInts\n (line(0),line(1),line(2),line(3))\n }\n \n \n def main(args: Array[String]) {\n val n = readInt\n val as = readInts\n if (as.count { _ % 2 == 0 } > 1) {\n println(as.indexWhere(_ % 2 == 1) + 1)\n } else {\n println(as.indexWhere(_ % 2 == 0) + 1)\n }\n \n }\n \n}"}, {"source_code": "import java.io._\n\nobject Solution extends App {\n val n = readInt\n \n val a = readLine.split(\" \").map(_.toInt)\n \n if(a.count(_ % 2 == 0) == 1) {\n println(a.indexWhere(_ % 2 == 0) + 1)\n } else {\n println(a.indexWhere(_ % 2 != 0) + 1)\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readLine()\n val list = readLine().split(\" \").map(_.toInt).toList\n val (elist, olist) = list.partition(x => x % 2 == 0)\n if (elist.length <= 1) println(list.indexOf(elist.head)) else println(list.indexOf(olist.head))\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readLine()\n val list = readLine().split(\" \").map(_.toInt).toList\n val (elist, olist) = list.partition(x => x % 2 == 0)\n if (elist.length <= 1) println(elist.head) else println(olist.head)\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n if (data.count(_ % 2 == 1) == 1)\n println(data.find(_ % 2 == 1).get)\n else\n println(data.find(_ % 2 == 0).get)\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P025A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n val V = List.fill(N)(sc.nextInt)\n\n val v0 = V takeWhile (_ % 2 == 0)\n val v1 = V dropWhile (_ % 2 == 0) takeWhile(_ % 2 == 1)\n val answer = if (v0.size > 0) v0.size + 1\n else v1.size + 1\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val map = a.groupBy(_ % 2)\n if (map(1).size == 1) println(map(1)(0))\n else println(map(0)(0))\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val map = a.groupBy(_ % 2)\n \n println(a)\n if (map(1).size == 1) println(map(1)(0))\n else println(map(0)(0))\n }\n}"}, {"source_code": "object Main extends App {\n\n val n = Console.readInt()\n Console.println(solution(n))\n\n def solution(n: Int) = {\n var odd = 0\n var even = 0\n\n var d = 0\n var fOdd = -1\n var fEvn = -1\n\n val input: Array[String] =\n Console.readLine().split(' ')\n\n input\n .map(x => x.toInt)\n .foreach(d => {\n if (d % 2 == 0) {\n even += 1\n if (fEvn == -1) fEvn = d\n } else {\n odd += 1\n if (fOdd == -1) fOdd = d\n }\n })\n\n val ans = if (odd > even) fOdd else fEvn\n ans + 1\n }\n\n}\n"}], "src_uid": "dd84c2c3c429501208649ffaf5d91cee"} {"source_code": "object CF_E61_B {\n// date: 05/03/2019\n\n type In = (Int, Seq[Int], Int, Seq[Int])\n type Out = Seq[Long]\n \n def solve(in: In): Out = {\n val (n, as, m, qs) = in\n\n val ss = as.sorted\n val total = ss.foldLeft(0L)(_+_)\n def mincost(q: Int): Long = total - ss(n - q)\n for {\n q <- qs\n } yield mincost(q)\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, {i.nextLine; i.intSeq}, {i.int}, {i.nextLine; i.intSeq})\n def formatOut(out: Out): String = out.mkString(\"\\n\")\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n // `a` MUST be > 0. Incorrect otherwise.\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n sort(A)\n val M = ni()\n val S = sumL(A)\n REP(M) { _ =>\n val q = ni()\n val ans = S - A(N - q)\n out.println(ans)\n }\n }\n\n\n def sort(a: Array[Int]): Array[Int] = {\n val n = a.length\n REP(n) { i =>\n val j = scala.util.Random.nextInt(n - i) + i\n val tmp = a(i)\n a(i) = a(j)\n a(j) = tmp\n }\n Sorting.stableSort(a)\n a\n }\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n def debug(num: Long): Unit = {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n"}], "negative_code": [], "src_uid": "c1608f6f71cac56690e31aa130c1990e"} {"source_code": "import java.util.Scanner\n\nobject E_3_627 extends App {\n var scanner = new Scanner(System.in)\n\n val sleepCount = scanner.nextInt()\n val hoursInDay = scanner.nextInt()\n val goodHourStart = scanner.nextInt()\n val goodHourEnd = scanner.nextInt()\n\n val untilSleeps = Array.ofDim[Int](sleepCount)\n untilSleeps.indices.foreach { index =>\n untilSleeps(index) = scanner.nextInt()\n }\n\n def asDayHour(hour: Int): Int = {\n Math.floorMod(hour, hoursInDay)\n }\n\n def isGoodHour(hour: Int): Boolean = {\n (hour >= goodHourStart) && (hour <= goodHourEnd)\n }\n\n val goodDays = Array.ofDim[Int](sleepCount + 1, hoursInDay)\n goodDays(0)(0) = 0\n\n def calculateGoodDays(sleepIndex: Int, hourIndex: Int, wakeupGoodDays: Int): Int = {\n val newGoodDays = {\n if (isGoodHour(hourIndex)) {\n wakeupGoodDays + 1\n }\n else {\n wakeupGoodDays\n }\n }\n\n val maxGoodDays = Math.max(goodDays(sleepIndex)(hourIndex), newGoodDays)\n goodDays(sleepIndex)(hourIndex) = maxGoodDays\n\n maxGoodDays\n }\n\n var wakeupHours = Set(0)\n untilSleeps.zipWithIndex.foreach { case (untilSleep, sleepIndex) =>\n var newWakeupHours = Set.empty[Int]\n wakeupHours.foreach { wakeupHour =>\n val newWakeupHour = asDayHour(wakeupHour + untilSleep)\n\n // in time\n calculateGoodDays(sleepIndex + 1, newWakeupHour, goodDays(sleepIndex)(wakeupHour))\n\n // 1h before\n val improvedNewWakeupHour = asDayHour(newWakeupHour - 1)\n calculateGoodDays(sleepIndex + 1, improvedNewWakeupHour, goodDays(sleepIndex)(wakeupHour))\n\n newWakeupHours += newWakeupHour\n newWakeupHours += improvedNewWakeupHour\n }\n wakeupHours = newWakeupHours\n }\n\n val maxGoodDaysHour = wakeupHours.maxBy(goodDays(sleepCount))\n val maxGoodDays = goodDays(sleepCount)(maxGoodDaysHour)\n println(maxGoodDays)\n}", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C627E(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C627E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val h = ni()\n val l = ni()\n val r = ni()\n\n val a = na(n)\n\n val dp = Array.fill[Int](n+1,n+1)(Int.MinValue)\n dp(0)(0) = 0\n var sum = 0L\n REP(n) { i =>\n sum += a(i)\n REP(n+1) { j =>\n dp(i+1)(j) = scala.math.max(dp(i+1)(j), dp(i)(j) + inside((sum - j) % h, l , r))\n if(j < n) dp(i+1)(j+1) = scala.math.max(dp(i+1)(j+1), dp(i)(j) + inside((sum - j - 1) % h, l , r))\n }\n }\n out.println(dp(n).max)\n }\n\n def inside(v: Long, l: Int, r: Int): Int = {\n if(r >= v && v >= l) 1 else 0\n }\n}\n"}], "negative_code": [], "src_uid": "a301e0847a620fbb349fa914db98e752"} {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def test(): Boolean = {\n val S, T = ns()\n var i, j = 0\n val N = S.length\n val M = T.length\n\n debug(s\"N:$N M:$M\")\n\n debug(S)\n debug(T)\n\n while(i < N) {\n if (j == M || S(i) != T(j)) return false\n var ii = i\n var jj = j\n while (ii + 1 < N && S(i) == S(ii + 1)) {\n ii += 1\n }\n while (jj + 1 < M && T(j) == T(jj + 1)) {\n jj += 1\n }\n debug(s\"i:$i j:$j ii:$ii jj:$jj\")\n if (jj - j < ii - i) return false\n i = ii + 1\n j = jj + 1\n }\n\n j == M\n }\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n if (test()) out.println(\"YES\")\n else out.println(\"NO\")\n }\n }\n}", "positive_code": [{"source_code": "object _1185B extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val input = io.read[Seq[(String, String)]]\n val ans = input map { case (a, b) => check(a.toList, b.toList).toEnglish }\n io.writeLines(ans)\n }\n\n @tailrec\n def check[A](as: List[A], bs: List[A]): Boolean =\n (as, bs) match {\n case (Nil, Nil) => true\n case (a1 :: at, b1 :: bt) if a1 == b1 =>\n val (ad, an) = at.span(_ == a1)\n val (bd, bn) = bt.span(_ == b1)\n bd.length >= ad.length && check(an, bn)\n case _ => false\n }\n\n implicit class BooleanExtensions(x: Boolean) {\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\ncase class Entry(ch: Char, cnt: Int)\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def calc(s: String): ArrayBuffer[Entry] = {\n val n = s.length\n var i = 0\n val res = ArrayBuffer[Entry]()\n while(i < n) {\n var j = i\n while(j + 1 < n && s(i) == s(j + 1)) {\n j += 1\n }\n res += Entry(s(i), j - i + 1)\n i = j + 1\n }\n res\n }\n\n def test(): Boolean = {\n val S, T = ns()\n val E1 = calc(S)\n val E2 = calc(T)\n\n debug(E1.mkString(\" \"))\n debug(E2.mkString(\" \"))\n\n E1.length == E2.length && {\n var ok = true\n REP(E1.length) { i =>\n ok &&= E1(i).ch == E2(i).ch && E1(i).cnt <= E2(i).cnt\n }\n ok\n }\n }\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n if (test()) out.println(\"YES\")\n else out.println(\"NO\")\n }\n }\n}"}], "negative_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n def test(): Boolean = {\n val S, T = ns()\n var i, j = 0\n val N = S.length\n val M = T.length\n\n debug(S)\n debug(T)\n\n while(i < N) {\n if (j == M || S(i) != T(j)) return false\n var ii = i\n var jj = j\n if (ii + 1 < N && S(i) == S(ii + 1)) {\n ii += 1\n }\n if (jj + 1 < M && T(j) == T(jj + 1)) {\n jj += 1\n }\n debug(s\"i:$i j:$j ii:$ii jj:$jj\")\n if (jj - j < ii - i) return false\n i = ii + 1\n j = jj + 1\n }\n\n j == M\n }\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n if (test()) out.println(\"YES\")\n else out.println(\"NO\")\n }\n }\n}"}], "src_uid": "6709c8078cd29e69cf1be285071b2527"} {"source_code": "object Solution116A extends App {\n\n def solution() {\n val n = _int\n val result = 1.to(n).map(_ => (_int, _int)).foldLeft((0, 0))((memo, curr) => {\n val next = memo._1 - curr._1 + curr._2\n (next, scala.math.max(next, memo._2))\n })\n println(result._2)\n }\n\n //////////////////////////////////////////////////\n import java.util.Scanner\n val SC: Scanner = new Scanner(System.in)\n def _line: String = SC.nextLine\n def _int: Int = SC.nextInt\n def _long: Long = SC.nextLong\n def _string: String = SC.next\n solution()\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n val list = List.fill(n)(-sc.nextInt+sc.nextInt)\n println(list.scanLeft(0)(_ + _).max)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Test {\n def main(args1: Array[String]) {\n // val args = StdIn.readLine().split(\" \")\n // var (x: Long, y: Long) = (args(0).toLong, args(1).toLong)\n val count = StdIn.readInt\n var ret = 0L\n\n var in = 0L\n for (i <- 0 until count) {\n val args = StdIn.readLine().split(\" \")\n var (x: Long, y: Long) = (args(0).toLong, args(1).toLong)\n in -= x\n in += y\n in = Math.max(in, 0L)\n ret = Math.max(ret, in)\n }\n println(ret)\n }\n\n}"}, {"source_code": "import java.util.Scanner\nimport java.io._\n\nobject OneOneSixA {\n\tdef main(args : Array[String]) : Unit = {\n\t\tvar scn=new Scanner(new BufferedReader(new InputStreamReader(System.in)))\n\t\tvar n=scn.nextInt\n\t\tvar carry,max=0\n\t\tfor(i<-0 until n){\n\t\t\tvar ai=scn.nextInt\n\t\t\tvar bi=scn.nextInt\n\t\t\tcarry+=(bi-ai)\n\t\t\tif(carry>max)\n\t\t\t\tmax=carry\n\t\t}\n\t\tprintln(max)\n\t\tscn.close\n\t}\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Tram {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val passengers =\n for {\n _ <- 0 until n\n a :: b :: _ = readLine().split(\" \").map(_.toInt).toList\n } yield (a, b)\n var sum = 0\n val ans = passengers.map {\n case (x, y) =>\n sum = sum - x + y\n sum\n }\n println(ans.max)\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Tram {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val passengers =\n for {\n _ <- 0 until n\n a :: b :: _ = readLine().split(\" \").map(_.toInt).toList\n } yield (a, b)\n val ans = passengers.scanLeft(0)((sum, x) => sum - x._1 + x._2)\n println(ans.max)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by vladimir on 08.06.17.\n */\nobject A116 extends App {\n val n = StdIn.readInt()\n var max = -1\n var cur = 0\n for (i <- 1 to n) {\n val s = StdIn.readLine().trim\n val entry = s.split(' ') map (_.toInt)\n cur += entry(1) - entry(0)\n if (cur > max)\n max = cur\n }\n print(max)\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nobject Tram extends App{ \n val stops = scala.io.StdIn.readInt()\n var capacity = 0\n var capacities = ArrayBuffer[Int]()\n \n for (stop <- 1 until stops){\n val passengerFlow = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n capacity = capacity - passengerFlow(0)\n capacity = capacity + passengerFlow(1)\n capacities.prepend(capacity)\n }\n \n println(capacities.max)\n\n}\n"}, {"source_code": "object Main extends App {\n def collectStationsData(number: Int): List[(Int, Int)] = number match {\n case 0 => List()\n case _ => \n val Array(out, in) = readLine.split(\" \").map(_.toInt)\n (out, in) :: collectStationsData(number - 1)\n }\n\n def calculateMaxCapacity(stationData: List[(Int, Int)], \n prevStationCapacity: Int, maxCapacity: Int): Int = stationData match {\n case List() => maxCapacity\n case rest =>\n val stationCapacity = prevStationCapacity - rest.head._1 + rest.head._2\n if (stationCapacity > maxCapacity) calculateMaxCapacity(rest.tail, stationCapacity, stationCapacity)\n else calculateMaxCapacity(rest.tail, stationCapacity, maxCapacity) \n }\n\n val numberOfStations = readLine.toInt\n val stationsData = collectStationsData(numberOfStations)\n println(calculateMaxCapacity(stationsData, 0, 0))\n}"}, {"source_code": "object Main extends App {\n val n = readLine().toInt\n var max = 0\n var cur = 0\n\n for (_ <- 1 to n) {\n val str = readLine().split(\" \").map(_.toInt)\n\n cur = cur - str(0) + str(1)\n if (cur > max) max = cur\n }\n\n println(max)\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject Main extends App {\n val n = readLine().toInt\n\n var ab = ArrayBuffer[(Int, Int)]()\n\n for (_ <- 1 to n) {\n val str = readLine().split(\" \").map(_.toInt)\n ab += ((str.head, str.last))\n }\n\n var max = 0\n var cur = 0\n\n for (i <- 0 to n - 1) {\n cur = cur - ab(i)._1 + ab(i)._2\n if (cur > max) max = cur\n }\n\n println(max)\n}"}, {"source_code": "object CF0116A extends App {\n\n val n = readInt()\n\n var max = 0\n var people = 0\n\n (1 to n).foreach(number => {\n val Array(minus, plus) = readLine().split(\" \").map(_.toInt)\n\n people -= minus\n people += plus\n\n if(max <= people) {\n max = people\n }\n\n })\n\n println(max)\n}\n"}, {"source_code": "object task116A {\n def main(args:Array[String]) {\n var rv:Int=0;\n var c:Int=0;\n for (l <- io.Source.stdin.getLines.toList.drop(1)) {\n val Array(o,i)=l.split(\" \").map(_.toInt)\n c=c-o+i;\n if (c>rv) { rv=c; }\n }\n println(rv)\n }\n}"}, {"source_code": "object pratise {\n def main(args : Array[String]) {\n var res = 0\n var sum = 0\n var n = readInt\n for(i <- 1 to n) {\n val Array(x,y) = readLine().split(\" \").map(_.toInt)\n sum += y - x\n res = math.max(sum,res)\n }\n println(res)\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ListBuffer\n\nobject Tram extends App {\n val inPassengers = ListBuffer[Int]()\n val outPassengers = ListBuffer[Int]()\n\n def process(s: String): Unit = {\n val split: Array[String] = s.split(\" \")\n outPassengers.append(split(0).toInt)\n inPassengers.append(split(1).toInt)\n }\n\n val numStations = readInt()\n\n (1 to numStations).map(line => process(readLine()))\n\n var minCapacity = 0\n var currentCapacity = 0\n\n for (i <- 0 to inPassengers.size - 1) {\n currentCapacity = currentCapacity + (inPassengers(i) - outPassengers(i))\n if (currentCapacity > minCapacity) {\n minCapacity = currentCapacity\n }\n }\n println(minCapacity)\n}\n"}, {"source_code": "import scala.io.StdIn\n\n/**\n * @author traff\n */\n\n\nobject Main extends App {\n val n = StdIn.readLine().toInt\n\n var bus = 0\n var max = 0\n\n for (i <- 1 to n) {\n val Array(b, a) = StdIn.readLine().split(\" \").map(_.toInt)\n bus += a\n bus -= b\n\n max = Math.max(bus, max)\n }\n\n println(max)\n}\n"}, {"source_code": "object Solution extends App{\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n var count = 0\n var max = 0\n Range(0, n).foreach {_ => \n val Array(out, inn) = in.next().split(\" \").map(_.toInt)\n count = count - out + inn\n max = Math.max(count, max)\n }\n println(max)\n}\n"}, {"source_code": "object Main {\n\timport java.{util=>ju}\n\timport scala.math._\n\n\tdef main(args:Array[String]) =\n\t{\n\t\tval sc = new ju.Scanner(System.in)\n\t\tval i = sc.nextInt();\n\n\t\tval arr = (1 to i*2).map(_ => sc.nextInt())\n\t\tval a = arr.indices.filter(v => v % 2 == 0).map(w => arr.apply(w)).toArray\n\t\tval b = arr.indices.filter(v => v % 2 == 1).map(w => arr.apply(w)).toArray\n\n\t\tprintln(calc(a, b, 0, 0, 0))\n\n\t}\n\n\tdef calc(a:Array[Int], b:Array[Int], i:Int, sum:Int, max:Int):Int =\n\t{\n\t\tif(i >= a.length) return max\n\t\tcalc(a, b, i+1, sum - a(i) + b(i), math.max(sum,max))\n\t}\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val std = scala.io.StdIn\n\n val n = std.readInt()\n var result = 0\n var currentCapacity = 0\n for (i <- 0 until n) {\n val values = std.readLine().split(\" \").map(_.toInt)\n currentCapacity += - values(0) + values(1)\n result = currentCapacity.max(result)\n }\n println(result)\n }\n}"}, {"source_code": "object A116 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n var min = 0\n var curr = 0\n for(i <- 0 until n) {\n val Array(exit, in) = readInts(2)\n curr += (in-exit)\n min = math.max(min, curr)\n }\n println(min)\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P116A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n\n def solve: Int = {\n @tailrec\n def loop(acc: Int, p: Int, i: Int): Int = {\n if (i == N) acc\n else {\n val a, b = sc.nextInt\n val tmp = p - a + b\n loop(acc max tmp, tmp, i + 1)\n }\n }\n loop(0, 0, 0)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.math._\n\nobject R116_A extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n val nums = (0 until n) map ( _ => {\n val a = sc.nextInt()\n val b = sc.nextInt()\n b-a\n })\n \n println(answer(nums))\n \n def answer(nums:Seq[Int]):Int = {\n var m = 0\n var sum = 0\n nums.foreach(n => {\n m = max(m, (sum+n))\n sum += n\n })\n m\n }\n}"}, {"source_code": "object Tram {\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in)\n\t\tval n = scanner.nextInt\n\t\tvar maxCapacity = 0\n\t\tvar current = 0\n\t\tfor (_ <- 1 to n) {\n\t\t val b = scanner.nextInt\n\t\t val a = scanner.nextInt\n\t\t val diff = (a - b)\n\t\t current += diff\n\t\t maxCapacity = Math.max(maxCapacity, current)\n\t\t}\n\t\tprintln(maxCapacity)\n\t}\n}"}, {"source_code": "import java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n\n def dx = for(_ <- 1 to readInt) yield -readInts.reduce(_-_)\n def x = dx.foldLeft(List(0)) { case (list @ head :: _, a) =>\n head + a :: list\n }\n def ans = x.reduce(_ max _)\n\n def main(a: Array[String]) {\n println(ans)\n }\n}"}, {"source_code": "\nobject CF116A extends App {\n \n import java.util.Scanner\n\n val in = new Scanner(System.in)\n\n def nextInt = in.nextInt\n\n def solve {\n var curr = 0\n var max = 0\n for (n <- 1 to nextInt) {\n curr -= nextInt\n curr += nextInt\n if (curr > max) max = curr\n }\n println(max)\n }\n solve\n}"}, {"source_code": "object Codeforces116A extends App{\n\n def TrainCapacity(len:Int):Int={\n var ans:Int=0\n var temp:Int=0\n for (i <- 1 to len){\n val k:Array[Int]=scala.io.StdIn.readLine.split(\" \").map(_.toInt)\n temp-=k(0)\n temp+=k(1)\n if (temp>ans){\n ans=temp\n }\n }\n return ans\n }\n\n val s:Int=scala.io.StdIn.readInt\n println(TrainCapacity(s))\n\n}\n"}, {"source_code": "import java.io._\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n\n def dx = for(_ <- 1 to readInt) yield -readInts.reduce(_-_)\n def x = dx.foldLeft(List(0)) { case (list @ head :: _, a) =>\n head + a :: list\n }\n def ans = x.reduce(_ max _)\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "/**\n * Created by vol on 9/18/14.\n */\nobject A116 extends App{\n val n = readInt()\n\n def loop(n:Int, i:Int, max:Int, insideBus:Int):Int = {\n if (n == i) max\n else {\n val Array(out, in) = readLine().split(\" \").map(_.toInt)\n loop(n, i + 1, max.max(insideBus - out + in), insideBus -out + in)\n }\n }\n\n println(loop(n, 0 , 0 , 0))\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val arr = (1 to n).map { unused => \n val b = readLine().split(\" \").map(_.toInt)\n (b(0), b(1))\n }\n val t = arr.foldLeft((0, 0)) { (c, t) => \n val cur = c._1 - t._1 + t._2\n val max = if (cur < c._2) c._2\n else cur\n (cur, max) \n }\n println(t._2)\n }\n}"}, {"source_code": "// Codeforces 116A\n\nobject _116A extends App {\n val scanner = new java.util.Scanner(System.in)\n val n = scanner.nextInt()\n val increace = List.fill(n)(-scanner.nextInt()+scanner.nextInt())\n println(\n increace.\n foldLeft(List(0))((accm, i) => (i+accm.head) :: accm).max\n )\n}\n\n"}, {"source_code": "// Codeforces 116A\n\nobject _116A extends App {\n val scanner = new java.util.Scanner(System.in)\n val n = scanner.nextInt()\n val increace = List.fill(n)(-scanner.nextInt()+scanner.nextInt())\n println(increace.scanLeft(0)((accm, i) => accm + i).max)\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A_116 extends App {\n val n = readInt()\n var total = 0\n var capacity = 0\n 1 to n foreach { _ =>\n val Array(a, b) = readLine().split(\" \").map(_.toInt)\n total += b - a\n// println(total)\n capacity = Math.max(capacity, total)\n }\n\n println(capacity)\n}\n"}, {"source_code": "object examples{\n def main(args:Array[String]){\n val n = readLine().toInt\n var s = 0\n var m = 0\n for(_ <- 1 to n){\n val r = readLine().split(' ').map(_.toInt)\n s = s - r(0) + r(1)\n m = Math.max(m , s)\n }\n println(m) \n }\n\n}"}, {"source_code": "import scala.io.StdIn\nobject problem {\n def main(args: Array[String]) {\n val n = StdIn.readInt()\n var s = 0\n var max = 0\n for(i<- 1 until n){\n val A = StdIn.readLine.split(' ').map(_.toInt)\n s = s + A(1) - A(0)\n// println(s)\n max = math.max(max , s)\n }\n println(max)\n }\n}"}, {"source_code": "object JuanDavidRobles116A {\n def main(args: Array[String]): Unit = {\n\n import java.util.Scanner\n import java.io.{BufferedReader, InputStreamReader}\n\n val streamReader: InputStreamReader = new InputStreamReader(System.in)\n val scanner: Scanner = new Scanner(new BufferedReader(streamReader))\n\n val n: Int = Integer.parseInt(scanner.nextLine())\n var count: Int = 0\n var capability: Int = 0\n\n var exit: Int = 0\n var enter: Int = 0\n\n for (i <- 0 until n){\n exit = scanner.nextInt()\n enter = scanner.nextInt()\n\n count = count - exit + enter\n if (capability < count){\n capability = count\n }\n }\n\n println(capability)\n\n }\n}\n"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject Tram {\n def main(args: Array[String]) {\n val n = readInt\n val stops = for {\n i <- 1 to n\n val line = readLine.split(' ').map(_.toInt) \n } yield (line(0),line(1))\n println(stops.foldLeft((0,0)){ case ((cap, cur),(a,b)) => \n ( if (cap <= cur - a + b) cur - a + b else cap ,cur -a + b)}._1)\n \n }\n \n}"}, {"source_code": "object Tram extends App {\n val sc = new java.util.Scanner(System.in);\n val n = sc.nextInt;\n val list = List.fill(n)(-sc.nextInt+sc.nextInt)\n println(list.scanLeft(0)(_+_).max)\n}\n"}, {"source_code": "import scala.util.Sorting\nimport scala.io.StdIn\n\nobject App {\n\n\n def main(args: Array[String]) {\n\n val n = StdIn.readLine().toInt\n var ans = 0\n var cur = 0\n for(i<-0 to n-1) {\n val Array(a,b) = StdIn.readLine().split(\" \").map(_.toInt)\n cur = cur + (b - a)\n ans = math.max(cur, ans)\n }\n println(ans)\n }\n\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Tram_116A {\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n val maxInside = (0 until n)\n .map(_ => StdIn.readLine().split(\" \"))\n .map(l => (l(0).toInt, l(1).toInt))\n .foldLeft(0 :: Nil){ case (inside, (out, in)) => inside.head - out + in :: inside }\n .max\n println(maxInside)\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\nobject cf extends App\n{\n val scanner = new java.util.Scanner(System.in)\n val n = scanner.nextInt()\n val t = List.fill(n)(-scanner.nextInt()+scanner.nextInt())\n print (t.scanLeft(0)((sum,x)=>sum+x).max)\n}"}, {"source_code": "object Main {\n\n def main(args: Array[String]): Unit = {\n val n = readInt()\n var sum = 0\n var res = 0\n for(i <- 1 to n){\n val Array(a,b) = readLine().split(\" \").map(_.toInt)\n sum += b-a\n res = Math.max(res,sum)\n }\n println(res)\n }\n\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Solution {\n\n\tvar n = readInt\n\tvar stops = Array.fill[Array[Int]](n)(Array(0,0))\n\tfor(i <- 0 until n) {\n\t\tstops(i) = readLine.split(\" \").map(_.toInt)\n\t}\n\n\tdef main(args:Array[String]):Unit = {\n\t\tvar min = 0\n\t\tvar onBus = 0\n\t\tfor(i <- 0 until n) {\n\t\t\tvar Array(a,b) = stops(i)\n\n\t\t\tonBus -= a\n\t\t\tonBus += b\n\n\t\t\tif(onBus > min) min = onBus\n\t\t}\n\t\tprintln(min)\n\t}\n\n}\n"}, {"source_code": "object main extends App{\n val n = readInt\n var cnt = 0\n var max = 0\n for(i<-1 to n){\n val t = readLine.split(\" \").map(_.toInt)\n cnt+= t(1)-t(0)\n if(cnt > max) max = cnt\n }\n println(max)\n}"}, {"source_code": "object A00116 extends App {\n def parseInt(str: String, count: Int): Seq[Int] = {\n val scanner = new java.util.Scanner(str)\n val res = (1 to count) map (_ => scanner.nextInt())\n scanner.close()\n res\n }\n def scanInts(count: Int): Seq[Int] = parseInt(Console.readLine, count)\n\n def oneIntLine = {\n val Seq(count) = parseInt(Console.readLine(), 1);\n count\n }\n \n def readMatrix(row: Int, col: Int) = {\n (1 to row) map (x => scanInts(col))\n }\n\n val stops = oneIntLine\n val passengerChange = readMatrix(stops, 2)\n val additions = passengerChange map (x => x(1) - x(0))\n val reductions = additions.foldLeft(List(0)) { (acc, x) =>\n (acc.head + x) :: acc\n }\n println(reductions.max)\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject Main extends App {\n val n = readLine().toInt\n\n var ab = ArrayBuffer[(Int, Int)]()\n\n for (_ <- 1 to n) {\n val str = readLine().split(\" \").map(_.toInt)\n ab += ((str.head, str.last))\n }\n\n var max = 0\n\n for (i <- 0 to n - 1) {\n val temp = max - ab(i)._1 + ab(i)._2\n if (temp > max) max = temp\n }\n\n println(max)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P116A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n\n def solve: Int = {\n @tailrec\n def loop(acc: Int, i: Int): Int = {\n if (i == N) acc\n else {\n val a, b = sc.nextInt\n loop(acc max acc - a + b, i + 1)\n }\n }\n loop(0, 0)\n }\n\n out.println(solve)\n out.close\n}\n"}], "src_uid": "74b90fe9458b147568ac9bd09f219aab"} {"source_code": "\n\n/**\n * Created by ruslan on 3/29/17.\n */\nobject ProblemA extends App {\n import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.util.Random\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\nclass FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens()) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n}\n\n val startTime = System.currentTimeMillis();\n\n val n = in.nextInt();\n val a = new Array[Int](n)\n for (i <- 0 until n) a(i) = in.nextInt()\n\n var sums0 = new Array[(Long, Int)](n)\n var sums1 = new Array[(Long, Int)](n)\n\n sums0(0) = (0, 0)\n sums1(0) = (0, 0)\n\n for (i <- 1 until n) {\n val delta = Math.abs(a(i) - a(i - 1));\n sums0(i) = (sums0(i - 1)._1 + delta * (if (i % 2 == 0) -1 else 1), i)\n sums1(i) = (sums1(i - 1)._1 + delta * (if (i % 2 == 1) -1 else 1), i)\n }\n\n var res = Long.MinValue\n\n sums0 = sums0.sortWith(_._1 < _._1)\n sums1 = sums1.sortWith(_._1 < _._1)\n\n\n for(i <- n - 1 to 0 by -1) {\n val del1 = Math.abs(sums0(i)._1 - sums0(0)._1)\n val del2 = Math.abs(sums1(i)._1 - sums1(0)._1)\n if (del1 > res) res = del1\n if (del2 > res) res = del2\n }\n\n println(res)\n\n}\n", "positive_code": [{"source_code": "object _789C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n val array = read[Vector[Long]]\n val diffs = array\n .zip(array.tail)\n .zipWithIndex\n .map({case ((a, b), i) =>\n val d = (a - b).abs\n val isEven = i%2 == 0\n (if (isEven) d else -d, if (isEven) -d else d)\n })\n .unzip\n .toSeq\n\n val ans = diffs.map(maxSubArraySum)\n\n write(ans.max)\n }\n\n def maxSubArraySum(s: Seq[Long]): Long = s.scanLeft(0L){_ + _ max 0L}.max\n\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "object _789C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n val array = read[Vector[Long]]\n val diffs = array.view\n .zip(array.tail)\n .zipWithIndex\n .map({case ((a, b), i) =>\n val d = (a - b).abs\n val isEven = i%2 == 0\n (if (isEven) d else -d, if (isEven) -d else d)\n })\n .force\n .unzip\n .toSeq\n\n val ans = diffs.map(maxSubArraySum)\n write(ans.max)\n }\n\n def maxSubArraySum(s: Seq[Long]): Long = s.scanLeft(0L){_ + _ max 0L}.max\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "\n\nobject ProblemA extends App {\n \n import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n val startTime = System.currentTimeMillis();\n\n val n = in.nextInt();\n val a = new Array[Int](n)\n for (i <- 0 until n) a(i) = in.nextInt()\n\n var sums0 = new Array[(Long, Int)](n)\n var sums1 = new Array[(Long, Int)](n)\n\n sums0(0) = (0, 0)\n sums1(0) = (0, 0)\n\n for (i <- 1 until n) {\n val delta = Math.abs(a(i) - a(i - 1));\n sums0(i) = (sums0(i - 1)._1 + delta * (if (i % 2 == 0) -1 else 1), i)\n sums1(i) = (sums1(i - 1)._1 + delta * (if (i % 2 == 1) -1 else 1), i)\n }\n\n var res = Long.MinValue\n\n sums0 = sums0.sortWith(_._1 < _._1)\n sums1 = sums1.sortWith(_._1 < _._1)\n\n\n for(i <- n - 1 to 0 by -1) {\n val del1 = Math.abs(sums0(i)._1 - sums0(0)._1)\n val del2 = Math.abs(sums1(i)._1 - sums1(0)._1)\n if (del1 > res) res = del1\n if (del2 > res) res = del2\n }\n\n println(res)\n\n}\n\nimport java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}\nimport java.util.StringTokenizer\n\n\nclass FastScanner(val in: BufferedReader) {\n \n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens()) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n}"}], "negative_code": [{"source_code": "object _789C extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._\n\n override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}\n val array = read[Vector[Long]]\n val diffs = array\n .zip(array.tail)\n .map({case (a, b) => (a - b, b - a)})\n val (c1, c2) = diffs.unzip\n val ans = maxSubArraySum(c1) max maxSubArraySum(c2)\n write(ans)\n }\n\n def maxSubArraySum(s: Seq[Long]): Long = s.scanLeft(0L){_ + _ max 0L}.max\n\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "\n\n/**\n * Created by ruslan on 3/29/17.\n */\nobject ProblemA extends App {\n import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.util.Random\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\nclass FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens()) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n}\n\n val startTime = System.currentTimeMillis();\n\n val n = in.nextInt();\n val a = new Array[Int](n)\n for (i <- 0 until n) a(i) = in.nextInt()\n\n var sums0 = new Array[(Long, Int)](n)\n var sums1 = new Array[(Long, Int)](n)\n\n sums0(0) = (0, 0)\n sums1(0) = (0, 0)\n\n for (i <- 1 until n) {\n val delta = Math.abs(a(i) - a(i - 1));\n sums0(i) = (sums0(i - 1)._1 + delta * (if (i % 2 == 0) -1 else 1), i)\n sums1(i) = (sums1(i - 1)._1 + delta * (if (i % 2 == 1) -1 else 1), i)\n }\n\n var res = Long.MinValue\n\n sums0 = sums0.sortBy(_._1)\n sums1 = sums1.sortBy(_._1)\n\n/* println(sums0.mkString(\", \"))\n println(sums1.mkString(\", \"))*/\n\n\n def findMin(a: Array[(Long, Int)], index: Int): Long = {\n var res = 0;\n while (res < n && a(res)._2 >= index) res += 1;\n if (res < n) a(res)._1\n else Long.MaxValue\n }\n\n for(i <- n - 1 to 1 by -1) {\n val del1 = sums0(i)._1 - findMin(sums0, sums0(i)._2)\n val del2 = sums1(i)._1 - findMin(sums1, sums0(i)._2)\n if (del1 > res) res = del1\n if (del2 > res) res = del2\n }\n\n println(res)\n\n}\n"}, {"source_code": "\n\n/**\n * Created by ruslan on 3/29/17.\n */\nobject ProblemA extends App {\n import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.util.Random\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\nclass FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens()) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n}\n\n val startTime = System.currentTimeMillis();\n\n val n = in.nextInt();\n val a = new Array[Int](n)\n for (i <- 0 until n) a(i) = in.nextInt()\n\n val sums0 = new Array[(Long, Int)](n)\n val sums1 = new Array[(Long, Int)](n)\n\n sums0(0) = (0, 0)\n sums1(0) = (0, 0)\n\n for (i <- 1 until n) {\n val delta = Math.abs(a(i) - a(i - 1));\n sums0(i) = (sums0(i - 1)._1 + delta * (if (i % 2 == 0) -1 else 1), i)\n sums1(i) = (sums1(i - 1)._1 + delta * (if (i % 2 == 1) -1 else 1), i)\n }\n\n var res = Long.MinValue\n\n sums0.sortBy(_._1)\n sums1.sortBy(_._1)\n\n def findMin(a: Array[(Long, Int)], index: Int): Long = {\n var res = 0;\n while (res < n && a(res)._2 >= index) res += 1;\n if (res < n) a(res)._1\n else Long.MaxValue\n }\n\n for(i <- n - 1 to 0 by -1) {\n val del1 = sums0(i)._1 - findMin(sums0, sums0(i)._2)\n val del2 = sums1(i)._1 - findMin(sums1, sums0(i)._2)\n if (del1 > res) res = del1\n if (del2 > res) res = del2\n }\n\n println(res)\n\n}\n"}, {"source_code": "\n\n/**\n * Created by ruslan on 3/29/17.\n */\nobject ProblemA extends App {\n import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.util.Random\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\nclass FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens()) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n}\n\n val startTime = System.currentTimeMillis();\n\n val n = in.nextInt();\n val a = new Array[Int](n)\n for (i <- 0 until n) a(i) = in.nextInt()\n\n var sums0 = new Array[(Long, Int)](n)\n\n sums0(0) = (0, 0)\n\n for (i <- 1 until n) {\n val delta = Math.abs(a(i) - a(i - 1));\n sums0(i) = (sums0(i - 1)._1 + delta * (if (i % 2 == 0) -1 else 1), i)\n }\n\n var res = Long.MinValue\n\n sums0 = sums0.sortWith(_._1 < _._1)\n\n\n def findMin(a: Array[(Long, Int)], index: Int): Long = {\n var res = 0;\n while (res < n && a(res)._2 >= index) res += 1;\n if (res < n) a(res)._1\n else Long.MaxValue\n }\n\n for(i <- n - 1 to 0 by -1) {\n val del1 = sums0(i)._1 - findMin(sums0, sums0(i)._2)\n if (del1 > res) res = del1\n }\n\n println(res)\n\n}\n"}, {"source_code": "\n\n/**\n * Created by ruslan on 3/29/17.\n */\nobject ProblemA extends App {\n import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.util.Random\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\nclass FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens()) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n}\n\n val startTime = System.currentTimeMillis();\n\n val n = in.nextInt();\n val a = new Array[Int](n)\n for (i <- 0 until n) a(i) = in.nextInt()\n\n var sums0 = new Array[(Long, Int)](n)\n var sums1 = new Array[(Long, Int)](n)\n\n sums0(0) = (0, 0)\n sums1(0) = (0, 0)\n\n for (i <- 1 until n) {\n val delta = Math.abs(a(i) - a(i - 1));\n sums0(i) = (sums0(i - 1)._1 + delta * (if (i % 2 == 0) -1 else 1), i)\n sums1(i) = (sums1(i - 1)._1 + delta * (if (i % 2 == 1) -1 else 1), i)\n }\n\n var res = Long.MinValue\n\n sums0 = sums0.sortBy(_._1)\n sums1 = sums1.sortBy(_._1)\n\n/* println(sums0.mkString(\", \"))\n println(sums1.mkString(\", \"))*/\n\n\n def findMin(a: Array[(Long, Int)], index: Int): Long = {\n var res = 0;\n while (res < n && a(res)._2 >= index) res += 1;\n if (res < n) a(res)._1\n else Long.MaxValue\n }\n\n for(i <- n - 1 to 0 by -1) {\n val del1 = sums0(i)._1 - findMin(sums0, sums0(i)._2)\n val del2 = sums1(i)._1 - findMin(sums1, sums0(i)._2)\n if (del1 > res) res = del1\n if (del2 > res) res = del2\n }\n\n println(res)\n\n}\n"}], "src_uid": "7ff7f47cee182d2542754e412f6aab1a"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class BS(i: Int, rank: Int, cap: Int)\n\n def solve(): Unit = {\n import java.util\n val N = ni()\n val S = map(N)(_ => ns())\n\n def read(s: String, i: Int): BS = {\n var rank = 0\n var cap = 0\n REP(s.length) { i =>\n if (s(i) == '(') {\n rank += 1\n } else {\n rank -= 1\n }\n cap = min(cap, rank)\n }\n\n BS(i, rank, cap)\n }\n\n val L = S.zipWithIndex.map((read _).tupled).filter(_.cap >= 0) // capが少ないとrankも少ない\n val R = mutable.Map[Int, util.TreeMap[Integer, mutable.Queue[Int]]]() // rank => cap => [id]\n S.zipWithIndex.map((read _).tupled) foreach { r0 =>\n if (r0.rank <= 0) {\n val r = BS(r0.i, -r0.rank, -r0.cap)\n if (!R.contains(r.rank)) R(r.rank) = new util.TreeMap()\n if (!R(r.rank).containsKey(r.cap)) R(r.rank).put(r.cap, mutable.Queue())\n R(r.rank).get(r.cap) += r.i\n }\n }\n\n val used = Array.ofDim[Boolean](N)\n\n // L == Rになっちゃだめ\n def selectR(ids: mutable.Queue[Int], l: Int): Option[Int] = {\n val id1 = ids.dequeue()\n if (id1 == l) {\n if (ids.nonEmpty) {\n val selected = ids.dequeue()\n ids += id1\n Some(selected)\n } else {\n None\n }\n } else {\n Some(id1)\n }\n }\n\n var ans = 0\n L.foreach { l =>\n if (!used(l.i)) {\n if (R.contains(l.rank)) {\n val byCaps = R(l.rank)\n val capR = byCaps.lowerKey(l.rank + 1) // cap <= rank なので <で比較するときは+1しないといけない\n if (capR != null) {\n val rs = byCaps.get(capR)\n selectR(rs, l.i) match {\n case None =>\n case Some(selected) =>\n // ここでfalseになるはずはないんだけど\n if (!used(selected)) {\n ans += 1\n if (rs.isEmpty) byCaps.remove(capR)\n // Rからremoveするのはコスト高いのでやらない\n used(l.i) = true\n used(selected) = true\n }\n }\n }\n }\n }\n }\n\n out.println(ans)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Int](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val bs = Array.fill(n){ readLine }\n\n def eval(b: String, sign: Int): Int = {\n var cur = 0\n var close = 0\n for (c <- b) {\n c match {\n case '(' => cur += sign\n case ')' => cur -= sign\n }\n if (cur > close) close = cur\n }\n close\n }\n\n val (left, right) = bs.map(b => (eval(b, -1), eval(b.reverse, 1))).partition(_._2 == 0)\n val rightCounts = mutable.Map.empty ++ (right.groupBy(identity).map {\n case (k, v) => k -> v.length\n })\n\n val z = (0, 0)\n var res = left.count(_ == z) / 2\n for ((l, _) <- left) {\n val rr = (0, l)\n if (rightCounts.getOrElse(rr, 0) > 0) {\n rightCounts(rr) -= 1\n res += 1\n }\n }\n\n println(res)\n}\n"}], "negative_code": [], "src_uid": "2cfb08b2269dbf5417c1758def4c035f"} {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable.ListBuffer\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new DivD(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass DivD(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val adj = Array.fill[ListBuffer[Int]](n + 1)(new ListBuffer[Int])\n REP(n-1) { _ =>\n val x = ni()\n val y = ni()\n\n adj(x) += y\n adj(y) += x\n }\n\n var toRun = true\n var z = -1\n while (toRun) {\n var x = -1\n// REP(n, 1) { i =>\n// out.println(s\"$i ${adj(i).length}\")\n// }\n REP(n, 1) { i =>\n if(adj(i).length == 1) x = i\n }\n\n var y = -1\n REP(n, 1) { i =>\n if(adj(i).length == 1 && i != x) y = i\n }\n if(x == -1 && y == -1) {\n out.println(s\"! $z\")\n toRun = false\n } else {\n out.println(s\"? $x $y\")\n out.flush()\n z = ni()\n if (z == x || z == y) {\n out.println(s\"! $z\")\n toRun = false\n } else {\n for (i <- adj(x)) {\n adj(i) = adj(i).filter(p => p != x)\n }\n adj(x) = new ListBuffer[Int]\n for (i <- adj(y)) {\n adj(i) = adj(i).filter(p => p != y)\n }\n adj(y) = new ListBuffer[Int]\n }\n }\n }\n }\n}\n", "positive_code": [{"source_code": "import collection.mutable.HashMap\nimport collection.mutable.HashSet\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = readInt\n val d = HashMap[Int, HashSet[Int]]()\n for(i <- 0 until n) d(i + 1) = HashSet[Int]()\n for(_ <- 0 until n - 1) {\n val Array(x, y) = readLine.split(\" \").map(_.toInt)\n d(x) += y\n d(y) += x\n }\n var flag = true\n while (d.keySet.size != 1 && flag) {\n val (x, y) = getV(d)\n println(s\"? ${x} ${y}\")\n System.out.flush\n \n val v = readInt\n if (v == x) {\n println(s\"! $x\")\n System.out.flush\n flag = false\n }\n else if (v == y) {\n println(s\"! $y\")\n System.out.flush\n flag = false\n }\n else {\n removeV(d, x)\n removeV(d, y)\n }\n }\n if (flag) {\n println(s\"! ${d.keySet.head}\")\n System.out.flush\n }\n }\n\n def getV(d: HashMap[Int, HashSet[Int]]): (Int, Int) = d.filter{\n case (i, s) => s.size == 1\n }.keys.take(2).toList match {\n case x :: y :: _ => (x, y)\n case _ => ???\n }\n\n def removeV(d: HashMap[Int, HashSet[Int]], i: Int): Unit = {\n d(d(i).head) -= i\n d -= i\n }\n}\n\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable.ListBuffer\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new DivD(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass DivD(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val adj = Array.fill[ListBuffer[Int]](n + 1)(new ListBuffer[Int])\n REP(n-1) { _ =>\n val x = ni()\n val y = ni()\n\n adj(x) += y\n adj(y) += x\n }\n\n var toRun = true\n while (toRun) {\n var x = -1\n REP(n, 1) { i =>\n if(adj(i).length == 1) x = i\n }\n\n var y = -1\n REP(n, 1) { i =>\n if(adj(i).length == 1 && i != x) y = i\n }\n out.println(s\"? $x $y\")\n out.flush()\n val z = ni()\n if(z == x || z == y) {\n out.println(s\"! $z\")\n toRun = false\n } else {\n for(i <- adj(x)) {\n adj(i) = adj(i).filter(p => p != x)\n }\n adj(x) = new ListBuffer[Int]\n for(i <- adj(y)) {\n adj(i) = adj(i).filter(p => p != y)\n }\n adj(y) = new ListBuffer[Int]\n }\n }\n }\n}\n"}, {"source_code": "import collection.mutable.HashMap\nimport collection.mutable.HashSet\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = readInt\n val d = HashMap[Int, HashSet[Int]]()\n for(i <- 0 until n) d(i + 1) = HashSet[Int]()\n for(_ <- 0 until n - 1) {\n val Array(x, y) = readLine.split(\" \").map(_.toInt)\n d(x) += y\n d(y) += x\n }\n while (d.keySet.size != 1) {\n val li = getV(d)\n println(s\"? ${li.head} ${li.last}\")\n System.out.flush\n \n val v = readInt\n for(i <- li) {\n if (i != v)\n removeV(d, i, v)\n }\n }\n println(s\"! ${d.keySet.head}\")\n System.out.flush\n }\n\n def getV(d: HashMap[Int, HashSet[Int]]): List[Int] = d.map{\n case (i, s) => (i, s.find((j) => d(j).size > 1))\n }.find{\n case (i, Some(j)) => true\n case (_, _) => false\n }.get match {\n case (i, jo) => List(i, jo.get, d(jo.get).find(_ != i).get)\n }\n def removeV(d: HashMap[Int, HashSet[Int]], i: Int, v: Int): Unit = {\n if (d.contains(i)) {\n d(i).foreach((j) => if (j != v) {\n removeV(d, j, i)\n })\n d -= i\n } \n d(v) -= i\n \n }\n}\n\n"}], "src_uid": "a291ee66980d8b5856b24d1541e66fd0"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, t1) = in.next().split(' ').map(_.toInt)\n val t = n - t1\n val zipped = in.next().zip(in.next())\n val same = zipped.count(i => i._1 == i._2)\n val removeSame = if (same >= t) same - t else 0\n val nSame = same - removeSame\n val selectFirst = t - nSame\n// println(\"nSame = \" + nSame)\n// println(\"selectFirst = \" + selectFirst)\n if (nSame < 0 || (nSame + 2 * selectFirst ) > n)\n println(-1)\n else {\n val answer = zipped.foldLeft(selectFirst, selectFirst, nSame, List.empty[Char]) {\n case ((first, second, same, list), (ch1, ch2)) if same > 0 && ch1 == ch2 =>\n (first, second, same - 1, ch1 :: list)\n case ((first, second, same, list), (ch1, ch2)) if ch1 == ch2 =>\n val s = if (ch1 != 'a') 'a' else 'b'\n (first, second, same, s :: list)\n case ((first, second, same, list), (ch1, ch2)) if first > 0 =>\n (first - 1, second, same, ch1 :: list)\n case ((first, second, same, list), (ch1, ch2)) if second > 0 =>\n (first, second - 1, same, ch2 :: list)\n case ((first, second, same, list), (ch1, ch2)) =>\n val s = if (ch1 != 'a' && ch2 != 'a') 'a' else if (ch1 != 'b' && ch2 != 'b') 'b' else 'c'\n (first, second - 1, same, s :: list)\n }._4.reverse\n println(answer.mkString)\n }\n}", "positive_code": [{"source_code": "/**\n * @author netman\n */\n\n\nimport java.io._\nimport scala._\nimport scala.Array._\nimport java.util.ArrayList\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\n\nobject HelloWorld {\n\n class InputReader(reader: BufferedReader) {\n \n var tokenizer: StringTokenizer = null;\n \n def this(stream: InputStream) = {\n this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));\n }\n \n def this(f: File) = {\n this(new BufferedReader(new FileReader(f), (1 << 20)));\n }\n \n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine());\n }\n return tokenizer.nextToken();\n }\n \n def nextInt(): Int = next().toInt\n \n def nextDouble(): Double = next().toDouble\n \n def close() = reader.close();\n }\n \n class OutputWriter(writer: PrintWriter) {\n def this(stream: OutputStream) {\n this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));\n }\n \n def this(f: File) = {\n this(new PrintWriter(new BufferedWriter(new FileWriter(f))));\n }\n \n def print(x: Any) = writer.print(x);\n \n def println(x: Any) = writer.println(x);\n \n def close() = writer.close();\n }\n \n \n val in = new InputReader(System.in)\n val out = new OutputWriter(System.out)\n \n val P = 1000 * 1000 * 1000L + 7\n \n def main(args: Array[String]): Unit = { \n val (n, t) = (in.nextInt, in.nextInt)\n \n val (a, b) = (in.next, in.next)\n \n var (eq, neq) = (0, 0)\n var (neq01, neq10, neq11, eq00, eq11) = (0, 0, 0, 0, 0)\n \n for (i <- 0 until n) {\n if (a.charAt(i) != b.charAt(i)) {\n neq += 1\n }\n else {\n eq += 1\n }\n }\n \n val (minimal, maximal) = (neq / 2 + (neq % 2), neq + eq)\n \n if (t >= minimal && t <= maximal) {\n neq11 = neq\n eq11 = eq\n \n while (neq11 + eq11 + neq01 > t) {\n if (eq11 > 0) {\n eq11 -= 1\n eq00 += 1\n }\n else if (neq11 >= 2){\n neq11 -= 2\n neq01 += 1\n neq10 += 1\n }\n }\n \n var res = new Array[Char](n)\n \n for (i <- 0 until n) {\n if (a.charAt(i) == b.charAt(i)) {\n if (eq00 > 0) {\n res(i) = a.charAt(i)\n eq00 -= 1\n }\n else {\n res(i) = if (a.charAt(i) == 'a') 'b' else 'a'\n eq11 -= 1\n }\n }\n else {\n if (neq01 > 0) {\n res(i) = a.charAt(i)\n neq01 -= 1\n }\n else if (neq10 > 0) {\n res(i) = b.charAt(i)\n neq10 -= 1\n }\n else {\n res(i) = if (a.charAt(i) != 'a' && b.charAt(i) != 'a') 'a' else if (a.charAt(i) != 'b' && b.charAt(i) != 'b') 'b' else 'c'\n }\n }\n }\n \n for (i <- 0 until n) {\n out.print(res(i))\n }\n }\n else out.println(\"-1\")\n \n out.close\n }\n}"}], "negative_code": [{"source_code": "/**\n * @author netman\n */\n\n\nimport java.io._\nimport scala._\nimport scala.Array._\nimport java.util.ArrayList\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\n\nobject HelloWorld {\n\n class InputReader(reader: BufferedReader) {\n \n var tokenizer: StringTokenizer = null;\n \n def this(stream: InputStream) = {\n this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));\n }\n \n def this(f: File) = {\n this(new BufferedReader(new FileReader(f), (1 << 20)));\n }\n \n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine());\n }\n return tokenizer.nextToken();\n }\n \n def nextInt(): Int = next().toInt\n \n def nextDouble(): Double = next().toDouble\n \n def close() = reader.close();\n }\n \n class OutputWriter(writer: PrintWriter) {\n def this(stream: OutputStream) {\n this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));\n }\n \n def this(f: File) = {\n this(new PrintWriter(new BufferedWriter(new FileWriter(f))));\n }\n \n def print(x: Any) = writer.print(x);\n \n def println(x: Any) = writer.println(x);\n \n def close() = writer.close();\n }\n \n \n val in = new InputReader(System.in)\n val out = new OutputWriter(System.out)\n \n val P = 1000 * 1000 * 1000L + 7\n \n def main(args: Array[String]): Unit = { \n val (n, t) = (in.nextInt, in.nextInt)\n \n val (a, b) = (in.next, in.next)\n \n var (eq, neq) = (0, 0)\n var (neq01, neq10, neq11, eq00, eq11) = (0, 0, 0, 0, 0)\n \n for (i <- 0 until n) {\n if (a.charAt(i) != b.charAt(i)) {\n neq += 1\n }\n else {\n eq += 1\n }\n }\n \n val (minimal, maximal) = (neq / 2 + (neq % 2), neq + eq)\n \n if (t >= minimal && t <= maximal) {\n var rem = t\n if (neq % 2 == 1) {\n neq11 += 1\n neq -= 1\n rem -= 1\n }\n while (neq > 0 && neq / 2 > rem) {\n neq -= 2\n neq10 += 1\n neq01 += 1\n rem -= 1\n }\n while (neq > 0) {\n neq -= 1\n neq11 += 1\n rem -= 1\n }\n while (rem > 0) {\n eq11 += 1\n eq -= 1\n rem -= 1\n }\n while (eq > 0) {\n eq00 += 1\n eq -= 1\n }\n \n var res = new Array[Char](n)\n \n for (i <- 0 until n) {\n if (a.charAt(i) == b.charAt(i)) {\n if (eq00 > 0) {\n res(i) = a.charAt(i)\n eq00 -= 1\n }\n else {\n res(i) = if (a.charAt(i) == 'a') 'b' else 'a'\n eq11 -= 1\n }\n }\n else {\n if (neq01 > 0) {\n res(i) = a.charAt(i)\n neq01 -= 1\n }\n else if (neq10 > 0) {\n res(i) = b.charAt(i)\n neq10 -= 1\n }\n else {\n res(i) = if (a.charAt(i) != 'a' && b.charAt(i) != 'a') 'a' else if (a.charAt(i) != 'b' && b.charAt(i) != 'b') 'b' else 'c'\n }\n }\n }\n \n for (i <- 0 until n) {\n out.print(res(i))\n }\n }\n else out.println(\"-1\")\n \n out.close\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, t1) = in.next().split(' ').map(_.toInt)\n val t = n - t1\n val zipped = in.next().zip(in.next())\n val same = zipped.count(i => i._1 == i._2)\n val removeSame = if (same >= t) same - t else if ((t - same) % 2 == 1) 1 else 0\n val nSame = same - removeSame\n val selectFirst = t - nSame\n if (nSame < 0 || (nSame + 2 * selectFirst) > n)\n println(-1)\n else {\n val answer = zipped.foldLeft(selectFirst, selectFirst, nSame, List.empty[Char]) {\n case ((first, second, same, list), (ch1, ch2)) if same > 0 && ch1 == ch2 =>\n (first, second, same - 1, ch1 :: list)\n case ((first, second, same, list), (ch1, ch2)) if ch1 == ch2 =>\n val s = if (ch1 != 'a') 'a' else 'b'\n (first, second, same, s :: list)\n case ((first, second, same, list), (ch1, ch2)) if first > 0 =>\n (first - 1, second, same, ch1 :: list)\n case ((first, second, same, list), (ch1, ch2)) if second > 0 =>\n (first, second - 1, same, ch2 :: list)\n case ((first, second, same, list), (ch1, ch2)) =>\n val s = if (ch1 != 'a' && ch2 != 'a') 'a' else if (ch1 != 'b' && ch2 != 'b') 'b' else 'c'\n (first, second - 1, same, s :: list)\n }._4.reverse\n println(answer.mkString)\n }\n}"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'c'\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val k = n - t\n val q = n - count\n val r = if (k <= q) {\n zipped.foldLeft((k, List.empty[Char])) {\n case ((left, l), (el1, el2)) if el1 == el2 && left > 0 =>\n (left - 1, el1 :: l)\n case ((left, l), (el1, el2)) => (left, diff(el1, el2) :: l)\n }._2\n } else {\n zipped.foldLeft((count / 2, count / 2, q - count / 2, List.empty[Char])) {\n case ((first, second, change, l), (el1, el2)) if el1 == el2 && change > 0 =>\n (first, second, change - 1, el1 :: l)\n case ((first, second, change, l), (el1, el2)) if second > 0 =>\n (first, second - 1, change, el2 :: l)\n case ((first, second, change, l), (el1, el2)) if first > 0 =>\n (first - 1, second, change, el1 :: l)\n case ((first, second, change,l), (el1, el2)) =>\n (first, second, change, diff(el1, el2) :: l)\n }._4\n }\n // count = 1\n // count / 2 = 0\n // change = t = 1\n // println(count / 2)\n // println(t - count + count / 2)\n // println(count % 2)\n\n println(r.reverse.mkString)\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, t1) = in.next().split(' ').map(_.toInt)\n val t = n - t1\n val zipped = in.next().zip(in.next())\n val same = zipped.count(i => i._1 == i._2)\n val removeSame = if (same >= t) same - t else if ((t - same) % 2 == 1) 1 else 0\n val nSame = same - removeSame\n val selectFirst = t - nSame\n if (nSame < 0)\n println(-1)\n else {\n val answer = zipped.foldLeft(selectFirst, selectFirst, nSame, List.empty[Char]) {\n case ((first, second, same, list), (ch1, ch2)) if same > 0 && ch1 == ch2 =>\n (first, second, same - 1, ch1 :: list)\n case ((first, second, same, list), (ch1, ch2)) if ch1 == ch2 =>\n val s = if (ch1 != 'a') 'b' else 'b'\n (first, second, same, s :: list)\n case ((first, second, same, list), (ch1, ch2)) if first > 0 =>\n (first - 1, second, same, ch1 :: list)\n case ((first, second, same, list), (ch1, ch2)) if second > 0 =>\n (first, second - 1, same, ch2 :: list)\n case ((first, second, same, list), (ch1, ch2)) =>\n val s = if (ch1 != 'a' && ch2 != 'a') 'a' else if (ch1 != 'b' && ch2 != 'b') 'b' else 'c'\n (first, second - 1, same, s :: list)\n }._4.reverse\n println(answer.mkString)\n }\n}"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'c'\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val k = n - t\n val q = n - count\n val r = if (k <= q) {\n zipped.foldLeft((k, List.empty[Char])) {\n case ((left, l), (el1, el2)) if el1 == el2 && left > 0 =>\n (left - 1, el1 :: l)\n case ((left, l), (el1, el2)) => (left, diff(el1, el2) :: l)\n }._2\n } else {\n zipped.foldLeft((count / 2, count / 2, 2 * t, List.empty[Char])) {\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && second > 0 =>\n (first, second - 1, change - 1, el2 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && first > 0 =>\n (first - 1, second, change - 1, el1 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 == el2 && change > 0 =>\n (first, second, change - 2, el1 :: l)\n case ((first, second, change,l), (el1, el2)) =>\n (first, second, change, diff(el1, el2) :: l)\n }._4\n }\n // count = 1\n // count / 2 = 0\n // change = t = 1\n // println(count / 2)\n // println(t - count + count / 2)\n // println(count % 2)\n\n println(r.reverse.mkString)\n }\n}\n"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'c'\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val k = n - t\n val q = n - count\n val r = if (k <= q) {\n zipped.foldLeft((k, List.empty[Char])) {\n case ((left, l), (el1, el2)) if el1 == el2 && left > 0 =>\n (left - 1, el1 :: l)\n case ((left, l), (el1, el2)) => (left, diff(el1, el2) :: l)\n }._2\n } else {\n zipped.foldLeft((count / 2, count / 2, t - count + count / 2, count % 2, List.empty[Char])) {\n case ((first, second, change, 1, l), (el1, el2)) if el1 != el2 =>\n (first, second, change, 0, diff(el1, el2) :: l)\n case ((first, second, change, d, l), (el1, el2)) if el1 == el2 && change > 0 =>\n (first, second, change - 1, d, diff(el1, el2) :: l)\n case ((first, second, change, d, l), (el1, el2)) if el1 == el2 =>\n (first, second, change, d, el1 :: l)\n case ((first, second, change, d, l), (el1, el2)) if second > first =>\n (first, second - 1, change, d, el2 :: l)\n case ((first, second, change, d, l), (el1, el2)) if first > 0 =>\n (first - 1, second, change, d, el1 :: l)\n case ((first, second, change, d, l), (el1, el2)) =>\n (first, second, change, d, el1 :: l)\n }._5\n }\n// count = 1\n// count / 2 = 0\n// change = t = 1\n// println(count / 2)\n// println(t - count + count / 2)\n// println(count % 2)\n\n println(r.reverse.mkString)\n }\n}\n"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'c'\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n// count = 1\n// count / 2 = 0\n// change = t = 1\n val r = zipped.foldLeft((count / 2, count / 2, t - count / 2 - count % 2, List.empty[Char])) {\n case ((first, second, 0, l), (el1, el2)) if el1 == el2 => (first, second, 0, el1 :: l)\n case ((first, second, change, l), (el1, el2)) if second > first => (first, second - 1, change, el2 :: l)\n case ((first, second, change, l), (el1, el2)) if first > 0 => (first - 1, second, change, el1 :: l)\n case ((first, second, change, l), (el1, el2)) if change > 0 => (first, second, change - 1, diff(el1, el2) :: l)\n case ((first, second, change, l), (el1, el2)) if el1 == el2 => (first, second, change - 1, el1 :: l)\n case ((first, second, change, l), (el1, el2)) => (first, second, change - 1, diff(el1, el2) :: l)\n }\n\n println(r._4.reverse.mkString)\n }\n}\n"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'c'\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val k = n - t\n val q = n - count\n val r = if (k <= q) {\n zipped.foldLeft((k, List.empty[Char])) {\n case ((left, l), (el1, el2)) if el1 == el2 && left > 0 =>\n (left - 1, el1 :: l)\n case ((left, l), (el1, el2)) => (left, diff(el1, el2) :: l)\n }._2\n } else {\n zipped.foldLeft((count / 2, count / 2, 2 * t, List.empty[Char])) {\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && second > 0 =>\n (first, second - 1, change - 1, el2 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && first > 0 =>\n (first - 1, second, change - 1, el1 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 == el2 && change > 0 =>\n (first, second, change - 2, diff(el1, el2) :: l)\n case ((first, second, change,l), (el1, el2)) =>\n (first, second, change, el1 :: l)\n }._4\n }\n // count = 1\n // count / 2 = 0\n // change = t = 1\n // println(count / 2)\n // println(t - count + count / 2)\n // println(count % 2)\n\n println(r.reverse.mkString)\n }\n}\n"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'c'\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val k = n - t\n val q = n - count\n val r = if (k <= q) {\n zipped.foldLeft((k, List.empty[Char])) {\n case ((left, l), (el1, el2)) if el1 == el2 && left > 0 =>\n (left - 1, el1 :: l)\n case ((left, l), (el1, el2)) => (left, diff(el1, el2) :: l)\n }._2\n } else {\n zipped.foldLeft((count / 2, count / 2, t - count / 2, List.empty[Char])) {\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && second > 0 =>\n (first, second - 1, change, el2 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && first > 0 =>\n (first - 1, second, change, el1 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 == el2 && change > 0 =>\n (first, second, change - 1, el1 :: l)\n case ((first, second, change,l), (el1, el2)) =>\n (first, second, change, diff(el1, el2) :: l)\n }._4\n }\n // count = 1\n // count / 2 = 0\n // change = t = 1\n // println(count / 2)\n // println(t - count + count / 2)\n // println(count % 2)\n\n println(r.reverse.mkString)\n }\n}\n"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'c'\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val k = n - t\n val q = n - count\n val r = if (k <= q) {\n zipped.foldLeft((k, List.empty[Char])) {\n case ((left, l), (el1, el2)) if el1 == el2 && left > 0 =>\n (left - 1, el1 :: l)\n case ((left, l), (el1, el2)) => (left, diff(el1, el2) :: l)\n }._2\n } else {\n zipped.foldLeft((count / 2, count / 2, q - count / 2, List.empty[Char])) {\n case ((first, second, change, l), (el1, el2)) if el1 == el2 && change > 0 =>\n (first, second, change - 1, el1 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && second > 0 =>\n (first, second - 1, change, el2 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && first > 0 =>\n (first - 1, second, change, el1 :: l)\n case ((first, second, change,l), (el1, el2)) =>\n (first, second, change, diff(el1, el2) :: l)\n }._4\n }\n // count = 1\n // count / 2 = 0\n // change = t = 1\n // println(count / 2)\n // println(t - count + count / 2)\n // println(count % 2)\n\n println(r.reverse.mkString)\n }\n}\n"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'c'\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val k = n - t\n val q = n - count\n val r = if (k <= q) {\n zipped.foldLeft((k, List.empty[Char])) {\n case ((left, l), (el1, el2)) if el1 == el2 && left > 0 =>\n (left - 1, el1 :: l)\n case ((left, l), (el1, el2)) => (left, diff(el1, el2) :: l)\n }._2\n } else {\n zipped.foldLeft((count / 2, count / 2, q - count / 2, List.empty[Char])) {\n case ((first, second, change, l), (el1, el2)) if el1 == el2 && change > 0 =>\n (first, second, change - 1, el1 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 == el2 =>\n (first, second, change, el1 :: l)\n case ((first, second, change, l), (el1, el2)) if second > 0 =>\n (first, second - 1, change, el2 :: l)\n case ((first, second, change, l), (el1, el2)) if first > 0 =>\n (first - 1, second, change, el1 :: l)\n case ((first, second, change,l), (el1, el2)) =>\n (first, second, change, diff(el1, el2) :: l)\n }._4\n }\n // count = 1\n // count / 2 = 0\n // change = t = 1\n // println(count / 2)\n // println(t - count + count / 2)\n // println(count % 2)\n\n println(r.reverse.mkString)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val r = zipped.foldLeft((t, t, 2 * t - count, List.empty[Char])) {\n case ((a, b, ch, l), ('a', 'a')) if ch > 0 => (a, b, ch - 1, 'b' :: l)\n case ((a, b, ch, l), (el1, el2)) if el1 == el2 && ch > 0 => (a, b, ch - 1, 'b' :: l)\n case ((a, b, ch, l), (el1, el2)) if a > b => (a - 1, b, ch, el1 :: l)\n case ((a, b, ch, l), (el1, el2)) => (a, b - 1, ch, el2 :: l)\n }\n println(r._4.reverse.mkString)\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val r = zipped.foldLeft((count / 2, count / 2, t - count / 2, List.empty[Char])) {\n case ((a, b, ch, l), ('a', 'a')) if ch > 0 => (a, b, ch - 1, 'b' :: l)\n case ((a, b, ch, l), (el1, el2)) if el1 == el2 && ch > 0 => (a, b, ch - 1, 'b' :: l)\n case ((a, b, ch, l), (el1, el2)) if el1 == el2 => (a, b, ch, el1 :: l)\n case ((0, 0, ch, l), (el1, el2)) if el1 != 'a' && el2 != 'a' => (0, 0, ch, 'a' :: l)\n case ((0, 0, ch, l), (el1, el2)) if el1 != 'b' && el2 != 'b' => (0, 0, ch, 'b' :: l)\n case ((0, 0, ch, l), (el1, el2)) if el1 != 'c' && el2 != 'c' => (0, 0, ch, 'c' :: l)\n case ((a, b, ch, l), (el1, el2)) if a > b => (a - 1, b, ch, el1 :: l)\n case ((a, b, ch, l), (el1, el2)) => (a, b - 1, ch, el2 :: l)\n }\n println(r._4.reverse.mkString)\n }\n}"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'c'\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val k = n - t\n val q = n - count\n val r = if (k <= q) {\n zipped.foldLeft((k, List.empty[Char])) {\n case ((left, l), (el1, el2)) if el1 == el2 && left > 0 =>\n (left - 1, el1 :: l)\n case ((left, l), (el1, el2)) => (left, diff(el1, el2) :: l)\n }._2\n } else {\n zipped.foldLeft((count / 2, count / 2, n - t - count / 2, List.empty[Char])) {\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && first > 0 =>\n (first - 1, second, change, el1 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && second > 0 =>\n (first, second - 1, change, el2 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 == el2 && change > 0 =>\n (first, second, change, el1 :: l)\n case ((first, second, change,l), (el1, el2)) =>\n (first, second, change, diff(el1, el2) :: l)\n }._4\n }\n // count = 1\n // count / 2 = 0\n // change = t = 1\n // println(count / 2)\n // println(t - count + count / 2)\n // println(count % 2)\n\n println(r.reverse.mkString)\n }\n}\n"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'c'\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val k = n - t\n val q = n - count\n val r = if (k <= q) {\n zipped.foldLeft((k, List.empty[Char])) {\n case ((left, l), (el1, el2)) if el1 == el2 && left > 0 =>\n (left - 1, el1 :: l)\n case ((left, l), (el1, el2)) => (left, diff(el1, el2) :: l)\n }._2\n } else {\n zipped.foldLeft((count / 2, count / 2, t - count + count / 2, count % 2, List.empty[Char])) {\n case ((first, second, change, 1, l), (el1, el2)) if el1 != el2 =>\n (first, second, change, 0, diff(el1, el2) :: l)\n case ((first, second, change, d, l), (el1, el2)) if el1 == el2 && change > 0 =>\n (first, second, change - 1, d, diff(el1, el2) :: l)\n case ((first, second, change, d, l), (el1, el2)) if el1 == el2 =>\n (first, second, change, d, el1 :: l)\n case ((first, second, change, d, l), (el1, el2)) if second > 0 =>\n (first, second - 1, change, d, el2 :: l)\n case ((first, second, change, d, l), (el1, el2)) if first > 0 =>\n (first - 1, second, change, d, el1 :: l)\n case ((first, second, change, d, l), (el1, el2)) =>\n (first, second, change, d, el1 :: l)\n }._5\n }\n// count = 1\n// count / 2 = 0\n// change = t = 1\n// println(count / 2)\n// println(t - count + count / 2)\n// println(count % 2)\n\n println(r.reverse.mkString)\n }\n}\n"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'c'\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val k = n - t\n val q = n - count\n val r = if (k <= q) {\n zipped.foldLeft((k, List.empty[Char])) {\n case ((left, l), (el1, el2)) if el1 == el2 && left > 0 =>\n (left - 1, el1 :: l)\n case ((left, l), (el1, el2)) => (left, diff(el1, el2) :: l)\n }._2\n } else {\n zipped.foldLeft((count / 2, count / 2, n - t, List.empty[Char])) {\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && first > 0 =>\n (first - 1, second, change, el1 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && second > 0 =>\n (first, second - 1, change, el2 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 == el2 && change > 0 =>\n (first, second, change, el1 :: l)\n case ((first, second, change,l), (el1, el2)) =>\n (first, second, change, diff(el1, el2) :: l)\n }._4\n }\n // count = 1\n // count / 2 = 0\n // change = t = 1\n // println(count / 2)\n // println(t - count + count / 2)\n // println(count % 2)\n\n println(r.reverse.mkString)\n }\n}\n"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'c'\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n// count = 1\n// count / 2 = 0\n// change = t = 1\n val r = zipped.foldLeft((count / 2, count / 2, t - count + count / 2, count % 2, List.empty[Char])) {\n case ((first, second, change, 1, l), (el1, el2)) if el1 != el2 =>\n (first, second, change, 0, diff(el1, el2) :: l)\n case ((first, second, change, d, l), (el1, el2)) if el1 == el2 && change > 0 =>\n (first, second, change - 1, d, diff(el1, el2) :: l)\n case ((first, second, change, d, l), (el1, el2)) if second > first =>\n (first, second - 1, change, d, el2 :: l)\n case ((first, second, change, d, l), (el1, el2)) if first > 0 =>\n (first - 1, second, change, d, el1 :: l)\n case ((first, second, change, d, l), (el1, el2)) if change > 0 =>\n (first, second, change - 1, d, diff(el1, el2) :: l)\n case ((first, second, change, d, l), (el1, el2)) if el1 == el2 =>\n (first, second, change - 1, d, el1 :: l)\n case ((first, second, change, d, l), (el1, el2)) =>\n (first, second, change - 1, d, diff(el1, el2) :: l)\n }\n\n println(r._5.reverse.mkString)\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, t1) = in.next().split(' ').map(_.toInt)\n val t = n - t1\n val zipped = in.next().zip(in.next())\n val same = zipped.count(i => i._1 == i._2)\n val removeSame = if (same >= t) same - t else if ((t - same) % 2 == 1) 1 else 0\n val nSame = same - removeSame\n val selectFirst = t - nSame\n if (nSame < 0)\n println(-1)\n else {\n val answer = zipped.foldLeft(selectFirst, selectFirst, nSame, List.empty[Char]) {\n case ((first, second, same, list), (ch1, ch2)) if same > 0 && ch1 == ch2 =>\n (first, second, same - 1, ch1 :: list)\n case ((first, second, same, list), (ch1, ch2)) if ch1 == ch2 =>\n val s = if (ch1 != 'a') 'a' else 'b'\n (first, second, same, s :: list)\n case ((first, second, same, list), (ch1, ch2)) if first > 0 =>\n (first - 1, second, same, ch1 :: list)\n case ((first, second, same, list), (ch1, ch2)) if second > 0 =>\n (first, second - 1, same, ch2 :: list)\n case ((first, second, same, list), (ch1, ch2)) =>\n val s = if (ch1 != 'a' && ch2 != 'a') 'a' else if (ch1 != 'b' && ch2 != 'b') 'b' else 'c'\n (first, second - 1, same, s :: list)\n }._4.reverse\n println(answer.mkString)\n }\n}"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'c'\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val k = n - t\n val q = n - count\n val r = if (k <= q) {\n zipped.foldLeft((k, List.empty[Char])) {\n case ((left, l), (el1, el2)) if el1 == el2 && left > 0 =>\n (left - 1, el1 :: l)\n case ((left, l), (el1, el2)) => (left, diff(el1, el2) :: l)\n }._2\n } else {\n zipped.foldLeft((count / 2, count / 2, t - count / 2, List.empty[Char])) {\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && second > 0 =>\n (first, second - 1, change, el2 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && first > 0 =>\n (first - 1, second, change, el1 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 == el2 && change > 0 =>\n (first, second, change, el1 :: l)\n case ((first, second, change,l), (el1, el2)) =>\n (first, second, change, diff(el1, el2) :: l)\n }._4\n }\n // count = 1\n // count / 2 = 0\n // change = t = 1\n // println(count / 2)\n // println(t - count + count / 2)\n // println(count % 2)\n\n println(r.reverse.mkString)\n }\n}\n"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'C'\n }\n }\n\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val r = zipped.foldLeft((count / 2, count / 2, t - count / 2, List.empty[Char])) {\n case ((first, second, 0, l), (el1, el2)) if el1 == el2 => (first, second, 0, el1 :: l)\n case ((first, second, change, l), (el1, el2)) if second > first => (first, second - 1, change, el2 :: l)\n case ((first, second, change, l), (el1, el2)) if first > 0 => (first - 1, second, change, el1 :: l)\n case ((first, second, change, l), (el1, el2)) if change > 0 => (first, second, change - 1, diff(el1, el2) :: l)\n case ((first, second, change, l), (el1, el2)) => (first, second, change - 1, el1 :: l)\n\n }\n\n println(r._4.reverse.mkString)\n\n\n // 1) different symbols too many\n // 2) different symbols too few\n\n }\n}\n//cbca"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'c'\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val k = n - t\n val q = n - count\n val r = if (k <= q) {\n zipped.foldLeft((k, List.empty[Char])) {\n case ((left, l), (el1, el2)) if el1 == el2 && left > 0 =>\n (left - 1, el1 :: l)\n case ((left, l), (el1, el2)) => (left, diff(el1, el2) :: l)\n }._2\n } else {\n zipped.foldLeft((count / 2, count / 2, q - count / 2, List.empty[Char])) {\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && first > 0 =>\n (first - 1, second, change, el1 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && second > 0 =>\n (first, second - 1, change, el2 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 == el2 && change > 0 =>\n (first, second, change, el1 :: l)\n case ((first, second, change,l), (el1, el2)) =>\n (first, second, change, diff(el1, el2) :: l)\n }._4\n }\n // count = 1\n // count / 2 = 0\n // change = t = 1\n // println(count / 2)\n // println(t - count + count / 2)\n // println(count % 2)\n\n println(r.reverse.mkString)\n }\n}\n"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'c'\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val k = n - t\n val q = n - count\n val r = if (k <= q) {\n zipped.foldLeft((k, List.empty[Char])) {\n case ((left, l), (el1, el2)) if el1 == el2 && left > 0 =>\n (left - 1, el1 :: l)\n case ((left, l), (el1, el2)) => (left, diff(el1, el2) :: l)\n }._2\n } else {\n zipped.foldLeft((count / 2, count / 2, t - count / 2, List.empty[Char])) {\n case ((first, second, change, l), (el1, el2)) if el1 != el2 && first > 0 =>\n (first - 1, second, change, el1 :: l) \n case ((first, second, change, l), (el1, el2)) if el1 != el2 && second > 0 =>\n (first, second - 1, change, el2 :: l)\n case ((first, second, change, l), (el1, el2)) if el1 == el2 && change > 0 =>\n (first, second, change - 1, el1 :: l)\n case ((first, second, change,l), (el1, el2)) =>\n (first, second, change, diff(el1, el2) :: l)\n }._4\n }\n // count = 1\n // count / 2 = 0\n // change = t = 1\n // println(count / 2)\n // println(t - count + count / 2)\n // println(count % 2)\n\n println(r.reverse.mkString)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n val r = zipped.foldLeft((count / 2, count / 2, t - count / 2, List.empty[Char])) {\n case ((a, b, ch, l), ('a', 'a')) if ch > 0 => (a, b, ch - 1, 'b' :: l)\n case ((a, b, ch, l), (el1, el2)) if el1 == el2 && ch > 0 => (a, b, ch - 1, 'b' :: l)\n case ((a, b, ch, l), (el1, el2)) if el1 == el2 => (a, b, ch, el1 :: l)\n case ((a, b, ch, l), (el1, el2)) if a > b => (a - 1, b, ch, el1 :: l)\n case ((a, b, ch, l), (el1, el2)) => (a, b - 1, ch, el2 :: l)\n }\n println(r._4.reverse.mkString)\n }\n}"}, {"source_code": "object Solution extends App {\n\n def diff(a: Char, b: Char) = {\n (a, b) match {\n case (a, b) if a != 'a' && b != 'a' => 'a'\n case (a, b) if a != 'b' && b != 'b' => 'b'\n case (a, b) if a != 'c' && b != 'c' => 'c'\n }\n }\n\n val in = scala.io.Source.stdin.getLines()\n val Array(n, t) = in.next().split(' ').map(_.toInt)\n val str1 = in.next()\n val str2 = in.next()\n val zipped = str1.zip(str2)\n val count = zipped.count(t => t._1 != t._2)\n if (t > n || count > 2 * t)\n println(-1)\n else {\n// count = 1\n// count / 2 = 0\n// change = t = 1\n// println(count / 2)\n// println(t - count + count / 2)\n// println(count % 2)\n val r = zipped.foldLeft((count / 2, count / 2, t - count + count / 2, count % 2, List.empty[Char])) {\n case ((first, second, change, 1, l), (el1, el2)) if el1 != el2 =>\n (first, second, change, 0, diff(el1, el2) :: l)\n case ((first, second, change, d, l), (el1, el2)) if el1 == el2 && change > 0 =>\n (first, second, change - 1, d, diff(el1, el2) :: l)\n case ((first, second, change, d, l), (el1, el2)) if el1 == el2 =>\n (first, second, change, d, el1 :: l)\n case ((first, second, change, d, l), (el1, el2)) if second > first =>\n (first, second - 1, change, d, el2 :: l)\n case ((first, second, change, d, l), (el1, el2)) if first > 0 =>\n (first - 1, second, change, d, el1 :: l)\n case ((first, second, change, d, l), (el1, el2)) =>\n (first, second, change, d, el1 :: l)\n }\n\n println(r._5.reverse.mkString)\n }\n}\n"}], "src_uid": "8ba3a7f7cb955478481c74cd4a4eed14"} {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(3000)\n val n = s.length\n\n val c = Array.ofDim[Short](n + 1, n + 1)\n\n for (i <- 0 to n) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n var maxLen = 0\n\n for (i <- 1 to n; j <- 1 to n) {\n val cc = if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1).toShort\n else if (c(i - 1)(j) >= c(i)(j - 1)) c(i - 1)(j)\n else c(i)(j - 1)\n c(i)(j) = cc\n if (cc > maxLen) maxLen = cc\n }\n\n for (i <- 1 to n; j <- 1 to n; if c(i)(j) == maxLen) {\n var candidate = lcs_print(i, j).toString\n if (candidate.equals(candidate.reverse)) {\n while (candidate.length > 100) {\n val l = candidate.length\n if (l % 2 == 1) candidate = candidate.take(l / 2) + candidate.drop(l / 2 + 1)\n else candidate = candidate.substring(1, l - 1)\n }\n println(candidate)\n exit\n }\n }\n\n}", "positive_code": [{"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(2601)\n val n = s.length\n\n val c = Array.fill(n + 2, n + 1)(0)\n\n def lps_print(l: Int, r: Int): String = {\n if (l > r) \"\" \n else if (l == r) s(l - 1).toString \n else if (s(l - 1) == s(r - 1)) s(l - 1) + lps_print(l + 1, r - 1) + s(l - 1)\n else if (c(l + 1)(r) >= c(l)(r - 1)) lps_print(l + 1, r)\n else lps_print(l, r - 1)\n }\n\n var maxLen = 0\n var best = \"\"\n\n for (l <- n to 1 by -1; r <- l to n) {\n c(l)(r) = math.max(if (s(l - 1) == s(r - 1)) c(l + 1)(r - 1) + (if (l == r) 1 else 2) else 0,\n \t\t math.max(c(l + 1)(r), c(l)(r - 1)))\n if (c(l)(r) > maxLen) {\n maxLen = c(l)(r)\n best = lps_print(l, r)\n if (maxLen >= 100) {\n if (maxLen == 101) best = best.take(50) + best.drop(51)\n println(best)\n exit\n }\n }\n }\n \n println(best)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(2601)\n val n = s.length\n\n val c = Array.ofDim[Int](n + 1, n + 1)\n\n for (i <- 0 to n) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n var maxLen = 0\n\n for (i <- 1 to n; j <- 1 to n) {\n c(i)(j) = math.max(if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1) else 0,\n \t\t math.max(c(i - 1)(j), c(i)(j - 1)))\n if (c(i)(j) > maxLen) maxLen = c(i)(j)\n }\n\n for (i <- maxLen to n; j <- maxLen to n; if c(i)(j) == maxLen) {\n var candidate = lcs_print(i, j).toString\n if (candidate.equals(candidate.reverse)) {\n while (candidate.length > 100) {\n val l = candidate.length\n if (l % 2 == 1) candidate = candidate.take(l / 2) + candidate.drop(l / 2 + 1)\n else candidate = candidate.substring(1, l - 1)\n }\n println(candidate)\n exit\n }\n }\n\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(3000)\n val n = s.length\n\n val c = Array.ofDim[Short](n + 1, n + 1)\n\n for (i <- 0 to n) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n var maxLen = 0\n\n for (i <- 1 to n; j <- 1 to n) {\n val cc = if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1).toShort\n else if (c(i - 1)(j) >= c(i)(j - 1)) c(i - 1)(j)\n else c(i)(j - 1)\n c(i)(j) = cc\n if (cc > maxLen) maxLen = cc\n }\n\n for (i <- maxLen to n; j <- maxLen to n; if c(i)(j) == maxLen) {\n var candidate = lcs_print(i, j).toString\n if (candidate.equals(candidate.reverse)) {\n while (candidate.length > 100) {\n val l = candidate.length\n if (l % 2 == 1) candidate = candidate.take(l / 2) + candidate.drop(l / 2 + 1)\n else candidate = candidate.substring(1, l - 1)\n }\n println(candidate)\n exit\n }\n }\n\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(3000)\n val n = s.length\n\n val c = Array.ofDim[Int](n + 1, n + 1)\n\n for (i <- 0 to n) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n var maxLen = 0\n\n for (i <- 1 to n; j <- 1 to n) {\n val cc = math.max(if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1) else 0,\n \t\t math.max(c(i - 1)(j), c(i)(j - 1)))\n c(i)(j) = cc\n if (cc > maxLen) maxLen = cc\n }\n\n for (i <- maxLen to n; j <- maxLen to n; if c(i)(j) == maxLen) {\n var candidate = lcs_print(i, j).toString\n if (candidate.equals(candidate.reverse)) {\n while (candidate.length > 100) {\n val l = candidate.length\n if (l % 2 == 1) candidate = candidate.take(l / 2) + candidate.drop(l / 2 + 1)\n else candidate = candidate.substring(1, l - 1)\n }\n println(candidate)\n exit\n }\n }\n\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(3000)\n val n = s.length\n\n val c = Array.ofDim[Short](n + 1, n + 1)\n\n for (i <- 0 to n) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n var i = 0\n var maxLen = 0\n var best = \"\"\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n while (i < n) {\n i += 1\n var j = 0\n while (j < n) {\n j += 1\n val cc = if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1).toShort\n else if (c(i - 1)(j) >= c(i)(j - 1)) c(i - 1)(j)\n else c(i)(j - 1)\n c(i)(j) = cc\n if (cc > maxLen) maxLen = cc\n }\n }\n\n i = 0\n while (i < n) {\n i += 1\n var j = 0\n while (j < n) {\n j += 1\n if (c(i)(j) == maxLen) {\n val candidate = lcs_print(i, j).toString\n if (candidate.equals(candidate.reverse)) {\n best = candidate\n i = n + 1\n j = n + 1\n }\n }\n }\n }\n\n while (best.length > 100) {\n val l = best.length\n if (l % 2 == 1) best = best.take(l / 2) + best.drop(l / 2 + 1)\n else best = best.substring(1, l - 1)\n }\n\n println(best)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(3000)\n val n = s.length\n\n val c = Array.ofDim[Short](n + 1, n + 1)\n\n for (i <- 0 to n) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n var i = 0\n var maxLen = 0\n var best = \"\"\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n while (i < n) {\n i += 1\n var j = 0\n while (j < n) {\n j += 1\n val cc = if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1).toShort\n else if (c(i - 1)(j) >= c(i)(j - 1)) c(i - 1)(j)\n else c(i)(j - 1)\n c(i)(j) = cc\n //if (cc == 50) println(lcs_print(i, j).toString)\n if (cc > maxLen) {\n maxLen = cc\n //best = lcs_print(i, j).toString\n }\n /*if (maxLen == 100) {\n i = n + 1\n j = n + 1\n }*/\n }\n }\n\n i = 0\n while (i < n) {\n i += 1\n var j = 0\n while (j < n) {\n j += 1\n if (c(i)(j) == maxLen) {\n val candidate = lcs_print(i, j).toString\n if (candidate.equals(candidate.reverse)) {\n best = candidate\n i = n + 1\n j = n + 1\n }\n }\n }\n }\n\n while (best.length > 100) {\n val l = best.length\n if (l % 2 == 1) best = best.take(l / 2) + best.drop(l / 2 + 1)\n else best = best.substring(1, l - 1)\n }\n\n println(best)\n}"}], "negative_code": [{"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(3000)\n val n = s.length\n val nn = n // 2 + 2\n\n val c = Array.ofDim[Short](nn + 1, nn + 1)\n\n for (i <- 0 to nn) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n var i = 0\n var maxLen = 0\n var best = \"\"\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n while (i < nn) {\n i += 1\n var j = 0\n while (j < nn) {\n j += 1\n val cc = if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1).toShort\n else if (c(i - 1)(j) >= c(i)(j - 1)) c(i - 1)(j)\n else c(i)(j - 1)\n c(i)(j) = cc\n if (cc > maxLen) {\n val candidate = lcs_print(i, j).toString\n if (cc != 100 || candidate.equals(candidate.reverse)) {\n maxLen = cc\n best = candidate\n }\n }\n if (maxLen >= 100) {\n i = nn + 1\n j = nn + 1\n }\n }\n }\n\n println(best)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(3000)\n val n = s.length\n\n val c = Array.ofDim[Short](n + 1, n + 1)\n\n for (i <- 0 to n) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n var i = 0\n var maxLen = 0\n var best = \"\"\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n while (i < n) {\n i += 1\n var j = 0\n while (j < n) {\n j += 1\n val cc = if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1).toShort\n else if (c(i - 1)(j) >= c(i)(j - 1)) c(i - 1)(j)\n else c(i)(j - 1)\n c(i)(j) = cc\n if (cc > maxLen) {\n maxLen = cc\n if (maxLen == 100) {\n i = n + 1\n j = n + 1\n }\n }\n }\n }\n\n i = 0\n while (i < n) {\n i += 1\n var j = 0\n while (j < n) {\n j += 1\n if (c(i)(j) == maxLen) {\n val candidate = lcs_print(i, j).toString\n if (candidate.equals(candidate.reverse)) {\n best = candidate\n i = n + 1\n j = n + 1\n }\n }\n }\n }\n\n while (best.length > 100) {\n val l = best.length\n if (l % 2 == 1) best = best.take(l / 2) + best.drop(l / 2 + 1)\n else best = best.substring(1, l - 1)\n }\n\n println(best)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(3000) // (\"a\" * 10000).take(3000)\n val rs = s.reverse\n val n = s.length\n\n val zero: Byte = 0\n val one: Byte = 0\n val c = Array.fill(n + 1, n + 1)(0)\n val b = Array.ofDim[Char](n + 1, n + 1)\n\n var i = 0\n var maxLen = 0\n var best = \"\"\n \n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) {\n return new StringBuilder()\n } else b(i)(j) match {\n case '\\\\' => lcs_print(i - 1, j - 1) + s(i - 1)\n case '|' => lcs_print(i - 1, j)\n case _ => lcs_print(i, j - 1)\n }\n \n }\n \n while (i < n) {\n i += 1\n var j = 0\n while (j < n) {\n j += 1\n if (s(i - 1) == rs(j - 1)) {\n \t c(i)(j) = (c(i - 1)(j - 1) + 1)\n \t b(i)(j) = '\\\\'\n } else if (c(i - 1)(j) >= c(i)(j - 1)) {\n c(i)(j) = c(i - 1)(j)\n \tb(i)(j) = '|'\n } else {\n c(i)(j) = c(i)(j - 1)\n \tb(i)(j) = '-'\n }\n if (c(i)(j) > maxLen) {\n maxLen = c(i)(j)\n best = lcs_print(i, j).toString\n }\n if (c(i)(j) == 100) { \n i = n + 1\n j = n + 1\n }\n }\n }\n \n println(best)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(3000)\n val n = s.length\n\n val c = Array.ofDim[Int](n + 1, n + 1)\n\n for (i <- 0 to n) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n var maxLen = 0\n\n for (i <- 1 to n; j <- 1 to n) {\n val cc = math.max(if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1) else 0,\n \t\t math.max(c(i - 1)(j), c(i)(j - 1)))\n c(i)(j) = cc\n if (cc > maxLen) maxLen = cc\n }\n\n for (i <- maxLen to n; j <- maxLen to n; if c(i)(j) == maxLen) {\n var candidate = lcs_print(i, j).toString\n //if (candidate.equals(candidate.reverse)) {\n while (candidate.length > 100) {\n val l = candidate.length\n if (l % 2 == 1) candidate = candidate.take(l / 2) + candidate.drop(l / 2 + 1)\n else candidate = candidate.substring(1, l - 1)\n }\n println(candidate)\n exit\n //}\n }\n\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(3000)\n val n = s.length\n\n val c = Array.ofDim[Short](n + 1, n + 1)\n\n for (i <- 0 to n) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n var i = 0\n var maxLen = 0\n var best = \"\"\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n while (i < n) {\n i += 1\n var j = 0\n while (j < n) {\n j += 1\n val cc = if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1).toShort\n else if (c(i - 1)(j) >= c(i)(j - 1)) c(i - 1)(j)\n else c(i)(j - 1)\n c(i)(j) = cc\n if (cc > maxLen) {\n maxLen = cc\n best = lcs_print(i, j).toString\n }\n /*if (maxLen == 100) {\n i = n + 1\n j = n + 1\n }*/\n }\n }\n \n while (best.length > 100) {\n val l = best.length\n if (l % 2 == 1) best = best.take(l / 2) + best.drop(l / 2 + 1)\n else best = best.substring(1, l - 1)\n }\n\n println(best)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(2601)\n val n = s.length\n\n val c = Array.ofDim[Int](n + 2, n + 1)\n\n for (i <- 0 to n) {\n c(i)(0) = 0\n c(n)(i) = 0\n }\n\n def lps_print(l: Int, r: Int): String = {\n if (l > n || r == 0) \"\"\n else if (s(l - 1) == s(r - 1)) (if (l == r) s(l - 1).toString else s(l - 1) + lps_print(l + 1, r - 1) + s(l - 1))\n else if (c(l + 1)(r) >= c(l)(r - 1)) lps_print(l + 1, r)\n else lps_print(l, r - 1)\n }\n\n var maxLen = 0\n var best = \"\"\n\n for (l <- n to 1 by -1; r <- l to n) {\n c(l)(r) = math.max(if (s(l - 1) == s(r - 1)) c(l + 1)(r - 1) + (if (l == r) 1 else 2) else 0,\n \t\t math.max(c(l + 1)(r), c(l)(r - 1)))\n if (c(l)(r) > maxLen) {\n maxLen = c(l)(r)\n best = lps_print(l, r)\n if (maxLen == 100) {\n println(best)\n exit\n }\n }\n }\n println(best)\n// for (i <- maxLen to n; j <- maxLen to n; if c(i)(j) == maxLen) {\n// var candidate = lcs_print(i, j).toString\n// if (candidate.equals(candidate.reverse)) {\n// while (candidate.length > 100) {\n// val l = candidate.length\n// if (l % 2 == 1) candidate = candidate.take(l / 2) + candidate.drop(l / 2 + 1)\n// else candidate = candidate.substring(1, l - 1)\n// }\n// println(candidate)\n// exit\n// }\n// }\n\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(3000)\n val n = s.length\n val nn = n \n\n val c = Array.ofDim[Short](nn + 1, nn + 1)\n\n for (i <- 0 to nn) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n var i = 0\n var maxLen = 0\n var best = \"\"\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n while (i < nn) {\n i += 1\n var j = 0\n while (j < nn) {\n j += 1\n val cc = if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1).toShort\n else if (c(i - 1)(j) >= c(i)(j - 1)) c(i - 1)(j)\n else c(i)(j - 1)\n c(i)(j) = cc\n if (cc <= 100 && cc > maxLen) {\n val candidate = lcs_print(i, j).toString\n if (cc < 100 || candidate.equals(candidate.reverse)) {\n maxLen = cc\n best = candidate\n }\n }\n if (maxLen == 100) {\n println(best.length)\n exit\n }\n }\n }\n\n println(best)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(2601)\n val n = s.length\n\n val c = Array.fill(n + 2, n + 1)(0)\n\n def lps_print(l: Int, r: Int): String = {\n if (l > r) \"\" \n else if (l == r) s(l - 1).toString \n else if (s(l - 1) == s(r - 1)) s(l - 1) + lps_print(l + 1, r - 1) + s(l - 1)\n else if (c(l + 1)(r) >= c(l)(r - 1)) lps_print(l + 1, r)\n else lps_print(l, r - 1)\n }\n\n var maxLen = 0\n var best = \"\"\n\n for (l <- n to 1 by -1; r <- l to n) {\n c(l)(r) = math.max(if (s(l - 1) == s(r - 1)) c(l + 1)(r - 1) + (if (l == r) 1 else 2) else 0,\n \t\t math.max(c(l + 1)(r), c(l)(r - 1)))\n if (c(l)(r) > maxLen) {\n maxLen = c(l)(r)\n best = lps_print(l, r)\n if (maxLen == 100) {\n println(best)\n exit\n }\n }\n }\n \n println(best)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(2601)\n val n = s.length\n\n val c = Array.ofDim[Int](n + 2, n + 1)\n\n for (i <- 0 to n) {\n c(i)(0) = 0\n c(n)(i) = 0\n }\n\n def lps_print(l: Int, r: Int): String = {\n if (l > n || r == 0) \"\"\n else if (s(l - 1) == s(r - 1)) (if (l == r) s(l - 1).toString else s(l - 1) + lps_print(l + 1, r - 1) + s(l - 1))\n else if (c(l + 1)(r) >= c(l)(r - 1)) lps_print(l + 1, r)\n else lps_print(l, r - 1)\n }\n\n var maxLen = 0\n var best = \"\"\n\n for (l <- n to 1 by -1; r <- l to n) {\n c(l)(r) = math.max(if (s(l - 1) == s(r - 1)) c(l + 1)(r - 1) + (if (l == r) 1 else 2) else 0,\n \t\t math.max(c(l + 1)(r), c(l)(r - 1)))\n if (c(l)(r) > maxLen) {\n maxLen = c(l)(r)\n best = lps_print(l, r)\n }\n }\n println(best)\n// for (i <- maxLen to n; j <- maxLen to n; if c(i)(j) == maxLen) {\n// var candidate = lcs_print(i, j).toString\n// if (candidate.equals(candidate.reverse)) {\n// while (candidate.length > 100) {\n// val l = candidate.length\n// if (l % 2 == 1) candidate = candidate.take(l / 2) + candidate.drop(l / 2 + 1)\n// else candidate = candidate.substring(1, l - 1)\n// }\n// println(candidate)\n// exit\n// }\n// }\n\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(3000)\n val n = s.length\n val nn = n // 2 + 2\n\n val c = Array.ofDim[Short](nn + 1, nn + 1)\n\n for (i <- 0 to nn) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n var i = 0\n var maxLen = 0\n var best = \"\"\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n while (i < nn) {\n i += 1\n var j = 0\n while (j < nn) {\n j += 1\n val cc = if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1).toShort\n else if (c(i - 1)(j) >= c(i)(j - 1)) c(i - 1)(j)\n else c(i)(j - 1)\n c(i)(j) = cc\n if (cc > maxLen) {\n maxLen = cc\n best = lcs_print(i, j).toString\n }\n if (maxLen >= 100) {\n i = nn + 1\n j = nn + 1\n }\n }\n }\n\n println(best)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString //.take(3000)\n val n = s.length\n val nn = n // 2 + 2\n\n val c = Array.ofDim[Short](nn + 1, nn + 1)\n\n for (i <- 0 to nn) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n var i = 0\n var maxLen = 0\n var best = \"\"\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n while (i < nn) {\n i += 1\n var j = 0\n while (j < nn) {\n j += 1\n val cc = if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1).toShort\n else if (c(i - 1)(j) >= c(i)(j - 1)) c(i - 1)(j)\n else c(i)(j - 1)\n c(i)(j) = cc\n if (cc > maxLen) {\n maxLen = cc\n best = lcs_print(i, j).toString\n }\n if (maxLen >= 100) {\n i = nn + 1\n j = nn + 1\n }\n }\n }\n\n println(best)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(3000)\n val n = s.length\n\n val c = Array.ofDim[Short](n + 1, n + 1)\n\n for (i <- 0 to n) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n var i = 0\n var maxLen = 0\n var best = \"\"\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n while (i < n) {\n i += 1\n var j = 0\n while (j < n) {\n j += 1\n val cc = if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1).toShort\n else if (c(i - 1)(j) >= c(i)(j - 1)) c(i - 1)(j)\n else c(i)(j - 1)\n c(i)(j) = cc\n if (cc > maxLen) {\n maxLen = cc\n best = lcs_print(i, j).toString\n }\n /*if (maxLen == 100) {\n i = n + 1\n j = n + 1\n }*/\n }\n }\n \n while (best.length > 100) {\n val l = best.length\n if (l % 2 == 1) best = best.take(l / 2) + best.drop(l / 2 + 1)\n else best = best.substring(2, l - 2)\n }\n\n println(best)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(3000)\n val n = s.length\n\n val c = Array.ofDim[Short](n + 1, n + 1)\n\n for (i <- 0 to n) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n var maxLen = 0\n\n for (i <- 1 until n; j <- 1 until n) {\n val cc = if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1).toShort\n else if (c(i - 1)(j) >= c(i)(j - 1)) c(i - 1)(j)\n else c(i)(j - 1)\n c(i)(j) = cc\n if (cc > maxLen) maxLen = cc\n }\n\n for (i <- maxLen until n; j <- maxLen until n; if c(i)(j) == maxLen) {\n var candidate = lcs_print(i, j).toString\n if (candidate.equals(candidate.reverse)) {\n while (candidate.length > 100) {\n val l = candidate.length\n if (l % 2 == 1) candidate = candidate.take(l / 2) + candidate.drop(l / 2 + 1)\n else candidate = candidate.substring(1, l - 1)\n }\n println(candidate)\n exit\n }\n }\n\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString//.take(3000)\n val n = s.length\n val nn = n \nif (s(0) == 'v') {\n println(n)\n exit\n}\n val c = Array.ofDim[Short](nn + 1, nn + 1)\n\n for (i <- 0 to nn) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n var i = 0\n var maxLen = 0\n var best = \"\"\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n while (i < nn) {\n i += 1\n var j = 0\n while (j < nn) {\n j += 1\n val cc = if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1).toShort\n else if (c(i - 1)(j) >= c(i)(j - 1)) c(i - 1)(j)\n else c(i)(j - 1)\n c(i)(j) = cc\n if (cc <= 100 && cc > maxLen) {\n val candidate = lcs_print(i, j).toString\n if (cc < 100 || candidate.equals(candidate.reverse)) {\n maxLen = cc\n best = candidate\n }\n }\n if (maxLen == 100) {\n println(best)\n exit\n }\n }\n }\n\n println(best)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(3000)\n val n = s.length\n val nn = n // 2 + 2\n\n val c = Array.ofDim[Short](nn + 1, nn + 1)\n\n for (i <- 0 to nn) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n var i = 0\n var maxLen = 0\n var best = \"\"\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n while (i < nn) {\n i += 1\n var j = 0\n while (j < nn) {\n j += 1\n val cc = if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1).toShort\n else if (c(i - 1)(j) >= c(i)(j - 1)) c(i - 1)(j)\n else c(i)(j - 1)\n c(i)(j) = cc\n if (cc <= 100 && cc > maxLen) {\n val candidate = lcs_print(i, j).toString\n if (cc < 100 || candidate.equals(candidate.reverse)) {\n maxLen = cc\n best = candidate\n }\n }\n if (maxLen == 100) {\n i = nn + 1\n j = nn + 1\n }\n }\n }\n\n println(best)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString.take(2601)\n val n = s.length\n\n val c = Array.fill(n + 2, n + 1)(0)\n\n def lps_print(l: Int, r: Int): String = {\n if (l > r) \"\" \n else if (l == r) s(l - 1).toString \n else if (s(l - 1) == s(r - 1)) s(l - 1) + lps_print(l + 1, r - 1) + s(l - 1)\n else if (c(l + 1)(r) >= c(l)(r - 1)) lps_print(l + 1, r)\n else lps_print(l, r - 1)\n }\n\n var maxLen = 0\n var best = \"\"\n\n for (l <- n to 1 by -1; r <- l to n) {\n c(l)(r) = math.max(if (s(l - 1) == s(r - 1)) c(l + 1)(r - 1) + (if (l == r) 1 else 2) else 0,\n \t\t math.max(c(l + 1)(r), c(l)(r - 1)))\n if (c(l)(r) > maxLen && c(l)(r) <= 100) {\n maxLen = c(l)(r)\n best = lps_print(l, r)\n if (maxLen == 100) {\n println(best)\n exit\n }\n }\n }\n \n println(best)\n}"}, {"source_code": "object B extends App {\n\n def readString = Console.readLine\n\n val s = readString//.take(3000)\n val n = s.length\n val nn = n \nif (s(0) == 'v') {\n println(s.drop(500))\n exit\n}\n val c = Array.ofDim[Short](nn + 1, nn + 1)\n\n for (i <- 0 to nn) {\n c(i)(0) = 0\n c(0)(i) = 0\n }\n\n var i = 0\n var maxLen = 0\n var best = \"\"\n\n def lcs_print(i: Int, j: Int): StringBuilder = {\n if (i == 0 || j == 0) new StringBuilder()\n else if (s(i - 1) == s(n - j)) lcs_print(i - 1, j - 1) + s(i - 1)\n else if (c(i - 1)(j) >= c(i)(j - 1)) lcs_print(i - 1, j)\n else lcs_print(i, j - 1)\n }\n\n while (i < nn) {\n i += 1\n var j = 0\n while (j < nn) {\n j += 1\n val cc = if (s(i - 1) == s(n - j)) (c(i - 1)(j - 1) + 1).toShort\n else if (c(i - 1)(j) >= c(i)(j - 1)) c(i - 1)(j)\n else c(i)(j - 1)\n c(i)(j) = cc\n if (cc <= 100 && cc > maxLen) {\n val candidate = lcs_print(i, j).toString\n if (cc < 100 || candidate.equals(candidate.reverse)) {\n maxLen = cc\n best = candidate\n }\n }\n if (maxLen == 100) {\n println(best)\n exit\n }\n }\n }\n\n println(best)\n}"}], "src_uid": "f6280717d5644db30a1f9b525100b8b5"} {"source_code": "import scala.annotation.tailrec\n\nobject Worms extends App {\n\n import scala.io.StdIn\n\n val n = StdIn.readLine().toInt\n val as = StdIn.readLine().split(' ').map(_.toInt)\n val m = StdIn.readLine().toInt\n val qs = StdIn.readLine().split(' ').map(_.toInt)\n\n Worms(as, qs).solve foreach println\n}\n\ncase class Worms(as: Seq[Int], qs: Seq[Int]) {\n val n = as.length\n\n def solve: Seq[Int] = qs.map(search(_, 1, n))\n\n val accum = as.scanLeft(0)(_+_).toArray\n\n @tailrec\n private[this] def search(x: Int, lo: Int, hi: Int): Int = (lo + hi) / 2 match {\n case _ if lo == hi => lo\n case m if accum(m) < x => search(x, m + 1, hi)\n case m if accum(m) > x => search(x, lo, m)\n case m if accum(m) == x => m\n }\n}", "positive_code": [{"source_code": "object B474 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val ai = readInts(n)\n\n val loc = Array.fill[Int](1000000 + 10)(0)\n var curr = 0\n\n for(i <- 1 to n) {\n for(j <- curr until curr+ai(i-1)) {\n loc(j+1) = i\n }\n curr += ai(i-1)\n }\n\n val Array(m) = readInts(1)\n val qi = readInts(m)\n println(qi.map(loc(_)).mkString(\"\\n\"))\n }\n}"}, {"source_code": "import java.util._\nimport java.io._\nimport java.util\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val worms = new Array[Int](n)\n val left = new Array[Int](n)\n val right = new Array[Int](n)\n worms(0) = nextInt\n left(0) = 1\n right(0) = worms(0)\n for (i <- 1 until n) {\n worms(i) = nextInt\n left(i) = right(i - 1) + 1\n right(i) = worms(i) + right(i - 1)\n }\n// left.foreach(x => out.print(x + \" \"))\n// out.println()\n// right.foreach(x => out.print(x + \" \"))\n// out.println()\n val m = nextInt\n for (i <- 0 until m) {\n val q = nextInt\n val l = Arrays.binarySearch(left, q)\n if (l >= 0) {\n out.println(l + 1)\n } else {\n val ins = -l - 1\n if (ins >= 0 && right(ins - 1) >= q && left(ins - 1) <= q) {\n out.println(ins)\n } else if (ins < n && right(ins) >= q && left(ins) <= q) {\n out.println(ins + 1)\n } else if (ins + 1 < n && right(ins + 1) >= q && left(ins + 1) <= q) {\n out.println(ins + 2)\n }\n }\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "object Main extends App {\n\ndef binary(ds: Array[Long], key: Long): Int = {\n def go(lo: Int, hi: Int): Int = {\n if (lo > hi)\n lo\n else {\n val mid: Int = lo + (hi - lo)/2\n ds(mid) match {\n case mv if (mv == key) => mid\n case mv if (mv < key) => go(mid + 1, hi)\n case _ => go(lo, mid - 1)\n }\n } \n }\n \n go(0, ds.size - 1)\n}\n\n\n\n readLine\n val ass = readLine.split(\" \").map(_.toLong)\n val indexed = ass.scanLeft(0.toLong)(_ + _)\n readLine\n val qs = readLine.split(\" \").map(_.toLong)\n \n qs foreach {el => println(binary(indexed, el))}\n}"}, {"source_code": "import scala.io.StdIn._\nimport scala.annotation.tailrec\n\nobject Main extends App {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt).scanLeft(1)(_ + _)\n val m = readInt()\n val q = readLine().split(\" \").map(x => binarySearch(a, x.toInt) + 1)\n q.foreach(println)\n \n def binarySearch(a: Array[Int], x: Int): Int = {\n @tailrec\n def bSearch(lo: Int, hi: Int, idx: Int): Int = {\n if (hi < lo) idx\n else {\n val mid = lo + (hi - lo) / 2\n if (a(mid) <= x) bSearch(mid + 1, hi, mid)\n else bSearch(lo, mid - 1, idx)\n }\n }\n bSearch(0, a.length - 1, -1)\n }\n}"}, {"source_code": "import java.util.Scanner\n\n/** B. Worms\n * http://codeforces.com/problemset/problem/474/B\n *\n * @author Yuichiroh Matsubayashi\n * Created on 15/01/19.\n */\nobject P474B extends App {\n val in = new Scanner(Console.in)\n\n val n = in.nextInt()\n// val as = Array.fill(n)(in.nextInt())\n\n val q2pile = (1 to n).flatMap(i => Array.fill(in.nextInt())(i))\n\n val m = in.nextInt()\n\n def solution = (1 to m).map(i => q2pile(in.nextInt() - 1))\n\n println(solution.mkString(\"\\n\"))\n}"}, {"source_code": "import java.util.StringTokenizer\n\nimport scala.Array.canBuildFrom\n\nobject _474B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt).toArray\n val prefix = a.scanLeft(0)(_ + _).toArray\n\n val builder = new StringBuilder\n for (q <- 1 to next.toInt) {\n val cb = next.toInt\n var left = 0\n var right = prefix.length - 1\n while (left + 1 < right) {\n val mid = (left + right) / 2\n if (prefix(mid) < cb) left = mid\n else right = mid\n }\n builder.append(right)\n builder.append('\\n')\n }\n println(builder.toString)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val piles = in.next().split(\" \").map(_.toInt)\n val m = in.next().toInt\n val worms = in.next().split(\" \").map(_.toInt)\n val sorted = worms.sorted\n val nums = piles.scanLeft(0)(_+_).tail.zipWithIndex\n var i = 0\n var j = 0\n val answer = scala.collection.mutable.Map.empty[Int, Int]\n while (j < m) {\n if (nums(i)._1 < sorted(j))\n i += 1\n else {\n answer += (sorted(j) -> (nums(i)._2 + 1))\n j += 1\n }\n }\n println(worms.map(answer).mkString(\"\\n\"))\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\nobject CF271_2 extends App {\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def binarySearch(a: Array[Long], needle: Int): Int = {\n @tailrec\n def binarySearch(low: Int, high: Int): Int = {\n if (low <= high) {\n val middle = low + (high - low) / 2\n\n if (a(middle) == needle)\n middle\n else if (a(middle) < needle)\n binarySearch(middle + 1, high)\n else\n binarySearch(low, middle - 1)\n } else\n -(low + 1)\n }\n binarySearch(0, a.length - 1)\n }\n\n val Array(n) = readInts(1)\n val a = readInts(n)\n val Array(m) = readInts(1)\n val juicyWorms = readInts(m)\n\n val cumA = Array.ofDim[Long](n)\n\n var cumsum = 0\n for(i <- 0 until n) {\n cumsum += a(i)\n cumA(i) = cumsum\n }\n\n for(juicyWorm <- juicyWorms) {\n val v = binarySearch(cumA, juicyWorm)\n if(v>=0) {\n println(v + 1)\n } else {\n println(-v)\n }\n\n }\n}\n"}], "negative_code": [{"source_code": "import annotation.tailrec\nimport util.Try\nobject Main extends App{\n\ndef exitWithError(msg:String) = { Console.err.println(msg); sys.exit(1) }\n\ndef readInt = Try(readLine.toInt)\n\ndef readNInt = Try(readLine split \" \" filter {!_.isEmpty} map {_.toInt})\n\ndef n = readInt getOrElse exitWithError(\"\")\ndef ai = readNInt getOrElse exitWithError(\"\")\ndef m = readInt getOrElse exitWithError(\"\")\ndef qi = readNInt getOrElse exitWithError(\"\")\n\nval pileRanges = {\n @tailrec def ranges(start:Int, iseq:Seq[Int], accu:Seq[Range]):Seq[Range] = \n if (iseq.isEmpty) accu else{\n val limit = start+iseq.head\n ranges(limit, iseq.tail, accu ++ Seq(start until limit))\n }\n\n ranges(1, ai, Seq.empty)\n}\n\nval wormIndices = qi\nval result = wormIndices map { wi => pileRanges.indexWhere(_.contains(wi))+1 }\nprintln(result mkString \"\\n\") \n\n}"}, {"source_code": "object B474 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val ai = readInts(n)\n\n val loc = Array.fill[Int](1000000 + 10)(0)\n var curr = 0\n\n for(i <- 1 to n) {\n for(j <- curr to curr+ai(i-1)) {\n loc(j) = i\n }\n curr += ai(i-1)\n }\n\n val Array(m) = readInts(1)\n val qi = readInts(m)\n println(qi.map(loc(_)).mkString(\"\\n\"))\n }\n}"}, {"source_code": "import java.util._\nimport java.io._\nimport java.util\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val worms = new Array[Int](n)\n val left = new Array[Int](n)\n val right = new Array[Int](n)\n worms(0) = nextInt\n left(0) = 1\n right(0) = worms(0)\n for (i <- 1 until n) {\n worms(i) = nextInt\n left(i) = right(i - 1) + 1\n right(i) = worms(i) + right(i - 1)\n }\n left.foreach(x => out.print(x + \" \"))\n out.println()\n right.foreach(x => out.print(x + \" \"))\n out.println()\n val m = nextInt\n for (i <- 0 until m) {\n val q = nextInt\n val l = Arrays.binarySearch(left, q)\n if (l >= 0) {\n out.println(l + 1)\n } else {\n val ins = -l - 1\n if (ins >= 0 && right(ins - 1) >= q && left(ins - 1) <= q) {\n out.println(ins)\n } else if (ins < n && right(ins) >= q && left(ins) <= q) {\n out.println(ins + 1)\n } else if (ins + 1 < n && right(ins + 1) >= q && left(ins + 1) <= q) {\n out.println(ins + 2)\n }\n }\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "src_uid": "10f4fc5cc2fcec02ebfb7f34d83debac"} {"source_code": "object Solution {\n \n def main(args: Array[String]) {\n val input = readLine.split(\" \").map(_ toInt)\n val n = input(0)\n var (a,b) = (input(1), input(2))\n println(readLine.scanLeft('*')((f,s) => {\n if(s == '*' || a == 0 && b == 0)'*'\n else if(f == 'A' && b != 0){b-=1; 'B'}\n else if(f == 'B' && a != 0){a-=1; 'A'}\n else if(f == '*'){if(a > b){a-=1;'A'}else{b-=1;'B'}}\n else '*'\n }).count(_!='*'))\n \n }\n}\n", "positive_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val r = new Reader\n val n, sp, sa = r.read[Int]\n val s = r.read[String].toList.group(_ == _).filter(x => x.head == '.').map(_.length)\n \n val res = s.foldLeft((0, sp, sa)) {\n case ((res, sp1, sa1), x) => {\n val x2 = x/2\n val x21 = x/2 + 1\n val sp2e = sp1.min(x2)\n val sp2o = sp1.min(x21)\n val sa2e = sa1.min(x2)\n val sa2o = sa1.min(x21)\n \n if (x % 2 == 0) {\n (res + sp2e + sa2e, sp1 - sp2e, sa1 - sa2e)\n } else if (sp1 > sa1) {\n (res + sp2o + sa2e, sp1 - sp2o, sa1 - sa2e)\n } else {\n (res + sp2e + sa2o, sp1 - sp2e, sa1 - sa2o)\n }\n }\n }._1\n \n println(res)\n }\n\n implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)\n\n class ExtendedList[A](xs: List[A]) {\n def group(g: (A, A) => Boolean) =\n xs.foldRight(List[List[A]]()) {\n case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs\n case (x, _) => List(List(x))\n } \n }\n}\n\nimport java.io.{ BufferedReader, InputStreamReader }\nimport java.util.StringTokenizer\n\nclass Reader(br: BufferedReader) {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n def this() = this(new InputStreamReader(System.in))\n\n def read[A](implicit read: Reader.Read[A]): A = read.apply(this)\n\n val tokenizer = new Tokenizer(br)\n}\n\nobject Reader {\n class Read[A](val apply: Reader => A) {}\n\n object Read {\n implicit val string: Read[String] = new Read(_.tokenizer.next)\n implicit val int: Read[Int] = new Read(_.read[String].toInt)\n implicit val long: Read[Long] = new Read(_.read[String].toLong)\n implicit val double: Read[Double] = new Read(_.read[String].toDouble)\n\n implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n\n import scala.collection.generic.CanBuildFrom\n\n // what the f*ck??\n implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =\n new Read(r => Iterator.continually(r.read[A]).take(n).to[T])\n }\n}\n\nclass Tokenizer(br: BufferedReader) extends Iterator[String] {\n def this(isr: InputStreamReader) = this(new BufferedReader(isr))\n\n def hasNext = hasMoreTokens || {\n if (tokenizers.hasNext) {\n tokenizers.next()\n hasMoreTokens\n } else false\n }\n\n def next() = if (hasNext) { tokenizers.head.nextToken } else null\n\n private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens).getOrElse(false)\n\n private val tokenizers =\n Iterator.continually(br.readLine).takeWhile(_ != null).filter(_ != \"\").map(new StringTokenizer(_)).buffered\n}"}, {"source_code": "object Solution {\n \n def main(args: Array[String]) {\n val input = readLine.split(\" \").map(_ toInt)\n val n = input(0)\n var (a,b) = (input(1), input(2))\n var ans = 0\n readLine.foldLeft('*')((f,s) => {\n if(s == '*' || a == 0 && b == 0)'*'\n else if(f == 'A' && b != 0){b-=1;ans+=1; 'B'}\n else if(f == 'B' && a != 0){a-=1;ans+=1; 'A'}\n else if(f == '*'){if(a > b){a-=1;ans+=1;'A'}else{b-=1;ans+=1;'B'}}\n else '*'\n })\n println(ans)\n \n }\n}\n"}], "negative_code": [], "src_uid": "6208dbdf9567b759b0026db4af4545a9"} {"source_code": "import scala.io.StdIn._\n\nobject C_1200 extends App {\n def gcd(a: Long, b: Long): Long = {\n var aa = a\n var bb = b\n\n while (true) {\n if (bb == 0) return aa\n val m = aa % bb\n aa = bb\n bb = m\n }\n\n 1\n }\n\n val Array(n, m, q) = readLine().split(\" \").map(_.toLong)\n val g = gcd(n, m)\n\n def pivot1(i: Long) = {\n if (i == 0) 0L\n else if (i % (n / g) == 0) i / (n / g) - 1\n else i / (n / g)\n }\n\n def pivot2(i: Long) = {\n if (i == 0) 0L\n else if (i % (m / g) == 0) i / (m / g) - 1\n else i / (m / g)\n }\n\n 1 to q.toInt foreach { _ =>\n val Array(sx, sy, ex, ey) = readLine().split(\" \").map(_.toLong)\n if (g <= 1) println(\"YES\")\n else {\n val r1 = if (sx == 1) {\n pivot1(sy)\n } else {\n pivot2(sy)\n }\n\n val r2 = if (ex == 1) {\n pivot1(ey)\n } else {\n pivot2(ey)\n }\n\n println(\n if (r1 == r2) \"YES\" else \"NO\"\n )\n }\n }\n\n}\n", "positive_code": [{"source_code": "object C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, m, q) = readLongs(3)\n\n def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)\n\n val g = gcd(n, m)\n val g1 = n / g\n val g2 = m / g\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (_ <- 1 to q.toInt) {\n val Array(sx, sy, ex, ey) = readLongs(4)\n val s = if (sx == 1) BigInt(sy - 1) * g2 / g1 else BigInt(sy - 1)\n val e = if (ex == 1) BigInt(ey - 1) * g2 / g1 else BigInt(ey - 1)\n val can = s / g2 == e / g2\n println(if (can) \"YES\" else \"NO\")\n }\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject C_1200 extends App {\n def gcd(a: Long, b: Long): Long = {\n var aa = a\n var bb = b\n\n while (true) {\n if (bb == 0) return aa\n val m = aa % bb\n aa = bb\n bb = m\n }\n\n 1\n }\n\n val Array(n, m, q) = readLine().split(\" \").map(_.toLong)\n val g = gcd(n, m)\n val pivot1 = n / g\n val pivot2 = m / g\n println(pivot1)\n println(pivot2)\n\n 1 to q.toInt foreach { _ =>\n val Array(sx, sy, ex, ey) = readLine().split(\" \").map(_.toLong)\n if (g <= 1) println(\"YES\")\n else {\n val r1 = if (sx == 1) {\n sy <= pivot1\n } else {\n sy <= pivot2\n }\n\n val r2 = if (ex == 1) {\n ey <= pivot1\n } else {\n ey <= pivot2\n }\n\n println(\n if (r1 == r2) \"YES\" else \"NO\"\n )\n }\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C_1200 extends App {\n def gcd(a: Long, b: Long): Long = {\n var aa = a\n var bb = b\n\n while (true) {\n if (bb == 0) return aa\n val m = aa % bb\n aa = bb\n bb = m\n }\n\n 1\n }\n\n val Array(n, m, q) = readLine().split(\" \").map(_.toLong)\n val g = gcd(n, m)\n val pivot1 = n / g\n val pivot2 = m / g\n\n 1 to q.toInt foreach { _ =>\n val Array(sx, sy, ex, ey) = readLine().split(\" \").map(_.toLong)\n if (g <= 1) println(\"YES\")\n else {\n val r1 = if (sx == 1) {\n sy <= pivot1\n } else {\n sy <= pivot2\n }\n\n val r2 = if (ex == 1) {\n ey <= pivot1\n } else {\n ey <= pivot2\n }\n\n println(\n if (r1 == r2) \"YES\" else \"NO\"\n )\n }\n }\n\n}\n"}], "src_uid": "d4ae071cf261ec3d91187a9a7dddcda0"} {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n case class Pair(x: Int, y: Int)\n val Max = 1000000\n val A = Array.ofDim[Pair](Max + 1)\n\n val n = readLine().toInt\n\n for (i <- 2 to 2 * n) {\n val values = readLine().split(\" \").map(_.toInt)\n for (j <- 1 to i - 1) {\n update(i, j, values(j - 1))\n }\n }\n\n def update(x: Int, y: Int, power: Int): Unit = {\n// println(s\"update $x $y $power\")\n A(power) = Pair(x, y)\n }\n\n var counter = 1\n var i = Max\n val choice = Array.ofDim[Int](2 * n + 1)\n val marker = Array.ofDim[Boolean](Max + 1)\n\n while (counter <= n) {\n if (A(i) != null && (!marker(A(i).x) && !marker(A(i).y))) {\n// println(\"consider \" + A(i))\n val curr = A(i)\n choice(curr.x) = curr.y\n choice(curr.y) = curr.x\n marker(curr.x) = true\n marker(curr.y) = true\n counter += 1\n }\n i -= 1\n }\n\n println(choice.drop(1).mkString(\" \"))\n}\n", "positive_code": [{"source_code": "//package round320.b\n\nimport java.util.Scanner\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n val t = Array.fill(2*n+1)(0)\n val as = Array.ofDim[(Int, Int, Int)](n * (2*n-1))\n var ii = 0\n for(i <- 2 to 2*n; j <- 1 until i) {\n val aij = sc.nextInt\n as(ii) = (aij, i, j)\n ii += 1\n }\n\n val as2 = as.sorted\n ii -= 1\n\n var pairs = 0\n while(pairs < n) {\n val (_, i, j) = as2(ii)\n if(t(i) == 0 && t(j) == 0) {\n t(i) = j\n t(j) = i\n pairs += 1\n }\n ii -= 1\n }\n\n for(i <- 1 to 2*n) {\n print(t(i))\n print(\" \")\n }\n\n println()\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n var data = (2 to 2 * n).flatMap { i =>\n in.next().split(\" \").map(_.toInt).zipWithIndex.map{\n case(el, index) => (i, index + 1, el)\n }\n }.sortBy(_._3).reverse\n val result = Array.fill(2 * n){ 0 }\n\n while (data.nonEmpty) {\n val max = data.head\n if (result(max._1 - 1) == 0 && result(max._2 - 1) == 0) {\n result(max._1 - 1) = max._2\n result(max._2 - 1) = max._1\n }\n data = data.tail\n }\n println(result.mkString(\" \"))\n}"}], "negative_code": [], "src_uid": "8051385dab9d7286f54fd332c64e836e"} {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 1 to t) {\n val _ = StdIn.readLine().trim.toInt\n val xs = StdIn.readLine().split(\" \").map(_.toInt).sorted\n val s = xs.toSet\n val xs1 = xs.distinct\n var res = 0\n for (i <- xs.indices) {\n for (j <- xs.indices.reverse by -1 if i < j) {\n val w = xs(i) + xs(j)\n var (ii, jj) = (i, j)\n var temp = 0\n while (ii < jj) {\n val target = xs(ii) + xs(jj)\n if (target == w) {\n temp += 1; ii += 1; jj -= 1;\n } else if (target < w) ii += 1\n else jj -= 1\n }\n res = res max temp\n }\n }\n println(res)\n }\n }\n}\n", "positive_code": [{"source_code": "import java.lang.Math._\n\nimport scala.io.Source\n\nobject BoatsCompetition1399C extends App {\n\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n// val lines: Iterator[String] =\n// Source.fromString(\"5\\n5\\n1 2 3 4 5\\n8\\n6 6 6 6 6 6 8 8\\n8\\n1 2 2 1 2 1 1 2\\n3\\n1 3 3\\n6\\n1 1 3 4 2 2\").getLines\n val ntc: Int = lines.next.toInt\n 0 until ntc map { _ =>\n handleTC()\n } foreach println\n\n def handleTC() = {\n val prts = lines.next.toInt\n if (prts == 1) {\n lines.next\n 0\n } else if (prts <= 3) {\n lines.next\n 1\n } else {\n val ws = lines.next.split(\" \").map(_.toInt)\n solve(ws)\n }\n }\n\n def solve(ws: Array[Int]) = {\n val counts = ws.groupBy(identity).map { case (k, v) => k -> v.length }\n (for (s <- 2 * ws.min to 2 * ws.max) yield\n (for (i <- max(ws.min, s - ws.max) to s / 2) yield {\n val ic = counts.getOrElse(i, 0)\n if (ic == 0) 0\n else if (i != s - i)\n min(ic, counts.getOrElse(s - i, 0))\n else ic / 2\n }).sum).max\n }\n}\n"}, {"source_code": "//package codeforces.contests._1399\n\nobject BoatsCompetition {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val n = io.StdIn.readInt()\n val a = io.StdIn.readLine.split(\" \").map(_.toInt).sorted\n\n if (n >= 2) {\n val wF = new Array[Int](n + 1)\n a.foreach(wF(_) += 1)\n\n val ans = (2 to 2 * n).map { s =>\n\n (1 to ((s - 1) min n)).foldLeft(0)((acc, w1) => acc + {\n val w2 = s - w1\n if (w2 <= n && w1 <= w2) (if (w1 < w2) wF(w1) min wF(w2) else wF(w1) / 2) else 0\n })\n\n }\n\n println(ans.max)\n } else println(0)\n }\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1399\n\nobject BoatsCompetition {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val n = io.StdIn.readInt()\n val a = io.StdIn.readLine.split(\" \").map(_.toInt).sorted\n\n var ans = Int.MinValue\n\n for {\n i <- 0 until n\n j <- i + 1 until n\n s = a(i) + a(j)\n result = {\n var ii = i\n var jj = j\n\n var count = 0\n while (ii < jj) {\n if (a(ii) + a(jj) == s) count += 1\n ii += 1\n jj -= 1\n }\n\n count\n }\n } ans = ans max result\n\n println(ans)\n }\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject BoatsCompetition1399C extends App {\n\n val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n// val lines: Iterator[String] =\n// Source.fromString(\"5\\n5\\n1 2 3 4 5\\n8\\n6 6 6 6 6 6 8 8\\n8\\n1 2 2 1 2 1 1 2\\n3\\n1 3 3\\n6\\n1 1 3 4 2 2\").getLines\n val ntc: Int = lines.next.toInt\n 0 until ntc map { _ =>\n handleTC()\n } foreach println\n\n def handleTC() = {\n val prts = lines.next.toInt\n if (prts == 1) {\n lines.next\n 0\n } else if (prts <= 3) {\n lines.next\n 1\n } else {\n val ws = lines.next.split(\" \").map(_.toInt).sorted\n solve(ws, Array())\n }\n }\n\n def solve(ws: Array[Int], solutio: Array[Int]): Int = {\n if (ws.length < 2) compute(solutio)\n else ws.tail.zipWithIndex.map { case (_, ind) =>\n val updWs = ws.tail.take(ind - 1) ++ ws.tail.drop(ind)\n \n solve(updWs, solutio ++ Array(ws.head + ws.tail(ind)))\n }.max\n }\n\n def compute(sol: Array[Int]): Int = {\n sol.groupBy(identity).values.map(_.length).max\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject BoatsCompetition1399C extends App {\n\n// val lines: Iterator[String] = Source.fromInputStream(System.in).getLines\n val lines: Iterator[String] =\n Source.fromString(\"5\\n5\\n1 2 3 4 5\\n8\\n6 6 6 6 6 6 8 8\\n8\\n1 2 2 1 2 1 1 2\\n3\\n1 3 3\\n6\\n1 1 3 4 2 2\").getLines\n val ntc: Int = lines.next.toInt\n 0 until ntc map { _ =>\n handleTC()\n } foreach println\n\n def handleTC() = {\n val prts = lines.next.toInt\n if (prts == 1) {\n lines.next\n 0\n } else if (prts <= 3) {\n lines.next\n 1\n } else {\n val ws = lines.next.split(\" \").map(_.toInt).sorted\n solve(ws, Array())\n }\n }\n\n def solve(ws: Array[Int], solutio: Array[Int]): Int = {\n if (ws.length < 2) compute(solutio)\n else ws.tail.zipWithIndex.map { case (_, ind) =>\n val updWs = ws.tail.take(ind) ++ ws.tail.drop(ind+1)\n\n solve(updWs, solutio ++ Array(ws.head + ws.tail(ind)))\n }.max\n }\n\n def compute(sol: Array[Int]): Int = {\n sol.groupBy(identity).values.map(_.length).max\n }\n}\n"}], "src_uid": "0048623eeb27c6f7c6900d8b6e620f19"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, k, l, r, sAll, sK) = in.next().split(' ').map(_.toInt)\n val answer = Array.ofDim[Int](n)\n val m = sK / k\n val left = sK % k\n (0 until left).foreach(i => answer(i) = m + 1)\n (left to k - 1).foreach(i => answer(i) = m)\n if (k != n) {\n val m1 = (sAll - sK) / (n - k)\n val left1 = (sAll - sK) % (n - k)\n (k until k + left1).foreach(i => answer(i) = m1 + 1)\n (k + left1 to n - 1).foreach(i => answer(i) = m1)\n }\n println(answer.mkString(\" \"))\n\n}\n", "positive_code": [{"source_code": "object HelloWorld {\n def main(args:Array[String]){\n var Array(n,k,l,r,sall,sk)=readLine().split(\" \").map(_.toInt)\n var array=Array.fill(n)(l)\n var pos=0\n\n var ka:Int=sk/k\n var kb:Int=sk%k\n \n for(i<-0 to kb-1){\n array(i)=ka+1\n }\n for(i<-kb to k-1){\n array(i)=ka\n }\n if(n!=k)\n {\n var la:Int=(sall-sk)/(n-k)\n var lb:Int=(sall-sk)%(n-k)\n for(i<-k to k+lb-1){\n array(i)=la+1\n }\n for(i<-k+lb to n-1){\n array(i)=la\n }\n }\n println(array.mkString(\" \"))\n }\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, k, l, r, sAll, sK) = in.next().split(' ').map(_.toInt)\n val answer = Array.ofDim[Int](n)\n val m = sK / k\n val left = sK % k\n (0 until left).foreach(i => answer(i) = m + 1)\n (left to k - 1).foreach(i => answer(i) = m)\n if (k <= n - 2) {\n val m = (sAll - sK) / (n - k)\n val left = (sAll - sK) % (n - k)\n (k until k + left).foreach(i => answer(i) = m + 1)\n (k + left to n - 1).foreach(i => answer(i) = m)\n }\n println(answer.mkString(\" \"))\n\n}\n"}], "src_uid": "59154ca15716f0c1c91a37d34c5bbf1d"} {"source_code": "\nimport java.io.InputStreamReader\nimport java.io.BufferedReader\n\n/**\n * @author pvasilyev\n * @since 25 Jun 2016\n */\nobject A222 extends App {\n\n def solve() = {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val Array(n, k) = reader.readLine().split(\" \").map(_.toInt)\n val a: Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n\n var c = 0\n var eq = true\n for (i <- k - 1 until n) {\n if (c == 0) {\n c = a(i)\n } else if (c != a(i)) {\n eq = false\n }\n }\n\n if (!eq) {\n println(\"-1\")\n } else {\n\n var index = k - 1\n for (i <- (k - 1).until(0, -1)) {\n\n if (eq) {\n if (a(index - 1) == a(i)) {\n index -= 1\n } else {\n eq = false\n }\n }\n }\n\n println(index)\n }\n }\n\n solve()\n\n}\n", "positive_code": [{"source_code": "object test5 extends App {\n val Array(n,k)=readLine.split(' ').map(_.toInt)\n val arr=readLine.split(' ').map(_.toInt)\n if(arr.slice(k-1,n).distinct.size>1)\n {\n \tprintln(-1)\n }\n else\n {\n \tdef find(i:Int):Int=i match{\n \t\tcase -1=> 0\n \t\tcase _ if arr(i)==arr(k-1)=>find(i-1)\n \t\tcase _=>i+1\n \t}\n\n println(find(k-2))\n }\n} \n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val nk = readLine().split(\" \").map(_.toInt)\n val a = readLine().split(\" \").map(_.toInt)\n val n = nk(0)\n val k = nk(1)\n \n if (a.drop(k - 1).toSet.size != 1) println(\"-1\")\n else {\n val e = a(k - 1)\n val c = a.take(k - 1).reverse.takeWhile(_ == e).size\n println(k - c - 1)\n }\n }\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt)\n val lastIndex = (n - 2 to 0 by -1).find(i => data(i) != data.last)\n if (lastIndex.isEmpty)\n println(0)\n else if (lastIndex.get + 1 >= k)\n println(-1)\n else\n println(lastIndex.get + 1)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P222A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, K = sc.nextInt\n val a = List.fill(N)(sc.nextInt)\n\n val n = a(K - 1)\n val i = a.lastIndexWhere(_ != n)\n val answer = if (i > K - 1) -1\n else i + 1\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n def readLine = reader.readLine\n\n val Array(n, k) = readInts\n val a = readInts\n def cnt = a.drop(k - 1).sliding(2).count(x => x.last != x.head)\n def ans = if(cnt == 0) n - a.reverse.takeWhile(_ == a.last).length else -1\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "object test5 extends App {\n val Array(n,k)=readLine.split(' ').map(_.toInt)\n val arr=readLine.split(' ').map(_.toInt)\n if(arr.slice(k-1,n).distinct.size>1)\n {\n \tprintln(-1)\n }\n else\n {\n var i=k-2\n while(i>=0 && arr(i)==arr(i+1))\n \ti-=1\n println(i+1)\n }\n} \n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt)\n val lastIndex = (n - 2 to 0 by -1).find(_ != data.last)\n if (lastIndex.isEmpty)\n println(0)\n else if (lastIndex.get + 1 >= k)\n println(-1)\n else\n println(lastIndex.get + 1)\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P222A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N, K = sc.nextInt\n val a = List.fill(N)(sc.nextInt)\n \n def solve1(): Int = if (a.distinct.size == 1) 0\n else -1\n\n def solveM(): Int = {\n\n @tailrec\n def loop(n: Int, as: List[Int]): Int = {\n if (as.distinct.size == 1) n\n else {\n val (f, r) = as splitAt (K - 1)\n loop(n + 1, f.tail ++ r.tail ++ List(r.head))\n }\n }\n\n loop(0, a)\n }\n\n def solve(): Int = K match {\n case 1 | `N` => solve1\n case _ => solveM\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "\nimport java.io.InputStreamReader\nimport java.io.BufferedReader\n\n/**\n * @author pvasilyev\n * @since 25 Jun 2016\n */\nobject A222 extends App {\n\n def solve() = {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n val Array(n, k) = reader.readLine().split(\" \").map(_.toInt)\n val a: Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n\n var c = 0\n var eq = true\n for (i <- k - 1 until n) {\n if (c == 0) {\n c = a(i)\n } else if (c != a(i)) {\n eq = false\n }\n }\n\n if (!eq) {\n println(\"-1\")\n } else {\n println(k - 1)\n }\n }\n\n solve()\n\n}\n"}, {"source_code": "object test5 extends App {\n val Array(n,k)=readLine.split(' ').map(_.toInt)\n val arr=readLine.split(' ').map(_.toInt)\n if(arr.distinct.size==1)\n {\n \tprintln(0)\n }\n else\n {\n arr(0)=arr(k-1)\n \n if(arr.distinct.size==1)\n \tprintln(1)\n else\n \tprintln(-1)\n }\n} \n"}, {"source_code": "object test5 extends App {\n val Array(n,k)=readLine.split(' ').map(_.toInt)\n val arr=readLine.split(' ').map(_.toInt)\n if(arr.slice(k-1,n).distinct.size>1)\n {\n \tprintln(-1)\n }\n else\n {\n \tdef find(i:Int):Int=i match{\n \t\tcase -1=> 0\n \t\tcase _ if i==arr(k-1)=>find(i-1)\n \t\tcase _=>i+1\n \t}\n\n println(find(k-2))\n }\n} \n"}, {"source_code": "object test5 extends App {\n val Array(n,k)=readLine.split(' ').map(_.toInt)\n val arr=readLine.split(' ').map(_.toInt)\n arr(0)=arr(k-1)\n \n if(arr.distinct.size==1)\n \tprintln(1)\n else\n \tprintln(-1)\n} \n"}], "src_uid": "bcee233ddb1509a14f2bd9fd5ec58798"} {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject P279F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rs = readInts(n)\n\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (i <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adj = adjBuilders.map(_.result)\n\n val minByLen = Array.ofDim[Int](n + 1)\n val as = Array.ofDim[Int](n)\n var max = 0\n\n def dfs(u: Int, prev: Int, depth: Int): Unit = {\n\n as(depth) = rs(u)\n\n var i = 0\n while (i < adj(u).length) {\n val v = adj(u)(i)\n if (v != prev) dfs(v, u, depth + 1)\n i += 1\n }\n\n if (adj(u).length == 1 && depth >= max) {\n\n var len = 0\n\n for (i <- 0 to depth) {\n\n var lo = 1\n var hi = len\n\n while (lo <= hi) {\n val mid = (lo + hi) >> 1\n if (as(minByLen(mid)) < as(i)) lo = mid + 1\n else hi = mid - 1\n }\n\n minByLen(lo) = i\n if (lo > len) len = lo\n }\n\n if (len > max) max = len\n }\n }\n\n for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)\n\n println(max)\n}", "positive_code": [{"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject P279F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rs = readInts(n)\n\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (i <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adj = adjBuilders.map(_.result)\n\n val minByLen = Array.ofDim[Int](n + 1)\n val as = Array.ofDim[Int](n)\n var max = 0\n\n def dfs(u: Int, prev: Int, depth: Int): Unit = {\n\n as(depth) = rs(u)\n\n for (v <- adj(u))\n if (v != prev) dfs(v, u, depth + 1)\n\n if (adj(u).length == 1 && depth >= max) {\n\n var len = 0\n\n for (i <- 0 to depth) {\n\n var lo = 1\n var hi = len\n\n while (lo <= hi) {\n val mid = (lo + hi) >> 1\n if (as(minByLen(mid)) < as(i)) lo = mid + 1\n else hi = mid - 1\n }\n\n minByLen(lo) = i\n if (lo > len) len = lo\n }\n\n if (len > max) max = len\n }\n }\n\n for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)\n\n println(max)\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject P279F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rs = readInts(n)\n\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (i <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adj = adjBuilders.map(_.result)\n\n val minByLen = Array.ofDim[Int](n + 1)\n val as = Array.ofDim[Int](n)\n var max = 0\n\n def dfs(u: Int, prev: Int, depth: Int): Unit = {\n\n as(depth) = rs(u)\n\n var i = 0\n while (i < adj(u).length) {\n val v = adj(u)(i)\n if (v != prev) dfs(v, u, depth + 1)\n i += 1\n }\n\n if (adj(u).length == 1 && depth >= max) {\n\n var i, len = 0\n\n while (i <= depth) {\n\n var lo = 1\n var hi = len\n\n while (lo <= hi) {\n val mid = (lo + hi) >> 1\n if (as(minByLen(mid)) < as(i)) lo = mid + 1\n else hi = mid - 1\n }\n\n minByLen(lo) = i\n if (lo > len) len = lo\n \n i += 1\n }\n\n if (len > max) max = len\n }\n }\n\n for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)\n\n println(max)\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject P279F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rs = readInts(n)\n\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (i <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adj = adjBuilders.map(_.result)\n\n val minByLen = Array.ofDim[Int](n + 1)\n val as = Array.ofDim[Int](n)\n var max = 0\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int, target: Int): Int = {\n if (hi < low) low // not found - return insertion point\n else {\n val mid = (low + hi) >>> 1\n val fmid = minByLen(mid)\n if (fmid == target) mid\n else if (fmid < target) binSearch(mid + 1, hi, target)\n else binSearch(low, mid - 1, target)\n }\n }\n\n def lis(as: Array[Int], limit: Int): Int = {\n\n var len = 0\n\n for (i <- 0 until limit) {\n val a = as(i)\n val j = binSearch(0, len - 1, a)\n if (j == len) {\n minByLen(j) = a\n len += 1\n } else if (a < minByLen(j)) minByLen(j) = a\n }\n\n len\n }\n\n\n def dfs(u: Int, prev: Int, depth: Int): Unit = {\n\n as(depth) = rs(u)\n\n for (v <- adj(u))\n if (v != prev) dfs(v, u, depth + 1)\n\n if (adj(u).length == 1 && depth >= max) max = math.max(max, lis(as, depth + 1))\n }\n\n for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)\n\n println(max)\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject P279F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rs = readInts(n)\n\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (i <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adj = adjBuilders.map(_.result)\n\n val minByLen = Array.ofDim[Int](n + 1)\n val as = Array.ofDim[Int](n)\n var max = 0\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int, target: Int): Int = {\n if (hi < low) low // not found - return insertion point\n else {\n val mid = (low + hi) >>> 1\n val fmid = minByLen(mid)\n if (fmid == target) mid\n else if (fmid < target) binSearch(mid + 1, hi, target)\n else binSearch(low, mid - 1, target)\n }\n }\n\n def lis(as: Array[Int], limit: Int): Int = {\n\n var i, len = 0\n\n while (i < limit) {\n val a = as(i)\n val j = binSearch(0, len - 1, a)\n if (j == len) {\n minByLen(j) = a\n len += 1\n } else if (a < minByLen(j)) minByLen(j) = a\n i += 1\n }\n\n len\n }\n\n\n def dfs(u: Int, prev: Int, depth: Int): Unit = {\n\n as(depth) = rs(u)\n\n var i = 0\n while (i < adj(u).length) {\n val v = adj(u)(i)\n if (v != prev) dfs(v, u, depth + 1)\n i += 1\n }\n\n if (adj(u).length == 1 && depth >= max) max = math.max(max, lis(as, depth + 1))\n }\n\n for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)\n\n println(max)\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject P279F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rs = readInts(n)\n\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (i <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adj = adjBuilders.map(_.result)\n\n val m = Array.ofDim[Int](n + 1)\n val population = Array.ofDim[Int](n)\n var max = 0\n\n def dfs(u: Int, prev: Int, depth: Int): Unit = {\n\n population(depth) = rs(u)\n\n var i = 0\n while (i < adj(u).length) {\n val v = adj(u)(i)\n if (v != prev) dfs(v, u, depth + 1)\n i += 1\n }\n\n if (adj(u).length == 1 && depth >= max) {\n\n var i, len = 0\n\n while (i <= depth) {\n\n var lo = 1\n var hi = len\n\n while (lo <= hi) {\n val mid = (lo + hi) >> 1\n if (population(m(mid)) < population(i)) lo = mid + 1\n else hi = mid - 1\n }\n\n m(lo) = i\n if (lo > len) len = lo\n \n i+= 1\n }\n\n if (len > max) max = len\n }\n }\n\n for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)\n\n println(max)\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject P279F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rs = readInts(n)\n\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (i <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adj = adjBuilders.map(_.result)\n\n val minByLen = Array.ofDim[Int](n)\n val as = Array.ofDim[Int](n)\n var max = 0\n\n def dfs(u: Int, prev: Int, depth: Int): Unit = {\n\n as(depth) = rs(u)\n\n var i = 0\n while (i < adj(u).length) {\n val v = adj(u)(i)\n if (v != prev) dfs(v, u, depth + 1)\n i += 1\n }\n\n if (adj(u).length == 1 && depth >= max) {\n\n var i, len = 0\n\n while (i <= depth) {\n\n var lo = 0\n var hi = len - 1\n\n while (lo <= hi) {\n val mid = (lo + hi) >> 1\n if (as(minByLen(mid)) < as(i)) lo = mid + 1\n else hi = mid - 1\n }\n\n minByLen(lo) = i\n if (lo == len) len += 1\n \n i += 1\n }\n\n if (len > max) max = len\n }\n }\n\n for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)\n\n println(max)\n}"}], "negative_code": [{"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject P279F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rs = readInts(n)\n\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (i <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adj = adjBuilders.map(_.result)\n\n val m = Array.ofDim[Int](n + 1)\n val population = Array.ofDim[Int](n)\n var max = 0\n\n def dfs(u: Int, prev: Int, depth: Int): Unit = {\n\n population(depth) = rs(u)\n\n var i = 0\n while (i < adj(u).length) {\n val v = adj(u)(i)\n if (v != prev) dfs(v, u, depth + 1)\n i += 1\n }\n\n if (adj(u).length == 1 && depth > max) {\n\n var i, len = 0\n\n while (i <= depth) {\n\n var lo = 1\n var hi = len\n\n while (lo <= hi) {\n val mid = (lo + hi) >> 1\n if (population(m(mid)) < population(i)) lo = mid + 1\n else hi = mid - 1\n }\n\n m(lo) = i\n if (lo > len) len = lo\n \n i+= 1\n }\n\n if (len > max) max = len\n }\n }\n\n for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)\n\n println(max)\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject P279F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rs = readInts(n)\n\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (i <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adj = adjBuilders.map(_.result)\n\n val m = Array.ofDim[Int](n + 1)\n val as = Array.ofDim[Int](n)\n var max = 0\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int, f: Int => Int, target: Int): (Boolean, Int) = {\n if (hi < low) (false, low) // not found - return insertion point\n else {\n val mid = (low + hi) >>> 1\n val fmid = f(mid)\n if (fmid == target) (true, mid)\n else if (fmid < target) binSearch(mid + 1, hi, f, target)\n else binSearch(low, mid - 1, f, target)\n }\n }\n\n def lis(as: Array[Int]): Int = {\n\n var len = 0\n for (a <- as) {\n val (_, j) = binSearch(0, len - 1, m, a)\n if (j == len) {\n m(j) = a\n len += 1\n } else if (a < m(j)) m(j) = a\n }\n\n len\n }\n\n def dfs(u: Int, prev: Int, depth: Int): Unit = {\n\n as(depth) = rs(u)\n\n for (v <- adj(u))\n if (v != prev) dfs(v, u, depth + 1)\n\n if (adj(u).length == 1 && depth >= max) max = math.max(max, lis(as))\n }\n\n for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)\n\n println(max)\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject P279F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rs = readInts(n)\n\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (i <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adj = adjBuilders.map(_.result)\n\n val m = Array.ofDim[Int](n + 1)\n val population = Array.ofDim[Int](n)\n var max = 0\n\n def dfs(u: Int, prev: Int, depth: Int, len: Int): Unit = {\n\n population(depth) = rs(u)\n\n var lo = 0\n var hi = len\n\n while (lo <= hi) {\n val mid = (lo + hi) / 2\n if (population(m(mid)) < population(depth)) lo = mid + 1\n else hi = mid - 1\n }\n\n m(lo) = depth\n if (lo > max) max = lo\n\n for (v <- adj(u)) if (v != prev) {\n dfs(v, u, depth + 1, lo)\n }\n }\n\n for (u <- 0 until n) dfs(u, -1, 0, 0)\n\n println(max + 1)\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject P279F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rs = readInts(n)\n\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (i <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adj = adjBuilders.map(_.result)\n\n val m = Array.ofDim[Int](n + 1)\n val population = Array.ofDim[Int](n)\n var max = 0\n\n def dfs(u: Int, prev: Int, depth: Int, len: Int): Unit = {\n population(depth) = rs(u)\n\n var lo = 0\n var hi = len\n\n while (lo <= hi) {\n val mid = (lo + hi) / 2\n if (population(m(mid)) < population(depth)) lo = mid + 1\n else hi = mid - 1\n }\n\n m(lo) = depth\n if (lo > max) max = lo\n\n for (v <- adj(u)) if (v != prev) {\n dfs(v, u, depth + 1, lo max len)\n }\n }\n\n for (u <- 0 until n) dfs(u, -1, 0, 0)\n\n println(max + 1)\n}"}, {"source_code": "import scala.collection._\nimport scala.collection.mutable.ArrayBuilder\n\nobject P279F extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n val Array(n) = readInts(1)\n val rs = readInts(n)\n\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (i <- 1 until n) {\n val Array(u, v) = readInts(2)\n adjBuilders(u - 1) += v - 1\n adjBuilders(v - 1) += u - 1\n }\n\n val adj = adjBuilders.map(_.result)\n\n val m = Array.ofDim[Int](n + 1)\n val population = Array.ofDim[Int](n)\n var max = 0\n\n def dfs(u: Int, prev: Int, depth: Int): Unit = {\n\n population(depth) = rs(u)\n\n var noChildren = true\n for (v <- adj(u)) if (v != prev) {\n dfs(v, u, depth + 1)\n noChildren = false\n }\n\n if (noChildren) {\n var len = 0\n for (i <- 0 until depth) {\n\n var lo = 1\n var hi = len\n\n while (lo <= hi) {\n val mid = (lo + hi) / 2\n if (population(m(mid)) < population(i)) lo = mid + 1\n else hi = mid - 1\n }\n\n m(lo) = i\n if (lo > len) len = lo\n\n }\n\n if (len > max) max = len\n }\n }\n\n for (u <- 0 until n) dfs(u, -1, 0)\n\n println(max + 1)\n}"}], "src_uid": "52f681a64def8f2c73e5ba24ee494293"} {"source_code": "//package codeforces.contests._1374\n\nobject ReadingBookEasy {\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val (aliceL, bobL, bothL) = (1 to n).foldLeft((List.empty[Int], List.empty[Int], List.empty[Int])) {\n case ((alice, bob, both), _) =>\n val Array(time, a, b) = io.StdIn.readLine.split(\" \").map(_.toInt)\n (\n if (a == 1 && b == 0) time :: alice else alice,\n if (a == 0 && b == 1) time :: bob else bob,\n if (a == 1 && b == 1) time :: both else both\n )\n }\n\n val aliceA = aliceL.toArray\n val bobA = bobL.toArray\n val bothA = bothL.toArray\n\n println {\n if (aliceA.length + bothA.length >= k && bobA.length + bothA.length >= k) {\n\n val aliceP = aliceA.sorted.scanLeft(0)(_ + _)\n val bobP = bobA.sorted.scanLeft(0)(_ + _)\n val bothP = bothA.sorted.scanLeft(0)(_ + _)\n\n val i = bothP.indices.minBy { i =>\n if (i > k) Int.MaxValue\n else {\n val r = k - i\n if (r < aliceP.length && r < bobP.length)\n aliceP(r) + bobP(r) + bothP(i)\n else Int.MaxValue\n }\n }\n val r = k - i\n aliceP(r) + bobP(r) + bothP(i)\n } else -1\n }\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new CF653A(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass CF653A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val n = ni()\n val k = ni()\n\n val b = Array.ofDim[Books](n)\n REP(n) { i =>\n b(i) = Books(ni(), ni(), ni())\n }\n\n if(b.count(p => p.a == 1) < k || b.count(p => p.b == 1) < k) {\n out.println(\"-1\")\n } else {\n val c = b.sortBy(f => f.t)\n val lstA = c.filter(p => p.a == 1 && p.b == 0)\n val lstB = c.filter(p => p.a == 0 && p.b == 1)\n val lstC = c.filter(p => p.a == 1 && p.b == 1)\n\n var cst = 0\n var tk = 0\n var idL = 0\n var idT = 0\n\n while (tk < k) {\n val g = if(idL < lstA.length && idL < lstB.length) {\n lstA(idL).t + lstB(idL).t\n } else Int.MaxValue\n\n val h = if(idT < lstC.length) lstC(idT).t else Int.MaxValue\n// out.println(g + \" \" + h)\n if(g < h) {\n cst += g\n idL+=1\n } else {\n cst += h\n idT += 1\n }\n tk += 1\n }\n out.print(cst)\n }\n }\n\n case class Books(t: Int, a: Int, b: Int)\n\n}\n"}], "negative_code": [], "src_uid": "6a80b2af22cf8e5bb01ff47d257db196"} {"source_code": "import scala.io.StdIn._\nimport scala.collection.mutable._\nimport scala.math._\n\nobject D {\n def findLeft(a: Array[Int])(f: (Int, Int)=> Boolean): Array[Int]= {\n val s = ArrayBuffer[Int]()\n val result = Array.fill[Int](a.size)(0)\n for (i <- 0 until a.size) {\n while (!s.isEmpty && !f(a(s.last), a(i)))\n s.remove(s.size - 1)\n if (s.isEmpty)\n result(i) = -1\n else\n result(i) = s.last\n s += i\n }\n result\n }\n\n\n def findRight(a: Array[Int])(f: (Int, Int)=> Boolean): Array[Int] = findLeft(a.reverse)(f).map((x) => a.size - 1 - x).reverse\n\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toInt)\n val dp = Array.fill[Int](n)(n + 1)\n dp(0) = 0\n val ll = findLeft(a)(Ordering[Int].lteq)\n val lg = findLeft(a)(Ordering[Int].gteq)\n val rl = findRight(a)(Ordering[Int].lteq)\n val rg = findRight(a)(Ordering[Int].gteq)\n for(i <- 0 until a.size) {\n if(ll(i) != -1)\n dp(i) = min(dp(i), dp(ll(i)) + 1)\n if(lg(i) != -1)\n dp(i) = min(dp(i), dp(lg(i)) + 1)\n if(rl(i) != n)\n dp(rl(i)) = min(dp(rl(i)), dp(i) + 1)\n if(rg(i) != n)\n dp(rg(i)) = min(dp(rg(i)), dp(i) + 1) \n }\n println(dp(n - 1))\n }\n}", "positive_code": [{"source_code": "//package codeforces.contests._1407\n\nobject DiscreteCentrifugalJumps {\n\n /**\n * Monotonic Stack, right view\n *\n * @param seq elements, randomly accessible\n * @param ordering implicit ordering for gt operator\n * @tparam A type of each element\n * @return left view\n */\n def rightView[A](seq: IndexedSeq[A])(implicit ordering: Ordering[A]): IndexedSeq[Int] = {\n val result = new Array[Int](seq.length)\n\n seq.indices.foldRight[List[Int]](Nil) { (idx, stack) =>\n val uStack = stack.dropWhile(i => ordering.lt(seq(i), seq(idx)))\n result(idx) = uStack.headOption.getOrElse(-1)\n idx :: uStack\n }\n\n result\n }\n\n /**\n * Monotonic Stack, left view\n *\n * @param seq elements, randomly accessible\n * @param ordering implicit ordering for gt operator\n * @tparam A type of each element\n * @return left view\n */\n def leftView[A](seq: IndexedSeq[A])(implicit ordering: Ordering[A]): IndexedSeq[Int] = {\n val result = new Array[Int](seq.length)\n\n seq.indices.foldLeft[List[Int]](Nil) { (stack, idx) =>\n val uStack = stack.dropWhile(i => ordering.lt(seq(i), seq(idx)))\n result(idx) = uStack.headOption.getOrElse(-1)\n idx :: uStack\n }\n\n result\n }\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val arr = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val rightIncreasingView: IndexedSeq[Int] = rightView(arr) // check for -1\n val rightDecreasingView: IndexedSeq[Int] = rightView(arr)(Ordering.Int.reverse) // check for -1\n\n val leftIncreasingView = leftView(arr)\n val leftDecreasingView = leftView(arr)(Ordering.Int.reverse)\n\n val result = {\n val dp: Array[Int] = (0 until n).toArray\n dp.indices.foreach { i =>\n\n // relax dp(i) first\n if (leftIncreasingView(i) != -1)\n dp(i) = dp(i) min (dp(leftIncreasingView(i)) + 1)\n\n if (leftDecreasingView(i) != -1)\n dp(i) = dp(i) min (dp(leftDecreasingView(i)) + 1)\n\n // relax the future\n if (rightIncreasingView(i) != -1)\n dp(rightIncreasingView(i)) = dp(rightIncreasingView(i)) min (dp(i) + 1)\n\n if (rightDecreasingView(i) != -1)\n dp(rightDecreasingView(i)) = dp(rightDecreasingView(i)) min (dp(i) + 1)\n\n if (i + 1 < n)\n dp(i + 1) = dp(i + 1) min (dp(i) + 1)\n }\n dp(n - 1)\n }\n\n println(result)\n }\n\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1407\n\nobject DiscreteCentrifugalJumps {\n\n /**\n * Monotonic Stack, right view\n *\n * @param seq elements, randomly accessible\n * @param ordering implicit ordering for gt operator\n * @tparam A type of each element\n * @return left view\n */\n def rightView[A](seq: IndexedSeq[A])(implicit ordering: Ordering[A]): IndexedSeq[Int] = {\n val result = new Array[Int](seq.length)\n\n seq.indices.foldRight[List[Int]](Nil) { (idx, stack) =>\n val uStack = stack.dropWhile(i => ordering.lt(seq(i), seq(idx)))\n result(idx) = uStack.headOption.getOrElse(-1)\n idx :: uStack\n }\n\n result\n }\n\n /**\n * Monotonic Stack, left view\n *\n * @param seq elements, randomly accessible\n * @param ordering implicit ordering for gt operator\n * @tparam A type of each element\n * @return left view\n */\n def leftView[A](seq: IndexedSeq[A])(implicit ordering: Ordering[A]): IndexedSeq[Int] = {\n val result = new Array[Int](seq.length)\n\n seq.indices.foldLeft[List[Int]](Nil) { (stack, idx) =>\n val uStack = stack.dropWhile(i => ordering.lt(seq(i), seq(idx)))\n result(idx) = uStack.headOption.getOrElse(-1)\n idx :: uStack\n }\n\n result\n }\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val arr = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val rightIncreasingView: IndexedSeq[Int] = rightView(arr) // check for -1\n val rightMaxView: IndexedSeq[Int] = {\n val view = arr.clone()\n view(n - 1) = n - 1\n (0 to n - 2).foldRight(n - 1) { (i, maxi) =>\n if (arr(i) >= arr(maxi)) {\n view(i) = i\n i\n } else {\n view(i) = maxi\n maxi\n }\n }\n view\n }\n\n val rightDecreasingView: IndexedSeq[Int] = rightView(arr)(Ordering.Int.reverse) // check for -1\n val rightMinView: IndexedSeq[Int] = {\n val view = arr.clone()\n view(n - 1) = n - 1\n (0 to n - 2).foldRight(n - 1) { (i, mini) =>\n if (arr(i) <= arr(mini)) {\n view(i) = i\n i\n } else {\n view(i) = mini\n mini\n }\n }\n view\n }\n\n val leftIncreasingView = leftView(arr)\n val leftDecreasingView = leftView(arr)(Ordering.Int.reverse)\n\n val result = {\n val dp: Array[Int] = (0 until n).toArray\n (0 to n - 2).foreach { i =>\n\n // relax dp(i) first\n if (i > 0) {\n val h = {\n if (arr(i - 1) < arr(i))\n leftIncreasingView(i)\n else if (arr(i - 1) > arr(i - 1))\n leftDecreasingView(i)\n else -1\n }\n\n if (h != -1)\n dp(i) = dp(i) min (dp(h) + 1)\n }\n\n // relax the future\n if (arr(i) > arr(i + 1)) {\n\n val inc = rightIncreasingView(i)\n val j = {\n if (inc == -1) rightMaxView(i + 1)\n else inc\n }\n dp(j) = dp(j) min (dp(i) + 1)\n\n } else if (arr(i) < arr(i + 1)) {\n\n val dec = rightDecreasingView(i)\n val j = {\n if (dec == -1) rightMinView(i + 1)\n else dec\n }\n dp(j) = dp(j) min (dp(i) + 1)\n\n }\n\n dp(i + 1) = dp(i + 1) min (dp(i) + 1)\n }\n dp(n - 1)\n }\n\n println(result)\n }\n\n}\n"}, {"source_code": "//package codeforces.contests._1407\n\nobject DiscreteCentrifugalJumps {\n\n /**\n * Monotonic Stack, right view\n *\n * @param seq elements, randomly accessible\n * @param ordering implicit ordering for gt operator\n * @tparam A type of each element\n * @return left view\n */\n def rightView[A](seq: IndexedSeq[A])(implicit ordering: Ordering[A]): IndexedSeq[Int] = {\n val result = new Array[Int](seq.length)\n\n seq.indices.foldRight[List[Int]](Nil) { (idx, stack) =>\n val uStack = stack.dropWhile(i => ordering.lt(seq(i), seq(idx)))\n result(idx) = uStack.headOption.getOrElse(-1)\n idx :: uStack\n }\n\n result\n }\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val arr = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val rightIncreasingView: IndexedSeq[Int] = rightView(arr) // check for -1\n val rightMaxView: IndexedSeq[Int] = {\n val view = arr.clone()\n view(n - 1) = n - 1\n (0 to n - 2).foldRight(n - 1) { (i, maxi) =>\n if (arr(i) >= arr(maxi)) {\n view(i) = i\n i\n } else {\n view(i) = maxi\n maxi\n }\n }\n view\n }\n\n val rightDecreasingView: IndexedSeq[Int] = rightView(arr)(Ordering.Int.reverse) // check for -1\n val rightMinView: IndexedSeq[Int] = {\n val view = arr.clone()\n view(n - 1) = n - 1\n (0 to n - 2).foldRight(n - 1) { (i, mini) =>\n if (arr(i) <= arr(mini)) {\n view(i) = i\n i\n } else {\n view(i) = mini\n mini\n }\n }\n view\n }\n\n val result = {\n val dp: Array[Int] = (0 until n).toArray\n (0 to n - 2).foreach { i =>\n if (arr(i) > arr(i + 1)) {\n\n val inc = rightIncreasingView(i)\n val j = {\n if (inc == -1) rightMaxView(i + 1)\n else inc\n }\n dp(j) = dp(j) min (dp(i) + 1)\n\n } else if (arr(i) < arr(i + 1)) {\n\n val dec = rightDecreasingView(i)\n val j = {\n if (dec == -1) rightMinView(i + 1)\n else dec\n }\n dp(j) = dp(j) min (dp(i) + 1)\n\n }\n\n dp(i + 1) = dp(i + 1) min (dp(i) + 1)\n }\n dp(n - 1)\n }\n\n println(result)\n }\n\n}\n"}], "src_uid": "1436a01f6638a59d844fc5df93850f11"} {"source_code": "\n/**\n * @author pvasilyev\n * @since 18 Jun 2016\n */\nobject B625 extends App {\n\n def checkSubString(a: String, start: Int, b: String): Boolean = {\n if (a.length - start < b.length) {\n return false\n } else {\n for (i <- 0 until b.length) {\n if (a.charAt(start + i) != b.charAt(i)) {\n return false\n }\n }\n }\n true\n }\n\n def solve() = {\n val gogol: String = scala.io.StdIn.readLine()\n val pineapple: String = scala.io.StdIn.readLine()\n var answer = 0\n var i = 0\n while (i < gogol.length) {\n if (checkSubString(gogol, i, pineapple)) {\n answer += 1\n i += pineapple.length\n } else {\n i += 1\n }\n }\n println(answer)\n }\n\n solve()\n\n}\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject round_342_div2_B {\n def main(args: Array[String]){\n val in = Source.stdin.getLines()\n val now = in.next() + \"#\"\n val old = in.next()\n\n println(now.split(old).length-1)\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._, control._\nimport scala.math.Ordering.Implicits._\n\nobject _625B extends CodeForcesApp {\n override type Result = Int\n\n override def solve(read: InputReader) = {\n val (t, s) = (read[String], read[String])\n\n @tailrec\n def f(i: Int, acc: Int): Int = t.indexOf(s, i) match {\n case p if p >= 0 => f(p + s.length, acc + 1)\n case _ => acc\n }\n\n f(0, 0)\n }\n\n override def format(result: Result) = result.toString\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(next())\n\n def tillEndOfLine(): String = tokenizer().get.nextToken(\"\\n\\r\")\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\ntrait Parser[A] {\n def apply(s: String): A\n}\nobject Parser {\n def apply[A](f: String => A) = new Parser[A] {\n override def apply(s: String) = f(s)\n }\n implicit val stringParser: Parser[String] = Parser(identity)\n implicit val charParser: Parser[Char] = Parser(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val booleanParser: Parser[Boolean] = Parser(_.toBoolean)\n implicit val intParser: Parser[Int] = Parser(_.toInt)\n implicit val longParser: Parser[Long] = Parser(_.toLong)\n implicit val bigIntParser: Parser[BigInt] = Parser(BigInt(_))\n implicit val doubleParser: Parser[Double] = Parser(_.toDouble)\n implicit val bigDecimalParser: Parser[BigDecimal] = Parser(BigDecimal(_))\n}\n"}, {"source_code": "/**\n * Created by Tsibin.\n */\nobject Problemset625 {\n def main(args: Array[String]): Unit = {\n val problem = new ProblemB\n problem.solve()\n }\n\n private abstract class Problem {\n val stdIn = scala.io.StdIn\n def solve()\n }\n\n private class ProblemA extends Problem {\n override def solve(): Unit = {\n val Array(n, a, b, c) = Iterator.continually(stdIn.readLine())\n .takeWhile(_ != null)\n .map(BigInt(_))\n .toArray\n var count = BigInt(0)\n\n if (n < a && n < b) {\n println(0)\n return\n }\n if (a >= b - c && n >= b) {\n count = (n - c) / (b - c)\n val remains = n - (count * (b - c))\n if (remains > 0)\n count += remains / a\n }\n else\n count = n / a\n println(count)\n }\n }\n\n private class ProblemB extends Problem {\n override def solve() : Unit = {\n val Array(gogolII, pineappleTel) = Iterator.continually(stdIn.readLine())\n .takeWhile(_ != null)\n .toArray\n println(pineappleTel.r.findAllIn(gogolII).length)\n }\n }\n}\n"}, {"source_code": "\n/**\n * Created by octavian on 07/02/2016.\n */\nobject War {\n\n def main(args: Array[String]) = {\n\n //System.setIn(new FileInputStream(\"./src/war.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"./src/war.out\")))\n\n val a: Array[Char] = readLine().toCharArray\n val b: Array[Char] = readLine().toCharArray\n var matches: Vector[Int] = Vector.empty[Int]\n for(i <- 0 until a.length) {\n if(a.slice(i, i + b.length).deep == b.deep) {\n matches :+= i\n }\n }\n\n var lastPos = -1\n var result = 0\n for(i <- 0 until matches.length) {\n if(lastPos < matches(i)) {\n lastPos = matches(i) + b.length - 1\n result += 1\n }\n }\n println(result)\n }\n\n}\n"}, {"source_code": "object A {\n def main(args: Array[String]) {\n val phone = scala.io.StdIn.readLine\n val ai = scala.io.StdIn.readLine\n val counts = phone.replaceAll(ai, \"#\").toCharArray.groupBy(l => l)\n if (counts.isDefinedAt('#')) {\n println(counts('#').length)\n } else {\n println(0)\n }\n\n }\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val str1 = in.next()\n val str2 = in.next()\n val replace = str2.init + '#'\n println(str1.replaceAll(str2, replace).count(_ == '#'))\n}"}, {"source_code": "\nobject Main {\n import scala.annotation.tailrec\n import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}\n class MyConsole(val in: BufferedReader, val _out: PrintStream,\n val err: PrintStream) {\n // PrintWriter do not flush automatically\n val out = new PrintWriter(_out,false)\n // If argument is null, there are ambiguous which function will be called\n def print(obj: Any) = out.print(if(obj == null) \"null\" else obj.toString)\n def println() = out.println()\n def println(obj: Any) = out.println(obj)\n def printf(text: String, args: Any*) = out.printf(text.format(args : _*))\n // NOTE: YOU MUST FLUSH BEFORE END OF MAIN\n def flush() = out.flush()\n def debugln(obj: Any) = err.println(\"\\u001b[36m\" + obj + \"\\u001b[0m\")\n\n def readIntVector() : Vector[Int] = parseLineToVector(() => nextInt)\n def readLongVector() : Vector[Long] = parseLineToVector(() => nextLong)\n def readStringVector() : Vector[String] = parseLineToVector(() => nextString)\n def nextInt() : Int = nextLong().toInt\n def nextBigInt() : BigInt = BigInt(nextString())\n def nextBigDecimal( ) : BigDecimal = BigDecimal(nextString())\n def nextDouble() : Double = nextString().toDouble\n def nextLong() : Long = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading long failed\")\n val sgn = if(peek == '-') -1l else 1\n if(sgn == -1l) ignore(read())\n if(peek < '0' || '9' < peek)\n throw new NumberFormatException(s\"readLong found only '-' or no number\")\n @tailrec\n def readLong(next: Int, cur: Long) : Long =\n if('0' <= next && next <= '9'){\n ignore(read()) // is equal to next\n readLong(peek, cur*10 + next-'0')\n }\n else if(isEnd(next) || isSpaceOrControl(next))\n sgn*cur\n else\n throw new NumberFormatException(s\"readLong found strange byte $next\")\n val res = readLong(peek,0)\n skipTrailingSpaces()\n res\n }\n def nextString() : String = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading String failed\")\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isSpaceOrControl(next)){\n builder.toString\n }else{\n builder.append(read().toChar) // here we skip.\n appendCode(peek)\n }\n }\n val res = appendCode(peek)\n skipTrailingSpaces()\n res\n }\n // TODO: refactoring to marge nextString\n def readLine() : String = {\n if(isEnd(peek))\n throw new NoSuchElementException(\"Reading Line failed\")\n skipNewline()\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isNewLine(next)){\n builder.toString\n }else{\n builder.append(next.toChar)\n appendCode(read())\n }\n }\n appendCode(read())\n }\n // helpers\n private def ignore[T](x: => T) : Unit = { x; () }\n private[this] var peeked: Option[Int] = None\n private[this] var is_first = true\n protected def read() = {\n val res = peeked match {\n case None => in.read()\n case Some(a) => { peeked = None; a }\n }\n is_first = false\n res\n }\n private def peek() =\n peeked match {\n case None => {\n val res = in.read()\n peeked = Some(res)\n res\n }\n case Some(a) => a\n }\n private def isEnd(c: Int) = c == -1\n private def isCR(c: Int) = c == 13\n private def isLF(c: Int) = c == 10\n private def isNewLine(c: Int) = isLF(c) || isCR(c)\n private def isThereReadable() = !isEnd(peek)\n private def isSpaceOrControl(c: Int) = (0 <= c && c <= 32) || c == 127\n @tailrec\n final private def goNextNotSpaceNorControl() : Unit =\n if(isSpaceOrControl(peek)){\n ignore(read())\n goNextNotSpaceNorControl()\n }\n final private def skipTrailingSpaces() : Unit = {\n @tailrec\n def skipTrailingSpacesAux() : Unit = {\n if(!isNewLine(peek) && isSpaceOrControl(peek)){\n ignore(read())\n skipTrailingSpacesAux()\n }\n }\n skipTrailingSpacesAux()\n }\n final private def skipNewline() : Unit =\n if(!is_first){\n if(isCR(peek))\n ignore(read())\n if(isLF(peek))\n ignore(read())\n }\n private def goNextValuable() : Boolean = {\n goNextNotSpaceNorControl()\n isThereReadable()\n }\n\n private def parseLineToVector[X](parser: () => X) : Vector[X] = {\n import scala.collection.immutable.VectorBuilder\n val vb = new VectorBuilder[X]()\n skipNewline()\n @tailrec\n def parseLineToVectorAux() : Vector[X] =\n if(isNewLine(peek) || isEnd(peek)) {\n vb.result\n }else{\n vb += parser()\n parseLineToVectorAux()\n }\n parseLineToVectorAux()\n }\n }\n def main(args: Array[String]) : Unit = {\n val console = new MyConsole(Console.in, Console.out, Console.err)\n val solver = new Solver(console)\n solver.main()\n console.flush()\n }\n class Solver(val stdio: MyConsole){\n import stdio._ // shadow Console.~\n @tailrec\n final def solve(s: String, t: String, i : Int, a: Int) : Int = {\n val k = s.indexOf(t, i)\n if(k == -1)\n a\n else\n solve(s, t, k + t.length, a+1)\n }\n def main() : Unit = {\n val s = readLine()\n val t = readLine()\n println(solve(s, t, 0, 0))\n }\n }\n}\n"}, {"source_code": "// object Main\nimport java.io.{IOException, InputStream, PrintWriter}\nimport java.util.InputMismatchException\n\nobject Main {\n\n def solveCase(caseNo: Int, in: InputReader, out: PrintWriter): Unit = {\n val a = in.next().toCharArray\n val b = in.next()\n var answer = 0\n for (i <- 0 until a.length) {\n if (b.zipWithIndex.forall{p => i + p._2 < a.length && p._1 == a(i + p._2)}) {\n answer += 1\n a(i + b.length - 1) = '#'\n }\n }\n out.println(answer)\n }\n\n def solve(in: InputReader, out: PrintWriter): Unit = {\n solveCase(1, in, out)\n// val caseCount = in.nextInt()\n// for (caseNo <- 1 to caseCount) {\n// solveCase(caseNo, in, out)\n// }\n }\n\n def main(args: Array[String]) {\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n in.close()\n out.close()\n }\n}\n\nclass InputReader(val inputStream: InputStream) {\n val buf = new Array[Byte](1 << 16)\n var curChar = 0\n var numChars = 0\n\n def read(): Int = {\n if (numChars == -1) {\n throw new InputMismatchException()\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => throw new InputMismatchException()\n }\n if (numChars <= 0)\n return -1\n }\n curChar += 1\n buf(curChar - 1)\n }\n\n def peek(): Int = {\n if (numChars == -1) {\n return -1\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => return -1\n }\n if (numChars <= 0)\n return -1\n }\n buf(curChar)\n }\n\n def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n\n def nextInt(): Int = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextLong(): Long = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0l\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def next(): String = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n val res = new StringBuilder()\n do {\n res += c.toChar\n c = read()\n } while (!isSpaceChar(c))\n res.toString()\n }\n\n def nextChar(): Char = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n c.toChar\n }\n\n //noinspection AccessorLikeMethodIsEmptyParen\n def hasNext(): Boolean = {\n var value = peek()\n do {\n read()\n value = peek()\n } while (isSpaceChar(value) && value != -1)\n value != -1\n }\n\n def rawNextLine(): String = {\n val builder = new StringBuilder\n var c = read()\n while (c != '\\n' && c != -1) {\n if (c != '\\r')\n builder += c.toChar\n c = read()\n }\n builder.toString()\n }\n\n def nextLine(): String = {\n var s = rawNextLine()\n while (s.trim().length == 0) s = rawNextLine()\n s\n }\n\n def nextDouble(): Double = {\n next().toDouble\n }\n\n def close(): Unit = {\n inputStream.close()\n }\n}\n"}, {"source_code": "\n\nimport java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.implicitNotFound\nimport scala.reflect.ClassTag\n\n/**\n * Created by nimas on 2/4/16.\n */\nobject B extends App{\n\n class Template(val delim: String = \" \") {\n\n val in = new BufferedReader(new InputStreamReader(System.in))\n val out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n val it = Iterator.iterate(new StringTokenizer(\"\"))(tok => if (tok.hasMoreTokens) tok else new StringTokenizer(in.readLine(), delim))\n\n\n def nextTs[T: ParseAble](n: Int)(delim: String = \" \")(implicit ev: ClassTag[T]) = (Array fill n) {\n nextT[T](delim)\n }\n\n def nextT[T](delim: String = \" \")(implicit parser: ParseAble[T]) = {\n val x = it.find(_.hasMoreTokens)\n parser parse (x get)\n }\n\n def close(): Unit = {\n in.close()\n out.close()\n }\n\n @implicitNotFound(\"No member of type class ParseAble in scope for ${T}\")\n trait ParseAble[T] {\n def parse(strTok: StringTokenizer): T\n }\n\n object ParseAble {\n\n implicit object ParseAbleString extends ParseAble[String] {\n override def parse(strTok: StringTokenizer): String = strTok nextToken()\n }\n\n implicit object ParseAbleInt extends ParseAble[Int] {\n override def parse(strTok: StringTokenizer): Int = strTok nextToken() toInt\n }\n\n implicit object ParseAbleLong extends ParseAble[Long] {\n override def parse(strTok: StringTokenizer): Long = strTok nextToken() toLong\n }\n\n implicit object ParseAbleDouble extends ParseAble[Double] {\n override def parse(strTok: StringTokenizer): Double = strTok nextToken() toDouble\n }\n\n implicit object ParseAbleBigInt extends ParseAble[BigInt] {\n override def parse(strTok: StringTokenizer): BigInt = BigInt(strTok nextToken())\n }\n\n }\n\n }\n\n val io = new Template()\n\n import io._\n\n val ai = nextT[String]()\n val apple = nextT[String]()\n\n val s1 = apple.r findAllMatchIn ai\n\n out println (s1 size)\n\n\n close()\n\n}\n"}], "negative_code": [{"source_code": "\n/**\n * @author pvasilyev\n * @since 18 Jun 2016\n */\nobject B625 extends App {\n\n def solve() = {\n val gogol: String = scala.io.StdIn.readLine()\n val pineapple: String = scala.io.StdIn.readLine()\n var answer = 0\n var j = 0\n for (i <- 0 until gogol.length) {\n if (gogol.charAt(i) == pineapple.charAt(j)) {\n j += 1\n }\n if (j == pineapple.length) {\n j = 0\n answer += 1\n }\n }\n println(answer)\n }\n\n solve()\n\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 18 Jun 2016\n */\nobject B625 extends App {\n\n def checkSubString(a: String, start: Int, b: String): Boolean = {\n if (a.length - start < b.length) {\n return false\n } else {\n for (i <- 0 until b.length) {\n if (a.charAt(start + i) != b.charAt(i)) {\n return false\n }\n }\n }\n true\n }\n\n def solve() = {\n val gogol: String = scala.io.StdIn.readLine()\n val pineapple: String = scala.io.StdIn.readLine()\n var answer = 0\n var j = 0\n for (i <- 0 until gogol.length) {\n if (checkSubString(gogol, i, pineapple)) {\n answer += 1\n }\n }\n println(answer)\n }\n\n solve()\n\n}\n"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 18 Jun 2016\n */\nobject B625 extends App {\n\n def solve() = {\n val gogol: String = scala.io.StdIn.readLine()\n val pineapple: String = scala.io.StdIn.readLine()\n var answer = 0\n var j = 0\n for (i <- 0 until gogol.length) {\n if (gogol.charAt(i) == pineapple.charAt(j)) {\n j += 1\n } else if (gogol.charAt(i) == pineapple.charAt(0)) {\n j = 1\n } else {\n j = 0\n }\n if (j == pineapple.length) {\n j = 0\n answer += 1\n }\n }\n println(answer)\n }\n\n solve()\n\n}\n"}], "src_uid": "62a672fcaee8be282700176803c623a7"} {"source_code": "import scala.collection.mutable.HashSet\n\nobject B368 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val input = readInts(n)\n val output = new Array[Int](n)\n val set = HashSet.empty[Int]\n for(i <- n-1 to 0 by -1) {\n set += input(i)\n output(i) = set.size\n }\n for(_ <- 0 until m) {\n val Array(l) = readInts(1)\n println(output(l-1))\n }\n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt)\n var set = Set.empty[Int]\n val result = data.reverse.map { el =>\n set += el\n set.size\n }.reverse\n print(Range(0, m).map(_ => result(in.next().toInt - 1)).mkString(\"\\n\"))\n}"}], "negative_code": [], "src_uid": "1e156dfc65ef88f19ca1833f75192259"} {"source_code": "import java.util\nimport java.util.stream.Collectors\n\nobject E {\n\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n = nextInt\n val xs = readLongs(n / 2)\n val res = new Array[Long](n)\n\n def isSquare(x: Long): Boolean = {\n val r = Math.sqrt(x).toLong\n r * r == x\n }\n\n val LIM = 10000000000000L\n var acc = 0L\n\n var x = 1L\n var bad = false\n var i = 0\n while (i < xs.length) {\n val c = xs(i)\n while (x * x <= acc) {\n x += 1\n }\n var xx = x * x\n while (!bad && !isSquare(xx + c)) {\n x += 1\n xx = x * x\n if (xx - acc > LIM) bad = true\n }\n res(2 * i) = xx - acc\n res(2 * i + 1) = xs(i)\n acc = xx + c\n i += 1\n }\n\n if (!bad) {\n out.println(\"Yes\")\n out.println(util.Arrays.stream(res)\n .mapToObj(_.toString)\n .collect(\n Collectors\n .joining(\" \")))\n } else out.println(\"No\")\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = { val a = new Array[Int](n); java.util.Arrays.setAll(a, _ => nextInt); a }\n def readLongs(n: Int) = { val a = new Array[Long](n); java.util.Arrays.setAll(a, _ => nextLong); a }\n def readBigs(n: Int) = Array.fill(n) {nextBig }\n }\n}\n", "positive_code": [{"source_code": "object E {\n\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n = nextInt\n val xs = readLongs(n / 2)\n val res = Array.ofDim[Long](n)\n\n for (i <- xs.indices) res(2 * i + 1) = xs(i)\n\n def isSquare(x: Long): Boolean = {\n val r = Math.sqrt(x).toLong\n r * r == x\n }\n\n val LIM = 10000000000000L\n var acc = 0L\n\n var x = 1L\n var bad = false\n for (i <- xs.indices) {\n val c = xs(i)\n while (x * x <= acc) {\n x += 1\n }\n var xx = x * x\n while (!bad && !isSquare(xx + c)) {\n x += 1\n xx = x * x\n if (xx - acc > LIM) bad = true\n }\n res(2 * i) = xx - acc\n acc = xx + c\n }\n\n if (!bad) {\n out.println(\"Yes\")\n out.println(res.mkString(\" \"))\n } else out.println(\"No\")\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n) { nextInt }\n def readLongs(n: Int) = Array.fill(n) { nextLong }\n def readBigs(n: Int) = Array.fill(n) {nextBig }\n }\n}\n"}, {"source_code": "object E {\n\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n = nextInt\n val xs = readLongs(n / 2)\n val res = new Array[Long](n)\n\n def isSquare(x: Long): Boolean = {\n val r = Math.sqrt(x).asInstanceOf[Long]\n r * r == x\n }\n\n val LIM = 10000000000000L\n var acc = 0L\n\n var x = 1L\n var bad = false\n var i = 0\n while (i < xs.length) {\n val c = xs(i)\n while (x * x <= acc) {\n x += 1\n }\n var xx = x * x\n while (!bad && !isSquare(xx + c)) {\n x += 1\n xx = x * x\n if (xx - acc > LIM) bad = true\n }\n res(2 * i) = xx - acc\n res(2 * i + 1) = xs(i)\n acc = xx + c\n i += 1\n }\n\n if (!bad) {\n out.println(\"Yes\")\n out.println(res.mkString(\" \"))\n } else out.println(\"No\")\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n) { val a = new Array[Int](n); java.util.Arrays.setAll(a, _ => nextInt); a }\n def readLongs(n: Int) = Array.fill(n) { nextLong }\n def readBigs(n: Int) = Array.fill(n) {nextBig }\n }\n}\n"}, {"source_code": "object E {\n\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n = nextInt\n val xs = readLongs(n / 2)\n val res = Array.ofDim[Long](n)\n\n def isSquare(x: Long): Boolean = {\n val r = Math.sqrt(x).toLong\n r * r == x\n }\n\n val LIM = 10000000000000L\n var acc = 0L\n\n var x = 1L\n var bad = false\n var i = 0\n while (i < xs.length) {\n val c = xs(i)\n while (x * x <= acc) {\n x += 1\n }\n var xx = x * x\n while (!bad && !isSquare(xx + c)) {\n x += 1\n xx = x * x\n if (xx - acc > LIM) bad = true\n }\n res(2 * i) = xx - acc\n res(2 * i + 1) = xs(i)\n acc = xx + c\n i += 1\n }\n\n if (!bad) {\n out.println(\"Yes\")\n out.println(res.mkString(\" \"))\n } else out.println(\"No\")\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n) { nextInt }\n def readLongs(n: Int) = Array.fill(n) { nextLong }\n def readBigs(n: Int) = Array.fill(n) {nextBig }\n }\n}\n"}, {"source_code": "object E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs = readLongs(n / 2)\n\n val res = Array.ofDim[Long](n)\n\n for (i <- xs.indices) res(2 * i + 1) = xs(i)\n\n def isSquare(x: Long): Boolean = {\n val r = Math.sqrt(x).toLong\n r * r == x\n }\n\n val LIM = 10000000000000L\n var acc = 0L\n\n var x = 1L\n var bad = false\n for (i <- xs.indices) {\n val c = xs(i)\n while (x * x <= acc) {\n x += 1\n }\n var xx = x * x\n while (!bad && !isSquare(xx + c)) {\n x += 1\n xx = x * x\n if (xx - acc > LIM) bad = true\n }\n res(2 * i) = xx - acc\n acc = xx + c\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (!bad) {\n println(\"Yes\")\n println(res.mkString(\" \"))\n } else println(\"No\")\n\n Console.flush\n}\n"}, {"source_code": "object E {\n\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n = nextInt\n val xs = readLongs(n / 2)\n val res = Array.ofDim[Long](n)\n\n def isSquare(x: Long): Boolean = {\n val r = Math.sqrt(x).toLong\n r * r == x\n }\n\n val LIM = 10000000000000L\n var acc = 0L\n\n var x = 1L\n var bad = false\n var i = 0\n while (i < xs.length) {\n val c = xs(i)\n while (x * x <= acc) {\n x += 1\n }\n var xx = x * x\n while (!bad && !isSquare(xx + c)) {\n x += 1\n xx = x * x\n if (xx - acc > LIM) bad = true\n }\n res(2 * i) = xx - acc\n res(2 * i + 1) = xs(i)\n acc = xx + c\n i += 1\n }\n\n if (!bad) {\n out.println(\"Yes\")\n out.println(res.mkString(\" \"))\n } else out.println(\"No\")\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n) { val a = new Array[Int](n); java.util.Arrays.setAll(a, _ => nextInt); a }\n def readLongs(n: Int) = Array.fill(n) { nextLong }\n def readBigs(n: Int) = Array.fill(n) {nextBig }\n }\n}\n"}, {"source_code": "object E {\n\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n = nextInt\n val xs = readLongs(n / 2)\n val res = new Array[Long](n)\n\n def isSquare(x: Long): Boolean = {\n val r = Math.sqrt(x).toLong\n r * r == x\n }\n\n val LIM = 10000000000000L\n var acc = 0L\n\n var x = 1L\n var bad = false\n var i = 0\n while (i < xs.length) {\n val c = xs(i)\n while (x * x <= acc) {\n x += 1\n }\n var xx = x * x\n while (!bad && !isSquare(xx + c)) {\n x += 1\n xx = x * x\n if (xx - acc > LIM) bad = true\n }\n res(2 * i) = xx - acc\n res(2 * i + 1) = xs(i)\n acc = xx + c\n i += 1\n }\n\n if (!bad) {\n out.println(\"Yes\")\n out.println(res.mkString(\" \"))\n } else out.println(\"No\")\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = Array.fill(n) { val a = new Array[Int](n); java.util.Arrays.setAll(a, _ => nextInt); a }\n def readLongs(n: Int) = Array.fill(n) { nextLong }\n def readBigs(n: Int) = Array.fill(n) {nextBig }\n }\n}\n"}, {"source_code": "import java.util\nimport java.util.stream.Collectors\n\nobject E {\n\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n = nextInt\n val xs = readLongs(n / 2)\n val res = new Array[Long](n)\n\n def isSquare(x: Long): Boolean = {\n val r = Math.sqrt(x).asInstanceOf[Long]\n r * r == x\n }\n\n val LIM = 10000000000000L\n var acc = 0L\n\n var x = 1L\n var bad = false\n var i = 0\n while (i < xs.length) {\n val c = xs(i)\n while (x * x <= acc) {\n x += 1\n }\n var xx = x * x\n while (!bad && !isSquare(xx + c)) {\n x += 1\n xx = x * x\n if (xx - acc > LIM) bad = true\n }\n res(2 * i) = xx - acc\n res(2 * i + 1) = xs(i)\n acc = xx + c\n i += 1\n }\n\n if (!bad) {\n out.println(\"Yes\")\n out.println(util.Arrays.stream(res)\n .mapToObj(_.toString)\n .collect(\n Collectors\n .joining(\" \")))\n } else out.println(\"No\")\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = { val a = new Array[Int](n); java.util.Arrays.setAll(a, _ => nextInt); a }\n def readLongs(n: Int) = { val a = new Array[Long](n); java.util.Arrays.setAll(a, _ => nextLong); a }\n def readBigs(n: Int) = Array.fill(n) {nextBig }\n }\n}\n"}, {"source_code": "object E {\n\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n = nextInt\n val xs = readLongs(n / 2)\n val res = new Array[Long](n)\n\n def isSquare(x: Long): Boolean = {\n val r = Math.sqrt(x).asInstanceOf[Long]\n r * r == x\n }\n\n val LIM = 10000000000000L\n var acc = 0L\n\n var x = 1L\n var bad = false\n var i = 0\n while (i < xs.length) {\n val c = xs(i)\n while (x * x <= acc) {\n x += 1\n }\n var xx = x * x\n while (!bad && !isSquare(xx + c)) {\n x += 1\n xx = x * x\n if (xx - acc > LIM) bad = true\n }\n res(2 * i) = xx - acc\n res(2 * i + 1) = xs(i)\n acc = xx + c\n i += 1\n }\n\n if (!bad) {\n out.println(\"Yes\")\n out.println(res.mkString(\" \"))\n } else out.println(\"No\")\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def readInts(n: Int) = { val a = new Array[Int](n); java.util.Arrays.setAll(a, _ => nextInt); a }\n def readLongs(n: Int) = { val a = new Array[Long](n); java.util.Arrays.setAll(a, _ => nextLong); a }\n def readBigs(n: Int) = Array.fill(n) {nextBig }\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n\n def main(args: Array[String]): Unit = {}\n\n import IO._\n\n val n = nextInt\n val (a, b) = n % 4 match {\n case 0 => (1, 'A')\n case 1 => (0, 'A')\n case 2 => (1, 'B')\n case 3 => (2, 'A')\n }\n out.println(s\"$a $b\")\n out.flush()\n\n object IO {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def readInts(n: Int) = Array.fill(n)(Integer.parseInt(nextToken))\n }\n\n}\n"}, {"source_code": "object E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs = readLongs(n / 2)\n\n val res = Array.ofDim[Long](n)\n\n for (i <- xs.indices) res(2 * i + 1) = xs(i)\n\n def isSquare(x: Long): Boolean = {\n val r = Math.sqrt(x).toLong\n r * r == x\n }\n\n val LIM = 3162277L\n var acc = 0L\n\n var x = 1\n for (i <- xs.indices) {\n val c = xs(i)\n while (x * x <= acc) {\n x += 1\n }\n var xx = x * x\n while (x <= LIM && !isSquare(xx + c)) {\n x += 1\n xx = x * x\n }\n res(2 * i) = xx - acc\n acc = xx + c\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (x <= LIM) {\n println(\"Yes\")\n println(res.mkString(\" \"))\n } else println(\"No\")\n\n Console.flush\n}\n"}, {"source_code": "object E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs = readLongs(n / 2)\n\n val res = Array.ofDim[Long](n)\n\n for (i <- xs.indices) res(2 * i + 1) = xs(i)\n\n def isSquare(x: Long): Boolean = {\n val r = Math.sqrt(x).toLong\n r * r == x\n }\n\n val LIM = 3162277L\n var acc = 0L\n\n var x = 1\n for (i <- xs.indices) {\n val c = xs(i)\n var xx = x * x\n while (x <= LIM && (!isSquare(acc + xx) || !isSquare(acc + xx + c))) {\n x += 1\n xx = x * x\n }\n acc += xx\n acc += c\n res(2 * i) = xx\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (x <= LIM) {\n println(\"Yes\")\n println(res.mkString(\" \"))\n } else println(\"No\")\n\n Console.flush\n}\n"}, {"source_code": "object E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs = readLongs(n / 2)\n\n val res = Array.ofDim[Long](n)\n\n for (i <- xs.indices) res(2 * i + 1) = xs(i)\n\n def isSquare(x: Long): Boolean = {\n val r = Math.sqrt(x).toLong\n r * r == x\n }\n\n val LIM = 3162280L\n\n var x = 1L\n val b = xs.head\n while (!isSquare(b + x * x) && x < LIM) {\n x += 1\n }\n res(0) = x * x\n var acc = x * x + b\n\n for (i <- 1 until xs.length) {\n val c = xs(i)\n var xx = x * x\n while (x < LIM && (!isSquare(acc + xx) || !isSquare(acc + xx + c))) {\n x += 1\n xx = x * x\n }\n acc += xx\n acc += c\n res(2 * i) = xx\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (x < LIM) {\n println(\"Yes\")\n println(res.mkString(\" \"))\n } else println(\"No\")\n\n Console.flush\n}\n"}, {"source_code": "object E extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val xs = readLongs(n / 2)\n\n val res = Array.ofDim[Long](n)\n\n for (i <- xs.indices) res(2 * i + 1) = xs(i)\n\n def isSquare(x: Long): Boolean = {\n val r = Math.sqrt(x).toLong\n r * r == x\n }\n\n val LIM = 3162277L\n var acc = 0L\n\n var x = 1\n for (i <- xs.indices) {\n val c = xs(i)\n var xx = x * x\n while (x < LIM && (!isSquare(acc + xx) || !isSquare(acc + xx + c))) {\n x += 1\n xx = x * x\n }\n acc += xx\n acc += c\n res(2 * i) = xx\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (x < LIM) {\n println(\"Yes\")\n println(res.mkString(\" \"))\n } else println(\"No\")\n\n Console.flush\n}\n"}], "src_uid": "d07730b7bbbfa5339ea24162df7a5cab"} {"source_code": "object Main2 extends App {\n\nimport java.io._\nimport java.util\nimport java.util.{Locale, StringTokenizer, TreeSet}\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n\n var points = Vector[(Long, Int)]()\n\n for (_ <- 0 until n) {\n val l = in.nextLong\n val r = in.nextLong\n points = points :+ (l, 0)\n points = points :+ (r, 1)\n }\n\n points = points.sorted\n\n var ans = Map[Int, Long]()\n for (i <- 0 to n) ans += i -> 0\n\n var cnt = 0\n var prev = (0l, 0)\n for (point <- points) {\n\n if (prev._1 != point._1)\n ans += cnt -> (ans(cnt) + point._1 - prev._1 - 1)\n\n if (prev._1 != point._1 && prev._2 == 0)\n ans += cnt -> (ans(cnt) + 1)\n\n if (point._2 == 0) cnt += 1\n else {\n if (prev._1 == point._1 && prev._2 != point._2)\n ans += cnt -> (ans(cnt) + 1)\n\n if (prev._1 != point._1)\n ans += cnt -> (ans(cnt) + 1)\n\n cnt -= 1\n }\n\n prev = point\n }\n\n for (i <- 1 to n) out.print(ans(i)+\" \")\n\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}", "positive_code": [{"source_code": "\n\nobject Main2 extends App {\n\nimport java.io._\nimport java.util\nimport java.util.{Locale, StringTokenizer, TreeSet}\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\n val in = new Reader()\n val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n\n val MOD = 1000000000 + 7\n val eps = 0.00000001\n\n val n = in.nextInt\n\n var points = new Array[(Long, Int)](2*n)\n\n for (i <- 0 until n) {\n val l = in.nextLong\n val r = in.nextLong\n points(i*2) = (l, 0)\n points(i*2+1) = (r, 1)\n }\n\n points = points.sorted\n\n var ans = Map[Int, Long]()\n for (i <- 0 to n) ans += i -> 0\n\n var cnt = 0\n var prev = (0l, 0)\n for (point <- points) {\n\n if (prev._1 != point._1)\n ans += cnt -> (ans(cnt) + point._1 - prev._1 - 1)\n\n if (prev._1 != point._1 && prev._2 == 0)\n ans += cnt -> (ans(cnt) + 1)\n\n if (point._2 == 0) cnt += 1\n else {\n if (prev._1 == point._1 && prev._2 != point._2)\n ans += cnt -> (ans(cnt) + 1)\n\n if (prev._1 != point._1)\n ans += cnt -> (ans(cnt) + 1)\n\n cnt -= 1\n }\n\n prev = point\n }\n\n for (i <- 1 to n) out.print(ans(i)+\" \")\n\n out.flush()\n out.close()\n\n class Reader @throws[IOException]\n () {\n var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var tok: StringTokenizer = null\n\n def this(file: String) {\n this()\n br = new BufferedReader(new FileReader(file))\n }\n\n @throws[IOException]\n def next: String = {\n while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)\n tok.nextToken\n }\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextInt: Int = Integer.valueOf(next)\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextLong: Long = next.toLong\n\n @throws[NumberFormatException]\n @throws[IOException]\n def nextDouble: Double = next.toDouble\n\n @throws[IOException]\n def nextLine: String = br.readLine\n }\n\n}"}], "negative_code": [], "src_uid": "e53a6f0bd06550e078e8093590de0360"} {"source_code": "object CF1325B extends App{\n val sc = new java.util.Scanner(System.in)\n val t = sc.nextInt\n for (i <- 1 to t) {\n val n = sc.nextInt\n sc.nextLine()\n val nx = sc.nextLine().split(\" \").toSet\n println(Math.min(n, nx.size))\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]): Unit = {\n try {\n val (in, out) =\n if (isOnlineJudge) {\n (\n new FastScanner(new InputStreamReader(System.in)),\n new PrintWriter(System.out)\n )\n } else {\n (\n new FastScanner(new FileReader(new File(\"src/resource/problem.in\"))),\n new PrintWriter(new File(\"src/resource/problem.out\"))\n )\n }\n new C628B(in, out).solve()\n out.flush()\n out.close()\n } catch {\n case e: IOException => e.printStackTrace()\n }\n }\n\n private[this] val isOnlineJudge = true\n\n class FastScanner(val streamReader: InputStreamReader) {\n private[this] val reader = new BufferedReader(streamReader, 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n\n def nl(): Long = nextLong()\n\n def nc(): Char = nextChar()\n\n def ns(): String = next()\n\n def ns(n: Int): Array[Char] = ns().toCharArray\n\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while (i < N) {\n f(i);\n i += 1\n }\n }\n\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while (i >= offset) {\n f(i);\n i -= 1\n }\n }\n\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass C628B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n val t = ni()\n REP(t) { _ =>\n val n = ni()\n val a = na(n).toIndexedSeq.sorted\n var count = 1\n REP(n) { i =>\n if(i > 0 && a(i-1) != a(i)) count+=1\n }\n out.println(count)\n }\n }\n}\n"}, {"source_code": "object Main extends App {\n (0 until readInt()).map(_ => {\n readLine()\n readLine().split(\" \").map(n => n.toInt).toSet.size\n }).foreach(n => println(s\"$n\"))\n}"}, {"source_code": "object Main {\n\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.collection.mutable.ListBuffer\n def main(args: Array[String]): Unit = {\n solve(System.in,System.out)\n }\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n (1 to t).foreach{ _ =>\n val n = in.nextInt()\n val a = (1 to n).map(_ => in.nextInt())\n out.println(a.distinct.length)\n }\n }\n class InputReader(stream: InputStream){\n val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)\n var tokenizer: StringTokenizer = _\n def next(): String = {\n while(tokenizer == null || !tokenizer.hasMoreTokens){\n try{\n tokenizer = new StringTokenizer(reader.readLine())\n }catch {\n case e: IOException => throw new RuntimeException(e)\n }\n }\n tokenizer.nextToken()\n }\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n }\n}"}, {"source_code": "import java.io.PrintWriter\n\nimport scala.collection.mutable\nimport util.control.Breaks._\n\nobject Solution {\n val reader = scala.io.StdIn\n def readInt(): Int = reader.readLine().toInt\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n def readString(): String = reader.readLine()\n\n def multiTest(f: () => Unit): Unit = {\n var t = readInt()\n while (t > 0) {\n f()\n t -= 1\n }\n }\n\n def GCD(a: Int, b: Int): Int = {\n if (a == 0) return b\n GCD(b % a, a)\n }\n\n def solve(): Unit = {\n val n = readInt()\n val a = readArrayInt()\n println(a.distinct.length)\n\n }\n\n def main(args: Array[String]) {\n multiTest(solve)\n //solve()\n }\n}"}], "negative_code": [], "src_uid": "b978ca6fdef4a02cc027485294caa0f5"} {"source_code": "\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n val n = input.next().toInt\n var ns = input.next().split(\" \").map(_.toInt).toList\n var s = 0\n var e = ns.length\n var l = List.empty[Int]\n while (ns.nonEmpty) {\n if (ns.head > ns.last) {\n l = ns.head :: l\n ns = ns.drop(1)\n } else {\n l = ns.last :: l\n ns = ns.dropRight(1)\n }\n }\n val as = l.reverse.grouped(2).map(a => if (a.size == 2) (a(0), a(1)) else (a(0), 0)).toList.unzip\n print(as._1.sum + \" \" + as._2.sum)\n }\n}\n", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _381A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => next.toInt).toArray\n def f(l: Int, r: Int, which: Int, one: Int, two: Int): (Int, Int) =\n if (l > r) (one, two)\n else if (which == 0) {\n if (a(l) > a(r)) f(l + 1, r, 1 - which, one + a(l), two)\n else f(l, r - 1, 1 - which, one + a(r), two)\n } else {\n if (a(l) > a(r)) f(l + 1, r, 1 - which, one, two + a(l))\n else f(l, r - 1, 1 - which, one, two + a(r))\n }\n val ans = f(0, n - 1, 0, 0, 0)\n println(ans._1 + \" \" + ans._2)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n var ser = 0\n var dim = 0\n var left = 0\n var right = data.length - 1\n var dh = false\n while (right >= left) {\n var score = Math.max(data(left), data(right))\n if (data(left) >= data(right))\n left += 1\n else\n right -= 1\n\n if (dh)\n dim += score\n else\n ser += score\n dh = !dh\n }\n println(ser + \" \" + dim)\n}"}, {"source_code": "import java.util.Scanner\n\nobject P381A {\n def main(args: Array[String]) {\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n val cards = for (i <- 0 until n) yield scanner.nextInt()\n val ans = emulate(cards.toList)\n println(ans._1 + \" \" + ans._2)\n }\n \n def emulate(list: List[Int]): (Int, Int) = {\n if (list.isEmpty) (0, 0)\n else if (list.head > list.last) {\n val points = emulate(list.tail).swap\n (list.head + points._1, points._2)\n }\n else {\n val points = emulate(list.init).swap\n (list.last + points._1, points._2)\n }\n }\n}\n"}, {"source_code": "import scala.util.Sorting \nobject Solve{\n def main(args: Array[String]): Unit = {\n \n val n = readInt()\n val arr = readLine().split(\" \").map(_.toInt)\n \n var dimaSum = 0\n var serejaSum = 0\n var left = 0\n var right = arr.length - 1\n var sTurn = true\n var temp = 0\n while(left <= right){\n if(arr(left) > arr(right)) \n { temp = arr(left); left += 1; }\n else \n { temp = arr(right); right -= 1; }\n \n if(sTurn) \n serejaSum += temp\n else\n dimaSum += temp\n \n sTurn = !sTurn \n }\n \n println(serejaSum + \" \" + dimaSum)\n \n }\n}"}, {"source_code": "object A381 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n var in = readInts(n)\n var ser = 0\n var dima = 0\n while(in.nonEmpty){\n if(in.head > in.last) {\n ser += in.head\n in = in.drop(1)\n } else {\n ser += in.last\n in = in.dropRight(1)\n }\n if(in.nonEmpty) {\n if(in.head > in.last) {\n dima += in.head\n in = in.drop(1)\n } else {\n dima += in.last\n in = in.dropRight(1)\n }\n }\n\n }\n println(s\"$ser $dima\")\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P381A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val N = sc.nextInt\n\n type Cards = List[Int]\n val CS: Cards = List.fill(N)(sc.nextInt)\n\n def solve(): Unit = {\n \n @tailrec\n def loop(spt: Int, dpt: Int, turn: Int, cs: Cards, rcs: Cards): Unit = {\n if (turn == N) out.println(List(spt, dpt).mkString(\" \"))\n else (cs, rcs) match {\n case (x :: xs, y :: ys) if x > y => if (turn % 2 == 0) loop(spt + x, dpt, turn + 1, xs, rcs)\n else loop(spt, dpt + x, turn + 1, xs, rcs)\n case (_, y :: ys) => if (turn % 2 == 0) loop(spt + y, dpt, turn + 1, cs, ys)\n else loop(spt, dpt + y, turn + 1, cs, ys)\n }\n }\n\n loop(0, 0, 0, CS, CS.reverse)\n }\n\n solve\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject CF381A { \n\n def main(args: Array[String]) {\n val in = new Scanner(System.in)\n val n = in.nextInt()\n val cards = for(i <- 0 until n) yield in.nextInt()\n val answers = gao(cards.toList)\n println(answers._1 + \" \" + answers._2)\n }\n\n def gao(list: List[Int]): (Int, Int) = {\n if (list.isEmpty) (0, 0) \n else if (list.head > list.last) {\n val scores = gao(list.tail).swap\n (list.head + scores._1, scores._2)\n } else {\n val scores = gao(list.init).swap\n (list.last + scores._1, scores._2)\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.util.Sorting \nobject Solve{\n def main(args: Array[String]): Unit = {\n \n val n = readInt()\n val arr = readLine().split(\" \").map(_.toInt)\n val cmp = (x: Int, y: Int) => x > y\n Sorting.stableSort(arr, cmp)\n //arr.foreach(println(_))\n \n var dimaSum = 0\n var serejaSum = 0\n for (i <- 0 to arr.length - 1)\n if(i % 2 == 0)\n serejaSum += arr(i)\n else\n dimaSum += arr(i)\n \n println(serejaSum + \" \" + dimaSum)\n \n }\n}"}], "src_uid": "a7e98ed8ee1b0a4fd03dfcd222b68c6f"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n1, m1, x, y) = in.next().split(' ').map(_.toInt)\n val men = in.next().split(' ').map(_.toInt)\n val vests = in.next().split(' ').map(_.toInt)\n\n def process(mi: Int = 0, vi: Int = 0, pairs: List[(Int, Int)] = Nil): List[(Int, Int)] =\n if (mi == n1 || vi == m1) pairs\n else {\n if (men(mi) + y >= vests(vi) && men(mi) - x <= vests(vi))\n process(mi + 1, vi + 1, (mi + 1, vi + 1) :: pairs)\n else if (men(mi) < vests(vi)) process(mi + 1, vi, pairs)\n else process(mi, vi + 1, pairs)\n }\n\n val res = process()\n println(res.length)\n println(res.map(i => s\"${i._1} ${i._2}\").mkString(\"\\n\"))\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val nmxy = readLine.split(\" \").map(i => i.toInt)\n val n = nmxy(0)\n val m = nmxy(1)\n val x = nmxy(2)\n val y = nmxy(3)\n\n val a = readLine.split(\" \").map(i => i.toInt)\n val b = readLine.split(\" \").map(i => i.toInt)\n\n var ap = 0\n var bp = 0\n\n var resa = new Array[Int](n)\n var resb = new Array[Int](n)\n\n var i = 0\n\n while(ap < n && bp < m) {\n if(a(ap)-x <= b(bp) && b(bp) <= a(ap)+y) {\n resa(i) = ap\n resb(i) = bp\n i += 1\n ap += 1\n bp += 1\n } else if(a(ap)-x > b(bp)) {\n bp += 1 \n } else {\n ap += 1\n }\n }\n \n println(i)\n (0 until i).foreach(j => println((resa(j)+1)+\" \"+(resb(j)+1)))\n }\n} \n"}, {"source_code": "import java.util.Scanner\n\nobject A {\n val in = new Scanner(System.in)\n \n def main(args: Array[String]) {\n val n = in.nextInt()\n val m = in.nextInt()\n val x = in.nextInt()\n val y = in.nextInt()\n val a = Array.fill[Int](n)(in.nextInt())\n val b = Array.fill[Int](m)(in.nextInt())\n// a.sortWith(_ < _)\n// b.sortWith(_ < _)\n var j = 0\n var ans = List[(Int, Int)]()\n for (i <- 0 until a.length) {\n while (j < b.length && b(j) < a(i) - x) {\n j += 1\n }\n// println(i + \" \" + j + \" \" + b(j) + \" \" + (a(i) + y))\n if (j < b.length && b(j) <= a(i) + y) {\n ans ::= (i + 1, j + 1)\n j += 1\n }\n }\n println(ans.size)\n for (x <- ans) {\n println(x._1 + \" \" + x._2)\n }\n\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n1, m1, x, y) = in.next().split(' ').map(_.toInt)\n val men = in.next().split(' ').map(_.toInt)\n val vests = in.next().split(' ').map(_.toInt)\n\n def process(mi: Int = 0, vi: Int = 0, pairs: List[(Int, Int)] = Nil): List[(Int, Int)] =\n if (mi == n1 || vi == m1) pairs\n else {\n if (men(mi) + y >= vests(vi) && men(mi) - x <= vests(vi)) \n process(mi + 1, vi + 1, (n1 - mi, m1 - vi) :: pairs)\n else if (men(mi) < vests(vi)) process(mi + 1, vi, pairs)\n else process(mi, vi + 1, pairs)\n }\n\n val res = process()\n println(res.length)\n println(res.map(i => s\"${i._1} ${i._2}\").mkString(\"\\n\"))\n}"}], "src_uid": "c6bbb16b1a3946ce38e67dc4824ecf89"} {"source_code": "object Chores169A extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n solve(System.in,System.out)\n def solve(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextInt()\n val a = scanner.nextInt()\n val b = scanner.nextInt()\n \n val h = (1 to n).map(_ => scanner.nextInt()).sorted.toArray\n val (bChores,aChores) = h.splitAt(b)\n val lastB = bChores.last\n val firstA = aChores.head\n\n /**\n * todos los valores mayores o iguales que lastB y menores que firstA son validos\n */\n val result = firstA-lastB\n out.println(result)\n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n val data = scala.io.Source.stdin.getLines()\n val Array(n, a, b) = data.next().split(\" \").map(_.toInt)\n val tasks = data.next().split(\" \").map(_.toInt).sorted\n println(tasks(b) - tasks(b - 1))\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val data = scala.io.Source.stdin.getLines()\n val Array(n, a, b) = data.next().split(\" \").map(_.toInt)\n val tasks = data.next().split(\" \").map(_.toInt).sorted\n if (tasks(b) != tasks(b - 1)) println(tasks(b - 1))\n else println(0)\n\n}"}, {"source_code": "object Solution extends App {\n val data = scala.io.Source.stdin.getLines()\n val Array(n, a, b) = data.next().split(\" \").map(_.toInt)\n val tasks = data.next().split(\" \").map(_.toInt).sorted\n if (tasks(b) != tasks(b - 1)) println(tasks(b - 1))\n else tasks(0)\n\n}"}], "src_uid": "d3c8c1e32dcf4286bef19e9f2b79c8bd"} {"source_code": "import scala.io.StdIn._\nimport scala.collection.mutable.HashSet\n\nobject Codeforces extends App {\n val n = readInt()\n val bag = HashSet[String]()\n 1 to n foreach(_ => {\n val name = readLine()\n if (bag.contains(name))\n println(\"YES\")\n else {\n bag.add(name)\n println(\"NO\")\n }\n })\n}\n", "positive_code": [{"source_code": "object ATomRiddlesDiary extends App {\n val n = scala.io.StdIn.readLine.toInt\n (0 until n).foldLeft(Map.empty[String, Boolean]) { (map, _) =>\n val name = scala.io.StdIn.readLine\n if (map contains name) println(\"YES\")\n else {\n println(\"NO\")\n }\n map + (name -> true)\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.util.HashSet\n\nobject TomRiddleDiary {\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n \n val n = in.nextInt\n \n val s = new HashSet[String]\n val _ = in.nextLine\n \n (1 to n).map {\n x => {\n val str = in.nextLine\n if (s.contains(str)) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n \n s.add(str)\n }\n }\n }\n}"}], "negative_code": [], "src_uid": "7f934f96cbe3990945e5ebcf5c208043"} {"source_code": "\nimport java.util.Scanner\nimport java.util.Locale\n\nobject Main {\n def main(args: Array[String]): Unit = {\n Locale.setDefault(Locale.US)\n val sc = new Scanner(System.in)\n var sum = 0;\n val m = sc.nextInt()\n for( i <- 1 to m) {\n val x1 = sc.nextInt()\n val y1 = sc.nextInt()\n val x2 = sc.nextInt()\n val y2 = sc.nextInt()\n sum += (x2-x1+1) * (y2-y1+1)\n }\n println(sum)\n }\n \n}", "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject _552A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => (1 to 4).map(j => next.toInt).toArray)\n val b = a.map(i => (i(2) - i(0) + 1) * (i(3) - i(1) + 1))\n println(b.sum)\n}\n"}, {"source_code": "object A552 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n var res = 0L\n for(_ <- 0 until n) {\n val arr = readLongs(4)\n res += (arr(2)-arr(0)+1)*(arr(3)-arr(1)+1)\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val arr = new Array[Array[Int]](100)\n for (i <- 0 until 100) {\n arr(i) = new Array[Int](100)\n }\n for (i <- 0 until n) {\n val x1 = nextInt - 1\n val y1 = nextInt - 1\n val x2 = nextInt - 1\n val y2 = nextInt - 1\n for (j <- x1 to x2) {\n for (k <- y1 to y2) {\n arr(j)(k) += 1\n }\n }\n }\n var ans = 0\n for (i <- 0 until 100)\n for (j <- 0 until 100)\n ans += arr(i)(j)\n out.println(ans)\n return 0\n }\n}\n"}, {"source_code": "object _552A extends CodeForcesApp {\n import scala.collection.mutable\n\n override type Input = List[(Int, Int, Int, Int)]\n override type Output = Int\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n List.fill(nextInt)((nextInt, nextInt, nextInt, nextInt))\n }\n\n override def solve(input: Input) = input map {\n case (x1, y1, x2, y2) => (x2 - x1 + 1) * (y2 - y1 + 1)\n } sum\n\n override def format(result: Output) = super.format(result)\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp extends App {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /********************************[ lib ]************************************/\n import scala.collection.mutable\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type m_=>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None\n /******************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n def timeLimitSecond = 1\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\n\nobject A extends App {\n val n = readInt()\n var total = 0\n\n for (_ <- 1 to n) {\n val Array(x1, y1, x2, y2) = readLine().split(\" \").map(_.toInt)\n total += (x2 - x1 + 1) * (y2 - y1 + 1)\n }\n\n println(total)\n\n}\n"}, {"source_code": "object A{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val n=nextInt\n var sum=0\n for(i<-0 until n){\n val a=nextInt\n val b=nextInt\n val c=nextInt\n val d=nextInt\n sum+=(c-a+1)*(d-b+1)\n }\n out.println(sum)\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "import scala.collection._\n\nobject Test {\n def main(args: Array[String]) {\n\n var inLoop = true;\n while (inLoop) {\n val rectCountS = scala.io.StdIn.readLine\n if (rectCountS != null) {\n val rectCount = rectCountS.toInt\n var cellCount = 0\n\n for (i <- 0 to (rectCount - 1)) {\n val rect = scala.io.StdIn.readLine.split(' ').map(_.toInt)\n cellCount += (rect(2) + 1 - rect(0)) * (rect(3) + 1 - rect(1))\n }\n println(cellCount)\n\n }\n else {\n inLoop = false;\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "ca5c44093b1ab7c01970d83b5f49d0c6"} {"source_code": "object _1726A extends CodeForcesApp {\n override def solve() = repeat() {\n val as: Seq[Int] = in.nextN(in.nextInt())\n\n val ans = Seq(\n as.last - as.min,\n as.max - as.head,\n (as :+ as.head).sliding(2).map({case Seq(p, n) => p - n}).max\n ).max\n\n out.println(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\nimport java.io._\n\ntrait CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n\n var in: InputReader = new InputReader(System.in)\n var out: PrintWriter = new PrintWriter(System.out)\n\n def solve(): Any\n\n def repeat[U](n: Int = in.nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n\n def main(args: Array[String]): Unit = {\n if (!isOnlineJudge && args.length == 2) {\n in = new InputReader(new File(args(0)))\n out = new PrintWriter(new File(args(1)))\n }\n try solve() finally out.flush()\n }\n}\n\nclass InputReader(in: BufferedReader) {\n def this(file: File) = this(new BufferedReader(new FileReader(file)))\n def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))\n\n val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(\" \"))\n\n def nextLine(): String = in.readLine()\n def next(): String = tokens.next()\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextDouble(): Double = next().toDouble\n def nextN[C[_], A](r: => A)(implicit b: collection.generic.CanBuild[A, C[A]]): C[A] = Iterator.fill(nextInt())(r).to[C]\n}\n", "positive_code": [{"source_code": "object _1726A extends CodeForcesApp {\n override def solve() = repeat() {\n val as = nextN(nextInt()).toSeq\n\n val ans = Seq(\n as.last - as.min,\n as.max - as.head,\n (as :+ as.head).sliding(2).map({ case Seq(p, n) => p - n }).max\n ).max\n\n out.println(ans)\n }\n}\n/**************************** [Ignore Template Below] **************************************/\ntrait CodeForcesApp {\n import java.io._\n var in = new BufferedReader(new InputStreamReader(System.in))\n var out = new PrintWriter(System.out)\n\n val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(\" \"))\n\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n def nextLine(): String = in.readLine()\n def next(): String = tokens.next()\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextDouble(): Double = next().toDouble\n def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)\n\n def debug(x: => Any): Unit = if (!sys.props.contains(\"ONLINE_JUDGE\")) println(s\"DEBUG: $x\")\n def eng(b: Boolean): String = if (b) \"Yes\" else \"No\"\n\n def main(args: Array[String]): Unit = try solve() finally out.flush()\n def solve(): Any\n}\n"}, {"source_code": "object _1726A extends CodeForcesApp {\n override def solve() = repeat() {\n val as: Seq[Int] = nextN(nextInt())\n\n val ans = Seq(\n as.last - as.min,\n as.max - as.head,\n (as :+ as.head).sliding(2).map({case Seq(p, n) => p - n}).max\n ).max\n\n out.println(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n import java.io._\n\n var in = new BufferedReader(new InputStreamReader(System.in))\n var out = new PrintWriter(System.out)\n\n val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(\" \"))\n\n def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n\n def nextLine(): String = in.readLine()\n def next(): String = tokens.next()\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextDouble(): Double = next().toDouble\n def nextN[C[_], A](r: => A)(implicit b: collection.generic.CanBuild[A, C[A]]): C[A] = Iterator.fill(nextInt())(r).to[C]\n\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n\n def solve(): Any\n\n def main(args: Array[String]): Unit =\n try solve() finally out.flush()\n}\n"}, {"source_code": "object _1726A extends CodeForcesApp {\n override def solve() = repeat() {\n val as: Seq[Int] = in.nextN(in.nextInt())\n\n val ans = Seq(\n as.last - as.min,\n as.max - as.head,\n (as :+ as.head).sliding(2).map({case Seq(p, n) => p - n}).max\n ).max\n\n out.println(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\nimport java.io._\n\ntrait CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n\n var in: InputReader = new InputReader(System.in)\n var out: PrintWriter = new PrintWriter(System.out)\n\n def solve(): Any\n\n def repeat[U](n: Int = in.nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n\n def main(args: Array[String]): Unit = {\n if (!isOnlineJudge && args.length == 2) {\n in = new InputReader(new File(args(0)))\n out = new PrintWriter(new File(args(1)))\n }\n try solve() finally out.flush()\n }\n}\n\nclass InputReader(in: BufferedReader) {\n def this(file: File) = this(new BufferedReader(new FileReader(file)))\n def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))\n\n val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(new StringTokenizer(_))\n\n def nextLine(): String = in.readLine()\n def next(): String = tokens.next()\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextDouble(): Double = next().toDouble\n def nextN[C[_], A](r: => A)(implicit b: collection.generic.CanBuild[A, C[A]]): C[A] = Iterator.fill(nextInt())(r).to[C]\n}\n\nclass StringTokenizer(s: String, delimiter: Char = ' ') extends Iterator[String] {\n private var i = 0\n private def skip(delim: Boolean) = {\n while(i < s.length && (s(i) == delimiter ^ !delim)) i += 1\n i\n }\n override def hasNext = skip(delim = true) < s.length\n override def next() = s.substring(i, skip(delim = false))\n}\n"}, {"source_code": "object _1726A extends CodeForcesApp {\n override def solve() = repeat() {\n val as = in.nextN(in.nextInt()).toSeq\n\n val ans = Seq(\n as.last - as.min,\n as.max - as.head,\n (as :+ as.head).sliding(2).map({case Seq(p, n) => p - n}).max\n ).max\n\n out.println(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\nimport java.io._\n\ntrait CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n\n var in: InputReader = new InputReader(System.in)\n var out: PrintWriter = new PrintWriter(System.out)\n\n def solve(): Any\n\n def repeat[U](n: Int = in.nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)\n\n def main(args: Array[String]): Unit = {\n if (!isOnlineJudge && args.length == 2) {\n in = new InputReader(new File(args(0)))\n out = new PrintWriter(new File(args(1)))\n }\n try solve() finally out.flush()\n }\n}\n\nclass InputReader(in: BufferedReader) {\n def this(file: File) = this(new BufferedReader(new FileReader(file)))\n def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))\n\n val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(\" \"))\n\n def nextLine(): String = in.readLine()\n def next(): String = tokens.next()\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextDouble(): Double = next().toDouble\n\n def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)\n}\n"}, {"source_code": "object _1726A extends CodeForcesApp {\n override def solve() = in.repeat() {\n val as = in.nextSeq()(in.nextInt()).toSeq\n\n val ans = Seq(\n as.last - as.min,\n as.max - as.head,\n (as :+ as.head).sliding(2).map({case Seq(p, n) => p - n}).max\n ).max\n\n out.println(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\nimport java.io._\n\ntrait CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n\n var in: InputReader = new InputReader(System.in)\n var out: PrintWriter = new PrintWriter(System.out)\n\n def solve(): Any\n\n def main(args: Array[String]): Unit = {\n if (!isOnlineJudge) {\n in = new InputReader(new File(args(0)))\n out = new PrintWriter(new File(args(1)))\n }\n try solve() finally out.flush()\n }\n}\n\nclass InputReader(in: BufferedReader) {\n def this(file: File) = this(new BufferedReader(new FileReader(file)))\n def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))\n\n val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(\" \"))\n\n def nextLine(): String = in.readLine()\n def next(): String = tokens.next()\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextDouble(): Double = next().toDouble\n\n def repeat(n: Int = nextInt())(f: => Unit): Unit = (1 to n).foreach(_ => f)\n def nextSeq[A](n: Int = nextInt())(r: => A): Iterator[A] = Iterator.fill(n)(r)\n}\n"}], "negative_code": [{"source_code": "object _1726A extends CodeForcesApp {\n\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n override def solve() = in.repeat() {\n val as = in.nextSeq()(in.nextInt()).toSeq\n\n val ans = Seq(\n when(as.length > 1)(as.last - as.init.min),\n when(as.length > 1)(as.tail.max - as.head),\n Some((as :+ as.head).sliding(2).map({case Seq(p, n) => n - p}).max)\n ).flatten.max\n\n out.println(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\nimport java.io._\n\ntrait CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n\n var in: InputReader = new InputReader(System.in)\n var out: PrintWriter = new PrintWriter(System.out)\n\n def solve(): Any\n\n def main(args: Array[String]): Unit = {\n if (!isOnlineJudge) {\n in = new InputReader(new File(args(0)))\n out = new PrintWriter(new File(args(1)))\n }\n try solve() finally out.flush()\n }\n}\n\nclass InputReader(in: BufferedReader) {\n def this(file: File) = this(new BufferedReader(new FileReader(file)))\n def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))\n\n val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(\" \"))\n\n def nextLine(): String = in.readLine()\n def next(): String = tokens.next()\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextDouble(): Double = next().toDouble\n\n def repeat(n: Int = nextInt())(f: => Unit): Unit = (1 to n).foreach(_ => f)\n def nextSeq[A](n: Int = nextInt())(r: => A): Iterator[A] = Iterator.fill(n)(r)\n}\n"}, {"source_code": "object _1726A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val as = io.read[IndexedSeq[Int]]\n\n val ans = Seq(\n as.last - as.min,\n as.max - as.head,\n (as :+ as.head).sliding(2).map({case Seq(p, n) => n - p}).max\n ).max\n\n io.writeLine(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Utils]****************************************/\nobject Utils {\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int])(f)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}, {"source_code": "object _1726A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val as = io.read[IndexedSeq[Int]]\n val n = as.length\n\n val ans = Seq(\n as(n-1) - as.min,\n as.max - as(0),\n if (as.length > 1) as(n-2) - as(n-1) else -1\n ).max\n\n io.writeLine(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Utils]****************************************/\nobject Utils {\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int])(f)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}, {"source_code": "object _1726A extends CodeForcesApp {\n import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def solve(io: IO) = io.repeat {\n val as = io.read[IndexedSeq[Int]]\n\n val ans = Seq(\n as.last - as.min,\n as.max - as.head,\n (as ++ as).sliding(2).map({case Seq(p, n) => n - p}).max\n ).max\n\n io.writeLine(ans)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def solve(io: IO): Any\n def main(args: Array[String]): Unit = {\n val io = new IO(System.in, System.out)\n try solve(io) finally io.close()\n }\n}\n/****************************[Scala Utils]****************************************/\nobject Utils {\n def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n\n def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any*): this.type = writeAll(obj)\n def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = {printer.print(obj.mkString(separator)); this}\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n def repeat(f: => Unit): Unit = Utils.repeat(read[Int])(f)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n"}], "src_uid": "943ce230777aca97266c272bdb9b364c"} {"source_code": "import scala.io.StdIn.readInt\n\nobject Main extends App {\n val t = readInt()\n\n for (_ <- 1 to t) {\n val n = readInt()\n println((n + 1) / 2 - 1)\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Solution_A extends App {\n\n val T = StdIn.readInt()\n for (t <- 1 to T) {\n val N = StdIn.readInt()\n if (N <= 2) {\n println(\"0\")\n } else {\n println((N - 1) / 2)\n }\n }\n}\n"}, {"source_code": "\nobject Main extends App {\n import scala.io.StdIn._\n val t = readInt\n for(_ <- 0 until t) {\n val n = readInt()\n println((n - 1) >> 1)\n }\n}\n"}, {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val ans = 0 max (n - n / 2 - 1)\n println(ans)\n }\n}"}, {"source_code": "object A extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val ans = (n - 1) / 2\n println(ans)\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Main2 extends App {\n val testNumber = readInt()\n 0.until(testNumber)\n .map(_ => readInt())\n .map(n => (n-1) / 2)\n .foreach(println(_))\n}\n"}, {"source_code": "import java.io.PrintWriter\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\nimport util.control.Breaks._\n\nobject Solution {\n val reader = scala.io.StdIn\n def readInt(): Int = reader.readLine().toInt\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n def readString(): String = reader.readLine()\n\n def multiTest(f: Int => Unit): Unit = {\n val t = readInt()\n for (i <- 1 to t) f(i)\n }\n\n def GCD(a: Int, b: Int): Int = {\n if (a == 0) return b\n GCD(b % a, a)\n }\n\n def solve(t: Int): Unit = {\n val n = readInt()\n if (n % 2 == 0) println(n / 2 - 1)\n else println(n / 2)\n }\n\n def main(args: Array[String]) {\n multiTest(solve)\n //solve()\n }\n}"}], "negative_code": [], "src_uid": "b69170c8377623beb66db4706a02ffc6"} {"source_code": "import java.util.Scanner\nobject Circles {\n\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt();\n \n val rs = (1 to n) map (i=> scanner.nextInt())\n \n def main(args: Array[String]): Unit = {\n val sorted = rs sortWith( (a,b)=> a > b )\n val sum = (0.0/:(0 until(n,2))){(sum,r) => sum + Math.Pi*sorted(r)*sorted(r)}\n val ans = (sum/:(1 until(n,2))){(sum,r) => sum - Math.Pi*sorted(r)*sorted(r)}\n println(\"%.9f\".format(ans))\n }\n\n}", "positive_code": [{"source_code": "/**\n * Created by IntelliJ IDEA.\n * User: User\n * Date: 01.03.12\n * Time: 1:51\n * To change this template use File | Settings | File Templates.\n */\nobject B {\n def main(args: Array[String]) {\n val n = readInt()\n import math.{abs, Pi}\n println( Pi * abs(0 :: (readLine split ' ' map (_.toInt) sortBy (-_) toList) reduceLeft ((sum, x) => - sum + x * x)))\n\n }\n}\n\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n println(in.next().split(' ').map(_.toInt).sorted.reverse.foldLeft((0, 1)) {\n case ((sum, sign), i) => (sum + i * i * sign, -sign)\n }._1 * Math.PI)\n\n}\n"}, {"source_code": "object B {\n def main(args: Array[String]): Unit = {\n val lines = scala.io.Source.stdin.getLines().toList.tail.head.split(\" \").map(_ toDouble).toList.sort(_>_)\n println (lines.zip(Stream.continually(List(1,-1)).flatten).map ({ case (r,s) => scala.math.Pi * r * r * s}).sum)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val a = readLine().split(\" \").map(_.toLong).sorted.reverse\n val sum = a.zipWithIndex.map{ t => \n if (t._2 % 2 == 0) t._1 * t._1\n else -t._1 * t._1\n }.sum\n println(3.1415926535897932384626433832795f * sum)\n }\n}"}], "negative_code": [], "src_uid": "48b9c68380d3bd64bbc69d921a098641"} {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n for (_ <- 1 to t) {\n val n = nextInt\n var res = 0\n for (d <- 1L to 9L) {\n var dd = d\n while (dd <= n) {\n dd = 10 * dd + d\n res += 1\n }\n }\n out.println(res)\n }\n\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) = {\n val t = readInt\n (0 until t).foreach((x) => f1)\n }\n def f1(): Unit = { \n val n = readLong\n val (k, c) = aux(0, n)\n val j = (0 until k).foldLeft(1.toLong){\n case (i, _) => i * 10 + 1\n }\n val r = if (j * c <= n) (9 * k) + c else (9 * k) + c - 1\n println(r)\n }\n\n def aux(i: Long, n: Long): (Int, Long) = {\n if (n < 10) (i.toInt, n) else aux(i + 1, n / 10)\n }\n }"}], "negative_code": [], "src_uid": "99a5b21a5984d5248e82f843f82e9420"} {"source_code": "object A extends App {\r\n\r\n def consecutiveSumRiddle(n: Long): (Long, Long) = (-n + 1, n)\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextLong()\r\n val (l, r) = consecutiveSumRiddle(n)\r\n\r\n out.println(s\"$l $r\")\r\n }\r\n\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject sample extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class myType(var social: Int, var cp: Int, var ind: Int)extends Ordered[myType] {\n override def compare(that: myType): Int = {\n if (social < that.social)\n return -1\n else if (social == that.social)\n return 0\n else\n return 1\n }\n }\n\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readLong()\n writer.print(-1L * n + 1L)\n writer.print(' ')\n writer.println(n)\n }\n writer.flush()\n}\n"}], "negative_code": [{"source_code": "object A extends App {\r\n\r\n def consecutiveSumRiddle(n: Long): (Long, Long) = {\r\n val l = n / 2\r\n val r = l + n % 2\r\n (l - 1, r + 1)\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextLong()\r\n val (l, r) = consecutiveSumRiddle(n)\r\n\r\n out.println(s\"$l $r\")\r\n }\r\n\r\n out.flush()\r\n\r\n final object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}], "src_uid": "a4628208668e9d838cd019e9dc03e470"} {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val t = nextInt\n val ress = Array.ofDim[Int](t)\n for (i <- 0 until t) {\n val n = nextLong\n var a = 3L\n var b = (a * a - 1) / 2\n var c = a * a - b\n var res = 0\n while (c <= n) {\n// println(a, b, c)\n a += 2\n val aa = a * a\n b = (aa - 1) >> 1\n c = aa - b\n res += 1\n }\n\n ress(i) = res\n }\n out.println(ress.mkString(\"\\n\"))\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "\r\nobject D {\r\n import scala.io.{StdIn => in}\r\n\r\n def main(args: Array[String]): Unit = {\r\n val tests = in.readInt()\r\n (1 to tests).foreach { _ =>\r\n val n = in.readInt()\r\n var cnt = 0\r\n var i = 3\r\n while ((i * i + 1) / 2 <= n) {\r\n cnt += 1\r\n i += 2\r\n }\r\n println(cnt)\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "31064ad58b7802c32b3c51137057b6f5"} {"source_code": "import scala.math.min \nimport java.io.BufferedReader\nimport java.io.IOException\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\nobject Sample{\n\tdef func(i: Int,x: Int,y: Int,z: Int,s: String): Int = {\n\t\tif(i%3==x && s(i)!='R')\n\t\t\treturn 1\n\t\tif(i%3==y && s(i)!='G')\n\t\t\treturn 1\n\t\tif(i%3==z && s(i)!='B')\n\t\t\treturn 1\n\t\treturn 0\n\t}\n\tdef typ(k: Int,n: Int,x: Int,y: Int,z: Int,s: String): Int = {\n\t\tvar c = 0;var c1 = 0;var i =0;var j = 0\n\t\tc=n\n\t\tfor(i <- 0 to k-1)\n\t\t{\n\t\t\tc1+=func(i,x,y,z,s)\n\t\t}\n\t\tc=min(c,c1)\n\t\ti = 0\n\t\tj = k\n\t\twhile(j < n)\n\t\t{\n\t\t\tc1+=func(j,x,y,z,s)\n\t\t\tc1-=func(i,x,y,z,s)\n\t\t\tc = min(c,c1)\n\t\t\tj+=1\n\t\t\ti+=1\n\t\t}\n\t\treturn c\n\t}\n\tdef main(args: Array[String]) = {\n\t\tvar br = new BufferedReader(new InputStreamReader(System.in));\n \tvar st = new StringTokenizer(br.readLine());\n\t\tvar t: Int = st.nextToken().toInt\n\t\t\n\t\twhile(t>0)\n\t\t{\n\t\t\tt-=1\n\t\t\tvar a: Array[String] = br.readLine().split(\" \")\n\t\t\tval n: Int = a(0).toInt\n\t\t\tval k: Int = a(1).toInt\n\t\t\tvar s = br.readLine()\n\t\t\tvar ans: Int = n\n\t\t\tvar i: Int = 0\n\t\t\tvar j: Int = 0\n\t\t\t//RGB\n\t\t\tans=min(ans,typ(k,n,0,1,2,s))\n\t\t\t//BRG\n\t\t\tans=min(ans,typ(k,n,1,2,0,s))\n\t\t\t//GBR\n\t\t\tans=min(ans,typ(k,n,2,0,1,s))\n\t\t\tprintln(ans)\n\t\t}\n\t}\n}\n", "positive_code": [{"source_code": "object Main {\n import scala.util.control.Breaks.{breakable,break}\n import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue}\n import java.io._\n\n val in = new InputReader(System.in)\n val pw = new PrintWriter(System.out)\n\n def main (args: Array[String]){\n\n val q = in.next().toInt\n for (_ <- 1 to q) {\n val n, k = in.next().toInt\n val s = \"0\" + in.next()\n\n def calc(c: Array[Char]): Int = {\n val imos = new Array[Int](n+1)\n for (i <- 1 to n)\n if (s(i) != c((i-1) % 3))\n imos(i) = 1\n\n for (i <- 2 to n)\n imos(i) += imos(i-1)\n\n var res = Int.MaxValue\n for (i <- k to n) {\n val now = imos(i) - imos(i-k)\n res = Math.min(res, now)\n }\n\n res\n }\n\n var ans = Int.MaxValue\n\n {\n val c = Array('R', 'G', 'B')\n ans = Math.min(ans, calc(c))\n }\n\n {\n val c = Array('G', 'B', 'R')\n ans = Math.min(ans, calc(c))\n }\n\n {\n val c = Array('B', 'R', 'G')\n ans = Math.min(ans, calc(c))\n }\n\n pw.println(ans)\n }\n\n pw.flush()\n }\n}\n\nimport java.io._\nclass InputReader(stream: InputStream) {\n import java.util.StringTokenizer\n\n private val reader = new BufferedReader(new InputStreamReader(stream))\n private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())\n def next(): String = {\n while (!tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine())\n }\n tokenizer.nextToken()\n }\n}\n"}, {"source_code": "object Main {\n import scala.util.control.Breaks.{breakable,break}\n import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue}\n import java.io._\n\n val in = new InputReader(System.in)\n val pw = new PrintWriter(System.out)\n\n def main (args: Array[String]){\n\n val q = in.next().toInt\n for (_ <- 1 to q) {\n val n, k = in.next().toInt\n val s = \"0\" + in.next()\n\n def calc(c: Array[Char]): Int = {\n val imos = new Array[Int](n+1)\n for (i <- 1 to n)\n if (s(i) != c((i-1) % 3))\n imos(i) = 1\n\n for (i <- 2 to n)\n imos(i) += imos(i-1)\n\n var res = Int.MaxValue\n for (i <- k to n) {\n val now = imos(i) - imos(i-k)\n res = Math.min(res, now)\n }\n\n res\n }\n\n var ans = Int.MaxValue\n\n {\n val c = Array('R', 'G', 'B')\n ans = Math.min(ans, calc(c))\n }\n\n {\n val c = Array('G', 'B', 'R')\n ans = Math.min(ans, calc(c))\n }\n\n {\n val c = Array('B', 'R', 'G')\n ans = Math.min(ans, calc(c))\n }\n\n pw.println(ans)\n }\n\n pw.flush()\n }\n}\n\nimport java.io._\nclass InputReader(stream: InputStream) {\n import java.util.StringTokenizer\n\n private val reader = new BufferedReader(new InputStreamReader(stream))\n private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())\n def next(): String = {\n while (!tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine())\n }\n tokenizer.nextToken()\n }\n}\n"}, {"source_code": "import java.util.Scanner;\nimport scala.math.min \n\nobject Sample{\n\tdef func(i: Int,x: Int,y: Int,z: Int,s: String): Int = {\n\t\tif(i%3==x && s(i)!='R')\n\t\t\treturn 1\n\t\tif(i%3==y && s(i)!='G')\n\t\t\treturn 1\n\t\tif(i%3==z && s(i)!='B')\n\t\t\treturn 1\n\t\treturn 0\n\t}\n\tdef typ(k: Int,n: Int,x: Int,y: Int,z: Int,s: String): Int = {\n\t\tvar c = 0;var c1 = 0;var i =0;var j = 0\n\t\tc=n\n\t\tfor(i <- 0 to k-1)\n\t\t{\n\t\t\tc1+=func(i,x,y,z,s)\n\t\t}\n\t\tc=min(c,c1)\n\t\ti = 0\n\t\tj = k\n\t\twhile(j < n)\n\t\t{\n\t\t\tc1+=func(j,x,y,z,s)\n\t\t\tc1-=func(i,x,y,z,s)\n\t\t\tc = min(c,c1)\n\t\t\tj+=1\n\t\t\ti+=1\n\t\t}\n\t\treturn c\n\t}\n\tdef main(args: Array[String]) = {\n\t\tvar scanner = new Scanner(System.in)\n\t\tvar t: Int = scanner.nextLine().toInt\n\t\t\n\t\twhile(t>0)\n\t\t{\n\t\t\tt-=1\n\t\t\tvar a: Array[String] = scanner.nextLine().split(\" \")\n\t\t\tval n: Int = a(0).toInt\n\t\t\tval k: Int = a(1).toInt\n\t\t\tvar s = scanner.nextLine()\n\t\t\tvar ans: Int = n\n\t\t\tvar i: Int = 0\n\t\t\tvar j: Int = 0\n\t\t\t//RGB\n\t\t\tans=min(ans,typ(k,n,0,1,2,s))\n\t\t\t//BRG\n\t\t\tans=min(ans,typ(k,n,1,2,0,s))\n\t\t\t//GBR\n\t\t\tans=min(ans,typ(k,n,2,0,1,s))\n\t\t\tprintln(ans)\n\t\t}\n\t\tscanner.close();\n\t}\n}\n"}, {"source_code": "object _1196D1 extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val inputs = io.read[Seq[(Int, Int, String)]]\n\n val rgb = \"RGB\"\n val rgbStream = Stream.from(0).map(i => rgb(i%3))\n\n inputs foreach { case (n, k, s) =>\n val target: Seq[String] = (1 to 3).map(i => rgbStream.slice(i, i + k).mkString)\n\n var ans = k\n val seen = mutable.Set.empty[String]\n\n for {\n i <- s.indices if i <= n - k\n sub = s.substring(i, i + k) if !seen(sub)\n t <- target\n } {\n seen += sub\n ans = ans min diff(sub, t)\n }\n io.writeLine(ans)\n }\n\n io\n }\n\n def diff(a: String, b: String) =\n a.zip(b).count({case (u, v) => u != v})\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = \"\\n\")\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "1aa8f887eb3b09decb223c71b40bb25b"} {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject C_310 { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n is = new ByteArrayInputStream(Test.t6.trim.getBytes(\"ISO-8859-1\"))\n debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n val k = line1.int\n \n class Group() {\n var lis = List[Int]()\n var size = 0;\n var firstGroup = true\n override def toString() = lis.mkString(\",\")\n def add(el:Int) = {\n if (lis == Nil && el != 1) {\n firstGroup = false\n }\n if (lis != Nil && lis.head+1 != el) {\n firstGroup = false\n }\n lis +:= el\n size += 1\n }\n }\n \n var groups = List[Group]()\n var splits = 0\n \n for (i <- 0 until k) {\n val cLine = readLine\n val lineSize = cLine.int\n var gr = new Group()\n groups +:= gr\n var lastEl = -1 \n for(j <- 0 until lineSize) {\n val el = cLine.int \n if (lastEl != -1 && lastEl + 1 != el){\n gr = new Group()\n groups +:= gr\n splits += 1\n }\n gr.add (el)\n lastEl = el\n }\n }\n \n db(\"splits \" + splits)\n \n val joins = groups.foldLeft(-1)((y:Int, x:Group) => 1 + y)\n db(\"loins \" + joins)\n val rejoins = groups.foldLeft(0)((y:Int, x:Group) => if (!x.firstGroup) {(x.size-1)*2 + y} else {y})\n db(\"rejoins \" + rejoins)\n \n val res = splits + joins + rejoins\n println(res)\n \n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n \n //---------------------------- service code ----------------------------------\n\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n \n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n7 3\n3 1 3 7\n2 2 5\n2 4 6\n\"\"\"\n\nval t5 = \"\"\"\n5 3\n1 4\n3 1 2 3\n1 5\n\"\"\"\n\nval t6 = \"\"\"\n8 5\n2 1 2\n2 3 4\n1 5\n2 6 7\n1 8\n\n\"\"\"\n\n}\n\n}\n", "positive_code": [{"source_code": "object _556C extends CodeForcesApp[Int] {\n import java.util.Scanner\n import scala.annotation.tailrec, scala.collection.mutable\n import CodeForcesApp._\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val n = nextInt\n val chains = Seq.fill(nextInt)(Seq.fill(nextInt)(nextInt))\n val cost = chains map {chain =>\n val increasingPrefix = chain.zipWithIndex prefixLength {case (a, i) => a == i+1}\n debug(chain, increasingPrefix)\n chain.length - (2*increasingPrefix max 1)\n }\n cost.sum + n\n }\n}\n\nabstract class CodeForcesApp[A] {\n import java.util.Scanner\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solve(scanner))\n def solve(scanner: Scanner): A\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n\nobject CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n val modulus = 1000000007\n def when[A](condition: Boolean)(f: => A) = if (condition) Some(f) else None\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n}\n"}, {"source_code": "object _556C extends CodeForcesApp {\n import CodeForcesApp._, scala.annotation.tailrec, scala.collection.mutable\n\n override type Input = (Int, Seq[Seq[Int]])\n override type Output = Int\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n (nextInt, Seq.fill(nextInt)(Seq.fill(nextInt)(nextInt)))\n }\n\n override def solve(input: Input) = {\n val (n, chains) = input\n var m = 0\n val unchained = chains map {chain =>\n val increasingPrefix = chain.zipWithIndex prefixLength {case (a, i) => a == i+1}\n m = m max increasingPrefix\n val k = chain.length\n val r = if (increasingPrefix > 1) k - increasingPrefix else k - 1\n r\n }\n unchained.sum + (n - m)\n }\n\n override def format(result: Output) = super.format(result)\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n import CodeForcesApp._\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n/********************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n}\n/**********************************[ lib ]************************************/\nobject CodeForcesApp {\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = collection.mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type ==>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A) = if (condition) Some(f) else None\n/*******************************[ constants ]*********************************/\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n val modulus = 1000000007\n}\n"}, {"source_code": "object A{\n //import scala.collection.mutable.PriorityQueue\n //import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val n=nextInt\n val k=nextInt\n var p=0\n\n for(i<-0 until k){\n val m=nextInt\n for(j<-0 until m){\n if(j==nextInt-1){\n p=j+1\n }\n }\n\n }\n out.println(2*n-(k-1)-2*p)\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "import scala.annotation.tailrec, scala.collection.mutable\nimport CodeForcesApp._\nobject _556C extends CodeForcesApp[Int]({scanner => import scanner._\n val n = nextInt\n val chains = Seq.fill(nextInt)(Seq.fill(nextInt)(nextInt))\n chains.foldLeft(n) {case (cost, chain) =>\n val increasingPrefix = chain.zipWithIndex prefixLength {case (a, i) => a == i+1}\n cost + chain.length - (2*increasingPrefix max 1)\n }\n})\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n val modulus: Int = 1000000007\n def when[A](x: Boolean)(f: => A): Option[A] = if (x) Some(f) else None\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n}\n"}], "negative_code": [{"source_code": "object _556C extends CodeForcesApp {\n import CodeForcesApp._, scala.annotation.tailrec, scala.collection.mutable\n\n override type Input = Seq[Seq[Int]]\n override type Output = Int\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n val (n, k) = (nextInt, nextInt)\n Seq.fill(k){Seq.fill(nextInt)(nextInt)}\n }\n\n override def solve(input: Input) = {\n val unchained = input map {chain =>\n val increasingPrefix = (chain.zip(chain.tail) prefixLength {case (a, b) => a == b-1}) + 1\n val cost = chain.length - increasingPrefix\n cost + cost + 1\n }\n unchained.sum - 1\n }\n\n override def format(result: Output) = super.format(result)\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n import CodeForcesApp._\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n/********************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n}\n/**********************************[ lib ]************************************/\nobject CodeForcesApp {\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = collection.mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type ==>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A) = if (condition) Some(f) else None\n/*******************************[ constants ]*********************************/\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n val modulus = 1000000007\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject C_310 { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n // is = new ByteArrayInputStream(Test.sa1.trim.getBytes(\"ISO-8859-1\"))\n // debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n val k = line1.int\n \n class Group() {\n var lis = List[Int]()\n override def toString() = lis.mkString(\",\")\n }\n \n var groups = List[Group]()\n var splits = 0\n \n for (i <- 0 until k) {\n val cLine = readLine\n val lineSize = cLine.int\n var gr = new Group()\n groups :+= gr\n var lastEl = -1 \n for(j <- 0 until lineSize) {\n val el = cLine.int \n if (lastEl != -1 && lastEl + 1 != el){\n gr = new Group()\n groups :+= gr\n splits += 1\n }\n gr.lis :+= el\n lastEl = el\n }\n }\n \n db(\"splits \" + splits)\n \n val joins = groups.foldLeft(-1)((y:Int, x:Group) => 1 + y)\n println(splits + joins)\n \n \n \n\n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n \n //---------------------------- service code ----------------------------------\n\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n \n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n7 3\n3 1 3 7\n2 2 5\n2 4 6\n\"\"\"\n\n}\n\n}\n"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n\nobject C_310 { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n is = new ByteArrayInputStream(Test.t6.trim.getBytes(\"ISO-8859-1\"))\n debugV = true\n\n\n //---------------------------- parameters reading --------------------------\n br = setupInputOutput(); \n val line1 = readLine\n val n = line1.int\n val k = line1.int\n \n class Group() {\n var lis = List[Int]()\n var size = 0;\n override def toString() = lis.mkString(\",\")\n def add(el:Int) = {\n lis :+= el\n size += 1\n }\n }\n \n var groups = List[Group]()\n var splits = 0\n \n for (i <- 0 until k) {\n val cLine = readLine\n val lineSize = cLine.int\n var gr = new Group()\n groups :+= gr\n var lastEl = -1 \n for(j <- 0 until lineSize) {\n val el = cLine.int \n if (lastEl != -1 && lastEl + 1 != el){\n gr = new Group()\n groups :+= gr\n splits += 1\n }\n gr.add (el)\n lastEl = el\n }\n }\n \n db(\"splits \" + splits)\n \n val joins = groups.foldLeft(-1)((y:Int, x:Group) => 1 + y)\n db(\"loins \" + joins)\n val rejoins = groups.tail.foldLeft(0)((y:Int, x:Group) => (x.size-1)*2 + y)\n db(\"rejoins \" + rejoins)\n \n val res = splits + joins + rejoins\n println(res)\n \n \n //---------------------------- parameters reading end ----------------------\n\n }\n\n \n //---------------------------- service code ----------------------------------\n\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n \n }\n \n var debugV = false\n var is = System.in\n var br = setupInputOutput(); \n def db(x: => String) = if (debugV) println(x) // nullary function\n def setupInputOutput(): BufferedReader = {\n val devEnv = this.getClass.getCanonicalName.contains(\".\")\n if (!devEnv) {\n is = System.in\n debugV = false\n }\n val bis = new BufferedInputStream(is);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n7 3\n3 1 3 7\n2 2 5\n2 4 6\n\"\"\"\n\nval t6 = \"\"\"\n8 5\n2 1 2\n2 3 4\n1 5\n2 6 7\n1 8\n\n\"\"\"\n\n}\n\n}\n"}], "src_uid": "6590c99e35f6f65e1b1bbd4f5bdca43a"} {"source_code": "object P5E {\n class Deque[T : reflect.ClassTag](n : Int) {\n val a = {\n val size = 1 << Math.getExponent((n + 1).toFloat) + 1\n Array.ofDim[T](size)\n }\n val m = a.size - 1\n var (p1, p2) = (0, -1)\n def head = a(p1)\n def last = a(p2)\n def popHead {p1 = p1 + 1 & m}\n def popLast {p2 = p2 - 1 & m}\n def pushLast(x : T) {p2 = p2 + 1 & m; a(p2) = x}\n def size = p2 - p1 + m + 2 & m\n def apply(n : Int) = a(p1 + n & m)\n def nonEmpty = size != 0\n }\n\n def main(args: Array[String]) {\n val n = readLine.toInt\n val a = readLine split ' ' map {_.toInt}\n var answer = 0L\n for (a <- Array(a, a.reverse)) {\n case class Node(x : Int, i : Int, r : Int)\n val s = new Deque[Node](n)\n for (i <- 0 to n - 1) {\n val x = a(i)\n while (s.nonEmpty && s.last.x < x) s.popLast\n val r = if (s.nonEmpty && s.last.x == x) s.last.r else 0\n s pushLast Node(x, i, r + 1)\n }\n for (i <- 0 to n - 1) yield {\n while (s.nonEmpty && s.head.i <= i) s.popHead\n val x = a(i)\n while (s.nonEmpty && s.last.x < x) {\n s.popLast\n answer = answer + 2\n }\n val r = if (s.nonEmpty && s.last.x == x) s.last.r else 0\n answer = answer + (r min s.size)\n s pushLast Node(x, n, r + 1)\n }\n }\n val v = {\n val a1 = a.max\n val z1 = a count {_ == a1}\n if (z1 > 1) z1.toLong * (z1 - 1) >>> 1 else {\n val b = a filter {_ != a1}\n val a2 = b.max\n b count {_ == a2}\n }\n }\n println((answer >>> 1) - v)\n }\n}\n", "positive_code": [{"source_code": "object P5E {\n def main(args: Array[String]) {\n val n = readLine.toInt\n val a = readLine split ' ' map {_.toInt}\n var answer = 0L\n for (a <- Array(a, a.reverse)) {\n case class Node(x : Int, i : Int, r : Int)\n val s = new java.util.ArrayDeque[Node]\n for (i <- 0 to n - 1) {\n val x = a(i)\n while (!s.isEmpty && s.getLast.x < x) s.removeLast\n val r = if (!s.isEmpty && s.getLast.x == x) s.getLast.r else 0\n s addLast Node(x, i, r + 1)\n }\n for (i <- 0 to n - 1) yield {\n while (!s.isEmpty && s.getFirst.i <= i) s.removeFirst\n val x = a(i)\n while (!s.isEmpty && s.getLast.x < x) {\n s.removeLast\n answer = answer + 2\n }\n val r = if (!s.isEmpty && s.getLast.x == x) s.getLast.r else 0\n answer = answer + (r min s.size)\n s addLast Node(x, n, r + 1)\n }\n }\n val v = {\n val a1 = a.max\n val z1 = a count {_ == a1}\n if (z1 > 1) z1.toLong * (z1 - 1) >>> 1 else {\n val b = a filter {_ != a1}\n val a2 = b.max\n b count {_ == a2}\n }\n }\n println((answer >>> 1) - v)\n }\n}\n"}, {"source_code": "object P5E {\n def main(args: Array[String]) {\n val n = readLine.toInt\n val tk = new java.util.StringTokenizer(readLine)\n val a = Array.fill(n){tk.nextToken.toInt}\n var answer = 0L\n for (a <- Array(a, a.reverse)) {\n case class Node(x : Int, i : Int, r : Int)\n val s = new java.util.ArrayDeque[Node]\n for (i <- 0 to n - 1) {\n val x = a(i)\n while (!s.isEmpty && s.getLast.x < x) s.removeLast\n val r = if (!s.isEmpty && s.getLast.x == x) s.getLast.r else 0\n s addLast Node(x, i, r + 1)\n }\n for (i <- 0 to n - 1) yield {\n while (!s.isEmpty && s.getFirst.i <= i) s.removeFirst\n val x = a(i)\n while (!s.isEmpty && s.getLast.x < x) {\n s.removeLast\n answer = answer + 2\n }\n val r = if (!s.isEmpty && s.getLast.x == x) s.getLast.r else 0\n answer = answer + (r min s.size)\n s addLast Node(x, n, r + 1)\n }\n }\n val v = {\n val a1 = a.max\n val z1 = a count {_ == a1}\n if (z1 > 1) z1.toLong * (z1 - 1) >>> 1 else {\n val b = a filter {_ != a1}\n val a2 = b.max\n b count {_ == a2}\n }\n }\n println((answer >>> 1) - v)\n }\n}\n"}, {"source_code": "object P5E {\n def main(args: Array[String]) {\n val sc = new java.util.Scanner(System.in)\n val n = sc.next.toInt\n val a = Array.fill(n){sc.next.toInt}\n var answer = 0L\n for (a <- Array(a, a.reverse)) {\n case class Node(x : Int, i : Int, r : Int)\n val s = new java.util.ArrayDeque[Node]\n for (i <- 0 to n - 1) {\n val x = a(i)\n while (!s.isEmpty && s.getLast.x < x) s.removeLast\n val r = if (!s.isEmpty && s.getLast.x == x) s.getLast.r else 0\n s addLast Node(x, i, r + 1)\n }\n for (i <- 0 to n - 1) yield {\n while (!s.isEmpty && s.getFirst.i <= i) s.removeFirst\n val x = a(i)\n while (!s.isEmpty && s.getLast.x < x) {\n s.removeLast\n answer = answer + 2\n }\n val r = if (!s.isEmpty && s.getLast.x == x) s.getLast.r else 0\n answer = answer + (r min s.size)\n s addLast Node(x, n, r + 1)\n }\n }\n val v = {\n val a1 = a.max\n val z1 = a count {_ == a1}\n if (z1 > 1) z1.toLong * (z1 - 1) >>> 1 else {\n val b = a filter {_ != a1}\n val a2 = b.max\n b count {_ == a2}\n }\n }\n println((answer >>> 1) - v)\n }\n}\n"}], "negative_code": [{"source_code": "object P5E {\n class Deque[T : reflect.ClassTag](n : Int) {\n val a = {\n val size = 1 << Math.getExponent((n + 1).toFloat) + 1\n Array.ofDim[T](size)\n }\n val m = a.size - 1\n var (p1, p2) = (0, -1)\n def head = a(p1)\n def last = a(p2)\n def popHead {p1 = p1 + 1 & m}\n def popLast {p2 = p2 - 1 & m}\n def pushLast(x : T) {p2 = p2 + 1 & m; a(p2) = x}\n def size = p2 - p1 + m + 2 & m\n def apply(n : Int) = a(p1 + n & m)\n def nonEmpty = size != 0\n }\n\n def main(args: Array[String]) {\n val n = readLine.toInt\n val a = readLine split \" \" map {_.toInt}\n if (n == 1000000) return\n var answer = 0L\n for (a <- Array(a, a.reverse)) {\n case class Node(x : Int, i : Int, r : Int)\n val s = new Deque[Node](n)\n for (i <- 0 to n - 1) {\n val x = a(i)\n while (s.nonEmpty && s.last.x < x) s.popLast\n val r = if (s.nonEmpty && s.last.x == x) s.last.r else 0\n s pushLast Node(x, i, r + 1)\n }\n for (i <- 0 to n - 1) yield {\n while (s.nonEmpty && s.head.i <= i) s.popHead\n val x = a(i)\n while (s.nonEmpty && s.last.x < x) {\n s.popLast\n answer = answer + 2\n }\n val r = if (s.nonEmpty && s.last.x == x) s.last.r else 0\n answer = answer + (r min s.size)\n s pushLast Node(x, n, r + 1)\n }\n }\n val v = {\n val a1 = a.max\n val z1 = a count {_ == a1}\n if (z1 > 1) z1.toLong * (z1 - 1) >>> 1 else {\n val b = a filter {_ != a1}\n val a2 = b.max\n b count {_ == a2}\n }\n }\n println((answer >>> 1) - v)\n }\n}\n"}, {"source_code": "object P5E {\n class Deque[T : reflect.ClassTag](n : Int) {\n val a = {\n val size = 1 << Math.getExponent((n + 1).toFloat) + 1\n Array.ofDim[T](size)\n }\n val m = a.size - 1\n var (p1, p2) = (0, -1)\n def head = a(p1)\n def last = a(p2)\n def popHead {p1 = p1 + 1 & m}\n def popLast {p2 = p2 - 1 & m}\n def pushLast(x : T) {p2 = p2 + 1 & m; a(p2) = x}\n def size = p2 - p1 + m + 2 & m\n def apply(n : Int) = a(p1 + n & m)\n def nonEmpty = size != 0\n }\n\n def main(args: Array[String]) {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n val a = Array.fill(n){sc.nextInt}\n if (n == 1000000) return\n var answer = 0L\n for (a <- Array(a, a.reverse)) {\n case class Node(x : Int, i : Int, r : Int)\n val s = new Deque[Node](n)\n for (i <- 0 to n - 1) {\n val x = a(i)\n while (s.nonEmpty && s.last.x < x) s.popLast\n val r = if (s.nonEmpty && s.last.x == x) s.last.r else 0\n s pushLast Node(x, i, r + 1)\n }\n for (i <- 0 to n - 1) yield {\n while (s.nonEmpty && s.head.i <= i) s.popHead\n val x = a(i)\n while (s.nonEmpty && s.last.x < x) {\n s.popLast\n answer = answer + 2\n }\n val r = if (s.nonEmpty && s.last.x == x) s.last.r else 0\n answer = answer + (r min s.size)\n s pushLast Node(x, n, r + 1)\n }\n }\n val v = {\n val a1 = a.max\n val z1 = a count {_ == a1}\n if (z1 > 1) z1.toLong * (z1 - 1) >>> 1 else {\n val b = a filter {_ != a1}\n val a2 = b.max\n b count {_ == a2}\n }\n }\n println((answer >>> 1) - v)\n }\n}\n"}], "src_uid": "e32328aaeeea789e993d09335764c021"} {"source_code": "object A580 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n\n var res = 1\n var i = 1\n var curr = 1\n while(i < n) {\n if(input(i-1) <= input(i)) {\n curr += 1\n } else {\n curr = 1\n }\n res = math.max(res, curr)\n i += 1\n }\n println(res)\n }\n}", "positive_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject Main extends App {\n readInt()\n val a = readLine().split(\" \").map(_.toInt).toList\n val ans = solve(a, 0)\n println(ans)\n \n @tailrec\n def solve(l: List[Int], ans: Int): Int = l match {\n case Nil => ans\n case x :: xs =>\n var prev = x\n val (before, after) = l.span { e =>\n val res = prev <= e\n prev = e\n res\n }\n solve(after, math.max(ans, before.length))\n }\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.Source\n\nobject Main extends App {\n val in = Source.stdin.getLines()\n in.next()\n val a = in.next().split(\" \").map(_.toInt).toList\n val ans = solve(a, 0)\n println(ans)\n \n @tailrec\n def solve(l: List[Int], ans: Int): Int = l match {\n case Nil => ans\n case x :: xs =>\n var prev = x\n val (before, after) = l.span { e =>\n val res = prev <= e\n prev = e\n res\n }\n solve(after, math.max(ans, before.length))\n }\n}"}, {"source_code": "/**\n * @author netman\n */\n\n\nimport java.io._\nimport scala._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\n\nobject HelloWorld {\n\n class InputReader(reader: BufferedReader) {\n \n var tokenizer: StringTokenizer = null;\n \n def this(stream: InputStream) = {\n this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));\n }\n \n def this(f: File) = {\n this(new BufferedReader(new FileReader(f), (1 << 20)));\n }\n \n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n tokenizer = new StringTokenizer(reader.readLine());\n }\n return tokenizer.nextToken();\n }\n \n def nextInt(): Int = next().toInt\n \n def nextDouble(): Double = next().toDouble\n \n def close() = reader.close();\n }\n \n class OutputWriter(writer: PrintWriter) {\n def this(stream: OutputStream) {\n this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));\n }\n \n def this(f: File) = {\n this(new PrintWriter(new BufferedWriter(new FileWriter(f))));\n }\n \n def print(x: Any) = writer.print(x);\n \n def println(x: Any) = writer.println(x);\n \n def close() = writer.close();\n }\n \n \n val in = new InputReader(System.in)\n val out = new OutputWriter(System.out)\n \n def main(args: Array[String]): Unit = {\n val n = in.nextInt\n \n var a = new Array[Int](n)\n \n for (i <- 0 until n) {\n a(i) = in.nextInt\n }\n \n var res = 0\n \n var cur = 0\n \n for (i <- 0 until n) {\n if (i == 0 || a(i - 1) <= a(i)) {\n cur += 1\n }\n else {\n cur = 1\n }\n res = math.max(res, cur)\n }\n \n \n out.println(res)\n \n out.close\n }\n}"}, {"source_code": "\nobject Solution {\n\n def main(args: Array[String]) {\n val n = readLine().toInt\n val a = readLine().split(\" \").map(s => s.toInt)\n val result = a.foldLeft((0,0,0)) {\n (prevPair, current) =>\n if (current >= prevPair._1)\n (current, prevPair._2 + 1, math.max(prevPair._3, prevPair._2 + 1))\n else\n (current, 1, prevPair._3)\n }._3\n println(result)\n }\n}"}, {"source_code": "//package round321.a\n\nimport java.util.Scanner\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n\n val a = for(_ <- 0 until n) yield sc.nextInt\n\n var max = 1\n var cur = 1\n for(i <- 1 until n) {\n if(a(i) < a(i - 1)) {\n cur = 1\n } else {\n cur += 1\n }\n max = Math.max(max, cur)\n }\n\n println(max)\n}\n\n"}, {"source_code": "// So you like object Task\nimport java.io.{IOException, InputStream, PrintWriter}\nimport java.util.InputMismatchException\n\nobject Task {\n\n\n def solve(in: InputReader, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val a = Array.fill(n) { in.nextInt() }\n var count = 0\n var answer = 0\n for (i <- 0 until n) {\n if (i > 0 && a(i) < a(i - 1)) {\n count = 0\n }\n count += 1\n answer = answer max count\n\n }\n\n println(answer)\n\n }\n\n def main(args: Array[String]) {\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n solve(in, out)\n\n in.close()\n out.close()\n }\n}\n\nclass InputReader(val inputStream: InputStream) {\n val buf = new Array[Byte](1 << 16)\n var curChar = 0\n var numChars = 0\n\n def read(): Int = {\n if (numChars == -1) {\n throw new InputMismatchException()\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => throw new InputMismatchException()\n }\n if (numChars <= 0)\n return -1\n }\n curChar += 1\n buf(curChar - 1)\n }\n\n def peek(): Int = {\n if (numChars == -1) {\n return -1\n }\n if (curChar >= numChars) {\n curChar = 0\n try {\n numChars = inputStream.read(buf)\n } catch {\n case _: IOException => return -1\n }\n if (numChars <= 0)\n return -1\n }\n buf(curChar)\n }\n\n def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1\n\n def nextInt(): Int = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def nextLong(): Long = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n var sgn = 1\n if (c == '-') {\n sgn = -1\n c = read()\n }\n var res = 0l\n do {\n if (c < '0' || c > '9')\n throw new InputMismatchException()\n res *= 10\n res += c & 15\n c = read()\n } while (!isSpaceChar(c))\n res * sgn\n }\n\n def next(): String = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n val res = new StringBuilder()\n do {\n res += c.toChar\n c = read()\n } while(!isSpaceChar(c))\n res.toString()\n }\n\n def nextChar(): Char = {\n var c = read()\n while (isSpaceChar(c)) c = read()\n c.toChar\n }\n\n //noinspection AccessorLikeMethodIsEmptyParen\n def hasNext(): Boolean = {\n var value = peek()\n do {\n read()\n value = peek()\n } while (isSpaceChar(value) && value != -1)\n value != -1\n }\n\n def rawNextLine(): String = {\n val builder = new StringBuilder\n var c = read()\n while (c != '\\n' && c != -1) {\n if (c != '\\r')\n builder += c.toChar\n c = read()\n }\n builder.toString()\n }\n\n def nextLine(): String = {\n var s = rawNextLine()\n while (s.trim().length == 0) s = rawNextLine()\n s\n }\n\n def nextDouble(): Double = {\n next().toDouble\n }\n\n def close(): Unit = {\n inputStream.close()\n }\n}\n"}, {"source_code": "\n\nobject KefaAndFirstSteps {\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in);\n\t\tval n = scanner.nextInt;\n\t\tval sequence = scanner.nextLine;\n\t\tvar localMax = 0;\n\t\tvar globalMax = -1;\n\t\tvar previous = - 1;\n\t\tfor (i <- 1 to n) {\n\t\t\tval elt = scanner.nextInt();\n\t\t\tif (elt >= previous) {\n\t\t\t\tlocalMax += 1;\n\t\t\t\tif (localMax > globalMax) {\n\t\t\t\t\tglobalMax = localMax\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlocalMax = 1\n\t\t\t}\n\t\t\tprevious = elt\n\t\t}\n\t\tprintln(globalMax)\n\t}\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\nobject Solution extends App {\n val days = StdIn.readInt()\n val allIncomes = StdIn.readLine().split(\" \").map(_.toInt).toList\n\n val result = longestIncreasingSubsegment(allIncomes)\n\n System.out.println(result)\n\n def longestIncreasingSubsegment(input: List[Int]) = {\n var maxLen = 1\n var len = 0\n var prev = 0\n input.foreach(x => {\n if (x >= prev) {\n len += 1\n } else {\n if (len > maxLen)\n maxLen = len\n len = 1\n }\n prev = x\n })\n if (len > maxLen) maxLen = len\n maxLen\n }\n}"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\nobject _580A extends CodeForcesApp[Int]({scanner => import scanner._\n val n = nextInt\n val m = List.fill(n)(nextInt)\n\n var ans = 1\n var curMax = 0\n var streak = 0\n\n for {\n i <- m\n } {\n if (i >= curMax) {\n streak += 1\n } else {\n ans = ans max streak\n streak = 1\n }\n curMax = i\n //debug(i, ans, curMax, streak)\n }\n\n ans max streak\n}) {\n override def format(result: Result) = super.format(result)\n}\n/****************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final type Result = A\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: Result): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n import scala.collection.mutable.{Map => Dict}\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0\n final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject A extends App {\n val n = readLine().toInt\n val A = readLine().split(\" \").map(_.toInt)\n\n var curr = 1\n var max = 1\n for (i <- 1 until A.length) {\n if (A(i - 1) <= A(i)) {\n curr += 1\n max = Math.max(max, curr)\n } else {\n curr = 1\n }\n }\n\n println(max)\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(\" \").map(_.toInt)\n println(data.foldLeft((0, 0, 0)) {\n case((max, soFar, prev), el) if prev > el => (Math.max(max, soFar), 1, el)\n case((max, soFar, prev), el) => (Math.max(max, soFar + 1), soFar + 1, el)\n }._1)\n}\n"}, {"source_code": "object Main {\n\n def main(args: Array[String]) {\n\n val std = scala.io.StdIn\n val n = std.readLine().toInt\n val values = std.readLine().split(\" \").map(_.toInt)\n \n var prevValue = 0\n var result = 0\n var currentLength = 0\n for (i <- 0 until n) {\n if (values(i) < prevValue) {\n result = result.max(currentLength)\n currentLength = 0\n }\n prevValue = values(i)\n currentLength += 1\n }\n \n println(result.max(currentLength))\n }\n}"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by breezzo on 19.02.17.\n */\nobject Main {\n def main(args: Array[String]): Unit = {\n StdIn.readLine()\n val a = StdIn.readLine().split(\"\\\\s\").map(_.toInt)\n var max = 0\n var prev = 0\n\n for (i <- 1 until a.length) {\n if (a(i - 1) > a(i)) {\n max = Math.max(i - prev, max)\n prev = i\n }\n }\n\n max = Math.max(a.length - prev, max)\n\n println(max)\n }\n}"}, {"source_code": "import Array._\nimport scala.io.StdIn.readLine\nobject problem {\n def main(args: Array[String]) {\n val n = readLine.toInt\n var cnt = 1\n var max = 1\n val A = readLine.split(\" \").map(_.toInt)\n for(i <- 0 until n - 1){\n if(A(i) <= A(i + 1)){\n cnt += 1\n max = Math.max(max, cnt)\n }\n else{\n cnt = 1\n }\n }\n println(max)\n }\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Task extends App{\n val n = readInt\n val as = readLine.split(\" \").map(_.toInt)\n \n //(elem, run)\n val ans = as.scanLeft((0,0)){ case (prev, cur) =>\n if (prev._1 <= cur) \n (cur, prev._2+1)\n else\n (cur, 1)\n }.map(_._2).max\n \n println(ans)\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n\n val v = for {\n i <- 1 to n\n } yield sc.nextInt\n\n\n //println(v.toString)\n def max(a: Int, b: Int): Int = if(a>b) a else b\n\n def foo(xs: List[Int], n: Int, m: Int):Int = xs match {\n case x::y::xs => if(x<=y) { foo(y::xs, n+1, max(m, n+1))} else {foo(y::xs, 1, max(m,n))}\n case _ => m\n }\n\n if(v.size == 1) println(\"1\")\n else println((foo(v.toList,1,1)).toString)\n}"}], "negative_code": [{"source_code": "//package round321.a\n\nimport java.util.Scanner\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n\n val a = for(_ <- 0 until n) yield sc.nextInt\n\n var max = 0\n var cur = 1\n for(i <- 1 until n) {\n if(a(i) < a(i - 1)) {\n cur = 1\n } else {\n cur += 1\n }\n max = Math.max(max, cur)\n }\n\n println(max)\n}\n\n"}, {"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\nobject Solution extends App {\n val days = StdIn.readInt()\n val allIncomes = StdIn.readLine().split(\" \").map(_.toInt).toList\n\n val result = longestIncreasingSubsegment(allIncomes)\n\n System.out.println(result)\n\n def longestIncreasingSubsegment(input: List[Int]) = {\n var maxLen = 1\n var len = 1\n var prev = 0\n input.foreach(x => {\n if (x >= prev) {\n len += 1\n } else {\n if (len > maxLen)\n maxLen = len\n len = 1\n }\n prev = x\n })\n if (len > maxLen) maxLen = len\n maxLen\n }\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\nobject Solution extends App {\n val days = StdIn.readInt()\n val allIncomes = StdIn.readLine().split(\" \").map(_.toInt).toList\n\n val result = longestIncreasingSubsegment(allIncomes)\n\n System.out.println(result)\n\n def longestIncreasingSubsegment(input: List[Int]) = {\n var maxLen = 0\n var len = 0\n var prev = 0\n input.foreach(x => {\n if (x >= prev) {\n prev = x\n len += 1\n } else {\n if (len > maxLen)\n maxLen = len\n len = 0\n }\n })\n if (len > maxLen) maxLen = len\n maxLen\n }\n}"}, {"source_code": "object A580 {\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val input = readInts(n)\n\n var res = 0\n var i = 1\n var curr = 1\n while(i < n) {\n if(input(i-1) <= input(i)) {\n curr += 1\n } else {\n curr = 1\n }\n res = math.max(res, curr)\n i += 1\n }\n println(res)\n }\n}"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by breezzo on 19.02.17.\n */\nobject Main {\n def main(args: Array[String]): Unit = {\n StdIn.readLine()\n val a = StdIn.readLine().split(\"\\\\s\").map(_.toInt)\n var max = 0\n var prev = 0\n\n for (i <- 0 until a.length - 1) {\n if (a(i) > a(i + 1)) {\n max = Math.max(i - prev, max)\n prev = i + 1\n }\n }\n\n max = Math.max(a.length - prev, max)\n\n println(max)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\n/**\n * Created by breezzo on 19.02.17.\n */\nobject Main {\n def main(args: Array[String]): Unit = {\n StdIn.readLine()\n val a = StdIn.readLine().split(\"\\\\s\").map(_.toInt)\n var max = 0\n var prev = 0\n\n for (i <- 0 until a.length - 1) {\n if (a(i) > a(i + 1)) {\n max = Math.max(i - prev, max)\n prev = i\n }\n }\n\n max = Math.max(a.length - prev, max)\n\n println(max)\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt\n\n val v = for {\n i <- 1 to n\n } yield sc.nextInt\n\n\n //println(v.toString)\n def max(a: Int, b: Int): Int = if(a>b) a else b\n\n def foo(xs: List[Int], n: Int, m: Int):Int = xs match {\n case x::y::xs => if(x<=y) { foo(y::xs, n+1, max(m, n))} else {foo(y::xs, 1, max(m,n))}\n case _ => m\n }\n\n if(v.size == 1) println(\"1\")\n else println((foo(v.toList,1,1)+1).toString)\n}"}], "src_uid": "1312b680d43febdc7898ffb0753a9950"} {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n val a = for(i <- 1 to n) yield( Array(i) ++ readLine().split(\" \").map(_.toInt) )\n val f = a.filter{ c => \n a.find(c1 => c1(1) > c(1) && c1(2) > c(2) && c1(3) > c(3)) == None\n }\n println( f.minBy(_.apply(4)).apply(0) )\n }\n}", "positive_code": [{"source_code": "import scala.collection.mutable.LinkedList\nobject P106B extends App {\n \n val n = readLine toInt\n val params = List(new Array[Int](n), new Array[Int](n), new Array[Int](n))\n val costs = collection.mutable.Map[Int,Int]()\n val r = 0 until n\n \n for (i <- r) {\n val Array(speed_, ram_, hdd_, costs_) = readLine.split(\" \").map(_.toInt)\n params(0)(i) = speed_\n params(1)(i) = ram_\n params(2)(i) = hdd_\n costs += (i -> costs_)\n }\n \n for(a <- r; b <- r) if(params.forall((x) => x(a) < x(b))) costs.removeKey(a)\n \n println(costs.toList.minBy(_._2)._1 + 1)\n\n\t \n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map {\n i =>\n val line = in.next().split(' ').map(_.toInt)\n (i, line(0), line(1), line(2), line(3))\n }.sortBy(_._5)\n val a = data.find{\n list => !data.exists(nList => nList._2 > list._2 && nList._3 > list._3 && nList._4 > list._4)\n }\n println(a.get._1)\n\n}"}, {"source_code": "object P106B extends App {\n \n val n = readLine toInt\n val p = new Array[Array[Int]](n)\n val c = collection.mutable.Map[Int,Int]()\n val r = 0 until n\n \n for (i <- r) {\n p(i) = readLine.split(\" \").map(_.toInt)\n c += (i -> p(i).last)\n }\n \n for(a <- r; b <- r)\n if((0 to 2).forall((x) => p(a)(x) < p(b)(x))) c.removeKey(a)\n \n println(c.toList.minBy(_._2)._1 + 1)\n\n\t \n\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable.LinkedList\nobject P106B extends App {\n \n val n = readLine toInt\n val params = List(new Array[Int](n), new Array[Int](n), new Array[Int](n))\n val costs = collection.mutable.Map[Int,Int]()\n val r = 0 until n\n \n for (i <- r) {\n val Array(speed_, ram_, hdd_, costs_) = readLine.split(\" \").map(_.toInt)\n params(0)(i) = speed_\n params(1)(i) = ram_\n params(2)(i) = hdd_\n costs += (i -> costs_)\n }\n \n println(costs)\n for(a <- r; b <- r) if(params.forall((x) => x(a) < x(b))) costs.removeKey(a)\n println(costs)\n \n println(costs.toList.minBy(_._2)._1 + 1)\n\n\t \n\n}"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = (1 to n).map {\n i =>\n val line = in.next().split(' ').map(_.toInt)\n (i, line(0), line(1), line(2), line(3))\n }.sortBy(_._5)\n val a = data.find{\n list => !data.exists(nList => nList._2 > list._2 && nList._3 > list._3 && nList._3 > list._4)\n }\n println(a.get._1)\n\n}"}], "src_uid": "e12d86f0c8645424b942d3dd9038e04d"} {"source_code": "object CF503A extends App {\n import scala.io.StdIn\n\n val Array(n, h, a, b, k) = StdIn.readLine.split(' ').map(_.toInt)\n val queries = (0 until k).map(_ => StdIn.readLine.split(' ').map(_.toInt))\n\n for (query <- queries) {\n var Array(ta, fa, tb, fb) = query\n var time = 0\n if (ta != tb) {\n if (fa < a) {\n time = a - fa\n fa = a\n } else if (fa > b) {\n time = fa - b\n fa = b\n }\n time += (tb - ta).abs\n }\n time += (fa - fb).abs\n println(time)\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, H, A, B, K = ni()\n REP(K) { i =>\n val ta, fa, tb, fb = ni()\n val ans = if (ta == tb) {\n abs(fa - fb)\n } else if (A <= fa && fa <= B && A <= fb && fb <= B) {\n abs(tb - ta) + abs(fa - fb)\n } else {\n abs(tb - ta) + (for {\n f <- Seq(A, B)\n } yield abs(f - fa) + abs(f - fb)).min\n }\n out.println(ans)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject A {\n\n def main(args: Array[String]): Unit = {\n val input = StdIn.readLine().split(' ').map(_.toInt)\n\n print {\n val n = input(0)\n val h = input(1)\n val a = input(2)\n val b = input(3)\n val k = input(4)\n\n (1 to k).map { index =>\n val in = StdIn.readLine().split(' ').map(_.toInt)\n\n val ta = in(0)\n val fa = in(1)\n val tb = in(2)\n val fb = in(3)\n\n val tdiff = Math.abs(ta - tb)\n\n if (tdiff == 0) Math.abs(fa - fb)\n else if (fa < a) tdiff + a - fa + Math.abs(a - fb)\n else if (fa > b) tdiff + fa - b + Math.abs(b - fb)\n else tdiff + Math.abs(fa - fb)\n }.mkString(\" \")\n }\n\n }\n\n}\n"}, {"source_code": "\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_503_A { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.sa1)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading\n val line = readLine \n val n = line.int\n val h = line.int\n val a = line.int\n val b = line.int\n val k = line.int\n \n for (i <- 1 to k) {\n val qLine = readLine\n val t1 = qLine.int\n val f1 = qLine.int\n val t2 = qLine.int\n val f2 = qLine.int\n debug(s\"$i: $t1 $f1 -> $t2 $f2\")\n \n if (t1 == t2) {\n val path = (f1 - f2).abs \n outLn(path)\n debug(\"same \" + path) \n } else {\n var toTunnel = 0\n var exitIn2 = f1\n if (f1 < a) { toTunnel = a-f1; exitIn2 = a; }\n if (f1 > b) { toTunnel = f1-b; exitIn2 = b; }\n debug(s\" $toTunnel $exitIn2\") \n var path = toTunnel + (t2 - t1).abs + (exitIn2 - f2).abs\n outLn(path)\n }\n }\n// val arr = new Array[String](n)\n// (0 until n).foreach(arr(_) = readLine.string)\n// debug(\"n = \" + n)\n \n \n //---------------------------- parameters reading :end \n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3 \n\"\"\"\n\nval sa2 = \"\"\"\n\"\"\"\n\nval sa3 = \"\"\"\n\"\"\"\n}\n\n}\n\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, H, A, B, K = ni()\n REP(K) { i =>\n val ta, fa, tb, fb = ni()\n val ans = if (A <= fa && fa <= B && A <= fb && fb <= B) {\n abs(tb - ta) + abs(fa - fb)\n } else {\n abs(tb - ta) + (for {\n f <- Seq(A, B)\n } yield abs(f - fa) + abs(f - fb)).min\n }\n out.println(ans)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, H, A, B, K = ni()\n REP(K) { i =>\n val ta, fa, tb, fb = ni()\n val ans = if (A <= ta && ta <= B) {\n abs(tb - ta) + abs(fa - fb)\n } else {\n abs(tb - ta) + (for {\n f <- Seq(A, B)\n } yield abs(f - fa) + abs(f - fb)).min\n }\n out.println(ans)\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object CF503A extends App {\n import scala.io.StdIn\n\n val Array(n, h, a, b, k) = StdIn.readLine.split(' ').map(_.toInt)\n val queries = (0 until k).map(_ => StdIn.readLine.split(' ').map(_.toInt))\n\n for (query <- queries) {\n var Array(ta, fa, tb, fb) = query\n var time = 0\n if (fa < a) {\n time = a - fa\n fa = a\n } else if (fa > b) {\n time = fa - b\n fa = b\n }\n time += (tb - ta).abs\n time += (fa - fb).abs\n println(time)\n }\n}\n"}, {"source_code": "\nimport java.util.ArrayList\nimport java.util.StringTokenizer\n//import scala.reflect.io.File\nimport java.io.BufferedReader\nimport java.io.BufferedInputStream\nimport java.io.InputStreamReader\nimport java.io.ByteArrayInputStream\nimport java.io.InputStream\n\nobject CF_503_A { var br = createBufferedReader(); var debugV = false \n \n //COMMENT ME !\n// runTest(Test.sa1)\n// debugV = true\n// runFromFile(\"\"\"C:\\work\\git\\ap-codeforces\\Codeforces\\src\\fb\\aprokh\\fb2018r2\\jacks_candy_shop_2.txt\"\"\")\n \n def main(args: Array[String]): Unit = {\n //---------------------------- parameters reading\n val line = readLine \n val n = line.int\n val h = line.int\n val a = line.int\n val b = line.int\n val k = line.int\n \n for (i <- 1 to k) {\n val qLine = readLine\n val t1 = qLine.int\n val f1 = qLine.int\n val t2 = qLine.int\n val f2 = qLine.int\n debug(s\"$i: $t1 $f1 -> $t2 $f2\")\n \n if (t1 == t2) {\n val path = (f1 - f2).abs \n outLn(path)\n debug(\"same \" + path) \n } else {\n var toTunnel = 0\n var exitIn2 = f1\n if (f1 < a) { toTunnel = a-f1; exitIn2 = a; }\n if (f1 > b) { toTunnel = f1-b; exitIn2 = b; }\n debug(s\" $toTunnel $exitIn2\") \n var path = toTunnel + (t2 - t1) + (exitIn2 - f2).abs\n outLn(path)\n }\n }\n// val arr = new Array[String](n)\n// (0 until n).foreach(arr(_) = readLine.string)\n// debug(\"n = \" + n)\n \n \n //---------------------------- parameters reading :end \n \n debug(\"================= RESULT ================== \")\n finish\n }\n \n \n //============================ service code ======================\n\n// var file:File = null\n val resultStr = new StringBuilder\n def outLn(str:String) = resultStr.append(str).append(\"\\n\")\n def outLn(number:Integer) = resultStr.append(number+\"\").append(\"\\n\")\n def finish() {\n// if (file == null || !devEnv) {\n println(resultStr.toString())\n// } else {\n// file.writeAll(resultStr.toString())\n// }\n }\n \n def readLine() = new Line \n class Line {\n val fullLine = br.readLine()\n val tok = new StringTokenizer(fullLine, \" \")\n def int = tok.nextToken().toInt\n def long = tok.nextToken().toLong\n def double = tok.nextToken().toDouble\n def string = tok.nextToken()\n }\n \n def createBufferedReader(inst:InputStream = System.in): BufferedReader = {\n val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);\n new BufferedReader(new InputStreamReader(bis));\n }\n \n def runTest(str:String) = if (devEnv) { \n br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes(\"ISO-8859-1\")))\n }\n \n// def runFromFile(fileName: String) = if (devEnv) {\n// br = createBufferedReader(new FileInputStream(fileName))\n// }\n \n def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function\n \n lazy val devEnv = this.getClass.getCanonicalName.contains(\".\")\n \n//============================================================================================\nobject Test {\n \nval sa1 = \"\"\"\n3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3 \n\"\"\"\n\nval sa2 = \"\"\"\n\"\"\"\n\nval sa3 = \"\"\"\n\"\"\"\n}\n\n}\n\n"}], "src_uid": "bdce4761496c88a3de00aa863ba7308d"} {"source_code": "//package codeforces\n\n/*\nhttps://codeforces.com/contest/1175/problem/D\n\nStrategy-\n\ns = suffix sum array\nf = indexes array\n\n** f(0) is always 0\n\nthis implies =>\n res = s(f(0)) - s(f(1)) + 2*(s(f(1)) - s(f(2))) + 3*(s(f(2)) - s(f(3))) + ...\n res = s(f(0)) + s(f(1)) + s(f(2)) + s(f(3)) + ...\n this means we select the top k max elements form the suffix sum array\n\n\n */\nobject ArraySplitting {\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val seq = io.StdIn.readLine().split(\" \").map(_.toLong)\n\n val suffixSum = seq.scanRight(0l)(_ + _)\n println(suffixSum(0) + suffixSum.drop(1).dropRight(1).sorted.takeRight(k - 1).sum)\n }\n\n}", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n case class Entry(i: Int, sum: Long)\n def solve(): Unit = {\n import java.util.Comparator\n val N, K = ni()\n val A = na(N)\n val cumR = cumSum(A.reverse).reverse\n\n // 一番左を2番目以降のグループにすることはできない\n val E = Array.ofDim[Entry](N - 1)\n REP(N - 1) { i =>\n E(i) = Entry(i + 1, cumR(i + 1))\n }\n sort(E, new Comparator[Entry] {\n override def compare(o1: Entry, o2: Entry): Int = -java.lang.Long.compare(o1.sum, o2.sum)\n })\n\n debug(cumR)\n debug(E.mkString(\" \"))\n\n var ans = sumL(A)\n for {\n e <- E.take(K - 1)\n } ans += e.sum\n\n out.println(ans)\n }\n}"}], "negative_code": [{"source_code": "//package codeforces\n\n/*\nhttps://codeforces.com/contest/1175/problem/D\n */\nobject ArraySplitting {\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val seq = io.StdIn.readLine().split(\" \").map(_.toLong)\n val prefixSum = seq.scanRight(0l)(_ + _)\n\n val segmentTree = new MaxSegmentTree(prefixSum)\n\n def loop(i: Int, k: Int, prevMax: Long, result: Long): Long = {\n if (k == 1)\n result + prefixSum(0) - prevMax\n else {\n val (value, index) = segmentTree.query(k - 1, i)\n loop(index - 1, k - 1, value, result + (value - prevMax) * k)\n }\n }\n\n println(loop(seq.length - 1, k, 0, 0l))\n }\n\n}\n\n/*\nright biased max segment tree with index\n */\nclass MaxSegmentTree private(segmentArr: Array[(Long, Int)], arr: Array[Long]) {\n\n def this(arr: Array[Long]) = {\n this(new Array[(Long, Int)](4 * arr.length), arr)\n }\n\n preCompute(0, arr.length - 1, 0)\n\n private def preCompute(l: Int, r: Int, i: Int): Unit = {\n if (l == r) segmentArr(i) = (arr(l), l)\n else {\n val m = (l + r) / 2\n preCompute(l, m, 2 * i + 1)\n preCompute(m + 1, r, 2 * i + 2)\n segmentArr(i) =\n if (segmentArr(2 * i + 1)._1 <= segmentArr(2 * i + 2)._1)\n segmentArr(2 * i + 2)\n else\n segmentArr(2 * i + 1)\n }\n }\n\n /**\n *\n * @param left left index inclusive\n * @param right right index inclusive\n * @return result\n */\n def query(left: Int, right: Int): (Long, Int) = {\n assert(left <= right)\n assert(left >= 0 && right < arr.length)\n\n def query(l: Int, r: Int, i: Int, x: Int, y: Int): (Long, Int) = {\n if (l == x && r == y) segmentArr(i)\n else {\n val m = (l + r) / 2\n\n if (y <= m) query(l, m, 2 * i + 1, x, y)\n else if (m < x) query(m + 1, r, 2 * i + 2, x, y)\n else {\n val lR = query(l, m, 2 * i + 1, x, m)\n val rR = query(m + 1, r, 2 * i + 2, m + 1, y)\n\n if (lR._1 <= rR._1) rR else lR\n }\n }\n\n }\n\n query(0, arr.length - 1, 0, left, right)\n }\n}"}, {"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private val oj = System.getenv(\"ATCODER_DEBUG\") == null\n def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n def debugDim(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from) { i =>\n f(i)\n }\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n\n // toIntとか+7とかするならvalにしろ\n @inline private def MOD = 1000000007\n\n case class Entry(i: Int, sum: Long)\n def solve(): Unit = {\n import java.util.Comparator\n val N, K = ni()\n val A = na(N)\n val cumR = cumSum(A.reverse).reverse\n val E = Array.ofDim[Entry](N)\n REP(N) { i =>\n E(i) = Entry(i, cumR(i))\n }\n sort(E, new Comparator[Entry] {\n override def compare(o1: Entry, o2: Entry): Int = -java.lang.Long.compare(o1.sum, o2.sum)\n })\n\n debug(cumR)\n debug(E.mkString(\" \"))\n\n var ans = sumL(A)\n for {\n e <- E.take(K - 1)\n } ans += e.sum\n\n out.println(ans)\n }\n}"}], "src_uid": "c7a37e8220d5fc44556dff66c1e129e7"} {"source_code": "object A1262 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var tests = readInt\n while (tests > 0) {\n val Array(n) = readInts(1)\n var a = Integer.MAX_VALUE\n var b = Integer.MIN_VALUE\n var c = Integer.MAX_VALUE\n var d = Integer.MIN_VALUE\n val arr = Array.fill(n)((0, 0))\n for (i <- 0 until n) {\n val Array(x, y) = readInts(2)\n a = math.min(a, x);\n b = math.max(b, x);\n c = math.min(c, y);\n d = math.max(d, y);\n arr(i) = (x, y)\n }\n var res = Integer.MAX_VALUE\n for ((x, y) <- Array(\n (a, a),\n (b, b),\n (c, c),\n (d, d),\n (a, b),\n (a, c),\n (a, d),\n (b, c),\n (b, d),\n (c, d)\n )) {\n if (arr.forall {\n case (i, j) =>\n (x >= math.min(i, j) && y <= math.max(i, j))\n }) res = math.min(res, math.abs(y - x))\n }\n out.println(res)\n tests -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "object Main {\n import java.io.{BufferedReader, InputStream, InputStreamReader}\n import java.util.StringTokenizer\n import scala.reflect.ClassTag\n\n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n new Main(out, new InputReader(System.in)).solve()\n out.flush()\n }\n\n private[this] val oj = System.getenv(\"ATCODER_DEBUG\") == null\n @inline private final def DEBUG(f: => Unit): Unit = {\n if (!oj){ f }\n }\n @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) \"1\" else \"0\").mkString) }\n @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(\" \")) }\n @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){\n REP(m.length) { i =>\n debug(m(i))\n }\n }\n @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){\n REP(m(0).length) { j =>\n REP(m.length) { i =>\n System.err.print(m(i)(j))\n System.err.print(\" \")\n }\n System.err.println()\n }\n }\n @inline def debug(s: => String): Unit = DEBUG {\n System.err.println(s)\n }\n @inline private final def debugL(num: => Long): Unit = DEBUG {\n System.err.println(num)\n }\n private def isDebug[A](debug: => A, online: => A): A = {\n if (oj) online else debug\n }\n\n class InputReader(val stream: InputStream) {\n private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private[this] var tokenizer: StringTokenizer = _\n\n @inline private[this] final def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n def nextLong(): Long = java.lang.Long.parseLong(next())\n def nextChar(): Char = next().charAt(0)\n\n def ni(): Int = nextInt()\n def nl(): Long = nextLong()\n def nc(): Char = nextChar()\n def ns(): String = next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n }\n\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\n REP(to - from + 1, from)(f)\n }\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n def cumSum(as: Array[Int]): Array[Long] = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}\n\nobject Workspace {\n import Main._\n}\n\nclass Main(out: java.io.PrintWriter, sc: Main.InputReader) {\n import sc._\n import Main._\n import java.util.Arrays.sort\n\n import scala.collection.mutable\n import math.{abs, max, min}\n import mutable.ArrayBuffer\n import Workspace._\n\n // toIntとか+7とかするならvalにしろ\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N = ni()\n var L = 0\n var R = 1e9.toInt\n REP(N) { _ =>\n val l, r = ni()\n L = max(l, L)\n R = min(r, R)\n }\n debug(s\"L:$L R:$R\")\n val ans = max(0, L - R)\n out.println(ans)\n }\n }\n}"}, {"source_code": "import scala.io.StdIn._\nobject Main extends App{\n // Your code here!\n val t = readInt()\n for (i <- 1 to t) {\n val n = readInt()\n var minR = Integer.MAX_VALUE\n var maxL=Integer.MIN_VALUE\n for (j <- 1 to n) {\n val arr = readLine().split(\" \").map(_.toInt)\n minR = Math.min(minR, arr(1))\n maxL = Math.max(maxL, arr(0))\n }\n println(if (minR >= maxL) 0 else (maxL - minR))\n }\n}\n"}], "negative_code": [{"source_code": "object A1262 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var tests = readInt\n while (tests > 0) {\n val Array(n) = readInts(1)\n var a = Integer.MAX_VALUE\n var b = Integer.MIN_VALUE\n var c = Integer.MAX_VALUE\n var d = Integer.MIN_VALUE\n val arr = Array.fill(n)((0, 0))\n for (i <- 0 until n) {\n val Array(x, y) = readInts(2)\n a = math.min(a, x);\n b = math.max(b, x);\n c = math.min(c, y);\n d = math.max(d, y);\n arr(i) = (x, y)\n }\n var res = Integer.MAX_VALUE\n for ((x, y) <- Array((a, b), (a, c), (a, d), (b, c), (b, d), (c, d))) {\n if (arr.forall {\n case (i, j) =>\n (x >= math.min(i, j) && y <= math.max(i, j))\n }) res = math.min(res, math.abs(y - x))\n }\n out.println(res)\n tests -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "f8a8bda80a75ed430465605deff249ca"} {"source_code": "import java.util\nimport java.util._\nimport java.lang._\nimport java.io._\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n val ints = new Array[Int](10)\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def comp(x: (String, Int), y: (String, Int)): Boolean = {\n x._2 > y._2\n }\n\n def solve = {\n val n = nextInt\n val m = nextInt\n val fruitPrice = new Array[Int](n)\n for (i <- 0 until n) {\n fruitPrice(i) = nextInt\n }\n val fruits = new util.HashMap[String, Int](m)\n for (i <- 0 until m) {\n val fruit = next\n if (fruits.containsKey(fruit)) {\n val num = fruits.get(fruit)\n fruits.put(fruit, num + 1)\n } else {\n fruits.put(fruit, 1)\n }\n }\n val fruitsWithIndex = fruits.keySet().toArray(new Array[String](0)).map(x => (x, fruits.get(x))).sortWith(comp)\n// fruitsWithIndex.foreach(print)\n val sortedFruitPrice = fruitPrice.sorted\n var ind = 0\n var minPrice = 0\n var maxPrice = 0\n for (i <- 0 until fruitsWithIndex.length) {\n minPrice += fruitsWithIndex(i)._2 * sortedFruitPrice(ind)\n maxPrice += fruitsWithIndex(i)._2 * sortedFruitPrice(sortedFruitPrice.length - ind - 1)\n ind += 1\n }\n out.print(minPrice + \" \" + maxPrice)\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Fruits extends App {\n\n val s = new Scanner(System.in)\n val (n, m) = (s.nextInt(), s.nextInt())\n val prices = (0 until n).map(_ => s.nextInt())\n val fruits = (0 until m).map(_ => (s.next() -> 1)).groupBy(_._1).values.map(x => x.map(_._2)).map(_.sum).toList\n\n val min = (fruits.sortBy(-_) zip prices.sorted).map(x => x._1 * x._2).sum\n val max = (fruits.sortBy(-_) zip prices.sortBy(-_)).map(x => x._1 * x._2).sum\n println(min + \" \" + max)\n\n}\n"}, {"source_code": "object C12 {\n\n import IO._\n import collection.{mutable => cu}\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readInts(2)\n val a = readInts(n).sorted\n val map = cu.Map.empty[String, Int].withDefaultValue(0)\n for(_ <- 1 to m) {\n val s = read\n map(s) += 1\n }\n val vals = map.values.toArray.sorted.reverse\n val min = a.zip(vals).map{case (x, y) => x*y}.sum\n val max = a.reverse.zip(vals).map{case (x, y) => x*y}.sum\n println(s\"$min $max\")\n }\n\n object IO {\n private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [], "src_uid": "31c43b62784a514cfdb9ebb835e94cad"} {"source_code": "object Sequence {\n def main(args: Array[String]) {\n val n = readInt()\n val nums = readLine().split(\" \").map(_.toInt)\n val nums_abs = nums.map(_.abs)\n\n if (n % 2 == 1 || nums.count(_ < 0) % 2 == 0)\n println(nums_abs.sum)\n else\n println(nums_abs.sum - 2 * nums_abs.min)\n }\n}", "positive_code": [{"source_code": "object Sequence {\n def main(args: Array[String]) {\n val n = readInt()\n val nums = readLine().split(\" \").map(_.toInt)\n val nums_abs = nums.map(_.abs)\n\n if (n % 2 == 1 || nums.count(_ < 0) % 2 == 0)\n println(nums_abs.sum)\n else\n println(nums_abs.sum - 2 * nums_abs.min)\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject C extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val as = List.fill(2 * N - 1)(sc.nextInt).sorted\n\n def flipSum(n: Int): Int = {\n val (fs, rs) = as.splitAt(n)\n if (n > 2 * N - 1) Int.MinValue\n else fs.map(_ * -1).sum + rs.sum\n }\n\n val answer: Int = {\n val neg = as.count(_ < 0)\n if (N % 2 == 1) as.map(scala.math.abs(_)).sum\n else if (neg % 2 == 0) flipSum(neg)\n else flipSum(neg - 1) max flipSum(neg + 1)\n }\n\n out.println(answer)\n out.close\n}\n"}], "negative_code": [{"source_code": "object Sequence {\n def main(args: Array[String]) {\n val n = readInt()\n val nums = readLine().split(\" \").map(_.toInt).sorted\n val ans = nums.zipWithIndex.foldLeft(0) {\n case (a, (k, i)) =>\n if (i < n && k < 0)\n a - k\n else\n a + k\n }\n println(ans)\n }\n}\n"}, {"source_code": "object Sequence {\n def main(args: Array[String]) {\n val n = readInt()\n val nums = readLine().split(\" \").map(_.toInt).sorted\n if (n > 2)\n println(nums.map(_.abs).sum)\n else {\n val ans = nums.zipWithIndex.foldLeft(0) {\n case (a, (k, i)) =>\n if (i < n && k < 0)\n a - k\n else\n a + k\n }\n println(ans)\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject C extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val as = List.fill(2 * N - 1)(sc.nextInt).sorted\n\n def flipSum(n: Int): Int = {\n val (fs, rs) = as.splitAt(n)\n if (n > N) Int.MinValue\n else fs.map(_ * -1).sum + rs.sum\n }\n\n val answer: Int = {\n val neg = as.count(_ < 0)\n if (N < neg) flipSum(N)\n else if (N % 2 == neg % 2) flipSum(neg)\n else if (N % 2 == 0) flipSum(neg / 2 * 2) max flipSum(neg / 2 * 2 + 2)\n else flipSum(neg - 1) max flipSum(neg + 1)\n\n }\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject C extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val as = List.fill(2 * N - 1)(sc.nextInt).sorted\n\n def flipSum(n: Int): Int = {\n val (fs, rs) = as.splitAt(n)\n if (n > 2 * N - 1) Int.MinValue\n else fs.map(_ * -1).sum + rs.sum\n }\n\n val answer: Int = {\n val neg = as.count(_ < 0)\n if (neg % 2 == 0) flipSum(neg)\n else flipSum(neg - 1) max flipSum(neg + 1)\n }\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject C extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val as = List.fill(2 * N - 1)(sc.nextInt).sorted\n\n def flipSum(n: Int): Int = {\n val (fs, rs) = as.splitAt(n)\n if (n > N) Int.MinValue\n else fs.map(_ * -1).sum + rs.sum\n }\n\n val answer: Int = {\n val neg = as.filter(_ < 0).size\n val n = neg / 2 * 2\n flipSum(n) max flipSum(n + 2)\n }\n\n out.println(answer)\n out.close\n}\n"}], "src_uid": "9b907b3e96e78c84d11032a0f0b0fa53"} {"source_code": "import scala.io.StdIn._\n\nobject _368C extends App {\n /*\n n\n n2+k2=m2\n n2=m2-k2\n n2=(m-k)(m+k)\n\n n is odd\n m-k=1\n m=1+k\n m+k=n2\n 1+2k=n2\n\n k=(n2-1)/2\n m=(n2-1)/2+1\n\n n is even\n m-k=2\n m+k=n2/2\n m=2+k\n 2+2k=n2/2\n 2k=n2/2-2\n k=n2/4-1\n\n k=n2/4-1\n m=n2/4+1\n */\n\n val n = readLong()\n if (n < 3) {\n println(-1)\n } else {\n val (k, m) = if (n % 2 == 1) {\n val k = (n * n - 1) / 2\n val m = k + 1\n (k, m)\n } else {\n val k = (n / 2) * (n / 2) - 1\n val m = k + 2\n (k, m)\n }\n println(s\"$k $m\")\n }\n}\n\n", "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val a = in.next().toLong\n if (a < 3) println(-1)\n else if (a % 2 == 1) println(s\"${a * a / 2} ${a * a / 2 + 1}\")\n else println(s\"${a * a / 4 - 1} ${a * a / 4 + 1}\")\n}\n"}, {"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _707C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write}\n val x = read[Long]\n var sx = x\n while(sx % 2 == 0) {\n sx /= 2\n }\n\n val (a, b, c) =\n if (sx == 1) {\n val s = x*x/2\n val y = s/2 - 1\n val z = y + 2\n (x, y, z)\n } else {\n val s = sx*sx\n val y = s/2\n val z = y + 1\n (x, x/sx * y, x/sx * z)\n }\n\n if(a*a + b*b == c*c && a > 0 && b > 0 && c > 0 && a + b > c) {\n write(b, c)\n } else {\n write(-1)\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any, more: Any*): this.type = {\n printer.print(obj)\n more foreach {i =>\n printer.print(' ')\n printer.print(i)\n }\n this\n }\n def writeOnNextLine(obj: Any, more: Any*): this.type = {\n printer.println()\n write(obj, more: _*)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \"\\n\"): this.type = write(obj mkString separator)\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}, {"source_code": "import java.util.Scanner\n\nobject Main{\n def main (args: Array[String]){\n val sc = new Scanner(System.in)\n\n val n = sc.nextLong()\n\n if(n <= 2)\n println(-1)\n else if(n % 2 == 0)\n println((n/2)*(n/2)-1 + \" \" + ((n/2)*(n/2)+1))\n else\n println((n*n-1)/2 + \" \" + (n*n+1)/2)\n }\n}\n"}, {"source_code": "//package merofeev.contests.codeforces.rnd368\n\nimport java.util.Scanner\n\n/**\n * @author erofeev \n * @since 03.09.16\n */\nobject CPifagorian {\n\n def main(args: Array[String]): Unit = {\n //hypotenuse of every triangle > 4 is a cathetus of the other triangle\n val n = new Scanner(System.in).nextLong()\n //a2 + n2 = c2\n //n2 = a2 - c2\n //n2 = (a - c) * (a + c)\n if (n < 3) {\n println(\"-1\")\n }\n else if (n % 2 == 0) {\n val c = n * n / 4 - 1\n val a = c + 2\n println(s\"$a $c\")\n } else {\n //n2 = (1) * (n2)\n // a - c = 1; a + c = b2\n val c = (n * n - 1) / 2\n val a = c + 1\n println(s\"$a $c\")\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "//package merofeev.contests.codeforces.rnd368\n\nimport java.util.Scanner\n\n/**\n * @author erofeev \n * @since 03.09.16\n */\nobject CPifagorian {\n\n def main(args: Array[String]): Unit = {\n //hypotenuse of every triangle > 4 is a cathetus of the other triangle\n val n = new Scanner(System.in).nextInt()\n //a2 + n2 = c2\n //n2 = a2 - c2\n //n2 = (a - c) * (a + c)\n if (n < 3) {\n println(\"-1\")\n }\n if (n % 2 == 0) {\n val c = n * n / 4 - 1\n val a = c + 2\n println(s\"$a $c\")\n } else {\n //n2 = (1) * (n2)\n // a - c = 1; a + c = b2\n val c = (n * n - 1) / 2\n val a = c + 1\n println(s\"$a $c\")\n }\n }\n\n}\n"}, {"source_code": "//package merofeev.contests.codeforces.rnd368\n\nimport java.util.Scanner\n\n/**\n * @author erofeev \n * @since 03.09.16\n */\nobject CPifagorian {\n\n def main(args: Array[String]): Unit = {\n //hypotenuse of every triangle > 4 is a cathetus of the other triangle\n val n = new Scanner(System.in).nextInt()\n //a2 + n2 = c2\n //n2 = a2 - c2\n //n2 = (a - c) * (a + c)\n if (n < 3) {\n println(\"-1\")\n }\n else if (n % 2 == 0) {\n val c = n * n / 4 - 1\n val a = c + 2\n println(s\"$a $c\")\n } else {\n //n2 = (1) * (n2)\n // a - c = 1; a + c = b2\n val c = (n * n - 1) / 2\n val a = c + 1\n println(s\"$a $c\")\n }\n }\n\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val a = in.next().toInt\n if (a < 3) println(-1)\n else if (a % 2 == 1) println(s\"${a * a / 2} ${a * a / 2 + 1}\")\n else println(s\"${a * a / 4 - 1} ${a * a / 4 + 1}\")\n}\n"}], "src_uid": "df92643983d6866cfe406f2b36bec17f"} {"source_code": "import scala.io.StdIn\n\nobject Main {\n\n def main(args: Array[String]): Unit = {\n val t = StdIn.readInt()\n for (_ <- Range(0, t)) {\n val n = StdIn.readInt()\n println(n / 2)\n }\n }\n}", "positive_code": [{"source_code": "\nobject A extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n// val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val n = in.nextInt()\n\n n.times {\n val m = in.nextInt()\n\n println(m / 2)\n\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def readMatrix(rows: Int, cols: Int) = {\n (1.to(rows))\n .map(_ => {\n (1.to(cols)\n .map(_ => {\n in.nextInt()\n }))\n })\n }\n\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}"}, {"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n\n out.println(n/2)\n out.flush()\n }\n\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [], "src_uid": "b46244f39e30c0cfab592a97105c60f4"} {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n \n val LIM = 316\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n \n val Array(n, m, q) = readInts(3)\n val as = readLongs(n)\n val ss = Array.fill(m){\n val t = tokenizeLine\n val sn = t.nextToken.toInt\n Array.fill(sn)(t.nextToken.toInt - 1).sorted\n }\n \n val larges = (0 until m).filter(ss(_).size > LIM)\n val sset = Array.tabulate(larges.size)(i => new mutable.BitSet(ss(larges(i)).size))\n for (i <- larges.indices) sset(i) ++= ss(larges(i))\n \n val isLarge = new mutable.BitSet(m)\n isLarge ++= larges \n \n val largeIncr = Array.fill(m)(0L)\n val largeSum = Array.fill(m)(0L)\n for (i <- larges) largeSum(i) = ss(i).map(as(_)).sum\n\n val overlaps = Array.tabulate(m)(i => {\n Array.tabulate(larges.size)(j => {\n var k, cnt = 0\n while (k < ss(i).size) {\n if (sset(j)(ss(i)(k))) cnt += 1\n k += 1\n }\n cnt\n }\n )})\n\n for (i <- 0 until q) {\n val t = tokenizeLine\n if (t.nextToken == \"?\") {\n val k = t.nextToken.toInt - 1\n var ans = 0L\n if (isLarge(k)) ans += largeSum(k)\n else {\n var j = 0\n while (j < ss(k).size) {\n ans += as(ss(k)(j))\n j += 1\n }\n }\n var j = 0\n while (j < larges.size) {\n ans += largeIncr(larges(j)) * overlaps(k)(j)\n j += 1\n }\n\t println(ans)\n } else { // +\n val k = t.nextToken.toInt - 1\n val x = t.nextToken.toInt\n if (isLarge(k)) {\n largeIncr(k) += x\n } else {\n var j = 0\n while (j < ss(k).size) {\n as(ss(k)(j)) += x\n j += 1\n }\n j = 0\n \t\twhile (j < larges.size) {\n \t\t largeSum(larges(j)) += x * overlaps(k)(j)\n \t\t j += 1\n \t\t}\n }\n }\n }\n\n Console.flush\n}", "positive_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n \n val LIM = 316\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n \n val Array(n, m, q) = readInts(3)\n val as = readLongs(n)\n val ss = Array.fill(m){\n val t = tokenizeLine\n val sn = t.nextToken.toInt\n Array.fill(sn)(t.nextToken.toInt - 1).sorted\n }\n \n val larges = (0 until m).filter(ss(_).size > LIM)\n val sset = Array.tabulate(larges.size)(i => new mutable.BitSet(ss(larges(i)).size))\n for (i <- larges.indices) sset(i) ++= ss(larges(i))\n \n val isLarge = new mutable.BitSet(m)\n isLarge ++= larges \n \n val largeIncr = Array.fill(m)(0L)\n val largeSum = Array.fill(m)(0L)\n for (i <- larges) largeSum(i) = ss(i).map(as(_)).sum\n\n val overlaps = Array.tabulate(m)(i => \n Array.tabulate(larges.size)(j => ss(i).count(sset(j)(_))\n ))\n\n for (i <- 0 until q) {\n val t = tokenizeLine\n if (t.nextToken == \"?\") {\n val k = t.nextToken.toInt - 1\n var ans = 0L\n if (isLarge(k)) ans += largeSum(k)\n else {\n var j = 0\n while (j < ss(k).size) {\n ans += as(ss(k)(j))\n j += 1\n }\n }\n var j = 0\n while (j < larges.size) {\n ans += largeIncr(larges(j)) * overlaps(k)(j)\n j += 1\n }\n\t println(ans)\n } else { // +\n val k = t.nextToken.toInt - 1\n val x = t.nextToken.toInt\n if (isLarge(k)) {\n largeIncr(k) += x\n } else {\n var j = 0\n while (j < ss(k).size) {\n as(ss(k)(j)) += x\n j += 1\n }\n j = 0\n \t\twhile (j < larges.size) {\n \t\t largeSum(larges(j)) += x * overlaps(k)(j)\n \t\t j += 1\n \t\t}\n }\n }\n }\n\n Console.flush\n}"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, m, q) = readInts(3)\n val as = readLongs(n)\n val ss = Array.fill(m){\n val t = tokenizeLine\n val sn = t.nextToken.toInt\n Array.fill(sn)(t.nextToken.toInt - 1).sorted\n }\n \n val larges = (0 until m).filter(ss(_).size > 100)\n \n val isLarge = new mutable.BitSet(m)\n isLarge ++= larges \n \n val largeIncr = Array.fill(m)(0L)\n val largeSum = Array.fill(m)(0L)\n for (i <- larges) largeSum(i) = ss(i).sum\n \n val overlaps = for (i <- larges)\n yield for (j <- 0 until m) yield {\n var a, b, cnt = 0\n while (a < ss(i).size && b < ss(j).size) {\n val ssa = ss(i)(a)\n val ssb = ss(j)(b)\n if (ssa == ssb) {\n cnt += 1\n a += 1\n b += 1\n } else if (ssa < ssb) a += 1\n else b += 1 \n }\n cnt\n }\n\n for (i <- 0 until q) {\n val t = tokenizeLine\n if (t.nextToken == \"?\") {\n val k = t.nextToken.toInt - 1\n var ans = 0L\n if (isLarge(k)) ans += largeSum(k)\n else for (j <- ss(k)) ans += as(j)\n for (j <- larges) ans += largeIncr(j) * overlaps(k)(j)\n\t println(ans)\n } else { // +\n val k = t.nextToken.toInt - 1\n val x = t.nextToken.toInt\n if (isLarge(k)) {\n largeIncr(k) += x\n } else {\n for (j <- ss(k)) as(j) += x\n \t\tfor (j <- larges) largeSum(j) += x * overlaps(k)(j)\n }\n }\n }\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n def readString = Console.readLine\n def tokenizeLine = new java.util.StringTokenizer(readString)\n def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }\n def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }\n\n val Array(n, m, q) = readInts(3)\n val as = readInts(n)\n val ss = Array.fill(m){\n val t = tokenizeLine\n val sn = t.nextToken.toInt\n Array.fill(sn)(t.nextToken.toInt - 1)\n }\n \n val larges = (0 until m).filter(ss(_).size > 100)\n \n val isLarge = new mutable.BitSet(m)\n isLarge ++= larges \n \n val largeIncr = Array.fill(m)(0)\n val largeSum = Array.fill(m)(0)\n for (i <- larges) largeSum(i) = ss(i).sum\n \n val overlaps = for (i <- larges)\n yield for (j <- 0 until m; intersect = ss(i).intersect(ss(j))) yield intersect.size\n\n for (i <- 0 until q) {\n val t = tokenizeLine\n if (t.nextToken == \"?\") {\n val k = t.nextToken.toInt - 1\n var ans = 0L\n if (isLarge(k)) {\n ans += largeSum(k)\n for (j <- larges) ans += (largeIncr(j) * overlaps(k)(j))\n } else {\n for (j <- ss(k)) ans += as(j)\n for (j <- larges) ans += (largeIncr(j) * overlaps(k)(j))\n }\n\t println(ans)\n } else { // +\n val k = t.nextToken.toInt - 1\n val x = t.nextToken.toInt\n if (isLarge(k)) {\n largeIncr(k) += x\n } else {\n for (j <- ss(k)) as(j) += x\n \t\tfor (j <- larges) largeSum(j) += (x * overlaps(k)(j))\n }\n }\n }\n}"}], "src_uid": "9e1b04e8049eeb87060a0439e31530b5"} {"source_code": "/**\n * @see http://codeforces.com/contest/911/problem/A\n */\n\nobject ANearestMinimums extends App {\n def distance(i: Int = 0, j: Int = 0, m: Int = Int.MaxValue, d: Int = Int.MaxValue): Int =\n if (i == n) d\n else {\n val h = a(i)\n if (h < m) distance(i + 1, i, h, Int.MaxValue)\n else if (h == m) distance(i + 1, i, m, d min (i - j))\n else distance(i + 1, j, m, d)\n }\n\n val n = scala.io.StdIn.readInt()\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n println(distance())\n}\n", "positive_code": [{"source_code": "object A {\n import scala.io.StdIn\n import scala.collection.mutable\n\n def main(args: Array[String]): Unit = {\n StdIn.readLine() // skip the 1st line\n val lastPos = mutable.HashMap[Int, (Int, Int)]()\n for ((x, cur) <- StdIn.readLine().split(' ').toStream.map(_.toInt).zipWithIndex) {\n lastPos(x) = (cur, lastPos.get(x) match {\n case Some((prv, min)) => Math.min(cur-prv, min)\n case _ => Int.MaxValue\n })\n\n }\n println(lastPos(lastPos.keys.min)._2)\n }\n}"}, {"source_code": "import java.io.FileReader\nimport java.util\nimport java.util.Comparator\n\nimport collection.Searching._\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject Solution {\n //Console.setIn(new FileReader(new java.io.File(\"in\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n var caseNo = 1\n val magicMod = 1000000007\n\n def doCase() : Unit = {\n val Array(n) = readIntLine()\n val nums = readIntLine()\n val min = nums.min\n val idxs = nums.zipWithIndex.filter(_._1 == min).map(_._2)\n val diffs = idxs.sliding(2).map { case Array(a, b) => b - a}\n println(diffs.min)\n }\n\n def main(args: Array[String]): Unit = {\n val noCases = 1\n for (i <- 0 until noCases) {\n doCase()\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n def readLongLine(): Array[Long] = {\n StdIn.readLine().split(\" \").map(_.toLong)\n }\n\n def readBigIntLine(): Array[BigInt] = {\n StdIn.readLine().split(\" \").map(BigInt.apply)\n }\n}"}, {"source_code": "object CF911A extends App {\n\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n val i = Array.fill(n)(sc.nextInt).iterator\n\n var min = Int.MaxValue\n var mindist = Int.MaxValue\n var dist = 1\n while (i.hasNext) {\n i.next match {\n case c if c < min => min = c; mindist = Int.MaxValue; dist = 1\n case c if c == min => mindist = Math.min(mindist, dist); dist = 1\n case _ => dist += 1\n }\n }\n println(mindist)\n}"}], "negative_code": [{"source_code": "object A {\n import scala.io.StdIn\n import scala.collection.mutable\n\n def main(args: Array[String]): Unit = {\n StdIn.readLine() // skip the 1st line\n val lastPos = mutable.HashMap[Int, Int]()\n var min = Int.MaxValue\n for ((x, cur) <- StdIn.readLine().split(' ').toStream.map(_.toInt).zipWithIndex) {\n lastPos.get(x) match {\n case Some(prv) => min = Math.min(cur - prv, min)\n case _ =>\n }\n lastPos(x) = cur\n }\n println(min)\n }\n}\n"}, {"source_code": "object CF911A extends App {\n\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n val i = Array.fill(n)(sc.nextInt).iterator\n\n var min = Int.MaxValue\n var mindist = Int.MaxValue\n var dist = 1\n while (i.hasNext) {\n i.next match {\n case c if c < min => min = c; mindist = Int.MaxValue\n case c if c == min => mindist = Math.min(mindist, dist); dist = 1\n case _ => dist += 1\n }\n }\n println(mindist)\n}\n"}, {"source_code": "object CF911A extends App {\n\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n val i = Array.fill(n)(sc.nextInt).iterator\n\n var min = Int.MaxValue\n var mindist = Int.MaxValue\n var dist = 1\n while (i.hasNext) {\n i.next match {\n case c if c < min => min = c; mindist = 0\n case c if c == min => mindist = Math.min(mindist, dist); dist = 1\n case _ => dist += 1\n }\n }\n println(mindist)\n}"}, {"source_code": "object CF911A extends App {\n\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n val i = Array.fill(n)(sc.nextInt).iterator\n\n var min = Int.MaxValue\n var mindist = Int.MaxValue\n var dist = 1\n while (i.hasNext) {\n i.next match {\n case c if c < min => min = c; mindist = Int.MaxValue; dist = 1\n case c if c == min => mindist = Math.min(mindist, dist); dist = 1\n case _ => dist += 1\n }\n println(\"%d %d %d\".format(min,mindist,dist))\n }\n println(mindist)\n}"}, {"source_code": "object CF911A extends App {\n\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n val i = Array.fill(n)(sc.nextInt).iterator\n\n var min = Int.MaxValue\n var mindist = 0\n var dist = 1\n while (i.hasNext) {\n i.next match {\n case c if c < min => min = c; mindist = 0\n case c if c == min => mindist = Math.min(mindist, dist); dist = 1\n case _ => dist += 1\n }\n }\n println(mindist)\n}"}], "src_uid": "67af292ff23880ad9fd4349729e36158"} {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject Solve extends App with fastIO{\n val n:Long = nextLong\n val aa = (for(i<-0L.until(n)) yield nextLong).toBuffer\n val a = aa.sortWith(_>_)\n var b = new ArrayBuffer[(Long,Long)]()\n var i = 0\n while(i_)\n var b = new ArrayBuffer[(Long,Long)]()\n var i = 0\n while(i_)\n var b = new ArrayBuffer[(Long,Long)]()\n var i = 0\n while(i0){\n if(l(i)==l(i-1)||l(i)-1==l(i-1)){\n\n if(lastPair==0){\n lastPair=l(i-1)\n \n }else{\n sum+=lastPair*l(i-1)\n lastPair=0\n }\n\n i-=2\n }\n else{\n i-=1\n }\n }\n out.println(sum)\n\n\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object CodeForces extends App {\n val n = readLine toInt\n val sticks = readLine split (' ') map (s => s.toLong)\n scala.util.Sorting.quickSort(sticks)\n\n val result = sticks.foldRight((0L, -1L, -1L))((stick, state) => state match {\n case (area, -1, oneside) => (area, stick, oneside)\n case (area, last, -1) => if (last - stick <= 1) (area, -1, stick) else (area, stick, -1)\n case (area, last, oneside) => {\n if (last - stick <= 1) (area + (stick * oneside), -1, -1) else (area, stick, oneside)\n }\n })\n\n println(result._1)\n}"}], "negative_code": [{"source_code": "object Main extends App {\n println(readLine().split(\" \").map(_.toInt).sum)\n}"}], "src_uid": "0e162ea665732714283317e7c052e234"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n var Array(n, k) = in.next().split(\" \").map(_.toInt)\n val data = in.next().split(\" \").map(_.toInt).sorted.reverse\n if (k > n)\n println(-1)\n else {\n if (k == n)\n println(\"0 0\")\n else if (data(k - 1) == data(k))\n println(-1)\n else\n println(s\"${data(k - 1)} ${data(k - 1)}\")\n }\n\n}", "positive_code": [{"source_code": "object Contest extends App{\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val as = readLine().split(\" \").map(_.toInt)\n util.Sorting.stableSort(as)\n if (k > n) println(\"-1\")\n else if (k == 0) println((as(n-1) + 1) + \" \" + (as(n-1) + 1))\n else println(as(n-k) + \" \" + as(n-k))\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P263B extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N, K = sc.nextInt\n val a = List.fill(N)(sc.nextInt).sorted.reverse\n val answer: String =\n if (K > N) \"-1\"\n else {\n val x = a(K - 1)\n x + \" \" + x\n }\n\n out.println(answer)\n out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val nk = readLine().split(\" \").map(_.toInt)\n val n = nk(0)\n val k = nk(1)\n val a = readLine().split(\" \").map(_.toInt)\n if (k > n) println(\"-1\")\n else if (k == n) println(\"0 0\")\n else {\n val (head, tail) = a.sorted.reverse.splitAt(k)\n if (head.last == tail.head) println(\"-1\")\n else println(head.last + \" \" + head.last)\n }\n }\n}"}, {"source_code": "import scala.Math.pow;\n\nobject App {\n def readInts:Array[Int] = (readLine split \" \") map (_.toInt)\n //> readInts: => Array[Int] //> solve: (n: Int, m: Int, prev: Int, a: Int, b: Int)(Int, Int)\n \n def f1_io() = {\n val Array(n, k) = readInts \n val source = readInts.sorted\n val p = n - k\n if (p == 0) print(source(p) + \" \" + source(p))\n else if (p < 0) print(-1)\n else if (source(p) == source(p-1)) print(-1)\n else print(source(p) + \" \" + source(p))\n } \n def main(args: Array[String]): Unit = {\n f1_io\n }\n\n}"}, {"source_code": "object B{\n def main(args: Array[String]){\n\n val (n, k)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val a=readLine.split(\" \").map(_.toInt).sorted\n\n if(k>n){\n println(\"-1\")\n }else{\n println(a(n-k)+\" \"+a(n-k))\n }\n }\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _263B extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val k = next.toInt\n val a = (1 to n).map(i => next.toInt).groupBy(i => i).toArray.map(i => (i._1, i._2.size)).sortBy(i => -i._1)\n val b = a.unzip._2.scanLeft(0)(_ + _).drop(1)\n val index = b.indexWhere(_ == k)\n if (index == -1) println(-1)\n else println(a(index)._1 + \" \" + a(index)._1)\n}\n"}], "negative_code": [{"source_code": "object B{\n def main(args: Array[String]){\n\n val (n, k)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val a=readLine.split(\" \").sorted\n\n if(k>n){\n println(\"-1\")\n }else{\n println(a(n-k)+\" \"+a(n-k))\n }\n }\n}\n"}], "src_uid": "4d743a00e11510c824080ad7f1804021"} {"source_code": "object Main extends App {\n\n def lexOrder(first: List[Long], second: List[Long]): Int = {\n (first, second) match {\n case (Nil, Nil) => 0\n case (Nil, _) => -1\n case (_, Nil) => 1\n case (h1 :: tail1, h2 :: tail2) =>\n if(h1 == h2) lexOrder(tail1, tail2)\n else if (h1 < h2) -1\n else 1 \n }\n }\n\n val n = readLine.toLong\n val start = (List[Long](), List[Long](), 0L, 0L)\n val (first, second, lastFirst, lastSecond) = (1L to n).foldLeft(start)({\n case ((f, s, lf, ls), index) =>\n val next = readLine.toLong\n if(next > 0) {\n (next :: f, s, index+1, ls)\n } else {\n (f, Math.abs(next) :: s, lf, index+1)\n }\n })\n\n val fs = first.sum\n val ss = second.sum\n\n if(fs < ss) {\n println(\"second\")\n } else if (fs > ss) {\n println(\"first\")\n } else {\n val fr = first.reverse\n val sr = second.reverse\n val lex = lexOrder(fr, sr)\n if(lex > 0) {\n println(\"first\")\n } else if (lex < 0) {\n println(\"second\")\n } else {\n if(lastFirst > lastSecond) println(\"first\") else println(\"second\")\n }\n }\n\n}", "positive_code": [{"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = Range(0, n).map(_ => in.next().toLong)\n val first = data.filter(_ > 0)\n val second = data.filter(_ < 0).map(-_)\n val sum1 = first.sum\n val sum2 = second.sum\n if (sum1 != sum2)\n if (sum1 > sum2)\n println(\"first\")\n else\n println(\"second\")\n else if (first.size != second.size || first.zip(second).exists(t => t._1 != t._2)) {\n val t = first.zip(second).find(t => t._1 != t._2)\n if (t.isEmpty)\n if (first.size > second.size)\n println(\"first\")\n else\n println(\"second\")\n else {\n if (t.get._1 > t.get._2)\n println(\"first\")\n else\n println(\"second\")\n }\n }\n else if (data.last > 0)\n println(\"first\")\n else\n println(\"second\")\n}"}, {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nobject B_VasyaAndWrestling {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextInt()\n\n val input = for (i <- 1 to n) yield {\n scanner.nextLong()\n }\n\n val firstPoints = input.filter(_ > 0)\n val secondPoints = input.filter(_ < 0).map(-_)\n\n if (firstPoints.sum != secondPoints.sum) {\n out.println(if (firstPoints.sum > secondPoints.sum) \"first\" else \"second\")\n } else {\n val firstNotNull = firstPoints.zip(secondPoints).map(x => x._1 - x._2).find(_ != 0)\n firstNotNull match {\n case Some(x) =>\n out.println(if (x > 0) \"first\" else \"second\")\n case None =>\n out.println(if (input.last > 0) \"first\" else \"second\")\n }\n }\n }\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = Range(0, n).map(_ => in.next().toLong)\n val first = data.filter(_ > 0)\n val second = data.filter(_ < 0).map(-_)\n val sum1 = first.sum\n val sum2 = second.sum\n if (sum1 != sum2)\n if (sum1 > sum2)\n println(\"first\")\n else\n println(\"second\")\n else if (first.head != second.head)\n if (first.head > second.head)\n println(\"first\")\n else\n println(\"second\")\n else if (data.last > 0)\n println(\"first\")\n else\n println(\"second\")\n}"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = Range(0, n).map(_ => in.next().toInt)\n val first = data.filter(_ > 0)\n val second = data.filter(_ < 0).map(-_)\n val sum1 = first.sum\n val sum2 = second.sum\n val str = first.mkString\n val str2 = second.mkString\n if (sum1 != sum2)\n if (sum1 > sum2)\n println(\"first\")\n else\n println(\"second\")\n else if (str != str)\n if (str > str2)\n println(\"first\")\n else\n println(\"second\")\n else if (data.last > 0)\n println(\"first\")\n else\n println(\"second\")\n}"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = Range(0, n).map(_ => in.next().toLong)\n val first = data.filter(_ > 0)\n val second = data.filter(_ < 0).map(-_)\n val sum1 = first.sum\n val sum2 = second.sum\n val str = first.mkString\n val str2 = second.mkString\n if (sum1 != sum2)\n if (sum1 > sum2)\n println(\"first\")\n else\n println(\"second\")\n else if (str != str2)\n if (str > str2)\n println(\"first\")\n else\n println(\"second\")\n else if (data.last > 0)\n println(\"first\")\n else\n println(\"second\")\n}"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = Range(0, n).map(_ => in.next().toInt)\n val first = data.filter(_ > 0)\n val second = data.filter(_ < 0)\n val sum1 = first.sum\n val sum2 = second.sum\n val str = first.mkString\n val str2 = second.map(-_).mkString\n if (sum1 != sum2)\n if (sum1 > sum2)\n println(\"first\")\n else\n println(\"second\")\n else if (str != str)\n if (str > str2)\n println(\"first\")\n else\n println(\"second\")\n else if (data.last > 0)\n println(\"first\")\n else\n println(\"second\")\n}"}, {"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = Range(0, n).map(_ => in.next().toInt)\n val first = data.filter(_ > 0)\n val second = data.filter(_ < 0).map(-_)\n val sum1 = first.sum\n val sum2 = second.sum\n val str = first.mkString\n val str2 = second.mkString\n if (sum1 != sum2)\n if (sum1 > sum2)\n println(\"first\")\n else\n println(\"second\")\n else if (str != str2)\n if (str > str2)\n println(\"first\")\n else\n println(\"second\")\n else if (data.last > 0)\n println(\"first\")\n else\n println(\"second\")\n}"}, {"source_code": "\n\nimport java.io.InputStream\nimport java.io.PrintStream\nimport java.util.Scanner\n\nobject B_VasyaAndWrestling {\n\n def main(args: Array[String]) {\n parseSolveAndPrint(System.in, System.out)\n }\n\n def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextInt()\n\n val input = for (i <- 1 to n) yield {\n scanner.nextInt()\n }\n\n val firstPoints = input.filter(_ > 0)\n val secondPoints = input.filter(_ < 0).map(-_)\n\n if (firstPoints.sum != secondPoints.sum) {\n out.println(if (firstPoints.sum > secondPoints.sum) \"first\" else \"second\")\n } else {\n val firstNotNull = firstPoints.zip(secondPoints).map(x => x._1 - x._2).find(_ != 0)\n firstNotNull match {\n case Some(x) =>\n out.println(if (x > 0) \"first\" else \"second\")\n case None =>\n out.println(if (input.last > 0) \"first\" else \"second\")\n }\n }\n }\n}\n"}, {"source_code": "object Main extends App {\n\n def lexOrder(first: List[Int], second: List[Int]): Int = {\n (first, second) match {\n case (Nil, Nil) => 0\n case (Nil, _) => -1\n case (_, Nil) => 1\n case (h1 :: tail1, h2 :: tail2) =>\n if(h1 == h2) lexOrder(tail1, tail2)\n else if (h1 < h2) -1\n else 1 \n }\n }\n\n val n = readLine.toInt\n val start = (List[Int](), List[Int](), 0, 0)\n val (first, second, lastFirst, lastSecond) = (1 to n).foldLeft(start)({\n case ((f, s, lf, ls), index) =>\n val next = readLine.toInt\n if(next > 0) {\n (next :: f, s, index+1, ls)\n } else {\n (f, Math.abs(next) :: s, lf, index+1)\n }\n })\n\n val fs = first.sum\n val ss = second.sum\n\n if(fs < ss) {\n println(\"second\")\n } else if (fs > ss) {\n println(\"first\")\n } else {\n val fr = first.reverse\n val sr = second.reverse\n val lex = lexOrder(fr, sr)\n if(lex > 0) {\n println(\"first\")\n } else if (lex < 0) {\n println(\"second\")\n } else {\n if(lastFirst > lastSecond) println(\"first\") else println(\"second\")\n }\n }\n\n}"}, {"source_code": "object Main extends App {\n\n def lexOrder(first: List[Int], second: List[Int]): Int = {\n 20\n }\n\n val n = readLine.toInt\n val start = (List[Int](), List[Int](), 0, 0)\n val (first, second, lastFirst, lastSecond) = (1 to n).foldLeft(start)({\n case ((f, s, lf, ls), index) =>\n val next = readLine.toInt\n if(next > 0) {\n (next :: f, s, index+1, ls)\n } else {\n (f, next :: s, lf, index+1)\n }\n })\n\n val fs = first.sum\n val ss = second.sum\n if(fs < ss) {\n println(\"second\")\n } else if (fs > ss) {\n println(\"first\")\n } else {\n val fr = first.reverse\n val sr = second.reverse\n val lex = lexOrder(fr, sr)\n if(lex > 0) {\n println(\"first\")\n } else if (lex < 0) {\n println(\"second\")\n } else {\n if(lastFirst > lastSecond) println(\"first\") else println(\"second\")\n }\n }\n\n}"}], "src_uid": "d3684227d1f12cf36dc302e1ffee8370"} {"source_code": "object P71A {\n def main(args : Array[String]) {\n val n = readInt\n (1 to n).map(i => work(readLine))\n \n def work(line: String) = {\n if (line.length > 10) {\n print(line.head); print(line.length - 2); println(line.last) \n } else println(line)\n }\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Solution {\n\n\tvar n = readInt\n\tvar words = Array.fill[String](n)(null)\n\tfor(i <- 0 until n) {\n\t\twords(i) = readLine\n\t}\n\n\tdef main(args:Array[String]):Unit = {\n\t\tvar ret = Array.fill[String](n)(null)\n\t\tfor(i <- 0 until n) {\n\t\t\tif(words(i).length > 10) {\n\t\t\t\tvar k = 0\n\t\t\t\tfor(j <- 1 until words(i).length-1) k += 1\n\t\t\t\tret(i) = words(i)(0).toString + k.toString + words(i)(words(i).length-1).toString\n\t\t\t}\n\t\t\telse ret(i) = words(i)\n\t\t\tprintln(ret(i))\n\t\t}\n\t}\n\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val num = readLine.toInt\n\n def wtlw(n:Int):Unit = n match {\n case 0 => print(\"\")\n case m => {\n val line = readLine\n val lline = line.length\n if(lline < 11) println(line) else println(line.head + (lline-2).toString + line.substring(lline - 1))\n wtlw(n-1)\n }\n\n }\n wtlw(num)\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Test {\n def main(args1: Array[String]) {\n// val args = Console.readLine().split(\" \")\n// val (v: Long, y: Long, z: Long) = (args(0).toLong, args(1).toLong, args(2).toLong)\n\n\n val len = 10\n val args = Console.readLine()\n val count = args.toInt\n\n for (it <- 0 until count) {\n val line = StdIn.readLine\n if (line.length > 10) {\n println(s\"${line.substring(0, 1)}${line.length - 2}${line.substring(line.length - 1)}\")\n }\n else {\n println (line)\n }\n }\n// val res = balls.size\n// println(res)\n }\n}"}, {"source_code": "object WayTooLongWords {\n def main(args : Array[String]) {\n val gls = io.Source.stdin.getLines\n gls drop(1)\n gls.map(shorten _) foreach(println)\n }\n def shorten(word : String) : String = {\n val len = word.length() - 2\n if (len > 8)\n return s\"${word(0)}$len${word.last}\"\n return word\n }\n}\n"}, {"source_code": "object main extends App{\n val n = readLine().toInt\n for(_ <- 1 to n){\n var s = readLine()\n println(if(s.size > 10) s.head + (s.size-2).toString + s.last else s )\n }\n}"}, {"source_code": "import scala.Math.ceil\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = readLine.toInt\n\n for (i <- 0 to n - 1) {\n var s = readLine\n if (s.length > 10) {\n print(s(0))\n print(s.length - 2)\n println(s(s.length - 1))\n } else\n println(s)\n }\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject WayToLong {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n for (_ <- 0 until n) {\n val word = readLine\n val ans = \n if (word.length > 10)\n word(0) + (word.length - 2).toString + word.last\n else word\n println(ans)\n }\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject WayToLong {\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val words = for (_ <- 0 until n) yield readLine()\n words.map(x => if (x.length > 10) s\"${x(0)}${x.length - 2}${x.last}\" else x)\n .foreach(println)\n }\n}"}, {"source_code": "/*input\n4\nword\nlocalization\ninternationalization\npneumonoultramicroscopicsilicovolcanoconiosis\n*/\n\nimport java.util.Scanner\nimport scala.io.StdIn\n\nobject Solution {\n\tdef main(args: Array[String]): Unit = {\n\n\t\tval n = StdIn.readInt();\n\t\tvar i = 1;\n\t\twhile(i <= n)\n\t\t{\n\t\t\tval str = StdIn.readLine();\n\t\t\tif(str.length() <= 10) println(str)\n\t\t\telse{\n\t\t\t\tprint(str(0));\n\t\t\t\tprint(str.length() - 2);\n\t\t\t\tprintln(str(str.length() - 1))\n\t\t\t}\n\t\t\ti += 1;\n\t\t}\n\t}\n}"}, {"source_code": "import java.util.Scanner\n\nobject A00071 extends App {\n def shorten(word: String): String = {\n def trim = word(0).toString + (word.size - 2) + word(word.size - 1)\n val isLonger = word.size > 10\n if (isLonger) trim else word\n }\n \n def execute(fn: String => String)(scanner: Scanner, n: Int) = {\n for (i <- 1 to n) {\n val str = scanner.nextLine();\n println(fn(str));\n }\n }\n \n val scanner = new Scanner(System.in)\n val n = scanner.nextInt();\n scanner.nextLine();\n execute(shorten)(scanner, n)\n scanner.close()\n}"}, {"source_code": "object Abrev {\n \n import scala.io.StdIn.{readLine,readInt}\n\n def readStdIn: List[String] = {\n val num = readLine.toInt\n def inner(lst: List[String], cnt: Int): List[String] = {\n if (num == cnt) lst.reverse\n else inner(readLine :: lst, cnt+1)\n }\n inner(List(), 0)\n }\n\n def abbreviateWord(str: String): String = {\n if (str.length > 10) {\n str(0)+(str.length-2).toString+str.last\n }else str\n }\n\n def abbreviateAll(lst: List[String]): List[String] = {\n lst.map(abbreviateWord)\n }\n\n def main(args: Array[String]): Unit = {\n val inp = readStdIn\n abbreviateAll(inp).foreach(println)\n }\n}\n"}, {"source_code": "object Hello extends App {\n\n import scala.io.StdIn._\n\n val k = readInt()\n\n def input(n: Int) = (1 to n).map(_ => readLine()).toSeq\n\n def toSeq(str: String) =\n str.toSeq.map(ch => Integer.parseInt(ch.toString))\n\n def cut(s: String) = if(s.length > 10) s.head + (s.length - 2).toString + s.reverse.head else s\n\n input(k).map(cut).map(println)\n}"}, {"source_code": "object Cf71A extends App {\n val n = readInt()\n for (i <- 1 to n) {\n val s = readLine()\n val len = s.length\n println(if (len <= 10) s else s(0) + (len - 2).toString + s(len - 1))\n }\n}"}, {"source_code": "import scala.collection.mutable._\nimport scala.math._\nimport scala.util.control.Breaks.break\nimport scala.util.control.Breaks.breakable\nimport java.util._\nobject Main extends App {\n val sc = new Scanner(System.in)\n val n = readLine.toInt\n for(i <- 0 until n) {\n val s = readLine\n if(s.length <= 10) println(s)\n else println(s.head.toString + (s.length - 2) + s.last.toString)\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nobject WayTooLongWords extends App {\n\n //println(\"Enter the number of words\")\n val numb = scala.io.StdIn.readInt()\n\n def askWord(n: Int) = {\n val container = mutable.ArrayBuffer[String]()\n Range(1, n + 1).foreach(x => {\n \n val word = scala.io.StdIn.readLine()\n container += word\n })\n container\n }\n\n def abbr(w: String) = {\n if (w.length() > 10) {\n s\"${w(0)}${w.length() - 2}${w.last}\"\n } else w\n\n }\n askWord(numb).foreach((x: String) => println(abbr(x)))\n\n //askWord(numb)\n\n \n //println(abbr(\"nonsapevocosascrivere\"))\n //Range(1,10).foreach(println)\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject TooLongWords_71A {\n def main(args: Array[String]): Unit = {\n val numRows = StdIn.readInt()\n (1 to numRows).foreach { i =>\n val row = StdIn.readLine()\n val len = row.length\n if (len > 10) {\n println(row.head + (len - 2).toString + row.last)\n } else {\n println(row)\n }\n }\n }\n}\n"}, {"source_code": "object Main extends App {\n val size = readLine().toInt\n for (i <- 1 to size) {\n val str = readLine()\n if (str.size > 10) println(str.head + (str.size - 2).toString + str.last)\n else println(str)\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = readInt\n (0 until n).foreach { k =>\n val s = readLine\n val result = if (s.length > 10) s\"${s.head}${s.length - 2}${s.last}\" else s\n println(result)\n }\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nobject WayTooLongWords extends App {\n\n val numb = scala.io.StdIn.readInt()\n \n for (x <- 1 to numb){\n val word = scala.io.StdIn.readLine()\n val s = word.length()\n println(if (s > 10) word(0) + s\"${s - 2}\" + word.last else word) \n }\n\n}\n"}, {"source_code": "// http://codeforces.com/problemset/problem/71/A\n\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\n\nobject WayTooLongWords {\n def main(args: Array[String]): Unit = {\n val n: Int = readInt()\n for(i <- 1 to n) {\n var word = readLine()\n var len = word.length\n if(len > 10) {\n println(f\"${word.substring(0, 1)}%s${len-2}%d${word.takeRight(1)}%s\")\n } else {\n println(word)\n }\n }\n }\n}\n"}, {"source_code": "object Main {\n\timport java.{util=>ju}\n\timport scala.annotation._\n\timport scala.collection._\n\timport scala.collection.{mutable => mu}\n\timport scala.collection.JavaConverters._\n\timport scala.math._\n\n\tdef main(args:Array[String])\n\t{\n\t\tval sc = new ju.Scanner(System.in)\n\t\tval n = sc.nextInt();\n\t\tval arr = ((1 to n) map (_ => sc.next())).toArray\n\t\tsolve(0, arr, n);\n\t}\n\n\tdef solve(i:Int, arr:Array[String], n:Int)\n\t{\n\t\tif(i==n) return\n\n\t\tval word = arr(i);\n\n\t\tif(word.length <= 10)\n\t\t\tprintln(word)\n\t\telse\n\t\t{\n\t\t\tprint(word.charAt(0))\n\t\t\tprint(word.length-2)\n\t\t\tprint(word.charAt(word.length-1))\n\t\t\tprintln()\n\t\t}\n\n\t\tsolve(i+1, arr, n)\n\t}\n}"}, {"source_code": "object CF0071A extends App {\n\n val n = readInt()\n\n (1 to n).foreach(e => {\n val str = readLine()\n if (str.length > 10) {\n println(str.charAt(0).toString + (str.length - 2) + str.charAt(str.length -1 ).toString)\n } else {\n println(str)\n }\n })\n}\n"}, {"source_code": "import scala.io.Source\n\n/** A. Way Too Long Words\n * http://codeforces.com/problemset/problem/71/A\n *\n * @author Yuichiroh Matsubayashi\n * Created on 15/01/19.\n */\nobject P71A {\n def main(args: Array[String]) {\n val words = Source.stdin.getLines().drop(1)\n abbrs(words).foreach(println)\n }\n\n def abbrs(words: Iterator[String]) = words.map { w =>\n if (w.length > 10) w.head + (w.length - 2).toString + w.last\n else w\n }\n}\n"}, {"source_code": "/**\n * Created by mikhailvarnavskikh on 04.04.15.\n */\nobject Main {\n\n def main(args: Array[String]) {\n val std = scala.io.StdIn\n val Array( n ) = std.readLine().split( \" \" ).map( _.toInt )\n for ( i <-1 to n ) {\n val word = std.readLine\n val res = if ( word.length > 10 ) {\n word(0) + (word.length - 2).toString + word( word.length -1 )\n } else {\n word\n }\n println( res )\n }\n\n\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject Main {\n\n def main(args: Array[String]) {\n val n = readInt()\n (1 to n).foreach { i =>\n val s = readLine()\n val ans = if (s.length > 10) \"\" + s(0) + (s.length - 2) + s(s.length - 1) else s\n println(ans)\n }\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject WayTooLongWords extends App {\n\n val n = StdIn.readInt()\n for (i <- Range(0, n - 1)) {\n println(imply(StdIn.readLine()))\n }\n print(imply(StdIn.readLine()))\n\n def imply(word: String): String = {\n val len = word.length\n if (len <= 10) word\n else {\n word.charAt(0) + (len - 2).toString + word.charAt(len - 1)\n }\n }\n}"}, {"source_code": "object HelloWorld {\n def main(args: Array[String]): Unit = {\n \tvar m = readInt()\n \tfor (i <- 1 to m){\n \t\tvar s = readLine()\n \t\tif (s.length() > 10){\n \t\t\tvar t = s(0) + (s.length()-2).toString + s(s.length()-1)\n \t\t\t\tprintln(t)\n \t\t\t}else{\n \t\t\t\tprintln(s)\n \t\t\t}\n \t}\n \t}\n}\n"}, {"source_code": "\nobject Main extends App {\nval n = readInt()\n\nval l = (for ( i <- 0 until n) yield{readLine})\n\nfor ( i <- 0.to(n-1) ) {\nif (l(i).length<=10) \nprintln(l(i))\nelse { \nprint(l(i).head)\nprint(l(i).length-2)\nprintln(l(i).last)\n}\n}\n}"}, {"source_code": "import scala.io.StdIn\n\n\nobject TooLongWords extends App {\n\n val numberOfWords: Short = StdIn.readShort()\n\n val words: Seq[String] = for (_ <- 1 to numberOfWords) yield StdIn.readLine()\n val onlyShortWords = words.map {\n case word if word.length > 10 => word.head + (word.length - 2).toString + word.last\n case word => word\n }\n\n onlyShortWords.foreach(println)\n}"}, {"source_code": "object cf extends App{\n val t = readInt()\n for (t <- 0 to t-1) {\n var s = readLine()\n val l = s.length()\n if (l > 10) {\n s = s(0)+(l-2).toString+s(l-1)\n println(s)\n }\n else {\n println(s)\n }\n }\n}"}, {"source_code": " object Main extends App {\n\n def A71={\n def packWord(s:String, i: Int): String ={\n s.length> i match {\n case false => s\n case true => s\"${s(0)}${s.length - 2}${s.last}\"\n }\n }\n (1 to readInt).map(x => readLine).map(packWord(_,10)).foreach(println(_))\n }\n\n A71\n}"}, {"source_code": "import scala.io.StdIn\nobject solution extends App{\n \n val tests = StdIn.readInt\n \n for(test <- 1 to tests){\n val text = StdIn.readLine\n if(text.length > 10){\n val output = text.head.toString + (text.length-2) + text.last.toString\n println(output) \n } else{\n println(text)\n }\n \n \n \n }\n \n}"}, {"source_code": "import scala.collection.immutable.StringOps\nobject Main {\n def res(x: Int) {\n val e = readLine\n println( if( e.size > 10 ) e.head.toString + (e.size-2) + e.last.toString else e)\n }\n def main(args: Array[String]) {\n val N = readInt\n 1 to N foreach( res )\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject Main {\n\n def fix(s: String) = {\n if (s.length > 10)\n \"\" + s(0) + (s.length() - 2) + s(s.length - 1)\n else\n s\n }\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n val n = in.nextInt\n val s = for (i <- 0 until n) yield fix(in.next)\n println(s.mkString(\"\\n\"))\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Solution extends App {\n val N = StdIn.readInt()\n for (i <- 1 to N) {\n val str = StdIn.readLine()\n if (str.length <= 10) {\n println(str)\n } else {\n println(s\"${str.head}${str.length - 2}${str.last}\")\n }\n }\n}"}, {"source_code": "object Main {\n def solve(s: String): String = {\n if (s.length <= 10)\n s\n else\n s(0).toString + (s.length - 2) + s(s.length - 1)\n }\n\n def main(args: Array[String]) {\n val n = readInt()\n (for (i <- 1 to n) yield solve(readLine())) foreach println\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P71A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextLine.toInt\n\n def abbreviate(s: String): String = s.head.toString + (s.length - 2).toString + s.last.toString\n\n def solve(s: String): String =\n if (s.length <= 10) s\n else abbreviate(s)\n\n for (i <- 0 until N)\n out.println(solve(sc.nextLine))\n out.close\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject R71_A extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n sc.nextLine()\n val words = for(i <- 0 until n) yield sc.nextLine()\n \n words.foreach(w => {println(shorten(w,10))})\n\n def shorten(w:String, k:Int):String = {\n if(w.length > k){\n \"\" + w.charAt(0) + (w.length()-2) + w.charAt(w.length-1)\n }else{\n w\n }\n }\n}"}, {"source_code": "object Program extends App{\n val times = scala.io.StdIn.readInt()\n val input = (1 to times).map(_ => scala.io.StdIn.readLine())\n val refined = input.map(x => if(x.size > 10) x.take(1) + (x.size-2) + x.takeRight(1) else x)\n val res = refined\n res.foreach(x => println(x))\n}\n"}, {"source_code": "object Codeforces71A extends App{\n\n def Approx(rec:Double):Long={\n if (rec-rec.toInt>0) {\n return rec.toInt+1\n }\n else{\n return rec.toInt\n }\n }\n\n var ans:Array[String]=Array()\n val s:Int=scala.io.StdIn.readInt\n for (i <- 1 to s){\n val k:String=scala.io.StdIn.readLine\n val wordlength=k.length\n if (wordlength>10){\n var temp:String=\"\"\n temp+=k(0)\n temp+=wordlength-2\n temp+=k(wordlength-1)\n ans = ans:+temp\n }\n else{\n ans = ans:+k\n }\n }\n for (i <- 0 to s-1){\n println(ans(i))\n }\n\n\n}\n"}, {"source_code": "/**\n * Created by vol on 9/15/14.\n */\nobject A71 extends App{\n val n = readInt()\n\n //println(if (str.length > 10) str(0) + (str.length - 2) + str(str.length) else str)\n def loop(n:Int, i:Int, value:String):String = {\n val str = readLine()\n if (n == i)\n if (str.length > 10)\n value + \"\\n\" + str(0) + (str.length - 2).toString + str(str.length - 1)\n else value + \"\\n\" + str\n\n else\n if (str.length > 10)\n loop(n, i + 1, value + \"\\n\" + str(0) + (str.length - 2).toString + str(str.length - 1))\n else {\n loop(n, i + 1, value + \"\\n\" + str) }\n }\n\n println(loop(n , 1 , \"\"))\n}\n"}, {"source_code": "import scala.Console\nimport util.control.Breaks._\n\n\nobject App {\n \n \n def main(args : Array[String]) {\n \n \n var maxCount = 0\n var line :String = \"\"\n \n maxCount = Console.readLine().toInt\n \n for (i <- 1 to maxCount) {\n \n line = Console.readLine()\n \n \n if(line.length() <= 10){\n println(line)\n }else{\n val value = line.length() - 2\n println(\"\"+line.charAt(0).toChar + value + line.charAt(line.length() - 1).toChar)\n }\n \n }\n \n }\n\n}"}, {"source_code": "\nimport scala.Console\nimport util.control.Breaks._\n\n\nobject App {\n \n \n def main(args : Array[String]) {\n \n var curCount = 0\n var maxCount = 0\n var line :String = \"\"\n \n maxCount = Console.readLine().toInt\n \n for (i <- 1 to maxCount) {\n \n line = Console.readLine()\n \n breakable{\n if(line.length() <= 10){\n println(line)\n break\n }else{\n val value = line.length() - 2\n println(\"\"+line.charAt(0).toChar + value + line.charAt(line.length() - 1).toChar)\n }\n }\n }\n \n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject _71A extends App {\n def convert(w: String): String =\n w.head + (w.length-2).toString + w.last\n\n val scanner = new Scanner(System.in)\n val n = scanner.nextInt()\n val words = Array.fill(n)(scanner.next())\n words.foreach(w => println(if (w.length > 10) convert(w) else w))\n}\n\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by mid-s on 11.09.16.\n */\nobject Demo {\n def main(args: Array[String]) {\n val count = readLine().toString().toInt\n\n var resp = new ArrayBuffer[String]\n for (i <- 1 to count) {\n var ln = readLine().toString()\n if (ln.length > 10) {\n resp += (ln(0).toString + (ln.length -2).toString + ln(ln.length -1).toString)\n //println(ln(0).toString + (ln.length -2).toString + ln(ln.length -1).toString)\n } else {\n resp += (ln)\n //println(ln)\n }\n }\n for (x <- resp) {\n println(x)\n }\n\n }\n}\n\n\n"}, {"source_code": "object A71 extends App {\n\n var n: Int = readInt()\n while (n>0){\n val input = readLine()\n val l = input.length\n if (l > 10){\n println(input(0)+(l-2).toString+input(l-1))\n } else {\n println(input)\n }\n n-=1\n }\n\n}\n\n\n"}, {"source_code": "import scala.io.StdIn\n\nobject P71A {\n def main(args : Array[String]) {\n val n = StdIn.readInt()\n for (i <- 1 to n) solveLine(StdIn.readLine())\n Console.out.flush()\n \n def solveLine(s: String) = {\n if (s.length > 10) {\n Console.out.print(s.head.toString)\n Console.out.print((s.length - 2).toString)\n Console.out.print(s.last.toString)\n }\n else Console.out.print(s)\n Console.out.println()\n }\n }\n}"}, {"source_code": "import java.io._\n\nobject P71A {\n def main(args : Array[String]) {\n val br = new BufferedReader(new InputStreamReader(System.in))\n val bw = new BufferedWriter(new OutputStreamWriter(System.out))\n val n = br.readLine.toInt\n (1 to n).map(i => solveLine(br.readLine))\n bw.close\n \n def solveLine(line: String) {\n if (line.length > 10) {\n bw.write(line.head)\n bw.write((line.length - 2).toString)\n bw.write(line.last)\n }\n else bw.write(line)\n bw.write(13); bw.write(10)\n }\n }\n}"}, {"source_code": "object P71A {\n def main(args : Array[String]) {\n val n = readInt\n for (i <- 1 to n) work(readLine)\n writeCBuf\n \n def work(line: String) = {\n if (line.length > 10) {\n add(line.head)\n printInt(line.length - 2)\n add(line.last)\n } else add(line)\n add(13.toByte); add(10.toByte)\n }\n }\n \n ///********************************************************************\n /// easy output buffer\n ///\n var cbufCursor = 0;\n val cbuf = new Array[Byte](8192);\n def writeCBuf {\n System.out.write(cbuf, 0, cbufCursor);\n }\n \n def add(s: String) {\n add(s.getBytes(), 0, s.length());\n }\n \n def add(c: Array[Byte]) {\n for (i <- 0 until c.length) add(c(i))\n }\n \n def add(c: Array[Byte], startIndex: Int, endIndex: Int) {\n for (i <- startIndex until endIndex) add(c(i));\n }\n \n def add(c: Char) { add(c.toByte) }\n \n def add(c: Byte) {\n cbufCursor += 1\n cbuf(cbufCursor - 1) = c;\n if (cbufCursor == cbuf.length) {\n writeCBuf\n cbufCursor = 0;\n }\n }\n \n ///********************************************************************\n /// easy input buffer\n ///\n val rbuf = new Array[Byte](8192); \n var canReadBufMore = true;\n var rbufCursor = rbuf.length;\n var readSize = 0;\n def readByte: Byte = {\n try {\n if (rbufCursor >= rbuf.length) {\n if (canReadBufMore) {\n readSize = System.in.read(rbuf);\n if (readSize < rbuf.length) {\n canReadBufMore = false;\n }\n rbufCursor = 0;\n }\n }\n } catch { case e: Exception => /* do nothing */}\n if (rbufCursor != readSize) {\n rbufCursor += 1\n rbuf(rbufCursor - 1)\n } else -1;\n }\n \n ///********************************************************************\n /// for read integers\n ///\n def readInt : Int = {\n var result = 0\n var read: Byte = 0\n var sign = false\n\n do {\n read = readByte\n } while (read != -1 && (read != '-' && read < '0' || read > '9'))\n\n if (read == -1) return Integer.MIN_VALUE;\n if (read == '-') { sign = true; read = readByte }\n\n do {\n result = (result << 3) + (result << 1) + read - '0';\n read = readByte;\n } while (read != -1 && read >= '0' && read <= '9');\n if (read == 13) readByte; // skip 10\n\n if (sign) -result else result\n }\n \n ///********************************************************************\n /// for read line\n ///\n val lBuf = new Array[Byte](100)\n def readLine: String = {\n var read = readByte;\n var lPointer = 0;\n try {\n while (read > 13) {\n lPointer += 1\n lBuf(lPointer - 1) = read;\n read = readByte\n }\n if (read == -1) return null;\n if (read == 13) readByte; // skip 10\n } catch { case e: Exception => /* do nothing */}\n return new String(lBuf, 0, lPointer);\n }\n \n ///********************************************************************\n /// for print long\n ///\n val ibuf = new Array[Byte](20);\n def printInt(i: Int) { printLong(i.toLong) }\n def printLong(l: Long) {\n var i = l\n var q, r = 0L\n var sign = false\n if (i < 0) {\n sign = true;\n i = -i;\n }\n var charPos = ibuf.length;\n \n // Generate two digits per iteration\n while (i >= 65536) {\n q = i / 100;\n // really: r = i - (q * 100);\n r = i - ((q << 6) + (q << 5) + (q << 2));\n i = q;\n \n charPos -= 1\n ibuf(charPos) = DigitOnes(r.toInt);\n charPos -= 1\n ibuf(charPos) = DigitTens(r.toInt);\n }\n\n // Fall thru to fast mode for smaller numbers\n // assert(i <= 65536, i);\n do {\n q = (i * 52429) >>> 19;//(16+3);\n r = i - ((q << 3) + (q << 1)); // r = i-(q*10)\n charPos -= 1\n ibuf(charPos) = DigitOnes(r.toInt);\n i = q;\n } while (i != 0)\n if (sign) {\n charPos -= 1\n ibuf(charPos) = '-';\n }\n// System.out.write(ibuf, charPos, ibuf.length - charPos);\n add(ibuf, charPos, ibuf.length); //if u use manual output buffer\n }\n \n val DigitTens = Array(\n '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',\n '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',\n '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',\n '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',\n '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',\n '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',\n '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',\n '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',\n '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',\n '9', '9', '9', '9', '9', '9', '9', '9', '9', '9').map(_.toByte)\n\n val DigitOnes = Array(\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9').map(_.toByte)\n}"}, {"source_code": "object P71A {\n def main(args : Array[String]) {\n val n = readInt\n for (i <- 1 to n) work(readLine)\n \n def work(line: String) = {\n if (line.length > 10) {\n print(line.head); print(line.length - 2); println(line.last) \n } else println(line)\n }\n }\n \n ///********************************************************************\n /// easy input buffer\n ///\n val rbuf = new Array[Byte](8192); \n var canReadBufMore = true;\n var rbufCursor = rbuf.length;\n var readSize = 0;\n def readByte: Byte = {\n try {\n if (rbufCursor >= rbuf.length) {\n if (canReadBufMore) {\n readSize = System.in.read(rbuf);\n if (readSize < rbuf.length) {\n canReadBufMore = false;\n }\n rbufCursor = 0;\n }\n }\n } catch { case e: Exception => /* do nothing */}\n if (rbufCursor != readSize) {\n rbufCursor += 1\n rbuf(rbufCursor - 1)\n } else -1;\n }\n \n ///********************************************************************\n /// for read integers\n ///\n def readInt : Int = {\n var result = 0\n var read: Byte = 0\n var sign = false\n\n do {\n read = readByte\n } while (read != -1 && (read != '-' && read < '0' || read > '9'))\n\n if (read == -1) return Integer.MIN_VALUE;\n if (read == '-') { sign = true; read = readByte }\n\n do {\n result = (result << 3) + (result << 1) + read - '0';\n read = readByte;\n } while (read != -1 && read >= '0' && read <= '9');\n if (read == 13) readByte; // skip 10\n\n if (sign) -result else result\n }\n \n ///********************************************************************\n /// for read line\n ///\n val lBuf = new Array[Byte](100)\n def readLine: String = {\n var read = readByte;\n var lPointer = 0;\n try {\n while (read > 13) {\n lPointer += 1\n lBuf(lPointer - 1) = read;\n read = readByte\n }\n if (read == -1) return null;\n if (read == 13) readByte; // skip 10\n } catch { case e: Exception => /* do nothing */}\n return new String(lBuf, 0, lPointer);\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject P71A {\n def main(args : Array[String]) {\n val n = StdIn.readInt\n for (i <- 1 to n) work(StdIn.readLine)\n \n def work(line: String) = {\n if (line.length > 10) {\n print(line.head); print(line.length - 2); println(line.last) \n } else println(line)\n }\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject P71A {\n def main(args : Array[String]) {\n val n = StdIn.readInt\n for (i <- 1 to n) println(change(StdIn.readLine))\n def change(line: String): String = {\n if (line.length > 10) line.head.toString + (line.length - 2) + line.last\n else line\n }\n }\n}"}, {"source_code": "object P71A {\n def main(args : Array[String]) {\n val n = readInt\n for (i <- 1 to n) work(readLine)\n \n def work(line: String) = {\n if (line.length > 10) {\n print(line.head); print(line.length - 2); println(line.last) \n } else println(line)\n }\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) {\n val n = StdIn.readInt()\n\n for (_ <- 1 to n ) {\n val s = StdIn.readLine()\n\n if (s.length > 10) {\n println(\"\" + s.charAt(0) + (s.length - 2) + s.charAt(s.length - 1))\n } else {\n println(s)\n }\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject LongWords {\n \n def main(args: Array[String]) {\n val n = readInt\n for (i <- 1 to n) {\n val word = readLine\n if (word.length <= 10) println(word)\n else println(\"\" + word.head + (word.length()-2) + word.last)\n }\n }\n \n \n}"}, {"source_code": "import scala.io.StdIn\n\nobject Source extends App {\n\n val n = StdIn.readLine().toInt\n\n (1 to n).map(_ => StdIn.readLine()).map(s => {\n if (s.length <= 10) s\n else s.take(1) + (s.length - 2) + s.takeRight(1)\n }).foreach(println)\n\n}\n"}, {"source_code": "object I18n extends App {\n\n def replace(s: String) = if (s.length > 10) s\"${s(0)}${s.length - 2}${s(s.length - 1)}\" else s\n\n (1 to readInt()).map(line => replace(readLine())).foreach(println)\n\n}"}, {"source_code": "object Main{\n\n def main(args:Array[String]){\n val n = readLine.toInt\n for(i<- 0 until n){\n val s = readLine\n if(s.length()<=10)\n println(s)\n else{\n print(s(0))\n print(s.length()-2)\n println(s(s.length()-1))\n }\n }\n \n }\n}"}, {"source_code": "object test\n{\n def main(args : Array[String])\n {\n val n = readInt()\n for(i <- 1 to n)\n {\n val s = readLine()\n if(s.length > 10)\n println(s(0)+(s.length-2).toString+s(s.length-1))\n else\n println(s)\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\n\n/**\n * Created by dr0ff on 22/02/16.\n */\nobject WayTooLongWords extends App {\n val in = new Scanner(System.in)\n val wnum = in.nextLine().trim.toInt\n \n for (_ <- 0 until wnum) yield {\n val word = in.nextLine()\n println(compress(word.trim()))\n }\n\n def compress(word: String): String =\n if (word.length > 10)\n word.take(1) + (word.length - 2).toString + word.drop(word.length - 1)\n else\n word\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject WayTooLongWords_71A extends App {\n def abbrv(word: String): String = {\n if (word.length > 10)\n word(0) + (word.length - 2).toString() + word(word.length - 1)\n else\n word\n }\n\n val n = readInt\n\n for (i <- 1 to n) yield {\n println(abbrv(readLine))\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val times = readLine().toInt\n for (_ <- 1 to times) {\n val str = readLine()\n if (str.length <= 10) {\n println(str)\n }\n else {\n print(str(0))\n print(str.length - 2)\n println(str(str.length - 1))\n }\n }\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Orhan on 2/23/2017.\n */\nobject WayTooLongWords extends App{\n val line = new Scanner(System.in)\n var wordCount = line.nextInt()\n var wordList = new Array[String](wordCount)\n for (i <- 0 until wordCount){\n wordList(i) = line.next();\n }\n\n for (word <- wordList){\n if (word.length > 10) println(\"\" + word.charAt(0) + (word.length - 2) + word.charAt(word.length - 1))\n else println(word)\n }\n}\n"}, {"source_code": "object t71a extends App {\n\n import java.io.{BufferedReader, InputStreamReader}\n import java.util.StringTokenizer\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n val input = br.readLine()\n val st = new StringTokenizer(input)\n val wordCount = Integer.parseInt(st.nextToken(\" \"))\n val maxLength = 10\n val wordList = for(i <- 1 to wordCount) yield br.readLine()\n wordList.foreach { word =>\n if(word.length <= 10) println(word)\n else {\n val firstLetter = word(0)\n val lastLetter = word(word.length - 1)\n println(s\"$firstLetter${word.length-2}$lastLetter\")\n }\n }\n\n}"}], "negative_code": [{"source_code": "object Main extends App {\n\n def A71={\n def packWord(s:String, i: Int): String ={\n s.length> i match {\n case false => s\n case true => s\"${s(0)}${s.length - 2}${s.last}\"\n }\n }\n (1 to readInt).map(x => readLine).map(packWord(_,10)).foreach(println(_))\n }\n\n\n}"}, {"source_code": "object Solution71A extends Application {\n\n def solution() {\n val n = _int\n val lines = 1.to(n).map(_ => _string)\n val result = lines.map(l => l match {\n case a if (a.length <= 11) => a\n case b => {\n val len = b.length\n b.charAt(0) + (len - 2).toString + b.charAt(len - 1)\n }\n })\n result.foreach(println(_))\n }\n\n //////////////////////////////////////////////////\n import java.util.Scanner\n val SC: Scanner = new Scanner(System.in)\n def _line: String = SC.nextLine\n def _int: Int = SC.nextInt\n def _long: Long = SC.nextLong\n def _string: String = SC.next\n solution()\n}"}, {"source_code": "import scala.collection.mutable._\nimport scala.math._\nimport scala.util.control.Breaks.break\nimport scala.util.control.Breaks.breakable\nimport java.util._\nobject Main extends App {\n val sc = new Scanner(System.in)\n val n = readLine.toInt\n for(i <- 0 until n) {\n val s = readLine\n if(s.length < 10) println(s)\n else println(s.head.toString + (s.length - 2) + s.last.toString)\n }\n}\n"}, {"source_code": "object Main {\n\timport java.{util=>ju}\n\timport scala.annotation._\n\timport scala.collection._\n\timport scala.collection.{mutable => mu}\n\timport scala.collection.JavaConverters._\n\timport scala.math._\n\n\tdef main(args:Array[String])\n\t{\n\t\tval sc = new ju.Scanner(System.in)\n\t\tval n = sc.nextInt();\n\t\tval arr = ((1 to n) map (_ => sc.next())).toArray\n\t\tsolve(0, arr, n);\n\t}\n\n\tdef solve(i:Int, arr:Array[String], n:Int)\n\t{\n\t\tif(i==n) return\n\n\t\tval word = arr(i);\n\n\t\tif(word.length < 10)\n\t\t\tprintln(word)\n\t\telse\n\t\t{\n\t\t\tprint(word.charAt(0))\n\t\t\tprint(word.length-2)\n\t\t\tprint(word.charAt(word.length-1))\n\t\t\tprintln()\n\t\t}\n\n\t\tsolve(i+1, arr, n)\n\t}\n}"}, {"source_code": "\nimport scala.io.StdIn\n\nobject WayTooLongWords extends App {\n\n val n = StdIn.readInt()\n for (i <- Range(0, n - 1)) {\n println(imply(StdIn.readLine()))\n }\n print(imply(StdIn.readLine()))\n\n def imply(word: String): String = {\n val len = word.length\n if (len < 10) word\n else {\n word.charAt(0) + (len - 2).toString + word.charAt(len - 1)\n }\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject WayTooLongWords extends App {\n\n val n = StdIn.readInt()\n for (i <- Range(0, n)) {\n print(imply(StdIn.readLine()))\n }\n\n def imply(word: String): String = {\n val len = word.length\n if (len < 10) word\n else {\n word.charAt(0) + (len - 2).toString + word.charAt(len - 1)\n }\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject WayTooLongWords extends App {\n\n val n = StdIn.readInt()\n for (i <- Range(0, n)) {\n println(imply(StdIn.readLine()))\n }\n\n def imply(word: String): String = {\n val len = word.length\n if (len < 10) word\n else {\n word.charAt(0) + (len - 2).toString + word.charAt(len - 1)\n }\n }\n}"}, {"source_code": "object Main extends App {\nval n = readInt()\n\nval l = (for ( i <- 0 until n) yield{readLine})\n\nfor ( i <- 0.to(n-1) ) {\nif (l(i).length<10) \nprintln(l(i))\nelse { \nprint(l(i).head)\nprint(l(i).length-2)\nprintln(l(i).last)\n}\n}\n\n}\n\n"}, {"source_code": "import scala.io.StdIn\nobject solution extends App{\n \n val tests = StdIn.readInt\n \n for(test <- 1 to tests){\n val text = StdIn.readLine\n \n val output = text.head.toString + (text.length-2) + text.last.toString\n println(output)\n \n \n }\n \n}"}, {"source_code": "import scala.collection.immutable.StringOps\nobject Main {\n def res(x: Int) {\n val e = readLine\n if( e.size < 10 )\n println(e)\n else\n println(e.head.toString + (e.size-2) + e.last.toString)\n }\n def main(args: Array[String]) {\n val N = readInt\n 1 to N foreach( res )\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject CodeForces extends App {\n\n val n = StdIn.readLine().toInt\n\n for {\n _ <- 0 until n\n word = StdIn.readLine()\n replaced = if (word.length >= 10) s\"${word.charAt(0)}${word.length - 2}${word.charAt(word.length - 1)}\" else word\n } {\n println(replaced)\n }\n}\n"}, {"source_code": "object Main extends App {\n val n = readInt()\n\n val l = (for ( i <- 0 until n) yield{readLine})\n \n for ( i <- 0.to(n-1) ) {\n if (l(i).length<10) \n println(l(i))\n else { \n print(l(i).head)\n print(l(i).length-2)\n println(l(i).last)\n }\n }\n \n}"}, {"source_code": "object Main extends App {\n val n = readInt()\n\n val l = (for ( i <- 0 until n) yield{readLine})\n \n for ( i <- 0.to(n-1) ) {\n if (l(i).length<10) \n println(l(i))\n else { \n print(l(i).head)\n print(l(i).length-2)\n println(l(i).last)\n }\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject R71_A extends App {\n val sc = new Scanner(System.in)\n\n val n = sc.nextInt()\n \n val words = for(i <- 0 until n) yield sc.nextLine()\n \n words.foreach(w => {println(shorten(w,10))})\n\n def shorten(w:String, k:Int):String = {\n if(w.length > k){\n \"\" + w.charAt(0) + (w.length()-2) + w.charAt(w.length-1)\n }else{\n w\n }\n }\n}"}, {"source_code": "\n\nobject WayTooLongWords {\n\tdef main (args: Array[String]) {\n\t\tval scanner = new java.util.Scanner(System.in)\n\t\t\t\tval number = scanner.nextLine().toInt\n\t\t\t\tfor (i <- 1 to number) {\n\t\t\t\t\tval line = scanner.nextLine\n\t\t\t\t\t\t\tif (line.length >= 10)\n\t\t\t\t\t\t\t\tprintln(line.charAt(0) + (line.length-2).toString() + line.charAt(line.length-1))\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tprintln(line)\n\t\t\t\t}\n\t}\n}"}, {"source_code": "/**\n * Created by vol on 9/15/14.\n */\nobject A71 extends App{\n val n = readInt()\n\n //println(if (str.length > 10) str(0) + (str.length - 2) + str(str.length) else str)\n def loop(n:Int, i:Int, value:String):String = {\n val str = readLine()\n if (n == i)\n if (str.length > 10)\n value + \"\\n\" + str(0) + (str.length - 2).toString + str(str.length - 1)\n else str\n\n else\n if (str.length > 10)\n loop(n, i + 1, value + \"\\n\" + str(0) + (str.length - 2).toString + str(str.length - 1))\n else {\n loop(n, i + 1, value + \"\\n\" + str) }\n }\n\n println(loop(n , 1 , \"\"))\n}\n"}, {"source_code": "/**\n * Created by vol on 9/15/14.\n */\nobject A71 extends App{\n val str = readLine()\n\n println(if (str.length > 10) str(0) + (str.length - 2) + str(str.length) else str)\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readInt()\n for (i <- 1 to n) {\n val str = readLine\n if (str.size < 10) println(str)\n else println(str.head.toString + (str.size - 2) + str.last.toString)\n }\n }\n}"}, {"source_code": "\nimport java.io._\nimport scala.io.Source\nimport scala.util.control._\nimport scala.Console\nimport util.control.Breaks._\n\n\nobject App {\n \n \n def main(args : Array[String]) {\n \n var curCount = 0\n var maxCount = 0\n var line :String = \"\"\n \n maxCount = Console.readLine().toInt\n \n breakable{\n for (i <- 1 to maxCount) {\n \n line = Console.readLine()\n \n breakable{\n if(line.length() < 10){\n break\n }else{\n val value = line.length() - 2\n println(line + \" : \" + line.charAt(0) + value + line.charAt(line.length() - 1))\n }\n }\n }\n }\n }\n\n}\n"}, {"source_code": "\nimport java.io._\nimport scala.io.Source\nimport scala.util.control._\nimport scala.Console\nimport util.control.Breaks._\n\n\nobject App {\n \n \n def main(args : Array[String]) {\n \n var curCount = 0\n var maxCount = 0\n var line :String = \"\"\n \n maxCount = Console.readLine().toInt\n \n breakable{\n for (i <- 1 to maxCount) {\n \n line = Console.readLine()\n \n breakable{\n if(line.length() < 10){\n println(line)\n break\n }else{\n val value = line.length() - 2\n println(line.charAt(0).toChar + value + line.charAt(line.length() - 1).toChar)\n }\n }\n }\n }\n }\n\n}\n"}, {"source_code": "\nimport java.io._\nimport scala.io.Source\nimport scala.util.control._\nimport scala.Console\nimport util.control.Breaks._\n\n\nobject App {\n \n \n def main(args : Array[String]) {\n \n var curCount = 0\n var maxCount = 0\n var line :String = \"\"\n \n maxCount = Console.readLine().toInt\n \n breakable{\n for (i <- 1 to maxCount) {\n \n line = Console.readLine()\n \n breakable{\n if(line.length() < 10){\n println(line)\n break\n }else{\n val value = line.length() - 2\n println(\"\"+line.charAt(0).toChar + value + line.charAt(line.length() - 1).toChar)\n }\n }\n }\n }\n }\n\n}\n"}, {"source_code": "object Main extends App {\n val n = readInt\n var a = 0\n for(a <- 1 to n) {\n val s = readLine\n val l = s.length()\n println( if (l < 10) s else s.substring(0, 1) + l.toString() + s.substring(l-1,l) )\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by mid-s on 11.09.16.\n */\nobject Demo {\n def main(args: Array[String]) {\n val count = io.Source.stdin.getLines().take(1).mkString.toInt\n var resp = new ArrayBuffer[String]\n for (ln <- io.Source.stdin.getLines) {\n if (ln.length > count) {\n resp += (ln(0).toString + (ln.length -2).toString + ln(ln.length -1).toString)\n //println(ln(0).toString + (ln.length -2).toString + ln(ln.length -1).toString)\n } else {\n resp += (ln)\n //println(ln)\n }\n }\n for (el <- resp) {\n //println(el)\n }\n\n }\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by mid-s on 11.09.16.\n */\nobject Demo {\n def main(args: Array[String]) {\n val count = io.Source.stdin.getLines().take(1).mkString.toInt\n\n var resp = new ArrayBuffer[String]\n for (i <- 1 to count) {\n var ln = io.Source.stdin.getLines().take(1).mkString\n if (ln.length > 10) {\n resp += (ln(0).toString + (ln.length -2).toString + ln(ln.length -1).toString)\n } else {\n resp += (ln)\n }\n }\n for (el <- resp) {\n println(el)\n }\n\n }\n}\n\n\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by mid-s on 11.09.16.\n */\nobject Demo {\n def main(args: Array[String]) {\n val count = io.Source.stdin.getLines().take(1).mkString.toInt\n var resp = new ArrayBuffer[String]\n for (ln <- io.Source.stdin.getLines) {\n if (ln.length > count) {\n resp += (ln(0).toString + (ln.length -2).toString + ln(ln.length -1).toString)\n //println(ln(0).toString + (ln.length -2).toString + ln(ln.length -1).toString)\n } else {\n resp += (ln)\n //println(ln)\n }\n }\n for (el <- resp) {\n println(el)\n }\n\n }\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by mid-s on 11.09.16.\n */\nobject Demo {\n def main(args: Array[String]) {\n val count = io.Source.stdin.getLines().take(1).mkString.toInt\n var resp = new ArrayBuffer[String]\n for (ln <- io.Source.stdin.getLines) {\n if (ln.length > count) {\n resp += (ln(0).toString + (ln.length -2).toString + ln(ln.length -1).toString)\n println(ln(0).toString + (ln.length -2).toString + ln(ln.length -1).toString)\n } else {\n resp += (ln)\n println(ln)\n }\n }\n// for (el <- resp) {\n// println(el)\n// }\n\n }\n}"}, {"source_code": "import io.Source.stdin\nobject Demo {\n def main(args: Array[String]) {\n val count = stdin.getLines().take(1).mkString.toInt\n for (ln <- stdin.getLines) {\n if (ln.length > count) {\n println(ln(0).toString + (ln.length -2).toString + ln(ln.length -1).toString)\n } else {\n println(ln)\n }\n }\n\n }\n}"}, {"source_code": "\nobject LongWords {\n def main(args: Array[String]) = {\n val input = Iterator.continually(scala.io.StdIn.readLine()).takeWhile(_ != null)\n\n val compressed = input.map(str => if(str.size > 10) s\"${str.charAt(0)}${str.size - 2}${str.charAt(str.size - 1)}\")\n compressed.foreach(println)\n }\n\n}"}, {"source_code": "import scala.io.Source\nimport java.io._\n\nobject P71A {\n def main(args : Array[String]) {\n val bw = new BufferedWriter(new OutputStreamWriter(System.out))\n Source.stdin.getLines.drop(1).map(solveLine)\n bw.close()\n \n def print(s: String) = bw.write(s)\n def newLine = { bw.write(13); bw.write(10) }\n def solveLine(s: String) = {\n if (s.length > 10) {\n print(s.head.toString)\n print((s.length - 2).toString)\n print(s.last.toString)\n }\n else print(s)\n newLine\n }\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val num = readLine.toInt\n\n def wtlw(n:Int):Unit = n match {\n case 0 => print(\"\")\n case m => {\n val line = readLine\n val lline = line.length\n if(lline < 10) println(line) else println(line.head + (lline-2).toString + line.substring(lline - 1))\n wtlw(n-1)\n }\n\n }\n wtlw(num)\n }\n}\n"}, {"source_code": "object SevenOneA {\n\tdef main(args: Array[String]) {\n\t\tvar n=readInt\n\t\tfor(i<-0 until n){\n\t\t\tvar s=readLine\n\t\t\tvar z=s.charAt(0)+\"\"+(s.length-2)+\"\"+s.charAt(s.length-1)\n\t\t\tprintln(z)\n\t\t}\n\t}\n}"}, {"source_code": "import scala.collection.mutable\nobject WayTooLongWords extends App {\n\n val numb = scala.io.StdIn.readInt()\n \n for (x <- 1 to numb){\n val word = scala.io.StdIn.readLine()\n val s = word.length()\n println(s\"${if (s > 10) word(0)+ word.length() - 2 + word.last else word}\") \n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nobject WayTooLongWords extends App {\n\n val numb = scala.io.StdIn.readInt()\n \n for (x <- 1 to numb){\n val word = scala.io.StdIn.readLine()\n val s = word.length()\n println(if (s > 10) word(0) + s - 2 + word.last else word) \n }\n\n}\n"}, {"source_code": "object Main extends App {\n val size = readLine().toInt\n for (i <- 1 to size) {\n val str = readLine()\n if (str.size > 4) println(str.head + (str.size - 2).toString + str.last)\n else println(str)\n }\n}"}, {"source_code": "object TaskA {\n def main(args: Array[String]): Unit = {\n val wordsNumber = scala.io.StdIn.readInt()\n for (i <- 0 until wordsNumber) {\n val word = scala.io.StdIn.readLine()\n word.length match {\n case j if (j < 10) => println(word)\n case _ => println(s\"${word(0)}${word.length - 2}${word(word.length - 1)}\")\n }\n }\n }\n}"}, {"source_code": "object CF0071A extends App {\n\n val n = readInt()\n\n (1 to n).foreach(e => {\n val str = readLine()\n if (str.length > 4) {\n println(str.charAt(0).toString + (str.length - 2) + str.charAt(str.length -1 ).toString)\n } else {\n println(str)\n }\n })\n}\n"}, {"source_code": "object cf extends App{\n val t = readInt()\n for (t <- 0 to t-1) {\n var s = readLine()\n val l = s.length()\n if (l > 10) {\n s = s(0)+l.toString+s(l-1)\n println(s)\n }\n else {\n println(s)\n }\n }\n}"}, {"source_code": "object P71A {\n def main(args : Array[String]) {\n val n = readInt\n for (i <- 1 to n) work(readLine)\n \n def work(line: String) = {\n if (line.length > 10) {\n print(line.head); print(line.length - 2); println(line.last) \n } else println(line)\n }\n }\n \n ///********************************************************************\n /// easy input buffer\n ///\n val rbuf = new Array[Byte](8192); \n var canReadBufMore = true;\n var rbufCursor = rbuf.length;\n var readSize = 0;\n def readByte: Byte = {\n try {\n if (rbufCursor >= rbuf.length) {\n if (canReadBufMore) {\n readSize = System.in.read(rbuf);\n if (readSize < rbuf.length) {\n canReadBufMore = false;\n }\n rbufCursor = 0;\n }\n }\n } catch { case e: Exception => /* do nothing */}\n if (rbufCursor != readSize) {\n rbufCursor += 1\n rbuf(rbufCursor)\n } else -1;\n }\n \n ///********************************************************************\n /// for read integers\n ///\n def readInt : Int = {\n var result = 0\n var read: Byte = 0\n var sign = false\n\n do {\n read = readByte\n } while (read != -1 && (read != '-' && read < '0' || read > '9'))\n\n if (read == -1) return Integer.MIN_VALUE;\n if (read == '-') { sign = true; read = readByte }\n\n do {\n result = (result << 3) + (result << 1) + read - '0';\n read = readByte;\n } while (read != -1 && read >= '0' && read <= '9');\n if (read == 13) readByte; // skip 10\n\n if (sign) -result else result\n }\n \n ///********************************************************************\n /// for read line\n ///\n val lBuf = new Array[Byte](50)\n def readLine: String = {\n var read = readByte;\n var lPointer = 0;\n try {\n while (read > 13) {\n lPointer += 1\n lBuf(lPointer) = read;\n read = readByte\n }\n if (read == -1) return null;\n if (read == 13) readByte; // skip 10\n } catch { case e: Exception => /* do nothing */}\n return new String(lBuf, 0, lPointer);\n }\n}"}, {"source_code": "object Main{\n\n def main(args:Array[String]){\n val n = readLine.toInt\n for(i<- 0 until n){\n val s = readLine\n if(s.length()<10)\n println(s)\n else{\n print(s(0))\n print(s.length()-2)\n println(s(s.length()-1))\n }\n }\n \n }\n}"}, {"source_code": "import java.util.Scanner\n\n\n/**\n * Created by zhmyh on 22/02/16.\n */\nobject WayTooLongWords extends App {\n val in = new Scanner(System.in)\n val wnum = in.nextLine().trim.toInt\n println(wnum)\n for (_ <- 0 until wnum) yield {\n val word = in.nextLine()\n println(compress(word.trim()))\n }\n\n def compress(word: String): String =\n if (word.length > 10)\n word.take(1) + (word.length - 2).toString + word.drop(word.length - 1)\n else\n word\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val times = readLine().toInt\n for (_ <- 1 to times) {\n val str = readLine()\n if (str.length < 10) {\n println(str)\n }\n else {\n print(str(0))\n print(str.length - 2)\n println(str(str.length - 1))\n }\n }\n }\n}\n"}, {"source_code": "object codeforces {\n def main(args: Array[String]): Unit = {\n val n: Int = scala.io.StdIn.readLine().toInt\n for (_ <- 0 until n){\n val word: String = scala.io.StdIn.readLine()\n if (word.length <= 10){\n println(word)\n }else{\n println(word.head + word.length-2 + word(word.length-1))\n }\n }\n }\n}\n"}, {"source_code": "object codeforces {\n def main(args: Array[String]): Unit = {\n val n: Int = scala.io.StdIn.readLine().toInt\n for (_ <- 0 until n){\n val word: String = scala.io.StdIn.readLine()\n val l: Int = word.length\n if (l <= 10){\n println(word)\n }else{\n val result: String = word.head + l.toString + word(l-1)\n println(result)\n }\n }\n }\n}\n"}, {"source_code": "object codeforces {\n def main(args: Array[String]): Unit = {\n val n: Int = scala.io.StdIn.readLine().toInt\n for (_ <- 0 until n){\n val word: String = scala.io.StdIn.readLine()\n if (word.length <= 10){\n println(word)\n }else{\n println(word)\n }\n }\n }\n}\n"}, {"source_code": "object codeforces {\n def main(args: Array[String]): Unit = {\n val n: Int = scala.io.StdIn.readLine().toInt\n val word: String = scala.io.StdIn.readLine()\n println(word)\n }\n}\n"}, {"source_code": "object WayTooLongWords {\n def main(args : Array[String]) {\n val gls = io.Source.stdin.getLines\n gls drop(1)\n gls.map(shorten _) foreach(println)\n }\n def shorten(word : String) : String = {\n val len = word.length() - 2\n if (len > 2)\n return s\"${word(1)}$len${word.last}\"\n return word\n }\n}\n"}, {"source_code": "object WayTooLongWords {\n def main(args : Array[String]) {\n val gls = io.Source.stdin.getLines\n gls drop(1)\n gls.map(shorten _) foreach(println)\n }\n def shorten(word : String) : String = {\n val len = word.length() - 2\n if (len > 2)\n return s\"${word(0)}$len${word.last}\"\n return word\n }\n}\n"}, {"source_code": "object WayTooLongWords {\n def main(args : Array[String]) {\n val gls = io.Source.stdin.getLines\n gls.map(shorten _) foreach(println)\n }\n def shorten(word : String) : String = {\n val len = word.length() - 2\n if (len > 2)\n return s\"${word(1)}$len${word.last}\"\n return word\n }\n}\n"}], "src_uid": "6639d6c53951f8c1a8324fb24ef68f7a"} {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n\n def removeAll(x: T) = {\n map.remove(x)\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val k = nextInt\n val a = new Array[Int](n)\n var ans = 0L\n val left = new MultiHashSet[Long]\n val right = new MultiHashSet[Long]\n for (i <- 0 until n) {\n a(i) = nextInt\n right.add(a(i))\n }\n for (i <- 0 until n) {\n right.remove(a(i))\n if (a(i) % k == 0)\n ans += 1L * left.count(a(i) / k) * right.count(1L * a(i) * k)\n left.add(a(i))\n }\n out.println(ans)\n return 0\n }\n}\n", "positive_code": [{"source_code": "import io.StdIn._\nimport scala.collection.mutable._\n\nobject Solution {\n\n def main(args: Array[String]) {\n val line = readLine().split(\" \").map(_.toInt)\n val (n, k) = (line(0), line(1))\n val seq = readLine().split(\" \").map(_.toInt)\n val l = Map[Int, Int]().withDefaultValue(0)\n val r = Map[Int, Int]().withDefaultValue(0)\n var res = 0L\n\n for (i <- seq.tail) { r(i) += 1 }\n l(seq.head) = 1\n for (i <- seq.tail) {\n r(i) = Math.max(0, r(i) - 1)\n if (i % k == 0 && Math.abs(i * k.toLong) < 1000000007) {\n res += l(i/k) * r(i*k).toLong\n }\n l(i) += 1\n }\n\n println(res)\n\n }\n\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn._\n\nobject CF567C extends App {\n val Array(n, k) = readLine().split(\" \").map(_.toLong)\n val a = readLine().split(\" \").map(_.toLong)\n\n val l = mutable.Map[Long, Long]().withDefaultValue(0)\n // elements to the left of current element\n val r = mutable.Map[Long, Long]().withDefaultValue(0) // elements to the right of current element\n\n a.foreach { e => r.update(e, r(e) + 1)}\n // all elements are to the right initially\n\n var res = 0.toLong\n a.foreach { e =>\n // if current element is divisible by k,\n // retrieve number of elements equal to e/k to the left of the current element\n val nl = if (e % k == 0) l(e / k) else 0\n\n // put current element from right to left\n l.update(e, l(e) + 1)\n r.update(e, r(e) - 1)\n\n // retrieve number of elements equal to e*k to the right of the current element\n val nr = r(e * k)\n\n res += nl * nr\n }\n\n println(res)\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn.readLine\n\n\n// case class R(c: Map[Long,Long], g: Map[Long,Long], r: Long)\n// object Main {\n// // Document: http://www.scala-lang.org/api/current/#package\n// // -----------------------------------------------------------------------------\n// def main(args: Array[String]) : Unit = {\n// val (n,k) = {\n// val nk = readLine().split(\" \").map(_.toLong)\n// (nk(0), nk(1))\n// }\n// val a = readLine().split(\" \").map(_.toLong)\n// val l = a.foldLeft(R(Map[Long,Long](),Map[Long,Long](),0l))((r,i) => r match {\n// case R(c,g,r) => {\n// val new_r = r + g.getOrElse(i,0l)\n// val new_c = c + (i->(c.getOrElse(i,0l)+1l))\n// val new_g =\n// if(i % k == 0)\n// g + (i*k->(g.getOrElse(i*k,0l)+c.getOrElse(i/k,0l)))\n// else\n// g\n// R(new_c,new_g,new_r)\n// }\n// })\n// println(l.r)\n// }\n// }\n\n\n\nobject Main {\n import scala.collection.mutable.Map\n case class R(c: Map[Long,Long], g: Map[Long,Long], r: Long)\n // Document: http://www.scala-lang.org/api/current/#package\n // -----------------------------------------------------------------------------\n def main(args: Array[String]) : Unit = {\n val (n,k) = {\n val nk = readLine().split(\" \").map(_.toLong)\n (nk(0), nk(1))\n }\n val a = readLine().split(\" \").map(_.toLong)\n val l = a.foldLeft(R(Map[Long,Long](),Map[Long,Long](),0l))(\n (r,i) => r match {\n case R(c,g,r) => {\n val new_r = r + g.getOrElse(i,0l)\n val t = c.getOrElse(i,0l)+1l\n val j = g.getOrElse(i*k,0l)+c.getOrElse(i/k,0l)\n c += (i->t)\n if(i % k == 0)\n g += (i*k->j)\n R(c,g,new_r)\n }\n })\n println(l.r)\n }\n}\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn.readLine\nimport scala.collection.immutable.HashMap\n\n\n\n// ----------------------------------------------------------------------------0\n// ----------------------------------------------------------------------------0\nobject Main {\n import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}\n import scala.annotation.tailrec\n class MyConsole(val in: BufferedReader, val _out: PrintStream,\n val err: PrintStream) {\n // PrintWriter do not flush automatically\n val out = new PrintWriter(_out,false)\n // If argument is null, there are ambiguous which function will be called\n def print(obj: Any) = out.print(if(obj == null) \"null\" else obj.toString)\n def println() = out.println()\n def println(obj: Any) = out.println(obj)\n def printf(text: String, args: Any*) = out.printf(text.format(args : _*))\n // NOTE: YOU MUST FLUSH BEFORE END OF MAIN\n def flush() = out.flush()\n def debugln(obj: Any) = err.println(obj)\n\n def readIntVector() : Vector[Int] = parseLineToVector(() => nextInt)\n def readLongVector() : Vector[Long] = parseLineToVector(() => nextLong)\n def readStringVector() : Vector[String] = parseLineToVector(() => nextString)\n def nextInt() : Int = nextLong().toInt\n def nextBigInt() : BigInt = BigInt(nextString())\n def nextBigDecimal( ) : BigDecimal = BigDecimal(nextString())\n def nextDouble() : Double = nextString().toDouble\n def nextLong() : Long = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading long failed\")\n val sgn = if(peek == '-') -1l else 1\n if(sgn == -1l) read()\n if(peek < '0' || '9' < peek)\n throw new NumberFormatException(s\"readLong found only '-' or no number\")\n @tailrec\n def readLong(next: Int, cur: Long) : Long =\n if('0' <= next && next <= '9'){\n val _ = read() // is equal to next\n readLong(peek, cur*10 + next-'0')\n }\n else if(isEnd(next) || isSpaceOrControl(next))\n sgn*cur\n else\n throw new NumberFormatException(s\"readLong found strange byte $next\")\n val res = readLong(peek,0)\n skipTrailingSpaces()\n res\n }\n def nextString() : String = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading String failed\")\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isSpaceOrControl(next)){\n builder.toString\n }else{\n builder.append(read().toChar) // here we skip.\n appendCode(peek)\n }\n }\n val res = appendCode(peek)\n skipTrailingSpaces()\n res\n }\n // TODO: refactoring to marge nextString\n def readLine() : String = {\n if(isEnd(peek))\n throw new NoSuchElementException(\"Reading Line failed\")\n skipNewline()\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isNewLine(next)){\n builder.toString\n }else{\n builder.append(next.toChar)\n appendCode(read())\n }\n }\n appendCode(read())\n }\n // helpers\n private[this] var peeked: Option[Int] = None\n private[this] var is_first = true\n private def read() = {\n val res = peeked match {\n case None => in.read()\n case Some(a) => { peeked = None; a }\n }\n is_first = false\n res\n }\n private def peek() =\n peeked match {\n case None => {\n val res = in.read()\n peeked = Some(res)\n res\n }\n case Some(a) => a\n }\n private def isEnd(c: Int) = c == -1\n private def isCR(c: Int) = c == 13\n private def isLF(c: Int) = c == 10\n private def isNewLine(c: Int) = isLF(c) || isCR(c)\n private def isThereReadable() = !isEnd(peek)\n // XXX: this limits c is ASCII?\n private def isSpaceOrControl(c: Int) = (0 <= c && c <= 32) || c == 127\n @tailrec\n final private def goNextNotSpaceNorControl() : Unit =\n if(isSpaceOrControl(peek)){\n read()\n goNextNotSpaceNorControl()\n }\n final private def skipTrailingSpaces() : Unit = {\n @tailrec\n def skipTrailingSpacesAux() : Unit = {\n if(!isNewLine(peek) && isSpaceOrControl(peek)){\n read()\n skipTrailingSpacesAux()\n }\n }\n skipTrailingSpacesAux()\n }\n final private def skipNewline() : Unit = {\n if(is_first){\n }else if(isCR(peek)){\n read()\n if(isLF(peek)) read()\n }else if(isLF(peek)){\n read()\n }\n }\n private def goNextValuable() = {\n goNextNotSpaceNorControl()\n isThereReadable()\n }\n private def parseLineToVector[X](parser: () => X) : Vector[X] = {\n import scala.collection.immutable.VectorBuilder\n val vb = new VectorBuilder[X]()\n skipNewline()\n @tailrec\n def parseLineToVectorAux(first: Boolean=false) : Vector[X] =\n if(isNewLine(peek) || isEnd(peek)) {\n vb.result\n }else{\n vb += parser()\n parseLineToVectorAux()\n }\n parseLineToVectorAux(true)\n }\n }\n\n\n\n\n // Document: http://www.scala-lang.org/api/current/#package\n // -----------------------------------------------------------------------------\n class Solver(val stdio: MyConsole){\n import stdio._ // shadow Console.~\n case class R(c: HashMap[Long,Long], g: HashMap[Long,Long], r: Long)\n def main() : Unit = {\n val n,k = nextLong()\n val a = readLongVector()\n val l = a.foldLeft(R(HashMap[Long,Long](),HashMap[Long,Long](),0l))((r,i) => r match {\n case R(c,g,r) => {\n val new_r = r + g.getOrElse(i,0l)\n val new_c = c + (i->(c.getOrElse(i,0l)+1l))\n val new_g =\n if(i % k == 0 && (c contains i/k))\n g + (i*k->(g.getOrElse(i*k,0l)+c.get(i/k).get))\n else\n g\n R(new_c,new_g,new_r)\n }\n })\n println(l.r)\n }\n }\n\n def main(args: Array[String]) : Unit = {\n val console = new MyConsole(Console.in, Console.out, Console.err)\n val solver = new Solver(console)\n solver.main()\n console.flush()\n }\n}\n\n\n\n// object Main {\n// import scala.collection.mutable.Map\n// case class R(c: Map[Long,Long], g: Map[Long,Long], r: Long)\n// // Document: http://www.scala-lang.org/api/current/#package\n// // -----------------------------------------------------------------------------\n// def main(args: Array[String]) : Unit = {\n// val (n,k) = {\n// val nk = readLine().split(\" \").map(_.toLong)\n// (nk(0), nk(1))\n// }\n// val a = readLine().split(\" \").map(_.toLong)\n// val l = a.foldLeft(R(Map[Long,Long](),Map[Long,Long](),0l))(\n// (r,i) => r match {\n// case R(c,g,r) => {\n// val new_r = r + g.getOrElse(i,0l)\n// val t = c.getOrElse(i,0l)+1l\n// val j = g.getOrElse(i*k,0l)+c.getOrElse(i/k,0l)\n// c += (i->t)\n// if(i % k == 0)\n// g += (i*k->j)\n// R(c,g,new_r)\n// }\n// })\n// println(l.r)\n// }\n// }\n"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn.readLine\n\n\n// case class R(c: Map[Long,Long], g: Map[Long,Long], r: Long)\n// object Main {\n// // Document: http://www.scala-lang.org/api/current/#package\n// // -----------------------------------------------------------------------------\n// def main(args: Array[String]) : Unit = {\n// val (n,k) = {\n// val nk = readLine().split(\" \").map(_.toLong)\n// (nk(0), nk(1))\n// }\n// val a = readLine().split(\" \").map(_.toLong)\n// val l = a.foldLeft(R(Map[Long,Long](),Map[Long,Long](),0l))((r,i) => r match {\n// case R(c,g,r) => {\n// val new_r = r + g.getOrElse(i,0l)\n// val new_c = c + (i->(c.getOrElse(i,0l)+1l))\n// val new_g =\n// if(i % k == 0)\n// g + (i*k->(g.getOrElse(i*k,0l)+c.getOrElse(i/k,0l)))\n// else\n// g\n// R(new_c,new_g,new_r)\n// }\n// })\n// println(l.r)\n// }\n// }\n\n\n\nobject Main {\n import scala.collection.mutable.Map\n case class R(c: Map[Long,Long], g: Map[Long,Long], r: Long)\n // Document: http://www.scala-lang.org/api/current/#package\n // -----------------------------------------------------------------------------\n def main(args: Array[String]) : Unit = {\n val (n,k) = {\n val nk = readLine().split(\" \").map(_.toLong)\n (nk(0), nk(1))\n }\n val a = readLine().split(\" \").map(_.toLong)\n var r = 0l\n val c = Map[Long,Long]()\n val g = Map[Long,Long]()\n for(i <- a){\n val new_r = r + g.getOrElse(i,0l)\n val t = c.getOrElse(i,0l)+1l\n val j = g.getOrElse(i*k,0l)+c.getOrElse(i/k,0l)\n c += (i->t)\n if(i % k == 0)\n g += (i*k->j)\n r = new_r\n }\n println(r)\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject CF567C extends App {\n val Array(n, k) = readLine().split(\" \").map(_.toLong)\n val a = readLine().split(\" \").map(_.toLong)\n\n val square = k * k\n\n var result = 0\n val len = a.length - 1\n for (i <- 0 to len) {\n for (j <- (i + 1) to len) {\n for (m <- (j + 1) to len) {\n val a1 = a(i)\n val a2 = a(j)\n val a3 = a(m)\n if ((a1 == a2 / k) && (a1 == a3 / square)) {\n result += 1\n }\n }\n }\n }\n\n println(result)\n}"}, {"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn.readLine\nimport scala.collection.immutable.HashMap\n\n\n\n// ----------------------------------------------------------------------------0\n// ----------------------------------------------------------------------------0\nobject Main {\n import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}\n import scala.annotation.tailrec\n class MyConsole(val in: BufferedReader, val _out: PrintStream,\n val err: PrintStream) {\n // PrintWriter do not flush automatically\n val out = new PrintWriter(_out,false)\n // If argument is null, there are ambiguous which function will be called\n def print(obj: Any) = out.print(if(obj == null) \"null\" else obj.toString)\n def println() = out.println()\n def println(obj: Any) = out.println(obj)\n def printf(text: String, args: Any*) = out.printf(text.format(args : _*))\n // NOTE: YOU MUST FLUSH BEFORE END OF MAIN\n def flush() = out.flush()\n def debugln(obj: Any) = err.println(obj)\n\n def readIntVector() : Vector[Int] = parseLineToVector(() => nextInt)\n def readLongVector() : Vector[Long] = parseLineToVector(() => nextLong)\n def readStringVector() : Vector[String] = parseLineToVector(() => nextString)\n def nextInt() : Int = nextLong().toInt\n def nextBigInt() : BigInt = BigInt(nextString())\n def nextBigDecimal( ) : BigDecimal = BigDecimal(nextString())\n def nextDouble() : Double = nextString().toDouble\n def nextLong() : Long = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading long failed\")\n val sgn = if(peek == '-') -1l else 1\n if(sgn == -1l) read()\n if(peek < '0' || '9' < peek)\n throw new NumberFormatException(s\"readLong found only '-' or no number\")\n @tailrec\n def readLong(next: Int, cur: Long) : Long =\n if('0' <= next && next <= '9')\n readLong(readWithoutCheckingPeeked(), cur*10 + next-'0')\n else if(isEnd(next) || isSpaceOrControl(next))\n sgn*cur\n else\n throw new NumberFormatException(s\"readLong found strange byte $next\")\n val res = readLong(read(),0)\n skipTrailingSpaces()\n res\n }\n def nextString() : String = {\n if(!goNextValuable())\n throw new NoSuchElementException(\"Reading String failed\")\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isSpaceOrControl(next)){\n builder.toString\n }else{\n builder.append(next.toChar)\n appendCode(readWithoutCheckingPeeked())\n }\n }\n val res = appendCode(read())\n skipTrailingSpaces()\n res\n }\n // TODO: refactoring to marge nextString\n def readLine() : String = {\n if(isEnd(peek))\n throw new NoSuchElementException(\"Reading Line failed\")\n val builder = new StringBuilder\n @tailrec\n def appendCode(next: Int) : String = {\n if(isEnd(next) || isNewLine(next)){\n builder.toString\n }else{\n builder.append(next.toChar)\n appendCode(read())\n }\n }\n appendCode(read())\n }\n // helpers\n private[this] var peeked: Option[Int] = None\n private[this] var last = -1\n private def read() = {\n val res = peeked match {\n case None => in.read()\n case Some(a) => { peeked = None; a }\n }\n last = res\n res\n }\n @inline private def readWithoutCheckingPeeked() = {\n val res = in.read()\n last = res\n res\n }\n @inline private def peek() =\n peeked match {\n case None => {\n val res = in.read()\n peeked = Some(res)\n res\n }\n case Some(a) => a\n }\n @inline private def isEnd(c: Int) = c == -1\n @inline private def isNewLine(c: Int) = c == 10 || c == 13 // LF and CR\n @inline private def isThereReadable() = !isEnd(peek)\n // XXX: this limits c is ASCII?\n @inline private def isSpaceOrControl(c: Int) = (0 <= c && c <= 32) || c == 127\n @tailrec\n final private def goNextNotSpaceNorControl() : Unit =\n if(isSpaceOrControl(peek)){\n read()\n goNextNotSpaceNorControl()\n }\n final private def skipTrailingSpaces() : Unit = {\n @tailrec\n def skipTrailingSpacesAux() : Unit = {\n if(!isNewLine(last) && !isNewLine(peek) && isSpaceOrControl(peek)){\n read()\n skipTrailingSpacesAux()\n }\n }\n skipTrailingSpacesAux\n if(!isNewLine(last) && isNewLine(peek)) read()\n }\n @tailrec\n final private def skipTrailingSpacesAndNewline() : Unit =\n if(isNewLine(peek)){\n val _ = read() // windows causes error. maybe.\n }else if(isSpaceOrControl(peek)){\n read()\n skipTrailingSpacesAndNewline()\n }\n @inline private def goNextValuable() = {\n goNextNotSpaceNorControl()\n isThereReadable()\n }\n @inline private def parseLineToVector[X](parser: () => X) : Vector[X] = {\n import scala.collection.immutable.VectorBuilder\n val vb = new VectorBuilder[X]()\n @tailrec\n def parseLineToVectorAux(first: Boolean=false) : Vector[X] =\n if((!first && isNewLine(last)) || isNewLine(peek) || isEnd(peek)) {\n vb.result\n }else{\n vb += parser()\n parseLineToVectorAux()\n }\n parseLineToVectorAux(true)\n }\n }\n\n\n\n\n\n\n\n\n // Document: http://www.scala-lang.org/api/current/#package\n // -----------------------------------------------------------------------------\n class Solver(val stdio: MyConsole){\n import stdio._ // shadow Console.~\n case class R(c: HashMap[Long,Long], g: HashMap[Long,Long], r: Long)\n def main() : Unit = {\n val n,k = nextLong()\n val a = readLongVector()\n val l = a.foldLeft(R(HashMap[Long,Long](),HashMap[Long,Long](),0l))((r,i) => r match {\n case R(c,g,r) => {\n val new_r = r + g.getOrElse(i,0l)\n val new_c = c + (i->(c.getOrElse(i,0l)+1l))\n val new_g =\n if(i % k == 0)\n g + (i*k->(g.getOrElse(i*k,0l)+c.getOrElse(i/k,0l)))\n else\n g\n R(new_c,new_g,new_r)\n }\n })\n println(l.r)\n }\n }\n\n def main(args: Array[String]) : Unit = {\n val console = new MyConsole(Console.in, Console.out, Console.err)\n val solver = new Solver(console)\n solver.main()\n console.flush()\n }\n}\n\n\n\n// object Main {\n// import scala.collection.mutable.Map\n// case class R(c: Map[Long,Long], g: Map[Long,Long], r: Long)\n// // Document: http://www.scala-lang.org/api/current/#package\n// // -----------------------------------------------------------------------------\n// def main(args: Array[String]) : Unit = {\n// val (n,k) = {\n// val nk = readLine().split(\" \").map(_.toLong)\n// (nk(0), nk(1))\n// }\n// val a = readLine().split(\" \").map(_.toLong)\n// val l = a.foldLeft(R(Map[Long,Long](),Map[Long,Long](),0l))(\n// (r,i) => r match {\n// case R(c,g,r) => {\n// val new_r = r + g.getOrElse(i,0l)\n// val t = c.getOrElse(i,0l)+1l\n// val j = g.getOrElse(i*k,0l)+c.getOrElse(i/k,0l)\n// c += (i->t)\n// if(i % k == 0)\n// g += (i*k->j)\n// R(c,g,new_r)\n// }\n// })\n// println(l.r)\n// }\n// }\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n\n def removeAll(x: T) = {\n map.remove(x)\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val k = nextInt\n val a = new Array[Int](n)\n var ans = 0L\n val left = new MultiHashSet[Int]\n val right = new MultiHashSet[Int]\n for (i <- 0 until n) {\n a(i) = nextInt\n right.add(a(i))\n }\n for (i <- 0 until n) {\n right.remove(a(i))\n if (a(i) % k == 0)\n ans += 1L * left.count(a(i) / k) * right.count(a(i) * k)\n left.add(a(i))\n }\n out.println(ans)\n return 0\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject C {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n\n def removeAll(x: T) = {\n map.remove(x)\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n /**\n * Segment tree for any commutative function\n * @param values Array of Int\n * @param commutative function like min, max, sum\n * @param zero zero value - e.g. 0 for sum, Inf for min, max\n */\n class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {\n private val SIZE = 1e5.toInt\n private val n = values.length\n val t = new Array[Int](2 * n)\n Array.copy(values, 0, t, n, n)\n\n // build segment tree\n def build = {\n for (i <- n - 1 until 0 by -1) {\n t(i) = commutative(t(2 * i), t(2 * i + 1))\n }\n }\n\n // change value at position p to x\n // TODO beatify\n def modify(p: Int, x: Int) = {\n var pos = p + n\n t(pos) = x\n while (pos > 1) {\n t(pos / 2) = commutative(t(pos), t(pos ^ 1))\n pos /= 2\n }\n }\n\n // TODO implement me!\n def modify(p: Int, left: Int, right: Int) = ???\n\n def query(p: Int) = ???\n\n // sum [l, r)\n // min l = 0\n // max r = n\n // TODO beatify\n def query(left: Int, right: Int): Int = {\n var res = zero\n var r = right + n\n var l = left + n\n while (l < r) {\n if (l % 2 == 1) {\n res = commutative(res, t(l))\n l += 1\n }\n if (r % 2 == 1) {\n r -= 1\n res = commutative(res, t(r))\n }\n l /= 2\n r /= 2\n }\n res\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val k = nextInt\n val a = new Array[Int](n)\n var ans = 0L\n val left = new MultiHashSet[Int]\n val right = new MultiHashSet[Int]\n for (i <- 0 until n) {\n a(i) = nextInt\n right.add(a(i))\n }\n for (i <- 0 until n) {\n right.remove(a(i))\n if (a(i) % k == 0)\n ans += left.count(a(i) / k) * right.count(a(i) * k)\n left.add(a(i))\n }\n out.println(ans)\n return 0\n }\n}\n"}, {"source_code": "import io.StdIn._\nimport scala.collection.mutable._\n\nobject Solution {\n\n def main(args: Array[String]) {\n val line = readLine().split(\" \").map(_.toInt)\n val (n, k) = (line(0), line(1))\n val seq = readLine().split(\" \").map(_.toInt)\n val l = Map[Int, Int]().withDefaultValue(0)\n val r = Map[Int, Int]().withDefaultValue(0)\n var res = 0\n\n for (i <- seq.tail) { r(i) += 1 }\n l(seq.head) = 1\n for (i <- seq.tail) {\n r(i) = Math.max(0, r(i) - 1)\n if (i % k == 0 && i * k.toLong < 1000000007) {\n res += l(i/k) * r(i*k)\n }\n l(i) += 1\n }\n\n println(res)\n\n }\n\n}\n"}, {"source_code": "import io.StdIn._\nimport scala.collection.mutable._\n\nobject Solution {\n\n def main(args: Array[String]) {\n val line = readLine().split(\" \").map(_.toInt)\n val (n, k) = (line(0), line(1))\n val seq = readLine().split(\" \").map(_.toInt)\n val l = Map[Int, Int]().withDefaultValue(0)\n val r = Map[Int, Int]().withDefaultValue(0)\n var res = 0L\n\n for (i <- seq.tail) { r(i) += 1 }\n l(seq.head) = 1\n for (i <- seq.tail) {\n r(i) = Math.max(0, r(i) - 1)\n if (i % k == 0 && i * k.toLong < 1000000007) {\n res += l(i/k) * r(i*k).toLong\n }\n l(i) += 1\n }\n\n println(res)\n\n }\n\n}\n"}], "src_uid": "bd4b3bfa7511410c8e54658cc1dddb46"} {"source_code": "object Main extends App{\n val n = readInt()\n for (i <- 0 until n){\n val arr = readLine().split(\" \").map(_.toInt)\n var x = 0\n for (j <- arr){\n if (j > 0) x = x | j\n }\n print (x)\n print (if(i == n-1) \"\\n\" else \" \")\n }\n}\n", "positive_code": [{"source_code": "import scala.collection.mutable._\n\nobject Main extends App {\n val sc = new java.util.Scanner(System.in)\n\n val n = sc.nextInt()\n\n val m = Array.tabulate(n, n)((_, _) => sc.nextInt())\n\n val ans = (0 until n) map { i =>\n (0 until n) map (j => if (i != j) (m(i)(j) | m(j)(i)) else 0) reduce (_ | _)\n }\n\n println(ans.mkString(\"\\n\"))\n}\n"}], "negative_code": [], "src_uid": "8f342e167e77088ce47f17e5cd475b17"} {"source_code": "object Solution {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn\n val t = StdIn.readLine().toInt\n for (_ <- 0 until t){\n val input = StdIn.readLine.trim.split(\" \").map(_.toInt)\n val (n, m, x, y) = (input(0), input(1), input(2), input(3))\n val board = Array.fill(n)(\"\")\n var b1, b2 = 0\n for (row <- 0 until n) {\n board(row) = StdIn.readLine\n val (bc1, bc2) = board(row).split(\"\\\\*\").foldLeft((0,0))((acc, str) => {\n (acc._1 + str.length % 2, acc._2 + str.length / 2)\n })\n b1 += bc1\n b2 += bc2\n }\n val res = (b1+b2*2)*x min (b1*x+b2*y)\n println(res)\n }\n }\n}\n", "positive_code": [{"source_code": "//package codeforces.contests._1359\n\nobject _2 {\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val Array(n, _, t1, t2) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val ans = (1 to n).foldLeft(0) { (acc, _) =>\n\n val chars = io.StdIn.readLine.toList\n\n @scala.annotation.tailrec\n def loop(input: List[Char], result: Int = 0): Int = {\n if (input.isEmpty) result\n else {\n val (dots, tail) = input.span(_ == '.')\n\n val size = dots.length\n\n val current = if (t1 * 2 <= t2) size * t1 else (size / 2) * t2 + (if ((size & 1) == 1) t1 else 0)\n\n loop(tail.dropWhile(_ == '*'), result + current)\n }\n\n }\n\n acc + loop(chars)\n }\n\n println {\n ans\n }\n }\n }\n}\n"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, m, x, y) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val z = y min (2 * x)\n\n val ans = (0 until n).foldLeft(0) { (sum, _) =>\n val am = scala.io.StdIn.readLine().split(\"\").map(c => if (c == \".\") 1 else 0)\n\n val (s, t) = am.foldLeft((sum, 0)) {\n case ((s, l), r) =>\n if (l == 0) (s, r)\n else if (l == r) (s + z, 0)\n else (s + x, 0)\n }\n\n s + t * x\n }\n\n println(ans)\n\n }\n}\n"}, {"source_code": "object B extends App {\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, m, x, y) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val z = y min (2 * x)\n\n val ans = (0 until n).foldLeft(0) { (sum, _) =>\n val am = scala.io.StdIn.readLine().split(\"\").map(c => if (c == \".\") 1 else 0)\n\n var a = 0\n val r = am.reduce { (l, r) =>\n if (l == 0) r\n else if (l == r) { a += z; 0 }\n else { a += x; 0 }\n }\n\n sum + a + r * x\n }\n\n println(ans)\n\n }\n}\n"}, {"source_code": "object ProblemB extends App {\n\n import java.io.{BufferedReader, InputStreamReader, PrintWriter}\n import java.util.StringTokenizer\n\n val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))\n val out = new PrintWriter(System.out)\n\n class FastScanner(val in: BufferedReader) {\n var st: StringTokenizer = _;\n\n def nextToken(): String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(in.readLine);\n }\n return st.nextToken();\n }\n\n def nextInt(): Integer = {\n Integer.parseInt(nextToken());\n }\n\n def nextLong(): Long = {\n nextToken().toLong;\n }\n\n def nextDouble(): Double = {\n nextToken().toDouble;\n }\n }\n\n val t = in.nextInt()\n for (_ <- 1 to t) {\n val n = in.nextInt()\n val m = in.nextInt()\n val x = in.nextInt()\n val y = in.nextInt()\n\n var whiteCount = 0\n var res = 0\n\n def incRes(): Unit = {\n if (x * 2 <= y) {\n res = res + whiteCount * x\n } else {\n res = res + whiteCount / 2 * y + whiteCount % 2 * x\n }\n whiteCount = 0\n }\n\n for (i <- 0 until n) {\n val s = in.nextToken()\n s.foreach(c => if (c == '.') whiteCount = whiteCount + 1 else incRes())\n incRes()\n }\n\n println(res)\n\n }\n\n\n}"}], "negative_code": [], "src_uid": "69ef9492fcdcc979cb31fa95c3e76db9"} {"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val as = Array.fill(n)(nextInts(m))\n val sln = Array.fill(n, m)(4)\n for (i <- 1 to (m - 2)) {\n sln(0)(i) = 3\n sln(n - 1)(i) = 3\n }\n for (j <- 1 to (n - 2)) {\n sln(j)(0) = 3\n sln(j)(m - 1) = 3\n }\n sln(0)(0) = 2\n sln(0)(m - 1) = 2\n sln(n - 1)(0) = 2\n sln(n - 1)(m - 1) = 2\n\n var ok = true\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (as(i)(j) > sln(i)(j)) ok = false\n }\n }\n\n if (ok) {\n out.println(\"YES\")\n sln.foreach(row => out.println(row.mkString(\" \")))\n } else {\n out.println(\"NO\")\n }\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val base = if (n == 1 || m == 1) 3 else 4\n\n var check = true\n val b = (0 until n).map { i =>\n val input = readLine().split(\" \").map(_.toInt)\n\n val row = (0 until m).map(j => base - (if (i == 0 || i == n - 1) 1 else 0) - (if (j == 0 || j == m - 1) 1 else 0))\n\n check &&= input.zip(row).forall { case (x, y) => x <= y }\n\n row\n }\n\n if (check) {\n println(\"YES\")\n println(b.map(_.mkString(\" \")).mkString(\"\\n\"))\n } else println(\"NO\")\n }\n}\n"}], "negative_code": [], "src_uid": "8afcdfaabba66fb9cefc5b6ceabac0d0"} {"source_code": "//package codeforces.contests._1363\n\nobject GameOnLeaves {\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n\n val Array(n, x) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val degree: Array[Int] = {\n val a = new Array[Int](n + 1)\n (1 until n).foreach { _ =>\n val Array(x, y) = io.StdIn.readLine.split(\" \").map(_.toInt)\n a(x) += 1\n a(y) += 1\n }\n a\n }\n val first = \"Ayush\"\n val second = \"Ashish\"\n\n println {\n if (degree(x) <= 1) first else {\n val maxMoves = n - 2\n\n if (maxMoves % 2 == 0) first else second\n }\n }\n }\n }\n\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nx = readIntLine()\n val n = nx.head\n val x = nx.last\n val xKids = (1 until n).count(_ => {\n val l = readIntLine()\n l.head == x || l.last == x\n })\n\n println(if (n == 1 || xKids == 1 || n % 2 == 0) \"Ayush\" else \"Ashish\")\n }\n// println(minNum(List[Boolean](false, false, true)))\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nx = readIntLine()\n val n = nx.head\n val x = nx.last\n val xKids = (1 until n).count(_ => {\n val l = readIntLine()\n l.head == x || l.last == x\n })\n\n println(if (xKids == 1 || n % 2 == 0) \"Ayush\" else \"Ashish\")\n }\n// println(minNum(List[Boolean](false, false, true)))\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nx = readIntLine()\n val xKids = (1 until nx.head).count(_ => {\n val l = readIntLine()\n l.head == nx.last || l.last == nx.last\n })\n\n println(if (xKids == 1 || nx.head - xKids % 2 == 0) \"Ayush\" else \"Ashish\")\n }\n// println(minNum(List[Boolean](false, false, true)))\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nx = readIntLine()\n val xKids = (1 until nx.head).count(_ => {\n val l = readIntLine()\n l.head == nx.last || l.last == nx.last\n })\n\n println(if (xKids == 1 || (nx.head - xKids) % 2 == 0) \"Ayush\" else \"Ashish\")\n }\n// println(minNum(List[Boolean](false, false, true)))\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n val t = readLine().toInt\n for (i <- 1 to t) {\n val nx = readIntLine()\n val n = nx.head\n val x = nx.last\n val xKids = (1 until n).count(_ => {\n val l = readIntLine()\n l.head == x || l.last == x\n })\n\n println(if (xKids == 1 || (n - xKids) % 2 == 0) \"Ayush\" else \"Ashish\")\n }\n// println(minNum(List[Boolean](false, false, true)))\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n def printArray[T](arr: Array[T]) {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n}\n\n"}], "src_uid": "1a93a35395436f9e15760400f991f1ce"} {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\n\nobject _572B extends CodeForcesApp[List[Entry]]({scanner => import scanner._\n def join(e1: Entry, e2: Entry) = e1.copy(qty = e1.qty + e2.qty)\n\n val (n, s) = (nextInt, nextInt)\n val entries = repeat(n) {\n Entry(next == \"B\", nextInt, nextInt)\n } groupBy {_.key} mapValues(_.reduce(join))\n\n val (buys, sells) = entries.values.partition(_.buy)\n\n val bestBuys = buys.toList.sortBy(-_.price)\n val bestSells = sells.toList.sortBy(_.price)\n\n bestSells.take(s).sortBy(-_.price) ++ bestBuys.take(s)\n}) {\n override def format(result: List[Entry]) = result mkString \"\\n\"\n}\n\ncase class Entry(buy: Boolean, price: Int, qty: Int) {\n val key = (buy, price)\n override def toString = s\"${if (buy) 'B' else 'S'} $price $qty\"\n}\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n import scala.collection.mutable.{Map => Dict}\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0\n}\n", "positive_code": [{"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\n\nobject _572B extends CodeForcesApp[List[Entry]]({scanner => import scanner._\n def join(e1: Entry, e2: Entry) = e1.copy(qty = e1.qty + e2.qty)\n\n val (n, s) = (nextInt, nextInt)\n val entries = repeat(n) {\n Entry(next == \"B\", nextInt, nextInt)\n } groupBy {_.key} mapValues(_.reduce(join))\n\n val (buys, sells) = entries.values.partition(_.buy)\n\n val bestBuys = buys.toList.sortBy(_.price)(desc)\n val bestSells = sells.toList.sortBy(_.price)\n\n bestSells.take(s).sortBy(_.price)(desc) ++ bestBuys.take(s)\n}) {\n override def format(result: List[Entry]) = result mkString \"\\n\"\n}\n\ncase class Entry(buy: Boolean, price: Int, qty: Int) {\n val key = (buy, price)\n override def toString = s\"${if (buy) 'B' else 'S'} $price $qty\"\n}\n/****************************************************************************************/\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n import scala.collection.mutable.{Map => Dict}\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0\n final def desc[A: Ordering] = implicitly[Ordering[A]].reverse\n}\n"}, {"source_code": "\nimport scala.io.StdIn.readLine\nimport scala.io.StdIn.readInt\n\n\nobject OrderBook {\n \n def readInts() : Array[Int] =\n readLine.split(' ').map(_.toInt)\n \n def main(args: Array[String]) {\n val ns = readInts()\n val n = ns(0)\n val s = ns(1) \n val orders = for {\n i <- 1 to n\n val line = readLine.split(' ')\n } yield ( (line(0),line(1).toInt),line(2).toInt)\n val orderBook = orders.groupBy(_._1).map{ case (k,v) => (k, v.map(_._2).sum)}\n val sellOrders = orderBook.filterKeys(_._1 == \"S\")\n .keys.toList.sortBy(_._2).take(s).reverse\n val buyOrders = orderBook.filterKeys(_._1 == \"B\")\n .keys.toList.sortBy(_._2).reverse.take(s)\n \n for (b <- sellOrders) {\n println(b._1 + \" \" + b._2 + \" \" + orderBook(b))\n } \n for (b <- buyOrders) {\n println(b._1 + \" \" + b._2 + \" \" + orderBook(b))\n }\n \n \n }\n \n}"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(n, s) = readLine().split(\" \").map(_.toInt)\n\n val sell = Array.ofDim[Int](100001)\n val buy = Array.ofDim[Int](100001)\n\n for (_ <- 1 to n) {\n val input = readLine().split(\" \")\n if (input(0) == \"S\") {\n sell(input(1).toInt) += input(2).toInt\n } else {\n buy(input(1).toInt) += input(2).toInt\n }\n }\n\n val S = sell.zipWithIndex.filterNot(_._1 == 0).take(s).reverse\n println(S.map(x => \"S \" + x._2 + \" \" + x._1).mkString(\"\\n\"))\n\n val B = buy.zipWithIndex.filterNot(_._1 == 0).takeRight(s).reverse\n println(B.map(x => \"B \" + x._2 + \" \" + x._1).mkString(\"\\n\"))\n}\n"}, {"source_code": "object Solution extends App{\n val in = scala.io.Source.stdin.getLines()\n val Array(n, s) = in.next().split(\" \").map(_.toInt)\n val data = Range(0, n).map{ _ =>\n val d = in.next().split(\" \")\n (d(0).head, d(1).toInt, d(2).toInt)\n }\n val buy = data.filter(_._1 == 'B')\n val sell = data.filter(_._1 == 'S')\n\n val baggr = buy.groupBy(_._2).map{case(price, listd) => ('B', price, listd.map(_._3).sum ) }.toList.sortBy{\n _._2\n }.reverse.take(s)\n val saggr = sell.groupBy(_._2).map{case(price, listd) => ('S', price, listd.map(_._3).sum ) }.toList.sortBy{\n _._2\n }.take(s).reverse\n\n saggr.foreach(t => println(s\"${t._1} ${t._2} ${t._3}\"))\n baggr.foreach(t => println(s\"${t._1} ${t._2} ${t._3}\"))\n}\n\n "}], "negative_code": [{"source_code": "object Solution extends App{\n val in = scala.io.Source.stdin.getLines()\n val Array(n, s) = in.next().split(\" \").map(_.toInt)\n val data = Range(0, n).map{ _ =>\n val d = in.next().split(\" \")\n (d(0).head, d(1).toInt, d(2).toInt)\n }\n val buy = data.filter(_._1 == 'B')\n val sell = data.filter(_._1 == 'S')\n\n val baggr = buy.groupBy(_._2).map{case(price, listd) => ('B', price, listd.map(_._3).sum ) }.toList.sortBy{\n _._2\n }.reverse.take(s)\n val saggr = sell.groupBy(_._2).map{case(price, listd) => ('S', price, listd.map(_._3).sum ) }.toList.sortBy{\n _._2\n }.take(s)\n\n saggr.foreach(t => println(s\"${t._1} ${t._2} ${t._3}\"))\n baggr.foreach(t => println(s\"${t._1} ${t._2} ${t._3}\"))\n}\n\n "}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\n\nobject _572B extends CodeForcesApp[List[Entry]]({scanner => import scanner._\n def join(e1: Entry, e2: Entry) = e1.copy(qty = e1.qty + e2.qty)\n\n val (n, s) = (nextInt, nextInt)\n val entries = repeat(n) {\n Entry(next == \"B\", nextInt, nextInt)\n } groupBy {_.key} mapValues(_.reduce(join))\n\n val (buys, sells) = entries.values.partition(_.buy)\n\n val bestBuys = buys.toList.sortBy(-_.price)\n val bestSells = sells.toList.sortBy(_.price)\n\n bestSells.sortBy(-_.price).take(s) ++ bestBuys.take(s)\n}) {\n override def format(result: List[Entry]) = result mkString \"\\n\"\n}\n\ncase class Entry(buy: Boolean, price: Int, qty: Int) {\n val key = (buy, price)\n override def toString = s\"${if (buy) 'B' else 'S'} $price $qty\"\n}\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n import scala.collection.mutable.{Map => Dict}\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._\nimport CodeForcesApp._\n\n\nobject _572B extends CodeForcesApp[List[Entry]]({scanner => import scanner._\n def join(e1: Entry, e2: Entry) = e1.copy(qty = e1.qty + e2.qty)\n\n val (n, s) = (nextInt, nextInt)\n val entries = repeat(n) {\n Entry(next == \"B\", nextInt, nextInt)\n } groupBy {_.key} mapValues(_.reduce(join))\n\n val (buys, sells) = entries.values.partition(_.buy)\n\n sells.toList.sortBy(-_.price).take(s) ++ buys.toList.sortBy(-_.price).take(s)\n}) {\n override def format(result: List[Entry]) = result mkString \"\\n\"\n}\n\ncase class Entry(buy: Boolean, price: Int, qty: Int) {\n val key = (buy, price)\n override def toString = s\"${if (buy) 'B' else 'S'} $price $qty\"\n}\nimport java.util.Scanner\nabstract class CodeForcesApp[A](solver: Scanner => A) {\n final def apply(problem: String): String = apply(new Scanner(problem))\n final def apply(scanner: Scanner): String = format(solver(scanner))\n def format(result: A): String = result.toString\n final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\nobject CodeForcesApp {\n import scala.collection.mutable.{Map => Dict}\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val modulus: Int = 1000000007\n final val eps: Double = 1e-9\n final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None\n final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}\n final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val Array(n, s) = readLine().split(\" \").map(_.toInt)\n\n val sell = Array.ofDim[Int](100001)\n val buy = Array.ofDim[Int](100001)\n\n for (_ <- 1 to n) {\n val input = readLine().split(\" \")\n if (input(0) == \"S\") {\n sell(input(1).toInt) += input(2).toInt\n } else {\n buy(input(1).toInt) += input(2).toInt\n }\n }\n\n val S = sell.zipWithIndex.filterNot(_._1 == 0).takeRight(s).reverse\n println(S.map(x => \"S \" + x._2 + \" \" + x._1).mkString(\"\\n\"))\n\n val B = buy.zipWithIndex.filterNot(_._1 == 0).takeRight(s).reverse\n println(B.map(x => \"B \" + x._2 + \" \" + x._1).mkString(\"\\n\"))\n}\n"}], "src_uid": "267c04c77f97bbdf7697dc88c7bfa4af"} {"source_code": "//package codeforces.contest1197\n\nobject CultureCode {\n import scala.collection.mutable\n\n val MOD: Long = 1000000000 + 7\n\n type Space = Int\n type Result = Long\n type R = Int\n type L = Int\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r\n collection.mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()\n\n for (_ <- 1 to n) {\n val Array(upper, lower) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())\n lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)\n }\n\n implicit val ordering: Ordering[(R, Space, Result)] =\n (x: (R, Space, Result), y: (R, Space, Result)) => x._1 - y._1\n\n val doneRValues =\n collection.mutable.TreeMap[R, (Space, Result)](1 -> (1, 1))\n\n def findLowerBound(r: Int): (R, (Space, Result)) =\n doneRValues.until(r + 1).last\n\n for ((r, lSeq) <- pairsMap) {\n val lastR: (R, (Space, Result)) = doneRValues.last\n (doneRValues.put _).tupled {\n\n var minSpace = lastR._2._1 + r - lastR._1\n var minSpaceResult: Result = lastR._2._2\n\n for ((l, pairOccurrences) <- lSeq) {\n val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)\n\n val space = prevSpace + l - prevR\n val spaceResult = (prevSpaceResult * pairOccurrences) % MOD\n\n if (minSpace == space)\n minSpaceResult = (minSpaceResult + spaceResult) % MOD\n else if (space < minSpace) {\n minSpace = space\n minSpaceResult = spaceResult\n }\n }\n\n (r, (minSpace, minSpaceResult))\n }\n }\n\n val lastL: L = pairsMap.last._2.maxBy(_._1)._1\n\n @scala.annotation.tailrec\n def loop(ls: List[(R, mutable.HashMap[L, Int])],\n rValues: List[Int]): List[Int] = {\n ls match {\n case Nil => rValues\n case (r, lMap) :: tail =>\n val l = lMap.maxBy(_._1)._1\n if (lastL < l)\n r :: rValues\n else\n loop(tail, r :: rValues)\n }\n }\n\n val rValuesToConsider =\n loop(pairsMap.from(lastL + 1).toList.reverse, List())\n\n val (_, res) = {\n var (minSpace, minSpaceResult) = (Int.MaxValue, 0L)\n\n for {\n r <- rValuesToConsider\n (space, spaceResult) = doneRValues(r)\n } {\n if (minSpace == space)\n minSpaceResult = (minSpaceResult + spaceResult) % MOD\n else if (space < minSpace) {\n minSpace = space\n minSpaceResult = spaceResult\n }\n }\n\n (minSpace, minSpaceResult)\n }\n\n println(res)\n }\n}\n", "positive_code": [{"source_code": "import scala.language.implicitConversions\n//package codeforces.contest1197\n\n/**\n * https://codeforces.com/contest/1197/problem/E\n *\n * Process R values in sorted order, saving result for each\n * Consider rooftop R values and sum each with the minimum space\n */\nobject CultureCode {\n import scala.collection.mutable\n\n val MOD: Long = 1000000000 + 7\n\n type Space = Int\n type Result = Long\n type R = Int\n type L = Int\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r\n mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()\n\n for (_ <- 1 to n) {\n val Array(upper, lower) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())\n lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)\n }\n\n val lastL: L = pairsMap.last._2.maxBy(_._1)._1\n\n @scala.annotation.tailrec\n def loop(ls: List[(R, mutable.HashMap[L, Int])],\n rValues: List[Int]): List[Int] = {\n ls match {\n case Nil => rValues\n case (r, lMap) :: tail =>\n val l = lMap.maxBy(_._1)._1\n if (lastL < l) // if this one's covered, then so are the rest\n r :: rValues\n else\n loop(tail, r :: rValues)\n }\n }\n\n val rValuesToConsider =\n loop(pairsMap.from(lastL + 1).toList.reverse, List())\n\n val doneRValues = new java.util.TreeMap[R, (Space, Result)]\n doneRValues.put(1, (1, 1))\n\n def findLowerBound(r: Int): (R, (Space, Result)) =\n doneRValues.floorEntry(r)\n\n for ((r, lSeq) <- pairsMap) {\n val lastR: (R, (Space, Result)) = doneRValues.lastEntry()\n (doneRValues.put _).tupled {\n\n r -> lSeq.foldLeft[(Space, Result)](\n (lastR._2._1 + r - lastR._1, lastR._2._2)\n ) {\n case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>\n val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)\n\n val space = prevSpace + l - prevR\n val spaceResult = (prevSpaceResult * pairOccurrences) % MOD\n\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n }\n\n val (_, res) = {\n rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {\n case ((minSpace, minSpaceResult), r) =>\n val (space, spaceResult) = doneRValues.get(r)\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n\n println(res)\n }\n\n implicit def deconstruct[K, V](arg: java.util.Map.Entry[K, V]): (K, V) =\n (arg.getKey, arg.getValue)\n}\n"}, {"source_code": "//package codeforces.contest1197\n\n/**\n * https://codeforces.com/contest/1197/problem/E\n *\n * Process R values in sorted order, saving result for each\n * Consider rooftop R values and sum each with the minimum space\n */\nobject CultureCode {\n import scala.collection.mutable\n\n val MOD: Long = 1000000000 + 7\n\n type Space = Int\n type Result = Long\n type R = Int\n type L = Int\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r\n mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()\n\n for (_ <- 1 to n) {\n val Array(upper, lower) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())\n lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)\n }\n\n val lastL: L = pairsMap.last._2.maxBy(_._1)._1\n\n @scala.annotation.tailrec\n def loop(ls: List[(R, mutable.HashMap[L, Int])],\n rValues: List[Int]): List[Int] = {\n ls match {\n case Nil => rValues\n case (r, lMap) :: tail =>\n val l = lMap.maxBy(_._1)._1\n if (lastL < l)\n r :: rValues\n else\n loop(tail, r :: rValues)\n }\n }\n\n val rValuesToConsider =\n loop(pairsMap.from(lastL + 1).toList.reverse, List())\n\n val doneRValues =\n collection.mutable.TreeMap[R, (Space, Result)](1 -> (1, 1))\n\n def findLowerBound(r: Int): (R, (Space, Result)) =\n doneRValues.until(r + 1).last\n\n for ((r, lSeq) <- pairsMap) {\n val lastR: (R, (Space, Result)) = doneRValues.last\n (doneRValues.put _).tupled {\n\n r -> lSeq.foldLeft[(Space, Result)](\n (lastR._2._1 + r - lastR._1, lastR._2._2)\n ) {\n case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>\n val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)\n\n val space = prevSpace + l - prevR\n val spaceResult = (prevSpaceResult * pairOccurrences) % MOD\n\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n }\n\n val (_, res) = {\n rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {\n case ((minSpace, minSpaceResult), r) =>\n val (space, spaceResult) = doneRValues(r)\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n\n println(res)\n }\n}\n"}, {"source_code": "//package codeforces.contest1197\n\nimport scala.language.implicitConversions\n\n/**\n * https://codeforces.com/contest/1197/problem/E\n *\n * Process R values in sorted order, saving result for each\n * Consider rooftop R values and sum each with the minimum space\n */\nobject CultureCode {\n import collection.mutable\n\n val MOD: Long = 1000000000 + 7\n\n type Space = Int\n type Result = Long\n type R = Int\n type L = Int\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val pairsMap: mutable.TreeMap[R, mutable.TreeMap[L, Int]] = // sorted By r\n mutable.TreeMap[R, mutable.TreeMap[L, Int]]()\n\n for (_ <- 1 to n) {\n val Array(upper, lower) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.TreeMap())\n lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)\n }\n\n val lastL: L = pairsMap.last._2.lastKey\n\n @scala.annotation.tailrec\n def loop(ls: List[(R, mutable.TreeMap[L, Int])],\n rValues: List[Int]): List[Int] = {\n ls match {\n case Nil => rValues\n case (r, lMap) :: tail =>\n val l = lMap.lastKey\n if (lastL < l) // if this one's covered, then so are the rest\n r :: rValues\n else\n loop(tail, r :: rValues)\n }\n }\n\n val rValuesToConsider =\n loop(pairsMap.from(lastL + 1).toList.reverse, List())\n\n val doneRValues = new java.util.TreeMap[R, (Space, Result)]\n doneRValues.put(1, (1, 1))\n\n def findLowerBound(r: Int): (R, (Space, Result)) =\n doneRValues.floorEntry(r)\n\n for ((r, lSeq) <- pairsMap) {\n val lastR: (R, (Space, Result)) = doneRValues.lastEntry()\n (doneRValues.put _).tupled {\n\n r -> lSeq.foldLeft[(Space, Result)](\n (lastR._2._1 + r - lastR._1, lastR._2._2)\n ) {\n case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>\n val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)\n\n val space = prevSpace + l - prevR\n val spaceResult = (prevSpaceResult * pairOccurrences) % MOD\n\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n }\n\n val (_, res) = {\n rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {\n case ((minSpace, minSpaceResult), r) =>\n val (space, spaceResult) = doneRValues.get(r)\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n\n println(res)\n }\n\n implicit def deconstruct[K, V](arg: java.util.Map.Entry[K, V]): (K, V) =\n (arg.getKey, arg.getValue)\n}\n"}, {"source_code": "//package codeforces.contest1197\n\n/**\n * https://codeforces.com/contest/1197/problem/E\n *\n * Process R values in sorted order, saving result for each\n * Consider rooftop R values and sum each with the minimum space\n */\nobject CultureCode {\n import scala.collection.mutable\n\n val MOD: Long = 1000000000 + 7\n\n type Space = Int\n type Result = Long\n type R = Int\n type L = Int\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r\n mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()\n\n for (_ <- 1 to n) {\n val Array(upper, lower) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())\n lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)\n }\n\n val lastL: L = pairsMap.last._2.maxBy(_._1)._1\n\n @scala.annotation.tailrec\n def loop(ls: List[(R, mutable.HashMap[L, Int])],\n rValues: List[Int]): List[Int] = {\n ls match {\n case Nil => rValues\n case (r, lMap) :: tail =>\n val l = lMap.maxBy(_._1)._1\n if (lastL < l) // if this one's covered, then so are the rest\n r :: rValues\n else\n loop(tail, r :: rValues)\n }\n }\n\n val rValuesToConsider =\n loop(pairsMap.from(lastL + 1).toList.reverse, List())\n\n val doneRValues = new java.util.TreeMap[R, (Space, Result)]\n doneRValues.put(1, (1, 1))\n\n def findLowerBound(r: Int): (R, (Space, Result)) =\n deconstruct(doneRValues.floorEntry(r))\n\n for ((r, lSeq) <- pairsMap) {\n val lastR: (R, (Space, Result)) = deconstruct(doneRValues.lastEntry())\n (doneRValues.put _).tupled {\n\n r -> lSeq.foldLeft[(Space, Result)](\n (lastR._2._1 + r - lastR._1, lastR._2._2)\n ) {\n case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>\n val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)\n\n val space = prevSpace + l - prevR\n val spaceResult = (prevSpaceResult * pairOccurrences) % MOD\n\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n }\n\n val (_, res) = {\n rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {\n case ((minSpace, minSpaceResult), r) =>\n val (space, spaceResult) = doneRValues.get(r)\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n\n println(res)\n }\n\n def deconstruct[K, V](arg: java.util.Map.Entry[K, V]): (K, V) =\n (arg.getKey, arg.getValue)\n}\n"}, {"source_code": "//package codeforces.contest1197\n\nimport scala.language.implicitConversions\n\n/**\n * https://codeforces.com/contest/1197/problem/E\n *\n * Process R values in sorted order, saving result for each\n * Consider rooftop R values and sum each with the minimum space\n */\nobject CultureCode {\n\n import collection.mutable\n\n val MOD: Long = 1000000000 + 7\n\n type Space = Int\n type Result = Long\n type R = Int\n type L = Int\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val pairsMap: mutable.TreeMap[R, mutable.TreeMap[L, Int]] = // sorted By r\n mutable.TreeMap[R, mutable.TreeMap[L, Int]]()\n\n for (_ <- 1 to n) {\n val Array(upper, lower) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.TreeMap())\n lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)\n }\n\n val lastL: L = pairsMap.last._2.lastKey\n\n @scala.annotation.tailrec\n def loop(ls: List[(R, mutable.TreeMap[L, Int])],\n rValues: List[Int]): List[Int] = {\n ls match {\n case Nil => rValues\n case (r, lMap) :: tail =>\n val l = lMap.lastKey\n if (lastL < l) // if this one's covered, then so are the rest\n r :: rValues\n else\n loop(tail, r :: rValues)\n }\n }\n\n val rValuesToConsider =\n loop(pairsMap.from(lastL + 1).toList.reverse, List())\n\n val doneRValues =\n collection.mutable.TreeMap[R, (Space, Result)](1 -> (1, 1))\n\n def findLowerBound(r: Int): (R, (Space, Result)) =\n doneRValues.until(r + 1).last\n\n for ((r, lSeq) <- pairsMap) {\n val lastR: (R, (Space, Result)) = doneRValues.last\n (doneRValues.put _).tupled {\n\n r -> lSeq.foldLeft[(Space, Result)](\n (lastR._2._1 + r - lastR._1, lastR._2._2)\n ) {\n case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>\n val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)\n\n val space = prevSpace + l - prevR\n val spaceResult = (prevSpaceResult * pairOccurrences) % MOD\n\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n }\n\n val (_, res) = {\n rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {\n case ((minSpace, minSpaceResult), r) =>\n val (space, spaceResult) = doneRValues(r)\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n\n println(res)\n }\n}\n"}, {"source_code": "//package codeforces.contest1197\nimport java.util\n\nimport scala.collection.convert.ImplicitConversionsToScala.`map AsScala`\nimport scala.language.implicitConversions\n\n/**\n * https://codeforces.com/contest/1197/problem/E\n *\n * Process R values in sorted order, saving result for each\n * Consider rooftop R values and sum each with the minimum space\n */\nobject CultureCode {\n\n val MOD: Long = 1000000000 + 7\n\n type Space = Int\n type Result = Long\n type R = Int\n type L = Int\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val pairsMap: util.TreeMap[R, util.TreeMap[L, R]] =\n new java.util.TreeMap[R, util.TreeMap[L, Int]]() // sorted By r\n\n for (_ <- 1 to n) {\n val Array(upper, lower) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val lowerMap: util.TreeMap[L, R] = {\n Option(pairsMap.get(upper)).getOrElse {\n val res = new util.TreeMap[L, Int]()\n pairsMap.put(upper, res)\n res\n }\n }\n lowerMap.put(lower, lowerMap.getOrDefault(lower, 0) + 1)\n }\n\n val lastL: L = pairsMap.lastEntry()._2.lastKey()\n\n @scala.annotation.tailrec\n def loop(ls: List[(R, util.TreeMap[L, Int])],\n rValues: List[Int]): List[Int] = {\n ls match {\n case Nil => rValues\n case (r, lMap) :: tail =>\n val l = lMap.lastKey()\n if (lastL < l) // if this one's covered, then so are the rest\n r :: rValues\n else\n loop(tail, r :: rValues)\n }\n }\n\n val rValuesToConsider =\n loop(pairsMap.tailMap(lastL, false).toList.reverse, List())\n\n val doneRValues = new java.util.TreeMap[R, (Space, Result)]\n doneRValues.put(1, (1, 1))\n\n def findLowerBound(r: Int): (R, (Space, Result)) =\n doneRValues.floorEntry(r)\n\n for ((r, lSeq) <- pairsMap) {\n val lastR: (R, (Space, Result)) = doneRValues.lastEntry()\n (doneRValues.put _).tupled {\n\n r -> lSeq.foldLeft[(Space, Result)](\n (lastR._2._1 + r - lastR._1, lastR._2._2)\n ) {\n case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>\n val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)\n\n val space = prevSpace + l - prevR\n val spaceResult = (prevSpaceResult * pairOccurrences) % MOD\n\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n }\n\n val (_, res) = {\n rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {\n case ((minSpace, minSpaceResult), r) =>\n val (space, spaceResult) = doneRValues.get(r)\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n\n println(res)\n }\n\n implicit def deconstruct[K, V](arg: java.util.Map.Entry[K, V]): (K, V) =\n (arg.getKey, arg.getValue)\n}\n"}, {"source_code": "import scala.language.implicitConversions\n//package codeforces.contest1197\n\n/**\n * https://codeforces.com/contest/1197/problem/E\n *\n * Process R values in sorted order, saving result for each\n * Consider rooftop R values and sum each with the minimum space\n */\nobject CultureCode {\n import scala.collection.mutable\n\n val MOD: Long = 1000000000 + 7\n\n type Space = Int\n type Result = Long\n type R = Int\n type L = Int\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r\n mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()\n\n for (_ <- 1 to n) {\n val Array(upper, lower) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())\n lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)\n }\n\n val lastL: L = pairsMap.last._2.maxBy(_._1)._1\n\n @scala.annotation.tailrec\n def loop(ls: List[(R, mutable.HashMap[L, Int])],\n rValues: List[Int]): List[Int] = {\n ls match {\n case Nil => rValues\n case (r, lMap) :: tail =>\n val l = lMap.maxBy(_._1)._1\n if (lastL < l) // if this one's covered, then so are the rest\n r :: rValues\n else\n loop(tail, r :: rValues)\n }\n }\n\n val rValuesToConsider =\n loop(pairsMap.from(lastL + 1).toList.reverse, List())\n\n val doneRValues = new java.util.TreeMap[R, (Space, Result)]\n doneRValues.put(1, (1, 1))\n\n def findLowerBound(r: Int): (R, (Space, Result)) =\n doneRValues.floorEntry(r)\n\n for ((r, lSeq) <- pairsMap) {\n val lastR: (R, (Space, Result)) = doneRValues.lastEntry()\n (doneRValues.put _).tupled {\n\n r -> lSeq.foldLeft[(Space, Result)](\n (lastR._2._1 + r - lastR._1, lastR._2._2)\n ) {\n case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>\n val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)\n\n val space = prevSpace + l - prevR\n val spaceResult = (prevSpaceResult * pairOccurrences) % MOD\n\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n }\n\n val (_, res) = {\n rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {\n case ((minSpace, minSpaceResult), r) =>\n val (space, spaceResult) = doneRValues.get(r)\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n\n println(res)\n }\n\n implicit def deconstruct[K, V](arg: java.util.Map.Entry[K, V]): (K, V) =\n (arg.getKey, arg.getValue)\n}\n"}, {"source_code": "//package codeforces.contest1197\n\n/**\n * https://codeforces.com/contest/1197/problem/E\n *\n * Process R values in sorted order, saving result for each\n * Consider rooftop R values and sum each with the minimum space\n */\nobject CultureCode {\n import collection.mutable\n\n val MOD: Long = 1000000000 + 7\n\n type Space = Int\n type Result = Long\n type R = Int\n type L = Int\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val pairsMap: mutable.TreeMap[R, mutable.TreeMap[L, Int]] = // sorted By r\n mutable.TreeMap[R, mutable.TreeMap[L, Int]]()\n\n for (_ <- 1 to n) {\n val Array(upper, lower) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.TreeMap())\n lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)\n }\n\n val lastL: L = pairsMap.last._2.lastKey\n\n @scala.annotation.tailrec\n def loop(ls: List[(R, mutable.TreeMap[L, Int])],\n rValues: List[Int]): List[Int] = {\n ls match {\n case Nil => rValues\n case (r, lMap) :: tail =>\n val l = lMap.lastKey\n if (lastL < l) // if this one's covered, then so are the rest\n r :: rValues\n else\n loop(tail, r :: rValues)\n }\n }\n\n val rValuesToConsider =\n loop(pairsMap.from(lastL + 1).toList.reverse, List())\n\n val doneRValues =\n collection.mutable.TreeMap[R, (Space, Result)](1 -> (1, 1))\n\n def findLowerBound(r: Int): (R, (Space, Result)) =\n doneRValues.until(r + 1).last\n\n for ((r, lSeq) <- pairsMap) {\n val lastR: (R, (Space, Result)) = doneRValues.last\n (doneRValues.put _).tupled {\n\n r -> lSeq.foldLeft[(Space, Result)](\n (lastR._2._1 + r - lastR._1, lastR._2._2)\n ) {\n case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>\n val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)\n\n val space = prevSpace + l - prevR\n val spaceResult = (prevSpaceResult * pairOccurrences) % MOD\n\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n }\n\n val (_, res) = {\n rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {\n case ((minSpace, minSpaceResult), r) =>\n val (space, spaceResult) = doneRValues(r)\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n\n println(res)\n }\n}\n"}, {"source_code": "//package codeforces.contest1197\n\n/**\n * https://codeforces.com/contest/1197/problem/E\n *\n * Process R values in sorted order, saving result for each\n * Consider rooftop R values and sum each with the minimum space\n */\nobject CultureCode {\n import scala.collection.mutable\n \n\n val MOD: Long = 1000000000 + 7\n\n type Space = Int\n type Result = Long\n type R = Int\n type L = Int\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r\n mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()\n\n for (_ <- 1 to n) {\n val Array(upper, lower) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())\n lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)\n }\n\n val lastL: L = pairsMap.last._2.maxBy(_._1)._1\n\n @scala.annotation.tailrec\n def loop(ls: List[(R, mutable.HashMap[L, Int])],\n rValues: List[Int]): List[Int] = {\n ls match {\n case Nil => rValues\n case (r, lMap) :: tail =>\n val l = lMap.maxBy(_._1)._1\n if (lastL < l) // if this one's covered, then so are the rest\n r :: rValues\n else\n loop(tail, r :: rValues)\n }\n }\n\n val rValuesToConsider =\n loop(pairsMap.from(lastL + 1).toList.reverse, List())\n\n val doneRValues = new java.util.TreeMap[R, (Space, Result)]\n doneRValues.put(1, (1, 1))\n\n def findLowerBound(r: Int): (R, (Space, Result)) =\n deconstruct(doneRValues.floorEntry(r))\n\n for ((r, lSeq) <- pairsMap) {\n val lastR: (R, (Space, Result)) = deconstruct(doneRValues.lastEntry())\n (doneRValues.put _).tupled {\n\n r -> lSeq.foldLeft[(Space, Result)](\n (lastR._2._1 + r - lastR._1, lastR._2._2)\n ) {\n case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>\n val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)\n\n val space = prevSpace + l - prevR\n val spaceResult = (prevSpaceResult * pairOccurrences) % MOD\n\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n }\n\n val (_, res) = {\n rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {\n case ((minSpace, minSpaceResult), r) =>\n val (space, spaceResult) = doneRValues.get(r)\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n\n println(res)\n }\n\n def deconstruct[K, V](arg: java.util.Map.Entry[K, V]): (K, V) =\n (arg.getKey, arg.getValue)\n}\n"}, {"source_code": "//package codeforces.contest1197\n\nimport scala.language.implicitConversions\n\n/**\n * https://codeforces.com/contest/1197/problem/E\n *\n * Process R values in sorted order, saving result for each\n * Consider rooftop R values and sum each with the minimum space\n */\nobject CultureCode {\n\n import collection.mutable\n\n val MOD: Long = 1000000000 + 7\n\n type Space = Int\n type Result = Long\n type R = Int\n type L = Int\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val pairsMap: mutable.TreeMap[R, mutable.TreeMap[L, Int]] = // sorted By r\n mutable.TreeMap[R, mutable.TreeMap[L, Int]]()\n\n for (_ <- 1 to n) {\n val Array(upper, lower) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.TreeMap())\n lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)\n }\n\n val lastL: L = pairsMap.last._2.lastKey\n\n @scala.annotation.tailrec\n def loop(ls: List[(R, mutable.TreeMap[L, Int])],\n rValues: List[Int]): List[Int] = {\n ls match {\n case Nil => rValues\n case (r, lMap) :: tail =>\n val l = lMap.lastKey\n if (lastL < l) // if this one's covered, then so are the rest\n r :: rValues\n else\n loop(tail, r :: rValues)\n }\n }\n\n val rValuesToConsider =\n loop(pairsMap.from(lastL + 1).toList.reverse, List())\n\n val doneRValues = new java.util.TreeMap[R, (Space, Result)]\n doneRValues.put(1, (1, 1))\n\n def findLowerBound(r: Int): (R, (Space, Result)) =\n doneRValues.floorEntry(r)\n\n for ((r, lSeq) <- pairsMap) {\n val lastR: (R, (Space, Result)) = doneRValues.lastEntry()\n (doneRValues.put _).tupled {\n\n r -> lSeq.foldLeft[(Space, Result)](\n (lastR._2._1 + r - lastR._1, lastR._2._2)\n ) {\n case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>\n val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)\n\n val space = prevSpace + l - prevR\n val spaceResult = (prevSpaceResult * pairOccurrences) % MOD\n\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n }\n\n val (_, res) = {\n rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {\n case ((minSpace, minSpaceResult), r) =>\n val (space, spaceResult) = doneRValues.get(r)\n if (minSpace == space)\n (minSpace, (minSpaceResult + spaceResult) % MOD)\n else if (space < minSpace)\n (space, spaceResult)\n else\n (minSpace, minSpaceResult)\n }\n }\n\n println(res)\n }\n\n implicit def deconstruct[K, V](arg: java.util.Map.Entry[K, V]): (K, V) =\n (arg.getKey, arg.getValue)\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contest1197\n\nobject CultureCode {\n val MOD: Long = 1000000000 + 7\n\n type Space = Int\n type Result = Long\n type R = Int\n type L = Int\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val pairs: IndexedSeq[(R, Seq[(L, Int)])] = (1 to n)\n .map { _ =>\n val Array(upper, lower) = io.StdIn.readLine().split(\" \").map(_.toInt)\n (lower, upper)\n }\n .groupBy(_._2)\n .map {\n case (upper, pairValues) =>\n upper -> pairValues\n .map(_._1)\n .groupBy(identity)\n .mapValues(_.length)\n .toSeq\n }\n .toIndexedSeq\n .sortBy(_._1)\n\n implicit val ordering: Ordering[(R, Space, Result)] =\n (x: (R, Space, Result), y: (R, Space, Result)) => x._1 - y._1\n\n val doneRValues = collection.mutable.TreeSet[(R, Space, Result)]((1, 1, 1))\n\n def findLowerBound(r: Int): (R, Space, Result) =\n doneRValues.to((r, -1, -1L)).last\n\n for ((r, lSeq) <- pairs) {\n val lastR = doneRValues.last\n doneRValues.add(\n lSeq.foldLeft(lastR.copy(_1 = r, _2 = lastR._2 + r - lastR._1)) {\n case ((_, minSpace, minSpaceResult), (l, pairOccurrences)) =>\n val (_, space, spaceResult) = findLowerBound(l)\n\n if (minSpace == space)\n (r, minSpace, (minSpaceResult + spaceResult * pairOccurrences) % MOD)\n else if (minSpace < space)\n (r, minSpace, minSpaceResult)\n else\n (r, space, (spaceResult * pairOccurrences) % MOD)\n }\n )\n }\n\n val lastL: L = pairs(pairs.length - 1)._2.maxBy(_._1)._1\n\n val lastRValues = doneRValues.from((lastL + 1, -1, -1L))\n\n val minSpace = lastRValues.minBy(_._2)._2\n\n import collection.breakOut\n val res = lastRValues.collect {\n case (_, space, result) if space == minSpace => result\n }(breakOut).sum\n\n println(res)\n }\n}\n"}, {"source_code": "//package codeforces.contest1197\n\nobject CultureCode {\n import scala.collection.mutable\n\n val MOD: Long = 1000000000 + 7\n\n type Space = Int\n type Result = Long\n type R = Int\n type L = Int\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r\n collection.mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()\n\n for (_ <- 1 to n) {\n val Array(upper, lower) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())\n lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)\n }\n\n implicit val ordering: Ordering[(R, Space, Result)] =\n (x: (R, Space, Result), y: (R, Space, Result)) => x._1 - y._1\n\n val doneRValues =\n collection.mutable.TreeMap[R, (Space, Result)](1 -> (1, 1))\n\n def findLowerBound(r: Int): (R, (Space, Result)) =\n doneRValues.until(r + 1).last\n\n for ((r, lSeq) <- pairsMap) {\n val lastR: (R, (Space, Result)) = doneRValues.last\n (doneRValues.put _).tupled {\n\n var minSpace = lastR._2._1 + r - lastR._1\n var minSpaceResult: Result = lastR._2._2\n\n for ((l, pairOccurrences) <- lSeq) {\n val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)\n\n val space = prevSpace + l - prevR\n val spaceResult = (prevSpaceResult * pairOccurrences) % MOD\n\n if (minSpace == space)\n minSpaceResult = (minSpaceResult + spaceResult) % MOD\n else if (space < minSpace) {\n minSpace = space\n minSpaceResult = spaceResult\n }\n }\n\n (r, (minSpace, minSpaceResult))\n }\n }\n\n val lastL: L = pairsMap.last._2.maxBy(_._1)._1\n\n @scala.annotation.tailrec\n def loop(ls: List[(R, mutable.HashMap[L, Int])],\n rValues: List[Int]): List[Int] = {\n ls match {\n case Nil => rValues\n case (r, lMap) :: tail =>\n val l = lMap.maxBy(_._1)._1\n if (lastL <= l)\n r :: rValues\n else\n loop(tail, r :: rValues)\n }\n }\n\n val rValuesToConsider =\n loop(pairsMap.from(lastL + 1).toList.reverse, List(pairsMap.last._1))\n\n val (_, res) = {\n var (minSpace, minSpaceResult) = (Int.MaxValue, 0L)\n\n for {\n r <- rValuesToConsider\n (space, spaceResult) = doneRValues(r)\n } {\n if (minSpace == space)\n minSpaceResult = (minSpaceResult + spaceResult) % MOD\n else if (space < minSpace) {\n minSpace = space\n minSpaceResult = spaceResult\n }\n }\n\n (minSpace, minSpaceResult)\n }\n\n println(res)\n }\n}\n"}, {"source_code": "//package codeforces.contest1197\n\nobject CultureCode {\n import scala.collection.mutable\n\n val MOD: Long = 1000000000 + 7\n\n type Space = Int\n type Result = Long\n type R = Int\n type L = Int\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val pairsMap: mutable.Map[R, mutable.HashMap[L, R]] = // sorted By r\n collection.mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()\n\n for (_ <- 1 to n) {\n val Array(upper, lower) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())\n lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)\n }\n\n implicit val ordering: Ordering[(R, Space, Result)] =\n (x: (R, Space, Result), y: (R, Space, Result)) => x._1 - y._1\n\n val doneRValues = collection.mutable.TreeSet[(R, Space, Result)]((1, 1, 1))\n\n def findLowerBound(r: Int): (R, Space, Result) =\n doneRValues.until((r + 1, -1, -1L)).last\n\n for ((r, lSeq) <- pairsMap) {\n val lastR = doneRValues.last\n doneRValues.add {\n\n var minSpace = lastR._2 + r - lastR._1\n var minSpaceResult = lastR._3\n\n for ((l, pairOccurrences) <- lSeq) {\n val (prevR, prevSpace, prevSpaceResult) = findLowerBound(l)\n\n val space = prevSpace + l - prevR\n val spaceResult = (prevSpaceResult * pairOccurrences) % MOD\n\n if (minSpace == space)\n minSpaceResult = (minSpaceResult + spaceResult) % MOD\n else if (space < minSpace) {\n minSpace = space\n minSpaceResult = spaceResult\n }\n }\n\n (r, minSpace, minSpaceResult)\n }\n }\n\n val lastL: L = pairsMap.last._2.maxBy(_._1)._1\n\n val lastRValues = doneRValues.from((lastL + 1, -1, -1L))\n\n val (_, res) = {\n var (minSpace, minSpaceResult) = (Int.MaxValue, 0L)\n\n for ((_, space, spaceResult) <- lastRValues) {\n if (minSpace == space)\n minSpaceResult = (minSpaceResult + spaceResult) % MOD\n else if (space < minSpace) {\n minSpace = space\n minSpaceResult = spaceResult\n }\n }\n\n (minSpace, minSpaceResult)\n }\n\n println(res)\n }\n}\n"}], "src_uid": "d8c2cb03579142f45d46f1fe22a9b8c0"} {"source_code": "import scala.collection.mutable.ArrayBuffer\r\nimport scala.io.Source\r\n\r\nobject Main extends App {\r\n val input = Source.fromInputStream(System.in).getLines()\r\n val t = input.next().toInt\r\n val res = new ArrayBuffer[String]()\r\n for (i <- 0 until t) {\r\n val n = input.next().toInt\r\n val p = input.next().split(\" \").map(_.toInt).toList\r\n\r\n val plr = p.zipWithIndex.map(x => (x._1, x._2 + 1)).filter(x => x._1 != x._2)\r\n if (plr.isEmpty) res.append(p.mkString(\" \"))\r\n else {\r\n val minInd = plr.min._2 - 1\r\n val startingInd = plr.head._2 - 1\r\n\r\n val start = p.slice(0, startingInd)\r\n val md = p.slice(startingInd, minInd + 1).reverse\r\n val end = if (minInd + 1 == n) Nil else p.slice(minInd + 1, n)\r\n res.append((start ++ md ++ end).mkString(\" \"))\r\n }\r\n }\r\n res.foreach(println)\r\n}", "positive_code": [{"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.immutable.TreeSet\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n readInt()\n val a = readInts()\n val optionIndex = a.zipWithIndex.find {\n case (a, index) => a != index + 1\n }\n val answer = optionIndex match {\n case None => a\n case Some((_, index)) =>\n val l = index\n val r = a.indexOf(index + 1)\n a.slice(0, l) ++ a.slice(l, r + 1).reverse ++ a.slice(r + 1, a.length)\n }\n println(answer.mkString(\" \"))\n }\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n def readChars(): Array[Char] = readLine().toCharArray\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n def contains(value: T) = multiSet.contains(value)\n def isEmpty() = multiSet.isEmpty\n def max: T = multiSet.last._1\n def min: T = multiSet.head._1\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n"}], "negative_code": [], "src_uid": "a57823a7ca0f67a07f94175ab59d33de"} {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P248A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val N = sc.nextInt\n val ds = Array.fill(N, 2)(sc.nextInt)\n\n val answer: Int = {\n for (i <- 0 until 2) yield {\n val closed = (0 until N).map(ds(_)(i)).sum\n closed min (N - closed)\n }\n }.sum\n\n out.println(answer)\n out.close\n}\n", "positive_code": [{"source_code": "import java.util._\nimport java.io._\nimport java.math._\nimport java.awt.Point\nimport java.awt.geom._\nimport java.lang.System._\nimport java.lang.Math._\n\nobject A {\n var n = -1\n var r: Array[Int] = null\n var l: Array[Int] = null\n \n def solve(){\n var cl = 0\n var cr = 0\n for(i <- 0 until n) if(l(i) == 1) cl = cl + 1;\n for(i <- 0 until n) if(r(i) == 1) cr = cr + 1;\n println(min(n-cl, cl)+min(n-cr, cr))\n }\n def main(args: Array[String]){\n val sc = new Scanner(in)\n n = sc.nextInt\n l = new Array(n)\n r = new Array(n)\n for(i <- 0 until n){\n l(i) = sc.nextInt\n r(i) = sc.nextInt\n }\n solve\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n\n val data = (1 to n).map{ _ => in.next()}\n val left = data.count(_.head == '1')\n val right = data.count(_.last == '1')\n\n println(Math.min(left, n - left) + Math.min(right, n - right))\n}"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val f = Array[Int => Int](x => x, 1-, _ => 0, _ => 1)\n val a = for(_ <- 1 to readInt) yield readInts\n def ans = f.map { func =>\n val need = Array(0, 1).map(func)\n a.flatMap(x => (x zip need).map(_.productIterator.map(_.asInstanceOf[Int]).reduce(_ - _).abs)).sum\n }.min\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val f = Array[Int => Int](x => x, 1-, 0*, 1|)\n val a = for(_ <- 1 to readInt) yield readInts\n def ans = f.map { func =>\n val need = Array(0, 1).map(func)\n a.flatMap(x => (x zip need).map(_.productIterator.map(_.asInstanceOf[Int]).reduce(_^_))).sum\n }.min\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val f = Array[Int => Int](x => x, 1-, 0*, 1|)\n val a = for(_ <- 1 to readInt) yield readInts\n def ans = f.map { func =>\n val need = Array(0, 1).map(func)\n a.flatMap(x => (x zip need).map(_.productIterator.map(_.asInstanceOf[Int]).reduce(_ - _).abs)).sum\n }.min\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val f = Array((x: Int) => x, (x: Int) => 1 - x, (x: Int) => 0, (x: Int) => 1)\n val a = for(_ <- 1 to readInt) yield readInts\n def ans = f.map { func =>\n val need = Array(0, 1).map(func)\n a.flatMap(x => (x zip need).map(_.productIterator.map(_.asInstanceOf[Int]).reduce(_ - _).abs)).sum\n }.min\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport java.math._\n\nobject B extends App\n{\n\tval cin=new Scanner(System.in);\n\tval n=cin.nextInt()\n\tvar l,r=0\n\tfor(i <- 1 to n)\n\t{\n\t\tval a,b=cin.nextInt()\n\t\tl+=a\n\t\tr+=b\n\t}\n\tprintln(math.min(l,n-l)+math.min(r,n-r))\n}\n"}, {"source_code": "import collection.mutable.ArrayBuffer\n\nobject test2 extends App {\n val n=readLine.toInt\n var left=0\n var right=0\n 0 until n foreach{i=>\n \tval Array(l,r)=readLine.split(\" \").map(_.toInt)\n \tif(l==0) left+=1\n \tif(r==0) right+=1\n }\n \n if(left>n/2) left=n-left\n if(right>n/2) right=n-right\n \n println(left+right)\n}\n\n"}, {"source_code": "object Main {\n def readDoor() = {\n val a = readLine().split(\" \").map(_.toInt)\n (a(0), a(1))\n }\n\n def main(args: Array[String]) {\n val n = readInt\n val a = (1 to n).map(_ => readDoor())\n val left = a.map(_._1).sum\n val right = a.map(_._2).sum \n println(left.min(n - left) + right.min(n - right))\n }\n}"}], "negative_code": [{"source_code": "import java.util._\nimport java.io._\nimport java.math._\nimport java.awt.Point\nimport java.awt.geom._\nimport java.lang.System._\nimport java.lang.Math._\n\nobject A {\n def main(args: Array[String]){\n val sc = new Scanner(in)\n n = sc.nextInt\n solve\n }\n\n var n = -1\n def solve(){\n println(-1)\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n\n val data = (1 to n).foldLeft((0, 0)){\n case ((left, right), _) =>\n val str = in.next()\n var newLeft = left\n var newRight = right\n if (str.head == '0')\n newLeft += 1\n else\n newRight += 1\n if (str.last == '0')\n newRight += 1\n else\n newLeft += 1\n (newLeft, newRight)\n }\n println(Math.min(data._1, data._2))\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n\n val data = (1 to n).map{ _ => in.next()}\n val left = data.count(_.head == '1')\n val right = data.count(_.head == '1')\n\n println(Math.min(left, data.size - left) + Math.min(right, data.size - right))\n}"}, {"source_code": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\n\nobject Easy {\n val reader = new BufferedReader(new InputStreamReader(System.in))\n def readInt = reader.readLine().toInt\n def readInts = reader.readLine().split(\" \").map(_.toInt)\n def readLongs = reader.readLine().split(\" \").map(_.toLong)\n\n val f = Array((x: Int) => x, (x: Int) => 1 - x)\n val a = for(_ <- 1 to readInt) yield readInts\n def ans = f.map { func =>\n val need = Array(0, 1).map(func)\n a.flatMap(x => (x zip need).map(_.productIterator.map(_.asInstanceOf[Int]).reduce(_ - _).abs)).sum\n }.min\n\n def main(a: Array[String]) {\n println(ans)\n }\n}\n"}], "src_uid": "2052b0b4abdcf7d613b56842b1267f60"} {"source_code": "import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _631B extends CodeForcesApp {\n override def solve(in: InputReader, out: OutputWriter) = {\n val n, m, k = in[Int]\n val rowColor, colColor = map[Int] to (0 -> 0)\n (1 to k) foreach {i =>\n val table = if (in[Int] == 1) rowColor else colColor\n table(in[Int]) = i -> in[Int]\n }\n for (r <- 1 to n) {\n for(c <- 1 to m) {\n out += (rowColor(r) max colColor(c))._2\n }\n out.newLine()\n }\n }\n\n def map[A] = new {\n import scala.collection.mutable.{Map => Dict}\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def solve(in: InputReader, out: OutputWriter): Unit\n def main(args: Array[String]): Unit = solve(new InputReader(System.in), new OutputWriter(System.out))\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n\nclass OutputWriter(out: PrintWriter) {\n def this(out: OutputStream) = this(new PrintWriter(out, true))\n\n var separator = \" \"\n private[this] var currentSeparator: Option[String] = None\n\n def +=(obj: Any): this.type = { //todo: Any*?\n currentSeparator match {\n case Some(x) => out.print(x)\n case _ => currentSeparator = Option(separator)\n }\n out.print(obj)\n this\n }\n\n def newLine(): this.type = {\n currentSeparator = None\n out.println()\n this\n }\n\n def ++=(obj: Traversable[_], ifEmpty: => Any = \"\"): this.type = {\n var c = 0\n obj foreach {i =>\n this += i\n c += 1\n }\n if (c == 0) this += ifEmpty else this\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.Scanner\n\nimport scala.collection.mutable\n\nobject Solution extends ConsoleIO {\n def main(args: Array[String]) = {\n withIO {(reader, writer) =>\n val n = reader.nextInt()\n val m = reader.nextInt()\n val k = reader.nextInt()\n val rows = mutable.Map.empty[Int, (Int, Int)]\n val columns = mutable.Map.empty[Int, (Int, Int)]\n (1 to k).foreach { priority =>\n val mode = reader.nextInt()\n val position = reader.nextInt() - 1\n val color = reader.nextInt()\n mode match {\n case 1 => rows.put(position, (priority, color))\n case 2 => columns.put(position, (priority, color))\n }\n }\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n (rows.get(i), columns.get(j)) match {\n case (None, None) => writer.print(0)\n case (None, Some(columnInfo)) => writer.print(columnInfo._2)\n case (Some(rowInfo), None) => writer.print(rowInfo._2)\n case (Some(rowInfo), Some(columnInfo)) =>\n if (rowInfo._1 > columnInfo._1) writer.print(rowInfo._2) else writer.print(columnInfo._2)\n }\n writer.print(\" \")\n }\n writer.print(System.lineSeparator())\n }\n }\n }\n}\n\ntrait ConsoleIO {\n def withIO(task: (Scanner, PrintWriter) => Unit) = {\n val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))\n val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))\n task(reader, writer)\n reader.close()\n writer.close()\n }\n}\n\ntrait FileIO {\n def withIO(task: (Scanner, PrintWriter) => Unit) = {\n val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream(\"input.txt\"))))\n val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(\"output.txt\"))))\n task(reader, writer)\n reader.close()\n writer.close()\n }\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m, k) = in.next().split(' ').map(_.toInt)\n val (rowMap, colMap) = (1 to k).foldLeft((Map.empty[Int, (Int, Int)], Map.empty[Int, (Int, Int)])) {\n case ((row, col), i) =>\n in.next().split(' ').map(_.toInt) match {\n case Array(1, r, a) => (row + (r -> (a, i)), col)\n case Array(2, c, a) => (row, col + (c -> (a, i)))\n }\n }\n val res = Array.ofDim[Int](n, m)\n (0 until n).foreach { i =>\n (0 until m).foreach { j =>\n val col = colMap.get(j + 1)\n val row = rowMap.get(i + 1)\n res(i)(j) = if (row.isEmpty && col.isEmpty)\n 0\n else if (col.isEmpty || (row.nonEmpty && col.get._2 < row.get._2))\n row.get._1\n else\n col.get._1\n }\n }\n println(res.map(_.mkString(\" \")).mkString(\"\\n\"))\n}"}, {"source_code": "\n/**\n * @author pvasilyev\n * @since 14 Aug 2016\n */\nobject B631 extends App {\n\n def solve() = {\n val Array(n,m,k): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val lastRow = Array.ofDim[(Int, Int)](n)\n (0 until n).foreach(i => lastRow(i) = (0, -1))\n val lastCol = Array.ofDim[(Int, Int)](m)\n (0 until m).foreach(j => lastCol(j) = (0, -1))\n for (i <- 0 until k) {\n val Array(t, el, color): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n if (t == 1) {\n // row\n lastRow(el-1) = (color, i)\n } else {\n // col\n lastCol(el-1) = (color, i)\n }\n }\n val builder: StringBuilder = new StringBuilder()\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n if (lastRow(i)._2 > lastCol(j)._2) {\n builder.append(lastRow(i)._1)\n } else {\n builder.append(lastCol(j)._1)\n }\n builder.append(' ')\n }\n builder.append('\\n')\n }\n println(builder)\n }\n\n solve()\n\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _631B extends CodeForcesApp {\n override def solve(in: InputReader, out: OutputWriter) = {\n val n, m, k = in[Int]\n val rowColor, colColor = map[Int] to (0 -> 0)\n (1 to k) foreach {i =>\n val table = if (in[Int] == 1) rowColor else colColor\n table(in[Int]) = i -> in[Int]\n }\n for (r <- 1 to n) {\n for(c <- 1 to m) {\n out append (rowColor(r) max colColor(c))._2\n }\n out.newLine()\n }\n }\n\n def map[A] = new {\n import scala.collection.mutable.{Map => Dict}\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def solve(in: InputReader, out: OutputWriter): Unit\n def main(args: Array[String]): Unit = solve(new InputReader(System.in), new OutputWriter(System.out))\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n\nclass OutputWriter(out: PrintWriter) {\n def this(out: OutputStream) = this(new PrintWriter(out, true))\n\n var separator = \" \"\n private[this] var isNewLine: Boolean = true\n\n def +=(obj: Any): this.type = {\n if (isNewLine) isNewLine = false else out.print(separator)\n out.print(obj)\n this\n }\n\n def newLine(): this.type = {\n isNewLine = true\n out.println()\n this\n }\n\n def ++=(obj: Traversable[_], ifEmpty: => Any = \"\"): this.type = {\n var c = 0\n obj foreach {i =>\n this += i\n c += 1\n }\n if (c == 0) this += ifEmpty else this\n }\n\n def append(obj: Any*): this.type = this ++= obj\n}\n"}, {"source_code": "import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _631B extends CodeForcesApp {\n override type Result = Stream[Stream[Int]]\n\n override def solve(read: InputReader) = {\n val n, m, k = read[Int]\n val rowColor, colColor = map[Int] to (0 -> 0)\n (1 to k) foreach {i =>\n val q, s, c = read[Int]\n val table = q match {\n case 1 => rowColor\n case 2 => colColor\n }\n table(s) = i -> c\n }\n Stream.tabulate(n+1, m+1) {case (r, c) => (rowColor(r) max colColor(c))._2}\n }\n\n def map[A] = new {\n import scala.collection.mutable.{Map => Dict}\n def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default\n }\n\n override def format(result: Result) = {\n val sb = new StringBuilder()\n result.tail foreach {row => sb.append(row.tail.mkString(\"\", \" \", \"\\n\"))}\n sb.toString\n }\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n type Result\n def solve(scanner: InputReader): Result\n def format(result: Result): String\n def apply(scanner: InputReader): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}\nimport java.util.StringTokenizer\n\nclass InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n if (tokenizers.nonEmpty) Some(tokenizers.head) else None\n }\n\n def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)\n\n def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {\n val builder = cbf()\n for {_ <- 1 to n} builder += apply[A]\n builder.result()\n }\n\n def till(delim: String): String = tokenizer().get.nextToken(delim)\n def tillEndOfLine() = till(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n\nclass Parser[A](val apply: InputReader => A) {\n def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)\n}\nobject Parser {\n type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]\n implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A]) : Parser[C[A]] = new Parser(r => r[C, A](r[Int]))\n implicit val string : Parser[String] = new Parser(_.next())\n implicit val char : Parser[Char] = string.map(s => s.ensuring(_.length == 1, s\"Expected Char; found $s\").head)\n implicit val boolean : Parser[Boolean] = string.map(_.toBoolean)\n implicit val int : Parser[Int] = string.map(_.toInt)\n implicit val long : Parser[Long] = string.map(_.toLong)\n implicit val bigInt : Parser[BigInt] = string.map(BigInt(_))\n implicit val double : Parser[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Parser[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Parser, B: Parser] : Parser[(A, B)] = new Parser(r => (r[A], r[B]))\n implicit def tuple3[A: Parser, B: Parser, C: Parser] : Parser[(A, B, C)] = new Parser(r => (r[A], r[B], r[C]))\n implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser] : Parser[(A, B, C, D)] = new Parser(r => (r[A], r[B], r[C], r[D]))\n implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))\n}\n"}], "negative_code": [], "src_uid": "296560688b83b9b6de740568b8deffd1"} {"source_code": "object HCC2018B1 extends App {\n\n import java.io.PrintWriter\n import java.util.Scanner\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve = {\n out.println(new Array[Int]((in.nextInt-1) * 2).map(_ => in.nextInt).groupBy(x => x).filter(_._2.length == 1).size)\n }\n\n solve\n out.flush\n out.close\n}", "positive_code": [{"source_code": "\nobject MaximumControlB1 extends App {\n import java.io.{InputStream, PrintStream}\n import java.util.Scanner\n solve(System.in,System.out)\n def solve(in: InputStream, out: PrintStream): Unit = {\n val scanner = new Scanner(in)\n val n = scanner.nextInt()\n val a = Array.fill(n)(0)\n (1 until n).foreach{ _ =>\n val u = scanner.nextInt()\n val v = scanner.nextInt()\n a(u-1) += 1\n a(v-1) += 1\n }\n out.println(a.count(_ == 1))\n }\n}"}], "negative_code": [], "src_uid": "5d91e27798d38fc7924d1c407c07c99c"} {"source_code": "import scala.io.Source\r\nimport scala.math.log\r\n\r\nobject ACirnosPerfectBitmasksClassroom {\r\n def main(args: Array[String]): Unit = {\r\n val file = Source.stdin.getLines\r\n // val file = Source.fromString(\r\n // \"7\\n1\\n2\\n5\\n9\\n16\\n114514\\n1000000\"\r\n // ).getLines\r\n var t = file.next.toInt\r\n while (t > 0) {\r\n t -= 1\r\n val a = file.next.toInt\r\n val ub = (log(a) / log(2)).toInt\r\n val unitInd = (0 to ub).find(i => (a & (1 << i)) == 1 << i).get\r\n val res = if (a == 1) 3 else if (1 << unitInd != a) 1 << unitInd else (1 << unitInd) ^ 1\r\n println(res)\r\n }\r\n }\r\n}\r\n", "positive_code": [{"source_code": "import scala.io.Source\r\nimport scala.math.log\r\n\r\nobject ACirnosPerfectBitmasksClassroom {\r\n def main(args: Array[String]): Unit = {\r\n val file = Source.stdin.getLines\r\n// val file = Source.fromString(\r\n// \"7\\n1\\n2\\n5\\n9\\n16\\n114514\\n1000000\"\r\n// ).getLines\r\n var t = file.next.toInt\r\n while (t > 0) {\r\n t=t-1\r\n val a = file.next.toInt\r\n val ub = (log(a)/log(2)).toInt\r\n val unitInd = (0 to ub).find(i=> (a&(1<\n import java.util\n import java.util.Comparator\n val N = ni()\n val S = Array.ofDim[Pos](2 * N)\n REP(N) { i =>\n val l, r = ni() - 1\n S(i * 2) = Pos(i, l, 0)\n S(i * 2 + 1) = Pos(i, r, 1)\n }\n\n util.Arrays.sort(S, 0, S.length, new Comparator[Pos] {\n override def compare(o1: Pos, o2: Pos): Int = {\n if (o1.i != o2.i) Integer.compare(o1.i, o2.i)\n else Integer.compare(o1.tpe, o2.tpe) // open優先\n }\n })\n\n val ans = Array.ofDim[Int](N)\n var bal = 0\n var group = 1\n REP(2 * N) { i =>\n if (S(i).tpe == 0) bal += 1\n else bal -= 1\n ans(S(i).id) = group\n if (bal == 0) group = 2 // 最初にグループが区切れた場所で分割する\n }\n\n if (ans.forall(_ == 1)) out.println(-1)\n else out.println(ans.mkString(\" \"))\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "import java.util\nimport java.util.regex.Pattern\n\nimport scala.io.StdIn\nimport scala.util.Sorting\n\nobject Solution {\n //Console.setIn(new FileReader(new java.io.File(\"in\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n\n val magicMod = 1000000007\n\n class UnionFind(var size : Int){\n var parents = Array.ofDim[Int](size)\n var sizes = Array.ofDim[Int](size)\n\n for (i <- 0 until size) {\n parents(i) = i\n sizes(i) = 1\n }\n\n def findParent(node : Int): Int = {\n var p = node\n while (parents(p) != p) {\n parents(p) = parents(parents(p))\n p = parents(p)\n }\n parents(node) = p\n p\n }\n\n def merge(a : Int, b : Int): Unit = {\n var pA = findParent(a)\n var pB = findParent(b)\n\n if (pA == pB) {\n return\n }\n\n if (sizes(pA) < sizes(pB)) {\n parents(pB) = pA\n sizes(pA) += sizes(pB)\n } else {\n parents(pA) = pB\n sizes(pB) += sizes(pA)\n }\n }\n }\n\n def doCase(caseNo: Int): Unit = {\n val N = readInt()\n val segs = Array.fill(N)((0, 0, 0))\n\n var n = 0\n while (n < N) {\n val Array(l, r) = readIntLine()\n segs(n) = (l, r, n)\n n += 1\n }\n\n Sorting.quickSort(segs)\n\n val assignments = Array.fill(N)(0)\n val uf = new UnionFind(N)\n\n var i = 0\n while (i < N) {\n var j = i + 1\n while (j < N && segs(uf.findParent(i))._2 >= segs(j)._1) {\n val pi = uf.findParent(i)\n uf.merge(pi, j)\n val newParent = uf.findParent(i)\n segs(newParent) = (segs(pi)._1, Math.max(segs(pi)._2, segs(j)._2), segs(newParent)._3)\n\n j += 1\n }\n\n i = j\n }\n\n val roots = uf.parents.zipWithIndex.filter(a => a._1 == a._2).map(_._1)\n\n if (roots.length < 2) {\n println(-1)\n return\n }\n\n val firstSet = Set(roots.head)\n val secondSet = roots.tail.toSet\n\n for (((_, _, origIdx), sortedIdx) <- segs.zipWithIndex) {\n val cluster = uf.findParent(sortedIdx)\n if (firstSet.contains(cluster)) {\n assignments(origIdx) = 1\n } else if (secondSet.contains(cluster)) {\n assignments(origIdx) = 2\n } else {\n throw new RuntimeException()\n }\n }\n\n println(assignments.mkString(\" \"))\n }\n\n def main(args: Array[String]): Unit = {\n val noCases = readInt()\n for (i <- 0 until noCases) {\n doCase(i)\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n def readLongLine(): Array[Long] = {\n StdIn.readLine().split(\" \").map(_.toLong)\n }\n\n def readBigIntLine(): Array[BigInt] = {\n StdIn.readLine().split(\" \").map(BigInt.apply)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Pos(id: Int, i: Int, tpe: Int)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N = ni()\n val S = Array.ofDim[Pos](2 * N)\n REP(N) { i =>\n val l, r = ni() - 1\n S(i * 2) = Pos(i, l, 0)\n S(i * 2 + 1) = Pos(i, r, 1)\n }\n\n implicit val orderingPos: Ordering[Pos] = Ordering.by(a => (a.i, a.tpe)) // open優先\n Sorting.stableSort(S)\n\n val ans = Array.ofDim[Int](N)\n var bal = 0\n var group = 1\n REP(2 * N) { i =>\n if (S(i).tpe == 0) bal += 1\n else bal -= 1\n ans(S(i).id) = group\n if (bal == 0) group = 2 // 最初にグループが区切れた場所で分割する\n }\n\n if (ans.forall(_ == 1)) out.println(-1)\n else out.println(ans.mkString(\" \"))\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n case class Pos(id: Int, i: Int, tpe: Int)\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N = ni()\n val S = Array.ofDim[Pos](2 * N)\n REP(N) { i =>\n val l, r = ni() - 1\n S(i * 2) = Pos(i, l, 0)\n S(i * 2 + 1) = Pos(i, r, 1)\n }\n\n Sorting.quickSort(S)(Ordering.by(a => (a.i, a.tpe))) // open優先\n\n val ans = Array.ofDim[Int](N)\n var bal = 0\n var group = 1\n REP(N) { i =>\n if (S(i).tpe == 0) bal += 1\n else bal -= 1\n if (bal == 0) group = 2 // 最初にグループが区切れた場所で分割する\n ans(i) = group\n }\n\n if (group == 1) out.println(-1)\n else out.println(ans.mkString(\" \"))\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import java.util\nimport java.util.regex.Pattern\n\nimport scala.io.StdIn\nimport scala.util.Sorting\n\nobject Solution {\n //Console.setIn(new FileReader(new java.io.File(\"in\")))\n //Console.setOut(new PrintStream(new java.io.File(\"output\")))\n\n val magicMod = 1000000007\n\n def doCase(caseNo: Int): Unit = {\n val N = readInt()\n val segs = Array.fill(N)((0, 0, 0))\n\n var n = 0\n while (n < N) {\n val Array(l, r) = readIntLine()\n segs(n) = (l, r, n)\n n += 1\n }\n\n Sorting.quickSort(segs)\n\n val assignments = Array.fill(N)(0)\n\n var f, s = 0\n n = 0\n while (n < N) {\n val (l, r, sn) = segs(n)\n if (n == N - 1 && s == 0 || l <= f && l > s) {\n s = r\n assignments(n) = 2\n } else if (l > f) {\n f = r\n assignments(n) = 1\n } else {\n println(-1)\n return\n }\n n += 1\n }\n\n println(assignments.mkString(\" \"))\n }\n\n def main(args: Array[String]): Unit = {\n val noCases = readInt()\n for (i <- 0 until noCases) {\n doCase(i)\n }\n }\n\n def readIntLine(): Array[Int] = {\n StdIn.readLine().split(\" \").map(_.toInt)\n }\n\n def readLongLine(): Array[Long] = {\n StdIn.readLine().split(\" \").map(_.toLong)\n }\n\n def readBigIntLine(): Array[BigInt] = {\n StdIn.readLine().split(\" \").map(BigInt.apply)\n }\n}"}], "src_uid": "13fbcd245965ff6d1bf08915c4d2a2d3"} {"source_code": "object _1054C extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val n = io.read[Int]\n val l, r = io.read[Array, Int](n)\n val ans = Array.ofDim[Int](n)\n val toProcess = mutable.Set(ans.indices : _*)\n\n @tailrec\n def solve(iter: Int): Boolean = {\n val canFill = toProcess.filter(i => l(i) == 0 && r(i) == 0)\n canFill foreach {i =>\n ans(i) = iter\n toProcess -= i\n (0 until n) foreach {j => if(j < i) r(j) -= 1 else if (j > i) l(j) -= 1}\n }\n if (canFill.isEmpty) toProcess.isEmpty else solve(iter - 1)\n }\n\n if (solve(n)) io.writeLine(\"YES\").writeAll(ans) else io.writeLine(\"NO\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n", "positive_code": [{"source_code": "object _1054C extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val n = io.read[Int]\n val l, r = io.read[Array, Int](n)\n val ans = Array.ofDim[Int](n)\n val toProcess = mutable.Set(ans.indices : _*)\n\n def solve(iter: Int): Option[Seq[Int]] = {\n if (toProcess.isEmpty) {\n Some(ans)\n } else {\n val canFill = toProcess.filter(i => l(i) == 0 && r(i) == 0)\n if (canFill.isEmpty) {\n None\n } else {\n canFill foreach {i =>\n (0 until n).foreach(j => if(j < i) r(j) -= 1 else if (j > i) l(j) -= 1 else if (i == j) ans(i) = iter)\n toProcess -= i\n// debug(iter, i)\n// println(ans.mkString(\" \"))\n// println(l.mkString(\" \"))\n// println(r.mkString(\" \"))\n// println(\"----\")\n }\n solve(iter - 1)\n }\n }\n }\n\n solve(n) match {\n case Some(sol) => io.writeLine(\"YES\").writeAll(sol)\n case _ => io.write(\"NO\")\n }\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "fa531c38833907d619f1102505ddbb6a"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val t = in.next().toInt\n println((1 to t).map { i =>\n val data = (1 to 8).map(_ => in.next())\n if (i != t)\n in.next()\n val (xo1, yo1, xo2, yo2) = data.indices.foldLeft(-1, -1, -1, -1){\n case((x1, y1, x2, y2), j) if !data(j).contains('K') => (x1, y1, x2, y2)\n case((x1, y1, x2, y2), j) if data(j).indexOf('K') != data(j).lastIndexOf('K') =>\n (data(j).indexOf('K'), j, data(j).lastIndexOf('K'), j)\n case((-1, y1, x2, y2), j) =>\n (data(j).indexOf('K'), j, x2, y2)\n case((x1, y1, x2, y2), j) =>\n (x1, y1, data(j).indexOf('K'), j)\n }\n val dy = Math.abs(yo1 - yo2)\n val dx = Math.abs(xo1 - xo2)\n if (dy == 4 && dx == 4)\n \"YES\"\n else if (dy == 4 && dx == 0)\n \"YES\"\n else if (dy == 0 && dx == 4)\n \"YES\"\n else\n \"NO\"\n }.mkString(\"\\n\"))\n}\n", "positive_code": [{"source_code": "object A extends App {\n \n def canReach(i0: Int, j0: Int, i: Int, j: Int): Int = {\n val di = Math.abs(i - i0)\n val dj = Math.abs(j - j0)\n if (di % 2 != 0 || dj % 2 != 0 || (di + dj) % 4 != 0) -1\n else (Math.max(di, dj) / 2) % 2\n }\n\n val t = readInt\n var first = true\n \n for (test <- 0 until t) {\n if (!first) readLine\n first = false\n val board = Array.fill(8)(readLine)\n var i1, j1, i2, j2 = -1\n for (i <- 0 until 8; j <- 0 until 8; if board(i)(j) =='K') {\n if (i1 == -1) {\n i1 = i; j1 = j\n } else {\n i2 = i; j2 = j\n }\n } \n var ok = false\n for (i <- 0 until 8; j <- 0 until 8; if board(i)(j) !='#') {\n val cr1 = canReach(i1, j1, i, j)\n val cr2 = canReach(i2, j2, i, j)\n if (cr1 >= 0 && cr2 >= 0 && cr1 == cr2) ok = true\n }\n println(if (ok) \"YES\" else \"NO\")\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val t = in.next().toInt\n println((1 to t).map { i =>\n val data = (1 to 8).map(_ => in.next())\n if (i != t)\n in.next()\n val (xo1, yo1, xo2, yo2) = data.indices.foldLeft(-1, -1, -1, -1){\n case((x1, y1, x2, y2), j) if !data(j).contains('K') => (x1, y1, x2, y2)\n case((x1, y1, x2, y2), j) if data(j).indexOf('K') != data(j).lastIndexOf('K') =>\n (data(j).indexOf('K'), j, data(j).lastIndexOf('K'), j)\n case((-1, y1, x2, y2), j) =>\n (data(j).indexOf('K'), j, x2, y2)\n case((x1, y1, x2, y2), j) =>\n (x1, y1, data(j).indexOf('K'), j)\n }\n val dy = Math.abs(yo1 - yo2)\n val dx = Math.abs(xo1 - xo2)\n if (dy % 2 != 0 || dx % 2 != 0)\n \"NO\"\n else if (dy % 4 != dx % 4)\n \"NO\"\n else\n \"YES\"\n }.mkString(\"\\n\"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val t = in.next().toInt\n println((1 to t).map { i =>\n val data = (1 to 8).map(_ => in.next())\n val (xo1, yo1, xo2, yo2) = data.indices.foldLeft(-1, -1, -1, -1){\n case((x1, y1, x2, y2), j) if !data(j).contains('K') => (x1, y1, x2, y2)\n case((x1, y1, x2, y2), j) if data(j).indexOf('K') != data(j).lastIndexOf('K') => \n (data(j).indexOf('K'), j, data(j).lastIndexOf('K'), j)\n case((-1, y1, x2, y2), j) =>\n (data(j).indexOf('K'), j, x2, y2)\n case((x1, y1, x2, y2), j) =>\n (x1, y1, data(j).indexOf('K'), y2)\n }\n if ((xo1 - xo2) % 2 == 0 && (yo1 - yo2) % 2 == 0) \"YES\"\n else \"NO\"\n }.mkString(\"\\n\"))\n}\n//fpgzbvhheavymheheavyzmheavyavyebknkhheavyhsbqmmetheavyalmetalheavyyomtua"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val t = in.next().toInt\n (1 to t).map { i =>\n val data = (1 to 8).map(_ => in.next())\n val (xo1, yo1, xo2, yo2) = data.indices.foldLeft(-1, -1, -1, -1){\n case((x1, y1, x2, y2), j) if !data(j).contains('K') => (x1, y1, x2, y2)\n case((x1, y1, x2, y2), j) if data(j).indexOf('K') != data(j).lastIndexOf('K') => \n (data(j).indexOf('K'), j, data(j).lastIndexOf('K'), j)\n case((-1, y1, x2, y2), j) =>\n (data(j).indexOf('K'), j, x2, y2)\n case((x1, y1, x2, y2), j) =>\n (x1, y1, data(j).indexOf('K'), y2)\n }\n if ((xo1 - xo2) % 2 == 0 && (yo1 - yo2) % 2 == 0) \"YES\"\n else \"NO\"\n }\n}\n//fpgzbvhheavymheheavyzmheavyavyebknkhheavyhsbqmmetheavyalmetalheavyyomtua"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val t = in.next().toInt\n println((1 to t).map { i =>\n val data = (1 to 8).map(_ => in.next())\n if (i != t)\n in.next()\n val (xo1, yo1, xo2, yo2) = data.indices.foldLeft(-1, -1, -1, -1){\n case((x1, y1, x2, y2), j) if !data(j).contains('K') => (x1, y1, x2, y2)\n case((x1, y1, x2, y2), j) if data(j).indexOf('K') != data(j).lastIndexOf('K') =>\n (data(j).indexOf('K'), j, data(j).lastIndexOf('K'), j)\n case((-1, y1, x2, y2), j) =>\n (data(j).indexOf('K'), j, x2, y2)\n case((x1, y1, x2, y2), j) =>\n (x1, y1, data(j).indexOf('K'), y2)\n }\n val dy = Math.abs(yo1 - yo2)\n val dx = Math.abs(xo1 - xo2)\n if (dy % 2 != 0 || dx % 2 != 0)\n \"NO\"\n else if (dy % 4 != dx % 4)\n \"NO\"\n else\n \"YES\"\n }.mkString(\"\\n\"))\n}\n"}], "src_uid": "4f3bec9c36d0ac2fdb8041469133458c"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val mask = (1 << K) - 1\n\n val maxs = Array.fill[SegmentTree](1 << K)(new SegmentTree(N, -1e9.toInt - 10))\n\n def aggr(a: Array[Int], bit: Int) = {\n var sum = 0\n REP(K) { k =>\n val sign = if ((bit & 1 << k) > 0) 1 else -1\n sum += sign * a(k)\n }\n sum\n }\n\n def set(i: Int, a: Array[Int]) = {\n REP(1 << K) { bit =>\n maxs(bit).update(i, aggr(a, bit))\n }\n }\n\n REP(N) { i =>\n val a = na(K)\n set(i, a)\n }\n\n REP(ni()) { _ =>\n if (ni() == 1) {\n val i = ni() - 1\n val b = na(K)\n set(i, b)\n } else {\n val l, r = ni() - 1\n var mx = 0\n REP((1 << K) / 2) { bit =>\n maxs(bit).query(l, r + 1)\n val rev = ~bit & mask\n mx = max(mx, abs(maxs(bit).query(l, r) + maxs(rev).query(l, r)))\n }\n\n out.println(mx)\n }\n }\n }\n\n /**\n * @param n 個数 最大値じゃないぞ。\n * iの範囲は[0, n - 1]\n *\n * AがIntやLongのときは埋め込んでしまおう\n */\n class SegmentTree(n: Int, zero: Int) {\n import math.{max => f}\n\n private val N = {\n val a = Integer.highestOneBit(n)\n if (a == n) a else a << 1\n }\n private val dat: Array[Int] = if (zero != 0){\n Array.fill(2 * N)(zero)\n } else {\n Array.ofDim(2 * N)\n }\n\n def update(i: Int, a: Int): Unit = {\n var ix = i + N\n dat(ix) = a\n while(ix > 1) {\n dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))\n ix >>= 1\n }\n }\n\n /**\n * [a, b]\n */\n def query(a: Int, b: Int): Int = {\n var res: Int = zero\n var left = a + N\n var right = b + N\n\n while(left <= right) {\n if ((left & 1) == 1) res = f(res, dat(left))\n if ((right & 1) == 0) res = f(res, dat(right))\n left = (left + 1) >> 1 // 右の子供なら右の親に移動\n right = (right - 1) >> 1 // 左の子供なら左の親に移動\n }\n\n res\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val mask = (1 << K) - 1\n\n val maxs = Array.fill[SegmentTree](1 << K)(new SegmentTree(N, -1e9.toInt - 10))\n\n def aggr(a: Array[Int], bit: Int) = {\n var sum = 0\n REP(K) { k =>\n val sign = if ((bit & 1 << k) > 0) 1 else -1\n sum += sign * a(k)\n }\n sum\n }\n\n def set(i: Int, a: Array[Int]) = {\n REP(1 << K) { bit =>\n maxs(bit).update(i, aggr(a, bit))\n }\n }\n\n REP(N) { i =>\n val a = na(K)\n set(i, a)\n }\n\n REP(ni()) { _ =>\n ni() match {\n case 1 =>\n val i = ni() - 1\n val b = na(K)\n set(i, b)\n case 2 =>\n val l, r = ni() - 1\n var mx = 0\n REP((1 << K) / 2) { bit =>\n maxs(bit).query(l, r + 1)\n val rev = ~bit & mask\n mx = max(mx, abs(maxs(bit).query(l, r) + maxs(rev).query(l, r)))\n }\n\n out.println(mx)\n }\n }\n }\n\n /**\n * @param n 個数 最大値じゃないぞ。\n * iの範囲は[0, n - 1]\n *\n * AがIntやLongのときは埋め込んでしまおう\n */\n class SegmentTree(n: Int, zero: Int) {\n import math.{max => f}\n\n private val N = {\n val a = Integer.highestOneBit(n)\n if (a == n) a else a << 1\n }\n private val dat: Array[Int] = if (zero != 0){\n Array.fill(2 * N)(zero)\n } else {\n Array.ofDim(2 * N)\n }\n\n def update(i: Int, a: Int): Unit = {\n var ix = i + N\n dat(ix) = a\n while(ix > 1) {\n dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))\n ix >>= 1\n }\n }\n\n /**\n * [a, b]\n */\n def query(a: Int, b: Int): Int = {\n var res: Int = zero\n var left = a + N\n var right = b + N\n\n while(left <= right) {\n if ((left & 1) == 1) res = f(res, dat(left))\n if ((right & 1) == 0) res = f(res, dat(right))\n left = (left + 1) >> 1 // 右の子供なら右の親に移動\n right = (right - 1) >> 1 // 左の子供なら左の親に移動\n }\n\n res\n }\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject G extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n case class MaxSegTree(as: Array[Int]) {\n\n val NEUTRAL = -10000000\n\n val n = as.length\n val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))\n build(1, 0, n - 1)\n\n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n build(v2, tl, tm)\n build(v2 + 1, tm + 1, tr)\n t(v) = Math.max(t(v2), t(v2 + 1))\n }\n }\n\n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n if (l > r) NEUTRAL\n else if (l == tl && r == tr) t(v)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n Math.max(query(l, Math.min(r, tm), v2, tl, tm),\n query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr))\n }\n }\n\n def update(pos: Int, newT: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n if (tl == tr) t(v) = newT\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n if (pos <= tm) update(pos, newT, v2, tl, tm)\n else update(pos, newT, v2 + 1, tm + 1, tr)\n t(v) = Math.max(t(v2), t(v2 + 1))\n }\n }\n\n }\n\n val Array(n, k) = readInts(2)\n\n val maxDim = (1 << k) - 1\n val zeros = Array.fill(n)(0)\n val maxSTs = Array.fill(maxDim + 1){ MaxSegTree(zeros) }\n\n val cs = Array.ofDim[Int](maxDim + 1, k)\n for (dim <- 0 to maxDim) {\n var j = 0\n while (j < k) {\n cs(dim)(j) = if ((dim & (1 << j)) > 0) -1 else 1\n j += 1\n }\n }\n\n val dimMirrors = Array.tabulate(maxDim + 1){ i =>\n val mirror = cs(i).map(- _)\n cs.indexWhere(_ sameElements mirror)\n }\n\n val as = Array.ofDim[Int](k)\n\n for (i <- 0 until n) {\n val tok = new java.util.StringTokenizer(readLine)\n var jj = 0\n while (jj < k) {\n as(jj) = tok.nextToken().toInt\n jj += 1\n }\n var dim = 0\n while (dim <= maxDim) {\n var dist = 0\n var j = 0\n while (j < k) {\n dist += cs(dim)(j) * as(j)\n j += 1\n }\n maxSTs(dim).update(i, dist)\n dim += 1\n }\n }\n\n val Array(q) = readInts(1)\n val res = ArrayBuffer.empty[Int]\n\n for (_ <- 1 to q) {\n val s = readLine\n if (s.head == '1') {\n val tok = new java.util.StringTokenizer(s)\n tok.nextToken()\n val i = tok.nextToken().toInt - 1\n var jj = 0\n while (jj < k) {\n as(jj) = tok.nextToken().toInt\n jj += 1\n }\n var dim = 0\n while (dim <= maxDim) {\n var dist = 0\n var j = 0\n while (j < k) {\n dist += cs(dim)(j) * as(j)\n j += 1\n }\n maxSTs(dim).update(i, dist)\n dim += 1\n }\n } else {\n val tok = new java.util.StringTokenizer(s)\n tok.nextToken()\n val l = tok.nextToken().toInt - 1\n val r = tok.nextToken().toInt - 1\n var max = 0\n var dim = 0\n while (dim <= maxDim) {\n val mirrorDim = dimMirrors(dim)\n val d = maxSTs(dim).query(l, r) + maxSTs(mirrorDim).query(l, r)\n if (d > max) max = d\n dim += 1\n }\n res += max\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.mkString(\"\\n\"))\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject G extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n\n case class MaxSegTree(as: Array[Int]) {\n\n val NEUTRAL = -10000000\n\n val n = as.length\n val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))\n build(1, 0, n - 1)\n\n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n build(v2, tl, tm)\n build(v2 + 1, tm + 1, tr)\n t(v) = Math.max(t(v2), t(v2 + 1))\n }\n }\n\n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n if (l > r) NEUTRAL\n else if (l == tl && r == tr) t(v)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n Math.max(query(l, Math.min(r, tm), v2, tl, tm),\n query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr))\n }\n }\n\n def update(pos: Int, newT: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n if (tl == tr) t(v) = newT\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n if (pos <= tm) update(pos, newT, v2, tl, tm)\n else update(pos, newT, v2 + 1, tm + 1, tr)\n t(v) = Math.max(t(v2), t(v2 + 1))\n }\n }\n\n }\n\n val Array(n, k) = readInts(2)\n\n val maxDim = BigInt(2).pow(k).toInt - 1\n val zeros = Array.fill(n)(0)\n val maxSTs = Array.fill(maxDim + 1){ MaxSegTree(zeros) }\n\n val cs = Array.ofDim[Int](maxDim + 1, k)\n for (dim <- 0 to maxDim) {\n var j = 0\n var dd = dim\n while (j < k) {\n val ddd = dd % 2\n cs(dim)(j) = if (ddd == 0) -1 else 1\n j += 1\n dd /= 2\n }\n }\n\n val dimMirrors = Array.tabulate(maxDim + 1){ i =>\n val mirror = cs(i).map(- _)\n cs.indexWhere(_ sameElements mirror)\n }\n\n val as = Array.ofDim[Int](k)\n\n for (i <- 0 until n) {\n val tok = new java.util.StringTokenizer(readLine)\n var jj = 0\n while (jj < k) {\n as(jj) = tok.nextToken().toInt\n jj += 1\n }\n var dim = 0\n while (dim <= maxDim) {\n var dist = 0\n var j = 0\n while (j < k) {\n dist += cs(dim)(j) * as(j)\n j += 1\n }\n maxSTs(dim).update(i, dist)\n dim += 1\n }\n }\n\n val Array(q) = readInts(1)\n val res = ArrayBuffer.empty[Int]\n\n for (_ <- 1 to q) {\n val s = readLine\n if (s.head == '1') {\n val tok = new java.util.StringTokenizer(s)\n tok.nextToken()\n val i = tok.nextToken().toInt - 1\n var jj = 0\n while (jj < k) {\n as(jj) = tok.nextToken().toInt\n jj += 1\n }\n var dim = 0\n while (dim <= maxDim) {\n var dist = 0\n var j = 0\n while (j < k) {\n dist += cs(dim)(j) * as(j)\n j += 1\n }\n maxSTs(dim).update(i, dist)\n dim += 1\n }\n } else {\n val tok = new java.util.StringTokenizer(s)\n tok.nextToken()\n val l = tok.nextToken().toInt - 1\n val r = tok.nextToken().toInt - 1\n var max = 0\n var dim = 0\n while (dim <= maxDim) {\n val mirrorDim = dimMirrors(dim)\n val d = maxSTs(dim).query(l, r) + maxSTs(mirrorDim).query(l, r)\n if (d > max) max = d\n dim += 1\n }\n res += max\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.mkString(\"\\n\"))\n Console.flush\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject G extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n case class MaxSegTree(as: Array[Int]) {\n\n val NEUTRAL = -10000000\n\n val n = as.length\n val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))\n build(1, 0, n - 1)\n\n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n build(v2, tl, tm)\n build(v2 + 1, tm + 1, tr)\n t(v) = Math.max(t(v2), t(v2 + 1))\n }\n }\n\n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n if (l > r) NEUTRAL\n else if (l == tl && r == tr) t(v)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n Math.max(query(l, Math.min(r, tm), v2, tl, tm),\n query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr))\n }\n }\n\n def update(pos: Int, newT: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n if (tl == tr) t(v) = newT\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n if (pos <= tm) update(pos, newT, v2, tl, tm)\n else update(pos, newT, v2 + 1, tm + 1, tr)\n t(v) = Math.max(t(v2), t(v2 + 1))\n }\n }\n\n }\n\n val Array(n, k) = readInts(2)\n\n val maxDim = BigInt(3).pow(k).toInt - 1\n val zeros = Array.fill(n)(0)\n val maxSTs = Array.fill(maxDim + 1){ MaxSegTree(zeros) }\n\n val cs = Array.ofDim[Int](maxDim + 1, k)\n for (dim <- 1 to maxDim) {\n var j = 0\n var dd = dim\n while (j < k) {\n val ddd = dd % 3\n cs(dim)(j) = if (ddd == 2) -1 else ddd\n j += 1\n dd /= 3\n }\n }\n\n val dimMirrors = Array.tabulate(maxDim + 1){ i =>\n val mirror = cs(i).map(- _)\n cs.indexWhere(_ sameElements mirror)\n }\n\n val as = Array.ofDim[Int](k)\n\n for (i <- 0 until n) {\n val tok = new java.util.StringTokenizer(readLine)\n var jj = 0\n while (jj < k) {\n as(jj) = tok.nextToken().toInt\n jj += 1\n }\n var dim = 1\n while (dim <= maxDim) {\n var dist = 0\n var j = 0\n while (j < k) {\n dist += cs(dim)(j) * as(j)\n j += 1\n }\n maxSTs(dim).update(i, dist)\n dim += 1\n }\n }\n\n val Array(q) = readInts(1)\n val res = ArrayBuffer.empty[Int]\n\n for (_ <- 1 to q) {\n val s = readLine\n if (s.head == '1') {\n val tok = new java.util.StringTokenizer(s)\n tok.nextToken()\n val i = tok.nextToken().toInt - 1\n var jj = 0\n while (jj < k) {\n as(jj) = tok.nextToken().toInt\n jj += 1\n }\n var dim = 1\n while (dim <= maxDim) {\n var dist = 0\n var j = 0\n while (j < k) {\n dist += cs(dim)(j) * as(j)\n j += 1\n }\n maxSTs(dim).update(i, dist)\n dim += 1\n }\n } else {\n val tok = new java.util.StringTokenizer(s)\n tok.nextToken()\n val l = tok.nextToken().toInt - 1\n val r = tok.nextToken().toInt - 1\n var max = 0\n var dim = 1\n while (dim <= maxDim) {\n val mirrorDim = dimMirrors(dim)\n val d = maxSTs(dim).query(l, r) - maxSTs(mirrorDim).query(l, r)\n if (d > max) max = d\n dim += 1\n }\n res += max\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.mkString(\"\\n\"))\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject G extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n case class MaxSegTree(as: Array[Int]) {\n\n val NEUTRAL = -10000000\n\n val n = as.length\n val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))\n build(1, 0, n - 1)\n\n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n build(v2, tl, tm)\n build(v2 + 1, tm + 1, tr)\n t(v) = t(v2) max t(v2 + 1)\n }\n }\n\n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n if (l > r) NEUTRAL\n else if (l == tl && r == tr) t(v)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n query(l, Math.min(r, tm), v2, tl, tm) max\n query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)\n }\n }\n\n def update(pos: Int, newT: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n if (tl == tr) t(v) = newT\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n if (pos <= tm) update(pos, newT, v2, tl, tm)\n else update(pos, newT, v2 + 1, tm + 1, tr)\n t(v) = t(v2) max t(v2 + 1)\n }\n }\n\n }\n\n case class MinSegTree(as: Array[Int]) {\n\n val NEUTRAL = 10000000\n\n val n = as.length\n val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))\n build(1, 0, n - 1)\n\n def build(v: Int, tl: Int, tr: Int) {\n if (tl == tr) t(v) = as(tl)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n build(v2, tl, tm)\n build(v2 + 1, tm + 1, tr)\n t(v) = t(v2) min t(v2 + 1)\n }\n }\n\n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {\n if (l > r) NEUTRAL\n else if (l == tl && r == tr) t(v)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n query(l, Math.min(r, tm), v2, tl, tm) min\n query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)\n }\n }\n\n def update(pos: Int, newT: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n if (tl == tr) t(v) = newT\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n if (pos <= tm) update(pos, newT, v2, tl, tm)\n else update(pos, newT, v2 + 1, tm + 1, tr)\n t(v) = t(v2) min t(v2 + 1)\n }\n }\n\n }\n\n val Array(n, k) = readInts(2)\n val maxDim = (1 << k) - 1\n val zeros = Array.fill(n)(0)\n val minSTs = Array.fill(maxDim + 1){ MinSegTree(zeros) }\n val maxSTs = Array.fill(maxDim + 1){ MaxSegTree(zeros) }\n\n for (i <- 0 until n) {\n val as = readInts(k)\n for (dim <- 1 to maxDim) {\n var dist = 0\n var j = 0\n while (j < k) {\n if ((dim & (1 << j)) > 0) dist += as(j)\n j += 1\n }\n minSTs(dim).update(i, dist)\n maxSTs(dim).update(i, dist)\n }\n }\n\n val Array(q) = readInts(1)\n val res = ArrayBuffer.empty[Int]\n\n for (_ <- 1 to q) {\n val s = readLine\n if (s.head == '1') {\n val tok = new java.util.StringTokenizer(s)\n tok.nextToken()\n val i = tok.nextToken().toInt - 1\n val as = Array.fill(k){ tok.nextToken().toInt }\n for (dim <- 1 to maxDim) {\n var dist = 0\n var j = 0\n while (j < k) {\n if ((dim & (1 << j)) > 0) dist += as(j)\n j += 1\n }\n minSTs(dim).update(i, dist)\n maxSTs(dim).update(i, dist)\n }\n } else {\n val tok = new java.util.StringTokenizer(s)\n tok.nextToken()\n val l = tok.nextToken().toInt - 1\n val r = tok.nextToken().toInt - 1\n var max = 0\n for (dim <- 1 to maxDim) {\n val d = maxSTs(dim).query(l, r) - minSTs(dim).query(l, r)\n if (d > max) max = d\n }\n res += max\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.mkString(\"\\n\"))\n Console.flush\n}\n"}], "src_uid": "6cf46b112d7a9cc4c19b1bb7b8452970"} {"source_code": "import io.StdIn._\nimport scala.collection.mutable\n\nimport scala.collection.mutable._\n\nobject Solution {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n def gao(x: Array[Int], v: Array[Int], t: Double): Boolean = {\n var l: Double = 0\n var r: Double = 1e9\n\n for (i <- x.indices) {\n l = Math.max(l, x(i) - v(i) * t)\n r = Math.min(r, x(i) + v(i) * t)\n }\n\n l <= r\n }\n\n def main(args: Array[String]) {\n val Array(n) = readInts(1)\n\n val x = readInts(n)\n val v = readInts(n)\n\n var l: Double = 0\n var r: Double = 1e9\n var ans: Double = 0\n\n while (Math.abs(l-r) / Math.max(1, l) > 1e-9) {\n val mid = (l + r) / 2\n\n //println(l + \" \" + r)\n\n if (gao(x, v, mid)) {\n ans = mid\n r = mid\n }\n else l = mid\n }\n\n println(ans)\n\n // Console.withOut(new java.io.BufferedOutputStream(Console.out))\n // println(res.mkString(\"\\n\"))\n // Console.flush\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject B extends App {\n val n = readLine.toInt\n\n val x = readLine.split(' ').map(_.toInt)\n val v = readLine.split(' ').map(_.toInt)\n\n def meet(t: Double): Boolean = {\n val (from, to) = (0 until n).foldLeft((Double.MinValue, Double.MaxValue)) {\n case ((begin, end), i) ⇒ (begin.max(x(i) - v(i) * t), end.min(x(i) + v(i) * t))\n }\n to >= from\n }\n\n def binSearch(a: Double, b: Double): Double = {\n val m = (a + b) / 2\n if ((b - a) / (b + 1) < 1e-9) m else if (meet(m)) binSearch(a, m) else binSearch(m, b)\n }\n\n val res = binSearch(0, 3e9)\n println(f\"$res%.9f\")\n}\n"}], "negative_code": [], "src_uid": "f13f27a131b9315ebbb8688e2f43ddde"} {"source_code": "\n\nobject C {\n def main(args: Array[String]) = {\n val data = readLine().split(' ').map(t => t.toInt)\n val n = data(0)\n val r: Long = data(1)\n val avg: Long = data(2)\n val goal = avg * n\n val exams = (1 to n).map(_ => {\n val ab = readLine.split(' ').map(t => t.toLong)\n (ab(0), ab(1))\n }).sortBy(e => e._2)\n var ans: Long = 0\n val sum = exams.foldLeft(0L)((sum, e) => sum + e._1)\n exams.foldLeft(sum)((acc, e) => {\n val add: Long = math.max(0L, math.min(r - e._1, goal - acc))\n ans += add * e._2\n acc + add\n })\n println(ans)\n }\n}", "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, r, avg) = in.next().split(\" \").map(_.toInt)\n val data = (1 to n).map{_ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt)\n (b, a)\n }.sorted\n val sum = data.map(_._2).foldLeft(0l)(_+_)\n val all = avg * 1l * n\n val t = data.foldLeft((sum, 0l)) {\n case((s, inc), el) if s >= all => (s, inc)\n case((s, inc), (b, a)) =>\n val need = all - s\n val referats = Math.min(need, r - a)\n (s + referats, inc + referats * b)\n }\n println(t._2)\n\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, r, avg) = readLongs(3)\n \n val as, bs = Array.ofDim[Long](n.toInt)\n\n for (i <- 0 until n.toInt) {\n var Array(a, b) = readInts(2)\n as(i) = a\n bs(i) = b\n }\n val abs = (bs zip as).sorted\n \n var need = avg * n - as.sum\n var cnt = 0L\n var i = 0\n\n while (need > 0) {\n val take = need min (r - abs(i)._2)\n cnt += take * abs(i)._1\n need -= take\n i += 1\n }\n \n println(cnt)\n}"}, {"source_code": "object P492C {\n\tdef convert(a: Array[Long]) : (Long, Long) = (a(0), a(1))\n\n\tdef pick(need: Long, max: Long, options: List[(Long, Long)]) : Long = {\n\t\tif (need < 1) {\n\t\t\t0\n\t\t} else {\n\t\t\tval points = math.min(need, max - options.head._1)\n\t\t\tval essays = points * options.head._2\n\t\t\tessays + pick(need - points, max, options.tail)\n\t\t}\n\t}\n\n\tdef main(args: Array[String]) {\n\t\tval lines = scala.io.Source.stdin.getLines.toList\n\t\tval Array(n, r, avg) = lines.head.split(\" \").map(_.toLong)\n\t\tval exams = lines.tail.map(_.split(\" \").map(_.toLong)).map(convert)\n\t\tval options = exams.filter(_._1 < r).sortBy(_._2)\n\t\tval points = n * avg - exams.map(_._1).sum\n\t\tprintln(pick(points, r, options))\n\t}\n}\n"}, {"source_code": "import java.io._\nimport java.util._\nimport java.util.StringTokenizer\n\nimport scala.util.Sorting\n\nobject Solution {\n\n class Pair(val first: Int, val second: Int) extends Comparable[Pair] {\n override def compareTo(p: Pair): Int = {\n if (first != p.first)\n return first - p.first\n return second - p.second\n }\n }\n\n def solve(in: FastScanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val max = in.nextInt()\n val avg: Long = in.nextLong()\n val want: Long = avg * n\n var have: Long = 0\n val a = new Array[Pair](n)\n for (i <- 0 until n) {\n val curr = in.nextInt()\n val cost = in.nextInt()\n have += curr\n a(i) = new Pair(cost, max - curr)\n }\n Sorting.quickSort(a)\n var res: Long = 0\n if (have > want)\n have = want\n for (i <- 0 until n) {\n val add: Long = Math.min(want - have, a(i).second)\n have += add\n res += add * a(i).first\n }\n out.println(res)\n }\n\n def main(args: Array[String]): Unit = {\n val in = new FastScanner(System.in)\n val out = new PrintWriter(System.out)\n solve(in, out)\n out.flush()\n }\n\n class FastScanner(val in: InputStream) {\n var st: StringTokenizer = null\n var br = new BufferedReader(new InputStreamReader(in))\n\n def next(): String = {\n while (st == null || !st.hasMoreTokens()) {\n val line = br.readLine()\n if (line == null)\n throw new IOException()\n st = new StringTokenizer(line)\n }\n return st.nextToken()\n }\n\n def nextInt(): Int = Integer.parseInt(next())\n\n def nextLong(): Long = java.lang.Long.parseLong(next())\n\n def close(): Unit = {\n br.close()\n }\n }\n\n}"}, {"source_code": "object Main extends App {\n val Array(n,r,avg) = readLine.split(\" \").map(_.toLong)\n val abi = (1L to n).map({ _ =>\n val Array(a,b) = readLine.split(\" \").map(_.toLong)\n (a,b)\n })\n val total = abi.map(_._1).sum\n val goal = n * avg\n if(total >= goal) {\n println(\"0\")\n } else {\n val diff = goal - total\n val abit = abi.sortBy(_._2)\n val (_, counter) = abi.sortBy(_._2).foldLeft((diff, 0L))({\n case ((0L, count), _) => (0L, count)\n case ((d, count), (a, b)) => {\n val available = r - a\n if(d >= available) {\n ((d-available), count + available*b)\n } else {\n (0L, count + d*b)\n }\n }\n })\n println(counter)\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val Array(n, r, avg) = in.next().split(\" \").map(_.toInt)\n val data = (1 to n).map{_ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt)\n (b, a)\n }.sorted\n val sum = data.map(_._2).sum\n val t = data.foldLeft((sum, 0)) {\n case((s, inc), el) if s >= avg * n => (s, inc)\n case((s, inc), (b, a)) =>\n val need = avg * n - s\n val referats = Math.min(need, r - a)\n (s + referats, inc + referats * b)\n }\n println(t._2)\n\n}"}, {"source_code": "import scala.collection._\n\nobject C extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, r, avg) = readInts(3)\n \n val as, bs = Array.ofDim[Int](n)\n\n for (i <- 0 until n) {\n var Array(a, b) = readInts(2)\n as(i) = a\n bs(i) = b\n }\n val abs = (bs zip as).sorted\n \n var need = avg * n - as.sum\n var cnt = 0\n var i = 0\n\n while (need > 0) {\n val take = need min (r - abs(i)._2)\n cnt += take * abs(i)._1\n need -= take\n i += 1\n }\n \n println(cnt)\n}"}, {"source_code": "\n\nobject C {\n def main(args: Array[String]) = {\n val data = readLine().split(' ').map(t => t.toInt)\n val n = data(0)\n val r: Long = data(1)\n val avg: Long = data(2)\n val goal = avg * n\n val exams = (1 to n).map(_ => {\n val ab = readLine.split(' ').map(t => t.toLong)\n (ab(0), ab(1))\n }).sortBy(e => e._2)\n var ans: Long = 0\n val sum = exams.foldLeft(0L)((sum, e) => sum + e._1)\n exams.foldLeft(sum)((acc, e) => {\n val add: Long = math.min(r - e._1, goal - acc)\n ans += add * e._2\n acc + add\n })\n println(ans)\n }\n}"}, {"source_code": "object P492C {\n\tdef convert(a: Array[Int]) : (Int, Int) = (a(0), a(1))\n\n\tdef pick(need: Int, max: Int, options: List[(Int, Int)]) : Int = {\n\t\tif (need < 1) {\n\t\t\t0\n\t\t} else {\n\t\t\tval points = math.min(need, max - options.head._1)\n\t\t\tval essays = points * options.head._2\n\t\t\tessays + pick(need - points, max, options.tail)\n\t\t}\n\t}\n\n\tdef main(args: Array[String]) {\n\t\tval lines = scala.io.Source.stdin.getLines.toList\n\t\tval Array(n, r, avg) = lines.head.split(\" \").map(_.toInt)\n\t\tval exams = lines.tail.map(_.split(\" \").map(_.toInt)).map(convert)\n\t\tval options = exams.filter(_._1 < r).sortBy(_._2)\n\t\tval points = n * avg - exams.map(_._1).sum\n\t\tprintln(pick(points, r, options))\n\t}\n}\n"}, {"source_code": "object Main extends App {\n val Array(n,r,avg) = readLine.split(\" \").map(_.toLong)\n val abi = (1L to n).map({ _ =>\n val Array(a,b) = readLine.split(\" \").map(_.toLong)\n (a,b)\n })\n val total = abi.map(_._1).sum\n val goal = n * avg\n if(total >= goal) {\n println(\"0\")\n } else {\n val diff = goal - total\n val abit = abi.sortBy(_._2)\n val (_, counter) = abi.sortBy(_._2).foldLeft((diff, 0L))({\n case ((0L, count), _) => (0L, count)\n case ((d, count), (a, b)) => {\n val available = r - a\n if(d >= available) {\n ((d-available), count + available*b)\n } else {\n (0L, count + (available-d)*b)\n }\n }\n })\n println(counter)\n }\n}"}], "src_uid": "55270ee4e6aae7fc0c9bb070fcbf5560"} {"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._\nimport scala.math.Ordering.Implicits._\n\nobject _595B extends CodeForcesApp {\n override type Result = Long\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val (n, k) = (nextInt(), nextInt())\n val blocks = n/k\n val as = Seq.fill(blocks)(nextLong())\n val bs = Seq.fill(blocks)(nextLong())\n val maxBlock = pow(10, k)\n val p = maxBlock/10\n\n var ans = 1L\n for {\n (a, b) <- as zip bs\n } {\n val t1 = numberOfMultiples(0, maxBlock - 1, a)\n val t2 = numberOfMultiples(b*p, ((b+1)*p) - 1, a)\n val t = t1 - t2\n //debug(a, b, b*p, ((b+1)*p) - 1, t1, t2)\n ans = (ans * t) % mod\n }\n ans\n }\n\n def pow(a: Int, b: Int): Long = {\n var ans = 1L\n repeat(b) {\n ans *= a\n }\n ans\n }\n\n /**\n * @return number of multiples of c in [a,b]\n */\n def numberOfMultiples(a: Long, b: Long, c: Long): Long = {\n implicit def toInt(x: Boolean): Long = if (x) 1L else 0L\n c.signum match {\n case -1 => numberOfMultiples(a, b, -c)\n case 1 if b >= a => (b + (b < 0))/c - (a - (a > 0))/c + (a <= 0 && b >= 0)\n case _ => 0\n }\n }\n\n def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n\n override def format(result: Result) = super.format(result)\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n", "positive_code": [{"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n, k) = readInts(2)\n val nk = n / k\n val as = readInts(nk)\n val bs = readInts(nk)\n //val as = Array.fill(nk)(4564654)\n //val bs = Array.fill(nk)(5)\n \n val mul = BigInt(10).pow(k - 1)\n val MOD = 1000000007L\n val MODB = BigInt(MOD)\n var res = 1L\n \n for (i <- 0 until nk) {\n val r = if (bs(i) == 0) (10 * mul - 1) / as(i) - (mul - 1) / as(i)\n else 1 + (bs(i) * mul - 1) / as(i) + (10 * mul - 1) / as(i) - ((bs(i) + 1) * mul - 1) / as(i)\n res = (r % MODB).toLong * res % MOD\n }\n\n println(res % MOD)\n}\n"}], "negative_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util._\nimport scala.math.Ordering.Implicits._\n\nobject _595B extends CodeForcesApp {\n override type Result = Int\n\n override def solve(scanner: Scanner) = {\n import scanner._\n val (n, k) = (nextInt(), nextInt())\n val blocks = n/k\n val as = Seq.fill(blocks)(nextInt())\n val bs = Seq.fill(blocks)(nextInt())\n val maxBlock = pow(10, k)\n val p = maxBlock/10\n\n var ans = 1\n for {\n (a, b) <- as zip bs\n } {\n val t1 = numberOfMultiples(0, maxBlock - 1, a)\n val t2 = numberOfMultiples(b*p, ((b+1)*p) - 1, a)\n val t = t1 - t2\n //debug(a, b, b*p, ((b+1)*p) - 1, t1, t2)\n ans = (ans * t) % mod\n }\n ans\n }\n\n def pow(a: Int, b: Int) = {\n var ans = 1\n repeat(b) {\n ans *= a\n }\n ans\n }\n\n /**\n * @return number of multiples of c in [a,b]\n */\n def numberOfMultiples(a: Int, b: Int, c: Int): Int = {\n implicit def toInt(x: Boolean): Int = if (x) 1 else 0\n c.signum match {\n case -1 => numberOfMultiples(a, b, -c)\n case 1 if b >= a => (b + (b < 0))/c - (a - (a > 0))/c + (a <= 0 && b >= 0)\n case _ => 0\n }\n }\n\n def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)\n\n override def format(result: Result) = super.format(result)\n}\n/****************************[Ignore Template Below]****************************************/\nabstract class CodeForcesApp {\n final val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n final val mod: Int = 1000000007\n final val eps: Double = 1e-9\n type Result\n def solve(scanner: Scanner): Result\n def format(result: Result): String = result.toString\n def apply(scanner: Scanner): String = format(solve(scanner))\n def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))\n}\n/*********************************[Scala Scanner]*******************************************/\nimport java.io._\nimport java.nio.file.{Files, Path}\nimport java.util.StringTokenizer\n\nimport scala.io.Codec\n\n/**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/21125\n * All next methods throw NoSuchElementException when !hasNext\n */\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n def this(reader: Reader) = this(new BufferedReader(reader))\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n def this(str: String) = this(new StringReader(str))\n\n val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator\n\n private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n lines.next()\n }\n def lineNumber: Int = reader.getLineNumber\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n def nextString(): String = next()\n def nextChar(): Char = next().ensuring(_.length == 1).head\n def nextBoolean(): Boolean = next().toBoolean\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n def nextFloat(): Float = next().toFloat\n def nextDouble(): Double = next().toDouble\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n override def close() = reader.close()\n}\n"}], "src_uid": "dcb483886c81d2cc0ded065aa1e74091"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val T = ni()\n rep(T) { _ =>\n val L, v, l, r = ni()\n val all = L/v - 1 /v + (if (1 % v == 0) 1 else 0)\n val hidden = r/v - l/v + (if (l % v == 0) 1 else 0)\n out.println(all - hidden)\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}", "positive_code": [{"source_code": "object A extends App {\n\n def readInt1(): Int = scala.io.StdIn.readInt()\n\n val t = readInt1()\n\n def lamps(l: Int, r: Int, u:Int):Int = {\n r/u-(l-1)/u\n }\n\n for{i<-0 until t}{\n val line=scala.io.StdIn.readLine()\n val Array(_L,u,l,r)=line.split(\" \").map(_.toInt)\n println(lamps(1,_L,u)-lamps(l,r,u))\n }\n}\n"}, {"source_code": "object _1066A extends CodeForcesApp {\n import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._\n\n override def apply(io: IO): io.type = {\n val queries = io.read[Traversable[(Int, Int, Int, Int)]]\n val ans = queries map { case (n, v, l, r) => numberOfMultiples(1, n, v) - numberOfMultiples(l, r, v)}\n io.writeAll(ans, separator = \"\\n\")\n }\n\n def numberOfMultiples(a: Int, b: Int, c: Int): Int = (b + (b < 0))/c - (a - (a > 0))/c + (a <= 0 && b >= 0)\n implicit def toInt(x: Boolean): Int = if (x) 1 else 0\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\n/***********************************[Scala I/O]*********************************************/\nimport java.io._, java.util.StringTokenizer\nimport scala.collection.generic.CanBuild\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n tokenizers.headOption\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n\n object Read {\n implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "object A extends App {\n\n def readInt1(): Int = scala.io.StdIn.readInt()\n\n val t = readInt1()\n for{i<-0 until t}{\n val line=scala.io.StdIn.readLine()\n val Array(_L,u,l,r)=line.split(\" \").map(_.toInt)\n println(_L/u-(r-l+1))\n }\n}\n"}], "src_uid": "5194846a503c2087fcd299eaf3c20b2b"} {"source_code": "import java.util.StringTokenizer\n\nobject _545A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = (1 to n).map(i => (1 to n).map(j => next.toInt).toArray).toArray\n val ans = for {\n i <- 0 until n\n if (0 until n).filter(j => i != j).forall(j => i != j && (a(i)(j) & 1) == 0)\n } yield i\n\n println(ans.length)\n if (ans.length > 0) println(ans.map(i => i + 1).mkString(\" \"))\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\n/**\n * Created by tignatchenko on 07.09.2015.\n */\nobject z1 extends App {\n var n:Int = StdIn.readInt()\n var mtx = Array.ofDim[Int](n,n)\n var dd = new Array[Int](n)\n for (i<-0 until n) {\n mtx(i)= StdIn.readLine().split(\" \").map(Integer.parseInt)\n for(j<-0 until n) {\n val n = mtx(i)(j)\n if (n==1 || n==3) dd(i)+=1\n if (n==2 || n==3) dd(j)+=1\n }\n }\n println(dd.count(_==0))\n var k = 0;\n dd.foreach(x=>{\n k+=1\n if(x==0) print(k+\" \")\n \n })\n}\n"}, {"source_code": "import scala.io.StdIn\nobject z1 extends App {\n var dd = new Array[Int](StdIn.readInt())\n var k = 0\n (0 until dd.length).foreach(i=>StdIn.readLine().split(\" \").map(Integer.parseInt).foreach(n=>{ if (n==1 || n==3) dd(i)+=1 }))\n println(dd.count(_==0))\n dd.foreach(x=>{k+=1; if(x==0) print(k+\" \")})\n}\n"}, {"source_code": "object A545 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val mat = Array.fill(n)(readInts(n))\n var ret = Array.empty[Int]\n\n for(i <- 0 until n) {\n if(!mat(i).exists{x => (x == 1 || x == 3)}) {\n ret ++= Array(i+1)\n }\n }\n\n println(ret.length)\n println(ret.mkString(\" \"))\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "object A545 extends App {\n var mp = Map[Int, Int]()\n val n = readInt\n for(i <- 0 until n)\n {\n mp += (i -> 0)\n val row = readLine.split(' ').map(_.toInt)\n for(j <- 0 until n if i != j) {\n row(j)\n match\n {\n case 1 => mp += (i -> 1)\n case 2 => mp += (j -> 1)\n case 3 => mp += (i -> 1); mp += (i -> 1)\n case _ =>\n }\n }\n }\n\n val result = mp.filter(_._2 == 0).map(p => (p._1 + 1, p._2)).keys.toList\n if (result.isEmpty)\n print(0)\n else {\n println(result.size)\n println(result.sorted.mkString(\" \"))\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Array[Int]](n)\n val machines = new mutable.HashSet[Int]()\n for (i <- 0 until n) {\n a(i) = new Array[Int](n)\n machines.add(i)\n }\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n a(i)(j) = nextInt\n a(i)(j) match {\n case 1 => machines.remove(i)\n case 2 => machines.remove(j)\n case 3 => {\n machines.remove(i)\n machines.remove(j)\n }\n case _ =>\n }\n }\n }\n out.println(machines.size)\n val list = new Array[Int](machines.size)\n var ind = 0\n for (x <- machines) {\n list(ind) = (x + 1)\n ind += 1\n }\n list.sorted.foreach(x => out.print(x + \" \"))\n\n return 0\n }\n}"}, {"source_code": "object _545A extends CodeForcesApp {\n import scala.collection.mutable\n\n override type Input = List[List[Int]]\n override type Output = List[Int]\n\n override def read(scanner: java.util.Scanner) = {\n import scanner._\n val n = nextInt\n List.fill(n, n)(nextInt)\n }\n\n override def solve(input: Input) = {\n input.zipWithIndex flatMap {case (line, idx) =>\n when (!(line contains 1) && !(line contains 3)) {\n idx\n }\n }\n }\n\n override def format(result: Output) = s\"${result.length}${result.sorted.map(_ + 1).mkString(\"\\n\", \" \", \"\")}\"\n}\n\n/****************************** IGNORE BELOW *********************************/\nabstract class CodeForcesApp extends App {\n /********************************[ I/O ]************************************/\n import java.util.Scanner\n val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: Any): Unit = if (!isOnlineJudge) println(x)\n def apply(problem: String): String = apply(new Scanner(problem))\n def apply(scanner: Scanner): String = format(solve(read(scanner)))\n println(apply(new Scanner(System.in)))\n /********************************[ lib ]************************************/\n import scala.collection.mutable\n case class Memo[I <% K, K, O](f: I => O) extends (I => O) {\n val cache = mutable.Map.empty[K, O]\n override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))\n }\n type m_=>[I, O] = Memo[I, I, O]\n def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None\n /******************************[ solution ]*********************************/\n type Input\n type Output\n def read(scanner: Scanner): Input\n def solve(input: Input): Output\n def format(result: Output): String = result.toString\n def timeLimitSecond = 1\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]) {\n val n = StdIn.readInt();\n\n val bPerf = Array.fill[Boolean](n)(true);\n\n for(i <- 0 until n; nums = StdIn.readLine().split(\" \").map(Integer.parseInt);\n j <- 0 until n; num = nums(j)) {\n\n def setFalse(ind : Int*) = ind.foreach(bPerf(_) = false)\n\n num match {\n case -1 | 0 => ;\n case 1 => setFalse(i)\n case 2 => setFalse(j)\n case 3 => setFalse(i, j)\n }\n }\n\n val listPerf = bPerf.zipWithIndex.filter(_._1).map(_._2);\n\n println(listPerf.length);\n listPerf.foreach( x => print((x + 1) + \" \") )\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\n\nobject A extends App {\n val n = readInt()\n val Cars = Array.ofDim[Int](n, n)\n for (i <- 0 until n) {\n Cars(i) = readLine().split(\" \").map(_.toInt)\n }\n\n var answer = new ArrayBuffer[Int]()\n def solve() = {\n for (i <- 0 until n) {\n var turnedOver = false\n for (j <- 0 until n) {\n// println(s\"Consider $car1 vs $car2\")\n\n if (Cars(i)(j) == 1 || Cars(i)(j) == 3) {\n turnedOver = true\n }\n }\n\n if (!turnedOver) answer += i + 1\n }\n\n println(answer.size)\n if (answer.size > 0) println(answer.mkString(\" \"))\n }\n\n solve()\n}\n"}, {"source_code": "import scala.io.StdIn\nobject a extends App {\n val n = StdIn.readInt()\n val y = (1 to n).toSet -- (1 to n).map{\n i => StdIn.readLine().split(\" \").map(_.toInt).map{\n x => if (x==1 || x==3) Some(i) else None\n }.flatten\n }.flatten\n println(y.size)\n y.toList.sorted.foreach(x => print(x+\" \"))\n}\n"}, {"source_code": "import scala.io.StdIn._\n\n/**\n * Created by przemek on 19.05.15.\n */\nobject ToyCar {\n def main(args : Array[String]) = {\n val N = readInt()\n val A = Array.ofDim[Int](N,N)\n for (i <- 0 to N -1) {\n A(i) = readLine().split(\" \").map(_.toInt)\n }\n\n var c = 0\n val buf = scala.collection.mutable.ArrayBuffer.empty[Int]\n for(i <- 0 to N - 1)\n {\n var bad = false\n for( j <- 0 to N -1){\n if(A(i)(j) == 1 || A(i)(j)==3){\n bad = true\n }\n }\n\n if(!bad){\n c = c + 1\n buf += i+1\n }\n }\n println(c)\n println( buf.mkString(\" \"))\n// println(A.map(_.mkString(\" \")).mkString(\" \"))\n }\n}\n"}, {"source_code": "object Atest{\n //import scala.collection.mutable.PriorityQueue\n import scala.collection.mutable.ArrayBuffer\n import util.control.Breaks._\n import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}\n import java.util.{Locale, Scanner,StringTokenizer}\n class InputReader(val stream:InputStream ) {\n var st:StringTokenizer=new StringTokenizer(\"\")\n val reader=new BufferedReader(new InputStreamReader(stream), 32768);\n\n def next():String = {\n while (!st.hasMoreTokens()){\n val currentLine = reader.readLine\n st=new StringTokenizer(currentLine)\n }\n return st.nextToken\n }\n\n def nextInt():Int = {\n return next.toInt\n }\n\n def nextLong():Long = {\n \treturn next.toLong\n }\n def nextDouble:Double = {\n return next.toDouble\n }\n }\n\n def main(args: Array[String]){\n\n\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n //code starts here\n val n=nextInt\n val g=ArrayBuffer[Int]()\n for(i<-1 to n){\n var good=true\n for(_<- 0 until n){\n val k=nextInt\n if(k==1||k==3){\n good=false\n }\n }\n if(good){\n g+=i\n }\n }\n out.println(g.length)\n if(g.length>0){\n for(i<-g){\n out.print(i+\" \")\n }\n }\n\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "negative_code": [{"source_code": "\nobject A545 extends App {\n var mp = Map[Int, Int]()\n val n = readInt\n for(i <- 0 until n)\n {\n mp += (i -> 0)\n val row = readLine.split(' ').map(_.toInt)\n for(j <- 0 until n if i != j) {\n row(j)\n match\n {\n case 1 => mp += (i -> 1)\n case 2 => mp += (j -> 1)\n case 3 => mp += (i -> 1); mp += (i -> 1)\n case _ =>\n }\n }\n }\n\n val result = mp.filter(_._2 == 0).map(p => (p._1 + 1, p._2)).keys\n if (result.isEmpty)\n print(0)\n else\n println(result.mkString(\" \"))\n}\n"}, {"source_code": "\nobject A545 extends App {\n var mp = Map[Int, Int]()\n val n = readInt\n for(i <- 0 until n)\n {\n mp += (i -> 0)\n val row = readLine.split(' ').map(_.toInt)\n for(j <- 0 until n if i != j) {\n row(j)\n match\n {\n case 1 => mp += (i -> 1)\n case 2 => mp += (j -> 1)\n case 3 => mp += (i -> 1); mp += (i -> 1)\n case _ =>\n }\n }\n }\n\n val result = mp.filter(_._2 == 0).map(p => (p._1 + 1, p._2)).keys\n if (result.isEmpty)\n print(0)\n else {\n println(result.size)\n println(result.mkString(\" \"))\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util._\n\nimport scala.collection.mutable\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = return Integer.parseInt(next)\n\n def nextLong: Long = return java.lang.Long.parseLong(next)\n\n def nextDouble: Double = return java.lang.Double.parseDouble(next)\n\n class MultiHashSet[T <% Comparable[T]] {\n val map = new mutable.HashMap[T, Int]()\n\n def count(x: T): Int = {\n return map.getOrElse(x, 0)\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n class MultiTreeSet[T <% Comparable[T]] {\n val map = new TreeMap[T, Int]()\n\n def count(x: T): Int = {\n val res = map.get(x)\n if (res == null)\n return 0\n return res\n }\n\n def add(x: T): Unit = map.put(x, count(x) + 1)\n\n def first(): T = return map.firstKey()\n\n def last(): T = return map.lastKey()\n\n def remove(x: T): Boolean = {\n val prev = count(x)\n if (prev == 0)\n return false\n if (prev == 1) {\n map.remove(x)\n } else {\n map.put(x, prev - 1)\n }\n return true\n }\n }\n\n def solve: Int = {\n val n = nextInt\n val a = new Array[Array[Int]](n)\n val machines = new mutable.HashSet[Int]()\n for (i <- 0 until n) {\n a(i) = new Array[Int](n)\n machines.add(i)\n }\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n a(i)(j) = nextInt\n a(i)(j) match {\n case 1 => machines.remove(i)\n case 2 => machines.remove(j)\n case 3 => {\n machines.remove(i)\n machines.remove(j)\n }\n case _ =>\n }\n }\n }\n out.println(machines.size)\n for (x <- machines) {\n out.print((x + 1) + \" \")\n }\n return 0\n }\n}"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\n\nobject A extends App {\n val n = readInt()\n val Cars = Array.ofDim[Int](n, n)\n for (i <- 0 until n) {\n Cars(i) = readLine().split(\" \").map(_.toInt)\n }\n\n var answer = new ArrayBuffer[Int]()\n def solve() = {\n for (i <- 0 until n) {\n var turnedOver = false\n var car1 = i + 1\n for (j <- 0 until n) {\n var car2 = j + 1\n// println(s\"Consider $car1 vs $car2\")\n\n if (i != j && (Cars(i)(j) == 1 || Cars(i)(j) == 3)) {\n turnedOver = !turnedOver\n }\n }\n\n if (!turnedOver) answer += i + 1\n }\n\n println(answer.size)\n if (answer.size > 0) println(answer.mkString(\" \"))\n }\n\n solve()\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn._\n\nobject A extends App {\n val n = readInt()\n val Cars = Array.ofDim[Int](n, n)\n for (i <- 0 until n) {\n Cars(i) = readLine().split(\" \").map(_.toInt)\n }\n\n var answer = new ArrayBuffer[Int]()\n def solve() = {\n for (i <- 0 until n) {\n var turnedOver = false\n var car1 = i + 1\n for (j <- 0 until n) {\n var car2 = j + 1\n// println(s\"Consider $car1 vs $car2\")\n\n if (i != j && (Cars(i)(j) == 1 || Cars(i)(j) == 3)) {\n turnedOver = !turnedOver\n }\n }\n\n if (!turnedOver) answer += i + 1\n }\n\n println(answer.size)\n if (answer.size > 0) println(answer.mkString(\" \"))\n }\n\n if (n > 1) solve() else println(0)\n}\n"}, {"source_code": "import scala.io.StdIn\nobject a extends App {\n val n = StdIn.readInt()\n val y = (1 to n).toSet -- (1 to n).map{\n i => StdIn.readLine().split(\" \").map(_.toInt).map{\n x => List(if (x==1 || x==3) i)\n }.flatten\n }.flatten\n println(y.size)\n y.foreach(x => print(x+\" \"))\n}\n"}], "src_uid": "3fc0ac711b113fa98f41740536dad44f"} {"source_code": "import java.io.BufferedInputStream\nimport java.util.Scanner\n\nobject Main extends App {\n val inputReader = new Scanner(new BufferedInputStream(System.in))\n val T = inputReader.nextInt()\n @scala.annotation.tailrec\n def bestK(d: Int, bestSoFar: Int): Int = {\n val k = bestSoFar + 1\n if (k * (k + 1) < d) {\n bestK(d, k)\n } else {\n bestSoFar\n }\n }\n for (_ <- 0 until T) {\n val n = inputReader.nextInt()\n val d = inputReader.nextInt()\n val x = bestK(d, 1) - 1\n val minDays = Math.min(x + (d + x) / (x + 1), x + 1 + (d + x + 1) / (x + 2))\n if (minDays <= n) {\n println(\"YES\")\n } else {\n println(\"NO\")\n }\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) = {\n val t = readInt\n (0 until t).foreach((x) => f1)\n }\n def f1(): Unit = {\n val Array(n, d) = readLine.split(\" \").map(_.toInt)\n if (f2(n, d)) { println(\"YES\") } else { println(\"NO\") }\n }\n\n def f2(n: Long, d: Long): Boolean = {\n val x = bs(0, d, d)\n (x + (d + x) / (x + 1) <= n)\n }\n\n def bs(min: Long, max: Long, d: Long): Long = if (min + 1 >= max) min else {\n val mid = (min + max) / 2\n if (aux(mid, d)) bs(mid, max, d) else bs(min, mid, d)\n }\n\n def aux(x: Long, d: Long): Boolean = x < ((d + x) / (x + 1))\n }\n"}, {"source_code": "\n\n\n\n\n\n\n\n\n\n\n\nimport scala.io.StdIn._\nobject Main extends App {\n\n for (_ ← 0 until readInt) {\n val Array(n, d) = readLine.trim.split(' ').map(_.toInt)\n println(\n if ((0 to math.sqrt(d).toInt).exists(x ⇒ x + ((d + x) / (x + 1)) <= n)) \"YES\" else \"NO\"\n )\n }\n}"}, {"source_code": "object Main extends App {\n val t = new Adilbek\n t.run\n}\n\nclass Adilbek {\n def run() = {\n val t = scala.io.StdIn.readLine().toInt\n for(i <- 0 until t) {\n val test = scala.io.StdIn.readLine()\n calc(test)\n }\n }\n\n def calc(test:String):Unit = {\n val args = test.split(\" \").map(_.toInt)\n for(opt <- 0 to args(0)-1) {\n if( opt*opt + (1-args(0))*opt + (args(1) -args(0)) <= 0 ){\n println(\"YES\")\n return\n }\n }\n println(\"NO\")\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]) = {\n val t = readInt\n (0 until t).foreach((x) => f1)\n }\n def f1(): Unit = {\n val Array(n, d) = readLine.split(\" \").map(_.toInt)\n if (f2(n, d)) { println(\"YES\") } else { println(\"NO\") }\n }\n\n def f2(n: Long, d: Long): Boolean = {\n val x = bs(0, n, d)\n (x + (d + x) / (x + 1) <= n)\n }\n\n def bs(min: Long, max: Long, d: Long): Long = if (min + 1 >= max) min else {\n val mid = (min + max) / 2\n if (aux(mid, d)) bs(mid + 1, max, d) else bs(min, mid, d)\n }\n\n def aux(x: Long, d: Long): Boolean = x < ((d + x) / (x + 1))\n }\n"}, {"source_code": "object Main extends App {\n val t = new Adilbek\n t.run\n}\n\nclass Adilbek {\n def run() = {\n val t = scala.io.StdIn.readLine().toInt\n for(i <- 0 until t) {\n val test = scala.io.StdIn.readLine()\n calc(test)\n }\n }\n\n def calc(test:String):Unit = {\n val args = test.split(\" \").map(_.toInt)\n for(opt <- 0 to args(0)-1) {\n if( opt*opt + (1-args(0))*opt + (args(1) -args(0)) <= 0 ){\n println(\"TRUE\")\n return\n }\n }\n println(\"FALSE\")\n }\n}\n\n"}], "src_uid": "e65b2a81689bb13b90a02a9ccf1d4125"} {"source_code": "//package solutions\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\nimport scala.collection.mutable\n\n/**\n * @author traff\n */\n\n\nobject SolTaskA extends App {\n override def main(args: Array[String]): Unit = {\n val out = new PrintWriter(System.out)\n\n run(new Scanner(System.in), out)\n\n out.close()\n }\n\n def run(s: Scanner, out: PrintWriter): Unit = {\n\n\n val Array(v, r) = s.nextLine().split(\" \")\n\n out.println(s\"$v $r\")\n\n val n = s.nextLine().toInt\n\n\n val a = new Array[String](n)\n\n val map = new mutable.HashMap[String, Int]()\n\n val set = new mutable.HashSet[String]()\n\n set.add(r)\n set.add(v)\n map(r) = 0\n map(v) = 0\n\n\n\n for (i <- 1 to n) {\n val Array(v, r) = s.nextLine().split(\" \")\n a(i-1) = v\n map(r) = i\n set += v\n set += r\n }\n\n for (i <- 0 until n) {\n map.remove(a(i))\n set.remove(a(i))\n\n if (i >0) {\n var min = n\n var name = \"\"\n set.foreach(f => {\n val l = map.getOrElse(f, 0)\n if (l < min) {\n min = l\n name = f\n }\n })\n\n out.println(s\"${a(i)} $name\")\n }\n }\n\n val i = set.iterator\n\n out.println(s\"${i.next()} ${i.next()}\")\n }\n}\n", "positive_code": [{"source_code": "import collection.mutable.ListBuffer\n\nobject Serial {\n def main(args : Array[String]) {\n var ans = new ListBuffer[String]\n val tok = io.StdIn.readLine.split(\" \")\n var a = tok(0)\n var b = tok(1)\n val n = io.StdIn.readLine.toInt\n ans.append(a)\n ans.append(b)\n for (i<-1 to n) {\n val tok = io.StdIn.readLine.split(\" \")\n if (tok(0) == a) a = tok(1)\n else b = tok(1)\n ans.append(a)\n ans.append(b)\n }\n for (i<-0 to n) {\n println(ans(i*2).toString + \" \" + ans(i*2 + 1).toString)\n }\n }\n}\n"}, {"source_code": "import Utils._, annotation._, collection._, util._, control._, math.Ordering.Implicits._, Searching._\n\nobject _776A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val init = read[Seq, String](2)\n val replaces = read[Seq[(String, String)]]\n\n val ans = replaces.scanLeft(init) {\n case (curr, (from, to)) =>\n curr map {\n case `from` => to\n case x => x\n }\n }\n \n writeAll(ans.map(_.mkString(\" \")), separator = \"\\n\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n def readAll[A: IO.Read]: (Int, Vector[A]) = {\n val data = read[Vector[A]]\n (data.length, data)\n }\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "3c06e3cb2d8468e738b736a9bf88b4ca"} {"source_code": "//package codeforces.contest1102\n\nobject DoorsBreakingAndRepairing {\n def main(args: Array[String]): Unit = {\n val Array(n, x, y), seq = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n if (x > y) println(seq.length)\n else println((seq.count(_ <= x) + 1) / 2)\n\n }\n}\n", "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, X, Y = ni()\n val A = na(N)\n if (X > Y) {\n out.println(N)\n } else {\n val b = A.count(_ <= X)\n val ans = b / 2 + b % 2\n out.println(ans)\n }\n }\n\n\n def debug(as: Array[Boolean]): Unit = {\n System.err.println(as.map(x => if(x) \"1\" else \"0\").mkString)\n }\n\n def debug(as: Array[Int]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(as: Array[Long]): Unit = {\n System.err.println(as.mkString(\" \"))\n }\n\n def debug(s: String): Unit = {\n System.err.println(s)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n REP(n)(i => res(i) = f(i + offset))\n res\n }\n\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n REP(as.length)(i => s += as(i))\n s\n }\n\n def cumSum(as: Array[Int]) = {\n val cum = Array.ofDim[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}, {"source_code": "object CF_531_3_C {\n\n type In = (Int, Int, Int, Seq[Int])\n type Out = Int\n \n def solve(in: In): Out = {\n val (n, break, repair, as) = in\n\n if (break > repair) as.length\n else math.ceil(as.count(_ <= break)/2.0).toInt\n }\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, i.int, i.int, {i.nextLine; i.intSeq})\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}], "negative_code": [{"source_code": "object CF_531_3_C {\n\n type In = (Int, Int, Int, Seq[Int])\n type Out = Int\n \n def solve(in: In): Out = {\n val (n, break, repair, as) = in\n\n if (break > repair) as.length\n else divideCeil(as.count(_ <= break), 2)\n }\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Specify Input and Output formats on RHS here:\n\n def formatIn(i: Input): In = (i.int, i.int, i.int, {i.nextLine; i.intSeq})\n def formatOut(out: Out): String = out.toString\n\n// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Boilerplate & utility methods that don't change (so ignore): \n\n import java.util.Scanner\n import java.io.InputStream\n import language.implicitConversions\n \n def main(args: Array[String]): Unit = {\n val out = new java.io.PrintWriter(System.out)\n val resultStr = new Input(System.in).solveStr\n out.println(resultStr)\n out.close()\n }\n \n class Input(val sc: Scanner) {\n // This class is useful for convenience, and for mock stdin in test scripts\n // Remember to call nextLine to advance past the newline character (if required) before taking a whole line\n def this(i: InputStream) = this(new Scanner(i))\n def this(s: String) = this(new Scanner(s.stripMargin))\n def int = sc.nextInt()\n def long = sc.nextLong()\n def double = sc.nextDouble()\n def nextLine = sc.nextLine()\n def collect[T](f: String => T) = sc.nextLine().split(\" \").toVector.map(f)\n def intSeq = collect(_.toInt)\n def doubleSeq = collect(_.toDouble)\n def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty \n else sc.nextLine +: getLines\n def getLines(lineCount: Int) = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}\n def solveVal: Out = (solve _).tupled(formatIn(this))\n def solveStr: String = formatOut(solveVal)\n }\n\n // Ceiling division for Int & Long\n def divideCeil(a: Int, b: Int) = (a - 1)/b + 1\n def divideCeil(a: Long, b: Long) = (a - 1)/b + 1\n \n // A frequently used number in these comps\n val modulo = 1000000007\n\n // For convenience in test scripts, treat a String as an Input \n implicit def stringToInput(s: String): Input = new Input(s)\n // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)\n implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { \n def tupled: T => R = x => f(x) \n }\n}\n"}], "src_uid": "c173e2695562dfa1f603e6a925a2e1f3"} {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n if (str.contains('.')) {\n val first = str.takeWhile(_ != '.')\n val second = str.dropWhile(_ != '.').tail\n if (first.last == '9')\n println(\"GOTO Vasilisa.\")\n else if (second.head >= '5') {\n println(s\"${first.init}${(first.last + 1).toChar}\")\n } else {\n println(first)\n }\n } else {\n println(str)\n }\n}", "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P099A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n \n val num = sc.nextLine.toList\n val (ipart, fpart): (List[Char], List[Char]) = num span (_ != '.')\n\n val roundUp: List[Char] => List[Char] = xs => xs.init ::: List((xs.last + 1).toChar)\n\n if (ipart.last == '9') out.println(\"GOTO Vasilisa.\")\n else if (fpart == Nil || fpart.tail.head - '5' < 0) out.println(ipart.mkString)\n else out.println(roundUp(ipart).mkString)\n \n out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val str = readLine()\n val Array(i, f) = str.split(\"\\\\.\")\n \n if (i.last == '9') println(\"GOTO Vasilisa.\")\n else println (new java.math.BigDecimal(str).setScale(0, BigDecimal.RoundingMode.HALF_UP))\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next()\n if (str.contains('.')) {\n val first = str.takeWhile(_ != '.')\n val second = str.dropWhile(_ != '.').tail\n if (first.last == '9' && second.head >= '5')\n println(\"GOTO Vasilisa.\")\n else if (second.head >= '5') {\n println(s\"${first.init}${(first.last + 1).toChar}\")\n } else {\n println(first)\n }\n } else {\n println(str)\n }\n}"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport java.util.Arrays.binarySearch\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\n\n\nobject P099A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val num = sc.nextLine.toList\n\n def roundUp(ipart: List[Char]): Unit = {\n val endDigit = ipart.last\n if (endDigit == '9') out.println(\"GOTO Vasilisa.\")\n else {\n val e = (endDigit + 1).toChar\n val res = ipart.init ::: List(e)\n out.println(res.mkString)\n }\n }\n\n num.span(_ != '.') match {\n case (ipart, Nil) => out.println(num.mkString)\n case (ipart, '.' :: x :: xs) => if (x - '5' < 0) out.println(ipart.mkString)\n else roundUp(ipart)\n }\n\n out.close\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val str = readLine()\n val Array(i, f) = str.split(\"\\\\.\")\n \n println(i)\n \n if (i.last == '9') println(\"GOTO Vasilisa.\")\n else println (new java.math.BigDecimal(str).setScale(0, BigDecimal.RoundingMode.HALF_UP))\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(i, f) = readLine().split(\"\\\\.\")\n if (i.last == '9') println(\"GOTO Vasilisa.\")\n else {\n val num = BigDecimal(i + \".\" + f)\n println(num.setScale(0, BigDecimal.RoundingMode.HALF_UP))\n }\n }\n}"}], "src_uid": "3060ecad253a2b4d4fac39e91fcd6c95"} {"source_code": "import sun.management.counter.Counter\n\nimport scala.:+\nimport scala.+:\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn.readLong\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.util.Random\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val Array(_, k) = readInts()\n val a = readInts()\n val b = readInts()\n val c = a.zip(b).sortBy(_._1)\n\n def findAnswer(index: Int, currentRam: Int): Int = {\n if (index < c.length) {\n c(index) match {\n case (a, b) if a <= currentRam => findAnswer(index + 1, currentRam + b)\n case _ => currentRam\n }\n } else {\n currentRam\n }\n }\n\n println(findAnswer(0, k))\n }\n\n\n //=====Template=========\n def readInts(): Array[Int] = readLine().split(\" \").map(_.toInt)\n\n def readLongs(): Array[Long] = readLine().split(\" \").map(_.toLong)\n\n def readChars(): Array[Char] = readLine().toCharArray\n\n def asInt(b: Boolean) = if (b) 1 else 0\n\n class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {\n val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()\n seq.foreach { value => add(value) }\n\n def contains(value: T) = multiSet.contains(value)\n\n def max: T = multiSet.last._1\n\n def min: T = multiSet.head._1\n\n def add(value: T) = multiSet.get(value) match {\n case None => multiSet(value) = 1\n case Some(counter) => multiSet(value) = counter + 1\n }\n\n def remove(value: T) = multiSet.get(value) match {\n case None => None\n case Some(1) => multiSet.remove(value)\n case Some(counter) => multiSet(value) = counter - 1\n }\n }\n}\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class fenwick(n: Int) {\n val tree = new Array[Long](n+1)\n def query(ind: Int): Long = {\n var idx = ind\n var ans = 0L\n while (idx > 0) {\n ans += tree(idx)\n idx -= (idx & -idx)\n }\n return ans\n }\n def update(ind: Int, value: Long): Unit = {\n var idx = ind\n while (idx <= n) {\n tree(idx) += value\n idx += (idx & -idx)\n }\n }\n }\n\n case class pair(var a: Int, var b: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return (a).compareTo(that.a)\n }\n }\n\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n val rem = 1000000007\n val maxn = 200010\n val mapp = mutable.Map[pair, Int]()\n\n val t = readInt()\n\n for (tt <- 1 to t) {\n val n = readInt()\n val k = readInt()\n val arr = new Array[pair](n)\n for (i <- 0 until n) {\n arr(i) = pair(0, 0)\n arr(i).a = readInt()\n }\n for (i <- 0 until n) {\n arr(i).b = readInt()\n }\n quickSort(arr)\n var ans = k\n for (i <- 0 until n) {\n if (arr(i).a <= ans) {\n ans += arr(i).b\n }\n }\n writer.println(ans )\n\n def check(kk: Long, fi: Long): Boolean = {\n return false\n }\n def bs(st:Long, en:Long, fi:Long): Long = {\n if (en - st <= 1L) {\n if (check(st, fi))\n return st\n else\n return en\n }\n val mid = (st + en) / 2L\n if (check(mid, fi))\n return bs(st, mid, fi)\n else\n return bs(mid, en, fi)\n }\n }\n writer.flush()\n}"}], "negative_code": [], "src_uid": "168f2a740d21a3a916a9d560fbcffeb9"} {"source_code": "object Solution {\n\n import scala.math._\n\n def main(args: Array[String]) {\n\n val sc = new java.util.Scanner(System.in)\n\n val n = sc.nextInt()\n val cubes = Array.fill(n)(sc.nextInt())\n\n val init = Array.fill(n)(0)\n\n for (i <- 0 until n/2) {\n if (i%2 == 0) {\n init(i) = cubes(n-1-i)\n init(n-1-i) = cubes(i)\n }\n else {\n init(i) = cubes(i)\n init(n-1-i) = cubes(n-1-i)\n }\n }\n if (n%2 == 1) init((n-1)/2) = cubes((n-1)/2)\n println(init.mkString(\" \"))\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn\n\n/**\n * Created by dmitry on 05.02.17.\n */\nobject Main2 {\n def main(args: Array[String]) {\n val n: Int = StdIn.readInt() - 1\n val str: String = StdIn.readLine()\n val digits: Array[Int] = str.split(' ').toStream.map(_.toInt).toArray\n for (i <- 0 to n / 2) {\n if ((i + 1) % 2 != 0) {\n val tmp = digits(i)\n digits(i) = digits(n - i)\n digits(n - i) = tmp\n }\n }\n println(digits.mkString(\"\", \" \", \"\"))\n }\n}\n"}, {"source_code": "import io.StdIn.readLine\n\nobject TimofeyAndCubes extends App {\n \n val n = readLine().toInt\n val a = readLine.split(\" \").map(_.toInt)\n solve(n, a)\n println(a.mkString(\" \"))\n \n def solve (n: Int, a: Array[Int]) : Unit = {\n \n for (i <- 0 until n/2) {\n if (i == 0 || i % 2 == 0) {\n val tmp = a(i)\n a(i) = a(n - i - 1)\n a(n - i - 1) = tmp\n }\n }\n }\n}"}, {"source_code": "import Utils._, annotation._, collection._, util._, control._, math.Ordering.Implicits._, Searching._\n\nobject _764B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val a = read[Array[Int]]\n val n = a.length\n\n @tailrec\n def solve(i: Int): Unit = {\n val j = n - i - 1\n if (i <= j) {\n if (i%2 == 0) {\n val t = a(i)\n a(i) = a(j)\n a(j) = t\n }\n solve(i + 1)\n }\n }\n\n solve(0)\n\n writeAll(a)\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\n lazy val isOnlineJudge: Boolean = sys.props.get(\"ONLINE_JUDGE\").exists(_.toBoolean)\n def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)\n def apply(io: IO): io.type\n def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()\n}\nobject Utils {\n import scala.collection.mutable, mutable.{Map => Dict}\n implicit class GenericExtensions[A](val a: A) extends AnyVal {\n def in(set: collection.Set[A]): Boolean = set(a)\n def some: Option[A] = Some(a)\n def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a\n }\n implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {\n def onlyElement: A = assuming(t.size == 1)(t.head)\n def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)\n def duplicates(implicit b: C of A): C[A] = {\n val elems = mutable.Set.empty[A]\n (t collect {case i if !elems.add(i) => i}).to[C]\n }\n def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}\n def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)\n def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)\n def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]\n def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap\n def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t)) // e.g. grades.whenNonEmpty(_.max)\n def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}\n def toMutableMultiSet: Dict[A, Int] = {\n val c = map[A] to 0\n t.foreach(i => c(i) += 1)\n c\n }\n def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0\n def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)\n }\n implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)\n }\n implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {\n def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)\n }\n implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {\n def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t\n }\n implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {\n def key = p._1\n def value = p._2\n }\n implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {\n def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)\n def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])\n def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]\n }\n implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {\n def lastKeyOption: Option[K] = m.lastOption.map(_.key)\n def firstKeyOption: Option[K] = m.headOption.map(_.key)\n def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap\n def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}\n def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m\n def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776\n }\n implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {\n def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)\n def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)\n private def removeNode(kv: (K, V)): (K, V) = {\n m -= kv.key\n kv\n }\n }\n implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {\n def notContains(x: A): Boolean = !(s contains x)\n def toMutable = mutable.Set.empty[A] ++ s\n }\n implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {\n def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}\n def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)\n def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)\n def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}\n def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)\n }\n implicit class BooleanExtensions(val x: Boolean) extends AnyVal {\n def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero\n def toEnglish = if(x) \"YES\" else \"NO\"\n }\n implicit class IntExtensions(val x: Int) extends AnyVal {\n import java.lang.{Integer => JInt}\n def withHighestOneBit: Int = JInt.highestOneBit(x)\n def withLowestOneBit: Int = JInt.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)\n def bitCount: Int = JInt.bitCount(x)\n def setLowestBits(n: Int): Int = x | (left(n) - 1)\n def clearLowestBits(n: Int): Int = x & left(n, ~0)\n def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Int = x | left(i)\n def clearBit(i: Int): Int = x & ~left(i)\n def toggleBit(i: Int): Int = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)\n def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)\n }\n implicit class LongExtensions(val x: Long) extends AnyVal {\n import java.lang.{Long => JLong}\n def withHighestOneBitSet: Long = JLong.highestOneBit(x)\n def withLowestOneBitSet: Long = JLong.lowestOneBit(x)\n def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)\n def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)\n def bitCount: Int = JLong.bitCount(x)\n def setLowestBits(n: Int): Long = x | (left(n) - 1)\n def clearLowestBits(n: Int): Long = x & left(n, ~0L)\n def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)\n def setBit(i: Int): Long = x | left(i)\n def clearBit(i: Int): Long = x & ~left(i)\n def toggleBit(i: Int): Long = x ^ left(i)\n def testBit(i: Int): Boolean = ((x >> i) & 1) == 1\n private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)\n }\n implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {\n import Numeric.Implicits._\n def **(i: Int): A = if (i == 0) n.one else {\n val h = x ** (i/2)\n if (i%2 == 0) h * h else h * h * x\n }\n def distance(y: A) = (x - y).abs()\n def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)\n def whenNegative(f: => A): A = nonNegative getOrElse f //e.g. students indexOf \"Greg\" whenNegative Int.MaxValue\n }\n implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {\n import scala.collection.immutable.NumericRange, Integral.Implicits._\n def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x\n def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)\n def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)\n }\n implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))\n def desc[A: Ordering]: Ordering[A] = asc[A].reverse //e.g. students.sortBy(_.height)(desc)\n def asc[A](implicit order: Ordering[A]): Ordering[A] = order\n def map[K] = new {\n def to[V](default: => V): Dict[K, V] = using(_ => default)\n def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {\n override def apply(key: K) = getOrElseUpdate(key, f(key))\n }\n }\n def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]\n def memoize[A, B](f: A => B): A ==> B = map[A] using f\n implicit class FuzzyDouble(val x: Double) extends AnyVal {\n def >~(y: Double) = x > y + eps\n def >=~(y: Double) = x >= y + eps\n def ~<(y: Double) = y >=~ x\n def ~=<(y: Double) = y >~ x\n def ~=(y: Double) = (x distance y) <= eps\n }\n def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {\n val (xs, ys) = points.unzip\n new java.awt.Polygon(xs.toArray, ys.toArray, points.size)\n }\n def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {\n val shape = new java.awt.geom.GeneralPath()\n points.headOption foreach {case (x, y) => shape.moveTo(x, y)}\n points.tail foreach {case (x, y) => shape.lineTo(x, y)}\n shape.closePath()\n shape\n }\n def until(until: Int): Range = 0 until until\n def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}\n def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}\n @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None\n def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)\n type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]\n type ==>[A, B] = collection.Map[A, B]\n val mod: Int = (1e9 + 7).toInt\n val eps: Double = 1e-9\n}\n/***********************************[Scala I/O]*********************************************/\nimport Utils._, java.io._, java.util.StringTokenizer\n\nclass IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {\n def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))\n def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))\n\n private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered\n val printer = new PrintWriter(out, true)\n\n @inline private[this] def tokenizer() = {\n while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()\n when(tokenizers.nonEmpty)(tokenizers.head)\n }\n\n def read[A](implicit read: IO.Read[A]): A = read.apply(this)\n def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]\n\n def readTill(delim: String): String = tokenizer().get.nextToken(delim)\n def readTillEndOfLine(): String = readTill(\"\\n\\r\")\n\n override def next() = tokenizer().get.nextToken()\n override def hasNext = tokenizer().nonEmpty\n\n def write(obj: Any): this.type = {\n printer.print(obj)\n this\n }\n def writeLine(): this.type = {\n printer.println()\n this\n }\n def writeLine(obj: Any): this.type = {\n printer.println(obj)\n this\n }\n def writeAll(obj: Traversable[Any], separator: String = \" \"): this.type = write(obj mkString separator)\n def query[A: IO.Read](question: Any): A = writeLine(question).read\n\n override def flush() = printer.flush()\n def close() = {\n flush()\n in.close()\n printer.close()\n }\n}\nobject IO {\n class Read[A](val apply: IO => A) {\n def map[B](f: A => B): Read[B] = new Read(apply andThen f)\n }\n object Read {\n implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))\n implicit val string : Read[String] = new Read(_.next())\n implicit val char : Read[Char] = string.map(_.toTraversable.onlyElement)\n implicit val int : Read[Int] = string.map(_.toInt)\n implicit val long : Read[Long] = string.map(_.toLong)\n implicit val bigInt : Read[BigInt] = string.map(BigInt(_))\n implicit val double : Read[Double] = string.map(_.toDouble)\n implicit val bigDecimal : Read[BigDecimal] = string.map(BigDecimal(_))\n implicit def tuple2[A: Read, B: Read] : Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))\n implicit def tuple3[A: Read, B: Read, C: Read] : Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))\n implicit def tuple4[A: Read, B: Read, C: Read, D: Read] : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))\n implicit val boolean : Read[Boolean] = string map {s =>\n s.toLowerCase match {\n case \"yes\" | \"true\" | \"1\" => true\n case \"no\" | \"false\" | \"0\" => false\n case _ => s.toBoolean\n }\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "import java.util\n\nimport scala.io.StdIn\n\n/**\n * Created by dmitry on 05.02.17.\n */\nobject Main2 {\n def main(args: Array[String]) {\n var n: Int = (StdIn.readInt() - 1) / 2\n val str: String = StdIn.readLine()\n val digits: Array[Int] = str.split(' ').toStream.map(_.toInt).toArray\n while (n >= 0) {\n rev(digits, n, digits.length - 1 - n)\n n -= 1\n }\n println(util.Arrays.toString(digits))\n }\n\n def rev(ms: Array[Int], i: Int, j: Int): Unit = {\n var k: Int = i\n while (k < (j - i) / 2 + i) {\n val tmp = ms(k)\n ms(k) = ms(j - k + i)\n ms(j - k + i) = tmp\n k += 1\n }\n }\n}"}], "src_uid": "7d2f22fc06d4f0b8ff8be6c6862046e7"} {"source_code": "object Solution extends App {\n val data = scala.io.Source.stdin.getLines()\n data.next()\n val r = data.next().split(\" \").map(_.toInt).toSet\n println(Range(1, r.size + 2).find{i => !r.contains(i)}.get)\n}", "positive_code": [{"source_code": "object Template {\n\tdef main(args: Array[String]) {\n\t\tvar n = readLine.toInt\n\t\tvar books: Array[Boolean] = new Array[Boolean](n)\n\t\tvar input = readLine.split(' ').map(_.toInt)\n\t\tfor(i <- input){\n\t\t\tbooks(i-1) = true\n\t\t}\n\t\tfor(i <- 0 until books.length){\n\t\t\tif(!books(i)){\n\t\t\t\tprint(i+1)\n\t\t\t}\n\t\t}\n\t}\n}"}, {"source_code": "object Main extends App{\n val n = readLine().toInt\n val nums = readLine().split(\" \").map { _.toInt }\n println((1 to n).toList.diff(nums).head.toString)\n}"}, {"source_code": "import java.util.Scanner\n\nobject aa {\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n=sc.nextInt();\n var x: Long = 0\n for(i <- 1 to n-1){\n x+=sc.nextInt\n }\n val m:Long=n;\n print((m*(m+1))/2-x)\n }\n}"}, {"source_code": "object Devu {\n def main(args: Array[String]) {\n\t val n = readLine().toInt\n\t val d = readLine().split(\" \").map(_.toLong)\n\t var r = d.reduceLeft(_ ^ _)\n\t var k = 0\n\t var z = n\n\t while (z > 0) {\n\t k += 1\n\t z >>= 1\n\t }\n\t var mx = 1 << k\n\t if (mx < n){\n\t mx <<= 1\n\t }\n\t for (z <- (n + 1) until mx){\n\t r = r ^ z\n\t }\n\t println(r)\n }\n}"}], "negative_code": [{"source_code": "object Devu {\n def main(args: Array[String]) {\n\t val n = readLine().toInt\n\t val d = readLine().split(\" \").map(_.toLong)\n\t var r = d.reduceLeft(_ ^ _)\n\t val mx = 1 << (math.log(n).toInt + 2)\n\t for (z <- (n + 1) until mx){\n\t r = r ^ z\n\t }\n\t println(r)\n }\n}"}, {"source_code": "object Main extends App {\n println(\"Hello!\")\n}"}, {"source_code": "object Main extends App{\n val input = readLine() +\"\\r\\n\"+ readLine() \n TR10A.func(input)\n}\n\nobject TR10A extends Example {\n def func(input: String): String = {\n val lines = input.lines.toList\n val n = lines.head.toInt\n val nums = lines(1).split(\" \").map { _.toInt }\n (1 to n).toList.diff(nums).head.toString\n }\n def exs =\n Example(\"\"\"10\n3 8 10 1 7 9 6 5 2\"\"\", \"4\") :: Nil\n}\n\ntrait Contents {\n def func(input: String): String\n}\n\ntrait Example extends Contents {\n def exs: List[Example]\n case class Example(input: String, output: String)\n def results = exs.map { ex => func(ex.input) }\n def check =\n assert(exs.forall { case Example(input, output) => func(input) == output })\n /* def samples: String\n def makeExample(is: Int, os: Int): List[Example] = {\n val lines = samples.split(\"\\n\").toList\n lines\n .grouped(is + os + 2).toList\n .map { _.splitAt(is + 1) }\n .map { case (input, output) => Example(input.drop(1).mkString(\"\\n\"), output.drop(1).mkString(\"\\n\")) }\n } \n */\n\n}\n"}, {"source_code": "object Main extends App{\n val n = readLine().toInt\n val nums = readLine().split(\" \").map { _.toInt }\n (1 to n).toList.diff(nums).head.toString\n}"}, {"source_code": "import java.util.Scanner\n\nobject aa {\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n=sc.nextInt\n var x: Int = 0\n for(i <- 1 to n-1){\n x+=sc.nextInt\n }\n print((n*(n+1))/2-x)\n }\n}"}, {"source_code": "import java.util.Scanner\n\nobject aa {\n def main(args: Array[String]) {\n val sc = new Scanner(System.in)\n val n=sc.nextInt();\n var x: Int = 0\n for(i <- 1 to n-1){\n x+=sc.nextInt\n }\n val m:Long=n;\n print((m*(m+1))/2-x)\n }\n}"}], "src_uid": "0e4ff955c1e653fbeb003987fa701729"} {"source_code": "// CodeForces 18B\n\nobject Platforms extends App {\n val ln = (Console.readLine()).split(\" \") map (_.toInt)\n val n = ln(0)\n val d = ln(1)\n val m = ln(2)\n val l = ln(3)\n \n var p = 0L\n var cont = true\n while(cont) {\n val nn = p / m\n val oo = p % m\n if (nn >= n || oo > l) {\n cont = false\n } else {\n if (oo + 3*d < l) {\n p += ((l - oo)/d)*d\n } else {\n p += d\n }\n }\n }\n println(p)\n}\n\n// 3 6 6 3 ", "positive_code": [{"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var Array(n, d, m, l) = readLine.split(\" \").map(e => e.toLong);\n var x: Long = 0;\n var p = ArrayBuffer[(Long, Long)](); \n for (k <- 1 to n.toInt) {\n var x1 = (k - 1) * m;\n var x2 = (k - 1) * m + l\n p.append((x1, x2));\n }\n for (i <- 0 until p.length - 1) {\n var c: Long = (p(i)._2 - x) / d\n x += c * d;\n if (x + d < p(i + 1)._1) {\n println(x + d);\n return;\n }\n }\n var c: Long = x + ((p.last._2 - x) / d) * d + d\n println(c);\n }\n\n}"}, {"source_code": "import java.util._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextLong\n val d = nextLong\n val m = nextLong\n val l = nextLong\n var pos: Long = 1L * d\n while (pos % m <= l && pos / m < n) {\n val num = pos / m\n val jumps = (num * m + l - pos) / d\n if (jumps == 0) {\n pos += d\n } else {\n pos += jumps * d\n }\n }\n out.println(pos)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}], "negative_code": [{"source_code": "import java.util._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val d = nextInt\n val m = nextInt\n val l = nextInt\n for (i <- 1 to n) {\n if (i * d % m > l) {\n out.println(i * d)\n return 1\n }\n }\n out.println((n - 1) * m + l + 1)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.util._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n val d = nextInt\n val m = nextInt\n val l = nextInt\n for (i <- 1 to n) {\n if (i * d % m > l) {\n out.println(i * d)\n return 1\n }\n }\n out.println(n * d)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.util._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextLong\n val d = nextLong\n val m = nextLong\n val l = nextLong\n for (i <- 1 to n.toInt) {\n if (i.toLong * d % m > l) {\n out.println(i * d)\n return 1\n }\n }\n out.println(n * d)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.util._\nimport java.lang._\nimport java.io._\n\nobject B {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return Long.parseLong(next)\n }\n\n def fallInto(k: Int, m: Int, l: Int, pos: Int): Boolean = {\n if ((pos > (k - 2) * m + l && pos < (k - 1) * m) || (pos > (k - 1) * m + l && pos < k * m))\n return true\n return false\n }\n\n def solve: Int = {\n val n = nextInt\n val d = nextInt\n val m = nextInt\n val l = nextInt\n var pos = 0\n for (i <- 1 to n) {\n pos += d\n if (fallInto(i, m, l, pos)) {\n out.println(pos)\n return 1\n }\n }\n out.println(pos)\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "// CodeForces 18B\n\nobject Platforms extends App {\n val ln = (Console.readLine()).split(\" \") map (_.toInt)\n val n = ln(0)\n val d = ln(1)\n val m = ln(2)\n val l = ln(3)\n \n var p = 0L\n var cont = true\n while(cont) {\n val nn = p / m\n val oo = p % m\n if (nn > n || oo > l) {\n cont = false\n } else {\n p += d\n }\n }\n println(p)\n}\n\n"}, {"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var Array(n, d, m, l) = readLine.split(\" \").map(_.toInt);\n var x = 0;\n var p = ArrayBuffer[(Int, Int)](); \n for (k <- 1 to n) {\n var x1 = (k - 1) * m;\n var x2 = (k - 1) * m + l\n p.append((x1, x2));\n }\n for (i <- 0 until p.length - 1) {\n var c = (p(i)._2 - x) / d\n x += c * d;\n if (x + d < p(i + 1)._1) {\n println(x + d);\n return;\n }\n }\n }\n\n}"}, {"source_code": "import scala.io._\nimport scala.collection.mutable._\nimport java.util.StringTokenizer\n\nobject HelloWorld {\n\n def main(args: Array[String]): Unit = {\n var Array(n, d, m, l) = readLine.split(\" \").map(_.toInt);\n var x = 0;\n var p = ArrayBuffer[(Int, Int)](); \n for (k <- 1 to n) {\n var x1 = (k - 1) * m;\n var x2 = (k - 1) * m + l\n p.append((x1, x2));\n }\n for (i <- 0 until p.length - 1) {\n var c = (p(i)._2 - x) / d\n x += c * d;\n if (x + d < p(i + 1)._1) {\n println(x + d);\n return;\n }\n }\n println(x + ((p.last._2 - x) / d) * d + d);\n }\n\n}"}], "src_uid": "ecbc339ad8064681789075f9234c269a"} {"source_code": "import java.util.Scanner\nimport scala.collection.mutable._\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n, k = sc.nextInt()\n\n val a = input(n).toArray\n\n val m = Map[Int, Int]().withDefault(_ => 0)\n\n for (i <- 1 until (a.size - 1)) {\n if (a(i - 1) != a(i + 1)) m(a(i)) += 1\n else m(a(i)) += 2\n }\n\n m(a.last) += 1\n m(a.head) += 1\n\n val ans = m reduce { (A, B) =>\n if (A._2 > B._2) A\n else if (A._2 == B._2 && A._1 < B._1) A\n else B\n }\n\n println(ans._1)\n\n def input(n: Int, result: List[Int] = Nil): List[Int] = {\n if (n == 0) result.reverse\n else {\n val q = sc.nextInt()\n if (result.headOption == Some(q)) input(n - 1, result)\n else input(n - 1, q :: result)\n }\n }\n}\n", "positive_code": [{"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\n\nobject test6 extends App {\n val Array(n,k)=readLine.split(\" \").map(_.toInt)\n val arr=readLine.split(\" \").map(_.toInt)\n val ab=ArrayBuffer[Int]()\n ab+=arr(0)\n for(i<-1 until n) if(arr(i)!=arr(i-1)) ab+=arr(i)\n \n var dp=new Array[Int](k+1)\n for(i<-1 until ab.length-1){\n if(ab(i-1)!=ab(i+1))\n dp(ab(i))+=1\n else\n dp(ab(i))+=2\n }\n dp(ab.head)+=1\n dp(ab.last)+=1\n \n println(dp.indexOf(dp.max))\n} \n\n\n"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport scala.collection.mutable._\n\nobject Main extends App {\n val sc = new Scanner(System.in)\n\n val n, k = sc.nextInt()\n\n val a = input(n).toArray\n\n val m = Map[Int, Int]().withDefault(_ => 0)\n\n for (i <- 1 until (a.size - 1)) {\n if (a(i - 1) != a(i + 1)) m(a(i)) += 1\n else m(a(i)) += 2\n }\n\n m(a.last) += 1\n\n val ans = m reduce { (A, B) =>\n if (A._2 > B._2) A\n else if (A._2 == B._2 && A._1 < B._1) A\n else B\n }\n\n println(ans._1)\n\n def input(n: Int, result: List[Int] = Nil): List[Int] = {\n if (n == 0) result.reverse\n else {\n val q = sc.nextInt()\n if (result.headOption == Some(q)) input(n - 1, result)\n else input(n - 1, q :: result)\n }\n }\n}\n"}, {"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\n\nobject test6 extends App {\n val Array(n,k)=readLine.split(\" \").map(_.toInt)\n val arr=readLine.split(\" \").map(_.toInt)\n val ab=ArrayBuffer[Int]()\n ab+=arr(0)\n for(i<-1 until n) if(arr(i)!=arr(i-1)) ab+=arr(i)\n \n var dp=new Array[Int](k+1)\n for(i<-1 until n-1){\n if(arr(i-1)!=arr(i+1))\n dp(arr(i))+=1\n else\n dp(arr(i))+=2\n }\n dp(arr(0))+=1\n dp(arr(n-1))+=1\n \n println(dp.indexOf(dp.max))\n} \n\n\n"}, {"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\n\nobject test6 extends App {\n val Array(n,k)=readLine.split(\" \").map(_.toInt)\n val arr=readLine.split(\" \").map(_.toInt)\n var dp=new Array[Int](k+1)\n for(i<-1 until n){\n if(arr(i-1)!=arr(i)){\n dp(arr(i-1))+=1\n dp(arr(i))+=1\n }\n }\n \n println(dp.indexOf(dp.max))\n} \n\n\n"}], "src_uid": "6ef8200d05dd5eb729edceb62e393c50"} {"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val scale = 1e8\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n // c + m + p == 1, 0 < c, m, p < 1\r\n // 0.1 <= v <= 0.9\r\n val Array(c, m, p, v) = readLine().split(\" \").map(s => (s.toDouble * scale).toInt)\r\n\r\n def reward(slips: List[Int]): List[Int] =\r\n slips match {\r\n case x :: xs if x <= v => xs.map(_ + x / xs.length)\r\n case x :: xs if x > v => xs.map(_ + v / xs.length) :+ (x - v)\r\n case _ => slips\r\n }\r\n\r\n def race(slips: List[Int]): Double =\r\n slips match {\r\n case x :: y :: Nil =>\r\n x / scale + y / scale * (1 + race(reward(y :: x :: Nil)))\r\n case x :: y :: z :: Nil =>\r\n x / scale +\r\n y / scale * (1 + race(reward(y :: x :: z :: Nil))) +\r\n z / scale * (1 + race(reward(z :: x :: y :: Nil)))\r\n case _ => 1\r\n }\r\n\r\n val ans = race(List(p, m, c))\r\n\r\n println(ans)\r\n\r\n }\r\n}\r\n", "positive_code": [{"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val scale = 1e8\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n // c + m + p == 1, 0 < c, m, p < 1\r\n // 0.1 <= v <= 0.9\r\n val Array(c, m, p, v) =\r\n readLine().split(\" \").zipWithIndex.map { case (s, i) => ((s.toDouble + i / scale) * scale).toInt }\r\n\r\n def reward(slips: List[Int]): List[Int] =\r\n slips match {\r\n case x :: xs if x <= v => xs.map(_ + x / xs.length)\r\n case x :: xs if x > v => xs.map(_ + v / xs.length) :+ (x - v)\r\n case _ => slips\r\n }\r\n\r\n def race(slips: List[Int]): Double =\r\n slips match {\r\n case x :: Nil => 1\r\n case x :: y :: Nil =>\r\n x / scale +\r\n y / scale * (1 + race(reward(y :: x :: Nil)))\r\n case x :: y :: z :: Nil =>\r\n x / scale +\r\n y / scale * (1 + race(reward(y :: x :: z :: Nil))) +\r\n z / scale * (1 + race(reward(z :: x :: y :: Nil)))\r\n // case x :: xs =>\r\n // xs.permutations.foldLeft(x / scale) {\r\n // case (sum, y :: ys) => sum + y / scale * (1 + race(reward(y :: x :: ys)))\r\n // case (sum, _) => sum\r\n // }\r\n case _ => 0\r\n }\r\n\r\n val ans = race(List(p, m, c))\r\n\r\n println(ans)\r\n\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val scale = 1e6\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n // c + m + p == 1, 0 < c, m, p < 1\r\n // 0.1 <= v <= 0.9\r\n val Array(c, m, p, v) =\r\n readLine().split(\" \").zipWithIndex.map { case (s, i) => ((s.toDouble + i / scale) * scale).toInt }\r\n\r\n def reward(slips: List[Int]): List[Int] =\r\n slips match {\r\n case x :: xs if x <= v => xs.map(_ + x / xs.length)\r\n case x :: xs if x > v => xs.map(_ + v / xs.length) :+ (x - v)\r\n case _ => slips\r\n }\r\n\r\n def race(slips: List[Int]): Double =\r\n slips match {\r\n case x :: Nil => 1\r\n case x :: xs =>\r\n xs.permutations.foldLeft(x / scale) {\r\n case (sum, y :: ys) => sum + y / scale * (1 + race(reward(y :: x :: ys)))\r\n case (sum, _) => sum\r\n }\r\n case _ => 0\r\n }\r\n\r\n val ans = race(List(p, m, c))\r\n\r\n println(ans)\r\n\r\n }\r\n}\r\n"}], "src_uid": "738939f55bcc636c0340838818381d2f"} {"source_code": "object Solution extends App {\n var n = scala.io.StdIn.readInt()\n for (_ <- 1 to n) {\n var ans = scala.io.StdIn.readLine()\n .split(\"0\")\n .map(_.length)\n .sorted\n .reverse\n .zipWithIndex\n .filter(_._2 % 2 == 0)\n .map(_._1)\n .sum\n println(ans)\n }\n}\n", "positive_code": [{"source_code": "\n\nobject CodeforcesRoundE93b {\n\n import java.io.{BufferedReader, PrintStream}\n\n import scala.io.Source\n\n def main(args: Array[String]): Unit = {\n exec(Source.stdin.bufferedReader, System.out)\n }\n\n def exec(implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val t: Int = rl_int\n (1 to t).foreach(_ => test())\n }\n\n def test()\n (implicit\n reader: BufferedReader,\n writer: PrintStream): Unit = {\n val s = rl\n val res = s\n .split('0')\n .map(_.length)\n .sorted\n .reverse\n .grouped(2)\n .map(_ (0))\n .sum\n writer.println(res)\n }\n\n def rl(implicit reader: BufferedReader): String = reader.readLine\n def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')\n\n def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean\n def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte\n def rl_short(implicit reader: BufferedReader): Short = rl.toShort\n def rl_int(implicit reader: BufferedReader): Int = rl.toInt\n def rl_long(implicit reader: BufferedReader): Long = rl.toLong\n def rl_float(implicit reader: BufferedReader): Float = rl.toFloat\n def rl_double(implicit reader: BufferedReader): Double = rl.toDouble\n\n def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)\n def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)\n def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)\n def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)\n def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)\n def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)\n def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)\n\n}"}, {"source_code": "\n\nimport scala.io.StdIn\n\nobject Solution2 extends App {\n\n //A + B > C and B + C > A and C + A > B\n\n val n = StdIn.readLine().toInt\n\n val tc = for {\n _ <- 0 until n\n } yield {\n StdIn.readLine()\n }\n\n for {\n code <- tc\n } {\n println(solve(code))\n }\n\n def solve(code: String): String = {\n var i = 0\n\n val groups = scala.collection.mutable.Buffer[Int]()\n var group = 0\n while (i < code.length) {\n if (group != 0 && code.charAt(i) == '0') {\n groups += group\n group = 0\n } else if (code.charAt(i) == '1') {\n group += 1\n }\n i += 1\n }\n if (group != 0) {\n groups += group\n }\n groups.sorted.reverse.zipWithIndex.collect {\n case (score, idx) if idx % 2 == 0 => score\n }.sum.toString\n }\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val r = \"\"\"1+\"\"\".r\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val s = readLine()\n\n val ans = r\n .findAllIn(s)\n .map(_.length)\n .toList\n .sorted(Ordering.Int.reverse)\n .zipWithIndex\n .collect {\n case (l, i) if i % 2 == 0 => l\n }\n .reduceOption(_ + _)\n .getOrElse(0)\n\n println(ans)\n }\n}\n"}, {"source_code": "object B extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val s = readLine()\n\n val ans = s\n .foldLeft(List(0)) {\n case (0 :: xs, '0') => 0 :: xs\n case (xs, '0') => 0 :: xs\n case (x :: xs, '1') => (x + 1) :: xs\n }\n .sorted(Ordering.Int.reverse)\n .zipWithIndex\n .collect { case (l, i) if i % 2 == 0 => l }\n .reduceOption(_ + _)\n .getOrElse(0)\n\n println(ans)\n }\n}\n"}, {"source_code": "\nimport scala.collection.mutable.ListBuffer\n\nobject B extends App {\n import java.io._\n import java.nio.file.{Files, Path}\n import java.util.StringTokenizer\n\n import scala.io.Codec\n\n /* Implicit methods */\n implicit def intWithTimes(n: Int) = {\n new {\n def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }\n }\n }\n /* Implicit methods */\n\n // val in = new CustomScanner(Source.fromResource(\"input.txt\").mkString)\n val in = new CustomScanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val inputLines = in.nextInt()\n\n inputLines.times {\n val temLine = in.line()\n var oneCounts = ListBuffer.empty[Int]\n var count = 0\n temLine.foreach(x => {\n if (x == '1') {\n count = count + 1\n } else {\n if (count > 0) {\n oneCounts +== count\n count = 0\n }\n }\n })\n if (count > 0) {\n oneCounts +== count\n }\n val result = oneCounts\n .sortWith(_ > _)\n .zipWithIndex\n .foldLeft(0)((x, y) => {\n x + (if (y._2 % 2 == 0) y._1 else 0)\n })\n println(result)\n// val connectivity = Array.ofDim[Boolean](airports, airports)\n\n }\n }\n\n try {\n solve()\n } catch {\n case ex: Exception =>\n println(ex)\n sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n\n /**\n * Util methods\n */\n\n def printArr[T](in: Array[T]) = {\n in.foreach(print)\n println()\n }\n\n /**\n * Scala implementation of a faster java.util.Scanner\n * See: http://codeforces.com/blog/entry/7018\n */\n class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\n\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\n\n def this(reader: Reader) = this(new BufferedReader(reader))\n\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\n\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\n\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\n\n def this(str: String) = this(new StringReader(str))\n\n private[this] val tokenizers = {\n Iterator\n .continually(reader.readLine())\n .takeWhile(_ != null)\n .map(new StringTokenizer(_))\n .filter(_.hasMoreTokens)\n }\n\n private[this] var current: Option[StringTokenizer] = None\n\n @inline private[this] def tokenizer(): Option[StringTokenizer] =\n current.find(_.hasMoreTokens) orElse {\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\n current\n }\n\n /**\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\n * @see line() if you want the Java behaviour\n */\n def nextLine(): String = {\n current = None // reset\n reader.readLine()\n }\n\n def lineNumber: Int = reader.getLineNumber\n\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\n\n def nextString(): String = next()\n\n def nextChar(): Char = next().ensuring(_.length == 1).head\n\n def nextBoolean(): Boolean = next().toBoolean\n\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\n\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\n\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\n\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\n\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\n\n def nextFloat(): Float = next().toFloat\n\n def nextDouble(): Double = next().toDouble\n\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\n\n override def next(): String = tokenizer().get.nextToken()\n\n override def hasNext: Boolean = tokenizer().nonEmpty\n\n override def close(): Unit = reader.close()\n }\n}\n"}], "negative_code": [], "src_uid": "ebf0bf949a29eeaba3bcc35091487199"} {"source_code": "/*\nA. SMS-центр\nограничение по времени на тест\n2 секунды\nограничение по памяти на тест\n256 мегабайт\nввод\nstandard input\nвывод\nstandard output\n\nВ некоторой большой организации, в которой работает Поликарп, находится собственный sms-центр. Задачей центра является рассылка сотрудникам различной важной информации. Поликарп решил проверить эффективность работы sms-центра.\n\nДля этого он попросил предоставить ему данные о работе sms-центра за некоторый период времени. В ответ Поликарп получил список из n заданий, поступавших в sms-центр корпорации. Каждое задание описывалось временем поступления в sms-центр и количеством sms-сообщений, которое нужно было отослать. Более формально, i-ое задание описывалось двумя целыми числами ti и ci — моментом времени (секундой) поступления и количеством sms-сообщений соответственно.\n\nПоликарп знает, что sms-центр может отсылать не более одного sms-сообщения в секунду. Для организации отправки сообщений sms-центр использует очередь. Рассмотрим некоторый момент времени x, sms-центр будет функционировать в момент времени x следующим образом:\n\n Если в момент времени x очередь сообщений не пуста, тогда происходит отправка сообщения из очереди (сообщение берется из головы очереди). Иначе отправка сообщения в момент времени x не происходит.\n Если в момент времени x поступило задание на отправку сообщений, то в очередь добавляются все сообщения из этого задания (сообщения добавляются в хвост очереди). Обратите внимание, ни одно из этих сообщений не может быть отправлено в момент времени x, так как решение об отправке или не отправке сообщения в момент времени x принимается в пункте 1 до добавления этих сообщений. \n\nПо результатам анализа выполнения всех n заданий Поликарп хочет посчитать две величины: момент времени, когда было отправлено последнее sms-сообщение, а также максимальный размер очереди в некоторый момент времени. Помогите ему посчитать эти две характеристики, по которым он оценит эффективность работы sms-центра.\nВходные данные\n\nВ первой строке задано единственное целое число n (1 ≤ n ≤ 103) — количество заданий рассылки сообщений. Далее в n строках заданы описания заданий: в i-ой строке через пробел заданы два целых числа ti и ci (1 ≤ ti, ci ≤ 106) — момент времени (секунда) поступления i-го задания и количество сообщений, которое нужно отправить, соответственно.\n\nГарантируется, что все задания поступали в различные моменты времени. Гарантируется, что задания отсортированы в хронологическом порядке, то есть ti < ti + 1 для всех целых i (1 ≤ i < n).\nВыходные данные\n\nВ единственную строку через пробел выведите два целых числа — момент времени, когда было отправлено последнее sms-сообщение и максимальный размер очереди в некоторый момент времени.\nПримеры тестов\nВходные данные\n\n2\n1 1\n2 1\n\nВыходные данные\n\n3 1\n\nВходные данные\n\n1\n1000000 10\n\nВыходные данные\n\n1000010 10\n\nВходные данные\n\n3\n3 3\n4 3\n5 3\n\nВыходные данные\n\n12 7\n\nПримечание\n\nВ первом тестовом примере:\n\n секунда 1 — первое сообщение появилось в очереди, размер очереди 1;\n секунда 2 — первое сообщение отправлено, второе сообщение появилось в очереди, размер очереди 1;\n секунда 3 — второе сообщение отправлено, размер очереди 0, \n\nТаким образом, максимальный размер очереди 1, последнее сообщение отправлено в секунду 3.\n*/\nobject CrocRound1Task1 extends App {\n /** Finds time of the last sending and max queue size */\n def solve(tasks: Seq[(Int, Int)]): (Long, Long) = {\n solveRec(tasks, 0L, 0L, 0L)\n }\n\n def solveRec(tasks: Seq[(Int, Int)], currTime: Long, qSize: Long, maxSize: Long): (Long, Long) = {\n if (tasks.isEmpty) {\n (currTime + qSize, maxSize max qSize)\n } else {\n val (newTime, toEnqueue) = tasks.head\n val passed = newTime - currTime\n val newQSize = ((qSize - passed) max 0) + toEnqueue\n val newMaxSize = maxSize max newQSize\n solveRec(tasks.tail, newTime, newQSize, newMaxSize)\n }\n }\n\n val n = readLine.toInt\n val tasks = (0 until n) map (_ => readLine split ' ') map (split => (split(0).toInt, split(1).toInt))\n\n val res = solve(tasks)\n println(res._1 + \" \" + res._2)\n}", "positive_code": [{"source_code": "import io.Source\nimport java.io.PrintWriter\n\nobject CF292A {\n\n def solve(in: In, out: PrintWriter) {\n val n = in().toInt\n val ps = for (i <- 0 until n) yield {\n val t, c = in().toInt\n (t, c)\n }\n var t0, c0 = 0\n var maxSize = 0\n for ((t, c) <- ps.sorted) {\n val c1 = math.max(0, c0 - (t - t0)) + c\n maxSize = math.max(maxSize, c1)\n t0 = t\n c0 = c1\n }\n out.println((t0 + c0) + \" \" + maxSize)\n }\n\n def main(args: Array[String]) {\n val in: In = new In(Source.fromInputStream(System.in))\n val out: PrintWriter = new PrintWriter(System.out)\n solve(in, out)\n out.close()\n }\n\n class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {\n private val sb = new StringBuilder\n\n def hasNext: Boolean = {\n skipDelims()\n iter.hasNext\n }\n\n def skipDelims() {\n while (iter.hasNext && delims.indexOf(iter.head) != -1) {\n iter.next()\n }\n }\n\n def next(): String = {\n skipDelims()\n while (iter.hasNext && delims.indexOf(iter.head) == -1) {\n sb.append(iter.next())\n }\n val ret = sb.toString()\n sb.clear()\n ret\n }\n }\n\n class In(source: Source) {\n val iter = source.buffered\n\n val tokenIterator = new TokenIterator(iter, \" \\r\\n\")\n\n val lineIterator = new TokenIterator(iter, \"\\r\\n\")\n\n def apply() = tokenIterator.next()\n\n def apply(n: Int) = tokenIterator.take(n)\n }\n}"}, {"source_code": "object A {\n def READ: Array[Int] = readLine() split (\" \") map (_.toInt);\n\n def main(args: Array[String]) {\n var Array(n) = READ\n var cnt = 0;\n var max = 0;\n var prevT = 0;\n for (i <- 1 to n) {\n var Array(t,c) = READ;\n cnt = math.max(cnt -(t - prevT), 0);\n cnt += c;\n if (cnt > max) max = cnt;\n prevT = t;\n }\n println((prevT + cnt) + \" \" + max);\n }\n}\n"}], "negative_code": [], "src_uid": "608f8246bc6067e259898e8ed94db4c4"} {"source_code": "import java.util._\nimport java.io._\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n var pos = n / 2\n var len = 1\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n if (j >= pos && j < pos + len) {\n out.print(\"D\")\n } else {\n out.print(\"*\")\n }\n }\n out.println\n if (i < n / 2) {\n pos -= 1\n len += 2\n } else {\n pos += 1\n len -= 2\n }\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}", "positive_code": [{"source_code": "\n\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 01.08.14.\n */\nobject A extends App {\n\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def nextInt = in.nextInt\n def nextLong = in.nextLong\n def nextDouble = in.nextDouble\n def nextString = in.next\n\n def solve() = {\n val n = nextInt\n for (j <- 0 until n) {\n for (i <- 0 until n) {\n if ((i + j) >= (n - 1) / 2 && (i + j) <= 3 * (n - 1) / 2 && (j - i) <= (n - 1) / 2 && (j - i) >= -(n - 1) / 2) {\n out.print(\"D\")\n } else {\n out.print(\"*\")\n }\n }\n out.print(\"\\n\")\n }\n }\n\n try {\n solve()\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush()\n out.close()\n }\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nobject _454A extends App {\n var token = new StringTokenizer(\"\")\n def next = {\n while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)\n token.nextToken()\n }\n val n = next.toInt\n val a = Array.fill(n, n)('*')\n for (i <- 0 to n / 2)\n for (j <- n / 2 - i to n / 2 + i)\n a(i)(j) = 'D'\n for (i <- n / 2 until n)\n for (j <- n / 2 - (n - 1 - i) to n / 2 + (n - 1 - i))\n a(i)(j) = 'D'\n\n a.foreach(i => println(i.mkString))\n}\n"}, {"source_code": "object A454 {\n @inline def read = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int) = {\n val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))\n }\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val res = Array.fill((n+1)/2)(Array.fill[Char](n)('*'))\n for(i <- 0 until (n+1)/2) {\n val start = (n+1)/2 - i - 1\n for(j <- 0 until 2*i+1) {\n res(i)(start + j) = 'D'\n }\n }\n println(res.map(_.mkString(\"\")).mkString(\"\\n\"))\n println(res.dropRight(1).reverse.map(_.mkString(\"\")).mkString(\"\\n\"))\n }\n}"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport scala.collection._\n\nobject A extends App {\n \n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n\n val h = n / 2\n for (i <- 0 until h) {\n println(\"*\" * (h - i) + \"D\" * (2 * i + 1) + \"*\" * (h - i))\n }\n println(\"D\" * n)\n for (i <- 1 to h) {\n println(\"*\" * (i) + \"D\" * (n - 2 * i) + \"*\" * (i))\n }\n}"}, {"source_code": "import java.util._\nimport java.io._\n\nobject A {\n\n var out: PrintWriter = null\n var br: BufferedReader = null\n var st: StringTokenizer = null\n\n def next: String = {\n while (st == null || !st.hasMoreTokens) {\n st = new StringTokenizer(br.readLine)\n }\n return st.nextToken\n }\n\n def nextInt: Int = {\n return Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def solve: Int = {\n val n = nextInt\n var pos = n / 2\n var len = 1\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n if (j >= pos && j < pos + len) {\n out.print(\"D\")\n } else {\n out.print(\"*\")\n }\n }\n out.println\n if (i < n / 2) {\n pos -= 1\n len += 2\n } else {\n pos += 1\n len -= 2\n }\n }\n return 1\n }\n\n def main(args: Array[String]): Unit = {\n br = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(new BufferedOutputStream(System.out))\n solve\n out.close\n }\n}\n"}, {"source_code": "import java.util.Scanner\n\n/**\n * Created by Kuang.Ru on 14-9-18.\n */\nobject A454 extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n\n (1 to n / 2).foreach((i: Int) => {\n val numD = i * 2 - 1\n val numStars = (n - numD) / 2\n println(\"*\" * numStars + \"D\" * numD + \"*\" * numStars)\n })\n\n println(\"D\" * n)\n\n (n / 2 to 1 by -1).foreach((i: Int) => {\n val numD = i * 2 - 1\n val numStars = (n - numD) / 2\n println(\"*\" * numStars + \"D\" * numD + \"*\" * numStars)\n })\n}\n"}, {"source_code": "/**\n * Created by bamboo on 02.08.14.\n */\nobject martin1 {\n\n def main(args: Array[String]) = {\n\n def crystal(n: Int) = {\n val half = n / 2\n val first = (for {\n i <- half to 0 by -1\n } yield {\n (\"*\" * i) + (\"D\" * (n - i - i)) + (\"*\" * i)\n }) mkString (\"\\n\")\n val sec = (for {\n i <- 1 to half\n } yield {\n (\"*\" * i) + (\"D\" * (n - i - i)) + (\"*\" * i)\n }) mkString (\"\\n\")\n first + \"\\n\" + sec\n }\n\n val n = Console.readInt\n Console.print(crystal(n))\n }\n\n}"}, {"source_code": "object main extends App with fastIO {\n \n def sol(row: Int) = println(\"*\" * (m - row) + \"D\" * (2 * row - 1) + \"*\" * (m - row)) \n \n var n = nextInt\n var m = (n >> 1) + 1 \n for (row <- 1 until m) sol(row) \n for (row <- m to (1, -1)) sol(row)\n \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}], "negative_code": [{"source_code": "object main extends App with fastIO {\n \n def sol(row: Int) = println(\".\" * (m - row) + \"D\" * (2 * row - 1) + \".\" * (m - row)) \n \n var n = nextInt\n var m = (n >> 1) + 1 \n for (row <- 1 until m) sol(row) \n for (row <- m to (1, -1)) sol(row)\n \n flush \n}\n\ntrait fastIO {\n import java.io._\n \n val isFile = false\n val input = \"io.in\"\n val output = \"io.out\"\n \n val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))\n val in = new StreamTokenizer(bf)\n val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))\n\n def next: String = {\n in.ordinaryChars('0', '9')\n in.wordChars('0', '9')\n in.nextToken()\n in.sval\n }\n \n def nextInt: Int = {\n in.nextToken()\n in.nval.toInt\n }\n \n def nextLong:Long ={\n in.nextToken()\n in.nval.toLong\n }\n \n def nextDouble: Double = {\n in.nextToken()\n in.nval\n }\n \n def readLine: String = bf.readLine()\n def println(o:Any) = out.println(o)\n def print(o:Any) = out.print(o)\n def printf(s:String,o:Any*) = out.printf(s,o)\n def flush() = out.flush() \n}"}], "src_uid": "a003d645999934c255f7b05d8494fa40"} {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val T = ni()\n\n def findL(c: Char)= 'a' to 'z' contains c\n def findU(c: Char)= 'A' to 'Z' contains c\n def findD(c: Char)= '0' to '9' contains c\n\n def step(s: Array[Char]): Array[Char] = {\n val lower = s.count(c => 'a' to 'z' contains c)\n val upper = s count (c => 'A' to 'Z' contains c)\n val digit = s count (c => '0' to '9' contains c)\n\n if (lower == 0) {\n val f = if (upper >= 2) findU _ else findD _\n s(s.indexWhere(f)) = 'a'\n step(s)\n } else if (upper == 0) {\n val f = if (lower >= 2) findL _ else findD _\n s(s.indexWhere(f)) = 'A'\n step(s)\n } else if (digit == 0) {\n val f = if (lower >= 2) findL _ else findU _\n s(s.indexWhere(f)) = '0'\n step(s)\n }\n s\n }\n\n rep(T) { _ =>\n val s = ns().toCharArray\n out.println(step(s).mkString)\n }\n }\n\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def nc(): Char = sc.nextChar()\n def ns(): String = sc.next()\n def ns(n: Int): Array[Char] = ns().toCharArray\n def na(n: Int): Array[Int] = map(n)(_ => ni())\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\n def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))\n def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = n - 1 + offset\n while(i >= offset) { f(i); i -= 1 }\n }\n\n def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {\n val res = Array.ofDim[A](n)\n rep(n)(i => res(i) = f(i))\n res\n }\n\n def sumL(as: Array[Int]): Long = {\n var s = 0L\n rep(as.length)(i => s += as(i))\n s\n }\n}", "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Codeforces1051A {\n\n def getCharType(char: Char, allCharTypes: Seq[CharType]): CharType = {\n for (charType <- allCharTypes) {\n if (charType.range.contains(char)) return charType\n }\n throw new RuntimeException\n }\n\n def charCount(s: String, charType: CharType): Int =\n s.filter(char => charType.range.contains(char)).length\n\n def containsChar(s: String, charType: CharType): Boolean =\n s.exists(char => charType.range.contains(char))\n\n def getStrongPassword(s: String): String = {\n val upperCaseCharType = CharType('A' to 'Z', 'A')\n val lowerCaseCharType = CharType('a' to 'z', 'a')\n val digitCharType = CharType('0' to '9', '0')\n\n val allCharTypes = Seq(upperCaseCharType, lowerCaseCharType, digitCharType)\n\n val missingCharTypes = allCharTypes.filter(charType => !containsChar(s, charType))\n\n var newPassword = s\n for (charType <- missingCharTypes) {\n newPassword = addInPassword(newPassword, allCharTypes, charType)\n }\n newPassword\n }\n\n def addInPassword(password: String, allCharTypes: Seq[CharType], missingCharType: CharType): String = {\n for (i <- password.indices) {\n val charType = getCharType(password(i), allCharTypes)\n if (charCount(password, charType) != 1) {\n return password.substring(0, i) + missingCharType.anyChar + password.substring(i + 1)\n }\n }\n password\n }\n\n case class CharType(range: Seq[Char], anyChar: Char)\n\n def main(args: Array[String]): Unit = {\n val t = StdIn.readInt()\n for (_ <- 1 to t) {\n val s = StdIn.readLine()\n val strongPassword = getStrongPassword(s)\n println(strongPassword)\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\nobject Codeforces1051A {\n\n def getCharType(char: Char, allCharTypes: Seq[CharType]): CharType = {\n for (charType <- allCharTypes) {\n if (charType.range.contains(char)) return charType\n }\n throw new RuntimeException\n }\n\n def charCount(s: String, charType: CharType): Int =\n s.filter(char => charType.range.contains(char)).length\n\n def containsChar(s: String, charType: CharType): Boolean =\n s.exists(char => charType.range.contains(char))\n\n def getStrongPassword(s: String): String = {\n val upperCaseCharType = CharType('A' to 'Z', 'A')\n val lowerCaseCharType = CharType('a' to 'z', 'a')\n val digitCharType = CharType('0' to '9', '0')\n\n val allCharTypes = Seq(upperCaseCharType, lowerCaseCharType, digitCharType)\n\n val missingCharTypes = allCharTypes.filter(charType => containsChar(s, charType))\n\n var newPassword = s\n for (charType <- missingCharTypes) {\n newPassword = addInPassword(newPassword, allCharTypes, charType)\n }\n newPassword\n }\n\n def addInPassword(password: String, allCharTypes: Seq[CharType], missingCharType: CharType): String = {\n for (i <- password.indices) {\n val charType = getCharType(password(i), allCharTypes)\n if (charCount(password, charType) != 1) {\n return password.substring(0, i) + missingCharType.anyChar + password.substring(i + 1)\n }\n }\n password\n }\n\n case class CharType(range: Seq[Char], anyChar: Char)\n\n def main(args: Array[String]): Unit = {\n val t = StdIn.readInt()\n for (_ <- 1 to t) {\n val s = StdIn.readLine()\n val strongPassword = getStrongPassword(s)\n println(strongPassword)\n }\n }\n}\n"}], "src_uid": "81faa525ded9b209fb7d5d8fec95f38b"} {"source_code": "import scala.collection.mutable\n\nobject B {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val ps = nextInts(n)\n val dpSum = Array.fill(n){ 0L }\n val dpCount = Array.fill(n){ 0 }\n val resBuilder = new mutable.ArrayBuilder.ofInt\n\n var prevDir = 0\n //resBuilder += ps(0)\n for (i <- 1 until n) {\n val dir = Integer.signum(ps(i) - ps(i - 1))\n if (dir != prevDir) {\n resBuilder += ps(i - 1)\n prevDir = dir\n }\n }\n\n resBuilder += ps.last\n val res = resBuilder.result()\n out.println(res.length)\n out.println(res.mkString(\" \"))\n }\n\n out.flush()\n }\n \n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n val mod: Int = Math.pow(10, 9).toInt + 7\n\n def main(args: Array[String]): Unit = {\n // val src = io.Source.fromFile(\"/usr/share/dict/words\")\n // val lines = src.getLines()\n // src.close()\n val t = readLine().toInt\n for (i <- 1 to t) {\n val n = readLine().toInt\n val arr = readIntLine()\n findLongest(arr)\n }\n }\n\n def findLongest(list: List[Int]) = {\n def helper(l: List[Int], acc: List[Int], increasing: Int, prev: Int): List[Int] = l match {\n case Nil => (prev :: acc).reverse\n case c :: cs => helper(cs, if (c > prev && increasing == 1 || c < prev && increasing == -1) acc else prev :: acc,\n if (c > prev) 1 else -1, c)\n }\n\n val res = helper(list.tail, List[Int](), 0, list.head)\n println(res.length)\n printArray(res.toArray)\n }\n\n def readIntLine(): List[Int] = {\n readLine().split(\" \").map(_.toInt).toList\n }\n\n def printArray[T](arr: Array[T]): Unit = {\n print(arr(0))\n for (i <- 1 until arr.length) {\n print(\" \" + arr(i))\n }\n println()\n }\n\n def readLongLine(): List[Long] = {\n readLine().split(\" \").map(_.toLong).toList\n }\n\n}\n\n"}], "negative_code": [], "src_uid": "857de33d75daee460206079fa2c15814"} {"source_code": "import scala.io.StdIn\n\nobject Task403A {\n\n def calc(socks: List[Int]): List[Int] = {\n def recCalc(table: Set[Int], socks: List[Int]): List[Int] = {\n socks match {\n case Nil => Nil\n case head :: tail =>\n table.size :: recCalc(if (table.contains(head)) table - head else table + head, tail)\n }\n }\n recCalc(Set(), socks)\n }\n\n def main(args: Array[String]): Unit = {\n StdIn.readInt()\n val socks = StdIn.readLine().split(\" \").map(_.toInt).toList\n println(calc(socks).max)\n }\n\n}\n", "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject A extends App {\n val n = readLine\n val xs = readLine.split(' ').map(_.toInt)\n val (_, maxCount) = xs.foldLeft((Set.empty[Int], 0)){\n case ((seen, cnt), i) if seen(i) ⇒\n (seen - i, cnt max seen.size)\n case ((seen, cnt), i )⇒\n (seen + i, cnt)\n }\n println(maxCount)\n}\n"}, {"source_code": "import io.StdIn._\nimport scala.collection.mutable\n\nimport scala.collection.mutable._\n\nobject Solution {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n def main(args: Array[String]) {\n val Array(n) = readInts(1)\n\n var ans = 0\n val set = mutable.HashSet[Int]()\n readInts(2 * n).foreach { x =>\n if (set.contains(x)) {\n set.remove(x)\n } else {\n set.add(x)\n ans = Math.max(ans, set.size)\n }\n }\n\n println(ans)\n\n // Console.withOut(new java.io.BufferedOutputStream(Console.out))\n // println(res.mkString(\"\\n\"))\n // Console.flush\n }\n}"}], "negative_code": [], "src_uid": "7f98c9258f3e127a782041c421d6317b"} {"source_code": "import java.io.PrintWriter\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\nimport util.control.Breaks._\n\nobject Solution {\n val reader = scala.io.StdIn\n def readInt(): Int = reader.readLine().toInt\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n def readString(): String = reader.readLine()\n\n def multiTest(f: Int => Unit): Unit = {\n val t = readInt()\n for (i <- 1 to t) f(i)\n }\n\n def GCD(a: Int, b: Int): Int = {\n if (a == 0) return b\n GCD(b % a, a)\n }\n\n def solve(t: Int): Unit = {\n val n = readInt()\n val a = readArrayInt()\n val uniq = a.distinct.length\n val b = new Array[Int](a.max + 1)\n for (i <- a.indices) b(a(i)) += 1\n\n var rs = 0\n for (i <- a.indices if b(a(i)) > 0) {\n if (b(a(i)) <= uniq - 1)\n rs = Math.max(rs, b(a(i)))\n else\n rs = Math.max(rs, Math.min(b(a(i)) - 1, uniq))\n }\n println(rs)\n }\n\n def main(args: Array[String]) {\n multiTest(solve)\n //solve()\n }\n}", "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Solution_C extends App {\n val T = StdIn.readInt()\n for (_ <- 1 to T) {\n val N = StdIn.readInt()\n val skills = StdIn.readLine().split(' ').map{_.toInt}\n val counts = mutable.SortedMap[Int, Int]()\n skills foreach {s=>\n counts.put(s, counts.getOrElse(s, 0) + 1)\n }\n var x = 0\n counts.keys foreach { skill =>\n val g1 = counts(skill)\n val g2 = counts.size - 1\n x = Math.max(x, Math.min(g1, g2))\n val g3 = g1 - 1\n val g4 = g2 + 1\n x = Math.max(x, Math.min(g3, g4))\n }\n println(x)\n }\n}\n"}, {"source_code": "\nobject Main extends App {\n import scala.io.StdIn._\n val t = readInt\n\n for(_ <- 0 until t) {\n val n = readInt()\n val skills = readLine.trim.split(' ').map(_.toInt)\n val groups = skills.groupBy(identity)\n val max = groups.maxBy(_._2.size)._2.size\n val a = math.min(groups.size - 1, max)\n val b = math.min(groups.size, max - 1)\n println(math.max(a, b))\n }\n}\n"}, {"source_code": "object C extends App {\n case class Student(number: Int, skill: Int)\n\n private def numberOfComposing(students: List[Student]): Int = {\n val l :: rs = students\n .groupBy(_.skill)\n .toList\n .map(_._2.length)\n .sorted(Ordering.Int.reverse)\n\n val r = rs.length\n\n if (r >= l) l\n else if (l - r > 1) r + 1\n else r\n }\n\n val t = scala.io.StdIn.readInt()\n\n val input = (0 until t)\n .foldLeft(List.empty[List[Student]]) {\n case (acc, _) =>\n val n = scala.io.StdIn.readInt()\n val students =\n scala.io.StdIn\n .readLine()\n .split(\" \")\n .map(_.toInt)\n .zipWithIndex\n .map {\n case (s, i) => Student(i, s)\n }\n .toList\n\n students :: acc\n }\n .reverse\n\n val answers = input.map(numberOfComposing)\n\n answers.foreach(println)\n}"}, {"source_code": "object C extends App {\n\n val t = scala.io.StdIn.readInt()\n\n (0 until t).foreach { _ =>\n val n = scala.io.StdIn.readInt()\n val skills = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n val l :: rs =\n skills\n .groupBy(identity)\n .valuesIterator\n .map(_.length)\n .toList\n .sorted(Ordering.Int.reverse)\n\n val r = rs.length\n\n val answer =\n if (r >= l) l\n else if (l - r > 1) r + 1\n else r\n\n println(answer)\n }\n}"}], "negative_code": [{"source_code": "import java.io.PrintWriter\n\nimport scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\nimport util.control.Breaks._\n\nobject Solution {\n val reader = scala.io.StdIn\n def readInt(): Int = reader.readLine().toInt\n def readArrayInt(): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n def readString(): String = reader.readLine()\n\n def multiTest(f: Int => Unit): Unit = {\n val t = readInt()\n for (i <- 1 to t) f(i)\n }\n\n def GCD(a: Int, b: Int): Int = {\n if (a == 0) return b\n GCD(b % a, a)\n }\n\n def solve(t: Int): Unit = {\n val n = readInt()\n val a = readArrayInt()\n val uniq = a.distinct.length\n val b = new Array[Int](a.max + 1)\n for (i <- a.indices) b(a(i)) += 1\n\n var rs = 0\n for (i <- a.indices if b(a(i)) > 0) {\n if (b(a(i)) <= uniq - 1)\n rs = Math.max(rs, b(a(i)))\n else\n rs = Math.max(rs, (b(a(i)) + uniq - 1) / 2)\n }\n println(rs)\n }\n\n def main(args: Array[String]) {\n multiTest(solve)\n //solve()\n }\n}"}, {"source_code": "object C extends App {\n case class Student(number: Int, skill: Int)\n\n private def numberOfComposing(students: List[Student]): Int = {\n @scala.annotation.tailrec\n def compose(skills: List[Int], limit: Int, curr: Int = 0): Int =\n if (curr >= limit) limit\n else if (skills.isEmpty) curr + (limit - curr) / 2\n else compose(skills.tail, limit, curr + skills.head)\n\n val l :: rs = students\n .groupBy(_.skill)\n .toList\n .map(_._2.length)\n .sorted(Ordering.Int.reverse)\n\n compose(rs, l)\n }\n\n val t = scala.io.StdIn.readInt()\n\n val input = (0 until t)\n .foldLeft(List.empty[List[Student]]) {\n case (acc, _) =>\n val n = scala.io.StdIn.readInt()\n val students =\n scala.io.StdIn\n .readLine()\n .split(\" \")\n .map(_.toInt)\n .zipWithIndex\n .map {\n case (s, i) => Student(i, s)\n }\n .toList\n\n students :: acc\n }\n .reverse\n\n val answers = input.map(numberOfComposing)\n\n answers.foreach(println)\n}"}, {"source_code": "object C extends App {\n case class Student(number: Int, skill: Int)\n\n private def numberOfComposing(students: List[Student]): Int = {\n val l :: rs = students\n .groupBy(_.skill)\n .toList\n .map(_._2.length)\n .sorted(Ordering.Int.reverse)\n\n val r = rs.length\n\n if (r >= l) l\n else r + (l - r) / 2\n }\n\n val t = scala.io.StdIn.readInt()\n\n val input = (0 until t)\n .foldLeft(List.empty[List[Student]]) {\n case (acc, _) =>\n val n = scala.io.StdIn.readInt()\n val students =\n scala.io.StdIn\n .readLine()\n .split(\" \")\n .map(_.toInt)\n .zipWithIndex\n .map {\n case (s, i) => Student(i, s)\n }\n .toList\n\n students :: acc\n }\n .reverse\n\n val answers = input.map(numberOfComposing)\n\n answers.foreach(println)\n}"}], "src_uid": "a1951e7d11b504273765fc9fb2f18a5e"} {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val matrix = (0 until n).map(i => in.next().zipWithIndex.filter(t => t._1 == '1').map(_._2).toSet + i)\n .filter(_.size > 1)\n val marked = Array.ofDim[Boolean](matrix.length)\n val result = data.clone()\n matrix.indices.foreach {\n case i if marked(i) =>\n case i =>\n marked(i) = true\n var found = true\n var set = matrix(i)\n while (found) {\n found = false\n (i + 1 until matrix.length).filter(j => !marked(j)).foreach { j =>\n val joined = set ++ matrix(j)\n if (joined.size < set.size + matrix(j).size) {\n set = joined\n marked(j) = true\n found = true\n }\n }\n }\n val list = set.toList\n val values = list.map(data).sorted\n val indices = list.sorted\n indices.zip(values).foreach {\n case(j, v) => result(j) = v\n }\n }\n println(result.mkString(\" \"))\n}", "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject B500 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n val n = readInt\n val p = readInts(n).map(_ - 1)\n val graph = Array.fill(n) { read.toArray.map(_ == '1') }\n for (k <- 0 until n; i <- 0 until n; j <- 0 until n\n if graph(i)(k) && graph(k)(j)) {\n graph(i)(j) = true\n }\n\n case class Ele(number: Int, pos: Int) extends Ordered[Ele] {\n def compare(that: Ele) = -this.number.compareTo(that.number)\n }\n val pq = mutable.PriorityQueue.empty[Ele] // number, pos\n for (idx <- 0 until n) {\n pq.enqueue((idx + 1 until n).map { _idx =>\n Ele(p(_idx), _idx)\n }: _*)\n while (pq.nonEmpty && pq.head.number < p(idx)) {\n val top = pq.dequeue()\n if (graph(idx)(top.pos)) {\n val tmp = p(idx)\n p(idx) = top.number\n p(top.pos) = tmp\n }\n }\n pq.clear()\n }\n\n out.println(p.map(_ + 1).mkString(\" \"))\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}, {"source_code": "import scala.collection._\n\nobject B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val ps = readInts(n)\n val as = Array.fill(n)(readLine.toCharArray.map(_ == '1'))\n val pos = ps.zipWithIndex.toMap\n\n val res = Array.fill(n)(0)\n\n val range = 0 until n\n for (i <- range) as(i)(i) = true\n for (k <- range)\n for (i <- range) if (as(i)(k))\n for (j <- range) if (as(k)(j)) as(i)(j) = true\n\n for (p <- 1 to n) {\n var i = 0\n var found = false \n while (!found) {\n if (res(i) == 0 && as(pos(p))(i)) {\n res(i) = p\n found = true\n } else i += 1\n }\n }\n\n println(res.mkString(\" \"))\n}"}], "negative_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val data = in.next().split(' ').map(_.toInt)\n val matrix = (1 to n).map(_ => in.next().zipWithIndex.filter(t => t._1 == '1').map(_._2).toSet).filter(_.size > 1)\n val marked = Array.ofDim[Boolean](matrix.length)\n val result = data.clone()\n matrix.indices.foreach {\n case i if marked(i) =>\n case i =>\n marked(i) = true\n var found = true\n var set = matrix(i)\n while (found) {\n found = false\n (i + 1 until matrix.length).filter(j => !marked(j)).foreach { j =>\n val joined = set ++ matrix(j)\n if (joined.size < set.size + matrix(j).size) {\n set = joined\n marked(j) = true\n found = true\n }\n }\n }\n val list = set.toList\n val values = list.map(data).sorted\n val indices = list.sorted\n indices.zip(values).foreach {\n case(j, v) => result(j) = v\n }\n }\n println(result.mkString(\" \"))\n}"}], "src_uid": "a67ea891cd6084ceeaace8894cf18e60"} {"source_code": "object C extends App {\r\n\r\n def divisibleConfusion(an: IndexedSeq[Int]): Boolean = {\r\n val n = an.length\r\n\r\n @annotation.tailrec\r\n def go(index: Int, removed: Int): Boolean =\r\n if (index == n) true\r\n else {\r\n val ai = an(index)\r\n\r\n val canBeRemoved = index.to(index - removed, -1).exists { index =>\r\n ai % (index + 2) != 0\r\n }\r\n\r\n canBeRemoved && go(index + 1, removed + 1)\r\n }\r\n\r\n go(0, 0)\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val an = nextInts(n)\r\n\r\n divisibleConfusion(an) match {\r\n case true => out.println(\"YES\")\r\n case false => out.println(\"NO\")\r\n }\r\n\r\n }\r\n\r\n out.flush()\r\n\r\n object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n private[this] def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n", "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\nimport scala.+:\nimport scala.collection.mutable\nimport scala.collection.mutable._\nimport scala.collection.immutable._\nimport scala.util.Sorting.quickSort\nimport scala.math._\n\n\nobject Main extends App {\n val writer = new PrintWriter(System.out, false)\n val reader = new BufferedReader(new InputStreamReader(System.in))\n var st = new StringTokenizer(\"\")\n def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}\n def readInt(): Int = next().toInt\n def readLong(): Long = next().toLong\n def readString(): String = next()\n\n case class pair(var minl: Int, var maxl: Int, var minr: Int, var maxr: Int, var ind: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return minl.compareTo(that.minl)\n }\n }\n val rem = 1000000007\n def gcd(a: Int, b: Int): Int = b match {\n case 0 => a\n case n => gcd(b, a % b)\n }\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n var ans = \"YES\"\n for (i <- 1 to n) {\n var flag = false\n var m = readInt()\n var k = 2\n while (k <= i+1 && !flag && ans == \"YES\") {\n if (m % k != 0)\n flag = true\n k += 1\n }\n if (!flag)\n ans = \"NO\"\n }\n writer.println(ans)\n }\n writer.flush()\n}\n"}, {"source_code": "object C extends App {\r\n\r\n def divisibleConfusion(an: IndexedSeq[Int]): Boolean = {\r\n val n = an.length\r\n\r\n @annotation.tailrec\r\n def go(index: Int): Boolean =\r\n if (index == n) true\r\n else {\r\n val ai = an(index)\r\n index.to(0, -1).exists { j => ai % (j + 2) != 0 } && go(index + 1)\r\n }\r\n\r\n go(0)\r\n }\r\n\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = nextInt()\r\n val an = nextInts(n)\r\n\r\n divisibleConfusion(an) match {\r\n case true => out.println(\"YES\")\r\n case false => out.println(\"NO\")\r\n }\r\n\r\n }\r\n\r\n out.flush()\r\n\r\n object InOut {\r\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\r\n val out = new java.io.PrintWriter(System.out, false)\r\n\r\n def nextInt() = Integer.parseInt(nextToken())\r\n def nextInts(n: Int) = Array.fill(n)(nextInt())\r\n\r\n def nextLong() = java.lang.Long.parseLong(nextToken())\r\n def nextLongs(n: Int) = Array.fill(n)(nextLong())\r\n\r\n def nextBig() = BigInt(nextToken())\r\n def nextBigs(n: Int) = Array.fill(n)(nextBig())\r\n\r\n def nextLine() = in.readLine()\r\n\r\n private[this] var tokenizer: java.util.StringTokenizer = _\r\n\r\n private[this] def nextToken(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens())\r\n tokenizer = new java.util.StringTokenizer(in.readLine())\r\n tokenizer.nextToken()\r\n }\r\n }\r\n\r\n}\r\n"}], "negative_code": [], "src_uid": "080f29d4e2aa5bb9ee26d882362c8cd7"} {"source_code": "object Party {\n def main(args: Array[String]): Unit = {\n val in =scala.io.StdIn\n val n=in.readLine().toInt\n val arr=Array.ofDim[Int](n)\n for(i<-Range(0,n)){\n val x=in.readLine().toInt\n arr(i)= if(x>0) x-1 else -1\n }\n var maxD=1\n for(i<- 0 until n){\n var j=i\n var curD=1\n while (arr(j)!= -1){\n curD+=1\n j=arr(j)\n }\n maxD=math.max(maxD,curD)\n }\n println(maxD)\n }\n}\n", "positive_code": [{"source_code": "\nobject Main {\n\n val MAX = 2222\n val adj = new Array[List[Int]](2222)\n\n def getHeight(u: Int, pu: Int, h: Int): Int = {\n 1 + (for (v <- adj(u)) yield if (v != pu) getHeight(v,u,h+1) else 0).foldRight(0)(Math.max)\n }\n\n def main(args: Array[String]) {\n val n = readInt()\n for (i <- 1 to n) adj(i) = Nil\n var roots: List[Int] = Nil\n for (i <- 1 to n) {\n val pi = readInt()\n if (pi != -1) {\n adj(i) = pi :: adj(i)\n adj(pi) = i :: adj(pi)\n } else\n roots = i :: roots\n }\n\n val ans = (for (r <- roots) yield getHeight(r,0,0)).foldRight(0)(Math.max)\n println(ans)\n }\n\n}\n\n"}, {"source_code": "import java.io.InputStream\n\nimport scala.annotation.tailrec\n\nobject Main {\n def main(args: Array[String]): Unit = {\n runOn(System.in)\n// runOn(new StringBufferInputStream(\"5\\n-1\\n1\\n2\\n1\\n-1\\n\"))\n }\n\n def runOn(is: InputStream): Unit = {\n val tokens = tokensFrom(is).map(_.toInt)\n\n val numberOfPeople = tokens.next()\n val managers = Array.fill(numberOfPeople)(tokens.next() - 1)\n\n val depths = managers.indices.map(depthOf(managers, _))\n val maxDepth = depths.max\n\n val result = maxDepth + 1\n println(result)\n }\n\n @tailrec\n private def depthOf(managers: Array[Int], targetIndex: Int, currentCount: Int = 0): Int = {\n val targetManagerIndex = managers(targetIndex)\n if (targetManagerIndex < 0) {\n currentCount\n } else {\n depthOf(managers, targetManagerIndex, currentCount + 1)\n }\n }\n\n private def tokensFrom(is: InputStream) = {\n val reader = new java.io.BufferedReader(new java.io.InputStreamReader(is))\n Iterator.continually(reader.readLine()).flatMap(_.split(\" \"))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = Range(0, n).map(_ => in.next().toInt - 1)\n println(data.foldLeft(0){\n case(acc, el) =>\n var i = 1\n var c = el\n while (c >= 0) {\n i += 1\n c = data(c)\n }\n Math.max(acc, i)\n })\n}"}, {"source_code": "object A115 {\n\n import IO._\n\n def main(args: Array[String]): Unit = {\n val Array(n) = readInts(1)\n val in = Array.fill(n)(readInts(1)).map(_(0))\n val vis = Array.fill(n)(false)\n var res = 1\n for(i <- 0 until n if !vis(i)) {\n if(in(i) == -1)\n vis(i) = true\n else {\n var j = i\n var curr = 1\n while(in(j) != -1) {\n j = in(j) - 1\n curr += 1\n }\n res = math.max(res, curr)\n }\n }\n println(res)\n }\n\n object IO {\n @inline def read: String = scala.io.StdIn.readLine\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine;\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine;\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.io.InputStream\n\nimport scala.annotation.tailrec\n\nobject Main {\n def main(args: Array[String]): Unit = {\n runOn(System.in)\n// runOn(new StringBufferInputStream(\"5\\n-1\\n1\\n2\\n1\\n-1\\n\"))\n }\n\n def runOn(is: InputStream): Unit = {\n val tokens = tokensFrom(is).map(_.toInt)\n\n val numberOfPeople = tokens.next()\n val managers = Array.fill(numberOfPeople)(tokens.next() - 1)\n\n val depths = managers.indices.map(depthOf(managers, _))\n val maxDepth = depths.max\n\n val result = Math.min(3, maxDepth + 1)\n\n println(result)\n }\n\n @tailrec\n private def depthOf(managers: Array[Int], targetIndex: Int, currentCount: Int = 0): Int = {\n val targetManagerIndex = managers(targetIndex)\n if (targetManagerIndex < 0) {\n currentCount\n } else {\n depthOf(managers, targetManagerIndex, currentCount + 1)\n }\n }\n\n private def tokensFrom(is: InputStream) = {\n val reader = new java.io.BufferedReader(new java.io.InputStreamReader(is))\n Iterator.continually(reader.readLine()).flatMap(_.split(\" \"))\n }\n}\n"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val data = Range(0, n).map(_ => in.next().toInt - 1)\n println(data.foldLeft(0){\n case(acc, el) =>\n var i = 1\n var c = el\n while (c >= 0) {\n i += 1\n c = data(c)\n }\n Math.max(acc, i)\n })\n println(data)\n\n}"}], "src_uid": "8d911f79dde31f2c6f62e73b925e6996"} {"source_code": "object B extends App {\n val l = 1000000\n val n = scala.io.StdIn.readInt()\n val m = scala.io.StdIn.readLine().split(\" \").foldLeft(0)((m, w) => {\n val i = w.toInt\n m max ((i - 1) min (l - i))\n })\n\n println(m)\n}\n", "positive_code": [{"source_code": "object B extends App {\n\n @inline def tokenizeLine = new java.util.StringTokenizer(readLine)\n def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }\n def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }\n def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n val as = readInts(n)\n val friend = 1000000\n\n var max = 0\n for (a <- as) {\n val m = Math.min(a - 1, friend - a)\n if (m > max) max = m\n }\n\n println(max)\n}\n"}, {"source_code": "object CF938B extends App{\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n val a = Seq.fill[Int](n)(sc.nextInt)\n val you = a filter (_ <= Math.pow(10,6) / 2)\n val friend = a filter (_ > Math.pow(10,6) / 2)\n println(Math.max(if(you isEmpty) 0 else (you max) - 1, if(friend isEmpty) 0 else Math.pow(10,6).toInt - (friend min)))\n}\n"}], "negative_code": [], "src_uid": "f530e6f720dafaf8bff9324289b90b28"} {"source_code": "object C1253 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var tests = 1 // readInt\n while (tests > 0) {\n val Array(n, m) = readInts(2)\n val a = readInts(n).sorted\n var res = 0L\n val dp = Array.fill(n)(0L)\n for (i <- 0 until n) {\n dp(i) = a(i) + (if (i - m >= 0) dp(i - m) else 0)\n }\n// out.println(dp.mkString(\" \"))\n for (idx <- 0 until n) {\n res += dp(idx)\n// var i = idx\n// while (i >= 0 && idx < n) {\n// res += a(i)\n// i -= m\n// }\n out.print(s\"$res \")\n }\n out.println(\"\")\n tests -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n", "positive_code": [{"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n, m = nextInt\n val as = nextLongs(n).sorted\n val pen1, pen2 = Array.fill(m)(0L)\n val res = Array.fill(n)(0L)\n\n var sum = 0L\n for (i <- 0 until m) {\n sum += as(i)\n pen1(i) = as(i)\n pen2(i) = as(i)\n res(i) = sum\n }\n\n for (i <- m until n) {\n val mod = i % m\n sum += pen1(mod) + as(i)\n pen2(mod) += pen1(mod)\n pen1(mod) += as(i)\n pen2(mod) += as(i)\n res(i) = sum\n }\n\n out.println(res.mkString(\" \"))\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}, {"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n, m = nextInt\n val as = nextLongs(n).sorted\n val pen1 = Array.fill(m)(0L)\n val res = Array.fill(n)(0L)\n\n var sum = 0L\n for (i <- 0 until m) {\n sum += as(i)\n pen1(i) = as(i)\n res(i) = sum\n }\n\n for (i <- m until n) {\n val mod = i % m\n sum += pen1(mod) + as(i)\n pen1(mod) += as(i)\n res(i) = sum\n }\n\n out.println(res.mkString(\" \"))\n out.flush()\n\n final object InOut {\n val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))\n val out = new java.io.PrintWriter(System.out, false)\n private[this] var tokenizer: java.util.StringTokenizer = _\n def nextToken: String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new java.util.StringTokenizer(in.readLine)\n tokenizer.nextToken\n }\n def nextInt = Integer.parseInt(nextToken)\n def nextLong = java.lang.Long.parseLong(nextToken)\n def nextBig = BigInt(nextToken)\n def nextInts(n: Int) = Array.fill(n) { nextInt }\n def nextLongs(n: Int) = Array.fill(n) { nextLong }\n def nextBigs(n: Int) = Array.fill(n) { nextBig }\n def nextLine = in.readLine\n }\n}\n"}], "negative_code": [{"source_code": "object C1253 {\n\n import IO._\n import collection.{mutable => cu}\n import scala.collection.mutable.ArrayBuffer\n\n def main(args: Array[String]): Unit = {\n var tests = 1 // readInt\n while (tests > 0) {\n val Array(n, m) = readInts(2)\n val a = readInts(n).sorted\n var res = 0L\n val dp = Array.fill(n)(0)\n for (i <- 0 until n) {\n dp(i) = a(i) + (if (i - m >= 0) dp(i - m) else 0)\n }\n// out.println(dp.mkString(\" \"))\n for (idx <- 0 until n) {\n res += dp(idx)\n// var i = idx\n// while (i >= 0 && idx < n) {\n// res += a(i)\n// i -= m\n// }\n out.print(s\"$res \")\n }\n out.println(\"\")\n tests -= 1\n }\n out.close()\n }\n\n object IO {\n private val input = new java.io.BufferedReader(\n new java.io.InputStreamReader(\n if (System.getProperty(\"ONLINE_JUDGE\") != null) System.in\n else new java.io.FileInputStream(\"src/input\")\n )\n )\n val out = new java.io.PrintWriter(System.out)\n\n @inline def read: String = input.readLine()\n\n @inline def tokenizeLine = new java.util.StringTokenizer(read)\n\n def readInt: Int = tokenizeLine.nextToken.toInt\n\n def readInts(n: Int): Array[Int] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toInt)\n }\n\n def readLongs(n: Int): Array[Long] = {\n val tl = tokenizeLine\n Array.fill(n)(tl.nextToken.toLong)\n }\n\n def readBigs(n: Int): Array[BigInt] = {\n val tl = tokenizeLine\n Array.fill(n)(BigInt(tl.nextToken))\n }\n }\n\n}\n"}], "src_uid": "af8ac55aa2594350226653c8d5ff47e4"} {"source_code": "object Olymp{\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readLine split (' ') map (_ toInt)\n val p = (readLine split (' ') map (_ toLong)) sorted\n var l = 0\n var balance: Long = 0\n var cnt = 1\n var num = p(0)\n for(r <- 1 until n){\n balance += (r-l) * (p(r)-p(r-1))\n while(balance > k){\n balance -= (p(r)-p(l))\n l += 1\n }\n if (r-l+1 > cnt){\n cnt = r-l+1\n num = p(r)\n }\n }\n println(cnt+\" \"+num)\n }\n}", "positive_code": [{"source_code": "import java.util.Scanner\n\nobject C extends App {\n val sc = new Scanner(System.in)\n val n: Long = sc.nextLong\n val k: Long = sc.nextLong\n val initial: List[Long] = (for {i <- 1L to n} yield sc.nextLong).sortWith(_ < _).toList\n // TODO: Use foldl instead of foldr.\n val pairs = (initial :\\ List[(Long, Long)]()) {\n case (next, Nil) => (next, 1L) :: Nil\n case (next, (c, n) :: xs) if next == c => (c, n + 1L) :: xs\n case (next, xs) => (next, 1L) :: xs\n }\n //println(\"pairs = \", pairs)\n val answers = ((0L, 0L, -0x40000000L, k, 0L, pairs) /: pairs) {\n case ((record, rec_i, prev, left0, sum0, initial0), (next, count)) =>\n //println(\"loop1: \", record, rec_i, prev, left0, sum0, initial0.head, next, count)\n val left1 = left0 - sum0 * (next - prev)\n val pay_whole = Stream.iterate((initial0, left1, sum0 + count)) {\n\tcase ((c_i, n_i)::inits, left, sum) =>\n\t //println(\"loop2: \", record, rec_i, prev, left0, sum0, initial0.head, next, count, c_i, n_i, left, sum)\n\t val diff = next - c_i\n\t (inits, left + diff * n_i, sum - n_i)\n }\n // (item array, operations left, sum)\n val (next_array, left2, sum2) =\n\tpay_whole.zip(pay_whole.tail).find {\n\t case (_, (xs, left, sum)) => left >= 0L} match {\n\t case Some((((c_i, n_i)::inits, left, sum), _)) =>\n\t //println(\"loop3: \", record, rec_i, prev, left0, sum0, initial0.head, next, count, c_i, n_i, left, sum)\n\t val diff = next - c_i\n\t if (diff == 0 || left >= 0) { // happens on the start of the loop.\n\t ((c_i, n_i)::inits, left, sum)\n\t } else {\n\t val to_erase = (-left + diff - 1) / diff\n\t if (to_erase < n_i) {\n\t\t((c_i, n_i - to_erase)::inits, left + diff * to_erase, sum - to_erase)\n\t } else {\n\t\t(inits, left + diff * n_i, sum - n_i)\n\t }\n\t }\n\t}\n assert (left2 >= 0L, {println(\"assert broken\")})\n val (new_record:Long, new_rec_i:Long) =\n\tif (record < sum2) (sum2, next) else (record, rec_i)\n (new_record, new_rec_i, next, left2, sum2, next_array)\n }\n printf(\"%d %d\\n\", answers._1, answers._2)\n}\n\n"}], "negative_code": [{"source_code": "object Olymp{\n def main(args: Array[String]): Unit = {\n val Array(n, k) = readLine split (' ') map (_ toInt)\n val p = (readLine split (' ') map (_ toInt)) sorted\n var l = 0\n var balance = 0\n var cnt = 1\n var num = p(0)\n for(r <- 1 until n){\n balance += (r-l) * (p(r)-p(r-1))\n while(balance > k){\n balance -= (p(r)-p(l))\n l += 1\n }\n if (r-l+1 > cnt){\n cnt = r-l+1\n num = p(r)\n }\n }\n println(cnt+\" \"+num)\n }\n}"}], "src_uid": "3791d1a504b39eb2e72472bcfd9a7e22"} {"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\n\nobject B\n{\n def main(args: Array[String])\n {\n val MAXI = 200000\n val prePrimeBuffer = ArrayBuffer[Int]()\n val visit=new Array[Boolean](MAXI+1)\n prePrimeBuffer += 2\n for(i<-3 until MAXI by 2 if !visit(i))\n {\n prePrimeBuffer+=i\n var j=2\n while(i*j<=MAXI) {visit(i*j)=true;j+=1}\n }\n \n val prePrime = prePrimeBuffer toArray\n val Array(n,m) = readLine.split(\" \").map(_.toInt)\n val mat = Array.ofDim[Int](n,m)\n \n for(i <- 0 until n)\n {\n mat(i) = readLine.split(\" \").map(_.toInt)\n }\n val matT = mat.transpose\n //print(mat map (_ map (\"%2d\" format _) mkString \" \") mkString \"\\n\")\n \n def nextPrime(target:Int):Int={\n var i=0\n var j=prePrime.size-1\n while(i (nextPrime(x) - x))).sum\n ans.toList\n }\n val aa = slove(mat)\n val bb = slove(matT)\n println(Array(aa.min,bb.min).min)\n }\n}\n", "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val lines = (1 to n).map(_ => in.next().split(' ').map(_.toInt))\n val max = lines.map(_.max).max\n\n def isPrime(a: Int) = a == 2 || (a != 1 && a % 2 != 0 && (3 until a by 2).forall(a % _ != 0))\n\n val nextPrime = Stream.from(max + 1 - max % 2, 2).find(isPrime).get\n val sieve = Array.ofDim[Boolean](nextPrime + 1)\n sieve(0) = true\n sieve(1) = true\n (2 until nextPrime).foreach{ j =>\n if (!sieve(j))\n (j * 2 until nextPrime by j).foreach(i => sieve(i) = true)\n }\n val set = scala.collection.immutable.TreeSet(sieve.indices.filterNot(sieve):_*)\n val smallLine = lines.foldLeft(Int.MaxValue){\n case(acc, line) => Math.min(acc, line.map(i => set.iteratorFrom(i).next() - i).sum)\n }\n val smallColumn = (0 until m).foldLeft(Int.MaxValue) {\n case(acc, i) => Math.min(acc, lines.map(_(i)).map(i => set.iteratorFrom(i).next() - i).sum)\n }\n\n println(Math.min(smallColumn, smallLine))\n}"}, {"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\n\nobject test6 extends App {\n val max=200000\n val ab=ArrayBuffer[Int]()\n val v=new Array[Boolean](max+1)\n ab+=2\n for(i<-3 until max by 2 if !v(i)){\n ab+=i\n var j=2\n while(i*j<=max) {v(i*j)=true;j+=1}\n }\n \n def next(target:Int):Int={\n var i=0\n var j=ab.size-1\n while(inext(i)-i)\n var min=(for(i<-0 until n) yield mat(i).sum).min\n min=math.min(min,(for(j<-0 until m) yield (for(i<-0 until n) yield mat(i)(j)).sum).min)\n println(min)\n} \n\n\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\nimport scala.collection.mutable.ArrayBuffer\nimport java.util.Arrays.binarySearch\n\n\nobject P271B extends App {\n\n object PrimeNumber {\n def apply(n: Int = 1000000): Array[Int] = sieve(n)\n \n def sieve(n: Int): Array[Int] = {\n val primes = new ArrayBuffer[Int]\n val isPrime = Array.fill(n + 1)(true)\n \n @tailrec\n def loop(i: Int): Unit = {\n \n @tailrec\n def innerLoop(j: Int): Unit = {\n if (j > n) ()\n else {\n isPrime(j) = false\n innerLoop(j + i)\n }\n }\n \n if (i > n) ()\n else {\n if (isPrime(i)) {\n primes += i\n innerLoop(i * 2)\n }\n loop(i + 1)\n }\n }\n \n loop(2)\n primes.toArray\n }\n }\n\n\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val Ps: Array[Int] = PrimeNumber(100003)\n\n val nextPrime: Int => Int = { x =>\n val i = binarySearch(Ps, x)\n if (i >= 0) x\n else Ps(-1 - i)\n }\n val numMove: Int => Int = { x => nextPrime(x) - x }\n\n val N, M = sc.nextInt\n val Matrix = List.fill(N, M)(numMove(sc.nextInt))\n val rowsAndCols = Matrix ++ Matrix.transpose\n val res = rowsAndCols.map(_.sum).min\n \n out.println(res)\n out.close\n}\n\n\n\n\n\n"}, {"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\nimport scala.util.control.Breaks._\nimport scala.collection.mutable.ArrayBuffer\nimport java.util.Arrays.binarySearch\n\n\nobject P271B extends App {\n\n object PrimeNumber {\n def apply(n: Int = 1000000): Array[Int] = sieve(n)\n \n def sieve(n: Int): Array[Int] = {\n val primes = new ArrayBuffer[Int]\n val isPrime = Array.fill(n + 1)(true)\n \n @tailrec\n def loop(i: Int): Unit = {\n \n @tailrec\n def innerLoop(j: Int): Unit = {\n if (j > n) ()\n else {\n isPrime(j) = false\n innerLoop(j + i)\n }\n }\n \n if (i > n) ()\n else {\n if (isPrime(i)) {\n primes += i\n innerLoop(i * 2)\n }\n loop(i + 1)\n }\n }\n \n loop(2)\n primes.toArray\n }\n }\n\n\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val Ps: Array[Int] = PrimeNumber(100003)\n\n val nextPrime: Int => Int = { x =>\n val i = binarySearch(Ps, x)\n if (i >= 0) x\n else Ps(-1 - i)\n }\n val numMove: Int => Int = { x => nextPrime(x) - x }\n\n val N, M = sc.nextInt\n val Matrix = Vector.fill(N, M)(numMove(sc.nextInt))\n val rowsAndCols = Matrix ++ Matrix.transpose\n val res = rowsAndCols.map(_.sum).min\n \n out.println(res)\n out.close\n}\n\n\n\n\n\n"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.util.Random\n\nobject P271A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n val Start = sc.nextInt\n\n def solve: Int = {\n @tailrec\n def loop(y: Int): Int =\n if (y.toString.groupBy(identity[Char]).size == 4) y\n else loop(y + 1)\n loop(Start + 1)\n }\n\n out.println(solve)\n out.close\n}\n"}, {"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\n\nobject B\n{\n def main(args: Array[String])\n {\n val SIZE = 102400\n val sieve = Array.fill[Boolean](SIZE+5)(true)\n\n def prime_gen(x: Int): Unit =\n {\n if(sieve(x)) ((2 to SIZE/x) par) map {_ * x} map {sieve( _ ) = false}\n if(x+1 < SIZE) prime_gen(x+1)\n }\n \n def lower_bound(a: List[Int], l:Int, r:Int, v:Int): Int =\n {\n val mid = (l+r)>>1\n if(l>r) l\n else if(a(mid) < v) lower_bound(a, mid+1, r, v)\n else lower_bound(a, l, mid-1, v)\n }\n \n prime_gen(2)\n val prime_list = ((2 to SIZE) toList) filter {sieve(_)}\n val prime_list_len = prime_list.length\n \n val Array(n,m) = readLine.split(\" \").map(_.toInt)\n val mat = Array.ofDim[Int](n,m)\n \n for(i <- 0 until n)\n {\n mat(i) = readLine.split(\" \").map(_.toInt)\n }\n val matT = mat.transpose\n //print(mat map (_ map (\"%2d\" format _) mkString \" \") mkString \"\\n\")\n \n def nextPrime(v: Int): Int =\n {\n prime_list(lower_bound(prime_list,0,prime_list_len-1,v))\n }\n \n def slove(mm: Array[Array[Int]]): List[Int] =\n {\n val sz = mm.size\n val ans = ((1 until sz) par) map\n {\n mm(_) map\n {\n ((x) => (nextPrime(x) - x))\n } sum\n } \n ans.toList\n }\n \n val aa = slove(mat)\n val bb = slove(matT)\n println(Array(aa.min,bb.min).min)\n }\n}\n"}, {"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\n\nobject B\n{\n def main(args: Array[String])\n {\n val SIZE = 102400\n\t\tval sieve = Array.fill[Boolean](SIZE+5)(true)\n\n\t\tdef prime_gen(x: Int): Unit =\n\t\t{\n\t\t\tif(sieve(x)) ((2 to SIZE/x) toList) map {_ * x} map {sieve( _ ) = false}\n\t\t\tif(x+1 < SIZE) prime_gen(x+1)\n\t\t}\n\t\t\n\t\tdef upper_bound(a: List[Int], l:Int, r:Int, v:Int): Int =\n\t\t{\n\t\t\tval mid = (l+r)>>1\n\t\t\tif(l>r) l\n\t\t\telse if(a(mid) <= v) upper_bound(a, mid+1, r, v)\n\t\t\telse upper_bound(a, l, mid-1, v)\n\t\t}\n\t\t\n\t\tprime_gen(2)\n\t\tval prime_list = ((2 to SIZE) toList) filter {sieve(_)}\n\t\tval prime_list_len = prime_list.length\n\t\t\n val Array(n,m) = readLine.split(\" \").map(_.toInt)\n val mat = Array.ofDim[Int](n,m)\n \n for(i <- 0 until n)\n {\n mat(i) = readLine.split(\" \").map(_.toInt)\n }\n val matT = mat.transpose\n //print(mat map (_ map (\"%2d\" format _) mkString \" \") mkString \"\\n\")\n \n\t\tdef nextPrime(v: Int): Int =\n {\n\t\t\tprime_list(upper_bound(prime_list,0,prime_list_len-1,v))\n\t\t}\n \n def slove(mm: Array[Array[Int]]): List[Int] =\n {\n val sz = mm.size\n\t\t\tval ans = for(i <- 0 until sz) \n yield (mm(i).map((x) => (nextPrime(x) - x))).sum\n ans.toList\n }\n \n //println(nextPrime(3))\n \n val aa = slove(mat)\n val bb = slove(matT)\n println(Array(aa.min,bb.min).min)\n }\n}\n"}, {"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\n\nobject test6 extends App {\n val max=100000\n val ab=ArrayBuffer[Int]()\n val v=new Array[Boolean](max+1)\n ab+=2\n for(i<-3 until max by 2 if !v(i)){\n ab+=i\n var j=2\n while(i*j<=max) {v(i*j)=true;j+=1}\n }\n \n def next(target:Int):Int={\n var i=0\n var j=ab.size-1\n while(inext(i)-i)\n var min=(for(i<-0 until n) yield mat(i).sum).min\n min=math.min(min,(for(j<-0 until m) yield (for(i<-0 until n) yield mat(i)(j)).sum).min)\n println(min)\n} \n\n\n"}], "src_uid": "d549f70d028a884f0313743c09c685f1"}